Skip to content

The agent that grows with you

refactor(tui): split auto-continue, session history shaping and agent-callback wiring out of server.py

Teknium1134e5171d7e
diff --git a/tui_gateway/agent_callbacks.py b/tui_gateway/agent_callbacks.py
new file mode 100644
index 00000000000..7c2c993ac74
--- /dev/null
+++ b/tui_gateway/agent_callbacks.py
@@ -0,0 +1,686 @@
+"""Agent callback wiring: child-session live mirror, per-session agent callbacks, personality overlay, background/preview agent kwargs, agent reset.
+
+Bodies are rebound onto server.py's globals at install time (see
+method_ctx.bind_module), so they reference server.py globals bare.
+"""
+
+from __future__ import annotations
+
+import threading
+
+from .method_ctx import HandlerRegistry, bind_module
+
+_registry = HandlerRegistry()
+
+
+# ── Child-session live mirror ────────────────────────────────────────
+# A delegated child is not a live gateway session — it runs synchronously
+# inside the parent's turn, and its activity reaches the gateway only as
+# relayed ``subagent.*`` events on the PARENT sid. When a UI opens the child's
+# own session (session.resume on ``child_session_id``, e.g. the desktop's
+# open-in-new-window), that window would otherwise sit silent until the run
+# persists. Translate the relayed events into the native stream events the
+# window already renders — emitted on the CHILD sid, routed to its transport
+# by write_json — so the window shows a real midstream turn.
+_child_mirrors: dict[str, dict] = {}
+_child_mirrors_lock = threading.Lock()
+# Stored child session ids with a delegation run currently in flight (refreshed
+# on every relayed subagent.* event, popped on subagent.complete). Lets a lazy
+# watch resume report running=true so the window shows a busy indicator even
+# while the child is silent inside a long tool call (no events for 25s+).
+_active_child_runs: dict[str, float] = {}
+# Staleness bound for the registry: entries refresh on every relayed event, so
+# anything this quiet means the completion event was lost (callback raised,
+# parent crashed) — don't let a leaked entry pin "running" forever.
+_CHILD_RUN_STALE_S = 3600.0
+
+
+def _child_run_active(child_key: str) -> bool:
+ ts = _active_child_runs.get(child_key)
+ return ts is not None and (time.time() - ts) < _CHILD_RUN_STALE_S
+
+
+def _mirror_subagent_to_child(event_type: str, payload: dict) -> None:
+ child_key = str(payload.get("child_session_id") or "")
+ if not child_key:
+ return
+ # Liveness registry first — it must be accurate even when no window is
+ # open, so a window opened mid-run can immediately know the child is busy.
+ if event_type == "subagent.complete":
+ _active_child_runs.pop(child_key, None)
+ else:
+ _active_child_runs[child_key] = time.time()
+ # Mirror only into a live watch session (keyed by session_key; its live sid
+ # differs from the stored id) that has NOT been upgraded to a full agent.
+ # No window / closed → nothing to mirror; an upgraded session owns a real
+ # native stream and mirroring on top would interleave two turns on one sid.
+ # Either way drop state so a reopened window starts a fresh synthetic turn.
+ live = _find_live_session_by_key(child_key)
+ if live is None or live[1].get("agent") is not None:
+ with _child_mirrors_lock:
+ _child_mirrors.pop(child_key, None)
+ return
+ csid = live[0]
+ with _child_mirrors_lock:
+ st = _child_mirrors.setdefault(child_key, {"seq": 0, "open_tool": None, "started": False})
+ if not st["started"]:
+ st["started"] = True
+ _emit("message.start", csid)
+ if event_type == "subagent.thinking":
+ if text := str(payload.get("text") or ""):
+ _emit("reasoning.delta", csid, {"text": text})
+ elif event_type == "subagent.text":
+ # The child's streamed reply text — the actual "agent talking".
+ # Relayed token-by-token from the child's run_conversation
+ # stream_callback, so the watch window streams the reply live.
+ if text := str(payload.get("text") or ""):
+ _emit("message.delta", csid, {"text": text})
+ elif event_type == "subagent.start":
+ # One-time header line (the child's goal) so a freshly opened window
+ # shows immediate context before the first reply token streams.
+ if text := str(payload.get("text") or ""):
+ _emit("message.delta", csid, {"text": f"{text}\n"})
+ elif event_type == "subagent.tool":
+ if st["open_tool"]:
+ _emit("tool.complete", csid, st["open_tool"])
+ st["seq"] += 1
+ tool = {
+ "name": str(payload.get("tool_name") or "tool"),
+ "tool_id": f"submirror:{child_key}:{st['seq']}",
+ "args": {},
+ }
+ if preview := str(payload.get("tool_preview") or payload.get("text") or ""):
+ tool["preview"] = preview
+ st["open_tool"] = tool
+ _emit("tool.start", csid, tool)
+ elif event_type == "subagent.complete":
+ if st["open_tool"]:
+ _emit("tool.complete", csid, st["open_tool"])
+ summary = str(payload.get("summary") or payload.get("text") or "")
+ _emit("message.complete", csid, {"text": summary})
+ _child_mirrors.pop(child_key, None)
+
+
+def _agent_cbs(sid: str) -> dict:
+ callbacks = {
+ "tool_start_callback": lambda tc_id, name, args: _on_tool_start(
+ sid, tc_id, name, args
+ ),
+ "tool_complete_callback": lambda tc_id, name, args, result: _on_tool_complete(
+ sid, tc_id, name, args, result
+ ),
+ "tool_progress_callback": lambda event_type, name=None, preview=None, args=None, **kwargs: _on_tool_progress(
+ sid, event_type, name, preview, args, **kwargs
+ ),
+ "tool_gen_callback": lambda name: _tool_progress_enabled(sid)
+ and _emit("tool.generating", sid, {"name": name}),
+ "thinking_callback": lambda text: _emit("thinking.delta", sid, {"text": text}),
+ # Affection reaction (ily / <3 / good bot) → hearts. Core-detected, so
+ # the TUI heart and desktop floating hearts share one signal.
+ "reaction_callback": lambda kind: _emit("reaction", sid, {"kind": kind}),
+ "reasoning_callback": lambda text: _emit(
+ "reasoning.delta",
+ sid,
+ {"text": text, **({"verbose": True} if _session_verbose(sid) else {})},
+ ),
+ "status_callback": lambda kind, text=None: _status_update(
+ sid, str(kind), None if text is None else str(text)
+ ),
+ # Credits/notice spine (L1): an AgentNotice fired by the agent becomes a
+ # notification.show WS event; a recovery clear becomes notification.clear.
+ # Snake_case payload to match the existing gateway-event convention.
+ "notice_callback": lambda n: _emit(
+ "notification.show",
+ sid,
+ {
+ "text": n.text,
+ "level": n.level,
+ "kind": n.kind,
+ "ttl_ms": n.ttl_ms,
+ "key": n.key,
+ "id": n.id,
+ },
+ ),
+ "notice_clear_callback": lambda key: _emit(
+ "notification.clear", sid, {"key": key}
+ ),
+ "clarify_callback": lambda q, c, multi_select=False, questions=None: (
+ _clarify_block(sid, q, c, multi_select=multi_select, questions=questions)
+ ),
+ # read_terminal tool (desktop GUI): same blocking bridge as clarify — the
+ # renderer answers terminal.read.respond with the serialized buffer.
+ "read_terminal_callback": lambda start=None, count=None: _block(
+ "terminal.read.request",
+ sid,
+ {k: v for k, v in (("start", start), ("count", count)) if v is not None},
+ timeout=30,
+ ),
+ # read_preview tool (desktop GUI): the renderer serializes the active
+ # preview tab (a Browser webview's readable text, a file's identity)
+ # and answers preview.read.respond. Longer timeout than the terminal
+ # read — a URL tab extracts text from a live page.
+ "read_preview_callback": lambda start=None, count=None: _block(
+ "preview.read.request",
+ sid,
+ {k: v for k, v in (("start", start), ("count", count)) if v is not None},
+ timeout=45,
+ ),
+ # drive_preview tool (desktop GUI): the renderer injects the interaction
+ # engine into the preview pane's webview (or drives the pane's history)
+ # and answers preview.act.respond with the outcome plus a refreshed
+ # element inventory. Same budget as the preview read, which it ends
+ # with — a click on a slow page pays for the settle and the re-scan.
+ # annotate_preview rides this same callback: it resolves a target
+ # through the same engine and differs only in the verb it sends, so it
+ # needs a tool of its own but not a channel of its own.
+ "drive_preview_callback": lambda payload: _block(
+ "preview.act.request",
+ sid,
+ dict(payload),
+ timeout=45,
+ ),
+ # read_window_below tool (desktop GUI): the renderer asks its main
+ # process (which owns native window enumeration) which OS window sits
+ # directly underneath the Hermes window, and answers
+ # window.read.respond with the serialized metadata.
+ "read_window_below_callback": lambda: _block(
+ "window.read.request",
+ sid,
+ {},
+ timeout=30,
+ ),
+ # setup_mcp tool (desktop GUI): the renderer shows an inline consent
+ # card and walks the user through install/enable/OAuth via the REST
+ # endpoints, then answers mcp.setup.respond with the JSON outcome.
+ # Long timeout on purpose — the flow can include typing an API key or
+ # a browser OAuth round-trip. Same lifecycle as clarify: on timeout
+ # the tool returns "unanswered" and a late answer is tolerated.
+ "setup_mcp_callback": lambda server, action, reason: _block(
+ "mcp.setup.request",
+ sid,
+ {"server": server, "action": action, "reason": reason},
+ timeout=600,
+ ),
+ # tour tool (desktop GUI): the renderer drives driver.js — highlighting
+ # elements in the app's own DOM or injecting the engine into the
+ # preview pane's webview — and answers tour.respond with the outcome
+ # (did the selector match, which step is active).
+ "tour_callback": lambda payload: _tour_request(sid, payload),
+ }
+
+ # Interim assistant commentary (text alongside tool calls, or the attempted
+ # final answer before a verify-on-stop nudge). Gated on
+ # display.interim_assistant_messages (default true). Also set per-turn in
+ # _run_prompt_submit as defense-in-depth — the per-turn set overwrites
+ # this, and the finally block clears it so a stale closure can't fire.
+ if _load_interim_assistant_messages():
+ callbacks["interim_assistant_callback"] = (
+ lambda text, *, already_streamed=False: _emit(
+ "message.interim",
+ sid,
+ {"text": str(text), "already_streamed": bool(already_streamed)},
+ )
+ )
+
+ return callbacks
+
+
+def _apply_project_workspace(task_id: str, path: str, _name: str = "") -> None:
+ """Intentional workspace move from the project_* tools: re-anchor the live
+ session's cwd to the chosen project's folder and push session.info so the
+ desktop follows (refresh tree + scope into the project). This is the ONLY
+ auto-cwd path — driven by an explicit tool call, never a terminal `cd`."""
+ if not path:
+ return
+
+ # The tool's task_id is the durable session_key, but _sessions is keyed by a
+ # short sid uuid (and the desktop routes events by that sid). Resolve it.
+ key = str(task_id or "")
+ sid = ""
+ session = None
+ with _sessions_lock:
+ if key in _sessions:
+ sid, session = key, _sessions[key]
+ else:
+ for cand_sid, cand in _sessions.items():
+ if cand.get("session_key") == key or getattr(cand.get("agent"), "session_id", None) == key:
+ sid, session = cand_sid, cand
+ break
+
+ if session is None:
+ return
+
+ resolved = os.path.abspath(os.path.expanduser(str(path)))
+ if not os.path.isdir(resolved):
+ return
+
+ session["cwd"] = resolved
+ session["explicit_cwd"] = True
+ # An explicit project switch supersedes any earlier settle-adopted cwd.
+ session["cwd_from_settle"] = False
+ _register_session_cwd(session)
+
+ _persist_session_cwd_and_schedule_git_meta(session, resolved)
+
+ try:
+ agent = session.get("agent")
+ info = (
+ _session_info(agent, session)
+ if agent is not None
+ else {
+ "cwd": resolved,
+ "branch": _git_branch_for_cwd(resolved),
+ "project": _project_info_for_cwd(resolved),
+ "lazy": True,
+ }
+ )
+ _emit("session.info", sid, info)
+ except Exception:
+ logger.debug("failed to emit session.info after project workspace move", exc_info=True)
+
+
+def _wire_callbacks(sid: str):
+ from tools.terminal_tool import set_sudo_password_callback
+ from tools.skills_tool import set_secret_capture_callback
+ from tools.project_tools import set_project_workspace_callback
+
+ set_sudo_password_callback(lambda: _block("sudo.request", sid, {}, timeout=120))
+ set_project_workspace_callback(_apply_project_workspace)
+
+ def secret_cb(env_var, prompt, metadata=None):
+ pl = {"prompt": prompt, "env_var": env_var}
+ if metadata:
+ pl["metadata"] = metadata
+ val = _block("secret.request", sid, pl)
+ if not val:
+ return {
+ "success": True,
+ "stored_as": env_var,
+ "validated": False,
+ "skipped": True,
+ "message": "skipped",
+ }
+ from hermes_cli.config import save_env_value_secure
+
+ return {
+ **save_env_value_secure(env_var, val),
+ "skipped": False,
+ "message": "ok",
+ }
+
+ set_secret_capture_callback(secret_cb)
+
+
+def _render_personality_prompt(value) -> str:
+ """Delegates to hermes_cli.personality (single owner of rendering)."""
+ from hermes_cli.personality import render_personality_prompt
+
+ return render_personality_prompt(value)
+
+
+def _available_personalities(cfg: dict | None = None) -> dict:
+ """Built-ins + user overrides, via hermes_cli.personality (single owner)."""
+ from hermes_cli.personality import available_personalities
+
+ if cfg is None:
+ cfg = _load_cfg()
+ return available_personalities(cfg)
+
+
+def _validate_personality(value: str, cfg: dict | None = None) -> tuple[str, str]:
+ """Resolve a requested personality against _available_personalities.
+
+ Same contract as hermes_cli.personality.resolve_personality — (name,
+ prompt) or ValueError — but resolves through the module-level
+ _available_personalities so tests (and future gateway-side overrides)
+ keep a single patch point.
+ """
+ from hermes_cli.personality import normalize_personality_name
+
+ name = normalize_personality_name(value)
+ if not name:
+ return "", ""
+ personalities = _available_personalities(cfg)
+ if name not in personalities:
+ names = ", ".join(f"`{n}`" for n in sorted(personalities))
+ raise ValueError(
+ f"Unknown personality: `{str(value).strip()}`.\n\nAvailable: `none`, {names}"
+ )
+ return name, _render_personality_prompt(personalities[name])
+
+
+def _prompt_text(value) -> str:
+ """Normalize config prompt values from YAML before handing them to AIAgent.
+
+ Delegates to hermes_cli.personality (single owner).
+ """
+ from hermes_cli.personality import prompt_text
+
+ return prompt_text(value)
+
+
+def _apply_personality_to_session(
+ sid: str, session: dict, new_prompt: str, personality: str = ""
+) -> tuple[bool, dict | None]:
+ """Apply a personality change to an existing session without resetting history.
+
+ Updates the agent's ephemeral system prompt in-place so the new personality
+ takes effect on the next turn. The cached base system prompt is left intact
+ (ephemeral_system_prompt is appended at API-call time, not baked into the
+ cache), which preserves prompt-cache hits.
+
+ Also injects a system-role marker into the conversation history so the model
+ knows to pivot its style from this point forward (without this, LLMs tend to
+ continue the tone established by earlier messages in the transcript).
+
+ Returns (history_reset, info) — history_reset is always False since we
+ preserve the conversation.
+ """
+ if not session:
+ return False, None
+ session["personality"] = personality
+
+ agent = session.get("agent")
+ if agent:
+ agent.ephemeral_system_prompt = new_prompt or None
+ # Inject a pivot marker into history so the model sees the change point.
+ # This prevents it from pattern-matching its prior style.
+ if new_prompt:
+ marker = (
+ "[System: The user has changed the assistant's personality. "
+ "From this point forward, adopt the following persona and respond "
+ f"accordingly: {new_prompt}]"
+ )
+ else:
+ marker = (
+ "[System: The user has cleared the personality overlay. "
+ "From this point forward, respond in your normal default style.]"
+ )
+ # Tagged like the model-switch marker (`_append_model_switch_marker`):
+ # the marker rides as role=user so strict OpenAI-compatible providers
+ # accept it mid-conversation, but `display_kind` keeps it out of the
+ # `truncate_before_user_ordinal` addressing space. Untagged, it counts
+ # as a real user turn on the gateway side while no client counts it, so
+ # every later rewind resolves one turn too early and `replace_messages`
+ # hard-deletes the difference (#82756).
+ with session["history_lock"]:
+ session["history"].append(
+ {"role": "user", "content": marker, "display_kind": "personality_switch"}
+ )
+ session["history_version"] = int(session.get("history_version", 0)) + 1
+ info = _session_info(agent)
+ _emit("session.info", sid, info)
+ return False, info
+ return False, None
+
+
+def _cfg_max_turns(cfg: dict, default: int) -> int:
+ from hermes_cli.config import resolve_turn_limit as _resolve_turn_limit
+ # Env var override (highest priority)
+ env_val = os.environ.get("HERMES_TUI_MAX_TURNS")
+ if env_val:
+ return _resolve_turn_limit(env_val, default=default)
+ # Config file value — route through resolve_turn_limit so that
+ # "none"/"unlimited"/0 are first-class spellings, not int() crashes.
+ agent_cfg = cfg.get("agent") or {}
+ raw = agent_cfg.get("max_turns")
+ if raw is None:
+ raw = cfg.get("max_turns")
+ if raw is not None:
+ return _resolve_turn_limit(raw, default=default)
+ return default
+
+
+def _parse_tui_skills_env() -> list[str]:
+ raw = os.environ.get("HERMES_TUI_SKILLS", "")
+ skills: list[str] = []
+ seen: set[str] = set()
+ for part in raw.replace("\n", ",").split(","):
+ item = part.strip()
+ if item and item not in seen:
+ seen.add(item)
+ skills.append(item)
+ return skills
+
+
+def _load_fallback_model():
+ """Return the configured fallback chain for TUI-created agents.
+
+ Delegates to the shared ``get_fallback_chain`` helper so the TUI path
+ stays in parity with ``HermesCLI.__init__`` and ``gateway/run.py``:
+ ``fallback_providers`` is the primary source of truth and keeps its
+ order, with legacy ``fallback_model`` entries merged in afterwards
+ (deduped on provider/model/base_url).
+ """
+ from hermes_cli.fallback_config import get_fallback_chain
+
+ return get_fallback_chain(_load_cfg())
+
+
+def _agent_fallback_model(agent):
+ """Return an agent's fallback chain without rehydrating deliberately empty chains."""
+ if hasattr(agent, "_fallback_chain"):
+ return getattr(agent, "_fallback_chain") or []
+ if hasattr(agent, "_fallback_model"):
+ return getattr(agent, "_fallback_model", None)
+ return _load_fallback_model()
+
+
+def _background_agent_kwargs(agent, task_id: str) -> dict:
+ cfg = _load_cfg()
+
+ return {
+ "base_url": getattr(agent, "base_url", None) or None,
+ "api_key": getattr(agent, "api_key", None) or None,
+ "provider": getattr(agent, "provider", None) or None,
+ "api_mode": getattr(agent, "api_mode", None) or None,
+ "acp_command": getattr(agent, "acp_command", None) or None,
+ "acp_args": getattr(agent, "acp_args", None) or None,
+ "model": getattr(agent, "model", None) or _resolve_model(),
+ "max_iterations": _cfg_max_turns(cfg, 25),
+ "enabled_toolsets": getattr(agent, "enabled_toolsets", None)
+ # Detached background tasks declare platform="tui" below: they have no
+ # UI session id, so a renderer-routed event has nowhere to land. Resolve
+ # their toolsets against that same platform rather than the gateway
+ # process's, so they never carry GUI schema they cannot use.
+ or _load_enabled_toolsets("tui"),
+ "quiet_mode": True,
+ "verbose_logging": False,
+ "ephemeral_system_prompt": getattr(agent, "ephemeral_system_prompt", None)
+ or None,
+ "providers_allowed": getattr(agent, "providers_allowed", None),
+ "providers_ignored": getattr(agent, "providers_ignored", None),
+ "providers_order": getattr(agent, "providers_order", None),
+ "provider_sort": getattr(agent, "provider_sort", None),
+ "provider_require_parameters": getattr(
+ agent, "provider_require_parameters", False
+ ),
+ "provider_data_collection": getattr(agent, "provider_data_collection", None),
+ "openrouter_min_coding_score": getattr(agent, "openrouter_min_coding_score", None),
+ "session_id": task_id,
+ "reasoning_config": getattr(agent, "reasoning_config", None)
+ or _load_reasoning_config(str(getattr(agent, "model", "") or "")),
+ "service_tier": getattr(agent, "service_tier", None) or _load_service_tier(),
+ "request_overrides": dict(getattr(agent, "request_overrides", {}) or {}),
+ "platform": "tui",
+ "session_db": _get_db(),
+ "fallback_model": _agent_fallback_model(agent),
+ }
+
+
+def _ephemeral_preview_agent_kwargs(agent, task_id: str) -> dict:
+ kwargs = _background_agent_kwargs(agent, task_id)
+ kwargs.update(
+ {
+ "enabled_toolsets": ["terminal", "file"],
+ "session_db": None,
+ "skip_memory": True,
+ }
+ )
+ return kwargs
+
+
+def _preview_restart_history(session: dict, max_messages: int = 24, max_tool_chars: int = 1200) -> list[dict]:
+ """Distill the parent session's recent history into a context the
+ ephemeral preview-restart agent can actually use.
+
+ The restart agent has no idea what app the user was building, what
+ server they ran, what cwd was active, or which port belongs to which
+ project. Without this, it would take the bare URL + console logs and
+ guess — usually starting the wrong thing.
+
+ We keep the last ``max_messages`` messages from the parent session so
+ the restart agent sees recent user prompts, assistant replies, and
+ most importantly any terminal/tool calls. Tool result payloads are
+ truncated so we don't blow the context window with file dumps.
+ """
+ try:
+ with session["history_lock"]:
+ history = list(session.get("history", []) or [])
+ except Exception:
+ history = list(session.get("history", []) or [])
+
+ if not history:
+ return []
+
+ # Anchor on the last user turn so we always include at least the most
+ # recent request and the assistant/tool work that followed it. Then
+ # extend backwards up to max_messages so we capture the prior context.
+ last_user_idx = None
+ for idx in range(len(history) - 1, -1, -1):
+ if history[idx].get("role") == "user":
+ last_user_idx = idx
+ break
+
+ start = max(0, len(history) - max_messages)
+ if last_user_idx is not None:
+ start = min(start, last_user_idx)
+
+ trimmed: list[dict] = []
+ for msg in history[start:]:
+ if not isinstance(msg, dict):
+ continue
+ role = msg.get("role")
+ if role not in ("user", "assistant", "tool", "system"):
+ continue
+
+ copy = {k: v for k, v in msg.items() if k != "reasoning"}
+ # Truncate heavy tool outputs so a single 50KB file read doesn't
+ # crowd out the rest of the context.
+ if role == "tool":
+ content = copy.get("content")
+ if isinstance(content, str) and len(content) > max_tool_chars:
+ copy["content"] = (
+ content[:max_tool_chars]
+ + f"\n... (truncated, original {len(content)} chars)"
+ )
+ trimmed.append(copy)
+
+ return trimmed
+
+
+def _preview_tool_result_preview(name: str, result: str) -> str:
+ try:
+ data = json.loads(result)
+ except Exception:
+ return ""
+
+ if not isinstance(data, dict):
+ return ""
+
+ if name == "terminal":
+ output = str(data.get("output") or "").strip()
+ exit_code = data.get("exit_code")
+ if output:
+ return output[-1200:]
+ if data.get("session_id"):
+ return f"Background process started: {data.get('session_id')}"
+ if exit_code is not None:
+ return f"terminal exited with code {exit_code}"
+
+ return str(data.get("error") or "").strip()[:1200]
+
+
+def _preview_restart_callbacks(parent: str, task_id: str) -> dict:
+ started_at: dict[str, float] = {}
+
+ def progress(message: str, level: str = "info") -> None:
+ text = str(message or "").strip()
+ if text:
+ _emit("preview.restart.progress", parent, {"task_id": task_id, "level": level, "text": text})
+
+ def tool_start(tool_call_id: str, name: str, args: dict) -> None:
+ started_at[tool_call_id] = time.time()
+ ctx = _tool_ctx(name, args)
+ progress(f"Running {name}{f': {ctx}' if ctx else ''}")
+
+ def tool_complete(tool_call_id: str, name: str, _args: dict, result: str) -> None:
+ duration_s = time.time() - started_at.get(tool_call_id, time.time())
+ summary = _tool_summary(name, result, duration_s) or f"Finished {name}{f' in {_fmt_tool_duration(duration_s)}' if duration_s else ''}"
+ output = _preview_tool_result_preview(name, result)
+ progress(summary + (f"\n{output}" if output else ""))
+
+ def tool_progress(event_type: str, name: str | None = None, preview: str | None = None, **_kwargs) -> None:
+ if preview:
+ progress(str(preview))
+ elif name:
+ progress(f"{event_type.replace('.', ' ')}: {name}")
+
+ return {
+ "tool_start_callback": tool_start,
+ "tool_complete_callback": tool_complete,
+ "tool_progress_callback": tool_progress,
+ "tool_gen_callback": lambda name: progress(f"Preparing {name}"),
+ "status_callback": lambda kind, text=None: progress(text if text is not None else kind),
+ }
+
+
+def _reset_session_agent(sid: str, session: dict) -> dict:
+ tokens = _set_session_context(session["session_key"])
+ try:
+ # /new is a full conversation boundary: session-scoped runtime
+ # overrides (/model, /reasoning, /fast) do NOT carry forward — the
+ # fresh agent re-derives model/provider, reasoning, and service tier
+ # from config.yaml (#48055, #23131). Session pins are cleared below so
+ # a rebuild can't resurrect them. (Global process state is still never
+ # touched — see the cross-session-contamination note in
+ # _apply_model_switch.)
+ session.pop("model_override", None)
+ session.pop("create_reasoning_override", None)
+ session.pop("create_service_tier_override", None)
+ session.pop("one_turn_model_restore", None)
+ new_agent = _make_agent(
+ sid,
+ session["session_key"],
+ session_id=session["session_key"],
+ platform_override=_session_source(session),
+ context_cwd_is_launch_artifact=(
+ _context_cwd_is_launch_artifact(session)
+ ),
+ )
+ finally:
+ _clear_session_context(tokens)
+ session["agent"] = new_agent
+ session["config_model_seen"] = _config_model_target()
+ session["attached_images"] = []
+ session["queued_prompt"] = None
+ session.pop("queued_prompts", None)
+ session["_queued_prompt_generation"] = int(session.get("_queued_prompt_generation", 0)) + 1
+ session["edit_snapshots"] = {}
+ session["image_counter"] = 0
+ session["running"] = False
+ session["show_reasoning"] = _load_show_reasoning()
+ session["tool_progress_mode"] = _load_tool_progress_mode()
+ session["tool_started_at"] = {}
+ with session["history_lock"]:
+ session["history"] = []
+ session["history_version"] = int(session.get("history_version", 0)) + 1
+ info = _session_info(new_agent, session)
+ _emit("session.info", sid, info)
+ _restart_slash_worker(sid, session)
+ return info
+
+
+def register(server) -> None:
+ """Publish this module's helpers + handlers onto ``server``, rebound to its globals."""
+ bind_module(globals(), server, skip=("_",))
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index 476789b2709..a865c5726dc 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -8361,674 +8361,6 @@ def _on_tool_progress(
_mirror_subagent_to_child(event_type, payload)
-# ── Child-session live mirror ────────────────────────────────────────
-# A delegated child is not a live gateway session — it runs synchronously
-# inside the parent's turn, and its activity reaches the gateway only as
-# relayed ``subagent.*`` events on the PARENT sid. When a UI opens the child's
-# own session (session.resume on ``child_session_id``, e.g. the desktop's
-# open-in-new-window), that window would otherwise sit silent until the run
-# persists. Translate the relayed events into the native stream events the
-# window already renders — emitted on the CHILD sid, routed to its transport
-# by write_json — so the window shows a real midstream turn.
-_child_mirrors: dict[str, dict] = {}
-_child_mirrors_lock = threading.Lock()
-# Stored child session ids with a delegation run currently in flight (refreshed
-# on every relayed subagent.* event, popped on subagent.complete). Lets a lazy
-# watch resume report running=true so the window shows a busy indicator even
-# while the child is silent inside a long tool call (no events for 25s+).
-_active_child_runs: dict[str, float] = {}
-# Staleness bound for the registry: entries refresh on every relayed event, so
-# anything this quiet means the completion event was lost (callback raised,
-# parent crashed) — don't let a leaked entry pin "running" forever.
-_CHILD_RUN_STALE_S = 3600.0
-
-
-def _child_run_active(child_key: str) -> bool:
- ts = _active_child_runs.get(child_key)
- return ts is not None and (time.time() - ts) < _CHILD_RUN_STALE_S
-
-
-def _mirror_subagent_to_child(event_type: str, payload: dict) -> None:
- child_key = str(payload.get("child_session_id") or "")
- if not child_key:
- return
- # Liveness registry first — it must be accurate even when no window is
- # open, so a window opened mid-run can immediately know the child is busy.
- if event_type == "subagent.complete":
- _active_child_runs.pop(child_key, None)
- else:
- _active_child_runs[child_key] = time.time()
- # Mirror only into a live watch session (keyed by session_key; its live sid
- # differs from the stored id) that has NOT been upgraded to a full agent.
- # No window / closed → nothing to mirror; an upgraded session owns a real
- # native stream and mirroring on top would interleave two turns on one sid.
- # Either way drop state so a reopened window starts a fresh synthetic turn.
- live = _find_live_session_by_key(child_key)
- if live is None or live[1].get("agent") is not None:
- with _child_mirrors_lock:
- _child_mirrors.pop(child_key, None)
- return
- csid = live[0]
- with _child_mirrors_lock:
- st = _child_mirrors.setdefault(child_key, {"seq": 0, "open_tool": None, "started": False})
- if not st["started"]:
- st["started"] = True
- _emit("message.start", csid)
- if event_type == "subagent.thinking":
- if text := str(payload.get("text") or ""):
- _emit("reasoning.delta", csid, {"text": text})
- elif event_type == "subagent.text":
- # The child's streamed reply text — the actual "agent talking".
- # Relayed token-by-token from the child's run_conversation
- # stream_callback, so the watch window streams the reply live.
- if text := str(payload.get("text") or ""):
- _emit("message.delta", csid, {"text": text})
- elif event_type == "subagent.start":
- # One-time header line (the child's goal) so a freshly opened window
- # shows immediate context before the first reply token streams.
- if text := str(payload.get("text") or ""):
- _emit("message.delta", csid, {"text": f"{text}\n"})
- elif event_type == "subagent.tool":
- if st["open_tool"]:
- _emit("tool.complete", csid, st["open_tool"])
- st["seq"] += 1
- tool = {
- "name": str(payload.get("tool_name") or "tool"),
- "tool_id": f"submirror:{child_key}:{st['seq']}",
- "args": {},
- }
- if preview := str(payload.get("tool_preview") or payload.get("text") or ""):
- tool["preview"] = preview
- st["open_tool"] = tool
- _emit("tool.start", csid, tool)
- elif event_type == "subagent.complete":
- if st["open_tool"]:
- _emit("tool.complete", csid, st["open_tool"])
- summary = str(payload.get("summary") or payload.get("text") or "")
- _emit("message.complete", csid, {"text": summary})
- _child_mirrors.pop(child_key, None)
-
-
-def _agent_cbs(sid: str) -> dict:
- callbacks = {
- "tool_start_callback": lambda tc_id, name, args: _on_tool_start(
- sid, tc_id, name, args
- ),
- "tool_complete_callback": lambda tc_id, name, args, result: _on_tool_complete(
- sid, tc_id, name, args, result
- ),
- "tool_progress_callback": lambda event_type, name=None, preview=None, args=None, **kwargs: _on_tool_progress(
- sid, event_type, name, preview, args, **kwargs
- ),
- "tool_gen_callback": lambda name: _tool_progress_enabled(sid)
- and _emit("tool.generating", sid, {"name": name}),
- "thinking_callback": lambda text: _emit("thinking.delta", sid, {"text": text}),
- # Affection reaction (ily / <3 / good bot) → hearts. Core-detected, so
- # the TUI heart and desktop floating hearts share one signal.
- "reaction_callback": lambda kind: _emit("reaction", sid, {"kind": kind}),
- "reasoning_callback": lambda text: _emit(
- "reasoning.delta",
- sid,
- {"text": text, **({"verbose": True} if _session_verbose(sid) else {})},
- ),
- "status_callback": lambda kind, text=None: _status_update(
- sid, str(kind), None if text is None else str(text)
- ),
- # Credits/notice spine (L1): an AgentNotice fired by the agent becomes a
- # notification.show WS event; a recovery clear becomes notification.clear.
- # Snake_case payload to match the existing gateway-event convention.
- "notice_callback": lambda n: _emit(
- "notification.show",
- sid,
- {
- "text": n.text,
- "level": n.level,
- "kind": n.kind,
- "ttl_ms": n.ttl_ms,
- "key": n.key,
- "id": n.id,
- },
- ),
- "notice_clear_callback": lambda key: _emit(
- "notification.clear", sid, {"key": key}
- ),
- "clarify_callback": lambda q, c, multi_select=False, questions=None: (
- _clarify_block(sid, q, c, multi_select=multi_select, questions=questions)
- ),
- # read_terminal tool (desktop GUI): same blocking bridge as clarify — the
- # renderer answers terminal.read.respond with the serialized buffer.
- "read_terminal_callback": lambda start=None, count=None: _block(
- "terminal.read.request",
- sid,
- {k: v for k, v in (("start", start), ("count", count)) if v is not None},
- timeout=30,
- ),
- # read_preview tool (desktop GUI): the renderer serializes the active
- # preview tab (a Browser webview's readable text, a file's identity)
- # and answers preview.read.respond. Longer timeout than the terminal
- # read — a URL tab extracts text from a live page.
- "read_preview_callback": lambda start=None, count=None: _block(
- "preview.read.request",
- sid,
- {k: v for k, v in (("start", start), ("count", count)) if v is not None},
- timeout=45,
- ),
- # drive_preview tool (desktop GUI): the renderer injects the interaction
- # engine into the preview pane's webview (or drives the pane's history)
- # and answers preview.act.respond with the outcome plus a refreshed
- # element inventory. Same budget as the preview read, which it ends
- # with — a click on a slow page pays for the settle and the re-scan.
- # annotate_preview rides this same callback: it resolves a target
- # through the same engine and differs only in the verb it sends, so it
- # needs a tool of its own but not a channel of its own.
- "drive_preview_callback": lambda payload: _block(
- "preview.act.request",
- sid,
- dict(payload),
- timeout=45,
- ),
- # read_window_below tool (desktop GUI): the renderer asks its main
- # process (which owns native window enumeration) which OS window sits
- # directly underneath the Hermes window, and answers
- # window.read.respond with the serialized metadata.
- "read_window_below_callback": lambda: _block(
- "window.read.request",
- sid,
- {},
- timeout=30,
- ),
- # setup_mcp tool (desktop GUI): the renderer shows an inline consent
- # card and walks the user through install/enable/OAuth via the REST
- # endpoints, then answers mcp.setup.respond with the JSON outcome.
- # Long timeout on purpose — the flow can include typing an API key or
- # a browser OAuth round-trip. Same lifecycle as clarify: on timeout
- # the tool returns "unanswered" and a late answer is tolerated.
- "setup_mcp_callback": lambda server, action, reason: _block(
- "mcp.setup.request",
- sid,
- {"server": server, "action": action, "reason": reason},
- timeout=600,
- ),
- # tour tool (desktop GUI): the renderer drives driver.js — highlighting
- # elements in the app's own DOM or injecting the engine into the
- # preview pane's webview — and answers tour.respond with the outcome
- # (did the selector match, which step is active).
- "tour_callback": lambda payload: _tour_request(sid, payload),
- }
-
- # Interim assistant commentary (text alongside tool calls, or the attempted
- # final answer before a verify-on-stop nudge). Gated on
- # display.interim_assistant_messages (default true). Also set per-turn in
- # _run_prompt_submit as defense-in-depth — the per-turn set overwrites
- # this, and the finally block clears it so a stale closure can't fire.
- if _load_interim_assistant_messages():
- callbacks["interim_assistant_callback"] = (
- lambda text, *, already_streamed=False: _emit(
- "message.interim",
- sid,
- {"text": str(text), "already_streamed": bool(already_streamed)},
- )
- )
-
- return callbacks
-
-
-def _apply_project_workspace(task_id: str, path: str, _name: str = "") -> None:
- """Intentional workspace move from the project_* tools: re-anchor the live
- session's cwd to the chosen project's folder and push session.info so the
- desktop follows (refresh tree + scope into the project). This is the ONLY
- auto-cwd path — driven by an explicit tool call, never a terminal `cd`."""
- if not path:
- return
-
- # The tool's task_id is the durable session_key, but _sessions is keyed by a
- # short sid uuid (and the desktop routes events by that sid). Resolve it.
- key = str(task_id or "")
- sid = ""
- session = None
- with _sessions_lock:
- if key in _sessions:
- sid, session = key, _sessions[key]
- else:
- for cand_sid, cand in _sessions.items():
- if cand.get("session_key") == key or getattr(cand.get("agent"), "session_id", None) == key:
- sid, session = cand_sid, cand
- break
-
- if session is None:
- return
-
- resolved = os.path.abspath(os.path.expanduser(str(path)))
- if not os.path.isdir(resolved):
- return
-
- session["cwd"] = resolved
- session["explicit_cwd"] = True
- # An explicit project switch supersedes any earlier settle-adopted cwd.
- session["cwd_from_settle"] = False
- _register_session_cwd(session)
-
- _persist_session_cwd_and_schedule_git_meta(session, resolved)
-
- try:
- agent = session.get("agent")
- info = (
- _session_info(agent, session)
- if agent is not None
- else {
- "cwd": resolved,
- "branch": _git_branch_for_cwd(resolved),
- "project": _project_info_for_cwd(resolved),
- "lazy": True,
- }
- )
- _emit("session.info", sid, info)
- except Exception:
- logger.debug("failed to emit session.info after project workspace move", exc_info=True)
-
-
-def _wire_callbacks(sid: str):
- from tools.terminal_tool import set_sudo_password_callback
- from tools.skills_tool import set_secret_capture_callback
- from tools.project_tools import set_project_workspace_callback
-
- set_sudo_password_callback(lambda: _block("sudo.request", sid, {}, timeout=120))
- set_project_workspace_callback(_apply_project_workspace)
-
- def secret_cb(env_var, prompt, metadata=None):
- pl = {"prompt": prompt, "env_var": env_var}
- if metadata:
- pl["metadata"] = metadata
- val = _block("secret.request", sid, pl)
- if not val:
- return {
- "success": True,
- "stored_as": env_var,
- "validated": False,
- "skipped": True,
- "message": "skipped",
- }
- from hermes_cli.config import save_env_value_secure
-
- return {
- **save_env_value_secure(env_var, val),
- "skipped": False,
- "message": "ok",
- }
-
- set_secret_capture_callback(secret_cb)
-
-
-def _render_personality_prompt(value) -> str:
- """Delegates to hermes_cli.personality (single owner of rendering)."""
- from hermes_cli.personality import render_personality_prompt
-
- return render_personality_prompt(value)
-
-
-def _available_personalities(cfg: dict | None = None) -> dict:
- """Built-ins + user overrides, via hermes_cli.personality (single owner)."""
- from hermes_cli.personality import available_personalities
-
- if cfg is None:
- cfg = _load_cfg()
- return available_personalities(cfg)
-
-
-def _validate_personality(value: str, cfg: dict | None = None) -> tuple[str, str]:
- """Resolve a requested personality against _available_personalities.
-
- Same contract as hermes_cli.personality.resolve_personality — (name,
- prompt) or ValueError — but resolves through the module-level
- _available_personalities so tests (and future gateway-side overrides)
- keep a single patch point.
- """
- from hermes_cli.personality import normalize_personality_name
-
- name = normalize_personality_name(value)
- if not name:
- return "", ""
- personalities = _available_personalities(cfg)
- if name not in personalities:
- names = ", ".join(f"`{n}`" for n in sorted(personalities))
- raise ValueError(
- f"Unknown personality: `{str(value).strip()}`.\n\nAvailable: `none`, {names}"
- )
- return name, _render_personality_prompt(personalities[name])
-
-
-def _prompt_text(value) -> str:
- """Normalize config prompt values from YAML before handing them to AIAgent.
-
- Delegates to hermes_cli.personality (single owner).
- """
- from hermes_cli.personality import prompt_text
-
- return prompt_text(value)
-
-
-def _apply_personality_to_session(
- sid: str, session: dict, new_prompt: str, personality: str = ""
-) -> tuple[bool, dict | None]:
- """Apply a personality change to an existing session without resetting history.
-
- Updates the agent's ephemeral system prompt in-place so the new personality
- takes effect on the next turn. The cached base system prompt is left intact
- (ephemeral_system_prompt is appended at API-call time, not baked into the
- cache), which preserves prompt-cache hits.
-
- Also injects a system-role marker into the conversation history so the model
- knows to pivot its style from this point forward (without this, LLMs tend to
- continue the tone established by earlier messages in the transcript).
-
- Returns (history_reset, info) — history_reset is always False since we
- preserve the conversation.
- """
- if not session:
- return False, None
- session["personality"] = personality
-
- agent = session.get("agent")
- if agent:
- agent.ephemeral_system_prompt = new_prompt or None
- # Inject a pivot marker into history so the model sees the change point.
- # This prevents it from pattern-matching its prior style.
- if new_prompt:
- marker = (
- "[System: The user has changed the assistant's personality. "
- "From this point forward, adopt the following persona and respond "
- f"accordingly: {new_prompt}]"
- )
- else:
- marker = (
- "[System: The user has cleared the personality overlay. "
- "From this point forward, respond in your normal default style.]"
- )
- # Tagged like the model-switch marker (`_append_model_switch_marker`):
- # the marker rides as role=user so strict OpenAI-compatible providers
- # accept it mid-conversation, but `display_kind` keeps it out of the
- # `truncate_before_user_ordinal` addressing space. Untagged, it counts
- # as a real user turn on the gateway side while no client counts it, so
- # every later rewind resolves one turn too early and `replace_messages`
- # hard-deletes the difference (#82756).
- with session["history_lock"]:
- session["history"].append(
- {"role": "user", "content": marker, "display_kind": "personality_switch"}
- )
- session["history_version"] = int(session.get("history_version", 0)) + 1
- info = _session_info(agent)
- _emit("session.info", sid, info)
- return False, info
- return False, None
-
-
-def _cfg_max_turns(cfg: dict, default: int) -> int:
- from hermes_cli.config import resolve_turn_limit as _resolve_turn_limit
- # Env var override (highest priority)
- env_val = os.environ.get("HERMES_TUI_MAX_TURNS")
- if env_val:
- return _resolve_turn_limit(env_val, default=default)
- # Config file value — route through resolve_turn_limit so that
- # "none"/"unlimited"/0 are first-class spellings, not int() crashes.
- agent_cfg = cfg.get("agent") or {}
- raw = agent_cfg.get("max_turns")
- if raw is None:
- raw = cfg.get("max_turns")
- if raw is not None:
- return _resolve_turn_limit(raw, default=default)
- return default
-
-
-def _parse_tui_skills_env() -> list[str]:
- raw = os.environ.get("HERMES_TUI_SKILLS", "")
- skills: list[str] = []
- seen: set[str] = set()
- for part in raw.replace("\n", ",").split(","):
- item = part.strip()
- if item and item not in seen:
- seen.add(item)
- skills.append(item)
- return skills
-
-
-def _load_fallback_model():
- """Return the configured fallback chain for TUI-created agents.
-
- Delegates to the shared ``get_fallback_chain`` helper so the TUI path
- stays in parity with ``HermesCLI.__init__`` and ``gateway/run.py``:
- ``fallback_providers`` is the primary source of truth and keeps its
- order, with legacy ``fallback_model`` entries merged in afterwards
- (deduped on provider/model/base_url).
- """
- from hermes_cli.fallback_config import get_fallback_chain
-
- return get_fallback_chain(_load_cfg())
-
-
-def _agent_fallback_model(agent):
- """Return an agent's fallback chain without rehydrating deliberately empty chains."""
- if hasattr(agent, "_fallback_chain"):
- return getattr(agent, "_fallback_chain") or []
- if hasattr(agent, "_fallback_model"):
- return getattr(agent, "_fallback_model", None)
- return _load_fallback_model()
-
-
-def _background_agent_kwargs(agent, task_id: str) -> dict:
- cfg = _load_cfg()
-
- return {
- "base_url": getattr(agent, "base_url", None) or None,
- "api_key": getattr(agent, "api_key", None) or None,
- "provider": getattr(agent, "provider", None) or None,
- "api_mode": getattr(agent, "api_mode", None) or None,
- "acp_command": getattr(agent, "acp_command", None) or None,
- "acp_args": getattr(agent, "acp_args", None) or None,
- "model": getattr(agent, "model", None) or _resolve_model(),
- "max_iterations": _cfg_max_turns(cfg, 25),
- "enabled_toolsets": getattr(agent, "enabled_toolsets", None)
- # Detached background tasks declare platform="tui" below: they have no
- # UI session id, so a renderer-routed event has nowhere to land. Resolve
- # their toolsets against that same platform rather than the gateway
- # process's, so they never carry GUI schema they cannot use.
- or _load_enabled_toolsets("tui"),
- "quiet_mode": True,
- "verbose_logging": False,
- "ephemeral_system_prompt": getattr(agent, "ephemeral_system_prompt", None)
- or None,
- "providers_allowed": getattr(agent, "providers_allowed", None),
- "providers_ignored": getattr(agent, "providers_ignored", None),
- "providers_order": getattr(agent, "providers_order", None),
- "provider_sort": getattr(agent, "provider_sort", None),
- "provider_require_parameters": getattr(
- agent, "provider_require_parameters", False
- ),
- "provider_data_collection": getattr(agent, "provider_data_collection", None),
- "openrouter_min_coding_score": getattr(agent, "openrouter_min_coding_score", None),
- "session_id": task_id,
- "reasoning_config": getattr(agent, "reasoning_config", None)
- or _load_reasoning_config(str(getattr(agent, "model", "") or "")),
- "service_tier": getattr(agent, "service_tier", None) or _load_service_tier(),
- "request_overrides": dict(getattr(agent, "request_overrides", {}) or {}),
- "platform": "tui",
- "session_db": _get_db(),
- "fallback_model": _agent_fallback_model(agent),
- }
-
-
-def _ephemeral_preview_agent_kwargs(agent, task_id: str) -> dict:
- kwargs = _background_agent_kwargs(agent, task_id)
- kwargs.update(
- {
- "enabled_toolsets": ["terminal", "file"],
- "session_db": None,
- "skip_memory": True,
- }
- )
- return kwargs
-
-
-def _preview_restart_history(session: dict, max_messages: int = 24, max_tool_chars: int = 1200) -> list[dict]:
- """Distill the parent session's recent history into a context the
- ephemeral preview-restart agent can actually use.
-
- The restart agent has no idea what app the user was building, what
- server they ran, what cwd was active, or which port belongs to which
- project. Without this, it would take the bare URL + console logs and
- guess — usually starting the wrong thing.
-
- We keep the last ``max_messages`` messages from the parent session so
- the restart agent sees recent user prompts, assistant replies, and
- most importantly any terminal/tool calls. Tool result payloads are
- truncated so we don't blow the context window with file dumps.
- """
- try:
- with session["history_lock"]:
- history = list(session.get("history", []) or [])
- except Exception:
- history = list(session.get("history", []) or [])
-
- if not history:
- return []
-
- # Anchor on the last user turn so we always include at least the most
- # recent request and the assistant/tool work that followed it. Then
- # extend backwards up to max_messages so we capture the prior context.
- last_user_idx = None
- for idx in range(len(history) - 1, -1, -1):
- if history[idx].get("role") == "user":
- last_user_idx = idx
- break
-
- start = max(0, len(history) - max_messages)
- if last_user_idx is not None:
- start = min(start, last_user_idx)
-
- trimmed: list[dict] = []
- for msg in history[start:]:
- if not isinstance(msg, dict):
- continue
- role = msg.get("role")
- if role not in ("user", "assistant", "tool", "system"):
- continue
-
- copy = {k: v for k, v in msg.items() if k != "reasoning"}
- # Truncate heavy tool outputs so a single 50KB file read doesn't
- # crowd out the rest of the context.
- if role == "tool":
- content = copy.get("content")
- if isinstance(content, str) and len(content) > max_tool_chars:
- copy["content"] = (
- content[:max_tool_chars]
- + f"\n... (truncated, original {len(content)} chars)"
- )
- trimmed.append(copy)
-
- return trimmed
-
-
-def _preview_tool_result_preview(name: str, result: str) -> str:
- try:
- data = json.loads(result)
- except Exception:
- return ""
-
- if not isinstance(data, dict):
- return ""
-
- if name == "terminal":
- output = str(data.get("output") or "").strip()
- exit_code = data.get("exit_code")
- if output:
- return output[-1200:]
- if data.get("session_id"):
- return f"Background process started: {data.get('session_id')}"
- if exit_code is not None:
- return f"terminal exited with code {exit_code}"
-
- return str(data.get("error") or "").strip()[:1200]
-
-
-def _preview_restart_callbacks(parent: str, task_id: str) -> dict:
- started_at: dict[str, float] = {}
-
- def progress(message: str, level: str = "info") -> None:
- text = str(message or "").strip()
- if text:
- _emit("preview.restart.progress", parent, {"task_id": task_id, "level": level, "text": text})
-
- def tool_start(tool_call_id: str, name: str, args: dict) -> None:
- started_at[tool_call_id] = time.time()
- ctx = _tool_ctx(name, args)
- progress(f"Running {name}{f': {ctx}' if ctx else ''}")
-
- def tool_complete(tool_call_id: str, name: str, _args: dict, result: str) -> None:
- duration_s = time.time() - started_at.get(tool_call_id, time.time())
- summary = _tool_summary(name, result, duration_s) or f"Finished {name}{f' in {_fmt_tool_duration(duration_s)}' if duration_s else ''}"
- output = _preview_tool_result_preview(name, result)
- progress(summary + (f"\n{output}" if output else ""))
-
- def tool_progress(event_type: str, name: str | None = None, preview: str | None = None, **_kwargs) -> None:
- if preview:
- progress(str(preview))
- elif name:
- progress(f"{event_type.replace('.', ' ')}: {name}")
-
- return {
- "tool_start_callback": tool_start,
- "tool_complete_callback": tool_complete,
- "tool_progress_callback": tool_progress,
- "tool_gen_callback": lambda name: progress(f"Preparing {name}"),
- "status_callback": lambda kind, text=None: progress(text if text is not None else kind),
- }
-
-
-def _reset_session_agent(sid: str, session: dict) -> dict:
- tokens = _set_session_context(session["session_key"])
- try:
- # /new is a full conversation boundary: session-scoped runtime
- # overrides (/model, /reasoning, /fast) do NOT carry forward — the
- # fresh agent re-derives model/provider, reasoning, and service tier
- # from config.yaml (#48055, #23131). Session pins are cleared below so
- # a rebuild can't resurrect them. (Global process state is still never
- # touched — see the cross-session-contamination note in
- # _apply_model_switch.)
- session.pop("model_override", None)
- session.pop("create_reasoning_override", None)
- session.pop("create_service_tier_override", None)
- session.pop("one_turn_model_restore", None)
- new_agent = _make_agent(
- sid,
- session["session_key"],
- session_id=session["session_key"],
- platform_override=_session_source(session),
- context_cwd_is_launch_artifact=(
- _context_cwd_is_launch_artifact(session)
- ),
- )
- finally:
- _clear_session_context(tokens)
- session["agent"] = new_agent
- session["config_model_seen"] = _config_model_target()
- session["attached_images"] = []
- session["queued_prompt"] = None
- session.pop("queued_prompts", None)
- session["_queued_prompt_generation"] = int(session.get("_queued_prompt_generation", 0)) + 1
- session["edit_snapshots"] = {}
- session["image_counter"] = 0
- session["running"] = False
- session["show_reasoning"] = _load_show_reasoning()
- session["tool_progress_mode"] = _load_tool_progress_mode()
- session["tool_started_at"] = {}
- with session["history_lock"]:
- session["history"] = []
- session["history_version"] = int(session.get("history_version", 0)) + 1
- info = _session_info(new_agent, session)
- _emit("session.info", sid, info)
- _restart_slash_worker(sid, session)
- return info
-
-
def _schedule_mcp_late_refresh(sid: str, agent) -> None:
"""Refresh a session's tool snapshot when MCP discovery lands late.
@@ -9515,1354 +8847,6 @@ def _resolve_checkpoint_hash(mgr, cwd: str, ref: str) -> str:
raise ValueError(f"Invalid checkpoint number. Use 1-{len(checkpoints)}.")
-def _active_image_routing_identity(agent: Any) -> tuple[str, str]:
- """Return the live provider/model, falling back before agent startup."""
- from agent.auxiliary_client import _read_main_model, _read_main_provider
-
- return (
- getattr(agent, "provider", "") or _read_main_provider(),
- getattr(agent, "model", "") or _read_main_model(),
- )
-
-
-def _build_image_ref_message(user_text: str, image_paths: list[str]) -> str:
- """Reference attached images by path so the agent analyzes them in-loop.
-
- This used to pre-analyze every image with the auxiliary vision model
- *before* the turn was dispatched (``_enrich_with_attached_images``):
- serial blocking calls on the submit path — 60-90s per large photo —
- with failures silently swallowed and an interrupt during the window
- killing the turn with zero API calls (#83291). It also prepended the
- vision description to the first user message, poisoning session
- auto-titles (#82339). The CLI never gates turn dispatch on vision
- like this, which is why the same message was seconds there and
- minutes on desktop.
-
- Now the turn starts immediately. The agent examines each image itself
- with ``vision_analyze`` — its own retries, visible tool progress —
- exactly how the ``@folder:`` reference path already behaves, which
- responds in seconds for the same images.
- """
- parts: list[str] = []
- for path in image_paths:
- p = Path(path)
- if not p.exists():
- continue
- parts.append(
- f"[The user attached an image: {p.name}]\n"
- f"[Examine it with the vision_analyze tool using image_url: {p}]"
- )
-
- text = user_text or ""
- prefix = "\n\n".join(parts)
- if prefix:
- return f"{prefix}\n\n{text}" if text else prefix
- return text or "What do you see in this image?"
-
-
-def _build_persist_message_with_image_refs(user_text: str, image_paths: list[str]) -> str:
- """Build the clean, UI-recognizable version of the user's message for
- persisting to session history. Uses ``@image:<path>`` directives — the
- format the desktop client (directive-text.tsx / HERMES_DIRECTIVE_RE)
- actually parses and renders as an image — unlike
- ``_build_image_ref_message``, which embeds an
- ``image_url:`` hint meant only for the model and must never be
- persisted as-is (it silently breaks image rendering after a full
- restart, and reorders image/text on live session-switch reconciliation).
-
- The caption leads and the directives trail: session previews are the first
- 60 characters of the first user message (``list_sessions_rich``), so a
- leading directive would label the session with a truncated file path in the
- sidebar, switcher, and command palette. Clients lift the refs out of the
- body by line, so their position does not affect how the turn renders.
- """
- from agent.context_references import format_reference_value
-
- text = user_text or ""
- refs = "\n".join(f"@image:{format_reference_value(p)}" for p in image_paths if Path(p).exists())
- if not refs:
- return text
- return f"{text}\n{refs}" if text else refs
-
-
-def _build_persist_user_message(user_text: str, image_paths: list[str], run_message: Any) -> Any:
- """Shape the persisted user turn to match what was sent to the model.
-
- Native-vision turns send ``content`` as a parts list, and
- ``_flush_messages_to_session_db`` deliberately ignores a plain-string
- override for a list payload (a text override must not erase a turn's
- image/audio summary). So mirror the shape: replace only the text part with
- the ``@image:`` ref form and keep the image parts, so the model still has
- the pixels for the rest of the session. Any API-only text part (the
- barge-in note) is dropped along the way, which is the point of the override.
- """
- persist_text = _build_persist_message_with_image_refs(user_text, image_paths)
- if not isinstance(run_message, list):
- return persist_text
- image_parts = [p for p in run_message if not (isinstance(p, dict) and p.get("type") == "text")]
- return [{"type": "text", "text": persist_text}, *image_parts]
-
-
-def _content_display_text(content: Any) -> str:
- if content is None:
- return ""
- if isinstance(content, str):
- return content
- if isinstance(content, (int, float)):
- return str(content)
- if isinstance(content, list):
- parts = []
- for part in content:
- text = _content_display_text(part).strip()
- if text:
- parts.append(text)
- return "\n".join(parts)
- if isinstance(content, dict):
- kind = content.get("type")
- if kind in {"text", "input_text", "output_text"}:
- return str(content.get("text") or content.get("content") or "")
- if kind in {"image_url", "input_image", "image"}:
- return "[image]"
- if kind in {"input_audio", "audio"}:
- return "[audio]"
- if kind:
- return f"[{kind}]"
- if "text" in content:
- return str(content.get("text") or "")
- return "[structured content]"
- return str(content)
-
-
-def _coerce_message_text(content: Any) -> str:
- """Render ``message['content']`` as a plain string for transport.
-
- Provider-side, ``content`` may be a string (most common), a list of
- multimodal parts (e.g. ``[{"type": "text", "text": "..."},
- {"type": "image_url", "image_url": {...}}]``), or a single structured
- dict. Calling ``.strip()`` on a list raises ``'list' object has no
- attribute 'strip'`` and breaks session resume entirely.
-
- Image parts (``image_url``) are preserved by appending the underlying
- URL (data: or http:) into the text. The desktop renderer pulls these
- back out via ``extractEmbeddedImages`` so the user sees the image
- instead of the URL — and it stops the resume payload from disagreeing
- with the cached message (which would otherwise cause the inline image
- to flash, then disappear when the resume payload overwrites the cache).
-
- Other structured dict shapes (audio, unknown types) fall back to a
- bracketed placeholder so resume doesn't drop the message entirely.
- """
- if content is None:
- return ""
- if isinstance(content, str):
- return content
- if isinstance(content, (int, float)):
- return str(content)
- if isinstance(content, list):
- chunks: list[str] = []
- for part in content:
- if isinstance(part, str):
- chunks.append(part)
- continue
- if not isinstance(part, dict):
- continue
- text = part.get("text")
- if isinstance(text, str):
- chunks.append(text)
- continue
- kind = part.get("type")
- if kind in {"text", "input_text", "output_text"}:
- t = part.get("text") or part.get("content") or ""
- if t:
- chunks.append(str(t))
- continue
- if kind in {"image_url", "input_image", "image"}:
- image_url = part.get("image_url")
- url = ""
- if isinstance(image_url, dict):
- candidate = image_url.get("url")
- if isinstance(candidate, str):
- url = candidate
- elif isinstance(image_url, str):
- url = image_url
- if url:
- chunks.append(f"\n{url}")
- else:
- chunks.append("\n[image]")
- continue
- if kind in {"input_audio", "audio"}:
- chunks.append("\n[audio]")
- continue
- if kind:
- chunks.append(f"\n[{kind}]")
- return "".join(chunks)
- if isinstance(content, dict):
- kind = content.get("type")
- if kind in {"text", "input_text", "output_text"}:
- return str(content.get("text") or content.get("content") or "")
- if kind in {"image_url", "input_image", "image"}:
- image_url = content.get("image_url")
- url = ""
- if isinstance(image_url, dict):
- candidate = image_url.get("url")
- if isinstance(candidate, str):
- url = candidate
- elif isinstance(image_url, str):
- url = image_url
- return url or "[image]"
- if kind in {"input_audio", "audio"}:
- return "[audio]"
- if kind:
- return f"[{kind}]"
- if "text" in content:
- return str(content.get("text") or "")
- return "[structured content]"
- return str(content)
-
-
-_TEXT_ONLY_BUSY_PART_KINDS = frozenset({"text", "input_text", "output_text"})
-
-
-def _is_text_only_busy_payload(content: Any) -> bool:
- """True when a busy submit carries only plain text, not attachments/media."""
- if content is None:
- return False
- if isinstance(content, (str, int, float)):
- return True
- if isinstance(content, list):
- if not content:
- return False
- for part in content:
- if isinstance(part, str):
- continue
- if not isinstance(part, dict):
- return False
- kind = part.get("type")
- if kind in _TEXT_ONLY_BUSY_PART_KINDS:
- continue
- if kind is None and isinstance(part.get("text"), str):
- continue
- return False
- return True
- if isinstance(content, dict):
- kind = content.get("type")
- if kind in _TEXT_ONLY_BUSY_PART_KINDS:
- return True
- return kind is None and isinstance(content.get("text"), str)
- return False
-
-
-def _is_display_hidden_marker(role: str | None, text: str) -> bool:
- """Gateway bookkeeping notices (model-switch, personality) are persisted as
- role=user ``[System: …]`` rows so strict providers accept them mid-history.
- They are model-facing runtime metadata, not user turns, and must never
- render as a user bubble in ANY client transcript (desktop, TUI, CLI, web).
-
- Filtering here — the single display projection every surface reads — hides
- them everywhere while the raw marker stays in ``session["history"]`` for the
- model. It also removes the stored marker from the payload the desktop
- reconciles against, so it can no longer shift user-message ordinals and
- duplicate the optimistic prompt (#67603)."""
- return role == "user" and text.lstrip().startswith("[System:")
-
-
-def _skill_scaffold_projection(content_text: str) -> str:
- """Return the invocation a slash-skill-expanded turn came from, else "".
-
- A ``/skill`` invocation expands into a model-facing message that embeds the
- whole skill body. That payload belongs to the agent — every UI renders the
- invocation (``/work fix the leak``) instead, so no surface can leak the
- body into a chat bubble.
- """
- return describe_skill_invocation(content_text, separator=" ") or ""
-
-
-def _expand_skill_invocation_for_replay(text: str, task_id: str) -> str:
- """Re-expand a projected `/skill` invocation before re-running that turn.
-
- The inverse of :func:`_skill_scaffold_projection`. Because a skill turn is
- displayed as its invocation, a rewind/regenerate hands us back
- ``/work fix the leak`` rather than the body the agent originally saw —
- re-running that verbatim would drop the skill. Re-expanding here keeps the
- body server-side (no client ever holds it) and makes the replayed turn
- identical to the original.
-
- Returns *text* unchanged when it isn't a resolvable skill invocation.
- """
- head, _, arg = (text or "").strip().partition(" ")
- if not head.startswith("/"):
- return text
-
- try:
- from agent.skill_commands import (
- build_skill_invocation_message,
- resolve_skill_command_key,
- )
-
- cmd_key = resolve_skill_command_key(head.lstrip("/"))
- if cmd_key is None:
- return text
-
- return build_skill_invocation_message(cmd_key, arg.strip(), task_id=task_id) or text
- except Exception:
- # A skill that no longer resolves (renamed, disabled, external dir
- # gone) must not break the rewind — replay the text as typed.
- logger.debug("skill re-expansion failed for replay", exc_info=True)
- return text
-
-
-# Opening of the crash-recovery note synthesized by _auto_continue_note.
-# Matched (not just built) so a row persisted before the display type was
-# stamped at turn start still reads as a timeline event, and to recognize the
-# messaging gateway's twin note.
-_AUTO_CONTINUE_NOTE_PREFIX = "[System note: Your previous turn was interrupted mid-run"
-
-
-def _legacy_display_kind(role: str, text: str) -> str | None:
- """Infer the display type of a synthetic row persisted without one.
-
- Turn-start typing (see ``persist_user_display_kind``) covers everything
- written from here on. Sessions already on disk carry untyped rows — and a
- turn killed mid-run never reached the post-turn stamp at all, which is
- exactly the auto-continue case — so the raw recovery note would paint as a
- user bubble forever. Sniffing the one fixed synthetic prefix is the
- migration for those rows; it is not how new rows get typed.
- """
- if role == "user" and text.lstrip().startswith(_AUTO_CONTINUE_NOTE_PREFIX):
- return "auto_continue"
- return None
-
-
-def _history_to_messages(history: list[dict]) -> list[dict]:
- messages = []
- tool_call_args = {}
-
- for m in history:
- if not isinstance(m, dict):
- continue
- m = project_compaction_message_for_display(m)
- if m is None:
- continue
- role = m.get("role")
- if role not in {"user", "assistant", "tool", "system"}:
- continue
- # An explicit display_kind="hidden" row is model-facing scaffolding
- # (compaction references, interrupted-turn checkpoints). The string
- # sniff below only catches the "[System:" convention; honor the
- # declared field too, or scaffolding reaches every surface that reads
- # this projection.
- if m.get("display_kind") == "hidden":
- continue
- content_text = _coerce_message_text(m.get("content"))
- if _is_display_hidden_marker(role, content_text):
- continue
- if role == "assistant" and m.get("tool_calls"):
- for tc in m["tool_calls"]:
- fn = tc.get("function", {})
- tc_id = tc.get("id", "")
- if tc_id and fn.get("name"):
- try:
- args = json.loads(fn.get("arguments", "{}"))
- except (json.JSONDecodeError, TypeError):
- args = {}
- tool_call_args[tc_id] = (fn["name"], args)
- if not content_text.strip():
- continue
- if role == "tool":
- tc_id = m.get("tool_call_id", "")
- tc_info = tool_call_args.get(tc_id) if tc_id else None
- name = (tc_info[0] if tc_info else None) or m.get("tool_name") or "tool"
- args = (tc_info[1] if tc_info else None) or {}
- tool_msg = {"role": "tool", "name": name, "context": _tool_ctx(name, args)}
- # This is the display projection, so keep it faithful. `context`
- # is an 80-char preview for collapsed row titles. A renderer that
- # shows the full call (the expanded `$` transcript in the desktop)
- # rebuilds it from args. When only the preview shipped, that
- # truncation was permanent.
- if args:
- tool_msg["args"] = args
- messages.append(tool_msg)
- continue
- # An assistant turn may carry only reasoning/thinking content with no
- # visible text (extended-thinking turns, thinking-only recovery
- # responses). Such a turn is persisted with its reasoning fields and is
- # recallable from the transcript, but dropping it here as "empty" makes
- # it vanish from the resumed/reloaded session view while the desktop's
- # reasoning disclosure has nothing to render. Keep it when it carries
- # reasoning so the "Thinking…" block still shows. (#44022)
- reasoning_keys = (
- "reasoning",
- "reasoning_content",
- "reasoning_details",
- "codex_reasoning_items",
- )
- has_reasoning = role == "assistant" and any(
- m.get(key) for key in reasoning_keys
- )
- if not content_text.strip() and not has_reasoning:
- continue
- msg = {"role": role, "text": content_text}
- # Persisted authoring time (Unix seconds) for display.timestamps
- # renderers (#41531). Display-only: never fed back into model context.
- ts = m.get("timestamp")
- if isinstance(ts, (int, float)) and ts > 0:
- msg["timestamp"] = float(ts)
- # Durable row identity, stamped by _rows_to_conversation. The renderer's
- # own message ids are ephemeral (timestamp+index derived, and a
- # different shape for live vs rehydrated vs optimistic rows), so
- # anything that addresses a specific persisted message later — message
- # reactions — needs this instead.
- if m.get("_row_id") is not None:
- msg["row_id"] = m["_row_id"]
- if role == "user":
- invocation = _skill_scaffold_projection(content_text)
- if invocation:
- # Show the invocation, never the expanded skill body. The raw
- # payload stays server-side: a rewind/regenerate re-sends the
- # turn by ordinal, so no client needs it.
- msg["text"] = invocation
- msg["display_kind"] = "skill_invocation"
- if role == "assistant":
- for key in reasoning_keys:
- if key in m and m.get(key) is not None:
- msg[key] = m.get(key)
- # Forward display-only timeline metadata so the TUI can render
- # model switches and delegation completions as events instead of
- # opaque user messages, and hide compaction handoffs entirely.
- display_kind = m.get("display_kind") or _legacy_display_kind(role, content_text)
- if display_kind:
- msg["display_kind"] = display_kind
- if m.get("display_metadata"):
- msg["display_metadata"] = m["display_metadata"]
- messages.append(msg)
-
- return messages
-
-
-def _coerce_seed_history(value: Any) -> list[dict]:
- if not isinstance(value, list):
- return []
-
- history = []
- for item in value:
- if not isinstance(item, dict):
- continue
-
- role = item.get("role")
- if role not in ("user", "assistant", "system"):
- continue
-
- content = item.get("content")
- if content is None:
- content = item.get("text")
- if not isinstance(content, str) or not content.strip():
- continue
-
- history.append({"role": role, "content": content})
-
- return history
-
-
-def _inflight_text(value: Any) -> str:
- return _content_display_text(value).strip()
-
-
-def _start_inflight_turn(session: dict, text: Any) -> None:
- now = time.time()
- session["inflight_turn"] = {
- "assistant": "",
- "started_at": now,
- "streaming": True,
- "updated_at": now,
- "user": _inflight_text(text),
- }
-
-
-def _append_inflight_delta(session: dict, delta: Any) -> None:
- text = "" if delta is None else str(delta)
- if not text:
- return
- turn = session.get("inflight_turn")
- if not isinstance(turn, dict):
- turn = {"assistant": "", "streaming": True, "user": ""}
- turn["assistant"] = f"{turn.get('assistant') or ''}{text}"
- turn["streaming"] = True
- turn["updated_at"] = time.time()
- session["inflight_turn"] = turn
-
-
-def _record_inflight_correction(session: dict, text: Any) -> None:
- """Record an accepted mid-turn correction on the live turn.
-
- The correction is appended, never written over ``user``: a resuming client
- must be able to rebuild BOTH bubbles. Overwriting the slot erased the
- prompt that started the turn from the only snapshot resume can read, so a
- reconnect (or a dev hot-reload that wipes the renderer cache) repainted the
- thread with the user's original message missing.
- """
- correction = _inflight_text(text)
- if not correction:
- return
- turn = session.get("inflight_turn")
- if not isinstance(turn, dict):
- return
- turn = dict(turn)
- corrections = list(turn.get("corrections") or [])
- corrections.append(correction)
- turn["corrections"] = corrections
- # Arrival-order boundary: how much assistant text had already streamed
- # when this correction was accepted. Resuming clients use it to place the
- # correction bubble AFTER the output the user had already seen and BEFORE
- # the output it redirected (#73793) instead of above the whole reply.
- offsets = list(turn.get("correction_offsets") or [])
- offsets.append(len(str(turn.get("assistant") or "")))
- turn["correction_offsets"] = offsets
- turn["updated_at"] = time.time()
- session["inflight_turn"] = turn
-
-
-def _clear_inflight_turn(session: dict) -> None:
- session["inflight_turn"] = None
-
-
-def _fail_inflight_turn(
- session: dict, error: Any, error_surface: Optional[dict] = None
-) -> None:
- """Mark the in-flight turn terminal-error but keep it replayable.
-
- Normal completion clears ``inflight_turn`` because the response is now in
- canonical history. Failures are different: the terminal frame can be lost
- on a WS disconnect, and the failed turn may never have been committed.
- Retaining a compact error snapshot lets ``session.resume`` replay the
- user's prompt, any partial assistant text, and the error itself instead of
- leaving the client stranded on a spinner or hydrating from stale DB state.
- The snapshot lives until the next turn starts (``_start_inflight_turn``
- overwrites it) or the session closes.
-
- Caller must hold ``session["history_lock"]``.
- """
- message = str(error) if not isinstance(error, BaseException) else (str(error) or type(error).__name__)
- now = time.time()
- turn = session.get("inflight_turn")
- if not isinstance(turn, dict):
- turn = {"assistant": "", "user": "", "started_at": now}
- turn["assistant"] = str(turn.get("assistant") or "")
- turn["user"] = str(turn.get("user") or "")
- turn["error"] = message or "turn failed"
- turn["status"] = "error"
- turn["recoverable"] = True
- if error_surface:
- # Structured {layer, code, retryable} descriptor — replayed to
- # resuming clients via the resume snapshot so a reconnect renders the
- # same layered error card the live frame carried.
- turn["error_surface"] = dict(error_surface)
- else:
- turn.pop("error_surface", None)
- turn["streaming"] = False
- turn["updated_at"] = now
- session["inflight_turn"] = turn
-
-
-_TURN_FAILURE_DETAIL_LIMIT = 240
-# Shortest run of the submitted prompt that counts as the provider quoting it
-# back. Long enough that shared boilerplate ("Invalid request for model ") does
-# not trip it, short enough to catch a quoted sentence.
-_TURN_PROMPT_ECHO_WINDOW = 24
-# Ceiling on the prompt we shingle. An @-expanded prompt can carry a whole
-# file; the failure path must stay cheap.
-_TURN_PROMPT_ECHO_MAX_PROMPT = 65536
-
-
-def _strip_prompt_echo(message: str, prompt: Any) -> str:
- """Blank runs of the submitted prompt that ``message`` quotes back.
-
- Secret redaction and prompt omission are different contracts, and only the
- first one is pattern-based. A provider 4xx that echoes the request carries
- ordinary private prose -- a paragraph about a person, a pasted file from an
- ``@`` reference -- that matches no credential pattern and would otherwise
- reach the log intact. This closes that path directly: anything the message
- shares with the prompt for ``_TURN_PROMPT_ECHO_WINDOW`` characters or more
- becomes ``<prompt>``.
-
- Shingle-set matching, not a diff: cost is linear in both strings, which
- matters because this runs on every failed turn and an ``@`` reference can
- make the prompt arbitrarily long. The JSON-escaped form of the prompt is
- shingled too, since a provider that hands back its own request body often
- hands it back escaped.
-
- Verbatim echo is what this stops. A paraphrase, a re-encoding (base64, a
- different unicode normalization) or a summary of the prompt would survive,
- so this is a floor and not a proof; the guarantee it does give is that the
- prompt cannot reach the record by being quoted.
- """
- if not message or not prompt:
- return message
- needle = " ".join(str(prompt).split())[:_TURN_PROMPT_ECHO_MAX_PROMPT]
- window = _TURN_PROMPT_ECHO_WINDOW
- if len(needle) < window or len(message) < window:
- return message
- shingles = {needle[i:i + window] for i in range(len(needle) - window + 1)}
- try:
- escaped = json.dumps(needle)[1:-1]
- except Exception:
- escaped = ""
- if escaped and escaped != needle:
- shingles.update(
- escaped[i:i + window] for i in range(len(escaped) - window + 1)
- )
- out: list[str] = []
- i = 0
- n = len(message)
- while i <= n - window:
- if message[i:i + window] in shingles:
- j = i + window
- while j < n and message[j - window + 1:j + 1] in shingles:
- j += 1
- out.append("<prompt>")
- i = j
- else:
- out.append(message[i])
- i += 1
- out.append(message[i:])
- return "".join(out)
-
-
-def _turn_failure_detail(error: Any, reason: Any = None, prompt: Any = None) -> str:
- """Render why a turn failed, for the ``tui turn finished`` bookend.
-
- Returns ``""`` when there is nothing to say, otherwise a fragment that
- already carries its own leading space, so the caller can append it to the
- record unconditionally.
-
- #86865 added the bookend to trace compression rotations, so it logs
- identities and a coarse ``status`` and deliberately logs no content.
- #89117 is what the missing cause costs: a report consisting of two lines
- reading ``status=error error_retained=True duration=0.9s`` with no way to
- tell a provider 4xx from a budget wall from a crashed finalizer. The
- returned-error path -- the one a 0.9 s failure almost always takes --
- emits no other log line at all; only the exception path prints to stderr,
- which is why the quiet failures are the ones that get filed.
-
- Content discipline follows #86865's, and it takes two separate steps
- because it is two separate contracts. ``redact_sensitive_text`` removes
- credentials, which are pattern-shaped. It does nothing about a 4xx body
- that quotes the request back, because ordinary private prose is not
- pattern-shaped -- so ``_strip_prompt_echo`` removes that separately, using
- the submitted ``prompt`` itself as the thing to look for. The invariant the
- two of them keep is: this record may gain failure classification and
- provider detail, and may not newly persist the user's own content.
-
- ``prompt`` is optional so the helper stays callable from a path that has no
- prompt in scope, but the turn paths always pass it; without it, only the
- secret contract is enforced.
- """
- reason_text = str(reason or "").strip()
- message = str(error or "").strip()
- if isinstance(error, BaseException):
- message = message or type(error).__name__
- if not message and not reason_text:
- return ""
- try:
- from agent.redact import redact_sensitive_text
-
- message = redact_sensitive_text(message, force=True)
- except Exception:
- # A redactor that cannot run must not be able to leak the raw
- # message into the log by failing open.
- message = "<unredactable>"
- message = " ".join(message.split())
- # After the collapse, so both sides are compared in the same shape, and
- # before the truncation, so a quote that starts inside the kept prefix
- # cannot survive by being cut mid-run.
- message = _strip_prompt_echo(message, prompt)
- if len(message) > _TURN_FAILURE_DETAIL_LIMIT:
- message = message[:_TURN_FAILURE_DETAIL_LIMIT] + "\u2026"
- out = ""
- if reason_text:
- out += " failure_reason=%s" % " ".join(reason_text.split())
- if message:
- out += " cause=%r" % message
- return out
-
-
-# ── Auto-continue: resume a turn killed by a process/machine death ────
-#
-# A turn that concludes — success, handled error, interrupt — clears its
-# durable marker (see tui_gateway/turn_marker.py) in _run_prompt_submit's
-# finally. Only a process death leaves the marker behind, so a marker found
-# at session.resume time is positive proof the turn never finished AND the
-# client never saw a terminal frame. If the interruption is fresh, re-submit
-# the interrupted prompt automatically (the messaging gateway has done this
-# for restart-interrupted sessions since #27856); if it's stale, clear the
-# marker and let the recovered partial transcript speak for itself — the
-# user can ask to continue manually.
-
-_AUTO_CONTINUE_ENABLED_DEFAULT = True
-_AUTO_CONTINUE_FRESHNESS_MINUTES_DEFAULT = 15
-_AUTO_CONTINUE_MAX_ATTEMPTS_DEFAULT = 2
-
-
-def _auto_continue_config() -> tuple[bool, float, int]:
- """(enabled, freshness window in seconds, max attempts) from config.yaml."""
- desktop = _load_cfg().get("desktop")
- cfg = desktop.get("auto_continue") if isinstance(desktop, dict) else None
- if not isinstance(cfg, dict):
- cfg = {}
- try:
- minutes = float(cfg.get("freshness_minutes", _AUTO_CONTINUE_FRESHNESS_MINUTES_DEFAULT))
- except (TypeError, ValueError):
- minutes = float(_AUTO_CONTINUE_FRESHNESS_MINUTES_DEFAULT)
- return (
- is_truthy_value(cfg.get("enabled"), default=_AUTO_CONTINUE_ENABLED_DEFAULT),
- max(0.0, minutes) * 60.0,
- _coerce_int_config_value(
- cfg.get("max_attempts"), _AUTO_CONTINUE_MAX_ATTEMPTS_DEFAULT, min_value=0
- ),
- )
-
-
-def _session_home(session: dict) -> Path:
- """The HERMES_HOME the session's durable state lives in (profile-aware)."""
- profile_home = session.get("profile_home")
- return Path(profile_home) if profile_home else Path(_hermes_home)
-
-
-def _retire_turn_marker(session: dict, *keys: str) -> None:
- """Drop the crash marker for a turn whose outcome is about to reach the client.
-
- Called immediately before the terminal frame rather than at the end of the
- turn thread: post-turn work (titles, memory sync, goal hooks) runs for a
- second or more after the client has its answer, and quitting inside that
- window would leave a marker that looks like a crash — re-running a finished
- turn on the next launch. Extra ``keys`` cover a session_key that
- compression rotated mid-turn.
- """
- home = _session_home(session)
- for key in dict.fromkeys((*keys, str(session.get("session_key") or ""))):
- if key:
- clear_turn_marker(home, key)
-
-
-def _auto_continue_note(prompt: str) -> str:
- # Same opening as the messaging gateway's recovery notes so transcript
- # tooling recognizes both. The original prompt is embedded because a hard
- # crash persists nothing of the interrupted turn to the session DB — this
- # note is the only copy the model will see.
- return (
- f"{_AUTO_CONTINUE_NOTE_PREFIX} — the app or its backend process "
- "stopped before the turn could finish. Some of the work may already "
- "be complete; check the current state before redoing anything, then "
- "finish the task. The interrupted request was:]\n\n"
- f"{prompt}"
- )
-
-
-def _maybe_schedule_auto_continue(sid: str, session: dict, session_key: str) -> dict | None:
- """Kick off a continuation turn for a crash-interrupted session.
-
- Called from session.resume's cold paths after the live record is
- registered. Returns a small descriptor for the resume payload when a
- continuation was scheduled, else None. The turn itself runs on a
- background thread after the (deferred) agent build finishes, through the
- same _run_prompt_submit machinery as every other synthesized turn — so
- the client that just resumed streams it live.
- """
- # Hosted room turns are recovered by their durable task/lease state
- # machine. Generic session auto-continue would bypass its execution
- # generation and can duplicate work after a process restart.
- if session.get("source") == "bot_room":
- return None
-
- home = _session_home(session)
- marker = read_turn_marker(home, session_key)
- if marker is None:
- return None
- enabled, freshness_secs, max_attempts = _auto_continue_config()
- age = time.time() - marker["started_at"]
- if not enabled or age > freshness_secs or marker["attempts"] >= max_attempts:
- # Stale, disabled, or crash-looping: stop trying. The journal/partial
- # transcript still shows what happened; a manual message continues it.
- clear_turn_marker(home, session_key)
- return None
- if session.get("_auto_continue_scheduled"):
- return None
- session["_auto_continue_scheduled"] = True
- attempt = marker["attempts"] + 1
- text = _auto_continue_note(marker["prompt"])
-
- def kickoff() -> None:
- rid = f"__auto_continue__{int(time.time() * 1000)}"
- try:
- _start_agent_build(sid, session)
- err = _wait_agent(session, rid, timeout=120.0)
- except Exception:
- logger.warning("auto-continue agent build failed for %s", sid, exc_info=True)
- err = {"error": {"message": "agent build failed"}}
- if err:
- # Leave the marker: the next resume retries (bounded by attempts).
- session["_auto_continue_scheduled"] = False
- return
- with session["history_lock"]:
- if session.get("running") or session.get("_turn_cancel_requested") or session.get("_finalized"):
- # A real user prompt beat us to it — their turn wins, and its
- # own conclusion clears the marker.
- session["_auto_continue_scheduled"] = False
- return
- session["running"] = True
- session["last_active"] = time.time()
- # Ownership admission BEFORE message.start: the interrupted-turn
- # marker this continuation is recovering may have been written by a
- # sibling backend that is still alive and mid-turn (#94778 — two
- # backends share one HERMES_HOME; B resumes S while A runs it and
- # sees A's fresh marker). Running the continuation anyway would be
- # the double-writer this fence exists to prevent. Leave the marker:
- # once the owner finishes or dies, a later resume retries.
- if _ensure_active_session_slot(sid, session) is not None:
- logger.info(
- "auto-continue for %s refused: session has another live owner",
- session_key,
- )
- with session["history_lock"]:
- session["running"] = False
- session["_auto_continue_scheduled"] = False
- return
- with session["history_lock"]:
- # Hand this turn its own marker inputs (read back by
- # _run_prompt_submit): count the attempt so a crash during the
- # continuation trips the breaker, and re-record the ORIGINAL
- # prompt so a second crash doesn't nest note inside note. Set
- # here, not at schedule time, so a bail above leaves nothing
- # behind for a racing user turn to inherit.
- session["_auto_continue_attempt"] = attempt
- session["_auto_continue_prompt"] = marker["prompt"]
- try:
- _emit(
- "status.update",
- sid,
- {"kind": "process", "text": "Resuming interrupted turn…"},
- )
- _emit("message.start", sid)
- _run_prompt_submit(rid, sid, session, text, display_kind="auto_continue")
- except Exception as exc:
- print(
- f"[tui_gateway] auto-continue dispatch failed: "
- f"{type(exc).__name__}: {exc}",
- file=sys.stderr,
- )
- with session["history_lock"]:
- session["running"] = False
-
- threading.Thread(target=kickoff, daemon=True).start()
- logger.info(
- "auto-continue scheduled for session %s (attempt %d, interrupted %.0fs ago)",
- session_key,
- attempt,
- age,
- )
- return {"attempt": attempt, "interrupted_at": marker["started_at"]}
-
-
-def _enqueue_prompt(
- session: dict,
- text: Any,
- transport: Any,
- image_paths: list[str] | None = None,
-) -> None:
- """Stash a message to run as the very next turn once the live one ends.
-
- Used when a prompt arrives mid-turn (see ``_handle_busy_submit``). Text-only
- arrivals share a slot and merge losslessly (mirroring the consecutive-user
- merge in ``repair_message_sequence``). Image-bearing submissions stay as
- separate envelopes, so their attachment ownership and chronology survive.
- ``transport`` is pinned so the drained turn streams back to the client that
- sent it even if the session transport is rebound meanwhile.
- """
- image_paths = list(image_paths or [])
- # #84417: scrub any live-turn self-duplicates first so the consecutive-text
- # merge below cannot glue "{original}\\n\\n{later}" and re-fire original
- # on drain after a later correction settles.
- _drop_queued_duplicates_of_inflight_user(session)
- # Never queue a text-only self-copy of the live inflight user prompt. The
- # live turn already owns that text; draining it after settle would restart
- # the same user turn as a fresh agent invocation.
- if not image_paths and isinstance(text, str):
- turn = session.get("inflight_turn")
- original = (
- str(turn.get("user") or "").strip() if isinstance(turn, dict) else ""
- )
- if original and text.strip() == original:
- return
- queued = {"text": text, "transport": transport}
- if image_paths:
- queued["image_paths"] = image_paths
- existing = session.get("queued_prompt")
- if (
- existing
- and isinstance(existing.get("text"), str)
- and isinstance(text, str)
- and not existing.get("image_paths")
- and not image_paths
- and not session.get("queued_prompts")
- ):
- prev = existing["text"]
- existing["text"] = f"{prev}\n\n{text}" if prev and text else (prev or text)
- return
- if existing:
- session.setdefault("queued_prompts", []).append(queued)
- return
- session["queued_prompt"] = queued
-
-
-def _sanitize_queued_entry_vs_inflight_user(
- entry: Any, original: str
-) -> dict | None:
- """Drop or rewrite a queue envelope that re-carries the live user text.
-
- Returns ``None`` to drop the envelope, or a (possibly rewritten) dict to
- keep. Text-only self-duplicates of ``original`` are dropped. A merged
- slot ``"{original}\\n\\n{later}"`` (from ``_enqueue_prompt``'s consecutive
- text merge) is rewritten to just ``later`` so a later correction is not
- lost and the original is not re-fired (#84417). Image-bearing envelopes
- are left alone — their chronology/ownership is load-bearing.
- """
- if not original or not isinstance(entry, dict):
- return entry if isinstance(entry, dict) else None
- if entry.get("image_paths"):
- return entry
- text = entry.get("text")
- if not isinstance(text, str):
- return entry
- stripped = text.strip()
- if not stripped:
- return None
- if stripped == original:
- return None
- # Lossless text-merge glued the live original onto a later follow-up.
- for sep in ("\n\n", "\n"):
- prefix = original + sep
- if text.startswith(prefix):
- rest = text[len(prefix) :].strip()
- if not rest or rest == original:
- return None
- cleaned = dict(entry)
- cleaned["text"] = rest
- return cleaned
- return entry
-
-
-def _drop_queued_duplicates_of_inflight_user(session: dict) -> None:
- """Remove server-queue copies of the live turn's original user text.
-
- A mid-turn ``prompt.submit`` of the same text can land in
- ``queued_prompt`` when redirect is not yet available (model not active,
- build window, tool boundary). If the user then corrects the turn with a
- different prompt via redirect, that stale self-duplicate must not
- ``_drain_queued_prompt`` after the redirected turn completes — otherwise
- the original prompt restarts as a fresh agent turn (#84417).
-
- Unrelated follow-ups (different text, image-bearing envelopes) stay.
- Merged ``original + later`` slots are rewritten to ``later`` only.
- """
- turn = session.get("inflight_turn")
- if not isinstance(turn, dict):
- return
- original = str(turn.get("user") or "").strip()
- if not original:
- return
-
- head = session.get("queued_prompt")
- rest = list(session.get("queued_prompts") or [])
- kept: list[dict] = []
- for entry in ([head] if head else []) + rest:
- cleaned = _sanitize_queued_entry_vs_inflight_user(entry, original)
- if cleaned is not None:
- kept.append(cleaned)
-
- if not kept:
- session["queued_prompt"] = None
- session.pop("queued_prompts", None)
- return
- session["queued_prompt"] = kept[0]
- if len(kept) > 1:
- session["queued_prompts"] = kept[1:]
- else:
- session.pop("queued_prompts", None)
-
-
-def _interrupt_busy_session(sid: str, session: dict, agent: Any) -> None:
- """Interrupt a busy turn without blocking the RPC reader or session lock.
-
- Some providers cannot apply ``interrupt()`` until a synchronous tool or
- network call returns. Running that call inline used to leave
- ``prompt.submit`` holding ``history_lock`` for the whole wait, which in turn
- blocked ``session.resume`` and delayed the queued prompt itself. Keep at
- most one interrupt worker per session so repeated steering cannot leak an
- unbounded number of blocked threads.
- """
- use_agent = agent is not None and hasattr(agent, "interrupt")
- use_compute_host = not use_agent and _session_uses_compute_host(session)
- if not use_agent and not use_compute_host:
- return
-
- with session["history_lock"]:
- if session.get("_busy_interrupt_pending"):
- return
- session["_busy_interrupt_pending"] = True
-
- def interrupt() -> None:
- try:
- if use_agent:
- agent.interrupt()
- else:
- _get_compute_host_supervisor().interrupt(sid)
- except Exception:
- pass
- finally:
- with session["history_lock"]:
- session["_busy_interrupt_pending"] = False
-
- threading.Thread(target=interrupt, daemon=True, name=f"busy-interrupt-{sid}").start()
-
-
-def _handle_busy_submit(
- rid, sid: str, session: dict, text: Any, transport: Any, queued: bool = False
-) -> dict | None:
- """Apply the ``display.busy_input_mode`` policy to a prompt that lands while
- a turn is in flight, instead of rejecting it with ``session busy``.
-
- The old rejection forced clients into a deadline-bounded busy-retry that
- silently dropped the send when turn teardown outlived the deadline. The
- default policy now redirects a capable core agent in place; older agents
- retain the proven interrupt-and-queue path drained from ``run``'s tail.
-
- Modes: ``interrupt`` (default) → redirect the live turn, falling back to
- hard interrupt + queue for older agents; ``queue`` → queue without
- interrupting; ``steer`` → inject after the current atomic action.
-
- ``queued=True`` (client's queue drain, ``prompt.submit`` param) overrides
- the mode entirely: the message was explicitly queued as "run after", so it
- must NEVER become a live-turn correction or interrupt. Without this, a
- drain that loses the settle race (client observed idle, server still
- unwinding the turn) redirected the live turn with next-turn text — queue
- semantics betrayed by a millisecond race the user can't see.
- """
- mode = "queue" if queued else _load_busy_input_mode()
- agent = session.get("agent")
- with session["history_lock"]:
- if not session.get("running"):
- # The turn ended between prompt.submit's first busy check and this
- # helper. Let the caller retry and claim the now-idle session.
- return None
- with session["history_lock"]:
- if not session.get("running"):
- return None
- image_paths = list(session.get("attached_images", []))
- if image_paths:
- # Claim at submission time. A later paste must not be consumed by
- # this prompt after the active turn finally yields.
- session["attached_images"] = []
- text_only = not image_paths and _is_text_only_busy_payload(text)
- plain_text = _coerce_message_text(text).strip() if text_only else ""
- if mode == "steer" and text_only and plain_text and agent is not None and hasattr(agent, "steer"):
- try:
- if agent.steer(plain_text):
- with session["history_lock"]:
- _record_inflight_correction(session, plain_text)
- _drop_queued_duplicates_of_inflight_user(session)
- session["last_active"] = time.time()
- return _ok(rid, {"status": "steered"})
- except Exception:
- pass # fall through to queue
- # Text-only corrections redirect the live turn in place when the runtime
- # supports it; media/attachment payloads and older agents fall through to
- # the proven interrupt + queue path below.
- if (
- mode == "interrupt"
- and text_only
- and plain_text
- and agent is not None
- and getattr(agent, "_supports_active_turn_redirect", False) is True
- and hasattr(agent, "redirect")
- ):
- try:
- if agent.redirect(plain_text):
- with session["history_lock"]:
- _record_inflight_correction(session, plain_text)
- # #84417: do not re-fire the live turn's original user text
- # from a stale server-queue self-duplicate after settle.
- _drop_queued_duplicates_of_inflight_user(session)
- session["last_active"] = time.time()
- return _ok(rid, {"status": "redirected"})
- except Exception:
- pass # preserve the proven interrupt + queue fallback below
- # Queue before asking the live turn to stop. In particular, never call a
- # provider or compute-host method while holding history_lock: an interrupt
- # can wait behind the very operation it is trying to cancel.
- with session["history_lock"]:
- if not session.get("running"):
- if image_paths:
- session["attached_images"] = image_paths + list(session.get("attached_images", []))
- return None
- _enqueue_prompt(session, text, transport, image_paths=image_paths)
- session["last_active"] = time.time()
-
- # Attachments need a separate model invocation. Queue them without
- # cancelling the active turn so the user gets both results in order.
- #
- # #86134: ``steer`` mode must NEVER escalate to a hard interrupt. A burst
- # of user messages while the agent is busy can land as a mix of accepted
- # steers (stashed in ``AIAgent._pending_steer``) and fall-through queue
- # envelopes (payload not steerable, ``steer()`` rejected/raised). A hard
- # interrupt here kills the live turn AND ``AIAgent.interrupt()`` drops
- # the pending steer buffer — silently destroying the earlier messages of
- # the burst. Steer-mode fall-throughs keep queue semantics: preserved
- # FIFO in ``queued_prompt``/``queued_prompts`` and drained on turn end.
- if mode == "interrupt" and not image_paths:
- _interrupt_busy_session(sid, session, agent)
- return _ok(rid, {"status": "queued"})
-
-
-def _drain_queued_prompt(rid, sid: str, session: dict) -> bool:
- """Fire a queued next-turn prompt if one is waiting and the session is idle.
-
- Returns True if a queued prompt was dispatched (the caller should then skip
- lower-priority follow-ups this cycle — the user's message wins). Mirrors the
- claim-under-lock pattern used by the goal-continuation re-fire.
- """
- with session["history_lock"]:
- if session.get("_closing"):
- return False
- queued = session.get("queued_prompt")
- if not queued or session.get("running"):
- return False
- queue_generation = int(session.get("_queued_prompt_generation", 0))
- queued_prompts = session.get("queued_prompts") or []
- session["queued_prompt"] = queued_prompts.pop(0) if queued_prompts else None
- if not queued_prompts:
- session.pop("queued_prompts", None)
- session["running"] = True
- if queued.get("transport") is not None:
- session["transport"] = queued["transport"]
- use_compute_host = _session_uses_compute_host(session)
- with session["history_lock"]:
- if int(session.get("_queued_prompt_generation", 0)) != queue_generation:
- # Generation cancelled the claim (Stop, compress re-anchor, …).
- # Do not dispatch — but put the claimed envelope back so a
- # legitimate follow-up is not silently dropped. Order: claimed
- # head first, then whatever advanced into the slot while we held
- # the claim (#84417 belt accuracy).
- rest: list = []
- advanced = session.get("queued_prompt")
- if advanced:
- rest.append(advanced)
- rest.extend(session.get("queued_prompts") or [])
- session["queued_prompt"] = queued
- if rest:
- session["queued_prompts"] = rest
- else:
- session.pop("queued_prompts", None)
- session["running"] = False
- return True
- dispatch_failed = False
- try:
- if use_compute_host:
- if queued.get("image_paths"):
- resp = _submit_prompt_to_compute_host(
- rid,
- sid,
- session,
- queued["text"],
- image_paths=queued["image_paths"],
- queued_prompt_generation=queue_generation,
- )
- else:
- resp = _submit_prompt_to_compute_host(
- rid, sid, session, queued["text"], queued_prompt_generation=queue_generation
- )
- if resp.get("error"):
- message = str(((resp.get("error") or {}).get("message")) or "queued prompt failed")
- with session["history_lock"]:
- session["running"] = False
- _clear_inflight_turn(session)
- _emit("error", sid, {"message": message})
- dispatch_failed = True
- else:
- if queued.get("image_paths"):
- _run_prompt_submit(
- rid,
- sid,
- session,
- queued["text"],
- image_paths=queued["image_paths"],
- queued_prompt_generation=queue_generation,
- )
- else:
- _run_prompt_submit(
- rid,
- sid,
- session,
- queued["text"],
- queued_prompt_generation=queue_generation,
- )
- except Exception as exc:
- print(
- f"[tui_gateway] queued prompt dispatch failed: "
- f"{type(exc).__name__}: {exc}",
- file=sys.stderr,
- )
- with session["history_lock"]:
- session["running"] = False
- dispatch_failed = True
- if dispatch_failed:
- with session["history_lock"]:
- drain_next = bool(session.get("queued_prompt")) and not session.get(
- "_turn_cancel_requested"
- )
- if drain_next:
- _drain_queued_prompt(rid, sid, session)
- return True
-
-
-def _inflight_snapshot(session: dict) -> dict | None:
- turn = session.get("inflight_turn")
- if not isinstance(turn, dict):
- return None
- user = str(turn.get("user") or "").strip()
- assistant = str(turn.get("assistant") or "")
- streaming = bool(turn.get("streaming"))
- error = str(turn.get("error") or "").strip()
- if not user and not assistant and not streaming and not error:
- return None
- snapshot = {
- "assistant": assistant,
- "streaming": streaming,
- "user": user,
- }
- raw_corrections = turn.get("corrections") or []
- raw_offsets = turn.get("correction_offsets") or []
- correction_pairs = [
- (str(c), raw_offsets[i] if i < len(raw_offsets) else None)
- for i, c in enumerate(raw_corrections)
- if str(c).strip()
- ]
- if correction_pairs:
- # Mid-turn redirects. Carried alongside the original prompt (not over
- # it) so resume can rebuild every user bubble the turn produced.
- snapshot["corrections"] = [c for c, _ in correction_pairs]
- # Assistant-text lengths at each correction boundary (parallel list).
- # Only sent when every correction has one, so clients can trust the
- # pairing; older in-memory turns without offsets omit the field and
- # clients fall back to placing corrections after the assistant dump.
- if all(isinstance(offset, int) and offset >= 0 for _, offset in correction_pairs):
- snapshot["correction_offsets"] = [int(offset) for _, offset in correction_pairs] # type: ignore[arg-type]
- if error:
- # Retained failed turn (see _fail_inflight_turn): carry the error
- # semantics so a resuming client can rebuild the failed-turn bubble
- # instead of rendering the partial text as a healthy reply.
- snapshot["error"] = error
- snapshot["status"] = str(turn.get("status") or "error")
- snapshot["recoverable"] = bool(turn.get("recoverable"))
- surface = turn.get("error_surface")
- if isinstance(surface, dict) and surface:
- snapshot["error_surface"] = surface
- return snapshot
-
-
-def _emit_terminal_turn_error(
- sid: str,
- session: dict,
- error: Any,
- error_surface: Optional[dict] = None,
- *,
- retire_marker: bool = True,
-) -> None:
- """Close a failed turn with a terminal ``message.complete`` frame.
-
- Emits the same ``status: "error"`` frame shape the returned-error path in
- ``_run_prompt_submit`` already produces (so TUI/desktop handling is
- uniform), and retains the failed turn via ``_fail_inflight_turn`` so a
- client that missed this frame (disconnect window) can recover it from
- ``session.resume``'s ``inflight`` payload.
-
- ``error_surface`` lets callers that already know the failing layer (e.g.
- agent-init failures = local runtime) pass it explicitly; exception
- callers leave it None and the classifier derives it here.
- """
- agent = session.get("agent")
- # Classify the failure into a {layer, code, retryable} descriptor so the
- # desktop can say "Provider error" / "Gateway error" with matching
- # recovery actions instead of a generic toast. Never raises (advisory).
- if error_surface is None and isinstance(error, BaseException):
- try:
- from agent.error_surface import build_error_surface_from_exception
-
- error_surface = build_error_surface_from_exception(
- error,
- provider=str(getattr(agent, "provider", "") or ""),
- model=str(getattr(agent, "model", "") or ""),
- )
- except Exception:
- error_surface = None
- with session["history_lock"]:
- _fail_inflight_turn(session, error, error_surface=error_surface)
- turn = session.get("inflight_turn") or {}
- message = str(turn.get("error") or "turn failed")
- partial = str(turn.get("assistant") or "")
- cols = int(session.get("cols", 80))
- text = partial or f"Error: {message}"
- payload = {
- "text": text,
- "usage": _get_usage(agent) if agent is not None else {},
- "status": "error",
- "error": message,
- "recoverable": True,
- }
- if error_surface:
- payload["error_surface"] = error_surface
- if partial:
- payload["partial"] = True
- try:
- rendered = render_message(text, cols)
- except Exception:
- rendered = ""
- if rendered:
- payload["rendered"] = rendered
- if retire_marker:
- _retire_turn_marker(session)
- _emit("message.complete", sid, payload)
-
-
-def _restore_agent_history_after_turn_error(session: dict, agent) -> bool:
- """Keep a failed turn's working transcript in the gateway session.
-
- ``AIAgent`` persists its working messages independently of the gateway's
- history snapshot. If the turn raises after that persistence, the next
- prompt must see the working transcript instead of the pre-turn snapshot.
- """
- agent_messages = getattr(agent, "_session_messages", None)
- if not isinstance(agent_messages, list):
- return False
- with session["history_lock"]:
- session["history"] = list(agent_messages)
- session["history_version"] = int(session.get("history_version", 0)) + 1
- return True
-
-
-def _queued_prompt_snapshot(session: dict) -> dict | None:
- """Return the accepted next-turn prompt without its transport handle.
-
- A busy ``prompt.submit`` lives only in ``session["queued_prompt"]`` until
- the current turn winds down. Desktop may reconnect or restart during that
- window, so the live-session projection must carry the user-visible text;
- otherwise the accepted prompt disappears until it finally drains.
- """
- queued = session.get("queued_prompt")
- if not isinstance(queued, dict):
- return None
- user = _inflight_text(queued.get("text"))
- return {"user": user} if user else None
-
-
# ── Methods: session ─────────────────────────────────────────────────
@@ -15439,6 +13423,9 @@ from . import ( # noqa: E402
methods_browser as _methods_browser,
methods_slash as _methods_slash,
methods_complete_helpers as _methods_complete_helpers,
+ session_auto_continue as _session_auto_continue,
+ agent_callbacks as _agent_callbacks,
+ session_history as _session_history,
methods_browser_control as _methods_browser_control,
methods_bot_relay as _methods_bot_relay,
methods_complete as _methods_complete,
@@ -15452,6 +13439,9 @@ from . import ( # noqa: E402
)
for _m in (
+ _session_history,
+ _agent_callbacks,
+ _session_auto_continue,
_methods_complete_helpers,
_methods_slash,
_methods_voice,
diff --git a/tui_gateway/session_auto_continue.py b/tui_gateway/session_auto_continue.py
new file mode 100644
index 00000000000..00aef441210
--- /dev/null
+++ b/tui_gateway/session_auto_continue.py
@@ -0,0 +1,695 @@
+"""Auto-continue: resume a turn killed by a process/machine death, plus queued-prompt drain and busy-submit handling.
+
+Bodies are rebound onto server.py's globals at install time (see
+method_ctx.bind_module), so they reference server.py globals bare.
+"""
+
+from __future__ import annotations
+
+
+from .method_ctx import HandlerRegistry, bind_module
+
+_registry = HandlerRegistry()
+
+
+# ── Auto-continue: resume a turn killed by a process/machine death ────
+#
+# A turn that concludes — success, handled error, interrupt — clears its
+# durable marker (see tui_gateway/turn_marker.py) in _run_prompt_submit's
+# finally. Only a process death leaves the marker behind, so a marker found
+# at session.resume time is positive proof the turn never finished AND the
+# client never saw a terminal frame. If the interruption is fresh, re-submit
+# the interrupted prompt automatically (the messaging gateway has done this
+# for restart-interrupted sessions since #27856); if it's stale, clear the
+# marker and let the recovered partial transcript speak for itself — the
+# user can ask to continue manually.
+
+_AUTO_CONTINUE_ENABLED_DEFAULT = True
+_AUTO_CONTINUE_FRESHNESS_MINUTES_DEFAULT = 15
+_AUTO_CONTINUE_MAX_ATTEMPTS_DEFAULT = 2
+
+
+def _auto_continue_config() -> tuple[bool, float, int]:
+ """(enabled, freshness window in seconds, max attempts) from config.yaml."""
+ desktop = _load_cfg().get("desktop")
+ cfg = desktop.get("auto_continue") if isinstance(desktop, dict) else None
+ if not isinstance(cfg, dict):
+ cfg = {}
+ try:
+ minutes = float(cfg.get("freshness_minutes", _AUTO_CONTINUE_FRESHNESS_MINUTES_DEFAULT))
+ except (TypeError, ValueError):
+ minutes = float(_AUTO_CONTINUE_FRESHNESS_MINUTES_DEFAULT)
+ return (
+ is_truthy_value(cfg.get("enabled"), default=_AUTO_CONTINUE_ENABLED_DEFAULT),
+ max(0.0, minutes) * 60.0,
+ _coerce_int_config_value(
+ cfg.get("max_attempts"), _AUTO_CONTINUE_MAX_ATTEMPTS_DEFAULT, min_value=0
+ ),
+ )
+
+
+def _session_home(session: dict) -> Path:
+ """The HERMES_HOME the session's durable state lives in (profile-aware)."""
+ profile_home = session.get("profile_home")
+ return Path(profile_home) if profile_home else Path(_hermes_home)
+
+
+def _retire_turn_marker(session: dict, *keys: str) -> None:
+ """Drop the crash marker for a turn whose outcome is about to reach the client.
+
+ Called immediately before the terminal frame rather than at the end of the
+ turn thread: post-turn work (titles, memory sync, goal hooks) runs for a
+ second or more after the client has its answer, and quitting inside that
+ window would leave a marker that looks like a crash — re-running a finished
+ turn on the next launch. Extra ``keys`` cover a session_key that
+ compression rotated mid-turn.
+ """
+ home = _session_home(session)
+ for key in dict.fromkeys((*keys, str(session.get("session_key") or ""))):
+ if key:
+ clear_turn_marker(home, key)
+
+
+def _auto_continue_note(prompt: str) -> str:
+ # Same opening as the messaging gateway's recovery notes so transcript
+ # tooling recognizes both. The original prompt is embedded because a hard
+ # crash persists nothing of the interrupted turn to the session DB — this
+ # note is the only copy the model will see.
+ return (
+ f"{_AUTO_CONTINUE_NOTE_PREFIX} — the app or its backend process "
+ "stopped before the turn could finish. Some of the work may already "
+ "be complete; check the current state before redoing anything, then "
+ "finish the task. The interrupted request was:]\n\n"
+ f"{prompt}"
+ )
+
+
+def _maybe_schedule_auto_continue(sid: str, session: dict, session_key: str) -> dict | None:
+ """Kick off a continuation turn for a crash-interrupted session.
+
+ Called from session.resume's cold paths after the live record is
+ registered. Returns a small descriptor for the resume payload when a
+ continuation was scheduled, else None. The turn itself runs on a
+ background thread after the (deferred) agent build finishes, through the
+ same _run_prompt_submit machinery as every other synthesized turn — so
+ the client that just resumed streams it live.
+ """
+ # Hosted room turns are recovered by their durable task/lease state
+ # machine. Generic session auto-continue would bypass its execution
+ # generation and can duplicate work after a process restart.
+ if session.get("source") == "bot_room":
+ return None
+
+ home = _session_home(session)
+ marker = read_turn_marker(home, session_key)
+ if marker is None:
+ return None
+ enabled, freshness_secs, max_attempts = _auto_continue_config()
+ age = time.time() - marker["started_at"]
+ if not enabled or age > freshness_secs or marker["attempts"] >= max_attempts:
+ # Stale, disabled, or crash-looping: stop trying. The journal/partial
+ # transcript still shows what happened; a manual message continues it.
+ clear_turn_marker(home, session_key)
+ return None
+ if session.get("_auto_continue_scheduled"):
+ return None
+ session["_auto_continue_scheduled"] = True
+ attempt = marker["attempts"] + 1
+ text = _auto_continue_note(marker["prompt"])
+
+ def kickoff() -> None:
+ rid = f"__auto_continue__{int(time.time() * 1000)}"
+ try:
+ _start_agent_build(sid, session)
+ err = _wait_agent(session, rid, timeout=120.0)
+ except Exception:
+ logger.warning("auto-continue agent build failed for %s", sid, exc_info=True)
+ err = {"error": {"message": "agent build failed"}}
+ if err:
+ # Leave the marker: the next resume retries (bounded by attempts).
+ session["_auto_continue_scheduled"] = False
+ return
+ with session["history_lock"]:
+ if session.get("running") or session.get("_turn_cancel_requested") or session.get("_finalized"):
+ # A real user prompt beat us to it — their turn wins, and its
+ # own conclusion clears the marker.
+ session["_auto_continue_scheduled"] = False
+ return
+ session["running"] = True
+ session["last_active"] = time.time()
+ # Ownership admission BEFORE message.start: the interrupted-turn
+ # marker this continuation is recovering may have been written by a
+ # sibling backend that is still alive and mid-turn (#94778 — two
+ # backends share one HERMES_HOME; B resumes S while A runs it and
+ # sees A's fresh marker). Running the continuation anyway would be
+ # the double-writer this fence exists to prevent. Leave the marker:
+ # once the owner finishes or dies, a later resume retries.
+ if _ensure_active_session_slot(sid, session) is not None:
+ logger.info(
+ "auto-continue for %s refused: session has another live owner",
+ session_key,
+ )
+ with session["history_lock"]:
+ session["running"] = False
+ session["_auto_continue_scheduled"] = False
+ return
+ with session["history_lock"]:
+ # Hand this turn its own marker inputs (read back by
+ # _run_prompt_submit): count the attempt so a crash during the
+ # continuation trips the breaker, and re-record the ORIGINAL
+ # prompt so a second crash doesn't nest note inside note. Set
+ # here, not at schedule time, so a bail above leaves nothing
+ # behind for a racing user turn to inherit.
+ session["_auto_continue_attempt"] = attempt
+ session["_auto_continue_prompt"] = marker["prompt"]
+ try:
+ _emit(
+ "status.update",
+ sid,
+ {"kind": "process", "text": "Resuming interrupted turn…"},
+ )
+ _emit("message.start", sid)
+ _run_prompt_submit(rid, sid, session, text, display_kind="auto_continue")
+ except Exception as exc:
+ print(
+ f"[tui_gateway] auto-continue dispatch failed: "
+ f"{type(exc).__name__}: {exc}",
+ file=sys.stderr,
+ )
+ with session["history_lock"]:
+ session["running"] = False
+
+ threading.Thread(target=kickoff, daemon=True).start()
+ logger.info(
+ "auto-continue scheduled for session %s (attempt %d, interrupted %.0fs ago)",
+ session_key,
+ attempt,
+ age,
+ )
+ return {"attempt": attempt, "interrupted_at": marker["started_at"]}
+
+
+def _enqueue_prompt(
+ session: dict,
+ text: Any,
+ transport: Any,
+ image_paths: list[str] | None = None,
+) -> None:
+ """Stash a message to run as the very next turn once the live one ends.
+
+ Used when a prompt arrives mid-turn (see ``_handle_busy_submit``). Text-only
+ arrivals share a slot and merge losslessly (mirroring the consecutive-user
+ merge in ``repair_message_sequence``). Image-bearing submissions stay as
+ separate envelopes, so their attachment ownership and chronology survive.
+ ``transport`` is pinned so the drained turn streams back to the client that
+ sent it even if the session transport is rebound meanwhile.
+ """
+ image_paths = list(image_paths or [])
+ # #84417: scrub any live-turn self-duplicates first so the consecutive-text
+ # merge below cannot glue "{original}\\n\\n{later}" and re-fire original
+ # on drain after a later correction settles.
+ _drop_queued_duplicates_of_inflight_user(session)
+ # Never queue a text-only self-copy of the live inflight user prompt. The
+ # live turn already owns that text; draining it after settle would restart
+ # the same user turn as a fresh agent invocation.
+ if not image_paths and isinstance(text, str):
+ turn = session.get("inflight_turn")
+ original = (
+ str(turn.get("user") or "").strip() if isinstance(turn, dict) else ""
+ )
+ if original and text.strip() == original:
+ return
+ queued = {"text": text, "transport": transport}
+ if image_paths:
+ queued["image_paths"] = image_paths
+ existing = session.get("queued_prompt")
+ if (
+ existing
+ and isinstance(existing.get("text"), str)
+ and isinstance(text, str)
+ and not existing.get("image_paths")
+ and not image_paths
+ and not session.get("queued_prompts")
+ ):
+ prev = existing["text"]
+ existing["text"] = f"{prev}\n\n{text}" if prev and text else (prev or text)
+ return
+ if existing:
+ session.setdefault("queued_prompts", []).append(queued)
+ return
+ session["queued_prompt"] = queued
+
+
+def _sanitize_queued_entry_vs_inflight_user(
+ entry: Any, original: str
+) -> dict | None:
+ """Drop or rewrite a queue envelope that re-carries the live user text.
+
+ Returns ``None`` to drop the envelope, or a (possibly rewritten) dict to
+ keep. Text-only self-duplicates of ``original`` are dropped. A merged
+ slot ``"{original}\\n\\n{later}"`` (from ``_enqueue_prompt``'s consecutive
+ text merge) is rewritten to just ``later`` so a later correction is not
+ lost and the original is not re-fired (#84417). Image-bearing envelopes
+ are left alone — their chronology/ownership is load-bearing.
+ """
+ if not original or not isinstance(entry, dict):
+ return entry if isinstance(entry, dict) else None
+ if entry.get("image_paths"):
+ return entry
+ text = entry.get("text")
+ if not isinstance(text, str):
+ return entry
+ stripped = text.strip()
+ if not stripped:
+ return None
+ if stripped == original:
+ return None
+ # Lossless text-merge glued the live original onto a later follow-up.
+ for sep in ("\n\n", "\n"):
+ prefix = original + sep
+ if text.startswith(prefix):
+ rest = text[len(prefix) :].strip()
+ if not rest or rest == original:
+ return None
+ cleaned = dict(entry)
+ cleaned["text"] = rest
+ return cleaned
+ return entry
+
+
+def _drop_queued_duplicates_of_inflight_user(session: dict) -> None:
+ """Remove server-queue copies of the live turn's original user text.
+
+ A mid-turn ``prompt.submit`` of the same text can land in
+ ``queued_prompt`` when redirect is not yet available (model not active,
+ build window, tool boundary). If the user then corrects the turn with a
+ different prompt via redirect, that stale self-duplicate must not
+ ``_drain_queued_prompt`` after the redirected turn completes — otherwise
+ the original prompt restarts as a fresh agent turn (#84417).
+
+ Unrelated follow-ups (different text, image-bearing envelopes) stay.
+ Merged ``original + later`` slots are rewritten to ``later`` only.
+ """
+ turn = session.get("inflight_turn")
+ if not isinstance(turn, dict):
+ return
+ original = str(turn.get("user") or "").strip()
+ if not original:
+ return
+
+ head = session.get("queued_prompt")
+ rest = list(session.get("queued_prompts") or [])
+ kept: list[dict] = []
+ for entry in ([head] if head else []) + rest:
+ cleaned = _sanitize_queued_entry_vs_inflight_user(entry, original)
+ if cleaned is not None:
+ kept.append(cleaned)
+
+ if not kept:
+ session["queued_prompt"] = None
+ session.pop("queued_prompts", None)
+ return
+ session["queued_prompt"] = kept[0]
+ if len(kept) > 1:
+ session["queued_prompts"] = kept[1:]
+ else:
+ session.pop("queued_prompts", None)
+
+
+def _interrupt_busy_session(sid: str, session: dict, agent: Any) -> None:
+ """Interrupt a busy turn without blocking the RPC reader or session lock.
+
+ Some providers cannot apply ``interrupt()`` until a synchronous tool or
+ network call returns. Running that call inline used to leave
+ ``prompt.submit`` holding ``history_lock`` for the whole wait, which in turn
+ blocked ``session.resume`` and delayed the queued prompt itself. Keep at
+ most one interrupt worker per session so repeated steering cannot leak an
+ unbounded number of blocked threads.
+ """
+ use_agent = agent is not None and hasattr(agent, "interrupt")
+ use_compute_host = not use_agent and _session_uses_compute_host(session)
+ if not use_agent and not use_compute_host:
+ return
+
+ with session["history_lock"]:
+ if session.get("_busy_interrupt_pending"):
+ return
+ session["_busy_interrupt_pending"] = True
+
+ def interrupt() -> None:
+ try:
+ if use_agent:
+ agent.interrupt()
+ else:
+ _get_compute_host_supervisor().interrupt(sid)
+ except Exception:
+ pass
+ finally:
+ with session["history_lock"]:
+ session["_busy_interrupt_pending"] = False
+
+ threading.Thread(target=interrupt, daemon=True, name=f"busy-interrupt-{sid}").start()
+
+
+def _handle_busy_submit(
+ rid, sid: str, session: dict, text: Any, transport: Any, queued: bool = False
+) -> dict | None:
+ """Apply the ``display.busy_input_mode`` policy to a prompt that lands while
+ a turn is in flight, instead of rejecting it with ``session busy``.
+
+ The old rejection forced clients into a deadline-bounded busy-retry that
+ silently dropped the send when turn teardown outlived the deadline. The
+ default policy now redirects a capable core agent in place; older agents
+ retain the proven interrupt-and-queue path drained from ``run``'s tail.
+
+ Modes: ``interrupt`` (default) → redirect the live turn, falling back to
+ hard interrupt + queue for older agents; ``queue`` → queue without
+ interrupting; ``steer`` → inject after the current atomic action.
+
+ ``queued=True`` (client's queue drain, ``prompt.submit`` param) overrides
+ the mode entirely: the message was explicitly queued as "run after", so it
+ must NEVER become a live-turn correction or interrupt. Without this, a
+ drain that loses the settle race (client observed idle, server still
+ unwinding the turn) redirected the live turn with next-turn text — queue
+ semantics betrayed by a millisecond race the user can't see.
+ """
+ mode = "queue" if queued else _load_busy_input_mode()
+ agent = session.get("agent")
+ with session["history_lock"]:
+ if not session.get("running"):
+ # The turn ended between prompt.submit's first busy check and this
+ # helper. Let the caller retry and claim the now-idle session.
+ return None
+ with session["history_lock"]:
+ if not session.get("running"):
+ return None
+ image_paths = list(session.get("attached_images", []))
+ if image_paths:
+ # Claim at submission time. A later paste must not be consumed by
+ # this prompt after the active turn finally yields.
+ session["attached_images"] = []
+ text_only = not image_paths and _is_text_only_busy_payload(text)
+ plain_text = _coerce_message_text(text).strip() if text_only else ""
+ if mode == "steer" and text_only and plain_text and agent is not None and hasattr(agent, "steer"):
+ try:
+ if agent.steer(plain_text):
+ with session["history_lock"]:
+ _record_inflight_correction(session, plain_text)
+ _drop_queued_duplicates_of_inflight_user(session)
+ session["last_active"] = time.time()
+ return _ok(rid, {"status": "steered"})
+ except Exception:
+ pass # fall through to queue
+ # Text-only corrections redirect the live turn in place when the runtime
+ # supports it; media/attachment payloads and older agents fall through to
+ # the proven interrupt + queue path below.
+ if (
+ mode == "interrupt"
+ and text_only
+ and plain_text
+ and agent is not None
+ and getattr(agent, "_supports_active_turn_redirect", False) is True
+ and hasattr(agent, "redirect")
+ ):
+ try:
+ if agent.redirect(plain_text):
+ with session["history_lock"]:
+ _record_inflight_correction(session, plain_text)
+ # #84417: do not re-fire the live turn's original user text
+ # from a stale server-queue self-duplicate after settle.
+ _drop_queued_duplicates_of_inflight_user(session)
+ session["last_active"] = time.time()
+ return _ok(rid, {"status": "redirected"})
+ except Exception:
+ pass # preserve the proven interrupt + queue fallback below
+ # Queue before asking the live turn to stop. In particular, never call a
+ # provider or compute-host method while holding history_lock: an interrupt
+ # can wait behind the very operation it is trying to cancel.
+ with session["history_lock"]:
+ if not session.get("running"):
+ if image_paths:
+ session["attached_images"] = image_paths + list(session.get("attached_images", []))
+ return None
+ _enqueue_prompt(session, text, transport, image_paths=image_paths)
+ session["last_active"] = time.time()
+
+ # Attachments need a separate model invocation. Queue them without
+ # cancelling the active turn so the user gets both results in order.
+ #
+ # #86134: ``steer`` mode must NEVER escalate to a hard interrupt. A burst
+ # of user messages while the agent is busy can land as a mix of accepted
+ # steers (stashed in ``AIAgent._pending_steer``) and fall-through queue
+ # envelopes (payload not steerable, ``steer()`` rejected/raised). A hard
+ # interrupt here kills the live turn AND ``AIAgent.interrupt()`` drops
+ # the pending steer buffer — silently destroying the earlier messages of
+ # the burst. Steer-mode fall-throughs keep queue semantics: preserved
+ # FIFO in ``queued_prompt``/``queued_prompts`` and drained on turn end.
+ if mode == "interrupt" and not image_paths:
+ _interrupt_busy_session(sid, session, agent)
+ return _ok(rid, {"status": "queued"})
+
+
+def _drain_queued_prompt(rid, sid: str, session: dict) -> bool:
+ """Fire a queued next-turn prompt if one is waiting and the session is idle.
+
+ Returns True if a queued prompt was dispatched (the caller should then skip
+ lower-priority follow-ups this cycle — the user's message wins). Mirrors the
+ claim-under-lock pattern used by the goal-continuation re-fire.
+ """
+ with session["history_lock"]:
+ if session.get("_closing"):
+ return False
+ queued = session.get("queued_prompt")
+ if not queued or session.get("running"):
+ return False
+ queue_generation = int(session.get("_queued_prompt_generation", 0))
+ queued_prompts = session.get("queued_prompts") or []
+ session["queued_prompt"] = queued_prompts.pop(0) if queued_prompts else None
+ if not queued_prompts:
+ session.pop("queued_prompts", None)
+ session["running"] = True
+ if queued.get("transport") is not None:
+ session["transport"] = queued["transport"]
+ use_compute_host = _session_uses_compute_host(session)
+ with session["history_lock"]:
+ if int(session.get("_queued_prompt_generation", 0)) != queue_generation:
+ # Generation cancelled the claim (Stop, compress re-anchor, …).
+ # Do not dispatch — but put the claimed envelope back so a
+ # legitimate follow-up is not silently dropped. Order: claimed
+ # head first, then whatever advanced into the slot while we held
+ # the claim (#84417 belt accuracy).
+ rest: list = []
+ advanced = session.get("queued_prompt")
+ if advanced:
+ rest.append(advanced)
+ rest.extend(session.get("queued_prompts") or [])
+ session["queued_prompt"] = queued
+ if rest:
+ session["queued_prompts"] = rest
+ else:
+ session.pop("queued_prompts", None)
+ session["running"] = False
+ return True
+ dispatch_failed = False
+ try:
+ if use_compute_host:
+ if queued.get("image_paths"):
+ resp = _submit_prompt_to_compute_host(
+ rid,
+ sid,
+ session,
+ queued["text"],
+ image_paths=queued["image_paths"],
+ queued_prompt_generation=queue_generation,
+ )
+ else:
+ resp = _submit_prompt_to_compute_host(
+ rid, sid, session, queued["text"], queued_prompt_generation=queue_generation
+ )
+ if resp.get("error"):
+ message = str(((resp.get("error") or {}).get("message")) or "queued prompt failed")
+ with session["history_lock"]:
+ session["running"] = False
+ _clear_inflight_turn(session)
+ _emit("error", sid, {"message": message})
+ dispatch_failed = True
+ else:
+ if queued.get("image_paths"):
+ _run_prompt_submit(
+ rid,
+ sid,
+ session,
+ queued["text"],
+ image_paths=queued["image_paths"],
+ queued_prompt_generation=queue_generation,
+ )
+ else:
+ _run_prompt_submit(
+ rid,
+ sid,
+ session,
+ queued["text"],
+ queued_prompt_generation=queue_generation,
+ )
+ except Exception as exc:
+ print(
+ f"[tui_gateway] queued prompt dispatch failed: "
+ f"{type(exc).__name__}: {exc}",
+ file=sys.stderr,
+ )
+ with session["history_lock"]:
+ session["running"] = False
+ dispatch_failed = True
+ if dispatch_failed:
+ with session["history_lock"]:
+ drain_next = bool(session.get("queued_prompt")) and not session.get(
+ "_turn_cancel_requested"
+ )
+ if drain_next:
+ _drain_queued_prompt(rid, sid, session)
+ return True
+
+
+def _inflight_snapshot(session: dict) -> dict | None:
+ turn = session.get("inflight_turn")
+ if not isinstance(turn, dict):
+ return None
+ user = str(turn.get("user") or "").strip()
+ assistant = str(turn.get("assistant") or "")
+ streaming = bool(turn.get("streaming"))
+ error = str(turn.get("error") or "").strip()
+ if not user and not assistant and not streaming and not error:
+ return None
+ snapshot = {
+ "assistant": assistant,
+ "streaming": streaming,
+ "user": user,
+ }
+ raw_corrections = turn.get("corrections") or []
+ raw_offsets = turn.get("correction_offsets") or []
+ correction_pairs = [
+ (str(c), raw_offsets[i] if i < len(raw_offsets) else None)
+ for i, c in enumerate(raw_corrections)
+ if str(c).strip()
+ ]
+ if correction_pairs:
+ # Mid-turn redirects. Carried alongside the original prompt (not over
+ # it) so resume can rebuild every user bubble the turn produced.
+ snapshot["corrections"] = [c for c, _ in correction_pairs]
+ # Assistant-text lengths at each correction boundary (parallel list).
+ # Only sent when every correction has one, so clients can trust the
+ # pairing; older in-memory turns without offsets omit the field and
+ # clients fall back to placing corrections after the assistant dump.
+ if all(isinstance(offset, int) and offset >= 0 for _, offset in correction_pairs):
+ snapshot["correction_offsets"] = [int(offset) for _, offset in correction_pairs] # type: ignore[arg-type]
+ if error:
+ # Retained failed turn (see _fail_inflight_turn): carry the error
+ # semantics so a resuming client can rebuild the failed-turn bubble
+ # instead of rendering the partial text as a healthy reply.
+ snapshot["error"] = error
+ snapshot["status"] = str(turn.get("status") or "error")
+ snapshot["recoverable"] = bool(turn.get("recoverable"))
+ surface = turn.get("error_surface")
+ if isinstance(surface, dict) and surface:
+ snapshot["error_surface"] = surface
+ return snapshot
+
+
+def _emit_terminal_turn_error(
+ sid: str,
+ session: dict,
+ error: Any,
+ error_surface: Optional[dict] = None,
+ *,
+ retire_marker: bool = True,
+) -> None:
+ """Close a failed turn with a terminal ``message.complete`` frame.
+
+ Emits the same ``status: "error"`` frame shape the returned-error path in
+ ``_run_prompt_submit`` already produces (so TUI/desktop handling is
+ uniform), and retains the failed turn via ``_fail_inflight_turn`` so a
+ client that missed this frame (disconnect window) can recover it from
+ ``session.resume``'s ``inflight`` payload.
+
+ ``error_surface`` lets callers that already know the failing layer (e.g.
+ agent-init failures = local runtime) pass it explicitly; exception
+ callers leave it None and the classifier derives it here.
+ """
+ agent = session.get("agent")
+ # Classify the failure into a {layer, code, retryable} descriptor so the
+ # desktop can say "Provider error" / "Gateway error" with matching
+ # recovery actions instead of a generic toast. Never raises (advisory).
+ if error_surface is None and isinstance(error, BaseException):
+ try:
+ from agent.error_surface import build_error_surface_from_exception
+
+ error_surface = build_error_surface_from_exception(
+ error,
+ provider=str(getattr(agent, "provider", "") or ""),
+ model=str(getattr(agent, "model", "") or ""),
+ )
+ except Exception:
+ error_surface = None
+ with session["history_lock"]:
+ _fail_inflight_turn(session, error, error_surface=error_surface)
+ turn = session.get("inflight_turn") or {}
+ message = str(turn.get("error") or "turn failed")
+ partial = str(turn.get("assistant") or "")
+ cols = int(session.get("cols", 80))
+ text = partial or f"Error: {message}"
+ payload = {
+ "text": text,
+ "usage": _get_usage(agent) if agent is not None else {},
+ "status": "error",
+ "error": message,
+ "recoverable": True,
+ }
+ if error_surface:
+ payload["error_surface"] = error_surface
+ if partial:
+ payload["partial"] = True
+ try:
+ rendered = render_message(text, cols)
+ except Exception:
+ rendered = ""
+ if rendered:
+ payload["rendered"] = rendered
+ if retire_marker:
+ _retire_turn_marker(session)
+ _emit("message.complete", sid, payload)
+
+
+def _restore_agent_history_after_turn_error(session: dict, agent) -> bool:
+ """Keep a failed turn's working transcript in the gateway session.
+
+ ``AIAgent`` persists its working messages independently of the gateway's
+ history snapshot. If the turn raises after that persistence, the next
+ prompt must see the working transcript instead of the pre-turn snapshot.
+ """
+ agent_messages = getattr(agent, "_session_messages", None)
+ if not isinstance(agent_messages, list):
+ return False
+ with session["history_lock"]:
+ session["history"] = list(agent_messages)
+ session["history_version"] = int(session.get("history_version", 0)) + 1
+ return True
+
+
+def _queued_prompt_snapshot(session: dict) -> dict | None:
+ """Return the accepted next-turn prompt without its transport handle.
+
+ A busy ``prompt.submit`` lives only in ``session["queued_prompt"]`` until
+ the current turn winds down. Desktop may reconnect or restart during that
+ window, so the live-session projection must carry the user-visible text;
+ otherwise the accepted prompt disappears until it finally drains.
+ """
+ queued = session.get("queued_prompt")
+ if not isinstance(queued, dict):
+ return None
+ user = _inflight_text(queued.get("text"))
+ return {"user": user} if user else None
+
+
+def register(server) -> None:
+ """Publish this module's helpers + handlers onto ``server``, rebound to its globals."""
+ bind_module(globals(), server, skip=("_",))
diff --git a/tui_gateway/session_history.py b/tui_gateway/session_history.py
new file mode 100644
index 00000000000..5dbbd35c102
--- /dev/null
+++ b/tui_gateway/session_history.py
@@ -0,0 +1,687 @@
+"""Session history/message shaping: image-ref messages, content coercion, history->wire messages, in-flight turn tracking and turn-failure detail.
+
+Bodies are rebound onto server.py's globals at install time (see
+method_ctx.bind_module), so they reference server.py globals bare.
+"""
+
+from __future__ import annotations
+
+
+from .method_ctx import HandlerRegistry, bind_module
+
+_registry = HandlerRegistry()
+
+
+def _active_image_routing_identity(agent: Any) -> tuple[str, str]:
+ """Return the live provider/model, falling back before agent startup."""
+ from agent.auxiliary_client import _read_main_model, _read_main_provider
+
+ return (
+ getattr(agent, "provider", "") or _read_main_provider(),
+ getattr(agent, "model", "") or _read_main_model(),
+ )
+
+
+def _build_image_ref_message(user_text: str, image_paths: list[str]) -> str:
+ """Reference attached images by path so the agent analyzes them in-loop.
+
+ This used to pre-analyze every image with the auxiliary vision model
+ *before* the turn was dispatched (``_enrich_with_attached_images``):
+ serial blocking calls on the submit path — 60-90s per large photo —
+ with failures silently swallowed and an interrupt during the window
+ killing the turn with zero API calls (#83291). It also prepended the
+ vision description to the first user message, poisoning session
+ auto-titles (#82339). The CLI never gates turn dispatch on vision
+ like this, which is why the same message was seconds there and
+ minutes on desktop.
+
+ Now the turn starts immediately. The agent examines each image itself
+ with ``vision_analyze`` — its own retries, visible tool progress —
+ exactly how the ``@folder:`` reference path already behaves, which
+ responds in seconds for the same images.
+ """
+ parts: list[str] = []
+ for path in image_paths:
+ p = Path(path)
+ if not p.exists():
+ continue
+ parts.append(
+ f"[The user attached an image: {p.name}]\n"
+ f"[Examine it with the vision_analyze tool using image_url: {p}]"
+ )
+
+ text = user_text or ""
+ prefix = "\n\n".join(parts)
+ if prefix:
+ return f"{prefix}\n\n{text}" if text else prefix
+ return text or "What do you see in this image?"
+
+
+def _build_persist_message_with_image_refs(user_text: str, image_paths: list[str]) -> str:
+ """Build the clean, UI-recognizable version of the user's message for
+ persisting to session history. Uses ``@image:<path>`` directives — the
+ format the desktop client (directive-text.tsx / HERMES_DIRECTIVE_RE)
+ actually parses and renders as an image — unlike
+ ``_build_image_ref_message``, which embeds an
+ ``image_url:`` hint meant only for the model and must never be
+ persisted as-is (it silently breaks image rendering after a full
+ restart, and reorders image/text on live session-switch reconciliation).
+
+ The caption leads and the directives trail: session previews are the first
+ 60 characters of the first user message (``list_sessions_rich``), so a
+ leading directive would label the session with a truncated file path in the
+ sidebar, switcher, and command palette. Clients lift the refs out of the
+ body by line, so their position does not affect how the turn renders.
+ """
+ from agent.context_references import format_reference_value
+
+ text = user_text or ""
+ refs = "\n".join(f"@image:{format_reference_value(p)}" for p in image_paths if Path(p).exists())
+ if not refs:
+ return text
+ return f"{text}\n{refs}" if text else refs
+
+
+def _build_persist_user_message(user_text: str, image_paths: list[str], run_message: Any) -> Any:
+ """Shape the persisted user turn to match what was sent to the model.
+
+ Native-vision turns send ``content`` as a parts list, and
+ ``_flush_messages_to_session_db`` deliberately ignores a plain-string
+ override for a list payload (a text override must not erase a turn's
+ image/audio summary). So mirror the shape: replace only the text part with
+ the ``@image:`` ref form and keep the image parts, so the model still has
+ the pixels for the rest of the session. Any API-only text part (the
+ barge-in note) is dropped along the way, which is the point of the override.
+ """
+ persist_text = _build_persist_message_with_image_refs(user_text, image_paths)
+ if not isinstance(run_message, list):
+ return persist_text
+ image_parts = [p for p in run_message if not (isinstance(p, dict) and p.get("type") == "text")]
+ return [{"type": "text", "text": persist_text}, *image_parts]
+
+
+def _content_display_text(content: Any) -> str:
+ if content is None:
+ return ""
+ if isinstance(content, str):
+ return content
+ if isinstance(content, (int, float)):
+ return str(content)
+ if isinstance(content, list):
+ parts = []
+ for part in content:
+ text = _content_display_text(part).strip()
+ if text:
+ parts.append(text)
+ return "\n".join(parts)
+ if isinstance(content, dict):
+ kind = content.get("type")
+ if kind in {"text", "input_text", "output_text"}:
+ return str(content.get("text") or content.get("content") or "")
+ if kind in {"image_url", "input_image", "image"}:
+ return "[image]"
+ if kind in {"input_audio", "audio"}:
+ return "[audio]"
+ if kind:
+ return f"[{kind}]"
+ if "text" in content:
+ return str(content.get("text") or "")
+ return "[structured content]"
+ return str(content)
+
+
+def _coerce_message_text(content: Any) -> str:
+ """Render ``message['content']`` as a plain string for transport.
+
+ Provider-side, ``content`` may be a string (most common), a list of
+ multimodal parts (e.g. ``[{"type": "text", "text": "..."},
+ {"type": "image_url", "image_url": {...}}]``), or a single structured
+ dict. Calling ``.strip()`` on a list raises ``'list' object has no
+ attribute 'strip'`` and breaks session resume entirely.
+
+ Image parts (``image_url``) are preserved by appending the underlying
+ URL (data: or http:) into the text. The desktop renderer pulls these
+ back out via ``extractEmbeddedImages`` so the user sees the image
+ instead of the URL — and it stops the resume payload from disagreeing
+ with the cached message (which would otherwise cause the inline image
+ to flash, then disappear when the resume payload overwrites the cache).
+
+ Other structured dict shapes (audio, unknown types) fall back to a
+ bracketed placeholder so resume doesn't drop the message entirely.
+ """
+ if content is None:
+ return ""
+ if isinstance(content, str):
+ return content
+ if isinstance(content, (int, float)):
+ return str(content)
+ if isinstance(content, list):
+ chunks: list[str] = []
+ for part in content:
+ if isinstance(part, str):
+ chunks.append(part)
+ continue
+ if not isinstance(part, dict):
+ continue
+ text = part.get("text")
+ if isinstance(text, str):
+ chunks.append(text)
+ continue
+ kind = part.get("type")
+ if kind in {"text", "input_text", "output_text"}:
+ t = part.get("text") or part.get("content") or ""
+ if t:
+ chunks.append(str(t))
+ continue
+ if kind in {"image_url", "input_image", "image"}:
+ image_url = part.get("image_url")
+ url = ""
+ if isinstance(image_url, dict):
+ candidate = image_url.get("url")
+ if isinstance(candidate, str):
+ url = candidate
+ elif isinstance(image_url, str):
+ url = image_url
+ if url:
+ chunks.append(f"\n{url}")
+ else:
+ chunks.append("\n[image]")
+ continue
+ if kind in {"input_audio", "audio"}:
+ chunks.append("\n[audio]")
+ continue
+ if kind:
+ chunks.append(f"\n[{kind}]")
+ return "".join(chunks)
+ if isinstance(content, dict):
+ kind = content.get("type")
+ if kind in {"text", "input_text", "output_text"}:
+ return str(content.get("text") or content.get("content") or "")
+ if kind in {"image_url", "input_image", "image"}:
+ image_url = content.get("image_url")
+ url = ""
+ if isinstance(image_url, dict):
+ candidate = image_url.get("url")
+ if isinstance(candidate, str):
+ url = candidate
+ elif isinstance(image_url, str):
+ url = image_url
+ return url or "[image]"
+ if kind in {"input_audio", "audio"}:
+ return "[audio]"
+ if kind:
+ return f"[{kind}]"
+ if "text" in content:
+ return str(content.get("text") or "")
+ return "[structured content]"
+ return str(content)
+
+
+_TEXT_ONLY_BUSY_PART_KINDS = frozenset({"text", "input_text", "output_text"})
+
+
+def _is_text_only_busy_payload(content: Any) -> bool:
+ """True when a busy submit carries only plain text, not attachments/media."""
+ if content is None:
+ return False
+ if isinstance(content, (str, int, float)):
+ return True
+ if isinstance(content, list):
+ if not content:
+ return False
+ for part in content:
+ if isinstance(part, str):
+ continue
+ if not isinstance(part, dict):
+ return False
+ kind = part.get("type")
+ if kind in _TEXT_ONLY_BUSY_PART_KINDS:
+ continue
+ if kind is None and isinstance(part.get("text"), str):
+ continue
+ return False
+ return True
+ if isinstance(content, dict):
+ kind = content.get("type")
+ if kind in _TEXT_ONLY_BUSY_PART_KINDS:
+ return True
+ return kind is None and isinstance(content.get("text"), str)
+ return False
+
+
+def _is_display_hidden_marker(role: str | None, text: str) -> bool:
+ """Gateway bookkeeping notices (model-switch, personality) are persisted as
+ role=user ``[System: …]`` rows so strict providers accept them mid-history.
+ They are model-facing runtime metadata, not user turns, and must never
+ render as a user bubble in ANY client transcript (desktop, TUI, CLI, web).
+
+ Filtering here — the single display projection every surface reads — hides
+ them everywhere while the raw marker stays in ``session["history"]`` for the
+ model. It also removes the stored marker from the payload the desktop
+ reconciles against, so it can no longer shift user-message ordinals and
+ duplicate the optimistic prompt (#67603)."""
+ return role == "user" and text.lstrip().startswith("[System:")
+
+
+def _skill_scaffold_projection(content_text: str) -> str:
+ """Return the invocation a slash-skill-expanded turn came from, else "".
+
+ A ``/skill`` invocation expands into a model-facing message that embeds the
+ whole skill body. That payload belongs to the agent — every UI renders the
+ invocation (``/work fix the leak``) instead, so no surface can leak the
+ body into a chat bubble.
+ """
+ return describe_skill_invocation(content_text, separator=" ") or ""
+
+
+def _expand_skill_invocation_for_replay(text: str, task_id: str) -> str:
+ """Re-expand a projected `/skill` invocation before re-running that turn.
+
+ The inverse of :func:`_skill_scaffold_projection`. Because a skill turn is
+ displayed as its invocation, a rewind/regenerate hands us back
+ ``/work fix the leak`` rather than the body the agent originally saw —
+ re-running that verbatim would drop the skill. Re-expanding here keeps the
+ body server-side (no client ever holds it) and makes the replayed turn
+ identical to the original.
+
+ Returns *text* unchanged when it isn't a resolvable skill invocation.
+ """
+ head, _, arg = (text or "").strip().partition(" ")
+ if not head.startswith("/"):
+ return text
+
+ try:
+ from agent.skill_commands import (
+ build_skill_invocation_message,
+ resolve_skill_command_key,
+ )
+
+ cmd_key = resolve_skill_command_key(head.lstrip("/"))
+ if cmd_key is None:
+ return text
+
+ return build_skill_invocation_message(cmd_key, arg.strip(), task_id=task_id) or text
+ except Exception:
+ # A skill that no longer resolves (renamed, disabled, external dir
+ # gone) must not break the rewind — replay the text as typed.
+ logger.debug("skill re-expansion failed for replay", exc_info=True)
+ return text
+
+
+# Opening of the crash-recovery note synthesized by _auto_continue_note.
+# Matched (not just built) so a row persisted before the display type was
+# stamped at turn start still reads as a timeline event, and to recognize the
+# messaging gateway's twin note.
+_AUTO_CONTINUE_NOTE_PREFIX = "[System note: Your previous turn was interrupted mid-run"
+
+
+def _legacy_display_kind(role: str, text: str) -> str | None:
+ """Infer the display type of a synthetic row persisted without one.
+
+ Turn-start typing (see ``persist_user_display_kind``) covers everything
+ written from here on. Sessions already on disk carry untyped rows — and a
+ turn killed mid-run never reached the post-turn stamp at all, which is
+ exactly the auto-continue case — so the raw recovery note would paint as a
+ user bubble forever. Sniffing the one fixed synthetic prefix is the
+ migration for those rows; it is not how new rows get typed.
+ """
+ if role == "user" and text.lstrip().startswith(_AUTO_CONTINUE_NOTE_PREFIX):
+ return "auto_continue"
+ return None
+
+
+def _history_to_messages(history: list[dict]) -> list[dict]:
+ messages = []
+ tool_call_args = {}
+
+ for m in history:
+ if not isinstance(m, dict):
+ continue
+ m = project_compaction_message_for_display(m)
+ if m is None:
+ continue
+ role = m.get("role")
+ if role not in {"user", "assistant", "tool", "system"}:
+ continue
+ # An explicit display_kind="hidden" row is model-facing scaffolding
+ # (compaction references, interrupted-turn checkpoints). The string
+ # sniff below only catches the "[System:" convention; honor the
+ # declared field too, or scaffolding reaches every surface that reads
+ # this projection.
+ if m.get("display_kind") == "hidden":
+ continue
+ content_text = _coerce_message_text(m.get("content"))
+ if _is_display_hidden_marker(role, content_text):
+ continue
+ if role == "assistant" and m.get("tool_calls"):
+ for tc in m["tool_calls"]:
+ fn = tc.get("function", {})
+ tc_id = tc.get("id", "")
+ if tc_id and fn.get("name"):
+ try:
+ args = json.loads(fn.get("arguments", "{}"))
+ except (json.JSONDecodeError, TypeError):
+ args = {}
+ tool_call_args[tc_id] = (fn["name"], args)
+ if not content_text.strip():
+ continue
+ if role == "tool":
+ tc_id = m.get("tool_call_id", "")
+ tc_info = tool_call_args.get(tc_id) if tc_id else None
+ name = (tc_info[0] if tc_info else None) or m.get("tool_name") or "tool"
+ args = (tc_info[1] if tc_info else None) or {}
+ tool_msg = {"role": "tool", "name": name, "context": _tool_ctx(name, args)}
+ # This is the display projection, so keep it faithful. `context`
+ # is an 80-char preview for collapsed row titles. A renderer that
+ # shows the full call (the expanded `$` transcript in the desktop)
+ # rebuilds it from args. When only the preview shipped, that
+ # truncation was permanent.
+ if args:
+ tool_msg["args"] = args
+ messages.append(tool_msg)
+ continue
+ # An assistant turn may carry only reasoning/thinking content with no
+ # visible text (extended-thinking turns, thinking-only recovery
+ # responses). Such a turn is persisted with its reasoning fields and is
+ # recallable from the transcript, but dropping it here as "empty" makes
+ # it vanish from the resumed/reloaded session view while the desktop's
+ # reasoning disclosure has nothing to render. Keep it when it carries
+ # reasoning so the "Thinking…" block still shows. (#44022)
+ reasoning_keys = (
+ "reasoning",
+ "reasoning_content",
+ "reasoning_details",
+ "codex_reasoning_items",
+ )
+ has_reasoning = role == "assistant" and any(
+ m.get(key) for key in reasoning_keys
+ )
+ if not content_text.strip() and not has_reasoning:
+ continue
+ msg = {"role": role, "text": content_text}
+ # Persisted authoring time (Unix seconds) for display.timestamps
+ # renderers (#41531). Display-only: never fed back into model context.
+ ts = m.get("timestamp")
+ if isinstance(ts, (int, float)) and ts > 0:
+ msg["timestamp"] = float(ts)
+ # Durable row identity, stamped by _rows_to_conversation. The renderer's
+ # own message ids are ephemeral (timestamp+index derived, and a
+ # different shape for live vs rehydrated vs optimistic rows), so
+ # anything that addresses a specific persisted message later — message
+ # reactions — needs this instead.
+ if m.get("_row_id") is not None:
+ msg["row_id"] = m["_row_id"]
+ if role == "user":
+ invocation = _skill_scaffold_projection(content_text)
+ if invocation:
+ # Show the invocation, never the expanded skill body. The raw
+ # payload stays server-side: a rewind/regenerate re-sends the
+ # turn by ordinal, so no client needs it.
+ msg["text"] = invocation
+ msg["display_kind"] = "skill_invocation"
+ if role == "assistant":
+ for key in reasoning_keys:
+ if key in m and m.get(key) is not None:
+ msg[key] = m.get(key)
+ # Forward display-only timeline metadata so the TUI can render
+ # model switches and delegation completions as events instead of
+ # opaque user messages, and hide compaction handoffs entirely.
+ display_kind = m.get("display_kind") or _legacy_display_kind(role, content_text)
+ if display_kind:
+ msg["display_kind"] = display_kind
+ if m.get("display_metadata"):
+ msg["display_metadata"] = m["display_metadata"]
+ messages.append(msg)
+
+ return messages
+
+
+def _coerce_seed_history(value: Any) -> list[dict]:
+ if not isinstance(value, list):
+ return []
+
+ history = []
+ for item in value:
+ if not isinstance(item, dict):
+ continue
+
+ role = item.get("role")
+ if role not in ("user", "assistant", "system"):
+ continue
+
+ content = item.get("content")
+ if content is None:
+ content = item.get("text")
+ if not isinstance(content, str) or not content.strip():
+ continue
+
+ history.append({"role": role, "content": content})
+
+ return history
+
+
+def _inflight_text(value: Any) -> str:
+ return _content_display_text(value).strip()
+
+
+def _start_inflight_turn(session: dict, text: Any) -> None:
+ now = time.time()
+ session["inflight_turn"] = {
+ "assistant": "",
+ "started_at": now,
+ "streaming": True,
+ "updated_at": now,
+ "user": _inflight_text(text),
+ }
+
+
+def _append_inflight_delta(session: dict, delta: Any) -> None:
+ text = "" if delta is None else str(delta)
+ if not text:
+ return
+ turn = session.get("inflight_turn")
+ if not isinstance(turn, dict):
+ turn = {"assistant": "", "streaming": True, "user": ""}
+ turn["assistant"] = f"{turn.get('assistant') or ''}{text}"
+ turn["streaming"] = True
+ turn["updated_at"] = time.time()
+ session["inflight_turn"] = turn
+
+
+def _record_inflight_correction(session: dict, text: Any) -> None:
+ """Record an accepted mid-turn correction on the live turn.
+
+ The correction is appended, never written over ``user``: a resuming client
+ must be able to rebuild BOTH bubbles. Overwriting the slot erased the
+ prompt that started the turn from the only snapshot resume can read, so a
+ reconnect (or a dev hot-reload that wipes the renderer cache) repainted the
+ thread with the user's original message missing.
+ """
+ correction = _inflight_text(text)
+ if not correction:
+ return
+ turn = session.get("inflight_turn")
+ if not isinstance(turn, dict):
+ return
+ turn = dict(turn)
+ corrections = list(turn.get("corrections") or [])
+ corrections.append(correction)
+ turn["corrections"] = corrections
+ # Arrival-order boundary: how much assistant text had already streamed
+ # when this correction was accepted. Resuming clients use it to place the
+ # correction bubble AFTER the output the user had already seen and BEFORE
+ # the output it redirected (#73793) instead of above the whole reply.
+ offsets = list(turn.get("correction_offsets") or [])
+ offsets.append(len(str(turn.get("assistant") or "")))
+ turn["correction_offsets"] = offsets
+ turn["updated_at"] = time.time()
+ session["inflight_turn"] = turn
+
+
+def _clear_inflight_turn(session: dict) -> None:
+ session["inflight_turn"] = None
+
+
+def _fail_inflight_turn(
+ session: dict, error: Any, error_surface: Optional[dict] = None
+) -> None:
+ """Mark the in-flight turn terminal-error but keep it replayable.
+
+ Normal completion clears ``inflight_turn`` because the response is now in
+ canonical history. Failures are different: the terminal frame can be lost
+ on a WS disconnect, and the failed turn may never have been committed.
+ Retaining a compact error snapshot lets ``session.resume`` replay the
+ user's prompt, any partial assistant text, and the error itself instead of
+ leaving the client stranded on a spinner or hydrating from stale DB state.
+ The snapshot lives until the next turn starts (``_start_inflight_turn``
+ overwrites it) or the session closes.
+
+ Caller must hold ``session["history_lock"]``.
+ """
+ message = str(error) if not isinstance(error, BaseException) else (str(error) or type(error).__name__)
+ now = time.time()
+ turn = session.get("inflight_turn")
+ if not isinstance(turn, dict):
+ turn = {"assistant": "", "user": "", "started_at": now}
+ turn["assistant"] = str(turn.get("assistant") or "")
+ turn["user"] = str(turn.get("user") or "")
+ turn["error"] = message or "turn failed"
+ turn["status"] = "error"
+ turn["recoverable"] = True
+ if error_surface:
+ # Structured {layer, code, retryable} descriptor — replayed to
+ # resuming clients via the resume snapshot so a reconnect renders the
+ # same layered error card the live frame carried.
+ turn["error_surface"] = dict(error_surface)
+ else:
+ turn.pop("error_surface", None)
+ turn["streaming"] = False
+ turn["updated_at"] = now
+ session["inflight_turn"] = turn
+
+
+_TURN_FAILURE_DETAIL_LIMIT = 240
+# Shortest run of the submitted prompt that counts as the provider quoting it
+# back. Long enough that shared boilerplate ("Invalid request for model ") does
+# not trip it, short enough to catch a quoted sentence.
+_TURN_PROMPT_ECHO_WINDOW = 24
+# Ceiling on the prompt we shingle. An @-expanded prompt can carry a whole
+# file; the failure path must stay cheap.
+_TURN_PROMPT_ECHO_MAX_PROMPT = 65536
+
+
+def _strip_prompt_echo(message: str, prompt: Any) -> str:
+ """Blank runs of the submitted prompt that ``message`` quotes back.
+
+ Secret redaction and prompt omission are different contracts, and only the
+ first one is pattern-based. A provider 4xx that echoes the request carries
+ ordinary private prose -- a paragraph about a person, a pasted file from an
+ ``@`` reference -- that matches no credential pattern and would otherwise
+ reach the log intact. This closes that path directly: anything the message
+ shares with the prompt for ``_TURN_PROMPT_ECHO_WINDOW`` characters or more
+ becomes ``<prompt>``.
+
+ Shingle-set matching, not a diff: cost is linear in both strings, which
+ matters because this runs on every failed turn and an ``@`` reference can
+ make the prompt arbitrarily long. The JSON-escaped form of the prompt is
+ shingled too, since a provider that hands back its own request body often
+ hands it back escaped.
+
+ Verbatim echo is what this stops. A paraphrase, a re-encoding (base64, a
+ different unicode normalization) or a summary of the prompt would survive,
+ so this is a floor and not a proof; the guarantee it does give is that the
+ prompt cannot reach the record by being quoted.
+ """
+ if not message or not prompt:
+ return message
+ needle = " ".join(str(prompt).split())[:_TURN_PROMPT_ECHO_MAX_PROMPT]
+ window = _TURN_PROMPT_ECHO_WINDOW
+ if len(needle) < window or len(message) < window:
+ return message
+ shingles = {needle[i:i + window] for i in range(len(needle) - window + 1)}
+ try:
+ escaped = json.dumps(needle)[1:-1]
+ except Exception:
+ escaped = ""
+ if escaped and escaped != needle:
+ shingles.update(
+ escaped[i:i + window] for i in range(len(escaped) - window + 1)
+ )
+ out: list[str] = []
+ i = 0
+ n = len(message)
+ while i <= n - window:
+ if message[i:i + window] in shingles:
+ j = i + window
+ while j < n and message[j - window + 1:j + 1] in shingles:
+ j += 1
+ out.append("<prompt>")
+ i = j
+ else:
+ out.append(message[i])
+ i += 1
+ out.append(message[i:])
+ return "".join(out)
+
+
+def _turn_failure_detail(error: Any, reason: Any = None, prompt: Any = None) -> str:
+ """Render why a turn failed, for the ``tui turn finished`` bookend.
+
+ Returns ``""`` when there is nothing to say, otherwise a fragment that
+ already carries its own leading space, so the caller can append it to the
+ record unconditionally.
+
+ #86865 added the bookend to trace compression rotations, so it logs
+ identities and a coarse ``status`` and deliberately logs no content.
+ #89117 is what the missing cause costs: a report consisting of two lines
+ reading ``status=error error_retained=True duration=0.9s`` with no way to
+ tell a provider 4xx from a budget wall from a crashed finalizer. The
+ returned-error path -- the one a 0.9 s failure almost always takes --
+ emits no other log line at all; only the exception path prints to stderr,
+ which is why the quiet failures are the ones that get filed.
+
+ Content discipline follows #86865's, and it takes two separate steps
+ because it is two separate contracts. ``redact_sensitive_text`` removes
+ credentials, which are pattern-shaped. It does nothing about a 4xx body
+ that quotes the request back, because ordinary private prose is not
+ pattern-shaped -- so ``_strip_prompt_echo`` removes that separately, using
+ the submitted ``prompt`` itself as the thing to look for. The invariant the
+ two of them keep is: this record may gain failure classification and
+ provider detail, and may not newly persist the user's own content.
+
+ ``prompt`` is optional so the helper stays callable from a path that has no
+ prompt in scope, but the turn paths always pass it; without it, only the
+ secret contract is enforced.
+ """
+ reason_text = str(reason or "").strip()
+ message = str(error or "").strip()
+ if isinstance(error, BaseException):
+ message = message or type(error).__name__
+ if not message and not reason_text:
+ return ""
+ try:
+ from agent.redact import redact_sensitive_text
+
+ message = redact_sensitive_text(message, force=True)
+ except Exception:
+ # A redactor that cannot run must not be able to leak the raw
+ # message into the log by failing open.
+ message = "<unredactable>"
+ message = " ".join(message.split())
+ # After the collapse, so both sides are compared in the same shape, and
+ # before the truncation, so a quote that starts inside the kept prefix
+ # cannot survive by being cut mid-run.
+ message = _strip_prompt_echo(message, prompt)
+ if len(message) > _TURN_FAILURE_DETAIL_LIMIT:
+ message = message[:_TURN_FAILURE_DETAIL_LIMIT] + "\u2026"
+ out = ""
+ if reason_text:
+ out += " failure_reason=%s" % " ".join(reason_text.split())
+ if message:
+ out += " cause=%r" % message
+ return out
+
+
+def register(server) -> None:
+ """Publish this module's helpers + handlers onto ``server``, rebound to its globals."""
+ bind_module(globals(), server, skip=("_",))