The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tui_gateway): inline single-use turn phases, merge truncation persist, WHY-only docstrings in prompt modules
Teknium1fe670403e87
diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.pyindex 9e5b488854d..f052258f3c5 100644--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@ -28,20 +28,15 @@ def _message_row_id(msg: dict):raw = msg.get("_row_id")if raw is None:raw = msg.get("row_id")- try:+ with contextlib.suppress(TypeError, ValueError):return None if raw is None else int(raw)- except (TypeError, ValueError):- return None+ return Nonedef _mem_db_pair_agrees(mem, db_msg) -> bool:- """True when a live-memory entry plausibly corresponds to a durable row.-- Positional trust needs more than equal lengths: roles and display-marker status- must match (a marker on one side shifts every later position), and an addressable- user turn must show the same text. Multimodal content can't be compared cheaply —- role/marker agreement suffices.- """+ """True when a live-memory entry plausibly corresponds to a durable row: roles and+ display-marker status must match (a marker shifts every later position) and an+ addressable user turn must show the same text (multimodal: role/marker suffice)."""if not isinstance(mem, dict) or not isinstance(db_msg, dict):return Falseif mem.get("role") != db_msg.get("role"):@@ -92,22 +87,17 @@ def _load_durable_truncation_history(def _resolve_truncate_row_id(session: dict, history: list, target_row_id: int):- """Resolve ``truncate_before_row_id`` to ``(user_ordinal, history_index)``.-- Prefer in-memory ``_row_id``/``row_id`` stamps; when a live turn rewrote- ``session["history"]`` without them, load the durable transcript and map the matched- user-turn ordinal onto the live list. Never falls back to a client-supplied- ordinal — unknown row ids refuse.- """+ """Resolve ``truncate_before_row_id`` to ``(user_ordinal, history_index)``: in-memory+ stamps first, else the durable transcript mapped onto the live list by user ordinal.+ Never falls back to a client-supplied ordinal — unknown row ids refuse."""if (hit := _find_user_turn_by_row_id(history, target_row_id)) is not None:return hitdb_history = _load_durable_truncation_history(session)if db_history is None:return None- # Heal missing stamps only when EVERY pair agrees (all-or-nothing): the durable copy- # is alternation-repaired (may merge/drop rows) while the live list can carry- # optimistic/marker rows; a stamp on a misaligned pair is sticky and re-aims every- # later rewind at the wrong durable row.+ # Heal missing stamps only when EVERY pair agrees: the durable copy is alternation-+ # repaired while the live list can carry optimistic/marker rows, and a stamp on a+ # misaligned pair is sticky (re-aims every later rewind at the wrong durable row).if len(db_history) == len(history) and all(_mem_db_pair_agrees(mem, db_msg) for mem, db_msg in zip(history, db_history)):for mem, db_msg in zip(history, db_history):@@ -119,9 +109,8 @@ def _resolve_truncate_row_id(session: dict, history: list, target_row_id: int):return Nonedb_ord, db_idx = db_hitmem_user_indices = _history_user_indices(history)- # Same-ordinal mapping across lists that can diverge (repair may have merged a- # user;user pair): trust it only when the mapped live turn shows the same content as- # the durable target — else refuse (caller fails closed, 4018).+ # Same-ordinal mapping across lists that can diverge (repair may merge a user;user+ # pair): trust it only when the mapped live turn shows the durable target's content.if db_ord >= len(mem_user_indices) or not _mem_db_pair_agrees(history[mem_user_indices[db_ord]], db_history[db_idx]):return None@@ -137,40 +126,9 @@ def _coerce_truncate_int(rid, value, param_name="truncate_before_user_ordinal"):return None, _err(rid, 4004, f"{param_name} must be an integer")-def _reconcile_client_ordinal(- rid, sid, client_ordinal, msg_ordinal, param_name, target_repr, prefix_user_count=0):- """Cross-check a client ordinal against a resolved durable target.-- Returns ``(ordinal, error_response)``: the target's tip-relative ordinal when the- client sent none or agreed, else the 4004/4030 refusal — a stale ordinal beside a- *resolved* durable id is drift; never guess which the user meant. Client ordinals- count the full displayed lineage, so after compression ``msg_ordinal +- prefix_user_count`` is the SAME turn. The cut is always aimed by the durable- target, so this can never re-aim a truncation.- """- if client_ordinal is None:- return msg_ordinal, None- ordinal, err = _coerce_truncate_int(rid, client_ordinal)- if err is not None:- return None, err- if ordinal == msg_ordinal or (- prefix_user_count > 0 and ordinal == msg_ordinal + prefix_user_count):- return msg_ordinal, None- logger.warning(- "prompt.submit: REFUSED truncation due to ordinal mismatch for session %s "- "(ordinal=%d, %s_ordinal=%d, %s=%s, prefix_user_count=%d). "- "Stale truncate_before_user_ordinal detected.",- sid, ordinal, param_name, msg_ordinal, param_name, target_repr, prefix_user_count)- return None, _err(- rid, 4030,- f"truncate_before_user_ordinal ({ordinal}) does not match "- f"{param_name} target turn ({msg_ordinal})")--def _pending_reaction_notes(session: dict) -> str:- """Note block for reactions added since the last turn, or "". Applied to the MODEL- INPUT only, never the persisted prompt; each reaction is announced once (rows are- stamped ``seen`` on read). Feature-gated (display.message_reactions)."""+ """Note block for reactions since the last turn (model input only, announced once —+ rows are stamped ``seen`` on read), or "". Gated on display.message_reactions."""session_key = str(session.get("session_key") or "")if not session_key:return ""@@ -182,9 +140,7 @@ def _pending_reaction_notes(session: dict) -> str:return ""try:with _session_db(session) as db:- if db is None:- return ""- pending = db.take_unseen_reactions(session_key, author="user")+ pending = None if db is None else db.take_unseen_reactions(session_key, author="user")except Exception:logger.debug("Failed to read pending reactions", exc_info=True)return ""@@ -207,17 +163,15 @@ def _pending_reaction_notes(session: dict) -> str:def _typed_stop_phrase_response(rid, text):- """End the voice chat when a bare stop phrase is TYPED while backend voice mode is on- (typed twin of the spoken stop phrase). Returns the RPC reply, or None for a normal- message. The desktop's renderer-owned voice chat handles its own typed stop."""+ """RPC reply ending the voice chat when a bare stop phrase is TYPED while backend voice+ mode is on (typed twin of the spoken stop phrase), or None for a normal message."""if not (isinstance(text, str) and _voice_mode_enabled()):return Nonetry:from tools.voice_mode import is_voice_stop_phrase- typed_stop = is_voice_stop_phrase(text)+ if not is_voice_stop_phrase(text):+ return Noneexcept Exception:- typed_stop = False- if not typed_stop:return None_end_voice_chat(stop_loop=True, stop_tts=True)_voice_emit("voice.transcript", {"stop_phrase": True, "typed": True})@@ -244,13 +198,11 @@ def _hosted_submit_error(rid, session, hosted_task, hosted_terminal_callback):def _legacy_group_fence_error(rid, session, params):- """Older Desktop builds know the ``Group: <room-id>`` title but not the hosted- authority marker; once a gateway owns that room a direct prompt would start a second- renderer driver. Fence server-side instead of trusting the client."""+ """Fence direct prompts into a hosted room from older Desktop builds (they know the+ ``Group: <room-id>`` title but not the authority marker; a direct prompt would start a+ second renderer driver)."""title = str(session.get("title") or "")- if not title.startswith("Group: "):- return None- room_id = title.removeprefix("Group: ").strip()+ room_id = title.removeprefix("Group: ").strip() if title.startswith("Group: ") else ""if not room_id:return Nonetry:@@ -284,31 +236,25 @@ def _legacy_group_fence_error(rid, session, params):def _parse_truncation_params(rid, sid, session, params, history):"""Coerce + admit the truncation params; ``(target_row_id, client_ordinal, err)``.-- Precedence: malformed params (4004) -> unconfirmed (4029, checked BEFORE target- resolution so a leaked-state request never pays the durable read or heal-stamps live- dicts). An ordinal/id alone is not consent: a leftover ordinal on an ORDINARY submit- is indistinguishable from a real rewind, and the cut is a destructive replace_messages().- """- truncate_user_ordinal = params.get("truncate_before_user_ordinal")- truncate_row_id = params.get("truncate_before_row_id")+ Malformed (4004) -> unconfirmed (4029; checked BEFORE target resolution so a+ leaked-state request never pays the durable read or heal-stamps live dicts). An+ ordinal/id alone is not consent: a leftover ordinal on an ORDINARY submit is+ indistinguishable from a real rewind, and the cut is a destructive replace."""target_row_id = client_ordinal = None- if truncate_row_id is not None:+ if (truncate_row_id := params.get("truncate_before_row_id")) is not None:target_row_id, err = _coerce_truncate_int(rid, truncate_row_id, "truncate_before_row_id")if err is not None:return None, None, err- if truncate_user_ordinal is not None:+ if (truncate_user_ordinal := params.get("truncate_before_user_ordinal")) is not None:client_ordinal, err = _coerce_truncate_int(rid, truncate_user_ordinal)if err is not None:return None, None, errif is_truthy_value(params.get("confirm_truncate")):return target_row_id, client_ordinal, Nonelogger.warning(- "prompt.submit: REFUSED unconfirmed truncation of session %s "- "(%d messages held; ordinal=%s, row_id=%s, message_id=%s). "- "The client attached truncation parameters without "- "confirm_truncate — likely stale truncation parameters on "- "an ordinary submit.",+ "prompt.submit: REFUSED unconfirmed truncation of session %s (%d messages held; "+ "ordinal=%s, row_id=%s, message_id=%s). The client attached truncation parameters without "+ "confirm_truncate — likely stale truncation parameters on an ordinary submit.",sid, len(history), client_ordinal, target_row_id, params.get("truncate_before_message_id"))return None, None, _err(rid, 4029,@@ -317,48 +263,22 @@ def _parse_truncation_params(rid, sid, session, params, history):"(update your Hermes client if a rewind was intended)")-def _ordinal_only_truncation_error(rid, sid, session, history, user_indices, client_ordinal):- """4004 refusal when an ordinal-only cut targets a durable session, else None.-- Durability is a state.db property, not an annotation on the live copy (resume paths- historically omitted _row_id stamps). An unreadable durable state fails closed too:- absence of proof is not proof of an ephemeral conversation.- """- has_stamped_user = any(_message_row_id(history[h_idx]) is not None for h_idx in user_indices)- durable_history = [] if has_stamped_user else _load_durable_truncation_history(session, sid)- if not (has_stamped_user or durable_history is None or durable_history):- return None- logger.warning(- "prompt.submit: REFUSED ordinal-only truncation of durable "- "session %s (ordinal=%d); truncate_before_row_id required",- sid, client_ordinal)- return _err(- rid, 4004,- "ordinal-only truncation is unsafe for durable session history; "- "include truncate_before_row_id")--def _resolve_truncation_ordinal(rid, sid, session, params, history):- """Resolve the truncation target to ``(ordinal, cut_index, err)``.-- After ``_parse_truncation_params``: unresolvable target (4018, fail closed — never- degrade a missing row_id/message_id into an ordinal cut) -> ordinal drift (4030) ->- ordinal-only on a durable session (4004).- """+ """Resolve the truncation target to ``(ordinal, cut_index, err)``: unresolvable target+ (4018, fail closed — never degrade a missing row_id/message_id into an ordinal cut) ->+ ordinal drift (4030) -> ordinal-only on a durable session (4004)."""target_row_id, client_ordinal, err = _parse_truncation_params(rid, sid, session, params, history)if err is not None:return None, None, errtruncate_message_id = params.get("truncate_before_message_id")- # Client ordinals count the full displayed lineage; after compression the tip is- # session["history"] and ancestors live in display_history_prefix. Count ancestor- # user turns once so client and tip-relative ordinals translate.+ # Client ordinals count the full displayed lineage; after compression ancestors live in+ # display_history_prefix, so count their user turns once to translate ordinals.prefix_user_count = len(_history_user_indices(session.get("display_history_prefix") or []))user_indices = _history_user_indices(history)def _stale(resolved_ordinal=None):- # Structured recovery fields: Desktop resyncs + retries on a stale target- # and shows "compressed away" when segment_ordinal < 0 (ancestor-only).+ # Recovery fields: Desktop resyncs + retries, "compressed away" when segment < 0.segment = (client_ordinal - prefix_user_count if client_ordinal is not None else resolved_ordinal)return None, None, _err(rid, 4018, _STALE_TARGET_MSG, data={@@ -383,21 +303,43 @@ def _resolve_truncation_ordinal(rid, sid, session, params, history):"prompt.submit: " + not_found + "; refusing truncation without fallback",target_repr, sid)return _stale()- ordinal, err = _reconcile_client_ordinal(- rid, sid, client_ordinal, found_match[0], param_name, target_repr,- prefix_user_count=prefix_user_count)- if err is not None:- return None, None, err+ ordinal = found_match[0]+ # A stale client ordinal beside a *resolved* durable id is drift — never guess+ # which the user meant. Client ordinals count the full displayed lineage, so+ # after compression ``ordinal + prefix_user_count`` is the SAME turn. The cut is+ # always aimed by the durable target, so this can never re-aim a truncation.+ if client_ordinal is not None and client_ordinal != ordinal and not (+ prefix_user_count > 0 and client_ordinal == ordinal + prefix_user_count):+ logger.warning(+ "prompt.submit: REFUSED truncation due to ordinal mismatch for session %s "+ "(ordinal=%d, %s_ordinal=%d, %s=%s, prefix_user_count=%d). "+ "Stale truncate_before_user_ordinal detected.",+ sid, client_ordinal, param_name, ordinal, param_name, target_repr,+ prefix_user_count)+ return None, None, _err(+ rid, 4030,+ f"truncate_before_user_ordinal ({client_ordinal}) does not match "+ f"{param_name} target turn ({ordinal})")else:ordinal = client_ordinal - prefix_user_countif ordinal < 0 or ordinal >= len(user_indices):return _stale()- err = _ordinal_only_truncation_error(- rid, sid, session, history, user_indices, client_ordinal)- if err is not None:- return None, None, err- # Reject out-of-range on BOTH ends: a negative ordinal would hit Python's negative- # indexing (user_indices[-1] -> the LAST user turn) and persist the loss.+ # Ordinal-only cut on a durable session: durability is a state.db property, not a+ # live-copy annotation (resume paths omitted _row_id stamps); an unreadable+ # durable state fails closed too.+ has_stamped_user = any(+ _message_row_id(history[h_idx]) is not None for h_idx in user_indices)+ durable = [] if has_stamped_user else _load_durable_truncation_history(session, sid)+ if has_stamped_user or durable is None or durable:+ logger.warning(+ "prompt.submit: REFUSED ordinal-only truncation of durable "+ "session %s (ordinal=%d); truncate_before_row_id required",+ sid, client_ordinal)+ return None, None, _err(+ rid, 4004,+ "ordinal-only truncation is unsafe for durable session history; "+ "include truncate_before_row_id")+ # BOTH ends: a negative ordinal would index user_indices[-1] and persist the loss.if ordinal < 0 or ordinal >= len(user_indices):return _stale(resolved_ordinal=ordinal)return ordinal, user_indices[ordinal], None@@ -407,54 +349,62 @@ def _row_ids_of(messages) -> set:return {row_id for message in messages if isinstance((row_id := _message_row_id(message)), int)}-def _persist_truncation(rid, sid, session, history, truncated, ordinal, requested_rebind_ids):- """Write the truncated transcript BEFORE touching memory (fail closed).-- If replace_messages failed after session["history"] was rewritten, the turn would run- against the short list while state.db kept the old tail, and the append-only flush- would stack the new exchange on the "undone" turns — zombie history on resume.- Writes through ``_session_db`` (owner of this session's row), never ``_get_db()``: a- profile session's transcript lives in its own profile's state.db. Returns- ``(err, survivor_fields)``; the fields are the client rowId-rebind payload.- """+def _truncate_history_for_submit(rid, sid, session, params, requested_rebind_ids):+ """Rewind/regenerate cut under ``history_lock``: ``(err, survivor_fields)``; the fields+ are the client rowId-rebind payload."""+ history = _history_without_ephemeral_scaffolding(session.get("history", []))+ ordinal, cut_index, err = _resolve_truncation_ordinal(rid, sid, session, params, history)+ if err is not None:+ return err, {}+ from agent.context_compressor import history_before_user_originated_turn+ truncated, _live_view = history_before_user_originated_turn(history, cut_index)+ # Second gate: ordinal 0 would DELETE every durable row; wiping needs its own opt-in.+ if not truncated and history and not is_truthy_value(params.get("confirm_empty_truncate")):+ logger.warning(+ "prompt.submit: REFUSED empty truncation of session %s "+ "(%d messages would be wiped; ordinal=%d).",+ sid, len(history), ordinal)+ return _err(+ rid, 4028,+ "truncation would erase the entire session transcript; "+ "resubmit with confirm_empty_truncate=true if this is intended"), {}+ log_fn = logger.warning if not truncated else logger.info+ log_fn(+ "prompt.submit: truncating session %s history %d -> %d messages (ordinal=%d)",+ sid, len(history), len(truncated), ordinal)+ # Write the truncated transcript BEFORE touching memory (fail closed: a failed write+ # after the in-memory rewrite would stack the new exchange on the "undone" turns).+ # Writes through _session_db (profile sessions own their state.db).fields = {}with _session_db(session) as db:if db is not None:try:- # session_key can be NULL for old CLI-origin sessions; fall back to- # sid or replace_messages(None) trips an FK violation.+ # NULL session_key (old CLI-origin sessions) would trip an FK violation.truncation_key = session.get("session_key") or sidold_active_row_ids = _row_ids_of(history)if requested_rebind_ids is not None:- # Row-id fallback can resolve a target the live list is too misaligned- # to stamp, and repair can merge a user;user pair: read the un-repaired- # pre-write active-id set so a rewritten row is never mistaken for an- # untouched archived/ancestor row.+ # Un-repaired pre-write active-id set: a rewritten row must never be+ # mistaken for an untouched archived/ancestor row.durable_rebind_history = _load_durable_truncation_history(session, truncation_key, repair_alternation=False)if durable_rebind_history is None:raise RuntimeError("could not load durable row identities for truncation")old_active_row_ids.update(_row_ids_of(durable_rebind_history))old_survivor_row_ids = [_message_row_id(message) for message in truncated]- # active_only=True: compaction keeps the pre-compaction transcript as- # active=0 rows under this key; a bare replace would DELETE that archive on- # every edit. archive_dropped=True: soft-archive the dropped turns- # (active=0, still in FTS) so a mis-aimed cut is recoverable.+ # active_only: a bare replace would DELETE the compaction archive (active=0+ # rows) on every edit. archive_dropped: a mis-aimed cut stays recoverable.db.replace_messages(truncation_key, truncated, active_only=True, archive_dropped=True,reject_active_turn_lease=True)except Exception as exc:logger.error(- "prompt.submit: replace_messages failed for session %s "- "(ordinal=%d); refusing turn so memory and DB stay "- "aligned: %s",+ "prompt.submit: replace_messages failed for session %s (ordinal=%d); refusing "+ "turn so memory and DB stay aligned: %s",sid, ordinal, exc, exc_info=True)- return _err(rid, 5008, f"failed to persist history truncation: {exc}"), fields- # replace_messages re-inserted the survivors as NEW rows with fresh _row_id- # stamps. Surface the surviving user-turn ids (visible-user-ordinal order) so- # the client rebinds its cached rowIds — else a second rewind sends the- # pre-rewind id and the resolver refuses with 4018. None entries: the client- # must drop its cached id for that turn.+ return _err(rid, 5008, f"failed to persist history truncation: {exc}"), {}+ # Survivors were re-inserted as NEW rows: surface the fresh ids so the client+ # rebinds its cached rowIds (else a second rewind refuses with 4018). None+ # entries: the client must drop its cached id for that turn.if requested_rebind_ids is None:fields["survivor_user_row_ids"] = [_message_row_id(truncated[i]) for i in _history_user_indices(truncated)]@@ -467,48 +417,14 @@ def _persist_truncation(rid, sid, session, history, truncated, ordinal, requesteand old_row_id in requested_rebind_ids}for dropped_row_id in requested_rebind_ids.intersection(old_active_row_ids):row_id_map.setdefault(str(dropped_row_id), None)- return None, fields---def _truncate_history_for_submit(rid, sid, session, params, requested_rebind_ids):- """Rewind/regenerate cut, under ``history_lock``. Returns ``(err, survivor_fields)``;- on success ``session["history"]`` is replaced and ``history_version`` bumped."""- history = _history_without_ephemeral_scaffolding(session.get("history", []))- ordinal, cut_index, err = _resolve_truncation_ordinal(rid, sid, session, params, history)- if err is not None:- return err, {}- from agent.context_compressor import history_before_user_originated_turn- truncated, _live_view = history_before_user_originated_turn(history, cut_index)- # Second gate on top of confirm_truncate: ordinal 0 -> history[:0] == [] and- # replace_messages() DELETEs every durable row. Wiping the whole transcript needs- # its own opt-in (legitimate restore/regenerate of the first turn).- if not truncated and history and not is_truthy_value(params.get("confirm_empty_truncate")):- logger.warning(- "prompt.submit: REFUSED empty truncation of session %s "- "(%d messages would be wiped; ordinal=%d).",- sid, len(history), ordinal)- return _err(- rid, 4028,- "truncation would erase the entire session transcript; "- "resubmit with confirm_empty_truncate=true if this is intended"), {}- log_fn = logger.warning if not truncated else logger.info- log_fn(- "prompt.submit: truncating session %s history %d -> %d messages (ordinal=%d)",- sid, len(history), len(truncated), ordinal)- err, fields = _persist_truncation(- rid, sid, session, history, truncated, ordinal, requested_rebind_ids)- if err is not None:- return err, {}session["history"] = truncatedsession["history_version"] = int(session.get("history_version", 0)) + 1return None, fieldsdef _persist_session_row_for_submit(rid, session):- """Lazily persist the DB row now that the user actually sent a message; a branch- becomes real here (parent transcript copied as its seed). Returns an error reply (the- only user-visible signal; desktop maps it to a toast) or None. On failure the- in-flight turn is released."""+ """Lazily persist the DB row now that the user sent a message (a branch becomes real+ here); the error reply is the only user-visible signal (desktop maps it to a toast)."""try:if _ensure_session_db_row(session) is False:return _err(@@ -526,21 +442,19 @@ def _persist_session_row_for_submit(rid, session):if is_disk_full_error(exc):return _err(rid, 5070,- "disk full: session storage could not be written — free some disk space and try again",- )+ "disk full: session storage could not be written — free some disk space and try again")logger.warning("prompt.submit: session persist failed: %s", exc, exc_info=True)return _err(rid, 5071, f"session storage could not be written: {exc}")return Nonedef _run_after_agent_ready(rid, sid, session, text, display_kind, hosted_terminal_callback):- """Turn thread body: patient wait for a deferred build (the message is already the- accepted in-flight turn, so a slow build must not eat it), then run."""+ """Turn thread body: patient wait for a deferred build (a slow build must not eat the+ accepted in-flight message), then run."""err = _wait_agent_for_prompt(session, rid, sid)if err:- # Terminal frame + retained snapshot (not a bare "error" event): if the client is- # disconnected, the snapshot is the only way resume shows this. Construction- # never reached the provider: local-runtime failure.+ # Terminal frame + retained snapshot (not a bare "error" event): the snapshot is+ # the only way resume shows this to a disconnected client._emit_terminal_turn_error(sid, session, (err.get("error") or {}).get("message", "agent initialization failed"),error_surface={"layer": "runtime", "code": "agent_init_failed", "retryable": True})@@ -553,8 +467,7 @@ def _run_after_agent_ready(rid, sid, session, text, display_kind, hosted_terminaif session.get("_turn_cancel_requested") or not session.get("running"):session["running"] = False_clear_inflight_turn(session)- # Without this emit the turn vanishes silently: the client saw- # {"status": "streaming"} but never gets message.start or error.+ # Without this emit the turn vanishes silently after {"status": "streaming"}._emit("error", sid, {"message": "Turn cancelled before the agent was ready"if session.get("_turn_cancel_requested")@@ -569,45 +482,20 @@ _TRUNCATION_PARAMS = ("truncate_before_user_ordinal", "truncate_before_row_id", "truncate_before_message_id")-def _claim_submit_slot(rid, sid, session, text, params, transport, internal_hosted_submit):- """Claim the turn against a possibly-running session; returns an early RPC reply- (busy/queued) or None once ``running`` is observed False.-- A mid-turn prompt is queued (by default interrupting the live turn) instead of- rejected. The provider interrupt happens after ``history_lock`` is released: a- non-interruptible tool may hold it. If the old turn finished between the two lock- acquisitions, retry the claim rather than strand this prompt in a queue whose drain- already ran.- """- while True:- with session["history_lock"]:- if not session.get("running"):- return None- if internal_hosted_submit:- return _err(rid, 4091, "hosted room member session is busy")- busy_transport = transport or session.get("transport")- busy_response = _handle_busy_submit(- rid, sid, session, text, busy_transport, queued=bool(params.get("queued")))- if busy_response is not None:- return busy_response--def _lock_in_submit_turn(rid, sid, session, text, params, has_truncation, requested_rebind_ids, hosted_task):- """Under ``history_lock``: refuse watch-child races and malformed truncation, apply- the cut, then mark the turn running + in flight. Returns ``(err, survivor_fields)``."""+ """Under ``history_lock``: refuse watch-child races / malformed truncation, apply the+ cut, mark the turn running + in flight. Returns ``(err, survivor_fields)``."""fields = {}with session["history_lock"]:- # A watch session's run lives in the PARENT turn, so its own running flag is- # False; typing mid-run would build a second agent racing the child on the same- # stored session. After the run completes, submitting is fine.+ # A watch session's run lives in the PARENT turn (own running flag False); typing+ # mid-run would build a second agent racing the child on the same stored session.if session.get("lazy") and _child_run_active(str(session.get("session_key") or "")):return _err(rid, 4009, "subagent still running — wait for it to finish"), fieldsif is_truthy_value(params.get("confirm_truncate")) and not has_truncation:return _err(rid, 4004,- "confirm_truncate requires truncate_before_user_ordinal, truncate_before_message_id, or truncate_before_row_id",- ), fields+ "confirm_truncate requires truncate_before_user_ordinal, truncate_before_message_id, or truncate_before_row_id"), fieldsif has_truncation:err, fields = _truncate_history_for_submit(rid, sid, session, params, requested_rebind_ids)@@ -628,14 +516,13 @@ def _(rid, params: dict) -> dict:sid = params.get("session_id", "")raw_text = params.get("text", "")text = sanitize_user_prompt_text(raw_text) if isinstance(raw_text, str) else raw_text- # Off-screen sends (widget intents) type the persisted row so no client- # renders a bubble. Whitelisted to "hidden": this RPC must not mint kinds.+ # Off-screen sends (widget intents) type the row so no client renders a bubble;+ # whitelisted to "hidden" — this RPC must not mint kinds.display_kind = "hidden" if params.get("display_kind") == "hidden" else Noneif (stopped := _typed_stop_phrase_response(rid, text)) is not None:return stoppedif params.get("interrupted"):- # Client-side barge-in (desktop VAD / typing over playback): latch it so- # this turn's model message carries the interruption note.+ # Client-side barge-in: latch so this turn's model message carries the note.from tools.tts_streaming import mark_speech_interruptedmark_speech_interrupted()session, err = _sess_nowait(params, rid)@@ -644,42 +531,49 @@ def _(rid, params: dict) -> dict:hosted_task = params.get("_hosted_task")hosted_terminal_callback = params.get("_hosted_terminal_callback")internal_hosted_submit = hosted_task is not None or hosted_terminal_callback is not None- if internal_hosted_submit:- err = _hosted_submit_error(rid, session, hosted_task, hosted_terminal_callback)- else:- err = _legacy_group_fence_error(rid, session, params)+ err = (+ _hosted_submit_error(rid, session, hosted_task, hosted_terminal_callback)+ if internal_hosted_submit else _legacy_group_fence_error(rid, session, params))if err is not None:return errif (limit_message := _ensure_active_session_slot(sid, session)) is not None:- # Refused HERE — before the busy queue, _ensure_session_db_row and- # _start_agent_build — so a refusal leaves the session exactly as it was.- # The reason travels as machine-readable data ("at capacity, retry" vs- # "live owner, your write would interleave"), never as matched prose.+ # Refused HERE — before the busy queue, db row and agent build — so a refusal+ # leaves the session untouched. The reason travels as machine-readable data.reason = getattr(limit_message, "reason", None)return _err(rid, 4090, str(limit_message), {"reason": reason} if reason else None)- # Rewritten on every submit: one session can be driven from the app window- # and the HUD in turn, and a stale "hud" misinforms the model.+ # Rewritten every submit: a session alternates app window / HUD; stale "hud" misinforms.session["client_surface"] = "hud" if params.get("surface") == "hud" else ""has_truncation = any(params.get(k) is not None for k in _TRUNCATION_PARAMS)if has_truncation and isinstance(text, str):- # A rewind replays what the transcript shows; a skill turn shows its- # invocation, so re-expand it or `/work fix it` sends nine literal chars.+ # A rewind replays what the transcript shows: re-expand a skill invocation or+ # `/work fix it` sends nine literal chars.text = _expand_skill_invocation_for_replay(text, str(session.get("session_key") or ""))turn_isolation = _session_uses_compute_host(session, _load_dashboard_process_isolation_config())if internal_hosted_submit and turn_isolation:return _err(rid, 4121, "hosted room turns do not support isolated compute workers yet")- # Re-bind to the current client transport so streaming stays on the active- # websocket even if a disconnect/fallback moved the session to stdio.+ # Re-bind to the current transport: streaming must stay on the active websocket even+ # if a disconnect/fallback moved the session to stdio.if (t := current_transport()) is not None:session["transport"] = t- busy = _claim_submit_slot(rid, sid, session, text, params, t, internal_hosted_submit)- if busy is not None:- return busy+ # Claim the turn against a possibly-running session (busy/queued reply, else fall+ # through once ``running`` is observed False). The provider interrupt happens after+ # history_lock is released (a non-interruptible tool may hold it); if the old turn+ # finished between the two acquisitions, retry the claim rather than strand this+ # prompt in a queue whose drain already ran.+ while True:+ with session["history_lock"]:+ if not session.get("running"):+ break+ if internal_hosted_submit:+ return _err(rid, 4091, "hosted room member session is busy")+ busy_transport = t or session.get("transport")+ busy_response = _handle_busy_submit(+ rid, sid, session, text, busy_transport, queued=bool(params.get("queued")))+ if busy_response is not None:+ return busy_responseraw_rebind_ids = params.get("rebind_survivor_row_ids")requested_rebind_ids = (- {- row_id for row_id in raw_rebind_ids- if isinstance(row_id, int) and not isinstance(row_id, bool)}+ {r for r in raw_rebind_ids if isinstance(r, int) and not isinstance(r, bool)}if isinstance(raw_rebind_ids, list) else None)err, survivor_fields = _lock_in_submit_turn(rid, sid, session, text, params, has_truncation, requested_rebind_ids, hosted_task)@@ -697,8 +591,7 @@ def _(rid, params: dict) -> dict:isolated_response["error"].get("message", "unknown error"))if (err := _persist_session_row_for_submit(rid, session)) is not None:return err- # A completed FAILED build must not wedge the session: rebuild with fresh- # provider resolution instead of replaying the cached failure forever.+ # A completed FAILED build must not wedge the session: rebuild, don't replay it.if not _restart_completed_failed_agent_build(sid, session, session.get("agent_ready")):_start_agent_build(sid, session)run_thread = threading.Thread(@@ -738,10 +631,9 @@ def _(rid, params: dict) -> dict:# Save-first (CLI keybinding parity): more robust than a has_image() precheck.if not save_clipboard_image(img_path):session["image_counter"] = max(0, session["image_counter"] - 1)- msg = (+ return _ok(rid, {"attached": False, "message": ("Clipboard has image but extraction failed" if has_clipboard_image()- else "No image found in clipboard")- return _ok(rid, {"attached": False, "message": msg})+ else "No image found in clipboard")})session.setdefault("attached_images", []).append(str(img_path))return _ok(rid, _attached_image_result(session, img_path))@@ -757,10 +649,8 @@ def _(rid, params: dict) -> dict:try:from cli import (_IMAGE_EXTENSIONS, _detect_file_drop, _resolve_attachment_path, _split_path_input)- dropped = _detect_file_drop(raw)- if dropped:- image_path = dropped["path"]- remainder = dropped["remainder"]+ if dropped := _detect_file_drop(raw):+ image_path, remainder = dropped["path"], dropped["remainder"]else:path_token, remainder = _split_path_input(raw)image_path = _resolve_attachment_path(path_token)@@ -778,10 +668,8 @@ def _(rid, params: dict) -> dict:@method("image.attach_bytes")def _(rid, params: dict) -> dict:- """Attach an image from base64 bytes (remote client: its file isn't on our disk).- Reply shape mirrors ``image.attach``. ``content_base64``/``data`` accept a- ``data:image/...;base64,`` prefix; ``filename``/``ext`` hint the extension, else- magic bytes decide (PNG/JPEG/GIF/WebP/BMP, fallback ``.png``)."""+ """Attach an image from base64 bytes (remote client); reply mirrors ``image.attach``.+ ``filename``/``ext`` hint the extension, else magic bytes decide (fallback ``.png``)."""session, err = _sess_building(params, rid)if err:return err@@ -827,22 +715,21 @@ def _pdf_attach_source(rid, params, td_path, raw_path, raw_b64):resolved = _resolve_attachment_path(raw_path)except Exception:resolved = None- if resolved is None or not Path(resolved).is_file():+ if resolved is None or not (pdf := Path(resolved)).is_file():return None, None, _err(rid, 4016, f"PDF not found: {raw_path}")- if Path(resolved).suffix.lower() != ".pdf":- return None, None, _err(rid, 4016, f"not a PDF: {Path(resolved).name}")- if Path(resolved).stat().st_size > _PDF_ATTACH_MAX_BYTES:+ if pdf.suffix.lower() != ".pdf":+ return None, None, _err(rid, 4016, f"not a PDF: {pdf.name}")+ if pdf.stat().st_size > _PDF_ATTACH_MAX_BYTES:mb = _PDF_ATTACH_MAX_BYTES // (1024 * 1024)return None, None, _err(rid, 4018, f"PDF too large; cap is {mb} MB")- return Path(resolved), Path(resolved).name, None+ return pdf, pdf.name, Nonedef _pdf_page_range(rid, params):"""Validate first/last page against the per-call cap: ``(first, last, err)``."""try:first_page = int(params.get("first_page") or 1)- last_page_param = params.get("last_page")- last_page = int(last_page_param) if last_page_param is not None else None+ last_page = None if params.get("last_page") is None else int(params.get("last_page"))except (TypeError, ValueError):return None, None, _err(rid, 4015, "first_page/last_page must be integers")if first_page < 1:@@ -859,9 +746,8 @@ def _pdf_page_range(rid, params):@method("pdf.attach")def _(rid, params: dict) -> dict:- """Attach a PDF by rendering each page to PNG (``pdftoppm`` @150 DPI, poppler-utils;- 5028 if missing) and queuing the pages as images. Accepts a host ``path`` or base64- ``content_base64``. Caps: 50 MB / 25 pages per call."""+ """Attach a PDF by rendering each page to PNG (``pdftoppm``; 5028 if missing) and+ queuing the pages as images. Host ``path`` or base64 ``content_base64``."""import shutilimport subprocessimport tempfile@@ -903,10 +789,7 @@ def _(rid, params: dict) -> dict:attached_pages = []for src in rendered:page_num = src.stem.split("-", 1)[-1]- try:- page_int = int(page_num)- except ValueError:- page_int = first_page + len(attached_pages)+ page_int = int(page_num) if page_num.isdigit() else first_page + len(attached_pages)dst = _queue_attached_image(session, src.read_bytes(), ".png", prefix=f"pdf_p{page_num}")attached_pages.append({"path": str(dst), "page": page_int, **_image_meta(dst)})@@ -918,10 +801,8 @@ def _(rid, params: dict) -> dict:@method("file.attach")def _(rid, params: dict) -> dict:- """Stage a non-image file into the session workspace and return a workspace-relative- ``@file:`` ref the agent's file tools can read. ``path`` is the client/host path- (naming + local resolution); ``data_url`` carries the bytes when the path isn't- visible to the gateway; ``name`` overrides the filename."""+ """Stage a non-image file into the session workspace; returns a workspace-relative+ ``@file:`` ref. ``data_url`` carries the bytes when ``path`` isn't gateway-visible."""session, err = _sess_building(params, rid)if err:return err@@ -950,8 +831,7 @@ def _(rid, params: dict) -> dict:raw = str(params.get("path", "") or "").strip()if not raw:return _err(rid, 4015, "path required")- images = session.setdefault("attached_images", [])- before = len(images)+ before = len(images := session.setdefault("attached_images", []))session["attached_images"] = [path for path in images if path != raw]return _ok(rid, {"detached": len(session["attached_images"]) != before,@@ -965,12 +845,10 @@ def _(rid, params: dict) -> dict:return errtry:from cli import _detect_file_drop- raw = str(params.get("text", "") or "")- dropped = _detect_file_drop(raw)+ dropped = _detect_file_drop(str(params.get("text", "") or ""))if not dropped:return _ok(rid, {"matched": False})- drop_path = dropped["path"]- remainder = dropped["remainder"]+ drop_path, remainder = dropped["path"], dropped["remainder"]if dropped["is_image"]:session.setdefault("attached_images", []).append(str(drop_path))return _ok(rid, {@@ -995,12 +873,9 @@ def _final_response_text(result) -> str:def _spawn_side_agent(rid, session, task_id, parent, event, body, *, cwd="", extra=None, cleanup=None):- """Run ``body()`` (an ephemeral agent call) on a daemon thread under the session's- profile home and cwd; its text — or ``error: <exc>`` — lands on ``parent`` as- ``event`` with ``task_id`` (+ ``extra``). ``cleanup`` runs in the finally before the- session context is cleared. Replies ``{task_id}``. The HERMES_HOME ContextVar set- on the session-create thread doesn't propagate, so the profile home is re-bound here- or a non-default profile would run against the wrong home."""+ """Run ``body()`` on a daemon thread under the session's profile home (the ContextVar+ doesn't propagate across threads) and cwd; its text — or ``error: <exc>`` — lands on+ ``parent`` as ``event`` with ``task_id`` (+ ``extra``). Replies ``{task_id}``."""extra = extra or {}def run():@@ -1053,18 +928,16 @@ def _(rid, params: dict) -> dict:@method("prompt.btw")def _(rid, params: dict) -> dict:- """Answer a side question without touching session history: snapshot the live- conversation (in-flight ``_session_messages`` else ``session["history"]``) and run a- one-shot auxiliary call (``agent/side_question.py``). History, role alternation and- prompt cache stay untouched; answer arrives as ``btw.complete``."""+ """Side question over a snapshot of the live conversation (``agent/side_question.py``);+ history, alternation and prompt cache stay untouched. Answer: ``btw.complete``."""session, text, parent, task_id, err = _side_agent_args(rid, params, "btw")if err:return erragent = session.get("agent")snapshot = list(getattr(agent, "_session_messages", None) or session.get("history") or [])main_runtime = {- k: getattr(agent, k, None) for k in ("model", "provider", "base_url", "api_key", "api_mode")- }+ k: getattr(agent, k, None)+ for k in ("model", "provider", "base_url", "api_key", "api_mode")}def body():from agent.side_question import answer_side_question@@ -1120,8 +993,7 @@ def _(rid, params: dict) -> dict:_PREVIEW_RESTART_HISTORY_NOTE if parent_history else None,*_PREVIEW_RESTART_RULES]if line)- # A malformed client path (embedded NUL, etc.) must not blow up the restart:- # treat it as "no validated cwd".+ # A malformed client path (embedded NUL, etc.) is "no validated cwd".try:preview_cwd = os.path.abspath(os.path.expanduser(cwd)) if cwd else ""if preview_cwd and not os.path.isdir(preview_cwd):@@ -1140,9 +1012,8 @@ def _(rid, params: dict) -> dict:_emit("preview.restart.progress", parent,{"task_id": task_id, "text": f"Starting hidden restart agent{history_note}"})- # Deliberately NOT closed through task-wide process cleanup: the whole point is- # to leave a background server running under this task_id, and AIAgent.close()- # would kill every process for it.+ # Deliberately NOT closed via AIAgent.close(): it would kill the background+ # server this task exists to leave running.result = AIAgent(**_ephemeral_preview_agent_kwargs(session["agent"], task_id),**_preview_restart_callbacks(parent, task_id),@@ -1155,18 +1026,15 @@ def _(rid, params: dict) -> dict:from tools.terminal_tool import clear_task_env_overridesclear_task_env_overrides(task_id)- # Pin the validated preview cwd, else the parent workspace — never an invalid- # client path (which would silently fall back to the launch dir).+ # Pin the validated preview cwd, else the parent workspace — never an invalid path.return _spawn_side_agent(rid, session, task_id, parent, "preview.restart.complete", body,cwd=preview_cwd, cleanup=cleanup)# ── late-answer RPCs for tool-driven UI cards ───────────────────────────────-# All use allow_expired=True: each tool's bounded wait (read_terminal 30s, setup_mcp-# 10min, clarify ...) can expire — its _pending entry popped — while the card is still-# visible (e.g. a WS reconnect dropped tool.complete). A late answer must resolve-# gracefully instead of the raw 4009 "no pending answer request".+# allow_expired=True everywhere: a tool's bounded wait can expire (its _pending entry+# popped) while the card is still visible; a late answer must not surface the raw 4009.@method("clarify.respond")@@ -1182,14 +1050,8 @@ _LATE_RESPOND_KEYS = {"sudo.respond": "password", "secret.respond": "value"}-def _late_respond(key: str):- def handler(rid, params: dict) -> dict:- return _respond(rid, params, key, allow_expired=True)- return handler--for _name, _key in _LATE_RESPOND_KEYS.items():- method(_name)(_late_respond(_key))+ method(_name)(lambda rid, params, _k=_key: _respond(rid, params, _k, allow_expired=True))del _name, _key@@ -1227,11 +1089,9 @@ def _(rid, params: dict) -> dict:def _approval_respond_session_fallback(params: dict):- """Durable-identity fallback for ``approval.respond``: the desktop can answer with a- stale live sid (runtime re-minted after a reconnect while the prompt stayed on- screen). Try (1) the approval ``request_id`` (unique across sessions) against every- live session's pending approvals, then (2) ``session_id`` as a STORED id mapped to- its live record. Returns the live session or None."""+ """Durable-identity fallback for a stale live sid (re-minted after a reconnect while+ the prompt stayed on screen): (1) the ``request_id`` against every live session's+ pending approvals, then (2) ``session_id`` as a STORED id. Live session or None."""request_id = str(params.get("request_id") or "")if request_id:try:@@ -1246,11 +1106,9 @@ def _approval_respond_session_fallback(params: dict):return sessionexcept Exception:logger.debug("approval.respond request_id fallback failed", exc_info=True)- target = str(params.get("session_id") or "")- if target:+ if target := str(params.get("session_id") or ""):try:- live = _find_live_session_by_key(target)- if live is not None:+ if (live := _find_live_session_by_key(target)) is not None:return live[1]except Exception:logger.debug("approval.respond stored-id fallback failed", exc_info=True)diff --git a/tui_gateway/prompt_attachments.py b/tui_gateway/prompt_attachments.pyindex 60d1687ce3f..36290d8147c 100644--- a/tui_gateway/prompt_attachments.py+++ b/tui_gateway/prompt_attachments.py@@ -28,8 +28,8 @@ del _re # bodies are rebound onto server globals: import inside functions onlydef _b64_payload(raw: str, data_url_re: str, flags: int) -> bytes:- """Strip an optional ``data:...;base64,`` wrapper and all whitespace, then- strictly decode (raises ``binascii.Error``/``ValueError`` on bad base64)."""+ """Strip an optional ``data:...;base64,`` wrapper and all whitespace, then strictly+ decode (raises ``binascii.Error``/``ValueError`` on bad base64)."""import base64 as _base64import re as _recleaned = (raw or "").strip()@@ -40,8 +40,7 @@ def _b64_payload(raw: str, data_url_re: str, flags: int) -> bytes:def _decode_attach_base64(raw: str, *, mime_prefix: str) -> bytes | None:- """Decode a base64 payload, optionally ``data:<mime_prefix>...;base64,``-wrapped,- tolerating embedded whitespace. ``None`` when not valid base64."""+ """Decode a (``data:<mime_prefix>...;base64,``-wrapped) payload; None when invalid."""import re as _retry:return _b64_payload(@@ -52,8 +51,7 @@ def _decode_attach_base64(raw: str, *, mime_prefix: str) -> bytes | None:def _decode_attach_payload(rid, raw_b64: str, *, mime_prefix: str, max_bytes: int, label: str, empty_msg: str):- """``(bytes, None)`` or ``(None, error)`` for an upload: 4017 on bad/empty- base64, 4018 over *max_bytes*."""+ """``(bytes, None)`` or ``(None, error)``: 4017 on bad/empty base64, 4018 over *max_bytes*."""data = _decode_attach_base64(raw_b64, mime_prefix=mime_prefix)if data is None:return None, _err(rid, 4017, "data is not valid base64")@@ -85,26 +83,20 @@ def _allowed_image_extensions() -> frozenset[str]:def _session_home_dir(session: dict, name: str) -> Path:- """``<session home>/<name>``, anchored on the session's stored ``profile_home``.-- Attach RPCs run BEFORE ``prompt.submit`` installs the profile HERMES_HOME- override, so ``get_hermes_home()`` would return the gateway's launch home —- while the sandbox mounts and the vision host-read allowlist resolve the- *session profile's* dirs at run time. Writing anywhere else means the agent- can never see the file.- """+ """``<session home>/<name>``, anchored on the session's stored ``profile_home``: attach+ RPCs run BEFORE ``prompt.submit`` installs the profile HERMES_HOME override, while+ the sandbox mounts and the vision host-read allowlist resolve the *session profile's*+ dirs at run time — writing anywhere else means the agent can never see the file."""profile_home = session.get("profile_home")return (Path(profile_home) if profile_home else _hermes_home) / namedef _session_images_dir(session: dict) -> Path:- """Uploads ``images/`` dir for the session (see ``_session_home_dir``)."""return _session_home_dir(session, "images")def _queue_attached_image(session: dict, img_bytes: bytes, ext: str, *, prefix: str) -> Path:- """Write image bytes into the session images dir and append to- ``session["attached_images"]`` so the next ``prompt.submit`` picks them up."""+ """Write image bytes into the session images dir and queue them for the next submit."""session["image_counter"] = session.get("image_counter", 0) + 1img_dir = _session_images_dir(session)img_dir.mkdir(parents=True, exist_ok=True)@@ -139,74 +131,37 @@ def _attachment_ref_path(session: dict, target: Path) -> str:return str(target.resolve())-def _desktop_attachment_dir(session: dict) -> Path:- """File-attachment staging dir (``attachments/``, see ``_session_home_dir``);- registered in ``tools.credential_files._CACHE_DIRS`` and auto-mounted into- containers, so a staged file lands where the bind mount points."""- root = _session_home_dir(session, "attachments")- root.mkdir(parents=True, exist_ok=True)- return root--def _sanitize_attachment_name(name: str) -> str:import re as _recandidate = _re.sub(r"[\x00-\x1f]+", "_", Path(str(name or "").strip()).name)return candidate.strip().strip(".") or "attachment"-def _unique_attachment_path(root: Path, filename: str) -> Path:- candidate = root / filename- if not candidate.exists():- return candidate- stem = Path(filename).stem or "attachment"- suffix = Path(filename).suffix- counter = 2- while (next_candidate := root / f"{stem}-{counter}{suffix}").exists():- counter += 1- return next_candidate---def _resolve_gateway_attachment_path(raw: str) -> Path | None:- """Resolve a raw path token to a gateway-visible file, or None."""- if not raw:- return None- try:- from cli import _detect_file_drop, _resolve_attachment_path, _split_path_input- except Exception:- return None- dropped = _detect_file_drop(raw)- if dropped:- return Path(dropped["path"]).resolve()- path_token, _remainder = _split_path_input(raw)- resolved = _resolve_attachment_path(path_token)- return Path(resolved).resolve() if resolved is not None else None---def _decode_attachment_data_url(data_url: str) -> bytes:- """Decode a ``data:<any-mime>;base64,<b64>`` payload (any media type, unlike the- image-specific ``_decode_attach_base64``); bare base64 also accepted."""- import binascii as _binascii- import re as _re- try:- return _b64_payload(- data_url, r"^data:[^;,]*(?:;[^;,=]+=[^;,]+)*;base64,(.*)$", _re.DOTALL | _re.I)- except (ValueError, _binascii.Error) as exc:- raise ValueError("invalid data_url payload") from exc--def _stage_session_file_attachment(session: dict, *, raw_path: str, data_url: str, name: str) -> tuple[Path, bool]:- """Make a desktop file attachment available to the gateway agent.+ """Make a desktop file attachment available to the gateway agent: ``(stored_path, uploaded)``.1. Path resolves INSIDE the session workspace -> use as-is (``uploaded=False``).- 2. Gateway-visible file OUTSIDE the workspace -> copy into ``attachments/``- (bind-mounted into container backends) so ``@file:`` resolves in the sandbox.- 3. Not on the gateway (remote client disk) -> decode ``data_url`` bytes into- ``attachments/``.- Returns ``(stored_path, uploaded)``.+ 2. Gateway-visible file OUTSIDE the workspace -> copy into ``attachments/`` (registered+ in ``tools.credential_files._CACHE_DIRS`` and bind-mounted into container backends)+ so ``@file:`` resolves in the sandbox.+ 3. Not on the gateway (remote client disk) -> decode ``data_url`` bytes into ``attachments/``."""workspace = Path(_session_cwd(session)).resolve()- resolved = _resolve_gateway_attachment_path(raw_path)+ resolved = None+ if raw_path:+ try:+ from cli import _detect_file_drop, _resolve_attachment_path, _split_path_input+ except Exception:+ _detect_file_drop = None+ if _detect_file_drop is not None:+ dropped = _detect_file_drop(raw_path)+ if dropped:+ resolved = Path(dropped["path"]).resolve()+ else:+ path_token, _remainder = _split_path_input(raw_path)+ found = _resolve_attachment_path(path_token)+ resolved = Path(found).resolve() if found is not None else Noneif resolved is not None:try:resolved.relative_to(workspace)@@ -217,10 +172,25 @@ def _stage_session_file_attachment(else:if not data_url:raise ValueError("file not found on gateway and no data_url provided")- payload = _decode_attachment_data_url(data_url)+ # Any media type (unlike the image-specific decoder); bare base64 also accepted.+ import binascii as _binascii+ import re as _re+ try:+ payload = _b64_payload(+ data_url, r"^data:[^;,]*(?:;[^;,=]+=[^;,]+)*;base64,(.*)$", _re.DOTALL | _re.I)+ except (ValueError, _binascii.Error) as exc:+ raise ValueError("invalid data_url payload") from excfilename = _sanitize_attachment_name(name or Path(str(raw_path or "")).name)- target = _unique_attachment_path(- _desktop_attachment_dir(session), _sanitize_attachment_name(filename))+ root = _session_home_dir(session, "attachments")+ root.mkdir(parents=True, exist_ok=True)+ filename = _sanitize_attachment_name(filename)+ target = root / filename+ if target.exists():+ stem = Path(filename).stem or "attachment"+ suffix = Path(filename).suffix+ counter = 2+ while (target := root / f"{stem}-{counter}{suffix}").exists():+ counter += 1target.write_bytes(payload)return target.resolve(), Truediff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.pyindex 7a641a978d2..68460ac4209 100644--- a/tui_gateway/prompt_turn.py+++ b/tui_gateway/prompt_turn.py@@ -28,33 +28,30 @@ def _is_successful_goal_turn(result: Any, status: str, raw: Any) -> bool:and not (isinstance(result, dict) and result.get("completed") is False))-def _goal_max_turns() -> int:+def _active_goal_manager(session: dict):+ """The session's GoalManager when a goal is active, else None."""+ from hermes_cli.goals import GoalManagertry:- goals_cfg = _load_cfg().get("goals") or {}- return int(goals_cfg.get("max_turns", 20) or 20)+ max_turns = int((_load_cfg().get("goals") or {}).get("max_turns", 20) or 20)except Exception:- return 20+ max_turns = 20+ goal_mgr = GoalManager(+ session_id=str(session.get("session_key") or ""), default_max_turns=max_turns)+ return goal_mgr if goal_mgr.is_active() else Nonedef _plan_goal_compression_recovery(session: dict, result: Any, *, status: str, raw: Any) -> tuple[str | None, str | None]:- """Plan a bounded active-goal retry after compression exhaustion.-- Exhaustion is a failed turn: never judge input, never a spent goal turn. One- fresh continuation is allowed; if that also exhausts, pause the goal instead of- spinning until a random user message wakes it. Returns- ``(continuation_prompt, status_notice)``; no active goal -> ``(None, None)``.- """+ """Bounded active-goal retry after compression exhaustion: ``(continuation, notice)``.+ Exhaustion is a failed turn (never judge input, never a spent goal turn); one fresh+ continuation is allowed, a second exhaustion pauses the goal instead of spinning."""if not (isinstance(result, dict) and result.get("compression_exhausted")):if _is_successful_goal_turn(result, status, raw):session.pop(_GOAL_COMPRESSION_RECOVERY_ATTEMPTS, None)return None, None- from hermes_cli.goals import GoalManager- sid_key = str(session.get("session_key") or "")- if not sid_key:+ if not str(session.get("session_key") or ""):return None, None- goal_mgr = GoalManager(session_id=sid_key, default_max_turns=_goal_max_turns())- if not goal_mgr.is_active():+ if (goal_mgr := _active_goal_manager(session)) is None:session.pop(_GOAL_COMPRESSION_RECOVERY_ATTEMPTS, None)return None, Nonegoal_created_at = float(getattr(goal_mgr.state, "created_at", 0.0) or 0.0)@@ -86,13 +83,9 @@ def _plan_goal_compression_recovery(def _admit_prompt_turn(sid: str, session: dict, text: Any, image_paths: list[str] | None,queued_prompt_generation: int | None) -> tuple[list[str], Any] | None:- """Ownership + liveness gate every fresh turn source must cross.-- prompt.submit claims the slot in its RPC handler, but auto-continue, wake-ups- and other synthesized turns call ``_run_prompt_submit`` directly — the bypass- that once let a second backend run a duplicate turn. Returns- ``(images, agent)`` or None when refused (``running`` already reset).- """+ """Ownership + liveness gate every turn source must cross; ``(images, agent)`` or None.+ Synthesized turns (auto-continue, wake-ups) call ``_run_prompt_submit`` directly — the+ bypass that once let a second backend run a duplicate turn."""if (ownership_refusal := _ensure_active_session_slot(sid, session)) is not None:logger.info("Refusing turn for session %s at _run_prompt_submit: %s",@@ -108,33 +101,25 @@ def _admit_prompt_turn(and int(session.get("_queued_prompt_generation", 0)) != queued_prompt_generation):session["running"] = Falsereturn None+ images = list(session.get("attached_images", []) if image_paths is None else image_paths)if image_paths is None:- images = list(session.get("attached_images", []))session["attached_images"] = []- else:- images = list(image_paths)inflight = session.get("inflight_turn")# A retained failed turn (see _fail_inflight_turn) is a stale leftover# by the time a new turn starts — replace it, never append onto it.if not isinstance(inflight, dict) or inflight.get("status") == "error":_start_inflight_turn(session, text)agent = session["agent"]- if hasattr(agent, "clear_interrupt"):- with contextlib.suppress(Exception):- agent.clear_interrupt()+ with contextlib.suppress(Exception):+ agent.clear_interrupt()return images, agentdef _record_turn_marker(session: dict, text: Any) -> str:- """Write the durable crash marker; returns the session key it was written under.-- Retired when the outcome reaches the client; a surviving marker means the- process died mid-turn and session.resume auto-continues from it. Compression- can rotate session_key mid-turn, so the caller keeps this key. The key is- published before the disk write so an interrupt racing startup can retire it;- the post-write cancel check closes the inverse race (Stop landed first, no- file to clear yet).- """+ """Write the durable crash marker; returns the session key it was written under (compression+ can rotate session_key mid-turn). A surviving marker means the process died mid-turn.+ The key is published before the disk write so an interrupt racing startup can retire+ it; the post-write cancel check closes the inverse race (Stop landed first, no file)."""marker_home = _session_home(session)marker_key = str(session.get("session_key") or "")marker_attempt = int(session.pop("_auto_continue_attempt", 0) or 0)@@ -161,63 +146,10 @@ class _TurnScopes:terminal: Any = None-def _bind_turn_scopes(sid: str, session: dict, scopes: _TurnScopes) -> None:- """Bind approval/session/profile/terminal scopes for this turn thread.-- Fills ``scopes`` field by field so a failure midway still leaves every bound- token for ``_release_turn_scopes``. The profile's COMPLETE terminal policy is- bound too: terminal_tool otherwise reads the launch process's pinned env, and- a failed install leaves a refusal scope so terminal tools fail closed.- """- from tools.approval import set_current_session_key- scopes.approval = set_current_session_key(session["session_key"])- scopes.session_tokens = _set_session_context(session["session_key"], ui_session_id=sid)- profile_home = session.get("profile_home")- if profile_home:- scopes.home = set_hermes_home_override(profile_home)- scopes.secret = set_secret_scope(build_profile_secret_scope(Path(profile_home)))- from tools.terminal_scope import install_profile_terminal_scope- scopes.terminal = install_profile_terminal_scope(Path(profile_home))- # The sudo password callback is thread-local: the build thread's wiring doesn't- # reach this turn thread and sudo prompts would fall through to /dev/tty and- # hang the headless gateway (secret capture is a module global; re-run is a no-op).- _wire_callbacks(sid)---def _release_turn_scopes(scopes: _TurnScopes) -> None:- with contextlib.suppress(Exception):- if scopes.approval is not None:- from tools.approval import reset_current_session_key- reset_current_session_key(scopes.approval)- if scopes.home is not None:- reset_hermes_home_override(scopes.home)- if scopes.secret is not None:- reset_secret_scope(scopes.secret)- if scopes.terminal is not None:- from tools.terminal_scope import reset_terminal_scope- reset_terminal_scope(scopes.terminal)- _clear_session_context(scopes.session_tokens)---def _expand_context_references(agent, prompt: str, cwd: str):- """Expand ``@file`` references; returns the preprocess result (``.blocked``/``.message``)."""- from agent.context_references import preprocess_context_references- from agent.model_metadata import get_model_context_length- ctx_len = get_model_context_length(- getattr(agent, "model", "") or _resolve_model(),- base_url=getattr(agent, "base_url", "") or "", api_key=getattr(agent, "api_key", "") or "",- provider=getattr(agent, "provider", "") or "",- config_context_length=getattr(agent, "_config_context_length", None))- return preprocess_context_references(prompt, cwd=cwd, allowed_root=cwd, context_length=ctx_len)--def _route_turn_images(agent, prompt: Any, images: list[str]) -> Any:- """Build the run message for a turn with attached images.-- "native" passes pixels as OpenAI-style content parts; "text" references the- paths so the agent analyzes them in-loop with vision_analyze, never blocking- the submit path on vision calls. Decision table: agent/image_routing.py.- """+ """Run message for a turn with attached images: "native" content parts, or "text" path+ references the agent analyzes in-loop (never blocking submit on vision calls).+ Decision table: agent/image_routing.py."""try:from agent.image_routing import build_native_content_parts, decide_image_input_modefrom hermes_cli.config import load_config as _tui_load_config@@ -248,14 +180,9 @@ def _route_turn_images(agent, prompt: Any, images: list[str]) -> Any:def _start_turn_voice() -> tuple[Any, bool]:- """Arm voice-mode turn audio; returns ``(tts_queue, thinking_started)``.-- ``_tts_stream_begin`` goes first: cutting a still-speaking previous turn IS- this turn's barge-in, so it must latch before the caller consumes the latch.- The full-duplex listener lets the user interject DURING generation. The- "thinking" sound keeps long silences from reading as a dead session; its- gate skips while TTS plays or the mic captures; stopped in the turn's finally.- """+ """Arm voice-mode turn audio; ``(tts_queue, thinking_started)``. ``_tts_stream_begin``+ goes first: cutting a still-speaking previous turn IS this turn's barge-in, so it must+ latch before the caller consumes the latch."""tts_queue = _tts_stream_begin()if not _voice_mode_enabled():return tts_queue, False@@ -277,104 +204,12 @@ def _start_turn_voice() -> tuple[Any, bool]:return tts_queue, False-def _apply_turn_notes(run_message: Any, session: dict) -> Any:- """Prepend the per-turn API-message notes (same enrichment channel as images):- barge mid-speech, reactions since the last turn, then which window the message- was typed into (HUD mode is per-turn state; not for the byte-stable system prompt)."""- from tools.tts_streaming import SPEECH_INTERRUPTED_NOTE, take_speech_interrupted- if take_speech_interrupted():- run_message = _prepend_note(run_message, SPEECH_INTERRUPTED_NOTE)- run_message = _prepend_note(run_message, _pending_reaction_notes(session))- return _prepend_note(run_message, _hud_surface_note(session))---def _build_run_kwargs(- agent, session: dict, history: list, prompt: Any, images: list[str], run_message: Any,- stream_cb, display_kind: str | None, display_metadata: dict | None) -> dict:- """Assemble ``run_conversation`` kwargs, feature-detecting optional parameters.-- A synthesized turn is typed at turn START so the crash persist writes its row- as a timeline event, not a raw user bubble (forever, if the turn never ends).- The post-turn stamp is the fallback for an older agent; re-stamping is a no-op.- """- run_kwargs = {- "conversation_history": list(history),- "stream_callback": stream_cb,- "persist_user_message": (- _build_persist_user_message(prompt, images, run_message) if images else prompt)}- try:- run_params = inspect.signature(agent.run_conversation).parameters- except (TypeError, ValueError):- run_params = {}- if "task_id" in run_params:- run_kwargs["task_id"] = session["session_key"]- if display_kind and "persist_user_display_kind" in run_params:- run_kwargs["persist_user_display_kind"] = display_kind- run_kwargs["persist_user_display_metadata"] = display_metadata- return run_kwargs---def _stamp_synthetic_display_kind(- agent, session: dict, result: Any, text: str, display_kind: str, display_metadata: dict | None-) -> None:- """Post-turn fallback stamp of a synthesized turn's display kind (DB row + result)."""- db = getattr(agent, "_session_db", None)- current_session_id = getattr(agent, "session_id", None) or session.get("session_key")- if db is not None:- try:- db.set_latest_matching_message_display_kind(- current_session_id, role="user", content=text, display_kind=display_kind,- display_metadata=display_metadata)- except Exception:- logger.debug("failed to stamp synthetic display kind", exc_info=True)- if isinstance(result, dict) and isinstance(result.get("messages"), list):- for message in reversed(result["messages"]):- if message.get("role") == "user" and message.get("content") == text:- message["display_kind"] = display_kind- if display_metadata:- message["display_metadata"] = display_metadata- break---def _restore_moa_one_shot(sid: str, session: dict) -> None:- """Undo a /moa one-shot after its turn — through the switch path, because the- one-shot did a real in-place ``agent.switch_model()``; resetting- ``model_override`` alone would leave the live client pinned to MoA."""- _restore = session.pop("moa_one_shot_restore", None)- if isinstance(_restore, dict):- _prev_override = _restore.get("override")- _prev_model = _restore.get("model")- _prev_provider = _restore.get("provider")- if _prev_override is None:- session.pop("model_override", None)- else:- session["model_override"] = _prev_override- if _prev_model:- _raw = f"{_prev_model} --provider {_prev_provider}" if _prev_provider else _prev_model- try:- _apply_model_switch(- sid, session, _raw, confirm_expensive_model=False,- pin_session_override=bool(_prev_override),- persist_override=False) # session-internal restore, never config.yaml- except Exception as _moa_restore_exc:- logger.warning("MoA one-shot model restore failed: %s", _moa_restore_exc)- elif _restore is None:- session.pop("model_override", None)- else:- session["model_override"] = _restore--def _commit_turn_history(session: dict, result: dict, history: list, history_version: int) -> str | None:"""Write the agent's messages back to session history; returns a client warning or None.-- Caller holds no lock. If history_version moved during the turn, the only- tolerated mutation is a pivot marker the gateway itself inserted mid-turn- (model switch, /personality); then the output is merged after the current- history. ``_append_model_switch_marker`` strips prior markers in place then- appends, so the delta is NOT a tail slice — compare content, not indices.- Any other desync (undo/compress/retry/rollback) is surfaced, never dropped.- """+ If history_version moved mid-turn, the only tolerated mutation is a gateway-inserted+ pivot marker (compare content, not indices: ``_append_model_switch_marker`` strips prior+ markers in place); any other desync is surfaced, never dropped."""with session["history_lock"]:current_version = int(session.get("history_version", 0))if current_version == history_version:@@ -386,12 +221,9 @@ def _commit_turn_history(current_no_markers = [e for e in current_history if not _is_pivot_marker(e)]if current_no_markers == history_no_markers and any(_is_pivot_marker(e) for e in current_history):- # Auto-compression can make result["messages"] shorter than the- # turn-start history; then the full result is the base.- if len(result["messages"]) > len(history):- new_messages = result["messages"][len(history):]- else:- new_messages = list(result["messages"])+ # Auto-compression can leave the result shorter than the turn-start history.+ msgs = result["messages"]+ new_messages = msgs[len(history):] if len(msgs) > len(history) else list(msgs)session["history"] = current_history + new_messagessession["history_version"] = current_version + 1return None@@ -417,9 +249,8 @@ def _turn_outcome(result: Any) -> tuple[Any, str, str | None]:return str(result), "complete", Noneraw = result.get("final_response", "")status = _result_status(result)- # No visible response AND a real error (e.g. invalid model slug -> provider- # 4xx): surface the error as the text (classic CLI parity) instead of an- # empty turn. An empty successful turn still renders as empty.+ # No visible response AND a real error: surface the error as the text (classic CLI+ # parity). An empty successful turn still renders as empty.if (not raw) and result.get("error") and (result.get("failed") or result.get("partial")):raw = f"Error: {result.get('error')}"# "Operation interrupted: waiting for model response (…)" is cancellation@@ -432,26 +263,11 @@ def _turn_outcome(result: Any) -> tuple[Any, str, str | None]:return raw, status, last_reasoning-def _turn_error_surface(agent, result: Any) -> Any:- """{layer, code, retryable} descriptor for an error result (advisory, never raises)."""- try:- from agent.error_surface import build_error_surface_from_result- return build_error_surface_from_result(- result, provider=str(getattr(agent, "provider", "") or ""),- model=str(getattr(agent, "model", "") or ""))- except Exception:- return None--def _goal_followup_after_turn(sid: str, session: dict, result: Any, status: str, raw: Any) -> str | None:- """/goal continuation (mirrors gateway/run._post_turn_goal_continuation).-- Asks the judge whether the goal is done and, if not and under budget, returns- the continuation prompt to chain once ``running`` is released. The verdict is- surfaced as a status line either way. Compression failures are never judge- input: the error text is not work toward the goal, and judging it spends a turn.- """+ """/goal continuation (mirrors gateway/run._post_turn_goal_continuation): the prompt to+ chain once ``running`` is released, or None. Compression failures are never judge+ input: the error text is not work toward the goal, and judging it spends a turn."""goal_followup = Nonecompression_exhausted = bool(isinstance(result, dict) and result.get("compression_exhausted"))try:@@ -459,18 +275,13 @@ def _goal_followup_after_turn(session, result, status=status, raw=raw)if recovery_notice:_emit("status.update", sid, {"kind": "goal", "text": recovery_notice})- if recovery_prompt:- goal_followup = recovery_prompt+ goal_followup = recovery_prompt or Noneexcept Exception as _goal_recovery_exc:_hook_failure("goal compression recovery", _goal_recovery_exc)if compression_exhausted or not _is_successful_goal_turn(result, status, raw):return goal_followuptry:- from hermes_cli.goals import GoalManager- sid_key = session.get("session_key") or ""- if sid_key and (- goal_mgr := GoalManager(session_id=sid_key, default_max_turns=_goal_max_turns())- ).is_active():+ if session.get("session_key") and (goal_mgr := _active_goal_manager(session)) is not None:try:from hermes_cli.goals import gather_background_processes as _gather_bg_bg_procs = _gather_bg()@@ -488,8 +299,8 @@ def _goal_followup_after_turn(return goal_followup-def _complete_loop_tick(sid: str, session: dict, raw: Any) -> None:- """If this turn was a /loop wakeup, evaluate it (LOOP_COMPLETE, --until judge, caps, next)."""+def _after_complete_turn(sid: str, session: dict, st: _TurnRun, raw: Any) -> None:+ """Hooks for a ``complete`` turn: /loop tick evaluation, pending title, voice fallback."""try:from hermes_cli.loops import LoopManagerloop_sid_key = session.get("session_key") or ""@@ -502,30 +313,34 @@ def _complete_loop_tick(sid: str, session: dict, raw: Any) -> None:_emit("status.update", sid, {"kind": "loop", "text": loop_msg})except Exception as _loop_exc:_hook_failure("loop completion hook", _loop_exc)---def _apply_pending_title(sid: str, session: dict) -> None:- """Apply pending_title now that the DB row exists — in the session-owned profile store."""- _pending = session.get("pending_title")- if not _pending:- return- _session_key = session.get("session_key") or sid- try:- with _session_db(session) as _pdb:- if _pdb and _pdb.set_session_title(_session_key, _pending):- session["pending_title"] = None- except ValueError as exc:- # Invalid/duplicate title — non-retryable, drop it; auto-title takes over.- session["pending_title"] = None- logger.info("Dropping pending title for session %s: %s", _session_key, exc)- except Exception:- pass # transient DB failure — keep pending_title for retry+ # Apply pending_title now that the DB row exists — in the session-owned profile store.+ if _pending := session.get("pending_title"):+ _session_key = session.get("session_key") or sid+ try:+ with _session_db(session) as _pdb:+ if _pdb and _pdb.set_session_title(_session_key, _pending):+ session["pending_title"] = None+ except ValueError as exc:+ # Invalid/duplicate title — non-retryable, drop it; auto-title takes over.+ session["pending_title"] = None+ logger.info("Dropping pending title for session %s: %s", _session_key, exc)+ except Exception:+ pass # transient DB failure — keep pending_title for retry+ # Voice fallback when the streaming pipeline couldn't start (tts_queue already spoke+ # everything otherwise); barge-aware.+ if st.tts_queue is None and isinstance(raw, str) and raw.strip() and _voice_tts_enabled():+ try:+ threading.Thread(target=_speak_text_with_barge, args=(raw,), daemon=True).start()+ except ImportError:+ logger.warning("voice TTS skipped: hermes_cli.voice unavailable")+ except Exception as e:+ logger.warning("voice TTS dispatch failed: %s", e)def _dispatch_followup_turn(rid, sid: str, session: dict, prompt: Any, what: str, *,on_done=None, on_error=None) -> None:- """Chain one follow-up turn (caller already set ``running``); a dispatch failure- runs ``on_error``, logs, and releases ``running``."""+ """Chain one follow-up turn (caller set ``running``); on failure run ``on_error``, log,+ release ``running``."""try:_emit("message.start", sid)_run_prompt_submit(rid, sid, session, prompt)@@ -541,19 +356,14 @@ def _dispatch_followup_turn(rid, sid: str, session: dict, prompt: Any, what: strdef _run_post_turn_followups(rid, sid: str, session: dict, result: Any, goal_followup: str | None) -> None:- """Chain whatever should run after ``running`` was released.-- Order: a user prompt that arrived mid-turn wins over every auto follow-up —- drain it and skip the rest this cycle. A leftover /steer the agent couldn't- inject is requeued first so it isn't dropped (a real queued prompt still wins:- ``_enqueue_prompt`` merges both). Then the goal continuation, then completion- notifications that arrived mid-turn. Each nested ``_run_prompt_submit`` checks- ``running`` under the lock first, so a racing user prompt wins.- """- _leftover_steer = result.get("pending_steer") if isinstance(result, dict) else None- if isinstance(_leftover_steer, str) and _leftover_steer.strip():+ """Chain whatever should run after ``running`` was released. Order: a mid-turn user+ prompt wins over every auto follow-up (drain it, skip the rest); a leftover /steer is+ requeued first so it isn't dropped; then goal continuation, then completion+ notifications. Each nested submit re-checks ``running`` under the lock."""+ steer = result.get("pending_steer") if isinstance(result, dict) else None+ if isinstance(steer, str) and steer.strip():with session["history_lock"]:- _enqueue_prompt(session, _leftover_steer, session.get("transport"))+ _enqueue_prompt(session, steer, session.get("transport"))if _drain_queued_prompt(rid, sid, session):returnif goal_followup:@@ -562,11 +372,9 @@ def _run_post_turn_followups(return # user already sent something — their turn winssession["running"] = True_dispatch_followup_turn(rid, sid, session, goal_followup, "goal continuation dispatch")- # Safety net for completion events that arrived mid-turn (the poller handles- # between-turn delivery). Ownership is positive-proof and compression-chain- # aware (same fail-closed gate as the poller): session B must not consume- # session A's event; a post-compression session still claims its- # pre-compression dispatches. Unclaimable events are requeued for the poller.+ # Safety net for completion events that arrived mid-turn. Ownership is positive-proof+ # and compression-chain aware (same fail-closed gate as the poller): session B must+ # not consume session A's event. Unclaimable events are requeued for the poller.try:from tools.process_registry import process_registrydrained = process_registry.drain_notifications(@@ -595,23 +403,15 @@ def _run_post_turn_followups(@dataclasses.dataclass(slots=True)class _TurnRun:- """Mutable state the phase helpers of one turn thread share.-- ``agent`` is bound eagerly so except/finally always have one even if setup- throws (re-read after ``_sync_bot_capabilities`` may swap in a rebuilt agent).- ``error_retained``: the finally skips the inflight clear (failed snapshot stays- for resume replay). ``error_detail``: cause for the "tui turn finished" bookend,- stashed by both failure paths (the finally sees neither ``result`` nor the- exception reliably); ``prompt_text`` is the post-@-expansion prompt the cause- is checked against for quoting it back.- """+ """Shared state of one turn thread. ``agent`` is bound eagerly so except/finally always+ have one; ``error_retained`` makes the finally keep the failed inflight snapshot for+ resume replay; ``error_detail`` is the "tui turn finished" failure cause."""agent: Anyone_turn_restore: Anyterminal_callback: Anyreceipt_committed: boolscopes: _TurnScopes = dataclasses.field(default_factory=_TurnScopes)- goal_followup: Any = Noneresult: Any = None # read after the finally for leftover /steertts_queue: Any = Nonethinking_started: bool = False@@ -626,25 +426,33 @@ class _TurnRun:def _prepare_turn_input(sid: str, session: dict, st: _TurnRun, text: Any, images: list[str]):- """Bind scopes, sync the agent, snapshot history and build the run message.-- Returns ``(prompt, run_message, cols, streamer)``, or None when @-expansion- was refused (error already emitted). The config-model sync is skipped while- a /model --once override is active: the once-model is deliberately not pinned- as model_override, so the sync would clobber it (a config.yaml change is- adopted NEXT turn). A model picked mid-turn was queued, not applied — apply- it before the config sync so the explicit pick wins over a config change.- """- _bind_turn_scopes(sid, session, st.scopes)+ """Bind scopes, sync the agent, snapshot history, build the run message; returns+ ``(prompt, run_message, cols, streamer)`` or None when @-expansion was refused.+ Scopes fill field by field so a failure midway still leaves every bound token for the+ finally; the profile's terminal policy is bound too (a failed install leaves a+ fail-closed refusal scope). The config-model sync is skipped under a /model --once+ override (not pinned as model_override, the sync would clobber it); a model picked+ mid-turn is applied first so the explicit pick wins over a config change."""+ from tools.approval import set_current_session_key+ scopes = st.scopes+ scopes.approval = set_current_session_key(session["session_key"])+ scopes.session_tokens = _set_session_context(session["session_key"], ui_session_id=sid)+ profile_home = session.get("profile_home")+ if profile_home:+ scopes.home = set_hermes_home_override(profile_home)+ scopes.secret = set_secret_scope(build_profile_secret_scope(Path(profile_home)))+ from tools.terminal_scope import install_profile_terminal_scope+ scopes.terminal = install_profile_terminal_scope(Path(profile_home))+ # The sudo password callback is thread-local: without re-wiring here, sudo prompts+ # fall through to /dev/tty and hang the headless gateway (re-run is a no-op).+ _wire_callbacks(sid)if not st.one_turn_restore:_apply_pending_model_switch(sid, session)_sync_agent_model_with_config(sid, session)_sync_agent_compression_with_config(sid, session)- # Bot Chat: adopt Settings->Capabilities edits into the eternal bot session first.- _sync_bot_capabilities(sid, session)+ _sync_bot_capabilities(sid, session) # Bot Chat: adopt Settings->Capabilities editsst.agent = agent = session["agent"]- # Snapshot after turn-start model sync: a deferred switch mutates history- # and its version, and that mutation belongs to this turn.+ # Snapshot after the model sync: a deferred switch's history mutation belongs to this turn.with session["history_lock"]:st.history = list(session["history"])st.history_version = int(session.get("history_version", 0))@@ -654,7 +462,16 @@ def _prepare_turn_input(sid: str, session: dict, st: _TurnRun, text: Any, imagesstreamer = make_stream_renderer(cols)prompt = textif isinstance(prompt, str) and "@" in prompt:- ctx = _expand_context_references(agent, prompt, cwd)+ from agent.context_references import preprocess_context_references+ from agent.model_metadata import get_model_context_length+ ctx_len = get_model_context_length(+ getattr(agent, "model", "") or _resolve_model(),+ base_url=getattr(agent, "base_url", "") or "",+ api_key=getattr(agent, "api_key", "") or "",+ provider=getattr(agent, "provider", "") or "",+ config_context_length=getattr(agent, "_config_context_length", None))+ ctx = preprocess_context_references(+ prompt, cwd=cwd, allowed_root=cwd, context_length=ctx_len)if ctx.blocked:_emit("error", sid, {"message": "\n".join(ctx.warnings) or "Context injection refused."})@@ -663,7 +480,13 @@ def _prepare_turn_input(sid: str, session: dict, st: _TurnRun, text: Any, imagesst.prompt_text = prompt if isinstance(prompt, str) else ""run_message: Any = _route_turn_images(agent, prompt, images) if images else promptst.tts_queue, st.thinking_started = _start_turn_voice()- return prompt, _apply_turn_notes(run_message, session), cols, streamer+ # Per-turn API-message notes: barge mid-speech, reactions, HUD surface (per-turn state+ # that must not touch the byte-stable system prompt).+ from tools.tts_streaming import SPEECH_INTERRUPTED_NOTE, take_speech_interrupted+ if take_speech_interrupted():+ run_message = _prepend_note(run_message, SPEECH_INTERRUPTED_NOTE)+ run_message = _prepend_note(run_message, _pending_reaction_notes(session))+ return prompt, _prepend_note(run_message, _hud_surface_note(session)), cols, streamerdef _invoke_agent(@@ -682,21 +505,33 @@ def _invoke_agent(st.tts_queue.put(delta)_emit("message.delta", sid, payload)- # Interim assistant text (commentary beside tool calls, or a pre-nudge final- # answer) is sealed by the desktop as its own segment instead of being lost- # when message.complete replaces the streaming buffer. Gated on- # display.interim_assistant_messages (default true).+ # Interim assistant text (commentary beside tool calls, pre-nudge final answer) is+ # sealed by the desktop as its own segment instead of being lost when+ # message.complete replaces the streaming buffer.if _load_interim_assistant_messages():def _interim_assistant_cb(text: str, *, already_streamed: bool = False) -> None:_emit("message.interim", sid, {"text": text, "already_streamed": already_streamed})agent.interim_assistant_callback = _interim_assistant_cbelse:agent.interim_assistant_callback = None- st.run_kwargs = _build_run_kwargs(- agent, session, st.history, prompt, images, run_message, _stream, display_kind,- display_metadata)- # Auto-titling fires inside the turn prologue; this live-rename hook- # repaints the sidebar the moment a title lands.+ # Feature-detect optional run_conversation parameters. A synthesized turn is typed at+ # turn START so a crash persist writes a timeline event, not a raw user bubble; the+ # post-turn stamp is the fallback for an older agent.+ st.run_kwargs = run_kwargs = {+ "conversation_history": list(st.history),+ "stream_callback": _stream,+ "persist_user_message": (+ _build_persist_user_message(prompt, images, run_message) if images else prompt)}+ try:+ run_params = inspect.signature(agent.run_conversation).parameters+ except (TypeError, ValueError):+ run_params = {}+ if "task_id" in run_params:+ run_kwargs["task_id"] = session["session_key"]+ if display_kind and "persist_user_display_kind" in run_params:+ run_kwargs["persist_user_display_kind"] = display_kind+ run_kwargs["persist_user_display_metadata"] = display_metadata+ # Live-rename hook: auto-titling fires inside the turn prologue._title_key = session.get("session_key") or sidagent._on_session_title = lambda t, _src, _k=_title_key: _emit("session.title", sid, {"session_id": _k, "title": t})@@ -704,11 +539,9 @@ def _invoke_agent(try:st.result = agent.run_conversation(run_message, **st.run_kwargs)finally:- # Stop AND join before anything below emits: a tick surviving past- # message.complete would roll the client's final usage back to a stale- # snapshot. The join is deliberately unbounded — once stop is set it only- # waits out one in-flight _get_usage/_emit, whose worst case (a stalled- # transport write) would stall the message.complete emit just the same.+ # Stop AND join before anything emits: a tick surviving past message.complete+ # would roll the client's usage back to a stale snapshot. The unbounded join only+ # waits out one in-flight _get_usage/_emit (same worst case as the emit itself)._usage_stop.set()_usage_thread.join()@@ -717,28 +550,66 @@ def _absorb_turn_result(sid: str, session: dict, st: _TurnRun, text: Any, display_kind: str | None, display_metadata) -> str | None:"""Stamp, restore /moa, commit history, re-sync the session key; returns the history warning."""- result = st.result+ result, agent = st.result, st.agentif display_kind and isinstance(text, str):- _stamp_synthetic_display_kind(- st.agent, session, result, text, display_kind, display_metadata)+ # Post-turn fallback stamp of a synthesized turn's display kind (DB row + result).+ db = getattr(agent, "_session_db", None)+ current_session_id = getattr(agent, "session_id", None) or session.get("session_key")+ if db is not None:+ try:+ db.set_latest_matching_message_display_kind(+ current_session_id, role="user", content=text, display_kind=display_kind,+ display_metadata=display_metadata)+ except Exception:+ logger.debug("failed to stamp synthetic display kind", exc_info=True)+ if isinstance(result, dict) and isinstance(result.get("messages"), list):+ for message in reversed(result["messages"]):+ if message.get("role") == "user" and message.get("content") == text:+ message["display_kind"] = display_kind+ if display_metadata:+ message["display_metadata"] = display_metadata+ breakif "moa_one_shot_restore" in session:- _restore_moa_one_shot(sid, session)+ # Undo a /moa one-shot through the switch path: resetting model_override alone+ # would leave the live client pinned to MoA after the in-place switch_model().+ _restore = session.pop("moa_one_shot_restore", None)+ if isinstance(_restore, dict):+ _prev_override = _restore.get("override")+ _prev_model = _restore.get("model")+ _prev_provider = _restore.get("provider")+ if _prev_override is None:+ session.pop("model_override", None)+ else:+ session["model_override"] = _prev_override+ if _prev_model:+ _raw = (+ f"{_prev_model} --provider {_prev_provider}" if _prev_provider else _prev_model)+ try:+ _apply_model_switch(+ sid, session, _raw, confirm_expensive_model=False,+ pin_session_override=bool(_prev_override),+ persist_override=False) # session-internal restore, never config.yaml+ except Exception as _moa_restore_exc:+ logger.warning("MoA one-shot model restore failed: %s", _moa_restore_exc)+ elif _restore is None:+ session.pop("model_override", None)+ else:+ session["model_override"] = _restorestatus_note = Noneif isinstance(result, dict):if isinstance(result.get("messages"), list):status_note = _commit_turn_history(session, result, st.history, st.history_version)- # Auto-compression inside run_conversation() may have rotated- # agent.session_id: sync session_key before title/goal/finalize use it,- # keep pending_title (user intent), and restart the slash worker so- # worker-backed commands (/title etc.) target the live session.+ # Auto-compression may have rotated agent.session_id: sync session_key before+ # title/goal/finalize use it, keep pending_title (user intent), restart the slash+ # worker so worker-backed commands target the live session._sync_session_key_after_compress(sid, session, clear_pending_title=False, restart_slash_worker=True)return status_notedef _complete_turn_payload(session: dict, st: _TurnRun, status_note: str | None, cols: int):- """Build the ``message.complete`` payload, retain/clear the inflight turn and- settle the hosted-room terminal receipt. Returns ``(payload, raw, status)``."""+ """``(payload, raw, status)`` for message.complete; retains/clears the inflight turn and+ settles the hosted-room terminal receipt."""result, agent = st.result, st.agentraw, status, last_reasoning = _turn_outcome(result)payload = {"text": raw, "usage": _get_usage(agent), "status": status}@@ -748,29 +619,32 @@ def _complete_turn_payload(session: dict, st: _TurnRun, status_note: str | None,payload["warning"] = status_noteif result.get("response_previewed"):payload["response_previewed"] = True- # Structured billing-wall descriptor so the client renders a- # billing-specific recovery surface instead of re-parsing text.- _billing_block = result.get("billing_block") if isinstance(result, dict) else None- if _billing_block:+ # Structured billing-wall descriptor: the client renders recovery without re-parsing text.+ if _billing_block := result.get("billing_block"):payload["billing"] = _billing_blockpayload["failure_reason"] = result.get("failure_reason")if rendered := render_message(raw, cols):payload["rendered"] = rendered- # Layer descriptor computed before the retain below so resume replay- # carries the same one (advisory; older clients ignore it).- _error_surface = _turn_error_surface(agent, result) if status == "error" else None- _result_error = result.get("error") if isinstance(result, dict) else None- error_value = _result_error if isinstance(result, dict) else raw+ # {layer, code, retryable} descriptor (advisory), computed before the retain below so+ # resume replay carries the same one.+ _error_surface = None+ if status == "error":+ try:+ from agent.error_surface import build_error_surface_from_result+ _error_surface = build_error_surface_from_result(+ result, provider=str(getattr(agent, "provider", "") or ""),+ model=str(getattr(agent, "model", "") or ""))+ except Exception:+ _error_surface = None+ error_value = result.get("error")with session["history_lock"]:if status == "error":- # Retain the failed turn for resume replay: if this terminal frame- # is lost to a disconnect, resume's inflight payload is the only- # carrier of the failure.+ # Retain the failed turn: if this frame is lost to a disconnect, resume's+ # inflight payload is the only carrier of the failure._fail_inflight_turn(session, error_value, error_surface=_error_surface)st.error_retained = Truest.error_detail = _turn_failure_detail(- error_value, result.get("failure_reason") if isinstance(result, dict) else None,- st.prompt_text)+ error_value, result.get("failure_reason"), st.prompt_text)else:_clear_inflight_turn(session)if status == "error":@@ -785,9 +659,7 @@ def _complete_turn_payload(session: dict, st: _TurnRun, status_note: str | None,"cancelled" if status == "interrupted"else "failed" if status == "error" else "settled"),"text": raw if isinstance(raw, str) else str(raw),- **(- {"error": str(_result_error or raw)}- if status == "error" and isinstance(result, dict) else {})})+ **({"error": str(error_value or raw)} if status == "error" else {})})st.receipt_committed = Trueif st.receipt_committed:_retire_turn_marker(session, st.marker_key)@@ -805,10 +677,8 @@ def _recover_turn_exception(sid: str, session: dict, st: _TurnRun, e: BaseExceptf"{time.strftime('%Y-%m-%d %H:%M:%S')} · sid={sid} ===\n")f.write(traceback.format_exc())print(f"[gateway-turn] {type(e).__name__}: {e}", file=sys.stderr, flush=True)- # An exception in the agent's finalizer can leave the gateway's in-memory- # history at the turn-start snapshot; keep the partial turn available to- # the next prompt (the durable inflight record still carries the- # recoverable error state).+ # A finalizer exception can leave in-memory history at the turn-start snapshot; keep+ # the partial turn available to the next prompt._restore_agent_history_after_turn_error(session, st.agent)if st.terminal_callback is not None and not st.receipt_attempted:st.receipt_attempted = True@@ -818,8 +688,7 @@ def _recover_turn_exception(sid: str, session: dict, st: _TurnRun, e: BaseExceptexcept Exception:logger.exception("hosted room terminal receipt commit failed")try:- # Same terminal error frame shape as the returned-error path (uniform- # client handling), retaining the turn for replay.+ # Same terminal error frame shape as the returned-error path._emit_terminal_turn_error(sid, session, e, retire_marker=st.receipt_committed)st.error_retained = Truest.error_detail = _turn_failure_detail(e, type(e).__name__, st.prompt_text)@@ -832,14 +701,11 @@ def _recover_turn_exception(sid: str, session: dict, st: _TurnRun, e: BaseExceptdef _finish_turn(sid: str, session: dict, st: _TurnRun) -> None:"""Finally-path of the turn: release everything, then the "tui turn finished" bookend."""- agent, history, run_kwargs = st.agent, st.history, st.run_kwargs- # Drop both snapshots of the pre-turn history before asking glibc to return- # pages; session["history"] already points at the new/pruned result.- history.clear()- if isinstance(run_kwargs, dict):- run_kwargs.clear()- # While any profile-specific HERMES_HOME override is still active, so- # context.memory_trim resolves from the session's own config.+ # Drop both pre-turn history snapshots before asking glibc to return pages.+ st.history.clear()+ if isinstance(st.run_kwargs, dict):+ st.run_kwargs.clear()+ # While the profile HERMES_HOME override is still active (session's own config).try:from hermes_cli.mem_trim import trim_memorytrim_memory(reason="tui turn completion")@@ -853,32 +719,25 @@ def _finish_turn(sid: str, session: dict, st: _TurnRun) -> None:st.tts_queue.put(None) # end-of-text sentinel — flush + finish speakingif st.one_turn_restore:try:- _restore_agent_model_runtime(agent, st.one_turn_restore)+ _restore_agent_model_runtime(st.agent, st.one_turn_restore)_restart_slash_worker(sid, session)_persist_live_session_runtime(session)_persist_live_session_system_prompt(session)except Exception:logger.debug("TUI one-turn model restore failed", exc_info=True)- _release_turn_scopes(st.scopes)---def _log_turn_finished(sid: str, session: dict, st: _TurnRun, started_monotonic: float) -> None:- """Closing bookend of "tui prompt accepted" — fires on every path, so one- accepted prompt produces exactly one finished record. agent.session_id is- re-read because compression may have rotated it mid-turn (an accepted/finished- pair whose id changed IS a rotation trace). A missing finished record means- the thread died before the finally."""- result = st.result- if isinstance(result, dict):- status = _result_status(result)- else:- status = "error" if st.error_retained else "complete"- logger.info(- "tui turn finished: ui_session=%s session_key=%s "- "agent_session_id=%s status=%s error_retained=%s duration=%.1fs"- "%s",- sid, session.get("session_key") or "", getattr(st.agent, "session_id", "") or "", status,- st.error_retained, time.monotonic() - started_monotonic, st.error_detail)+ scopes = st.scopes+ with contextlib.suppress(Exception):+ if scopes.approval is not None:+ from tools.approval import reset_current_session_key+ reset_current_session_key(scopes.approval)+ if scopes.home is not None:+ reset_hermes_home_override(scopes.home)+ if scopes.secret is not None:+ reset_secret_scope(scopes.secret)+ if scopes.terminal is not None:+ from tools.terminal_scope import reset_terminal_scope+ reset_terminal_scope(scopes.terminal)+ _clear_session_context(scopes.session_tokens)def _run_prompt_submit(@@ -890,10 +749,8 @@ def _run_prompt_submit(if admitted is None:return Falseimages, agent = admitted- # The ONE INFO record proving a Desktop/TUI prompt was accepted by THIS- # process; ties the UI session id, gateway session_key and the agent's live- # session_id (compression rotates the last independently) together for a- # rotation-mute trace. No prompt content is logged.+ # The ONE INFO record proving a prompt was accepted by THIS process; ties ui sid,+ # session_key and the agent's live session_id together. No prompt content is logged._turn_started_monotonic = time.monotonic()logger.info("tui prompt accepted: ui_session=%s session_key=%s agent_session_id=%s "@@ -903,15 +760,15 @@ def _run_prompt_submit(_emit("message.start", sid)def run():- # ContextVars from the RPC dispatcher do not follow onto this thread:- # rebind the exact transport stored on this session generation before any- # tool can commission a child (delegate_task captures it as authority).+ # RPC-dispatcher ContextVars do not follow onto this thread: rebind the transport+ # before any tool can commission a child (delegate_task captures it as authority).transport_token = bind_transport(session.get("transport"))runtime_session_token = _current_runtime_session_record.set(session)st = _TurnRun(session["agent"], session.pop("one_turn_model_restore", None), terminal_callback,receipt_committed=terminal_callback is None)st.marker_key = _record_turn_marker(session, text)+ goal_followup = Nonetry:prepared = _prepare_turn_input(sid, session, st, text, images)if prepared is None:@@ -924,23 +781,9 @@ def _run_prompt_submit(sid, session, st, text, display_kind, display_metadata)payload, raw, status = _complete_turn_payload(session, st, status_note, cols)_emit("message.complete", sid, payload)- st.goal_followup = _goal_followup_after_turn(sid, session, st.result, status, raw)+ goal_followup = _goal_followup_after_turn(sid, session, st.result, status, raw)if status == "complete":- _complete_loop_tick(sid, session, raw)- _apply_pending_title(sid, session)- # Voice fallback when the streaming pipeline couldn't start (the- # streaming path already spoke everything via tts_queue); barge-aware- # so spoken interruptions cut this playback too.- if (- st.tts_queue is None and isinstance(raw, str) and raw.strip()- and _voice_tts_enabled()):- try:- threading.Thread(- target=_speak_text_with_barge, args=(raw,), daemon=True).start()- except ImportError:- logger.warning("voice TTS skipped: hermes_cli.voice unavailable")- except Exception as e:- logger.warning("voice TTS dispatch failed: %s", e)+ _after_complete_turn(sid, session, st, raw)except Exception as e:_recover_turn_exception(sid, session, st, e)finally:@@ -954,7 +797,19 @@ def _run_prompt_submit(session["last_active"] = time.time()if not st.error_retained:_clear_inflight_turn(session)- _log_turn_finished(sid, session, st, _turn_started_monotonic)+ # Closing bookend of "tui prompt accepted" — exactly one per accepted prompt.+ # agent.session_id is re-read because compression may have rotated it (an+ # accepted/finished pair whose id changed IS a rotation trace).+ if isinstance(st.result, dict):+ status = _result_status(st.result)+ else:+ status = "error" if st.error_retained else "complete"+ logger.info(+ "tui turn finished: ui_session=%s session_key=%s agent_session_id=%s status=%s "+ "error_retained=%s duration=%.1fs%s",+ sid, session.get("session_key") or "", getattr(st.agent, "session_id", "") or "",+ status, st.error_retained, time.monotonic() - _turn_started_monotonic,+ st.error_detail)# Backstop for turns that never reached a terminal frame.if st.receipt_committed:_retire_turn_marker(session, st.marker_key)@@ -964,7 +819,7 @@ def _run_prompt_submit(session.pop("_hosted_room_task", None)session.pop("_auto_continue_scheduled", None)_emit_settled_session_info(sid, session, st.agent)- _run_post_turn_followups(rid, sid, session, st.result, st.goal_followup)+ _run_post_turn_followups(rid, sid, session, st.result, goal_followup)run_thread = threading.Thread(target=run, daemon=True)with _sessions_lock:registered = _sessions.get(sid)