Skip to content

The agent that grows with you

Merge origin/main (#17: 454 commits to e6757f20292) into feat/unified-gateway-runtime

Tekniumca38632fc01f
diff --cc agent/session_source.py
index 00000000000,6cb706223a3..83f79227e27
mode 000000,100644..100644
--- a/agent/session_source.py
+++ b/agent/session_source.py
@@@ -1,0 -1,44 +1,49 @@@
+ """Session source vocabulary: the ``source`` label a session row carries, and which sources have a
+ person reading the turn as it runs. A leaf (its one import is the stdlib-only session context), so
+ the ``run_agent`` facade and its siblings import it directly."""
+
+ from __future__ import annotations
+
+ from typing import Any, Optional
+
+ from gateway.session_context import get_session_env
+
+ # Sources that label the human conversation an interactive UI transport hosts. A finite ``hermes chat -q`` /
+ # one-shot child spawned from such a session inherits HERMES_SESSION_SOURCE (the terminal tool bridges the
+ # session env into child processes) but is NOT that conversation: labelling it ``tui``/``desktop`` lists it
+ # in the TUI/WebUI pickers as a resumable chat and lets ``hermes -c`` in the TUI continue it (#112550).
+ # Automation sources (kanban, tool, cron, a2a, ...) are inherited on purpose.
+ UI_TRANSPORT_SOURCES = frozenset({"tui", "desktop"})
+
+ # Finite non-interactive CLI runs (``hermes chat -q``/``--oneshot``, ``hermes -z``) get their own source so human
+ # pickers hide them without title/cwd heuristics; ``hermes -c`` still treats them as CLI history.
+ ONESHOT_SOURCE = "oneshot"
+ CLI_FAMILY_SOURCES = frozenset({"cli", ONESHOT_SOURCE})
+
+ # A person reads the turn as it runs: not cron, batch, a messaging chat, or a one-shot run.
+ ATTENDED_SOURCES = UI_TRANSPORT_SOURCES | {"cli", "acp"}
+
+
+ def session_source_for(platform: Optional[str]) -> str:
+ source = str(get_session_env("HERMES_SESSION_SOURCE", "") or "").strip()
+ single_query = get_session_env("HERMES_SINGLE_QUERY_SESSION", "") == "1"
+ explicit = get_session_env("HERMES_SESSION_SOURCE_EXPLICIT", "") == "1"
+ if single_query and not explicit and source in UI_TRANSPORT_SOURCES:
+ source = ""
+ if single_query and not source and (platform or "cli") == "cli":
+ return ONESHOT_SOURCE
+ return source or platform or "cli"
+
+
+ def is_attended(agent: Any) -> bool:
+ """A delegated child answers its parent, not a person, though its copied context still carries
+ the parent's source; a library caller (no platform) has no one reading either."""
+ platform = getattr(agent, "platform", None)
+ if not platform or platform == "subagent":
+ return False
++ # A gateway-admitted ``hermes chat -q`` / ``-z`` turn carries its one-shot fact on the admission,
++ # not in HERMES_SINGLE_QUERY_SESSION (the daemon never had that env).
++ from gateway.session_finite import finite_turn_required
++ if finite_turn_required() is True:
++ return False
+ return session_source_for(platform) in ATTENDED_SOURCES
diff --cc apps/desktop/e2e/core/harness.ts
index e2e8911ec91,9bb7d2e9b91..d3890673cbc
--- a/apps/desktop/e2e/core/harness.ts
+++ b/apps/desktop/e2e/core/harness.ts
@@@ -82,75 -77,9 +82,72 @@@ export function createCoreSandbox(label
}
}
+function sleepSync(ms: number): void {
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
+}
+
+function processHomeUnder(pid: number, root: string): boolean {
+ const info = readProc(pid)
+
+ return Boolean(info?.cmdline) && info!.environ.split('\0').some(entry => entry.startsWith(`HERMES_HOME=${root}`))
+}
+
+/**
+ * SIGTERM (then SIGKILL after 15 s) every daemon recorded in a sandbox
+ * `gateway.lock` (launch home and each profile home). The pid is only
+ * signalled while its environment still names this sandbox, so a recycled pid
+ * is never touched.
+ */
+function stopSandboxGatewayDaemons(root: string, hermesHome: string): void {
+ const profilesDir = path.join(hermesHome, 'profiles')
+
+ const homes = [
+ hermesHome,
+ ...(fs.existsSync(profilesDir) ? fs.readdirSync(profilesDir).map(name => path.join(profilesDir, name)) : [])
+ ]
+
+ const pids = new Set<number>()
+
+ for (const home of homes) {
+ try {
+ const pid = Number(JSON.parse(fs.readFileSync(path.join(home, 'gateway.lock'), 'utf8'))?.pid)
+
+ if (Number.isInteger(pid) && pid > 0 && processHomeUnder(pid, root)) {
+ pids.add(pid)
+ }
+ } catch {
+ // No lock (remote-only spec, never booted) or an empty one: nothing to stop.
+ }
+ }
+
+ const signal = (sig: NodeJS.Signals) => {
+ for (const pid of pids) {
+ try {
+ process.kill(pid, sig)
+ } catch {
+ pids.delete(pid)
+ }
+ }
+ }
+
+ signal('SIGTERM')
+
+ for (const deadline = Date.now() + 15_000; pids.size && Date.now() < deadline; ) {
+ sleepSync(100)
+
+ for (const pid of [...pids]) {
+ if (!processHomeUnder(pid, root)) {
+ pids.delete(pid)
+ }
+ }
+ }
+
+ signal('SIGKILL')
+}
+
/**
- * Sandbox config: only the scripted provider. The external tirith scanner is
- * off: with none on PATH the backend downloads it from GitHub on the first
- * terminal command (network in a required lane), and with one on PATH it
- * fetched a 12 MB threat DB that was still being written after quit. The
- * approval prompts under test come from Hermes's own detector.
+ * Sandbox config: only the scripted provider. The approval prompts under test
+ * come from Hermes's own detector.
*/
export function providerConfigYaml(providerUrl: string, extra = '', approvals: 'manual' | 'off' = 'off'): string {
return `model:
diff --cc apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
index b50f81ffd21,d3d57a98303..caa2ae7ed07
--- a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
@@@ -377,77 -377,6 +377,78 @@@ describe('desktop branch creation idemp
expect($sessions.get().filter(session => session.id === 'stored-pandora')).toHaveLength(1)
expect($sessions.get().filter(session => session.id === 'stored-other-box')).toHaveLength(1)
})
+
+ it('opens the branch child even when the router lands on its route after the resume started', async () => {
+ // Branching the open chat navigates to the child and resumes it in the same
+ // tick. The router commits the child route only on its next render, so the
+ // resume starts on the PARENT's route token and then sees the child's. That
+ // change is the navigation this resume is for, not a user leaving: the
+ // child must still be attached, or "Waking up…" never clears.
- let routeToken = 'route:parent'
++ // Real desktop-controller token shape: `${pathname}:${search}:${hash}`.
++ let routeToken = `${sessionRoute('parent')}::`
+ let routedId: null | string = 'parent'
+
+ const navigate = vi.fn((to: string) => {
+ queueMicrotask(() => {
- routeToken = `route:${to}`
++ routeToken = `${to}::`
+ routedId = to === sessionRoute('stored-branch') ? 'stored-branch' : null
+ })
+ })
+
+ const requestGateway = vi.fn(async (method: string) =>
+ (method === 'session.branch_stored'
+ ? { session_id: 'runtime-branch', stored_session_id: 'stored-branch' }
+ : {}) as never
+ )
+
+ // The child's resume is profile-routed (resolveStoredSession stamps it).
+ vi.mocked(requestGatewayForProfile).mockImplementation((async (_profile: string, method: string) =>
+ (method === 'session.resume'
+ ? {
+ info: {},
+ message_count: 0,
+ messages: [],
+ resumed: 'stored-branch',
+ session_id: 'runtime-branch',
+ session_key: 'stored-branch'
+ }
+ : {}) as never) as never)
+
+ let actions: HarnessHandle | null = null
+
+ setSessions([storedSession({ id: 'parent', message_count: 2, title: 'Parent' })])
+
+ render(
+ <Harness
+ getRoutedStoredSessionId={() => routedId}
+ getRouteToken={() => routeToken}
+ navigate={navigate}
+ onReady={value => (actions = value)}
+ requestGateway={requestGateway}
+ selectedStoredSessionId="parent"
+ />
+ )
+ await waitFor(() => expect(actions).not.toBeNull())
+
+ await act(async () => {
+ await expect(actions!.branchStoredSession('parent')).resolves.toBe(true)
+ })
+
+ expect(navigate).toHaveBeenCalledWith(sessionRoute('stored-branch'), { replace: true })
+ // The resume dispatches on the child's profile socket.
+ await waitFor(() =>
+ expect(
+ vi
+ .mocked(requestGatewayForProfile)
+ .mock.calls.filter(([, method, params]) => method === 'session.resume' && params?.session_id === 'stored-branch')
+ ).toHaveLength(1)
+ )
+ await waitFor(() => expect($activeSessionId.get()).toBe('runtime-branch'))
+ expect($resumeFailedSessionId.get()).toBeNull()
+ vi.mocked(requestGatewayForProfile).mockReset()
+ setSelectedStoredSessionId(null)
+ setActiveSessionId(null)
+ })
})
describe('connection-qualified session deletion', () => {
diff --cc apps/desktop/src/i18n/en.ts
index 0c21a949158,c345155a8a9..e893179db9f
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@@ -1158,37 -1163,13 +1163,7 @@@ export const en: Translations =
},
fieldLabels: FIELD_LABELS,
fieldDescriptions: FIELD_DESCRIPTIONS,
- uninstallSection: {
- dangerZone: 'Danger zone',
- checkingInstalled: 'Checking what’s installed…',
- uninstallHermes: 'Uninstall Hermes',
- chooseHowMuch:
- 'Choose how much to remove. The app closes to finish the job; reopen the installer any time to come back.',
- confirmUninstall: 'Confirm uninstall',
- confirmBody: what => `This removes ${what}. This can’t be undone.`,
- appLabel: 'App:',
- couldNotStart: 'Uninstall could not start.',
- uninstalling: 'Uninstalling…',
- yesUninstall: 'Yes, uninstall',
- options: {
- gui: {
- title: 'Uninstall Chat GUI only',
- description: 'Remove this desktop app. The Hermes agent, your config, and chats all stay.',
- consequence: 'the desktop Chat GUI (this app and its data)'
- },
- lite: {
- title: 'Uninstall GUI + agent, keep my data',
- description:
- 'Remove the app and the Hermes agent, but keep config, chats, and secrets for a future reinstall.',
- consequence: 'the Chat GUI and the Hermes agent (config, chats, and secrets are kept)'
- },
- full: {
- title: 'Uninstall everything',
- description: 'Remove the app, the agent, and all user data — config, chats, scheduled jobs, secrets, logs.',
- consequence: 'EVERYTHING — the Chat GUI, the Hermes agent, and all of your config, chats, secrets, and logs'
- }
- }
- },
+ uninstallSection: enUninstallSection,
- poolLimits: {
- warmBotBackendsAria: 'Warm bot backends',
- warmBotBackendsTitle: 'Warm Bot Backends',
- backendIdleTimeoutAria: 'Backend idle timeout in milliseconds',
- backendIdleTimeoutTitle: 'Backend Idle Timeout'
- },
customEndpoints: {
active: 'Active',
apiKeySet: 'API key set',
diff --cc apps/desktop/src/i18n/types.ts
index e46f795c970,acb3ca209a6..1cf7a5b5fd4
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@@ -947,23 -951,13 +951,7 @@@ export interface Translations extends N
}
fieldLabels: Record<string, string>
fieldDescriptions: Record<string, string>
- uninstallSection: {
- dangerZone: string
- checkingInstalled: string
- uninstallHermes: string
- chooseHowMuch: string
- confirmUninstall: string
- confirmBody: (what: string) => string
- appLabel: string
- couldNotStart: string
- uninstalling: string
- yesUninstall: string
- options: {
- gui: { title: string; description: string; consequence: string }
- lite: { title: string; description: string; consequence: string }
- full: { title: string; description: string; consequence: string }
- }
- }
+ uninstallSection: UninstallSectionTranslations
- poolLimits: {
- warmBotBackendsAria: string
- warmBotBackendsTitle: string
- backendIdleTimeoutAria: string
- backendIdleTimeoutTitle: string
- }
customEndpoints: {
active: string
apiKeySet: string
diff --cc cli-config.yaml.example
index 4505d53bae3,46f4272b68b..e3f9995a680
--- a/cli-config.yaml.example
+++ b/cli-config.yaml.example
@@@ -7,7 -7,7 +7,7 @@@
# Schema version of this file. The installers copy it to seed config.yaml, and
# `hermes update` uses it to know which one-time migrations the file already
# has. Hermes manages it: do not copy it into another config.
--_config_version: 50
++_config_version: 51
# =============================================================================
# Database Configuration
diff --cc cron/jobs.py
index bc4d365cabd,8c132fe0e60..7c8df1b2943
--- a/cron/jobs.py
+++ b/cron/jobs.py
@@@ -28,9 -28,11 +28,11 @@@ except ImportError: # pragma: no cove
msvcrt = None
from datetime import datetime, timedelta, timezone
from pathlib import Path
-from hermes_constants import get_hermes_home
+from hermes_constants import display_hermes_home, get_hermes_home
from cron.constants import CLAIM_TTL_INACTIVITY_HEADROOM, FIRE_CLAIM_SKEW_SECONDS, FIRE_CLAIM_TTL_SECONDS
from cron.env_settings import cron_env_setting
+ from cron.scheduler_ownership import _claim_owner_is_dead
+ from cron import store_health
from typing import Optional, Dict, List, Any, Callable, Set, Tuple, Union, Collection
logger = logging.getLogger(__name__)
diff --cc cron/scheduler_tick.py
index a3f9878fe74,68d3b183a8c..d22330c5637
--- a/cron/scheduler_tick.py
+++ b/cron/scheduler_tick.py
@@@ -2,10 -2,35 +2,36 @@@
import concurrent.futures
import contextlib
+ import logging
+ import time
+
+ from cron import store_health
+ from cron.constants import is_recurring
+
+ logger = logging.getLogger("cron.scheduler")
+
+ # Log the yield at most once per episode (reset when the skew changes) to avoid per-interval spam.
+ _YIELD_LOG_INTERVAL_SECONDS = 3600.0
+ _last_yield_log: dict[str, object] = {}
+
+
+ def _log_tick_yield_once(reason: str) -> None:
+ """Log the yield at error level once per episode (skew signature)."""
+ global _last_yield_log
+ now = time.monotonic()
+ last_reason = _last_yield_log.get("reason")
+ last_at = _last_yield_log.get("at", 0.0)
+ if last_reason != reason or (now - float(last_at)) >= _YIELD_LOG_INTERVAL_SECONDS:
+ logger.error(
+ "Cron tick yielded: this process is running stale code (%s) and a "
+ "fresher gateway owns the runtime lock — jobs will fire from that "
+ "process. Restart this one to reclaim its ticks.",
+ reason)
+ _last_yield_log = {"reason": reason, "at": now}
-def tick(verbose=True, adapters=None, loop=None, sync=True, *, can_dispatch=None):
+def tick(verbose=True, adapters=None, loop=None, sync=True, *, can_dispatch=None,
+ headless: bool = False):
from hermes_cli.backend_retirement import retirement
# Hold admission through the entire scan/advance/submit handoff. A predicate alone races
@@@ -13,18 -38,43 +39,47 @@@
with retirement.work() as admitted:
if not admitted:
return 0
- return _tick_admitted(verbose, adapters, loop, sync, can_dispatch=can_dispatch)
+ return _tick_admitted(verbose, adapters, loop, sync, can_dispatch=can_dispatch,
+ headless=headless)
+ def _acquire_tick_lock_or_degrade(_sched):
+ """The tick lock fd, or None when this tick must not run: another ticker holds the lock, or
+ the store cannot be written (read-only/full/denied: the lock file cannot even be created), in
+ which case the store is marked degraded and the MCP orphan sweep still runs."""
+ lock_dir, lock_file = _sched._get_lock_paths()
+ _sched._ensure_cron_dir(lock_dir)
+ try:
+ return _sched._acquire_tick_lock(lock_file)
+ except OSError as exc:
+ if exc.errno not in store_health.UNWRITABLE_ERRNOS:
+ raise # EMFILE/ENFILE etc. stay a FAILED tick (#87644)
+ store_health.note_unwritable(exc, "tick lock unavailable", "lock", cron_dir=lock_dir)
+ _sched._sweep_mcp_orphans()
+ return None
+
+
+ def _advance_or_drop_recurring(_sched, due_jobs: list) -> list:
+ """Persist the recurring jobs' advance before any runs; when the store refuses it, drop them
+ (no durable advance -> a crash mid-run would re-fire them, so skipping is the at-most-once
+ side). One-shots still go through their own fire claim."""
+ try:
+ _sched.advance_next_runs([job["id"] for job in due_jobs])
+ return due_jobs
+ except OSError as exc:
+ skipped = [j for j in due_jobs if is_recurring(j)]
+ store_health.note_unwritable(exc, f"skipped {len(skipped)} recurring job(s)", "advance", skipped)
+ return [j for j in due_jobs if not is_recurring(j)]
+
+
def _tick_admitted(
- verbose: bool = True, adapters=None, loop=None, sync: bool = True, *, can_dispatch=None):
+ verbose: bool = True, adapters=None, loop=None, sync: bool = True, *, can_dispatch=None,
+ headless: bool = False):
"""Check and run all due jobs. File-locked so only one tick runs at a time (gateway ticker vs
standalone daemon / manual tick). ``can_dispatch``: optional gate; false leaves due jobs for the
- next allowed tick. Returns the number of jobs executed (0 if another tick holds the lock)."""
+ next allowed tick. ``headless``: the tick runs outside any gateway (system crontab, ``hermes
+ cron tick``) and must refuse agent jobs rather than spawn one. Returns the number of jobs
+ executed (0 if another tick holds the lock)."""
from cron import scheduler as _sched
# Stale-code yield gate — BEFORE the lock race. A process whose checkout was updated under it
diff --cc gateway/run_bootstrap.py
index 4d83cdf7729,00000000000..e6e9b03e896
mode 100644,000000..100644
--- a/gateway/run_bootstrap.py
+++ b/gateway/run_bootstrap.py
@@@ -1,785 -1,0 +1,778 @@@
+"""Process startup phases; diagnostics remain in the gateway facade."""
+from __future__ import annotations
+
+import threading
+from pathlib import Path
+from typing import Any, Optional
+
+from gateway.config import GatewayConfig
+
+async def _start_gateway_replace_existing_instance(existing_pid: int, replace: bool) -> bool:
+ """Handle a live gateway PID under this HERMES_HOME: replace it (``--replace``) or refuse.
+ Returns False when startup must abort (refused, permission denied, target still alive)."""
+ from gateway.run import (_clear_takeover_marker_quiet, _replace_target_belongs_to_other_profile, _wait_for_pid_exit, get_hermes_home, logger, suppress)
+ from gateway.status import get_process_start_time, remove_pid_file, terminate_pid
+ if not replace:
+ hermes_home = str(get_hermes_home())
+ logger.error(
+ "Another gateway instance is already running (PID %d, HERMES_HOME=%s) and did not "
+ "publish a host record this process could attach to.",
+ existing_pid, hermes_home)
+ print(
+ f"\n❌ A gateway already owns this host (PID {existing_pid}).\n"
+ f" One gateway per host serves every profile, so there is nothing to start here.\n"
+ f" Attach is impossible: PID {existing_pid} published no usable host record\n"
+ f" (an older build, or an unwritable lock directory).\n"
+ f" Take the host over: hermes gateway run --replace\n"
+ f" Or stop it first: hermes gateway stop\n")
+ return False
+
+ # Never signal a process not provably ours (a poisoned PID record → cross-profile restart loop).
+ if _replace_target_belongs_to_other_profile(existing_pid):
+ from gateway.status import _get_process_hermes_home
+ logger.error(
+ "Refusing --replace: PID %d cannot be proven to belong "
+ "to this profile's gateway (HERMES_HOME %s). Remove the "
+ "stale PID record or stop the owning profile explicitly.",
+ existing_pid, _get_process_hermes_home())
+ return False
+ existing_start_time = get_process_start_time(existing_pid)
+ logger.info("Replacing existing gateway instance (PID %d) with --replace.", existing_pid)
+ # Takeover marker: target exits 0 on our SIGTERM (exit 1 → systemd Restart=on-failure flap loop).
+ try:
+ from gateway.status import write_takeover_marker
+ write_takeover_marker(existing_pid)
+ except Exception as e:
+ logger.debug("Could not write takeover marker: %s", e)
+ # Snapshot children BEFORE signalling: reparented orphans are invisible yet hold scoped token locks.
+ try:
+ from gateway.status import _snapshot_gateway_children
+ _old_gateway_children = _snapshot_gateway_children(existing_pid)
+ except Exception:
+ _old_gateway_children = []
+ try:
+ terminate_pid(existing_pid, force=False)
+ except ProcessLookupError:
+ pass # Already gone
+ except (PermissionError, OSError):
+ logger.error("Permission denied killing PID %d. Cannot replace.", existing_pid)
+ _clear_takeover_marker_quiet()
+ return False
+ # Up to 10s for SIGTERM, then SIGKILL.
+ if not await _wait_for_pid_exit(existing_pid, 20, 0.5):
+ logger.warning("Old gateway (PID %d) did not exit after SIGTERM, sending SIGKILL.", existing_pid)
+ old_gateway_exited = False
+ try:
+ terminate_pid(existing_pid, force=True, expected_start_time=existing_start_time)
+ except ProcessLookupError:
+ old_gateway_exited = True
+ except (PermissionError, OSError):
+ pass
+ # Confirm SIGKILL took (D-state/zombie) before clearing PID/locks, or two gateways share a token.
+ if not old_gateway_exited and not await _wait_for_pid_exit(existing_pid, 20, 0.25):
+ logger.error(
+ "Old gateway (PID %d) still appears alive after SIGKILL; "
+ "aborting replacement to avoid a duplicate gateway.", existing_pid)
+ _clear_takeover_marker_quiet()
+ return False
+ # Reap orphaned children (POSIX; mirrors Windows taskkill /T) so they stop holding scoped token locks.
+ try:
+ from gateway.status import reap_gateway_children
+ reap_gateway_children(_old_gateway_children, parent_pid=existing_pid)
+ except Exception:
+ logger.debug("Child reap for replaced gateway PID %d failed", existing_pid, exc_info=True)
+ remove_pid_file()
+ # remove_pid_file() is a no-op when the PID doesn't match; force-unlink covers a crashed old process.
+ with suppress(Exception):
+ (get_hermes_home() / "gateway.pid").unlink(missing_ok=True)
+ # The old process may not have consumed the marker (SIGKILL'd before its handler read it).
+ _clear_takeover_marker_quiet()
+ # Stopped (Ctrl+Z) processes don't release scoped locks on exit; stale lock files block the new gateway.
+ try:
+ from gateway.status import release_all_scoped_locks
+ _released = release_all_scoped_locks(owner_pid=existing_pid, owner_start_time=existing_start_time)
+ if _released:
+ logger.info("Released %d stale scoped lock(s) from old gateway.", _released)
+ except Exception:
+ pass
+ return True
+
+
+def _start_gateway_configure_logging(verbosity: Optional[int]) -> None:
+ """Sync bundled skills, set up file logging + startup security audit, and the -v/-q stderr handler."""
+ from gateway.run import (_best_effort, _gateway_stderr_formatter, _hermes_home, logging)
+ def _sync_skills() -> None:
+ from tools.skills_sync import sync_skills
+ sync_skills(quiet=True)
+
+ _best_effort(_sync_skills)
+
+ # Centralized logging (agent.log INFO+, errors.log WARNING+, gateway.log gateway-only); idempotent.
+ from hermes_logging import setup_logging, _safe_stderr
+ setup_logging(hermes_home=_hermes_home, mode="gateway")
+
+ def _security_audit() -> None:
+ # Warn-on-load, never blocks: surfaces root / weak-SSH / unauthenticated-listener exposure.
+ from hermes_cli.security_audit_startup import log_startup_security_warnings
+
+ def _raw_cfg():
+ from hermes_cli.config import read_raw_config
+ return read_raw_config()
+
+ log_startup_security_warnings(hermes_home=_hermes_home, config=_best_effort(_raw_cfg))
+
+ _best_effort(_security_audit, "Startup security audit failed (non-fatal): %s")
+
+ # Optional stderr handler from -v/-q: None (quiet) = none; 0 = WARNING; 1 = INFO; 2+ = DEBUG.
+ if verbosity is not None:
+ _stderr_level = {0: logging.WARNING, 1: logging.INFO}.get(verbosity, logging.DEBUG)
+ _stderr_handler = logging.StreamHandler(_safe_stderr())
+ _stderr_handler.setLevel(_stderr_level)
+ _stderr_handler.setFormatter(_gateway_stderr_formatter())
+ root = logging.getLogger()
+ root.addHandler(_stderr_handler)
+ if _stderr_level < root.level: # so DEBUG records can reach the handler
+ root.setLevel(_stderr_level)
+
+
+def _start_gateway_make_shutdown_signal_handler(runner, _signal_initiated_shutdown: list):
+ """Build the SIGINT/SIGTERM handler; ``_signal_initiated_shutdown[0]`` records an unplanned signal."""
+ from gateway.run import (_best_effort, _hermes_home, asyncio, logger, signal)
+ planned_stop_seen = [False]
+
+ def shutdown_signal_handler(received_signal=None):
+ # Planned --replace takeover (sibling marked this PID): exit 0 so systemd won't revive us.
+ def _takeover() -> bool:
+ from gateway.status import consume_takeover_marker_for_self
+ return consume_takeover_marker_for_self()
+
+ # Planned stop: CLI marks first, else its SIGTERM looks like an external kill. SIGINT = Ctrl+C.
+ def _planned_stop() -> bool:
+ from gateway.status import consume_planned_stop_marker_for_self
+ return consume_planned_stop_marker_for_self()
+
+ # Fast (<10ms) sync snapshot: stdlib + /proc, no subprocesses (`ps aux` here once blocked ~3s).
+ def _snapshot():
+ from gateway.shutdown_forensics import snapshot_shutdown_context
+ return snapshot_shutdown_context(received_signal)
+
+ planned_takeover = bool(_best_effort(_takeover, "Takeover marker check failed: %s"))
+ planned_stop = received_signal == signal.SIGINT or (
+ not planned_takeover and bool(_best_effort(_planned_stop, "Planned stop marker check failed: %s")))
+ # `hermes gateway stop` writes the marker, THEN signals: the planned-stop watcher can consume
+ # the marker in between, and the CLI's own SIGTERM must not then read as an external kill.
+ if planned_stop:
+ planned_stop_seen[0] = True
+ elif planned_stop_seen[0] and not planned_takeover:
+ planned_stop = True
+ _shutdown_ctx = _best_effort(_snapshot, "snapshot_shutdown_context failed: %s")
+ sig_name = _shutdown_ctx["signal"] if _shutdown_ctx else None
+
+ if planned_takeover:
+ logger.info("Received %s as a planned --replace takeover — exiting cleanly", sig_name or "SIGTERM")
+ elif planned_stop:
+ logger.info("Received %s as a planned gateway stop — exiting cleanly", sig_name or "SIGTERM/SIGINT")
+ else:
+ # Mirrored onto the runner so _stop_impl suppresses the gateway_state=stopped persist for
+ # unexpected signals; operator stops take the `planned_stop` branch and leave it False (DO persist).
+ _signal_initiated_shutdown[0] = runner._signal_initiated_shutdown = True
+ logger.info("Received %s — initiating shutdown", sig_name or "SIGTERM/SIGINT")
+
+ if _shutdown_ctx is not None:
+ def _log_context() -> None:
+ # The most useful line for "gateway keeps dying" tickets.
+ from gateway.shutdown_forensics import format_context_for_log
+ logger.warning("Shutdown context: %s", format_context_for_log(_shutdown_ctx))
+
+ def _diagnostic() -> None:
+ # Heavyweight (ps auxf, pstree, dmesg), detached so it finishes even if our cgroup is torn
+ # down; bounded by an internal timeout, never blocks.
+ from gateway.shutdown_forensics import spawn_async_diagnostic
+ spawn_async_diagnostic(
+ _hermes_home / "logs" / "gateway-shutdown-diag.log", _shutdown_ctx["signal"], timeout_seconds=5.0)
+
+ _best_effort(_log_context, "format_context_for_log failed: %s")
+ _best_effort(_diagnostic, "spawn_async_diagnostic failed: %s")
+ if not planned_takeover:
+ # Supervisor/operator SIGNAL stop (bootout, kickstart -k, systemd, s6, bare kill) — the
+ # only kind launchd times with ExitTimeOut. In-band SIGUSR1 restarts never pass through
+ # here, and a sibling-driven --replace takeover is not launchd-timed either, so both
+ # keep the configured drain. _stop_impl uses this to cap the drain to the live budget.
+ runner._stop_requested_by_signal = True
+ asyncio.create_task(runner.stop())
+ return shutdown_signal_handler
+
+
+def _start_gateway_claim_pid_file(force: bool = False) -> bool:
+ """Claim the runtime lock + PID file (O_EXCL winner is the authoritative gateway). False = lost."""
+ from gateway.run import (_claim_host_gateway_role, logger, os)
+ import atexit
+ from gateway.status import (
+ acquire_gateway_runtime_lock, get_running_pid, release_gateway_runtime_lock,
+ remove_pid_file, write_pid_file)
+ _current_pid = get_running_pid()
+ if _current_pid is not None and _current_pid != os.getpid():
+ logger.error("Another gateway instance (PID %d) started during our startup. "
+ "Exiting to avoid double-running.", _current_pid)
+ return False
+ if not acquire_gateway_runtime_lock():
+ logger.error("Gateway runtime lock is already held by another instance. Exiting.")
+ return False
+ try:
+ write_pid_file()
+ except FileExistsError:
+ release_gateway_runtime_lock()
+ logger.error("PID file race lost to another gateway instance. Exiting.")
+ return False
+ atexit.register(remove_pid_file)
+ atexit.register(release_gateway_runtime_lock)
+ _claim_host_gateway_role(force=force)
+ return True
+
+
+async def _start_gateway_start_control_socket(runner):
+ """Start the gateway control socket (identify/status/pause-for-update); None when unavailable."""
+ from gateway.run import (asyncio, logger, os, threading)
+ import atexit
+ import concurrent.futures
+ _control_server = None
+ try:
+ # Started immediately after the PID-file claim: winning that O_EXCL race is the moment this process
+ # becomes the authoritative gateway for its HERMES_HOME, so from here on "does a socket answer?" is
+ # a truthful liveness/identity query for updater and fleet consumers. Strictly non-fatal: a bind
+ # failure only means consumers fall back to the process-scan/state-file layer, exactly as before
+ # this feature. See #92091.
+ from gateway.control_socket import GatewayControlServer, build_identify_payload
+ from gateway.run_profile_reconcile import (
+ migrate_profile_identity_verb, purge_profile_identity_verb,
+ unserve_profile_verb, serve_profile_verb,
+ )
+ from gateway.run_plugin_rewire import reload_plugins_verb
+ descriptor = runner.session_runtime_descriptor
+
+ def _identify_runtime():
+ payload = build_identify_payload()
+ payload.update({key: descriptor[key] for key in (
+ "instance_id", "runtime_protocol", "authority_epoch", "state", "api_origin",
+ "served_profiles", "parked_profiles", "capabilities") if key in descriptor})
+ if getattr(runner, '_draining', False):
+ payload.update(state='draining', capabilities=[])
+ payload["supervisor"] = {"manual": "none", "desktop": "none"}.get(
+ payload.get("supervisor"), payload.get("supervisor", "none"))
+ return payload
+ # pause-for-update: the updater asks us to drain + exit (freeing venv handles) vs. a tree-kill
+ # (same path as SIGUSR1). Handler runs on the socket executor thread, so marshal onto the loop.
+ # pause-for-update (#92091 step 2): the updater asks this gateway to drain in-flight turns and exit
+ # cleanly — releasing every venv file handle — instead of being tree-killed mid-turn. Same drain
+ # path as SIGUSR1/service restarts (request_restart(via_service=True)); the updater (or the service
+ # manager) relaunches after the code swap.
+ _main_loop = asyncio.get_running_loop()
+
+ def _pause_for_update_handler() -> dict:
+ try:
+ from hermes_cli.gateway import _get_restart_drain_timeout
+ _drain = float(_get_restart_drain_timeout())
+ except Exception:
+ _drain = 30.0
+ accepted_box: list[bool] = []
+ _done = threading.Event()
+
+ def _request() -> None:
+ try:
+ accepted_box.append(runner.request_restart(detached=False, via_service=True))
+ finally:
+ _done.set()
+
+ _main_loop.call_soon_threadsafe(_request)
+ _done.wait(timeout=5.0)
+ accepted = bool(accepted_box and accepted_box[0])
+ return {
+ "pausing": accepted, "already_stopping": not accepted,
+ "pid": os.getpid(), "drain_timeout": _drain}
+
+ def _rescan_profiles_handler() -> dict:
+ """``hermes profile create/delete`` asks the multiplexer to reconcile ``profiles/`` now
+ (the watcher also rescans periodically). Runs on the socket executor: marshal onto the loop
+ and wait briefly so the caller learns whether the profile is served."""
+ if not getattr(runner.config, "multiplex_profiles", False):
+ return {"multiplex": False, "served_profiles": runner.served_profile_names()}
+ future = asyncio.run_coroutine_threadsafe(
+ runner.reconcile_served_profiles(reason="control-socket"), _main_loop)
+ try:
+ # Bounded: a token-less create reconciles in milliseconds; a credential-add whose adapter
+ # connect outlasts this keeps running and the caller sees ``pending`` (not an error).
+ return {"multiplex": True, **future.result(timeout=5.0)}
+ except concurrent.futures.TimeoutError:
+ return {"multiplex": True, "pending": True, "served_profiles": runner.served_profile_names()}
+
+ _control_server = GatewayControlServer(
+ verb_handlers={"pause-for-update": _pause_for_update_handler, "identify": _identify_runtime,
+ "rescan-profiles": _rescan_profiles_handler,
+ "migrate-profile-identity": migrate_profile_identity_verb(runner),
+ "unserve-profile": unserve_profile_verb(runner),
+ "serve-profile": serve_profile_verb(runner),
+ "purge-profile-identity": purge_profile_identity_verb(runner),
+ # A plugin installed/enabled by another process loads now and re-wires the
+ # live adapters' handlers (#87770); tools/prompt still wait for the next session.
+ "reload-plugins": reload_plugins_verb(runner, _main_loop)})
+ _control_server.ticket_store = runner.session_ticket_store
+ if not await _control_server.start():
+ _control_server = None
+ else:
+ atexit.register(_control_server.cleanup_files)
+ # Hosted-room transports install onto this listener; bind it here so every launcher
+ # that starts the control socket (not only start_gateway) exposes it.
+ runner.session_control_server = _control_server
+ except Exception as _cs_exc:
+ logger.debug("Control socket startup failed (non-fatal): %s", _cs_exc)
+ _control_server = None
+ return _control_server
+
+
+def _start_gateway_start_cron_and_housekeeping(runner):
+ """Start the cron scheduler thread + gateway housekeeping thread; returns
+ ``(cron_stop, cron_provider, cron_thread, housekeeping_thread)``."""
+ from gateway.run import (Dict, Platform, _cron_profile_gate, _cron_tick_profile_homes, _start_gateway_housekeeping, asyncio, logger, threading)
+ # The event loop is passed so cron delivery can use live adapters (E2EE support).
+ from cron.scheduler_provider import (
+ InProcessCronScheduler, resolve_cron_scheduler, scheduler_for_profile_mode)
+ cron_stop = threading.Event()
+ # ONE gateway process per host multiplexes every profile, so its cron ticker owns EVERY
+ # profile's store — `gateway.multiplex_profiles` gates adapters, not cron. Gating the tick set
+ # on that flag left every non-launch profile's jobs in a store no ticker visited: they
+ # silently never fired.
+ try:
+ cron_profile_homes = _cron_tick_profile_homes(runner.config)
+ except Exception as exc:
+ logger.warning("Could not resolve profile homes for cron: %s", exc)
+ cron_profile_homes = []
+ # External providers own one unscoped remote registry, so they can only serve a single home.
+ cron_provider = scheduler_for_profile_mode(
+ resolve_cron_scheduler(), multiplex_profiles=len(cron_profile_homes) > 1)
+ cron_start_kwargs: Dict[str, Any] = {"adapters": runner.adapters, "loop": asyncio.get_running_loop()}
+
+ if isinstance(cron_provider, InProcessCronScheduler) and cron_profile_homes:
+ # Live enumerator: the ticker re-reads profiles/ every cycle so a profile created while
+ # the gateway runs gets its jobs fired without a restart (hot-serve).
+ cron_start_kwargs["profile_homes"] = lambda: _cron_tick_profile_homes(runner.config)
+ # Stand down, per tick, for a profile whose OWN gateway process ticks it.
+ cron_start_kwargs["profile_gate"] = _cron_profile_gate
+ # Per-profile adapters so each profile's cron output goes via its own bot, not the
+ # default's. Absent (no multiplexed adapters), delivery for a secondary profile falls
+ # back to the primary's routed adapters or fails closed — the job still FIRES.
+ cron_start_kwargs["profile_adapters"] = getattr(runner, "_profile_adapters", None)
+ # runner.adapters belongs to the LAUNCH profile (``default``, or the ``--profile``
+ # name); naming it keeps the ticker from routing a secondary's cron through that bot
+ # and lets a named multiplexer's own jobs reuse its live adapters.
+ cron_start_kwargs["default_profile"] = runner._primary_profile_name
+ logger.info(
+ "Cron scheduler will tick %d profile(s): %s", len(cron_profile_homes),
+ [p[0] if isinstance(p, tuple) else p for p in cron_profile_homes])
+
+ # Only the in-process ticker polls local due jobs, so only it gets the external-drain dispatch gate.
+ if isinstance(cron_provider, InProcessCronScheduler):
+ cron_start_kwargs["can_dispatch"] = lambda: not (
+ runner._draining or runner._external_drain_active)
+ # Supervised: a ticker that dies without a stop request is respawned by housekeeping (#111010).
+ from cron.scheduler_thread import SupervisedTickerThread
+ cron_thread = SupervisedTickerThread(
+ cron_provider.start, args=(cron_stop,), kwargs=cron_start_kwargs, stop_event=cron_stop)
+ from gateway.runtime_ownership import process_ownership
+ process_ownership.start_writer(cron_thread)
+
+ # External providers fire over loopback HTTP to THIS process's api_server; if it never came up (usually
+ # API_SERVER_KEY missing) every fire fails while manual runs work — misread as a job bug. Say it ONCE.
+ if not isinstance(cron_provider, InProcessCronScheduler):
+ try:
+ _has_api_server = Platform.API_SERVER in (runner.adapters or {})
+ except Exception:
+ _has_api_server = True # never let the tell break startup
+ if not _has_api_server:
+ logger.warning(
+ "Cron provider '%s' is active but the api_server adapter is "
+ "NOT running in this gateway — scheduled fires arrive over "
+ "loopback HTTP and will all fail (jobs only run when "
+ "triggered manually). Most common cause: API_SERVER_KEY is "
+ "missing from this gateway process's environment. Restart "
+ "the gateway through its supervisor (`hermes gateway "
+ "restart`) so the profile env loads.",
+ getattr(cron_provider, "name", "external"))
+
+ # Gateway-only housekeeping runs independently of the cron provider; shares cron_stop for shutdown.
+ housekeeping_thread = threading.Thread(
+ target=_start_gateway_housekeeping, args=(cron_stop,),
+ kwargs={"adapters": runner.adapters, "loop": asyncio.get_running_loop(),
+ "cron_provider": cron_provider, "runner": runner, "cron_thread": cron_thread},
+ daemon=True, name="gateway-housekeeping")
+ process_ownership.start_writer(housekeeping_thread)
+ return cron_stop, cron_provider, cron_thread, housekeeping_thread
+
+
+async def _start_gateway_shutdown_tail(
+ runner, _control_server, cron_stop: threading.Event, cron_provider,
+ cron_thread: Any, housekeeping_thread: threading.Thread,
+ _planned_stop_watcher_stop: threading.Event, _planned_stop_watcher_thread: threading.Thread,
+ _signal_initiated_shutdown: list) -> bool:
+ """Post-``wait_for_shutdown`` teardown; returns the process exit verdict (True = exit 0)."""
+ from gateway.run import (_CRON_SHUTDOWN_DRAIN_TIMEOUT, _HOUSEKEEPING_SHUTDOWN_DRAIN_TIMEOUT, _await_thread_exit, _best_effort, _resolve_gateway_exit_verdict, _shutdown_mcp_servers_nonblocking, _stop_cron_provider, logger, suppress)
+ # Control socket first: once shutdown begins we are no longer a truthful "serving here" answer and a
+ # successor must be able to bind. Early-exit paths rely on the atexit cleanup_files hook instead.
+ if _control_server is not None:
+ try:
+ await _control_server.stop()
+ except Exception:
+ logger.debug("Control socket stop failed (non-fatal)", exc_info=True)
+
+ def _stop_keepalive() -> None:
+ from hermes_cli.nous_auth_keepalive import stop_nous_auth_keepalive
+ stop_nous_auth_keepalive()
+
+ _best_effort(_stop_keepalive)
+
+ # Never join(): an in-flight cron delivery is a coroutine on THIS loop; a sync join would drop it.
+ # Stop cron scheduler + housekeeping cleanly. These MUST be awaited cooperatively, not join()ed. A cron
+ # delivery in flight when the gateway restarts is a coroutine scheduled onto THIS event loop
+ # (safe_schedule_threadsafe); the ticker thread is blocked on its future.result(). A synchronous
+ # cron_thread.join() would block the loop, so that delivery could never run — it timed out and the
+ # message was silently dropped (#58818). Awaiting keeps the loop alive so the in-flight delivery
+ # finishes before we tear down.
+ cron_stop.set()
+ _stop_cron_provider(cron_provider)
+ if not await _await_thread_exit(cron_thread, timeout=_CRON_SHUTDOWN_DRAIN_TIMEOUT):
+ logger.warning("Cron ticker did not exit within %.0fs of shutdown — an in-flight "
+ "delivery may have been dropped.", _CRON_SHUTDOWN_DRAIN_TIMEOUT)
+ await _await_thread_exit(housekeeping_thread, timeout=_HOUSEKEEPING_SHUTDOWN_DRAIN_TIMEOUT)
+
+ # Stop the planned-stop watcher (daemon=True so this is belt-and-suspenders).
+ _planned_stop_watcher_stop.set()
+ _planned_stop_watcher_thread.join(timeout=2)
+
+ # Never suppressed: a raise here is a real teardown failure (it once hid a changed signature,
+ # leaving every MCP connection and the shared loop up while the gateway reported a clean exit).
+ try:
+ await _shutdown_mcp_servers_nonblocking(config=getattr(runner, "config", None))
+ except Exception:
+ logger.warning("MCP shutdown failed; connections may be left open", exc_info=True)
+
+ # The failure verdict comes AFTER the cooperative teardown: returning early here leaked the
+ # cron ticker + housekeeping threads (and open MCP connections) for embedded callers (#12175).
+ return _resolve_gateway_exit_verdict(runner, _signal_initiated_shutdown[0])
+
+
+
+def _launch_home_may_multiplex(config=None) -> bool:
+ """A named profile serving ``default`` as a secondary splits default's local sessions between
+ the two stores (routing rows follow the launch home, receipts follow the authority), so the
+ multiplexer is the default profile's job.
+
+ An EXPLICIT ``gateway.multiplex_profiles: true`` (config.yaml or ``GATEWAY_MULTIPLEX_PROFILES``)
+ on a named launch home exits EX_CONFIG: a config verdict, never a retry. The implicit default
+ (unset key, or the retired ``false`` that ``resolve_multiplex_mode`` settles like unset) is not
+ the operator's choice, so it is downgraded the way every other implicit-multiplex blocker is:
+ this process comes up standalone, says why, and *config* is flipped in place so the boot below
+ reserves and serves only the launch profile."""
+ from hermes_constants import profile_name_for_home
+ from gateway.run import get_hermes_home, logger
+ name = profile_name_for_home(get_hermes_home())
+ if name in (None, "default"):
+ return True
+ from hermes_cli.gateway_multiplex_mode import explicit_multiplex_flag
+ if config is not None and not explicit_multiplex_flag(get_hermes_home()):
+ from hermes_cli.gateway_multiplex_mode import MultiplexDecision, log_multiplex_decision
+ decision = MultiplexDecision(
+ False, "guard",
+ f"profile {name!r} launched the gateway, and only the default profile runs the multiplexer "
+ "(start it with `hermes gateway run` from the default profile to serve every profile)")
+ config.multiplex_profiles = False
+ log_multiplex_decision(decision)
+ return True
+ from gateway.restart import GATEWAY_FATAL_CONFIG_EXIT_CODE
+ from gateway.run import _write_runtime_status_quiet
+ logger.error(
+ "gateway.multiplex_profiles is set on profile %r, but only the default profile can run the "
+ "multiplexer. Unset the flag in this profile's config.yaml, or start the gateway from the "
+ "default profile (`hermes gateway run`), which serves this profile too.", name)
+ _write_runtime_status_quiet(gateway_state="startup_failed", exit_reason="multiplex_requires_default_profile")
+ raise SystemExit(GATEWAY_FATAL_CONFIG_EXIT_CODE)
+
+
+async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool = False,
+ verbosity: Optional[int] = 0, force: bool = False) -> bool:
+ """Start the gateway and run until interrupted; False if it failed to start (non-zero exit so
+ systemd can auto-restart). ``replace`` kills any existing instance first (avoids restart-loop
+ deadlocks); ``force`` starts without consulting the host owner at all."""
+ from gateway.cwd_placeholder import CWD_PLACEHOLDERS, resolve_placeholder_terminal_cwd
+ from gateway.run import (
+ GatewayRunner,
+ _best_effort,
+ _discover_gateway_mcp_tools,
+ _enable_multiplex_log_routing,
+ _ensure_windows_gateway_venv_imports,
+ _gateway_loop_exception_handler,
+ _host_attach_or_none,
+ _log_standalone_profiles_at_boot,
+ _multiplex_profile_homes,
- _recover_pending_flushes,
+ _refresh_host_gateway_record,
+ _resolve_gateway_exit_verdict,
+ _run_planned_stop_watcher,
+ _shutdown_gateway_health_export,
+ _shutdown_mcp_servers_nonblocking,
+ _start_gateway_make_restart_signal_handler,
+ asyncio,
+ get_hermes_home,
+ load_gateway_config_for_runner,
+ logger,
+ os,
+ signal,
+ suppress,
+ threading,
+ )
+ # Set here (not at import) so incidental gateway.run imports from CLI code don't poison it.
+ os.environ["HERMES_EXEC_ASK"] = "1"
+
+ # Messaging-only defaults belong to startup, not incidental imports by the TUI.
+ configured_cwd = os.environ.get("TERMINAL_CWD", "")
+ if not configured_cwd or configured_cwd in CWD_PLACEHOLDERS:
+ resolved_cwd = resolve_placeholder_terminal_cwd(
+ configured_cwd=configured_cwd,
+ terminal_backend=os.environ.get("TERMINAL_ENV", ""),
+ messaging_cwd=os.getenv("MESSAGING_CWD"),
+ docker_mount_cwd_to_workspace=os.getenv(
+ "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE", "false").lower()
+ in {"true", "1", "yes"},
+ home_fallback=str(Path.home()))
+ if resolved_cwd is None:
+ os.environ.pop("TERMINAL_CWD", None)
+ else:
+ os.environ["TERMINAL_CWD"] = resolved_cwd
+
+ from hermes_cli.resource_limits import apply_nofile_soft_limit
+ apply_nofile_soft_limit()
+
+ # Snapshot the revision while sys.modules matches disk so a later `git pull` is detected safely.
+ from gateway.code_skew import record_boot_fingerprint
+ record_boot_fingerprint()
+
+ # Config verdicts come before the duplicate-instance guard: `--replace` must not stop a healthy
+ # gateway for a launch that cannot start.
+ resolved_config = config if config is not None else load_gateway_config_for_runner()
+ profile_homes = (_multiplex_profile_homes(resolved_config)
+ if getattr(resolved_config, 'multiplex_profiles', False) else [])
+ if profile_homes and not _launch_home_may_multiplex(resolved_config):
+ return False
+ if profile_homes and not getattr(resolved_config, 'multiplex_profiles', False):
+ profile_homes = [] # implicit default downgraded: this named launch serves only itself
+
+ # Multiplex-only: the ONE host gateway decides first. Attach to it, make it serve this profile,
+ # replace it (--replace) or refuse — before anything below binds a port or claims a PID file.
+ _host_decision = await _host_attach_or_none(replace, force)
+ if _host_decision is not None:
+ return _host_decision
+
+ # Duplicate-instance guard scoped to HERMES_HOME (the host record is absent or unusable here).
+ from gateway.status import get_running_pid
+ existing_pid = get_running_pid()
+ if (existing_pid is not None and existing_pid != os.getpid()
+ and not await _start_gateway_replace_existing_instance(existing_pid, replace)):
+ return False
+
+ from gateway.runtime_ownership import process_ownership, OwnershipConflict
+ from gateway.status import remove_pid_file, release_gateway_runtime_lock
+ try:
+ process_ownership.reserve([get_hermes_home(), *(home for _, home in profile_homes)])
+ except OwnershipConflict as exc:
+ logger.error("Cannot reserve gateway profiles: %s", exc)
+ # A named profile that the LIVE default multiplexer already serves is a configuration
+ # verdict (gateway.multiplex_profiles), not a transient fault: exit EX_CONFIG so systemd's
+ # RestartPreventExitStatus=78 parks the unit instead of restart-looping (#51228, #97120).
+ # Any other same-user contender keeps the ordinary "already running" exit 1.
+ from hermes_cli.gateway import named_profile_served_by_running_multiplexer
+ if named_profile_served_by_running_multiplexer():
+ from gateway.restart import GATEWAY_FATAL_CONFIG_EXIT_CODE
+ from gateway.run import _write_runtime_status_quiet
+ logger.error(
+ "The default gateway is running as a profile multiplexer and already serves this profile. "
+ "Manage it with `hermes gateway restart` from the default profile instead of starting a "
+ "second gateway for the profile.")
+ _write_runtime_status_quiet(gateway_state="startup_failed", exit_reason=str(exc))
+ raise SystemExit(GATEWAY_FATAL_CONFIG_EXIT_CODE)
+ return False
+ except OSError as exc:
+ logger.error("Cannot reserve gateway profiles: %s", exc)
+ return False
+ # Freeze discovery: later profile additions must restart and reserve before opening stores.
+ if profile_homes:
+ resolved_config._runtime_profile_homes = tuple(profile_homes)
+ # PID file BEFORE adapters: of two concurrent `run --replace`, only the O_EXCL winner opens sockets.
+ # Only --force skips the host-lock refusal. Every generated unit carries --replace, so reading it as
+ # --force there disabled the one arbiter of the two-units-at-once race; a replace that took the
+ # owner over already freed the lock with that process.
+ if not _start_gateway_claim_pid_file(force=force):
+ release_gateway_runtime_lock()
+ return False
+
+ _control_server = None
+ runner = None
+ _planned_stop_watcher_stop = None
+ try:
+ _start_gateway_configure_logging(verbosity)
+
+ from gateway.run_startup import recover_left_core_at_gateway_start
+ await asyncio.to_thread(recover_left_core_at_gateway_start) # before the runner loads platform config
+
+ runner = GatewayRunner(resolved_config)
+ from gateway.run_runtime import initialize_gateway_runtime
+ await initialize_gateway_runtime(runner)
+ # Multiplex: swap the launch-home file handlers for per-profile routers so each profile's records
+ # land in its own logs/. Must run after the runner resolved (possibly None) config and setup_logging.
+ # See #82936.
+ _enable_multiplex_log_routing(runner.config)
+ # ``--replace`` is explicit startup authority, not a durable reconnect policy: GatewayRunner scopes
+ # it to cold adapter connects and clears it before the background reconnect watcher starts.
+ runner._platform_lock_takeover_on_start = bool(replace)
+
+ # Unexpected signals exit non-zero so service managers revive us; planned stops write a marker first.
+ _signal_initiated_shutdown = [False]
+
+ shutdown_signal_handler = _start_gateway_make_shutdown_signal_handler(
+ runner, _signal_initiated_shutdown)
+
+ restart_signal_handler = _start_gateway_make_restart_signal_handler(runner)
+
+ loop = asyncio.get_running_loop()
+
+ # Swallow transient network errors from background tasks; one unhandled httpx error would kill us.
+ # Issues #31066 / #31110: an unhandled ``telegram.error.TimedOut`` (or peer NetworkError / httpx
+ # connection error) in any awaited coroutine would propagate to the loop and kill the gateway process,
+ # taking down every profile attached to the same runner. systemd then restarts the service after ~5s but
+ # the active conversation turn is lost. The fix is intentionally narrow: only well-known transient
+ # network errors are swallowed (and logged with full traceback so the originating call site is still
+ # discoverable). Anything else is forwarded to the default handler so real bugs still surface.
+ loop.set_exception_handler(_gateway_loop_exception_handler)
+
+ if threading.current_thread() is threading.main_thread():
+ # add_signal_handler raises NotImplementedError on Windows; SIGUSR1 is POSIX-only.
+ handlers = [(sig, shutdown_signal_handler, (sig,)) for sig in (signal.SIGINT, signal.SIGTERM)]
+ if hasattr(signal, "SIGUSR1"):
+ handlers.append((signal.SIGUSR1, restart_signal_handler, ())) # windows-footgun: ok — hasattr-guarded
+ for sig, handler, args in handlers:
+ with suppress(NotImplementedError):
+ loop.add_signal_handler(sig, handler, *args) # windows-footgun: ok — suppress(NotImplementedError)
+ else:
+ logger.info("Skipping signal handlers (not running in main thread).")
+
+ # Windows has no add_signal_handler, so `hermes gateway stop`'s SIGTERM would never drain; poll the
+ # planned-stop marker (written BEFORE the kill) instead. Runs everywhere so masked-SIGTERM drains.
+ # Windows fallback: asyncio.add_signal_handler raises NotImplementedError on Windows, so `hermes gateway
+ # stop`'s SIGTERM (which Python maps to TerminateProcess on Windows) never invokes
+ # shutdown_signal_handler. That means the drain loop never runs, mark_resume_pending never fires, and
+ # sessions are silently lost across restarts (issue #33778). The fix is a marker-polling thread: `hermes
+ # gateway stop` writes the planned-stop marker BEFORE killing, and this thread notices it and drives the
+ # same shutdown path the signal handler would have. Runs on every platform (cheap, defensive) so
+ # non-signal-bearing environments (Windows native, sandboxed CI runners that mask SIGTERM) still get a
+ # clean drain.
+ _planned_stop_watcher_stop = threading.Event()
+ _planned_stop_watcher_thread = threading.Thread(
+ target=_run_planned_stop_watcher,
+ args=(_planned_stop_watcher_stop, runner, loop, shutdown_signal_handler), daemon=True,
+ name="planned-stop-watcher")
+ _planned_stop_watcher_thread.start()
+
+ # Right after the PID claim (which makes us authoritative); non-fatal — consumers fall back to scan.
+ _control_server = await _start_gateway_start_control_socket(runner)
+ if _control_server is None:
+ raise RuntimeError("gateway session bootstrap control listener unavailable")
+ # Now the attach channel answers: republish the host record with the settled served set.
+ _refresh_host_gateway_record(runner)
+ _log_standalone_profiles_at_boot(runner)
+ from gateway.run_runtime import start_gateway_runtime_api
+ await start_gateway_runtime_api(runner)
+
+ def _lifecycle_record_startup() -> None:
+ # Report if the previous life died uncleanly (SIGKILL / OOM / VM death), then claim the
+ # sentinel for this life. After the PID-file claim so a --replace loser can't clobber it.
+ from gateway.lifecycle_ledger import record_startup
+ record_startup()
+
+ def _start_keepalive() -> None:
+ from hermes_cli.nous_auth_keepalive import start_nous_auth_keepalive
+ start_nous_auth_keepalive()
+
+ _best_effort(_lifecycle_record_startup, "Lifecycle ledger startup record failed: %s")
+ _best_effort(_start_keepalive, "Nous auth keepalive did not start: %s")
+ _ensure_windows_gateway_venv_imports()
+
+ # discover_mcp_tools() blocks up to 120s; on the loop thread it would freeze platform heartbeats.
+ try:
+ # MCP tool discovery — run in an executor so the asyncio event loop stays responsive even when a
+ # configured MCP server is slow or unreachable. discover_mcp_tools() uses a blocking 120s wait
+ # internally; calling it from the loop thread would freeze platform heartbeats (Discord shard,
+ # Telegram polling) until it returned. See #16856.
+ await _discover_gateway_mcp_tools(runner.config)
+ except Exception as e:
+ logger.debug("MCP tool discovery failed: %s", e)
+
+ try:
+ success = await runner.start()
+ except BaseException:
+ _shutdown_gateway_health_export(runner)
+ raise
+ if not success:
+ _shutdown_gateway_health_export(runner)
+ return False
+
- def _recover_pending() -> None:
- recovered = _recover_pending_flushes(runner)
- if recovered:
- logger.info("Recovered %d pending message(s) from shutdown flush", recovered)
-
- _best_effort(_recover_pending)
+ if runner.should_exit_cleanly:
+ _shutdown_gateway_health_export(runner)
+ if runner.exit_reason:
+ logger.error("Gateway exiting cleanly: %s", runner.exit_reason)
+ # Explicit exit codes (GATEWAY_FATAL_CONFIG_EXIT_CODE) must propagate so s6 finish maps 78 → 125.
+ if runner.exit_code is not None:
+ raise SystemExit(runner.exit_code)
+ return True
+ if not runner._running:
+ # Startup aborted by restart/shutdown before running mode; preserve that path without starting cron.
+ try:
+ await runner.wait_for_shutdown()
+ try:
+ await _shutdown_mcp_servers_nonblocking(config=getattr(runner, "config", None))
+ except Exception:
+ logger.warning("MCP shutdown failed; connections may be left open", exc_info=True)
+ return _resolve_gateway_exit_verdict(runner, _signal_initiated_shutdown[0])
+ finally:
+ _shutdown_gateway_health_export(runner)
+
+ cron_stop, cron_provider, cron_thread, housekeeping_thread = (
+ _start_gateway_start_cron_and_housekeeping(runner))
+
+ # READY only once adapters, cron and housekeeping run; missing systemd state just disables watchdog.
+ from gateway.run_runtime import publish_gateway_runtime_ready
+ publish_gateway_runtime_ready(runner)
+ runner._start_systemd_watchdog()
+
+ from gateway.run_runtime import wait_gateway_runtime
+ try:
+ await wait_gateway_runtime(runner)
+ finally:
+ try:
+ await runner.stop()
+ finally:
+ verdict = await _start_gateway_shutdown_tail(
+ runner, _control_server, cron_stop, cron_provider, cron_thread, housekeeping_thread,
+ _planned_stop_watcher_stop, _planned_stop_watcher_thread, _signal_initiated_shutdown)
+ return verdict
+
+ finally:
+ try:
+ if runner is not None:
+ from gateway.run_runtime import drain_gateway_runtime
+ await drain_gateway_runtime(runner)
+ # Startup may have opened adapters before an exception. The same
+ # stop path owns their writers and DB handles on every exit.
+ await runner.stop()
+ finally:
+ if _planned_stop_watcher_stop is not None:
+ _planned_stop_watcher_stop.set()
+ if _control_server is not None:
+ await _control_server.stop()
+ remove_pid_file()
+ release_gateway_runtime_lock()
diff --cc gateway/run_runtime_init.py
index 56835ef1e2c,00000000000..b253aca4661
mode 100644,000000..100644
--- a/gateway/run_runtime_init.py
+++ b/gateway/run_runtime_init.py
@@@ -1,266 -1,0 +1,233 @@@
+"""Writable runner initialization, separate from process ownership."""
+from __future__ import annotations
+
+class GatewayRuntimeInitMixin:
+ def _init_runtime_settings(self) -> None:
+ """Load ephemeral per-call config (prefill, reasoning, busy modes, timeouts, routing)."""
+ from gateway.run import (Dict, Optional, _load_gateway_config)
+ self._prefill_messages = self._load_prefill_messages()
+ self._reasoning_config = self._load_reasoning_config()
+ self._service_tier = self._load_service_tier()
+ self._show_reasoning = self._load_show_reasoning()
+ self._busy_input_mode = self._load_busy_input_mode()
+ self._busy_text_mode = self._load_busy_text_mode()
+ # Secondary-profile busy modes snapshotted at multiplex startup; handlers never reread config.
+ self._busy_input_modes_by_profile: Dict[str, str] = {}
+ self._busy_text_modes_by_profile: Dict[str, str] = {}
+ self._busy_text_timing = self._busy_text_timing_from_config(_load_gateway_config())
+ self._busy_text_timing_by_profile: Dict[str, tuple[float, float]] = {}
+ self._human_delay = self._human_delay_from_config(_load_gateway_config())
+ self._human_delay_by_profile: Dict[str, Optional[tuple[int, int]]] = {}
+ self._restart_drain_timeout = self._load_restart_drain_timeout()
+ # Live launchd ``ExitTimeOut`` for this job (None when not launchd-owned). Read once at
+ # boot — launchd fixes it at load — and applied only to signal-driven stops, which are the
+ # only stops launchd times. See _load_launchd_exit_timeout().
+ self._stop_requested_by_signal = False
+ self._launchd_exit_timeout_s = self._load_launchd_exit_timeout(self._restart_drain_timeout)
+ self._restart_after_turn_timeout = self._load_restart_after_turn_timeout()
+ self._cron_drain_timeout = self._load_cron_drain_timeout()
+ self._signal_interrupt_grace_timeout = self._load_signal_interrupt_grace_timeout()
+ self._provider_routing = self._load_provider_routing()
+ self._fallback_model = self._load_fallback_model()
+
+ def _init_session_store(self) -> None:
+ """Build the SessionStore (with process-registry reset guard), its async facade and the router."""
+ from gateway.run import (AsyncSessionStore, DeliveryRouter, SessionStore)
+ from tools.process_registry import process_registry
+ self.session_store = SessionStore(
+ self.config.sessions_dir, self.config,
+ has_active_processes_fn=lambda key: process_registry.has_active_for_session(
+ key))
+ # Loop-side boundary: sync helpers use ``session_store`` directly; async handlers await this facade.
+ self._async_session_store = AsyncSessionStore(self.session_store)
+ self.delivery_router = DeliveryRouter(self.config)
+
+ def _init_lifecycle_state(self) -> None:
+ """Initialise run/exit/restart flags, per-session state, and completion-delivery bookkeeping."""
+ from gateway.run import (Dict, List, MessageEvent, Optional, OrderedDict, Platform, SessionSource, SessionState, SessionTurnLeaseRegistry, asyncio, concurrent, threading, time)
+ self._running = self._exit_cleanly = self._exit_with_failure = self._draining = False
+ self._gateway_loop: Optional[asyncio.AbstractEventLoop] = None
+ self._shutdown_event = asyncio.Event()
+ self._exit_reason: Optional[str] = None
+ self._exit_code: Optional[int] = None
+ self._profile_failed_platforms: Dict[str, Dict[Platform, asyncio.Task]] = {}
+ self._systemd_watchdog = None
+ # External (NAS-driven) drain, distinct from one-way ``_draining``: set while ``.drain_request.json``
+ # exists — NEW turns refused, process stays up, removing the marker reverts to ``running``.
+ self._external_drain_active = False
+ # ``_signal_initiated_shutdown``: SIGTERM/SIGINT with no planned-stop/takeover marker (container,
+ # OOM, bare kill); _stop_impl must NOT persist gateway_state=stopped or container_boot won't restart.
+ self._restart_requested = self._signal_initiated_shutdown = self._restart_task_started = False
+ self._restart_detached = self._restart_via_service = self._detached_restart_helper_started = False
+ self._restart_command_source: Optional[SessionSource] = None
+ # Construction clock: bounds the /restart redelivery guard's window (missing dedup marker = stale).
+ self._startup_time: float = time.time()
+ # True when booted from a chat /restart (.restart_notify.json existed). One-shot signal so the
+ # marker-missing fallback suppresses a /restart only when we KNOW we just restarted.
+ self._booted_from_restart: bool = False
+ self._stop_task: Optional[asyncio.Task] = None
+ self._restart_task: Optional[asyncio.Task] = None
+ self._executor_lock = threading.Lock()
+ self._executor: Optional[concurrent.futures.ThreadPoolExecutor] = None
+ # Best-effort session housekeeping runs on its OWN pool; see _run_housekeeping_in_executor.
+ self._housekeeping_executor: Optional[concurrent.futures.ThreadPoolExecutor] = None
+ # Set on gateway stop so the recreate-on-shutdown path can't resurrect the pool.
+ self._executor_closing = False
+ # ALL per-session state lives here (gateway/session_state.py); use _session_state / _peek_session_state.
+ self._sessions: Dict[str, SessionState] = {}
+ # Per-SESSION_ID turn lease: serializes [load history → run → flush] when two ROUTING KEYS resolve
+ # to one session_id (switch_session's many-to-one mapping), which routing-key guards cannot see.
+ self._turn_leases = SessionTurnLeaseRegistry()
+ # Stall-notified keys clear when pending clears / activity resumes / conversation boundary.
+ # Held turn-lease tokens live on SessionState.turn.lease_tokens keyed by run generation, so a
+ # stale unwind can never free a newer turn's lease (#28686). Runner-level queued interrupt text lives on
+ # SessionState.persistent.pending_command_text (NOTE: distinct from the adapter-level
+ # _pending_messages Dict[str, MessageEvent] in gateway/platforms/base.py, which shares the legacy
+ # name). Last successfully-resolved (non-empty) model, keyed by session. Used as a fallback when a
+ # fresh config read transiently returns an empty model (e.g. an mtime-keyed config-cache miss during
+ # a post-interrupt recovery turn). Without this, the agent is built with model="" and every API call
+ # fails HTTP 400 "No models provided" — the session goes silent until the user manually re-sends.
+ # See #35314. The ``"*"`` session entry holds a process-wide last-known-good for sessions seen for
+ # the first time. Lives on SessionState.conversation.last_resolved_model. Overflow buffer for
+ # explicit /queue commands. The adapter-level _pending_messages dict is a single slot per session
+ # (designed for "next-turn" follow-ups where repeated sends collapse into one event). /queue has
+ # different semantics: each invocation must produce its own full agent turn, in FIFO order, with no
+ # merging. When the slot is occupied, additional /queue items land here and are promoted
+ # one-at-a-time after each run's drain. Cleared on /new and /reset. /model and other mid-session
+ # operations preserve the queue. Lives on SessionState.conversation.queued_events; native image
+ # paths, busy-ack debounce timestamps and the monotonic run-generation counter (#28686, NEVER reset)
+ # live on SessionState too. See gateway.session_stall.
+ self._session_stall_notified: Dict[str, bool] = {}
+ # Consecutive "persisted transcript lagged live cached history" turns per session key; see
+ # run_turn_runner._load_turn_history (#114266). Cleared on /new.
+ self._transcript_lag_streaks: Dict[str, int] = {}
+ # Startup restore gate: while restart-interrupted sessions auto-resume, real inbound messages
+ # queue instead of competing with the synthetic resume turns; drained after all resume tasks end.
+ self._startup_restore_in_progress = False
+ self._startup_restore_queue: List[MessageEvent] = []
+ self._startup_restore_tasks: List[asyncio.Task] = []
+ # Set by start_gateway() only for an explicit ``--replace`` launch; scoped to each adapter's
+ # cold-start connect and removed before any reconnect can run.
+ self._platform_lock_takeover_on_start = False
+ # Capped LRU of live SessionSources for fallback routing (shutdown notices, synthetic events) when
+ # the persisted origin is missing and _parse_session_key can't recover thread_id.
+ self._session_sources: "OrderedDict[str, SessionSource]" = OrderedDict()
+ self._session_sources_max = 512
+ # Lifecycle-scoped completion dedup: closes queue/watcher races inside one gateway without claiming
+ # exactly-once across a crash; durable replay state stays owned by tools.async_delegation.
+ self._completion_delivery_lock = threading.Lock()
+ self._completion_deliveries_inflight: set[tuple[str, str, object]] = set()
+ self._completion_deliveries_delivered: "OrderedDict[tuple[str, str, object], None]" = OrderedDict()
+ self._completion_delivery_retention = 2048
+ # Agent-triggered terminal completions from one conversation often land in the same scheduler
+ # tick; hold them briefly so the agent gets one synthetic turn instead of one per process.
+ # See #70300.
+ self._completion_notification_batches: dict[tuple[str, ...], list[tuple[str, dict, asyncio.Future]]] = {}
+ self._completion_notification_batch_tasks: dict[tuple[str, ...], asyncio.Task] = {}
+ self._completion_notification_batch_flush_tasks: set[asyncio.Task] = set()
+ self._completion_notification_batch_window = 0.1
+ self._completion_notification_batches_stopping = False
+
+ def _init_runtime_caches(self) -> None:
+ """Agent cache, profile identity, Teams runtime, failed-platform tracking, slash-confirm counter."""
+ from gateway.run import (Any, Dict, Optional, OrderedDict, Platform, threading)
+ # AIAgent per session preserves prompt caching (fresh agent per message ~10x cost on Anthropic).
+ # Value: (AIAgent, config_signature); LRU cap in _enforce_agent_cache_cap, TTL in expiry watcher.
+ self._agent_cache: "OrderedDict[str, tuple]" = OrderedDict()
+ self._agent_cache_lock = threading.Lock()
+ # Launch-time identity of the profile that owns ``self.adapters``; ``_authorization_adapter``
+ # compares against this rather than the per-turn ``_active_profile_name()``. A multiplex
+ # host's primary map is always the default profile, even when a named profile launched
+ # the process (that launcher is a secondary adapter owner).
+ launch = self._active_profile_name()
+ self._kanban_notifier_profile = launch
+ self._primary_profile_name = (
+ "default" if getattr(self.config, "multiplex_profiles", False) else launch
+ )
+ # Teams meeting pipeline runtime (bound later when msgraph_webhook adapter exists).
+ self._teams_pipeline_runtime = None
+ self._teams_pipeline_runtime_error: Optional[str] = None
+ # Failed-to-connect platforms for background reconnection: Platform -> {config, attempts, next_retry}
+ self._failed_platforms: Dict[Platform, Dict[str, Any]] = {}
+ # Strong refs to detached fatal-error handler tasks so the loop can't GC them mid-run.
+ self._fatal_handler_tasks: set = set()
+ # Slash-confirm state lives in tools.slash_confirm (module-level) so adapters resolve callbacks
+ # without a runner backref; local counter keeps confirm_ids compact (64-byte callback_data caps).
+ import itertools
+ self._slash_confirm_counter = itertools.count(1)
+
- def _init_startup_checks(self) -> None:
- """Ensure tirith is installed and warn when manual approvals have no automated assessor."""
- from gateway.run import (_best_effort, cfg_get, logger)
- def _ensure_tirith() -> None:
- from tools.tirith_security import ensure_installed
- ensure_installed(log_failures=False) # downloads if needed; fail-open at scan time
-
- _best_effort(_ensure_tirith)
-
- # Manual approvals with no automated assessor (tirith off AND no auxiliary.approval) fail closed
- # on unattended gateways — surface it so operators knowingly enable one.
- try:
- from hermes_cli.config import load_config as _load_full_config
- # Startup heads-up (#30882): a gateway in manual approval mode with no automated risk assessor
- # (tirith disabled AND no auxiliary.approval model) can only gate dangerous commands /
- # execute_code scripts via live in-chat approval.
- _appr_cfg = _load_full_config()
- _appr_mode = str(
- cfg_get(_appr_cfg, "approvals", "mode", default="manual") or "manual"
- ).strip().lower()
- _tirith_on = bool(cfg_get(_appr_cfg, "security", "tirith_enabled", default=True))
- _aux_approval = cfg_get(_appr_cfg, "auxiliary", "approval", default=None)
- if _appr_mode == "manual" and not _tirith_on and not _aux_approval:
- logger.warning(
- "Gateway approvals.mode=manual with no automated risk "
- "assessor (security.tirith_enabled is false and "
- "auxiliary.approval is unset): dangerous commands and "
- "execute_code scripts will BLOCK until a human approves "
- "them in chat. Enable security.tirith_enabled or configure "
- "auxiliary.approval for unattended operation.")
- except Exception:
- logger.debug("approvals.mode startup check skipped", exc_info=True)
-
+ def _init_session_db(self) -> None:
+ """Open the session DB for the active scope and run opportunistic state.db / checkpoint maintenance."""
+ from gateway.run import (Any, Dict, Path, _SESSION_DB_UNPINNED, _housekeeping_chore, _housekeeping_state_db_maintenance, _launch_sessions_dir, logger, threading)
+ # Session DB is a property caching one AsyncSessionDB per path (a handle bound here would pin the
+ # root home under multiplex); priming here keeps startup diagnostics at init.
+ # Initialize session database for session_search tool support. Same frozen-handle class of bug as
+ # SessionStore._db (#88532): a handle bound here is pinned to the process's root home, but /resume,
+ # /title, /history and session search all run inside _profile_runtime_scope on a multiplexed gateway
+ # and must see that profile's own state.db.
+ self._session_db_pinned: Any = _SESSION_DB_UNPINNED
+ self._session_db_handles: Dict[Path, Any] = {}
+ self._session_db_handles_lock = threading.Lock()
+ from gateway.session_db_recovery import RecoverableHandleCache
+ self._session_db_handle_cache = RecoverableHandleCache(
+ handles=self._session_db_handles, lock=self._session_db_handles_lock)
+ try:
+ self._open_session_db_for_active_scope(raise_on_error=True)
+ except Exception as e:
+ # WARNING (not DEBUG) so it lands in errors.log; else an NFS HERMES_HOME silently loses /resume etc.
+ logger.warning("SQLite session store not available: %s", e)
+ self._session_db_init_error = str(e) # surfaced on the home channel(s) once connected
+
+ # Opportunistic state.db maintenance (prune + optional VACUUM), at most once per min_interval_hours.
+ # A few blocking seconds per day is fine for a long-lived gateway; failures log, never raise.
+ # Surface the failure to the user via their home channel(s) once the gateway connects. Without this,
+ # state.db corruption or NFS/SMB lock failures silently degrade the entire gateway — messages may
+ # flow but nothing is persisted, and the user has no indication until they try /resume and find
+ # nothing (#88235).
+ # Once per SERVED profile, each under its own scope: both the store and the ``sessions:``
+ # config that governs it must be the profile's own. Bound to ``self._session_db`` this ran
+ # against the construction-time launch home only, so a multiplexed secondary profile's
+ # state.db was never pruned or vacuumed by anybody, and the launch profile's
+ # retention_days/auto_prune decided whether it happened at all.
+ from gateway.run_profile_reconcile import _for_each_served_profile
+ _launch_sessions = _launch_sessions_dir(self.config) # resolved OUTSIDE any profile scope
+ _housekeeping_chore(
+ "state.db startup maintenance",
+ lambda: _for_each_served_profile(
+ self, lambda _label: _housekeeping_state_db_maintenance(_launch_sessions)))
+ # Checkpoint store pruning is a housekeeping chore (``_housekeeping_checkpoint_prune``), not a
+ # constructor step: its ``git gc`` repacks the whole store (tens of seconds on a GB store) and
+ # here it ran before the control socket, adapters and the code_sha stamp — so the first
+ # restart of the day (the ``hermes update`` one) looked hung and failed fleet verification.
+
+ def _init_registries_and_clocks(self) -> None:
+ """Pairing stores, hook registry, voice modes, background-task set, liveness and idle clocks."""
+ from gateway.run import (Dict, List, Optional, asyncio, time)
+ # ``pairing_store``: global/default store (CLI, callers without profile context); ``pairing_stores``:
+ # per-profile map ``authz_mixin._is_user_authorized`` routes through (one whitelist per profile).
+ from gateway.pairing import PairingStore
+ from gateway.hooks import ProfileHookRegistries
+ self.pairing_store = PairingStore()
+ self.pairing_stores: Dict[str, "PairingStore"] = {}
+ # One HookRegistry per served profile home, resolved from the active scope at emit time.
+ self.hooks = ProfileHookRegistries()
+ # Per-chat voice reply mode: "off" | "voice_only" | "all"
+ self._voice_mode: Dict[str, str] = self._load_voice_modes()
+ # Per-(bot, guild, text channel, user) transcript dedup: voice/STT can emit one utterance twice.
+ self._recent_voice_transcripts: Dict[tuple, List[tuple[float, str]]] = {}
+ # Background tasks kept referenced so they are not garbage-collected mid-execution.
+ self._background_tasks: set = set()
+ # Event-loop liveness heartbeat: rewritten every 30s while the loop dispatches; supervisors use
+ # the file mtime / updated_at to tell "process alive" from "loop frozen".
+ # See #66892.
+ self._gateway_started_at: float = time.time()
+ self._loop_heartbeat_task: Optional[asyncio.Task] = None
+ self._loop_floor_timer_handle = self._loop_liveness_watchdog = None
+ # scale-to-zero: gateway-scoped "last inbound seen" clock, stamped in _handle_message (the single
+ # inbound chokepoint) and seeded to "now" so a fresh gateway isn't idle from epoch.
+ self._last_inbound_at: float = time.time()
+ # Re-arm cooldown after a wake so we don't go dormant again before the drained backlog updates
+ # the clock; and a one-shot latch so the "platform owns the suspend" notice logs once.
+ self._scale_to_zero_cooldown_until: float = 0.0
+ self._scale_to_zero_no_suspend_logged: bool = False
+ self._scale_to_zero_direct_platform_logged: bool = False
diff --cc gateway/run_turn_runner.py
index 02142b11f04,f8e8d09e257..37c7594eef9
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@@ -386,12 -1271,11 +385,14 @@@ class TurnRunner(GatewayTurnProgressMix
agent.notice_clear_callback = None # sends can't be retracted
agent.event_callback = ctx._event_callback_sync
agent.reasoning_config, agent.service_tier = reasoning_config, runner._service_tier
- agent._voice_turn_pending = ctx.voice_turn # auxiliary.voice_chat route
++ from gateway.session_surface import surface_turn_note, surface_voice_turn
++ # auxiliary.voice_chat route: a voice note, or a canonical admission committed as a voice turn.
++ agent._voice_turn_pending = ctx.voice_turn or surface_voice_turn()
self._merge_turn_request_overrides(agent, turn_route)
# Must-deliver notes for THIS turn ride the current user message (api_content sidecar), never
# the system prompt. Assigned unconditionally so a reused agent never replays a stale note.
- from gateway.session_surface import surface_turn_note
- agent._gateway_turn_context_notes = "\n\n".join(runner._consume_pending_turn_sidecar_notes(ctx.session_key))
+ agent._gateway_turn_context_notes = "\n\n".join(
+ note for note in (*runner._consume_pending_turn_sidecar_notes(ctx.session_key), surface_turn_note(agent)) if note)
agent.background_review_callback, bg_release = self._make_bg_review_callbacks()
# Register the release hook on the adapter so base.py's finally block fires it after the
# main response is delivered.
diff --cc gateway/session_authority.py
index b3ba2a792b2,00000000000..5e8d26ad993
mode 100644,000000..100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@@ -1,604 -1,0 +1,605 @@@
+"""Gateway-owned live sessions and canonical durable FIFO scheduling.
+
+Only the runtime bootstrap holding profile ownership may initialize this service.
+Transport attachment never constructs an agent or takes a turn lease.
+"""
+from __future__ import annotations
+
+import asyncio
+from dataclasses import asdict, dataclass, field
+from functools import partial
+import uuid
+
+from gateway.session_contract import (
+ CANONICAL_GATEWAY_PROTOCOL, AdmissionReceipt, PendingAdmission, Principal, SessionHandle, SessionRef, Submission,
+ SubscriptionSnapshot,
+)
+from gateway.session_events import SessionEvents
+from gateway.session_pending_controls import PendingControls
+from hermes_state_runtime import (
+ RuntimeStoreError, admit_session_input, begin_runtime_epoch,
+ cancel_session_input, claim_session_input, get_session_admission,
+ list_session_admissions, recover_session_inputs, resolve_unknown_session_input,
+)
+
+
+@dataclass
+class LiveSession:
+ source: object
+ route: str
+ task: asyncio.Task | None = None
+ subscribers: dict = field(default_factory=dict)
+ event_stream: SessionEvents = field(default_factory=SessionEvents)
+ controls: PendingControls = field(init=False)
+ # The messaging ingress tells the platform user once per pause episode (unknown head,
+ # preflight refusal), not per message; the drain clears it when the FIFO moves again.
+ pause_notified: bool = False
+
+ def __post_init__(self):
+ self.controls = PendingControls(self.event_stream)
+
+
+def _log_drain_failure(task):
+ """A dead pump is the one failure this module must never swallow."""
+ if task.cancelled() or task.exception() is None:
+ return
+ import logging
+ logging.getLogger(__name__).error('Session drain task died: %r', task.exception())
+
+
+class SessionAuthority:
+ def __init__(self, runner, *, profile_id, instance_id, db, epoch):
+ self.runner = runner
+ self.profile_id = profile_id
+ self.instance_id = instance_id
+ self.db = db
+ self.epoch = epoch
+ self.sessions = {}
+ self.waiters = {}
+ self.events = {}
+ self.native_waiters = set()
+ self.pending_results = {}
+ # Stops accepted for a running generation whose agent does not exist yet
+ # (first-turn construction); consumed by adopt_agent, keyed session -> generation.
+ self.pending_stops = {}
+
+ def authorize(self, actor, ref, capability):
+ """Every handler calls this first, so a later ``self.sessions[ref.session_id]`` is
+ safe: a deleted/evicted live entry surfaces here as ``not_found``, not as a KeyError
+ deeper in the handler."""
+ if actor.profile_id != self.profile_id or ref.profile_id != self.profile_id:
+ raise RuntimeStoreError('profile_mismatch')
+ if capability not in actor.capabilities:
+ raise RuntimeStoreError('permission_denied')
+ if ref.session_id not in self.sessions:
+ row = self.db.get_session(ref.session_id)
+ if row is None:
+ raise RuntimeStoreError('not_found')
+ from hermes_state_local import POLICY_PREFIX
+ with self.db._read_ctx() as conn:
+ from hermes_state_local_migration import LEGACY_PREFIX
+ local = conn.execute('SELECT 1 FROM state_meta WHERE key IN (?,?)',
+ (POLICY_PREFIX + ref.session_id, LEGACY_PREFIX + ref.session_id)).fetchone()
+ if local or str(row.get('chat_id') or '').startswith('local-'):
+ from gateway.session_local_recovery import restore_local_session
+ restore_local_session(self, ref.session_id)
+ else:
+ from gateway.session_api import restore_api_session
+ restore_api_session(self, ref.session_id)
+ from gateway.config import Platform
+ source = self.sessions[ref.session_id].source
+ if (source is not None and source.platform == Platform.LOCAL
+ and source.user_id != actor.subject and 'session:operator' not in actor.capabilities):
+ raise RuntimeStoreError('permission_denied')
+
+ def _require_admission_open(self):
+ if self.runner._draining:
+ raise RuntimeStoreError('runtime_draining')
+
+ def logical_owner(self, session_id):
+ """The FIFO/admission identity of a route: the root of its compression lineage.
+ Compression advances the physical transcript, never the admission identity. A session this
+ store does not hold (another served profile's, under multiplex) keeps its own id."""
+ if not session_id:
+ return session_id
+ lineage = self.db.get_compression_lineage(session_id)
+ return lineage[0] if lineage else session_id
+
+ def physical_target(self, ref):
+ return self.db.get_compression_tip(ref.session_id) or ref.session_id
+
+ def register(self, source):
+ self._require_admission_open()
+ entry = self.runner.session_store.get_or_create_session(source)
+ sid = self.logical_owner(entry.session_id)
+ self.sessions.setdefault(sid, LiveSession(source, entry.session_key))
+ # SessionStore reserves routing metadata before the first AIAgent exists.
+ if self.db.get_session(sid) is None:
+ self.db.create_session(sid, source=source.platform.value)
+ return SessionRef(self.profile_id, sid)
+
+ def agent(self, ref):
+ return self.runner._cached_agent_for(self.sessions[ref.session_id].route)
+
+ def _handle(self, ref):
+ row = self.db.get_session(ref.session_id)
+ pending = list_session_admissions(self.db, session_id=ref.session_id)
+ state = 'unknown' if any(r['status'] == 'unknown' for r in pending) else (
+ 'running' if any(r['status'] == 'started' for r in pending) else 'idle')
+ return SessionHandle(ref, self.instance_id, self.epoch, row['runtime_revision'],
+ row['runtime_generation'], state)
+
+ async def resolve(self, actor, ref):
+ self.authorize(actor, ref, 'session:read')
+ return self._handle(ref)
+
+ async def attach(self, actor, ref):
+ self.authorize(actor, ref, 'session:read')
+ live = self.sessions[ref.session_id]
+ from gateway.session_local_recovery import local_history
+ with live.event_stream.lock:
+ subscription = next((key for key, member in live.subscribers.items()
+ if member == actor), None) or uuid.uuid4().hex
+ live.subscribers[subscription] = actor
+ transport = self.events.get(actor.transport_id)
+ if transport is not None:
+ live.event_stream.fanout.attach(transport)
+ live.event_stream.on_overflow = partial(self._retire_overflowed, ref.session_id)
+ handle = self._handle(ref)
+ active_generation = handle.execution_generation if handle.execution_state == "running" else None
+ prompts = live.controls.snapshot(ref.session_id, active_generation)
+ epoch, sequence = live.event_stream.watermark()
+ return SubscriptionSnapshot(subscription, handle, epoch,
+ sequence, tuple(local_history(self, ref)),
+ tuple(self._pending_receipt(r) for r in list_session_admissions(
+ self.db, session_id=ref.session_id)), prompts)
+
+ def _retire_overflowed(self, session_id, transport):
+ """The fanout dropped this peer's backlog: its subscription is over even though the
+ socket still answers RPCs. A later resume re-attaches it with a fresh snapshot."""
+ live = self.sessions[session_id]
+ for subscription, member in list(live.subscribers.items()):
+ if self.events.get(member.transport_id) is transport:
+ del live.subscribers[subscription]
+
+ async def detach(self, actor, subscription_id):
+ for session_id, live in self.sessions.items():
+ if subscription_id in live.subscribers:
+ if live.subscribers[subscription_id] != actor:
+ raise RuntimeStoreError('permission_denied')
+ del live.subscribers[subscription_id]
+ transport = self.events.get(actor.transport_id)
+ if transport is not None:
+ live.event_stream.fanout.detach(transport)
+ if not live.subscribers:
+ from gateway.session_acp_lifecycle import end_idle_acp_session
+ end_idle_acp_session(self, session_id)
+ return
+ raise RuntimeStoreError('not_found')
+
+ def _receipt(self, row):
+ return AdmissionReceipt(row['admission_id'], SessionRef(self.profile_id, row['target_session_id']),
+ row['seq'], row['status'], row['outcome'],
+ row['owner_epoch'] or self.epoch, row['generation'])
+
+ def _pending_receipt(self, row):
+ # Only public input text crosses the viewer boundary, never the
+ # private native envelope's routing or authorization provenance.
+ payload = row['payload']
+ text = payload.get('text')
+ if text is None:
+ text = payload.get('native_text_v1', {}).get('event', {}).get('text', '')
+ return PendingAdmission(**vars(self._receipt(row)), input_id=row['request_id'], text=text)
+
+ def _publish_pending(self, ref):
+ live = self.sessions[ref.session_id]
+ with live.event_stream.lock:
+ handle = self._handle(ref)
+ pending = [asdict(self._pending_receipt(row)) for row in
+ list_session_admissions(self.db, session_id=ref.session_id)]
+ # Turns bump runtime_revision without any session.updated event, so
+ # this is the only place a viewer learns the CAS revision a later
+ # prepared mutation must present.
+ live.event_stream.publish(ref.session_id, {
+ 'stored_session_id': ref.session_id, 'pending': pending,
+ 'desktop_protocol': CANONICAL_GATEWAY_PROTOCOL,
+ 'running': handle.execution_state == 'running',
+ 'execution_generation': handle.execution_generation,
+ 'revision': handle.revision,
+ }, event_type='session.info')
+
+ def _schedule(self, ref):
+ live = self.sessions[ref.session_id]
+ if live.task is None or live.task.done():
+ live.task = asyncio.create_task(self._drain(ref))
+ live.task.add_done_callback(_log_drain_failure)
+
+ def _pause(self, ref, reason):
+ """The FIFO stopped without claiming its head. Committed rows stay queued for a later
+ drain; only the process-local messaging delivery waiters on this session are released,
+ with the reason instead of a reply, so an adapter loop is never parked on a turn that
+ will not run. The ingress turns that refusal into one user-facing notice per episode."""
+ for row in list_session_admissions(self.db, session_id=ref.session_id):
+ admission_id = row['admission_id']
+ if admission_id not in self.native_waiters:
+ continue
+ self.native_waiters.discard(admission_id)
+ waiter = self.waiters.pop(admission_id, None)
+ if waiter is not None and not waiter.done():
+ waiter.set_exception(RuntimeStoreError(reason))
+
+ async def admit_automation(self, adapter, event, identity):
+ from gateway.session_automation import admit_automation
+ return await admit_automation(self, adapter, event, identity)
+
+ async def admit_native(self, event):
+ """Await current connector policy, then commit before ACK or scheduling execution."""
+ import json
+ from gateway.session_envelope import prepare_native, restore_native
+ self._require_admission_open()
+ payload = await prepare_native(self.runner, event)
+ self._require_admission_open()
+ source = restore_native(payload).source
+ ref = self.register(source)
+ identity = json.dumps([source.profile, source.platform.value, source.chat_id,
+ source.thread_id, source.user_id], separators=(',', ':'))
+ row = admit_session_input(self.db, epoch=self.epoch, principal_id='messaging:' + identity,
+ session_id=ref.session_id,
+ request_id=str(payload['native_text_v1']['event']['message_id'] or uuid.uuid4().hex),
+ payload=payload)
+ event._gateway_accepted = True
+ self._publish_pending(ref)
+ self._schedule(ref)
+ return self._receipt(row)
+
+ async def recover_native_sessions(self, bindings):
+ """Bind only server-observed native routes; unknown work stays paused."""
+ from collections import Counter
+ from gateway.session_envelope import check_native_route
+ bindings = list(bindings)
+ counts = Counter(sid for sid, _, _ in bindings)
+ results = {}
+ for sid, available_source, adapter in bindings:
+ try:
+ if counts[sid] != 1:
+ raise RuntimeStoreError('admission_conflict')
+ rows = list_session_admissions(self.db, session_id=sid, pending_only=False)
+ native = [row for row in rows if 'native_text_v1' in row['payload']]
+ if not native:
+ raise RuntimeStoreError('not_found')
+ target = self.physical_target(SessionRef(self.profile_id, sid))
+ source, route = await check_native_route(self.runner, native[-1]['payload'], target,
+ available_source, adapter)
+ for row in rows:
+ if row['status'] != 'queued':
+ continue
+ if 'native_text_v1' in row['payload']:
+ await check_native_route(self.runner, row['payload'], target, available_source, adapter)
+ elif 'local_automation_v1' in row['payload']:
+ from gateway.session_automation import check_local_automation
+ check_local_automation(
+ self, SessionRef(self.profile_id, sid), row, route=route)
+ else:
+ from gateway.session_operator import check_local_input
+ check_local_input(
+ self, SessionRef(self.profile_id, sid), row, source=source)
+ self._require_admission_open()
+ self.sessions.setdefault(sid, LiveSession(source, route))
+ if any(row['status'] == 'unknown' for row in rows):
+ raise RuntimeStoreError('unknown_execution')
+ self._schedule(SessionRef(self.profile_id, sid))
+ results[sid] = 'ready'
+ except RuntimeStoreError as exc:
+ results[sid] = exc.reason
+ return results
+
+ async def submit(self, actor: Principal, request: Submission, *, _authorize_write=None):
+ self.authorize(actor, request.ref, 'session:submit')
+ self._require_admission_open()
+ if (request.intent != 'queue' or not {'text'} <= set(request.payload) <= {
- 'text', 'attachments', 'finite', 'unattended', 'surface', 'voice_context', 'interrupted'}
++ 'text', 'attachments', 'finite', 'unattended', 'surface', 'voice_context', 'interrupted',
++ 'voice_turn'}
+ or not isinstance(request.payload['text'], str)):
+ raise RuntimeStoreError('invalid_params')
+ from gateway.session_ingress_media import admit_attachments
+ from gateway.session_finite import admit_finite
+ from gateway.session_surface import admit_surface
+ finite = admit_finite(request.payload)
+ payload = {'text': request.payload['text'], **finite, **admit_surface(request.payload),
+ **admit_attachments(request.payload.get('attachments'))}
+ source = self.sessions[request.ref.session_id].source
+ if source is not None and source.user_id != actor.subject:
+ # Durable server authorization, not a client payload field. The original
+ # principal remains the admission/retry identity across owner restarts.
+ # Operator provenance is about who was authorized at this boundary, not
+ # whether the bound session happens to use the LOCAL transport.
+ payload['local_operator_v1'] = {
+ 'profile_id': self.profile_id, 'session_id': request.ref.session_id,
+ 'principal_id': actor.subject}
+ row = admit_session_input(self.db, epoch=self.epoch, principal_id=actor.subject,
+ session_id=request.ref.session_id, request_id=request.request_id,
+ payload=payload, intent=request.intent,
+ _authorize_write=_authorize_write)
+ self._publish_pending(request.ref)
+ self._schedule(request.ref)
+ return self._receipt(row)
+
+ async def receipt(self, actor, ref, admission_id):
+ self.authorize(actor, ref, 'session:submit')
+ row = get_session_admission(self.db, admission_id=admission_id)
+ if row is None or row['target_session_id'] != ref.session_id:
+ raise RuntimeStoreError('not_found')
+ if row['principal_id'] != actor.subject and 'session:control' not in actor.capabilities:
+ raise RuntimeStoreError('permission_denied')
+ return self._receipt(row)
+
+ async def cancel_queued(self, actor, ref, admission_id):
+ before = await self.receipt(actor, ref, admission_id)
+ row = cancel_session_input(self.db, epoch=self.epoch, admission_id=admission_id)
+ from gateway.session_ingress_media import release_admission_media
+ release_admission_media(self.db, admission_id)
+ if before.status != 'queued' or row['status'] != 'terminal':
+ self._publish_pending(ref)
+ return self._receipt(row)
+ # The only place a queued row becomes terminal: every observer kind that waits on
+ # the admission (native delivery, API/webhook/hosted waiters, ACP and viewer streams)
+ # settles here, or a cancelled row that never reaches _drain blocks them forever.
+ live = self.sessions[ref.session_id]
+ with live.event_stream.lock:
+ self._publish_pending(ref)
+ running = live.event_stream.execution
+ # A queued row owns no execution generation; stamp its own identity so the
+ # completion is not attributed to the turn currently running ahead of it.
+ live.event_stream.execution = {'authority_epoch': self.epoch, 'admission_id': admission_id}
+ try:
+ live.event_stream.publish(ref.session_id, {
+ 'text': '', 'content': '', 'admission_id': admission_id, 'outcome': 'cancelled'})
+ finally:
+ live.event_stream.execution = running
+ self.native_waiters.discard(admission_id)
+ waiter = self.waiters.pop(admission_id, None)
+ if waiter is not None and not waiter.done():
+ waiter.set_result(None)
+ # A paused drain (preclaim refusal on this head) ended its task; the successors
+ # need a fresh drain that revalidates them on their own merits.
+ self._schedule(ref)
+ return self._receipt(row)
+
+ async def resolve_unknown(self, actor, ref, admission_id, generation):
+ """Operator acknowledgement that a turn lost across an owner restart will not
+ finish; the paused FIFO behind it resumes. Never requeues the lost input."""
+ self.authorize(actor, ref, 'session:control')
+ await self.receipt(actor, ref, admission_id)
+ row = resolve_unknown_session_input(self.db, epoch=self.epoch, admission_id=admission_id,
+ generation=generation)
+ # Before the follower is scheduled: its request must not carry the discarded text merged in.
+ from gateway.session_local_recovery import transcript_target
+ from gateway.session_results import close_discarded_turn
+ close_discarded_turn(self.db, transcript_target(self, ref))
+ self._publish_pending(ref)
+ self._schedule(ref)
+ return self._receipt(row)
+
+ async def interrupt(self, actor, ref, generation):
+ self.authorize(actor, ref, 'session:control')
+ handle = self._handle(ref)
+ if handle.execution_generation != generation:
+ raise RuntimeStoreError('stale_generation')
+ if handle.execution_state == 'running':
+ agent = self.agent(ref)
+ if agent is not None:
+ agent.interrupt()
+ else:
+ # Accepted for this exact claim; the turn must not construct its agent
+ # afterwards and run the work as if no Stop had arrived.
+ self.pending_stops[ref.session_id] = generation
+ return self._handle(ref)
+
+ def adopt_agent(self, session_id, generation, agent):
+ """The turn installs its agent for the running claim; a Stop latched while there
+ was no agent to deliver it to fires now, never against a later generation."""
+ if self.pending_stops.get(session_id) == generation:
+ del self.pending_stops[session_id]
+ agent.interrupt()
+
+ def check_approval_generation(self, session_id, generation):
+ handle = self._handle(SessionRef(self.profile_id, session_id))
+ if handle.execution_generation != generation or handle.execution_state != "running":
+ raise RuntimeStoreError("stale_generation")
+
+ def publish_execution(self, session_id, generation, event_type, payload):
+ """Worker callbacks never outlive their exact running claim."""
+ live = self.sessions[session_id]
+ with live.event_stream.lock:
+ try:
+ self.check_approval_generation(session_id, generation)
+ except RuntimeStoreError:
+ return False
+ delivered = live.event_stream.publish(session_id, payload, event_type=event_type)
+ from gateway.session_api_turn import publish_api_event
+ observed = publish_api_event(self, session_id, event_type, payload)
+ return bool(delivered or observed)
+
+ def register_approval(self, session_id, generation, route, data):
+ live = self.sessions[session_id]
+ with live.event_stream.lock:
+ self.check_approval_generation(session_id, generation)
+ live.controls.register(session_id, route, generation, data)
+
+ def register_clarify(self, session_id, generation, entry):
+ live = self.sessions[session_id]
+ with live.event_stream.lock:
+ self.check_approval_generation(session_id, generation)
+ live.controls.register_clarify(session_id, generation, entry)
+
+ async def respond(self, actor, ref, generation, prompt_id, response, *, kind="approval"):
+ capability = {"approval": "session:approve", "clarify": "session:respond"}.get(kind)
+ if capability is None:
+ raise RuntimeStoreError("invalid_params")
+ self.authorize(actor, ref, capability)
+ live = self.sessions[ref.session_id]
+ with live.event_stream.lock:
+ if actor not in live.subscribers.values():
+ raise RuntimeStoreError("permission_denied")
+ if type(generation) is not int:
+ raise RuntimeStoreError("stale_generation")
+ self.check_approval_generation(ref.session_id, generation)
+ if not isinstance(prompt_id, str) or not prompt_id:
+ raise RuntimeStoreError("invalid_params")
+ return live.controls.respond(ref.session_id, generation, prompt_id, response, kind=kind)
+
+ async def _drain(self, ref):
+ from gateway.session_finite import execute_finite_admission
+ live = self.sessions[ref.session_id]
+ while True:
+ try:
+ pending = list_session_admissions(self.db, session_id=ref.session_id)
+ if any(row['status'] == 'unknown' for row in pending):
+ self._pause(ref, 'unknown_execution')
+ return
+ first = next((row for row in pending if row['status'] == 'queued'), None)
+ from gateway.config import Platform
+ if first is not None and live.source.platform == Platform.LOCAL:
+ from gateway.session_local_recovery import restore_local_session
+ restore_local_session(self, ref.session_id)
+ if first['request_id'].startswith('hosted:'):
+ from gateway.session_hosted_transport import check_remote_hosted_admission
+ if not await asyncio.to_thread(check_remote_hosted_admission, self, ref, first):
+ service = getattr(self, 'hosted_room_service', None)
+ if service is None:
+ raise RuntimeStoreError('permission_denied')
+ await asyncio.to_thread(service.check_admission, ref, first)
+ # Cancellation may advance the FIFO while the source owner is awaited;
+ # the successor must earn its own reauthorization, not inherit this one.
+ current = get_session_admission(self.db, admission_id=first['admission_id'])
+ if current is None or current['status'] != 'queued':
+ continue
+ if 'local_automation_v1' in first['payload']:
+ from gateway.session_automation import check_local_automation
+ check_local_automation(self, ref, first)
+ else:
+ from gateway.session_operator import check_local_input
+ check_local_input(self, ref, first)
+ # The first real turn reopens a finalized row (#85303): mounts are reads, and
+ # SessionStore would route a stamped row as stale onto a FRESH session.
+ from gateway.session_local_recovery import reopen_local_session
+ reopen_local_session(self, ref)
+ if first is not None and 'native_text_v1' in first['payload']:
+ from gateway.session_envelope import check_native_route
+ await check_native_route(self.runner, first['payload'], self.physical_target(ref), live.source,
+ self.runner._adapter_for_source(live.source))
+ # Cancellation may advance FIFO while the connector is awaited.
+ # Never let the successor inherit this row's fresh verdict.
+ current = get_session_admission(self.db, admission_id=first['admission_id'])
+ if current is None or current['status'] != 'queued':
+ continue
+ if first is not None and live.source.platform == Platform.API_SERVER:
+ from gateway.session_api_turn import check_api_turn
+ check_api_turn(self, ref, first['payload'])
+ self._require_admission_open()
+ row = claim_session_input(self.db, epoch=self.epoch, session_id=ref.session_id)
+ except RuntimeStoreError as exc:
+ import logging
+ logging.getLogger(__name__).warning('Session %s paused: %s', ref.session_id, exc.reason)
+ self._pause(ref, exc.reason)
+ return
+ # The FIFO is moving again (or empty): the next pause is a new episode.
+ live.pause_notified = False
+ if row is None:
+ return
+ admission_id = row['admission_id']
+ with live.event_stream.lock:
+ live.event_stream.execution = {
+ 'authority_epoch': self.epoch, 'execution_generation': row['generation'],
+ 'admission_id': admission_id}
+ live.event_stream.publish(ref.session_id, {}, event_type='message.start')
+ self._publish_pending(ref)
+ try:
+ response = await execute_finite_admission(self, ref, row)
+ outcome = 'completed'
+ except Exception:
+ import logging
+ logging.getLogger(__name__).exception('Admitted turn %s failed', admission_id)
+ response = 'The admitted turn failed.'
+ outcome = 'failed'
+ try:
+ with live.event_stream.lock:
+ from gateway.session_results import finish_result
+ captured = self.pending_results.pop(admission_id, None)
+ settled, response = finish_result(self.db, epoch=self.epoch, row=row,
+ response=response, outcome=outcome, result=captured)
+ live.controls.snapshot(ref.session_id, None)
+ from gateway.session_ingress_media import release_admission_media
+ release_admission_media(self.db, admission_id)
+ # ``status`` is the message.complete contract's TurnStatus: the Desktop
+ # extends a Stopped bubble to the persisted partial only on 'interrupted'.
+ complete = {
+ 'text': response, 'content': response, 'admission_id': admission_id,
+ 'outcome': 'cancelled' if settled['outcome'] == 'interrupted' else settled['outcome'],
+ 'status': {'completed': 'complete', 'interrupted': 'interrupted'}.get(
+ settled['outcome'], 'error')}
+ # Only the agent's reuse site sets this (never inferred from equal text): the
+ # final repeats a reply the viewer already painted, so it settles in place.
+ captured_result = (captured or {}).get('result') or {}
+ if response and captured_result.get('response_reused'):
+ complete['response_reused'] = True
+ # The committed row addresses of the turn: a viewer binds the streamed reply to
+ # its stored row, so a transcript read racing this frame never paints it twice.
+ # ``submission_id`` names whose turn it is: the sending viewer binds its optimistic
+ # prompt (``user-<submission_id>``), which the queued admission ack could not name.
+ if isinstance(captured_result.get('persisted_turn'), dict):
+ complete['persisted_turn'] = {**captured_result['persisted_turn'],
+ 'submission_id': row['request_id']}
+ live.event_stream.publish(ref.session_id, complete)
+ # The idle snapshot (running=false) follows the completion, as on every other
+ # host: a viewer that read running=false first settled the reply as a turn whose
+ # terminal frame was lost and raced its own transcript read against the real one.
+ self._publish_pending(ref)
+ except Exception:
+ # The settle fence lost (a reset/compression moved runtime_generation under
+ # the turn). The row stays `started` for recovery -> `unknown`; re-settling
+ # it here would forge an outcome the ledger refused. The pump itself must
+ # not die silently: log with the id and fall through to release observers.
+ import logging
+ logging.getLogger(__name__).exception(
+ 'Settlement of admission %s failed; left for recovery', admission_id)
+ response = 'The admitted turn could not be settled.'
+ finally:
+ # The stamp names a claimed, unsettled execution. Left in place, idle
+ # mutations (session.updated) would carry a terminal generation and
+ # a versioned viewer fence would discard them as late frames.
+ with live.event_stream.lock:
+ live.event_stream.execution = {}
+ self.pending_stops.pop(ref.session_id, None)
+ waiter = self.waiters.pop(admission_id, None)
+ if waiter is not None and not waiter.done():
+ waiter.set_result(response)
+
+
+async def initialize_session_authority(runner, *, profile_id, instance_id, db=None, register=True):
+ """Call after exclusive profile ownership, before connecting adapters/API.
+
+ ``register=False`` builds a served secondary's authority without making it the runner's
+ launch authority (``runner.session_authority``); the per-home registry owns the lookup.
+ """
+ if db is None:
+ db = getattr(runner._session_db, '_db', runner._session_db)
+ epoch = begin_runtime_epoch(db, instance_id=instance_id)
+ recover_session_inputs(db, epoch=epoch)
+ authority = SessionAuthority(runner, profile_id=profile_id, instance_id=instance_id, db=db, epoch=epoch)
+ if register:
+ runner.session_authority = authority
+ from gateway.session_cron import bind_owner
+ bind_owner(authority)
+ store = runner.session_store
+ if register:
+ store._local_authority_epoch = epoch
+ # Local resets write the owning profile's store; the epoch fence must be that store's.
+ epochs = getattr(store, '_local_authority_epochs', None)
+ if epochs is None:
+ epochs = store._local_authority_epochs = {}
+ from pathlib import Path
+ epochs[Path(db.db_path).resolve()] = epoch
+ from gateway.session_local_recovery import recover_local_sessions
+ recover_local_sessions(authority)
+ return authority
diff --cc gateway/session_controls.py
index 919b438cd82,00000000000..e3b5e903af8
mode 100644,000000..100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@@ -1,453 -1,0 +1,453 @@@
+"""Authenticated WS projection of the gateway authority; no TUI execution fallback."""
+from dataclasses import asdict
+from pathlib import Path
+import sqlite3
+import uuid
+
+from gateway.config import Platform
+from gateway.session_contract import CANONICAL_GATEWAY_PROTOCOL, Principal, SessionRef, Submission
+from hermes_state_runtime import RuntimeStoreError
+
+
+# Verbs whose param sets are closed and never carried a ``profile`` key.
+_PROFILE_IMPLICIT = frozenset({'session.create', 'session.list', 'session.info', 'session.resume', 'session.detach',
+ 'prompt.submit', 'prompt.receipt', 'prompt.cancel', 'prompt.resolve_unknown',
+ 'session.interrupt', 'session.events.since', 'session.mutate',
+ 'approval.respond', 'clarify.respond'})
+
+
+class AuthorityConnection:
+ def __init__(self, authority, transport, identity, *, operator=False):
+ self.authority = authority
+ self.transport = transport
+ capabilities = frozenset({'session:read', 'session:submit', 'session:control',
+ 'session:approve', 'session:respond'})
+ if identity:
+ capabilities |= {'session:create'}
+ if 'capabilities' in identity:
+ capabilities = frozenset(identity['capabilities'])
+ # Only verified transport gates may issue this capability, never identity data.
+ capabilities -= {'session:operator'}
+ if operator is True:
+ capabilities |= {'session:operator'}
+ if (not identity.get('user_id')
+ or identity.get('instance_id', authority.instance_id) != authority.instance_id):
+ capabilities = frozenset()
+ from gateway.session_identity import authenticated_subject
+ self.actor = Principal(authenticated_subject(identity),
+ identity.get('profile_id', authority.profile_id),
+ capabilities, uuid.uuid4().hex)
+ from gateway.session_local_migration import bind_native_transport
+ bind_native_transport(authority, self.actor, identity)
+ self.native_owner = identity.get('native_bootstrap') is True
+ self.subscriptions = {}
+ self._identity, self._operator, self._siblings = identity, operator, {}
+ authority.events[self.actor.transport_id] = transport
+
+ def _sibling_for(self, profile):
+ """Connection bound to the sibling authority a ``profile`` param names, or None for our own
+ home. One native socket serves every profile this process multiplexes (the Desktop's
+ shared-primary route); a profile nobody here serves is a mismatch, never a fallback."""
+ from hermes_cli.profiles import profile_matches_home
+ if profile_matches_home(profile, Path(self.authority.profile_id)):
+ return None
+ registry = getattr(getattr(self.authority, 'runner', None), 'session_authorities', None)
+ for sibling in (registry or ()):
+ if sibling is not self.authority and profile_matches_home(profile, Path(sibling.profile_id)):
+ connection = self._siblings.get(sibling.profile_id)
+ if connection is None:
+ identity = dict(self._identity, profile_id=sibling.profile_id, instance_id=sibling.instance_id)
+ connection = AuthorityConnection(sibling, self.transport, identity, operator=self._operator)
+ self._siblings[sibling.profile_id] = connection
+ return connection
+ raise RuntimeStoreError('profile_mismatch')
+
+ async def dispatch(self, request):
+ rid = request.get('id')
+ method = request.get('method')
+ params = request.get('params') or {}
+ if not isinstance(params, dict):
+ # Every handler indexes params as a mapping; refuse the frame before ``.get``.
+ return {'jsonrpc': '2.0', 'id': rid, 'error': {
+ 'code': 4001, 'message': 'invalid_params', 'data': {'reason': 'invalid_params'}}}
+ profile = params.get('profile')
+ if isinstance(profile, str) and profile:
+ try:
+ routed = self._sibling_for(profile)
+ except RuntimeStoreError as exc:
+ return {'jsonrpc': '2.0', 'id': rid, 'error': {
+ 'code': 4001, 'message': exc.reason, 'data': {'reason': exc.reason}}}
+ if routed is not None:
+ return await routed.dispatch(request)
+ # Our own home: the scope is implicit for the strict session verbs, which refuse
+ # unknown keys; every other handler validates ``profile`` itself.
+ if method in _PROFILE_IMPLICIT:
+ params = {key: value for key, value in params.items() if key != 'profile'}
+ ref = SessionRef(self.actor.profile_id, params.get('session_id', ''))
+ handlers = {'session.create': self.create, 'ping': self.ping, 'runtime.describe': self.describe,
+ 'commands.catalog': self.command_catalog, 'complete.slash': self.slash_completions,
+ 'slash.exec': self.slash_exec, 'command.dispatch': self.command_dispatch,
+ 'session.list': self.list_sessions, 'session.info': self.info,
+ 'session.mutate': self.mutate, 'bot_relay.deliver': self.bot_deliver,
+ 'bot_relay.roster.sync': self.bot_roster, 'bot_relay.outbox.drain': self.bot_outbox,
+ 'bot_relay.reply': self.bot_reply, 'a2a.forward': self.a2a_forward,
+ 'kanban.run': self.kanban_run,
+ 'cron.submit': self.cron_submit, 'cron.status': self.cron_status,
+ 'cron.cancel': self.cron_cancel, 'cron.recover': self.cron_recover,
+ 'worker.register': self.worker_register, 'worker.adopt': self.worker_adopt,
+ 'worker.persist': self.worker_persist,
+ 'setup.status': self.setup_status, 'setup.runtime_check': self.setup_runtime_check,
+ 'session.resume': self.resume, 'session.detach': self.detach,
+ 'prompt.submit': self.submit,
+ 'prompt.receipt': self.receipt, 'prompt.cancel': self.cancel,
+ 'prompt.resolve_unknown': self.resolve_unknown,
+ 'session.interrupt': self.interrupt, 'session.events.since': self.events_since,
+ 'approval.respond': self.respond, 'clarify.respond': self.respond_clarify}
+ from gateway.session_busy_controls import handlers as busy_handlers
+ handlers.update(busy_handlers(self))
+ from gateway.session_config import handlers as config_handlers
+ handlers.update(config_handlers(self))
+ from gateway.session_ancillary import handlers as ancillary_handlers
+ handlers.update(ancillary_handlers(self))
+ from gateway.session_images import attach_bytes
+ from functools import partial
+ handlers['image.attach_bytes'] = partial(attach_bytes, self)
+ try:
+ from gateway.session_group_controls import GROUP_METHODS, dispatch_group_control
+ # Every handler reads config/jobs/policy for the OWNING profile: enter its home so
+ # ``_load_gateway_config`` / ``build_policy(get_hermes_home())`` never snapshot the
+ # launch profile's config into a served secondary's session. Under a single profile
+ # the scope is that profile's own home, so behaviour is unchanged.
+ from gateway.session_authorities import owner_scope
+ with owner_scope(self.authority):
+ if method in GROUP_METHODS or method == 'profiles.list':
+ result = await dispatch_group_control(self, method, params)
+ return {'jsonrpc': '2.0', 'id': rid, 'result': result}
+ if method not in handlers:
+ # JSON-RPC's own verdict: clients key compat fallbacks on -32601, and a
+ # 4001 'invalid_params' would read as a bad argument on a method that exists.
+ return {'jsonrpc': '2.0', 'id': rid, 'error': {
+ 'code': -32601, 'message': f'unknown method: {method}',
+ 'data': {'reason': 'unknown_method'}}}
+ result = await handlers[method](ref, params)
+ return {'jsonrpc': '2.0', 'id': rid, 'result': result}
+ except RuntimeStoreError as exc:
+ return {'jsonrpc': '2.0', 'id': rid, 'error': {
+ 'code': 4001, 'message': exc.reason, 'data': {'reason': exc.reason}}}
+ except sqlite3.Error:
+ return {'jsonrpc': '2.0', 'id': rid, 'error': {
+ 'code': 5001, 'message': 'storage_unavailable', 'data': {'reason': 'storage_unavailable'}}}
+
+ async def a2a_forward(self, ref, params):
+ from gateway.session_a2a import forward
+ return await forward(self, params)
+
+ async def kanban_run(self, ref, params):
+ from gateway.session_kanban import run_task
+ return await run_task(self, params)
+
+ async def cron_recover(self, ref, params):
+ from gateway.session_cron import rpc
+ return await rpc(self, 'recover', params)
+
+ async def cron_submit(self, ref, params):
+ from gateway.session_cron import rpc
+ return await rpc(self, 'submit', params)
+
+ async def cron_status(self, ref, params):
+ from gateway.session_cron import rpc
+ return await rpc(self, 'status', params)
+
+ async def cron_cancel(self, ref, params):
+ from gateway.session_cron import rpc
+ return await rpc(self, 'cancel', params)
+
+ async def bot_roster(self, ref, params):
+ from gateway.session_bot import relay_operation
+ return relay_operation(self, 'roster', params)
+
+ async def bot_outbox(self, ref, params):
+ from gateway.session_bot import relay_operation
+ return relay_operation(self, 'outbox', params)
+
+ async def bot_reply(self, ref, params):
+ from gateway.session_bot import relay_operation
+ return relay_operation(self, 'reply', params)
+
+ async def bot_deliver(self, ref, params):
+ from gateway.session_bot import deliver
+ return await deliver(self, params)
+
+ async def worker_register(self, ref, params):
+ from gateway.session_worker import worker_request
+ return await worker_request(self, ref, params, operation='register')
+
+ async def worker_adopt(self, ref, params):
+ from gateway.session_worker import worker_request
+ return await worker_request(self, ref, params, operation='adopt')
+
+ async def worker_persist(self, ref, params):
+ from gateway.session_worker import worker_request
+ return await worker_request(self, ref, params, operation='persist')
+
+ async def slash_exec(self, ref, params):
+ from gateway.session_commands import execute_command
+ return await execute_command(self, ref, params)
+
+ async def command_dispatch(self, ref, params):
+ from gateway.session_commands import execute_command
+ return await execute_command(self, ref, params, dispatch=True)
+
+ async def command_catalog(self, ref, params):
+ from gateway.session_discovery import discover_commands
+ return await discover_commands(self.authority, self.actor, params)
+
+ async def slash_completions(self, ref, params):
+ from gateway.session_discovery import discover_commands
+ return await discover_commands(self.authority, self.actor, params, completion=True)
+
+ async def setup_status(self, ref, params):
+ from gateway.session_readiness import readiness
+ return await readiness(self.authority, self.actor, params, runtime=False)
+
+ async def setup_runtime_check(self, ref, params):
+ from gateway.session_readiness import readiness
+ return await readiness(self.authority, self.actor, params, runtime=True)
+
+ async def create(self, ref, params):
+ from gateway.session_local import create_local_session
+ from gateway.session_local_title import resolve_titled_session, title_new_session, validate_title
+ # ``-c <title> --create-if-missing``: resolve-or-create is one owner step (no await
+ # between lookup and creation), so concurrent programmatic callers converge.
+ title = validate_title(params.pop('title')) if 'title' in params else None
+ # Bot Mode's forever-chat mint: born hidden from the sidebar; `follow_profile_config` is
+ # the canonical default (a local session's runtime is built from the profile's current
+ # config on every attach), so the flag is accepted for the legacy contract and implied.
+ hidden = params.pop('hidden', False)
+ params.pop('follow_profile_config', None)
+ if type(hidden) is not bool:
+ raise RuntimeStoreError('invalid_params')
+ ref = title and resolve_titled_session(self.authority, self.actor, title, missing_ok=True)
+ if not ref:
+ ref = create_local_session(self.authority, self.actor, params)
+ if title:
+ title_new_session(self.authority, ref, title)
+ if hidden:
+ self.authority.db.set_session_hidden(ref.session_id, True)
+ return await self.resume(ref, {})
+
+ async def ping(self, ref, params):
+ if not self.actor.capabilities:
+ raise RuntimeStoreError('permission_denied')
+ if params:
+ raise RuntimeStoreError('invalid_params')
+ return {'pong': True}
+
+ async def describe(self, ref, params):
+ await self.ping(ref, params)
+ from gateway.session_policy import CREATE_FIELDS
+ return {'instance_id': self.authority.instance_id, 'profile_id': self.authority.profile_id,
+ 'authority_epoch': self.authority.epoch,
+ 'capabilities': ['durable-admission-v1', 'event-replay-v1', 'local-cli-create-v1', 'acp-editor-policy-v1', 'acp-session-mcp-v1'],
+ 'session_create': {'sources': ['cli', 'tui', 'gui', 'acp'],
+ 'parameters': sorted(CREATE_FIELDS | {'title'})}}
+
+ async def info(self, ref, params):
+ from gateway.session_local import local_session_info
+ if set(params) != {'session_id'}:
+ raise RuntimeStoreError('invalid_params')
+ await self.authority.resolve(self.actor, ref)
+ return local_session_info(self.authority, ref)
+
+ async def list_sessions(self, ref, params):
+ if 'session:read' not in self.actor.capabilities:
+ raise RuntimeStoreError('permission_denied')
+ limit = params.get('limit', 200)
+ if set(params) - {'limit', 'title', 'include_hidden'} or type(limit) is not int or not 1 <= limit <= 200:
+ raise RuntimeStoreError('invalid_params')
+ if 'title' in params:
+ # Title-as-identity lookup (the Bots roster's forever-chat registry): the same
+ # resolver `session.resume title=` uses, so a hidden canonical chat answers here
+ # instead of being re-minted. Never confirms another principal's titles.
+ from gateway.session_local_title import resolve_titled_session
+ found = resolve_titled_session(self.authority, self.actor, params['title'], missing_ok=True)
+ if found is None:
+ return {'sessions': [], 'scope': 'stored'}
+ row = self.authority.db.get_session(found.session_id) or {}
+ root = self.authority.db.get_session(
+ self.authority.db.resolve_session_by_title(params['title']) or found.session_id) or row
+ return {'sessions': [{'session_id': found.session_id, 'id': root.get('id') or found.session_id,
+ 'resolved_id': found.session_id, 'title': row.get('title') or '',
+ 'root_title': root.get('title') or '', 'source': row.get('source'),
+ 'started_at': row.get('started_at'),
+ 'message_count': row.get('message_count', 0),
+ 'running': found.session_id in self.authority.sessions}],
+ 'scope': 'stored'}
+ sessions = []
+ for sid in tuple(self.authority.sessions):
+ candidate = SessionRef(self.actor.profile_id, sid)
+ try:
+ handle = await self.authority.resolve(self.actor, candidate)
+ except RuntimeStoreError as exc:
+ if exc.reason not in {'permission_denied', 'profile_mismatch', 'not_found'}:
+ raise
+ continue
+ row = self.authority.db.get_session(sid)
+ sessions.append({'session_id': sid, 'id': sid, 'title': row.get('title') or '',
+ 'source': row.get('source'), 'started_at': row.get('started_at'),
+ 'message_count': row.get('message_count', 0),
+ 'running': handle.execution_state == 'running'})
+ sessions.sort(key=lambda row: row['started_at'] or 0, reverse=True)
+ return {'sessions': sessions[:limit], 'scope': 'live'}
+
+ async def resume(self, ref, params):
+ from gateway.session_local import local_session_info
+ if 'title' in params:
+ from gateway.session_local_title import resolve_titled_session
+ ref = resolve_titled_session(self.authority, self.actor, params['title'])
+ if 'title' not in params:
+ from gateway.session_local_migration import resolve_local_target
+ row = self.authority.db.get_session(ref.session_id)
+ if row and row['source'] in {'cli', 'tui', 'gui'}:
+ ref = resolve_local_target(self.authority, self.actor,
+ self.authority.db.get_compression_tip(ref.session_id) or ref.session_id)
+ if params.get('editor') is not None:
+ self.authority.authorize(self.actor, ref, 'session:control')
+ from gateway.session_local_mcp import resume_editor_mcp
+ resume_editor_mcp(self.authority, ref, params['editor'])
+ # Read-only mount (#85303): an ended row stays ended until the first admitted turn
+ # reopens it (``reopen_local_session`` in the drain), so opening a finished chat
+ # never re-lights DB-derived liveness with no new activity.
+ self.authority.authorize(self.actor, ref, 'session:read')
+ snapshot = await self.authority.attach(self.actor, ref)
+ self.subscriptions[ref.session_id] = snapshot.subscription_id
+ # Only local routes have a frozen local launch policy to project.
+ info = {'desktop_protocol': CANONICAL_GATEWAY_PROTOCOL}
+ source = self.authority.sessions[snapshot.handle.ref.session_id].source
+ if source is not None and source.platform == Platform.LOCAL:
+ info = local_session_info(self.authority, snapshot.handle.ref)
+ return {'session_id': ref.session_id, 'stored_session_id': ref.session_id,
+ 'messages': list(snapshot.history), 'message_count': len(snapshot.history),
+ 'running': snapshot.handle.execution_state == 'running',
+ 'authority_epoch': snapshot.handle.authority_epoch,
+ 'replay_epoch': snapshot.replay_epoch, 'last_sequence': snapshot.last_sequence,
+ 'subscription_id': snapshot.subscription_id, 'revision': snapshot.handle.revision,
+ 'execution_generation': snapshot.handle.execution_generation,
+ 'pending': [asdict(r) for r in snapshot.pending],
+ 'prompts': list(snapshot.prompts), 'info': info}
+
+ async def detach(self, ref, params):
+ if set(params) != {'session_id', 'subscription_id'}:
+ raise RuntimeStoreError('invalid_params')
+ session_id = params['session_id']
+ subscription_id = params['subscription_id']
+ if (not isinstance(session_id, str) or not session_id
+ or not isinstance(subscription_id, str) or not subscription_id):
+ raise RuntimeStoreError('invalid_params')
+ result = {'session_id': session_id, 'subscription_id': subscription_id,
+ 'detached': False}
+ if self.subscriptions.get(session_id) != subscription_id:
+ return result
+ await self.authority.detach(self.actor, subscription_id)
+ if self.subscriptions.get(session_id) == subscription_id:
+ del self.subscriptions[session_id]
+ result['detached'] = True
+ return result
+
+ async def events_since(self, ref, params):
+ self.authority.authorize(self.actor, ref, 'session:read')
+ sequence = params.get('last_sequence', params.get('last_seen', 0))
+ epoch = params.get('replay_epoch')
+ if type(sequence) is not int or sequence < 0 or (epoch is not None and not isinstance(epoch, str)):
+ raise RuntimeStoreError('invalid_params')
+ return self.authority.sessions[ref.session_id].event_stream.since(epoch, sequence)
+
+ async def submit(self, ref, params):
+ if ref.session_id not in self.subscriptions:
+ raise RuntimeStoreError('permission_denied')
+ forbidden = set(params) - {'session_id', 'text', 'submission_id', 'input_id', 'queued', 'attachments', 'finite', 'unattended',
- 'surface', 'voice_context', 'interrupted'}
++ 'surface', 'voice_context', 'interrupted', 'voice_turn'}
+ if forbidden:
+ raise RuntimeStoreError('invalid_params')
+ request_id = params.get('submission_id') or params.get('input_id')
+ if not isinstance(request_id, str) or not request_id:
+ raise RuntimeStoreError('invalid_params')
+ from gateway.session_finite import admit_finite
+ from gateway.session_surface import submit_surface_fields
+ payload = {'text': params.get('text'), **admit_finite(params), **submit_surface_fields(params)}
+ if 'attachments' in params:
+ payload['attachments'] = params['attachments']
+ receipt = await self.authority.submit(self.actor, Submission(request_id, ref, payload, 'queue'))
+ return asdict(receipt)
+
+ async def mutate(self, ref, params):
+ from gateway.session_mutations import mutate_session
+ from hermes_state_mutation_guards import MUTATION_GUARD_REFUSALS
+ try:
+ result = await mutate_session(self.authority, self.actor, ref, params)
+ except MUTATION_GUARD_REFUSALS as exc:
+ # A live turn lease / compression lock is the same retryable busy verdict a
+ # running admission gets (REST maps it to 409), not an internal error.
+ raise RuntimeStoreError('session_busy') from exc
+ # The branching viewer navigates straight into its new child; attach it
+ # here (create parity) so the first submit is not refused as a stranger.
+ child = result.get('branched_session_id') if isinstance(result, dict) else None
+ if child and child not in self.subscriptions:
+ await self.resume(SessionRef(ref.profile_id, child), {})
+ return result
+
+ async def receipt(self, ref, params):
+ receipt = await self.authority.receipt(self.actor, ref, params.get('admission_id'))
+ out = asdict(receipt)
+ if params.get('include_result') is True and receipt.status == 'terminal':
+ # The exact structured result the turn committed with settlement (`finish_result`):
+ # a finite viewer reads its ledger (tokens, cost, model, exit reason) from here, the same
+ # dict the in-process one-shot wrote from `run_conversation`.
+ from gateway.session_results import admission_result
+ saved = admission_result(self.authority.db, receipt.admission_id)
+ if saved is not None:
+ out['result'] = saved['result']
+ out['usage'] = saved.get('usage') or {}
+ return out
+
+ async def cancel(self, ref, params):
+ return asdict(await self.authority.cancel_queued(self.actor, ref, params.get('admission_id')))
+
+ async def resolve_unknown(self, ref, params):
+ if set(params) != {'session_id', 'admission_id', 'execution_generation'}:
+ raise RuntimeStoreError('invalid_params')
+ return asdict(await self.authority.resolve_unknown(
+ self.actor, ref, params['admission_id'], params['execution_generation']))
+
+ async def interrupt(self, ref, params):
+ from gateway.session_managed_worker import interrupt_managed
+ if interrupt_managed(self.authority, self.actor, ref, params.get('execution_generation')):
+ return asdict(self.authority._handle(ref))
+ return asdict(await self.authority.interrupt(self.actor, ref, params.get('execution_generation')))
+
+ async def respond(self, ref, params):
+ if set(params) != {"session_id", "execution_generation", "prompt_id", "choice"}:
+ raise RuntimeStoreError("invalid_params")
+ return await self.authority.respond(self.actor, ref, params["execution_generation"],
+ params["prompt_id"], {"choice": params["choice"]})
+
+ async def respond_clarify(self, ref, params):
+ if set(params) != {"session_id", "execution_generation", "prompt_id", "answer"}:
+ raise RuntimeStoreError("invalid_params")
+ return await self.authority.respond(self.actor, ref, params["execution_generation"],
+ params["prompt_id"], {"answer": params["answer"]}, kind="clarify")
+
+ async def close(self):
+ for sibling in self._siblings.values():
+ await sibling.close()
+ self._siblings.clear()
+ # Deletion may already have evicted a subscribed session; its membership died
+ # with it, and one retired ID must not leave the others (or the transport) attached.
+ for session_id, subscription in list(self.subscriptions.items()):
+ live = self.authority.sessions.get(session_id)
+ if live is not None and subscription in live.subscribers:
+ await self.authority.detach(self.actor, subscription)
+ from gateway.session_local_migration import unbind_native_transport
+ unbind_native_transport(self.authority, self.actor)
+ self.subscriptions.clear()
+ self.authority.events.pop(self.actor.transport_id, None)
diff --cc gateway/session_local.py
index 5d9aeac78bd,00000000000..f85f27f1a39
mode 100644,000000..100644
--- a/gateway/session_local.py
+++ b/gateway/session_local.py
@@@ -1,189 -1,0 +1,205 @@@
+"""Fresh local routes owned by the authenticated gateway, not by a viewer.
+
+Source and supported launch settings are frozen per route, never process env.
+"""
+from __future__ import annotations
+
+import uuid
+
+from gateway.config import Platform, PlatformConfig
+from gateway.platforms.base import BasePlatformAdapter, SendResult
+from gateway.session import SessionSource
+from gateway.session_contract import CANONICAL_GATEWAY_PROTOCOL
+from hermes_state_runtime import RuntimeStoreError
+
+
+class LocalSessionAdapter(BasePlatformAdapter):
+ """Delivery stays in the canonical event stream; no second local transport."""
+
+ def __init__(self, authority):
+ super().__init__(PlatformConfig(enabled=True), Platform.LOCAL)
+ self.authority = authority
+ self.sources = {}
+ self.policies = {}
+
+ def authorize_source(self, source):
+ saved = self.sources.get(source.chat_id)
+ if saved is None:
+ return False
+ original, identity = saved
+ return (source is original and self._identity(source) == identity
+ and any(live.source is source for live in self.authority.sessions.values()))
+
+ @staticmethod
+ def _identity(source):
+ return source.platform, source.chat_id, source.user_id, source.profile, source.chat_type
+
+ def register_source(self, source):
+ self.sources[source.chat_id] = source, self._identity(source)
+
+ async def connect(self, *, is_reconnect=False):
+ return True
+
+ async def disconnect(self):
+ self.sources.clear()
+
+ async def send(self, chat_id, content, reply_to=None, metadata=None):
+ # TurnRunner already publishes model/tool deltas and settlement exactly once.
+ return SendResult(success=True, message_id=uuid.uuid4().hex)
+
+ async def edit_message(self, chat_id, message_id, content, *, finalize=False):
+ return SendResult(success=True, message_id=message_id)
+
+ async def _record_delivery_obligation(self, *args, **kwargs):
+ # No platform ACK to lose: viewers replay the durable transcript. A ledger row would only
+ # park a raw copy of the reply in state.db that no redelivery can ever use.
+ return None
+
+ async def send_typing(self, chat_id, metadata=None):
+ return None
+
+ async def get_chat_info(self, chat_id):
+ return {'id': chat_id, 'type': 'dm'}
+
+ async def send_exec_approval(self, **kwargs):
+ # The existing callback owns registration in PendingControls. An ACK here
+ # selects that rendering path without a plaintext fallback or a second waiter.
+ return SendResult(success=True, message_id=uuid.uuid4().hex)
+
+
+def authorize_local_source(runner, source):
+ """None for legacy/nonlocal routes; registered local adapters fail closed."""
+ if source.platform != Platform.LOCAL:
+ return None
+ # A forged profile must not miss this adapter and fall into a messaging
+ # allow-all policy. Local source identity is owned by this authority alone.
+ from gateway.session_authorities import all_authorities
+ owners = all_authorities(runner)
+ adapter = runner._adapters_for_profile(source.profile).get(Platform.LOCAL)
+ if not isinstance(adapter, LocalSessionAdapter):
+ # A LOCAL source naming a profile this runtime does not serve must fail closed rather
+ # than fall into a messaging allow-all policy; legacy runners (no authority) stay None.
+ return False if owners else None
+ # The adapter's authority must be one THIS runtime owns (the launch authority or a served
+ # secondary's), never a stale/foreign object that happens to carry a LOCAL adapter.
+ if not any(adapter.authority is owner for owner in owners):
+ return False
+ return adapter.authorize_source(source)
+
+
+def _bypass_policy(params, *, private_secrets):
+ """Frozen snapshot for --safe-mode / --ignore-user-config: code defaults plus the explicit
+ launch options. The profile's config.yaml/.env are never read, so a malformed profile cannot
+ block or shape the session; there is no default model to inherit, so one must be explicit."""
+ import copy
+ from gateway.session_policy import build_policy
+ from hermes_cli.config_defaults import DEFAULT_CONFIG
+ if not params.get('model'):
+ raise RuntimeStoreError('invalid_params')
+ defaults = copy.deepcopy(DEFAULT_CONFIG)
+ if not isinstance(defaults.get('model'), dict): # code default is the empty string
+ defaults['model'] = {}
+ return build_policy(params, defaults, private_secrets=private_secrets, profile_terminal=False)
+
+
+def create_local_session(authority, actor, params, *, trusted_policy=None, trusted_secrets=None):
+ if actor.profile_id != authority.profile_id:
+ raise RuntimeStoreError('profile_mismatch')
+ if 'session:create' not in actor.capabilities:
+ raise RuntimeStoreError('permission_denied')
+ from gateway.session_policy import build_policy, BYPASS_FIELDS
+ from gateway.run import _load_gateway_config, _resolve_gateway_model
+ from dataclasses import replace
+ private_secrets = dict(trusted_secrets or {})
+ if trusted_policy is not None:
+ policy = trusted_policy
+ elif any(params.get(name) is True for name in BYPASS_FIELDS):
+ policy = _bypass_policy(params, private_secrets=private_secrets)
+ else:
+ from gateway.session_local_route import resolve_launch_route
+ config = _load_gateway_config()
+ params = resolve_launch_route(params, config)
+ policy = build_policy(params, config, private_secrets=private_secrets)
+ if policy.model is None:
+ policy = replace(policy, model=_resolve_gateway_model(policy.config()))
+ request_id = params.get('request_id', uuid.uuid4().hex)
+ if not isinstance(request_id, str) or not request_id or len(request_id) > 256:
+ raise RuntimeStoreError('invalid_params')
+ from dataclasses import asdict
+ from gateway.session import SessionEntry
+ from gateway.session_lifecycle import _now
+ from gateway.session_local_recovery import local_identity, restore_local_session
+ from hermes_state_local import commit_local_session
+ authority._require_admission_open()
+ sid = local_identity(authority.profile_id, actor.subject, request_id)
+ from gateway.session_policy import bind_launch_key, restore_policy, launch_key
+ if authority.db.get_session(sid) is not None:
+ from hermes_state_local import local_receipt
+ saved = local_receipt(authority.db, sid)
+ original = restore_policy(saved['policy'])
+ if original.request_json != policy.request_json:
+ raise RuntimeStoreError('invalid_params')
+ if original.credential_ref is not None or params.get('api_key') is not None:
+ import hmac
+ key = launch_key(authority, original)
+ if key is None or not hmac.compare_digest(key, params.get('api_key') or ''):
+ raise RuntimeStoreError('admission_conflict')
+ return restore_local_session(authority, sid)
+ policy = bind_launch_key(authority, sid, policy, params.get("api_key"), config_secrets=private_secrets)
+ from gateway.session_local_recovery import local_source
+ source = local_source(authority, sid, actor.subject)
+ route = authority.runner.session_store._generate_session_key(source)
+ # Same clock as every other routing entry: the recovery sweeps compare against a
+ # naive cutoff, and one aware entry aborts the whole iteration.
+ now = _now()
+ entry = SessionEntry(route, sid, now, now, origin=source, platform=Platform.LOCAL)
+ commit_local_session(authority.db, epoch=authority.epoch, receipt={
+ 'profile_id': authority.profile_id, 'principal_id': actor.subject, 'request_id': request_id,
+ 'session_id': sid, 'route': route, 'entry': entry.to_dict(), 'policy': asdict(policy)})
+ return restore_local_session(authority, sid)
+
+
+def publish_local_policy(authority, session_id):
+ from hermes_state_local import local_receipt
+ from gateway.session_policy import restore_policy
+ live = authority.sessions[session_id]
+ from gateway.session_local_recovery import local_adapter_map
+ adapter = local_adapter_map(authority)[Platform.LOCAL]
+ adapter.policies[live.source.chat_id] = restore_policy(local_receipt(authority.db, session_id)['policy'])
+ authority.runner._evict_cached_agent(live.route)
+
+
++def _lazy_model(authority, policy):
++ """The model a not-yet-built session will run: with no provider pinned, the free tier's agent
++ build pins ``nous/welcome`` (``pin_model_for_route``), so the configured default is not it."""
++ import json
++ model = policy.model if policy else None
++ if (policy is None or json.loads(policy.request_json).get('model')
++ or str(policy.provider or '').strip().lower() not in {'', 'auto'}):
++ return model
++ from gateway.session_authorities import owner_scope
++ from hermes_cli.anon_auth import GUEST_MODEL, free_tier_route
++ with owner_scope(authority):
++ return GUEST_MODEL if free_tier_route() else model
++
++
+def local_session_info(authority, ref):
+ live = authority.sessions[ref.session_id]
+ agent = authority.agent(ref)
+ from gateway.session_authorities import served_profile_name
+ from gateway.session_policy import policy_for_source
+ policy = policy_for_source(authority.runner, live.source)
+ info = {'source': policy.source if policy else live.source.platform.value,
- 'model': getattr(agent, 'model', policy.model if policy else None), 'lazy': agent is None,
++ 'model': (getattr(agent, 'model', policy.model if policy else None) if agent is not None
++ else _lazy_model(authority, policy)),
++ 'lazy': agent is None,
+ 'profile_id': authority.profile_id, 'desktop_protocol': CANONICAL_GATEWAY_PROTOCOL,
+ # Main's TUI labels a named profile's composer (``alpha ❯``) from this field.
+ 'profile_name': served_profile_name(authority.profile_id),
+ **({'cwd': policy.cwd} if policy else {})}
+ if policy:
+ # The creation request the route was frozen with (secrets already extracted), so a
+ # resuming client can tell "same flags again" from a real override attempt.
+ import json
+ info['launch_request'] = json.loads(policy.request_json)
+ return info
diff --cc gateway/session_policy.py
index 46dec3aea9d,00000000000..f8564efb699
mode 100644,000000..100644
--- a/gateway/session_policy.py
+++ b/gateway/session_policy.py
@@@ -1,323 -1,0 +1,322 @@@
+"""Frozen, explicit local-client launch policy for the existing TurnRunner."""
+from contextlib import contextmanager
+from contextvars import ContextVar
+from dataclasses import dataclass
+import json
+from pathlib import Path
+
+from hermes_state_runtime import RuntimeStoreError
+
+CREATE_FIELDS = frozenset({'request_id', 'source', 'cwd', 'model', 'toolsets',
+ 'provider', 'base_url', 'reasoning', 'max_turns', 'ignore_rules', 'api_key', 'editor',
+ 'yolo', 'safe_mode', 'ignore_user_config'})
+BYPASS_FIELDS = ('safe_mode', 'ignore_user_config')
+_ACTIVE_POLICY: ContextVar = ContextVar('local_session_policy', default=None)
+SURFACES = {'cli': 'cli', 'tui': 'tui', 'gui': 'desktop', 'acp': 'acp'}
+
+
+@dataclass(frozen=True)
+class LocalSessionPolicy:
+ source: str
+ platform: str
+ cwd: str
+ model: str | None
+ toolsets: tuple[str, ...]
+ config_json: str
+ request_json: str
+ terminal_json: str
+ credential_ref: str | None = None
+ config_secret_ref: str | None = None
+ editor_mcp_json: str | None = None
+ kanban_json: str | None = None
+ # Troubleshooting isolation is derived by the owner at creation and frozen with the
+ # route; safe_mode always implies ignore_user_config (normalized once in build_policy).
+ safe_mode: bool = False
+ ignore_user_config: bool = False
+
+ def config(self, authority=None):
+ config = present_sections(json.loads(self.config_json))
+ if self.config_secret_ref is not None and authority is not None:
+ from gateway.session_policy_credentials import recover_config_secrets
+ secrets = recover_config_secrets(authority, self)
+ for path, value in secrets.items():
+ if path[0] is None: # private terminal projection, not config
+ continue
+ target = config
+ for key in path[:-1]:
+ target = target[key]
+ target[path[-1]] = value
+ return config
+
+ @property
+ def provider(self):
+ return self.config().get('model', {}).get('provider')
+
+ @property
+ def base_url(self):
+ return self.config().get('model', {}).get('base_url')
+
+ @property
+ def ignore_rules(self):
+ return self.safe_mode or json.loads(self.request_json).get('ignore_rules', False)
+
+ @property
+ def yolo(self):
+ """`hermes chat --yolo`: this session's dangerous-command approvals are bypassed, exactly the
+ scope `/yolo` gives a messaging chat; never the process-wide HERMES_YOLO_MODE."""
+ return json.loads(self.request_json).get('yolo', False)
+
+ @property
+ def max_turns(self):
+ from hermes_cli.config import resolve_turn_limit
+ cfg = self.config()
+ return resolve_turn_limit(cfg.get('agent', {}).get('max_turns', cfg.get('max_turns')))
+
+ @property
+ def reasoning_config(self):
+ from hermes_constants import resolve_reasoning_config
+ return resolve_reasoning_config(self.config(), self.model or '')
+
+
+def present_sections(config):
+ """A bare ``gateway:`` key parses as YAML null; like load_config's merge (#58277), treat it as absent so
+ ``cfg.get('gateway', {}).get(...)`` reads the default instead of crashing a fresh install's first turn."""
+ return {key: value for key, value in config.items() if value is not None}
+
+
+def build_policy(params, config, *, private_secrets=None, profile_terminal=True):
+ from hermes_cli.tools_config import _get_platform_tools
+ from toolsets import validate_toolset
+ from agent.runtime_cwd import resolve_agent_cwd
+ from tools.terminal_scope import build_profile_terminal_scope, default_terminal_scope
+ from hermes_constants import get_hermes_home
+
+ source = params.get('source', 'cli')
+ if source == 'a2a':
+ from gateway.session_a2a import build_forward_policy
+ return build_forward_policy(params, config, private_secrets=private_secrets)
+ if set(params) - CREATE_FIELDS or not isinstance(source, str) or source not in SURFACES:
+ raise RuntimeStoreError('invalid_params')
+ if any(name in params and type(params[name]) is not bool for name in BYPASS_FIELDS):
+ raise RuntimeStoreError('invalid_params')
+ safe_mode = params.get('safe_mode', False)
+ ignore_user_config = safe_mode or params.get('ignore_user_config', False)
+ if 'api_key' in params and (not isinstance(params['api_key'], str) or not params['api_key'].strip()):
+ raise RuntimeStoreError('invalid_params')
+ model = params.get('model')
+ if 'model' in params and (not isinstance(model, str) or not model.strip()):
+ raise RuntimeStoreError('invalid_params')
+ cwd = params.get('cwd', str(resolve_agent_cwd()))
+ if not isinstance(cwd, str) or not Path(cwd).is_absolute() or not Path(cwd).is_dir():
+ raise RuntimeStoreError('invalid_params')
+ from gateway.session_local_editor import validate_editor
+ validate_editor(source, params.get('editor'))
+ config = present_sections(json.loads(json.dumps(config)))
+ from urllib.parse import urlsplit
+ from hermes_constants import parse_reasoning_effort
+ for key in ('provider', 'base_url'):
+ if key in params:
+ value = params[key]
+ if not isinstance(value, str) or not value.strip():
+ raise RuntimeStoreError('invalid_params')
+ if key == 'base_url':
+ url = urlsplit(value)
+ if (url.scheme not in {'http', 'https'} or not url.hostname
+ or url.username or url.password or url.query or url.fragment):
+ raise RuntimeStoreError('invalid_params')
+ config.setdefault('model', {})[key] = value
+ for flag in ('ignore_rules', 'yolo'):
+ if flag in params and type(params[flag]) is not bool:
+ raise RuntimeStoreError('invalid_params')
+ if 'max_turns' in params:
+ value = params['max_turns']
+ if type(value) is not int or value <= 0:
+ raise RuntimeStoreError('invalid_params')
+ config.setdefault('agent', {})['max_turns'] = value
+ if 'reasoning' in params:
+ if not isinstance(params['reasoning'], str) or parse_reasoning_effort(params['reasoning']) is None:
+ raise RuntimeStoreError('invalid_params')
+ config.setdefault('agent', {})['reasoning_effort'] = params['reasoning']
+ # An explicit launch level wins over a per-model default, just like CLI.
+ config['agent'].pop('reasoning_overrides', None)
+ explicit = params.get('toolsets')
+ if 'toolsets' in params:
+ if (not isinstance(explicit, list) or any(not isinstance(x, str) or not validate_toolset(x) for x in explicit)
+ or ('desktop_ui' in explicit and source != 'gui')):
+ raise RuntimeStoreError('invalid_params')
+ config.setdefault('platform_toolsets', {})['acp' if source == 'acp' else 'cli'] = explicit
+ enabled = _get_platform_tools(config, 'acp' if source == 'acp' else 'cli')
+ if explicit is not None:
+ from toolsets import resolve_toolset
+ requested = {t for name in explicit for t in resolve_toolset(name)}
+ effective = {t for name in enabled for t in resolve_toolset(name)}
+ if not requested <= effective:
+ raise RuntimeStoreError('invalid_params')
+ elif source in {'tui', 'gui'}:
+ # Same surface toolsets as the native TUI factory, without its env inference.
+ # The fold-in lands after _get_platform_tools subtracted agent.disabled_toolsets, so
+ # subtract again or `disabled_toolsets: [project]` is a no-op here (#54433).
+ # desktop_ui is the client's own control surface, not a model toolset.
+ from agent.skill_utils import parse_config_string_list
++ from toolsets import CLIENT_SURFACE_TOOLSETS
+ disabled = set(parse_config_string_list((config.get('agent') or {}).get('disabled_toolsets')))
- if 'project' not in disabled:
- enabled.add('project')
- if source == 'gui':
- enabled.add('desktop_ui')
++ surface = set(CLIENT_SURFACE_TOOLSETS) if source == 'gui' else {'project'}
++ enabled |= surface - (disabled - {'desktop_ui'})
+ if safe_mode:
+ # Plugin toolsets are user customizations; the safe worker never imports them.
+ from hermes_cli.tools_config import _get_plugin_toolset_keys
+ enabled -= _get_plugin_toolset_keys()
+ terminal = build_profile_terminal_scope(get_hermes_home()) if profile_terminal else default_terminal_scope()
+ terminal['TERMINAL_CWD'] = cwd
+ request = {k: v for k, v in params.items() if k not in {'request_id', 'api_key'}}
+ request.setdefault('source', 'cli')
+ from gateway.session_local_mcp import private_editor_request
+ private_editor_request(request, private_secrets)
+ _extract_config_secrets(config, private_secrets)
+ _extract_config_secrets(terminal, private_secrets, (None,))
+ return LocalSessionPolicy(source, SURFACES[source], cwd, model, tuple(sorted(enabled)),
+ json.dumps(config), json.dumps(request, sort_keys=True), json.dumps(terminal),
+ safe_mode=safe_mode, ignore_user_config=ignore_user_config)
+
+
+def _extract_config_secrets(value, private, path=()):
+ # Reuse the configuration owner's structural classification; opaque keys need
+ # not match a vendor prefix. Only the authority keeps their original values.
+ from hermes_cli.config import _SECRET_CONFIG_KEYS
+ from agent.credential_persistence import _is_secret_payload_key
+ containers = {'env', 'headers', 'extra_headers', 'docker_env', 'docker_extra_args',
+ 'terminal_docker_env', 'terminal_docker_extra_args'}
+ items = value.items() if isinstance(value, dict) else enumerate(value) if isinstance(value, list) else ()
+ for key, child in items:
+ child_path = path + (key,)
+ sensitive = isinstance(key, str) and (key.lower() in _SECRET_CONFIG_KEYS
+ or key.lower() in containers or _is_secret_payload_key(key))
+ if sensitive and child and child not in ('{}', '[]'):
+ if private is None:
+ raise RuntimeStoreError('launch_credentials_unavailable')
+ private[child_path] = child
+ value[key] = None
+ else:
+ _extract_config_secrets(child, private, child_path)
+
+
+def bind_launch_key(authority, session_id, policy, api_key, *, config_secrets=None):
+ """CLI keys live only in this authority lifetime, never its durable receipt.
+
+ Restart deliberately revokes them. History remains readable; inference must
+ report launch_credentials_unavailable, never select a profile fallback key.
+ """
+ from dataclasses import replace
+ import hmac
+ from gateway.session_local_mcp import PRIVATE_KEY, bind_editor_mcp
+ config_secrets = dict(config_secrets or {})
+ policy = bind_editor_mcp(authority, session_id, policy, config_secrets.pop(PRIVATE_KEY, None))
+ if api_key is None and not config_secrets:
+ return policy
+ keys = getattr(authority, '_local_launch_keys', None)
+ if keys is None:
+ keys = authority._local_launch_keys = {}
+ ref = f'{authority.instance_id}:{authority.epoch}:{session_id}'
+ old = keys.get(ref)
+ if old is not None and (api_key is None or not hmac.compare_digest(old, api_key)):
+ raise RuntimeStoreError('admission_conflict')
+ configs = getattr(authority, '_local_config_secrets', None)
+ if configs is None:
+ configs = authority._local_config_secrets = {}
+ config_ref = ref
+ if config_secrets and getattr(authority, 'db', None) is not None:
+ from gateway.session_policy_credentials import config_reference
+ config_ref = config_reference(authority, session_id, policy, config_secrets)
+ if config_ref in configs and configs[config_ref] != config_secrets:
+ raise RuntimeStoreError('admission_conflict')
+ if config_secrets:
+ configs[config_ref] = dict(config_secrets)
+ if api_key is not None:
+ keys[ref] = api_key
+ return replace(policy, credential_ref=ref if api_key is not None else None,
+ config_secret_ref=config_ref if config_secrets else None)
+
+
+def launch_key(authority, policy):
+ if policy.credential_ref is None:
+ return None
+ value = getattr(authority, '_local_launch_keys', {}).get(policy.credential_ref)
+ if value is None:
+ raise RuntimeStoreError('launch_credentials_unavailable')
+ return value
+
+
+def restore_policy(data):
+ """Reject incomplete private policy rather than rebuilding from current defaults."""
+ try:
+ policy = LocalSessionPolicy(**data)
+ from gateway.session_a2a import is_forward_policy
+ surfaces = {**SURFACES, 'cron': 'cron', 'kanban': 'cli', 'bot_room': 'bot_room'}
+ if ((not is_forward_policy(policy) and
+ (policy.source not in surfaces or policy.platform != surfaces[policy.source]))
+ or not isinstance(policy.cwd, str) or not Path(policy.cwd).is_absolute()
+ or not Path(policy.cwd).is_dir()
+ or not isinstance(policy.model, str) or not policy.model.strip()
+ or not isinstance(policy.toolsets, (list, tuple))
+ or any(not isinstance(name, str) for name in policy.toolsets)
+ or type(policy.safe_mode) is not bool or type(policy.ignore_user_config) is not bool
+ or (policy.safe_mode and not policy.ignore_user_config)):
+ raise ValueError('invalid policy')
+ from dataclasses import replace
+ for value in (policy.config_json, policy.request_json, policy.terminal_json):
+ if not isinstance(json.loads(value), dict):
+ raise ValueError('invalid policy object')
+ if json.loads(policy.terminal_json).get('TERMINAL_CWD') != policy.cwd:
+ raise ValueError('terminal policy mismatch')
+ return replace(policy, toolsets=tuple(policy.toolsets))
+ except (KeyError, TypeError, ValueError) as exc:
+ raise RuntimeStoreError('storage_unavailable') from exc
+
+
+def policy_for_source(runner, source):
+ from gateway.session_local import LocalSessionAdapter
+ from gateway.config import Platform
+ if source.platform != Platform.LOCAL:
+ return None
+ adapter = runner._adapter_for_source(source)
+ if isinstance(adapter, LocalSessionAdapter) and adapter.authorize_source(source):
+ policy = adapter.policies.get(source.chat_id)
+ if policy is None:
+ # Cold recovery must restore the frozen policy before executing, not
+ # reinterpret a LOCAL route as a default CLI launch.
+ raise RuntimeStoreError('storage_unavailable')
+ return policy
+ return None
+
+
+@contextmanager
+def policy_scope(policy, *, authority=None):
+ if policy is None:
+ yield
+ return
+ from agent.runtime_cwd import set_session_cwd
+ from tools.terminal_scope import set_terminal_scope, reset_terminal_scope
+ terminal = json.loads(policy.terminal_json)
+ if policy.config_secret_ref is not None:
+ from gateway.session_policy_credentials import recover_config_secrets
+ for path, value in recover_config_secrets(authority, policy).items():
+ if path[0] is None:
+ terminal[path[1]] = value
+ cwd_token = set_session_cwd(policy.cwd)
+ terminal_token = set_terminal_scope(terminal)
+ policy_token = _ACTIVE_POLICY.set(policy)
+ from gateway.session_local_editor import editor_scope
+ try:
+ from gateway.session_local_mcp import editor_mcp_scope
+ with editor_scope(policy), editor_mcp_scope(authority, policy):
+ yield
+ finally:
+ _ACTIVE_POLICY.reset(policy_token)
+ reset_terminal_scope(terminal_token)
+ cwd_token.var.reset(cwd_token)
+
+
+def active_policy():
+ """The frozen launch policy of the turn executing in this context, or ``None`` (standalone
+ serve / messaging turns). Consumers read it instead of re-deriving from live config."""
+ return _ACTIVE_POLICY.get()
diff --cc gateway/session_surface.py
index 373cfcf2bbf,00000000000..13e47c07897
mode 100644,000000..100644
--- a/gateway/session_surface.py
+++ b/gateway/session_surface.py
@@@ -1,85 -1,0 +1,93 @@@
+"""Per-turn client surface (floating HUD, live voice) carried through canonical admission.
+
+A surface is a fact about ONE turn, never about the session: the same session alternates
+between the app window, the HUD and a spoken delegation. It is committed with the admission
+row and reaches the model as a note on the user message (api_content sidecar), so the
+persisted user row stays the words the user typed and the frozen system prefix is untouched.
+"""
+from contextlib import contextmanager
+from contextvars import ContextVar
+
+from hermes_state_runtime import RuntimeStoreError
+
+SURFACES = frozenset({'hud', 'voice-live'})
+_VOICE_CONTEXT_LIMIT = 6000
- _SUBMIT_FIELDS = ('surface', 'voice_context', 'interrupted')
++_SUBMIT_FIELDS = ('surface', 'voice_context', 'interrupted', 'voice_turn')
+_surface_turn = ContextVar('surface_turn', default=None)
+
+
+def submit_surface_fields(params):
+ """The raw per-turn surface fields of a ``prompt.submit`` request, forwarded to admission."""
+ return {key: params[key] for key in _SUBMIT_FIELDS if key in params}
+
+
+def admit_surface(params):
- """Wire ``surface`` / ``voice_context`` / ``interrupted`` -> committed ``surface_v1`` (``{}`` when absent)."""
- surface, context, interrupted = (params.get(key) for key in _SUBMIT_FIELDS)
++ """Wire ``surface`` / ``voice_context`` / ``interrupted`` / ``voice_turn`` -> committed ``surface_v1``
++ (``{}`` when absent). ``voice_turn`` marks a spoken voice-mode turn: it runs on ``auxiliary.voice_chat``."""
++ surface, context, interrupted, voice_turn = (params.get(key) for key in _SUBMIT_FIELDS)
+ if surface is not None and surface not in SURFACES:
+ raise RuntimeStoreError('invalid_params')
+ # The spoken transcript only makes sense for a live-voice delegation; anywhere else it is
+ # a client smuggling model input past the persisted row.
+ if context is not None and (surface != 'voice-live' or not isinstance(context, str)):
+ raise RuntimeStoreError('invalid_params')
- if interrupted is not None and type(interrupted) is not bool:
++ if any(flag is not None and type(flag) is not bool for flag in (interrupted, voice_turn)):
+ raise RuntimeStoreError('invalid_params')
+ committed = {}
+ if surface:
+ committed['surface'] = surface
+ if context:
+ committed['voice_context'] = context[:_VOICE_CONTEXT_LIMIT]
+ if interrupted:
+ committed['interrupted'] = True
++ if voice_turn:
++ committed['voice_turn'] = True
+ return {'surface_v1': committed} if committed else {}
+
+
+def _hud_note(committed, valid_tool_names):
+ from agent.prompt_builder import hud_surface_note
+ return hud_surface_note(valid_tool_names)
+
+
+def _voice_live_note(committed, valid_tool_names):
+ from tools.voice_live import voice_live_turn_note
+ return voice_live_turn_note(committed.get('voice_context') or '')
+
+
+_SURFACE_NOTES = {'hud': _hud_note, 'voice-live': _voice_live_note}
+
+
+def surface_note(committed, valid_tool_names=None):
+ """The model-bound note for a committed surface (``""`` for the plain app window): barge-in
+ first, then the HUD read-the-window-below prior or the spoken-delegation contract."""
+ notes = []
+ if committed.get('interrupted'):
+ from tools.tts_streaming import SPEECH_INTERRUPTED_NOTE
+ notes.append(SPEECH_INTERRUPTED_NOTE)
+ render = _SURFACE_NOTES.get(committed.get('surface'))
+ if render is not None:
+ notes.append(render(committed, valid_tool_names))
+ return '\n\n'.join(note for note in notes if note)
+
+
+@contextmanager
+def surface_turn_scope(committed):
+ token = _surface_turn.set(committed)
+ try:
+ yield
+ finally:
+ _surface_turn.reset(token)
+
+
++def surface_voice_turn():
++ """Whether the executing admission is a spoken voice turn (``auxiliary.voice_chat`` route)."""
++ return bool((_surface_turn.get() or {}).get('voice_turn'))
++
++
+def surface_turn_note(agent):
+ """The executing admission's surface note, gated on the tools this agent actually has."""
+ committed = _surface_turn.get()
+ if not committed:
+ return ''
+ return surface_note(committed, getattr(agent, 'valid_tool_names', None))
diff --cc hermes_cli/config_defaults.py
index 674352b46a4,770fcc5a3a4..2f38976df3e
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@@ -2725,7 -2719,7 +2720,7 @@@ DEFAULT_CONFIG =
# Extra ports detection probes for an external llama-server (besides 8080).
"detect_ports": [],
},
-- "_config_version": 50, # Config schema version - bump this when adding new required fields
++ "_config_version": 51, # Config schema version - bump this when adding new required fields
}
diff --cc hermes_cli/config_migrations.py
index 62b1c4dc785,bd517c73f8a..51d6430907e
--- a/hermes_cli/config_migrations.py
+++ b/hermes_cli/config_migrations.py
@@@ -814,18 -833,8 +833,20 @@@ MIGRATIONS: Tuple[Tuple[int, Callable[[
(48, _migrate_to_48),
# 48 → 49: the seeded Vercel runtime pin is dropped so fresh sandboxes use the managed image (see _migrate_to_49).
(49, _migrate_to_49),
- # 49 → 50: cron.bot_chat_delivery_timeout_seconds is gone with the local `hermes chat`
+ # 49 → 50: security.tirith_* dropped; the bundled scanner is gone (see _migrate_to_50).
+ (50, _migrate_to_50),
++ # 50 → 51: cron.bot_chat_delivery_timeout_seconds is gone with the local `hermes chat`
+ # fallback lane it bounded. Bot Chat deliveries are admitted to the running gateway and
+ # settle on its durable receipt; there is no cron-side turn left to time out.
- (50, functools.partial(
++ (51, functools.partial(
+ _rewrite_key, section="cron", key="bot_chat_delivery_timeout_seconds", new=None,
+ match=lambda _cur: True,
+ added="removed cron.bot_chat_delivery_timeout_seconds",
+ message=(
+ " ✓ Removed cron.bot_chat_delivery_timeout_seconds — bot-chat deliveries are now "
+ "admitted to the target profile's running gateway and tracked by receipt, so cron no "
+ "longer runs (or times out) a Bot Chat turn of its own."),
+ extra_guard=lambda raw: "bot_chat_delivery_timeout_seconds" in raw)),
)
#: Steps triggered by a legacy key or identifier (a renamed or retired key, a removed plugin or
diff --cc hermes_state_runtime.py
index f85a43d28f2,00000000000..53e884d535d
mode 100644,000000..100644
--- a/hermes_state_runtime.py
+++ b/hermes_state_runtime.py
@@@ -1,700 -1,0 +1,700 @@@
+"""Canonical runtime transactions; callers authorize and resolve session identity.
+
+No execution, transport, or authority objects live here. Every mutation uses the
+SessionDB transaction owner, including its inode guard and SQLite retry policy.
+"""
+import json
+import uuid
+
+from agent.conversation_compression_archive import ABSORBED_ROW_IDS
+from agent.message_metadata import CANONICAL_ROW, DB_ROW_SNAPSHOT, PERSISTENCE_ONLY_MESSAGE_FIELDS
+from gateway.session_admission import admission_fingerprint
+
+
+class RuntimeStoreError(ValueError):
+ def __init__(self, reason: str):
+ self.reason = reason
+ super().__init__(reason)
+
+
+def _text(value):
+ if not isinstance(value, str) or not value or len(value) > 1024:
+ raise RuntimeStoreError('invalid_params')
+ return value
+
+
+def _json(value):
+ if not isinstance(value, dict):
+ raise RuntimeStoreError('invalid_params')
+ try:
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False)
+ except (TypeError, ValueError, UnicodeError) as exc:
+ raise RuntimeStoreError('invalid_params') from exc
+
+
+def _epoch(conn, epoch):
+ row = conn.execute('SELECT epoch FROM runtime_epoch WHERE singleton=1').fetchone()
+ if type(epoch) is not int or row is None or row[0] != epoch:
+ raise RuntimeStoreError('stale_epoch')
+
+
+def _session(conn, session_id):
+ row = conn.execute('SELECT * FROM sessions WHERE id=?', (session_id,)).fetchone()
+ if row is None:
+ raise RuntimeStoreError('not_found')
+ return row
+
+
+def _admission(conn, admission_id):
+ row = conn.execute('SELECT * FROM session_admissions WHERE admission_id=?', (admission_id,)).fetchone()
+ if row is None:
+ from hermes_state_terminal import terminal_admission
+ row = terminal_admission(conn, admission_id)
+ if row is None:
+ raise RuntimeStoreError('not_found')
+ return row
+
+
+def _retire_admission_workers(conn, row, owner_epoch):
+ """Retire the worker rows this admission's generation owns on BOTH the logical
+ FIFO owner and its current physical transcript (reset/compression move the private
+ worker assignment to the child while target_session_id stays the logical ID)."""
+ lineage = json.loads(row['lineage_json'])
+ targets = list({row['target_session_id'], lineage[-1] if lineage else row['target_session_id']})
+ conn.execute(f"UPDATE worker_executions SET status='terminal' WHERE session_id IN ({','.join('?' * len(targets))}) "
+ "AND generation=? AND owner_epoch=?", (*targets, row['generation'], owner_epoch))
+
+
+def _row(row):
+ if row is None:
+ return None
+ result = dict(row)
+ result['payload'] = json.loads(result.pop('payload_json'))
+ result.pop('payload_digest')
+ result.pop('lineage_json')
+ return result
+
+
+def begin_runtime_epoch(db, *, instance_id: str) -> int:
+ """Caller MUST hold the profile ownership lock, not merely an endpoint ticket."""
+ _text(instance_id)
+ def write(conn):
+ conn.execute('''INSERT INTO runtime_epoch(singleton,epoch,instance_id) VALUES(1,1,?)
+ ON CONFLICT(singleton) DO UPDATE SET epoch=runtime_epoch.epoch+1, instance_id=excluded.instance_id''', (instance_id,))
+ return conn.execute('SELECT epoch FROM runtime_epoch WHERE singleton=1').fetchone()[0]
+ return db._execute_write(write)
+
+
+def admit_session_input(db, *, epoch: int, principal_id: str, session_id: str,
+ request_id: str, payload: dict, intent: str = 'queue',
+ _authorize_write=None) -> dict:
+ """Admit input; the trusted private guard raises to refuse a NEW write.
+
+ The guard receives the owning transaction connection, must not commit it or
+ perform external effects, and may run again on SQLite retry. Exact existing
+ and terminal replays bypass it: they cannot create or change accepted work.
+ """
+ for value in (principal_id, session_id, request_id):
+ _text(value)
+ if intent not in ('queue', 'steer', 'redirect'):
+ raise RuntimeStoreError('invalid_params')
+ encoded = _json(payload)
+ from hermes_state_terminal import retry_terminal_admission
+ retired = retry_terminal_admission(db, epoch=epoch, principal_id=principal_id, session_id=session_id,
+ request_id=request_id, payload=payload, intent=intent)
+ if retired is not None:
+ return retired
+ digest = admission_fingerprint(canonical_target=session_id, payload={'input': json.loads(encoded), 'intent': intent})
+ def write(conn):
+ _epoch(conn, epoch)
+ _session(conn, session_id)
+ old = conn.execute('''SELECT * FROM session_admissions
+ WHERE principal_id=? AND target_session_id=? AND request_id=?''', (principal_id, session_id, request_id)).fetchone()
+ if old is not None:
+ if old['payload_digest'] != digest:
+ raise RuntimeStoreError('admission_conflict')
+ return _row(old)
+ if _authorize_write is not None:
+ _authorize_write(conn)
+ admission_id = uuid.uuid4().hex
+ conn.execute('''INSERT INTO session_admissions(admission_id,request_id,principal_id,
+ target_session_id,lineage_json,payload_json,payload_digest,intent,status,owner_epoch)
+ VALUES(?,?,?,?,?,?,?,?,'queued',?)''',
+ (admission_id, request_id, principal_id, session_id, json.dumps([session_id]), encoded, digest, intent, epoch))
+ return _row(_admission(conn, admission_id))
+ return db._execute_write(write)
+
+
+def get_session_admission(db, *, admission_id: str) -> dict | None:
+ with db._read_ctx() as conn:
+ from hermes_state_terminal import terminal_admission
+ row = conn.execute('SELECT * FROM session_admissions WHERE admission_id=?', (admission_id,)).fetchone()
+ return _row(row if row is not None else terminal_admission(conn, admission_id))
+
+
+def list_session_admissions(db, *, session_id: str, pending_only: bool = True) -> list[dict]:
+ with db._read_ctx() as conn:
+ return [_row(row) for row in conn.execute('''SELECT * FROM session_admissions
+ WHERE target_session_id=? AND (?=0 OR status!='terminal') ORDER BY seq''', (session_id, int(pending_only)))]
+
+
+def claim_session_input(db, *, epoch: int, session_id: str) -> dict | None:
+ def write(conn):
+ _epoch(conn, epoch)
+ session = _session(conn, session_id)
+ blocked = conn.execute("SELECT status FROM session_admissions WHERE target_session_id=? AND status IN ('started','unknown')", (session_id,)).fetchall()
+ if any(row[0] == 'unknown' for row in blocked):
+ raise RuntimeStoreError('unknown_execution')
+ if conn.execute("SELECT 1 FROM worker_executions WHERE session_id=? AND status='unknown'", (session_id,)).fetchone():
+ raise RuntimeStoreError('unknown_execution')
+ if blocked or conn.execute("SELECT 1 FROM worker_executions WHERE session_id=? AND status IN ('registered','running')", (session_id,)).fetchone():
+ return None
+ row = conn.execute("SELECT * FROM session_admissions WHERE target_session_id=? AND status='queued' ORDER BY seq LIMIT 1", (session_id,)).fetchone()
+ if row is None:
+ return None
+ generation = session['runtime_generation'] + 1
+ conn.execute('UPDATE sessions SET runtime_generation=? WHERE id=?', (generation, session_id))
+ changed = conn.execute("UPDATE session_admissions SET status='started',owner_epoch=?,generation=? WHERE admission_id=? AND status='queued'", (epoch, generation, row['admission_id']))
+ if changed.rowcount != 1:
+ raise RuntimeStoreError('stale_generation')
+ return _row(_admission(conn, row['admission_id']))
+ return db._execute_write(write)
+
+
+def settle_session_input(db, *, epoch: int, admission_id: str, generation: int, outcome: str,
+ result: dict | None = None) -> dict:
+ if outcome not in ('completed', 'interrupted', 'rejected', 'failed'):
+ raise RuntimeStoreError('invalid_params')
+ encoded = _json(result) if result is not None else None
+ def write(conn):
+ _epoch(conn, epoch)
+ row = _admission(conn, admission_id)
+ session = _session(conn, row['target_session_id'])
+ if (row['status'] != 'started' or row['owner_epoch'] != epoch
+ or type(generation) is not int or row['generation'] != generation
+ or session['runtime_generation'] != generation):
+ raise RuntimeStoreError('stale_generation')
+ _retire_admission_workers(conn, row, epoch)
+ if encoded is not None:
+ from hermes_state_terminal import RESULT_PREFIX
+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?) '
+ 'ON CONFLICT(key) DO UPDATE SET value=excluded.value',
+ (RESULT_PREFIX + admission_id, encoded))
+ conn.execute("UPDATE session_admissions SET status='terminal',outcome=? WHERE admission_id=?", (outcome, admission_id))
+ conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?', (row['target_session_id'],))
+ return _row(_admission(conn, admission_id))
+ return db._execute_write(write)
+
+
+def cancel_session_input(db, *, epoch: int, admission_id: str) -> dict:
+ def write(conn):
+ _epoch(conn, epoch)
+ row = _admission(conn, admission_id)
+ if row['status'] == 'unknown':
+ raise RuntimeStoreError('unknown_execution')
+ if row['status'] == 'started':
+ raise RuntimeStoreError('stale_generation')
+ if row['status'] == 'queued':
+ conn.execute("UPDATE session_admissions SET status='terminal',outcome='cancelled' WHERE admission_id=?", (admission_id,))
+ return _row(_admission(conn, admission_id))
+ return db._execute_write(write)
+
+
+def recover_session_inputs(db, *, epoch: int) -> int:
+ """Never replay started work. Live worker adoption is a separate explicit operation."""
+ def write(conn):
+ _epoch(conn, epoch)
+ conn.execute("UPDATE worker_executions SET status='unknown' WHERE status IN ('registered','running') AND owner_epoch!=?", (epoch,))
+ return conn.execute("UPDATE session_admissions SET status='unknown' WHERE status='started' AND owner_epoch!=?", (epoch,)).rowcount
+ return db._execute_write(write)
+
+
+def mutate_runtime_session(db, *, epoch: int, principal_id: str, session_id: str,
+ request_id: str, expected_revision: int,
+ operation: str, payload: dict, expected_generation: int | None = None,
+ _live_guard=None, _authorize_write=None, _prepare_only=False, _prepared=None) -> dict:
+ """Commit a closed metadata edit and its retry receipt in the same transaction.
+
+ Caller authorizes the principal and resolves the canonical session. These
+ metadata edits do not stop execution. Existing direct writers must migrate
+ before this seam can provide universal revision fencing.
+ """
+ for value in (principal_id, session_id, request_id):
+ _text(value)
+ if type(expected_revision) is not int or expected_revision < 0:
+ raise RuntimeStoreError('invalid_params')
+ from hermes_state_mutations import validate_action, apply_action
+ validate_action(operation, payload)
+ if expected_generation is not None and (type(expected_generation) is not int or expected_generation < 0):
+ raise RuntimeStoreError('invalid_params')
+ if operation in {'delete', 'rewind', 'reset', 'branch', 'model', 'compress'} and expected_generation is None:
+ raise RuntimeStoreError('invalid_params')
+ # Snapshot caller data before waiting for the writer lock.
+ payload = json.loads(_json(payload))
+ key = 'gateway.mutation.v1.' + admission_fingerprint(
+ canonical_target=session_id, payload={'principal': principal_id, 'request': request_id})
+ fingerprint = {'operation': operation, 'payload': payload, 'expected_revision': expected_revision}
+ if expected_generation is not None:
+ fingerprint['expected_generation'] = expected_generation
+ digest = admission_fingerprint(canonical_target=session_id, payload=fingerprint)
+
+ def write(conn):
+ _epoch(conn, epoch)
+ old = conn.execute('SELECT value FROM state_meta WHERE key=?', (key,)).fetchone()
+ if old is not None:
+ receipt = json.loads(old[0])
+ if receipt['digest'] != digest:
+ raise RuntimeStoreError('admission_conflict')
+ return receipt['result']
+ session = conn.execute('SELECT * FROM sessions WHERE id=?', (session_id,)).fetchone()
+ if session is None and operation != 'import':
+ raise RuntimeStoreError('not_found')
+ revision = session['runtime_revision'] if session else 0
+ if revision != expected_revision:
+ raise RuntimeStoreError('revision_conflict')
+ if expected_generation is not None and (session is None or session['runtime_generation'] != expected_generation):
+ raise RuntimeStoreError('stale_generation')
+ if _live_guard is not None:
+ from hermes_state_mutation_guards import delete_targets
+ targets = delete_targets(conn, session_id) if operation == 'delete' else [session_id]
+ _live_guard(targets)
+ if _authorize_write is not None:
+ _authorize_write(conn)
+ if _prepare_only:
+ from hermes_state_mutation_prepared import local_snapshot
+ return {'snapshot': local_snapshot(db, conn, session_id)}
+ affected, projection = apply_action(db, conn, session_id, operation, payload, prepared=_prepared)
+ conn.executemany('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?',
+ [(target,) for target in affected])
+ updated = conn.execute('SELECT * FROM sessions WHERE id=?', (session_id,)).fetchone()
+ result = {'session_id': session_id, 'revision': updated['runtime_revision'] if updated else expected_revision + 1,
+ 'operation': operation, **projection}
+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)',
+ (key, _json({'digest': digest, 'result': result})))
+ return result
+ return db._execute_write(write)
+
+
+_IMPORT_KEY = 'gateway.prompt_admissions_import.v1'
+
+
+def _canonical_chain(conn, session_id):
+ # Same selector as SessionDB.get_compression_chain, on OUR transaction connection.
+ from hermes_state_compression import _CHAIN_STEP_SQL
+ _session(conn, session_id)
+ chain = [session_id]
+ for _ in range(100):
+ child = conn.execute(_CHAIN_STEP_SQL, (chain[-1],)).fetchone()
+ if child is None:
+ return chain
+ if child['id'] in chain:
+ raise RuntimeStoreError('admission_conflict')
+ chain.append(child['id'])
+ raise RuntimeStoreError('admission_conflict')
+
+
+def _import_legacy_row(conn, row, epoch, principal_id):
+ for field in ('admission_id', 'target_session_id', 'root'):
+ _text(row[field])
+ lineage = json.loads(row['lineage'])
+ if not isinstance(lineage, list) or row['target_session_id'] not in lineage:
+ raise RuntimeStoreError('invalid_params')
+ payload = json.loads(row['payload'])
+ encoded = _json(payload)
+ intent = payload.get('intent', 'queue')
+ intent = 'redirect' if intent == 'interrupt' else intent
+ if intent not in ('queue', 'steer', 'redirect') or row['status'] not in ('queued', 'started', 'unknown', 'terminal'):
+ raise RuntimeStoreError('invalid_params')
+ chain = _canonical_chain(conn, row['target_session_id'])
+ target = chain[-1]
+ status = 'unknown' if row['status'] == 'started' else row['status']
+ generation = row['generation']
+ if generation is None and status == 'unknown':
+ generation = _session(conn, target)['runtime_generation'] + 1
+ if generation is not None and (type(generation) is not int or generation < 0):
+ raise RuntimeStoreError('invalid_params')
+ digest = admission_fingerprint(canonical_target=target, payload={'input': payload, 'intent': intent})
+ conn.execute("""INSERT INTO session_admissions(admission_id,request_id,principal_id,
+ target_session_id,lineage_json,payload_json,payload_digest,intent,status,outcome,owner_epoch,generation)
+ VALUES(?,?,?,?,?,?,?,?,?,?,?,?)""", (row['admission_id'], row['admission_id'], principal_id,
+ target, json.dumps(chain), encoded, digest, intent, status, row['outcome'], epoch, generation))
+ if generation is not None:
+ conn.execute('UPDATE sessions SET runtime_generation=MAX(runtime_generation,?) WHERE id=?', (generation, target))
+
+
+def import_legacy_session_admissions(db, *, epoch: int, source_path, principal_id: str,
+ writers_drained: bool) -> int:
+ """Import a frozen legacy snapshot; original file remains rollback evidence.
+
+ The caller proves the old writers are drained before invoking this function.
+ Fingerprinting uses SQL snapshot data, never a raw open/close on a live inode.
+ """
+ from contextlib import closing
+ from pathlib import Path
+ import hashlib
+ import sqlite3
+ from hermes_cli.sqlite_safe_read import connect_tracked
+ if writers_drained is not True:
+ raise RuntimeStoreError('invalid_params')
+ _text(principal_id)
+ source_path = Path(source_path).resolve(strict=True)
+ with closing(connect_tracked(source_path.as_uri() + '?mode=ro', uri=True)) as source:
+ source.row_factory = sqlite3.Row
+ source.execute('PRAGMA query_only=ON')
+ source.execute('BEGIN')
+ rows = [dict(r) for r in source.execute('SELECT * FROM admissions ORDER BY seq')]
+ executions = []
+ if source.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='executions'").fetchone():
+ executions = [dict(r) for r in source.execute('SELECT * FROM executions ORDER BY root')]
+ fingerprint = hashlib.sha256(_json({'rows': rows, 'executions': executions}).encode('utf-8')).hexdigest()
+ marker = _json({'source': str(source_path), 'fingerprint': fingerprint, 'imported_id_count': len(rows), 'principal_id': principal_id})
+ def write(conn):
+ _epoch(conn, epoch)
+ old = conn.execute('SELECT value FROM state_meta WHERE key=?', (_IMPORT_KEY,)).fetchone()
+ if old is not None:
+ if old[0] != marker:
+ raise RuntimeStoreError('admission_conflict')
+ return 0
+ for execution in executions:
+ generation = execution['generation']
+ if type(generation) is not int or generation < 0:
+ raise RuntimeStoreError('invalid_params')
+ target = _canonical_chain(conn, _text(execution['root']))[-1]
+ conn.execute('UPDATE sessions SET runtime_generation=MAX(runtime_generation,?) WHERE id=?', (generation, target))
+ for row in rows:
+ _import_legacy_row(conn, row, epoch, principal_id)
+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)', (_IMPORT_KEY, marker))
+ return len(rows)
+ return db._execute_write(write)
+
+
+def resolve_unknown_session_input(db, *, epoch: int, admission_id: str, generation: int) -> dict:
+ """Explicit operator acknowledgement; resolves uncertainty, never requeues it."""
+ def write(conn):
+ _epoch(conn, epoch)
+ row = _admission(conn, admission_id)
+ if type(generation) is not int or row['status'] != 'unknown' or row['generation'] != generation:
+ raise RuntimeStoreError('stale_generation')
+ _retire_admission_workers(conn, row, row['owner_epoch'])
+ conn.execute("UPDATE session_admissions SET status='terminal',outcome='interrupted' WHERE admission_id=?", (admission_id,))
+ conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?', (row['target_session_id'],))
+ return _row(_admission(conn, admission_id))
+ return db._execute_write(write)
+
+
+def _worker_public(row):
+ result = dict(row)
+ result.pop('adoption_digest')
+ return result
+
+
+def _worker_assignment(conn, execution_id, session_id, generation):
+ row = conn.execute('SELECT * FROM worker_executions WHERE execution_id=?', (execution_id,)).fetchone()
+ if row is None:
+ raise RuntimeStoreError('not_found')
+ if row['session_id'] != session_id:
+ raise RuntimeStoreError('permission_denied')
+ if (type(generation) is not int or row['generation'] != generation
+ or _session(conn, session_id)['runtime_generation'] != generation):
+ raise RuntimeStoreError('stale_generation')
+ return row
+
+
+def _linked_worker_admission(conn, session_id, generation, owner_epoch, statuses):
+ placeholders = ','.join('?' for _ in statuses)
+ rows = conn.execute(f"""SELECT * FROM session_admissions
+ WHERE generation=? AND owner_epoch=? AND status IN ({placeholders})
+ AND (target_session_id=? OR EXISTS (
+ SELECT 1 FROM json_each(session_admissions.lineage_json) WHERE value=?
+ )) ORDER BY seq""",
+ (generation, owner_epoch, *statuses, session_id, session_id)).fetchall()
+ if len(rows) > 1:
+ raise RuntimeStoreError('admission_conflict')
+ return rows[0] if rows else None
+
+
+def _secret_digest(secret):
+ import hashlib
+ _text(secret)
+ return hashlib.sha256(secret.encode('utf-8')).hexdigest()
+
+
+def register_worker_execution(db, *, epoch: int, execution_id: str, session_id: str,
+ generation: int, kind: str, adoption_secret: str, require_idle: bool = False) -> dict:
+ for value in (execution_id, session_id):
+ _text(value)
+ if kind not in ('cron', 'child', 'compute', 'kanban'):
+ raise RuntimeStoreError('invalid_params')
+ digest = _secret_digest(adoption_secret)
+ def write(conn):
+ _epoch(conn, epoch)
+ session = _session(conn, session_id)
+ if type(generation) is not int or session['runtime_generation'] != generation:
+ raise RuntimeStoreError('stale_generation')
+ old = conn.execute('SELECT * FROM worker_executions WHERE execution_id=?', (execution_id,)).fetchone()
+ if old is not None:
+ if (old['session_id'], old['generation'], old['kind'], old['owner_epoch'], old['adoption_digest']) != (session_id, generation, kind, epoch, digest):
+ raise RuntimeStoreError('admission_conflict')
+ return _worker_public(old)
+ if require_idle and conn.execute("SELECT 1 FROM session_admissions WHERE target_session_id=? AND status!='terminal'", (session_id,)).fetchone():
+ raise RuntimeStoreError('stale_generation')
+ if conn.execute("SELECT 1 FROM worker_executions WHERE session_id=? AND status!='terminal'", (session_id,)).fetchone():
+ raise RuntimeStoreError('stale_generation')
+ if conn.execute("SELECT 1 FROM session_admissions WHERE target_session_id=? AND status='unknown'", (session_id,)).fetchone():
+ raise RuntimeStoreError('unknown_execution')
+ conn.execute("""INSERT INTO worker_executions(execution_id,session_id,kind,owner_epoch,generation,status,adoption_digest)
+ VALUES(?,?,?,?,?,'registered',?)""", (execution_id, session_id, kind, epoch, generation, digest))
+ return _worker_public(_worker_assignment(conn, execution_id, session_id, generation))
+ return db._execute_write(write)
+
+
+def adopt_worker_execution(db, *, epoch: int, execution_id: str, session_id: str,
+ generation: int, adoption_secret: str) -> dict:
+ """Authority first verifies the original producer claim and live worker proof."""
+ import hmac
+ digest = _secret_digest(adoption_secret)
+ def write(conn):
+ _epoch(conn, epoch)
+ row = _worker_assignment(conn, execution_id, session_id, generation)
+ if row['status'] == 'terminal':
+ raise RuntimeStoreError('stale_generation')
+ if not hmac.compare_digest(row['adoption_digest'], digest):
+ raise RuntimeStoreError('permission_denied')
+ linked = _linked_worker_admission(
+ conn, session_id, generation, row['owner_epoch'], ('started', 'unknown'))
+ if linked is not None:
+ changed = conn.execute("""UPDATE session_admissions SET owner_epoch=?,status='started'
+ WHERE admission_id=? AND generation=? AND owner_epoch=?
+ AND status IN ('started','unknown')""",
+ (epoch, linked['admission_id'], generation, row['owner_epoch']))
+ if changed.rowcount != 1:
+ raise RuntimeStoreError('stale_generation')
+ changed = conn.execute(
+ "UPDATE worker_executions SET owner_epoch=?,status='running' WHERE execution_id=?",
+ (epoch, execution_id))
+ if changed.rowcount != 1:
+ raise RuntimeStoreError('stale_generation')
+ return _worker_public(_worker_assignment(conn, execution_id, session_id, generation))
+ return db._execute_write(write)
+
+
+def persist_worker_message(db, *, epoch: int, execution_id: str, session_id: str,
+ generation: int, sequence: int, role: str, content: str) -> dict:
+ """Typed text append primitive, NOT a general remote SessionDB implementation.
+
+ Structured tools/reasoning/usage/compression require their own typed operations.
+ No caller-supplied callable can commit inside this transaction.
+ """
+ import time
+ if type(sequence) is not int or sequence < 1 or role not in ('user', 'assistant', 'system') or not isinstance(content, str):
+ raise RuntimeStoreError('invalid_params')
+ digest = admission_fingerprint(canonical_target=session_id, payload={'operation': 'append_text', 'role': role, 'content': content})
+ def write(conn):
+ _epoch(conn, epoch)
+ row = _worker_assignment(conn, execution_id, session_id, generation)
+ if row['owner_epoch'] != epoch:
+ raise RuntimeStoreError('stale_epoch')
+ old = conn.execute('SELECT * FROM worker_receipts WHERE execution_id=? AND sequence=?', (execution_id, sequence)).fetchone()
+ if old is not None:
+ if old['payload_digest'] != digest:
+ raise RuntimeStoreError('admission_conflict')
+ return json.loads(old['result_json'])
+ if row['status'] == 'terminal':
+ raise RuntimeStoreError('stale_generation')
+ if sequence != row['last_sequence'] + 1:
+ raise RuntimeStoreError('invalid_params')
+ db._check_transcript_write_guards(conn, session_id, None)
+ now = time.time()
+ message = conn.execute('INSERT INTO messages(session_id,role,content,timestamp) VALUES(?,?,?,?)', (session_id, role, db._encode_content(content), now))
+ conn.execute('UPDATE sessions SET message_count=message_count+1,last_activity_at=?,runtime_revision=runtime_revision+1 WHERE id=?', (now, session_id))
+ result = {'message_id': message.lastrowid}
+ conn.execute('INSERT INTO worker_receipts(execution_id,sequence,payload_digest,result_json) VALUES(?,?,?,?)', (execution_id, sequence, digest, json.dumps(result, ensure_ascii=True, allow_nan=False)))
+ conn.execute("UPDATE worker_executions SET last_sequence=?,status='running' WHERE execution_id=?", (sequence, execution_id))
+ return result
+ return db._execute_write(write)
+
+
+
+
+_MESSAGE_FIELDS = frozenset({
+ 'role', 'content', 'tool_name', 'tool_calls', 'tool_call_id', 'token_count',
+ 'finish_reason', 'reasoning', 'reasoning_content', 'reasoning_details',
+ 'codex_reasoning_items', 'codex_message_items', 'platform_message_id', 'message_id',
+ 'observed', 'effect_disposition', '_compressed_summary', 'timestamp', 'api_content',
+ 'display_kind', 'display_metadata', '_row_id', '_canonical_content', DB_ROW_SNAPSHOT, CANONICAL_ROW,
+ # Main's durable message identity (message_uid / merge witness / tool-call uids) and the alternation
+ # repair's row counts ride every persisted dict; the owner's insert and coverage read them.
+}) | PERSISTENCE_ONLY_MESSAGE_FIELDS | {ABSORBED_ROW_IDS}
+# Row state the owner's transcript repair stamps on each message (main mutates the caller's dict
+# in place; a worker gets it back as an annotation). None = absent, so a stale adoption is cleared.
+_ROW_ANNOTATION_KEYS = ('_row_id', 'timestamp', DB_ROW_SNAPSHOT, CANONICAL_ROW)
+
+
+def row_annotations(messages):
+ return [{key: msg.get(key) for key in _ROW_ANNOTATION_KEYS} for msg in messages]
+
+
+def _worker_append(db, conn, session_id, payload):
+ if set(payload) - {'messages', 'turn_lease_holder'} or 'messages' not in payload:
+ raise RuntimeStoreError('invalid_params')
+ messages = payload['messages']
+ if not isinstance(messages, list) or len(messages) > 1000:
+ raise RuntimeStoreError('invalid_params')
+ for msg in messages:
+ if (not isinstance(msg, dict) or set(msg) - _MESSAGE_FIELDS
+ or msg.get('role') not in ('user', 'assistant', 'system', 'tool')):
+ raise RuntimeStoreError('invalid_params')
+ # Existing row annotations can adopt only rows in THIS transcript.
+ if '_row_id' in msg and not conn.execute(
+ 'SELECT 1 FROM messages WHERE id=? AND session_id=?',
+ (msg['_row_id'], session_id)).fetchone():
+ raise RuntimeStoreError('permission_denied')
+ holder = payload.get('turn_lease_holder')
+ if holder is not None:
+ _text(holder)
+ count = db._append_messages_in_transaction(conn, session_id, messages, turn_lease_holder=holder)
+ return {'count': count, 'annotations': row_annotations(messages)}
+
+
+def _worker_turn(db, conn, session_id, payload, operation):
+ import time
+ from hermes_state_compression import _claim_lease_row
+ from hermes_state import _compression_lock_holder_process_is_dead
+ allowed = {'holder'} if operation == 'turn.release' else {'holder', 'ttl_seconds'}
+ if set(payload) != allowed:
+ raise RuntimeStoreError('invalid_params')
+ holder = _text(payload['holder'])
+ ttl = payload.get('ttl_seconds', 300)
+ if type(ttl) not in (float, int) or not 0.1 <= ttl <= 3600:
+ raise RuntimeStoreError('invalid_params')
+ key = db._session_turn_lease_key_on_conn(conn, session_id)
+ now = time.time()
+ if operation == 'turn.acquire':
+ value = _claim_lease_row(conn, 'session_turn_leases', 'conversation_id', key,
+ holder, now, now + ttl,
+ lambda h, e: float(e) <= now or _compression_lock_holder_process_is_dead(h))[0]
+ elif operation == 'turn.renew':
+ value = conn.execute('UPDATE session_turn_leases SET expires_at=? WHERE conversation_id=? AND holder=?',
+ (now + ttl, key, holder)).rowcount > 0
+ else:
+ conn.execute('DELETE FROM session_turn_leases WHERE conversation_id=? AND holder=?', (key, holder))
+ value = None
+ return {'value': value}
+
+
+def _worker_usage(db, conn, session_id, payload, *, auxiliary=False):
+ from hermes_state_usage import _MODEL_USAGE_FIELDS, _TOKEN_COUNTERS
+ if not auxiliary:
+ # ``source`` feeds the legacy path's row-existence guard (#111999); an authority-owned
+ # session row was minted with its real surface at admission, so nothing to repair here.
+ payload = {k: v for k, v in payload.items() if k != 'source'}
- allowed = (_MODEL_USAGE_FIELDS - {'billing_mode', 'actual_cost_usd', 'cost_status', 'cost_source'} | {'task'}) if auxiliary else (_MODEL_USAGE_FIELDS | {'pricing_version', 'absolute'})
++ allowed = (_MODEL_USAGE_FIELDS - {'billing_mode', 'actual_cost_usd', 'cost_status', 'cost_source'} | {'task'}) if auxiliary else (_MODEL_USAGE_FIELDS | {'pricing_version', 'absolute', 'task'})
+ if set(payload) - allowed:
+ raise RuntimeStoreError('invalid_params')
+ for key, value in payload.items():
+ if key in (*_TOKEN_COUNTERS, 'api_call_count'):
+ valid = type(value) is int and 0 <= value <= 2**53
+ elif key in ('estimated_cost_usd', 'actual_cost_usd'):
+ valid = value is None or (type(value) in (int, float) and 0 <= value <= 1e12)
+ elif key == 'absolute':
+ valid = type(value) is bool
+ else:
+ valid = value is None or (isinstance(value, str) and len(value) <= 4096)
+ if not valid:
+ raise RuntimeStoreError('invalid_params')
+ if auxiliary:
+ if not payload.get('task'):
+ raise RuntimeStoreError('invalid_params')
+ db._record_model_usage(conn, session_id, **({'api_call_count': 1} | payload))
+ else:
+ db._update_token_counts_in_transaction(conn, session_id, **payload)
+ return {'value': None}
+
+
+def _worker_finish(db, conn, session_id, payload):
+ if payload:
+ raise RuntimeStoreError('invalid_params')
+ return {'status': 'terminal'}
+
+
+def mutate_worker_execution(db, *, epoch, execution_id, session_id, generation,
+ sequence, operation, payload):
+ """One closed durable mutation and receipt; never call a self-committing API here."""
+ from hermes_state_worker_context import worker_context, worker_prompt, worker_sidecars, worker_tool_names
+ from hermes_state_worker_compression import WORKER_COMPRESSION_HANDLERS, worker_receipt_assignment
+ from hermes_state_worker_lifecycle import WORKER_LIFECYCLE_HANDLERS
+ handlers = {
+ **WORKER_LIFECYCLE_HANDLERS,
+ **WORKER_COMPRESSION_HANDLERS,
+ 'session.context': worker_context,
+ 'session.prompt': worker_prompt,
+ 'session.sidecars': worker_sidecars,
+ 'session.tools': worker_tool_names,
+ 'transcript.append': _worker_append,
+ 'execution.finish': _worker_finish,
+ 'usage.main': _worker_usage,
+ 'usage.auxiliary': lambda db, conn, sid, p: _worker_usage(db, conn, sid, p, auxiliary=True),
+ **{name: (lambda db, conn, sid, p, op=name: _worker_turn(db, conn, sid, p, op))
+ for name in ('turn.acquire', 'turn.renew', 'turn.release')},
+ }
+ if type(sequence) is not int or sequence < 1 or not isinstance(operation, str) or operation not in handlers:
+ raise RuntimeStoreError('invalid_params')
+ encoded = _json(payload)
+ if len(encoded.encode('utf-8', errors='surrogatepass')) > 4 * 1024 * 1024:
+ raise RuntimeStoreError('invalid_params')
+ digest = admission_fingerprint(canonical_target=session_id,
+ payload={'operation': operation, 'payload': json.loads(encoded)})
+ def write(conn):
+ _epoch(conn, epoch)
+ row = worker_receipt_assignment(conn, execution_id, session_id, generation, sequence, digest)
+ if row['owner_epoch'] != epoch:
+ raise RuntimeStoreError('stale_epoch')
+ old = conn.execute('SELECT * FROM worker_receipts WHERE execution_id=? AND sequence=?',
+ (execution_id, sequence)).fetchone()
+ if old is not None:
+ if old['payload_digest'] != digest:
+ raise RuntimeStoreError('admission_conflict')
+ return json.loads(old['result_json'])
+ if row['status'] not in ('registered', 'running'):
+ raise RuntimeStoreError('stale_generation')
+ if sequence != row['last_sequence'] + 1:
+ raise RuntimeStoreError('invalid_params')
+ # Each SQLite retry gets fresh rows; rolled-back annotations must not escape.
+ result = handlers[operation](db, conn, session_id, json.loads(encoded))
+ conn.execute('INSERT INTO worker_receipts(execution_id,sequence,payload_digest,result_json) VALUES(?,?,?,?)',
+ (execution_id, sequence, digest, json.dumps(result, ensure_ascii=True, allow_nan=False)))
+ conn.execute("UPDATE worker_executions SET last_sequence=?,status=? WHERE execution_id=?",
+ (sequence, 'terminal' if operation == 'execution.finish' else 'running', execution_id))
+ conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?', (session_id,))
+ return result
+ return db._execute_write(write, patience_s=db._TRANSCRIPT_WRITE_PATIENCE_S)
+
+
+def finish_worker_execution(db, *, epoch: int, execution_id: str, session_id: str,
+ generation: int) -> dict:
+ def write(conn):
+ _epoch(conn, epoch)
+ row = _worker_assignment(conn, execution_id, session_id, generation)
+ if row['owner_epoch'] != epoch:
+ raise RuntimeStoreError('stale_epoch')
+ if row['status'] == 'terminal':
+ return _worker_public(row)
+ linked = _linked_worker_admission(conn, session_id, generation, epoch, ('started',))
+ changed = conn.execute(
+ "UPDATE worker_executions SET status='terminal' WHERE execution_id=? AND status!='terminal'",
+ (execution_id,))
+ if changed.rowcount != 1:
+ raise RuntimeStoreError('stale_generation')
+ if linked is not None:
+ changed = conn.execute("""UPDATE session_admissions
+ SET status='terminal',outcome='completed'
+ WHERE admission_id=? AND status='started' AND owner_epoch=? AND generation=?""",
+ (linked['admission_id'], epoch, generation))
+ if changed.rowcount != 1:
+ raise RuntimeStoreError('stale_generation')
+ conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?',
+ (linked['target_session_id'],))
+ result = _worker_public(row)
+ result['status'] = 'terminal'
+ return result
+ return db._execute_write(write)
diff --cc hermes_state_usage.py
index 9c997a1c0a6,18909ec26e9..4ad2822d550
--- a/hermes_state_usage.py
+++ b/hermes_state_usage.py
@@@ -276,32 -276,21 +276,34 @@@ class SessionUsageMixin
actual_cost_usd: Optional[float]=None, cost_status: Optional[str]=None, cost_source: Optional[str]=None,
pricing_version: Optional[str]=None, billing_provider: Optional[str]=None, billing_base_url: Optional[str]=None,
billing_mode: Optional[str]=None, api_call_count: int=0, absolute: bool=False,
- source: Optional[str]=None,
+ source: Optional[str]=None, task: str = "",
) -> None:
- """Update token counters and backfill model if unset. *absolute*=False increments
- (per-API-call deltas, CLI path); *absolute*=True sets directly (gateway path,
- where the cached agent holds cumulative totals). ``source`` is the session's real surface
- for the row-existence guard; callers that don't know it leave the placeholder. ``task`` names a
- per-turn route (``voice_chat``): its calls count in the session totals and land in
- ``session_model_usage`` under that task, but never become the session's recorded route."""
- usage = {k: v for k, v in locals().items() if k in _MODEL_USAGE_FIELDS}
+ """Update totals and route attribution, ensuring the legacy missing-row backfill.
+ *absolute*=False increments (per-API-call deltas, CLI path); *absolute*=True sets directly
+ (gateway path, where the cached agent holds cumulative totals). ``source`` is the session's
- real surface for the row-existence guard; callers that don't know it leave the placeholder."""
++ real surface for the row-existence guard; callers that don't know it leave the placeholder.
++ ``task`` names a per-turn route (``voice_chat``): its calls count in the session totals and
++ land in ``session_model_usage`` under that task, but never become the session's recorded route."""
+ values = dict(locals())
+ values.pop('self')
+ values.pop('session_id')
+ values.pop('source')
# Ensure the row exists: under concurrent load create_session() may have failed on
# locking, and the UPDATE would silently affect 0 rows. When this guard is the first
# writer it must carry the agent's real source: the turn lease treats an existing row as
# proof the create already happened, so the creator never returns to repair an anonymous
# ``unknown`` placeholder and the session stays a phantom for life (#111999).
self._insert_session_row(session_id, source or "unknown", model=model)
+ self._execute_write(lambda conn: self._update_token_counts_in_transaction(conn, session_id, **values))
+
+ def _update_token_counts_in_transaction(
+ self, conn, session_id: str, input_tokens: int=0, output_tokens: int=0, model: str=None, cache_read_tokens: int=0,
+ cache_write_tokens: int=0, reasoning_tokens: int=0, estimated_cost_usd: Optional[float]=None,
+ actual_cost_usd: Optional[float]=None, cost_status: Optional[str]=None, cost_source: Optional[str]=None,
+ pricing_version: Optional[str]=None, billing_provider: Optional[str]=None, billing_base_url: Optional[str]=None,
- billing_mode: Optional[str]=None, api_call_count: int=0, absolute: bool=False,
++ billing_mode: Optional[str]=None, api_call_count: int=0, absolute: bool=False, task: str="",
+ ) -> None:
+ usage = {k: v for k, v in locals().items() if k in _MODEL_USAGE_FIELDS}
sql = _TOKEN_UPDATE_ABSOLUTE_SQL if absolute else _TOKEN_UPDATE_DELTA_SQL
has_usage = bool(input_tokens or output_tokens or cache_read_tokens or cache_write_tokens or reasoning_tokens
or api_call_count or estimated_cost_usd)
@@@ -324,26 -313,28 +326,26 @@@
# of how many times the user switches. See #51607.
record_model_usage = (not absolute) and has_usage
- def _do(conn):
- row = conn.execute(
- "SELECT model, billing_provider, api_call_count FROM sessions WHERE id = ?", (session_id,),
- ).fetchone()
- existing = dict(row) if row is not None else {}
- # create_session records the requested route before any API call. If that fails
- # and fallback succeeds, the first accounted usage is the authoritative route;
- # after that keep the row as is (one row cannot represent mixed usage).
- first_accounted_route = (
- not task and int(existing.get("api_call_count") or 0) == 0 and has_accounted_usage and bool(model)
- and bool(billing_provider)
- and (existing.get("model") != model or existing.get("billing_provider") != billing_provider)
- )
- if first_accounted_route:
- conn.execute("""UPDATE sessions
- SET model = ?, billing_provider = ?,
- billing_base_url = ?, billing_mode = ?
- WHERE id = ?""", (model, billing_provider, billing_base_url, billing_mode, session_id))
- conn.execute(sql, params)
- if record_model_usage:
- self._record_model_usage(conn, session_id, task=task, **usage)
- self._execute_write(_do)
+ row = conn.execute(
+ "SELECT model, billing_provider, api_call_count FROM sessions WHERE id = ?", (session_id,),
+ ).fetchone()
+ existing = dict(row) if row is not None else {}
+ # create_session records the requested route before any API call. If that fails
+ # and fallback succeeds, the first accounted usage is the authoritative route;
+ # after that keep the row as is (one row cannot represent mixed usage).
+ first_accounted_route = (
- int(existing.get("api_call_count") or 0) == 0 and has_accounted_usage and bool(model)
++ not task and int(existing.get("api_call_count") or 0) == 0 and has_accounted_usage and bool(model)
+ and bool(billing_provider)
+ and (existing.get("model") != model or existing.get("billing_provider") != billing_provider)
+ )
+ if first_accounted_route:
+ conn.execute("""UPDATE sessions
+ SET model = ?, billing_provider = ?,
+ billing_base_url = ?, billing_mode = ?
+ WHERE id = ?""", (model, billing_provider, billing_base_url, billing_mode, session_id))
+ conn.execute(sql, params)
+ if record_model_usage:
- self._record_model_usage(conn, session_id, **usage)
++ self._record_model_usage(conn, session_id, task=task, **usage)
def _record_model_usage(
self, conn, session_id: str, *, model: Optional[str]=None, billing_provider: Optional[str]=None,
diff --cc tests/agent/test_welcome_tier_recovery.py
index c7e38ccfd74,431f209d5da..2b5e39034d1
--- a/tests/agent/test_welcome_tier_recovery.py
+++ b/tests/agent/test_welcome_tier_recovery.py
@@@ -254,3 -258,70 +258,78 @@@ class TestTerminalResultsCarryTheFreeTi
error_msg="503", api_kwargs=None, api_messages=[], messages=[], conversation_history=[],
api_call_count=3, approx_tokens=10, provider="nous", base_url=PAID, model="hermes-4")
assert "free_tier" not in result
+
+
+ def _plain_429(retry_after: int) -> MockAPIError:
+ """A 429 with no structured welcome refusal: only the provider's ``retry_after``."""
+ return _gateway_error(429, {"error": {"message": "Rate limit exceeded", "retry_after": retry_after}})
+
+
+ def _backoff_agent(**overrides):
+ agent = _agent(_client_log_context=lambda: "", **overrides)
+ agent.emitted, agent.buffered, agent.waits = [], [], []
+ agent._emit_diagnostic_status = agent.emitted.append
+ agent._buffer_diagnostic_status = agent.buffered.append
+ agent._emit_diagnostic_wait = agent.waits.append
+ return agent
+
+
+ class TestFreeTierCooldownCutoff:
+ """Q9: an attended session on the free model ends the turn at once with the reset time; a
+ delegated child, a library caller and an unattended run keep waiting."""
+
+ @pytest.fixture(autouse=True)
+ def _no_inherited_source(self, monkeypatch):
+ for name in ("HERMES_SESSION_SOURCE", "HERMES_SINGLE_QUERY_SESSION", "HERMES_SESSION_SOURCE_EXPLICIT"):
+ monkeypatch.delenv(name, raising=False)
+
+ def test_an_attended_desktop_session_ends_the_turn_and_names_the_reset(self):
+ from agent.turn_recovery import free_tier_cooldown_ends_turn, max_retries_exhausted_result
+ err = _plain_429(90)
+ assert free_tier_cooldown_ends_turn(_agent(platform="desktop"), err, WELCOME) is True
+ result = max_retries_exhausted_result(
+ TestTerminalResultsCarryTheFreeTierBlock._terminal_agent(), err, _classify(err), attempts=1,
+ is_rate_limited=True, error_msg="429", api_kwargs=None, api_messages=[], messages=[],
+ conversation_history=[], api_call_count=1, approx_tokens=10, provider="nous", base_url=WELCOME,
+ model="nous/welcome")
+ assert "resets in ~2 min" in result["final_response"]
+
+ def test_a_subagent_of_a_desktop_session_keeps_waiting(self):
+ """The child runs in a copy of the parent's context, so it reads the parent's source."""
+ from agent.turn_recovery import free_tier_cooldown_ends_turn
+ from gateway.session_context import clear_session_vars, set_session_vars
+ tokens = set_session_vars(source="desktop")
+ try:
+ assert free_tier_cooldown_ends_turn(_agent(platform="subagent"), _plain_429(90), WELCOME) is False
+ finally:
+ clear_session_vars(tokens)
+
++ def test_a_gateway_admitted_finite_cli_turn_keeps_waiting(self):
++ """``hermes chat -q`` over the daemon carries its one-shot fact on the admission, not in env."""
++ from agent.turn_recovery import free_tier_cooldown_ends_turn
++ from gateway.session_finite import finite_turn_scope
++ with finite_turn_scope(True):
++ assert free_tier_cooldown_ends_turn(_agent(platform="cli"), _plain_429(90), WELCOME) is False
++ assert free_tier_cooldown_ends_turn(_agent(platform="cli"), _plain_429(90), WELCOME) is True
++
+ @pytest.mark.parametrize("platform", ["cron", None])
+ def test_an_unattended_run_keeps_waiting_and_is_told_the_reset(self, platform):
+ from agent.turn_recovery import compute_error_backoff, free_tier_cooldown_ends_turn
+ err = _plain_429(90)
+ agent = _backoff_agent(platform=platform)
+ assert free_tier_cooldown_ends_turn(agent, err, WELCOME) is False
+ compute_error_backoff(agent, err, retry_count=1, max_retries=3, is_rate_limited=True,
+ is_zai_coding_overload=False, base_url=WELCOME, model="nous/welcome")
+ assert "Resets in ~" in agent.buffered[0]
+
+ def test_a_paid_long_wait_stays_buffered_with_mains_attempt_numbers(self):
+ """A paid 300 s Retry-After: the status line is buffered (replayed only if every retry
+ fails) and the live wait line names the attempt that just failed, as on main."""
+ from agent.turn_recovery import compute_error_backoff
+ agent = _backoff_agent(provider="openrouter", api_key="sk-or-test", platform="desktop")
+ err = _plain_429(300)
+ wait = compute_error_backoff(agent, err, retry_count=1, max_retries=3, is_rate_limited=True,
+ is_zai_coding_overload=False, base_url="https://openrouter.ai/api/v1", model="m")
+ assert wait == 300
+ assert agent.emitted == [] and len(agent.buffered) == 1
+ assert "(attempt 1/3)" in agent.waits[0]
diff --cc tests/e2e/core/providers/test_catalog_oauth.py
index d2e1b4d8699,5ad67f5cc9a..93bdcf78216
--- a/tests/e2e/core/providers/test_catalog_oauth.py
+++ b/tests/e2e/core/providers/test_catalog_oauth.py
@@@ -93,9 -93,6 +93,9 @@@ class Home
"CODEX_HOME": str(self.home / ".codex"),
# Child HOME is the fixture home, so its state.db is tmp_path's (guard's documented escape).
"HERMES_STATE_DB_GUARD_BYPASS": "1",
- # A turn boots the gateway, whose startup pre-installs tirith through PM (a GitHub
- # download); like every gateway harness, the hermetic run opts out of lazy installs.
++ # A turn boots the gateway; like every gateway harness, the hermetic run opts out of
++ # lazy installs (PM downloads).
+ "HERMES_DISABLE_LAZY_INSTALLS": "1",
**self.sentinel.proxy_env()})
env.update(extra or {})
return env
diff --cc tests/gateway/test_session_policy.py
index 612bdf27f5a,00000000000..9bea3825514
mode 100644,000000..100644
--- a/tests/gateway/test_session_policy.py
+++ b/tests/gateway/test_session_policy.py
@@@ -1,198 -1,0 +1,217 @@@
+"""Fresh local policy is frozen and scoped, not process launcher state."""
+import os
+from concurrent.futures import ThreadPoolExecutor
+
+import pytest
+
+
+def test_policy_selects_surface_and_isolates_cwd(tmp_path):
+ from gateway.session_policy import build_policy, policy_scope
+ from agent.runtime_cwd import resolve_agent_cwd
+ from tools.terminal_scope import terminal_env
+ from hermes_state_runtime import RuntimeStoreError
+
+ cfg = {'platform_toolsets': {'cli': ['terminal']}}
+ before = dict(os.environ)
+ policies = []
+ for source in ('cli', 'tui', 'gui'):
+ cwd = tmp_path / source
+ cwd.mkdir()
+ policies.append(build_policy({'source': source, 'cwd': str(cwd), 'model': source}, cfg))
+ assert policies[2].platform == 'desktop'
+ assert 'desktop_ui' in policies[2].toolsets
+ assert all('desktop_ui' not in p.toolsets for p in policies[:2])
++ # Platform-gated toolsets (catalog) ride on the Desktop surface only, like the native TUI factory.
++ assert 'catalog' in policies[2].toolsets and all('catalog' not in p.toolsets for p in policies[:2])
+ cfg['platform_toolsets']['cli'].clear()
+ assert 'terminal' in policies[0].toolsets
+
+ def run(policy):
+ with policy_scope(policy):
+ assert str(resolve_agent_cwd()) == policy.cwd
+ assert terminal_env('TERMINAL_CWD') == policy.cwd
+ with ThreadPoolExecutor(max_workers=3) as pool:
+ list(pool.map(run, policies))
+ assert dict(os.environ) == before
+ for params in ({'source': 'cron'}, {'toolsets': ['not-a-toolset']}, {'cwd': '.'},
+ {'provider': 12}, {'skills': ['x']}, {'toolsets': ['desktop_ui'], 'source': 'cli'}):
+ with pytest.raises(RuntimeStoreError, match='invalid_params'):
+ build_policy(params, {})
+
+
+def test_launch_policy_reaches_real_turn_runner(tmp_path):
+ import json
+ from pathlib import Path
+ import subprocess
+ import sys
+ repo = Path(__file__).resolve().parents[2]
+ home, state = tmp_path / 'home', tmp_path / 'state'
+ home.mkdir()
+ state.mkdir()
+ from tests.gateway.fixtures.local_recovery_probe import child_env
+ env = child_env()
+ env.update(HOME=str(home), USERPROFILE=str(home), HERMES_HOME=str(state), PYTHONPATH=str(repo))
+ result = subprocess.run([sys.executable, str(Path(__file__).parent / 'fixtures' / 'session_policy_peer.py')],
+ cwd=repo, env=env, stdin=subprocess.DEVNULL, capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=130)
+ assert result.returncode == 0, result.stdout + '\n' + result.stderr
+ receipt = json.loads((state / 'policy-receipt.json').read_text())
+ assert receipt['cwd_effects'] and receipt['same_agents'] and receipt['no_spill']
+ print(json.dumps(receipt))
+
+
+def test_launch_options_are_frozen_and_validated(tmp_path):
+ from gateway.session_policy import build_policy
+ from hermes_constants import parse_reasoning_effort
+ from hermes_state_runtime import RuntimeStoreError
+ cfg = {'agent': {'max_turns': 8, 'reasoning_effort': 'low'}}
+ params = dict(cwd=str(tmp_path), provider='custom', base_url='http://127.0.0.1:1234/v1',
+ model='fixture', reasoning='high', max_turns=3, ignore_rules=True)
+ policy = build_policy(params, cfg)
+ assert policy.provider == 'custom' and policy.base_url == params['base_url']
+ assert policy.ignore_rules and policy.max_turns == 3
+ assert policy.reasoning_config == parse_reasoning_effort('high')
+ cfg['agent']['reasoning_effort'] = 'none'
+ assert policy.reasoning_config == parse_reasoning_effort('high')
+ assert build_policy(dict(cwd=str(tmp_path), ignore_rules=False), cfg).ignore_rules is False
+ for bad in ({'max_turns': True}, {'max_turns': 0}, {'reasoning': 'garbage'},
+ {'ignore_rules': 'false'}, {'base_url': 'http://user:secret@localhost/v1'}):
+ with pytest.raises(RuntimeStoreError, match='invalid_params'):
+ build_policy(dict(cwd=str(tmp_path), **bad), cfg)
+
+
+def test_explicit_key_is_private_and_missing_after_restart_fails_closed(tmp_path):
+ import json
+ from dataclasses import asdict
+ from types import SimpleNamespace
+ from gateway.session_policy import build_policy, bind_launch_key, launch_key
+ from hermes_state_runtime import RuntimeStoreError
+ authority = SimpleNamespace(instance_id='owned', profile_id='profile', epoch=1)
+ sibling = SimpleNamespace(instance_id='sibling', profile_id='profile', epoch=1)
+ raw = 'UNIQUE-PRIVATE-LAUNCH-KEY'
+ before = dict(os.environ)
+ params = dict(cwd=str(tmp_path), model='fixture', api_key=raw)
+ private = {}
+ policy = build_policy(params, {'model': {'api_key': raw}}, private_secrets=private)
+ policy = bind_launch_key(authority, 'session-a', policy, raw, config_secrets=private)
+ assert policy.config(authority)['model']['api_key'] == raw
+ assert raw not in json.dumps(asdict(policy))
+ assert launch_key(authority, policy) == raw
+ retry_private = {}
+ retry = build_policy(params, {'model': {'api_key': raw}}, private_secrets=retry_private)
+ assert bind_launch_key(authority, 'session-a', retry, raw, config_secrets=retry_private) == policy
+ for other in (sibling, SimpleNamespace(instance_id='owned', profile_id='profile', epoch=2)):
+ with pytest.raises(RuntimeStoreError, match='launch_credentials_unavailable'):
+ launch_key(other, policy)
+ with pytest.raises(RuntimeStoreError, match='launch_credentials_unavailable'):
+ policy.config(other)
+ with pytest.raises(RuntimeStoreError, match='admission_conflict'):
+ bind_launch_key(authority, 'session-a', build_policy(params, {}), 'different')
+ assert dict(os.environ) == before
+
+
+def test_ordinary_daemon_cli_launch_policy(tmp_path):
+ import subprocess
+ import sys
+ import json
+ from pathlib import Path
+ root = Path(__file__).resolve().parents[2]
+ result = subprocess.run([sys.executable, '-c',
+ 'import json,sys; from pathlib import Path; '
+ 'from tests.gateway.fixtures.cli_launch_policy_probe import probe; '
+ 'print(json.dumps(probe(Path(sys.argv[1]))))', str(tmp_path)], cwd=root,
+ stdin=subprocess.DEVNULL, capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=180)
+ assert result.returncode == 0, result.stdout + result.stderr
+ print(json.dumps(json.loads(result.stdout.splitlines()[-1])))
+
+
+def test_null_config_sections_read_as_absent(tmp_path):
+ # A fresh install's config.yaml carries a bare ``gateway:`` (YAML null); the managed-worker gate chains
+ # ``.get('gateway', {}).get(...)`` on the frozen policy and must read the default, not crash the turn.
+ from gateway.session_policy import build_policy, LocalSessionPolicy
+ from dataclasses import replace
+ import json
+
+ cfg = {'gateway': None, 'display': None, 'platform_toolsets': {'cli': ['terminal']}}
+ policy = build_policy({'source': 'cli', 'cwd': str(tmp_path)}, cfg)
+ assert policy.config().get('gateway', {}).get('managed_workers') is None
+ legacy = replace(policy, config_json=json.dumps(cfg)) # persisted before normalization
+ assert isinstance(legacy, LocalSessionPolicy)
+ assert legacy.config().get('display', {}).get('busy_input_mode', 'interrupt') == 'interrupt'
+
+
+
+def test_frozen_route_keeps_its_endpoint_after_live_config_edit(tmp_path, monkeypatch):
+ """R2-M2: the frozen policy's config-derived endpoint is the one its frozen credential
+ belongs to; a later ``model.base_url`` edit must not redirect that credential."""
+ import json
+ from types import SimpleNamespace
+ from gateway.session_policy import build_policy, bind_launch_key
+ from gateway.run_turn_prepare import GatewayTurnPrepareMixin
+ from hermes_cli.config_effective import load_user_config_effective
+ home = tmp_path / 'home'
+ home.mkdir()
+ monkeypatch.setenv('HERMES_HOME', str(home))
+
+ def write(url, key):
+ (home / 'config.yaml').write_text(json.dumps(
+ {'model': {'provider': 'custom', 'base_url': url, 'api_key': key, 'default': 'm'}}))
+ write('http://127.0.0.1:1/v1', 'sk-frozen-endpoint-one')
+ private = {}
+ policy = build_policy({'cwd': str(tmp_path), 'model': 'm'}, load_user_config_effective(home / 'config.yaml'),
+ private_secrets=private)
+ authority = SimpleNamespace(instance_id='i', epoch=1, profile_id='p', db=None)
+ policy = bind_launch_key(authority, 'sid', policy, None, config_secrets=private)
+ write('http://127.0.0.1:2/v1', 'sk-new-endpoint-two')
+ monkeypatch.setattr('gateway.session_policy.policy_for_source', lambda runner, source: policy)
+ runner = SimpleNamespace(session_authority=authority)
+ _, runtime = GatewayTurnPrepareMixin._resolve_session_agent_runtime(runner, source=SimpleNamespace())
+ assert (runtime['base_url'], runtime['api_key']) == ('http://127.0.0.1:1/v1', 'sk-frozen-endpoint-one')
+
+
+def test_frozen_bare_custom_route_keeps_its_endpoint_pool_and_launch_key_wins(tmp_path, monkeypatch):
+ """The frozen ``model.api_key`` is config, not a launch key: a URL-matched credential pool still
+ serves the frozen endpoint (refresh/rotation on 401/429), while a bound launch key wins (R2-M1)."""
+ import json
+ from types import SimpleNamespace
+ from gateway.session_policy import build_policy, bind_launch_key
+ from gateway.run_turn_prepare import GatewayTurnPrepareMixin
+ from hermes_cli.config_effective import load_user_config_effective
+ home = tmp_path / 'home'
+ home.mkdir()
+ monkeypatch.setenv('HERMES_HOME', str(home))
+ url = 'http://127.0.0.1:1/v1'
+ (home / 'config.yaml').write_text(json.dumps(
+ {'model': {'provider': 'custom', 'base_url': url, 'api_key': 'sk-frozen-config', 'default': 'm'}}))
+ pool = object()
+ monkeypatch.setattr('hermes_cli.runtime_provider._try_resolve_from_custom_pool', lambda base_url, *a, **k: {
+ 'provider': 'custom', 'api_mode': 'chat_completions', 'base_url': base_url, 'api_key': 'sk-pooled',
+ 'source': 'pool:custom', 'credential_pool': pool} if base_url.rstrip('/') == url else None)
+ authority = SimpleNamespace(instance_id='i', epoch=1, profile_id='p', db=None)
+ runner = SimpleNamespace(session_authority=authority)
+ runtimes = []
+ for sid, launch in (('config-keyed', None), ('launch-keyed', 'sk-launch-explicit')):
+ private = {}
+ params = {'cwd': str(tmp_path), 'model': 'm'} | ({'api_key': launch} if launch else {})
+ policy = build_policy(params, load_user_config_effective(home / 'config.yaml'), private_secrets=private)
+ policy = bind_launch_key(authority, sid, policy, launch, config_secrets=private)
+ monkeypatch.setattr('gateway.session_policy.policy_for_source', lambda runner, source, p=policy: p)
+ runtimes.append(GatewayTurnPrepareMixin._resolve_session_agent_runtime(runner, source=SimpleNamespace())[1])
+ assert (runtimes[0]['base_url'], runtimes[0]['credential_pool']) == (url, pool)
+ assert (runtimes[1]['api_key'], runtimes[1]['credential_pool']) == ('sk-launch-explicit', None)
++
++
++def test_lazy_info_reports_the_free_tier_pinned_model(tmp_path, monkeypatch):
++ """A not-yet-built session with no launch model/provider runs on ``nous/welcome`` on the free
++ tier (the agent build pins it), so ``session.info`` says so; an explicit launch model stands."""
++ from dataclasses import replace
++ from types import SimpleNamespace
++ from gateway.session_local import _lazy_model
++ from gateway.session_policy import build_policy
++ import hermes_cli.anon_auth as anon_auth
++ authority = SimpleNamespace(runner=None, profile_id='fixture')
++ monkeypatch.setattr(anon_auth, 'free_tier_route', lambda: True)
++ configured = replace(build_policy({'cwd': str(tmp_path)}, {'model': {'default': 'cfg-model'}}), model='cfg-model')
++ assert _lazy_model(authority, configured) == anon_auth.GUEST_MODEL
++ assert _lazy_model(authority, build_policy({'cwd': str(tmp_path), 'model': 'pick'}, {})) == 'pick'
++ monkeypatch.setattr(anon_auth, 'free_tier_route', lambda: False)
++ assert _lazy_model(authority, configured) == 'cfg-model'
diff --cc tests/gateway/test_surface_admission.py
index ab8c98aacba,00000000000..d13da83a927
mode 100644,000000..100644
--- a/tests/gateway/test_surface_admission.py
+++ b/tests/gateway/test_surface_admission.py
@@@ -1,148 -1,0 +1,181 @@@
+"""HUD / live-voice submit fields survive canonical admission and reach the model as a per-turn note."""
+import asyncio
+from contextlib import closing
+from http.server import ThreadingHTTPServer
+import json
+from pathlib import Path
+import sqlite3
+import threading
+import time
+from types import SimpleNamespace
+
+import pytest
+
+from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon, rpc, websocket
+
+
+async def _authority(tmp_path, monkeypatch, answer):
+ from gateway.config import GatewayConfig, Platform
+ from gateway.session import SessionSource, SessionStore
+ from gateway.session_authority import LiveSession, initialize_session_authority
+
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ runner = SimpleNamespace(_session_db=store._db, session_store=store, _draining=False,
+ _handle_message=answer, _adapter_for_source=lambda source: None)
+ authority = await initialize_session_authority(runner, profile_id='p', instance_id='owner')
+ store._db.create_session('s', source='telegram')
+ authority.sessions['s'] = LiveSession(SessionSource(platform=Platform.TELEGRAM, chat_id='c'), 's')
+ return authority
+
+
+async def test_surface_fields_are_admitted_and_scoped_to_their_own_turn(tmp_path, monkeypatch):
+ from gateway.session_controls import AuthorityConnection
+ from gateway.session_surface import surface_turn_note
+ from hermes_state_runtime import list_session_admissions
+ from tools.voice_live import VOICE_LIVE_TURN_NOTE
+
+ seen = []
+ async def answer(event):
+ # The note is rendered against the executing agent's tools; a live-voice turn needs none.
+ seen.append((event.text, surface_turn_note(SimpleNamespace(valid_tool_names=set()))))
+ return 'ok'
+ authority = await _authority(tmp_path, monkeypatch, answer)
+ connection = AuthorityConnection(authority, object(), {'user_id': 'owner'})
+ try:
+ await connection.dispatch({'id': 1, 'method': 'session.resume', 'params': {'session_id': 's'}})
+ reply = await connection.dispatch({'id': 2, 'method': 'prompt.submit', 'params': {
+ 'session_id': 's', 'submission_id': 'spoken', 'text': "what's the weather",
+ 'surface': 'voice-live', 'voice_context': "Voice assistant: Hi\nUser: what's the weather"}})
+ assert reply['result']['status'] == 'queued', reply
+ await authority.sessions['s'].task
+ plain = await connection.dispatch({'id': 3, 'method': 'prompt.submit', 'params': {
+ 'session_id': 's', 'submission_id': 'typed', 'text': 'and tomorrow?'}})
+ assert plain['result']['status'] == 'queued', plain
+ await authority.sessions['s'].task
+ rejected = await connection.dispatch({'id': 4, 'method': 'prompt.submit', 'params': {
+ 'session_id': 's', 'submission_id': 'smuggled', 'text': 'x', 'voice_context': 'User: smuggled'}})
+ assert rejected['error']['message'] == 'invalid_params', rejected
+ finally:
+ await connection.close()
+
+ rows = {row['request_id']: row for row in list_session_admissions(authority.db, session_id='s', pending_only=False)}
+ assert rows['spoken']['payload']['surface_v1'] == {
+ 'surface': 'voice-live', 'voice_context': "Voice assistant: Hi\nUser: what's the weather"}
+ assert 'surface_v1' not in rows['typed']['payload'] and 'smuggled' not in rows
+ (spoken_text, spoken_note), (typed_text, typed_note) = seen
+ assert spoken_text == "what's the weather", 'the persisted user row stays the words the user said'
+ assert spoken_note.startswith(VOICE_LIVE_TURN_NOTE) and "User: what's the weather" in spoken_note
+ assert (typed_text, typed_note) == ('and tomorrow?', '')
+
+
++
++async def test_voice_turn_is_admitted_and_scoped_to_its_own_turn(tmp_path, monkeypatch):
++ """A spoken voice-mode turn (TUI/Desktop ``voice_turn``) rides canonical admission to the turn
++ that runs on ``auxiliary.voice_chat``; the next typed turn stays on the main model."""
++ from gateway.session_controls import AuthorityConnection
++ from gateway.session_surface import surface_turn_note, surface_voice_turn
++ from hermes_state_runtime import list_session_admissions
++
++ seen = []
++ async def answer(event):
++ seen.append((event.text, surface_voice_turn(), surface_turn_note(SimpleNamespace(valid_tool_names=set()))))
++ return 'ok'
++ authority = await _authority(tmp_path, monkeypatch, answer)
++ connection = AuthorityConnection(authority, object(), {'user_id': 'owner'})
++ try:
++ await connection.dispatch({'id': 1, 'method': 'session.resume', 'params': {'session_id': 's'}})
++ for rid, extra in (('spoken', {'voice_turn': True}), ('typed', {})):
++ reply = await connection.dispatch({'id': 2, 'method': 'prompt.submit', 'params': {
++ 'session_id': 's', 'submission_id': rid, 'text': rid, **extra}})
++ assert reply['result']['status'] == 'queued', reply
++ await authority.sessions['s'].task
++ rejected = await connection.dispatch({'id': 3, 'method': 'prompt.submit', 'params': {
++ 'session_id': 's', 'submission_id': 'bad', 'text': 'x', 'voice_turn': 'yes'}})
++ assert rejected['error']['message'] == 'invalid_params', rejected
++ finally:
++ await connection.close()
++
++ rows = {row['request_id']: row for row in list_session_admissions(authority.db, session_id='s', pending_only=False)}
++ assert rows['spoken']['payload']['surface_v1'] == {'voice_turn': True}
++ assert 'surface_v1' not in rows['typed']['payload'] and 'bad' not in rows
++ assert seen == [('spoken', True, ''), ('typed', False, '')]
++
+def _admissions(home):
+ with closing(sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True)) as db:
+ return dict(db.execute('SELECT request_id, status FROM session_admissions'))
+
+
+def _wait_for(predicate):
+ deadline = time.monotonic() + 30
+ while time.monotonic() < deadline:
+ if predicate():
+ return
+ time.sleep(.05)
+ pytest.fail('Timed out waiting for the admitted turn')
+
+
+def test_real_daemon_accepts_hud_and_voice_live_submits_and_notes_the_model(tmp_path, monkeypatch):
+ from tools.voice_live import VOICE_LIVE_TURN_NOTE
+
+ root = Path(__file__).resolve().parents[2]
+ home, user = tmp_path / 'state', tmp_path / 'user'
+ home.mkdir(mode=0o700)
+ user.mkdir()
+ monkeypatch.setenv('HERMES_HOME', str(home))
+ monkeypatch.setenv('HOME', str(user))
+ monkeypatch.setenv('USERPROFILE', str(user))
+ model = ThreadingHTTPServer(('127.0.0.1', 0), Model)
+ model.requests = []
+ model.blocked, model.release = threading.Event(), threading.Event()
+ thread = threading.Thread(target=model.serve_forever, daemon=True)
+ thread.start()
+ base = f'http://127.0.0.1:{model.server_port}/v1'
+ (home / 'config.yaml').write_text(json.dumps({
+ 'gateway': {'multiplex_profiles': False},
+ 'model': {'provider': 'custom', 'default': 'local-wire-stub', 'base_url': base},
+ 'auxiliary': {'title_generation': {'enabled': False}},
+ 'platform_toolsets': {'gui': []}, 'terminal': {'cwd': str(home)},
+ }))
+ env = child_env() | dict(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home),
+ PYTHONPATH=str(root), OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=base, PYTHONUNBUFFERED='1')
+
+ async def drive(desc):
+ async with websocket(home, desc) as ws:
+ created = await rpc(ws, 'session.create', request_id='surface-target', source='gui', cwd=str(home), toolsets=[])
+ assert 'result' in created, created
+ sid = created['result']['session_id']
+ replies = {}
+ for name, extra in (('window', {}), ('hud', {'surface': 'hud'}),
+ ('voice', {'surface': 'voice-live', 'voice_context': 'User: earlier words'})):
+ replies[name] = await rpc(ws, 'prompt.submit', session_id=sid, submission_id=name, text=name.upper() + '_TURN', **extra)
+ await asyncio.to_thread(_wait_for, lambda: _admissions(home).get(name) == 'terminal')
+ return replies
+
+ try:
+ with daemon(root, home, env, barrier=False) as (proc, desc):
+ replies = asyncio.run(drive(desc))
+ finally:
+ model.release.set()
+ model.shutdown()
+ model.server_close()
+ thread.join(timeout=5)
+
+ assert all(reply.get('result', {}).get('status') == 'queued' for reply in replies.values()), replies
+ users = {}
+ for request in model.requests:
+ content = next(m['content'] for m in reversed(request['messages']) if m['role'] == 'user')
+ text = content if isinstance(content, str) else ''.join(p.get('text', '') for p in content)
+ for name in ('window', 'hud', 'voice'):
+ if name.upper() + '_TURN' in text:
+ users[name] = text
+ assert set(users) == {'window', 'hud', 'voice'}, users
+ # Live voice: the delegation contract + the spoken context ride the model input, never the row.
+ assert VOICE_LIVE_TURN_NOTE in users['voice'] and 'User: earlier words' in users['voice']
+ assert VOICE_LIVE_TURN_NOTE not in users['window'] and VOICE_LIVE_TURN_NOTE not in users['hud']
+ # HUD without read_window_below (toolsets=[]) is accepted and withholds the tool-gated note.
+ assert 'HUD mode' not in users['hud'] and 'HUD mode' not in users['window']
+ assert all(request['messages'][0]['role'] == 'system' for request in model.requests)
+ assert len({request['messages'][0]['content'] for request in model.requests}) == 1, 'frozen system prefix must not vary per surface'
diff --cc tests/hermes_cli/test_config.py
index bef77431e79,ff609c9879b..9801cd8dce2
--- a/tests/hermes_cli/test_config.py
+++ b/tests/hermes_cli/test_config.py
@@@ -1039,28 -1039,6 +1039,28 @@@ class TestCuratorFasterPrune
assert raw["curator"]["archive_after_days"] == 180
+class TestRetiredBotChatDeliveryTimeout:
- def test_v50_drops_bot_chat_delivery_timeout_with_a_note(self, tmp_path, monkeypatch):
++ def test_v51_drops_bot_chat_delivery_timeout_with_a_note(self, tmp_path, monkeypatch):
+ """The removed cron knob is dropped from existing configs with a one-time note;
+ sibling cron settings and the rest of the file survive untouched."""
+ from hermes_cli.config import DEFAULT_CONFIG
+ from hermes_cli.config_migrations import run_migrations
+
+ config_path = tmp_path / "config.yaml"
+ config_path.write_text(yaml.safe_dump({
- "_config_version": 49,
++ "_config_version": 50,
+ "cron": {"bot_chat_delivery_timeout_seconds": 900, "max_parallel_jobs": 2},
+ }), encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ results = {"env_added": [], "config_added": [], "warnings": []}
- run_migrations(49, results, quiet=True)
++ run_migrations(50, results, quiet=True)
+ raw = yaml.safe_load(config_path.read_text(encoding="utf-8"))
+ assert "bot_chat_delivery_timeout_seconds" not in raw["cron"]
+ assert raw["cron"]["max_parallel_jobs"] == 2
+ assert any("bot_chat_delivery_timeout_seconds" in note for note in results["config_added"])
+ assert "bot_chat_delivery_timeout_seconds" not in DEFAULT_CONFIG["cron"]
+
+
class TestCustomProviderCompatibility:
"""Custom provider compatibility across legacy and v12+ config schemas.
diff --cc tests/hermes_state/test_runtime_worker_usage.py
index ee30b0b1a07,00000000000..399b13ac77f
mode 100644,000000..100644
--- a/tests/hermes_state/test_runtime_worker_usage.py
+++ b/tests/hermes_state/test_runtime_worker_usage.py
@@@ -1,37 -1,0 +1,56 @@@
+import sqlite3
+import pytest
+from hermes_state import SessionDB
+import hermes_state_runtime as rt
+
+
+def test_usage_receipt_includes_route_rows_and_rolls_back_on_receipt_failure(tmp_path):
+ db = SessionDB(tmp_path / 'state.db')
+ try:
+ db.create_session('s', source='cli')
+ epoch = rt.begin_runtime_epoch(db, instance_id='owner')
+ scope = dict(epoch=epoch, execution_id='w', session_id='s', generation=0)
+ rt.register_worker_execution(db, **scope, kind='compute', adoption_secret='private')
+ payload = {'input_tokens': 13, 'output_tokens': 7, 'api_call_count': 1,
+ 'model': 'model-a', 'billing_provider': 'provider', 'estimated_cost_usd': 0.25}
+ args = dict(**scope, sequence=1, operation='usage.main', payload=payload)
+ receipt = rt.mutate_worker_execution(db, **args)
+ assert rt.mutate_worker_execution(db, **args) == receipt
+ assert db.get_session('s')['input_tokens'] == 13
+ with db._read_ctx() as conn:
+ assert conn.execute('SELECT input_tokens FROM session_model_usage').fetchone()[0] == 13
+ db._execute_write(lambda c: c.execute("CREATE TRIGGER deny_receipt BEFORE INSERT ON worker_receipts BEGIN SELECT RAISE(ABORT, 'deny receipt'); END"))
+ with pytest.raises(sqlite3.IntegrityError, match='deny receipt'):
+ rt.mutate_worker_execution(db, **(args | {'sequence': 2}))
+ assert db.get_session('s')['input_tokens'] == 13
+ db._execute_write(lambda c: c.execute('DROP TRIGGER deny_receipt'))
+ aux = dict(**scope, sequence=2, operation='usage.auxiliary',
+ payload={'task': 'compression', 'model': 'aux', 'input_tokens': 3})
+ rt.mutate_worker_execution(db, **aux)
+ rt.mutate_worker_execution(db, **aux)
+ assert db.get_session('s')['input_tokens'] == 13
+ with db._read_ctx() as conn:
+ assert conn.execute("SELECT input_tokens FROM session_model_usage WHERE task='compression'").fetchone()[0] == 3
+ with pytest.raises(rt.RuntimeStoreError, match='invalid_params'):
+ rt.mutate_worker_execution(db, **(args | {'sequence': 3, 'payload': {'input_tokens': -1}}))
+ finally:
+ db.close()
++
++
++def test_worker_voice_turn_usage_counts_but_never_rewrites_the_session_route(tmp_path):
++ """A managed worker's per-turn route (``task``) reaches the owner: totals count, the
++ session's recorded model stays the one the user picked, and the per-task row is kept."""
++ db = SessionDB(tmp_path / 'state.db')
++ try:
++ db.create_session('s', source='cli', model='main-model')
++ epoch = rt.begin_runtime_epoch(db, instance_id='owner')
++ scope = dict(epoch=epoch, execution_id='w', session_id='s', generation=0)
++ rt.register_worker_execution(db, **scope, kind='compute', adoption_secret='private')
++ payload = {'input_tokens': 10, 'api_call_count': 1, 'model': 'voice-model',
++ 'billing_provider': 'voicep', 'task': 'voice_chat'}
++ rt.mutate_worker_execution(db, **scope, sequence=1, operation='usage.main', payload=payload)
++ row = db.get_session('s')
++ assert (row['input_tokens'], row['model']) == (10, 'main-model')
++ assert db.auxiliary_usage_by_task('s')['voice_chat']['input_tokens'] == 10
++ finally:
++ db.close()
diff --cc tui_gateway/agent_factory.py
index ce894fac339,00000000000..2551e8712fb
mode 100644,000000..100644
--- a/tui_gateway/agent_factory.py
+++ b/tui_gateway/agent_factory.py
@@@ -1,693 -1,0 +1,687 @@@
+"""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.model_switch import resolve_startup_model_route
+ from hermes_cli.models import detect_static_provider_for_model
+ full_cfg = _load_cfg()
+ cfg = full_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")
+ # Same owner as HermesCLI/oneshot: ``custom:<name>:<model>`` selects that provider (#73943).
+ if route := resolve_startup_model_route(
+ explicit_model, current_provider=current_provider,
+ user_providers=full_cfg.get("providers"), custom_providers=full_cfg.get("custom_providers")):
+ return route.model, route.provider
+ if detected := detect_static_provider_for_model(explicit_model, current_provider):
+ provider, detected_model = detected
+ return detected_model, provider
+ return model, None
+
+
+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 _row_follows_profile(row: dict | None) -> bool:
+ """Whether a stored row is a canonical Bot Chat whose runtime follows the member profile's config.
+ Identity is the persisted ``follow_profile_config`` marker; the bare title compare stays ONLY here as
+ the legacy fallback for rows written before the marker existed."""
+ if not row:
+ return False
+ model_config = _parse_model_config(row.get("model_config"), quiet=True)
+ return bool(model_config.get("follow_profile_config") or str(row.get("title") or "").strip() == "Bot Chat")
+
+
+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 normally rebuild from the member profile's CURRENT config (a stale provider pin left room bots
+ "out of Nous credits" after a profile switch). A canonical Bot Chat may instead restore an explicit
+ composer pick while the profile model it diverged from remains unchanged."""
+ if not row:
+ return {}
+ model_config = _parse_model_config(row.get("model_config"), quiet=True)
+ _row_title = str(row.get("title") or "").strip()
+ room_plumbing = model_config.get("room_plumbing") or (row.get("hidden") and _row_title.startswith("Group:"))
+ composer_profile = model_config.get("composer_override_profile")
+ composer_profile_matches = isinstance(composer_profile, dict) and (
+ str(composer_profile.get("model") or "").strip(),
+ str(composer_profile.get("provider") or "").strip(),
+ ) == _config_model_target()
+ if room_plumbing or (_row_follows_profile(row) and not composer_profile_matches):
+ return {}
+ overrides: dict = {}
+ model = str(row.get("model") or model_config.get("model") or "").strip()
+ # Canonical route reader shared with CLI --resume: nested ``gateway_runtime`` (the route the messaging
+ # gateway last ran) before the TUI's top-level keys, then a routable ``billing_provider`` (#125942).
+ from hermes_state import SessionDB
+ route = SessionDB.session_gateway_runtime(row)
+ provider, base_url, api_mode = (str(route.get(k) or "").strip() for k in ("provider", "base_url", "api_mode"))
+ service_tier = str(model_config.get("service_tier") or "").strip()
+ reasoning_config = model_config.get("reasoning_config")
+ from hermes_cli.runtime_provider import is_foreign_provider_endpoint
+ if is_foreign_provider_endpoint(provider, base_url):
+ # The endpoint and its wire belong to the provider this chat left; resolve the stored one's own.
+ base_url = api_mode = ""
+ # 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 isinstance(composer_profile := session.get("composer_override_profile"), dict):
+ model_config["composer_override_profile"] = composer_profile
+ elif "composer_override_profile" in session:
+ model_config.pop("composer_override_profile", None)
+ 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)
+
+
+def _load_service_tier() -> str | None:
+ from agent.fast_mode import parse_service_tier
+
+ return parse_service_tier((_load_cfg().get("agent") or {}).get("service_tier", ""))
+
+
+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)."""
+ from toolsets import CLIENT_SURFACE_TOOLSETS
+ return set(CLIENT_SURFACE_TOOLSETS) if platform == "desktop" else {"project"}
+
+
- def _with_session_toolsets(selection, platform: str | None) -> list[str]:
- """*selection* plus what the session carries whatever its config says (the client surface's
- toolsets when *platform* is given; the ones its PROFILE's role reserves, from the backend-written
- profile.yaml under the session's home override), minus toolsets reserved for another role.
++def _with_session_toolsets(selection, platform: str) -> list[str]:
++ """*selection* plus the client surface's toolsets the session carries whatever its config says.
+
+ The fold-in happens after ``_get_platform_tools`` already subtracted ``agent.disabled_toolsets``,
+ so the same subtraction is applied to the fold-in itself — otherwise ``disabled_toolsets:
+ [project]`` is a no-op on desktop/TUI, the only surfaces where the client toolsets exist
+ (#54433). ``desktop_ui`` is kept regardless: it is the client's own control surface, not a
+ model toolset."""
- from toolsets import profile_role_toolsets
- granted, denied = profile_role_toolsets()
- surface = _gui_surface_toolsets(platform) if platform is not None else set()
- kept = [name for name in selection if name not in denied]
- fold_in = (surface | granted) - set(kept)
++ fold_in = _gui_surface_toolsets(platform) - set(selection)
+ disabled = set(_load_disabled_toolsets() or [])
+ if disabled:
+ fold_in -= disabled - {"desktop_ui"}
- return [*kept, *sorted(fold_in)]
++ return [*selection, *sorted(fold_in)]
+
+
+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 tools.mcp_tool_common import mcp_server_enabled
+ 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 = mcp_server_enabled(server_cfg)
+ (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.
+ An explicitly saved EMPTY list (``platform_toolsets.cli: []`` that resolves to nothing) is a
+ zero-tool state and returns [] — never None, which would mean unrestricted (#82010)."""
+ 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(_with_session_toolsets(selection, 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:
- # An operator pin replaces the surface fold-in but never strips the profile's own role toolsets.
- return resolved if resolved is None else _with_session_toolsets(resolved, None)
++ # An operator pin replaces the surface fold-in.
++ 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, _platform_toolsets_explicitly_saved
+ 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)
+ if enabled:
+ return sorted(_with_session_toolsets(enabled, session_platform))
+ # An explicitly saved list that resolves to nothing (``platform_toolsets.cli: []`` with no
+ # enabled MCP servers) is an explicit zero-tool state, not "no filter": fail closed with []
+ # instead of None (#82010). The client-surface fold-in must not resurrect tools the user
+ # explicitly switched off, so [] is returned bare. Only an ABSENT/unset key keeps the
+ # None = "no restriction" default below.
+ if _platform_toolsets_explicitly_saved(cfg, "cli"):
+ return []
+ return 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 _load_disabled_toolsets() -> list[str] | None:
+ """``agent.disabled_toolsets`` from config.yaml, or ``None``.
+
+ The classic CLI (``cli_init_mixin``) and the messaging gateway both forward this list to
+ AIAgent, where ``get_tool_definitions`` strips the named toolsets even out of composite
+ defaults like ``hermes-cli`` (#17309). The desktop/TUI gateway historically dropped it, so
+ e.g. ``disabled_toolsets: [browser]`` silently had no effect on Desktop — the only consumer
+ was ``_get_platform_tools``'s name-level subtraction, which can't reach inside a composite
+ default toolset (#44499).
+ """
+ try:
+ from agent.skill_utils import parse_config_string_list
+
+ from hermes_cli.config import load_config
+
+ agent_cfg = load_config().get("agent") or {}
+ disabled = parse_config_string_list(agent_cfg.get("disabled_toolsets"))
+ return [str(ts) for ts in disabled] or None
+ except Exception:
+ 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 _session_show_reasoning(sid: str) -> bool:
+ """Session display flag. Missing means the config default, not hidden."""
+ session = _sessions.get(sid) or {}
+ if "show_reasoning" in session:
+ return bool(session["show_reasoning"])
+ return _load_show_reasoning()
+
+
+def _tool_progress_enabled(sid: str) -> bool:
+ return _session_tool_progress_mode(sid) != "off"
+
+
+_TOOL_LIFECYCLE_UI_TOOLS = frozenset({
+ "clarify", "manage_connections", "setup_mcp",
+ "image_generate", "manage_catalog", "delegate_task",
+ # File edits are the turn's deliverable — the diff card the user reviews.
+ "edit_file", "patch", "write_file",
+})
+
+
+def _tool_lifecycle_required_for_ui(name: str) -> bool:
+ """Interactive UI / card surfaces, not optional chrome.
+
+ Desktop renders these from the tool-call part itself, so suppressing the
+ lifecycle hides the turn's deliverable entirely (`isCardTool` /
+ `isFileEditTool` in apps/desktop/src/lib/tool-render-class.ts must stay in
+ sync with `_TOOL_LIFECYCLE_UI_TOOLS`): clarify / connection cards are
+ consent surfaces, image_generate / manage_catalog / delegate_task draw the
+ thing the user asked for, and file edits are the diff the user reviews.
+ The start and complete guards both consult this set, so a card's
+ `tool.complete` can never arrive without its `tool.start`.
+ """
+ return name in _TOOL_LIFECYCLE_UI_TOOLS
+
+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 effective_runtime_provider, 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)
+ # Named custom entries resolve to the bare "custom" billing class; keep the configured
+ # identity so the session/UI shows the provider name, matching the manual-switch path (#98739).
+ runtime["provider"] = effective_runtime_provider(entry, runtime)
+ from hermes_cli.auth import primary_failure_wording
+ logging.getLogger(__name__).warning(
+ "Primary %s (%s), falling back to %s model %s",
+ primary_failure_wording(primary_exc)[0], 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")
+ # Same pre-agent switch the messaging gateway surfaces (#74349); _make_agent pops it onto the
+ # agent's one-shot notice so the TUI/Desktop user sees which provider actually answered.
+ from hermes_cli.fallback_config import pre_agent_fallback_notice
+ # requested_provider=None means resolve_runtime_provider read the persisted config provider;
+ # ``model: <id>`` (string shorthand) names no provider.
+ cfg_model = _load_cfg().get("model")
+ primary_provider = requested_provider or (cfg_model.get("provider") if isinstance(cfg_model, dict) else None)
+ resolution.runtime["_fallback_notice"] = pre_agent_fallback_notice(
+ primary_provider, model, resolution.runtime.get("provider"), resolution.selected_model)
+ return resolution.selected_model, resolution.runtime
+ if resolution.runtime.get("source") == "local-runtime":
+ # Live supervisor beat any persisted loopback URL for this identity.
+ overrides.pop("base_url", None)
+ resolution.runtime.update({k: v for k, v in overrides.items() if v})
+ if any(overrides.values()):
+ _rederive_per_model_route(model, resolution.runtime)
+ return model, resolution.runtime
+
+
+def _rederive_per_model_route(model: str, runtime: dict) -> None:
+ """A row's persisted api_mode/base_url were written for whichever model the session last ran. Providers
+ that pick the wire per model (OpenCode Zen/Go, Copilot, Nous) must re-derive both from the target model,
+ or a resumed opencode-go session keeps a MiniMax-era anthropic_messages route (and its /v1-stripped or
+ other-family relay URL) for a chat_completions model like deepseek-v4-flash-vision-exp (#96066)."""
+ from hermes_cli.model_switch import model_derived_api_mode
+ from hermes_cli.models import normalize_opencode_base_url
+ provider = str(runtime.get("requested_provider") or runtime.get("provider") or "")
+ api_mode = model_derived_api_mode(provider, model)
+ if api_mode is None:
+ return
+ runtime["api_mode"] = api_mode
+ runtime["base_url"] = normalize_opencode_base_url(provider, api_mode, runtime.get("base_url"))
+
+
+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, format_missing_skills
+ skills_prompt, loaded_skills, missing_skills = build_preloaded_skills_prompt(startup_skills, task_id=task_id)
+ if missing_skills:
+ if not loaded_skills:
+ raise ValueError(format_missing_skills(missing_skills))
+ logger.warning("Skipping %s. Continuing with: %s. List available skills with `hermes skills list`.",
+ format_missing_skills(missing_skills), ", ".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,
+ cwd_override: str | 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)
+ fallback_notice = runtime.pop("_fallback_notice", None)
+ _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"),
+ requested_provider=runtime.get("requested_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),
+ disabled_toolsets=_load_disabled_toolsets(),
+ # 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,
+ cwd=cwd_override,
+ # 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=_resolve_checkpoints_enabled(cfg),
+ 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(),
+ # The resolved provider's request body (a custom entry's extra_body), as the CLI/cron/gateway pass it.
+ request_overrides=runtime.get("request_overrides"),
+ prefill_messages=_load_prefill_messages() or None, **_agent_cbs(sid))
+ if context_cwd_is_launch_artifact is None:
+ context_cwd_is_launch_artifact = _context_cwd_is_launch_artifact(session)
+ agent._context_cwd_is_launch_artifact = bool(context_cwd_is_launch_artifact)
+ if fallback_notice:
+ # Emitted once on the first successful reply via _emit_pending_fallback_notice -> status_callback.
+ agent._pending_fallback_notice = fallback_notice
+ return agent
+
+
+def register(server):
+ bind_module(globals(), server)
diff --cc tui_gateway/session_registry.py
index 72d9cdad33a,00000000000..2124c77aac6
mode 100644,000000..100644
--- a/tui_gateway/session_registry.py
+++ b/tui_gateway/session_registry.py
@@@ -1,787 -1,0 +1,786 @@@
+"""TUI session_registry seam; functions bind to the server namespace at registration."""
+
+from __future__ import annotations
+
+import re
+
+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_STILL_STARTING)
+ 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 | None") -> "_TurnScopes | None":
+ """Bind a session profile's HERMES_HOME / secret / terminal scopes for an agent build. ``None`` is the
+ launch profile: its own launch-env secret scope (live env while single-profile, frozen once
+ multiplexing is active — a hosted-room turn for a default member otherwise died at build with
+ ``UnscopedSecretError`` because the launch profile was treated as "no scope"). 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()
+ with contextlib.suppress(Exception):
+ return _profile_runtime_scope_tokens(profile_home)
+ if profile_home: # secret/terminal helper failed: keep at least the home + terminal refusal scope
+ scopes.home = set_hermes_home_override(profile_home)
+ 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") -> None:
+ with contextlib.suppress(Exception):
+ _release_profile_runtime_scope_tokens(scopes)
+
+
+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), "cwd_override": _session_cwd(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(sid: str, current: dict, agent) -> bool:
+ """Attach a freshly built agent to its live record (session DB row deferred to first run_conversation()).
+ False when ``session.close`` popped this record mid-build: teardown saw ``agent=None`` and closed
+ nothing, so the caller owns closing the orphan (#49852)."""
+ # 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
+ # Under the same lock session.close takes to pop the record: no window between "still live" and "attached".
+ with _sessions_lock:
+ if _sessions.get(sid) is not current:
+ return False
+ current["agent"] = agent
+ # A workspace move can land while construction is still in flight.
+ _register_session_cwd(current)
+ _session_todo_state(current)
+ # Baseline for the per-turn config sync (profile home override still active).
+ current["config_model_seen"] = _config_model_target()
+ return True
+
+
+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 after the agent was attached: _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 ""), session.get("profile_home") or None):
+ 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:
+ # Closed/reaped before the build started: nothing will ever attach an agent to this
+ # record, yet ``agent_ready`` must be set so a prompt waiting on it fails instead of hanging.
+ session["agent_error"] = AGENT_BUILD_ABANDONED
+ 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):
+ # Replaced mid-build: the finally still sets ``agent_ready`` with ``agent`` None, so record
+ # why — a turn admitted against this record refuses with the real reason (#111531).
+ current["agent_error"] = AGENT_BUILD_ABANDONED
+ return
+ tokens = _set_session_context(key, cwd=_session_cwd(current))
+ # 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.
+ scopes = _bind_build_profile_scopes(profile_home)
+ if 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 atomically against session teardown: ``session.close`` may have popped this
+ # session while the expensive build was in flight, in which case teardown could not close
+ # an agent that did not exist yet. Release the orphan immediately and do not keep wiring
+ # workers/callbacks for a dead session (#49852).
+ if not _attach_built_agent(sid, current, agent):
+ # Same contract as the replaced-before-attach exit above: a turn admitted against
+ # this record must refuse with the real reason rather than a generic missing agent.
+ current["agent_error"] = AGENT_BUILD_ABANDONED
+ with contextlib.suppress(Exception):
+ if hasattr(agent, "close"):
+ agent.close()
+ return
+ # 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:
+ from agent.auxiliary_unavailable import ProviderNotConfiguredError
+ current["agent_error"] = str(e)
+ # A client can route "no provider is set up" to its setup flow instead of a dead-end
+ # error toast — but only if it can tell. The sentence is for the reader, the code is
+ # for the client; older clients keep matching the text.
+ _emit("error", sid, {
+ "message": agent_init_failed_message(e),
+ **({"code": "provider_not_configured"} if isinstance(e, ProviderNotConfiguredError) else {})})
+ 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 new_session_id()
+
+
+# Server-minted session keys are ``%Y%m%d_%H%M%S_`` + 6 hex chars (see
+# ``_new_session_key``). session.resume uses this shape as the fail-closed gate
+# for materializing a row for a minted-but-never-persisted key: only keys the
+# server itself could have produced qualify — arbitrary strings and 8-hex
+# runtime session ids (``uuid4().hex[:8]``) are rejected.
+_MINTED_SESSION_KEY_RE = re.compile(r"^\d{8}_\d{6}_[0-9a-f]{6}$")
+
+
+def _is_server_minted_key(value: str | None) -> bool:
+ return bool(value and _MINTED_SESSION_KEY_RE.fullmatch(value))
+
+
+def _any_live_session_claims_key(target: str) -> bool:
+ """True if any live registry record claims this stored key (any profile).
+
+ Fail-closed gate for minted-key materialization: a key claimed by a live
+ session — even one scoped to a different profile — is owned, so an
+ unscoped resume must not mint a phantom row in the launch store (#93296
+ cross-profile rule: routing guesses are forbidden).
+ """
+ for record in list(_sessions.values()):
+ if not isinstance(record, dict):
+ continue
+ if str(record.get("session_key") or "") == target:
+ return True
+ return False
+
+
+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 _session_default_model({"profile_home": _profile_home(profile)}),
++ **_lazy_info_route({"profile_home": _profile_home(profile)}, {"model": model, "provider": provider} if model else {}),
+ "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, *, model_history_only: bool = False) -> 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
+ if model_history_only:
+ raw_history = db.get_messages_as_conversation(
+ stored_id, repair_alternation=True, include_row_ids=True)
+ return raw_history, [], []
+ 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,
+ model_history_only: 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"})
+ # Read-only mount (#85303): hydration is a read; an ended row stays ended —
+ # the first real turn (prompt.submit) reopens it. But a restart discarded the
+ # busy-queue, so retire never-drained accept rows (#125577) before the read —
+ # with #128508 the reopen (and its retire) no longer runs on this path.
+ # Best-effort like the resume guard: a handle without the method skips it.
+ retire = getattr(db, "retire_undrained_queue_rows", None)
+ if callable(retire):
+ retire(stored_id)
+ raw_history, display_history, prefix = _load_resume_transcript(
+ db, stored_id, model_history_only=model_history_only)
+ # 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)
+ if not model_history_only:
+ session["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": session["resume_message_count"], "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 = resume_failed_message(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:
+ """Method of the server→client request *sid* is blocked on ("" when none)."""
+ from tui_gateway import server_requests
+ return server_requests.pending_kind(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": _session_default_model(session), "skills": {}, "tools": {}, "desktop_contract": DESKTOP_BACKEND_CONTRACT,
++ **_lazy_info_route(session, {}), "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, inline_images: bool = True) -> 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)
+ # message_count follows _resume_response: the stored size when messages are omitted, else the wire count
+ # (a hidden seed row is in ``history`` but never on the wire).
+ messages = ([] if omit_messages else
+ _history_to_messages(history, profile_home=session.get("profile_home"), image_urls=inline_images))
+ 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 ""))),
+ ("open_requests", _open_requests(sid)),
+ ("pending_connection", _pending_connection_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 = {}
+ # ``session_id`` rides along so a session-bound ``llm.oneshot`` (title, approval) on an OpenCode
+ # route sends the conversation's ``x-opencode-session`` like the main turn does (#112717).
+ for field in ("provider", "model", "base_url", "api_key", "api_mode", "auth_mode", "session_id"):
+ 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 ui-tui/src/app/createGatewayEventHandler.ts
index 4b9211f0a0e,97108ba1b40..4808a08bbbf
--- a/ui-tui/src/app/createGatewayEventHandler.ts
+++ b/ui-tui/src/app/createGatewayEventHandler.ts
@@@ -39,7 -37,7 +39,8 @@@ import { markBubbleShown, newlyStartedR
import { flashGoodVibes, flashPet } from './petFlashStore.js'
import { forgetServerRequest } from './serverRequestStore.js'
import { reportStartupLatency } from './startupLatency.js'
+ import { markNextSubmitVoice } from './submissionCore.js'
+import { captureDestination, isCurrentDestination } from './submissionDestination.js'
import { turnController } from './turnController.js'
import { getTurnState } from './turnStore.js'
import { getUiState, patchUiState } from './uiStore.js'
@@@ -813,43 -803,10 +815,47 @@@ export function createGatewayEventHandl
return
}
+ // Lifecycle authority is local to an owner epoch. Only attachment RPC
+ // snapshots replace that epoch; delayed push events cannot reset it.
+ const current = getUiState().info
+ const execution = (ev.payload ?? {}) as { execution_epoch?: string; execution_generation?: number }
+
+ const genericError = ev.type === 'error' &&
+ execution.execution_epoch === undefined && execution.execution_generation === undefined
+
+ const lifecycle = !genericError && ['session.info', 'message.start', 'message.complete', 'error'].includes(ev.type)
+
+ if (lifecycle && current?.execution_generation !== undefined) {
+ const incoming = (ev.payload ?? {}) as { execution_epoch?: string; execution_generation?: number }
+
+ if (
+ incoming.execution_epoch !== current.execution_epoch ||
+ typeof incoming.execution_generation !== 'number' ||
+ !Number.isSafeInteger(incoming.execution_generation) ||
+ incoming.execution_generation < current.execution_generation
+ ) {
+ return
+ }
+
+ if (ev.type !== 'session.info') {
+ patchUiState({ info: { ...current, execution_generation: incoming.execution_generation } })
+ }
+ }
+
+ if (ev.type === 'approval.settled' || ev.type === 'clarify.settled') {
+ const kind = ev.type === 'approval.settled' ? 'approval' : 'clarify'
+ const promptId = ev.payload?.prompt_id
+
+ patchOverlayState(previous => previous[kind]?.sharedControl?.prompt_id === promptId
+ ? { ...previous, [kind]: null } : previous)
+
+ return
+ }
+
+ if (handleVoiceCapture(ev, ctx.voice)) {
+ return
+ }
+
switch (ev.type) {
case 'connection.request':
if (ev.payload) {
@@@ -1194,13 -1090,8 +1181,16 @@@
// is committed before submit reads it; invalid config also falls
// back to this established direct-submit behavior.
setInput('')
- markNextSubmitVoice(text)
- setTimeout(() => submitRef.current(text), 0)
+ setTimeout(() => {
+ if (isCurrentDestination(destination)) {
++ // Only a transcript submitted where it was spoken is a voice turn;
++ // one re-routed to its own session's queue lands as typed text.
++ markNextSubmitVoice(text)
+ submitRef.current(text)
+ } else {
+ enqueue?.(text, text, destination)
+ }
+ }, 0)
})
return
diff --cc ui-tui/src/app/submissionCore.ts
index 3f07ddab3d1,e7f94ec6162..c20f4ebb390
--- a/ui-tui/src/app/submissionCore.ts
+++ b/ui-tui/src/app/submissionCore.ts
@@@ -70,130 -74,34 +86,132 @@@ export function submitPrompt
return deps.sys('session not ready yet')
}
+ // An identityless write cannot be deduplicated, even after the owner upgrades.
+ if (opts.queueItem?.legacyAttempted) {
+ opts.queueItem.settle?.(false)
+
+ if (focused()) {
+ deps.sys('delivery unconfirmed — check the session before sending a new input; retained input was not resent')
+ patchUiState({ status: 'delivery unconfirmed' })
+ }
+
+ return
+ }
+
// Close the async-busy gap up front, before the detect_drop round-trip.
- markSubmitting()
+ if (ownsTurn()) {
+ markSubmitting()
+ }
const startSubmit = (displayText: string, submitText: string, show = true) => {
- const liveSid = getUiState().sid
+ if (ownsTurn()) {
+ turnController.clearStatusTimer()
+ deps.setLastUserMsg(text)
+
+ if (show) {
+ deps.appendMessage({ role: 'user', text: displayOverride || displayText })
+ }
- if (!liveSid) {
- return deps.sys('session not ready yet')
+ patchUiState({ busy: true, status: 'running…' })
+ turnController.bufRef = ''
+ turnController.interrupted = false
}
- turnController.clearStatusTimer()
- deps.setLastUserMsg(text)
+ const item = opts.queueItem
- if (show) {
- deps.appendMessage({ role: 'user', text: displayOverride || displayText })
+ if (item) {
+ item.preparedText ??= submitText
+
+ // Busy controls have no deduplication receipt: never replay after an ambiguous reply.
+ if (item.controlMethod) { item.legacyAttempted = true }
+ item.attachments ??= opts.attachments?.map(attachment => ({ ...attachment }))
+
+ if (opts.behindTurn) { item.queued = true }
+
+ if (ownsTurn() && show) { markBubbleShown(item.submissionId) }
+ savePendingInput(item)
}
- patchUiState({ busy: true, status: 'running…' })
- turnController.bufRef = ''
- turnController.interrupted = false
+ if (item?.controlMethod && item.attachments?.length) {
+ item.settle?.(false)
+
+ if (focused()) { deps.sys('busy corrections accept text only — image input retained; submit it with /queue') }
+
+ return
+ }
deps.gw
- .request<PromptSubmitResponse>('prompt.submit', {
- session_id: liveSid,
- text: submitText,
- ...(takeVoiceTurn(submitText) && { voice_turn: true })
+ .request<PromptSubmitResponse>(item?.controlMethod ?? 'prompt.submit', {
+ session_id: sid,
+ text: item?.preparedText ?? submitText,
+ ...((item?.attachments ?? opts.attachments)?.length ? { attachments: item?.attachments ?? opts.attachments } : {}),
+ ...(item?.controlMethod ? { execution_generation: item.executionGeneration } : {}),
- ...(item && !item.controlMethod ? { submission_id: item.submissionId, queued: item.queued !== false } : {})
++ ...(item && !item.controlMethod ? { submission_id: item.submissionId, queued: item.queued !== false } : {}),
++ // A busy correction (steer/redirect) is not a turn: it never claims the voice route.
++ ...(!item?.controlMethod && takeVoiceTurn(submitText) && { voice_turn: true })
})
.then(r => {
+ if (item?.controlMethod) {
+ const control = r as PromptSubmitResponse & { execution_generation?: number }
+
+ const accepted = control.execution_generation === item.executionGeneration &&
+ ['queued', 'redirected'].includes(control.status ?? '')
+
+ item.settle?.(accepted)
+
+ if (focused()) { deps.sys(accepted ? `correction ${control.status}` : 'correction rejected — input retained') }
+
+ return
+ }
+
+ if (item) {
+ const accepted =
+ (r?.input_id ?? r?.admission_id) === item.submissionId &&
+ Boolean(destination.storedSid) &&
+ r?.target_session_id === destination.storedSid &&
+ r?.target_profile_home === destination.profileHome &&
+ ['queued', 'started', 'terminal', 'unknown'].includes(r?.status ?? '')
+
+ item.settle?.(accepted)
+
+ // A replay receipt ends this admission, not necessarily the current
+ // execution. Refresh the same live attachment without its transcript.
+ if (accepted && focused() && ['terminal', 'unknown'].includes(r.status ?? '')) {
+ const observed = getUiState().info
+
+ void deps.gw.request<SessionActivateResponse>('session.activate', { session_id: sid, omit_messages: true })
+ .then(snapshot => {
+ const current = getUiState().info
+ const info = snapshot.info
+
+ // Push lifecycle events (including same-generation completion)
+ // win over an in-flight snapshot; attachment changes win too.
+ if (!focused() || current !== observed || snapshot.session_id !== sid ||
+ (snapshot.session_key || info?.stored_session_id) !== owner.storedSid ||
+ typeof snapshot.running !== 'boolean' ||
+ (current?.execution_generation !== undefined &&
+ (info?.execution_epoch !== current.execution_epoch ||
+ !Number.isSafeInteger(info?.execution_generation) ||
+ (info?.execution_generation ?? -1) < current.execution_generation))) {
+ return
+ }
+
+ patchUiState({ busy: snapshot.running, status: snapshot.running ? 'running…' : 'ready',
+ info: current && { ...current, execution_epoch: info?.execution_epoch ?? current.execution_epoch,
+ execution_generation: info?.execution_generation ?? current.execution_generation,
+ running: snapshot.running } })
+ })
+ .catch((error: Error) => {
+ if (focused()) { deps.sys(`execution status unconfirmed: ${error.message}`) }
+ })
+ }
+
+ if (!accepted && focused()) {
+ deps.sys('admission not confirmed — input retained; use Alt+K to retry with the same identity')
+ patchUiState({ status: 'admission unconfirmed' })
+ }
+ }
+
// The gateway consumed a typed voice stop phrase server-side (voice
// chat ended, no turn started) — release the busy latch; the
// voice.transcript {stop_phrase} event handles the mode flags + notice.
diff --cc ui-tui/src/types.ts
index da557dd516c,a056b9d6fe6..97c52b88256
--- a/ui-tui/src/types.ts
+++ b/ui-tui/src/types.ts
@@@ -98,8 -96,7 +98,8 @@@ export interface DelegationStatus
}
export interface ApprovalReq {
+ sharedControl?: SharedControl
- // false when the backend won't honor a permanent allow (tirith warning) → hide "Always allow".
+ // false when the backend won't honor a permanent allow → hide "Always allow".
allowPermanent?: boolean
choices?: string[]
command: string