The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge remote-tracking branch 'origin/main' into fix/106742-thread-resolution
teknium1eec5bd667387
diff --cc acp_adapter/entry.pyindex 9f6ec9ebe87,0851ad16766..10d4a4ee502--- a/acp_adapter/entry.py+++ b/acp_adapter/entry.py@@@ -182,18 -190,32 +190,25 @@@ def main(argv: list[str] | None = Noneimport acpfrom .server import HermesACPAgent+ # Windows: import the configured memory provider (and numpy) on the main thread before- # the MCP-discovery and ACP stdin-reader threads start (hermes_cli's ~150 ms- # plugin-discovery thread is the only one already running). A first-time- # native-extension import (numpy via holographic / mnemosyne / hindsight) racing another- # thread's import chain deadlocked in create_module and session/new never answered- # (#58083). After this the off-loop agent build finds the modules in sys.modules.++ # the ACP stdin-reader thread starts. A first-time native-extension import racing another++ # thread's import chain deadlocked in create_module and session/new never answered (#58083).+ if sys.platform == "win32":+ _warm_memory_provider_import(logger)+- # MCP discovery from config.yaml runs in a background daemon thread so the ACP server is- # responsive immediately (blocking here cost 2-5 s); per-session MCP servers registered via- # asyncio.to_thread are unaffected. Metadata-only hosts can opt out of the global startup.- # Previously this blocked asyncio.run() for 2-5 s. (ACP also registers per-session MCP servers- # dynamically via asyncio.to_thread inside the event loop; that path is unaffected.) Moved from- # model_tools.py module scope to avoid freezing the gateway's loop on lazy import (#16856).- if os.environ.get("HERMES_ACP_SKIP_CONFIGURED_MCP", "").strip() != "1":- try:- from hermes_cli.mcp_startup import start_background_mcp_discovery++ # MCP discovery and execution belong to the gateway daemon; this process is a viewer.+ agent = HermesACPAgent()- start_background_mcp_discovery(logger=logger, thread_name="acp-mcp-discovery")- except Exception:- logger.debug("MCP tool discovery failed at ACP startup", exc_info=True)+ async def serve():+ # MCP and execution belong to the daemon. Close only this viewer, while+ # its event loop is still alive, including on protocol/transport errors.+ try:+ await acp.run_agent(agent, use_unstable_protocol=True)+ finally:+ await agent.aclose()- agent = HermesACPAgent()try:- asyncio.run(acp.run_agent(agent, use_unstable_protocol=True))+ asyncio.run(serve())except KeyboardInterrupt:logger.info("Shutting down (KeyboardInterrupt)")except Exception:diff --cc agent/agent_init.pyindex 72b468d4d2a,4d2bb6c993f..d6f41877b68--- a/agent/agent_init.py+++ b/agent/agent_init.py@@@ -2234,29 -2345,8 +2354,15 @@@ def init_agentcheckpoint_max_snapshots: int = 20, checkpoint_max_total_size_mb: int = 500,checkpoint_max_file_size_mb: int = 10, pass_session_id: bool = False,requested_provider: str = None, capabilities: Optional[Dict[str, bool]] = None, cwd: Optional[str] = None,+ side_agent: bool = False,):- """Initialize the AI Agent (body of :meth:`AIAgent.__init__`).-- Non-obvious parameters:- max_iterations: default unlimited (sys.maxsize); the budget is shared with subagents.- requested_provider: provider identity before runtime canonicalization.- cwd: logical session workspace, available to memory providers during construction;- None or empty leaves the runtime cwd resolver unpinned.- openrouter_min_coding_score: coding-score floor for ``openrouter/pareto-code`` only.- clarify_callback: ``(question, choices) -> str``; None → the clarify tool errors.- reasoning_config: None → ``{"enabled": True, "effort": "medium"}`` on OpenRouter.- prefill_messages: priming history. Anthropic Sonnet/Opus 4.6+ 400 on a trailing- assistant message — use structured outputs there instead.- skip_context_files: skip SOUL.md/.hermes.md/AGENTS.md/CLAUDE.md/.cursorrules injection;- load_soul_identity keeps ~/.hermes/SOUL.md as identity regardless.- """+ from agent.safe_worker_policy import safe_worker_enabled++ if safe_worker_enabled():+ skip_context_files = skip_memory = skip_background_review = True+ load_soul_identity = False+ prefill_messages = []+ fallback_model = {}_install_safe_stdio()_params = locals()diff --cc agent/skill_commands.pyindex f03a4672c3a,7f3de811485..e6c50d5f7fa--- a/agent/skill_commands.py+++ b/agent/skill_commands.py@@@ -152,12 -153,17 +153,21 @@@ def _resolve_skill_commands_home() -> sreturn str(get_hermes_home())+ def _resolve_skill_commands_project() -> Optional[str]:+ """The project root the scan's project skills resolve from (None outside a repo). One multi-session+ host serves sessions in different repos; without this tag the first session's project skills stayed+ published for every other session's ``get_skill_commands`` lookup (#114359)."""+ from agent.skill_utils import find_project_root+ root = find_project_root()+ return str(root) if root is not None else None++def _load_skill_payload(skill_identifier: str, task_id: str | None = None) -> tuple[dict[str, Any], Path | None, str] | None:"""Load a skill by name/path and return (loaded_payload, skill_dir, display_name)."""+ from agent.safe_worker_policy import safe_worker_enabled++ if safe_worker_enabled():+ return Noneraw_identifier = (skill_identifier or "").strip()if not raw_identifier:return None@@@ -372,13 -393,10 +397,14 @@@ def scan_skill_commands() -> Dict[str,Builds a local map and publishes once at the end: writing straight into theglobal exposed partial results to overlapping scans, which then loggedbogus "already claimed" collisions against their own incumbents."""+ from agent.safe_worker_policy import safe_worker_enabled++ if safe_worker_enabled():+ return {}- global _skill_commands, _skill_commands_platform, _skill_commands_home+ global _skill_commands, _skill_commands_platform, _skill_commands_home, _skill_commands_projectplatform = _resolve_skill_commands_platform()home = _resolve_skill_commands_home()+ project = _resolve_skill_commands_project()# Build into a local map and publish once, at the end. Writing straight into the global made a scan's# partial results visible to everything else in the process: a second, overlapping scan deduped against# its own (empty) ``seen_names`` but collided against the first scan's already- published slugs, logging@@@ -427,20 -445,15 +453,19 @@@def get_skill_commands() -> Dict[str, Dict[str, Any]]:"""Return the current skill commands mapping (scan first if empty). Rescanswhen the platform scope (one gateway serving Telegram and Discord) or the- active profile's home (Desktop profile switch) changes, so each sees its- own ``platform_disabled`` / ``external_dirs`` view.+ active profile's home (Desktop profile switch) or the session's project root (two sessions in two+ repos) changes, so each sees its own ``platform_disabled`` / ``external_dirs`` / project-skill view.- See #14536, #88023.+ See #14536, #88023, #114359."""+ from agent.safe_worker_policy import safe_worker_enabled++ if safe_worker_enabled():+ return {}- current_platform = _resolve_skill_commands_platform()- current_home = _resolve_skill_commands_home()+ current = (_resolve_skill_commands_platform(), _resolve_skill_commands_home(), _resolve_skill_commands_project())with _publish_lock:commands = _skill_commands- is_fresh = bool(commands) and (_skill_commands_platform, _skill_commands_home) == (current_platform, current_home)+ is_fresh = bool(commands) and (_skill_commands_platform, _skill_commands_home, _skill_commands_project) == current# Scan outside the lock — file I/O and deferred imports; concurrent scans# are safe since each builds its own map.return commands if is_fresh else scan_skill_commands()diff --cc apps/desktop/electron/main.tsindex a5bd985a357,6779b7ac93b..23dd50a7e26--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@@ -1,17 -1,4 +1,18 @@@import { execFileSync, spawn } from 'node:child_process'++import type { GatewayEndpoint } from './local-gateway'+import { configureWindowsGatewayTicketClient, createLocalGatewayDials, ensureLocalGateway, mintLocalGatewayTicket, nativeGatewayHttpHeaders, redialLocalGateway, runGatewayEnsure } from './local-gateway'+import { mintGatewayTicketWithPython } from './local-gateway-python'+const localGatewayDials = createLocalGatewayDials()+configureWindowsGatewayTicketClient(async (endpoint, purpose) => {+ const backend = await ensureRuntime(await resolveHermesBackend([]), () => undefined)+++ if (backend.kind !== 'python' || backend.shell) {+ throw new Error('Gateway ticket bootstrap requires the installed Hermes Python runtime')+ }++ return mintGatewayTicketWithPython(backend, resolveHermesCwd(), endpoint, purpose)+})import crypto from 'node:crypto'import fs from 'node:fs'import http from 'node:http'@@@ -248,6 -256,13 +266,7 @@@ importtightenSecretFileMode,writeSecretFileAtomic} from './hardening'-import {- type AttachedBackend,- attachOrReserveSpawn,- spawnLedgerPath,- type SpawnReservation-} from './host-backend-attach'-import { assertNoSecondLocalBackend, assertNotPassiveSpawn } from './host-backend-singleton'++import { assertNotPassiveSpawn } from './host-backend-singleton'import { requestHudClose } from './hud-close'import { cursorPointInWindow } from './hud-cursor'import { startHudGameOverlayWatch } from './hud-game-overlay'@@@ -283,8 -302,9 +306,9 @@@ importimport { registerMcpOauthCallbackIpc } from './mcp-oauth-callback-ipc'import { createMediaProtocolHandler, MEDIA_PROTOCOL } from './media-protocol'import { fetchLocalMedia } from './media-range'+ import { createMinimizeToTray } from './minimize-to-tray'import { createNativeAccessTokenCoordinator, NativeAuthChangedError } from './native-access-token'-import { oauthSessionIsLive, resolveJsonBody, resolveReadinessProbeAuth } from './native-auth-decisions'+import { oauthSessionIsLive, resolveJsonBody, resolveOauthRestAuth, resolveReadinessProbeAuth } from './native-auth-decisions'import {nativeRefreshUrl,type NativeTokenSet,@@@ -311,8 -331,25 +335,10 @@@ importlocalRouteFallbackProfiles,undialedSshRouteSeeds} from './plugin-profile-routes'-import { clampPoolLimits, parsePoolLimits, POOL_LIMITS_DEFAULTS } from './pool-limits'-import { createPoolRetirer } from './pool-retire'-import { createPoolRetirementClient } from './pool-retire-http'-import {- BackgroundSlotRetryBackoff,- BackgroundSlotRetryDeferredError,- isBackgroundSlotRetryDeferred,- isBackgroundSlotWaitTimeout,- LocalBackendSpawnCoordinator,- type LocalBackendSpawnPriority,- type LocalBackendSpawnRequest,- registerLocalBackendExitFinalizer,- releaseLocalBackendSlotAfterExit-} from './pool-spawn-coordinator'-import { createPoolStopper } from './pool-stop'-import { poolTouchKeys } from './pool-touch-scope'+ import { createPortalSession } from './portal-session'import { createKeepAwake } from './power-save'+ import { readPreUpdateBackupEnabled } from './pre-update-backup-config'+import { registerPreparedSubmissions } from './prepared-submissions'import { capturePreviewContents } from './preview-capture'import { PreviewReachRegistry } from './preview-reach'import {@@@ -1475,37 -1552,219 +1542,32 @@@ const backendDialClaims = new BackendDi// True while connection-config:apply soft-rehomes the primary — suppresses the// backend-exit toast so an intentional kill doesn't look like a crash.let softRehomeInProgress = false-// Primary-slot bookkeeping for the exit supervisor (#112344). `primaryStartsInFlight`-// counts startHermes() calls that have not settled; `primaryRecoverySuppressed`-// is set by every intentional invalidate of the slot and cleared by the next-// startHermes(), so the dying child's stale exit never respawns behind a-// re-home, a quit, or a latched boot failure.-let primaryStartsInFlight = 0-let primaryRecoverySuppressed = false-const primaryExitRecovery = createBackendExitRecoveryLatch()-// Additional per-profile backends, keyed by profile name. The PRIMARY backend-// (the desktop's launch profile) stays managed by backendConnectionState +-// startHermes(); this pool only holds EXTRA profile-// backends spawned lazily when a session belongs to a different profile. A user-// with no named profiles never populates this map, so their experience is-// byte-for-byte the single-backend behavior.-const backendPool = new Map() // profile -> { process, port, token, connectionPromise, lastActiveAt }+// Cached connection DESCRIPTORS for every non-primary (connectionId, profile)+// scope the app has dialed: canonical local gateways reached through+// `hermes gateway ensure`, registry remotes, per-profile remote overrides.+// Never a process — the gateway owns its own lifetime; forgetting an entry only+// forces the next ensure*() to re-dial. A user with no named profiles never+// populates this map.+const backendPool = new Map() // scope key -> { connectionPromise, remoteBaseUrl }++// Escape hatch: a dedicated, private backend for this app instead of the host's.++const ISOLATED_BACKEND = process.env.HERMES_DESKTOP_ISOLATED_BACKEND === '1'const profileDeletionGate = new ProfileDeletionGate()-// Keep the pool light: cap concurrent profile backends (LRU eviction) and reap-// idle ones. A user idles at exactly the primary backend; pool backends only-// exist while a non-primary profile is actively being chatted through.-// Pool sizing is a device preference (Settings → Advanced → pool rows), not a-// launch constant: mutable at runtime, persisted in userData, applied live.-// The legacy HERMES_DESKTOP_POOL_* env vars remain the initial-value fallback-// for scripted/headless setups; after launch the stored preference wins.-const POOL_LIMITS_PATH = path.join(app.getPath('userData'), 'pool-limits.json')--function readPersistedPoolLimits() {- try {- const limits = parsePoolLimits(fs.readFileSync(POOL_LIMITS_PATH, 'utf8'))- rememberLog(- `[pool-limits] loaded from ${POOL_LIMITS_PATH}: maxBackends=${limits.maxBackends}, idleMs=${limits.idleMs}`- )-- return limits- } catch {- // No persisted file yet — fall back to the legacy env vars so scripted- // setups keep working. Log which source won: a silently-ignored env var- // here costs a scripted-setup user a debugging session.- const fromEnv = clampPoolLimits({- maxBackends: Number(process.env.HERMES_DESKTOP_POOL_MAX) || undefined,- idleMs: Number(process.env.HERMES_DESKTOP_POOL_IDLE_MS) || undefined- })-- if (fromEnv.maxBackends !== POOL_LIMITS_DEFAULTS.maxBackends || fromEnv.idleMs !== POOL_LIMITS_DEFAULTS.idleMs) {- rememberLog(- `[pool-limits] no saved file; using env-var overrides: maxBackends=${fromEnv.maxBackends}, idleMs=${fromEnv.idleMs}`- )- } else {- rememberLog('[pool-limits] no saved file and no env overrides; using defaults')- }-- return fromEnv- }-}--function persistPoolLimits(limits) {- try {- fs.mkdirSync(path.dirname(POOL_LIMITS_PATH), { recursive: true })- // Atomic write: write to a temp file in the same directory, then rename.- // A crash mid-write would otherwise leave truncated JSON and silently- // lose the user's saved sizing.- const tmpPath = `${POOL_LIMITS_PATH}.tmp`- fs.writeFileSync(tmpPath, JSON.stringify(limits, null, 2), 'utf8')- fs.renameSync(tmpPath, POOL_LIMITS_PATH)- } catch (error) {- rememberLog(`[pool-limits] write failed: ${error.message}`)- }-}-// rememberLog() state. Declared here, before the top-level-// readPersistedPoolLimits() call below, because that call logs during module-// evaluation; declaring these later crashed launch with `undefined.push` in-// the packaged build (esbuild lowers the TDZ to undefined instead of throwing).-const hermesLog: string[] = []+// rememberLog() state. Declared before any top-level caller that logs during+// module evaluation; declaring these later crashed launch with `undefined.push`+// in the packaged build (esbuild lowers the TDZ to undefined instead of throwing).+const hermesLog = []let desktopLogBuffer = ''let desktopLogFlushTimer = nulllet desktopLogFlushPromise = Promise.resolve()- // Passive reads may reuse a cached descriptor, but never start an owner.- function assertNotPassiveSpawn(passive: boolean, poolKey: string): void {- if (passive) {- throw new Error(`Passive read: no warm backend for "${poolKey}"`)-let poolLimits = readPersistedPoolLimits()-// Hard cap on local backends that are starting OR running (the LRU eviction-// above is soft — it spares keepalive-fresh entries). Follows the live-// preference: setPoolLimits() pushes a new max into the coordinator.-const localBackendSpawnCoordinator = new LocalBackendSpawnCoordinator(poolLimits.maxBackends)-const backgroundSlotRetryBackoff = new BackgroundSlotRetryBackoff()-// How long a spawn may wait for a free local slot. Must stay under the-// renderer's BACKEND_BOOT_WAIT_TIMEOUT_MS (45s, src/lib/with-timeout.ts) so-// the queued ticket fails before the renderer does and the user sees why.-const POOL_SLOT_WAIT_MS = 30_000--function spawnPriorityFrom(value: unknown): LocalBackendSpawnPriority {- return value === 'foreground' ? 'foreground' : 'background'-}--// Foreground intent for a dial whose pool entry does not exist yet: a user-// click that joins an in-flight backendDialClaims claim never re-enters-// ensureBackend(), and the claim owner may still be awaiting poolStopper /-// registry resolution before backendPool.set(). The local spawn takes the mark-// right before its slot request; the IPC handler that set it clears it once-// the claim settles, so a dial that never reaches a slot request (primary-// route, remote scope, a guard rejection) cannot leave it for a later-// hydration spawn of the same key to pick up.-const pendingForegroundSpawns = new Set<string>()--function takeForegroundSpawn(...poolKeys: string[]): boolean {- let marked = false-- for (const poolKey of poolKeys) {- marked = pendingForegroundSpawns.delete(poolKey) || marked-- }-- return marked-}--// Upgrade a pooled entry (running, spawning, or queued for a slot) to-// foreground so a queued slot wait can take the reserved foreground slot.-function promotePoolEntry(entry: any): void {- entry.spawnPriority = 'foreground'- entry.localBackendSpawnRequest?.promote?.('foreground')--}---// Land a spawn failure in desktop.log. Background slot waits back off per-// profile under a saturated pool, so a roster refresh cannot create a retry-// storm while a user-triggered foreground open still gets its reserved slot.+// Land a spawn failure in desktop.log.function logPoolSpawnFailure(label: string, error: unknown): void {- if (isBackgroundSlotRetryDeferred(error)) {- return- }-- if (isBackgroundSlotWaitTimeout(error)) {- rememberLog(`Profile backend ${label} slot wait timed out (background); retry is backing off`)- } else {- rememberLog(- `Hermes backend for profile ${label} failed to start: ${error instanceof Error ? error.message : String(error)}`- )- }-}--// Apply foreground intent to the dial claim for `scopeKey`: an entry already-// in the pool is promoted directly, otherwise the intent is marked for the-// spawn the claim owner is about to start. Returns the cleanup that clears a-// mark the dial never consumed.-function applySpawnPriority(scopeKey: string, spawnPriority: LocalBackendSpawnPriority): () => void {- // The renderer's socket-close event may beat its parking IPC. Main owns- // this fence too, so that race cannot resurrect the retired generation.- for (const key of poolTouchKeys(scopeKey)) {- poolRetirer.assertCanOpen(key, spawnPriority)- }-- if (spawnPriority !== 'foreground') {- return () => undefined- }-- const existing = backendPool.get(scopeKey)-- if (existing) {- promotePoolEntry(existing)- } else {- pendingForegroundSpawns.add(scopeKey)- }-- return () => void pendingForegroundSpawns.delete(scopeKey)-}--function poolMaxBackends() {- return poolLimits.maxBackends-}--function poolIdleMs() {- return poolLimits.idleMs-}--/**- * Apply new limits live: persist, then converge the running pool — evict- * LRU backends down to the new max, and let the (already running) idle- * reaper handle a shortened idle window on its next tick. Returns the- * limits actually in force (post-clamp).- */-function setPoolLimits(raw) {- poolLimits = clampPoolLimits(raw)- persistPoolLimits(poolLimits)- localBackendSpawnCoordinator.setLimit(poolLimits.maxBackends)- void evictLruPoolBackends(poolMaxBackends())- startPoolIdleReaper()-- return { ...poolLimits }+ rememberLog(+ `Hermes backend for profile ${label} failed to start: ${error instanceof Error ? error.message : String(error)}`+ )}-// A backend touched within this window has a live renderer socket (the keepalive-// pings every 60s for every open profile). LRU eviction must spare these — a-// concurrent multi-profile session keeps several backends "fresh" at once, and-// killing one to honor the soft cap would abort a running agent.-//-// The window is intentionally MUCH wider than the 60s ping cadence:-// * 1 missed ping = +60s of apparent silence-// * WSL2 IPC stall = the renderer's `hermes:backend:touch` roundtrips-// through 9p; a single brief 9p hiccup can stretch a-// ping to ~30s of observed silence (#95189: gateways-// exited every ~2 min on WSL2 because the previous-// 90s window left no headroom — one delayed ping-// pushed a live backend past the threshold and the-// cap-driven eviction killed the active profile's-// backend mid-session, re-minting runtime ids and-// re-allocating pooled gateway secondaries ~700×/day).-// * 3× ping + 60s headroom = ~4 min, comfortable margin for two missed-// pings + WSL2 IPC stall. The hard ceiling for the cap-eligible set is-// pool idle window above (default 10 min) — this constant only governs the-// "is this backend plausibly still alive" question for LRU eviction,-// not when the idle reaper definitively tears a backend down.-const POOL_KEEPALIVE_FRESH_MS = Math.max(- 120_000,- Number(process.env.HERMES_DESKTOP_POOL_KEEPALIVE_FRESH_MS) || 4 * 60_000-)--let poolIdleReaper = nulllet backendOrphanReapPromise = null// Auto-reload budget for renderer crashes, shared by EVERY window (primary,// secondary session, instance) so a crash loop anywhere is suppressed after@@@ -11243,58 -11420,31 +11186,67 @@@ function profileRouteOptions(profile, r// Resolve a backend connection for the given profile, per the routing table in// resolveProfileBackendRoute(). An empty / unknown profile resolves to the// primary, so legacy callers are unchanged.+// Drop the cached descriptor for a canonical local gateway whose owner is gone+// so the next ensureBackend() re-runs `gateway ensure` (attach or start) instead+// of minting tickets against a dead control socket. Nothing is killed: the+// descriptor never owned the runtime.+async function forgetLocalGatewayDescriptor(profile) {+ const key = profile && String(profile).trim() ? String(profile).trim() : primaryProfileKey()+ const route = resolveProfileBackendRoute(key, profileRouteOptions(key))++ if (route.backend === 'primary') {+ const attempt = backendConnectionState.startAttempt()+ attempt.promise = backendConnectionState.getPromise()+ backendConnectionState.clearPromiseForAttempt(attempt)+ rememberLog(`[gateway] forgot stale canonical endpoint for primary "${key}"; re-ensuring`)++ return+ }++ if (backendPool.delete(key)) {+ rememberLog(`[gateway] forgot stale canonical endpoint for profile "${key}"; re-ensuring`)+ }+}++// Registry twin of forgetLocalGatewayDescriptor: a 'local' registry connection+// either delegates to the v1 profile route or pools a forced-local child under+// its composite key, so the stale descriptor lives wherever ensureRegistryBackend+// put it.+async function forgetRegistryLocalGatewayDescriptor(connectionId, profile) {+ const profileKey = String(profile ?? '').trim() || 'default'+++ const localRoute = resolveRegistryLocalRoute(profileKey, {+ globalRemote: globalRemoteActive(),+ profileRemoteOverride: Boolean(profileHasRemoteOverride(profileKey))+ })++ if (localRoute.delegate) {+ return forgetLocalGatewayDescriptor(profile)+ }++ if (backendPool.delete(localRoute.poolKey)) {+ rememberLog(`[gateway] forgot stale canonical endpoint for connection "${String(connectionId || '').trim() || 'primary'}" profile "${profileKey}"; re-ensuring`)+ }+}+- async function ensureBackend(profile, opts: { passive?: boolean } = {}) {+ async function ensureBackend(+ profile,- opts: {- passive?: boolean- request?: { method?: string; path?: string }- spawnPriority?: LocalBackendSpawnPriority- } = {}++ opts: { passive?: boolean; request?: { method?: string; path?: string } } = {}+ ) {- localBackendLifecycle.assertCanStart()const key = profile && String(profile).trim() ? String(profile).trim() : primaryProfileKey()- const spawnPriority = spawnPriorityFrom(opts.spawnPriority)- poolRetirer.assertCanOpen(key, spawnPriority)const passive = Boolean(opts.passive)profileDeletionGate.assertCanStart(key)- const route = resolveProfileBackendRoute(key, profileRouteOptions(key))+ // The REQUEST is part of the routing decision (case 5/6): resolving without+ // it would collapse a profile onto the shared backend that the caller's+ // resolveProfileApiRequest deliberately kept pooled, and the unscopable+ // destructive write would execute against the primary's home after all.+ const routeOpts = profileRouteOptions(key, opts.request)+ const route = resolveProfileBackendRoute(key, routeOpts)if (route.backend === 'primary') {- const connection = await startHermes()+ const connection = await startHermes(key)setWslBridgeProfileState(key, connection.mode !== 'remote')// A shared backend still owes the caller its profile scope, so renderer-side@@@ -12180,40 -12561,347 +12132,41 @@@ async function dialPoolBackend(profile}}- // Everything below starts a LOCAL `hermes serve` child. Multiplex-only says- // the host has exactly one, and routing (resolveProfileBackendRoute case 6)- // keeps local profiles off this path — this is the backstop that makes the- // pool spawn path genuinely unreachable rather than merely unused.- // Same options object the router reads, so the guard cannot drift from it- // (profileRouteOptions folds the per-profile SSH override into- // profileRemoteOverride; a hand-rolled term here missed that).- const guardRoute = profileRouteOptions(profile)+ assertLocalProfileCanStart(profile, profileDeletionGate, key =>+ directoryExists(path.join(HERMES_HOME, 'profiles', key))+ )- assertNoSecondLocalBackend(poolKey, {- isolated: guardRoute.isolatedBackend,- primaryRemoteActive: guardRoute.primaryRemoteActive,- profileRemoteOverride: opts.forceLocal ? false : guardRoute.profileRemoteOverride,- unscopableRequest: opts.unscopableRequest- })-- // Bound the slot wait BELOW the renderer's backend-boot budget (45s): once- // the renderer has given up on this spawn, a ticket still queued for the- // pool-idle window (10 min) would hold the pool key hostage and every- // later click on the profile would join that stale wait. Failing here- // surfaces the "all N slots busy" reason instead of a generic boot timeout.- // The caller stamped entry.spawnPriority from its own request; a foreground- // dial that joined the claim before this entry existed left a mark instead.- if (takeForegroundSpawn(poolKey, profile)) {- entry.spawnPriority = 'foreground'- }-- const spawnPriority: LocalBackendSpawnPriority = spawnPriorityFrom(entry.spawnPriority)-- assertPoolEntryStillOwned(poolKey, entry)-- if (spawnPriority === 'background' && !backgroundSlotRetryBackoff.canAttempt(poolKey)) {- throw new BackgroundSlotRetryDeferredError(profile)- }-- // The arbiter subscribes to the actual coordinator queue, so a later- // foreground promotion receives reclamation too, not just fresh starts.- const spawnRequest = localBackendSpawnCoordinator.request(poolKey, {- timeoutMs: POOL_SLOT_WAIT_MS,- priority: spawnPriority- })-- entry.localBackendSlotKey = poolKey- entry.localBackendSpawnRequest = spawnRequest-- if (spawnRequest.queued) {- rememberLog(- `Profile backend "${profile}" waiting for a free local slot (${localBackendSpawnCoordinator.activeCount}/${poolMaxBackends()} busy, ${localBackendSpawnCoordinator.queuedCount} queued)`+ const connection = await ensureLocalGateway(async () => {+ const backend = await ensureRuntime(+ await resolveHermesBackend(['--profile', profile, 'gateway', 'ensure', '--json']),+ () => assertPoolEntryStillOwned(poolKey, entry))- }-- const cancelRequest = () => spawnRequest.cancel()- localBackendLifecycle.signal.addEventListener('abort', cancelRequest, { once: true })-- try {- entry.releaseLocalBackendSlot = await spawnRequest.acquired- backgroundSlotRetryBackoff.clear(poolKey)- } catch (error) {- if (isBackgroundSlotWaitTimeout(error)) {- backgroundSlotRetryBackoff.recordFailure(poolKey)- }-- throw error- } finally {- localBackendLifecycle.signal.removeEventListener('abort', cancelRequest)- }+- if (entry.localBackendSpawnRequest === spawnRequest) {- entry.localBackendSpawnRequest = null- }-- assertPoolEntryStillOwned(poolKey, entry)-- const token = crypto.randomBytes(32).toString('base64url')-- // Same update mutual exclusion as the primary window's waitForLocalStart- // (#73822): pool backends spawn from the same venv, so an ungated respawn- // during applyUpdates' critical section re-locks the venv and trips the- // venv-blocker preflight. No boot-progress UI here — pool backends boot- // silently for background profiles — so we only log while parked.- {- let poolAnnounced = false-- const clearance = await waitForUpdateClearance(updateGateDeps(), {- signal: localBackendLifecycle.signal,- isCancelled: () => backendPool.get(poolKey) !== entry,- onWaitTick: reason => {- if (!poolAnnounced) {- poolAnnounced = true- rememberLog(`[updates] update in progress (${reason}); deferring pool backend start for profile "${profile}"`)- }- },- pollMs: UPDATE_WAIT_POLL_MS,- timeoutMs: UPDATE_WAIT_TIMEOUT_MS- })-- if (clearance === 'cancelled') {- assertPoolEntryStillOwned(poolKey, entry)- }- }-- profileDeletionGate.assertCanStart(profile)- assertPoolEntryStillOwned(poolKey, entry)-- // --profile wins over the inherited HERMES_HOME env (see _apply_profile_override- // step 3 in hermes_cli/main.py), so the child re-homes to this profile.- // --port 0: the OS assigns an ephemeral port; the child announces it on stdout.- const backendArgs = ['--profile', profile, 'serve', '--host', '127.0.0.1', '--port', '0']-- const backend = await ensureRuntime(await resolveHermesBackend(backendArgs), () =>+ profileDeletionGate.assertCanStart(profile)assertPoolEntryStillOwned(poolKey, entry)- )- // Route old runtimes (no `serve`) through the legacy `dashboard --no-open`.- backend.args = await getBackendArgsForRuntime(backend)- assertPoolEntryStillOwned(poolKey, entry)- const hermesCwd = resolveHermesCwd()- const webDist = resolveWebDist()- const readyFile = backend.readyFile ? makeDashboardReadyFile() : null-- // Guard BEFORE the "Starting" line: a profile that only exists on a remote- // backend (remote-primary desktop asked for a forced-local child) rejects- // here, and logging "Starting" first left an orphaned line with no READY- // and no exit — the exact undiagnosable burst signature in remote-gateway- // user bundles (Aug 2026, Dash's report).- assertLocalProfileCanStart(profile, profileDeletionGate, key =>- directoryExists(path.join(HERMES_HOME, 'profiles', key))- )- rememberLog(`Starting Hermes backend for profile "${profile}" via ${backend.label}`)-- const parentStartMarker = await desktopParentStartMarker()- const backendNonce = crypto.randomBytes(16).toString('hex')- const parentIdentityEnv = parentWatchdogEnv(process.pid, parentStartMarker, backendNonce)- assertPoolEntryStillOwned(poolKey, entry)-- const child = spawnOwnedBackend(- backend.command,- backend.args,- hiddenWindowsChildOptions({- cwd: hermesCwd,- env: desktopBackendSpawnEnv(- {- ...process.env,- HERMES_HOME,- ...backend.env,- // Pin the gateway's tool/terminal cwd to the same directory we chose for- // the child process. Inherited TERMINAL_CWD (or a stale config bridge)- // can still point at the install dir even when spawn cwd is home.- TERMINAL_CWD: hermesCwd,- HERMES_DASHBOARD_SESSION_TOKEN: token,- // Marks this dashboard backend as desktop-spawned so it runs the cron- // scheduler tick loop (the gateway isn't running under the app).- HERMES_DESKTOP: '1',- // Exact parent identity lets the backend self-exit after an unclean- // Desktop death without mistaking a reused PID for its owner. If the- // optional marker probe fails, retain legacy PID-only tracking.- ...parentIdentityEnv,- HERMES_WEB_DIST: webDist,- ...(readyFile ? { HERMES_DESKTOP_READY_FILE: readyFile } : {})- },- GUEST_ONBOARDING- ),- shell: backend.shell,- stdio: ['ignore', 'pipe', 'pipe']- })- )-- entry.process = child- entry.token = token- registerLocalBackendExitFinalizer(backendPool, poolKey, entry, () => releaseLocalBackendSlot(entry))- // Buffer stdout+stderr from the instant of spawn (#93608): an early crash's- // traceback must survive into the claim error and the before-ready exit- // message instead of a bare exit code. rememberLog attaches later, after- // the claim, and would miss anything printed before it.- const outputTail = createBackendOutputTail()- outputTail.attach(child)-- let ready = false- let rejectStart = null-- const startFailed = new Promise((_resolve, reject) => {- rejectStart = reject- })-- // Exit/error can now arrive while the ownership claim is still pending.- startFailed.catch(() => {})-- child.once('error', error => {- rememberLog(`Hermes backend for profile "${profile}" failed to start: ${error.message}`)- void teardownFailedLocalBackend(poolKey, entry).catch(cleanupError => {- rememberLog(- `Hermes backend for profile "${profile}" cleanup failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`- )- })- rejectStart?.(error)- })- child.once('exit', (code, signal) => {- rememberLog(formatBackendExitLine(`Hermes backend for profile "${profile}" exited`, code, signal, outputTail))- releaseBackendChild(child)-- if (!ready) {- rejectStart?.(- new Error(- `Hermes backend for profile "${profile}" exited before it became ready (${signal || code}).${outputTail.describe()}`- )- )- }- })-- // Start watching for the READY announcement BEFORE any await (#60323):- // stdout is already flowing into the tail, and Node streams never replay- // consumed chunks to late listeners — a sentinel printed while- // claimBackendChild runs would otherwise be lost forever, timing out a- // healthy backend. The tail-buffer accessor covers any residual gap.- const portAnnouncement = waitForDashboardPortAnnouncement(child, {- bufferedOutput: () => outputTail.text(),- describeOutputTail: () => outputTail.describe(),- readyFile- })-- portAnnouncement.catch(() => {})- await claimBackendChild(child, `${backend.command} ${backend.args.join(' ')}`, profile, backendNonce, outputTail)- assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })-- child.stdout.on('data', rememberLog)- child.stderr.on('data', rememberLog)-- const port = await Promise.race([portAnnouncement, startFailed])- assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })-- if (readyFile) {- fs.unlink(readyFile, () => {})- }-- entry.port = port-- const baseUrl = `http://127.0.0.1:${port}`- await Promise.race([waitForHermes(baseUrl, token), startFailed])- assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })- ready = true-- const authToken = await adoptServedDashboardToken(baseUrl, token, {- childAlive: () => child.exitCode === null && !child.killed,- label: `Hermes backend for profile "${profile}"`,- rememberLog+ return runGatewayEnsure({ ...backend, env: desktopBackendSpawnEnv(backend.env || {}, GUEST_ONBOARDING) }, resolveHermesCwd(), HERMES_HOME)+ }, async () => {+ await waitForUpdateClearance(updateGateDeps(), { pollMs: UPDATE_WAIT_POLL_MS, timeoutMs: UPDATE_WAIT_TIMEOUT_MS })+ // Update waits yield: retirement or profile deletion may win in that gap.+ assertPoolEntryStillOwned(poolKey, entry)+ assertLocalProfileCanStart(profile, profileDeletionGate, key => directoryExists(path.join(HERMES_HOME, 'profiles', key)))})- assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })-- entry.token = authToken-- // Verify the WebSocket session token before declaring backend ready.- // HTTP /api/status can pass while WS auth fails (separate transport, separate guards).- const wsUrl = `ws://127.0.0.1:${port}/api/ws?token=${encodeURIComponent(authToken)}`- const wsProbe = await probeGatewayWebSocket(wsUrl, { WebSocketImpl: globalThis.WebSocket })- assertPoolEntryStillOwned(poolKey, entry, { releaseSlot: false })-- if (!wsProbe.ok) {- throw new Error(- `Hermes backend for profile "${profile}" is HTTP-reachable but the WebSocket (/api/ws) rejected the session token: ${wsProbe.reason}`- )- }-- return {- baseUrl,- mode: 'local',- source: 'local',- authMode: 'token',- token: authToken,- profile,- wsUrl,- logs: hermesLog.slice(-80),- ...getWindowState()- }-}--// Bounded, deduplicated pool teardown (see pool-stop.ts): every stop path —-// idle reaper, LRU eviction, profile delete/rename, quit — shares one-// in-flight stop per key and retains the process handle until the bounded-// SIGTERM -> SIGKILL escalation in waitForBackendExit() resolves. Previously-// SIGTERM + immediate entry delete dropped the handle and a slow child-// survived detached under PID 1.-const poolStopper = createPoolStopper({- pool: backendPool,- stopChild: child => stopBackendChild(child),- waitForExit: child => waitForBackendExit(child),- // Remote / SSH-isolated pool entries keep `process: null`. Child exit is- // immediate; hold the same in-flight fence through bootstrap drain + SSH- // teardown so a reconnect cannot publish into a dying scope (#106935).- afterStop: async key => {- try {- await sshBootstrapCoordinator.cancelAndWait(key, () => teardownSshConnection(key))- } catch (err) {- // The idle reaper calls stopPoolBackend un-awaited; a failed SSH teardown- // must not surface as an unhandled rejection or block the pool fence.- sshRememberLog(`[ssh-teardown] ${key}: ${String(err)}`)- }- }-})--function stopPoolBackend(profile: string): Promise<void> {- const entry = backendPool.get(profile)-- const stopping = releaseLocalBackendSlotAfterExit(- () => releaseLocalBackendSlot(entry),- () => poolStopper.stop(profile)- )-- // Fire-and-forget callers still need diagnostics; awaiters receive the- // rejection, while physical ownership and the exit finalizer remain live.- void stopping.catch(error => {- rememberLog(`Profile backend "${profile}" stop failed: ${error instanceof Error ? error.message : String(error)}`)- })+ assertPoolEntryStillOwned(poolKey, entry)- return stopping+ return { ...connection, profile, logs: hermesLog.slice(-80), ...getWindowState() }}-// Tell every window the pooled backend under `poolKey` is being retired so the-// renderer parks that scope (wantOpen=false) instead of redialing into the-// slot it just vacated. Fired BEFORE the SIGTERM (pool-retire.ts contract).-function broadcastPoolBackendRetiring(poolKey: string) {- for (const win of BrowserWindow.getAllWindows()) {- const { webContents } = win-- if (webContents && !webContents.isDestroyed()) {- webContents.send('hermes:pool:retiring', { poolKey })- }- }+// Forget a cached descriptor. Nothing is killed: the gateway behind it owns its+// own lifetime (`hermes gateway ensure` attach semantics), so the next+// ensure*() for this key simply re-dials. Every retire path — dispatch probe+// failure, resume revalidation, registry removal, profile delete/rename, quit —+// funnels through here so the verb stays in one place.+async function stopPoolBackend(profile: string) {+ backendPool.delete(profile)}-const poolRetirer = createPoolRetirer({- pool: backendPool,- coordinator: localBackendSpawnCoordinator,- ...createPoolRetirementClient(fetchJson),- stopBackend: stopPoolBackend,- onRetiring: broadcastPoolBackendRetiring,- log: rememberLog-})--localBackendLifecycle.signal.addEventListener('abort', poolRetirer.dispose, { once: true })-async function teardownPoolBackendAndWait(profile) {await Promise.all(localProfilePoolKeys(profile).map(key => stopPoolBackend(key)))}@@@ -12300,7 -13004,250 +12261,16 @@@ async function prepareProfileRenameRequ})}-// ── Attach-first: one backend per HOST (multiplex-only) ───────────────────-// Escape hatch: a dedicated, private backend for this app instead of the host's.-const ISOLATED_BACKEND = process.env.HERMES_DESKTOP_ISOLATED_BACKEND === '1'-const ATTACHED_LIVENESS_POLL_MS = 15_000-let attachedBackendMonitor: NodeJS.Timeout | null = null-let hostSpawnReservation: SpawnReservation | null = null--function stopAttachedBackendMonitor() {- if (attachedBackendMonitor) {- clearInterval(attachedBackendMonitor)- attachedBackendMonitor = null- }-}--/**- * An attached backend has no child process, so `child.exit` can never drive- * recovery. Poll its readiness instead; a backend that dies under us- * invalidates the connection and hands the respawn to the same supervisor path- * a dead child would (which re-runs discovery and spawns, since the host now- * has no backend).- */-function startAttachedBackendMonitor(attached: AttachedBackend) {- stopAttachedBackendMonitor()-- attachedBackendMonitor = setInterval(() => {- void waitForHermes(attached.baseUrl, attached.token, undefined, 'token', {}).catch(() => {- stopAttachedBackendMonitor()- rememberLog(`[attach] attached backend on ${attached.baseUrl} (pid ${attached.pid}) is gone; recovering`)- invalidatePrimaryConnection()- scheduleUnexpectedPrimaryRecovery({ error: 'The Hermes backend this app attached to exited.', ready: true })- })- }, ATTACHED_LIVENESS_POLL_MS)-- attachedBackendMonitor.unref?.()-}--/** Discover and attach to the host's running backend; null means "spawn one". */-function attachToRunningHostBackend(): Promise<AttachedBackend | null> {- const options = { isolated: ISOLATED_BACKEND, ledgerPath: spawnLedgerPath(HERMES_HOME, path.join) }-- return attachOrReserveSpawn(options, hostBackendAttachDeps(), hostSpawnGateDeps())- .then(outcome => {- if ('attached' in outcome) {- releaseHostSpawnReservation()-- return outcome.attached- }-- hostSpawnReservation = outcome.reservation-- return null- })- .catch(error => {- // Discovery must never be able to block boot: fall through to spawning.- rememberLog(`[attach] host backend discovery failed (${error.message}); spawning our own`)-- return null- })-}--function hostBackendAttachDeps() {- return {- log: rememberLog,- readLedger: (target: string) => {- try {- return fs.readFileSync(target, 'utf8')- } catch {- return null- }- },- probeWebSocket: (wsUrl: string) => probeGatewayWebSocket(wsUrl, { WebSocketImpl: globalThis.WebSocket }),- resolveServedToken: (baseUrl: string) => resolveServedDashboardToken(baseUrl, ''),- waitForReady: (baseUrl: string, token: string) => waitForHermes(baseUrl, token, undefined, 'token', {})- }-}--function hostSpawnGatePath() {- return path.join(HERMES_HOME, 'desktop-backend-spawn.json')-}--function hostSpawnGateDeps() {- return {- now: () => Date.now(),- read: () => {- try {- const record = JSON.parse(fs.readFileSync(hostSpawnGatePath(), 'utf8'))- const owner = Number(record?.pid)-- if (!Number.isInteger(owner) || owner <= 0) {- return null- }-- // A gate whose owner is gone is no gate at all.- try {- process.kill(owner, 0)- } catch {- return null- }-- return { ownerAlive: true, startedAt: Number(record?.startedAt) || 0 }- } catch {- return null- }- },- take: () => {- const gatePath = hostSpawnGatePath()-- try {- fs.writeFileSync(gatePath, JSON.stringify({ pid: process.pid, startedAt: Date.now() }), { mode: 0o600 })- } catch {- // A gate we cannot write is a race we cannot win; spawning anyway is- // exactly today's behaviour, so never fail boot over it.- }-- return () => {- try {- fs.unlinkSync(gatePath)- } catch {- // Already gone / never written.- }- }- },- sleep: (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms))- }-}--function releaseHostSpawnReservation() {- hostSpawnReservation?.release()- hostSpawnReservation = null-}--function startHermes({ supervisorRecovery = false }: { supervisorRecovery?: boolean } = {}) {- primaryRecoverySuppressed = false- primaryStartsInFlight += 1-- const start = localBackendLifecycle.start(() => runHermesStart({ supervisorRecovery }))-- const releaseStart = () => {- primaryStartsInFlight -= 1- }-- // Ordering contract: this reaction is registered on the SAME promise the- // caller receives, before any caller `.catch`, so releaseStart has already- // run (primaryStartsInFlight back to 0) when runPrimaryRecoverySpawn's- // `.catch` evaluates primaryRecoveryState(). Returning a derived promise- // (start.then(...)) or wrapping `start` would invert that order: every- // pre-ready retry would see hasPendingStart:true, be refused, and leave the- // recovery claim stuck with no retry and no UI.- void start.then(releaseStart, releaseStart)-- return start-}--function primaryRecoveryState() {- return {- hasCurrentOwner: backendConnectionState.getProcess() !== null || backendConnectionState.getPromise() !== null,- hasPendingStart: primaryStartsInFlight > 0,- intentionalTeardown: primaryRecoverySuppressed || isQuittingForHandoff || backendShutdown.hasStarted()- }-}--function reportPrimaryRecoveryCrashLoop(code: number | null, signal: string | null): boolean {- if (!primaryExitRecovery.isCrashLooping()) {- return false- }-- const message =- 'Hermes backend keeps crashing right after it restarts; not restarting it again. Relaunch Hermes Desktop.'-- rememberLog(`[supervisor] ${message}`)- sendBackendExit({ code, signal, error: message })-- return true-}--function runPrimaryRecoverySpawn(code: number | null, signal: string | null) {- startHermes({ supervisorRecovery: true }).catch(respawnError => {- rememberLog(`[supervisor] backend respawn failed: ${firstLine(respawnError.message)}`)-- // Terminal boot failures still own their existing recovery UI. Only a- // supervisor-owned respawn that failed transiently before ready may spend- // another bounded recovery slot.- const latched = latchedBootFailure()-- if (latched) {- rememberLog(`[supervisor] respawn refused: boot failure latched: ${firstLine(latched.message)}`)-- return- }-- // releaseStart (startHermes) already ran: same-promise reaction order, so- // hasPendingStart is false here. See the ordering contract in startHermes.- if (primaryExitRecovery.retryAfterFailedStart(primaryRecoveryState())) {- rememberLog('[supervisor] backend respawn failed before ready; retrying within crash-loop budget')- runPrimaryRecoverySpawn(code, signal)-- return- }-- reportPrimaryRecoveryCrashLoop(code, signal)- })-}--// A ready primary child died. When its exit leaves the primary slot with no-// owner and no start in flight (outside an intentional teardown), the-// supervisor owns the respawn (#112344): the stale-classified exit used to-// "log and return", and recovery then hinged on the renderer noticing its-// socket drop — a 9 h engine-less window when it did not. Pool children are-// deliberately not consulted: they never own the window backend.-function scheduleUnexpectedPrimaryRecovery({- code = null,- signal = null,- error = null,- ready = false-}: { code?: number | null; error?: string | null; ready?: boolean; signal?: string | null } = {}) {- if (!ready) {- return false- }-- const claimed = primaryExitRecovery.claim(primaryRecoveryState())-- if (!claimed) {- return reportPrimaryRecoveryCrashLoop(code, signal)- }-- rememberLog('[supervisor] backend exit left no primary owner and no start in flight; respawning')- sendBackendExit({ code, signal, ...(error ? { error } : {}) })- runPrimaryRecoverySpawn(code, signal)-- return true-}-+ /**+ * The terminal boot failure currently latched in this process, if any. These+ * latches are cleared only by an explicit recovery path (reset, repair,- * apply-config, confirmed sign-in, or the child 'exit' handler), never by a- * retry, so both the per-request short-circuit in runHermesStart and the- * supervisor's respawn refusal must consult the same trio in the same order.++ * apply-config, confirmed sign-in), never by a retry.+ */+ function latchedBootFailure(): Error | null {+ return bootstrapFailure ?? backendStartFailure ?? remoteReauthFailure ?? null+ }+-async function runHermesStart({ supervisorRecovery = false }: { supervisorRecovery?: boolean } = {}) {+async function startHermes(requestedProfile?: string) {// Only the single-instance lock holder may reap/spawn/claim the desktop// backend. A lock-losing instance must stay inert even if some path reaches// here (e.g. the deferred-quit window before `ready`): its reapOrphans()@@@ -12465,6 -13418,37 +12435,12 @@@return setup.connection}- // Multiplex-only: a backend was already running on this host and we attached- // to it. Nothing was spawned, so there is no child to own — liveness is- // polled instead (startAttachedBackendMonitor).++ // No `attachHostBackend` is wired: `hermes gateway ensure` below IS the++ // attach-or-start step for the canonical local gateway.+ if (setup.kind === 'attached') {- const attached = setup.attached-- setWslBridgeProfileState(primaryProfile, true)- startAttachedBackendMonitor(attached)-- updateBootProgress({- phase: 'backend.ready',- message: 'Attached to the running Hermes backend',- progress: 94,- running: true,- error: null- })-- return {- baseUrl: attached.baseUrl,- mode: 'local',- source: 'local',- authMode: 'token',- attached: true,- token: attached.token,- profile: primaryProfile,- wsUrl: attached.wsUrl,- logs: hermesLog.slice(-80),- ...getWindowState()- }++ throw new Error('Unexpected attached backend outcome without a host attach step.')+ }+// Local WSL backend — paths are bridgeable.setWslBridgeProfileState(primaryProfile, true)@@@ -12511,7 -13725,8 +12487,8 @@@// child 'exit' handler to clear the cache — latching it would wedge the app// on "session expired" until a full restart, defeating reconnect, the// "Sign out & sign in" reload, and the wake-recovery revalidate path.+ // A supervisor-owned respawn never latches (see the predicate).- if (shouldLatchBackendStartFailure({ attemptedRemote, supervisorRecovery })) {+ if (shouldLatchBackendStartFailure({ attemptedRemote })) {backendStartFailure = error instanceof Error ? error : new Error(message)}@@@ -14141,9 -15414,19 +14173,10 @@@ async function connectDesktopProfileRou// both land here. The claim key mirrors ensureBackend()'s own profile// normalization so every spelling of the primary coalesces onto one dial.const scopeKey = backendScopeKey(route.connectionId, route.profile)- const clearSpawnPriority = applySpawnPriority(scopeKey, spawnPriority)+- let connection-- try {- connection = await backendDialClaims.run(scopeKey, () =>- route.connectionId- ? ensureRegistryBackend(route.connectionId, route.profile, '', { spawnPriority })- : ensureBackend(route.profile, { spawnPriority })- )- } finally {- clearSpawnPriority()- }+ const connection = await backendDialClaims.run(scopeKey, () =>+ route.connectionId ? ensureRegistryBackend(route.connectionId, route.profile) : ensureBackend(route.profile)+ )if (route.connectionId) {return { ...connection, connectionId: route.connectionId, registryScoped: true }@@@ -15966,68 -17276,22 +16019,73 @@@ async function handleHermesApiRequest(r: resolveRouteProfile(tornDownProfile, apiRoute.backendProfile)let response+ let connectiontry {- const connection = await ensureBackend(routeProfile, { passive: request?.passive })- connection = await ensureBackend(routeProfile, {++ const connection = await ensureBackend(routeProfile, {+ passive: request?.passive,- request: { method: request?.method, path: request?.path },- spawnPriority++ request: { method: request?.method, path: request?.path }+ })++const timeoutMs = resolveTimeoutMs(request?.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS)- response = await fetchJsonForBackend(connection, apiRoute.requestPath, {- method: request?.method,- body: request?.body,- upload: request?.upload,- timeoutMs- })+ const url = `${connection.baseUrl}${apiRoute.requestPath}`++ // OAuth gateways authenticate REST via EITHER a native bearer token+ // (cookieless RFC 8252 flow) OR the HttpOnly session cookie held in the OAuth+ // partition. Prefer the native bearer when present (mirroring+ // mintGatewayWsTicket): the native flow never sets a cookie, so routing an+ // oauth-mode REST call through the cookie-only path returns 401 no_cookie even+ // though a valid bearer is held. Cookie mode rides Electron's net stack bound+ // to the OAuth partition so the cookie attaches automatically. Token/local+ // modes keep using the static session-token header.+ if (connection.authMode === 'oauth') {+ // The OAuth path rides electron.net with JSON headers; multipart isn't+ // wired there. Fail loudly rather than corrupting the upload.+ if (request?.upload) {+ throw new Error('File uploads are not supported against OAuth-gated remote backends yet.')+ }++ // Native bearer first (cookieless). ensureNativeAccessToken transparently+ // refreshes a near-expiry AT via /auth/native/refresh; a null return means+ // no native session (resolveOauthRestAuth then selects the cookie path).+ const nativeAt = await ensureNativeAccessToken(connection.baseUrl).catch(() => null)+ const restAuth = resolveOauthRestAuth(nativeAt)++ if (restAuth.kind === 'bearer') {+ response = await fetchJson(url, null, {+ method: request?.method,+ body: request?.body,+ timeoutMs,+ bearer: restAuth.token+ })+ } else {+ response = await fetchJsonViaOauthSession(url, {+ method: request?.method,+ body: request?.body,+ timeoutMs+ })+ }+ } else if (connection.gatewayEndpoint) {+ response = await redialLocalGateway({+ ensure: () => ensureBackend(routeProfile),+ forget: () => forgetLocalGatewayDescriptor(routeProfile),+ use: current => fetchJson(`${current.baseUrl}${apiRoute.requestPath}`, current.token, {+ method: request?.method,+ body: request?.body,+ upload: request?.upload,+ timeoutMs,+ gatewayDescriptor: current+ })+ })+ } else {+ response = await fetchJson(url, connection.token, {+ method: request?.method,+ body: request?.body,+ upload: request?.upload,+ timeoutMs+ })+ }} catch (error) {// A failed rename PATCH must not strand the app on the temporary primary:// restore the original active profile and restart its backend.diff --cc apps/desktop/src/api/client.tsindex c51cae17cea,bbbd3703c2c..360529dc79f--- a/apps/desktop/src/api/client.ts+++ b/apps/desktop/src/api/client.ts@@@ -27,60 -25,23 +27,68 @@@ const DEFAULT_GATEWAY_REQUEST_TIMEOUT_M// ever fires when the turn itself would have been abandoned server-side.export const PROMPT_SUBMIT_REQUEST_TIMEOUT_MS = 1_800_000+ export const GATEWAY_NOT_CONNECTED_MESSAGE = 'Hermes gateway is not connected'+export class HermesGateway extends JsonRpcGatewayClient {+ private canonical = false+ private readonly protocol = new CanonicalDesktopProtocol()++ override on<K extends GatewayEventName>(type: K, handler: (event: GatewayEvent<K>) => void): () => void {+ return super.on<K>(type, event => {+ // Named listeners run before wildcard listeners in the shared client.+ // Normalize before either kind sees the prompt, including replay delivery.+ if (this.canonical) { this.protocol.event(event) }+ handler(event)+ })+ }++ override async connect(wsUrl: string): Promise<void> {+ this.canonical = new URL(wsUrl).searchParams.has('native_dial')++ return super.connect(wsUrl)+ }++ override async request<T>(method: string, params: Record<string, unknown> = {}, timeoutMs?: number, signal?: AbortSignal): Promise<T> {+ if (!this.canonical) { return super.request<T>(method, params, timeoutMs, signal) }+ const prepared = this.protocol.prepare(method, params)+ const wireMethod = this.protocol.wire(method, prepared)++ try {+ const result = await super.request<T>(wireMethod, prepared, timeoutMs, signal)++ return this.protocol.settle(method, prepared, this.protocol.result(method, prepared, result), (m, p) => this.request(m, p)) as T+ } catch (error) {+ this.protocol.failure(prepared, error)+ throw error+ }+ }+constructor() {super({closedErrorMessage: 'Hermes gateway connection closed',connectErrorMessage: 'Could not connect to Hermes gateway',createRequestId: nextId => nextId,- notConnectedErrorMessage: 'Hermes gateway is not connected',+ notConnectedErrorMessage: GATEWAY_NOT_CONNECTED_MESSAGE,+ // The channel already answered -32603; surface the crash in devtools like the dial-failure sink.+ onRequestHandlerError: (error, request) =>+ console.error(`[gateway] server request handler crashed for ${request.method} (${request.id}):`, error),+ // The channel already answered -32601; note the missing registry in devtools.+ onUnhandledRequest: request =>+ console.warn(`[gateway] Hermes Desktop has no server-request registry for ${request.method} (${request.id})`),- requestTimeoutMs: DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS+ requestTimeoutMs: DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS,+ socketFactory: url => {+ const parsed = new URL(url)++ if (!parsed.searchParams.has('native_dial')) {return new WebSocket(url)}+ const ticket = parsed.searchParams.get('ticket')++ if (!ticket) {throw new Error('Native gateway requires a fresh private ticket')}+ parsed.searchParams.delete('ticket')++ return new WebSocket(parsed.toString(), [CANONICAL_GATEWAY_PROTOCOL, `hermes-gateway-ticket.${ticket}`])+ }})+ this.onEvent(event => { if (this.canonical) { this.protocol.event(event) } })}}diff --cc apps/desktop/src/api/sessions.test.tsindex b216d699dac,f3399eab4aa..4788d11d9b2--- a/apps/desktop/src/api/sessions.test.ts+++ b/apps/desktop/src/api/sessions.test.ts@@@ -19,6 -26,7 +26,12 @@@ const hermesApi = vi.mocked(client.hermbeforeEach(() => {vi.clearAllMocks()vi.mocked(client.getApiRequestConnection).mockReturnValue('prometheus')+ vi.mocked(client.getApiRequestProfile).mockReturnValue(null)++ // Session writes scope through the same helper as reads: a named owner is++ // its own scope, an unnamed one is the ambient (empty) scope.++ vi.mocked(client.capabilityScoped).mockImplementation(scope =>++ typeof scope === 'string' && scope.trim() ? { profile: scope.trim() } : {}++ )})describe('deleteSession profile scoping', () => {@@@ -103,12 -126,30 +131,30 @@@ describe('setSessionArchived profile sc})})- it('omits the profile from the body when none is given', async () => {+ it('falls back to the ACTIVE profile in the body when no owner is given', async () => {+ // Multiplex-only: the PATCH handler resolves its state.db from+ // `body.profile` and there is no per-profile backend whose HERMES_HOME+ // could stand in. An unnamed owner therefore has to mean "the profile I am+ // looking at" — otherwise the archive lands on the shared backend's own+ // state.db and silently no-ops.- hermesApi.mockResolvedValue({ ok: true } as never)+ hermesApi.mockResolvedValue({ ok: true, exists: true, runtime_revision: 5, runtime_generation: 2 } as never)+ vi.mocked(client.getApiRequestProfile).mockReturnValue('beta')await setSessionArchived('sess-b', false)- expect(hermesApi.mock.calls[0][0]).toMatchObject({++ expect(hermesApi.mock.calls.filter(([request]) => request.method)[0][0]).toMatchObject({+ method: 'PATCH',+ profile: 'beta',+ body: { archived: false, profile: 'beta' }+ })+ })++ it('omits the profile from the body only when there is no active profile at all', async () => {- hermesApi.mockResolvedValue({ ok: true } as never)++ hermesApi.mockResolvedValue({ ok: true, exists: true, runtime_revision: 5, runtime_generation: 2 } as never)++ await setSessionArchived('sess-b2', false)+- const req = hermesApi.mock.calls[0][0] as { body: Record<string, unknown> }+ const req = hermesApi.mock.calls.filter(([request]) => request.method)[0][0] as { body: Record<string, unknown> }expect(req).toMatchObject({ method: 'PATCH', body: { archived: false } })expect(req.body).not.toHaveProperty('profile')})@@@ -141,15 -182,18 +187,28 @@@ describe('setSessionPinnedRemote / setS})})+ it('omits the profile from the body when none is given', async () => {+ hermesApi.mockResolvedValue({ ok: true, exists: true, runtime_revision: 5, runtime_generation: 2 } as never)++ await setSessionPinnedRemote('sess-p2', false)++ const req = hermesApi.mock.calls.filter(([request]) => request.method)[0][0] as { body: Record<string, unknown> }+ expect(req).toMatchObject({ method: 'PATCH', body: { pinned: false } })+ expect(req.body).not.toHaveProperty('profile')+ })+++ it('falls back to the ACTIVE profile in the body when no owner is given', async () => {- hermesApi.mockResolvedValue({ ok: true } as never)++ hermesApi.mockResolvedValue({ ok: true, exists: true, runtime_revision: 5, runtime_generation: 2 } as never)+ vi.mocked(client.getApiRequestProfile).mockReturnValue('beta')++ await setSessionPinnedRemote('sess-p2', false)+- expect(hermesApi.mock.calls[0][0]).toMatchObject({++ expect(hermesApi.mock.calls.filter(([request]) => request.method)[0][0]).toMatchObject({+ method: 'PATCH',+ profile: 'beta',+ body: { pinned: false, profile: 'beta' }+ })+ })})describe('listSidebarSessions remote ownership', () => {diff --cc apps/desktop/src/api/sessions.tsindex 96b806a3113,d983fc10336..a9239b2491b--- a/apps/desktop/src/api/sessions.ts+++ b/apps/desktop/src/api/sessions.ts@@@ -331,41 -347,60 +349,41 @@@ export async function listSidebarSessio}}-// Mutations take the owning `profile` so Electron can route them to the correct-// remote backend or local profile scope. Omit for the current/default profile.+const runSessionMutation = createSessionMutationClient()++function mutateSessionHttp<T>(id: string, method: 'PATCH' | 'DELETE', payload: Record<string, unknown>, profile?: ProfileScope): Promise<T> {+ const scope = { connectionId: getApiRequestConnection() || 'local', ...sessionScoped(profile) }+ const path = `/api/sessions/${encodeURIComponent(id)}`+ const query = new URLSearchParams(scope.profile ? { profile: scope.profile } : {})+ const suffix = query.size ? `?${query}` : ''+ const key = JSON.stringify([scope, id, method, payload])++ return runSessionMutation(key,+ () => hermesApi<SessionMutationSnapshot>({ ...scope, path: `${path}/mutation-snapshot${suffix}` }),+ identity => {+ if (method === 'DELETE') {+ const params = new URLSearchParams(query)++ for (const [name, value] of Object.entries(identity)) { params.set(name, String(value)) }++ return hermesApi<T>({ ...scope, path: `${path}?${params}`, method })+ }++ return hermesApi<T>({ ...scope, path, method,+ body: { ...payload, ...identity, ...(scope.profile ? { profile: scope.profile } : {}) } })+ })+}+export function setSessionArchived(id: string, archived: boolean, profile?: string | null): Promise<{ ok: boolean }> {- return mutateSessionHttp(id, 'PATCH', { archived }, profile)- // Carry the owning profile IN THE PATCH BODY, mirroring renameSession — the- // backend reads its target DB from body.profile (_open_session_db_for_profile).- // Passing it only as request.profile (Electron routing) is not enough on a- // remote gateway with no remoteProfile alias: the archive lands on the wrong- // (default) state.db, no-ops on a missing row, and the archived/unarchived- // state silently fails to stick — the same class as the unscoped DELETE.- const owner = sessionWriteProfile(profile)-- return hermesApi<{ ok: boolean }>({- ...(owner ? { profile: owner } : {}),- path: `/api/sessions/${encodeURIComponent(id)}`,- method: 'PATCH',- body: { archived, ...(owner ? { profile: owner } : {}) }- })++ return mutateSessionHttp(id, 'PATCH', { archived }, sessionWriteProfile(profile))}-// Mirror a sidebar pin to the backend "keep" flag so the sessions.auto_archive-// sweep (which runs backend-side, blind to Desktop localStorage) never hides a-// pinned chat. Best-effort: the sidebar stays localStorage-driven for its own-// display; this only feeds the backend policy.export function setSessionPinnedRemote(id: string, pinned: boolean, profile?: string | null): Promise<{ ok: boolean }> {- return mutateSessionHttp(id, 'PATCH', { pinned }, profile)- // Owning profile in the PATCH body (see setSessionArchived / renameSession):- // the handler reads its target DB from body.profile, so a remote/foreign- // profile's pin must travel in the body or it no-ops on the wrong state.db.- const owner = sessionWriteProfile(profile)-- return hermesApi<{ ok: boolean }>({- ...(owner ? { profile: owner } : {}),- path: `/api/sessions/${encodeURIComponent(id)}`,- method: 'PATCH',- body: { pinned, ...(owner ? { profile: owner } : {}) }- })++ return mutateSessionHttp(id, 'PATCH', { pinned }, sessionWriteProfile(profile))}-// Mirror a sidebar unread toggle to the backend read-state watermark-// (sessions.last_read_at via SessionDB.set_session_read). Same profile-// routing as the other session mutations: a remote session's row lives only-// on its remote host, so the owning profile must travel with the request.export function setSessionUnreadRemote(id: string, unread: boolean, profile?: string | null): Promise<{ ok: boolean }> {- return mutateSessionHttp(id, 'PATCH', { unread }, profile)- // Owning profile in the PATCH body (see setSessionArchived / renameSession):- // the handler reads its target DB from body.profile, so a remote/foreign- // profile's unread toggle must travel in the body or it no-ops on the wrong- // state.db.- const owner = sessionWriteProfile(profile)-- return hermesApi<{ ok: boolean }>({- ...(owner ? { profile: owner } : {}),- path: `/api/sessions/${encodeURIComponent(id)}`,- method: 'PATCH',- body: { unread, ...(owner ? { profile: owner } : {}) }- })++ return mutateSessionHttp(id, 'PATCH', { unread }, sessionWriteProfile(profile))}export function searchSessions(query: string): Promise<SessionSearchResponse> {@@@ -590,9 -625,38 +608,9 @@@ export async function getAllSessionMess}export function deleteSession(id: string, profile?: ProfileScope): Promise<{ ok: boolean }> {- // Scope the DELETE to the owning profile IN THE URL, mirroring getSession /- // getSessionMessages. Passing the profile only via request.profile (which the- // Electron main process consumes for backend routing) is NOT enough: on a- // remote gateway whose connection has no remoteProfile alias, the main-process- // path rewrite leaves the URL unscoped, so the backend opens its OWN (default)- // state.db, fails to find another profile's session, and returns- // {ok:true, already_absent:true}. The row then vanishes optimistically but was- // never deleted and reappears on the next sidebar refresh — the "All Profiles- // delete doesn't stick" report. The endpoint already honours ?profile=- // (get/rename/messages all send it); DELETE was the one mutation that dropped- // it after the api/ split. request.profile stays on for per-profile remote- // override + global-remote routing (both re-read/re-append the param).- const suffix = sessionScopeQuery(profile)-- return hermesApi<{ ok: boolean }>({- ...sessionScoped(profile),- path: `/api/sessions/${encodeURIComponent(id)}${suffix}`,- method: 'DELETE'- })+ return mutateSessionHttp(id, 'DELETE', {}, profile)}-export function renameSession(- id: string,- title: string,- profile?: string | null-): Promise<{ ok: boolean; title: string }> {- const owner = sessionWriteProfile(profile)-- return hermesApi<{ ok: boolean; title: string }>({- ...(owner ? { profile: owner } : {}),- path: `/api/sessions/${encodeURIComponent(id)}`,- method: 'PATCH',- body: { title, ...(owner ? { profile: owner } : {}) }- })+export function renameSession(id: string, title: string, profile?: string | null): Promise<{ ok: boolean; title: string }> {- return mutateSessionHttp(id, 'PATCH', { title }, profile)++ return mutateSessionHttp(id, 'PATCH', { title }, sessionWriteProfile(profile))}diff --cc apps/desktop/src/app/chat/composer/index.tsxindex 8f96b1fca91,5b16bbf6e9f..44307c4ac2f--- a/apps/desktop/src/app/chat/composer/index.tsx+++ b/apps/desktop/src/app/chat/composer/index.tsx@@@ -1,15 -1,21 +1,23 @@@import { ComposerPrimitive } from '@assistant-ui/react'import { useStore } from '@nanostores/react'- import { type ClipboardEvent, type FormEvent, type KeyboardEvent, useCallback, useEffect, useMemo, useRef } from 'react'+ import {+ type ClipboardEvent,+ type FormEvent,+ type KeyboardEvent,+ useCallback,+ useEffect,+ useId,+ useMemo,+ useRef+ } from 'react'import { useTourMarker } from '@/app/chat/tour-marker'+import type { GatewayRequester } from '@/app/contrib/types'import { useHudComposerDrag } from '@/app/hud/composer-drag'+import { useBusyInputMode } from '@/app/session/hooks/use-busy-input-mode'- import { composerFill, composerFloatingStrip, composerSurfaceGlass } from '@/components/chat/composer-dock'+ import { composerFloatingStrip, composerInputBacking } from '@/components/chat/composer-dock'import { $chatOnboardingSolo, $chatOnboardingThreadIds } from '@/components/onboarding-chat/assembly'import { OnboardingSkip } from '@/components/onboarding-chat/skip'- import { OnboardingStart } from '@/components/onboarding-chat/start'import { Button } from '@/components/ui/button'import { Slot as ContribSlot } from '@/contrib/react/slot'import { useI18n } from '@/i18n'@@@ -25,7 -32,7 +34,8 @@@ import { browseBackward, browseForwardimport { POPOUT_WIDTH_REM } from '@/store/composer-popout'import { parkQueuedPrompts, removeQueuedPrompt, unparkQueuedPrompts } from '@/store/composer-queue'import { $hudMode } from '@/store/hud'+ import { $showsAdvancedChrome } from '@/store/interface-mode'+import { notifyError } from '@/store/notifications'import { sessionBlockingPrompt } from '@/store/prompts'import { toggleReview } from '@/store/review'import { $gatewayState } from '@/store/session'@@@ -74,8 -81,8 +85,9 @@@ import { useSessionStatusPresence } froimport { shouldConvertPasteToAttachment } from './large-paste'import { ActionBadges } from './micro-actions'import { chipTypedPathOnSpace, pathifyRefs } from './path-refs'+import { PreparedImageRecovery } from './prepared-image-recovery'import { QueuePanel } from './queue-panel'+ import { RestoredDraftNotice } from './restored-draft-notice'import {beginComposerComposition,composerPlainText,@@@ -197,18 -205,10 +210,21 @@@ export function ChatBar(// undelivered behind the blocked tool batch). Drives the button affordance.const blockingPrompt = useStore(useMemo(() => sessionBlockingPrompt(sessionId ?? null), [sessionId]))const activeQueueSessionKey = queueSessionKey || sessionId || null+ const { collapsed: statusDrawerCollapsed, toggle: toggleStatusDrawer } = useStatusDrawer(activeQueueSessionKey)+ const statusDrawerId = useId()+ const codingDrawerId = useId()+ const requestBusyConfig = useCallback<GatewayRequester>(+ (method, params) => (gateway ? gateway.request(method, params) : Promise.reject(new Error('Gateway unavailable'))),+ [gateway]+ )++ const busyInputMode = useBusyInputMode({+ sessionId: sessionId ?? null,+ storedSessionId: queueSessionKey ?? null,+ requestGateway: requestBusyConfig+ })+// Status items (subagents, background processes) are keyed by the RUNTIME// session id — gateway events and process.list both speak that id. Only the// queue uses the stored-session fallback key (prompts can queue pre-resume).@@@ -1271,58 -1311,45 +1331,59 @@@<div className={cn(composerFloatingStrip, 'px-[5px] pb-1.5 empty:hidden')}><ActionBadges sessionId={statusSessionId} /><SuggestionPills sessionId={statusSessionId} />+ <PreparedImageRecovery+ occupied={hasText || attachments.length > 0 || busy || disabled}+ onRestore={loadIntoComposer}+ request={requestBusyConfig}+ sessionKey={activeQueueSessionKey}+ /><OnboardingSkip />- <OnboardingStart /></div>{/* Session-scoped status stack (todos, subagents, background tasks,queue). An in-flow dock child: the dock is bottom-anchored, so itgrows upward over the thread and the dock's own measurement coversit. Collapses to nothing when every status is empty. */}- <ComposerStatusStack- onSubmit={onSubmit}- queue={- activeQueueSessionKey && queuedPrompts.length > 0 ? (- <QueuePanel- busy={busy}- editingId={queueEdit?.entryId ?? null}- entries={queuedPrompts}- onDelete={id => {- if (removeQueuedPrompt(activeQueueSessionKey, id) && queueEdit?.entryId === id) {- exitQueuedEdit('cancel')- }- }}- onDiscardLost={gateway ? id => {- // Server-owned row: the authority's pending fanout retires it- // from the queue once the acknowledgement commits. Canonical- // local sessions key the queue by their own session id, so the- // stored key stands in when the runtime id is not bound yet.- discardLostPrompt(sessionId, activeQueueSessionKey, id, gateway.request.bind(gateway))- .catch((error: unknown) => notifyError(error, t.composer.queueLostDiscard))- } : undefined}- onEdit={beginQueuedEdit}- onResume={() => {- unparkQueuedPrompts(activeQueueSessionKey)-- // Idle → kick the head immediately; busy → the settle drain- // takes over now that the park is lifted.- if (!busy) {- void drainNextQueued()- }- }}- onSendNow={id => void sendQueuedNow(id)}- onSteerNow={id => void steerQueuedNow(id)}- parked={queueParked}- />- ) : null- }- sessionId={statusSessionId}- />+ <StatusDrawerContent collapsed={statusDrawerCollapsed} id={statusDrawerId}>+ <ComposerStatusStack+ onSubmit={onSubmit}+ queue={+ activeQueueSessionKey && queuedPrompts.length > 0 ? (+ <QueuePanel+ busy={busy}+ editingId={queueEdit?.entryId ?? null}+ entries={queuedPrompts}+ onDelete={id => {+ if (removeQueuedPrompt(activeQueueSessionKey, id) && queueEdit?.entryId === id) {+ exitQueuedEdit('cancel')+ }+ }}++ onDiscardLost={gateway ? id => {++ // Server-owned row: the authority's pending fanout retires it++ // from the queue once the acknowledgement commits. Canonical++ // local sessions key the queue by their own session id, so the++ // stored key stands in when the runtime id is not bound yet.++ discardLostPrompt(sessionId, activeQueueSessionKey, id, gateway.request.bind(gateway))++ .catch((error: unknown) => notifyError(error, t.composer.queueLostDiscard))++ } : undefined}+ onEdit={beginQueuedEdit}+ onResume={() => {+ unparkQueuedPrompts(activeQueueSessionKey)++ // Idle → kick the head immediately; busy → the settle drain+ // takes over now that the park is lifted.+ if (!busy) {+ void drainNextQueued()+ }+ }}+ onSendNow={id => void sendQueuedNow(id)}+ onSteerNow={id => void steerQueuedNow(id)}+ parked={queueParked}+ />+ ) : null+ }+ sessionId={statusSessionId}+ />+ </StatusDrawerContent><ComposerPrimitive.RootclassName={cn('group/composer relative w-full overflow-visible rounded-2xl',diff --cc apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.tsindex e3778836f6b,9e328360047..ff753e9f518--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts@@@ -423,45 -395,21 +423,48 @@@ export function useSessionTileDelegate(updateSessionState(runtimeId,- state => ({- ...state,- busy: Boolean(info?.running),- // Persist the session's own model/provider from resume so the tile- // pill does not wait on a chrome-scoped catalog read (#93892).- ...(typeof info?.model === 'string' ? { model: info.model } : {}),- ...(typeof info?.provider === 'string' ? { provider: info.provider } : {}),- ...(typeof info?.reasoning_effort === 'string' ? { reasoningEffort: info.reasoning_effort } : {}),- ...(typeof info?.reasoning_effort_wire === 'string'- ? { reasoningEffortWire: info.reasoning_effort_wire }- : {}),- ...(typeof info?.fast === 'boolean' ? { fast: info.fast } : {}),- messages:- state.messages.length > 0 ? state.messages : toChatMessages(prefetch?.messages ?? resumed?.messages ?? [])- }),+ state => {+ const previousMessages = state.messages.length > 0 ? state.messages : resumeRequestBaselineMessages++ const messages = authoritativeSnapshot+ ? resumed.messages.length > 0+ ? overlayConcurrentMessageChanges(+ mergeTileTranscript(+ resumeRequestBaselineMessages,+ resumed.messages,+ cached?.streamId+ ),+ resumeRequestBaselineMessages,+ previousMessages+ )+ : previousMessages+ : previousMessages.length > 0+ ? previousMessages+ : toChatMessages(prefetch?.messages ?? resumed.messages ?? [])++ const busyChangedWhileResuming = cached+ ? Boolean(+ state.busy &&+ (state.turnStartedAt !== cached.turnStartedAt || (state.turnLive && !cached.turnLive))+ )+ : state.busy++ const running = resolveResumedBusy(resumed.running ?? info?.running, busyChangedWhileResuming)++ return {+ ...state,+ ...(typeof info?.fast === 'boolean' ? { fast: info.fast } : {}),+ ...(typeof info?.model === 'string' ? { model: info.model } : {}),+ ...(typeof info?.provider === 'string' ? { provider: info.provider } : {}),+ ...(typeof info?.reasoning_effort === 'string' ? { reasoningEffort: info.reasoning_effort } : {}),++ ...(typeof info?.reasoning_effort_wire === 'string'++ ? { reasoningEffortWire: info.reasoning_effort_wire }++ : {}),+ awaitingResponse: running && !resumed.inflight?.assistant,+ busy: running,+ messages+ }+ },storedSessionId)diff --cc apps/desktop/src/app/contrib/wiring.tsxindex 8fd60f65efb,fc80385a6d0..cc40e9fe2b0--- a/apps/desktop/src/app/contrib/wiring.tsx+++ b/apps/desktop/src/app/contrib/wiring.tsx@@@ -51,8 -48,10 +48,9 @@@ import { $activeConnectionId } from '@/import { $cronReviewRequest, setCronFocusJobId } from '@/store/cron'import { requestGatewayForProfile } from '@/store/gateway'import { reconnectGateway } from '@/store/gateway-reconnect'+ import { $interfaceMode, shownInMode } from '@/store/interface-mode'import { $pinnedSessionIds, pinSession, restoreWorktree, unpinSession } from '@/store/layout'import { notifyError } from '@/store/notifications'-import { $poolLimitsSettingsRequest } from '@/store/pool-limits'import { $previewTarget } from '@/store/preview'import {$activeGatewayProfile,diff --cc apps/desktop/src/app/gateway/hooks/use-gateway-boot.tsindex 62ba9d212dc,58e5449f4b3..c4ab8596141--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts@@@ -1064,16 -1205,18 +1187,18 @@@ export function useGatewayBoot(// profile has a running (working) or blocked (needs-input) session, OR an// open owner-routed tile (Bot chats stay on a secondary while chrome stays// on the launch profile). Once the last consumer leaves, the socket drops- // and its backend is free to idle-reap. The active profile is always spared.+ // (the gateway behind it keeps running). The active profile is always spared.// Do not key this off `entry.retained` — that flag only skips dispose-after-// RPC; idle prune is what reclaims hover-warmed sockets after you leave.- const recomputeKeptGateways = () => {+ // Scopes with a running or needs-input session: registry-scoped+ // (connectionId, profile) keys plus the bare profile of every live local+ // session. Two sources can expose the same profile name (every source has+ // a 'default'), so bare profile names can't represent a non-local+ // source's liveness without keeping the wrong gateway alive. Feeds the+ // pruner's keep-set and the wake probe's in-flight-work signal.+ const liveWorkScopes = (): Set<string> => {const live = new Set([...$workingSessionIds.get(), ...$attentionSessionIds.get()])- // Registry-scoped (connectionId, profile) scopes with live work. Two- // sources can expose the same profile name (every source has a- // 'default'), so bare profile names can't represent a non-local- // source's liveness without keeping the wrong gateway alive.- const keep = new Set([...liveSessionScopes(), ...foregroundSessionScopes()])+ const scopes = liveSessionScopes()for (const session of $sessions.get()) {if (live.has(session.id)) {diff --cc apps/desktop/src/app/session/hooks/use-hermes-config.tsindex 40ab529bc33,0b9b3ef9589..7a323f68120--- a/apps/desktop/src/app/session/hooks/use-hermes-config.ts+++ b/apps/desktop/src/app/session/hooks/use-hermes-config.ts@@@ -4,10 -4,8 +4,11 @@@ import { setTerminalFontFamilyFromConfiimport { getHermesConfig, getHermesConfigDefaults } from '@/hermes'import { BUILTIN_PERSONALITIES, normalizePersonalityValue, personalityNamesFromConfig } from '@/lib/chat-runtime'import { normalize } from '@/lib/text'+import { $busyInputConfig, busyInputOwnerKey, normalizeBusyInputMode } from '@/store/busy-input-mode'import { setDisplayTimestampsFromConfig } from '@/store/display-timestamps'+import { $activeGatewayProfile } from '@/store/profile'+ import { setShowReasoningFromConfig } from '@/store/reasoning-disclosure'+import { $connection } from '@/store/session'import {getComposerSelectionGeneration,getCurrentModelSource,@@@ -144,15 -140,8 +145,16 @@@ export function useHermesConfig({ activreturn}+ if ($connection.get() === connection && $activeGatewayProfile.get() === profile) {+ $busyInputConfig.set({+ owner: busyInputOwnerKey(connection?.connectionId, profile),+ connection,+ mode: normalizeBusyInputMode(config.display?.busy_input_mode)+ })+ }+setDisplayTimestampsFromConfig(config.display?.timestamps)+ setShowReasoningFromConfig(config.display?.show_reasoning)setTerminalFontFamilyFromConfig(config.terminal?.font_family)setChatFontFamilyFromConfig(config.desktop?.font_family)diff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/index.tsindex ed47c6235f6,131a94ab6f6..1f317b1c13a--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts@@@ -72,7 -68,7 +72,8 @@@ importtype SurvivorUserRowIds} from './rewind'import { useSlashCommand } from './slash'+ import { captureSteeringSession } from './steering-session'+import { captureSubmissionDestination } from './submission-destination'import { useSubmitPrompt } from './submit'import {blobToDataUrl,@@@ -138,11 -136,7 +141,11 @@@ export async function uploadComposerAttterminalBackend?: string}): Promise<ComposerAttachment> {- const { backendCwd, remote, storedSessionId, onSessionRecovered, terminalBackend } = opts- const { backendCwd, remote, requestGateway, storedSessionId, onRecovered, onSessionRecovered, terminalBackend } = opts++ const { backendCwd, remote, storedSessionId, onRecovered, onSessionRecovered, terminalBackend } = opts++ const destination = captureSubmissionDestination(storedSessionId ?? opts.sessionId, opts.requestGateway)+ const requestGateway = destination.requestGateway+const path = attachment.path ?? ''const label = attachment.label || pathLabel(path)const uploadBytes = remote || attachmentPathNeedsUpload(path, backendCwd, terminalBackend)@@@ -368,23 -345,15 +375,29 @@@ export function usePromptActions(async (sessionId: string,attachments: ComposerAttachment[],- options: { storedSessionId?: null | string; updateComposerAttachments?: boolean } = {}+ options: {+ updateComposerAttachments?: boolean+ storedSessionId?: string | null+ requestGateway?: GatewayRequest+ } = {}): Promise<{ attachments: ComposerAttachment[]; sessionId: string }> => {const updateComposerAttachments = options.updateComposerAttachments ?? true++ // The submit's own target, never the chat on screen: a queued send drains+ // after the user has moved on, so a stale runtime here must recover the+ // session the text belongs to — not stage the files on, and then submit+ // into, whichever chat is selected now (#46194, the attachments edition).- const storedSessionId = options.storedSessionId ?? selectedStoredSessionIdRef.current+ const storedSessionId =+ options.storedSessionId !== undefined ? options.storedSessionId : selectedStoredSessionIdRef.current++ const targetIsForeground = storedSessionId === selectedStoredSessionIdRef.current+++ const uploadRequest =+ options.requestGateway ??+ captureSubmissionDestination(storedSessionId ?? sessionId, requestGateway).requestGateway++ const backendCwd = $currentCwd.get()+ const terminalBackend = $terminalBackend.get()const remote = isSessionRemote(storedSessionId ?? sessionId)let liveSessionId = sessionIdconst synced: ComposerAttachment[] = []@@@ -426,13 -406,14 +450,14 @@@if (attachment.kind === 'image' || attachment.kind === 'file') {const nextAttachment = await uploadComposerAttachment(attachment, {- backendCwd: $currentCwd.get(),+ backendCwd,remote,- requestGateway,+ requestGateway: uploadRequest,sessionId: liveSessionId,storedSessionId,+ onRecovered,onSessionRecovered,- terminalBackend: $terminalBackend.get()+ terminalBackend})// Update-only: never resurrect a chip the user removed mid-upload.@@@ -790,8 -771,9 +815,9 @@@// completed work intact. During a tool it waits for the safe result boundary.// Returns false when the turn raced to completion so the composer can queue.const redirectPrompt = useCallback(- async (rawText: string): Promise<boolean> => {+ async (rawText: string, mode: 'interrupt' | 'steer' = 'interrupt'): Promise<boolean> => {const text = sanitizeComposerInput(rawText).trim()+// Ref, not the closure-captured prop — see cancelRun above. A redirect// reaches the live model mid-turn, so a stale target delivers the user's// correction into a conversation they are no longer looking at.@@@ -807,9 -796,14 +840,9 @@@// message after the interrupted checkpoint, matching the durable core// transcript rather than a system note that changes role after reload.const send = async (id: string): Promise<boolean> => {- // Redirect aborts the model request, so the completion event can race- // its RPC response. Record the correction *before* awaiting the- // gateway, in arrival order: sealed already-streamed output above,- // correction bubble below it, post-redirect deltas below that- // (#73793, #83151).- const messageId = appendSessionTextMessage(id, 'user', text, target.storedSessionId, {- appendAfterActiveReply: true- })+ // Reserve the correction's arrival position, but do not seal the live+ // stream until acceptance: a refusal must leave in-flight deltas intact.- const messageId = appendSessionTextMessage(id, 'user', text)++ const messageId = appendSessionTextMessage(id, 'user', text, target.storedSessionId)const discardOptimisticMessage = () =>updateSessionState(id, state => ({@@@ -827,29 -821,12 +860,29 @@@})try {- const result = await requestGateway<SessionRedirectResponse>(- const result = await target.requestGateway<SessionRedirectResponse>('session.redirect', {- session_id: id,- text- })++ const result = await target.requestGateway<SessionRedirectResponse>(+ mode === 'steer' ? 'session.steer' : 'session.redirect',+ { session_id: id, text }+ )if (result?.status === 'redirected') {+ if (mode === 'interrupt') {+ updateSessionState(id, state => {+ const message = state.messages.find(candidate => candidate.id === messageId)++ // A newer reply may precede this ACK; it already owns its boundary.+ const hasNewReply = state.messages.slice(state.messages.findIndex(candidate => candidate.id === messageId) + 1)+ .some(candidate => candidate.role === 'assistant')++ return message && state.streamId && !hasNewReply+ ? appendMidTurnUserMessage(+ { ...state, messages: state.messages.filter(candidate => candidate.id !== messageId) },+ message+ )+ : state+ })+ }+triggerHaptic('submit')return true@@@ -880,21 -854,24 +913,24 @@@// A stale runtime id after reconnect 404s ("session not found"): the// shared resolver resumes the stored session and retries once, so a// correction right after a reconnect isn't lost to the race.- const { result } = await withSessionNotFoundResume(sessionId, selectedStoredSessionIdRef.current, send, {- requestGateway,- onRecovered: recoveredId => {- activeSessionIdRef.current = recoveredId- setActiveSessionId(recoveredId)- }- })+ const { result } = await withSessionNotFoundResume(target.sessionId, target.storedSessionId, send, target)return result- } catch {- // Swallow — caller queues the text so nothing is lost.+ } catch (err) {+ notifyError(err, copy.promptFailed)+ throw err}-- return false},- [activeSessionIdRef, appendSessionTextMessage, copy.promptFailed, requestGateway, selectedStoredSessionIdRef, updateSessionState]+ [+ activeSessionIdRef,+ appendSessionTextMessage,++ copy.promptFailed,+ getRoutedStoredSessionId,+ requestGateway,+ runtimeIdByStoredSessionIdRef,+ selectedStoredSessionIdRef,+ updateSessionState+ ])// A hidden note that lands mid-turn must reach the model without becoming adiff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/slash.tsindex 3343d64a48b,baee82f366e..b233d20ba44--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts@@@ -17,9 -17,10 +17,10 @@@ importresolveDesktopCommand} from '@/lib/desktop-slash-commands'import { isMissingRpcMethod } from '@/lib/gateway-rpc'+ import { applyReasoningSlashResult, reasoningSlashParams } from '@/lib/reasoning-slash'import { setSessionYolo } from '@/lib/yolo-session'import { openCommandPalettePage } from '@/store/command-palette'-import { setComposerDraft } from '@/store/composer'+import { $composerAttachments, setComposerDraft } from '@/store/composer'import { applyGoalStatusText } from '@/store/goals'import { dismissNotification, notify, notifyError } from '@/store/notifications'import { setPetScale } from '@/store/pet-gallery'diff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/steering-recovery.test.tsxindex 00000000000,8f7e444bb38..ee3cb722c96mode 000000,100644..100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/steering-recovery.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/steering-recovery.test.tsx@@@ -1,0 -1,427 +1,429 @@@+ import { useStore } from '@nanostores/react'+ import { QueryClient } from '@tanstack/react-query'+ import { act, cleanup, render, waitFor } from '@testing-library/react'+ import { afterEach, expect, it, vi } from 'vitest'++ import { createSessionRpcDispatcher } from '@/app/contrib/session-rpc-dispatcher'+ import { sessionRoute } from '@/app/routes'+ import { textPart } from '@/lib/chat-messages'+ import { requestGatewayForAgent, requestGatewayForProfile } from '@/store/gateway'+ import {+ $activeSessionId,+ $activeSessionStoredIdRotation,+ $messages,+ $selectedStoredSessionId,+ setActiveSessionId,+ setAwaitingResponse,+ setBusy,+ setMessages,+ setSelectedStoredSessionId,+ setSessions+ } from '@/store/session'+ import { clearAllSessionStates } from '@/store/session-states'+ import type { SessionInfo } from '@/types/hermes'++ import { handleSessionInfoEvent } from '../use-message-stream/gateway-event/session-info'+ import { useSessionStateCache } from '../use-session-state-cache'++ import { clearSingleFlightSessionResumeState, registerRecoveredRuntime } from './single-flight-resume'++ import { usePromptActions } from '.'++ // Real prompt hooks, cache, ownership router, and dispatcher; only the external+ // gateway edge is substituted. No test injects a corrupted ownership mapping.+ vi.mock('@/store/gateway', async original => ({+ ...(await original<Record<string, unknown>>()),+ requestGatewayForAgent: vi.fn(),+ requestGatewayForProfile: vi.fn(),+ retainGatewayForSessionTurn: vi.fn(async () => () => undefined)+ }))++ const busyRef = { current: false }+ let routedStoredId: string | null = 'stored-B'+ let handle: { actions: ReturnType<typeof usePromptActions>; cache: ReturnType<typeof useSessionStateCache> }++ function Harness() {+ const activeSessionId = useStore($activeSessionId)+ const selectedStoredSessionId = useStore($selectedStoredSessionId)++ const cache = useSessionStateCache({+ activeSessionId,+ selectedStoredSessionId,+ busyRef,+ setAwaitingResponse,+ setBusy,+ setMessages+ })++ const requestGateway = createSessionRpcDispatcher({+ ...cache,+ ambientRequest: async () => {+ throw new Error('unexpected ambient request')+ }+ })++ const actions = usePromptActions({+ activeSessionId,+ ...cache,+ busyRef,+ branchCurrentSession: async () => false,+ createBackendSessionForSend: async () => {+ throw new Error('unexpected create')+ },+ getRoutedStoredSessionId: () => routedStoredId,+ getRouteToken: () => `${routedStoredId ? sessionRoute(routedStoredId) : '/'}::`,+ handleSkinCommand: () => '',+ openMemoryGraph: () => undefined,+ refreshSessions: async () => undefined,+ requestGateway,+ resumeStoredSession: async () => {+ throw new Error('unexpected foreground resume')+ },+ startFreshSessionDraft: () => undefined,+ sttEnabled: false+ })++ handle = { actions, cache }++ return null+ }++ function seed() {+ routedStoredId = 'stored-B'+ busyRef.current = false+ // Same profile name on distinct backends: profile equality is not ownership.+ setSessions(+ ['A', 'B'].map(id => ({+ id: `stored-${id}`,+ connection_id: `connection-${id}`,+ profile: 'default',+ source: 'desktop',+ message_count: 1+ })) as SessionInfo[]+ )+ setSelectedStoredSessionId('stored-B')+ setActiveSessionId('rt-B')+ render(<Harness />)+ act(() => {+ for (const id of ['A', 'B']) {+ handle.cache.updateSessionState(+ `rt-${id}`,+ state => ({+ ...state,+ messages: [{ id: `history-${id}`, role: 'assistant', parts: [textPart(`history ${id}`)] }]+ }),+ `stored-${id}`+ )+ }+ })+ }++ function navigateToA() {+ act(() => {+ routedStoredId = 'stored-A'+ setSelectedStoredSessionId('stored-A')+ setActiveSessionId('rt-A')+ })+ act(() => {+ handle.cache.syncSessionStateToView('rt-A', handle.cache.sessionStateByRuntimeIdRef.current.get('rt-A')!)+ })+ }++ function deferred<T>() {+ let resolve!: (value: T) => void+ let reject!: (error: Error) => void++ const promise = new Promise<T>((yes, no) => {+ resolve = yes+ reject = no+ })++ return { promise, resolve, reject }+ }++ afterEach(() => {+ cleanup()+ clearAllSessionStates()+ clearSingleFlightSessionResumeState()+ setActiveSessionId(null)+ setSelectedStoredSessionId(null)+ setSessions([])+ setBusy(false)+ setAwaitingResponse(false)+ setMessages([])+ window.localStorage.clear()+ vi.clearAllMocks()+ })++ it.each(['redirectPrompt', 'injectHiddenPrompt'] as const)(+ '%s refuses a source whose route, selection, and runtime do not agree',+ async action => {+ vi.mocked(requestGatewayForAgent).mockResolvedValue({ status: 'queued' })+ seed()+ const originalB = handle.cache.sessionStateByRuntimeIdRef.current.get('rt-B')+ // Route publication can precede both selection and runtime publication.+ routedStoredId = 'stored-A'+ await act(async () => {+ expect(await handle.actions[action]('not B input')).toBe(false)+ })+ expect(requestGatewayForAgent).not.toHaveBeenCalled()+ expect(handle.cache.sessionStateByRuntimeIdRef.current.get('rt-B')).toBe(originalB)++ // Selection/route can also agree while the active runtime still lags.+ act(() => {+ setSelectedStoredSessionId('stored-A')+ })+ // Missing forward proof must not turn a known foreign runtime into A's.+ handle.cache.runtimeIdByStoredSessionIdRef.current.delete('stored-A')+ await act(async () => {+ expect(await handle.actions[action]('A input')).toBe(false)+ })+ expect(requestGatewayForAgent).not.toHaveBeenCalled()+ expect(handle.cache.runtimeIdByStoredSessionIdRef.current.has('stored-A')).toBe(false)+ expect(handle.cache.runtimeIdByStoredSessionIdRef.current.get('stored-B')).toBe('rt-B')++ // A fresh draft must not steer the previous chat's still-live runtime.+ act(() => {+ routedStoredId = null+ setSelectedStoredSessionId(null)+ })+ await act(async () => {+ expect(await handle.actions[action]('new chat input')).toBe(false)+ })+ expect(requestGatewayForAgent).not.toHaveBeenCalled()+ }+ )++ const steeringActions = [+ { action: 'redirectPrompt' as const, method: 'session.redirect', status: 'redirected' },+ { action: 'redirectPrompt' as const, method: 'session.redirect', status: 'queued' },+ { action: 'injectHiddenPrompt' as const, method: 'session.steer', status: 'queued' }+ ]++ const recoveryCases = (['before-stale-error', 'during-resume', 'stay'] as const).flatMap(navigation =>+ [false, true].flatMap(expiredRecovery => steeringActions.map(action => ({ ...action, navigation, expiredRecovery })))+ )++ it.each(recoveryCases)(+ '$action recovery ($status, $navigation, expired cache: $expiredRecovery) retains its owner without stealing another chat',+ async ({ action, method, status, navigation, expiredRecovery }) => {+ const first = deferred<unknown>()+ const resume = deferred<{ session_id: string }>()+ vi.mocked(requestGatewayForAgent).mockImplementation(async (_connection, _profile, rpc, params) => {+ if (rpc === method && params?.session_id === 'rt-B') {+ return first.promise+ }++ if (rpc === 'session.resume') {+ return resume.promise+ }++ if (rpc === method && params?.session_id === 'rt-B-cached') {+ throw new Error('session not found')+ }++ if (rpc === method) {+ return { status }+ }++ if (rpc === 'prompt.submit') {- return { status: 'streaming' }++ // Durable admission protocol: a successful submit is acknowledged with++ // the receipt for THIS submission, never a bare legacy status.++ return { admission_id: params?.submission_id, status: 'started' }+ }++ throw new Error(`unexpected ${rpc}`)+ })+ seed()++ if (expiredRecovery) {+ registerRecoveredRuntime('stored-B', 'rt-B-cached')+ }++ let pending!: Promise<boolean>+ act(() => {+ pending = handle.actions[action]('B correction')+ })+ await waitFor(() =>+ expect(requestGatewayForAgent).toHaveBeenCalledWith('connection-B', 'default', method, {+ session_id: 'rt-B',+ text: 'B correction'+ })+ )++ if (navigation === 'before-stale-error') {+ navigateToA()+ }++ await act(async () => {+ first.reject(new Error('session not found'))+ })+ await waitFor(() =>+ expect(requestGatewayForAgent).toHaveBeenCalledWith(+ 'connection-B',+ 'default',+ 'session.resume',+ expect.objectContaining({ session_id: 'stored-B' })+ )+ )++ if (expiredRecovery) {+ expect(requestGatewayForAgent).toHaveBeenCalledWith('connection-B', 'default', method, {+ session_id: 'rt-B-cached',+ text: 'B correction'+ })+ expect($activeSessionId.get()).toBe(navigation === 'before-stale-error' ? 'rt-A' : 'rt-B-cached')+ }++ if (navigation === 'during-resume') {+ navigateToA()+ }++ await act(async () => {+ resume.resolve({ session_id: 'rt-B2' })+ expect(await pending).toBe(true)+ })++ expect(requestGatewayForAgent).toHaveBeenCalledWith('connection-B', 'default', method, {+ session_id: 'rt-B2',+ text: 'B correction'+ })+ expect(requestGatewayForProfile).not.toHaveBeenCalled()+ expect(handle.cache.runtimeIdByStoredSessionIdRef.current.get('stored-A')).toBe('rt-A')+ expect(handle.cache.runtimeIdByStoredSessionIdRef.current.get('stored-B')).toBe('rt-B2')+ expect(handle.cache.sessionStateByRuntimeIdRef.current.get('rt-B2')?.storedSessionId).toBe('stored-B')++ const correctionRows = [...handle.cache.sessionStateByRuntimeIdRef.current.values()]+ .flatMap(state => state.messages)+ .filter(message => message.role === 'user')++ expect(correctionRows).toHaveLength(action === 'redirectPrompt' ? 1 : 0)+ expect($activeSessionId.get()).toBe(navigation === 'stay' ? 'rt-B2' : 'rt-A')+ expect(handle.cache.activeSessionIdRef.current).toBe($activeSessionId.get())+ expect($selectedStoredSessionId.get()).toBe(navigation === 'stay' ? 'stored-B' : 'stored-A')++ if (navigation === 'stay') {+ navigateToA()+ }++ expect($messages.get().map(message => message.id)).toEqual(['history-A'])+ // An ordinary foreground send must still route to A after B's recovery.+ await act(async () => {+ expect(await handle.actions.submitText('A next prompt', { attachments: [], composerScope: 'stored-A' })).toBe(+ true+ )+ })+ expect(requestGatewayForAgent).toHaveBeenLastCalledWith(+ 'connection-A',+ 'default',+ 'prompt.submit',+ expect.objectContaining({ session_id: 'rt-A', text: 'A next prompt' }),+ expect.any(Number),+ undefined+ )+ }+ )++ const rebuiltRuntimeCases = steeringActions.flatMap(action =>+ [false, true].flatMap(recover => ['stored-B', 'stored-B-tip'].map(selection => ({ ...action, recover, selection })))+ )++ it.each(rebuiltRuntimeCases)(+ '$action ($status, recovery: $recover, selection: $selection) preserves a rebuilt runtime’s tip binding and durable route',+ async ({ action, method, status, recover, selection }) => {+ seed()+ const rotation = $activeSessionStoredIdRotation.get()++ act(() => {+ setSessions([+ {+ id: 'stored-B-tip',+ _lineage_root_id: 'stored-B',+ profile: 'default',+ connection_id: 'connection-B',+ source: 'desktop',+ message_count: 2+ }+ ] as SessionInfo[])+ handleSessionInfoEvent({+ deps: {+ ...handle.cache,+ activeGatewayProfile: 'default',+ compactedTurnRef: { current: new Set() },+ lastCwdInfoSessionRef: { current: null },+ nativeSubagentSessionsRef: { current: new Set() },+ appendAssistantDelta: vi.fn(),+ appendReasoningDelta: vi.fn(),+ completeAssistantMessage: vi.fn(),+ failAssistantMessage: vi.fn(),+ flushQueuedDeltas: vi.fn(),+ finalizeInterimAssistantMessage: vi.fn(),+ hydrateFromStoredSession: vi.fn(async () => undefined),+ queryClient: new QueryClient(),+ refreshHermesConfig: vi.fn(async () => undefined),+ scheduleSessionsRefresh: vi.fn(),+ sessionInterrupted: () => false,+ upsertToolCall: vi.fn()+ },+ event: { profile: 'default', session_id: 'rt-B-rebuilt', type: 'session.info' },+ explicitSid: 'rt-B-rebuilt',+ fromActiveSource: () => true,+ isActiveEvent: false,+ occurredAt: Date.now() / 1000,+ payload: { stored_session_id: 'stored-B-tip', model: 'fixture-model', running: true },+ scheduleConfigRefresh: vi.fn(),+ sessionId: 'rt-B-rebuilt'+ })+ })+ // The real reducer adopts this runtime without rotating the durable selection.+ expect($activeSessionId.get()).toBe('rt-B-rebuilt')+ expect($selectedStoredSessionId.get()).toBe('stored-B')+ expect(handle.cache.sessionStateByRuntimeIdRef.current.get('rt-B-rebuilt')?.storedSessionId).toBe('stored-B-tip')++ // A selection may also follow the tip while the durable route stays on root.+ act(() => {+ setSelectedStoredSessionId(selection)+ })++ vi.mocked(requestGatewayForAgent).mockImplementation(async (_connection, _profile, rpc, params) => {+ if (rpc === 'session.resume') {+ return { session_id: 'rt-B2' }+ }++ if (recover && params?.session_id === 'rt-B-rebuilt') {+ throw new Error('session not found')+ }++ return { status }+ })+ await act(async () => {+ expect(await handle.actions[action]('same chat correction')).toBe(true)+ })++ const runtimeId = recover ? 'rt-B2' : 'rt-B-rebuilt'+ expect(requestGatewayForAgent).toHaveBeenLastCalledWith('connection-B', 'default', method, {+ session_id: runtimeId,+ text: 'same chat correction'+ })++ if (recover) {+ expect(requestGatewayForAgent).toHaveBeenCalledWith(+ 'connection-B',+ 'default',+ 'session.resume',+ expect.objectContaining({ session_id: 'stored-B-tip' })+ )+ }++ expect($activeSessionId.get()).toBe(runtimeId)+ expect(handle.cache.activeSessionIdRef.current).toBe(runtimeId)+ expect($selectedStoredSessionId.get()).toBe(selection)+ expect(routedStoredId).toBe('stored-B')+ expect(handle.cache.sessionStateByRuntimeIdRef.current.get('rt-B-rebuilt')?.storedSessionId).toBe('stored-B-tip')+ expect(handle.cache.sessionStateByRuntimeIdRef.current.get(runtimeId)?.storedSessionId).toBe('stored-B-tip')+ expect(handle.cache.runtimeIdByStoredSessionIdRef.current.get('stored-B-tip')).toBe(runtimeId)+ expect(handle.cache.runtimeIdByStoredSessionIdRef.current.get('stored-B')).toBe('rt-B')+ expect($activeSessionStoredIdRotation.get()).toBe(rotation)+ expect(requestGatewayForProfile).not.toHaveBeenCalled()+ }+ )diff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/submit.tsindex c119e762309,7c2a00bc0c3..59869f81e3d--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts@@@ -109,6 -101,6 +110,14 @@@ const MAIN_SUBMIT_SCOPE: NonNullable<Su}/** The prompt submit pipeline, extracted from usePromptActions. */++/** Canonical admission receipt; `user_row_id` binds the optimistic bubble to its durable row. */++type SubmitReceipt = Pick<PromptSubmitResult, 'user_row_id'> & {++ admission_id?: string++ submission_id?: string++ session_id?: string++ status?: string++}++export function useSubmitPrompt(deps: SubmitPromptDeps) {const {activeSessionIdRef,@@@ -833,78 -780,31 +846,79 @@@// the next turn untouched — without it, losing the settle race// (client saw idle, server still unwinding) redirects or interrupts// the live turn with text the user explicitly queued.- ...((options?.fromQueue || queueAdmission) && { queued: true })- ...(options?.fromQueue && { queued: true }),++ ...((options?.fromQueue || queueAdmission) && { queued: true }),+ ...(titlePreview && { title_preview: titlePreview })})+ // A fresh draft had no session owner at entry. Adopt its published+ // route only if it is the SAME captured connection/profile authority.+ const publishedDestination = captureSubmissionDestination(targetStoredSessionId, ambientRequestGateway, {+ owner: knownOwnerForSession(targetStoredSessionId)+ })++ const prepared: NonNullable<typeof retained> = retained ?? {+ id: submissionId,+ owner: destination.owner ??+ (publishedDestination.scopeKey === destination.scopeKey ? publishedDestination.owner : undefined),+ displayText: options?.displayText,+ attachments: syncedAttachments,+ text,+ params: submitParams(liveSessionId)+ }++ const retryKey = retryKeyForTarget()+ await writePreparedSubmission(retryKey, prepared)++ if (sessionDriftReason()) {return abortForSessionSwitch(liveSessionId)}+// On sleep/wake the gateway's in-memory session may have been cleared// while the desktop app still holds the old session ID. The shared// resolver re-registers the stored session and retries once; every// other session-scoped RPC (attach, /compress, rewind, interrupt) goes// through the same helper so one policy covers the whole bug class.let submitErr: unknown = null+ let legacyAccepted = falsetry {- const recoverStoredSessionId = targetStoredSessionId ?? selectedStoredSessionIdRef.current+ const recoverStoredSessionId = targetStoredSessionId- const { result, sessionId: receiptSessionId } = await withSessionNotFoundResume<{ admission_id?: string; submission_id?: string; session_id?: string; status?: string }>(- const submitted = await withSessionNotFoundResume(++ const { result, sessionId: receiptSessionId } = await withSessionNotFoundResume<SubmitReceipt>(sessionId,recoverStoredSessionId,liveId =>- withSessionBusyRetry(() =>- requestGateway<PromptSubmitResult>(- 'prompt.submit',- submitParams(liveId),- PROMPT_SUBMIT_REQUEST_TIMEOUT_MS- )- ),+ withSessionBusyRetry(async () => {+ // Recovery can re-enter this callback within the same submit.+ // An identityless write cannot be deduplicated after a lost ACK.+ if (prepared.legacyAttempted) {+ throw new Error('Legacy submission acknowledgement is unknown; automatic retry is unsafe')+ }++ const params: Record<string, unknown> = { ...prepared.params, session_id: liveId }++ try {- return await requestGateway<{ admission_id?: string; submission_id?: string; session_id?: string; status?: string }>(++ return await requestGateway<SubmitReceipt>(+ 'prompt.submit', params, PROMPT_SUBMIT_REQUEST_TIMEOUT_MS+ )+ } catch (error) {+ // 4094 is an explicit PRE-admission capability refusal. Never+ // downgrade on a timeout, malformed ACK or an ambiguous retry.+ if (!error || typeof error !== 'object' || !('code' in error) || error.code !== 4094 || prepared.legacyAttempted) {+ throw error+ }++ prepared.legacyAttempted = true+ await writePreparedSubmission(retryKey, prepared)+ const { submission_id: _id, ...legacyParams } = params+- const result = await requestGateway<{ admission_id?: string; submission_id?: string; session_id?: string; status?: string }>(++ const result = await requestGateway<SubmitReceipt>(+ 'prompt.submit', legacyParams, PROMPT_SUBMIT_REQUEST_TIMEOUT_MS+ )++ legacyAccepted = true++ return result+ }+ }),{requestGateway,driftReason: sessionDriftReason,@@@ -933,47 -833,25 +947,67 @@@{ alsoTimeout: true })- const rowId = submitted.result?.user_row_id+ if (+ !legacyAccepted &&+ ((result?.submission_id ?? result?.admission_id) !== submissionId ||+ (result?.session_id !== undefined && result.session_id !== receiptSessionId) ||+ !['queued', 'started', 'terminal'].includes(result?.status ?? ''))+ ) {+ dropOptimistic(sessionId)+ releaseBusy()++ return false+ }++ if ((result?.submission_id ?? result?.admission_id) === submissionId) {+ trackPendingSubmission(targetStoredSessionId ?? liveSessionId, {+ id: submissionId,+ text,+ displayText: options?.displayText,+ status: result.status+ })++ // Queued is also the initial receipt for an idle session's first+ // turn. Keep its input and any start event that raced this ACK;+ // explicit queue-only sends never inserted an optimistic bubble.+ if (result.status === 'terminal') {+ // Deduplication does not start a turn or promise another terminal+ // event. Remove our duplicate bubble, but preserve any live turn+ // that an owner event established while the receipt was in flight.+ const next = updateSessionState(receiptSessionId, state => ({+ ...state,+ messages: state.messages.filter(message => message.id !== optimisticId),+ ...(!state.turnLive && !state.streamId && !state.sawAssistantPayload && {+ busy: false,+ awaitingResponse: false,+ pendingBranchGroup: null,+ turnStartedAt: null+ })+ }), targetStoredSessionId)++ if (!next.busy && !next.awaitingResponse) {releaseBusy()}+ }+ }++++ const rowId = result?.user_row_id++ if (typeof rowId === 'number' && Number.isSafeInteger(rowId) && rowId > 0) {+ // The worker may finish before this acknowledgement arrives. Bind+ // only this send's optimistic occurrence; never reset live state or+ // assume the newest user row still belongs to this RPC.- updateSessionState(submitted.sessionId, state => {++ updateSessionState(receiptSessionId, state => {+ const index = state.messages.findIndex(message => message.id === optimisticId && message.role === 'user')++ if (index < 0 || state.messages[index].rowId === rowId) {+ return state+ }++ return {+ ...state,+ messages: state.messages.map((message, i) => (i === index ? { ...message, rowId } : message))+ }+ })+ }} catch (firstErr) {if (firstErr instanceof SessionRecoveryAborted) {console.warn('[submit-drift-abort]', firstErr.reason, { phase: 'post-resume-retry' })diff --cc apps/desktop/src/app/session/hooks/use-session-actions/utils.tsindex 15467ef52e7,f285e73a365..cfc8689303d--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts@@@ -6,9 -13,9 +13,10 @@@ import { normalizePersonalityValue } frimport { embeddedImageUrls, textWithoutEmbeddedImages } from '@/lib/embedded-images'import { parseErrorSurface } from '@/lib/error-surface'import { isMessagingSource, normalizeSessionSource } from '@/lib/session-source'+ import { isLiveTailReplyId } from '@/lib/spoken-reply'import { reconcileApprovalModeForProfile } from '@/store/approval-mode'import { requestDesktopOnboardingForCredentialWarning } from '@/store/onboarding'+import { reconcilePendingSubmissions } from '@/store/pending-submissions'import { $activeGatewayProfile, $profiles, normalizeProfileKey } from '@/store/profile'import { $projectTree } from '@/store/projects'import {diff --cc apps/desktop/src/global.d.tsindex 80ba78208be,f0e1fa45a47..279db5b67d6--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@@ -2,7 -2,9 +2,8 @@@ import type { GatewayWsUrlResult } froimport type { TranslucencyState } from '@hermes/shared/translucency'import type { ScreenshotApi } from '../electron/command-screenshot-types'+ import type { HudModifierApi } from '../electron/hud-modifier-types'import type { HermesNotification } from '../electron/notification-types'-import type { PoolLimits } from '../electron/pool-limits'import type { WakeIndicatorState } from './lib/wake-indicator'import type {diff --cc apps/desktop/src/lib/chat-messages/hydration.tsindex 5f0c5134fb7,aa21ce40e09..5186d767e8f--- a/apps/desktop/src/lib/chat-messages/hydration.ts+++ b/apps/desktop/src/lib/chat-messages/hydration.ts@@@ -20,20 -19,12 +20,26 @@@ const ATTACHED_CONTEXT_MARKER_RE = /(?:const CONTEXT_WARNINGS_MARKER_RE = /(?:^|\n)--- Context Warnings ---[\s\S]*$/const CONTEXT_REF_RE = /@(file|folder|url|image|tool|terminal):(?:"[^"\n]+"|'[^'\n]+'|`[^`\n]+`|\S+)/g+// Native ingress persists the image-routing hints followed by one placeholder+// per flattened image part. Recognize that suffix only, not quoted caption prose.+function persistedImageRefs(text: string) {+ const suffix = /\n\n((?:\[Image attached(?: at)?: [^\n]+\]\n)+)((?:\[screenshot\](?:\n|$))+)$/.exec(text)++ if (!suffix) { return extractImageRefs(text) }+ const paths = [...suffix[1].matchAll(/^\[Image attached(?: at)?: (.+)\]$/gm)].map(match => match[1])++ if (paths.length !== suffix[2].split('[screenshot]').length - 1) { return extractImageRefs(text) }+ const extracted = extractImageRefs(text.slice(0, suffix.index))++ return { cleanedText: extracted.cleanedText, refs: [...extracted.refs, ...paths.map(path => `@image:${formatRefValue(path)}`)] }+}++ // Gateway routing note for Discord turns (gateway/run_inbound.py::discord_triggering_note).+ // Current gateways persist the authored text; this heals rows written before that fix. Only+ // the note is model-facing — the `[Replying to: …]` pointer next to it is kept.+ const DISCORD_TRIGGERING_NOTE_RE =+ /(^|\n)\[Triggering message id: `[^`\n]*` — use as `message_id` for reply\/react\/pin via the discord tools\.\]\n*/+/*** Reply text from a Responses-API `codex_message_items` sidecar (#68321), for rows* whose `content` persisted empty. `commentary` / `analysis` items are mid-turndiff --cc apps/desktop/src/plugins/hermes-bots/group-chat-view.inline-code.test.tsxindex 00000000000,b9dc2e124cc..4c5072ce370mode 000000,100644..100644--- a/apps/desktop/src/plugins/hermes-bots/group-chat-view.inline-code.test.tsx+++ b/apps/desktop/src/plugins/hermes-bots/group-chat-view.inline-code.test.tsx@@@ -1,0 -1,90 +1,92 @@@+ import { readFileSync } from 'node:fs'+ import { dirname, resolve } from 'node:path'+ import { fileURLToPath } from 'node:url'+-import { cleanup, render } from '@testing-library/react'++import { cleanup, render, waitFor } from '@testing-library/react'+ import type { ReactNode } from 'react'+ import { afterEach, beforeAll, expect, it, vi } from 'vitest'++ import { translateBots } from './i18n-test-helper'++ // Room bodies render through the shell's message renderer, whose markdown+ // root is `aui-md prose` — the same container the 1:1 chat uses, minus the+ // `[data-slot='aui_assistant-message-content']` ancestor that scopes the+ // themed inline-code rule in styles.css. Without a room-owned hook the room's+ // `<code>` falls through to Tailwind Typography's fixed near-black ink, which+ // is invisible on every dark theme (#114086). The stubs below emit the two+ // shapes the room can produce (renderer path, raw Streamdown fallback) so the+ // real stylesheet's cascade decides, not a regex over the source text.+ vi.mock('@hermes/plugin-sdk', async () => {+ const { pluginSdkMock, createGroupGateway } = await import('./group-test-utils')+ const base = await pluginSdkMock(createGroupGateway().host)++ const Button = ({ children, onClick, title }: { children?: ReactNode; onClick?: () => void; title?: string }) => (+ <button onClick={onClick} title={title}>+ {children}+ </button>+ )++ return {+ ...base,+ Button,+ RowButton: Button,+ cn: (...values: unknown[]) => values.filter(Boolean).join(' '),+ Codicon: () => null,+ CopyButton: () => null,+ Switch: () => null,+ ConfirmDialog: () => null,+ Dialog: () => null,+ DialogContent: () => null,+ DialogDescription: () => null,+ DialogFooter: () => null,+ DialogHeader: () => null,+ DialogTitle: () => null,+ Input: () => null,+ MessageTextContent: ({ text }: { text: string }) => (+ <div className="aui-md prose">+ <p>+ set <code data-testid="renderer-code">{text}</code> first+ </p>+ </div>+ ),+ Tip: ({ children }: { children: ReactNode }) => children,+ relativeTime: () => 'now',+ useI18n: () => ({ t: { common: { cancel: 'Cancel', save: 'Save' } } }),+ usePluginI18n: () => translateBots+ }+ })+ vi.mock('./avatar', () => ({ avatarColor: () => '#888', botAppearance: () => ({}), BotFace: () => null }))+ vi.mock('./group-chat-parts', () => ({+ GroupClarifyCard: () => null,+ GroupImageControls: () => null,+ GroupMentionInput: () => null+ }))++ const STYLES = resolve(dirname(fileURLToPath(import.meta.url)), '../../styles.css')++ beforeAll(() => {+ Element.prototype.scrollIntoView = vi.fn()+ const sheet = document.createElement('style')+ sheet.textContent = readFileSync(STYLES, 'utf8')+ document.head.appendChild(sheet)+ })+ afterEach(cleanup)++ it('themes inline code in room message bodies with the chat inline-code tokens', async () => {+ const { $groupChats } = await import('./group-chat')+ const { GroupChatWorkspace } = await import('./group-chat-view')++ const log = [+ { id: 'm1', thread: 'a', from: { kind: 'member' as const, name: 'builder' }, text: 'discover_models', at: 1 }+ ]++ $groupChats.set({ Room: { log, watermarks: {}, sessions: {} } })++ const { getByTestId } = render(<GroupChatWorkspace group="Room" members={[{ name: 'builder' }] as never} />)++ // The room paints once the async group-driver gate resolves to the legacy workspace.++ await waitFor(() => expect(getByTestId('renderer-code')).toBeTruthy())+ const style = getComputedStyle(getByTestId('renderer-code'))++ expect(style.color).toBe('var(--ui-inline-code-foreground)')+ expect(style.background).toBe('var(--ui-inline-code-background)')+ })diff --cc apps/desktop/src/plugins/hermes-bots/group-chat-view.render.test.tsxindex 7ec5ccb4d12,43f7ff341f2..29e491a2ea9--- a/apps/desktop/src/plugins/hermes-bots/group-chat-view.render.test.tsx+++ b/apps/desktop/src/plugins/hermes-bots/group-chat-view.render.test.tsx@@@ -1,4 -1,4 +1,4 @@@- import { cleanup, render, waitFor } from '@testing-library/react'-import { cleanup, fireEvent, render, screen } from '@testing-library/react'++import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import type { ReactNode } from 'react'import { afterEach, expect, it, vi } from 'vitest'@@@ -85,3 -84,35 +86,37 @@@ it('renders member replies through the['MEDIA:/tmp/remote.png', 'false']])})++ it('removes Stop controls from historical working rows after the room settles', async () => {+ Element.prototype.scrollIntoView = vi.fn()++ const [{ $groupChats }, activity, { GroupChatWorkspace }] = await Promise.all([+ import('./group-chat'),+ import('./group-activity'),+ import('./group-chat-view')+ ])++ $groupChats.set({+ Settled: {+ epoch: 1,+ log: [],+ members: [{ name: 'builder' }],+ running: false,+ sessions: {},+ watermarks: {}+ }+ })+ activity.recordGroupActivity('Settled', { kind: 'working', member: 'builder' })+ activity.recordGroupActivity('Settled', { kind: 'replied', member: 'builder' })+ activity.recordGroupActivity('Settled', { kind: 'settled', member: null })++ render(<GroupChatWorkspace group="Settled" members={[{ name: 'builder' }]} />)++ // The room paints once the async group-driver gate resolves to the legacy workspace.++ await waitFor(() => expect(screen.getByRole('button', { name: /^Activity/ })).toBeTruthy())+ fireEvent.click(screen.getByRole('button', { name: /^Activity/ }))++ expect(screen.getByText('builder is working…')).toBeTruthy()+ expect(screen.getByText('builder replied')).toBeTruthy()+ expect(screen.getByText('turn settled')).toBeTruthy()+ expect(screen.queryByRole('button', { name: 'Stop' })).toBeNull()+ })diff --cc apps/desktop/src/plugins/hermes-bots/group-compress.test.tsxindex 00000000000,194993035d6..e96e42230a7mode 000000,100644..100644--- a/apps/desktop/src/plugins/hermes-bots/group-compress.test.tsx+++ b/apps/desktop/src/plugins/hermes-bots/group-compress.test.tsx@@@ -1,0 -1,149 +1,151 @@@+ import { cleanup, fireEvent, render, waitFor } from '@testing-library/react'+ import type { ReactNode } from 'react'+ import { afterEach, beforeEach, expect, it, vi } from 'vitest'++ import { createGroupGateway } from './group-test-utils'+ import type { ScriptedGateway } from './group-test-utils'+ import { translateBots } from './i18n-test-helper'++ // #102291: room member sessions are hidden plumbing nothing else can compress.+ // The room settings dialog owns a per-member "Compress history" that resumes+ // every session the room holds for that member and runs session.compress on+ // the LIVE runtime id — never minting a new session as a side effect.++ const { host } = vi.hoisted(() => ({ host: {} as Record<string, unknown> }))+ const state = { gateway: null as null | ScriptedGateway }++ vi.mock('@hermes/plugin-sdk', async () => {+ const { pluginSdkMock } = await import('./group-test-utils')+ const base = await pluginSdkMock(host)+ const Passthrough = ({ children }: { children?: ReactNode }) => <>{children}</>++ const Button = ({+ children,+ disabled,+ onClick,+ 'aria-label': label+ }: {+ 'aria-label'?: string+ children?: ReactNode+ disabled?: boolean+ onClick?: () => void+ }) => (+ <button aria-label={label} disabled={disabled} onClick={onClick}>+ {children}+ </button>+ )++ return {+ ...base,+ Button,+ RowButton: Button,+ cn: (...values: unknown[]) => values.filter(Boolean).join(' '),+ Codicon: () => null,+ CopyButton: () => null,+ Switch: () => null,+ ConfirmDialog: () => null,+ Dialog: Passthrough,+ DialogContent: Passthrough,+ DialogDescription: Passthrough,+ DialogFooter: Passthrough,+ DialogHeader: Passthrough,+ DialogTitle: Passthrough,+ Input: () => null,+ Tip: Passthrough,+ relativeTime: () => 'now',+ useI18n: () => ({ t: { common: { cancel: 'Cancel', save: 'Save' } } }),+ usePluginI18n: () => translateBots+ }+ })+ vi.mock('./avatar', () => ({ avatarColor: () => '#888', botAppearance: () => ({}), BotFace: () => null }))+ vi.mock('./group-chat-parts', () => ({+ GroupClarifyCard: () => null,+ GroupImageControls: () => null,+ GroupMentionInput: () => null+ }))++ beforeEach(() => {+ vi.resetModules()+ state.gateway = createGroupGateway()++ for (const key of Object.keys(host)) {+ delete host[key]+ }++ // The scripted gateway answers unknown methods with `{}`; give+ // session.compress the in-process gateway's real result shape.+ const inner = state.gateway.host.request as (method: string, params: Record<string, unknown>) => Promise<unknown>++ state.gateway.host.request = async (method: string, params: Record<string, unknown> = {}) => {+ if (method === 'session.compress') {+ state.gateway!.rpc.push({ method, params, refcountAfter: 0 })++ return { status: 'compressed', before_messages: 1588, after_messages: 134, summary: { headline: '1588 → 134' } }+ }++ return inner(method, params)+ }++ Object.assign(host, state.gateway.host)+ })+ afterEach(cleanup)++ async function seedMemberSession(profile: string, title: string) {+ const request = state.gateway!.host.request as (method: string, params: Record<string, unknown>) => Promise<unknown>+ const created = (await request('session.create', { profile, title, hidden: true })) as { stored_session_id: string }+ state.gateway!.rpc.length = 0++ return created.stored_session_id+ }++ it('compressGroupMemberHistory resumes each stored session for the member and compresses the live runtime id', async () => {+ const { $groupChats } = await import('./group-chat')+ const { compressGroupMemberHistory } = await import('./group-compress')+ const mason = await seedMemberSession('mason', 'Group: room-1 · t1')+ const critic = await seedMemberSession('critic', 'Group: room-1 · t1')+ $groupChats.set({+ Build: {+ log: [],+ roomId: 'room-1',+ sessions: { 'thread:t1::mason': mason, 'thread:t1::critic': critic },+ watermarks: {}+ }+ })++ const outcome = await compressGroupMemberHistory('Build', { name: 'mason' } as never)++ expect(outcome).toMatchObject({ compressed: 1, pending: 0, skipped: 0, lines: ['1588 → 134'] })+ const methods = state.gateway!.rpc.map(call => call.method)+ expect(methods).toEqual(['session.resume', 'session.compress'])+ const [resume, compress] = state.gateway!.rpc+ expect(resume.params).toMatchObject({ session_id: mason, profile: 'mason', omit_messages: true })+ // The compress targets the runtime id the resume minted, not the stored id.+ expect(compress.params.session_id).toBe(state.gateway!.sessions.get(mason)!.runtime)+ expect(compress.params.session_id).not.toBe(mason)+ expect(methods).not.toContain('session.create')+ })++ it('the room settings dialog offers Compress history per member and reports the result', async () => {+ Element.prototype.scrollIntoView = vi.fn()+ const { $groupChats } = await import('./group-chat')+ const { GroupChatWorkspace } = await import('./group-chat-view')+ const mason = await seedMemberSession('mason', 'Group: room-1 · t1')+ $groupChats.set({ Build: { log: [], roomId: 'room-1', sessions: { 'thread:t1::mason': mason }, watermarks: {} } })+ const members = [{ name: 'mason' }, { name: 'critic' }] as never++ const { getByLabelText } = render(<GroupChatWorkspace group="Build" members={members} />)++ // The room paints once the async group-driver gate resolves to the legacy workspace.++ await waitFor(() => expect(getByLabelText('Group settings for Build')).toBeTruthy())+ fireEvent.click(getByLabelText('Group settings for Build'))+ fireEvent.click(getByLabelText('Compress history: mason'))++ await waitFor(() => expect(state.gateway!.rpcFor('session.compress')).toHaveLength(1))+ const notify = state.gateway!.host.notify as ReturnType<typeof vi.fn>+ await waitFor(() =>+ expect(notify.mock.calls.map(([toast]) => (toast as { message: string }).message)).toContain(+ 'Compressed 1 room session for Mason — 1588 → 134'+ )+ )+ // Only mason's session was touched — critic never had one and none was created.+ expect(state.gateway!.rpcFor('session.create')).toHaveLength(0)+ })diff --cc apps/desktop/src/plugins/hermes-bots/group-test-utils.tsindex 34ce5b70c61,af3600f40c9..fa0177a1614--- a/apps/desktop/src/plugins/hermes-bots/group-test-utils.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-test-utils.ts@@@ -437,9 -454,8 +459,9 @@@ export async function pluginSdkMock(hosblobatarSvg: undefined,computed: nanostores.computed,createBudgetedLoop: undefined,+ gatewayActivationEpoch: () => 0,host,- SkillsView: undefined,+ CapabilitiesView: undefined,MessageTextContent: undefined,Streamdown: undefined,queryClient: { invalidateQueries: () => undefined },diff --cc apps/desktop/src/plugins/hermes-bots/relay.tsindex 11eb5e80d3a,e159ea247d8..ad9e428e5c1--- a/apps/desktop/src/plugins/hermes-bots/relay.ts+++ b/apps/desktop/src/plugins/hermes-bots/relay.ts@@@ -105,24 -105,12 +105,23 @@@ const relay: RelayLifecycle =// leases. Local routes get a no-op release inside the host (idle-reaper// exemption). stopBotRelay releases everything.const relayRouteRetentions = new Map<string, () => void>()+// Claimed envelopes remain pinned to their sender until terminal reply ACK.+// The sender's durable claimed directory restores these after renderer restart.+const pendingRelays = new Map<string, Map<string, RelayEnvelope>>()++function pendingRelaysFor(sender: RelayConnection): Map<string, RelayEnvelope> {+ const senderKey = JSON.stringify(sender.route)+ const pending = pendingRelays.get(senderKey) || new Map<string, RelayEnvelope>()+ pendingRelays.set(senderKey, pending)++ return pending+}- /** One reachable gateway plus a representative route onto it. The route comes- * from `host.profileRoutes()`, which carries identity only — the optional- * label fields are read defensively in relayAgentsOn and never arrive. */+ /** One reachable gateway plus a representative route onto it. The route carries+ * identity only, so the human label comes from the registry (connectionLabels). */interface RelayConnection {id: string- route: ProfileRoute & { connectionLabel?: string; label?: string }+ route: ProfileRoute}/** One agent as pushed to a peer gateway's relay roster. */diff --cc apps/desktop/src/store/composer.tsindex 3c866b3ac40,7a581b2272f..83e8d5fc1bf--- a/apps/desktop/src/store/composer.ts+++ b/apps/desktop/src/store/composer.ts@@@ -19,8 -19,8 +19,10 @@@ export interface ComposerAttachment/** Downscaled data URL for the attachment card and optimistic bubble only. */thumbnailUrl?: stringpath?: string+ /** Validated MIME returned by canonical owner staging. */+ mime?: string+ /** Bounded source text from a Hermes-generated large paste, sent only to the title path. */+ titlePreview?: stringattachedSessionId?: string/** Set while the file/image bytes are being staged into the session* workspace (remote upload or local stage), and 'error' if that failed.diff --cc apps/desktop/src/store/gateway.tsindex 48d72def561,3bc17ab82e2..43b4f80d52b--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@@ -359,20 -464,33 +451,33 @@@ async function ridesPrimaryBackendreturn false}+ // Resolved per call, never cached: main answers the route per request+ // (`resolveProfileBackendRoute` case 6 keeps a pooled backend for+ // `HERMES_DESKTOP_ISOLATED_BACKEND=1`), and for a pooled profile this is the+ // same dial `openSecondary` makes next, coalesced by main's claim key.try {const conn = await withTimeout(- desktop.getConnectionFor({ connectionId: id, profile: key, ...dialPriority(spawnPriority) }),+ desktop.getConnectionFor({ connectionId: id, profile: key }),RECONNECT_ATTEMPT_TIMEOUT_MS,- `Timed out resolving shared-remote route for "${key}"`+ `Timed out resolving the backend route for "${key}"`)- return Boolean(conn && typeof conn === 'object' && (conn as { sharedRemote?: boolean }).sharedRemote === true)+ const flags =+ conn && typeof conn === 'object' ? (conn as { sharedPrimary?: boolean; sharedRemote?: boolean }) : null++ return flags?.sharedRemote === true || flags?.sharedPrimary === true} catch {- // Probe failed. A secondary at this already-attached source is the #96493- // ghost WebSocket (accept/close, messages=1). Prefer the primary until a- // later probe can prove isolation (`sharedRemote: false`). Isolated SSH- // still dials its own socket when getConnectionFor succeeds.- return true+ // Probe failed on a remote (or not-yet-classified) primary: a secondary at+ // this already-attached source is the #96493 ghost WebSocket (accept/close,+ // messages=1), so prefer the primary until a later probe can prove+ // isolation (`sharedRemote: false`). A LOCAL primary must NOT get that+ // fallback: when main routes the profile to a pooled child (isolated+ // backend), the primary would still ACCEPT a `profile`-tagged+ // session.create (profile_home multiplexing) and mint the session under+ // its own pid, but the exact-owner route names the pool backend — after a+ // renderer reload or a pool respawn the resume dials that backend and is+ // refused SESSION_NOT_OWNED by a pid of the same Desktop (#101416).+ return g.primaryConnectionMode !== 'local'}}@@@ -528,9 -646,15 +633,15 @@@ function clearTimer(entry: Secondary):}}-async function openSecondary(entry: Secondary, spawnPriority: SpawnPriority = 'background'): Promise<void> {+async function openSecondary(entry: Secondary): Promise<void> {const desktop = window.hermesDesktop+ const reauthError = g.reauthFailures.get(entry.scope)?.error++ if (reauthError) {+ throw reauthError+ }+if (!desktop) {return}@@@ -951,11 -1142,12 +1106,9 @@@ export async function requestGatewayForparams: Record<string, unknown> = {},timeoutMs?: number,signal?: AbortSignal,- // Dial intent (#111651): accepted so Settings-scoped callers keep one call- // shape; the canonical ensure path has no slot to reserve.- _options: { spawnPriority?: SpawnPriority } = {}+ { spawnPriority = 'background' }: { spawnPriority?: SpawnPriority } = {}): Promise<T> {- const route = await gatewayForProfile(profile, true)- // A user-initiated Settings-scoped RPC (the Vault tab's "Applies to" pick)- // dials `foreground` so a cold profile spawn is not queued behind background- // work (#111651); ambient callers keep the background default.+ const route = await gatewayForProfile(profile, true, spawnPriority)try {if (!route.gateway) {@@@ -1363,6 -1606,25 +1567,31 @@@ export async function retainGatewayForSreturn release}+ function scopeHasTurnLease(scope: string): boolean {+ const prefix = `${scope}\u0000`++ for (const key of g.turnLeases.keys()) {+ if (key.startsWith(prefix)) {+ return true+ }+ }++ return false+ }++ // Tell main whether a prompt turn leases this scope's pooled backend. An early+ // skip for cooperative retirement (electron/pool-retire.ts), never the proof:+ // main asks the backend itself before stopping anything. From #104871.+ function publishTurnLease(scope: string, activeTurn: boolean): void {- void window.hermesDesktop?.touchBackend?.(scope, { activeTurn }).catch(() => undefined)++ // Older Desktop hosts own pooled children. Canonical hosts expose no touch++ // capability: their gateway lifetime is independent of renderer leases.++ const desktop = window.hermesDesktop as (typeof window.hermesDesktop & {++ touchBackend?: (scope: string, options?: { activeTurn?: boolean }) => Promise<unknown>++ })++++ void desktop?.touchBackend?.(scope, { activeTurn }).catch(() => undefined)+ }+function releaseTerminalTurnLease(scope: string, event: GatewayEvent): void {const sessionId = String(event.session_id || '').trim()@@@ -1723,13 -2108,11 +2077,15 @@@ export function openSecondaryCount(): n// "Live" means the socket is OPEN: a wantOpen entry stuck in its reconnect// backoff has no consumer on that backend, and pinging it anyway kept a// tile-pinned backend keepalive-fresh forever, so LRU eviction and the idle- // reaper never freed its pool slot (#103375).+ // reaper never freed its pool slot (#103375). Each ping also carries whether a+ // prompt turn leases the scope, so a foreground dial that must retire a+ // resident can skip leased ones early (the backend probe stays the proof).export function touchSecondaryGateways(): void {- const desktop = window.hermesDesktop+ // Older Desktop hosts own pooled children. Canonical hosts expose no touch+ // capability: their gateway lifetime is independent of renderer keepalives.+ const desktop = window.hermesDesktop as (typeof window.hermesDesktop & {- touchBackend?: (scope: string) => Promise<unknown>++ touchBackend?: (scope: string, options?: { activeTurn?: boolean }) => Promise<unknown>+ })for (const entry of g.secondaries.values()) {if (entry.wantOpen && isOpen(entry.gateway)) {diff --cc apps/desktop/src/store/notifications.tsindex 7738e06aef4,00fd7c22243..79f8921dbe2--- a/apps/desktop/src/store/notifications.ts+++ b/apps/desktop/src/store/notifications.ts@@@ -1,6 -1,8 +1,7 @@@import { atom } from 'nanostores'import { translateNow } from '@/i18n'+ import { isOutOfSyncRpcParams } from '@/lib/gateway-rpc'-import { isLocalBackendSlotWaitTimeout, requestPoolLimitsSettings } from '@/store/pool-limits'import { requestBackendRestart, requestRoute } from '@/store/recovery-requests'export type NotificationKind = 'error' | 'warning' | 'info' | 'success'@@@ -246,15 -257,27 +256,21 @@@ export function notify(input: Notificatreturn id}- export function notifyError(error: unknown, fallback: string, options: { action?: NotificationAction } = {}): string {+ export function notifyError(+ error: unknown,+ fallback: string,+ options: { action?: NotificationAction; id?: string } = {}+ ): string {const readable = readableError(error, fallback)- const poolSlotTimeout = isLocalBackendSlotWaitTimeout(error)return notify({- action: poolSlotTimeout- ? {- label: translateNow('desktop.poolSlotTimeoutOpenSettings'),- onClick: requestPoolLimitsSettings- }- : (options.action ?? readable.action),+ action: options.action ?? readable.action,+ // A caller that can fire again for the same cause names its toast, so the repeat replaces it.+ id: options.id,kind: 'error',title: fallback,- message: poolSlotTimeout ? translateNow('desktop.poolSlotTimeoutBody') : readable.message,- detail: poolSlotTimeout ? readable.message : readable.detail+ message: readable.message,+ detail: readable.detail})}diff --cc apps/shared/src/json-rpc-gateway-replay.test.tsindex eeeebb2a822,33eb4fb1a9c..6796214bec0--- a/apps/shared/src/json-rpc-gateway-replay.test.ts+++ b/apps/shared/src/json-rpc-gateway-replay.test.ts@@@ -289,121 -289,51 +289,166 @@@ describe('JsonRpcGatewayClient event-seclient.close()})+ it('keeps canonical replay epochs session-local while retaining the legacy gateway epoch', async () => {+ const client = makeClient()+ const first = client.connect('ws://x')+ let sock = sockets[sockets.length - 1]+ sock.open()+ await first++ const ready = (epoch: string) => sock.serverFrame({+ jsonrpc: '2.0', method: 'event', params: { type: 'gateway.ready', payload: { replay_epoch: epoch } }+ })++ const live = (session_id: string, seq: number, replay_epoch?: string) => sock.serverFrame({+ jsonrpc: '2.0', method: 'event', params: { type: 'message.delta', session_id, seq, replay_epoch }+ })++ ready('gateway-A')+ live('s1', 7, 's1-A')+ live('s2', 9, 's2-A')+ live('legacy', 20)+ live('s1', 1, 's1-B')+ expect(client.getSeqWatermarks()).toEqual({ s1: 1, s2: 9, legacy: 20 })++ client.invalidate('drop')+ const second = client.connect('ws://x')+ sock = sockets[sockets.length - 1]+ sock.open()+ await second++ const requests = sock.sent.map(raw => JSON.parse(raw) as ReturnType<FakeWebSocket['lastRequest']>)+ expect(requests).toHaveLength(3)+ expect(requests.map(req => req.params)).toEqual(expect.arrayContaining([+ { session_id: 's1', last_seen: 1, replay_epoch: 's1-B' },+ { session_id: 's2', last_seen: 9, replay_epoch: 's2-A' },+ { session_id: 'legacy', last_seen: 20, replay_epoch: 'gateway-A' }+ ]))++ for (const req of requests) {+ const sid = req.params.session_id+ const epoch = req.params.replay_epoch+ const seq = Number(req.params.last_seen) + 1+ sock.serverFrame({+ jsonrpc: '2.0', id: req.id,+ result: {+ events: [{ type: 'message.delta', session_id: sid, seq }], epoch,+ ...(sid === 'legacy' ? {} : { replay_epoch: epoch }),+ latest_seq: seq, truncated: false, count: 1+ }+ })+ }++ await vi.waitFor(() => {+ expect(client.getSeqWatermarks()).toEqual({ s1: 2, s2: 10, legacy: 21 })+ })++ // A legacy process restart must not erase canonical session cursors.+ ready('gateway-B')+ expect(client.getSeqWatermarks()).toEqual({ s1: 2, s2: 10 })+ client.close()+ })++ it('applies parked session epochs after replay so a new generation does not poison the old gap', async () => {+ const client = makeClient()+ const seen: string[] = []+ client.on('message.delta', event => {+ const frame = event as unknown as { replay_epoch: string; seq: number }+ seen.push(`${frame.replay_epoch}:${frame.seq}`)+ })+ const first = client.connect('ws://x')+ let sock = sockets[sockets.length - 1]+ sock.open()+ await first+ sock.serverFrame({+ jsonrpc: '2.0', method: 'event',+ params: { type: 'message.delta', session_id: 's1', seq: 5, replay_epoch: 'old' }+ })+ client.invalidate('drop')+ const second = client.connect('ws://x')+ sock = sockets[sockets.length - 1]+ sock.open()+ await second+ const req = sock.lastRequest()+ expect(req.method).toBe('session.events.since')++ // These arrive before the response, but belong AFTER the old replay gap.+ for (const seq of [1, 2]) {+ sock.serverFrame({+ jsonrpc: '2.0', method: 'event',+ params: { type: 'message.delta', session_id: 's1', seq, replay_epoch: 'new' }+ })+ }++ expect(client.getSeqWatermarks()).toEqual({ s1: 5 })+ expect(seen).toEqual(['old:5'])+ sock.serverFrame({+ jsonrpc: '2.0', id: req.id,+ result: {+ // Include an overlapping old frame: early epoch adoption would replay it twice.+ events: [5, 6, 7].map(seq => ({ type: 'message.delta', session_id: 's1', seq, replay_epoch: 'old' })),+ epoch: 'old', replay_epoch: 'old', latest_seq: 7, truncated: false, count: 3+ }+ })+ await vi.waitFor(() => {+ expect(seen).toEqual(['old:5', 'old:6', 'old:7', 'new:1', 'new:2'])+ })+ expect(client.getSeqWatermarks()).toEqual({ s1: 2 })++ client.invalidate('drop')+ const third = client.connect('ws://x')+ sock = sockets[sockets.length - 1]+ sock.open()+ await third+ expect(sock.lastRequest().params).toEqual({ session_id: 's1', last_seen: 2, replay_epoch: 'new' })+ client.close()+ })++ it('restarts replay after its socket is invalidated before rejected cleanup runs', async () => {+ const client = makeClient()+ const seen: number[] = []+ client.on('message.delta', e => seen.push((e as unknown as { seq: number }).seq))++ const first = client.connect('ws://x')+ sockets[0].open()+ await first+ sockets[0].serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'message.delta', session_id: 's1', seq: 1 } })++ client.invalidate('first drop')+ const second = client.connect('ws://x')+ sockets[1].open()+ await second+ await vi.waitFor(() => expect(sockets[1].lastRequest().method).toBe('session.events.since'))++ // The old request rejects asynchronously after detach. Open the+ // replacement before its cleanup runs; it must own a fresh replay.+ client.invalidate('second drop')+ const third = client.connect('ws://x')+ sockets[2].open()+ await third+ await vi.waitFor(() => expect(sockets[2].lastRequest().method).toBe('session.events.since'))++ const request = sockets[2].lastRequest()+ expect(request.params).toEqual({ session_id: 's1', last_seen: 1 })++ // A live frame racing the new replay is parked by the NEW hold; the stale+ // replay's cleanup must neither flush it nor advance the watermark past+ // the gap it never recovered.+ sockets[2].serverFrame({ jsonrpc: '2.0', method: 'event', params: { type: 'message.delta', session_id: 's1', seq: 3 } })+ await Promise.resolve()+ expect(seen).toEqual([1])+ expect(client.getSeqWatermarks()).toEqual({ s1: 1 })++ sockets[2].serverFrame({+ jsonrpc: '2.0', id: request.id,+ result: { events: [{ type: 'message.delta', session_id: 's1', seq: 2 }], latest_seq: 2, truncated: false, count: 1 }+ })++ await vi.waitFor(() => expect(seen).toEqual([1, 2, 3]))+ expect(client.getSeqWatermarks()).toEqual({ s1: 3 })+ client.close()+ })+it('clears stale watermarks when the backend epoch changes (restart poisoning)', async () => {const client = makeClient()diff --cc apps/shared/src/json-rpc-gateway.tsindex b1b228f7749,71374ee5a3c..6b6add7d4cb--- a/apps/shared/src/json-rpc-gateway.ts+++ b/apps/shared/src/json-rpc-gateway.ts@@@ -125,10 -132,11 +132,12 @@@ export class JsonRpcGatewayClient* silently believe nothing was missed.*/private replayEpoch: string | null = null+ private replayEpochBySession = new Map<string, string>()private readonly stateHandlers = new Set<(state: ConnectionState) => void>()- private readonly options: Required<Omit<GatewayClientOptions, 'socketFactory'>> &- Pick<GatewayClientOptions, 'socketFactory'>+ private readonly options: Required<+ Omit<GatewayClientOptions, 'onRequestHandlerError' | 'onUnhandledRequest' | 'socketFactory'>+ > &+ Pick<GatewayClientOptions, 'onRequestHandlerError' | 'onUnhandledRequest' | 'socketFactory'>constructor(options: GatewayClientOptions = {}) {this.options = {@@@ -457,19 -481,24 +484,26 @@@// One RPC per known session keeps params flat; sessions are few (<20).const results = await Promise.allSettled(- entries.map(([sid, lastSeen]) =>+ entries.map(([sid, lastSeen]) => {+ const epoch = this.replayEpochBySession.get(sid) ?? this.replayEpoch+// `open_requests` on the answer are re-delivered by the channel itself.- this.request<{ events?: Array<{ type: string; session_id?: string; seq?: number; payload?: unknown }> }>(+ return this.request<{ events?: Array<{ type: string; session_id?: string; seq?: number; payload?: unknown }> }>('session.events.since',- { session_id: sid, last_seen: lastSeen },+ { session_id: sid, last_seen: lastSeen, ...(epoch ? { replay_epoch: epoch } : {}) },REPLAY_REQUEST_TIMEOUT_MS)- )+ }))+ // The socket that owned this replay was dropped while its requests were+ // settling. Its results and cleanup must not consume the replacement+ // socket's replay window.+ if (this.replayGeneration !== replayGeneration) {+ return+ }+- for (const result of results) {+ for (const [index, result] of results.entries()) {if (result.status !== 'fulfilled' || !Array.isArray(result.value?.events)) {continue}diff --cc cron/jobs.pyindex e6e1dea16a0,bd9be129cd4..59f82df2c8d--- a/cron/jobs.py+++ b/cron/jobs.py@@@ -27,7 -27,8 +27,8 @@@ except ImportError: # pragma: no covemsvcrt = Nonefrom datetime import datetime, timedelta, timezonefrom 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_SECONDSfrom cron.env_settings import cron_env_settingfrom typing import Optional, Dict, List, Any, Callable, Set, Tuple, Union, Collection@@@ -2461,8 -2350,8 +2369,9 @@@ def mark_job_runstatus: Optional[str] = None,*,expected_fire_owner: Optional[str] = None,+ execution_id: Optional[str] = None,model_unreachable: bool = False,+ quota_hold_seconds: Optional[float] = None,) -> bool:"""Mark a job as run: update last_run_at/last_status, bump completed, recompute next_run_at,and retire the record as a terminal completion when the repeat limit is reached.@@@ -2476,10 -2365,12 +2385,14 @@@zero API calls). Recurring jobs then get a bounded automatic re-run — ``next_run_at`` is pulledearlier per ``cron.unreachable_retry.RETRY_DELAYS_SECONDS`` — instead of waiting a full period(Cowork-style; see cron/unreachable_retry.py).++ ``quota_hold_seconds``: the provider said it stays closed for this long (a quota 429 with+ ``retry after <N>s``). Recurring jobs are parked at their first occurrence after the window+ instead of re-firing into it on every tick (cron/quota_hold.py, #89376)."""def apply(jobs, _i, job):+ if execution_id is not None and execution_id in job.get("canonical_completions", []):+ return Trueif expected_fire_owner is not None:claim = job.get("fire_claim")if not isinstance(claim, dict) or claim.get("by") != expected_fire_owner:@@@ -2489,9 -2380,8 +2402,10 @@@return Falsenow = _hermes_now().isoformat()_record_run_outcome(job, success, error, delivery_error, status, now)+ if execution_id is not None:+ job.setdefault("canonical_completions", []).append(execution_id)_advance_after_run(job, now)+ from cron import quota_holdfrom cron.unreachable_retry import clear_state, plan_retryif not success and model_unreachable and not is_terminal_job(job):diff --cc cron/scheduler.pyindex 17d09f8dd86,1d156c0d6e6..2585dc4f051--- a/cron/scheduler.py+++ b/cron/scheduler.py@@@ -1097,16 -1314,15 +1314,19 @@@ def drain_delivery_queue(adapters, loop# open/create entirely until a worker has actually queued something.if not _path().exists():return 0- return drain(- lambda queued_job, queued_content, queued_for_failure: _deliver_result(- queued_job,- queued_content,- adapters=adapters,- loop=loop,+ def send(queued_job, queued_content, queued_for_failure):+ error = _deliver_result(+ queued_job, queued_content, adapters=adapters, loop=loop,for_failure=queued_for_failure,)- if not error and queued_for_failure:- )++ # The ping left the process: book the incident alerted. A notice every target hid++ # (warning notifications suppressed) is a durable disposition, not an alert.++ if (not error and queued_for_failure++ and not queued_job.get("_notification_all_targets_suppressed")):+ _mark_incident_alerted(queued_job.get("_failure_incident_id"))+ return error++ return drain(send)_DEFAULT_SCRIPT_TIMEOUT = 3600 # seconds (1 hour)diff --cc cron/scheduler_authority.pyindex e0bc2180f08,00000000000..bba09dea2c7mode 100644,000000..100644--- a/cron/scheduler_authority.py+++ b/cron/scheduler_authority.py@@@ -1,123 -1,0 +1,124 @@@+"""Transport-only cron execution; output/delivery remain with the firing scheduler."""+import asyncio+import hashlib+import json+import uuid+++class CronExecutionUnknown(RuntimeError):+ """The owner may have accepted this fire; never book it as failed or re-fire."""+++def journal_path(job_id, request_id):+ from hermes_constants import get_hermes_home+ key = hashlib.sha256(json.dumps([job_id, request_id]).encode()).hexdigest()+ return get_hermes_home() / 'cron' / 'admissions' / (key + '.json')+++def run_canonical_job(job, *, extra_prompt=None, cancel_event=None, execution_id=None):+ from gateway.session_cron import owner_for_home, operation+ from hermes_cli.gateway_client import connect_gateway+ from hermes_constants import get_hermes_home+ from utils import atomic_json_write++ params = {'job_id': job['id'], 'request_id': execution_id or job.get('execution_id') or uuid.uuid4().hex,+ 'extra_prompt': extra_prompt}+ root = get_hermes_home() / 'cron' / 'admissions'+ journal = journal_path(params['job_id'], params['request_id'])+ record = {'params': params, 'receipt': None}+ if journal.exists():+ record = json.loads(journal.read_text(encoding='utf-8'))+ if record['params'] != params:+ raise CronExecutionUnknown('cron admission identity conflict')+ attempted = journal.exists()+ owner = owner_for_home(get_hermes_home())++ def save():+ root.mkdir(parents=True, exist_ok=True)+ atomic_json_write(journal, record, mode=0o600)++ async def observe(call):+ nonlocal attempted+ attempted = True+ save()+ receipt = await call('submit', params)+ record['receipt'] = receipt+ save()+ while True:+ if cancel_event is not None and cancel_event.is_set():+ await call('cancel', receipt)+ state = await call('status', receipt)+ if state['status'] == 'terminal':++ job.update(state.get('job_flags') or {})+ return tuple(state['result'])+ if state['status'] == 'unknown':+ raise CronExecutionUnknown('unknown_execution: cron admission was not replayed')+ await asyncio.sleep(.1)++ async def remote():+ async with connect_gateway() as client:+ return await observe(lambda op, data: client.rpc('cron.' + op, **data))++ try:+ if owner is not None:+ authority, loop = owner+ try:+ current = asyncio.get_running_loop()+ except RuntimeError:+ current = None+ if current is loop:+ raise RuntimeError('cron synchronous execution must run off the owner event loop')+ return asyncio.run_coroutine_threadsafe(+ observe(lambda op, data: operation(authority, op, data)), loop).result()+ return asyncio.run(remote())+ except Exception as exc:+ if attempted:+ raise CronExecutionUnknown(f'Cron execution unverified; reconcile {journal}: {exc}') from exc+ error = f'{type(exc).__name__}: {exc}'+ return False, f'# Cron Job: {job["id"]} (FAILED)\n\n{error}\n', '', error++def reconcile_pending():+ """Observe prepared fires; never submit missing or interrupted work."""+ from gateway.session_cron import owner_for_home, operation+ from hermes_constants import get_hermes_home+ from hermes_cli.gateway_client import connect_gateway+ from cron.jobs import pause_job, mark_job_run, save_job_output+ from cron.scheduler import _compose_run_delivery, _is_cron_silence_response+ from cron.delivery_queue import enqueue+ import logging++ root = get_hermes_home() / 'cron' / 'admissions'+ for journal in sorted(root.glob('*.json')):+ try:+ record = json.loads(journal.read_text(encoding='utf-8'))+ params = record['params']+ if journal != journal_path(params['job_id'], params['request_id']):+ raise ValueError('cron journal identity conflict')+ owner = owner_for_home(get_hermes_home())+ async def observe():+ if owner is not None:+ return await operation(owner[0], 'recover', params)+ async with connect_gateway() as client:+ return await client.rpc('cron.recover', **params)+ if owner is not None:+ state = asyncio.run_coroutine_threadsafe(observe(), owner[1]).result(timeout=20)+ else:+ state = asyncio.run(observe())+ if state['status'] != 'terminal':+ if state['status'] in {'unknown', 'missing'}:+ pause_job(params['job_id'], reason='Canonical cron ' + state['status'] + '; no automatic re-execution')+ continue+ success, output, answer, error = state['result']+ job = state['job']+ job['execution_id'] = params['request_id']+ output_file = save_job_output(job['id'], output)+ content, _, silent, _, _ = _compose_run_delivery(+ job, success=success, error=error, final_response=answer, output_file=output_file)+ deliver = bool(content.strip()) and not silent and not (success and _is_cron_silence_response(content))+ if deliver:+ enqueue(params['request_id'], job, content, for_failure=not success)+ mark_job_run(job['id'], success, error, status='delivery_queued' if deliver else None,+ execution_id=params['request_id'])+ journal.unlink(missing_ok=True)+ except Exception:+ logging.getLogger(__name__).warning('Cron receipt recovery deferred: %s', journal, exc_info=True)diff --cc cron/scheduler_delivery.pyindex 6fec4111dc5,fae39081d23..2966f747e56--- a/cron/scheduler_delivery.py+++ b/cron/scheduler_delivery.py@@@ -648,13 -688,96 +685,33 @@@ def _resolve_single_delivery_targetreturn _home_target(platform_name, chat_id, home_provenance) if chat_id else None- def _deliver_to_bot_chat(job: dict, content: str, profile: str) -> Optional[str]:-def _get_bot_chat_delivery_timeout() -> int:- """Timeout for one bot-chat delivery turn (a full agent turn — minutes, not seconds).- ``cron.bot_chat_delivery_timeout_seconds``; default 600."""- try:- cfg = _sched.load_config()- value = int(cfg.get("cron", {}).get("bot_chat_delivery_timeout_seconds", 600))- return value if value > 0 else 600- except Exception:- return 600--+ def _get_standalone_send_timeout() -> int:+ """Wall-clock bound for one standalone-lane send (#115469).++ ``_send_to_platform``'s gateway-loop dispatch deliberately awaits its future with no+ timeout ("the adapter and outer _run_async bound the wait") — but on this lane the+ outer runner is a bare ``asyncio.run``, not ``model_tools._run_async``, so without a+ bound here a reconnecting transport pins the run (and the restart drain behind it)+ indefinitely. Mirrors the sibling lanes: live dispatch ``future.result(timeout=60)``,+ thread fallback ``result(timeout=30)``. ``cron.standalone_send_timeout_seconds``;+ default 60."""+ try:+ cfg = _sched.load_config()+ value = int(cfg.get("cron", {}).get("standalone_send_timeout_seconds", 60))+ return value if value > 0 else 60+ except Exception:+ return 60++-_BOT_CHAT_STDERR_TAIL = 500-# stdout is the model's answer; only a short tail is persisted (jobs.json / ledger).-_BOT_CHAT_STDOUT_TAIL = 200-_BOT_CHAT_BANNER_PREFIXES = ("Resumed session", "session_id:")---def _run_bot_chat_turn(argv: list, env: dict, report_path: str, timeout: float) -> subprocess.CompletedProcess:- """Run one ``hermes chat -Q`` delivery child; the cap bounds the TURN, not the process (#113608).-- The booking policy lives with the report contract (``quiet_single_query.run_reported_turn``):- this lane needs only the outcome, so a child that reported its turn gets the exit grace and is- then left to its linger; only a turn that never ends is killed.- """- from hermes_cli.quiet_single_query import run_reported_turn-- # The scheduler may sit in a directory that no longer exists (a kanban worker whose- # scratch workspace was reaped): a child inheriting that cwd dies at CLI startup- # (#102941). The target home is the one directory this lane has already verified.- # Decoding is the runner's platform policy: lossy everywhere (#105582), UTF-8 only on- # win32 (#115894), the locale codec on POSIX (#66566).- return run_reported_turn(argv, env=env, report_path=report_path, timeout=timeout,- cwd=env.get("HERMES_HOME") or None)---def _format_failure_streams(result) -> str:- """Exit code plus labeled, redacted stderr/stdout tails for a failed delivery turn.-- ``-Q`` reports the resume banner and ``session_id:`` while the response- rides stdout, so ``stderr or stdout`` discarded half the signal — and when- stderr is empty and stdout holds only the banner, the recorded error- carried zero diagnostics (#104056). The banner lines are dropped from the- stdout tail so what remains is the reason; the exit code is always named.- The text lands in ``last_delivery_error`` on disk, so it is scrubbed like- ``cron.incidents`` / ``cron.delivery_queue`` scrub their persisted errors.- """- from agent.redact import redact_sensitive_text-- err = (getattr(result, "stderr", None) or "").strip()- out = (getattr(result, "stdout", None) or "").strip()- parts = [f"exit code {getattr(result, 'returncode', '?')}"]- if err:- parts.append(f"stderr: {err[-_BOT_CHAT_STDERR_TAIL:]}")- if out:- kept = "\n".join(- line for line in out.splitlines()- if line.strip() and not line.strip().lstrip("↻ ").startswith(_BOT_CHAT_BANNER_PREFIXES))- parts.append(- f"stdout: {kept[-_BOT_CHAT_STDOUT_TAIL:]}" if kept- else "stdout was only the resume banner")- return redact_sensitive_text(" | ".join(parts), force=True, redact_url_credentials=True)---def _deliver_to_bot_chat(job: dict, content: str, profile: str, *, deferred: Optional[dict] = None,++def _deliver_to_bot_chat(job: dict, content: str, profile: str, *,+ for_failure: bool = False) -> Optional[str]:- """Hand output to the live Bot Chat owner, or use the legacy unowned CLI lane.+ """Admit job output to the target profile's authority as a real inbound Bot Chat turn.- None means the target's durable receipt is settled; anything else is an explicit- unverified status string so Optional[str] callers cannot misreport admission as- delivery. ``profile`` is ``""`` for the job's own profile. There is no second-writer- fallback: without a running authority the payload stays unverified for retry.- None means completed; a queued/claimed receipt returns an explicit unverified status- string so existing Optional[str] callers cannot misreport admission as delivery.- ``profile`` is ``""`` for the job's own profile. A ``for_failure`` notice whose target- profile hides warning notifications is recorded as ``suppressed`` (a durable- disposition, never a send) and flagged on the job.++ None means the target's durable receipt is settled (or a failure notice was recorded as++ ``suppressed`` — a durable disposition, never a send — and flagged on the job); anything++ else is an explicit unverified status string so Optional[str] callers cannot misreport++ admission as delivery. ``profile`` is ``""`` for the job's own profile. There is no++ second-writer fallback: without a running authority the payload stays unverified for retry."""import hashlibimport json@@@ -667,14 -791,29 +724,24 @@@job_id = job.get("id", "?")profile_label = profile or "(own)"- # Outward lane: this text becomes an inbound turn in another profile's Bot Chat — via the- # live owner, the CLI fallback, or a deferred record replayed later — so it gets the same- # fail-closed scrub as the chat message and the session mirror. Rebind ``content`` itself so- # the durable deferred record below also carries the scrubbed copy, not the raw output.++ # Outward lane: this text becomes an inbound turn in another profile's Bot Chat through the++ # live owner's durable admission record, so it gets the same fail-closed scrub as the chat++ # message and the session mirror. Rebind ``content`` itself so the admitted record carries++ # the scrubbed copy, not the raw output.+ content = _redact_cron_payload(content, "bot-chat payload")+ job_name = _redact_cron_payload(job.get("name", job_id), "job name")message = (- f'[Cronjob "{job.get("name", job_id)}" output — scheduled job, not the user. '- f"Review it, act on anything that needs action, and summarize "- f"for the chat.]\n\n{content}"+ f'[Cronjob "{job_name}" output — '+ f"scheduled job, not the user. Review it, act on anything that needs action, and "+ f"summarize for the chat.]\n\n{content}")try:source_home = get_hermes_home().resolve()- from pathlib import Path- home = (Path(deferred["home"]) if deferred is not None else- get_profile_dir(profile) if profile else source_home).resolve()- for_failure = for_failure or bool((deferred or {}).get("for_failure"))+ home = (get_profile_dir(profile) if profile else source_home).resolve()+ from gateway.warning_notifications import warning_notifications_enabled+ from hermes_cli.config_effective import load_user_config_effective+ suppress_notification = for_failure and not warning_notifications_enabled(+ BOT_CHAT_POLICY_PLATFORM, load_user_config_effective(home / "config.yaml"))- if deferred is not None and not (home / "state.db").is_file():- return f"bot-chat delivery target no longer exists: {home}; do not resend"# run_one_job/claim_fire attach the durable execution id before delivery. The# transient fallback supports direct helper callers, never deduping recurring# runs by their (potentially identical) output or previous last_run timestamp.@@@ -685,29 -824,170 +752,37 @@@[str(source_home), job_id, str(run_id), str(home)],ensure_ascii=False, separators=(",", ":"),).encode("utf-8")).hexdigest()- if deferred is not None:- key = deferred["id"]# Read BEFORE discovery: the previous owner may have exited after accepting.- # No receipt state, including ambiguous/failed, authorizes a CLI replay.receipt = read_delivery_result(home, key)- if receipt is None and not deferred:- from cron.bot_chat_delivery import defer, read_pending- from tools.bot_live_delivery import find_canonical_owner-- pending = read_pending(key)- # Suppression is a durable disposition, not a send: record it under the producer- # lock even when a live owner exists, so the deferred lane never replays it.- if (pending is not None or suppress_notification- or (find_canonical_live_owner(home) is None and find_canonical_owner(home))):- pending = defer(key, dict(job), content, profile, home,- for_failure=for_failure, suppressed=suppress_notification)- if pending is not None:- status = pending["status"]- target = f"bot-chat:{profile_label}"- job.setdefault("_bot_chat_delivery_receipts", {})[target] = {- "status": status, "delivery_id": key}- if status == "suppressed":- job["_notification_all_targets_suppressed"] = True- return None if status in ("settled", "suppressed") else f"{target} {status} (receipt {key}): completion unverified; do not resend"++ target = f"bot-chat:{profile_label}"++ if receipt is None and suppress_notification:++ # Suppression is a durable disposition, not a send: the failure notice is booked++ # against the job and never handed to the owner (the target profile hides++ # warning notifications).++ job.setdefault("_bot_chat_delivery_receipts", {})[target] = {++ "status": "suppressed", "delivery_id": key}++ job["_notification_all_targets_suppressed"] = True++ return Noneif receipt is None:owner = find_canonical_live_owner(home)- if owner is not None:- receipt = deliver_to_live_owner(home, owner, message, delivery_id=key,- **({"notification_category": "diagnostic"} if for_failure else {}))- if receipt is not None:- if (receipt["message"] != message- or receipt.get("notification_category", "result") != ("diagnostic" if for_failure else "result")):- raise ValueError("delivery id already belongs to a different payload")- status = receipt["status"]- target = f"bot-chat:{profile_label}"- receipts = job.setdefault("_bot_chat_delivery_receipts", {})- receipts[target] = {"status": status, "delivery_id": key}- logger.info("Job '%s': Bot Chat %s receipt=%s status=%s",- job_id, profile_label, key, status)- if status == "settled":- return None- detail = ("completion unverified; do not resend" if status in ("queued", "claimed")- else receipt.get("error") or receipt.get("reason") or "not completed")- return f"{target} {status} (receipt {key}): {detail}"+ if owner is None:+ return f"bot-chat delivery to profile '{profile_label}' unverified: no canonical Bot Chat"+ receipt = deliver_to_live_owner(home, owner, message, delivery_id=key)+ if receipt["message"] != message:+ raise ValueError("delivery id already belongs to a different payload")+ status = receipt["status"]- target = f"bot-chat:{profile_label}"+ receipts = job.setdefault("_bot_chat_delivery_receipts", {})+ receipts[target] = {"status": status, "delivery_id": key}+ logger.info("Job '%s': Bot Chat %s receipt=%s status=%s",+ job_id, profile_label, key, status)+ if status == "settled":+ return None+ detail = ("completion unverified; do not resend" if status in ("queued", "claimed")+ else receipt.get("error") or receipt.get("reason") or "not completed")+ return f"{target} {status} (receipt {key}): {detail}"except Exception as exc:- # Discovery/admission uncertainty must never open a second-writer fallback.return f"bot-chat delivery to profile '{profile_label}' unverified: {exc}"- # The running install first (same trust order as gateway.run._resolve_hermes_bin): the- # scheduler lives in the long-running gateway, so a PATH-first lookup would hand delivery- # to whatever `hermes` PATH names — another install, or a planted one — instead of this one.- try:- import importlib.util as _ilu- found = _ilu.find_spec("hermes_cli") is not None- except Exception:- found = False- if found:- argv = [sys.executable, "-m", "hermes_cli.main"]- else:- hermes_bin = shutil.which("hermes")- if not hermes_bin:- return ("Hermes could not deliver this result to Bot Chat: the `hermes` command was not found. "- "The result is saved; run `hermes cron runs` to see it, or `hermes doctor` if this keeps happening")- argv = [hermes_bin]-- def _fail(msg: str, **log_kwargs) -> str:- logger.warning("Job '%s': %s", job_id, msg, **log_kwargs)- return msg-- from agent.delegation_context import delegated_child_subprocess_env- from tools.environments.local import served_profile_child_env- if not home.is_dir():- return _fail(f"bot-chat delivery target no longer exists: {home}; do not resend")- # Built for ``home``, the DELIVERY TARGET — the only cron child that acts for a profile other- # than the one whose tick spawned it, so the launch residue cannot be resolved from the ambient- # override the way every other lane resolves it. Discovery (or deferred admission) owns the- # destination, not HOME or a subsequently changed active_profile: do not resolve it again.- # ``inherit_credentials``: the child runs a full agent turn as that profile, on its own secrets.- try:- env = served_profile_child_env(- delegated_child_subprocess_env(os.environ), target_home=home, inherit_credentials=True)- except Exception as exc: # unreadable target home / secret source: refuse, never fall back- return _fail(f"bot-chat delivery to profile '{profile_label}' could not build the target "- f"profile's environment ({type(exc).__name__}: {exc}); do not resend")- if home.parent.name != "profiles":- argv += ["-p", "default"]-- query_file = None- try:- with tempfile.NamedTemporaryFile(- "w", encoding="utf-8", suffix=".txt", prefix="hermes-cron-botchat-", delete=False,- ) as fh:- fh.write(message)- query_file = fh.name-- argv += [- "chat", "--in", "~", "-c", "Bot Chat", "--create-if-missing",- "-Q", "--query-file", query_file,- ]- from hermes_cli.quiet_single_query import TURN_REPORT_FILE_ENV- report_file = f"{query_file}.turn.json"- env[TURN_REPORT_FILE_ENV] = report_file- timeout_s = _get_bot_chat_delivery_timeout()- result = _run_bot_chat_turn(argv, env, report_file, timeout_s)- if result.returncode != 0:- tail = _format_failure_streams(result)- logger.warning(- "Job '%s': bot-chat delivery to profile '%s' failed at %s: %s",- job_id, profile_label, home, tail)- return (- f"Hermes could not deliver this result to Bot Chat (profile '{profile_label}'). "- "The result is saved; run `hermes cron runs` to see it, or `hermes doctor` if this keeps happening"- f". Details: {tail}")- logger.info("Job '%s': delivered to Bot Chat of profile '%s'", job_id, profile_label)- return None- except subprocess.TimeoutExpired:- # Replaying the full payload risks a duplicate (the killed turn may already have- # persisted it); staying silent loses the alert entirely (2026-09-19 docgen-deadman- # case). So queue a SHORT marker that points at the saved output, once per execution- # (stable key); the re-mark guard reads the record's ``degraded`` flag, never the text.- marker_queued = False- if not (deferred or {}).get("degraded"):- marker = (- f"DELIVERY DEGRADED: this alert's bot-chat turn timed out after "- f"{timeout_s}s, so the full output could NOT be posted here. Read the "- f"complete saved output with `hermes cron runs` (job '{job_id}'). "- f"Excerpt: {content.strip()[:280]}"- )- try:- from cron.bot_chat_delivery import defer as _defer_marker- # Deferred ids double as live-owner delivery ids, which must be 32-64 hex- # chars (tools.bot_live_delivery._delivery_id) — so the marker's id is a- # fresh digest derived from the execution key, not a suffixed one.- marker_key = hashlib.sha256(f"{key}:degraded".encode("utf-8")).hexdigest()- _defer_marker(marker_key, dict(job), marker, profile, home,- for_failure=for_failure, degraded=True)- marker_queued = True- except Exception as defer_exc:- logger.warning(- "Job '%s': degraded-delivery marker could not be queued: %s",- job_id, defer_exc)- hint = (- "a short degraded-delivery notice was queued to Bot Chat — posted once the "- f"session frees; full output stays saved, run `hermes cron runs` for job '{job_id}'"- if marker_queued else- "the result is saved; run `hermes cron runs` to see it, or `hermes doctor` "- "if this keeps happening")- return _fail(- f"bot-chat delivery to profile '{profile_label}' timed out "- f"after {timeout_s}s ({hint}; raise "- "cron.bot_chat_delivery_timeout_seconds if this recurs)")- except Exception as e:- logger.warning(- "Job '%s': bot-chat delivery to profile '%s' failed: %s", job_id, profile_label,- str(e) or type(e).__name__, exc_info=True)- return (- f"Hermes could not deliver this result to Bot Chat (profile '{profile_label}'). "- "The result is saved; run `hermes cron runs` to see it, or `hermes doctor` if this keeps happening")- finally:- if query_file:- for path in (query_file, f"{query_file}.turn.json"):- with contextlib.suppress(OSError):- os.unlink(path)-def _normalize_deliver_value(deliver) -> str:"""Normalize ``deliver`` to its canonical comma-separated string; ``"local"`` when falsy.diff --cc cron/scheduler_tick.pyindex 00000000000,3afd054d671..a3e4a8cb27emode 000000,100644..100644--- a/cron/scheduler_tick.py+++ b/cron/scheduler_tick.py@@@ -1,0 -1,121 +1,126 @@@+ """In-process tick admission and dispatch; job execution stays in scheduler.py."""++ import concurrent.futures+ import contextlib++-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+ # prepare after the check but before a due job enters the running-job ledger.+ 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 _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+ # serves mixed sys.modules (jobs die on ImportErrors); if a fresher gateway holds the runtime+ # lock, ITS ticker dispatches. With no fresh holder (desktop-standalone) the tick proceeds.+ _skew = _sched._should_yield_tick_to_fresh_gateway()+ if _skew is not None:+ _sched._log_tick_yield_once(f"boot={_skew[0]} disk={_skew[1]}")+ raise _sched.CronTickYielded(_skew[0], _skew[1])++ lock_dir, lock_file = _sched._get_lock_paths()+ _sched._ensure_cron_dir(lock_dir)+ lock_fd = _sched._acquire_tick_lock(lock_file)+ if lock_fd is None:+ return 0++ try:+ # `hermes pause` ESTOP: skip dispatch, never touch in-flight runs; check_paused logs once.+ with contextlib.suppress(ImportError):+ from agent.estop import check_paused as _estop_check_paused+ if _estop_check_paused("cron", _sched.logger):+ return 0++ if can_dispatch is not None and not can_dispatch():+ _sched.logger.debug("Cron dispatch paused while gateway drains existing work")+ return 0+- from cron.bot_chat_delivery import drain, drain_in_background- if sync:- drain()- else:- drain_in_background()++ from cron.scheduler_authority import reconcile_pending++ reconcile_pending()+ _sched._maybe_reap_dead_owners()+ # Periodic worktree GC (6h, threaded) — the only sweep gateway-only boxes get.+ try:+ _sched._maybe_run_worktree_maintenance()+ except Exception as _wt_exc:+ _sched.logger.debug("Worktree maintenance dispatch failed: %s", _wt_exc)++ due_jobs = _sched.get_due_jobs()+ _sched._sweep_stale_inflight_for_tick(due_jobs)++ if headless:++ from cron.scheduler_gateway_gate import refuse_agent_jobs_without_gateway++ due_jobs = refuse_agent_jobs_without_gateway(due_jobs)++ if not due_jobs:+ # Idle tick: skip config load + pool setup, but still reap crashed jobs' MCP orphans.+ if verbose:+ # Idle tick: skip config load + pool partitioning entirely (#33612 — the gateway ticker+ # calls tick(verbose=False) every 60s, so idle ticks previously fell through to+ # load_config()). Still run the post-tick MCP orphan sweep: main intentionally sweeps on+ # idle ticks so orphaned stdio children from crashed jobs are reaped even when nothing is+ # due.+ _sched.logger.info("%s - No jobs due", _sched._hermes_now().strftime('%H:%M:%S'))+ _sched._sweep_mcp_orphans()+ return 0++ if verbose:+ _sched.logger.info("%s - %s job(s) due", _sched._hermes_now().strftime('%H:%M:%S'), len(due_jobs))++ # Advance next_run_at for recurring jobs FIRST, under the lock, before any execution+ # (at-most-once). Re-advancing running jobs keeps the grace window alive; mark_job_run+ # overwrites it on completion. Composes with the claim-time advance in claim_job_for_fire.+ _sched.advance_next_runs([job["id"] for job in due_jobs])++ _max_workers = _sched._resolve_max_parallel_workers()+ if verbose:+ _sched.logger.info(+ "Running %d job(s) in parallel (max_workers=%s)",+ len(due_jobs),+ _max_workers if _max_workers else "unbounded")++ def _process_job(job: dict) -> bool:+ return _sched._process_due_job(job, adapters, loop, verbose)++ # Persistent pool, non-blocking dispatch. Already-running jobs are skipped; mark_job_run+ # re-arms next_run_at on completion, so no catch-up queue is needed.+ _results: list = []+ _all_futures: list = []+ pool = _sched._get_parallel_pool(_max_workers)+ for job in due_jobs:+ fut = _sched._submit_with_guard(job, pool, _process_job)+ if fut is None:+ continue+ _all_futures.append(fut)+ if not sync:+ _results.append(True) # optimistically counted++ if sync:+ for f in concurrent.futures.as_completed(_all_futures):+ try:+ _results.append(f.result())+ except Exception as exc:+ _sched.logger.error("Cron job future failed: %s", exc)+ _results.append(False)+ _sched._sweep_mcp_orphans()+ return sum(_results)++ _sched._sweep_mcp_orphans_when_all_done(_all_futures)+ return sum(_results)+ finally:+ _sched._release_tick_lock(lock_fd)diff --cc gateway/control_socket.pyindex 2b6dad8f1bc,0230e6f9b33..9be732b4a0c--- a/gateway/control_socket.py+++ b/gateway/control_socket.py@@@ -55,8 -53,8 +55,8 @@@ def _fallback_socket_path(home: Path) -"""Short temp-dir path for homes whose direct socket path exceeds sun_path: ``tempfile.gettempdir()``then ``/tmp`` (POSIX); if nothing fits the tempdir candidate is returned anyway — bind failsnon-fatally and consumers use the scan layer."""- name = f"hermes-gw-{_home_hash(home)}.sock"+ name = f"hermes-gw-{_home_hash(home)}/control.sock"- candidates = [Path(tempfile.gettempdir()) / name] + ([] if _IS_WINDOWS else [Path("/tmp") / name])+ candidates = [Path(tempfile.gettempdir()) / name] + ([] if _IS_WINDOWS else [Path("/tmp") / name]) # no-tmp: ok — AF_UNIX 104-byte path limit needs the short /tmp candidatereturn next((c for c in candidates if _fits_sun_path(c)), candidates[0])diff --cc gateway/platforms/api_server.pyindex 95f809fb55e,4ea5a6eef73..a51c830af9a--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@@ -3146,9 -3191,127 +3213,135 @@@ class APIServerAdapter(OpenAICompatRoutreturn ""return "confirmed" if runtime else "accepted"+ async def _admit_to_live_bot_chat(+ self, session_id: str, message: Any, author: Optional[Dict[str, Any]],+ ) -> Optional[Tuple[Path, Dict[str, Any]]]:+ """Admit a turn aimed at the canonical Bot Chat to the Desktop session that holds it live.++ ``(profile home, mailbox record)`` when a live owner took it; None when this process should+ run the turn itself — the session is not the canonical Bot Chat's own lineage, or nobody+ holds that chat. Both peer transports (``/api/sessions/{id}/chat`` for ``peer dm``,+ ``/v1/runs`` for ``peer run``) go through here, so the two lanes cannot drift.+ """+ if not isinstance(message, str):+ return None++ # Under session authority the canonical FIFO is the single writer for every session,++ # so a peer turn is admitted there (``run_api_turn``) rather than handed to a lease holder.++ if getattr(self.gateway_runner, "session_authority", None) is not None:++ return None+ db = await self._ensure_session_db_async()+ if db is None:+ return None+ home = Path(db.db_path).parent+ from tools.bot_live_delivery import deliver_to_live_owner, find_canonical_live_owner++ def _admit() -> Optional[Dict[str, Any]]:- owner = find_canonical_live_owner(home)++ try:++ owner = find_canonical_live_owner(home)++ except ValueError:++ # No reachable profile authority to hand the chat to: this process runs the turn.++ return None+ # Only the canonical Bot Chat's own lineage: a peer turn into any other session runs here.+ if owner is None or db.get_compression_tip(session_id) != owner["session_id"]:+ return None+ return deliver_to_live_owner(home, owner, message, author=author)++ record = await asyncio.to_thread(_admit)+ return None if record is None else (home, record)++ async def _answer_through_live_bot_chat(self, ctx: Dict[str, Any]) -> Optional["web.Response"]:+ """Hand a turn aimed at a canonical Bot Chat that a Desktop holds live to that owner.++ This is the ``hermes peer dm`` transport. Running the turn here would make this process a+ second writer beside the lease holder: the open chat never shows the message or the reply,+ its live context never learns of them, and the two transcripts interleave in state.db.+ Local and relayed DMs already hand such a message to the owner's mailbox+ (``tools/bot_mode_dm.py``, ``tui_gateway/methods_bot_relay.py``). This waits for the owner's+ receipt on the same budget as the local path, so the peer still gets the reply on this call.+ """+ session_id = ctx["session_id"]+ admitted = await self._admit_to_live_bot_chat(session_id, ctx["user_message"], ctx["run_kwargs"]["turn_author"])+ if admitted is None:+ return None+ record = await self._await_live_bot_chat_receipt(*admitted)+ delivery_id = record["delivery_id"]+ headers = self._session_headers(session_id, ctx["gateway_session_key"])+ if record["status"] == "settled":+ return web.json_response(+ {"object": "hermes.session.chat.completion", "session_id": session_id,+ "message": {"role": "assistant", "content": record.get("reply") or ""},+ "usage": {}, "runtime": {}, "delivery_id": delivery_id}, headers=headers)+ if record["status"] in ("queued", "claimed"):+ return web.json_response(+ {"object": "hermes.session.chat.queued", "session_id": session_id,+ "status": record["status"], "delivery_id": delivery_id}, status=202, headers=headers)+ return _error_response(record.get("error") or f"Bot Chat delivery {record['status']}", 502,+ code=record.get("reason") or record["status"], headers=headers)++ async def _await_live_bot_chat_receipt(self, home: Path, record: Dict[str, Any], *, keepalive=None) -> Dict[str, Any]:+ """Wait on the owner's mailbox record through the shared ``await_delivery_async`` primitive until it+ settles or the local DM budget runs out; ``keepalive`` (async) is called every SSE keepalive interval+ so a streaming caller's proxy keeps the socket."""+ from tools.bot_live_delivery import await_delivery_async+ from tools.bot_mode_dm import _LIVE_WAIT_SECONDS+ delivery_id = record["delivery_id"]+ deadline = time.monotonic() + _LIVE_WAIT_SECONDS+ while record["status"] in ("queued", "claimed"):+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ break+ budget = remaining if keepalive is None else min(remaining, CHAT_COMPLETIONS_SSE_KEEPALIVE_SECONDS)+ record = await await_delivery_async(home, delivery_id, budget) or record+ if keepalive is not None and record["status"] in ("queued", "claimed"):+ await keepalive()+ return record++ async def _stream_through_live_bot_chat(self, request: "web.Request", ctx: Dict[str, Any]) -> Optional["web.StreamResponse"]:+ """``_answer_through_live_bot_chat`` for the SSE sibling route: the owner's settled receipt is+ the run's single ``assistant.completed`` event; a receipt still open at the budget is a+ ``run.queued`` event (the 202 shape), a failed one an ``error`` event carrying the reason."""+ session_id = ctx["session_id"]+ admitted = await self._admit_to_live_bot_chat(session_id, ctx["user_message"], ctx["run_kwargs"]["turn_author"])+ if admitted is None:+ return None+ events = _SessionEventQueue(session_id, f"run_{uuid.uuid4().hex}")+ response = web.StreamResponse(status=200, headers={+ "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "X-Accel-Buffering": "no",+ **self._session_headers(session_id, ctx["gateway_session_key"])})+ await response.prepare(request)++ async def _write(name: str, payload: Dict[str, Any]) -> None:+ name, payload = events.payload(name, payload)+ await response.write(_sse_frame(payload, event=name, ensure_ascii=False))++ async def _keepalive() -> None:+ await response.write(b": keepalive\n\n")++ try:+ await _write("run.started", {"user_message": {"role": "user", "content": ctx["user_message"]}, "runtime": {}})+ record = await self._await_live_bot_chat_receipt(*admitted, keepalive=_keepalive)+ delivery_id = record["delivery_id"]+ if record["status"] == "settled":+ message_id = f"msg_{uuid.uuid4().hex}"+ await _write("message.started", {"message": {"id": message_id, "role": "assistant"}})+ await _write("assistant.completed", {+ "message_id": message_id, "content": record.get("reply") or "", "delivery_id": delivery_id, "runtime": {}})+ await _write("run.completed", {"message_id": message_id, "delivery_id": delivery_id, "usage": {}, "runtime": {}})+ elif record["status"] in ("queued", "claimed"):+ await _write("run.queued", {"status": record["status"], "delivery_id": delivery_id})+ else:+ await _write("error", {"message": record.get("error") or f"Bot Chat delivery {record['status']}",+ "code": record.get("reason") or record["status"], "delivery_id": delivery_id})+ await _write("done", {})+ except (ConnectionResetError, ConnectionAbortedError, BrokenPipeError, OSError):+ logger.info("Session SSE client disconnected while a live Bot Chat held the turn")+ return response+@_admit_api_agent_requestasync def _handle_session_chat(self, request: "web.Request") -> "web.Response":- """POST /api/sessions/{session_id}/chat — one synchronous agent turn."""+ """POST /api/sessions/{session_id}/chat — one synchronous agent turn (plus the delivery lanes'+ one bounded re-run of a transient failure; ``hermes peer dm`` is the client)."""+ from tools.bot_failure_reasons import RETRY_NONE, result_retry_action# This turn runs through _run_agent, so it already COUNTS toward the cap (#7483).# Spending the budget without checking it refused every other caller while never# refusing this route — and a fleet's cross-machine DMs all arrive here.@@@ -3158,7 -3321,9 +3351,10 @@@ctx, err = await self._prepare_session_chat(request)if err is not None:return err+ from gateway.platforms.api_server_openai_routes import _response_status+ handed_off = await self._answer_through_live_bot_chat(ctx)+ if handed_off is not None:+ return handed_offgateway_session_key = ctx["gateway_session_key"]session_id = ctx["session_id"]history = await self._conversation_history_for_session(session_id)@@@ -3725,9 -3920,9 +3951,10 @@@route: Optional[Dict[str, Any]] = None, session_model: Optional[str] = None,requested_runtime: Optional[Dict[str, Any]] = None, route_source: str = "global",confirmed_runtime_lock: bool = False, bind_declared_conversation: bool = False,+ request_id: Optional[str] = None, history_from_session: bool = False,session_history_delivery: str = "", turn_author: Optional[Dict[str, Any]] = None,- relay_metadata: Optional[Dict[str, Any]] = None) -> tuple:+ relay_metadata: Optional[Dict[str, Any]] = None, notification_category: str = "result",+ resume_unanswered_turn: bool = False) -> tuple:"""Create an agent and run one turn in a thread executor -> ``(result, usage)``.``agent_ref[0]`` receives the agent so SSE writers can interrupt it; ``active_run_id``registers it in ``_active_run_agents``. Under a confirmed model lock the actual@@@ -3735,20 -3930,11 +3962,24 @@@``session_history_delivery`` declares #98619 session-id provenance and default-denies: only auditedproducers whose client can address the id again pass "1" (see``_bind_api_server_session``).- ``turn_author`` only labels the turn for memory attribution. It grants nothing."""+ ``turn_author`` only labels the turn for memory attribution. It grants nothing.+ ``resume_unanswered_turn`` marks a policy-gated re-run of a turn whose user row the failed attempt+ already persisted: the transcript's unanswered tail row is adopted from ``conversation_history``+ as THIS turn's user message instead of being appended a second time+ (``agent.session_persistence.adopt_unanswered_turn``; #115325)."""+ if getattr(self.gateway_runner, "session_authority", None) is not None:+ from gateway.session_api_turn import run_api_turn+ return await run_api_turn(self, user_message=user_message, conversation_history=conversation_history,+ ephemeral_system_prompt=ephemeral_system_prompt, session_id=session_id,+ stream_delta_callback=stream_delta_callback, tool_progress_callback=tool_progress_callback,+ tool_start_callback=tool_start_callback, tool_complete_callback=tool_complete_callback,+ agent_ref=agent_ref, active_run_id=active_run_id, gateway_session_key=gateway_session_key,+ requested_model=requested_model, requested_provider=requested_provider, model_options=model_options,+ route=route, session_model=session_model, requested_runtime=requested_runtime,+ route_source=route_source, confirmed_runtime_lock=confirmed_runtime_lock,+ bind_declared_conversation=bind_declared_conversation, request_id=request_id,+ history_from_session=history_from_session, session_history_delivery=session_history_delivery,- turn_author=turn_author)++ turn_author=turn_author, resume_unanswered_turn=resume_unanswered_turn)loop = asyncio.get_running_loop()# ContextVars do not follow run_in_executor threads: capture here, re-enter in _run().request_profile = _api_request_profile.get()diff --cc gateway/platforms/api_server_openai_routes.pyindex b0eda4a5a64,0a261a2fd49..c06f419b3bc--- a/gateway/platforms/api_server_openai_routes.py+++ b/gateway/platforms/api_server_openai_routes.py@@@ -370,14 -498,12 +514,15 @@@ class _ResponsesStreamself.terminal_snapshot_persisted = Trueawait self.write_event("response.failed", {"type": "response.failed", "response": env})- async def emit_completed(self) -> None:- env = self.terminal_envelope("completed", self._final_items())+ async def emit_completed(self) -> Dict[str, Any]:result = self.result+ status = _response_status(result)+ env = self.terminal_envelope(status, self._final_items(),+ error=self._api._redact_api_error_text(result.get('error') or 'The admitted turn failed.')+ if status == 'failed' else None)full_history = self.adapter._build_response_conversation_history(- self.conversation_history, self.user_message, result, self.final_response_text)+ self.conversation_history, self.user_message, result, self.final_response_text,+ tool_output_max_chars=self.adapter._history_tool_output_max_chars)# Transcript substitution for result["_compressed"] happens in the history builder; only# a compression-rotated session_id is propagated so chaining resumes the child session.sid = result.get("session_id") if isinstance(result, dict) else None@@@ -531,13 -670,10 +690,17 @@@ class OpenAICompatRoutesMixin# id from a header-less client is NOT: delegate_task keeps its forced-sync fallback# there — the wake would hard-fail or land in history that client never reloads.session_history_delivery=("1" if provided_session_id else ""))+ if getattr(self.gateway_runner, 'session_authority', None) is not None:+ key = request.headers.get('Idempotency-Key')+ # The durable admission identity carries the authenticated namespace: a rotated+ # API key (or another profile) reusing a client key is a new principal, not a retry.+ run_kwargs.update(+ request_id=f'chat:{self._run_idempotency_scope(request)}:{key}' if key else None,+ history_from_session=bool(provided_session_id))+ # This is presentation only. The ordinary API-key/session authorization+ # above still applies; it grants no internal ingress or control authority.+ if provided_session_id and body.get("hermes_notification_category") == "diagnostic":+ run_kwargs["notification_category"] = "diagnostic"if stream:_stream_q = ThreadSafeAsyncQueue()# tool_call_ids with an emitted "running": a "completed" without one (internal/@@@ -652,12 -791,10 +821,13 @@@else:result, usage = await compute()return (result, usage), None+ except RuntimeStoreError as exc:+ from gateway.platforms.api_server import _openai_error+ return None, web.json_response(_openai_error(exc.reason, code=exc.reason), status=409)except Exception as e:logger.error("Error running agent for %s: %s", log_label, e, exc_info=True)- return None, _error_response(f"Internal server error: {e}", 500, err_type="server_error")+ message = "" if getattr(e, "_notification_presentation_suppressed", False) is True else f"Internal server error: {e}"+ return None, _error_response(message, 500, err_type="server_error")async def _prepare_sse_response(self, request: "web.Request", session_id: Optional[str], gateway_session_key: Optional[str],@@@ -746,11 -893,10 +926,12 @@@"""Write the SSE stream for POST /v1/responses.Events: ``response.created`` -> ``output_text.delta/done`` + ``output_item.added/done``- (function_call / function_call_output) -> ``response.completed`` (non-streaming envelope)+ (reasoning / function_call / function_call_output) + ``reasoning_summary_part/text.*``+ -> ``response.completed`` (non-streaming envelope)or ``response.failed``. On disconnect the agent is interrupted and, with ``store=True``,an ``incomplete`` snapshot replaces ``in_progress`` so GET / chaining still work.+ ``durable_key`` (canonical Idempotency-Key record) is written only once the admitted turn+ settled, so an exact retry replays this stream instead of admitting different history."""from gateway.platforms.api_server import _abandon_agent_task, _redact_api_error_textresponse = await self._prepare_sse_response(request, session_id, gateway_session_key)@@@ -929,8 -1034,9 +1114,8 @@@_declared_selected = not stored_session_id and bool(gateway_session_key)session_id = (stored_session_id- or self._declared_conversation_session(gateway_session_key)+ or await asyncio.to_thread(self._declared_conversation_session, gateway_session_key)or str(uuid.uuid4()))- stream = _coerce_request_bool(body.get("stream"), default=False)route, agent_overrides, selection_error = self._select_request_route(body, session_id=session_id, gateway_session_key=gateway_session_key,model_alias=body.get("model"))diff --cc gateway/platforms/api_server_runs.pyindex d50ea0450e6,f018926c39c..9257bb9442f--- a/gateway/platforms/api_server_runs.py+++ b/gateway/platforms/api_server_runs.py@@@ -37,20 -82,17 +82,22 @@@ _SUBAGENT_EVENT_KEYS ="output_tokens", "reasoning_tokens", "api_calls", "cost_usd", "files_read", "files_written","output_tail")_SUBAGENT_TEXT_KEYS = ("goal", "summary", "output_tail")- # Terminal usage payload: (wire key, agent attribute), in wire order.+ # Terminal usage payload: (wire key, agent attribute), in wire order. Cache reads ride along so a+ # cost poller does not book them as full-price input (#102101)._USAGE_FIELDS = (("input_tokens", "session_prompt_tokens"), ("output_tokens", "session_completion_tokens"),- ("total_tokens", "session_total_tokens"))+ ("total_tokens", "session_total_tokens"), ("cache_read_tokens", "session_cache_read_tokens"),+ ("cache_write_tokens", "session_cache_write_tokens"))# Tool-progress event -> SSE payload fields (tool_name, preview, kwargs); key order is wire format.+def _call_id(kw: Dict[str, Any]) -> Dict[str, Any]:+ return {"tool_call_id": kw["tool_call_id"]} if kw.get("tool_call_id") else {}++_FIXED_EVENT_FIELDS = {- "tool.started": lambda tool, preview, kw: {"tool": tool, "preview": preview},+ "tool.started": lambda tool, preview, kw: {"tool": tool, "preview": preview, **_call_id(kw)},"tool.completed": lambda tool, preview, kw: {- "tool": tool, "duration": round(kw.get("duration", 0), 3), "error": kw.get("is_error", False)},+ "tool": tool, "duration": round(kw.get("duration", 0), 3), "error": kw.get("is_error", False),+ **_call_id(kw)},"reasoning.available": lambda tool, preview, kw: {"text": preview or ""}}_TOOL_COMPLETED_PREVIEW_MAX_CHARS = 500@@@ -126,12 -168,15 +173,14 @@@ def _initialize_run_state(self, *, storself._run_owner_started = int(get_process_start_time(self._run_owner_pid) or 0)except Exception:self._run_owner_started = 0- # All keyed by run_id: SSE queues (+creation time for the TTL sweep), connected- # subscribers, live agent/task refs for cooperative stop (the executor thread may- # outlive the request, hence the separate stopping set), pollable statuses, and- # approval session keys (approval core resolves by session key, clients by run_id).+ # All keyed by run_id: SSE fanout streams (+creation time for the TTL sweep), live+ # agent/task refs for cooperative stop (the executor thread may outlive the request,+ # hence the separate stopping set), pollable statuses, and approval session keys+ # (approval core resolves by session key, clients by run_id).self._run_idempotency_ids: set[str] = set()- self._run_stream_subscribers: set[str] = set()self._stopping_run_ids: set[str] = set()+ self._shutdown_interrupted_run_ids: set[str] = set()+ self._run_shutdown_requested_at: Optional[float] = None(self._run_owners, self._run_streams, self._run_streams_created, self._active_run_agents,self._active_run_tasks, self._run_statuses, self._run_approval_sessions,@@@ -577,30 -686,16 +726,38 @@@ async def _handle_runs(self, request: "browser_control_principal=_api_server._api_request_browser_control_principal.get(),browser_control_transport_family=_api_server._api_request_browser_control_transport_family.get(),turn_author=turn_author)+ if getattr(self.gateway_runner, 'session_authority', None) is not None:+ from gateway.session_api_turn import admit_api_turn+ from hermes_state_runtime import RuntimeStoreError+ try:+ with self._profile_scope(launch.request_profile):+ launch.admission = admit_api_turn(self, user_message=launch.user_message,+ conversation_history=launch.conversation_history, active_run_id=run_id,+ run_owner_scope=self._run_owners[run_id],+ turn_author=launch.turn_author,+ history_from_session=session_history_delivery,+ session_history_delivery='1' if session_history_delivery else '',+ bind_declared_conversation=_declared_selected,+ **launch.agent_kwargs)+ except RuntimeStoreError as exc:+ # A refused admission owns no run: drop every reservation so an exact+ # retry is refused again instead of replaying a run nobody executes.+ _forget_run(+ self, run_id, self._run_streams, self._run_streams_created, self._run_approval_sessions,+ self._run_statuses, self._run_owners, self._run_idempotency_ids)+ if idempotency_key:+ self._run_idempotency_store.forget(idempotency_scope, idempotency_key)+ return _json_error(_openai_error, exc.reason, code=exc.reason, status=409)self._activate_admitted_request()- task = self._active_run_tasks[run_id] = asyncio.create_task(_execute_run(self, launch, _api_server=_api_server))+ # A canonical Bot Chat that a Desktop holds live is that Desktop's to run: executing here would+ # be a second writer beside its lease (#114959). The owner's mailbox takes the turn and its+ # receipt drives this run's status, so `peer run` keeps its run_id and `peer status` still works.+ admitted = await self._admit_to_live_bot_chat(session_id, user_message, turn_author) if selected_session_id else None+ if admitted is not None:+ task = self._active_run_tasks[run_id] = asyncio.create_task(+ _execute_run_via_live_owner(self, launch, *admitted, _api_server=_api_server))+ else:+ task = self._active_run_tasks[run_id] = asyncio.create_task(_execute_run(self, launch, _api_server=_api_server))with suppress(TypeError):self._background_tasks.add(task) # tracked for shutdown drainif hasattr(task, "add_done_callback"):@@@ -723,42 -910,16 +972,46 @@@ async def _execute_run(self, run: _RunLif run_id in self._stopping_run_ids:_finish("cancelled")return- with self._profile_scope(run.request_profile):- agent = self._create_agent(- stream_delta_callback=_text_cb, tool_progress_callback=self._make_run_event_callback(run_id, loop),- interim_assistant_callback=_interim_cb, **run.agent_kwargs)- self._active_run_agents[run_id] = agent- approval_notify = _make_approval_notify(self, run, _api_server=_api_server)- result, usage, served_runtime = await _submit_api_worker(- loop, lambda: _run_agent_sync(self, run, agent, approval_notify, _api_server=_api_server))+ if run.admission is not None:+ from gateway.session_api_turn import observe_api_controls, observe_api_turn+ tool_cb = self._make_run_event_callback(run_id, loop)++ def _control_cb(event_type, prompt):+ # Same authority prompt the WS viewer and GET pending_controls expose, on the+ # run's own stream so a streaming-only client learns it must respond.+ with suppress(Exception):+ loop.call_soon_threadsafe(run.put_event, _run_event(run_id, event_type, **prompt))++ def _tool_start(call_id, name, args):+ from agent.display import build_tool_preview+ tool_cb("tool.started", name, build_tool_preview(name, args or {}) or "", args, tool_call_id=call_id)++ def _tool_complete(call_id, name, args, result):+ from agent.display import _detect_tool_failure+ is_error, _ = _detect_tool_failure(name, result)+ tool_cb("tool.completed", name, None, args, tool_call_id=call_id, is_error=bool(is_error))++ with observe_api_controls(run.admission, _control_cb):+ result, usage = await observe_api_turn(+ run.admission, stream_delta_callback=_text_cb,+ tool_start_callback=_tool_start, tool_complete_callback=_tool_complete)++ # The canonical turn has no agent object here; the served pair rides on the++ # committed usage/result runtime metadata when the turn recorded one.++ served_runtime = ((usage or {}).get("runtime") if isinstance(usage, dict) else None) or (++ result.get("runtime") if isinstance(result, dict) else None) or {}+ else:+ with self._profile_scope(run.request_profile):+ agent = self._create_agent(+ stream_delta_callback=_text_cb, tool_progress_callback=self._make_run_event_callback(run_id, loop),- **run.agent_kwargs)++ interim_assistant_callback=_interim_cb, **run.agent_kwargs)+ self._active_run_agents[run_id] = agent+ approval_notify = _make_approval_notify(self, run, _api_server=_api_server)- result, usage = await loop.run_in_executor(- None, lambda: _run_agent_sync(self, run, agent, approval_notify, _api_server=_api_server))++ result, usage, served_runtime = await _submit_api_worker(++ loop, lambda: _run_agent_sync(self, run, agent, approval_notify, _api_server=_api_server))if not isinstance(result, dict):result = {}+ # The committed outcome decides: a stop issued over WS by another viewer interrupts+ # this run just as much as one issued through this adapter's own /stop.status, fields = terminal_run_status(result)if status == "cancelled":_finish("cancelled", fields)diff --cc gateway/platforms/webhook.pyindex e23e0426c3f,8f361e725f1..868dbe4c85a--- a/gateway/platforms/webhook.py+++ b/gateway/platforms/webhook.py@@@ -17,10 -17,8 +17,9 @@@ import logginimport osimport reimport subprocess- import sysimport timefrom collections import deque+from datetime import datetime, timezonefrom contextlib import nullcontext, suppressfrom typing import Any, Deque, Dict, List, Optionaldiff --cc gateway/run.pyindex 085f035ee43,7d1f33e6170..b496e672260--- a/gateway/run.py+++ b/gateway/run.py@@@ -3344,9 -3387,9 +3400,16 @@@ class GatewayRunnerGatewayVoiceMixin, GatewayAdapterLifecycleMixin, GatewayTopicThreadsMixin, GatewayTurnMixin,GatewayShutdownMixin, GatewayBusySessionMixin, GatewayConfigLoadersMixin, GatewayStartupMixin,GatewaySessionWatchersMixin, GatewayNotificationsMixin, GatewayInboundMixin, GatewayGoalsMixin,- GatewayAgentCacheMixin, GatewayRuntimeInitMixin, GatewayProfileReconcileMixin):- GatewayAgentCacheMixin, GatewayProfileReconcileMixin, GatewayPluginRewireMixin):++ GatewayAgentCacheMixin, GatewayRuntimeInitMixin, GatewayProfileReconcileMixin, GatewayPluginRewireMixin):"""Main gateway controller: manages adapter lifecycles, routes messages to/from the agent."""++ def _adapter_for_source(self, source):++ """The adapter that owns *source* for the session authority (admission checks, canonical++ automation, native route checks, recovery bindings). Main split the old resolver into the++ intake and delivery seams; the authority needs the answering adapter, so this is the++ delivery seam under its historical name."""++ return self._delivery_adapter_for(source)++# Class-level defaults so partial construction in tests doesn't blow up on attribute access._busy_input_mode: str = "interrupt"_busy_text_mode: str = "interrupt"@@@ -3467,7 -3518,256 +3538,6 @@@self._init_session_db()self._init_registries_and_clocks()- def _init_runtime_settings(self) -> None:- """Load ephemeral per-call config (prefill, reasoning, busy modes, timeouts, routing)."""- 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 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."""- 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."""- # 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()``.- self._primary_profile_name = self._kanban_notifier_profile = self._active_profile_name()- # 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."""- 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."""- # 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."""- # ``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-(guild,user) transcript dedup: the voice/STT pipeline can emit one utterance twice.- self._recent_voice_transcripts: Dict[tuple[int, int], 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--def _open_session_db_for_active_scope(self, raise_on_error: bool = False) -> Any:"""AsyncSessionDB for the active profile scope, resolved per access (not in ``__init__``) since``SessionDB()`` reads the context-local HERMES_HOME; one handle cached per path. Construction@@@ -4661,10 -5123,818 +4898,248 @@@ async def _wait_for_pid_exit(pid: int,return False- async def start_gateway(config: Optional[GatewayConfig] = None, replace: bool = False, verbosity: Optional[int] = 0) -> bool:-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.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."""- 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_restart_signal_handler(runner):+ """Build the SIGUSR1 handler: log what the signal means, then the drain-aware service restart."""+ def restart_signal_handler():+ # systemd's `reload` verb (ExecReload=kill -USR1) lands here too; say so, because operators+ # expect `reload` to mean an in-process config reload, not a drain-and-relaunch (#117267).+ logger.info(+ "SIGUSR1 received (systemctl reload / hermes gateway restart): performing a graceful "+ "gateway restart — drain active turns, exit, supervisor relaunches. Not an in-process "+ "config reload.")+ runner.request_restart(detached=False, via_service=True)+ return restart_signal_handler++-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."""- 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")))- _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 (comm-only ps, 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."""- 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--+ def _claim_host_gateway_role(force: bool = False) -> None:+ """Take the HOST-wide gateway lock, publish the record — or REFUSE to be the second gateway.++ The lock is no longer observe-only. ``gateway.host_attach`` already answers "is there a host+ gateway and does it serve me?" before anything binds, but it reads a RECORD, and a record is+ published a moment after the owner starts: two gateways launched together (a supervisor+ restarting two units, an update relaunch racing a manual start) can both see no owner and both+ proceed. The lock is the only atomic arbiter of that race, so losing it means we are the second+ gateway on this host — the shape multiplex-only forbids.++ The refusal is deliberately EX_TEMPFAIL (75), never the parking 78: losing a lock race is a+ runtime observation, not a config verdict. Every supervisor we generate retries 75, and on the+ retry the owner's record exists, so the attach path resolves the profile properly (attach,+ rescan-then-attach, or a named refusal) instead of the unit being parked forever.++ ``--force`` skips the question exactly as it does in the attach path.+ """+ from gateway import host_rendezvous as hr++ # The host lock can be free after a standalone owner exits while a coexisting+ # multiplexer remains live. Its per-home channel still governs our opt-out.+ if not force:+ from gateway.host_attach import REFUSE, standalone_attach_decision+ decision = standalone_attach_decision(get_hermes_home(), None)+ if decision is not None and decision.outcome == REFUSE:+ from gateway.restart import GATEWAY_SERVICE_RESTART_EXIT_CODE+ print(decision.message)+ raise SystemExit(GATEWAY_SERVICE_RESTART_EXIT_CODE)+ try:+ outcome, error = hr.claim_host_lock(hr.ROLE_GATEWAY)+ if outcome is hr.HostLockOutcome.ACQUIRED:+ # PROVISIONAL: an owner exists, its served set is not decided yet (multiplex is+ # settled by the runner, and the attach channel is not bound for another moment).+ # Publishing a guessed set here parked a second profile's supervised unit against+ # profiles this process may never serve; _refresh_host_gateway_record() fills it in+ # once the control socket answers.+ hr.publish_record(hr.ROLE_GATEWAY, profiles=(), home=str(get_hermes_home()))+ # SIGTERM (systemd stop, docker stop, the update relaunch) does not run atexit.+ hr.cleanup_on_exit(hr.ROLE_GATEWAY)+ return+ if outcome is hr.HostLockOutcome.COULD_NOT_OPEN:+ # NOT contention: a read-only/undeletable lock dir. Refusing here would take a working+ # single-gateway host down over an unusable directory.+ logger.warning(+ "Host gateway lock could not be opened (%s); this gateway is not discoverable. "+ "No second gateway is implied — the lock directory itself is unusable.", error)+ return+ except Exception:+ logger.debug("host gateway rendezvous failed", exc_info=True)+ return+ # Lost the lock. Reading the owner's record may fail (it is published a moment after the+ # claim); that changes WHO we can name, never the verdict -- we are the second gateway.+ owner = None+ try:+ owner = hr.read_record(hr.ROLE_GATEWAY, include_stale=True)+ except Exception:+ logger.debug("host gateway record unreadable", exc_info=True)+ if force:+ logger.warning("--force: starting a second gateway although %s owns this host.",+ hr.describe(owner) if owner else "another process")+ return+ from gateway.host_attach import (+ ATTACH_CHANNEL_WAIT_S, START, host_gateway, standalone_attach_decision,+ )+ from hermes_cli.profiles import profile_is_standalone+ if profile_is_standalone(get_hermes_home()):+ # Recheck after losing the atomic lock: the pre-lock served set may be stale.+ live_owner = host_gateway(wait_for_channel=ATTACH_CHANNEL_WAIT_S)+ if live_owner is not None:+ decision = standalone_attach_decision(get_hermes_home(), live_owner)+ if decision is not None:+ if decision.outcome == START:+ return+ from gateway.restart import GATEWAY_SERVICE_RESTART_EXIT_CODE+ print(decision.message)+ raise SystemExit(GATEWAY_SERVICE_RESTART_EXIT_CODE)+ _refuse_second_host_gateway(owner)+ if _owner_is_standalone():+ # COMPOSITION with #118236: `host_attach.decide` sent us here with START precisely because+ # the owner is another profile's STANDALONE gateway and will never serve us. Refusing now+ # exits 75, the supervisor retries in 5s, and the next claim loses the same race — the host+ # lock is per OS user and every gateway takes it, so a second profile can NEVER win. An+ # unmigrated fleet would spin forever instead of running. Start beside it and point at the+ # one command that converges; multiplex-only is enforced against a MULTIPLEXER owner.+ logger.warning(+ "Another profile's standalone gateway owns this host (%s); starting beside it rather "+ "than retrying a race no second profile can win. Fold every profile onto one gateway "+ "with: %s", hr.describe(owner) if owner else "owner unknown", _migrate_command())+ return+ _refuse_second_host_gateway(owner)+++ def _migrate_command() -> str:+ from hermes_cli.gateway_migrate import MIGRATE_COMMAND++ return MIGRATE_COMMAND+++ def _owner_is_standalone() -> bool:+ """True when the host owner answers that it does NOT multiplex (an unmigrated fleet).++ Asked only on the lock-losing path, and any failure answers False: an owner we cannot reach+ is treated as a multiplexer, which keeps the second-gateway refusal as the default.+ """+ try:+ from gateway.host_attach import host_gateway, profile_name_for_home, request_serve_profile++ owner = host_gateway()+ if owner is None or owner.pid == os.getpid():+ return False+ answered = request_serve_profile(profile_name_for_home(get_hermes_home()), owner=owner)+ return bool(answered is not None and answered.standalone)+ except Exception:+ logger.debug("standalone-owner probe failed; keeping the second-gateway refusal",+ exc_info=True)+ return False+++ def _refuse_second_host_gateway(owner) -> None:+ """Print the named refusal and exit 75 so a supervisor retries instead of parking the unit."""+ from gateway import host_rendezvous as hr+ from gateway.restart import GATEWAY_SERVICE_RESTART_EXIT_CODE+ from hermes_cli.gateway_migrate import MIGRATE_COMMAND++ who = hr.describe(owner) if owner else "owner unknown (its record is gone)"+ message = (+ f"❌ Another gateway already owns this host: {who}\n"+ f" Exactly one gateway per host serves every profile, so this process will not start a\n"+ f" second one (it would double-bind this profile's platforms).\n"+ f" Fold every profile onto the owner: {MIGRATE_COMMAND}\n"+ f" Or take the host over: hermes gateway run --replace\n"+ f" Or start one anyway: hermes gateway run --force")+ logger.error("Refusing to start a second gateway on this host: %s", who)+ print(message)+ raise SystemExit(GATEWAY_SERVICE_RESTART_EXIT_CODE)+++ def _log_standalone_profiles_at_boot(runner) -> None:+ """One INFO line per standalone profile when the MULTIPLEXER takes its served set at boot.++ The host gateway silently omits an opted-out profile from its served set; without this line an+ operator reading the boot log cannot tell "not created yet" from "excluded by config".+ """+ try:+ if not getattr(runner.config, "multiplex_profiles", False):+ return+ from hermes_cli.profiles import profiles_to_serve, profile_is_standalone+ from hermes_cli.gateway_multiplex_mode import STANDALONE_DEPRECATION_NOTICE+ served = set(runner.served_profile_names())+ for name, home in profiles_to_serve(True, include_standalone=True):+ if name != "default" and name not in served and profile_is_standalone(home):+ logger.warning("profile '%s' is standalone (gateway.standalone: true); not served by "+ "this gateway. %s", name, STANDALONE_DEPRECATION_NOTICE)+ except Exception:+ logger.warning("standalone-profile boot notice failed", exc_info=True)+++ def _refresh_host_gateway_record(runner) -> None:+ """Republish the host record with the SETTLED served set, now that the channel answers.++ The claim-time publish is deliberately empty: only the runner knows whether multiplex ended up+ on and which profiles it took. A standalone gateway serves exactly its own profile — not the+ whole roster ``served_profiles()`` would have guessed for it.+ """+ from gateway import host_rendezvous as hr+ from gateway.host_attach import profile_name_for_home++ try:+ if not hr.owns_host_lock(hr.ROLE_GATEWAY):+ return+ home = get_hermes_home()+ if getattr(runner.config, "multiplex_profiles", False):+ served = tuple(runner.served_profile_names())+ else:+ served = (profile_name_for_home(home),)+ hr.publish_record(hr.ROLE_GATEWAY, profiles=served, home=str(home))+ except Exception:+ logger.debug("host gateway record refresh failed", exc_info=True)++++# Bootstrap phases bound on the facade: ``_host_attach_or_none`` reads the replace step through this++# module, and the lifecycle tests patch/drive these phases as ``gateway.run`` attributes.++from gateway.run_bootstrap import ( # noqa: E402++ _start_gateway_make_shutdown_signal_handler, _start_gateway_replace_existing_instance,++ _start_gateway_shutdown_tail, _start_gateway_start_cron_and_housekeeping,++)+++++ async def _host_attach_or_none(replace: bool, force: bool = False) -> Optional[bool]:+ """Attach / rescan / refuse against the ONE host gateway; ``None`` = start normally.++ Returns ``True`` when this invocation is satisfied by the running host process (exit 0, nothing+ spawned) and ``False`` when it must refuse. The per-home duplicate guard below cannot answer+ this at all: another profile's gateway lives in another home, so it sees no PID and starts a+ second process — the shape multiplex-only forbids.++ ``force`` is the operator's escape hatch when the owner is wedged or lying: skip the whole+ question and start. Ignoring it here made ``--force`` print the starting banner and then attach+ anyway, leaving no supported way to start a gateway at all.+ """+ if force:+ logger.warning("--force: starting a gateway without asking the host owner.")+ return None++ from gateway.host_attach import ATTACH, REFUSE, REPLACE_HOST, decide++ decision = decide(get_hermes_home(), replace=replace)+ if decision.outcome == ATTACH:+ logger.info("Attaching to the host gateway instead of starting a second one: %s",+ decision.owner.describe() if decision.owner else "unknown")+ print(decision.message)+ return True+ if decision.outcome == REFUSE:+ logger.error("Refusing to start a second gateway on this host: %s",+ decision.owner.describe() if decision.owner else "unknown")+ print(decision.message)+ return False+ if decision.outcome == REPLACE_HOST and decision.owner is not None:+ # --replace names the HOST process, whichever home launched it.+ if not await _start_gateway_replace_existing_instance(decision.owner.pid, True):+ return False+ return None++-async def _start_gateway_start_control_socket(runner):- """Start the gateway control socket (identify/status/pause-for-update); None when unavailable."""- import atexit- _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- from gateway.run_profile_reconcile import migrate_profile_identity_verb, purge_profile_identity_verb- from gateway.run_plugin_rewire import reload_plugins_verb- # 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,- "rescan-profiles": _rescan_profiles_handler,- "migrate-profile-identity": migrate_profile_identity_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)})- if not await _control_server.start():- _control_server = None- else:- atexit.register(_control_server.cleanup_files)- 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)``."""- # 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)- cron_thread.start()-- # 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")- housekeeping_thread.start()- 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)."""- # 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])--+ 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."""- # Set here (not at import) so incidental gateway.run imports from CLI code don't poison it.- os.environ["HERMES_EXEC_ASK"] = "1"-- 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()-- # 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-- _start_gateway_configure_logging(verbosity)-- runner = GatewayRunner(config)- # 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()-- # PID file BEFORE adapters: of two concurrent `run --replace`, only the O_EXCL winner opens sockets.- if not _start_gateway_claim_pid_file(force=force or replace):- return False-- # 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)- # 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)-- 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:- from gateway.shutdown_flush import recover_pending_to_db- recovered = recover_pending_to_db(- session_resolver=runner.session_store.resolve_session_id_for_key,- )- 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.- runner._start_systemd_watchdog()-- await runner.wait_for_shutdown()-- return 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)+ """Run the process lifecycle; the runner facade remains the public entrypoint."""+ from gateway.run_bootstrap import start_gateway as bootstrap- return await bootstrap(config, replace, verbosity)++ return await bootstrap(config, replace, verbosity, force)def _guard_corrupt_user_config() -> None:diff --cc gateway/run_adapters.pyindex 46307891be8,af4adf7c62f..0319655bf27--- a/gateway/run_adapters.py+++ b/gateway/run_adapters.py@@@ -1342,43 -1423,79 +1426,87 @@@ class GatewayAdapterLifecycleMixin@staticmethoddef _scope_or_null(scope_factory, profile_home):- """``scope_factory(profile_home)`` or a nullcontext when the profile home is unknown."""- return scope_factory(profile_home) if profile_home is not None else contextlib.nullcontext()+ """The runtime scope for one body, by what ``profile_home`` IS:++ * a home — that profile's scope;+ * ``None`` — no routed profile: the LAUNCH profile's own work, so bind the launch profile+ explicitly once this process multiplexes. A bare ``nullcontext()`` made the launch+ profile the one tenant running on ambient ``os.environ`` and the process home, which a+ secondary's context may have poisoned; under the one-process-per-host ruling it is a+ tenant like any other. Single-profile hosts are unchanged (no-op until activation);+ * :data:`UNRESOLVED_PROFILE_HOME` — a NAMED profile whose home is gone: bind nothing, so an+ unscoped ``get_secret`` raises ``UnscopedSecretError`` under multiplexing. A profile never+ borrows another profile's value, and "we cannot tell whose this is" must fail closed.+ """+ if profile_home is UNRESOLVED_PROFILE_HOME:+ return contextlib.nullcontext()+ if profile_home is not None:+ return scope_factory(profile_home)+ from tui_gateway.launch_profile_policy import launch_profile_scope_if_multiplexed+ return launch_profile_scope_if_multiplexed()@staticmethod- def _stamp_event_profile(event, profile_name: str) -> None:- """Best-effort: stamp ``source.profile`` on an inbound event that has none yet."""- with suppress(Exception):- if getattr(event, "source", None) is not None and not event.source.profile:- event.source.profile = profile_name+ def _async_scope_or_null(scope_factory, profile_home):+ """``async with`` twin of :meth:`_scope_or_null` (for ``_async_profile_runtime_scope``)."""+ if profile_home is UNRESOLVED_PROFILE_HOME:+ return contextlib.nullcontext()+ if profile_home is not None:+ return scope_factory(profile_home)+ from tui_gateway.launch_profile_policy import async_launch_profile_scope_if_multiplexed+ return async_launch_profile_scope_if_multiplexed()++ def _canonicalize(self, source, *, transport_profile: Optional[str] = None,+ primary_home: Optional[Path] = None):+ """Runner-side identity seam: the pinned :class:`RoutingIdentity` of *source*, resolving it+ once when absent. ``transport_profile`` names a secondary's own bot (its handlers know it by+ construction); ``None`` = the primary/shared bot. ``None`` result = rejected route under+ multiplexing (the caller drops; the ingress gate warns once) or a source that cannot resolve+ (bare test rigs) — the legacy readers then stay in force."""+ if source is None:+ return None+ from gateway.session_identity import canonical_identity+ try:+ identity = canonical_identity(+ source, runner=self, transport_profile=transport_profile, primary_home=primary_home)+ except Exception:+ logger.debug("identity resolution failed; legacy readers stay in force", exc_info=True)+ return None+ if transport_profile and not getattr(source, "profile", None):+ with suppress(Exception):+ source.profile = transport_profile # a secondary's own event is at least its own+ return identitydef _make_profile_message_handler(self, profile_name: str):- """Message handler that stamps source.profile, then delegates under the profile scope- (auth runs BEFORE the agent-turn scope, so the profile's ``.env`` must be visible here)."""+ """Message handler that canonicalizes the event's identity FIRST, then delegates under the+ profile scope (auth runs BEFORE the agent-turn scope, so the profile's ``.env`` must be+ visible here)."""from gateway.run import _async_profile_runtime_scope- profile_home = self._profile_home_or_none(profile_name)+ profile_home = self._routed_profile_home(profile_name)+ from gateway.session_ingress_context import native_callback, register_transport_home- register_transport_home(self, profile_name, profile_home)++ # An unresolvable named profile has no transport home: the native callback then fails++ # closed under session authority (``profile_mismatch``) instead of naming a path.++ transport_home = None if profile_home is UNRESOLVED_PROFILE_HOME else profile_home++ register_transport_home(self, profile_name, transport_home)- async def _handler(event):+ async def _handler(_runner, event):- self._stamp_event_profile(event, profile_name)- if profile_home is not None:- event.source._authorization_profile_home = profile_home- with native_callback(self, event, profile_home, profile_name):- async with self._scope_or_null(_async_profile_runtime_scope, profile_home):+ self._canonicalize(getattr(event, "source", None), transport_profile=profile_name)- async with self._async_scope_or_null(_async_profile_runtime_scope, profile_home):- return await self._handle_message(event)++ if transport_home is not None:++ event.source._authorization_profile_home = transport_home++ with native_callback(self, event, transport_home, profile_name):++ async with self._async_scope_or_null(_async_profile_runtime_scope, profile_home):+ return await self._handle_message(event)- return _handler+ return _handler.__get__(self)def _make_profile_busy_session_handler(self, profile_name: str):- """Stamp an owning adapter's profile, then resolve busy policy under the profile scope+ """Busy-path twin: canonicalize FIRST, then resolve busy policy under the profile scope(auth runs against the profile's own allowlist, same as the cold-path message handler)."""from gateway.run import _async_profile_runtime_scope- profile_home = self._profile_home_or_none(profile_name)+ profile_home = self._routed_profile_home(profile_name)async def _handler(event, _session_key):- self._stamp_event_profile(event, profile_name)- async with self._scope_or_null(_async_profile_runtime_scope, profile_home):+ self._canonicalize(event.source, transport_profile=profile_name)+ async with self._async_scope_or_null(_async_profile_runtime_scope, profile_home):return await self._handle_active_session_busy_message(event, self._session_key_for_source(event.source))return _handlerdiff --cc gateway/run_bootstrap.pyindex 7e4b690daaf,00000000000..6758f69b7c2mode 100644,000000..100644--- a/gateway/run_bootstrap.py+++ b/gateway/run_bootstrap.py@@@ -1,687 -1,0 +1,731 @@@+"""Process startup phases; diagnostics remain in the gateway facade."""+from __future__ import annotations++import threading+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). "- "Use 'hermes gateway restart' to replace it, or 'hermes gateway stop' first.",++ "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❌ Gateway already running (PID {existing_pid}).\n"- f" Use 'hermes gateway restart' to replace it,\n"- f" or 'hermes gateway stop' to kill it first.\n"- f" Or use 'hermes gateway run --replace' to auto-replace.\n")++ 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)+ 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")))+ _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() -> bool:++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 (logger, os)++ 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++ 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),- "purge-profile-identity": purge_profile_identity_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_tick_profile_homes, _start_gateway_housekeeping, asyncio, logger, threading)++ 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()- multiplex_cron = bool(getattr(runner.config, "multiplex_profiles", False))++ # 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=multiplex_cron)++ resolve_cron_scheduler(), multiplex_profiles=len(cron_profile_homes) > 1)+ cron_start_kwargs: Dict[str, Any] = {"adapters": runner.adapters, "loop": asyncio.get_running_loop()}+- # Multiplex: tell the ticker which profile homes to tick, else secondary profiles' jobs never run.- if isinstance(cron_provider, InProcessCronScheduler) and multiplex_cron:- try:- profile_homes = _cron_tick_profile_homes(runner.config)- if profile_homes:- # Live enumerator: re-read per cycle so a hot-served profile's jobs fire without a restart.- cron_start_kwargs["profile_homes"] = lambda: _cron_tick_profile_homes(runner.config)- # Per-profile adapters so each profile's cron output goes via its own bot, not the default's.- 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) under multiplex: %s", len(profile_homes),- [p[0] if isinstance(p, tuple) else p for p in profile_homes])- except Exception as exc:- logger.warning("Could not resolve profile homes for multiplex cron: %s", exc)++ 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)+- with suppress(Exception):- await _shutdown_mcp_servers_nonblocking()++ # 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() -> 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. Exits EX_CONFIG: a config verdict, never a retry."""+ 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 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) -> bool:++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)."""++ 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.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,++ _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"++ 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():+ return False+- # Duplicate-instance guard scoped to HERMES_HOME; distinct-home multi-profile setups coexist.++ # 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)- if not _start_gateway_claim_pid_file():++ # PID file BEFORE adapters: of two concurrent `run --replace`, only the O_EXCL winner opens sockets.++ if not _start_gateway_claim_pid_file(force=force or replace):+ release_gateway_runtime_lock()+ return False++ _control_server = None+ runner = None+ _planned_stop_watcher_stop = None+ try:+ _start_gateway_configure_logging(verbosity)++ 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)+- def restart_signal_handler():- runner.request_restart(detached=False, via_service=True)++ 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:+ from gateway.shutdown_flush import recover_pending_to_db- recovered = recover_pending_to_db()++ recovered = recover_pending_to_db(++ session_resolver=runner.session_store.resolve_session_id_for_key,++ )+ 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()- with suppress(Exception):- await _shutdown_mcp_servers_nonblocking()++ 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_goals.pyindex fef1720b73c,31412fd5d79..dc5b7deb51c--- a/gateway/run_goals.py+++ b/gateway/run_goals.py@@@ -139,13 -139,9 +139,13 @@@ class GatewayGoalsMixinreturnsession_id = currentwatch[quick_key] = (source, session_id)- adapter = self._adapter_for_source(source)+ adapter = self._delivery_adapter_for(source)if adapter is None or not adapter._message_handler:return+ if getattr(self, 'session_authority', None) is not None:+ from gateway.run_heartbeat_acceptance import admit_heartbeat+ await admit_heartbeat(self, adapter, source, session_id, quick_key)+ returnif (self._is_session_running(quick_key)or quick_key in adapter._active_sessionsdiff --cc gateway/run_profile_reconcile.pyindex c94ecd58ec8,e0f32bd5e1e..a817bd9b3e1--- a/gateway/run_profile_reconcile.py+++ b/gateway/run_profile_reconcile.py@@@ -107,35 -104,34 +108,50 @@@ class GatewayProfileReconcileMixinreturn {**result, "pending": True, "served_profiles": self.served_profile_names()}async with self._reconcile_lock():active = getattr(self, "_primary_profile_name", None) or "default"- current = {str(name): Path(home) for name, home in _multiplex_profile_homes(self.config)}+ live = {str(name): Path(home) for name, home in profiles_to_serve(multiplex=True)}known = dict(self._served_profile_homes or {})+ from gateway.status import live_gateway_pid_for_home++ blocked = set()+ warned = self._profile_own_gateway_warned or set()- for name in list(current):++ for name in list(live):+ if name == active or name in known:+ continue- if live_gateway_pid_for_home(current[name]) is not None:++ if live_gateway_pid_for_home(live[name]) is not None:+ blocked.add(name)+ if name not in warned:+ logger.warning("[MULTIPLEX] Profile '%s' still runs its own gateway; "+ "stop it before the host can serve this profile", name)- del current[name]++ del live[name]+ self._profile_own_gateway_warned = blockedsigs = self._served_profile_signatures or {}- added = [n for n in current if n not in known and n != active]- removed = [n for n in known if n not in current and n != active]- changed = [n for n in current if n in known and n != active and n not in added- and profile_serve_signature(current[n]) != sigs.get(n)]+ from gateway.run_runtime import park_profile, unpark_profile+ for name in [n for n in self._parked_profile_names() if n not in live]:+ unpark_profile(self, name)+ parked = self._parked_profile_names()+ # The watcher never re-parks the same profile every cycle; a creator's explicit signal does.+ retry_parked = reason == "control-socket"+ added = [n for n in live if n not in known and n != active and (retry_parked or n not in parked)]+ removed = [n for n in known if n not in live and n != active]+ changed = [n for n in live if n in known and n != active and n not in added+ and profile_serve_signature(live[n]) != sigs.get(n)]if not (added or removed or changed):return {**result, "served_profiles": self.served_profile_names()}for name in removed:await self._unserve_profile(name, known[name])result["removed"].append(name)+ current = {n: h for n, h in live.items() if n in known or n == active}+ for name in list(added):+ reason = await self._serve_profile_runtime(name, live[name])+ if reason is not None:+ added.remove(name)+ park_profile(self, name, reason)+ result["parked"].append(name)+ continue+ unpark_profile(self, name)+ current[name] = live[name]claimed = self._live_resource_claims(active)+ transient_failed = set()for name in added + changed:# Only acknowledge the configuration observed before connecting;# a setup save during an awaited handshake needs another scan.@@@ -238,39 -228,34 +277,41 @@@task.cancel()if tasks:await asyncio.wait(tasks, timeout=self._adapter_disconnect_timeout_secs())- adapters = (getattr(self, "_profile_adapters", None) or {}).pop(name, None) or {}- for platform, adapter in list(adapters.items()):- await self._bounded_adapter_teardown(adapter, platform, profile=name)- # Its ``<name>:<platform>`` runtime entries describe a profile that no longer exists.- _write_runtime_status_quiet(drop_profile_platforms=name)- for attr in ("pairing_stores", "_busy_text_modes_by_profile", "_busy_input_modes_by_profile"):- store = getattr(self, attr, None)- if isinstance(store, dict):- store.pop(name, None)- if isinstance(self._served_profile_homes, dict):- self._served_profile_homes.pop(name, None)- if isinstance(self._served_profile_signatures, dict):- self._served_profile_signatures.pop(name, None)- from gateway.session import _session_key_namespace- prefix = _session_key_namespace(name) + ":"- cache = getattr(self, "_agent_cache", None)- for key in [k for k in list(cache or {}) if str(k).startswith(prefix)]:- with _log_suppressed(logging.DEBUG, "agent eviction failed for %s", key, exc_info=True):- self._evict_cached_agent(key)- # Its session authority and reservation go before the store handles: the authority owns the- # state.db writer, and the next restart must not try to reserve a home that no longer exists.- from gateway.run_runtime import release_profile_home, unserve_profile_runtime- if getattr(self, "session_authorities", None) is not None:- with _log_suppressed(logging.WARNING, "session authority retirement failed for %s", name, exc_info=True):- await unserve_profile_runtime(self, home)- release_profile_home(self, home)- with _log_suppressed(logging.DEBUG, "profile handle release failed", exc_info=True):- from hermes_state_registry import close_all_under- close_all_under(home)- with _log_suppressed(logging.DEBUG, "memory-store release failed", exc_info=True):- from plugins.memory.holographic.store import MemoryStore- MemoryStore.release_all_under(home)- logger.info("[MULTIPLEX] Profile '%s' deleted — %d adapter(s) stopped and unrouted", name, len(adapters))+ with _profile_runtime_scope(Path(home), hydrate_secrets=False):+ adapters = (getattr(self, "_profile_adapters", None) or {}).pop(name, None) or {}+ for platform, adapter in list(adapters.items()):+ await self._bounded_adapter_teardown(adapter, platform, profile=name)+ # Its ``<name>:<platform>`` runtime entries describe a profile that no longer exists.+ _write_runtime_status_quiet(drop_profile_platforms=name)+ for attr in ("pairing_stores", "_busy_text_modes_by_profile", "_busy_input_modes_by_profile",+ "_busy_text_timing_by_profile", "_human_delay_by_profile", "_profile_configs"):+ store = getattr(self, attr, None)+ if isinstance(store, dict):+ store.pop(name, None)+ if isinstance(self._served_profile_homes, dict):+ self._served_profile_homes.pop(name, None)+ if isinstance(self._served_profile_signatures, dict):+ self._served_profile_signatures.pop(name, None)+ from gateway.session import _session_key_namespace+ prefix = _session_key_namespace(name) + ":"+ cache = getattr(self, "_agent_cache", None)+ for key in [k for k in list(cache or {}) if str(k).startswith(prefix)]:+ with _log_suppressed(logging.DEBUG, "agent eviction failed for %s", key, exc_info=True):+ self._evict_cached_agent(key)++ # Its session authority and reservation go before the store handles: the authority owns the++ # state.db writer, and the next restart must not try to reserve a home that no longer exists.++ from gateway.run_runtime import release_profile_home, unserve_profile_runtime++ if getattr(self, "session_authorities", None) is not None:++ with _log_suppressed(logging.WARNING, "session authority retirement failed for %s", name, exc_info=True):++ await unserve_profile_runtime(self, home)++ release_profile_home(self, home)+ with _log_suppressed(logging.DEBUG, "profile handle release failed", exc_info=True):+ from hermes_state_registry import close_all_under+ close_all_under(home)+ with _log_suppressed(logging.DEBUG, "memory-store release failed", exc_info=True):+ from plugins.memory.holographic.store import MemoryStore+ MemoryStore.release_all_under(home)+ logger.info("[MULTIPLEX] Profile '%s' deleted — %d adapter(s) stopped and unrouted", name, len(adapters))def _mcp_config_reconciler(runner=None):diff --cc gateway/run_runtime_init.pyindex 4159dbaf523,00000000000..03c86c864f6mode 100644,000000..100644--- a/gateway/run_runtime_init.py+++ b/gateway/run_runtime_init.py@@@ -1,262 -1,0 +1,260 @@@+"""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)++ 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()``.+ self._primary_profile_name = self._kanban_notifier_profile = self._active_profile_name()+ # 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, logger, threading)++ 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).- if self._session_db is not None:- try:- from hermes_cli.config import load_config as _load_full_config- _sess_cfg = (_load_full_config().get("sessions") or {})- if _sess_cfg.get("auto_archive", False):- self._session_db._db.maybe_auto_archive(- idle_days=float(_sess_cfg.get("auto_archive_days", 3)),- min_interval_hours=int(_sess_cfg.get("min_interval_hours", 24)))- if _sess_cfg.get("auto_prune", False):- # Construction-time, before the loop serves traffic; sync DB is fine.- self._session_db._db.maybe_auto_prune_and_vacuum(- retention_days=int(_sess_cfg.get("retention_days", 90)),- min_interval_hours=int(_sess_cfg.get("min_interval_hours", 24)),- min_vacuum_interval_days=int(- _sess_cfg.get("min_vacuum_interval_days", 30)),- vacuum=bool(_sess_cfg.get("vacuum_after_prune", True)),- sessions_dir=self.config.sessions_dir)- except Exception as exc:- logger.debug("state.db auto-maintenance skipped: %s", exc)-++ # 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-(guild,user) transcript dedup: the voice/STT pipeline can emit one utterance twice.+ self._recent_voice_transcripts: Dict[tuple[int, int], 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 = Falsediff --cc gateway/run_shutdown.pyindex 5932c22c47b,142f8ac9aef..1c6d711db70--- a/gateway/run_shutdown.py+++ b/gateway/run_shutdown.py@@@ -1625,8 -1755,7 +1755,9 @@@ class GatewayShutdownMixinself._running = Falseself._clear_plugin_message_injector()self._draining = True+ from gateway.run_runtime import drain_gateway_runtime+ await drain_gateway_runtime(self)+ self._mark_api_runs_shutdown_requested()# getattr-guards: shutdown-path test doubles may lack the room worker / systemd watchdog.stop_room_worker = getattr(self, "_stop_hosted_room_worker", None)if callable(stop_room_worker):@@@ -1877,10 -2033,13 +2035,11 @@@_step("Shared SessionDB close error", _close_shared)logger.info("Shutdown phase: SessionDB close done at +%.2fs", ctx.elapsed())- def _stop_persist_exit_state(self, ctx: "GatewayShutdownMixin._StopContext") -> None:- """Persist exit markers; process bootstrap releases ownership after writer drain."""+ async def _stop_persist_exit_state(self, ctx: "GatewayShutdownMixin._StopContext") -> None:- """PID/lock release, clean-shutdown marker, restart markers, terminal runtime status."""++ """Clean-shutdown marker, restart markers, terminal runtime status; process bootstrap++ releases PID/lock ownership after the writer drain."""from gateway.run import _hermes_home, _planned_restart_notification_path, _shutdown_gateway_health_exportfrom utils import atomic_json_write- from gateway.status import remove_pid_file, release_gateway_runtime_lock- remove_pid_file()- release_gateway_runtime_lock()# Clean-shutdown marker skips suspend_recently_active() next boot; a timed-out drain left# half-finished sessions, so no marker — the next startup suspends them.if not ctx.timed_out:@@@ -1963,12 -2144,10 +2144,12 @@@await GatewayRunner._stop_drain_active_work(self, timeout, ctx)if ctx.timed_out:await GatewayRunner._stop_interrupt_remaining_work(self, ctx)+ from gateway.run_runtime import settle_gateway_runtime+ await settle_gateway_runtime(self)await GatewayRunner._stop_finalize_agents_and_adapters(self, ctx)- GatewayRunner._stop_release_runtime_state(self, ctx)+ await GatewayRunner._stop_release_runtime_state(self, ctx)GatewayRunner._stop_quiesce_and_close_session_dbs(self, timeout, ctx)- GatewayRunner._stop_persist_exit_state(self, ctx)+ await GatewayRunner._stop_persist_exit_state(self, ctx)finally:_watchdog_done.set()diff --cc gateway/run_turn.pyindex dcac2b981b9,a6ded88d346..3c0e132ba3d--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@@ -110,15 -139,225 +139,42 @@@ def bound_model_input_without_hygiene(hreturn history[:head_end] + history[tail_start:]+ def hygiene_no_commit_reason(agent) -> str:+ """Name WHY a hygiene compression left the session id unchanged with no in-place commit.+ The terminal ``else`` used to blame "no session_db on the hygiene agent" for every route into it,+ but that is one of several causes (#71097): an attempt that ABORTED before any commit boundary+ (lock skip, transient cooldown, summary timeout, codex thread interrupted) leaves+ ``_last_compression_attempt_in_place`` at ``None``; a DB-less agent is only the case when+ ``_session_db`` really is missing. Read the per-attempt signals the compressor sets, in that order."""+ if not bool(getattr(agent, "_last_compression_attempt_recorded", False)):+ return "compression did not run"+ lock_skip = getattr(agent, "_compression_skipped_due_to_lock", None)+ if lock_skip is True or isinstance(lock_skip, str):+ return "attempt skipped: compression lease held by another process"+ blocked = getattr(agent, "_compression_blocked_transient", None)+ if blocked:+ return f"attempt blocked: {blocked}"+ if getattr(agent, "_last_compression_attempt_in_place", None) is None:+ detail = "summary timed out" if getattr(agent, "_last_compression_timed_out", False) else "aborted before commit"+ warning = getattr(agent, "_last_compression_summary_warning", None)+ return f"attempt {detail}" + (f": {warning}" if warning else "")+ if getattr(agent, "_session_db", None) is None:+ return "no session_db on the hygiene agent"+ return "in-place commit did not complete"+++ class GatewayTurnMixin:+ """Agent-turn execution for GatewayRunner (see module docstring)."""+- def _resolve_session_agent_runtime(- self, *, source: Optional[SessionSource] = None, session_key: Optional[str] = None,- user_config: Optional[dict] = None,- ) -> tuple[str, dict]:- """Resolve model/runtime for a session.-- Priority (highest first): session ``/model`` → ``channel_overrides`` → global config/env- (``_resolve_gateway_model(user_config)`` and default provider resolution)."""- from gateway.run import (- _credential_pool_for_provider, _get_channel_override, _resolve_gateway_model,- _resolve_runtime_agent_kwargs, _resolve_runtime_agent_kwargs_for_provider,- )- skey = self._resolve_session_key_or_none(source, session_key)- # Every exit path starts clean: the /model-override fast path returns before the pop below,- # and hygiene/inbound callers resolve without a turn runner consuming the stash — a stale- # notice must never attach to another session's next turn (#74349).- self._pre_agent_fallback_notice = None-- model = _resolve_gateway_model(user_config)- if skey:- self._rehydrate_session_model_override(skey)- _override_state = self._peek_session_state(skey) if skey else None- override = _override_state.conversation.model_override if _override_state else None- if override:- override_model = override.get("model", model)- override_runtime = {- k: override.get(k) for k in (- "provider", "requested_provider", "api_key", "base_url", "api_mode",- "max_tokens", "credential_pool", "request_overrides", "capabilities",- )- }- override_runtime["capabilities"] = dict(override_runtime["capabilities"] or {})- if override_runtime.get("api_key"):- if override_runtime.get("credential_pool") is None:- override_runtime["credential_pool"] = _credential_pool_for_provider(override.get("provider"))- logger.debug(- "Session model override (fast): session=%s config_model=%s -> override_model=%s provider=%s",- skey or "", model, override_model, override_runtime.get("provider"),- )- return override_model, override_runtime- # No api_key on the override: env-based resolution below, override model/provider on top.- logger.debug(- "Session model override (no api_key, fallback): session=%s config_model=%s override_model=%s",- skey or "", model, override_model,- )- else:- logger.debug(- "No session model override: session=%s config_model=%s override_keys=%s",- skey or "", model,- [- _key for _key, _st in list(self._sessions_map().items())- if _st.conversation.model_override is not None- ][:5] or "[]",- )- runtime_kwargs = _resolve_runtime_agent_kwargs()- # Private notice metadata must never reach an ``AIAgent(**runtime_kwargs)`` spread; the turn- # runner surfaces it through the agent's one-shot fallback notice (#74349).- self._pre_agent_fallback_notice = runtime_kwargs.pop("_fallback_notice", None)- runtime_model = runtime_kwargs.pop("model", None)- if runtime_model:- logger.info("Runtime provider supplied explicit model override: %s -> %s", model, runtime_model)- model = runtime_model-- cfg = getattr(self, "config", None) # getattr: bare object.__new__ test runners- if cfg and source is not None:- ch = _get_channel_override(- cfg, source.platform, str(source.chat_id) if source.chat_id else "",- thread_id=str(source.thread_id) if getattr(source, "thread_id", None) else None,- parent_id=str(source.parent_chat_id) if getattr(source, "parent_chat_id", None) else None,- )- if ch:- if ch.model:- model = ch.model- if ch.provider:- runtime_kwargs = _resolve_runtime_agent_kwargs_for_provider(ch.provider, target_model=model or None)- ch_runtime_model = runtime_kwargs.pop("model", None)- # Adopt the provider's bundled model only when the override named none.- if ch_runtime_model and not ch.model:- model = ch_runtime_model-- if override and skey:- model, runtime_kwargs = self._apply_session_model_override(skey, model, runtime_kwargs)-- # Provider resolved but no model.default (`hermes auth add` without `hermes model`): use the- # provider's first catalog model.- if not model and runtime_kwargs.get("provider"):- with suppress(Exception):- from hermes_cli.models import get_default_model_for_provider- model = get_default_model_for_provider(runtime_kwargs["provider"])- if model:- logger.info(- "No model configured — defaulting to %s for provider %s", model, runtime_kwargs["provider"],- )+from gateway.run_turn_prepare import GatewayTurnPrepareMixin+from gateway.run_turn_hygiene import GatewayTurnHygieneMixin+from gateway.run_turn_persistence import GatewayTurnPersistenceMixin+++class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, GatewayTurnPersistenceMixin):+ """Agent-turn execution for GatewayRunner (see module docstring)."""- # Final safety net: an empty model (transient config-cache miss) makes every API call 400 and- # the session goes silent — reuse the last model resolved for this session, else process-wide.- if not model:- _lr_state = self._peek_session_state(skey) if skey else None- _lr_star = self._peek_session_state("*")- _recovered = (- (_lr_state.conversation.last_resolved_model if _lr_state else "")- or (_lr_star.conversation.last_resolved_model if _lr_star else "")- )- if _recovered:- logger.warning(- "Empty model resolved for session=%s — recovering "- "last-known-good model %s (config read likely returned "- "empty; see #35314)", skey or "", _recovered,- )- model = _recovered- else:- # Cache the good resolution for future recovery turns.- if skey:- self._session_state(skey).conversation.last_resolved_model = model- self._session_state("*").conversation.last_resolved_model = model-- return model, runtime_kwargs-- def _resolve_turn_agent_config(self, user_message: str, model: str, runtime_kwargs: dict) -> dict:- """Effective model/runtime config for one turn. With `/fast` priority on, fast-mode- ``request_overrides`` are deep-merged OVER the per-provider ones so both reach the model."""- from gateway.run import _deep_merge_request_overrides- from hermes_cli.models import resolve_fast_mode_overrides- # Tests bind this method onto bare namespaces, so no class-level tables here.- runtime = {- k: runtime_kwargs.get(k) for k in (- "api_key", "base_url", "provider", "requested_provider", "api_mode", "command", "args",- "credential_pool", "max_tokens", "capabilities",- )- }- runtime["args"] = list(runtime["args"] or [])- runtime["capabilities"] = dict(runtime["capabilities"] or {})- base_request_overrides = dict(runtime_kwargs.get("request_overrides") or {})- route = {- "model": model,- "runtime": runtime,- "signature": (- model, runtime["provider"], runtime["requested_provider"], runtime["base_url"],- runtime["api_mode"], runtime["command"], tuple(runtime["args"]),- ),- }- if getattr(self, "_service_tier", None) != "priority":- # None / auto / cold: the bounded window is applied per request by agent.fast_mode.- route["request_overrides"] = base_request_overrides- return route- try:- overrides = resolve_fast_mode_overrides(- route["model"], provider=runtime["provider"], base_url=runtime["base_url"],- )- except Exception:- overrides = None- # Fast-mode keys (service_tier / speed) are top-level and don't collide with extra_body.- route["request_overrides"] = _deep_merge_request_overrides(base_request_overrides, overrides or {})- return route-- def _sync_session_model_from_agent(self, session_id: str, agent: Any) -> None:- """Persist the runtime model/provider a gateway turn actually used (provider fallback can- switch them after the row was created). Runs in the ``run_sync`` executor thread, so it- uses the sync ``SessionDB`` (``_db``), not the AsyncSessionDB forwarder."""- if not session_id or agent is None or self._session_db is None:- return- model = getattr(agent, "model", None)- if not model:- return- runtime = {k: getattr(agent, k, None) for k in ("provider", "base_url", "api_mode")}- runtime["fallback_active"] = bool(getattr(agent, "_fallback_activated", False))- runtime = {k: v for k, v in runtime.items() if v not in (None, "")}- try:- db = self._session_db._db- row = db.get_session(session_id)- if not row:- return- # Legacy backfill: canonical Bot Chats created BEFORE the follow_profile_config contract existed- # carry no marker, yet they are still the plugin-owned forever-DM. The plugin's own identity- # rule is "the profile's session titled exactly 'Bot Chat'" (UNIQUE(title) makes that an exact- # registry, and pre-policy rows may be visible OR hidden), so mirror that rule here. Without- # this, every Bot Chat that already exists in the field stays pinned to its stale stored- # provider until the user deletes it — the exact live-report shape (#89497 / #94818).- raw_config = row.get("model_config")- config = {}- with suppress(Exception):- config = json.loads(raw_config) if raw_config else {}- if not isinstance(config, dict):- config = {}- gateway_runtime = dict(config.get("gateway_runtime") or {})- if row.get("model") == model and all(gateway_runtime.get(k) == v for k, v in runtime.items()):- return- config["gateway_runtime"] = runtime- db.update_session_meta(session_id, json.dumps(config), model=model)- except Exception:- logger.debug("Failed to sync gateway session model metadata", exc_info=True)def _event_thread_metadata(self, event, source):"""Thread metadata for a send that replies to ``event`` on ``source``."""@@@ -929,17 -2909,13 +997,18 @@@_gateway_platform_value, _has_platform_display_override, _load_gateway_config,_platform_config_key,)+ from agent.secret_scope import get_secretfrom gateway.display_config import resolve_display_setting, resolve_tool_progressfrom gateway.status_phrases import choose_status_phrase, resolve_status_phrase_catalog- user_config = _load_gateway_config()- platform_key = _platform_config_key(source.platform)+ from gateway.session_policy import policy_for_source+ policy = policy_for_source(self, source)+ from gateway.session_authorities import active_authority+ user_config = policy.config(active_authority(self)) if policy else _load_gateway_config()+ platform_key = policy.platform if policy else _platform_config_key(source.platform)enabled_toolsets, disabled_toolsets = self._resolve_turn_toolsets(user_config, source, platform_key)+ if policy:+ enabled_toolsets = list(policy.toolsets)- adapter = self._adapter_for_source(source)+ adapter = self._delivery_adapter_for(source)# Tool preview length (0 = no limit) and friendly tool labels (default on), per-platform.for _setter, _setting, _default, _cast in (("set_tool_preview_max_len", "tool_preview_length", 0, lambda v: int(v) if v else 0),diff --cc gateway/run_turn_hygiene.pyindex 4201e93fd84,00000000000..079ae807da5mode 100644,000000..100644--- a/gateway/run_turn_hygiene.py+++ b/gateway/run_turn_hygiene.py@@@ -1,823 -1,0 +1,827 @@@+"""Gateway turn hygiene phases; inherited by GatewayTurnMixin."""+from __future__ import annotations++import logging+from typing import TYPE_CHECKING+import asyncio+import dataclasses+import inspect+import json+import os+import queue+import threading+import time+from agent.i18n import t+from agent.session_activity import format_iteration_progress+from contextlib import nullcontext, suppress+from contextvars import copy_context+from gateway.config import Platform+from gateway.media_repair import repair_explicit_computer_use_media_paths+from gateway.platforms.base import BasePlatformAdapter+from gateway.platforms.event import MessageEvent+from gateway.session import (+ SessionSource, _session_key_namespace, build_channel_continuity_note,+ build_session_context,+)+from gateway.session_transcript import TranscriptReadError+from gateway.turn_context import TurnContext+from gateway.turn_lease import DEFAULT_LEASE_WAIT, TurnLeaseTimeoutError+from hermes_constants import get_hermes_home_override+from pathlib import Path+from typing import Any, Callable, Dict, List, Optional, Tuple+from utils import base_url_hostname++if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)+ from gateway.run import GatewayRunner # noqa: F401+ from gateway.run_turn_runner import TurnRunner # noqa: F401++# Log-record parity with the origin module.+logger = logging.getLogger("gateway.run")+++class GatewayTurnHygieneMixin:+ @dataclasses.dataclass+ class _HygienePlan:+ """Hygiene pre-check outcome for one turn."""++ needs_compress: bool+ approx_tokens: int+ msg_count: int+ warn_token_threshold: int++ @staticmethod+ def _hmwa_hygiene_read_config(hs, data):+ """Apply model / compression knobs from the gateway config onto ``hs`` (invalid values keep the defaults)."""+ # Resolve model name (same logic as run_sync)+ _model_cfg = data.get("model", {})+ if isinstance(_model_cfg, str):+ hs.model = _model_cfg+ elif isinstance(_model_cfg, dict):+ hs.model = _model_cfg.get("default") or _model_cfg.get("model") or hs.model+ _raw_ctx = _model_cfg.get("context_length")+ if _raw_ctx is not None:+ with suppress(TypeError, ValueError):+ hs.config_context_length = int(_raw_ctx)+ hs.provider = _model_cfg.get("provider") or None+ hs.base_url = _model_cfg.get("base_url") or None++ # Only the enabled flag is shared with the agent's compression config (hygiene runs higher).+ _comp_cfg = data.get("compression", {})+ if not isinstance(_comp_cfg, dict):+ return+ hs.compression_enabled = str(_comp_cfg.get("enabled", True)).lower() in {"true", "1", "yes"}++ def _knob(key, current, cast, allow_zero=False):+ raw = _comp_cfg.get(key)+ if raw is None:+ return current+ try:+ parsed = cast(raw)+ except (TypeError, ValueError):+ return current+ return parsed if (parsed >= 0 if allow_zero else parsed > 0) else current++ hs.hard_msg_limit = _knob("hygiene_hard_message_limit", hs.hard_msg_limit, int)+ hs.timeout_seconds = _knob("hygiene_timeout_seconds", hs.timeout_seconds, float)+ hs.total_ceiling_seconds = _knob("hygiene_total_ceiling_seconds", hs.total_ceiling_seconds, float)+ # The ceiling can never be tighter than one idle window, or the extension loop would be dead code.+ hs.total_ceiling_seconds = max(hs.total_ceiling_seconds, hs.timeout_seconds)+ hs.max_turn_hold_seconds = _knob("hygiene_max_turn_hold_seconds", hs.max_turn_hold_seconds, float)+ hs.failure_cooldown_seconds = _knob(+ "hygiene_failure_cooldown_seconds", hs.failure_cooldown_seconds, float, allow_zero=True,+ )++ async def _hmwa_hygiene_settings(self, source, session_key):+ """Resolve model/provider/context-length + hygiene knobs (fail-soft: errors keep defaults).++ The 0.85 threshold is deliberately HIGHER than the agent's compressor (0.50): a safety net+ for sessions that grew between turns. ``max_turn_hold_seconds`` bounds the TURN wait+ (compressor keeps running detached, commit fenced); kept below transport idle-timeouts."""+ from gateway.run import _load_gateway_config+ hs = self._HygieneSettings(+ model="anthropic/claude-sonnet-4.6", threshold_pct=0.85, compression_enabled=True,+ hard_msg_limit=5000, timeout_seconds=30.0, total_ceiling_seconds=600.0,+ max_turn_hold_seconds=10.0, failure_cooldown_seconds=300.0, config_context_length=None,+ provider=None, base_url=None, api_key=None, data={},+ )+ try:+ hs.data = _load_gateway_config()+ if hs.data:+ self._hmwa_hygiene_read_config(hs, hs.data)+ configured_model, configured_provider, configured_base_url = hs.model, hs.provider, hs.base_url++ with suppress(Exception):+ hs.model, _hyg_runtime = self._resolve_session_agent_runtime(+ source=source, session_key=session_key,+ user_config=hs.data if isinstance(hs.data, dict) else None,+ )+ hs.provider = _hyg_runtime.get("provider") or hs.provider+ hs.base_url = _hyg_runtime.get("base_url") or hs.base_url+ hs.api_key = _hyg_runtime.get("api_key") or hs.api_key++ if hs.config_context_length is not None:+ try:+ from hermes_cli.route_identity import should_clear_context_pin_async++ if await should_clear_context_pin_async(+ configured_model, hs.model, configured_base_url, hs.base_url,+ configured_provider, hs.provider,+ ):+ hs.config_context_length = None+ except Exception:+ hs.config_context_length = None++ # custom_providers per-model context_length fallback (as in run_agent.py); needs base_url.+ if hs.config_context_length is None and hs.base_url:+ with suppress(TypeError, ValueError):+ try:+ from hermes_cli.config import (+ get_compatible_custom_providers as _gw_gcp,+ get_custom_provider_context_length as _gw_gccl,+ )+ _hyg_custom_providers = _gw_gcp(hs.data)+ except Exception:+ _hyg_custom_providers = hs.data.get("custom_providers")+ if not isinstance(_hyg_custom_providers, list):+ _hyg_custom_providers = []+ _hyg_custom_ctx = _gw_gccl(+ model=hs.model, base_url=hs.base_url, custom_providers=_hyg_custom_providers,+ )+ if _hyg_custom_ctx:+ hs.config_context_length = int(_hyg_custom_ctx)+ except Exception:+ pass+ return hs++ async def _hmwa_hygiene_plan(self, hs, history, session_entry, session_key):+ """Decide whether hygiene compression fires this turn (token/message thresholds, DB-backed+ failure cooldown, in-flight compression)."""+ from agent.model_metadata import estimate_messages_tokens_rough, get_model_context_length_async+ _hyg_context_length = await get_model_context_length_async(+ hs.model, base_url=hs.base_url or "", api_key=hs.api_key or "",+ config_context_length=hs.config_context_length, provider=hs.provider or "",+ )+ _compress_token_threshold = int(_hyg_context_length * hs.threshold_pct)+ _warn_token_threshold = int(_hyg_context_length * 0.95)+ _msg_count = len(history)++ # Real usage decides: the API-reported prompt count, else the anchor persisted on the session+ # row (real count + delta of what was appended since, survives gateway restarts), else the+ # rough estimate (runs 30-50% high, which only fires hygiene early — safe). Do NOT compensate+ # with a threshold multiplier.+ from agent.image_token_cost import image_cost_context, learned_image_token_cost+ _anchored = None+ # Images in any local delta/estimate are priced at the cost learned from this model's usage.+ with image_cost_context(learned_image_token_cost(hs.model, hs.base_url)):+ if session_entry.last_prompt_tokens <= 0:+ from agent.usage_anchor import persisted_anchor_tokens+ _session_db = getattr(self, "_session_db", None)+ _anchored = persisted_anchor_tokens(+ getattr(_session_db, "_db", _session_db), session_entry.session_id, history,+ )+ if session_entry.last_prompt_tokens > 0:+ _approx_tokens, _token_source = session_entry.last_prompt_tokens, "actual"+ elif _anchored is not None:+ _approx_tokens, _token_source = _anchored, "anchored"+ else:+ _approx_tokens, _token_source = estimate_messages_tokens_rough(history), "estimated"++ # Hard safety valve: force compression at an extreme message count regardless of tokens,+ # breaking the disconnect → no token data → no compression spiral. 5000 clears 1M+ sessions.+ _needs_compress = _approx_tokens >= _compress_token_threshold or _msg_count >= hs.hard_msg_limit++ if _needs_compress:+ # DB-backed cooldown (shared with context_compressor.py): survives gateway restarts, so a+ # failing compression is not re-triggered on every restart.+ # The in-memory dict was reset on every restart, re-triggering the same failing compression and+ # wedging session storage (#74136).+ _session_db = getattr(self, "_session_db", None)+ _getter = getattr(getattr(_session_db, "_db", _session_db), "get_compression_failure_cooldown", None)+ if _getter is not None:+ _cooldown_state = None+ with suppress(Exception):+ _cooldown_state = _getter(session_entry.session_id)+ if _cooldown_state and _cooldown_state.get("remaining_seconds", 0) > 0:+ logger.info(+ "Session hygiene: skipping compression for %s; "+ "previous failure cooldown active for %.1fs",+ session_entry.session_id, _cooldown_state["remaining_seconds"],+ )+ _needs_compress = False++ if _needs_compress and await self._session_has_compression_in_flight(session_key):+ # A prior compression still holds the durable lock (e.g. a shielded worker left by /stop):+ # another attempt would wait up to 600s behind a commit the fence will refuse.+ logger.info(+ "Session hygiene: skipping compression for %s; "+ "another compression is already in flight", session_entry.session_id,+ )+ _needs_compress = False++ if _needs_compress:+ logger.info(+ "Session hygiene: %s messages, ~%s tokens (%s) — auto-compressing "+ "(threshold: %s%% of %s = %s tokens)",+ _msg_count, f"{_approx_tokens:,}", _token_source,+ int(hs.threshold_pct * 100), f"{_hyg_context_length:,}", f"{_compress_token_threshold:,}",+ )+ return self._HygienePlan(_needs_compress, _approx_tokens, _msg_count, _warn_token_threshold)++ async def _hmwa_hygiene_wait_for_summary(self, attempt, hs, session_entry):+ """Progress-aware inline wait for the detached hygiene compressor. Returns the compressed+ transcript; raises ``HygieneTurnHoldExceeded`` (turn-hold budget) or+ ``asyncio.TimeoutError`` (idle/ceiling/fence cancel) for the caller's handlers.++ Idle timeout (fence ticks per streamed token) + hard ceiling + turn-hold cap."""+ from gateway.run import HygieneTurnHoldExceeded, hygiene_wait_should_extend+ fence = attempt.commit_fence+ while True:+ if fence.is_cancelled:+ raise asyncio.TimeoutError+ # Charge the idle budget from the LAST PROGRESS event, else silence can approach 2x timeout.+ _hyg_waited = time.monotonic() - attempt.wait_started+ _slice = min(+ max(hs.timeout_seconds - fence.seconds_since_progress(), 0.005),+ max(hs.total_ceiling_seconds - _hyg_waited, 0.005),+ )+ # Cap the slice at the remaining turn-hold budget so a continuously-streaming worker can't+ # hold the turn until the ceiling. Budget exhausted → immediate timeout → abandonment.+ _turn_hold_remaining = hs.max_turn_hold_seconds - (time.monotonic() - attempt.wait_started)+ _slice = 0.005 if _turn_hold_remaining <= 0 else min(_slice, max(_turn_hold_remaining, 0.005))+ # Short poll so a /stop or /restart cancel is not stuck behind a full idle window.+ _idle_left = max(hs.timeout_seconds - fence.seconds_since_progress(), 0.005)+ _slice = min(_slice, 0.25)+ try:+ _compressed, _ = await asyncio.wait_for(asyncio.shield(attempt.future), timeout=_slice)+ return _compressed+ except asyncio.TimeoutError:+ if fence.is_cancelled:+ raise+ _hyg_waited = time.monotonic() - attempt.wait_started+ _idle = fence.seconds_since_progress()+ # Never hold the TURN past the budget even while the summary streams: proceed on the+ # uncompressed transcript so the wire never trips a transport idle-timeout.+ if _hyg_waited >= hs.max_turn_hold_seconds:+ logger.info(+ "Session hygiene compression for session %s exceeded the turn-hold "+ "budget (%.1fs >= %.1fs) — abandoning inline wait, proceeding "+ "without compression this turn",+ session_entry.session_id, _hyg_waited, hs.max_turn_hold_seconds,+ )+ raise HygieneTurnHoldExceeded(+ f"turn-hold budget {hs.max_turn_hold_seconds:.1f}s "+ f"elapsed after {_hyg_waited:.1f}s"+ )+ if hygiene_wait_should_extend(+ idle=_idle, timeout=hs.timeout_seconds, waited=_hyg_waited,+ ceiling=hs.total_ceiling_seconds, fence_cancelled=fence.is_cancelled,+ ):+ if _slice >= _idle_left - 1e-9:+ logger.info(+ "Session hygiene compression for session %s still streaming after "+ "%.0fs (last progress %.1fs ago) — extending wait (ceiling %.0fs)",+ session_entry.session_id, _hyg_waited, _idle, hs.total_ceiling_seconds,+ )+ continue+ raise++ async def _hmwa_hygiene_cancel_or_adopt(self, attempt, context):+ """Cancel the worker at the commit fence; on success release its lease and defer agent+ cleanup, returning ``None``. When the worker already crossed into its commit, consume and+ return the compressed transcript instead (a successful compaction is never a timeout; the+ turn may be held past the budget by up to the commit duration — by design). The lock-free+ ``commit_in_flight`` marker keeps the poll from spinning on a hung commit."""+ fence = attempt.commit_fence+ while not fence.commit_in_flight:+ cancelled = fence.try_cancel_before_commit()+ if cancelled is None:+ await asyncio.sleep(0.025)+ elif cancelled:+ fence.release_cancelled_compression_lock()+ self._hmwa_hygiene_defer_cleanup(attempt, context)+ return None+ else:+ break+ _compressed, _ = await attempt.future+ return _compressed++ def _hmwa_hygiene_defer_cleanup(self, attempt, context):+ """Hand the agent's cleanup to the still-running worker future and mark it deferred."""+ self._defer_agent_cleanup_until_future_done(attempt.future, attempt.agent, context=context)+ attempt.cleanup_deferred = True++ @staticmethod+ def _hmwa_hygiene_stamp(agent, desc, provenance_name, debug_label):+ from agent.session_activity import ActivityProvenance+ from gateway.run import _stamp_hygiene_compression_provenance+ _stamp_hygiene_compression_provenance(agent, desc, getattr(ActivityProvenance, provenance_name), debug_label)++ async def _hmwa_hygiene_notify(self, source, meta, message, what):+ """Best-effort user notice on the hygiene thread; failure is logged, never raised."""+ try:- _adapter = self._adapter_for_source(source)++ _adapter = self._delivery_adapter_for(source)+ if _adapter and source.chat_id:- await _adapter.send(source.chat_id, message, metadata=meta)++ await _adapter.emit_warning(source.chat_id, message, metadata=meta,++ logical_platform=source.platform)+ except Exception as _werr:+ logger.warning("Failed to deliver %s to user: %s", what, _werr)++ async def _hmwa_hygiene_record_failure_cooldown(self, hs, session_key, session_id, reason):+ """Escalate the failure streak (off-loop) and persist the cooldown, when enabled."""+ from gateway.run import _hygiene_cooldown_for_failure, _record_hygiene_cooldown+ if hs.failure_cooldown_seconds < 0:+ return+ _hyg_cooldown = await asyncio.to_thread(+ _hygiene_cooldown_for_failure, self, session_key, hs.failure_cooldown_seconds,+ )+ _record_hygiene_cooldown(self, session_id, _hyg_cooldown, reason)++ async def _hmwa_hygiene_on_turn_hold(self, attempt, hs, session_entry, session_key, source):+ """``except HygieneTurnHoldExceeded`` body: keep or cancel the worker's commit admission,+ notify the user, and re-raise; returns the compressed transcript only when the worker+ was already committing.++ Turn-hold expiry is an availability boundary, not a failure: the streak must NOT advance,+ only flat retry spacing is recorded. A watermark-fenced commit (rows appended after+ compression start survive as cloned tail) KEEPS admission: the turn proceeds uncompressed+ now and the summary is adopted at the worker's fenced commit — always cancelling burned+ every attempt for thinking summary models. Without the fence a late commit could clobber+ newer turns, so cancel."""+ from gateway.run import (+ _HYGIENE_TURNHOLD_RETRY_SECONDS, _record_hygiene_cooldown, _reset_hygiene_failure_streak+ )+ fence = attempt.commit_fence+ _hyg_keep_admission = bool(getattr(fence, "commit_watermark_fenced", False)) and not fence.is_cancelled+ if _hyg_keep_admission:+ self._hmwa_hygiene_defer_cleanup(attempt, "session hygiene turn-hold")+ # NO retry-after here (it would also block the agent-side preflight compressor); spacing+ # comes from the durable compression lock. The done-callback records the flat retry-after+ # ONLY if the worker ends without committing anything.+ _sid, _skey, _agent = session_entry.session_id, session_key, attempt.agent++ def _hyg_adopt_or_space_retry(_fut, _gw=self, _sid=_sid, _skey=_skey, _agent=_agent):+ try:+ _exc = _fut.exception()+ except (asyncio.CancelledError, Exception):+ _committed = False+ else:+ _committed = _exc is None and (+ bool(getattr(_agent, "_last_compaction_in_place", False))+ or getattr(_agent, "session_id", _sid) != _sid+ )+ if _committed:+ logger.info(+ "Session hygiene compression for session %s finished after the "+ "turn-hold was released — summary adopted at the watermark-fenced "+ "commit boundary (#97963)", _sid,+ )+ try:+ _reset_hygiene_failure_streak(_gw, _skey)+ except Exception as _rs_err:+ logger.debug("hygiene streak reset after deferred adoption failed: %s", _rs_err)+ else:+ # Nothing to adopt (summary failed / fence refused / superseded): flat spacing so+ # sustained traffic doesn't spawn and abandon a compressor every turn.+ _record_hygiene_cooldown(+ _gw, _sid, _HYGIENE_TURNHOLD_RETRY_SECONDS,+ "hygiene compression deferred: turn-hold budget expired and the "+ "detached attempt did not commit",+ )++ attempt.future.add_done_callback(_hyg_adopt_or_space_retry)+ _log_suffix = (+ " — the watermark-fenced worker keeps its commit admission and the summary "+ "will be adopted when it finishes"+ )+ else:+ _adopted = await self._hmwa_hygiene_cancel_or_adopt(attempt, "session hygiene turn-hold")+ if _adopted is not None:+ return _adopted+ # Short flat retry-after, else every turn re-spawns, holds and cancels a compressor.+ _record_hygiene_cooldown(+ self, session_entry.session_id, _HYGIENE_TURNHOLD_RETRY_SECONDS,+ "hygiene compression deferred: turn-hold budget expired while the "+ "summary was still streaming",+ )+ _log_suffix = ""+ self._hmwa_hygiene_stamp(+ attempt.agent, "session hygiene compression turn-hold",+ "AGENT_COMPRESSION_TURNHOLD", "hygiene compression turn-hold activity stamp failed",+ )+ logger.info(+ "Session hygiene compression for session %s exceeded turn-hold budget (%.1fs); "+ "proceeding without compression this turn%s",+ session_entry.session_id, time.monotonic() - attempt.wait_started, _log_suffix,+ )+ await self._hmwa_hygiene_notify(+ source, attempt.meta, t("gateway.compress.turnhold_deferred"), "compression-turnhold notice",+ )+ raise++ async def _hmwa_hygiene_on_timeout(self, attempt, hs, session_entry, session_key, source):+ """``except asyncio.TimeoutError`` body: cancel at the commit fence, record the failure+ cooldown, warn the user, and re-raise; returns the compressed transcript only when the+ worker crossed the commit boundary first."""+ from gateway.run import _hygiene_compression_timeout_message+ fence = attempt.commit_fence+ _hyg_waited = time.monotonic() - attempt.wait_started+ _hyg_total_exhausted = _hyg_waited >= hs.total_ceiling_seconds or fence.deadline_exceeded+ if _hyg_total_exhausted:+ # The worker checks this deadline between digest calls; keep its lease until it exits so+ # an unchanged session cannot overlap a retry (the release below is then a no-op).+ fence.retain_compression_lock_until_worker_done()+ # Capture fence state BEFORE try_cancel (which itself sets is_cancelled).+ _hyg_fence_cancelled = fence.is_cancelled+ _adopted = await self._hmwa_hygiene_cancel_or_adopt(attempt, "session hygiene timeout")+ if _adopted is not None:+ return _adopted+ await self._hmwa_hygiene_record_failure_cooldown(+ hs, session_key, session_entry.session_id,+ "session hygiene compression " + (+ "cancelled at commit fence" if _hyg_fence_cancelled+ else "total ceiling exhausted" if _hyg_total_exhausted+ else "timed out with no output from the summary model"+ ),+ )+ self._hmwa_hygiene_stamp(+ attempt.agent,+ "session hygiene compression cancelled at commit fence" if _hyg_fence_cancelled+ else "session hygiene compression timed out",+ "AGENT_COMPRESSION_TIMEOUT", "hygiene compression timeout activity stamp failed",+ )+ if _hyg_fence_cancelled:+ logger.warning(+ "Session hygiene compression for session %s was cancelled at the "+ "commit fence; continuing without compression", session_entry.session_id,+ )+ raise+ _hyg_elapsed = time.monotonic() - attempt.wait_started+ if _hyg_total_exhausted:+ logger.warning(+ "Session hygiene compression for session %s reached its total ceiling after "+ "%.1fs (progress observed=%s); continuing without compression",+ session_entry.session_id, _hyg_elapsed, fence.progress_observed,+ )+ else:+ logger.warning(+ "Session hygiene compression for session %s made no progress for %.1fs "+ "(total wait %.1fs, ceiling %.1fs); continuing without compression",+ session_entry.session_id, fence.seconds_since_progress(), _hyg_elapsed, hs.total_ceiling_seconds,+ )+ await self._hmwa_hygiene_notify(+ source, attempt.meta,+ _hygiene_compression_timeout_message(+ total_exhausted=_hyg_total_exhausted, elapsed=_hyg_elapsed,+ idle_timeout=hs.timeout_seconds, progress_observed=fence.progress_observed,+ ),+ "compression-timeout warning",+ )+ raise++ def _hmwa_hygiene_on_unwind(self, attempt, hs, session_entry, session_key):+ """``except BaseException`` body (caller re-raises): revoke commit admission BEFORE the host+ unwinds so the detached worker can never commit later, and record a cooldown — otherwise+ the next turn re-arms hygiene and waits up to 600s behind a fence that refuses again."""+ from gateway.run import _hygiene_cooldown_for_failure, _record_hygiene_cooldown+ attempt.commit_fence.revoke_commit_admission()+ if not attempt.cleanup_deferred:+ self._hmwa_hygiene_defer_cleanup(attempt, "session hygiene unwind")+ if hs.failure_cooldown_seconds >= 0:+ try:+ _record_hygiene_cooldown(+ self, session_entry.session_id,+ _hygiene_cooldown_for_failure(self, session_key, hs.failure_cooldown_seconds),+ "session hygiene compression cancelled at commit fence",+ )+ except Exception as _cd_err:+ logger.debug("hygiene unwind cooldown record failed: %s", _cd_err)++ async def _hmwa_hygiene_adopt_transcript(+ self, attempt, _compressed, history, plan, *, session_entry, source, _quick_key, run_generation,+ ):+ """Adopt a finished compression (rotation / in-place / refused); publishes the transcript to+ continue with on ``attempt.history``. Returns ``(rotated, in_place, new_count, new_tokens)``.++ Rewrite only on rotation (NEW session id): in-place compaction already soft-archived the+ old rows and rewrite_transcript() would DELETE them; neither rotation nor in-place signals+ FAILURE and an unconditional rewrite would leave only the summary. Write-before-repoint:+ a repoint-then-failed-rewrite would point the live entry at an empty session."""++ from gateway.run_turn import hygiene_no_commit_reason+ from agent.model_metadata import estimate_messages_tokens_rough+ _hyg_agent = attempt.agent+ # _compress_context rotates to a NEW session_id so the old transcript stays intact/searchable.+ _hyg_new_sid = _hyg_agent.session_id+ _hyg_rotated = _hyg_new_sid != session_entry.session_id+ _hyg_in_place = bool(getattr(_hyg_agent, "_last_compaction_in_place", False))+ # Anti-growth guard: refuse a compression that did not shrink the transcript (seen 427K→598K).+ _hyg_in_toks = estimate_messages_tokens_rough(history)+ _hyg_out_toks = estimate_messages_tokens_rough(_compressed)+ if _hyg_rotated and _hyg_out_toks > _hyg_in_toks:+ logger.warning(+ "Gateway hygiene compression for session %s would grow transcript (~%s -> ~%s "+ "tokens); keeping the original transcript unchanged",+ session_entry.session_id, f"{_hyg_in_toks:,}", f"{_hyg_out_toks:,}",+ )+ _hyg_rotated = False+ _compressed = history+ # Only rewrite the transcript when rotation produced a NEW session id. In-place compaction does NOT+ # need a rewrite: archive_and_compact() has already soft-archived the previous active rows and+ # inserted the compacted messages as the new active set inside _compress_context(). Calling+ # rewrite_transcript() after in-place compaction would invoke replace_messages(active_only=False)+ # which DELETEs ALL rows — including the archived turns that archive_and_compact() deliberately+ # preserved (silent data loss, #61145). The danger this guards against (mirrors the /compress fix+ # #44794/#39704): if _compress_context returns a summary but neither rotates nor completes+ # archive_and_compact(), the session_id is unchanged for a FAILURE reason, and an unconditional+ # rewrite_transcript() would DELETE the original messages and replace them with only the compressed+ # summary (permanent data loss, #21301). Write-before-repoint (mirrors manual /compress): if we+ # repointed session_entry onto the child SID and rewrite_transcript then failed (lock/ENOSPC), the+ # live entry would already reference a brand-new empty session while the turn continues — the+ # conversation silently vanishes. Persist the child transcript first; only then rebind the live+ # entry.+ if _hyg_rotated:+ if not await self.async_session_store.rewrite_transcript(_hyg_new_sid, _compressed):+ logger.error(+ "Session hygiene: failed to persist compressed transcript for rotated session "+ "%s → %s; keeping the live entry on the original session so the "+ "conversation is not dropped", session_entry.session_id, _hyg_new_sid,+ )+ # Fail closed: treat like no rotation.+ _hyg_rotated = False+ _hyg_in_place = False+ else:+ session_entry.session_id = _hyg_new_sid+ # The held turn lease follows the rotation (alias keys still serialize on this turn).+ self._rebind_turn_lease(_quick_key, run_generation, _hyg_new_sid)+ await self.async_session_store._save()+ await asyncio.to_thread(+ self._sync_telegram_topic_binding, source, session_entry, reason="hygiene-compression",+ )++ if _hyg_rotated or _hyg_in_place:+ # Rewritten (rotation) or persisted by archive_and_compact() (in-place): reset token count.+ session_entry.last_prompt_tokens = 0+ attempt.history = _compressed+ _new_count = len(_compressed)+ _new_tokens = estimate_messages_tokens_rough(_compressed)+ else:+ # No rewrite happened — post-compression counts equal the pre-compression ones.+ _new_count = plan.msg_count+ _new_tokens = plan.approx_tokens+ logger.warning(- "Gateway hygiene compression for session %s did not rotate or compact in place (no "- "session_db on the hygiene agent) — preserving the original transcript instead "- "of overwriting it with the summary (#21301).", session_entry.session_id,++ "Gateway hygiene compression for session %s did not rotate or compact in place (%s) — "++ "preserving the original transcript instead of overwriting it with the summary (#21301).",++ session_entry.session_id, hygiene_no_commit_reason(_hyg_agent),+ )++ logger.info(+ "Session hygiene: compressed %s → %s msgs, ~%s → ~%s tokens",+ plan.msg_count, _new_count, f"{plan.approx_tokens:,}", f"{_new_tokens:,}",+ )+ if _new_tokens >= plan.warn_token_threshold:+ logger.warning("Session hygiene: still ~%s tokens after compression", f"{_new_tokens:,}")+ return _hyg_rotated, _hyg_in_place, _new_count, _new_tokens++ async def _hmwa_hygiene_apply_result(+ self, attempt, hs, _compressed, history, plan, *,+ session_entry, session_key, source, _quick_key, run_generation,+ ):+ """Adopt a finished hygiene compression, rebind the session + turn lease, record+ streak/cooldown, and warn the user on abort."""+ from gateway.run import _reset_hygiene_failure_streak, hygiene_compaction_recovered+ _hyg_rotated, _hyg_in_place, _new_count, _new_tokens = await self._hmwa_hygiene_adopt_transcript(+ attempt, _compressed, history, plan, session_entry=session_entry, source=source,+ _quick_key=_quick_key, run_generation=run_generation,+ )+ # Summary failure aborts the compressor (nothing dropped). Warn the user visibly — agent.log+ # is invisible on TG/Discord — so they know the chat is "frozen" and can /compress or /reset.+ _comp = getattr(attempt.agent, "context_compressor", None)+ _hyg_aborted = _comp is not None and getattr(_comp, "_last_compress_aborted", False)+ # A fence-cancelled _compress_context returns the original transcript with+ # _last_compress_aborted False: treat that no-op as an abort so hygiene records a cooldown+ # instead of retrying into the 600s wait. A committed rotate/in-place is never an abort.+ _hyg_fence_cancelled = bool(attempt.commit_fence.is_cancelled and not _hyg_rotated and not _hyg_in_place)+ if _hyg_fence_cancelled:+ _hyg_aborted = True+ # Recovery decision lives in the unit-tested predicate: the "neither rotated nor in place"+ # path reuses pre-compression counts, so a numbers-only check would read a no-op as success.+ if not _hyg_aborted and hygiene_compaction_recovered(+ aborted=_hyg_aborted, rotated=_hyg_rotated, in_place=_hyg_in_place,+ msg_count=plan.msg_count, new_count=_new_count, approx_tokens=plan.approx_tokens,+ new_tokens=_new_tokens,+ ):+ await asyncio.to_thread(_reset_hygiene_failure_streak, self, session_key)+ if _hyg_aborted:+ await self._hmwa_hygiene_record_failure_cooldown(+ hs, session_key, session_entry.session_id,+ "session hygiene compression cancelled at commit fence" if _hyg_fence_cancelled+ else getattr(_comp, "_last_summary_error", None),+ )+ self._hmwa_hygiene_stamp(+ attempt.agent, "session hygiene compression aborted",+ "AGENT_COMPRESSION_COOLDOWN", "hygiene compression abort activity stamp failed",+ )+ if not _hyg_fence_cancelled:+ # Force-redact: provider exception text may contain credentials; this reaches users.+ from agent.redact import redact_sensitive_text+ _err = redact_sensitive_text(getattr(_comp, "_last_summary_error", None) or "unknown error", force=True)+ logger.warning("Session hygiene compression aborted: %s", _err)+ await self._hmwa_hygiene_notify(+ source, attempt.meta,+ "⚠️ Shortening the conversation history failed, so I kept everything as-is. "+ "Run /compress to try again or /new to start fresh. If this keeps happening, "+ "run `hermes doctor` on the host.",+ "compression-failure warning",+ )+ # Configured aux model failed, recovered on the main model: only the user can fix that config.+ elif _comp is not None and getattr(_comp, "_last_aux_model_failure_model", None):+ _aux_model = getattr(_comp, "_last_aux_model_failure_model", "")+ _aux_err = getattr(_comp, "_last_aux_model_failure_error", None) or "unknown error"+ await self._hmwa_hygiene_notify(+ source, attempt.meta, f"ℹ️ Configured compression model `{_aux_model}` "+ f"failed ({_aux_err}). Recovered using your main "+ "model — context is intact — but you may want to "+ "check `auxiliary.compression.model` in config.yaml.",+ "aux-model-fallback notice",+ )++ async def _hmwa_hygiene_codex_compaction(self, hs, plan, history, session_entry, session_key, _hyg_runtime):+ """codex app-server runtime: the real context is the server-side thread, not the transcript+ mirror. The detached-agent path would only rewrite the mirror and its finally-eviction+ would destroy the live thread (next turn starts blank), so use the cached agent's+ thread/compact/start and KEEP it cached."""+ from gateway.run import run_codex_hygiene_compaction+ # codex app-server runtime: the model's real context is the app-server's server-side thread, not the+ # transcript mirror. See #73503.+ _hyg_codex_auto = "native"+ _hyg_comp_cfg = hs.data.get("compression") if isinstance(hs.data, dict) else None+ if isinstance(_hyg_comp_cfg, dict):+ _hyg_codex_auto = str(_hyg_comp_cfg.get("codex_app_server_auto", "native") or "native")+ _hyg_codex_outcome = await run_codex_hygiene_compaction(+ self, session_key, session_entry.session_id, auto_mode=_hyg_codex_auto, history=history,+ approx_tokens=plan.approx_tokens, timeout_seconds=hs.total_ceiling_seconds,+ failure_cooldown_seconds=hs.failure_cooldown_seconds,+ )+ logger.info(+ "Session hygiene (codex app-server): %s (session=%s, mode=%s, ~%s tokens)",+ _hyg_codex_outcome, session_entry.session_id, _hyg_codex_auto, f"{plan.approx_tokens:,}",+ )++ async def _hmwa_hygiene_build_agent(self, _hyg_model, _hyg_runtime, session_entry):+ """Build the detached hygiene ``AIAgent`` with the live session's system prompt. Returns+ ``(agent, sync_session_db)``."""+ from gateway.run import _GATEWAY_HYGIENE_PLATFORM, _seed_hygiene_system_prompt+ from run_agent import AIAgent+ try:+ _hyg_session_row = await self._session_db.get_session(session_entry.session_id)+ except Exception as exc:+ _hyg_session_row = None+ logger.warning(+ "Session hygiene could not restore the system prompt for session %s: %s. "+ "Preserving an empty prompt so the live turn rebuilds it with its "+ "configured providers.", session_entry.session_id, exc, exc_info=True,+ )+ _hyg_session_db = getattr(self._session_db, "_db", self._session_db)+ # With compression.checkpoint_required on, load the memory provider so the checkpoint exists+ # before any mutation; otherwise keep the fast path (no provider init).+ from hermes_cli.config import load_config as _load_cfg+ from utils import is_truthy_value as _is_truthy++ _hyg_checkpoint_required = _is_truthy(+ ((_load_cfg() or {}).get("compression") or {}).get("checkpoint_required"), default=False,+ )+ _hyg_agent = AIAgent(+ **_hyg_runtime, model=_hyg_model, max_iterations=4, quiet_mode=True,+ skip_memory=not _hyg_checkpoint_required, enabled_toolsets=["memory"],+ session_id=session_entry.session_id, session_db=_hyg_session_db,+ )+ _seed_hygiene_system_prompt(_hyg_agent, _hyg_session_row)+ # A rebuilt (not retained) prompt is deliberately stale for every real gateway surface.+ _hyg_agent.platform = _GATEWAY_HYGIENE_PLATFORM+ return _hyg_agent, _hyg_session_db++ async def _hmwa_hygiene_detached_attempt(+ self, attempt, hs, plan, history, _hyg_msgs, _hyg_model, _hyg_runtime,+ source, session_entry, session_key, _quick_key, run_generation,+ ):+ """Run one detached hygiene compression attempt end to end; publishes the transcript to+ continue with (compressed or original) on ``attempt.history``."""+ from gateway.run import HygieneTurnHoldExceeded+ from agent.conversation_compression import CompressionCommitFence+ _hyg_agent, _hyg_session_db = await self._hmwa_hygiene_build_agent(_hyg_model, _hyg_runtime, session_entry)+ attempt.agent = _hyg_agent+ try:+ # Hygiene owns the session binding, so prefer in-place compaction over minting a+ # continuation child. Without a SessionDB this stays False.+ _hyg_agent.compression_in_place = True+ _bind_hyg_state = getattr(getattr(_hyg_agent, "context_compressor", None), "bind_session_state", None)+ if callable(_bind_hyg_state):+ _bind_hyg_state(_hyg_session_db, session_entry.session_id)+ # Never finalize on close() — that would end the live gateway session row.+ _hyg_agent._end_session_on_close = False+ _hyg_agent._print_fn = lambda *a, **kw: None++ loop = asyncio.get_running_loop()+ _hyg_commit_fence = CompressionCommitFence(total_ceiling_seconds=hs.total_ceiling_seconds)+ # Default executor (NOT self._get_executor): a hung summary must never occupy an+ # agent-work slot. MUST run in the caller's contextvars (multiplex secret scope).+ attempt.commit_fence = _hyg_commit_fence+ attempt.future = loop.run_in_executor(+ None,+ # But it MUST run inside the caller's contextvars: under multiplex_profiles the profile+ # secret scope / HERMES_HOME override live in ContextVars, and a bare run_in_executor worker+ # starts with an empty Context — the summary model's get_secret(<PROVIDER>_API_KEY) then+ # fails closed (UnscopedSecretError) and every hygiene compaction silently degrades to a+ # lossy truncation (#100849 bundle).+ copy_context().run,++ # task_id = the live turn's dedup bucket (session row id), never "" (= reset every task).+ lambda: _hyg_agent._compress_context(+ _hyg_msgs, "", approx_tokens=plan.approx_tokens, commit_fence=_hyg_commit_fence,++ task_id=session_entry.session_id or "default",+ ),+ )+ attempt.wait_started = time.monotonic()+ try:+ _compressed = await self._hmwa_hygiene_wait_for_summary(attempt, hs, session_entry)+ except HygieneTurnHoldExceeded:+ _compressed = await self._hmwa_hygiene_on_turn_hold(attempt, hs, session_entry, session_key, source)+ except asyncio.TimeoutError:+ _compressed = await self._hmwa_hygiene_on_timeout(attempt, hs, session_entry, session_key, source)+ except BaseException:+ self._hmwa_hygiene_on_unwind(attempt, hs, session_entry, session_key)+ raise++ await self._hmwa_hygiene_apply_result(+ attempt, hs, _compressed, history, plan, session_entry=session_entry,+ session_key=session_key, source=source, _quick_key=_quick_key,+ run_generation=run_generation,+ )+ finally:+ # Evict the cached agent so the next turn rebuilds its system prompt.+ self._evict_cached_agent(session_key)+ if not attempt.cleanup_deferred:+ await self._cleanup_agent_resources_off_loop(_hyg_agent, context="session hygiene")++ async def _hmwa_run_session_hygiene(+ self, event, source, session_entry, session_key, history, _quick_key, run_generation,+ ):+ """Auto-compress pathologically large transcripts before the agent starts so oversized+ histories don't cause repeated truncation/context failures. Token source: the API's+ prompt_tokens from the last turn, else a char/4 estimate."""+ from gateway.run import HygieneTurnHoldExceeded+ if not history or len(history) < 4:+ return history++ hs = await self._hmwa_hygiene_settings(source, session_key)+ # Hygiene can never land with compression disabled; a sub-limit transcript is the identity (#111988).+ if not hs.compression_enabled:+ return self._bound_hygiene_payload(history, hs, session_entry)+ plan = await self._hmwa_hygiene_plan(hs, history, session_entry, session_key)+ # No compression this turn (under both thresholds, cooldown, or one already in flight): without+ # the bound the model would get the full uncompressed transcript.+ if not plan.needs_compress:+ return self._bound_hygiene_payload(history, hs, session_entry)++ attempt = self._HygieneAttempt(agent=None, meta=self._event_thread_metadata(event, source), history=history)+ try:+ _hyg_model, _hyg_runtime = self._resolve_session_agent_runtime(+ source=source, session_key=session_key,+ user_config=hs.data if isinstance(hs.data, dict) else None,+ )+ if str(_hyg_runtime.get("api_mode") or "").lower() == "codex_app_server":+ await self._hmwa_hygiene_codex_compaction(hs, plan, history, session_entry, session_key, _hyg_runtime)+ elif _hyg_runtime.get("api_key"):+ # Pass the FULL transcript (tool results included) as the agent loop does: filtering+ # to user/assistant starved the compressor (tool results are the bulk of context).+ _hyg_msgs = [m for m in history if m.get("role") in {"user", "assistant", "tool"}]+ if len(_hyg_msgs) >= 4:+ await self._hmwa_hygiene_detached_attempt(+ attempt, hs, plan, history, _hyg_msgs, _hyg_model, _hyg_runtime,+ source, session_entry, session_key, _quick_key, run_generation,+ )+ except HygieneTurnHoldExceeded:+ # Availability boundary, not a failure — already logged at INFO by the turn-hold handler.+ # Must not hit the generic "auto-compress failed" warning below: that log is how thinking-model+ # deployments read as permanently broken (#97963; surfaced by @686f6c61 in PR #99657).+ pass+ except Exception as e:+ logger.warning("Session hygiene auto-compress failed: %s", e)+ # A landed compression published a NEW transcript on attempt.history: leave it byte-identical.+ # Anything else (turn-hold, timeout, unwind, codex path) left the FULL uncompressed transcript+ # there — that is the fail-closed case (#111988).+ if attempt.history is history:+ return self._bound_hygiene_payload(history, hs, session_entry)+ return attempt.history++ @staticmethod+ def _bound_hygiene_payload(history, hs, session_entry):+ """``bound_model_input_without_hygiene`` over ``hs.hard_msg_limit``, with one INFO line when the+ cut is real. Below the limit this is the identity — no allocation, no behaviour change."""+ from gateway.run_turn import bound_model_input_without_hygiene+ bounded = bound_model_input_without_hygiene(history, hs.hard_msg_limit)+ if bounded is not history:+ logger.info(+ "Session hygiene did not land for %s: bounding the model payload to %s of %s "+ "messages (hard limit %s) — the stored transcript is unchanged",+ session_entry.session_id, len(bounded), len(history), hs.hard_msg_limit,+ )+ return boundeddiff --cc gateway/run_turn_persistence.pyindex cdbb6409720,00000000000..7b0f0bf26fcmode 100644,000000..100644--- a/gateway/run_turn_persistence.py+++ b/gateway/run_turn_persistence.py@@@ -1,565 -1,0 +1,573 @@@+"""Gateway turn persistence phases; inherited by GatewayTurnMixin."""+from __future__ import annotations++import logging+from typing import TYPE_CHECKING+import asyncio+import dataclasses+import inspect+import json+import os+import queue+import threading+import time+from agent.i18n import t++from agent.turn_failure_copy import FAILED_TURN_NOTICE, PARTIAL_FAILED_TURN_NOTICE+from agent.session_activity import format_iteration_progress+from contextlib import nullcontext, suppress+from contextvars import copy_context+from gateway.config import Platform+from gateway.media_repair import repair_explicit_computer_use_media_paths+from gateway.platforms.base import BasePlatformAdapter+from gateway.platforms.event import MessageEvent+from gateway.session import (+ SessionSource, _session_key_namespace, build_channel_continuity_note,+ build_session_context,+)+from gateway.session_transcript import TranscriptReadError+from gateway.turn_context import TurnContext++from gateway.warning_notifications import diagnostic_wake_muted+from gateway.turn_lease import DEFAULT_LEASE_WAIT, TurnLeaseTimeoutError+from hermes_constants import get_hermes_home_override+from pathlib import Path+from typing import Any, Callable, Dict, List, Optional, Tuple+from utils import base_url_hostname++if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)+ from gateway.run import GatewayRunner # noqa: F401+ from gateway.run_turn_runner import TurnRunner # noqa: F401++# Log-record parity with the origin module.+logger = logging.getLogger("gateway.run")+++class GatewayTurnPersistenceMixin:+ async def _hmwa_shape_agent_response(+ self, agent_result, source, history, session_entry, session_key,+ _quick_key, run_generation, _run_start_session_id, _platform_name, _msg_start_time,+ persist_user_display_kind: Optional[str] = None,+ ):+ """Turn the raw agent result into the outbound text: sentinel/silence handling, response+ logging, resume-pending clear, empty-response normalization, and identity-guarded+ post-compression session_id propagation. Returns+ ``(response, _intentional_silence, agent_messages)``."""+ from gateway.run import (+ _is_gateway_hidden_reasoning_incomplete_turn, _normalize_empty_agent_response,+ _sanitize_gateway_final_response, _should_clear_resume_pending_after_turn,+ )+ response = agent_result.get("final_response") or ""+ # Hidden-reasoning-only retry exhaustion: the loop's sentinel text doubles as final_response+ # and would be delivered verbatim (peer agents would ingest it as a completed turn).+ if _is_gateway_hidden_reasoning_incomplete_turn(agent_result):+ response = ""+ _intentional_silence = self._is_intentional_silence(agent_result, response)+ # A queued (/queue) chain's TERMINAL turn owns the silence verdict, not the event that+ # opened the chain: an internal follow-up may go silent, a human one must not.+ from gateway.response_filters import is_machinery_display_kind+ from gateway.run_turn import _UNEXPECTED_SILENCE_REPLY+ _silence_kind = agent_result.get("queued_terminal_display_kind", persist_user_display_kind)+ if _intentional_silence and not is_machinery_display_kind(_silence_kind):+ logger.warning(+ "silence marker rejected on a user turn: platform=%s chat=%s",+ _platform_name, source.chat_id or "unknown",+ )+ _intentional_silence = False+ response = _UNEXPECTED_SILENCE_REPLY++ # "(empty)" = the model produced no visible content after exhausting all retries. One+ # text with the CLI explainer and the desktop (agent/turn_explainers.py) so the user+ # reads the same words on every surface.+ if response == "(empty)" and not _intentional_silence:+ from agent.turn_explainers import EMPTY_RESPONSE_EXPLANATION++ _model = str(agent_result.get("model") or "").strip() or "The model"+ response = "⚠️ " + EMPTY_RESPONSE_EXPLANATION.format(model=_model)+ agent_messages = agent_result.get("messages", [])+ logger.info(+ "response ready: platform=%s chat=%s session=%s time=%.1fs api_calls=%d response=%d chars",+ _platform_name, source.chat_id or "unknown", session_key or "unknown",+ time.time() - _msg_start_time, agent_result.get("api_calls", 0), len(response),+ )++ # Successful turn: clear the consecutive-restart stuck-loop counter and resume_pending (set+ # by drain-timeout shutdown) so later messages don't get the restart-interruption note.+ if session_key and _should_clear_resume_pending_after_turn(agent_result):+ await self._clear_restart_failure_count(session_key)+ try:+ await self.async_session_store.clear_resume_pending(session_key)+ except Exception as _e:+ logger.debug("clear_resume_pending failed for %s: %s", session_key, _e)++ # Normalize empty responses: surface errors, partial failures, and work-without-text.+ # Fix for #18765.+ if not _intentional_silence:+ response = _normalize_empty_agent_response(agent_result, response, history_len=len(history))+ response = _sanitize_gateway_final_response(source.platform, response)++ # The agent thread already updated the contextvar; propagate to SessionEntry + _save() only+ # if the binding still points at the session this run was launched against.+ if agent_result.get("session_id") and agent_result["session_id"] != session_entry.session_id:+ if session_entry.session_id == _run_start_session_id:+ session_entry.session_id = agent_result["session_id"]+ # The held turn lease follows the rotation (persistence writes to the NEW id).+ self._rebind_turn_lease(_quick_key, run_generation, session_entry.session_id)+ await self.async_session_store._save()+ await self.async_session_store._record_gateway_session_peer(+ session_entry.session_id, session_key, source,+ )+ await asyncio.to_thread(+ self._sync_telegram_topic_binding, source, session_entry, reason="agent-result-compression",+ )+ else:+ logger.info(+ "Skipping agent-result session split sync for %s because the session binding "+ "moved from %s to %s before compression finished",+ session_key or "?", _run_start_session_id, session_entry.session_id,+ )+ return response, _intentional_silence, agent_messages++ # reasoning_style → (header line, per-line quote prefix for blank / non-blank lines)+ _REASONING_QUOTE_STYLES = {+ "subtext": ("-# 💭 Reasoning", "-# ", "-#"), "blockquote": ("> 💭 **Reasoning:**", "> ", ">")+ }++ def _hmwa_prepend_reasoning(self, agent_result, response, source, _intentional_silence):+ """Prepend the last reasoning block when show_reasoning is on for this platform. Mattermost+ requires an explicit per-platform opt-in (scratch text, not final-answer content)."""+ from gateway.run import _load_gateway_config, _platform_config_key, _resolve_gateway_display_bool+ try:+ _show_reasoning_effective = _resolve_gateway_display_bool(+ _load_gateway_config(), _platform_config_key(source.platform), "show_reasoning",+ default=bool(getattr(self, "_show_reasoning", False)), platform=source.platform,+ require_platform_override_for={Platform.MATTERMOST},+ )+ except Exception:+ _show_reasoning_effective = (+ False if source.platform == Platform.MATTERMOST else getattr(self, "_show_reasoning", False)+ )+ last_reasoning = agent_result.get("last_reasoning")+ if not (_show_reasoning_effective and response and not _intentional_silence and last_reasoning):+ return response+ from gateway.stream_consumer_fences import escape_code_fences_for_display+ # Collapse long reasoning to keep messages readable+ lines = last_reasoning.strip().splitlines()+ if len(lines) > 15:+ display_reasoning = "\n".join(lines[:15]) + f"\n_... ({len(lines) - 15} more lines)_"+ else:+ display_reasoning = last_reasoning.strip()+ # Per-platform render style: Discord defaults to "-# " subtext, others keep the code block.+ try:+ from gateway.display_config import resolve_display_setting+ _reasoning_style = resolve_display_setting(+ _load_gateway_config(), _platform_config_key(source.platform), "reasoning_style", "code",+ )+ except Exception:+ _reasoning_style = "code"+ _quote = self._REASONING_QUOTE_STYLES.get(_reasoning_style)+ if _quote:+ header, prefix, empty = _quote+ _quoted = "\n".join(f"{prefix}{ln}" if ln else empty for ln in display_reasoning.splitlines())+ return f"{header}\n{_quoted}\n\n{response}"+ # Escape ``` inside reasoning so inner fences don't break the outer code block.+ display_reasoning = escape_code_fences_for_display(display_reasoning)+ return f"💭 **Reasoning:**\n```\n{display_reasoning}\n```\n\n{response}"++ def _hmwa_runtime_footer_line(self, agent_result, source, _turn_seconds):+ """Runtime-metadata footer for the FINAL message of the turn; off by default+ (display.runtime_footer.enabled=false)."""+ from gateway.run import _load_gateway_config, _platform_config_key, _terminal_scope_cwd+ try:+ from gateway.runtime_footer import build_footer_line as _bfl+ return _bfl(+ user_config=_load_gateway_config(),+ platform_key=_platform_config_key(source.platform), model=agent_result.get("model"),+ context_tokens=agent_result.get("last_prompt_tokens", 0) or 0,+ context_length=agent_result.get("context_length") or None,+ cwd=_terminal_scope_cwd(""), turn_seconds=_turn_seconds,++ requested_model=agent_result.get("requested_model"),++ served_model=agent_result.get("served_model"),+ )+ except Exception as _footer_err:+ logger.debug("runtime_footer build failed: %s", _footer_err)+ return ""++ async def _hmwa_post_turn_hooks(self, hook_ctx, agent_result, response):+ """agent:end hook, process-watcher scheduling, and watch-notification drain."""+ await self.hooks.emit("agent:end", {+ **hook_ctx, "response": (response or "")[:500], "model": agent_result.get("model", ""),+ "provider": agent_result.get("provider", ""),+ })++ # Pending process watchers (check_interval on background processes)+ try:+ from tools.process_registry import process_registry+ # Detach the batch atomically (reassign, not clear()) so concurrent appends aren't dropped.+ watchers = process_registry.pending_watchers+ process_registry.pending_watchers = []+ for i, watcher in enumerate(watchers):+ asyncio.create_task(self._run_process_watcher(watcher))+ if i % 100 == 99:+ await asyncio.sleep(0)+ except Exception as e:+ logger.error("Process watcher setup error: %s", e)++ # Drain watch notifications that arrived during the run; the queue also carries process /+ # async-delegation completions owned elsewhere — inject only watch-type events.+ try:+ from tools.process_registry import process_registry as _pr+ await self._drain_watch_notifications(_pr.completion_queue)+ except Exception as e:+ logger.debug("Watch queue drain error: %s", e)+- _FAILED_TURN_NOTICE = (- "Your request was not processed. Send it again if you still want me to carry it out."- )- _PARTIAL_FAILED_TURN_NOTICE = (- "This turn did not complete. Some actions may already have run; verify their effects "- "before resending."- )++ # One owner for the boundary copy (agent/turn_failure_copy.py): the core closer in++ # agent/conversation_loop.py writes the same row on the paths that never reach this layer.++ def _hmwa_add_failed_turn_notice(self, response, notice):+ """Make failed-turn delivery explicit without replacing the provider-specific guidance."""+ response = str(response or "").strip()+ return f"{response}\n\n{notice}" if response else notice++ def _hmwa_failed_turn_notice(self, agent_result):+ """Choose retry guidance without assuming completed tool effects can be repeated safely."""+ from gateway.media_repair import _current_turn_messages+ # Compression during the failed turn can move the slice boundary; the shared helper falls+ # back to the last user row so tool evidence is not silently dropped.+ turn_messages = _current_turn_messages(+ agent_result.get("messages", []) or [], agent_result.get("history_offset", 0),+ )+ if any(+ message.get("role") == "tool"+ or (message.get("role") == "assistant" and message.get("tool_calls"))+ for message in turn_messages+ ):- return self._PARTIAL_FAILED_TURN_NOTICE- return self._FAILED_TURN_NOTICE++ return PARTIAL_FAILED_TURN_NOTICE++ return FAILED_TURN_NOTICE++ async def _hmwa_close_failed_turn(self, session_id, notice):+ """Append the gateway-owned assistant boundary iff the durable tail is an open user row.++ The tail, not "did the gateway write the user row", is the key: on the primary path the+ agent's turn-start flush already persisted the row (so the platform-id dedupe skips the+ gateway write), and a platform redelivery of an already-closed turn must not stack a+ second assistant row."""+ if await self.async_session_store.transcript_tail_role(session_id) != "user":+ return+ await self.async_session_store.append_to_transcript(session_id, {+ "role": "assistant", "content": notice, "timestamp": time.time(),+ })++ def _hmwa_classify_turn_failure(self, agent_result, history, session_entry):+ """Classify a finished turn for transcript persistence. Returns+ ``(agent_failed_early, hidden_reasoning_incomplete, is_context_overflow_failure)``.++ Context-overflow failures must NOT persist the user message (session would grow and+ reproduce the failure forever); transient failures (429/timeout/5xx) DO."""+ from gateway.run import _is_gateway_hidden_reasoning_incomplete_turn+ # Save the full conversation to the transcript, including tool calls. This preserves the complete+ # agent loop (tool_calls, tool results, intermediate reasoning) so sessions can be resumed with full+ # context and transcripts are useful for debugging and training data. IMPORTANT: For+ # context-overflow failures (compression exhausted, generic 400 on large sessions) we must NOT+ # persist the user's message — doing so would grow the session further and cause the same failure on+ # the next attempt, an infinite loop. (#1630, #9893) Transient failures (429, timeout, connection+ # error, provider 5xx) are different: the session is not oversized, and silently dropping the user+ # message causes severe context loss on retry — the agent forgets what was just asked. Persist the+ # user turn so the conversation is preserved. (#7100)+ agent_failed_early = bool(agent_result.get("failed"))+ hidden_reasoning_incomplete = _is_gateway_hidden_reasoning_incomplete_turn(agent_result)+ from gateway.run_turn import is_context_overflow_failure_result+ is_context_overflow_failure = is_context_overflow_failure_result(agent_result, len(history))+ if is_context_overflow_failure:+ logger.info(+ "Skipping transcript persistence for context-overflow "+ "failure in session %s to prevent session growth loop.", session_entry.session_id,+ )+ elif agent_failed_early:+ logger.info(+ "Transient agent failure in session %s — persisting user "+ "message so conversation context is preserved on retry.", session_entry.session_id,+ )+ elif hidden_reasoning_incomplete:+ logger.warning(+ "Suppressing hidden-reasoning-only incomplete gateway turn for session %s: %s",+ session_entry.session_id, agent_result.get("error", "processing incomplete"),+ )+ return agent_failed_early, hidden_reasoning_incomplete, is_context_overflow_failure++ async def _hmwa_compression_exhaustion_reset(+ self, agent_result, response, session_entry, session_key, source,+ ):+ """Auto-reset a permanently oversized session so the next message starts fresh instead of+ replaying the oversized context forever. Never on a lock-contended defer — that is the+ OPPOSITE case (a concurrent path holds the lock and is shrinking it). Returns+ ``(response, session_entry)``."""+ # When compression is exhausted, the session is permanently too large to process. (#9893) Never wipe+ # the session for that — retry-next-message semantics apply (#69870 lock-skip consumer; salvaged+ # from #49874).+ if agent_result.get("compression_deferred"):+ logger.info(+ "Compression deferred for session %s — the compression "+ "lock is held by a concurrent compressor. Keeping the "+ "session intact; the next message retries normally.",+ session_entry.session_id if session_entry else "?",+ )+ elif agent_result.get("compression_exhausted") and session_entry and session_key:+ logger.info("Auto-resetting session %s after compression exhaustion.", session_entry.session_id)+ new_entry = await self.async_session_store.reset_session(session_key)+ self._evict_cached_agent(session_key)+ # Conversation boundary: the funnel clears every conversation-scoped per-session dict.+ self._clear_conversation_scope(session_key, reason="compression_exhausted_reset")+ if new_entry is not None:+ # Re-point the Telegram topic binding at the fresh session, or the binding-heal walk+ # switches the next message back onto the bloated child and re-triggers exhaustion+ # forever. No-op on non-topic lanes.+ # Compression rotated session_entry.session_id to the oversized compressed child earlier+ # this turn (the agent-result sync above), and that _sync also rewrote the (chat_id,+ # thread_id) -> bloated-child binding. reset_session swaps in a clean, parentless session,+ # but without re-syncing the binding the next inbound message in this topic gets+ # switch_session'd back onto the bloated child by the binding-heal walk, reloads the+ # oversized transcript, and re-triggers compression exhaustion forever (#35809 — regression+ # of the #9893/#10063 auto-reset).+ session_entry = new_entry+ await asyncio.to_thread(+ self._sync_telegram_topic_binding, source, session_entry, reason="compression-exhausted-reset",+ )+ response = (response or "") + (+ "\n\n🔄 Session auto-reset — the conversation exceeded the maximum context size and "+ "could not be compressed further. Your next message will start a fresh session."+ )+ return response, session_entry++ @staticmethod+ def _hmwa_user_transcript_entry(event, prepared, ts):+ """Transcript row for the inbound user turn (clean text + event time when captured)."""+ # Transient failure (429/timeout/5xx): persist only the user message so the next message can load a+ # transcript that reflects what was said. Skip the assistant error text since it's a+ # gateway-generated hint, not model output. Hidden- reasoning-only incomplete turns follow the same+ # persistence rule so peer-agent channels don't ingest them as completed assistant turns. (#7100,+ # #51628)+ _user_entry = {+ "role": "user",+ "content": (+ prepared.persist_user_message if prepared.persist_user_message is not None+ else prepared.message_text+ ),+ "timestamp": prepared.persist_user_timestamp if prepared.persist_user_timestamp is not None else ts,+ }+ if prepared.persist_user_display_kind:+ _user_entry["display_kind"] = prepared.persist_user_display_kind+ if prepared.persistence_owner:+ _user_entry["display_metadata"] = {"gateway_input_owner": prepared.persistence_owner}+ if getattr(event, "message_id", None):+ _user_entry["message_id"] = str(event.message_id)+ return _user_entry++ async def _hmwa_persist_turn_transcript(+ self, *, event, source, session_entry, session_key, agent_result, agent_messages,+ prepared, response, agent_failed_early, hidden_reasoning_incomplete, is_context_overflow_failure,+ ):+ """Persist this turn to the transcript (session_meta on first turn, user-only on transient+ failure, nothing on context overflow), update last_prompt_tokens, and re-baseline the+ cached agent's message count."""+ from gateway.run import _resolve_gateway_model+ ts = time.time() # Unix epoch float — consistent with DB storage+ store = self.async_session_store+ sid = session_entry.session_id+ history = prepared.history+ # The agent already persisted this turn's rows (codex app-server reports agent_persisted=True+ # too); skip the DB write. Default = a session DB exists; non-persisting runtimes pass False.+ # The agent already persisted these messages to SQLite via _flush_messages_to_session_db(), so skip+ # the DB write here to prevent the duplicate-write bug (#860 / #42039). This holds for the codex+ # app-server runtime too: although it early-returns and bypasses conversation_loop's per-step+ # flushes, it flushes its own projected assistant/tool messages before returning and reports+ # agent_persisted=True (see agent/codex_runtime.py). Reading the flag (default = self._session_db is+ # not None) keeps the persistence contract explicit and lets any future non-persisting runtime opt+ # into a gateway-side write by returning False.+ agent_persisted = agent_result.get("agent_persisted", self._session_db is not None)+ _user_row = self._hmwa_user_transcript_entry(event, prepared, ts)++ if is_context_overflow_failure:+ pass # Skip all transcript writes — don't grow a broken session+ else:+ if not history:+ # Fresh session: the tool definitions (as sent in the API request) make the transcript+ # self-describing.+ await store.append_to_transcript(sid, {+ "role": "session_meta",+ "tools": agent_result.get("tools", []) or [],+ "model": _resolve_gateway_model(),+ "platform": source.platform.value if source.platform else "",+ "timestamp": ts,+ })+ if agent_failed_early or hidden_reasoning_incomplete:+ # Transient failure / hidden-reasoning incomplete: persist only the user message (the+ # assistant error text is a gateway hint, not model output). Dedupe on platform+ # message_id (Telegram retries after transient failures).+ if event.message_id and await store.has_platform_message_id(sid, str(event.message_id)):+ logger.info(+ "Skipping duplicate user turn (message_id=%s) in session %s",+ event.message_id, sid,+ )+ else:+ await store.append_to_transcript(sid, _user_row, skip_db=agent_persisted)+ # Close the failed turn: a user-only tail lets alternation repair merge this request+ # into an unrelated future message and replay stale side effects (#107070).+ await self._hmwa_close_failed_turn(sid, self._hmwa_failed_turn_notice(agent_result))+ else:+ # Only the NEW messages: history_offset (what the agent saw), not len(history), which+ # counts session_meta entries stripped before the agent saw them.+ history_len = agent_result.get("history_offset", len(history))+ new_messages = agent_messages[history_len:] if len(agent_messages) > history_len else []+ if not new_messages:+ # Edge case: fall back to simple user/assistant rows.+ await store.append_to_transcript(sid, _user_row, skip_db=agent_persisted)+ if response:+ await store.append_to_transcript(+ sid, {"role": "assistant", "content": response, "timestamp": ts},+ skip_db=agent_persisted,+ )+ else:+ # Attach the inbound platform message_id to the first user entry so platform-level+ # quote-resolution (e.g. Yuanbao) can find earlier @bot messages by original id.+ _user_msg_id_attached = False+ for msg in new_messages:+ if msg.get("role") == "system":+ continue # rebuilt each run+ entry = {**msg, "timestamp": ts}+ if (+ not _user_msg_id_attached+ and msg.get("role") == "user"+ and event.message_id+ and "message_id" not in entry+ ):+ entry["message_id"] = str(event.message_id)+ _user_msg_id_attached = True+ await store.append_to_transcript(sid, entry, skip_db=agent_persisted)++ # The agent persists token counts/model itself; keep only last_prompt_tokens for hygiene.+ await store.update_session(+ session_entry.session_key, last_prompt_tokens=agent_result.get("last_prompt_tokens", 0),+ touch_activity=not bool(getattr(event, "internal", False)),+ )++ # Re-baseline the cached agent's message_count now that ALL of this turn's writes are done:+ # the coherence guard snapshots at agent-BUILD time, so our own writes would otherwise+ # trigger a rebuild next turn (destroying prompt caching).+ await self._refresh_agent_cache_message_count(session_key, sid)++ async def _hmwa_deliver_turn_response(+ self, event, source, session_entry, session_key, run_generation,+ agent_result, agent_messages, response, _footer_line, _intentional_silence,+ ):+ """Final delivery decisions: intentional silence, voice reply, streamed-turn media/footer.+ Returns the text for the adapter to send, or ``None`` when already delivered."""++ if diagnostic_wake_muted(event):++ return None+ # Intentional silence is a delivery decision: the [SILENT] turn stays persisted (alternation).+ if _intentional_silence:+ logger.info("Suppressing intentional silence marker for session %s", session_entry.session_id)+ response = ""+- adapter = self._adapter_for_source(source)++ adapter = self._delivery_adapter_for(source)+ # Auto voice reply (TTS audio before the text) unless streaming TTS already delivered audio.+ _streaming_tts_done = adapter is not None and bool(+ getattr(adapter, "_streaming_tts_turn_completed", lambda *_a, **_k: False)(session_key, run_generation)+ )+ if not _streaming_tts_done and self._should_send_voice_reply(+ event, response, agent_messages, already_sent=bool(agent_result.get("already_sent")),+ ):+ await self._send_voice_reply(event, response)++ # Streamed responses still need MEDIA: files delivered (chunks carry the tags verbatim). Never+ # skip when the agent failed: the error text is new content streaming didn't show.+ if agent_result.get("already_sent") and not agent_result.get("failed"):- if response and adapter:++ # The queued-follow-up lane uploads this response's attachments itself; re-scanning here++ # would upload every file a second time.++ if response and adapter and not agent_result.get("media_already_delivered"):+ await self._deliver_media_from_response(response, event, adapter)+ # Streaming delivered the body, but the footer was held back (`not already_sent` gate).+ if _footer_line and adapter:+ try:+ await adapter.send(source.chat_id, _footer_line, metadata=self._event_thread_metadata(event, source))+ except Exception as _e:+ logger.debug("trailing footer send failed: %s", _e)+ # Return None so the body isn't sent twice; stash the delivered text on the event for the+ # /loop and /goal hooks that read the return value.+ with suppress(Exception):+ event._streamed_final_response = str(response or "")+ return None++ return response++ # Chat-side next steps keyed by HTTP status; Hermes commands only (/login is the gateway's own- # sign-in, `hermes auth add <provider>` the host equivalent).++ # sign-in, `{relogin}` the profile-aware host equivalent, filled from the turn's agent provider).+ _STATUS_HINTS = {+ 401: (" Your sign-in to the AI model service has expired or the API key is wrong. "- "Use /login here, or run `hermes auth add <provider>` on the host."),++ "Use /login here, or run `{relogin}` on the host."),+ 402: " Your AI model service balance or quota is used up. Top it up on the service's website, or use /model to switch models.",+ 529: " The AI model service is temporarily overloaded. Wait a moment, then use /retry.",+ }++ async def _hmwa_agent_error_reply(self, e, event, source, session_entry, session_key, prepared):+ """``except Exception`` body of the agent turn: stop typing, log, persist the inbound user+ turn once, and build the sanitized user-facing error reply."""+ # Retain Slack thread/workspace routing so a failed turn cannot leave its status visible.+ await self._hmwa_stop_typing_for_turn(event, source)+ logger.exception("Agent error in session %s", session_key)+ status_code = getattr(e, "status_code", None)+ if status_code in {400, 500} and len(prepared.history) > 50:+ # Context overflow / payload too large: a deterministic rejection (#107567), and the same+ # no-grow rule as the persist path (#1630) — nothing is written into an oversized session.+ from gateway.run import _CONTEXT_OVERFLOW_REPLY+ return _CONTEXT_OVERFLOW_REPLY+ # Replay can coalesce inputs; only this input's durable marker establishes ownership.+ try:+ if prepared.message_text is not None and session_entry is not None:+ _owned = await self.async_session_store.has_input_owner(+ prepared.persistence_session_id, prepared.persistence_owner,+ )+ if not _owned:+ await self.async_session_store.append_to_transcript(+ session_entry.session_id, self._hmwa_user_transcript_entry(event, prepared, time.time()),+ )+ # Tool effects are unknown after an exception.- await self._hmwa_close_failed_turn(session_entry.session_id, self._PARTIAL_FAILED_TURN_NOTICE)++ await self._hmwa_close_failed_turn(session_entry.session_id, PARTIAL_FAILED_TURN_NOTICE)+ except Exception:+ logger.debug("Failed to persist inbound user message after agent exception", exc_info=True)+ # Never expose raw exception types/messages to end users (info-leakage risk).+ status_hint = self._STATUS_HINTS.get(status_code, "")- if status_code == 429:++ if status_code == 401:++ from agent.turn_failure_copy import relogin_command_hint++++ _turn_agent = getattr(self._session_state(session_key).turn, "agent", None)++ status_hint = status_hint.format(relogin=relogin_command_hint(getattr(_turn_agent, "provider", None)))++ elif status_code == 429:+ # Plan usage limit (resets on a schedule) vs a transient rate limit+ _err_json = {}+ with suppress(Exception):+ _err_json = e.response.json().get("error", {})+ if not isinstance(_err_json, dict):+ _err_json = {}+ _resets_in = _err_json.get("resets_in_seconds")+ if _err_json.get("type") != "usage_limit_reached":+ status_hint = " You are being rate-limited. Please wait a moment and try again."+ elif _resets_in and _resets_in > 0:+ import math+ status_hint = f" Your plan's usage limit has been reached. It resets in ~{math.ceil(_resets_in / 3600)}h."+ else:+ status_hint = " Your plan's usage limit has been reached. Please wait until it resets."+ elif status_code == 400:+ status_hint = " The AI model service rejected the request."+ return self._hmwa_add_failed_turn_notice(+ f"⚠️ Something went wrong and I couldn't finish this reply.{status_hint}\n"+ "Use /retry to try again, or /new to start a fresh conversation. "+ "Technical details are in the gateway log (`hermes logs`).",- self._PARTIAL_FAILED_TURN_NOTICE,++ PARTIAL_FAILED_TURN_NOTICE,+ )++ def _hmwa_discard_stale_result(self, source, _quick_key, run_generation):+ """A newer run generation superseded this turn: drop its deferred post-delivery callback."""+ logger.info(+ "Discarding stale agent result for %s — generation %d is no longer current",+ _quick_key or "?", run_generation,+ )- self._pop_post_delivery_callback(self._adapter_for_source(source), _quick_key, run_generation)++ self._pop_post_delivery_callback(self._delivery_adapter_for(source), _quick_key, run_generation)diff --cc gateway/run_turn_prepare.pyindex e7f1ef0ea7b,00000000000..43edd8d7954mode 100644,000000..100644--- a/gateway/run_turn_prepare.py+++ b/gateway/run_turn_prepare.py@@@ -1,672 -1,0 +1,685 @@@+"""Gateway turn prepare phases; inherited by GatewayTurnMixin."""+from __future__ import annotations++import logging+from typing import TYPE_CHECKING+import asyncio+import dataclasses+import inspect+import json+import os+import queue+import threading+import time+from agent.i18n import t+from agent.session_activity import format_iteration_progress+from contextlib import nullcontext, suppress+from contextvars import copy_context+from gateway.config import Platform+from gateway.media_repair import repair_explicit_computer_use_media_paths+from gateway.platforms.base import BasePlatformAdapter+from gateway.platforms.event import MessageEvent+from gateway.session import (+ SessionSource, _session_key_namespace, build_channel_continuity_note,+ build_session_context,+)+from gateway.session_transcript import TranscriptReadError+from gateway.turn_context import TurnContext+from gateway.turn_lease import DEFAULT_LEASE_WAIT, TurnLeaseTimeoutError+from hermes_constants import get_hermes_home_override+from pathlib import Path+from typing import Any, Callable, Dict, List, Optional, Tuple+from utils import base_url_hostname++if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)+ from gateway.run import GatewayRunner # noqa: F401+ from gateway.run_turn_runner import TurnRunner # noqa: F401++# Log-record parity with the origin module.+logger = logging.getLogger("gateway.run")+++class GatewayTurnPrepareMixin:+ def _resolve_session_agent_runtime(+ self, *, source: Optional[SessionSource] = None, session_key: Optional[str] = None,+ user_config: Optional[dict] = None,+ ) -> tuple[str, dict]:+ """Resolve model/runtime for a session.++ Priority (highest first): session ``/model`` → ``channel_overrides`` → global config/env+ (``_resolve_gateway_model(user_config)`` and default provider resolution)."""+ from gateway.run import (+ _credential_pool_for_provider, _get_channel_override, _resolve_gateway_model,+ _resolve_runtime_agent_kwargs, _resolve_runtime_agent_kwargs_for_provider,+ )+ from gateway.session_policy import policy_for_source+ policy = policy_for_source(self, source) if source is not None else None+ if policy is not None:+ from hermes_cli.runtime_provider import resolve_runtime_provider+ from gateway.run import _runtime_agent_kwargs+ from gateway.session_policy import launch_key+ from hermes_cli.runtime_provider_custom import _resolve_named_custom_runtime+ from gateway.session_authorities import active_authority+ authority = active_authority(self)+ frozen = policy.config(authority)+ key = launch_key(authority, policy)+ import json+ runtime = _resolve_named_custom_runtime(requested_provider=policy.provider,+ explicit_api_key=key, explicit_base_url=json.loads(policy.request_json).get('base_url'),+ target_model=policy.model, config=frozen)+ if runtime is None:+ if key is None:+ key = frozen.get('model', {}).get('api_key')+ runtime = resolve_runtime_provider(requested=policy.provider,+ explicit_api_key=key, explicit_base_url=policy.base_url, target_model=policy.model)+ return policy.model, _runtime_agent_kwargs(runtime)+ skey = self._resolve_session_key_or_none(source, session_key)++ # Every exit path starts clean: the /model-override fast path returns before the pop below,++ # and hygiene/inbound callers resolve without a turn runner consuming the stash — a stale++ # notice must never attach to another session's next turn (#74349).++ self._pre_agent_fallback_notice = None++ model = _resolve_gateway_model(user_config)+ if skey:+ self._rehydrate_session_model_override(skey)+ _override_state = self._peek_session_state(skey) if skey else None+ override = _override_state.conversation.model_override if _override_state else None+ if override:+ override_model = override.get("model", model)+ override_runtime = {+ k: override.get(k) for k in (+ "provider", "requested_provider", "api_key", "base_url", "api_mode",+ "max_tokens", "credential_pool", "request_overrides", "capabilities",+ )+ }+ override_runtime["capabilities"] = dict(override_runtime["capabilities"] or {})+ if override_runtime.get("api_key"):+ if override_runtime.get("credential_pool") is None:+ override_runtime["credential_pool"] = _credential_pool_for_provider(override.get("provider"))+ logger.debug(+ "Session model override (fast): session=%s config_model=%s -> override_model=%s provider=%s",+ skey or "", model, override_model, override_runtime.get("provider"),+ )+ return override_model, override_runtime+ # No api_key on the override: env-based resolution below, override model/provider on top.+ logger.debug(+ "Session model override (no api_key, fallback): session=%s config_model=%s override_model=%s",+ skey or "", model, override_model,+ )+ else:+ logger.debug(+ "No session model override: session=%s config_model=%s override_keys=%s",+ skey or "", model,+ [+ _key for _key, _st in list(self._sessions_map().items())+ if _st.conversation.model_override is not None+ ][:5] or "[]",+ )++ runtime_kwargs = _resolve_runtime_agent_kwargs()++ # Private notice metadata must never reach an ``AIAgent(**runtime_kwargs)`` spread; the turn++ # runner surfaces it through the agent's one-shot fallback notice (#74349).++ self._pre_agent_fallback_notice = runtime_kwargs.pop("_fallback_notice", None)+ runtime_model = runtime_kwargs.pop("model", None)+ if runtime_model:+ logger.info("Runtime provider supplied explicit model override: %s -> %s", model, runtime_model)+ model = runtime_model++ cfg = getattr(self, "config", None) # getattr: bare object.__new__ test runners+ if cfg and source is not None:+ ch = _get_channel_override(+ cfg, source.platform, str(source.chat_id) if source.chat_id else "",+ thread_id=str(source.thread_id) if getattr(source, "thread_id", None) else None,+ parent_id=str(source.parent_chat_id) if getattr(source, "parent_chat_id", None) else None,+ )+ if ch:+ if ch.model:+ model = ch.model+ if ch.provider:- runtime_kwargs = _resolve_runtime_agent_kwargs_for_provider(ch.provider)++ runtime_kwargs = _resolve_runtime_agent_kwargs_for_provider(ch.provider, target_model=model or None)+ ch_runtime_model = runtime_kwargs.pop("model", None)+ # Adopt the provider's bundled model only when the override named none.+ if ch_runtime_model and not ch.model:+ model = ch_runtime_model++ if override and skey:+ model, runtime_kwargs = self._apply_session_model_override(skey, model, runtime_kwargs)++ # Provider resolved but no model.default (`hermes auth add` without `hermes model`): use the+ # provider's first catalog model.+ if not model and runtime_kwargs.get("provider"):+ with suppress(Exception):+ from hermes_cli.models import get_default_model_for_provider+ model = get_default_model_for_provider(runtime_kwargs["provider"])+ if model:+ logger.info(+ "No model configured — defaulting to %s for provider %s", model, runtime_kwargs["provider"],+ )++ # Final safety net: an empty model (transient config-cache miss) makes every API call 400 and+ # the session goes silent — reuse the last model resolved for this session, else process-wide.+ if not model:+ _lr_state = self._peek_session_state(skey) if skey else None+ _lr_star = self._peek_session_state("*")+ _recovered = (+ (_lr_state.conversation.last_resolved_model if _lr_state else "")+ or (_lr_star.conversation.last_resolved_model if _lr_star else "")+ )+ if _recovered:+ logger.warning(+ "Empty model resolved for session=%s — recovering "+ "last-known-good model %s (config read likely returned "+ "empty; see #35314)", skey or "", _recovered,+ )+ model = _recovered+ else:+ # Cache the good resolution for future recovery turns.+ if skey:+ self._session_state(skey).conversation.last_resolved_model = model+ self._session_state("*").conversation.last_resolved_model = model++ return model, runtime_kwargs++ def _resolve_turn_agent_config(self, user_message: str, model: str, runtime_kwargs: dict) -> dict:+ """Effective model/runtime config for one turn. With `/fast` priority on, fast-mode+ ``request_overrides`` are deep-merged OVER the per-provider ones so both reach the model."""+ from gateway.run import _deep_merge_request_overrides+ from hermes_cli.models import resolve_fast_mode_overrides+ # Tests bind this method onto bare namespaces, so no class-level tables here.+ runtime = {+ k: runtime_kwargs.get(k) for k in (+ "api_key", "base_url", "provider", "requested_provider", "api_mode", "command", "args",+ "credential_pool", "max_tokens", "capabilities",+ )+ }+ runtime["args"] = list(runtime["args"] or [])+ runtime["capabilities"] = dict(runtime["capabilities"] or {})+ base_request_overrides = dict(runtime_kwargs.get("request_overrides") or {})+ route = {+ "model": model,+ "runtime": runtime,+ "signature": (+ model, runtime["provider"], runtime["requested_provider"], runtime["base_url"],+ runtime["api_mode"], runtime["command"], tuple(runtime["args"]),+ ),+ }+ if getattr(self, "_service_tier", None) != "priority":+ # None / auto / cold: the bounded window is applied per request by agent.fast_mode.+ route["request_overrides"] = base_request_overrides+ return route+ try:+ overrides = resolve_fast_mode_overrides(+ route["model"], provider=runtime["provider"], base_url=runtime["base_url"],+ )+ except Exception:+ overrides = None+ # Fast-mode keys (service_tier / speed) are top-level and don't collide with extra_body.+ route["request_overrides"] = _deep_merge_request_overrides(base_request_overrides, overrides or {})+ return route++ def _sync_session_model_from_agent(self, session_id: str, agent: Any) -> None:+ """Persist the runtime model/provider a gateway turn actually used (provider fallback can+ switch them after the row was created). Runs in the ``run_sync`` executor thread, so it+ uses the sync ``SessionDB`` (``_db``), not the AsyncSessionDB forwarder."""+ if not session_id or agent is None or self._session_db is None:+ return+ model = getattr(agent, "model", None)+ if not model:+ return+ runtime = {k: getattr(agent, k, None) for k in ("provider", "base_url", "api_mode")}+ runtime["fallback_active"] = bool(getattr(agent, "_fallback_activated", False))+ runtime = {k: v for k, v in runtime.items() if v not in (None, "")}+ try:+ db = self._session_db._db+ row = db.get_session(session_id)+ if not row:+ return+ # Legacy backfill: canonical Bot Chats created BEFORE the follow_profile_config contract existed+ # carry no marker, yet they are still the plugin-owned forever-DM. The plugin's own identity+ # rule is "the profile's session titled exactly 'Bot Chat'" (UNIQUE(title) makes that an exact+ # registry, and pre-policy rows may be visible OR hidden), so mirror that rule here. Without+ # this, every Bot Chat that already exists in the field stays pinned to its stale stored+ # provider until the user deletes it — the exact live-report shape (#89497 / #94818).+ raw_config = row.get("model_config")+ config = {}+ with suppress(Exception):+ config = json.loads(raw_config) if raw_config else {}+ if not isinstance(config, dict):+ config = {}+ gateway_runtime = dict(config.get("gateway_runtime") or {})+ if row.get("model") == model and all(gateway_runtime.get(k) == v for k, v in runtime.items()):+ return+ config["gateway_runtime"] = runtime+ db.update_session_meta(session_id, json.dumps(config), model=model)+ except Exception:+ logger.debug("Failed to sync gateway session model metadata", exc_info=True)++ async def _hmwa_resolve_session(self, event, source):+ """Resolve ``source`` to its session entry (topic recovery, internal-route guards, Telegram+ topic-binding heal). Returns ``(source, session_entry, session_key)`` or ``None`` to drop+ the event."""+ # Topic-mode DMs: rewrite a stale/foreign thread_id to the user's last-active topic so a+ # cross-topic Reply doesn't fragment the conversation.+ event_metadata = getattr(event, "metadata", None) or {}+ expected_session_key = str(event_metadata.get("gateway_session_key") or "").strip()+ recovered = (await asyncio.to_thread(self._recover_telegram_topic_thread_id, source)+ if not expected_session_key else None)+ if recovered is not None:+ logger.info(+ "telegram topic recovery: chat=%s user=%s %r -> %s",+ source.chat_id, source.user_id, source.thread_id, recovered,+ )+ source = dataclasses.replace(source, thread_id=recovered)+ with suppress(Exception):+ event.source = source++ if expected_session_key:+ derived_session_key = self._session_key_for_source(source)+ if derived_session_key != expected_session_key:+ logger.warning(+ "Dropping internally routed event after route recovery: expected session=%s derived=%s",+ expected_session_key, derived_session_key,+ )+ return++ strict_session = bool(event_metadata.get("gateway_session_strict"))+ pinned_session_id = str(event_metadata.get("gateway_session_id") or "").strip()+ if strict_session:+ session_entry = await self.async_session_store.lookup_by_session_key(expected_session_key)+ if session_entry is None or not pinned_session_id or session_entry.session_id != pinned_session_id:+ logger.warning(+ "Dropping internally routed event: expected session id=%s is no longer current for key=%s",+ pinned_session_id or "missing", expected_session_key or "missing",+ )+ return+ else:+ # Internal wakes observe reset policy without counting as user activity, or periodic+ # notifications keep the routing key alive across every daily/idle boundary.+ session_entry = await self.async_session_store.get_or_create_session(+ source, touch_activity=not bool(getattr(event, "internal", False)),+ )+ session_key = session_entry.session_key+ if not strict_session and pinned_session_id:+ resolved_entry = await self._resolve_async_delegation_session(session_entry, pinned_session_id)+ if resolved_entry is None:+ return+ session_entry = resolved_entry+ self._cache_session_source(session_key, source)+ if await asyncio.to_thread(self._is_telegram_topic_lane, source):+ session_entry = await self._hmwa_heal_telegram_topic_binding(source, session_entry, session_key)+ from gateway.run_heartbeat_acceptance import resolve_heartbeat_owner+ if not await resolve_heartbeat_owner(self, event, session_entry):+ return+ return source, session_entry, session_key++ async def _hmwa_heal_telegram_topic_binding(self, source, session_entry, session_key):+ """Follow the (chat_id, thread_id) topic binding — healed to its compression tip — or record+ a fresh one. Returns the (possibly switched) session entry."""+ binding = None+ try:+ if self._session_db:+ binding = await self._session_db.get_telegram_topic_binding(+ chat_id=str(source.chat_id), thread_id=str(source.thread_id),+ profile_name=self._telegram_topic_profile_name(source),+ )+ except Exception:+ logger.debug("Failed to read Telegram topic binding", exc_info=True)+ if not binding:+ try:+ await asyncio.to_thread(self._record_telegram_topic_binding, source, session_entry)+ except Exception:+ logger.debug("Failed to record Telegram topic binding", exc_info=True)+ return session_entry+ stored_session_id = str(binding.get("session_id") or "")+ bound_session_id = stored_session_id+ # A binding pointing at a pre-compression parent is walked forward to the tip so the next+ # message resumes the compressed child instead of reloading the oversized parent.+ # Returns the input unchanged when the session isn't a compression parent, so this is cheap and+ # safe. See #20470, #29712, #33414.+ if bound_session_id and self._session_db is not None:+ try:+ canonical_session_id = await self._session_db.get_compression_tip(bound_session_id)+ except Exception:+ logger.debug("compression-tip lookup failed for %s", bound_session_id, exc_info=True)+ canonical_session_id = bound_session_id+ if canonical_session_id and canonical_session_id != bound_session_id:+ bound_session_id = canonical_session_id+ if bound_session_id and bound_session_id != session_entry.session_id:+ # Route through SessionStore so the key → id mapping persists and the previous lane- # session ends cleanly (in-place mutation split-brained the JSON index).- switched = await self.async_session_store.switch_session(session_key, bound_session_id)++ # session ends cleanly (in-place mutation split-brained the JSON index). The two DB++ # awaits above are a window for /new or /resume to move the route; the CAS on the++ # snapshot id lets that win instead of being clobbered by a stale binding.++ switched = await self.async_session_store.switch_session(++ session_key, bound_session_id, expected_session_id=session_entry.session_id,++ )+ if switched is not None:+ session_entry = switched+ if bound_session_id and bound_session_id != stored_session_id:+ # The stored binding pointed at a parent: rewrite it to the canonical descendant.+ await asyncio.to_thread(+ self._sync_telegram_topic_binding, source, session_entry, reason="compression-tip-walk",+ )+ return session_entry++ async def _hmwa_open_session(self, session_entry, session_key, source):+ """Consume auto-reset / fresh-reset flags and emit ``session:start`` for new sessions.+ Returns ``(_was_auto_reset, _is_new_session)``."""+ # Consume was_auto_reset immediately so it cannot re-fire and wipe overrides set between turns.+ # Capture and immediately consume was_auto_reset so it does not re-fire on subsequent messages —+ # preventing the cleanup from wiping model/reasoning overrides set between turns (Closes #48031).+ _was_auto_reset = getattr(session_entry, "was_auto_reset", False)+ if _was_auto_reset:+ # Conversation boundary: the funnel clears every conversation-scoped dict; evict the cached+ # agent so context_compressor._previous_summary cannot leak into new summaries.+ # Treat auto-reset as a full conversation boundary — clear every conversation-scoped per-session+ # dict in one funnel call so the fresh session does not inherit the previous conversation's+ # model/reasoning overrides, a queued "/model switched" note, or a stale resolved-model cache+ # (#48031, #58403). See _CONVERSATION_SCOPED_STATE.+ self._clear_conversation_scope(session_key, reason="auto_reset")+ self._evict_cached_agent(session_key)+ session_entry.was_auto_reset = False++ _is_fresh_reset = getattr(session_entry, "is_fresh_reset", False)+ _is_new_session = session_entry.created_at == session_entry.updated_at or _was_auto_reset or _is_fresh_reset+ # Consume is_fresh_reset so it doesn't leak onto later messages in the same session.+ if _is_fresh_reset:+ # See #6508.+ session_entry.is_fresh_reset = False+ if _is_new_session:+ await self.hooks.emit("session:start", {+ "platform": source.platform.value if source.platform else "",+ "user_id": source.user_id,+ "session_id": session_entry.session_id,+ "session_key": session_key,+ })+ return _was_auto_reset, _is_new_session++ async def _hmwa_deliver_auto_reset_notice(self, session_entry, source, turn_sidecar_notes):+ """Stage the auto-reset sidecar note for the agent and notify the user (policy-gated)."""+ from gateway.run import _AUTO_RESET_CONTEXT_NOTES+ reset_reason = getattr(session_entry, 'auto_reset_reason', None) or 'suspended'+ context_note = _AUTO_RESET_CONTEXT_NOTES.get(reset_reason, _AUTO_RESET_CONTEXT_NOTES["suspended"])+ # Long-lived channels: point the agent at the prior same-channel session for session_search.+ try:+ # Returns None (appends nothing) for other platforms or when there's no prior activity to+ # recall. Deterministic — no extra API/DB calls (#36220).+ continuity_note = build_channel_continuity_note(session_entry, source)+ except Exception:+ continuity_note = None+ if continuity_note:+ context_note = context_note + "\n\n" + continuity_note+ turn_sidecar_notes.append(context_note)++ try:+ should_notify = reset_reason == "suspended"- adapter = self._adapter_for_source(source) if should_notify else None++ adapter = self._delivery_adapter_for(source) if should_notify else None+ if adapter:+ notice = (+ "◐ Session reset after being stopped. "+ f"Conversation history cleared.\n"+ f"Use /resume to browse and restore a previous session.\n"+ )+ with suppress(Exception):+ session_info = await asyncio.to_thread(self._reset_notice_session_info, source)+ if session_info:+ notice = f"{notice}\n\n{session_info}"+ await adapter.send(source.chat_id, notice, metadata=self._thread_metadata_for_source(source))+ except Exception as e:+ logger.debug("Auto-reset notification failed (non-fatal): %s", e)++ # was_auto_reset was consumed in _hmwa_open_session; only the reason needs clearing.+ session_entry.auto_reset_reason = None++ def _hmwa_auto_load_skills(self, event, _auto, _quick_key, session_key):+ """Prepend topic/channel-bound skill payload(s) to ``event.text`` on a new session."""+ _skill_names = [_auto] if isinstance(_auto, str) else list(_auto)+ try:+ from agent.skill_commands import _load_skill_payload, _build_skill_message+ _combined_parts: list[str] = []+ _loaded_names: list[str] = []+ for _sname in _skill_names:+ _loaded = _load_skill_payload(_sname, task_id=_quick_key)+ if not _loaded:+ logger.warning("[Gateway] Auto-skill '%s' not found", _sname)+ continue+ _loaded_skill, _skill_dir, _display_name = _loaded+ _part = _build_skill_message(+ _loaded_skill, _skill_dir,+ f'[IMPORTANT: The "{_display_name}" skill is auto-loaded. '+ f"Follow its instructions for this session.]",+ )+ if _part:+ _combined_parts.append(_part)+ _loaded_names.append(_sname)+ if _combined_parts:+ _combined_parts.append(event.text) # user's original text after the payloads+ event.text = "\n\n".join(_combined_parts)+ logger.info("[Gateway] Auto-loaded skill(s) %s for session %s", _loaded_names, session_key)+ except Exception as e:+ logger.warning("[Gateway] Failed to auto-load skill(s) %s: %s", _skill_names, e)++ async def _hmwa_acquire_turn_lease(self, _quick_key, run_generation, session_entry, _session_env_tokens):+ """Serialize [load history → run → flush] per resolved SESSION_ID so another routing key on+ the same session waits for the prior flush. Fail-closed on timeout (outer dispatch returns+ a resend notice). Released in _handle_message's finally, granted per (routing key, run+ generation) so a stale unwind can't release a newer turn's."""+ from gateway.run import _float_env+ _lease_registry = getattr(self, "_turn_leases", None)+ if _lease_registry is None:+ return+ try:+ _lease_token = await _lease_registry.acquire(+ session_entry.session_id, owner_key=_quick_key, generation=run_generation,+ timeout=_float_env("HERMES_TURN_LEASE_TIMEOUT", DEFAULT_LEASE_WAIT),+ )+ except TurnLeaseTimeoutError:+ # The cleanup finally starts later; restore the tokens here or this exit leaks identity.+ self._clear_session_env(_session_env_tokens)+ raise+ if _lease_token is not None:+ self._session_state(_quick_key).turn.lease_tokens[run_generation] = _lease_token++ async def _hmwa_first_contact_notes(self, source, history, turn_sidecar_notes):+ """First-ever-message onboarding note + one-time 'no home channel' prompt (both only when+ the session has no history). Delivered on the user message (sidecar), NOT the ephemeral+ system prompt: present-on-turn-1/absent-on-turn-2 was a guaranteed prompt diff + rebuild."""+ from gateway.run import _hermes_home, _home_target_env_var, _load_gateway_config+ if history:+ return+ if not await self.async_session_store.has_any_sessions():+ _intro_note = (+ "[System note: This is the user's very first message ever. "+ "Briefly introduce yourself and mention that /help shows available commands. "+ "Keep the introduction concise -- one or two sentences max.]"+ )+ # onboarding.profile_build == "ask" (default) and not yet offered: swap the plain intro for+ # a consent-gated profile-build directive. Fires at most once.+ try:+ from agent.onboarding import (+ PROFILE_BUILD_FLAG, is_seen, mark_seen, profile_build_directive,+ profile_build_mode,+ )+ _onb_cfg = _load_gateway_config()+ if profile_build_mode(_onb_cfg) == "ask" and not is_seen(_onb_cfg, PROFILE_BUILD_FLAG):+ turn_sidecar_notes.append(profile_build_directive().strip())+ mark_seen(_hermes_home / "config.yaml", PROFILE_BUILD_FLAG)+ else:+ turn_sidecar_notes.append(_intro_note)+ except Exception as _pb_err:+ logger.debug("Profile-build onboarding directive failed, using plain intro: %s", _pb_err)+ turn_sidecar_notes.append(_intro_note)++ # One-time prompt if no home channel is set (webhooks deliver to configured targets instead).+ if not source.platform or source.platform in (Platform.LOCAL, Platform.WEBHOOK):+ return+ platform_name = source.platform.value+ env_key = _home_target_env_var(platform_name)+ # Multiplex: the home channel may live only in the profile secret scope, not os.environ.+ home_env = ""+ if env_key:+ # A secondary with no home channel must not borrow the default profile's from+ # os.environ; only an UNSCOPED single-profile read may fall back to the process env.+ from agent.secret_scope import UnscopedSecretError, get_secret+ try:+ home_env = (get_secret(env_key) or "").strip()+ except UnscopedSecretError:+ home_env = (os.getenv(env_key) or "").strip()+ except Exception:+ home_env = ""+ # Also honor in-memory / yaml home_channel on this platform.+ with suppress(Exception):+ if not home_env and self.config.get_home_channel(source.platform):+ home_env = "set"+ # Secondary-profile platforms may only exist under that profile's config — re-read in scope.+ if not home_env:+ with suppress(Exception):+ from gateway.config import load_gateway_config as _lgc+ prof = (getattr(source, "profile", None) or "").strip()+ if prof and prof != "default" and _lgc().get_home_channel(source.platform):+ home_env = "set"+ if not home_env:+ # Slack routes every command through the parent `/hermes`; bare `/sethome` would fail.+ sethome_cmd = "/hermes sethome" if source.platform == Platform.SLACK else "/sethome"+ await self._deliver_platform_notice(+ source, f"📬 No home channel is set for {platform_name.title()}. "+ f"A home channel is where Hermes delivers cron job results and cross-platform "+ f"messages.\n\nType {sethome_cmd} to make this chat your home channel, or ignore "+ f"to skip.",+ )++ def _hmwa_apply_message_timestamp(self, event, message_text):+ """Capture the platform event time as message metadata and keep the persisted transcript- clean (strip any leading timestamp prefix) regardless of the toggle; only the in-context++ clean — strip any leading timestamp prefix and the Discord triggering-message note (a++ model instruction, not authored text) — regardless of the toggle; only the in-context+ RENDER is gated behind gateway.message_timestamps.enabled (default OFF)."""+ from gateway.run import _load_gateway_config, _message_timestamps_enabled++ from gateway.run_inbound import strip_discord_triggering_note+ persist_user_message = None+ persist_user_timestamp = None+ try:+ from hermes_time import get_timezone as _get_evt_tz+ from gateway.message_timestamps import (+ coerce_message_timestamp as _coerce_msg_ts,+ render_user_content_with_timestamp as _render_msg_ts,+ strip_leading_message_timestamps as _strip_msg_ts,+ )+ _evt_tz = _get_evt_tz()+ if message_text and isinstance(message_text, str):+ _clean_message_text, _embedded_ts = _strip_msg_ts(message_text, tz=_evt_tz)- persist_user_message = _clean_message_text++ persist_user_message = strip_discord_triggering_note(event, _clean_message_text)+ _event_epoch = _coerce_msg_ts(getattr(event, "timestamp", None), tz=_evt_tz)+ persist_user_timestamp = _event_epoch if _event_epoch is not None else _embedded_ts+ if _message_timestamps_enabled(_load_gateway_config()):+ message_text = _render_msg_ts(_clean_message_text, persist_user_timestamp, tz=_evt_tz)+ else:+ # Toggle off: the model sees the clean message; timestamp stored for later opt-in.+ message_text = _clean_message_text+ except Exception as _ts_err:+ logger.debug("Message timestamp injection failed (non-fatal): %s", _ts_err)+ return message_text, persist_user_message, persist_user_timestamp++ @dataclasses.dataclass+ class _PreparedTurn:+ """Inputs to the agent run assembled by ``_hmwa_prepare_turn``."""++ history: Any+ context_prompt: str+ message_text: Any+ persist_user_message: Any+ persist_user_timestamp: Any+ persist_user_display_kind: Optional[str]+ persistence_session_id: Optional[str] = None+ persistence_owner: Optional[str] = None++ async def _hmwa_prepare_turn(self, event, source, session_entry, session_key, _quick_key, run_generation):+ """Everything between session resolution and the agent run: session open, task-local env,+ context prompt, sidecar notes, turn lease, transcript load + hygiene, inbound text. Returns+ ``(_PreparedTurn, env_tokens)``; a ``str`` first element is a reply to send instead of+ running (history unreadable); ``None`` drops the turn (inbound text rejected)."""+ from gateway.run import _load_gateway_config+ _was_auto_reset, _is_new_session = await self._hmwa_open_session(session_entry, session_key, source)+ context = build_session_context(source, self.config, session_entry)+ # Session context variables for tools (task-local, concurrency-safe)+ _session_env_tokens = self._set_session_env(context)+ # Self-injected turns (MessageEvent(internal=True)) persist with a DB-only display_kind so+ # UIs render timeline notices, not user bubbles; role/content untouched.+ from gateway.response_filters import display_kind_for_event+ persist_user_display_kind = display_kind_for_event(event)+ _redact_pii = False # privacy.redact_pii, re-read per message+ with suppress(Exception):+ _redact_pii = bool((_load_gateway_config().get("privacy") or {}).get("redact_pii", False))++ # The context prompt render is pinned per session, keyed by a hash of the renderer inputs, so+ # the system prompt cannot drift turn-over-turn; a miss (thread rename, /sethome) re-renders.+ context_prompt = self._pinned_session_context_prompt(context, _redact_pii, session_key)++ # Per-turn notes ride the user message via the api_content sidecar, NOT context_prompt+ # (appending to the ephemeral system prompt forced a full agent rebuild).+ turn_sidecar_notes: List[str] = []+ if _was_auto_reset:+ await self._hmwa_deliver_auto_reset_notice(session_entry, source, turn_sidecar_notes)++ # Auto-load bound skill(s) only on NEW sessions; ongoing ones carry the content in history.+ _auto = getattr(event, "auto_skill", None)+ if _is_new_session and _auto:+ self._hmwa_auto_load_skills(event, _auto, _quick_key, session_key)++ await self._hmwa_acquire_turn_lease(_quick_key, run_generation, session_entry, _session_env_tokens)++ # A turn becomes durable recovery work only after it owns the per-session lease; marking+ # earlier would falsely recover a message that never began processing.+ await self._mark_durable_active_turn(event, session_entry.session_key)++ # An unreadable store is not an empty conversation: stop before the agent invents continuity+ # from []. Restore task-local context here (before the broad cleanup finally).+ try:+ history = await self.async_session_store.load_transcript(session_entry.session_id)+ history = await self._hmwa_run_session_hygiene(+ event, source, session_entry, session_key, history, _quick_key, run_generation,+ )+ except TranscriptReadError:+ self._clear_session_env(_session_env_tokens)+ return (+ "⚠️ This session's history is temporarily unavailable, so this message was not "+ "processed. Ask the operator to inspect state.db, then resend after it is healthy. "+ "Use /reset only if you intentionally want to start a new conversation."+ ), _session_env_tokens++ await self._hmwa_first_contact_notes(source, history, turn_sidecar_notes)++ # Voice channel state rides the user message ONLY when changed (in the system prompt it+ # forced a rebuild + prompt-cache re-key per message).+ _vc_note = self._voice_channel_sidecar_note(event, source, session_key)+ if _vc_note:+ turn_sidecar_notes.append(_vc_note)++ # Auto-analyze user images so the model gets a description plus the local path.+ message_text = await self._prepare_profile_scoped_inbound_message_text(+ event=event, source=source, history=history, session_key=session_key,+ )+ if message_text is None:+ return None, _session_env_tokens++ message_text, persist_user_message, persist_user_timestamp = (+ self._hmwa_apply_message_timestamp(event, message_text)+ )++ # Stage the notes (one-shot; consumed in run_sync) AFTER the early-out so an aborted turn+ # cannot leak them into the next turn.+ if turn_sidecar_notes and session_key:+ self._set_pending_turn_sidecar_notes(session_key, turn_sidecar_notes)++ # Bind this run generation to the adapter so deferred post-delivery callbacks are released+ # by the run that registered them.- self._bind_adapter_run_generation(self._adapter_for_source(source), session_key, run_generation)++ self._bind_adapter_run_generation(self._delivery_adapter_for(source), session_key, run_generation)+ # Delivery IDs are only unique in their transport namespace. Keyless turns+ # need their own identity, even when another process writes to this session.+ import uuid+ namespace = [source.platform.value, source.profile, source.scope_id,+ source.chat_id, source.thread_id, str(event.message_id)]+ owner = (str(uuid.uuid5(uuid.NAMESPACE_URL, json.dumps(namespace)))+ if event.message_id else str(uuid.uuid4()))+ return self._PreparedTurn(+ history, context_prompt, message_text, persist_user_message, persist_user_timestamp,+ persist_user_display_kind, session_entry.session_id, owner,+ ), _session_env_tokensdiff --cc gateway/run_turn_progress.pyindex 95044dc9bf0,00000000000..eaac20fa5acmode 100644,000000..100644--- a/gateway/run_turn_progress.py+++ b/gateway/run_turn_progress.py@@@ -1,869 -1,0 +1,876 @@@+"""Extracted gateway run_turn_progress responsibility; consumed by TurnRunner."""+from __future__ import annotations++import asyncio+import dataclasses+import json+import logging+import queue+import re+import threading+import time+from contextlib import suppress+from datetime import datetime+from typing import TYPE_CHECKING, Any, Dict, List, Optional++from agent.interrupt_compat import _accepts_keyword+from agent.replay_cleanup import strip_stale_dangerous_confirmations+from gateway.config import Platform+from gateway.media_repair import repair_explicit_computer_use_media_paths+from gateway.platforms.base import BasePlatformAdapter+from gateway.turn_context import TurnContext+from hermes_cli.config import cfg_get+from utils import is_truthy_value++if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)+ from gateway.run import GatewayRunner # noqa: F401++# Log-record parity with the origin module.+logger = logging.getLogger("gateway.run")+++class GatewayTurnProgressMixin:+ # ── shared thread→loop plumbing ─────────────────────────────────────────────────────────++ def _schedule(self, coro, log_message: str, loop=None):+ """Hop a coroutine from the agent's sync worker thread onto the gateway loop."""+ from gateway.run import safe_schedule_threadsafe+ return safe_schedule_threadsafe(+ coro, self._ctx._loop_for_step if loop is None else loop, logger=logger, log_message=log_message,+ )++ def _agent_interrupted(self) -> bool:+ """True once the user sent `stop` (agent_holder[0] is the shared agent handle)."""+ try:+ agent = self._ctx.agent_holder[0] if self._ctx.agent_holder else None+ return bool(agent is not None and getattr(agent, "is_interrupted", False))+ except Exception:+ return False++ def _stream_consumer(self):+ holder = self._ctx.stream_consumer_holder+ return holder[0] if holder else None++ def _drain_progress_queue(self) -> None:+ q = self._ctx.progress_queue+ with suppress(Exception):+ while not q.empty():+ q.get_nowait()++ def _track_progress_result(self, result) -> None:+ """Remember a delivered progress/status message id for end-of-turn cleanup."""+ ctx = self._ctx+ if ctx._cleanup_progress and getattr(result, "success", False) and getattr(result, "message_id", None):+ ctx._cleanup_msg_ids.append(str(result.message_id))++ def _track_future_cleanup_id(self, fut) -> None:+ try:+ res = fut.result()+ except Exception:+ return+ self._track_progress_result(res)++ # ── progress_callback (agent thread → progress queue) ───────────────────────────────────++ def progress_callback(self, event_type: str, tool_name: str = None, preview: str = None, args: dict = None, **kwargs):+ """Callback invoked by agent on tool lifecycle events."""+ ctx = self._ctx+ # Failed subagent → one clean user-facing notice, handled FIRST, before every progress-queue+ # gate: platforms with tool_progress off must still hear about a dead delegation.+ if event_type == "subagent.complete":+ self._progress_subagent_notice(preview, kwargs)+ return+ self._progress_live_status(event_type, tool_name, args)+ # "log" mode: append tool.started lines to the log queue, silent in chat. Handled before+ # the progress_queue guard because log mode runs without a chat progress queue.+ if ctx.log_queue is not None and event_type == "tool.started" and tool_name and tool_name != "_thinking":+ ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")+ preview_str = f' "{preview}"' if preview else ""+ ctx.log_queue.put(f"{ts} {tool_name}:{preview_str}".rstrip())+ if not ctx.progress_queue or not ctx._run_still_current():+ return+ if event_type == "tool.completed" and not ctx.long_tool_hint_fired[0]:+ self._progress_onboarding_hint(kwargs)+ return+ # "_thinking" is assistant scratch text between tool calls, never ordinary tool progress:+ # only relayed when the platform explicitly opted into thinking_progress.+ if event_type == "_thinking" or tool_name == "_thinking":+ thinking_text = (preview if tool_name == "_thinking" else tool_name) if ctx._thinking_enabled else None+ if thinking_text:+ ctx.progress_queue.put(f"💬 {thinking_text}")+ return+ # Native task cards consume the ID-bearing tool_start/tool_complete callbacks instead;+ # name-correlated text events would duplicate cards and mispair concurrent same-tool calls.+ if ctx._native_slack_task_cards and event_type in {"tool.started", "tool.completed"}:+ return+ # tool_progress off → only _thinking passes (above). Only tool.started renders. clarify:+ # send_clarify IS the user-facing rendering (a bubble would duplicate it, and verbose mode+ # would dump the raw args JSON right under the prompt). Post-`stop`: N parallel tool calls+ # fire N tool.started events before the interrupt check, so a late stop must not render them.+ if (+ not ctx.tool_progress_enabled+ or event_type != "tool.started"+ # The adapter's send_clarify IS the user-facing rendering (interactive buttons or the+ # numbered-text fallback), so a progress bubble is pure duplication — and in verbose mode it+ # dumps the raw tool-call args JSON ({"question": ..., "choices": [...]}) into the chat. Because+ # the progress queue drains on a background task, that raw JSON typically lands right underneath+ # the rendered prompt (#52374).+ or tool_name == "clarify"+ or self._agent_interrupted()+ ):+ return+ # "new" mode: only report when tool changes+ if ctx.progress_mode == "new" and tool_name == ctx.last_tool[0]:+ return+ ctx.last_tool[0] = tool_name+ msg = self._progress_build_message(tool_name, preview, args)+ if msg is not None:+ self._progress_emit(msg)++ def _progress_subagent_notice(self, preview, kwargs: dict) -> None:+ """Only terminal failure statuses render (same notice rail as credit warnings)."""+ ctx = self._ctx++ from gateway.warning_notifications import render_notification+ status = kwargs.get("status")+ try:+ from tools.delegate_tool import SUBAGENT_FAILURE_STATUSES, format_subagent_failure_line+ if status in SUBAGENT_FAILURE_STATUSES and ctx._run_still_current():+ line = format_subagent_failure_line(+ kwargs.get("goal"), status, error=kwargs.get("summary") or preview,+ duration_seconds=kwargs.get("duration_seconds"), failure_reason=kwargs.get("failure_reason"),+ )- self._schedule(self._runner._deliver_platform_notice(ctx.source, line), "subagent failure notice scheduling error")++ render_notification(++ lambda: self._schedule(self._runner._deliver_platform_notice(ctx.source, line), "subagent failure notice scheduling error"),++ platform=ctx.source.platform, user_config=ctx.user_config)+ except Exception:+ logger.debug("subagent failure notice failed", exc_info=True)++ def _progress_live_status(self, event_type: str, tool_name, args) -> None:+ """Live status line (Slack assistant status): stash the tool phrase on the adapter; the+ _keep_typing refresh renders it. Plain dict write, safe from the sync worker thread."""+ ctx = self._ctx+ adapter = ctx._live_status_adapter+ if adapter is None or ctx._live_status_mode == "off" or tool_name == "_thinking":+ return+ try:+ if event_type == "tool.started" and tool_name and ctx._run_still_current():+ from agent.display import build_status_phrase+ adapter.set_status_text(ctx.source.chat_id, build_status_phrase(tool_name, args if ctx._live_status_mode == "full" else None))+ elif event_type == "tool.completed":+ # Between tools the model is genuinely "thinking" again — revert to the static default.+ adapter.set_status_text(ctx.source.chat_id, None)+ except Exception as err:+ logger.debug("live status update failed: %s", err)++ def _progress_onboarding_hint(self, kwargs: dict) -> None:+ """First-touch onboarding: the first time a tool exceeds _LONG_TOOL_THRESHOLD_S while+ streaming every tool (progress_mode == "all"), append a one-time /verbose hint."""+ from gateway.run import _hermes_home, _load_gateway_config+ ctx = self._ctx+ try:+ if (kwargs.get("duration") or 0) >= ctx._LONG_TOOL_THRESHOLD_S and ctx.progress_mode == "all":+ from agent.onboarding import TOOL_PROGRESS_FLAG, is_seen, mark_seen, tool_progress_hint_gateway+ cfg = _load_gateway_config()+ gate_on = is_truthy_value(cfg_get(cfg, "display", "tool_progress_command"), default=False)+ if gate_on and not is_seen(cfg, TOOL_PROGRESS_FLAG):+ ctx.long_tool_hint_fired[0] = True+ ctx.progress_queue.put(tool_progress_hint_gateway())+ mark_seen(_hermes_home / "config.yaml", TOOL_PROGRESS_FLAG)+ except Exception as err:+ logger.debug("tool-progress onboarding hint failed: %s", err)++ @staticmethod+ def _preview_cap() -> int:+ """tool_preview_length (default 40): the one-line preview budget for "all"/"new" modes."""+ from agent.display import get_tool_preview_max_len+ pl = get_tool_preview_max_len()+ return pl if pl > 0 else 40++ def _progress_terminal_blocks(self, adapter, tool_name, args, emoji):+ """(full, short) fenced blocks for a terminal command on markdown platforms, else (None, None).++ No language tag: Slack mrkdwn renders it as a literal first code line. Verbose shows the FULL+ command; "all"/"new" truncate to one line capped at ``tool_preview_length``. Consecutive+ terminal calls drop the repeated header so back-to-back commands render as adjacent blocks.+ """+ if not (+ getattr(adapter, "supports_code_blocks", False) and tool_name == "terminal" and isinstance(args, dict)+ and isinstance(args.get("command"), str) and args["command"].strip()+ ):+ return None, None+ cmd_full = args["command"].rstrip()+ header = "" if self._ctx.last_was_terminal_block[0] else f"{emoji} {tool_name}\n"+ cap = self._preview_cap()+ lines = cmd_full.splitlines()+ cmd_short = lines[0] if lines else cmd_full+ if len(cmd_short) > cap:+ cmd_short = cmd_short[:cap - 3] + "..."+ elif len(lines) > 1:+ cmd_short += " ..."+ return f"{header}```\n{cmd_full}\n```", f"{header}```\n{cmd_short}\n```"++ def _progress_build_message(self, tool_name, preview, args) -> Optional[str]:+ """Render the progress line. Verbose mode queues directly (no dedup) and returns None."""+ ctx = self._ctx+ from agent.display import get_tool_emoji+ emoji = get_tool_emoji(tool_name, default="⚙️")+ try:- adapter = self._runner._adapter_for_source(ctx.source)++ adapter = self._runner._delivery_adapter_for(ctx.source)+ except Exception:+ adapter = None+ code_full, code_short = self._progress_terminal_blocks(adapter, tool_name, args, emoji)+ verbose = ctx.progress_mode == "verbose"+ code = code_full if verbose else code_short+ ctx.last_was_terminal_block[0] = code is not None+ if verbose:+ if code is None and args:+ from agent.display import get_tool_preview_max_len+ pl = get_tool_preview_max_len()+ args_str = json.dumps(args, ensure_ascii=False, default=str)+ # tool_preview_length 0 (default) = no truncation in verbose mode; the user asked+ # for full detail and platform message-length limits handle the rest.+ if pl > 0 and len(args_str) > pl:+ args_str = args_str[:pl - 3] + "..."+ code = f"{emoji} {tool_name}({list(args.keys())})\n{args_str}"+ elif code is None:+ code = f"{emoji} {tool_name}: \"{preview}\"" if preview else f"{emoji} {tool_name}..."+ ctx.progress_queue.put(code)+ return None+ if code is not None:+ return code+ if not preview:+ return f"{emoji} {tool_name}..."+ from agent.display import get_tool_verb, prepare_tool_preview, tool_verb_connector, verb_drops_preview+ prepared = prepare_tool_preview(tool_name, args, fallback=preview, max_len=self._preview_cap())+ preview = adapter.format_tool_preview(prepared) if adapter is not None else prepared.text+ # Friendly labels: human-phrased line for built-in tools ("🔍 Searching the web for ...")+ # by prefixing the verb onto the computed preview, so the command/url/query is kept.+ verb = get_tool_verb(tool_name)+ if not verb:+ return f"{emoji} {tool_name}: \"{preview}\""+ return f"{emoji} {verb}" if verb_drops_preview(tool_name) else f"{emoji} {verb}{tool_verb_connector(tool_name)}{preview}"++ def _progress_emit(self, msg: str) -> None:+ """Dedup consecutive identical lines (execute_code boilerplate), then route to the native+ stream bubble when the consumer accepts tool progress, else the progress queue."""+ ctx = self._ctx+ sc = self._stream_consumer()+ native = sc is not None and getattr(sc, "accepts_tool_progress", False)+ if msg == ctx.last_progress_msg[0]:+ ctx.repeat_count[0] += 1+ if native:+ sc.on_tool_progress(f"{msg} (×{ctx.repeat_count[0] + 1})")+ else:+ ctx.progress_queue.put(("__dedup__", msg, ctx.repeat_count[0]))+ return+ ctx.last_progress_msg[0], ctx.repeat_count[0] = msg, 0+ if native:+ sc.on_tool_progress(msg)+ else:+ ctx.progress_queue.put(msg)++ # ── Slack-native task cards (progress-queue drain) ──────────────────────────────────────++ @dataclasses.dataclass+ class _TaskCardState:+ """Task-card rail state for ``_send_native_task_card_progress``."""+ adapter: Any+ tasks: Dict[str, Dict[str, str]] = dataclasses.field(default_factory=dict)+ task_order: List[str] = dataclasses.field(default_factory=list)+ fallback_msg_id: Optional[str] = None+ native_failed: bool = False+ # TERMINAL for the turn, distinct from native_failed: no later publication+ # in this turn may deliver task text through the native lane OR the text+ # fallback. Two causes, both properties of the destination rather than of+ # one attempt: the connector's egress guard refused the chat, or the chat+ # cannot host a card (no thread anchor). Declared rather than set+ # dynamically so the state is visible where it lives.+ publication_suppressed: bool = False+ anonymous_seq: int = 0++ @staticmethod+ def _compact(value: Any, limit: int = 120) -> str:+ text = re.sub(r"\s+", " ", str(value or "")).strip()+ return text if len(text) <= limit else text[: limit - 3].rstrip() + "..."++ def visible_tasks(self) -> List[Dict[str, str]]:+ return [self.tasks[task_id] for task_id in self.task_order[-8:]]++ def fallback_text(self) -> str:+ labels = {"in_progress": "running", "complete": "complete", "error": "error"}+ lines = [f"- {t['title']} - {labels.get(t['status'], t['status'])}" for t in self.visible_tasks()]+ return "Hermes is working\n" + "\n".join(lines)++ def _upsert(self, call_id: str, title: str) -> Dict[str, str]:+ if call_id not in self.tasks:+ self.task_order.append(call_id)+ self.tasks[call_id] = {"id": call_id, "title": self._compact(title), "status": "in_progress"}+ return self.tasks[call_id]++ def apply_event(self, raw: Any) -> bool:+ event_type = raw.get("type") if isinstance(raw, dict) else None+ if event_type not in {"tool.started", "tool.completed"}:+ return False+ call_id = str(raw.get("tool_call_id") or "")+ if not call_id:+ self.anonymous_seq += 1+ call_id = f"anonymous_{self.anonymous_seq}"+ tool_name = str(raw.get("tool_name") or "tool")+ if event_type == "tool.started":+ preview = self._compact(raw.get("preview"), 64)+ self._upsert(call_id, f"{tool_name} - {preview}" if preview else tool_name)+ return True+ # Completion-only events are rare but valid on some runtimes; keep their real ID instead+ # of guessing a same-name pending call.+ task = self.tasks.get(call_id) or self._upsert(call_id, tool_name)+ task["status"] = "error" if raw.get("is_error") else "complete"+ return True++ async def _task_card_send_or_edit_fallback(self, st) -> None:+ ctx = self._ctx+ text = st.fallback_text()+ from gateway.relay.egress import declined_send++ if st.publication_suppressed:+ return+ if st.fallback_msg_id:+ result = await st.adapter.edit_message(+ chat_id=ctx.source.chat_id, message_id=st.fallback_msg_id, content=text, metadata=ctx._progress_metadata,+ )+ if getattr(result, "success", False):+ return+ # P5(b): R5-4 made a declined native CARD terminal but left this+ # editable-text fallback: a declined edit fell through to+ # _send_progress_text and re-sent the same task text to the refused+ # chat. The decline must set the terminal state here too.+ if declined_send(result):+ logger.warning(+ "Task-card fallback edit DECLINED by the connector's egress "+ "guard; suppressing progress delivery for the rest of this "+ "turn (the destination is not approved)"+ )+ st.publication_suppressed = True+ return+ result = await self._send_progress_text(st, text)+ if getattr(result, "success", False) and getattr(result, "message_id", None):+ st.fallback_msg_id = str(result.message_id)++ async def _task_card_publish(self, st) -> None:+ ctx = self._ctx+ if not st.tasks:+ return+ if st.publication_suppressed:+ # Publication was suppressed earlier in the turn (egress refusal or a chat+ # that cannot host a card); every later publication would re-deliver the+ # same task text there.+ return+ # Resolve eligibility in the owning adapter BEFORE transport I/O: a first+ # timeout/disconnect must not turn an un-cardable chat into text fallback.+ # Optional for older adapters; only an explicit False refuses publication.+ destination_supported = getattr(st.adapter, "native_task_card_destination_supported", None)+ if callable(destination_supported) and destination_supported(+ ctx.source.chat_id, reply_to=ctx._progress_reply_to, metadata=ctx._progress_metadata,+ ) is False:+ self._task_card_uncardable_destination(st)+ if st.publication_suppressed:+ return+ if not st.native_failed:+ result = await st.adapter.send_native_task_card_progress(+ chat_id=ctx.source.chat_id, tasks=st.visible_tasks(), title="Hermes is working",+ reply_to=ctx._progress_reply_to, metadata=ctx._progress_metadata, fallback_text=st.fallback_text(),+ )+ if getattr(result, "success", False):+ return+ # P5(b): an AUTHORIZATION decline is not a broken card lane. The+ # fallback below sends the same task text to the same chat, which+ # turns a refused card into delivered plain text. Stop the lane+ # without re-delivering; the refusal is already logged.+ from gateway.relay.egress import declined_send++ if declined_send(result):+ # TERMINAL, and stored SEPARATELY from native_failed. Reusing+ # native_failed suppressed exactly ONE update: the next progress+ # event skipped this branch (the lane is already "failed") and+ # went straight to the text fallback. A refusal does not expire+ # after one tick.+ st.publication_suppressed = True+ st.native_failed = True+ logger.warning(+ "Slack native task-card progress DECLINED by the connector's "+ "egress guard — suppressing the text fallback for the rest "+ "of this turn (the destination is not approved)"+ )+ return+ st.native_failed = True+ from gateway.run_turn_runner import _CARD_DESTINATION_REFUSALS+ if getattr(result, "error", None) in _CARD_DESTINATION_REFUSALS:+ self._task_card_uncardable_destination(st, getattr(result, "error", "unknown error"))+ if st.publication_suppressed:+ return+ else:+ logger.warning(+ "Slack native task-card progress failed; falling back "+ "to an editable text update: %s", getattr(result, "error", "unknown error"),+ )+ # Once the native rail fails, every later lifecycle event edits the same fallback message.+ await self._task_card_send_or_edit_fallback(st)++ def _task_card_uncardable_destination(self, st, reason: str = "no thread anchor") -> None:+ """The chat cannot host a card (flat DM: no thread anchor) — a property of the destination,+ not a transient outage. The text fallback exists to keep a WORKING card lane live through a+ transient failure, not to invent text bubbles the operator never asked for: with Slack's tier+ default (``tool_progress: off``) the lane goes silent for the turn. An operator who WROTE+ ``new``/``all`` asked for text progress, so the editable fallback carries it instead."""+ if self._ctx.tool_progress_enabled:+ st.native_failed = True+ logger.info(+ "Slack native task cards are unsupported for this destination (%s); "+ "tool progress continues as an editable text update", reason,+ )+ return+ st.publication_suppressed = True+ logger.info(+ "Slack native task cards are unsupported for this destination (%s); "+ "tool progress stays off for this turn", reason,+ )++ def _task_card_drain(self, st) -> bool:+ changed = False+ try:+ while True:+ changed = st.apply_event(self._ctx.progress_queue.get_nowait()) or changed+ except queue.Empty:+ pass+ except Exception:+ logger.debug("Slack native progress queue drain failed", exc_info=True)+ return changed++ async def _send_native_task_card_progress(self, adapter) -> None:+ """Drain progress into native cards; supported destinations retain editable fallback.+ Unsupported destinations and egress refusals suppress publication, never finalization.++ See #29483.+ """+ ctx = self._ctx+ st = self._TaskCardState(adapter)+ try:+ while ctx._run_still_current():+ try:+ raw = ctx.progress_queue.get_nowait()+ except queue.Empty:+ await asyncio.sleep(0.1)+ continue+ if not self._agent_interrupted() and st.apply_event(raw):+ await self._task_card_publish(st)+ except asyncio.CancelledError:+ if self._task_card_drain(st) and ctx._run_still_current() and not self._agent_interrupted():+ await self._task_card_publish(st)+ finally:+ if hasattr(adapter, "stop_native_task_card_progress"):+ # Best-effort on the turn-cleanup path: an escaping transport exception would skip+ # final-delivery logic (cleanup awaits catch only CancelledError).+ try:+ await adapter.stop_native_task_card_progress(+ ctx.source.chat_id, reply_to=ctx._progress_reply_to, metadata=ctx._progress_metadata,+ )+ except asyncio.CancelledError:+ raise+ except Exception:+ logger.debug("task-card stop failed during turn cleanup", exc_info=True)++ # ── editable progress bubbles (progress-queue drain) ────────────────────────────────────++ @dataclasses.dataclass+ class _ProgressEditState:+ """Mutable editable-bubble state shared by ``send_progress_messages`` and its helpers."""+ adapter: Any+ progress_lines: list+ progress_msg_id: Any+ can_edit: bool+ _progress_len_fn: Any+ _PROGRESS_TEXT_LIMIT: int+ _edit_accepts_metadata: bool++ def _progress_edit_state(self, adapter) -> "TurnRunner._ProgressEditState":+ ctx = self._ctx+ len_fn = adapter.message_len_fn if isinstance(adapter, BasePlatformAdapter) else len+ try:+ raw_limit = int(getattr(adapter, "MAX_MESSAGE_LENGTH", 4000) or 4000)+ except Exception:+ raw_limit = 4000+ # Per-chat resolution (relay adapter fronting N platforms): cap and length unit follow the+ # chat's underlying platform; native adapters return their scalar/property unchanged.+ if isinstance(adapter, BasePlatformAdapter):+ with suppress(Exception):+ raw_limit = int(adapter.max_message_length_for_chat(ctx.source.chat_id) or 4000)+ len_fn = adapter.message_len_fn_for_chat(ctx.source.chat_id)+ return self._ProgressEditState(+ adapter=adapter, progress_lines=[], progress_msg_id=None,+ # "separate" = one message per tool (pre-v0.9 behavior)+ can_edit=ctx.progress_grouping != "separate",+ _progress_len_fn=len_fn,+ # Leave room for platform quirks / formatting; tiny test adapters keep a usable limit.+ _PROGRESS_TEXT_LIMIT=max(1, raw_limit - (64 if raw_limit > 128 else 0)),+ # Overflow edits pass metadata (Telegram topic/thread routing) only when edit_message takes it.+ _edit_accepts_metadata=bool(ctx._progress_metadata) and _accepts_keyword(adapter.edit_message, "metadata"),+ )++ async def _edit_progress_message(self, st, message_id: str, content: str):+ ctx = self._ctx+ kwargs = {"chat_id": ctx.source.chat_id, "message_id": message_id, "content": content}+ if getattr(st.adapter, "REQUIRES_EDIT_FINALIZE", False):+ kwargs["finalize"] = True+ if st._edit_accepts_metadata:+ kwargs["metadata"] = ctx._progress_metadata+ return await st.adapter.edit_message(**kwargs)++ @staticmethod+ def _progress_text(lines: list) -> str:+ return "\n".join(str(line) for line in lines)++ def _split_progress_groups(self, st, lines: list) -> list[list]:+ """Partition progress lines into platform-sized editable bubbles."""+ groups: list[list] = []+ current: list = []+ for line in lines:+ candidate = current + [line]+ if current and st._progress_len_fn(self._progress_text(candidate)) > st._PROGRESS_TEXT_LIMIT:+ groups.append(current)+ candidate = [line]+ current = candidate+ return groups + ([current] if current else [])++ async def _send_progress_text(self, st, text: str):+ ctx = self._ctx+ result = await st.adapter.send(+ chat_id=ctx.source.chat_id, content=text, reply_to=ctx._progress_reply_to, metadata=ctx._progress_metadata,+ )+ self._track_progress_result(result)+ return result++ async def _roll_progress_overflow_if_needed(self, st) -> bool:+ """Start fresh editable progress bubbles before a bubble exceeds limit.++ Returns True when it delivered/split the buffer or a transient edit failure left it+ intact for retry — either way the caller skips the normal send/edit path this tick.+ """+ if not st.progress_lines or not st.can_edit:+ return False+ groups = self._split_progress_groups(st, st.progress_lines)+ if len(groups) <= 1:+ return False+ if st.progress_msg_id is not None:+ result = await self._edit_progress_message(st, st.progress_msg_id, self._progress_text(groups[0]))+ if not result.success:+ if getattr(result, "retryable", False):+ logger.debug("[%s] Transient overflow edit failure — keeping can_edit=True", st.adapter.name)+ return True+ st.can_edit = False+ # Fall back to the existing non-edit behavior.+ return False+ groups = groups[1:]+ for group in groups:+ result = await self._send_progress_text(st, self._progress_text(group))+ if result.success and result.message_id:+ st.progress_msg_id = result.message_id+ # The newest continuation is the only mutable bubble: keep just its lines so later+ # edits update it instead of replaying the full transcript into new messages.+ st.progress_lines = groups[-1]+ return True++ @staticmethod+ def _is_reset_marker(raw) -> bool:+ return isinstance(raw, tuple) and len(raw) >= 1 and raw[0] == "__reset__"++ def _reset_progress_bubble(self, st) -> None:+ """Content bubble landed — close the tool-progress bubble so the next tool starts fresh+ below it; else tool edits hit the ORIGINAL message above (out of order)."""+ st.progress_msg_id, st.progress_lines = None, []+ self._ctx.last_progress_msg[0], self._ctx.repeat_count[0] = None, 0++ def _progress_absorb(self, st, raw) -> Any:+ """Fold a queue item into the bubble buffer; returns the line to render this tick."""+ if isinstance(raw, tuple) and len(raw) == 3 and raw[0] == "__dedup__":+ _, base_msg, count = raw+ if not st.progress_lines:+ return base_msg+ st.progress_lines[-1] = f"{base_msg} (×{count + 1})"+ return st.progress_lines[-1]+ st.progress_lines.append(raw)+ return raw++ async def _flush_progress_edit(self, st) -> None:+ if st.can_edit and st.progress_lines and st.progress_msg_id:+ with suppress(Exception):+ await self._edit_progress_message(st, st.progress_msg_id, self._progress_text(st.progress_lines))++ async def _drain_progress_on_cancel(self, st) -> None:+ ctx = self._ctx+ with suppress(Exception):+ while not ctx.progress_queue.empty():+ raw = ctx.progress_queue.get_nowait()+ if self._is_reset_marker(raw):+ # Content-bubble marker during drain: close the current progress bubble+ # and start a fresh one for tool lines that arrived after.+ await self._roll_progress_overflow_if_needed(st)+ await self._flush_progress_edit(st)+ self._reset_progress_bubble(st)+ else:+ self._progress_absorb(st, raw)+ await self._roll_progress_overflow_if_needed(st)+ # Final edit with all remaining tools (only if editing works)+ if st.can_edit and st.progress_lines and st.progress_msg_id:+ await self._roll_progress_overflow_if_needed(st)+ await self._flush_progress_edit(st)++ async def _progress_restore_typing(self, st) -> None:+ ctx = self._ctx+ await asyncio.sleep(0.3)+ if ctx._run_still_current():+ await st.adapter.send_typing(ctx.source.chat_id, metadata=ctx._progress_metadata)++ async def _progress_send_or_edit(self, st, msg) -> bool:+ """Deliver this tick's bubble. Returns False on a transient edit failure (retry next tick).++ Transient network errors (ConnectError, timeouts) must not disable editing; only permanent+ failures (not found, permissions) set can_edit=False. Flood control backs off but keeps editing.+ """+ if st.can_edit and st.progress_msg_id is not None:+ result = await self._edit_progress_message(st, st.progress_msg_id, "\n".join(st.progress_lines))+ if result.success:+ return True+ if getattr(result, "retryable", False):+ logger.debug("[%s] Transient edit failure — keeping can_edit=True", st.adapter.name)+ return False+ if any(w in (getattr(result, "error", "") or "").lower() for w in ("flood", "retry after")):+ logger.info("[%s] Progress edit flood control, backing off", st.adapter.name)+ else:+ st.can_edit = False+ await self._send_progress_text(st, msg)+ return True+ # First tool: send all accumulated text as a new message; editing unsupported: just this line.+ result = await self._send_progress_text(st, "\n".join(st.progress_lines) if st.can_edit else msg)+ if result.success and result.message_id:+ st.progress_msg_id = result.message_id+ return True++ async def send_progress_messages(self):+ ctx = self._ctx- adapter = self._runner._adapter_for_source(ctx.source) if ctx.progress_queue else None++ adapter = self._runner._delivery_adapter_for(ctx.source) if ctx.progress_queue else None+ if not adapter:+ return+ if ctx._native_slack_task_cards and hasattr(adapter, "send_native_task_card_progress"):+ await self._send_native_task_card_progress(adapter)+ return+ # Skip tool progress for platforms that can't edit messages (e.g. iMessage/BlueBubbles):+ # each update would be a separate bubble. getattr, not attribute access: duck-typed+ # adapters (test fakes, minimal plugins) may lack edit_message — treated as "can't edit".+ adapter_edit = getattr(type(adapter), "edit_message", None)+ if adapter_edit is None or adapter_edit is BasePlatformAdapter.edit_message:+ self._drain_progress_queue()+ return+ st = self._progress_edit_state(adapter)+ last_edit_ts = 0.0+ EDIT_INTERVAL = 1.5 # Minimum seconds between edits (Telegram flood control)+ while True:+ try:+ if not ctx._run_still_current():+ self._drain_progress_queue()+ return+ raw = ctx.progress_queue.get_nowait()+ # Drain silently when interrupted: events queued in the window between tool parse+ # and interrupt processing should not render as bubbles.+ if self._agent_interrupted():+ await asyncio.sleep(0)+ continue+ if self._is_reset_marker(raw):+ self._reset_progress_bubble(st)+ continue+ msg = self._progress_absorb(st, raw)+ if not await self._roll_progress_overflow_if_needed(st):+ # Throttle edits: batch rapid tool updates into fewer API calls (grammY pattern:+ # proactively rate-limit rather than react to 429s). Loop back to drain further+ # queued messages before sending a single batched edit.+ remaining = EDIT_INTERVAL - (time.monotonic() - last_edit_ts)+ if remaining > 0:+ await asyncio.sleep(remaining)+ continue+ if not ctx._run_still_current():+ return+ if not await self._progress_send_or_edit(st, msg):+ continue+ last_edit_ts = time.monotonic()+ await self._progress_restore_typing(st)+ except queue.Empty:+ await asyncio.sleep(0.3)+ except asyncio.CancelledError:+ await self._drain_progress_on_cancel(st)+ return+ except Exception as e:+ logger.error("Progress message error: %s", e)+ await asyncio.sleep(1)++ # ── ID-bearing lifecycle callbacks (agent thread) ───────────────────────────────────────++ def voice_ack_callback(self, call_id, tool_name, args):+ """tool_start_callback: speak a one-time ack in the voice channel."""+ ctx = self._ctx+ if ctx._voice_ack_fired[0] or ctx._voice_ack_guild[0] is None or not ctx._run_still_current():+ return+ ctx._voice_ack_fired[0] = True+ adapter = self._runner.adapters.get(Platform.DISCORD)+ if adapter is None or not hasattr(adapter, "play_ack_in_voice"):+ return+ try:+ self._schedule(+ adapter.play_ack_in_voice(ctx._voice_ack_guild[0]), "voice ack scheduling error", loop=ctx._voice_ack_loop,+ )+ except Exception as err:+ logger.debug("voice ack schedule failed: %s", err)++ # Slack-native task cards ride agent.tool_start_callback / tool_complete_callback so start and+ # completion correlate by the REAL tool-call id; name-correlated progress_callback text events+ # would duplicate cards and mispair concurrent calls.++ def _native_card_gate(self) -> bool:+ ctx = self._ctx+ return bool(ctx.progress_queue) and ctx._run_still_current() and not self._agent_interrupted()++ # ── Slack-native task cards: ID-bearing lifecycle callbacks (#29483) ── These ride+ # agent.tool_start_callback / agent.tool_complete_callback so start/completion events correlate by the+ # REAL tool-call id — the name-correlated text events in progress_callback would duplicate cards and+ # mispair concurrent calls to the same tool.+ def native_tool_start_callback(self, call_id, tool_name, args):+ """Queue an ID-correlated native progress start from the agent thread."""+ if not self._native_card_gate():+ return+ from agent.display import build_tool_preview+ name = str(tool_name or "tool")+ self._ctx.progress_queue.put({+ "type": "tool.started", "tool_call_id": str(call_id or ""), "tool_name": name,+ "preview": build_tool_preview(name, args or {}, max_len=64) or "",+ })++ def native_tool_complete_callback(self, call_id, tool_name, args, result):+ """Queue the matching native completion using the real tool-call ID."""+ if not self._native_card_gate():+ return+ from agent.display import _detect_tool_failure+ name = str(tool_name or "tool")+ is_error, _ = _detect_tool_failure(name, result)+ self._ctx.progress_queue.put({+ "type": "tool.completed", "tool_call_id": str(call_id or ""), "tool_name": name, "is_error": bool(is_error),+ })++ def combined_tool_start_callback(self, call_id, tool_name, args):+ """Compose the voice ack + native task-card start consumers."""+ self._publish_execution("tool.start", {+ "tool_call_id": str(call_id or ""), "tool_name": str(tool_name or "tool"),+ "args": args if isinstance(args, dict) else {}})+ self._publish_api_tool("tool.start", call_id, tool_name, args)+ if self._ctx._voice_ack_guild[0] is not None:+ self.voice_ack_callback(call_id, tool_name, args)+ if self._ctx._native_slack_task_cards:+ self.native_tool_start_callback(call_id, tool_name, args)++ def combined_tool_complete_callback(self, call_id, tool_name, args, result):+ from agent.display import _detect_tool_failure+ is_error, _ = _detect_tool_failure(tool_name, result)+ self._publish_execution("tool.complete", {+ "tool_call_id": str(call_id or ""), "tool_name": str(tool_name or "tool"),+ "is_error": bool(is_error), "args": args if isinstance(args, dict) else {},+ "result": result if isinstance(result, str) else str(result)})+ self._publish_api_tool("tool.complete", call_id, tool_name, args, result)+ if self._ctx._native_slack_task_cards:+ self.native_tool_complete_callback(call_id, tool_name, args, result)++ # ── hook / status bridges (agent thread → gateway loop) ────────────────────────────────++ def _step_callback_sync(self, iteration: int, prev_tools: list) -> None:+ ctx = self._ctx+ if not ctx._run_still_current():+ return+ self._publish_execution("agent.step", {"iteration": iteration})+ if not ctx._hooks_ref.loaded_hooks:+ return+ # prev_tools may be list[str] or list[dict] with "name"/"result" keys. Normalise so+ # "tool_names" stays backward-compatible for user hooks that do ', '.join(tool_names).+ names = [(t.get("name") or "") if isinstance(t, dict) else str(t) for t in (prev_tools or [])]+ self._schedule(+ ctx._hooks_ref.emit("agent:step", {+ "platform": ctx.source.platform.value if ctx.source.platform else "",+ "user_id": ctx.source.user_id, "session_id": ctx.session_id,+ "iteration": iteration, "tool_names": names, "tools": prev_tools,+ }),+ "agent:step hook scheduling error",+ )++ def _event_callback_sync(self, event_type: str, context: dict) -> None:+ ctx = self._ctx+ try:+ asyncio.run_coroutine_threadsafe(ctx._hooks_ref.emit(event_type, context), ctx._loop_for_step)+ except Exception as e:+ logger.debug("event_callback hook error: %s", e)++ def _status_live(self) -> bool:+ """Status adapter present and this run is still the current generation."""+ return bool(self._ctx._status_adapter) and self._ctx._run_still_current()++ def _send_status_text(self, text: str, metadata, log_message: str) -> None:+ ctx = self._ctx+ self._schedule(ctx._status_adapter.send(ctx._status_chat_id, text, metadata=metadata), log_message)++ def _attach_session_title_callback(self, agent, ctx) -> None:+ """Wire the platform thread-rename lane onto the agent as `_on_session_title`.++ The titler runs in the turn prologue, so attach before the run, not after it.+ """+ try:+ # Gateway auto-title failures are not user-actionable, so never surface them as messages;+ # overriding the failure sink keeps CLI on _emit_auxiliary_failure while gateway logs debug.+ agent._title_failure_callback = lambda task, exc: logger.debug(+ "Gateway auto-title failure suppressed (not user-visible): %s: %s", task, exc,+ )+ session_id = getattr(agent, "session_id", None)+ source = ctx.source+ runner = self._runner+ # Both lanes spend a rate-limited platform call per title, so they use the model's title+ # only (TitleCallback); renaming twice burns Discord's 2-per-10-min budget on a throwaway.+ # Relay Discord predicate is shape-only: whether the connector auto-threaded our reply is+ # only knowable AFTER delivery, so register eagerly and let the rename lane look up the+ # cache at fire time — gating registration on the cache read meant it never registered.+ if runner._is_telegram_topic_lane(source):+ lane = "_schedule_telegram_topic_title_rename"+ elif runner._is_discord_auto_thread_lane(source) or runner._is_relay_discord_channel_lane(source):+ lane = "_schedule_discord_semantic_thread_rename"+ else:+ return+ agent._on_session_title = lambda title, title_source: (+ title_source == "llm" and getattr(runner, lane)(source, session_id, title)+ )+ except Exception:+ logger.debug("Failed to attach session title callback", exc_info=True)++ def _status_callback_sync(self, event_type: str, message: str) -> None:+ from gateway.run import _prepare_gateway_status_message, _redact_gateway_user_facing_secrets, _send_or_update_status_coro++ from gateway.warning_notifications import is_warning_status, render_notification+ ctx = self._ctx- if not self._status_live():++ if ctx.mute_notification_reply or not self._status_live():+ return+ prepared = _prepare_gateway_status_message(ctx.source.platform, event_type, message)+ if prepared is None:+ logger.debug(+ "status_callback suppressed for %s/%s: %s",+ ctx.source.platform.value if ctx.source.platform else "unknown", event_type,+ _redact_gateway_user_facing_secrets(str(message or ""))[:160],+ )+ return- fut = self._schedule(- _send_or_update_status_coro(ctx._status_adapter, ctx._status_chat_id, event_type, prepared, ctx._status_thread_metadata),- f"status_callback ({event_type}) scheduling error",- )- if fut is not None and ctx._cleanup_progress:- fut.add_done_callback(self._track_future_cleanup_id)++ def present():++ fut = self._schedule(++ _send_or_update_status_coro(ctx._status_adapter, ctx._status_chat_id, event_type, prepared, ctx._status_thread_metadata),++ f"status_callback ({event_type}) scheduling error",++ )++ if fut is not None and ctx._cleanup_progress:++ fut.add_done_callback(self._track_future_cleanup_id)++ render_notification(present, platform=ctx.source.platform, user_config=ctx.user_config,++ diagnostic=is_warning_status(event_type, message))diff --cc gateway/run_turn_runner.pyindex a553efc2a61,1b2e2c0bd31..5a3c397fe80--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@@ -152,13 -959,16 +167,18 @@@ class TurnRunner(GatewayTurnProgressMixexcept Exception as err:logger.debug("Could not set up stream consumer: %s", err)# Deltas tee to the stream consumer (when text streaming is on) and to streaming TTS.- delta_sinks = [sc for sc in ((stream_consumer if want_stream_deltas else None), stts) if sc is not None]+ delta_sinks = [+ sc for sc in (+ stream_consumer if stream_consumer and stream_consumer.stream_deltas_enabled else None,+ stts,+ ) if sc is not None+ ]stream_delta_cb = None- if delta_sinks:+ if delta_sinks or self._approval_owner is not None:def stream_delta_cb(text: Optional[str]) -> None:if ctx._run_still_current():+ if text is not None: # None closes only the native stream segment.+ self._publish_execution("message.delta", {"text": text})for sink in delta_sinks:sink.on_delta(text)@@@ -299,10 -1290,17 +326,20 @@@# Thinking between tool calls is independent of tool_progress mode (Mattermost opts in# per platform so global scratch-text doesn't leak into threads).agent.thinking_progress = ctx._thinking_enabled+ if ctx.mute_notification_reply:+ # Controls and operational event/step callbacks remain wired. These+ # presentation callbacks are rebound on every next turn.+ agent.tool_progress_callback = None+ agent.tool_start_callback = None+ agent.tool_complete_callback = None+ # Keep diagnostic observers installed; concrete sinks veto display.+ agent.stream_delta_callback = None+ agent.interim_assistant_callback = None+ agent.thinking_progress = Falsectx.agent_holder[0] = agent # interrupt support+ if self._approval_owner is not None:+ authority, owner_id, generation = self._approval_owner+ authority.adopt_agent(owner_id, generation, agent)# The titler fires from the turn prologue, so attach the rename lane before the run.self._attach_session_title_callback(agent, ctx)# Publish turn ownership for /stop, /new, disconnect and shutdown interrupts; older session@@@ -396,7 -1390,16 +436,16 @@@session_key = ctx.session_key or ""clarify_id = uuid.uuid4().hex[:10]choices = list(choices) if choices else None+ send_kwargs = dict(+ chat_id=ctx._status_chat_id, question=question, choices=choices, clarify_id=clarify_id,+ session_key=session_key, metadata=ctx._status_thread_metadata,+ )++ def _text_fallback():+ """Schedule the plain-text prompt when the native card cannot render; None = no such path."""+ coro = text_fallback_coro(ctx._status_adapter, **send_kwargs)+ return None if coro is None else self._schedule(coro, "Clarify text fallback failed to schedule")- clarify_mod.register(+ entry = clarify_mod.register(clarify_id=clarify_id, session_key=session_key, question=question, choices=choices,multi_select=bool(multi_select),)@@@ -417,20 -1420,16 +466,19 @@@except Exception:logger.debug("Stream-consumer flush before clarify prompt failed", exc_info=True)fut = self._schedule(- self._send_shared_clarify(entry,- chat_id=ctx._status_chat_id, question=question, choices=choices, clarify_id=clarify_id,- session_key=session_key, metadata=ctx._status_thread_metadata,- ),- ctx._status_adapter.send_clarify(**send_kwargs),++ self._send_shared_clarify(entry, **send_kwargs),"Clarify send failed to schedule",)# Boundary rule (see _approval_send_outcome): a send timeout is AMBIGUOUS — the card may# have posted with a late ack. Only a definitive failure tears down the registration;- # ambiguous falls through to the bounded wait so a late reply resolves.+ # ambiguous falls through to the bounded wait so a late reply resolves. A definitive+ # failure — immediate or late — retries once as plain text before giving up.response, answered = _clarify_send_then_wait(- fut, clarify_id=clarify_id, session_key=session_key, clarify_mod=clarify_mod)+ fut, clarify_id=clarify_id, session_key=session_key, clarify_mod=clarify_mod,+ fallback=_text_fallback)+ if self._approval_owner is not None:+ authority, session_id, generation = self._approval_owner+ authority.sessions[session_id].controls.snapshot(session_id, generation)# Branch on the explicit flag, never on the text: a real answer can start with '[' (a# "[A] staging" label, "[urgent] ..." free text) and must not be mistaken for a sentinel.if not answered:@@@ -734,17 -1721,9 +793,19 @@@# turn so a restart-interrupted turn is recorded WITH its id for drain-window dedup.if ctx.inbound_message_id is not None:kwargs["persist_user_platform_id"] = str(ctx.inbound_message_id)+ from agent.notification_presentation import notification_turn+ from gateway.session_results import execution_result+ captured = execution_result.get()+ before = (getattr(agent, 'session_prompt_tokens', 0) or 0,+ getattr(agent, 'session_completion_tokens', 0) or 0)- result = agent.run_conversation(api_message, **kwargs)+ with notification_turn(agent, muted=ctx.mute_notification_reply, session_id=ctx.session_id or ""):- return agent.run_conversation(api_message, **kwargs)++ result = agent.run_conversation(api_message, **kwargs)+ if captured is not None:+ incoming = max(0, (getattr(agent, 'session_prompt_tokens', 0) or 0) - before[0])+ outgoing = max(0, (getattr(agent, 'session_completion_tokens', 0) or 0) - before[1])+ captured['usage'] = {'input_tokens': incoming, 'output_tokens': outgoing,+ 'total_tokens': incoming + outgoing}+ return resultfinally:unregister_gateway_notify(session_key)# Cancel pending clarify entries so blocked agent threads don't hang past the end of the@@@ -956,10 -1911,10 +1017,14 @@@model, runtime_kwargs = runner._resolve_session_agent_runtime(source=ctx.source, session_key=ctx.session_key, user_config=ctx.user_config,)+ # Stashed by _resolve_session_agent_runtime when the primary's credentials failed and a+ # fallback was resolved before any agent exists (#74349); one-shot per turn.+ pending_fallback_notice = getattr(runner, "_pre_agent_fallback_notice", None)+ runner._pre_agent_fallback_notice = None+ from gateway.session_api_turn import prepare_api_runtime+ model, runtime_kwargs = prepare_api_runtime(model, runtime_kwargs)+ if policy and policy.model:+ model = policy.modellogger.debug("run_agent resolved: model=%s provider=%s session=%s",model, runtime_kwargs.get("provider"), ctx.session_key or "",@@@ -968,34 -1923,23 +1033,43 @@@# Model/credential resolution failed before the turn began; the raw text (URLs, status# codes) belongs in the log, and the chat gets the commands that fix it.logger.warning("Model resolution failed for session %s: %s", ctx.session_key or "", exc)+ from hermes_state_runtime import RuntimeStoreError+ if isinstance(exc, RuntimeStoreError):+ # Session-policy refusals carry a stable reason code (e.g. a CLI launch key+ # revoked by daemon restart): keep it in the reply so clients can act on it, and+ # do not suggest /login — the profile's own credentials were never in play.+ text = (f"⚠️ This session's launch credentials are no longer available "+ f"({exc.reason}), so this message wasn't processed. Start a new "+ "session from the CLI to bind them again.")- else:- text = ("⚠️ I couldn't connect to the AI model service, so this message wasn't processed. "- "Use /login to sign in again, or /model to pick a different model. If it keeps "- "failing, run `hermes doctor` on the host.")- return {"final_response": text, "messages": [], "api_calls": 0, "tools": []}++ return {"final_response": text, "messages": [], "api_calls": 0, "tools": []}+ from hermes_cli.auth import is_rate_limited_auth_error+ if is_rate_limited_auth_error(exc.__cause__):+ # Quota cap with valid credentials: /login cannot help; name the reset window (#89401).+ from gateway.run import _gateway_provider_error_reply+ return {"final_response": _gateway_provider_error_reply(str(exc)),+ "messages": [], "api_calls": 0, "tools": []}+ return {+ "final_response": (+ "⚠️ I couldn't connect to the AI model service, so this message wasn't processed. "+ "Use /login to sign in again, or /model to pick a different model. If it keeps "+ "failing, run `hermes doctor` on the host."),+ "messages": [], "api_calls": 0, "tools": [],+ }pr = runner._provider_routing- reasoning_config = runner._resolve_session_reasoning_config(source=ctx.source, session_key=ctx.session_key, model=model)- runner._reasoning_config = reasoning_config+ reasoning_config = (policy.reasoning_config if policy else+ runner._resolve_session_reasoning_config(source=ctx.source, session_key=ctx.session_key, model=model))runner._service_tier = runner._resolve_session_service_tier(source=ctx.source, session_key=ctx.session_key)+ from gateway.session_api_turn import api_execution+ api = api_execution.get()+ if api is not None:+ from gateway.platforms.api_server import _request_reasoning_config, _request_service_tier, _REQUEST_OPTION_MISSING+ requested_reasoning = _request_reasoning_config(api['settings'].get('model_options'))+ if requested_reasoning is not None:+ reasoning_config = requested_reasoning+ tier = _request_service_tier(api['settings'].get('model_options'))+ if tier is not _REQUEST_OPTION_MISSING:+ runner._service_tier = tier+ runner._reasoning_config = reasoning_configstream_consumer, stream_delta_cb, interim_cb, want_interim = self._setup_stream_consumer(platform_key)turn_route = runner._resolve_turn_agent_config(ctx.message, model, runtime_kwargs)agent, reused_cached_agent = self._resolve_turn_agent(diff --cc gateway/session_cron.pyindex 902dbf2f031,00000000000..8c0b2ed5b6amode 100644,000000..100644--- a/gateway/session_cron.py+++ b/gateway/session_cron.py@@@ -1,198 -1,0 +1,209 @@@+"""Trusted cron producer and owner execution of the existing scheduler contract.++Public callers name a persisted job, never supply agent policy or arbitrary jobs.+The ordinary admission ledger owns execution; the scheduler owns final delivery.+"""+import asyncio+from contextvars import ContextVar+from dataclasses import asdict, replace+import json+import os+from pathlib import Path+import threading++from gateway.session_contract import Principal, SessionRef+from hermes_state_runtime import RuntimeStoreError, admit_session_input, get_session_admission++_execution: ContextVar[tuple | None] = ContextVar('cron_owner_execution', default=None)+_owners = {}+++def bind_owner(authority):+ home = Path(authority.db.db_path).resolve().parent+ _owners[home] = (os.getpid(), authority, asyncio.get_running_loop())+++def unbind_owner(authority):+ home = Path(authority.db.db_path).resolve().parent+ bound = _owners.get(home)+ if bound is not None and bound[1] is authority:+ del _owners[home]+++def owner_for_home(home):+ bound = _owners.get(Path(home).resolve())+ if bound is not None and bound[0] == os.getpid() and not bound[2].is_closed():+ return bound[1:]+ return None+++def current_execution():+ return _execution.get()+++def _actor(authority, actor):+ if actor is None:+ return Principal('cron-owner', authority.profile_id,+ frozenset({'session:create', 'session:submit', 'session:read', 'session:control'}), 'cron-ticker')+ if actor.profile_id != authority.profile_id:+ raise RuntimeStoreError('profile_mismatch')+ if not {'session:create', 'session:submit', 'session:control'} <= actor.capabilities:+ raise RuntimeStoreError('permission_denied')+ # Cron fires belong to the profile scheduler, not the transport that observes+ # them. The same execution ID from ticker and CLI must dedupe together.+ return Principal('cron-owner', authority.profile_id, actor.capabilities, actor.transport_id)+++def _create(authority, actor, params):+ from cron.jobs import get_job+ from gateway.session_local_recovery import local_identity, restore_local_session+ from gateway.session_policy import build_policy, bind_launch_key+ from gateway.run import _load_gateway_config+ from cron.scheduler import _load_cron_job_config+ from hermes_state_local import commit_local_session+ from gateway.config import Platform+ from gateway.session import SessionSource, SessionEntry+ from gateway.session_lifecycle import _now++ if set(params) != {'job_id', 'request_id', 'extra_prompt'}:+ raise RuntimeStoreError('invalid_params')+ jid, request_id, extra = params['job_id'], params['request_id'], params['extra_prompt']+ if (not isinstance(jid, str) or not jid or not isinstance(request_id, str)+ or not request_id or len(request_id) > 256 or (extra is not None and not isinstance(extra, str))):+ raise RuntimeStoreError('invalid_params')+ request_id = 'cron:' + jid + ':' + request_id+ sid = local_identity(authority.profile_id, actor.subject, request_id)+ if authority.db.get_session(sid) is not None:+ return restore_local_session(authority, sid), request_id+ job = get_job(jid)+ if job is None or job.get('no_agent'):+ raise RuntimeStoreError('not_found')+ config = _load_gateway_config()+ private = {}+ launch = {'source': 'cli', 'request_id': request_id, 'toolsets': []}+ if job.get('workdir'):+ launch['cwd'] = job['workdir']+ policy = build_policy(launch, config, private_secrets=private)+ policy = replace(policy, source='cron', platform='cron', model=_load_cron_job_config(job, jid, job.get('name') or jid).model,+ request_json=json.dumps({'cron_job': job, 'extra_prompt': extra, 'request_id': request_id}))+ policy = bind_launch_key(authority, sid, policy, None, config_secrets=private)+ from gateway.session_local_recovery import local_source+ source = local_source(authority, sid, actor.subject)+ route = authority.runner.session_store._generate_session_key(source)+ 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), request_id++++# Run-side verdicts run_job stamps on the job dict for the firing scheduler's bookkeeping tail++# (cron/quota_hold.py parks past a closed usage window; cron/unreachable_retry.py re-runs a++# never-reached model). They cross the authority boundary inside the cron result.++RUN_JOB_FLAGS = ('_model_unreachable', '_quota_hold_seconds')+++++async def operation(authority, name, params, actor=None):+ actor = _actor(authority, actor)+ authority._require_admission_open()+ if name == 'recover':+ from gateway.session_local_recovery import local_identity+ if (set(params) != {'job_id', 'request_id', 'extra_prompt'}+ or any(not isinstance(params[k], str) or not params[k] for k in ('job_id', 'request_id'))+ or (params['extra_prompt'] is not None and not isinstance(params['extra_prompt'], str))):+ raise RuntimeStoreError('invalid_params')+ request_id = 'cron:' + params['job_id'] + ':' + params['request_id']+ sid = local_identity(authority.profile_id, actor.subject, request_id)+ from hermes_state_runtime import list_session_admissions+ rows = list_session_admissions(authority.db, session_id=sid, pending_only=False)+ row = next((r for r in rows if r['request_id'] == request_id and r['principal_id'] == actor.subject), None)+ if row is None:+ return {'status': 'missing', 'result': None}+ state = await operation(authority, 'status', {'session_id': sid, 'admission_id': row['admission_id']}, actor)+ from gateway.session_local_recovery import restore_local_session+ restore_local_session(authority, sid)+ from gateway.config import Platform+ from gateway.session_local_recovery import local_adapter_map+ policy = local_adapter_map(authority)[Platform.LOCAL].policies[sid]+ frozen = json.loads(policy.request_json)+ if frozen['extra_prompt'] != params['extra_prompt']:+ raise RuntimeStoreError('admission_conflict')+ state['job'] = frozen['cron_job']+ return state+ if name == 'submit':+ from gateway.session_authorities import owner_scope+ # The job id, jobs file and gateway config belong to the OWNING profile.+ with owner_scope(authority):+ ref, request_id = _create(authority, actor, params)+ row = admit_session_input(authority.db, epoch=authority.epoch, principal_id=actor.subject,+ session_id=ref.session_id, request_id=request_id,+ payload={'text': params['extra_prompt'] or ''})+ authority._publish_pending(ref)+ authority._schedule(ref)+ return {'session_id': ref.session_id, 'admission_id': row['admission_id']}+ if set(params) != {'session_id', 'admission_id'} or name not in {'status', 'cancel'}:+ raise RuntimeStoreError('invalid_params')+ ref = SessionRef(authority.profile_id, params['session_id'])+ authority.authorize(actor, ref, 'session:submit')+ row = get_session_admission(authority.db, admission_id=params['admission_id'])+ if row is None or row['target_session_id'] != ref.session_id or row['principal_id'] != actor.subject:+ raise RuntimeStoreError('permission_denied')+ if name == 'cancel':+ if row['status'] == 'queued':+ await authority.cancel_queued(actor, ref, row['admission_id'])+ elif row['status'] == 'started':+ # The claim commits before execute() registers its event; latching the+ # cancellation on the admission here means that window cannot lose it.+ _cancellations(authority).setdefault(row['admission_id'], threading.Event()).set()+ return {'ok': True}- result = None++ result, flags = None, {}+ if row['status'] == 'terminal':+ from gateway.session_results import admission_result+ saved = admission_result(authority.db, row['admission_id'])+ result = saved['result'].get('cron_result') if saved else None++ flags = (saved['result'].get('cron_job_flags') or {}) if saved else {}+ if result is None:+ result = [False, '', '', row.get('outcome') or 'unknown_execution']- return {'status': row['status'], 'result': result}++ return {'status': row['status'], 'result': result, 'job_flags': flags}+++def _cancellations(authority):+ cancellations = getattr(authority, '_cron_cancellations', None)+ if cancellations is None:+ cancellations = authority._cron_cancellations = {}+ return cancellations+++async def rpc(connection, name, params):+ return await operation(connection.authority, name, params, connection.actor)+++async def execute(authority, ref, row, policy):+ from cron.scheduler import run_job+ from gateway.run import _profile_runtime_scope+ data = json.loads(policy.request_json)+ if (row['payload'] != {'text': data['extra_prompt'] or ''}+ or row['request_id'] != data['request_id']+ or row['principal_id'] != authority.sessions[ref.session_id].source.user_id):+ raise RuntimeStoreError('admission_conflict')+ cancellations = _cancellations(authority)+ cancel = cancellations.setdefault(row['admission_id'], threading.Event())+ token = _execution.set((authority, ref.session_id, data['cron_job']['id'], row['admission_id']))+ try:++ job = data['cron_job']+ with _profile_runtime_scope(Path(authority.db.db_path).resolve().parent):- result = await asyncio.to_thread(run_job, data['cron_job'], extra_prompt=data['extra_prompt'],++ result = await asyncio.to_thread(run_job, job, extra_prompt=data['extra_prompt'],+ execution_id=row['admission_id'], cancel_event=cancel)++ # run_job stamps run-side verdicts on ITS job copy (quota hold, unreachable model); the++ # firing scheduler's bookkeeping reads them off its own dict, so they ride the result.++ flags = {key: job[key] for key in RUN_JOB_FLAGS if key in job}+ authority.pending_results[row['admission_id']] = {- 'result': {'final_response': result[2], 'cron_result': list(result),++ 'result': {'final_response': result[2], 'cron_result': list(result), 'cron_job_flags': flags,+ 'failed': not result[0], 'completed': result[0]}, 'usage': {}}+ if not result[0]:+ raise RuntimeError(result[3] or 'cron execution failed')+ return result[2]+ finally:+ _execution.reset(token)+ cancellations.pop(row['admission_id'], None)diff --cc gateway/session_identity.pyindex 3a0d30622d1,aba8789b506..65b9cc68044--- a/gateway/session_identity.py+++ b/gateway/session_identity.py@@@ -1,18 -1,273 +1,290 @@@- """Stable owner keys from server-authenticated identity, never RPC parameters."""+ """One frozen routing identity per inbound gateway event.++ A multiplexed gateway answers three questions about every event, and until now answered them in+ three places that only agreed because they read the same fallback chain: WHICH bot received it+ (``_transport_owner``), WHO may admit it (``_authorization_home_for_source``) and WHERE the turn+ runs (``_resolve_profile_home_for_source`` / ``_session_key_profile``). :func:`resolve_identity`+ answers all three once and pins the result on the source as a wire-invisible dynamic attribute+ (like ``_transport_adapter_ref``); the existing helpers read it when present and keep their+ fallback chain when absent, so a source built outside the runner still resolves as before.++ ``SessionSource.profile`` stays the serialized runtime profile — ``None`` on the wire means the+ receiving bot's own profile — so nothing here changes the wire format or any historical+ ``agent:main`` key.+ """+ from __future__ import annotations++ import dataclasses+import json+ import logging+ from contextlib import suppress+ import weakref+ from dataclasses import dataclass, field+ from pathlib import Path+ from typing import TYPE_CHECKING, Any, Optional++ if TYPE_CHECKING:+ from gateway.session import SessionSource++ logger = logging.getLogger(__name__)++ _IDENTITY_ATTR = "_identity"+ # Wire-invisible provenance copied alongside the identity when a source is duplicated.+ _PROVENANCE_ATTRS = ("_transport_adapter_ref", "_authorization_profile_home", _IDENTITY_ATTR)+++ class IdentityUnresolved(RuntimeError):+ """Under multiplexing the event's runtime profile could not be established (an explicit+ ``profile_routes`` entry targets a profile this gateway does not serve). Callers drop the+ event; it must never fall through to the default profile."""+++ @dataclass(frozen=True)+ class RoutingIdentity:+ """Everything a turn needs to know about who it is, resolved once at ingress.++ ``transport_profile`` owns the receiving adapter (its credential and allowlist);+ ``runtime_profile`` is the profile that executes the turn — the same name unless a+ ``profile_routes`` entry re-homed the event. Both are explicit (``"default"`` is spelled out);+ ``None`` never means default here. ``multiplexed`` is False for a standalone gateway, whose+ keys stay in the legacy ``agent:main`` namespace whatever profile it was launched with.+ """++ transport_profile: str+ runtime_profile: str+ authorization_home: Path+ runtime_home: Path+ multiplexed: bool = True+ # Receiving adapter; None for restored/synthetic sources (no live provenance → fail closed).+ # Provenance, not identity: two events from the same bot share one identity.+ transport: Optional[weakref.ref] = field(default=None, compare=False, hash=False)+ # True when nothing named the receiving bot (no live adapter, no persisted transport_profile,+ # no explicit hint) and ``transport_profile`` is the primary by default. A hand-built or+ # pre-column source. Delivery may still fall back to the runtime profile's unique adapter for+ # these; an identity whose transport is KNOWN (live or restored) never does.+ transport_inferred: bool = field(default=False, compare=False, hash=False)++ @property+ def namespace(self) -> str:+ """``agent:<ns>`` prefix for this identity's session keys — byte-identical to+ :func:`gateway.session._session_key_namespace` for every historical key."""+ from gateway.session import _session_key_namespace+ return _session_key_namespace(self.session_key_profile)++ @property+ def store_path(self) -> Path:+ return self.runtime_home / "state.db"++ @property+ def session_key_profile(self) -> Optional[str]:+ """The ``profile=`` argument :func:`gateway.session.build_session_key` expects for this+ identity: the runtime profile under multiplexing, else ``None`` (legacy namespace)."""+ return self.runtime_profile if self.multiplexed else None++ def adapter(self) -> Any:+ """The live receiving adapter, or None when it is gone or was never known."""+ return self.transport() if self.transport is not None else None+++ def identity_of(source: Any) -> Optional[RoutingIdentity]:+ """The identity pinned on *source* by :func:`resolve_identity`, if any."""+ identity = getattr(source, _IDENTITY_ATTR, None)+ return identity if isinstance(identity, RoutingIdentity) else None+++ def clear_identity(source: Any) -> None:+ """Drop the pinned identity AND the routed runtime profile so the next :func:`canonical_identity`+ re-routes from scratch — for sources a caller reuses across events whose routing may differ (a+ guild's cached voice source is shared by every speaker, and ``profile_routes[].user_id`` routes+ per speaker). ``source.profile`` is the previous event's routing *result*; left in place it+ short-circuits the route and the new speaker runs as the old one."""+ for attr in (_IDENTITY_ATTR, "profile_route_rejected", "_authorization_profile_home"):+ with suppress(AttributeError):+ delattr(source, attr)+ with suppress(AttributeError):+ source.profile = None+++ def transport_profile_of(source: Any) -> Optional[str]:+ """The receiving bot's profile to persist alongside a routing entry (``SessionEntry.transport_profile``);+ None outside multiplexing or when nothing resolved the source (an unknown transport is never guessed)."""+ identity = identity_of(source)+ return identity.transport_profile if identity is not None and identity.multiplexed else None+++ def replace_source(source: "SessionSource", **changes: Any) -> "SessionSource":+ """:func:`dataclasses.replace` that keeps the wire-invisible provenance (transport ref,+ authorization home, identity). A plain ``replace`` silently produces a source the runner+ can only route through heuristics."""+ copied = dataclasses.replace(source, **changes)+ for name in _PROVENANCE_ATTRS:+ value = getattr(source, name, None)+ if value is not None:+ setattr(copied, name, value)+ return copied+++ def _name(value: Any) -> Optional[str]:+ text = value.strip() if isinstance(value, str) else ""+ return text or None+++ def canonical_identity(+ source: "SessionSource", *, runner: Any, adapter: Any = None,+ transport_profile: Optional[str] = None, primary_home: Optional[Path] = None,+ ) -> Optional[RoutingIdentity]:+ """The identity already pinned on *source*, else :func:`resolve_identity` — the one call every+ ingress path makes FIRST, before any key is derived. ``None`` = unresolved under multiplexing+ (``source.profile_route_rejected`` is set): the caller drops the event and says so once; it+ must never fall through to ``agent:main``."""+ identity = identity_of(source)+ if identity is not None:+ return identity+ try:+ return resolve_identity(+ source, runner=runner, adapter=adapter, transport_profile=transport_profile,+ primary_home=primary_home)+ except IdentityUnresolved as exc:+ logger.debug("identity unresolved: %s", exc)+ return None+++ def restore_identity(+ source: "SessionSource", *, runner: Any, transport_profile: Optional[str],+ ) -> Optional[RoutingIdentity]:+ """Pin the identity of a source rebuilt from durable state (``SessionEntry.origin``, a+ ``sessions`` row, a cached copy) — no live adapter, so ``transport=None``: the restored row of the+ transport matrix, where delivery goes through the persisted transport owner or fails closed.++ *transport_profile* is what the routing index persisted at ingress (``SessionEntry.transport_profile``);+ ``None`` = a row written before the column existed, whose transport is unknown → nothing is pinned+ and the legacy heuristics (``_is_shared_bot_satellite``) keep deciding. Standalone gateways have+ nothing to restore (one bot, one home).+ """+ transport_name = _name(transport_profile)+ if transport_name is None:+ return None+ if not bool(getattr(getattr(runner, "config", None), "multiplex_profiles", False)):+ return None+ existing = identity_of(source)+ if existing is not None:+ return existing+ from hermes_cli.profiles import get_profile_dir+ from hermes_constants import get_process_hermes_home++ primary_profile = _name(getattr(runner, "_primary_profile_name", None)) or "default"+ runtime_name = _name(getattr(source, "profile", None)) or primary_profile+ authorization_home = (+ Path(get_process_hermes_home()) if transport_name == primary_profile+ else get_profile_dir(transport_name))+ runtime_home = (+ authorization_home if runtime_name == transport_name+ else Path(runner._resolve_profile_home_for_source(source)))+ source._authorization_profile_home = authorization_home+ identity = RoutingIdentity(+ transport_profile=transport_name, runtime_profile=runtime_name,+ authorization_home=authorization_home, runtime_home=runtime_home,+ multiplexed=True, transport=None)+ setattr(source, _IDENTITY_ATTR, identity)+ return identity+++ def resolve_identity(+ source: "SessionSource", *, runner: Any, adapter: Any = None,+ transport_profile: Optional[str] = None, primary_home: Optional[Path] = None,+ ) -> RoutingIdentity:+ """Resolve and pin the :class:`RoutingIdentity` of an inbound *source*.++ *adapter* is the receiving adapter when the caller holds it; otherwise the source's own+ transport provenance is consulted. *transport_profile* names the receiving bot's owning+ profile when the caller knows it by construction (the runner's per-profile handlers);+ ``None`` = derive it from the adapter registry, primary when unknown. *primary_home* is the+ primary bot's home for authorization (default: the process home, never a per-turn override).++ Stamps ``source.profile`` the way the ingress handlers always did (routed name, else a+ secondary's own name; ``None`` stays ``None`` for the primary so the wire is unchanged) and+ ``_authorization_profile_home`` for the existing authorization readers.++ Raises :class:`IdentityUnresolved` under multiplexing when the route is rejected.+ """+ from gateway.profile_routing import ProfileRouteRejected+ from hermes_constants import get_hermes_home, get_process_hermes_home++ multiplexed = bool(getattr(getattr(runner, "config", None), "multiplex_profiles", False))+ primary_profile = _name(getattr(runner, "_primary_profile_name", None))+ if primary_profile is None:+ active = getattr(runner, "_active_profile_name", None)+ primary_profile = (_name(active()) if callable(active) else None) or "default"+ platform = getattr(source, "platform", None)++ owner_profile: Optional[str] = None+ if adapter is None:+ owner = runner._transport_owner(source)+ if owner is not None:+ adapter, owner_profile = owner+ else:+ if getattr(source, "_transport_adapter_ref", None) is None:+ source._transport_adapter_ref = weakref.ref(adapter)+ _registered, owner_profile = runner._owning_profile(adapter, platform)+ transport_name = _name(transport_profile) or _name(owner_profile) or primary_profile+ transport_inferred = adapter is None and _name(transport_profile) is None and _name(owner_profile) is None+ transport_ref = weakref.ref(adapter) if adapter is not None else None++ if not multiplexed:+ home = Path(get_hermes_home())+ identity = RoutingIdentity(+ transport_profile=primary_profile, runtime_profile=primary_profile,+ authorization_home=home, runtime_home=home, multiplexed=False, transport=transport_ref)+ setattr(source, _IDENTITY_ATTR, identity)+ return identity++ if transport_name == primary_profile:+ authorization_home = Path(primary_home) if primary_home is not None else Path(get_process_hermes_home())+ else:+ from hermes_cli.profiles import get_profile_dir+ authorization_home = get_profile_dir(transport_name)+ source._authorization_profile_home = authorization_home++ where = f"{getattr(platform, 'value', platform)}/{getattr(source, 'chat_id', '')}"+ if getattr(source, "profile_route_rejected", False) is True:+ raise IdentityUnresolved(f"{where}: profile route rejected")+ if _name(getattr(source, "profile", None)) is None:+ adapter_profile = None if transport_name == primary_profile else transport_name+ try:+ # The primary keeps the historical one-argument call (its adapter profile is None).+ routed = (+ runner._profile_name_for_source(source) if adapter_profile is None+ else runner._profile_name_for_source(source, adapter_profile=adapter_profile))+ except ProfileRouteRejected as exc:+ source.profile_route_rejected = True+ raise IdentityUnresolved(f"{where}: {exc}") from exc+ source.profile = routed or adapter_profile++ runtime_name = _name(source.profile) or primary_profile+ # A routed runtime goes through the runner's resolver (missing-profile fallback + warning);+ # a bot serving its own profile runs where it authorizes.+ runtime_home = (+ authorization_home if runtime_name == transport_name+ else Path(runner._resolve_profile_home_for_source(source)))+ identity = RoutingIdentity(+ transport_profile=transport_name, runtime_profile=runtime_name,+ authorization_home=authorization_home, runtime_home=runtime_home,+ multiplexed=True, transport=transport_ref, transport_inferred=transport_inferred)+ setattr(source, _IDENTITY_ATTR, identity)+ return identity+++def authenticated_subject(identity):+ """Keep private native receipts stable; namespace every dashboard identity.++ Only the private bootstrap stamps profile/instance/capabilities. A dashboard+ provider named 'local' (or a subject resembling a UID) is not native provenance.+ Historical remote bare-subject receipts cannot be assigned to a first caller.+ """+ subject = str(identity.get('user_id') or 'unbound')+ if (identity.get('provider') == 'local' and identity.get('profile_id')+ and identity.get('instance_id') and 'capabilities' in identity):+ return subject+ return 'auth:v1:' + json.dumps(+ [identity.get('provider') or '', identity.get('issuer') or '', subject],+ separators=(',', ':'), ensure_ascii=True)diff --cc gateway/session_recovery.pyindex b6e00147207,a466af5a25d..e29cc0a6740--- a/gateway/session_recovery.py+++ b/gateway/session_recovery.py@@@ -277,10 -336,9 +336,11 @@@ class SessionRecoveryMixinrecorder = getattr(db, "record_gateway_session_peer", None)if not callable(recorder):return+ from gateway.session_api import api_storage_source+ from gateway.session_a2a import storage_source+ from gateway.session_identity import transport_profile_ofpeer = dict(- source=source.platform.value, user_id=source.user_id, session_key=session_key,+ source=storage_source(db, source, session_id, api_storage_source(db, session_id, source.platform.value)), user_id=source.user_id, session_key=session_key,chat_id=source.chat_id, chat_type=source.chat_type, thread_id=source.thread_id)try:recorder(diff --cc gateway/status.pyindex 72ef433fe1d,96c84bb2f33..b88720c8822--- a/gateway/status.py+++ b/gateway/status.py@@@ -792,74 -1059,72 +1030,74 @@@ def _prepare_runtime_status_updateactive_agents: Any = _UNSET, active_work: Any = _UNSET, platform: Any = _UNSET, platform_state: Any = _UNSET,error_code: Any = _UNSET, error_message: Any = _UNSET, needs_attention: Any = _UNSET,retrying_since: Any = _UNSET, served_profiles: Any = _UNSET, session_store: Any = _UNSET,- multiplex_standalone_reason: Any = _UNSET,+ parked_profiles: Any = _UNSET, multiplex_standalone_reason: Any = _UNSET,ingress_url: Any = _UNSET, listener_base: Any = _UNSET, clear_profile_platforms: bool = False,drop_profile_platforms: Optional[str] = None,- ) -> None:- """Persist gateway runtime health information for diagnostics/status. ``drop_profile_platforms``- removes one deleted profile's ``<profile>:<platform>`` entries (hot unroute)."""+ load_existing: bool = True, reload_existing: bool = False,+ ) -> tuple[Path, dict[str, Any], dict[str, Any]]:+ """Merge one update into the process-wide canonical status snapshot."""+ global _runtime_status_state_path, _runtime_status_statepath = _get_runtime_status_path()- payload = _read_json_file(path) or _build_runtime_status_record()- previous_payload = copy.deepcopy(payload)- current_record = _build_pid_record()- payload.setdefault("platforms", {})- if clear_profile_platforms or drop_profile_platforms:- # Secondary-profile entries are keyed ``<profile>:<platform>``. A fresh process must not- # inherit them or /api/status stays degraded until every old adapter re-emits.- platforms = payload["platforms"] if isinstance(payload["platforms"], dict) else {}- drop_prefix = f"{drop_profile_platforms}:" if drop_profile_platforms else None- payload["platforms"] = {- k: v for k, v in platforms.items()- if not isinstance(k, str) or ":" not in k or (drop_prefix is not None and not k.startswith(drop_prefix))- }- # Re-stamp identity + code fields on every write: the file can outlive its creator and the- # top-level record must describe the CURRENT writer.- payload.update({key: current_record[key] for key in ("kind", "pid", "argv", "start_time")})- payload["updated_at"] = _utc_now_iso()- payload.update(_get_code_identity_fields())- _apply_set_fields(payload, (- ("gateway_state", gateway_state, None), ("exit_reason", exit_reason, None),- ("restart_requested", restart_requested, bool),- ("active_agents", active_agents, parse_active_agents),- # Named in-flight units (see GatewayShutdownMixin._describe_active_work); None clears.- ("active_work", active_work, lambda v: list(v) if v else None),- # Multiplexed profiles; absent/empty for a single-profile gateway.- ("served_profiles", served_profiles, lambda v: list(v or [])),- # Profiles the multiplexer could not serve, name -> reason; clients fail fast on them.- ("parked_profiles", parked_profiles, lambda v: {str(k): str(r) for k, r in dict(v or {}).items()}),- # Why an unset-default (multiplex on) gateway is serving one profile; None clears it.- ("multiplex_standalone_reason", multiplex_standalone_reason, lambda v: str(v) if v else None),- ("session_store", session_store, _coerce_session_store),- ))- if platform is not _UNSET:- platform_payload = payload["platforms"].get(platform, {})- if platform_state == "connected":- # Every writer that publishes ``connected`` (startup stamp, adapter ``_mark_connected``,- # Telegram's in-place polling recovery) ends the retry episode; only the watcher's- # reconnect path used to say so, and a restart after a NEEDS_ATTENTION escalation- # carried the flag into a healthy record for weeks.- needs_attention = False if needs_attention is _UNSET else needs_attention- retrying_since = None if retrying_since is _UNSET else retrying_since- _apply_set_fields(platform_payload, (- ("state", platform_state, None), ("error_code", error_code, None),- ("error_message", error_message, None),- # Reconnect-loop escalation past the attention threshold: a signal for owners/fleet- # monitoring, not a circuit breaker (retry never stops). Cleared on reconnect.- ("needs_attention", needs_attention, bool),- # ISO start of the current retry episode; None clears it.- ("retrying_since", retrying_since, None),- # Shared-listener secondaries: the /p/<profile>/ callback URL the vendor console must target.- ("ingress_url", ingress_url, None),- # Bound listener (``http://host:port``) of the default's api_server/webhook: a served- # profile's mirror of that platform is reported off it (``<listener_base>/p/<profile>/...``).- ("listener_base", listener_base, None),+ with _runtime_status_state_lock:+ if reload_existing or _runtime_status_state_path != path or _runtime_status_state is None:+ _runtime_status_state_path = path+ _runtime_status_state = (+ (_read_json_file(path) if load_existing else None) or _build_runtime_status_record())+ # The module snapshot is only ever reassigned (never mutated in place) and+ # submit() copies again, so the previous snapshot can be handed out as-is.+ previous_payload = _runtime_status_state+ payload = copy.deepcopy(previous_payload)+ current_record = _build_pid_record()+ payload.setdefault("platforms", {})+ if not isinstance(payload["platforms"], dict):+ payload["platforms"] = {}+ if clear_profile_platforms or drop_profile_platforms:+ drop_prefix = f"{drop_profile_platforms}:" if drop_profile_platforms else None+ payload["platforms"] = {+ k: v for k, v in payload["platforms"].items()+ if not isinstance(k, str) or ":" not in k+ or (drop_prefix is not None and not k.startswith(drop_prefix))+ }+ payload.update({key: current_record[key] for key in ("kind", "pid", "argv", "start_time")})+ payload["updated_at"] = _utc_now_iso()+ payload.update(_get_code_identity_fields())+ _apply_set_fields(payload, (+ ("gateway_state", gateway_state, None), ("exit_reason", exit_reason, None),+ ("restart_requested", restart_requested, bool),+ ("active_agents", active_agents, parse_active_agents),+ ("active_work", active_work, lambda v: list(v) if v else None),+ ("served_profiles", served_profiles, lambda v: list(v or [])),++ # Profiles the multiplexer could not serve, name -> reason; clients fail fast on them.++ ("parked_profiles", parked_profiles, lambda v: {str(k): str(r) for k, r in dict(v or {}).items()}),+ ("multiplex_standalone_reason", multiplex_standalone_reason, lambda v: str(v) if v else None),+ ("session_store", session_store, _coerce_session_store),))- # Per-entry writer provenance: top-level pid/start_time only identify the most recent- # writer; /api/status tells "live" from "preserved" by exact (pid, start_time) equality.- platform_payload.update(updated_at=_utc_now_iso(), writer_pid=current_record["pid"],- writer_start_time=current_record["start_time"])- payload["platforms"][platform] = platform_payload- _write_json_file(path, payload)+ if platform is not _UNSET:+ platform_payload = copy.deepcopy(payload["platforms"].get(platform, {}))+ if not isinstance(platform_payload, dict):+ platform_payload = {}+ if platform_state == "connected":+ needs_attention = False if needs_attention is _UNSET else needs_attention+ retrying_since = None if retrying_since is _UNSET else retrying_since+ _apply_set_fields(platform_payload, (+ ("state", platform_state, None), ("error_code", error_code, None),+ ("error_message", error_message, None),+ ("needs_attention", needs_attention, bool),+ ("retrying_since", retrying_since, None),+ ("ingress_url", ingress_url, None),+ ("listener_base", listener_base, None),+ ))+ platform_payload.update(+ updated_at=_utc_now_iso(), writer_pid=current_record["pid"],+ writer_start_time=current_record["start_time"])+ payload["platforms"][platform] = platform_payload+ _runtime_status_state = payload+ return path, payload, previous_payload+++ def _emit_runtime_status_transition(+ previous_payload: dict[str, Any], payload: dict[str, Any]+ ) -> None:with contextlib.suppress(Exception):from agent.monitoring.gateway_health import emit_runtime_status_transitionemit_runtime_status_transition(previous_payload, payload)diff --cc hermes_cli/cli_auto_maintenance.pyindex 00000000000,dcc14dc7ee9..39c463012d3mode 000000,100644..100644--- a/hermes_cli/cli_auto_maintenance.py+++ b/hermes_cli/cli_auto_maintenance.py@@@ -1,0 -1,74 +1,78 @@@+ """Startup auto-maintenance for the classic CLI: state-db pack/vacuum and checkpoint pruning run off the prompt thread.++ Split out of ``cli.py``; ``cli`` re-exports every public name and moved bodies late-bind+ cli-level names through ``from cli import ...`` at call time so facade monkeypatch seams hold.+ """++ from __future__ import annotations++ import logging+ import threading++ # Log-record parity with the origin module.+ logger = logging.getLogger("cli")+++ def _run_state_db_auto_maintenance(session_db) -> None:+ """One-time repairs + auto-archive/prune/vacuum per the ``sessions:`` config. Never raises."""+ if session_db is None:+ return+ try:+ from hermes_cli.config import load_config as _load_full_config+ from hermes_constants import get_hermes_home as _get_hermes_home # lazy: tests patch it+ _hermes_home_maint = _get_hermes_home()++ # One-time repairs, each latched in state_meta once it has run.+ for meta_key, repair, done_msg, skip_msg in (+ (+ "ghost_session_prune_v1",+ lambda: session_db.prune_empty_ghost_sessions(sessions_dir=_hermes_home_maint / "sessions"),+ "Pruned %d empty TUI ghost sessions", "Ghost session prune skipped: %s",+ ),+ (+ "orphaned_compression_finalize_v1",+ session_db.finalize_orphaned_compression_sessions,+ "Finalized %d orphaned compression sessions", "Orphan compression finalize skipped: %s",+ ),+ ):++ if session_db.get_meta(meta_key):++ continue+ try:- if not session_db.get_meta(meta_key):- count = repair()- session_db.set_meta(meta_key, "1")- if count:- logger.info(done_msg, count)++ count = repair()+ except Exception as _exc:- logger.debug(skip_msg, _exc)++ # Latched below regardless: a repair this store refuses (live ledger work,++ # locked file) must surface once, not retry silently on every start.++ logger.warning(skip_msg, _exc)++ count = 0++ session_db.set_meta(meta_key, "1")++ if count:++ logger.info(done_msg, count)++ cfg = (_load_full_config().get("sessions") or {})++ # Auto-archive is independent of auto_prune: run it before prune's early return.+ if cfg.get("auto_archive", False):+ session_db.maybe_auto_archive(+ idle_days=float(cfg.get("auto_archive_days", 3)),+ min_interval_hours=int(cfg.get("min_interval_hours", 24)),+ )++ if not cfg.get("auto_prune", False):+ return+ session_db.maybe_auto_prune_and_vacuum(+ retention_days=int(cfg.get("retention_days", 90)),+ min_interval_hours=int(cfg.get("min_interval_hours", 24)),+ min_vacuum_interval_days=int(cfg.get("min_vacuum_interval_days", 30)),+ vacuum=bool(cfg.get("vacuum_after_prune", True)),+ sessions_dir=_hermes_home_maint / "sessions",+ )+ except Exception as exc:+ logger.debug("state.db auto-maintenance skipped: %s", exc)+++ def _run_checkpoint_auto_maintenance() -> None:+ """Checkpoint store retention on a daemon thread: its ``git gc`` can block for tens of seconds+ on a large store, which used to stall the prompt once a day. ``auto_prune_from_config`` owns the+ config gate and the 24h marker and never raises."""+ from tools.checkpoint_manager import auto_prune_from_config+ threading.Thread(target=auto_prune_from_config, name="checkpoint-auto-prune", daemon=True).start()diff --cc hermes_cli/cli_single_query.pyindex 00000000000,ed35d53ee5d..0547433bdf1mode 000000,100644..100644--- a/hermes_cli/cli_single_query.py+++ b/hermes_cli/cli_single_query.py@@@ -1,0 -1,509 +1,506 @@@+ """Single-query (``-q`` / one-shot) helpers: kanban goal loops, exit-code mapping, quiet single-query runner, image routing, signal handlers and the single-query mode orchestrator.++ Split out of ``cli.py``; ``cli`` re-exports every public name and moved bodies late-bind+ cli-level names through ``from cli import ...`` at call time so facade monkeypatch seams hold.+ """++ from __future__ import annotations++ from typing import TYPE_CHECKING++ import logging+ import os+ import sys+ import time+ from agent.interrupt_compat import request_hard_interrupt+ from contextlib import suppress+ from pathlib import Path+ from typing import Any++ # Log-record parity with the origin module.+ logger = logging.getLogger("cli")++ if TYPE_CHECKING:+ from cli import HermesCLI+++ def _int_or(value, default: int) -> int:+ """``int(value)``, or ``default`` when it does not parse."""+ try:+ return int(value)+ except (TypeError, ValueError):+ return default+++ def _interrupt_agent_for_signal(agent, signum) -> None:+ """Hard-interrupt ``agent`` for a shutdown signal, then sleep ``HERMES_SIGTERM_GRACE`` (1.5 s).++ The grace lets the agent thread kill the tool's setsid subprocess group before the+ main thread unwinds (else an orphan child). Never raises.+ """+ from cli import _float_env+ try:+ if agent is not None:+ request_hard_interrupt(agent, f"received signal {signum}")+ _grace = _float_env("HERMES_SIGTERM_GRACE", 1.5)+ if _grace > 0:+ time.sleep(_grace)+ except Exception:+ pass # never block signal handling+++ def _run_kanban_goal_loop_q(cli: "HermesCLI", first_response: str, run_turn=None, log=None) -> None:+ """Drive a kanban goal_mode worker through ``goals.run_kanban_goal_loop`` after its first turn.++ ``run_turn`` defaults to the bare ``-Q`` turn (final answer only). The ``-q`` worker path+ passes ``cli.chat`` so every follow-up turn keeps the tool activity feed that the Kanban+ worker log is made of. The caller swallows all errors: a broken loop must never wedge a worker.+ """+ from cli import _int_or, _sync_cli_session_id_from_agent+ task_id = (os.environ.get("HERMES_KANBAN_TASK") or "").strip()+ if not task_id:+ return+ raw_run_id = (os.environ.get("HERMES_KANBAN_RUN_ID") or "").strip()+ worker_run_id = _int_or(raw_run_id, None) if raw_run_id else None+ if raw_run_id and worker_run_id is None:+ logger.warning("invalid HERMES_KANBAN_RUN_ID=%r", raw_run_id)++ from hermes_cli import kanban_db as _kb+ from hermes_cli import kanban_db_connect as _kbc+ from hermes_cli.goals import run_kanban_goal_loop as _run_loop, DEFAULT_MAX_TURNS as _DEF_TURNS++ # Goal text = title + body (the acceptance criteria the judge evaluates against).+ with _kbc.connect_closing() as conn:+ task = _kb.get_task(conn, task_id)+ if task is None:+ return++ goal_text = "\n\n".join(p for p in (task.title or "", task.body) if p).strip()+ if not goal_text:+ return++ def _quiet_turn(prompt: str) -> str:+ result = cli.agent.run_conversation(user_message=prompt, conversation_history=cli.conversation_history)+ _sync_cli_session_id_from_agent(cli)+ resp = result.get("final_response", "") if isinstance(result, dict) else str(result)+ if resp:+ print(resp)+ return resp or ""++ def _task_status() -> "str | None":+ with _kbc.connect_closing() as c:+ return _kb.goal_run_status(c, task_id, worker_run_id)++ def _block(reason: str) -> None:+ with _kbc.connect_closing() as c:+ _kb.block_task(c, task_id, reason=reason, expected_run_id=worker_run_id)++ _run_loop(+ task_id=task_id, goal_text=goal_text, run_turn=run_turn or _quiet_turn,+ task_status_fn=_task_status, block_fn=_block,+ max_turns=task.goal_max_turns or _DEF_TURNS, first_response=first_response or "",+ log=log or (lambda m: logger.info("%s", m)),+ )+++ def _run_kanban_goal_loop_chat(cli: "HermesCLI", first_response: str) -> None:+ """``-q`` worker variant: follow-up turns go through ``cli.chat`` (tool feed stays on stdout,+ which is the Kanban worker log) and judge verdicts are printed there too, so a goal_mode card's+ log reads like any other worker's instead of staying blank until the final answer."""+ from cli import _run_kanban_goal_loop_q++ def _log(msg: str) -> None:+ logger.info("%s", msg)+ print(msg, flush=True)++ _run_kanban_goal_loop_q(cli, first_response, run_turn=lambda p: cli.chat(p) or "", log=_log)+++ def _sync_cli_session_id_from_agent(cli) -> None:+ """Keep ``cli.session_id`` in sync when mid-run compression rotated the agent's session."""+ if getattr(cli.agent, "session_id", None) and cli.agent.session_id != cli.session_id:+ cli.session_id = cli.agent.session_id+++ # ``failure_reason`` values that say nothing about the task itself: the provider is walled,+ # down or unreachable, or the account is out of credit, so a Kanban worker signals "try+ # later" instead of "I failed" and the dispatcher does not spend the task's retry budget on it.+ _TRANSIENT_PROVIDER_REASONS = frozenset({+ "rate_limit", "upstream_rate_limit", "billing", "overloaded", "server_error", "timeout",+ })+++ # ``failure_reason`` values a retry can never heal: the credential was rejected, the model does+ # not exist for this account, or the TLS chain is broken. A Kanban worker exits+ # ``KANBAN_TERMINAL_PROVIDER_EXIT_CODE`` so the dispatcher parks the card after ONE spawn with+ # the provider's words as the reason, instead of re-spawning into the same wall until+ # ``kanban.failure_limit`` is spent. ``billing`` stays transient: credit comes back.+ # ``upstream_blocked`` (a WAF/CDN refusing the SDK's User-Agent) is terminal too: only a+ # header change heals it, never a retry.+ _TERMINAL_PROVIDER_REASONS = frozenset({+ "auth", "auth_permanent", "model_not_found", "ssl_cert_verification", "upstream_blocked",+ })+++ def _single_query_exit_code(result, *, credentials_rate_limited: bool = False) -> int:+ """Map a one-shot turn result onto a process exit code, for both `-q` and `-Q`.++ 0 only when the turn completed; 130 when it was interrupted; 1 when it failed, stopped+ partway (`partial`, `completed: False`) or never ran at all (credentials / agent init+ failed, so ``result`` is not a dict). A Kanban worker (``HERMES_KANBAN_TASK`` set) that+ failed purely on a provider rate-limit / billing wall exits ``KANBAN_RATE_LIMIT_EXIT_CODE``+ (EX_TEMPFAIL): the dispatcher books that run ``rate_limited`` and requeues the task+ WITHOUT counting a failure, so a quota window or a provider outage cannot trip the breaker.+ The same sentinel applies when credential resolution itself is a quota/rate-limit+ AuthError (no turn result object is produced). One that failed on a terminal provider+ error (credential revoked, model gone) exits ``KANBAN_TERMINAL_PROVIDER_EXIT_CODE``+ (EX_CONFIG): the dispatcher blocks the card at once.+ """+ from cli import _TERMINAL_PROVIDER_REASONS, _TRANSIENT_PROVIDER_REASONS+ if not isinstance(result, dict):+ if credentials_rate_limited and os.environ.get("HERMES_KANBAN_TASK"):+ from hermes_cli.kanban_db import KANBAN_RATE_LIMIT_EXIT_CODE+ return KANBAN_RATE_LIMIT_EXIT_CODE+ return 1+ if result.get("interrupted"):+ return 130+ if not (result.get("failed") or result.get("partial") or result.get("completed") is False):+ return 0+ if os.environ.get("HERMES_KANBAN_TASK"):+ reason = result.get("failure_reason")+ if reason in _TRANSIENT_PROVIDER_REASONS:+ from hermes_cli.kanban_db import KANBAN_RATE_LIMIT_EXIT_CODE+ return KANBAN_RATE_LIMIT_EXIT_CODE+ if reason in _TERMINAL_PROVIDER_REASONS:+ from hermes_cli.kanban_db import KANBAN_TERMINAL_PROVIDER_EXIT_CODE+ return KANBAN_TERMINAL_PROVIDER_EXIT_CODE+ return 1+++ def _run_quiet_single_query(cli, effective_query, emitter=None):+ """Quiet (-Q) one-shot turn: run, print the response (stderr for errors/session_id), then sys.exit with the automation exit code.+ With a ``StreamJsonEmitter`` the final answer and the exit line become the terminal ``result`` JSONL record instead.+ HERMES_TURN_AUTHOR (set only by a bot-to-bot dispatcher) is consumed here so tool subprocesses do not inherit it.+ Nested Bot Mode notifies bind this session's key (not the dispatcher's) and resume in-process+ before stdout is printed, so a teammate reply is the quiet run's final answer rather than a+ stranded receipt."""+ from cli import _emit_interrupted_session_end, _run_kanban_goal_loop_q, _single_query_exit_code, _sync_cli_session_id_from_agent+ from agent.interrupt_compat import _accepts_keyword+ from agent.turn_author import take_turn_author_from_env+ from hermes_cli.quiet_single_query import (- adopt_unanswered_turn, bind_quiet_session_key, continue_quiet_notify_completions,- exit_single_query, quiet_notify_linger_seconds, take_turn_report_path, write_turn_report,++ bind_quiet_session_key, continue_quiet_notify_completions, exit_single_query, quiet_notify_linger_seconds, take_turn_report_path, write_turn_report,+ )++ author = take_turn_author_from_env()+ # A spawner that bounds only the turn (cron Bot Chat lane) learns the outcome from this+ # report, written before the linger below; popped so tool subprocesses do not inherit it.+ turn_report_path = take_turn_report_path()- # A dispatcher's re-run of a failed bot delivery resumes the DM row its first attempt persisted.- adopt_unanswered_turn(cli, effective_query)+ author_kwargs = {"turn_author": author} if author is not None and _accepts_keyword(cli.agent.run_conversation, "turn_author") else {}+ with bind_quiet_session_key(getattr(cli, "session_id", "") or "default"):+ try:+ result = cli.agent.run_conversation(+ user_message=effective_query, conversation_history=cli.conversation_history, **author_kwargs,+ )+ except KeyboardInterrupt:+ _emit_interrupted_session_end(cli, reason="keyboard_interrupt")+ if emitter is not None:+ exit_single_query(emitter.emit_result({"failed": True, "error": "Interrupted"}, session_id=cli.session_id or "", exit_code=130))+ print(f"\nsession_id: {cli.session_id}", file=sys.stderr)+ exit_single_query(130)+ # The exit line below reports session_id to stderr for automation wrappers;+ # without this sync it would point at the ended parent after compression.+ _sync_cli_session_id_from_agent(cli)+ # The turn is over and persisted: the one-shot exit linger that follows protects nested+ # notify_on_complete replies and is NOT part of the spawner's delivery (#113608). The+ # report carries what this run will print, so a spawner booking a child still lingering+ # at its cap relays the answer instead of a timeout (#114980).+ def _report_turn(res) -> None:+ write_turn_report(+ turn_report_path, exit_code=_single_query_exit_code(res),+ error=str(res.get("error") or "") if isinstance(res, dict) else "agent turn did not run",+ reply=res.get("final_response", "") if isinstance(res, dict) else str(res),+ )++ _report_turn(result)+ if isinstance(result, dict) and not result.get("failed"):+ history = result.get("messages") or cli.conversation_history++ def _follow_up(text):+ nonlocal history+ follow = cli.agent.run_conversation(+ user_message=text, conversation_history=history, **author_kwargs,+ )+ if isinstance(follow, dict) and follow.get("messages"):+ history = follow["messages"]+ # Same sync contract as the main turn: a compression rotation during a+ # follow-up must not leave a stale id on the exit line / drain key.+ _sync_cli_session_id_from_agent(cli)+ return follow++ # One shared linger budget for the whole run: the loop below and the later+ # _wait_for_oneshot_background_completions pass must not each wait the full+ # oneshot_completion_wait_seconds on the same stuck notify_on_complete child.+ # Flagged after the loop (finally-equivalent): the wait is the loop's first+ # statement, so anything raising past that point has consumed budget the+ # finalize pass must not re-wait.+ try:+ continued = continue_quiet_notify_completions(+ getattr(cli, "session_id", "") or "",+ _follow_up,+ owns_event=getattr(cli, "_owns_process_notification", None),+ linger_budget=quiet_notify_linger_seconds(),+ )+ finally:+ cli._quiet_notify_linger_done = True+ if isinstance(continued, dict):+ result = continued+ # A teammate's reply displaced the answer this run prints; tell the spawner.+ _report_turn(result)+ response = result.get("final_response", "") if isinstance(result, dict) else str(result)+ # Surface backend errors that produced no visible output (e.g. invalid model slug+ # -> provider 4xx) on stderr so piped stdout stays clean.+ if emitter is not None:+ pass # the result record below carries text/error; nothing else may touch stdout+ elif (+ not response and isinstance(result, dict) and result.get("error")+ and (result.get("failed") or result.get("partial"))+ ):+ print(f"Error: {result['error']}", file=sys.stderr)+ elif response:+ print(response)++ # Kanban goal_mode: keep working in THIS session until a judge agrees the card is+ # done, the worker terminates it, or the turn budget runs out (sticky block).+ if os.environ.get("HERMES_KANBAN_GOAL_MODE") == "1":+ try:+ _run_kanban_goal_loop_q(cli, response)+ except Exception as _goal_exc:+ logger.debug("kanban goal loop failed: %s", _goal_exc)++ if emitter is None:+ print(f"\nsession_id: {cli.session_id}", file=sys.stderr)++ _exit_code = _single_query_exit_code(result)+ if emitter is not None:+ _exit_code = emitter.emit_result(result, session_id=cli.session_id or "", exit_code=_exit_code)+ exit_single_query(_exit_code)+++ def _route_single_query_images(cli, query, effective_query, single_query_images, single_query_image_urls):+ """Attach one-shot images natively when the model supports vision, else pre-describe them as text."""+ if not (single_query_images or single_query_image_urls):+ return effective_query+ # Same image-routing decision as the interactive path: a vision-capable model+ # (incl. custom-provider models declaring `model.supports_vision: true`) gets+ # native image_url parts; otherwise the text pipeline (vision_analyze+ # pre-description).+ _img_mode = "text"+ _build_parts = None+ try:+ from agent.image_routing import build_native_content_parts as _build_parts # noqa: F811+ from agent.image_routing import decide_image_input_mode+ from hermes_cli.config import load_config++ _img_mode = decide_image_input_mode(+ (cli.provider or "").strip(), (cli.model or "").strip(), load_config(),+ requested_provider=(cli.requested_provider or "").strip(),+ )+ except Exception:+ _img_mode = "text"++ def _text_fallback():+ # ``_preprocess_images_with_vision`` only knows local files; when only URLs+ # were supplied keep the original query text intact.+ if single_query_images:+ return cli._preprocess_images_with_vision(query, single_query_images, announce=False)+ return effective_query++ if _img_mode != "native" or _build_parts is None:+ return _text_fallback()+ try:+ _parts, _skipped = _build_parts(+ query if isinstance(query, str) else "",+ [str(p) for p in single_query_images],+ image_urls=list(single_query_image_urls) or None,+ )+ if any(p.get("type") == "image_url" for p in _parts):+ return _parts+ return _text_fallback() # all images unreadable+ except Exception:+ return _text_fallback()+++ def _collect_kanban_task_images(single_query_images):+ """Kanban workers: image paths/URLs in the task body join the first turn's attachments."""+ single_query_image_urls: list[str] = []+ _kanban_task_id = os.environ.get("HERMES_KANBAN_TASK", "").strip()+ if not _kanban_task_id:+ return single_query_image_urls+ try:+ from hermes_cli import kanban_db as _kb+ from hermes_cli import kanban_db_connect as _kbc+ from agent.image_routing import extract_image_refs as _extract_refs++ with _kbc.connect_closing() as _conn:+ _task = _kb.get_task(_conn, _kanban_task_id)+ _body = getattr(_task, "body", "") if _task is not None else ""+ if _body:+ _kb_paths, _kb_urls = _extract_refs(_body)+ # Dedupe against any --image the user already passed.+ _seen = {str(p) for p in single_query_images}+ for _p in _kb_paths:+ if _p not in _seen:+ _seen.add(_p)+ single_query_images.append(Path(_p))+ single_query_image_urls.extend(_kb_urls)+ except Exception as _exc:+ # Best-effort enrichment; never block worker startup on it.+ logger.debug("kanban image-ref extraction failed: %s", _exc)+ return single_query_image_urls+++ def _install_single_query_signal_handlers(cli):+ """Route SIGINT/SIGTERM/SIGHUP through agent.interrupt() before unwinding; kanban workers hard-exit.++ A plain KeyboardInterrupt only unwinds the main thread, so tool worker threads+ would orphan the setsid child; the interrupt + grace window lets them kill it.+ """+ from cli import _arm_exit_watchdog_on_shutdown_signal, _flush_logging_and_stdio, _flush_one_shot_session_store, _interrupt_agent_for_signal+ import signal as _signal++ def _signal_handler_q(signum, frame):+ logger.debug("Received signal %s in single-query mode", signum)+ _arm_exit_watchdog_on_shutdown_signal() # covers wedges in the unwind below+ _interrupt_agent_for_signal(getattr(cli, "agent", None), signum)+ # Kanban: a non-daemon worker blocked in _wait_for_process survives KeyboardInterrupt+ # and the dispatcher sees 'running' forever, so os._exit(0) (SIGALRM deadman guards+ # a blocking flush). That skips atexit + the token-drain hook, hence the explicit flush.+ # Kanban worker exit path (#28181): SIGTERM hits a dispatcher-spawned worker that's likely in a+ # non-daemon thread waiting on a child subprocess in _wait_for_process. Raising KeyboardInterrupt+ # only unwinds the main thread; the worker thread keeps running, the process gets reparented to+ # init, and the dispatcher's _pid_alive check returns True forever — task stuck in 'running'+ # indefinitely. Skip the controlled-unwind dance and call os._exit(0) so the kernel reclaims the PID+ # immediately and detect_crashed_workers can reclaim the stale claim on the next tick. Flush logging+ # + stdout/stderr first so the final debug trace isn't lost; SIGALRM deadman guards the flush+ # against any rare blocking-I/O case (the reporter measured flush in <1ms; the alarm is a failsafe,+ # not the common path).+ if os.environ.get("HERMES_KANBAN_TASK"):+ with suppress(Exception):+ if hasattr(_signal, "SIGALRM"):+ _signal.signal(_signal.SIGALRM, lambda *_: os._exit(0))+ _signal.alarm(5)+ with suppress(Exception):+ # Durable flush FIRST: memory-provider shutdown inside _run_cleanup can issue aux-LLM calls,+ # and nothing after it may fail in a way that loses the turn (#88583).+ # os._exit(0) skips atexit AND SessionDB's token-drain hook, so flush + finalize the session+ # store here or the worker's turn (and its usage deltas) never become durable (#88583 /+ # #50881 class). Best-effort under the SIGALRM deadman above.+ _flush_one_shot_session_store(cli)+ _flush_logging_and_stdio()+ os._exit(0)+ raise KeyboardInterrupt()+ with suppress(Exception): # restricted environments+ for _name in ("SIGINT", "SIGTERM", "SIGHUP"):+ if hasattr(_signal, _name):+ _signal.signal(getattr(_signal, _name), _signal_handler_q)+++ def _configure_quiet_agent(agent) -> None:+ """Neutralize every stdout-writing callback so -Q stdout carries only the final response."""+ agent.quiet_mode = True+ agent.suppress_status_output = True+ agent.stream_delta_callback = None+ agent.tool_gen_callback = None+ agent.reasoning_callback = None+ # The diff/progress callbacks print directly and are gated by neither quiet_mode nor+ # tool_progress_mode, so they must go too; "off" also covers the executor's direct prints.+ agent.tool_progress_callback = None+ agent.tool_start_callback = None+ agent.tool_complete_callback = None+ agent.tool_progress_mode = "off"+++ def _run_single_query_mode(cli, query, image, quiet, oneshot, stream_json: bool = False):+ """``-q``/``--image`` entry: seed an interactive session on a TTY, else run the one-shot turn and exit.+ ``stream_json`` (implies quiet) swaps the plain-text final answer for the JSONL event protocol."""+ from cli import _SeededQueryMessage, _collect_kanban_task_images, _collect_query_images, _configure_quiet_agent, _finalize_single_query, _route_single_query_images, _run_kanban_goal_loop_chat, _run_quiet_single_query, _should_seed_interactive, _single_query_exit_code+ if _should_seed_interactive(query, image, quiet, oneshot):+ seeded_query, seeded_images = _collect_query_images(query, image)+ logger.info(+ "Seeding interactive session with -q prompt (%d chars, %d images)",+ len(seeded_query or ""), len(seeded_images),+ )+ cli._seeded_first_message = _SeededQueryMessage(seeded_query, seeded_images)+ return cli.run()+ cli._single_query_mode = True # agent waits the full MCP cold-start before its only tool snapshot+ # Only the interactive run loop set this, so plugin tools dispatched from a `-q`/`-Q` turn got no+ # parent_agent (PluginContext.dispatch_tool reads it) — #67597.+ from hermes_cli.plugins import get_plugin_manager+ get_plugin_manager()._cli_ref = cli+ # No user can answer approval prompts: the approval gate takes the deterministic path.+ # One-shot mode: no between-turns MCP late-binding refresh, so the agent must wait the full MCP+ # cold-start bound before its first (and only) tool snapshot. See #51316.+ # Mark single-query for the approval gate. cli.py sets HERMES_INTERACTIVE earlier for interactive sudo+ # prompts, but a -q run has NO user waiting to answer approval prompts. The gate reads this marker (via+ # gateway.session_context.get_session_env, which falls back to os.environ when the session-context layer+ # isn't engaged) and takes the deterministic approvals.single_query_mode path instead of waiting the+ # full timeout. See #86878.+ os.environ["HERMES_SINGLE_QUERY_SESSION"] = "1"+ from hermes_cli.quiet_single_query import exit_single_query+ if not cli._claim_active_session("cli", stderr=bool(quiet)):+ exit_single_query(1)+ try:+ query, single_query_images = _collect_query_images(query, image)+ single_query_image_urls = _collect_kanban_task_images(single_query_images)+ if quiet:+ # Quiet mode: suppress banner, spinner, tool previews.+ cli.tool_progress_mode = "off"+ emitter = None+ if stream_json:+ # Built BEFORE credentials/agent init so a failed start still closes the protocol+ # (init + result) instead of exiting 1 with an empty stdout.+ from hermes_cli.stream_json import StreamJsonEmitter+ emitter = StreamJsonEmitter(model=getattr(cli, "model", "") or "", session_id=cli.session_id or "")+ if cli._ensure_runtime_credentials():+ effective_query: Any = _route_single_query_images(+ cli, query, query, single_query_images, single_query_image_urls+ )+ turn_route = cli._resolve_turn_agent_config(effective_query)+ if turn_route["signature"] != cli._active_agent_route_signature:+ cli.agent = None+ if cli._init_agent(+ model_override=turn_route["model"],+ runtime_override=turn_route["runtime"],+ request_overrides=turn_route.get("request_overrides"),+ ):+ _configure_quiet_agent(cli.agent)+ if emitter is not None:+ emitter.attach(cli.agent)+ _run_quiet_single_query(cli, effective_query, emitter=emitter)++ fail_code = _single_query_exit_code(+ None, credentials_rate_limited=getattr(cli, "_credentials_rate_limited", False))+ if emitter is not None:+ emitter.emit_result({"failed": True, "error": "credentials or agent init failed"},+ session_id=cli.session_id or "", exit_code=fail_code)+ exit_single_query(fail_code) # credentials or agent init failed+ # No welcome banner (~420 ms cold); session id / resume hint come from _print_exit_summary().+ _query_label = query or ("[image attached]" if single_query_images else "")+ if _query_label:+ cli.console.print(f"[bold blue]Query:[/] {_query_label}")+ cli._show_security_advisories()+ response = cli.chat(query, images=single_query_images or None)+ # Kanban goal_mode on the `-q` path: same judge loop as `-Q`, but each follow-up turn+ # runs through cli.chat so the worker log keeps its live tool feed (the dispatcher+ # used to force -Q here, which left goal_mode cards with a blank Worker log).+ if os.environ.get("HERMES_KANBAN_GOAL_MODE") == "1":+ try:+ _run_kanban_goal_loop_chat(cli, response or "")+ except Exception as _goal_exc:+ logger.debug("kanban goal loop failed: %s", _goal_exc)+ cli._print_exit_summary(clear_screen=False)+ # Same exit contract as `-Q`: scripts and the Kanban dispatcher read the outcome from+ # the exit code. This path used to fall through to an implicit 0 for every outcome.+ exit_single_query(_single_query_exit_code(cli._last_turn_result))+ finally:+ _finalize_single_query(cli)diff --cc hermes_cli/config.pyindex 783ac3ccf9a,a007ad63ee9..0d8a36b2645--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@@ -1932,12 -1961,31 +1961,37 @@@ def cfg_get(cfg: Optional[Dict[str, Anyreturn node+ def _raw_config_cache_hit(path_key: str, cache_key: Tuple[Any, ...]) -> Optional[Dict[str, Any]]:+ """Pure lookup: the cached raw config for ``path_key`` if its signature equals ``cache_key``,+ else ``None``. Shared by the lock-free fast path and the locked re-check of+ ``_read_raw_config_impl`` so the predicate cannot drift between them."""+ cached = _RAW_CONFIG_CACHE.get(path_key)+ if cached is not None and cached[:len(cache_key)] == cache_key:+ return cached[len(cache_key)]+ return None++def _read_raw_config_impl(*, want_deepcopy: bool) -> Dict[str, Any]:+ from agent.safe_worker_policy import worker_config_snapshot++ snapshot = worker_config_snapshot()+ if snapshot is not None:+ return snapshot+++ # Lock-free fast path for cache hits — same shape as `_load_config_impl`. `_RAW_CONFIG_CACHE`+ # publishes each entry as ONE `(*sig, data)` tuple replaced wholesale, so a reader sees either+ # the complete old entry or the complete new one; `_CONFIG_LOCK` only serializes the re-parse+ # and the writers (`save_config()` holds it across an atomic YAML write, which used to stall+ # every cached read for the duration). A lost race just falls through to the locked re-check.+ try:+ config_path = get_config_path()+ cache_key = file_signature(config_path.stat())+ hit = _raw_config_cache_hit(str(config_path), cache_key)+ if hit is not None:+ return copy.deepcopy(hit) if want_deepcopy else hit+ except Exception:+ pass+with _CONFIG_LOCK:try:config_path = get_config_path()@@@ -2255,12 -2308,39 +2314,45 @@@ def _merge_managed_overlay(expanded: Direturn _deep_merge(expanded, _expand_env_vars(managed_normalized)), managed_config+ def _load_config_cache_hit(path_key: str, cache_sig: Any) -> Optional[Dict[str, Any]]:+ """Pure lookup: the cached expanded config for ``path_key`` if its signature equals+ ``cache_sig`` AND every ``${VAR}`` it was expanded against still has the same value, else+ ``None``. Signatures matching is not enough: a load before load_hermes_dotenv() would otherwise+ pin unexpanded literals (e.g. auxiliary.<task>.api_key) for the process lifetime (#58514).+ Shared by the lock-free fast path and the locked re-check of ``_load_config_impl``."""+ cached = _LOAD_CONFIG_CACHE.get(path_key)+ if cached is None or cache_sig is None or cached[:8] != cache_sig:+ return None+ env_snapshot = cached[9] if len(cached) > 9 else {}+ if all(_env_ref_lookup(k) == v for k, v in env_snapshot.items()):+ return cached[8]+ return None++def _load_config_impl(*, want_deepcopy: bool) -> Dict[str, Any]:+ from agent.safe_worker_policy import worker_config_snapshot++ snapshot = worker_config_snapshot()+ if snapshot is not None:+ return _deep_merge(copy.deepcopy(DEFAULT_CONFIG), snapshot)+++ # Lock-free fast path for cache hits — same publication contract as `_read_raw_config_impl`+ # above (whole-tuple replace, `_CONFIG_LOCK` only serializes rebuilds and writers). A hit costs+ # ~0.024ms; behind a lock held by `save_config()` the same read measured 10010ms, and on a+ # gateway that stalls every inbound message's hook path. A lost race falls through to the lock.+ try:+ config_path = get_config_path()+ path_key = str(config_path)+ if path_key in _LOAD_CONFIG_CACHE:+ _, fast_sig = _load_config_cache_sig(config_path)+ hit = _load_config_cache_hit(path_key, fast_sig)+ if hit is not None:+ return copy.deepcopy(hit) if want_deepcopy else hit+ except Exception:+ # Any surprise here falls through to the locked path, which is the+ # original fully-defensive implementation.+ pass+with _CONFIG_LOCK:ensure_hermes_home()config_path = get_config_path()@@@ -2436,39 -2511,13 +2523,19 @@@ def save_config_LAST_EXPANDED_CONFIG_BY_PATH[str(config_path)] = copy.deepcopy(current_normalized)- # load_env() memo keyed on (path, *file_signature). Editing .env bumps mtime/inode -> rebuild;- # invalidate_env_cache() is the explicit knob for writers on coarse-mtime filesystems.- _env_cache: Optional[Tuple[Tuple[str, Optional[Tuple[int, int, int, int]]], Dict[str, str]]] = None--def load_env() -> Dict[str, str]:- """Load ~/.hermes/.env as a dict (memoised; ``get_env_value()`` runs hundreds of times per- interactive menu render). Each assignment's value is opaque data for boundary discovery."""- global _env_cache+ """Load ~/.hermes/.env as a dict. Memoised inside ``load_env_file`` (``get_env_value()`` runs+ hundreds of times per interactive menu render). Each assignment's value is opaque data for+ boundary discovery."""+ from agent.safe_worker_policy import worker_config_snapshot++ # A frozen-policy worker never opens the profile's files; its secrets arrive+ # through the owner-installed scope, so the .env layer is empty here.+ if worker_config_snapshot() is not None:+ return {}- env_path = get_env_path()-- try:- st = env_path.stat()- cache_key = (str(env_path), file_signature(st))- except FileNotFoundError:- cache_key = (str(env_path), None)- except Exception:- cache_key = None- if cache_key is not None and _env_cache is not None and _env_cache[0] == cache_key:- return dict(_env_cache[1])-from agent.secret_scope import load_env_file # the one .env tokenizer; also installs profile scopes- env_vars = load_env_file(env_path)- if cache_key is not None:- _env_cache = (cache_key, dict(env_vars))- return env_vars+ return load_env_file(get_env_path())def invalidate_env_cache() -> None:@@@ -3938,25 -3973,31 +3991,35 @@@ _inject_profile_env_vars(def _platform_plugin_manifests():- """Yield ``(dir_name, manifest_dict)`` for every bundled ``plugins/platforms/*/plugin.y(a)ml``."""+ """Yield ``(dir_name, manifest_dict)`` for every platform plugin manifest: bundled+ ``plugins/platforms/*``, the user's ``<HERMES_HOME>/plugins/platforms/*`` category dir, and flat+ user installs ``<HERMES_HOME>/plugins/*`` that declare ``kind: platform`` (#46600)."""+ from agent.safe_worker_policy import safe_worker_enabled++ if safe_worker_enabled():+ return- platforms_dir = get_project_root() / "plugins" / "platforms"- if not platforms_dir.is_dir():- return- for child in platforms_dir.iterdir():- manifest_path = next(- (p for p in (child / "plugin.yaml", child / "plugin.yml") if child.is_dir() and p.exists()), None)- if manifest_path is None:- continue- try:- with open(manifest_path, "r", encoding="utf-8") as f:- manifest = fast_safe_load(f) or {}- except Exception:+ user_plugins = get_hermes_home() / "plugins"+ roots = (+ (get_project_root() / "plugins" / "platforms", False),+ (user_plugins / "platforms", False),+ (user_plugins, True), # flat layout: only manifests that say they are platforms+ )+ for root, require_kind in roots:+ if not root.is_dir():continue- yield child.name, manifest+ for child in root.iterdir():+ manifest_path = next(+ (p for p in (child / "plugin.yaml", child / "plugin.yml") if child.is_dir() and p.exists()), None)+ if manifest_path is None:+ continue+ try:+ with open(manifest_path, "r", encoding="utf-8") as f:+ manifest = fast_safe_load(f) or {}+ except Exception:+ continue+ if not isinstance(manifest, dict) or (require_kind and manifest.get("kind") != "platform"):+ continue+ yield child.name, manifestdef _inject_platform_plugin_env_vars() -> None:diff --cc hermes_cli/config_defaults.pyindex 706e8248a65,ef6b1939769..d5ea16a1b53--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@@ -1944,7 -2062,6 +2062,7 @@@ DEFAULT_CONFIG =# Seconds to let a SIGTERM-interrupted gateway agent unwind before adapter/database# teardown. Keep short so service-manager shutdowns don't exhaust their stop budget."signal_interrupt_grace_timeout": 1,++ "service_install_choice": None, # null | install | decline; never authorizes ordinary launch installation.# Durable delivery-obligation ledger: final responses are recorded in state.db around the# platform send; a gateway that died between finalize and platform ACK redelivers on next# boot (ambiguous cases carry a "recovered reply — may be a duplicate" marker;@@@ -2451,7 -2623,7 +2624,7 @@@# Extra ports detection probes for an external llama-server (besides 8080)."detect_ports": [],},-- "_config_version": 46, # Config schema version - bump this when adding new required fields++ "_config_version": 47, # Config schema version - bump this when adding new required fields}diff --cc hermes_cli/config_migrations.pyindex 824d87e4665,b011814ea29..78a2f936df3--- a/hermes_cli/config_migrations.py+++ b/hermes_cli/config_migrations.py@@@ -709,18 -751,8 +751,20 @@@ MIGRATIONS: Tuple[Tuple[int, Callable[["skills/.archive/ (recoverable with `hermes curator restore`). Set it back to 90 to keep the old window."))),# 44 → 45: saved platform_toolsets lists predate the connections toolset (see _migrate_to_45).(45, _migrate_to_45),- # 45 → 46: cron.bot_chat_delivery_timeout_seconds is gone with the local `hermes chat`+ # 45 → 46: legacy editor `disabled: true` on MCP servers becomes `enabled: false` (see _migrate_to_46).+ (46, _migrate_to_46),++ # 46 → 47: 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.- (46, functools.partial(++ (47, 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)),)diff --cc hermes_cli/kanban_db_dispatch.pyindex 697bae8fe26,17b34604474..1c5c3122bf5--- a/hermes_cli/kanban_db_dispatch.py+++ b/hermes_cli/kanban_db_dispatch.py@@@ -984,7 -1044,7 +1054,7 @@@ def _classify_dead_workerin the event payload, appended to the error text) so the board and the retryworker see WHY instead of a bare label; a rate-limited requeue does not need it."""- dead = _classify_dead_worker_exit(pid, claimer, exit_code)- dead = _classify_dead_worker_exit(pid, claimer, task_id=task_id, board=board)++ dead = _classify_dead_worker_exit(pid, claimer, exit_code, task_id=task_id, board=board)if task_id and not dead.rate_limited:worker_output = _worker_final_output(task_id, board=board)if worker_output:@@@ -993,12 -1053,26 +1063,30 @@@return dead- def _classify_dead_worker_exit(pid: int, claimer: Optional[str], exit_code=None) -> _DeadWorker:- """Exit status -> reclaim bookkeeping, before the worker's own words are folded in."""+ def _classify_dead_worker_exit(+ pid: int,+ claimer: Optional[str],++ exit_code=None,+ *,+ task_id: Optional[str] = None,+ board: Optional[str] = None,+ ) -> _DeadWorker:+ """Exit status -> reclaim bookkeeping, before the worker's own words are folded in.+- The reap registry only knows children of THIS process; a per-tick dispatcher- reads the exit trailer the worker left in its log instead, so the same death- gets the same booking (protocol violation / rate-limit requeue / crash) as- under the gateway-embedded dispatcher. A worker that never reached its exit- epilogue (killed, OOM) leaves no trailer and stays a plain crash.++ ``exit_code`` is the authority's exact-run result for a managed worker (a child of the++ profile owner, never of this dispatcher, so it cannot be reaped here). Otherwise the reap++ registry only knows children of THIS process; a per-tick dispatcher reads the exit trailer++ the worker left in its log instead, so the same death gets the same booking (protocol++ violation / rate-limit requeue / crash) as under the gateway-embedded dispatcher. A worker++ that never reached its exit epilogue (killed, OOM) leaves no trailer and stays a plain crash.+ """kind, code = _classify_worker_exit(pid)- if kind == "unknown" and task_id:+ if exit_code is not None:- code = exit_code- kind = "rate_limited" if code == _kb.KANBAN_RATE_LIMIT_EXIT_CODE else ("clean_exit" if code == 0 else "nonzero_exit")++ kind, code = _exit_code_kind(int(exit_code))++ elif kind == "unknown" and task_id:+ logged = _worker_log_exit_code(task_id, board=board)+ if logged is not None:+ kind, code = _exit_code_kind(logged)if kind == "clean_exit":# rc=0 while still ``running``: usually the work succeeded and only the# paperwork was skipped; the corrective sentence reaches the retry@@@ -2355,8 -2571,80 +2601,79 @@@ def _worker_terminal_timeout_envreturn str(desired)+ @contextlib.contextmanager+ def _worker_profile_scope(hermes_home: str, *, bind_home: bool = True):+ """Bind an assigned profile's runtime scope (secrets + terminal policy, optionally home) for+ one dispatch-side read or spawn-env build.++ The dispatcher runs detached from any turn, so nothing binds a profile for it: ``load_config``,+ the toolset probes' ``get_secret`` reads and ``build_subprocess_env``'s passthrough resolution+ all fall back to the LAUNCH profile's ambient ``os.environ`` / ``TERMINAL_*``. Binding was+ previously conditional on ``is_multiplex_active()``, so on a single-profile host a worker for+ profile B was built entirely from the dispatcher's own environment.++ ``bind_home=False`` for the spawn-env build: which variables may cross into a child is the+ DISPATCHER's ``terminal.env_passthrough`` policy (#109494, read through the home override) —+ only their VALUES come from the assignee's scope, so that branch binds the secret scope alone.+ Toolset resolution binds the home and the terminal policy, as it always has.++ The secret mapping is never widened: a profile that is not this process's own home gets its own+ ``.env`` + external sources ONLY, while the launch home keeps its established+ env-over-``.env`` precedence (``launch_secret_scope``) so systemd / ``op run`` injection still+ resolves for a standalone dispatcher.+ """+ from agent.secret_scope import build_profile_secret_scope, reset_secret_scope, set_secret_scope+ from hermes_constants import get_process_hermes_home, reset_hermes_home_override, set_hermes_home_override+ from tools.terminal_scope import install_profile_terminal_scope, reset_terminal_scope+ from tui_gateway.launch_profile_policy import launch_secret_scope, launch_terminal_env++ home = Path(hermes_home)+ is_launch_home = str(home.resolve()) == str(Path(get_process_hermes_home()).resolve())+ home_token = set_hermes_home_override(str(home)) if bind_home else None+ secret_token = set_secret_scope(+ launch_secret_scope(home) if is_launch_home else build_profile_secret_scope(home))+ terminal_token = install_profile_terminal_scope(+ home, env_overlay=launch_terminal_env() if is_launch_home else None) if bind_home else None+ try:+ yield+ finally:+ if terminal_token is not None:+ reset_terminal_scope(terminal_token)+ reset_secret_scope(secret_token)+ if home_token is not None:+ reset_hermes_home_override(home_token)+++ def _resolve_worker_cli_toolsets(hermes_home: Optional[str]) -> Optional[list[str]]:+ """Return the assigned profile's effective CLI toolsets for a worker.++ Resolved at dispatch time and passed as an explicit ``--toolsets`` pin so+ worker startup cannot fall back to a stale root/active-profile config or a+ profile whose top-level ``toolsets`` is only the kanban orchestrator+ surface. ``model_tools`` still appends the task-scoped kanban lifecycle+ tools when ``HERMES_KANBAN_TASK`` is set.+ """+ if not hermes_home:+ return None+ try:+ from hermes_cli.config import load_config+ from hermes_cli.tools_config import _get_platform_tools++ with _worker_profile_scope(hermes_home):+ cfg = load_config()+ toolsets = sorted(_get_platform_tools(cfg, "cli"))+ return toolsets or None+ except Exception as exc:+ _kb._log.debug(+ "kanban worker: could not resolve CLI toolsets for HERMES_HOME=%r (%s)",+ hermes_home,+ exc,+ )+ return None++_retagged_workspace_roots: set[str] = set()-def _retag_legacy_worker_sessions(workspaces_root_path: str) -> None:"""Reclaim pre-tag worker rows in state.db so they leave the session lists.diff --cc hermes_cli/lifecycle.pyindex 1e04a41ccf8,4ea636a1e53..5cd1da23398--- a/hermes_cli/lifecycle.py+++ b/hermes_cli/lifecycle.py@@@ -37,12 -29,17 +37,21 @@@ def invoke_hook(hook_name: str, **kwargreturn _plugin_hooks(hook_name, **kwargs)+ async def ainvoke_hook(hook_name: str, **kwargs: Any) -> List[Any]:+ """:func:`invoke_hook` for callers on an event loop: same observers-then-plugins+ composition, with ``async def`` plugin callbacks awaited on that loop."""+ _observe(hook_name, **kwargs)+ from hermes_cli import plugins++ return await plugins.ainvoke_hook(hook_name, **kwargs)++def has_hook(hook_name: str) -> bool:"""Return whether a first-party observer or plugin consumes a hook."""+ from agent.safe_worker_policy import safe_worker_enabled++ if safe_worker_enabled():+ return Falsetry:from hermes_cli.observability import handles_hookdiff --cc hermes_cli/plugins.pyindex 88522f53984,274deb117fe..3149b425a1b--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@@ -1228,10 -1260,11 +1260,15 @@@ class PluginManager(PluginLoaderMixin,def discover_and_load(self, force: bool = False) -> None:"""Scan all plugin sources and load each plugin found; ``force`` unloads first so configchanges / new bundled backends become visible in long-lived sessions."""+ from agent.safe_worker_policy import safe_worker_enabled++ if safe_worker_enabled():+ return+ if self._discovered and not force and in_plugin_load_worker():+ # A plugin whose register() re-enters discovery (importing model_tools does) runs on a+ # deadline worker that cannot re-acquire the sweep's RLock; the flag is already set for the+ # whole sweep, so return where the locked re-entry used to. Every other caller still waits.+ returnwith self._discovery_lock, _plugin_home_scope(self.home_path):if self._discovered and not force:returndiff --cc hermes_cli/plugins_dispatch.pyindex 787241b90bb,78c3927fc4f..b7c0e523ea4--- a/hermes_cli/plugins_dispatch.py+++ b/hermes_cli/plugins_dispatch.py@@@ -448,18 -478,48 +482,56 @@@ class PluginDispatchMixindef has_hook(self, hook_name: str) -> bool:"""Return True when at least one callback is registered for a hook."""+ from agent.safe_worker_policy import safe_worker_enabled++ if safe_worker_enabled():+ return Falsereturn bool(self._hooks.get(hook_name))+ async def ainvoke_hook(self, hook_name: str, **kwargs: Any) -> List[Any]:+ """:meth:`invoke_hook` for callers that are already on an event loop.++ Same payload narrowing, per-callback isolation and result contract. The difference is+ where an ``async def`` callback runs: here it is awaited on the caller's own loop, so a+ callback that awaits anything scheduled on that loop can make progress. Through the+ sync path it runs on a helper thread while the caller blocks in ``done.wait()`` — on the+ gateway that stalls the whole event loop for the callback's duration. Sync callbacks+ run inline. Bounded hooks keep ``plugins.hook_callback_timeout`` via ``asyncio.wait_for``+ (the coroutine is cancelled, not abandoned); a timed-out ``pre_tool_call`` fails closed.+ """+ from hermes_cli.plugins import _resolve_hook_callback_timeout+ if hook_name != "gateway_platform_event":+ kwargs.setdefault("telemetry_schema_version", OBSERVER_SCHEMA_VERSION)+ results: List[Any] = []+ timeout = _resolve_hook_callback_timeout()+ use_timeout = _hook_uses_callback_timeout(hook_name, timeout)+ fail_closed = hook_name in _HOOK_TIMEOUT_FAIL_CLOSED_HOOKS+ for cb in self._hooks.get(hook_name, []):+ callback_name = getattr(cb, "__name__", repr(cb))+ try:+ ret = cb(**self._hook_callback_kwargs(cb, kwargs))+ if inspect.isawaitable(ret):+ ret = await (asyncio.wait_for(ret, timeout) if use_timeout else ret)+ if ret is not None:+ results.append(ret)+ except asyncio.TimeoutError:+ logger.warning("Hook '%s' callback %s timed out after %.0fs", hook_name, callback_name, timeout)+ if fail_closed: # policy hook: fail closed with a block directive+ results.append({"action": "block", "message": _PRE_TOOL_CALL_TIMEOUT_BLOCK_MESSAGE})+ except (Exception, SystemExit) as exc:+ # Same isolation + failure contract as the sync path (#111922 warn-once, #109624+ # a raising policy guard fails closed).+ self._report_hook_failure(hook_name, cb, kwargs, exc)+ if fail_closed:+ results.append(_policy_error_block_directive(hook_name, cb, exc))+ return results+def iter_hook_callbacks(self, hook_name: str) -> tuple[Callable, ...]:"""Return a stable snapshot of callbacks registered for a hook."""+ from agent.safe_worker_policy import safe_worker_enabled++ if safe_worker_enabled():+ return ()return tuple(self._hooks.get(hook_name, ()))def render_system_prompt_sections(diff --cc hermes_cli/profiles.pyindex effbdb09267,0c7fe8c95a2..a0a8b53cffd--- a/hermes_cli/profiles.py+++ b/hermes_cli/profiles.py@@@ -899,25 -1162,6 +1162,25 @@@ def _clone_all_into(source_dir: Path, p)+def _strip_multiplex_flag(config_path: Path) -> None:+ """Multiplexing belongs to the default profile; a clone that keeps the flag would start its+ own multiplexer (or be refused at boot) the first time it runs a gateway."""+ if not config_path.is_file():+ return+ with contextlib.suppress(Exception): # creation must not fail over an unreadable copy- import yaml- from hermes_cli.config import read_user_config_raw++ from hermes_cli.config import atomic_config_write, read_user_config_raw+ cfg = read_user_config_raw(config_path)+ gateway = cfg.get("gateway") if isinstance(cfg.get("gateway"), dict) else {}+ if "multiplex_profiles" not in cfg and "multiplex_profiles" not in gateway:+ return+ cfg.pop("multiplex_profiles", None)+ gateway.pop("multiplex_profiles", None)+ if not gateway and "gateway" in cfg:+ cfg.pop("gateway")- config_path.write_text(yaml.safe_dump(cfg, sort_keys=False), encoding="utf-8")++ # Absent keys are deleted by the round-trip writer; the clone's comments survive.++ atomic_config_write(config_path, cfg)++def _bootstrap_profile_dir(profile_dir: Path, source_dir: Optional[Path],sync_imports: bool = False) -> None:"""Fresh layout: bootstrap dirs, then either seed a model block (no source) or clone@@@ -936,13 -1180,9 +1199,10 @@@returnfor relpath in _CLONE_CONFIG_FILES:_clone_file(source_dir, profile_dir, relpath)+ _strip_multiplex_flag(profile_dir / "config.yaml")source_skills = source_dir / "skills"if source_skills.is_dir():- shutil.copytree(- source_skills, profile_dir / "skills", symlinks=True, dirs_exist_ok=True,- ignore=_non_exportable_entries,- )+ _copytree_keep_junctions(source_skills, profile_dir / "skills", _non_exportable_entries, dirs_exist_ok=True)for relpath in _CLONE_SUBDIR_FILES:_clone_file(source_dir, profile_dir, relpath)if sync_imports:diff --cc hermes_cli/runtime_provider_custom.pyindex c1130be93ed,d0ee1a81eee..d4b5e0e6ca3--- a/hermes_cli/runtime_provider_custom.py+++ b/hermes_cli/runtime_provider_custom.py@@@ -470,8 -542,7 +542,9 @@@ def _resolve_named_custom_runtime(*, rerequested_norm = "custom"if requested_norm == "custom" and explicit_base_url:return _resolve_direct_alias_runtime(requested_provider, explicit_api_key, explicit_base_url)- custom_provider = (rp._get_named_custom_provider(requested_provider) if config is None- else _get_named_custom_provider(requested_provider, config=config))- custom_provider = custom_provider or rp._get_named_custom_provider(requested_provider)++ if custom_provider is None:++ custom_provider = (rp._get_named_custom_provider(requested_provider) if config is None++ else _get_named_custom_provider(requested_provider, config=config))if not custom_provider:return Nonebase_url = ((explicit_base_url or "").strip() or custom_provider.get("base_url", "")).rstrip("/")diff --cc hermes_cli/session_schema_history.pyindex e2f3d2216b5,88aa10350b9..f8135ee46a7--- a/hermes_cli/session_schema_history.py+++ b/hermes_cli/session_schema_history.py@@@ -203,10 -203,7 +203,11 @@@ SCHEMA_HISTORY: dict[str, _TableHistory('+', 'compression_recovery_deadline', 'compression_ineffective_count'),)),('26 2026-09-02T14:22Z 8e4366d358', (('+', 'tool_names', 'last_read_at'),)),- ('27 2026-09-19T00:10Z 922a0c3c87', (('+', 'transport_profile', 'profile_name'),)),+ ('27 2026-09-08T18:45Z 0695b12b4c', (+ ('+', 'runtime_revision', 'id'),+ ('+', 'runtime_generation', 'runtime_revision'),+ )),++ ('28 2026-09-19T00:10Z 922a0c3c87', (('+', 'transport_profile', 'profile_name'),)),),),"messages": _TableHistory(diff --cc hermes_cli/update_cmd.pyindex ce29c481a2b,6a1f42ddc61..9603002db6b--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@@ -97,8 -99,8 +99,7 @@@ from hermes_cli.update_cmd_git import_prune_orphan_rescue_refs, _should_skip_upstream_prompt, _sync_fork_with_upstream,_sync_with_upstream_if_needed)from hermes_cli.update_cmd_maint import ( # noqa: F401- _PRE_UPDATE_SNAPSHOT_KEEP, _PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE, _STALE_PURGE_PROTECTED,- _UPDATE_RUNTIME_RELOAD_MODULES,+ _PRE_UPDATE_SNAPSHOT_KEEP, _PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE,- _clear_stale_sqlite_sidecars,_ensure_acp_launcher, _ensure_fhs_path_guard, _finish_dashboard_update_cleanup,_format_time_ago, _post_update_sqlite_runtime_status, _print_bundled_skills_sync_report,_print_curator_first_run_notice, _print_curator_recent_run_notice,diff --cc hermes_cli/web_routers/sessions.pyindex 3a0c85a1035,c5ce453a691..b6991c1af20--- a/hermes_cli/web_routers/sessions.py+++ b/hermes_cli/web_routers/sessions.py@@@ -19,10 -19,10 +19,10 @@@ from fastapi.responses import Streamingfrom hermes_cli.web_deps import latefrom hermes_cli.web_server_gateway import _strip_session_list_rows-from hermes_cli.web_server_sessions import _maybe_auto_archive_for_profile, _session_latest_descendant+from hermes_cli.web_server_sessions import _session_latest_descendantfrom hermes_cli.web_models import (BulkDeleteSessions, SessionImport, SessionOwnerBackfill, SessionPrune, SessionRename)- from hermes_cli.web_routers._common import log as _log, http_failure+ from hermes_cli.web_routers._common import log as _log, destructive_profile, http_failurefrom hermes_state import is_malformed_db_errorfrom hermes_state_errors import is_transient_sqlite_error@@@ -484,21 -496,9 +494,21 @@@ async def get_session_detail(session_idsession["is_default_profile"] = session["profile"] == "default"return session- return _with_db(profile, _detail, read_only=True)+ return await asyncio.to_thread(_with_db, profile, _detail, read_only=True)+@manage_router.get("/api/sessions/{session_id}/mutation-snapshot")+async def get_session_mutation_snapshot(session_id: str, request: Request, profile: Optional[str] = None):+ from hermes_cli.web_server_sessions import _session_mutation_context+ authority, _actor = _session_mutation_context(request, profile)+ row = authority.db.get_session(session_id)+ # An absent import anchor has revision zero by the owner's storage contract,+ # not by a client guessing after a failed or stale detail request.+ return {'session_id': session_id, 'exists': row is not None,+ 'runtime_revision': row['runtime_revision'] if row else 0,+ 'runtime_generation': row['runtime_generation'] if row else None}++@manage_router.get("/api/sessions/{session_id}/latest-descendant")async def get_session_latest_descendant(session_id: str, profile: Optional[str] = None):latest, path = await asyncio.to_thread(@@@ -726,10 -789,12 +763,14 @@@ async def export_session_endpoint(sessi@manage_router.post("/api/sessions/prune")async def prune_sessions_endpoint(body: SessionPrune):"""Delete ended sessions matching filters without blocking the event loop."""- if not body.dry_run:- # Same destructive rule as the rest of the family; a dry run deletes nothing, so it- # keeps working unnamed (it is the preview the confirm dialog reads).- body = body.model_copy(update={- "profile": destructive_profile(body.profile, "POST /api/sessions/prune")})- return await asyncio.to_thread(_prune_sessions, body)+ if body.dry_run:+ return await asyncio.to_thread(_prune_sessions, body)++ # Same destructive rule as the rest of the family; a dry run deletes nothing, so it++ # keeps working unnamed (it is the preview the confirm dialog reads).++ body = body.model_copy(update={++ "profile": destructive_profile(body.profile, "POST /api/sessions/prune")})+ from hermes_cli.web_server_sessions import _with_session_maintenance+ return await asyncio.to_thread(_with_session_maintenance, body.profile, _prune_sessions, body)# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----diff --cc hermes_state_sessions.pyindex 5c5e8f2cf12,931303ac5d3..47090ed70bc--- a/hermes_state_sessions.py+++ b/hermes_state_sessions.py@@@ -312,14 -331,68 +333,15 @@@ class SessionSessionsMixinsidebar even though its transcript is intact (#99222). Stores outside the profile tree (explicit``db_path`` in tests, ad-hoc copies) derive nothing and keep NULL — never guess."""- if not (profile_name or "").strip():- profile_name = self._own_profile_name()- def _do(conn):- system_prompt_hash = self._store_system_prompt(conn, system_prompt)- conn.execute(- """INSERT INTO sessions (- id, source, user_id, session_key, chat_id, chat_type, thread_id,- model, model_config, system_prompt, system_prompt_hash,- parent_session_id, cwd, profile_name, transport_profile, git_repo_root,- origin_json, display_name, started_at- )- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?)- ON CONFLICT(id) DO UPDATE SET- source = CASE- WHEN sessions.source = 'unknown'- THEN COALESCE(excluded.source, 'unknown')- ELSE sessions.source- END,- model = COALESCE(sessions.model, excluded.model),- model_config = CASE- WHEN excluded.model_config IS NOT NULL- AND json_type(- sessions.model_config, '$._reset_from'- ) IS NOT NULL- AND json_remove(- sessions.model_config, '$._reset_from'- ) = '{}'- THEN json_set(- excluded.model_config,- '$._reset_from',- json_extract(- sessions.model_config, '$._reset_from'- )- )- ELSE COALESCE(- sessions.model_config, excluded.model_config- )- END,- system_prompt_hash = COALESCE(- sessions.system_prompt_hash,- excluded.system_prompt_hash- ),- system_prompt = CASE- WHEN sessions.system_prompt_hash IS NULL- AND excluded.system_prompt_hash IS NOT NULL- THEN NULL- ELSE sessions.system_prompt- END,-""" + _UPSERT_KEEP_EXISTING_SQL,- (- session_id, source, user_id, session_key, chat_id, chat_type, thread_id, model,- json.dumps(model_config) if model_config else None, system_prompt_hash,- parent_session_id, cwd, profile_name, transport_profile, git_repo_root, origin_json,- display_name, time.time(),- ),- )- if system_prompt_hash is not None:- self._delete_unreferenced_system_prompts(conn)- if parent_session_id:- self._inherit_parent_session_metadata(conn, session_id)- # Transcript-critical: a failed row creation aborts the turn.- self._execute_write(_do, patience_s=self._TRANSCRIPT_WRITE_PATIENCE_S)+ from hermes_state_worker_lifecycle import insert_session_row_in_transaction+ params = dict(session_id=session_id, source=source, model=model, model_config=model_config,+ system_prompt=system_prompt, user_id=user_id, session_key=session_key,+ chat_id=chat_id, chat_type=chat_type, thread_id=thread_id,+ parent_session_id=parent_session_id, cwd=cwd, profile_name=profile_name,- git_repo_root=git_repo_root, origin_json=origin_json, display_name=display_name)++ git_repo_root=git_repo_root, origin_json=origin_json, display_name=display_name,++ transport_profile=transport_profile)+ self._execute_write(lambda conn: insert_session_row_in_transaction(self, conn, **params),+ patience_s=self._TRANSCRIPT_WRITE_PATIENCE_S)def create_session(self, session_id: str, source: str, **kwargs) -> str:"""Create (upsert) a session record. Returns the session_id."""diff --cc hermes_state_worker_compression.pyindex a0bb4ca9f18,00000000000..96d114a25e5mode 100644,000000..100644--- a/hermes_state_worker_compression.py+++ b/hermes_state_worker_compression.py@@@ -1,497 -1,0 +1,497 @@@+"""Closed compression operations on the worker receipt's connection.++No handler opens a connection or invokes a self-committing SessionDB method.+"""+from typing import Any, Dict, List, Optional+import json+from functools import partial+import math+import time++from hermes_state_runtime import RuntimeStoreError, _text+from hermes_state_compression import _claim_lease_row+++def _fields(payload, required, optional=()):+ if not isinstance(payload, dict) or set(payload) - set(required) - set(optional) or set(required) - set(payload):+ raise RuntimeStoreError('invalid_params')+++def _number(value):+ if type(value) not in (int, float) or not math.isfinite(value):+ raise RuntimeStoreError('invalid_params')+ return value+++def worker_compression_lock(db, conn, sid, payload, *, action):+ if action == 'holder':+ _fields(payload, ())+ row = conn.execute('SELECT holder FROM compression_locks WHERE session_id=? AND expires_at>?',+ (sid, time.time())).fetchone()+ return {'value': row[0] if row else None}+ _fields(payload, ('holder',), () if action == 'release' else ('ttl_seconds',))+ holder = _text(payload['holder'])+ now = time.time()+ ttl = _number(payload.get('ttl_seconds', 300.0))+ if not 0.1 <= ttl <= 3600:+ raise RuntimeStoreError('invalid_params')+ if action == 'acquire':+ from hermes_state import _compression_lock_holder_process_is_dead+ value = _claim_lease_row(conn, 'compression_locks', 'session_id', sid, holder, now, now + ttl,+ lambda h, e: e < now or _compression_lock_holder_process_is_dead(h))[0]+ elif action == 'renew':+ value = conn.execute('UPDATE compression_locks SET expires_at=? WHERE session_id=? AND holder=?',+ (now + ttl, sid, holder)).rowcount > 0+ else:+ conn.execute('DELETE FROM compression_locks WHERE session_id=? AND holder=?', (sid, holder))+ value = None+ return {'value': value}+++def worker_cooldown_record(db, conn, sid, payload):+ _fields(payload, ('cooldown_until', 'error'))+ deadline = _number(payload['cooldown_until'])+ error = payload['error']+ if error is not None and not isinstance(error, str):+ raise RuntimeStoreError('invalid_params')+ conn.execute('UPDATE sessions SET compression_failure_cooldown_until = CASE '+ 'WHEN compression_failure_cooldown_until IS NOT NULL AND compression_failure_cooldown_until > ? '+ 'THEN compression_failure_cooldown_until ELSE ? END, compression_failure_error=? WHERE id=?',+ (deadline, deadline, error, sid))+ return {'value': None}+++def worker_cooldown_restore(db, conn, sid, payload):+ _fields(payload, ('snapshot',))+ snapshot = payload['snapshot']+ _fields(snapshot, ('session_exists', 'cooldown_until', 'error'))+ if type(snapshot['session_exists']) is not bool:+ raise RuntimeStoreError('invalid_params')+ if not snapshot['session_exists']:+ raise RuntimeError('cannot restore absent compression cooldown row: session now exists')+ deadline, error = snapshot['cooldown_until'], snapshot['error']+ if deadline is not None:+ _number(deadline)+ if error is not None and not isinstance(error, str):+ raise RuntimeStoreError('invalid_params')+ conn.execute('UPDATE sessions SET compression_failure_cooldown_until=?, compression_failure_error=? WHERE id=?',+ (deadline, error, sid))+ actual = conn.execute('SELECT compression_failure_cooldown_until,compression_failure_error FROM sessions WHERE id=?',+ (sid,)).fetchone()+ if actual is None or tuple(actual) != (deadline, error):+ raise RuntimeError('compression cooldown rollback verification failed')+ return {'value': None}+++def worker_cooldown_clear(db, conn, sid, payload):+ _fields(payload, ())+ return worker_cooldown_restore(db, conn, sid, {'snapshot': {+ 'session_exists': True, 'cooldown_until': None, 'error': None}})+++def worker_compression_counter(db, conn, sid, payload, *, column):+ _fields(payload, ('value',))+ value = payload['value']+ if value is not None:+ _number(value)+ if column != 'compression_recovery_deadline' and (type(value) is not int or value < 0):+ raise RuntimeStoreError('invalid_params')+ conn.execute(f'UPDATE sessions SET {column}=? WHERE id=?', (value, sid))+ return {'value': None}+++class CompressionSnapshot:+ """Reuse production read algorithms on the receipt connection, never a second handle.++ Only read primitives are provided; this object cannot start/commit a write.+ Wire handlers below select concrete projections, not caller-named methods.+ """+ from hermes_state_compression import SessionCompressionMixin as _C+ from hermes_state_messages import SessionMessagesMixin as _M+ from hermes_state_sessions import SessionSessionsMixin as _S++ get_compression_chain = _C.get_compression_chain+ get_compression_tip = _C.get_compression_tip+ get_compression_lineage = _C.get_compression_lineage+ _is_compression_child_row = _C._is_compression_child_row+ _session_lineage_root_to_tip = _S._session_lineage_root_to_tip+ _is_explicit_branch_session = _S._is_explicit_branch_session+ declared_scope_identity = _S.declared_scope_identity+ _resume_lineage_ids = _M._resume_lineage_ids+ get_conversation_root = _M.get_conversation_root+ resolve_resume_session_id = _M.resolve_resume_session_id+ latest_conversation_boundary = _M.latest_conversation_boundary+ _is_explicit_fork_child_row = _M._is_explicit_fork_child_row++ def __init__(self, db, conn):+ self.db, self.conn = db, conn++ def _read_ctx(self):+ from contextlib import nullcontext+ return nullcontext(self.conn)++ def _read_one(self, sql, params=()):+ return self.conn.execute(sql, params).fetchone()++ def _read_all(self, sql, params=()):+ return self.conn.execute(sql, params).fetchall()++ def get_session(self, sid):+ from hermes_state_worker_context import worker_context+ return worker_context(self.db, self.conn, sid, {})['session']++ def authorize(self, assigned, target):+ _text(target)+ # Attribution ancestry is readable; unrelated siblings and foreign trees are not.+ allowed = self._session_lineage_root_to_tip(assigned)+ allowed += self.get_compression_chain(assigned)+ if target not in allowed:+ raise RuntimeStoreError('permission_denied')+++def worker_lineage_context(db, conn, sid, payload):+ _fields(payload, ('target',))+ view = CompressionSnapshot(db, conn)+ target = payload['target']+ view.authorize(sid, target)+ return {'session': view.get_session(target)}+++def worker_lineage(db, conn, sid, payload):+ _fields(payload, ('target',))+ view = CompressionSnapshot(db, conn)+ target = payload['target']+ view.authorize(sid, target)+ return {'readable_ids': view._session_lineage_root_to_tip(sid) + view.get_compression_chain(sid),+ 'lineage': view.get_compression_lineage(target),+ 'root': view.get_conversation_root(target),+ 'tip': view.get_compression_tip(target),+ 'resume': view.resolve_resume_session_id(target),+ 'identity': view.declared_scope_identity(target)}+++def worker_boundary(db, conn, sid, payload):+ _fields(payload, ('session_key', 'source'))+ view = CompressionSnapshot(db, conn)+ row = view.get_session(sid)+ if (row['session_key'], row['source']) != (payload['session_key'], payload['source']):+ raise RuntimeStoreError('permission_denied')+ return {'value': view.latest_conversation_boundary(payload['session_key'], payload['source'])}+++def worker_history(db, conn, sid, payload):+ _fields(payload, ('target', 'include_ancestors', 'include_inactive', 'repair_alternation',+ 'include_row_ids', 'include_compacted'))+ if any(type(v) is not bool for k, v in payload.items() if k != 'target'):+ raise RuntimeStoreError('invalid_params')+ view = CompressionSnapshot(db, conn)+ target = payload['target']+ view.authorize(sid, target)+ ids = view._resume_lineage_ids(target) if payload['include_ancestors'] else [target]+ active = db._active_clause(payload['include_inactive'], payload['include_compacted'])+ rows = conn.execute(f'SELECT {db._CONVERSATION_ROW_COLUMNS} FROM messages '+ f'WHERE session_id IN ({",".join("?" for _ in ids)}){active} ORDER BY id', ids).fetchall()+ if payload['include_compacted']:+ rows = db._dedupe_display_generations(rows)+ return {'messages': db._rows_to_conversation(rows, session_id=target,+ include_ancestors=payload['include_ancestors'], repair_alternation=payload['repair_alternation'],+ include_row_ids=payload['include_row_ids'])}++++from hermes_state_common import _COMPRESSION_LOCK_ROW_SQL, is_automatic_end_reason, _placeholders+from hermes_state_messages import _ARCHIVE_ACTIVE_SQL, _SET_COUNTERS_SQL+from hermes_state_errors import CompressionSessionBusyError, SessionCompressionInProgressError+_LOCK_ROW_SQL = _COMPRESSION_LOCK_ROW_SQL+++def archive_on_connection(db, conn, session_id: str, compacted_messages: List[Dict[str, Any]], model_config_patch: Optional[Dict[str, Any]]=None, watermark: Optional[int]=None, lock_holder: Optional[str]=None, tail_count: int=0):+ if lock_holder is not None:+ lock_row = conn.execute(_COMPRESSION_LOCK_ROW_SQL, (session_id,)).fetchone()+ if lock_row is None or lock_row['holder'] != lock_holder or float(lock_row['expires_at']) <= time.time():+ raise SessionCompressionInProgressError(f'Compression lease for {session_id!r} lost before commit; refusing to publish a stale compaction')+ patch = model_config_patch is not None+ patched_model_config = db._merge_model_config_json(conn, session_id, model_config_patch, on_missing='raise') if patch else None+ tail_ids, tail_tool_calls = ([], 0) if watermark is None else db._tail_rows_after_watermark(conn, 'SELECT id, tool_calls FROM messages WHERE session_id = ? AND active = 1 AND id > ? ORDER BY id', (session_id, int(watermark)))+ rewind_ids: list[int] = []+ if tail_count > 0:+ bound = watermark is not None+ rewind_ids = [int(row['id']) for row in conn.execute(f"SELECT id FROM messages WHERE session_id = ? AND active = 1{(' AND id <= ?' if bound else '')} ORDER BY id DESC LIMIT ?", (session_id, *((int(watermark),) if bound else ()), int(tail_count))).fetchall()]+ rewind_ids += tail_ids+ if rewind_ids:+ placeholders = _placeholders(rewind_ids)+ conn.execute(f'UPDATE messages SET active = 0, compacted = 0 WHERE session_id = ? AND id IN ({placeholders})', [session_id, *rewind_ids])+ conn.execute(f'{_ARCHIVE_ACTIVE_SQL} AND id NOT IN ({placeholders})', [session_id, *rewind_ids])+ else:+ conn.execute(_ARCHIVE_ACTIVE_SQL, (session_id,))+ inserted, tool_calls_total = db._insert_message_rows(conn, session_id, compacted_messages)+ if tail_ids:+ db._clone_message_rows(conn, tail_ids)+ inserted += len(tail_ids)+ tool_calls_total += tail_tool_calls+ conn.execute(f"{_SET_COUNTERS_SQL}{(', model_config = ?' if patch else '')} WHERE id = ?", (inserted, tool_calls_total, *((patched_model_config,) if patch else ()), session_id))+ return inserted++def publish_on_connection(db, conn, *, parent_session_id: str, child_session_id: str, source: str, messages: List[Dict[str, Any]], model: str=None, model_config: Dict[str, Any]=None, system_prompt: str=None, cwd: str=None, profile_name: str=None, compression_lock_holder: str=None, require_compression_lease: bool=True, require_lease_refresh: bool=False, lease_ttl_seconds: float=300.0, watermark: Optional[int]=None, watermark_ceiling: Optional[int]=None):+ if require_lease_refresh and compression_lock_holder:+ conn.execute('UPDATE compression_locks SET expires_at = ? WHERE session_id = ? AND holder = ?', (time.time() + lease_ttl_seconds, parent_session_id, compression_lock_holder))+ lock_row = conn.execute(_LOCK_ROW_SQL, (parent_session_id,)).fetchone()+ if require_compression_lease and (lock_row is None or not compression_lock_holder or lock_row['holder'] != compression_lock_holder or (float(lock_row['expires_at']) <= time.time())):+ raise CompressionSessionBusyError(f'Compression lease lost before publication: {parent_session_id}')+ parent = conn.execute('SELECT ended_at, end_reason, cwd, git_branch, git_repo_root,\n user_id, session_key, chat_id, chat_type,\n thread_id, display_name, origin_json, profile_name\n FROM sessions WHERE id = ?', (parent_session_id,)).fetchone()+ if parent is None:+ raise RuntimeError(f'Compression parent not found: {parent_session_id}')+ if parent['ended_at'] is not None:+ if not is_automatic_end_reason(parent['end_reason']):+ raise RuntimeError(f'Compression parent already ended: {parent_session_id}')+ conn.execute('UPDATE sessions SET ended_at = NULL, end_reason = NULL WHERE id = ?', (parent_session_id,))+ if not messages:+ raise RuntimeError('Compression child handoff must not be empty')+ db._publish_child_session_row(conn, parent, parent_session_id=parent_session_id, child_session_id=child_session_id, source=source, model=model, model_config=model_config, system_prompt=system_prompt, cwd=cwd, profile_name=profile_name)+ total_messages, total_tool_calls = db._insert_message_rows(conn, child_session_id, messages)+ if watermark is not None:+ bounded = watermark_ceiling is not None+ tail_ids, tail_tool_calls = db._tail_rows_after_watermark(conn, f"SELECT id, tool_calls FROM messages WHERE session_id = ? AND active = 1 AND id > ?{(' AND id <= ?' if bounded else '')} ORDER BY id", [parent_session_id, int(watermark), *([int(watermark_ceiling)] if bounded else [])])+ if tail_ids:+ db._clone_message_rows(conn, tail_ids, session_id=child_session_id)+ total_messages += len(tail_ids)+ total_tool_calls += tail_tool_calls+ conn.execute('UPDATE sessions SET message_count = ?, tool_call_count = ? WHERE id = ?', (total_messages, total_tool_calls, child_session_id))+ updated = conn.execute("UPDATE sessions SET ended_at = ?, end_reason = 'compression' WHERE id = ? AND ended_at IS NULL", (time.time(), parent_session_id))+ if updated.rowcount != 1:+ raise RuntimeError(f'Compression parent changed during publication: {parent_session_id}')+ from hermes_state_local_lineage import advance_local_target+ advance_local_target(conn, parent_session_id, child_session_id)+++def worker_watermark(db, conn, sid, payload):+ _fields(payload, ())+ return {'value': conn.execute('SELECT COALESCE(MAX(id),0) FROM messages WHERE session_id=? AND active=1',+ (sid,)).fetchone()[0]}+++def _handoff_messages(conn, sid, messages):+ from hermes_state_runtime import _MESSAGE_FIELDS+ 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 - {'_compressed_summary_has_user_turn'} or msg.get('role') not in ('user', 'assistant', 'system', 'tool'):+ raise RuntimeStoreError('invalid_params')+ if '_row_id' in msg and not conn.execute('SELECT 1 FROM messages WHERE session_id=? AND id=?',+ (sid, msg['_row_id'])).fetchone():+ raise RuntimeStoreError('permission_denied')+++def _watermarks(payload):+ for field in ('watermark', 'watermark_ceiling'):+ value = payload.get(field)+ if value is not None and (type(value) is not int or value < 0):+ raise RuntimeStoreError('invalid_params')+++def worker_archive(db, conn, sid, payload):+ from hermes_state_worker_context import SIDECAR_KEYS+ _fields(payload, ('messages', 'model_config_patch', 'watermark', 'lock_holder', 'tail_count'))+ _handoff_messages(conn, sid, payload['messages'])+ _watermarks(payload)+ # Micro-compaction and proactive prune archive in place without a lease, like the owner path.+ if payload['lock_holder'] is not None:+ _text(payload['lock_holder'])+ patch = payload['model_config_patch']+ if patch is not None and (not isinstance(patch, dict) or set(patch) - SIDECAR_KEYS):+ raise RuntimeStoreError('invalid_params')+ if type(payload['tail_count']) is not int or payload['tail_count'] < 0:+ raise RuntimeStoreError('invalid_params')+ value = archive_on_connection(db, conn, sid, payload['messages'], model_config_patch=patch,+ watermark=payload['watermark'], lock_holder=payload['lock_holder'], tail_count=payload['tail_count'])+ return {'value': value, 'row_ids': [message['_row_id'] for message in payload['messages']]}+++def _migrate_worker_automation(db, conn, parent, child):+ from hermes_cli.goals import GoalState+ from hermes_cli.heartbeat import HeartbeatState+ from hermes_cli.loops import LoopState+ for family, state_type in (('goal', GoalState), ('heartbeat', HeartbeatState), ('loop', LoopState)):+ old_key, new_key = f'{family}:{parent}', f'{family}:{child}'+ row = conn.execute('SELECT value FROM state_meta WHERE key=?', (old_key,)).fetchone()+ if row is None:+ continue+ state = state_type.from_json(row[0])+ if state.status == 'cleared':+ continue+ prior = conn.execute('SELECT value FROM state_meta WHERE key=?', (new_key,)).fetchone()+ if prior is not None and (family != 'heartbeat' or state_type.from_json(prior[0]).status != 'cleared'):+ continue+ db.set_meta(new_key, state.to_json(), cursor=conn)+ state.status = 'cleared'+ db.set_meta(old_key, state.to_json(), cursor=conn)+++def worker_publish(db, conn, sid, payload):+ from hermes_state_sessions import _parse_model_config+ _fields(payload, ('child_session_id', 'source', 'messages', 'model', 'model_config', 'system_prompt',+ 'cwd', 'profile_name', 'compression_lock_holder', 'require_compression_lease',+ 'require_lease_refresh', 'lease_ttl_seconds', 'watermark', 'watermark_ceiling'))+ child = _text(payload['child_session_id'])+ _text(payload['compression_lock_holder'])+ _watermarks(payload)+ if payload['require_compression_lease'] is not True or type(payload['require_lease_refresh']) is not bool:+ raise RuntimeStoreError('invalid_params')+ if not 0.1 <= _number(payload['lease_ttl_seconds']) <= 3600:+ raise RuntimeStoreError('invalid_params')+ _handoff_messages(conn, sid, payload['messages'])+ parent = CompressionSnapshot(db, conn).get_session(sid)+ for key in ('source', 'cwd', 'profile_name'):+ if payload[key] is not None and payload[key] != parent[key]:+ raise RuntimeStoreError('permission_denied')+ for key in ('model', 'system_prompt'):+ if payload[key] is not None and not isinstance(payload[key], str):+ raise RuntimeStoreError('invalid_params')+ cfg = payload['model_config']+ if cfg is not None and not isinstance(cfg, dict):+ raise RuntimeStoreError('invalid_params')+ cfg = dict(cfg or {})+ prior = _parse_model_config(parent['model_config'])+ for key in ('_branched_from', '_delegate_from', '_reset_from'):+ if key in cfg and cfg[key] != prior.get(key):+ raise RuntimeStoreError('permission_denied')+ if key in prior:+ cfg[key] = prior[key]+ if conn.execute('SELECT 1 FROM sessions WHERE id=?', (child,)).fetchone():+ raise RuntimeStoreError('permission_denied')+ worker = conn.execute("SELECT * FROM worker_executions WHERE session_id=? AND status IN ('registered','running')", (sid,)).fetchone()+ if worker is None:+ raise RuntimeStoreError('stale_generation')+ publish_on_connection(db, conn, parent_session_id=sid, **dict(payload, model_config=cfg))+ _migrate_worker_automation(db, conn, sid, child)+ conn.execute('UPDATE sessions SET runtime_generation=? WHERE id=?', (worker['generation'], child))+ conn.execute('UPDATE worker_executions SET session_id=? WHERE execution_id=?', (child, worker['execution_id']))+ # The FIFO/retry key is immutable; only physical lineage follows rotation.+ conn.execute("UPDATE session_admissions SET lineage_json=json_insert(lineage_json,'$[#]',?) "+ "WHERE json_extract(lineage_json,'$[#-1]')=? AND generation=? AND owner_epoch=? "+ "AND status IN ('started','unknown')",+ (child, sid, worker['generation'], worker['owner_epoch']))+ return {'value': None, 'worker_assignment': {'parent': sid, 'session_id': child},+ 'row_ids': [message['_row_id'] for message in payload['messages']]}+++def worker_receipt_assignment(conn, execution_id, session_id, generation, sequence, digest):+ """Only an identical already-committed publication can retry its old assignment."""+ from hermes_state_runtime import _worker_assignment+ receipt = conn.execute('SELECT payload_digest,result_json FROM worker_receipts WHERE execution_id=? AND sequence=?',+ (execution_id, sequence)).fetchone()+ if receipt and receipt['payload_digest'] == digest:+ assignment = json.loads(receipt['result_json']).get('worker_assignment')+ if assignment and assignment['parent'] == session_id:+ current = conn.execute('SELECT session_id FROM worker_executions WHERE execution_id=?', (execution_id,)).fetchone()+ return _worker_assignment(conn, execution_id, current['session_id'], generation)+ return _worker_assignment(conn, execution_id, session_id, generation)+++def worker_claim_origin(db, params):+ """Keep the producer claim bound to its original identity after physical rotation."""+ with db._read_ctx() as conn:+ row = conn.execute("SELECT result_json FROM worker_receipts WHERE execution_id=? "+ "AND json_extract(result_json,'$.worker_assignment.parent') IS NOT NULL ORDER BY sequence LIMIT 1",+ (params['execution_id'],)).fetchone()+ return json.loads(row[0])['worker_assignment']['parent'] if row else params['session_id']+++def worker_retry_target(db, params):+ """Transport verification accepts old targets only for exact publication replay."""+ from gateway.session_admission import admission_fingerprint+ if params.get('operation') != 'compression.publish':+ return params['session_id']+ digest = admission_fingerprint(canonical_target=params['session_id'],+ payload={'operation': params['operation'], 'payload': params['payload']})+ with db._read_ctx() as conn:+ row = worker_receipt_assignment(conn, params['execution_id'], params['session_id'],+ params['generation'], params['sequence'], digest)+ return row['session_id']+++from hermes_state_common import _ENDED_ROW_SQL, _ended_by_compression++def reopen_on_connection(db, conn, session_id):+ if not _ended_by_compression(conn.execute(_ENDED_ROW_SQL, (session_id,)).fetchone()):+ return False- child = conn.execute('\n SELECT 1\n FROM sessions\n WHERE parent_session_id = ?\n ' + db._NON_CONTINUATION_CHILD_FILTER_SQL.format(alias='') + '\n LIMIT 1\n ', (session_id, session_id, session_id)).fetchone()++ child = conn.execute('\n SELECT 1\n FROM sessions\n WHERE parent_session_id = ?\n ' + db._NON_CONTINUATION_CHILD_FILTER_SQL.format(alias='') + '\n LIMIT 1\n ', (session_id,) * 4).fetchone()+ if child is not None:+ return False+ now = time.time()+ lock_row = conn.execute(_LOCK_ROW_SQL, (session_id,)).fetchone()+ if lock_row is not None:+ expires_at = lock_row['expires_at']+ if expires_at is None or float(expires_at) >= now:+ return False+ deleted = conn.execute('DELETE FROM compression_locks WHERE session_id = ? AND holder = ? AND expires_at = ?', (session_id, lock_row['holder'], expires_at))+ if deleted.rowcount != 1:+ return False+ updated = conn.execute("UPDATE sessions SET ended_at = NULL, end_reason = NULL WHERE id = ? AND ended_at IS NOT NULL AND end_reason = 'compression'", (session_id,))+ return updated.rowcount == 1+++def worker_reopen(db, conn, sid, payload):+ _fields(payload, ())+ return {'value': reopen_on_connection(db, conn, sid)}+++def worker_compression_cleanup(db, conn, sid, payload):+ _fields(payload, ('target', 'holder'))+ target = _text(payload['target'])+ holder = _text(payload['holder'])+ view = CompressionSnapshot(db, conn)+ view.authorize(sid, target)+ if db._session_turn_lease_key_on_conn(conn, sid) != db._session_turn_lease_key_on_conn(conn, target):+ raise RuntimeStoreError('permission_denied')+ conn.execute('DELETE FROM compression_locks WHERE session_id=? AND holder=?', (target, holder))+ return {'value': None}+++def worker_compression_append(db, conn, sid, payload):+ _fields(payload, ('messages', 'compression_lock_holder', 'turn_lease_holder', 'turn_lease_ttl_seconds'))+ _handoff_messages(conn, sid, payload['messages'])+ for key in ('compression_lock_holder', 'turn_lease_holder'):+ if payload[key] is not None:+ _text(payload[key])+ if not 0.1 <= _number(payload['turn_lease_ttl_seconds']) <= 3600:+ raise RuntimeStoreError('invalid_params')+ count = db._append_messages_in_transaction(conn, sid, **payload)+ return {'count': count, 'annotations': [+ {key: msg[key] for key in ('_row_id', '_canonical_content') if key in msg} for msg in payload['messages']]}+++def worker_turn_cleanup(db, conn, sid, payload):+ _fields(payload, ('target', 'holder'))+ target = _text(payload['target'])+ holder = _text(payload['holder'])+ CompressionSnapshot(db, conn).authorize(sid, target)+ key = db._session_turn_lease_key_on_conn(conn, sid)+ if key != db._session_turn_lease_key_on_conn(conn, target):+ raise RuntimeStoreError('permission_denied')+ conn.execute('DELETE FROM session_turn_leases WHERE conversation_id=? AND holder=?', (key, holder))+ return {'released': True}+++WORKER_COMPRESSION_HANDLERS = {+ 'turn.cleanup': worker_turn_cleanup,+ 'compression.append': worker_compression_append,+ 'compression.reopen': worker_reopen,+ 'compression.cleanup': worker_compression_cleanup,+ 'compression.watermark': worker_watermark,+ 'compression.archive': worker_archive,+ 'compression.publish': worker_publish,+ 'compression.context': worker_lineage_context,+ 'compression.lineage': worker_lineage,+ 'compression.boundary': worker_boundary,+ 'compression.history': worker_history,+ **{'compression.lock.' + action: partial(worker_compression_lock, action=action)+ for action in ('acquire', 'renew', 'release', 'holder')},+ 'compression.cooldown.record': worker_cooldown_record,+ 'compression.cooldown.restore': worker_cooldown_restore,+ 'compression.cooldown.clear': worker_cooldown_clear,+ **{'compression.' + name: partial(worker_compression_counter, column=column)+ for name, column in (('fallback', 'compression_fallback_streak'),+ ('ineffective', 'compression_ineffective_count'),+ ('recovery', 'compression_recovery_deadline'))},+}diff --cc hermes_state_worker_lifecycle.pyindex 73d07dca617,00000000000..7f345e92411mode 100644,000000..100644--- a/hermes_state_worker_lifecycle.py+++ b/hermes_state_worker_lifecycle.py@@@ -1,244 -1,0 +1,245 @@@+"""Closed worker lifecycle handlers, called only inside the receipt transaction."""+import json+import time++from hermes_state_runtime import RuntimeStoreError+++_IDENTITY_FIELDS = frozenset({+ 'user_id', 'session_key', 'chat_id', 'chat_type', 'thread_id',+ 'parent_session_id', 'cwd', 'profile_name', 'git_repo_root', 'origin_json', 'display_name',+})+_CREATE_FIELDS = _IDENTITY_FIELDS | {'source', 'model', 'model_config', 'system_prompt'}+_CONSTRUCTOR_CONFIG = frozenset({'max_iterations', 'max_tokens', 'reasoning_config', 'yolo_mode'})+++def worker_create(db, conn, session_id, payload):+ if set(payload) - _CREATE_FIELDS or 'source' not in payload:+ raise RuntimeStoreError('invalid_params')+ row = conn.execute('SELECT * FROM sessions WHERE id=?', (session_id,)).fetchone()+ # A worker cannot mint a row or supply unreserved routing, lineage or cwd.+ if row is None or payload['source'] != row['source']:+ raise RuntimeStoreError('permission_denied')+ for key in _IDENTITY_FIELDS:+ value = payload.get(key)+ if value is not None and value != row[key]:+ raise RuntimeStoreError('permission_denied')+ for key in _CREATE_FIELDS - {'model_config'}:+ if payload.get(key) is not None and not isinstance(payload[key], str):+ raise RuntimeStoreError('invalid_params')+ config = payload.get('model_config')+ if config is not None and (not isinstance(config, dict) or set(config) - _CONSTRUCTOR_CONFIG):+ raise RuntimeStoreError('invalid_params')+ insert_session_row_in_transaction(db, conn, session_id, **payload)+ return {'value': session_id}+++def worker_end(db, conn, session_id, payload):+ if set(payload) != {'end_reason'} or not isinstance(payload['end_reason'], str) or not payload['end_reason']:+ raise RuntimeStoreError('invalid_params')+ db._end_and_bump(conn,+ 'UPDATE sessions SET ended_at=?,end_reason=? WHERE id=? AND ended_at IS NULL',+ (time.time(), payload['end_reason'], session_id), session_id, payload['end_reason'])+ return {'value': None}+++def worker_lifecycle(db, conn, session_id, payload):+ from hermes_state_sessions import classify_session_status+ if payload:+ raise RuntimeStoreError('invalid_params')+ row = conn.execute("SELECT role,tool_calls IS NOT NULL AS has_tool_calls,finish_reason "+ "FROM messages WHERE session_id=? ORDER BY id DESC LIMIT 1", (session_id,)).fetchone()+ value = classify_session_status(role=row['role'], has_tool_calls=bool(row['has_tool_calls']),+ finish_reason=row['finish_reason']) if row else 'empty'+ return {'value': value}+++def worker_title(db, conn, session_id, payload):+ if (set(payload) != {'title', 'source'} or payload['source'] not in ('user', 'derived', 'llm')+ or not (payload['title'] is None or isinstance(payload['title'], str))):+ raise RuntimeStoreError('invalid_params')+ try:+ value = bool(db._set_session_title_in_transaction(+ conn, session_id, payload['title'], source=payload['source']))+ except ValueError:+ # Expected validation/conflict outcomes must not poison the retry journal.+ # Keep candidate authority in the receipt, not an in-memory worker claim.+ return {'value': False, 'error': 'Title unavailable or invalid', 'title_candidate': payload['title']}+ return {'value': value}+++def worker_title_source(db, conn, session_id, payload):+ if set(payload) != {'source'} or payload['source'] not in ('user', 'derived', 'llm'):+ raise RuntimeStoreError('invalid_params')+ return {'value': conn.execute(+ 'UPDATE sessions SET title_source=? WHERE id=? AND title IS NOT NULL',+ (payload['source'], session_id)).rowcount > 0}+++def worker_next_title(db, conn, session_id, payload):+ from hermes_state_titles import _NUMBERED_TITLE_RE+ from hermes_state_common import escape_like+ if set(payload) != {'base_title'} or not isinstance(payload['base_title'], str):+ raise RuntimeStoreError('invalid_params')+ title = conn.execute('SELECT title FROM sessions WHERE id=?', (session_id,)).fetchone()[0]+ # Only an assigned title or a receipted title attempt authorizes dedupe.+ # Concurrent activity/usage receipts must not invalidate that title attempt.+ candidate = payload['base_title']+ attempted = conn.execute(+ "SELECT 1 FROM worker_receipts r JOIN worker_executions w ON w.execution_id=r.execution_id "+ "WHERE w.session_id=? AND w.status='running' "+ "AND json_extract(r.result_json,'$.title_candidate')=? LIMIT 1",+ (session_id, candidate)).fetchone()+ if candidate != title and attempted is None:+ raise RuntimeStoreError('permission_denied')+ match = _NUMBERED_TITLE_RE.match(candidate)+ base = match.group(1) if match else candidate+ rows = conn.execute("SELECT title FROM sessions WHERE title=? OR title LIKE ? ESCAPE '\\'",+ (base, f'{escape_like(base)} #%')).fetchall()+ if not rows:+ return {'value': base}+ numbers = [int(m.group(2)) for m in (_NUMBERED_TITLE_RE.match(row['title']) for row in rows) if m]+ return {'value': f'{base} #{max([1, *numbers]) + 1}'}+++def worker_activity(db, conn, session_id, payload):+ import math+ from agent.session_activity import bound_activity_description, normalize_activity_provenance+ if (set(payload) != {'ts', 'description', 'provenance'}+ or any(payload[k] is not None and not isinstance(payload[k], str)+ for k in ('description', 'provenance'))):+ raise RuntimeStoreError('invalid_params')+ when = payload['ts']+ if when is not None and (type(when) not in (float, int) or not math.isfinite(when)):+ raise RuntimeStoreError('invalid_params')+ when = time.time() if when is None else float(when)+ conn.execute('UPDATE sessions SET last_activity_at=?,last_activity_description=?,last_activity_provenance=? '+ 'WHERE id=? AND (last_activity_at IS NULL OR last_activity_at<?)',+ (when, bound_activity_description(payload['description']),+ normalize_activity_provenance(payload['provenance']).value, session_id, when))+ return {'value': None}+++def worker_activity_clear(db, conn, session_id, payload):+ from agent.session_activity import ActivityProvenance+ if payload:+ raise RuntimeStoreError('invalid_params')+ conn.execute('UPDATE sessions SET last_activity_description=?,last_activity_provenance=? WHERE id=?',+ ('', ActivityProvenance.UNKNOWN.value, session_id))+ return {'value': None}+++def worker_billing_route(db, conn, session_id, payload):+ if (set(payload) != {'provider', 'base_url', 'billing_mode'}+ or any(payload[k] is not None and not isinstance(payload[k], str) for k in payload)):+ raise RuntimeStoreError('invalid_params')+ conn.execute('UPDATE sessions SET billing_provider=?,billing_base_url=?,billing_mode=COALESCE(?,billing_mode),'+ 'system_prompt=NULL,system_prompt_hash=NULL WHERE id=?',+ (payload['provider'], payload['base_url'], payload['billing_mode'], session_id))+ db._delete_unreferenced_system_prompts(conn)+ return {'value': None}+++def worker_api_content(db, conn, session_id, payload):+ from hermes_state_messages import _scrub_surrogates+ if set(payload) != {'content', 'api_content'} or not isinstance(payload['api_content'], str):+ raise RuntimeStoreError('invalid_params')+ value = conn.execute(+ "UPDATE messages SET api_content=? WHERE id=(SELECT id FROM messages WHERE session_id=? "+ "AND role='user' AND active=1 ORDER BY id DESC LIMIT 1) AND content IS ?",+ (_scrub_surrogates(payload['api_content']), session_id, db._encode_content(payload['content']))).rowcount+ return {'value': value}+++WORKER_LIFECYCLE_HANDLERS = {+ 'session.title': worker_title,+ 'session.title_source': worker_title_source,+ 'session.next_title': worker_next_title,+ 'session.activity': worker_activity,+ 'session.activity_clear': worker_activity_clear,+ 'session.billing_route': worker_billing_route,+ 'session.api_content': worker_api_content,+ 'session.create': worker_create,+ 'session.end': worker_end,+ 'session.lifecycle': worker_lifecycle,+}+++def insert_session_row_in_transaction(+ self, conn, session_id, source, model=None, model_config=None,+ system_prompt=None, user_id=None, session_key=None, chat_id=None,+ chat_type=None, thread_id=None, parent_session_id=None, cwd=None,- profile_name=None, git_repo_root=None, origin_json=None, display_name=None):++ profile_name=None, git_repo_root=None, origin_json=None, display_name=None,++ transport_profile=None):+ """Connection-taking body of the keep-existing constructor upsert.++ The ordinary constructor should delegate here too. Worker identity is+ validated before entry; this helper never opens or commits a DB.+ """+ from hermes_state_sessions import _UPSERT_KEEP_EXISTING_SQL+ from hermes_state_mutation_retirement import RETIRED_PREFIX+ # A delayed constructor/accounting backfill must not recreate a deleted session+ # beside its durable tombstone (the exact delete retry would then report a stale+ # success while a fresh delete collides with the existing marker).+ if (conn.execute('SELECT 1 FROM sessions WHERE id=?', (session_id,)).fetchone() is None+ and conn.execute('SELECT 1 FROM state_meta WHERE key=?', (RETIRED_PREFIX + session_id,)).fetchone()):+ raise RuntimeStoreError('not_found')+ if not (profile_name or "").strip():+ profile_name = self._own_profile_name()+ system_prompt_hash = self._store_system_prompt(conn, system_prompt)+ conn.execute(+ """INSERT INTO sessions (+ id, source, user_id, session_key, chat_id, chat_type, thread_id,+ model, model_config, system_prompt, system_prompt_hash,- parent_session_id, cwd, profile_name, git_repo_root,++ parent_session_id, cwd, profile_name, transport_profile, git_repo_root,+ origin_json, display_name, started_at+ )- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?)++ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ ON CONFLICT(id) DO UPDATE SET+ source = CASE+ WHEN sessions.source = 'unknown'+ THEN COALESCE(excluded.source, 'unknown')+ ELSE sessions.source+ END,+ model = COALESCE(sessions.model, excluded.model),+ model_config = CASE+ WHEN excluded.model_config IS NOT NULL+ AND json_type(+ sessions.model_config, '$._reset_from'+ ) IS NOT NULL+ AND json_remove(+ sessions.model_config, '$._reset_from'+ ) = '{}'+ THEN json_set(+ excluded.model_config,+ '$._reset_from',+ json_extract(+ sessions.model_config, '$._reset_from'+ )+ )+ ELSE COALESCE(+ sessions.model_config, excluded.model_config+ )+ END,+ system_prompt_hash = COALESCE(+ sessions.system_prompt_hash,+ excluded.system_prompt_hash+ ),+ system_prompt = CASE+ WHEN sessions.system_prompt_hash IS NULL+ AND excluded.system_prompt_hash IS NOT NULL+ THEN NULL+ ELSE sessions.system_prompt+ END,+""" + _UPSERT_KEEP_EXISTING_SQL,+ (+ session_id, source, user_id, session_key, chat_id, chat_type, thread_id, model,+ json.dumps(model_config) if model_config else None, system_prompt_hash,- parent_session_id, cwd, profile_name, git_repo_root, origin_json, display_name,- time.time(),++ parent_session_id, cwd, profile_name, transport_profile, git_repo_root, origin_json,++ display_name, time.time(),+ ),+ )+ if system_prompt_hash is not None:+ self._delete_unreferenced_system_prompts(conn)+ if parent_session_id:+ self._inherit_parent_session_metadata(conn, session_id)diff --cc providers/__init__.pyindex a4efd5dca48,66b276770b8..93e80fdcc57--- a/providers/__init__.py+++ b/providers/__init__.py@@@ -72,14 -153,11 +153,15 @@@ def get_provider_profile(name: str) ->Returns None if the provider has no profile (falls back to generic)."""+ from agent.safe_worker_policy import safe_worker_enabled++ if safe_worker_enabled():+ return Noneif not _discovered:_discover_providers()- canonical = _ALIASES.get(name, name)- profile = _REGISTRY.get(canonical)+ layer = _home_layer()+ canonical = layer.aliases.get(name) or _ALIASES.get(name, name)+ profile = layer.registry.get(canonical) or _REGISTRY.get(canonical)# Named custom routes share the generic wire policy unless a plugin# explicitly registered that route. Other names retain exact lookup.if profile is None and isinstance(name, str) and name.lower().startswith("custom:"):@@@ -115,11 -193,8 +197,12 @@@ def routed_model_rejects_vision_tool_medef list_providers() -> list[ProviderProfile]:- """Return all registered provider profiles (one per canonical name)."""+ """Return all registered provider profiles (one per canonical name); the bound home's+ ``$HERMES_HOME`` plugins shadow process-wide profiles of the same name."""+ from agent.safe_worker_policy import safe_worker_enabled++ if safe_worker_enabled():+ return []global _PROVIDER_LIST_CACHEif not _discovered:_discover_providers()@@@ -364,19 -510,13 +518,17 @@@ def _discover_providers() -> NoneOrder:1. Bundled plugins at ``<repo>/plugins/model-providers/<name>/``- 2. User plugins at ``$HERMES_HOME/plugins/model-providers/<name>/``- 2b. Plugins installed by ``hermes plugins install`` at- ``$HERMES_HOME/plugins/<name>/`` that declare ``kind: model-provider``- 3. Legacy per-file modules at ``providers/<name>.py`` (back-compat)+ 2. Legacy per-file modules at ``providers/<name>.py`` (back-compat)Each step imports its plugins, which call ``register_provider()`` at- module-level. Later steps win on name collision.+ module-level. Later steps win on name collision. ``$HERMES_HOME`` plugins are+ per profile home and load through :func:`_home_layer` at lookup time."""+ from agent.safe_worker_policy import safe_worker_enabled++ if safe_worker_enabled():+ return- global _discovered+ global _discovered, _discoveringif _discovered:return_discovered = Truediff --cc tests/cron/conftest.pyindex 70b99b82307,256fff14032..d20ff3034f8--- a/tests/cron/conftest.py+++ b/tests/cron/conftest.py@@@ -75,50 -70,3 +75,53 @@@ def _reset_session_context_vars()_reset_all()yield_reset_all()+++def cron_owner(monkeypatch):+ """Replace only the client transport with the production owner execution seam.++ This is not admission/RPC coverage. Tests requesting it exercise the real+ scheduler under the exact owner-store identity and profile scope.+ """+ from gateway.session_contract import SessionRef+ from gateway.session_cron import current_execution, execute+ from hermes_state_registry import acquire, release++ def run(job, *, extra_prompt=None, cancel_event=None, execution_id=None):+ from cron.scheduler import _get_hermes_home++ db = acquire(_get_hermes_home() / "state.db")+ identity = uuid4().hex+ ref = SessionRef("test-profile", "cron-" + identity)+ db.create_session(ref.session_id, source="cron")+ authority = SimpleNamespace(+ db=db, sessions={ref.session_id: SimpleNamespace(+ source=SimpleNamespace(user_id="cron-owner"))}, pending_results={})+ request_id = execution_id or identity+ row = {"admission_id": identity, "request_id": request_id,+ "principal_id": "cron-owner", "payload": {"text": extra_prompt or ""}}+ policy = SimpleNamespace(request_json=json.dumps({+ "cron_job": job, "extra_prompt": extra_prompt, "request_id": request_id}))++ async def execute_job():+ previous = current_execution()+ try:+ await execute(authority, ref, row, policy)+ except RuntimeError:+ if identity not in authority.pending_results:+ raise+ assert current_execution() is previous+ assert not authority._cron_cancellations- return tuple(authority.pending_results[identity]["result"]["cron_result"])++ saved = authority.pending_results[identity]["result"]++ # The transport carries run-side verdicts back like run_canonical_job's status poll.++ job.update(saved.get("cron_job_flags") or {})++ return tuple(saved["cron_result"])++ try:+ return asyncio.run(execute_job())+ finally:+ release(db)++ monkeypatch.setattr("cron.scheduler_authority.run_canonical_job", run)+ return rundiff --cc tests/cron/test_cleanup_timeout.pyindex 8c5904e44b3,9fcc97b43c1..df982ef0313--- a/tests/cron/test_cleanup_timeout.py+++ b/tests/cron/test_cleanup_timeout.py@@@ -148,14 -132,8 +148,14 @@@ def test_dispatch_guard_releases_after_"next_run_at": "2020-01-01T00:00:00","deliver": "local",}+ from cron import jobs++ def admitted(fired, **kwargs):+ with _owner_execution(fake_db, fired, kwargs.get("execution_id")):+ return run_job(fired, **kwargs)+- sched._parallel_pool = None- sched._parallel_pool_max_workers = None+ sched._parallel_pools.clear()+ sched._parallel_pool_max_workers.clear()sched._running_job_ids.clear()try:@@@ -180,12 -155,9 +180,12 @@@mock_agent_cls.return_value = mock_agentassert sched.tick(verbose=False) == 1+ assert fake_db.entered.is_set()+ assert mock_agent.run_conversation.call_count == 1assert "cleanup-guard-hang" not in sched.get_running_job_ids()assert sched.tick(verbose=False) == 1+ assert mock_agent.run_conversation.call_count == 2finally:release.set()- sched._running_job_ids.discard("cleanup-guard-hang")+ sched._running_job_ids.discard(sched._inflight_key("cleanup-guard-hang"))sched._shutdown_parallel_pool()diff --cc tests/cron/test_cron_bot_chat_delivery.pyindex d92c3c05e2c,41f55c43bca..e3c164de0c2--- a/tests/cron/test_cron_bot_chat_delivery.py+++ b/tests/cron/test_cron_bot_chat_delivery.py@@@ -112,38 -120,281 +112,68 @@@ def test_create_validation_accepts_bare# ── delivery lane ────────────────────────────────────────────────────────────-def _completed(returncode=0, stdout="", stderr=""):- return subprocess.CompletedProcess(args=[], returncode=returncode, stdout=stdout, stderr=stderr)---def test_deliver_runs_canonical_bot_chat_lane():- """The subprocess must use the Bot Mode agent-to-agent chat lane:- chat --in ~ -c "Bot Chat" --create-if-missing -Q --query-file <tmp>."""- calls = {}-- def fake_run(argv, env, report_path, timeout):- calls["argv"], calls["env"], calls["report_path"] = argv, env, report_path- return _completed()-- with mock.patch.object(sched_delivery, "_run_bot_chat_turn", side_effect=fake_run), \- mock.patch.object(sched_delivery.shutil, "which", return_value="/usr/bin/hermes"):- err = _deliver_to_bot_chat({"id": "j1", "name": "Daily digest"}, "the output", "")-- assert err is None- argv = calls["argv"]- # The running install's interpreter, not whatever `hermes` PATH names (same order as /update).- assert argv[:3] == [sys.executable, "-m", "hermes_cli.main"]- assert argv[3:5] == ["-p", "default"] # do not follow active_profile- assert "chat" in argv- assert "Bot Chat" in argv- assert "--create-if-missing" in argv- assert "-Q" in argv- assert "--query-file" in argv- # Message rides a temp file, never inline argv (quote/expansion safety).- assert not any("the output" in str(a) for a in argv)- # The child reports its turn outcome here so the cap bounds the turn, not the exit linger.- assert calls["env"][TURN_REPORT_FILE_ENV] == calls["report_path"]---def test_deliver_failure_returns_error_string():- with mock.patch.object(- sched_delivery, "_run_bot_chat_turn", return_value=_completed(returncode=1, stderr="boom")- ), mock.patch.object(sched_delivery.shutil, "which", return_value="/usr/bin/hermes"):- err = _deliver_to_bot_chat({"id": "j1", "name": "n"}, "out", "")- assert err is not None- assert "boom" in err+def test_deliver_message_carries_cron_attribution(tmp_path, monkeypatch):+ """The admitted turn self-identifies as scheduled output, not the user."""+ from tools import bot_live_delivery as mailbox+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ captured = {}-def test_deliver_failure_reports_both_streams_labeled():- """A failed turn must keep stderr AND stdout, labeled — ``stderr or- stdout`` discarded half the signal (#104056)."""- with mock.patch.object(- sched_delivery, "_run_bot_chat_turn",- return_value=_completed(returncode=1, stdout="banner out", stderr="boom-err"),- ), mock.patch.object(sched_delivery.shutil, "which", return_value="/usr/bin/hermes"):- err = _deliver_to_bot_chat({"id": "j1", "name": "n"}, "out", "")- assert err is not None- assert "stderr: boom-err" in err- assert "stdout: banner out" in err---def test_deliver_failure_banner_only_stdout_names_exit_code_not_banner():- """The reported shape: empty stderr, stdout holding only the resume- banner — the recorded error must say what happened (exit code, banner-only- stdout) instead of echoing the banner as if it were a reason (#104056)."""- banner = ('↻ Resumed session 20260905_121420_8084c7 "Bot Chat" (1 user message, 1 total messages)'- '\n\nsession_id: 20260905_121420_8084c7')- with mock.patch.object(- sched_delivery, "_run_bot_chat_turn",- return_value=_completed(returncode=1, stdout=banner, stderr=""),- ), mock.patch.object(sched_delivery.shutil, "which", return_value="/usr/bin/hermes"):- err = _deliver_to_bot_chat({"id": "j1", "name": "n"}, "out", "")- assert err is not None- assert "exit code 1" in err- assert "stdout was only the resume banner" in err- assert "Resumed session" not in err- assert "stderr:" not in err---def test_deliver_failure_persisted_stdout_tail_is_short_and_redacted():- """``last_delivery_error`` lands in jobs.json / the ledger: the model's- answer on stdout is capped to a short tail and secrets are scrubbed."""- answer = "x" * 5000 + "\nToken: sk-ant-api03-" + "A" * 80 + " done"- with mock.patch.object(- sched_delivery, "_run_bot_chat_turn",- return_value=_completed(returncode=1, stdout=answer, stderr="boom-err"),- ), mock.patch.object(sched_delivery.shutil, "which", return_value="/usr/bin/hermes"):- err = _deliver_to_bot_chat({"id": "j1", "name": "n"}, "out", "")- assert err is not None- stdout_part = err.split("stdout: ", 1)[1]- assert len(stdout_part) <= 200- assert "sk-ant-api03-" + "A" * 80 not in err+ def fake_deliver(home, owner, message, *, delivery_id):+ captured["message"] = message+ return {"status": "settled", "message": message, "delivery_id": delivery_id}+ monkeypatch.setattr(mailbox, "find_canonical_live_owner", lambda home: {"session_id": "local-bot"})+ monkeypatch.setattr(mailbox, "deliver_to_live_owner", fake_deliver)+ assert _deliver_to_bot_chat({"id": "j1", "name": "Daily digest", "execution_id": "r1"}, "the payload", "") is None+ assert 'Cronjob "Daily digest" output' in captured["message"]+ assert "not the user" in captured["message"]+ assert "the payload" in captured["message"]-def test_deliver_timeout_returns_error_string():- with mock.patch.object(- sched_delivery, "_run_bot_chat_turn",- side_effect=subprocess.TimeoutExpired(cmd="hermes", timeout=600),- ), mock.patch.object(sched_delivery.shutil, "which", return_value="/usr/bin/hermes"):- err = _deliver_to_bot_chat({"id": "j1", "name": "n"}, "out", "")- assert err is not None- assert "timed out" in err+def test_deliver_without_authority_is_unverified_not_a_second_writer(tmp_path, monkeypatch):+ """No running authority → explicit unverified status; never a local CLI turn."""+ import subprocess+ from tools import bot_live_delivery as mailbox-def test_deliver_message_carries_cron_attribution(tmp_path):- """The injected turn must self-identify as scheduled output, not the user."""- captured = {}+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setattr(subprocess, "run", mock.Mock(side_effect=AssertionError("no local inference fallback")))+ monkeypatch.setattr(mailbox, "find_canonical_live_owner",+ mock.Mock(side_effect=ValueError("profile authority is not ready")))+ err = _deliver_to_bot_chat({"id": "j1", "name": "n", "execution_id": "r1"}, "out", "")+ assert err is not None and "unverified" in err and "not ready" in err- def fake_run(argv, env, report_path, timeout):- qf = argv[argv.index("--query-file") + 1]- with open(qf, encoding="utf-8") as fh:- captured["message"] = fh.read()- return _completed()- with mock.patch.object(sched_delivery, "_run_bot_chat_turn", side_effect=fake_run), \- mock.patch.object(sched_delivery.shutil, "which", return_value="/usr/bin/hermes"):- _deliver_to_bot_chat({"id": "j1", "name": "Daily digest"}, "the payload", "")++def test_failure_notice_to_a_profile_hiding_warnings_is_suppressed_not_sent(tmp_path, monkeypatch):++ """A ``for_failure`` notice whose TARGET profile hides warning notifications is booked as a++ durable ``suppressed`` disposition (flagged on the job), never admitted to the owner; a++ requested (non-failure) result is never gated."""++ from tools import bot_live_delivery as mailbox+- assert 'Cronjob "Daily digest" output' in captured["message"]- assert "not the user" in captured["message"]- assert "the payload" in captured["message"]++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))++ (tmp_path / "config.yaml").write_text("display: {suppress_warning_notifications: true}\n")++ admitted = []++++ def fake_deliver(home, owner, message, *, delivery_id):++ admitted.append(message)++ return {"status": "queued", "message": message, "delivery_id": delivery_id}++++ monkeypatch.setattr(mailbox, "find_canonical_live_owner", lambda home: {"session_id": "bot"})++ monkeypatch.setattr(mailbox, "deliver_to_live_owner", fake_deliver)+++ failure = {"id": "j1", "name": "n", "execution_id": "r1"}++ assert _deliver_to_bot_chat(failure, "diagnostic", "", for_failure=True) is None++ assert failure["_notification_all_targets_suppressed"] is True++ assert failure["_bot_chat_delivery_receipts"]["bot-chat:(own)"]["status"] == "suppressed"++ assert admitted == []+-_REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(sched_delivery.__file__)))---def _child_env() -> dict:- """The stand-in child imports ``hermes_cli`` from this checkout, like the real ``-m hermes_cli.main``."""- return {**os.environ, "PYTHONPATH": os.pathsep.join(p for p in (_REPO_ROOT, os.environ.get("PYTHONPATH")) if p)}---def test_turn_report_books_the_delivery_while_the_child_still_lingers(tmp_path):- """The cap bounds the TURN: a child that reported its turn and then lingers for a nested- notify_on_complete reply (bounded by oneshot_completion_wait_seconds, default == the cap) is- booked from the report promptly and is NOT killed (#113608)."""- report = tmp_path / "turn.json"- child = textwrap.dedent("""- import os, time- from hermes_cli.quiet_single_query import TURN_REPORT_FILE_ENV, write_turn_report- write_turn_report(os.environ.pop(TURN_REPORT_FILE_ENV), exit_code=0)- time.sleep(30)- """)- procs, real_popen = [], subprocess.Popen-- def spy(*args, **kwargs):- procs.append(real_popen(*args, **kwargs))- return procs[-1]-- started = time.monotonic()- try:- with mock.patch.object(sched_delivery.subprocess, "Popen", side_effect=spy):- result = sched_delivery._run_bot_chat_turn(- [sys.executable, "-c", child], {**_child_env(), TURN_REPORT_FILE_ENV: str(report)}, str(report), timeout=10)- elapsed = time.monotonic() - started- assert result.returncode == 0- assert elapsed < 8, elapsed- assert procs[0].poll() is None, "the lingering child must survive the booking"- finally:- for proc in procs:- proc.kill()- proc.wait(timeout=10)--[email protected]_only-def test_delivery_child_runs_in_the_target_home_not_the_schedulers_cwd(tmp_path, monkeypatch):- """The spawn pins ``cwd`` to the target home: a scheduler left in a reaped kanban scratch- workspace must not hand its dead cwd to the child, which then dies before argv (#102941)."""- home = tmp_path / "home"- home.mkdir()- report = tmp_path / "turn.json"- gone = tmp_path / "scratch"- gone.mkdir()- monkeypatch.chdir(gone)- gone.rmdir()- child = textwrap.dedent("""- import os, sys- from hermes_cli.quiet_single_query import TURN_REPORT_FILE_ENV, write_turn_report- sys.stdout.write(os.getcwd())- write_turn_report(os.environ.pop(TURN_REPORT_FILE_ENV), exit_code=0)- """)- env = {**_child_env(), "HERMES_HOME": str(home), TURN_REPORT_FILE_ENV: str(report)}- result = sched_delivery._run_bot_chat_turn([sys.executable, "-c", child], env, str(report), timeout=30)- assert result.returncode == 0, result.stderr- assert result.stdout.strip() == os.path.realpath(home)---def test_turn_that_never_ends_is_still_killed_at_the_cap(tmp_path):- """Control: with no turn report the cap stays the guard it always was."""- started = time.monotonic()- with pytest.raises(subprocess.TimeoutExpired):- sched_delivery._run_bot_chat_turn(- [sys.executable, "-c", "import time; time.sleep(30)"], _child_env(), str(tmp_path / "turn.json"), timeout=1)- assert time.monotonic() - started < 8--[email protected]_only-def test_bot_chat_turn_keeps_failure_tail_under_non_utf8_parent(tmp_path):- """The gateway parent's locale codec, not the child's UTF-8, decides the decode: a parent- outside UTF-8 mode with a C locale (the Linux twin of the cp1252 gateway parent on Windows)- used to lose the failing child's accented stderr entirely — the drain thread died on the- first undecodable byte and ``_format_failure_streams`` recorded nothing but the exit code- (#115894). Lossy decoding keeps the tail: on POSIX the accented characters degrade to- U+FFFD (the locale default stays, #66566) but the diagnostic text and exit code survive.-- ``PYTHONUTF8=0`` alone is not enough on 3.11 — PEP 538 coerces the C locale to UTF-8, so- the nested parent also sets ``PYTHONCOERCECLOCALE=0`` and asserts it is really ASCII."""- nested = textwrap.dedent("""- import json, locale, os, sys- from cron.scheduler_delivery import _run_bot_chat_turn- child = "import sys; sys.stderr.buffer.write({!r}); sys.exit(3)".format(- bytes.fromhex(sys.argv[1]))- result = _run_bot_chat_turn(- [sys.executable, "-c", child], dict(os.environ), sys.argv[2], timeout=30)- print(json.dumps({"preferred": locale.getpreferredencoding(False),- "returncode": result.returncode, "stderr": result.stderr}))- """)- env = {**_child_env(), "LC_ALL": "C", "LANG": "C", "PYTHONUTF8": "0", "PYTHONCOERCECLOCALE": "0"}- env.pop("PYTHONIOENCODING", None)- tail = "relatório nº 3: falhou\n"- res = subprocess.run(- [sys.executable, "-X", "utf8=0", "-c", nested, tail.encode("utf-8").hex(), str(tmp_path / "turn.json")],- env=env, timeout=60, check=True, capture_output=True, encoding="utf-8")-- result = json.loads(res.stdout)- assert result["preferred"].lower() in ("ansi_x3.4-1968", "ascii", "us-ascii"), result- assert result["returncode"] == 3- assert result["stderr"] == "relat\ufffd\ufffdrio n\ufffd\ufffd 3: falhou\n"--[email protected]_only-def test_bot_chat_turn_failure_tail_decodes_lossily(tmp_path):- """The exit-1 tail is still surfaced (with U+FFFD for the bad byte) instead of- vanishing when the drain thread dies at the first undecodable byte (#105582)."""- child = "import os, sys; os.write(2, b'boom before \\x80 after\\n'); sys.exit(1)"- result = sched_delivery._run_bot_chat_turn(- [sys.executable, "-c", child], _child_env(), str(tmp_path / "turn.json"), timeout=15)-- assert result.returncode == 1- assert result.stderr == "boom before \ufffd after\n"--[email protected]_only-def test_bot_chat_turn_roundtrips_accented_utf8_reply(tmp_path):- """The delivery child writes UTF-8 unconditionally — hermes_cli reconfigures its- own streams via hermes_bootstrap on Windows even under PYTHONIOENCODING=cp1252 —- while the gateway parent there is NOT started in UTF-8 mode, so text=True alone- decoded the pipes with the ANSI code page: the reply came back mojibake'd, or the- reader thread died on bytes undefined in cp1252 and the reply was silently lost- while the delivery still booked as delivered (#115894).-- The gateway parent is a nested interpreter explicitly NOT in UTF-8 mode- (``PYTHONUTF8=0`` / ``-X utf8=0``), so its Popen(text=True) decodes with the- ANSI code page exactly like the production parent; the stand-in child writes- raw UTF-8 bytes through sys.stdout.buffer the way the bootstrapped hermes_cli- child does, independent of any locale. On the pre-fix branch the decode dies- on 0x8D (second byte of UTF-8 "Í", undefined in cp1252) inside the drain- thread and stdout comes back empty — RED; with the win32 UTF-8 pin the text- round-trips byte-for-byte. The JSON verdict rides the nested stdout with- ensure_ascii escapes, so the outer pipe encoding cannot distort it."""- text = "AÇÃO ÍNDICE: relatório nº 3\n"- nested = textwrap.dedent("""- import json, os, sys- from cron.scheduler_delivery import _run_bot_chat_turn- child = "import sys; sys.stdout.buffer.write({!r})".format(sys.argv[1].encode("utf-8"))- result = _run_bot_chat_turn(- [sys.executable, "-c", child], dict(os.environ), sys.argv[2], timeout=30)- print(json.dumps(- {"returncode": result.returncode, "stdout": result.stdout, "stderr": result.stderr}))- """)- env = {**_child_env(), "PYTHONUTF8": "0"}- env.pop("PYTHONIOENCODING", None)- res = subprocess.run(- [sys.executable, "-X", "utf8=0", "-c", nested, text, str(tmp_path / "turn.json")],- env=env, timeout=60, check=True, capture_output=True, encoding="utf-8")-- result = json.loads(res.stdout)- assert result["returncode"] == 0- assert result["stdout"] == text- assert result["stderr"] == ""++ result = {"id": "j1", "name": "n", "execution_id": "r2"}++ outcome = _deliver_to_bot_chat(result, "the report", "")++ assert outcome and "queued" in outcome++ assert not result.get("_notification_all_targets_suppressed")++ assert len(admitted) == 1++# ── delivery-targets listing (UI pickers) ────────────────────────────────────def test_delivery_targets_include_local_profiles():diff --cc tests/cron/test_cron_delivery_redaction.pyindex 00000000000,6e233cff19d..903263631b6mode 000000,100644..100644--- a/tests/cron/test_cron_delivery_redaction.py+++ b/tests/cron/test_cron_delivery_redaction.py@@@ -1,0 -1,123 +1,121 @@@+ """Cron output is secret-redacted on every outward lane, fail-closed.++ Shell-job stdout/stderr is redacted where it is captured, but an LLM cron job's response text+ reaches ``_deliver_result`` unscanned. Every egress lane — platform send, session mirror (payload+ and spliced job name), bot-chat turn — must apply ``redact_sensitive_text(force=True)``: the+ ``security.redact_secrets`` preference governs the user's own logs, not egress, and a raising+ redactor must replace the payload rather than let it through.+ """+ import importlib+ from contextlib import ExitStack+ from unittest.mock import AsyncMock, MagicMock, patch++ import pytest++ # Synthetic vendor-prefixed key, long enough to trip the redactor; never a real credential.+ FAKE_SECRET = "sk-" + "A" * 32+ BODY = "Job finished. 3 tasks done, 1 pending."+++ def _telegram_cfg():+ from gateway.config import Platform++ pconfig = MagicMock()+ pconfig.enabled = True+ cfg = MagicMock()+ cfg.platforms = {Platform.TELEGRAM: pconfig}+ return cfg+++ def _job(name: str = "daily-report") -> dict:+ return {"id": "report-job", "name": name, "deliver": "origin",+ "origin": {"platform": "telegram", "chat_id": "123"}}+++ def _flat(call) -> str:+ return " ".join(str(a) for a in call.args) + " " + " ".join(str(v) for v in call.kwargs.values())+++ def _deliver_platform_and_mirror(job: dict, content: str) -> tuple[str, str]:+ """Drive ``_deliver_result`` with the mirror on; stub only the outermost sinks (the platform+ send and the session write) so the real assembly — including the job-name splice — runs."""+ from cron.scheduler_delivery import _deliver_result++ send = AsyncMock(return_value={"success": True})+ sink = MagicMock(return_value=True)+ with patch("gateway.config.load_gateway_config", return_value=_telegram_cfg()), \+ patch("tools.send_message_tool._send_to_platform", new=send), \+ patch("cron.scheduler_delivery._cron_mirror_delivery_enabled", return_value=True), \+ patch("cron.scheduler_delivery._target_matches_origin", return_value=True), \+ patch("gateway.mirror.mirror_to_session", new=sink), \+ patch("sys.is_finalizing", return_value=False):+ _deliver_result(job, content)+ assert send.called and sink.called, "a sink did not run — assertions would be vacuous"+ return _flat(send.call_args), _flat(sink.call_args)+++ def _deliver_bot_chat(job: dict, content: str) -> str:- """Drive ``_deliver_to_bot_chat`` down to the CLI lane and capture the inbound turn."""++ """Drive ``_deliver_to_bot_chat`` down to the live-owner admission and capture the inbound turn."""+ from cron.scheduler_delivery import _deliver_to_bot_chat++ captured = {}+- def _fake_run(argv, *args, **kwargs):- with open(argv[argv.index("--query-file") + 1], encoding="utf-8") as fh:- captured["message"] = fh.read()- return MagicMock(returncode=0, stdout="", stderr="")-- # The CLI lane is seamed at whichever spawn helper the tree has: ``subprocess.run`` or the- # report-driven ``_run_bot_chat_turn(argv, env, report_path, timeout)`` (#113608); ``create``- # keeps the second patch a no-op where the helper does not exist, so no real child is spawned.- with patch("cron.scheduler_delivery.subprocess.run", side_effect=_fake_run), \- patch("cron.scheduler_delivery._run_bot_chat_turn", create=True, side_effect=_fake_run):- err = _deliver_to_bot_chat(job, content, "")++ def _fake_deliver(home, owner, message, *, delivery_id):++ captured["message"] = message++ return {"status": "settled", "message": message, "delivery_id": delivery_id}++++ # The canonical lane admits the turn to the target profile's live Bot Chat owner; the++ # admission record is the outward seam (no local CLI child is ever spawned).++ with patch("tools.bot_live_delivery.find_canonical_live_owner", return_value={"session_id": "bot"}), \++ patch("tools.bot_live_delivery.deliver_to_live_owner", side_effect=_fake_deliver):++ err = _deliver_to_bot_chat(dict(job, execution_id="r1"), content, "")+ assert err is None, err+ return captured["message"]+++ @pytest.mark.parametrize("lane", ["platform_send", "session_mirror", "bot_chat"])+ def test_every_outward_lane_masks_secret_in_payload_and_job_name(lane):+ """Secret in the body AND in the user-controlled job name is masked on every lane, while+ ordinary text and the lane's own framing survive (no over-redaction, no empty payload)."""+ job = _job(name=f"rotate {FAKE_SECRET} daily")+ content = f"{BODY} Token was {FAKE_SECRET} (oops)."+ if lane == "bot_chat":+ out = _deliver_bot_chat(job, content)+ assert "[Cronjob " in out+ else:+ sent, mirrored = _deliver_platform_and_mirror(job, content)+ out = sent if lane == "platform_send" else mirrored+ if lane == "session_mirror":+ assert "[Cron delivery:" in out, "mirror prefix missing — assembly path not exercised"+ assert "3 tasks done" in out, "payload mangled or empty — secret assertion would be vacuous"+ assert FAKE_SECRET not in out, f"secret reached the {lane} lane"+++ @pytest.mark.parametrize("mode", ["redact_secrets_off", "redactor_raises"])+ def test_delivery_redaction_is_forced_and_fails_closed(mode, monkeypatch):+ """Egress redaction is independent of ``security.redact_secrets`` (force=True) and a raising+ redactor replaces the payload instead of passing the unscanned text through."""+ import agent.redact+ from cron.scheduler_delivery import _deliver_result++ send = AsyncMock(return_value={"success": True})+ try:+ with ExitStack() as stack:+ stack.enter_context(patch("gateway.config.load_gateway_config", return_value=_telegram_cfg()))+ stack.enter_context(patch("tools.send_message_tool._send_to_platform", new=send))+ stack.enter_context(patch("sys.is_finalizing", return_value=False))+ if mode == "redact_secrets_off":+ monkeypatch.setenv("HERMES_REDACT_SECRETS", "false")+ importlib.reload(agent.redact)+ else:+ stack.enter_context(+ patch("agent.redact.redact_sensitive_text", side_effect=RuntimeError("boom")))+ _deliver_result(_job(), f"Token was {FAKE_SECRET}")+ finally:+ monkeypatch.delenv("HERMES_REDACT_SECRETS", raising=False)+ importlib.reload(agent.redact)++ delivered = _flat(send.call_args)+ assert FAKE_SECRET not in delivered, f"{mode}: secret reached the platform send"+ if mode == "redactor_raises":+ assert "REDACTED" in delivereddiff --cc tests/cron/test_cron_failure_deliver.pyindex 9409f9bc46a,da2dbbce57e..560367c32e2--- a/tests/cron/test_cron_failure_deliver.py+++ b/tests/cron/test_cron_failure_deliver.py@@@ -395,17 -372,15 +395,17 @@@ class TestOutcomeBookkeepingassert run_env["send"] == []assert self._outcome(run_env) == "suppressed"+ assert s.drain_delivery_queue(adapters={}, loop=None) == 0assert alerted == [], "silenced failure must NOT mark incident alerted"+ @pytest.mark.parametrize("transport_success", [True, False])def test_fd_explicit_target_failure_records_delivered(- self, run_env, monkeypatch+ self, run_env, monkeypatch, transport_success):"""deliver=origin (unresolvable) + failure_deliver=explicit target:- the notice IS delivered — outcome must say so, not 'not_configured'."""+ the notice is queued then delivered, never 'not_configured'."""alerted = []- monkeypatch.setattr(s, "_mark_incident_alerted", alerted.append)+ monkeypatch.setattr(s, "_mark_incident_alerted", lambda incident_id, execution_id=None: alerted.append(incident_id))monkeypatch.setattr(s, "_upsert_incident_for_failure", lambda *_a, **_kw: (False, "inc-b1"))diff --cc tests/cron/test_cron_incidents.pyindex 039d372521f,a1fb0669573..e4b1d03e426--- a/tests/cron/test_cron_incidents.py+++ b/tests/cron/test_cron_incidents.py@@@ -40,18 -42,15 +42,22 @@@ def _job(**overrides)return job--def _tick_failing(job, tmp_path, deliveries, error="boom unrelated"):++def _tick_failing(job, tmp_path, deliveries, error="boom unrelated", *, settle=False):"""Run one run_one_job tick whose agent raises ``error`` (the failurepath that composes the per-run failure ping). Mirrors the preflight alert-once-- harness so the incident gating is exercised through the real scheduler."""- fake_db = MagicMock()++ harness so the incident gating is exercised through the real scheduler.++ ``settle=True`` emulates the durable queue's drain, which marks the incident++ alerted once the ping has left the process (``drain_delivery_queue.send``)."""- def fake_deliver(jb, content, adapters=None, loop=None, **kwargs):+ (tmp_path / "config.yaml").write_text(+ "platforms:\n slack:\n enabled: true\n token: xoxb-test\n"+ )++ def fake_deliver(execution_id, jb, content, **kwargs):deliveries.append(content)- return None++ if settle and kwargs.get("for_failure"):++ sched._mark_incident_alerted(jb.get("_failure_incident_id"))+ return {"status": "pending"}with cron_jobs.use_cron_store(tmp_path), \patch("cron.scheduler._hermes_home", tmp_path), \@@@ -225,22 -224,42 +231,40 @@@ def test_missing_db_no_crash(monkeypatc# ── Scheduler gating ───────────────────────────────────────────────────────- def test_unacked_failure_still_alerts(monkeypatch, tmp_path, cron_owner):-def test_repeat_failure_alerts_once_then_reminds_after_cooldown(monkeypatch, tmp_path):++def test_repeat_failure_alerts_once_then_reminds_after_cooldown(monkeypatch, tmp_path, cron_owner):+ """Same job + same error: the first failing run delivers, the repeat is withheld (but still+ recorded as a run), one reminder goes out once ``cron.failure_repeat_alert_hours`` has+ elapsed, and a green run re-arms the signature so the same error alerts again."""inc = _point_db(monkeypatch, tmp_path)deliveries = []+ # A real (non-local) lane: the ping leaves the process, so the incident is marked alerted.- job = _job(deliver="telegram:123")- (tmp_path / "config.yaml").write_text("cron:\n preflight: false\n", encoding="utf-8")- monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ job = _job()with cron_jobs.use_cron_store(tmp_path):cron_jobs.save_jobs([job])- _tick_failing(job, tmp_path, deliveries, error="unacked boom")- _tick_failing(job, tmp_path, deliveries, error="unacked boom")- _tick_failing(job, tmp_path, deliveries, error="repeat boom")- _tick_failing(job, tmp_path, deliveries, error="repeat boom")++ _tick_failing(job, tmp_path, deliveries, error="repeat boom", settle=True)++ _tick_failing(job, tmp_path, deliveries, error="repeat boom", settle=True)+ assert len(deliveries) == 1, "an alerted signature must not re-ping on every run"+ rows = inc.list_incidents()+ assert len(rows) == 1 and rows[0]["state"] == "alerted" and rows[0]["alerted_at"]+ stored = [j for j in cron_jobs.load_jobs() if j["id"] == job["id"]][0]+ assert stored["last_status"] == "error", "the withheld run is still recorded"++ # Cooldown elapsed: exactly one reminder, then silent again.+ stale = (_hermes_now() - timedelta(hours=7)).isoformat()+ with inc._transaction() as conn:+ conn.execute("UPDATE cron_incidents SET alerted_at=?", (stale,))- _tick_failing(job, tmp_path, deliveries, error="repeat boom")- _tick_failing(job, tmp_path, deliveries, error="repeat boom")++ _tick_failing(job, tmp_path, deliveries, error="repeat boom", settle=True)++ _tick_failing(job, tmp_path, deliveries, error="repeat boom", settle=True)+ assert len(deliveries) == 2, "one reminder after the cooldown, not one per run"- assert len(deliveries) == 2, "unacked failures must keep alerting per run"- rows = inc.list_incidents()- assert len(rows) == 1- assert rows[0]["state"] == "detected"+ # Recovery re-arms: the same error after a green run alerts immediately.+ sched._resolve_incidents_for_recovered_job(job)- _tick_failing(job, tmp_path, deliveries, error="repeat boom")++ _tick_failing(job, tmp_path, deliveries, error="repeat boom", settle=True)+ assert len(deliveries) == 3+ assert inc.count_incidents() == 1-def test_ack_suppresses_alert_until_signature_changes(monkeypatch, tmp_path):+def test_ack_suppresses_alert_until_signature_changes(monkeypatch, tmp_path, cron_owner):inc = _point_db(monkeypatch, tmp_path)deliveries = []job = _job()diff --cc tests/cron/test_cron_kanban_env_isolation.pyindex d2b7cbb5dc2,a177de98057..48119f1d84d--- a/tests/cron/test_cron_kanban_env_isolation.py+++ b/tests/cron/test_cron_kanban_env_isolation.py@@@ -404,20 -400,23 +404,26 @@@ def test_dispatcher_grants_only_the_assroot = str(Path(__file__).resolve().parents[2])worker.write_text(f"#!{sys.executable}\nimport sys, os, json;sys.path.insert(0, {root!r})\n"- "from tools.kanban_tools import _handle_complete\n"- f"result=_handle_complete({{'summary':'assigned worker'}});open({str(output)!r}, 'w').write(result)\n"+ "from tools.kanban_tools import _handle_complete, heartbeat_current_worker_from_env\n"+ "beat=heartbeat_current_worker_from_env()\n"+ f"result=json.loads(_handle_complete({{'summary':'assigned worker'}}));result['beat']=beat\n"+ f"open({str(output)!r}, 'w').write(json.dumps(result))\n")worker.chmod(0o700)- monkeypatch.setenv("HERMES_BIN", str(worker))+ # Observe the real spawn grant without launching an owner or inference.+ monkeypatch.setattr("hermes_cli.kanban_db_dispatch._worker_argv",+ lambda *_args: [sys.executable, str(worker)])# Building a new worker under an existing task must replace, not inherit, its scope.monkeypatch.setenv("HERMES_KANBAN_TASK", "prior-task")+ # A dispatcher launched from an agent's shell carries the descendant fence itself; the worker it+ # grants a task to must not (an inherited marker fences the worker's own heartbeat + handoff).+ monkeypatch.setenv("HERMES_DELEGATED_CHILD_CONTEXT", str(tmp_path))pid = _default_spawn(task, str(tmp_path), board="default")assert pid is not None- os.waitpid(pid, 0) # windows-footgun: ok — Linux-only real dispatcher spawn+ _, status = os.waitpid(pid, 0) # windows-footgun: ok — Linux-only real dispatcher spawn+ assert os.waitstatus_to_exitcode(status) == 0- assert json.loads(output.read_text())["ok"]+ result = json.loads(output.read_text())+ assert result["ok"] and result["beat"] is True, resultassert kb.get_task(conn, tid).status == "done"assert os.environ["HERMES_KANBAN_TASK"] == "prior-task"conn.close()diff --cc tests/cron/test_cron_mcp_toolset_empty_block.pyindex 7d186ffd3e1,3352868b387..461a3233065--- a/tests/cron/test_cron_mcp_toolset_empty_block.py+++ b/tests/cron/test_cron_mcp_toolset_empty_block.py@@@ -7,9 -7,6 +7,10 @@@ discovering profile's registry overlayfrom __future__ import annotations+import asyncio+import json++from pathlib import Path+from types import SimpleNamespacefrom unittest.mock import MagicMock, patchimport cron.jobs as cron_jobs@@@ -130,3 -90,94 +131,100 @@@ def test_requested_mcp_server_with_toolassert agent_built is Trueassert success is True and error is None++-def _park_notion(*, ever_connected: bool, park_reason=None):++def _park_notion(home, *, ever_connected: bool, park_reason=None):+ """Install a sessionless ``notion`` run task (tools deregistered, alias still global) the way+ the MCP layer leaves a degraded/parked server; ``ever_connected`` separates a server that+ worked in this process and lost its network from one that never came up here, and- ``park_reason`` is what ``_park`` recorded (permanent-error parks are not recovering)."""++ ``park_reason`` is what ``_park`` recorded (permanent-error parks are not recovering).++ The connection is keyed the way the owner bridge resolves it: cron turns run inside++ ``_profile_runtime_scope(home)``, so the served profile's overlay owns the key."""+ import tools.mcp_tool as core++ from tools.mcp_tool_scope import _resolve_server_key+ from tools.registry import registry++ from gateway.run import _profile_runtime_scope++ server = core.MCPServerTask("notion")+ server._ever_connected = ever_connected+ server._park_reason = park_reason+ registry.register_toolset_alias("notion", "mcp-notion")- core._servers["notion"] = server- return lambda: core._servers.pop("notion", None)++ with _profile_runtime_scope(Path(home).resolve()):++ key = _resolve_server_key("notion")++ core._servers[key] = server++ return lambda: core._servers.pop(key, None)+++ def test_requested_mcp_server_reconnecting_runs_without_its_tools(tmp_path):+ """A server that connected in this process and is parked/self-probing after a network blip+ is recoverable: the job runs with the tools that did resolve instead of blocking (#112871)."""- undo = _park_notion(ever_connected=True)++ undo = _park_notion(tmp_path, ever_connected=True)+ try:+ (success, _output, _final, error), agent_built = _run(+ _job(enabled_toolsets=["terminal", "notion"]), tmp_path)+ finally:+ undo()++ assert agent_built is True+ assert success is True and error is None+++ def test_requested_mcp_server_never_connected_still_blocks(tmp_path):+ """A parked server that never connected here (bad URL, wrong credentials) keeps the block."""- undo = _park_notion(ever_connected=False)++ undo = _park_notion(tmp_path, ever_connected=False)+ try:+ (success, _output, _final, error), agent_built = _run(+ _job(enabled_toolsets=["terminal", "notion"]), tmp_path)+ finally:+ undo()++ assert agent_built is False+ assert success is False+ assert error is not None and "[blocked_config]" in error and "notion" in error+++ def test_requested_mcp_server_parked_on_permanent_error_blocks(tmp_path):+ """A server that connected once and then parked on a PERMANENT error (revoked credentials,+ endpoint gone) is not recovering: its self-probe fails identically every time, so the job must+ take the one-shot blocked_config path instead of silently running tool-less forever."""- undo = _park_notion(ever_connected=True, park_reason="from parked state (permanent error)")++ undo = _park_notion(tmp_path, ever_connected=True, park_reason="from parked state (permanent error)")+ try:+ (success, _output, _final, error), agent_built = _run(+ _job(enabled_toolsets=["terminal", "notion"]), tmp_path)+ finally:+ undo()++ assert agent_built is False+ assert success is False+ assert error is not None and "[blocked_config]" in error and "notion" in error+++ def test_reconnecting_warning_is_once_per_job_and_server_per_outage(tmp_path, caplog):+ """The reconnecting exemption warns once per job+server while the outage lasts (not every+ tick) and warns again once the server recovered and dropped out a second time."""+ import logging++ import cron.scheduler_preflight as preflight++ preflight._RECONNECTING_WARNED.clear()+ job = _job(enabled_toolsets=["terminal", "notion"])- undo = _park_notion(ever_connected=True)++ undo = _park_notion(tmp_path, ever_connected=True)+ try:+ with caplog.at_level(logging.WARNING, logger="cron.scheduler_preflight"):+ _run(job, tmp_path)+ _run(job, tmp_path)+ warned = [r for r in caplog.records if "are reconnecting" in r.getMessage()]+ assert len(warned) == 1+ # Server back: the dedupe entry drops, so the next outage warns again.+ _register = _register_notion_in_scope(None)+ try:+ _run(job, tmp_path)+ finally:+ _register()+ assert ("mcpjob", "notion") not in preflight._RECONNECTING_WARNED+ _run(job, tmp_path)+ warned = [r for r in caplog.records if "are reconnecting" in r.getMessage()]+ assert len(warned) == 2+ finally:+ undo()+ preflight._RECONNECTING_WARNED.clear()diff --cc tests/cron/test_cron_pre_agent_fallback_notice.pyindex 00000000000,eb1a1e046f6..0ef9bd4ff76mode 000000,100644..100644--- a/tests/cron/test_cron_pre_agent_fallback_notice.py+++ b/tests/cron/test_cron_pre_agent_fallback_notice.py@@@ -1,0 -1,55 +1,58 @@@+ """A cron job whose primary provider failed credential resolution and ran on a fallback entry must say+ so in the delivered report (#74349): the cron agent has no status rail, so the pre-agent switch would+ otherwise live only in the scheduler log. Drives the real ``run_job`` path with AIAgent and+ ``resolve_runtime_provider`` mocked."""+ from unittest.mock import MagicMock, patch+-from cron.scheduler import run_job+ from hermes_cli.auth import AuthError++from tests.cron.test_scheduler import _run_owned_job++ _JOB = {"id": "fb-test", "name": "fb test", "prompt": "hello", "model": None, "provider": None,+ "provider_snapshot": None, "base_url": None}+++ def _run(tmp_path, *, response: str, primary_fails: bool):+ (tmp_path / "config.yaml").write_text(+ "model:\n default: gpt-5.6-sol\n provider: openai-codex\n"+ "fallback_providers:\n - provider: anthropic\n model: claude-sonnet-5\n api_key: fb-key\n")+++ fake_db = MagicMock()+++ def _resolve(**kwargs):+ # An unpinned job resolves the primary with requested=None (persisted config); only the+ # fallback entry names its provider explicitly.+ if primary_fails and kwargs.get("requested") != "anthropic":+ raise AuthError("expired")+ return {"api_key": "k", "base_url": "https://example.invalid/v1",+ "provider": kwargs.get("requested") or "openai-codex", "api_mode": "chat_completions"}++ with patch("cron.scheduler._hermes_home", tmp_path), \+ patch("cron.scheduler._get_hermes_home", return_value=tmp_path), \+ patch("cron.scheduler_delivery._resolve_origin", return_value=None), \+ patch("hermes_cli.env_loader.load_hermes_dotenv"), \+ patch("hermes_cli.env_loader.reset_secret_source_cache"), \- patch("hermes_state_registry.acquire", return_value=MagicMock()), \++ patch("hermes_state_registry.acquire", return_value=fake_db), \+ patch("hermes_cli.runtime_provider.resolve_runtime_provider", side_effect=_resolve), \+ patch("run_agent.AIAgent") as agent_cls:+ agent_cls.return_value.run_conversation.return_value = {"final_response": response}- success, _output, final, error = run_job(dict(_JOB))++ # Cron turns execute inside the gateway owner: drive the production owner bridge.++ success, _output, final, error = _run_owned_job(dict(_JOB), tmp_path, fake_db)+ return success, final, error, agent_cls.call_args.kwargs+++ def test_fallback_run_prepends_the_switch_notice_to_the_delivered_report(tmp_path):+ success, final, error, agent_kwargs = _run(tmp_path, response="Morning brief: all green.", primary_fails=True)+ assert (success, error) == (True, None)+ assert agent_kwargs["provider"] == "anthropic" and agent_kwargs["model"] == "claude-sonnet-5"+ assert "_fallback_notice" not in agent_kwargs+ first, _, rest = final.partition("\n\n")+ assert "openai-codex/gpt-5.6-sol" in first and "anthropic/claude-sonnet-5" in first+ assert rest == "Morning brief: all green."+++ def test_primary_run_and_silent_fallback_run_are_untouched(tmp_path):+ _s, final, _e, _k = _run(tmp_path, response="Morning brief: all green.", primary_fails=False)+ assert final == "Morning brief: all green."+ # [SILENT] keeps its whole-response contract so the delivery stays suppressed.+ _s, final, _e, _k = _run(tmp_path, response="[SILENT]", primary_fails=True)+ assert final == "[SILENT]"diff --cc tests/cron/test_cron_provider_pin.pyindex 1a9056191d7,dcab5bfb46f..e48f689a41b--- a/tests/cron/test_cron_provider_pin.py+++ b/tests/cron/test_cron_provider_pin.py@@@ -1,27 -1,18 +1,21 @@@- """Unpinned cron jobs run on their creation snapshot (#44585 follow-up).+ """Unpinned cron jobs run on the main agent model at fire time; ``pinned`` locks it.- Background: an UNPINNED cron job used to follow the live global default provider/model. A- temporary switch to a paid provider made every unpinned job silently inherit it on its next- tick (the $7.73 incident). The first fix failed closed on any drift, which instead killed every- unpinned job whenever the operator changed models — silently, for days.-- Current contract:- - create_job() snapshots the provider/model resolution WOULD pick at creation into- job["provider_snapshot"] / job["model_snapshot"] (unpinned, agent-backed jobs only).- - run_job() treats the snapshot as the effective pin: an unpinned axis runs on its snapshot- even after the global default moved. Explicit per-job pins and the cron.model /- cron.model_provider fleet defaults still win; a job with no snapshot follows the global- default as before.+ Contract:+ - run_job() resolves per-job pin > cron.model / cron.model_provider > the main agent model+ (config ``model:``). There is no creation-time snapshot axis any more: a record that still+ carries legacy ``provider_snapshot`` / ``model_snapshot`` keys follows the main model.+ - create_job(pinned=True) / update_job({"pinned": True}) lock the CURRENT main provider+model+ onto the job as an ordinary per-job pin; ``pinned=False`` releases both.These tests exercise the full run_job path (real imports, mocked AIAgent +- resolve_runtime_provider against a temp HERMES_HOME) and the create_job snapshot capture.+ resolve_runtime_provider against a temp HERMES_HOME) and the job-store pin helpers."""+import asyncio+import jsonimport sysfrom pathlib import Path+from types import SimpleNamespacefrom unittest.mock import MagicMock, patch# Ensure project root is importable.diff --cc tests/cron/test_fire_claim_lost_after_delivery.pyindex 00000000000,9d913dbbf8f..61400f5ddecmode 000000,100644..100644--- a/tests/cron/test_fire_claim_lost_after_delivery.py+++ b/tests/cron/test_fire_claim_lost_after_delivery.py@@@ -1,0 -1,251 +1,256 @@@+ """#105861 / #113357: a fire-claim that only *reads* as lost must not overwrite a completed run's+ terminal status — an ok, or a failure notice carrying its real error.++ `_FireOwnership.lost()` samples the claim from the store once. When that sample misses after+ the notice already reached the channel, the run must fall through to the owner-fenced terminal+ write in `_finish_completed_run` (the authoritative claim check) instead of recording an error.++ These drive the real store (``jobs.json`` under a temp HERMES_HOME) so the assertion is the+ actual on-disk ``last_status`` the health watchdog reads, not a mock's call list.+ """++ import threading+ import time++ import pytest+++ @pytest.fixture+ def temp_home(tmp_path, monkeypatch):+ """Isolated HERMES_HOME so jobs.json/executions don't touch the real store."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ return tmp_path+++ @pytest.fixture(autouse=True)+ def _clean_running_state():+ import cron.scheduler as sched++ sched._running_job_ids.clear()+ sched._running_fire_owners.clear()+ sched._interrupted_job_ids.clear()+ yield+ sched._running_job_ids.clear()+ sched._running_fire_owners.clear()+ sched._interrupted_job_ids.clear()+++ class _SampledHeartbeat:+ """The real ``heartbeat_fire_claim``, with exactly ONE armed sample missing."""++ def __init__(self, real, samples_before_miss: int):+ self._real = real+ self._samples_before_miss = samples_before_miss+ self._armed = False+ self._seen = 0+ self.missed = 0++ def __call__(self, job_id, *, expected_owner):+ if self._armed:+ self._seen += 1+ if self._seen > self._samples_before_miss:+ self._armed = False+ self.missed += 1+ return False+ return self._real(job_id, expected_owner=expected_owner)++ def arm(self):+ """Answer ``samples_before_miss`` samples truthfully from here on, then miss once."""+ self._seen = 0+ self._armed = True+++ def _claimed_job():+ """A real recurring job record holding a live fire claim (as a firing tick has)."""+ from cron.jobs import claim_job_for_fire, create_job, get_job+- job = create_job(prompt="x", schedule="every 5m", name="105861")++ # A real (non-local) lane: on this branch agent-job delivery rides the durable queue++ # (``cron.delivery_queue.enqueue``), which is the seam every probe below observes.++ job = create_job(prompt="x", schedule="every 5m", name="105861", deliver="telegram")+ assert claim_job_for_fire(job["id"]) is True+ job = get_job(job["id"])+ assert isinstance(job.get("fire_claim"), dict) and job["fire_claim"].get("by")+ return job+++ def _drive(monkeypatch, *, run_result, samples_before_miss):+ """Run one job through run_one_job with the sampled-heartbeat harness.++ After ``run_job`` returns the claim is sampled once (the pre-delivery check), once again just+ before the delivery side effect, and once after it (the post-delivery check that the incidents+ tripped on). ``samples_before_miss=2`` therefore makes the third, post-delivery sample miss.+ """+ import cron.scheduler as sched++ job = _claimed_job()+ hb = _SampledHeartbeat(sched.heartbeat_fire_claim, samples_before_miss=samples_before_miss)+ delivered = []++ def fake_run_job(job, **kwargs):+ hb.arm()+ return run_result+- def fake_deliver(job, content, **kwargs):++ def fake_deliver(execution_id, job, content, **kwargs):+ delivered.append(content)- return None++ return {"status": "pending"}++ monkeypatch.setattr(sched, "heartbeat_fire_claim", hb)+ monkeypatch.setattr(sched, "run_job", fake_run_job)- monkeypatch.setattr(sched, "_deliver_result", fake_deliver)++ monkeypatch.setattr("cron.delivery_queue.enqueue", fake_deliver)+ return sched, job, hb, delivered+++ _REAL_ERROR = "the real error text the failure path recorded"+++ @pytest.mark.parametrize(+ "success, run_result, expected_status, expected_error",+ [- (True, (True, "output text", "the report", None), "ok", None),++ # A queued (durable-queue) success books ``delivery_queued`` until the gateway drains it.++ (True, (True, "output text", "the report", None), "delivery_queued", None),+ (False, (False, "output text", "", _REAL_ERROR), "error", _REAL_ERROR),+ ],+ ids=["delivered-ok", "delivered-failure-notice"],+ )+ def test_delivered_run_keeps_its_terminal_status_when_claim_sample_misses_after_delivery(+ temp_home, monkeypatch, success, run_result, expected_status, expected_error,+ ):+ """Delivery completed, then the claim sample missed → the on-disk record is the delivered+ run's real outcome (ok, or the real error — never ``_OWNERSHIP_LOST_INTERRUPTED``), and the+ loss latch stays on the raw source: the caller's idle transport event is left unset."""+ from cron.jobs import get_job++ sched, job, hb, delivered = _drive(monkeypatch, run_result=run_result, samples_before_miss=2)+ cancel = threading.Event()++ assert sched.run_one_job(job, cancel_event=cancel) is True++ assert len(delivered) == 1, "the notice must have left the process"+ if success:+ assert delivered == ["the report"]+ else:+ assert "failed" in delivered[0], "the failure notice, not the (empty) report, was delivered"+ assert hb.missed == 1, "exactly the post-delivery sample missed"+ assert cancel.is_set() is False, "the run's loss latch must not cancel the caller's transport"+ record = get_job(job["id"])+ assert record["last_status"] == expected_status+ assert record["last_error"] == expected_error+ assert record["last_error"] != sched._OWNERSHIP_LOST_INTERRUPTED+ assert record["failure_streak"] == (0 if success else 1)+++ def test_transport_cancel_during_delivery_stays_fail_closed(temp_home, monkeypatch):+ """An explicit transport cancel during delivery is not a sampled miss → still interrupted."""+ from cron.jobs import get_job++ sched, job, hb, delivered = _drive(+ monkeypatch, run_result=(True, "output text", "the report", None),+ samples_before_miss=99)+ cancel = threading.Event()- deliver_result = sched._deliver_result++ from cron import delivery_queue++ enqueue = delivery_queue.enqueue+- def deliver_then_cancel(job, content, **kwargs):- outcome = deliver_result(job, content, **kwargs)++ def deliver_then_cancel(execution_id, job, content, **kwargs):++ outcome = enqueue(execution_id, job, content, **kwargs)+ cancel.set()+ return outcome+- monkeypatch.setattr(sched, "_deliver_result", deliver_then_cancel)++ monkeypatch.setattr("cron.delivery_queue.enqueue", deliver_then_cancel)++ assert sched.run_one_job(job, cancel_event=cancel) is True++ assert delivered == ["the report"], "the notice had already left the process"+ assert hb.missed == 0, "the sampled claim never missed — only the transport event fired"+ record = get_job(job["id"])+ assert record["last_status"] == "error"+ assert record["last_error"] == sched._OWNERSHIP_LOST_INTERRUPTED+++ class _HeartbeatThreadMisses:+ """The real ``heartbeat_fire_claim``; the first ``misses`` samples taken on the heartbeat+ thread return False (optionally re-owning the stored claim so the loss is genuine)."""++ def __init__(self, real, misses: int, *, steal: bool = False):+ self._real, self._left, self._steal = real, misses, steal+ self.missed = 0++ def __call__(self, job_id, *, expected_owner):+ if threading.current_thread().name == "cron-fire-claim-heartbeat" and self._left:+ self._left -= 1+ self.missed += 1+ if self._steal:+ from cron.jobs import _with_job, save_jobs++ def re_own(jobs, _i, job):+ job["fire_claim"] = {**job["fire_claim"], "by": "replacement:deadbeef"}+ save_jobs(jobs)++ _with_job(job_id, re_own)+ return False+ return self._real(job_id, expected_owner=expected_owner)+++ def _drive_heartbeat_thread(monkeypatch, *, misses, steal=False):+ """run_one_job with the REAL fire-claim heartbeat thread sampling every 10 ms; ``run_job``+ finishes with a complete response once the heartbeat has taken its armed samples."""+ import cron.scheduler as sched++ job = _claimed_job()+ hb = _HeartbeatThreadMisses(sched.heartbeat_fire_claim, misses, steal=steal)+ delivered, run_cancel = [], []++ def fake_run_job(job, **kwargs):+ deadline = time.monotonic() + 5+ while hb.missed < misses and time.monotonic() < deadline:+ time.sleep(0.01)+ time.sleep(0.1) # let the heartbeat's confirm sample land+ run_cancel.append(kwargs["cancel_event"].is_set())+ return True, "output text", "the report", None++ monkeypatch.setattr(sched, "_RUN_CLAIM_HEARTBEAT_SECONDS", 0.01)+ monkeypatch.setattr(sched, "_FIRE_CLAIM_MISS_CONFIRM_SECONDS", 0.01, raising=False)+ monkeypatch.setattr(sched, "heartbeat_fire_claim", hb)+ monkeypatch.setattr(sched, "run_job", fake_run_job)- monkeypatch.setattr(sched, "_deliver_result", lambda job, content, **kw: delivered.append(content))++ monkeypatch.setattr("cron.delivery_queue.enqueue",++ lambda execution_id, job, content, **kw: (delivered.append(content), {"status": "pending"})[1])+ return sched, job, hb, delivered, run_cancel+++ @pytest.mark.parametrize("misses, latched", [(1, False), (2, True)], ids=["one-sample", "latched"])+ def test_heartbeat_miss_mid_run_keeps_completed_run(temp_home, monkeypatch, misses, latched):+ """#113357: the heartbeat thread's miss is a sample, not the verdict. One miss is re-sampled+ and never cancels the run; two consecutive misses latch, but a claim the store still validates+ at completion records the completed run — not ``_OWNERSHIP_LOST_INTERRUPTED``."""+ from cron.executions import get_execution+ from cron.jobs import get_job++ sched, job, hb, delivered, run_cancel = _drive_heartbeat_thread(monkeypatch, misses=misses)++ assert sched.run_one_job(job) is True++ assert hb.missed == misses+ assert run_cancel == [latched], "only a confirmed miss reaches the run's cancel event"+ assert delivered == ["the report"]+ record = get_job(job["id"])- assert record["last_status"] == "ok"++ assert record["last_status"] == "delivery_queued" # queued success, never the interrupted error+ assert record["last_error"] is None+ assert get_execution(job["execution_id"])["status"] == "completed"+++ def test_confirmed_claim_loss_mid_run_still_yields(temp_home, monkeypatch):+ """A genuinely re-owned claim (two misses, stored ``by`` rewritten) still fences the run out:+ nothing delivered, no terminal write over the new owner, ledger records the discard."""+ from cron.executions import get_execution+ from cron.jobs import get_job++ sched, job, hb, delivered, run_cancel = _drive_heartbeat_thread(+ monkeypatch, misses=2, steal=True)++ assert sched.run_one_job(job) is True++ assert run_cancel == [True]+ assert delivered == []+ record = get_job(job["id"])+ assert record["last_status"] is None+ assert record["fire_claim"]["by"] == "replacement:deadbeef"+ assert "discarded" in get_execution(job["execution_id"])["error"]diff --cc tests/cron/test_quota_hold.pyindex 00000000000,73fbe91edde..bda57efe9f7mode 000000,100644..100644--- a/tests/cron/test_quota_hold.py+++ b/tests/cron/test_quota_hold.py@@@ -1,0 -1,115 +1,119 @@@+ """Provider quota windows park a cron job instead of re-firing into them (#89376).++ Contract (cron/quota_hold.py): a failed run whose cause is a rate-limited ``AuthError`` with a+ ``retry after <N>s`` hint parks a recurring job's ``next_run_at`` past the window and stamps+ ``quota_hold_until``; the stale-error re-arm leaves a held job alone; a run that reaches the+ model clears the marker. The hint is read only from the AuthError in the cause chain, never from+ arbitrary failure text.+ """++ from datetime import datetime, timedelta, timezone+ from unittest.mock import MagicMock, patch++ import pytest++ import cron.scheduler as sched+ from cron import quota_hold as qh+ from cron.jobs import (+ _job_is_stale_error_recurring, create_job, get_due_jobs, get_job, mark_job_run, update_job,+ )+ from hermes_cli.auth import CODEX_RATE_LIMITED_CODE, AuthError++ QUOTA_MSG = "Codex provider quota exhausted (429); retry after 123518s. Credentials are still valid."+++ @pytest.fixture+ def tmp_cron_home(tmp_path, monkeypatch):+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ return home+++ def _quota_error() -> AuthError:+ return AuthError(QUOTA_MSG, provider="openai-codex", code=CODEX_RATE_LIMITED_CODE)+++ def test_hold_seconds_only_from_rate_limited_auth_error_in_cause_chain():+ """The scheduler wraps the resolve failure in a RuntimeError ``from`` the AuthError; the+ hint survives through the cause chain, and text alone (or a re-login AuthError) never+ parks a job."""+ try:+ raise RuntimeError(QUOTA_MSG) from _quota_error()+ except RuntimeError as wrapped:+ assert qh.hold_seconds_from_failure(wrapped) == 123518.0++ assert qh.hold_seconds_from_failure(RuntimeError(QUOTA_MSG)) is None+ assert qh.hold_seconds_from_failure(RuntimeError("HTTP 429: retry after 60s")) is None+ relogin = AuthError(QUOTA_MSG, provider="openai-codex", code="expired", relogin_required=True)+ assert qh.hold_seconds_from_failure(relogin) is None+ structured = AuthError("quota", code=CODEX_RATE_LIMITED_CODE, retry_after=900)+ assert qh.hold_seconds_from_failure(structured) == 900.0+++ def _raise_quota(**_kw):+ raise _quota_error()+++ def _tick(job, home, deliveries, resolve):+ """One real scheduler tick (preflight ON) with the provider resolver replaced by *resolve*."""+ with patch("cron.scheduler._hermes_home", home), \+ patch("cron.scheduler_delivery._resolve_origin", return_value=None), \+ patch("hermes_cli.env_loader.load_hermes_dotenv"), \+ patch("hermes_cli.env_loader.reset_secret_source_cache"), \+ patch("hermes_state_registry.acquire", return_value=MagicMock()), \+ patch("tools.mcp_tool_discovery.discover_mcp_tools", return_value=[]), \+ patch("hermes_cli.runtime_provider.resolve_runtime_provider", side_effect=resolve), \- patch.object(sched, "_deliver_result",- side_effect=lambda jb, content, **kw: deliveries.append(content)), \++ patch("cron.delivery_queue.enqueue",++ side_effect=lambda execution_id, jb, content, **kw: (++ deliveries.append(content), {"status": "pending"})[1]), \+ patch("run_agent.AIAgent") as agent_cls:+ agent_cls.return_value.run_conversation.side_effect = RuntimeError("model said no")+ sched.run_one_job(dict(job))++-def test_quota_hold_parks_past_window_survives_stale_rearm_and_clears_on_model_reach(tmp_cron_home):++def test_quota_hold_parks_past_window_survives_stale_rearm_and_clears_on_model_reach(tmp_cron_home, cron_owner):+ """A 30-minute job whose provider resolve raises the Codex quota AuthError ('retry after+ 123518s') is parked by the real scheduler tick: preflight lets the rate-limited AuthError+ through (it is not a missing credential), the one delivered alert carries the hold notice,+ and the job does not fire again inside the window (not even after the stale-error re-arm's+ cadence+grace). The marker clears once a run reaches the model."""- job = create_job("portfolio triage", "every 30m", deliver="local")++ # A real (non-local) lane: the alert rides the durable delivery queue, whose enqueue is the seam.++ (tmp_cron_home / "config.yaml").write_text(++ "platforms:\n slack:\n enabled: true\n token: xoxb-test\n", encoding="utf-8")++ job = create_job("portfolio triage", "every 30m", deliver="slack:alerts")+ job_id = job["id"]+ now = datetime.now(timezone.utc)+ deliveries: list = []++ _tick(get_job(job_id), tmp_cron_home, deliveries, _raise_quota)+ j = get_job(job_id)+ assert j["last_status"] == "error"+ assert len(deliveries) == 1 and "This job is held" in deliveries[0], deliveries+ assert "provider credential missing" not in deliveries[0]+ parked = datetime.fromisoformat(j["next_run_at"])+ assert parked - now >= timedelta(seconds=123518), "next_run_at must land past the window"+ assert j[qh.STATE_KEY] == j["next_run_at"]+ assert "_quota_hold_seconds" not in j++ # Two hours later the job looks like a wedged stale-error record (#62002) — the hold says+ # it is parked on purpose, so it is neither re-armed nor due.+ update_job(job_id, {"last_run_at": (now - timedelta(hours=2)).isoformat()})+ j = get_job(job_id)+ assert not _job_is_stale_error_recurring(j, j["schedule"], now)+ assert all(d["id"] != job_id for d in get_due_jobs())+ assert datetime.fromisoformat(get_job(job_id)["next_run_at"]) == parked++ # A run that reached the model (either outcome) clears the marker.+ assert mark_job_run(job_id, False, "RuntimeError: model said no")+ j = get_job(job_id)+ assert qh.STATE_KEY not in j+ assert datetime.fromisoformat(j["next_run_at"]) - now < timedelta(hours=1)++ # Editing the schedule recomputes next_run_at from the new cadence; the stale marker must+ # not linger on a record that is no longer parked where it says.+ assert mark_job_run(job_id, False, QUOTA_MSG, quota_hold_seconds=123518)+ assert qh.STATE_KEY in get_job(job_id)+ j = update_job(job_id, {"schedule": "every 15m"})+ assert qh.STATE_KEY not in j+ assert datetime.fromisoformat(j["next_run_at"]) - now < timedelta(hours=1)diff --cc tests/cron/test_retirement_dispatch.pyindex 00000000000,7f3d2512556..26b5c4a6e49mode 000000,100644..100644--- a/tests/cron/test_retirement_dispatch.py+++ b/tests/cron/test_retirement_dispatch.py@@@ -1,0 -1,90 +1,57 @@@+ """The tick-to-worker handoff must have no retirement-sized gap after can_dispatch."""++ from concurrent.futures import ThreadPoolExecutor+ from datetime import datetime, timezone+ import threading+++ def test_passed_gate_tick_and_queued_job_remain_busy_until_real_worker_exit(tmp_path, monkeypatch):+ from cron import jobs, scheduler+ from hermes_cli import backend_retirement++ fence = backend_retirement.RetirementFence()+ monkeypatch.setattr(backend_retirement, "retirement", fence)+ script = tmp_path / "job.py"+ script.write_text("print('no model')\n")+ job = jobs.create_job(prompt=None, schedule=datetime.now(timezone.utc).isoformat(), script=str(script), no_agent=True)+ for name in ("_maybe_run_worktree_maintenance", "_sweep_mcp_orphans", "_maybe_reap_dead_owners"):+ monkeypatch.setattr(scheduler, name, lambda: None)+ monkeypatch.setattr(scheduler, "_should_yield_tick_to_fresh_gateway", lambda: None)+ reached, release_tick, running, release_job = (threading.Event() for _ in range(4))+ due = scheduler.get_due_jobs+ gate_calls = []++ def get_due_jobs():+ reached.set()+ assert release_tick.wait(10)+ return due()++ def process_job(*args):+ running.set()+ assert release_job.wait(10)+ return True++ monkeypatch.setattr(scheduler, "get_due_jobs", get_due_jobs)+ monkeypatch.setattr(scheduler, "_process_due_job", process_job)+ with ThreadPoolExecutor(max_workers=1) as pool, ThreadPoolExecutor(max_workers=1) as ticker:+ monkeypatch.setattr(scheduler, "_get_parallel_pool", lambda *args: pool)+ tick = ticker.submit(scheduler.tick, verbose=False, sync=False, can_dispatch=lambda: gate_calls.append(True) or True)+ try:+ assert reached.wait(10)+ assert gate_calls+ assert not scheduler.get_running_job_ids()+ assert fence.prepare() == {"ok": False, "idle": False}+ release_tick.set()+ assert tick.result(10) == 1+ assert running.wait(10)+ assert job["id"] in scheduler.get_running_job_ids()+ assert fence.prepare() == {"ok": False, "idle": False}+ finally:+ release_tick.set()+ release_job.set()+ assert not scheduler.get_running_job_ids()+ token = fence.prepare()["token"]+ assert scheduler.tick(verbose=False, sync=False) == 0+ assert scheduler.try_register_running_job("manual-late") is False+ assert fence.commit(token) == {"ok": True}+ assert scheduler.tick(verbose=False, sync=False) == 0---def test_detached_cron_delivery_keeps_admission_after_its_tick_returns(tmp_path, monkeypatch):- from cron import bot_chat_delivery- from hermes_cli import backend_retirement- from hermes_constants import get_hermes_home-- fence = backend_retirement.RetirementFence()- monkeypatch.setattr(backend_retirement, "retirement", fence)- root = get_hermes_home() / "cron" / "bot_chat_pending"- root.mkdir(parents=True)- entered, release = threading.Event(), threading.Event()-- def drain(root):- entered.set()- assert release.wait(10)-- monkeypatch.setattr(bot_chat_delivery, "_drain", drain)- try:- bot_chat_delivery.drain_in_background()- assert entered.wait(10)- assert fence.prepare() == {"ok": False, "idle": False}- finally:- release.set()- for thread in threading.enumerate():- if thread.name == "cron-bot-chat-drain":- thread.join(10)- token = fence.prepare()["token"]- entered.clear()- bot_chat_delivery.drain_in_background()- bot_chat_delivery.drain(root)- assert not entered.is_set()- assert fence.cancel(token) == {"ok": True}diff --cc tests/cron/test_shutdown_interrupt.pyindex 9d70a960b1f,81571333d54..b81ac1bf130--- a/tests/cron/test_shutdown_interrupt.py+++ b/tests/cron/test_shutdown_interrupt.py@@@ -582,8 -587,8 +587,8 @@@ class TestRunOneJobHonoursInterruptedFlwould."""import cron.scheduler as sched- job = self._make_job()+ job = dict(self._make_job(), deliver="telegram")- sched._interrupted_job_ids.add(job["id"])+ sched._interrupted_job_ids.add(sched._inflight_key(job["id"]))with patch("cron.scheduler.claim_dispatch", return_value=True), \patch("agent.secret_scope.set_secret_scope", return_value=None), \diff --cc tests/cron/test_warning_execution_outcome.pyindex 00000000000,fd362912393..7bd8c373260mode 000000,100644..100644--- a/tests/cron/test_warning_execution_outcome.py+++ b/tests/cron/test_warning_execution_outcome.py@@@ -1,0 -1,60 +1,81 @@@+ """Suppressed automatic diagnostics retain failed jobs without invented delivery receipts."""+ import pytest++ from cron import executions, incidents, jobs, scheduler+ from gateway.config import GatewayConfig, Platform, PlatformConfig++++def delivery_queue_rows():++ from cron.delivery_queue import _connect++++ conn = _connect()++ try:++ return [dict(r) for r in conn.execute("SELECT execution_id, status FROM deliveries")]++ finally:++ conn.close()+++++ @pytest.mark.parametrize("mode", ["failure", "crash", "success"])+ @pytest.mark.parametrize("suppress", [False, True])+ @pytest.mark.parametrize("external_worker", [False, True])+ def test_real_run_ledger_and_incident_match_actual_presentation(tmp_path, monkeypatch, mode, suppress, external_worker):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ (tmp_path / "config.yaml").write_text(+ f"display: {{suppress_warning_notifications: {str(suppress).lower()}}}\n"+ )+ config = GatewayConfig()+ config.platforms[Platform.TELEGRAM] = PlatformConfig(enabled=True)+ monkeypatch.setattr("gateway.config.load_gateway_config", lambda: config)+ sent = []++ async def send(platform, pconfig, chat_id, text, **kwargs):+ sent.append(text)+ return {"success": True, "message_id": "receipt"}++ monkeypatch.setattr("tools.send_message_tool._send_to_platform", send)++ def run(job, **kwargs):+ if mode == "crash":+ raise RuntimeError("isolated provider failure")+ return (mode == "success", "retained raw output", "required result", None if mode == "success" else "isolated provider failure")++ monkeypatch.setattr(scheduler, "run_job", run)+ job = jobs.create_job(prompt="fixture only", schedule="every 1h", deliver="telegram:fixture")+ if external_worker:+ from cron import delivery_queue+ execution = executions.create_execution(job["id"], source="fixture")+ job["execution_id"] = execution["id"]+ monkeypatch.setenv("_HERMES_CRON_EXTERNAL_WORKER", execution["id"])+ original_wait = delivery_queue.enqueue_and_wait++ def drain_before_wait(execution_id, job, content, *, for_failure=False):+ delivery_queue.enqueue(execution_id, job, content, for_failure=for_failure)+ assert scheduler.drain_delivery_queue({}, None) == 1+ return original_wait(execution_id, job, content, for_failure=for_failure)++ monkeypatch.setattr(delivery_queue, "enqueue_and_wait", drain_before_wait)+ scheduler.run_one_job(job)+ row = executions.latest_execution(job["id"])+ expected_suppression = suppress and mode != "success"++ # Every agent run (in-process or restart-safe worker) hands its send to the durable queue++ # (gateway-attached cron): the ledger books the handoff and the gateway's drain performs++ # (or suppresses) the send. Only a crash notice is sent inline.++ queued_lane = mode != "crash"++ if queued_lane:++ assert len(sent) == 0++ assert row["delivery_outcome"] == "queued"++ assert scheduler.drain_delivery_queue({}, None) == 1++ (queued,) = delivery_queue_rows()++ assert queued["status"] == ("suppressed" if expected_suppression else "delivered")++ else:++ assert row["delivery_outcome"] == ("suppressed" if expected_suppression else "delivered")+ assert len(sent) == (0 if expected_suppression else 1)- assert row["delivery_outcome"] == ("suppressed" if expected_suppression else "delivered")+ saved = jobs.get_job(job["id"])- assert saved["last_status"] == ("ok" if mode == "success" else "error")++ assert saved["last_status"] == ("error" if mode != "success" else "delivery_queued" if queued_lane else "ok")+ if mode != "success":+ assert "isolated provider failure" in saved["last_error"]+ incident = next(i for i in incidents.list_incidents() if i["job_id"] == job["id"])+ assert incident["state"] == ("detected" if suppress else "alerted")+ if mode != "crash":+ outputs = list((tmp_path / "cron" / "output" / job["id"]).glob("*.md"))+ assert outputs and "retained raw output" in outputs[0].read_text()diff --cc tests/gateway/test_api_server_runs.pyindex 70cafef67e1,0a85ddadfd3..20851646c76--- a/tests/gateway/test_api_server_runs.py+++ b/tests/gateway/test_api_server_runs.py@@@ -467,43 -580,50 +581,87 @@@ class TestRunEventsassert "run.completed" in bodyassert "Hello!" in body+ @pytest.mark.asyncio+ async def test_two_subscribers_each_receive_every_event_and_survive_one_disconnect(self, adapter):+ """/events is fanout, not a work queue: every subscriber sees the whole ordered stream,+ and one client's disconnect never tears down the stream another client still reads."""++ from gateway.platforms.api_server_runs import _mark_run_event++ async def frame(resp):+ return (await asyncio.wait_for(resp.content.readuntil(b"\n\n"), timeout=2.0)).decode()++ app = _create_runs_app(adapter)+ async with TestClient(TestServer(app)) as cli:+ with patch.object(adapter, "_create_agent") as mock_create:+ mock_agent, agent_ready, _ = _make_slow_agent()+ mock_create.return_value = mock_agent+ run_id = (await (await cli.post("/v1/runs", json={"input": "hello"})).json())["run_id"]+ assert agent_ready.wait(timeout=3.0)+ first = await cli.get(f"/v1/runs/{run_id}/events")+ second = await cli.get(f"/v1/runs/{run_id}/events")+ assert first.status == second.status == 200++ _mark_run_event(adapter, run_id, "run.steered", accepted=True)+ assert "run.steered" in await frame(first)+ assert "run.steered" in await frame(second)++ first.close()+ # The server only notices the dropped socket on its next write.+ _mark_run_event(adapter, run_id, "run.steered", accepted=False)+ assert "run.steered" in await frame(second)+ await asyncio.sleep(0.05)+ _mark_run_event(adapter, run_id, "approval.responded", choice="once")+ assert "approval.responded" in await frame(second)++ assert (await cli.post(f"/v1/runs/{run_id}/stop")).status == 200+ tail = await asyncio.wait_for(second.content.read(), timeout=5.0)+ assert b"stream closed" in tail++ @pytest.mark.asyncio+ async def test_completed_event_carries_served_runtime_and_cache_tokens(self, adapter):+ """The run.completed SSE event discloses the same served runtime and cache tokens as the+ pollable status, so streaming clients get identical cost-attribution data (#102101)."""+ import json as _json++ app = _create_runs_app(adapter)+ async with TestClient(TestServer(app)) as cli:+ with patch.object(adapter, "_create_agent") as mock_create:+ mock_agent = MagicMock()+ mock_agent.run_conversation.return_value = {"final_response": "served"}+ mock_agent.provider = "openai-codex"+ mock_agent.model = "gpt-5.6-luna"+ mock_agent.session_prompt_tokens = 774050+ mock_agent.session_completion_tokens = 6286+ mock_agent.session_total_tokens = 780336+ mock_agent.session_cache_read_tokens = 650000+ mock_agent.session_cache_write_tokens = 42+ mock_create.return_value = mock_agent++ resp = await cli.post("/v1/runs", json={"input": "hello", "model": "deepseek-v4-pro"})+ run_id = (await resp.json())["run_id"]++ events_resp = await cli.get(f"/v1/runs/{run_id}/events")+ assert events_resp.status == 200+ body = await events_resp.text()++ completed = None+ for frame in body.split("\n"):+ if frame.startswith("data: "):+ try:+ payload = _json.loads(frame[len("data: "):])+ except ValueError:+ continue+ if payload.get("event") == "run.completed":+ completed = payload+ break+ assert completed is not None, "run.completed event missing from stream"+ assert completed["runtime"]["provider"] == "openai-codex"+ assert completed["runtime"]["model"] == "gpt-5.6-luna"+ assert completed["runtime"]["requested"]["model"] == "deepseek-v4-pro"+ assert completed["usage"]["cache_read_tokens"] == 650000+ assert completed["usage"]["cache_write_tokens"] == 42+@pytest.mark.asyncioasync def test_approval_resolve_all_is_scoped_to_target_run(self, auth_adapter):diff --cc tests/gateway/test_status.pyindex d9aa6e206d6,ef51b6016f3..e302b6d3f12--- a/tests/gateway/test_status.py+++ b/tests/gateway/test_status.py@@@ -1248,34 -1410,104 +1413,52 @@@ class TestLaunchdPlistRespawnGovernanceassert "<key>ExitTimeOut</key>" in plistassert "<key>KeepAlive</key>" in plist+ def test_plist_exit_timeout_uses_full_gui_domain_clamp(self, tmp_path, monkeypatch):+ """launchd's gui domain clamps ExitTimeOut at 60s; ask for all of it.++ Anything above 60 is silently clamped, anything below throws away+ drain headroom the gateway could have used before SIGKILL.+ """+ import re++ from gateway.restart import LAUNCHD_GUI_EXIT_TIMEOUT_CLAMP_S, LAUNCHD_STOP_CLEANUP_RESERVE_S+ from hermes_cli.gateway import generate_launchd_plist++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ plist = generate_launchd_plist()+ m = re.search(r"<key>ExitTimeOut</key>\s*<integer>(\d+)</integer>", plist)+ assert m, plist+ # Ask for the whole gui-domain clamp, and leave room for post-drain cleanup inside it.+ assert int(m.group(1)) >= LAUNCHD_GUI_EXIT_TIMEOUT_CLAMP_S > LAUNCHD_STOP_CLEANUP_RESERVE_S+class TestPermissionErrorOnLockFile:- """Stale root-owned lock files from launchd Background sessions must not- crash the gateway on restart (issue #42685)."""-- def test_permission_error_on_lock_file_returns_false_and_removes(self, tmp_path, monkeypatch):- """When the lock file is not writable (root-owned), the function should- remove the stale file and report the lock as inactive."""- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- lock_path = tmp_path / "gateway.lock"- lock_path.write_text("stale", encoding="utf-8")-- real_open = open-- def deny_write(path, *args, **kwargs):- if str(path) == str(lock_path):- raise PermissionError(13, "Permission denied", str(path))- return real_open(path, *args, **kwargs)-- monkeypatch.setattr("builtins.open", deny_write)-- result = status.is_gateway_runtime_lock_active(lock_path)- assert result is False- assert not lock_path.exists(), "stale root-owned lock file should be removed"-- def test_permission_error_unlink_failure_still_returns_false(self, tmp_path, monkeypatch):- """Even if unlinking the stale lock file fails (e.g. directory not writable),- the function should still return False to allow startup."""- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- lock_path = tmp_path / "gateway.lock"- lock_path.write_text("stale", encoding="utf-8")-- real_open = open-- def deny_write(path, *args, **kwargs):- if str(path) == str(lock_path):- raise PermissionError(13, "Permission denied", str(path))- return real_open(path, *args, **kwargs)-- real_unlink = Path.unlink-- def deny_unlink(self, *args, **kwargs):- if str(self) == str(lock_path):- raise OSError(13, "Permission denied", str(self))- return real_unlink(self, *args, **kwargs)-- monkeypatch.setattr("builtins.open", deny_write)- monkeypatch.setattr(Path, "unlink", deny_unlink)-- result = status.is_gateway_runtime_lock_active(lock_path)- assert result is False-- def test_acquire_gateway_runtime_lock_recovers_from_permission_error(self, tmp_path, monkeypatch):- """acquire_gateway_runtime_lock must survive a stale root-owned lock- file: unlink it and retry with a fresh file instead of crashing."""+ @pytest.mark.linux_only+ def test_inaccessible_lock_is_not_deleted_or_treated_as_absence(self, tmp_path, monkeypatch):monkeypatch.setenv("HERMES_HOME", str(tmp_path))- lock_path = status._get_gateway_lock_path()- lock_path.parent.mkdir(parents=True, exist_ok=True)- lock_path.write_text("stale", encoding="utf-8")-- real_open = open-- def deny_write(path, *args, **kwargs):- # Simulate a root-owned file: opening fails while the ORIGINAL- # stale file is still on disk; after unlink, the fresh file the- # retry creates opens fine.- if (- str(path) == str(lock_path)- and lock_path.exists()- and lock_path.read_text(encoding="utf-8") == "stale"- ):- raise PermissionError(13, "Permission denied", str(path))- return real_open(path, *args, **kwargs)-- monkeypatch.setattr("builtins.open", deny_write)-+ lock = tmp_path / "gateway.lock"+ lock.write_text("existing owner")+ inode = lock.stat().st_ino+ lock.chmod(0)try:- assert status.acquire_gateway_runtime_lock() is True+ assert status.is_gateway_runtime_lock_active(lock) is True+ assert status.acquire_gateway_runtime_lock() is False+ assert lock.stat().st_ino == inodefinally:- status.release_gateway_runtime_lock()+ lock.chmod(0o600)+ assert lock.read_text() == "existing owner"+ assert status.acquire_gateway_runtime_lock() is True+ status.release_gateway_runtime_lock()+ assert lock.stat().st_ino == inode++ @pytest.mark.linux_only+ def test_runtime_lock_does_not_follow_symlink(self, tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ target = tmp_path / "unrelated"+ target.write_text("unchanged")+ (tmp_path / "gateway.lock").symlink_to(target)+ assert status.acquire_gateway_runtime_lock() is False+ assert target.read_text() == "unchanged"class TestNormalizeUpdatedAt:diff --cc tests/hermes_cli/test_gateway_multiplex_served_record.pyindex 4b49a6c5acb,c16cb765fa2..8efe232caab--- a/tests/hermes_cli/test_gateway_multiplex_served_record.py+++ b/tests/hermes_cli/test_gateway_multiplex_served_record.py@@@ -99,16 -103,16 +103,18 @@@ def test_setup_wizard_skips_service_insdef test_setup_gateway_service_step_skips_install_for_served_profile(served_root, monkeypatch, capsys):"""``hermes -p <profile> setup gateway`` (and ``hermes setup`` / ``hermes import``) reach the service- step through ``ensure_gateway_service``: a served profile gets the multiplexer note and no unit/plist,- while a profile the live record does not list is still installed (#111958)."""+ step through ``ensure_gateway_service``: a served profile gets the multiplexer note and no unit/plist+ (#111958), and a named profile the live record does not list gets no unit/plist either — one host+ gateway serves every profile, so setup must not grow a standalone fleet member that+ ``gateway install`` refuses (#109417)."""import hermes_cli.gateway as gw+ from hermes_cli.gateway_setup_service import ensure_gateway_servicecalls: list[str] = []+ # The orchestrator reads every service primitive through ``hermes_cli.gateway``; patch that binding.monkeypatch.setattr(gw, "supports_systemd_services", lambda: True)monkeypatch.setattr(gw, "_is_service_running", lambda: False)- monkeypatch.setattr(gw, "_is_service_installed", lambda: False)+ monkeypatch.setattr(gw, "_is_service_installed", lambda: "install" in calls)monkeypatch.setattr(gw, "has_conflicting_systemd_units", lambda: False)monkeypatch.setattr(gw, "systemd_install", lambda **kwargs: calls.append("install"))monkeypatch.setattr(gw, "systemd_start", lambda *args, **kwargs: calls.append("start"))@@@ -119,8 -122,9 +125,9 @@@assert "already served by the default multiplexer" in capsys.readouterr().outmonkeypatch.setenv("HERMES_HOME", str(served_root / "profiles" / "other")) # not in the live record- assert gw.ensure_gateway_service(context="setup") is True+ assert ensure_gateway_service(context="setup", install=True) is True- assert calls == ["install", "start"]+ assert calls == []+ assert "Profile 'other' does not get a gateway of its own" in capsys.readouterr().outdef test_recycled_pid_does_not_lend_a_stale_record_its_served_profiles(served_root):diff --cc tests/hermes_cli/test_kanban_gateway_restart_handoff.pyindex c3f42b96ef5,e6088ea2ecb..1c8bbc4d342--- a/tests/hermes_cli/test_kanban_gateway_restart_handoff.py+++ b/tests/hermes_cli/test_kanban_gateway_restart_handoff.py@@@ -141,9 -140,54 +143,55 @@@ def test_standalone_dispatcher_keeps_di)assert kbd._default_spawn(task, str(workspace)) == 4243- assert captured_cmd[:3] == ["hermes", "-p", "coder"]+ assert captured_cmd == [sys.executable, "-m", "hermes_cli.kanban_worker_client"]+ @pytest.mark.linux_only+ def test_oneshot_unit_dispatcher_scope_wraps_or_warns_never_dooms_silently(+ worker_setup: tuple[Path, kb.Task], monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture+ ) -> None:+ """A dispatcher under any systemd unit that is NOT the supervised gateway (a+ ``Type=oneshot`` dispatch timer, #113612) loses its cgroup at unit exit. With a+ user bus the worker gets its own ``hermes-worker-*`` scope; without one the+ spawn still happens (the unit's ``KillMode``/lifetime is unknowable, a+ long-lived sequencer keeps working) but the operator is told exactly why the+ workers may die. A cron caller under the same unit is unchanged."""+ from tools import process_registry++ workspace, task = worker_setup+ spawned: list[list[str]] = []++ class FakeProc:+ pid = 4243++ monkeypatch.setattr(subprocess, "Popen", lambda cmd, **kwargs: spawned.append(list(cmd)) or FakeProc())+ monkeypatch.setenv("INVOCATION_ID", "oneshot-dispatch-timer")+ monkeypatch.setattr(process_registry, "_is_supervised_gateway_process", lambda: False)+ monkeypatch.setattr(process_registry, "_systemd_run_user_scope_available", lambda: True)+ monkeypatch.setattr(+ process_registry, "_build_systemd_scope_argv",+ lambda cmd, unit_suffix: ["systemd-run", "--user", "--scope", "--unit", f"hermes-worker-{unit_suffix}", *cmd],+ )++ kbd._default_spawn(task, str(workspace))+ assert spawned[-1][:3] == ["systemd-run", "--user", "--scope"]+ assert f"hermes-worker-kanban-{task.id}-run-{task.current_run_id}" in spawned[-1]++ monkeypatch.setattr(process_registry, "_systemd_run_user_scope_available", lambda: False)+ monkeypatch.setattr(process_registry, "_scope_degraded_warned", False)+ with caplog.at_level("WARNING", logger=process_registry.logger.name):+ kbd._default_spawn(task, str(workspace))- assert spawned[-1][:3] == ["hermes", "-p", "coder"]++ # Unwrapped: the bare worker argv (the profile owner executes; this client waits for its receipt).++ assert spawned[-1] == [sys.executable, "-m", "hermes_cli.kanban_worker_client"]+ warned = [r.getMessage() for r in caplog.records if "KILLED when the unit exits" in r.getMessage()]+ assert len(warned) == 1 and "KillMode=process" in warned[0]++ cron = process_registry.restart_safe_gateway_child_argv(+ ["hermes", "cron"], unit_suffix="cron-job-1", require_restart_safe_scope=True,+ )+ assert cron.mode == "in_process"++@pytest.mark.linux_onlydef test_real_user_systemd_scope_preserves_worker_context(worker_setup: tuple[Path, kb.Task], monkeypatch: pytest.MonkeyPatchdiff --cc tests/hermes_cli/test_resolve_last_session.pyindex 8a89d910839,dd8d5e23748..846b2b5b6c6--- a/tests/hermes_cli/test_resolve_last_session.py+++ b/tests/hermes_cli/test_resolve_last_session.py@@@ -131,5 -131,34 +131,34 @@@ def test_resolve_last_session_real_db_pcmd, 0, stdout=str(repo_a), stderr=""),)- monkeypatch.setattr("hermes_state.SessionDB", lambda **kw: real_db(db_path=state_db, **kw))+ monkeypatch.setattr("hermes_cli.main.get_hermes_home", lambda: tmp_path)assert _resolve_last_session("cli") == "repo_a"+++ def test_resolve_last_session_cli_continues_a_oneshot(monkeypatch, tmp_path):+ """`hermes -z … --resume latest` / `hermes -c` chain on the previous one-shot: its distinct `oneshot`+ source hides it from pickers but it is still CLI history (#112550)."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)++ import hermes_state+ from pathlib import Path++ state_db = Path(tmp_path / "state.db")+ real_db = hermes_state.SessionDB+ db = real_db(db_path=state_db)+ try:+ db.create_session("interactive", source="cli")+ db.create_session("oneshot_run", source="oneshot")+ db.create_session("tui_chat", source="tui")+ with db._lock:+ for sid, started in (("interactive", 100.0), ("oneshot_run", 200.0), ("tui_chat", 300.0)):+ db._conn.execute("UPDATE sessions SET started_at=? WHERE id=?", (started, sid))+ db._conn.commit()+ finally:+ db.close()++ monkeypatch.setattr("hermes_cli.main._resolve_workspace_key", lambda: None)+ monkeypatch.setattr("hermes_state.SessionDB", lambda **kw: real_db(db_path=state_db, **kw))+ assert _resolve_last_session("cli") == "oneshot_run"+ assert _resolve_last_session("tui") == "tui_chat"diff --cc tests/hermes_cli/test_update_head_moved_gate.pyindex 40b3b1176b7,0e3faafe7b8..03b7e6c7366--- a/tests/hermes_cli/test_update_head_moved_gate.py+++ b/tests/hermes_cli/test_update_head_moved_gate.py@@@ -107,22 -107,7 +107,19 @@@ def _patch_update_deps(monkeypatch, tmpmonkeypatch.setattr(hermes_main, "_resume_windows_gateways_after_update", lambda *a, **k: None)- # No code is replaced in this simulation. A real purge would discard the- # discovery patches below and reimport helpers that can reach live services.- monkeypatch.setattr(hermes_main, "_purge_stale_hermes_modules", lambda: None)- # Short-circuit the long tail: dependency install + desktop build.+ from hermes_cli import update_cmd_fleet, update_inventory, update_receipt++ monkeypatch.setattr(+ update_inventory, "collect_runtime_inventory",+ lambda: update_inventory.UpdatePlan(install_method="git", profiles=[], runtimes=[]),+ )+ monkeypatch.setattr(update_receipt, "collect_fleet_versions", lambda **kwargs: [])+ monkeypatch.setattr(+ update_cmd_fleet, "_restart_macos_launchd_gateways", lambda *a, **k: None,+ )+ # These tests own only the HEAD gate, not installers or profile maintenance.+ monkeypatch.setattr(update_cmd, "_sync_python_dependencies_after_pull", lambda *a, **k: None)+ monkeypatch.setattr(update_cmd, "_run_post_update_maintenance", lambda **kwargs: True)monkeypatch.setattr(hermes_main, "_write_update_incomplete_marker", lambda: None)monkeypatch.setattr(hermes_main, "_clear_update_incomplete_marker", lambda: None)monkeypatch.setattr(main_install_repair, "_clear_update_incomplete_marker", lambda: None)diff --cc tests/tools/test_bot_live_owner_delivery.pyindex 0f48cdc62e2,3c07f6d0656..df1e120fffe--- a/tests/tools/test_bot_live_owner_delivery.py+++ b/tests/tools/test_bot_live_owner_delivery.py@@@ -145,5 -105,134 +145,31 @@@ def test_delivery_keeps_the_sender_and_assert mailbox.deliver_to_live_owner(tmp_path, owner, "hello", delivery_id="b" * 32, author=author) == queuedwith pytest.raises(ValueError):mailbox.deliver_to_live_owner(tmp_path, owner, "hello", delivery_id="b" * 32, author={**author, "id": "bot:other"})- assert "author" not in mailbox.deliver_to_live_owner(tmp_path, owner, "no sender", delivery_id="c" * 32)--[email protected](os.name == "nt" or getattr(os, "geteuid", lambda: 1)() == 0,- reason="needs POSIX file permissions for an unreadable ticket")-def test_unreadable_ticket_does_not_wedge_bulk_scans(tmp_path, caplog):- import logging-- from tools import bot_live_delivery as mailbox-- owner = dict(profile_home=str(tmp_path.resolve()), session_id="chat",- lease_id="lease", live_session_id="live")- queued = mailbox.deliver_to_live_owner(tmp_path, owner, "readable", delivery_id="d" * 32)- root = tmp_path / "runtime" / mailbox.DELIVERY_DIR_NAME- # A real admission that later turns unreadable: its sequence must survive the skip.- hidden = mailbox.deliver_to_live_owner(tmp_path, owner, "hidden", delivery_id="e" * 32)- (root / f"{'e' * 32}.json").chmod(0)- corrupt = root / f"{'1' * 32}.json"- corrupt.write_text("{not json", encoding="utf-8")- (root / f"{'2' * 32}.json").write_bytes(b"\xff\xfe\x00garbage") # invalid UTF-8, not just bad JSON- with caplog.at_level(logging.WARNING, logger="tools.bot_live_delivery"):- # Sender side: admission of a fresh id must survive the sequence sweep.- admitted = mailbox.deliver_to_live_owner(tmp_path, owner, "second", delivery_id="f" * 32)- # Receiver side: every readable queued ticket must still be claimed, in order.- assert mailbox.claim_pending_delivery(tmp_path, owner)["delivery_id"] == queued["delivery_id"]- assert mailbox.claim_pending_delivery(tmp_path, owner)["delivery_id"] == admitted["delivery_id"]- for _ in range(10): # the idle poller rescans twice a second- assert mailbox.claim_pending_delivery(tmp_path, owner) is None- assert admitted["status"] == "queued"- assert admitted["sequence"] > hidden["sequence"] > queued["sequence"]- denied = [record for record in caplog.records- if record.message.startswith(f"bot_live_delivery: skipping unreadable ticket {'e' * 32}.json")- and "Permission denied" in record.message]- assert len(denied) == 1, "one persistent bad ticket must warn once per process, not per scan"--[email protected](os.name == "nt" or getattr(os, "geteuid", lambda: 1)() == 0,- reason="needs POSIX file permissions for an unreadable ticket")-def test_unreadable_ticket_keeps_exact_id_reads_fail_closed(tmp_path):- from tools import bot_live_delivery as mailbox-- owner = dict(profile_home=str(tmp_path.resolve()), session_id="chat",- lease_id="lease", live_session_id="live")- unreadable = tmp_path / "runtime" / mailbox.DELIVERY_DIR_NAME / f"{'e' * 32}.json"- unreadable.parent.mkdir(parents=True, exist_ok=True)- unreadable.write_text('{"status": "queued"}', encoding="utf-8")- unreadable.chmod(0)- # Uninspectable is not absent: an exact-id retry must fail closed instead of- # minting a fresh receipt that overwrites the possibly-live one (#109820).- with pytest.raises(PermissionError):- mailbox.deliver_to_live_owner(tmp_path, owner, "same id", delivery_id="e" * 32)- with pytest.raises(PermissionError):- mailbox.read_delivery_result(tmp_path, "e" * 32)+ mailbox.deliver_to_live_owner(tmp_path, owner, "no sender", delivery_id="c" * 32)+ assert "author" not in authority.calls[-1][1]++-def test_non_dict_ticket_is_skipped_by_scans_and_fails_exact_id_reads_closed(tmp_path, caplog):- import logging-++def test_non_dict_ticket_fails_exact_id_reads_closed(tmp_path):++ """Malformed is not absent: an exact-id receipt read raises instead of reporting "no record"."""+ from tools import bot_live_delivery as mailbox+- owner = dict(profile_home=str(tmp_path.resolve()), session_id="chat",- lease_id="lease", live_session_id="live")- queued = mailbox.deliver_to_live_owner(tmp_path, owner, "readable", delivery_id="d" * 32)+ bad = tmp_path / "runtime" / mailbox.DELIVERY_DIR_NAME / f"{'e' * 32}.json"++ bad.parent.mkdir(parents=True)+ bad.write_text('"oops"', encoding="utf-8") # parses, but is not a record- with caplog.at_level(logging.WARNING, logger="tools.bot_live_delivery"):- admitted = mailbox.deliver_to_live_owner(tmp_path, owner, "second", delivery_id="f" * 32)- assert mailbox.claim_pending_delivery(tmp_path, owner)["delivery_id"] == queued["delivery_id"]- assert mailbox.claim_pending_delivery(tmp_path, owner)["delivery_id"] == admitted["delivery_id"]- assert mailbox.claim_pending_delivery(tmp_path, owner) is None- assert sum(r.message.startswith(f"bot_live_delivery: skipping unreadable ticket {'e' * 32}.json")- for r in caplog.records) == 1- # Malformed is not absent: exact-id reads fail closed rather than overwrite the receipt.- with pytest.raises(ValueError):- mailbox.deliver_to_live_owner(tmp_path, owner, "same id", delivery_id="e" * 32)+ with pytest.raises(ValueError):+ mailbox.read_delivery_result(tmp_path, "e" * 32)+ assert bad.read_text(encoding="utf-8") == '"oops"'++-def test_schema_damaged_ticket_does_not_wedge_bulk_scans(tmp_path, caplog):- """Valid JSON that lost a field must degrade like corrupt JSON: skipped, warned once, never raised."""- import logging-- from tools import bot_live_delivery as mailbox-- owner = dict(profile_home=str(tmp_path.resolve()), session_id="chat",- lease_id="lease", live_session_id="live")- queued = mailbox.deliver_to_live_owner(tmp_path, owner, "healthy", delivery_id="d" * 32)- root = tmp_path / "runtime" / mailbox.DELIVERY_DIR_NAME- damaged = {- root / f"{'a' * 32}.json": "{}",- root / f"{'b' * 32}.json": json.dumps(dict(- delivery_id="b" * 32, id="b" * 32, status="queued", created_at=1,- sequence=1, owner=None, message="owner lost")),- root / f"{'c' * 32}.json": json.dumps(dict(- delivery_id="c" * 32, id="c" * 32, status="queued", created_at=2,- sequence="old", owner=owner, message="sequence lost", **owner)),- root / f"{'e' * 32}.json": json.dumps(dict(- delivery_id="../wrong", id="../wrong", status="queued", created_at=3,- sequence=3, owner=owner, message="id lost", **owner)),- root / f"{'1' * 32}.json": json.dumps(dict(- delivery_id="1" * 32, id="1" * 32, status=[], created_at=4,- sequence=4, owner=owner, message="status lost", **owner)),- }- for path, contents in damaged.items():- path.write_text(contents, encoding="utf-8")- with caplog.at_level(logging.WARNING, logger="tools.bot_live_delivery"):- admitted = mailbox.deliver_to_live_owner(tmp_path, owner, "also healthy", delivery_id="f" * 32)- assert mailbox.claim_pending_delivery(tmp_path, owner)["delivery_id"] == queued["delivery_id"]- assert mailbox.claim_pending_delivery(tmp_path, owner)["delivery_id"] == admitted["delivery_id"]- for _ in range(3):- assert mailbox.claim_pending_delivery(tmp_path, owner) is None- assert admitted["sequence"] == queued["sequence"] + 1- assert {path: path.read_text(encoding="utf-8") for path in damaged} == damaged- skipped = [r.message for r in caplog.records if r.message.startswith("bot_live_delivery: skipping unreadable ticket")]- assert len(skipped) == len(damaged), "each damaged ticket warns once per process, not per scan"--+ def test_existing_mailbox_lock_does_not_fsync_parent_dirs(tmp_path, monkeypatch):- """The idle poller re-enters the lock twice a second; only a freshly created mailbox links its parents."""++ """The lock is re-entered on every receipt read; only a freshly created mailbox links its parents."""+ from tools import bot_live_delivery as mailbox++ calls = []+ monkeypatch.setattr(mailbox, "fsync_directory", lambda path: calls.append(path))+ with mailbox._locked(tmp_path):+ pass+ assert len(calls) == 2+ with mailbox._locked(tmp_path):+ pass+ assert len(calls) == 2diff --cc tests/tools/test_bot_mode_dm.pyindex e335a86ac0a,56b1b7f8c63..6fdf6a18852--- a/tests/tools/test_bot_mode_dm.py+++ b/tests/tools/test_bot_mode_dm.py@@@ -211,43 -235,6 +235,51 @@@ def _capture_spawn(monkeypatch)return calls+class _FakeAuthority:+ """The target profile's canonical ``bot_relay.deliver`` door: one admission per+ envelope id, exact retries inspect it, a changed payload conflicts."""++ def __init__(self):+ self.calls = []+ self.records = {}++ def __call__(self, home, params):+ from tools import bot_live_delivery as live++ self.calls.append((Path(home).resolve(), dict(params)))+ record = self.records.get(params["id"])+ if record is None:+ record = self.records[params["id"]] = dict(+ status="queued", delivery_id=params["id"], profile_home=str(Path(home).resolve()),+ session_id="local-bot", message=params["message"], admission_id="adm-" + params["id"][:8],+ reply="")+ with live._locked(home) as root:+ live._write(root / f"{params['id']}.json", record)+ elif record["message"] != params["message"]:+ raise ValueError("admission_conflict")+ return {k: record[k] for k in ("status", "delivery_id", "profile_home", "session_id", "reply")}++- def _canonical_target(monkeypatch, target: Path) -> _FakeAuthority:++def _canonical_target(monkeypatch, *targets: Path) -> _FakeAuthority:++ """Every ``targets`` profile home has a ready authority (its Bot Chat is admitted canonically);++ any other home has none, so a DM there falls through to the runner hand-off."""+ from tools import bot_live_delivery as live+- owner = dict(profile_home=str(target.resolve()), session_id="local-bot", canonical=True,- lease_id="authority-1", live_session_id="local-bot")- monkeypatch.setattr(live, "find_canonical_live_owner",- lambda home: owner if Path(home).resolve() == target.resolve() else None)++ homes = {t.resolve() for t in targets}++++ def owner_of(home):++ home = Path(home).resolve()++ if home not in homes:++ return None++ return dict(profile_home=str(home), session_id="local-bot", canonical=True,++ lease_id="authority-1", live_session_id="local-bot")++++ monkeypatch.setattr(live, "find_canonical_live_owner", owner_of)+ authority = _FakeAuthority()+ monkeypatch.setattr(live, "authority_delivery", authority)+ return authority++def _runner_parts(command):"""(mode, dm_file, transport argv) of a runner command. The optional ``--author <json>`` pair is skipped."""parts = shlex.split(command)@@@ -307,12 -284,24 +339,14 @@@ def test_local_delivery_admits_canonicaassert call["background"] is Trueassert call["notify_on_complete"] is Trueassert call["_host_local"] is True+ # The completion notification IS the reply: sized like a message, not a build log's 2000-char tail.+ assert call["_completion_output_chars"] == bot_mode_dm.REPLY_COMPLETION_CHARS == bot_mode_dm.MESSAGE_MAX_CHARS + 2000assert Path(call["workdir"]) == Path(bot_mode_dm.__file__).resolve().parent.parentcommand = call["command"]- mode, dm_file, transport_argv = _runner_parts(command)+ mode, dm_file, transport_argv, profile_home = _runner_parts(command)assert mode == "query-file"- assert transport_argv == [- "hermes",- "-p",- "researcher",- "chat",- "--in",- "~",- "-c",- "Bot Chat",- "--create-if-missing",- "-Q",- ]+ assert Path(profile_home) == target.resolve()+ assert transport_argv[:3] == ["hermes", "-p", "researcher"]# message body rides the temp file, never the command lineassert "PAYLOAD_SENTINEL_7A91" not in commandassert "$(" not in command@@@ -323,9 -312,103 +357,111 @@@content = Path(dm_file).read_text(encoding="utf-8")assert content.startswith("Message from 🤖 hermes (@hermes): ")assert '$(and this is not shell)' in content+ assert params["message"] == content+ def test_cli_runner_ack_is_a_dispatch_ack_that_names_the_completion_notification(tmp_path, monkeypatch):+ """``status: queued`` is returned before the background runner has delivered anything; the+ detail (and the schema text the model reads) must say the completion notification carries+ the outcome, so a runner that dies at exec is never read as a delivered message."""+ _capture_spawn(monkeypatch)+ home = _managed_home(tmp_path, teammates=("researcher",))++ _canonical_target(monkeypatch, home / "profiles" / "researcher")+ result = json.loads(bot_mode_dm.message_agent_tool(+ target="researcher", message="hi", agent=_FakeAgent(home, title="Bot Chat")))++ assert result["status"] == "queued"- assert "not a delivery receipt" in result["detail"]- assert "completion notification" in result["detail"]- assert "delivery failure" in result["detail"]++ assert "Do NOT wait or resend" in result["detail"]++ assert "delivered" not in result["detail"].lower()+ description = bot_mode_dm.message_agent_tool_schema()["function"]["description"]+ assert "dispatch acknowledgement" in description and "not a delivery receipt" in description++ assert "completion notification" in description and "delivery failure" in description+++ def test_cli_runner_ack_is_queued_with_the_runner_delivery_id(tmp_path, monkeypatch):+ """The CLI-runner ack speaks the same vocabulary as the live-owner and relay branches:+ ``queued`` + ``delivery_id`` (+ ``process_id``). The id is the one the runner itself pins+ for the same DM file when it admits to a live owner, so a sender can correlate both."""+ import hashlib++ calls = _capture_spawn(monkeypatch)+ home = _managed_home(tmp_path, teammates=("researcher",))++ authority = _canonical_target(monkeypatch, home / "profiles" / "researcher")+ result = json.loads(bot_mode_dm.message_agent_tool(+ target="researcher", message="hi", agent=_FakeAgent(home, title="Bot Chat")))++ assert result["status"] == "queued"+ assert result["process_id"] == "proc_test1234"- _, dm_file, _ = _runner_parts(calls[0]["command"])++ _, dm_file, _, _ = _runner_parts(calls[0]["command"])+ assert result["delivery_id"] == hashlib.sha256(str(Path(dm_file).resolve()).encode()).hexdigest()++ assert authority.calls[0][1]["id"] == result["delivery_id"]+++ def test_relay_ack_is_queued_with_the_envelope_id(tmp_path, monkeypatch):+ _capture_spawn(monkeypatch)+ home = _managed_home(tmp_path)+ bot_relay.write_remote_roster(home, [+ {"profile": "default", "handle": "hermes", "connection_id": "cloud-1", "connection_label": "Hermes Cloud"},+ ])+ result = json.loads(bot_mode_dm.message_agent_tool(target="hermes", message="ping", agent=_FakeAgent(home)))++ assert result["status"] == "queued"+ (envelope,) = bot_relay.claim_pending_envelopes(home)+ assert result["delivery_id"] == envelope["id"]+++ def _rename(home: Path, folder: str, *, display_name: str = "", title: str = "") -> None:+ lines = ["description: teammate for tests", "ui_meta:", " hermes-bots:", " shape: cloud"]+ if title:+ lines.append(f" title: {title}")+ if display_name:+ lines.append(f"display_name: {display_name}")+ (home / "profiles" / folder / "profile.yaml").write_text("\n".join(lines) + "\n", encoding="utf-8")+++ @pytest.mark.parametrize("target", ["Scribe", "@scribe", "Dr. Foo", "dr-foo", "drfoo", "Builder"])+ def test_friendly_names_and_desktop_slugs_resolve_to_folder_ids(tmp_path, monkeypatch, target):+ """A display name, Bot Mode title or the Desktop's @-slug of either lands on the+ folder id message_agent keys on — the same aliases the composer autocompletes (#100671)."""+ calls = _capture_spawn(monkeypatch)+ monkeypatch.setattr(bot_relay, "_hermes_cli", lambda: "hermes")+ home = _managed_home(tmp_path, teammates=("writer", "foo", "builder"))+ _rename(home, "writer", display_name="Scribe")+ _rename(home, "foo", title="Dr. Foo")+ _rename(home, "builder", display_name="Builder")+ expected = {"Scribe": "writer", "@scribe": "writer", "Dr. Foo": "foo", "dr-foo": "foo", "drfoo": "foo",+ "Builder": "builder"}[target]++ authority = _canonical_target(monkeypatch, *(home / "profiles" / name for name in ("writer", "foo", "builder")))++ result = json.loads(bot_mode_dm.message_agent_tool(target=target, message="ping", agent=_FakeAgent(home)))++ assert result["status"] == "queued", result+ assert result["to"] == f"@{expected}"- _mode, _dm_file, argv = _runner_parts(calls[0]["command"])++ _mode, _dm_file, argv, profile_home = _runner_parts(calls[0]["command"])+ assert argv[1:3] == ["-p", expected]++ assert Path(profile_home) == (home / "profiles" / expected).resolve()++ assert authority.calls[0][1]["profile"] == expected+++ def test_ambiguous_friendly_name_fails_closed(tmp_path, monkeypatch):+ """Two bots titled the same must not let a DM land on whichever sorts first; the+ reserved @hermes alias can never be hijacked by a rename."""+ calls = _capture_spawn(monkeypatch)+ home = _managed_home(tmp_path, teammates=("aaa", "bbb", "ops"))++ _canonical_target(monkeypatch, home, *(home / "profiles" / name for name in ("aaa", "bbb", "ops")))+ _rename(home, "aaa", display_name="Scribe")+ _rename(home, "bbb", display_name="Scribe")+ _rename(home, "ops", display_name="Hermes")++ ambiguous = json.loads(bot_mode_dm.message_agent_tool(target="Scribe", message="ping", agent=_FakeAgent(home)))+ hijack = json.loads(bot_mode_dm.message_agent_tool(target="hermes", message="ping",+ agent=_FakeAgent(home / "profiles" / "aaa")))++ assert "error" in ambiguous and "No teammate named 'Scribe'" in ambiguous["error"]+ assert hijack.get("to") == "@hermes"+ assert [_runner_parts(c["command"])[2][1:3] for c in calls] == [["-p", "default"]]++def test_peer_delivery_command_pins_registry_profile_for_secondary_bots(tmp_path, monkeypatch):@@@ -348,8 -431,8 +484,8 @@@result = json.loads(bot_mode_dm.message_agent_tool(target="spark", message="ping", agent=agent))- assert result["status"] == "sent"+ assert result["status"] == "queued"- mode, _dm_file, transport_argv = _runner_parts(calls[0]["command"])+ mode, _dm_file, transport_argv, _home = _runner_parts(calls[0]["command"])assert mode == "stdin"# The registry the tool validated against is the machine root's — the# default profile's home — so the CLI runs there, not in reviewer.@@@ -366,9 -449,9 +502,9 @@@ def test_peer_delivery_command(tmp_pathresult = json.loads(bot_mode_dm.message_agent_tool(target="spark/researcher", message="ping", agent=agent))- assert result["status"] == "sent"+ assert result["status"] == "queued"assert "spark" in result["to"]- mode, _dm_file, transport_argv = _runner_parts(calls[0]["command"])+ mode, _dm_file, transport_argv, _home = _runner_parts(calls[0]["command"])assert mode == "stdin"assert transport_argv == ["hermes", "-p", "default", "peer", "dm", "spark/researcher"]# the peer child reads the author from its env and forwards it in the request body@@@ -378,8 -461,8 +514,8 @@@result2 = json.loads(bot_mode_dm.message_agent_tool(target="spark", message="ping", agent=agent))- assert result2["status"] == "sent"+ assert result2["status"] == "queued"- mode, _dm_file, transport_argv = _runner_parts(calls[1]["command"])+ mode, _dm_file, transport_argv, _home = _runner_parts(calls[1]["command"])assert mode == "stdin"assert transport_argv == ["hermes", "-p", "default", "peer", "dm", "spark"]@@@ -415,8 -495,8 +551,8 @@@ def test_delivery_pins_the_hermes_entryresult2 = json.loads(bot_mode_dm.message_agent_tool(target="spark", message="ping", agent=agent))- assert result2["status"] == "sent"+ assert result2["status"] == "queued"- mode, _dm_file, transport_argv = _runner_parts(calls[1]["command"])+ mode, _dm_file, transport_argv, _profile_home = _runner_parts(calls[1]["command"])assert mode == "stdin"assert transport_argv == [str(hermes_entry), "-p", "default", "peer", "dm", "spark"]@@@ -427,16 -507,45 +563,47 @@@ def test_peer_delivery_author_carries_tcalls = _capture_spawn(monkeypatch)monkeypatch.setattr("socket.gethostname", lambda: " eri/mac\x00.local ")home = _managed_home(tmp_path, teammates=("researcher", "coder"), peers=("spark",))+ _canonical_target(monkeypatch, home / "profiles" / "researcher")agent = _FakeAgent(home / "profiles" / "coder", title="Bot Chat")- assert json.loads(bot_mode_dm.message_agent_tool(target="spark", message="ping", agent=agent))["status"] == "sent"+ assert json.loads(bot_mode_dm.message_agent_tool(target="spark", message="ping", agent=agent))["status"] == "queued"assert json.loads(bot_mode_dm.message_agent_tool(target="researcher", message="ping", agent=agent))["status"] == "queued"assert _runner_author(calls[0]["command"]) == {"id": "bot:erimac.local/coder", "name": "coder", "is_bot": True}assert _runner_author(calls[1]["command"]) == {"id": "bot:coder", "name": "coder", "is_bot": True}+ def test_renamed_primary_signs_with_its_friendly_name_and_is_reachable_by_it(tmp_path, monkeypatch):+ """#89720: `hermes profile rename default Maia` writes profile.yaml ``display_name`` (no Bot Mode+ title). The primary must then sign `Maia (@hermes)`, not `hermes (@hermes)`, and a teammate must+ reach it as `maia` / `@maia` — the tag the Desktop roster inserts — while `@hermes` keeps resolving.+ A Bot Mode title outranks the display_name in the signature, as in the Desktop's botFriendlyNames."""+ calls = _capture_spawn(monkeypatch)+ monkeypatch.setattr(bot_relay, "_hermes_cli", lambda: "hermes")+ home = _managed_home(tmp_path, teammates=("coder",))++ _canonical_target(monkeypatch, home, home / "profiles" / "coder")+ (home / "profile.yaml").write_text("display_name: Maia\n", encoding="utf-8")++ result = json.loads(bot_mode_dm.message_agent_tool(target="coder", message="hi", agent=_FakeAgent(home)))+ assert result["status"] == "queued"- _mode, dm_file, _argv = _runner_parts(calls[0]["command"])++ _mode, dm_file, _argv, _home = _runner_parts(calls[0]["command"])+ assert Path(dm_file).read_text(encoding="utf-8").startswith("Message from 🤖 Maia (@hermes): ")++ coder = _FakeAgent(home / "profiles" / "coder")+ for target in ("maia", "@maia", "@hermes"):+ result = json.loads(bot_mode_dm.message_agent_tool(target=target, message="pong", agent=coder))+ assert result["status"] == "queued", (target, result)- _mode, _dm_file, argv = _runner_parts(calls[-1]["command"])++ _mode, _dm_file, argv, _home = _runner_parts(calls[-1]["command"])+ assert argv[1:3] == ["-p", "default"], (target, argv)++ (home / "profile.yaml").write_text(+ "display_name: Maia\nui_meta:\n hermes-bots:\n title: Maia Prime\n", encoding="utf-8"+ )+ json.loads(bot_mode_dm.message_agent_tool(target="coder", message="hi", agent=_FakeAgent(home)))- _mode, dm_file, _argv = _runner_parts(calls[-1]["command"])++ _mode, dm_file, _argv, _home = _runner_parts(calls[-1]["command"])+ assert Path(dm_file).read_text(encoding="utf-8").startswith("Message from 🤖 Maia Prime (@hermes): ")++def test_named_profile_sender_prefix(tmp_path, monkeypatch):"""A named-profile bot signs with its own handle, not @hermes."""calls = _capture_spawn(monkeypatch)@@@ -1050,3 -1172,84 +1217,84 @@@ def test_relay_waiter_that_cannot_startassert "Do NOT resend" in result["detail"]assert "approval" in result["notification_error"]assert list((bot_relay.relay_root(root) / bot_relay.OUTBOX_DIR).glob("*.json")), "envelope still queued"+++ def test_ack_names_poll_return_path_when_session_cannot_receive_completions(tmp_path, monkeypatch):+ """#101142: on a non-push sender surface (api_server) terminal_tool refuses the+ ``notify_on_complete`` promise, so the reply can never be injected later. The ack must not+ promise a completion notification; it names the surface-supported return path instead."""+ import tools.terminal_tool as terminal_tool_module++ monkeypatch.setattr(terminal_tool_module, "terminal_tool", lambda command, **kw: json.dumps({+ "output": "Background process started", "session_id": "proc_np1", "notify_on_complete": False,+ "notify_unsupported": "poll"}))+ home = _managed_home(tmp_path, teammates=("researcher",))++ _canonical_target(monkeypatch, home / "profiles" / "researcher")+ result = json.loads(bot_mode_dm.message_agent_tool(+ target="researcher", message="hi", agent=_FakeAgent(home, title="Bot Chat")))++ assert result["status"] == "queued"+ assert result["reply_delivery"] == "poll"+ assert "completion notification carries" not in result["detail"]+ assert "process(action='wait', session_id='proc_np1')" in result["detail"]+ assert "if wait returns status=timeout, call wait again" in result["detail"]+++ def test_live_owner_ack_carries_the_poll_return_path_when_session_cannot_receive_completions(tmp_path, monkeypatch):+ """#101142 sibling: a live-owner (Desktop) target still runs the same tracked runner whose+ stdout carries the reply. On a non-push sender the live-owner ack must propagate+ ``reply_delivery="poll"`` and the wait instruction instead of 'finish your turn'."""- from tools import bot_live_delivery as live+ import tools.terminal_tool as terminal_tool_module++ home = _managed_home(tmp_path)+ target = home / "profiles" / "researcher"- owner = dict(profile_home=str(target), session_id="bot", lease_id="lease", live_session_id="live")- monkeypatch.setattr(live, "find_canonical_live_owner", lambda h: owner if Path(h) == target else None)++ _canonical_target(monkeypatch, target)+ monkeypatch.setattr(bot_mode_dm, "_dm_dir", lambda: tmp_path)+ monkeypatch.setattr(terminal_tool_module, "terminal_tool", lambda command, **kw: json.dumps({+ "output": "Background process started", "session_id": "proc_np2", "notify_on_complete": False}))++ result = json.loads(bot_mode_dm.message_agent_tool("researcher", "hello", agent=_FakeAgent(home)))+ assert result["status"] == "queued"+ assert result["process_id"] == "proc_np2"+ assert result["reply_delivery"] == "poll"+ assert "process(action='wait', session_id='proc_np2')" in result["detail"]+ assert "finish your turn" not in result["detail"].lower()+++ def test_poll_reply_is_persisted_as_a_delivery_row_when_the_runner_exits(tmp_path, monkeypatch):+ """#101142 durable leg: with no completion notification the sender may end its turn without+ polling; the tracked runner's exit must still land the reply in the sender's session transcript+ as a DELIVERY row (``display_kind=process_complete``), so nothing is silently lost."""+ import tools.terminal_tool as terminal_tool_module+ from tools.process_registry import process_registry++ reply = json.dumps({"status": "settled", "reply": "PAYLOAD_SENTINEL_42", "delivery_id": "d1"})+ procs = []++ def fake_terminal_tool(command, **kw):+ popen = subprocess.Popen([sys.executable, "-c", f"import json; print({reply!r})"],+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)+ procs.append(process_registry.adopt_local(popen, command=command, cwd=str(tmp_path), notify_on_complete=False))+ return json.dumps({"output": "Background process started", "session_id": procs[-1].id,+ "notify_on_complete": False})++ monkeypatch.setattr(terminal_tool_module, "terminal_tool", fake_terminal_tool)+ home = _managed_home(tmp_path, teammates=("researcher",))++ _canonical_target(monkeypatch, home / "profiles" / "researcher")+ agent = _FakeAgent(home, title="Bot Chat")+ rows = []+ agent._session_db.append_message = lambda session_id, role, **kw: rows.append((session_id, role, kw)) or 1++ result = json.loads(bot_mode_dm.message_agent_tool(target="researcher", message="hi", agent=agent))+ assert result["reply_delivery"] == "poll"+ assert "transcript" in result["detail"]+ deadline = time.monotonic() + 10+ while not rows and time.monotonic() < deadline:+ time.sleep(0.05)+ assert len(rows) == 1+ session_id, role, kw = rows[0]+ assert (session_id, role) == ("sess-1", "user")+ assert kw["display_kind"] == "process_complete"+ assert "PAYLOAD_SENTINEL_42" in kw["content"]+ assert procs[0].id in kw["content"]+ assert kw["display_metadata"]["display_text"].startswith("Background Process Finished")diff --cc tests/tools/test_bot_relay_windows_paths.pyindex 15e89314010,8592afcbfb0..12f01ac699f--- a/tests/tools/test_bot_relay_windows_paths.py+++ b/tests/tools/test_bot_relay_windows_paths.py@@@ -2,19 -2,16 +2,16 @@@ r"""Windows-path viability and venv CLTwo failures on a Windows desktop install talking to a remote gateway:- 1. ``waiter_command`` embeds the reply path into generated ``python -c``- source with ``!r``. repr escapes each backslash, but the Windows- execution layer the waiter runs under folds ``\\`` back to ``\`` —- ``\\U`` in ``C:\\Users\\...`` then parses as a unicode escape and- SyntaxErrors the whole script. The raw-string prefix keeps the folded- single backslash a literal; POSIX paths contain no backslashes, so it- is a no-op there, and ``\\'`` inside a raw literal still cannot- terminate the string, so the injection defense from #93091's- python -c hardening is unchanged.+ 1. ``waiter_command`` used to embed the reply path into generated ``python -c``+ source, where the Windows execution layer's backslash folding turned+ ``C:\\Users`` into a unicode escape and SyntaxErrored the script. The waiter+ is now a runner entrypoint (``bot_mode_dm.py --wait-reply``) that takes the+ path as argv, rewritten to forward slashes the way the delivery runner's+ argv is — the tracked local backend runs commands through Git Bash there.-2. ``local_delivery_command`` hardcoded ``"hermes"``, relying on PATH —+2. the delivery runner argv hardcoded ``"hermes"``, relying on PATH —which service contexts (systemd units, desktop launchers, non-login- SSH shells) do not provide, so delivery died with ENOENT. It now+ SSH shells) do not provide, so delivery died with ENOENT. ``_hermes_cli``resolves the CLI next to this gateway's own interpreter (the venvbin/Scripts sibling), falling back to the bare name. The #93091turn-lock recognition in bot_mode_dm matches the CLI element bydiff --cc tests/tools/test_bot_reply_receipt.pyindex 36e37f2270f,00000000000..40dad465ab0mode 100644,000000..100644--- a/tests/tools/test_bot_reply_receipt.py+++ b/tests/tools/test_bot_reply_receipt.py@@@ -1,15 -1,0 +1,18 @@@+"""A relay reply is an immutable delivery receipt, not a last-writer-wins file."""+import json- import pytest+++from tools.bot_relay import write_reply+++def test_relay_reply_retry_cannot_replace_a_settled_delivery(tmp_path):+ key = 'd' * 32+ path = write_reply(tmp_path, key, reply='original')+ before = path.read_bytes()+ assert write_reply(tmp_path, key, reply='original') == path+ assert path.read_bytes() == before- with pytest.raises(ValueError, match='different'):- write_reply(tmp_path, key, reply='replacement')++ # A replayed envelope's second outcome (or a bookkeeping timeout) never displaces the first++ # settled reply — the waiter may already have read it (tests/tools/test_bot_relay.py pins the++ # same rule from the drain side).++ assert write_reply(tmp_path, key, reply='replacement', error='late', reason='delivery_timeout') == path++ assert path.read_bytes() == before+ assert json.loads(path.read_text())['reply'] == 'original'diff --cc tests/tools/test_bot_retry_policy.pyindex 3f70f2e5c6b,5d811bddbb3..f66fade925e--- a/tests/tools/test_bot_retry_policy.py+++ b/tests/tools/test_bot_retry_policy.py@@@ -102,9 -180,107 +102,54 @@@ def test_run_delivery_never_retries_a_ldm = tmp_path / "dm.txt"dm.write_text("hello")- calls = []-- def _fake_run(argv, **kwargs):- calls.append(list(argv))- if len(calls) == 1:- return _Proc(1, stderr="server error - overloaded")- return _Proc(0, stdout="the reply text")-- monkeypatch.setattr(bot_mode_dm.subprocess, "run", _fake_run)- rc = bot_mode_dm._run_delivery(- ["hermes", "-p", "ops", "chat"], str(dm), stdin_file=False- )- assert rc == 0- assert len(calls) == 2- assert calls[0] == calls[1]- assert "the reply text" in capsys.readouterr().out- assert not dm.exists(), "dm file must be cleaned up"-+ monkeypatch.setattr(bot_mode_dm.subprocess, "run",+ lambda argv, **k: pytest.fail("local runner must not execute inference"))+ rc = bot_mode_dm._run_delivery(["hermes", "-p", "ops", "chat"], str(dm), stdin_file=False)+ assert rc == 1+ assert json.loads(capsys.readouterr().out)["reason"] == "runtime_unavailable"+ assert dm.read_text() == "hello", "payload is retained for the sender's evidence"+-def test_run_delivery_no_retry_for_missing_config(monkeypatch, tmp_path):- from tools import bot_mode_dm+- dm = tmp_path / "dm.txt"- dm.write_text("hello")- calls = []++# ── every local-runner failure ships a typed reason (#93091) ─────────────────+- def _fake_run(argv, **kwargs):- calls.append(list(argv))- return _Proc(1, stderr="No LLM provider configured")+- monkeypatch.setattr(bot_mode_dm.subprocess, "run", _fake_run)- rc = bot_mode_dm._run_delivery(- ["hermes", "-p", "ops", "chat"], str(dm), stdin_file=False- )- assert rc == 1- assert len(calls) == 1++class _WithReason(RuntimeError):++ """An exception carrying its own ``reason``. ``reason`` is a stdlib attribute on++ ``ssl.SSLError`` and ``urllib.error.URLError`` too, so a refusal must not forward whatever++ it finds there into a channel whose consumers expect a closed vocabulary."""+++ def __init__(self, reason: str, message: str) -> None:++ super().__init__(message)++ self.reason = reason+-# ── the streams a real failed `-Q` turn writes (#111721) ─────────────────────+-# `hermes … -Q` prints the turn's final_response (the provider prose) on STDOUT and the session-# bookkeeping on STDERR — on every run, so a `stderr or stdout` read never saw the provider error.-_REAL_FAILED_STDOUT = (- "Custom endpoint reported it was overloaded on all 1 attempts — it looks temporarily "- "unavailable. Wait a minute and send /retry.\n\nProvider said: HTTP 503: Overloaded\n"++ ("failure", "reason"),++ [++ (RuntimeError("Error code: 401 - invalid api key"), "provider_auth_or_access"),++ (RuntimeError("something nobody has a rule for"), "unknown"),++ (_WithReason("CERTIFICATE_VERIFY_FAILED", "ssl handshake failed"), "unknown"),++ (_WithReason("provider_quota_limit", "quota exhausted"), "provider_quota_limit"),++ ],++ ids=["classifiable-failure", "unclassifiable-failure", "reason-outside-the-vocabulary",++ "reason-inside-the-vocabulary"],+ )-_REAL_FAILED_STDERR = "Session 20260916_095917_b1a5cd found but has no messages. Starting fresh.\n\nsession_id: 20260916_095917_b1a5cd\n"---def test_deliver_retry_reads_the_stream_the_cli_writes_and_resumes_the_persisted_row(home, monkeypatch):- """A relay delivery whose first turn fails the way the CLI really fails (provider prose on- stdout, `session_id:` banner on stderr) gets its one re-run, and that re-run is told to resume- the user row the failed attempt already persisted; a still-failing turn hands the sender the- typed reason instead of `unknown`."""- from tools.bot_relay import RESUME_UNANSWERED_TURN_ENV-- envs = []-- def _fake_run(argv, **kwargs):- if not _is_hermes_cli(list(argv)):- return _Proc(0)- envs.append(kwargs.get("env") or {})- if len(envs) == 1:- return _Proc(1, stdout=_REAL_FAILED_STDOUT, stderr=_REAL_FAILED_STDERR)- return _Proc(0, stdout="recovered reply")-- monkeypatch.setattr("hermes_cli.quiet_single_query.run_reported_turn", _fake_run)- out = _deliver({"profile": "ops", "message": "ping"})- assert out["result"]["reply"] == "recovered reply"- assert [RESUME_UNANSWERED_TURN_ENV in env for env in envs] == [False, True]- assert envs[1][RESUME_UNANSWERED_TURN_ENV] == "1"-- monkeypatch.setattr(- "hermes_cli.quiet_single_query.run_reported_turn",- lambda argv, **k: _Proc(1, stdout=_REAL_FAILED_STDOUT, stderr=_REAL_FAILED_STDERR)- if _is_hermes_cli(list(argv)) else _Proc(0),- )- out = _deliver({"profile": "ops", "message": "ping"})- assert out["error"]["data"]["reason"] == bfr.PROVIDER_SERVER_ERROR---def test_run_local_turn_retry_reads_the_stream_the_cli_writes_and_resumes_the_persisted_row(monkeypatch, tmp_path, capsys):- """Same invariant on the same-install `message_agent` runner: the real stdout/stderr split opens- the retry gate once, and only the re-run carries the resume marker (the first attempt's env is- otherwise kept)."""++def test_delivery_main_reports_every_failure_as_typed_json(tmp_path, monkeypatch, capsys, failure, reason):++ """The local lane's runner stdout IS the sender's completion notification. A failure other++ than target_busy used to reach the sender as stderr prose with no reason, so it could not++ tell an auth failure from a transient one; it now rides the same vocabulary as the relay."""+ from tools import bot_mode_dm- from tools.bot_relay import RESUME_UNANSWERED_TURN_ENV++ dm = tmp_path / "dm.txt"- dm.write_text("hello")- envs = []-- def _fake_run(argv, **kwargs):- envs.append(kwargs.get("env") or {})- if len(envs) == 1:- return _Proc(1, stdout=_REAL_FAILED_STDOUT, stderr=_REAL_FAILED_STDERR)- return _Proc(0, stdout="the reply text")-- monkeypatch.setattr(bot_mode_dm.subprocess, "run", _fake_run)- rc = bot_mode_dm._run_local_turn(["hermes", "-p", "ops", "chat"], str(dm), env={"HERMES_HOME": str(tmp_path)})- assert rc == 0- assert envs[0] == {"HERMES_HOME": str(tmp_path)}- assert envs[1] == {"HERMES_HOME": str(tmp_path), RESUME_UNANSWERED_TURN_ENV: "1"}- assert "the reply text" in capsys.readouterr().out++ dm.write_text("hi", encoding="utf-8")++++ def _raise(*args, **kwargs):++ raise failure++++ monkeypatch.setattr(bot_mode_dm, "_run_delivery", _raise)++++ rc = bot_mode_dm._delivery_main(["--run-delivery", "query-file", str(dm), "hermes", "-p", "ops", "chat"])++++ assert rc == 1++ payload = json.loads(capsys.readouterr().out.strip())++ assert payload == {"error": str(failure), "reason": reason}diff --cc tests/tools/test_bot_turn_lock.pyindex 13c88143223,69cb765d5de..f9508b20f8e--- a/tests/tools/test_bot_turn_lock.py+++ b/tests/tools/test_bot_turn_lock.py@@@ -12,7 -12,8 +12,7 @@@ from __future__ import annotationimport jsonimport osimport re-import subprocess+ import sysimport threadingimport timediff --cc tests/tui_gateway/test_bot_live_owner_delivery.pyindex 7aa34291993,e15a72ecb2e..b2744a5493c--- a/tests/tui_gateway/test_bot_live_owner_delivery.py+++ b/tests/tui_gateway/test_bot_live_owner_delivery.py@@@ -1,4 -1,4 +1,5 @@@"""Imported turns retain their receipt and cannot bypass the local FIFO."""++import contextlibimport threadingfrom types import SimpleNamespace@@@ -65,28 -67,109 +69,29 @@@ def test_imported_crash_marker_never_auassert schedule("live", {}, "chat") is None-def test_local_work_blocks_mailbox_claim_without_consuming_envelope(monkeypatch, tmp_path):- import tools.bot_live_delivery as mailbox- owner = {"lease_id": "lease", "live_session_id": "live", "session_id": "chat"}- author = {"id": "bot:coder", "name": "coder", "is_bot": True}- pending = [{"id": "receipt", "message": "imported", "author": author}]- monkeypatch.setattr(mailbox, "find_canonical_live_owner", lambda home: owner)- monkeypatch.setattr(mailbox, "claim_pending_delivery", lambda home, pinned: pending.pop(0))- receipts = []- monkeypatch.setattr(mailbox, "complete_delivery", lambda *args, **kwargs: receipts.append((args, kwargs)))- submitted = []- def submit(rid, sid, session, text, **kwargs):- submitted.append((text, kwargs.get("turn_author")))- kwargs["terminal_callback"]({"status": "settled", "text": "reply"})- return True- poll = rebind(session_notifications._poll_bot_live_delivery_once, {- "_session_home": lambda session: tmp_path,- "_session_turn_admission": _session_turn_admission,- "_run_prompt_submit": submit,- "_notif_release_turn": lambda session: session.update(running=False),- })- mailbox._root(tmp_path).mkdir(parents=True) # a delivery was admitted for this profile- session = {"history_lock": threading.RLock(), "agent": object(), "session_key": "chat",- "active_session_lease": SimpleNamespace(lease_id="lease", released=False)}- for blocker in ("running", "queued_prompt", "queued_prompts", "_auto_continue_scheduled"):- session[blocker] = True- assert poll("live", session) is False- assert pending and not submitted- session.pop(blocker)- assert poll("other-live", session) is False- assert pending- assert poll("live", session) is True- assert submitted == [("imported", author)] and not pending- assert receipts[0][0][1] == "receipt"- assert receipts[0][1]["reply"] == "reply"---def test_mailbox_poll_skips_owner_lookup_without_a_mailbox(monkeypatch, tmp_path):- """No mailbox directory → no state.db open / registry lock per pass; the lookup runs once one exists."""- import tools.bot_live_delivery as mailbox- lookups = []- monkeypatch.setattr(mailbox, "find_canonical_live_owner", lambda home: lookups.append(home) or None)- poll = rebind(session_notifications._poll_bot_live_delivery_once, {- "_session_home": lambda session: tmp_path, "_session_turn_admission": _session_turn_admission})- session = {"history_lock": threading.RLock(), "agent": object(), "session_key": "chat",- "active_session_lease": SimpleNamespace(lease_id="lease", released=False)}- assert poll("live", session) is False- assert lookups == []- mailbox._root(tmp_path).mkdir(parents=True)- assert poll("live", session) is False- assert lookups == [tmp_path]---def test_failing_mailbox_poll_warns_once_per_window():- """A failing poll is logged at WARNING once per window; repeats within it are counted, not logged."""- import logging- records = []-- class _Handler(logging.Handler):- def emit(self, record):- records.append(record)-- log = logging.getLogger("test.bot_poll_throttle")- log.addHandler(_Handler())- log.setLevel(logging.DEBUG)- attempts = []-- def failing(sid, session):- attempts.append(sid)- raise RuntimeError("active session file lock unavailable")-- guarded = rebind(session_notifications._poll_bot_live_delivery_guarded, {- "_poll_bot_live_delivery_once": failing, "logger": log,- "_BOT_POLL_WARN_INTERVAL_S": session_notifications._BOT_POLL_WARN_INTERVAL_S})- session = {}- for now in (0.0, 6.0, 12.0, 61.0): # the poller calls at _BOT_DELIVERY_POLL_SECONDS cadence- guarded("live", session, now)- warnings = [r for r in records if r.levelno == logging.WARNING]- assert [r.getMessage() for r in warnings] == [- "Bot live-owner delivery poll failed (0 repeat(s) suppressed since the last report)",- "Bot live-owner delivery poll failed (2 repeat(s) suppressed since the last report)"]- assert all(r.exc_info for r in warnings)---def test_mailbox_poll_delivers_past_a_schema_damaged_ticket(monkeypatch, tmp_path):- """A `{}` ticket beside a healthy envelope must not wedge the live poller's claim (real mailbox on disk)."""+def test_viewer_poller_never_discovers_or_claims_bot_execution(monkeypatch, tmp_path):+ import queue+ import timeimport tools.bot_live_delivery as mailbox- owner = dict(profile_home=str(tmp_path.resolve()), session_id="chat", lease_id="lease", live_session_id="live")- queued = mailbox.deliver_to_live_owner(tmp_path, owner, "healthy", delivery_id="d" * 32)- (mailbox._root(tmp_path) / f"{'a' * 32}.json").write_text("{}", encoding="utf-8")- monkeypatch.setattr(mailbox, "find_canonical_live_owner", lambda home: owner)- submitted = []- def submit(rid, sid, session, text, **kwargs):- submitted.append(text)- kwargs["terminal_callback"]({"status": "settled", "text": "reply"})- return True- poll = rebind(session_notifications._poll_bot_live_delivery_once, {- "_session_home": lambda session: tmp_path,- "_session_turn_admission": _session_turn_admission,- "_run_prompt_submit": submit,- "_notif_release_turn": lambda session: session.update(running=False),+ from tools.process_registry import process_registry+ calls = []+ monkeypatch.setattr(mailbox, 'find_canonical_live_owner', lambda home: calls.append(home))+ stop = threading.Event()+ events = queue.Queue()+ events.put({'type': 'owned-completion'})+ monkeypatch.setattr(process_registry, 'completion_queue', events)+ delivered = []- poll = rebind(session_notifications._notification_poller_loop, {++ poll = rebind(session_notifications._notification_poller_scoped_loop, {+ 'time': time, '_LOOP_POLL_SECONDS': 0, '_KANBAN_POLL_SECONDS': 0,+ '_poll_bot_live_delivery_once': lambda *a: calls.append('legacy-claim'),+ '_maybe_fire_tui_loop_tick': lambda *a: None,+ '_maybe_fire_tui_heartbeat_tick': lambda *a: None,+ '_notif_poll_kanban': lambda *a: None,++ '_session_profile_runtime_scope': lambda session: contextlib.nullcontext(),+ '_session_home': lambda session: tmp_path,+ '_notif_handle_ready': lambda sid, session, ready, *a, **kw: (delivered.extend(ready), stop.set()),})- session = {"history_lock": threading.RLock(), "agent": object(), "session_key": "chat",- "active_session_lease": SimpleNamespace(lease_id="lease", released=False)}- assert poll("live", session) is True- assert submitted == ["healthy"]- assert mailbox.read_delivery_result(tmp_path, queued["delivery_id"])["status"] == "settled"+ poll(stop, 'live', {'agent': object(), 'history_lock': threading.RLock(), 'session_key': 'chat',+ 'active_session_lease': SimpleNamespace(lease_id='lease', released=False)})+ assert delivered == [{'type': 'owned-completion'}]+ assert calls == []diff --cc tests/tui_gateway/test_bot_relay_methods.pyindex 972991db80f,6e565675734..39aa93367b4--- a/tests/tui_gateway/test_bot_relay_methods.py+++ b/tests/tui_gateway/test_bot_relay_methods.py@@@ -62,81 -69,307 +62,107 @@@ def test_outbox_drain_replays_canonicalfirst = _result(srv._methods["bot_relay.outbox.drain"](1, {}))assert [e["id"] for e in first["envelopes"]] == [env["id"]]second = _result(srv._methods["bot_relay.outbox.drain"](2, {}))- assert second["envelopes"] == []+ assert [e["id"] for e in second["envelopes"]] == [env["id"]], "same id, never a duplicate envelope"+ assert second["envelopes"][0]["message"] == "m"+ _result(srv._methods["bot_relay.reply"](3, {"id": env["id"], "reply": "done"}))+ assert _result(srv._methods["bot_relay.outbox.drain"](4, {}))["envelopes"] == []-def test_outbox_drain_reoffers_a_claimed_envelope_the_desktop_never_delivered(home):- """A Desktop that disconnects between ``outbox.drain`` and ``bot_relay.deliver`` leaves the- envelope in ``claimed/`` with no reply: silent until the waiter's deadline, then swept, while- every later drain saw an empty outbox (#111021, redo of #111207). Once it has sat unanswered- for ``REOFFER_AFTER_SECONDS`` the next drain hands it out again — exactly once, ever — an- envelope whose reply already landed is never re-offered, and one still unanswered when the- waiter's ``REPLY_WAIT_SECONDS`` run out gets a ``delivery_timeout`` reply instead of a turn loop."""- import os++def test_outbox_drain_settles_a_claimed_envelope_nobody_answered_with_a_typed_timeout(home):++ """A Desktop that disconnects between ``outbox.drain`` and ``bot_relay.deliver`` leaves the envelope in++ ``claimed/`` with no reply (#111021, #111207). It is replayed on every drain — same id, so the target++ authority admits one turn — until the waiter's ``REPLY_WAIT_SECONDS`` run out; then the drain writes a++ ``delivery_timeout`` reply so the sender learns, and never hands the envelope out again."""+ import time++ target = {"profile": "scout", "handle": "scout", "connection_id": "cloud-1",+ "connection_label": "", "title": "", "description": ""}+ lost = bot_relay.enqueue_envelope(home, target=target, message="lost", sender_profile="w", sender_handle="w")+ done = bot_relay.enqueue_envelope(home, target=target, message="done", sender_profile="w", sender_handle="w")+ drain = srv._methods["bot_relay.outbox.drain"]+ assert sorted(e["id"] for e in _result(drain(1, {}))["envelopes"]) == sorted([lost["id"], done["id"]])+ bot_relay.write_reply(home, done["id"], reply="answered")- # Fresh claims are the Desktop's for a whole window: nothing to re-offer yet.- assert _result(drain(2, {}))["envelopes"] == []- claimed_dir = bot_relay.relay_root(home) / bot_relay.CLAIMED_DIR- lost_path = claimed_dir / f"{lost['id']}.json"- old = time.time() - bot_relay.REOFFER_AFTER_SECONDS - 1- for path in claimed_dir.glob("*.json"):- os.utime(path, (old, old))- reoffered = _result(drain(3, {}))["envelopes"]- assert [(e["id"], e["message"]) for e in reoffered] == [(lost["id"], "lost")]- # One re-offer per envelope: a second silent loss is not handed out again, however old it gets.- os.utime(lost_path, (old, old))- assert _result(drain(4, {}))["envelopes"] == []- assert json.loads(lost_path.read_text(encoding="utf-8"))["reoffered_at"] >= int(old)- # Past the waiter's deadline the drain settles it with a typed timeout so the sender learns.++ # An answered envelope is never re-offered; the unanswered one rides every drain.++ assert [e["id"] for e in _result(drain(2, {}))["envelopes"]] == [lost["id"]]++ lost_path = bot_relay.relay_root(home) / bot_relay.CLAIMED_DIR / f"{lost['id']}.json"+ stale = json.loads(lost_path.read_text(encoding="utf-8"))+ stale["created_at"] = int(time.time()) - bot_relay.REPLY_WAIT_SECONDS - 1+ lost_path.write_text(json.dumps(stale), encoding="utf-8")- assert _result(drain(5, {}))["envelopes"] == []++ assert _result(drain(3, {}))["envelopes"] == []+ reply = json.loads((bot_relay.relay_root(home) / bot_relay.REPLIES_DIR / f"{lost['id']}.json").read_text(encoding="utf-8"))+ assert reply["reason"] == "delivery_timeout" and reply["error"]++ assert _result(drain(4, {}))["envelopes"] == []++-def test_deliver_validates_profile_and_runs_transport(home, monkeypatch):- calls = {}-- class _Proc:- returncode = 0- stdout = "pong from ops"- stderr = ""-- def _fake_run(argv, **kwargs):- calls["argv"] = argv- calls["kwargs"] = kwargs- return _Proc()-- monkeypatch.setattr("hermes_cli.quiet_single_query.run_reported_turn", _fake_run)- out = _result(- srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": "ping"})- )- assert out["reply"] == "pong from ops"- # The cap bounds the turn; the relay wants the printed answer, so a reported child is- # booked only at the cap (exit_grace=None), never early like the cron lane (#114980).- assert calls["kwargs"]["timeout"] == bot_relay.TURN_ATTEMPT_TIMEOUT_SECONDS- assert calls["kwargs"]["exit_grace"] is None- assert calls["kwargs"]["report_path"].endswith(".turn.json")- argv = calls["argv"]- # argv[0] may be a resolved venv path (#93590) — match by basename.- assert argv[1:3] == ["-p", "ops"]- assert argv[0].rsplit("\\", 1)[-1].rsplit("/", 1)[-1] in ("hermes", "hermes.exe")- assert "Bot Chat" in argv and "--query-file" in argv-- # 'hermes' alias resolves to default- _result(srv._methods["bot_relay.deliver"](2, {"profile": "hermes", "message": "x"}))- assert calls["argv"][1:3] == ["-p", "default"]-- # unknown profile refuses without spawning; so does a bare infra dir under profiles/ (#99392)- calls.clear()- (home / "profiles" / "sessions" / "cron").mkdir(parents=True)- for target in ("ghost", "sessions"):- err = srv._methods["bot_relay.deliver"](3, {"profile": target, "message": "x"})- assert "error" in err and target in err["error"]["message"]- assert not calls---def test_deliver_requires_params(home):- err = srv._methods["bot_relay.deliver"](1, {"profile": "", "message": ""})- assert "error" in err---def test_deliver_restamps_relayed_sender_with_a_reply_safe_handle(home, monkeypatch):- """#103731: the sender signs with its bare @handle, which for another machine's ``default`` is- ``@hermes`` — the recipient's OWN default. The delivered text names the sender by the form this- gateway resolves back to it: its title slug when the local relay roster carries it, else- ``handle@connection``. A stamp that is not the relay's is left alone."""- seen = []-- class _Proc:- returncode, stderr, stdout = 0, "", "ok"-- def _fake_run(argv, **_kwargs):- seen.append(Path(argv[argv.index("--query-file") + 1]).read_text(encoding="utf-8"))- return _Proc()-- # The deliver child's runner, whichever this tree has: subprocess.run today, and- # quiet_single_query.run_reported_turn once the relay books turns from their report- # (#114980) — patching only the first would spawn a real ``hermes chat -Q`` child there.- monkeypatch.setattr("subprocess.run", _fake_run)- monkeypatch.setattr("hermes_cli.quiet_single_query.run_reported_turn", _fake_run, raising=False)- bot_relay.write_remote_roster(home, [- {"profile": "default", "handle": "hermes", "connection_id": "vps-1", "title": "CoS Bot"},- ])- stamp = "Message from 🤖 CoS Bot (@hermes): are we done?"- sender = {"from_profile": "default", "from_handle": "hermes", "from_connection": "vps-1"}- _result(srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": stamp, **sender}))- _result(srv._methods["bot_relay.deliver"](2, {"profile": "ops", "message": stamp, **sender, "from_connection": "lan-2"}))- _result(srv._methods["bot_relay.deliver"](3, {"profile": "ops", "message": "plain text (@hermes): x", **sender}))- assert seen == ["Message from 🤖 CoS Bot (@cos-bot): are we done?",- "Message from 🤖 CoS Bot (@hermes@lan-2): are we done?",- "plain text (@hermes): x"]---def test_deliver_relays_empty_reply_for_a_bare_silence_marker(home, monkeypatch):- """#110782: the subprocess transport applies the gateway's silence rule — a bare marker- relays as "", prose that merely mentions one is relayed verbatim."""- class _Proc:- returncode, stderr = 0, ""- stdout = " *NO_REPLY* "-- monkeypatch.setattr("hermes_cli.quiet_single_query.run_reported_turn", lambda *_a, **_k: _Proc())- assert _result(srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": "ping"}))["reply"] == ""-- _Proc.stdout = "The NO_REPLY marker means do not answer."- out = _result(srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": "ping"}))- assert out["reply"] == _Proc.stdout.strip()---def test_deliver_lands_in_live_bot_chat_instead_of_subprocess(home, monkeypatch):- """#100523: a Desktop-owned Bot Chat receives the DM as a normal user turn.+def test_deliver_forwards_stable_id_to_target_profile_authority(home, monkeypatch):+ """The relay door is a transport bridge: it resolves the target profile's+ own home and forwards the envelope id + message to THAT authority. It+ never runs a CLI turn of its own."""+ from tools import bot_live_delivery as live- With the target's Bot Chat live in this gateway, the subprocess transport- would be fenced out by the single-owner lease and drop the payload. The- handler must route through prompt.submit (the composer's choke point) and- never spawn the CLI.- """+ forwarded = []spawned = []- submitted = []-- class _Proc:- returncode, stdout, stderr = 0, "pong", ""def _fake_run(argv, *a, **k):- # The server module's import-time update prefetch runs `git ...` on a- # daemon thread; only the relay's `hermes` CLI spawn is under test.+ # The server module's import-time update prefetch runs `git ...`; only+ # a `hermes` spawn would be a delivery attempt.if argv and argv[0] != "git":spawned.append(argv)- return _Proc()-- monkeypatch.setattr("hermes_cli.quiet_single_query.run_reported_turn", _fake_run)- monkeypatch.setitem(- srv._methods, "prompt.submit", lambda rid, p: submitted.append(p) or srv._ok(rid, {"status": "streaming"})- )- monkeypatch.setattr(srv, "_profile_home", lambda name: home / "profiles" / name)- monkeypatch.setitem(- srv._sessions,- "live-ops",- {"profile_home": str(home / "profiles" / "ops"), "pending_title": "Bot Chat", "history": []},- )- out = _result(srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": "ping"}))- # queued=True is the invariant: a DM never interrupts a turn in flight.- assert submitted == [{"session_id": "live-ops", "text": "ping", "queued": True}]- assert not spawned- assert "reply" in out-- # A live session titled anything else for the same profile does not qualify:- # the subprocess path runs exactly as before.- srv._sessions["live-ops"]["pending_title"] = "Scratch"- submitted.clear()-- out = _result(srv._methods["bot_relay.deliver"](2, {"profile": "ops", "message": "ping"}))- assert out["reply"] == "pong" and spawned and not submitted+ return type("P", (), {"returncode": 0, "stdout": "", "stderr": ""})()+ def _fake_authority(target_home, params):+ forwarded.append((target_home, dict(params)))+ return {"status": "queued", "delivery_id": params["id"], "reply": ""}-def _lease_open_bot_chat(home, *, live_session_id="live-in-other-process"):- """A Bot Chat leased by a mailbox-capable live owner in the target's home (real state.db row,- real lease) — what a Desktop-opened Bot Chat looks like from the relay handler's side."""- from hermes_cli.active_sessions import try_acquire_active_session- from hermes_state import SessionDB+ monkeypatch.setattr("subprocess.run", _fake_run)+ monkeypatch.setattr(live, "authority_delivery", _fake_authority)+ envelope_id = "b" * 32+ out = _result(srv._methods["bot_relay.deliver"](1, {"id": envelope_id, "profile": "ops", "message": "ping"}))+ assert out["status"] == "queued" and out["delivery_id"] == envelope_id+ assert forwarded[-1][0] == home / "profiles" / "ops"+ assert forwarded[-1][1]["id"] == envelope_id and forwarded[-1][1]["profile"] == "ops"++ # Exact retry carries the SAME id to the same authority — no second envelope.+ _result(srv._methods["bot_relay.deliver"](2, {"id": envelope_id, "profile": "ops", "message": "ping"}))+ assert [p["id"] for _h, p in forwarded] == [envelope_id, envelope_id]++ # 'hermes' alias resolves to the default profile's home.+ _result(srv._methods["bot_relay.deliver"](3, {"id": "c" * 32, "profile": "hermes", "message": "x"}))+ assert forwarded[-1][0] == home and forwarded[-1][1]["profile"] == "default"+ assert not spawned- ops_home = home / "profiles" / "ops"- db = SessionDB(db_path=ops_home / "state.db")- db.create_session(session_id="chat", source="desktop")- db.set_session_title("chat", "Bot Chat")- db.close()- lease, refusal = try_acquire_active_session(- session_id="chat", surface="desktop", config={}, registry_home=ops_home,- metadata={"live_session_id": live_session_id, "bot_live_delivery_consumer": True})- assert refusal is None- return ops_home, lease+def test_deliver_unreachable_authority_is_a_typed_refusal(home, monkeypatch):+ from tools import bot_live_delivery as live-def _no_cli_transport(monkeypatch, spawned):- def _fake_run(argv, *a, **k):- if argv and argv[0] != "git":- spawned.append(argv)- raise AssertionError("the CLI transport collides with the live owner")+ def _down(target_home, params):+ raise ValueError("profile authority is not ready")- # Guard the deliver child's runner, whichever this tree has: subprocess.run today, and- # quiet_single_query.run_reported_turn once the relay books turns from their report- # (#114980) — guarding only the first would let a real ``hermes chat -Q`` child spawn there.- monkeypatch.setattr("subprocess.run", _fake_run)- monkeypatch.setattr("hermes_cli.quiet_single_query.run_reported_turn", _fake_run, raising=False)---def _owner_settles(ops_home, outcome: dict) -> threading.Thread:- """Stand in for the owner's poller (session_notifications._poll_bot_live_delivery_once): claim- the queued DM, run "the turn", write the terminal receipt."""- from tools import bot_live_delivery as mailbox-- def run():- owner = mailbox.find_canonical_live_owner(ops_home)- deadline = time.monotonic() + 10- while time.monotonic() < deadline:- claimed = mailbox.claim_pending_delivery(ops_home, owner)- if claimed is not None:- mailbox.complete_delivery(ops_home, claimed["delivery_id"], **outcome)- return- time.sleep(0.05)-- thread = threading.Thread(target=run, daemon=True)- thread.start()- return thread--- ("live_here", "outcome", "expect"),- [- (True, {"status": "settled", "reply": "pong from the open chat"}, ("reply", "pong from the open chat")),- (False, {"status": "failed", "error": "Error code: 429 - rate limit exceeded", "reason": "provider_rate_limit"},- ("reason", "provider_rate_limit")),- ],- ids=["answer-from-a-chat-live-here", "typed-failure-from-a-chat-live-elsewhere"],-)-def test_deliver_into_an_open_bot_chat_returns_the_owners_answer(home, monkeypatch, live_here, outcome, expect):- """#113753 put a relayed DM into the mailbox of a Bot Chat live in a sibling process, and the- owner settles a receipt carrying the reply — the receipt local DMs wait on (_wait_live_dm).- The relay answered with a receipt sentence instead, so the sending agent never got the target's- answer whenever its Bot Chat happened to be open. Now the handler waits on the receipt, on the- local lane's budget: the reply comes back, a failed turn as the typed 5092 refusal, and the- CLI is never spawned. A mailbox-capable chat live in THIS process takes the same door — one- door, one receipt — and prompt.submit (#100523) stays the fallback for a live session with no- mailbox (test_deliver_lands_in_live_bot_chat_instead_of_subprocess)."""- ops_home, lease = _lease_open_bot_chat(home)- spawned, submitted = [], []- _no_cli_transport(monkeypatch, spawned)- monkeypatch.setitem(- srv._methods, "prompt.submit", lambda rid, p: submitted.append(p) or srv._ok(rid, {"status": "streaming"}))- monkeypatch.setattr(srv, "_profile_home", lambda name: ops_home)- monkeypatch.setattr(srv, "_sessions", (- {"live-ops": {"profile_home": str(ops_home), "pending_title": "Bot Chat", "history": []}} if live_here else {}))- monkeypatch.setattr("tools.bot_mode_dm._LIVE_WAIT_SECONDS", 10)- try:- owner = _owner_settles(ops_home, outcome)- out = srv._methods["bot_relay.deliver"](1, {- "profile": "ops", "message": "ping", "from_profile": "cody", "from_handle": "cody",- "from_connection": "conn-a"})- owner.join(timeout=10)- assert not spawned and submitted == []- key, value = expect- if key == "reply":- assert _result(out)["reply"] == value- else:- assert out["error"]["code"] == 5092 and out["error"]["data"]["reason"] == value- finally:- lease.release()+ monkeypatch.setattr(live, "authority_delivery", _down)+ err = srv._methods["bot_relay.deliver"](1, {"id": "d" * 32, "profile": "ops", "message": "x"})+ assert err["error"]["data"]["reason"] == "runtime_unavailable"+ assert "not ready" in err["error"]["message"]+ # A name that is not a live profile (#99392: infra dirs and bare shells are not teammates)+ # is refused before any authority is consulted.+ (home / "profiles" / "sessions").mkdir()+ for ghost in ("ghost", "sessions"):+ err = srv._methods["bot_relay.deliver"](2, {"id": "e" * 32, "profile": ghost, "message": "x"})+ assert err["error"]["data"]["reason"] == "unknown_profile", ghost-def test_deliver_into_a_busy_open_bot_chat_reports_it_queued_and_keeps_the_receipt(home, monkeypatch):- """The owner admits at its next idle boundary; a DM not answered within the budget is reported- queued there — the record stays for the owner, carrying the message and the relayed sender as- the turn author, and the sender is told not to resend."""- from tools import bot_live_delivery as mailbox[email protected]("params", [+ {"profile": "", "message": ""},+ {"profile": "ops", "message": "no envelope id"},+ {"id": "../evil", "profile": "ops", "message": "x"},+ {"id": "e" * 32, "profile": "../ops", "message": "x"},+])+def test_deliver_requires_stable_id_and_valid_profile(home, monkeypatch, params):+ from tools import bot_live_delivery as live- ops_home, lease = _lease_open_bot_chat(home)- spawned = []- _no_cli_transport(monkeypatch, spawned)- monkeypatch.setattr(srv, "_profile_home", lambda name: ops_home)- monkeypatch.setattr(srv, "_sessions", {})- monkeypatch.setattr("tools.bot_mode_dm._LIVE_WAIT_SECONDS", 0.6)- try:- out = _result(srv._methods["bot_relay.deliver"](1, {- "profile": "ops", "message": "ping", "from_profile": "cody", "from_handle": "cody",- "from_connection": "conn-a"}))- assert not spawned and "open Bot Chat" in out["reply"] and "Do not resend" in out["reply"]- (queued,) = [- r for p in (ops_home / "runtime" / mailbox.DELIVERY_DIR_NAME).glob("*.json")- if (r := json.loads(p.read_text(encoding="utf-8")))]- assert queued["status"] == "queued" and queued["message"] == "ping"- assert queued["owner"]["lease_id"] == lease.lease_id- assert queued["author"]["name"] == "cody" and queued["author"]["is_bot"] is True- finally:- lease.release()+ monkeypatch.setattr(live, "authority_delivery",+ lambda *a, **k: pytest.fail("malformed requests never reach an authority"))+ err = srv._methods["bot_relay.deliver"](1, params)+ assert err["error"]["data"]["reason"] == "invalid_params"def test_reply_roundtrip_and_id_validation(home):@@@ -175,26 -483,59 +201,82 @@@ SENDER = {"from_profile": "scout", "froSENDER_AUTHOR = {"id": "bot:cloud-1/scout", "name": "scout", "is_bot": True}- @pytest.mark.parametrize("identity, refused", [- (None, False),- ({"user_id": INTERNAL_USER_ID, "provider": INTERNAL_PROVIDER}, False),- ({"user_id": "alice", "provider": "google"}, True),- ])- def test_relay_sender_attribution_obeys_transport_identity(home, monkeypatch, bound_client, identity, refused):+ @pytest.mark.parametrize("identity", [+ None,+ {"user_id": INTERNAL_USER_ID, "provider": INTERNAL_PROVIDER},+ ], ids=["no identity", "server-internal identity"])-def test_deliver_accepts_a_sender_from_an_admitted_non_login_client(home, fake_runs, bound_client, identity):++def test_deliver_accepts_a_sender_from_an_admitted_non_login_client(home, monkeypatch, bound_client, identity):+ """A caller with no identity, or one holding the ``?internal=`` credential, keeps its sender fields.++ NOT the Desktop: it mints a ws-ticket carrying the signed-in ``{user_id, provider}`` on every+ gateway that requires sign-in (``hermes_cli/dashboard_auth/routes.py``), so it is a login- identity and takes the principal-author branch above.- """- from agent.turn_author import TURN_AUTHOR_ENV-- calls, _outcomes = fake_runs++ identity and takes the principal-author branch below."""+ from tools import bot_live_delivery as live+ forwarded = []+ monkeypatch.setattr(live, "authority_delivery",+ lambda home, params: forwarded.append(params) or {"status": "queued"})bound_client.auth_identity = identity-- _result(srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": "ping", **SENDER}))-- assert [json.loads(c["env"][TURN_AUTHOR_ENV]) for c in calls] == [SENDER_AUTHOR]+ result = srv._methods["bot_relay.deliver"](1, {+ "id": "f" * 32, "profile": "ops", "message": "ping", **SENDER})- if refused:- assert result["error"]["code"] == 4095- assert not forwarded- else:- assert _result(result)["status"] == "queued"- assert forwarded[0]["author"] == SENDER_AUTHOR- assert not any(key in forwarded[0] for key in SENDER)++ assert _result(result)["status"] == "queued"++ assert forwarded[0]["author"] == SENDER_AUTHOR++ assert not any(key in forwarded[0] for key in SENDER)+++ def test_deliver_from_a_logged_in_client_is_attributed_to_its_principal_never_to_the_claimed_sender(- home, fake_runs, bound_client):++ home, monkeypatch, bound_client):+ """A logged-in client's sender fields are not trusted — but the dm is neither refused nor left unattributed.+- Refusing the CALL (the original guard) took cross-machine relay offline for every auth-gated gateway,- because the Desktop is itself a logged-in client there. Dropping the AUTHOR instead made the turn the- human's to the recipient's memory (Honcho routes an unattributed turn into the human session and allows- conclusion / profile / mirror writes). So the author is derived from the caller's minted identity:- stable, unspoofable, and still a bot — whether or not the client named a sender.- """- import json-- from agent.turn_author import TURN_AUTHOR_ENV-- calls, _outcomes = fake_runs++ Refusing the CALL took cross-machine relay offline for every auth-gated gateway, because the Desktop is++ itself a logged-in client there. Dropping the AUTHOR would make the turn the human's to the recipient's++ memory. So the author is derived from the caller's minted identity: stable, unspoofable, and still a bot —++ whether or not the client named a sender — and the authority receives it with the sender fields stripped."""++ from tools import bot_live_delivery as live++ forwarded = []++ monkeypatch.setattr(live, "authority_delivery",++ lambda home, params: forwarded.append(params) or {"status": "queued"})+ bound_client.auth_identity = {"user_id": "alice", "provider": "google"}++ shapes = ({"from_profile": "scout"}, {"from_connection": "cloud-1"}, SENDER, {})+ for rid, sender in enumerate(shapes):- _result(srv._methods["bot_relay.deliver"](rid, {"profile": "ops", "message": "ping", **sender}))++ _result(srv._methods["bot_relay.deliver"](rid, {"id": "f" * 32, "profile": "ops", "message": "ping", **sender}))+- assert len(calls) == len(shapes), "every relayed dm from a logged-in client must still run its turn"- authors = [json.loads(c["env"][TURN_AUTHOR_ENV]) for c in calls]++ assert len(forwarded) == len(shapes), "every relayed dm from a logged-in client must still be admitted"++ authors = [p["author"] for p in forwarded]+ assert all(a["is_bot"] is True for a in authors), "a relayed dm stays bot-authored for the recipient's memory"+ assert all(a["id"].startswith("bot:principal:dashboard:") and a["id"].endswith("/relay") for a in authors)+ assert all(a["name"] == "relayed teammate" for a in authors)+ assert SENDER_AUTHOR not in authors, "the claimed sender must not become the author"+ assert len({a["id"] for a in authors}) == 1, "one signed-in principal, one author — with or without sender fields"++ assert not any(key in p for p in forwarded for key in SENDER)++ bound_client.auth_identity = {"user_id": "bob", "provider": "google"}- _result(srv._methods["bot_relay.deliver"](9, {"profile": "ops", "message": "ping", **SENDER}))- assert json.loads(calls[-1]["env"][TURN_AUTHOR_ENV])["id"] != authors[0]["id"], "a different principal is a different author"++ _result(srv._methods["bot_relay.deliver"](9, {"id": "f" * 32, "profile": "ops", "message": "ping", **SENDER}))++ assert forwarded[-1]["author"]["id"] != authors[0]["id"], "a different principal is a different author"++++++def test_deliver_restamps_relayed_sender_with_a_reply_safe_handle(home, monkeypatch):++ """#103731: the sender signs with its bare @handle, which for another machine's ``default`` is++ ``@hermes`` — the recipient's OWN default. The text forwarded to the target authority names the++ sender by the form this gateway resolves back to it: its title slug when the local relay roster++ carries it, else ``handle@connection``. A stamp that is not the relay's is left alone."""++ from tools import bot_live_delivery as live++ seen = []++ monkeypatch.setattr(live, "authority_delivery",++ lambda home, params: seen.append(params["message"]) or {"status": "queued"})++ bot_relay.write_remote_roster(home, [++ {"profile": "default", "handle": "hermes", "connection_id": "vps-1", "title": "CoS Bot"},++ ])++ stamp = "Message from 🤖 CoS Bot (@hermes): are we done?"++ sender = {"from_profile": "default", "from_handle": "hermes", "from_connection": "vps-1"}++ _result(srv._methods["bot_relay.deliver"](1, {"id": "a" * 32, "profile": "ops", "message": stamp, **sender}))++ _result(srv._methods["bot_relay.deliver"](2, {"id": "b" * 32, "profile": "ops", "message": stamp, **sender,++ "from_connection": "lan-2"}))++ _result(srv._methods["bot_relay.deliver"](3, {"id": "c" * 32, "profile": "ops", "message": "plain text (@hermes): x",++ **sender}))++ assert seen == ["Message from 🤖 CoS Bot (@cos-bot): are we done?",++ "Message from 🤖 CoS Bot (@hermes@lan-2): are we done?",++ "plain text (@hermes): x"]@pytest.mark.parametrize("subdir", ["profiles/ops", "dev"])diff --cc tests/tui_gateway/test_notification_admission_refusal.pyindex ea6102984df,00000000000..af72a6dca53mode 100644,000000..100644--- a/tests/tui_gateway/test_notification_admission_refusal.py+++ b/tests/tui_gateway/test_notification_admission_refusal.py@@@ -1,70 -1,0 +1,72 @@@+"""A refused legacy turn is not a completion delivery receipt."""+import logging+import queue+import threading+import time+from types import SimpleNamespace++import pytest++from tui_gateway import prompt_turn, session_notifications+from tui_gateway.method_ctx import rebind++from tui_gateway.session_lifecycle import _session_turn_admission++[email protected]('kind', ['async_delegation', 'completion'])+def test_refused_notification_retains_result_without_spending_attempts(tmp_path, kind):+ from tests.gateway.test_completion_admission import pending+ from tools import async_delegation as delegation+ from tools.process_registry import process_registry++ event = pending('owned', 'refused-notification') if kind == 'async_delegation' else {+ 'type': 'completion', 'session_id': 'owned-process', 'session_key': 'owned'}+ session = {'history_lock': threading.RLock(), '_closing': True, 'running': True}+ emitted = []+ namespace = dict(time=time, logger=logging.getLogger(__name__),+ _emit=lambda *args: emitted.append(args),++ _session_turn_admission=_session_turn_admission,+ _ensure_active_session_slot=lambda *args: None,+ _notif_log_failure=lambda *args: None)+ for module, names in [(prompt_turn, ('_admit_prompt_turn', '_run_prompt_submit')),+ (session_notifications, ('_notif_submit', '_notif_claim_turn', '_notif_release_turn',+ '_notif_dispatch_event', '_notif_dispatch_completions', '_async_delegation_display_metadata'))]:+ for name in names:+ namespace[name] = rebind(getattr(module, name), namespace)+ # Also bind the retry helper when present; old code must fail on the receipt, not an absent test import.+ if hasattr(session_notifications, '_notif_defer_event'):+ namespace['_notif_defer_event'] = rebind(session_notifications._notif_defer_event, namespace)+ # The dispatcher binds the session's DB row before admission; this session has no store.+ namespace['_ensure_session_db_row'] = lambda _session: True+ original_queue = process_registry.completion_queue+ process_registry.completion_queue = queue.Queue()+ try:+ for _ in range(10):+ session['running'] = kind == 'async_delegation'+ if kind == 'async_delegation':+ namespace['_notif_dispatch_event']('live', session, event, 'nonhuman summary')+ record = delegation.get_durable_delegation(event['delegation_id'])+ assert (record['delivery_state'], record['delivery_attempts']) == ('pending', 0), record+ else:+ namespace['_notif_dispatch_completions']('live', session, [(event, 'result')],+ SimpleNamespace(completion_queue=process_registry.completion_queue,+ is_completion_consumed=lambda _: False), None)+ assert process_registry.completion_queue.get_nowait() == event+ assert session['running'] is False+ assert not any(e[0] == 'message.start' for e in emitted), emitted+ accepted = []+ def accept(*args, **kwargs):+ accepted.append((args, kwargs))+ return True+ namespace['_run_prompt_submit'] = accept+ session['running'] = kind == 'async_delegation'+ if kind == 'async_delegation':+ namespace['_notif_dispatch_event']('live', session, event, 'nonhuman summary')+ assert delegation.get_durable_delegation(event['delegation_id'])['delivery_state'] == 'delivered'+ assert accepted[0][1]['display_kind'] == 'async_delegation_complete'+ else:+ namespace['_notif_dispatch_completions']('live', session, [(event, 'result')],+ SimpleNamespace(completion_queue=process_registry.completion_queue,+ is_completion_consumed=lambda _: False), None)+ assert len(accepted) == 1 and process_registry.completion_queue.empty()+ finally:+ process_registry.completion_queue = original_queuediff --cc tests/tui_gateway/test_notification_turn_release.pyindex 00000000000,d35edbc8331..5ef162ad972mode 000000,100644..100644--- a/tests/tui_gateway/test_notification_turn_release.py+++ b/tests/tui_gateway/test_notification_turn_release.py@@@ -1,0 -1,134 +1,133 @@@+ """A notification that claims the session's turn must hand it back whenever no turn runs.++ The poller claims the idle session (``running = True``) and only then claims the event's durable+ delivery row. Nothing else clears ``running``: a busy session is exempt from the reaper, keeps its+ active-session lease, diverts every ``prompt.submit`` into a queue that only a finishing turn+ drains, and never polls its bot mailbox again — so a dispatch that returns or raises without+ starting a turn leaves that session unusable for the life of the backend.+ """++ from __future__ import annotations++ import queue+ import sqlite3+ import threading+ from types import SimpleNamespace++ import pytest++ from tui_gateway import server++ DELEGATION = {"type": "async_delegation", "delegation_id": "deleg-1", "session_key": "stored"}+++ def _claimed_session() -> dict:+ session = {"history_lock": threading.RLock(), "running": False, "history": []}+ assert server._notif_claim_turn(session) is True+ return session+++ def _no_turn(monkeypatch) -> list:+ started: list = []+ monkeypatch.setattr(server, "_run_prompt_submit", lambda *a, **k: started.append(a))+ monkeypatch.setattr(server, "_emit", lambda *a, **k: None)+ return started+++ @pytest.mark.parametrize("claim", [None, sqlite3.OperationalError("database is locked")],+ ids=["row-held-by-another-consumer", "ledger-unreadable"])+ def test_a_lost_delivery_claim_hands_the_turn_back(monkeypatch, claim):+ """A gateway sharing this home claims the durable row before it verifies the target, so the+ poller holding the live copy of the same event gets ``None`` — after it already took the turn."""+ def _claim(evt, consumer):+ if isinstance(claim, Exception):+ raise claim+ return claim++ monkeypatch.setattr("tools.async_delegation.claim_event_delivery", _claim)+ started = _no_turn(monkeypatch)+ session = _claimed_session()++ server._notif_dispatch_event("sid", session, dict(DELEGATION), "text")++ assert session["running"] is False+ assert started == []+ assert server._notif_claim_turn(session) is True, "the session must be claimable again"+++ @pytest.mark.parametrize("fail_at", ["claim", "render"])+ def test_a_completion_batch_that_cannot_be_prepared_hands_the_turn_back(monkeypatch, fail_at):+ events = [{"type": "completion", "session_id": "proc_a"}, {"type": "completion", "session_id": "proc_b"}]+ released: list = []+ claims = iter(["claim-a", sqlite3.OperationalError("database is locked")] if fail_at == "claim"+ else ["claim-a", "claim-b"])++ def _claim(evt, consumer):+ value = next(claims)+ if isinstance(value, Exception):+ raise value+ return value++ monkeypatch.setattr("tools.async_delegation.claim_event_delivery", _claim)+ monkeypatch.setattr("tools.async_delegation.release_event_delivery", lambda evt, c: released.append(c))+ if fail_at == "render":+ monkeypatch.setattr("tools.process_registry_notifications.ProcessNotificationBatch.render",+ lambda self, registry: (_ for _ in ()).throw(ValueError("bad payload")))+ started = _no_turn(monkeypatch)+ session = {"history_lock": threading.RLock(), "running": False, "history": []}++ server._notif_dispatch_completions("sid", session, [(e, "t") for e in events],+ SimpleNamespace(completion_queue=queue.Queue()), None)++ assert session["running"] is False and started == []+ # Claims already taken go back too, or those completions are lost to every consumer for 300 s.+ assert released == (["claim-a"] if fail_at == "claim" else ["claim-a", "claim-b"])+++ def test_a_loop_wakeup_whose_send_cannot_start_hands_the_turn_back(monkeypatch):+ """The /loop slash wakeup re-claims the turn for a command that resolves to a prompt, then runs+ the send under ``except Exception: pass`` — which swallowed the only signal that no turn started."""+ monkeypatch.setitem(server._methods, "command.dispatch",+ lambda rid, params: {"result": {"type": "send", "message": "run the skill"}})+ monkeypatch.setattr(server, "_emit", lambda *a, **k: None)+ monkeypatch.setattr(server, "_run_prompt_submit",+ lambda *a, **k: (_ for _ in ()).throw(RuntimeError("no free worker")))+ ticks: list = []+ mgr = SimpleNamespace(abandon_tick=lambda: ticks.append("abandoned"),+ complete_tick=lambda text: ticks.append("completed") or {})+ session = _claimed_session()++ server._notif_slash_loop_tick("rid", "sid", session, mgr, "/skill go")++ assert session["running"] is False+ assert ticks == ["completed"]+++ def test_the_poller_thread_survives_a_dispatch_that_raises(monkeypatch):+ """The poller is the session's only path to notifications, /loop, /heartbeat and its bot+ mailbox; an exception out of one event's dispatch used to end the thread for good."""+ events: queue.Queue = queue.Queue()+ events.put({"type": "completion", "session_id": "proc_a"})+ monkeypatch.setattr("tools.process_registry.process_registry", SimpleNamespace(completion_queue=events))- for name in ("_poll_bot_live_delivery_guarded", "_maybe_fire_tui_loop_tick",- "_maybe_fire_tui_heartbeat_tick", "_notif_poll_kanban"):++ for name in ("_maybe_fire_tui_loop_tick", "_maybe_fire_tui_heartbeat_tick", "_notif_poll_kanban"):+ monkeypatch.setattr(server, name, lambda *a, **k: None)+ stop = threading.Event()+ handled: list = []++ def _handle_ready(sid, session, ready, emitted, registry, fmt, deferred, **kwargs):+ if deferred is not None: # the post-stop drain+ return+ handled.append(len(ready))+ if len(handled) == 1:+ events.put({"type": "completion", "session_id": "proc_b"})+ raise RuntimeError("one bad event")+ stop.set()++ monkeypatch.setattr(server, "_notif_handle_ready", _handle_ready)+ session = {"history_lock": threading.RLock(), "running": False, "history": []}+ worker = threading.Thread(target=server._notification_poller_scoped_loop, args=(stop, "sid", session), daemon=True)+ worker.start()+ worker.join(timeout=10)++ assert not worker.is_alive()+ assert handled == [1, 1], "the second event must still be dispatched after the first one raised"diff --cc tests/tui_gateway/test_retirement_admission.pyindex 00000000000,8260cb8979c..62cbd64b4a5mode 000000,100644..100644--- a/tests/tui_gateway/test_retirement_admission.py+++ b/tests/tui_gateway/test_retirement_admission.py@@@ -1,0 -1,95 +1,85 @@@+ """Every admission source participates in the same process retirement fence."""++ from concurrent.futures import ThreadPoolExecutor+ import queue+ import threading++ import pytest+++ @pytest.fixture+ def runtime(monkeypatch):+ from tui_gateway import server+ from hermes_cli import backend_retirement++ fence = backend_retirement.RetirementFence()+ monkeypatch.setattr(backend_retirement, "retirement", fence)+ return server, fence+++ class Transport:+ def __init__(self):+ self.frames = queue.Queue()++ def write(self, frame):+ self.frames.put(frame)+ return True+++ def test_queued_and_running_rpc_hold_admission_until_the_response(runtime, monkeypatch):+ from hermes_cli.web_server_idle_proof import idle_proof++ server, fence = runtime+ release_pool, entered, release_handler = (threading.Event() for _ in range(3))+ transport = Transport()++ def handler(rid, params):+ entered.set()+ assert release_handler.wait(10)+ return server._ok(rid, {"done": True})++ monkeypatch.setitem(server._methods, "test.retirement", handler)+ monkeypatch.setattr(server, "_LONG_HANDLERS", {"test.retirement"})+ with ThreadPoolExecutor(max_workers=1) as pool:+ monkeypatch.setattr(server, "_pool", pool)+ blocked = pool.submit(release_pool.wait, 10)+ try:+ assert server.dispatch({"id": "test", "method": "test.retirement"}, transport) is None+ assert fence.prepare() == {"ok": False, "idle": False}+ assert idle_proof()["idle"] is False+ release_pool.set()+ blocked.result(10)+ assert entered.wait(10)+ assert fence.prepare() == {"ok": False, "idle": False}+ release_handler.set()+ assert transport.frames.get(timeout=10)["result"] == {"done": True}+ finally:+ release_pool.set()+ release_handler.set()+ assert idle_proof()["idle"] is True+ token = fence.prepare()["token"]+ assert server.dispatch({"id": "late", "method": "test.retirement"}, transport)["error"]["code"] == 5035+ assert fence.cancel(token) == {"ok": True}+++ def test_prompt_claim_and_automatic_continuations_cannot_cross_prepare(runtime, monkeypatch):+ server, fence = runtime+ session = {"history_lock": threading.RLock(), "running": False, "history": []}+ dispatched = []+ monkeypatch.setattr(server, "_run_prompt_submit", lambda *a, **kw: dispatched.append(a))+ token = fence.prepare()["token"]+ err, _ = server._lock_in_submit_turn("r", "s", session, "hello", {}, False, None, None, None)+ assert err and err["error"]["code"] == 5035+ assert session["running"] is False+ session["queued_prompt"] = {"text": "next", "transport": None}+ assert server._drain_queued_prompt("r", "s", session) is False+ assert session["queued_prompt"]["text"] == "next"+ assert server._notif_claim_turn(session) is False+ # Use a separate idle session so the goal branch is reached without the queued prompt.+ goal_session = {"history_lock": threading.RLock(), "running": False}+ server._run_post_turn_followups("r", "s", goal_session, {}, "keep going")+ assert goal_session["running"] is False+ assert not dispatched- from types import SimpleNamespace- from tools import bot_live_delivery-- monkeypatch.setattr(bot_live_delivery, "has_mailbox", lambda home: True)- monkeypatch.setattr(bot_live_delivery, "find_canonical_live_owner", lambda home: {- "lease_id": "l", "live_session_id": "s", "session_id": "stored"})- monkeypatch.setattr(bot_live_delivery, "claim_pending_delivery", lambda *a: pytest.fail("retiring backend claimed a delivery"))- mailbox_session = {"history_lock": threading.RLock(), "agent": object(), "session_key": "stored",- "active_session_lease": SimpleNamespace(lease_id="l", released=False)}- assert server._poll_bot_live_delivery_once("s", mailbox_session) is False+ assert fence.cancel(token) == {"ok": True}+ assert server._notif_claim_turn(session) is True+ assert session["running"] is Truediff --cc tools/async_delegation.pyindex b474741ba07,65186f44e5b..0aaf70e675a--- a/tools/async_delegation.py+++ b/tools/async_delegation.py@@@ -235,9 -228,8 +239,9 @@@ def _recovered_results(task: Dict[str,def recover_abandoned_delegations() -> int:"""Classify records whose owning process disappeared as outcome unknown; children a multi-child unit had alreadyrecorded (``record_unit_child``) are replayed with their real results."""+ require_ledger_owner()try:- from gateway.status import _pid_exists, get_process_start_time+ from gateway.status import _pid_exists, get_process_start_time, start_time_fingerprints_matchexcept Exception:return 0now, recovered = time.time(), 0@@@ -620,17 -614,20 +645,23 @@@ def _dispatch_admittedfinally:_finalize(delegation_id, result, status)+ from hermes_cli.backend_retirement import retirement++ # The outer dispatch reservation prevents a freeze during this handoff. Retain a worker+ # reservation too: the stall monitor may finalize its registry record before it really exits.+ retirement.acquire()try:- # Propagate the dispatching profile so the detached child resolves get_hermes_home() correctly.- executor.submit(propagate_context_to_thread(_worker))+ future = executor.submit(propagate_context_to_thread(_worker))+ future.add_done_callback(lambda _: retirement.release())except Exception as exc: # pragma: no cover — pool submit failure is rare+ retirement.release()with _records_lock:_records.pop(delegation_id, None)- with _DB_LOCK, _transaction() as conn:- conn.execute("DELETE FROM async_delegations WHERE delegation_id=?", (delegation_id,))+ if remote := worker_ledger():+ remote.unscheduled(delegation_id)+ else:+ with _DB_LOCK, _transaction() as conn:+ conn.execute("DELETE FROM async_delegations WHERE delegation_id=?", (delegation_id,))return {"status": "rejected", "error": f"Failed to schedule async delegation{label}: {exc}"}if progress_fn is not None:_ensure_stale_monitor()diff --cc tools/bot_live_delivery.pyindex a93dfdcba47,7372b3cf6d1..8da2846f824--- a/tools/bot_live_delivery.py+++ b/tools/bot_live_delivery.py@@@ -243,11 -294,53 +278,60 @@@ def complete_deliverydef read_delivery_result(profile_home: Path | str, delivery_id: str) -> dict[str, Any] | None:"""Read admission/claim/terminal state without waiting or deleting its receipt."""- return _read(_root(profile_home) / f"{_delivery_id(delivery_id)}.json")+ record = _read(_root(profile_home) / f"{_delivery_id(delivery_id)}.json")+ if record is not None and record.get('admission_id'):+ home = Path(profile_home).resolve()+ # The authority compares the stored author to the retry payload; omitting it is a conflict.+ return authority_delivery(home, dict(id=delivery_id,+ profile=home.name if home.parent.name == 'profiles' else 'default', message=record['message'],+ **({'author': dict(record['author'])} if record.get('author') else {})))+ return record+++ _PENDING = ("queued", "claimed")+ _POLL_SECONDS = 0.5+++ def await_delivery(+ profile_home: Path | str, delivery_id: str, timeout: float | None,+ *, should_stop: Callable[[], bool] | None = None,+ ) -> dict[str, Any] | None:+ """Poll a receipt until the owner settles it, ``timeout`` lapses, or ``should_stop`` says so.++ Every transport that hands a turn to a live Bot Chat owner (local ``message_agent``, the+ Desktop relay, ``hermes peer dm`` and ``hermes peer run``) waits on the same receipt; keeping+ the loop here is what stops the lanes drifting (one lane returned a receipt sentence instead+ of the reply, two never waited at all). Returns the last record read — still pending when the+ budget lapsed, None when the receipt was never readable.+ """+ deadline = None if timeout is None else time.monotonic() + timeout+ while True:+ record = read_delivery_result(profile_home, delivery_id)+ if record is None or record["status"] not in _PENDING:+ return record+ if should_stop is not None and should_stop():+ return record+ remaining = None if deadline is None else deadline - time.monotonic()+ if remaining is not None and remaining <= 0:+ return record+ time.sleep(_POLL_SECONDS if remaining is None else min(_POLL_SECONDS, remaining))+++ async def await_delivery_async(+ profile_home: Path | str, delivery_id: str, timeout: float | None,+ *, should_stop: Callable[[], bool] | None = None,+ ) -> dict[str, Any] | None:+ """``await_delivery`` for an event loop: never blocks a worker thread for the whole budget."""+ import asyncio++ deadline = None if timeout is None else time.monotonic() + timeout+ while True:+ record = await asyncio.to_thread(read_delivery_result, profile_home, delivery_id)+ if record is None or record["status"] not in _PENDING:+ return record+ if should_stop is not None and should_stop():+ return record+ remaining = None if deadline is None else deadline - time.monotonic()+ if remaining is not None and remaining <= 0:+ return record+ await asyncio.sleep(_POLL_SECONDS if remaining is None else min(_POLL_SECONDS, remaining))diff --cc tools/bot_mode_dm.pyindex 7cc9efd6c69,c6aebeb9656..4915e4f2f71--- a/tools/bot_mode_dm.py+++ b/tools/bot_mode_dm.py@@@ -180,10 -201,10 +201,10 @@@ def message_agent_tool(target: str = ""home = _agent_home(agent)try:from tools.bot_mode_probe import (- BOT_CHAT_TITLE, _handle, _hermes_root, _peers, _profile_name as _self_profile_name, _roster,- is_bot_mode_managed,+ BOT_CHAT_TITLE, _display_name, _handle, _hermes_root, _peers, _profile_name as _self_profile_name,+ _roster, is_bot_mode_managed,)- from tools.bot_relay import BOT_CHAT_TURN_ARGS, _hermes_cli+ from tools.bot_relay import _hermes_cliif _session_title(agent) != BOT_CHAT_TITLE:return _err("message_agent is only available in a Bot Mode 'Bot Chat' session. "@@@ -386,6 -408,66 +410,12 @@@ def _delivery_lock(argv: list[str], *,return acquire_turn_lock(_hermes_root(Path(_default_home())), argv[2])-def _run_local_turn(argv: list[str], dm_file: str, *, env: Optional[dict[str, str]] = None) -> int:- """One Bot Chat turn via ``--query-file`` (plus one policy-gated retry); re-emits- the transport's streams and returns its exit code. Transient failures re-run the- same session; a context_overflow re-run lets the retried turn's pre-API compaction- compact the transcript first (no fresh session is ever minted). Auth/quota/config never retry."""-- def _turn(turn_env=env):- return subprocess.run([*argv, "--query-file", dm_file], check=False, stdin=subprocess.DEVNULL,- capture_output=True, text=True, env=turn_env)-- proc = _turn()- if proc.returncode != 0:- from tools.bot_failure_reasons import RETRY_NONE, classify_agent_error, retry_action, turn_failure_text- from tools.bot_relay import retry_turn_env-- # The re-run replays the same session and payload; the failed attempt already persisted the- # user row, so the retried process is told to resume it (RESUME_UNANSWERED_TURN_ENV).- if retry_action(classify_agent_error(turn_failure_text(proc.stdout, proc.stderr))) != RETRY_NONE:- proc = _turn(retry_turn_env(env))- stderr_text = proc.stderr or ""- reason = next((line.removeprefix("hermes-refusal-reason: ").strip()- for line in stderr_text.splitlines()- if line.startswith("hermes-refusal-reason: ")), None)- # A code wins over prose, including unknown codes from newer CLIs.- # Only older CLIs without a marker need the historical wording fallback.- refused_not_owned = (reason == "SESSION_NOT_OWNED" if reason is not None- else "already has a live owner" in stderr_text)- if proc.returncode != 0 and refused_not_owned:- # The target's Bot Chat is held live by another surface (Desktop); the turn- # never ran — tell the sender plainly instead of leaking a raw lease error.- # See #100523.- who = argv[argv.index("-p") + 1] if "-p" in argv[:-1] else "the teammate"- print(json.dumps({- "error": f"Delivery failed: @{who}'s Bot Chat is open on another "- "surface right now, so your message was NOT delivered. Try again later.",- "reason": "target_busy",- }))- return 1- # Re-emit the transport's streams: stdout is the reply text the- # completion notification carries back to the sending agent. A successful bare- # silence marker is a delivery decision (same rule as the gateway and the live- # Bot Chat completion): the turn stays in the target's transcript, the sender- # never sees the marker as prose.- from gateway.response_filters import is_intentional_silence_response- reply = proc.stdout or ""- if proc.returncode == 0 and is_intentional_silence_response(reply):- reply = ""- for stream, text in ((sys.stdout, reply), (sys.stderr, proc.stderr)):- if text:- stream.write(text)- stream.flush()- return proc.returncode--+ def _dm_delivery_id(dm_file: "str | os.PathLike") -> str:+ """One delivery id per DM file: the dispatch ack, the live-owner intent and every retry+ of the runner derive it the same way, so the sender can correlate all of them."""+ return hashlib.sha256(str(Path(dm_file).resolve()).encode()).hexdigest()++def _admit_live_dm(profile_home: Path | None, dm_file: str, author: Optional[dict] = None) -> dict | None:"""Pin intent before admission; retries may inspect, never change transport."""from tools.bot_live_delivery import deliver_to_live_owner, find_canonical_live_owner, read_delivery_result@@@ -399,9 -481,9 +429,9 @@@assert profile_home is not Noneowner = find_canonical_live_owner(profile_home)if owner is None:- return None+ raise ValueError("canonical Bot Chat target is unavailable; no local fallback")intent = dict(owner=owner, message=Path(dm_file).read_text(encoding="utf-8"),- delivery_id=hashlib.sha256(str(Path(dm_file).resolve()).encode()).hexdigest(),+ delivery_id=_dm_delivery_id(dm_file),**({"author": author} if author else {}))try:fd = os.open(intent_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)diff --cc tools/bot_relay.pyindex eb2ced170a7,689effed530..7491873a4b5--- a/tools/bot_relay.py+++ b/tools/bot_relay.py@@@ -49,8 -49,16 +49,15 @@@ DESKTOP_DELIVER_SETTLEMENT_MARGIN_SECONDESKTOP_DELIVER_TIMEOUT_SECONDS = (TURN_WAIT_SECONDS_FALLBACK + TURN_ATTEMPT_TIMEOUT_SECONDS * TURN_MAX_ATTEMPTS + DESKTOP_DELIVER_SETTLEMENT_MARGIN_SECONDS)- # The Desktop posts its own timeout reply at that deadline, so the waiter must still be watching then.- REPLY_WAIT_SECONDS = DESKTOP_DELIVER_TIMEOUT_SECONDS + 60-# A claimed envelope still unanswered this long after its claim was taken by a Desktop that died-# before ``bot_relay.deliver``; the next drain re-offers it, once. The longest a LIVE delivery can-# be in flight without a reply on disk is the Desktop's own deliver deadline (it posts a-# ``delivery_timeout`` reply when that passes, and the gateway-side hold — lock wait + the turn-# attempts — ends before it by construction), so past that point plus posting headroom the silence-# is provably the Desktop's death, not a slow turn. tests/tools/test_bot_relay.py pins the order.++# A claimed envelope is replayed on every drain until its reply lands (``_replay_unanswered``); the++# budgets below only bound how long the sender-side waiter keeps watching. The longest a LIVE delivery++# can be in flight without a reply on disk is the Desktop's own deliver deadline (it posts a++# ``delivery_timeout`` reply when that passes), so a second delivery of a replayed envelope can start++# no earlier than that plus posting headroom. tests/tools/test_bot_relay.py pins the order.+ REOFFER_AFTER_SECONDS = DESKTOP_DELIVER_TIMEOUT_SECONDS + 60-# The waiter must outlive the Desktop's timeout reply for the first delivery AND for the one-# re-offered delivery: re-offer window + a whole deliver budget + posting headroom.++# The waiter must outlive the Desktop's timeout reply for the first delivery AND for one replayed++# delivery: replay window + a whole deliver budget + posting headroom.+ REPLY_WAIT_SECONDS = REOFFER_AFTER_SECONDS + DESKTOP_DELIVER_TIMEOUT_SECONDS + 60# Envelopes/replies older than this are stale artifacts (Desktop closed) and are swept.STALE_AFTER_SECONDS = 6 * 3600# Only a recent roster is authoritative for the fail-fast offline check: the@@@ -271,20 -363,71 +345,57 @@@ def claim_pending_envelopes(root: Pathclaimed = base / CLAIMED_DIR / path.namewith contextlib.suppress(OSError, ValueError):os.replace(path, claimed) # atomic claim- out.append(json.loads(claimed.read_text(encoding="utf-8")))- seen = {row['id'] for row in out}- for path in sorted((base / CLAIMED_DIR).glob('*.json')):- os.utime(claimed, (now, now)) # the re-offer window counts from the claim, not the enqueue+ envelope = json.loads(claimed.read_text(encoding="utf-8"))+ if not isinstance(envelope, dict):+ raise ValueError(f"expected a JSON object, got {type(envelope).__name__}")+ out.append(envelope)++ seen = {row["id"] for row in out}++ out.extend(_replay_unanswered(root, base, seen, now))+ return out++-def _reoffer_unanswered(root: Path | str, base: Path, ttl: float, now: float) -> list[dict]:- """``claimed/`` envelopes unanswered ``REOFFER_AFTER_SECONDS`` after their claim, at most once each.-- The claim is the Desktop's: one that disconnects between ``outbox.drain`` and ``bot_relay.deliver``- leaves the envelope here with no reply, silent until the waiter's deadline and then swept, while- the reconnected Desktop's drains see an empty outbox (#111021, #111207). Bounds, in check order:++def _replay_unanswered(root: Path | str, base: Path, seen: set, now: float) -> list[dict]:++ """``claimed/`` canonical envelopes whose reply has not landed yet, replayed on EVERY drain.+- * ``created_at + REPLY_WAIT_SECONDS`` passed with no reply — the waiter is gone (or about to be);- a ``delivery_timeout`` reply is written so it learns, and the envelope is never handed out again.- * already re-offered (``reoffered_at`` stamped on the envelope) — one extra delivery per message,- never a turn loop against a target nobody is listening for.- * ``bot_mode.envelope_ttl_seconds`` applies to the re-offer leg exactly as to the outbox: the- message is back in the queue from ``claim + REOFFER_AFTER_SECONDS``; a drain that comes ``ttl``- later than that refuses it with ``queued_expired``.++ A drained envelope is not "delivered": its stable id is handed out again until the target's++ terminal reply is written under that id, so a Desktop that disconnects between ``outbox.drain``++ and ``bot_relay.deliver`` (#111021, #111207) or loses the drain result cannot drop the DM. The++ replay is safe because ``bot_relay.deliver`` forwards the SAME id to the target profile's++ authority, which admits one turn per id and answers a retry with the existing record — never a++ second turn. Once ``created_at + REPLY_WAIT_SECONDS`` passes with no reply the waiter is gone++ (or about to be): a ``delivery_timeout`` reply is written so it learns, and the envelope is++ never handed out again.+ """+ out: list[dict] = []+ for path in sorted((base / CLAIMED_DIR).glob("*.json"), key=_queued_at):+ if (base / REPLIES_DIR / path.name).exists():+ continuewith contextlib.suppress(OSError, ValueError):- envelope = json.loads(path.read_text(encoding='utf-8'))- if (envelope.get('canonical_delivery_v1') is True and envelope['id'] not in seen- and not (base / REPLIES_DIR / path.name).exists()):- out.append(envelope)- claimed_at = path.stat().st_mtime+ envelope = json.loads(path.read_text(encoding="utf-8"))+ if not isinstance(envelope, dict):+ raise ValueError(f"expected a JSON object, got {type(envelope).__name__}")++ if envelope.get("canonical_delivery_v1") is not True or envelope.get("id") in seen:++ continue+ env_id = str(envelope.get("id") or "")+ label = f"@{envelope.get('target_handle') or '?'} on {envelope.get('target_connection') or '?'}"- created = float(envelope.get("created_at") or claimed_at)++ created = float(envelope.get("created_at") or path.stat().st_mtime)+ if now - created > REPLY_WAIT_SECONDS:+ write_reply(root, env_id, reason="delivery_timeout", error=(+ f"no reply from {label} within {REPLY_WAIT_SECONDS}s of sending — the Desktop picked "+ "the message up but never reported a delivery. It will not be retried; resend if it matters."))+ continue- if envelope.get("reoffered_at"):- continue- queued_for = now - claimed_at - REOFFER_AFTER_SECONDS- if queued_for < 0:- continue- if ttl > 0 and queued_for > ttl:- write_reply(root, env_id, reason="queued_expired", error=(- f"re-queued message to {label} expired after {ttl}s waiting for the Desktop to drain it "- "again — it was NOT delivered. Resend once the Desktop reconnects."))- continue- envelope["reoffered_at"] = int(now)- _atomic_write_json(path, envelope)+ out.append(envelope)return outdef write_reply(root: Path | str, envelope_id: str, *, reply: str = "", error: str = "", reason: str = "") -> Path:"""Persist the relayed reply (or delivery error) for the waiter. ``reason`` (typed- code, ``tools.bot_failure_reasons``) is classified from ``error`` when omitted."""+ code, ``tools.bot_failure_reasons``) is classified from ``error`` when omitted.++ Idempotent by envelope id — the first settled reply stands, error or not. That is safe because- two deliveries of one envelope never overlap: ``_reoffer_unanswered`` waits past the Desktop's own- deliver deadline (``REOFFER_AFTER_SECONDS``), so by the time a second delivery can start, the first- has either replied (and the waiter may already have read it) or provably died without one. A- later write is therefore a duplicate or a bookkeeping timeout, never a truer answer."""++ a replayed envelope (``_replay_unanswered``) carries the SAME id into the target authority,++ which admits one turn per id, so a later write is a duplicate or a bookkeeping timeout, never++ a truer answer."""base = _ensure_dirs(root)safe = str(envelope_id or "").strip()if not re.match(r"^[0-9a-f]{32}$", safe):diff --cc tools/mcp_tool_discovery.pyindex 4a53fc039ba,1dd1eb9b169..3a7343a0942--- a/tools/mcp_tool_discovery.py+++ b/tools/mcp_tool_discovery.py@@@ -452,10 -557,8 +562,11 @@@ def discover_mcp_tools(allowed_mcp_namelist simply don't match); ``None`` spawns every configured server. Used by``hermes -z -t <toolsets>`` to skip cold-starting servers the caller doesn't need (10-60seach); it only affects which servers start, not which names ``-t`` validation can see."""+ from agent.safe_worker_policy import safe_worker_enabled+ if safe_worker_enabled():+ return []- servers = _config._load_mcp_config()+ with _owner_secret_scope():+ servers = _config._load_mcp_config()if not servers:logger.debug("No MCP servers configured")return []diff --cc tui_gateway/agent_factory.pyindex 5b21d86a298,00000000000..cca985c013fmode 100644,000000..100644--- a/tui_gateway/agent_factory.py+++ b/tui_gateway/agent_factory.py@@@ -1,556 -1,0 +1,628 @@@+"""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- cfg = _load_cfg().get("model") or {}++ 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+++# Bare billing buckets are not routable provider identities; restoring one as a session provider override+# breaks resume. ``openrouter`` is deliberately NOT in this set (fully routable; agent_init's gate is a different set).+# (agent_init's fail-fast gate is a DIFFERENT set that also skips "openrouter" — there it means "default+# route, don't fail fast", not "unroutable".) ``openrouter`` is deliberately excluded here — it is a fully+# routable provider with its own API key and base_url. Sessions that used OpenRouter store+# ``billing_provider="openrouter"``; dropping it forces resume to the current global model (e.g. a custom+# endpoint), which is the wrong provider for the stored model. See #57588.+++def _is_routable_provider(provider: str) -> bool:+ with contextlib.suppress(Exception):+ from hermes_cli.runtime_provider import is_routable_provider+ return is_routable_provider(provider)+ return False+++def _overrides_have_routable_provider(overrides: dict) -> bool:+ """Whether persisted runtime overrides still name a routable provider (renamed/removed → "Unknown+ provider" at agent init). Empty = NOT routable, so the caller falls back to the session's picked model."""+ provider = str(overrides.get("provider_override") or "").strip()+ if not provider:+ provider = str((overrides.get("model_override") or {}).get("provider") or "").strip()+ return bool(provider) and _is_routable_provider(provider)+++def _parse_model_config(raw, *, quiet: bool = False) -> dict:+ """A row's ``model_config`` (dict or JSON text) as a dict; ``{}`` when absent/invalid."""+ if isinstance(raw, dict):+ return raw+ if isinstance(raw, str) and raw.strip():+ try:+ parsed = json.loads(raw)+ return parsed if isinstance(parsed, dict) else {}+ except Exception:+ if not quiet:+ raise+ logger.debug("failed to parse stored session model_config", exc_info=True)+ return {}++++def _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 are exempt and rebuild from the member profile's CURRENT config (a stale provider pin left- room bots "out of Nous credits" after a profile switch); signals: ``room_plumbing`` /- ``follow_profile_config`` markers, the legacy hidden + "Group:" title, the title exactly "Bot Chat"."""++ 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()- if (model_config.get("room_plumbing") or (row.get("hidden") and _row_title.startswith("Group:"))- or model_config.get("follow_profile_config") or _row_title == "Bot Chat"):++ 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 = {}+ field = lambda k: str(model_config.get(k) or "").strip()+ model = str(row.get("model") or model_config.get("model") or "").strip()+ # ``billing_provider`` is only the billing bucket — for a custom endpoint the bare class "custom", which+ # agent_init treats as non-routable. Only restore an explicit provider; else resume uses the configured default.+ provider = field("provider")+ billing_provider = str(model_config.get("billing_provider") or row.get("billing_provider") or "").strip()+ if not provider and billing_provider.lower() not in _BARE_BILLING_PROVIDERS:+ provider = billing_provider+ base_url, api_mode, service_tier = field("base_url"), field("api_mode"), field("service_tier")+ reasoning_config = model_config.get("reasoning_config")+ # Heal a stale provider persisted by an older build (renamed/removed custom provider → "Unknown provider"):+ # recover ``custom:<name>`` from the stored base_url, then from the entry serving the model; else drop it.+ if provider and not _is_routable_provider(provider):+ healed = None+ try:+ from hermes_cli.runtime_provider import canonical_custom_identity+ healed = canonical_custom_identity(base_url=base_url or None, model=model or None)+ except Exception:+ logger.debug("custom provider identity recovery failed", exc_info=True)+ if healed:+ logger.info("healed stale session provider %r to %r", provider, healed)+ provider = healed+ base_url = "" # the healed identity owns a registered endpoint; the snapshot URL must not override it+ else:+ provider = ""+ if model:+ # Same dict-shaped override live /model switches use, so a DB-restored session keeps custom endpoint+ # metadata across resume and rebuilds (/new). Raw api_key is never persisted/restored.+ overrides["model_override"] = {+ "model": model, "provider": provider or None, "base_url": base_url or None, "api_mode": api_mode or None}+ if provider:+ overrides["provider_override"] = provider+ if isinstance(reasoning_config, dict):+ overrides["reasoning_config_override"] = reasoning_config+ if service_tier: # None = "inherit the profile" at _make_agent; "" = real override "no priority tier"+ overrides["service_tier_override"] = "" if service_tier.lower() == "normal" else service_tier+ return overrides+++def _runtime_model_config(agent, existing: dict | None = None) -> dict:+ """Merge the agent's CURRENT runtime identity onto the row's persisted ``model_config``. Falsy agent+ attributes DELETE the key rather than skip the write: resume reads provider/endpoint from this JSON+ (model column written separately), so a stale provider would route the resumed chat to the wrong endpoint."""+ config = dict(existing or {})+ attr = lambda k: str(getattr(agent, k, "") or "").strip()+ model, provider, base_url = attr("model"), attr("provider"), attr("base_url")+ if provider.lower() == "custom":+ # ``agent.provider`` resolves every named custom entry to the literal "custom", losing the entry+ # identity (api_key is never persisted): recover ``custom:<name>`` from the endpoint URL.+ try:+ from hermes_cli.runtime_provider import canonical_custom_identity+ provider = canonical_custom_identity(base_url=base_url, model=model or None) or provider+ except Exception:+ logger.debug("custom provider identity lookup failed", exc_info=True)+ reasoning_config = getattr(agent, "reasoning_config", None)+ live = {+ "model": model, "provider": provider, "base_url": base_url, "api_mode": attr("api_mode"),+ # An empty dict is still a real (present) reasoning config.+ "reasoning_config": reasoning_config if isinstance(reasoning_config, dict) else None,+ "service_tier": getattr(agent, "service_tier", None),+ }+ for key, value in live.items():+ if value or isinstance(value, dict):+ config[key] = value+ else:+ config.pop(key, None)+ return config+++def _persist_live_session_runtime(session: dict | None) -> None:+ """Persist active session runtime so future resumes restore the same footer."""+ live = _live_session_agent_db(session)+ if live is None:+ return+ agent, session_key, db = live+ try:+ row = db.get_session(session_key) or {}+ model_config = _runtime_model_config(agent, _parse_model_config(row.get("model_config")))++ if 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)+++_SERVICE_TIER_ALIASES = {"fast": "priority", "priority": "priority", "on": "priority", "auto": "auto", "cold": "cold"}+++def _load_service_tier() -> str | None:+ raw = str((_load_cfg().get("agent") or {}).get("service_tier", "") or "").strip().lower()+ return _SERVICE_TIER_ALIASES.get(raw)+++def _load_provider_routing() -> dict:+ """OpenRouter ``provider_routing`` prefs (gateway/CLI parity — without them OpenRouter picks an effectively random provider)."""+ with contextlib.suppress(Exception):+ return _load_cfg().get("provider_routing", {}) or {}+ return {}+++def _load_show_reasoning() -> bool:+ # Fallback True — keep in sync with DEFAULT_CONFIG display.show_reasoning (no DEFAULT_CONFIG merge here).+ return bool(_display_cfg().get("show_reasoning", True))+++def _load_memory_notifications() -> str:+ """``display.memory_notifications`` (``off`` / ``on`` default / ``verbose``; bool normalized) — gates the+ "💾 Self-improvement review" summary (gateway/CLI parity)."""+ raw = _display_cfg().get("memory_notifications")+ if isinstance(raw, bool):+ return "on" if raw else "off"+ return str(raw).lower() if raw else "on"+++_TOOL_PROGRESS_MODES = frozenset({"off", "new", "all", "verbose"})+++def _load_tool_progress_mode() -> str:+ env = os.environ.get("HERMES_TUI_TOOL_PROGRESS", "").strip().lower()+ if env in _TOOL_PROGRESS_MODES:+ return env+ raw = _display_cfg().get("tool_progress", "all")+ if isinstance(raw, bool):+ return "all" if raw else "off"+ mode = str(raw or "all").strip().lower()+ return mode if mode in _TOOL_PROGRESS_MODES else "all"+++def _gui_surface_toolsets(platform: str) -> set[str]:+ """Toolsets that exist because of the CLIENT (both off ``_HERMES_CORE_TOOLS``; this is the one gate).+ ``platform`` is the SESSION's source, never a process env var: the desktop may drive a URL/cloud+ backend where ``HERMES_DESKTOP`` is unset (AGENTS.md surface rule)."""+ return {"project", "desktop_ui"} if platform == "desktop" else {"project"}++++def _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."""++ 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]++ return [*kept, *sorted((surface | granted) - set(kept))]+++++def _tui_notice(text: str) -> None:+ print(text, file=sys.stderr, flush=True)+++def _resolve_explicit_toolsets(explicit: list[str], validate_toolset) -> list[str] | None | bool:+ """Resolve a HERMES_TUI_TOOLSETS pin: list, None for "all", False when nothing was valid."""+ built_in = [name for name in explicit if validate_toolset(name)]+ unresolved = [name for name in explicit if name not in built_in]+ if unresolved:+ try:+ from hermes_cli.plugins import discover_plugins+ discover_plugins()+ plugin_valid = [name for name in unresolved if validate_toolset(name)]+ except Exception:+ plugin_valid = []+ built_in.extend(plugin_valid)+ unresolved = [name for name in unresolved if name not in plugin_valid]+ if any(name in {"all", "*"} for name in built_in):+ if ignored := [name for name in explicit if name not in {"all", "*"}]:+ _tui_notice(f"[tui] HERMES_TUI_TOOLSETS=all enables every toolset; ignoring additional entries: {', '.join(ignored)}")+ return None+ if not unresolved:+ return built_in+ try: # (enabled, disabled) MCP server names from raw config; both empty on any failure+ from hermes_cli.config import read_raw_config- from hermes_cli.tools_config import _parse_enabled_flag++ 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 = _parse_enabled_flag(server_cfg.get("enabled", True), default=True)++ 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."""+ session_platform = platform or _resolve_session_platform()+ explicit = [item.strip() for item in os.environ.get("HERMES_TUI_TOOLSETS", "").split(",") if item.strip()]+ fallback_notice = None+ if not explicit:+ with contextlib.suppress(Exception):+ from agent.coding_context import coding_selection+ selection = coding_selection(platform=session_platform)+ if selection is not None:- return sorted({*selection, *_gui_surface_toolsets(session_platform)})++ 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:- return resolved++ # 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)+ fallback_notice = "[tui] no valid HERMES_TUI_TOOLSETS entries; using configured CLI toolsets"+ try:+ from hermes_cli.config import load_config+ from hermes_cli.tools_config import _get_platform_tools+ cfg = load_config()+ # include_default_mcp_servers=True is the runtime variant (the agent must be able to call+ # default MCP servers); the config-editing variant would silently drop MCP tools from the TUI.+ # Passing ``False`` here is the config-editing variant — used when we need to persist a toolset list+ # without baking in implicit MCP defaults. Using the wrong variant at agent creation time makes MCP+ # tools silently missing from the TUI. See PR #3252 for the original design split.+ enabled = _get_platform_tools(cfg, "cli", include_default_mcp_servers=True)+ if fallback_notice is not None:+ _tui_notice(fallback_notice)- return sorted(enabled | _gui_surface_toolsets(session_platform)) if enabled else None++ return sorted(_with_session_toolsets(enabled, session_platform)) if enabled else None+ except Exception:+ if fallback_notice is not None:+ _tui_notice("[tui] no valid HERMES_TUI_TOOLSETS entries and configured CLI toolsets could not be loaded; enabling all toolsets")+ return None+++def _session_tool_progress_mode(sid: str) -> str:+ return str(_sessions.get(sid, {}).get("tool_progress_mode", "all") or "all")+++def _session_verbose(sid: str) -> bool:+ return _session_tool_progress_mode(sid) == "verbose"+++def _tool_progress_enabled(sid: str) -> bool:+ return _session_tool_progress_mode(sid) != "off"+++def _tool_lifecycle_required_for_ui(name: str) -> bool:+ """Interactive UI, not optional chrome: Desktop renders clarify / connection cards from the tool-call part."""+ return name in ("clarify", "manage_connections", "setup_mcp")++def _resolve_runtime_with_fallback(resolve_kwargs: dict | None = None) -> _RuntimeFallbackResolution:+ """Resolve the primary runtime or one complete provider/model fallback. Provider-only fallback entries+ are skipped so the unavailable primary model can never leak into a different runtime."""+ from hermes_cli.auth import AuthError+ from hermes_cli.runtime_provider import resolve_runtime_provider+ try:+ return _RuntimeFallbackResolution(resolve_runtime_provider(**(resolve_kwargs or {})), None, False)+ except AuthError as primary_exc:+ for entry in _load_fallback_model() or []:+ fb_provider = str(entry.get("provider") or "").strip() if isinstance(entry, dict) else ""+ fb_model = str(entry.get("model") or "").strip() if isinstance(entry, dict) else ""+ if not fb_provider or not fb_model:+ continue+ try:+ from hermes_cli.fallback_config import 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 auth failed (%s), falling back to %s model %s", primary_exc, fb_provider, fb_model)++ "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.++ primary_provider = requested_provider or (_load_cfg().get("model") or {}).get("provider")++ 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+ skills_prompt, loaded_skills, missing_skills = build_preloaded_skills_prompt(startup_skills, task_id=task_id)+ if missing_skills:+ missing_display = ", ".join(missing_skills)+ if not loaded_skills:+ raise ValueError(f"Unknown skill(s): {missing_display}")+ logger.warning("Unknown skill(s) requested, skipping: %s. Continuing with: %s. "+ "List available skills with `hermes skills list`.", missing_display, ", ".join(loaded_skills))+ if skills_prompt:+ system_prompt = "\n\n".join(part for part in (system_prompt, skills_prompt) if part).strip()+ return system_prompt+++def _make_agent(+ sid: str, key: str, session_id: str | None = None, session_db=None,+ model_override: dict | str | None = None, provider_override: str | None = None,+ reasoning_config_override: dict | None = None, service_tier_override: str | None = None,+ platform_override: str | None = None, context_cwd_is_launch_artifact: bool | None = None,+ 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),+ # 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=is_truthy_value(os.environ.get("HERMES_TUI_CHECKPOINTS")),+ pass_session_id=is_truthy_value(os.environ.get("HERMES_TUI_PASS_SESSION_ID")),+ skip_context_files=ignore_rules, skip_memory=ignore_rules, fallback_model=_load_fallback_model(),+ **_agent_cbs(sid))+ if context_cwd_is_launch_artifact is None:+ 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/command_discovery.pyindex 8e00db90e6e,00000000000..b07751a462dmode 100644,000000..100644--- a/tui_gateway/command_discovery.py+++ b/tui_gateway/command_discovery.py@@@ -1,258 -1,0 +1,276 @@@+"""Shared slash discovery data; no server import or session execution runtime.++Transport wrappers own authentication and profile binding before calling these+builders. Keep the legacy catalog and completion semantics identical here.+"""+import contextlib+from importlib import import_module+import logging++logger = logging.getLogger(__name__)++_TUI_HIDDEN: frozenset[str] = frozenset({"sethome", "set-home", "commands", "approve", "deny"})++_TUI_EXTRA: list[tuple[str, str, str]] = [+ ("/density", "Toggle compact display mode", "TUI"),+ ("/logs", "Show recent gateway log lines", "TUI"),+ ("/mouse", "Set mouse tracking preset [on|off|toggle|wheel|buttons|all]", "TUI"),+ ("/sessions", "Switch between live TUI sessions", "TUI"),+]++_SLASH_EXTRAS = [+ ("/density", "Toggle compact display mode"), ("/details", "Control agent detail visibility"),+ ("/logs", "Show recent gateway log lines"),+ ("/mouse", "Set mouse tracking preset [on|off|toggle|wheel|buttons|all]")]+++def _item(text: str, meta: str, display: str | None = None) -> dict:+ return {"text": text, "display": display if display is not None else text, "meta": meta}+++def _skill_usage_lookup():+ """``(usage, origin)`` callables for the skill catalog: activity count (use + view + patch) and+ "hub" / "bundled" / "local" (``/api/skills`` ``provenance``, "local" spelled "agent"). Failure → 0 / "local"."""+ try:+ from tools.skill_usage import (+ _read_bundled_manifest_names, _read_hub_installed_names, activity_count, load_usage)+ records, bundled, hub = load_usage(), _read_bundled_manifest_names(), _read_hub_installed_names()+ except Exception as e:+ logger.debug("skill usage lookup unavailable: %s", e)+ return (lambda _name: 0), (lambda _name: "local")++ def usage(name: str) -> int:+ with contextlib.suppress(Exception):+ return activity_count(records.get(name) or {})+ return 0++ def origin(name: str) -> str:+ return "hub" if name in hub else "bundled" if name in bundled else "local"+ return usage, origin+++_SLASH_COMPLETION_LIMIT = 30+++def _rank_slash_completions(items: list[dict], usage, origin_of, *, browsing: bool, score_of=None) -> list[dict]:+ """Registry commands keep their order; only skills reorder: fuzzy ``score_of`` first, then most-used, then+ A-Z. The limit is spent PER KIND (a flat cut on a large install offered no skill at all). ``browsing``+ (bare ``/``) drops never-used bundled skills as noise; a typed query is SEARCHING — nothing pruned, only reordered."""+ def name_of(item: dict) -> str:+ return str(item.get("text", "")).strip().lstrip("/").lower()+ commands = [item for item in items if item.get("kind") != "skill"]+ skills = [item for item in items if item.get("kind") == "skill"]+ if browsing:+ skills = [item for item in skills if origin_of(name_of(item)) != "bundled" or usage(name_of(item)) > 0]+ skills.sort(key=lambda item: (+ *(() if score_of is None else (score_of(item),)), -usage(name_of(item)), name_of(item)))+ return commands[:_SLASH_COMPLETION_LIMIT] + skills[:_SLASH_COMPLETION_LIMIT]+++_DETAILS_SECTIONS = ("thinking", "tools", "subagents", "activity")+_DETAILS_MODES = ("hidden", "collapsed", "expanded")+++def _details_root_meta(candidate: str) -> str:+ if candidate in _DETAILS_SECTIONS:+ return "section override"+ return "cycle global mode" if candidate == "cycle" else "global mode"+++def _details_completions(text: str) -> list[dict] | None:+ """Argument completions for ``/details [section] [mode]``; None when ``text`` is not that command."""+ if not text.lower().startswith("/details"):+ return None+ stripped = text.strip()+ if stripped and not "/details".startswith(stripped.lower().split()[0]):+ return None+ body = text[len("/details") :].removeprefix(" ")+ parts = body.split()+ trailing = text.endswith(" ")+ root_candidates = (*_DETAILS_MODES, "cycle", *_DETAILS_SECTIONS)+ if not body or (not parts and trailing):+ lead = "" if trailing else " "+ return [_item(f"{lead}{c}", _details_root_meta(c)) for c in root_candidates]+ if len(parts) == 1 and not trailing:+ prefix = parts[0].lower()+ return [_item(c, _details_root_meta(c)) for c in root_candidates if c.startswith(prefix) and c != prefix]+ section = parts[0].lower() if parts else ""+ if section not in _DETAILS_SECTIONS:+ return []++ def section_meta(candidate: str) -> str:+ return f"clear {section} override" if candidate == "reset" else f"set {section}"+ mode_candidates = (*_DETAILS_MODES, "reset")+ if len(parts) == 1: # trailing space after the section+ return [_item(c, section_meta(c)) for c in mode_candidates]+ if len(parts) == 2 and not trailing:+ prefix = parts[1].lower()+ return [_item(c, section_meta(c)) for c in mode_candidates if c.startswith(prefix) and c != prefix]+ return []+++class _Catalog:+ """Accumulator for commands.catalog: ``pairs`` (every [key, desc]), ``canon`` (lowercase+ key/alias → canonical key), ``commands`` (key → desktop meta) and ordered categories."""++ def __init__(self) -> None:+ self.pairs: list[list[str]] = []+ self.canon: dict[str, str] = {}+ self.commands: dict[str, dict[str, str | None]] = {}+ self.cat_map: dict[str, list[list[str]]] = {} # insertion order = category order++ def add(self, key: str, desc: str, cat: str) -> None:+ self.canon[key.lower()] = key+ self.pairs.append([key, desc])+ self.cat_map.setdefault(cat, []).append([key, desc])+++def _catalog_registry(cat: _Catalog, module_loader) -> None:+ commands = module_loader("hermes_cli.commands")+ for cmd in commands.COMMAND_REGISTRY:+ meta = commands.command_desktop_meta(cmd)+ cat.commands.update({f"/{key}": dict(meta) for key in (cmd.name, *cmd.aliases)})+ if cmd.name in _TUI_HIDDEN or cmd.gateway_only:+ continue+ cat.add(f"/{cmd.name}", commands._build_description(cmd), cmd.category)+ for a in cmd.aliases:+ cat.canon[f"/{a}".lower()] = f"/{cmd.name}"+ for name, desc, category in _TUI_EXTRA:+ # Registry command/alias wins over a colliding TUI extra (e.g. /compact, /sessions).+ if name.lower() not in cat.canon:+ cat.add(name, desc, category)+++def _catalog_quick_commands(cat: _Catalog, load_cfg) -> None:+ qcmds = load_cfg().get("quick_commands", {}) or {}+ if not (isinstance(qcmds, dict) and qcmds):+ return+ cat.cat_map.setdefault("User commands", []) # category exists even when every entry is malformed+ for qname, qc in sorted(qcmds.items()):+ if not isinstance(qc, dict):+ continue+ qtype = qc.get("type", "")+ default_desc = {"exec": f"exec: {qc.get('command', '')}", "alias": f"alias → {qc.get('target', '')}"}+ desc = str(qc.get("description") or default_desc.get(qtype, qtype or "quick command"))+ cat.add(f"/{qname}", desc, "User commands")+++def _catalog_plugin_commands(cat: _Catalog, module_loader) -> None:+ plugin_cmds = module_loader("hermes_cli.plugins").get_plugin_commands() or {}+ if plugin_cmds:+ cat.cat_map.setdefault("Plugin commands", [])+ for pname, info in sorted(plugin_cmds.items()):+ key = f"/{pname}"+ if not isinstance(info, dict) or key.lower() in cat.canon:+ continue+ cat.add(key, str(info.get("description") or "Plugin command"), "Plugin commands")+ mode = info.get("argument_mode")+ if mode not in {"options", "text", "mixed"}:+ mode = "text" if str(info.get("args_hint") or "").strip() else None+ cat.commands[key] = {"argument_mode": mode, "desktop": None}++- def _catalog_skills(cat: _Catalog, skills: dict[str, dict], module_loader) -> None:- """Append skill pairs and fill ``skills`` = ``{key: {usage, origin}}`` (every consumer ranks by them)."""++def _catalog_skills(cat: _Catalog, skills: dict[str, dict], module_loader) -> str:++ """Append skill pairs and fill ``skills`` = ``{key: {usage, origin}}`` (every consumer ranks by them).++ Returns the one-line notice for skills whose name is a built-in command (no ``/<name>`` entry;++ ``agent.skill_commands`` guard), ``""`` when none."""+ usage, origin_of = _skill_usage_lookup()- for k, info in sorted(module_loader("agent.skill_commands").scan_skill_commands().items()):++ sc = module_loader("agent.skill_commands")++ for k, info in sorted(sc.scan_skill_commands().items()):+ cat.pairs.append([k, str(info.get("description", "Skill"))])+ name = str(info.get("name") or k.lstrip("/"))+ skills[k] = {"usage": usage(name), "origin": origin_of(name)}++ collision_note = getattr(sc, "skill_command_collision_note", None)++ if collision_note is None:++ return ""++ names = sorted(s["name"] for s in module_loader("tools.skills_tool")._find_all_skills())++ return "; ".join(filter(None, map(collision_note, names)))++- def command_catalog(load_cfg=None, module_loader=import_module) -> dict:++def command_catalog(load_cfg=None, module_loader=import_module, scope=None) -> dict:+ """Registry-backed slash metadata, categorized, no aliases. Discovery failures land in ``warning``- (skills' message wins, then quick commands', then plugins')."""++ (skills' message wins, then quick commands', then plugins'); only with no failure does it carry++ the built-in-name collision notice for skills that have no ``/<name>`` (empty when none). ``scope``++ is a context manager binding the calling session's profile home and workspace around skill++ discovery so project-local skills register for the repo the session is actually in (#114359)."""+ if load_cfg is None:+ from hermes_cli.config import load_config_readonly+ load_cfg = load_config_readonly+ cat = _Catalog()+ _catalog_registry(cat, module_loader)+ warning = ""+ try:+ _catalog_quick_commands(cat, load_cfg)+ except Exception as e:+ warning = f"quick_commands discovery unavailable: {e}"+ try:+ _catalog_plugin_commands(cat, module_loader)+ except Exception as e:+ warning = warning or f"plugin command discovery unavailable: {e}"+ skills: dict[str, dict] = {}+ try:- _catalog_skills(cat, skills, module_loader)++ with scope if scope is not None else contextlib.nullcontext():++ collision_note = _catalog_skills(cat, skills, module_loader) # always runs: skills must list even when a loader failed++ warning = warning or collision_note+ except Exception as e:+ warning = f"skill discovery unavailable: {e}"+ return {+ "pairs": cat.pairs, "sub": {k: v[:] for k, v in module_loader("hermes_cli.commands").SUBCOMMANDS.items()},+ "canon": cat.canon,+ "commands": cat.commands,+ "categories": [{"name": c, "pairs": rows} for c, rows in cat.cat_map.items()],+ "skills": skills, "skill_count": len(skills), "warning": warning}++- def slash_completions(text: str = "") -> dict:++def slash_completions(text: str = "", scope=None) -> dict:++ """``scope`` binds the calling session's profile and workspace around the skill/bundle lookups++ (home- and cwd-keyed) so the popup offers the project-local skills ``command.dispatch`` accepts++ for that session (#114359)."""+ if not text.startswith("/"):+ return {"items": []}+ from hermes_cli.commands_completion import SlashCommandCompleter+ from prompt_toolkit.document import Document+ from prompt_toolkit.formatted_text import to_plain_text+ from agent.skill_commands import get_skill_commands+ from agent.skill_bundles import get_skill_bundles++ with scope if scope is not None else contextlib.nullcontext():++ skill_commands, skill_bundles = dict(get_skill_commands()), dict(get_skill_bundles())+ completer = SlashCommandCompleter(- skill_commands_provider=lambda: get_skill_commands(), skill_bundles_provider=lambda: get_skill_bundles())++ skill_commands_provider=lambda: skill_commands, skill_bundles_provider=lambda: skill_bundles)+ # `kind` reaches the TUI as data (from the providers, not sniffed from ⚡/▣ glyphs):+ # skills/bundles are the only completions for an inline `/skill` typed mid-message.- skill_names = {key.lstrip("/").lower() for key in (*get_skill_commands(), *get_skill_bundles())}++ skill_names = {key.lstrip("/").lower() for key in (*skill_commands, *skill_bundles)}++ def to_items(doc: Document) -> list[dict]:+ # display/display_meta are FormattedText; the TUI contract is a plain string+ # (the raw list trips Ink's row layout into 1-char truncation).+ return [+ {+ "text": c.text, "display": to_plain_text(c.display) if c.display else c.text,+ "meta": to_plain_text(c.display_meta) if c.display_meta else "",+ "kind": "skill" if c.text.strip().lstrip("/").lower() in skill_names else "command"}+ for c in completer.get_completions(doc, None)]+ items = to_items(Document(text, len(text)))+ # Rank + bound while a `/token` is under the cursor (the one stage skills are+ # offered at); an argument stage (`/personality `) keeps its command's order.+ if text.rsplit(" ", 1)[-1].startswith("/"):+ score_of = None+ # Command-token stage: the completer only emits name-prefix matches, so merge in+ # catalog entries whose name SUBSTRING or DESCRIPTION words match (name outranks description).+ if " " not in text and len(text) > 1:+ from tui_gateway.slash_fuzzy import fuzzy_rank_slash_items, normalize_slash_search_query+ items, score_of = fuzzy_rank_slash_items(+ items, to_items(Document("/", 1)), normalize_slash_search_query(text))+ usage, origin_of = _skill_usage_lookup()+ items = _rank_slash_completions(items, usage, origin_of, browsing=text == "/", score_of=score_of)+ else:+ items = items[:_SLASH_COMPLETION_LIMIT]+ text_lower = text.lower()+ for extra_text, extra_meta in _SLASH_EXTRAS:+ if extra_text.startswith(text_lower) and not any(item["text"] == extra_text for item in items):+ items.append({**_item(extra_text, extra_meta), "kind": "command"})+ if (details_items := _details_completions(text)) is not None:+ return {"items": details_items, "replace_from": text.rfind(" ") + 1 if " " in text else len(text)}+ return {"items": items, "replace_from": text.rfind(" ") + 1 if " " in text else 1}++diff --cc tui_gateway/methods_bot_relay.pyindex b17417fcf95,b679a87f045..71086581cfb--- a/tui_gateway/methods_bot_relay.py+++ b/tui_gateway/methods_bot_relay.py@@@ -6,12 -6,15 +6,8 @@@ Chat delivery on the TARGET gateway, rethe SENDER gateway for its waiter). Plumbing: ``tools/bot_relay.py``; handlers are rebound ontoserver.py's globals (method_ctx.py) and reference ``_ok``/``_err`` bare."""-import contextlib--import os-import subprocessfrom pathlib import Path--# Defined beside the sender-side waiter budget so the two Python sides cannot drift (#93911).-from tools.bot_failure_reasons import delivery_failure_reason--from tools.bot_relay import TURN_ATTEMPT_TIMEOUT_SECONDS--from .method_ctx import HandlerRegistry_registry = HandlerRegistry()@@@ -54,39 -73,161 +50,57 @@@ def _(rid, params: dict, _root=_relay_r@method("bot_relay.deliver")-def _(rid, params: dict, _root=_relay_root, _run=_run_delivery,- _failure_reason=delivery_failure_reason) -> dict:- """Deliver a relayed DM (``profile``, attribution-prefixed ``message``) into a Bot Chat ON THIS- GATEWAY via the one-turn ``hermes -p <profile> chat -c "Bot Chat"`` transport local DMs use →- ``{reply}``. Blocking by design (Desktop relay worker; the RPC pool keeps it off the reader)."""- import tempfile- profile = str(params.get("profile") or "").strip()- message = str(params.get("message") or "").strip()- if not profile or not message:- return _err(rid, 4090, "profile and message required")+def _(rid, params: dict, _root=_relay_root) -> dict:+ """Legacy transport bridge only: canonical admission or an explicit refusal."""+ from tools.bot_live_delivery import _delivery_id, authority_delivery+ from tools.bot_relay import _HANDLE_REtry:- from tools.bot_mode_dm import MESSAGE_MAX_CHARS- from tools.bot_relay import acquire_turn_lock- if len(message) > MESSAGE_MAX_CHARS + 200: # + attribution headroom- return _err(rid, 4091, "message too long")- root = _root()- from tools.bot_mode_probe import _roster- known = {name for name, _ in _roster(root)}- resolved = "default" if profile.lower() == "hermes" else profile- if resolved not in known:- return _err(rid, 4092, f"no profile '{profile}' on this gateway")+ _delivery_id(params.get('id'))+ profile = params.get('profile')+ if not isinstance(profile, str) or not _HANDLE_RE.fullmatch(profile):+ raise ValueError('invalid profile')+ except ValueError:+ return _err(rid, 4090, 'invalid_params', data={'reason': 'invalid_params'})- from tools.bot_relay import delivery_turn_author- from tui_gateway.methods_browser_control import _is_authenticated_identity++ from tools.bot_relay import delivery_turn_author, relaying_principal_author++ from tui_gateway.methods_browser_control import _is_authenticated_identity, _principal_digest+ sender_fields = ("from_profile", "from_handle", "from_connection")- if (any(params.get(key) for key in sender_fields)- and _is_authenticated_identity(getattr(current_transport(), "auth_identity", None))):- return _err(rid, 4095, "a logged-in client cannot name the sender of a relayed dm")- author = delivery_turn_author(*(params.get(key) for key in sender_fields))++ identity = getattr(current_transport(), "auth_identity", None)++ if _is_authenticated_identity(identity):++ # A logged-in client's sender fields are NOT trusted — but the delivery is not refused++ # either: the Desktop is itself a logged-in client on every gateway that requires sign-in++ # (it mints a ws-ticket carrying the signed-in {user_id, provider} —++ # hermes_cli/dashboard_auth/routes.py), so refusing took cross-connection relay offline++ # for exactly the auth-gated gateways it serves; only ``?internal=`` callers are++ # identity-exempt and the Desktop cannot present one. Nor is the author dropped: an++ # unattributed turn is the HUMAN's to the recipient's memory, so a bot DM must stay++ # bot-authored. The author is derived from the caller's minted identity instead — stable,++ # unspoofable, and ``is_bot`` — whether or not the client named a sender.++ author = relaying_principal_author(_principal_digest(identity))++ else:++ author = delivery_turn_author(*(params.get(key) for key in sender_fields))+ forwarded = {key: value for key, value in params.items() if key not in sender_fields}+ if author:+ forwarded["author"] = author+ resolved = 'default' if profile.lower() == 'hermes' else profile+ root = _root()+ # Same identity predicate as `profile list`: infra dirs and tombstones under profiles/ are+ # not teammates (#99392), so a DM never targets one.+ from tools.bot_mode_probe import _roster+ home = dict(_roster(root)).get(resolved)+ if home is None:+ return _err(rid, 4092, f"no profile '{profile}' on this gateway", data={'reason': 'unknown_profile'})++ if isinstance(forwarded.get("message"), str):+ # The sender stamped itself with its bare @handle; a relayed "@hermes" is ANOTHER machine's+ # default, so re-stamp it with the form this gateway can reply to (#103731).+ from tools.bot_mode_probe import local_taken_forms+ from tools.bot_relay import qualify_sender_stamp, read_remote_roster- message = qualify_sender_stamp(message, params.get("from_handle"), params.get("from_connection"),- read_remote_roster(root), local_taken_forms(root))-- # When THIS gateway already hosts the target's Bot Chat live, the subprocess transport is- # fenced out by the single-owner lease and the payload dropped (#100523). See below.- from tools.bot_mode_probe import BOT_CHAT_TITLE- live_home = _profile_home(resolved)- want_home = str(live_home) if live_home is not None else None- live_sid = next((- live_sid for live_sid, record in list(_sessions.items())- if isinstance(record, dict) and (record.get("profile_home") or None) == want_home- and _session_live_title(- record, _session_lookup_key(record, fallback=live_sid)) == BOT_CHAT_TITLE), "")- # The sender fields are whatever the relaying client says. The author labels memory only and grants nothing.- from tools.bot_relay import (- DeliveryAuthor, delivery_env, delivery_turn_author, relaying_principal_author)- from tui_gateway.methods_browser_control import _is_authenticated_identity, _principal_digest- sender_fields = ("from_profile", "from_handle", "from_connection")- identity = getattr(current_transport(), "auth_identity", None)- if _is_authenticated_identity(identity):- # A logged-in client's sender fields are NOT trusted — but the delivery is not refused- # either: the Desktop is itself a logged-in client on every gateway that requires sign-in- # (it mints a ws-ticket carrying the signed-in {user_id, provider} —- # hermes_cli/dashboard_auth/routes.py), so refusing took cross-connection relay offline- # for exactly the auth-gated gateways it serves; only ``?internal=`` callers are- # identity-exempt and the Desktop cannot present one. Nor is the author dropped: an- # unattributed turn is the HUMAN's to the recipient's memory (Honcho routes it into the- # human session and allows conclusion / profile / mirror writes), so a bot DM must stay- # bot-authored. The author is derived from the caller's minted identity instead — stable,- # unspoofable, and ``is_bot`` — whether or not the client named a sender. The human-facing- # "Message from 🤖 …" signature stays in the text the sender composed.- author = relaying_principal_author(_principal_digest(identity))- else:- author = delivery_turn_author(*(params.get(k) for k in sender_fields))-- # This process's _sessions is not the ownership authority: the Desktop pools one backend per- # (connection, profile) and an SSH source runs one remote dashboard per profile, so the- # target's Bot Chat can be live in a sibling process on this host while the relay RPC lands- # here. The subprocess transport would then be refused SESSION_NOT_OWNED by that owner's- # lease (#113753). Hand the DM to the live owner — this process or a sibling — through the- # same mailbox local DMs use (tools/bot_mode_dm.py::_run_delivery); its poller admits it at- # the next idle boundary and settles a receipt carrying the reply. Local DMs wait on that- # receipt (_wait_live_dm); so does this relay, on the same budget, so the sender gets the- # target's answer rather than a receipt when its Bot Chat happens to be open.- from tools.bot_live_delivery import await_delivery, deliver_to_live_owner, find_canonical_live_owner- from tools.bot_mode_dm import _LIVE_WAIT_SECONDS- owner_home = live_home if live_home is not None else Path(_hermes_home)- owner = find_canonical_live_owner(owner_home)- if owner is not None:- record = deliver_to_live_owner(owner_home, owner, message, author=author)- record = await_delivery(owner_home, record["delivery_id"], _LIVE_WAIT_SECONDS) or record- if record["status"] == "settled":- from tui_gateway.prompt_turn import _bot_mode_delivery_text- return _ok(rid, {"reply": _bot_mode_delivery_text((record.get("reply") or "").strip(), successful=True)})- if record["status"] in ("queued", "claimed"):- # Admitted but not answered within the budget: the receipt stays, the turn still runs.- reply = (f"Queued for @{resolved}'s open Bot Chat; it runs as that chat's next turn and the reply "- "will appear there. Do not resend.")- return _ok(rid, {"reply": reply})- from tools.bot_failure_reasons import CANCELLED, classify_agent_error- error = str(record.get("error") or f"Bot Chat delivery {record['status']}")- reason = record.get("reason") or (CANCELLED if record["status"] == "cancelled" else classify_agent_error(error))- return _err(rid, 5092, f"delivery turn failed: {error[-500:]}", data={"reason": reason})-- if live_sid:- # A live Bot Chat here that advertises no mailbox: land the DM through prompt.submit, the- # composer's choke point, so role alternation, persistence and streaming behave as a- # typed message would (#100523). queued=True: a teammate's DM runs as the NEXT turn and- # never interrupts or steers a turn in flight (the default busy mode does).- submit_params: dict = {"session_id": live_sid, "text": message, "queued": True}- if author:- submit_params["_turn_author"] = DeliveryAuthor(author)- submitted = _methods["prompt.submit"](rid, submit_params)- if "error" in submitted:- return submitted- reply = f"Delivered into @{resolved}'s open Bot Chat; the reply will appear there."- return _ok(rid, {"reply": reply})-- def _detail(p) -> str:- from tools.bot_failure_reasons import turn_failure_text- return turn_failure_text(p.stdout, p.stderr)-- turn_env = delivery_env(author, live_home)-- fd, tmp = tempfile.mkstemp(prefix="hermes-relay-dm-", suffix=".txt", text=True)- try:- with os.fdopen(fd, "w", encoding="utf-8") as f:- f.write(message)- # Per-profile turn lock serializes with any other delivery turn into this profile and- # covers only the turn window. Worst-case hold is lock wait (bot_mode.turn_wait_seconds,- # default 120s) + the 600s turn timeout, doubled on one retry — callers tolerate ~1320s.- # Worst-case handler hold is lock wait (bot_mode.turn_wait_seconds, default 120s) + the 600s- # turn timeout below — doubled when the retry policy grants one bounded re-run — so clients- # calling bot_relay.deliver must tolerate ~1320s before assuming failure. See #93091.- with acquire_turn_lock(root, resolved):- proc = _run(resolved, tmp, turn_env)- if proc.returncode != 0:- # Retry policy: transient classes re-run the SAME session once; context_overflow- # too — the retried turn's pre-API compaction pass compacts the over-threshold- # transcript first (no fresh session is minted). Auth/quota/config never retry.- # See #93091.- from tools.bot_failure_reasons import (- RETRY_NONE, classify_agent_error, retry_action)- if retry_action(classify_agent_error(_detail(proc))) != RETRY_NONE:- # The failed attempt already persisted the DM; the re-run resumes that row.- from tools.bot_relay import retry_turn_env- proc = _run(resolved, tmp, retry_turn_env(turn_env))- finally:- with contextlib.suppress(OSError):- os.unlink(tmp)- if proc.returncode != 0:- from tools.bot_failure_reasons import classify_agent_error- detail = _detail(proc)- return _err(rid, 5092, f"delivery turn failed: {detail[-500:] or proc.returncode}",- data={"reason": classify_agent_error(detail)})- # Use the same canonical whole-response predicate as live Bot Chat- # completion. A marker remains a successful turn, but is never sent- # back to the relay caller as visible prose.- from tui_gateway.prompt_turn import _bot_mode_delivery_text- reply = _bot_mode_delivery_text((proc.stdout or "").strip(), successful=True)- return _ok(rid, {"reply": reply})- except subprocess.TimeoutExpired:- # Every classified refusal has to ride `data.reason`: the Desktop forwards only that field,- # and the sender re-classifies from free text, which cannot name these. This branch is also- # `delivery_timeout`'s only producer.- from tools.bot_failure_reasons import DELIVERY_TIMEOUT- return _err(rid, 5093, "delivery turn timed out", data={"reason": DELIVERY_TIMEOUT})- except Exception as e:- reason = _failure_reason(e)- return _err(rid, 5096 if reason == "target_busy" else 5094, str(e), data={"reason": reason})++ forwarded["message"] = qualify_sender_stamp(++ forwarded["message"], params.get("from_handle"), params.get("from_connection"),++ read_remote_roster(root), local_taken_forms(root))+ try:+ return _ok(rid, authority_delivery(home, {**forwarded, 'profile': resolved}))+ except Exception as exc:+ return _err(rid, 5094, str(exc), data={'reason': 'runtime_unavailable'})@method("bot_relay.reply")diff --cc tui_gateway/methods_complete.pyindex 235a624b4ee,3e7aecdbb85..f9a7d5b5ebc--- a/tui_gateway/methods_complete.py+++ b/tui_gateway/methods_complete.py@@@ -262,8 -276,55 +270,11 @@@ def _(rid, params: dict) -> dict@method("complete.slash")@_catch(5020)def _(rid, params: dict) -> dict:- text = params.get("text", "")- if not text.startswith("/"):- return _ok(rid, {"items": []})- from hermes_cli.commands_completion import SlashCommandCompleter- from prompt_toolkit.document import Document- from prompt_toolkit.formatted_text import to_plain_text- from agent.skill_commands import get_skill_commands- from agent.skill_bundles import get_skill_bundles+ from tui_gateway.command_discovery import slash_completions- return _ok(rid, slash_completions(params.get("text", "")))+ # Skill/bundle lookups are home- and cwd-keyed: bind the calling session's profile and workspace so+ # the popup offers the project-local skills ``command.dispatch`` accepts for that session (#114359).- with _session_home_scope(_sessions.get(params.get("session_id", "")), cwd=_completion_cwd(params)):- skill_commands, skill_bundles = dict(get_skill_commands()), dict(get_skill_bundles())- completer = SlashCommandCompleter(- skill_commands_provider=lambda: skill_commands, skill_bundles_provider=lambda: skill_bundles)- # `kind` reaches the TUI as data (from the providers, not sniffed from ⚡/▣ glyphs):- # skills/bundles are the only completions for an inline `/skill` typed mid-message.- skill_names = {key.lstrip("/").lower() for key in (*skill_commands, *skill_bundles)}-- def to_items(doc: Document) -> list[dict]:- # display/display_meta are FormattedText; the TUI contract is a plain string- # (the raw list trips Ink's row layout into 1-char truncation).- return [- {- "text": c.text, "display": to_plain_text(c.display) if c.display else c.text,- "meta": to_plain_text(c.display_meta) if c.display_meta else "",- "kind": "skill" if c.text.strip().lstrip("/").lower() in skill_names else "command"}- for c in completer.get_completions(doc, None)]- items = to_items(Document(text, len(text)))- # Rank + bound while a `/token` is under the cursor (the one stage skills are- # offered at); an argument stage (`/personality `) keeps its command's order.- if text.rsplit(" ", 1)[-1].startswith("/"):- score_of = None- # Command-token stage: the completer only emits name-prefix matches, so merge in- # catalog entries whose name SUBSTRING or DESCRIPTION words match (name outranks description).- if " " not in text and len(text) > 1:- from tui_gateway.slash_fuzzy import fuzzy_rank_slash_items, normalize_slash_search_query- items, score_of = fuzzy_rank_slash_items(- items, to_items(Document("/", 1)), normalize_slash_search_query(text))- usage, origin_of = _skill_usage_lookup()- items = _rank_slash_completions(items, usage, origin_of, browsing=text == "/", score_of=score_of)- else:- items = items[:_SLASH_COMPLETION_LIMIT]- text_lower = text.lower()- for extra_text, extra_meta in _SLASH_EXTRAS:- if extra_text.startswith(text_lower) and not any(item["text"] == extra_text for item in items):- items.append({**_item(extra_text, extra_meta), "kind": "command"})- if (details_items := _details_completions(text)) is not None:- return _ok(rid, {"items": details_items, "replace_from": text.rfind(" ") + 1 if " " in text else len(text)})- return _ok(rid, {"items": items, "replace_from": text.rfind(" ") + 1 if " " in text else 1})++ scope = _session_home_scope(_sessions.get(params.get("session_id", "")), cwd=_completion_cwd(params))++ return _ok(rid, slash_completions(params.get("text", ""), scope=scope))def _session_agent(params: dict):diff --cc tui_gateway/methods_tools.pyindex 4489fda02e2,5456de09d46..86367ac0180--- a/tui_gateway/methods_tools.py+++ b/tui_gateway/methods_tools.py@@@ -359,11 -407,113 +407,15 @@@ def _(rid, params: dict) -> dict# ─── Command catalog / dispatch ──────────────────────────────────────────────-class _Catalog:- """Accumulator for commands.catalog: ``pairs`` (every [key, desc]), ``canon`` (lowercase- key/alias → canonical key), ``commands`` (key → desktop meta) and ordered categories."""-- def __init__(self) -> None:- self.pairs: list[list[str]] = []- self.canon: dict[str, str] = {}- self.commands: dict[str, dict[str, str | None]] = {}- self.cat_map: dict[str, list[list[str]]] = {} # insertion order = category order-- def add(self, key: str, desc: str, cat: str) -> None:- self.canon[key.lower()] = key- self.pairs.append([key, desc])- self.cat_map.setdefault(cat, []).append([key, desc])---def _catalog_registry(cat: _Catalog) -> None:- commands = _tools_mod("hermes_cli.commands")- for cmd in commands.COMMAND_REGISTRY:- meta = commands.command_desktop_meta(cmd)- cat.commands.update({f"/{key}": dict(meta) for key in (cmd.name, *cmd.aliases)})- if cmd.name in _TUI_HIDDEN or cmd.gateway_only:- continue- cat.add(f"/{cmd.name}", commands._build_description(cmd), cmd.category)- for a in cmd.aliases:- cat.canon[f"/{a}".lower()] = f"/{cmd.name}"- for name, desc, category in _TUI_EXTRA:- # Registry command/alias wins over a colliding TUI extra (e.g. /compact, /sessions).- if name.lower() not in cat.canon:- cat.add(name, desc, category)---def _catalog_quick_commands(cat: _Catalog) -> None:- qcmds = _load_cfg().get("quick_commands", {}) or {}- if not (isinstance(qcmds, dict) and qcmds):- return- cat.cat_map.setdefault("User commands", []) # category exists even when every entry is malformed- for qname, qc in sorted(qcmds.items()):- if not isinstance(qc, dict):- continue- qtype = qc.get("type", "")- default_desc = {"exec": f"exec: {qc.get('command', '')}", "alias": f"alias → {qc.get('target', '')}"}- desc = str(qc.get("description") or default_desc.get(qtype, qtype or "quick command"))- cat.add(f"/{qname}", desc, "User commands")---def _catalog_plugin_commands(cat: _Catalog) -> None:- plugin_cmds = _tools_mod("hermes_cli.plugins").get_plugin_commands() or {}- if plugin_cmds:- cat.cat_map.setdefault("Plugin commands", [])- for pname, info in sorted(plugin_cmds.items()):- key = f"/{pname}"- if not isinstance(info, dict) or key.lower() in cat.canon:- continue- cat.add(key, str(info.get("description") or "Plugin command"), "Plugin commands")- mode = info.get("argument_mode")- if mode not in {"options", "text", "mixed"}:- mode = "text" if str(info.get("args_hint") or "").strip() else None- cat.commands[key] = {"argument_mode": mode, "desktop": None}---def _catalog_skills(cat: _Catalog, skills: dict[str, dict]) -> str:- """Append skill pairs and fill ``skills`` = ``{key: {usage, origin}}`` (every consumer ranks by them).- Returns the one-line notice for skills whose name is a built-in command (no ``/<name>`` entry;- ``agent.skill_commands`` guard), ``""`` when none."""- usage, origin_of = _skill_usage_lookup()- sc = _tools_mod("agent.skill_commands")- for k, info in sorted(sc.scan_skill_commands().items()):- cat.pairs.append([k, str(info.get("description", "Skill"))])- name = str(info.get("name") or k.lstrip("/"))- skills[k] = {"usage": usage(name), "origin": origin_of(name)}- names = sorted(s["name"] for s in _tools_mod("tools.skills_tool")._find_all_skills())- return "; ".join(filter(None, map(sc.skill_command_collision_note, names)))--@_rpc("commands.catalog", 5020)def _(rid, params: dict) -> dict:- """Registry-backed slash metadata, categorized, no aliases (shared builder in command_discovery)."""- """Registry-backed slash metadata, categorized, no aliases. Discovery failures land in ``warning``- (skills' message wins, then quick commands', then plugins'); only with no failure does it carry- the built-in-name collision notice for skills that have no ``/<name>`` (empty when none). Skill++ """Registry-backed slash metadata, categorized, no aliases (shared builder in command_discovery). Skill+ discovery is bound to the calling session's profile and workspace (``_completion_cwd``: its record,+ else the cwd a new session would be seeded with) so project-local skills register for the repo the+ session is actually in (#114359)."""- cat = _Catalog()- _catalog_registry(cat)- warning = ""- try:- _catalog_quick_commands(cat)- except Exception as e:- warning = f"quick_commands discovery unavailable: {e}"- try:- _catalog_plugin_commands(cat)- except Exception as e:- warning = warning or f"plugin command discovery unavailable: {e}"- skills: dict[str, dict] = {}- try:- with _session_home_scope(_sessions.get(params.get("session_id", "")), cwd=_completion_cwd(params)):- collision_note = _catalog_skills(cat, skills) # always runs: skills must list even when a loader failed- warning = warning or collision_note- except Exception as e:- warning = f"skill discovery unavailable: {e}"- return _ok(rid, {- "pairs": cat.pairs, "sub": {k: v[:] for k, v in _tools_mod("hermes_cli.commands").SUBCOMMANDS.items()},- "canon": cat.canon,- "commands": cat.commands,- "categories": [{"name": c, "pairs": rows} for c, rows in cat.cat_map.items()],- "skills": skills, "skill_count": len(skills), "warning": warning})+ from tui_gateway.command_discovery import command_catalog- return _ok(rid, command_catalog(load_cfg=_load_cfg, module_loader=_tools_mod))++ scope = _session_home_scope(_sessions.get(params.get("session_id", "")), cwd=_completion_cwd(params))++ return _ok(rid, command_catalog(load_cfg=_load_cfg, module_loader=_tools_mod, scope=scope))@method("cli.exec")diff --cc tui_gateway/server.pyindex 2051f374174,cb7db335aec..487f8e715d0--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@@ -866,42 -870,304 +870,7 @@@ def _current_session_steer_authority(sereturn transport, session- def dispatch(req: dict, transport: Optional[Transport] = None) -> dict | None:- """Route inbound RPCs — long handlers to the pool (returns None; the worker writes its own- response via the bound transport), everything else inline (returns the response dict).- *transport* pins every write of this request — events included — to that transport;- omitted → the module stdio transport (``tui_gateway.entry`` behaviour)."""- t = transport or _stdio_transport- token = bind_transport(t)- try:- from tui_gateway import server_requests- if server_requests.is_response_frame(req):- # The renderer answering one of OUR requests (clarify, approval, …): no response frame goes back.- if not server_requests.resolve_response(req) and not _relay_compute_host_response(req):- logger.debug("dropping response for unknown server request id=%r", req.get("id"))- return None- normalized = _normalize_request(req)- if isinstance(normalized, dict):- return normalized- if normalized[1] not in _LONG_HANDLERS:- return handle_request(req)- ctx = contextvars.copy_context() # the pool worker must see the bound transport- if normalized[1] in _CONNECTOR_RPC_METHODS:- ctx.run(_capture_connector_rpc_owner, normalized[2])-- def run():- try:- resp = handle_request(req)- except Exception as exc:- resp = _err(req.get("id"), -32000, f"handler error: {exc}")- if resp is not None:- t.write(resp)- _pool.submit(lambda: ctx.run(run))- return None- finally:- reset_transport(token)--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(current: dict, agent) -> None:- """Attach a freshly built agent to its live record (session DB row deferred to first run_conversation())."""- # Bot Mode gate hint: the DB title lands post-first-turn but the system prompt builds at turn START.- if _title_hint := str(current.get("pending_title") or "").strip():- agent._session_title_hint = _title_hint- current["agent"] = agent- # 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()---def _announce_built_agent(sid: str, key: str, current: dict, agent) -> None:- """Post-wiring tail of a build: credits seed, session services, session.info, late MCP catch-up."""- # Credits notices at session OPEN (notice_callback already wired) so depletion warnings show at "ready".- with contextlib.suppress(Exception):- from agent.credits_tracker import seed_credits_at_session_start- seed_credits_at_session_start(agent)- _start_session_services(sid, key, current)- info = _session_info(agent, current)- if cfg_warn := _probe_config_health(_load_cfg()):- info["config_warning"] = cfg_warn- logger.warning(cfg_warn)- _emit("session.info", sid, info)- _schedule_mcp_late_refresh(sid, agent) # servers slower than the bounded discovery wait land here---def _finish_agent_build(sid: str, key: str, current: dict, *, notify_registered: bool, scopes, session_db) -> None:- """Release build scopes and settle ownership of the late notify registration + dedicated db handle."""- if scopes is not None:- _release_build_profile_scopes(scopes)- # Reaped mid-build: _attach_worker closed the worker; only a late notify registration can still- # leak (session.close unregistered before _build registered).- with _sessions_lock:- replaced = _sessions.get(sid) is not current- if replaced and notify_registered:- with contextlib.suppress(Exception):- from tools.approval import unregister_gateway_notify- unregister_gateway_notify(key)- # Dedicated profile handle: hand it to the agent that will be torn down, else close it (build- # failed, or `replaced`: this agent is discarded and _teardown_session never reaches it).- if session_db is not None and not _transfer_db_to_agent(None if replaced else current.get("agent"), session_db):- with contextlib.suppress(Exception):- session_db.close()---def _start_agent_build(sid: str, session: dict) -> None:- """Start building the real AIAgent for a TUI session, once. Deferred until the first prompt (or any- command needing the agent) so the composer isn't blocked on tool discovery / model metadata;- the ready/error event contract is unchanged."""- ready = session.get("agent_ready")- if ready is None:- return- # A lazy watch session spectating an in-flight child must stay lazy so the subagent live-mirror keeps- # flowing (it bails once agent is set); incidental RPCs via _sess() would upgrade it mid-stream.- if session.get("lazy") and _child_run_active(str(session.get("session_key") or "")):- return- with session.setdefault("agent_build_lock", threading.Lock()):- if ready.is_set() or session.get("agent_build_started"):- return- session["agent_build_started"] = True- session.pop("lazy", None) # now genuinely mid-construction: restore the "still starting" eviction exemption- key = session["session_key"]-- def _build() -> None:- with _sessions_lock:- current = _sessions.get(sid)- if current is None:- # 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_built_agent(current, agent)- # No eager slash-worker pre-warm (slash.exec spawns on demand): each worker forks the full stdio- # MCP fleet, and live-transport sessions are never reaped, so fleets would accumulate.- notify_registered = _wire_session_agent(sid, key, agent)- _announce_built_agent(sid, key, current, agent)- except Exception as e:- current["agent_error"] = str(e)- _emit("error", sid, {"message": agent_init_failed_message(e)})- finally:- _finish_agent_build(- sid, key, current, notify_registered=notify_registered, scopes=scopes, session_db=session_db)- ready.set()-- build_thread = threading.Thread(target=_build, daemon=True)- # _wait_agent_for_prompt handle: dead thread + unset agent_ready = died hard; waiters must not sit out the cap.- session["_agent_build_thread"] = build_thread- build_thread.start()---def _sess_nowait(params, rid):- sid = params.get("session_id") or ""- s = _sessions.get(sid)- if s:- return (s, None)- # Stale runtime id (reaped/evicted/TTL): the client should session.resume the STORED id. Logged so- # "message vanished" reads as "arrived and was rejected".- logger.warning("session-scoped RPC rejected: method=%s session_id=%r not in memory "- # A session-scoped RPC hit a runtime id the gateway no longer holds (detached on WS- # disconnect and orphan-reaped, LRU-evicted, or torn down after an idle TTL). The client- # is expected to recover via session.resume on the STORED session id, but a plain- # stale-id send leaves no trace anywhere when the resume never fires — every RPC in this- # class returned a silent 4001. Log it so a "message vanished" report is diagnosable as- # "request arrived and was rejected" instead of "request never arrived" (see #90428).- "(detached/reaped runtime; client should resume the stored session), rid=%r",- _current_rpc_method.get() or "?", sid, rid)- return (None, _err(rid, 4001, "session not found"))---def _sess(params, rid):- s, err = _sess_building(params, rid)- return (None, err) if err else (s, _wait_agent(s, rid))---def _sess_building(params, rid):- """Resolve a session and warm its agent build WITHOUT waiting — for the attach RPCs (image/file/pdf,- clipboard.paste, image.detach), which only touch creation-time fields and run inline on the socket- reader thread, where waiting on a cold build stalled every RPC behind it ("text is instant, images hang")."""- s, err = _sess_nowait(params, rid)- if not err:- _start_agent_build(params.get("session_id") or "", s)- return (None, err) if err else (s, None)# ── Config I/O ────────────────────────────────────────────────────────@@@ -1946,12 -3322,10 +1925,13 @@@ from .mcp_rpc_helpers import summarize_# ── Split @method handler modules (see method_ctx.py): imported last so every global the handlers close# over exists; register() rebinds them onto this namespace.+from hermes_state import _BARE_BILLING_PROVIDERS # noqa: E402, F401+from . import ( # noqa: E402+ session_registry as _session_registry, agent_factory as _agent_factory,methods_voice as _methods_voice, methods_browser as _methods_browser, methods_slash as _methods_slash,methods_complete_helpers as _methods_complete_helpers, session_auto_continue as _session_auto_continue,+ rpc_dispatch as _rpc_dispatch,agent_callbacks as _agent_callbacks, session_history as _session_history,prompt_attachments as _prompt_attachments, session_notifications as _session_notifications,tool_progress as _tool_progress, change_watcher as _change_watcher,@@@ -1967,13 -3341,13 +1947,14 @@@methods_projects as _methods_projects, methods_session_foreign as _methods_session_foreign,methods_session_control as _methods_session_control, methods_subagents as _methods_subagents,methods_vault as _methods_vault, methods_free_tier as _methods_free_tier,- methods_connectors as _methods_connectors)+ methods_connectors as _methods_connectors, methods_connectors_account as _methods_connectors_account,+ methods_onboarding as _methods_onboarding)for _m in (+ _session_registry, _agent_factory,_session_transports, _session_reaper, _session_lifecycle, _session_workdir, _compute_host_bridge, _model_switch,_session_compression, _change_watcher, _tool_progress, _session_notifications,- _prompt_attachments, _session_history, _agent_callbacks, _session_auto_continue,+ _prompt_attachments, _session_history, _agent_callbacks, _session_auto_continue, _rpc_dispatch,_methods_complete_helpers, _methods_slash, _methods_voice, _methods_browser,_methods_browser_control, _methods_session, _methods_prompt, _methods_config,_methods_config_set, _methods_complete, _methods_tools, _methods_profiles, _methods_images,diff --cc tui_gateway/session_lifecycle.pyindex aeeb016dc94,0beeb087b67..9af4e6a7b75--- a/tui_gateway/session_lifecycle.py+++ b/tui_gateway/session_lifecycle.py@@@ -26,6 -60,12 +60,12 @@@ _SESSION_OWNERSHIP_UNAVAILABLE = "Herme_AUTOMATIC_SESSION_END_REASONS = frozenset({"ws_orphan_reap", "ws_disconnect", "idle_timeout", "lru_evict", "tui_shutdown"})+ def _lease_metadata(live_session_id: str) -> dict:- """Writer identity for a lease: ``live_session_id`` is half of ``_is_same_writer``; the delivery flag is- what Bot Chat gates live delivery on (session_notifications)."""- return {"live_session_id": live_session_id, "bot_live_delivery_consumer": True}++ """Writer identity for a lease: ``live_session_id`` is half of ``_is_same_writer``. Bot Chat delivery is++ admitted by the session authority (gateway/session_bot), never gated on a lease flag."""++ return {"live_session_id": live_session_id}++def _claim_active_session_slot(session_key: str, *, live_session_id: str, surface: str = "tui", profile_home: str | Path | None = None) -> tuple[Any, str | None]:diff --cc tui_gateway/session_notifications.pyindex 7f69d4d99f5,74818a4c3fa..7b8d0b2c534--- a/tui_gateway/session_notifications.py+++ b/tui_gateway/session_notifications.py@@@ -136,7 -135,9 +137,9 @@@ def _notification_event_dedup_key(evt:# Mirror gateway/kanban_watchers.py TERMINAL_KINDS: claim silent kinds (archived/unblocked) too so the cursor advances# past them and they can't wedge a later completed/blocked event behind an unclaimed row._KANBAN_NOTIFY_KINDS = ("completed", "blocked", "gave_up", "crashed", "timed_out", "status", "archived", "unblocked")- _KANBAN_POLL_SECONDS = _LOOP_POLL_SECONDS = 5.0 # /loop and /heartbeat share one idle-poll cadence+ # kanban, /loop + /heartbeat and the bot mailbox share one idle-poll cadence; probing the lease registry on+ # every 0.5s queue timeout cost ~a core at 11 sessions (#108005).-_KANBAN_POLL_SECONDS = _LOOP_POLL_SECONDS = _BOT_DELIVERY_POLL_SECONDS = 5.0++_KANBAN_POLL_SECONDS = _LOOP_POLL_SECONDS = 5.0def _notif_release_turn(session: dict) -> None:@@@ -429,19 -444,18 +445,26 @@@ def _notif_poll_kanban_scoped(sid: strif not session.get("_kanban_pending") or not _notif_claim_turn(session):returnwith session["history_lock"]:- batch, session["_kanban_pending"] = list(session.get("_kanban_pending") or []), []+ pending = session.get("_kanban_pending") or []+ from gateway.warning_notifications import DiagnosticText, warning_notifications_enabled+ split = not warning_notifications_enabled("tui")+ diagnostic = split and isinstance(pending[0], DiagnosticText)+ batch = [text for text in pending if not split or isinstance(text, DiagnosticText) == diagnostic]+ session["_kanban_pending"] = [text for text in pending if split and isinstance(text, DiagnosticText) != diagnostic]with contextlib.suppress(Exception):- _notif_submit(f"__notif__{int(time.time() * 1000)}", sid, session, "\n".join(batch), "kanban notification dispatch failed")+ _notif_submit(f"__notif__{int(time.time() * 1000)}", sid, session, "\n".join(batch),+ "kanban notification dispatch failed",+ **({"display_metadata": {"notification_category": "diagnostic"}} if diagnostic else {}))+def _notif_defer_event(evt, claim, put=None):+ from tools.async_delegation import defer_completion_delivery+ from tools.process_registry import process_registry+ if claim:+ defer_completion_delivery(evt['delegation_id'], claim)+ (put or process_registry.completion_queue.put)(evt)++def _notif_dispatch_event(sid: str, session: dict, evt: dict, text: str) -> None:"""Run the claimed (running=True) agent turn for one notification event."""from tools.async_delegation import claim_event_delivery, complete_event_delivery, release_event_delivery@@@ -450,11 -472,11 +481,14 @@@returnkwargs = ({"display_kind": "async_delegation_complete", "display_metadata": _async_delegation_display_metadata(evt)}if evt.get("type") == "async_delegation" else {})+ from agent.notification_presentation import diagnostic_process_event+ if diagnostic_process_event(evt):+ kwargs.setdefault("display_metadata", {})["notification_category"] = "diagnostic"try:- _notif_submit(f"__notif__{int(time.time() * 1000)}", sid, session, text, "notification poller dispatch failed", **kwargs)+ if not _notif_submit(f"__notif__{int(time.time() * 1000)}", sid, session, text,+ "notification poller dispatch failed", **kwargs):+ _notif_defer_event(evt, claim)+ returnexcept Exception:release_event_delivery(evt, claim)return@@@ -563,7 -593,95 +609,12 @@@ def _notif_handle_ready(sid, session, e_notif_dispatch_completions(sid, session, completions, registry, deferred)-def _poll_bot_live_delivery_once(sid: str, session: dict) -> bool:- """Run one durable envelope only after local FIFO/continuations yield the idle boundary."""- from tools.bot_live_delivery import claim_pending_delivery, complete_delivery, find_canonical_live_owner, has_mailbox-- home = _session_home(session)- # Most profiles never receive a delivery: without a mailbox there is nothing to claim, and the owner- # lookup below costs a state.db open plus the exclusive active-session registry lock every pass (#111719).- if not has_mailbox(home):- return False- with _session_turn_admission(session) as admitted:- if not admitted or any(session.get(key) for key in (- "running", "_closing", "_finalized", "queued_prompt", "queued_prompts",- "_auto_continue_scheduled")) or session.get("agent") is None:- return False- lease = session.get("active_session_lease")- if lease is None or getattr(lease, "released", False):- return False- owner = find_canonical_live_owner(home)- if (not owner or owner.get("lease_id") != lease.lease_id- or owner.get("live_session_id") != sid- or owner.get("session_id") != session.get("session_key")):- return False- # The mailbox matches each envelope to this pinned lease/live id and compression lineage.- claimed = claim_pending_delivery(home, owner)- if claimed is None:- return False- session["running"] = True-- delivery_id = str(claimed["id"])-- def terminal_receipt(terminal: dict) -> None:- status = str(terminal.get("status") or "failed")- error = str(terminal.get("error") or "")- reason = "cancelled" if status == "cancelled" else ""- if status not in {"settled", "cancelled"}:- from tools.bot_failure_reasons import classify_agent_error- reason = classify_agent_error(error)- # Let a failed write propagate: the turn must not retire its crash marker without its receipt.- complete_delivery(home, delivery_id, status=status,- reply=str(terminal.get("text") or "") if status == "settled" else "",- error=error, reason=reason)-- try:- started = _run_prompt_submit(f"__bot_dm__{delivery_id}", sid, session, claimed["message"],- image_paths=[], terminal_callback=terminal_receipt,- turn_author=claimed.get("author") or None,- **({"display_metadata": {"notification_category": "diagnostic"}}- if claimed.get("notification_category") == "diagnostic" else {}))- except Exception as exc:- _notif_release_turn(session)- terminal_receipt({"status": "failed", "error": str(exc)})- raise- if not started:- _notif_release_turn(session)- terminal_receipt({"status": "failed", "error": "live session owner could not start the delivery turn"})- return started---# A failing mailbox poll (typically the active-session registry lock unavailable under contention) is-# retried on the next ``_BOT_DELIVERY_POLL_SECONDS`` pass; log the failure once per window, not per attempt.-_BOT_POLL_WARN_INTERVAL_S = 60.0---def _poll_bot_live_delivery_guarded(sid: str, session: dict, now: float) -> None:- """One poller-loop pass of the mailbox poll. A failure is logged at WARNING once per- ``_BOT_POLL_WARN_INTERVAL_S`` (with the count of suppressed repeats) and at DEBUG otherwise. An- unthrottled poll logged ``Bot live-owner delivery poll failed`` ~2×/minute per session for days,- 91% of an install's WARNING output (#111719)."""- try:- _poll_bot_live_delivery_once(sid, session)- except Exception:- suppressed = int(session.get("_bot_poll_warn_suppressed", 0))- if now - session.get("_bot_poll_warned_at", -_BOT_POLL_WARN_INTERVAL_S) < _BOT_POLL_WARN_INTERVAL_S:- session["_bot_poll_warn_suppressed"] = suppressed + 1- logger.debug("Bot live-owner delivery poll failed (repeat)", exc_info=True)- return- session["_bot_poll_warned_at"], session["_bot_poll_warn_suppressed"] = now, 0- logger.warning("Bot live-owner delivery poll failed (%d repeat(s) suppressed since the last report)",- suppressed, exc_info=True)- return- session["_bot_poll_warn_suppressed"] = 0--def _notification_poller_loop(stop_event: threading.Event, sid: str, session: dict) -> None:+ with _session_profile_runtime_scope(session):+ _notification_poller_scoped_loop(stop_event, sid, session)+++ def _notification_poller_scoped_loop(stop_event: threading.Event, sid: str, session: dict) -> None:"""Daemon thread (started by _init_session()) that drains the process-global completion_queue for this session(ownership routing: _notif_handle_event) and polls ``kanban_notify_subs`` every ``_KANBAN_POLL_SECONDS`` — thedelivery path for platform="tui" rows.diff --cc tui_gateway/session_transports.pyindex b9f3c47b2a4,383e16e9eaf..59d7ae32e76--- a/tui_gateway/session_transports.py+++ b/tui_gateway/session_transports.py@@@ -35,26 -35,18 +35,38 @@@ def _session_has_live_transport(sessionreturn any(peer is not excluding for peer in _session_live_transports(session))+def _transport_auth_user_id(transport) -> str | None:+ """``<provider>:<user id>`` the WS-upgrade credential authenticated for ``transport``, or None for the legacy+ token, stdio and the PTY child's server-internal credential. The prefix keeps a basic-auth ``alice`` and an+ OIDC ``alice`` apart."""+ identity = getattr(transport, "auth_identity", None)+ if _methods_browser_control._is_authenticated_identity(identity):+ return f"{str(identity['provider']).strip()}:{str(identity['user_id']).strip()}"+ return None+++def _session_auth_user_id(session: dict | None) -> str | None:+ """The login ``session`` was created under, stamped on the record as ``auth_user_id``. A second window turns+ the transport slot into a FanoutTransport, which names no login, so only a record without the slot reads+ its transport."""+ session = session or {}+ if "auth_user_id" in session:+ return session["auth_user_id"]+ return _transport_auth_user_id(session.get("transport"))+++ def _session_client_answers_requests(sid: str) -> bool:+ """Whether a server→client request for *sid* can be answered: False only when every live WebSocket+ client attached to the session is a build that never sent ``client.capabilities`` (Desktop / dashboard+ update separately from this backend; the stdio TUI ships with it). No attached client is still True — the+ question waits in ``open_requests`` for the reconnect replay. Compute-host relays and other non-client+ transports never count."""+ from tui_gateway import server_requests+ from tui_gateway.ws import WSTransport+ clients = [peer for peer in _session_live_transports(_sessions.get(sid)) if isinstance(peer, WSTransport)]+ return not clients or any(server_requests.answers_requests(peer) for peer in clients)++def _warn_foreign_login(session: dict, transport) -> None:"""Ownership is not enforced; a second login sharing a session is only logged, and the agent keeps thecreator's user id."""diff --cc ui-tui/src/__tests__/createGatewayEventHandler.test.tsindex d7cd57968c5,d3cd31a30d5..ff7d7180cdd--- a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts+++ b/ui-tui/src/__tests__/createGatewayEventHandler.test.ts@@@ -85,57 -95,10 +95,58 @@@ describe('createGatewayEventHandler', (patchUiState({ showReasoning: true })})+ it('displays generic errors without settling versioned execution', () => {+ const ctx = buildCtx([])+ const onEvent = createGatewayEventHandler(ctx)+ patchUiState({ sid: 'owner', busy: true, status: 'running…', info: { model: 'test', tools: {}, skills: {}, execution_epoch: 'owner-epoch', execution_generation: 2 } })+ onEvent({ type: 'error', session_id: 'owner', payload: { message: 'build failed' } } as any)+ expect(ctx.system.sys).toHaveBeenCalledWith('error: build failed')+ expect(getUiState()).toMatchObject({ busy: true, status: 'running…' })+ onEvent({ type: 'error', session_id: 'owner', payload: { message: 'turn failed', execution_epoch: 'owner-epoch', execution_generation: 2 } } as any)+ expect(ctx.system.sys).toHaveBeenCalledWith('error: turn failed')+ expect(getUiState().busy).toBe(false)+ })++ it('fences restarted owner lifecycle events until resume establishes the new epoch', () => {+ const appended: Msg[] = []+ const onEvent = createGatewayEventHandler(buildCtx(appended))++ const info = { model: 'test', skills: {}, tools: {}, running: true,+ execution_epoch: 'old-owner', execution_generation: 9 }++ patchUiState({ sid: 'focused', info, busy: true })+ const emit = (type: string, payload: any) => onEvent({ type, payload, session_id: 'focused' } as any)+ emit('session.info', { execution_epoch: 'new-owner', execution_generation: 1, running: false })+ expect(getUiState().busy).toBe(true)+ // session.resume replaces info with the authoritative attachment snapshot.+ patchUiState({ info: { ...info, execution_epoch: 'new-owner', execution_generation: 1 } })++ for (const payload of [{}, { execution_epoch: 'old-owner', execution_generation: 99 },+ { execution_epoch: 'new-owner', execution_generation: 0 }]) {+ emit('message.complete', { ...payload, text: 'stale' })+ emit('error', { ...payload, message: 'stale' })+ emit('session.info', { ...payload, running: false })+ expect(getUiState().busy).toBe(true)+ }++ expect(appended).toEqual([])+ emit('message.complete', { execution_epoch: 'new-owner', execution_generation: 1, text: 'fresh' })+ expect(getUiState().busy).toBe(false)+ expect(appended.some(m => m.text === 'fresh')).toBe(true)+ emit('message.start', { execution_epoch: 'new-owner', execution_generation: 2 })+ emit('message.complete', { execution_epoch: 'new-owner', execution_generation: 1, text: 'late' })+ expect(getUiState().busy).toBe(true)+ expect(getUiState().info?.execution_generation).toBe(2)+ emit('message.complete', { execution_epoch: 'new-owner', execution_generation: 4, text: 'missed start' })+ emit('message.start', { execution_epoch: 'new-owner', execution_generation: 3 })+ expect(getUiState().busy).toBe(false)+ expect(getUiState().info?.execution_generation).toBe(4)+ })+it('heals missed completion and blocking prompts only from the focused authoritative idle snapshot', () => {patchUiState({ sid: 'focused' })- const onEvent = createGatewayEventHandler(buildCtx([]))+ const ctx = buildCtx([])+ const onEvent = createGatewayEventHandler(ctx)onEvent({ session_id: 'focused', payload: {}, type: 'message.start' } as any)serverRequest('approval', { session_id: 'focused', request_id: 'approval', command: 'test' })const busyOverlay = getOverlayState().approval@@@ -152,24 -115,63 +163,81 @@@expect(getUiState().status).toBe('ready')expect(getOverlayState().approval).toBeNull()expect(getTurnState().tools).toEqual([])+ onEvent({+ session_id: 'focused',+ payload: { ...snapshot, running: true, execution_generation: 2 },+ type: 'session.info'+ } as any)+ onEvent({+ session_id: 'focused',+ payload: { running: false, execution_generation: 1 },+ type: 'session.info'+ } as any)+ expect(getUiState().busy).toBe(true)+ onEvent({+ session_id: 'focused',+ payload: { running: false, execution_generation: 2 },+ type: 'session.info'+ } as any)+ expect(getUiState().busy).toBe(false)+ expect(getUiState().info?.model).toBe('test')++ const target: ConnectionOperationTarget = { action: 'install', kind: 'mcp', name: 'asana', state: 'pending' }+ onEvent({+ session_id: 'focused',+ payload: {+ deadline_at: 10,+ op_id: 'op-1',+ seq: 2,+ targets: [target],+ timeout_seconds: 30+ },+ type: 'connection.request'+ })+ expect($connectionOperation.get()).toMatchObject({ opId: 'op-1', seq: 2, targets: [target] })+ expect(getOverlayState().connection).toEqual({ opId: 'op-1' })++ onEvent({+ session_id: 'focused',+ payload: {+ deadline_at: 11,+ op_id: 'op-1',+ seq: 1,+ settled: false,+ targets: [{ ...target, state: 'failed' }]+ },+ type: 'connection.update'+ })+ expect($connectionOperation.get()).toMatchObject({ seq: 2, targets: [target] })++ // Esc on the "Finishing…" card drops it and it must not come back on a replay, but the settling+ // frame that follows still records how each app ended.+ const request = {+ deadline_at: 10,+ op_id: 'op-1',+ seq: 2,+ targets: [target],+ timeout_seconds: 30+ }++ dismissConnectionOperation('op-1')+ expect($connectionOperation.get()).toBeNull()+ onEvent({ session_id: 'focused', payload: request, type: 'connection.request' })+ expect($connectionOperation.get()).toBeNull()+ expect(getOverlayState().connection).toBeNull()++ onEvent({+ session_id: 'focused',+ payload: {+ deadline_at: 12,+ op_id: 'op-1',+ seq: 3,+ settled: true,+ targets: [{ ...target, state: 'connected' }]+ },+ type: 'connection.update'+ })+ expect(ctx.system.sys.mock.calls.map((call: unknown[]) => call[0])).toEqual(['asana: connected'])})it('keeps the durable session id when a session.info payload omits it', () => {diff --cc ui-tui/src/__tests__/gatewayClient.test.tsindex fbf5becf28a,b5905b012bc..b979b6be8a2--- a/ui-tui/src/__tests__/gatewayClient.test.ts+++ b/ui-tui/src/__tests__/gatewayClient.test.ts@@@ -139,68 -139,6 +139,71 @@@ describe('GatewayClient websocket attac}})+ it('publishes canonical readiness once after discovery and arms the negotiated heartbeat', async () => {+ vi.useFakeTimers()+ delete process.env.HERMES_TUI_GATEWAY_URL+ delete process.env.HERMES_TUI_SIDECAR_URL+ const gw = new GatewayClient(async () => ({ url: 'ws://gateway.test/api/ws', protocols: [], instance_id: 'owner', profile_id: 'fixture' }))+ const events: any[] = []+ gw.on('event', event => events.push(event))++ try {+ gw.start()+ gw.drain()+ await vi.advanceTimersByTimeAsync(0)+ expect(FakeWebSocket.instances).toHaveLength(1)+ const socket = FakeWebSocket.instances[0]!+ socket.open()+ socket.message(JSON.stringify({ jsonrpc: '2.0', method: 'event', params: { type: 'gateway.ready', payload: { heartbeat: true } } }))+ await vi.advanceTimersByTimeAsync(0)+ expect(events.filter(event => event.type === 'gateway.ready')).toHaveLength(0)- const request = JSON.parse(socket.sent[0]!)- expect(request.method).toBe('runtime.describe')++ // The wire's ready frame triggers the client.capabilities advertisement; discovery++ // (runtime.describe) is the other frame and the one readiness waits on.++ const sent = socket.sent.map(text => JSON.parse(text) as { id?: number; method: string })++ expect(sent.map(frame => frame.method).sort()).toEqual(['client.capabilities', 'runtime.describe'])++ const request = sent.find(frame => frame.method === 'runtime.describe')!+ socket.message(JSON.stringify({ jsonrpc: '2.0', id: request.id, result: {+ session_create: { sources: ['tui'], parameters: ['source', 'request_id'] }+ } }))+ await vi.advanceTimersByTimeAsync(0)+ expect(events.filter(event => event.type === 'gateway.ready')).toHaveLength(1)++ await vi.advanceTimersByTimeAsync(WS_HEARTBEAT_INTERVAL_MS)+ expect(JSON.parse(socket.sent.at(-1) ?? '{}')).toMatchObject({ method: 'gateway.ping' })+ } finally {+ gw.kill()+ expect(vi.getTimerCount()).toBe(0)+ vi.useRealTimers()+ }+ })++ it('keeps discovery-only retries alive and delivers readiness to the mounted subscriber', async () => {+ vi.useFakeTimers()+ delete process.env.HERMES_TUI_GATEWAY_URL+ const grant = { url: 'ws://gateway.test/api/ws', protocols: [], instance_id: 'owner', profile_id: 'fixture' }+ const bootstrap = vi.fn().mockResolvedValueOnce(grant).mockRejectedValueOnce(new Error('owner stopped')).mockRejectedValueOnce(new Error('owner stopped')).mockResolvedValue(grant)+ const gw = new GatewayClient(bootstrap)+ const events: any[] = []+ gw.on('event', event => events.push(event))++ try {+ gw.start(); gw.drain()+ await vi.advanceTimersByTimeAsync(0)+ FakeWebSocket.instances[0]!.open()+ await vi.advanceTimersByTimeAsync(0)+ FakeWebSocket.instances[0]!.close()+ await vi.advanceTimersByTimeAsync(RECONNECT_MAX_MS * 4)+ expect(bootstrap.mock.calls.map(args => args[0])).toEqual([true, false, false, false])+ const socket = FakeWebSocket.instances.at(-1)!+ socket.open()+ await vi.advanceTimersByTimeAsync(0)+ const request = JSON.parse(socket.sent[0]!)+ socket.message(JSON.stringify({ id: request.id, result: { session_create: { sources: ['tui'], parameters: [] } } }))+ await vi.advanceTimersByTimeAsync(0)+ expect(events.some(event => event.type === 'gateway.ready')).toBe(true)+ } finally { gw.kill(); vi.useRealTimers() }+ })+it('waits for websocket open and resolves RPC requests', async () => {process.env.HERMES_TUI_GATEWAY_URL = 'ws://gateway.test/api/ws?token=abc'const gw = new GatewayClient()diff --cc ui-tui/src/__tests__/gatewayClientKillLatch.test.tsindex 00000000000,10fb26a76fb..e62edcfe3e4mode 000000,100644..100644--- a/ui-tui/src/__tests__/gatewayClientKillLatch.test.ts+++ b/ui-tui/src/__tests__/gatewayClientKillLatch.test.ts@@@ -1,0 -1,191 +1,196 @@@+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+-// The race from issue #114987 lives only in spawn mode: kill() leaves-// `this.proc` pointing at the child it just killed, so the late `exit` event-// passes the identity guard, reaches handleTransportExit and is emitted to-// the app — whose recovery subscriber answers with start(), which un-latches-// `disposed` and spawns a replacement gateway onto the vanished PTY. These-// tests drive that exact sequence with a fake child_process.spawn.--const { fakeSpawn, FakeChildProcess } = vi.hoisted(() => {- class FakeStream {++// The race from issue #114987: kill() left the client's transport reference++// in place, so the transport's late exit reached handleTransportExit →++// emit('exit') → useMainApp's recovery subscriber → start(), which un-latched++// `disposed` and spawned a replacement gateway onto a vanished PTY. The Ink++// client now attaches to the unified gateway over a WebSocket after the++// bootstrap grant, so the same three invariants are driven through a fake++// socket: a killed transport's late close is identity-skipped, start() after++// kill() is refused, and an unexpected close still recovers.++++const { FakeWebSocket } = vi.hoisted(() => {++ class FakeWebSocket {++ static CONNECTING = 0++ static OPEN = 1++ static CLOSING = 2++ static CLOSED = 3++ static instances: FakeWebSocket[] = []++++ readyState = FakeWebSocket.CONNECTING++ sent: string[] = []++ readonly url: string+ private listeners = new Map<string, Array<(event: any) => void>>()+- resume() {- return this++ constructor(url: string) {++ this.url = url++ FakeWebSocket.instances.push(this)+ }+- pause() {- return this++ static reset() {++ FakeWebSocket.instances = []+ }+- write(_text: string) {- return true- }-- on(type: string, callback: (event: any) => void) {++ addEventListener(type: string, callback: (event: any) => void) {+ const entries = this.listeners.get(type) ?? []++ entries.push(callback)+ this.listeners.set(type, entries)+ }+- removeListener(type: string, callback: (event: any) => void) {++ removeEventListener(type: string, callback: (event: any) => void) {+ const entries = this.listeners.get(type)+- if (!entries) {- return++ if (entries) {++ this.listeners.set(type, entries.filter(entry => entry !== callback))+ }-- this.listeners.set(- type,- entries.filter(entry => entry !== callback)- )+ }+- emit(type: string, ...args: unknown[]) {- for (const callback of [...(this.listeners.get(type) ?? [])]) {- callback(...args)- }++ send(payload: string) {++ this.sent.push(payload)+ }- }+- class FakeChildProcess {- static instances: FakeChildProcess[] = []-- killed = false- exitCode: null | number = null- signalCode: null | string = null- pid = 4242- stdin = new FakeStream()- stdout = new FakeStream()- stderr = new FakeStream()- private listeners = new Map<string, Array<(event: any) => void>>()-- constructor() {- FakeChildProcess.instances.push(this)++ /** What the client calls on an intentional shutdown; the real 'close' event lands later. */++ close(_code = 1000) {++ this.readyState = FakeWebSocket.CLOSING+ }+- kill() {- this.killed = true-- return true++ open() {++ this.readyState = FakeWebSocket.OPEN++ this.emit('open', {})+ }+- on(type: string, callback: (event: any) => void) {- const entries = this.listeners.get(type) ?? []-- entries.push(callback)- this.listeners.set(type, entries)++ /** The transport-side close event (late for a killed socket, unexpected for a live one). */++ closed(code: number) {++ this.readyState = FakeWebSocket.CLOSED++ this.emit('close', { code })+ }+- emit(type: string, ...args: unknown[]) {++ private emit(type: string, event: any) {+ for (const callback of [...(this.listeners.get(type) ?? [])]) {- callback(...args)++ callback(event)+ }+ }+ }+- const fakeSpawn = vi.fn(() => new FakeChildProcess())-- return { fakeSpawn, FakeChildProcess }++ return { FakeWebSocket }+ })+-vi.mock('node:child_process', () => ({ spawn: fakeSpawn }))-vi.mock('node:fs', () => ({ existsSync: vi.fn(() => false) }))++vi.mock('undici', () => ({ WebSocket: FakeWebSocket }))++ import { GatewayClient } from '../gatewayClient.js'+-describe('GatewayClient spawn-mode kill latch (issue #114987)', () => {++const grant = { url: 'ws://gateway.test/api/ws', protocols: [], instance_id: 'owner', profile_id: 'fixture' }++++describe('GatewayClient kill latch (issue #114987)', () => {++ const originalWebSocket = globalThis.WebSocket+ let originalGatewayUrl: string | undefined+ let originalSidecarUrl: string | undefined++ beforeEach(() => {+ originalGatewayUrl = process.env.HERMES_TUI_GATEWAY_URL+ originalSidecarUrl = process.env.HERMES_TUI_SIDECAR_URL+ delete process.env.HERMES_TUI_GATEWAY_URL+ delete process.env.HERMES_TUI_SIDECAR_URL- fakeSpawn.mockClear()- FakeChildProcess.instances.length = 0++ FakeWebSocket.reset()++ ;(globalThis as { WebSocket?: unknown }).WebSocket = FakeWebSocket as unknown as typeof WebSocket++ vi.useFakeTimers()+ })++ afterEach(() => {++ vi.useRealTimers()+++ if (originalGatewayUrl === undefined) {+ delete process.env.HERMES_TUI_GATEWAY_URL+ } else {+ process.env.HERMES_TUI_GATEWAY_URL = originalGatewayUrl+ }++ if (originalSidecarUrl === undefined) {+ delete process.env.HERMES_TUI_SIDECAR_URL+ } else {+ process.env.HERMES_TUI_SIDECAR_URL = originalSidecarUrl+ }+- fakeSpawn.mockClear()- FakeChildProcess.instances.length = 0++ FakeWebSocket.reset()++++ if (originalWebSocket) {++ globalThis.WebSocket = originalWebSocket++ } else {++ delete (globalThis as { WebSocket?: unknown }).WebSocket++ }+ })+- it('a killed child late exit does not respawn a replacement gateway', async () => {- const gw = new GatewayClient()++ const startAndConnect = async (gw: GatewayClient) => {++ gw.start()++ gw.drain()++ await vi.advanceTimersByTimeAsync(0)++ expect(FakeWebSocket.instances).toHaveLength(1)++ FakeWebSocket.instances[0]!.open()++ }++++ it('a killed transport late close does not respawn a replacement gateway', async () => {++ const gw = new GatewayClient(async () => grant)+ const exits: Array<null | number> = []++ // The recovery subscriber useMainApp installs: an emitted 'exit' with a+ // session to recover restarts the gateway.+ gw.on('exit', code => {+ exits.push(code)++ if (exits.length === 1) {+ gw.start()+ }+ })+- gw.start()- gw.drain()- await Promise.resolve()- expect(fakeSpawn).toHaveBeenCalledTimes(1)++ await startAndConnect(gw)+- // Intentional kill (graceful-exit cleanup, dead PTY): the reference must- // be detached before the kill so the late exit is identity-skipped and- // the recovery subscriber never sees an 'exit' to restart from.++ // Intentional kill (graceful-exit cleanup, dead PTY): the reference is++ // detached before close() so the late close is identity-skipped and the++ // recovery subscriber never sees an 'exit' to restart from.+ gw.kill('graceful-exit-cleanup')- FakeChildProcess.instances[0]!.emit('exit', null, 'SIGTERM')++ FakeWebSocket.instances[0]!.closed(1006)++ await vi.advanceTimersByTimeAsync(60_000)++ expect(exits).toEqual([])- expect(fakeSpawn).toHaveBeenCalledTimes(1)++ expect(FakeWebSocket.instances).toHaveLength(1)++ expect(vi.getTimerCount()).toBe(0)+ })+- it('start() after kill() is refused even when called directly', () => {- const gw = new GatewayClient()++ it('start() after kill() is refused even when called directly', async () => {++ const gw = new GatewayClient(async () => grant)+- gw.start()- expect(fakeSpawn).toHaveBeenCalledTimes(1)++ await startAndConnect(gw)++ gw.kill('app.die')+ gw.start()- expect(fakeSpawn).toHaveBeenCalledTimes(1)++ await vi.advanceTimersByTimeAsync(0)++ expect(FakeWebSocket.instances).toHaveLength(1)+ })+- it('an unexpected child death still respawns through the recovery subscriber', async () => {- const gw = new GatewayClient()++ it('an unexpected transport close still respawns through the recovery subscriber', async () => {++ const gw = new GatewayClient(async () => grant)+ const exits: Array<null | number> = []++ gw.on('exit', code => {+ exits.push(code)++ if (exits.length === 1) {+ gw.start()+ }+ })+- gw.start()- gw.drain()- await Promise.resolve()++ await startAndConnect(gw)+- // Crash while the TUI is alive: identity intact, exit must be emitted.- FakeChildProcess.instances[0]!.emit('exit', 1, null)++ try {++ // Crash while the TUI is alive: identity intact, exit must be emitted.++ FakeWebSocket.instances[0]!.closed(1011)++ await vi.advanceTimersByTimeAsync(0)+- expect(exits).toEqual([1])- expect(fakeSpawn).toHaveBeenCalledTimes(2)++ expect(exits).toEqual([1011])++ expect(FakeWebSocket.instances).toHaveLength(2)++ } finally {++ gw.kill()++ }+ })+ })diff --cc ui-tui/src/app/createGatewayEventHandler.tsindex 386e315281c,ced683d85ad..d891f4e70d0--- a/ui-tui/src/app/createGatewayEventHandler.ts+++ b/ui-tui/src/app/createGatewayEventHandler.ts@@@ -799,44 -793,24 +805,61 @@@ export function createGatewayEventHandlreturn}+ // 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+ }+switch (ev.type) {+ case 'connection.request':+ if (ev.payload) {+ applyConnectionRequest(ev.payload)+ }++ return++ case 'connection.update':+ if (ev.payload) {+ // The settling frame is the only record of how each app ended; the card is gone by then.+ for (const line of applyConnectionUpdate(ev.payload)) {+ sys(line)+ }+ }++ return+case 'gateway.ready':handleReady(ev.payload?.skin)diff --cc ui-tui/src/app/turnController.tsindex 423f8fb99f1,e91462e6b86..4e753ff588b--- a/ui-tui/src/app/turnController.ts+++ b/ui-tui/src/app/turnController.ts@@@ -10,15 -10,16 +10,17 @@@ importimport type { SessionInterruptResponse } from '../gatewayTypes.js'import { appendToolShelfMessage, isToolShelfMessage } from '../lib/liveProgress.js'import { hasReasoningTag, splitReasoning } from '../lib/reasoning.js'+import { rpcErrorMessage } from '../lib/rpc.js'import {boundedLiveRenderText,- buildToolTrailLine,- buildVerboseToolTrailLine,estimateTokensRough,+ formatToolCall,+ formatToolLabel,isTransientTrailLine,sameToolTrailGroup,- toolTrailLabel+ toolTrailLabel,+ toolTrailLine,+ verboseToolTrailLine} from '../lib/text.js'import type { ActiveTool, ActivityItem, Msg, SubagentProgress, TodoItem } from '../types.js'diff --cc ui-tui/src/app/useInputHandlers.tsindex f97f6d769bf,27867214f52..d574029125f--- a/ui-tui/src/app/useInputHandlers.ts+++ b/ui-tui/src/app/useInputHandlers.ts@@@ -6,8 -5,8 +6,8 @@@ import { sharedControlParams } from '..import { DASHBOARD_TUI_MODE } from '../config/env.js'import { DOUBLE_ESC_MS, TYPING_IDLE_MS } from '../config/timing.js'import { applyCompletion } from '../domain/slash.js'-import type { ConfigSetResponse, VoiceRecordResponse } from '../gatewayTypes.js'+import type { ConfigSetResponse, SharedControlRespondResponse, VoiceRecordResponse } from '../gatewayTypes.js'- import { isAction, isCopyShortcut, isMac, isVoiceToggleKey } from '../lib/platform.js'+ import { isAction, isCopyShortcut, isMac, isMacActionFallback, isVoiceToggleKey } from '../lib/platform.js'import { computePrecisionWheelStep, initPrecisionWheel } from '../lib/precisionWheel.js'import { computeWheelStep, initWheelAccelForHost } from '../lib/wheelAccel.js'import { closeWidget, dispatchWidgetInput } from '../sdk/host.js'diff --cc ui-tui/src/app/useMainApp.tsindex 6c054735f22,248a659d4c4..872bbcc6bf8--- a/ui-tui/src/app/useMainApp.ts+++ b/ui-tui/src/app/useMainApp.ts@@@ -55,13 -54,12 +55,14 @@@ import { createServerRequestHandler } fimport { createSlashHandler } from './createSlashHandler.js'import { planGatewayRecovery } from './gatewayRecovery.js'import { getInputSelection } from './inputSelectionStore.js'-import { type GatewayRpc, type StateSetter, type TranscriptRow } from './interfaces.js'-import { $overlayState, patchOverlayState } from './overlayStore.js'+import { type GatewayRpc, type SlashHandler, type StateSetter, type TranscriptRow } from './interfaces.js'+import { $overlayState, capturePromptResponseGuard, patchOverlayState } from './overlayStore.js'import { $goodVibesTick } from './petFlashStore.js'+ import { applyProcessSnapshot, type ProcessEntry } from './processRoster.js'import { scrollWithSelectionBy } from './scroll.js'import { respondToServerRequest } from './serverRequestStore.js'+import { mutateCanonicalSession } from './slash/canonicalSessionControls.js'+import { captureDestination, isCurrentDestination, type SubmissionDestination } from './submissionDestination.js'import { turnController } from './turnController.js'import { patchTurnState, useTurnSelector } from './turnStore.js'import { $uiState, getUiState, patchUiState } from './uiStore.js'diff --cc ui-tui/src/app/useSessionLifecycle.tsindex 4a6cdb64d0f,5c89b56962f..67be0999918--- a/ui-tui/src/app/useSessionLifecycle.ts+++ b/ui-tui/src/app/useSessionLifecycle.ts@@@ -400,21 -300,12 +403,23 @@@ export function useSessionLifecycle(optconst activateLiveSession = useCallback((id: string) => {+ const flight = ++attachmentFlight.current+ pendingAttachments.current.add(flight)+ const previousSid = getUiState().sid+ const previousSubscription = previousSid ? canonicalSubscriptions.current.get(previousSid) : undefinedpatchOverlayState({ sessions: false })patchUiState({ status: 'switching session…' })+ // The card belongs to the session being left; the activated one answers with its own.+ clearConnectionOperation()- gw.request<SessionActivateResponse>('session.activate', { session_id: id })+ const pendingDetach = canonicalDetachFlights.current.get(id)++ const request = pendingDetach+ ? pendingDetach.then(() => flight === attachmentFlight.current+ ? gw.request<SessionActivateResponse>('session.activate', { session_id: id }) : null)+ : gw.request<SessionActivateResponse>('session.activate', { session_id: id })++ request.then(raw => {const r = asRpcResult<SessionActivateResponse>(raw)@@@ -450,16 -334,16 +455,21 @@@storedSid,usage: usageFrom(info)})+ // resetSession dropped the previous session's controls; the snapshot's+ // still-pending approval/clarify prompts are the only way they come back.+ gw.hydrateSharedPrompts?.(r)hydrateLiveSessionInflight(r.inflight)++ if (r.pending_connection) {+ applyConnectionRequest(r.pending_connection)+ }+cancelResumeScrollRef.current?.()cancelResumeScrollRef.current = scheduleResumeScrollToBottom(scrollRef)+ adoptAttachment(r, previousSid, previousSubscription)}).catch((e: Error) => {+ if (flight !== attachmentFlight.current) {return}sys(`error: ${e.message}`)patchUiState({ status: 'ready' })})@@@ -539,8 -397,14 +549,15 @@@storedSid,usage: usageFrom(info)})+ gw.hydrateSharedPrompts?.(r)hydrateLiveSessionInflight(r.inflight)++ if (r.pending_connection) {+ applyConnectionRequest(r.pending_connection)+ } else {+ clearConnectionOperation()+ }+cancelResumeScrollRef.current?.()cancelResumeScrollRef.current = scheduleResumeScrollToBottom(scrollRef)diff --cc ui-tui/src/gatewayClient.tsindex b6170bfc669,cdba97ff312..3b8e7d497b0--- a/ui-tui/src/gatewayClient.ts+++ b/ui-tui/src/gatewayClient.ts@@@ -137,8 -133,15 +137,15 @@@ export class GatewayClient extends Even// only owns the two transports (child stdio, attached socket) and the// buffered-event replay that Ink's mount order needs.private readonly channel = new JsonRpcRequestChannel({+ // A mid-turn socket streams deltas every second; killing the only+ // transport that carried live traffic split sessions that completed+ // server-side (#115251). Count any inbound frame as liveness, exactly+ // like the desktop/web client; a silent drop still trips the deadline.+ heartbeatLiveness: 'any-inbound',- onEvent: ev => this.publish(ev as AnyGatewayEvent),+ onEvent: ev => this.publishWire(ev as AnyGatewayEvent),onHeartbeatFailure: () => this.onHeartbeatFailure(),+ onRequestHandlerError: (error, req) =>+ this.pushLog(`[protocol] server request handler crashed: ${req.method} (${error.message})`),onUnhandledRequest: req => this.pushLog(`[protocol] unhandled server request: ${req.method}`),requestTimeoutMs: REQUEST_TIMEOUT_MS,unrefTimers: truediff --cc ui-tui/src/gatewayTypes.tsindex 57566f21737,832f8e028af..57f8d2f927a--- a/ui-tui/src/gatewayTypes.ts+++ b/ui-tui/src/gatewayTypes.ts@@@ -1,7 -1,8 +1,8 @@@import type { UsageModelData } from '@hermes/shared/billing'import type {+ ConnectionRequestPayload,GatewayEvent,- GatewayEventName,+ GatewayEventMap,InflightTurn,TranscriptMessage,Usagediff --cc ui-tui/src/types.tsindex 3820c19bef6,b44ea9ed834..f8d93d4af78--- a/ui-tui/src/types.ts+++ b/ui-tui/src/types.ts@@@ -1,7 -1,5 +1,7 @@@- import type { ProjectInfo, SessionLiveInfo, SubagentStatus } from '@hermes/shared/gateway-events'+ import type { ProjectInfo, SessionLiveInfo, SubagentStatus, ToolLabel } from '@hermes/shared/gateway-events'+import type { SharedControl } from './canonicalGateway.js'+export interface ActiveTool {context?: stringid: stringdiff --cc web/src/lib/api.tsindex 6c0f7d24962,47e063f37d7..5371fbb2d9d--- a/web/src/lib/api.ts+++ b/web/src/lib/api.ts@@@ -3,10 -3,9 +3,12 @@@ importtype ModelOptionProvider,type ModelOptionsResult,} from "@hermes/shared";+import { createDashboardSessionMutations } from "./session-mutations";++const mutateSessionHttp = createDashboardSessionMutations(fetchJSON);+ import { dashboardServingProfile } from "./profile-bootstrap";+// The dashboard can be served either at the root of its host (e.g.// https://kanban.tilos.com/) or under a URL prefix when reverse-proxied// (e.g. https://mission-control.tilos.com/hermes/). The Python backenddiff --cc website/docs/developer-guide/context-compression-and-caching.mdindex ef72519df8b,d80b893596d..fefed9174d2--- a/website/docs/developer-guide/context-compression-and-caching.md+++ b/website/docs/developer-guide/context-compression-and-caching.md@@@ -4,9 -4,38 +4,38 @@@ Hermes Agent uses a dual compression symanage context window usage efficiently across long conversations.Source files: `agent/context_engine.py` (ABC), `agent/context_compressor.py` (default engine),-`agent/prompt_caching.py`, `gateway/run_turn.py` (session hygiene), `agent/compression_facade.py` (search for `_compress_context`)+`agent/prompt_caching.py`, `gateway/run_turn_hygiene.py` (session hygiene), `agent/compression_facade.py` (search for `_compress_context`)+ ## Bedrock context window cache++ Bedrock context resolution in `agent/model_metadata.py` uses this precedence:++ - **Explicit overrides win.** Configured context lengths take priority over cache,+ probes, and the static table.+ - **Provider-confirmed limits persist.** A successful probe or a limit learned+ from a provider error remains authoritative, even below the static table.+ The compressor uses the same value after restart.+ - **Legacy entries are revalidated.** Old scalar entries have no provenance and+ may be either probe results or fallbacks. Their size does not establish which.+ - **Failed probes use the current table without persisting it.** Failures have a+ five-minute in-memory cooldown scoped to Hermes home, endpoint, model, and+ region. Expiry or explicit cache invalidation permits another attempt.++ The cache remains at `context_length_cache.yaml` under the active Hermes home.+ `context_lengths` retains scalar values for older readers. An additive+ `bedrock_confirmed_v1` map binds each confirmed key to its exact value in the+ same atomic write. Generic writes clear that key's provenance. Older writers+ may drop the additive map, which causes revalidation after upgrading again.+ Downgrading remains readable but restores the older runtime's resolution rules.++ The static fallback for `xai.grok-4.6` (including `global.` and `us.` inference+ profiles) is 500,000 tokens, per the+ [AWS model card](https://docs.aws.amazon.com/bedrock/latest/userguide/model-card-xai-grok-4-6.html).+ This is Bedrock-specific, not the direct xAI API window. Existing compression+ rules still apply: without output reservation, the small-window 75% threshold floor+ yields 375,000 at this window, which the default `threshold_tokens` cap (256,000) then lowers.+## Pluggable Context EngineContext management is built on the `ContextEngine` ABC (`agent/context_engine.py`). The built-in `ContextCompressor` is the default implementation, but plugins can replace it with alternative engines (e.g., Lossless Context Management).diff --cc website/docs/reference/cli-commands.mdindex b6c1129b487,03d148f441f..3aab0fb45c3--- a/website/docs/reference/cli-commands.md+++ b/website/docs/reference/cli-commands.md@@@ -130,9 -132,8 +132,9 @@@ Common options| `--pass-session-id` | Pass the session ID into the system prompt. || `--ignore-user-config` | Ignore `~/.hermes/config.yaml` and use built-in defaults. Credentials in `.env` are still loaded. Useful for isolated CI runs, reproducible bug reports, and third-party integrations. || `--ignore-rules` | Skip auto-injection of `AGENTS.md`, `SOUL.md`, `.cursorrules`, persistent memory, and preloaded skills. Combine with `--ignore-user-config` for a fully isolated run. |-| `--safe-mode` | Troubleshooting mode: disable ALL customizations — user config, rules/memory injection, plugins, shell hooks, and MCP servers (implies `--ignore-user-config` and `--ignore-rules`). Use to isolate whether a problem comes from your setup or from Hermes itself. |+| `--safe-mode` | Troubleshooting mode: disable ALL customizations — user config, rules/memory injection, plugins, shell hooks, and MCP servers (implies `--ignore-user-config` and `--ignore-rules`). The gateway freezes code defaults plus your explicit options into the session and runs the turn in an isolated worker process that never reads the profile, so a broken `config.yaml` cannot block it. Requires an explicit `--model` (there is no profile default to inherit); pair with `--provider custom --base-url <url> --api-key <key>` for a fully explicit endpoint. |+| `--base-url <url>` / `--api-key <key>` | Explicit OpenAI-compatible endpoint and launch-only key for `--provider custom`. The key is held in the running gateway's memory for this session and never written to disk. |- | `--source <tag>` | Session source tag for filtering (default: `cli`). Use `tool` for third-party integrations that should not appear in user session lists. |+ | `--source <tag>` | Session source tag for filtering (default: `cli`; one-shot runs default to `oneshot`, which pickers hide). Use `tool` for third-party integrations that should not appear in user session lists. An explicit `--source` is always stored as given, even for a one-shot run launched from inside a TUI or Desktop session. || `--max-turns <N>` | Maximum tool-calling iterations per conversation turn (default: 500, or `agent.max_turns` in config). |Examples:@@@ -348,78 -352,9 +359,78 @@@ stopped`hermes gateway enroll` accepts `--token`, `--connector-url`, `--gateway-id`, and `--wake-url`. It exchanges the enrollment token with the connector and writes the resulting `GATEWAY_RELAY_ID`, `GATEWAY_RELAY_SECRET`, `GATEWAY_RELAY_DELIVERY_KEY`, optional `GATEWAY_RELAY_URL`, and (when `--wake-url` is given) `GATEWAY_RELAY_WAKE_URL` values to the active profile's `.env`.:::tip WSL users- Use `hermes gateway run` instead of `hermes gateway start` — WSL's systemd support is unreliable. Wrap it in tmux for persistence: `tmux new -s hermes 'hermes gateway run'`. See [WSL FAQ](/reference/faq#wsl-gateway-keeps-disconnecting-or-hermes-gateway-start-fails) for details.+ Use `hermes gateway run` instead of `hermes gateway start` — WSL's systemd support is unreliable. Wrap it in tmux for persistence: `tmux new -s hermes 'hermes gateway run'`. See [WSL FAQ](./faq.md#wsl-gateway-keeps-disconnecting-or-hermes-gateway-start-fails) for details.:::+### Local runtime discovery and startup++```bash+hermes gateway ensure --json --timeout 30+```++`ensure` targets the active profile and emits one JSON object with `state`,+`reason_code`, and `endpoint`. The endpoint is present only when authenticated+local discovery reports compatible session readiness. Output contains no bootstrap+tickets or bearer credentials. JSON is also the default without `--json`.++The timeout is a finite, positive total deadline in seconds (default `30`). An+existing reservation or starting owner is waited for, not replaced. When absence+is established, an existing service takes precedence; an unmanaged process is+requested only when no service is found. This command never installs or rewrites+service definitions, enables linger, elevates privileges, or clears update fences.+Ambiguous or inaccessible ownership fails closed.++Before requesting a service start, `ensure` checks its canonical profile directory+and execution account, not just its unit/task name. Linux uses the manager's+loaded command and environment (including effective drop-ins), macOS checks the+loaded launchd job rather than assuming the on-disk plist is current, and Windows+queries the actual task XML, principal, and installed launcher.++- `profile_mismatch`: the installed service selects a different home or profile.+ Inspect the selected service's `HERMES_HOME` and command-line profile selector;+ use the matching profile or explicitly repair the service configuration.+- `service_account_mismatch`: the service belongs to another account. Run the+ client as that account, or explicitly configure a service for the intended user.+- `service_identity_unverified`: the manager did not expose enough identity data,+ or the definition uses unsupported dynamic configuration. Inspect it with+ `systemctl [--user] show <unit> --all`, `launchctl print <domain>/<label>`, or+ `schtasks /Query /TN <task> /XML`. Linux environment files, PAM/dynamic users,+ start-time hooks and alternate root filesystems require operator review;+ arbitrary shell launchers and modified Windows launcher scripts are not+ interpreted by `ensure`. Restore an explicit supported definition through an+ intentional service-management operation before retrying.++These refusals do not start a service, rewrite configuration, or launch an+unmanaged replacement. Standard explicitly bound default and custom-root installs+remain eligible; a successful start request still must pass live readiness checks.++On POSIX, local bootstrap requires an owner-only profile directory. Newly reserved+homes are created with mode `0700`; existing permissions are never changed by+`ensure`. An existing home readable by other users returns+`inaccessible / unsafe_control_permissions`. Review the directory's intended+sharing policy and explicitly make it private before retrying local attachment.++| Exit code | Meaning |+|-----------|---------|+| `0` | Compatible session runtime ready. |+| `2` | Invalid invocation, including invalid timeout or unknown arguments. |+| `3` | Incompatible runtime protocol or capabilities. |+| `4` | Authorization or profile mismatch. |+| `5` | Deadline reached; startup may still be pending. |+| `6` | Runtime draining or update in progress. |+| `7` | Inaccessible runtime, conflicting supervisor, or startup failure. |++A service start command or process creation is not a readiness acknowledgement.+A gateway that has not exposed the session-authority capability can remain+`starting` until the deadline even while its messaging adapters work. Do not treat+exit `5` as permission to replace that owner. On Windows, a Startup-folder-only+installation requires login rather than an unmanaged fallback; failure to detach+from a parent job is reported instead of retried with weaker process isolation.++Service persistence is separately opt-in during setup. Imports and noninteractive+setup do not install a missing service based on an imported preference. See+[optional service installation](../developer-guide/gateway-internals.md#optional-service-installation).+## `hermes lsp````bashdiff --cc website/docs/reference/environment-variables.mdindex 359a1de6990,17889cbe8b7..9b5e6db3cff--- a/website/docs/reference/environment-variables.md+++ b/website/docs/reference/environment-variables.md@@@ -809,12 -822,10 +822,10 @@@ Advanced per-platform knobs for throttl| `HERMES_ACCEPT_HOOKS` | Auto-approve any unseen shell hooks declared in `config.yaml` without a TTY prompt. Equivalent to `--accept-hooks` or `hooks_auto_accept: true`. || `HERMES_IGNORE_USER_CONFIG` | Skip `~/.hermes/config.yaml` and use built-in defaults (credentials in `.env` still load). Equivalent to `--ignore-user-config`. || `HERMES_IGNORE_RULES` | Skip auto-injection of `AGENTS.md`, `SOUL.md`, `.cursorrules`, memory, and preloaded skills. Equivalent to `--ignore-rules`. |-| `HERMES_SAFE_MODE` | Troubleshooting mode: disable ALL customizations — skips plugin discovery, MCP server loading, and shell-hook registration. Set automatically by `--safe-mode` (which also sets the two flags above). |+| `HERMES_SAFE_MODE` | Legacy in-process troubleshooting switch: skips plugin discovery, MCP server loading, and shell-hook registration for that process. `hermes chat --safe-mode` no longer sets it — the gateway freezes the safe policy into the session and executes it in an isolated worker instead, so the running daemon's environment is never mutated. || `HERMES_TOOL_PROGRESS` | Unsupported since the config-v12 support floor — the variable is ignored. Use `display.tool_progress` in `config.yaml`. || `HERMES_TOOL_PROGRESS_MODE` | Deprecated compatibility variable for tool progress mode (still read by the gateway as a fallback). Prefer `display.tool_progress` in `config.yaml`. |- | `HERMES_HUMAN_DELAY_MODE` | Response pacing: `off`/`natural`/`custom` |- | `HERMES_HUMAN_DELAY_MIN_MS` | Custom delay range minimum (ms) |- | `HERMES_HUMAN_DELAY_MAX_MS` | Custom delay range maximum (ms) |+ | `HERMES_HUMAN_DELAY_MODE` / `HERMES_HUMAN_DELAY_MIN_MS` / `HERMES_HUMAN_DELAY_MAX_MS` | No longer read. Response pacing is the `human_delay` section of each profile's `config.yaml` (`mode`, `min_ms`, `max_ms`), so multiplexed profiles keep independent pacing. || `HERMES_QUIET` | Suppress non-essential output (`true`/`false`) || `CODEX_HOME` | When [Codex app-server runtime](../user-guide/features/codex-app-server-runtime) is enabled, override the directory Codex CLI reads its config + auth from (default: `~/.codex`). Hermes' migration writes the managed block to `<CODEX_HOME>/config.toml`. || `HERMES_KANBAN_TASK` | Set by the kanban dispatcher when spawning a worker (task UUID). Workers and the spawned `hermes-tools` MCP subprocess inherit it so kanban tools gate correctly. Don't set manually. |diff --cc website/docs/user-guide/desktop.mdindex 6f9d03f3a22,67fe84f888a..2cca6e9838d--- a/website/docs/user-guide/desktop.md+++ b/website/docs/user-guide/desktop.md@@@ -47,12 -47,14 +47,14 @@@ The center of the app. You get- **The same conversation history** as every other Hermes surface — sessions started here resume in the CLI/TUI and vice versa.- **Drag-and-drop files** anywhere in the chat area to attach them to your next message.- **Independent background drafts** — hidden chat tabs can update their drafts without moving the caret or selection in the visible composer.+ - **Unsent drafts survive a lost session** — a draft you typed into a chat whose session no longer exists (deleted elsewhere, or a stale tab after a profile rename or wiped backend) is carried into the fresh chat the app falls back to, with an inline **Restored your unsent message** strip above the input. **Undo** puts the text back where it was; nothing is sent, navigated, or focused on your behalf, and the strip appears once per lost draft.- **Directive chip actions** — hover an actionable reference (such as a URL) to reveal its action pill. A short grace period lets you move from the chip to the pill before it dismisses. The pill stays available while you move within it; after leaving, unrelated pointer movement does not delay dismissal. Clicking its action preserves the draft selection.- **A right-hand preview rail** — render web pages, files, and tool outputs side by side while you keep chatting.+ - **Hide vs. Close for stateful panes** — a zone holding a Browser (or HTML preview) or the Terminal pane offers **Hide** instead of Minimize. Hiding collapses the zone to its restore rail but keeps the pane's body mounted: a live page keeps its unsaved form input, timers, scroll position, and the agent's `drive_preview` automation target; a terminal keeps its running shell and scrollback; and **Restore** shows the same content without a reload. The hidden body is inert — it never takes keyboard shortcuts or steals composer focus. **Close** (the tab's ×) is what actually releases the page or shell.- **Comment mode in the in-app browser** — click **Annotate** in the preview browser bar, then click any element (or drag a box) on the live page and type a note; each saved comment stays as a numbered pin on the page. Saving a pin never sends a turn — when you're done, **Add N comments** attaches a cropped screenshot per pin and a short prompt naming each comment to the composer, and you still hit send yourself. Each element comment carries its CSS selector, its markup, and the computed styles that matter for layout, so the agent can find the element in your source instead of guessing from the picture. Password and hidden field values, and any attribute that looks like a key or token, are redacted on the page before the markup leaves it. Larger batches arrive grouped by which part of the page each comment sits in, so twenty-odd comments become a handful of pieces of work rather than one task each — and because the groups are separate DOM subtrees they usually touch separate files, which is what makes handing them to parallel workers safe. Pin numbers hold steady if you delete one, and switching chats clears the stack.-- **Composer history and queue editing** — press the up/down arrow keys in an empty composer to recall and reuse previous prompts, and edit messages you've queued up before they're sent. Pressing Stop (or Esc) while turns are queued pauses the queue and expands it above the composer; resume it from there, or send, edit, and delete individual entries.+- **Composer history and queue editing** — press the up/down arrow keys in an empty composer to recall and reuse previous prompts, and edit messages you've queued up before they're sent. Pressing Stop (or Esc) while turns are queued pauses the queue and expands it above the composer; resume it from there, or send, edit, and delete individual entries. The queue itself lives on the gateway, so it survives an app or gateway restart and every window attached to the same chat sees the same list. If the gateway restarts while a turn is mid-flight, that turn cannot be finished or safely repeated: the queue shows it as **Turn lost during restart** with a single **Discard** button, and the turns queued behind it wait until you discard it. Your text stays in the transcript to resend. (The gateway CLI has the same control as `/discard <admission_id>`.)- **Task progress above the composer** — expand the Tasks header to inspect each phase. Long lists stay bounded above the input; scroll inside the expanded list to reach the final tasks without moving the conversation.- - **A conversation timeline rail** — long chats get a slim rail of markers along the edge of the transcript, one per prompt. Hover it to pop open the list of prompts, click one to jump straight to that point in the conversation. (It appears once the chat has a handful of turns.)+ - **A conversation timeline rail** — long chats get a slim rail of markers along the edge of the transcript, one per prompt. Hover it to pop open the list of prompts, click one to jump straight to that point in the conversation. After a jump, **Show earlier** at the top of the transcript keeps paging backwards from that prompt all the way to the start of the session. (It appears once the chat has a handful of turns.)- **Reading-position memory** — returning to a session restores its saved distance from the bottom instead of always jumping to the latest message. Sessions left at the bottom continue following new output. Use **Scroll to bottom** to return to the live edge. Positions are kept in this Desktop installation's local storage; they are not synchronized through the backend.- **Find in page** — press **Cmd/Ctrl+F** to open a find bar that searches the rendered chat transcript. Enter / Shift+Enter (or Cmd/Ctrl+G / Cmd/Ctrl+Shift+G while the bar is open) step through matches; Esc closes it.@@@ -112,10 -114,10 +114,12 @@@ Explore and preview the working directo### Artifacts+ Preview links above the composer are session suggestions, not a task-completion checklist. Dismissing one keeps historical tool rows from bringing it back after navigation or reload. A new successful tool completion can offer the file again. Read-only file inspection and failed writes do not create suggestions. Files with the same name show enough directory context to distinguish them; dismissing a suggestion does not delete its file or transcript. Changing a `/goal` does not erase a conversation's artifacts.+When connected to a remote gateway, opening a file artifact downloads it through that gateway, using the artifact’s originating profile and session. Relative paths resolve against the session’s saved working directory; home-relative paths use the gateway’s home, never the Desktop machine’s home. Windows-style relative paths are recognized alongside forward-slash paths, and file URIs retain drive and network-share information for the gateway to interpret. Missing sessions or working directories produce an error rather than selecting a different local file.+If Desktop closes before an image message is acknowledged, reopen its original chat. The **Restore image draft** button above the composer restores the saved text and image attachment together; press Send to retry the original submission. It never sends automatically or replaces a newer draft.+The **Artifacts** view collects what your sessions generate — **images, files, and links** — into one searchable, browsable gallery. Open it from the sidebar, the command palette (**Artifacts — Browse generated outputs**), or a `nav.artifacts` shortcut you bind yourself. It indexes recent session outputs automatically; every artifact shows which session produced it with a jump back to that chat, and images and files open in a preview with download / open-in-browser / copy actions.### Windows, tabs & panesdiff --cc website/docs/user-guide/features/api-server.mdindex 3397216a785,32d586ffb99..995e04136e4--- a/website/docs/user-guide/features/api-server.md+++ b/website/docs/user-guide/features/api-server.md@@@ -51,26 -51,8 +51,26 @@@ curl http://localhost:8642/v1/chat/comp-d '{"model": "hermes-agent", "messages": [{"role": "user", "content": "Hello!"}]}'```- Or connect Open WebUI, LobeChat, or any other frontend — see the [Open WebUI integration guide](/user-guide/messaging/open-webui) for step-by-step instructions.+ Or connect Open WebUI, LobeChat, or any other frontend — see the [Open WebUI integration guide](../messaging/open-webui.md) for step-by-step instructions.+## Conversation and terminal-result semantics++API requests use the gateway's durable admission queue. Structured image content stays+structured through execution; it is not interpreted as a gateway slash command.++- `/v1/runs` and `/v1/responses` retain the conversation declared by+ `X-Hermes-Session-Key`. An explicit session or response chain takes precedence and+ does not transfer its conversation identity to a different header.+- A nonempty `/v1/runs` `conversation_history` is authoritative, even with an explicit+ `session_id`. Otherwise session continuation loads history when the turn executes,+ after earlier queued work finishes.+- Runs polling and SSE agree on `cancelled` or `failed`. Responses uses the same+ terminal status and `response.cancelled` / `response.failed` events, including when+ diagnostic text is present. Chat Completions reports `finish_reason: "cancelled"`+ for interrupted turns and `"error"` for failures, not a successful `"stop"`.+- Session-chat replies include `status`; their streams report matching terminal run+ events. An assistant finalization frame is not itself proof of successful execution.+## Endpoints### POST /v1/chat/completionsdiff --cc website/docs/user-guide/features/cron.mdindex 7e60bbb7f28,c419c6db59b..ce84a9ce39f--- a/website/docs/user-guide/features/cron.md+++ b/website/docs/user-guide/features/cron.md@@@ -273,13 -265,8 +278,13 @@@ What they do- `run` — trigger the job on the next scheduler tick- `remove` — delete it entirely- `edit` — modify schedule, prompt, delivery, etc.+- `tick` — run one scheduler pass and exit (for a system crontab or other external+ scheduler). **The gateway must be running:** agent jobs execute inside the gateway, and a+ tick never starts one. With no gateway up, agent jobs are skipped with a logged reason+ (`hermes cron list` shows it) and fire on the next tick after `hermes gateway start`; their+ schedule is not advanced or penalised. `no_agent` script jobs still run from a bare tick.- **Name-based lookup.** All four mutating verbs (`pause`, `resume`, `run`, `remove`, `edit`) plus the agent's `cronjob` tool now accept a job **name** (case-insensitive) in place of the hex ID. The agent and CLI both prefer an exact ID match if one exists; ambiguous name matches (multiple jobs sharing the same name) are refused with the full list of candidate IDs so you can pick one explicitly. Names are not unique, so this guard is load-bearing — it prevents silently mutating the wrong job when two share a name.+ **Name-based lookup.** All four mutating verbs (`pause`, `resume`, `run`, `remove`, `edit`) plus the agent's `cronjob_manage` tool now accept a job **name** (case-insensitive) in place of the hex ID. The agent and CLI both prefer an exact ID match if one exists; ambiguous name matches (multiple jobs sharing the same name) are refused with the full list of candidate IDs so you can pick one explicitly. Names are not unique, so this guard is load-bearing — it prevents silently mutating the wrong job when two share a name.### Pausing everything: `hermes pause`@@@ -818,10 -851,32 +868,22 @@@ cronOr set the `HERMES_CRON_MEDIA_SEND_TIMEOUT` environment variable. The resolution order is: env var → config.yaml → 300s default. A timed-out attachment is recorded in the job's run status as a partial delivery failure (the text still delivers).-## Bot Chat delivery timeout--A `bot-chat` delivery runs a full agent turn in the target bot's chat, so its bound is minutes, not seconds — 600s by default:--```yaml-# ~/.hermes/config.yaml-cron:- bot_chat_delivery_timeout_seconds: 900-```--A timed-out delivery is recorded in `last_delivery_error`; the bot's turn may still complete on its own.+## Bot Chat delivery completion-The cap bounds the bot's **turn** only. When that turn messages a teammate (`message_agent`), the delivery process stays alive afterwards — bounded by `terminal.oneshot_completion_wait_seconds` — so the teammate's reply can land in the Bot Chat; that wait is not part of the delivery and is never counted against, or cut short by, this cap.+A `bot-chat` delivery is admitted to the target profile's running gateway and executed there as a full agent turn. The job's run status records the admission receipt (`delivery_outcome=queued`) until the target's durable receipt settles; a retry of the same run reuses the same receipt and never re-admits. If the target profile's gateway is not running, the run is recorded `delivery_failed` and no local fallback turn is run.+ ## Standalone send timeout++ When the live gateway adapter cannot deliver (or no gateway is running), a target is sent through the platform's standalone sender. That send is bounded by a wall-clock timeout — 60 seconds by default — so a transport that is mid-reconnect cannot pin the job run (and a pending restart drain behind it) indefinitely:++ ```yaml+ # ~/.hermes/config.yaml+ cron:+ standalone_send_timeout_seconds: 120+ ```++ A timed-out send is recorded in `last_delivery_error` as `standalone send to <target> timed out after Ns`; the message may still land if the adapter had already accepted it.+## No-agent mode (script-only jobs)For recurring jobs that don't need LLM reasoning — classic watchdogs, disk/memory alerts, heartbeats, CI pings — pass `no_agent=True` at creation time. The scheduler runs your script on schedule and delivers its stdout directly, skipping the agent entirely:@@@ -842,11 -897,23 +904,23 @@@ Semantics- `{"wakeAgent": false}` on the last line → silent tick (same gate LLM jobs use).- No tokens, no model, no provider fallback — the job never touches the inference layer.-`.sh` / `.bash` files run under `bash` from `PATH` when available, otherwise `/bin/bash` (important on Windows Git Bash). Anything else runs under the current Python interpreter (`sys.executable`). Scripts must resolve inside `$HERMES_HOME/scripts/` — relative names, absolute paths, and `~`-prefixed paths are accepted when the resolved target stays in that directory; paths that escape it are rejected. Subprocess env is sanitized (`_sanitize_subprocess_env`): provider API credentials and other Hermes-managed secrets are **not** inherited by cron scripts.+`.sh` / `.bash` files run under `bash` from `PATH` when available, otherwise `/bin/bash` (important on Windows Git Bash). Anything else runs under the current Python interpreter (`sys.executable`). `script` is always a **file**, never a command line: `--script "echo hi"` is refused at creation (write the command into `~/.hermes/scripts/hi.sh` and pass `hi.sh`). Scripts must resolve inside `$HERMES_HOME/scripts/` — relative names, absolute paths, and `~`-prefixed paths are accepted when the resolved target stays in that directory; paths that escape it are rejected. Subprocess env is sanitized (`_sanitize_subprocess_env`): provider API credentials and other Hermes-managed secrets are **not** inherited by cron scripts.+ #### Giving a script a credential++ A script that must authenticate to an external service (an API token, a service-account key) gets it the same way terminal and `execute_code` children do — declare the variable name in the owning profile's `config.yaml` and define the value in that profile's `.env` (or an external [secret source](../secrets/index.md)):++ ```yaml+ terminal:+ env_passthrough:+ - MY_SERVICE_TOKEN+ ```++ The variable is forwarded into the script's environment with the **owning profile's** value: for a job that belongs to a profile served by a multi-profile gateway or the Desktop/dashboard backend, the value is resolved through that profile's secret scope, never the launch profile's process environment, and that profile's own `.env` credentials never reach another profile's scripts. Hermes-managed provider credentials (`OPENAI_API_KEY`, gateway tokens, …) cannot be declared — the sanitizer rejects them. On a single-profile install the script inherits what the gateway's `.env` put in the process environment, as before. Log presence (`set`/`MISSING`), never the value: script output is delivered verbatim.+### The agent sets these up for you- The `cronjob` tool's schema exposes `no_agent` to Hermes directly, so you can describe a watchdog in chat and let the agent wire it up:+ The `cronjob_manage` tool's schema exposes `no_agent` to Hermes directly, so you can describe a watchdog in chat and let the agent wire it up:```textPing me on Telegram if RAM is over 85%, every 5 minutes.