Skip to content

The agent that grows with you

Merge remote-tracking branch 'origin/main' into fix/106742-thread-resolution

teknium1caa329904c6e
diff --cc apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
index 8bc60e6f692,f1f18ea115f..7b670bad73f
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
@@@ -1,9 -2,7 +2,8 @@@ import { SLASH_COMMAND_RE } from '@herm
import { type RefObject, useLayoutEffect, useRef } from 'react'
import { usePaneVisible } from '@/components/pane-shell/pane-visibility'
- import { SLASH_COMMAND_RE } from '@/lib/chat-runtime'
import { triggerHaptic } from '@/lib/haptics'
+import type { BusyInputMode } from '@/store/busy-input-mode'
import { hasClarifyRequest, skipClarifyRequest } from '@/store/clarify'
import { clearSessionDraft, type ComposerAttachment } from '@/store/composer'
import { resetBrowseState } from '@/store/composer-input-history'
diff --cc apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts
index 01c29fdc5d1,1c2ff50b63d..f83164c63cd
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts
@@@ -1,6 -1,6 +1,7 @@@
+ import type { GatewayEvent } from '@hermes/shared'
import type { HermesSkin } from '@hermes/shared/skin'
+import { eventSourceMatchesOwner, gatewayEventSource } from '@/lib/replay-gap-owner'
import {
notifyCronChanged,
notifyPairingChanged,
diff --cc apps/desktop/src/app/session/hooks/use-message-stream/steer-arrival-order.test.tsx
index 3d09a11d2ad,893d8a8c5e5..487b64fff4d
--- a/apps/desktop/src/app/session/hooks/use-message-stream/steer-arrival-order.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/steer-arrival-order.test.tsx
@@@ -25,8 -24,6 +26,8 @@@ import { usePromptActions } from '@/app
import type { ClientSessionState } from '@/app/types'
import { chatMessageText } from '@/lib/chat-messages'
import { createClientSessionState } from '@/lib/chat-runtime'
+import { setSessionTileDelegate } from '@/store/session-states'
- import type { RpcEvent } from '@/types/hermes'
++
import { STREAM_DELTA_FLUSH_MS } from './utils'
diff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
index 5d8bd74ada1,63d346a5914..ceeb3ccdded
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
@@@ -3,12 -5,10 +5,11 @@@ import { stripAnsi } from '@hermes/shar
import { useStore } from '@nanostores/react'
import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'
+import { hermesApi } from '@/api/client'
import { transcribeAudio } from '@/hermes'
import { useI18n } from '@/i18n'
- import { stripAnsi } from '@/lib/ansi'
import { type ChatMessage, textPart } from '@/lib/chat-messages'
- import { pathLabel, SLASH_COMMAND_RE } from '@/lib/chat-runtime'
+ import { pathLabel } from '@/lib/chat-runtime'
import { sanitizeComposerInput } from '@/lib/composer-input-sanitize'
import { triggerHaptic } from '@/lib/haptics'
import { setMutableRef } from '@/lib/mutable-ref'
diff --cc apps/desktop/src/app/settings/config-settings.test.tsx
index e6c61996a47,fb42ea448ae..8060c781cc8
--- a/apps/desktop/src/app/settings/config-settings.test.tsx
+++ b/apps/desktop/src/app/settings/config-settings.test.tsx
@@@ -3,10 -3,10 +3,12 @@@ import { cleanup, render, screen } fro
import { atom } from 'nanostores'
import { createRef } from 'react'
import { MemoryRouter } from 'react-router'
- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+ import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+
+ import type { ConfigSettings as ConfigSettingsType } from './config-settings'
+import { ConfigSettings } from './config-settings'
+
const getHermesConfigRecord = vi.fn()
const getHermesConfigSchema = vi.fn()
const saveHermesConfig = vi.fn()
diff --cc apps/desktop/src/store/composer-queue.ts
index 09fe55cf7f8,09e64832b84..b4b6f8fc577
--- a/apps/desktop/src/store/composer-queue.ts
+++ b/apps/desktop/src/store/composer-queue.ts
@@@ -1,22 -1,6 +1,21 @@@
+ import { SLASH_COMMAND_RE } from '@hermes/shared'
import { atom } from 'nanostores'
- import { SLASH_COMMAND_RE } from '@/lib/chat-runtime'
-
+import { $connection } from './session'
+import { knownOwnerForSession } from './session-states'
+
+/** Local owner routes use canonical admission; remote legacy queues stay local. */
+export function serverOwnsComposerQueue(sessionId: string | null | undefined): boolean {
+ const owner = knownOwnerForSession(sessionId)
+
+ if (owner && typeof owner === 'object' && owner.mode) { return owner.mode === 'local' }
+ const connection = $connection.get()
+
+ if (owner && typeof owner === 'object' && owner.connectionId !== connection?.connectionId) { return false }
+
+ return Boolean(connection?.wsUrl && new URL(connection.wsUrl).searchParams.has('native_dial'))
+}
+
import type { ComposerAttachment } from './composer'
export interface QueuedPromptEntry {
diff --cc apps/shared/src/gateway-events.ts
index 00000000000,e6d26aed34c..e7f4535539e
mode 000000,100644..100644
--- a/apps/shared/src/gateway-events.ts
+++ b/apps/shared/src/gateway-events.ts
@@@ -1,0 -1,767 +1,781 @@@
+ /**
+ * Wire types for `tui_gateway` JSON-RPC notifications and the RPC responses the
+ * TypeScript surfaces (Ink TUI, Desktop, web dashboard) share.
+ *
+ * Every notification arrives as `{jsonrpc: '2.0', method: 'event', params: GatewayEvent}`
+ * (`tui_gateway/server.py::_event_frame`). `GatewayEventMap` is the single map from
+ * event `type` to payload shape; `BACKEND_EVENT_NAMES` mirrors the emitter side and is
+ * pinned to `gateway-events.json` by `gateway-events.test.ts` (vitest) and
+ * `tests/tui_gateway/test_gateway_event_contract.py` (Python), so a name added on one
+ * side without the other fails a test instead of drifting silently.
+ *
+ * Payload interfaces are typed from the Python emitters (file::symbol noted per
+ * interface). Events whose payload no TS client reads yet are `Record<string, unknown>`;
+ * they still MUST be keys so `on('x', …)` stays exhaustive.
+ */
+ import type { BillingBlock } from './billing-types.js'
+ import type { HermesSkin } from './skin.js'
+
+ // ── Shared value shapes ──────────────────────────────────────────────
+
+ /** `tui_gateway/server.py::_get_usage` — a session's token/cost counters. */
+ export interface Usage {
+ active_subagents?: number
+ /** Rolling mean API latency over the last 10 calls (seconds). */
+ avg_latency_s?: number
+ /** Rolling output tokens/sec over the last 10 calls. */
+ avg_tps?: number
+ /** Session prompt-cache hit ratio (cache_read / prompt tokens, %). Omitted (not 0)
+ * when the provider reports no cache reads. */
+ cache_hit_pct?: number
+ cache_read?: number
+ cache_write?: number
+ calls: number
+ compressions?: number
+ context_max?: number
+ context_percent?: number
+ context_estimated?: boolean
+ context_source?: string
+ context_used?: number
+ cost_status?: string
+ cost_usd?: number
+ dev_credits_spent_micros?: number
+ input: number
+ output: number
+ reasoning?: number
+ total: number
+ }
+
+ /** Advisory `{layer, code, retryable}` descriptor (`agent/error_surface.py`). */
+ export interface ErrorSurface {
+ code?: string
+ layer?: string
+ retryable?: boolean
+ }
+
+ /** `tui_gateway/tool_progress.py::_normalize_todo_state` — full task snapshot. */
+ export interface TodoStatePayload {
+ revision?: number
+ todos?: unknown[]
+ }
+
+ export type SubagentStatus = 'completed' | 'error' | 'failed' | 'interrupted' | 'queued' | 'running' | 'timeout'
+
+ /** `tui_gateway/tool_progress.py::_progress_subagent` — every `subagent.*` frame. */
+ export interface SubagentEventPayload {
+ api_calls?: number
+ /** The child's own gateway session id — the key a watch window mirrors. */
+ child_session_id?: string
+ /** Batch (delegation) id this subagent belongs to — distinguishes
+ * interleaved `[n/N]` progress from concurrent or nested fan-outs. */
+ delegation_id?: string
+ depth?: number
+ duration_seconds?: number
+ files_read?: string[]
+ files_written?: string[]
+ goal: string
+ input_tokens?: number
+ model?: string
+ output_tail?: { is_error?: boolean; preview?: string; tool?: string }[]
+ output_tokens?: number
+ parent_id?: null | string
+ reasoning_tokens?: number
+ status?: SubagentStatus
+ subagent_id?: string
+ summary?: string
+ task_count?: number
+ task_index: number
+ text?: string
+ tool_count?: number
+ tool_name?: string
+ tool_preview?: string
+ toolsets?: string[]
+ }
+
+ // ── Event payloads ───────────────────────────────────────────────────
+
+ /** `tui_gateway/entry.py` (stdio) / `tui_gateway/ws.py` (WebSocket) first frame. */
+ export interface GatewayReadyPayload {
+ /** Backends with the change watcher broadcast `*.changed` events; consumers
+ * demote their legacy polls to slow backstops. */
+ change_events?: boolean
+ /** WebSocket transport only: the server answers heartbeat pings. */
+ heartbeat?: boolean
+ /** Opaque token for this server process's `seq` numbering; a new epoch means
+ * replay watermarks must be discarded. */
+ replay_epoch?: string
+ skin?: HermesSkin
+ }
+
+ /** `tui_gateway/prompt_turn.py::_complete_turn_payload` and
+ * `tui_gateway/session_auto_continue.py::_emit_terminal_turn_error`. */
+ export interface MessageCompletePayload {
+ /** Structured billing wall when the turn failed with FailoverReason.billing. */
+ billing?: BillingBlock
+ /** `status: "error"` — the failure message (`text` may be streamed output). */
+ error?: string
+ error_surface?: ErrorSurface
+ failure_reason?: string | null
+ /** `status: "error"` — `text` is streamed partial output to keep, not the error string. */
+ partial?: boolean
+ reasoning?: string
+ /** `status: "error"` — the failed turn was retained and replays via `session.resume.inflight`. */
+ recoverable?: boolean
+ rendered?: string
+ /** The final text was already previewed via `message.interim`; settle, don't duplicate. */
+ response_previewed?: boolean
+ status?: 'complete' | 'error' | 'interrupted' | string
+ text?: string
+ usage?: Usage
+ /** History-commit note (e.g. a mid-turn desync the gateway surfaced instead of dropping). */
+ warning?: string
+ }
+
+ /** `tui_gateway/tool_progress.py::_on_tool_start`. */
+ export interface ToolStartPayload {
+ /** Full tool arguments — the 80-char `context` preview is display-only. */
+ args?: Record<string, unknown>
+ /** Verbose mode only: pretty-printed args. */
+ args_text?: string
+ context?: string
+ name?: string
+ /** Mirrored child tool rows carry a short preview instead of args. */
+ preview?: string
+ tool_id: string
+ /** Not on the wire (`_on_tool_start` never sets it): the todo snapshot rides `tool.complete` /
+ * `todo.updated`. Kept because the TUI handler reads it and its fixtures exercise that path. */
+ todos?: unknown[]
+ }
+
+ /** `tui_gateway/tool_progress.py::_on_tool_complete`. */
+ export interface ToolCompletePayload {
+ args?: Record<string, unknown>
+ duration_s?: number
+ inline_diff?: string
+ name?: string
+ /** Parsed JSON when the tool returned JSON, else the raw string. */
+ result?: unknown
+ /** Verbose mode only. */
+ result_text?: string
+ revision?: number
+ summary?: string
+ tool_id: string
+ todos?: unknown[]
+ }
+
+ export interface ToolGeneratingPayload {
+ name?: string
+ }
+
+ /** `tui_gateway/tool_progress.py::_progress_output_risk`. */
+ export interface ToolOutputRiskPayload {
+ findings?: string[]
+ name?: string
+ redacted?: boolean
+ risk?: string
+ tool_id?: string
+ }
+
+ export interface StatusUpdatePayload {
+ kind?: string
+ text?: string
+ }
+
+ export interface NotificationShowPayload {
+ id?: string
+ key?: string
+ kind?: 'sticky' | 'ttl' | string
+ level?: 'error' | 'info' | 'success' | 'warn' | string
+ text?: string
+ ttl_ms?: null | number
+ }
+
+ export interface NotificationClearPayload {
+ key?: string
+ }
+
+ export interface TextPayload {
+ text?: string
+ }
+
+ /** `message.delta` / `reasoning.delta` / `reasoning.available` / `thinking.delta`. */
+ export interface StreamDeltaPayload {
+ rendered?: string
+ text?: string
+ /** Verbose reasoning mode is on for this session. */
+ verbose?: boolean
+ }
+
+ export interface MessageInterimPayload {
+ already_streamed?: boolean
+ text: string
+ }
+
+ export interface SessionUsagePayload {
+ usage?: Usage
+ }
+
+ export interface SessionTitlePayload {
+ session_id?: string
+ title?: string
+ }
+
+ /** `tui_gateway/methods_session.py` resume hydration progress. */
+ export interface SessionResumeProgressPayload {
+ message?: string
+ message_count?: number
+ phase?: string
+ status?: 'complete' | 'failed' | 'loading' | string
+ }
+
+ /** `tui_gateway/session_lifecycle.py::_announce_session_reclaimed`. */
+ export interface SessionReclaimedPayload {
+ reason?: string
+ session_id?: string
+ stored_session_id?: string
+ }
+
+ export interface SessionControlUpdatePayload {
+ control?: unknown
+ }
+
+ export interface ErrorPayload {
+ message?: string
+ reason?: string
+ }
+
+ export interface NoticePayload {
+ message?: string
+ }
+
+ export interface ReactionPayload {
+ kind?: string
+ }
+
+ export interface BillingStepUpVerificationPayload {
+ user_code?: string
+ verification_url: string
+ }
+
+ export interface VoiceStatusPayload {
+ state?: 'idle' | 'listening' | 'transcribing' | string
+ }
+
+ export interface VoiceTranscriptPayload {
+ no_speech_limit?: boolean
+ stop_phrase?: boolean
+ text?: string
+ typed?: boolean
+ voice_stopped?: boolean
+ }
+
+ export interface WakeDetectedPayload {
+ phrase?: string
+ profile?: null | string
+ start_new_session?: boolean
+ }
+
+ export interface BrowserProgressPayload {
+ level?: 'error' | 'info' | 'warn' | string
+ message?: string
+ }
+
+ export interface MoaReferencePayload {
+ count?: number
+ index?: number
+ label?: string
+ text?: string
+ }
+
+ export interface MoaAggregatingPayload {
+ aggregator?: string
+ }
+
+ export interface MoaProgressPayload {
+ label?: string
+ refs_done?: number
+ refs_total?: number
+ }
+
+ export interface MoaPhasePayload {
+ aggregator?: string
+ phase?: string
+ refs_done?: number
+ refs_total?: number
+ }
+
+ // Blocking bridges (`tui_gateway/server.py::_block`): every `*.request` carries a
+ // `request_id`; the matching `*.expire` names the same id when the wait timed out.
+
+ export interface RequestExpirePayload {
+ request_id: string
+ }
+
+ export interface ClarifyQuestion {
+ choices?: null | string[]
+ multi_select?: boolean
+ qid: string
+ question: string
+ }
+
+ export interface ClarifyRequestPayload {
+ answers?: Record<string, string>
+ choices?: null | string[]
+ multi_select?: boolean
+ question?: string
+ questions?: ClarifyQuestion[]
+ request_id: string
+ }
+
+ /** `tui_gateway/server.py::_approval_request_payload` (command redacted server-side). */
+ export interface ApprovalRequestPayload {
+ allow_permanent?: boolean
+ choices?: string[]
+ command: string
+ description: string
+ request_id?: string
+ smart_denied?: boolean
+ }
+
+ export interface SudoRequestPayload {
+ request_id: string
+ }
+
+ export interface SecretRequestPayload {
+ env_var: string
+ prompt: string
+ request_id: string
+ }
+
+ export interface VaultUnlockRequestPayload {
+ backend: string
+ display_name: string
+ request_id: string
+ }
+
+ export interface VaultCodeRequestPayload {
+ hint?: string
+ request_id: string
+ site?: string
+ }
+
+ export interface McpSetupRequestPayload {
+ action?: string
+ reason?: string
+ request_id: string
+ server?: string
+ }
+
+ /** Side agents (`tui_gateway/methods_prompt.py::_spawn_side_agent`). */
+ export interface SideAgentCompletePayload {
+ question?: string
+ task_id: string
+ text: string
+ }
+
+ export interface PreviewRestartProgressPayload {
+ task_id: string
+ text: string
+ }
+
+ export interface TerminalOutputPayload {
+ chunk?: string
+ process_id?: string
+ }
+
+ export interface TerminalClosePayload {
+ process_id?: string
+ }
+
+ // ── The map ──────────────────────────────────────────────────────────
+
+ /**
+ * Backend-emitted notification names. Derived from the `tui_gateway` emitter call
+ * sites and pinned to `gateway-events.json`; keep sorted. Adding a name here without
+ * the JSON (or vice versa) fails `gateway-events.test.ts`, and a Python emitter that
+ * names an event missing from the JSON fails `test_gateway_event_contract.py`.
+ */
+ export const BACKEND_EVENT_NAMES = [
+ 'agent.terminal.output',
+ 'approval.request',
+ 'background.complete',
+ 'billing.step_up.verification',
+ 'bot_relay.outbox.pending',
+ 'browser.controller.cancel',
+ 'browser.controller.command',
+ 'browser.progress',
+ 'btw.complete',
+ 'clarify.expire',
+ 'clarify.request',
+ 'cron.changed',
+ 'error',
+ 'gateway.ready',
+ 'layout.apply',
+ 'mcp.setup.expire',
+ 'mcp.setup.request',
+ 'message.complete',
+ 'message.delta',
+ 'message.interim',
+ 'message.reaction',
+ 'message.start',
+ 'moa.aggregating',
+ 'moa.phase',
+ 'moa.progress',
+ 'moa.reference',
+ 'notice',
+ 'notification.clear',
+ 'notification.show',
+ 'pairing.changed',
+ 'pane.reveal',
+ 'pet.changed',
+ 'pet.generate.progress',
+ 'pet.hatch.progress',
+ 'platforms.changed',
+ 'preview.act.expire',
+ 'preview.act.request',
+ 'preview.close',
+ 'preview.open',
+ 'preview.read.expire',
+ 'preview.read.request',
+ 'preview.restart.complete',
+ 'preview.restart.progress',
+ 'reaction',
+ 'reasoning.available',
+ 'reasoning.delta',
+ 'review.summary',
+ 'secret.expire',
+ 'secret.request',
+ 'session.control.update',
+ 'session.info',
+ 'session.reclaimed',
+ 'session.resume_progress',
+ 'session.title',
+ 'session.usage',
+ 'sessions.changed',
+ 'setup.ready',
+ 'skin.changed',
+ 'status.update',
+ 'subagent.complete',
+ 'subagent.progress',
+ 'subagent.spawn_requested',
+ 'subagent.start',
+ 'subagent.thinking',
+ 'subagent.tool',
+ 'sudo.expire',
+ 'sudo.request',
+ 'terminal.close',
+ 'terminal.read.expire',
+ 'terminal.read.request',
+ 'thinking.delta',
+ 'tip.show',
+ 'todo.updated',
+ 'tool.complete',
+ 'tool.generating',
+ 'tool.output_risk',
+ 'tool.start',
+ 'tour.expire',
+ 'tour.request',
+ 'vault.code.expire',
+ 'vault.code.request',
+ 'vault.save_login.expire',
+ 'vault.save_login.request',
+ 'vault.unlock.expire',
+ 'vault.unlock.request',
+ 'voice.interrupted',
+ 'voice.status',
+ 'voice.transcript',
+ 'wake.detected',
+ 'window.read.expire',
+ 'window.read.request'
+ ] as const satisfies readonly (keyof BackendGatewayEventMap)[]
+
+ export type BackendGatewayEventName = (typeof BACKEND_EVENT_NAMES)[number]
+
+ /** Payload per backend-emitted notification `type`. Keys are exactly `BACKEND_EVENT_NAMES`. */
+ export interface BackendGatewayEventMap {
+ 'agent.terminal.output': TerminalOutputPayload
+ 'approval.request': ApprovalRequestPayload
+ 'background.complete': SideAgentCompletePayload
+ 'billing.step_up.verification': BillingStepUpVerificationPayload
+ 'bot_relay.outbox.pending': Record<string, unknown>
+ 'browser.controller.cancel': Record<string, unknown>
+ 'browser.controller.command': Record<string, unknown>
+ 'browser.progress': BrowserProgressPayload
+ 'btw.complete': SideAgentCompletePayload
+ 'clarify.expire': RequestExpirePayload
+ 'clarify.request': ClarifyRequestPayload
+ 'cron.changed': Record<string, unknown>
+ error: ErrorPayload
+ 'gateway.ready': GatewayReadyPayload
+ 'layout.apply': Record<string, unknown>
+ 'mcp.setup.expire': RequestExpirePayload
+ 'mcp.setup.request': McpSetupRequestPayload
+ 'message.complete': MessageCompletePayload
+ 'message.delta': StreamDeltaPayload
+ 'message.interim': MessageInterimPayload
+ 'message.reaction': Record<string, unknown>
+ 'message.start': undefined
+ 'moa.aggregating': MoaAggregatingPayload
+ 'moa.phase': MoaPhasePayload
+ 'moa.progress': MoaProgressPayload
+ 'moa.reference': MoaReferencePayload
+ notice: NoticePayload
+ 'notification.clear': NotificationClearPayload
+ 'notification.show': NotificationShowPayload
+ 'pairing.changed': Record<string, unknown>
+ 'pane.reveal': Record<string, unknown>
+ 'pet.changed': Record<string, unknown>
+ 'pet.generate.progress': Record<string, unknown>
+ 'pet.hatch.progress': Record<string, unknown>
+ 'platforms.changed': Record<string, unknown>
+ 'preview.act.expire': RequestExpirePayload
+ 'preview.act.request': Record<string, unknown>
+ 'preview.close': Record<string, unknown>
+ 'preview.open': Record<string, unknown>
+ 'preview.read.expire': RequestExpirePayload
+ 'preview.read.request': Record<string, unknown>
+ 'preview.restart.complete': SideAgentCompletePayload
+ 'preview.restart.progress': PreviewRestartProgressPayload
+ reaction: ReactionPayload
+ 'reasoning.available': StreamDeltaPayload
+ 'reasoning.delta': StreamDeltaPayload
+ 'review.summary': TextPayload
+ 'secret.expire': RequestExpirePayload
+ 'secret.request': SecretRequestPayload
+ 'session.control.update': SessionControlUpdatePayload
+ /** Surface-specific shape (`tui_gateway/server.py::_session_info`); each client narrows. */
+ 'session.info': Record<string, unknown>
+ 'session.reclaimed': SessionReclaimedPayload
+ 'session.resume_progress': SessionResumeProgressPayload
+ 'session.title': SessionTitlePayload
+ 'session.usage': SessionUsagePayload
+ 'sessions.changed': Record<string, unknown>
+ 'setup.ready': Record<string, unknown>
+ 'skin.changed': HermesSkin
+ 'status.update': StatusUpdatePayload
+ 'subagent.complete': SubagentEventPayload
+ 'subagent.progress': SubagentEventPayload
+ 'subagent.spawn_requested': SubagentEventPayload
+ 'subagent.start': SubagentEventPayload
+ 'subagent.thinking': SubagentEventPayload
+ 'subagent.tool': SubagentEventPayload
+ 'sudo.expire': RequestExpirePayload
+ 'sudo.request': SudoRequestPayload
+ 'terminal.close': TerminalClosePayload
+ 'terminal.read.expire': RequestExpirePayload
+ 'terminal.read.request': Record<string, unknown>
+ 'thinking.delta': StreamDeltaPayload
+ 'tip.show': Record<string, unknown>
+ 'todo.updated': TodoStatePayload
+ 'tool.complete': ToolCompletePayload
+ 'tool.generating': ToolGeneratingPayload
+ 'tool.output_risk': ToolOutputRiskPayload
+ 'tool.start': ToolStartPayload
+ 'tour.expire': RequestExpirePayload
+ 'tour.request': Record<string, unknown>
+ 'vault.code.expire': RequestExpirePayload
+ 'vault.code.request': VaultCodeRequestPayload
+ 'vault.save_login.expire': RequestExpirePayload
+ 'vault.save_login.request': Record<string, unknown>
+ 'vault.unlock.expire': RequestExpirePayload
+ 'vault.unlock.request': VaultUnlockRequestPayload
+ 'voice.interrupted': Record<string, unknown>
+ 'voice.status': VoiceStatusPayload
+ 'voice.transcript': VoiceTranscriptPayload
+ 'wake.detected': WakeDetectedPayload
+ 'window.read.expire': RequestExpirePayload
+ 'window.read.request': Record<string, unknown>
+ }
+
+ /**
+ * Client-local synthetic events. Never emitted by `tui_gateway`; the Ink TUI's
+ * `gatewayClient` publishes them into the same handler stream to report transport
+ * state. Excluded from `gateway-events.json` on purpose.
+ */
+ export interface ClientLocalGatewayEventMap {
+ 'dashboard.new_session_requested': { reason?: string }
+ 'gateway.protocol_error': { preview?: string }
+ 'gateway.reconnecting': { attempt?: number; delay_ms?: number }
+ 'gateway.start_timeout': { cwd?: string; python?: string; stderr_tail?: string }
+ 'gateway.stderr': { line: string }
++ /** Synthetic on the client (a reconnect replay could not cover the gap: epoch changed /
++ * ring truncated) AND emitted by canonical gateways on fanout overflow
++ * (`gateway/session_events.py`); consumers re-resume the session for a snapshot. */
++ 'session.replay_gap': { latest_seq?: number; replay_epoch?: string }
+ }
+
+ export interface GatewayEventMap extends BackendGatewayEventMap, ClientLocalGatewayEventMap {}
+
+ export type GatewayEventName = keyof GatewayEventMap
+
+ /** One `event` notification's `params`. */
+ export interface GatewayEvent<K extends GatewayEventName = GatewayEventName> {
+ /** Registry connection whose socket delivered the event (renderer-side tag;
+ * absent for the local/legacy primary path). */
+ connectionId?: string
++ /** Owner execution stamp on canonical gateways: the integer runtime epoch and the claimed
++ * generation, spread onto the params beside `type`/`payload` (`gateway/session_events.py`). */
++ authority_epoch?: number
++ execution_generation?: number
++ /** Session-scoped replay generation on canonical gateways. */
++ replay_epoch?: string
+ payload?: GatewayEventMap[K]
+ /** Renderer-side source tag added by the Desktop gateway registry. */
+ profile?: string
+ /** Per-session monotonic counter stamped by `tui_gateway/event_replay.py::_stamp_event`;
+ * absent on session-less broadcasts. */
+ seq?: number
+ session_id?: string
+ type: K
+ }
+
+ // ── RPC responses shared across surfaces ─────────────────────────────
+
+ /** `hermes_cli/inventory.py` one `model.options` provider row (union of every field the
+ * backend sets; `pricing_pending` / `free_tier_pending` mark the cached-only fail-closed path). */
+ export interface ModelOptionProvider {
+ /** User-defined providers only: every accepted identity for this endpoint
+ * (bare config key, `custom:<key>`, normalized display name, …). A session's
+ * `model.options` reports the canonical `custom:<key>` form, so "is this row
+ * the current provider?" must check membership here, not slug equality. */
+ aliases?: string[]
+ /** OpenAI-compatible endpoint for a user-defined provider. The backend
+ * exposes this as `api_url`; model assignments send it back as `base_url`. */
+ api_url?: string
+ /** Auth flow for an unconfigured provider: "api_key" can be activated inline
+ * by pasting `key_env`; anything else (oauth_*, external, aws_sdk, …) needs
+ * the `hermes model` CLI / onboarding OAuth flow. */
+ auth_type?: string
+ /** True when the provider has usable credentials. False for canonical
+ * providers surfaced by `include_unconfigured` that the user hasn't set up
+ * yet — render these with a setup affordance instead of hiding them. */
+ authenticated?: boolean
+ /** Per-model option support, keyed by model id (present when the picker
+ * requested capabilities). Lets the UI gate fast/reasoning controls. */
+ capabilities?: Record<string, ModelCapabilities>
+ /** Curated shortlist (one flagship per lab) the picker shows by default for
+ * aggregator providers that serve dozens of models across many labs. */
+ featured_models?: string[]
+ /** Nous only: whether the current account is on the free plan. */
+ free_tier?: boolean
+ /** Nous only, cached-only inventory: entitlement unknown, every model rendered locked. */
+ free_tier_pending?: boolean
+ /** True for the free-tier route's own provider row (no account behind it).
+ * Never match this row by `name` — the label is copy and can change. */
+ free_tier_row?: boolean
+ is_current?: boolean
+ /** True for providers defined via the user's `providers:` config block. */
+ is_user_defined?: boolean
+ /** Env var to paste an API key into, for unconfigured `api_key` providers. */
+ key_env?: string
+ models?: string[]
+ name: string
+ /** Per-model pricing keyed by model id (present when the picker requested
+ * pricing and the provider supports live pricing). */
+ pricing?: Record<string, ModelPricing>
+ /** Cached-only inventory: pricing not fetched yet. */
+ pricing_pending?: boolean
+ slug: string
+ source?: string
+ total_models?: number
+ /** Nous only: paid models a free-tier user cannot select (shown disabled). */
+ unavailable_models?: string[]
+ warning?: string
+ }
+
+ export interface ModelPricing {
+ /** Formatted $/Mtok cached-input price, or null when the model has none. */
+ cache: null | string
+ /** Sale: rounded percent off list when gateway sends pricing.original. */
+ discount_percent?: number
+ /** True when the model costs nothing (free tier eligible). */
+ free: boolean
+ /** Formatted $/Mtok input price, e.g. "$3.00", or "free", or "" if unknown. */
+ input: string
+ /** Formatted $/Mtok output price. */
+ output: string
+ /** Sale: formatted pre-discount input $/Mtok ("was"). */
+ was_input?: string
+ /** Sale: formatted pre-discount output $/Mtok ("was"). */
+ was_output?: string
+ }
+
+ export interface ModelCapabilities {
+ /** False when the route rejects a reasoning disable ("mandatory" in the
+ * provider catalog), so the Thinking toggle must not be offered. */
+ can_disable_reasoning?: boolean
+ fast: boolean
+ reasoning: boolean
+ }
+
+ export interface ModelOptionsResponse {
+ model?: string
+ provider?: string
+ providers?: ModelOptionProvider[]
+ }
+
+ /** `tui_gateway/methods_session.py::_session_row_summary` — one `session.list` row. */
+ export interface SessionListItem {
+ id: string
+ message_count: number
+ preview: string
+ /** The runtime id this stored session is currently attached to, when live. */
+ resolved_id?: string
+ source?: string
+ started_at: number
+ title: string
+ }
+
+ export interface SessionListResponse {
+ sessions?: SessionListItem[]
+ }
+
+ /** Transcript row as projected by the gateway (`session.resume` / `session.activate`). */
+ export interface GatewayTranscriptMessage {
+ args?: unknown
+ context?: string
+ display_kind?: string
+ display_metadata?: unknown
+ name?: string
+ role: 'assistant' | 'system' | 'tool' | 'user'
+ text?: string
+ }
+
+ export interface SessionInflightTurn {
+ assistant?: string
+ correction_offsets?: number[]
+ corrections?: string[]
+ error?: string
+ error_surface?: ErrorSurface
+ recoverable?: boolean
+ status?: string
+ streaming?: boolean
+ user?: string
+ }
+
+ /** `tui_gateway/methods_session.py::_resume_response`. `info` is surface-specific
+ * (`SessionInfo` in the TUI, `SessionRuntimeInfo` on Desktop); narrow at the call site. */
+ export interface SessionResumeResponse<Info = Record<string, unknown>, Message = GatewayTranscriptMessage> {
+ /** Present when the backend found a fresh crash-interrupted turn and scheduled its
+ * automatic continuation; the turn arrives as a normal message.start stream. */
+ auto_continue?: { attempt: number; interrupted_at: number }
+ /** Deferred hydration: history arrives via `session.resume_progress`. */
+ hydrating?: boolean
+ inflight?: null | SessionInflightTurn
+ info?: Info
+ message_count?: number
+ messages: Message[]
+ /** `omit_messages` resume: the client still learns the stored size. */
+ messages_omitted?: boolean
+ resumed?: string
+ running?: boolean
+ session_id: string
+ session_key?: string
+ started_at?: number
+ status?: string
++ /** Canonical gateways: the durable id of the row this live session projects. */
++ stored_session_id?: string
++ /** Canonical gateways: the actor's subscription token for `session.detach`. */
++ subscription_id?: string
+ todo_state?: TodoStatePayload
+ }
diff --cc apps/shared/src/json-rpc-gateway.ts
index 21dc9559521,48bb2acf818..ce6410c0464
--- a/apps/shared/src/json-rpc-gateway.ts
+++ b/apps/shared/src/json-rpc-gateway.ts
@@@ -151,8 -124,6 +124,7 @@@ export class JsonRpcGatewayClient
* silently believe nothing was missed.
*/
private replayEpoch: string | null = null
+ private replayEpochBySession = new Map<string, string>()
- private readonly eventHandlers = new Map<string, Set<(event: GatewayEvent) => void>>()
private readonly stateHandlers = new Set<(state: ConnectionState) => void>()
private readonly options: Required<Omit<GatewayClientOptions, 'socketFactory'>> &
Pick<GatewayClientOptions, 'socketFactory'>
@@@ -513,10 -397,8 +398,10 @@@
*/
private recordSeq(event: GatewayEvent): void {
const sid = event.session_id
- const seq = (event as { seq?: unknown }).seq
+ const seq = event.seq
+ if (sid) { this.adoptSessionReplayEpoch(sid, event.replay_epoch) }
+
if (!sid || typeof seq !== 'number' || !Number.isFinite(seq)) {
return
}
@@@ -632,11 -495,8 +517,11 @@@
*/
private dispatchIfNewer(event: GatewayEvent): void {
const sid = event.session_id
- const seq = (event as { seq?: unknown }).seq
+ const seq = event.seq
+ // Parked frames reach here only after the replay window has been applied.
+ if (sid) { this.adoptSessionReplayEpoch(sid, event.replay_epoch) }
+
if (sid && typeof seq === 'number' && Number.isFinite(seq)) {
const prev = this.lastSeenSeq.get(sid) ?? 0
diff --cc cron/jobs.py
index a88ed56db73,6002eb3a471..9b6b7fd7915
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@@ -2317,7 -2366,7 +2385,8 @@@ def mark_job_run
status: Optional[str] = None,
*,
expected_fire_owner: Optional[str] = None,
+ execution_id: Optional[str] = None,
+ model_unreachable: bool = False,
) -> bool:
"""Mark a job as run: update last_run_at/last_status, bump completed, recompute next_run_at,
and retire the record as a terminal completion when the repeat limit is reached.
@@@ -2326,10 -2375,13 +2395,15 @@@
``last_status = "delivery_failed"`` (never "ok") while ``failure_streak`` is left alone. An
explicit ``status`` (e.g. "blocked_config") overrides the derived value. False when the fence
can't be taken, the job is missing, or ``expected_fire_owner`` no longer holds the fire claim.
+
+ ``model_unreachable``: this failed run never reached the model (transient network/DNS error,
+ zero API calls). Recurring jobs then get a bounded automatic re-run — ``next_run_at`` is pulled
+ earlier per ``cron.unreachable_retry.RETRY_DELAYS_SECONDS`` — instead of waiting a full period
+ (Cowork-style; see cron/unreachable_retry.py).
"""
def apply(jobs, _i, job):
+ if execution_id is not None and execution_id in job.get("canonical_completions", []):
+ return True
if expected_fire_owner is not None:
claim = job.get("fire_claim")
if not isinstance(claim, dict) or claim.get("by") != expected_fire_owner:
@@@ -2339,9 -2391,14 +2413,16 @@@
return False
now = _hermes_now().isoformat()
_record_run_outcome(job, success, error, delivery_error, status, now)
+ if execution_id is not None:
+ job.setdefault("canonical_completions", []).append(execution_id)
_advance_after_run(job, now)
+ from cron.unreachable_retry import clear_state, plan_retry
+
+ if not success and model_unreachable and not is_terminal_job(job):
+ plan_retry(job)
+ else:
+ # Any run that reached the model (either outcome) resets the re-run ladder.
+ clear_state(job)
save_jobs(jobs)
return True
diff --cc cron/scheduler.py
index 1702e24a61d,498f2a40abe..54eb2158d6d
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@@ -2764,11 -2749,11 +2795,15 @@@ def _finish_completed_run(d: _RunDelive
from cron.jobs import update_job
update_job(job["id"], {"last_delivery_queued": None})
job["last_delivery_queued"] = None
- mark_kwargs = {"delivery_error": d.delivery_error}
+ mark_kwargs: dict = {"delivery_error": d.delivery_error}
+ from cron.scheduler_authority import journal_path
+ journal = journal_path(job['id'], execution_id)
+ if not job.get('no_agent'):
+ mark_kwargs['execution_id'] = execution_id
+ if not d.success and job.pop("_model_unreachable", False):
+ # Never-reached-the-model failure: schedule the Cowork-style bounded re-run
+ # (cron/unreachable_retry.py) inside the same fenced store write.
+ mark_kwargs["model_unreachable"] = True
if d.success and not d.delivery_error and d.should_deliver and job.get("last_delivery_queued"):
mark_kwargs["status"] = "delivery_queued"
if fire_owner is not None:
diff --cc evals/shared_gateway/worker-constructor-context-wave20.md
index f98a55ff00f,00000000000..eb0ca565666
mode 100644,000000..100644
--- a/evals/shared_gateway/worker-constructor-context-wave20.md
+++ b/evals/shared_gateway/worker-constructor-context-wave20.md
@@@ -1,76 -1,0 +1,76 @@@
+# Worker constructor context — wave 20 (partial migration)
+
+This extends `worker-persistence-substrate.md`; it does **not** enable the legacy
+compute-host, cron-agent, or delegated-child constructors as migrated workers.
+Those consumers still have unsupported operations in the Q1 inventory.
+
+## Implemented
+
+- `session.context`: assigned-session snapshot, resolved content-addressed system
+ prompt, with the same epoch/generation/sequence/receipt fence as worker mutations.
+ Read receipts are replayable snapshots, not a promise to refresh an old receipt.
+- `session.prompt`: content-addressed prompt update and GC inside the receipt transaction.
+- `session.sidecars`: merge only `_usage_anchor` / `_proactive_prune_rearm_tokens`;
+ no arbitrary model-config, lineage, credential, or identity mutation.
+- Concrete store getters restore title, compression cooldown/raw cooldown, fallback
+ streak, ineffective count and recovery deadline before context-engine binding.
+- A successful **self** registration/adoption through `WorkerRPC` marks that
+ interpreter as a worker before AIAgent imports. The marker is process-scoped so
+ fresh helper threads cannot perform owner-only delegation recovery.
+- `async_delegation` leaves recovery/delivery queues with the ordinary owner and
+ refuses direct worker ledger opens. Its actual dispatch/finish/delivery SQL has
+ **not** been migrated to typed RPC.
+- Existing child/cron opener seams refuse registered-worker fallback to writable
+ `SessionDB` or persistence-disabled `None`. Ordinary unregistered callers keep
+ their existing behavior. These are migration fences, not working child/cron RPC.
+
+The process marker is cooperative ownership, not an OS sandbox. Arbitrary Python,
+raw SQLite, plugins, and unrelated SessionDB constructors are not confined by it.
+No environment credential scrubbing, toolset changes, prompt-prefix rewrites,
+profile policy changes, new daemon, or new worker table is introduced.
+
+## Live proof
+
+`tests/gateway/test_worker_agent_execution.py` runs an ordinary `gateway.run`
+subprocess plus a separate interpreter constructing and executing the real AIAgent
+with `RuntimeSessionStore`, against an owned loopback HTTP/SSE model fixture.
+It verifies one model request, actual user/assistant rows, persisted system prompt,
+10 input / 5 output tokens, terminal worker receipt, released turn lease, zero
+canonical SQLite connection audit events and zero writable DB/WAL/SHM descriptors.
+The second case calls real child/cron openers and the delegation ledger from a fresh
+helper thread, requires explicit refusal, then executes a real script-only cron
+before the same model inference. This proves rejection and script preservation,
+**not** child or cron agent migration or tool-enabled inference.
+
+`tests/gateway/test_worker_persistence.py` separately retains the substrate's real
+owner-kill, surviving-worker/outbox, stale epoch rejection, adoption and one-time
+usage settlement proof. Lost ACK is a controlled discarded RPC result, not a
+kernel packet-drop claim. It is not an AIAgent interrupted mid-inference restart.
+
- `tests/state/test_runtime_worker_context.py` proves assigned-row isolation,
++`tests/hermes_state/test_runtime_worker_context.py` proves assigned-row isolation,
+sidecar identity preservation, prompt lost-ACK replay and real ContextCompressor
+binding of persisted guards. Missing methods previously silently reset guards.
+
+## Remaining core inventory
+
+AST method-name intersection with the Q1 index: **17 of 51 names**, not 17 complete
+unrestricted SessionDB contracts. Append retains substrate option restrictions;
+sidecar patches are deliberately restricted. The **34 absent names** are:
+
+- `archive_and_compact`, `clear_compression_failure_cooldown`, `clear_session_activity_labels`
+- `create_session`, `declared_scope_identity`, `end_session`, `get_active_message_watermark`
+- `get_compression_lineage`, `get_compression_lock_holder`, `get_compression_tip`
+- `get_conversation_root`, `get_messages_as_conversation`, `get_next_title_in_lineage`
+- `get_session_title_source`, `is_explicit_fork_child`, `latest_conversation_boundary`
+- `publish_compression_child`, `record_compression_failure_cooldown`, `refresh_compression_lock`
+- `release_compression_lock`, `reopen_orphaned_compression_session`, `resolve_resume_session_id`
+- `restore_compression_failure_cooldown_row`, `session_lifecycle_statuses`, `set_auto_title`
+- `set_compression_fallback_streak`, `set_compression_ineffective_count`, `set_compression_recovery_deadline`
+- `set_latest_user_api_content`, `set_session_title`, `set_session_title_source`
+- `touch_session_activity`, `try_acquire_compression_lock`, `update_session_billing_route`
+
+Producer-validated child/cron/Kanban reservation, same-PID authority adapters,
+constructor-time identity backfill, compression assignment advance, raw delegation
+ledger migration, recalled-tool storage reads, legacy compute control/notification
+closure, and deferred finalization remain blockers. Keep all existing consumers
+on their existing paths until those contracts are implemented and exercised.
diff --cc evals/shared_gateway/worker-lifecycle-wave22.md
index da7f8deb1be,00000000000..6ec37eeaa3f
mode 100644,000000..100644
--- a/evals/shared_gateway/worker-lifecycle-wave22.md
+++ b/evals/shared_gateway/worker-lifecycle-wave22.md
@@@ -1,104 -1,0 +1,104 @@@
+# Worker lifecycle extension — wave 22
+
+This is a **parent-composed extension**, not activation of child/cron/legacy-compute
+consumers. The shared adapter and dispatch modules are deliberately unchanged in
+this lane. Tests need the hookups below; uncomposed tests reproduce absent methods.
+
+## Parent hookups (all exercised in the disposable composition)
+
+1. `agent/runtime_session_store.py`: import
+ `RuntimeSessionLifecycleMixin` from `agent.runtime_session_lifecycle` alongside
+ the module imports, and add it to `RuntimeSessionStore`'s bases.
+2. `hermes_state_runtime.py::mutate_worker_execution`: late-import
+ `WORKER_LIFECYCLE_HANDLERS` from `hermes_state_worker_lifecycle`, and unpack it
+ into the existing `handlers` table. Keep `_epoch`, `_worker_assignment`, owner
+ epoch, receipt digest/sequence, terminal status and transaction code unchanged.
+3. `hermes_state_sessions.py::SessionSessionsMixin._insert_session_row`: replace
+ the current function body after its docstring with:
+
+ ```python
+ from hermes_state_worker_lifecycle import insert_session_row_in_transaction
+ params = dict(session_id=session_id, source=source, model=model, model_config=model_config,
+ system_prompt=system_prompt, user_id=user_id, session_key=session_key,
+ chat_id=chat_id, chat_type=chat_type, thread_id=thread_id,
+ parent_session_id=parent_session_id, cwd=cwd, profile_name=profile_name,
+ git_repo_root=git_repo_root, origin_json=origin_json, display_name=display_name)
+ self._execute_write(lambda conn: insert_session_row_in_transaction(self, conn, **params),
+ patience_s=self._TRANSCRIPT_WRITE_PATIENCE_S)
+ ```
+
+ The new helper contains the existing keep-existing/reset-marker upsert body,
+ prompt hash/GC and metadata inheritance. This hookup removes the temporary
+ duplicate body; do not retain two independent constructor implementations.
+
+No new RPC endpoint, SQL RPC, worker registry, receipt table, or service is needed.
+The ordinary `worker.persist` endpoint already forwards the closed operation.
+
+## Contracts
+
+- Concrete methods: `create_session`, `end_session`, `session_lifecycle_statuses`,
+ `set_session_title`, `set_auto_title`, `get_session_title_source`,
+ `set_session_title_source`, `get_next_title_in_lineage`, `touch_session_activity`,
+ `clear_session_activity_labels`, `update_session_billing_route`,
+ `set_latest_user_api_content`.
+- Creation means backfilling an **already reserved** row. A worker cannot choose a
+ new id, source, profile, parent, cwd, routing origin, git identity or display
+ identity. Supplied identity values must match the reserved row; omitted values
+ cannot replace it. Constructor config accepts only the current AIAgent's
+ `max_iterations`, `max_tokens`, `reasoning_config`, `yolo_mode` keys. Arbitrary
+ config/lineage mutation remains unavailable.
+- Keep-existing model/config/prompt semantics reuse the constructor body. The
+ existing `_end_and_bump` preserves first end reason and boundary atomicity.
+ Session end and worker terminal settlement remain distinct.
+- Titles reuse `_set_session_title_in_transaction`, including rank, canonical
+ Bot Chat protection and compression-ancestor transfer. Expected title errors
+ are receipted outcomes, converted back to `ValueError` **after** the local
+ journal is acknowledged, so real title-generator dedupe can proceed.
+ Error messages do not disclose the conflicting session id.
+- Next-title lookup requires the assigned current title or a previous receipted
+ title attempt in its active worker execution. It returns only a candidate,
+ never rows/session ids. Unrelated arbitrary title queries are refused. The
+ lookup is not atomic reservation; the normal setter remains authoritative.
+- Activity remains monotonic and uses the existing description/provenance
+ normalization; clearing labels retains the timestamp. Receipt transactions use
+ the substrate's transcript-write patience, not the local observation-only short
+ patience/no-op fast path. This latency distinction remains for integration.
+- Billing route changes follow preceding durable usage receipts, reject sticky
+ pending failures, and clear/GC the prompt snapshot just like the local method.
+ Main/auxiliary usage logic is unchanged: no inferred/recomputed provider usage.
+- API content stamps only the newest active user row matching encoded content.
+- All operations revalidate assignment/generation/epoch **before receipt replay**.
+ Old finalizers cannot close or relabel a later generation. `close()` remains
+ local outbox release; it neither closes the owner's DB nor settles a worker.
+
+## Proof
+
- `tests/state/test_runtime_worker_lifecycle.py` (two invariants) covers constructor
++`tests/hermes_state/test_runtime_worker_lifecycle.py` (two invariants) covers constructor
+backfill, identity refusal, lifecycle status, lost-ACK end replay, first-end wins,
+and late/foreign end refusal. `test_runtime_worker_metadata.py` (two invariants)
+covers title ranks/activity and exact two-route counters/API content. The title
+retry invariant invokes the real `agent.title_generator._persist_session_title`.
+
+`tests/gateway/test_worker_lifecycle_execution.py` starts ordinary `gateway.run`
+and a separate worker interpreter using the existing loopback SSE model fixture.
+The real AIAgent persists a turn; the worker applies title/activity/API content/
+route/end/finish, then remains alive while a real owner `prompt.submit` executes
+generation 1. Its old generation-0 end/title/clear/route requests are refused.
+Foreign end/title/clear requests are refused. SQLite audit starts before AIAgent
+imports; canonical worker connect events and writable DB/WAL/SHM descriptors are
+both zero. This is a controlled delayed callback, not a timed-out child/cron job.
+
+The composed broad run passed **140 files, 1511 tests, one Windows-only skip**:
+all `tests/state` and `tests/cron`, selected agent title/activity/finalizer/store
+files, current worker-agent integration, the new successor probe, and existing
+worker owner-kill/adoption/outbox coverage. It is not the entire repository suite.
+
+## Not completed by this lane
+
+Producer reservation/migration for child, cron and Kanban; same-PID adapter;
+compression assignment/history/locks (sibling lane); async delegation ledger
+(sibling lane); recall/reaction/raw tool storage and legacy compute controls;
+arbitrary legacy `update_session_meta`; coordinator tracking of outstanding
+background callbacks before terminal settlement. Existing deferred-cleanup code
+was not changed and its cron regression suite remains green. None of these
+consumers should be enabled solely on the strength of this scoped proof.
diff --cc evals/shared_gateway/worker-persistence-inventory.md
index 6ea7b1d52f3,00000000000..afbc62e9644
mode 100644,000000..100644
--- a/evals/shared_gateway/worker-persistence-inventory.md
+++ b/evals/shared_gateway/worker-persistence-inventory.md
@@@ -1,1692 -1,0 +1,1692 @@@
+# Worker persistence consumer inventory (Q1)
+
+## Scope and verdict
+
+Source snapshot: `34407c9ec6ca0922233dc9c8f7cd4070609b0bf1`, worktree
+`ugw-worker-contract-wave15`, branch `docs/ugw-worker-contract-wave15`.
+This is the eval README companion for plan **Q1**, not implementation or a Q2–Q8 acceptance receipt.
+The root and agent/gateway/tools/cron/tui_gateway instructions were read. No production imports,
+user-state access, vendor calls, worker launch, or production edits are required by the census below.
+The plan was read from the parent worktree's
+`.hermes/plans/2026-09-08_031437-unified-gateway-runtime.md`; Q requires an inventory before switching a worker.
+The preceding `worker-gap-wave14.md` was treated as a lead, not source truth.
+
+**Correction to the preceding audit:** the two proposed adapter modules are absent, but
+`hermes_state_runtime.py` already contains `register_worker_execution`, `adopt_worker_execution`,
+`persist_worker_message`, and `finish_worker_execution`, with `worker_executions`/`worker_receipts`.
- A repository search finds their callers only in `tests/state/test_runtime_worker.py` and
- `tests/state/test_runtime_adoption.py`, not gateway/cron/child/compute production.
++A repository search finds their callers only in `tests/hermes_state/test_runtime_worker.py` and
++`tests/hermes_state/test_runtime_adoption.py`, not gateway/cron/child/compute production.
+The text-only primitive is NOT a SessionDB adapter: it accepts only user/assistant/system text,
+not tool rows, structured content, reasoning, sidecars, compression, or usage.
+Reuse its epoch/assignment/sequence/receipt checks; do not implement a second worker registry.
+
+**Switching any full worker is still blocked.** In particular, replacing `agent._session_db`
+alone cannot satisfy zero canonical writable opens:
+
+* `tools/async_delegation.py::_connect` directly opens **canonical `state.db`**, creates/migrates
+ `async_delegations`, and performs dispatch/completion/delivery SQL independently of SessionDB.
+* `tools/process_registry_results.py::_owns_result` opens writable `SessionDB()` for a lineage read.
+* `tools/react_to_message_tool.py::_open_session_db` independently calls registry `acquire()`.
+* `tools/session_search_tool.py::_get_message_storage_state` dereferences `_lock` and `_conn`;
+ its ordinary search paths also reach cross-session/profile data, not just the execution's row.
+* The legacy compute host imports the complete TUI server: `_transfer_db_to_agent` itself calls
+ `_get_db()`, and `_session_db`/`_workdir_owner_db` reopen by profile even with an injected agent store.
+ Its notification poller and slash/control paths enlarge the execution closure.
+
+These are named, actionable blockers, not permission for a generic SQL or method-dispatch RPC.
+The static census establishes the built-in call surface below; it does not prove arbitrary plugins,
+model-chosen tools, runtime rebinding, or dynamically loaded third-party code cannot open state.db.
+
+## 1. Construction and complete turn ordering
+
+1. `run_agent.py::AIAgent.__init__` delegates to `agent/agent_init.py::init_agent`.
+ `_init_session_state` assigns the supplied store and session/parent ids; it does not create a row.
+ `_memory_provider_init_kwargs` reads `get_session_title` (errors suppressed).
+ `_build_context_engine` calls the engine's `bind_session_state`, which for the built-in compressor
+ immediately reads cooldown, fallback streak, ineffective count, recovery deadline and prune runway.
+ Store capability and profile identity must therefore exist **before construction**, not at first append.
+ The constructor also creates ordinary request-log/checkpoint resources; these are not canonical DB writes.
+2. `run_agent.py::_ensure_db_session` calls `create_session` with source/model/model_config/prompt,
+ gateway origin fields, parent id, cwd and explicit profile. `_session_db_created` changes only on
+ non-raising return; errors log and leave it retryable. `_insert_session_row` performs a keep-existing
+ UPSERT with null backfill, parent metadata inheritance and content-addressed system-prompt storage.
+ `create_session` is not permission to choose a new arbitrary session/profile over the wire: the
+ owner reserves the execution's row/parent and validates any allowed mutable metadata.
+3. `agent/turn_facade.py` invokes `admit_durable_turn_lease` before the synchronous conversation loop.
+ `get_session` missing means fresh seed (no lease/reload); a read error means **try the lease**.
+ Concrete-type `acquire_session_turn_lease` availability is inspected, not just instance getattr.
+ Acquire precedes history load. Only if acquisition waited, resolve resume tip and reload messages
+ with `repair_alternation=True, include_row_ids=True`; immediate acquisition preserves cached history.
+ Lease holder/TTL are installed only on success. Failure returns zero-call interrupted/timeout result.
+4. `conversation_loop::_restore_or_build_system_prompt` reads `get_session`; an existing stored
+ system prompt is reused for history. `_persist_system_prompt` writes the assembled snapshot.
+ `prompt_cache_scope` reads compression lineage, fork/source identity and durable conversation boundary;
+ `_conversation_root_id`/`system_prompt::_session_start_like` read the attribution lineage root.
+ These are different identities: delegate children MUST NOT inherit the parent's prompt-cache scope.
+5. `turn_context` ensures the row before auto-title, loads/persists usage anchors, and stamps API-only
+ user content through `set_latest_user_api_content` after a preflight compaction may already have
+ inserted the user row. Match is newest active user row plus encoded content, not arbitrary row id.
+6. `session_persistence::_db_flush_collect` owns serialization/filtering and `_db_flush_write` calls
+ `append_messages_batch` once with structured rows and compression/turn holders. Keep all existing
+ reasoning/Codex/display/platform/timestamp/api_content handling and ephemeral scaffolding filtering.
+ `_DB_PERSISTED_MARKER` and flush cursors are stamped **after successful durable return**, never at
+ send time. `_insert_message_rows` may enrich row dictionaries with persistence identities; a remote
+ adapter must return/apply those row annotations before `sync_flushed_message_markers`, not only count.
+ Tool-round and tool-executor flush failures stop progress; other exit paths also flush.
+7. Main response usage (`turn_usage::record_response_usage`, `codex_runtime::_queue_token_counts`)
+ ensures the row and queues per-route deltas; `_persist_session` appends then calls
+ `flush_token_counts` at every persist point. Auxiliary context is installed around the turn and
+ copied into auxiliary/title work. `aux_accounting::record_aux_usage` and
+ `background_review::_record_review_usage_to_parent` write per-model/task usage to the **parent**;
+ the review fork sets `_persist_disabled=True`, `_session_db=None`, and unbinds its compressor.
+ It must never regain a writable DB through `_get_session_db_for_recall`.
+8. Turn finally stops/cancels renewal timers, clears lease interrupt, releases the admitted holder, then clears activity labels;
+ `DurableTurnLease.release` uses the original id while refresh uses the live compression tip. Existing
+ lease-key resolution keeps them in one logical conversation. Delayed finally/aux/title callbacks
+ need execution-generation fencing as well as a holder check; title rank alone is not fencing.
+9. `run_agent.py::_finalize_owned_session_row` ends the live session unless explicitly disabled, then
+ registry-releases if `_owns_session_db`. `close` must become local adapter release, not an RPC to
+ close the owner's shared connection. Token barrier, session end, worker terminal settlement, and local scope release are distinct
+ operations; terminal settlement must not race outstanding durable mutations. Preserve deferred close for
+ still-running child/cron threads; a caller timeout does not stop a thread or undo its side effects.
+
+## 2. Transaction and error contracts (apply to the operation index)
+
+The exact signatures, source definitions and every detected core consumer are in §7. Defaults below
+refer to the current local SessionDB, not promised remote behavior.
+
+| Operation family | Return/error and transaction/ordering contract |
+|---|---|
+| Ordinary SessionDB writes | `_execute_write` owns `BEGIN IMMEDIATE`, callback result, commit and rollback. It retries the whole callback on classified busy/locked conditions, under bounded patience. IOERR is retried only when BEGIN failed before callback execution; once callback started settlement may be unknown. Inode replacement/corruption guards remain owner-side. Do not call a public self-committing method from inside the receipt transaction: that nests BEGIN and cannot atomically bind mutation to receipt. Extract/reuse its connection-taking body. |
+| `append_messages_batch` | Returns inserted count, 0 for empty. One transaction when `chunk_rows=None` (the core path). Explicit chunking is multiple transactions and partial progress is possible. Reuses `resolve_and_repair_transcript_batch`, `_insert_message_rows`, counters and FTS triggers. Turn-holder loss raises `SessionTurnLeaseLostError`; ended compression parent raises `CompressionSessionClosedError`. Ordinary appends intentionally do NOT reject a foreign compression lock: watermark preservation makes concurrent appends safe. |
+| Agent append wrapper | `True` success, `False` caught persistence failure, `None` when deliberately disabled/no DB. Closed compression parent can adopt a validated live tip and retry exactly once. Replacement/corruption currently diverts JSONL; managed-worker outage must use the private bounded outbox instead, never direct SQLite/fallback transcript adoption. An outbox ACK must not be confused with owner commit when a caller needs row ids, watermarks or committed history. |
+| Session reads | `get_session` returns resolved row dict/None; drains token queue first but ignores a `False` flush timeout, so “exact totals” in its docstring is conditional. Other read errors normally propagate. `get_messages_as_conversation` returns a reconstructed list; repair is in-memory only, and model reads must not include compacted display history. Most lineage methods perform multiple reads, not a snapshot transaction. Compression adoption deliberately confirms tip again after loading. |
+| Turn leases | `try_acquire_session_turn_lease` is an atomic lineage-root walk + claim/reclaim. `acquire_session_turn_lease` is a polling orchestrator, bool on success/abort/deadline; only classified locked SQLite errors retry, other errors propagate. Wait/status/abort callbacks execute locally and are not serializable RPC fields. Refresh returns holder-qualified bool, release returns None/idempotent. Renewal can revive still-owned expired rows, never a successor's row. |
+| Compression leases | Try-acquire and refresh return False on SQLite error (not an authoritative free lock); release logs SQLite errors and returns None. Replaced-handle RuntimeError may still propagate. Compression lock is physical session keyed; turn lease is logical-conversation keyed. `get_compression_lock_holder` is diagnostic, not write authorization. |
+| Compaction | `archive_and_compact` returns new active count; archives/reinserts/foreign-tail clone/model-config merge/counters share one transaction. `lock_holder` is checked there. Watermark captured before summary, `tail_count` prevents searchable duplicate carried tail. Guard loss raises `SessionCompressionInProgressError`; config-patch missing row raises. `micro_compaction` and prune-only use this too; do not support only LLM compaction. |
+| Rotation | `publish_compression_child` returns None; parent close, child row, handoff rows, bounded foreign-tail clone and `advance_local_target` commit together. Lease absence/loss raises `CompressionSessionBusyError`; missing/deliberately ended parent or empty handoff raises RuntimeError. Automatic end stamps may be reopened inside that transaction. Follow-up title/provenance/prompt/engine state writes are currently separate; worker assignment must gain the authorized child atomically with publication before any of them. |
+| Cooldown and anti-thrash | get active cooldown => dict/None (expiry-filtered); raw getter => exact `{session_exists,cooldown_until,error}`. Record merge-maxes deadline, latest diagnostic wins; clear removes both. Record/clear/streak/count/deadline setters use `_write_sql_logged`, swallowing SQLite errors. `restore_compression_failure_cooldown_row` intentionally propagates write/verification errors and rejects restoring a now-existing formerly absent row. A receipt must never certify swallowed failed mutation; reuse strict connection helpers, not these best-effort outer wrappers. Numeric reads use missing/non-numeric fallback, deadline is wall-clock, local waits are monotonic. |
+| Usage queue/barrier | `queue_token_counts` returns None after memory enqueue; after writer stop uses synchronous update (can raise). `_apply_token_batch` logs and discards failed deltas. `flush_token_counts` returns bool/False timeout and does not expose prior dropped-delta failures. Adjacent incremental same-route coalescing only; never merge absolute totals or reorder route switches. For worker mode, durable outbox append precedes ACK; application and receipt must atomically include both session counters and per-model usage. Existing queue return is NOT durable proof. |
+| Billing/aux | `update_token_counts` creates a missing row in a separate transaction, then updates counters and incremental model-usage in one transaction. First accounted route can override requested route; absolute updates do not duplicate per-model deltas. `record_auxiliary_usage` also ensures row separately then records per-(model,provider,task) usage only, NOT session totals; despite “best-effort” docstring its DB exceptions propagate to callers which catch them. `update_session_billing_route` flushes deltas before route update and clearing prompt hash/snapshot; its ignored False barrier must not become successful worker settlement. |
+| Model sidecars | `patch_session_model_config` merges JSON atomically (None deletes; missing/empty no-op). Core keys are `_usage_anchor` and `_proactive_prune_rearm_tokens`; compaction includes the latter in the transcript transaction. `get_session_model_config_value` parses tolerantly with default. RPC must restrict keys to concrete supported sidecars, not arbitrary config mutation. `set_latest_user_api_content` returns 0/1, content-fenced UPDATE. `update_system_prompt` updates content-addressed prompt ownership; keep byte stability except existing permitted boundaries. |
+| Titles | Get title/source returns str/None. `set_auto_title` accepts only derived/llm source, returns False if higher authority won; explicit `set_session_title` has user rank and returns bool, ValueError on validation/conflict. Provenance setter returns whether titled row changed. `get_next_title_in_lineage` searches all titles matching base, not a child-id lineage; lookup is not atomic reservation. Preserve dedupe retry and author rank, but expose an authorized title operation, not a profile-wide arbitrary title query. |
+| Activity | Touch returns None, max timestamp/normalized bounded description/provenance, short write patience; throttled by caller. Clear preserves timestamp and avoids no-op write. Errors are caught by agent callers. For workers, stale generation must not clear successor labels or advertise a revived execution. |
+| End/finalize | `end_session` returns None, first end reason wins and boundary counter update shares its transaction. It has no worker-generation check today. `session_lifecycle_statuses` returns id=>status from last row; cron downgrades only known interrupted/error/empty statuses and currently fails open on probe errors. Generation validation and final mutation/receipt must precede terminal worker status; late finalizers must be refused without mutating the next turn. |
+
+### Compression's required sequence (do not collapse into append-text)
+
+`_try_acquire_durable_lock` => acquire compression lease => capture active watermark and authoritative
+raw cooldown under lease => optional grow/adopt durable history and preflush => slow summary/pruning
+outside DB transaction => validate cancellation/lease => archive OR atomic publish-child => install
+returned durable transcript markers and new session id => carry title/provenance, usage-anchor/runway,
+anti-thrash state and context-engine boundary => release holder. Cancellation rollback uses exact raw
+cooldown snapshot, not the expiry-filtered view. `_adopt_live_compression_child` verifies child alive,
+loads conversation, then confirms the tip; `_reopen_orphaned_parent` conservatively refuses live child/lease.
+No async fire-and-forget replacement can preserve these dependencies.
+
+## 3. Concrete worker producers and extra consumers
+
+### Cron
+
+`_open_cron_session_db` => registry acquire on a copied-context helper thread (timeout continues with None;
+late result closes). `_construct_cron_agent` passes that store before constructor. Main/watchdog thread
+runs `run_conversation`; `_defer_cron_worker_teardown` in `scheduler_detached_worker.py` retains store and
+agent until the timed-out future actually exits. `_finalize_cron_session` resolves compression tip,
+sets deduped nonblank title BEFORE end, classifies last row, ends, disarms agent's redundant end, releases.
+`_BoundedCronSessionDB.__getattr__` forwards **every attribute**, runs callable cleanup under timeout,
+and a timed-out cleanup may still complete later. It is a local timeout shim, never the wire API.
+Concrete method set is the core index plus `session_lifecycle_statuses`, title/tip helpers already indexed.
+
+External scheduler adoption (`_run_external_worker_payload` / `adopt_claimed_execution`) is a cron
+execution-store claim, not authority adoption. Keep its durable job claim, worker PID, cancel/watchdog,
+job/context_from/script/workdir/provider/memory policy. A script-only job need not invent a model session.
+Cron-open failure policy must change to visible pause/failure under managed mode; None silently disables
+persistence and is not a valid managed capability. Cron claim/delivery stores are not to be reimplemented
+by the SessionDB adapter.
+
+### Children / grandchildren / schema retry
+
+`delegate_tool::_build_child_agent` calls `_open_child_session_db`, deriving `parent_store.db_path`
+and registry-acquiring it; missing parent DB disables persistence. Constructor failures release the handle.
+On success `_owns_session_db=True`; child-run close (including deferred late close) owns that reference.
+This shares a physical connection in one PID; it is a fresh writable open in another PID. The typed
+replacement needs authority-reserved child identity before construction and inherited exact profile scope.
+`delegate_tool_registry::_resolve_session_lineage` uses `resolve_resume_session_id` best-effort (input
+unchanged on failure). `delegate_tool_child_run` runs schema correction through another real
+`run_conversation` on the same child, not an independent unregistered agent. Apply the same rules to
+nested orchestrators. Async completion ledger writes below remain independently reachable even when
+the child transcript handle has been replaced.
+
+### Compute host (existing legacy route, NOT the normal canonical turn path)
+
+`HostSupervisor.submit_turn` => `ComputeHost._run_real_turn` => `_build_server_session` => profile
+registry acquire => `agent_factory::_make_agent` => `_transfer_db_to_agent` => `_init_session` =>
+`_ensure_session_db_row` => `_persist_branch_seed` => `prompt_turn::_run_prompt_submit` => synchronous
+AIAgent in its run thread. It joins that thread, builds metadata/session.info, then emits turn.end.
+Shutdown drains in-flight turns and skips still-live session ids before `_finalize_session`; that path
+persists agent snapshot, emits hooks/commits memory, reads source, conditionally ends row, stops notification
+poller/active-session slot and delegates. There is no authority-issued worker assignment in these frames.
+
+Extra **known** SessionDB operations in this route (see §8 exact call-site index):
+
+* `_hydrate_session_cwd` reads row; `_persist_session_cwd_and_schedule_git_meta` => `update_session_cwd`
+ returns cwd generation, then `_persist_session_git_meta` => `publish_session_git_metadata` checks
+ cwd+generation before updating branch/root. Async metadata must carry the same capability.
+* `_ensure_session_db_row` => create + deferred `set_session_hidden`; `_persist_branch_seed` => chunked
+ append (partial seed can exist). Owner must reserve/seed before launching, rather than duplicate this.
+* `prompt_turn::_absorb_turn_result` => `set_latest_matching_message_display_kind` after response;
+ `_after_complete_turn` writes pending title (drops invalid ValueError, retains transient failures).
+* Model restore/switch => `agent_factory::_persist_live_session_runtime` reads row and uses
+ `update_session_meta` (fallback `update_session_model`); server `_append_model_switch_marker`
+ uses structured `append_message`; `_persist_live_session_system_prompt` writes prompt.
+* TUI resume helpers => `assert_resume_safe`, `get_resume_conversations`,
+ `get_ancestor_display_prefix`, `reopen_session`; display reads are not model-input history.
+* `methods_prompt` reaction notes => `take_unseen_reactions`; truncate => `replace_messages`;
+ retry/rewind => `get_active_message_ids`, `get_messages_as_conversation`, `rewind_to_message`.
+
+`MUTATOR_ROUTE_TABLE` includes save/compress/truncate/model/personality/prompt/reset/history-reload/retry,
+not just turn submit. `_control_ack` uses server methods for save/compress and `_SLASH_MIRRORS` for the
+rest. `_init_session` starts `_start_notification_poller`; this is an independent producer, not a harmless
+metadata mirror. **Do not transplant all legacy TUI helpers into the scoped core facade.** Parent should
+select the authority execution adapter and keep session creation/metadata/rewind/control admission and
+notification ownership in authority. If full legacy control parity remains in the external host, its
+expanded exact helper closure must be converted and behavior-probed before enabling that route; the
+core index alone is explicitly insufficient. Plugin/mirror rebinding makes automatic reachability
+classification an overapproximation; §8 includes extra helpers, not a claim all run every turn.
+
+## 4. Raw SQL and store-property blockers
+
+### Async delegation ledger: exact operations, existing transaction semantics
+
+All following are `tools/async_delegation.py`; `_db_path` is `get_hermes_home()/state.db`.
+`_transaction` opens via `_connect` (schema/DDL durability setup), `with conn` commits/rolls back,
+then ALWAYS closes. `_DB_LOCK` serializes locally only; this is not SessionDB `_execute_write` or a
+worker receipt transaction. Do not forward `_update_delivery(sql, params)` remotely.
+
+| Consumer => concrete operation | Return/error/order contract |
+|---|---|
+| `_dispatch` => `_persist_dispatch(record)` | None; INSERT OR REPLACE running row, owner PID/start, routing/task JSON, pending attempts=0. Persist before submitting runner; submit failure DELETEs ledger row. DB errors can reject dispatch. Separate `_prune_durable_records` transaction follows insert. Replay must not reset completed delivery state. |
+| `_prune_durable_records` | None; delete old delivered and bound terminal/pending rows, preferring delivered. Owner-only retention; must not prune Q's pending outbox/receipts. |
+| `_finalize` => `_push_completion_event` => `_persist_completion(event,result)` | None; update terminal state, event/result JSON, pending delivery before live queue publication. If persistence raises, live queue publication and the subsequent in-memory terminal status assignment are not reached. No atomic ledger+queue/admission guarantee today. |
+| `delegate_tool_dispatch` => `record_unit_child(id,entry)` | None; within one local transaction read running result_json, replace same task_index, write partial results. Exceptions logged/suppressed. Preserve already-finished children across recovery; do not rerun missing/unknown children. |
+| `recover_abandoned_delegations` | int changed; running/finalizing rows whose PID/start witness died become unknown, retaining completed partial results. Import failure returns 0; DB/JSON errors otherwise propagate. Owner-only producer recovery, not worker self-adoption. |
+| `restore_undelivered_completions(queue)` | int enqueued; invokes recovery, orders pending events by completed_at/id, drops expired events, puts restored=True events on queue inside transaction. Queue effect cannot roll back with SQL. Canonical migration must bind admitted producer identity before ACK, never treat this as atomic admission. |
+| `claim_completion_delivery(id,claim)` | bool; absent legacy row returns True; otherwise pending + no claim/stale claim => claim and increment attempts. Reclaim interval in source. Managed registered events must not inherit absent-row success as proof. |
+| `release_completion_delivery(id,claim)` | bool row changed; matching pending claim => capped attempts becomes dropped, otherwise clears claim for retry; charged attempt retained. |
+| `defer_completion_delivery(id,claim)` | bool row changed; matching pending claim => clear + refund one attempt (floor 0), for refusal before admission. |
+| `drop_completion_delivery(id,claim)` | bool row changed; matching pending claim => dropped (not delivered), target permanently gone. |
+| `complete_completion_delivery(id,claim)` | bool row changed; matching pending claim => delivered and timestamps, clear claim. |
+| `mark_completion_delivered(id)` | bool row changed; legacy unqualified id ACK where not already delivered. Keep owner-only migration, not a worker capability. |
+| `get_durable_delegation(id)` | dict/None; decodes result JSON after read. Uses writable/schema-creating `_transaction` even for this read. |
+| `claim_event_delivery` / `_event_delivery` | Local routing wrappers. Interim task-failure notices deliberately bypass final-row claiming; claim string empty=no token needed, None=refused, nonempty=token. `_event_delivery(fn,...)` is not a wire function parameter. |
+
+Implement named producer operations for dispatch, partial child result, terminal completion and scoped
+status; delivery claim/defer/drop/complete belongs to automation owner. Reuse existing SQL bodies after
+extracting connection-taking helpers; fence lineage/execution plus mutation/receipt atomically. This
+crosses the child and automation lanes and must be assigned once by the parent.
+
+### Recall, reactions, completed-process lookup, and DB properties
+
+* Inline `session_search` receives `_get_session_db_for_recall()` and calls real
+ `tools/session_search_tool.py`. Typed reads used: `get_session`, `resolve_session_by_title`,
+ `get_messages`, `get_anchored_view`, `fts_rebuild_status`, `search_messages`,
+ `list_recent_sessions_bounded`, `get_messages_around`. `_get_message_storage_state` additionally
+ executes exactly `SELECT session_id, active, compacted FROM messages WHERE id = ?` via `_lock/_conn`;
+ returns dict/None and suppresses lookup error. Its visibility decision distinguishes compacted archive
+ from rewind-deleted rows. Add a specific owner-side storage-state query or run authorized recall in
+ owner; never give workers `_conn`. `_locate_session_db`/explicit profile reads use read_only=True,
+ but cross-profile discovery is a separate capability, not implied by execution write scope.
+ FTS search may initiate index-repair paths on a writable handle; “it's only a search” is not proof of
+ zero writable opens. Disabled recall in a full worker is a behavior regression, not automatic parity.
+* `process_registry_results::_owns_result`: owner==parent shortcut, otherwise writable SessionDB,
+ `get_compression_tip(parent)==owner`, finally close. Replace the lookup with scoped lineage read.
+ Completed result JSON files themselves remain private process-result artifacts, not DB receipts.
+* `react_to_message_tool`: independent registry open; `latest_message_row_id` or `get_message_role`
+ then `set_message_reaction` returning reaction list/None. Tool converts store failures to tool_error,
+ and emits a live reaction only after write. Capability must restrict exact session/message ownership.
+* `agent/system_prompt::_agent_home` derives home from `db_path` as fallback; the exact
+ function is included in the census source-access list. `delegate_tool::_open_child_session_db`
+ interprets that same property as permission to acquire SQLite. Expose immutable assigned profile
+ identity separately; `db_path` is metadata only if retained, never a worker-side opening mechanism.
+* Registry `release_or_close` first identity-refcounts, then calls `close` for unknown objects.
+ A scoped proxy's local close may release transport/outbox handles but must not close shared owner DB.
+* `type(db)` capability probes in leases/compression require concrete explicit adapter methods;
+ instance-only `__getattr__` looks supported to some consumers and absent to others. Compressor's
+ `_durable_read/_durable_write/_load_durable` dynamic method strings are fully enumerated in §7.
+ Cron's bounded `__getattr__` stays a local shim. No generic remote method API is justified.
+* `agent/insights.py` holds `db._conn` and issues analytics SQL, while `agent/trace_upload.py` opens/reads
+ sessions for explicit trace export. These are census candidates outside the normal AIAgent turn;
+ they are not to be exposed as execution-scoped operations. A plugin invoking them changes the closure.
+* `agent/transcript_repair.py` receives an owner transaction connection from the append implementation;
+ its SQL is already in the correct process. Move/reuse its call, not its connection, at the wire boundary.
+ Append's returned row annotations include both `_row_id` and `_canonical_content` (concurrent-winner
+ adoption); compaction/publication also mutate their input row dictionaries with `_row_id`. Preserve
+ these post-commit effects across the RPC, not only their scalar return values.
+* The remaining raw-SQL census candidates in `agent/verification_evidence.py` use the separate
+ `get_hermes_home()/verification_evidence.db`, NOT canonical state.db. Keep this coding-evidence
+ ledger distinct from execution persistence. The `.execute` hits in `prompt_builder::_run_backend_probe`,
+ `tool_executor::_run_agent_tool_execution_middleware`, and `turn_api_call::perform_api_call`
+ are environment/relay execution calls, not SQLite. These false positives are classified, not ignored.
+
+## 5. Smallest closed typed seam and thread/RPC design
+
+**Facade:** preserve the explicit core methods in §7 for unchanged built-in AIAgent/compressor callers;
+implement `acquire_session_turn_lease` locally as a poll loop over a named try-acquire primitive.
+Do not mirror all of SessionDB. Recall, delegation-ledger, reactions and legacy compute control remain
+separate scoped services with concrete consumers above. `create_session`'s kwargs and queued usage kwargs
+must become enumerated payload fields (see `_insert_session_row` / `update_token_counts`), not open bags.
+Map core model-config access to two concrete sidecar keys; reject all other keys until a named consumer
+is assigned. `set_auto_title_if_empty` is a legacy fallback in title_generator, absent on current SessionDB;
+it does not need a new remote method when `set_auto_title` is present. Likewise
+`is_explicit_fork_child` is the compatibility branch when `declared_scope_identity` is unavailable;
+a concrete current adapter can derive the former from the latter's typed result rather than add a
+second wire operation. The source census enumerates fallback consumers without mandating redundant RPCs.
+
+**Closed wire families (each variant gets explicit fields/results, never `{method,args,kwargs}`):**
+
+1. Assigned session create/backfill, row/history read and authorized lineage/cache-identity reads.
+2. Structured transcript append returning count AND input-row persistence annotations; API-content stamp.
+3. Turn try-acquire/renew/release; local wait callbacks. Compression try-acquire/renew/release/watermark.
+4. In-place compact and publish compression continuation (authorized child reservation + assignment
+ advancement in the same transaction). Exact cooldown snapshot/restore; explicit counters/deadline.
+5. Main usage delta, auxiliary usage delta, receipt barrier, billing-route switch; typed usage-anchor
+ and prune-runway read/write, system-prompt snapshot.
+6. Ranked title apply/read, activity touch/clear, lifecycle classification/end, terminal execution finish.
+
+This is the minimal closed **core** set, not a statement that six generic RPCs are sufficient. Keep
+separate variants where inputs/results/authorization differ; a tagged closed union is permissible,
+caller-selected SQL or Python method names are not. Snapshotting constructor reads can reduce trips,
+but refreshing tip/cooldown/history after a lease wait must still cross to authority. A cached missing
+row or cooldown is not authoritative after an outage. Need no new “session manager” parallel to authority.
+
+**Same PID:** synchronous methods can call the authority-owned store's transaction path directly from
+AIAgent/cron/child threads with explicit capability checks. A gateway/API event-loop thread must never
+submit an RPC to itself and block on the reply. DB waits/flushes and lease polling cannot monopolize the
+loop; schedule off-loop where called from async ingress. Sharing SessionDB does not automatically supply
+execution authorization; use the same fenced mutation bodies for direct and remote variants.
+
+**External process:** synchronous facade waits for a dedicated transport receiver, not the model/tool
+thread and not a blocked owner loop. The receiver must process control/cancellation and ACK concurrently
+with a blocked persistence call. Lease refresh scheduler, compression refresher, title thread, auxiliary
+review and child threads all share the facade; serialize mutation sequence under one lock, persist the
+private byte-bounded outbox before send, retain until receipt, and keep pending entries immune to cleanup.
+Reads needing prior writes require an explicit receipt barrier. No secret/profile env fallback or SQLite
+open on transport failure. Full/unavailable/revoked are distinguishable outcomes; caught “best-effort”
+callers still require a sticky runtime pause/fail signal so they cannot continue tools after losing
+persistence. Do not classify an outage as missing method, missing row or unheld compression lock.
+
+Existing worker primitives validate epoch, assignment(session,generation), owner epoch, consecutive
+sequence and payload fingerprint. A duplicate returns stored result before terminal-state refusal;
+conflict rejects. Adoption validates secret and current generation; **caller must verify original
+producer claim and live worker proof** (the existing docstring explicitly delegates this). New owner
+epoch does not imply replay permission. The primitive currently has only text receipts: use common
+private connection helpers to extend structured variants, with strict exceptions and one final commit.
+Do not enqueue normal token-writer work and commit a success receipt before usage is applied.
+
+## 6. Exclusive implementation handoff and acceptance blockers
+
+* **Substrate lane:** `gateway/session_worker.py`, `agent/runtime_session_store.py`,
+ `hermes_state_runtime.py`, `agent/session_persistence.py`, `agent/turn_facade_lease.py`,
+ `tests/gateway/test_worker_persistence.py`. Request exclusive extraction seams in
+ `hermes_state_messages.py`, `hermes_state_usage.py`, `hermes_state_compression.py`,
+ `hermes_state_sessions.py`, `hermes_state_titles.py` for connection-taking mutation bodies.
+ No maintenance/backup/recovery ownership changes. Receipt atomicity cannot be implemented correctly
+ by nesting existing public methods; these extraction seams are prerequisite ownership, not optional.
+* **Parent-exclusive:** authority lifecycle/epoch, authenticated worker bootstrap/dispatch, execution
+ reservation and canonical compute adapter selection. Reserve a continuation/child before inference
+ and atomically carry assignment over compression. Define terminal ordering relative to parent admission.
+* **Cron lane:** injection before constructor, restart claim proof, no None fallback, deferred-finalize
+ ordering and scoped adapter close; existing scheduler/external-worker lifecycle remains.
+* **Child/automation boundary:** one owner for `tools/async_delegation.py` SQL extraction and routing;
+ child lane supplies dispatch/partial/final event identity, automation lane owns claim/admission/settle.
+ No full worker switch until this direct writer and process-result/reaction opens are addressed.
+* **Compute lane:** replace `_get_db`/`_workdir_owner_db` bypasses and server-started notification/control
+ ownership, not only `compute_host::_build_server_session`'s first acquire. Extend typed operations
+ only for controls explicitly retained in external host. Profile scope must reach all helper threads.
+* **Read-tool lane/parent:** authorize recall and storage-state query separately from session writes;
+ preserve compacted-vs-rewind filtering, profile boundaries and result semantics.
+
+Q2–Q8 remain unexecuted here: actual process zero writable FDs/opens, lost ACK replay/conflict, forged
+profile/session/generation, outbox full/unavailable, restart adoption without rerunning tool, stale finally,
+compression annotation round-trip, route/aux accounting exactly once, constructor sidecars, schema retry,
+legacy compute control isolation and loop liveness. Native behavior is not proven by this source inventory.
+Core consumers that currently catch/suppress errors, custom context engines/plugins, runtime tool choice,
+background timeout races and SQL settlement after process death need executable behavior probes; an AST
+cannot certify those. The existing broad gateway suite does not substitute for these worker cases.
+
+## 7. Exact core consumer => operation index
+
+Generated from the executable census in §9; consumer symbols are stable references, with diagnostic
+snapshot line numbers. Each signature is the actual source signature (not a proposed open RPC schema).
+Source docstrings are quoted to preserve default/return intent; §2 records important differences between
+that intent and implementation (notably usage barriers and swallowed errors). Duplicate occurrences in
+the same function are represented once. Helper-only `try_acquire_session_turn_lease` and
+`update_token_counts` are included in §2 as transitive implementation seams, not extra direct consumers.
+
+### `acquire_session_turn_lease`
+
+Definition: `hermes_state_compression.py::acquire_session_turn_lease`
+
+```python
+acquire_session_turn_lease(self, session_id: str, holder: str, *, ttl_seconds: float=300.0, wait_seconds: float=1800.0, poll_interval_seconds: float=1.0, on_wait=None, wait_notice_interval_seconds: float=15.0, should_abort=None, acquire_patience_s: float=0.5) -> bool
+```
+
+Source contract: Wait for a cross-process turn lease without holding a SQLite lock. ``on_wait(elapsed)`` is best-effort: called when the first attempt fails and about every ``wait_notice_interval_seconds`` after. ``should_abort()`` True (e.g. ``/stop``) returns False at once.
+
+Consumers:
+- `agent/turn_facade_lease.py::admit_durable_turn_lease` (snapshot 251)
+- `agent/turn_facade_lease.py::admit_durable_turn_lease` (snapshot 271)
+
+### `append_messages_batch`
+
+Definition: `hermes_state_messages.py::append_messages_batch`
+
+```python
+append_messages_batch(self, session_id: str, messages: List[Dict[str, Any]], compression_lock_holder: Optional[str]=None, turn_lease_holder: Optional[str]=None, chunk_rows: Optional[int]=None, turn_lease_ttl_seconds: float=300.0) -> int
+```
+
+Source contract: Append *messages* in ONE write txn (all rows land or none, guards run once); returns the inserted count. ``chunk_rows`` bounds txn size for LARGE copies (branch seeds; FTS triggers run per row).
+
+Consumers:
+- `agent/session_persistence.py::_db_flush_write` (snapshot 208)
+
+### `archive_and_compact`
+
+Definition: `hermes_state_messages.py::archive_and_compact`
+
+```python
+archive_and_compact(self, session_id: str, compacted_messages: List[Dict[str, Any]], model_config_patch: Optional[Dict[str, Any]]=None, watermark: Optional[int]=None, lock_holder: Optional[str]=None, tail_count: int=0) -> int
+```
+
+Source contract: Non-destructive in-place compaction under ONE session id: soft-archive the active rows (``active=0, compacted=1``: summarized away, still searchable) and insert *compacted_messages* as fresh active rows, atomically; returns the new ACTIVE count (= ``message_count``). *watermark* (compression START): rows ``id > watermark`` arrived during the slow summary and are re-sequenced after the compacted set by a pure-SQL clone (fresh ids); ``None`` archives everything. *lock_holder*: verified in-txn so a reclaimed lease fails instead of clobbering the winner. *tail_count*: the LAST N compacted rows are the verbatim carried tail; their originals and the clones' originals are superseded duplicates and get rewind flags (``active=0, compacted=0``) so search doesn't return each carried message once per compaction. ``model_config_patch`` merges in the same txn (``None`` removes a key). Concurrent-append safety (#75316): when *watermark* is provided (the value of :meth:`get_active_message_watermark` captured at compression START), rows that arrived during the slow provider summary call (``id > watermark``) are NOT summarized away. They are re-sequenced after the compacted set by a pure-SQL column clone (every column except ``id`` — content, api_content, platform_message_id, token counts, reasoning sidecars all survive byte-exact, and the FTS triggers index the clones naturally), and the originals are archived. NOTE: re-sequencing assigns the tail rows fresh ids; consumers that reference durable row ids re-resolve by content (see 3e8ab0610).
+
+Consumers:
+- `agent/context_compressor.py::prune_tool_results_only` (snapshot 2857)
+- `agent/context_compressor.py::prune_tool_results_only` (snapshot 2878)
+- `agent/conversation_compression.py::_commit_compaction` (snapshot 3260)
+- `agent/micro_compaction.py::_sync_micro_compact_to_db` (snapshot 352)
+
+### `clear_compression_failure_cooldown`
+
+Definition: `hermes_state_compression.py::clear_compression_failure_cooldown`
+
+```python
+clear_compression_failure_cooldown(self, session_id: str) -> None
+```
+
+Source contract: Clear any persisted compression-failure cooldown for a session.
+
+Consumers:
+- `agent/context_compressor.py::_clear_compression_failure_cooldown` (snapshot 2126)
+- `agent/conversation_compression.py::_rollback_durable_cooldown` (snapshot 281)
+
+### `clear_session_activity_labels`
+
+Definition: `hermes_state_sessions.py::clear_session_activity_labels`
+
+```python
+clear_session_activity_labels(self, session_id: str) -> None
+```
+
+Source contract: Clear activity labels after a turn (``last_activity_at`` is kept so idle / watchdog clocks stay continuous). A no-op clear skips the write transaction. Description and provenance are observation labels for *what was happening at* that timestamp during an active turn; once the turn is idle they must not keep advertising "compressing" / "executing tool" (#72039). Response-critical-path contract (#76354 review S1): runs in the turn's ``finally``; a no-op clear (labels already empty) skips the write transaction entirely, and a real clear uses the same short sub-second busy budget as :meth:`touch_session_activity` instead of the full routine write patience.
+
+Consumers:
+- `agent/activity_tracking.py::_reset_activity_labels_after_turn` (snapshot 134)
+- `agent/conversation_compression.py::_finish_compaction_boundary` (snapshot 3057)
+
+### `create_session`
+
+Definition: `hermes_state_sessions.py::create_session`
+
+```python
+create_session(self, session_id: str, source: str, **kwargs) -> str
+```
+
+Source contract: Create (upsert) a session record. Returns the session_id.
+
+Consumers:
+- `run_agent.py::_ensure_db_session` (snapshot 337)
+
+### `declared_scope_identity`
+
+Definition: `hermes_state_sessions.py::declared_scope_identity`
+
+```python
+declared_scope_identity(self, session_id: str) -> Tuple[bool, str]
+```
+
+Source contract: (is_fork_child, source) in ONE read (prompt_cache_scope needs both from the same row). Missing row → (False, ""); DB errors propagate (fail closed). ``agent/prompt_cache_scope.py`` needs both to resolve a host-declared conversation scope, and both live on the same ``sessions`` row; asking for them separately read that row twice per resolution (@teknium1 on 98811). The marker rules stay here, beside :meth:`is_explicit_fork_child`, instead of being re-implemented by the caller. See #98811.
+
+Consumers:
+- `agent/prompt_cache_scope.py::declared_conversation_scope` (snapshot 109)
+
+### `end_session`
+
+Definition: `hermes_state_sessions.py::end_session`
+
+```python
+end_session(self, session_id: str, end_reason: str) -> None
+```
+
+Source contract: Mark a session ended; the first end_reason wins (a compression split must keep ``'compression'`` even if a stale end_session() lands later); reopen_session() to re-end.
+
+Consumers:
+- `cron/scheduler.py::_finalize_cron_session` (snapshot 1984)
+- `run_agent.py::_finalize_owned_session_row` (snapshot 985)
+
+### `flush_token_counts`
+
+Definition: `hermes_state_usage.py::flush_token_counts`
+
+```python
+flush_token_counts(self, timeout: float=5.0) -> bool
+```
+
+Source contract: Block until every queued token delta has been applied. False on timeout (callers then read totals stale by the queued deltas). Never raises.
+
+Consumers:
+- `agent/session_persistence.py::_persist_session` (snapshot 302)
+
+### `get_active_message_watermark`
+
+Definition: `hermes_state_messages.py::get_active_message_watermark`
+
+```python
+get_active_message_watermark(self, session_id: str) -> int
+```
+
+Source contract: MAX(id) of the active rows (0 if none), captured at compression START: every active row above it arrived concurrently and must survive compaction verbatim.
+
+Consumers:
+- `agent/conversation_compression.py::_publish_rotated_compaction` (snapshot 2952)
+- `agent/conversation_compression.py::_try_acquire_durable_lock` (snapshot 2382)
+
+### `get_compression_failure_cooldown`
+
+Definition: `hermes_state_compression.py::get_compression_failure_cooldown`
+
+```python
+get_compression_failure_cooldown(self, session_id: str) -> Optional[Dict[str, Any]]
+```
+
+Source contract: Return the active (unexpired) compression-failure cooldown, or None.
+
+Consumers:
+- `agent/context_compressor.py::get_active_compression_failure_cooldown` (snapshot 2062)
+
+### `get_compression_failure_cooldown_row`
+
+Definition: `hermes_state_compression.py::get_compression_failure_cooldown_row`
+
+```python
+get_compression_failure_cooldown_row(self, session_id: str) -> Dict[str, Any]
+```
+
+Source contract: Exact stored cooldown columns, no expiry filtering, so compression cancellation can roll back an expired, partially-null, or absent row exactly.
+
+Consumers:
+- `agent/conversation_compression.py::_capture_authoritative_cooldown_under_lease` (snapshot 345)
+
+### `get_compression_fallback_streak`
+
+Definition: `hermes_state_compression.py::get_compression_fallback_streak`
+
+```python
+get_compression_fallback_streak(self, session_id: str) -> int
+```
+
+Source contract: Return the persisted deterministic-fallback streak.
+
+Consumers:
+- `agent/context_compressor.py::_load_fallback_compression_streak` (snapshot 1954)
+- `agent/context_compressor.py::on_session_start` (snapshot 1896)
+
+### `get_compression_ineffective_count`
+
+Definition: `hermes_state_compression.py::get_compression_ineffective_count`
+
+```python
+get_compression_ineffective_count(self, session_id: str) -> int
+```
+
+Source contract: Persisted ineffective-compaction strike count — the durable half of the built-in compressor's anti-thrash guard, so a fresh compressor bound to a resumed session inherits an armed/tripped guard across restarts.
+
+Consumers:
+- `agent/context_compressor.py::_load_ineffective_compression_count` (snapshot 1972)
+- `agent/context_compressor.py::on_session_start` (snapshot 1899)
+
+### `get_compression_lineage`
+
+Definition: `hermes_state_compression.py::get_compression_lineage`
+
+```python
+get_compression_lineage(self, session_id: str) -> List[str]
+```
+
+Source contract: Return compression ancestors through tip in chronological order.
+
+Consumers:
+- `agent/prompt_cache_scope.py::_lineage_root` (snapshot 27)
+
+### `get_compression_lock_holder`
+
+Definition: `hermes_state_compression.py::get_compression_lock_holder`
+
+```python
+get_compression_lock_holder(self, session_id: str) -> Optional[str]
+```
+
+Source contract: Current (non-expired) holder for ``session_id``, or None. Diagnostic only.
+
+Consumers:
+- `agent/conversation_compression.py::_sit_out_lock_contention` (snapshot 2413)
+- `agent/conversation_compression.py::recover_rotated_compression_session` (snapshot 1461)
+
+### `get_compression_recovery_deadline`
+
+Definition: `hermes_state_compression.py::get_compression_recovery_deadline`
+
+```python
+get_compression_recovery_deadline(self, session_id: str) -> float
+```
+
+Source contract: Persisted anti-thrash recovery deadline (epoch; ``0.0`` = not armed). Durable because the gateway rebuilds the compressor every turn / cache eviction. The deadline is the durable half of the 14694 recovery clock: the gateway rebuilds the compressor on every turn / cache eviction, so a process-local deadline restarted the wait on each rebuild and a tripped session never earned its probe (#100185).
+
+Consumers:
+- `agent/context_compressor.py::_load_anti_thrash_recovery_deadline` (snapshot 1982)
+
+### `get_compression_tip`
+
+Definition: `hermes_state_compression.py::get_compression_tip`
+
+```python
+get_compression_tip(self, session_id: str) -> Optional[str]
+```
+
+Source contract: Live tip of a compression chain (``get_compression_chain`` semantics); the input id when no continuation exists.
+
+Consumers:
+- `agent/conversation_compression.py::_adopt_live_compression_child` (snapshot 1389)
+- `agent/session_persistence.py::_db_flush_adopt_compression_tip` (snapshot 222)
+- `cron/scheduler.py::_finalize_cron_session` (snapshot 1921)
+
+### `get_conversation_root`
+
+Definition: `hermes_state_messages.py::get_conversation_root`
+
+```python
+get_conversation_root(self, session_id: str) -> str
+```
+
+Source contract: ROOT id of the lineage: the stable conversation id across compression segments and delegate subagents (Nous Portal usage tagging). Unchanged when there is no recorded parent.
+
+Consumers:
+- `agent/system_prompt.py::_session_start_like` (snapshot 209)
+- `agent/title_generator.py::auto_title_session` (snapshot 373)
+- `run_agent.py::_conversation_root_id` (snapshot 1333)
+
+### `get_messages_as_conversation`
+
+Definition: `hermes_state_messages.py::get_messages_as_conversation`
+
+```python
+get_messages_as_conversation(self, session_id: str, include_ancestors: bool=False, include_inactive: bool=False, repair_alternation: bool=False, include_row_ids: bool=False, include_compacted: bool=False) -> List[Dict[str, Any]]
+```
+
+Source contract: Load messages in OpenAI format. ``include_compacted`` (deduped display history) is for DISPLAY reads only: the model-fed restore must not regrow what compaction summarized away. ``repair_alternation`` repairs the loaded list for LIVE REPLAY callers (a durable ``user;user`` pair would re-trigger the per-request repair forever); the stored transcript is never mutated.
+
+Consumers:
+- `agent/conversation_compression.py::_adopt_grown_durable_parent` (snapshot 2551)
+- `agent/conversation_compression.py::_adopt_live_compression_child` (snapshot 1391)
+- `agent/turn_facade_lease.py::admit_durable_turn_lease` (snapshot 292)
+
+### `get_next_title_in_lineage`
+
+Definition: `hermes_state_titles.py::get_next_title_in_lineage`
+
+```python
+get_next_title_in_lineage(self, base_title: str) -> str
+```
+
+Source contract: Next title in a lineage ("my session" -> "my session #2"): strip any " #N" suffix, then increment the highest existing number.
+
+Consumers:
+- `agent/title_generator.py::_persist_session_title` (snapshot 329)
+- `cron/scheduler.py::_finalize_cron_session` (snapshot 1951)
+- `cron/scheduler.py::_set_cron_session_title` (snapshot 90)
+
+### `get_session`
+
+Definition: `hermes_state_sessions.py::get_session`
+
+```python
+get_session(self, session_id: str) -> Optional[Dict[str, Any]]
+```
+
+Source contract: Get a session by ID (drains queued token deltas first so cost readers see exact totals).
+
+Consumers:
+- `agent/conversation_compression.py::_adopt_live_compression_child` (snapshot 1390)
+- `agent/conversation_compression.py::_parent_deliberately_ended` (snapshot 2886)
+- `agent/conversation_compression.py::_session_was_rotated_by_compression` (snapshot 1178)
+- `agent/conversation_loop.py::_restore_or_build_system_prompt` (snapshot 652)
+- `agent/prompt_cache_scope.py::_agent_source` (snapshot 50)
+- `agent/session_persistence.py::_db_flush_adopt_compression_tip` (snapshot 229)
+- `agent/turn_facade_lease.py::_durable_session_exists` (snapshot 217)
+
+### `get_session_model_config_value`
+
+Definition: `hermes_state_sessions.py::get_session_model_config_value`
+
+```python
+get_session_model_config_value(self, session_id: str, key: str, default: Any=None) -> Any
+```
+
+Source contract: Read one key out of a session's model_config JSON (tolerant parse).
+
+Consumers:
+- `agent/context_compressor.py::_load_proactive_prune_rearm_tokens` (snapshot 1959)
+- `agent/usage_anchor.py::persisted_anchor_tokens` (snapshot 157)
+- `agent/usage_anchor.py::restore_usage_anchor` (snapshot 138)
+
+### `get_session_title`
+
+Definition: `hermes_state_titles.py::get_session_title`
+
+```python
+get_session_title(self, session_id: str) -> Optional[str]
+```
+
+Source contract: Get the title for a session, or None.
+
+Consumers:
+- `agent/agent_init.py::_memory_provider_init_kwargs` (snapshot 1217)
+- `agent/conversation_compression.py::_publish_rotated_compaction` (snapshot 2964)
+- `agent/conversation_loop.py::_bot_chat_prompt_stale` (snapshot 618)
+- `agent/system_prompt.py::_bot_mode_parts` (snapshot 325)
+- `agent/title_generator.py::_has_upgraded_title` (snapshot 296)
+- `agent/title_generator.py::_session_is_untitled` (snapshot 410)
+
+### `get_session_title_source`
+
+Definition: `hermes_state_titles.py::get_session_title_source`
+
+```python
+get_session_title_source(self, session_id: str) -> Optional[str]
+```
+
+Source contract: Get the provenance of a session's title, or None when untitled.
+
+Consumers:
+- `agent/conversation_compression.py::_carry_session_state_to_child` (snapshot 2919)
+- `agent/title_generator.py::_has_upgraded_title` (snapshot 293)
+
+### `is_explicit_fork_child`
+
+Definition: `hermes_state_messages.py::is_explicit_fork_child`
+
+```python
+is_explicit_fork_child(self, session_id: str) -> bool
+```
+
+Source contract: Read-only :meth:`_is_explicit_fork_child_row`; a missing row is not a fork (prompt_cache_scope keeps a declared conversation key from crossing the fork boundary).
+
+Consumers:
+- `agent/prompt_cache_scope.py::declared_conversation_scope` (snapshot 113)
+
+### `latest_conversation_boundary`
+
+Definition: `hermes_state_messages.py::latest_conversation_boundary`
+
+```python
+latest_conversation_boundary(self, session_key: str, source: str) -> Optional[int]
+```
+
+Source contract: Conversation boundaries (``_RESET_END_REASONS`` ends) this peer has crossed, or ``None`` if never reset. The peer is ``(session_key, source)``, never the key alone (an API caller may legally reuse a Telegram row's key). Read from ``conversation_generations`` (advanced in each boundary's txn), not an aggregate over session rows: deletes/prunes would re-emit a retired pair. Rows are never GC'd (dropping one re-issues generation 1: the ABA this prevents). Wall-clock-free, so a backwards NTP correction cannot reorder it. DBs upgraded mid-conversation take their first generation from the next boundary written (a pre-upgrade reset shares its predecessor's scope once: costs a warm prompt-cache bucket, never crosses an identity).
+
+Consumers:
+- `agent/prompt_cache_scope.py::_conversation_generation` (snapshot 79)
+
+### `patch_session_model_config`
+
+Definition: `hermes_state_sessions.py::patch_session_model_config`
+
+```python
+patch_session_model_config(self, session_id: str, patch: Dict[str, Any]) -> None
+```
+
+Source contract: Merge ``patch`` into model_config atomically (``None`` removes a key); no-op when the row or patch is empty.
+
+Consumers:
+- `agent/context_compressor.py::_clear_durable_proactive_prune_rearm` (snapshot 1965)
+- `agent/usage_anchor.py::persist_usage_anchor` (snapshot 115)
+
+### `publish_compression_child`
+
+Definition: `hermes_state_compression.py::publish_compression_child`
+
+```python
+publish_compression_child(self, *, parent_session_id: str, child_session_id: str, source: str, messages: List[Dict[str, Any]], model: str=None, model_config: Dict[str, Any]=None, system_prompt: str=None, cwd: str=None, profile_name: str=None, compression_lock_holder: str=None, require_compression_lease: bool=True, require_lease_refresh: bool=False, lease_ttl_seconds: float=300.0, watermark: Optional[int]=None, watermark_ceiling: Optional[int]=None) -> None
+```
+
+Source contract: Atomically close a parent and publish its durable compression child: closure, child row, and handoff commit in one transaction, so readers see the live parent or a complete child, never an ended parent with a missing/empty child. *watermark* (parent's ``get_active_message_watermark`` at compression start): parent rows with ``id > watermark`` — appends landed during the slow summary — are column-cloned into the child AFTER the handoff. *watermark_ceiling* bounds the clone: the rotation path flushes its OWN transcript to the parent just before publishing and those rows are already in the handoff, so only ``(watermark, watermark_ceiling]`` is foreign tail (``None`` = unbounded). *require_lease_refresh* + *compression_lock_holder* refreshes the lease on the same ``conn`` before the expiry check (no TOCTOU window), so a refresher that died on transient DB errors gets one last chance. See #75316. ``None`` = unbounded (no internal flush happened). See #47202.
+
+Consumers:
+- `agent/conversation_compression.py::_publish_rotated_compaction` (snapshot 2967)
+
+### `queue_token_counts`
+
+Definition: `hermes_state_usage.py::queue_token_counts`
+
+```python
+queue_token_counts(self, session_id: str, **kwargs) -> None
+```
+
+Source contract: Enqueue a token/cost delta for the background writer (same kwargs as :meth:`update_token_counts`). After close() stopped the writer, falls back to the synchronous path and may raise.
+
+Consumers:
+- `agent/codex_runtime.py::_queue_token_counts` (snapshot 80)
+- `agent/turn_usage.py::record_response_usage` (snapshot 249)
+
+### `record_auxiliary_usage`
+
+Definition: `hermes_state_usage.py::record_auxiliary_usage`
+
+```python
+record_auxiliary_usage(self, session_id: str, task: str, *, model: Optional[str]=None, billing_provider: Optional[str]=None, billing_base_url: Optional[str]=None, input_tokens: int=0, output_tokens: int=0, cache_read_tokens: int=0, cache_write_tokens: int=0, reasoning_tokens: int=0, estimated_cost_usd: Optional[float]=None, api_call_count: int=1) -> None
+```
+
+Source contract: Record an auxiliary LLM call's usage (vision, compression, title generation, ...) as a per-(model, provider, task) delta in ``session_model_usage`` WITHOUT touching the ``sessions`` summary row (the gateway overwrites those counters with absolute main-loop totals). ``api_call_count`` may aggregate N calls. Best-effort. See #23270. Background-review forks record an aggregate of N fork API calls in one write with ``task='background_review'`` (issue #87250).
+
+Consumers:
+- `agent/aux_accounting.py::record_aux_usage` (snapshot 84)
+- `agent/background_review.py::_record_review_usage_to_parent` (snapshot 730)
+
+### `record_compression_failure_cooldown`
+
+Definition: `hermes_state_compression.py::record_compression_failure_cooldown`
+
+```python
+record_compression_failure_cooldown(self, session_id: str, cooldown_until: float, error: Optional[str]=None) -> None
+```
+
+Source contract: Persist the active compression-failure cooldown. Merge-max with any longer live deadline so a later shorter write can't reopen the thrash window; error always takes the latest diagnostic.
+
+Consumers:
+- `agent/context_compressor.py::_record_compression_failure_cooldown` (snapshot 2110)
+- `agent/conversation_compression.py::_rollback_durable_cooldown` (snapshot 277)
+
+### `refresh_compression_lock`
+
+Definition: `hermes_state_compression.py::refresh_compression_lock`
+
+```python
+refresh_compression_lock(self, session_id: str, holder: str, ttl_seconds: float=300.0) -> bool
+```
+
+Source contract: Extend the compression lock lease if ``holder`` still owns it. Ownership is decided by ``holder`` alone, deliberately NOT ``expires_at``: a live owner whose refresher stalled past its TTL must be able to revive its still-unclaimed row, otherwise it keeps compressing with no lease — the window in which a competing path can fork the lineage. It cannot resurrect a lock someone else took: SQLite serialises writes, so the reclaim (DELETE-expired + INSERT OR IGNORE) never interleaves with this UPDATE.
+
+Consumers:
+- `agent/conversation_compression.py::_run` (snapshot 1682)
+
+### `refresh_session_turn_lease`
+
+Definition: `hermes_state_compression.py::refresh_session_turn_lease`
+
+```python
+refresh_session_turn_lease(self, session_id: str, holder: str, *, ttl_seconds: float=300.0) -> bool
+```
+
+Source contract: Extend a turn lease only while ``holder`` still owns it.
+
+Consumers:
+- `agent/turn_facade_lease.py::refresh_tick` (snapshot 184)
+
+### `release_compression_lock`
+
+Definition: `hermes_state_compression.py::release_compression_lock`
+
+```python
+release_compression_lock(self, session_id: str, holder: str) -> None
+```
+
+Source contract: Release the compression lock iff we own it; idempotent when gone/reclaimed.
+
+Consumers:
+- `agent/conversation_compression.py::_try_acquire_durable_lock` (snapshot 2397)
+- `agent/conversation_compression.py::release_holder_only` (snapshot 2326)
+
+### `release_session_turn_lease`
+
+Definition: `hermes_state_compression.py::release_session_turn_lease`
+
+```python
+release_session_turn_lease(self, session_id: str, holder: str) -> None
+```
+
+Source contract: Release a turn lease iff ``holder`` still owns it; idempotent.
+
+Consumers:
+- `agent/turn_facade_lease.py::release` (snapshot 100)
+
+### `reopen_orphaned_compression_session`
+
+Definition: `hermes_state_compression.py::reopen_orphaned_compression_session`
+
+```python
+reopen_orphaned_compression_session(self, session_id: str) -> bool
+```
+
+Source contract: Reopen a compression parent only when no continuation was published (older builds could leave a closed parent after an interrupted handoff). Conservative: an active lease or any canonical child means another path owns the lineage.
+
+Consumers:
+- `agent/conversation_compression.py::_reopen_orphaned_parent` (snapshot 1440)
+
+### `resolve_resume_session_id`
+
+Definition: `hermes_state_messages.py::resolve_resume_session_id`
+
+```python
+resolve_resume_session_id(self, session_id: str) -> str
+```
+
+Source contract: Redirect a resume target to the descendant holding the messages: follow the compression chain to the live tip (lineage-aware, so delegate/branch children never hijack it), then walk ``parent_session_id`` forward to the DEEPEST node with messages (a continuation may hold newer turns), skipping branch/delegate/reset/tool children. Unchanged when nothing has messages; depth cap 32. Context compression ends the current session and forks a new child session (linked via ``parent_session_id``). The flush cursor is reset, so the child is where new messages actually land — the parent ends up with ``message_count = 0`` rows unless messages had already been flushed to it before compression. See #15000.
+
+Consumers:
+- `agent/turn_facade_lease.py::admit_durable_turn_lease` (snapshot 288)
+- `tools/delegate_tool_registry.py::_resolve_session_lineage` (snapshot 203)
+
+### `restore_compression_failure_cooldown_row`
+
+Definition: `hermes_state_compression.py::restore_compression_failure_cooldown_row`
+
+```python
+restore_compression_failure_cooldown_row(self, session_id: str, snapshot: Dict[str, Any]) -> None
+```
+
+Source contract: Restore and verify an exact cooldown-row snapshot. Unlike record/clear this rollback API propagates write and verification failures: cancellation must not be reported mutation-free when compensation failed.
+
+Consumers:
+- `agent/conversation_compression.py::_rollback_durable_cooldown` (snapshot 268)
+
+### `session_lifecycle_statuses`
+
+Definition: `hermes_state_sessions.py::session_lifecycle_statuses`
+
+```python
+session_lifecycle_statuses(self, session_ids: List[str]) -> Dict[str, str]
+```
+
+Source contract: ``{session_id: status}`` from each session's LAST message row (``'empty'`` when none); one query, MAX(id) per session joined back — never scans transcripts.
+
+Consumers:
+- `cron/scheduler.py::_finalize_cron_session` (snapshot 1973)
+
+### `set_auto_title`
+
+Definition: `hermes_state_titles.py::set_auto_title`
+
+```python
+set_auto_title(self, session_id: str, title: str, *, source: str) -> bool
+```
+
+Source contract: Set an automatic title; False (untouched) when a higher-authority title holds the row.
+
+Consumers:
+- `agent/title_generator.py::_persist_session_title` (snapshot 311)
+
+### `set_compression_fallback_streak`
+
+Definition: `hermes_state_compression.py::set_compression_fallback_streak`
+
+```python
+set_compression_fallback_streak(self, session_id: str, streak: int) -> None
+```
+
+Source contract: Persist the deterministic-fallback streak for one session.
+
+Consumers:
+- `agent/context_compressor.py::_persist_fallback_compression_streak` (snapshot 1968)
+
+### `set_compression_ineffective_count`
+
+Definition: `hermes_state_compression.py::set_compression_ineffective_count`
+
+```python
+set_compression_ineffective_count(self, session_id: str, count: int) -> None
+```
+
+Source contract: Persist the ineffective-compaction strike count for one session.
+
+Consumers:
+- `agent/context_compressor.py::_persist_ineffective_compression_count` (snapshot 1975)
+
+### `set_compression_recovery_deadline`
+
+Definition: `hermes_state_compression.py::set_compression_recovery_deadline`
+
+```python
+set_compression_recovery_deadline(self, session_id: str, deadline: float) -> None
+```
+
+Source contract: Persist the anti-thrash recovery deadline; ``0`` / ``None`` disarms it.
+
+Consumers:
+- `agent/context_compressor.py::_set_anti_thrash_recovery_deadline` (snapshot 1989)
+
+### `set_latest_user_api_content`
+
+Definition: `hermes_state_messages.py::set_latest_user_api_content`
+
+```python
+set_latest_user_api_content(self, session_id: str, content: Any, api_content: str) -> int
+```
+
+Source contract: Backfill the ``api_content`` sidecar onto the newest ACTIVE user row (0/1 rows). Preflight compaction inserts that row BEFORE the sidecar exists and the later persist identity-skips compacted dicts; without this a reload reopens the prompt-cache divergence. ``content`` match guards a racing rewrite.
+
+Consumers:
+- `agent/turn_context.py::_stamp_api_content_sidecar` (snapshot 745)
+
+### `set_session_title`
+
+Definition: `hermes_state_titles.py::set_session_title`
+
+```python
+set_session_title(self, session_id: str, title: str) -> bool
+```
+
+Source contract: Set a title on the user's behalf (``user`` provenance). Empty clears it. Raises ValueError on conflict or validation failure.
+
+Consumers:
+- `agent/conversation_compression.py::_carry_session_state_to_child` (snapshot 2921)
+- `agent/title_generator.py::_persist_session_title._set` (snapshot 322)
+- `cron/scheduler.py::_set_cron_session_title` (snapshot 86)
+- `cron/scheduler.py::_set_cron_session_title` (snapshot 96)
+
+### `set_session_title_source`
+
+Definition: `hermes_state_titles.py::set_session_title_source`
+
+```python
+set_session_title_source(self, session_id: str, source: str) -> bool
+```
+
+Source contract: Overwrite a title's provenance without touching the text (a title copied across a compression rotation keeps the original's authority).
+
+Consumers:
+- `agent/conversation_compression.py::_carry_session_state_to_child` (snapshot 2928)
+
+### `touch_session_activity`
+
+Definition: `hermes_state_sessions.py::touch_session_activity`
+
+```python
+touch_session_activity(self, session_id: str, ts: Optional[float]=None, *, description: Optional[str]=None, provenance: Optional[ActivityProvenance]=None) -> None
+```
+
+Source contract: Stamp durable mid-turn activity (observation-only; rate-limited by the caller) so surfaces see activity before any message row lands. Never moves ``last_activity_at`` backwards. Called (rate-limited) from ``AIAgent._touch_activity`` so gateway/CLI surfaces and stall consumers observe API/tool/compaction activity even when no new message row has been written yet (#72016 / #72039).
+
+Consumers:
+- `agent/activity_tracking.py::_persist_session_activity_if_due` (snapshot 95)
+
+### `try_acquire_compression_lock`
+
+Definition: `hermes_state_compression.py::try_acquire_compression_lock`
+
+```python
+try_acquire_compression_lock(self, session_id: str, holder: str, ttl_seconds: float=300.0) -> bool
+```
+
+Source contract: Try to atomically acquire the compression lock for ``session_id``. ``False``: another holder owns a live lock and the caller MUST NOT compress (its rotation would split the lineage). Expired locks and structured holders whose local ``pid=`` is dead are reclaimed transparently.
+
+Consumers:
+- `agent/conversation_compression.py::_lock_api_is_absent_on_session_db` (snapshot 1155)
+- `agent/conversation_compression.py::_resolve_lock_api` (snapshot 2352)
+
+### `update_session_billing_route`
+
+Definition: `hermes_state_usage.py::update_session_billing_route`
+
+```python
+update_session_billing_route(self, session_id: str, *, provider: str, base_url: str, billing_mode: Optional[str]=None) -> None
+```
+
+Source contract: Unconditionally set the billing route (``update_token_counts`` only COALESCE-fills NULLs) so the dashboard reflects the latest /model switch; also nulls ``system_prompt`` so the cached snapshot header is rebuilt. See #48173, #48248.
+
+Consumers:
+- `agent/agent_runtime_helpers.py::_persist_switch_billing_route` (snapshot 2096)
+
+### `update_system_prompt`
+
+Definition: `hermes_state_sessions.py::update_system_prompt`
+
+```python
+update_system_prompt(self, session_id: str, system_prompt: Optional[str]) -> None
+```
+
+Source contract: Store the full assembled system prompt snapshot.
+
+Consumers:
+- `agent/conversation_compression.py::_commit_compaction` (snapshot 3275)
+- `agent/conversation_loop.py::_persist_system_prompt` (snapshot 633)
+
+## 8. Extension candidates: recall/tools and legacy compute helpers
+
+This is an overapproximate source inventory, not a claim every helper runs in every compute turn.
+The routing and bypass findings in §3–4 determine which need authority-side execution instead.
+
+### Extension `append_message`
+
+`hermes_state_messages.py::append_message`
+
+```python
+append_message(self, session_id: str, role: str, content: str=None, tool_name: str=None, tool_calls: Any=None, tool_call_id: str=None, token_count: int=None, finish_reason: str=None, reasoning: str=None, reasoning_content: str=None, reasoning_details: Any=None, codex_reasoning_items: Any=None, codex_message_items: Any=None, platform_message_id: str=None, observed: bool=False, effect_disposition: Optional[str]=None, _compressed_summary: bool=False, timestamp: Any=None, api_content: Optional[str]=None, display_kind: Optional[str]=None, display_metadata: Optional[Dict[str, Any]]=None, compression_lock_holder: Optional[str]=None, turn_lease_holder: Optional[str]=None, turn_lease_ttl_seconds: float=300.0) -> int
+```
+
+Append one message; returns the row id and bumps the session counters. ``platform_message_id``: the platform's own id. ``api_content``: byte-fidelity sidecar, the exact string sent to the API when it differed from ``content``, stored as sent except lone surrogates.
+
+- `tui_gateway/server.py::_append_model_switch_marker` (snapshot 1150)
+
+### Extension `append_messages_batch`
+
+`hermes_state_messages.py::append_messages_batch`
+
+```python
+append_messages_batch(self, session_id: str, messages: List[Dict[str, Any]], compression_lock_holder: Optional[str]=None, turn_lease_holder: Optional[str]=None, chunk_rows: Optional[int]=None, turn_lease_ttl_seconds: float=300.0) -> int
+```
+
+Append *messages* in ONE write txn (all rows land or none, guards run once); returns the inserted count. ``chunk_rows`` bounds txn size for LARGE copies (branch seeds; FTS triggers run per row).
+
+- `tui_gateway/session_workdir.py::_persist_branch_seed` (snapshot 326)
+
+### Extension `assert_resume_safe`
+
+`hermes_state_messages.py::assert_resume_safe`
+
+```python
+assert_resume_safe(self, session_id: str, max_messages: Optional[int]=None, *, tip_only: bool=False) -> int
+```
+
+Resume row count, or raise ``SessionResumeTooLargeError``. ``max_messages=None`` reads config; 0 disables the guard without counting. ``tip_only`` bounds only the tip's active rows for callers that never materialize the lineage: a heavily compressed conversation is a success, not a rejection.
+
+- `tui_gateway/session_registry.py::_load_resume_transcript` (snapshot 466)
+
+### Extension `create_session`
+
+`hermes_state_sessions.py::create_session`
+
+```python
+create_session(self, session_id: str, source: str, **kwargs) -> str
+```
+
+Create (upsert) a session record. Returns the session_id.
+
+- `tui_gateway/session_workdir.py::_ensure_session_db_row` (snapshot 269)
+
+### Extension `end_session`
+
+`hermes_state_sessions.py::end_session`
+
+```python
+end_session(self, session_id: str, end_reason: str) -> None
+```
+
+Mark a session ended; the first end_reason wins (a compression split must keep ``'compression'`` even if a stale end_session() lands later); reopen_session() to re-end.
+
+- `tui_gateway/session_lifecycle.py::_finalize_session` (snapshot 256)
+
+### Extension `fts_rebuild_status`
+
+`hermes_state_search.py::fts_rebuild_status`
+
+```python
+fts_rebuild_status(self) -> Optional[Dict[str, Any]]
+```
+
+Deferred-rebuild progress ``{"pending", "total", "indexed", "percent"}`` or None. Reads via the pooled reader (not get_meta/self._lock) so search never blocks on the writer.
+
+- `tools/session_search_tool.py::_discover_payload` (snapshot 224)
+
+### Extension `get_active_message_ids`
+
+`hermes_state_messages.py::get_active_message_ids`
+
+```python
+get_active_message_ids(self, session_id: str) -> List[int]
+```
+
+Ordered physical active ids for rewind CAS checks (includes legacy harness rows projections omit).
+
+- `tui_gateway/session_workdir.py::_rewind_active_session_history` (snapshot 410)
+
+### Extension `get_ancestor_display_prefix`
+
+`hermes_state_messages.py::get_ancestor_display_prefix`
+
+```python
+get_ancestor_display_prefix(self, session_id: str) -> List[Dict[str, Any]]
+```
+
+Ancestor-only display messages of a lineage (row ``session_id != tip``) that ``session.resume`` prepends. Identified by row origin, not ``display[:len(display) - len(model)]``, so alternation repair cannot overcount.
+
+- `tui_gateway/session_registry.py::_load_resume_transcript` (snapshot 478)
+
+### Extension `get_anchored_view`
+
+`hermes_state_search.py::get_anchored_view`
+
+```python
+get_anchored_view(self, session_id: str, around_message_id: int, window: int=5, bookend: int=3, keep_roles: Optional[Tuple[str, ...]]=('user', 'assistant')) -> Dict[str, Any]
+```
+
+Anchored window (``get_messages_around``) plus session bookends, so one call yields the goal and the resolution of a long session. ``window`` is filtered to ``keep_roles`` (None disables) EXCEPT the anchor; ``bookend_start`` / ``bookend_end`` are the first/last ``bookend`` non-empty-content messages with ids strictly outside the window (empty when it overlaps the head/tail). Empty result when the anchor isn't in the session.
+
+- `tools/session_search_tool.py::_hydrate_hit` (snapshot 241)
+- `tools/session_search_tool.py::_title_match_result` (snapshot 205)
+
+### Extension `get_compression_tip`
+
+`hermes_state_compression.py::get_compression_tip`
+
+```python
+get_compression_tip(self, session_id: str) -> Optional[str]
+```
+
+Live tip of a compression chain (``get_compression_chain`` semantics); the input id when no continuation exists.
+
+- `tools/process_registry_results.py::_owns_result` (snapshot 77)
+
+### Extension `get_message_role`
+
+`hermes_state_messages.py::get_message_role`
+
+```python
+get_message_role(self, session_id: str, row_id: int) -> Optional[str]
+```
+
+Role of the active message at *row_id* in *session_id*, or ``None``.
+
+- `tools/react_to_message_tool.py::react_to_message_tool` (snapshot 43)
+
+### Extension `get_messages`
+
+`hermes_state_messages.py::get_messages`
+
+```python
+get_messages(self, session_id: str, include_inactive: bool=False, include_compacted: bool=False, limit: Optional[int]=None, offset: int=0, latest: bool=False, after_id: Optional[int]=None) -> List[Dict[str, Any]]
+```
+
+Load messages in insertion order (id, never timestamp: clocks regress). ``include_inactive``: rewind rows too; ``include_compacted``: compaction-archived display history (not rewind rows). ``latest`` pages back from the newest but returns chronological order; ``after_id``: keyset paging.
+
+- `tools/session_search_tool.py::_read_session` (snapshot 373)
+- `tools/session_search_tool.py::_title_match_result` (snapshot 202)
+
+### Extension `get_messages_around`
+
+`hermes_state_messages.py::get_messages_around`
+
+```python
+get_messages_around(self, session_id: str, around_message_id: int, window: int=5) -> Dict[str, Any]
+```
+
+Up to *window* messages either side of an anchor id (ascending). ``messages_before``/``_after`` count strictly around the anchor (fewer than *window* = session boundary). Empty for a foreign anchor.
+
+- `tools/session_search_tool.py::_scroll` (snapshot 467)
+- `tools/session_search_tool.py::_scroll` (snapshot 477)
+
+### Extension `get_messages_as_conversation`
+
+`hermes_state_messages.py::get_messages_as_conversation`
+
+```python
+get_messages_as_conversation(self, session_id: str, include_ancestors: bool=False, include_inactive: bool=False, repair_alternation: bool=False, include_row_ids: bool=False, include_compacted: bool=False) -> List[Dict[str, Any]]
+```
+
+Load messages in OpenAI format. ``include_compacted`` (deduped display history) is for DISPLAY reads only: the model-fed restore must not regrow what compaction summarized away. ``repair_alternation`` repairs the loaded list for LIVE REPLAY callers (a durable ``user;user`` pair would re-trigger the per-request repair forever); the stored transcript is never mutated.
+
+- `tui_gateway/methods_prompt.py::_load_durable_truncation_history` (snapshot 76)
+- `tui_gateway/methods_slash.py::_live_session_messages` (snapshot 85)
+- `tui_gateway/session_registry.py::_live_visible_history` (snapshot 642)
+- `tui_gateway/session_registry.py::_load_resume_transcript` (snapshot 479)
+- `tui_gateway/session_workdir.py::_rewind_active_session_history` (snapshot 411)
+
+### Extension `get_resume_conversations`
+
+`hermes_state_messages.py::get_resume_conversations`
+
+```python
+get_resume_conversations(self, session_id: str) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]
+```
+
+``(model_history, display_history)`` for a resume from ONE SELECT; byte-identical to the separate reads. model: the tip's active rows, alternation-repaired, summary marker kept for pre-compress checkpointing. display: the full lineage (``/branch`` stands alone), compaction-archived rows deduped. The display projection also includes rows preserved by IN-PLACE compaction (``active=0, compacted=1``), deduped by :meth:`_dedupe_display_generations`. Without them a compacted conversation resumes showing only its summary plus the carried-forward tail — the user's own turns read as deleted even though every row is still on disk, and the REST transcript read (which has always included them) disagreed with this one about the same session (#92080).
+
+- `tui_gateway/session_registry.py::_load_resume_transcript` (snapshot 477)
+
+### Extension `get_session`
+
+`hermes_state_sessions.py::get_session`
+
+```python
+get_session(self, session_id: str) -> Optional[Dict[str, Any]]
+```
+
+Get a session by ID (drains queued token deltas first so cost readers see exact totals).
+
+- `tools/session_search_tool.py::_get_session_meta` (snapshot 74)
+- `tools/session_search_tool.py::_title_match_result` (snapshot 198)
+- `tui_gateway/agent_factory.py::_persist_live_session_runtime` (snapshot 202)
+- `tui_gateway/server.py::_hydrate_session_cwd` (snapshot 1486)
+- `tui_gateway/session_lifecycle.py::_finalize_session` (snapshot 253)
+- `tui_gateway/session_lifecycle.py::_session_has_active_delegations` (snapshot 429)
+
+### Extension `get_session_title`
+
+`hermes_state_titles.py::get_session_title`
+
+```python
+get_session_title(self, session_id: str) -> Optional[str]
+```
+
+Get the title for a session, or None.
+
+- `tui_gateway/session_registry.py::_session_live_title` (snapshot 552)
+
+### Extension `latest_message_row_id`
+
+`hermes_state_messages.py::latest_message_row_id`
+
+```python
+latest_message_row_id(self, session_id: str, *, role: str='user', offset: int=0, require_text: bool=True) -> Optional[int]
+```
+
+Row id of the most recent active *role* message, or ``None``. ``offset`` steps back; ``require_text`` skips rows without plain-text content so "the latest message" never resolves to an invisible bubble.
+
+- `tools/react_to_message_tool.py::react_to_message_tool` (snapshot 39)
+
+### Extension `list_recent_sessions_bounded`
+
+`hermes_state_sessions.py::list_recent_sessions_bounded`
+
+```python
+list_recent_sessions_bounded(self, *, limit: int=20, exclude_sources: List[str]=None, timeout_seconds: float=3.0, candidate_limit: int=None, lineage_limit: int=None) -> List[Dict[str, Any]]
+```
+
+Latency-bounded recent-conversation browse (``session_search()``): preselect a small candidate set from the indexed durable activity timestamp (fallback ``started_at``), resolve only those across compression ancestry/chains, then hydrate activity/previews for that bounded set. Lineage traversal uses ``UNION`` plus a total-row ceiling so a corrupt cycle or a deep/branching lineage cannot defeat the bound; a lineage that hits the ceiling before a terminal root/tip is omitted, not expanded. A cooperative SQLite progress deadline interrupts sustained work past ``timeout_seconds`` and raises ``TimeoutError`` (cheap statements may finish between callbacks). Supports only the agent-tool browse filters; rich callers keep using :meth:`list_sessions_rich`.
+
+- `tools/session_search_tool.py::_list_recent_sessions._browse` (snapshot 409)
+
+### Extension `publish_session_git_metadata`
+
+`hermes_state_sessions.py::publish_session_git_metadata`
+
+```python
+publish_session_git_metadata(self, session_id: str, cwd: str, generation: int, git_branch: Optional[str]=None, git_repo_root: Optional[str]=None) -> bool
+```
+
+Publish async Git enrichment only while its cwd claim is current.
+
+- `tui_gateway/session_workdir.py::_persist_session_git_meta._run` (snapshot 491)
+
+### Extension `reopen_session`
+
+`hermes_state_sessions.py::reopen_session`
+
+```python
+reopen_session(self, session_id: str) -> None
+```
+
+Clear ended_at/end_reason so a session can be resumed; first stamp markerless legacy reset children that depend on the parent's mutable end_reason (WHERE shared with the listing predicate so they cannot drift).
+
+- `tui_gateway/session_registry.py::_schedule_resume_hydration._run` (snapshot 492)
+
+### Extension `replace_messages`
+
+`hermes_state_messages.py::replace_messages`
+
+```python
+replace_messages(self, session_id: str, messages: List[Dict[str, Any]], active_only: bool=False, archive_dropped: bool=False, reject_active_turn_lease: bool=False) -> None
+```
+
+Atomically replace a session's messages (/retry, /undo, /compress). DESTRUCTIVE by default (rows DELETEd, leave FTS). ``active_only`` spares soft-archived rows (needed with in-place compaction). ``archive_dropped`` SOFT-archives live rows rewind-style: what rewind/edit/regenerate must use, since DELETE leaves nothing to recover. ``reject_active_turn_lease``: in-txn lease check for user rewrites. Pass ``archive_dropped=True`` to SOFT-archive the live rows instead of DELETEing them: the replaced turns stay on disk with ``active = 0``, ``compacted = 0`` — the same "the user took it back" marking :meth:`rewind_to_message` applies — and stay readable via :meth:`get_messages` with ``include_inactive=True``. This is the mode a rewind/edit/regenerate must use: those flows overwrite a transcript the user may not have meant to drop, and a plain DELETE also evicts the rows from the FTS index, leaving nothing to recover from (#82756). It implies active-only handling — already-archived rows are never touched — so ``active_only`` is redundant with it. The rewritten set is inserted as fresh active rows exactly as in the destructive path, so the live view is identical either way; only the durability of the dropped turns differs.
+
+- `tui_gateway/methods_prompt.py::_truncate_history_for_submit` (snapshot 413)
+
+### Extension `resolve_session_by_title`
+
+`hermes_state_titles.py::resolve_session_by_title`
+
+```python
+resolve_session_by_title(self, title: str) -> Optional[str]
+```
+
+Resolve a title to a session ID, preferring the latest "title #N" continuation.
+
+- `tools/session_search_tool.py::_title_match_result` (snapshot 189)
+
+### Extension `rewind_to_message`
+
+`hermes_state_messages.py::rewind_to_message`
+
+```python
+rewind_to_message(self, session_id: str, target_message_id: int, *, preserve_compaction_handoff: bool=False, expected_active_ids: Optional[List[int]]=None, expected_target_content: Any=None) -> Dict[str, Any]
+```
+
+Soft-delete (``active=0``) every message with id >= *target_message_id*, target included (the caller pre-fills it as the next prompt). Returns ``{"rewound_count", "target_message", "new_head_id"}``, plus ``replacement_message_id`` with ``preserve_compaction_handoff`` (archives a composite summary carrier, inserts its hidden handoff scaffold as the new head). ``ValueError``: target missing or not ``user``. ``expected_active_ids`` / ``expected_target_content`` pin the active set and canonical live payload in-txn before any mutation (presentation-only metadata changes don't invalidate a rewind). A live turn lease refuses; expired/dead holders are reclaimed. ``rewind_count`` always increments.
+
+- `tui_gateway/session_workdir.py::_rewind_active_session_history` (snapshot 425)
+
+### Extension `search_messages`
+
+`hermes_state_search.py::search_messages`
+
+```python
+search_messages(self, query: str, source_filter: List[str]=None, exclude_sources: List[str]=None, role_filter: List[str]=None, limit: int=20, offset: int=0, sort: str=None, include_inactive: bool=False, fields: Optional[Collection[str]]=None) -> List[Dict[str, Any]]
+```
+
+:meth:`_search_messages_impl` plus one log line per slow search with the routing path taken. Threshold HERMES_SEARCH_SLOW_MS (default 1000; 0 logs every call).
+
+- `tools/session_search_tool.py::_discover` (snapshot 266)
+
+### Extension `set_latest_matching_message_display_kind`
+
+`hermes_state_messages.py::set_latest_matching_message_display_kind`
+
+```python
+set_latest_matching_message_display_kind(self, session_id: str, *, role: str, content: str, display_kind: str, display_metadata: Optional[Dict[str, Any]]=None) -> bool
+```
+
+Stamp presentation metadata on this turn's freshly persisted row (newest active row by content, right after the serial turn flushed); the model still sees ``role``/``content`` unchanged, so producer provenance survives without classifying by content at render time.
+
+- `tui_gateway/prompt_turn.py::_absorb_turn_result` (snapshot 567)
+
+### Extension `set_message_reaction`
+
+`hermes_state_messages.py::set_message_reaction`
+
+```python
+set_message_reaction(self, session_id: str, message_row_id: int, emoji: Optional[str], *, author: str='user') -> Optional[List[Dict[str, Any]]]
+```
+
+Set (``emoji=None``: clear) *author*'s reaction. Tapback semantics: one per author per message; the same emoji again clears, a different one replaces. Returns the list after the write, or ``None`` for a foreign row.
+
+- `tools/react_to_message_tool.py::react_to_message_tool` (snapshot 45)
+
+### Extension `set_session_hidden`
+
+`hermes_state_sessions.py::set_session_hidden`
+
+```python
+set_session_hidden(self, session_id: str, hidden: bool) -> bool
+```
+
+Hide/unhide a session and its compression lineage from the default listing; still resumable.
+
+- `tui_gateway/session_workdir.py::_ensure_session_db_row` (snapshot 282)
+
+### Extension `set_session_title`
+
+`hermes_state_titles.py::set_session_title`
+
+```python
+set_session_title(self, session_id: str, title: str) -> bool
+```
+
+Set a title on the user's behalf (``user`` provenance). Empty clears it. Raises ValueError on conflict or validation failure.
+
+- `tui_gateway/prompt_turn.py::_after_complete_turn` (snapshot 336)
+
+### Extension `take_unseen_reactions`
+
+`hermes_state_messages.py::take_unseen_reactions`
+
+```python
+take_unseen_reactions(self, session_id: str, *, author: str='user') -> List[Dict[str, Any]]
+```
+
+Return *author*'s not-yet-surfaced reactions and mark them seen. Reactions are announced on the NEXT user turn (never by rewriting the reacted message: cache-safe); ``seen`` makes it exactly once.
+
+- `tui_gateway/methods_prompt.py::_pending_reaction_notes` (snapshot 148)
+
+### Extension `update_session_cwd`
+
+`hermes_state_sessions.py::update_session_cwd`
+
+```python
+update_session_cwd(self, session_id: str, cwd: str, git_branch: Optional[str]=None, git_repo_root: Optional[str]=None, replace_git_meta: bool=False) -> Optional[int]
+```
+
+Persist the authoritative cwd and claim a Git metadata generation. git fields are written only when non-empty (a probe failure never clobbers a value) except under ``replace_git_meta`` (a workspace MOVE overwrites the old repo identity). Async probes publish with the returned generation so an older worker cannot overwrite a newer claim (A -> B -> A).
+
+- `tui_gateway/server.py::_hydrate_session_cwd` (snapshot 1491)
+- `tui_gateway/session_workdir.py::_persist_session_cwd_and_schedule_git_meta` (snapshot 504)
+
+### Extension `update_session_meta`
+
+`hermes_state_sessions.py::update_session_meta`
+
+```python
+update_session_meta(self, session_id: str, model_config_json: str, model: Optional[str]=None) -> None
+```
+
+Update model_config and (COALESCE) optionally model.
+
+- `tui_gateway/agent_factory.py::_persist_live_session_runtime` (snapshot 208)
+- `tui_gateway/agent_factory.py::_persist_live_session_runtime` (snapshot 209)
+
+### Extension `update_session_model`
+
+`hermes_state_sessions.py::update_session_model`
+
+```python
+update_session_model(self, session_id: str, model: str, provider: Optional[str]=None) -> None
+```
+
+Set the model after a mid-session /model switch (unconditionally), null system_prompt so stale Model:/Provider: footers rebuild, and drop any Browser runtime lock (lineage markers survive). *provider* is merged into model_config so resume recombines model and provider. When *provider* is given, it is merged into ``model_config`` alongside the model (``$.model`` / ``$.provider``) so a later resume recombines the persisted model with the provider that actually serves it instead of the config.yaml primary provider (#79536). Callers without provider knowledge leave any stored provider untouched.
+
+- `tui_gateway/agent_factory.py::_persist_live_session_runtime` (snapshot 210)
+- `tui_gateway/agent_factory.py::_persist_live_session_runtime` (snapshot 211)
+
+### Extension `update_system_prompt`
+
+`hermes_state_sessions.py::update_system_prompt`
+
+```python
+update_system_prompt(self, session_id: str, system_prompt: Optional[str]) -> None
+```
+
+Store the full assembled system prompt snapshot.
+
+- `tui_gateway/server.py::_persist_live_session_system_prompt` (snapshot 1080)
+- `tui_gateway/server.py::_persist_live_session_system_prompt` (snapshot 1092)
+
+## 9. Executable static proof and limits
+
+Run from this checkout root; this imports only Python stdlib, reads tracked source, and never opens
+state.db or launches an agent. It is an offline inventory census, NOT a source-shape regression test.
+No pytest test is added. AST handles attributes and literal indirect method names; the full report
+also emits every db-like attribute/access, dynamic getter, raw SQL call, and constructor/open/close
+candidate in the declared file scope. `conn.execute(sql,...)` is emitted verbatim; the async-delegation
+closed wrappers in §4 resolve that local SQL parameter. Name-only matching deliberately overmatches;
+the exclusions for analytics/export and common-name collisions are explicit in the executable.
+
+```sh
+python3 -c 'from pathlib import Path; p=Path("evals/shared_gateway/worker-persistence-inventory.md"); exec(p.read_text().rsplit("<!-- census:start -->",1)[1].split("```python",1)[1].split("```",1)[0])'
+# Append --full to print all source hashes, consumer mappings and access/SQL/open candidates.
+```
+
+<!-- census:start -->
+```python
+import ast
+import hashlib
+import json
+from pathlib import Path
+import subprocess
+import sys
+
+root = Path.cwd()
+tracked = subprocess.check_output(["git", "ls-files", "-z"], text=True).split("\0")
+state_files = sorted(p for p in tracked if p.startswith("hermes_state") and p.endswith(".py") and "/" not in p)
+definitions = {}
+for path in state_files:
+ source = (root / path).read_text(encoding="utf-8")
+ for node in ast.walk(ast.parse(source, filename=path)):
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ definitions.setdefault(node.name, []).append({
+ "file": path, "line": node.lineno,
+ "signature": ast.unparse(node.args),
+ "return": ast.unparse(node.returns) if node.returns else None,
+ "doc": ast.get_docstring(node),
+ })
+core = sorted(p for p in tracked if p.endswith(".py") and (
+ p == "run_agent.py" or (p.startswith("agent/") and p.count("/") == 1)
+ or (p.startswith("cron/scheduler") and p.count("/") == 1)
+ or p.startswith("tools/delegate_tool") or p == "tools/async_delegation.py"
+ or p.startswith("tui_gateway/compute_host") or p == "tui_gateway/host_supervisor.py"))
+extensions = ['tools/session_search_tool.py', 'tools/react_to_message_tool.py', 'tools/process_registry_results.py', 'tui_gateway/server.py', 'tui_gateway/agent_factory.py', 'tui_gateway/session_workdir.py', 'tui_gateway/session_registry.py', 'tui_gateway/session_lifecycle.py', 'tui_gateway/prompt_turn.py', 'tui_gateway/methods_prompt.py', 'tui_gateway/methods_slash.py']
+noise = {"add", "close", "write", "stats", "message_count", "resolve_session_id"}
+nonturn = {"agent/trace_upload.py", "agent/insights.py"}
+refs, accesses, indirect, sql, opens = [], [], [], [], []
+class Census(ast.NodeVisitor):
+ def __init__(self, path):
+ self.path, self.scope = path, []
+ def mark(self, node, value):
+ return {"file": self.path, "consumer": ".".join(self.scope), "line": node.lineno, "value": value}
+ def visit_FunctionDef(self, node):
+ self.scope.append(node.name)
+ self.generic_visit(node)
+ self.scope.pop()
+ visit_AsyncFunctionDef = visit_FunctionDef
+ def visit_Attribute(self, node):
+ value = ast.unparse(node)
+ if "db" in value.lower():
+ accesses.append(self.mark(node, value))
+ if node.attr in definitions:
+ refs.append({**self.mark(node, node.attr), "expression": value})
+ self.generic_visit(node)
+ def visit_Constant(self, node):
+ if isinstance(node.value, str) and node.value in definitions:
+ refs.append({**self.mark(node, node.value), "expression": repr(node.value)})
+ def visit_Call(self, node):
+ value = ast.unparse(node)
+ name = ast.unparse(node.func)
+ if name in {"getattr", "hasattr", "vars"} and node.args and "db" in ast.unparse(node.args[0]).lower():
+ indirect.append(self.mark(node, value))
+ if isinstance(node.func, ast.Attribute) and node.func.attr in {"execute", "executemany", "executescript"}:
+ sql.append(self.mark(node, value))
+ if name in {"SessionDB", "acquire", "sqlite3.connect", "release_or_close"}:
+ opens.append(self.mark(node, value))
+ self.generic_visit(node)
+for path in sorted(set(core + extensions)):
+ Census(path).visit(ast.parse((root / path).read_text(encoding="utf-8"), filename=path))
+core_refs = [r for r in refs if r["file"] in core and r["file"] not in nonturn and r["value"] not in noise]
+methods = sorted({r["value"] for r in core_refs})
+source_files = sorted(set(core + extensions + state_files))
+hashes = {p: hashlib.sha256((root / p).read_bytes()).hexdigest() for p in source_files}
+source_digest = hashlib.sha256(json.dumps(hashes, sort_keys=True).encode()).hexdigest()
+summary = {
+ "core_files": len(core), "extension_files": len(extensions), "source_files": len(source_files),
+ "core_candidate_references": len(core_refs), "core_operations": len(methods),
+ "source_digest": source_digest, "raw_sql_candidates": len(sql),
+ "dynamic_db_access_candidates": len(indirect), "open_close_candidates": len(opens),
+ "operation_names": methods,
+}
+if "--full" in sys.argv:
+ print(json.dumps({"summary": summary, "hashes": hashes, "core_refs": core_refs,
+ "extension_refs": [r for r in refs if r["file"] in extensions],
+ "db_accesses": accesses, "indirect": indirect, "sql": sql, "opens": opens,
+ "definitions": {k: definitions[k] for k in methods}}, indent=2))
+else:
+ print(json.dumps(summary, indent=2))
+```
+<!-- census:end -->
+
+Observed census output at the source snapshot:
+
+```json
+{
+ "core_files": 235,
+ "extension_files": 11,
+ "source_files": 271,
+ "core_candidate_references": 95,
+ "core_operations": 51,
+ "source_digest": "43b5398f1ac7f2b1811aa454b25d1040c3bd91aa20c9444ccb2173c0842bb7e9",
+ "raw_sql_candidates": 45,
+ "dynamic_db_access_candidates": 44,
+ "open_close_candidates": 26,
+ "operation_names": [
+ "acquire_session_turn_lease",
+ "append_messages_batch",
+ "archive_and_compact",
+ "clear_compression_failure_cooldown",
+ "clear_session_activity_labels",
+ "create_session",
+ "declared_scope_identity",
+ "end_session",
+ "flush_token_counts",
+ "get_active_message_watermark",
+ "get_compression_failure_cooldown",
+ "get_compression_failure_cooldown_row",
+ "get_compression_fallback_streak",
+ "get_compression_ineffective_count",
+ "get_compression_lineage",
+ "get_compression_lock_holder",
+ "get_compression_recovery_deadline",
+ "get_compression_tip",
+ "get_conversation_root",
+ "get_messages_as_conversation",
+ "get_next_title_in_lineage",
+ "get_session",
+ "get_session_model_config_value",
+ "get_session_title",
+ "get_session_title_source",
+ "is_explicit_fork_child",
+ "latest_conversation_boundary",
+ "patch_session_model_config",
+ "publish_compression_child",
+ "queue_token_counts",
+ "record_auxiliary_usage",
+ "record_compression_failure_cooldown",
+ "refresh_compression_lock",
+ "refresh_session_turn_lease",
+ "release_compression_lock",
+ "release_session_turn_lease",
+ "reopen_orphaned_compression_session",
+ "resolve_resume_session_id",
+ "restore_compression_failure_cooldown_row",
+ "session_lifecycle_statuses",
+ "set_auto_title",
+ "set_compression_fallback_streak",
+ "set_compression_ineffective_count",
+ "set_compression_recovery_deadline",
+ "set_latest_user_api_content",
+ "set_session_title",
+ "set_session_title_source",
+ "touch_session_activity",
+ "try_acquire_compression_lock",
+ "update_session_billing_route",
+ "update_system_prompt"
+ ]
+}
+```
+
+Interpretation: counts are candidate references, not dynamically executed call counts. Source digest
+is over exact file-name=>SHA256 pairs for the declared scope. No syntax errors were tolerated. The
+51 core operations are enumerated in §7; legacy title fallback absent from current SessionDB is
+classified in §5, not silently treated as a callable. Read-only source enumeration cannot prove
+network ACK timing, transaction durability after crash, runtime plugin/tool activation, profile
+ContextVar propagation, blocked-loop behavior or complete external-worker FD isolation. Those remain
+explicit acceptance blockers in §6. No worker substrate acceptance is claimed.
+
+### Checks actually executed for this document
+
+* Executed the fenced stdlib census from the worktree root: 235 core files + 11 extension files;
+ 271 total source/definition files; 95 core references covering 51 indexed operations; source digest
+ matched the recorded output. The extension index covers 34 operation names (overlaps core).
+* Programmatically checked that every core operation has an index heading and all 95 candidate
+ references have their consumer symbol recorded. Reviewed all raw-SQL/open/property candidate
+ consumer names, classifying separate verification-evidence storage and non-SQL execute calls.
+* `python3 scripts/check-windows-footguns.py --all`: passed (1534 files scanned).
+* `python3 scripts/check_compat_pointers.py`: passed (2091 pointers checked); emitted existing
+ Python invalid-escape SyntaxWarnings from other sources, not errors or changes in this Markdown.
+* No pytest suite run: this is a source-only documentation census with no production/test edit,
+ not a worker-runtime implementation. No Q2–Q8 green receipt is inferred from these checks.
diff --cc gateway/hosted_room_policy_checkpoint.py
index dcc047e8024,8de9187d30d..9f73c57443b
--- a/gateway/hosted_room_policy_checkpoint.py
+++ b/gateway/hosted_room_policy_checkpoint.py
@@@ -290,17 -293,9 +293,17 @@@ class HostedRoomPolicyCheckpoint
next_cursor = int(page.get("cursor") or cursor)
if not rows or next_cursor <= cursor:
raise RuntimeError("hosted room policy cursor did not advance")
- with self._connect() as conn:
+ with self._transaction() as conn:
conn.execute("BEGIN IMMEDIATE")
_require_room(conn, room_id)
+ current = conn.execute("SELECT through_seq FROM hosted_room_policy_cursors WHERE room_id=?",
+ (room_id,)).fetchone()
+ if current is None:
+ raise RuntimeError("room policy cursor disappeared during replay")
+ if int(current["through_seq"]) != cursor:
+ # Another worker applied the page: reload before any projection effects.
+ cursor = int(current["through_seq"])
+ continue
for event in rows:
self._apply_event(conn, event)
fenced_update(
@@@ -312,14 -307,10 +315,13 @@@
def snapshot(self, *, room_id: str, latest_seq: int) -> PolicySnapshot:
"""Return only the oldest active discussion and its watermark set."""
- through_seq = self.sync(room_id=room_id, latest_seq=latest_seq)
+ self.sync(room_id=room_id, latest_seq=latest_seq)
- with self._connect() as conn:
- conn.execute("BEGIN")
+ with self._transaction() as conn:
cursor = conn.execute(
- "SELECT stopped_through_seq FROM hosted_room_policy_cursors WHERE room_id=?", (room_id,)).fetchone()
+ "SELECT through_seq, stopped_through_seq FROM hosted_room_policy_cursors WHERE room_id=?", (room_id,)).fetchone()
+ if cursor is None:
+ raise hosted_rooms.RoomNotFoundError("hosted room checkpoint not found")
+ through_seq = int(cursor["through_seq"])
stopped_through_seq = int(cursor["stopped_through_seq"])
thread = conn.execute("""SELECT thread_id, discussion_event_id FROM hosted_room_policy_threads
WHERE room_id=? AND completed=0 AND latest_user_seq>?
@@@ -347,38 -338,12 +349,37 @@@
("""SELECT 1 FROM hosted_room_policy_publications
WHERE room_id=? AND task_id=? AND kind IN ('turn.settled', 'turn.failed', 'turn.cancelled')""",
(room_id, task_id)))
- with self._connect() as conn:
+ with self._transaction() as conn:
return conn.execute(sql, params).fetchone() is not None
- def events_for_task(self, *, room_id: str, source_event_seq: int) -> list[dict[str, Any]]:
+ def events_for_task(self, *, room_id: str, source_event_seq: int,
+ input_context: Mapping[str, Any] | None = None,
+ task_id: str | None = None) -> list[dict[str, Any]]:
"""Load one bounded discussion projection for terminal reconstruction."""
- with self._connect() as conn:
- conn.execute("BEGIN")
+ with self._transaction() as conn:
+ published = self._published_task_events(conn, room_id=room_id, task_id=task_id)
+ if input_context is not None:
+ context = validate_task_input(input_context)
+ seqs = sorted({source_event_seq, *context["event_seqs"]})
+ placeholders = ",".join("?" for _ in seqs)
+ rows = conn.execute(f"SELECT * FROM hosted_room_events WHERE room_id=? AND seq IN ({placeholders}) ORDER BY seq",
+ (room_id, *seqs)).fetchall()
+ if len(rows) != len(seqs):
+ raise RuntimeError("admitted task input event is missing")
+ events = {int(row["seq"]): _event_from_room_row(row) for row in rows}
+ source_event = events[source_event_seq]
+ thread_id = _text(source_event["payload"], "thread_id")
+ if source_event["kind"] != "message.user" or not thread_id:
+ raise RuntimeError("admitted task source is not a user discussion")
+ # Supersession remains authoritative after the display projection compacts.
+ latest = conn.execute("""SELECT * FROM hosted_room_events
+ WHERE room_id=? AND kind='message.user' AND json_extract(payload_json, '$.thread_id')=?
+ ORDER BY seq DESC LIMIT 1""", (room_id, thread_id)).fetchone()
+ if latest is not None:
+ events[int(latest["seq"])] = _event_from_room_row(latest)
+ for event in published:
+ events[int(event["seq"])] = event
+ return [events[seq] for seq in sorted(events)]
row = conn.execute(
f"SELECT {_ROOM_EVENT_COLUMNS} FROM hosted_room_events WHERE room_id=? AND seq=?",
(room_id, source_event_seq)).fetchone()
diff --cc gateway/run.py
index ce1c30f6f2f,fcaffe205a2..6505b31454d
--- a/gateway/run.py
+++ b/gateway/run.py
@@@ -2047,24 -2020,10 +2023,15 @@@ def _bridge_config_to_env(_cfg: dict) -
def _load_bridge_config(config_path: Path) -> dict:
- """Raw config read for the presence-sensitive env bridge, with the managed overlay applied. Raw (not
- defaults-merged) so only keys the user wrote are bridged, else all of DEFAULT_CONFIG would be
- exported; the overlay applies BEFORE bridging so pinned values win in env too. A bypass worker
- bridges its frozen explicit snapshot instead: the profile file is exactly what it must not read."""
+ """Effective USER config (no defaults) for the presence-sensitive env bridge: only keys the user
- or the managed layer wrote get bridged, else all of DEFAULT_CONFIG would be exported."""
++ or the managed layer wrote get bridged, else all of DEFAULT_CONFIG would be exported. A bypass
++ worker bridges its frozen explicit snapshot instead: the profile file is exactly what it must not read."""
+ from agent.safe_worker_policy import worker_config_snapshot
+ snapshot = worker_config_snapshot()
+ if snapshot is not None:
+ return snapshot
- from hermes_cli.config import _expand_env_vars, read_user_config_raw
- cfg = _expand_env_vars(read_user_config_raw(config_path))
- if not isinstance(cfg, dict):
- cfg = {}
- try:
- from hermes_cli import managed_scope
- cfg = managed_scope.apply_managed_overlay(cfg)
- except Exception:
- pass
- return cfg
+ from hermes_cli.config_effective import load_user_config_effective
+ return load_user_config_effective(config_path)
_config_path = _hermes_home / 'config.yaml'
diff --cc hermes_cli/env_loader.py
index 83bda8337e2,f42501dec58..decf2857a94
--- a/hermes_cli/env_loader.py
+++ b/hermes_cli/env_loader.py
@@@ -336,13 -319,10 +323,16 @@@ def load_hermes_dotenv
) -> list[Path]:
"""Load Hermes env files: ``~/.hermes/.env`` overrides stale shell exports; project ``.env`` is a dev
fallback that only fills gaps when the user env exists (and overrides shell vars when it does not)."""
+ from agent.safe_worker_policy import worker_config_snapshot
+
+ # The private bootstrap supplies credentials explicitly; do not rehydrate
+ # profile behavior, external secret plugins, or managed env in this worker.
+ if worker_config_snapshot() is not None:
+ return []
- home_path = Path(hermes_home or os.getenv("HERMES_HOME", Path.home() / ".hermes"))
+ # Process home on purpose (never the per-turn override): a startup .env load must not follow a routed
+ # profile — see the multiplex guard below.
+ from hermes_constants import get_process_hermes_home
+ home_path = Path(hermes_home) if hermes_home else get_process_hermes_home()
# Multiplex gateway: while a routed profile-home override is active, copying that profile's .env
# into os.environ would expose its credentials to sibling turns and every spawned child. Unscoped
diff --cc tests/acp_adapter/test_catalog_read_only.py
index 4d4ea41b429,00000000000..4d4ea41b429
mode 100644,000000..100644
--- a/tests/acp_adapter/test_catalog_read_only.py
+++ b/tests/acp_adapter/test_catalog_read_only.py
diff --cc tests/acp_adapter/test_gateway_cancel_admission.py
index e046230495b,00000000000..e046230495b
mode 100644,000000..100644
--- a/tests/acp_adapter/test_gateway_cancel_admission.py
+++ b/tests/acp_adapter/test_gateway_cancel_admission.py
diff --cc tests/acp_adapter/test_gateway_catalog_cwd.py
index d4385d95392,00000000000..d4385d95392
mode 100644,000000..100644
--- a/tests/acp_adapter/test_gateway_catalog_cwd.py
+++ b/tests/acp_adapter/test_gateway_catalog_cwd.py
diff --cc tests/acp_adapter/test_gateway_client_boundary.py
index 817b50e3622,00000000000..817b50e3622
mode 100644,000000..100644
--- a/tests/acp_adapter/test_gateway_client_boundary.py
+++ b/tests/acp_adapter/test_gateway_client_boundary.py
diff --cc tests/acp_adapter/test_gateway_controls.py
index d273bb78fc7,00000000000..d273bb78fc7
mode 100644,000000..100644
--- a/tests/acp_adapter/test_gateway_controls.py
+++ b/tests/acp_adapter/test_gateway_controls.py
diff --cc tests/acp_adapter/test_gateway_editor_cwd.py
index ff5dd1e8eb1,00000000000..ff5dd1e8eb1
mode 100644,000000..100644
--- a/tests/acp_adapter/test_gateway_editor_cwd.py
+++ b/tests/acp_adapter/test_gateway_editor_cwd.py
diff --cc tests/acp_adapter/test_gateway_editor_mcp.py
index 2baf383dbc3,00000000000..2baf383dbc3
mode 100644,000000..100644
--- a/tests/acp_adapter/test_gateway_editor_mcp.py
+++ b/tests/acp_adapter/test_gateway_editor_mcp.py
diff --cc tests/acp_adapter/test_gateway_editor_policy.py
index 0065e3d174d,00000000000..0065e3d174d
mode 100644,000000..100644
--- a/tests/acp_adapter/test_gateway_editor_policy.py
+++ b/tests/acp_adapter/test_gateway_editor_policy.py
diff --cc tests/acp_adapter/test_gateway_editor_v4a.py
index 6130a3eb1a5,00000000000..6130a3eb1a5
mode 100644,000000..100644
--- a/tests/acp_adapter/test_gateway_editor_v4a.py
+++ b/tests/acp_adapter/test_gateway_editor_v4a.py
diff --cc tests/acp_adapter/test_gateway_editor_wire.py
index 79d3e474118,00000000000..79d3e474118
mode 100644,000000..100644
--- a/tests/acp_adapter/test_gateway_editor_wire.py
+++ b/tests/acp_adapter/test_gateway_editor_wire.py
diff --cc tests/acp_adapter/test_gateway_entry_lifecycle.py
index 0433d47476c,00000000000..0433d47476c
mode 100644,000000..100644
--- a/tests/acp_adapter/test_gateway_entry_lifecycle.py
+++ b/tests/acp_adapter/test_gateway_entry_lifecycle.py
diff --cc tests/acp_adapter/test_gateway_new_cold.py
index 13da7599ae5,00000000000..13da7599ae5
mode 100644,000000..100644
--- a/tests/acp_adapter/test_gateway_new_cold.py
+++ b/tests/acp_adapter/test_gateway_new_cold.py
diff --cc tests/acp_adapter/test_gateway_prompt_content.py
index fe90976dd04,00000000000..fe90976dd04
mode 100644,000000..100644
--- a/tests/acp_adapter/test_gateway_prompt_content.py
+++ b/tests/acp_adapter/test_gateway_prompt_content.py
diff --cc tests/acp_adapter/test_gateway_sessions.py
index 8473d0a252b,00000000000..8473d0a252b
mode 100644,000000..100644
--- a/tests/acp_adapter/test_gateway_sessions.py
+++ b/tests/acp_adapter/test_gateway_sessions.py
diff --cc tests/acp_adapter/test_gateway_terminal_projection.py
index 3d7a66e9640,00000000000..3d7a66e9640
mode 100644,000000..100644
--- a/tests/acp_adapter/test_gateway_terminal_projection.py
+++ b/tests/acp_adapter/test_gateway_terminal_projection.py
diff --cc tests/acp_adapter/test_gateway_tool_projection.py
index 03b2cbde0ca,00000000000..03b2cbde0ca
mode 100644,000000..100644
--- a/tests/acp_adapter/test_gateway_tool_projection.py
+++ b/tests/acp_adapter/test_gateway_tool_projection.py
diff --cc tests/acp_adapter/test_gateway_wire_controls.py
index 73491108ae3,00000000000..73491108ae3
mode 100644,000000..100644
--- a/tests/acp_adapter/test_gateway_wire_controls.py
+++ b/tests/acp_adapter/test_gateway_wire_controls.py
diff --cc tests/acp_adapter/test_policy_identity_compat.py
index aabcf9f5923,00000000000..aabcf9f5923
mode 100644,000000..100644
--- a/tests/acp_adapter/test_policy_identity_compat.py
+++ b/tests/acp_adapter/test_policy_identity_compat.py
diff --cc tests/acp_adapter/test_session_mcp_frozen.py
index 465d58aeebd,00000000000..465d58aeebd
mode 100644,000000..100644
--- a/tests/acp_adapter/test_session_mcp_frozen.py
+++ b/tests/acp_adapter/test_session_mcp_frozen.py
diff --cc tests/acp_adapter/test_session_mcp_policy.py
index cb4ad1dbd9d,00000000000..cb4ad1dbd9d
mode 100644,000000..100644
--- a/tests/acp_adapter/test_session_mcp_policy.py
+++ b/tests/acp_adapter/test_session_mcp_policy.py
diff --cc tests/cron/test_scheduler.py
index 4b6bf53b866,029040b6132..60ddcee3a9a
--- a/tests/cron/test_scheduler.py
+++ b/tests/cron/test_scheduler.py
@@@ -1135,13 -1117,11 +1136,11 @@@ class TestRunJobConfigLogging
mock_agent.run_conversation.return_value = {"final_response": "ok"}
mock_agent_cls.return_value = mock_agent
- with caplog.at_level(logging.WARNING, logger="cron.scheduler"):
- success, _, _, error = _run_owned_job(job, tmp_path)
+ with caplog.at_level(logging.WARNING):
- run_job(job)
++ _run_owned_job(job, tmp_path)
- assert success is False
- assert "Refusing non-interactive startup" in error
- assert any("refusing to run" in r.message for r in caplog.records)
- mock_agent_cls.assert_not_called()
+ assert any("Failed to parse" in r.message and "config.yaml" in r.message for r in caplog.records), \
+ f"Expected a config.yaml parse warning in logs, got: {[r.message for r in caplog.records]}"
class TestRunJobConfigEnvVarExpansion:
diff --cc tests/hermes_state/test_ledger_delete_consistency.py
index f1606064378,00000000000..f1606064378
mode 100644,000000..100644
--- a/tests/hermes_state/test_ledger_delete_consistency.py
+++ b/tests/hermes_state/test_ledger_delete_consistency.py
diff --cc tests/hermes_state/test_runtime_admission.py
index c6376cfadcc,00000000000..c6376cfadcc
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_admission.py
+++ b/tests/hermes_state/test_runtime_admission.py
diff --cc tests/hermes_state/test_runtime_adoption.py
index bbe5bcf6275,00000000000..bbe5bcf6275
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_adoption.py
+++ b/tests/hermes_state/test_runtime_adoption.py
diff --cc tests/hermes_state/test_runtime_destructive_mutations.py
index ee3ecb85a99,00000000000..ee3ecb85a99
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_destructive_mutations.py
+++ b/tests/hermes_state/test_runtime_destructive_mutations.py
diff --cc tests/hermes_state/test_runtime_import_mutations.py
index a31b3a900f3,00000000000..a31b3a900f3
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_import_mutations.py
+++ b/tests/hermes_state/test_runtime_import_mutations.py
diff --cc tests/hermes_state/test_runtime_mutation_actions.py
index ed2fc36d3c3,00000000000..ed2fc36d3c3
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_mutation_actions.py
+++ b/tests/hermes_state/test_runtime_mutation_actions.py
diff --cc tests/hermes_state/test_runtime_mutation_retired_import.py
index b0cfb694805,00000000000..b0cfb694805
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_mutation_retired_import.py
+++ b/tests/hermes_state/test_runtime_mutation_retired_import.py
diff --cc tests/hermes_state/test_runtime_mutations.py
index 5d7b6c17811,00000000000..5d7b6c17811
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_mutations.py
+++ b/tests/hermes_state/test_runtime_mutations.py
diff --cc tests/hermes_state/test_runtime_recovery.py
index 691a18f7844,00000000000..691a18f7844
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_recovery.py
+++ b/tests/hermes_state/test_runtime_recovery.py
diff --cc tests/hermes_state/test_runtime_rewind_mutations.py
index 967859dde52,00000000000..967859dde52
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_rewind_mutations.py
+++ b/tests/hermes_state/test_runtime_rewind_mutations.py
diff --cc tests/hermes_state/test_runtime_schema.py
index d33be27ce86,00000000000..d33be27ce86
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_schema.py
+++ b/tests/hermes_state/test_runtime_schema.py
diff --cc tests/hermes_state/test_runtime_worker.py
index f1e74a9febb,00000000000..f1e74a9febb
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_worker.py
+++ b/tests/hermes_state/test_runtime_worker.py
diff --cc tests/hermes_state/test_runtime_worker_compaction.py
index 480e93bda69,00000000000..480e93bda69
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_worker_compaction.py
+++ b/tests/hermes_state/test_runtime_worker_compaction.py
diff --cc tests/hermes_state/test_runtime_worker_compression.py
index 1f92bef4ecd,00000000000..1f92bef4ecd
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_worker_compression.py
+++ b/tests/hermes_state/test_runtime_worker_compression.py
diff --cc tests/hermes_state/test_runtime_worker_compression_admission.py
index e708f878655,00000000000..e708f878655
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_worker_compression_admission.py
+++ b/tests/hermes_state/test_runtime_worker_compression_admission.py
diff --cc tests/hermes_state/test_runtime_worker_compression_annotations.py
index ee88fcc7f74,00000000000..ee88fcc7f74
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_worker_compression_annotations.py
+++ b/tests/hermes_state/test_runtime_worker_compression_annotations.py
diff --cc tests/hermes_state/test_runtime_worker_compression_cleanup.py
index 60e0440b9d3,00000000000..60e0440b9d3
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_worker_compression_cleanup.py
+++ b/tests/hermes_state/test_runtime_worker_compression_cleanup.py
diff --cc tests/hermes_state/test_runtime_worker_compression_flush.py
index e57ce287749,00000000000..e57ce287749
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_worker_compression_flush.py
+++ b/tests/hermes_state/test_runtime_worker_compression_flush.py
diff --cc tests/hermes_state/test_runtime_worker_context.py
index 51b8cc96d5b,00000000000..51b8cc96d5b
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_worker_context.py
+++ b/tests/hermes_state/test_runtime_worker_context.py
diff --cc tests/hermes_state/test_runtime_worker_history.py
index 0bae5208191,00000000000..0bae5208191
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_worker_history.py
+++ b/tests/hermes_state/test_runtime_worker_history.py
diff --cc tests/hermes_state/test_runtime_worker_lifecycle.py
index e31c45fb378,00000000000..e31c45fb378
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_worker_lifecycle.py
+++ b/tests/hermes_state/test_runtime_worker_lifecycle.py
diff --cc tests/hermes_state/test_runtime_worker_metadata.py
index bebaad46ee9,00000000000..bebaad46ee9
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_worker_metadata.py
+++ b/tests/hermes_state/test_runtime_worker_metadata.py
diff --cc tests/hermes_state/test_runtime_worker_operations.py
index 6fbde4aeb20,00000000000..6fbde4aeb20
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_worker_operations.py
+++ b/tests/hermes_state/test_runtime_worker_operations.py
diff --cc tests/hermes_state/test_runtime_worker_rotation_automation.py
index 5f58968adfd,00000000000..5f58968adfd
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_worker_rotation_automation.py
+++ b/tests/hermes_state/test_runtime_worker_rotation_automation.py
diff --cc tests/hermes_state/test_runtime_worker_title_retry.py
index f4cf6a7d392,00000000000..f4cf6a7d392
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_worker_title_retry.py
+++ b/tests/hermes_state/test_runtime_worker_title_retry.py
diff --cc tests/hermes_state/test_runtime_worker_turn_cleanup.py
index 536beb921f6,00000000000..536beb921f6
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_worker_turn_cleanup.py
+++ b/tests/hermes_state/test_runtime_worker_turn_cleanup.py
diff --cc tests/hermes_state/test_runtime_worker_usage.py
index ee30b0b1a07,00000000000..ee30b0b1a07
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_worker_usage.py
+++ b/tests/hermes_state/test_runtime_worker_usage.py
diff --cc tests/hermes_state/test_terminal_retirement.py
index 4f593de387b,00000000000..4f593de387b
mode 100644,000000..100644
--- a/tests/hermes_state/test_terminal_retirement.py
+++ b/tests/hermes_state/test_terminal_retirement.py
diff --cc tests/tui_gateway/test_bot_relay_methods.py
index ec1b0a136d2,4ce12bf763e..c2656b2383f
--- a/tests/tui_gateway/test_bot_relay_methods.py
+++ b/tests/tui_gateway/test_bot_relay_methods.py
@@@ -167,23 -265,59 +168,48 @@@ SENDER = {"from_profile": "scout", "fro
SENDER_AUTHOR = {"id": "bot:cloud-1/scout", "name": "scout", "is_bot": True}
[email protected]("identity", [
- None,
- {"user_id": INTERNAL_USER_ID, "provider": INTERNAL_PROVIDER},
-], ids=["no identity", "server-internal identity"])
-def test_deliver_accepts_a_sender_from_an_admitted_non_login_client(home, fake_runs, bound_client, identity):
- """The Desktop and server-internal callers carry no login identity; their sender fields become the author."""
- from agent.turn_author import TURN_AUTHOR_ENV
-
- calls, _outcomes = fake_runs
[email protected]("identity, refused", [
+ (None, False),
+ ({"user_id": INTERNAL_USER_ID, "provider": INTERNAL_PROVIDER}, False),
+ ({"user_id": "alice", "provider": "google"}, True),
+])
+def test_relay_sender_attribution_obeys_transport_identity(home, monkeypatch, bound_client, identity, refused):
+ from tools import bot_live_delivery as live
+ forwarded = []
+ monkeypatch.setattr(live, "authority_delivery",
+ lambda home, params: forwarded.append(params) or {"status": "queued"})
bound_client.auth_identity = identity
-
- _result(srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": "ping", **SENDER}))
-
- assert [json.loads(c["env"][TURN_AUTHOR_ENV]) for c in calls] == [SENDER_AUTHOR]
-
-
-def test_deliver_refuses_a_sender_from_a_logged_in_client(home, fake_runs, bound_client):
- """A browser login never relays for another connection, so its from_* fields are refused before any turn runs.
- Without sender fields the same client still delivers, unattributed."""
- from agent.turn_author import TURN_AUTHOR_ENV
-
- calls, _outcomes = fake_runs
- bound_client.auth_identity = {"user_id": "alice", "provider": "google"}
-
- for sender in ({"from_profile": "scout"}, {"from_connection": "cloud-1"}, SENDER):
- err = srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": "ping", **sender})
- assert err["error"]["code"] == 4095
- assert not calls
-
- _result(srv._methods["bot_relay.deliver"](2, {"profile": "ops", "message": "ping"}))
- assert len(calls) == 1 and TURN_AUTHOR_ENV not in calls[0]["env"]
+ result = srv._methods["bot_relay.deliver"](1, {
+ "id": "f" * 32, "profile": "ops", "message": "ping", **SENDER})
+ if refused:
+ assert result["error"]["code"] == 4095
+ assert not forwarded
+ else:
+ assert _result(result)["status"] == "queued"
+ assert forwarded[0]["author"] == SENDER_AUTHOR
+ assert not any(key in forwarded[0] for key in SENDER)
+
+
+ @pytest.mark.parametrize("subdir", ["profiles/ops", "dev"])
+ def test_gateway_drains_the_mailbox_the_tools_write_to(tmp_path, monkeypatch, subdir):
+ """Both ends of the relay mailbox derive the install root from HERMES_HOME with ONE formula.
+ The writer side (``message_agent``'s ``_hermes_root``) and the drain side
+ (``methods_bot_relay._relay_root``) must agree for a ``profiles/<name>`` home AND for an
+ arbitrary subdir of the native ``~/.hermes`` — a split here is silent non-delivery."""
+ from tools.bot_mode_probe import _default_home, _hermes_root
+ from tui_gateway import methods_bot_relay
+
+ monkeypatch.setenv("HOME", str(tmp_path))
+ home = tmp_path / ".hermes" / subdir
+ home.mkdir(parents=True)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+
+ writer_root = _hermes_root(Path(_default_home()))
+ target = {"profile": "scout", "handle": "scout", "connection_id": "cloud-1",
+ "connection_label": "", "title": "", "description": ""}
+ env = bot_relay.enqueue_envelope(
+ writer_root, target=target, message="m", sender_profile="default", sender_handle="hermes")
+
+ assert methods_bot_relay._relay_root() == writer_root
+ drained = _result(srv._methods["bot_relay.outbox.drain"](1, {}))
+ assert [e["id"] for e in drained["envelopes"]] == [env["id"]]
diff --cc tools/async_delegation.py
index 6ce8d96668e,0069015e7e3..bd739b4cb34
--- a/tools/async_delegation.py
+++ b/tools/async_delegation.py
@@@ -84,17 -82,19 +83,22 @@@ def _db_path()
def _connect() -> sqlite3.Connection:
+ from agent.runtime_session_store import WorkerPersistenceError, is_worker_process
+ if is_worker_process():
+ raise WorkerPersistenceError('worker_delegation_ledger_unavailable')
+ from hermes_cli.sqlite_util import open_db
+ # Same state.db as hermes_state.SessionDB -- reuse its owner-only (0600)
+ # hardening so this writer doesn't create/leave the file (and its WAL
+ # sidecars) at the process umask. See hermes_state._secure_state_db_files.
+ from hermes_state import _secure_state_db_files
+
path = _db_path()
path.parent.mkdir(parents=True, exist_ok=True)
- conn = sqlite3.connect(path, timeout=10)
- try:
- _initialize_schema(conn)
- except Exception:
- conn.close() # don't leak the connection on PRAGMA/DDL failure
- raise
+ _secure_state_db_files(path, create_main=True)
+ # wal=False: SessionDB owns state.db's journal mode (_initialize_schema applies the barriers).
+ conn = open_db(path, db_label="state.db (async_delegation)", busy_timeout_ms=10_000,
+ wal=False, row_factory=None, initialize=_initialize_schema)
+ _secure_state_db_files(path)
return conn
diff --cc tools/bot_mode_dm.py
index 09a4da2d853,99d31317bfd..9b089c18c5b
--- a/tools/bot_mode_dm.py
+++ b/tools/bot_mode_dm.py
@@@ -361,11 -362,54 +362,10 @@@ def _delivery_lock(argv: list[str], *,
return acquire_turn_lock(_hermes_root(Path(_default_home())), argv[2])
-def _run_local_turn(argv: list[str], dm_file: str, *, env: Optional[dict[str, str]] = None) -> int:
- """One Bot Chat turn via ``--query-file`` (plus one policy-gated retry); re-emits
- the transport's streams and returns its exit code. Transient failures re-run the
- same session; a context_overflow re-run lets the retried turn's pre-API compaction
- compact the transcript first (no fresh session is ever minted). Auth/quota/config never retry."""
-
- def _turn():
- return subprocess.run([*argv, "--query-file", dm_file], check=False, stdin=subprocess.DEVNULL,
- capture_output=True, text=True, env=env)
-
- proc = _turn()
- if proc.returncode != 0:
- from tools.bot_failure_reasons import RETRY_NONE, classify_agent_error, retry_action
-
- if retry_action(classify_agent_error((proc.stderr or proc.stdout or "").strip()[-500:])) != RETRY_NONE:
- proc = _turn()
- stderr_text = proc.stderr or ""
- reason = next((line.removeprefix("hermes-refusal-reason: ").strip()
- for line in stderr_text.splitlines()
- if line.startswith("hermes-refusal-reason: ")), None)
- # A code wins over prose, including unknown codes from newer CLIs.
- # Only older CLIs without a marker need the historical wording fallback.
- refused_not_owned = (reason == "SESSION_NOT_OWNED" if reason is not None
- else "already has a live owner" in stderr_text)
- if proc.returncode != 0 and refused_not_owned:
- # The target's Bot Chat is held live by another surface (Desktop); the turn
- # never ran — tell the sender plainly instead of leaking a raw lease error.
- # See #100523.
- who = argv[argv.index("-p") + 1] if "-p" in argv[:-1] else "the teammate"
- print(json.dumps({
- "error": f"Delivery failed: @{who}'s Bot Chat is open on another "
- "surface right now, so your message was NOT delivered. Try again later.",
- "reason": "target_busy",
- }))
- return 1
- # Re-emit the transport's streams: stdout is the reply text the
- # completion notification carries back to the sending agent.
- for stream, text in ((sys.stdout, proc.stdout), (sys.stderr, proc.stderr)):
- if text:
- stream.write(text)
- stream.flush()
- return proc.returncode
-
-
def _admit_live_dm(profile_home: Path | None, dm_file: str, author: Optional[dict] = None) -> dict | None:
"""Pin intent before admission; retries may inspect, never change transport."""
- from tools.bot_live_delivery import (
- _fsync_dir, deliver_to_live_owner, find_canonical_live_owner, read_delivery_result,
- )
+ from tools.bot_live_delivery import deliver_to_live_owner, find_canonical_live_owner, read_delivery_result
+ from utils import fsync_directory
intent: dict[str, Any]
intent_path = Path(dm_file + ".live.json")
@@@ -388,10 -432,10 +388,10 @@@
json.dump(intent, stream)
stream.flush()
os.fsync(stream.fileno())
- _fsync_dir(intent_path.parent)
+ fsync_directory(intent_path.parent)
home = intent["owner"]["profile_home"]
record = read_delivery_result(home, intent["delivery_id"])
- if record is None:
+ if record is None or intent["owner"].get("canonical"):
record = deliver_to_live_owner(home, intent["owner"], intent["message"],
delivery_id=intent["delivery_id"], author=intent.get("author"))
return record
diff --cc tools/bot_relay.py
index 1526d89d2b3,eb1fcc4a673..f2b13558efb
--- a/tools/bot_relay.py
+++ b/tools/bot_relay.py
@@@ -295,16 -278,8 +285,16 @@@ def write_reply(root: Path | str, envel
from tools.bot_failure_reasons import classify_agent_error
code = classify_agent_error(err)
+ from tools.bot_live_delivery import _locked, _read, _write
path = base / REPLIES_DIR / f"{safe}.json"
- _atomic_write_json(path, {"id": safe, "at": int(time.time()), "reply": str(reply or ""), "error": err, "reason": code})
+ outcome = {"reply": str(reply or ""), "error": err, "reason": code}
+ with _locked(root):
+ existing = _read(path)
+ if existing is not None:
+ if any(existing.get(key) != value for key, value in outcome.items()):
+ raise ValueError("delivery already has a different reply")
+ return path
- _write(path, {"id": safe, "at": int(time.time()), **outcome})
++ _atomic_write_json(path, {"id": safe, "at": int(time.time()), **outcome})
return path
diff --cc tui_gateway/agent_factory.py
index 61a71f09068,00000000000..c1cc9dace80
mode 100644,000000..100644
--- a/tui_gateway/agent_factory.py
+++ b/tui_gateway/agent_factory.py
@@@ -1,547 -1,0 +1,552 @@@
+"""TUI agent_factory seam; functions bind to the server namespace at registration."""
+
+from __future__ import annotations
+
+from .method_ctx import bind_module
+
+def _env_model_seed() -> str:
+ """The launch-scoped model seed (``hermes --tui -m``, hosted provisioning); "" when unset."""
+ return (os.environ.get("HERMES_MODEL", "") or os.environ.get("HERMES_INFERENCE_MODEL", "")).strip()
+
+
+def _resolve_model() -> str:
+ if env := _env_model_seed():
+ return env
+ m = _load_cfg().get("model", "")
+ if isinstance(m, dict):
+ return str(m.get("default", "") or "").strip()
+ if isinstance(m, str) and m:
+ return m.strip()
+ # No env seed / config preference: the cost-safe silent default (cache-only read), never an unpicked flagship.
+ with contextlib.suppress(Exception):
+ from hermes_cli.models import get_preferred_silent_default_model
+ return get_preferred_silent_default_model()
+ return "z-ai/glm-5.2"
+
+
+def _resolve_session_platform() -> str:
+ """``HERMES_DESKTOP=1`` without ``HERMES_DESKTOP_TERMINAL`` → "desktop" (chat panel; the agent then
+ suggests TUI-only slash commands), else "tui" (embedded terminal pane or standalone ``hermes --tui``)."""
+ desktop = is_truthy_value(os.environ.get("HERMES_DESKTOP"))
+ return "desktop" if desktop and not is_truthy_value(os.environ.get("HERMES_DESKTOP_TERMINAL")) else "tui"
+
+
+def _resolve_session_source(explicit: str | None) -> str:
+ """Session DB ``source``: an explicit caller value (plugin session tagged ``"telegram"``) is never
+ rewritten; only empty/None falls back to the env-resolved platform."""
+ return explicit or _resolve_session_platform()
+
+
+def _resolve_agent_platform(source: str | None) -> str:
+ return _resolve_session_source(source)
+
+
+def _config_model_target() -> tuple[str, str]:
+ """(model, provider) selected by config.yaml — and ONLY config: the HERMES_MODEL launch seed fed into
+ the per-turn sync would be replayed as a /model switch and persisted globally, or pin the session so
+ dashboard/CLI model changes never reach an open chat. Empty model = "no preference" → no-op sync."""
+ cfg_model = _load_cfg().get("model")
+ if isinstance(cfg_model, dict):
+ provider = str(cfg_model.get("provider") or "").strip()
+ return str(cfg_model.get("default", "") or "").strip(), "" if provider.lower() == "auto" else provider
+ return (cfg_model.strip() if isinstance(cfg_model, str) else ""), ""
+
+
+def _resolve_startup_runtime() -> tuple[str, str | None]:
+ model = _resolve_model()
+ if explicit_provider := os.environ.get("HERMES_TUI_PROVIDER", "").strip():
+ return model, explicit_provider
+ if not (explicit_model := _env_model_seed()):
+ return model, None
+ with contextlib.suppress(Exception):
+ from hermes_cli.models import detect_static_provider_for_model
+ cfg = _load_cfg().get("model") or {}
+ current_provider = ((str(cfg.get("provider") or "").strip().lower() if isinstance(cfg, dict) else "")
+ or os.environ.get("HERMES_INFERENCE_PROVIDER", "").strip().lower() or "auto")
+ if detected := detect_static_provider_for_model(explicit_model, current_provider):
+ provider, detected_model = detected
+ return detected_model, provider
+ return model, None
+
+
+# Bare billing buckets are not routable provider identities; restoring one as a session provider override
+# breaks resume. ``openrouter`` is deliberately NOT in this set (fully routable; agent_init's gate is a different set).
+# (agent_init's fail-fast gate is a DIFFERENT set that also skips "openrouter" — there it means "default
+# route, don't fail fast", not "unroutable".) ``openrouter`` is deliberately excluded here — it is a fully
+# routable provider with its own API key and base_url. Sessions that used OpenRouter store
+# ``billing_provider="openrouter"``; dropping it forces resume to the current global model (e.g. a custom
+# endpoint), which is the wrong provider for the stored model. See #57588.
+
+
+def _is_routable_provider(provider: str) -> bool:
+ with contextlib.suppress(Exception):
+ from hermes_cli.runtime_provider import is_routable_provider
+ return is_routable_provider(provider)
+ return False
+
+
+def _overrides_have_routable_provider(overrides: dict) -> bool:
+ """Whether persisted runtime overrides still name a routable provider (renamed/removed → "Unknown
+ provider" at agent init). Empty = NOT routable, so the caller falls back to the session's picked model."""
+ provider = str(overrides.get("provider_override") or "").strip()
+ if not provider:
+ provider = str((overrides.get("model_override") or {}).get("provider") or "").strip()
+ return bool(provider) and _is_routable_provider(provider)
+
+
+def _parse_model_config(raw, *, quiet: bool = False) -> dict:
+ """A row's ``model_config`` (dict or JSON text) as a dict; ``{}`` when absent/invalid."""
+ if isinstance(raw, dict):
+ return raw
+ if isinstance(raw, str) and raw.strip():
+ try:
+ parsed = json.loads(raw)
+ return parsed if isinstance(parsed, dict) else {}
+ except Exception:
+ if not quiet:
+ raise
+ logger.debug("failed to parse stored session model_config", exc_info=True)
+ return {}
+
+
+def _stored_session_runtime_overrides(row: dict | None) -> dict:
+ """Runtime fields persisted with a stored session (model column, ``billing_provider``, JSON ``model_config``):
+ resume restores the model/provider/reasoning THAT chat used, not the global pick. Plugin-owned Bot-Mode
+ sessions are exempt and rebuild from the member profile's CURRENT config (a stale provider pin left
+ room bots "out of Nous credits" after a profile switch); signals: ``room_plumbing`` /
+ ``follow_profile_config`` markers, the legacy hidden + "Group:" title, the title exactly "Bot Chat"."""
+ if not row:
+ return {}
+ model_config = _parse_model_config(row.get("model_config"), quiet=True)
+ _row_title = str(row.get("title") or "").strip()
+ if (model_config.get("room_plumbing") or (row.get("hidden") and _row_title.startswith("Group:"))
+ or model_config.get("follow_profile_config") or _row_title == "Bot Chat"):
+ return {}
+ overrides: dict = {}
+ field = lambda k: str(model_config.get(k) or "").strip()
+ model = str(row.get("model") or model_config.get("model") or "").strip()
+ # ``billing_provider`` is only the billing bucket — for a custom endpoint the bare class "custom", which
+ # agent_init treats as non-routable. Only restore an explicit provider; else resume uses the configured default.
+ provider = field("provider")
+ billing_provider = str(model_config.get("billing_provider") or row.get("billing_provider") or "").strip()
+ if not provider and billing_provider.lower() not in _BARE_BILLING_PROVIDERS:
+ provider = billing_provider
+ base_url, api_mode, service_tier = field("base_url"), field("api_mode"), field("service_tier")
+ reasoning_config = model_config.get("reasoning_config")
+ # Heal a stale provider persisted by an older build (renamed/removed custom provider → "Unknown provider"):
+ # recover ``custom:<name>`` from the stored base_url, then from the entry serving the model; else drop it.
+ if provider and not _is_routable_provider(provider):
+ healed = None
+ try:
+ from hermes_cli.runtime_provider import canonical_custom_identity
+ healed = canonical_custom_identity(base_url=base_url or None, model=model or None)
+ except Exception:
+ logger.debug("custom provider identity recovery failed", exc_info=True)
+ if healed:
+ logger.info("healed stale session provider %r to %r", provider, healed)
+ provider = healed
+ base_url = "" # the healed identity owns a registered endpoint; the snapshot URL must not override it
+ else:
+ provider = ""
+ if model:
+ # Same dict-shaped override live /model switches use, so a DB-restored session keeps custom endpoint
+ # metadata across resume and rebuilds (/new). Raw api_key is never persisted/restored.
+ overrides["model_override"] = {
+ "model": model, "provider": provider or None, "base_url": base_url or None, "api_mode": api_mode or None}
+ if provider:
+ overrides["provider_override"] = provider
+ if isinstance(reasoning_config, dict):
+ overrides["reasoning_config_override"] = reasoning_config
+ if service_tier: # None = "inherit the profile" at _make_agent; "" = real override "no priority tier"
+ overrides["service_tier_override"] = "" if service_tier.lower() == "normal" else service_tier
+ return overrides
+
+
+def _runtime_model_config(agent, existing: dict | None = None) -> dict:
+ """Merge the agent's CURRENT runtime identity onto the row's persisted ``model_config``. Falsy agent
+ attributes DELETE the key rather than skip the write: resume reads provider/endpoint from this JSON
+ (model column written separately), so a stale provider would route the resumed chat to the wrong endpoint."""
+ config = dict(existing or {})
+ attr = lambda k: str(getattr(agent, k, "") or "").strip()
+ model, provider, base_url = attr("model"), attr("provider"), attr("base_url")
+ if provider.lower() == "custom":
+ # ``agent.provider`` resolves every named custom entry to the literal "custom", losing the entry
+ # identity (api_key is never persisted): recover ``custom:<name>`` from the endpoint URL.
+ try:
+ from hermes_cli.runtime_provider import canonical_custom_identity
+ provider = canonical_custom_identity(base_url=base_url, model=model or None) or provider
+ except Exception:
+ logger.debug("custom provider identity lookup failed", exc_info=True)
+ reasoning_config = getattr(agent, "reasoning_config", None)
+ live = {
+ "model": model, "provider": provider, "base_url": base_url, "api_mode": attr("api_mode"),
+ # An empty dict is still a real (present) reasoning config.
+ "reasoning_config": reasoning_config if isinstance(reasoning_config, dict) else None,
+ "service_tier": getattr(agent, "service_tier", None),
+ }
+ for key, value in live.items():
+ if value or isinstance(value, dict):
+ config[key] = value
+ else:
+ config.pop(key, None)
+ return config
+
+
+def _persist_live_session_runtime(session: dict | None) -> None:
+ """Persist active session runtime so future resumes restore the same footer."""
+ live = _live_session_agent_db(session)
+ if live is None:
+ return
+ agent, session_key, db = live
+ try:
+ row = db.get_session(session_key) or {}
+ model_config = _runtime_model_config(agent, _parse_model_config(row.get("model_config")))
+ if (tier_override := session.get("create_service_tier_override")) is not None:
+ # agent.service_tier is None for explicit normal; without this the distinction is erased on every persist.
+ model_config["service_tier"] = tier_override or "normal"
+ model = str(getattr(agent, "model", "") or "").strip()
+ if hasattr(db, "update_session_meta"):
+ db.update_session_meta(session_key, json.dumps(model_config), model or None)
+ elif model and hasattr(db, "update_session_model"):
+ db.update_session_model(session_key, model)
+ except Exception:
+ logger.debug("failed to persist live session runtime", exc_info=True)
+
+def _load_approval_mode() -> str:
+ """Effective ``approvals.mode`` via the gate's own ``_get_approval_mode`` (a raw re-read missed the
+ managed overlay and ``${VAR}`` expansion)."""
+ from tools.approval_context import _get_approval_mode
+ mode = _get_approval_mode()
+ return mode if mode in _APPROVAL_MODES else "manual"
+
+
+def _coerce_statusbar(raw) -> str:
+ if raw is False:
+ return "off"
+ return s if isinstance(raw, str) and (s := raw.strip().lower()) in _STATUSBAR_MODES else "top"
+
+
+_MOUSE_TRACKING_ALIASES = {
+ "0": "off", "1": "all", "all": "all", "any": "all", "button": "buttons", "buttons": "buttons",
+ "click": "buttons", "false": "off", "full": "all", "no": "off", "off": "off", "on": "all",
+ "scroll": "wheel", "true": "all", "wheel": "wheel", "yes": "all",
+}
+
+
+def _display_mouse_tracking(display: dict) -> str:
+ """display.mouse_tracking → ``off|wheel|buttons|all`` (bools: True → all, False → off); ``wheel`` (DEC
+ 1000+1006) is the tmux-friendly subset without hover events. Legacy ``tui_mouse`` only when ``mouse_tracking`` is absent."""
+ if not isinstance(display, dict):
+ return "all"
+ raw = display.get("mouse_tracking") if "mouse_tracking" in display else display.get("tui_mouse", True)
+ if isinstance(raw, str):
+ return _MOUSE_TRACKING_ALIASES.get(raw.strip().lower(), "all")
+ return "off" if raw is False or raw == 0 else "all"
+
+
+def _load_reasoning_config(model: str = "") -> dict | None:
+ """Via the shared chokepoint :func:`hermes_constants.resolve_reasoning_config` (per-model override >
+ global ``agent.reasoning_effort``; YAML False = disabled).
+
+ Closes #21256.
+ """
+ from hermes_constants import resolve_reasoning_config
+ return resolve_reasoning_config(_load_cfg(), model)
+
+
+_SERVICE_TIER_ALIASES = {"fast": "priority", "priority": "priority", "on": "priority", "auto": "auto", "cold": "cold"}
+
+
+def _load_service_tier() -> str | None:
+ raw = str((_load_cfg().get("agent") or {}).get("service_tier", "") or "").strip().lower()
+ return _SERVICE_TIER_ALIASES.get(raw)
+
+
+def _load_provider_routing() -> dict:
+ """OpenRouter ``provider_routing`` prefs (gateway/CLI parity — without them OpenRouter picks an effectively random provider)."""
+ with contextlib.suppress(Exception):
+ return _load_cfg().get("provider_routing", {}) or {}
+ return {}
+
+
+def _load_show_reasoning() -> bool:
+ # Fallback True — keep in sync with DEFAULT_CONFIG display.show_reasoning (no DEFAULT_CONFIG merge here).
+ return bool(_display_cfg().get("show_reasoning", True))
+
+
+def _load_memory_notifications() -> str:
+ """``display.memory_notifications`` (``off`` / ``on`` default / ``verbose``; bool normalized) — gates the
+ "💾 Self-improvement review" summary (gateway/CLI parity)."""
+ raw = _display_cfg().get("memory_notifications")
+ if isinstance(raw, bool):
+ return "on" if raw else "off"
+ return str(raw).lower() if raw else "on"
+
+
+_TOOL_PROGRESS_MODES = frozenset({"off", "new", "all", "verbose"})
+
+
+def _load_tool_progress_mode() -> str:
+ env = os.environ.get("HERMES_TUI_TOOL_PROGRESS", "").strip().lower()
+ if env in _TOOL_PROGRESS_MODES:
+ return env
+ raw = _display_cfg().get("tool_progress", "all")
+ if isinstance(raw, bool):
+ return "all" if raw else "off"
+ mode = str(raw or "all").strip().lower()
+ return mode if mode in _TOOL_PROGRESS_MODES else "all"
+
+
+def _gui_surface_toolsets(platform: str) -> set[str]:
+ """Toolsets that exist because of the CLIENT (both off ``_HERMES_CORE_TOOLS``; this is the one gate).
+ ``platform`` is the SESSION's source, never a process env var: the desktop may drive a URL/cloud
+ backend where ``HERMES_DESKTOP`` is unset (AGENTS.md surface rule)."""
+ return {"project", "desktop_ui"} if platform == "desktop" else {"project"}
+
+
+def _tui_notice(text: str) -> None:
+ print(text, file=sys.stderr, flush=True)
+
+
+def _resolve_explicit_toolsets(explicit: list[str], validate_toolset) -> list[str] | None | bool:
+ """Resolve a HERMES_TUI_TOOLSETS pin: list, None for "all", False when nothing was valid."""
+ built_in = [name for name in explicit if validate_toolset(name)]
+ unresolved = [name for name in explicit if name not in built_in]
+ if unresolved:
+ try:
+ from hermes_cli.plugins import discover_plugins
+ discover_plugins()
+ plugin_valid = [name for name in unresolved if validate_toolset(name)]
+ except Exception:
+ plugin_valid = []
+ built_in.extend(plugin_valid)
+ unresolved = [name for name in unresolved if name not in plugin_valid]
+ if any(name in {"all", "*"} for name in built_in):
+ if ignored := [name for name in explicit if name not in {"all", "*"}]:
+ _tui_notice(f"[tui] HERMES_TUI_TOOLSETS=all enables every toolset; ignoring additional entries: {', '.join(ignored)}")
+ return None
+ if not unresolved:
+ return built_in
+ try: # (enabled, disabled) MCP server names from raw config; both empty on any failure
+ from hermes_cli.config import read_raw_config
+ from hermes_cli.tools_config import _parse_enabled_flag
+ raw_cfg = read_raw_config()
+ mcp_servers = raw_cfg.get("mcp_servers") if isinstance(raw_cfg.get("mcp_servers"), dict) else {}
+ mcp_names, mcp_disabled = set(), set()
+ for name, server_cfg in mcp_servers.items():
+ if isinstance(server_cfg, dict):
+ on = _parse_enabled_flag(server_cfg.get("enabled", True), default=True)
+ (mcp_names if on else mcp_disabled).add(str(name))
+ except Exception:
+ mcp_names, mcp_disabled = set(), set()
+ mcp_valid = [name for name in unresolved if name in mcp_names]
+ disabled = [name for name in unresolved if name in mcp_disabled]
+ unknown = [name for name in unresolved if name not in mcp_names and name not in mcp_disabled]
+ if unknown:
+ _tui_notice(f"[tui] ignoring unknown HERMES_TUI_TOOLSETS entries: {', '.join(unknown)}")
+ if disabled:
+ _tui_notice("[tui] ignoring disabled MCP servers in HERMES_TUI_TOOLSETS "
+ f"(set enabled: true in config.yaml to use): {', '.join(disabled)}")
+ return (built_in + mcp_valid) or False
+
+
+def _load_enabled_toolsets(platform: str | None = None) -> list[str] | None:
+ """The agent's toolsets for this session (None = all): an explicit HERMES_TUI_TOOLSETS pin; else the
+ coding posture (coding_context collapses to coding toolset + enabled MCP servers in a code workspace);
+ else the configured CLI toolsets. Client-surface toolsets fold in here — only this surface can answer them."""
+ session_platform = platform or _resolve_session_platform()
+ explicit = [item.strip() for item in os.environ.get("HERMES_TUI_TOOLSETS", "").split(",") if item.strip()]
+ fallback_notice = None
+ if not explicit:
+ with contextlib.suppress(Exception):
+ from agent.coding_context import coding_selection
+ selection = coding_selection(platform=session_platform)
+ if selection is not None:
+ return sorted({*selection, *_gui_surface_toolsets(session_platform)})
+ try:
+ from toolsets import validate_toolset
+ except Exception:
+ validate_toolset = None
+ if explicit and validate_toolset is not None:
+ resolved = _resolve_explicit_toolsets(explicit, validate_toolset)
+ if resolved is not False:
+ return resolved
+ fallback_notice = "[tui] no valid HERMES_TUI_TOOLSETS entries; using configured CLI toolsets"
+ try:
+ from hermes_cli.config import load_config
+ from hermes_cli.tools_config import _get_platform_tools
+ cfg = load_config()
+ # include_default_mcp_servers=True is the runtime variant (the agent must be able to call
+ # default MCP servers); the config-editing variant would silently drop MCP tools from the TUI.
+ # Passing ``False`` here is the config-editing variant — used when we need to persist a toolset list
+ # without baking in implicit MCP defaults. Using the wrong variant at agent creation time makes MCP
+ # tools silently missing from the TUI. See PR #3252 for the original design split.
+ enabled = _get_platform_tools(cfg, "cli", include_default_mcp_servers=True)
+ if fallback_notice is not None:
+ _tui_notice(fallback_notice)
+ return sorted(enabled | _gui_surface_toolsets(session_platform)) if enabled else None
+ except Exception:
+ if fallback_notice is not None:
+ _tui_notice("[tui] no valid HERMES_TUI_TOOLSETS entries and configured CLI toolsets could not be loaded; enabling all toolsets")
+ return None
+
+
+def _session_tool_progress_mode(sid: str) -> str:
+ return str(_sessions.get(sid, {}).get("tool_progress_mode", "all") or "all")
+
+
+def _session_verbose(sid: str) -> bool:
+ return _session_tool_progress_mode(sid) == "verbose"
+
+
+def _tool_progress_enabled(sid: str) -> bool:
+ return _session_tool_progress_mode(sid) != "off"
+
+
+def _tool_lifecycle_required_for_ui(name: str) -> bool:
+ """Interactive UI, not optional chrome: Desktop renders clarify / setup_mcp cards from the tool-call part."""
+ return name in ("clarify", "setup_mcp")
+
+def _resolve_runtime_with_fallback(resolve_kwargs: dict | None = None) -> _RuntimeFallbackResolution:
+ """Resolve the primary runtime or one complete provider/model fallback. Provider-only fallback entries
+ are skipped so the unavailable primary model can never leak into a different runtime."""
+ from hermes_cli.auth import AuthError
+ from hermes_cli.runtime_provider import resolve_runtime_provider
+ try:
+ return _RuntimeFallbackResolution(resolve_runtime_provider(**(resolve_kwargs or {})), None, False)
+ except AuthError as primary_exc:
+ for entry in _load_fallback_model() or []:
+ fb_provider = str(entry.get("provider") or "").strip() if isinstance(entry, dict) else ""
+ fb_model = str(entry.get("model") or "").strip() if isinstance(entry, dict) else ""
+ if not fb_provider or not fb_model:
+ continue
+ try:
+ from hermes_cli.fallback_config import resolve_entry_api_key
+ fb_kwargs: dict = {"requested": fb_provider, "target_model": fb_model,
+ **({"explicit_base_url": entry["base_url"]} if entry.get("base_url") else {})}
+ if fb_api_key := resolve_entry_api_key(entry):
+ fb_kwargs["explicit_api_key"] = fb_api_key
+ runtime = resolve_runtime_provider(**fb_kwargs)
+ logging.getLogger(__name__).warning(
+ "Primary auth failed (%s), falling back to %s model %s", primary_exc, fb_provider, fb_model)
+ return _RuntimeFallbackResolution(runtime, fb_model, True)
+ except Exception:
+ continue
+ raise
+
+
+def _resolve_agent_model_runtime(model_override, provider_override) -> tuple[str, dict]:
+ """(model, runtime) for a new agent; a per-session override (/model switch or a resumed row's persisted
+ runtime) wins over global config/env. Older rows stored the resolved provider "custom" (no named entry
+ matches) — recover the identity from the persisted base_url or the rebuild fails "No LLM provider
+ configured". Persisted base_url/api_key/api_mode are honored only for the original runtime, never a fallback."""
+ if isinstance(model_override, dict) and model_override.get("model"):
+ model = str(model_override.get("model") or "")
+ requested_provider = model_override.get("provider") or provider_override or None
+ override_base_url = model_override.get("base_url")
+ resolve_kwargs = {}
+ if str(requested_provider or "").strip().lower() == "custom":
+ from hermes_cli.runtime_provider import canonical_custom_identity
+ if recovered := canonical_custom_identity(base_url=override_base_url or None, model=model or None):
+ requested_provider = recovered
+ if override_base_url:
+ # Failing identity recovery, still hand base_url to the direct-alias branch so pool/env credentials resolve.
+ resolve_kwargs["explicit_base_url"] = override_base_url
+ resolve_kwargs.update(requested=requested_provider, target_model=model or None)
+ overrides = {k: model_override.get(k) for k in ("base_url", "api_key", "api_mode")}
+ else:
+ model, requested_provider = _resolve_startup_runtime()
+ if isinstance(model_override, str) and model_override:
+ model = model_override
+ if provider_override:
+ requested_provider = provider_override
+ resolve_kwargs = {"requested": requested_provider, "target_model": model or None}
+ overrides = {}
+ resolution = _resolve_runtime_with_fallback(resolve_kwargs)
+ if resolution.used_fallback:
+ if not resolution.selected_model:
+ raise RuntimeError("Auth fallback resolved without a model")
+ return resolution.selected_model, resolution.runtime
+ resolution.runtime.update({k: v for k, v in overrides.items() if v})
+ return model, resolution.runtime
+
+
+def _startup_system_prompt(cfg: dict, task_id: str) -> str:
+ """Config ephemeral system prompt + HERMES_TUI_SKILLS preload block. Hard-fails only when EVERY requested
+ skill is missing (cli.py parity): a typo'd name must not auto-block the Kanban task."""
+ from hermes_cli.config import resolve_ephemeral_system_prompt_from_config
+ system_prompt = resolve_ephemeral_system_prompt_from_config(cfg)
+ startup_skills = _parse_tui_skills_env()
+ if not startup_skills:
+ return system_prompt
+ from agent.skill_commands import build_preloaded_skills_prompt
+ skills_prompt, loaded_skills, missing_skills = build_preloaded_skills_prompt(startup_skills, task_id=task_id)
+ if missing_skills:
+ missing_display = ", ".join(missing_skills)
+ if not loaded_skills:
+ raise ValueError(f"Unknown skill(s): {missing_display}")
+ logger.warning("Unknown skill(s) requested, skipping: %s. Continuing with: %s. "
+ "List available skills with `hermes skills list`.", missing_display, ", ".join(loaded_skills))
+ if skills_prompt:
+ system_prompt = "\n\n".join(part for part in (system_prompt, skills_prompt) if part).strip()
+ return system_prompt
+
+
+def _make_agent(
+ sid: str, key: str, session_id: str | None = None, session_db=None,
+ model_override: dict | str | None = None, provider_override: str | None = None,
+ reasoning_config_override: dict | None = None, service_tier_override: str | None = None,
- platform_override: str | None = None, context_cwd_is_launch_artifact: bool | None = None):
++ platform_override: str | None = None, context_cwd_is_launch_artifact: bool | None = None,
++ auth_user_id: str | None = None):
+ # AC-4 test seam: dead unless armed by the isolated certify harness.
+ from tui_gateway.synthetic_turn import maybe_build_synthetic_agent
+ synthetic = maybe_build_synthetic_agent(session_id or key, model_override)
+ if synthetic is not None:
+ return synthetic
+ from run_agent import AIAgent
+ # MCP discovery runs in a daemon thread (a dead server can't freeze the shell); the agent snapshots its tool
+ # list once, so briefly wait for in-flight discovery. Dashboard /api/ws uses mcp_startup; TUI stdio uses entry.
+ for _mod in ("hermes_cli.mcp_startup", "tui_gateway.entry"):
+ with contextlib.suppress(Exception):
+ importlib.import_module(_mod).wait_for_mcp_discovery()
+ cfg = _load_cfg()
+ # Load hooks alongside the same profile config used to construct this agent.
+ from agent.shell_hooks import register_from_config
+ register_from_config(cfg)
+ system_prompt = _startup_system_prompt(cfg, session_id or key)
+ model, runtime = _resolve_agent_model_runtime(model_override, provider_override)
+ _pr = _load_provider_routing()
+ platform = _resolve_agent_platform(platform_override)
+ ignore_rules = is_truthy_value(os.environ.get("HERMES_IGNORE_RULES"))
++ with _sessions_lock:
++ session = _sessions.get(sid)
+ agent = AIAgent(
+ model=model, max_iterations=_cfg_max_turns(cfg, 500), provider=runtime.get("provider"),
+ base_url=runtime.get("base_url"), api_key=runtime.get("api_key"), api_mode=runtime.get("api_mode"),
+ acp_command=runtime.get("command"), acp_args=runtime.get("args"),
+ credential_pool=runtime.get("credential_pool"), quiet_mode=True,
+ verbose_logging=False, # DEBUG agent logging; independent of tool_progress_mode
+ reasoning_config=(
+ reasoning_config_override if reasoning_config_override is not None else _load_reasoning_config(str(model or ""))),
+ service_tier=service_tier_override if service_tier_override is not None else _load_service_tier(),
+ enabled_toolsets=_load_enabled_toolsets(platform),
+ # OpenRouter provider_routing prefs (gateway + CLI parity).
+ providers_allowed=_pr.get("only"), providers_ignored=_pr.get("ignore"), providers_order=_pr.get("order"),
+ provider_sort=_pr.get("sort"), provider_require_parameters=_pr.get("require_parameters", False),
+ provider_data_collection=_pr.get("data_collection"), platform=platform, session_id=session_id or key,
++ # The dashboard login identity reaches memory providers as the runtime user, like a gateway user id.
++ # Builds that run before the record exists (branch, eager resume, compute host) pass it explicitly.
++ user_id=auth_user_id if auth_user_id is not None else _session_auth_user_id(session),
+ session_db=session_db if session_db is not None else _get_db(), ephemeral_system_prompt=system_prompt or None,
+ checkpoints_enabled=is_truthy_value(os.environ.get("HERMES_TUI_CHECKPOINTS")),
+ pass_session_id=is_truthy_value(os.environ.get("HERMES_TUI_PASS_SESSION_ID")),
+ skip_context_files=ignore_rules, skip_memory=ignore_rules, fallback_model=_load_fallback_model(),
+ **_agent_cbs(sid))
+ if context_cwd_is_launch_artifact is None:
- with _sessions_lock:
- context_cwd_is_launch_artifact = _context_cwd_is_launch_artifact(_sessions.get(sid))
++ context_cwd_is_launch_artifact = _context_cwd_is_launch_artifact(session)
+ agent._context_cwd_is_launch_artifact = bool(context_cwd_is_launch_artifact)
+ return agent
+
+
+def register(server):
+ bind_module(globals(), server)
diff --cc tui_gateway/methods_bot_relay.py
index dfb1810bfa6,4925e5435f1..7fd38e7c905
--- a/tui_gateway/methods_bot_relay.py
+++ b/tui_gateway/methods_bot_relay.py
@@@ -19,14 -20,18 +19,16 @@@ method = _registry.metho
def _relay_root() -> Path:
- """Install root shared by every profile (relay state is install-wide)."""
- home = Path(os.getenv("HERMES_HOME") or os.path.expanduser("~/.hermes"))
- return home.parent.parent if home.parent.name == "profiles" else home
+ """Install root shared by every profile (relay state is install-wide). Same formula as the
+ writers (``tools/bot_relay``, ``tools/bot_mode_dm``): both ends of the mailbox must agree for
+ every HERMES_HOME, including non-``profiles/`` subdirs of ``~/.hermes``."""
+ from tools.bot_mode_probe import _default_home, _hermes_root
+ return _hermes_root(Path(_default_home()))
-def _run_delivery(profile: str, tmp: str, env: dict | None = None) -> subprocess.CompletedProcess:
- from tools.bot_relay import local_delivery_command
- return subprocess.run(
- local_delivery_command(profile, tmp), capture_output=True, text=True, encoding="utf-8",
- errors="replace", timeout=TURN_ATTEMPT_TIMEOUT_SECONDS, env=env)
+# Historical Desktop deadline mirrors; no subprocess retry is performed here.
+# Remove with the renderer relay deadline/receipt migration.
+TURN_MAX_ATTEMPTS = 2 # first attempt + the policy-gated re-run
@method("bot_relay.roster.sync")
diff --cc tui_gateway/session_registry.py
index 9dddbca04bc,00000000000..42923ce1a35
mode 100644,000000..100644
--- a/tui_gateway/session_registry.py
+++ b/tui_gateway/session_registry.py
@@@ -1,705 -1,0 +1,706 @@@
+"""TUI session_registry seam; functions bind to the server namespace at registration."""
+
+from __future__ import annotations
+
+from .method_ctx import bind_module
+
+def _wait_agent(session: dict, rid: str, timeout: float = 30.0) -> dict | None:
+ ready = session.get("agent_ready")
+ if ready is not None and not ready.wait(timeout=timeout):
+ return _err(rid, 5032, "agent initialization timed out")
+ return _err(rid, 5032, err) if (err := session.get("agent_error")) else None
+
+
+# The deferred prompt path waits in short slices so a cancel is honored promptly and a slow
+# build is reported to the client exactly once.
+_AGENT_BUILD_WAIT_SLICE = 5.0
+_AGENT_BUILD_SLOW_NOTICE_AFTER = 30.0
+_AGENT_BUILD_SLOW_NOTICE_KEY = "agent-build-slow"
+
+
+def _agent_build_wait_cap() -> float:
+ """Seconds a submitted prompt waits for the deferred build before failing; ``agent.build_wait_timeout``
+ overrides the 600s default (raise it for many slow MCP servers / high-latency provider metadata)."""
+ with contextlib.suppress(Exception):
+ raw = (_load_cfg().get("agent") or {}).get("build_wait_timeout")
+ if raw is not None and float(raw) > 0:
+ return float(raw)
+ return 600.0
+
+
+def _wait_agent_for_prompt(session: dict, rid: str, sid: str) -> dict | None:
+ """Patient ``_wait_agent`` for deferred prompt.submit: the client already got ``streaming`` and the
+ first message IS the turn, while a cold build routinely outlives the flat 30s ceiling (timing out
+ silently discarded it). Waits in short slices (cancel honored promptly), notifies once (keyed) past
+ ``_AGENT_BUILD_SLOW_NOTICE_AFTER``, fails only on a dead build thread or the bounded cap.
+ Returns None on success OR cancel mid-wait (the caller's cancel branch owns that messaging).
+
+ The flat 30s ``_wait_agent`` ceiling was a message-eating cliff (#63078): ``prompt.submit`` has already
+ returned ``{"status": "streaming"}``, the user's first message IS the turn in flight, and the deferred
+ agent build (MCP discovery with per-server retry backoff, synchronous model-metadata HTTP, skills
+ scanning) routinely outlives 30 seconds on cold starts. On timeout the old path emitted an error EVENT
+ and returned without ever calling ``_run_prompt_submit`` — the first message was permanently discarded
+ while the build finished successfully in the background, leaving the blank first session.
+ """
+ ready = session.get("agent_ready")
+ if ready is None:
+ return None
+ start, cap, notified_slow = time.monotonic(), _agent_build_wait_cap(), False
+ while not ready.wait(timeout=_AGENT_BUILD_WAIT_SLICE):
+ with session["history_lock"]:
+ cancelled = session.get("_turn_cancel_requested") or not session.get("running")
+ if cancelled:
+ return None
+ waited = time.monotonic() - start
+ if waited >= cap:
+ return _err(rid, 5032, f"agent initialization timed out after {int(waited)}s — "
+ "your message was not sent; retry once the session is ready")
+ build_thread = session.get("_agent_build_thread")
+ if build_thread is not None and not build_thread.is_alive() and not ready.is_set():
+ # _build's finally guarantees ready.set(); dead thread + unset ready = died hard.
+ return _err(rid, 5032, session.get("agent_error") or "agent initialization failed before completing")
+ if not notified_slow and waited >= _AGENT_BUILD_SLOW_NOTICE_AFTER:
+ notified_slow = True # one keyed, replace-in-place notice (toast / status bar)
+ _emit("notification.show", sid, {
+ "text": "Still starting the agent (tool discovery / model setup) — your message will be sent as soon as it's ready.",
+ "level": "info", "kind": "agent", "ttl_ms": None,
+ "key": _AGENT_BUILD_SLOW_NOTICE_KEY, "id": _AGENT_BUILD_SLOW_NOTICE_KEY})
+ if notified_slow:
+ _emit("notification.clear", sid, {"key": _AGENT_BUILD_SLOW_NOTICE_KEY})
+ return _err(rid, 5032, err) if (err := session.get("agent_error")) else None
+
+
+def _bind_build_profile_scopes(profile_home: str) -> "_TurnScopes":
+ """Bind a session profile's HERMES_HOME / secret / terminal scopes for an agent build. Fail-open per
+ scope (the build must not die on a scope helper); the terminal installer itself fails closed (malformed
+ policy → refusal scope) so _make_agent's terminal probing / cwd hints resolve the routed profile."""
+ scopes = _TurnScopes()
+ scopes.home = set_hermes_home_override(profile_home)
+ with contextlib.suppress(Exception):
+ scopes.secret = set_secret_scope(build_profile_secret_scope(Path(profile_home)))
+ scopes.terminal = None
+ with contextlib.suppress(Exception):
+ from tools.terminal_scope import install_profile_terminal_scope
+ scopes.terminal = install_profile_terminal_scope(Path(profile_home))
+ return scopes
+
+
+def _release_build_profile_scopes(scopes: "_TurnScopes") -> None:
+ if scopes.home is not None:
+ reset_hermes_home_override(scopes.home)
+ if scopes.secret is not None:
+ with contextlib.suppress(Exception):
+ reset_secret_scope(scopes.secret)
+ if scopes.terminal is not None:
+ with contextlib.suppress(Exception):
+ from tools.terminal_scope import reset_terminal_scope
+ reset_terminal_scope(scopes.terminal)
+
+
+def _deferred_build_agent_kwargs(current: dict, session_db) -> dict:
+ """_make_agent kwargs for a deferred (first-prompt) build. A lazy-resumed (watch) session carries the
+ stored conversation id so the upgrade continues it; a cold deferred resume restores the full persisted
+ runtime identity (like the eager resume's overrides splat) so the build can't drop the provider. No
+ stored runtime, or an unroutable provider → this session's picked model/effort/tier, else the default."""
+ kw = {"session_db": session_db, "context_cwd_is_launch_artifact": _context_cwd_is_launch_artifact(current),
+ "platform_override": _session_source(current)}
+ if resume_sid := current.get("resume_session_id"):
+ kw["session_id"] = resume_sid
+ resume_overrides = current.get("resume_runtime_overrides")
+ if isinstance(resume_overrides, dict) and resume_overrides and _overrides_have_routable_provider(resume_overrides):
+ kw.update(resume_overrides)
+ else:
+ if override := current.get("model_override"):
+ kw["model_override"] = override
+ kw.update({k: v for k, v in (("reasoning_config_override", current.get("create_reasoning_override")),
+ ("service_tier_override", current.get("create_service_tier_override")))
+ if v is not None})
+ return kw
+
+
+def _wire_session_agent(sid: str, key: str, agent) -> bool:
+ """Post-build wiring; returns whether the approval notify got registered. Approval prompts route to the
+ client; the self-improvement "💾 …" summary is emitted as review.summary (no print surface), honoring
+ display.memory_notifications."""
+ notify_registered = False
+ with contextlib.suppress(Exception):
+ from tools.approval import load_permanent_allowlist, register_gateway_notify
+ register_gateway_notify(key, lambda data: _emit_approval_request(sid, data))
+ notify_registered = True
+ load_permanent_allowlist()
+ _wire_callbacks(sid)
+ with contextlib.suppress(Exception): # bare agents without the attribute must not break startup
+ agent.background_review_callback = lambda message, _sid=sid: _emit("review.summary", _sid, {"text": str(message)})
+ agent.memory_notifications = _load_memory_notifications()
+ return notify_registered
+
+
+def _start_session_services(sid: str, key: str, current: dict) -> None:
+ """Start the notification poller and fire the session-reset boundary hook."""
+ with _sessions_lock:
+ if (rec := _sessions.get(sid)) is not None:
+ rec["_notif_stop"] = _start_notification_poller(sid, rec)
+ _notify_session_boundary("on_session_reset", key, _session_source(current))
+
+
+def _await_resume_history(sid: str, current: dict) -> bool:
+ """Block on a cold resume's transcript hydration; False when this record was replaced meanwhile."""
+ history_ready = current.get("resume_history_ready")
+ if history_ready is None:
+ return True
+ if not history_ready.wait(timeout=300.0):
+ raise TimeoutError("session history hydration timed out")
+ if history_error := current.get("resume_history_error"):
+ raise RuntimeError(str(history_error))
+ with _sessions_lock:
+ return _sessions.get(sid) is current
+
+
+def _attach_built_agent(current: dict, agent) -> None:
+ """Attach a freshly built agent to its live record (session DB row deferred to first run_conversation())."""
+ # Bot Mode gate hint: the DB title lands post-first-turn but the system prompt builds at turn START.
+ if _title_hint := str(current.get("pending_title") or "").strip():
+ agent._session_title_hint = _title_hint
+ current["agent"] = agent
+ _session_todo_state(current)
+ # Baseline for the per-turn config sync (profile home override still active).
+ current["config_model_seen"] = _config_model_target()
+
+
+def _announce_built_agent(sid: str, key: str, current: dict, agent) -> None:
+ """Post-wiring tail of a build: credits seed, session services, session.info, late MCP catch-up."""
+ # Credits notices at session OPEN (notice_callback already wired) so depletion warnings show at "ready".
+ with contextlib.suppress(Exception):
+ from agent.credits_tracker import seed_credits_at_session_start
+ seed_credits_at_session_start(agent)
+ _start_session_services(sid, key, current)
+ info = _session_info(agent, current)
+ if cfg_warn := _probe_config_health(_load_cfg()):
+ info["config_warning"] = cfg_warn
+ logger.warning(cfg_warn)
+ _emit("session.info", sid, info)
+ _schedule_mcp_late_refresh(sid, agent) # servers slower than the bounded discovery wait land here
+
+
+def _finish_agent_build(sid: str, key: str, current: dict, *, notify_registered: bool, scopes, session_db) -> None:
+ """Release build scopes and settle ownership of the late notify registration + dedicated db handle."""
+ if scopes is not None:
+ _release_build_profile_scopes(scopes)
+ # Reaped mid-build: _attach_worker closed the worker; only a late notify registration can still
+ # leak (session.close unregistered before _build registered).
+ with _sessions_lock:
+ replaced = _sessions.get(sid) is not current
+ if replaced and notify_registered:
+ with contextlib.suppress(Exception):
+ from tools.approval import unregister_gateway_notify
+ unregister_gateway_notify(key)
+ # Dedicated profile handle: hand it to the agent that will be torn down, else close it (build
+ # failed, or `replaced`: this agent is discarded and _teardown_session never reaches it).
+ if session_db is not None and not _transfer_db_to_agent(None if replaced else current.get("agent"), session_db):
+ with contextlib.suppress(Exception):
+ session_db.close()
+
+
+def _start_agent_build(sid: str, session: dict) -> None:
+ """Start building the real AIAgent for a TUI session, once. Deferred until the first prompt (or any
+ command needing the agent) so the composer isn't blocked on tool discovery / model metadata;
+ the ready/error event contract is unchanged."""
+ ready = session.get("agent_ready")
+ if ready is None:
+ return
+ # A lazy watch session spectating an in-flight child must stay lazy so the subagent live-mirror keeps
+ # flowing (it bails once agent is set); incidental RPCs via _sess() would upgrade it mid-stream.
+ if session.get("lazy") and _child_run_active(str(session.get("session_key") or "")):
+ return
+ with session.setdefault("agent_build_lock", threading.Lock()):
+ if ready.is_set() or session.get("agent_build_started"):
+ return
+ session["agent_build_started"] = True
+ session.pop("lazy", None) # now genuinely mid-construction: restore the "still starting" eviction exemption
+ key = session["session_key"]
+
+ def _build() -> None:
+ with _sessions_lock:
+ current = _sessions.get(sid)
+ if current is None:
+ ready.set()
+ return
+ notify_registered, scopes, session_db = False, None, None
+ profile_home = current.get("profile_home")
+ try:
+ if not _await_resume_history(sid, current):
+ return
+ tokens = _set_session_context(key)
+ # Global-remote: bind the session profile's HERMES_HOME and hand the agent that profile's db —
+ # DEDICATED and ours until _transfer_db_to_agent in the finally; FAIL CLOSED rather than
+ # binding the launch DB and bleeding rows into the wrong state.db.
+ if profile_home:
+ scopes = _bind_build_profile_scopes(profile_home)
+ session_db = _open_profile_session_db(profile_home)
+ try:
+ from tui_gateway.entry import ensure_mcp_discovery_started
+ ensure_mcp_discovery_started()
+ except Exception:
+ logger.warning("MCP discovery startup failed", exc_info=True)
+ try:
+ agent = _make_agent(sid, key, **_deferred_build_agent_kwargs(current, session_db))
+ finally:
+ _clear_session_context(tokens)
+ _attach_built_agent(current, agent)
+ # No eager slash-worker pre-warm (slash.exec spawns on demand): each worker forks the full stdio
+ # MCP fleet, and live-transport sessions are never reaped, so fleets would accumulate.
+ notify_registered = _wire_session_agent(sid, key, agent)
+ _announce_built_agent(sid, key, current, agent)
+ except Exception as e:
+ current["agent_error"] = str(e)
+ _emit("error", sid, {"message": f"agent init failed: {e}"})
+ finally:
+ _finish_agent_build(
+ sid, key, current, notify_registered=notify_registered, scopes=scopes, session_db=session_db)
+ ready.set()
+
+ build_thread = threading.Thread(target=_build, daemon=True)
+ # _wait_agent_for_prompt handle: dead thread + unset agent_ready = died hard; waiters must not sit out the cap.
+ session["_agent_build_thread"] = build_thread
+ build_thread.start()
+
+
+def _sess_nowait(params, rid):
+ sid = params.get("session_id") or ""
+ s = _sessions.get(sid)
+ if s:
+ return (s, None)
+ # Stale runtime id (reaped/evicted/TTL): the client should session.resume the STORED id. Logged so
+ # "message vanished" reads as "arrived and was rejected".
+ logger.warning("session-scoped RPC rejected: method=%s session_id=%r not in memory "
+ # A session-scoped RPC hit a runtime id the gateway no longer holds (detached on WS
+ # disconnect and orphan-reaped, LRU-evicted, or torn down after an idle TTL). The client
+ # is expected to recover via session.resume on the STORED session id, but a plain
+ # stale-id send leaves no trace anywhere when the resume never fires — every RPC in this
+ # class returned a silent 4001. Log it so a "message vanished" report is diagnosable as
+ # "request arrived and was rejected" instead of "request never arrived" (see #90428).
+ "(detached/reaped runtime; client should resume the stored session), rid=%r",
+ _current_rpc_method.get() or "?", sid, rid)
+ return (None, _err(rid, 4001, "session not found"))
+
+
+def _sess(params, rid):
+ s, err = _sess_building(params, rid)
+ return (None, err) if err else (s, _wait_agent(s, rid))
+
+
+def _sess_building(params, rid):
+ """Resolve a session and warm its agent build WITHOUT waiting — for the attach RPCs (image/file/pdf,
+ clipboard.paste, image.detach), which only touch creation-time fields and run inline on the socket
+ reader thread, where waiting on a cold build stalled every RPC behind it ("text is instant, images hang")."""
+ s, err = _sess_nowait(params, rid)
+ if not err:
+ _start_agent_build(params.get("session_id") or "", s)
+ return (None, err) if err else (s, None)
+
+def _init_session(
+ sid: str, key: str, agent, history: list, cols: int = 80, cwd: str | None = None,
+ session_db=None, source: str | None = None, profile_home: str | None = None,
+ explicit_cwd: bool = False):
+ now = time.time()
+ with _sessions_lock:
+ _sessions[sid] = {
+ "agent": agent, "session_key": key, "history": history, "history_lock": threading.Lock(),
+ "history_version": 0, "inflight_turn": None, "created_at": now, "last_active": now,
+ "running": False, "attached_images": [], "image_counter": 0, "cwd": cwd or _completion_cwd(),
+ "explicit_cwd": bool(explicit_cwd), "cols": cols, "slash_worker": None,
+ "show_reasoning": _load_show_reasoning(), "source": _resolve_session_source(source),
+ "tool_progress_mode": _load_tool_progress_mode(), "edit_snapshots": {}, "tool_started_at": {},
+ # Profile-scoped HERMES_HOME (None = launch); SessionBranch copies the parent's (same state.db).
+ "profile_home": profile_home,
+ # In-session /model switch, honored on rebuild (/new, resume) — never leaks to siblings via env vars.
+ "model_override": None,
+ # Async events go to the transport that created the session (stdio for Ink, WS for the dashboard).
+ "transport": current_transport() or _stdio_transport,
++ "auth_user_id": _transport_auth_user_id(current_transport()),
+ }
+ _session_todo_state(_sessions[sid])
+ _hydrate_session_cwd(sid, key, session_db, profile_home)
+ _register_session_cwd(_sessions[sid])
+ _wire_session_agent(sid, key, agent) # no eager slash-worker pre-warm (see _start_agent_build)
+ _start_session_services(sid, key, _sessions.get(sid, {}))
+ _emit("session.info", sid, _session_info(agent, _sessions.get(sid, {})))
+ _schedule_mcp_late_refresh(sid, agent)
+
+
+def _new_session_key() -> str:
- return f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}"
++ return new_session_id()
+
+
+def _with_checkpoints(session, fn):
+ return fn(session["agent"]._checkpoint_mgr, _session_cwd(session))
+
+
+def _resolve_checkpoint_hash(mgr, cwd: str, ref: str) -> str:
+ try:
+ checkpoints = mgr.list_checkpoints(cwd)
+ idx = int(ref) - 1
+ except ValueError:
+ return ref
+ if 0 <= idx < len(checkpoints):
+ return checkpoints[idx].get("hash", ref)
+ raise ValueError(f"Invalid checkpoint number. Use 1-{len(checkpoints)}.")
+
+
+# ── Methods: session ─────────────────────────────────────────────────
+
+
+def _lazy_resume_info(cwd: str, *, model: str = "", provider: str = "", profile: str | None = None) -> dict:
+ """session.info for a not-yet-built session (session.create's shape); tools/skills land with the deferred build."""
+ return {
+ "cwd": cwd, "branch": git_probe.branch(cwd), "project": _project_info_for_cwd(cwd),
+ "model": model or _resolve_model(), "tools": {}, "skills": {}, "lazy": True,
+ "desktop_contract": DESKTOP_BACKEND_CONTRACT, "profile_name": _response_profile_name(profile),
+ **({"provider": provider} if provider else {}),
+ }
+
+
+def _deferred_session_record(
+ session_key: str, *, cols: int, cwd: str, history: list, lease, source: str = "tui",
+ close_on_disconnect: bool = False, display_history_prefix: list | None = None,
+ profile_home: Path | None = None, lazy: bool = False, model_override=None,
+ resume_runtime_overrides: dict | None = None, todo_state: dict | None = None,
+ explicit_cwd: bool = False) -> dict:
+ """A live-session record whose AIAgent is built later (lazy watch / cold resume) — _init_session's shape minus the agent."""
+ now = time.time()
+ return {
+ "agent": None, "agent_error": None, "agent_ready": threading.Event(), "attached_images": [],
+ "close_on_disconnect": close_on_disconnect, "active_session_lease": lease, "cols": cols,
+ "created_at": now, "cwd": cwd, "display_history_prefix": display_history_prefix or [],
+ "edit_snapshots": {}, "explicit_cwd": bool(explicit_cwd), "history": history,
+ "history_lock": threading.Lock(), "history_version": 0, "image_counter": 0,
+ "inflight_turn": None, "last_active": now, "lazy": lazy, "model_override": model_override,
+ "pending_title": None,
+ "profile_home": str(profile_home) if profile_home is not None else None,
+ "resume_runtime_overrides": resume_runtime_overrides, "resume_session_id": session_key,
+ "running": False, "session_key": session_key, "show_reasoning": _load_show_reasoning(),
+ "slash_worker": None, "source": source, "tool_progress_mode": _load_tool_progress_mode(),
+ "tool_started_at": {}, "todo_state": todo_state,
+ "transport": current_transport() or _stdio_transport,
++ "auth_user_id": _transport_auth_user_id(current_transport()),
+ }
+
+
+_ANY_PROFILE = object() # default: match a live session regardless of profile
+
+
+def _live_profile_matches(session: dict, profile_home) -> bool:
+ """True when ``session`` belongs to ``profile_home`` (None = launch profile; a record with no
+ ``profile_home`` is the launch profile's). ``_ANY_PROFILE`` disables the check."""
+ if profile_home is _ANY_PROFILE:
+ return True
+ return (session.get("profile_home") or None) == (str(profile_home) if profile_home else None)
+
+
+def _claim_or_reuse_live(sid: str, session_key: str, record: dict, lease) -> tuple[str, dict] | None:
+ """Register ``record`` as the live session for ``session_key`` under the resume lock, or — if a
+ concurrent resume already won — release ``lease`` and return the winner for the caller to reuse."""
+ # A live runtime of the same stored id under ANOTHER profile is not a winner to reuse.
+ # See #100029.
+ profile_home = record.get("profile_home")
+ with _session_resume_lock:
+ live = _find_live_session_by_key(session_key, profile_home)
+ if live is not None:
+ if lease is not None:
+ lease.release()
+ # The reap is cancelled by the guarded reuse (_reattach_refusal), not here: a rejected
+ # reattach must leave an in-flight orphan interrupt polling.
+ return live
+ with _sessions_lock:
+ _sessions[sid] = record
+ _register_session_cwd(_sessions[sid])
+ # A PRIOR runtime for this stored id may still be sentinel-parked with a reap Timer armed; cancel +
+ # finalize it quietly so the reap doesn't broadcast session.reclaimed (storm).
+ _cancel_ws_orphan_reap(sid)
+ stale = _claim_parked_runtimes(session_key, keep_sid=sid, profile_home=profile_home)
+ _finalize_superseded_runtimes(stale) # slow finalization stays OUTSIDE _session_resume_lock
+ return None
+
+
+def _claim_parked_runtimes(session_key: str, *, keep_sid: str, profile_home=_ANY_PROFILE) -> list[tuple[str, dict]]:
+ """Claim sentinel-parked stale runtimes of ``session_key`` for supersession: cancel their orphan-reap
+ Timer and pop them here (under the caller's _session_resume_lock); the caller finalizes after release."""
+ stale: list[tuple[str, dict]] = []
+ with _sessions_lock:
+ candidates = [
+ (old_sid, old) for old_sid, old in list(_sessions.items())
+ if old_sid != keep_sid and not old.get("_finalized")
+ and _session_lookup_key(old, fallback=old_sid) == session_key
+ and _live_profile_matches(old, profile_home) and old.get("transport") is _detached_ws_transport]
+ for old_sid, _old in candidates:
+ _cancel_ws_orphan_reap(old_sid)
+ if (popped := _pop_session_by_id(old_sid)) is not None:
+ stale.append((old_sid, popped))
+ return stale
+
+
+def _finalize_superseded_runtimes(stale: list[tuple[str, dict]]) -> None:
+ """end_reason ``superseded_by_resume`` is deliberately NOT in _RECLAIM_END_REASONS (no ``session.reclaimed``
+ broadcast → no reap->broadcast->resume loop) but IN _RECOVERABLE_END_REASONS (Bot Chat resurrection applies)."""
+ for old_sid, popped in stale:
+ try:
+ _teardown_popped_session(popped, end_reason="superseded_by_resume")
+ except Exception:
+ logger.exception("superseded runtime teardown failed sid=%s", old_sid)
+
+
+def _schedule_agent_build(sid: str, delay: float = 0.05) -> None:
+ """Pre-warm a deferred session's agent off the response path (session.create + cold resume; _sess() also builds on demand)."""
+
+ def _run():
+ if (session := _sessions.get(sid)) is not None:
+ _start_agent_build(sid, session)
+ timer = threading.Timer(delay, _run)
+ timer.daemon = True
+ timer.start()
+
+
+def _load_resume_transcript(db, stored_id: str) -> tuple[list, list, list]:
+ """(raw_history, display_history, ancestor_prefix) for a cold resume. The full lineage is materialized
+ only while it fits sessions.max_resume_messages (the transcript is REST-paginated), else the tip alone."""
+ from hermes_state import SessionResumeTooLargeError
+ prefix_fits = True
+ guard = getattr(db, "assert_resume_safe", None)
+ if callable(guard):
+ try:
+ guard(stored_id)
+ except SessionResumeTooLargeError as exc:
+ prefix_fits = False
+ logger.info("resume %s: compression lineage exceeds the resume limit (%s); hydrating the tip segment only",
+ stored_id, exc)
+ except Exception:
+ logger.debug("resume lineage guard failed; loading full lineage", exc_info=True)
+ if prefix_fits:
+ raw_history, display_history = db.get_resume_conversations(stored_id)
+ return raw_history, display_history, db.get_ancestor_display_prefix(stored_id)
+ raw_history = db.get_messages_as_conversation(stored_id, repair_alternation=True, include_row_ids=True)
+ return raw_history, raw_history, []
+
+
+def _schedule_resume_hydration(sid: str, stored_id: str, db, *, close_db: bool = False) -> None:
+ """Load a cold resume's transcript off the JSON-RPC response path."""
+
+ def _run() -> None:
+ session = _sessions.get(sid)
+ try:
+ if session is None:
+ return
+ _emit("session.resume_progress", sid, {"phase": "history", "status": "loading"})
+ db.reopen_session(stored_id)
+ raw_history, display_history, prefix = _load_resume_transcript(db, stored_id)
- # Display keeps the full transcript; the model-fed history drops a dangling/interrupted
- # tool-call tail so a session killed mid-loop does not replay the unanswered call forever
- # (#29086).
- history = sanitize_replay_history(raw_history)
++ # Display keeps the full transcript; the model-fed history uses the
++ # same canonicalization as gateway resume and the send path.
++ history = canonicalize_replay_history(raw_history)
+ if _sessions.get(sid) is not session:
+ return
+ with session["history_lock"]:
+ session.update(history=history, display_history_prefix=prefix, resume_hydrating=False,
+ resume_message_count=len(display_history))
+ # Deferred resumes answered before the transcript existed; cache the derived todo snapshot now.
+ todo_state = _todo_state_from_history(history)
+ if todo_state is not None and session.get("todo_state") is None:
+ session["todo_state"] = todo_state
+ session["resume_history_ready"].set()
+ _emit("session.resume_progress", sid,
+ {"message_count": len(display_history), "phase": "history", "status": "complete"})
+ _maybe_schedule_auto_continue(sid, session, stored_id)
+ _start_agent_build(sid, session)
+ except Exception as exc:
+ if _sessions.get(sid) is not session:
+ return
+ message = f"resume failed: {exc}"
+ session.update(resume_hydrating=False, resume_history_error=message, agent_error=message)
+ session["resume_history_ready"].set()
+ session["agent_ready"].set()
+ _emit("session.resume_progress", sid, {"message": message, "phase": "history", "status": "failed"})
+ _emit("error", sid, {"message": message})
+ with _sessions_lock:
+ discarded = _sessions.pop(sid, None) if _sessions.get(sid) is session else None
+ if (lease := (discarded or {}).get("active_session_lease")) is not None:
+ lease.release()
+ finally:
+ if close_db and hasattr(db, "close"):
+ try:
+ db.close()
+ except Exception:
+ logger.debug("failed to close resume db for %s", sid, exc_info=True)
+ threading.Thread(target=_run, daemon=True).start()
+
+
+def _session_pending_kind(sid: str) -> str:
+ return next((str(_pending_prompt_payloads.get(rid, ("input.request", {}))[0]).removesuffix(".request")
+ for rid, (owner_sid, _ev) in list(_pending.items()) if owner_sid == sid), "")
+
+
+def _session_live_status(sid: str, session: dict) -> str:
+ if _session_pending_kind(sid):
+ return "waiting"
+ ready = session.get("agent_ready")
+ # Unset + build never started = a lazy watch session idling, not one stuck mid-construction.
+ if ready is not None and not ready.is_set() and session.get("agent_build_started"):
+ return "starting"
+ return "working" if session.get("running") else "idle"
+
+
+def _session_live_title(session: dict, key: str) -> str:
+ title = str(session.get("pending_title") or "").strip()
+ with contextlib.suppress(Exception), _session_db(session) as db:
+ title = str(db.get_session_title(key) or title or "").strip() if db is not None else title
+ return title
+
+
+def _session_live_item(sid: str, session: dict, current_sid: str = "") -> dict:
+ key = _session_lookup_key(session, fallback=sid)
+ agent = session.get("agent")
+ history = list(session.get("history") or [])
+ status = _session_live_status(sid, session)
+ inflight = _inflight_snapshot(session)
+ queued = _queued_prompt_snapshot(session)
+ preview = next((" ".join(text.split())[:160] for msg in reversed(history)
+ if (text := _content_display_text(msg.get("content", msg.get("text", ""))).strip())), "")
+ if queued:
+ preview = " ".join(str(queued.get("user") or preview).split())[:160]
+ elif inflight:
+ preview = " ".join(str(inflight.get("assistant") or inflight.get("user") or preview).split())[:160]
+ now = time.time()
+ return {
+ "current": sid == current_sid, "id": sid,
+ "last_active": float(session.get("last_active") or session.get("created_at") or now),
+ "message_count": len(history),
+ "model": str(getattr(agent, "model", "") or _resolve_model()), "preview": preview,
+ "session_key": key, "started_at": float(session.get("created_at") or now), "status": status,
+ "title": _session_live_title(session, key),
+ }
+
+
+def _session_lookup_key(session: dict, *, fallback: str = "") -> str:
+ return str(getattr(session.get("agent"), "session_id", None) or session.get("session_key") or fallback or "")
+
+
+def _find_live_session_by_key(session_key: str, profile_home=_ANY_PROFILE) -> tuple[str, dict] | None:
+ # Timestamp-based stored ids can exist in several profiles' stores; a bare-id match would hand
+ # profile B's resume profile A's runtime, so profile-aware callers match on (profile_home, key).
+ # Profile-aware callers pass the home they resolved; the match must then be on (profile_home,
+ # session_key). See #100029.
+ for sid, session in list(_sessions.items()):
+ if (not session.get("_finalized") and _session_lookup_key(session, fallback=sid) == session_key
+ and _live_profile_matches(session, profile_home)):
+ return sid, session
+ return None
+
+
+def _fallback_session_info(session: dict) -> dict:
+ agent = session.get("agent")
+ if agent is not None:
+ return _session_info(agent)
+ # The SESSION's own workspace, not the launch dir (wrong project in the desktop Files pane). `branch` is
+ # always emitted ("" outside git) so a stale label clears; `desktop_contract` missing reads as "out of date".
+ # Reporting `_default_session_cwd()` here told a lazily-resumed session's client that its workspace was
+ # wherever the gateway process happened to start, so the desktop Files pane painted the wrong project
+ # even after the renderer rebound correctly (#71254). `branch` is always emitted ("" outside a git repo)
+ # so a client can clear a stale label instead of retaining it — the same contract `_lazy_session_info`
+ # above already follows.
+ cwd = _session_cwd(session)
+ return {
+ "cwd": cwd, "branch": git_probe.branch(cwd), "project": _project_info_for_cwd(cwd), "lazy": True,
+ "model": _resolve_model(), "skills": {}, "tools": {}, "desktop_contract": DESKTOP_BACKEND_CONTRACT,
+ }
+
+
+def _reconcile_display_with_live(db_display: list[dict], in_memory: list[dict]) -> list[dict]:
+ """Merge the persisted DISPLAY lineage with the in-memory live history: ``db_display`` is verbatim and
+ candidate-inclusive (verification rows the model history collapses out) but can lag by a flush;
+ ``in_memory`` is the recency authority but the collapsed *model* projection. Keep the DB display as base,
+ append only the in-memory tail past the last DB row's ``(role, text)`` anchor — the verification answer
+ survives a warm switch AND a not-yet-flushed live turn is kept."""
+ if not db_display:
+ return in_memory
+ if not in_memory:
+ return db_display
+
+ def _key(msg: dict) -> tuple:
+ return (msg.get("role"), _coerce_message_text(msg.get("content")))
+ anchor = _key(db_display[-1])
+ last_shared = max((idx for idx, msg in enumerate(in_memory) if isinstance(msg, dict) and _key(msg) == anchor), default=-1)
+ if last_shared == -1:
+ return db_display # DB tail not in memory (DB ahead, or diverged) — trust it over duplicating
+ return list(db_display) + list(in_memory[last_shared + 1 :])
+
+
+def _live_visible_history(session: dict, db, in_memory_fallback: list[dict]) -> list[dict]:
+ """User-visible DISPLAY projection for a live/warm session: the persisted display lineage (same read as
+ resume/REST so the payloads agree) reconciled with the in-memory tail; in-memory when the DB is unavailable."""
+ key = session.get("session_key")
+ if db is not None and key:
+ try:
+ # include_compacted: a compacted session's archived turns are still the user's
+ # conversation; without them a warm switch repainted the chat as summary + tail only.
+ display = db.get_messages_as_conversation(
+ key, include_ancestors=True, include_row_ids=True, include_compacted=True)
+ # See #92080.
+ return _reconcile_display_with_live(display, in_memory_fallback)
+ except Exception:
+ logger.debug("live display projection read failed", exc_info=True)
+ return in_memory_fallback
+
+
+def _live_session_payload(
+ sid: str, session: dict, *, cols: int | None = None, touch: bool = False,
+ transport: Transport | None = None, omit_messages: bool = False) -> dict:
+ with session["history_lock"]:
+ if cols is not None:
+ session["cols"] = cols
+ if transport is not None:
+ _rebind_live_transport(sid, session, transport)
+ if touch:
+ # #84417: do not re-fire the live turn's original user text from a stale server-queue
+ # self-duplicate after settle.
+ session["last_active"] = time.time()
+ in_memory_history = list(session.get("display_history_prefix") or []) + list(session.get("history") or [])
+ inflight, queued = _inflight_snapshot(session), _queued_prompt_snapshot(session)
+ running, turn_started_at = bool(session.get("running")), _turn_started_at(session)
+ # Persisted display lineage via the session's profile-aware DB (not the launch ``_get_db()``), read
+ # outside the history lock (the DB has its own). ``omit_messages`` skips the read (fast path).
+ if omit_messages:
+ history = in_memory_history
+ else:
+ with _session_db(session) as db:
+ history = _live_visible_history(session, db, in_memory_history)
+ messages = [] if omit_messages else _history_to_messages(history)
+ payload = {
+ "info": _fallback_session_info(session), "message_count": len(history) if omit_messages else len(messages),
+ "messages": messages,
+ "messages_omitted": omit_messages, "running": running, "turn_started_at": turn_started_at,
+ "session_id": sid, "session_key": _session_lookup_key(session, fallback=sid),
+ "started_at": float(session.get("created_at") or time.time()),
+ "status": _session_live_status(sid, session),
+ }
+ for key, value in (("inflight", inflight), ("queued", queued),
+ ("pending_approval", _pending_approval_request_payload(str(session.get("session_key") or ""))),
+ ("pending_clarify", _pending_clarify_request_payload(sid))):
+ if value:
+ payload[key] = value
+ return _attach_todo_state(payload, session)
+
+
+def _main_runtime_from_agent(agent) -> dict | None:
+ """Aux-client main_runtime override from a live agent, so a one-shot inherits the session's runtime."""
+ if agent is None:
+ return None
+ runtime: dict = {}
+ for field in ("provider", "model", "base_url", "api_key", "api_mode", "auth_mode"):
+ value = getattr(agent, field, None)
+ if isinstance(value, str) and value.strip():
+ runtime[field] = value.strip()
+ elif field == "api_key" and callable(value):
+ runtime[field] = value
+ return runtime or None
+
+
+def register(server):
+ bind_module(globals(), server)
diff --cc tui_gateway/session_transports.py
index 12ee7bc0465,07d5ecfe3ad..b9f3c47b2a4
--- a/tui_gateway/session_transports.py
+++ b/tui_gateway/session_transports.py
@@@ -35,6 -35,18 +35,38 @@@ def _session_has_live_transport(session
return any(peer is not excluding for peer in _session_live_transports(session))
++def _transport_auth_user_id(transport) -> str | None:
++ """``<provider>:<user id>`` the WS-upgrade credential authenticated for ``transport``, or None for the legacy
++ token, stdio and the PTY child's server-internal credential. The prefix keeps a basic-auth ``alice`` and an
++ OIDC ``alice`` apart."""
++ identity = getattr(transport, "auth_identity", None)
++ if _methods_browser_control._is_authenticated_identity(identity):
++ return f"{str(identity['provider']).strip()}:{str(identity['user_id']).strip()}"
++ return None
++
++
++def _session_auth_user_id(session: dict | None) -> str | None:
++ """The login ``session`` was created under, stamped on the record as ``auth_user_id``. A second window turns
++ the transport slot into a FanoutTransport, which names no login, so only a record without the slot reads
++ its transport."""
++ session = session or {}
++ if "auth_user_id" in session:
++ return session["auth_user_id"]
++ return _transport_auth_user_id(session.get("transport"))
++
++
+ def _warn_foreign_login(session: dict, transport) -> None:
+ """Ownership is not enforced; a second login sharing a session is only logged, and the agent keeps the
+ creator's user id."""
+ attaching = _transport_auth_user_id(transport)
+ if attaching is None:
+ return
+ creator = _session_auth_user_id(session)
+ if creator != attaching:
+ logger.warning("Session %s keeps the user id %s it was created with; a client logged in as %s attached",
+ session.get("session_key"), creator or "(none)", attaching)
+
+
def _attach_session_transport(session: dict | None, transport) -> bool:
"""Add live peers; flatten captured queued fanouts without nesting authority."""
if not session or transport is None:
diff --cc ui-tui/src/app/createGatewayEventHandler.ts
index 951d696465d,4f5a821202e..852bfc3157a
--- a/ui-tui/src/app/createGatewayEventHandler.ts
+++ b/ui-tui/src/app/createGatewayEventHandler.ts
@@@ -21,17 -22,15 +24,17 @@@ import { openExternalUrl } from '../lib
import { rpcErrorMessage } from '../lib/rpc.js'
import { topLevelSubagents } from '../lib/subagentTree.js'
import { isPaintableHex, setTerminalBackground, setTerminalForeground } from '../lib/terminalModes.js'
- import { formatAbandonedClarify, formatAbandonedClarifyBatch, formatToolCall, stripAnsi } from '../lib/text.js'
+ import { formatAbandonedClarify, formatAbandonedClarifyBatch, formatToolCall } from '../lib/text.js'
import { bootSeededPin, invalidateBootBackground, writeBootTheme } from '../lib/themeBoot.js'
import { defaultThemeForCurrentBackground, fromSkin, skinIsLight, type Theme, themeToneHex } from '../theme.js'
- import type { Msg, SubagentProgress, SubagentStatus, Usage } from '../types.js'
+ import type { Msg, SessionInfo, SubagentProgress } from '../types.js'
import { applyDelegationStatus, getDelegationState } from './delegationStore.js'
- import type { GatewayEventHandlerContext } from './interfaces.js'
+ import type { GatewayEventHandlerContext, NoticeLevel } from './interfaces.js'
import { getOverlayState, patchOverlayState } from './overlayStore.js'
+import { markBubbleShown, newlyStartedRows } from './pendingBubbles.js'
import { flashGoodVibes, flashPet } from './petFlashStore.js'
+import { captureDestination, isCurrentDestination } from './submissionDestination.js'
import { turnController } from './turnController.js'
import { getTurnState } from './turnStore.js'
import { getUiState, patchUiState } from './uiStore.js'
@@@ -418,10 -420,10 +424,10 @@@ const normalizeSubagentStatus = (status
return KNOWN_SUBAGENT_STATUSES.has(normalized) ? normalized : fallback
}
- export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev: GatewayEvent) => void {
+ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev: AnyGatewayEvent) => void {
syncThemeToTerminalBackground()
- const { rpc } = ctx.gateway
+ const { gw, rpc } = ctx.gateway
const { STARTUP_RESUME_ID, newSession, recoverSidRef, resumeById, setCatalog } = ctx.session
const { bellOnComplete, bellOnPrompt, stdout, sys } = ctx.system
@@@ -831,10 -787,9 +837,14 @@@
return
case 'session.info': {
- const info = ev.payload as SessionInfo | undefined
+ const current = getUiState().info
- const incoming = ev.payload
++ const incoming = ev.payload as SessionInfo | undefined
++
++ if (!incoming) {
++ return
++ }
- if (!info) {
+ if (incoming.profile_name && current?.profile_name && incoming.profile_name !== current.profile_name) {
return
}
@@@ -1322,11 -1258,10 +1339,15 @@@
}
case 'clarify.request': {
+ if (!ev.payload) {
+ return
+ }
+
+ const shared = ev.payload as typeof ev.payload & { prompt_id?: string; execution_generation?: number }
+
+ const sharedControl = shared.prompt_id && ev.session_id && typeof shared.execution_generation === 'number'
+ ? { session_id: ev.session_id, execution_generation: shared.execution_generation, prompt_id: shared.prompt_id } : undefined
+
const batch = (ev.payload.questions ?? [])
.filter(q => typeof q?.qid === 'string' && q.qid && typeof q?.question === 'string' && q.question.trim())
.map(q => ({
@@@ -1358,11 -1293,10 +1379,15 @@@
}
case 'approval.request': {
+ if (!ev.payload) {
+ return
+ }
+
+ const shared = ev.payload as typeof ev.payload & { prompt_id?: string; execution_generation?: number }
+
+ const sharedControl = shared.prompt_id && ev.session_id && typeof shared.execution_generation === 'number'
+ ? { session_id: ev.session_id, execution_generation: shared.execution_generation, prompt_id: shared.prompt_id } : undefined
+
const description = String(ev.payload.description ?? 'dangerous command')
// Only an explicit false (tirith warning) drops the permanent-allow option.
const allowPermanent = ev.payload.allow_permanent !== false
diff --cc ui-tui/src/app/turnController.ts
index f8562903414,afc9f3f6cf5..b695b0aa9a4
--- a/ui-tui/src/app/turnController.ts
+++ b/ui-tui/src/app/turnController.ts
@@@ -5,10 -7,9 +7,10 @@@ import
STREAM_SCROLL_BATCH_MS,
STREAM_TYPING_BATCH_MS
} from '../config/timing.js'
- import type { SessionInterruptResponse, SubagentEventPayload } from '../gatewayTypes.js'
+ import type { SessionInterruptResponse } from '../gatewayTypes.js'
import { appendToolShelfMessage, isToolShelfMessage } from '../lib/liveProgress.js'
import { hasReasoningTag, splitReasoning } from '../lib/reasoning.js'
+import { rpcErrorMessage } from '../lib/rpc.js'
import {
boundedLiveRenderText,
buildToolTrailLine,
diff --cc ui-tui/src/app/useMainApp.ts
index 2e5ad208cb0,bb5d22beaae..81ca02811ea
--- a/ui-tui/src/app/useMainApp.ts
+++ b/ui-tui/src/app/useMainApp.ts
@@@ -234,13 -228,13 +234,13 @@@ export function useMainApp(gw: GatewayC
)
const slashFlightRef = useRef(0)
- const slashRef = useRef<(cmd: string) => boolean>(() => false)
+ const slashRef = useRef<SlashHandler>(() => false)
const colsRef = useRef(cols)
const scrollRef = useRef<null | ScrollBoxHandle>(null)
- const onEventRef = useRef<(ev: GatewayEvent) => void>(() => {})
+ const onEventRef = useRef<(ev: AnyGatewayEvent) => void>(() => {})
const sysRef = useRef<(text: string) => void>(() => {})
const submitRef = useRef<(value: string) => void>(() => {})
- const submitLiteralRef = useRef<(value: string) => void>(() => {})
+ const submitLiteralRef = useRef<(value: string, attachments?: Array<{ path: string; mime: string }>) => void>(() => {})
const terminalHintsShownRef = useRef(new Set<string>())
const historyItemsRef = useRef(historyItems)
const lastUserMsgRef = useRef(lastUserMsg)
diff --cc ui-tui/src/app/useSessionLifecycle.ts
index 136e3fdbb3c,5457fb02264..7cdda5db494
--- a/ui-tui/src/app/useSessionLifecycle.ts
+++ b/ui-tui/src/app/useSessionLifecycle.ts
@@@ -3,9 -2,9 +3,10 @@@ import { writeFileSync } from 'node:fs
import type { ScrollBoxHandle } from '@hermes/ink'
import { evictInkCaches } from '@hermes/ink'
+ import type { SessionInflightTurn, SessionResumeResponse, Usage } from '@hermes/shared/gateway-events'
import { type RefObject, useCallback, useEffect, useMemo, useRef } from 'react'
+import { localCreationOptions } from '../canonicalGateway.js'
import { buildSetupRequiredSections, SETUP_REQUIRED_TITLE } from '../content/setup.js'
import { introMsg, toTranscriptMessages } from '../domain/messages.js'
import { ZERO } from '../domain/usage.js'
@@@ -14,15 -13,11 +15,13 @@@ import type
SessionActivateResponse,
SessionCloseResponse,
SessionCreateResponse,
+ SessionDetachResponse,
- SessionInflightTurn,
- SessionResumeResponse,
SessionTitleResponse,
SetupStatusResponse
} from '../gatewayTypes.js'
+import { migratePendingInputs } from '../lib/pendingInputs.js'
import { asRpcResult } from '../lib/rpc.js'
- import type { Msg, PanelSection, SessionInfo, Usage } from '../types.js'
+ import type { Msg, PanelSection, SessionInfo } from '../types.js'
import type { ComposerActions, GatewayRpc, StateSetter } from './interfaces.js'
import { patchOverlayState } from './overlayStore.js'
@@@ -473,22 -338,12 +472,22 @@@ export function useSessionLifecycle(opt
return
}
- const previousSid = getUiState().sid
+ const pendingDetach = canonicalDetachFlights.current.get(id)
+ const request = pendingDetach
+ ? pendingDetach.then(() => flight === attachmentFlight.current
- ? gw.request<SessionResumeResponse>('session.resume', { cols: colsRef.current, session_id: id }) : null)
- : gw.request<SessionResumeResponse>('session.resume', { cols: colsRef.current, session_id: id })
++ ? gw.request<SessionResumeResponse<SessionInfo>>('session.resume', { cols: colsRef.current, session_id: id }) : null)
++ : gw.request<SessionResumeResponse<SessionInfo>>('session.resume', { cols: colsRef.current, session_id: id })
- gw.request<SessionResumeResponse<SessionInfo>>('session.resume', { cols: colsRef.current, session_id: id })
+ return request
.then(raw => {
- const r = asRpcResult<SessionResumeResponse>(raw)
+ const r = asRpcResult<SessionResumeResponse<SessionInfo>>(raw)
+ if (flight !== attachmentFlight.current) {
+ discardStaleAttachment(r)
+
+ return
+ }
+
if (!r) {
sys('error: invalid response: session.resume')
diff --cc ui-tui/src/gatewayClient.ts
index c0cc2be2533,14d9350df87..43c0f367478
--- a/ui-tui/src/gatewayClient.ts
+++ b/ui-tui/src/gatewayClient.ts
@@@ -1,13 -1,20 +1,21 @@@
-import { type ChildProcess, spawn } from 'node:child_process'
+import { execFile } from 'node:child_process'
import { EventEmitter } from 'node:events'
import { existsSync } from 'node:fs'
-import { delimiter, resolve } from 'node:path'
-import { createInterface } from 'node:readline'
+import { resolve } from 'node:path'
+import { promisify } from 'node:util'
+ import type { GatewayEvent } from '@hermes/shared/gateway-events'
+ import {
+ DEFAULT_HEARTBEAT_DEADLINE_MS,
+ DEFAULT_HEARTBEAT_INTERVAL_MS,
+ JsonRpcRequestChannel,
+ wireFrameText
+ } from '@hermes/shared/json-rpc-channel'
+ import { reconnectBackoffDelayMs } from '@hermes/shared/reconnect-backoff'
import { WebSocket as UndiciWebSocket } from 'undici'
+import { canonicalEvent, canonicalRequest, canonicalResult, type CreationContract } from './canonicalGateway.js'
- import type { GatewayEvent } from './gatewayTypes.js'
+ import type { AnyGatewayEvent } from './gatewayTypes.js'
import { CircularBuffer } from './lib/circularBuffer.js'
import { recordParentLifecycle } from './lib/parentLog.js'
@@@ -163,13 -143,10 +155,9 @@@ export class GatewayClient extends Even
private readyTimer: ReturnType<typeof setTimeout> | null = null
private subscribed = false
private drainGeneration = 0
- private stdoutRl: ReturnType<typeof createInterface> | null = null
- private stderrRl: ReturnType<typeof createInterface> | null = null
+ private heartbeatTimer: ReturnType<typeof setInterval> | null = null
private reconnectTimer: ReturnType<typeof setTimeout> | null = null
private reconnectAttempts = 0
- private lastActivityAt = 0
- private heartbeatSeq = 0
- private heartbeatPendingId: string | null = null
- private heartbeatSentAt = 0
// Set on kill() so we never auto-reconnect after an intentional shutdown.
private disposed = false
@@@ -448,17 -377,7 +392,17 @@@
}
}
+ hydrateSharedPrompts(snapshot: unknown) {
+ if (!this.isCanonical) { return }
+ const result = snapshot as { session_id: string; authority_epoch: number; prompts?: Array<Record<string, unknown>> }
+
+ for (const prompt of result.prompts ?? []) {
+ this.publishLocalEvent({ type: `${prompt.kind}.request`, session_id: result.session_id,
- payload: { ...prompt, execution_epoch: String(result.authority_epoch) } } as unknown as GatewayEvent)
++ payload: { ...prompt, execution_epoch: String(result.authority_epoch) } } as unknown as AnyGatewayEvent)
+ }
+ }
+
- publishLocalEvent(ev: GatewayEvent) {
+ publishLocalEvent(ev: AnyGatewayEvent) {
const frame = JSON.stringify({ jsonrpc: '2.0', method: 'event', params: ev })
this.mirrorEventToSidecar(frame)
@@@ -489,25 -404,88 +429,32 @@@
}
}
+ private protocolError(what: string, text: string, emptyLabel: string) {
+ const preview = text.trim().slice(0, MAX_LOG_PREVIEW) || emptyLabel
+
+ this.pushLog(`[protocol] ${what}: ${preview}`)
+ this.publish({ type: 'gateway.protocol_error', payload: { preview } })
+ }
+
- private startSpawnedGateway(root: string) {
- const python = resolvePython(root)
- const cwd = process.env.HERMES_CWD || root
- const env = { ...process.env }
- const pyPath = env.PYTHONPATH?.trim()
-
- env.PYTHONPATH = pyPath ? `${root}${delimiter}${pyPath}` : root
- // Tell the gateway child where the Hermes source root is so its import
- // guard can force it ahead of any same-named package in the launch cwd.
- env.HERMES_PYTHON_SRC_ROOT = root
- this.startReadyTimer(python, cwd)
- this.proc = spawn(python, ['-m', 'tui_gateway.entry'], { cwd, env, stdio: ['pipe', 'pipe', 'pipe'] })
- this.lifecycle(`[lifecycle] spawned gateway child ${describeChild(this.proc)} python=${python} cwd=${cwd}`)
-
- const stdin = this.proc.stdin!
- this.channel.attach({ send: text => void stdin.write(text + '\n') })
-
- this.stdoutRl = createInterface({ input: this.proc.stdout! })
- this.stdoutRl.on('line', raw => {
- if (!this.channel.handleFrame(raw)) {
- this.protocolError('malformed stdout', raw, '(empty line)')
- }
- })
-
- this.stderrRl = createInterface({ input: this.proc.stderr! })
- this.stderrRl.on('line', raw => {
- const line = truncateLine(raw.trim())
-
- if (!line) {
- return
- }
-
- this.pushLog(line)
- this.publish({ type: 'gateway.stderr', payload: { line } })
- })
-
- const ownedProc = this.proc
- this.proc.on('error', err => {
- // Skip stale errors on an already-replaced child.
- if (this.proc !== ownedProc) {
- this.pushLog(`[lifecycle] stale child error ignored ${describeChild(ownedProc)} message=${err.message}`)
-
- return
- }
-
- const line = `[spawn] ${err.message}`
-
- this.lifecycle(`[lifecycle] child error ${describeChild(ownedProc)} message=${err.message}`)
- this.pushLog(line)
- this.publish({ type: 'gateway.stderr', payload: { line } })
- // Detach the reference up front so the late `exit` event for
- // this same child is identity-skipped (we don't want to emit
- // 'exit' twice). Then run the full teardown — clears the
- // startup timer so we don't fire a misleading
- // `gateway.start_timeout`, rejects pending RPCs, and emits or
- // queues a single `exit`.
- this.proc = null
- this.handleTransportExit(1, `gateway error: ${err.message}`)
- })
- this.proc.on('exit', (code, signal) => {
- // start() can replace `this.proc` while an old child is still
- // tearing down. Skip stale exits so we don't clear the new
- // startup timer or reject newly-issued pending requests.
- if (this.proc !== ownedProc) {
- this.pushLog(
- `[lifecycle] stale child exit ignored ${describeChild(ownedProc)} code=${code ?? 'null'} signal=${signal ?? 'null'}`
- )
-
- return
- }
-
- this.lifecycle(
- `[lifecycle] child exit ${describeChild(ownedProc)} code=${code ?? 'null'} signal=${signal ?? 'null'}`
- )
- this.handleTransportExit(code)
+ private startLocalGateway() {
+ const generation = ++this.localGeneration
+ const start = !this.localStarted
+ this.localStarted = true
+ this.bootstrapError = null
+ this.bootstrapFlight = this.bootstrap(start).then(grant => {
+ if (this.disposed || generation !== this.localGeneration) { return }
+ this.attachUrl = grant.url
+ this.isCanonical = true
+ this.startAttachedGateway(grant.url, grant.protocols)
+ }).catch(error => {
+ if (this.disposed || generation !== this.localGeneration) { return }
+ this.bootstrapError = error instanceof Error ? error : new Error(String(error))
+ this.clearReadyTimer()
+ this.publish({ type: 'gateway.start_timeout', payload: {
+ python: 'gateway ensure', cwd: '', stderr_tail: this.bootstrapError.message
+ } })
+ this.rejectPending(this.bootstrapError)
+ this.scheduleReconnect()
})
}
@@@ -542,21 -525,8 +494,20 @@@
resolve()
}
- this.lastActivityAt = Date.now()
this.clearReconnect()
this.connectSidecarMirror()
+
+ if (this.isCanonical) {
+ void this.requestOverWebSocket<{session_create: CreationContract}>('runtime.describe').then(description => {
+ this.creationContract = description.session_create
+
+ if (this.ws === ws) { this.publish({ type: 'gateway.ready', payload: {} }) }
+ }).catch(error => {
+ this.publish({ type: 'gateway.start_timeout', payload: {
+ python: 'runtime.describe', cwd: '', stderr_tail: String(error)
+ } })
+ })
+ }
},
{ once: true }
)
@@@ -635,8 -605,13 +585,7 @@@
this.sidecarUrl = sidecarUrl
this.resetStartupState()
this.clearReconnect()
- this.stopHeartbeat()
- if (this.proc && !this.proc.killed && this.proc.exitCode === null) {
- this.lifecycle(`[lifecycle] replacing live gateway child ${describeChild(this.proc)}`)
- this.proc.kill()
- }
-
- this.proc = null
this.closeGatewaySocket()
this.closeSidecarSocket()
@@@ -863,17 -725,20 +762,19 @@@
this.start()
}
- return this.requestOverWebSocket<T>(method, params)
+ return this.ensureAttachedWebSocket(method).then(() =>
+ this.channel.request<T>(method, params, timeoutMs, undefined, () => this.notConnected(method))
+ )
}
- if (!this.proc?.stdin || this.proc.killed || this.proc.exitCode !== null) {
- this.start()
- }
+ if (!this.bootstrapFlight) { this.start() }
- if (!this.proc?.stdin) {
- return Promise.reject(new Error('gateway not running'))
- }
+ return this.bootstrapFlight!.then(() => {
+ if (this.bootstrapError) { throw this.bootstrapError }
+ const request = canonicalRequest(method, params, this.creationContract)
- return this.channel.request<T>(method, params, timeoutMs, undefined, () => this.notConnected(method))
+ return this.requestOverWebSocket<T>(request.method, request.params).then(value => canonicalResult(method, value, request.params))
+ })
}
kill(reason = 'requested') {
diff --cc ui-tui/src/gatewayTypes.ts
index c78450ba06b,a353a6e4f1f..17ccede54a5
--- a/ui-tui/src/gatewayTypes.ts
+++ b/ui-tui/src/gatewayTypes.ts
@@@ -182,27 -177,10 +177,12 @@@ export interface SystemBatteryResponse
// ── Session lifecycle ────────────────────────────────────────────────
export interface SessionCreateResponse {
+ stored_session_id?: string
info?: SessionInfo & { config_warning?: string; credential_warning?: string }
session_id: string
+ subscription_id?: string
}
- export interface SessionResumeResponse {
- stored_session_id?: string
- session_key?: string
- inflight?: null | SessionInflightTurn
- info?: SessionInfo
- message_count?: number
- messages: GatewayTranscriptMessage[]
- resumed?: string
- running?: boolean
- session_id: string
- started_at?: number
- status?: LiveSessionStatus
- subscription_id?: string
- }
-
export type LiveSessionStatus = 'idle' | 'starting' | 'waiting' | 'working'
export interface SessionActiveItem {
@@@ -222,14 -200,7 +202,8 @@@ export interface SessionActiveListRespo
sessions?: SessionActiveItem[]
}
- export interface SessionInflightTurn {
- assistant?: string
- streaming?: boolean
- user?: string
- }
-
export interface SessionActivateResponse {
+ stored_session_id?: string
inflight?: null | SessionInflightTurn
info?: SessionInfo
message_count?: number
@@@ -239,28 -210,8 +213,15 @@@
session_key?: string
started_at?: number
status?: LiveSessionStatus
+ subscription_id?: string
+}
+
+export interface SessionDetachResponse {
+ detached: boolean
+ session_id: string
+ subscription_id: string
}
- export interface SessionListItem {
- id: string
- message_count: number
- preview: string
- source?: string
- started_at: number
- title: string
- }
-
- export interface SessionListResponse {
- sessions?: SessionListItem[]
- }
-
export interface SessionDeleteResponse {
deleted: string
}
diff --cc ui-tui/src/types.ts
index 3f0be998d64,4e2dfeb286d..8bfbd209c15
--- a/ui-tui/src/types.ts
+++ b/ui-tui/src/types.ts
@@@ -1,4 -1,4 +1,5 @@@
+import type { SharedControl } from './canonicalGateway.js'
+ import type { SubagentStatus, Usage } from '@hermes/shared/gateway-events'
export interface ActiveTool {
context?: string
diff --cc web/src/lib/api.ts
index 71858493213,b0ce13ae7dd..889c01f45f0
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@@ -1,7 -1,8 +1,11 @@@
- import { buildHermesWebSocketUrl } from "@hermes/shared";
+ import {
+ buildHermesWebSocketUrl,
+ type ModelOptionProvider,
+ type ModelOptionsResponse,
+ } from "@hermes/shared";
+import { createDashboardSessionMutations } from "./session-mutations";
+
+const mutateSessionHttp = createDashboardSessionMutations(fetchJSON);
// The dashboard can be served either at the root of its host (e.g.
// https://kanban.tilos.com/) or under a URL prefix when reverse-proxied
diff --cc website/docs/developer-guide/gateway-classic-cli.md
index f70e315725e,00000000000..dc5421373f3
mode 100644,000000..100644
--- a/website/docs/developer-guide/gateway-classic-cli.md
+++ b/website/docs/developer-guide/gateway-classic-cli.md
@@@ -1,66 -1,0 +1,71 @@@
++---
++title: Classic gateway client
++description: How hermes chat / --cli attach to the gateway authority
++---
++
+# Classic gateway client (initial migration)
+
+Normal `hermes --cli`, `hermes chat`, `hermes chat -q '…' -Q`, and top-level
+`hermes -z '…'` use the gateway authority. Direct `cli.main` chat launches also
+hand off before constructing a local agent. Local bootstrap uses the canonical
+ensure lifecycle and a single-use private control ticket, not service installation.
+An explicit `HERMES_TUI_GATEWAY_URL` remains remote-only: failed connection or
+authentication never launches a local replacement.
+
+The client prints the persisted `Session:` ID to stderr. Resume with
+`hermes --cli chat --resume ID`. Input is admitted with a fresh `input_id`; events
+and final replies come from the authority. `/quit`, `/exit`, `/detach`, EOF and
+closing the terminal detach only. `/stop` sends an execution-generation-fenced
+interrupt. Pending approvals display `/approve ID once|deny|…`; clarification
+uses `/answer ID TEXT`. The client uses the displayed prompt ID and its captured
+generation, not a locally reconstructed waiter. Other slash commands explicitly
+reject instead of running local mutations.
+
+One-shot stdout contains only the final reply. Exit status is 0 for a completed
+admission, 1 for failed execution/connection, 2 for unsupported frontend options,
+3 for a pending control that requires interactive reattachment, and 130 for a
+keyboard detach. A pending control does not imply cancellation. `-z` no longer
+implicitly bypasses approval policy.
+
+## Current parity limits — not full classic CLI parity
+
+The gateway advertises its accepted creation parameters through `runtime.describe`.
+Model, provider, reasoning, toolsets and max-turns are sent only when advertised;
+otherwise explicitly requested options reject. Caller cwd is sent when advertised;
+an old gateway lacking cwd support prints a warning that it uses its configured
+execution directory, while explicit `--in` rejects. Resume retains existing
+session policy; creation overrides on resume reject.
+
+Images, skills, worktrees, checkpoints, pass-session-id, safe mode, ignored rules
+or user config, YOLO, hook acceptance, continue/latest/title selection,
+create-if-missing, no-restore-cwd, usage reports, run budgets, direct API credentials,
+verbose/compact display and local tool listing are not implemented in this client
+and reject explicitly. Full legacy presentation, slash registry parity, interactive
+history editing, auto-reconnect, lost-ACK durable client journals, remote login
+bootstrap, cold-owner resume and native Windows/macOS QA remain outstanding.
+The client preserves an explicit remote URL's existing authentication mechanism;
+it does not acquire or mint remote credentials.
+
+`tests/hermes_cli/test_gateway_chat_native.py` exercises native tmux/PTY classic
+fresh input, detach, persisted-ID resume and one-shot through the ordinary daemon
+with a loopback model, isolated HOME/HERMES_HOME and caller cwd. Constructor
+instrumentation records no client AIAgent, SessionDB or GatewayRunner. The test
+also denies an invalid approval choice, then reconnects and consents before a real
+terminal effect on an owned fixture. Stale-control/active-Stop native coverage and
+native clarify interaction remain separate acceptance work.
+
+For two-checkout compatibility testing, load the narrowly scoped pytest option
+plugin and specify the disposable gateway peer's checkout (the normal runner's
+hermetic environment deliberately removes arbitrary environment overrides):
+
+```sh
+scripts/run_tests.sh -j 1 --file-retries 0 tests/hermes_cli/test_gateway_chat_native.py \
+ -p tests.hermes_cli.gateway_client_options --client-test-runtime-root=/path/to/runtime-checkout
+```
+
+The receipt explicitly reports `caller_cwd_effect_verified`. On a cwd-capable
+runtime the native client submits model/toolsets/cwd and the real terminal writes
+its actual execution directory into an owned temporary receipt. On an older
+runtime, explicit `--in` must reject without that effect. Do not count the latter
+as cwd parity. Both client and daemon use isolated test homes; this option does
+not install a service or alter the selected checkout.
diff --cc website/docs/developer-guide/gateway-local-sessions.md
index be1632146fb,00000000000..1a49b9484fc
mode 100644,000000..100644
--- a/website/docs/developer-guide/gateway-local-sessions.md
+++ b/website/docs/developer-guide/gateway-local-sessions.md
@@@ -1,169 -1,0 +1,174 @@@
++---
++title: Gateway local sessions
++description: Local CLI/TUI sessions as canonical gateway admissions
++---
++
+# Gateway-owned fresh local sessions
+
+The composed gateway listener can create fresh local **CLI, TUI, or GUI-policy** sessions without
+starting `tui_gateway`'s separate agent runtime. The existing `GatewayRunner` / `TurnRunner`
+own execution, approval waiters, tool calls, session storage, and canonical event delivery.
+
+A server-authenticated identity with `session:create` can call:
+
+```json
+{"jsonrpc":"2.0","id":1,"method":"session.create","params":{"request_id":"stable-client-create-id","source":"cli"}}
+```
+
+The result preserves `session_id`, `stored_session_id`, `messages`, `message_count`, and
+`info`, and includes the authority's normal resume snapshot fields. Both session IDs are
+the same stable persisted **logical** ID. Compression and reset may rotate the private
+physical transcript target without changing either client ID. Creation is lazy with respect
+to the agent, but reserves the real
+SessionDB/SessionStore identity before returning. One canonical SQLite transaction commits
+the session row, route, and private `gateway.local_policy.v1:<stored-id>` creation receipt.
+Repeating the request ID for the same principal and profile reuses that identity and frozen
+policy, including after daemon death. Omit the ID for a new session; clients that need
+lost-ACK retry protection must retain it. A failed transaction publishes no live session.
+
+Attach another authenticated viewer with `session.resume({session_id})`, and submit
+through `prompt.submit({session_id, submission_id, text})`. The accepted receipt is durable
+admission, not inference completion. Closing every viewer leaves the execution and its
+pending approval alive. A new viewer can resume the same identity and answer through
+`approval.respond({session_id, execution_generation, prompt_id, choice})`.
+
+## Deliberate behavior change: shared operator access
+
+Verified operators of the same gateway profile may attach to canonical local sessions
+created through another operator authentication path. This replaces the creator-subject-only
+access fence for those operators: the existing dashboard gate already grants operator access,
+so changing from native CLI/TUI to an authenticated dashboard must not create a second runtime
+or prevent attachment solely because the raw identities differ. This is shared access, not
+shared identity: creation receipts keep the original owner, and admissions and retries keep
+the submitting principal.
+
+The server issues `session:operator` only at these existing trusted boundaries:
+
+- Native interactive bootstrap ticket redemption (not worker-adoption tickets).
+- The dashboard WebSocket upgrade gate, including authenticated dashboard login tickets,
+ the process-lifetime internal credential for server-spawned PTY clients, and the verified
+ legacy session token when that authentication path is enabled.
+- The HTTP mutation gate, after a verified dashboard Session, native HTTP owner grant,
+ or permitted legacy session token has been accepted.
+
+A client cannot request this scope in RPC parameters or an identity capability list.
+Operator scope does not replace profile, instance, per-operation capability, subscription,
+revision, or generation checks. It does not upgrade messaging, room, worker, or service
+credentials, or permit remote first-claim adoption of unowned historical transcripts. If
+restricted dashboard identities are introduced, these issuance gates must reflect that
+restriction rather than treating every accepted dashboard credential as an operator.
+
+Cross-subject local submissions carry a private, server-written profile/session/principal
+binding for queued execution and recovery. It is not exposed in model requests or public
+session snapshots. This change does not expose the gateway listener remotely or implement
+OpenAI API-to-local session affinity; those remain separate integration paths.
+
+## Deliberately limited compatibility
+
+- `source` accepts `cli` (default), `tui`, or `gui`. These select the existing agent
+ platforms `cli`, `tui`, and `desktop`, respectively. The native local routing identity
+ remains server-owned `Platform.LOCAL`; source never grants messaging/native trust.
+ Default TUI selection folds in `project`; GUI folds in `project` and `desktop_ui`.
+ GUI policy is independent of `HERMES_DESKTOP` and of the attaching viewer's identity.
+- Optional flat creation fields: `cwd` (existing absolute gateway-local directory),
+ `model` (nonempty model identifier on the daemon's configured provider), and `toolsets`
+ (explicit array of established toolset names, including an empty array). Unknown or
+ policy-filtered toolsets reject instead of silently disappearing. Explicit toolsets
+ override the default surface additions; CLI/TUI cannot explicitly request `desktop_ui`.
+ `cwd`, model selection, source and effective toolsets are captured at creation; attach
+ cannot change them. A conflicting repeat `request_id` returns `invalid_params`.
+- Provider/base URL overrides, reasoning/service-tier, skills, cwd worktree creation,
+ seeded history, profile switching, YOLO, and other launch options still return
+ `invalid_params`. Provider credentials/routing and reasoning/service-tier defaults still
+ use the existing gateway resolution lifecycle; this is not full launch-option parity.
+ No supported launch field mutates daemon-wide configuration or process environment.
+- Fresh creation requires a server-authenticated identity with `session:create`, supplied
+ by the gated dashboard or native bootstrap path. The verified legacy `?token=` route
+ stamps a session-token identity and also supports creation. Callers cannot provide an
+ identity in RPC parameters, and operator scope does not promote resume-only capabilities
+ to `session:create`.
+- `session.list({limit})` returns authorized **live** authority sessions (`scope: "live"`),
+ not the full historical session picker. `session.info({session_id})` is a lightweight,
+ authorized view of source, current model, lazy-agent status, and profile ID.
+- `ping({})` returns `{pong: true}`. `runtime.describe({})` exposes only authority identity,
+ epoch, and the narrow implemented creation contract. It does not claim full runtime
+ protocol readiness, reveal credentials/paths, start an agent, or renew a turn lease.
+- Cold restart restores valid private local policies and server-owned routes before execution.
+ Creation receipts remain bound to their authenticated creating principal and profile;
+ verified operators in that profile may access the canonical session without replacing
+ that binding. Caller source/native context cannot reconstruct or authorize a local route.
+ Missing, malformed, foreign-profile or mismatched policy/identity fails closed, including preclaim checks;
+ historical pre-extension sessions without a receipt are not silently treated as CLI.
+- Never-started queued local inputs resume through the same authority FIFO after bootstrap
+ readiness. Interrupted started inputs become `unknown`, are never replayed, and pause
+ their followers. Reattachment can inspect the unknown snapshot without running it.
+- Compression publication atomically advances the receipt's private `entry.session_id` and
+ route alongside the child transcript. The receipt retains its creation `session_id`, policy,
+ principal/profile binding, and explicit approved `lineage`. Recovery validates compression
+ steps with the existing canonical child selector and reset steps with the existing
+ `_reset_from` boundary; it never adopts arbitrary forks or copied foreign receipts.
+- The canonical SessionStore local reset commits the new row, old-row closure, receipt and
+ route before changing the in-memory entry. Reset deliberately starts empty history while
+ preserving the frozen launch policy and queued admission owner. It does not replay an
+ interrupted execution or cancel later accepted inputs. Creating an independent conversation
+ still uses `session.create` with a new request ID; this is not a new revision-fenced reset RPC
+ or a change to the multi-view `/new` contract.
+- Admission targets, digests, claim generations, subscriber identity and uncertain outcomes
+ remain on the stable logical row. Thus lost-ACK retries keep their existing receipts after
+ either transition, and shared controls/stream callbacks keep the same execution owner.
+ Clients continue resuming the creation ID, not an internal physical continuation ID.
+
+## Verification
+
+`tests/gateway/test_operator_cross_surface.py` exercises native-created/dashboard-attached
+and dashboard-created/native-attached sessions through real bootstrap and dashboard
+login/callback/cookie/ticket paths in a disposable gateway process. The identity provider and
+model endpoint are test fixtures. It verifies client disconnect/reconnect, FIFO admission and
+retry, retained attribution and model context, unchanged system messages, and private
+operator provenance absent from public responses and model requests. It does **not** kill
+and restart the gateway process, directly compare simultaneous live fanout, or exercise
+shared approval/clarify across those two authentication methods.
+
+`tests/gateway/test_session_operator_scope.py` covers queued operator input across a fresh
+authority epoch using a stub executor and a paused scheduler. This is unit-level recovery
+evidence, not real cross-surface cold-process restart certification. The existing recovery
+fixtures described below provide separate coverage; their results must not be presented as
+a new end-to-end cross-authentication gateway-crash test.
+
+`tests/gateway/test_local_session.py` launches a disposable process with temporary HOME
+and HERMES_HOME, the production composed HTTP/WS listener, real single-use authenticated
+tickets, a loopback OpenAI-compatible model, the real TurnRunner/AIAgent, and the real
+terminal tool. It proves persisted identity and same-agent reattachment; closes both
+viewers while approval is pending; reconnects and consents before deleting only an owned
+temporary directory; checks canonical history; and rejects forged authentication/source/
+profile and unsupported launch fields. A second case runs the real clarify tool,
+reattaches after all viewers close, and verifies the answer reaches the next loopback
+model request. No native messaging allow-all credential authorizes the execution; a
+separate negative control enables messaging allow-all only while proving reconstructed
+local source/profile objects still fail closed.
+
+`tests/gateway/test_session_policy.py` adds three simultaneous CLI/TUI/GUI turns against
+an owned loopback model. A barrier holds their first requests concurrently; real terminal
+calls write separate files in three owned working directories. The next requests expose
+the correct cwd results, distinct requested models and surface-specific tool schemas.
+Reconnect preserves each agent; launcher environment carriers and config bytes do not
+change. This is loopback integration evidence, not native launcher or vendor evidence.
+`tests/gateway/test_local_session_recovery.py` proves rollback-before-publication and cold
+receipt reuse, then starts separate ordinary daemons on the same temporary database using
+real control-socket tickets and authenticated WebSockets. A fixture-only scheduler barrier
+kills the first daemon after an input commits but before claim; another model request is
+held after its real claim. Fresh daemons execute only the authorized queued input, preserve
+history/source/model/toolsets despite changed defaults, and refuse unknown, foreign,
+missing and corrupt policy cases. A further restart executes nothing twice. All inference
+is loopback-only; this is not native launcher or compression-transfer evidence.
+
+`tests/gateway/test_local_session_lineage.py` adds rollback and isolation invariants, plus
+three separate ordinary daemon processes. Its first-process fixture invokes the production
+agent rotation publication on the real cached AIAgent and the production SessionStore reset,
+then kills the daemon after a durable queued admission. Cold unmodified daemons preserve
+compressed history, reset's empty-history boundary, policy/cwd, admission identities and
+unknown-state blocking. Unrelated fork work and foreign receipts stay unclaimed. The model
+peer verifies recovered cwd in the actual prompt and frozen model/toolsets; this fixture does
+not execute a post-restart cwd tool effect, generate a compression summary, or exercise a
+native launcher. It proves the production publication/recovery boundary, not those separate
+surfaces.
diff --cc website/docs/user-guide/sessions.md
index 7ea7a763f11,e17fc4964e6..e876da8ee66
--- a/website/docs/user-guide/sessions.md
+++ b/website/docs/user-guide/sessions.md
@@@ -836,15 -801,32 +837,41 @@@ variables are ignored. Cached agents ma
replacing the durable conversation. Restart-recovery freshness limits automatic
continuation, not the history loaded when you send a message.
+**`/new` moves only the view that ran it.** One session can be open in several
+places at once — a Desktop window, the TUI, a `hermes chat --resume` terminal, an
+ACP editor, a Telegram topic — all attached to the same live conversation on the
+gateway. Running `/new` (or `/reset`) in one of them creates a fresh session and
+rebinds *that* window or chat route to it. The other viewers stay on the original
+session, its history is untouched, and a turn already running there keeps running.
+Ending or clearing the shared conversation is a separate, explicit action (Stop, then
+`/new`; or a delete, which is refused while a turn is live).
+
+ ### Session hygiene: why you should still run `/new`
+
+ Because gateway conversations never expire on their own, it is easy to run one
+ session for weeks. That works, but it quietly defeats the learning loop and
+ inflates costs:
+
+ - **Memory only pays off at boundaries.** `MEMORY.md` / `USER.md` are injected
+ at session start, and `session_search` exists to recall what fell out of
+ context. In a never-ending session everything is still *in* context, so the
+ agent has no reason to consult memory — the "self-learning" machinery barely
+ runs. Memory distillation (the save before reset) also only happens when a
+ session actually ends.
+ - **Cost grows with history.** Compression keeps a long session functional,
+ but every turn still carries a large (compacted) prefix. A fresh session
+ with distilled memory is almost always cheaper than a month-old thread.
+
+ Practical rule: end a session when you finish a task or topic. Run `/new`
+ (optionally named, e.g. `/new payments-refactor`) at natural stopping points —
+ daily or per-project both work. Before the reset, ask the agent to "remember
+ anything worth keeping" if the work surfaced durable preferences or
+ procedures; it saves memories and skills from the expiring session
+ automatically, but an explicit nudge helps. Restarting the machine or the
+ gateway is **not** a boundary — the same session resumes.
+
+ See [Memory](features/memory.md) for what gets carried across boundaries.
+
### Continuity After Crashes and Restarts
diff --cc website/sidebars.ts
index 55d1ed80160,7951d983d86..b83ecddafee
--- a/website/sidebars.ts
+++ b/website/sidebars.ts
@@@ -775,9 -781,13 +781,15 @@@ const sidebars: SidebarsConfig =
'developer-guide/agent-loop',
'developer-guide/prompt-assembly',
'developer-guide/context-compression-and-caching',
+ 'developer-guide/micro-compaction',
'developer-guide/gateway-internals',
+ 'developer-guide/gateway-session-lifecycle',
++ 'developer-guide/gateway-local-sessions',
++ 'developer-guide/gateway-classic-cli',
+ 'developer-guide/multiplexing-gateway',
'developer-guide/completion-backlog-delivery',
'developer-guide/session-storage',
+ 'developer-guide/state-db-recovery',
'developer-guide/provider-runtime',
'developer-guide/programmatic-integration',
],