The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(tui): compact docstrings in compression/auto-continue split modules
Teknium0e7c1d2b89f6
diff --git a/tui_gateway/session_auto_continue.py b/tui_gateway/session_auto_continue.pyindex e6576b4fc29..6414430dca4 100644--- a/tui_gateway/session_auto_continue.py+++ b/tui_gateway/session_auto_continue.py@@ -38,10 +38,9 @@ def _session_home(session: dict) -> Path:def _retire_turn_marker(session: dict, *keys: str) -> None:- """Drop the crash marker for a turn whose outcome is about to reach the client. Called right before- the terminal frame, not at turn-thread end: post-turn work (titles, memory sync, goal hooks) outlives- the client's answer, and quitting in that window would leave a marker that re-runs a finished turn- on next launch. Extra ``keys`` cover a session_key that compression rotated mid-turn."""+ """Drop the crash marker right before the terminal frame (not at turn-thread end: post-turn work+ outlives the client's answer, and quitting in that window would leave a marker that re-runs a+ finished turn). Extra ``keys`` cover a session_key that compression rotated mid-turn."""home = _session_home(session)for key in dict.fromkeys((*keys, str(session.get("session_key") or ""))):if key:@@ -68,10 +67,9 @@ def _ac_release_turn(session: dict, *, unschedule: bool = False) -> None:def _maybe_schedule_auto_continue(sid: str, session: dict, session_key: str) -> dict | None:- """Kick off a continuation turn for a crash-interrupted session (session.resume cold paths, once the- live record is registered). Returns a descriptor for the resume payload when scheduled, else None.- The turn runs on a background thread after the deferred agent build via the normal- _run_prompt_submit path, so the client that just resumed streams it live."""+ """Kick off a continuation turn for a crash-interrupted session (session.resume cold paths). Returns a+ descriptor for the resume payload when scheduled, else None. The turn runs on a background thread+ after the deferred agent build via _run_prompt_submit, so the client that just resumed streams it."""# Hosted room turns are recovered by their durable task/lease state machine; generic auto-continue# would bypass its execution generation and duplicate work.if session.get("source") == "bot_room":@@ -137,11 +135,9 @@ def _ac_inflight_original(session: dict) -> str:def _enqueue_prompt(session: dict, text: Any, transport: Any, image_paths: list[str] | None = None) -> None:- """Stash a message to run as the very next turn once the live one ends. Text-only arrivals share a- slot and merge losslessly (like the consecutive-user merge in ``repair_message_sequence``);- image-bearing ones stay separate envelopes so attachment ownership/chronology survive.- ``transport`` is pinned so the drained turn streams back to its sender even if the session- transport is rebound."""+ """Queue a message for the next turn. Text-only arrivals share a slot and merge losslessly (like the+ consecutive-user merge in ``repair_message_sequence``); image-bearing ones stay separate envelopes so+ attachment chronology survives. ``transport`` is pinned so the drained turn streams to its sender."""image_paths = list(image_paths or [])# Scrub live-turn self-duplicates first so the text merge below can't glue "{original}\n\n{later}"# and re-fire the original after a correction settles.@@ -168,10 +164,9 @@ def _enqueue_prompt(session: dict, text: Any, transport: Any, image_paths: list[def _sanitize_queued_entry_vs_inflight_user(entry: Any, original: str) -> dict | None:- """Drop (``None``) or rewrite a queue envelope that re-carries the live user text: text-only- self-duplicates are dropped; a merged slot ``"{original}\\n\\n{later}"`` is rewritten to ``later`` so- the correction survives without re-firing the original. Image-bearing envelopes are left alone- (chronology is load-bearing)."""+ """Drop (``None``) a text-only self-duplicate of the live user text, or rewrite a merged slot+ ``"{original}\\n\\n{later}"`` to ``later`` so the correction survives without re-firing the original.+ Image-bearing envelopes are left alone (chronology is load-bearing)."""if not isinstance(entry, dict):return Nonetext = entry.get("text")@@ -190,10 +185,8 @@ def _sanitize_queued_entry_vs_inflight_user(entry: Any, original: str) -> dict |def _drop_queued_duplicates_of_inflight_user(session: dict) -> None:- """Remove server-queue copies of the live turn's original user text. A mid-turn ``prompt.submit`` of- the same text can be queued while redirect is unavailable (build window, tool boundary); after a- later redirect it must not drain and restart the original as a fresh turn. Unrelated follow-ups- stay."""+ """Remove server-queue copies of the live turn's original user text: a mid-turn ``prompt.submit`` of+ the same text queued while redirect was unavailable must not drain and restart the original."""original = _ac_inflight_original(session)if not original:return@@ -213,10 +206,9 @@ def _ac_set_queue(session: dict, entries: list) -> None:def _interrupt_busy_session(sid: str, session: dict, agent: Any) -> None:- """Interrupt a busy turn on a worker thread, never under ``history_lock``: some providers can't apply- ``interrupt()`` until a blocking tool/network call returns, and doing it inline stalled- ``session.resume`` and the queued prompt. At most one interrupt worker per session so repeated- steering can't leak threads."""+ """Interrupt a busy turn on a worker thread, never under ``history_lock`` (some providers can't apply+ ``interrupt()`` until a blocking call returns; inline it stalled ``session.resume``). At most one+ interrupt worker per session so repeated steering can't leak threads."""use_agent = agent is not None and hasattr(agent, "interrupt")if not use_agent and not _session_uses_compute_host(session):return@@ -257,12 +249,11 @@ def _ac_try_correction(rid, session: dict, agent: Any, method: str, plain_text:def _handle_busy_submit(rid, sid: str, session: dict, text: Any, transport: Any, queued: bool = False) -> dict | None:- """Apply ``display.busy_input_mode`` to a prompt that lands mid-turn instead of rejecting it with- ``session busy`` (rejection made clients busy-retry and silently drop sends when teardown outlived- their deadline). Modes: ``interrupt`` (default) → redirect the live turn, falling back to hard- interrupt + queue for older agents; ``queue`` → queue only; ``steer`` → inject after the current- atomic action. ``queued=True`` (client queue drain) forces queue mode: a "run after" message must- NEVER become a live-turn correction, even when the drain loses the settle race."""+ """Apply ``display.busy_input_mode`` to a prompt that lands mid-turn instead of rejecting it (rejection+ made clients busy-retry and silently drop sends). ``interrupt`` (default) → redirect the live turn,+ falling back to hard interrupt + queue for older agents; ``queue`` → queue only; ``steer`` → inject+ after the current atomic action. ``queued=True`` (client queue drain) forces queue mode: a "run+ after" message must NEVER become a live-turn correction, even if the drain loses the settle race."""mode = "queue" if queued else _load_busy_input_mode()agent = session.get("agent")with session["history_lock"]:@@ -303,9 +294,8 @@ def _handle_busy_submit(rid, sid: str, session: dict, text: Any, transport: Any,def _drain_queued_prompt(rid, sid: str, session: dict) -> bool:- """Fire a queued next-turn prompt if one is waiting and the session is idle. True when dispatched:- the caller skips lower-priority follow-ups this cycle (the user's message wins). Claim-under-lock- like the goal-continuation re-fire."""+ """Fire a queued next-turn prompt if one is waiting and the session is idle. True when dispatched: the+ caller skips lower-priority follow-ups this cycle (the user's message wins)."""with session["history_lock"]:if session.get("_closing"):return False@@ -389,11 +379,9 @@ def _emit_terminal_turn_error(sid: str, session: dict, error: Any, error_surface: Optional[dict] = None, *, retire_marker: bool = True) -> None:"""Close a failed turn with the same ``status: "error"`` ``message.complete`` frame as- ``_run_prompt_submit``'s returned-error path, retaining the turn via ``_fail_inflight_turn`` so a- client that missed the frame recovers it from ``session.resume``'s ``inflight``. Callers that know- the failing layer pass ``error_surface``; exception callers leave it None and it is classified here- ({layer, code, retryable} so the desktop can say "Provider error" / "Gateway error"; advisory,- never raises)."""+ ``_run_prompt_submit``'s returned-error path, retaining the turn (``_fail_inflight_turn``) so a client+ that missed the frame recovers it from ``session.resume``'s ``inflight``. ``error_surface`` ({layer,+ code, retryable}) is classified here from an exception when the caller doesn't know the layer."""agent = session.get("agent")if error_surface is None and isinstance(error, BaseException):try:diff --git a/tui_gateway/session_compression.py b/tui_gateway/session_compression.pyindex 1e85ad76304..7b35cc8909a 100644--- a/tui_gateway/session_compression.py+++ b/tui_gateway/session_compression.py@@ -1,12 +1,9 @@"""Live compression: config hot-reload onto a running agent, pending model switch apply, /compress-(CompressionLockHeld when a turn holds the lock), session-key sync after compress.--Bodies are rebound onto server.py's globals (method_ctx.bind_module) and reference them bare.-"""+(CompressionLockHeld when a turn holds the lock), session-key sync after compress. Bodies are rebound+onto server.py's globals (method_ctx.bind_module) and reference them bare."""from __future__ import annotations-import contextlibfrom .method_ctx import bind_module@@ -14,15 +11,13 @@ from .method_ctx import bind_moduledef _tui_compression_config_signature(cfg: dict | None) -> tuple:"""Stable snapshot of compression/context keys that must apply next turn: the messaging-gateway- cache-busting extract (same key set as messaging) plus ``idle_compact_after_seconds`` and- ``tail_mode`` (affect live TUI sessions, not in the gateway tuple)."""+ cache-busting extract plus ``idle_compact_after_seconds``/``tail_mode`` (live-TUI-only keys)."""from gateway.run import GatewayRunnerkeys = GatewayRunner._extract_cache_busting_config(cfg)picked = {k: v for k, v in keys.items() if k.startswith("compression.") or k == "model.context_length"}compression = cfg.get("compression") if isinstance(cfg, dict) and isinstance(cfg.get("compression"), dict) else {}- for extra in ("idle_compact_after_seconds", "tail_mode"):- picked[f"compression.{extra}"] = compression.get(extra)+ picked.update({f"compression.{k}": compression.get(k) for k in ("idle_compact_after_seconds", "tail_mode")})return tuple(sorted(picked.items()))@@ -31,7 +26,6 @@ def _compressor_ctor_default(name: str, fallback: Any) -> Any:construction path's derivation instead of a hardcoded copy that could drift."""try:import inspect-from agent.context_compressor import ContextCompressordefault = inspect.signature(ContextCompressor.__init__).parameters[name].default@@ -52,13 +46,11 @@ def _derived_default_threshold_percent(agent: Any, compression: dict) -> float:from agent.agent_init import _resolve_compression_thresholdfrom agent.auxiliary_client import _compression_threshold_for_model, _is_codex_gpt54_or_gpt55, _is_codex_spark- model = getattr(agent, "model", "") or ""- provider = getattr(agent, "provider", "") or ""+ model, provider = getattr(agent, "model", "") or "", getattr(agent, "provider", "") or ""autoraise_enabled = str(compression.get("codex_gpt55_autoraise", True)).lower() in {"true", "1", "yes"}- model_cthresh = _compression_threshold_for_model(model, provider, allow_codex_gpt55_autoraise=autoraise_enabled)pct, _notice = _resolve_compression_threshold(- pct, model_cthresh, model=model,- is_codex_autoraise=_is_codex_gpt54_or_gpt55(model, provider) or _is_codex_spark(model, provider),+ pct, _compression_threshold_for_model(model, provider, allow_codex_gpt55_autoraise=autoraise_enabled),+ model=model, is_codex_autoraise=_is_codex_gpt54_or_gpt55(model, provider) or _is_codex_spark(model, provider),)except Exception:pass@@ -76,15 +68,11 @@ _COMPRESSION_INT_KEYS = (def _apply_live_compression_config(agent: Any, cfg: dict | None) -> None:- """Update a live session's compressor from current config.yaml, preserving the agent object, session- identity, history and callbacks. Recomputes the trigger from the ratio threshold, then applies- ``compression.threshold_tokens`` so raising/lowering/clearing the cap lands next preflight.-- Every adopted key has UNSET semantics: a removed key restores the normalized default (or the- model-derived value) through the construction path's own derivation (ctor signature defaults, Codex- autoraise, deferred context-length re-inference). Acting only on PRESENT keys would leave stale- values active forever.- """+ """Update a live session's compressor in place from current config.yaml (agent object, session+ identity, history and callbacks preserved). Every adopted key has UNSET semantics: a removed key+ restores the normalized default (or model-derived value) through the construction path's own+ derivation (ctor signature defaults, Codex autoraise, deferred context-length re-inference) —+ acting only on PRESENT keys would leave stale values active forever."""cfg = cfg if isinstance(cfg, dict) else {}compression = cfg.get("compression") if isinstance(cfg.get("compression"), dict) else {}model_cfg = cfg.get("model") if isinstance(cfg.get("model"), dict) else {}@@ -184,12 +172,9 @@ def _sync_agent_compression_with_config(sid: str, session: dict) -> None:def _apply_pending_model_switch(sid: str, session: dict) -> None:- """Apply a model switch queued (``session["pending_model_switch"]``) while a turn was running.-- Runs on the TURN thread at turn start — nothing in flight — so the in-place swap (client rebuild)- is safe. A failed switch keeps the current model and never blocks the turn, matching- ``_sync_agent_model_with_config``.- """+ """Apply a model switch queued (``session["pending_model_switch"]``) while a turn was running. Runs on+ the TURN thread at turn start — nothing in flight — so the in-place swap (client rebuild) is safe. A+ failed switch keeps the current model and never blocks the turn."""pending = session.pop("pending_model_switch", None)if not pending or session.get("agent") is None:return@@ -218,13 +203,10 @@ def _compress_session_history(before_messages: list | None = None, history_version: int | None = None,) -> tuple[int, dict]:"""Single choke point for all manual-compress routes (session.compress RPC, command.dispatch- /compress|/compact, slash-exec mirror).-- ``focus_topic`` is the RAW argument string after ``/compress``, parsed HERE (not per-route) with- :func:`parse_partial_compress_args` so boundary forms (``here [N]``, ``up to here``, ``--keep N``)- trigger a partial compress on EVERY route — otherwise "/compress here 3" would run a FULL compress- focused on the literal text "here 3". Mirrors cli.py ``_manual_compress`` / gateway slash_commands.- """+ /compress|/compact, slash-exec mirror). ``focus_topic`` is the RAW argument string after+ ``/compress``, parsed HERE (not per-route) so boundary forms (``here [N]``, ``up to here``,+ ``--keep N``) trigger a partial compress on EVERY route — otherwise "/compress here 3" would run a+ FULL compress focused on the literal text "here 3"."""from agent.conversation_compression import finalize_context_engine_compression_notificationfrom agent.model_metadata import estimate_request_tokens_roughfrom hermes_cli.partial_compress import (@@ -287,14 +269,11 @@ def _compress_session_history(def _sync_session_key_after_compress(sid: str, session: dict, *, clear_pending_title: bool = True, restart_slash_worker: bool = True) -> None:- """Re-anchor the gateway-side ``session_key`` when _compress_context rotates ``agent.session_id``- to a SessionDB continuation; otherwise approval routing, slash worker init, DB title/history- lookups and yolo state keep targeting the ended parent.-- clear_pending_title: True for manual /compress (title belongs to the old session); False for- post-turn auto-compression so pending_title applies to the continuation.- restart_slash_worker: True unless the caller manages the worker (it holds the stale key).- """+ """Re-anchor the gateway-side ``session_key`` when _compress_context rotates ``agent.session_id`` to+ a SessionDB continuation; otherwise approval routing, slash worker init, DB title/history lookups+ and yolo state keep targeting the ended parent. ``clear_pending_title``: True for manual /compress+ (title belongs to the old session), False for post-turn auto-compression. ``restart_slash_worker``:+ False only when the caller manages the worker (it holds the stale key)."""agent = session.get("agent")new_session_id = getattr(agent, "session_id", None) or ""old_key = session.get("session_key", "") or ""