فهرست منبع

M1:模型与配置改由内置 Hermes 提供,首次启动导入旧数据

- hermes_service.py:FastAPI 垫片记录路由,新增 dashboard.call,直接调用 Hermes 原生
  sessions/profiles/config/env/model/providers/files 处理函数,返回与 9119 相同的结构
- src/server/hermes/{api,sessions,embedded}.ts:进程内 HermesApi,按会话归属选择 Profile 或 Bot 的 Hermes home
- UpstreamClient 本地分发,服务账号会话在内置模式下不再登录、不再签发 WebSocket 凭据
- runtime/hermes_import.py + hermes/import.ts:首次启动只读导入 ~/.hermes(SQLite 在线备份,暂存目录原子替换)
- worker.py:按请求设置会话来源,工具进度带调用编号,应用工具结果按文本或多模态信封透传

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HvtCVd6vwAvwixrtCT1h76
Claude 1 روز پیش
والد
کامیت
6ee6d74f4a

+ 172 - 0
runtime/hermes_dashboard.py

@@ -0,0 +1,172 @@
+"""In-process dispatch to Hermes' own dashboard REST handlers (Yaoyao embedded mode).
+
+Yaoyao used to call a separately running Hermes dashboard over HTTP. The embedded runtime has
+no ASGI server: hermes_service.py shims FastAPI so the router modules import as plain functions
+and records each decorated route. ``call`` matches a method + path against those routes and
+invokes the native handler with path, query and body arguments, so responses keep the exact
+shapes the dashboard returned. One service process serves one Hermes home, so the ``profile``
+query parameter is resolved by the caller choosing the process, never by the handler.
+"""
+import asyncio
+import inspect
+import re
+import types
+import typing
+from typing import Any
+
+ROUTER_MODULES = (
+    "hermes_cli.web_routers.sessions",
+    "hermes_cli.web_routers.profiles",
+    "hermes_cli.web_routers.config_env",
+    "hermes_cli.web_routers.models",
+    "hermes_cli.web_routers.files",
+)
+_loaded = False
+_compiled: list[tuple[str, re.Pattern, list[str], Any]] = []
+
+
+def _load(routes):
+    global _loaded
+    if _loaded:
+        return
+    import importlib
+    import os
+    from pathlib import Path
+    home = Path(os.environ["HERMES_HOME"])
+    if not (home / "state.db").exists():
+        # The dashboard expects its gateway to have created the store; the embedded home creates it here.
+        from hermes_state import SessionDB
+        SessionDB(db_path=home / "state.db").close()
+    for name in ROUTER_MODULES:
+        importlib.import_module(name)
+    for method, template, fn in routes:
+        names = re.findall(r"{([A-Za-z_][A-Za-z0-9_]*)(?::path)?}", template)
+        pattern = re.escape(template)
+        for param in names:
+            pattern = pattern.replace(re.escape("{" + param + ":path}"), "(?P<%s>.+)" % param)
+            pattern = pattern.replace(re.escape("{" + param + "}"), "(?P<%s>[^/]+)" % param)
+        # Static routes (``/api/sessions/search``) win over templates (``/api/sessions/{id}``).
+        _compiled.append((method, re.compile("^" + pattern + "$"), names, fn))
+    _compiled.sort(key=lambda item: len(item[2]))
+    _loaded = True
+
+
+class _Request:
+    def __init__(self, query, body):
+        self.headers = {}
+        self.cookies = {}
+        self.query_params = query
+        self.client = types.SimpleNamespace(host="127.0.0.1", port=0)
+        self.url = types.SimpleNamespace(path="", query="")
+        self.state = types.SimpleNamespace()
+        self._body = body
+
+    async def json(self):
+        return self._body
+
+
+def _base_types(annotation):
+    if annotation is inspect.Parameter.empty:
+        return ()
+    origin = typing.get_origin(annotation)
+    if origin in (typing.Union, types.UnionType):
+        return tuple(a for a in typing.get_args(annotation) if a is not type(None))
+    return (annotation,)
+
+
+def _convert(value, annotation):
+    for kind in _base_types(annotation):
+        if kind is bool:
+            return str(value).lower() in ("1", "true", "yes", "on")
+        if kind is int:
+            return int(value)
+        if kind is float:
+            return float(value)
+        if kind is str:
+            return str(value)
+    return value
+
+
+def _model_type(annotation):
+    for kind in _base_types(annotation):
+        if inspect.isclass(kind) and hasattr(kind, "model_validate"):
+            return kind
+    return None
+
+
+def _arguments(fn, path_args, query, body):
+    kwargs = {}
+    for name, param in inspect.signature(fn).parameters.items():
+        annotation = param.annotation
+        if name in path_args:
+            kwargs[name] = _convert(path_args[name], annotation)
+        elif name == "request" or getattr(annotation, "__name__", "") == "Request":
+            kwargs[name] = _Request(query, body)
+        elif _model_type(annotation) is not None:
+            kwargs[name] = _model_type(annotation).model_validate(body or {})
+        elif name in query:
+            kwargs[name] = _convert(query[name], annotation)
+        elif name in ("body", "payload", "data") and body is not None:
+            kwargs[name] = body
+        elif param.default is not inspect.Parameter.empty:
+            kwargs[name] = param.default
+    return kwargs
+
+
+def _response(result):
+    if hasattr(result, "status_code") and hasattr(result, "body") and not hasattr(result, "kwargs"):
+        # Real starlette responses (JSONResponse, Response, PlainTextResponse).
+        raw = bytes(result.body or b"")
+        media = getattr(result, "media_type", None) or ""
+        if "json" in media:
+            import json
+            return {"status": int(result.status_code), "json": json.loads(raw or b"null")}
+        return {"status": int(result.status_code), "text": raw.decode("utf-8", "replace"), "media_type": media}
+    if hasattr(result, "path") and type(result).__name__ == "FileResponse" and not hasattr(result, "kwargs"):
+        return {"status": int(getattr(result, "status_code", 200)), "file": str(result.path),
+                "filename": getattr(result, "filename", None), "media_type": getattr(result, "media_type", None), "headers": {}}
+    args = getattr(result, "args", None)
+    options = getattr(result, "kwargs", None)
+    if args is None or options is None:
+        return {"status": 200, "json": result}
+    kind = type(result).__name__
+    if kind == "FileResponse":
+        path = options.get("path", args[0] if args else None)
+        return {"status": 200, "file": str(path), "filename": options.get("filename"),
+                "media_type": options.get("media_type"), "headers": options.get("headers") or {}}
+    status = int(options.get("status_code") or 200)
+    if kind == "JSONResponse":
+        return {"status": status, "json": options.get("content", args[0] if args else None)}
+    content = options.get("content", args[0] if args else b"")
+    if isinstance(content, bytes):
+        content = content.decode("utf-8", "replace")
+    return {"status": status, "text": content, "media_type": options.get("media_type")}
+
+
+def call(routes, error_type, args):
+    _load(routes)
+    method = str(args.get("method") or "GET").upper()
+    path = str(args.get("path") or "")
+    query = {k: v for k, v in (args.get("query") or {}).items() if k != "profile"}
+    body = args.get("body")
+    allowed = False
+    for route_method, pattern, _names, fn in _compiled:
+        match = pattern.match(path)
+        if not match:
+            continue
+        allowed = True
+        if route_method != method:
+            continue
+        try:
+            result = fn(**_arguments(fn, match.groupdict(), query, body))
+            if inspect.isawaitable(result):
+                result = asyncio.run(result) if inspect.iscoroutine(result) else asyncio.run(_await(result))
+            return _response(result)
+        except error_type as exc:
+            detail = getattr(exc, "detail", "") or str(exc)
+            return {"status": int(getattr(exc, "status_code", 500) or 500), "json": {"detail": detail}}
+    return {"status": 405 if allowed else 404, "json": {"detail": "Not Found" if not allowed else "Method Not Allowed"}}
+
+
+async def _await(value):
+    return await value

+ 97 - 0
runtime/hermes_import.py

@@ -0,0 +1,97 @@
+"""One-time, read-only import of an existing Hermes home into Yaoyao's embedded home.
+
+Usage: python hermes_import.py SOURCE STAGING
+
+SOURCE is never modified. SQLite databases are copied with the online backup API, so a
+Hermes process that is still running is read as a consistent snapshot. Re-downloadable
+runtimes, caches, logs, process files and Hermes' own installation are skipped. The
+yaoyao-bot-bridge plugin is skipped: the embedded kernel has no plugin bridge.
+Prints a JSON manifest on stdout.
+"""
+import hashlib
+import json
+import os
+import shutil
+import sqlite3
+import sys
+import time
+from pathlib import Path
+
+SKIP_DIRS = {"hermes-agent", "venv", ".venv", "node_modules", "models", "runtimes", "node", "logs",
+             "cache", "__pycache__", ".git", "sandboxes", "tmp", "pm"}
+SKIP_PLUGINS = {"yaoyao-bot-bridge"}
+SKIP_SUFFIXES = (".pid", ".lock", ".sock", "-wal", "-shm", "-journal")
+MAX_FILE = 512 * 1024 * 1024
+
+
+def is_sqlite(path: Path) -> bool:
+    try:
+        with path.open("rb") as handle:
+            return handle.read(16) == b"SQLite format 3\x00"
+    except OSError:
+        return False
+
+
+def backup(source: Path, target: Path) -> None:
+    src = sqlite3.connect(f"file:{source}?mode=ro", uri=True, timeout=30)
+    try:
+        dst = sqlite3.connect(target)
+        try:
+            src.backup(dst)
+        finally:
+            dst.close()
+    finally:
+        src.close()
+
+
+def digest(path: Path) -> str:
+    h = hashlib.sha256()
+    with path.open("rb") as handle:
+        for chunk in iter(lambda: handle.read(1024 * 1024), b""):
+            h.update(chunk)
+    return h.hexdigest()
+
+
+def main(source: Path, staging: Path) -> dict:
+    source = source.expanduser().resolve(strict=True)
+    staging.mkdir(parents=True, exist_ok=False, mode=0o700)
+    files, skipped = [], 0
+    for root, dirs, names in os.walk(source, followlinks=False):
+        current = Path(root)
+        relative = current.relative_to(source)
+        dirs[:] = [d for d in dirs if d not in SKIP_DIRS
+                   and not (relative.name == "plugins" and d in SKIP_PLUGINS)
+                   and not (current / d).is_symlink()]
+        (staging / relative).mkdir(parents=True, exist_ok=True, mode=0o700)
+        for name in names:
+            path = current / name
+            if name.endswith(SKIP_SUFFIXES) or path.is_symlink() or not path.is_file():
+                skipped += 1
+                continue
+            if path.stat().st_size > MAX_FILE:
+                skipped += 1
+                continue
+            target = staging / relative / name
+            if is_sqlite(path):
+                backup(path, target)
+            else:
+                shutil.copy2(path, target)
+            os.chmod(target, 0o600)
+            files.append({"path": str(relative / name), "sha256": digest(target)})
+    version = None
+    stamp = source / "hermes-agent" / "pyproject.toml"
+    if stamp.exists():
+        for line in stamp.read_text(errors="replace").splitlines():
+            if line.strip().startswith("version"):
+                version = line.split("=", 1)[1].strip().strip('"')
+                break
+    manifest = {"version": 1, "source": str(source), "importedAt": int(time.time() * 1000),
+                "hermesVersion": version, "files": files, "skipped": skipped}
+    (staging / ".import.json").write_text(json.dumps(manifest, ensure_ascii=False))
+    os.chmod(staging / ".import.json", 0o600)
+    return manifest
+
+
+if __name__ == "__main__":
+    result = main(Path(sys.argv[1]), Path(sys.argv[2]))
+    print(json.dumps({"files": len(result["files"]), "skipped": result["skipped"], "hermesVersion": result["hermesVersion"]}))

+ 47 - 3
runtime/hermes_service.py

@@ -29,6 +29,8 @@ sys.stdout = sys.stderr  # Hermes helpers print; keep the wire clean.
 _wire_lock = threading.Lock()
 
 # Native sections compiled into Bot runs; client reads are always redacted.
+DASHBOARD_ROUTES = []  # (method, path template, handler) recorded by the FastAPI shim
+
 CONFIG_KEYS = ("model", "providers", "custom_providers", "fallback_model", "auxiliary", "credential_pool_strategies", "image_gen", "video_gen", "web")
 
 
@@ -44,12 +46,24 @@ def _install_fastapi_shim():
     if "fastapi" in sys.modules:
         return
     fa = types.ModuleType("fastapi")
+    fa.__path__ = []  # a package, so ``fastapi.responses`` style imports resolve to the stubs below
 
     class APIRouter:
+        """Records routes so ``dashboard.call`` can dispatch to the native handler functions."""
         def __init__(self, *a, **k):
             pass
 
-        def __getattr__(self, _name):
+        def _route(self, method):
+            def register(path, *a, **k):
+                def decorate(fn):
+                    DASHBOARD_ROUTES.append((method, path, fn))
+                    return fn
+                return decorate
+            return register
+
+        def __getattr__(self, name):
+            if name in ("get", "post", "put", "patch", "delete"):
+                return self._route(name.upper())
             return lambda *a, **k: (lambda fn: fn)
 
     class Request:
@@ -61,13 +75,37 @@ def _install_fastapi_shim():
     fa.HTTPException = ServiceError
     fa.APIRouter = APIRouter
     fa.Request = Request
-    for name in ("Depends", "Query", "Body", "Header", "WebSocket", "WebSocketDisconnect", "UploadFile", "File", "Form", "Path"):
+    def _default(default=None, *a, **k):
+        # Query(20, ge=0) keeps its default so handlers called directly see native defaults.
+        return None if default is Ellipsis else default
+
+    for name in ("Depends", "WebSocket", "WebSocketDisconnect", "UploadFile"):
         setattr(fa, name, _noop)
+    for name in ("Query", "Body", "Header", "File", "Form", "Path"):
+        setattr(fa, name, _default)
     sys.modules["fastapi"] = fa
     responses = types.ModuleType("fastapi.responses")
+    def _capture(self, *a, **k):
+        self.args, self.kwargs = a, k
+
     for name in ("JSONResponse", "FileResponse", "HTMLResponse", "Response", "StreamingResponse", "PlainTextResponse", "RedirectResponse"):
-        setattr(responses, name, type(name, (), {"__init__": lambda self, *a, **k: None}))
+        setattr(responses, name, type(name, (), {"__init__": _capture}))
     sys.modules["fastapi.responses"] = responses
+    fa.responses = responses
+    encoders = types.ModuleType("fastapi.encoders")
+
+    def jsonable_encoder(value, *a, **k):
+        if hasattr(value, "model_dump"):
+            return value.model_dump(mode="json")
+        if isinstance(value, dict):
+            return {str(key): jsonable_encoder(item) for key, item in value.items()}
+        if isinstance(value, (list, tuple, set)):
+            return [jsonable_encoder(item) for item in value]
+        return value
+
+    encoders.jsonable_encoder = jsonable_encoder
+    sys.modules["fastapi.encoders"] = encoders
+    fa.encoders = encoders
     concurrency = types.ModuleType("fastapi.concurrency")
 
     async def run_in_threadpool(fn, *a, **k):
@@ -176,6 +214,12 @@ def _model(cls_name, args):
     return getattr(web_models, cls_name)(**args)
 
 
+def op_dashboard_call(args):
+    """Native dashboard REST handler for this home (sessions, profiles, config, models, files)."""
+    import hermes_dashboard
+    return hermes_dashboard.call(DASHBOARD_ROUTES, ServiceError, args)
+
+
 # ── ops ────────────────────────────────────────────────────────────────────────────────────────
 
 def op_ping(args):

+ 13 - 2
runtime/worker.py

@@ -24,6 +24,8 @@ steer_ready = False
 startup_steers = []
 # Prefix of the per-turn application state Yaovi renders (src/server/workspacePrompt.ts).
 TURN_CONTEXT_SENTINEL = "[[YAOVI_TURN_CONTEXT_V1]]"
+# Control-plane RPCs whose replies are JSON values, never model-facing tool output.
+CONTROL_TOOLS = ("yaovi_clarify", "yaovi_native_authorize", "yaovi_native_check")
 
 
 def emit(kind, **payload):
@@ -46,8 +48,15 @@ def dispatch(name, args, **metadata):
         value = reply.get() if persistent_waits else reply.get(timeout=600)
         if "error" in value:
             return json.dumps({"error": value["error"], "isError": True})
+        result = value.get("result")
+        if name not in CONTROL_TOOLS:
+            # Yaoyao normalizes application tool results (text, or Hermes' native multimodal envelope).
+            if isinstance(result, dict) and result.get("_multimodal") is True:
+                return result
+            if isinstance(result, str):
+                return result
         from workspace_media import computer_result
-        return computer_result(name, value.get("result"))
+        return computer_result(name, result)
     finally:
         with lock:
             pending.pop(call_id, None)
@@ -303,7 +312,7 @@ def main():
         base_url=runtime.get("base_url"), api_key=runtime.get("api_key"),
         api_mode=runtime.get("api_mode"), credential_pool=runtime.get("credential_pool"),
         fallback_model=config.get("fallback_model") or None,
-        session_id=session, session_db=db, platform="yaovi",
+        session_id=session, session_db=db, platform=str(request.get("platform") or "yaovi"),
         **({'cwd': host_cwd} if host_cwd else {}),
         max_iterations=config["agent"]["max_iterations"],
         reasoning_config=(None if route.get("reasoningEffort") in (None, "default")
@@ -318,6 +327,8 @@ def main():
         tool_progress_callback=lambda kind, name=None, preview=None, args=None, **kw: emit("kernel.event", name=kind, value={"tool":name,"preview":preview,"args":args,**kw}),
         clarify_callback=clarify,
     )
+    # Tag tool progress with the model's call id so the host can pair started/completed events.
+    agent._yaovi_embedded = True
     if request.get('reportOnlyReview') is True:
         # The Host admitted only the structured decision and session attachment
         # reader. Native skill,

+ 10 - 0
src/server/app.ts

@@ -40,6 +40,7 @@ import {
   isExactOrigin,
 } from './security.js'
 import { UpstreamHttpError, UpstreamClient } from './upstream.js'
+import { createEmbeddedHermes, type EmbeddedHermes } from './hermes/embedded.js'
 import { UploadStore } from './uploads.js'
 import { WorkspaceStore } from './workspaceStore.js'
 import { WorkspaceNodes } from './workspaceGateway.js'
@@ -91,6 +92,7 @@ export interface ApplicationOptions {
   auth?: LocalAuthStore
   pluginFetch?: typeof fetch
   upstreamSession?: UpstreamServiceSession
+  hermes?: EmbeddedHermes
   accountPairings?: AccountLoginPairingStore
   profileIdentities?: UpstreamProfileIdentityService
   push?: PushCoordinator
@@ -117,6 +119,7 @@ export interface ApplicationRuntime {
   updates: SystemUpdateManager
   auth: LocalAuthStore
   upstreamSession: UpstreamServiceSession
+  hermes: EmbeddedHermes
   accountPairings: AccountLoginPairingStore
   profileIdentities: UpstreamProfileIdentityService
   push: PushCoordinator
@@ -175,6 +178,10 @@ export function createApplication(options: ApplicationOptions = {}): Application
   const csrf = new CsrfProtection(persistentCsrfSecret(config.home, options.csrfSecret), Boolean(config.tlsCert))
   const pairings = options.pairings ?? new NodePairingStore(config.home)
   const upstream = new UpstreamClient(config.upstream, options.fetchImpl, Boolean(config.tlsCert))
+  // Embedded Hermes: the kernel runs as child processes under <data>/hermes; nothing listens on 9119.
+  const hermes = options.hermes ?? createEmbeddedHermes(config.home)
+  // `fetchImpl` is a test-only fake Dashboard transport; production always answers in process.
+  if (!options.upstreamSession && !options.fetchImpl) upstream.local = hermes.api
   const uploads = options.uploads ?? new UploadStore(config.home)
   const updates = options.updates ?? new SystemUpdateManager(config)
   const auth = options.auth ?? new LocalAuthStore(config.home, Boolean(config.tlsCert))
@@ -549,6 +556,7 @@ export function createApplication(options: ApplicationOptions = {}): Application
     updates,
     auth,
     upstreamSession,
+    hermes,
     accountPairings,
     profileIdentities,
     push,
@@ -595,6 +603,7 @@ export function createApplication(options: ApplicationOptions = {}): Application
     updates,
     auth,
     upstreamSession,
+    hermes,
     accountPairings,
     profileIdentities,
     push,
@@ -625,6 +634,7 @@ export function createApplication(options: ApplicationOptions = {}): Application
       workspaceRuntime.close()
       workspaceNodes.close()
       upstream.close()
+      if (!options.hermes) hermes.close()
       realtime.close()
       chatPushJobs.stop()
       push.close()

+ 78 - 0
src/server/hermes/api.ts

@@ -0,0 +1,78 @@
+import { readFile, stat } from 'node:fs/promises'
+import { basename } from 'node:path'
+import { HttpError } from '../errors.js'
+import type { HermesServicePool, HermesScope } from './service.js'
+import type { EmbeddedSessions } from './sessions.js'
+
+export interface LocalResponse { status: number; headers: Headers; body: Buffer }
+export interface LocalRequest { method: string; path: string; search?: URLSearchParams; body?: unknown; maxResponseBytes?: number }
+
+/** Dashboard REST families served by Hermes' own handlers through `hermes_service.py dashboard.call`. */
+const NATIVE = /^\/api\/(?:sessions(?:\/.*)?|profiles(?:\/.*)?|config(?:\/.*)?|env(?:\/.*)?|model\/.+|providers\/.+|files(?:\/.*)?|fs\/.+)$/
+const SESSION_PATH = /^\/api\/sessions\/([A-Za-z0-9_-]{1,128})(?:\/|$)/
+
+function json(status: number, value: unknown, headers: Record<string, string> = {}): LocalResponse {
+  return { status, headers: new Headers({ 'content-type': 'application/json', ...headers }), body: Buffer.from(JSON.stringify(value)) }
+}
+
+/**
+ * Answers the Hermes dashboard paths Yaoyao used to call over HTTP (9119), in process.
+ * There is no upstream account: Yaoyao's own Web login authorizes the caller before this point.
+ */
+export class HermesApi {
+  /** Optional hooks for paths owned by other embedded components. */
+  memoryExtract?: (profile: string, prompt: string) => Promise<unknown>
+
+  constructor(readonly pool: HermesServicePool, readonly sessions: EmbeddedSessions, readonly version = '0.23.0') {}
+
+  async handle(request: LocalRequest): Promise<LocalResponse> {
+    const method = request.method.toUpperCase()
+    const path = request.path
+    const search = request.search ?? new URLSearchParams()
+    if (path === '/api/status') return json(200, { auth_required: false, embedded: true, version: this.version, gateway_running: true })
+    if (path === '/api/auth/me') return json(200, { authenticated: true, user: { id: 'yaoyao', name: 'yaoyao' }, provider: 'embedded' })
+    if (path === '/api/auth/providers') return json(200, { providers: [] })
+    if (path.startsWith('/api/auth/') || path.startsWith('/auth/'))
+      return json(410, { error: '内置 Hermes 不使用独立账号,请使用夭夭账号登录。', code: 'embedded_hermes' })
+    if (path === '/api/plugins/yaoyao-bot-bridge/capabilities')
+      return json(200, { version: 1, ready: true, in_process: true, native_tools: true, embedded: true })
+    if (path === '/api/plugins/yaoyao-bot-bridge/memory-extract' && method === 'POST') {
+      if (!this.memoryExtract) return json(503, { ok: false, error: '记忆抽取不可用' })
+      const body = (request.body ?? {}) as { profile?: unknown; prompt?: unknown }
+      const result = await this.memoryExtract(typeof body.profile === 'string' ? body.profile : 'default', String(body.prompt ?? ''))
+      return json(200, { ok: true, ...(result && typeof result === 'object' ? result : { text: result }) })
+    }
+    if (!NATIVE.test(path)) return json(404, { detail: 'Not Found' })
+    return this.native(method, path, search, request.body, request.maxResponseBytes)
+  }
+
+  /** Hermes home that serves a dashboard path: the owning Bot home for its sessions, else the profile. */
+  scopeFor(path: string, search: URLSearchParams): HermesScope {
+    const profile = search.get('profile')?.trim() || 'default'
+    if (path === '/api/profiles' || path.startsWith('/api/profiles/')) return 'system'
+    const session = SESSION_PATH.exec(path)?.[1]
+    return this.sessions.scope(session, profile)
+  }
+
+  private async native(method: string, path: string, search: URLSearchParams, body: unknown, maxBytes = 64 * 1024 * 1024): Promise<LocalResponse> {
+    const scope = this.scopeFor(path, search)
+    const query = Object.fromEntries(search.entries())
+    const result = await this.pool.call<{ status: number; json?: unknown; text?: string; media_type?: string; file?: string; filename?: string; headers?: Record<string, string> }>(
+      scope, 'dashboard.call', { method, path, query, ...(body === undefined ? {} : { body }) }, { timeoutMs: 120_000 })
+    const deleted = method === 'DELETE' ? SESSION_PATH.exec(path)?.[1] : undefined
+    if (deleted && result.status >= 200 && result.status < 300) this.sessions.delete(deleted)
+    if (result.file) {
+      const info = await stat(result.file).catch(() => undefined)
+      if (!info?.isFile()) return json(404, { detail: 'File not found' })
+      if (info.size > maxBytes) throw new HttpError(502, 'Hermes 文件超过本次读取上限', 'upstream_too_large')
+      const name = result.filename || basename(result.file)
+      return { status: result.status, body: await readFile(result.file), headers: new Headers({
+        'content-type': result.media_type || 'application/octet-stream',
+        'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(name)}`,
+        'content-length': String(info.size), ...(result.headers ?? {}),
+      }) }
+    }
+    if (result.text !== undefined) return { status: result.status, headers: new Headers({ 'content-type': result.media_type || 'text/plain; charset=utf-8' }), body: Buffer.from(result.text) }
+    return json(result.status, result.json ?? null)
+  }
+}

+ 20 - 0
src/server/hermes/embedded.ts

@@ -0,0 +1,20 @@
+import { join } from 'node:path'
+import { HermesApi } from './api.js'
+import { HermesServicePool, type HermesServiceOptions } from './service.js'
+import { EmbeddedSessions } from './sessions.js'
+
+/** The embedded Hermes runtime owned by one Yaoyao server: service processes, sessions and the in-process API. */
+export interface EmbeddedHermes {
+  readonly home: string
+  readonly pool: HermesServicePool
+  readonly sessions: EmbeddedSessions
+  readonly api: HermesApi
+  close(): void
+}
+
+export function createEmbeddedHermes(dataHome: string, options: HermesServiceOptions = {}): EmbeddedHermes {
+  const pool = new HermesServicePool(dataHome, options)
+  const sessions = new EmbeddedSessions(join(dataHome, 'hermes'))
+  const api = new HermesApi(pool, sessions)
+  return { home: pool.systemHome, pool, sessions, api, close: () => pool.close() }
+}

+ 60 - 0
src/server/hermes/import.ts

@@ -0,0 +1,60 @@
+import { spawnSync } from 'node:child_process'
+import { existsSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { dirname, join, resolve } from 'node:path'
+import { kernelPaths } from './paths.js'
+
+export type HermesImportResult =
+  | { status: 'imported'; source: string; files: number; skipped: number; hermesVersion?: string | null }
+  | { status: 'skipped'; reason: 'already_initialized' | 'no_source' | 'kernel_unavailable' | 'disabled' }
+  | { status: 'failed'; source: string; error: string }
+
+const MARKERS = ['config.yaml', 'state.db', 'auth.json', '.env', 'profiles']
+
+/** The embedded home counts as empty until Hermes data or a previous import exists there. */
+function initialized(home: string): boolean {
+  if (!existsSync(home)) return false
+  return readdirSync(home).some(name => name !== 'yaoyao-sessions.json' && name !== 'import-error.json')
+}
+
+function legacySource(env: NodeJS.ProcessEnv): string | undefined {
+  const configured = env.YAOYAO_IMPORT_HERMES_HOME?.trim()
+  const candidate = resolve(configured || join(homedir(), '.hermes'))
+  if (!existsSync(candidate) || !statSync(candidate).isDirectory()) return undefined
+  return MARKERS.some(name => existsSync(join(candidate, name))) ? candidate : undefined
+}
+
+/**
+ * First start only: copy an existing Hermes home into `<data>/hermes`. The source stays read-only.
+ * Runs in a staging directory renamed into place on success, so a failure leaves no partial home and
+ * the next start retries. A previously imported or used embedded home is never touched.
+ */
+export function importLegacyHermes(dataHome: string, env: NodeJS.ProcessEnv = process.env): HermesImportResult {
+  const home = join(dataHome, 'hermes')
+  if (env.YAOYAO_IMPORT_HERMES === '0') return { status: 'skipped', reason: 'disabled' }
+  if (initialized(home)) return { status: 'skipped', reason: 'already_initialized' }
+  const source = legacySource(env)
+  if (!source) return { status: 'skipped', reason: 'no_source' }
+  if (resolve(source) === resolve(home)) return { status: 'skipped', reason: 'already_initialized' }
+  const paths = kernelPaths(env)
+  const script = join(paths.root, 'runtime/hermes_import.py')
+  if (!existsSync(paths.python) || !existsSync(script)) return { status: 'skipped', reason: 'kernel_unavailable' }
+  const staging = join(dirname(home), `.hermes-import-${process.pid}-${Date.now()}`)
+  const result = spawnSync(paths.python, ['-I', script, source, staging], { encoding: 'utf8', timeout: 30 * 60_000, env: { PATH: env.PATH, LANG: 'en_US.UTF-8' } })
+  if (result.status !== 0) {
+    rmSync(staging, { recursive: true, force: true })
+    const error = (result.stderr || result.error?.message || `exit ${result.status}`).trim().split('\n').at(-1)?.slice(0, 500) ?? '导入失败'
+    try { writeFileSync(join(dataHome, 'hermes-import-error.json'), JSON.stringify({ source, error, at: Date.now() }), { mode: 0o600 }) } catch { /* diagnostics only */ }
+    return { status: 'failed', source, error }
+  }
+  // An empty pre-created home (only the session registry) is replaced by the imported copy.
+  if (existsSync(home)) {
+    const registry = join(home, 'yaoyao-sessions.json')
+    if (existsSync(registry)) renameSync(registry, join(staging, 'yaoyao-sessions.json'))
+    rmSync(home, { recursive: true, force: true })
+  }
+  renameSync(staging, home)
+  rmSync(join(dataHome, 'hermes-import-error.json'), { force: true })
+  const summary = JSON.parse(result.stdout.trim().split('\n').at(-1) || '{}') as { files?: number; skipped?: number; hermesVersion?: string | null }
+  return { status: 'imported', source, files: summary.files ?? 0, skipped: summary.skipped ?? 0, hermesVersion: summary.hermesVersion }
+}

+ 19 - 5
src/server/hermes/service.ts

@@ -12,7 +12,9 @@ import { kernelEnv, kernelPaths, requireKernel } from './paths.js'
  * The system home is `<data>/hermes`; a Bot home is `<data>/bots/<agentId>/runtime` and reads the
  * system home as its Hermes profile parent (config, .env and auth.json read-through).
  */
-export type HermesScope = 'system' | { botId: string }
+/** `system` is the default profile; named profiles live in `<system>/profiles/<name>` (native layout). */
+export type HermesScope = 'system' | { profile: string } | { botId: string; profile?: string }
+const PROFILE = /^[a-z0-9][a-z0-9_-]{0,63}$/
 export interface HermesServiceOptions { env?: NodeJS.ProcessEnv; idleMs?: number }
 type Pending = { resolve: (v: any) => void; reject: (e: Error) => void; timer: ReturnType<typeof setTimeout> }
 type Proc = { child: ChildProcessWithoutNullStreams; ready: Promise<void>; pending: Map<string, Pending>; idle?: ReturnType<typeof setTimeout>; holds: number }
@@ -31,13 +33,25 @@ export class HermesServicePool {
     if (!/^[A-Za-z0-9_-]{1,128}$/.test(botId)) throw new HttpError(400, 'Bot 标识无效', 'invalid_bot')
     return join(this.dataHome, 'bots', botId, 'runtime')
   }
-  home(scope: HermesScope) { return scope === 'system' ? this.systemHome : this.botHome(scope.botId) }
+  profileHome(profile = 'default') {
+    if (profile === 'default') return this.systemHome
+    if (!PROFILE.test(profile)) throw new HttpError(400, 'Profile 名称无效', 'invalid_profile')
+    return join(this.systemHome, 'profiles', profile)
+  }
+  home(scope: HermesScope) {
+    if (scope === 'system') return this.systemHome
+    return 'botId' in scope ? this.botHome(scope.botId) : this.profileHome(scope.profile)
+  }
+  /** Profile parent read through for config, .env and auth.json; profiles use Hermes' native layout. */
+  parent(scope: HermesScope): string | undefined {
+    return scope !== 'system' && 'botId' in scope ? this.profileHome(scope.profile) : undefined
+  }
 
   /** Call one service op. `hold` keeps the process alive (pending OAuth sessions live in its memory). */
   async call<T = any>(scope: HermesScope, op: string, args: Record<string, unknown> = {}, opts: HermesCallOptions = {}): Promise<T> {
     opts.signal?.throwIfAborted()
     const home = this.home(scope)
-    const proc = this.start(home)
+    const proc = this.start(home, this.parent(scope))
     await proc.ready
     if (proc.idle) clearTimeout(proc.idle)
     if (opts.hold) proc.holds++
@@ -80,13 +94,13 @@ export class HermesServicePool {
     proc.idle.unref?.()
   }
 
-  private start(home: string): Proc {
+  private start(home: string, parent?: string): Proc {
     const existing = this.procs.get(home)
     if (existing && existing.child.exitCode === null && !existing.child.killed) return existing
     const paths = kernelPaths(this.env)
     requireKernel(paths, paths.service)
     mkdirSync(home, { recursive: true, mode: 0o700 })
-    const env = kernelEnv(home, this.env, this.systemHome)
+    const env = kernelEnv(home, this.env, parent)
     const child = spawn(paths.python, ['-u', paths.service], { cwd: dirname(paths.service), env, stdio: ['pipe', 'pipe', 'pipe'] })
     const pending = new Map<string, Pending>()
     let ready!: () => void, failed!: (e: Error) => void

+ 79 - 0
src/server/hermes/sessions.ts

@@ -0,0 +1,79 @@
+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
+import { dirname, join } from 'node:path'
+import { HttpError } from '../errors.js'
+import type { HermesScope } from './service.js'
+
+/** Per-session model selection made through `config.set` (native chat model picker, Bot settings). */
+export interface SessionModel { provider?: string; model?: string; reasoningEffort?: string; fastMode?: 'normal' | 'fast' }
+
+/**
+ * One embedded conversation. Hermes owns the transcript in the home's `state.db`; this record holds
+ * what the dashboard gateway used to keep in memory: which home serves the session and its
+ * per-session settings.
+ */
+export interface EmbeddedSession {
+  id: string
+  profile: string
+  /** Workspace Bot whose runtime home stores this session; absent for native chats. */
+  botId?: string
+  title?: string
+  source?: string
+  hidden?: boolean
+  cwd?: string
+  model?: SessionModel
+  createdAt: number
+  updatedAt: number
+}
+
+const SESSION_ID = /^[A-Za-z0-9_-]{1,128}$/
+
+export class EmbeddedSessions {
+  private readonly path: string
+  private readonly sessions = new Map<string, EmbeddedSession>()
+
+  constructor(hermesHome: string) {
+    this.path = join(hermesHome, 'yaoyao-sessions.json')
+    if (existsSync(this.path)) {
+      const parsed = JSON.parse(readFileSync(this.path, 'utf8')) as { sessions?: EmbeddedSession[] }
+      for (const session of parsed.sessions ?? []) if (SESSION_ID.test(session.id)) this.sessions.set(session.id, session)
+    }
+  }
+
+  get(id: string): EmbeddedSession | undefined { return SESSION_ID.test(id) ? this.sessions.get(id) : undefined }
+
+  require(id: string): EmbeddedSession {
+    const session = this.get(id)
+    if (!session) throw new HttpError(404, '会话不存在', 'session_not_found')
+    return session
+  }
+
+  list(): EmbeddedSession[] { return [...this.sessions.values()] }
+
+  put(session: EmbeddedSession): EmbeddedSession {
+    if (!SESSION_ID.test(session.id)) throw new HttpError(400, '会话标识无效', 'invalid_session')
+    this.sessions.set(session.id, { ...session, updatedAt: Date.now() })
+    this.save()
+    return this.sessions.get(session.id)!
+  }
+
+  update(id: string, patch: Partial<Omit<EmbeddedSession, 'id' | 'createdAt'>>): EmbeddedSession {
+    return this.put({ ...this.require(id), ...patch })
+  }
+
+  delete(id: string): void { if (this.sessions.delete(id)) this.save() }
+
+  /** Hermes home serving a session id; unknown ids belong to the profile they are addressed under. */
+  scope(id: string | undefined, profile = 'default'): HermesScope {
+    const session = id ? this.get(id) : undefined
+    if (session?.botId) return { botId: session.botId, profile: session.profile }
+    const name = session?.profile ?? profile
+    return name === 'default' ? 'system' : { profile: name }
+  }
+
+  private save(): void {
+    mkdirSync(dirname(this.path), { recursive: true, mode: 0o700 })
+    const temporary = `${this.path}.tmp`
+    writeFileSync(temporary, JSON.stringify({ version: 1, sessions: [...this.sessions.values()] }), { mode: 0o600 })
+    renameSync(temporary, this.path)
+  }
+}

+ 5 - 0
src/server/index.ts

@@ -14,6 +14,7 @@ import { legacyDataHome, resolveDataHome } from '../../bin/lib/data-home.mjs'
 import { spawn } from 'node:child_process'
 import { ServerDashboardController } from './dashboardController.js'
 import { DesktopActivation } from './desktopActivation.js'
+import { importLegacyHermes } from './hermes/import.js'
 
 migrateDataHome(resolveDataHome(process.env.YAOYAO_HOME || process.env.HERMES_YAOYAO_HOME, { preserveActiveUpdate: true }))
 const config = loadServerConfig()
@@ -24,6 +25,10 @@ if (config.home === legacyDataHome() && process.platform === 'darwin') {
 }
 const instance = acquireServiceInstance(config.home, readReleaseManifest(resolve(process.cwd(), 'release.json')).webVersion, process.env.HERMES_YAOYAO_DESKTOP === '1', readBuildIdentity(process.cwd()))
 process.once('exit', () => instance.release())
+// First start with the embedded kernel: copy an existing ~/.hermes (read-only) into <data>/hermes.
+const hermesImport = importLegacyHermes(config.home)
+if (hermesImport.status === 'imported') console.log(`已导入原 Hermes 数据(${hermesImport.source},${hermesImport.files} 个文件)`)
+else if (hermesImport.status === 'failed') console.error(`原 Hermes 数据导入失败,内置 Hermes 将从空数据启动:${hermesImport.error}`)
 const dashboardSupervisor = config.superviseDashboard
   && isLocalAuthorizationTarget(config.upstream) && config.upstream.hostname === '127.0.0.1'
   && config.upstream.protocol === 'http:' && config.upstream.port === '9119'

+ 5 - 1
src/server/localAuth.ts

@@ -603,6 +603,7 @@ export class UpstreamServiceSession {
   get authorizationMode(): 'local' | 'account' { return this.#localAuthorization ? 'local' : 'account' }
 
   async webSocketCredential(): Promise<{ name: 'token' | 'ticket'; value: string }> {
+    if (this.client.embedded) throw new HttpError(410, '内置 Hermes 不提供 WebSocket 连接', 'embedded_hermes')
     await this.ensure()
     if (this.#localAuthorization) {
       if (!this.#jar.sessionToken) await this.#renewAuthorization(this.#generation)
@@ -632,10 +633,11 @@ export class UpstreamServiceSession {
 
   connectionInfo(): {
     endpoint: string
-    authMode: 'unknown' | 'loopback-token' | 'loopback-direct' | 'password'
+    authMode: 'unknown' | 'loopback-token' | 'loopback-direct' | 'password' | 'embedded'
     networkScope: 'local' | 'network'
     lastVerifiedAt?: number
   } {
+    if (this.client.embedded) return { endpoint: 'embedded', authMode: 'embedded', networkScope: 'local', lastVerifiedAt: this.#now() }
     return {
       endpoint: this.client.baseURL.origin,
       authMode: this.#authMode,
@@ -645,6 +647,7 @@ export class UpstreamServiceSession {
   }
 
   async ensure(): Promise<void> {
+    if (this.client.embedded) return
     this.#syncCredentials()
     if (this.#validatedUntil > this.#now()) return
     if (this.#ensureTask) return this.#ensureTask
@@ -718,6 +721,7 @@ export class UpstreamServiceSession {
   }
 
   async verify(credentials: UpstreamCredentials): Promise<void> {
+    if (this.client.embedded) throw new HttpError(410, '内置 Hermes 不使用上游账号', 'embedded_hermes')
     await this.#authenticate(credentials, new CookieJar(''))
   }
 

+ 1 - 0
src/server/routes.ts

@@ -61,6 +61,7 @@ import { chatCacheKey, type ChatCacheCoordinator } from './chatCache.js'
 type JsonObject = Record<string, unknown>
 
 export interface RouteDependencies {
+  hermes?: import('./hermes/embedded.js').EmbeddedHermes
   hermesBridge: import('./hermesBridge.js').HermesBridgeManager
   onChatListChanged?: (owner:string,profile:string,id:string)=>void
   onServerIdentityChanged?: (identity: ServerIdentity) => void

+ 9 - 1
src/server/upstream.ts

@@ -143,7 +143,10 @@ export class UpstreamClient {
     readonly publicSecure = false,
     now: () => number = Date.now,
   ) { this.readCache = new UpstreamReadCache(now) }
-  get directAgent() { return isLocalAuthorizationTarget(this.baseURL) ? this.loopback.agent(this.baseURL) : undefined }
+  /** In-process Hermes (embedded kernel). When set, requests never leave the process. */
+  local?: import('./hermes/api.js').HermesApi
+  get embedded(): boolean { return !!this.local }
+  get directAgent() { return !this.local && isLocalAuthorizationTarget(this.baseURL) ? this.loopback.agent(this.baseURL) : undefined }
   close(): void { this.readCache.close(); this.loopback.close() }
 
   withReadScope<T>(scope: string, fresh: boolean, run: () => T): T {
@@ -226,6 +229,11 @@ export class UpstreamClient {
     if (!path.startsWith('/') || path.startsWith('//') || path.includes('\\')) {
       throw new HttpError(500, 'Invalid internal upstream path')
     }
+    if (this.local) {
+      let body = options.body
+      if (body === undefined && typeof options.rawBody === 'string') { try { body = JSON.parse(options.rawBody) } catch { body = undefined } }
+      return this.local.handle({ method: options.method ?? 'GET', path, search: options.search, body, maxResponseBytes: options.maxResponseBytes })
+    }
     const url = new URL(this.baseURL)
     const prefix = this.baseURL.pathname === '/' ? '' : this.baseURL.pathname.replace(/\/$/, '')
     const expectedPath = `${prefix}${path}`

+ 80 - 0
tests/runtime/test_hermes_import.py

@@ -0,0 +1,80 @@
+"""Read-only import of an existing Hermes home into the embedded home."""
+import hashlib
+import json
+import sqlite3
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+SCRIPT = ROOT / "runtime" / "hermes_import.py"
+
+
+def tree_digest(root: Path) -> str:
+    h = hashlib.sha256()
+    for path in sorted(p for p in root.rglob("*") if p.is_file() and not p.name.endswith(("-wal", "-shm"))):
+        h.update(str(path.relative_to(root)).encode())
+        h.update(path.read_bytes())
+    return h.hexdigest()
+
+
+class HermesImportTest(unittest.TestCase):
+    def test_copies_data_and_leaves_source_untouched(self):
+        with tempfile.TemporaryDirectory() as tmp:
+            source, staging = Path(tmp, "hermes"), Path(tmp, "staging")
+            (source / "profiles" / "writer").mkdir(parents=True)
+            (source / "config.yaml").write_text("model:\n  provider: openrouter\n")
+            (source / "auth.json").write_text('{"providers": {}}')
+            (source / ".env").write_text("OPENROUTER_API_KEY=sk-test\n")
+            (source / "profiles" / "writer" / "config.yaml").write_text("model:\n  default: x\n")
+            (source / "skills" / "demo").mkdir(parents=True)
+            (source / "skills" / "demo" / "SKILL.md").write_text("# demo\n")
+            for skipped in ("hermes-agent", "logs", "plugins/yaoyao-bot-bridge"):
+                (source / skipped).mkdir(parents=True)
+                (source / skipped / "file.txt").write_text("skip")
+            (source / "plugins" / "other").mkdir(parents=True)
+            (source / "plugins" / "other" / "plugin.yaml").write_text("name: other\n")
+            (source / "gateway.pid").write_text("123")
+            db = sqlite3.connect(source / "state.db")
+            db.execute("PRAGMA journal_mode=WAL")
+            db.execute("CREATE TABLE sessions (id TEXT PRIMARY KEY, title TEXT)")
+            db.execute("INSERT INTO sessions VALUES ('s1', 'hello')")
+            db.commit()  # keep the connection open: the import must read a live WAL database
+            before = tree_digest(source)
+
+            result = subprocess.run([sys.executable, "-I", str(SCRIPT), str(source), str(staging)],
+                                    capture_output=True, text=True, check=True)
+            after = tree_digest(source)
+            db.close()
+            summary = json.loads(result.stdout)
+            self.assertGreater(summary["files"], 0)
+
+            self.assertEqual((staging / "config.yaml").read_text(), "model:\n  provider: openrouter\n")
+            self.assertTrue((staging / "profiles" / "writer" / "config.yaml").exists())
+            self.assertTrue((staging / "skills" / "demo" / "SKILL.md").exists())
+            self.assertTrue((staging / "plugins" / "other" / "plugin.yaml").exists())
+            for skipped in ("hermes-agent", "logs", "plugins/yaoyao-bot-bridge", "gateway.pid"):
+                self.assertFalse((staging / skipped).exists(), skipped)
+            copied = sqlite3.connect(staging / "state.db")
+            self.assertEqual(copied.execute("SELECT title FROM sessions WHERE id='s1'").fetchone()[0], "hello")
+            copied.close()
+            manifest = json.loads((staging / ".import.json").read_text())
+            self.assertEqual(manifest["source"], str(source.resolve()))
+            self.assertEqual(oct((staging / ".env").stat().st_mode & 0o777), "0o600")
+            # The legacy home is read-only input (WAL files from our own writer aside).
+            self.assertEqual(after, before)
+
+    def test_refuses_existing_staging_directory(self):
+        with tempfile.TemporaryDirectory() as tmp:
+            source, staging = Path(tmp, "hermes"), Path(tmp, "staging")
+            source.mkdir()
+            (source / "config.yaml").write_text("{}")
+            staging.mkdir()
+            result = subprocess.run([sys.executable, "-I", str(SCRIPT), str(source), str(staging)], capture_output=True, text=True)
+            self.assertNotEqual(result.returncode, 0)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 48 - 0
tests/server/embeddedHermesApi.test.ts

@@ -0,0 +1,48 @@
+import { existsSync, mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { createEmbeddedHermes, type EmbeddedHermes } from '../../src/server/hermes/embedded.js'
+import { kernelPaths } from '../../src/server/hermes/paths.js'
+
+const kernel = existsSync(kernelPaths().python)
+const env = { ...process.env, YAOVI_HERMES_TEST_OFFLINE: '1' }
+
+describe.skipIf(!kernel)('embedded Hermes dashboard API', () => {
+  let home = ''
+  let hermes: EmbeddedHermes | undefined
+  afterEach(() => { hermes?.close(); hermes = undefined; if (home) rmSync(home, { recursive: true, force: true }) })
+
+  const call = async (method: string, path: string, query: Record<string, string> = {}, body?: unknown) => {
+    const response = await hermes!.api.handle({ method, path, search: new URLSearchParams(query), body })
+    return { status: response.status, body: JSON.parse(response.body.toString() || 'null') }
+  }
+
+  it('serves native dashboard shapes without any listening Hermes service', async () => {
+    home = mkdtempSync(join(tmpdir(), 'yaoyao-hermes-api-'))
+    hermes = createEmbeddedHermes(home, { env })
+    expect((await call('GET', '/api/status')).body).toMatchObject({ auth_required: false, embedded: true })
+    expect((await call('GET', '/api/sessions', { limit: '5' })).body).toMatchObject({ sessions: [], total: 0 })
+    const profiles = await call('GET', '/api/profiles')
+    expect(profiles.status).toBe(200)
+    expect(profiles.body.profiles.map((p: { name: string }) => p.name)).toContain('default')
+    const options = await call('GET', '/api/model/options')
+    expect(options.status).toBe(200)
+    expect(Array.isArray(options.body.providers)).toBe(true)
+    expect((await call('GET', '/api/sessions/missing/messages')).status).toBe(404)
+    expect((await call('GET', '/api/kanban/boards')).status).toBe(404)
+    expect((await call('POST', '/api/auth/ws-ticket')).status).toBe(410)
+  }, 120_000)
+
+  it('writes custom model endpoints into the embedded config.yaml', async () => {
+    home = mkdtempSync(join(tmpdir(), 'yaoyao-hermes-api-'))
+    hermes = createEmbeddedHermes(home, { env })
+    const created = await call('POST', '/api/providers/custom-endpoints', {}, {
+      name: 'local-test', base_url: 'http://127.0.0.1:9/v1', model: 'test-model', api_key: 'sk-local-test-key-0000',
+    })
+    expect(created.status, JSON.stringify(created.body)).toBeLessThan(300)
+    const listed = await call('GET', '/api/providers/custom-endpoints')
+    expect(JSON.stringify(listed.body)).toContain('local-test')
+    expect(existsSync(join(home, 'hermes', 'config.yaml'))).toBe(true)
+  }, 120_000)
+})