The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tui): compact server.py docstrings/comments, keep every WHY
Tekniumc0362aedd9b5
diff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 9ef5f429958..ae57bac1cd0 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -42,15 +42,12 @@ _hermes_home = get_hermes_home()load_hermes_dotenv(hermes_home=_hermes_home, project_env=Path(__file__).parent.parent / ".env")-# ── Panic logger ─────────────────────────────────────────────────────-# Crashes otherwise leave no forensics (stdout is the JSON-RPC pipe, stderr-# doesn't flush before exit): append every unhandled exception to-# logs/tui_gateway_crash.log and re-emit a one-line stderr summary for Activity.+# ── Panic logger: crashes otherwise leave no forensics (stdout is the JSON-RPC pipe, stderr doesn't+# flush before exit) → append every unhandled exception to the crash log + one-line stderr summary._CRASH_LOG = os.path.join(_hermes_home, "logs", "tui_gateway_crash.log")def _record_crash(kind: str, exc_type, exc_value, exc_tb, *, thread_name: str | None = None) -> None:- """Append the trace to the crash log, then print the one-line stderr summary the TUI shows."""import tracebacktrace = "".join(traceback.format_exception(exc_type, exc_value, exc_tb))suffix = f" · thread={thread_name}" if thread_name is not None else ""@@ -122,41 +119,36 @@ def _ws_orphan_setting(env_var: str, cfg_key: str, default: float) -> float:def _resolve_ws_orphan_reap_grace() -> float:- """Grace before an orphaned WS session is interrupted/reaped; 0 = park forever.- ws.py parks a disconnected session for a quick reattach, but a browser refresh- mints a NEW sid and never reattaches the old one (leaking its slash worker)."""+ """Grace before an orphaned WS session is interrupted/reaped (0 = park forever): ws.py parks a+ disconnected session for a quick reattach, but a browser refresh mints a NEW sid and never+ reattaches the old one (leaking its slash worker)."""return _ws_orphan_setting("HERMES_TUI_WS_ORPHAN_REAP_GRACE_S", "ws_orphan_reap_grace_s", 20.0)_WS_ORPHAN_REAP_GRACE_S = _resolve_ws_orphan_reap_grace()-# A detached RUNNING turn is interrupted by the orphan reaper only once its activity-# clock (API waits, stream tokens, tool heartbeats) has idled this long; 600s matches-# the turn-liveness watchdog so "wedged" means the same on both paths. 0 disables the gate.+# A detached RUNNING turn is interrupted only once its activity clock (API waits, stream tokens, tool+# heartbeats) idled this long; 600s = the turn-liveness watchdog so "wedged" means the same. 0 disables._WS_ORPHAN_ACTIVITY_STALE_S = _ws_orphan_setting("HERMES_TUI_WS_ORPHAN_ACTIVITY_STALE_S", "ws_orphan_activity_stale_s", 600.0)_WS_ORPHAN_INTERRUPT_REAP_POLL_S = 1.0-# Budget for the interrupt-then-reap poll chain: an interrupted turn that never-# settles (thread hung in a syscall) would reschedule the 1s poll forever. After-# this many polls, log loudly and force-reap.+# Interrupt-then-reap poll budget: a turn that never settles (thread hung in a syscall) would+# reschedule the 1s poll forever; after this many polls, log loudly and force-reap._WS_ORPHAN_INTERRUPT_REAP_MAX_POLLS = 60_TURN_SETTLE_BEFORE_CLOSE_SECONDS = 5.0_DETAIL_SECTION_NAMES = ("thinking", "tools", "subagents", "activity")_DETAIL_MODES = frozenset({"hidden", "collapsed", "expanded"})-# ── Async RPC dispatch ───────────────────────────────────────────────-# Slow handlers (seconds to minutes) would leave approval.respond and-# session.interrupt unread in the stdin pipe; only those go to a small thread-# pool, everything else stays inline so fast-path ordering stays sane.-# write_json is _stdout_lock-guarded, so concurrent response writes are safe.-# Why each is slow: billing/subscription/usage = blocking portal (+Stripe) round-trips;-# complete.* = git ls-files / prompt_toolkit import + skill scan; model.options =-# credential pool + pricing + provider probe; pet.* = network or PNG decode (generate-# = several image-model round-trips); reload.mcp / mcp.servers.* = server rediscovery,-# cold npx spawn, ~30s OAuth wait; profiles.* = skill-tree walk + state.db open;-# bot_relay.* = a FULL one-turn agent conversation (600s); setup.* / session.active_list-# = Desktop-polled and under GIL pressure block the WS read loop (false "needs setup",-# stalled interrupts); voice.*/wake.* = SYNCHRONOUS faster-whisper install (300s);-# session.workspace.move = git subprocess probes on an arbitrary (maybe slow) mount.+# ── Async RPC dispatch: slow handlers (seconds to minutes) would leave approval.respond and+# session.interrupt unread in the stdin pipe, so only THESE go to a small thread pool; everything else+# stays inline so fast-path ordering stays sane (write_json is _stdout_lock-guarded). Why each is slow:+# billing/subscription/usage = blocking portal (+Stripe) round-trips; complete.* = git ls-files /+# prompt_toolkit import + skill scan; model.options = credential pool + pricing + provider probe;+# pet.* = network or PNG decode (generate = several image-model round-trips); reload.mcp /+# mcp.servers.* = rediscovery, cold npx spawn, ~30s OAuth wait; profiles.* = skill-tree walk + state.db+# open; bot_relay.* = a FULL one-turn agent conversation (600s); setup.* / session.active_list =+# Desktop-polled and under GIL pressure block the WS read loop (false "needs setup", stalled+# interrupts); voice.*/wake.* = SYNCHRONOUS faster-whisper install (300s); session.workspace.move =+# git subprocess probes on an arbitrary (maybe slow) mount._LONG_HANDLERS = frozenset({"billing.state", "subscription.state", "subscription.preview", "subscription.change","subscription.resume", "subscription.upgrade", "usage.bars", "session.usage", "billing.step_up",@@ -176,8 +168,8 @@ _rpc_pool_workers = max(2, env_int("HERMES_TUI_RPC_POOL_WORKERS", 8))_pool = concurrent.futures.ThreadPoolExecutor(max_workers=_rpc_pool_workers, thread_name_prefix="tui-rpc")atexit.register(lambda: _pool.shutdown(wait=False, cancel_futures=True))-# Exact in-memory session generation executing on the current turn thread.-# Unlike a public session id, this object identity cannot be supplied by RPC.+# Exact in-memory session record executing on the current turn thread — unlike a public session id,+# this object identity cannot be supplied by RPC._current_runtime_session_record: contextvars.ContextVar[dict | None] = contextvars.ContextVar("hermes_gateway_runtime_session_record", default=None)# JSON-RPC method being dispatched on this thread/task. Diagnostic only (names WHICH client@@ -210,16 +202,14 @@ _detached_ws_transport = _DropTransport()def _prepend_tool_paths(env: dict[str, str]) -> dict[str, str]:- """Prepend managed bin, venv bin and ~/.local/bin to PATH so slash_worker children resolve- Hermes-managed CLIs (browser-use, uvx, uv) under the Desktop's minimal PATH. Managed bin leads- (managed-first policy for the Browser Use CLI)."""+ """Prepend managed bin (first: managed-first policy for the Browser Use CLI), venv bin and+ ~/.local/bin to PATH so slash_worker children resolve Hermes-managed CLIs under the Desktop's minimal PATH."""managed_bin = ""with contextlib.suppress(Exception):managed_bin = str(Path(get_hermes_home()) / "bin")venv_bin = str(Path(sys.executable).parent) # <venv>/bin (POSIX) or <venv>/Scripts (Windows)- user_bin = str(Path.home() / ".local" / "bin")- existing = env.get("PATH") or ""- env["PATH"] = os.pathsep.join([p for p in (managed_bin, venv_bin, user_bin) if p] + ([existing] if existing else []))+ parts = [p for p in (managed_bin, venv_bin, str(Path.home() / ".local" / "bin"), env.get("PATH") or "") if p]+ env["PATH"] = os.pathsep.join(parts)return env@@ -330,8 +320,7 @@ def _load_interim_assistant_messages() -> bool:def _shutdown_sessions() -> None:- # Durable-first: flush every un-flushed transcript (bounded budget) BEFORE the slow- # per-session teardown, so a supervisor SIGKILL mid-shutdown can no longer lose them.+ # Durable-first: flush transcripts (bounded budget) BEFORE the slow teardown so a supervisor SIGKILL can't lose them.for step in (_flush_sessions_before_exit, _release_gateway_wake_owner):with contextlib.suppress(Exception):step()@@ -341,13 +330,13 @@ def _shutdown_sessions() -> None:_close_session_by_id(sid, end_reason="tui_shutdown")-# Session reaping / flushing knobs (implementation: session_reaper.py). TTL is the last-resort-# net for disconnect paths that slip past the WS finally; hours-scale because last_active freezes-# during a long turn and on passive viewing — running/pending/starting/live-transport are hard exemptions.+# Session reaping / flushing knobs (session_reaper.py). TTL is the last-resort net for disconnect paths that+# slip past the WS finally; hours-scale because last_active freezes during a long turn and on passive+# viewing — running/pending/starting/live-transport are hard exemptions._SESSION_TTL_S = max(0.0, env_float("HERMES_TUI_SESSION_TTL_S", float(6 * 3600)))_REAPER_SCAN_S = 300.0-# Flush-on-kill budget + periodic incremental flush (piggybacks the reaper scan) so a-# SIGTERM/SIGKILL mid-update loses at most one flush interval of session state.+# Flush-on-kill budget + periodic incremental flush (piggybacks the reaper scan): a SIGTERM/SIGKILL+# mid-update loses at most one flush interval of session state._EXIT_FLUSH_BUDGET_S = max(0.0, env_float("HERMES_TUI_EXIT_FLUSH_BUDGET_S", 5.0))_INCREMENTAL_FLUSH_INTERVAL_S = max(0.0, env_float("HERMES_TUI_SESSION_FLUSH_INTERVAL_S", _REAPER_SCAN_S))@@ -383,14 +372,11 @@ def _get_db():def _transfer_db_to_agent(agent, db) -> bool:"""Hand a DEDICATED profile ``state.db`` handle to *agent* (``AIAgent.close()`` then releases it).- True only when the transfer happened; False (agent not holding *this* handle — build failed- before ``_make_agent`` or it got a different db) tells the caller the handle is still its own- to close. The shared launch handle never transfers: it outlives every agent, and ownership- would let session.close() tear down the process-wide database."""- if agent is None or db is None:- return False+ False = agent not holding *this* handle (build failed before ``_make_agent`` or got a different db):+ the caller still owns it. The shared launch handle never transfers — it outlives every agent, and+ ownership would let session.close() tear down the process-wide database."""try:- if getattr(agent, "_session_db", None) is not db:+ if agent is None or db is None or getattr(agent, "_session_db", None) is not db:return Falseif db is _get_db():logger.warning("Refused transfer of the shared launch SessionDB to a session "@@ -403,10 +389,9 @@ def _transfer_db_to_agent(agent, db) -> bool:def _open_profile_session_db(profile_home):- """Open a DEDICATED handle on ``profile_home``'s ``state.db`` — FAIL CLOSED.- A silent fallback to the launch ``state.db`` would bleed the session's rows into the wrong- profile's store exactly when the profile store is briefly unopenable (locked, mid-restore), so- callers let the raised error abort the agent build (deferred builds → ``agent_error``)."""+ """Open a DEDICATED handle on ``profile_home``'s ``state.db`` — FAIL CLOSED: a silent fallback to the+ launch ``state.db`` would bleed rows into the wrong profile's store exactly when the profile store is+ briefly unopenable (locked, mid-restore); callers let the error abort the build (→ ``agent_error``)."""from hermes_state import get_shared_session_dbdb_path = Path(profile_home) / "state.db"try:@@ -449,10 +434,9 @@ def _db_unavailable_error(rid, *, code: int):return _err(rid, code, f"state.db unavailable: {_db_error or 'state.db unavailable'}")-# ── per-session profile scoping (global remote mode) ───────────────────────────-# The desktop's app-global remote mode points every profile at this backend, so calls carry-# ``profile``: open that profile's db and bind its HERMES_HOME (ContextVar override) for the-# call so config/skills/model/persistence resolve to it. Omitted/own profile → launch profile.+# ── Per-session profile scoping: the desktop's app-global remote mode points every profile at this+# backend, so calls carry ``profile`` → open that profile's db and bind its HERMES_HOME (ContextVar+# override) so config/skills/model/persistence resolve to it. Omitted/own profile → launch profile.def _profile_home(profile: str | None) -> Path | None:"""Resolve a named profile's home on THIS host, or None for the launch profile."""if not (name := (profile or "").strip()):@@ -478,7 +462,6 @@ _served_profile_homes: set[Path] = set()def _profile_scoped(handler):"""Bind ``params['profile']``'s HERMES_HOME around a handler (pets/projects resolve via``get_hermes_home``, so app-global remote mode still hits the focused profile). No-op for launch."""-def wrapper(rid, params):home = _profile_home(params.get("profile") if isinstance(params, dict) else None)if home is None:@@ -491,8 +474,8 @@ def _profile_scoped(handler):return wrapper-# Placeholder ``terminal.cwd`` values that don't name a real directory — resolved to the home dir at-# runtime, so they must NOT be treated as an explicit workspace (mirrors gateway/run.py's config bridge).+# Placeholder ``terminal.cwd`` values (resolved to the home dir at runtime) — never an explicit+# workspace (mirrors gateway/run.py's config bridge)._CWD_PLACEHOLDERS = {".", "auto", "cwd"}@@ -507,11 +490,9 @@ def _configured_cwd_from_cfg(cfg: dict | None) -> str | None:def _profile_configured_cwd(profile_home: Path | None) -> str | None:- """A non-launch profile's ``terminal.cwd`` from ITS config.yaml (fail-open → None).- The process-global ``TERMINAL_CWD`` belongs to the *launch* profile; a session bound to- another profile must take its workspace from that profile's config, not the stale env var.- load_config() resolves the ACTIVE profile, so read the file directly + the _load_cfg pipeline.- """+ """A non-launch profile's ``terminal.cwd`` from ITS config.yaml (fail-open → None): the process-global+ ``TERMINAL_CWD`` belongs to the *launch* profile, and load_config() resolves the ACTIVE profile, so+ read the file directly through the _load_cfg pipeline."""if profile_home is None:return Nonetry:@@ -523,9 +504,8 @@ def _profile_configured_cwd(profile_home: Path | None) -> str | None:def _launch_configured_cwd() -> str | None:- """Launch profile's ``terminal.cwd`` from config.yaml: the dashboard's in-memory gateway gets no- bridged ``TERMINAL_CWD`` env (only the Node PTY child does), so a fresh /chat would start in- ``os.getcwd()`` unless config is read directly."""+ """Launch profile's ``terminal.cwd`` from config.yaml: the dashboard's in-memory gateway gets no bridged+ ``TERMINAL_CWD`` env (only the Node PTY child does), so a fresh /chat would otherwise start in ``os.getcwd()``."""try:return _configured_cwd_from_cfg(_load_cfg())except Exception:@@ -533,18 +513,16 @@ def _launch_configured_cwd() -> str | None:def _default_session_cwd() -> str:- """Fallback cwd for a session with no explicit / stored / profile cwd (mirrors the launch-config-aware- tail of :func:`_completion_cwd`, so created AND resumed sessions land in the configured ``terminal.cwd``)."""+ """Fallback cwd when no explicit / stored / profile cwd (mirrors :func:`_completion_cwd`'s tail so created+ AND resumed sessions land in the configured ``terminal.cwd``)."""return _launch_configured_cwd() or os.getenv("TERMINAL_CWD") or os.getcwd()def write_json(obj: dict) -> bool:- """Emit one JSON frame via the most-specific transport.- Precedence: (1) event frames with a session id → that session's transport, so async events- reach the owning client even from threads with no contextvar binding; (2) the transport bound- on the current context (:func:`dispatch`); (3) the module stdio transport (historical- behaviour; tests monkey-patch ``_real_stdout``). Every event frame gets a per-session- monotonic ``seq`` + replay-ring entry (event_replay) so ``session.events.since`` can resume."""+ """Emit one JSON frame via the most-specific transport: (1) event frames with a session id → that+ session's transport (async events reach the owner even from threads with no contextvar binding);+ (2) the context-bound transport (:func:`dispatch`); (3) module stdio (tests monkey-patch ``_real_stdout``).+ Every event frame gets a per-session monotonic ``seq`` + replay-ring entry so ``session.events.since`` can resume."""from tui_gateway.event_replay import _stamp_event_stamp_event(obj)if obj.get("method") == "event":@@ -566,8 +544,8 @@ def _emit(event: str, sid: str, payload: dict | None = None):write_json(_event_frame(event, sid, payload))-# Live WS peer transports (maintained by tui_gateway.ws): the only route for session-less-# background events, which write_json would otherwise drop on stdio. See _broadcast_global_event.+# Live WS peer transports (maintained by tui_gateway.ws): the only route for session-less background+# events, which write_json would otherwise drop on stdio (see _broadcast_global_event)._live_transports: set[Transport] = set()_live_transports_lock = threading.Lock()@@ -586,9 +564,8 @@ def unregister_live_transport(transport: Transport | None) -> None:def _broadcast_global_event(event: str, payload: dict | None = None) -> None:- """Fan a session-less, surface-global event (``skin.changed``) to every connected client.- Background emitters (skin watcher) bottom out at stdio in ``write_json``'s ladder, so WS peers- would never see the frame. No registered transports (stdio TUI, tests) → plain ``_emit``."""+ """Fan a session-less, surface-global event (``skin.changed``) to every connected client — background+ emitters bottom out at stdio in ``write_json``'s ladder. No registered transports (stdio TUI, tests) → ``_emit``."""with _live_transports_lock:targets = list(_live_transports)if not targets:@@ -618,11 +595,9 @@ def _approval_request_payload(data: dict | None) -> dict:def _pending_clarify_request_payload(sid: str) -> dict | None:- """Read-only snapshot of the clarify prompt still blocking a session, if any.- A client whose transport was detached when `clarify.request` was emitted would otherwise never- see the question (the agent thread stays parked until timeout). Same replay contract as- `pending_approval`: the registry stays authoritative; `clarify.respond` with the embedded- request_id resolves it."""+ """Read-only snapshot of the clarify prompt still blocking a session: a client detached when+ `clarify.request` was emitted would otherwise never see it (agent parked until timeout). Same replay+ contract as `pending_approval`: the registry stays authoritative; `clarify.respond` resolves by request_id."""with _prompt_lock:for rid, (owner_sid, _ev) in _pending.items():if owner_sid != sid:@@ -654,9 +629,8 @@ def _pending_approval_request_payload(session_key: str) -> dict | None:def _emit_approval_request(sid: str, data: dict | None) -> None:- """Emit ``approval.request`` with the command redacted: the payload is built from the RAW- command, so a credential-shaped value Tirith flagged would otherwise echo verbatim to the- TUI (third egress transport alongside chat platforms and the SSE/API stream)."""+ """Emit ``approval.request`` with the command redacted: a credential-shaped value Tirith flagged would+ otherwise echo verbatim to the TUI (third egress alongside chat platforms and the SSE/API stream)."""_emit("approval.request", sid, _approval_request_payload(data))@@ -802,19 +776,15 @@ def _agent_build_wait_cap() -> float:def _wait_agent_for_prompt(session: dict, rid: str, sid: str) -> dict | None:- """Patient ``_wait_agent`` for the deferred prompt.submit path.- prompt.submit already answered ``{"status": "streaming"}`` and the user's first message IS the- turn in flight, while a cold deferred build routinely outlives the flat 30s ceiling — timing- out here silently discarded that message. So: wait in short slices (cancel honored promptly),- notify the client once (keyed) past ``_AGENT_BUILD_SLOW_NOTICE_AFTER``, and fail only when the- build thread died without signalling ready or the bounded cap expired on a hung build.+ """Patient ``_wait_agent`` for deferred prompt.submit: the client already got ``streaming`` and the+ first message IS the turn, while a cold build routinely outlives the flat 30s ceiling (timing out+ silently discarded it). Waits in short slices (cancel honored promptly), notifies once (keyed) past+ ``_AGENT_BUILD_SLOW_NOTICE_AFTER``, fails only on a dead build thread or the bounded cap.Returns None on success OR cancel mid-wait (the caller's cancel branch owns that messaging)."""ready = session.get("agent_ready")if ready is None:return None- start = time.monotonic()- cap = _agent_build_wait_cap()- notified_slow = False+ start, cap, notified_slow = time.monotonic(), _agent_build_wait_cap(), Falsewhile not ready.wait(timeout=_AGENT_BUILD_WAIT_SLICE):with session["history_lock"]:cancelled = session.get("_turn_cancel_requested") or not session.get("running")@@ -833,32 +803,26 @@ def _wait_agent_for_prompt(session: dict, rid: str, sid: str) -> dict | None:if not notified_slow and waited >= _AGENT_BUILD_SLOW_NOTICE_AFTER:notified_slow = True # one keyed, replace-in-place notice (toast / status bar)_emit("notification.show", sid, {- "text": (- "Still starting the agent (tool discovery / model "- "setup) — your message will be sent as soon as it's "- "ready."),+ "text": "Still starting the agent (tool discovery / model setup) — your message will be sent as soon as it's ready.","level": "info", "kind": "agent", "ttl_ms": None,- "key": _AGENT_BUILD_SLOW_NOTICE_KEY, "id": _AGENT_BUILD_SLOW_NOTICE_KEY,- })+ "key": _AGENT_BUILD_SLOW_NOTICE_KEY, "id": _AGENT_BUILD_SLOW_NOTICE_KEY})if notified_slow:_emit("notification.clear", sid, {"key": _AGENT_BUILD_SLOW_NOTICE_KEY})return _err(rid, 5032, err) if (err := session.get("agent_error")) else Nonedef _bind_build_profile_scopes(profile_home: str) -> "_TurnScopes":- """Bind a session profile's HERMES_HOME / secret / terminal scopes for an agent build.- Fail-open per scope (the build must not die on a scope helper); the terminal installer itself- fails closed (malformed policy → refusal scope) so _make_agent's terminal probing / cwd hints- resolve the routed profile, never the launch process."""+ """Bind a session profile's HERMES_HOME / secret / terminal scopes for an agent build. Fail-open per+ scope (the build must not die on a scope helper); the terminal installer itself fails closed (malformed+ policy → refusal scope) so _make_agent's terminal probing / cwd hints resolve the routed profile."""scopes = _TurnScopes()scopes.home = set_hermes_home_override(profile_home)with contextlib.suppress(Exception):scopes.secret = set_secret_scope(build_profile_secret_scope(Path(profile_home)))- try:+ scopes.terminal = None+ with contextlib.suppress(Exception):from tools.terminal_scope import install_profile_terminal_scopescopes.terminal = install_profile_terminal_scope(Path(profile_home))- except Exception:- scopes.terminal = Nonereturn scopes@@ -875,13 +839,10 @@ def _release_build_profile_scopes(scopes: "_TurnScopes") -> None:def _deferred_build_agent_kwargs(current: dict, session_db) -> dict:- """_make_agent kwargs for a deferred (first-prompt) build.- A lazy-resumed (watch) session carries the stored conversation id so the upgrade continues it.- A cold deferred resume restores the full persisted runtime identity (as the eager resume's- _stored_session_runtime_overrides splat does) so the build can't drop the provider ("No LLM- provider configured"). No stored runtime, or its provider no longer resolves → the model/effort/- tier the desktop picked for THIS session, else the configured default — never "Unknown provider".- """+ """_make_agent kwargs for a deferred (first-prompt) build. A lazy-resumed (watch) session carries the+ stored conversation id so the upgrade continues it; a cold deferred resume restores the full persisted+ runtime identity (like the eager resume's overrides splat) so the build can't drop the provider. No+ stored runtime, or an unroutable provider → this session's picked model/effort/tier, else the default."""kw = {"session_db": session_db, "context_cwd_is_launch_artifact": _context_cwd_is_launch_artifact(current)}if resume_sid := current.get("resume_session_id"):kw["session_id"] = resume_sid@@ -900,9 +861,9 @@ def _deferred_build_agent_kwargs(current: dict, session_db) -> dict:def _wire_session_agent(sid: str, key: str, agent) -> bool:- """Post-build wiring for a session agent; returns whether the approval notify got registered.- Approval prompts route to the client; the self-improvement review's "💾 …" summary is emitted- as review.summary (the TUI has no print surface), honoring display.memory_notifications."""+ """Post-build wiring; returns whether the approval notify got registered. Approval prompts route to the+ client; the self-improvement "💾 …" summary is emitted as review.summary (no print surface), honoring+ display.memory_notifications."""notify_registered = Falsewith contextlib.suppress(Exception):from tools.approval import load_permanent_allowlist, register_gateway_notify@@ -939,8 +900,7 @@ def _await_resume_history(sid: str, current: dict) -> bool:def _attach_built_agent(current: dict, agent) -> None:"""Attach a freshly built agent to its live record (session DB row deferred to first run_conversation())."""- # Bot Mode gate hint: the DB title lands post-first-turn but the system prompt builds at- # turn START, so hand the agent its title.+ # Bot Mode gate hint: the DB title lands post-first-turn but the system prompt builds at turn START.if _title_hint := str(current.get("pending_title") or "").strip():agent._session_title_hint = _title_hintcurrent["agent"] = agent@@ -951,7 +911,7 @@ def _attach_built_agent(current: dict, agent) -> None:def _announce_built_agent(sid: str, key: str, current: dict, agent) -> None:"""Post-wiring tail of a build: credits seed, session services, session.info, late MCP catch-up."""- # Credits notices at session OPEN (after notice_callback is wired) so depletion warnings show at "ready".+ # Credits notices at session OPEN (notice_callback already wired) so depletion warnings show at "ready".with contextlib.suppress(Exception):from agent.credits_tracker import seed_credits_at_session_startseed_credits_at_session_start(agent)@@ -961,26 +921,23 @@ def _announce_built_agent(sid: str, key: str, current: dict, agent) -> None:info["config_warning"] = cfg_warnlogger.warning(cfg_warn)_emit("session.info", sid, info)- # MCP servers slower than _make_agent's bounded discovery wait are missing from the tool- # list; catch up once they land (cache-safe: pre-first-turn only).- _schedule_mcp_late_refresh(sid, agent)+ _schedule_mcp_late_refresh(sid, agent) # servers slower than the bounded discovery wait land heredef _finish_agent_build(sid: str, key: str, current: dict, *, notify_registered: bool, scopes, session_db) -> None:"""Release build scopes and settle ownership of the late notify registration + dedicated db handle."""if scopes is not None:_release_build_profile_scopes(scopes)- # _attach_worker already closed the worker if this session was reaped mid-build; only the- # late notify registration can still leak (session.close unregistered before _build registered).+ # Reaped mid-build: _attach_worker closed the worker; only a late notify registration can still+ # leak (session.close unregistered before _build registered).with _sessions_lock:replaced = _sessions.get(sid) is not currentif replaced and notify_registered:with contextlib.suppress(Exception):from tools.approval import unregister_gateway_notifyunregister_gateway_notify(key)- # Dedicated profile handle: hand it to the agent that will actually be torn down, or close- # it when no such agent exists (build failed, or `replaced`: this agent is discarded and- # _teardown_session never reaches it).+ # Dedicated profile handle: hand it to the agent that will be torn down, else close it (build+ # failed, or `replaced`: this agent is discarded and _teardown_session never reaches it).if session_db is not None:built = None if replaced else current.get("agent")if not _transfer_db_to_agent(built, session_db):@@ -989,16 +946,14 @@ def _finish_agent_build(sid: str, key: str, current: dict, *, notify_registered:def _start_agent_build(sid: str, session: dict) -> None:- """Start building the real AIAgent for a TUI session, once.- Deferred until the first prompt (or any command that needs the agent) so the composer is- responsive instead of blocked on tool discovery / model metadata; the ready/error event- contract for the frontend is unchanged."""+ """Start building the real AIAgent for a TUI session, once. Deferred until the first prompt (or any+ command needing the agent) so the composer isn't blocked on tool discovery / model metadata;+ the ready/error event contract is unchanged."""ready = session.get("agent_ready")if ready is None:return- # A lazy watch session spectating an in-flight child must stay lazy so the subagent- # live-mirror keeps flowing (the mirror bails once agent is set); incidental RPCs resolve- # through _sess() and would otherwise upgrade it mid-stream. Lifts once the child completes.+ # A lazy watch session spectating an in-flight child must stay lazy so the subagent live-mirror keeps+ # flowing (it bails once agent is set); incidental RPCs via _sess() would upgrade it mid-stream.if session.get("lazy") and _child_run_active(str(session.get("session_key") or "")):returnwith session.setdefault("agent_build_lock", threading.Lock()):@@ -1020,10 +975,9 @@ def _start_agent_build(sid: str, session: dict) -> None:if not _await_resume_history(sid, current):returntokens = _set_session_context(key)- # Build against the session's profile (global-remote): bind its HERMES_HOME so- # config/skills/model resolve to it, and hand the agent that profile's db. The handle- # is DEDICATED and ours until _transfer_db_to_agent in the finally; FAIL CLOSED on open- # failure rather than binding the launch DB and bleeding rows into the wrong state.db.+ # Global-remote: bind the session profile's HERMES_HOME and hand the agent that profile's db —+ # DEDICATED and ours until _transfer_db_to_agent in the finally; FAIL CLOSED rather than+ # binding the launch DB and bleeding rows into the wrong state.db.if profile_home:scopes = _bind_build_profile_scopes(profile_home)session_db = _open_profile_session_db(profile_home)@@ -1037,8 +991,8 @@ def _start_agent_build(sid: str, session: dict) -> None:finally:_clear_session_context(tokens)_attach_built_agent(current, agent)- # No eager slash-worker pre-warm (slash.exec spawns on demand): each worker forks the- # full stdio MCP fleet, and live-transport sessions are never reaped, so fleets would accumulate.+ # No eager slash-worker pre-warm (slash.exec spawns on demand): each worker forks the full stdio+ # MCP fleet, and live-transport sessions are never reaped, so fleets would accumulate.notify_registered = _wire_session_agent(sid, key, agent)_announce_built_agent(sid, key, current, agent)except Exception as e:@@ -1050,8 +1004,7 @@ def _start_agent_build(sid: str, session: dict) -> None:ready.set()build_thread = threading.Thread(target=_build, daemon=True)- # Handle for _wait_agent_for_prompt: a dead build thread with agent_ready still unset means- # the build died hard — waiters must not sit out the full cap on a corpse.+ # _wait_agent_for_prompt handle: dead thread + unset agent_ready = died hard; waiters must not sit out the cap.session["_agent_build_thread"] = build_threadbuild_thread.start()@@ -1061,8 +1014,8 @@ def _sess_nowait(params, rid):s = _sessions.get(sid)if s:return (s, None)- # Stale runtime id (orphan-reaped, LRU-evicted, idle-TTL torn down); the client should- # session.resume the STORED id. Logged so "message vanished" reads as "arrived and was rejected".+ # Stale runtime id (reaped/evicted/TTL): the client should session.resume the STORED id. Logged so+ # "message vanished" reads as "arrived and was rejected".logger.warning("session-scoped RPC rejected: method=%s session_id=%r not in memory ""(detached/reaped runtime; client should resume the stored session), rid=%r",@@ -1076,10 +1029,9 @@ def _sess(params, rid):def _sess_building(params, rid):- """Resolve a session and warm its agent build WITHOUT waiting for it — for the attach RPCs- (image/file/pdf attach, clipboard.paste, image.detach), which only touch record fields populated- at creation and run inline on the socket reader thread, where waiting on a cold build stalled the- paste AND every RPC behind it ("text is instant, images hang")."""+ """Resolve a session and warm its agent build WITHOUT waiting — for the attach RPCs (image/file/pdf,+ clipboard.paste, image.detach), which only touch creation-time fields and run inline on the socket+ reader thread, where waiting on a cold build stalled every RPC behind it ("text is instant, images hang")."""s, err = _sess_nowait(params, rid)if err:return (None, err)@@ -1125,11 +1077,10 @@ def _active_config_path() -> Path:def _load_cfg_raw() -> dict:- """The active profile's config.yaml EXACTLY as written — the write-back primitive.- ONLY for read→mutate→``_save_cfg`` round-trips and raw inspection: defaults, the managed overlay- or ``${VAR}`` expansion applied here would be persisted into the user's file on the next save.- Behavioral reads use :func:`_load_cfg`. Cache keyed on the resolved path so profiles don't clobber.- """+ """The active profile's config.yaml EXACTLY as written — the write-back primitive, ONLY for+ read→mutate→``_save_cfg`` round-trips and raw inspection (defaults / managed overlay / ``${VAR}``+ expansion applied here would be persisted on the next save). Behavioral reads use :func:`_load_cfg`.+ Cache keyed on the resolved path so profiles don't clobber."""global _cfg_cache, _cfg_mtime, _cfg_pathtry:p = _active_config_path()@@ -1157,10 +1108,9 @@ def _expand_cfg(cfg: dict) -> dict:def _load_cfg() -> dict:- """Behavioral config read: raw user file + managed overlay + ${VAR} expansion.- Same read-side pipeline as ``hermes_cli.config.load_config_readonly`` minus the DEFAULT_CONFIG- merge (callers treat a missing key as "unset"; merging would break ``_load_cfg() == {}``- sentinels). Never pass the result to ``_save_cfg`` — use ``_load_cfg_raw()`` for write-back."""+ """Behavioral config read: raw user file + managed overlay + ${VAR} expansion — ``load_config_readonly``+ minus the DEFAULT_CONFIG merge (callers treat a missing key as "unset"; merging would break+ ``_load_cfg() == {}`` sentinels). Never pass the result to ``_save_cfg`` (use ``_load_cfg_raw()``)."""cfg = _apply_managed(_load_cfg_raw())with contextlib.suppress(Exception):cfg = _expand_cfg(cfg)@@ -1168,9 +1118,9 @@ def _load_cfg() -> dict:def _apply_managed(cfg: dict) -> dict:- """Overlay administrator-pinned managed-scope values (read-side only, fail-open): this backend- builds config independently of load_config, so a managed skin / reasoning_effort / service_tier- / provider_routing would otherwise be silently ignored."""+ """Overlay administrator-pinned managed-scope values (read-side only, fail-open): this backend builds+ config independently of load_config, so managed skin/reasoning_effort/service_tier/provider_routing+ would otherwise be silently ignored."""try:from hermes_cli import managed_scopereturn managed_scope.apply_managed_overlay(cfg if isinstance(cfg, dict) else {})@@ -1182,8 +1132,8 @@ def _save_cfg(cfg: dict):global _cfg_cache, _cfg_mtime, _cfg_pathfrom utils import atomic_roundtrip_yaml_savepath = _active_config_path()- # Comment-, ordering- and Unicode-preserving write (a plain safe_dump clobbered hand-written- # configs); fails closed on an unreadable existing config.yaml like atomic_config_write.+ # Comment-, ordering- and Unicode-preserving write (a plain safe_dump clobbered hand-written configs);+ # fails closed on an unreadable existing config.yaml like atomic_config_write.atomic_roundtrip_yaml_save(path, cfg)with _cfg_lock:_cfg_cache, _cfg_path = copy.deepcopy(cfg), path@@ -1207,11 +1157,9 @@ def _set_session_context(session_key: str, cwd: str | None = None, *, ui_session# callers that know the workspace pass it.resolved = cwd if cwd is not None else (str(sess.get("cwd") or "") if sess is not None else "")source = _resolve_session_platform()- browser_control_principal = ""- browser_control_transport_family = ""- # Live conversation id for subprocess HERMES_SESSION_ID: an explicitly empty contextvar is- # authoritative for the subprocess-env bridge (no os.environ fallback), so never leave it "".- # Prefer the agent's durable session_id, then session_key (same derivation as session-finalize).+ browser_control_principal = browser_control_transport_family = ""+ # Live conversation id for subprocess HERMES_SESSION_ID: an explicitly empty contextvar is authoritative+ # (no os.environ fallback), so never leave it "" — agent's durable session_id, then session_key.session_id = session_keyif sess is not None:source = _session_source(sess)@@ -1244,9 +1192,8 @@ def _enable_gateway_prompts() -> None:# ── Blocking prompt factory ──────────────────────────────────────────-# Blocking bridges whose `*.respond` tolerates a late reply (allow_expired=True): on timeout the-# tool returns empty, but a slow renderer can still answer and would otherwise hit a raw 4009,-# so `.expire` tells it to tear the card down.+# Blocking bridges whose `*.respond` tolerates a late reply (allow_expired=True): on timeout the tool+# returns empty, but a slow renderer could still answer and hit a raw 4009 — `.expire` tears the card down._EXPIRING_REQUESTS = frozenset({"secret.request", "sudo.request", "clarify.request", "terminal.read.request","preview.read.request", "preview.act.request", "window.read.request", "mcp.setup.request",@@ -1263,15 +1210,14 @@ def _block(payload["request_id"] = rid_pending_prompt_payloads[rid] = (event, dict(payload))if batch_qids:- # Multi-question clarify: per-question answers accumulate here (update-in-place until- # every qid is locked). Locked answers survive a timeout — see the batch read-out below.+ # Multi-question clarify: per-question answers accumulate here (update-in-place until every+ # qid is locked); locked answers survive a timeout — see the batch read-out below._batch_clarify[rid] = {"qids": list(batch_qids), "answers": {}}- answered = False- batch_answers: dict | None = None+ answered, batch_answers = False, Nonetry:_emit(event, sid, payload)- # Natural Event semantics: None → wait forever (clarify_timeout <= 0, released only by a- # real answer or session.interrupt), 0 → return immediately, > 0 → bounded wait.+ # Event semantics: None → wait forever (clarify_timeout <= 0; released only by a real answer or+ # session.interrupt), 0 → return immediately, > 0 → bounded wait.answered = ev.wait(timeout)finally:with _prompt_lock:@@ -1283,14 +1229,12 @@ def _block(batch_answers = dict(batch_state["answers"])expire = lambda: _emit(f"{event.removesuffix('.request')}.expire", sid, {"request_id": rid})if batch_qids is not None:- # Cancel-all (respond with no question_id) resolves via _answers with an empty string —- # that stays a plain cancel, not a partial result.+ # Cancel-all (respond with no question_id) resolves via _answers with "" — a plain cancel, not a partial result.if answer_present:return answerresult: dict[str, object] = {"answers": batch_answers or {}}if not answered:- # Deadline hit: keep whatever was locked, tell the tool the rest are absences (not- # skips), and still fire the expire notification so live cards tear down.+ # Deadline hit: keep what was locked, report the rest as absences (not skips), still expire live cards.result["timed_out"] = Trueexpire()return json.dumps(result, ensure_ascii=False)@@ -1311,11 +1255,9 @@ def _clarify_timeout_seconds() -> float | None:def _clarify_block(sid: str, q, c, multi_select=False, questions=None) -> str:- """Bridge the clarify tool callback onto _block.- Single-question payloads keep their exact historical shape (``multi_select`` only when True,- so older renderers never see a new field). Batch calls emit one clarify.request with only the- wire fields (qid/question/choices/multi_select) — the tool-side entries also carry- result-assembly keys (id, choices_offered) the renderer must not see."""+ """Bridge the clarify tool callback onto _block. Single-question payloads keep their historical shape+ (``multi_select`` only when True — older renderers never see a new field); batch calls emit one+ clarify.request with only the wire fields (the tool-side entries carry result-assembly keys too)."""if questions:wire = [{"qid": e["qid"], "question": e["question"], "choices": e["choices"], "multi_select": bool(e["multi_select"])}@@ -1326,11 +1268,10 @@ def _clarify_block(sid: str, q, c, multi_select=False, questions=None) -> str:return _block("clarify.request", sid, payload, timeout=_clarify_timeout_seconds())-# A tour action is a DOM operation the renderer answers in milliseconds; the generous deadline-# exists only because a preview tour's first action injects the engine into a live page.+# A tour action is a DOM op the renderer answers in ms; the generous deadline exists only because a+# preview tour's first action injects the engine into a live page._TOUR_TIMEOUT_S = 45-# Until a session's client has proven it answers at all, hold it to a deadline a working-# renderer cannot miss. See _tour_request.+# Until a session's client has proven it answers at all, hold it to a deadline a working renderer cannot miss._TOUR_PROBE_TIMEOUT_S = 10_TOUR_BRIDGE_UNAVAILABLE = json.dumps({@@ -1345,12 +1286,10 @@ _TOUR_BRIDGE_UNAVAILABLE = json.dumps({def _tour_request(sid: str, payload: dict) -> str:- """Bridge the tour tool callback onto _block without paying for a client that cannot answer.- Renderer and backend update on different clocks: against an older app nobody calls- ``tour.respond`` and each action would block the full deadline, stacking per turn. So the- session's first action gets the short probe deadline; an unanswered probe marks the bridge- unavailable for that session; once a client has answered, actions get the full deadline. The- verdict lives on the session record, so a new session re-probes."""+ """Bridge the tour tool callback onto _block without paying for a client that cannot answer: against+ an older app nobody calls ``tour.respond`` and each action would block the full deadline, stacking per+ turn. First action per session gets the short probe deadline; unanswered → bridge marked unavailable+ for that session; once answered, the full deadline. Verdict lives on the record, so a new session re-probes."""session = _sessions.get(sid)if session is None: # detached caller: throwaway record, plain bridge, unprobedsession = {}@@ -1367,8 +1306,8 @@ def _tour_request(sid: str, payload: dict) -> str:def _clear_pending(sid: str | None = None) -> None:- """Release pending prompts with an empty answer: only *sid*'s (session.interrupt must not cancel- clarify/sudo/secret prompts on unrelated sessions), or every one when *sid* is None (shutdown)."""+ """Release pending prompts with an empty answer: only *sid*'s (session.interrupt must not cancel other+ sessions' prompts), or every one when *sid* is None (shutdown)."""with _prompt_lock:for rid, (owner_sid, ev) in list(_pending.items()):if sid is None or owner_sid == sid:@@ -1392,8 +1331,7 @@ def _resolve_model() -> str:return str(m.get("default", "") or "").strip()if isinstance(m, str) and m:return m.strip()- # No env seed and no config preference: the cost-safe silent default (catalog-labeled,- # cache-only read), never an expensive flagship the user didn't pick.+ # No env seed / config preference: the cost-safe silent default (cache-only read), never an unpicked flagship.try:from hermes_cli.models import get_preferred_silent_default_modelreturn get_preferred_silent_default_model()@@ -1402,16 +1340,15 @@ def _resolve_model() -> str:def _resolve_session_platform() -> str:- """Platform tag for a tui_gateway-routed session: ``HERMES_DESKTOP=1`` without- ``HERMES_DESKTOP_TERMINAL`` → "desktop" (chat panel; the agent then suggests TUI-only slash- commands), else "tui" (embedded terminal pane or standalone ``hermes --tui``)."""+ """``HERMES_DESKTOP=1`` without ``HERMES_DESKTOP_TERMINAL`` → "desktop" (chat panel; the agent then+ suggests TUI-only slash commands), else "tui" (embedded terminal pane or standalone ``hermes --tui``)."""desktop = is_truthy_value(os.environ.get("HERMES_DESKTOP"))return "desktop" if desktop and not is_truthy_value(os.environ.get("HERMES_DESKTOP_TERMINAL")) else "tui"def _resolve_session_source(explicit: str | None) -> str:- """Session DB ``source``: an explicit caller value (plugin session tagged ``"telegram"``) is- never rewritten; only empty/None falls back to the env-resolved platform."""+ """Session DB ``source``: an explicit caller value (plugin session tagged ``"telegram"``) is never+ rewritten; only empty/None falls back to the env-resolved platform."""return explicit or _resolve_session_platform()@@ -1420,11 +1357,9 @@ def _resolve_agent_platform(source: str | None) -> str:def _config_model_target() -> tuple[str, str]:- """(model, provider) selected by config.yaml — and ONLY config.- Never reads HERMES_MODEL / HERMES_INFERENCE_MODEL: that launch-scoped seed fed into the- per-turn sync would be replayed as a /model switch and persisted globally, or pin the session- so dashboard/CLI model changes never reach an open chat. Empty model = "no preference" → no-op sync.- """+ """(model, provider) selected by config.yaml — and ONLY config: the HERMES_MODEL launch seed fed into+ the per-turn sync would be replayed as a /model switch and persisted globally, or pin the session so+ dashboard/CLI model changes never reach an open chat. Empty model = "no preference" → no-op sync."""cfg_model = _load_cfg().get("model")if isinstance(cfg_model, dict):provider = str(cfg_model.get("provider") or "").strip()@@ -1451,9 +1386,8 @@ def _resolve_startup_runtime() -> tuple[str, str | None]:return model, None-# Bare billing buckets are not routable provider identities; restoring one as a session-# provider override breaks resume. ``openrouter`` is deliberately NOT in this set (fully-# routable) — agent_init's fail-fast gate is a different set that skips it.+# Bare billing buckets are not routable provider identities; restoring one as a session provider override+# breaks resume. ``openrouter`` is deliberately NOT in this set (fully routable; agent_init's gate is a different set).from hermes_state import _BARE_BILLING_PROVIDERS@@ -1466,9 +1400,8 @@ def _is_routable_provider(provider: str) -> bool:def _overrides_have_routable_provider(overrides: dict) -> bool:- """Whether persisted runtime overrides still name a routable provider (renamed/removed →- "Unknown provider" at agent init). Empty counts as NOT routable, so the caller falls back to the- session's picked model / configured default instead of a provider-less snapshot."""+ """Whether persisted runtime overrides still name a routable provider (renamed/removed → "Unknown+ provider" at agent init). Empty = NOT routable, so the caller falls back to the session's picked model."""provider = str(overrides.get("provider_override") or "").strip()if not provider:provider = str((overrides.get("model_override") or {}).get("provider") or "").strip()@@ -1492,38 +1425,31 @@ def _parse_model_config(raw, *, quiet: bool = False) -> dict:def _stored_session_runtime_overrides(row: dict | None) -> dict:- """Runtime fields persisted with a stored session (model column, ``billing_provider``, JSON ``model_config``).- ``session.resume`` is session-scoped: reopening an older chat restores the model/provider/- reasoning THAT chat used, not the global model most recently selected elsewhere.- Plugin-owned Bot-Mode sessions are exempt and always rebuild from the member profile's CURRENT- config (a stale provider pin left room bots failing "out of Nous credits" after a profile- switch). Signals, in order: explicit ``room_plumbing`` / ``follow_profile_config`` markers;- the legacy hidden + "Group:" title shape; the title exactly "Bot Chat" (UNIQUE(title))."""+ """Runtime fields persisted with a stored session (model column, ``billing_provider``, JSON ``model_config``):+ resume restores the model/provider/reasoning THAT chat used, not the global pick. Plugin-owned Bot-Mode+ sessions are exempt and rebuild from the member profile's CURRENT config (a stale provider pin left+ room bots "out of Nous credits" after a profile switch); signals: ``room_plumbing`` /+ ``follow_profile_config`` markers, the legacy hidden + "Group:" title, the title exactly "Bot Chat"."""if not row:return {}model_config = _parse_model_config(row.get("model_config"), quiet=True)_row_title = str(row.get("title") or "").strip()- if (- model_config.get("room_plumbing")- or (row.get("hidden") and _row_title.startswith("Group:"))- or model_config.get("follow_profile_config")- or _row_title == "Bot Chat"):+ if (model_config.get("room_plumbing") or (row.get("hidden") and _row_title.startswith("Group:"))+ or model_config.get("follow_profile_config") or _row_title == "Bot Chat"):return {}overrides: dict = {}field = lambda k: str(model_config.get(k) or "").strip()model = str(row.get("model") or model_config.get("model") or "").strip()- # ``billing_provider`` is only the billing bucket — for a custom endpoint the bare class- # "custom", which agent_init treats as non-routable ("No LLM provider configured" on resume).- # Only restore an explicit provider; otherwise resume falls back to the configured default.+ # ``billing_provider`` is only the billing bucket — for a custom endpoint the bare class "custom", which+ # agent_init treats as non-routable. Only restore an explicit provider; else resume uses the configured default.provider = field("provider")billing_provider = str(model_config.get("billing_provider") or row.get("billing_provider") or "").strip()if not provider and billing_provider.lower() not in _BARE_BILLING_PROVIDERS:provider = billing_providerbase_url, api_mode, service_tier = field("base_url"), field("api_mode"), field("service_tier")reasoning_config = model_config.get("reasoning_config")- # Heal a stale provider name persisted by an older build (renamed/removed custom provider →- # "Unknown provider"): recover the durable ``custom:<name>`` key from the stored base_url, then- # from the entry serving the stored model; when nothing names a real entry, drop the provider.+ # Heal a stale provider persisted by an older build (renamed/removed custom provider → "Unknown provider"):+ # recover ``custom:<name>`` from the stored base_url, then from the entry serving the model; else drop it.if provider and not _is_routable_provider(provider):healed = Nonetry:@@ -1538,11 +1464,10 @@ def _stored_session_runtime_overrides(row: dict | None) -> dict:else:provider = ""if model:- # Same dict-shaped override live /model switches use, so a DB-restored session keeps custom- # endpoint metadata across resume and rebuilds (/new). Raw api_key is never persisted/restored.+ # Same dict-shaped override live /model switches use, so a DB-restored session keeps custom endpoint+ # metadata across resume and rebuilds (/new). Raw api_key is never persisted/restored.overrides["model_override"] = {- "model": model, "provider": provider or None, "base_url": base_url or None, "api_mode": api_mode or None,- }+ "model": model, "provider": provider or None, "base_url": base_url or None, "api_mode": api_mode or None}if provider:overrides["provider_override"] = providerif isinstance(reasoning_config, dict):@@ -1556,18 +1481,15 @@ def _stored_session_runtime_overrides(row: dict | None) -> dict:def _runtime_model_config(agent, existing: dict | None = None) -> dict:- """Merge the agent's CURRENT runtime identity onto the row's persisted ``model_config``.- Falsy agent attributes DELETE the key rather than skip the write, so a stale value can never- survive the merge: ``_persist_live_session_runtime`` writes the model column separately and- resume reads provider/endpoint from this JSON — a stale provider would silently route the- resumed chat to the wrong endpoint while the model column claimed the new one."""+ """Merge the agent's CURRENT runtime identity onto the row's persisted ``model_config``. Falsy agent+ attributes DELETE the key rather than skip the write: resume reads provider/endpoint from this JSON+ (model column written separately), so a stale provider would route the resumed chat to the wrong endpoint."""config = dict(existing or {})attr = lambda k: str(getattr(agent, k, "") or "").strip()model, provider, base_url = attr("model"), attr("provider"), attr("base_url")if provider.lower() == "custom":- # ``agent.provider`` resolves every named custom entry to the literal "custom", losing the- # entry identity (api_key is never persisted, so resume couldn't re-resolve credentials).- # Recover the canonical ``custom:<name>`` key from the endpoint URL, else the configured provider.+ # ``agent.provider`` resolves every named custom entry to the literal "custom", losing the entry+ # identity (api_key is never persisted): recover ``custom:<name>`` from the endpoint URL.try:from hermes_cli.runtime_provider import canonical_custom_identityprovider = canonical_custom_identity(base_url=base_url, model=model or None) or provider@@ -1598,8 +1520,7 @@ def _persist_live_session_runtime(session: dict | None) -> None:row = db.get_session(session_key) or {}model_config = _runtime_model_config(agent, _parse_model_config(row.get("model_config")))if (tier_override := session.get("create_service_tier_override")) is not None:- # _runtime_model_config sees agent.service_tier=None for explicit normal and would- # otherwise erase the distinction on every live metadata persist.+ # agent.service_tier is None for explicit normal; without this the distinction is erased on every persist.model_config["service_tier"] = tier_override or "normal"model = str(getattr(agent, "model", "") or "").strip()if hasattr(db, "update_session_meta"):@@ -1630,10 +1551,8 @@ def _persist_live_session_system_prompt(session: dict | None) -> None:agent, session_key, db = liveif not hasattr(agent, "_build_system_prompt") or not hasattr(db, "update_system_prompt"):return-- # Re-bind HERMES_HOME to the session's profile (the build's finally reset it; the rebuilt- # prompt would use the root profile's SOUL.md/skills) and the session context (on the RPC- # thread _SESSION_CWD is unset, so the prompt would persist the process TERMINAL_CWD).+ # Re-bind the session's profile HERMES_HOME (the build's finally reset it → root profile's SOUL.md/skills)+ # and session context (on the RPC thread _SESSION_CWD is unset → the process TERMINAL_CWD would persist).profile_home = session.get("profile_home")home_token = set_hermes_home_override(profile_home) if profile_home else Nonesession_tokens = _set_session_context(session_key, cwd=_session_cwd(session))@@ -1661,28 +1580,23 @@ def _is_model_switch_marker(entry: Any) -> bool:def _is_pivot_marker(entry: Any) -> bool:- """Whether a history entry is a ``role=user`` pivot the gateway splices in mid-turn (model switch- or personality change) — either can be the sole reason turn-start and current history differ.- Only the model-switch marker is self-replacing, so :func:`_append_model_switch_marker` dedups narrower."""+ """A ``role=user`` pivot the gateway splices in mid-turn (model switch or personality change) — either can+ be the sole reason turn-start and current history differ. Only the model-switch marker is self-replacing."""return _is_model_switch_marker(entry) or (isinstance(entry, dict) and entry.get("display_kind") == "personality_switch")def _append_model_switch_marker(session: dict | None, *, model: str, provider: str) -> None:- """Record a real system-history pivot after a live model switch.- Only the newest marker is kept: each switch strips prior model-switch markers first, so N- switches leave one marker rather than N stale ones re-sent on every API call; self-healing- across resumes because the next switch collapses whatever a reload brought back."""- if not session:- return- session_key = str(session.get("session_key") or "").strip()+ """Record a real system-history pivot after a live model switch. Only the newest marker is kept (each+ switch strips prior ones, so N switches leave one marker, not N re-sent every API call; self-healing+ across resumes because the next switch collapses whatever a reload brought back)."""+ session_key = str((session or {}).get("session_key") or "").strip()if not session_key:returnprovider_part = f" via provider {provider}" if provider else ""marker = (f"{_MODEL_SWITCH_MARKER_PREFIX}{model}{provider_part}. From this point forward, use this runtime ""metadata when answering questions about what model/provider is active.]")- # A user message, not system: strict OpenAI-compatible providers (vLLM, Qwen) reject- # non-leading system messages.+ # A user message, not system: strict OpenAI-compatible providers (vLLM, Qwen) reject non-leading system messages.entry = {"role": "user", "content": marker, "display_kind": "model_switch"}with session.get("history_lock") or contextlib.nullcontext():history = session.setdefault("history", [])@@ -1704,8 +1618,7 @@ def _append_model_switch_marker(session: dict | None, *, model: str, provider: sdef _write_config_key(key_path: str, value):- # Write-back round-trip: raw read is mandatory — saving the managed-overlaid / env-expanded- # view would persist those values into the file.+ # Write-back round-trip: raw read is mandatory — saving the overlaid/expanded view would persist it.cfg = current = _load_cfg_raw()*parents, leaf = key_path.split(".")for key in parents:@@ -1719,9 +1632,8 @@ def _write_config_key(key_path: str, value):_STATUSBAR_MODES = frozenset({"off", "top", "bottom"})_APPROVAL_MODES = frozenset({"manual", "smart", "off"})-# Appearance switches the renderer owns but the AGENT must see (each gates a tool's `check_fn`),-# so the toggle must reach whichever gateway the app talks to. `config.set` answers 4002 for-# unlisted keys — a mirrored switch missing here writes nothing and its tool stays dark.+# Appearance switches the renderer owns but the AGENT must see (each gates a tool's `check_fn`). `config.set`+# answers 4002 for unlisted keys — a mirrored switch missing here writes nothing and its tool stays dark._DISPLAY_TOGGLE_KEYS = frozenset({"display.message_reactions", "display.in_app_tips", "display.in_app_tours"})_BOOL_WORDS = {"1": True, "on": True, "true": True, "yes": True, "0": False, "off": False, "false": False, "no": False,@@ -1729,8 +1641,8 @@ _BOOL_WORDS = {def _load_approval_mode() -> str:- """Effective ``approvals.mode`` via ``tools.approval._get_approval_mode`` so it cannot drift from- the gate's own view (a raw-config re-read missed the managed overlay and ``${VAR}`` expansion)."""+ """Effective ``approvals.mode`` via the gate's own ``_get_approval_mode`` (a raw re-read missed the+ managed overlay and ``${VAR}`` expansion)."""from tools.approval import _get_approval_modemode = _get_approval_mode()return mode if mode in _APPROVAL_MODES else "manual"@@ -1750,9 +1662,8 @@ _MOUSE_TRACKING_ALIASES = {def _display_mouse_tracking(display: dict) -> str:- """display.mouse_tracking → ``off|wheel|buttons|all``. Booleans keep their legacy meaning- (True → all, False → off); ``wheel`` (DEC 1000+1006) is the tmux-friendly subset without hover- events that trigger prompt-row clipboard probes. Legacy ``tui_mouse`` only when ``mouse_tracking`` is absent."""+ """display.mouse_tracking → ``off|wheel|buttons|all`` (bools: True → all, False → off); ``wheel`` (DEC+ 1000+1006) is the tmux-friendly subset without hover events. Legacy ``tui_mouse`` only when ``mouse_tracking`` is absent."""if not isinstance(display, dict):return "all"raw = display.get("mouse_tracking") if "mouse_tracking" in display else display.get("tui_mouse", True)@@ -1764,8 +1675,8 @@ def _display_mouse_tracking(display: dict) -> str:def _load_reasoning_config(model: str = "") -> dict | None:- """Reasoning effort via the shared chokepoint :func:`hermes_constants.resolve_reasoning_config`- (per-model override > global ``agent.reasoning_effort``; YAML False = disabled)."""+ """Via the shared chokepoint :func:`hermes_constants.resolve_reasoning_config` (per-model override >+ global ``agent.reasoning_effort``; YAML False = disabled)."""from hermes_constants import resolve_reasoning_configreturn resolve_reasoning_config(_load_cfg(), model)@@ -1779,8 +1690,7 @@ def _load_service_tier() -> str | None:def _load_provider_routing() -> dict:- """OpenRouter ``provider_routing`` prefs (gateway/CLI parity — without them OpenRouter picks an- effectively random provider even when the user configured routing)."""+ """OpenRouter ``provider_routing`` prefs (gateway/CLI parity — without them OpenRouter picks an effectively random provider)."""try:return _load_cfg().get("provider_routing", {}) or {}except Exception:@@ -1793,8 +1703,8 @@ def _load_show_reasoning() -> bool:def _load_memory_notifications() -> str:- """``display.memory_notifications`` (``off`` / ``on`` default / ``verbose``; bool normalized) — gates- the "💾 Self-improvement review" summary, gateway/CLI parity (this backend used to ignore ``off``)."""+ """``display.memory_notifications`` (``off`` / ``on`` default / ``verbose``; bool normalized) — gates the+ "💾 Self-improvement review" summary (gateway/CLI parity)."""raw = _display_cfg().get("memory_notifications")if isinstance(raw, bool):return "on" if raw else "off"@@ -1818,9 +1728,9 @@ def _load_tool_progress_mode() -> str:def _gui_surface_toolsets(platform: str) -> set[str]:- """Toolsets that exist because of the CLIENT, not the host — both off ``_HERMES_CORE_TOOLS``, so this- is the one gate exposing them. ``platform`` is the SESSION's source, never a process env var: the- desktop may drive a URL/cloud backend where ``HERMES_DESKTOP`` is unset (see AGENTS.md surface rule)."""+ """Toolsets that exist because of the CLIENT (both off ``_HERMES_CORE_TOOLS``; this is the one gate).+ ``platform`` is the SESSION's source, never a process env var: the desktop may drive a URL/cloud+ backend where ``HERMES_DESKTOP`` is unset (AGENTS.md surface rule)."""return {"project", "desktop_ui"} if platform == "desktop" else {"project"}@@ -1876,11 +1786,9 @@ def _resolve_explicit_toolsets(explicit: list[str], validate_toolset) -> list[stdef _load_enabled_toolsets(platform: str | None = None) -> list[str] | None:- """The agent's toolsets for this desktop/TUI session (None = all).- Order: an explicit HERMES_TUI_TOOLSETS pin; else the coding posture (agent/coding_context.py- collapses to the coding toolset + enabled MCP servers inside a code workspace); else the- configured CLI toolsets. The client-surface (pane/project) toolsets are folded in here because- this resolver runs only on the surface that can answer them."""+ """The agent's toolsets for this session (None = all): an explicit HERMES_TUI_TOOLSETS pin; else the+ coding posture (coding_context collapses to coding toolset + enabled MCP servers in a code workspace);+ else the configured CLI toolsets. Client-surface toolsets fold in here — only this surface can answer them."""session_platform = platform or _resolve_session_platform()explicit = [item.strip() for item in os.environ.get("HERMES_TUI_TOOLSETS", "").split(",") if item.strip()]fallback_notice = None@@ -1911,9 +1819,7 @@ def _load_enabled_toolsets(platform: str | None = None) -> list[str] | None:return sorted(enabled | _gui_surface_toolsets(session_platform)) if enabled else Noneexcept Exception:if fallback_notice is not None:- _tui_notice(- "[tui] no valid HERMES_TUI_TOOLSETS entries and configured CLI toolsets could not be loaded; enabling all toolsets"- )+ _tui_notice("[tui] no valid HERMES_TUI_TOOLSETS entries and configured CLI toolsets could not be loaded; enabling all toolsets")return None@@ -1930,8 +1836,7 @@ def _tool_progress_enabled(sid: str) -> bool:def _tool_lifecycle_required_for_ui(name: str) -> bool:- """Tool events that are interactive UI, not optional chrome: Desktop renders clarify / setup_mcp- cards from the tool-call part; suppressing them with progress off would leave only the sidebar dot."""+ """Interactive UI, not optional chrome: Desktop renders clarify / setup_mcp cards from the tool-call part."""return name in ("clarify", "setup_mcp")@@ -1947,8 +1852,7 @@ def _restart_slash_worker(sid: str, session: dict):except Exception:session["slash_worker"] = Nonereturn- # Store-iff-still-mapped: the post-turn restart races a close_on_disconnect reap, and a- # bare store would orphan the fresh worker.+ # Store-iff-still-mapped: the post-turn restart races a close_on_disconnect reap (a bare store would orphan it)._attach_worker(sid, session, new_worker)@@ -1964,10 +1868,9 @@ def _get_usage(agent) -> dict:}comp = getattr(agent, "context_compressor", None)if comp:- # context_used is *current-window* occupancy. Never fall back to usage["total"] (cumulative- # lifetime: an external engine without last_prompt_tokens showed 1.9m/120k clamped to 100%).- # A falsy last_prompt_tokens emits NO gauge rather than a fabricated one; the -1 "compression- # just ran" sentinel is clamped to 0 (matches cli.py _get_status_bar_snapshot).+ # context_used is *current-window* occupancy — never usage["total"] (cumulative: an external engine+ # showed 1.9m/120k clamped to 100%). Falsy last_prompt_tokens emits NO gauge; the -1 "compression+ # just ran" sentinel clamps to 0 (matches cli.py _get_status_bar_snapshot).last_prompt = max(0, getattr(comp, "last_prompt_tokens", 0) or 0)ctx_max = getattr(comp, "context_length", 0) or 0if ctx_max and last_prompt:@@ -1975,9 +1878,8 @@ def _get_usage(agent) -> dict:context_used=last_prompt, context_max=ctx_max,context_percent=max(0, min(100, round(last_prompt / ctx_max * 100))))usage["compressions"] = getattr(comp, "compression_count", 0) or 0- # Cache-hit ratio + rolling latency/tps (CLI status-bar parity): hit = cache_read / prompt_tokens;- # latency/tps read the per-call deque history. Omitted, not fabricated, when there is no data- # (Codex reports no latency; zero cache reads shows no hit% rather than an alarming 0).+ # Cache-hit ratio + rolling latency/tps (CLI status-bar parity). Omitted, not fabricated, when there is no+ # data (Codex reports no latency; zero cache reads shows no hit% rather than an alarming 0).with contextlib.suppress(Exception):_prompt_total = int(getattr(agent, "session_prompt_tokens", 0) or 0)_cache_read = int(getattr(agent, "session_cache_read_tokens", 0) or 0)@@ -2010,8 +1912,7 @@ def _get_usage(agent) -> dict:def _probe_credentials(agent) -> str:- """Light credential check at session creation — warning or ''. (``no-key-required`` is a valid- sentinel for keyless custom providers; only a genuinely missing key warns.)"""+ """Warning or '' (``no-key-required`` is a valid sentinel for keyless custom providers)."""with contextlib.suppress(Exception):if not (getattr(agent, "api_key", "") or ""):provider = getattr(agent, "provider", "") or ""@@ -2020,8 +1921,7 @@ def _probe_credentials(agent) -> str:def _probe_config_health(cfg: dict) -> str:- """Flag bare YAML keys (`agent:` with no value → None) that silently drop nested settings,- and a ``display.personality`` naming no known overlay. Returns warning or ''."""+ """Warn on bare YAML keys (`agent:` → None, silently dropping nested settings) and an unknown ``display.personality``."""if not isinstance(cfg, dict):return ""warnings: list[str] = []@@ -2052,11 +1952,10 @@ def _current_profile_name() -> str:return "default"-# Monotonic GUI<->backend contract version: the desktop refuses a backend reporting less (or none)-# with a one-click "update to align" prompt. Bump whenever the desktop's backend contract changes.-# v2 file.attach RPC; v3 approvals.mode RPCs + session.info reconciliation; v4 session.create-# fast=false = explicit normal-tier override; v5 ws_max_size raised for >16 MiB file.attach frames;-# v6 plugins.manage rows carry the canonical registry key (toggles key-addressed).+# Monotonic GUI<->backend contract version: the desktop refuses a backend reporting less (or none) with a+# one-click "update to align" prompt; bump whenever the desktop's backend contract changes. v2 file.attach;+# v3 approvals.mode RPCs + session.info reconciliation; v4 session.create fast=false = explicit normal tier;+# v5 ws_max_size >16 MiB file.attach frames; v6 plugins.manage rows carry the canonical registry key.DESKTOP_BACKEND_CONTRACT = 6@@ -2071,9 +1970,8 @@ def _session_usage_snapshot(session: dict | None) -> dict:def _project_info_for_cwd(cwd: str) -> dict | None:- """The first-class Project owning ``cwd`` (per-profile projects.db, the store the desktop's project- tree caches) so TUI status, desktop status bar and ``/status`` name the workspace identically.- Only explicit named projects resolve; an auto-discovered repo root falls back to the cwd leaf."""+ """The first-class Project owning ``cwd`` (per-profile projects.db) so TUI status, desktop status bar and+ ``/status`` name the workspace identically. Only explicit named projects resolve."""if not str(cwd or "").strip():return Nonetry:@@ -2089,8 +1987,7 @@ def _project_info_for_cwd(cwd: str) -> dict | None:def _turn_started_at(session: dict | None) -> float | None:- """Epoch seconds the current turn started, or None when idle — lets the desktop keep the- turn-elapsed timer across session switches (cold resume) instead of resetting to 0:00."""+ """Epoch seconds the current turn started, or None when idle (desktop keeps the elapsed timer across switches)."""inflight = (session or {}).get("inflight_turn")return float(inflight["started_at"]) if isinstance(inflight, dict) and inflight.get("started_at") else None@@ -2106,8 +2003,7 @@ def _session_info(agent, session: dict | None = None) -> dict:reasoning_config = getattr(agent, "reasoning_config", None)reasoning_effort = ""if isinstance(reasoning_config, dict):- # Disabled must differ from unset ("" = provider default), or the desktop adopts "" after- # the first turn and loses "thinking off".+ # Disabled must differ from unset ("" = provider default) or the desktop loses "thinking off" after turn 1.reasoning_effort = "none" if reasoning_config.get("enabled") is False else str(reasoning_config.get("effort", "") or "")service_tier = getattr(agent, "service_tier", None) or mirror.get("service_tier") or ""# yolo ORs the same three sources check_all_command_guards() does (approvals.mode=off, the process@@ -2119,8 +2015,8 @@ def _session_info(agent, session: dict | None = None) -> dict:yolo = bool(_YOLO_MODE_FROZEN) or session_yolo or approval_mode == "off"except Exception:yolo, approval_mode = False, "manual"- # A switch queued mid-turn applies at the next turn start, so agent.model still reads the OLD- # model; report the pending pick so the end-of-turn settle doesn't blip the UI back first.+ # A switch queued mid-turn applies at next turn start (agent.model still reads the OLD model); report the+ # pending pick so the end-of-turn settle doesn't blip the UI back first.pending_switch = sess.get("pending_model_switch") or {}pending_model = str(pending_switch.get("display_model") or "").strip()pending_provider = str(pending_switch.get("display_provider") or "").strip()@@ -2175,9 +2071,8 @@ def _session_info(agent, session: dict | None = None) -> dict:def _tool_ctx(name: str, args: dict) -> str:- """Argument preview for a tool row — never a phrased label: clients own their phrasing (the TUI- wraps it as ``Terminal("...")``, the desktop prepends a localized verb), so ``build_tool_label``- here would stutter ("Running Running …") and leak a display label into the desktop's ``args.context``."""+ """Argument preview for a tool row — never a phrased label: clients own their phrasing, so+ ``build_tool_label`` here would stutter ("Running Running …") and leak into the desktop's ``args.context``."""try:from agent.display import build_tool_previewreturn build_tool_preview(name, args, max_len=80) or ""@@ -2194,8 +2089,7 @@ def _emit_session_info_for_session(sid: str, session: dict) -> None:def broadcast_session_info() -> None:"""Re-emit ``session.info`` to every live session — for approvals-config writers that bypass the- self-re-emitting ``config.set`` RPC (REST config saves, the ``/approvals`` slash mirror). Only- reaches THIS process; a spawned ``tui_gateway.entry`` child gateway has its own ``_sessions``."""+ self-re-emitting ``config.set`` RPC. Only THIS process; a spawned child gateway has its own ``_sessions``."""with _sessions_lock:sessions = list(_sessions.items())for sid, sess in sessions:@@ -2203,12 +2097,10 @@ def broadcast_session_info() -> None:def _schedule_mcp_late_refresh(sid: str, agent) -> None:- """Refresh a session's tool snapshot when MCP discovery lands late.- ``_make_agent`` waits only a bounded ``mcp_discovery_timeout``, so a slow server (HTTP MCP on- first connect) lands after the build and its tools are missing all session. A daemon joins- discovery, then does the same rebuild ``/reload-mcp`` performs and re-emits ``session.info``.- Cache safety: only while pre-first-turn (nothing cached to invalidate); afterwards the snapshot- stays frozen and late tools need an explicit, consent-gated ``/reload-mcp``."""+ """Refresh a session's tool snapshot when MCP discovery lands late (``_make_agent`` waits only a bounded+ ``mcp_discovery_timeout``, so a slow server's tools would be missing all session): a daemon joins discovery,+ rebuilds like ``/reload-mcp`` and re-emits ``session.info``. Only pre-first-turn (nothing cached to+ invalidate); afterwards late tools need an explicit, consent-gated ``/reload-mcp``."""try:from tui_gateway.entry import mcp_discovery_in_flight, join_mcp_discoveryexcept Exception:@@ -2217,8 +2109,7 @@ def _schedule_mcp_late_refresh(sid: str, agent) -> None:returndef _wait_then_refresh() -> None:- # Bounded but generous — a server still not connected after this is genuinely slow/dead.- if not join_mcp_discovery(timeout=30.0):+ if not join_mcp_discovery(timeout=30.0): # a server still not connected after this is genuinely slow/deadreturnwith _sessions_lock:session = _sessions.get(sid)@@ -2246,10 +2137,8 @@ class _RuntimeFallbackResolution(NamedTuple):def _resolve_runtime_with_fallback(resolve_kwargs: dict | None = None) -> _RuntimeFallbackResolution:- """Resolve the primary runtime or one complete provider/model fallback.- Setup-time auth fallback only accepts entries with both fields: provider-only entries are- skipped so the unavailable primary model can never leak into a different runtime.- ``used_fallback`` stays explicit rather than overloading a nullable model as control flow."""+ """Resolve the primary runtime or one complete provider/model fallback. Provider-only fallback entries+ are skipped so the unavailable primary model can never leak into a different runtime."""from hermes_cli.auth import AuthErrorfrom hermes_cli.runtime_provider import resolve_runtime_providertry:@@ -2279,14 +2168,10 @@ def _resolve_runtime_with_fallback(resolve_kwargs: dict | None = None) -> _Runtidef _resolve_agent_model_runtime(model_override, provider_override) -> tuple[str, dict]:- """(model, runtime) for a new agent; a per-session override (in-session /model switch or a- resumed row's persisted runtime) wins over global config/env.-- Rows persisted before the custom-provider identity fix stored the resolved provider "custom",- which no named ``providers:`` entry matches — recover the identity from the persisted base_url- or the rebuild surfaces as "No LLM provider configured". Persisted base_url/api_key/api_mode are- honored only while the original runtime is used; they must not leak into a fallback pair.- """+ """(model, runtime) for a new agent; a per-session override (/model switch or a resumed row's persisted+ runtime) wins over global config/env. Older rows stored the resolved provider "custom" (no named entry+ matches) — recover the identity from the persisted base_url or the rebuild fails "No LLM provider+ configured". Persisted base_url/api_key/api_mode are honored only for the original runtime, never a fallback."""if isinstance(model_override, dict) and model_override.get("model"):model = str(model_override.get("model") or "")requested_provider = model_override.get("provider") or provider_override or None@@ -2297,8 +2182,7 @@ def _resolve_agent_model_runtime(model_override, provider_override) -> tuple[strif recovered := canonical_custom_identity(base_url=override_base_url or None, model=model or None):requested_provider = recoveredif override_base_url:- # Failing identity recovery, still hand the base_url to the direct-alias branch so- # pool/env credentials resolve for it.+ # Failing identity recovery, still hand base_url to the direct-alias branch so pool/env credentials resolve.resolve_kwargs["explicit_base_url"] = override_base_urlresolve_kwargs.update(requested=requested_provider, target_model=model or None)overrides = {k: model_override.get(k) for k in ("base_url", "api_key", "api_mode")}@@ -2320,8 +2204,8 @@ def _resolve_agent_model_runtime(model_override, provider_override) -> tuple[strdef _startup_system_prompt(cfg: dict, task_id: str) -> str:- """Config ephemeral system prompt + the HERMES_TUI_SKILLS preload block. Hard-fails only when EVERY- requested skill is missing (cli.py parity): a typo'd name must not auto-block the Kanban task."""+ """Config ephemeral system prompt + HERMES_TUI_SKILLS preload block. Hard-fails only when EVERY requested+ skill is missing (cli.py parity): a typo'd name must not auto-block the Kanban task."""from hermes_cli.config import resolve_ephemeral_system_prompt_from_configsystem_prompt = resolve_ephemeral_system_prompt_from_config(cfg)startup_skills = _parse_tui_skills_env()@@ -2353,9 +2237,8 @@ def _make_agent(if synthetic is not None:return syntheticfrom run_agent import AIAgent- # MCP discovery runs in a background daemon thread so a dead server can't freeze the shell; the- # agent snapshots its tool list once, so briefly (bounded) wait for in-flight discovery.- # Dashboard /api/ws uses hermes_cli.mcp_startup; TUI stdio keeps the tui_gateway.entry thread.+ # MCP discovery runs in a daemon thread (a dead server can't freeze the shell); the agent snapshots its tool+ # list once, so briefly wait for in-flight discovery. Dashboard /api/ws uses mcp_startup; TUI stdio uses entry.for _mod in ("hermes_cli.mcp_startup", "tui_gateway.entry"):with contextlib.suppress(Exception):importlib.import_module(_mod).wait_for_mcp_discovery()@@ -2402,9 +2285,8 @@ def _hydrate_session_cwd(sid: str, key: str, session_db, profile_home: str | Nondb = _open_profile_session_db(profile_home)owns_db = Trueexcept Exception:- # FAIL CLOSED (same class as the deferred-build bind): a named-profile session must never- # touch the launch state.db — skip cwd hydration (the row lands on the agent's own- # lazy-create once the store recovers).+ # FAIL CLOSED (as the deferred-build bind): a named-profile session must never touch the launch+ # state.db — skip hydration (the row lands on the agent's own lazy-create once the store recovers).logger.warning("profile session store unavailable for %s — skipping cwd ""hydration instead of touching the launch state.db",@@ -2441,11 +2323,9 @@ def _init_session("explicit_cwd": bool(explicit_cwd), "cols": cols, "slash_worker": None,"show_reasoning": _load_show_reasoning(), "source": _resolve_session_source(source),"tool_progress_mode": _load_tool_progress_mode(), "edit_snapshots": {}, "tool_started_at": {},- # Profile-scoped HERMES_HOME (None = launch profile); SessionBranch copies the parent's- # so the child stays on the same state.db.+ # Profile-scoped HERMES_HOME (None = launch); SessionBranch copies the parent's (same state.db)."profile_home": profile_home,- # In-session /model switch, honored on rebuild (/new, resume) so it never leaks into- # siblings via process-global env vars.+ # In-session /model switch, honored on rebuild (/new, resume) — never leaks to siblings via env vars."model_override": None,# Async events go to the transport that created the session (stdio for Ink, WS for the dashboard)."transport": current_transport() or _stdio_transport,@@ -2532,23 +2412,21 @@ def _live_profile_matches(session: dict, profile_home) -> bool:def _claim_or_reuse_live(sid: str, session_key: str, record: dict, lease) -> tuple[str, dict] | None:"""Register ``record`` as the live session for ``session_key`` under the resume lock, or — if aconcurrent resume already won — release ``lease`` and return the winner for the caller to reuse."""- # The record carries the home this resume resolved; a live runtime of the same stored id under- # ANOTHER profile is not a winner to reuse.+ # A live runtime of the same stored id under ANOTHER profile is not a winner to reuse.profile_home = record.get("profile_home")with _session_resume_lock:live = _find_live_session_by_key(session_key, profile_home)if live is not None:if lease is not None:lease.release()- # The winner is being reattached by this resume: a pending ws-orphan reap must not- # fire against the reclaimed client (storm killer — see _cancel_ws_orphan_reap).+ # The winner is being reattached: a pending ws-orphan reap must not fire against the reclaimed client._cancel_ws_orphan_reap(live[0])return livewith _sessions_lock:_sessions[sid] = record_register_session_cwd(_sessions[sid])- # A PRIOR runtime for this stored id may still be sentinel-parked with a reap Timer armed;- # cancel + finalize it quietly so the reap doesn't broadcast session.reclaimed (storm).+ # A PRIOR runtime for this stored id may still be sentinel-parked with a reap Timer armed; cancel ++ # finalize it quietly so the reap doesn't broadcast session.reclaimed (storm)._cancel_ws_orphan_reap(sid)stale = _claim_parked_runtimes(session_key, keep_sid=sid, profile_home=profile_home)_finalize_superseded_runtimes(stale) # slow finalization stays OUTSIDE _session_resume_lock@@ -2556,10 +2434,8 @@ def _claim_or_reuse_live(sid: str, session_key: str, record: dict, lease) -> tupdef _claim_parked_runtimes(session_key: str, *, keep_sid: str, profile_home=_ANY_PROFILE) -> list[tuple[str, dict]]:- """Claim sentinel-parked stale runtimes of ``session_key`` for supersession: older records for the- same stored id still parked on the detached-WS sentinel get their orphan-reap Timer cancelled and- are popped from ``_sessions`` here (under the caller's _session_resume_lock), then finalized by- :func:`_finalize_superseded_runtimes` after the lock is released."""+ """Claim sentinel-parked stale runtimes of ``session_key`` for supersession: cancel their orphan-reap+ Timer and pop them here (under the caller's _session_resume_lock); the caller finalizes after release."""stale: list[tuple[str, dict]] = []with _sessions_lock:candidates = [@@ -2575,10 +2451,8 @@ def _claim_parked_runtimes(session_key: str, *, keep_sid: str, profile_home=_ANYdef _finalize_superseded_runtimes(stale: list[tuple[str, dict]]) -> None:- """Quietly finalize runtimes claimed by :func:`_claim_parked_runtimes` with end_reason- ``superseded_by_resume`` — deliberately NOT in _RECLAIM_END_REASONS (no ``session.reclaimed``- broadcast, which fed the reap->broadcast->resume loop) but IN _RECOVERABLE_END_REASONS so- canonical Bot Chat resurrection still applies."""+ """end_reason ``superseded_by_resume`` is deliberately NOT in _RECLAIM_END_REASONS (no ``session.reclaimed``+ broadcast → no reap->broadcast->resume loop) but IN _RECOVERABLE_END_REASONS (Bot Chat resurrection applies)."""for old_sid, popped in stale:try:_teardown_popped_session(popped, end_reason="superseded_by_resume")@@ -2598,9 +2472,8 @@ def _schedule_agent_build(sid: str, delay: float = 0.05) -> None:def _load_resume_transcript(db, stored_id: str) -> tuple[list, list, list]:- """(raw_history, display_history, ancestor_prefix) for a cold resume.- The ancestor prefix is an in-memory convenience (the transcript is REST-paginated): the full- lineage is materialized only while it fits sessions.max_resume_messages, else the tip alone."""+ """(raw_history, display_history, ancestor_prefix) for a cold resume. The full lineage is materialized+ only while it fits sessions.max_resume_messages (the transcript is REST-paginated), else the tip alone."""from hermes_state import SessionResumeTooLargeErrorprefix_fits = Trueguard = getattr(db, "assert_resume_safe", None)@@ -2638,8 +2511,7 @@ def _schedule_resume_hydration(sid: str, stored_id: str, db, *, close_db: bool =with session["history_lock"]:session.update(history=history, display_history_prefix=prefix, resume_hydrating=False,resume_message_count=len(display_history))- # Deferred resumes answered before the transcript existed; cache the derived todo- # snapshot now so later payload attaches carry it.+ # Deferred resumes answered before the transcript existed; cache the derived todo snapshot now.todo_state = _todo_state_from_history(history)if todo_state is not None and session.get("todo_state") is None:session["todo_state"] = todo_state@@ -2740,9 +2612,8 @@ def _fallback_session_info(session: dict) -> dict:agent = session.get("agent")if agent is not None:return _session_info(agent)- # The SESSION's own workspace, not the gateway launch dir (that painted the wrong project in the- # desktop Files pane). `branch` is always emitted ("" outside git) so a client clears a stale label.- # `desktop_contract`: a lazy session is still served by THIS backend; missing reads as 0 = "out of date".+ # The SESSION's own workspace, not the launch dir (wrong project in the desktop Files pane). `branch` is+ # always emitted ("" outside git) so a stale label clears; `desktop_contract` missing reads as "out of date".cwd = _session_cwd(session)return {"cwd": cwd, "branch": _git_branch_for_cwd(cwd), "project": _project_info_for_cwd(cwd), "lazy": True,@@ -2751,13 +2622,11 @@ def _fallback_session_info(session: dict) -> dict:def _reconcile_display_with_live(db_display: list[dict], in_memory: list[dict]) -> list[dict]:- """Merge the persisted DISPLAY lineage with the in-memory live history.- ``db_display`` is verbatim and candidate-inclusive (verification rows the model history collapses- out via ``repair_message_sequence``) but can lag the newest turn by a flush; ``in_memory``- (``display_history_prefix + session["history"]``) is the recency authority but the collapsed- *model* projection. Keep the DB display as base and append only the in-memory tail past the- last DB row's ``(role, text)`` anchor, so the verification answer survives a warm switch AND- a not-yet-flushed live turn is not dropped."""+ """Merge the persisted DISPLAY lineage with the in-memory live history: ``db_display`` is verbatim and+ candidate-inclusive (verification rows the model history collapses out) but can lag by a flush;+ ``in_memory`` is the recency authority but the collapsed *model* projection. Keep the DB display as base,+ append only the in-memory tail past the last DB row's ``(role, text)`` anchor — the verification answer+ survives a warm switch AND a not-yet-flushed live turn is kept."""if not db_display:return in_memoryif not in_memory:@@ -2776,9 +2645,8 @@ def _reconcile_display_with_live(db_display: list[dict], in_memory: list[dict])def _live_visible_history(session: dict, db, in_memory_fallback: list[dict]) -> list[dict]:- """User-visible DISPLAY projection for a live/warm session: the persisted display lineage (same- read as resume/REST, so the two payloads agree — "substantive answer vanishes on switch")- reconciled with the fresh in-memory tail; in-memory when the DB/session_key is unavailable."""+ """User-visible DISPLAY projection for a live/warm session: the persisted display lineage (same read as+ resume/REST so the payloads agree) reconciled with the in-memory tail; in-memory when the DB is unavailable."""key = session.get("session_key")if db is not None and key:try:@@ -2800,8 +2668,8 @@ def _live_session_payload(session["cols"] = colsif transport is not None:session["transport"] = transport- # Every transport that has shown this session (pop-out windows resume the same sid);- # the last viewer becomes the transport on disconnect instead of the drop sentinel.+ # Every transport that showed this session (pop-outs resume the same sid); on disconnect the last+ # viewer becomes the transport instead of the drop sentinel.session.setdefault("viewers", {})[transport] = time.time()if transport is not _detached_ws_transport:_cancel_ws_orphan_reap(sid) # the client is back — a pending ws-orphan reap must not fire@@ -2810,9 +2678,8 @@ def _live_session_payload(in_memory_history = list(session.get("display_history_prefix") or []) + list(session.get("history") or [])inflight, queued = _inflight_snapshot(session), _queued_prompt_snapshot(session)running, turn_started_at = bool(session.get("running")), _turn_started_at(session)- # Persisted display lineage (candidate-inclusive) so this matches resume + REST; via the session's- # profile-aware DB, not the launch ``_get_db()``. The DB has its own lock — read outside the- # history lock. ``omit_messages`` skips the read entirely (fast path for counts/status).+ # Persisted display lineage via the session's profile-aware DB (not the launch ``_get_db()``), read+ # outside the history lock (the DB has its own). ``omit_messages`` skips the read (fast path).if omit_messages:history = in_memory_historyelse:@@ -2835,8 +2702,7 @@ def _live_session_payload(def _main_runtime_from_agent(agent) -> dict | None:- """Aux-client main_runtime override from a live agent, so a one-shot inherits the session's- provider/model/credentials instead of the cheapest auto-detected backend."""+ """Aux-client main_runtime override from a live agent, so a one-shot inherits the session's runtime."""if agent is None:return Noneruntime: dict = {}@@ -2967,8 +2833,7 @@ def _pet_active_selection():def _pet_state_rows(spritesheet) -> list[str]:- """Row taxonomy for the concrete active pet sheet (legacy 8-row petdex atlas or current 9-row- atlas); the desktop canvas indexes it with the same `PetState` names the Python renderer uses."""+ """Row taxonomy for the concrete sheet (legacy 8-row or current 9-row atlas), in the renderer's `PetState` names."""from agent.pet import constantstry:from PIL import Image@@ -3010,8 +2875,8 @@ def _pet_png_data_uri(path, *, max_px: int = 160) -> str:return "data:image/png;base64," + base64.standard_b64encode(buf.getvalue()).decode("ascii")-# Cooperative cancellation for pet generation: Stop aborts the RPC, but the pool job keeps-# running unless pet.cancel flips its token (polled between provider calls).+# Cooperative cancellation for pet generation: Stop aborts the RPC, but the pool job keeps running unless+# pet.cancel flips its token (polled between provider calls)._pet_cancel_lock = threading.Lock()_pet_cancelled: set[str] = set()_PET_REFERENCE_MIME_EXT = {"png": "png", "jpeg": "jpg", "jpg": "jpg", "webp": "webp", "gif": "gif"}@@ -3063,10 +2928,8 @@ def _pet_is_cancelled(token: str) -> bool:return token in _pet_cancelled-# ── Spawn-tree snapshots: TUI-written, disk-persisted ────────────────-# The TUI owns subagent state (the /agents overlay; registry in tools/delegate_tool); on-# turn-complete it posts the final tree here and /replay fetches by session_id + filename.-# Layout: $HERMES_HOME/spawn-trees/<session_id>/<timestamp>.json+# ── Spawn-tree snapshots: the TUI owns subagent state (/agents overlay; registry in tools/delegate_tool), posts+# the final tree on turn-complete and /replay fetches by session_id + filename. Layout: spawn-trees/<sid>/<ts>.jsondef _spawn_trees_root():@@ -3082,8 +2945,8 @@ def _spawn_tree_session_dir(session_id: str):return d-# Per-session append-only index (one JSON object per line) so `spawn_tree.list` needn't read every-# full snapshot. It is a cache: a lost line just means list() falls back to a directory scan.+# Per-session append-only JSONL index so `spawn_tree.list` needn't read every snapshot; a cache — a lost+# line just means list() falls back to a directory scan._SPAWN_TREE_INDEX = "_index.jsonl"@@ -3117,19 +2980,17 @@ def _read_spawn_tree_index(session_dir) -> list[dict]:_GOAL_COMPRESSION_RECOVERY_ATTEMPTS = "_goal_compression_recovery_attempts"_GOAL_COMPRESSION_RECOVERY_LIMIT = 1-# Captured at import time: tests monkeypatch threading.Thread with a synchronous stub, and this-# ticker only exits once `stop` is set AFTER run_conversation returns — inline it would spin forever.+# Captured at import time: tests monkeypatch threading.Thread with a synchronous stub, and the ticker only+# exits once `stop` is set AFTER run_conversation returns — inline it would spin forever._RealThread = threading.Threaddef _start_usage_ticker(sid: str, agent, interval: float = 1.0) -> tuple[threading.Event, threading.Thread]:- """Push live ``session.usage`` snapshots every ``interval`` s while a turn runs (otherwise the- status-bar context figure freezes until ``message.complete``). The caller must set the Event AND- join the thread before emitting ``message.complete``: a late tick would roll the client's final- usage back to a stale snapshot."""+ """Push live ``session.usage`` snapshots every ``interval`` s while a turn runs. The caller must set the+ Event AND join the thread before ``message.complete``: a late tick would roll the final usage back."""stop = threading.Event()- # Dedup baseline sampled BEFORE the thread starts (the client already has the turn-start- # values); a late-scheduled thread would otherwise absorb the first counter growth and never emit it.+ # Dedup baseline sampled BEFORE the thread starts (the client has the turn-start values); a late-scheduled+ # thread would otherwise absorb the first counter growth and never emit it.try:baseline: dict | None = _get_usage(agent)except Exception:@@ -3164,8 +3025,7 @@ def _respond(rid, params, key, *, allow_expired=False):_, ev = entrybatch = _batch_clarify.get(r)if batch is not None and question_id:- # Per-question lock; update-in-place so a locked answer stays editable until every- # qid is locked (the Confirm click).+ # Per-question lock; update-in-place so an answer stays editable until every qid is locked (Confirm).if question_id not in batch["qids"]:return _err(rid, 4002, f"unknown question_id {question_id!r}")batch["answers"][question_id] = params.get(key, "")@@ -3195,25 +3055,21 @@ def _session_processes(session: dict) -> list:return owned-# Serialize reload.mcp (runs on the pool): overlapping shutdown+discover pairs would leave the-# registry half-built.+# Serialize reload.mcp (runs on the pool): overlapping shutdown+discover pairs would leave the registry half-built._mcp_reload_lock = threading.Lock()-# Bumped per SUCCESSFUL reload; a follower skips only if it advanced while it waited (a leader-# that threw leaves it unchanged → follower reloads itself).+# Bumped per SUCCESSFUL reload; a follower skips only if it advanced while it waited (a leader that threw+# leaves it unchanged → the follower reloads itself)._mcp_reload_gen = 0-# The mcp_rev the last successful reload actually LOADED (re-hashed after discovery). A follower-# coalesces only when its requested rev matches; otherwise the config changed under the leader.+# The mcp_rev the last successful reload actually LOADED (re-hashed after discovery); a follower coalesces+# only when its requested rev matches, otherwise the config changed under the leader._mcp_reload_loaded_rev = ""-# Bounded convergence for a config edit racing a slow reload: the leader re-hashes after-# discovery and repeats until the hash is stable.+# Bounded convergence for a config edit racing a slow reload: the leader re-hashes until the hash is stable._MCP_RELOAD_MAX_PASSES = 3def _compute_mcp_rev() -> str:- """Hash of the MCP-relevant config sections: mcp_servers (definitions — omitting it meant an- edited server never bumped the rev and never connected) + mcp (settings) + tools (enables).- ``config.get mtime`` ships it so cosmetic writes don't trigger reloads; ``reload.mcp`` uses it- for revision-aware coalescing. "" = unknown (fail open)."""+ """Hash of mcp_servers (definitions — omitting it meant an edited server never bumped the rev) + mcp ++ tools. ``config.get mtime`` ships it so cosmetic writes don't reload; ``reload.mcp`` coalesces on it. "" = unknown."""try:cfg = _load_cfg()rev_src = json.dumps({k: cfg.get(k) for k in ("mcp", "mcp_servers", "tools")}, sort_keys=True, default=str)@@ -3245,8 +3101,8 @@ _TUI_EXTRA: list[tuple[str, str, str]] = [("/sessions", "Switch between live TUI sessions", "TUI"),]-# Commands that queue onto _pending_input in the CLI; the slash worker has no reader for that-# queue, so slash.exec routes them to command.dispatch instead.+# Commands that queue onto _pending_input in the CLI; the slash worker has no reader for that queue, so+# slash.exec routes them to command.dispatch instead._PENDING_INPUT_COMMANDS: frozenset[str] = frozenset({"retry", "queue", "q", "steer", "plan", "goal", "loop", "proactive", "moa", "undo", "learn","init", "compress", "compact",@@ -3256,9 +3112,8 @@ _WORKER_BLOCKED_COMMANDS: frozenset[str] = frozenset({"snapshot", "snap"})def _skill_usage_lookup():- """``(usage, origin)`` callables for the skill-command catalog: ``usage(name)`` = observed activity- count (use + view + patch); ``origin(name)`` = "hub" / "bundled" / "local" (what ``/api/skills``- reports as ``provenance``, "local" spelled "agent"). Any failure degrades to 0 / "local"."""+ """``(usage, origin)`` callables for the skill catalog: activity count (use + view + patch) and+ "hub" / "bundled" / "local" (``/api/skills`` ``provenance``, "local" spelled "agent"). Failure → 0 / "local"."""try:from tools.skill_usage import (_read_bundled_manifest_names, _read_hub_installed_names, activity_count, load_usage)@@ -3282,13 +3137,9 @@ _SLASH_COMPLETION_LIMIT = 30def _rank_slash_completions(items: list[dict], usage, origin_of, *, browsing: bool, score_of=None) -> list[dict]:- """Rank and bound slash completions the way the menu should read.- Registry commands keep their order; only the skill block is reordered: fuzzy ``score_of`` first- (a name match beats a description match), then most-used, then A-Z. The limit is spent PER KIND:- commands come before the first skill, so a flat cut on a large install offered no skill at all.- ``browsing`` (bare ``/``) drops never-used bundled skills as noise; a typed query is SEARCHING and- a search that hides a match is broken — nothing is pruned there, only reordered."""-+ """Registry commands keep their order; only skills reorder: fuzzy ``score_of`` first, then most-used, then+ A-Z. The limit is spent PER KIND (a flat cut on a large install offered no skill at all). ``browsing``+ (bare ``/``) drops never-used bundled skills as noise; a typed query is SEARCHING — nothing pruned, only reordered."""def name_of(item: dict) -> str:return str(item.get("text", "")).strip().lstrip("/").lower()commands = [item for item in items if item.get("kind") != "skill"]@@ -3336,8 +3187,8 @@ from .mcp_rpc_helpers import ( # noqa: E402, F401summarize_server as _mcp_summarize_server)-# ── Split @method handler modules (see method_ctx.py) ────────────────-# Imported last so every global the handlers close over exists; register() rebinds them onto this namespace.+# ── Split @method handler modules (see method_ctx.py): imported last so every global the handlers close+# over exists; register() rebinds them onto this namespace.from . import ( # noqa: E402methods_voice as _methods_voice, methods_browser as _methods_browser, methods_slash as _methods_slash,methods_complete_helpers as _methods_complete_helpers, session_auto_continue as _session_auto_continue,