Files
hermes-agent/tui_gateway/contracts/sessions.py
T
Siddharth Balyan ee2f5629b8 Desktop connect runs on the connection operation: one card, no link to the model, no renderer polling (NS-868) (#110574)
* refactor(connectors): cut comments that restate the code

Connector modules (tools/connectors, tui_gateway connector RPCs, desktop
connector card/store) keep only comments that carry a non-derivable why or
a cross-module contract. No behaviour change.

* feat(connectors): managed connect runs on the connection operation

Managed `connect` / `reconnect` mint one ConnectionOperation for every target and, on a
desktop session, block the tool turn until the operation settles; the result is per-target
outcomes and never carries a connect link. Off the desktop the result carries the links and
returns at once (PR3 delivers them as their own message).

Why: the previous leg handed the model a URL and a `wait` verb, and the renderer ran its own
2s poller on top of the backend's 5s one; both walked the whole gateway catalog at two vendor
calls per page to read one row (~3 Composio calls/s per pending target). A hidden composer
message started the model's `wait` on the user's behalf. None of it was observable from the
operation the MCP leg already used.

What the operation looks like now:
- `contract.py`: TargetState / Actor / SettleReason enums and the `(kind, from) -> {to: actor}`
  transition table. `operation.transition()` enforces it; a card cannot claim a managed
  target `connected`, only the backend watcher can.
- `live.py`: one open operation per session, found by `op_id`. `connectors.operation.status`
  reads it, `connection.respond` drives it, `pending_connection` on resume replays it.
- `run.py`: the one lifecycle for both target kinds (prepare -> card -> wake/observe loop ->
  settle -> result). The managed `observe` hook polls the gateway list once per tick for the
  whole operation; the exact-status route replaces that call when the gateway ships it.
- `connection.update` is emitted on every transition and on settlement; registered in the
  shared event contract with the operation vocabulary typed on the TS side.
- `wait`, `_rendered_links`, `_seen_instructions`, the just-minted bounce and `_clamp_timeout`
  are deleted. `force` on `reconnect` always reinitiates; plain `reconnect` repairs only what
  the gateway reports disconnected.
- `connections.wait_timeout_seconds` is removed from config defaults, the example and the
  docs. The deadline is `OPERATION_DEADLINE_SECONDS = 300` in `operation.py`; the key was
  added on this unmerged train so no migration is needed.
- Wire model: `statusReason` parsed on connection results; the seven-state `connectionStatus`
  is typed on list items and an unknown value fails validation; `CONNECTION_REQUIRED` carries
  `connect_card_available` instead of the link when the session platform is `desktop`.

Session platform, not callback presence, decides whether a card exists: the GUI bridge
attaches callbacks to every backend session, terminal TUI included.

* feat(desktop): connector card subscribes to the connection operation

The card renders from the backend's operation instead of driving its own: `connector-flow.ts`
(the renderer's 2s `connectors.list` poller, its 120s client deadline and `keepWaiting`) is
deleted, and both hidden composer submits in `connector-tool.tsx` go with it. The model is
never nudged into a `wait`; the tool call is blocked on the backend until the operation
settles.

- `connection-request.ts` is the operation store: keyed by `op_id`, one entry per session,
  `applyOperationStatus` / `applyConnectionUpdate` as pure reducers, `respond` leaves the
  entry in place (the backend answers with `connection.update`), `ConnectionTargetOutcome`
  is a discriminated union the backend's transition table accepts.
- `input-requests.ts` applies `connection.update`; `connection.expire` and the resume
  snapshot correlate by `op_id` (a snapshot has no `request_id`).
- `ConnectorOffer` renders one `ConnectorCard` per target from a single
  `Record<ConnectionTargetState, phase>` table; Connect opens the stored link, Try again on
  failed / expired reissues through `connectors.connect` on the open operation, Not now is a
  per-target `skipped`, Continue settles. A settled operation renders `ConnectorSummary` rows
  with no live control.
- `tool-render-class.ts`: `manage_connections` renders the card regardless of
  `HERMES_GUEST_ONBOARDING`; the flag still gates the onboarding flow, not the card. The
  backend gate already decided admission; a card only exists because the tool was admitted.
- `mcp-setup-tool.tsx` speaks the same outcome vocabulary (connected / skipped / failed).
- `ConnectorRow.connectionStatus` is the seven-state literal union, not `string | null`.
- The guided-onboarding poller (`first-build-connectors.ts`) keeps its own row/phase types
  and compiles unchanged; PR3 moves it onto the operation.

anti-slop: no net-new findings (17 touched files vs 11d1a12472).

* fix(connectors): the card never parks the tool thread; every update carries the snapshot

Found by the pre-PR adversarial review and a real-path E2E test (both left in the tree).

- The desktop `connection_callback` was still `_block("connection.request", ...)`, which parked
  the tool thread on a private request-id Event until a `_respond` that no longer exists for
  this event. `connection.respond` settled the operation but the tool waited its full deadline
  before the watcher loop even started. The callback now only emits the card; the operation's
  own wake loop is the wait. The MCP leg's blocking bridge goes with it: the card answers
  through `connection.respond` like every other card.
- `connection.request` and every `connection.update` frame carry the full target snapshot
  (state, link, detail). The initial mint happened before the card existed, so the renderer
  never saw the links and Connect stayed disabled; a Continue settlement stamped
  `not_connected` on the backend while the card still showed `initiated`. The store now
  overlays the snapshot; no state is reconstructed from deltas.
- The `connection.update` emitter is a class-level `on_change` slot on the operation, set
  once by `register()` (a second `register()` no longer stacks wrappers); session lookup takes
  `_sessions_lock`; a re-minted link on an `initiated` target goes through `refresh_link()`
  and emits, instead of a bare attribute write.
- `session.interrupt` is checked before the first observe, so an interrupted call settles
  `interrupt`, not `all_resolved`.
- A gateway list reporting `expired` for an initiated target is recorded with actor `clock`
  (the contract's owner of that edge); it raised `IllegalTransition` before.
- Dead `keepWaiting` i18n keys from the deleted renderer poller removed.

tests/tui_gateway/test_connector_operation_e2e.py runs the desktop lifecycle through the real
tool, registry, gateway RPC handlers and callback bridge with only the HTTP client faked.

* docs(connectors): prompts and docs describe the operation, not the deleted wait verb

The onboarding prompts told the model to call action="wait" with timeout_seconds and to
expect a hidden [setup]/[connectors] note; both are gone. tool-search.md and
toolsets-reference.md said the model gets a connect link on the desktop. tui_gateway/AGENTS.md
gains the connection-operation row of the surface table.

* fix(connectors): the panel re-mints only a dead link

Try again on a failed or expired target mints a fresh link on the open operation. A waiting
target keeps the link it was minted with; the card reopens it and connectors.connect refuses
to spend a second mint (LINK_STILL_VALID). The unused refresh_link() goes. The package
docstring names the new siblings; the nine-name public surface is unchanged.

* test(connectors): the local-batch test answers the operation the way the card does

The callback stopped returning an answer in f782b26d98 (the card answers through
connection.respond); this test still returned one and waited out the 300s deadline in CI.

* ci: retrigger

* fix(connectors): the desktop card appears outside guided onboarding

Live on a signed-in macOS desktop, the two-app connect never showed a card. Three
defects, each hidden by a test that bound state the running app never binds.

The backend read the surface from HERMES_SESSION_PLATFORM only. The desktop and TUI
gateway bind it as HERMES_SESSION_SOURCE (_set_session_context), so session_platform()
was "" and managed connects took the off-desktop branch: links in the model's message,
no operation. session_platform() now reads platform, then source. The E2E test binds
through server._set_session_context instead of set_session_vars(platform="desktop").

The renderer routed manage_connections to the card only under isOnboardingEnabled(),
the HERMES_GUEST_ONBOARDING launch flag, in message-parts.tsx and the run splitter in
fallback.tsx. tool-render-class.ts had already dropped that gate in this PR; the two
routers had not. Both now route on the tool name alone.

ConnectorTool resolved the session owner by the runtime id. Owner routes, hints and
session rows are keyed by the stored id, so in registry topology the owner never
resolved and the card rendered null while the tool blocked. It now resolves by the
stored id, matching the PR1.5 card and every other owner lookup.

message-parts-connectors.test.tsx mounts the real Fallback router with the onboarding
flag off and distinct runtime/stored ids; red before each renderer fix, green after.

* style(connectors): shorter comments, no module mock in the card router test

The router test mocked isOnboardingEnabled to false; jsdom has no preload bridge, so the
real function already returns false. Comments that restated the code are cut to one line.

anti-slop: no net-new findings (25 touched files)

* fix(connectors): Connect on a waiting row opens the stored link

ConnectorCard derived the button's loading state from the phase label, so a managed row that
read "Finish connecting in your browser" (every row, since links are minted up front) had a
disabled Connect button. Nothing on the desktop could open the sign-in link; every managed
connect ended skipped, not_connected, or at the deadline.

The card now takes `busy` for "the action itself is running" and keeps `phase` as a label.
The MCP card passes its in-flight flag; the connector card passes the re-mint wait. Red before:
the Connect button on an initiated row rendered disabled and a click opened nothing.

* fix(connectors): a settled card stays dead; the card binds to its tool call only

A second connect for the same apps revived the finished card on the old tool row. The
connection.request payload carried no id, so the renderer fell back to matching rows by
connector names, and any row with those names qualified, settled or not.

The operation now records the model's tool_call_id and sends it in connection.request and in
the resume snapshot. The card binds to the tool row with that id and to nothing else; the
name-match fallback is deleted. A payload without the id is rejected by the store.

`reason` is removed from the tool: it was the only text the card ever showed from the model
and its absence forked a second tool part, since `reason` doubled as the row-correlation key
in tool-parts.ts. The card never needed it.

`connection.expire` is deleted from the contract and from _EXPIRING_REQUESTS: the card is
raised with _emit, not _block, so nothing has emitted it since the operation lifecycle landed.

Sid's rule of record: a resolved card is fully dead; no path brings it back.

* fix(connectors): the watch loop settles once, on time, and never raises into the result

Three findings from the live review, one loop.

Continue racing a finished sign-in: the loop ran the gateway read, then settled. A read that
returned `connected` for an already-settled or failed target raised IllegalTransition out of
the tool and the model got a generic error instead of the per-app outcomes. The read now skips
targets that are not live (pending, initiated) and skips a settled operation; the loop checks
`settled` after every read.

Settle reason as row text: `settle()` wrote `continue`/`deadline` into each unresolved target's
`detail`, and the card printed it in red. The reason stays on the operation only.

Stop and the deadline waited for the next tick: `/stop` sets a per-thread flag with no wake
hook, so the sleep is sliced at 250 ms and the flag and clock are read each slice. The clock is
also checked before each read, not only after.

Tests: a failed mint that later reads connected settles cleanly; Continue during a read keeps
the settled result; no reason in detail; an interrupt settles within the same second.

* fix(connectors): MCP setup off the desktop returns unavailable instead of blocking

run_mcp_operation treated a non-None connection_callback as "a card exists". Every tui_gateway
session has that callback, the Ink TUI included, so an MCP install from the terminal UI blocked
until the 300 s deadline while the docs promised `unavailable` with the terminal commands.

The MCP path now reads the session surface the same way the managed path does; the callback is
never the predicate. Test binds the surface to `tui` with the callback attached.

* fix(connectors): a failed Try again shows the failure, not the old dead link

The panel's re-mint ignored the gateway's per-app status and moved the row to `initiated` with
whatever link came back, `None` included, so a mint that failed again rendered as waiting on the
link that had already died.

One reader of a mint response now serves both the first mint and Try again
(`managed.mint`, with the actor as a parameter). A repeated failure keeps the row `failed`,
drops the link, and carries the vendor's new text through `operation.refresh`, which emits a
frame without a state change so the card redraws.

* fix(connectors): a forced reconnect waits for the new sign-in before it reports connected

`reconnect` with `force: true` is the account switch. The vendor keeps the old account active
while the new link waits, so the first list read after the mint said `connected` and the
operation settled at once: the new link was dropped and the model was told the switch was done.

A forced target is marked awaiting_new_attempt after the mint. The watcher ignores its row until
the list shows the new attempt (`connectionStatus: initiated`) once, then trusts `connected`.

* fix(connectors): the operation registers under the gateway session key

The tool registered the operation under the agent's session_id; every RPC (connection.respond,
connectors.operation.status, the panel's connectors.connect) and the update emitter looked it up
by the gateway's session key. Those agree until compaction rotates the agent id mid-turn; then
the card's clicks find nothing, no update reaches it, and the tool waits out the deadline.

The registration key is now the bound HERMES_SESSION_KEY, with the agent id as the fallback for
callers with no gateway (unit tests, a bare CLI). The E2E passes a rotated agent id and drives
the card by the gateway key.

* fix(connectors): the forced-reconnect gate reads any non-active row; a failed re-mint of an expired row is failed

Three follow-ups from the verification of the fix pass.

The awaiting_new_attempt gate cleared only on the literal `connectionStatus: initiated`. The
field is optional on the wire and `initializing`, `failed`, `expired` are valid values, so a
forced reconnect could wait the full 300 s and swallow a failed new attempt. The gate now holds
only while the row still reads as the old account (`connected` or `active`) and releases on
anything else.

Try again on an `expired` row whose re-mint fails raised IllegalTransition (no expired → failed
edge). The re-mint steps through `initiated` as the user's attempt, then `failed`, then drops the
dead link.

`detail` never carries a state name any more: `failed` as detail rendered as the row label and
made agent/display.py tag the settled result as a tool error. Only vendor text goes there.

`connection.expire` removed from the renderer's unscoped-stream set; nothing emits it.
2026-09-15 00:41:14 +05:30

677 lines
21 KiB
Python

"""Session lifecycle contracts (``tui_gateway/methods_session.py``): create / resume / activate /
close, the live-session snapshot those share, history + compression + undo, mid-turn corrections,
listing/browsing stored rows, spawn-tree snapshots, event replay and the stateless one-shot LLM call.
"""
from __future__ import annotations
from pydantic import Field
from .base import JsonValue, Params, Result, WireEnum
from .common import (OpenModel, PendingApproval, ProfileParams, SessionLiveInfo, SessionParams, TranscriptMessage,
Usage)
from .connectors_operation import ConnectionRequestPayload
from .registry import method
# ── shared live-session snapshot ──────────────────────────────────────────────────────────────
class OpenRequestEntry(Result):
"""One unanswered server→client request (``server_requests.Request.snapshot``); the reconnecting
client re-delivers it to its request handlers."""
id: str
method: str
params: dict[str, JsonValue]
class InflightTurn(Result):
"""``session_auto_continue._inflight_snapshot``: the live (or retained failed) turn a reconnecting
client rebuilds its bubbles from."""
assistant: str = ""
streaming: bool = False
user: str = ""
corrections: list[str] | None = None
correction_offsets: list[int] | None = None
error: str | None = None
status: str | None = None
recoverable: bool | None = None
error_surface: dict[str, JsonValue] | None = None
class QueuedPrompt(Result):
user: str
class TodoState(Result):
"""``tool_progress._normalize_todo_state``: the authoritative todo snapshot."""
todos: list[dict[str, JsonValue]]
revision: int
class AutoContinue(Result):
"""A crash-interrupted turn was scheduled to continue right after this resume."""
attempt: int
interrupted_at: float
class LiveSessionStatus(WireEnum):
idle = "idle"
starting = "starting"
waiting = "waiting"
working = "working"
streaming = "streaming" # lazy watch window whose child run is active
resuming = "resuming" # deferred hydration in flight
class LiveSessionSnapshot(Result):
"""Union of ``server._live_session_payload``, ``methods_session._resume_response`` and the
live-unpersisted resume path; keys only some paths produce are optional."""
session_id: str
message_count: int
messages: list[TranscriptMessage]
info: SessionLiveInfo
stored_session_id: str | None = None
resumed: str | None = None
session_key: str | None = None
messages_omitted: bool | None = None
hydrating: bool | None = None
running: bool | None = None
turn_started_at: float | None = None
started_at: float | None = None
status: str | None = None # a LiveSessionStatus value
inflight: InflightTurn | None = None
queued: QueuedPrompt | None = None
pending_approval: PendingApproval | None = None
open_requests: list[OpenRequestEntry] | None = None
# The open connection operation (``tools/connectors/live.current``) as its ``connection.request``
# payload: the card restores with the server's deadline after a reconnect or restart.
pending_connection: ConnectionRequestPayload | None = None
todo_state: TodoState | None = None
auto_continue: AutoContinue | None = None
# ── session.create ────────────────────────────────────────────────────────────────────────────
class SeedMessage(Params):
"""One create-time transcript row (``session_history._coerce_seed_history``); ``text`` is the
legacy alias of ``content``; only ``display_kind: "hidden"`` is accepted from the wire. Clients
forward stored rows verbatim (``_row_id``, ``timestamp``, …) and the coercer drops what it does
not use, so the row stays open."""
model_config = Params.model_config | {"extra": "allow"}
role: str
content: str | None = None
text: str | None = None
display_kind: str | None = None
class SessionCreateParams(ProfileParams):
cols: int | None = None
source: str | None = None
cwd: str | None = None
messages: list[SeedMessage] | None = None
parent_session_id: str | None = None
title: str | None = None
model: str | None = None
provider: str | None = None
reasoning_effort: str | None = None
fast: bool | None = None # presence is the contract: omitted inherits, true pins priority, false pins normal
close_on_disconnect: bool = False
hidden: bool = False
room_plumbing: bool = False
follow_profile_config: bool = False
class SessionCreateResult(Result):
session_id: str
stored_session_id: str
message_count: int
messages: list[TranscriptMessage]
info: SessionLiveInfo
method("session.create", params=SessionCreateParams, result=SessionCreateResult,
doc="Mint a live session (agent builds after the reply); a DB row appears on the first prompt unless seeded.")
# ── session.resume / activate ─────────────────────────────────────────────────────────────────
class SessionResumeParams(SessionParams):
"""``session_id`` is the STORED id (or an exact title); the reply's ``session_id`` is the runtime id."""
cols: int | None = None
source: str | None = None
lazy: bool = False
defer_history: bool = False
omit_messages: bool = False
eager_build: bool = False
close_on_disconnect: bool = False
class SessionResumeResult(LiveSessionSnapshot):
pass
method("session.resume", params=SessionResumeParams, result=SessionResumeResult,
doc="Attach to a stored session: reuse it if live here, else lazy / deferred / cold / eager rebuild.")
class SessionActivateParams(SessionParams):
cols: int | None = None # sent by the desktop; the handler keeps the session's current width
omit_messages: bool = False
class SessionActivateResult(LiveSessionSnapshot):
pass
method("session.activate", params=SessionActivateParams, result=SessionActivateResult,
doc="Attach the frontend to a live session without closing the previously focused one.")
# ── listing ───────────────────────────────────────────────────────────────────────────────────
class SessionListParams(ProfileParams):
title: str | None = None # exact-title lookup (title as identity); windowless
limit: int | None = None
include_hidden: bool = False
class SessionListRow(Result):
"""``methods_session._session_row_summary``; ``resolved_id`` only on a title lookup that followed a
compression lineage to its tip."""
id: str
resolved_id: str | None = None
title: str = ""
preview: str = ""
started_at: float = 0
message_count: int = 0
source: str = ""
class SessionListResult(Result):
sessions: list[SessionListRow]
method("session.list", params=SessionListParams, result=SessionListResult,
doc="Human-facing stored sessions, most recent first (sub-agent / kanban sources denied).")
class SessionMostRecentParams(ProfileParams):
pass
class SessionMostRecentResult(Result):
session_id: str | None
title: str | None = None
started_at: float | None = None
source: str | None = None
method("session.most_recent", params=SessionMostRecentParams, result=SessionMostRecentResult,
doc="Most recent human-facing session; errors fold into a null session_id.")
class SessionActiveListParams(ProfileParams):
current_session_id: str | None = None
class SessionActiveItem(Result):
"""``server._session_live_item``."""
current: bool
id: str
last_active: float
message_count: int
model: str
preview: str
session_key: str
started_at: float
status: LiveSessionStatus
title: str
class SessionActiveListResult(Result):
sessions: list[SessionActiveItem]
method("session.active_list", params=SessionActiveListParams, result=SessionActiveListResult,
doc="Live sessions in this process, insertion order (not a DB browser).")
# ── stored-row mutation ───────────────────────────────────────────────────────────────────────
class SessionDeleteParams(SessionParams):
"""``session_id`` is the STORED id."""
class SessionDeleteResult(Result):
deleted: str
method("session.delete", params=SessionDeleteParams, result=SessionDeleteResult,
doc="Delete a stored session + transcripts; refused while it is live here.")
class SessionTitleParams(SessionParams):
title: str | None = None # absent: read; present: set (non-empty)
class SessionTitleResult(Result):
title: str
session_key: str | None = None
pending: bool | None = None # True: no row yet, applied on the first turn
method("session.title", params=SessionTitleParams, result=SessionTitleResult,
doc="Read or set a live session's title; a title set before the row exists is queued.")
class SessionSetHiddenParams(Params):
"""``session_id`` is a live runtime id first, else a stored id / key / title."""
session_id: str
hidden: bool = True
profile: str | None = None
class SessionSetHiddenResult(Result):
hidden: bool
session_key: str
method("session.set_hidden", params=SessionSetHiddenParams, result=SessionSetHiddenResult,
doc="Set/clear hidden (out of the default list, still resumable by its owner) on a session + lineage.")
class SessionWorkspaceMoveParams(ProfileParams):
session_key: str
cwd: str
class SessionWorkspaceMoveResult(Result):
cwd: str
branch: str | None = None
git_repo_root: str | None = None
method("session.workspace.move", params=SessionWorkspaceMoveParams, result=SessionWorkspaceMoveResult,
doc="Re-home a stored session's workspace; git identity is replaced and a live agent follows.")
class SessionCwdSetParams(SessionParams):
cwd: str
class SessionCwdSetResult(SessionLiveInfo):
"""The refreshed ``session.info`` view (full agent view, or the lazy shape)."""
method("session.cwd.set", params=SessionCwdSetParams, result=SessionCwdSetResult,
doc="Change a live, idle session's working directory.")
# ── live-session lifecycle ────────────────────────────────────────────────────────────────────
class SessionCloseParams(SessionParams):
pass
class SessionCloseResult(Result):
closed: bool # False when the runtime id was already gone
method("session.close", params=SessionCloseParams, result=SessionCloseResult,
doc="Tear down a live session (its stored row stays resumable).")
class SessionBranchParams(SessionParams):
name: str | None = None
count: int | None = None # keep only the first N rows of the source history
class SessionBranchResult(Result):
session_id: str
stored_session_id: str
title: str
parent: str
message_count: int
messages: list[TranscriptMessage]
info: SessionLiveInfo
method("session.branch", params=SessionBranchParams, result=SessionBranchResult,
doc="Fork a live session into a new stored child that shares the parent's history so far.")
class SessionUndoParams(SessionParams):
pass
class SessionUndoResult(Result):
removed: int
method("session.undo", params=SessionUndoParams, result=SessionUndoResult,
doc="Drop the last user turn (and everything after it) from an idle session.")
class SessionSaveParams(SessionParams):
pass
class SessionSaveResult(Result):
"""Under turn isolation the compute host's result passes through verbatim."""
file: str | None = None
model_config = Result.model_config | {"extra": "allow"}
method("session.save", params=SessionSaveParams, result=SessionSaveResult,
doc="Export the transcript to ~/.hermes/sessions/saved (classic /save).")
class SessionStatusParams(SessionParams):
pass
class SessionStatusResult(Result):
output: str
method("session.status", params=SessionStatusParams, result=SessionStatusResult,
doc="Rendered /status text for the session.")
class SessionHistoryParams(SessionParams):
pass
class SessionHistoryResult(Result):
count: int
messages: list[TranscriptMessage]
method("session.history", params=SessionHistoryParams, result=SessionHistoryResult,
doc="The durable display transcript (ancestors included, row ids attached).")
class SessionUsageParams(SessionParams):
pass
class SessionUsageResult(Usage):
credits_lines: list[str] | None = None
method("session.usage", params=SessionUsageParams, result=SessionUsageResult,
doc="Token / context / cost counters for the session (+ Nous credit lines when available).")
class SessionContextBreakdownParams(SessionParams):
pass
class ContextCategory(Result):
color: str
id: str
label: str
tokens: int
class SessionContextBreakdownResult(Result):
"""``agent.context_breakdown.compute_session_context_breakdown`` (empty categories before the agent builds)."""
categories: list[ContextCategory]
context_max: int
context_percent: int
context_used: int
estimated_total: int
context_estimated: bool
context_source: str
model: str
method("session.context_breakdown", params=SessionContextBreakdownParams, result=SessionContextBreakdownResult,
doc="Cursor-style split of the context window by category.")
# ── compression ───────────────────────────────────────────────────────────────────────────────
class CompressionSummary(OpenModel):
"""``agent.manual_compression_feedback.summarize_manual_compression``."""
noop: bool = False
aborted: bool = False
refused_would_grow: bool | None = None
fallback_used: bool | None = None
headline: str = ""
token_line: str = ""
note: str | None = None
class SessionCompressParams(SessionParams):
focus_topic: str | None = None
class SessionCompressResult(Result):
"""In-process: the before/after summary + replacement transcript. Compute host: its result passes
through (hence open) with ``turn_isolation``; a lock held elsewhere answers ``compressed: false``."""
status: str | None = None # compressed | aborted | pending
removed: int | None = None
before_messages: int | None = None
after_messages: int | None = None
before_tokens: int | None = None
after_tokens: int | None = None
summary: CompressionSummary | None = None
usage: Usage | None = None
info: SessionLiveInfo | None = None
messages: list[TranscriptMessage] | None = None
compressed: bool | None = None
lock_held: bool | None = None
message: str | None = None
turn_isolation: bool | None = None
host_ack: dict[str, JsonValue] | None = None
model_config = Result.model_config | {"extra": "allow"}
method("session.compress", params=SessionCompressParams, result=SessionCompressResult,
doc="Manual /compress of an idle session, optionally focused on a topic.")
# ── interrupt / steer / redirect ──────────────────────────────────────────────────────────────
class SessionInterruptParams(SessionParams):
expected_hosted_task_id: str | None = None # only interrupt if this hosted task is the running one
class InterruptStatus(WireEnum):
interrupted = "interrupted"
not_interrupted = "not_interrupted"
class SessionInterruptResult(Result):
status: InterruptStatus
interrupted: bool | None = None
turn_isolation: bool | None = None
method("session.interrupt", params=SessionInterruptParams, result=SessionInterruptResult,
doc="Stop the running turn (and streaming TTS); retires the crash-recovery marker.")
class CorrectionStatus(WireEnum):
queued = "queued"
redirected = "redirected"
rejected = "rejected"
class SessionCorrectionParams(SessionParams):
text: str
class SessionCorrectionResult(Result):
status: CorrectionStatus
text: str
method("session.steer", params=SessionCorrectionParams, result=SessionCorrectionResult,
doc="Inject text into the next tool result without interrupting the turn.")
method("session.redirect", params=SessionCorrectionParams, result=SessionCorrectionResult,
doc="Redirect the active turn (queued for the next turn while the agent is still building).")
# ── spawn trees ───────────────────────────────────────────────────────────────────────────────
class SpawnTreeSaveParams(ProfileParams):
subagents: list[dict[str, JsonValue]]
session_id: str | None = None # stored key; "default" when absent
started_at: float | None = None
finished_at: float | None = None
label: str | None = None
class SpawnTreeSaveResult(Result):
path: str
session_id: str
method("spawn_tree.save", params=SpawnTreeSaveParams, result=SpawnTreeSaveResult,
doc="Persist a finished delegation tree snapshot under the session's spawn-trees dir.")
class SpawnTreeListParams(ProfileParams):
session_id: str | None = None
cross_session: bool = False
limit: int | None = None
class SpawnTreeEntry(OpenModel):
"""Index row (``server._append_spawn_tree_index``) or a legacy file scan."""
path: str
session_id: str | None = None
started_at: float | None = None
finished_at: float | None = None
label: str = ""
count: int = 0
class SpawnTreeListResult(Result):
entries: list[SpawnTreeEntry]
method("spawn_tree.list", params=SpawnTreeListParams, result=SpawnTreeListResult,
doc="Saved spawn-tree snapshots, newest first.")
class SpawnTreeLoadParams(ProfileParams):
path: str
class SpawnTreeLoadResult(Result):
"""The snapshot file as written by ``spawn_tree.save`` (open: the file is the contract)."""
session_id: str | None = None
started_at: float | None = None
finished_at: float | None = None
label: str | None = None
subagents: list[dict[str, JsonValue]] = Field(default_factory=list)
model_config = Result.model_config | {"extra": "allow"}
method("spawn_tree.load", params=SpawnTreeLoadParams, result=SpawnTreeLoadResult,
doc="Read one saved spawn-tree snapshot (path must be under the spawn-trees root).")
# ── terminal / event replay ───────────────────────────────────────────────────────────────────
class TerminalResizeParams(SessionParams):
cols: int | None = None
class TerminalResizeResult(Result):
cols: int
method("terminal.resize", params=TerminalResizeParams, result=TerminalResizeResult,
doc="Record the client's column width for server-side rendering.")
class SessionEventsSinceParams(SessionParams):
last_seen: int | None = None
class SessionEventsSinceResult(Result):
events: list[dict[str, JsonValue]] # recorded event frames' ``params`` objects
latest_seq: int
truncated: bool
count: int
epoch: str
open_requests: list[OpenRequestEntry]
method("session.events.since", params=SessionEventsSinceParams, result=SessionEventsSinceResult,
doc="Replay events after a seq watermark on WS reconnect; truncated means refetch state.")
class SessionEventsStatsParams(ProfileParams):
pass
class SessionEventsStatsResult(Result):
"""``event_replay.replay_stats``."""
sessions: int
events: int
bytes: int
max_per_session: int
max_bytes_per_session: int
max_bytes_process: int
method("session.events.stats", params=SessionEventsStatsParams, result=SessionEventsStatsResult,
doc="Replay-buffer occupancy telemetry (ops/debug).")
# ── one-shot LLM ──────────────────────────────────────────────────────────────────────────────
class LlmOneshotParams(ProfileParams):
"""Needs a ``template`` or ``instructions`` / ``input``; a live ``session_id`` lends its model."""
template: str | None = None
instructions: str | None = None
input: str | None = None
variables: dict[str, JsonValue] | None = None
task: str | None = None
temperature: float | None = None
max_tokens: int | None = None
session_id: str | None = None
class LlmOneshotResult(Result):
text: str
method("llm.oneshot", params=LlmOneshotParams, result=LlmOneshotResult,
doc="Stateless one-shot LLM completion (titles, ideas) on the session's or the task backend.")