Skip to content

The agent that grows with you

Merge pull request #74298 from NousResearch/opt/tui-methods-split

Teknium1ea2ea18fda5
diff --cc tui_gateway/server.py
index 7d39f0ac123,2608ce7d53e..fdef04968ed
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@@ -10326,4397 -8307,1815 +8311,1815 @@@ def _notification_event_requires_owner(
)
- @method("session.undo")
- def _(rid, params: dict) -> dict:
- session, err = _sess(params, rid)
- if err:
- return err
- # Reject during an in-flight turn. If we mutated history while
- # the agent thread is running, prompt.submit's post-run history
- # write would either clobber the undo (version matches) or
- # silently drop the agent's output (version mismatch, see below).
- # Neither is what the user wants — make them /interrupt first.
- if session.get("running"):
- return _err(
- rid, 4009, "session busy — /interrupt the current turn before /undo"
- )
- removed = 0
- with session["history_lock"]:
- history = session.get("history", [])
- # Truncate from the last *real* user turn (no display_kind). Popping
- # only trailing assistant/tool then one user left timeline markers
- # (async_delegation_complete, model_switch, …) as the undo target —
- # so session.undo removed bookkeeping instead of the last exchange.
- # Match list_recent_user_messages / CLI turn counting.
- last_user_idx = None
- for i in range(len(history) - 1, -1, -1):
- msg = history[i]
- if msg.get("role") == "user" and not msg.get("display_kind"):
- last_user_idx = i
- break
- if last_user_idx is not None:
- removed = len(history) - last_user_idx
- del history[last_user_idx:]
- session["history_version"] = int(session.get("history_version", 0)) + 1
- return _ok(rid, {"removed": removed})
-
+ def _notification_event_dedup_key(evt: dict) -> tuple:
+ """Return the UI-emission identity for a process notification event.
- @method("session.compress")
- def _(rid, params: dict) -> dict:
- session, err = _sess_nowait(params, rid)
- if err:
- return err
- assert session is not None
- if _session_uses_compute_host(session):
- sid = str(params.get("session_id") or "")
- focus_topic = str(params.get("focus_topic", "") or "").strip()
- command = "/compress" + (f" {focus_topic}" if focus_topic else "")
- try:
- ack = _send_compute_host_control(
- sid,
- route_name="session.compress",
- command=command,
- wait=True,
- timeout=120.0,
- )
- except Exception as exc:
- return _err(rid, 5019, f"compute-host compress failed: {exc}")
- if ack.get("type") in {"control.error", "error"}:
- return _err(rid, 4009, str(ack.get("message") or "compute-host compress failed"))
- _apply_compute_host_metadata_mirror(session, ack)
- host_result = ack.get("result")
- if isinstance(host_result, dict):
- # The host owns the isolated session's agent/history, so preserve
- # its structured compression result verbatim. In particular this
- # carries `status: aborted` and `summary.aborted`; flattening the
- # old text-only acknowledgement made Desktop show aborted work as a
- # success toast.
- return _ok(rid, {**host_result, "turn_isolation": True})
- host_info = ack.get("session_info") if isinstance(ack.get("session_info"), dict) else {}
- host_messages = _history_to_messages(ack.get("messages")) if isinstance(ack.get("messages"), list) else []
- # `messages` is returned at top level for the desktop transcript
- # replacement. Keep the host acknowledgement metadata, but do not send
- # the same (potentially large) transcript a second time inside it.
- host_ack = {key: value for key, value in ack.items() if key != "messages"}
- return _ok(
- rid,
- {
- "status": "compressed",
- "turn_isolation": True,
- "host_ack": host_ack,
- "info": host_info,
- "messages": host_messages,
- "usage": host_info.get("usage") if isinstance(host_info.get("usage"), dict) else {},
- },
- )
- session, err = _sess(params, rid)
- if err:
- return err
- if session.get("running"):
- return _err(
- rid, 4009, "session busy — /interrupt the current turn before /compress"
+ Completion events are terminal notifications for a background process, so
+ they remain one-shot per process session. Watch-match events are not
+ terminal: a single background process can legitimately match the same or
+ different patterns many times, so include event-specific content to avoid
+ suppressing later distinct matches from the same process.
+ """
+ evt_type = evt.get("type", "completion")
+ evt_sid = evt.get("session_id", "")
+ if evt_type == "watch_match":
+ return (
+ evt_sid,
+ evt_type,
+ evt.get("command", ""),
+ evt.get("pattern", ""),
+ evt.get("output", ""),
+ evt.get("suppressed", 0),
+ evt.get("message_id", ""),
)
- from agent.conversation_compression import (
- finalize_context_engine_compression_notification,
- )
-
- sid = params.get("session_id", "")
- focus_topic = str(params.get("focus_topic", "") or "").strip()
- try:
- from agent.manual_compression_feedback import summarize_manual_compression
- from agent.model_metadata import estimate_request_tokens_rough
-
- with session["history_lock"]:
- before_messages = list(session.get("history", []))
- history_version = int(session.get("history_version", 0))
- before_count = len(before_messages)
- _agent = session["agent"]
- _sys_prompt = getattr(_agent, "_cached_system_prompt", "") or ""
- _tools = getattr(_agent, "tools", None) or None
- before_tokens = (
- estimate_request_tokens_rough(
- before_messages, system_prompt=_sys_prompt, tools=_tools
- )
- if before_count
- else 0
+ if evt_type.startswith("watch_overflow_") or evt_type == "watch_disabled":
+ return (
+ evt_sid,
+ evt_type,
+ evt.get("command", ""),
+ evt.get("message", ""),
+ evt.get("suppressed", 0),
)
+ if evt_type == "async_delegation":
+ # Async-delegation completions have no process session_id; without
+ # this the fallthrough keys every one as ("", "async_delegation")
+ # and the second completion's status update is suppressed forever.
+ return (evt.get("delegation_id", ""), evt_type)
+ return (evt_sid, evt_type)
- if before_count >= 4:
- focus_suffix = f', focus: "{focus_topic}"' if focus_topic else ""
- _status_update(
- sid,
- "compressing",
- f"⠋ compressing {before_count} messages "
- f"(~{before_tokens:,} tok){focus_suffix}…",
- )
- try:
- removed, usage = _compress_session_history(
- session,
- focus_topic,
- approx_tokens=before_tokens,
- before_messages=before_messages,
- history_version=history_version,
- )
- with session["history_lock"]:
- messages = list(session.get("history", []))
- after_count = len(messages)
- # Re-read system prompt + tools after compression — _compress_context
- # may have rebuilt the system prompt (_cached_system_prompt=None).
- _sys_prompt_after = (
- getattr(_agent, "_cached_system_prompt", "") or _sys_prompt
- )
- _tools_after = getattr(_agent, "tools", None) or _tools
- after_tokens = (
- estimate_request_tokens_rough(
- messages,
- system_prompt=_sys_prompt_after,
- tools=_tools_after,
- )
- if after_count
- else 0
- )
- agent = session["agent"]
- _sync_session_key_after_compress(sid, session)
- summary = summarize_manual_compression(
- before_messages,
- messages,
- before_tokens,
- after_tokens,
- compression_state=getattr(agent, "context_compressor", None),
- )
- info = _session_info(agent, session)
- _emit("session.info", sid, info)
- finalize_context_engine_compression_notification(
- agent,
- committed=True,
- )
- return _ok(
- rid,
- {
- "status": "aborted" if summary["aborted"] else "compressed",
- "removed": removed,
- "before_messages": before_count,
- "after_messages": after_count,
- "before_tokens": before_tokens,
- "after_tokens": after_tokens,
- "summary": summary,
- "usage": usage,
- "info": info,
- # Keep this identical to session.resume / session.history:
- # raw tool results can contain large or sensitive payloads
- # that belong in persisted history, not the transcript
- # replacement response.
- "messages": _history_to_messages(messages),
- },
- )
- finally:
- # Always clear the pinned compressing status so the bar
- # reverts to neutral whether compaction succeeded, was a
- # no-op, or raised.
- _status_update(sid, "ready")
- except CompressionLockHeld as e:
- _status_update(sid, "ready")
- from agent.manual_compression_feedback import (
- describe_compression_lock_skip,
- )
- return _ok(rid, {
- "compressed": False,
- "lock_held": True,
- "message": describe_compression_lock_skip(e.holder),
- })
- except Exception as e:
- finalize_context_engine_compression_notification(
- session["agent"],
- committed=False,
- )
- return _err(rid, 5005, str(e))
+ # Mirror gateway/kanban_watchers.py TERMINAL_KINDS: claim silent kinds too so
+ # the cursor advances past them and they can't wedge a later completed/blocked
+ # event behind an unclaimed row.
+ _KANBAN_NOTIFY_KINDS = (
+ "completed", "blocked", "gave_up", "crashed", "timed_out",
+ "status", "archived", "unblocked",
+ )
+ _KANBAN_SILENT_KINDS = frozenset({"archived", "unblocked"})
+ _KANBAN_POLL_SECONDS = 5.0
- @method("session.save")
- def _(rid, params: dict) -> dict:
- session, err = _sess(params, rid)
- if err:
- return err
+ def _format_kanban_event_text(sub: dict, task, ev, board_slug: str) -> Optional[str]:
+ """Single-line notification text for one kanban event.
- if _session_uses_compute_host(session):
- sid = str(params.get("session_id") or "")
+ Wording mirrors the gateway notifier (gateway/kanban_watchers.py) so a
+ task completion reads the same in the TUI as it does on Telegram.
+ Returns None for kinds that are claimed but intentionally silent.
+ """
+ kind = getattr(ev, "kind", "")
+ if not kind or kind in _KANBAN_SILENT_KINDS:
+ return None
+ task_id = sub.get("task_id", "")
+ title = (getattr(task, "title", None) or task_id)[:120]
+ board_tag = f"[{board_slug}] " if board_slug else ""
+ who = getattr(task, "assignee", None) or ""
+ tag = f"@{who} " if who else ""
+ payload = getattr(ev, "payload", None) or {}
+ if kind == "completed":
+ handoff = ""
+ summary = payload.get("summary")
+ if summary:
+ lines = str(summary).strip().splitlines()
+ handoff = f"\n{lines[0][:200]}" if lines else ""
+ elif getattr(task, "result", None):
+ lines = str(task.result).strip().splitlines()
+ handoff = f"\n{lines[0][:160]}" if lines else ""
+ return f"✔ {board_tag}{tag}Kanban {task_id} done — {title}{handoff}"
+ if kind == "blocked":
+ reason = f": {str(payload.get('reason'))[:160]}" if payload.get("reason") else ""
+ return f"⏸ {board_tag}{tag}Kanban {task_id} blocked{reason}"
+ if kind == "gave_up":
+ err = f"\n{str(payload.get('error'))[:200]}" if payload.get("error") else ""
+ return f"✖ {board_tag}{tag}Kanban {task_id} gave up after repeated spawn failures{err}"
+ if kind == "crashed":
+ return f"✖ {board_tag}{tag}Kanban {task_id} worker crashed (pid gone); dispatcher will retry"
+ if kind == "timed_out":
+ limit = 0
try:
- ack = _send_compute_host_control(
- sid,
- route_name="session.save",
- wait=True,
- )
- except Exception as exc:
- return _err(rid, 5011, f"compute-host session save failed: {exc}")
- if ack.get("type") in {"control.error", "error"}:
- return _err(rid, 5011, str(ack.get("message") or "compute-host session save failed"))
- result = ack.get("result")
- if not isinstance(result, dict):
- return _err(rid, 5011, "compute-host session save returned an invalid response")
- return _ok(rid, result)
+ limit = int(payload.get("limit_seconds") or 0)
+ except (TypeError, ValueError):
+ pass
+ return f"⏱ {board_tag}{tag}Kanban {task_id} timed out (max_runtime={limit}s); will retry"
+ if kind == "status":
+ return f"🔄 {board_tag}{tag}Kanban {task_id} → {payload.get('status') or ''}"
+ return None
- agent = session["agent"]
- # Mirror the classic CLI /save: snapshot under the Hermes profile home
- # (~/.hermes/sessions/saved/) rather than the project/workspace CWD, and
- # include the system prompt so the export matches the dashboard save.
- saved_dir = get_hermes_home() / "sessions" / "saved"
- try:
- saved_dir.mkdir(parents=True, exist_ok=True)
- except Exception as e:
- return _err(rid, 5011, f"failed to create save directory {saved_dir}: {e}")
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
- path = saved_dir / f"hermes_conversation_{timestamp}.json"
+ def _collect_kanban_notifications(session: dict) -> list:
+ """Claim unseen terminal kanban events for this TUI session's subscriptions.
- with session["history_lock"]:
- messages = list(session.get("history", []))
-
- session_id = getattr(agent, "session_id", None) or session.get("session_key") or ""
- # Prefer the agent's session_start datetime (matches the classic CLI export);
- # fall back to the gateway session's created_at timestamp.
- agent_start = getattr(agent, "session_start", None)
- if isinstance(agent_start, datetime):
- session_start = agent_start.isoformat()
- else:
- created_at = session.get("created_at")
- session_start = (
- datetime.fromtimestamp(created_at).isoformat()
- if isinstance(created_at, (int, float))
- else ""
- )
+ ``kanban_create`` auto-subscribes TUI/desktop sessions with
+ ``platform="tui"`` and ``chat_id=HERMES_SESSION_KEY`` (see
+ tools/kanban_tools.py ``_maybe_auto_subscribe``). The gateway notifier
+ can't deliver those — there is no "tui" messaging adapter — so this
+ poller is the delivery path for them (issue #59890). Uses the same
+ atomic cursor-claim (``claim_unseen_events_for_sub``) as the gateway
+ notifier, so a subscription is delivered exactly once even if a gateway
+ and a TUI poll the same board DB.
+ Returns the list of formatted notification texts (may be empty).
+ """
+ session_key = str(session.get("session_key") or "")
+ if not session_key or session.get("_finalized"):
+ return []
try:
- with open(path, "w", encoding="utf-8") as f:
- json.dump(
- {
- "model": getattr(agent, "model", ""),
- "session_id": session_id,
- "session_start": session_start,
- "system_prompt": getattr(agent, "_cached_system_prompt", "") or "",
- "messages": messages,
- },
- f,
- indent=2,
- ensure_ascii=False,
- )
- return _ok(rid, {"file": str(path)})
- except Exception as e:
- return _err(rid, 5011, str(e))
-
-
- @method("session.close")
- def _(rid, params: dict) -> dict:
- sid = params.get("session_id", "")
- # Serialize only the ownership claim against session.resume / the orphan
- # reaper. Finalization may run arbitrary plugin/agent cleanup and must not
- # keep every unrelated session.resume waiting behind it.
- with _session_resume_lock:
- session = _pop_session_by_id(sid)
- closed = _teardown_popped_session(session, end_reason="tui_close")
- return _ok(rid, {"closed": closed})
-
-
- @method("session.branch")
- def _(rid, params: dict) -> dict:
- session, err = _sess(params, rid)
- if err:
- return err
- # Branch must write into the parent's profile-scoped state.db (app-global
- # remote mode). Using the launch handle would orphan branch rows + history.
- with _session_db(session) as db:
- if db is None:
- return _db_unavailable_error(rid, code=5008)
- old_key = session["session_key"]
- with session["history_lock"]:
- history = [dict(msg) for msg in session.get("history", [])]
- if not history:
- return _err(rid, 4008, "nothing to branch — send a message first")
- count = params.get("count")
- if isinstance(count, int) and count > 0:
- history = history[:count]
- new_key = _new_session_key()
- new_sid = uuid.uuid4().hex[:8]
- source = _session_source(session)
- lease = None # claimed lazily on the first turn (_ensure_active_session_slot)
- branch_name = params.get("name", "")
+ from hermes_cli import kanban_db as _kb
+ except Exception:
+ return []
+ texts: list = []
+ try:
+ boards = _kb.list_boards(include_archived=False)
+ except Exception:
try:
- if branch_name:
- title = branch_name
- else:
- current = db.get_session_title(old_key) or "branch"
- title = (
- db.get_next_title_in_lineage(current)
- if hasattr(db, "get_next_title_in_lineage")
- else f"{current} (branch)"
- )
- db.create_session(
- new_key,
- source=source,
- model=_resolve_model(),
- # Stable _branched_from marker so list_sessions_rich() keeps the
- # branch visible in /resume and /sessions. The TUI branch leaves
- # the parent live (no end_reason='branched'), so the legacy
- # end_reason heuristic never matches it — the marker is the only
- # thing that surfaces TUI branches. See issue #20856.
- model_config={"_branched_from": old_key},
- parent_session_id=old_key,
- cwd=_session_cwd(session),
- # The branch stays on its parent's profile. Explicit stamp (not
- # just the parent-backfill) so it holds even when the parent row
- # predates the profile_name column.
- profile_name=(
- Path(session["profile_home"]).name
- if session.get("profile_home")
- else None
- ),
+ boards = [_kb.read_board_metadata(_kb.DEFAULT_BOARD)]
+ except Exception:
+ return []
+ # Poll each resolved DB path once — multiple slugs can point at the same
+ # DB when HERMES_KANBAN_DB pins the board path (same guard as the gateway
+ # notifier).
+ seen_db_paths: set = set()
+ for board_meta in boards:
+ slug = (board_meta or {}).get("slug") or _kb.DEFAULT_BOARD
+ db_path = (board_meta or {}).get("db_path")
+ try:
+ resolved = (
+ str(Path(db_path).expanduser().resolve())
+ if db_path else str(_kb.kanban_db_path(slug).resolve())
)
- for msg in history:
- db.append_message(
- session_id=new_key,
- role=msg.get("role", "user"),
- content=msg.get("content"),
- # Preserve the parent's original message timestamps —
- # branch copies are history, not new activity (9d73006ad).
- timestamp=msg.get("timestamp"),
- )
- db.set_session_title(new_key, title)
- except Exception as e:
- if lease is not None:
- lease.release()
- return _err(rid, 5008, f"branch failed: {e}")
- try:
- # Bind the branched AGENT to the parent's profile, mirroring
- # session.create/resume: home override so config/skills/memory resolve
- # to the profile during the build, and the profile's own state.db
- # handle so the live agent's message flushes — and any later
- # compression rotation — persist there. Writing only the row to the
- # parent's db while the agent stayed on the launch handle would
- # recreate the cross-profile split one turn later.
- parent_home = session.get("profile_home")
- branch_db = None
- if parent_home:
- from hermes_state import SessionDB
-
- branch_db = SessionDB(db_path=Path(parent_home) / "state.db")
- home_token = (
- set_hermes_home_override(parent_home) if parent_home else None
- )
+ except Exception:
+ resolved = f"slug:{slug}"
+ if resolved in seen_db_paths:
+ continue
+ seen_db_paths.add(resolved)
+ try:
+ conn = _kb.connect(board=slug)
+ except Exception:
+ continue
try:
- tokens = _set_session_context(new_key)
try:
- agent = _make_agent(
- new_sid,
- new_key,
- session_id=new_key,
- session_db=branch_db,
- platform_override=source,
+ subs = _kb.list_notify_subs(conn)
+ except Exception:
+ continue
+ for sub in subs:
+ if (sub.get("platform") or "").lower() != "tui":
+ continue
+ if sub.get("chat_id") != session_key:
+ continue
+ _old, _new, events = _kb.claim_unseen_events_for_sub(
+ conn,
+ task_id=sub["task_id"],
+ platform=sub["platform"],
+ chat_id=sub["chat_id"],
+ thread_id=sub.get("thread_id") or "",
+ kinds=_KANBAN_NOTIFY_KINDS,
)
- finally:
- _clear_session_context(tokens)
- _init_session(
- new_sid,
- new_key,
- agent,
- list(history),
- cols=session.get("cols", 80),
- cwd=_session_cwd(session),
- session_db=branch_db,
- source=source,
- profile_home=parent_home,
- )
+ if not events:
+ continue
+ task = _kb.get_task(conn, sub["task_id"])
+ for ev in events:
+ text = _format_kanban_event_text(sub, task, ev, slug)
+ if text:
+ texts.append(text)
+ # Unsubscribe only at a truly final status (done/archived);
+ # blocked/crashed subs stay live so a respawned task's next
+ # terminal event still reaches the user (same rule as the
+ # gateway notifier).
+ if task and getattr(task, "status", "") in {"done", "archived"}:
+ try:
+ _kb.remove_notify_sub(
+ conn,
+ task_id=sub["task_id"],
+ platform=sub["platform"],
+ chat_id=sub["chat_id"],
+ thread_id=sub.get("thread_id") or "",
+ )
+ except Exception:
+ pass
finally:
- if home_token is not None:
- reset_hermes_home_override(home_token)
- if new_sid in _sessions:
- _sessions[new_sid]["active_session_lease"] = lease
- except Exception as e:
- if lease is not None:
- lease.release()
- return _err(rid, 5000, f"agent init failed on branch: {e}")
- branched_session = _sessions.get(new_sid)
- return _ok(
- rid,
- {
- "session_id": new_sid,
- "stored_session_id": new_key,
- "title": title,
- "parent": old_key,
- "message_count": len(history),
- "messages": _history_to_messages(history),
- "info": _session_info(agent, branched_session),
- },
- )
-
-
- @method("session.interrupt")
- def _(rid, params: dict) -> dict:
- # Keypress barge-in: stopping the turn also silences its streaming TTS
- # (voice is process-global, so no per-session scoping is needed).
- _tts_stream_stop()
- session, err = _sess_nowait(params, rid)
- if err:
- return err
- if _session_uses_compute_host(session):
- sid = str(params.get("session_id") or "")
- if session.get("running"):
- try:
- _get_compute_host_supervisor().interrupt(sid, request_id=f"interrupt-{rid}")
- except Exception as exc:
- return _err(rid, 5019, f"compute-host interrupt failed: {exc}")
- with session["history_lock"]:
- session["_turn_cancel_requested"] = True
- session["queued_prompt"] = None
- _clear_pending(sid)
- try:
- from tools.approval import resolve_gateway_approval
-
- resolve_gateway_approval(session["session_key"], "deny", resolve_all=True)
- except Exception:
- pass
- return _ok(rid, {"status": "interrupted", "turn_isolation": True})
- session, err = _sess(params, rid)
- if err:
- return err
- # Safety net: if the turn's run thread is already gone but `running` stayed
- # stuck (a crash/desync that skipped the run loop's `finally`), force-clear it
- # so the session can't be permanently bricked at 4009 "session busy" — every
- # send/restore/resume would otherwise reject until a full backend restart.
- # Always tell the agent to interrupt when the session claims a run is active:
- # stale flags are cleared below, and fresh turns clear the interrupt flag at
- # entry. This keeps a stale/missing thread handle from making Stop a no-op.
- run_thread = session.get("_run_thread")
- run_thread_alive = run_thread is not None and run_thread.is_alive()
- should_interrupt = bool(session.get("running"))
- if should_interrupt and hasattr(session["agent"], "interrupt"):
- session["agent"].interrupt()
- with session["history_lock"]:
- session["_turn_cancel_requested"] = True
- session["queued_prompt"] = None
- if not run_thread_alive:
- with session["history_lock"]:
- if session.get("running"):
- session["running"] = False
- _clear_inflight_turn(session)
-
- # Stop = stop the TURN (cooperative interrupt above also kills the in-flight
- # foreground subprocess). Background processes the agent started (dev servers,
- # watchers) are intentionally left running — kill those individually with the
- # "x" on the task row (process.kill). Don't reap them here.
- # Scope the pending-prompt release to THIS session. A global
- # _clear_pending() would collaterally cancel clarify/sudo/secret
- # prompts on unrelated sessions sharing the same tui_gateway
- # process, silently resolving them to empty strings.
- _clear_pending(params.get("session_id", ""))
- try:
- from tools.approval import resolve_gateway_approval
-
- resolve_gateway_approval(session["session_key"], "deny", resolve_all=True)
- except Exception:
- pass
- return _ok(rid, {"status": "interrupted"})
-
-
- # ── Delegation: subagent tree observability + controls ───────────────
- # Powers the TUI's /agents overlay (see ui-tui/src/components/agentsOverlay).
- # The registry lives in tools/delegate_tool — these handlers are thin
- # translators between JSON-RPC and the Python API.
+ conn.close()
+ return texts
- @method("delegation.status")
- def _(rid, params: dict) -> dict:
- from tools.delegate_tool import (
- is_spawn_paused,
- list_active_subagents,
- _get_max_concurrent_children,
- _get_max_spawn_depth,
- )
+ def _notification_poller_loop(
+ stop_event: threading.Event, sid: str, session: dict
+ ) -> None:
+ """Poll completion_queue and dispatch notifications autonomously.
- return _ok(
- rid,
- {
- "active": list_active_subagents(),
- "paused": is_spawn_paused(),
- "max_spawn_depth": _get_max_spawn_depth(),
- "max_concurrent_children": _get_max_concurrent_children(),
- },
- )
+ Runs in a daemon thread started by _init_session(). Emits a
+ status.update (kind=process) for user visibility, then chains an
+ agent turn via _run_prompt_submit if the session is idle.
+ The completion_queue is process-global. In multi-session Desktop each
+ poller requeues events owned by another live session and drops addressed
+ events whose owner is gone; ownerless legacy notifications remain global.
- @method("delegation.pause")
- def _(rid, params: dict) -> dict:
- from tools.delegate_tool import set_spawn_paused
+ Also polls ``kanban_notify_subs`` every ``_KANBAN_POLL_SECONDS`` for this
+ session's TUI kanban subscriptions and delivers terminal task events the
+ same way (status.update + agent turn) — the delivery path
+ tools/kanban_tools.py documents for platform="tui" rows (issue #59890).
+ """
+ from tools.process_registry import process_registry, format_process_notification
- paused = bool(params.get("paused", True))
- return _ok(rid, {"paused": set_spawn_paused(paused)})
+ _emitted = set() # dedup re-queued events so same completion isn't emitted 50 times while session is busy
+ _last_kanban_poll = 0.0
+ while not stop_event.is_set() and not session.get("_finalized"):
+ _now = time.monotonic()
+ if _now - _last_kanban_poll >= _KANBAN_POLL_SECONDS:
+ _last_kanban_poll = _now
+ try:
+ _kanban_texts = _collect_kanban_notifications(session)
+ except Exception as _kb_exc:
+ print(
+ f"[tui_gateway] kanban notification poll failed: "
+ f"{type(_kb_exc).__name__}: {_kb_exc}",
+ file=sys.stderr,
+ )
+ _kanban_texts = []
+ if _kanban_texts:
+ for _kb_text in _kanban_texts:
+ _emit("status.update", sid, {"kind": "process", "text": _kb_text})
+ # Events are cursor-claimed (never re-queued), so buffer them
+ # until the session is idle instead of dropping the agent turn.
+ session.setdefault("_kanban_pending", []).extend(_kanban_texts)
+ _pending = session.get("_kanban_pending") or []
+ if _pending:
+ _batch: list = []
+ with session["history_lock"]:
+ if not session.get("running"):
+ session["running"] = True
+ _batch = list(_pending)
+ session["_kanban_pending"] = []
+ if _batch:
+ rid = f"__notif__{int(time.time() * 1000)}"
+ try:
+ _emit("message.start", sid)
+ _run_prompt_submit(rid, sid, session, "\n".join(_batch))
+ except Exception as exc:
+ print(
+ f"[tui_gateway] kanban notification dispatch failed: "
+ f"{type(exc).__name__}: {exc}",
+ file=sys.stderr,
+ )
+ with session["history_lock"]:
+ session["running"] = False
+ try:
+ evt = process_registry.completion_queue.get(timeout=0.5)
+ except Exception:
+ continue
+ # Multiple desktop sessions share this one process-wide queue. Only
+ # consume events that belong to *this* session — otherwise a background
+ # process started in session A would surface its completion in whichever
+ # session's poller happened to wake first (Ben's "reported in a
+ # different session" bug). Leave foreign events for their owner.
+ if _notification_event_belongs_elsewhere(sid, session, evt):
+ process_registry.completion_queue.put(evt)
+ time.sleep(0.1)
+ continue
- @method("subagent.interrupt")
- def _(rid, params: dict) -> dict:
- from tools.delegate_tool import interrupt_subagent
+ # What reaches here is not owned by another LIVE session. Addressed
+ # events still require positive proof before injection: exact UI origin,
+ # direct durable key, or compression lineage. If none proves ownership,
+ # the event is orphaned and must not be adopted by this chat. Truly
+ # ownerless ordinary notifications retain legacy global delivery.
+ requires_owner = _notification_event_requires_owner(evt)
+ if requires_owner and not _session_owns_notification_event(sid, session, evt):
+ log = (
+ logger.warning
+ if evt.get("type") == "async_delegation"
+ else logger.debug
+ )
+ log(
+ "Dropping unowned %s notification (origin=%r key=%r) instead "
+ "of delivering to session %s",
+ evt.get("type", "completion"),
+ str(evt.get("origin_ui_session_id") or ""),
+ str(evt.get("session_key") or ""),
+ sid,
+ )
+ continue
- subagent_id = str(params.get("subagent_id") or "").strip()
- if not subagent_id:
- return _err(rid, 4000, "subagent_id required")
- ok = interrupt_subagent(subagent_id)
- return _ok(rid, {"found": ok, "subagent_id": subagent_id})
+ _evt_sid = evt.get("session_id", "")
+ if evt.get("type") == "completion" and process_registry.is_completion_consumed(_evt_sid):
+ continue
+ text = format_process_notification(evt)
+ if not text:
+ continue
- # ── Spawn-tree snapshots: TUI-written, disk-persisted ────────────────
- # The TUI is the source of truth for subagent state (it assembles payloads
- # from the event stream). On turn-complete it posts the final tree here;
- # /replay and /replay-diff fetch past snapshots by session_id + filename.
- #
- # Layout: $HERMES_HOME/spawn-trees/<session_id>/<timestamp>.json
- # Each file contains { session_id, started_at, finished_at, subagents: [...] }.
+ # Only emit the same notification identity to TUI once — re-queued
+ # completions get re-emitted every 0.5s otherwise when session is busy,
+ # while distinct watch_match events from the same process must remain
+ # visible independently.
+ _dedup_key = _notification_event_dedup_key(evt)
+ if _dedup_key not in _emitted:
+ _emit("status.update", sid, {"kind": "process", "text": text})
+ _emitted.add(_dedup_key)
+ _requeued = False
+ with session["history_lock"]:
+ if session.get("running"):
+ process_registry.completion_queue.put(evt)
+ _requeued = True
+ else:
+ session["running"] = True
+ if _requeued:
+ # Back off before re-polling: the re-queued event keeps the queue
+ # non-empty, so without a sleep this loop spins at full speed
+ # (100% CPU, GIL churn) for as long as the session stays busy.
+ time.sleep(0.25)
+ continue
- def _spawn_trees_root():
- from hermes_constants import get_hermes_home
+ rid = f"__notif__{int(time.time() * 1000)}"
+ from tools.async_delegation import (
+ claim_event_delivery, complete_event_delivery, release_event_delivery,
+ )
+ _claim = claim_event_delivery(evt, "tui-poller")
+ if _claim is None:
+ continue
+ try:
+ _emit("message.start", sid)
+ if evt.get("type") == "async_delegation":
+ _run_prompt_submit(
+ rid,
+ sid,
+ session,
+ text,
+ display_kind="async_delegation_complete",
+ display_metadata=_async_delegation_display_metadata(evt),
+ )
+ else:
+ _run_prompt_submit(rid, sid, session, text)
+ complete_event_delivery(evt, _claim)
+ except Exception as exc:
+ release_event_delivery(evt, _claim)
+ print(
+ f"[tui_gateway] notification poller dispatch failed: "
+ f"{type(exc).__name__}: {exc}",
+ file=sys.stderr,
+ )
+ with session["history_lock"]:
+ session["running"] = False
- root = get_hermes_home() / "spawn-trees"
- root.mkdir(parents=True, exist_ok=True)
- return root
+ # Drain any remaining events after stop signal (process all pending
+ # before exiting so nothing is lost on shutdown). Events owned by other
+ # live sessions are set aside and re-queued so their poller still sees them.
+ # Orphaned events (owner gone) are dropped — same guard as the main loop.
+ deferred: list = []
+ while not process_registry.completion_queue.empty():
+ try:
+ evt = process_registry.completion_queue.get_nowait()
+ except Exception:
+ break
+ if _notification_event_belongs_elsewhere(sid, session, evt):
+ deferred.append(evt)
+ continue
+ # Same positive-proof rule as the live loop. Preserve the existing
+ # shutdown behavior for orphaned delegation payloads by deferring them
+ # for a later resume; ordinary addressed orphans are dropped.
+ requires_owner = _notification_event_requires_owner(evt)
+ if requires_owner and not _session_owns_notification_event(sid, session, evt):
+ if evt.get("type") == "async_delegation":
+ deferred.append(evt)
+ else:
+ logger.debug(
+ "Dropping unowned %s notification during shutdown drain "
+ "(origin=%r key=%r)",
+ evt.get("type", "completion"),
+ str(evt.get("origin_ui_session_id") or ""),
+ str(evt.get("session_key") or ""),
+ )
+ continue
+ _evt_sid = evt.get("session_id", "")
+ if evt.get("type") == "completion" and process_registry.is_completion_consumed(_evt_sid):
+ continue
+ text = format_process_notification(evt)
+ if not text:
+ continue
+ _dedup_key = _notification_event_dedup_key(evt)
+ if _dedup_key not in _emitted:
+ _emit("status.update", sid, {"kind": "process", "text": text})
+ _emitted.add(_dedup_key)
- def _spawn_tree_session_dir(session_id: str):
- safe = (
- "".join(c if c.isalnum() or c in "-_" else "_" for c in session_id) or "unknown"
- )
- d = _spawn_trees_root() / safe
- d.mkdir(parents=True, exist_ok=True)
- return d
+ with session["history_lock"]:
+ if session.get("running"):
+ process_registry.completion_queue.put(evt)
+ break
+ session["running"] = True
+ rid = f"__notif__{int(time.time() * 1000)}"
+ from tools.async_delegation import (
+ claim_event_delivery, complete_event_delivery, release_event_delivery,
+ )
+ _claim = claim_event_delivery(evt, "tui-poller")
+ if _claim is None:
+ continue
+ try:
+ _emit("message.start", sid)
+ if evt.get("type") == "async_delegation":
+ _run_prompt_submit(
+ rid,
+ sid,
+ session,
+ text,
+ display_kind="async_delegation_complete",
+ display_metadata=_async_delegation_display_metadata(evt),
+ )
+ else:
+ _run_prompt_submit(rid, sid, session, text)
+ complete_event_delivery(evt, _claim)
+ except Exception as exc:
+ release_event_delivery(evt, _claim)
+ print(
+ f"[tui_gateway] notification poller dispatch failed: "
+ f"{type(exc).__name__}: {exc}",
+ file=sys.stderr,
+ )
+ with session["history_lock"]:
+ session["running"] = False
- # Per-session append-only index of lightweight snapshot metadata. Read by
- # `spawn_tree.list` so scanning doesn't require reading every full snapshot
- # file (Copilot review on #14045). One JSON object per line.
- _SPAWN_TREE_INDEX = "_index.jsonl"
+ # Hand any other sessions' events back to the shared queue.
+ for evt in deferred:
+ process_registry.completion_queue.put(evt)
- def _append_spawn_tree_index(session_dir, entry: dict) -> None:
- try:
- with (session_dir / _SPAWN_TREE_INDEX).open("a", encoding="utf-8") as f:
- f.write(json.dumps(entry, ensure_ascii=False) + "\n")
- except OSError as exc:
- # Index is a cache — losing a line just means list() falls back
- # to a directory scan for that entry. Never block the save.
- logger.debug("spawn_tree index append failed: %s", exc)
+ def _async_delegation_display_metadata(evt: dict) -> dict:
+ """Build display-only metadata before the completion event is formatted."""
+ raw_results = evt.get("results")
+ results: list[dict] = [
+ result for result in raw_results if isinstance(result, dict)
+ ] if isinstance(raw_results, list) else []
+ task_count = len(results) or 1
+ completed_count = sum(
+ 1 for result in results
+ if result.get("status") in {"completed", "success"}
+ )
+ failed_count = sum(
+ 1 for result in results
+ if result.get("status") in {"failed", "error"}
+ )
+ metadata = {
+ "delegation_id": str(evt.get("delegation_id") or ""),
+ "task_count": task_count,
+ "completed_count": completed_count or task_count - failed_count,
+ "failed_count": failed_count,
+ }
+ duration = evt.get("total_duration_seconds") or evt.get("duration_seconds")
+ if isinstance(duration, (int, float)):
+ metadata["duration_seconds"] = duration
+ return metadata
- def _read_spawn_tree_index(session_dir) -> list[dict]:
- index_path = session_dir / _SPAWN_TREE_INDEX
- if not index_path.exists():
- return []
- out: list[dict] = []
- try:
- with index_path.open("r", encoding="utf-8") as f:
- for line in f:
- line = line.strip()
- if not line:
- continue
- try:
- out.append(json.loads(line))
- except json.JSONDecodeError:
- continue
- except OSError:
- return []
- return out
+ def _wire_agent_terminal_output() -> None:
+ """Idempotently route background-process output (and tab-close requests) to
+ the desktop, keyed by process id. Read-only agent terminal tabs stream
+ `agent.terminal.output` chunks live instead of polling the output tail, and
+ `process_registry.request_close_terminal` emits `terminal.close` so the agent
+ can drop a tab without killing the process. Events are routed to the window
+ that owns the process (its gateway session); `_emit`/`write_json` is
+ `_stdout_lock`-guarded, so calling it from the registry's reader threads is
+ safe."""
+ from tools.process_registry import process_registry
+ has_output_sink = getattr(process_registry, "on_output", None) is not None
+ has_close_sink = getattr(process_registry, "on_close", None) is not None
+ if has_output_sink and has_close_sink:
+ return
- @method("spawn_tree.save")
- def _(rid, params: dict) -> dict:
- session_id = str(params.get("session_id") or "").strip()
- subagents = params.get("subagents") or []
- if not isinstance(subagents, list) or not subagents:
- return _err(rid, 4000, "subagents list required")
-
- from datetime import datetime
-
- started_at = params.get("started_at")
- finished_at = params.get("finished_at") or time.time()
- label = str(params.get("label") or "")
- ts = datetime.utcfromtimestamp(float(finished_at)).strftime("%Y%m%dT%H%M%S")
- fname = f"{ts}.json"
- d = _spawn_tree_session_dir(session_id or "default")
- path = d / fname
- try:
- payload = {
- "session_id": session_id,
- "started_at": float(started_at) if started_at else None,
- "finished_at": float(finished_at),
- "label": label,
- "subagents": subagents,
- }
- path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
- except OSError as exc:
- return _err(rid, 5000, f"spawn_tree.save failed: {exc}")
+ def _owner_sid_for_process(session) -> str:
+ session_key = str(getattr(session, "session_key", "") or "")
+ if not session_key:
+ return ""
+ with _sessions_lock:
+ for sid, tui_session in _sessions.items():
+ if str(tui_session.get("session_key") or "") == session_key:
+ return sid
+ return ""
- _append_spawn_tree_index(
- d,
- {
- "path": str(path),
- "session_id": session_id,
- "started_at": payload["started_at"],
- "finished_at": payload["finished_at"],
- "label": label,
- "count": len(subagents),
- },
- )
+ def _emit_agent_terminal_output(session, chunk):
+ _emit(
+ "agent.terminal.output",
+ _owner_sid_for_process(session),
+ {"process_id": session.id, "chunk": chunk},
+ )
- return _ok(rid, {"path": str(path), "session_id": session_id})
+ def _emit_agent_terminal_close(session, process_id):
+ # session may be None (process already finished/pruned) — the tab can
+ # still linger and be closed; route to the owning window when we can.
+ sid = _owner_sid_for_process(session) if session is not None else ""
+ _emit("terminal.close", sid, {"process_id": process_id})
+ if not has_output_sink:
+ process_registry.on_output = _emit_agent_terminal_output
+ if not has_close_sink:
+ process_registry.on_close = _emit_agent_terminal_close
- @method("spawn_tree.list")
- def _(rid, params: dict) -> dict:
- session_id = str(params.get("session_id") or "").strip()
- limit = int(params.get("limit") or 50)
- cross_session = bool(params.get("cross_session"))
- if cross_session:
- root = _spawn_trees_root()
- roots = [p for p in root.iterdir() if p.is_dir()]
- else:
- roots = [_spawn_tree_session_dir(session_id or "default")]
-
- entries: list[dict] = []
- for d in roots:
- indexed = _read_spawn_tree_index(d)
- if indexed:
- # Skip index entries whose snapshot file was manually deleted.
- entries.extend(
- e for e in indexed if (p := e.get("path")) and Path(p).exists()
- )
- continue
+ _desktop_ui_wired = False
- # Fallback for legacy (pre-index) sessions: full scan. O(N) reads
- # but only runs once per session until the next save writes the index.
- for p in d.glob("*.json"):
- if p.name == _SPAWN_TREE_INDEX:
- continue
- try:
- stat = p.stat()
- try:
- raw = json.loads(p.read_text(encoding="utf-8"))
- except Exception:
- raw = {}
- subagents = raw.get("subagents") or []
- entries.append(
- {
- "path": str(p),
- "session_id": raw.get("session_id") or d.name,
- "finished_at": raw.get("finished_at") or stat.st_mtime,
- "started_at": raw.get("started_at"),
- "label": raw.get("label") or "",
- "count": len(subagents) if isinstance(subagents, list) else 0,
- }
- )
- except OSError:
- continue
-
- entries.sort(key=lambda e: e.get("finished_at") or 0, reverse=True)
- return _ok(rid, {"entries": entries[:limit]})
-
-
- @method("spawn_tree.load")
- def _(rid, params: dict) -> dict:
- from pathlib import Path
-
- raw_path = str(params.get("path") or "").strip()
- if not raw_path:
- return _err(rid, 4000, "path required")
- # Reject paths escaping the spawn-trees root.
- root = _spawn_trees_root().resolve()
- try:
- resolved = Path(raw_path).resolve()
- resolved.relative_to(root)
- except (ValueError, OSError) as exc:
- return _err(rid, 4030, f"path outside spawn-trees root: {exc}")
+ def _wire_desktop_ui() -> None:
+ """Bridge desktop-only tools (open_preview, focus_pane) to renderer events.
+ Idempotent. The tool hands back the turn's ``HERMES_UI_SESSION_ID`` as
+ ``sid`` so the event routes to the window that asked (``_emit`` /
+ ``write_json`` is ``_stdout_lock``-guarded, so calling it from the tool's
+ thread is safe)."""
+ global _desktop_ui_wired
+ if _desktop_ui_wired:
+ return
try:
- payload = json.loads(resolved.read_text(encoding="utf-8"))
- except (OSError, json.JSONDecodeError) as exc:
- return _err(rid, 5000, f"spawn_tree.load failed: {exc}")
-
- return _ok(rid, payload)
-
-
- @method("session.steer")
- def _(rid, params: dict) -> dict:
- """Inject a user message into the next tool result without interrupting.
+ from tools import desktop_ui
+ except Exception:
+ return
- Mirrors AIAgent.steer(). Safe to call while a turn is running — the text
- lands on the last tool result of the next tool batch and the model sees
- it on its next iteration. No interrupt, no new user turn, no role
- alternation violation.
- """
- text = (params.get("text") or "").strip()
- if not text:
- return _err(rid, 4002, "text is required")
- session, err = _sess_nowait(params, rid)
- if err:
- return err
- agent = session.get("agent")
- if agent is None or not hasattr(agent, "steer"):
- return _err(rid, 4010, "agent does not support steer")
- try:
- accepted = agent.steer(text)
- except Exception as exc:
- return _err(rid, 5000, f"steer failed: {exc}")
- if accepted:
- # Record the correction on the live turn exactly like session.redirect
- # does. Without this, a resume/reconnect while the turn is running
- # rebuilds the transcript from the inflight snapshot and the steered
- # text has no user bubble — the "my message vanished on reload" loss.
- with session["history_lock"]:
- _record_inflight_correction(session, text)
- session["last_active"] = time.time()
- return _ok(rid, {"status": "queued" if accepted else "rejected", "text": text})
+ desktop_ui.set_emitter(lambda sid, event, payload: _emit(event, sid, payload))
+ _desktop_ui_wired = True
- @method("session.redirect")
- def _(rid, params: dict) -> dict:
- """Redirect the active model turn while preserving valid work/context."""
- text = (params.get("text") or "").strip()
- if not text:
- return _err(rid, 4002, "text is required")
- session, err = _sess_nowait(params, rid)
- if err:
- return err
- agent = session.get("agent")
- # Turn-build window: a fresh turn flips running=True and kicks off an async
- # agent build, so session["agent"] is briefly None. That is not an
- # unsupported runtime — queue the correction server-side so it reaches the
- # model as the next turn, instead of a misleading 4010 the client silently
- # swallows into a lost follow-up.
- if agent is None and session.get("running"):
- _enqueue_prompt(session, text, current_transport() or _stdio_transport)
- session["last_active"] = time.time()
- return _ok(rid, {"status": "queued", "text": text})
- if (
- agent is None
- or getattr(agent, "_supports_active_turn_redirect", False) is not True
- or not hasattr(agent, "redirect")
- ):
- return _err(rid, 4010, "agent does not support active-turn redirect")
- try:
- accepted = agent.redirect(text)
- except Exception as exc:
- return _err(rid, 5000, f"redirect failed: {exc}")
- if accepted:
- with session["history_lock"]:
- _record_inflight_correction(session, text)
- session["last_active"] = time.time()
- return _ok(
- rid,
- {"status": "redirected" if accepted else "rejected", "text": text},
+ def _start_notification_poller(sid: str, session: dict) -> threading.Event:
+ """Start the background notification poller for a TUI session."""
+ _wire_agent_terminal_output()
+ _wire_desktop_ui()
+ stop = threading.Event()
+ t = threading.Thread(
+ target=_notification_poller_loop,
+ args=(stop, sid, session),
+ daemon=True,
)
+ t.start()
+ return stop
- @method("terminal.resize")
- def _(rid, params: dict) -> dict:
- session, err = _sess_nowait(params, rid)
- if err:
- return err
- session["cols"] = int(params.get("cols", 80))
- return _ok(rid, {"cols": session["cols"]})
-
-
- # ── Methods: prompt ──────────────────────────────────────────────────
-
-
- @method("prompt.submit")
- def _(rid, params: dict) -> dict:
- from hermes_cli.input_sanitize import sanitize_user_prompt_text
-
- sid = params.get("session_id", "")
- raw_text = params.get("text", "")
- text = sanitize_user_prompt_text(raw_text) if isinstance(raw_text, str) else raw_text
- # Typed bare stop phrase while backend voice mode is active ends the
- # voice chat instead of sending "stop" to the agent — the typed twin of
- # the spoken stop phrase (PR #73106), applied at the ONE server-side
- # choke point every TUI submit passes through. Guarded on voice mode
- # being ON: typed "stop" outside a voice chat is a normal message.
- # (The desktop's voice conversation is renderer-owned and never flips
- # the backend flag, so it handles its own typed stop client-side.)
- if isinstance(text, str) and _voice_mode_enabled():
+ def _run_prompt_submit(
+ rid, sid: str, session: dict, text: Any, *, display_kind: str | None = None,
+ display_metadata: dict | None = None,
+ ) -> None:
+ with session["history_lock"]:
+ history = list(session["history"])
+ history_version = int(session.get("history_version", 0))
+ images = list(session.get("attached_images", []))
+ session["attached_images"] = []
+ inflight = session.get("inflight_turn")
+ # A retained failed turn (see _fail_inflight_turn) is a stale leftover
+ # by the time a new turn starts — replace it, never append onto it.
+ if not isinstance(inflight, dict) or inflight.get("status") == "error":
+ _start_inflight_turn(session, text)
+ agent = session["agent"]
+ if hasattr(agent, "clear_interrupt"):
try:
- from tools.voice_mode import is_voice_stop_phrase
-
- typed_stop = is_voice_stop_phrase(text)
+ agent.clear_interrupt()
except Exception:
- typed_stop = False
- if typed_stop:
- os.environ["HERMES_VOICE"] = "0"
- os.environ["HERMES_VOICE_TTS"] = "0"
- try:
- from hermes_cli.voice import stop_continuous
-
- stop_continuous()
- except Exception:
- pass
- try:
- _tts_stream_stop(user_barge=False)
- except Exception:
- pass
- _voice_emit("voice.transcript", {"stop_phrase": True, "typed": True})
- logger.info("prompt.submit: typed stop phrase — voice chat ended")
- return _ok(rid, {"voice_stopped": True})
- truncate_user_ordinal = params.get("truncate_before_user_ordinal")
- if params.get("interrupted"):
- # Client-side barge-in (desktop VAD / typing over playback) — latch it
- # so this turn's model message carries the interruption note.
- from tools.tts_streaming import mark_speech_interrupted
-
- mark_speech_interrupted()
- session, err = _sess_nowait(params, rid)
- if err:
- return err
- if (limit_message := _ensure_active_session_slot(sid, session)) is not None:
- return _err(rid, 4090, limit_message)
- if truncate_user_ordinal is not None and isinstance(text, str):
- # A rewind/regenerate replays a turn from what the transcript shows. A
- # skill turn shows its invocation, so re-expand it here — otherwise
- # re-running `/work fix it` sends the agent nine literal characters
- # instead of the skill it originally loaded.
- text = _expand_skill_invocation_for_replay(
- text, str(session.get("session_key") or "")
- )
- isolation_cfg = _load_dashboard_process_isolation_config()
- turn_isolation = _session_uses_compute_host(session, isolation_cfg)
- # Re-bind to the current client transport for this request. This keeps
- # streaming events on the active websocket even if an earlier disconnect
- # or fallback moved the session transport to stdio.
- if (t := current_transport()) is not None:
- session["transport"] = t
- while True:
- busy_transport = None
- with session["history_lock"]:
- if session.get("running"):
- # Don't reject a mid-turn prompt — queue it (and, by default,
- # interrupt the live turn) so it runs as the next turn. The
- # provider interrupt itself must happen after this lock is
- # released: a non-interruptible tool may keep it waiting.
- busy_transport = t or session.get("transport")
- else:
- break
- busy_response = _handle_busy_submit(
- rid, sid, session, text, busy_transport,
- queued=bool(params.get("queued")),
- )
- if busy_response is not None:
- return busy_response
- # The old turn finished between the two lock acquisitions. Retry the
- # claim so this prompt starts normally instead of being stranded in a
- # queue whose drain already ran.
+ pass
+ _emit("message.start", sid)
- with session["history_lock"]:
- # A watch session's run lives in the PARENT turn, so its own running
- # flag is False — without this, typing mid-run builds a second agent
- # racing the in-flight child on the same stored session (interleaved
- # transcript, stale fork). After the run completes, submitting is fine:
- # the upgrade resumes the child's transcript as a normal conversation.
- if session.get("lazy") and _child_run_active(str(session.get("session_key") or "")):
- return _err(rid, 4009, "subagent still running — wait for it to finish")
- if truncate_user_ordinal is not None:
- try:
- ordinal = int(truncate_user_ordinal)
- except (TypeError, ValueError):
- return _err(rid, 4004, "truncate_before_user_ordinal must be an integer")
- history = session.get("history", [])
- user_indices = [
- i for i, m in enumerate(history)
- if m.get("role") == "user" and not m.get("display_kind")
- ]
- # Reject out-of-range ordinals on BOTH ends. A negative value would
- # otherwise sail past the upper-bound check and hit Python's negative
- # indexing below (user_indices[-1] -> the LAST user turn), silently
- # truncating history to everything before it and persisting that loss
- # via replace_messages — an unrecoverable overwrite of the session DB.
- if ordinal < 0 or ordinal >= len(user_indices):
- return _err(rid, 4018, "target user message is no longer in session history")
- truncated = history[: user_indices[ordinal]]
- # Stale clients can attach truncate_before_user_ordinal=0 to an
- # ordinary submit. That resolves to history[:0] == [] and
- # replace_messages() DELETEs every durable row — silent total
- # transcript loss. Refuse the empty-truncation edge unless the
- # client explicitly opts in (legitimate restore/regenerate of the
- # first user turn).
- if (
- not truncated
- and history
- and not is_truthy_value(params.get("confirm_empty_truncate"))
- ):
- logger.warning(
- "prompt.submit: REFUSED empty truncation of session %s "
- "(%d messages would be wiped; ordinal=%d).",
- sid,
- len(history),
- ordinal,
- )
- return _err(
- rid,
- 4028,
- "truncation would erase the entire session transcript; "
- "resubmit with confirm_empty_truncate=true if this is intended",
- )
- # Info for routine rewind/edit cuts; warning only when the client
- # explicitly opts into wiping the whole transcript.
- log_fn = logger.warning if not truncated else logger.info
- log_fn(
- "prompt.submit: truncating session %s history %d -> %d messages "
- "(ordinal=%d)",
- sid,
- len(history),
- len(truncated),
- ordinal,
+ def run():
+ approval_token = None
+ session_tokens = []
+ home_token = None # per-turn HERMES_HOME override for a resumed remote profile
+ secret_token = None
+ goal_followup = None # set by the post-turn goal hook below
+ result = None # turn outcome; read after the finally for leftover /steer
+ tts_queue = None # streaming-TTS feed for this turn (voice mode)
+ thinking_started = False # ambient thinking sound armed for this turn
+ one_turn_restore = session.pop("one_turn_model_restore", None)
+ # True once a failed turn's snapshot was retained for resume replay —
+ # tells the finally below to skip the normal inflight clear.
+ turn_error_retained = False
+ # Durable crash marker: written before the turn runs, retired the
+ # moment its outcome reaches the client (see _retire_turn_marker).
+ # Any concluded turn — success, handled error, interrupt — retires
+ # it, so a marker that survives means the process died mid-turn;
+ # session.resume auto-continues from it. Compression can rotate
+ # session_key mid-turn, so remember the key we wrote under.
+ marker_home = _session_home(session)
+ marker_key = str(session.get("session_key") or "")
+ marker_attempt = int(session.pop("_auto_continue_attempt", 0) or 0)
+ marker_text = session.pop("_auto_continue_prompt", None) or text
+ if isinstance(marker_text, str) and marker_text.strip():
+ record_turn_start(marker_home, marker_key, marker_text, attempts=marker_attempt)
+ try:
+ from tools.approval import (
+ reset_current_session_key,
+ set_current_session_key,
)
- session["history"] = truncated
- session["history_version"] = int(session.get("history_version", 0)) + 1
- if (db := _get_db()) is not None:
- try:
- db.replace_messages(session["session_key"], truncated)
- except Exception as exc:
- print(f"[tui_gateway] prompt.submit: replace_messages failed: {exc}", file=sys.stderr)
- session["running"] = True
- session["_turn_cancel_requested"] = False
- session["last_active"] = time.time()
- _start_inflight_turn(session, text)
- if turn_isolation:
- isolated_response = _submit_prompt_to_compute_host(rid, sid, session, text)
- if not isolated_response.get("error"):
- return isolated_response
- logger.warning(
- "compute-host dispatch failed for session %s; falling back inline: %s",
- sid,
- isolated_response["error"].get("message", "unknown error"),
- )
-
- # Persist the DB row lazily, now that the user has actually sent a message.
- _ensure_session_db_row(session)
- # A branch becomes real here: copy its parent's transcript into the row so it
- # resumes with full context (the agent won't persist the seed itself).
- _persist_branch_seed(session)
- _start_agent_build(sid, session)
-
- def run_after_agent_ready() -> None:
- # Patient wait (#63078): the user's message is already the accepted
- # in-flight turn, so a slow deferred build must not eat it. The wait
- # delivers the prompt when the still-running build completes, honors a
- # cancel promptly, notices the user once past the slow threshold, and
- # only errors when the build itself fails or the bounded cap expires.
- err = _wait_agent_for_prompt(session, rid, sid)
- if err:
- # Terminal frame + retained snapshot (not a bare "error" event +
- # cleared inflight): if the client is disconnected right now, the
- # retained snapshot is the only way resume can show this failure.
- _emit_terminal_turn_error(
- sid,
- session,
- (err.get("error") or {}).get("message", "agent initialization failed"),
+ approval_token = set_current_session_key(session["session_key"])
+ session_tokens = _set_session_context(
+ session["session_key"],
+ ui_session_id=sid,
)
- with session["history_lock"]:
- session["running"] = False
- session["last_active"] = time.time()
- _emit("session.info", sid, _session_info(session.get("agent"), session))
- return
- with session["history_lock"]:
- if session.get("_turn_cancel_requested") or not session.get("running"):
- session["running"] = False
- _clear_inflight_turn(session)
- # Surface the cancellation to the client. Without this emit the
- # turn vanishes silently — the Desktop sees `prompt.submit`
- # return `{"status": "streaming"}` but never receives a
- # `message.start` or `error` event, so the composer shows no
- # feedback (issue #63078 server-side half). Match the
- # `_wait_agent` error branch above: emit, then bail.
- _emit(
- "error",
- sid,
- {
- "message": "Turn cancelled before the agent was ready"
- if session.get("_turn_cancel_requested")
- else "Session no longer running before the agent was ready"
- },
- )
- return
- _run_prompt_submit(rid, sid, session, text)
+ _profile_home_str = session.get("profile_home")
+ if _profile_home_str:
+ home_token = set_hermes_home_override(_profile_home_str)
+ secret_token = set_secret_scope(build_profile_secret_scope(Path(_profile_home_str)))
+ # The sudo password callback is thread-local (tools.terminal_tool
+ # _callback_tls), so wiring it on the build thread doesn't reach this
+ # turn thread — terminal sudo prompts would fall through to /dev/tty
+ # and hang the headless gateway. Re-wire here so the prompt routes to
+ # the sudo.request overlay. (secret capture is a module global, so
+ # re-running is a harmless no-op.)
+ _wire_callbacks(sid)
+ # Skip the config-model sync while a /model --once override is
+ # active: the once-model is intentionally not pinned as a session
+ # model_override (it must not persist), so without this guard the
+ # sync would see "agent model != config model" and clobber the
+ # once-override back to the config model before the turn runs
+ # (#29923 review defect). Any config.yaml change is adopted on
+ # the NEXT turn, after the finally-restore below.
+ if not one_turn_restore:
+ _sync_agent_model_with_config(sid, session)
+ cwd = _session_cwd(session)
+ _register_session_cwd(session)
+ cols = session.get("cols", 80)
+ streamer = make_stream_renderer(cols)
+ prompt = text
- run_thread = threading.Thread(target=run_after_agent_ready, daemon=True)
- # Keep a handle so session.interrupt can tell a live turn from a stuck
- # `running` flag (a turn that died without clearing it) and recover the latter.
- session["_run_thread"] = run_thread
- run_thread.start()
- return _ok(rid, {"status": "streaming"})
+ if isinstance(prompt, str) and "@" in prompt:
+ from agent.context_references import preprocess_context_references
+ from agent.model_metadata import get_model_context_length
+ ctx_len = get_model_context_length(
+ getattr(agent, "model", "") or _resolve_model(),
+ base_url=getattr(agent, "base_url", "") or "",
+ api_key=getattr(agent, "api_key", "") or "",
+ provider=getattr(agent, "provider", "") or "",
+ config_context_length=getattr(
+ agent, "_config_context_length", None
+ ),
+ )
+ ctx = preprocess_context_references(
+ prompt,
+ cwd=cwd,
+ allowed_root=cwd,
+ context_length=ctx_len,
+ )
+ if ctx.blocked:
+ _emit(
+ "error",
+ sid,
+ {
+ "message": "\n".join(ctx.warnings)
+ or "Context injection refused."
+ },
+ )
+ return
+ prompt = ctx.message
- def _notification_event_belongs_elsewhere(sid: str, session: dict, evt: dict) -> bool:
- """True if ``evt`` is owned by a *different* live session.
+ # Decide image routing per-turn based on active provider/model.
+ # "native" → pass pixels to the main model as OpenAI-style content
+ # parts (adapters translate for Anthropic/Gemini/Bedrock/etc.).
+ # "text" → pre-analyze with vision_analyze and prepend the text.
+ # See agent/image_routing.py for the full decision table.
+ run_message: Any = prompt
+ if images:
+ try:
+ from agent.image_routing import (
+ decide_image_input_mode,
+ build_native_content_parts,
+ )
+ from hermes_cli.config import load_config as _tui_load_config
- Background completions carry the ``session_key`` of the session that started
- the work. Async delegation completions from the desktop also carry
- ``origin_ui_session_id``: the live TUI tab/window that commissioned them.
- Since all desktop sessions share one process-wide completion queue, each
- poller must skip events it doesn't own so a detached result surfaces in the
- launching session, not whichever poller happened to dequeue first.
- """
- evt_ui_sid = str(evt.get("origin_ui_session_id") or "")
- if evt_ui_sid:
- if evt_ui_sid == str(sid or "") and not session.get("_finalized"):
- return False
- try:
- with _sessions_lock:
- owner_live = evt_ui_sid in _sessions and not _sessions[evt_ui_sid].get("_finalized")
- except Exception:
- owner_live = False
- if owner_live:
- return True
- # If the exact UI tab is gone, fall through to durable session_key
- # routing. That avoids wrong-session delivery while still allowing a
- # resumed continuation with the same durable key/lineage to claim it.
-
- evt_key = str(evt.get("session_key") or "")
- if not evt_key:
- return False
-
- current_keys = {
- str(session.get("session_key") or ""),
- _session_lookup_key(session, fallback=sid),
- }
-
- # Compression can rotate AIAgent.session_id while the detached child is
- # still running. Resolve the event's original key to its continuation tip so
- # an event captured before or after compression still maps to the same live
- # desktop session instead of becoming an orphan that any poller may consume.
- resolved_key = evt_key
- try:
- db = _get_db()
- if db is not None:
- resolved_key = db.resolve_resume_session_id(evt_key) or evt_key
- except Exception:
- resolved_key = evt_key
-
- # If the key has a live continuation, prefer that continuation over the
- # compressed parent. Otherwise a stale parent tab could consume the event
- # before the real current conversation sees it.
- if resolved_key != evt_key:
- if resolved_key in current_keys:
- return False
- try:
- with _sessions_lock:
- continuation_live = any(
- not s.get("_finalized")
- and (
- str(s.get("session_key") or "") == resolved_key
- or _session_lookup_key(s, fallback="") == resolved_key
+ _cfg = _tui_load_config()
+ _provider, _model = _active_image_routing_identity(agent)
+ _mode = decide_image_input_mode(
+ _provider,
+ _model,
+ _cfg,
+ requested_provider=getattr(
+ agent, "requested_provider", ""
+ ),
)
- for s in _sessions.values()
- )
- except Exception:
- continuation_live = False
- if continuation_live:
- return True
+ if getattr(agent, "api_mode", "") == "codex_app_server":
+ _mode = "text"
+ except Exception as _img_exc:
+ print(
+ f"[tui_gateway] image_routing decision failed, defaulting to text: {_img_exc}",
+ file=sys.stderr,
+ )
+ _mode = "text"
- if evt_key in current_keys:
- return False
+ if _mode == "native":
+ try:
+ _parts, _skipped = build_native_content_parts(
+ prompt,
+ images,
+ )
+ if _skipped:
+ print(
+ f"[tui_gateway] native image attachment skipped {len(_skipped)} unreadable path(s)",
+ file=sys.stderr,
+ )
+ if any(p.get("type") == "image_url" for p in _parts):
+ run_message = _parts
+ else:
+ run_message = _enrich_with_attached_images(prompt, images)
+ except Exception as _img_exc:
+ print(
+ f"[tui_gateway] native attach failed, falling back to text: {_img_exc}",
+ file=sys.stderr,
+ )
+ run_message = _enrich_with_attached_images(prompt, images)
+ else:
+ run_message = _enrich_with_attached_images(prompt, images)
- try:
- with _sessions_lock:
- snapshot = list(_sessions.values())
- except Exception:
- # If we can't safely enumerate live sessions, fail open so we don't
- # crash the poller thread or drop the event.
- return False
+ # Streaming TTS: voice-mode replies are spoken sentence-by-sentence
+ # as tokens arrive (CLI parity) instead of after the full turn.
+ # begin() first — it cuts any still-speaking previous turn, and
+ # that cut IS this turn's barge-in, so it must latch before we
+ # consume the latch below.
+ tts_queue = _tts_stream_begin()
- return any(
- s is not session
- and not s.get("_finalized")
- and (
- str(s.get("session_key") or "") in {evt_key, resolved_key}
- or _session_lookup_key(s, fallback="") in {evt_key, resolved_key}
- )
- for s in snapshot
- )
+ # Full-duplex agent-turn listener: armed at utterance-submit so
+ # the user can interject DURING generation, not just during
+ # playback. _tts_stream_begin arms it too when a pipeline
+ # starts; this covers voice mode without working TTS.
+ if _voice_mode_enabled() and _voice_cfg_dict().get("barge_in", True):
+ _arm_full_duplex_listener()
+ # Ambient "thinking" sound (voice mode only): calm bubble blips
+ # while the agent works with no audio flowing, so long
+ # thinking/tool stretches don't read as a dead session. Per-blip
+ # gate skips while real TTS audio flows or the mic is capturing;
+ # stopped in the finally the instant the turn ends.
+ # voice.thinking_sound config-gates it; macOS TCC handled inside.
+ thinking_started = False
+ if _voice_mode_enabled():
+ try:
+ from tools.voice_mode import (
+ is_audio_output_active,
+ start_thinking_sound,
+ )
- def _session_owns_notification_event(sid: str, session: dict, evt: dict) -> bool:
- """True iff *this* session PROVABLY owns ``evt``.
+ def _thinking_should_play() -> bool:
+ if is_audio_output_active():
+ return False
+ try:
+ from hermes_cli.voice import is_continuous_active
- Positive ownership — the mirror of ``_notification_event_belongs_elsewhere``
- minus its orphan-adoption fallback. An event owns-matches when its
- ``origin_ui_session_id`` is this live session, or its ``session_key``
- (raw or resolved through the compression chain) matches this session's
- key/lineage. Used as the fail-closed gate for every addressed notification:
- "not provably elsewhere" is NOT good enough to inject a payload into this
- chat (#55578).
- """
- if session.get("_finalized"):
- return False
- if str(evt.get("origin_ui_session_id") or "") == str(sid or ""):
- return True
- evt_key = str(evt.get("session_key") or "")
- if not evt_key:
- return False
- current_keys = {
- str(session.get("session_key") or ""),
- _session_lookup_key(session, fallback=sid),
- }
- if evt_key in current_keys:
- return True
- try:
- db = _get_db()
- resolved_key = (
- db.resolve_resume_session_id(evt_key) if db is not None else evt_key
- ) or evt_key
- except Exception:
- resolved_key = evt_key
- return resolved_key in current_keys
+ return not is_continuous_active()
+ except Exception:
+ return True
+ thinking_started = start_thinking_sound(
+ should_play=_thinking_should_play
+ )
+ except Exception:
+ thinking_started = False
- def _notification_event_requires_owner(evt: dict) -> bool:
- """Whether ``evt`` must be positively claimed before TUI delivery."""
- return evt.get("type") == "async_delegation" or bool(
- str(evt.get("origin_ui_session_id") or "")
- or str(evt.get("session_key") or "")
- )
+ # Barged mid-speech? Tell the model (API-message note, same
+ # enrichment channel as attached images) so it can react
+ # ("rude!") instead of being oblivious to its own interruption.
+ from tools.tts_streaming import SPEECH_INTERRUPTED_NOTE, take_speech_interrupted
+ if take_speech_interrupted():
+ if isinstance(run_message, str):
+ run_message = f"{SPEECH_INTERRUPTED_NOTE}\n\n{run_message}"
+ elif isinstance(run_message, list):
+ run_message = [{"type": "text", "text": SPEECH_INTERRUPTED_NOTE}, *run_message]
- def _notification_event_dedup_key(evt: dict) -> tuple:
- """Return the UI-emission identity for a process notification event.
+ def _stream(delta):
+ with session["history_lock"]:
+ _append_inflight_delta(session, delta)
+ payload = {"text": delta}
+ if streamer and (r := streamer.feed(delta)) is not None:
+ payload["rendered"] = r
+ if tts_queue is not None and isinstance(delta, str):
+ tts_queue.put(delta)
+ _emit("message.delta", sid, payload)
- Completion events are terminal notifications for a background process, so
- they remain one-shot per process session. Watch-match events are not
- terminal: a single background process can legitimately match the same or
- different patterns many times, so include event-specific content to avoid
- suppressing later distinct matches from the same process.
- """
- evt_type = evt.get("type", "completion")
- evt_sid = evt.get("session_id", "")
- if evt_type == "watch_match":
- return (
- evt_sid,
- evt_type,
- evt.get("command", ""),
- evt.get("pattern", ""),
- evt.get("output", ""),
- evt.get("suppressed", 0),
- evt.get("message_id", ""),
- )
- if evt_type.startswith("watch_overflow_") or evt_type == "watch_disabled":
- return (
- evt_sid,
- evt_type,
- evt.get("command", ""),
- evt.get("message", ""),
- evt.get("suppressed", 0),
- )
- if evt_type == "async_delegation":
- # Async-delegation completions have no process session_id; without
- # this the fallthrough keys every one as ("", "async_delegation")
- # and the second completion's status update is suppressed forever.
- return (evt.get("delegation_id", ""), evt_type)
- return (evt_sid, evt_type)
+ # Surface interim assistant text (commentary emitted alongside
+ # tool calls, or the attempted final answer before a verify-on-stop
+ # nudge) so the desktop can seal it as its own segment instead of
+ # losing it when message.complete replaces the streaming buffer.
+ # Gated on display.interim_assistant_messages (default true).
+ if _load_interim_assistant_messages():
+ def _interim_assistant_cb(text: str, *, already_streamed: bool = False) -> None:
+ _emit("message.interim", sid, {
+ "text": text,
+ "already_streamed": already_streamed,
+ })
+ agent.interim_assistant_callback = _interim_assistant_cb
+ else:
+ agent.interim_assistant_callback = None
- # Mirror gateway/kanban_watchers.py TERMINAL_KINDS: claim silent kinds too so
- # the cursor advances past them and they can't wedge a later completed/blocked
- # event behind an unclaimed row.
- _KANBAN_NOTIFY_KINDS = (
- "completed", "blocked", "gave_up", "crashed", "timed_out",
- "status", "archived", "unblocked",
- )
- _KANBAN_SILENT_KINDS = frozenset({"archived", "unblocked"})
- _KANBAN_POLL_SECONDS = 5.0
-
-
- def _format_kanban_event_text(sub: dict, task, ev, board_slug: str) -> Optional[str]:
- """Single-line notification text for one kanban event.
-
- Wording mirrors the gateway notifier (gateway/kanban_watchers.py) so a
- task completion reads the same in the TUI as it does on Telegram.
- Returns None for kinds that are claimed but intentionally silent.
- """
- kind = getattr(ev, "kind", "")
- if not kind or kind in _KANBAN_SILENT_KINDS:
- return None
- task_id = sub.get("task_id", "")
- title = (getattr(task, "title", None) or task_id)[:120]
- board_tag = f"[{board_slug}] " if board_slug else ""
- who = getattr(task, "assignee", None) or ""
- tag = f"@{who} " if who else ""
- payload = getattr(ev, "payload", None) or {}
- if kind == "completed":
- handoff = ""
- summary = payload.get("summary")
- if summary:
- lines = str(summary).strip().splitlines()
- handoff = f"\n{lines[0][:200]}" if lines else ""
- elif getattr(task, "result", None):
- lines = str(task.result).strip().splitlines()
- handoff = f"\n{lines[0][:160]}" if lines else ""
- return f"✔ {board_tag}{tag}Kanban {task_id} done — {title}{handoff}"
- if kind == "blocked":
- reason = f": {str(payload.get('reason'))[:160]}" if payload.get("reason") else ""
- return f"⏸ {board_tag}{tag}Kanban {task_id} blocked{reason}"
- if kind == "gave_up":
- err = f"\n{str(payload.get('error'))[:200]}" if payload.get("error") else ""
- return f"✖ {board_tag}{tag}Kanban {task_id} gave up after repeated spawn failures{err}"
- if kind == "crashed":
- return f"✖ {board_tag}{tag}Kanban {task_id} worker crashed (pid gone); dispatcher will retry"
- if kind == "timed_out":
- limit = 0
- try:
- limit = int(payload.get("limit_seconds") or 0)
- except (TypeError, ValueError):
- pass
- return f"⏱ {board_tag}{tag}Kanban {task_id} timed out (max_runtime={limit}s); will retry"
- if kind == "status":
- return f"🔄 {board_tag}{tag}Kanban {task_id} → {payload.get('status') or ''}"
- return None
-
-
- def _collect_kanban_notifications(session: dict) -> list:
- """Claim unseen terminal kanban events for this TUI session's subscriptions.
-
- ``kanban_create`` auto-subscribes TUI/desktop sessions with
- ``platform="tui"`` and ``chat_id=HERMES_SESSION_KEY`` (see
- tools/kanban_tools.py ``_maybe_auto_subscribe``). The gateway notifier
- can't deliver those — there is no "tui" messaging adapter — so this
- poller is the delivery path for them (issue #59890). Uses the same
- atomic cursor-claim (``claim_unseen_events_for_sub``) as the gateway
- notifier, so a subscription is delivered exactly once even if a gateway
- and a TUI poll the same board DB.
-
- Returns the list of formatted notification texts (may be empty).
- """
- session_key = str(session.get("session_key") or "")
- if not session_key or session.get("_finalized"):
- return []
- try:
- from hermes_cli import kanban_db as _kb
- except Exception:
- return []
- texts: list = []
- try:
- boards = _kb.list_boards(include_archived=False)
- except Exception:
- try:
- boards = [_kb.read_board_metadata(_kb.DEFAULT_BOARD)]
- except Exception:
- return []
- # Poll each resolved DB path once — multiple slugs can point at the same
- # DB when HERMES_KANBAN_DB pins the board path (same guard as the gateway
- # notifier).
- seen_db_paths: set = set()
- for board_meta in boards:
- slug = (board_meta or {}).get("slug") or _kb.DEFAULT_BOARD
- db_path = (board_meta or {}).get("db_path")
- try:
- resolved = (
- str(Path(db_path).expanduser().resolve())
- if db_path else str(_kb.kanban_db_path(slug).resolve())
- )
- except Exception:
- resolved = f"slug:{slug}"
- if resolved in seen_db_paths:
- continue
- seen_db_paths.add(resolved)
- try:
- conn = _kb.connect(board=slug)
- except Exception:
- continue
- try:
- try:
- subs = _kb.list_notify_subs(conn)
- except Exception:
- continue
- for sub in subs:
- if (sub.get("platform") or "").lower() != "tui":
- continue
- if sub.get("chat_id") != session_key:
- continue
- _old, _new, events = _kb.claim_unseen_events_for_sub(
- conn,
- task_id=sub["task_id"],
- platform=sub["platform"],
- chat_id=sub["chat_id"],
- thread_id=sub.get("thread_id") or "",
- kinds=_KANBAN_NOTIFY_KINDS,
- )
- if not events:
- continue
- task = _kb.get_task(conn, sub["task_id"])
- for ev in events:
- text = _format_kanban_event_text(sub, task, ev, slug)
- if text:
- texts.append(text)
- # Unsubscribe only at a truly final status (done/archived);
- # blocked/crashed subs stay live so a respawned task's next
- # terminal event still reaches the user (same rule as the
- # gateway notifier).
- if task and getattr(task, "status", "") in {"done", "archived"}:
- try:
- _kb.remove_notify_sub(
- conn,
- task_id=sub["task_id"],
- platform=sub["platform"],
- chat_id=sub["chat_id"],
- thread_id=sub.get("thread_id") or "",
- )
- except Exception:
- pass
- finally:
- conn.close()
- return texts
-
-
- def _notification_poller_loop(
- stop_event: threading.Event, sid: str, session: dict
- ) -> None:
- """Poll completion_queue and dispatch notifications autonomously.
-
- Runs in a daemon thread started by _init_session(). Emits a
- status.update (kind=process) for user visibility, then chains an
- agent turn via _run_prompt_submit if the session is idle.
-
- The completion_queue is process-global. In multi-session Desktop each
- poller requeues events owned by another live session and drops addressed
- events whose owner is gone; ownerless legacy notifications remain global.
-
- Also polls ``kanban_notify_subs`` every ``_KANBAN_POLL_SECONDS`` for this
- session's TUI kanban subscriptions and delivers terminal task events the
- same way (status.update + agent turn) — the delivery path
- tools/kanban_tools.py documents for platform="tui" rows (issue #59890).
- """
- from tools.process_registry import process_registry, format_process_notification
-
- _emitted = set() # dedup re-queued events so same completion isn't emitted 50 times while session is busy
- _last_kanban_poll = 0.0
- while not stop_event.is_set() and not session.get("_finalized"):
- _now = time.monotonic()
- if _now - _last_kanban_poll >= _KANBAN_POLL_SECONDS:
- _last_kanban_poll = _now
+ run_kwargs = {
+ "conversation_history": list(history),
+ "stream_callback": _stream,
+ "persist_user_message": (
+ _build_persist_user_message(prompt, images, run_message) if images else prompt
+ ),
+ }
+ # Type a synthesized turn at turn START so the crash persist writes
+ # its row as a timeline event, instead of leaving a raw user bubble
+ # until the turn ends — and forever if it never does, which is
+ # exactly the auto-continue case. The post-turn stamp below is the
+ # fallback for an older agent without the parameter; re-stamping
+ # the same value is a no-op.
try:
- _kanban_texts = _collect_kanban_notifications(session)
- except Exception as _kb_exc:
- print(
- f"[tui_gateway] kanban notification poll failed: "
- f"{type(_kb_exc).__name__}: {_kb_exc}",
- file=sys.stderr,
- )
- _kanban_texts = []
- if _kanban_texts:
- for _kb_text in _kanban_texts:
- _emit("status.update", sid, {"kind": "process", "text": _kb_text})
- # Events are cursor-claimed (never re-queued), so buffer them
- # until the session is idle instead of dropping the agent turn.
- session.setdefault("_kanban_pending", []).extend(_kanban_texts)
- _pending = session.get("_kanban_pending") or []
- if _pending:
- _batch: list = []
- with session["history_lock"]:
- if not session.get("running"):
- session["running"] = True
- _batch = list(_pending)
- session["_kanban_pending"] = []
- if _batch:
- rid = f"__notif__{int(time.time() * 1000)}"
- try:
- _emit("message.start", sid)
- _run_prompt_submit(rid, sid, session, "\n".join(_batch))
- except Exception as exc:
- print(
- f"[tui_gateway] kanban notification dispatch failed: "
- f"{type(exc).__name__}: {exc}",
- file=sys.stderr,
- )
- with session["history_lock"]:
- session["running"] = False
- try:
- evt = process_registry.completion_queue.get(timeout=0.5)
- except Exception:
- continue
-
- # Multiple desktop sessions share this one process-wide queue. Only
- # consume events that belong to *this* session — otherwise a background
- # process started in session A would surface its completion in whichever
- # session's poller happened to wake first (Ben's "reported in a
- # different session" bug). Leave foreign events for their owner.
- if _notification_event_belongs_elsewhere(sid, session, evt):
- process_registry.completion_queue.put(evt)
- time.sleep(0.1)
- continue
-
- # What reaches here is not owned by another LIVE session. Addressed
- # events still require positive proof before injection: exact UI origin,
- # direct durable key, or compression lineage. If none proves ownership,
- # the event is orphaned and must not be adopted by this chat. Truly
- # ownerless ordinary notifications retain legacy global delivery.
- requires_owner = _notification_event_requires_owner(evt)
- if requires_owner and not _session_owns_notification_event(sid, session, evt):
- log = (
- logger.warning
- if evt.get("type") == "async_delegation"
- else logger.debug
- )
- log(
- "Dropping unowned %s notification (origin=%r key=%r) instead "
- "of delivering to session %s",
- evt.get("type", "completion"),
- str(evt.get("origin_ui_session_id") or ""),
- str(evt.get("session_key") or ""),
- sid,
- )
- continue
-
- _evt_sid = evt.get("session_id", "")
- if evt.get("type") == "completion" and process_registry.is_completion_consumed(_evt_sid):
- continue
-
- text = format_process_notification(evt)
- if not text:
- continue
-
- # Only emit the same notification identity to TUI once — re-queued
- # completions get re-emitted every 0.5s otherwise when session is busy,
- # while distinct watch_match events from the same process must remain
- # visible independently.
- _dedup_key = _notification_event_dedup_key(evt)
- if _dedup_key not in _emitted:
- _emit("status.update", sid, {"kind": "process", "text": text})
- _emitted.add(_dedup_key)
-
- _requeued = False
- with session["history_lock"]:
- if session.get("running"):
- process_registry.completion_queue.put(evt)
- _requeued = True
- else:
- session["running"] = True
- if _requeued:
- # Back off before re-polling: the re-queued event keeps the queue
- # non-empty, so without a sleep this loop spins at full speed
- # (100% CPU, GIL churn) for as long as the session stays busy.
- time.sleep(0.25)
- continue
-
- rid = f"__notif__{int(time.time() * 1000)}"
- from tools.async_delegation import (
- claim_event_delivery, complete_event_delivery, release_event_delivery,
- )
- _claim = claim_event_delivery(evt, "tui-poller")
- if _claim is None:
- continue
- try:
- _emit("message.start", sid)
- if evt.get("type") == "async_delegation":
- _run_prompt_submit(
- rid,
- sid,
- session,
- text,
- display_kind="async_delegation_complete",
- display_metadata=_async_delegation_display_metadata(evt),
- )
- else:
- _run_prompt_submit(rid, sid, session, text)
- complete_event_delivery(evt, _claim)
- except Exception as exc:
- release_event_delivery(evt, _claim)
- print(
- f"[tui_gateway] notification poller dispatch failed: "
- f"{type(exc).__name__}: {exc}",
- file=sys.stderr,
- )
- with session["history_lock"]:
- session["running"] = False
-
- # Drain any remaining events after stop signal (process all pending
- # before exiting so nothing is lost on shutdown). Events owned by other
- # live sessions are set aside and re-queued so their poller still sees them.
- # Orphaned events (owner gone) are dropped — same guard as the main loop.
- deferred: list = []
- while not process_registry.completion_queue.empty():
- try:
- evt = process_registry.completion_queue.get_nowait()
- except Exception:
- break
- if _notification_event_belongs_elsewhere(sid, session, evt):
- deferred.append(evt)
- continue
- # Same positive-proof rule as the live loop. Preserve the existing
- # shutdown behavior for orphaned delegation payloads by deferring them
- # for a later resume; ordinary addressed orphans are dropped.
- requires_owner = _notification_event_requires_owner(evt)
- if requires_owner and not _session_owns_notification_event(sid, session, evt):
- if evt.get("type") == "async_delegation":
- deferred.append(evt)
- else:
- logger.debug(
- "Dropping unowned %s notification during shutdown drain "
- "(origin=%r key=%r)",
- evt.get("type", "completion"),
- str(evt.get("origin_ui_session_id") or ""),
- str(evt.get("session_key") or ""),
- )
- continue
- _evt_sid = evt.get("session_id", "")
- if evt.get("type") == "completion" and process_registry.is_completion_consumed(_evt_sid):
- continue
- text = format_process_notification(evt)
- if not text:
- continue
-
- _dedup_key = _notification_event_dedup_key(evt)
- if _dedup_key not in _emitted:
- _emit("status.update", sid, {"kind": "process", "text": text})
- _emitted.add(_dedup_key)
-
- with session["history_lock"]:
- if session.get("running"):
- process_registry.completion_queue.put(evt)
- break
- session["running"] = True
-
- rid = f"__notif__{int(time.time() * 1000)}"
- from tools.async_delegation import (
- claim_event_delivery, complete_event_delivery, release_event_delivery,
- )
- _claim = claim_event_delivery(evt, "tui-poller")
- if _claim is None:
- continue
- try:
- _emit("message.start", sid)
- if evt.get("type") == "async_delegation":
- _run_prompt_submit(
- rid,
- sid,
- session,
- text,
- display_kind="async_delegation_complete",
- display_metadata=_async_delegation_display_metadata(evt),
- )
- else:
- _run_prompt_submit(rid, sid, session, text)
- complete_event_delivery(evt, _claim)
- except Exception as exc:
- release_event_delivery(evt, _claim)
- print(
- f"[tui_gateway] notification poller dispatch failed: "
- f"{type(exc).__name__}: {exc}",
- file=sys.stderr,
- )
- with session["history_lock"]:
- session["running"] = False
-
- # Hand any other sessions' events back to the shared queue.
- for evt in deferred:
- process_registry.completion_queue.put(evt)
-
-
- def _async_delegation_display_metadata(evt: dict) -> dict:
- """Build display-only metadata before the completion event is formatted."""
- raw_results = evt.get("results")
- results: list[dict] = [
- result for result in raw_results if isinstance(result, dict)
- ] if isinstance(raw_results, list) else []
- task_count = len(results) or 1
- completed_count = sum(
- 1 for result in results
- if result.get("status") in {"completed", "success"}
- )
- failed_count = sum(
- 1 for result in results
- if result.get("status") in {"failed", "error"}
- )
- metadata = {
- "delegation_id": str(evt.get("delegation_id") or ""),
- "task_count": task_count,
- "completed_count": completed_count or task_count - failed_count,
- "failed_count": failed_count,
- }
- duration = evt.get("total_duration_seconds") or evt.get("duration_seconds")
- if isinstance(duration, (int, float)):
- metadata["duration_seconds"] = duration
- return metadata
-
-
- def _wire_agent_terminal_output() -> None:
- """Idempotently route background-process output (and tab-close requests) to
- the desktop, keyed by process id. Read-only agent terminal tabs stream
- `agent.terminal.output` chunks live instead of polling the output tail, and
- `process_registry.request_close_terminal` emits `terminal.close` so the agent
- can drop a tab without killing the process. Events are routed to the window
- that owns the process (its gateway session); `_emit`/`write_json` is
- `_stdout_lock`-guarded, so calling it from the registry's reader threads is
- safe."""
- from tools.process_registry import process_registry
-
- has_output_sink = getattr(process_registry, "on_output", None) is not None
- has_close_sink = getattr(process_registry, "on_close", None) is not None
- if has_output_sink and has_close_sink:
- return
-
- def _owner_sid_for_process(session) -> str:
- session_key = str(getattr(session, "session_key", "") or "")
- if not session_key:
- return ""
- with _sessions_lock:
- for sid, tui_session in _sessions.items():
- if str(tui_session.get("session_key") or "") == session_key:
- return sid
- return ""
-
- def _emit_agent_terminal_output(session, chunk):
- _emit(
- "agent.terminal.output",
- _owner_sid_for_process(session),
- {"process_id": session.id, "chunk": chunk},
- )
-
- def _emit_agent_terminal_close(session, process_id):
- # session may be None (process already finished/pruned) — the tab can
- # still linger and be closed; route to the owning window when we can.
- sid = _owner_sid_for_process(session) if session is not None else ""
- _emit("terminal.close", sid, {"process_id": process_id})
-
- if not has_output_sink:
- process_registry.on_output = _emit_agent_terminal_output
- if not has_close_sink:
- process_registry.on_close = _emit_agent_terminal_close
-
-
- _desktop_ui_wired = False
-
-
- def _wire_desktop_ui() -> None:
- """Bridge desktop-only tools (open_preview, focus_pane) to renderer events.
-
- Idempotent. The tool hands back the turn's ``HERMES_UI_SESSION_ID`` as
- ``sid`` so the event routes to the window that asked (``_emit`` /
- ``write_json`` is ``_stdout_lock``-guarded, so calling it from the tool's
- thread is safe)."""
- global _desktop_ui_wired
- if _desktop_ui_wired:
- return
- try:
- from tools import desktop_ui
- except Exception:
- return
-
- desktop_ui.set_emitter(lambda sid, event, payload: _emit(event, sid, payload))
- _desktop_ui_wired = True
-
-
- def _start_notification_poller(sid: str, session: dict) -> threading.Event:
- """Start the background notification poller for a TUI session."""
- _wire_agent_terminal_output()
- _wire_desktop_ui()
- stop = threading.Event()
- t = threading.Thread(
- target=_notification_poller_loop,
- args=(stop, sid, session),
- daemon=True,
- )
- t.start()
- return stop
-
-
- def _run_prompt_submit(
- rid, sid: str, session: dict, text: Any, *, display_kind: str | None = None,
- display_metadata: dict | None = None,
- ) -> None:
- with session["history_lock"]:
- history = list(session["history"])
- history_version = int(session.get("history_version", 0))
- images = list(session.get("attached_images", []))
- session["attached_images"] = []
- inflight = session.get("inflight_turn")
- # A retained failed turn (see _fail_inflight_turn) is a stale leftover
- # by the time a new turn starts — replace it, never append onto it.
- if not isinstance(inflight, dict) or inflight.get("status") == "error":
- _start_inflight_turn(session, text)
- agent = session["agent"]
- if hasattr(agent, "clear_interrupt"):
- try:
- agent.clear_interrupt()
- except Exception:
- pass
- _emit("message.start", sid)
-
- def run():
- approval_token = None
- session_tokens = []
- home_token = None # per-turn HERMES_HOME override for a resumed remote profile
- secret_token = None
- goal_followup = None # set by the post-turn goal hook below
- result = None # turn outcome; read after the finally for leftover /steer
- tts_queue = None # streaming-TTS feed for this turn (voice mode)
- thinking_started = False # ambient thinking sound armed for this turn
- one_turn_restore = session.pop("one_turn_model_restore", None)
- # True once a failed turn's snapshot was retained for resume replay —
- # tells the finally below to skip the normal inflight clear.
- turn_error_retained = False
- # Durable crash marker: written before the turn runs, retired the
- # moment its outcome reaches the client (see _retire_turn_marker).
- # Any concluded turn — success, handled error, interrupt — retires
- # it, so a marker that survives means the process died mid-turn;
- # session.resume auto-continues from it. Compression can rotate
- # session_key mid-turn, so remember the key we wrote under.
- marker_home = _session_home(session)
- marker_key = str(session.get("session_key") or "")
- marker_attempt = int(session.pop("_auto_continue_attempt", 0) or 0)
- marker_text = session.pop("_auto_continue_prompt", None) or text
- if isinstance(marker_text, str) and marker_text.strip():
- record_turn_start(marker_home, marker_key, marker_text, attempts=marker_attempt)
- try:
- from tools.approval import (
- reset_current_session_key,
- set_current_session_key,
- )
-
- approval_token = set_current_session_key(session["session_key"])
- session_tokens = _set_session_context(
- session["session_key"],
- ui_session_id=sid,
- )
- _profile_home_str = session.get("profile_home")
- if _profile_home_str:
- home_token = set_hermes_home_override(_profile_home_str)
- secret_token = set_secret_scope(build_profile_secret_scope(Path(_profile_home_str)))
- # The sudo password callback is thread-local (tools.terminal_tool
- # _callback_tls), so wiring it on the build thread doesn't reach this
- # turn thread — terminal sudo prompts would fall through to /dev/tty
- # and hang the headless gateway. Re-wire here so the prompt routes to
- # the sudo.request overlay. (secret capture is a module global, so
- # re-running is a harmless no-op.)
- _wire_callbacks(sid)
- # Skip the config-model sync while a /model --once override is
- # active: the once-model is intentionally not pinned as a session
- # model_override (it must not persist), so without this guard the
- # sync would see "agent model != config model" and clobber the
- # once-override back to the config model before the turn runs
- # (#29923 review defect). Any config.yaml change is adopted on
- # the NEXT turn, after the finally-restore below.
- if not one_turn_restore:
- _sync_agent_model_with_config(sid, session)
- cwd = _session_cwd(session)
- _register_session_cwd(session)
- cols = session.get("cols", 80)
- streamer = make_stream_renderer(cols)
- prompt = text
-
- if isinstance(prompt, str) and "@" in prompt:
- from agent.context_references import preprocess_context_references
- from agent.model_metadata import get_model_context_length
-
- ctx_len = get_model_context_length(
- getattr(agent, "model", "") or _resolve_model(),
- base_url=getattr(agent, "base_url", "") or "",
- api_key=getattr(agent, "api_key", "") or "",
- provider=getattr(agent, "provider", "") or "",
- config_context_length=getattr(
- agent, "_config_context_length", None
- ),
- )
- ctx = preprocess_context_references(
- prompt,
- cwd=cwd,
- allowed_root=cwd,
- context_length=ctx_len,
- )
- if ctx.blocked:
- _emit(
- "error",
- sid,
- {
- "message": "\n".join(ctx.warnings)
- or "Context injection refused."
- },
- )
- return
- prompt = ctx.message
-
- # Decide image routing per-turn based on active provider/model.
- # "native" → pass pixels to the main model as OpenAI-style content
- # parts (adapters translate for Anthropic/Gemini/Bedrock/etc.).
- # "text" → pre-analyze with vision_analyze and prepend the text.
- # See agent/image_routing.py for the full decision table.
- run_message: Any = prompt
- if images:
- try:
- from agent.image_routing import (
- decide_image_input_mode,
- build_native_content_parts,
- )
- from hermes_cli.config import load_config as _tui_load_config
-
- _cfg = _tui_load_config()
- _provider, _model = _active_image_routing_identity(agent)
- _mode = decide_image_input_mode(
- _provider,
- _model,
- _cfg,
- requested_provider=getattr(
- agent, "requested_provider", ""
- ),
- )
- if getattr(agent, "api_mode", "") == "codex_app_server":
- _mode = "text"
- except Exception as _img_exc:
- print(
- f"[tui_gateway] image_routing decision failed, defaulting to text: {_img_exc}",
- file=sys.stderr,
- )
- _mode = "text"
-
- if _mode == "native":
- try:
- _parts, _skipped = build_native_content_parts(
- prompt,
- images,
- )
- if _skipped:
- print(
- f"[tui_gateway] native image attachment skipped {len(_skipped)} unreadable path(s)",
- file=sys.stderr,
- )
- if any(p.get("type") == "image_url" for p in _parts):
- run_message = _parts
- else:
- run_message = _enrich_with_attached_images(prompt, images)
- except Exception as _img_exc:
- print(
- f"[tui_gateway] native attach failed, falling back to text: {_img_exc}",
- file=sys.stderr,
- )
- run_message = _enrich_with_attached_images(prompt, images)
- else:
- run_message = _enrich_with_attached_images(prompt, images)
-
- # Streaming TTS: voice-mode replies are spoken sentence-by-sentence
- # as tokens arrive (CLI parity) instead of after the full turn.
- # begin() first — it cuts any still-speaking previous turn, and
- # that cut IS this turn's barge-in, so it must latch before we
- # consume the latch below.
- tts_queue = _tts_stream_begin()
-
- # Full-duplex agent-turn listener: armed at utterance-submit so
- # the user can interject DURING generation, not just during
- # playback. _tts_stream_begin arms it too when a pipeline
- # starts; this covers voice mode without working TTS.
- if _voice_mode_enabled() and _voice_cfg_dict().get("barge_in", True):
- _arm_full_duplex_listener()
-
- # Ambient "thinking" sound (voice mode only): calm bubble blips
- # while the agent works with no audio flowing, so long
- # thinking/tool stretches don't read as a dead session. Per-blip
- # gate skips while real TTS audio flows or the mic is capturing;
- # stopped in the finally the instant the turn ends.
- # voice.thinking_sound config-gates it; macOS TCC handled inside.
- thinking_started = False
- if _voice_mode_enabled():
- try:
- from tools.voice_mode import (
- is_audio_output_active,
- start_thinking_sound,
- )
-
- def _thinking_should_play() -> bool:
- if is_audio_output_active():
- return False
- try:
- from hermes_cli.voice import is_continuous_active
-
- return not is_continuous_active()
- except Exception:
- return True
-
- thinking_started = start_thinking_sound(
- should_play=_thinking_should_play
- )
- except Exception:
- thinking_started = False
-
- # Barged mid-speech? Tell the model (API-message note, same
- # enrichment channel as attached images) so it can react
- # ("rude!") instead of being oblivious to its own interruption.
- from tools.tts_streaming import SPEECH_INTERRUPTED_NOTE, take_speech_interrupted
-
- if take_speech_interrupted():
- if isinstance(run_message, str):
- run_message = f"{SPEECH_INTERRUPTED_NOTE}\n\n{run_message}"
- elif isinstance(run_message, list):
- run_message = [{"type": "text", "text": SPEECH_INTERRUPTED_NOTE}, *run_message]
-
- def _stream(delta):
- with session["history_lock"]:
- _append_inflight_delta(session, delta)
- payload = {"text": delta}
- if streamer and (r := streamer.feed(delta)) is not None:
- payload["rendered"] = r
- if tts_queue is not None and isinstance(delta, str):
- tts_queue.put(delta)
- _emit("message.delta", sid, payload)
-
- # Surface interim assistant text (commentary emitted alongside
- # tool calls, or the attempted final answer before a verify-on-stop
- # nudge) so the desktop can seal it as its own segment instead of
- # losing it when message.complete replaces the streaming buffer.
- # Gated on display.interim_assistant_messages (default true).
- if _load_interim_assistant_messages():
- def _interim_assistant_cb(text: str, *, already_streamed: bool = False) -> None:
- _emit("message.interim", sid, {
- "text": text,
- "already_streamed": already_streamed,
- })
-
- agent.interim_assistant_callback = _interim_assistant_cb
- else:
- agent.interim_assistant_callback = None
-
- run_kwargs = {
- "conversation_history": list(history),
- "stream_callback": _stream,
- "persist_user_message": (
- _build_persist_user_message(prompt, images, run_message) if images else prompt
- ),
- }
- # Type a synthesized turn at turn START so the crash persist writes
- # its row as a timeline event, instead of leaving a raw user bubble
- # until the turn ends — and forever if it never does, which is
- # exactly the auto-continue case. The post-turn stamp below is the
- # fallback for an older agent without the parameter; re-stamping
- # the same value is a no-op.
- try:
- _run_params = inspect.signature(agent.run_conversation).parameters
- except (TypeError, ValueError):
- _run_params = {}
- if "task_id" in _run_params:
- run_kwargs["task_id"] = session["session_key"]
- if display_kind and "persist_user_display_kind" in _run_params:
- run_kwargs["persist_user_display_kind"] = display_kind
- run_kwargs["persist_user_display_metadata"] = display_metadata
- result = agent.run_conversation(run_message, **run_kwargs)
- if display_kind and isinstance(text, str):
- db = getattr(agent, "_session_db", None)
- current_session_id = getattr(agent, "session_id", None) or session.get("session_key")
- if db is not None:
- try:
- db.set_latest_matching_message_display_kind(
- current_session_id,
- role="user",
- content=text,
- display_kind=display_kind,
- display_metadata=display_metadata,
- )
- except Exception:
- logger.debug("failed to stamp synthetic display kind", exc_info=True)
- if isinstance(result, dict) and isinstance(result.get("messages"), list):
- for message in reversed(result["messages"]):
- if message.get("role") == "user" and message.get("content") == text:
- message["display_kind"] = display_kind
- if display_metadata:
- message["display_metadata"] = display_metadata
- break
- if "moa_one_shot_restore" in session:
- _restore = session.pop("moa_one_shot_restore", None)
- # Restore the model the user was on before the /moa one-shot.
- # The one-shot did a real in-place agent.switch_model() to MoA
- # (#53444), so undoing it must go back through the switch path —
- # resetting session["model_override"] alone would leave the live
- # agent's client pinned to MoA for the next turn.
- if isinstance(_restore, dict):
- _prev_override = _restore.get("override")
- _prev_model = _restore.get("model")
- _prev_provider = _restore.get("provider")
- if _prev_override is None:
- session.pop("model_override", None)
- else:
- session["model_override"] = _prev_override
- if _prev_model:
- _raw = (
- f"{_prev_model} --provider {_prev_provider}"
- if _prev_provider
- else _prev_model
- )
- try:
- _apply_model_switch(
- sid,
- session,
- _raw,
- confirm_expensive_model=False,
- pin_session_override=bool(_prev_override),
- # Session-internal restore after the /moa
- # one-shot — never persist to config.yaml.
- persist_override=False,
- )
- except Exception as _moa_restore_exc:
- logger.warning(
- "MoA one-shot model restore failed: %s",
- _moa_restore_exc,
- )
- elif _restore is None:
- session.pop("model_override", None)
- else:
- session["model_override"] = _restore
-
- last_reasoning = None
- status_note = None
- if isinstance(result, dict):
- if isinstance(result.get("messages"), list):
- with session["history_lock"]:
- current_version = int(session.get("history_version", 0))
- if current_version == history_version:
- session["history"] = result["messages"]
- session["history_version"] = history_version + 1
- else:
- # History mutated externally during the turn
- # (undo/compress/retry/rollback now guard on
- # session.running, but this is the defensive
- # backstop for any path that slips past).
- # Surface the desync rather than silently
- # dropping the agent's output — the UI can
- # show the response and warn that it was
- # not persisted.
- print(
- f"[tui_gateway] prompt.submit: history_version mismatch "
- f"(expected={history_version} current={current_version}) — "
- f"agent output NOT written to session history",
- file=sys.stderr,
- )
- status_note = (
- "History changed during this turn — the response above is visible "
- "but was not saved to session history."
- )
-
- # If auto-compression fired inside run_conversation(), agent.session_id
- # may have rotated. Sync session_key before downstream title/goal/finalize
- # handling uses it. Preserve pending_title (user intent) so it can be
- # applied to the continuation. Restart slash worker so subsequent
- # worker-backed commands (/title etc.) target the live session.
- # Fix for #20001.
- _sync_session_key_after_compress(
- sid, session, clear_pending_title=False, restart_slash_worker=True,
- )
-
- raw = result.get("final_response", "")
- status = (
- "interrupted"
- if result.get("interrupted")
- else "error" if result.get("error") else "complete"
- )
- # When the backend produced no visible response AND reported a
- # real error (e.g. invalid model slug → provider 4xx), surface
- # that error as the visible text instead of shipping an empty
- # turn to Ink. Mirrors classic CLI behavior at cli.py where
- # (failed|partial) + no final_response → "Error: <detail>".
- # Leaves the None-with-no-error path untouched: an empty
- # successful turn still renders as empty, and the existing
- # "(empty)" sentinel handling stays in its own lane.
- if (not raw) and result.get("error") and (
- result.get("failed") or result.get("partial")
- ):
- raw = f"Error: {result.get('error')}"
- # "Operation interrupted: waiting for model response (…)" is
- # cancellation metadata, not assistant prose. gateway/run.py
- # and the ACP adapter already suppress this sentinel; without
- # this the desktop paints it as the agent's reply whenever a
- # stop/steer lands mid-request (#7921).
- if status == "interrupted" and isinstance(raw, str) and raw.strip().startswith(
- INTERRUPT_WAITING_FOR_MODEL_PREFIX
- ):
- raw = ""
- lr = result.get("last_reasoning")
- if isinstance(lr, str) and lr.strip():
- last_reasoning = lr.strip()
- else:
- raw = str(result)
- status = "complete"
-
- payload = {"text": raw, "usage": _get_usage(agent), "status": status}
- if last_reasoning:
- payload["reasoning"] = last_reasoning
- if status_note:
- payload["warning"] = status_note
- if result.get("response_previewed"):
- payload["response_previewed"] = True
- # Forward the structured billing-wall descriptor (provider,
- # billing_url, is_nous, message) so the TUI/desktop render a
- # billing-specific recovery surface instead of re-parsing text.
- _billing_block = result.get("billing_block") if isinstance(result, dict) else None
- if _billing_block:
- payload["billing"] = _billing_block
- payload["failure_reason"] = result.get("failure_reason")
- rendered = render_message(raw, cols)
- if rendered:
- payload["rendered"] = rendered
- with session["history_lock"]:
- if status == "error":
- # Returned-error result (provider 4xx, budget, etc.): retain
- # the failed turn for resume replay instead of clearing it.
- # If this terminal frame is lost to a disconnect, resume's
- # inflight payload is the only carrier of the failure.
- _fail_inflight_turn(
- session,
- result.get("error") if isinstance(result, dict) else raw,
- )
- turn_error_retained = True
- else:
- _clear_inflight_turn(session)
- if status == "error":
- payload["error"] = str(
- (result.get("error") if isinstance(result, dict) else "") or raw
- )
- payload["recoverable"] = True
- _retire_turn_marker(session, marker_key)
- _emit("message.complete", sid, payload)
-
- # ── /goal continuation (Ralph-style loop) ─────────────────
- # After every TUI turn, if a /goal is active, ask the judge
- # whether the goal is done and — if not and we're still under
- # budget — queue a continuation prompt to run after this
- # thread releases session["running"]. The verdict message
- # ("✓ Goal achieved" / "⏸ budget exhausted") is surfaced as
- # a system line so the user sees progress regardless of
- # outcome. Mirrors gateway/run._post_turn_goal_continuation.
- if status == "complete" and isinstance(raw, str) and raw.strip():
- try:
- from hermes_cli.goals import GoalManager
-
- sid_key = session.get("session_key") or ""
- if sid_key:
- try:
- goals_cfg = _load_cfg().get("goals") or {}
- goal_max_turns = int(goals_cfg.get("max_turns", 20) or 20)
- except Exception:
- goal_max_turns = 20
- goal_mgr = GoalManager(
- session_id=sid_key,
- default_max_turns=goal_max_turns,
- )
- if goal_mgr.is_active():
- try:
- from hermes_cli.goals import gather_background_processes as _gather_bg
- _bg_procs = _gather_bg()
- except Exception:
- _bg_procs = None
- decision = goal_mgr.evaluate_after_turn(
- raw,
- user_initiated=True,
- background_processes=_bg_procs,
- )
- verdict_msg = decision.get("message") or ""
- if verdict_msg:
- _emit(
- "status.update",
- sid,
- {"kind": "goal", "text": verdict_msg},
- )
- if decision.get("should_continue"):
- cont_prompt = decision.get("continuation_prompt") or ""
- if cont_prompt:
- goal_followup = cont_prompt
- except Exception as _goal_exc:
- print(
- f"[tui_gateway] goal continuation hook failed: "
- f"{type(_goal_exc).__name__}: {_goal_exc}",
- file=sys.stderr,
- )
-
- # Apply pending_title now that the DB row exists — in the
- # session-owned profile store (not the launch profile).
- _pending = session.get("pending_title")
- if _pending and status == "complete":
- _session_key = session.get("session_key") or sid
- try:
- with _session_db(session) as _pdb:
- if _pdb and _pdb.set_session_title(_session_key, _pending):
- session["pending_title"] = None
- except ValueError as exc:
- # Invalid/duplicate title — non-retryable, drop it.
- # Auto-title will take over. Fix for #19029.
- session["pending_title"] = None
- logger.info(
- "Dropping pending title for session %s: %s",
- _session_key, exc,
- )
- except Exception:
- # Transient DB failure — keep pending_title for retry.
- pass
-
- if (
- status == "complete"
- and isinstance(raw, str)
- and raw.strip()
- and isinstance(text, str)
- and text.strip()
- ):
- try:
- from agent.title_generator import maybe_auto_title
-
- _title_key = session.get("session_key") or sid
- # Snapshot the runtime identity; the validator lets the
- # background titler skip its LLM call if the session's
- # model changed before it fires (#19027).
- _title_model = getattr(agent, "model", None)
- _title_provider = getattr(agent, "provider", None)
- maybe_auto_title(
- _get_db(),
- _title_key,
- text,
- raw,
- session.get("history", []),
- # Keep auxiliary auto-detection aligned with the active
- # Desktop/Webapp session. Without this, providers that
- # rely on runtime auth (for example OpenAI Codex OAuth)
- # are skipped and the new session remains untitled.
- main_runtime={
- "model": getattr(agent, "model", None),
- "provider": getattr(agent, "provider", None),
- "base_url": getattr(agent, "base_url", None),
- "api_key": getattr(agent, "api_key", None),
- "api_mode": getattr(agent, "api_mode", None),
- },
- runtime_validator=lambda: (
- getattr(agent, "model", None) == _title_model
- and getattr(agent, "provider", None) == _title_provider
- ),
- # Push the generated title live so the sidebar renames
- # without waiting for the next list refresh (the titler
- # runs async, after this turn's refresh already fired).
- title_callback=lambda t, _k=_title_key: _emit(
- "session.title", sid, {"session_id": _k, "title": t}
- ),
- )
- except Exception:
- pass
-
- # Voice TTS fallback: when the streaming pipeline couldn't start
- # (no provider / missing deps probed at turn start), speak the
- # final text whole (cli.py:_voice_speak_response parity). The
- # streaming path already spoke everything via tts_queue.
- if (
- status == "complete"
- and tts_queue is None
- and isinstance(raw, str)
- and raw.strip()
- and _voice_tts_enabled()
- ):
- try:
- spoken = raw
- # Barge-aware: spoken interruptions must cut this
- # fallback playback too, not just the streaming path.
- threading.Thread(
- target=_speak_text_with_barge, args=(spoken,), daemon=True
- ).start()
- except ImportError:
- logger.warning("voice TTS skipped: hermes_cli.voice unavailable")
- except Exception as e:
- logger.warning("voice TTS dispatch failed: %s", e)
- except Exception as e:
- import traceback
-
- trace = traceback.format_exc()
- try:
- os.makedirs(os.path.dirname(_CRASH_LOG), exist_ok=True)
- with open(_CRASH_LOG, "a", encoding="utf-8") as f:
- f.write(
- f"\n=== turn-dispatcher exception · "
- f"{time.strftime('%Y-%m-%d %H:%M:%S')} · sid={sid} ===\n"
- )
- f.write(trace)
- except Exception:
- pass
- print(
- f"[gateway-turn] {type(e).__name__}: {e}", file=sys.stderr, flush=True
- )
- try:
- # Close the turn with the same terminal error frame shape as
- # the returned-error path (uniform client handling), retaining
- # the failed turn for resume replay.
- _emit_terminal_turn_error(sid, session, e)
- turn_error_retained = True
- except Exception as emit_exc:
- print(
- f"[gateway-turn] terminal error emit failed: "
- f"{type(emit_exc).__name__}: {emit_exc}",
- file=sys.stderr,
- flush=True,
- )
- _emit("error", sid, {"message": str(e)})
- finally:
- if thinking_started:
- # Kill the ambient thinking sound the moment the turn ends —
- # error and success paths both land here.
- try:
- from tools.voice_mode import stop_thinking_sound
-
- stop_thinking_sound()
- except Exception:
- pass
- if tts_queue is not None:
- tts_queue.put(None) # end-of-text sentinel — flush + finish speaking
- if one_turn_restore:
- try:
- _restore_agent_model_runtime(agent, one_turn_restore)
- _restart_slash_worker(sid, session)
- _persist_live_session_runtime(session)
- _persist_live_session_system_prompt(session)
- except Exception:
- logger.debug("TUI one-turn model restore failed", exc_info=True)
- try:
- if approval_token is not None:
- reset_current_session_key(approval_token)
- except Exception:
- pass
- if home_token is not None:
- reset_hermes_home_override(home_token)
- if secret_token is not None:
- reset_secret_scope(secret_token)
- _clear_session_context(session_tokens)
- # Clear the per-turn interim callback so a stale closure from
- # this turn can't fire during a later turn on the same agent.
- agent.interim_assistant_callback = None
- with session["history_lock"]:
- session["running"] = False
- session["last_active"] = time.time()
- if not turn_error_retained:
- _clear_inflight_turn(session)
- # Backstop for turns that never reached a terminal frame (the
- # frame paths retire the marker as they emit).
- _retire_turn_marker(session, marker_key)
- session.pop("_auto_continue_scheduled", None)
- _emit_settled_session_info(sid, session, agent)
-
- # A user prompt that arrived mid-turn (interrupt + queue) wins over
- # every auto follow-up below — drain it first and skip them this cycle;
- # the goal judge / notifications re-evaluate at the end of that turn.
- # Leftover /steer: the steer arrived after the last tool batch (e.g.
- # during the final API call), so the agent couldn't inject it and
- # returned it in result["pending_steer"]. Requeue it as the next turn
- # so it isn't silently dropped — same rule as cli.py and gateway/run.py.
- # A real queued prompt still wins: the merge in _enqueue_prompt keeps
- # both texts.
- _leftover_steer = result.get("pending_steer") if isinstance(result, dict) else None
- if isinstance(_leftover_steer, str) and _leftover_steer.strip():
- with session["history_lock"]:
- _enqueue_prompt(session, _leftover_steer, session.get("transport"))
- if _drain_queued_prompt(rid, sid, session):
- return
-
- # Chain a goal-continuation turn if the judge said so. We do
- # this AFTER the finally releases session["running"], so the
- # nested _run_prompt_submit doesn't deadlock on the busy
- # guard. A real user prompt that races us wins because
- # prompt.submit sets running=True under the history_lock and
- # we check that guard before re-firing.
- if goal_followup:
- with session["history_lock"]:
- if session.get("running"):
- # User already sent something — their turn wins,
- # the judge will re-run on the next turn anyway.
- return
- session["running"] = True
- try:
- _emit("message.start", sid)
- _run_prompt_submit(rid, sid, session, goal_followup)
- except Exception as _cont_exc:
- print(
- f"[tui_gateway] goal continuation dispatch failed: "
- f"{type(_cont_exc).__name__}: {_cont_exc}",
- file=sys.stderr,
- )
- with session["history_lock"]:
- session["running"] = False
-
- # Drain completion notifications that arrived during this turn.
- # The background poller handles between-turn delivery; this is
- # the safety net for events that arrived mid-turn.
- #
- # Ownership filter (#42674, #35652): a turn finishing in session B
- # must not consume an event that belongs to session A. The registry
- # requeues every addressed event this session cannot positively claim;
- # the poller then delivers it to a live owner or drops an orphan.
- try:
- from tools.process_registry import process_registry
-
- # Positive-proof ownership (compression-chain aware) — the same
- # fail-closed gate the poller uses, so the post-turn drain can't
- # adopt another session's addressed notification while a
- # post-compression session still claims its own pre-compression
- # dispatches (#55578).
- drained = process_registry.drain_notifications(
- session_key=session.get("session_key", ""),
- owns_event=lambda e: _session_owns_notification_event(sid, session, e),
- skip_poll_observed=False,
- )
- for index, (_evt, synth) in enumerate(drained):
- with session["history_lock"]:
- if session.get("running"):
- for pending_evt, _pending_synth in drained[index:]:
- process_registry.completion_queue.put(pending_evt)
- break
- session["running"] = True
- from tools.async_delegation import (
- claim_event_delivery, complete_event_delivery, release_event_delivery,
- )
- _claim = claim_event_delivery(_evt, "tui-post-turn")
- if _claim is None:
- continue
- try:
- _emit("message.start", sid)
- _run_prompt_submit(rid, sid, session, synth)
- complete_event_delivery(_evt, _claim)
- except Exception as _n_exc:
- release_event_delivery(_evt, _claim)
- print(
- f"[tui_gateway] completion notification dispatch failed: "
- f"{type(_n_exc).__name__}: {_n_exc}",
- file=sys.stderr,
- )
- with session["history_lock"]:
- session["running"] = False
- except Exception as _drain_exc:
- print(
- f"[tui_gateway] completion queue drain failed: "
- f"{type(_drain_exc).__name__}: {_drain_exc}",
- file=sys.stderr,
- )
-
- run_thread = threading.Thread(target=run, daemon=True)
- session["_run_thread"] = run_thread
- run_thread.start()
-
-
- @method("clipboard.paste")
- def _(rid, params: dict) -> dict:
- session, err = _sess(params, rid)
- if err:
- return err
- try:
- from hermes_cli.clipboard import has_clipboard_image, save_clipboard_image
- except Exception as e:
- return _err(rid, 5027, f"clipboard unavailable: {e}")
-
- session["image_counter"] = session.get("image_counter", 0) + 1
- img_dir = _hermes_home / "images"
- img_dir.mkdir(parents=True, exist_ok=True)
- img_path = (
- img_dir
- / f"clip_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{session['image_counter']}.png"
- )
-
- # Save-first: mirrors CLI keybinding path; more robust than has_image() precheck
- if not save_clipboard_image(img_path):
- session["image_counter"] = max(0, session["image_counter"] - 1)
- msg = (
- "Clipboard has image but extraction failed"
- if has_clipboard_image()
- else "No image found in clipboard"
- )
- return _ok(rid, {"attached": False, "message": msg})
-
- session.setdefault("attached_images", []).append(str(img_path))
- return _ok(
- rid,
- {
- "attached": True,
- "path": str(img_path),
- "count": len(session["attached_images"]),
- **_image_meta(img_path),
- },
- )
-
-
- @method("image.attach")
- def _(rid, params: dict) -> dict:
- session, err = _sess(params, rid)
- if err:
- return err
- raw = str(params.get("path", "") or "").strip()
- if not raw:
- return _err(rid, 4015, "path required")
- try:
- from cli import (
- _IMAGE_EXTENSIONS,
- _detect_file_drop,
- _resolve_attachment_path,
- _split_path_input,
- )
-
- dropped = _detect_file_drop(raw)
- if dropped:
- image_path = dropped["path"]
- remainder = dropped["remainder"]
- else:
- path_token, remainder = _split_path_input(raw)
- image_path = _resolve_attachment_path(path_token)
- if image_path is None:
- return _err(rid, 4016, f"image not found: {path_token}")
- if image_path.suffix.lower() not in _IMAGE_EXTENSIONS:
- return _err(rid, 4016, f"unsupported image: {image_path.name}")
- session.setdefault("attached_images", []).append(str(image_path))
- return _ok(
- rid,
- {
- "attached": True,
- "path": str(image_path),
- "count": len(session["attached_images"]),
- "remainder": remainder,
- "text": remainder or f"[User attached image: {image_path.name}]",
- **_image_meta(image_path),
- },
- )
- except Exception as e:
- return _err(rid, 5027, str(e))
-
-
- # Byte-upload attach caps. 25 MB matches Anthropic's per-image limit; 50 MB / 25
- # pages bounds a single PDF drop so it can't blow the context budget.
- _ATTACH_BYTES_MAX_BYTES = 25 * 1024 * 1024
- _PDF_ATTACH_MAX_BYTES = 50 * 1024 * 1024
- _PDF_ATTACH_MAX_PAGES = 25
-
- # Leading magic bytes → file extension, for filename-less uploads.
- _IMAGE_MAGIC: tuple[tuple[bytes, str], ...] = (
- (b"\x89PNG\r\n\x1a\n", ".png"),
- (b"\xff\xd8\xff", ".jpg"),
- (b"GIF87a", ".gif"),
- (b"GIF89a", ".gif"),
- (b"BM", ".bmp"),
- )
-
-
- def _decode_attach_base64(raw: str, *, mime_prefix: str) -> bytes | None:
- """Decode a base64 (optionally data-URL-wrapped) payload.
-
- Accepts ``data:<mime_prefix>...;base64,<b64>`` plus embedded whitespace.
- Returns the decoded bytes, or ``None`` when the input isn't valid base64.
- """
- import base64 as _base64
- import re as _re
-
- cleaned = raw.strip()
- m = _re.match(
- rf"^data:{_re.escape(mime_prefix)}[a-zA-Z0-9.+-]*;base64,(.*)$",
- cleaned,
- _re.DOTALL,
- )
- if m:
- cleaned = m.group(1)
- cleaned = _re.sub(r"\s+", "", cleaned)
- try:
- return _base64.b64decode(cleaned, validate=True)
- except Exception:
- return None
-
-
- def _sniff_image_ext(img_bytes: bytes, filename: str = "") -> str:
- """Resolve an image extension from a filename hint, else magic bytes.
-
- Falls back to ``.png``. WebP needs the RIFF/WEBP container check, handled
- before the generic table.
- """
- if filename:
- suffix = Path(filename).suffix.lower()
- if suffix:
- return suffix
- head = img_bytes[:16]
- if head.startswith(b"RIFF") and head[8:12] == b"WEBP":
- return ".webp"
- for sig, ext in _IMAGE_MAGIC:
- if head.startswith(sig):
- return ext
- return ".png"
-
-
- def _allowed_image_extensions() -> frozenset[str]:
- try:
- from cli import _IMAGE_EXTENSIONS
-
- return frozenset(_IMAGE_EXTENSIONS)
- except Exception:
- return frozenset({".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"})
-
-
- def _queue_attached_image(session: dict, img_bytes: bytes, ext: str, *, prefix: str) -> Path:
- """Write image bytes into the gateway's images dir and queue them.
-
- Mirrors what ``image.attach`` does for a local path: appends to
- ``session["attached_images"]`` so the next ``prompt.submit`` picks it up via
- the existing native-image-attach pipeline. Returns the written path.
- """
- session["image_counter"] = session.get("image_counter", 0) + 1
- img_dir = _hermes_home / "images"
- img_dir.mkdir(parents=True, exist_ok=True)
- ts = datetime.now().strftime("%Y%m%d_%H%M%S")
- img_path = img_dir / f"{prefix}_{ts}_{session['image_counter']}{ext}"
- try:
- img_path.write_bytes(img_bytes)
- except Exception:
- session["image_counter"] = max(0, session["image_counter"] - 1)
- raise
- session.setdefault("attached_images", []).append(str(img_path))
- return img_path
-
-
- @method("image.attach_bytes")
- def _(rid, params: dict) -> dict:
- """Attach an image to the session from base64 bytes (remote-client path).
-
- A desktop app or web dashboard running on a DIFFERENT machine than the
- gateway can't hand us a local path — that file only exists on the client's
- disk. So it uploads the raw image bytes (base64) and we write them into the
- gateway's own images dir. The response shape mirrors ``image.attach`` so the
- client treats both identically.
-
- Params:
- content_base64 / data (str, required): base64 image bytes. Accepts a
- ``data:image/...;base64,`` prefix and embedded whitespace. ``data`` is
- an accepted alias for older desktop builds.
- filename / ext (str, optional): extension hint. Without it, magic bytes
- identify PNG/JPEG/GIF/WebP/BMP, falling back to ``.png``.
- """
- session, err = _sess(params, rid)
- if err:
- return err
-
- raw_b64 = str(params.get("content_base64") or params.get("data") or "").strip()
- if not raw_b64:
- return _err(rid, 4015, "content_base64 required")
-
- img_bytes = _decode_attach_base64(raw_b64, mime_prefix="image/")
- if img_bytes is None:
- return _err(rid, 4017, "data is not valid base64")
- if not img_bytes:
- return _err(rid, 4017, "image is empty")
- if len(img_bytes) > _ATTACH_BYTES_MAX_BYTES:
- mb = _ATTACH_BYTES_MAX_BYTES // (1024 * 1024)
- return _err(rid, 4018, f"image too large ({len(img_bytes)} bytes; cap is {mb} MB)")
-
- filename = str(params.get("filename", "") or "")
- ext_hint = str(params.get("ext", "") or "").strip().lower()
- if ext_hint and not ext_hint.startswith("."):
- ext_hint = "." + ext_hint
- ext = _sniff_image_ext(img_bytes, filename or (f"x{ext_hint}" if ext_hint else ""))
- if ext not in _allowed_image_extensions():
- return _err(rid, 4016, f"unsupported image extension: {ext}")
-
- try:
- img_path = _queue_attached_image(session, img_bytes, ext, prefix="upload")
- except Exception as e:
- return _err(rid, 5027, f"write failed: {e}")
-
- return _ok(
- rid,
- {
- "attached": True,
- "path": str(img_path),
- "count": len(session["attached_images"]),
- "remainder": "",
- "text": f"[User attached image: {img_path.name}]",
- "bytes": len(img_bytes),
- **_image_meta(img_path),
- },
- )
-
-
- @method("pdf.attach")
- def _(rid, params: dict) -> dict:
- """Attach a PDF by rendering each page to PNG and queuing the pages.
-
- Anthropic's vision pipeline accepts images, not PDFs, so this runs
- ``pdftoppm`` (poppler-utils) at 150 DPI per page and queues each rendered
- page as an attached image. Accepts either a host ``path`` (local mode) or
- base64 ``content_base64`` (remote upload). Caps at 50 MB / 25 pages per call.
-
- Requires ``pdftoppm`` on $PATH (``apt install poppler-utils``); returns 5028
- if missing.
- """
- import shutil
- import subprocess
- import tempfile
-
- session, err = _sess(params, rid)
- if err:
- return err
-
- if shutil.which("pdftoppm") is None:
- return _err(rid, 5028, "pdftoppm not installed (poppler-utils package required)")
-
- raw_path = str(params.get("path", "") or "").strip()
- raw_b64 = str(params.get("content_base64") or params.get("data") or "").strip()
- if not raw_path and not raw_b64:
- return _err(rid, 4015, "path or content_base64 required")
-
- with tempfile.TemporaryDirectory(prefix="pdf_attach_") as td:
- td_path = Path(td)
- if raw_b64:
- pdf_bytes = _decode_attach_base64(raw_b64, mime_prefix="application/pdf")
- if pdf_bytes is None:
- return _err(rid, 4017, "data is not valid base64")
- if not pdf_bytes:
- return _err(rid, 4017, "decoded PDF is empty")
- if len(pdf_bytes) > _PDF_ATTACH_MAX_BYTES:
- mb = _PDF_ATTACH_MAX_BYTES // (1024 * 1024)
- return _err(rid, 4018, f"PDF too large ({len(pdf_bytes)} bytes; cap is {mb} MB)")
- if pdf_bytes[:5] != b"%PDF-":
- return _err(rid, 4017, "payload is not a PDF (missing %PDF- magic bytes)")
- pdf_path = td_path / "input.pdf"
- pdf_path.write_bytes(pdf_bytes)
- display_name = str(params.get("filename", "") or "uploaded.pdf")
- else:
- try:
- from cli import _resolve_attachment_path
-
- resolved = _resolve_attachment_path(raw_path)
- except Exception:
- resolved = None
- if resolved is None or not Path(resolved).is_file():
- return _err(rid, 4016, f"PDF not found: {raw_path}")
- if Path(resolved).suffix.lower() != ".pdf":
- return _err(rid, 4016, f"not a PDF: {Path(resolved).name}")
- if Path(resolved).stat().st_size > _PDF_ATTACH_MAX_BYTES:
- mb = _PDF_ATTACH_MAX_BYTES // (1024 * 1024)
- return _err(rid, 4018, f"PDF too large; cap is {mb} MB")
- pdf_path = Path(resolved)
- display_name = pdf_path.name
-
- try:
- first_page = int(params.get("first_page") or 1)
- last_page_param = params.get("last_page")
- last_page = int(last_page_param) if last_page_param is not None else None
- except (TypeError, ValueError):
- return _err(rid, 4015, "first_page/last_page must be integers")
-
- if first_page < 1:
- return _err(rid, 4015, "first_page must be >= 1")
- if last_page is None:
- last_page = first_page + _PDF_ATTACH_MAX_PAGES - 1
- if last_page < first_page:
- return _err(rid, 4015, "last_page must be >= first_page")
- if last_page - first_page + 1 > _PDF_ATTACH_MAX_PAGES:
- return _err(rid, 4019, f"page range exceeds cap of {_PDF_ATTACH_MAX_PAGES} pages per attach call")
-
- out_prefix = td_path / "page"
- argv = [
- "pdftoppm", "-png", "-r", "150",
- "-f", str(first_page), "-l", str(last_page),
- str(pdf_path), str(out_prefix),
- ]
- from hermes_cli._subprocess_compat import windows_hide_flags
-
- try:
- res = subprocess.run(
- argv, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL,
- # Force UTF-8 + lossy decode so non-UTF-8 child output can't
- # crash the gateway thread on locale-mismatched Windows (#53137).
- encoding="utf-8", errors="replace",
- creationflags=windows_hide_flags(),
- )
- except subprocess.TimeoutExpired:
- return _err(rid, 5028, "pdftoppm timed out (>120s)")
- if res.returncode != 0:
- tail = (res.stderr or res.stdout or "").strip().splitlines()[-3:]
- return _err(rid, 5028, "pdftoppm failed: " + " | ".join(tail))
-
- rendered = sorted(td_path.glob("page-*.png"))
- if not rendered:
- return _err(rid, 5028, "pdftoppm produced no pages (corrupt PDF?)")
-
- attached_pages = []
- for src in rendered:
- page_num = src.stem.split("-", 1)[-1]
- try:
- page_int = int(page_num)
- except ValueError:
- page_int = first_page + len(attached_pages)
- dst = _queue_attached_image(session, src.read_bytes(), ".png", prefix=f"pdf_p{page_num}")
- attached_pages.append({"path": str(dst), "page": page_int, **_image_meta(dst)})
-
- return _ok(
- rid,
- {
- "attached": True,
- "filename": display_name,
- "pages_attached": len(attached_pages),
- "pages": attached_pages,
- "count": len(session["attached_images"]),
- "text": f"[User attached PDF: {display_name} ({len(attached_pages)} page(s))]",
- },
- )
-
-
- _ATTACHMENT_REF_NEEDS_QUOTING_RE = None
-
-
- def _format_ref_value(value: str) -> str:
- """Quote a context-ref value when it contains whitespace or bracket chars.
-
- Mirrors the desktop ``formatRefValue`` so the staged ``@file:`` ref round-trips
- through ``agent.context_references`` cleanly.
- """
- import re as _re
-
- global _ATTACHMENT_REF_NEEDS_QUOTING_RE
- if _ATTACHMENT_REF_NEEDS_QUOTING_RE is None:
- _ATTACHMENT_REF_NEEDS_QUOTING_RE = _re.compile(r"""[\s()\[\]{}<>"'`]""")
- if not value or not _ATTACHMENT_REF_NEEDS_QUOTING_RE.search(value):
- return value
- if "`" not in value:
- return f"`{value}`"
- if '"' not in value:
- return f'"{value}"'
- if "'" not in value:
- return f"'{value}'"
- return value
-
-
- def _attachment_ref_path(session: dict, target: Path) -> str:
- """Workspace-relative path for an attachment, or the absolute path if outside."""
- workspace = Path(_session_cwd(session)).resolve()
- try:
- rel = target.resolve().relative_to(workspace)
- return str(rel).replace(os.sep, "/")
- except ValueError:
- return str(target.resolve())
-
-
- def _desktop_attachment_dir(session: dict) -> Path:
- root = Path(_session_cwd(session)).resolve() / ".hermes" / "desktop-attachments"
- root.mkdir(parents=True, exist_ok=True)
- return root
-
-
- def _sanitize_attachment_name(name: str) -> str:
- import re as _re
-
- candidate = Path(str(name or "").strip()).name
- candidate = _re.sub(r"[\x00-\x1f]+", "_", candidate)
- candidate = candidate.strip().strip(".")
- return candidate or "attachment"
-
-
- def _unique_attachment_path(root: Path, filename: str) -> Path:
- candidate = root / filename
- if not candidate.exists():
- return candidate
- stem = Path(filename).stem or "attachment"
- suffix = Path(filename).suffix
- counter = 2
- while True:
- next_candidate = root / f"{stem}-{counter}{suffix}"
- if not next_candidate.exists():
- return next_candidate
- counter += 1
-
-
- def _resolve_gateway_attachment_path(raw: str) -> Path | None:
- """Resolve a raw path token to a gateway-visible file, or None."""
- if not raw:
- return None
- try:
- from cli import _detect_file_drop, _resolve_attachment_path, _split_path_input
- except Exception:
- return None
-
- dropped = _detect_file_drop(raw)
- if dropped:
- return Path(dropped["path"]).resolve()
- path_token, _remainder = _split_path_input(raw)
- resolved = _resolve_attachment_path(path_token)
- return Path(resolved).resolve() if resolved is not None else None
-
-
- def _decode_attachment_data_url(data_url: str) -> bytes:
- """Decode a ``data:<any-mime>;base64,<b64>`` payload to bytes.
-
- Unlike ``_decode_attach_base64`` (image-mime-specific), this accepts any
- media type — text/csv, application/pdf, etc. — so non-image file uploads
- round-trip. Also tolerates a bare base64 string with no data-URL prefix.
- """
- import base64 as _base64
- import binascii as _binascii
- import re as _re
-
- cleaned = (data_url or "").strip()
- m = _re.match(r"^data:[^;,]*(?:;[^;,=]+=[^;,]+)*;base64,(.*)$", cleaned, _re.DOTALL | _re.I)
- if m:
- cleaned = m.group(1)
- cleaned = _re.sub(r"\s+", "", cleaned)
- try:
- return _base64.b64decode(cleaned, validate=True)
- except (ValueError, _binascii.Error) as exc:
- raise ValueError("invalid data_url payload") from exc
-
-
- def _stage_session_file_attachment(
- session: dict,
- *,
- raw_path: str,
- data_url: str,
- name: str,
- ) -> tuple[Path, bool]:
- """Make a desktop file attachment available to the remote gateway agent.
-
- Three cases:
- 1. The path resolves to a file already INSIDE the session workspace — use
- it as-is (no copy, ``uploaded=False``).
- 2. The path resolves to a gateway-visible file OUTSIDE the workspace — copy
- it into ``.hermes/desktop-attachments/`` so the ``@file:`` ref resolves.
- 3. The path doesn't exist on the gateway (the common remote case: it's a
- path on the CLIENT's disk) — decode the uploaded ``data_url`` bytes and
- write them into ``.hermes/desktop-attachments/``.
-
- Returns ``(stored_path, uploaded)``.
- """
- workspace = Path(_session_cwd(session)).resolve()
- resolved = _resolve_gateway_attachment_path(raw_path)
- if resolved is not None:
- try:
- resolved.relative_to(workspace)
- return resolved, False
- except ValueError:
- payload = resolved.read_bytes()
- filename = resolved.name
- else:
- if not data_url:
- raise ValueError("file not found on gateway and no data_url provided")
- payload = _decode_attachment_data_url(data_url)
- filename = _sanitize_attachment_name(name or Path(str(raw_path or "")).name)
-
- upload_dir = _desktop_attachment_dir(session)
- target = _unique_attachment_path(upload_dir, _sanitize_attachment_name(filename))
- target.write_bytes(payload)
- return target.resolve(), True
-
-
- @method("file.attach")
- def _(rid, params: dict) -> dict:
- """Stage a non-image file attachment into the session workspace.
-
- The image/PDF path renders to vision tiles; this one keeps the file as a
- readable artifact and returns a workspace-relative ``@file:`` ref so the
- agent's file tools (and ``agent.context_references``) can read it. Solves the
- remote-gateway case where the desktop passes a path that only exists on the
- CLIENT's disk: the client uploads ``data_url`` bytes and we materialize the
- file on the gateway.
-
- Params:
- session_id (str, required)
- path (str): client/host path of the file (used for naming + local-mode
- gateway-visible resolution).
- data_url (str): ``data:<mime>;base64,<b64>`` upload of the file bytes,
- required when the path isn't visible to the gateway.
- name (str, optional): preferred filename.
- """
- session, err = _sess(params, rid)
- if err:
- return err
- raw = str(params.get("path", "") or "").strip()
- data_url = str(params.get("data_url", "") or "").strip()
- name = str(params.get("name", "") or "").strip()
- if not raw and not data_url:
- return _err(rid, 4015, "path or data_url required")
- try:
- stored_path, uploaded = _stage_session_file_attachment(
- session, raw_path=raw, data_url=data_url, name=name
- )
- ref_path = _attachment_ref_path(session, stored_path)
- return _ok(
- rid,
- {
- "attached": True,
- "name": stored_path.name,
- "path": str(stored_path),
- "ref_path": ref_path,
- "ref_text": f"@file:{_format_ref_value(ref_path)}",
- "uploaded": uploaded,
- },
- )
- except Exception as e:
- return _err(rid, 5028, str(e))
-
-
- @method("image.detach")
- def _(rid, params: dict) -> dict:
- session, err = _sess(params, rid)
- if err:
- return err
- raw = str(params.get("path", "") or "").strip()
- if not raw:
- return _err(rid, 4015, "path required")
- images = session.setdefault("attached_images", [])
- before = len(images)
- session["attached_images"] = [path for path in images if path != raw]
- return _ok(
- rid,
- {
- "detached": len(session["attached_images"]) != before,
- "count": len(session["attached_images"]),
- },
- )
-
-
- @method("input.detect_drop")
- def _(rid, params: dict) -> dict:
- session, err = _sess_nowait(params, rid)
- if err:
- return err
- try:
- from cli import _detect_file_drop
-
- raw = str(params.get("text", "") or "")
- dropped = _detect_file_drop(raw)
- if not dropped:
- return _ok(rid, {"matched": False})
-
- drop_path = dropped["path"]
- remainder = dropped["remainder"]
- if dropped["is_image"]:
- session.setdefault("attached_images", []).append(str(drop_path))
- text = remainder or f"[User attached image: {drop_path.name}]"
- return _ok(
- rid,
- {
- "matched": True,
- "is_image": True,
- "path": str(drop_path),
- "count": len(session["attached_images"]),
- "text": text,
- **_image_meta(drop_path),
- },
- )
-
- text = f"[User attached file: {drop_path}]" + (
- f"\n{remainder}" if remainder else ""
- )
- return _ok(
- rid,
- {
- "matched": True,
- "is_image": False,
- "path": str(drop_path),
- "name": drop_path.name,
- "text": text,
- },
- )
- except Exception as e:
- return _err(rid, 5027, str(e))
-
-
- @method("prompt.background")
- def _(rid, params: dict) -> dict:
- session, err = _sess(params, rid)
- if err:
- return err
- text, parent = params.get("text", ""), params.get("session_id", "")
- if not text:
- return _err(rid, 4012, "text required")
- task_id = f"bg_{uuid.uuid4().hex[:6]}"
-
- def run():
- session_tokens = _set_session_context(task_id, cwd=_session_cwd(session))
- try:
- from run_agent import AIAgent
-
- result = AIAgent(
- **_background_agent_kwargs(session["agent"], task_id)
- ).run_conversation(
- user_message=text,
- task_id=task_id,
- )
- _emit(
- "background.complete",
- parent,
- {
- "task_id": task_id,
- "text": (
- result.get("final_response", str(result))
- if isinstance(result, dict)
- else str(result)
- ),
- },
- )
- except Exception as e:
- _emit(
- "background.complete",
- parent,
- {"task_id": task_id, "text": f"error: {e}"},
- )
- finally:
- _clear_session_context(session_tokens)
-
- threading.Thread(target=run, daemon=True).start()
- return _ok(rid, {"task_id": task_id})
-
-
- @method("preview.restart")
- def _(rid, params: dict) -> dict:
- session, err = _sess(params, rid)
- if err:
- return err
-
- url = str(params.get("url") or "").strip()
- cwd = str(params.get("cwd") or "").strip()
- context = str(params.get("context") or "").strip()
-
- if not url:
- return _err(rid, 4012, "url required")
-
- task_id = f"preview_{uuid.uuid4().hex[:6]}"
- parent = params.get("session_id", "")
- parent_history = _preview_restart_history(session)
- has_history = bool(parent_history)
- prompt = "\n".join(
- line
- for line in [
- "The desktop preview pane cannot load a local server URL.",
- "",
- f"Preview URL: {url}",
- f"Current working directory: {cwd or '(unknown)'}",
- "",
- f"Preview console:\n{context}" if context else "",
- "" if context else "",
- (
- "The conversation history above is from the user's main session — including the commands you (the assistant) previously ran to start servers, edit files, or check ports. Use it to figure out exactly which server should be running at this Preview URL. The user did not start a brand new task; recover what they had working."
- if has_history
- else None
- ),
- "Restart exactly the app intended for the Preview URL, not Hermes Desktop itself.",
- "The Preview URL and port are the target. Preserve that target unless you conclude it is impossible.",
- "If the prior conversation shows a specific command that bound this URL/port, prefer re-running THAT exact command (in the same cwd) over guessing a new one.",
- "First inspect what process, if any, owns the Preview URL port. If a stale server exists, inspect its cwd and prefer that cwd over the Hermes/Desktop process cwd.",
- "The Current working directory is only a hint. Do not assume it is the preview app root when the port owner or files indicate another root.",
- "If the console shows a module-script MIME error for src/main.tsx or similar, a static server is serving source files. Do not restart python -m http.server or any dumb static server for that app.",
- "For module-script MIME failures, inspect package.json/vite config in the candidate app root and start the real dev server/bundler (for example npm/pnpm/yarn dev) so module transforms happen.",
- "Before declaring success, verify the Preview URL responds with the intended app, not Hermes Desktop. If it serves Hermes/Desktop UI or another unrelated app, stop that process and report failure.",
- "Do not modify files. Do not ask the user unless blocked.",
- "Prefer existing project scripts or commands when they are clear.",
- "If a stale process owns the needed port, handle it safely.",
- "Start long-running servers detached/in the background, then return immediately.",
- "Do not run a foreground dev server command that blocks this background task.",
- "Keep the final response short: what command/server was started, or why it could not be restarted.",
- ]
- if line
- )
-
- # Normalize defensively: a malformed client path (embedded NUL, etc.) must
- # not blow up the whole restart — treat it as "no validated cwd".
- try:
- preview_cwd = os.path.abspath(os.path.expanduser(cwd)) if cwd else ""
- if preview_cwd and not os.path.isdir(preview_cwd):
- preview_cwd = ""
- except Exception:
- preview_cwd = ""
-
- def run():
- # Pin the validated preview cwd, else the parent workspace — never an
- # invalid client path, which would silently fall back to the launch dir.
- session_tokens = _set_session_context(task_id, cwd=(preview_cwd or _session_cwd(session)))
- try:
- from run_agent import AIAgent
- from tools.terminal_tool import register_task_env_overrides
-
- if preview_cwd:
- register_task_env_overrides(task_id, {"cwd": preview_cwd})
-
- history_note = (
- f" (with {len(parent_history)} parent-session messages of context)"
- if parent_history
- else ""
- )
- _emit(
- "preview.restart.progress",
- parent,
- {"task_id": task_id, "text": f"Starting hidden restart agent{history_note}"},
- )
- result = AIAgent(
- **_ephemeral_preview_agent_kwargs(session["agent"], task_id),
- **_preview_restart_callbacks(parent, task_id),
- ).run_conversation(
- user_message=prompt,
- task_id=task_id,
- conversation_history=parent_history or None,
- )
- text = (
- result.get("final_response", str(result))
- if isinstance(result, dict)
- else str(result)
- )
- _emit("preview.restart.complete", parent, {"task_id": task_id, "text": text})
- except Exception as e:
- _emit(
- "preview.restart.complete",
- parent,
- {"task_id": task_id, "text": f"error: {e}"},
- )
- finally:
- try:
- from tools.terminal_tool import clear_task_env_overrides
-
- clear_task_env_overrides(task_id)
- except Exception:
- pass
- _clear_session_context(session_tokens)
-
- threading.Thread(target=run, daemon=True).start()
- return _ok(rid, {"task_id": task_id})
-
-
- # ── Methods: respond ─────────────────────────────────────────────────
-
-
- def _respond(rid, params, key, *, allow_expired=False):
- r = params.get("request_id", "")
- with _prompt_lock:
- entry = _pending.get(r)
- if not entry:
- if allow_expired and r:
- return _ok(rid, {"status": "expired"})
- return _err(rid, 4009, f"no pending {key} request")
- _, ev = entry
- _answers[r] = params.get(key, "")
- ev.set()
- return _ok(rid, {"status": "ok"})
-
-
- @method("clarify.respond")
- def _(rid, params: dict) -> dict:
- # allow_expired=True: a clarify can time out server-side (its entry is popped
- # from _pending) while the card is still visible — common when a WebSocket
- # reconnect during the wait drops tool.complete. A late answer must resolve
- # gracefully instead of hitting the raw 4009 "no pending answer request".
- return _respond(rid, params, "answer", allow_expired=True)
-
-
- @method("terminal.read.respond")
- def _(rid, params: dict) -> dict:
- # `text` is a JSON string of the serialized terminal buffer + line metadata.
- # allow_expired=True: the read_terminal tool's _block() uses a short 30s
- # timeout, so a slow renderer losing the race is the common case — a late
- # response must not error after the tool already returned empty.
- return _respond(rid, params, "text", allow_expired=True)
-
-
- @method("sudo.respond")
- def _(rid, params: dict) -> dict:
- return _respond(rid, params, "password", allow_expired=True)
-
-
- @method("secret.respond")
- def _(rid, params: dict) -> dict:
- return _respond(rid, params, "value", allow_expired=True)
-
-
- @method("approval.respond")
- def _(rid, params: dict) -> dict:
- session, err = _sess(params, rid)
- if err:
- return err
- try:
- from tools.approval import resolve_gateway_approval
-
- return _ok(
- rid,
- {
- "resolved": resolve_gateway_approval(
- session["session_key"],
- params.get("choice", "deny"),
- resolve_all=params.get("all", False),
- )
- },
- )
- except Exception as e:
- return _err(rid, 5004, str(e))
-
-
- # ── Methods: config ──────────────────────────────────────────────────
-
-
- @method("config.set")
- def _(rid, params: dict) -> dict:
- key, value = params.get("key", ""), params.get("value", "")
- session = _sessions.get(params.get("session_id", ""))
-
- if key == "model":
- try:
- if not value:
- return _err(rid, 4002, "model value required")
- if session:
- # Reject during an in-flight turn. agent.switch_model()
- # mutates self.model / self.provider / self.base_url /
- # self.client in place; the worker thread running
- # agent.run_conversation is reading those on every
- # iteration. A mid-turn swap can send an HTTP request
- # with the new base_url but old model (or vice versa),
- # producing 400/404s the user never asked for. Parity
- # with the gateway's running-agent /model guard.
- if session.get("running"):
- return _err(
- rid,
- 4009,
- "session busy — /interrupt the current turn before switching models",
- )
- from hermes_cli.model_switch import parse_model_switch_args
-
- parsed_flags = parse_model_switch_args(value)
- explicit_provider = parsed_flags.explicit_provider
- if session.get("agent") is None and not explicit_provider.strip():
- session_id = params.get("session_id", "")
- _start_agent_build(session_id, session)
- init_err = _wait_agent(session, rid)
- if init_err:
- return init_err
- if session.get("agent") is None:
- return _err(rid, 5032, "agent initialization failed")
- result = _apply_model_switch(
- params.get("session_id", ""),
- session,
- value,
- confirm_expensive_model=bool(
- params.get("confirm_expensive_model", False)
- ),
- parsed_flags=parsed_flags,
- )
- else:
- result = _apply_model_switch(
- "",
- {"agent": None},
- value,
- confirm_expensive_model=bool(
- params.get("confirm_expensive_model", False)
- ),
- )
- return _ok(
- rid,
- {
- "key": key,
- "value": result["value"],
- "warning": result["warning"],
- "confirm_required": result.get("confirm_required", False),
- "confirm_message": result.get("confirm_message", ""),
- "scope": result.get("scope", "session"),
- },
- )
- except Exception as e:
- return _err(rid, 5001, str(e))
-
- if key == "fast":
- raw = str(value or "").strip().lower()
- agent = session.get("agent") if session else None
- if agent is not None:
- current_fast = getattr(agent, "service_tier", None) == "priority"
- elif session is not None and session.get("create_service_tier_override") is not None:
- # Pre-build session with a pinned tier (desktop draft pick or an
- # earlier session-scoped toggle) — report/toggle from the pin, not
- # the global default.
- current_fast = session["create_service_tier_override"] == "priority"
- else:
- current_fast = _load_service_tier() == "priority"
-
- if raw in {"status"}:
- return _ok(
- rid,
- {"key": key, "value": "fast" if current_fast else "normal"},
- )
-
- if raw in {"", "toggle"}:
- nv = "normal" if current_fast else "fast"
- elif raw in {"fast", "on"}:
- nv = "fast"
- elif raw in {"normal", "off"}:
- nv = "normal"
- else:
- return _err(rid, 4002, f"unknown fast mode: {value}")
-
- overrides = None
- if nv == "fast":
- from hermes_cli.models import resolve_fast_mode_overrides
-
- if agent is not None:
- target_model = getattr(agent, "model", None)
- else:
- # A pre-build session may already have a picked model riding in
- # model_override (desktop draft) — validate fast support against
- # THAT model, not the global default it will never use.
- session_override = (session or {}).get("model_override") or {}
- target_model = (
- session_override.get("model")
- if isinstance(session_override, dict)
- else None
- ) or _resolve_model()
- if not target_model:
- return _err(
- rid,
- 4002,
- "fast mode is not available without a selected model",
- )
- overrides = resolve_fast_mode_overrides(target_model)
- if overrides is None:
- return _err(
- rid,
- 4002,
- "fast mode is not available for this model",
- )
-
- if session is not None:
- # Session-scoped, like `reasoning` below (global persistence is
- # `--global` / Settings → Model territory). Writing config.yaml
- # here let every desktop model-menu selection (per-model fast
- # preset) rewrite the user's global agent.service_tier — flipping
- # fast mode for every OTHER session, profile, CLI, and gateway
- # build ("switch one session, switches everywhere"). Pin the
- # create override so lazily-built sessions and rebuilds (/new,
- # deferred resume) keep the choice; "" pins normal explicitly.
- session["create_service_tier_override"] = (
- "priority" if nv == "fast" else ""
- )
- else:
- _write_config_key("agent.service_tier", nv)
- if agent is not None:
- agent.service_tier = "priority" if nv == "fast" else None
- current_overrides = dict(getattr(agent, "request_overrides", {}) or {})
- current_overrides.pop("service_tier", None)
- current_overrides.pop("speed", None)
- if nv == "fast":
- current_overrides.update(overrides)
- agent.request_overrides = current_overrides
- _persist_live_session_runtime(session)
- _emit(
- "session.info",
- params.get("session_id", ""),
- _session_info(agent, session),
- )
- return _ok(rid, {"key": key, "value": nv})
-
- if key == "busy":
- raw = str(value or "").strip().lower()
- if raw in {"", "status"}:
- return _ok(rid, {"key": key, "value": _load_busy_input_mode()})
- if raw not in {"queue", "steer", "interrupt"}:
- return _err(rid, 4002, f"unknown busy mode: {value}")
- _write_config_key("display.busy_input_mode", raw)
- return _ok(rid, {"key": key, "value": raw})
-
- if key == "verbose":
- cycle = ["off", "new", "all", "verbose"]
- cur = (
- session.get("tool_progress_mode", _load_tool_progress_mode())
- if session
- else _load_tool_progress_mode()
- )
- if value and value != "cycle":
- nv = str(value).strip().lower()
- if nv not in cycle:
- return _err(rid, 4002, f"unknown verbose mode: {value}")
- else:
- try:
- idx = cycle.index(cur)
- except ValueError:
- idx = 2
- nv = cycle[(idx + 1) % len(cycle)]
- _write_config_key("display.tool_progress", nv)
- if session:
- session["tool_progress_mode"] = nv
- agent = session.get("agent")
- if agent is not None:
- agent.verbose_logging = nv == "verbose"
- return _ok(rid, {"key": key, "value": nv})
-
- if key == "focus":
- # Focus view — display-only reduced-output mode (/focus). Composes with
- # the tool_progress machinery rather than duplicating it: enabling it
- # pins tool_progress to "off" (the same value /verbose off uses) after
- # stashing the configured mode, and disabling it restores that mode.
- # Nothing about the request payload changes.
- from hermes_cli.focus_view import (
- FOCUS_TOOL_PROGRESS_MODE,
- normalize_tool_progress_mode,
- resolve_focus_arg,
- )
-
- cfg_f = _load_cfg()
- _display_f = cfg_f.get("display")
- d_f: dict = _display_f if isinstance(_display_f, dict) else {}
- cur_focus = bool(d_f.get("focus_view", False))
- action, target = resolve_focus_arg(str(value or ""), cur_focus)
- if action == "usage":
- return _err(rid, 4002, f"unknown focus value: {value} (use on|off|status)")
- if action == "status" or target is None:
- return _ok(
- rid,
- {
- "key": key,
- "value": "on" if cur_focus else "off",
- "tool_progress": _load_tool_progress_mode(),
- },
- )
-
- if target:
- saved = normalize_tool_progress_mode(
- (d_f.get("focus_saved_tool_progress") or _load_tool_progress_mode())
- if cur_focus
- else _load_tool_progress_mode()
- )
- _write_config_key("display.focus_saved_tool_progress", saved)
- _write_config_key("display.tool_progress", FOCUS_TOOL_PROGRESS_MODE)
- effective = FOCUS_TOOL_PROGRESS_MODE
- else:
- saved = normalize_tool_progress_mode(
- d_f.get("focus_saved_tool_progress") or "all"
- )
- _write_config_key("display.tool_progress", saved)
- effective = saved
- _write_config_key("display.focus_view", bool(target))
-
- if session:
- session["focus_view"] = bool(target)
- session["tool_progress_mode"] = effective
- agent_f = session.get("agent")
- if agent_f is not None:
- try:
- agent_f.tool_progress_mode = effective
- except Exception:
- pass
- return _ok(
- rid,
- {
- "key": key,
- "value": "on" if target else "off",
- "tool_progress": effective,
- },
- )
-
- if key in {"approval_mode", "approvals.mode"}:
- raw = str(value or "").strip().lower()
- if raw not in _APPROVAL_MODES:
- return _err(
- rid,
- 4002,
- f"unknown approval mode: {value}; pick one of manual|smart|off",
- )
-
- _write_config_key("approvals.mode", raw)
- for sid, sess in list(_sessions.items()):
- agent = sess.get("agent")
- if agent is not None:
- _emit("session.info", sid, _session_info(agent, sess))
- return _ok(rid, {"key": "approvals.mode", "value": raw})
-
- if key == "yolo":
- # Approval bypass. Two scopes:
- # scope="session" (default) — same as the TUI's Shift+Tab. Toggles
- # ONLY this session's _session_yolo flag; never touches global
- # config, so CLI / TUI / cron behavior is unaffected.
- # scope="global" (Shift+click the zap) — flips the persistent global
- # approvals.mode in config.yaml between "off" (bypass on) and
- # "manual" (bypass off). This DOES affect every session, the CLI,
- # the TUI, and cron, and survives restarts.
- scope = str(params.get("scope") or "session").strip().lower()
- try:
- from tools.approval import (
- disable_session_yolo,
- enable_session_yolo,
- is_session_yolo_enabled,
- )
-
- raw = str(value or "").strip().lower()
-
- def _resolve_toggle(current: bool) -> bool:
- if raw in {"1", "on", "true", "yes"}:
- return True
- if raw in {"0", "off", "false", "no"}:
- return False
- return not current
-
- if scope == "global":
- from tools.approval import _normalize_approval_mode
-
- cfg = _load_cfg()
- appr = cfg.get("approvals") if isinstance(cfg, dict) else None
- if not isinstance(appr, dict):
- appr = {}
- current = _normalize_approval_mode(appr.get("mode", "manual")) == "off"
- enable = _resolve_toggle(current)
- # Toggle between full bypass and the default manual gate. We do
- # not try to restore a prior "smart"/custom mode — the zap is a
- # binary on/off affordance; users with bespoke modes set them in
- # config.yaml.
- _write_config_key("approvals.mode", "off" if enable else "manual")
- nv = "1" if enable else "0"
- # Reflect the global flip in every live session's indicator.
- for sid, sess in list(_sessions.items()):
- agent = sess.get("agent")
- if agent is not None:
- _emit("session.info", sid, _session_info(agent, sess))
- return _ok(rid, {"key": key, "value": nv, "scope": "global"})
-
- if session:
- current = is_session_yolo_enabled(session["session_key"])
- enable = _resolve_toggle(current)
- if enable:
- enable_session_yolo(session["session_key"])
- nv = "1"
- else:
- disable_session_yolo(session["session_key"])
- nv = "0"
- agent = session.get("agent")
- if agent is not None:
- _emit(
- "session.info",
- params.get("session_id", ""),
- _session_info(agent, session),
- )
- else:
- current = is_truthy_value(os.environ.get("HERMES_YOLO_MODE"))
- enable = _resolve_toggle(current)
- if enable:
- os.environ["HERMES_YOLO_MODE"] = "1"
- nv = "1"
- else:
- os.environ.pop("HERMES_YOLO_MODE", None)
- nv = "0"
- return _ok(rid, {"key": key, "value": nv, "scope": "session"})
- except Exception as e:
- return _err(rid, 5001, str(e))
-
- if key == "reasoning":
- try:
- from hermes_constants import parse_reasoning_effort
-
- arg = str(value or "").strip().lower()
- scope = str(params.get("scope") or "").strip().lower()
- global_scope = scope == "global"
- if arg in {"show", "on"}:
- cfg = _load_cfg_raw() # write-back round-trip
- display = (
- cfg.get("display") if isinstance(cfg.get("display"), dict) else {}
- )
- sections = (
- display.get("sections")
- if isinstance(display.get("sections"), dict)
- else {}
- )
- display["show_reasoning"] = True
- sections["thinking"] = "expanded"
- display["sections"] = sections
- cfg["display"] = display
- _save_cfg(cfg)
- if session:
- session["show_reasoning"] = True
- return _ok(rid, {"key": key, "value": "show"})
- if arg in {"hide", "off"}:
- cfg = _load_cfg_raw() # write-back round-trip
- display = (
- cfg.get("display") if isinstance(cfg.get("display"), dict) else {}
- )
- sections = (
- display.get("sections")
- if isinstance(display.get("sections"), dict)
- else {}
- )
- display["show_reasoning"] = False
- sections["thinking"] = "hidden"
- display["sections"] = sections
- cfg["display"] = display
- _save_cfg(cfg)
- if session:
- session["show_reasoning"] = False
- return _ok(rid, {"key": key, "value": "hide"})
-
- # /reasoning full | clamp — parity with the classic CLI's
- # reasoning_full toggle. The TUI renders thinking as an
- # expand/collapse section rather than a fixed 10-line recap, so
- # full maps to sections.thinking=expanded and clamp to collapsed.
- # display.reasoning_full is persisted too so the config key stays
- # consistent across the CLI and TUI surfaces.
- if arg in {"full", "all"}:
- cfg = _load_cfg_raw() # write-back round-trip
- display = (
- cfg.get("display") if isinstance(cfg.get("display"), dict) else {}
- )
- sections = (
- display.get("sections")
- if isinstance(display.get("sections"), dict)
- else {}
- )
- display["reasoning_full"] = True
- sections["thinking"] = "expanded"
- display["sections"] = sections
- cfg["display"] = display
- _save_cfg(cfg)
- return _ok(rid, {"key": key, "value": "full"})
- if arg in {"clamp", "collapse", "short"}:
- cfg = _load_cfg_raw() # write-back round-trip
- display = (
- cfg.get("display") if isinstance(cfg.get("display"), dict) else {}
- )
- sections = (
- display.get("sections")
- if isinstance(display.get("sections"), dict)
- else {}
- )
- display["reasoning_full"] = False
- sections["thinking"] = "collapsed"
- display["sections"] = sections
- cfg["display"] = display
- _save_cfg(cfg)
- return _ok(rid, {"key": key, "value": "clamp"})
-
- parsed = parse_reasoning_effort(arg)
- if parsed is None:
- return _err(rid, 4002, f"unknown reasoning value: {value}")
- if global_scope or session is None:
- _write_config_key("agent.reasoning_effort", arg)
- if session is not None:
- session.pop("create_reasoning_override", None)
- else:
- # Session-scoped, like the messaging gateway's `/reasoning
- # <level>` (global persistence is `--global` / Settings →
- # Model territory). Writing config.yaml here let every
- # desktop model-menu selection rewrite the user's global
- # agent.reasoning_effort to the preset default.
- session["create_reasoning_override"] = parsed
- if session and session.get("agent") is not None:
- session["agent"].reasoning_config = parsed
- _persist_live_session_runtime(session)
- _emit(
- "session.info",
- params.get("session_id", ""),
- _session_info(session["agent"], session),
- )
- return _ok(rid, {"key": key, "value": arg})
- except Exception as e:
- return _err(rid, 5001, str(e))
-
- if key == "details_mode":
- nv = str(value or "").strip().lower()
- if nv not in _DETAIL_MODES:
- return _err(rid, 4002, f"unknown details_mode: {value}")
- cfg = _load_cfg_raw() # write-back round-trip
- display = cfg.get("display") if isinstance(cfg.get("display"), dict) else {}
- sections = (
- display.get("sections") if isinstance(display.get("sections"), dict) else {}
- )
- display["details_mode"] = nv
- for section in _DETAIL_SECTION_NAMES:
- sections[section] = nv
- display["sections"] = sections
- cfg["display"] = display
- _save_cfg(cfg)
- return _ok(rid, {"key": key, "value": nv})
-
- if key.startswith("details_mode."):
- # Per-section override: `details_mode.<section>` writes to
- # `display.sections.<section>`. Empty value clears the explicit
- # override and lets frontend resolution apply built-in section defaults
- # before the global details_mode.
- section = key.split(".", 1)[1]
- if section not in _DETAIL_SECTION_NAMES:
- return _err(rid, 4002, f"unknown section: {section}")
-
- cfg = _load_cfg_raw() # write-back round-trip
- display = cfg.get("display") if isinstance(cfg.get("display"), dict) else {}
- sections_cfg = (
- display.get("sections") if isinstance(display.get("sections"), dict) else {}
- )
-
- nv = str(value or "").strip().lower()
- if not nv:
- sections_cfg.pop(section, None)
- display["sections"] = sections_cfg
- cfg["display"] = display
- _save_cfg(cfg)
- return _ok(rid, {"key": key, "value": ""})
-
- if nv not in _DETAIL_MODES:
- return _err(rid, 4002, f"unknown details_mode: {value}")
-
- sections_cfg[section] = nv
- display["sections"] = sections_cfg
- cfg["display"] = display
- _save_cfg(cfg)
- return _ok(rid, {"key": key, "value": nv})
-
- if key == "thinking_mode":
- nv = str(value or "").strip().lower()
- allowed_tm = frozenset({"collapsed", "truncated", "full"})
- if nv not in allowed_tm:
- return _err(rid, 4002, f"unknown thinking_mode: {value}")
- _write_config_key("display.thinking_mode", nv)
- # Backward compatibility bridge: keep details_mode aligned.
- _write_config_key(
- "display.details_mode", "expanded" if nv == "full" else "collapsed"
- )
- return _ok(rid, {"key": key, "value": nv})
-
- if key == "density":
- raw = str(value or "").strip().lower()
- cfg0 = _load_cfg()
- d0 = cfg0.get("display") if isinstance(cfg0.get("display"), dict) else {}
- cur_b = bool(d0.get("tui_compact", False))
- if raw in {"", "toggle"}:
- nv_b = not cur_b
- elif raw == "on":
- nv_b = True
- elif raw == "off":
- nv_b = False
- else:
- return _err(rid, 4002, f"unknown density value: {value}")
- _write_config_key("display.tui_compact", nv_b)
- return _ok(rid, {"key": key, "value": "on" if nv_b else "off"})
-
- if key == "battery":
- raw = str(value or "").strip().lower()
- cfg0 = _load_cfg()
- d0 = cfg0.get("display") if isinstance(cfg0.get("display"), dict) else {}
- cur_b = bool(d0.get("battery", False))
- if raw in {"", "toggle"}:
- nv_b = not cur_b
- elif raw in {"on", "true", "yes"}:
- nv_b = True
- elif raw in {"off", "false", "no"}:
- nv_b = False
- else:
- return _err(rid, 4002, f"unknown battery value: {value}")
- _write_config_key("display.battery", nv_b)
- return _ok(rid, {"key": key, "value": "on" if nv_b else "off"})
-
- if key == "theme":
- # TUI light/dark mode pin: 'light'/'dark' beat background
- # auto-detection (xterm.js hosts misreport OSC 11); 'auto' trusts it.
- raw = str(value or "").strip().lower()
- if raw not in {"auto", "light", "dark"}:
- return _err(rid, 4002, f"unknown theme value: {value} (use auto|light|dark)")
- _write_config_key("display.tui_theme", raw)
- return _ok(rid, {"key": key, "value": raw})
-
- if key == "statusbar":
- raw = str(value or "").strip().lower()
- display = _load_cfg().get("display")
- d0 = display if isinstance(display, dict) else {}
- current = _coerce_statusbar(d0.get("tui_statusbar", "top"))
-
- if raw in {"", "toggle"}:
- nv = "top" if current == "off" else "off"
- elif raw == "on":
- nv = "top"
- elif raw in _STATUSBAR_MODES:
- nv = raw
- else:
- return _err(rid, 4002, f"unknown statusbar value: {value}")
-
- _write_config_key("display.tui_statusbar", nv)
- return _ok(rid, {"key": key, "value": nv})
-
- if key == "mouse":
- # Explicit None check rather than `value or ""` so falsy non-string
- # inputs (0, False) reach the alias map as themselves — both map to
- # 'off' via _MOUSE_TRACKING_ALIASES — instead of being collapsed to
- # '' and triggering the toggle path. The slash command always passes
- # a string, but programmatic JSON-RPC callers may send booleans.
- raw = ("" if value is None else str(value)).strip().lower()
- cfg = _load_cfg()
- display = cfg.get("display") if isinstance(cfg.get("display"), dict) else {}
- current = _display_mouse_tracking(display)
-
- if raw in {"", "toggle"}:
- nv = "all" if current == "off" else "off"
- elif raw in _MOUSE_TRACKING_ALIASES:
- nv = _MOUSE_TRACKING_ALIASES[raw]
- else:
- return _err(rid, 4002, f"unknown mouse value: {value}")
-
- _write_config_key("display.mouse_tracking", nv)
- return _ok(rid, {"key": key, "value": nv})
+ _run_params = inspect.signature(agent.run_conversation).parameters
+ except (TypeError, ValueError):
+ _run_params = {}
+ if "task_id" in _run_params:
+ run_kwargs["task_id"] = session["session_key"]
+ if display_kind and "persist_user_display_kind" in _run_params:
+ run_kwargs["persist_user_display_kind"] = display_kind
+ run_kwargs["persist_user_display_metadata"] = display_metadata
+ result = agent.run_conversation(run_message, **run_kwargs)
+ if display_kind and isinstance(text, str):
+ db = getattr(agent, "_session_db", None)
+ current_session_id = getattr(agent, "session_id", None) or session.get("session_key")
+ if db is not None:
+ try:
+ db.set_latest_matching_message_display_kind(
+ current_session_id,
+ role="user",
+ content=text,
+ display_kind=display_kind,
+ display_metadata=display_metadata,
+ )
+ except Exception:
+ logger.debug("failed to stamp synthetic display kind", exc_info=True)
+ if isinstance(result, dict) and isinstance(result.get("messages"), list):
+ for message in reversed(result["messages"]):
+ if message.get("role") == "user" and message.get("content") == text:
+ message["display_kind"] = display_kind
+ if display_metadata:
+ message["display_metadata"] = display_metadata
+ break
+ if "moa_one_shot_restore" in session:
+ _restore = session.pop("moa_one_shot_restore", None)
+ # Restore the model the user was on before the /moa one-shot.
+ # The one-shot did a real in-place agent.switch_model() to MoA
+ # (#53444), so undoing it must go back through the switch path —
+ # resetting session["model_override"] alone would leave the live
+ # agent's client pinned to MoA for the next turn.
+ if isinstance(_restore, dict):
+ _prev_override = _restore.get("override")
+ _prev_model = _restore.get("model")
+ _prev_provider = _restore.get("provider")
+ if _prev_override is None:
+ session.pop("model_override", None)
+ else:
+ session["model_override"] = _prev_override
+ if _prev_model:
+ _raw = (
+ f"{_prev_model} --provider {_prev_provider}"
+ if _prev_provider
+ else _prev_model
+ )
+ try:
+ _apply_model_switch(
+ sid,
+ session,
+ _raw,
+ confirm_expensive_model=False,
+ pin_session_override=bool(_prev_override),
+ # Session-internal restore after the /moa
+ # one-shot — never persist to config.yaml.
+ persist_override=False,
+ )
+ except Exception as _moa_restore_exc:
+ logger.warning(
+ "MoA one-shot model restore failed: %s",
+ _moa_restore_exc,
+ )
+ elif _restore is None:
+ session.pop("model_override", None)
+ else:
+ session["model_override"] = _restore
- if key == "indicator":
- # Use an explicit None check rather than `value or ""` so falsy
- # non-string inputs (0, False, []) still surface as themselves
- # in the error message instead of looking like a blank value.
- raw = ("" if value is None else str(value)).strip().lower()
- if raw not in _INDICATOR_STYLES:
- return _err(
- rid,
- 4002,
- f"unknown indicator: {raw!r}; pick one of {'|'.join(_INDICATOR_STYLES)}",
- )
- _write_config_key("display.tui_status_indicator", raw)
- return _ok(rid, {"key": key, "value": raw})
+ last_reasoning = None
+ status_note = None
+ if isinstance(result, dict):
+ if isinstance(result.get("messages"), list):
+ with session["history_lock"]:
+ current_version = int(session.get("history_version", 0))
+ if current_version == history_version:
+ session["history"] = result["messages"]
+ session["history_version"] = history_version + 1
+ else:
+ # History mutated externally during the turn
+ # (undo/compress/retry/rollback now guard on
+ # session.running, but this is the defensive
+ # backstop for any path that slips past).
+ # Surface the desync rather than silently
+ # dropping the agent's output — the UI can
+ # show the response and warn that it was
+ # not persisted.
+ print(
+ f"[tui_gateway] prompt.submit: history_version mismatch "
+ f"(expected={history_version} current={current_version}) — "
+ f"agent output NOT written to session history",
+ file=sys.stderr,
+ )
+ status_note = (
+ "History changed during this turn — the response above is visible "
+ "but was not saved to session history."
+ )
- if key in {"cwd", "terminal.cwd", "workdir"}:
- raw = str(value or "").strip()
- if not raw:
- return _err(rid, 4002, "cwd required")
- cwd = os.path.abspath(os.path.expanduser(raw))
- if not os.path.isdir(cwd):
- return _err(rid, 4002, f"working directory does not exist: {raw}")
- _write_config_key("terminal.cwd", cwd)
- os.environ["TERMINAL_CWD"] = cwd
- return _ok(
- rid,
- {"key": "terminal.cwd", "value": cwd, "cwd": cwd, "branch": _git_branch_for_cwd(cwd)},
- )
+ # If auto-compression fired inside run_conversation(), agent.session_id
+ # may have rotated. Sync session_key before downstream title/goal/finalize
+ # handling uses it. Preserve pending_title (user intent) so it can be
+ # applied to the continuation. Restart slash worker so subsequent
+ # worker-backed commands (/title etc.) target the live session.
+ # Fix for #20001.
+ _sync_session_key_after_compress(
+ sid, session, clear_pending_title=False, restart_slash_worker=True,
+ )
- if key in {"prompt", "personality", "skin"}:
- try:
- cfg = _load_cfg_raw() # write-back round-trip ("prompt" saves cfg)
- if key == "prompt":
- if value == "clear":
- cfg.pop("custom_prompt", None)
- nv = ""
- else:
- cfg["custom_prompt"] = value
- nv = value
- _save_cfg(cfg)
- elif key == "personality":
- sid_key = params.get("session_id", "")
- pname, new_prompt = _validate_personality(str(value or ""), cfg)
- _write_config_key("display.personality", pname)
- _write_config_key("agent.system_prompt", new_prompt)
- nv = str(value or "none")
- history_reset, info = _apply_personality_to_session(
- sid_key, session, new_prompt, pname
+ raw = result.get("final_response", "")
+ status = (
+ "interrupted"
+ if result.get("interrupted")
+ else "error" if result.get("error") else "complete"
)
+ # When the backend produced no visible response AND reported a
+ # real error (e.g. invalid model slug → provider 4xx), surface
+ # that error as the visible text instead of shipping an empty
+ # turn to Ink. Mirrors classic CLI behavior at cli.py where
+ # (failed|partial) + no final_response → "Error: <detail>".
+ # Leaves the None-with-no-error path untouched: an empty
+ # successful turn still renders as empty, and the existing
+ # "(empty)" sentinel handling stays in its own lane.
+ if (not raw) and result.get("error") and (
+ result.get("failed") or result.get("partial")
+ ):
+ raw = f"Error: {result.get('error')}"
+ # "Operation interrupted: waiting for model response (…)" is
+ # cancellation metadata, not assistant prose. gateway/run.py
+ # and the ACP adapter already suppress this sentinel; without
+ # this the desktop paints it as the agent's reply whenever a
+ # stop/steer lands mid-request (#7921).
+ if status == "interrupted" and isinstance(raw, str) and raw.strip().startswith(
+ INTERRUPT_WAITING_FOR_MODEL_PREFIX
+ ):
+ raw = ""
+ lr = result.get("last_reasoning")
+ if isinstance(lr, str) and lr.strip():
+ last_reasoning = lr.strip()
else:
- _write_config_key(f"display.{key}", value)
- nv = value
- if key == "skin":
- # Every connected surface repaints, not just the RPC's
- # client; then sync the watcher baseline so the poll loop
- # doesn't re-broadcast the skin this RPC just applied.
- _broadcast_global_event("skin.changed", resolve_skin())
- _note_skin_broadcast()
- resp = {"key": key, "value": nv}
- if key == "personality":
- resp["history_reset"] = history_reset
- if info is not None:
- resp["info"] = info
- return _ok(rid, resp)
- except Exception as e:
- return _err(rid, 5001, str(e))
-
- return _err(rid, 4002, f"unknown config key: {key}")
-
-
- # ---------------------------------------------------------------------------
- # Projects — first-class, per-profile, multi-folder workspaces
- # ---------------------------------------------------------------------------
-
-
- # JSON-RPC error codes for the projects surface.
- _E_PROJECTS = 5061 # generic failure
- _E_NO_PROJECT = 5062 # id resolved to nothing
- _E_PROJECT_ARG = 5063 # invalid argument (e.g. bad name/slug)
+ raw = str(result)
+ status = "complete"
+ payload = {"text": raw, "usage": _get_usage(agent), "status": status}
+ if last_reasoning:
+ payload["reasoning"] = last_reasoning
+ if status_note:
+ payload["warning"] = status_note
+ if result.get("response_previewed"):
+ payload["response_previewed"] = True
+ # Forward the structured billing-wall descriptor (provider,
+ # billing_url, is_nous, message) so the TUI/desktop render a
+ # billing-specific recovery surface instead of re-parsing text.
+ _billing_block = result.get("billing_block") if isinstance(result, dict) else None
+ if _billing_block:
+ payload["billing"] = _billing_block
+ payload["failure_reason"] = result.get("failure_reason")
+ rendered = render_message(raw, cols)
+ if rendered:
+ payload["rendered"] = rendered
+ with session["history_lock"]:
+ if status == "error":
+ # Returned-error result (provider 4xx, budget, etc.): retain
+ # the failed turn for resume replay instead of clearing it.
+ # If this terminal frame is lost to a disconnect, resume's
+ # inflight payload is the only carrier of the failure.
+ _fail_inflight_turn(
+ session,
+ result.get("error") if isinstance(result, dict) else raw,
+ )
+ turn_error_retained = True
+ else:
+ _clear_inflight_turn(session)
+ if status == "error":
+ payload["error"] = str(
+ (result.get("error") if isinstance(result, dict) else "") or raw
+ )
+ payload["recoverable"] = True
+ _retire_turn_marker(session, marker_key)
+ _emit("message.complete", sid, payload)
- class _NoProject(Exception):
- """Raised inside a projects handler when ``params['id']`` resolves to None."""
+ # ── /goal continuation (Ralph-style loop) ─────────────────
+ # After every TUI turn, if a /goal is active, ask the judge
+ # whether the goal is done and — if not and we're still under
+ # budget — queue a continuation prompt to run after this
+ # thread releases session["running"]. The verdict message
+ # ("✓ Goal achieved" / "⏸ budget exhausted") is surfaced as
+ # a system line so the user sees progress regardless of
+ # outcome. Mirrors gateway/run._post_turn_goal_continuation.
+ if status == "complete" and isinstance(raw, str) and raw.strip():
+ try:
+ from hermes_cli.goals import GoalManager
+ sid_key = session.get("session_key") or ""
+ if sid_key:
+ try:
+ goals_cfg = _load_cfg().get("goals") or {}
+ goal_max_turns = int(goals_cfg.get("max_turns", 20) or 20)
+ except Exception:
+ goal_max_turns = 20
+ goal_mgr = GoalManager(
+ session_id=sid_key,
+ default_max_turns=goal_max_turns,
+ )
+ if goal_mgr.is_active():
+ try:
+ from hermes_cli.goals import gather_background_processes as _gather_bg
+ _bg_procs = _gather_bg()
+ except Exception:
+ _bg_procs = None
+ decision = goal_mgr.evaluate_after_turn(
+ raw,
+ user_initiated=True,
+ background_processes=_bg_procs,
+ )
+ verdict_msg = decision.get("message") or ""
+ if verdict_msg:
+ _emit(
+ "status.update",
+ sid,
+ {"kind": "goal", "text": verdict_msg},
+ )
+ if decision.get("should_continue"):
+ cont_prompt = decision.get("continuation_prompt") or ""
+ if cont_prompt:
+ goal_followup = cont_prompt
+ except Exception as _goal_exc:
+ print(
+ f"[tui_gateway] goal continuation hook failed: "
+ f"{type(_goal_exc).__name__}: {_goal_exc}",
+ file=sys.stderr,
+ )
- def _projects_payload(conn) -> dict:
- from hermes_cli import projects_db as pdb
+ # Apply pending_title now that the DB row exists — in the
+ # session-owned profile store (not the launch profile).
+ _pending = session.get("pending_title")
+ if _pending and status == "complete":
+ _session_key = session.get("session_key") or sid
+ try:
+ with _session_db(session) as _pdb:
+ if _pdb and _pdb.set_session_title(_session_key, _pending):
+ session["pending_title"] = None
+ except ValueError as exc:
+ # Invalid/duplicate title — non-retryable, drop it.
+ # Auto-title will take over. Fix for #19029.
+ session["pending_title"] = None
+ logger.info(
+ "Dropping pending title for session %s: %s",
+ _session_key, exc,
+ )
+ except Exception:
+ # Transient DB failure — keep pending_title for retry.
+ pass
- return {
- "projects": [p.to_dict() for p in pdb.list_projects(conn, include_archived=True)],
- "active_id": pdb.get_active_id(conn),
- }
+ if (
+ status == "complete"
+ and isinstance(raw, str)
+ and raw.strip()
+ and isinstance(text, str)
+ and text.strip()
+ ):
+ try:
+ from agent.title_generator import maybe_auto_title
+ _title_key = session.get("session_key") or sid
+ # Snapshot the runtime identity; the validator lets the
+ # background titler skip its LLM call if the session's
+ # model changed before it fires (#19027).
+ _title_model = getattr(agent, "model", None)
+ _title_provider = getattr(agent, "provider", None)
+ maybe_auto_title(
+ _get_db(),
+ _title_key,
+ text,
+ raw,
+ session.get("history", []),
+ # Keep auxiliary auto-detection aligned with the active
+ # Desktop/Webapp session. Without this, providers that
+ # rely on runtime auth (for example OpenAI Codex OAuth)
+ # are skipped and the new session remains untitled.
+ main_runtime={
+ "model": getattr(agent, "model", None),
+ "provider": getattr(agent, "provider", None),
+ "base_url": getattr(agent, "base_url", None),
+ "api_key": getattr(agent, "api_key", None),
+ "api_mode": getattr(agent, "api_mode", None),
+ },
+ runtime_validator=lambda: (
+ getattr(agent, "model", None) == _title_model
+ and getattr(agent, "provider", None) == _title_provider
+ ),
+ # Push the generated title live so the sidebar renames
+ # without waiting for the next list refresh (the titler
+ # runs async, after this turn's refresh already fired).
+ title_callback=lambda t, _k=_title_key: _emit(
+ "session.title", sid, {"session_id": _k, "title": t}
+ ),
+ )
+ except Exception:
+ pass
- def _projects_method(name: str):
- """Register a projects RPC, injecting (pdb, conn) and unifying error mapping.
+ # Voice TTS fallback: when the streaming pipeline couldn't start
+ # (no provider / missing deps probed at turn start), speak the
+ # final text whole (cli.py:_voice_speak_response parity). The
+ # streaming path already spoke everything via tts_queue.
+ if (
+ status == "complete"
+ and tts_queue is None
+ and isinstance(raw, str)
+ and raw.strip()
+ and _voice_tts_enabled()
+ ):
+ try:
+ spoken = raw
+ # Barge-aware: spoken interruptions must cut this
+ # fallback playback too, not just the streaming path.
+ threading.Thread(
+ target=_speak_text_with_barge, args=(spoken,), daemon=True
+ ).start()
+ except ImportError:
+ logger.warning("voice TTS skipped: hermes_cli.voice unavailable")
+ except Exception as e:
+ logger.warning("voice TTS dispatch failed: %s", e)
+ except Exception as e:
+ import traceback
- Every project CRUD handler opened the per-profile DB, mapped a missing id to
- 5062, bad args to 5063, and everything else to 5061. This collapses that
- boilerplate so each handler is just its one meaningful operation.
- """
+ trace = traceback.format_exc()
+ try:
+ os.makedirs(os.path.dirname(_CRASH_LOG), exist_ok=True)
+ with open(_CRASH_LOG, "a", encoding="utf-8") as f:
+ f.write(
+ f"\n=== turn-dispatcher exception · "
+ f"{time.strftime('%Y-%m-%d %H:%M:%S')} · sid={sid} ===\n"
+ )
+ f.write(trace)
+ except Exception:
+ pass
+ print(
+ f"[gateway-turn] {type(e).__name__}: {e}", file=sys.stderr, flush=True
+ )
+ try:
+ # Close the turn with the same terminal error frame shape as
+ # the returned-error path (uniform client handling), retaining
+ # the failed turn for resume replay.
+ _emit_terminal_turn_error(sid, session, e)
+ turn_error_retained = True
+ except Exception as emit_exc:
+ print(
+ f"[gateway-turn] terminal error emit failed: "
+ f"{type(emit_exc).__name__}: {emit_exc}",
+ file=sys.stderr,
+ flush=True,
+ )
+ _emit("error", sid, {"message": str(e)})
+ finally:
+ if thinking_started:
+ # Kill the ambient thinking sound the moment the turn ends —
+ # error and success paths both land here.
+ try:
+ from tools.voice_mode import stop_thinking_sound
- def decorator(fn):
- @method(name)
- def handler(rid, params: dict) -> dict:
+ stop_thinking_sound()
+ except Exception:
+ pass
+ if tts_queue is not None:
+ tts_queue.put(None) # end-of-text sentinel — flush + finish speaking
+ if one_turn_restore:
+ try:
+ _restore_agent_model_runtime(agent, one_turn_restore)
+ _restart_slash_worker(sid, session)
+ _persist_live_session_runtime(session)
+ _persist_live_session_system_prompt(session)
+ except Exception:
+ logger.debug("TUI one-turn model restore failed", exc_info=True)
try:
- from hermes_cli import projects_db as pdb
+ if approval_token is not None:
+ reset_current_session_key(approval_token)
+ except Exception:
+ pass
+ if home_token is not None:
+ reset_hermes_home_override(home_token)
+ if secret_token is not None:
+ reset_secret_scope(secret_token)
+ _clear_session_context(session_tokens)
+ # Clear the per-turn interim callback so a stale closure from
+ # this turn can't fire during a later turn on the same agent.
+ agent.interim_assistant_callback = None
+ with session["history_lock"]:
+ session["running"] = False
+ session["last_active"] = time.time()
+ if not turn_error_retained:
+ _clear_inflight_turn(session)
+ # Backstop for turns that never reached a terminal frame (the
+ # frame paths retire the marker as they emit).
+ _retire_turn_marker(session, marker_key)
+ session.pop("_auto_continue_scheduled", None)
+ _emit_settled_session_info(sid, session, agent)
- with pdb.connect_closing() as conn:
- return fn(rid, params, pdb, conn)
- except _NoProject:
- return _err(rid, _E_NO_PROJECT, "no such project")
- except ValueError as e:
- return _err(rid, _E_PROJECT_ARG, str(e))
- except Exception as e:
- return _err(rid, _E_PROJECTS, str(e))
+ # A user prompt that arrived mid-turn (interrupt + queue) wins over
+ # every auto follow-up below — drain it first and skip them this cycle;
+ # the goal judge / notifications re-evaluate at the end of that turn.
+ # Leftover /steer: the steer arrived after the last tool batch (e.g.
+ # during the final API call), so the agent couldn't inject it and
+ # returned it in result["pending_steer"]. Requeue it as the next turn
+ # so it isn't silently dropped — same rule as cli.py and gateway/run.py.
+ # A real queued prompt still wins: the merge in _enqueue_prompt keeps
+ # both texts.
+ _leftover_steer = result.get("pending_steer") if isinstance(result, dict) else None
+ if isinstance(_leftover_steer, str) and _leftover_steer.strip():
+ with session["history_lock"]:
+ _enqueue_prompt(session, _leftover_steer, session.get("transport"))
+ if _drain_queued_prompt(rid, sid, session):
+ return
+
+ # Chain a goal-continuation turn if the judge said so. We do
+ # this AFTER the finally releases session["running"], so the
+ # nested _run_prompt_submit doesn't deadlock on the busy
+ # guard. A real user prompt that races us wins because
+ # prompt.submit sets running=True under the history_lock and
+ # we check that guard before re-firing.
+ if goal_followup:
+ with session["history_lock"]:
+ if session.get("running"):
+ # User already sent something — their turn wins,
+ # the judge will re-run on the next turn anyway.
+ return
+ session["running"] = True
+ try:
+ _emit("message.start", sid)
+ _run_prompt_submit(rid, sid, session, goal_followup)
+ except Exception as _cont_exc:
+ print(
+ f"[tui_gateway] goal continuation dispatch failed: "
+ f"{type(_cont_exc).__name__}: {_cont_exc}",
+ file=sys.stderr,
+ )
+ with session["history_lock"]:
+ session["running"] = False
- return handler
+ # Drain completion notifications that arrived during this turn.
+ # The background poller handles between-turn delivery; this is
+ # the safety net for events that arrived mid-turn.
+ #
+ # Ownership filter (#42674, #35652): a turn finishing in session B
+ # must not consume an event that belongs to session A. The registry
+ # requeues every addressed event this session cannot positively claim;
+ # the poller then delivers it to a live owner or drops an orphan.
+ try:
+ from tools.process_registry import process_registry
- return decorator
+ # Positive-proof ownership (compression-chain aware) — the same
+ # fail-closed gate the poller uses, so the post-turn drain can't
+ # adopt another session's addressed notification while a
+ # post-compression session still claims its own pre-compression
+ # dispatches (#55578).
+ drained = process_registry.drain_notifications(
+ session_key=session.get("session_key", ""),
+ owns_event=lambda e: _session_owns_notification_event(sid, session, e),
+ skip_poll_observed=False,
+ )
+ for index, (_evt, synth) in enumerate(drained):
+ with session["history_lock"]:
+ if session.get("running"):
+ for pending_evt, _pending_synth in drained[index:]:
+ process_registry.completion_queue.put(pending_evt)
+ break
+ session["running"] = True
+ from tools.async_delegation import (
+ claim_event_delivery, complete_event_delivery, release_event_delivery,
+ )
+ _claim = claim_event_delivery(_evt, "tui-post-turn")
+ if _claim is None:
+ continue
+ try:
+ _emit("message.start", sid)
+ _run_prompt_submit(rid, sid, session, synth)
+ complete_event_delivery(_evt, _claim)
+ except Exception as _n_exc:
+ release_event_delivery(_evt, _claim)
+ print(
+ f"[tui_gateway] completion notification dispatch failed: "
+ f"{type(_n_exc).__name__}: {_n_exc}",
+ file=sys.stderr,
+ )
+ with session["history_lock"]:
+ session["running"] = False
+ except Exception as _drain_exc:
+ print(
+ f"[tui_gateway] completion queue drain failed: "
+ f"{type(_drain_exc).__name__}: {_drain_exc}",
+ file=sys.stderr,
+ )
+ run_thread = threading.Thread(target=run, daemon=True)
+ session["_run_thread"] = run_thread
+ run_thread.start()
- def _require_project(pdb, conn, params: dict):
- """The project named by ``params['id']`` (or raise ``_NoProject``)."""
- proj = pdb.get_project(conn, str(params.get("id") or ""))
- if proj is None:
- raise _NoProject
- return proj
+ # Byte-upload attach caps. 25 MB matches Anthropic's per-image limit; 50 MB / 25
+ # pages bounds a single PDF drop so it can't blow the context budget.
+ _ATTACH_BYTES_MAX_BYTES = 25 * 1024 * 1024
+ _PDF_ATTACH_MAX_BYTES = 50 * 1024 * 1024
+ _PDF_ATTACH_MAX_PAGES = 25
- @_projects_method("projects.list")
- def _(rid, params, pdb, conn) -> dict:
- return _ok(rid, _projects_payload(conn))
+ # Leading magic bytes → file extension, for filename-less uploads.
+ _IMAGE_MAGIC: tuple[tuple[bytes, str], ...] = (
+ (b"\x89PNG\r\n\x1a\n", ".png"),
+ (b"\xff\xd8\xff", ".jpg"),
+ (b"GIF87a", ".gif"),
+ (b"GIF89a", ".gif"),
+ (b"BM", ".bmp"),
+ )
- @_projects_method("projects.get")
- def _(rid, params, pdb, conn) -> dict:
- return _ok(rid, {"project": _require_project(pdb, conn, params).to_dict()})
+ def _decode_attach_base64(raw: str, *, mime_prefix: str) -> bytes | None:
+ """Decode a base64 (optionally data-URL-wrapped) payload.
+ Accepts ``data:<mime_prefix>...;base64,<b64>`` plus embedded whitespace.
+ Returns the decoded bytes, or ``None`` when the input isn't valid base64.
+ """
+ import base64 as _base64
+ import re as _re
- @_projects_method("projects.create")
- def _(rid, params, pdb, conn) -> dict:
- pid = pdb.create_project(
- conn,
- name=str(params.get("name") or ""),
- slug=params.get("slug"),
- folders=params.get("folders") or [],
- primary_path=params.get("primary_path"),
- description=params.get("description"),
- icon=params.get("icon"),
- color=params.get("color"),
- board_slug=params.get("board_slug"),
+ cleaned = raw.strip()
+ m = _re.match(
+ rf"^data:{_re.escape(mime_prefix)}[a-zA-Z0-9.+-]*;base64,(.*)$",
+ cleaned,
+ _re.DOTALL,
)
- if params.get("use"):
- pdb.set_active(conn, pid)
- proj = pdb.get_project(conn, pid)
- return _ok(rid, {"project": proj.to_dict() if proj else None})
-
+ if m:
+ cleaned = m.group(1)
+ cleaned = _re.sub(r"\s+", "", cleaned)
+ try:
+ return _base64.b64decode(cleaned, validate=True)
+ except Exception:
+ return None
- @_projects_method("projects.update")
- def _(rid, params, pdb, conn) -> dict:
- proj = _require_project(pdb, conn, params)
- pdb.update_project(
- conn,
- proj.id,
- name=params.get("name"),
- description=params.get("description"),
- icon=params.get("icon"),
- color=params.get("color"),
- board_slug=params.get("board_slug"),
- )
- return _ok(rid, {"project": pdb.get_project(conn, proj.id).to_dict()})
+ def _sniff_image_ext(img_bytes: bytes, filename: str = "") -> str:
+ """Resolve an image extension from a filename hint, else magic bytes.
- @_projects_method("projects.add_folder")
- def _(rid, params, pdb, conn) -> dict:
- proj = _require_project(pdb, conn, params)
- pdb.add_folder(
- conn,
- proj.id,
- str(params.get("path") or ""),
- label=params.get("label"),
- is_primary=bool(params.get("is_primary")),
- )
- return _ok(rid, {"project": pdb.get_project(conn, proj.id).to_dict()})
+ Falls back to ``.png``. WebP needs the RIFF/WEBP container check, handled
+ before the generic table.
+ """
+ if filename:
+ suffix = Path(filename).suffix.lower()
+ if suffix:
+ return suffix
+ head = img_bytes[:16]
+ if head.startswith(b"RIFF") and head[8:12] == b"WEBP":
+ return ".webp"
+ for sig, ext in _IMAGE_MAGIC:
+ if head.startswith(sig):
+ return ext
+ return ".png"
- @_projects_method("projects.remove_folder")
- def _(rid, params, pdb, conn) -> dict:
- proj = _require_project(pdb, conn, params)
- pdb.remove_folder(conn, proj.id, str(params.get("path") or ""))
- return _ok(rid, {"project": pdb.get_project(conn, proj.id).to_dict()})
+ def _allowed_image_extensions() -> frozenset[str]:
+ try:
+ from cli import _IMAGE_EXTENSIONS
+ return frozenset(_IMAGE_EXTENSIONS)
+ except Exception:
+ return frozenset({".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp"})
- @_projects_method("projects.set_primary")
- def _(rid, params, pdb, conn) -> dict:
- proj = _require_project(pdb, conn, params)
- pdb.set_primary(conn, proj.id, str(params.get("path") or ""))
- return _ok(rid, {"project": pdb.get_project(conn, proj.id).to_dict()})
+ def _queue_attached_image(session: dict, img_bytes: bytes, ext: str, *, prefix: str) -> Path:
+ """Write image bytes into the gateway's images dir and queue them.
- @_projects_method("projects.archive")
- def _(rid, params, pdb, conn) -> dict:
- proj = _require_project(pdb, conn, params)
- (pdb.restore_project if params.get("restore") else pdb.archive_project)(conn, proj.id)
- return _ok(rid, _projects_payload(conn))
+ Mirrors what ``image.attach`` does for a local path: appends to
+ ``session["attached_images"]`` so the next ``prompt.submit`` picks it up via
+ the existing native-image-attach pipeline. Returns the written path.
+ """
+ session["image_counter"] = session.get("image_counter", 0) + 1
+ img_dir = _hermes_home / "images"
+ img_dir.mkdir(parents=True, exist_ok=True)
+ ts = datetime.now().strftime("%Y%m%d_%H%M%S")
+ img_path = img_dir / f"{prefix}_{ts}_{session['image_counter']}{ext}"
+ try:
+ img_path.write_bytes(img_bytes)
+ except Exception:
+ session["image_counter"] = max(0, session["image_counter"] - 1)
+ raise
+ session.setdefault("attached_images", []).append(str(img_path))
+ return img_path
- @_projects_method("projects.delete")
- def _(rid, params, pdb, conn) -> dict:
- proj = _require_project(pdb, conn, params)
- pdb.delete_project(conn, proj.id)
- return _ok(rid, _projects_payload(conn))
+ _ATTACHMENT_REF_NEEDS_QUOTING_RE = None
- @_projects_method("projects.set_active")
- def _(rid, params, pdb, conn) -> dict:
- pdb.set_active(conn, _require_project(pdb, conn, params).id if params.get("id") else None)
- return _ok(rid, {"active_id": pdb.get_active_id(conn)})
+ def _format_ref_value(value: str) -> str:
+ """Quote a context-ref value when it contains whitespace or bracket chars.
+ Mirrors the desktop ``formatRefValue`` so the staged ``@file:`` ref round-trips
+ through ``agent.context_references`` cleanly.
+ """
+ import re as _re
- @_projects_method("projects.for_cwd")
- def _(rid, params, pdb, conn) -> dict:
- cwd = _completion_cwd({"cwd": str(params.get("cwd") or "").strip()} if params.get("cwd") else {})
- proj = pdb.project_for_path(conn, cwd)
- return _ok(rid, {"project": proj.to_dict() if proj else None, "cwd": cwd, "branch": _git_branch_for_cwd(cwd)})
+ global _ATTACHMENT_REF_NEEDS_QUOTING_RE
+ if _ATTACHMENT_REF_NEEDS_QUOTING_RE is None:
+ _ATTACHMENT_REF_NEEDS_QUOTING_RE = _re.compile(r"""[\s()\[\]{}<>"'`]""")
+ if not value or not _ATTACHMENT_REF_NEEDS_QUOTING_RE.search(value):
+ return value
+ if "`" not in value:
+ return f"`{value}`"
+ if '"' not in value:
+ return f'"{value}"'
+ if "'" not in value:
+ return f"'{value}'"
+ return value
- def _is_repo_junk(root: str) -> bool:
- """A git root we never auto-surface as a project: the bare home dir or
- anything under HERMES_HOME (~/.hermes by default) — config/sessions/skills,
- not a workspace. User-created projects pointing there are still honored."""
- if not root:
- return True
+ def _attachment_ref_path(session: dict, target: Path) -> str:
+ """Workspace-relative path for an attachment, or the absolute path if outside."""
+ workspace = Path(_session_cwd(session)).resolve()
+ try:
+ rel = target.resolve().relative_to(workspace)
+ return str(rel).replace(os.sep, "/")
+ except ValueError:
+ return str(target.resolve())
- from hermes_constants import get_hermes_home
- real = os.path.realpath(root)
- home = os.path.realpath(os.path.expanduser("~"))
- hermes_home = os.path.realpath(str(get_hermes_home()))
+ def _desktop_attachment_dir(session: dict) -> Path:
+ root = Path(_session_cwd(session)).resolve() / ".hermes" / "desktop-attachments"
+ root.mkdir(parents=True, exist_ok=True)
+ return root
- return real == home or real == hermes_home or real.startswith(hermes_home + os.sep)
+ def _sanitize_attachment_name(name: str) -> str:
+ import re as _re
- def _is_session_cwd_junk(cwd: str) -> bool:
- """A non-git cwd that should stay in flat Recents rather than auto-group.
+ candidate = Path(str(name or "").strip()).name
+ candidate = _re.sub(r"[\x00-\x1f]+", "_", candidate)
+ candidate = candidate.strip().strip(".")
+ return candidate or "attachment"
- Unlike discovered git roots, an explicitly selected descendant of
- HERMES_HOME may be an intentional prose/data workspace. The pre-Projects
- desktop surfaced every such cwd, so exclude only the two broad defaults
- that would create catch-all projects.
- """
- if not cwd:
- return True
- from hermes_constants import get_hermes_home
+ def _unique_attachment_path(root: Path, filename: str) -> Path:
+ candidate = root / filename
+ if not candidate.exists():
+ return candidate
+ stem = Path(filename).stem or "attachment"
+ suffix = Path(filename).suffix
+ counter = 2
+ while True:
+ next_candidate = root / f"{stem}-{counter}{suffix}"
+ if not next_candidate.exists():
+ return next_candidate
+ counter += 1
- real = os.path.normcase(os.path.realpath(cwd))
- home = os.path.normcase(os.path.realpath(os.path.expanduser("~")))
- hermes_home = os.path.normcase(os.path.realpath(str(get_hermes_home())))
- return real == home or real == hermes_home
+ def _resolve_gateway_attachment_path(raw: str) -> Path | None:
+ """Resolve a raw path token to a gateway-visible file, or None."""
+ if not raw:
+ return None
+ try:
+ from cli import _detect_file_drop, _resolve_attachment_path, _split_path_input
+ except Exception:
+ return None
- def _repo_discovery_policy(raw: dict | None = None) -> dict:
- """Return the effective, profile-local Desktop repository scan policy."""
- from hermes_cli.config import DEFAULT_CONFIG
+ dropped = _detect_file_drop(raw)
+ if dropped:
+ return Path(dropped["path"]).resolve()
+ path_token, _remainder = _split_path_input(raw)
+ resolved = _resolve_attachment_path(path_token)
+ return Path(resolved).resolve() if resolved is not None else None
- defaults = DEFAULT_CONFIG["desktop"]
- source = raw if isinstance(raw, dict) else (_load_cfg().get("desktop") or {})
- if not isinstance(source, dict):
- source = {}
- enabled = source.get("enabled", source.get("repo_scan_enabled", defaults["repo_scan_enabled"]))
- roots = source.get("roots", source.get("repo_scan_roots", defaults["repo_scan_roots"]))
- excludes = source.get(
- "exclude_paths",
- source.get("repo_scan_exclude_paths", defaults["repo_scan_exclude_paths"]),
- )
+ def _decode_attachment_data_url(data_url: str) -> bytes:
+ """Decode a ``data:<any-mime>;base64,<b64>`` payload to bytes.
- return {
- "enabled": enabled if isinstance(enabled, bool) else defaults["repo_scan_enabled"],
- "roots": [value.strip() for value in roots if isinstance(value, str) and value.strip()]
- if isinstance(roots, list)
- else list(defaults["repo_scan_roots"]),
- "exclude_paths": [
- value.strip()
- for value in excludes
- if isinstance(value, str) and value.strip()
- ]
- if isinstance(excludes, list)
- else list(defaults["repo_scan_exclude_paths"]),
- }
+ Unlike ``_decode_attach_base64`` (image-mime-specific), this accepts any
+ media type — text/csv, application/pdf, etc. — so non-image file uploads
+ round-trip. Also tolerates a bare base64 string with no data-URL prefix.
+ """
+ import base64 as _base64
+ import binascii as _binascii
+ import re as _re
+
+ cleaned = (data_url or "").strip()
+ m = _re.match(r"^data:[^;,]*(?:;[^;,=]+=[^;,]+)*;base64,(.*)$", cleaned, _re.DOTALL | _re.I)
+ if m:
+ cleaned = m.group(1)
+ cleaned = _re.sub(r"\s+", "", cleaned)
+ try:
+ return _base64.b64decode(cleaned, validate=True)
+ except (ValueError, _binascii.Error) as exc:
+ raise ValueError("invalid data_url payload") from exc
- def _repo_discovery_policy_key(policy: dict) -> str:
- def _paths(values: list[str]) -> list[str]:
- normalized = set()
- home = os.path.expanduser("~")
- for value in values:
- expanded = os.path.expanduser(value)
- if not os.path.isabs(expanded):
- expanded = os.path.join(home, expanded)
- normalized.add(os.path.normcase(os.path.abspath(expanded)))
- return sorted(normalized)
+ def _stage_session_file_attachment(
+ session: dict,
+ *,
+ raw_path: str,
+ data_url: str,
+ name: str,
+ ) -> tuple[Path, bool]:
+ """Make a desktop file attachment available to the remote gateway agent.
- canonical = {
- "enabled": bool(policy["enabled"]),
- "roots": _paths(policy["roots"]),
- "exclude_paths": _paths(policy["exclude_paths"]),
- }
- return json.dumps(canonical, sort_keys=True, separators=(",", ":"))
+ Three cases:
+ 1. The path resolves to a file already INSIDE the session workspace — use
+ it as-is (no copy, ``uploaded=False``).
+ 2. The path resolves to a gateway-visible file OUTSIDE the workspace — copy
+ it into ``.hermes/desktop-attachments/`` so the ``@file:`` ref resolves.
+ 3. The path doesn't exist on the gateway (the common remote case: it's a
+ path on the CLIENT's disk) — decode the uploaded ``data_url`` bytes and
+ write them into ``.hermes/desktop-attachments/``.
+ Returns ``(stored_path, uploaded)``.
+ """
+ workspace = Path(_session_cwd(session)).resolve()
+ resolved = _resolve_gateway_attachment_path(raw_path)
+ if resolved is not None:
+ try:
+ resolved.relative_to(workspace)
+ return resolved, False
+ except ValueError:
+ payload = resolved.read_bytes()
+ filename = resolved.name
+ else:
+ if not data_url:
+ raise ValueError("file not found on gateway and no data_url provided")
+ payload = _decode_attachment_data_url(data_url)
+ filename = _sanitize_attachment_name(name or Path(str(raw_path or "")).name)
- def _repo_discovery_policy_is_default(policy: dict) -> bool:
- from hermes_cli.config import DEFAULT_CONFIG
+ upload_dir = _desktop_attachment_dir(session)
+ target = _unique_attachment_path(upload_dir, _sanitize_attachment_name(filename))
+ target.write_bytes(payload)
+ return target.resolve(), True
- return _repo_discovery_policy_key(policy) == _repo_discovery_policy_key(
- _repo_discovery_policy(DEFAULT_CONFIG["desktop"])
- )
+ # ── Methods: respond ─────────────────────────────────────────────────
- def _discover_repos_payload(
- db, *, conn=None, backfill: bool = True, include_cached: bool = True
- ) -> list[dict]:
- """Merge filesystem-scanned repos (cached) with session-derived repo roots.
- Repo-first: the disk scan (persisted by `projects.record_repos`) surfaces
- repos even with zero hermes sessions. Session-derived roots cover repos
- outside the scan roots. Both are junk-filtered (hermes home subtree + bare
- home) and carry their session totals for the overview.
+ def _respond(rid, params, key, *, allow_expired=False):
+ r = params.get("request_id", "")
+ with _prompt_lock:
+ entry = _pending.get(r)
+ if not entry:
+ if allow_expired and r:
+ return _ok(rid, {"status": "expired"})
+ return _err(rid, 4009, f"no pending {key} request")
+ _, ev = entry
+ _answers[r] = params.get(key, "")
+ ev.set()
+ return _ok(rid, {"status": "ok"})
- ``conn`` reuses an already-open projects.db connection (the tree path holds
- one); ``backfill`` persists resolved roots back onto session rows — kept off
- the per-turn tree path (grouping uses the live git resolver regardless) and
- done only on the explicit discover/record refresh.
- """
- _is_junk = _is_repo_junk
- repos: dict[str, dict] = {}
- def _agg(root: str) -> dict:
- return repos.setdefault(root, {"root": root, "label": "", "sessions": 0, "last_active": 0.0})
+ # ── Methods: config ──────────────────────────────────────────────────
- # Session-derived roots (common repo root, folding worktrees; cached) +
- # backfill the column so persisted git_repo_root matches the tree grouping.
- cwd_rows = list(db.distinct_session_cwds())
- # Warm the per-cwd git probes in parallel so a cold first paint doesn't
- # serialize one subprocess per distinct cwd before this loop reads the cache.
- git_probe.warm_roots(str(r.get("cwd") or "") for r in cwd_rows)
- cwd_to_root: dict[str, str] = {}
- for row in cwd_rows:
- cwd = str(row.get("cwd") or "")
- root = _git_common_repo_root_for_cwd(cwd)
- if not root:
- continue
- cwd_to_root[cwd] = root
- if _is_junk(root):
- continue
- agg = _agg(root)
- agg["sessions"] += int(row.get("sessions") or 0)
- agg["last_active"] = max(agg["last_active"], float(row.get("last_active") or 0))
- if backfill:
+ # NOTE: config.set intentionally stays in server.py for now — the in-flight
+ # opt/model-resolution-core PR touches its body; move it to methods_config.py
+ # in a follow-up once that PR lands.
+ @method("config.set")
+ def _(rid, params: dict) -> dict:
+ key, value = params.get("key", ""), params.get("value", "")
+ session = _sessions.get(params.get("session_id", ""))
+
+ if key == "model":
try:
- db.backfill_repo_roots(cwd_to_root)
- except Exception:
- logger.debug("failed to backfill repo roots", exc_info=True)
+ if not value:
+ return _err(rid, 4002, "model value required")
+ if session:
+ # Reject during an in-flight turn. agent.switch_model()
+ # mutates self.model / self.provider / self.base_url /
+ # self.client in place; the worker thread running
+ # agent.run_conversation is reading those on every
+ # iteration. A mid-turn swap can send an HTTP request
+ # with the new base_url but old model (or vice versa),
+ # producing 400/404s the user never asked for. Parity
+ # with the gateway's running-agent /model guard.
+ if session.get("running"):
+ return _err(
+ rid,
+ 4009,
+ "session busy — /interrupt the current turn before switching models",
+ )
- from hermes_cli.model_switch import parse_model_flags_detailed
++ from hermes_cli.model_switch import parse_model_switch_args
- if not include_cached:
- out = sorted(repos.values(), key=lambda repo: repo["last_active"], reverse=True)
- for repo in out:
- repo["label"] = (
- repo["label"]
- or os.path.basename(repo["root"].rstrip("/\\"))
- or repo["root"]
- parsed_flags = parse_model_flags_detailed(value)
++ parsed_flags = parse_model_switch_args(value)
+ explicit_provider = parsed_flags.explicit_provider
+ if session.get("agent") is None and not explicit_provider.strip():
+ session_id = params.get("session_id", "")
+ _start_agent_build(session_id, session)
+ init_err = _wait_agent(session, rid)
+ if init_err:
+ return init_err
+ if session.get("agent") is None:
+ return _err(rid, 5032, "agent initialization failed")
+ result = _apply_model_switch(
+ params.get("session_id", ""),
+ session,
+ value,
+ confirm_expensive_model=bool(
+ params.get("confirm_expensive_model", False)
+ ),
+ parsed_flags=parsed_flags,
+ )
+ else:
+ result = _apply_model_switch(
+ "",
+ {"agent": None},
+ value,
+ confirm_expensive_model=bool(
+ params.get("confirm_expensive_model", False)
+ ),
+ )
+ return _ok(
+ rid,
+ {
+ "key": key,
+ "value": result["value"],
+ "warning": result["warning"],
+ "confirm_required": result.get("confirm_required", False),
+ "confirm_message": result.get("confirm_message", ""),
+ "scope": result.get("scope", "session"),
+ },
)
- return out
+ except Exception as e:
+ return _err(rid, 5001, str(e))
- # Filesystem-scanned roots from the cache (may have zero sessions). Reuse the
- # caller's projects.db connection when given, else open a short-lived one.
- try:
- from hermes_cli import projects_db as pdb
+ if key == "fast":
+ raw = str(value or "").strip().lower()
+ agent = session.get("agent") if session else None
+ if agent is not None:
+ current_fast = getattr(agent, "service_tier", None) == "priority"
+ elif session is not None and session.get("create_service_tier_override") is not None:
+ # Pre-build session with a pinned tier (desktop draft pick or an
+ # earlier session-scoped toggle) — report/toggle from the pin, not
+ # the global default.
+ current_fast = session["create_service_tier_override"] == "priority"
+ else:
+ current_fast = _load_service_tier() == "priority"
- def _read(c) -> None:
- for entry in pdb.list_discovered_repos(c):
- root = str(entry.get("root") or "")
- if not root or _is_junk(root):
- continue
- agg = _agg(root)
- if entry.get("label"):
- agg["label"] = entry["label"]
- # NOTE: `last_seen` is when the disk scan last saw the directory,
- # not when the user last worked in it. Folding it into
- # `last_active` stamped every scanned repo with the scan time —
- # i.e. "just now" — so a git checkout with zero Hermes sessions
- # outranked the repos the user actually works in. Activity stays
- # session-derived; a repo with no sessions has no activity.
+ if raw in {"status"}:
+ return _ok(
+ rid,
+ {"key": key, "value": "fast" if current_fast else "normal"},
+ )
- if conn is not None:
- _read(conn)
+ if raw in {"", "toggle"}:
+ nv = "normal" if current_fast else "fast"
+ elif raw in {"fast", "on"}:
+ nv = "fast"
+ elif raw in {"normal", "off"}:
+ nv = "normal"
else:
- with pdb.connect_closing() as own:
- _read(own)
- except Exception:
- logger.debug("failed to read discovered repo cache", exc_info=True)
-
- out = sorted(repos.values(), key=lambda r: r["last_active"], reverse=True)
- for r in out:
- r["label"] = r["label"] or os.path.basename(r["root"].rstrip("/\\")) or r["root"]
- return out
+ return _err(rid, 4002, f"unknown fast mode: {value}")
+ overrides = None
+ if nv == "fast":
+ from hermes_cli.models import resolve_fast_mode_overrides
- @method("projects.discover_repos")
- def _(rid, params: dict) -> dict:
- """Repos for the desktop overview: scanned-from-disk (cached) ∪ session-derived."""
- try:
- db = _get_db()
- if db is None:
- return _ok(rid, {"repos": []})
- from hermes_cli import projects_db as pdb
+ if agent is not None:
+ target_model = getattr(agent, "model", None)
+ else:
+ # A pre-build session may already have a picked model riding in
+ # model_override (desktop draft) — validate fast support against
+ # THAT model, not the global default it will never use.
+ session_override = (session or {}).get("model_override") or {}
+ target_model = (
+ session_override.get("model")
+ if isinstance(session_override, dict)
+ else None
+ ) or _resolve_model()
+ if not target_model:
+ return _err(
+ rid,
+ 4002,
+ "fast mode is not available without a selected model",
+ )
+ overrides = resolve_fast_mode_overrides(target_model)
+ if overrides is None:
+ return _err(
+ rid,
+ 4002,
+ "fast mode is not available for this model",
+ )
- policy = _repo_discovery_policy()
- policy_key = _repo_discovery_policy_key(policy)
- with pdb.connect_closing() as conn:
- pdb.reconcile_discovered_repos_policy(
- conn,
- policy_key,
- preserve_unversioned=_repo_discovery_policy_is_default(policy),
+ if session is not None:
+ # Session-scoped, like `reasoning` below (global persistence is
+ # `--global` / Settings → Model territory). Writing config.yaml
+ # here let every desktop model-menu selection (per-model fast
+ # preset) rewrite the user's global agent.service_tier — flipping
+ # fast mode for every OTHER session, profile, CLI, and gateway
+ # build ("switch one session, switches everywhere"). Pin the
+ # create override so lazily-built sessions and rebuilds (/new,
+ # deferred resume) keep the choice; "" pins normal explicitly.
+ session["create_service_tier_override"] = (
+ "priority" if nv == "fast" else ""
)
- repos = _discover_repos_payload(
- db, conn=conn, include_cached=policy["enabled"]
+ else:
+ _write_config_key("agent.service_tier", nv)
+ if agent is not None:
+ agent.service_tier = "priority" if nv == "fast" else None
+ current_overrides = dict(getattr(agent, "request_overrides", {}) or {})
+ current_overrides.pop("service_tier", None)
+ current_overrides.pop("speed", None)
+ if nv == "fast":
+ current_overrides.update(overrides)
+ agent.request_overrides = current_overrides
+ _persist_live_session_runtime(session)
+ _emit(
+ "session.info",
+ params.get("session_id", ""),
+ _session_info(agent, session),
)
- return _ok(rid, {"repos": repos, "discovery_policy": policy})
- except Exception as e:
- return _err(rid, 5061, str(e))
-
+ return _ok(rid, {"key": key, "value": nv})
- @method("projects.record_repos")
- def _(rid, params: dict) -> dict:
- """Persist git repo roots found by the client's filesystem scan, then return
- the merged repo list. The native crawl runs on the desktop (local fs); this
- caches the result so later reads are instant instead of re-walking disk."""
- try:
- from hermes_cli import projects_db as pdb
+ if key == "busy":
+ raw = str(value or "").strip().lower()
+ if raw in {"", "status"}:
+ return _ok(rid, {"key": key, "value": _load_busy_input_mode()})
+ if raw not in {"queue", "steer", "interrupt"}:
+ return _err(rid, 4002, f"unknown busy mode: {value}")
+ _write_config_key("display.busy_input_mode", raw)
+ return _ok(rid, {"key": key, "value": raw})
- policy = _repo_discovery_policy()
- policy_key = _repo_discovery_policy_key(policy)
- incoming_raw = params.get("discovery_policy")
- incoming_policy = (
- _repo_discovery_policy(incoming_raw)
- if isinstance(incoming_raw, dict)
- else None
- )
- incoming_matches = (
- incoming_policy is not None
- and _repo_discovery_policy_key(incoming_policy) == policy_key
+ if key == "verbose":
+ cycle = ["off", "new", "all", "verbose"]
+ cur = (
+ session.get("tool_progress_mode", _load_tool_progress_mode())
+ if session
+ else _load_tool_progress_mode()
)
- accept_legacy_default = (
- incoming_policy is None and _repo_discovery_policy_is_default(policy)
+ if value and value != "cycle":
+ nv = str(value).strip().lower()
+ if nv not in cycle:
+ return _err(rid, 4002, f"unknown verbose mode: {value}")
+ else:
+ try:
+ idx = cycle.index(cur)
+ except ValueError:
+ idx = 2
+ nv = cycle[(idx + 1) % len(cycle)]
+ _write_config_key("display.tool_progress", nv)
+ if session:
+ session["tool_progress_mode"] = nv
+ agent = session.get("agent")
+ if agent is not None:
+ agent.verbose_logging = nv == "verbose"
+ return _ok(rid, {"key": key, "value": nv})
+
+ if key == "focus":
+ # Focus view — display-only reduced-output mode (/focus). Composes with
+ # the tool_progress machinery rather than duplicating it: enabling it
+ # pins tool_progress to "off" (the same value /verbose off uses) after
+ # stashing the configured mode, and disabling it restores that mode.
+ # Nothing about the request payload changes.
+ from hermes_cli.focus_view import (
+ FOCUS_TOOL_PROGRESS_MODE,
+ normalize_tool_progress_mode,
+ resolve_focus_arg,
)
- pairs: list[tuple[str, str | None]] = []
- for item in params.get("repos") or []:
- if isinstance(item, str):
- pairs.append((item, None))
- elif isinstance(item, dict) and item.get("root"):
- pairs.append((str(item["root"]), item.get("label")))
+ cfg_f = _load_cfg()
+ _display_f = cfg_f.get("display")
+ d_f: dict = _display_f if isinstance(_display_f, dict) else {}
+ cur_focus = bool(d_f.get("focus_view", False))
+ action, target = resolve_focus_arg(str(value or ""), cur_focus)
+ if action == "usage":
+ return _err(rid, 4002, f"unknown focus value: {value} (use on|off|status)")
+ if action == "status" or target is None:
+ return _ok(
+ rid,
+ {
+ "key": key,
+ "value": "on" if cur_focus else "off",
+ "tool_progress": _load_tool_progress_mode(),
+ },
+ )
- with pdb.connect_closing() as conn:
- pdb.reconcile_discovered_repos_policy(
- conn,
- policy_key,
- preserve_unversioned=_repo_discovery_policy_is_default(policy),
+ if target:
+ saved = normalize_tool_progress_mode(
+ (d_f.get("focus_saved_tool_progress") or _load_tool_progress_mode())
+ if cur_focus
+ else _load_tool_progress_mode()
)
- accepted = bool(
- policy["enabled"] and (incoming_matches or accept_legacy_default)
+ _write_config_key("display.focus_saved_tool_progress", saved)
+ _write_config_key("display.tool_progress", FOCUS_TOOL_PROGRESS_MODE)
+ effective = FOCUS_TOOL_PROGRESS_MODE
+ else:
+ saved = normalize_tool_progress_mode(
+ d_f.get("focus_saved_tool_progress") or "all"
)
- if accepted:
- pdb.record_discovered_repos(
- conn, pairs, replace=True, policy_key=policy_key
- )
- elif not policy["enabled"]:
- pdb.clear_discovered_repos(conn, policy_key=policy_key)
+ _write_config_key("display.tool_progress", saved)
+ effective = saved
+ _write_config_key("display.focus_view", bool(target))
- db = _get_db()
+ if session:
+ session["focus_view"] = bool(target)
+ session["tool_progress_mode"] = effective
+ agent_f = session.get("agent")
+ if agent_f is not None:
+ try:
+ agent_f.tool_progress_mode = effective
+ except Exception:
+ pass
return _ok(
rid,
{