The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge origin/main (61154b6f68e8) into feat/unified-gateway-runtime
teknium143c477571e9b
diff --cc agent/prompt_builder.pyindex 8f0f3c56d27,2920190abda..966766d57c4--- a/agent/prompt_builder.py+++ b/agent/prompt_builder.py@@@ -1599,19 -1663,8 +1671,12 @@@ def build_context_files_promptAGENTS.md chain (git root → cwd) → CLAUDE.md (cwd) → .cursorrules + .cursor/rules/*.mdc (cwd). SOUL.mdfrom HERMES_HOME is independent and always included unless *skip_soul* (already the identity slot)."""+ from agent.safe_worker_policy import safe_worker_enabled++ if safe_worker_enabled():+ return ""cwd_path = Path(cwd if cwd is not None else os.getcwd()).resolve()- # A FALLBACK-picked cwd inside the Hermes install tree must not gain system-prompt authority (the desktop- # default would load this repo's contributor AGENTS.md). An explicit cwd is honored verbatim.- # An explicitly configured cwd is honored verbatim — the Hermes tree is a legitimate workspace when the- # user deliberately points a session at it — and CLI-style surfaces pass- # allow_install_tree_fallback=True because their launch dir IS the user's shell cwd (developing Hermes- # in-tree). See #64590.- from agent.runtime_cwd import _is_install_tree- if cwd is None and not allow_install_tree_fallback and _is_install_tree(cwd_path):+ if _project_context_suppressed(cwd, cwd_path, allow_install_tree_fallback):logger.warning("skipping project-context discovery: working-directory resolution fell back to the Hermes ""install tree (%s) — set terminal.cwd to your project directory", cwd_path,diff --cc apps/desktop/electron/main.tsindex 41b250fcbe6,62e0e48231c..a19870bc454--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@@ -1,17 -1,4 +1,17 @@@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(resolveHermesBackend([]))++ 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'@@@ -45,6 -32,8 +45,7 @@@ importimport { classifyActiveRuntime } from './active-runtime-state'import {destroyKeepaliveAgents,- downloadAgentFor,+ htmlResponseError,httpStatusError,jsonAgentFor,readStatusCode,@@@ -66,22 -56,17 +67,17 @@@ importprocessStartMarker,REAP_PROBE_TIMEOUT_MS} from './backend-claim'- import { dashboardFallbackArgs, sourceDeclaresServe } from './backend-command'+ import { dashboardFallbackArgs } from './backend-command'import { createBackendConnectionState } from './backend-connection-state'+import { assertDescriptorStillOwned, forgetFailedDescriptor } from './backend-descriptor-cache'import { BackendDialClaims } from './backend-dial-claim'import { buildDesktopBackendEnv, hermesManagedNodePathEntries, normalizeHermesHomeRoot } from './backend-env'import { isReauthRequiredError, waitForHermesReady } from './backend-health'import { backendCommandMatches, createBackendOwnership, createBackendShutdownCoordinator } from './backend-ownership'- import {- canImportHermesCli,- execProbeSync,- PROBE_TIMEOUT_MS,- shouldTrustHermesOverride,- verifyHermesCli- } from './backend-probes'+ import { canImportHermesCli, PROBE_TIMEOUT_MS, shouldTrustHermesOverride, verifyHermesCli } from './backend-probes'-import { waitForDashboardPortAnnouncement } from './backend-ready'import { recycleOwnedBackend } from './backend-recycle'import { isPidAliveWindows, waitForBackendRelease } from './backend-release-gate'+ import { createBackendServeSupportResolver } from './backend-serve-support'import {isHostKeyChangedBootFailure,isRetryableRemoteBootFailure,@@@ -352,9 -358,12 +357,13 @@@ import} from './remote-liveness'import { resolveRemoteOauthTicket, rosterSourceEnumerationTimeoutMs } from './remote-oauth-ticket'import {+ applyRemoteRequestHeaders,+ attachRemoteRequestHeaderListener,+ collectRemoteHeaderSources,createRegistryGatewayWsUrlHandler,- createRemoteWsHeaderStore+ createRemoteWsHeaderStore,+ oauthLoginLoadUrlOptions,+ resolveRemoteRequestHeaders} from './remote-ws-headers'import { missingRendererAssets } from './renderer-bundle'import { loadRendererLoadErrorPage } from './renderer-load-error-page'@@@ -9010,16 -9295,12 +9053,31 @@@ function installRemoteHeaderRulesOnSessreturn}- remoteHeaderRulesInstalled = true- session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {- const nativeHeaders = localGatewayDials.headers(details)+ remoteHeaderSessions.add(sess)+- if (nativeHeaders) { callback({ requestHeaders: nativeHeaders });++ if (sess === session.defaultSession) {++ // Native one-use gateway dials (renderer WebSocket) drop Origin and ride++ // the minted ticket; every other request keeps the remote-header path.++ sess.webRequest.onBeforeSendHeaders((details, callback) => {++ const nativeHeaders = localGatewayDials.headers(details)+- return }++ if (nativeHeaders) {++ callback({ requestHeaders: nativeHeaders })+- applyRemoteRequestHeaders(details, callback, headersForRemoteRequest)- })++ return++ }++++ applyRemoteRequestHeaders(details, callback, headersForRemoteRequest)++ })++++ return++ }+++ attachRemoteRequestHeaderListener(sess, headersForRemoteRequest)+ }++ function installRemoteHeaderRules() {+ installRemoteHeaderRulesOnSession(session.defaultSession)}// Validate + normalize the per-profile remote overrides map read from disk.@@@ -11215,12 -11454,24 +11278,15 @@@ async function ensureBackend(profile, o// A shared backend still owes the caller its profile scope, so renderer-side// WebSocket, filesystem, and cache routing target the selected profile.// `sharedPrimary` marks this as the shared-primary route: pooled backends- // also carry `profile`, so only this descriptor gets the flag.+ // also carry `profile`, so only this descriptor gets the flag. The+ // unshared primary carries its own key too: a profile-less descriptor+ // reads as "default" downstream, which breaks per-source profile memory+ // (the primary IS "default" only when it actually booted as default).return route.descriptorProfile? { ...connection, profile: route.descriptorProfile, sharedPrimary: true }- : connection+ : { ...connection, profile: key }}- // A backend for this key may still be dying (idle reap, LRU eviction, a- // just-finished delete). Wait for its bounded exit before reusing or- // spawning, so two children never share one profile's HERMES_HOME.- const stopping = poolStopper.inFlight(key)-- if (stopping) {- await stopping- }-const existing = backendPool.get(key)if (existing) {@@@ -11426,8 -11737,8 +11492,9 @@@ async function ensureRegistryBackendawait stopPoolBackend(key)if (source.kind === 'ssh') {-- await sshBootstrapCoordinator.cancelAndWait(key)-- await teardownSshConnection(key)++ // Teardown runs INSIDE the bootstrap drain barrier so a reconnect++ // cannot start a new SSH bootstrap into a dying scope (#106935).++ await sshBootstrapCoordinator.cancelAndWait(key, () => teardownSshConnection(key))}}})@@@ -12026,10 -12366,48 +12094,7 @@@ async function stopRegistryConnectionBa])await Promise.all(-- [...sshScopes].map(async scope => {-- await sshBootstrapCoordinator.cancelAndWait(scope)-- await teardownSshConnection(scope)-- })- )-}--// Mark a pool profile as recently used so the idle reaper spares it. The-// renderer calls this when it opens a profile's chat WS and periodically while-// streaming, since the main process can't see the direct renderer↔backend WS.-function touchPoolBackend(profile) {- for (const key of poolTouchKeys(profile)) {- const entry = backendPool.get(key)-- if (entry) {- entry.lastActiveAt = Date.now()-- return- }- }-}--// Evict least-recently-used SPAWNED pool backends until at most `keep` remain —-// but only ever evict backends without a live renderer socket (stale beyond the-// keepalive window). When every backend is actively kept alive we let the pool-// exceed the soft cap rather than kill a running session. Process-less-// descriptor entries (remote/cloud registry sources, per-profile remote-// overrides — `entry.process === null`) are excluded from the cap entirely:-// they hold no local process, so counting them used to let a roster refresh-// across N registered remote connections LRU-evict a REAL local backend that-// was merely idle past the keepalive window. Descriptors are still reclaimed-// by the idle reaper.-async function evictLruPoolBackends(keep) {- return evictPoolEntries(- backendPool.entries(),- Math.max(0, keep),- Date.now(),- POOL_KEEPALIVE_FRESH_MS,- async profile => {- rememberLog(`Evicting idle profile backend "${profile}" (LRU cap ${poolMaxBackends()})`)- await stopPoolBackend(profile)- }++ [...sshScopes].map(scope => sshBootstrapCoordinator.cancelAndWait(scope, () => teardownSshConnection(scope))))}@@@ -12085,32 -12550,293 +12150,35 @@@ async function dialPoolBackend(profileassertLocalProfileCanStart(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- // 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)-- // 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- })-- // Mark handled so an early rejection (child dies during the claim) can't- // surface as an unhandled rejection before the Promise.race below attaches.- 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)-- let ready = false- let rejectStart = null-- const startFailed = new Promise((_resolve, reject) => {- rejectStart = reject- })-- 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(`Hermes backend for profile "${profile}" exited (${signal || code})`)- releaseLocalBackendSlot(entry)- releaseBackendChild(child)-- if (backendPool.get(poolKey) === entry) {- backendPool.delete(poolKey)- }-- if (!ready) {- rejectStart?.(- new Error(- `Hermes backend for profile "${profile}" exited before it became ready (${signal || code}).${outputTail.describe()}`- )- )- }- })-- // Discover the ephemeral port the child bound to- 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 connection = await ensureLocalGateway(async () => {- const backend = await ensureRuntime(resolveHermesBackend(['--profile', profile, 'gateway', 'ensure', '--json']))++ const backend = await ensureRuntime(++ await resolveHermesBackend(['--profile', profile, 'gateway', 'ensure', '--json']),++ () => assertPoolEntryStillOwned(poolKey, entry)++ )+ profileDeletionGate.assertCanStart(profile)+ assertPoolEntryStillOwned(poolKey, entry)- 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}`- )- }+ assertPoolEntryStillOwned(poolKey, entry)- return {- baseUrl,- mode: 'local',- source: 'local',- authMode: 'token',- token: authToken,- profile,- wsUrl,- logs: hermesLog.slice(-80),- ...getWindowState()- }+ return { ...connection, profile, 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)}`)- }- }-})-+// 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) {- const entry = backendPool.get(profile)- await poolStopper.stop(profile)- releaseLocalBackendSlot(entry)+ backendPool.delete(profile)}async function teardownPoolBackendAndWait(profile) {@@@ -12367,18 -13110,235 +12435,19 @@@ async function startHermes(requestedPro// Local WSL backend — paths are bridgeable.setWslBridgeProfileState(primaryProfile, true)- const backend = setup.backend- // Route old runtimes (no `serve`) through the legacy `dashboard --no-open`.- backend.args = await getBackendArgsForRuntime(backend)- backendConnectionState.assertCurrentAttempt(connectionAttempt)- const hermesCwd = resolveHermesCwd()- const webDist = resolveWebDist()- const readyFile = backend.readyFile ? makeDashboardReadyFile() : null-- await advanceBootProgress('backend.spawn', `Starting Hermes backend via ${backend.label}`, 84)- rememberLog(`Starting Hermes backend via ${backend.label}`)-- const profile = primaryProfileKey()- const parentStartMarker = await desktopParentStartMarker()- const backendNonce = crypto.randomBytes(16).toString('hex')- const parentIdentityEnv = parentWatchdogEnv(process.pid, parentStartMarker, backendNonce)-- backendConnectionState.assertCurrentAttempt(connectionAttempt)-- const hermesProcess = spawnOwnedBackend(- backend.command,- backend.args,- hiddenWindowsChildOptions({- cwd: hermesCwd,- env: desktopBackendSpawnEnv(- {- ...process.env,- // Explicitly pin HERMES_HOME for the child so Python's get_hermes_home()- // resolves to the SAME location our resolveHermesHome() picked. Without- // this pin, Python falls back to ~/.hermes on every platform — fine on- // mac/linux (where our default matches), but on Windows our default is- // %LOCALAPPDATA%\hermes, which differs from C:\Users\<u>\.hermes.- // Mismatch would split config / sessions / .env / logs across two- // directories. install.ps1 sets HERMES_HOME via setx; the desktop- // can't reliably do that, so we set it inline for every spawn.- HERMES_HOME,- ...backend.env,- 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']- })- )-- // 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 shown by the boot UI. rememberLog attaches- // later, after the claim, and would miss anything printed before it.- const primaryOutputTail = createBackendOutputTail()- primaryOutputTail.attach(hermesProcess)-- // Start watching for the READY announcement BEFORE any await (#60323):- // claimBackendChild can take seconds (its Windows Get-Process probe cold- // start alone runs 2-8s) and advanceBootProgress awaits renderer IPC.- // stdout is already flowing into the tail, and Node streams never replay- // consumed chunks to late listeners, so a sentinel printed during that- // window was lost forever — the wait then hit its 90s timeout and a- // healthy backend was killed (deterministic on Windows, racy on- // macOS/Linux). The tail-buffer accessor covers any residual gap.- const portAnnouncement = waitForDashboardPortAnnouncement(hermesProcess, {- bufferedOutput: () => primaryOutputTail.text(),- describeOutputTail: () => primaryOutputTail.describe(),- readyFile- })-- // Mark handled so an early rejection (child dies during the claim) can't- // surface as an unhandled rejection before the Promise.race below attaches.- portAnnouncement.catch(() => {})- await claimBackendChild(- hermesProcess,- `${backend.command} ${backend.args.join(' ')}`,- profile,- backendNonce,- primaryOutputTail- )- const processOwner = backendConnectionState.attachProcess(connectionAttempt, hermesProcess)-- if (!processOwner) {- stopBackendChild(hermesProcess)- await waitForBackendExit(hermesProcess)- releaseBackendChild(hermesProcess)- throw new Error('Hermes backend start was superseded by a newer connection attempt.')- }-- hermesProcess.stdout.on('data', rememberLog)- hermesProcess.stderr.on('data', rememberLog)- let backendReady = false- let rejectBackendStart = null-- const backendStartFailed = new Promise((_resolve, reject) => {- rejectBackendStart = reject- })-- hermesProcess.once('error', error => {- releaseBackendChild(hermesProcess)-- if (!backendConnectionState.clearForCurrentProcess(processOwner)) {- rememberLog(`Ignoring stale Hermes backend error: ${error.message}`)- rejectBackendStart?.(new Error('Hermes backend start was superseded by a newer connection attempt.'))-- return- }-- rememberLog(`Hermes backend failed to start: ${error.message}`)- updateBootProgress(- {- error: error.message,- message: `Hermes backend failed to start: ${error.message}`,- phase: 'backend.error',- running: false- },- { allowDecrease: true }- )- sendBackendExit({ code: null, signal: null, error: error.message })- rejectBackendStart?.(error)- })- hermesProcess.once('exit', (code, signal) => {- releaseBackendChild(hermesProcess)-- if (!backendConnectionState.clearForCurrentProcess(processOwner)) {- rememberLog(`Ignoring stale Hermes backend exit (${signal || code})`)+ const connection = await ensureLocalGateway(() => runGatewayEnsure({ ...setup.backend, env: desktopBackendSpawnEnv(setup.backend.env || {}, GUEST_ONBOARDING) }, resolveHermesCwd(), HERMES_HOME))+ void showPluginCompatNoticeOnce()- if (!backendConnectionState.isCurrentAttempt(connectionAttempt)) {- throw new Error('Hermes backend start was superseded by a newer connection attempt.')- }- if (!backendReady) {- rejectBackendStart?.(new Error('Hermes backend start was superseded by a newer connection attempt.'))- }-- return- }-- rememberLog(`Hermes backend exited (${signal || code})`)- sendBackendExit({ code, signal })-- if (!backendReady) {- const message = `Hermes backend exited before it became ready (${signal || code}).${primaryOutputTail.describe()}`- updateBootProgress(- {- error: message,- message,- phase: 'backend.error',- running: false- },- { allowDecrease: true }- )- rejectBackendStart?.(- new Error(- `Hermes backend exited before it became ready (${signal || code}). Log: ${DESKTOP_LOG_PATH}\n${recentHermesLog()}`- )- )- }- })-- await advanceBootProgress('backend.port', 'Waiting for Hermes backend to launch', 86)- backendConnectionState.assertCurrentAttempt(connectionAttempt)-- // Discover the ephemeral port the child bound to- const port = await Promise.race([portAnnouncement, backendStartFailed])+ backendConnectionState.assertCurrentAttempt(connectionAttempt)- if (readyFile) {- fs.unlink(readyFile, () => {})- }-- const baseUrl = `http://127.0.0.1:${port}`- await advanceBootProgress('backend.wait', 'Waiting for Hermes backend to become ready', 90)- backendConnectionState.assertCurrentAttempt(connectionAttempt)- await Promise.race([waitForHermes(baseUrl, token), backendStartFailed])- backendConnectionState.assertCurrentAttempt(connectionAttempt)- backendReady = truebackendStartFailure = null-- const authToken = await adoptServedDashboardToken(baseUrl, token, {- childAlive: () => hermesProcess.exitCode === null && !hermesProcess.killed,- rememberLog- })-- backendConnectionState.assertCurrentAttempt(connectionAttempt)-- // Verify the WebSocket session token before declaring backend ready.- const wsUrl = `ws://127.0.0.1:${port}/api/ws?token=${encodeURIComponent(authToken)}`- const wsProbe = await probeGatewayWebSocket(wsUrl, { WebSocketImpl: globalThis.WebSocket })- backendConnectionState.assertCurrentAttempt(connectionAttempt)-- if (!wsProbe.ok) {- throw new Error(- `Local Hermes backend is HTTP-reachable but the WebSocket (/api/ws) rejected the session token: ${wsProbe.reason}`- )- }-- updateBootProgress({- phase: 'backend.ready',- message: 'Hermes backend is ready. Finalizing desktop startup',- progress: 94,- running: true,- error: null- })-- // A successful boot (including a soft restart that the repair-guard- // chose over a hard reinstall, see #74874) means any in-flight repair- // attempt counter has been honoured — reset it so the next genuine- // failure starts fresh from attempt 1 instead of inheriting the- // accumulated count of the resolved episode.+ updateBootProgress({ phase: 'backend.ready', message: 'Hermes gateway is ready', progress: 94, running: true, error: null })bootstrapRepairAttempt = 0- return { ...connection, logs: hermesLog.slice(-80), ...getWindowState() }- // The backend's plugin discovery just ran and refreshed HERMES_HOME/.plugin-compat-report.json.- // Surface it once (per distinct set of affected plugins) after the window is up; never block boot.- setTimeout(() => void showPluginCompatNoticeOnce(), 1500)-- return {- baseUrl,- mode: 'local',- source: 'local',- authMode: 'token',- token: authToken,- profile,- wsUrl,- logs: hermesLog.slice(-80),- ...getWindowState()- }++ // The primary descriptor names its own profile: a profile-less descriptor++ // reads as "default" downstream and breaks per-source profile memory when++ // the primary actually booted as another profile (#825324fd).++ return { ...connection, profile: primaryProfileKey(), logs: hermesLog.slice(-80), ...getWindowState() }})().catch(async error => {if (!backendConnectionState.clearPromiseForAttempt(connectionAttempt)) {throw error@@@ -14000,14 -14983,42 +14092,29 @@@ function createWindow()})}- ipcMain.handle('hermes:connection', async (_event, profile) => {-ipcMain.handle('hermes:connection', async (event, profile, extra) => {++ipcMain.handle('hermes:connection', async (event, profile) => {+ const route = resolveDesktopConnectionRequest(+ profile,+ windowConnectionRoutes.get(event.sender.id),+ primaryProfileKey()+ )+- return connectDesktopProfileRoute(route, spawnPriorityFrom(extra?.priority))++ return connectDesktopProfileRoute(route)+ })+-async function connectDesktopProfileRoute(- route: DesktopProfileRoute,- spawnPriority: LocalBackendSpawnPriority = 'foreground'-) {++async function connectDesktopProfileRoute(route: DesktopProfileRoute) {// Coalesce concurrent renderer dials for one profile scope (#90812): the// renderer-side reconnect lock is per-window, so two windows waking at once// both land here. The claim key mirrors ensureBackend()'s own profile// normalization so every spelling of the primary coalesces onto one dial.- const profileKey = profile && String(profile).trim() ? String(profile).trim() : primaryProfileKey()- const scopeKey = backendScopeKey(null, profileKey)- const connection = await backendDialClaims.run(scopeKey, () => ensureBackend(profile))+ 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 }+ }const connectionId = resolvedConnectionId(readDesktopConnectionsRegistry(), connection)@@@ -14019,17 -15031,12 +14127,11 @@@// forces a genuinely-local child when the v1 global mode is remote (the// registry 'local' entry always means this machine).ipcMain.handle('hermes:connection:for', async (_event, payload) => {- const { connectionId, profile, priority } = payload && typeof payload === 'object' ? (payload as any) : ({} as any)+ const { connectionId, profile } = payload && typeof payload === 'object' ? (payload as any) : ({} as any)const registry = readDesktopConnectionsRegistry()const id = String(connectionId || '').trim() || registry.primary- const spawnPriority = spawnPriorityFrom(priority)- // Same single-owner claim as 'hermes:connection', keyed by the composite- // (connectionId, profile) scope (#90812): concurrent registry dials for one- // scope share the first spawn instead of bootstrapping duplicate remotes.- const scopeKey = backendScopeKey(id, profile)- const connection = await backendDialClaims.run(scopeKey, () => ensureRegistryBackend(id, profile))-- return { ...connection, connectionId: id, registryScoped: true }- return connectDesktopProfileRoute({ connectionId: id, profile: String(profile ?? '').trim() || 'default' }, spawnPriority)++ return connectDesktopProfileRoute({ connectionId: id, profile: String(profile ?? '').trim() || 'default' })})const windowConnectionRoutes = new WindowConnectionRouteRegistry()@@@ -14098,8 -15107,8 +14202,7 @@@ ipcMain.handle('hermes:connection:revalif (conn?.remoteKind === 'ssh') {const profile = primaryProfileKey()-- await sshBootstrapCoordinator.cancelAndWait(sshScopeKey(profile))-- await teardownSshConnection(profile)++ await sshBootstrapCoordinator.cancelAndWait(sshScopeKey(profile), () => teardownSshConnection(profile))}}@@@ -14156,8 -15165,8 +14259,7 @@@ function revalidateSuspectPoolAfterResu// The pool key doubles as the SSH scope for registry SSH backends and// resolves through sshScopeKey() for bare-profile remotes; both// teardown calls no-op when the scope holds no SSH state.-- await sshBootstrapCoordinator.cancelAndWait(poolKey)-- await teardownSshConnection(poolKey)++ await sshBootstrapCoordinator.cancelAndWait(poolKey, () => teardownSshConnection(poolKey))},tracker: remoteLiveness})@@@ -15773,8 -16783,8 +15877,8 @@@ function registryConnectionKind(connectasync function teardownConnectionScopedProfileBackend(connectionId, profile) {const key = backendScopeKey(connectionId, profile)await Promise.all([- poolStopper.stop(key),- sshBootstrapCoordinator.cancelAndWait(key).then(() => teardownSshConnection(key))+ stopPoolBackend(key),- sshBootstrapCoordinator.cancelAndWait(key).then(() => teardownSshConnection(key))++ sshBootstrapCoordinator.cancelAndWait(key, () => teardownSshConnection(key))])}diff --cc apps/desktop/src/AGENTS.mdindex 30bc61df67f,536e3b24f44..3ddf0036caf--- a/apps/desktop/src/AGENTS.md+++ b/apps/desktop/src/AGENTS.md@@@ -3,24 -3,35 +3,33 @@@Applies on top of `apps/desktop/AGENTS.md` (the judgment guide) and the root `AGENTS.md`.Root TypeScript style rules apply.-## The desktop is its own chat surface on a `hermes serve` backend--Electron + React + nanostores (`@assistant-ui/react`) talking to a `tui_gateway` backend over-JSON-RPC (`requestGateway(method, params)`); transport lives in the framework-agnostic `apps/shared`-(`@hermes/shared`: `JsonRpcGatewayClient` + WS URL helpers), which the web dashboard also consumes.-The desktop has **no build/runtime dependency on the dashboard frontend**: it spawns a headless-`hermes serve` (`headless_backend=True` → `cmd_dashboard` skips `_build_web_ui` and exports-`HERMES_SERVE_HEADLESS=1` so `mount_spa()` disables the SPA even if a stray `web_dist/` exists).-`dashboard` and `serve` share `cmd_dashboard`/`start_server` but neither launches the other. It does-NOT embed `hermes --tui` — own composer, transcript, slash pipeline.--**One backward-compat fallback:** `serve` is newer, so the spawn (`electron/backend-command.ts` +-`createBackendServeSupportResolver()` in `electron/backend-serve-support.ts`) checks whether the runtime registers `serve`-and ONLY when it does not (older managed install / PATH `hermes` not yet updated) rewrites argv to-legacy `dashboard --no-open`. Without it a new app against an un-upgraded runtime crashes on an-unknown subcommand and bricks every mid-upgrade user. Keep it narrow and tested.--Lifecycle: `serve` dies with the app by design; the messaging gateway survives it (spawned detached-via `/api/gateway/*`). Never re-parent the gateway under the backend — `gateway/AGENTS.md`.--The backend the app spawns is a **pooled `hermes serve --port 0` per (connection, profile)**: its-launch home is that profile, `HERMES_DESKTOP=1` is set, and its in-process cron ticker stands down-for homes a running gateway already serves. One process may still host sessions from several homes-(`tui_gateway/AGENTS.md` § Profile scope); the first non-launch home flips `set_multiplex_active`.-Remote connections (SSH, URL+token, Cloud) reach a backend with no desktop env var that may serve-several profiles from one process. Every lifecycle/status/settings REST call against a pooled-backend carries `?profile=` (or the `profile` param) and every new-session tile records an owner-route; a backend-side scope fix is probed twice — with the profile as the launch home of a pooled-backend (env-bound) and as a secondary served by one process (override-bound).+## Desktop local execution belongs to the canonical gateway++Electron + React + nanostores (`@assistant-ui/react`) talks JSON-RPC over the existing+`@hermes/shared` client. Normal local primary and pooled launches invoke+`hermes gateway ensure --json`, consume its credential-free endpoint, and authenticate+WebSockets with fresh private control tickets. The app never acquires the gateway PID as+an owned child. Closing, switching or evicting a Desktop connection disconnects the viewer;+only explicit gateway lifecycle commands stop the owner.++Native tickets cross the private preload IPC transiently, are removed from the URL before+WebSocket construction, and are offered as subprotocols. Electron removes Origin only for+an unexpired one-use dial bound to the requesting window. No public dashboard token is+scraped or added to the public connection descriptor. SSH/URL intent retains its existing+remote resolution and exposure lifecycle; a remote failure must never start a local owner.+++The gateway `gateway ensure` attaches to is **one multiplexing owner per home**: `HERMES_DESKTOP=1`++is not how the app finds it, and no per-profile `hermes serve --port 0` child is spawned. One++gateway process serves sessions from several homes (`tui_gateway/AGENTS.md` § Profile scope); a++served secondary answers through the multiplexer's control socket (`GatewayEndpoint.multiplex_home`).++Remote connections (SSH, URL+token, Cloud) likewise reach a backend that may serve several profiles++from one process. Every lifecycle/status/settings REST call carries `?profile=` (or the `profile`++param) and every new-session tile records an owner route; a backend-side scope fix is probed twice —++with the profile as the gateway's own launch home and as a secondary served by one process.+++This migration requires the runtime's canonical GUI creation policy and a private HTTP+API credential path. Do not bypass missing runtime capabilities by relabeling GUI sessions+as CLI, dropping launch options, or falling back to an independent local serve owner.## Slash commands: curated client-side, dispatched to the backenddiff --cc apps/desktop/src/app/chat/composer/controls.tsxindex 52ed82ea03e,e83f26d37bf..436cf780473--- a/apps/desktop/src/app/chat/composer/controls.tsx+++ b/apps/desktop/src/app/chat/composer/controls.tsx@@@ -127,23 -125,8 +132,23 @@@ export function ComposerControls({voiceControls}</>)}+ {busy && busyAction !== 'steer' && onSteer ? (+ <Tip label={c.steer}>+ <Button+ aria-label={c.steer}+ className={GHOST_ICON_BTN}+ disabled={disabled}+ onClick={onSteer}+ size="icon"+ type="button"+ variant="ghost"+ >+ <Codicon name="debug-step-over" size="0.875rem" />+ </Button>+ </Tip>+ ) : null}{showQueueButton ? (- <Tip label={<TipKeybindLabel actionId="composer.queue" text={c.queueMessage} />}>+ <Tip label={<TipKeybindLabel actionId="composer.queue" text={c.queueMessage} />} placement="control"><Buttonaria-label={c.queueMessage}className={GHOST_ICON_BTN}@@@ -165,12 -148,13 +170,13 @@@showStop ? (<TipKeybindLabel actionId="composer.send" text={c.stop} />) : (- <TipKeybindLabel actionId="composer.send" text={c.send} />+ <TipKeybindLabel actionId="composer.send" text={sendLabel} />)}+ placement="control"><Button- aria-label={showStop ? c.stop : c.send}+ aria-label={showStop ? c.stop : sendLabel}className={PRIMARY_ICON_BTN}disabled={disabled || !canSubmit}type="submit"diff --cc apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsxindex 4e797856b27,74be58ba866..972352b1210--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx@@@ -5,8 -5,7 +5,7 @@@ import { afterEach, describe, expect, iimport { PaneVisibleContext } from '@/components/pane-shell/pane-visibility'import { $clarifyRequests } from '@/store/clarify'import type { ComposerAttachment } from '@/store/composer'-import { clearQueuedPrompts, getQueuedPrompts } from '@/store/composer-queue'+import { $queuedPromptsBySession, clearQueuedPrompts, getQueuedPrompts } from '@/store/composer-queue'- import { $gateway } from '@/store/gateway'import {clearAllPrompts,hasBlockingPromptRequest,@@@ -14,7 -13,7 +13,8 @@@setSecretRequest,setSudoRequest} from '@/store/prompts'+ import { hasOpenServerRequest, rememberServerRequest, resetServerRequestsForTests } from '@/store/server-requests'+import { $connection } from '@/store/session'import { type ComposerTarget, requestComposerSubmit } from '../focus'import { ComposerScopeProvider, ComposerSurfaceProvider, MAIN_COMPOSER_SCOPE } from '../scope'@@@ -566,8 -508,8 +566,8 @@@ describe('useComposerSubmit with a clarhook.result.current.submitDraft()})- await waitFor(() => expect(onSteer).toHaveBeenCalledWith('change course'))+ await waitFor(() => expect(onSteer).toHaveBeenCalledWith('change course', 'interrupt'))- expect(gatewayRequest).toHaveBeenCalledWith('clarify.respond', { request_id: 'req-runtime-session', answer: '' })+ expect(respond).toHaveBeenCalledWith({ answer: '' })})it('leaves the question alone for an empty Enter (Stop, not an answer)', () => {diff --cc apps/desktop/src/app/chat/composer/hooks/use-composer-submit.tsindex 7b670bad73f,7339409ec24..8b45d9193aa--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts@@@ -7,8 -6,8 +7,8 @@@ import type { BusyInputMode } from '@/simport { hasClarifyRequest, skipClarifyRequest } from '@/store/clarify'import { clearSessionDraft, type ComposerAttachment } from '@/store/composer'import { resetBrowseState } from '@/store/composer-input-history'-import { enqueueQueuedPrompt, type QueuedPromptEntry } from '@/store/composer-queue'+import { enqueueQueuedPrompt, type QueuedPromptEntry, serverOwnsComposerQueue } from '@/store/composer-queue'- import { hasMcpSetupRequest, skipMcpSetupRequest } from '@/store/mcp-setup'+ import { hasConnectionRequest, skipConnectionRequest } from '@/store/connection-request'import { hasBlockingPromptRequest } from '@/store/prompts'import { cloneAttachments, type QueueEditState } from '../composer-utils'diff --cc apps/desktop/src/app/chat/composer/queue-panel.tsxindex aa553d31279,cc1136254bd..3ce5b7e61e0--- a/apps/desktop/src/app/chat/composer/queue-panel.tsx+++ b/apps/desktop/src/app/chat/composer/queue-panel.tsx@@@ -84,26 -77,13 +84,27 @@@ export function QueuePanel(return (<StatusRowclassName={cn(- 'border border-transparent',- isEditing && 'border-[color-mix(in_srgb,var(--dt-composer-ring)_40%,transparent)] bg-accent/25'+ isEditing && 'ring-1 ring-inset ring-[color-mix(in_srgb,var(--dt-composer-ring)_40%,transparent)] bg-accent/25')}+ dismiss={{ label: c.queueDelete, onDismiss: () => onDelete(entry.id) }}key={entry.id}+ leading={<Codicon className="text-muted-foreground/70" name="comment" size="0.8rem" />}trailing={- <>+ lost && onDiscardLost ? (+ <Tip label={c.queueLostDiscardTip}>+ <Button+ aria-label={c.queueLostDiscard}+ className="h-5 rounded-md px-1.5 text-[0.66rem]"+ data-slot="queue-lost-discard"+ onClick={() => onDiscardLost(entry.id)}+ size="micro"+ type="button"+ variant="text"+ >+ {c.queueLostDiscard}+ </Button>+ </Tip>+ ) : !entry.serverStatus && <><Tip label={c.queueEdit}><Buttonaria-label={c.queueEdit}diff --cc apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.tsindex c7d015fbae8,d58578e6dff..e3778836f6b--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts@@@ -350,16 -338,13 +350,16 @@@ export function useSessionTileDelegate(() => {assertSessionOwnerResolved(owner, { method: 'session.resume', sessionId: storedSessionId })- return singleFlightSessionResume(storedSessionId, () =>- requestForSessionProfile<SessionResumeResult>(owner, requestGateway, 'session.resume', {- session_id: storedSessionId,- cols: 96,- omit_messages: true,- ...(owner ? { profile: typeof owner === 'string' ? owner : owner.profile } : {})- })+ return singleFlightSessionResume(+ storedSessionId,+ () =>- requestForSessionProfile<SessionResumeResponse>(owner, requestGateway, 'session.resume', {++ requestForSessionProfile<SessionResumeResult>(owner, requestGateway, 'session.resume', {+ session_id: storedSessionId,+ cols: 96,+ omit_messages: !authoritativeSnapshot,+ ...(owner ? { profile: typeof owner === 'string' ? owner : owner.profile } : {})+ }),+ { requiresMessages: authoritativeSnapshot, scope: owner })},async () => {diff --cc apps/desktop/src/app/contrib/wiring.tsxindex 145f58f5acb,dd315eddf65..7f44eefd8e2--- a/apps/desktop/src/app/contrib/wiring.tsx+++ b/apps/desktop/src/app/contrib/wiring.tsx@@@ -49,8 -50,10 +50,9 @@@ import { requestVoiceConversationStartimport { $activeConnectionId } from '@/store/connections'import { $cronReviewRequest, setCronFocusJobId } from '@/store/cron'import { requestGatewayForProfile } from '@/store/gateway'+ import { reconnectGateway } from '@/store/gateway-reconnect'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,@@@ -194,6 -200,9 +198,8 @@@ export function ContribWiring({ childre// context (the sticky toast). The shell owns `navigate`, so it consumes the// intent counter here; the ref skips the initial mount value.const billingSettingsSeenRef = useRef(0)- const poolLimitsSettingsSeenRef = useRef(0)+ const routeRequestSeenRef = useRef(0)+ const backendRestartSeenRef = useRef(0)const cronReviewSeenRef = useRef(0)const activeTranscriptSignatureRef = useRef(new Map<string, string>())const activeTranscriptRequestSequenceRef = useRef(0)@@@ -204,6 -213,9 +210,8 @@@const gatewayState = useStore($gatewayState)const activeSessionId = useStore($activeSessionId)const billingSettingsRequest = useStore($billingSettingsRequest)- const poolLimitsSettingsRequest = useStore($poolLimitsSettingsRequest)+ const routeRequest = useStore($routeRequest)+ const backendRestartRequest = useStore($backendRestartRequest)const cronReviewRequest = useStore($cronReviewRequest)const currentCwd = useStore($currentCwd)diff --cc apps/desktop/src/app/gateway/hooks/use-gateway-boot.tsindex 38c0e5665cc,b510158fe52..2f707a6f02f--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts@@@ -40,10 -42,12 +42,11 @@@ importpruneSecondaryGateways,reconnectSecondaryGateways,reportPrimaryGatewayState,+ type ScopedServerRequest,setPrimaryGateway,- setPrimaryGatewayConnection,- touchSecondaryGateways+ setPrimaryGatewayConnection} from '@/store/gateway'- import { registerGatewayReconnect } from '@/store/gateway-reconnect'+ import { reconnectGateway, registerGatewayReconnect } from '@/store/gateway-reconnect'import {$gatewaySwitching,beginGatewaySwitch,@@@ -51,13 -55,16 +54,14 @@@isCurrentGatewaySwitch,registerGatewaySwitchLifecycle} from '@/store/gateway-switch'- import { checkLocalRuntimeUpdate, watchLocalRuntimeJobs } from '@/store/local-runtime-jobs'- import { notify, notifyError } from '@/store/notifications'+ import { watchLocalRuntimeJobs } from '@/store/local-runtime-jobs'+ import { notify, notifyError, RECOVERY_ACTIONS } from '@/store/notifications'-import { loadPoolLimits } from '@/store/pool-limits'import {$activeGatewayProfile,normalizeProfileKey,- refreshActiveProfile,- touchActiveGatewayBackend+ refreshActiveProfile} from '@/store/profile'+ import { requestBackendRestart } from '@/store/recovery-requests'import {$activeSessionId,$connection,diff --cc apps/desktop/src/app/session/hooks/use-hermes-config.tsindex 656af5d52ff,a4ce3785b0e..40ab529bc33--- a/apps/desktop/src/app/session/hooks/use-hermes-config.ts+++ b/apps/desktop/src/app/session/hooks/use-hermes-config.ts@@@ -143,16 -139,9 +144,17 @@@ 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)setTerminalFontFamilyFromConfig(config.terminal?.font_family)+ setChatFontFamilyFromConfig(config.desktop?.font_family)if (!canPublish()) {returndiff --cc apps/desktop/src/app/session/hooks/use-session-actions/index.tsindex dcc5d3832a0,d4f7378edbb..12207e2238a--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts@@@ -385,7 -405,8 +405,9 @@@ export function useSessionActions(const { t } = useI18n()const copy = t.desktopconst resumeRequestRef = useRef(0)+ const createIntentRef = useRef<string | null>(null)+ const transcriptHydrationByRuntimeRef = useRef(new Map<string, symbol>())+ const coldDisplayReadsRef = useRef(new Map<string, symbol>())const branchCreateFlightsRef = useRef(new Map<string, Promise<SessionCreateResponse>>())// Follow auto-compression's stored-id rotation only while the exact runtime,@@@ -576,11 -595,12 +598,13 @@@// reduce the owner to a bare profile name that later RPCs dial on a// different socket than the one that minted the runtime.const capturedRoute = resolveNewChatOwnerRoute()+ const capturedProfile = $newChatProfile.get() || normalizeProfileKey($activeGatewayProfile.get())+ const legacyProfileIntent = isLegacyNewChatProfile(capturedProfile)const params = {- ...(await desktopSessionCreateParams(cwd, capturedRoute)),+ ...(await desktopSessionCreateParams(cwd, capturedRoute, capturedProfile, legacyProfileIntent)),- ...sessionCreateOverrideParams(createOverrides, seedMessages)+ ...sessionCreateOverrideParams(createOverrides, seedMessages),+ request_id: createIntent}// Lease the owner socket for the whole create → owner-publication@@@ -803,8 -842,12 +848,13 @@@options?.cwd === null ? '' : typeof options?.cwd === 'string' ? options.cwd.trim() : resolveNewSessionCwd()const params = {- ...(await desktopSessionCreateParams(cwd, capturedRoute)),+ ...(await desktopSessionCreateParams(+ cwd,+ capturedRoute,+ requestedProfile,+ options?.route === null || defaultTarget?.route === null+ )),+ request_id: crypto.randomUUID(),...(workspaceScope.workspaceMode === 'bots' ? { hidden: true } : {})}@@@ -1610,29 -1690,22 +1703,29 @@@let resumeRuntimeBaselineMessages: ChatMessage[] = []const resumeStartedAt = Date.now() / 1000- const resumePromise = singleFlightSessionResume(storedSessionId, () =>- requestForSession<SessionResumeResult>('session.resume', {- session_id: storedSessionId,- cols: 96,- source: 'desktop',- defer_history: !watchWindow,- // REST is the transcript authority for Desktop. Avoid duplicating a- // potentially huge compression lineage in the WebSocket response.- // Watch windows attach lazily (live mirror). Every other cold resume- // gets the gateway's default deferred build: the RPC returns the- // transcript immediately instead of blocking the switch on _make_agent- // (MCP discovery / prompt build), and the agent pre-warms in the- // background while the prefetch above paints the transcript.- ...(watchWindow ? { lazy: true } : { omit_messages: true }),- ...(sessionProfile ? { profile: sessionProfile } : {})- })+ const resumePromise = singleFlightSessionResume(+ storedSessionId,+ () =>- requestForSession<SessionResumeResponse>('session.resume', {++ requestForSession<SessionResumeResult>('session.resume', {+ session_id: storedSessionId,+ cols: 96,+ source: 'desktop',+ defer_history: options?.authoritativeSnapshot ? false : !watchWindow,+ // REST is the transcript authority for Desktop. Avoid duplicating a+ // potentially huge compression lineage in the WebSocket response.+ // Watch windows attach lazily (live mirror). Every other cold resume+ // gets the gateway's default deferred build: the RPC returns the+ // transcript immediately instead of blocking the switch on _make_agent+ // (MCP discovery / prompt build), and the agent pre-warms in the+ // background while the prefetch above paints the transcript.+ ...(options?.authoritativeSnapshot+ ? { omit_messages: false }+ : watchWindow+ ? { lazy: true }+ : { omit_messages: true }),+ ...(sessionProfile ? { profile: sessionProfile } : {})+ }),+ { requiresMessages: options?.authoritativeSnapshot, scope: sessionOwner }).then(resumed => {resumeRuntimeBaselineMessages =sessionStateByRuntimeIdRef.current.get(resumed.session_id)?.messages ?? resumeRuntimeBaselineMessagesdiff --cc apps/desktop/src/components/notifications.test.tsxindex 2c4e15d5ce7,8619f7f5174..277f2033b02--- a/apps/desktop/src/components/notifications.test.tsx+++ b/apps/desktop/src/components/notifications.test.tsx@@@ -1,8 -1,10 +1,9 @@@- import { cleanup, render, screen } from '@testing-library/react'- import { afterEach, beforeEach, describe, expect, it } from 'vitest'+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+ import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest'import { I18nProvider } from '@/i18n'-import { $notifications, clearNotifications, notify, notifyError } from '@/store/notifications'-import { $poolLimitsSettingsRequest } from '@/store/pool-limits'+import { clearNotifications, notify } from '@/store/notifications'+ import { stubResizeObserver } from '@/test/jsdom'import { NotificationStack, toastTitleClassName } from './notifications'@@@ -47,6 -71,38 +68,4 @@@ describe('toast titles', () =>expect(title.className).toMatch(/\boverflow-y-auto\b/)expect(screen.getByText(DETAIL)).toBeTruthy()})-- it('makes a local pool-slot timeout actionable without changing ordinary errors', () => {- notifyError(- new Error(- `Error invoking remote method 'hermes:connection': Error: Local backend start for "research" timed out while waiting for a free slot.`- ),- 'Failed to switch to profile "research"'- )-- render(- <I18nProvider configClient={null} initialLocale="en">- <NotificationStack />- </I18nProvider>- )-- expect(screen.getByText(/Too many bots are running at once/)).toBeTruthy()-- fireEvent.click(screen.getByRole('button', { name: 'Open Advanced Settings' }))-- expect($poolLimitsSettingsRequest.get()).toBe(1)- expect($notifications.get()).toHaveLength(0)-- notifyError(new Error('gateway unavailable'), 'Failed to switch profile')- expect($notifications.get()[0]?.action).toBeUndefined()- })--- it('keeps background pool-slot timeouts quiet if they reach the renderer', () => {- notifyError(- new Error('Local backend start for "background" timed out while waiting for a free slot. (background)'),- 'Background profile warm-up failed'- )--- expect($notifications.get()[0]?.action).toBeUndefined()- })})diff --cc apps/desktop/src/hermes.test.tsindex 34195c75acf,bb06f19468f..c5e6019a56e--- a/apps/desktop/src/hermes.test.ts+++ b/apps/desktop/src/hermes.test.ts@@@ -191,9 -191,21 +191,22 @@@ describe('Hermes REST helpers', () =>expect(api.mock.calls[0][0]).not.toHaveProperty('profile')})+ it('pins the profile list to an explicit (connection, profile) scope', async () => {+ setApiRequestConnection('remote-a')+ setApiRequestProfile('iris')++ await getProfiles({ connectionId: 'remote-b', profile: 'scout' })+ await getProfiles({ connectionId: 'local', profile: 'default' })++ expect(api.mock.calls.map(([request]) => request)).toEqual([+ expect.objectContaining({ connectionId: 'remote-b', profile: 'scout', path: '/api/profiles' }),+ expect.objectContaining({ connectionId: 'local', profile: 'default', path: '/api/profiles' })+ ])+ })+it('preserves ambient and explicit-local ownership for session and profile requests', async () => {setApiRequestConnection('remote-a')+ api.mockResolvedValue({ ...emptySessionsResponse, exists: true, runtime_revision: 9, runtime_generation: 2 })await getSession('ambient-session')await getSessionMessages('ambient-session')diff --cc apps/desktop/src/plugins/hermes-bots/group-hold-status.test.tsxindex f631b8ccd61,d10266321cb..306f3fdf84f--- a/apps/desktop/src/plugins/hermes-bots/group-hold-status.test.tsx+++ b/apps/desktop/src/plugins/hermes-bots/group-hold-status.test.tsx@@@ -148,6 -147,26 +148,28 @@@ describe('durable group holds', () =>expect(status.textContent).toContain('builder (laptop)')})+ it('summarizes the most recent unresolved failure after a member fails again', async () => {+ const [{ GroupChatWorkspace }, chat, activity] = await Promise.all([+ import('./group-chat-view'), import('./group-chat'), import('./group-activity')+ ])++ chat.$groupChats.set({ Core: { log: [], members: MEMBERS, watermarks: {} } })++ for (const member of ['research', 'builder', 'research']) {+ activity.recordGroupActivity('Core', { kind: 'failed', member, thread: member })+ }++ activity.recordGroupActivity('Core', { kind: 'settled', member: null })+ const view = render(<GroupChatWorkspace group="Core" members={MEMBERS} />)- expect(screen.getByRole('button', { name: /^Activity/ }).textContent).toContain('research hit an error')++ // The workspace paints behind the group-source classification gate, so the++ // activity row appears once that async check settles.++ expect((await screen.findByRole('button', { name: /^Activity/ })).textContent).toContain('research hit an error')++ activity.recordGroupActivity('Core', { kind: 'replied', member: 'research' })+ view.rerender(<GroupChatWorkspace group="Core" members={MEMBERS} />)- expect(screen.getByRole('button', { name: /^Activity/ }).textContent).toContain('builder hit an error')++ expect((await screen.findByRole('button', { name: /^Activity/ })).textContent).toContain('builder hit an error')+ })+it('projects hydrated holds into the real group workspace', async () => {const [{ GroupChatWorkspace }, chat] = await Promise.all([import('./group-chat-view'), import('./group-chat')])diff --cc apps/desktop/src/plugins/hermes-bots/group-rounds.tsindex f9a4b70882d,eb5c6908f8c..9fb8f62d964--- a/apps/desktop/src/plugins/hermes-bots/group-rounds.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-rounds.ts@@@ -413,13 -431,11 +431,13 @@@ export async function stopGroupThread(g}/** Drive one bounded round-robin turn for ONE THREAD. Serial — one member at- * a time. A newer user send bumps the room epoch; this loop notices at the- * next member boundary, bails, and the newest send's own loop takes over.+ * a time. User follow-ups queue behind this drive; Stop invalidates its+ * epoch and discards queued continuations.* Watermarks are per thread+member (`${thread}::${memberKey}`), so parallel* topics never eat each other's deltas. */- export async function runGroupChatRounds(group: string, members: GroupMember[], thread: string) {+ export async function runGroupChatRounds(group: string, members: GroupMember[], thread: string, failedMembers = new Set<string>()) {+ if (group.startsWith('canonical:')) {throw new Error('Canonical rooms are driven by the gateway')}+const binding = followGroupChat(group, name => {group = name})diff --cc apps/desktop/src/plugins/hermes-bots/relay.test.tsindex c782171437a,7674b29592f..397433f324e--- a/apps/desktop/src/plugins/hermes-bots/relay.test.ts+++ b/apps/desktop/src/plugins/hermes-bots/relay.test.ts@@@ -731,3 -699,190 +758,195 @@@ describe('stop halts both loops', () =stopBotRelay()})})++ describe('the roster loop forgets a machine that left', () => {+ it('clears each remaining gateway’s remote roster once when the peer set drops below two', async () => {+ const calls = respondWith(call => {+ if (call.method === 'profiles.list') {+ return { profiles: [{ name: call.connectionId === 'a' ? 'default' : 'ops' }] }+ }++ return {}+ })++ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await vi.advanceTimersByTimeAsync(0)+ expect(calls.filter(call => call.method === 'bot_relay.roster.sync')).toHaveLength(2)+ calls.length = 0++ // b leaves the registry. Without a push, a's gateway keeps ops in its+ // roster (and as a message_agent target) until a second peer shows up.+ hostMock.profileRoutes = vi.fn(async () => [route('a')])+ await vi.advanceTimersByTimeAsync(60_000)++ const syncs = calls.filter(call => call.method === 'bot_relay.roster.sync')+ expect(syncs).toEqual([expect.objectContaining({ connectionId: 'a', params: { agents: [] } })])++ // Once, not on every tick.+ calls.length = 0+ await vi.advanceTimersByTimeAsync(60_000)+ expect(calls.filter(call => call.method === 'bot_relay.roster.sync')).toEqual([])++ // A returning peer starts the union pushes again.+ hostMock.profileRoutes = vi.fn(async () => [route('a'), route('b')])+ await vi.advanceTimersByTimeAsync(60_000)+ expect(calls.filter(call => call.method === 'bot_relay.roster.sync').map(call => call.connectionId)).toEqual([+ 'a',+ 'b'+ ])++ stopBotRelay()+ })++ it('clears the roster of a sole connection that replaced the previous sole one', async () => {+ const calls = respondWith(call => {+ if (call.method === 'profiles.list') {+ return { profiles: [{ name: call.connectionId === 'a' ? 'default' : 'ops' }] }+ }++ return {}+ })++ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await vi.advanceTimersByTimeAsync(0)+ hostMock.profileRoutes = vi.fn(async () => [route('a')])+ await vi.advanceTimersByTimeAsync(60_000)+ calls.length = 0++ // a is swapped for c between ticks — still one connection, but c's+ // gateway has never been told the roster is empty.+ hostMock.profileRoutes = vi.fn(async () => [route('c')])+ await vi.advanceTimersByTimeAsync(60_000)++ expect(calls.filter(call => call.method === 'bot_relay.roster.sync').map(call => call.connectionId)).toEqual([+ 'c'+ ])++ stopBotRelay()+ })+ })++ describe('the drain loop does not let one delivery hold every other gateway’s mail', () => {+ // A long turn on b (up to RELAY_DELIVER_TIMEOUT_MS) must not stop b's own+ // outbox from being claimed, nor a's delivery from running: the gateway+ // checks envelope age against bot_mode.envelope_ttl_seconds at the claim,+ // and the sender's waiter is finite.+ type RelayEnvelopeFixture = { id: string; message: string; target_connection: string; target_profile: string }+ const toB: RelayEnvelopeFixture = { id: 'env-1', message: 'long job', target_connection: 'b', target_profile: 'ops' }+ const toA: RelayEnvelopeFixture = { id: 'env-2', message: 'quick one', target_connection: 'a', target_profile: 'default' }++ // Canonical `bot_relay.deliver` answers carry the exact delivery identity;++ // a reply without it is retained for recovery, never ACKed to the sender.++ const settled = (id: string, reply: string) => ({ status: 'settled', delivery_id: id, admission_id: `adm-${id}`, reply })++ it('claims every outbox first and delivers to different targets concurrently', async () => {+ let releaseB!: (value: { reply: string }) => void++ const pendingB = new Promise<{ reply: string }>(resolve => {+ releaseB = resolve- })++ }).then(res => settled(toB.id, res.reply))++ const calls = respondWith(call => {+ if (call.method === 'bot_relay.outbox.drain') {+ return { envelopes: call.connectionId === 'a' ? [toB] : [toA] }+ }++ if (call.method === 'bot_relay.deliver') {- return call.connectionId === 'b' ? pendingB : { reply: 'done' }++ return call.connectionId === 'b' ? pendingB : settled(toA.id, 'done')+ }++ return {}+ })++ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await pushAndSettle()++ // b's turn is still running — yet b's outbox was claimed and its envelope delivered on a.+ expect(calls.filter(call => call.method === 'bot_relay.outbox.drain').map(call => call.connectionId)).toEqual([+ 'a',+ 'b'+ ])+ expect(calls.filter(call => call.method === 'bot_relay.deliver').map(call => call.connectionId)).toEqual(['b', 'a'])+ expect(calls.find(call => call.method === 'bot_relay.reply')).toMatchObject({+ connectionId: 'b',+ params: { id: 'env-2', reply: 'done' }+ })++ releaseB({ reply: 'finally' })+ await vi.advanceTimersByTimeAsync(10)++ expect(calls.filter(call => call.method === 'bot_relay.reply').map(call => call.params.id)).toEqual([+ 'env-2',+ 'env-1'+ ])++ stopBotRelay()+ })++ it('claims an envelope that lands DURING a long turn and delivers it now; the same target still queues behind', async () => {+ // Issue step 3: the push arrives while b's turn is running. The claim+ // must not wait for that turn (the TTL clock is running on the gateway),+ // a different target is delivered immediately, and a second envelope for+ // the SAME target profile waits for the running turn, in order.+ let releaseB!: (value: { reply: string }) => void++ const pendingB = new Promise<{ reply: string }>(resolve => {+ releaseB = resolve- })++ }).then(res => settled(toB.id, res.reply))++ const outbox: Record<string, RelayEnvelopeFixture[]> = { a: [toB], b: [] }++ const calls = respondWith(call => {+ if (call.method === 'bot_relay.outbox.drain') {+ return { envelopes: outbox[call.connectionId].splice(0) }+ }++ if (call.method === 'bot_relay.deliver') {- return call.params.message === 'long job' ? pendingB : { reply: `${call.params.message} done` }++ return call.params.message === 'long job'++ ? pendingB++ : settled(String(call.params.id), `${call.params.message} done`)+ }++ return {}+ })++ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await pushAndSettle()+ expect(calls.filter(call => call.method === 'bot_relay.deliver').map(call => call.params.message)).toEqual([+ 'long job'+ ])++ // b's turn is running; gateway b now queues one envelope for a and one more for b/ops.+ outbox.b.push(toA, { ...toB, id: 'env-3', message: 'second' })+ await pushAndSettle()++ expect(calls.filter(call => call.method === 'bot_relay.outbox.drain' && call.connectionId === 'b')).toHaveLength(2)+ expect(calls.filter(call => call.method === 'bot_relay.deliver').map(call => call.params.message)).toEqual([+ 'long job',+ 'quick one'+ ])++ releaseB({ reply: 'long job done' })+ await vi.advanceTimersByTimeAsync(10)++ expect(calls.filter(call => call.method === 'bot_relay.deliver').map(call => call.params.message)).toEqual([+ 'long job',+ 'quick one',+ 'second'+ ])+ expect(calls.filter(call => call.method === 'bot_relay.reply').map(call => call.params.id)).toEqual([+ 'env-2',+ 'env-1',+ 'env-3'+ ])++ stopBotRelay()+ })+ })diff --cc apps/desktop/src/plugins/hermes-bots/relay.tsindex b0674bfcde1,6086e0beb8c..11eb5e80d3a--- a/apps/desktop/src/plugins/hermes-bots/relay.ts+++ b/apps/desktop/src/plugins/hermes-bots/relay.ts@@@ -102,10 -105,7 +105,18 @@@ 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. */@@@ -360,124 -386,136 +399,172 @@@ async function drainRelayOutboxes(){})- envelopes = Array.isArray(res?.envelopes) ? res.envelopes : []++ const pending = pendingRelaysFor(sender)+++ for (const envelope of Array.isArray(res?.envelopes) ? res.envelopes : []) {++ if (envelope.id && !pending.has(envelope.id)) {pending.set(envelope.id, structuredClone(envelope))}++ }++++ // Every claimed-but-unACKed envelope rides again: a delivery that++ // settled without an exact identity, or whose ACK was lost, retries++ // from the sender's pin instead of being silently dropped.++ for (const envelope of pending.values()) {+ queued.push({ envelope, sender })+ }} catch {- continue+ // Older backend without the relay RPCs — skip this connection.}+ }- const senderKey = JSON.stringify(sender.route)- const pending = pendingRelays.get(senderKey) || new Map<string, RelayEnvelope>()- pendingRelays.set(senderKey, pending)+ // Phase 2 — deliver, without holding the drain. Envelopes for the same+ // target profile stay in order, one turn at a time (the target gateway+ // serialises that profile's turns behind its turn lock anyway; a second+ // envelope sent while the first runs would only burn its lock-wait+ // budget). Different targets run concurrently, so one long turn never+ // holds every other bot's mail. The lanes outlive this drain: `drainBusy`+ // covers the claim only, so a push that lands while a turn runs claims+ // its envelope NOW instead of after that turn — otherwise the TTL clock+ // kept running against a message the Desktop had not even looked at.+ for (const { envelope, sender } of queued) {+ enqueueRelayDelivery(sender, envelope, byId)+ }+ } finally {+ relay.drainBusy = false- for (const envelope of envelopes) {- if (envelope.id && !pending.has(envelope.id)) {pending.set(envelope.id, structuredClone(envelope))}- }+ if (relay.drainRerun && !relay.disposed) {+ // Envelopes signaled mid-drain: schedule one follow-up pass (debounced)+ // instead of leaving them to the interval poll.+ relay.drainRerun = false+ scheduleRelayPushDrain()+ }+ }+ }- for (const envelope of pending.values()) {- if (relay.disposed) {- return- }+ interface RelayQueuedEnvelope {+ envelope: RelayEnvelope+ sender: RelayConnection+ }- const envelopeId = String(envelope?.id || '')- const target = byId.get(String(envelope?.target_connection || ''))-- const postReply = async (payload: { error?: string; reason?: string; reply?: string }) => {- try {- await host.requestProfile(sender.route, 'bot_relay.reply', {- id: envelopeId,- ...payload- })- pending.delete(envelopeId)- } catch {- // Sender gateway unreachable — its waiter times out with guidance.- }- }+ // Delivery lanes: `target_connection::target_profile` → the tail of that+ // target's in-flight deliveries. A lane entry is removed once its tail+ // settles so an idle target holds no state.+ const relayLanes = new Map<string, Promise<void>>()- if (!envelopeId) {- continue- }+ /** Queue one claimed envelope behind the deliveries already running for the+ * same target profile; other targets are untouched. */+ function enqueueRelayDelivery(sender: RelayConnection, envelope: RelayEnvelope, byId: Map<string, RelayConnection>) {+ const key = `${String(envelope?.target_connection || '')}::${String(envelope?.target_profile || '')}`- if (!target) {- await postReply({- error: `connection '${envelope?.target_connection}' is not connected to this Desktop right now`- })+ const tail = (relayLanes.get(key) ?? Promise.resolve()).then(() =>+ relay.disposed ? undefined : deliverRelayEnvelope(sender, envelope, byId)+ )- continue- }+ relayLanes.set(key, tail)+ void tail.finally(() => {+ if (relayLanes.get(key) === tail) {+ relayLanes.delete(key)+ }+ })+ }- // Needs-attention hook (#93091 item 3): a delivered background DM is- // this bot's "good turn"; a classified delivery failure badges it.- const attentionKey = `${target.id}::${String(envelope?.target_profile || '')}`+ /** Deliver one claimed envelope on the target connection's own socket and post+ * the reply (or the error) back to the sender gateway for its waiter. */+ async function deliverRelayEnvelope(+ sender: RelayConnection,+ envelope: RelayEnvelope,+ byId: Map<string, RelayConnection>+ ) {+ const envelopeId = String(envelope?.id || '')+ const target = byId.get(String(envelope?.target_connection || ''))++ const pending = pendingRelaysFor(sender)++++ // A later drain re-queues every pinned envelope; the lane serialises them, so++ // one already ACKed by an earlier delivery in this lane must not ride twice.++ if (!envelopeId || !pending.has(envelopeId)) {++ return++ }- try {- const res = await host.requestProfile<{ status?: string; delivery_id?: string; admission_id?: string; reply?: string; error?: string; reason?: string }>(- { ...target.route, profile: String(envelope.target_profile), targetProfile: String(envelope.target_profile) },- 'bot_relay.deliver',- {- id: envelopeId,- profile: String(envelope?.target_profile || ''),- message: String(envelope?.message || ''),- from_profile: String(envelope?.from_profile || ''),- from_handle: String(envelope?.from_handle || ''),- from_connection: String(sender.id)- },- RELAY_DELIVER_TIMEOUT_MS- )-- if (res.delivery_id !== envelopeId || !res.admission_id) {- noteBotAttention(attentionKey, 'Delivery identity unavailable; retained for recovery')-- continue- }+ const postReply = async (payload: { error?: string; reason?: string; reply?: string }) => {+ try {+ await host.requestProfile(sender.route, 'bot_relay.reply', {+ id: envelopeId,+ ...payload+ })++ pending.delete(envelopeId)+ } catch {+ // Sender gateway unreachable — its waiter times out with guidance.+ }+ }- if (res.status !== 'settled' && res.status !== 'failed') {- if (res.status === 'ambiguous') {noteBotAttention(attentionKey, 'unknown_execution')}- if (!envelopeId) {- return- }-+ if (!target) {+ await postReply({+ error: `connection '${envelope?.target_connection}' is not connected to this Desktop right now`+ })- continue- }+ return+ }- if (res.status === 'failed') {- noteBotAttention(attentionKey, res.reason || res.error || 'delivery failed')- await postReply({ error: res.error || res.reply || 'delivery failed', reason: res.reason })+ // Needs-attention hook (#93091 item 3): a delivered background DM is+ // this bot's "good turn"; a classified delivery failure badges it.+ const attentionKey = `${target.id}::${String(envelope?.target_profile || '')}`- continue- }+ try {- const res = await host.requestProfile<{ reply?: string }>(- target.route,++ const res = await host.requestProfile<{ status?: string; delivery_id?: string; admission_id?: string; reply?: string; error?: string; reason?: string }>(++ { ...target.route, profile: String(envelope.target_profile), targetProfile: String(envelope.target_profile) },+ 'bot_relay.deliver',+ {++ id: envelopeId,+ profile: String(envelope?.target_profile || ''),+ message: String(envelope?.message || ''),+ from_profile: String(envelope?.from_profile || ''),+ from_handle: String(envelope?.from_handle || ''),+ from_connection: String(sender.id)+ },+ RELAY_DELIVER_TIMEOUT_MS+ )- clearBotAttention(attentionKey)- await postReply({- reply: String(res?.reply || '')- })- } catch (error: any) {- // #93091: bot_relay.deliver classifies the failed turn and ships the- // typed code in the JSON-RPC error's `data.reason`; forward it into- // the sender-side reply file so the waiter (and the sending agent)- // get the machine-readable cause, and prefer it for the badge —- // classified codes beat free-text re-parsing.- const reason = String(error?.data?.reason || '').trim()- noteBotAttention(attentionKey, reason || error?.message || error)-- // A transport exception can follow a committed admission; never settle it as failure.- if (!reason || reason === 'runtime_unavailable') {continue}- await postReply({- error: String(error?.message || error || 'delivery failed'),- ...(reason- ? {- reason- }- : {})- })- }- }++ if (res.delivery_id !== envelopeId || !res.admission_id) {++ noteBotAttention(attentionKey, 'Delivery identity unavailable; retained for recovery')++++ return+ }- } finally {- relay.drainBusy = false+- if (relay.drainRerun && !relay.disposed) {- // Envelopes signaled mid-drain: schedule one follow-up pass (debounced)- // instead of leaving them to the interval poll.- relay.drainRerun = false- scheduleRelayPushDrain()++ if (res.status !== 'settled' && res.status !== 'failed') {++ if (res.status === 'ambiguous') {noteBotAttention(attentionKey, 'unknown_execution')}++++ return++ }++++ if (res.status === 'failed') {++ noteBotAttention(attentionKey, res.reason || res.error || 'delivery failed')++ await postReply({ error: res.error || res.reply || 'delivery failed', reason: res.reason })++++ return+ }+++ clearBotAttention(attentionKey)+ await postReply({+ reply: String(res?.reply || '')+ })+ } catch (error: any) {+ // #93091: bot_relay.deliver classifies the failed turn and ships the+ // typed code in the JSON-RPC error's `data.reason`; forward it into+ // the sender-side reply file so the waiter (and the sending agent)+ // get the machine-readable cause, and prefer it for the badge —+ // classified codes beat free-text re-parsing.+ const reason = String(error?.data?.reason || '').trim()+ noteBotAttention(attentionKey, reason || error?.message || error)++++ // A transport exception can follow a committed admission; never settle it as failure.++ if (!reason || reason === 'runtime_unavailable') {return}+ await postReply({+ error: String(error?.message || error || 'delivery failed'),+ ...(reason+ ? {+ reason+ }+ : {})+ })}}diff --cc apps/desktop/src/sdk/index.tsindex 5356a82bdae,6c3466c13d3..ec445a93207--- a/apps/desktop/src/sdk/index.ts+++ b/apps/desktop/src/sdk/index.ts@@@ -21,13 -21,10 +21,14 @@@import { atom, computed, type ReadableAtom } from 'nanostores'import type { ReactNode } from 'react'-import { capabilityScoped } from '@/api/client'+import { capabilityScoped, getApiRequestConnection } from '@/api/client'++import { createSessionMutationClient, type SessionMutationSnapshot } from '../../../shared/src/session-http-mutations'++const mutatePersistedVisibility = createSessionMutationClient()import { PRIMARY_SESSION_VIEW } from '@/app/chat/session-view'import { openSession, type OpenSessionIntent } from '@/app/open-session'+ import { syncWorkspaceRoute } from '@/app/routes'import type { ClientSessionState } from '@/app/types'import {$narrowViewport,diff --cc apps/desktop/src/store/gateway-profile-request.test.tsindex 33199317def,5dfc6f11608..0cb827a3952--- a/apps/desktop/src/store/gateway-profile-request.test.ts+++ b/apps/desktop/src/store/gateway-profile-request.test.ts@@@ -108,6 -111,21 +110,23 @@@ describe('requestGatewayForProfile', (expect($gateway.get()).toBe(primary)})- it('dials the profile with foreground priority when a Settings-scoped caller asks for it (#111651)', async () => {++ it('accepts a Settings-scoped foreground dial hint without changing the canonical dial (#111651)', async () => {+ setPrimaryGateway(makePrimary() as never, 'default')++ const getConnection = vi.fn(async (profile: null | string) =>+ profile ? { port: 5151, profile, token: 'secondary-token' } : { port: 4242, token: 'primary-token' }+ )++ installDesktop(getConnection)+ await ensureGatewayForProfile('default')++ await requestGatewayForProfile('worker', 'vault.list', {}, undefined, undefined, { spawnPriority: 'foreground' })+- expect(getConnection).toHaveBeenCalledWith('worker', { priority: 'foreground' })++ // `gateway ensure` has no slot pool to reserve: the hint is carried by the++ // call shape, the dial itself stays the plain profile descriptor request.++ expect(getConnection).toHaveBeenCalledWith('worker')+ })+it('uses the primary socket and adds profile scope for a shared global remote route', async () => {const primary = makePrimary()setPrimaryGateway(primary as never, 'default')@@@ -568,8 -597,11 +589,10 @@@ describe('attached shared-remote groupgetGatewayWsUrlFor: vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) => ({ok: true as const,wsUrl: `ws://${connectionId}/${profile}`- })),- touchBackend: vi.fn(async () => undefined)+ }))}++ return getConnectionFor}it('reuses the primary socket for a named profile on the attached shared remote', async () => {diff --cc apps/desktop/src/store/gateway.tsindex eedba46180f,942a4c21449..48d72def561--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@@ -26,6 -27,26 +27,13 @@@ import { stampSecondaryProfileOwner } fconst normKey = (profile: string | null | undefined): string => (profile ?? '').trim() || 'default'-// Spawn-slot priority handed to Electron main with every backend dial. A-// user-initiated open is 'foreground' and may take the pool's reserved slot;-// roster hydration, hover prewarm and untagged dials are 'background' — main's-// default, so background dials keep the pre-priority IPC payload shape.++// Dial intent callers attach to a user-initiated open. The canonical++// `hermes gateway ensure` path has no local slot pool, so the hint changes++// nothing about the dial itself; it survives as the option shape the SDK,++// Settings scopes and session creation pass so an explicit user gesture stays++// distinguishable from ambient hydration at the call site.+ export type SpawnPriority = 'foreground' | 'background'+-function dialPriority(spawnPriority: SpawnPriority): { priority: 'foreground' } | Record<never, never> {- return spawnPriority === 'foreground' ? { priority: 'foreground' } : {}-}--function dialProfile(- desktop: NonNullable<typeof window.hermesDesktop>,- profile: string,- spawnPriority: SpawnPriority-): Promise<HermesConnection> {- return spawnPriority === 'foreground'- ? desktop.getConnection(profile, { priority: 'foreground' })- : desktop.getConnection(profile)-}-// Read connection state through a call so TS control-flow analysis doesn't// narrow the getter to a constant across guards (it genuinely changes).const isOpen = (gateway: HermesGateway | null): boolean => gateway?.connectionState === 'open'@@@ -919,9 -991,13 +950,12 @@@ export async function requestGatewayFormethod: string,params: Record<string, unknown> = {},timeoutMs?: number,- signal?: AbortSignal+ signal?: AbortSignal,- { spawnPriority = 'background' }: { spawnPriority?: SpawnPriority } = {}++ // Dial intent (#111651): accepted so Settings-scoped callers keep one call++ // shape; the canonical ensure path has no slot to reserve.++ _options: { spawnPriority?: SpawnPriority } = {}): Promise<T> {- // 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)+ const route = await gatewayForProfile(profile, true)try {if (!route.gateway) {@@@ -946,6 -1022,12 +980,11 @@@* composite (connectionId, profile) pool key prevents same-named agents on two* sources from sharing a socket. Only null/empty ids retain the v1 profile* resolver; explicit `local` is a registry source and must use getConnectionFor.+ *- * `spawnPriority` defaults to 'background' like every other dial in this file.- * A user gesture that reaches the pool through this RPC path (first send on a- * fresh chat, "New session", an explicit Bot Chat open) passes 'foreground' so- * its cold spawn takes the pool's reserved interactive slot instead of queuing- * behind roster hydration (#102281 primitive; #105104 symptom).++ * `spawnPriority` marks a user gesture that reaches this RPC path (first send on++ * a fresh chat, "New session", an explicit Bot Chat open) as 'foreground'++ * (#102281 primitive; #105104 symptom). The canonical ensure dial has no slot++ * to reserve, so the tag is carried, not acted on.*/export async function requestGatewayForAgent<T>(connectionId: null | string,@@@ -971,10 -1054,10 +1011,10 @@@// Require both owner identities to agree before collapsing the route; a// different source or profile must retain its isolated secondary.if (isPrimaryRegistryRoute(connectionId, key)) {- return requestGatewayForProfile<T>(key, method, params, timeoutMs, signal)+ return requestGatewayForProfile<T>(key, method, params, timeoutMs, signal, { spawnPriority })}- if (await isAttachedSharedRemote(connectionId, key, spawnPriority)) {+ if (await isAttachedSharedRemote(connectionId, key)) {return requestOnPrimaryGateway<T>(method, { ...params, profile: key }, timeoutMs, signal)}@@@ -1148,8 -1232,16 +1188,15 @@@ export function retainGatewayForRelay(c* acquire this lease before the first session-scoped RPC and release it in a* `finally`; the refcount keeps the socket (and the session it minted) alive* for the whole sequence. Primary/shared-primary routes return a no-op release.+ *+ * `spawnPriority` follows requestGatewayForAgent: the retain is the FIRST dial- * of a session-create gesture, so a user click passes 'foreground' here or the- * cold spawn still queues behind background hydration before the create RPC.++ * of a session-create gesture, so a user click passes 'foreground' here.*/- export async function retainGatewayForAgent(connectionId: null | string, profile: string): Promise<() => void> {+ export async function retainGatewayForAgent(+ connectionId: null | string,+ profile: string,- { spawnPriority = 'background' }: { spawnPriority?: SpawnPriority } = {}++ _options: { spawnPriority?: SpawnPriority } = {}+ ): Promise<() => void> {const key = normKey(profile)const scope = registryBackendScopeKey(connectionId, key)@@@ -1446,8 -1539,12 +1493,12 @@@ export async function ensureGatewayForAreturn !signal?.aborted}+ const activationEpoch = beginGatewayActivation()+- if (await isAttachedSharedRemote(connectionId, profile, 'foreground')) {+ if (await isAttachedSharedRemote(connectionId, profile)) {- return Boolean(isOpen(g.primaryGateway) && !signal?.aborted)+ // A retained primary can be open while the foreground still points at a+ // different source. Reusing its socket must also move the active route.+ return Boolean(isOpen(g.primaryGateway) && !signal?.aborted && applyActive(g.primaryProfile, activationEpoch))}if (!window.hermesDesktop?.getConnectionFor) {diff --cc apps/desktop/src/store/notifications.tsindex 54ecb9197fc,57d2fda740a..7738e06aef4--- 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 { isLocalBackendSlotWaitTimeout, requestPoolLimitsSettings } from '@/store/pool-limits'+ import { requestBackendRestart, requestRoute } from '@/store/recovery-requests'export type NotificationKind = 'error' | 'warning' | 'info' | 'success'@@@ -197,14 -247,21 +246,15 @@@ export function notify(input: Notificatreturn id}- export function notifyError(error: unknown, fallback: string): string {+ export function notifyError(error: unknown, fallback: string, options: { action?: NotificationAction } = {}): 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,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/gateway-events.tsindex e7f4535539e,f4cab921695..2f08f72a603--- a/apps/shared/src/gateway-events.ts+++ b/apps/shared/src/gateway-events.ts@@@ -1,598 -1,26 +1,43 @@@/**- * Wire types for `tui_gateway` JSON-RPC notifications and the RPC responses the- * TypeScript surfaces (Ink TUI, Desktop, web dashboard) share.+ * Wire types for the `tui_gateway` JSON-RPC surface shared by the Ink TUI, Desktop and the+ * web dashboard.*- * Every notification arrives as `{jsonrpc: '2.0', method: 'event', params: GatewayEvent}`- * (`tui_gateway/server.py::_event_frame`). `GatewayEventMap` is the single map from- * event `type` to payload shape; `BACKEND_EVENT_NAMES` mirrors the emitter side and is- * pinned to `gateway-events.json` by `gateway-events.test.ts` (vitest) and- * `tests/tui_gateway/test_gateway_event_contract.py` (Python), so a name added on one- * side without the other fails a test instead of drifting silently.+ * Every shape here is GENERATED from `tui_gateway/contracts` (Python is the single source):+ * `./gateway-contract.generated.ts` carries `RpcMethods` (client→server method → params/result),+ * `ServerRequestMap` (server→client request → params/result), `GatewayEventMap` (notification+ * type → payload) and every value shape. `scripts/gen_gateway_contracts.py` regenerates it and+ * `tests/tui_gateway/contracts/test_generated.py` fails when the committed file is stale, so a field the+ * backend stops sending fails `tsc` here instead of drifting.*- * Payload interfaces are typed from the Python emitters (file::symbol noted per- * interface). Events whose payload no TS client reads yet are `Record<string, unknown>`;- * they still MUST be keys so `on('x', …)` stays exhaustive.+ * This module adds only what the wire does not carry: the client-local synthetic events the TUI+ * transport publishes into the same handler stream, and the `GatewayEvent` envelope.*/- import type { BillingBlock } from './billing-types.js'- import type { HermesSkin } from './skin.js'+ import type { BackendGatewayEventMap } from './gateway-contract.generated.js'- // ── Shared value shapes ──────────────────────────────────────────────+ export * from './gateway-contract.generated.js'- /** `tui_gateway/server.py::_get_usage` — a session's token/cost counters. */- export interface Usage {- active_subagents?: number- /** Rolling mean API latency over the last 10 calls (seconds). */- avg_latency_s?: number- /** Rolling output tokens/sec over the last 10 calls. */- avg_tps?: number- /** Session prompt-cache hit ratio (cache_read / prompt tokens, %). Omitted (not 0)- * when the provider reports no cache reads. */- cache_hit_pct?: number- cache_read?: number- cache_write?: number- calls: number- compressions?: number- context_max?: number- context_percent?: number- context_estimated?: boolean- context_source?: string- context_used?: number- cost_status?: string- cost_usd?: number- dev_credits_spent_micros?: number- input: number- output: number- reasoning?: number- total: number- }-- /** Advisory `{layer, code, retryable}` descriptor (`agent/error_surface.py`). */- export interface ErrorSurface {- code?: string- layer?: string- retryable?: boolean- }-- /** `tui_gateway/tool_progress.py::_normalize_todo_state` — full task snapshot. */- export interface TodoStatePayload {- revision?: number- todos?: unknown[]- }-- export type SubagentStatus = 'completed' | 'error' | 'failed' | 'interrupted' | 'queued' | 'running' | 'timeout'-- /** `tui_gateway/tool_progress.py::_progress_subagent` — every `subagent.*` frame. */- export interface SubagentEventPayload {- api_calls?: number- /** The child's own gateway session id — the key a watch window mirrors. */- child_session_id?: string- /** Batch (delegation) id this subagent belongs to — distinguishes- * interleaved `[n/N]` progress from concurrent or nested fan-outs. */- delegation_id?: string- depth?: number- duration_seconds?: number- files_read?: string[]- files_written?: string[]- goal: string- input_tokens?: number- model?: string- output_tail?: { is_error?: boolean; preview?: string; tool?: string }[]- output_tokens?: number- parent_id?: null | string- reasoning_tokens?: number- status?: SubagentStatus- subagent_id?: string- summary?: string- task_count?: number- task_index: number- text?: string- tool_count?: number- tool_name?: string- tool_preview?: string- toolsets?: string[]- }-- // ── Event payloads ───────────────────────────────────────────────────-- /** `tui_gateway/entry.py` (stdio) / `tui_gateway/ws.py` (WebSocket) first frame. */- export interface GatewayReadyPayload {- /** Backends with the change watcher broadcast `*.changed` events; consumers- * demote their legacy polls to slow backstops. */- change_events?: boolean- /** WebSocket transport only: the server answers heartbeat pings. */- heartbeat?: boolean- /** Opaque token for this server process's `seq` numbering; a new epoch means- * replay watermarks must be discarded. */- replay_epoch?: string- skin?: HermesSkin- }-- /** `tui_gateway/prompt_turn.py::_complete_turn_payload` and- * `tui_gateway/session_auto_continue.py::_emit_terminal_turn_error`. */- export interface MessageCompletePayload {- /** Structured billing wall when the turn failed with FailoverReason.billing. */- billing?: BillingBlock- /** `status: "error"` — the failure message (`text` may be streamed output). */- error?: string- error_surface?: ErrorSurface- failure_reason?: string | null- /** `status: "error"` — `text` is streamed partial output to keep, not the error string. */- partial?: boolean- reasoning?: string- /** `status: "error"` — the failed turn was retained and replays via `session.resume.inflight`. */- recoverable?: boolean- rendered?: string- /** The final text was already previewed via `message.interim`; settle, don't duplicate. */- response_previewed?: boolean- status?: 'complete' | 'error' | 'interrupted' | string- text?: string- usage?: Usage- /** History-commit note (e.g. a mid-turn desync the gateway surfaced instead of dropping). */- warning?: string- }-- /** `tui_gateway/tool_progress.py::_on_tool_start`. */- export interface ToolStartPayload {- /** Full tool arguments — the 80-char `context` preview is display-only. */- args?: Record<string, unknown>- /** Verbose mode only: pretty-printed args. */- args_text?: string- context?: string- name?: string- /** Mirrored child tool rows carry a short preview instead of args. */- preview?: string- tool_id: string- /** Not on the wire (`_on_tool_start` never sets it): the todo snapshot rides `tool.complete` /- * `todo.updated`. Kept because the TUI handler reads it and its fixtures exercise that path. */- todos?: unknown[]- }-- /** `tui_gateway/tool_progress.py::_on_tool_complete`. */- export interface ToolCompletePayload {- args?: Record<string, unknown>- duration_s?: number- inline_diff?: string- name?: string- /** Parsed JSON when the tool returned JSON, else the raw string. */- result?: unknown- /** Verbose mode only. */- result_text?: string- revision?: number- summary?: string- tool_id: string- todos?: unknown[]- }-- export interface ToolGeneratingPayload {- name?: string- }-- /** `tui_gateway/tool_progress.py::_progress_output_risk`. */- export interface ToolOutputRiskPayload {- findings?: string[]- name?: string- redacted?: boolean- risk?: string- tool_id?: string- }-- export interface StatusUpdatePayload {- kind?: string- text?: string- }-- export interface NotificationShowPayload {- id?: string- key?: string- kind?: 'sticky' | 'ttl' | string- level?: 'error' | 'info' | 'success' | 'warn' | string- text?: string- ttl_ms?: null | number- }-- export interface NotificationClearPayload {- key?: string- }-- export interface TextPayload {- text?: string- }-- /** `message.delta` / `reasoning.delta` / `reasoning.available` / `thinking.delta`. */- export interface StreamDeltaPayload {- rendered?: string- text?: string- /** Verbose reasoning mode is on for this session. */- verbose?: boolean- }-- export interface MessageInterimPayload {- already_streamed?: boolean- text: string- }-- export interface SessionUsagePayload {- usage?: Usage- }-- export interface SessionTitlePayload {- session_id?: string- title?: string- }-- /** `tui_gateway/methods_session.py` resume hydration progress. */- export interface SessionResumeProgressPayload {- message?: string- message_count?: number- phase?: string- status?: 'complete' | 'failed' | 'loading' | string- }-- /** `tui_gateway/session_lifecycle.py::_announce_session_reclaimed`. */- export interface SessionReclaimedPayload {- reason?: string- session_id?: string- stored_session_id?: string- }-- export interface SessionControlUpdatePayload {- control?: unknown- }-- export interface ErrorPayload {- message?: string- reason?: string- }-- export interface NoticePayload {- message?: string- }-- export interface ReactionPayload {- kind?: string- }-- export interface BillingStepUpVerificationPayload {- user_code?: string- verification_url: string- }-- export interface VoiceStatusPayload {- state?: 'idle' | 'listening' | 'transcribing' | string- }-- export interface VoiceTranscriptPayload {- no_speech_limit?: boolean- stop_phrase?: boolean- text?: string- typed?: boolean- voice_stopped?: boolean- }-- export interface WakeDetectedPayload {- phrase?: string- profile?: null | string- start_new_session?: boolean- }-- export interface BrowserProgressPayload {- level?: 'error' | 'info' | 'warn' | string- message?: string- }-- export interface MoaReferencePayload {- count?: number- index?: number- label?: string- text?: string- }-- export interface MoaAggregatingPayload {- aggregator?: string- }-- export interface MoaProgressPayload {- label?: string- refs_done?: number- refs_total?: number- }-- export interface MoaPhasePayload {- aggregator?: string- phase?: string- refs_done?: number- refs_total?: number- }-- // Blocking bridges (`tui_gateway/server.py::_block`): every `*.request` carries a- // `request_id`; the matching `*.expire` names the same id when the wait timed out.-- export interface RequestExpirePayload {- request_id: string- }-- export interface ClarifyQuestion {- choices?: null | string[]- multi_select?: boolean- qid: string- question: string- }-- export interface ClarifyRequestPayload {- answers?: Record<string, string>- choices?: null | string[]- multi_select?: boolean- question?: string- questions?: ClarifyQuestion[]- request_id: string- }-- /** `tui_gateway/server.py::_approval_request_payload` (command redacted server-side). */- export interface ApprovalRequestPayload {- allow_permanent?: boolean- choices?: string[]- command: string- description: string++/** Owner-stamped pending prompt on a canonical gateway. */++export interface CanonicalPromptEvent {++ execution_generation?: number++ kind?: 'approval' | 'clarify'++ prompt_id: string++ /** Set by the Desktop canonical protocol layer for the named listeners. */+ request_id?: string- smart_denied?: boolean- }-- export interface SudoRequestPayload {- request_id: string- }-- export interface SecretRequestPayload {- env_var: string- prompt: string- request_id: string- }-- export interface VaultUnlockRequestPayload {- backend: string- display_name: string- request_id: string+}+- export interface VaultCodeRequestPayload {- hint?: string- request_id: string- site?: string- }-- export interface McpSetupRequestPayload {- action?: string- reason?: string- request_id: string- server?: string- }-- /** Side agents (`tui_gateway/methods_prompt.py::_spawn_side_agent`). */- export interface SideAgentCompletePayload {- question?: string- task_id: string- text: string- }-- export interface PreviewRestartProgressPayload {- task_id: string- text: string- }-- export interface TerminalOutputPayload {- chunk?: string- process_id?: string- }-- export interface TerminalClosePayload {- process_id?: string- }-- // ── The map ──────────────────────────────────────────────────────────-/**- * Backend-emitted notification names. Derived from the `tui_gateway` emitter call- * sites and pinned to `gateway-events.json`; keep sorted. Adding a name here without- * the JSON (or vice versa) fails `gateway-events.test.ts`, and a Python emitter that- * names an event missing from the JSON fails `test_gateway_event_contract.py`.- */- export const BACKEND_EVENT_NAMES = [- 'agent.terminal.output',- 'approval.request',- 'background.complete',- 'billing.step_up.verification',- 'bot_relay.outbox.pending',- 'browser.controller.cancel',- 'browser.controller.command',- 'browser.progress',- 'btw.complete',- 'clarify.expire',- 'clarify.request',- 'cron.changed',- 'error',- 'gateway.ready',- 'layout.apply',- 'mcp.setup.expire',- 'mcp.setup.request',- 'message.complete',- 'message.delta',- 'message.interim',- 'message.reaction',- 'message.start',- 'moa.aggregating',- 'moa.phase',- 'moa.progress',- 'moa.reference',- 'notice',- 'notification.clear',- 'notification.show',- 'pairing.changed',- 'pane.reveal',- 'pet.changed',- 'pet.generate.progress',- 'pet.hatch.progress',- 'platforms.changed',- 'preview.act.expire',- 'preview.act.request',- 'preview.close',- 'preview.open',- 'preview.read.expire',- 'preview.read.request',- 'preview.restart.complete',- 'preview.restart.progress',- 'reaction',- 'reasoning.available',- 'reasoning.delta',- 'review.summary',- 'secret.expire',- 'secret.request',- 'session.control.update',- 'session.info',- 'session.reclaimed',- 'session.resume_progress',- 'session.title',- 'session.usage',- 'sessions.changed',- 'setup.ready',- 'skin.changed',- 'status.update',- 'subagent.complete',- 'subagent.progress',- 'subagent.spawn_requested',- 'subagent.start',- 'subagent.thinking',- 'subagent.tool',- 'sudo.expire',- 'sudo.request',- 'terminal.close',- 'terminal.read.expire',- 'terminal.read.request',- 'thinking.delta',- 'tip.show',- 'todo.updated',- 'tool.complete',- 'tool.generating',- 'tool.output_risk',- 'tool.start',- 'tour.expire',- 'tour.request',- 'vault.code.expire',- 'vault.code.request',- 'vault.save_login.expire',- 'vault.save_login.request',- 'vault.unlock.expire',- 'vault.unlock.request',- 'voice.interrupted',- 'voice.status',- 'voice.transcript',- 'wake.detected',- 'window.read.expire',- 'window.read.request'- ] as const satisfies readonly (keyof BackendGatewayEventMap)[]-- export type BackendGatewayEventName = (typeof BACKEND_EVENT_NAMES)[number]-- /** Payload per backend-emitted notification `type`. Keys are exactly `BACKEND_EVENT_NAMES`. */- export interface BackendGatewayEventMap {- 'agent.terminal.output': TerminalOutputPayload- 'approval.request': ApprovalRequestPayload- 'background.complete': SideAgentCompletePayload- 'billing.step_up.verification': BillingStepUpVerificationPayload- 'bot_relay.outbox.pending': Record<string, unknown>- 'browser.controller.cancel': Record<string, unknown>- 'browser.controller.command': Record<string, unknown>- 'browser.progress': BrowserProgressPayload- 'btw.complete': SideAgentCompletePayload- 'clarify.expire': RequestExpirePayload- 'clarify.request': ClarifyRequestPayload- 'cron.changed': Record<string, unknown>- error: ErrorPayload- 'gateway.ready': GatewayReadyPayload- 'layout.apply': Record<string, unknown>- 'mcp.setup.expire': RequestExpirePayload- 'mcp.setup.request': McpSetupRequestPayload- 'message.complete': MessageCompletePayload- 'message.delta': StreamDeltaPayload- 'message.interim': MessageInterimPayload- 'message.reaction': Record<string, unknown>- 'message.start': undefined- 'moa.aggregating': MoaAggregatingPayload- 'moa.phase': MoaPhasePayload- 'moa.progress': MoaProgressPayload- 'moa.reference': MoaReferencePayload- notice: NoticePayload- 'notification.clear': NotificationClearPayload- 'notification.show': NotificationShowPayload- 'pairing.changed': Record<string, unknown>- 'pane.reveal': Record<string, unknown>- 'pet.changed': Record<string, unknown>- 'pet.generate.progress': Record<string, unknown>- 'pet.hatch.progress': Record<string, unknown>- 'platforms.changed': Record<string, unknown>- 'preview.act.expire': RequestExpirePayload- 'preview.act.request': Record<string, unknown>- 'preview.close': Record<string, unknown>- 'preview.open': Record<string, unknown>- 'preview.read.expire': RequestExpirePayload- 'preview.read.request': Record<string, unknown>- 'preview.restart.complete': SideAgentCompletePayload- 'preview.restart.progress': PreviewRestartProgressPayload- reaction: ReactionPayload- 'reasoning.available': StreamDeltaPayload- 'reasoning.delta': StreamDeltaPayload- 'review.summary': TextPayload- 'secret.expire': RequestExpirePayload- 'secret.request': SecretRequestPayload- 'session.control.update': SessionControlUpdatePayload- /** Surface-specific shape (`tui_gateway/server.py::_session_info`); each client narrows. */- 'session.info': Record<string, unknown>- 'session.reclaimed': SessionReclaimedPayload- 'session.resume_progress': SessionResumeProgressPayload- 'session.title': SessionTitlePayload- 'session.usage': SessionUsagePayload- 'sessions.changed': Record<string, unknown>- 'setup.ready': Record<string, unknown>- 'skin.changed': HermesSkin- 'status.update': StatusUpdatePayload- 'subagent.complete': SubagentEventPayload- 'subagent.progress': SubagentEventPayload- 'subagent.spawn_requested': SubagentEventPayload- 'subagent.start': SubagentEventPayload- 'subagent.thinking': SubagentEventPayload- 'subagent.tool': SubagentEventPayload- 'sudo.expire': RequestExpirePayload- 'sudo.request': SudoRequestPayload- 'terminal.close': TerminalClosePayload- 'terminal.read.expire': RequestExpirePayload- 'terminal.read.request': Record<string, unknown>- 'thinking.delta': StreamDeltaPayload- 'tip.show': Record<string, unknown>- 'todo.updated': TodoStatePayload- 'tool.complete': ToolCompletePayload- 'tool.generating': ToolGeneratingPayload- 'tool.output_risk': ToolOutputRiskPayload- 'tool.start': ToolStartPayload- 'tour.expire': RequestExpirePayload- 'tour.request': Record<string, unknown>- 'vault.code.expire': RequestExpirePayload- 'vault.code.request': VaultCodeRequestPayload- 'vault.save_login.expire': RequestExpirePayload- 'vault.save_login.request': Record<string, unknown>- 'vault.unlock.expire': RequestExpirePayload- 'vault.unlock.request': VaultUnlockRequestPayload- 'voice.interrupted': Record<string, unknown>- 'voice.status': VoiceStatusPayload- 'voice.transcript': VoiceTranscriptPayload- 'wake.detected': WakeDetectedPayload- 'window.read.expire': RequestExpirePayload- 'window.read.request': Record<string, unknown>- }-- /**- * Client-local synthetic events. Never emitted by `tui_gateway`; the Ink TUI's- * `gatewayClient` publishes them into the same handler stream to report transport- * state. Excluded from `gateway-events.json` on purpose.+ * Client-local synthetic events. Never emitted by `tui_gateway`; the Ink TUI's `gatewayClient`+ * publishes them into the same handler stream to report transport state.*/export interface ClientLocalGatewayEventMap {++ /** Canonical gateways (`gateway/session_pending_controls.py`) fan pending prompts out as++ * events stamped with the owner's `execution_generation`; Desktop's canonical protocol++ * layer projects them onto the named prompt listeners and answers over `approval.respond`++ * / `clarify.respond`. Not part of the generated `tui_gateway` contract. */++ 'approval.request': CanonicalPromptEvent & { command?: string; description?: string; choices?: string[]; edit?: unknown }++ 'approval.settled': CanonicalPromptEvent++ 'clarify.request': CanonicalPromptEvent & { question?: string; choices?: string[]; multi_select?: boolean }++ 'clarify.settled': CanonicalPromptEvent'dashboard.new_session_requested': { reason?: string }'gateway.protocol_error': { preview?: string }'gateway.reconnecting': { attempt?: number; delay_ms?: number }diff --cc apps/shared/src/json-rpc-gateway.tsindex ce6410c0464,338272b762c..b1b228f7749--- a/apps/shared/src/json-rpc-gateway.ts+++ b/apps/shared/src/json-rpc-gateway.ts@@@ -447,18 -454,17 +457,19 @@@ export class JsonRpcGatewayClient// 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)- )+ }))- 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/AGENTS.mdindex 0729303272f,b2a5b6b3909..a0c07aa8675--- a/cron/AGENTS.md+++ b/cron/AGENTS.md@@@ -23,13 -26,18 +27,24 @@@ Hardening invariants — each guards afinds the stamp with a dead owner restores the instant ONCE (`cron/occurrences.py`), theexecutions ledger's `scheduled_instant` blocks a second fire, `cron.catch_up_missed: false`skips past-grace misses with a logged reason. Never drop a slot silently (#107485).- - File lock `~/.hermes/cron/.tick.lock` prevents duplicate ticks across processes.+ - Per-home tick lock `<home>/cron/.tick.lock` prevents duplicate ticks across processes for+ that profile's store; never a `~/.hermes/...` literal.+- **Headless ticks refuse, never spawn.** `hermes cron tick` (system crontab / external scheduler)+ calls `tick(headless=True)`; `cron/scheduler_gateway_gate.py` skips agent jobs when discovery+ says no gateway owns the home (`last_fire_error` stamped, one warning per tick, due instant+ untouched) instead of letting `run_canonical_job → connect_gateway → ensure_gateway_runtime`+ spawn an unmanaged daemon. Same policy as approvals (headless/cron = refuse). The in-process+ ticker and `hermes cron run` are not headless.+ - **The ticker binds each served profile's scope for the whole tick, including pre-loop code.**+ `scheduler_provider.py::_start_multiplex` is ONE ticker iterating `profiles_to_serve()`+ sequentially under `_profile_cron_scope(home)` (home + secret scope + terminal scope) — never N+ threads (module globals race). Everything a tick touches lives inside that guard: store open,+ lock path, backoff/failure counters (`_note_tick_failure`), job env construction, and the+ `on_session_end` flush of a finished job. Supervision (`scheduler_thread.py::+ SupervisedTickerThread`; start on gateway boot, stand down for homes another gateway already+ serves, re-enumerate when a profile dir appears or is tombstoned) is per served home, not per+ process. Why: a store opened before the scope was entered wrote a secondary profile's run+ records into the launch profile's `jobs.json`.- Cron sessions pass `skip_memory=True`; memory providers intentionally do not run during cron.- Cron execution has its own session. Eligible continuable deliveries may mirror or seed thereply-facing conversation: origin, origin-less home fallback, user-written bare-platform home,diff --cc cron/jobs.pyindex 9b6b7fd7915,98e26aa0b24..e6e1dea16a0--- a/cron/jobs.py+++ b/cron/jobs.py@@@ -25,9 -25,9 +25,9 @@@ tryimport msvcrtexcept ImportError: # pragma: no cover - non-Windowsmsvcrt = None- from datetime import datetime, timedelta+ from datetime import datetime, timedelta, timezonefrom pathlib import Path-from hermes_constants import get_hermes_home+from hermes_constants import display_hermes_home, get_hermes_homefrom cron.env_settings import cron_env_settingfrom typing import Optional, Dict, List, Any, Callable, Set, Tuple, Union, Collectiondiff --cc gateway/control_socket.pyindex 8a8f112b0bb,1845936afcc..7fa8e3befdc--- a/gateway/control_socket.py+++ b/gateway/control_socket.py@@@ -137,8 -134,7 +138,8 @@@ class GatewayControlServerself._pipe_server: Any = None # Windows proactor pipe serverself._bind_path: Optional[Path] = Noneself._pointer_file: Optional[Path] = None+ self._file_identities = {}- self._handlers: dict[str, Callable[[], dict[str, Any]]] = {+ self._handlers: dict[str, Callable[..., dict[str, Any]]] = {"identify": build_identify_payload, "status": build_status_payload, **(verb_handlers or {})}async def start(self) -> bool:diff --cc gateway/platforms/api_server_runs.pyindex 3bbdeb57241,0acfed5a85f..d50ea0450e6--- a/gateway/platforms/api_server_runs.py+++ b/gateway/platforms/api_server_runs.py@@@ -42,16 -42,23 +42,28 @@@ _USAGE_FIELDS =("input_tokens", "session_prompt_tokens"), ("output_tokens", "session_completion_tokens"),("total_tokens", "session_total_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+++ def _tool_completed_preview(result: Any, redact_sensitive_text: Callable[..., str]) -> str:+ """Bounded, secret-redacted result summary for the public run stream — redacted BEFORE+ truncation so a cut never leaves a secret's prefix on the wire."""+ if result is None:+ return ""+ text = result if isinstance(result, str) else json.dumps(result, ensure_ascii=False, default=str)+ preview = redact_sensitive_text(text, force=True)+ limit = _TOOL_COMPLETED_PREVIEW_MAX_CHARS+ return preview if len(preview) <= limit else preview[: limit - 3] + "..."def _remember_room_retention(request: "web.Request", claims: dict[str, Any]) -> None:@@@ -685,51 -661,24 +723,50 @@@ 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),- **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))+ 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)+ 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)+ 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))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.- if result.get("interrupted") is True:- _finish("cancelled")+ status, fields = terminal_run_status(result)+ if status == "cancelled":+ _finish("cancelled", fields)elif result.get("failed"):# Non-retryable client errors (401/400) return failed=True rather than raising.- _finish("failed", error=_redact_api_error_text(result.get("error") or "agent run failed"))+ _finish("failed", fields, error=_redact_api_error_text(result.get("error") or "agent run failed"))else:- # Undelivered steer text rides on the terminal event/status for client replay.- extra = {"pending_steer": result["pending_steer"]} if result.get("pending_steer") else {}- _finish("completed", extra, output=result.get("final_response", ""), usage=usage)+ _finish(status, fields, output=result.get("final_response", ""), usage=usage)except asyncio.CancelledError:_finish("cancelled")raisediff --cc gateway/platforms/webhook.pyindex 3e7635176d9,e8b13aa9973..e23e0426c3f--- a/gateway/platforms/webhook.py+++ b/gateway/platforms/webhook.py@@@ -177,13 -189,9 +179,15 @@@ class WebhookAdapter(BasePlatformAdapteself._max_body_bytes: int = int(extra.get("max_body_bytes", 1_048_576)) # 1MBself._script_timeout_seconds: int = int(extra.get("script_timeout_seconds", DEFAULT_SCRIPT_TIMEOUT_SECONDS))self._route_processor = WebhookRouteProcessor(script_timeout_seconds=self._script_timeout_seconds)+ # Opt-in per-route debounce of rapid same-entity events (route ``coalesce`` block). #92066+ self._coalescer = WebhookCoalescer(dispatch=self._spawn_agent_run, render=self._render_prompt)+ @property+ def token(self):+ # Bind native replay to the currently configured signing credentials.+ return json.dumps([self._global_secret, {name: route.get("secret", self._global_secret)+ for name, route in self._routes.items()}], sort_keys=True)+# --- Lifecycle ---def _validate_route(self, name: str, route: dict) -> None:@@@ -569,18 -617,36 +618,61 @@@delivery_id = headers.get("X-GitHub-Delivery", headers.get("svix-id", headers.get("webhook-id", headers.get("X-Request-ID", str(int(time.time() * 1000))))))now = time.time() # idempotency: skip duplicate deliveries (webhook retries)- if not self._record_delivery_id(delivery_id, now):+ if route_config.get("deliver_only") and not self._record_delivery_id(delivery_id, now):logger.info("[webhook] Skipping duplicate delivery %s", delivery_id)return web.json_response({"status": "duplicate", "delivery_id": delivery_id}, status=200)+ if route_config.get("cron_job"):+ return self._handle_cron_trigger(prompt, route_config, route_name, event_type, delivery_id, profile)if route_config.get("deliver_only"):return await self._handle_deliver_only(prompt, payload, route_config, route_name, event_type, delivery_id,profile)+ coalesce = route_config.get("coalesce")++ # A coalesced event waits in memory before it is durably admitted, so the ledger cannot dedupe++ # a provider retry inside the window; the in-memory idempotency guard fills that gap here.++ if isinstance(coalesce, dict) and not self._record_delivery_id(delivery_id, now):++ logger.info("[webhook] Skipping duplicate delivery %s", delivery_id)++ return web.json_response({"status": "duplicate", "delivery_id": delivery_id}, status=200)+ if isinstance(coalesce, dict) and self._coalescer.enqueue(+ route_name=route_name, coalesce=coalesce, payload=payload, event_type=event_type, prompt=prompt,+ delivery_id=delivery_id, now=now, route_config=route_config, profile=profile):+ return web.json_response({"status": "coalesced", "route": route_name, "event": event_type,+ "delivery_id": delivery_id}, status=202)- return self._dispatch_agent_run(request, route_config, route_name, profile, payload, prompt, event_type,+ return await self._dispatch_agent_run(request, route_config, route_name, profile, payload, prompt, event_type,delivery_id, now)- def _dispatch_agent_run(self, request, route_config: dict, route_name: str, profile, payload: Any, prompt: str,+ async def _dispatch_agent_run(self, request, route_config: dict, route_name: str, profile, payload: Any, prompt: str,event_type: str, delivery_id: str, now: float) -> "web.Response":- """Spawn the agent run for one POST and return 202 immediately."""+ """Acknowledge only after the authority commits the immutable delivery."""+ logger.info("[webhook] %s event=%s route=%s prompt_len=%d delivery=%s", request.method, event_type, route_name,+ len(prompt), delivery_id)- self._spawn_agent_run(payload, prompt, delivery_id, now, route_config=route_config, route_name=route_name,- profile=profile, event_type=event_type)++ outcome = await self._admit_agent_run(payload, prompt, delivery_id, now, route_config=route_config,++ route_name=route_name, profile=profile, event_type=event_type)++ if outcome is None:++ return _json_error("Admission unavailable; retry this delivery", 503)++ if outcome == "duplicate":++ return web.json_response({"status": "duplicate", "delivery_id": delivery_id}, status=200)+ return web.json_response({"status": "accepted", "route": route_name, "event": event_type,+ "delivery_id": delivery_id}, status=202)++ def _spawn_agent_run(self, payload: Any, prompt: str, delivery_id: str, now: float, *, route_config: dict,+ route_name: str, profile, event_type: str) -> "asyncio.Task":- """Record delivery info and fire the agent run (shared by the immediate and coalesced paths)."""++ """Coalesced-path dispatch (settled timer / disconnect flush): admit the merged event as a task++ so ``WebhookCoalescer.flush`` can await the hand-off. The HTTP ack for these deliveries was++ already ``coalesced``; an admission failure is logged, never retried by the producer."""++ async def _admit_or_log():++ outcome = await self._admit_agent_run(payload, prompt, delivery_id, now, route_config=route_config,++ route_name=route_name, profile=profile, event_type=event_type)++ if outcome is None:++ logger.error("[webhook] Coalesced delivery %s on route %s was not admitted", delivery_id, route_name)++ task = asyncio.create_task(_admit_or_log())++ self._background_tasks.add(task)++ task.add_done_callback(self._background_tasks.discard)++ return task++++ async def _admit_agent_run(self, payload: Any, prompt: str, delivery_id: str, now: float, *, route_config: dict,++ route_name: str, profile, event_type: str) -> Optional[str]:++ """Record delivery info and admit the run through the durable producer (shared by the immediate++ and coalesced paths). ``"accepted"`` / ``"duplicate"``, or None when admission failed."""# delivery_id in the session key → concurrent webhooks on one route get independent runs.session_chat_id = f"webhook:{route_name}:{delivery_id}"# ``profile`` rides along so the reply leg (``send`` → ``_deliver_cross_platform``) egresses through@@@ -596,46 -662,41 +688,43 @@@if profile and isinstance(profile, str):source.profile = profileevent = MessageEvent(text=prompt, message_type=MessageType.TEXT, source=source, raw_message=payload,- message_id=delivery_id)- # The per-delivery session is closed by ``on_processing_complete`` once the run finishes- # (``handle_message`` is fire-and-forget, so nothing can be closed here).- task = asyncio.create_task(self.handle_message(event))+ message_id=delivery_id, timestamp=datetime.fromtimestamp(0, timezone.utc))- logger.info("[webhook] %s event=%s route=%s prompt_len=%d delivery=%s", request.method, event_type, route_name,- len(prompt), delivery_id)+ from gateway.platforms.webhook_ingress import admit_producer+ try:+ receipt = await admit_producer(self, event)+ except Exception:+ logger.exception("[webhook] Durable admission failed for %s", delivery_id)- return _json_error("Admission unavailable; retry this delivery", 503)++ return None+ if getattr(event, '_webhook_duplicate', False):- return web.json_response({"status": "duplicate", "delivery_id": delivery_id}, status=200)++ return "duplicate"+ from gateway.session_authorities import active_authority, authority_for_profile_id+ runner = self._message_handler.__self__+ authority = authority_for_profile_id(runner, receipt.ref.profile_id) or active_authority(runner)+ task = asyncio.create_task(self._finalize_delivery(event, authority, receipt))self._background_tasks.add(task)task.add_done_callback(self._background_tasks.discard)- return web.json_response({"status": "accepted", "route": route_name, "event": event_type,- "delivery_id": delivery_id}, status=202)- return task++ return "accepted"- async def on_processing_complete(self, event: "MessageEvent", outcome: Any) -> None:- """Close the one-shot per-delivery session: ``prune_sessions`` only reaps rows with ``ended_at`` set, so- unclosed webhook sessions leak unbounded. Fires at the true end of the run; ``end_session()`` is- first-reason-wins."""- await self._end_webhook_session(event, event.source.chat_id)+ async def _finalize_delivery(self, event, authority, receipt):+ from hermes_state_runtime import get_session_admission+ try:+ row = get_session_admission(authority.db, admission_id=receipt.admission_id)+ if row['status'] in {'queued', 'started'}:+ waiter = authority.waiters.setdefault(receipt.admission_id,+ asyncio.get_running_loop().create_future())+ await asyncio.shield(waiter)+ row = get_session_admission(authority.db, admission_id=receipt.admission_id)+ event._webhook_receipt = (authority, authority._receipt(row))+ await self._end_webhook_session(event, event.source.chat_id)+ except Exception:+ logger.exception("[webhook] Could not finalize admitted delivery %s", receipt.admission_id)async def _end_webhook_session(self, event: "MessageEvent", session_chat_id: str) -> None:- """Mark the per-delivery session ended via ``SessionDB.end_session`` (never a hand-written UPDATE),- resolving session_id from the SAME source the run was keyed on."""- runner = self.gateway_runner- session_db, store = getattr(runner, "_session_db", None), getattr(runner, "session_store", None)- key_fn = getattr(runner, "_session_key_for_source", None)- if runner is None or session_db is None or store is None or key_fn is None:- return- try:- session_key = key_fn(event.source)- session_id = _peek_session_id(store, session_key)- if not session_id:- logger.debug("[webhook] No session_id to close for %s (key=%s)", session_chat_id, session_key)- return- # AsyncSessionDB forwards end_session via to_thread; plain SessionDB is sync.- result = session_db.end_session(session_id, "webhook_complete")- if asyncio.iscoroutine(result):- await result- logger.debug("[webhook] Closed session %s for delivery %s", session_id, session_chat_id)- except Exception as e:- logger.debug("[webhook] Failed to close session for %s: %s", session_chat_id, e)+ from gateway.platforms.webhook_ingress import finalize_webhook+ binding = getattr(event, '_webhook_receipt', None)+ if binding is not None:+ authority, receipt = binding+ finalize_webhook(authority, receipt)# --- Signature validation ---diff --cc gateway/run_agent_cache.pyindex 060a4ac7d5a,1197ab4a330..8df46d6563a--- a/gateway/run_agent_cache.py+++ b/gateway/run_agent_cache.py@@@ -698,34 -693,38 +700,42 @@@ class GatewayAgentCacheMixinctx.run(self._run_release_in_profile_scope, target, args, session_key)def _run_release_in_profile_scope(self, target, args: tuple, session_key: Optional[str]) -> None:- """Call ``target(*args)`` under the profile that owns ``session_key``. Threads start with an- EMPTY context, so a bare thread would commit end-of-session memory (provider ``on_session_end``- reads credentials/home at call time) under the LAUNCH profile — lost memories or a secondary's- transcript extracted into the default profile's provider namespace. In-turn callers already- carry the scope (``copy_context`` preserves it); the unscoped housekeeping sweep resolves the- owner from the session key (``agent:<profile>:...``) and enters that profile's scope."""+ """Call ``target(*args)`` under the profile that OWNS ``session_key``.++ Threads start with an EMPTY context, so a bare thread would commit end-of-session memory+ (provider ``on_session_end`` reads credentials/home at call time) under the launch profile.+ And the LRU-cap eviction runs inside the REQUESTING turn, whose agent may belong to another+ profile — so "some scope is present" is not enough either. The owner comes from the session+ key: a named profile's home, else the DEFAULT profile (``agent:main:`` keys), which is the+ root Hermes dir even when the gateway was launched under a named profile. Its scope is+ entered unless the current one already is the owner's."""from agent.secret_scope import current_secret_scope, is_multiplex_active- if current_secret_scope() is not None or not is_multiplex_active():- target(*args)- return- from gateway.run import _profile_runtime_scope- from hermes_constants import get_hermes_home- home = None- store = getattr(self, "session_store", None)- if session_key and store is not None:- with suppress(Exception):- home = store._profile_home_for_key(session_key)- with _profile_runtime_scope(home or get_hermes_home()):+ scope = nullcontext()+ if is_multiplex_active():+ from gateway.run import _profile_runtime_scope+ from hermes_constants import get_default_hermes_root, get_hermes_home, hermes_home_key+ owner = None+ store = getattr(self, "session_store", None)+ if session_key and store is not None:+ try:+ owner = store._profile_home_for_key(session_key)+ except Exception:+ logger.warning("Could not resolve the owning profile for %s; releasing under the default profile",+ session_key, exc_info=True)+ owner_home = Path(owner) if owner else get_default_hermes_root()+ if current_secret_scope() is None or hermes_home_key(get_hermes_home()) != hermes_home_key(owner_home):+ scope = _profile_runtime_scope(owner_home)+ with scope:target(*args)- def _commit_memory_before_soft_evict(self, agent: Any, key: str) -> None:- """Commit the live transcript to memory providers before resource-only eviction."""- # No external memory provider (``_memory_manager`` None) — nothing to commit.- if agent is None or not hasattr(agent, "commit_memory_session") or getattr(agent, "_memory_manager", None) is None:+ def _commit_memory_before_soft_evict(self, agent: Any, key: str, boundary: bool = False) -> None:+ """Commit the live transcript to memory providers before resource-only eviction. A session+ boundary (reset, compress) also ends the context engine's session; that engine can run without a provider."""+ if agent is None or not hasattr(agent, "commit_memory_session"):+ return+ has_provider = getattr(agent, "_memory_manager", None) is not None+ has_engine = boundary and getattr(agent, "context_compressor", None) is not None+ if not has_provider and not has_engine:returntry:messages = getattr(agent, "_session_messages", None)diff --cc gateway/run_bootstrap.pyindex b09396eb4a4,00000000000..136a9fe66cfmode 100644,000000..100644--- a/gateway/run_bootstrap.py+++ b/gateway/run_bootstrap.py@@@ -1,683 -1,0 +1,686 @@@+"""Process startup phases; diagnostics remain in the gateway facade."""+from __future__ import annotations++import threading- from typing import Optional++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.",+ 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")+ 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")+ asyncio.create_task(runner.stop())+ return shutdown_signal_handler+++def _start_gateway_claim_pid_file() -> bool:+ """Claim the runtime lock + PID file (O_EXCL winner is the authoritative gateway). False = lost."""+ from gateway.run import (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)+ 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+ 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", "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})++ "rescan-profiles": _rescan_profiles_handler,++ "migrate-profile-identity": migrate_profile_identity_verb(runner)})+ _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 (Any, Dict, Platform, _cron_tick_profile_homes, _start_gateway_housekeeping, asyncio, logger, threading)++ from gateway.run import (Dict, Platform, _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))+ cron_provider = scheduler_for_profile_mode(+ resolve_cron_scheduler(), multiplex_profiles=multiplex_cron)+ 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)++ # 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)- cron_thread = threading.Thread(- target=cron_provider.start, args=(cron_stop,), kwargs=cron_start_kwargs, daemon=True,- name="cron-scheduler")++ # 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_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: threading.Thread, housekeeping_thread: threading.Thread,++ 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()++ # 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:+ """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)."""+ from gateway.run import (+ GatewayRunner,+ _best_effort,+ _discover_gateway_mcp_tools,+ _enable_multiplex_log_routing,+ _ensure_windows_gateway_venv_imports,+ _gateway_loop_exception_handler,+ _multiplex_profile_homes,+ _resolve_gateway_exit_verdict,+ _run_planned_stop_watcher,+ _shutdown_gateway_health_export,+ _shutdown_mcp_servers_nonblocking,+ 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.+ 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():+ 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)++ 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")+ 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()+ 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()+ return _resolve_gateway_exit_verdict(runner, _signal_initiated_shutdown[0])+ finally:+ _shutdown_gateway_health_export(runner)++ cron_stop, cron_provider, cron_thread, housekeeping_thread = (+ _start_gateway_start_cron_and_housekeeping(runner))++ # READY only once adapters, cron and housekeeping run; missing systemd state just disables watchdog.+ from gateway.run_runtime import publish_gateway_runtime_ready+ publish_gateway_runtime_ready(runner)+ runner._start_systemd_watchdog()++ from gateway.run_runtime import wait_gateway_runtime+ try:+ await wait_gateway_runtime(runner)+ finally:+ try:+ await runner.stop()+ finally:+ verdict = await _start_gateway_shutdown_tail(+ runner, _control_server, cron_stop, cron_provider, cron_thread, housekeeping_thread,+ _planned_stop_watcher_stop, _planned_stop_watcher_thread, _signal_initiated_shutdown)+ return verdict++ finally:+ try:+ if runner is not None:+ from gateway.run_runtime import drain_gateway_runtime+ await drain_gateway_runtime(runner)+ # Startup may have opened adapters before an exception. The same+ # stop path owns their writers and DB handles on every exit.+ await runner.stop()+ finally:+ if _planned_stop_watcher_stop is not None:+ _planned_stop_watcher_stop.set()+ if _control_server is not None:+ await _control_server.stop()+ remove_pid_file()+ release_gateway_runtime_lock()diff --cc gateway/run_runtime_init.pyindex e53aabd4cc6,00000000000..4159dbaf523mode 100644,000000..100644--- a/gateway/run_runtime_init.py+++ b/gateway/run_runtime_init.py@@@ -1,273 -1,0 +1,262 @@@+"""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)+ 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._restart_drain_timeout = self._load_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+ # 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] = {}+ # 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)+ # 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)+- # Stale checkpoint repo cleanup; opt-in via checkpoints.auto_prune, idempotent via .last_prune.- try:- from hermes_cli.config import load_config as _load_full_config- _ckpt_cfg = (_load_full_config().get("checkpoints") or {})- if _ckpt_cfg.get("auto_prune", False):- from tools.checkpoint_manager import maybe_auto_prune_checkpoints- # delete_orphans never honoured unattended: a missing workdir is ambiguous (deleted vs.- # unmounted share); orphan cleanup is only via explicit `hermes checkpoints prune`.- maybe_auto_prune_checkpoints(- retention_days=int(_ckpt_cfg.get("retention_days", 7)),- min_interval_hours=int(_ckpt_cfg.get("min_interval_hours", 24)),- delete_orphans=False,- max_total_size_mb=int(_ckpt_cfg.get("max_total_size_mb", 500)))- except Exception as exc:- logger.debug("checkpoint auto-maintenance skipped: %s", exc)++ # 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++diff --cc gateway/run_turn.pyindex 05166c5e1e6,3eac3a283c4..b88f1330312--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@@ -66,14 -78,226 +78,47 @@@ def is_context_overflow_failure_result(return any(p in err for p in _CONTEXT_OVERFLOW_ERROR_PHRASES) or ("400" in err and history_len > 50)+ # Setup/prefix rows rather than conversation: the agent rebuilds its own system prompt, and a+ # transcript meta row is logging-only — neither reaches the model, but both are the head a+ # fail-closed payload keeps.+ _HYGIENE_SETUP_ROLES = ("system", "session_meta")+++ def bound_model_input_without_hygiene(history: List[Any], limit: int) -> List[Any]:+ """Fail-closed in-context bound for a turn where hygiene has not landed (#111988).++ Keeps the leading ``system``/``session_meta`` setup rows plus the newest tail, total <= ``limit``.+ Deterministic (the same transcript always yields the same cut) and payload-only: the stored+ transcript is never touched, so the agent's durable-prefix slice (``history_offset``) is+ unaffected. Returns ``history`` unchanged — same object — when nothing needs dropping, so the+ landed-compression and below-the-limit paths stay byte-identical.+ """+ if len(history) <= limit:+ return history+ head_end = 0+ while (head_end < len(history) and isinstance(history[head_end], dict)+ and history[head_end].get("role") in _HYGIENE_SETUP_ROLES):+ head_end += 1+ # Always leave room for the newest row: a setup-only payload would answer nothing.+ head_end = min(head_end, limit - 1)+ tail_start = len(history) - (limit - head_end)+ # Never start the kept tail on a tool result: its parent assistant(tool_calls) row is dropped+ # with it, and an orphaned tool result is an invalid sequence for every provider.+ while (tail_start < len(history) and isinstance(history[tail_start], dict)+ and history[tail_start].get("role") == "tool"):+ tail_start += 1+ return history[:head_end] + history[tail_start:]++-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.+from gateway.run_turn_prepare import GatewayTurnPrepareMixin+from gateway.run_turn_hygiene import GatewayTurnHygieneMixin+from gateway.run_turn_persistence import GatewayTurnPersistenceMixin- 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)-- 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()- 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)- 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"],- )+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``."""@@@ -833,22 -2789,12 +896,17 @@@_gateway_platform_value, _has_platform_display_override, _load_gateway_config,_platform_config_key,)- from gateway.display_config import resolve_display_setting+ from 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)- # display.platforms.<platform>.<key> → display.<key> → built-in platform defaults.- _display_cfg = user_config.get("display", {})- if not isinstance(_display_cfg, dict):- _display_cfg = {}-# 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 9e8dc094334,00000000000..4201e93fd84mode 100644,000000..100644--- a/gateway/run_turn_hygiene.py+++ b/gateway/run_turn_hygiene.py@@@ -1,800 -1,0 +1,823 @@@+"""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)+ if _adapter and source.chat_id:+ await _adapter.send(source.chat_id, message, metadata=meta)+ 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 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,+ )++ 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, "⚠️ Context compression aborted "- f"({_err}). No messages were dropped — "- "conversation is unchanged. Run /compress to retry, /reset for a clean "- "session, or check your auxiliary.compression model configuration.",++ 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,+ lambda: _hyg_agent._compress_context(+ _hyg_msgs, "", approx_tokens=plan.approx_tokens, commit_fence=_hyg_commit_fence,+ ),+ )+ 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 history++ 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 history++ 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 1aa897bfdc4,00000000000..cdbb6409720mode 100644,000000..100644--- a/gateway/run_turn_persistence.py+++ b/gateway/run_turn_persistence.py@@@ -1,548 -1,0 +1,565 @@@+"""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.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 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.++ # "(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:- response = (- "⚠️ The model returned no response after processing tool results. This can happen "- "with some models — try again or rephrase your question."- )++ 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 time=%.1fs api_calls=%d response=%d chars",- _platform_name, source.chat_id or "unknown",++ "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,+ )+ 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."+ )++ 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++ 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."""+ # 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)+ # 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:+ 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).+ _STATUS_HINTS = {- 401: " Check your API key or run `claude /login` to refresh OAuth credentials.",- 402: " Your API balance or quota is exhausted. Check your provider dashboard.",- 529: " The API is temporarily overloaded. Please try again shortly.",++ 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."),++ 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.- return (- "⚠️ Session too large for the model's context window.\nUse /compact to "- "compress the conversation, or /reset to start fresh."- )++ 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)+ 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:+ # 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 request was rejected by the API."++ status_hint = " The AI model service rejected the request."+ return self._hmwa_add_failed_turn_notice(- f"Sorry, I encountered an unexpected error.{status_hint}\n"- "Try again or use /reset to start a fresh session.",++ 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,+ )++ 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)diff --cc gateway/run_turn_prepare.pyindex 8f0bd80fd5a,00000000000..e7f1ef0ea7bmode 100644,000000..100644--- a/gateway/run_turn_prepare.py+++ b/gateway/run_turn_prepare.py@@@ -1,671 -1,0 +1,672 @@@+"""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)++ 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()+ 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)+ 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)+ 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+ 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+ RENDER is gated behind gateway.message_timestamps.enabled (default OFF)."""+ from gateway.run import _load_gateway_config, _message_timestamps_enabled+ 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+ _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.- persist_user_display_kind = "internal_notification" if getattr(event, "internal", False) else None++ 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)+ # 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 6704f322bcf,00000000000..95044dc9bf0mode 100644,000000..100644--- a/gateway/run_turn_progress.py+++ b/gateway/run_turn_progress.py@@@ -1,831 -1,0 +1,869 @@@+"""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+ 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"),++ 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")+ 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)+ 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 authorization refusal, distinct from native_failed: the- # connector refused this destination, so no later publication in this- # turn may re-deliver the task text through the text fallback. Declared- # rather than set dynamically so the state is visible where it lives.- egress_declined: 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 getattr(st, "egress_declined", False):++ 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.egress_declined = True++ 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 getattr(st, "egress_declined", False):- # The connector refused this destination earlier in the turn; every- # later publication would re-deliver the same task text there.++ 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.egress_declined = True++ 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- logger.warning(- "Slack native task-card progress failed; falling back "- "to an editable text update: %s", getattr(result, "error", "unknown error"),- )++ 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 the progress queue into Slack-native plan/task cards; on any native failure, fall- back to an editable in-thread message so progress stays live.++ """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+ 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+ ctx = self._ctx+ if 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)diff --cc gateway/run_turn_runner.pyindex a83e6c80933,a2ee1c4667e..c4debde2ef6--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@@ -369,13 -1337,19 +386,22 @@@ class TurnRunner(GatewayTurnProgressMix# 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.- response = _clarify_send_then_wait(fut, clarify_id=clarify_id, session_key=session_key, clarify_mod=clarify_mod)+ response, answered = _clarify_send_then_wait(+ fut, clarify_id=clarify_id, session_key=session_key, clarify_mod=clarify_mod)+ if self._approval_owner is not None:+ authority, session_id, generation = self._approval_owner+ authority.sessions[session_id].controls.snapshot(session_id, generation)- # Only re-arm typing when the user actually answered — the undeliverable sentinel and the- # timeout/cancellation strings start with '[' and must pass through untouched.- if not (isinstance(response, str) and response.startswith("[")):+ # 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:+ # No answer arrived (timeout, /new, run end): retire the native card so it stops+ # looking answerable. Adapters without a persistent card have no such method.+ retire = getattr(type(ctx._status_adapter), "retire_clarify_card", None)+ if callable(retire):+ self._schedule(+ retire(ctx._status_adapter, clarify_id, _CLARIFY_EXPIRED_NOTICE),+ "Clarify card retire failed to schedule")+ else:# Reopen typing IMMEDIATELY, not on the LLM's first post-answer token (native streaming# otherwise re-seeds lazily on the first delta: ~48s of dead air). request_reopen_seed is# a no-op outside the reopen-pending native state.@@@ -890,22 -1812,20 +925,31 @@@model, runtime_kwargs.get("provider"), ctx.session_key or "",)except Exception as exc:- return {"final_response": f"⚠️ Provider authentication failed: {exc}", "messages": [], "api_calls": 0, "tools": []}+ # 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)+ 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_bot.pyindex 951670bf2c8,00000000000..436d3a48426mode 100644,000000..100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@@ -1,245 -1,0 +1,251 @@@+"""Bot Chat ingress into the existing authority FIFO; viewers never own delivery.++The mailbox is a delivery receipt, not an execution queue. A committed canonical+admission is the only consumer; unknown execution is never retried as inference.+"""+import asyncio+from pathlib import Path++from agent.turn_author import parse_turn_author++from gateway.session_contract import Principal, SessionRef+from gateway.config import Platform+from gateway.platforms.event import MessageEvent+from hermes_state_runtime import RuntimeStoreError, get_session_admission+from tools.bot_live_delivery import _delivery_id, _locked, _read, _write+++def _home(authority, actor, profile):+ from gateway.session_authorities import served_profile_name+ home = Path(authority.db.db_path).parent.resolve()+ name = served_profile_name(home)+ if actor.profile_id != authority.profile_id or profile not in (name, 'hermes' if name == 'default' else name):+ raise RuntimeStoreError('profile_mismatch')+ if 'session:submit' not in actor.capabilities:+ raise RuntimeStoreError('permission_denied')+ return home+++def _target(authority, actor):+ row = authority.db.get_session_by_title('Bot Chat')+ if row is None:+ ref = _create_bot_chat(authority, actor)+ else:+ tip = authority.db.get_compression_tip(row['id'])+ target = authority.db.get_session(tip)+ if target is None:+ raise RuntimeStoreError('not_found')+ from gateway.session_local_migration import resolve_local_target+ ref = resolve_local_target(authority, actor, target['id'])+ authority.authorize(actor, ref, 'session:submit')+ live = authority.sessions[ref.session_id]+ entry = authority.runner.session_store.lookup_by_session_key(live.route)+ if live.source.platform != Platform.LOCAL or entry is None:+ raise RuntimeStoreError('admission_conflict')+ return ref, live, entry+++def _create_bot_chat(authority, actor):+ """No Bot Chat yet: mint it the way ``hermes chat --in ~ -c "Bot Chat" --create-if-missing``+ did on the CLI lane this door replaced, so a fresh profile's first delivery has somewhere+ to land instead of being recorded as failed. Same owner step as ``session.create`` with a+ title: no await between the lookup and the titled creation. Creation is the actor's own+ capability; a submit-only principal (owner recovery) still gets ``not_found``."""+ if 'session:create' not in actor.capabilities:+ raise RuntimeStoreError('not_found')+ from gateway.session_local import create_local_session+ from gateway.session_local_title import title_new_session+ ref = create_local_session(authority, actor, {+ 'request_id': 'bot-chat:' + authority.profile_id, 'source': 'cli', 'cwd': str(Path.home())})+ title_new_session(authority, ref, 'Bot Chat')+ return ref+++def _result(authority, record):+ row = get_session_admission(authority.db, admission_id=record['admission_id'])+ if row is None:+ raise RuntimeStoreError('storage_unavailable')+ # A terminal row without a result blob is still definitive when the outcome says the+ # input never ran (cancelled) or was refused/failed; ambiguous is reserved for the+ # durable unknown state and for missing evidence (completed/interrupted without result).+ status = {'queued': 'queued', 'started': 'claimed', 'unknown': 'ambiguous',+ 'terminal': {'cancelled': 'cancelled', 'rejected': 'failed', 'failed': 'failed'}.get(row['outcome'], 'ambiguous')}[row['status']]+ # Read only this admission's committed result, never transcript recency.+ from gateway.session_results import admission_result+ saved = admission_result(authority.db, record['admission_id'])+ reply = record.get('reply', '')+ if saved is not None:+ reply = saved['result'].get('final_response', '')+ status = 'settled' if row['outcome'] == 'completed' else 'failed'++ # 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++ if status == 'settled' and is_intentional_silence_response(reply):++ reply = ''+ elif record.get('status') in {'settled', 'failed'}:+ status = record['status']+ return {k: v for k, v in dict(status=status, delivery_id=record['delivery_id'],+ profile_home=record['profile_home'], session_id=record['session_id'],+ admission_id=record['admission_id'], message=record['message'], reply=reply).items()}+++async def _record_reply(authority, home, key, future):+ await asyncio.shield(future)+ with _locked(home) as root:+ path = root / f'{key}.json'+ record = _read(path)+ record.update(_result(authority, record))+ _write(path, record)+++def relay_operation(connection, operation, params):+ authority, actor = connection.authority, connection.actor+ from gateway.session_authorities import served_profile_name+ home = Path(authority.db.db_path).parent.resolve()+ name = served_profile_name(home)+ _home(authority, actor, name)+ if 'session:control' not in actor.capabilities:+ raise RuntimeStoreError('permission_denied')+ fields = {'roster': {'agents'}, 'outbox': set(), 'reply': {'id', 'reply', 'error', 'reason'}}+ if set(params) - fields[operation]:+ raise RuntimeStoreError('invalid_params')+ from tools.bot_relay import write_remote_roster, claim_pending_envelopes, write_reply+ if operation == 'roster':+ return {'count': write_remote_roster(home, params.get('agents'))}+ if operation == 'outbox':+ return {'envelopes': claim_pending_envelopes(home)}+ try:+ write_reply(home, params.get('id'), reply=params.get('reply', ''),+ error=params.get('error', ''), reason=params.get('reason', ''))+ except ValueError as exc:+ raise RuntimeStoreError('admission_conflict') from exc+ return {'ok': True}+++async def _migrate(authority, actor, home, root):+ records = [(path, _read(path)) for path in root.glob('*.json')]+ legacy = [(path, record) for path, record in records+ if record and 'owner' in record and not record.get('admission_id')+ and record['status'] in {'queued', 'claimed'}]+ if not legacy:+ return+ ref, live, entry = _target(authority, actor)+ for path, record in sorted(legacy, key=lambda item: (item[1].get('sequence', item[1]['created_at']), item[0].name)):+ owner = record['owner']+ if owner['profile_home'] != str(home):+ continue+ if authority.db.get_compression_tip(owner['session_id']) != entry.session_id:+ continue+ from hermes_cli.active_sessions import active_session_liveness_guard+ with active_session_liveness_guard(owner['session_id'], registry_home=home) as active:+ if active:+ raise RuntimeStoreError('runtime_coordination_required')+ if record['status'] == 'claimed':+ record.update(status='ambiguous', reason='unknown_execution')+ _write(path, record)+ continue+ await _admit(authority, actor, home, root, _delivery_id(record['delivery_id']),+ record['message'], ref, live, entry, author=parse_turn_author(record.get('author')), legacy=record)+++async def recover_bot_deliveries(authority):+ """Rebuild derivative replies and queued legacy admissions at owner startup."""+ home = Path(authority.db.db_path).parent.resolve()+ with _locked(home) as root:+ records = [(path, _read(path)) for path in root.glob('*.json')]+ for path, record in records:+ if not record or record.get('profile_home') != str(home) or not record.get('admission_id'):+ continue+ record.update(_result(authority, record))+ _write(path, record)+ if record['status'] in {'queued', 'claimed'}:+ _watch_reply(authority, home, record['delivery_id'], record['admission_id'])+ row = authority.db.get_session_by_title('Bot Chat')+ if row is None:+ return+ target = authority.db.get_session(authority.db.get_compression_tip(row['id']))+ if target is None:+ return+ from hermes_state_local import POLICY_PREFIX+ with authority.db._read_ctx() as conn:+ bound = conn.execute('SELECT 1 FROM state_meta WHERE key=?',+ (POLICY_PREFIX + (target.get('chat_id') or target['id']),)).fetchone()+ if not bound:+ return # Unowned history requires a native ticket, never the first remote sender.+ actor = Principal(target['user_id'], authority.profile_id,+ frozenset({'session:submit', 'session:read'}), 'bot-owner-recovery')+ await _migrate(authority, actor, home, root)+++def _watch_reply(authority, home, key, admission_id):+ future = authority.waiters.setdefault(admission_id, asyncio.get_running_loop().create_future())+ task = asyncio.create_task(_record_reply(authority, home, key, future))+ tasks = getattr(authority, '_bot_receipt_tasks', None)+ if tasks is None:+ tasks = authority._bot_receipt_tasks = set()+ tasks.add(task)+ task.add_done_callback(tasks.discard)+++async def deliver(connection, params):+ authority, actor = connection.authority, connection.actor+ home = _home(authority, actor, params.get('profile'))+ if set(params) - {'id', 'profile', 'message', 'session_id', 'author'}:+ raise RuntimeStoreError('invalid_params')+ try:+ key = _delivery_id(params.get('id'))+ except ValueError as exc:+ raise RuntimeStoreError('invalid_params') from exc+ message = params.get('message')+ if not isinstance(message, str) or not message.strip() or len(message) > 16200:+ raise RuntimeStoreError('invalid_params')+ author = parse_turn_author(params.get('author'))+ if params.get('author') is not None and (not isinstance(params['author'], dict) or author is None):+ raise RuntimeStoreError('invalid_params')+ authority._require_admission_open()+ with _locked(home) as root:+ path = root / f'{key}.json'+ record = _read(path)+ if record is not None and record.get('admission_id'):+ if (record['message'] != message or record['principal_id'] != actor.subject+ or record.get('author') != author):+ raise RuntimeStoreError('admission_conflict')+ authority.authorize(actor, SessionRef(authority.profile_id, record['session_id']), 'session:submit')+ return _result(authority, record)+ await _migrate(authority, actor, home, root)+ record = _read(path)+ if record is not None and record.get('admission_id'):+ if (record['message'] != message or record['principal_id'] != actor.subject+ or record.get('author') != author):+ raise RuntimeStoreError('admission_conflict')+ authority.authorize(actor, SessionRef(authority.profile_id, record['session_id']), 'session:submit')+ return _result(authority, record)+ if record is not None:+ raise RuntimeStoreError('unknown_execution')+ ref, live, entry = _target(authority, actor)+ if params.get('session_id', entry.session_id) != entry.session_id:+ raise RuntimeStoreError('admission_conflict')+ return await _admit(authority, actor, home, root, key, message, ref, live, entry, author=author)+++async def _admit(authority, actor, home, root, key, message, ref, live, entry, author=None, legacy=None):+ path = root / f'{key}.json'+ event = MessageEvent(text=message, source=live.source, internal=True,+ message_id='bot:' + key, metadata={'gateway_session_key': live.route,+ 'gateway_session_id': entry.session_id})+ if author is not None:+ event.metadata['turn_author'] = dict(author)+ # Pin the physical target before committing. A process death in this+ # two-store window leaves an explicit unknown record, never a new target.+ record = dict(legacy or {}, delivery_id=key, profile_home=str(home), session_id=ref.session_id,+ principal_id=actor.subject, message=message, status='ambiguous')+ if author is not None:+ record['author'] = dict(author)+ _write(path, record)+ receipt = await authority.admit_automation(authority.runner._adapter_for_source(live.source), event, 'bot:' + key)+ record.update(status='canonical', admission_id=receipt.admission_id)+ _write(path, record)+ if receipt.status in {'queued', 'started'}:+ _watch_reply(authority, home, key, receipt.admission_id)+ return _result(authority, record)diff --cc gateway/session_kanban.pyindex 42931750e76,00000000000..28e2225fb31mode 100644,000000..100644--- a/gateway/session_kanban.py+++ b/gateway/session_kanban.py@@@ -1,222 -1,0 +1,229 @@@+"""Trusted dispatcher claims enter the ordinary owner's durable admission queue."""+from contextlib import closing+from dataclasses import asdict, replace+import json+from pathlib import Path+import sqlite3++from hermes_state_runtime import RuntimeStoreError+++def build_kanban_policy(connection, params, config):+ from hermes_cli import kanban_db as kb+ from hermes_cli.profiles import resolve_profile_env+ from gateway.session_policy import build_policy+ authority, actor = connection.authority, connection.actor+ if not connection.native_owner or 'session:create' not in actor.capabilities:+ raise RuntimeStoreError('permission_denied')+ if actor.profile_id != authority.profile_id:+ raise RuntimeStoreError('profile_mismatch')+ if (set(params) not in ({'board', 'task_id', 'run_id', 'claim_lock'}, {'board', 'task_id', 'run_id', 'claim_lock', 'db'})+ or any(not isinstance(params[k], str) or not params[k] for k in ('board', 'task_id', 'claim_lock'))+ or type(params['run_id']) is not int):+ raise RuntimeStoreError('invalid_params')+ try:+ board = kb._require_slug(params['board'])+ path = Path(params['db']).resolve(strict=True) if 'db' in params else kb.kanban_db_path(board=board).resolve()+ with closing(sqlite3.connect(path.as_uri() + '?mode=ro', uri=True)) as conn:+ conn.row_factory = sqlite3.Row+ task = kb.get_task(conn, params['task_id'])+ run = conn.execute('SELECT * FROM task_runs WHERE id=?', (params['run_id'],)).fetchone()+ if (task is None or run is None or task.status != 'running' or run['status'] != 'running'+ or task.current_run_id != params['run_id'] or run['task_id'] != task.id+ or task.claim_lock != params['claim_lock'] or run['claim_lock'] != task.claim_lock):+ raise RuntimeStoreError('stale_kanban_claim')+ if Path(resolve_profile_env(task.assignee)).resolve() != Path(authority.profile_id).resolve():+ raise RuntimeStoreError('profile_mismatch')+ bound = conn.execute("SELECT payload FROM task_events WHERE task_id=? AND run_id=? AND kind='owner_admitted' ORDER BY id DESC LIMIT 1",+ (task.id, task.current_run_id)).fetchone()+ if bound and json.loads(bound[0])['request_id'] != 'kanban:' + json.dumps([board, task.id, task.current_run_id], separators=(',', ':')):+ raise RuntimeStoreError('stale_kanban_claim')+ context = kb.build_worker_context(conn, task.id)+ except (ValueError, OSError, sqlite3.Error) as exc:+ raise RuntimeStoreError('invalid_kanban_claim') from exc+ cwd = task.workspace_path+ params_policy = {'source': 'cli', 'cwd': cwd}+ for name, value in (('model', task.model_override), ('provider', task.provider_override), ('reasoning', task.reasoning_effort)):+ if value:+ params_policy[name] = value+ private = {}+ policy = build_policy(params_policy, config, private_secrets=private)+ if policy.model is None:+ from gateway.run import _resolve_gateway_model+ policy = replace(policy, model=_resolve_gateway_model(policy.config()))+ context = dict(params, workspace=cwd, branch=task.branch_name, tenant=task.tenant,+ profile=task.assignee, workspaces_root=str(kb.workspaces_root(board=board).resolve()),+ skills=list(task.skills or ()), goal_mode=task.goal_mode, goal_max_turns=task.goal_max_turns,+ goal_text='\n\n'.join(p for p in (task.title, task.body) if p), context=context,+ max_runtime_seconds=task.max_runtime_seconds, accept_hooks=True)+ context['db'] = str(path)+ request = json.loads(policy.request_json)+ request.update(source='kanban', board=board, task_id=task.id, run_id=task.current_run_id)+ return replace(policy, source='kanban', platform='cli', toolsets=tuple(sorted(set(policy.toolsets) | {'kanban'})),+ request_json=json.dumps(request, sort_keys=True), kanban_json=json.dumps(context)), private+++async def run_task(connection, params):+ if not connection.native_owner or 'session:create' not in connection.actor.capabilities:+ raise RuntimeStoreError('permission_denied')+ from gateway.run import _load_gateway_config+ from gateway.session_local import create_local_session+ from gateway.session_contract import Submission+ from gateway.session_local_recovery import local_identity+ from hermes_state_local import local_receipt+ from gateway.session_policy import restore_policy+ authority = connection.authority+ # The dispatcher attempt is the durable request identity, including after the+ # task closes. Retry checks the saved claim, never reinterprets updated cards.+ request_id = 'kanban:' + json.dumps([params.get('board'), params.get('task_id'), params.get('run_id')], separators=(',', ':'))+ sid = local_identity(authority.profile_id, connection.actor.subject, request_id)+ saved = local_receipt(authority.db, sid) if authority.db.get_session(sid) is not None else None+ if saved:+ policy = restore_policy(saved['policy'])+ context = json.loads(policy.kanban_json or '{}')+ if (not connection.native_owner or set(params) not in ({'board', 'task_id', 'run_id', 'claim_lock'}, {'board', 'task_id', 'run_id', 'claim_lock', 'db'})+ or any(params[k] != context.get(k) for k in params)):+ raise RuntimeStoreError('permission_denied')+ from gateway.session_local_recovery import restore_local_session+ ref = restore_local_session(authority, sid)+ else:+ policy, private = build_kanban_policy(connection, params, _load_gateway_config())+ ref = create_local_session(authority, connection.actor, {'request_id': request_id},+ trusted_policy=policy, trusted_secrets=private)+ from hermes_cli.kanban_db_connect import connect_closing+ from hermes_cli import kanban_db as kb+ import os+ import psutil+ context = json.loads(policy.kanban_json)+ with connect_closing(Path(context['db'])) as conn, kb.write_txn(conn):+ # Either this exact attempt was already admitted to this session (retry after a+ # crash between session creation and admission), or the claim is still current+ # now; a reclaimed/closed task never reaches resume/submit.+ marker = conn.execute("SELECT payload FROM task_events WHERE task_id=? AND run_id=? AND kind='owner_admitted' ORDER BY id DESC LIMIT 1",+ (params['task_id'], params['run_id'])).fetchone()+ if marker:+ if json.loads(marker[0])['session_id'] != ref.session_id:+ raise RuntimeStoreError('stale_kanban_claim')+ else:+ task = kb.get_task(conn, params['task_id'])+ if not (task and task.status == 'running' and task.current_run_id == params['run_id'] and task.claim_lock == params['claim_lock']):+ raise RuntimeStoreError('stale_kanban_claim')+ kb._append_event(conn, task.id, 'owner_admitted',+ {'db': str(Path(authority.db.db_path).resolve()), 'session_id': ref.session_id,+ 'request_id': request_id, 'pid': os.getpid(), 'birth': psutil.Process().create_time()},+ run_id=task.current_run_id)+ await connection.resume(ref, {})+ receipt = await authority.submit(connection.actor, Submission(request_id, ref,+ {'text': f'work kanban task {params["task_id"]}'}, 'queue'))+ return {'session_id': ref.session_id, 'receipt': asdict(receipt)}+++def bind_worker_context(frame):+ """Only the adopted private exec calls this, before tool discovery imports."""+ import os+ context = json.loads(frame['policy'].get('kanban_json') or 'null')+ if context is None:+ return+ if frame['policy']['source'] != 'kanban':+ raise ValueError('invalid_kanban_policy')+ env = {'HERMES_KANBAN_TASK': context['task_id'], 'HERMES_KANBAN_BOARD': context['board'],+ 'HERMES_KANBAN_DB': context['db'], 'HERMES_KANBAN_RUN_ID': str(context['run_id']),+ 'HERMES_KANBAN_CLAIM_LOCK': context['claim_lock'], 'HERMES_KANBAN_WORKSPACE': context['workspace'],+ 'HERMES_KANBAN_WORKSPACES_ROOT': context['workspaces_root'], 'HERMES_PROFILE': context['profile'],+ 'HERMES_SESSION_SOURCE': 'kanban'}+ for key, value in (('HERMES_KANBAN_BRANCH', context['branch']), ('HERMES_TENANT', context['tenant'])):+ if value:+ env[key] = value+ if context['goal_mode']:+ env['HERMES_KANBAN_GOAL_MODE'] = '1'+ from hermes_cli.kanban_db_dispatch import _worker_terminal_timeout_env+ for key in ('TERMINAL_TIMEOUT', 'TERMINAL_MAX_FOREGROUND_TIMEOUT'):+ value = _worker_terminal_timeout_env(context['max_runtime_seconds'], os.environ.get(key))+ if value:+ env[key] = value+ from hermes_cli.kanban_db_connect import connect_closing+ from hermes_cli import kanban_db as kb+ with connect_closing(Path(context['db'])) as conn:+ with kb.write_txn(conn):+ task = kb.get_task(conn, context['task_id'])+ if (task is None or task.status != 'running' or task.current_run_id != context['run_id']+ or task.claim_lock != context['claim_lock']):+ raise RuntimeStoreError('stale_kanban_claim')- # Reclaim/timeout must track the executing interpreter, not its disposable viewer.- conn.execute('UPDATE tasks SET worker_pid=? WHERE id=?', (os.getpid(), task.id))- conn.execute('UPDATE task_runs SET worker_pid=? WHERE id=?', (os.getpid(), context['run_id']))++ # Reclaim/timeout must track the executing interpreter, not its disposable viewer. The++ # fingerprint moves with the pid: the dispatcher's liveness/kill checks compare the live++ # process against ``worker_started_at``, so a launcher fingerprint left beside our pid++ # would read as a recycled PID and reclaim a running worker.++ from hermes_cli.kanban_db_dispatch import UNVERIFIED_WORKER_FINGERPRINT, _process_fingerprint++ fingerprint = _process_fingerprint(os.getpid()) or UNVERIFIED_WORKER_FINGERPRINT++ conn.execute('UPDATE tasks SET worker_pid=?, worker_started_at=? WHERE id=?',++ (os.getpid(), fingerprint, task.id))++ conn.execute('UPDATE task_runs SET worker_pid=?, worker_started_at=? WHERE id=?',++ (os.getpid(), fingerprint, context['run_id']))+ kb._append_event(conn, task.id, 'worker_bound', {'pid': os.getpid(), 'claim_lock': context['claim_lock']}, run_id=context['run_id'])+ os.environ.update(env)+ os.chdir(context['workspace'])+ from agent.shell_hooks import register_from_config+ register_from_config(json.loads(frame['policy']['config_json']), accept_hooks=context['accept_hooks'])+++def run_worker_turns(agent, frame, history):+ context = json.loads(frame['policy'].get('kanban_json') or 'null')+ if context is None:+ author = frame.get('turn_author')+ return agent.run_conversation(frame['text'], conversation_history=history,+ **({'turn_author': author} if author is not None else {}))+ from hermes_cli.kanban_db import KANBAN_RATE_LIMIT_EXIT_CODE+ code = 1+ try:+ result = _run_task_turns(agent, frame, history, context)+ code = KANBAN_RATE_LIMIT_EXIT_CODE if result.get('failed') and result.get('failure_reason') in {'rate_limit', 'billing'} else int(bool(result.get('failed') or result.get('interrupted')))+ return result+ finally:+ import os+ from hermes_cli.kanban_db_connect import connect_closing+ from hermes_cli import kanban_db as kb+ with connect_closing(Path(context['db'])) as conn, kb.write_txn(conn):+ row = conn.execute("SELECT payload FROM task_events WHERE task_id=? AND run_id=? AND kind='worker_bound' ORDER BY id DESC LIMIT 1",+ (context['task_id'], context['run_id'])).fetchone()+ if row and json.loads(row[0]) == {'pid': os.getpid(), 'claim_lock': context['claim_lock']}:+ # Closing a run clears its claim/PID and replaces metadata; keep the+ # result in the immutable attempt event stream instead.+ kb._append_event(conn, context['task_id'], 'worker_result',+ {'pid': os.getpid(), 'claim_lock': context['claim_lock'], 'exit_code': code}, run_id=context['run_id'])+++def worker_exit_code(path, params):+ """Read only the dispatcher's exact attempt; never infer success from admission settlement."""+ with closing(sqlite3.connect(Path(path).resolve().as_uri() + '?mode=ro', uri=True)) as conn:+ row = conn.execute("SELECT payload FROM task_events WHERE run_id=? AND task_id=? AND kind='worker_result' ORDER BY id DESC LIMIT 1",+ (params['run_id'], params['task_id'])).fetchone()+ result = json.loads(row[0]) if row else {}+ return result.get('exit_code', 1) if result.get('claim_lock') == params['claim_lock'] else 1+++def _run_task_turns(agent, frame, history, context):+ from agent.skill_commands import build_preloaded_skills_prompt+ skills, loaded, missing = build_preloaded_skills_prompt(context['skills'], task_id=agent.session_id)+ if missing and not loaded:+ raise ValueError('kanban_skills_unavailable')+ prompt = '\n\n'.join(p for p in (skills, context['context'], frame['text']) if p)+ result = agent.run_conversation(prompt, conversation_history=history)+ if not context['goal_mode']:+ return result+ from hermes_cli.goals import run_kanban_goal_loop, DEFAULT_MAX_TURNS+ from hermes_cli import kanban_db as kb+ from hermes_cli.kanban_db_connect import connect_closing+ def status():+ with connect_closing() as conn:+ return kb.goal_run_status(conn, context['task_id'], context['run_id'])+ def block(reason):+ with connect_closing() as conn:+ kb.block_task(conn, context['task_id'], reason=reason, expected_run_id=context['run_id'])+ def turn(prompt):+ nonlocal result+ result = agent.run_conversation(prompt, conversation_history=agent._session_db.get_messages_as_conversation(agent.session_id))+ return result.get('final_response', '')+ run_kanban_goal_loop(task_id=context['task_id'], goal_text=context['goal_text'], run_turn=turn,+ task_status_fn=status, block_fn=block, max_turns=context['goal_max_turns'] or DEFAULT_MAX_TURNS,+ first_response=result.get('final_response', ''))+ return resultdiff --cc hermes_cli/config_defaults.pyindex 4f043572f87,3acddad8fe5..f03c7647012--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@@ -2412,7 -2443,7 +2444,7 @@@ DEFAULT_CONFIG =# Extra ports detection probes for an external llama-server (besides 8080)."detect_ports": [],},-- "_config_version": 45, # Config schema version - bump this when adding new required fields++ "_config_version": 46, # Config schema version - bump this when adding new required fields}diff --cc hermes_cli/config_migrations.pyindex 22553afee33,7d14ea3fedb..824d87e4665--- a/hermes_cli/config_migrations.py+++ b/hermes_cli/config_migrations.py@@@ -660,18 -707,8 +707,20 @@@ MIGRATIONS: Tuple[Tuple[int, Callable[[message=(" ✓ curator.archive_after_days 90→30 — skills unused for a month are archived to ""skills/.archive/ (recoverable with `hermes curator restore`). Set it back to 90 to keep the old window."))),- # 44 → 45: cron.bot_chat_delivery_timeout_seconds is gone with the local `hermes chat`+ # 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`+ # 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.- (45, functools.partial(++ (46, 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/gateway_setup_service.pyindex 27ac1c9697a,00000000000..a1f1b66fe79mode 100644,000000..100644--- a/hermes_cli/gateway_setup_service.py+++ b/hermes_cli/gateway_setup_service.py@@@ -1,140 -1,0 +1,142 @@@+"""Gateway service setup orchestration; runtime startup is separate."""++import sys++SERVICE_INSTALL_QUESTION = (+ "Install the gateway service so Hermes starts automatically at login "+ "and keeps scheduled jobs and messaging available?"+)+++def record_service_choice(choice: str, config: dict | None = None) -> None:+ from hermes_cli.config import load_config, save_config++ if choice not in {"install", "decline"}:+ raise ValueError("service_install_choice must be install or decline")+ current = load_config()+ current.setdefault("gateway", {})["service_install_choice"] = choice+ save_config(current)+ # Setup keeps a working config which it saves again after this step.+ if config is not None:+ config.setdefault("gateway", {})["service_install_choice"] = choice+++def wants_service_install(*, interactive: bool, install: bool = False,+ config: dict | None = None) -> bool:+ from hermes_cli.config import load_config+ from hermes_cli.gateway import prompt_yes_no++ if install:+ return True+ if not interactive or not sys.stdin.isatty():+ return False+ choice = (config if config is not None else load_config()).get("gateway", {}).get("service_install_choice")+ if choice is None:+ if prompt_yes_no(SERVICE_INSTALL_QUESTION, False):+ return True+ record_service_choice("decline", config)+ return choice == "install"+++def ensure_gateway_service(context: str = "setup", *, interactive: bool = False,+ install: bool = False, config: dict | None = None) -> bool:+ """Start existing services; install only with explicit setup consent.++ Import and ordinary noninteractive callers cannot install, even with a saved+ install preference. False leaves foreground/unmanaged startup to the caller.+ """+ from hermes_cli import gateway as gw+ from hermes_constants import is_container++ if is_container():+ gw.print_info("Run hermes gateway run as the container main process; use a Docker restart policy for persistence.")+ return False+ supports_systemd = gw.supports_systemd_services()+ if not (supports_systemd or gw.is_macos() or gw.is_windows()):+ gw.print_info("No supported service manager found. Run: hermes gateway run")+ return False+ try:+ if gw._is_service_running():+ return True++ if gw._served_profile_needs_no_service():++ return True+ if not gw._is_service_installed():+ if context == "import" or not wants_service_install(+ interactive=interactive, install=install, config=config+ ):+ gw.print_info("No service installed. Run: hermes gateway run")+ gw.print_info("Without a service, scheduled jobs and messaging stop at logout/reboot; jobs cannot run while the host is off.")+ return False+ if supports_systemd and gw.has_conflicting_systemd_units():+ gw.print_systemd_scope_conflict_warning()+ return False+ if supports_systemd:+ gw.systemd_install(force=False, non_interactive=True)+ elif gw.is_macos():+ gw.launchd_install(force=False)+ else:+ gw._gw_windows().install(force=False, start_now=True, start_on_login=True)+ # Installers can refuse without raising (e.g. temporary-home guard).+ if not gw._is_service_installed():+ gw.print_warning("Gateway service install did not complete. Retry: hermes gateway install")+ return False+ record_service_choice("install", config)+ if supports_systemd:+ gw.systemd_start()+ elif gw.is_macos():+ gw.launchd_start()+ else:+ gw._gw_windows().start()+ gw.print_success("Gateway service running (cron jobs + messaging platforms).")+ return True+ except gw.UserSystemdUnavailableError as exc:+ gw.print_warning("Could not reach user systemd to start the gateway service:")+ gw._print_indented(str(exc), gw.print_info)+ except gw.SystemScopeRequiresRootError as exc:+ gw.print_warning(f"Gateway service needs root for this scope: {exc}")+ gw._print_system_scope_remediation("start")+ except SystemExit:+ gw.print_warning("Gateway service install did not complete. Retry: hermes gateway install")+ except Exception as exc:+ gw.print_warning(f"Gateway service setup failed: {exc}")+ gw.print_info("You can retry manually: hermes gateway install")+ return False+++def _wizard_install_service(backend: str) -> None:+ """Choose persistence once; start-now without persistence stays unmanaged."""+ import subprocess+ from hermes_cli import gateway as gw+ from hermes_cli.gateway_runtime import ensure_gateway_runtime++ if not sys.stdin.isatty():+ return+ start_now = gw.prompt_yes_no(" Start the gateway now?", True)+ if not wants_service_install(interactive=True):+ gw.print_info("Without a service, messaging and scheduled jobs stop at logout/reboot; jobs cannot run while the host is off.")+ if start_now:+ result = ensure_gateway_runtime(gw.get_hermes_home(), timeout=5.0)+ if result.state == "ready":+ gw.print_success("Gateway runtime ready; no service was installed.")+ else:+ gw.print_info(f"Gateway runtime: {result.state} ({result.reason_code or 'pending'}). Check: hermes gateway status")+ else:+ gw.print_info("Run later: hermes gateway run. Install later: hermes gateway install")+ return+ try:+ scope, did_install = None, True+ if backend == "systemd":+ scope, did_install = gw.install_linux_gateway_from_setup(force=False, enable_on_startup=True)+ elif backend == "launchd":+ gw.launchd_install(force=False)+ else:+ gw._gw_windows().install(force=False, start_now=start_now, start_on_login=True)+ if not did_install or not gw._is_service_installed():+ gw.print_warning("Gateway service install did not complete. Retry: hermes gateway install")+ return+ record_service_choice("install")+ if start_now and backend != "windows":+ gw._setup_service_action("start", failed_label="Start failed", system=scope == "system")+ except (subprocess.CalledProcessError, SystemExit) as exc:+ gw.print_error(f"Install failed: {exc}")+ gw.print_info("You can try manually: hermes gateway install")diff --cc hermes_cli/kanban_db_dispatch.pyindex 4d328b6e4d3,f8e32c1c614..697bae8fe26--- a/hermes_cli/kanban_db_dispatch.py+++ b/hermes_cli/kanban_db_dispatch.py@@@ -625,13 -796,10 +802,13 @@@ def reconcile_orphaned_running(conn: sq"WHERE status = 'running' "" AND (claim_lock IS NULL OR claim_expires IS NULL)").fetchall()+ from hermes_cli.kanban_owner_recovery import owner_reclaim_pausedfor row in rows:+ if owner_reclaim_paused(conn, row["id"]):+ continuetid = row["id"]pid = row["worker_pid"]- if pid and _kb._pid_alive(pid):+ if pid and _worker_alive(pid, _kb._row_get(row, "worker_started_at")):# Never requeue beside a live process. Retry next tick._kb._log.debug("kanban reconcile: task %s has broken claim bookkeeping but "@@@ -759,12 -965,27 +974,31 @@@ class _DeadWorkerreturn "rate_limited" if self.rate_limited else "crashed"- def _classify_dead_worker(pid: int, claimer: Optional[str], exit_code=None) -> _DeadWorker:- """Map a dead worker's reaped exit status to its reclaim bookkeeping."""+ def _classify_dead_worker(- pid: int, claimer: Optional[str], *, task_id: Optional[str] = None, board: Optional[str] = None,++ pid: int, claimer: Optional[str], exit_code=None, *, task_id: Optional[str] = None,++ board: Optional[str] = None,+ ) -> _DeadWorker:+ """Map a dead worker's reaped exit status to its reclaim bookkeeping.++ A clean exit or a crash carries the worker's own last output (``worker_output``+ in the event payload, appended to the error text) so the board and the retry+ worker see WHY instead of a bare label; a rate-limited requeue does not need it.+ """- dead = _classify_dead_worker_exit(pid, claimer)++ dead = _classify_dead_worker_exit(pid, claimer, exit_code)+ if task_id and not dead.rate_limited:+ worker_output = _worker_final_output(task_id, board=board)+ if worker_output:+ dead.error_text += f" Worker's last output: {worker_output!r}"+ dead.event_payload["worker_output"] = worker_output+ return dead++-def _classify_dead_worker_exit(pid: int, claimer: Optional[str]) -> _DeadWorker:++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."""kind, code = _classify_worker_exit(pid)+ 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")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@@@ -840,15 -1058,7 +1074,15 @@@ def _reclaim_dead_workers(conn: sqlite3continuepid = int(row["worker_pid"])- dead = _classify_dead_worker(pid, row["claim_lock"], task_id=row["id"], board=board)+ # Managed interpreters are children of the authority, not this dispatcher.+ # Their exact-run result survives a dispatcher restart and cannot be reaped here.+ run = conn.execute(+ "SELECT e.payload FROM task_events e JOIN tasks t ON t.current_run_id=e.run_id "+ "WHERE t.id=? AND e.task_id=t.id AND e.kind='worker_result' ORDER BY e.id DESC LIMIT 1",+ (row["id"],)).fetchone()+ result = _kb._json_dict(run["payload"]) if run else {}+ exit_code = result.get("exit_code") if result.get("claim_lock") == row["claim_lock"] and result.get("pid") == pid else None- dead = _classify_dead_worker(pid, row["claim_lock"], exit_code)++ dead = _classify_dead_worker(pid, row["claim_lock"], exit_code, task_id=row["id"], board=board)retry_status = _kb._retry_status_for_run(conn, row["id"])dead.event_payload["retry_status"] = retry_statuscur = conn.execute(@@@ -1120,19 -1330,21 +1354,26 @@@ def _record_task_failurereturn True-def _set_worker_pid(conn: sqlite3.Connection, task_id: str, pid: int) -> None:- """Record the spawned child's pid + its restart-stable fingerprint (``_process_fingerprint``), and- emit a ``spawned`` event carrying them. The fingerprint is what lets every later liveness/kill- decision tell OUR worker from a process that recycled the PID after a reboot. A failed capture is- persisted as ``UNVERIFIED_WORKER_FINGERPRINT``, never NULL: NULL is the legacy pre-fingerprint row- whose bare-PID kill authority a new spawn must not inherit."""+def _set_worker_pid(conn: sqlite3.Connection, task_id: str, pid: int, *, run_id=None, claim_lock=None) -> None:- """Publish the launcher only while this claim has no executing worker yet."""++ """Publish the launcher only while this claim has no executing worker yet, together with its++ restart-stable fingerprint (``_process_fingerprint``); the ``spawned`` event carries both. The++ fingerprint is what lets every later liveness/kill decision tell OUR worker from a process that++ recycled the PID after a reboot. A failed capture is persisted as ``UNVERIFIED_WORKER_FINGERPRINT``,++ never NULL: NULL is the legacy pre-fingerprint row whose bare-PID kill authority a new spawn must++ not inherit."""+ started_at = _process_fingerprint(int(pid)) or UNVERIFIED_WORKER_FINGERPRINTwith _kb.write_txn(conn):- conn.execute("UPDATE tasks SET worker_pid = ?, worker_started_at = ? WHERE id = ?",- (int(pid), started_at, task_id))- run_id = _kb._current_run_id(conn, task_id)- if run_id is not None:+ if run_id is None:+ run_id = _kb._current_run_id(conn, task_id)+ cur = conn.execute(- "UPDATE tasks SET worker_pid = ? WHERE id = ? AND status = 'running' "++ "UPDATE tasks SET worker_pid = ?, worker_started_at = ? WHERE id = ? AND status = 'running' "+ "AND current_run_id IS ? AND worker_pid IS NULL "+ "AND (? IS NULL OR claim_lock = ?)",- (int(pid), task_id, run_id, claim_lock, claim_lock))++ (int(pid), started_at, task_id, run_id, claim_lock, claim_lock))+ if cur.rowcount:- conn.execute("UPDATE task_runs SET worker_pid = ? WHERE id = ?", (int(pid), run_id))- _kb._append_event(conn, task_id, "spawned", {"pid": int(pid)}, run_id=run_id)+ conn.execute("UPDATE task_runs SET worker_pid = ?, worker_started_at = ? WHERE id = ?",+ (int(pid), started_at, run_id))+ _kb._append_event(conn, task_id, "spawned", {"pid": int(pid), "started_at": started_at}, run_id=run_id)def _clear_failure_counter(conn: sqlite3.Connection, task_id: str) -> None:@@@ -2053,6 -2326,50 +2355,8 @@@ def _worker_terminal_timeout_envreturn str(desired)-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 agent.secret_scope import (- build_profile_secret_scope, is_multiplex_active, reset_secret_scope, set_secret_scope)- from hermes_constants import reset_hermes_home_override, set_hermes_home_override- from hermes_cli.config import load_config- from hermes_cli.tools_config import _get_platform_tools-- token = set_hermes_home_override(hermes_home)- # Toolset availability probes read credentials (``get_secret``); under multiplex an- # unscoped read raises and the pin was silently dropped for every worker.- secret_token = (- set_secret_scope(build_profile_secret_scope(Path(hermes_home)))- if is_multiplex_active() else None)- try:- cfg = load_config()- toolsets = sorted(_get_platform_tools(cfg, "cli"))- finally:- if secret_token is not None:- reset_secret_scope(secret_token)- reset_hermes_home_override(token)- 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/profiles.pyindex 6ad57afb866,a3ce6412c45..926fdd9d84c--- a/hermes_cli/profiles.py+++ b/hermes_cli/profiles.py@@@ -808,29 -865,16 +865,35 @@@ 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+ 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")++- def _bootstrap_profile_dir(profile_dir: Path, source_dir: Optional[Path]) -> None:+ 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 cloneconfig files, installed skills (the dashboard's "clone from default" must keep bundled- AND user-installed skills), and memory/identity files from *source_dir*."""+ AND user-installed skills), and memory/identity files from *source_dir*.++ ``sync_imports`` also copies the source's ``import-sync.json`` (the ``hermes import-agent``+ manifest) so the clone stays registered against the same external Claude Code / Codex trees+ and ``hermes -p <clone> import-agent --sync`` keeps pulling from them. The link is to the+ external tree, never to the source profile: both profiles stay independent islands."""profile_dir.mkdir(parents=True, exist_ok=True)for subdir in _PROFILE_DIRS:(profile_dir / subdir).mkdir(parents=True, exist_ok=True)@@@ -839,12 -883,17 +902,18 @@@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)+ shutil.copytree(+ source_skills, profile_dir / "skills", symlinks=True, dirs_exist_ok=True,+ ignore=_non_exportable_entries,+ )for relpath in _CLONE_SUBDIR_FILES:_clone_file(source_dir, profile_dir, relpath)+ if sync_imports:+ from hermes_cli.agent_import_sync import SYNC_MANIFEST_NAME # lazy: keeps yaml/utils off the hot startup path+ _clone_file(source_dir, profile_dir, SYNC_MANIFEST_NAME)def create_profile(diff --cc hermes_cli/runtime_readiness.pyindex 4277757e220,00000000000..715496c4521mode 100644,000000..100644--- a/hermes_cli/runtime_readiness.py+++ b/hermes_cli/runtime_readiness.py@@@ -1,24 -1,0 +1,39 @@@- """Provider readiness shared by authenticated frontend transports."""++"""Provider readiness probe shared by ``setup.runtime_check`` (TUI gateway) and the session authority."""++- def check_runtime_readiness(requested=None, *, strict_profile_scope=False):++def check_runtime_readiness(requested=None, *, strict_profile_scope=False, resolve=None):++ """ok/error verdict for the runtime a session would be built with.++++ ``resolve`` is an optional ``() -> (model, runtime)`` pair supplied by the caller that owns the++ session builder: without ``provider`` the TUI probe must run the SAME resolver as session creation++ (startup model + provider pin, then the configured fallback chain) — a probe that ignores the chain++ shows onboarding for a backend whose sessions build fine (#111775). An explicit ``requested``++ provider stays a strict single-provider check so onboarding can verify the provider just connected++ without another provider's fallback masking a failed connection. Both branches report the model.++ """+ from hermes_cli.runtime_provider import resolve_runtime_provider+ from hermes_cli.auth import has_usable_secret+ from hermes_cli.main import _has_any_provider_configured+- runtime = resolve_runtime_provider(requested=requested)++ if resolve is not None:++ model, runtime = resolve()++ else:++ runtime = resolve_runtime_provider(requested=requested)++ model = runtime.get('model')+ configured = bool(_has_any_provider_configured(strict_profile_scope=strict_profile_scope))+ provider = runtime.get('provider') or 'provider'+ source = str(runtime.get('source') or '')+ result = {'ok': True, 'provider': runtime.get('provider'),- 'model': runtime.get('model'), 'source': runtime.get('source')}++ 'model': model, 'source': runtime.get('source')}+ if not configured and provider == 'bedrock' and source in {'iam-role', 'aws-sdk-default-chain'}:+ return {**result, 'ok': False, 'error': 'No Hermes provider is configured.'}+ api_key = runtime.get('api_key')+ api_key_text = '' if callable(api_key) else str(api_key or '').strip()+ if not (callable(api_key) or api_key_text in {'aws-sdk', 'no-key-required'}+ or has_usable_secret(api_key_text) or bool(runtime.get('command'))):+ return {**result, 'ok': False, 'error': f'No usable credentials found for {provider}.'}+ from hermes_cli.anon_auth import route_is_welcome_host++ # free_tier is keyed on the SELECTED route (the welcome host serves only nous/welcome), not++ # on profile state: a paid Nous key beside a free-tier identity must not read as free.+ result['free_tier'] = provider == 'nous' and route_is_welcome_host(runtime.get('base_url'))+ return resultdiff --cc hermes_cli/sessions_cmd.pyindex 85d1d93b494,25e5d4f5db8..95bf874327f--- a/hermes_cli/sessions_cmd.py+++ b/hermes_cli/sessions_cmd.py@@@ -968,30 -990,17 +990,28 @@@ def cmd_sessions(args, sessions_parser=pre = _PRE_DB_HANDLERS.get(action)if pre is not None:return pre(args)- observational = action in _OBSERVATIONAL_DB_ACTIONS- from hermes_state import SessionDB, _default_db_path++ from hermes_state import SessionDB++ from hermes_constants import get_hermes_home++ # Verified deletion is an explicit mutation, not a read-only export.++ deleting_export = (++ action == "export" and getattr(args, "delete_after_verified", False)++ and getattr(args, "yes", False) and getattr(args, "session_id", None)++ and getattr(args, "format", None) in ("md", "qmd")++ )++ observational = action in _OBSERVATIONAL_DB_ACTIONS or (action == "export" and not deleting_export)++ # A served-profile process has no single default home: pass the store path explicitly.++ path = get_hermes_home() / "state.db"++ if observational and not path.exists():++ return _print_empty_store(action, args)try:- from hermes_state import SessionDB- from hermes_constants import get_hermes_home- path = get_hermes_home() / "state.db"- empty_messages = {- "export": "No sessions found.",- "list": "No sessions found.",- "stats": "Total sessions: 0\nTotal messages: 0",- "pinned": "[]" if getattr(args, "json", False) else- "No pinned sessions. Pin one with: hermes sessions pin <session_id>",- }- # Verified deletion is an explicit mutation, not a read-only export.- deleting_export = (- action == "export" and getattr(args, "delete_after_verified", False)- and getattr(args, "yes", False) and getattr(args, "session_id", None)- and getattr(args, "format", None) in ("md", "qmd")- )- read_only = action in empty_messages and not deleting_export- if action in empty_messages and not path.exists():- print(empty_messages[action])- return- db = SessionDB(db_path=path, read_only=read_only) if action in empty_messages else SessionDB()- db = SessionDB(read_only=observational)++ db = SessionDB(db_path=path, read_only=observational)except Exception as e:- print(f"Error: Could not open session database: {e}")+ # mode=ro cannot create the store; a reader on a fresh profile reports empty rather than failing.- if observational and not _default_db_path().exists():++ if observational and not path.exists():+ return _print_empty_store(action, args)+ print("Could not open your session history database. "+ "Run: hermes sessions repair to fix it (a backup is made first).")+ print(f"Details: {e}")return 1try:handler = _DB_HANDLERS.get(action)diff --cc hermes_cli/update_cmd.pyindex e7171cc7092,3f777354c68..0a8e03e3544--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@@ -97,8 -97,9 +97,8 @@@ 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_PREFIXES,- _STALE_PURGE_PROTECTED, _UPDATE_RUNTIME_RELOAD_MODULES,- _PRE_UPDATE_SNAPSHOT_KEEP, _PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE,- _STALE_PURGE_PROTECTED,- _UPDATE_RUNTIME_RELOAD_MODULES, _clear_stale_sqlite_sidecars,++ _PRE_UPDATE_SNAPSHOT_KEEP, _PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE, _STALE_PURGE_PROTECTED,++ _UPDATE_RUNTIME_RELOAD_MODULES,_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 86050cc0bf7,b3c75071d24..3a0c85a1035--- a/hermes_cli/web_routers/sessions.py+++ b/hermes_cli/web_routers/sessions.py@@@ -574,14 -564,78 +574,73 @@@ async def get_session_messages"returned": len(projected_messages)}}+ def _timeline_session_id(db, session_id: str, owner: str) -> str:+ # Durable jump addresses are exact ids, never title/prefix guesses. A NULL+ # legacy owner belongs to this profile's store, just like /messages pages.+ def owned(sid):+ row = db._read_one("SELECT profile_name FROM sessions WHERE id = ?", (sid,))+ return row is not None and row["profile_name"] in (None, owner)++ if not owned(session_id):+ raise HTTPException(status_code=404, detail=_NOT_FOUND)+ sid = db.resolve_resume_session_id(session_id)+ if not owned(sid):+ raise HTTPException(status_code=404, detail=_NOT_FOUND)+ return sid+++ @manage_router.get("/api/sessions/{session_id}/timeline")+ async def get_session_timeline(+ session_id: str, profile: Optional[str] = None,+ limit: int = Query(500, ge=1, le=500), after_row_id: int = Query(0, ge=0),+ ):+ """Prompt metadata only, including compacted display history (never rewind rows).++ ``next_cursor`` is a stable logical first-row id; pass it as ``after_row_id``.+ Entry ``row_id`` addresses the current representative for /messages/around.+ """+ from hermes_state_timeline import get_session_timeline as read_timeline++ owner = _serving_profile(profile)++ def _read(db):+ sid = _timeline_session_id(db, session_id, owner)+ return {"session_id": sid, "profile": owner,+ **read_timeline(db, sid, limit=limit, after_row_id=after_row_id)}++ return await asyncio.to_thread(_with_db, profile, _read, read_only=True)+++ @manage_router.get("/api/sessions/{session_id}/messages/around")+ async def get_session_messages_around(+ session_id: str, row_id: int = Query(..., ge=1), profile: Optional[str] = None,+ limit: int = Query(120, ge=1, le=120),+ ):+ """Bounded display page starting at a timeline prompt; no intervening payloads."""+ from hermes_state_timeline import get_session_messages_around as read_around++ owner = _serving_profile(profile)++ def _read(db):+ sid = _timeline_session_id(db, session_id, owner)+ page = read_around(db, sid, row_id, limit=limit)+ if page is None:+ raise HTTPException(status_code=404, detail="Prompt not found")+ return {"session_id": sid, "profile": owner, **page}++ result = await asyncio.to_thread(_with_db, profile, _read, read_only=True)+ result["messages"] = _project_for_display(result["messages"])+ return result++@manage_router.delete("/api/sessions/{session_id}")-async def delete_session_endpoint(session_id: str, profile: Optional[str] = None):- def _delete(db):- # Already-absent is an idempotent success: the desktop optimistically- # removes the row and RESTORES it on any error, so a 404 resurrected- # ghost rows (transient empties racing the sidebar snapshot).- sid = _resolve_session_id(db, session_id)- if not sid:- return {"ok": True, "already_absent": True}- db.delete_session(sid)- return {"ok": True}-- return await asyncio.to_thread(_with_db, profile, _delete, read_only=False)+async def delete_session_endpoint(session_id: str, request: Request, profile: Optional[str] = None,+ request_id: Optional[str] = None, expected_revision: Optional[int] = None,+ expected_generation: Optional[int] = None):+ from hermes_cli.web_server_sessions import _mutate_session_request+ return await _mutate_session_request(request, profile, session_id,+ request_id=request_id, expected_revision=expected_revision,+ expected_generation=expected_generation, operation='delete', payload={})@manage_router.post("/api/sessions/owner-backfill")diff --cc hermes_state_runtime.pyindex fa42f0fd1c7,00000000000..d6c62ce8001mode 100644,000000..100644--- a/hermes_state_runtime.py+++ b/hermes_state_runtime.py@@@ -1,677 -1,0 +1,681 @@@+"""Canonical runtime transactions; callers authorize and resolve session identity.++No execution, transport, or authority objects live here. Every mutation uses the+SessionDB transaction owner, including its inode guard and SQLite retry policy.+"""+import json+import uuid++from gateway.session_admission import admission_fingerprint+++class RuntimeStoreError(ValueError):+ def __init__(self, reason: str):+ self.reason = reason+ super().__init__(reason)+++def _text(value):+ if not isinstance(value, str) or not value or len(value) > 1024:+ raise RuntimeStoreError('invalid_params')+ return value+++def _json(value):+ if not isinstance(value, dict):+ raise RuntimeStoreError('invalid_params')+ try:+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False)+ except (TypeError, ValueError, UnicodeError) as exc:+ raise RuntimeStoreError('invalid_params') from exc+++def _epoch(conn, epoch):+ row = conn.execute('SELECT epoch FROM runtime_epoch WHERE singleton=1').fetchone()+ if type(epoch) is not int or row is None or row[0] != epoch:+ raise RuntimeStoreError('stale_epoch')+++def _session(conn, session_id):+ row = conn.execute('SELECT * FROM sessions WHERE id=?', (session_id,)).fetchone()+ if row is None:+ raise RuntimeStoreError('not_found')+ return row+++def _admission(conn, admission_id):+ row = conn.execute('SELECT * FROM session_admissions WHERE admission_id=?', (admission_id,)).fetchone()+ if row is None:+ from hermes_state_terminal import terminal_admission+ row = terminal_admission(conn, admission_id)+ if row is None:+ raise RuntimeStoreError('not_found')+ return row+++def _retire_admission_workers(conn, row, owner_epoch):+ """Retire the worker rows this admission's generation owns on BOTH the logical+ FIFO owner and its current physical transcript (reset/compression move the private+ worker assignment to the child while target_session_id stays the logical ID)."""+ lineage = json.loads(row['lineage_json'])+ targets = list({row['target_session_id'], lineage[-1] if lineage else row['target_session_id']})+ conn.execute(f"UPDATE worker_executions SET status='terminal' WHERE session_id IN ({','.join('?' * len(targets))}) "+ "AND generation=? AND owner_epoch=?", (*targets, row['generation'], owner_epoch))+++def _row(row):+ if row is None:+ return None+ result = dict(row)+ result['payload'] = json.loads(result.pop('payload_json'))+ result.pop('payload_digest')+ result.pop('lineage_json')+ return result+++def begin_runtime_epoch(db, *, instance_id: str) -> int:+ """Caller MUST hold the profile ownership lock, not merely an endpoint ticket."""+ _text(instance_id)+ def write(conn):+ conn.execute('''INSERT INTO runtime_epoch(singleton,epoch,instance_id) VALUES(1,1,?)+ ON CONFLICT(singleton) DO UPDATE SET epoch=runtime_epoch.epoch+1, instance_id=excluded.instance_id''', (instance_id,))+ return conn.execute('SELECT epoch FROM runtime_epoch WHERE singleton=1').fetchone()[0]+ return db._execute_write(write)+++def admit_session_input(db, *, epoch: int, principal_id: str, session_id: str,+ request_id: str, payload: dict, intent: str = 'queue') -> dict:+ for value in (principal_id, session_id, request_id):+ _text(value)+ if intent not in ('queue', 'steer', 'redirect'):+ raise RuntimeStoreError('invalid_params')+ encoded = _json(payload)+ from hermes_state_terminal import retry_terminal_admission+ retired = retry_terminal_admission(db, epoch=epoch, principal_id=principal_id, session_id=session_id,+ request_id=request_id, payload=payload, intent=intent)+ if retired is not None:+ return retired+ digest = admission_fingerprint(canonical_target=session_id, payload={'input': json.loads(encoded), 'intent': intent})+ def write(conn):+ _epoch(conn, epoch)+ _session(conn, session_id)+ old = conn.execute('''SELECT * FROM session_admissions+ WHERE principal_id=? AND target_session_id=? AND request_id=?''', (principal_id, session_id, request_id)).fetchone()+ if old is not None:+ if old['payload_digest'] != digest:+ raise RuntimeStoreError('admission_conflict')+ return _row(old)+ admission_id = uuid.uuid4().hex+ conn.execute('''INSERT INTO session_admissions(admission_id,request_id,principal_id,+ target_session_id,lineage_json,payload_json,payload_digest,intent,status,owner_epoch)+ VALUES(?,?,?,?,?,?,?,?,'queued',?)''',+ (admission_id, request_id, principal_id, session_id, json.dumps([session_id]), encoded, digest, intent, epoch))+ return _row(_admission(conn, admission_id))+ return db._execute_write(write)+++def get_session_admission(db, *, admission_id: str) -> dict | None:+ with db._read_ctx() as conn:+ from hermes_state_terminal import terminal_admission+ row = conn.execute('SELECT * FROM session_admissions WHERE admission_id=?', (admission_id,)).fetchone()+ return _row(row if row is not None else terminal_admission(conn, admission_id))+++def list_session_admissions(db, *, session_id: str, pending_only: bool = True) -> list[dict]:+ with db._read_ctx() as conn:+ return [_row(row) for row in conn.execute('''SELECT * FROM session_admissions+ WHERE target_session_id=? AND (?=0 OR status!='terminal') ORDER BY seq''', (session_id, int(pending_only)))]+++def claim_session_input(db, *, epoch: int, session_id: str) -> dict | None:+ def write(conn):+ _epoch(conn, epoch)+ session = _session(conn, session_id)+ blocked = conn.execute("SELECT status FROM session_admissions WHERE target_session_id=? AND status IN ('started','unknown')", (session_id,)).fetchall()+ if any(row[0] == 'unknown' for row in blocked):+ raise RuntimeStoreError('unknown_execution')+ if conn.execute("SELECT 1 FROM worker_executions WHERE session_id=? AND status='unknown'", (session_id,)).fetchone():+ raise RuntimeStoreError('unknown_execution')+ if blocked or conn.execute("SELECT 1 FROM worker_executions WHERE session_id=? AND status IN ('registered','running')", (session_id,)).fetchone():+ return None+ row = conn.execute("SELECT * FROM session_admissions WHERE target_session_id=? AND status='queued' ORDER BY seq LIMIT 1", (session_id,)).fetchone()+ if row is None:+ return None+ generation = session['runtime_generation'] + 1+ conn.execute('UPDATE sessions SET runtime_generation=? WHERE id=?', (generation, session_id))+ changed = conn.execute("UPDATE session_admissions SET status='started',owner_epoch=?,generation=? WHERE admission_id=? AND status='queued'", (epoch, generation, row['admission_id']))+ if changed.rowcount != 1:+ raise RuntimeStoreError('stale_generation')+ return _row(_admission(conn, row['admission_id']))+ return db._execute_write(write)+++def settle_session_input(db, *, epoch: int, admission_id: str, generation: int, outcome: str,+ result: dict | None = None) -> dict:+ if outcome not in ('completed', 'interrupted', 'rejected', 'failed'):+ raise RuntimeStoreError('invalid_params')+ encoded = _json(result) if result is not None else None+ def write(conn):+ _epoch(conn, epoch)+ row = _admission(conn, admission_id)+ session = _session(conn, row['target_session_id'])+ if (row['status'] != 'started' or row['owner_epoch'] != epoch+ or type(generation) is not int or row['generation'] != generation+ or session['runtime_generation'] != generation):+ raise RuntimeStoreError('stale_generation')+ _retire_admission_workers(conn, row, epoch)+ if encoded is not None:+ from hermes_state_terminal import RESULT_PREFIX+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?) '+ 'ON CONFLICT(key) DO UPDATE SET value=excluded.value',+ (RESULT_PREFIX + admission_id, encoded))+ conn.execute("UPDATE session_admissions SET status='terminal',outcome=? WHERE admission_id=?", (outcome, admission_id))+ conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?', (row['target_session_id'],))+ return _row(_admission(conn, admission_id))+ return db._execute_write(write)+++def cancel_session_input(db, *, epoch: int, admission_id: str) -> dict:+ def write(conn):+ _epoch(conn, epoch)+ row = _admission(conn, admission_id)+ if row['status'] == 'unknown':+ raise RuntimeStoreError('unknown_execution')+ if row['status'] == 'started':+ raise RuntimeStoreError('stale_generation')+ if row['status'] == 'queued':+ conn.execute("UPDATE session_admissions SET status='terminal',outcome='cancelled' WHERE admission_id=?", (admission_id,))+ return _row(_admission(conn, admission_id))+ return db._execute_write(write)+++def recover_session_inputs(db, *, epoch: int) -> int:+ """Never replay started work. Live worker adoption is a separate explicit operation."""+ def write(conn):+ _epoch(conn, epoch)+ conn.execute("UPDATE worker_executions SET status='unknown' WHERE status IN ('registered','running') AND owner_epoch!=?", (epoch,))+ return conn.execute("UPDATE session_admissions SET status='unknown' WHERE status='started' AND owner_epoch!=?", (epoch,)).rowcount+ return db._execute_write(write)+++def mutate_runtime_session(db, *, epoch: int, principal_id: str, session_id: str,+ request_id: str, expected_revision: int,+ operation: str, payload: dict, expected_generation: int | None = None,+ _live_guard=None, _authorize_write=None, _prepare_only=False, _prepared=None) -> dict:+ """Commit a closed metadata edit and its retry receipt in the same transaction.++ Caller authorizes the principal and resolves the canonical session. These+ metadata edits do not stop execution. Existing direct writers must migrate+ before this seam can provide universal revision fencing.+ """+ for value in (principal_id, session_id, request_id):+ _text(value)+ if type(expected_revision) is not int or expected_revision < 0:+ raise RuntimeStoreError('invalid_params')+ from hermes_state_mutations import validate_action, apply_action+ validate_action(operation, payload)+ if expected_generation is not None and (type(expected_generation) is not int or expected_generation < 0):+ raise RuntimeStoreError('invalid_params')+ if operation in {'delete', 'rewind', 'reset', 'branch', 'model', 'compress'} and expected_generation is None:+ raise RuntimeStoreError('invalid_params')+ # Snapshot caller data before waiting for the writer lock.+ payload = json.loads(_json(payload))+ key = 'gateway.mutation.v1.' + admission_fingerprint(+ canonical_target=session_id, payload={'principal': principal_id, 'request': request_id})+ fingerprint = {'operation': operation, 'payload': payload, 'expected_revision': expected_revision}+ if expected_generation is not None:+ fingerprint['expected_generation'] = expected_generation+ digest = admission_fingerprint(canonical_target=session_id, payload=fingerprint)++ def write(conn):+ _epoch(conn, epoch)+ old = conn.execute('SELECT value FROM state_meta WHERE key=?', (key,)).fetchone()+ if old is not None:+ receipt = json.loads(old[0])+ if receipt['digest'] != digest:+ raise RuntimeStoreError('admission_conflict')+ return receipt['result']+ session = conn.execute('SELECT * FROM sessions WHERE id=?', (session_id,)).fetchone()+ if session is None and operation != 'import':+ raise RuntimeStoreError('not_found')+ revision = session['runtime_revision'] if session else 0+ if revision != expected_revision:+ raise RuntimeStoreError('revision_conflict')+ if expected_generation is not None and (session is None or session['runtime_generation'] != expected_generation):+ raise RuntimeStoreError('stale_generation')+ if _live_guard is not None:+ from hermes_state_mutation_guards import delete_targets+ targets = delete_targets(conn, session_id) if operation == 'delete' else [session_id]+ _live_guard(targets)+ if _authorize_write is not None:+ _authorize_write(conn)+ if _prepare_only:+ from hermes_state_mutation_prepared import local_snapshot+ return {'snapshot': local_snapshot(db, conn, session_id)}+ affected, projection = apply_action(db, conn, session_id, operation, payload, prepared=_prepared)+ conn.executemany('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?',+ [(target,) for target in affected])+ updated = conn.execute('SELECT * FROM sessions WHERE id=?', (session_id,)).fetchone()+ result = {'session_id': session_id, 'revision': updated['runtime_revision'] if updated else expected_revision + 1,+ 'operation': operation, **projection}+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)',+ (key, _json({'digest': digest, 'result': result})))+ return result+ return db._execute_write(write)+++_IMPORT_KEY = 'gateway.prompt_admissions_import.v1'+++def _canonical_chain(conn, session_id):+ # Same selector as SessionDB.get_compression_chain, on OUR transaction connection.+ from hermes_state_compression import _CHAIN_STEP_SQL+ _session(conn, session_id)+ chain = [session_id]+ for _ in range(100):+ child = conn.execute(_CHAIN_STEP_SQL, (chain[-1],)).fetchone()+ if child is None:+ return chain+ if child['id'] in chain:+ raise RuntimeStoreError('admission_conflict')+ chain.append(child['id'])+ raise RuntimeStoreError('admission_conflict')+++def _import_legacy_row(conn, row, epoch, principal_id):+ for field in ('admission_id', 'target_session_id', 'root'):+ _text(row[field])+ lineage = json.loads(row['lineage'])+ if not isinstance(lineage, list) or row['target_session_id'] not in lineage:+ raise RuntimeStoreError('invalid_params')+ payload = json.loads(row['payload'])+ encoded = _json(payload)+ intent = payload.get('intent', 'queue')+ intent = 'redirect' if intent == 'interrupt' else intent+ if intent not in ('queue', 'steer', 'redirect') or row['status'] not in ('queued', 'started', 'unknown', 'terminal'):+ raise RuntimeStoreError('invalid_params')+ chain = _canonical_chain(conn, row['target_session_id'])+ target = chain[-1]+ status = 'unknown' if row['status'] == 'started' else row['status']+ generation = row['generation']+ if generation is None and status == 'unknown':+ generation = _session(conn, target)['runtime_generation'] + 1+ if generation is not None and (type(generation) is not int or generation < 0):+ raise RuntimeStoreError('invalid_params')+ digest = admission_fingerprint(canonical_target=target, payload={'input': payload, 'intent': intent})+ conn.execute("""INSERT INTO session_admissions(admission_id,request_id,principal_id,+ target_session_id,lineage_json,payload_json,payload_digest,intent,status,outcome,owner_epoch,generation)+ VALUES(?,?,?,?,?,?,?,?,?,?,?,?)""", (row['admission_id'], row['admission_id'], principal_id,+ target, json.dumps(chain), encoded, digest, intent, status, row['outcome'], epoch, generation))+ if generation is not None:+ conn.execute('UPDATE sessions SET runtime_generation=MAX(runtime_generation,?) WHERE id=?', (generation, target))+++def import_legacy_session_admissions(db, *, epoch: int, source_path, principal_id: str,+ writers_drained: bool) -> int:+ """Import a frozen legacy snapshot; original file remains rollback evidence.++ The caller proves the old writers are drained before invoking this function.+ Fingerprinting uses SQL snapshot data, never a raw open/close on a live inode.+ """+ from contextlib import closing+ from pathlib import Path+ import hashlib+ import sqlite3+ from hermes_cli.sqlite_safe_read import connect_tracked+ if writers_drained is not True:+ raise RuntimeStoreError('invalid_params')+ _text(principal_id)+ source_path = Path(source_path).resolve(strict=True)+ with closing(connect_tracked(source_path.as_uri() + '?mode=ro', uri=True)) as source:+ source.row_factory = sqlite3.Row+ source.execute('PRAGMA query_only=ON')+ source.execute('BEGIN')+ rows = [dict(r) for r in source.execute('SELECT * FROM admissions ORDER BY seq')]+ executions = []+ if source.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='executions'").fetchone():+ executions = [dict(r) for r in source.execute('SELECT * FROM executions ORDER BY root')]+ fingerprint = hashlib.sha256(_json({'rows': rows, 'executions': executions}).encode('utf-8')).hexdigest()+ marker = _json({'source': str(source_path), 'fingerprint': fingerprint, 'imported_id_count': len(rows), 'principal_id': principal_id})+ def write(conn):+ _epoch(conn, epoch)+ old = conn.execute('SELECT value FROM state_meta WHERE key=?', (_IMPORT_KEY,)).fetchone()+ if old is not None:+ if old[0] != marker:+ raise RuntimeStoreError('admission_conflict')+ return 0+ for execution in executions:+ generation = execution['generation']+ if type(generation) is not int or generation < 0:+ raise RuntimeStoreError('invalid_params')+ target = _canonical_chain(conn, _text(execution['root']))[-1]+ conn.execute('UPDATE sessions SET runtime_generation=MAX(runtime_generation,?) WHERE id=?', (generation, target))+ for row in rows:+ _import_legacy_row(conn, row, epoch, principal_id)+ conn.execute('INSERT INTO state_meta(key,value) VALUES(?,?)', (_IMPORT_KEY, marker))+ return len(rows)+ return db._execute_write(write)+++def resolve_unknown_session_input(db, *, epoch: int, admission_id: str, generation: int) -> dict:+ """Explicit operator acknowledgement; resolves uncertainty, never requeues it."""+ def write(conn):+ _epoch(conn, epoch)+ row = _admission(conn, admission_id)+ if type(generation) is not int or row['status'] != 'unknown' or row['generation'] != generation:+ raise RuntimeStoreError('stale_generation')+ _retire_admission_workers(conn, row, row['owner_epoch'])+ conn.execute("UPDATE session_admissions SET status='terminal',outcome='interrupted' WHERE admission_id=?", (admission_id,))+ conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?', (row['target_session_id'],))+ return _row(_admission(conn, admission_id))+ return db._execute_write(write)+++def _worker_public(row):+ result = dict(row)+ result.pop('adoption_digest')+ return result+++def _worker_assignment(conn, execution_id, session_id, generation):+ row = conn.execute('SELECT * FROM worker_executions WHERE execution_id=?', (execution_id,)).fetchone()+ if row is None:+ raise RuntimeStoreError('not_found')+ if row['session_id'] != session_id:+ raise RuntimeStoreError('permission_denied')+ if (type(generation) is not int or row['generation'] != generation+ or _session(conn, session_id)['runtime_generation'] != generation):+ raise RuntimeStoreError('stale_generation')+ return row+++def _linked_worker_admission(conn, session_id, generation, owner_epoch, statuses):+ placeholders = ','.join('?' for _ in statuses)+ rows = conn.execute(f"""SELECT * FROM session_admissions+ WHERE generation=? AND owner_epoch=? AND status IN ({placeholders})+ AND (target_session_id=? OR EXISTS (+ SELECT 1 FROM json_each(session_admissions.lineage_json) WHERE value=?+ )) ORDER BY seq""",+ (generation, owner_epoch, *statuses, session_id, session_id)).fetchall()+ if len(rows) > 1:+ raise RuntimeStoreError('admission_conflict')+ return rows[0] if rows else None+++def _secret_digest(secret):+ import hashlib+ _text(secret)+ return hashlib.sha256(secret.encode('utf-8')).hexdigest()+++def register_worker_execution(db, *, epoch: int, execution_id: str, session_id: str,+ generation: int, kind: str, adoption_secret: str, require_idle: bool = False) -> dict:+ for value in (execution_id, session_id):+ _text(value)+ if kind not in ('cron', 'child', 'compute', 'kanban'):+ raise RuntimeStoreError('invalid_params')+ digest = _secret_digest(adoption_secret)+ def write(conn):+ _epoch(conn, epoch)+ session = _session(conn, session_id)+ if type(generation) is not int or session['runtime_generation'] != generation:+ raise RuntimeStoreError('stale_generation')+ old = conn.execute('SELECT * FROM worker_executions WHERE execution_id=?', (execution_id,)).fetchone()+ if old is not None:+ if (old['session_id'], old['generation'], old['kind'], old['owner_epoch'], old['adoption_digest']) != (session_id, generation, kind, epoch, digest):+ raise RuntimeStoreError('admission_conflict')+ return _worker_public(old)+ if require_idle and conn.execute("SELECT 1 FROM session_admissions WHERE target_session_id=? AND status!='terminal'", (session_id,)).fetchone():+ raise RuntimeStoreError('stale_generation')+ if conn.execute("SELECT 1 FROM worker_executions WHERE session_id=? AND status!='terminal'", (session_id,)).fetchone():+ raise RuntimeStoreError('stale_generation')+ if conn.execute("SELECT 1 FROM session_admissions WHERE target_session_id=? AND status='unknown'", (session_id,)).fetchone():+ raise RuntimeStoreError('unknown_execution')+ conn.execute("""INSERT INTO worker_executions(execution_id,session_id,kind,owner_epoch,generation,status,adoption_digest)+ VALUES(?,?,?,?,?,'registered',?)""", (execution_id, session_id, kind, epoch, generation, digest))+ return _worker_public(_worker_assignment(conn, execution_id, session_id, generation))+ return db._execute_write(write)+++def adopt_worker_execution(db, *, epoch: int, execution_id: str, session_id: str,+ generation: int, adoption_secret: str) -> dict:+ """Authority first verifies the original producer claim and live worker proof."""+ import hmac+ digest = _secret_digest(adoption_secret)+ def write(conn):+ _epoch(conn, epoch)+ row = _worker_assignment(conn, execution_id, session_id, generation)+ if row['status'] == 'terminal':+ raise RuntimeStoreError('stale_generation')+ if not hmac.compare_digest(row['adoption_digest'], digest):+ raise RuntimeStoreError('permission_denied')+ linked = _linked_worker_admission(+ conn, session_id, generation, row['owner_epoch'], ('started', 'unknown'))+ if linked is not None:+ changed = conn.execute("""UPDATE session_admissions SET owner_epoch=?,status='started'+ WHERE admission_id=? AND generation=? AND owner_epoch=?+ AND status IN ('started','unknown')""",+ (epoch, linked['admission_id'], generation, row['owner_epoch']))+ if changed.rowcount != 1:+ raise RuntimeStoreError('stale_generation')+ changed = conn.execute(+ "UPDATE worker_executions SET owner_epoch=?,status='running' WHERE execution_id=?",+ (epoch, execution_id))+ if changed.rowcount != 1:+ raise RuntimeStoreError('stale_generation')+ return _worker_public(_worker_assignment(conn, execution_id, session_id, generation))+ return db._execute_write(write)+++def persist_worker_message(db, *, epoch: int, execution_id: str, session_id: str,+ generation: int, sequence: int, role: str, content: str) -> dict:+ """Typed text append primitive, NOT a general remote SessionDB implementation.++ Structured tools/reasoning/usage/compression require their own typed operations.+ No caller-supplied callable can commit inside this transaction.+ """+ import time+ if type(sequence) is not int or sequence < 1 or role not in ('user', 'assistant', 'system') or not isinstance(content, str):+ raise RuntimeStoreError('invalid_params')+ digest = admission_fingerprint(canonical_target=session_id, payload={'operation': 'append_text', 'role': role, 'content': content})+ def write(conn):+ _epoch(conn, epoch)+ row = _worker_assignment(conn, execution_id, session_id, generation)+ if row['owner_epoch'] != epoch:+ raise RuntimeStoreError('stale_epoch')+ old = conn.execute('SELECT * FROM worker_receipts WHERE execution_id=? AND sequence=?', (execution_id, sequence)).fetchone()+ if old is not None:+ if old['payload_digest'] != digest:+ raise RuntimeStoreError('admission_conflict')+ return json.loads(old['result_json'])+ if row['status'] == 'terminal':+ raise RuntimeStoreError('stale_generation')+ if sequence != row['last_sequence'] + 1:+ raise RuntimeStoreError('invalid_params')+ db._check_transcript_write_guards(conn, session_id, None)+ now = time.time()+ message = conn.execute('INSERT INTO messages(session_id,role,content,timestamp) VALUES(?,?,?,?)', (session_id, role, db._encode_content(content), now))+ conn.execute('UPDATE sessions SET message_count=message_count+1,last_activity_at=?,runtime_revision=runtime_revision+1 WHERE id=?', (now, session_id))+ result = {'message_id': message.lastrowid}+ conn.execute('INSERT INTO worker_receipts(execution_id,sequence,payload_digest,result_json) VALUES(?,?,?,?)', (execution_id, sequence, digest, json.dumps(result, ensure_ascii=True, allow_nan=False)))+ conn.execute("UPDATE worker_executions SET last_sequence=?,status='running' WHERE execution_id=?", (sequence, execution_id))+ return result+ return db._execute_write(write)+++++_MESSAGE_FIELDS = frozenset({+ 'role', 'content', 'tool_name', 'tool_calls', 'tool_call_id', 'token_count',+ 'finish_reason', 'reasoning', 'reasoning_content', 'reasoning_details',+ 'codex_reasoning_items', 'codex_message_items', 'platform_message_id', 'message_id',+ 'observed', 'effect_disposition', '_compressed_summary', 'timestamp', 'api_content',+ 'display_kind', 'display_metadata', '_row_id', '_canonical_content',+})+++def _worker_append(db, conn, session_id, payload):+ if set(payload) - {'messages', 'turn_lease_holder'} or 'messages' not in payload:+ raise RuntimeStoreError('invalid_params')+ messages = payload['messages']+ if not isinstance(messages, list) or len(messages) > 1000:+ raise RuntimeStoreError('invalid_params')+ for msg in messages:+ if (not isinstance(msg, dict) or set(msg) - _MESSAGE_FIELDS+ or msg.get('role') not in ('user', 'assistant', 'system', 'tool')):+ raise RuntimeStoreError('invalid_params')+ # Existing row annotations can adopt only rows in THIS transcript.+ if '_row_id' in msg and not conn.execute(+ 'SELECT 1 FROM messages WHERE id=? AND session_id=?',+ (msg['_row_id'], session_id)).fetchone():+ raise RuntimeStoreError('permission_denied')+ holder = payload.get('turn_lease_holder')+ if holder is not None:+ _text(holder)+ count = db._append_messages_in_transaction(conn, session_id, messages, turn_lease_holder=holder)+ return {'count': count, 'annotations': [+ {key: msg[key] for key in ('_row_id', '_canonical_content') if key in msg} for msg in messages]}+++def _worker_turn(db, conn, session_id, payload, operation):+ import time+ from hermes_state_compression import _claim_lease_row+ from hermes_state import _compression_lock_holder_process_is_dead+ allowed = {'holder'} if operation == 'turn.release' else {'holder', 'ttl_seconds'}+ if set(payload) != allowed:+ raise RuntimeStoreError('invalid_params')+ holder = _text(payload['holder'])+ ttl = payload.get('ttl_seconds', 300)+ if type(ttl) not in (float, int) or not 0.1 <= ttl <= 3600:+ raise RuntimeStoreError('invalid_params')+ key = db._session_turn_lease_key_on_conn(conn, session_id)+ now = time.time()+ if operation == 'turn.acquire':+ value = _claim_lease_row(conn, 'session_turn_leases', 'conversation_id', key,+ holder, now, now + ttl,+ lambda h, e: float(e) <= now or _compression_lock_holder_process_is_dead(h))[0]+ elif operation == 'turn.renew':+ value = conn.execute('UPDATE session_turn_leases SET expires_at=? WHERE conversation_id=? AND holder=?',+ (now + ttl, key, holder)).rowcount > 0+ else:+ conn.execute('DELETE FROM session_turn_leases WHERE conversation_id=? AND holder=?', (key, holder))+ value = None+ return {'value': value}+++def _worker_usage(db, conn, session_id, payload, *, auxiliary=False):+ from hermes_state_usage import _MODEL_USAGE_FIELDS, _TOKEN_COUNTERS++ if not auxiliary:++ # ``source`` feeds the legacy path's row-existence guard (#111999); an authority-owned++ # session row was minted with its real surface at admission, so nothing to repair here.++ payload = {k: v for k, v in payload.items() if k != 'source'}+ allowed = (_MODEL_USAGE_FIELDS - {'billing_mode', 'actual_cost_usd', 'cost_status', 'cost_source'} | {'task'}) if auxiliary else (_MODEL_USAGE_FIELDS | {'pricing_version', 'absolute'})+ if set(payload) - allowed:+ raise RuntimeStoreError('invalid_params')+ for key, value in payload.items():+ if key in (*_TOKEN_COUNTERS, 'api_call_count'):+ valid = type(value) is int and 0 <= value <= 2**53+ elif key in ('estimated_cost_usd', 'actual_cost_usd'):+ valid = value is None or (type(value) in (int, float) and 0 <= value <= 1e12)+ elif key == 'absolute':+ valid = type(value) is bool+ else:+ valid = value is None or (isinstance(value, str) and len(value) <= 4096)+ if not valid:+ raise RuntimeStoreError('invalid_params')+ if auxiliary:+ if not payload.get('task'):+ raise RuntimeStoreError('invalid_params')+ db._record_model_usage(conn, session_id, **({'api_call_count': 1} | payload))+ else:+ db._update_token_counts_in_transaction(conn, session_id, **payload)+ return {'value': None}+++def _worker_finish(db, conn, session_id, payload):+ if payload:+ raise RuntimeStoreError('invalid_params')+ return {'status': 'terminal'}+++def mutate_worker_execution(db, *, epoch, execution_id, session_id, generation,+ sequence, operation, payload):+ """One closed durable mutation and receipt; never call a self-committing API here."""+ from hermes_state_worker_context import worker_context, worker_prompt, worker_sidecars, worker_tool_names+ from hermes_state_worker_compression import WORKER_COMPRESSION_HANDLERS, worker_receipt_assignment+ from hermes_state_worker_lifecycle import WORKER_LIFECYCLE_HANDLERS+ handlers = {+ **WORKER_LIFECYCLE_HANDLERS,+ **WORKER_COMPRESSION_HANDLERS,+ 'session.context': worker_context,+ 'session.prompt': worker_prompt,+ 'session.sidecars': worker_sidecars,+ 'session.tools': worker_tool_names,+ 'transcript.append': _worker_append,+ 'execution.finish': _worker_finish,+ 'usage.main': _worker_usage,+ 'usage.auxiliary': lambda db, conn, sid, p: _worker_usage(db, conn, sid, p, auxiliary=True),+ **{name: (lambda db, conn, sid, p, op=name: _worker_turn(db, conn, sid, p, op))+ for name in ('turn.acquire', 'turn.renew', 'turn.release')},+ }+ if type(sequence) is not int or sequence < 1 or not isinstance(operation, str) or operation not in handlers:+ raise RuntimeStoreError('invalid_params')+ encoded = _json(payload)+ if len(encoded.encode('utf-8', errors='surrogatepass')) > 4 * 1024 * 1024:+ raise RuntimeStoreError('invalid_params')+ digest = admission_fingerprint(canonical_target=session_id,+ payload={'operation': operation, 'payload': json.loads(encoded)})+ def write(conn):+ _epoch(conn, epoch)+ row = worker_receipt_assignment(conn, execution_id, session_id, generation, sequence, digest)+ if row['owner_epoch'] != epoch:+ raise RuntimeStoreError('stale_epoch')+ old = conn.execute('SELECT * FROM worker_receipts WHERE execution_id=? AND sequence=?',+ (execution_id, sequence)).fetchone()+ if old is not None:+ if old['payload_digest'] != digest:+ raise RuntimeStoreError('admission_conflict')+ return json.loads(old['result_json'])+ if row['status'] not in ('registered', 'running'):+ raise RuntimeStoreError('stale_generation')+ if sequence != row['last_sequence'] + 1:+ raise RuntimeStoreError('invalid_params')+ # Each SQLite retry gets fresh rows; rolled-back annotations must not escape.+ result = handlers[operation](db, conn, session_id, json.loads(encoded))+ conn.execute('INSERT INTO worker_receipts(execution_id,sequence,payload_digest,result_json) VALUES(?,?,?,?)',+ (execution_id, sequence, digest, json.dumps(result, ensure_ascii=True, allow_nan=False)))+ conn.execute("UPDATE worker_executions SET last_sequence=?,status=? WHERE execution_id=?",+ (sequence, 'terminal' if operation == 'execution.finish' else 'running', execution_id))+ conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?', (session_id,))+ return result+ return db._execute_write(write, patience_s=db._TRANSCRIPT_WRITE_PATIENCE_S)+++def finish_worker_execution(db, *, epoch: int, execution_id: str, session_id: str,+ generation: int) -> dict:+ def write(conn):+ _epoch(conn, epoch)+ row = _worker_assignment(conn, execution_id, session_id, generation)+ if row['owner_epoch'] != epoch:+ raise RuntimeStoreError('stale_epoch')+ if row['status'] == 'terminal':+ return _worker_public(row)+ linked = _linked_worker_admission(conn, session_id, generation, epoch, ('started',))+ changed = conn.execute(+ "UPDATE worker_executions SET status='terminal' WHERE execution_id=? AND status!='terminal'",+ (execution_id,))+ if changed.rowcount != 1:+ raise RuntimeStoreError('stale_generation')+ if linked is not None:+ changed = conn.execute("""UPDATE session_admissions+ SET status='terminal',outcome='completed'+ WHERE admission_id=? AND status='started' AND owner_epoch=? AND generation=?""",+ (linked['admission_id'], epoch, generation))+ if changed.rowcount != 1:+ raise RuntimeStoreError('stale_generation')+ conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?',+ (linked['target_session_id'],))+ result = _worker_public(row)+ result['status'] = 'terminal'+ return result+ return db._execute_write(write)diff --cc hermes_state_titles.pyindex 4ed2fc944a7,4c49aaad8cd..e1997079876--- a/hermes_state_titles.py+++ b/hermes_state_titles.py@@@ -81,46 -75,56 +81,57 @@@ class SessionTitlesMixintitle = self.sanitize_title(title)is_user = source == self.TITLE_SOURCE_USERnew_rank = self._title_rank(source) if not is_user else None+ affected = []- def _do(conn):- current = conn.execute(- "SELECT title, title_source, hidden FROM sessions WHERE id = ?", (session_id,),+ current = conn.execute(+ "SELECT title, title_source, hidden FROM sessions WHERE id = ?", (session_id,),+ ).fetchone()+ if current is None:+ return []+ # The canonical Bot Chat's NAME is its identity (Bot Mode resolves it by+ # exact-title lookup on every open), so a rename orphans the conversation. Hidden+ # is the discriminator: canonical chats are born hidden; a visible session merely+ # named "Bot Chat" stays renameable. Provenance-blind.+ if ((current["title"] or "") == self.CANONICAL_BOT_CHAT_TITLE and bool(current["hidden"])+ and title != self.CANONICAL_BOT_CHAT_TITLE):+ if is_user:+ raise ValueError("This is the bot's canonical Bot Chat — its name is its "+ "identity, and renaming it would orphan the conversation. "+ "To start fresh, create a new bot instead.")+ return []+ if not is_user and current["title"] is not None and self._title_rank(current["title_source"]) >= new_rank:+ return []+ if title:+ conflict = conn.execute(- "SELECT id FROM sessions WHERE title = ? AND id != ?", (title, session_id),++ "SELECT id, archived, hidden FROM sessions WHERE title = ? AND id != ?", (title, session_id),).fetchone()- if current is None:- return 0- # The canonical Bot Chat's NAME is its identity (Bot Mode resolves it by- # exact-title lookup on every open), so a rename orphans the conversation. Hidden- # is the discriminator: canonical chats are born hidden; a visible session merely- # named "Bot Chat" stays renameable. Provenance-blind.- if ((current["title"] or "") == self.CANONICAL_BOT_CHAT_TITLE and bool(current["hidden"])- and title != self.CANONICAL_BOT_CHAT_TITLE):- if is_user:- raise ValueError("This is the bot's canonical Bot Chat — its name is its "- "identity, and renaming it would orphan the conversation. "- "To start fresh, create a new bot instead.")- return 0- if not is_user and current["title"] is not None and self._title_rank(current["title_source"]) >= new_rank:- return 0- if title:- conflict = conn.execute(- "SELECT id, archived, hidden FROM sessions WHERE title = ? AND id != ?", (title, session_id),- ).fetchone()- if conflict:- conflict_id = conflict["id"]- # A hidden compressed ancestor holding the title cannot be freed by the- # user, so transfer it onto the tip (uniqueness + lineage kept).- if self._is_compression_ancestor(conn, ancestor_id=conflict_id, descendant_id=session_id):- conn.execute("UPDATE sessions SET title = NULL WHERE id = ?", (conflict_id,))- # A deliberately archived hidden Bot Chat is a retired registry- # entry, not a live identity. Retire its name in the same title- # transaction so a replacement can become the sole canonical row;- # the old session remains archived and otherwise untouched.- elif (title == self.CANONICAL_BOT_CHAT_TITLE and bool(conflict["archived"])- and bool(conflict["hidden"])):- conn.execute(- "UPDATE sessions SET title = NULL, title_source = NULL WHERE id = ?",- (conflict_id,),- )- else:- raise ValueError(f"Title '{title}' is already in use by session {conflict_id}")- # CAS on the values just read (``IS`` is NULL-safe): a concurrent write between- # the SELECT and here loses instead of being overwritten.- return conn.execute(- "UPDATE sessions SET title = ?, title_source = ? WHERE id = ? AND title IS ? AND title_source IS ?",- (title, source if title else None, session_id, current["title"], current["title_source"]),- ).rowcount-- return self._execute_write(_do) > 0+ if conflict:+ conflict_id = conflict["id"]+ # A hidden compressed ancestor holding the title cannot be freed by the+ # user, so transfer it onto the tip (uniqueness + lineage kept).+ if self._is_compression_ancestor(conn, ancestor_id=conflict_id, descendant_id=session_id):+ conn.execute("UPDATE sessions SET title = NULL WHERE id = ?", (conflict_id,))+ affected.append(conflict_id)++ # A deliberately archived hidden Bot Chat is a retired registry++ # entry, not a live identity. Retire its name in the same title++ # transaction so a replacement can become the sole canonical row;++ # the old session remains archived and otherwise untouched.++ elif (title == self.CANONICAL_BOT_CHAT_TITLE and bool(conflict["archived"])++ and bool(conflict["hidden"])):++ conn.execute(++ "UPDATE sessions SET title = NULL, title_source = NULL WHERE id = ?",++ (conflict_id,),++ )++ affected.append(conflict_id)+ else:+ raise ValueError(f"Title '{title}' is already in use by session {conflict_id}")+ # CAS on the values just read (``IS`` is NULL-safe): a concurrent write between+ # the SELECT and here loses instead of being overwritten.+ changed = conn.execute(+ "UPDATE sessions SET title = ?, title_source = ? WHERE id = ? AND title IS ? AND title_source IS ?",+ (title, source if title else None, session_id, current["title"], current["title_source"]),+ ).rowcount+ return [*affected, session_id] if changed else affecteddef set_session_title(self, session_id: str, title: str) -> bool:"""Set a title on the user's behalf (``user`` provenance). Empty clears it. Raisesdiff --cc hermes_state_usage.pyindex 3f7549cbfca,5faf4f63e0d..3d23ec03e5b--- a/hermes_state_usage.py+++ b/hermes_state_usage.py@@@ -278,22 -278,19 +278,32 @@@ class SessionUsageMixinactual_cost_usd: Optional[float]=None, cost_status: Optional[str]=None, cost_source: Optional[str]=None,pricing_version: Optional[str]=None, billing_provider: Optional[str]=None, billing_base_url: Optional[str]=None,billing_mode: Optional[str]=None, api_call_count: int=0, absolute: bool=False,+ source: Optional[str]=None,) -> None:- """Update totals and route attribution, ensuring the legacy missing-row backfill."""- """Update token counters and backfill model if unset. *absolute*=False increments- (per-API-call deltas, CLI path); *absolute*=True sets directly (gateway path,- where the cached agent holds cumulative totals). ``source`` is the session's real surface- for the row-existence guard; callers that don't know it leave the placeholder."""- usage = {k: v for k, v in locals().items() if k in _MODEL_USAGE_FIELDS}++ """Update totals and route attribution, ensuring the legacy missing-row backfill.++ *absolute*=False increments (per-API-call deltas, CLI path); *absolute*=True sets directly++ (gateway path, where the cached agent holds cumulative totals). ``source`` is the session's++ real surface for the row-existence guard; callers that don't know it leave the placeholder."""+ values = dict(locals())+ values.pop('self')+ values.pop('session_id')- self._insert_session_row(session_id, "unknown", model=model)++ values.pop('source')+ # Ensure the row exists: under concurrent load create_session() may have failed on+ # locking, and the UPDATE would silently affect 0 rows. When this guard is the first+ # writer it must carry the agent's real source: the turn lease treats an existing row as+ # proof the create already happened, so the creator never returns to repair an anonymous+ # ``unknown`` placeholder and the session stays a phantom for life (#111999).+ self._insert_session_row(session_id, source or "unknown", model=model)+ self._execute_write(lambda conn: self._update_token_counts_in_transaction(conn, session_id, **values))++ def _update_token_counts_in_transaction(+ self, conn, session_id: str, input_tokens: int=0, output_tokens: int=0, model: str=None, cache_read_tokens: int=0,+ cache_write_tokens: int=0, reasoning_tokens: int=0, estimated_cost_usd: Optional[float]=None,+ actual_cost_usd: Optional[float]=None, cost_status: Optional[str]=None, cost_source: Optional[str]=None,+ pricing_version: Optional[str]=None, billing_provider: Optional[str]=None, billing_base_url: Optional[str]=None,+ billing_mode: Optional[str]=None, api_call_count: int=0, absolute: bool=False,+ ) -> None:+ usage = {k: v for k, v in locals().items() if k in _MODEL_USAGE_FIELDS}sql = _TOKEN_UPDATE_ABSOLUTE_SQL if absolute else _TOKEN_UPDATE_DELTA_SQLhas_usage = bool(input_tokens or output_tokens or cache_read_tokens or cache_write_tokens or reasoning_tokensor api_call_count or estimated_cost_usd)diff --cc hermes_state_worker_lifecycle.pyindex 814dffe99bf,00000000000..73d07dca617mode 100644,000000..100644--- a/hermes_state_worker_lifecycle.py+++ b/hermes_state_worker_lifecycle.py@@@ -1,239 -1,0 +1,244 @@@+"""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):+ """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,+ 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, 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 c3fa7253225,a8f8a777a86..a4efd5dca48--- a/providers/__init__.py+++ b/providers/__init__.py@@@ -87,12 -83,35 +87,39 @@@ def get_provider_profile(name: str) ->return profile+ def routed_model_rejects_vision_tool_messages(provider: str, model: str) -> bool:+ """Whether an active route or its aggregator-targeted model rejects image tool parts.++ Routing aggregators such as ``openrouter`` send vendor-prefixed model IDs+ (for example, ``xiaomi/mimo-v2.5``), but their own profile cannot describe+ every routed provider's tool-message compatibility. Preserve the transport+ profile as the default and consult a registered target profile only for+ routing aggregators. Missing or unrecognized identities deliberately fail open.+ """+ provider_name = str(provider or "").strip().lower()+ profile = get_provider_profile(provider_name)+ if profile is not None and profile.supports_vision_tool_messages is False:+ return True+ # Routing aggregators accept a ``vendor/model`` identifier while the request is sent+ # to the aggregator; the target provider can have stricter message-shape support than+ # the aggregator's generic OpenAI-compatible transport profile.+ from hermes_cli.providers import is_routing_aggregator+ if not is_routing_aggregator(provider_name):+ return False++ target_name, separator, _ = str(model or "").strip().partition("/")+ if not separator or not target_name:+ return False+ target_profile = get_provider_profile(target_name.strip().lower())+ return target_profile is not None and target_profile.supports_vision_tool_messages is False++def list_providers() -> list[ProviderProfile]:"""Return all registered provider profiles (one per canonical name)."""+ from agent.safe_worker_policy import safe_worker_enabled++ if safe_worker_enabled():+ return []global _PROVIDER_LIST_CACHEif not _discovered:_discover_providers()diff --cc tests/cron/test_cron_memory_contract.pyindex 00000000000,1e67e107388..8e0e9b8990fmode 000000,100644..100644--- a/tests/cron/test_cron_memory_contract.py+++ b/tests/cron/test_cron_memory_contract.py@@@ -1,0 -1,145 +1,147 @@@+ """Contract pin: cron <-> persistent-memory loading.++ This contract FLIPPED TWICE in August 2026 and must never flip silently again:++ * #91269 reported "cron loads MEMORY.md even though skip_memory is on".+ * PR #91384 flipped cron to ``skip_memory=True`` and denylisted the+ ``memory`` toolset ("do not load MEMORY.md into scheduled jobs").+ * PR #91447 flipped it BACK: "cron jobs now load and update persistent+ memory like every other agent" — ``skip_memory=False`` at the scheduler's+ AIAgent construction site, ``memory`` removed from the cron denylist,+ and ``agent/agent_init.py`` clarified that ``skip_memory`` skips the+ *external memory provider* path (built-in MEMORY.md/USER.md store follows+ the normal ``not skip_memory or memory-toolset-requested`` rule).++ CURRENT INTENDED MATRIX (as of PR #91447, pinned here):++ default cron job -> skip_memory=False; MEMORY.md/USER.md load into+ the system prompt; ``memory`` toolset follows+ normal resolution (NOT policy-denied).+ per-job enabled_toolsets -> naming ``memory`` keeps it; skip_memory stays+ False.+ config.yaml+ agent.disabled_toolsets:+ [memory] -> the ONLY off-switch: ``memory`` lands in the+ cron agent's disabled_toolsets (tool denied,+ and agent_init treats a denylisted toolset as+ not-requested). skip_memory itself is NOT a+ per-job/config toggle — the scheduler always+ passes False.++ ANY future flip of this behavior MUST consciously edit this test and cite+ the issue/PR that decided the flip in the module docstring above, extending+ the flip history. Do not "fix" a failure here by inverting an assertion+ without that citation.+-Tests drive the REAL ``cron.scheduler.run_job`` path and capture the actual-kwargs the scheduler passes to AIAgent (patched at ``run_agent.AIAgent``,-matching tests/cron/test_scheduler.py's pattern). The ON direction (default++Tests drive the REAL owner bridge (``gateway.session_cron.execute``, the path++``cron.scheduler.run_job`` hands a fire to) and capture the actual kwargs the++scheduler passes to AIAgent (patched at ``run_agent.AIAgent``, matching++tests/cron/test_scheduler.py's pattern). The ON direction (default+ skip_memory=False, memory not denylisted, per-job memory toolset kept) is+ already pinned by tests/cron/test_scheduler.py::test_run_job_*memory*; this+ module pins the OFF direction and the "no per-job knob" rule.+ """++ from __future__ import annotations++ import contextlib+ from unittest.mock import MagicMock, patch+-from cron.scheduler import run_job++from tests.cron.test_scheduler import _run_owned_job+++ @contextlib.contextmanager+ def _run_job_patches(tmp_path):+ """Patch bundle so run_job runs offline; yields (fake_db, mock_agent_cls).++ Mirrors tests/cron/test_scheduler.py::_run_job_patches — every patch is+ entered via one ExitStack so none can be silently dropped.+ ``cron.scheduler._hermes_home`` is pointed at ``tmp_path`` so run_job's+ config load reads ``tmp_path/config.yaml`` (write one to exercise config+ toggles).+ """+ fake_db = MagicMock()+ fake_db.get_compression_tip.side_effect = lambda session_id: session_id++ fake_db.db_path = str(tmp_path / "state.db")+ mock_agent = MagicMock()+ mock_agent.run_conversation.return_value = {"final_response": "ok"}+ base = [+ patch("cron.scheduler._hermes_home", 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=fake_db),+ patch(+ "hermes_cli.runtime_provider.resolve_runtime_provider",+ return_value={+ "api_key": "test-key",+ "base_url": "https://example.invalid/v1",+ "provider": "openrouter",+ "api_mode": "chat_completions",+ },+ ),+ patch("run_agent.AIAgent", return_value=mock_agent),+ ]+ with contextlib.ExitStack() as stack:+ entered = [stack.enter_context(cm) for cm in base]+ yield fake_db, entered[-1]+++ class TestCronMemoryContractOn:+ """Direction (a): default cron agents GET persistent memory (#91447)."""++ def test_resolver_denylist_has_no_memory_entry(self):+ """_resolve_cron_disabled_toolsets({}) itself never emits 'memory'."""+ from cron.scheduler import _resolve_cron_disabled_toolsets++ assert "memory" not in _resolve_cron_disabled_toolsets({})+ assert "memory" not in _resolve_cron_disabled_toolsets(+ {"cron": {"allow_agent_scheduling": True}}+ )+++ class TestCronMemoryContractOff:+ """Direction (b): the supported OFF switch stays off."""++ def test_config_disabled_toolsets_denies_memory(self, tmp_path):+ """agent.disabled_toolsets: [memory] in config.yaml denies the toolset.++ This is the intended user-level off-switch after #91447: the user+ denylist layers onto cron's base denylist (#25752), so the memory+ tool is denied AND agent_init treats a denylisted toolset as+ not-requested. A per-job enabled_toolsets cannot widen past it.+ """+ (tmp_path / "config.yaml").write_text(+ "agent:\n disabled_toolsets:\n - memory\n"+ )+ job = {+ "id": "mem-contract-off",+ "name": "t",+ "prompt": "hi",+ "enabled_toolsets": ["memory", "file"],+ }- with _run_job_patches(tmp_path) as (_db, agent_cls):- run_job(job)++ with _run_job_patches(tmp_path) as (fake_db, agent_cls):++ _run_owned_job(job, tmp_path, fake_db)+ kwargs = agent_cls.call_args.kwargs+ assert "memory" in (kwargs["disabled_toolsets"] or []), (+ "config.yaml agent.disabled_toolsets must propagate 'memory' into "+ "the cron agent's denylist — the OFF direction of the contract"+ )++ def test_skip_memory_is_not_a_per_job_knob(self, tmp_path):+ """No per-job field flips skip_memory: the scheduler always passes False.++ Guards against a partial re-flip where some job shape quietly gets+ #91384 behavior back. A field named skip_memory on the job dict is+ ignored by the construction site.+ """+ job = {+ "id": "mem-contract-noknob",+ "name": "t",+ "prompt": "hi",+ "skip_memory": True, # not a supported job field; must be ignored+ }- with _run_job_patches(tmp_path) as (_db, agent_cls):- run_job(job)++ with _run_job_patches(tmp_path) as (fake_db, agent_cls):++ _run_owned_job(job, tmp_path, fake_db)+ kwargs = agent_cls.call_args.kwargs+ assert kwargs["skip_memory"] is Falsediff --cc tests/cron/test_scheduler.pyindex 5040c1c3227,3eb0bf83736..09ad3791385--- a/tests/cron/test_scheduler.py+++ b/tests/cron/test_scheduler.py@@@ -1,7 -1,7 +1,8 @@@"""Tests for cron/scheduler.py — origin resolution, delivery routing, and error logging."""+import asyncioimport contextlib+ import contextvarsimport itertoolsimport jsonimport logging@@@ -25,52 -26,19 +27,65 @@@ from tools.env_passthrough import clearfrom tools.credential_files import clear_credential_files+def _run_owned_job(job, tmp_path, db=None):+ """Run the production owner bridge, preserving each test's agent/DB probes."""+ from gateway.session_contract import SessionRef+ from gateway.session_cron import current_execution, execute+ from hermes_state_registry import acquire, release++ ref = SessionRef("test-profile", "canonical-cron-session")+ admission_id = "cron-owner-admission"+ request_id = "cron-owner-request"+ owns_db = db is None+ if owns_db:+ db = acquire(tmp_path / "state.db")+ db.create_session(ref.session_id, source="cron")+ else:+ db.db_path = str(tmp_path / "state.db")+ authority = SimpleNamespace(+ db=db,+ sessions={ref.session_id: SimpleNamespace(source=SimpleNamespace(user_id="cron-owner"))},+ pending_results={},+ )+ row = {+ "admission_id": admission_id, "request_id": request_id,+ "principal_id": "cron-owner", "payload": {"text": ""},+ }+ policy = SimpleNamespace(request_json=json.dumps({+ "cron_job": job, "extra_prompt": None, "request_id": request_id,+ }))++ async def run():+ previous = current_execution()+ try:+ await execute(authority, ref, row, policy)+ except RuntimeError as exc:+ saved = authority.pending_results.get(admission_id)+ if saved is None:+ raise+ assert str(exc) == saved["result"]["cron_result"][3]+ assert current_execution() is previous+ assert authority._cron_cancellations == {}+ return tuple(authority.pending_results[admission_id]["result"]["cron_result"])++ try:+ return asyncio.run(run())+ finally:+ if owns_db:+ release(db)+ def test_cron_cleanup_worker_inherits_caller_contextvars():+ """Profile-scoped secrets must remain visible during threaded cleanup."""+ profile_scope = contextvars.ContextVar("test_cron_cleanup_profile_scope")+ profile_scope.set("profile-key")+ observed = []++ assert _run_cron_cleanup_with_timeout(+ lambda: observed.append(profile_scope.get(None)),+ job_id="context-scope",+ label="test cleanup",+ timeout_seconds=1,+ )+ assert observed == ["profile-key"]class TestSummarizeCronFailureForDelivery:@@@ -1137,14 -1147,10 +1164,10 @@@ class TestRunJobConfigLoggingmock_agent_cls.return_value = mock_agentwith caplog.at_level(logging.WARNING):- run_job(job)+ _run_owned_job(job, tmp_path)- # The owner bridge fails closed on a corrupt config before load_config()'s- # fallback warning; either message names the file and the parse error.- assert any(- ("Failed to parse" in r.message or "is invalid" in r.message) and "config.yaml" in r.message- for r in caplog.records- ), f"Expected a config.yaml parse warning in logs, got: {[r.message for r in caplog.records]}"+ assert any("formatting error" in r.message and "config.yaml" in r.message for r in caplog.records), \+ f"Expected a config.yaml parse warning in logs, got: {[r.message for r in caplog.records]}"class TestRunJobConfigEnvVarExpansion:@@@ -1453,11 -1459,12 +1476,11 @@@ class TestRunJobModelResolutionmock_agent = MagicMock()mock_agent.run_conversation.return_value = {"final_response": "ok"}mock_agent_cls.return_value = mock_agent- success, _, _, error = run_job(job)+ success, _, _, error = _run_owned_job(job, tmp_path, fake_db)- # Explicit job model survives the corrupt-config fall-through.- assert success is True- assert error is None- assert mock_agent_cls.call_args.kwargs["model"] == "explicit-model"+ assert success is False- assert "Refusing non-interactive startup" in error++ assert "Hermes stopped because your settings file" in error+ mock_agent_cls.assert_not_called()class TestRunJobSkillBacked:diff --cc tests/cron/test_script_claim_heartbeat.pyindex ae4b95979ea,854f0f4bf3e..7e1e22d85d4--- a/tests/cron/test_script_claim_heartbeat.py+++ b/tests/cron/test_script_claim_heartbeat.py@@@ -418,6 -418,120 +418,124 @@@ def test_lost_fire_claim_stops_stale_demark_run.assert_not_called()+ def _run_claimed_job_with_mid_run_action(+ tmp_path, monkeypatch, mid_run, *, execution_id, stub_output=True, crash=None,+ expect_result=True,+ ):+ """Fire a claimed job through run_one_job with a stubbed agent run that performs ``mid_run``+ on its own record, keeps working past one fire-claim heartbeat tick, then completes (or+ raises ``crash``)."""+ import cron.jobs as jobs+ import cron.scheduler as scheduler++ def _run_job(job, **_kwargs):+ mid_run(jobs, job)+ time.sleep(0.3)+ if crash is not None:+ raise crash+ return True, "saved output", "D1 is promoting", None+- delivered = MagicMock(return_value=None)++ # A completed agent run with an execution id hands its notice to the durable delivery queue++ # (drained by the gateway), never to an inline ``_deliver_result``; the enqueue IS the++ # delivery. A crash still alerts inline, so both doors are stubbed.++ delivered = MagicMock(return_value={"status": "queued"})++ monkeypatch.setattr(scheduler, "_deliver_result", MagicMock(return_value=None))+ finished = MagicMock()+ monkeypatch.setattr(scheduler, "_RUN_CLAIM_HEARTBEAT_SECONDS", 0.05)+ monkeypatch.setattr(scheduler, "run_job", _run_job)+ monkeypatch.setattr(scheduler, "claim_dispatch", lambda *_args: True)+ monkeypatch.setattr(scheduler, "mark_execution_running", lambda *_args: {})+ monkeypatch.setattr(scheduler, "finish_execution", finished)+ if stub_output:+ monkeypatch.setattr(scheduler, "save_job_output", lambda *_args: "output.md")- monkeypatch.setattr(scheduler, "_deliver_result", delivered)++ monkeypatch.setattr("cron.delivery_queue.enqueue", delivered)++ with jobs.use_cron_store(tmp_path):+ job = jobs.create_job(+ prompt="work", schedule="every 5m", name="remove self", deliver="telegram")+ assert jobs.claim_job_for_fire(job["id"])+ claimed = jobs.get_job(job["id"])+ claimed["execution_id"] = execution_id++ with patch("agent.secret_scope.set_secret_scope", return_value=None), \+ patch("agent.secret_scope.build_profile_secret_scope", return_value=None), \+ patch("agent.secret_scope.reset_secret_scope"):+ assert scheduler.run_one_job(claimed) is expect_result+ return delivered, finished+++ def test_self_removed_job_still_delivers_after_post_removal_heartbeat(tmp_path, monkeypatch):+ """A run that removes its own job (cronjob remove on its own id) and keeps working past a+ heartbeat tick must still deliver its final response and complete its ledger row (#111039)."""+ import cron.jobs as jobs++ delivered, finished = _run_claimed_job_with_mid_run_action(+ tmp_path, monkeypatch,+ lambda jobs_mod, job: jobs_mod.remove_job(job["id"]),+ execution_id="self-removal-heartbeat-execution")++ delivered.assert_called_once()+ finished.assert_called_once_with(+ "self-removal-heartbeat-execution",- success=True, error=None, delivery_outcome="delivered")++ success=True, error=None, delivery_outcome="queued")+ with jobs.use_cron_store(tmp_path):+ assert jobs.load_jobs() == []+++ def test_self_removed_job_leaves_no_output_directory(tmp_path, monkeypatch):+ """remove_job() deletes <cron>/output/<job_id>/; the finishing run must not re-create it+ (an orphan directory per self-removing job), so 'only the job record is gone' stays true."""+ import cron.jobs as jobs++ delivered, _finished = _run_claimed_job_with_mid_run_action(+ tmp_path, monkeypatch,+ lambda jobs_mod, job: jobs_mod.remove_job(job["id"]),+ execution_id="self-removal-output-execution", stub_output=False)++ delivered.assert_called_once()+ with jobs.use_cron_store(tmp_path):+ assert jobs.load_jobs() == []+ assert list((tmp_path / "cron" / "output").glob("*")) == []+++ def test_self_removed_job_crash_skips_mark_job_run(tmp_path, monkeypatch):+ """A run that crashes after removing its own record has no record to mark: the crash path+ must skip mark_job_run like the completion path does, not probe a missing record."""+ import cron.scheduler as scheduler++ marked = MagicMock(return_value=True)+ monkeypatch.setattr(scheduler, "mark_job_run", marked)+ _delivered, finished = _run_claimed_job_with_mid_run_action(+ tmp_path, monkeypatch,+ lambda jobs_mod, job: jobs_mod.remove_job(job["id"]),+ execution_id="self-removal-crash-execution",+ crash=RuntimeError("boom after self-removal"), expect_result=False)++ marked.assert_not_called()+ finished.assert_called_once_with(+ "self-removal-crash-execution", success=False,+ error="boom after self-removal", delivery_outcome="delivered")+++ def test_self_removal_followed_by_replacement_record_stays_fail_closed(tmp_path, monkeypatch):+ """Self-removal only excuses a MISSING record: once another owner's record reclaims the id,+ the run is stale again and its result must be discarded, never delivered."""++ def _remove_then_replace(jobs_mod, job):+ assert jobs_mod.remove_job(job["id"])+ replacement = {k: v for k, v in job.items() if k != "execution_id"}+ replacement["fire_claim"] = {"at": job["fire_claim"]["at"], "by": "other-machine:owner"}+ jobs_mod.save_jobs(jobs_mod.load_jobs() + [replacement])++ delivered, finished = _run_claimed_job_with_mid_run_action(+ tmp_path, monkeypatch, _remove_then_replace, execution_id="replacement-execution")++ delivered.assert_not_called()+ finished.assert_called_once_with(+ "replacement-execution", success=False,+ error="Fire claim ownership lost; stale result was discarded.")++def test_initially_lost_fire_claim_finishes_execution_without_running(monkeypatch):"""A stale claimed snapshot rejected before body entry must close its ledger row."""import cron.scheduler as schedulerdiff --cc tests/gateway/test_api_server_sse_keepalive.pyindex 00000000000,6eb3776bdee..017e6b2118emode 000000,100644..100644--- a/tests/gateway/test_api_server_sse_keepalive.py+++ b/tests/gateway/test_api_server_sse_keepalive.py@@@ -1,0 -1,91 +1,92 @@@+ """API-server SSE keepalive cadence while the agent is silent (preflight compression, long+ tool calls). Remote OpenAI-compatible clients commonly drop an idle stream after ~20 s and the+ disconnect interrupts the turn, so every SSE writer must emit a comment frame before that+ window closes (issue #111512)."""++ import asyncio+ import types++ import pytest+ from aiohttp import web+ from aiohttp.test_utils import TestClient, TestServer++ from gateway.config import PlatformConfig+ from gateway.platforms import api_server+ from gateway.platforms import api_server_openai_routes as routes+ from gateway.platforms.api_server import APIServerAdapter+ from gateway.platforms.api_server_openai_routes import _iter_stream_items++ REMOTE_CLIENT_IDLE_DEADLINE_S = 20.0+++ class _RecordingResponse:+ def __init__(self) -> None:+ self.writes: list[bytes] = []++ async def write(self, data: bytes) -> None:+ self.writes.append(data)+++ @pytest.fixture+ def adapter():+ return APIServerAdapter(PlatformConfig(enabled=True, extra={}))+++ @pytest.mark.asyncio+ async def test_idle_openai_stream_writes_keepalive_before_remote_client_deadline(monkeypatch):+ """Chat/Responses streams (``_iter_stream_items``) keep the wire alive inside the client window."""+ assert api_server.CHAT_COMPLETIONS_SSE_KEEPALIVE_SECONDS <= REMOTE_CLIENT_IDLE_DEADLINE_S++ # Module-local fake clock: each read is one keepalive interval later, so the poll loop+ # observes an idle stream without waiting real seconds (asyncio keeps the real clock).+ reads = [0.0]+ step = api_server.CHAT_COMPLETIONS_SSE_KEEPALIVE_SECONDS++ def monotonic():+ reads[0] += step+ return reads[0]++ monkeypatch.setattr(routes, "time", types.SimpleNamespace(monotonic=monotonic))+ stream_q: asyncio.Queue = asyncio.Queue()+ agent_task = asyncio.get_running_loop().create_future()+ response = _RecordingResponse()++ async def _finish_after_first_keepalive():+ while not response.writes:+ await asyncio.sleep(0.05)+ agent_task.set_result(None)++ finisher = asyncio.create_task(_finish_after_first_keepalive())+ items = [item async for item in _iter_stream_items(stream_q, agent_task, response)]+ await finisher++ assert items == []+ assert response.writes[0] == b": keepalive\n\n"+++ @pytest.mark.asyncio+ async def test_idle_run_events_stream_uses_shared_keepalive_cadence(monkeypatch, adapter):+ """``GET /v1/runs/{id}/events`` follows the same keepalive constant as the OpenAI routes."""+ monkeypatch.setattr(api_server, "CHAT_COMPLETIONS_SSE_KEEPALIVE_SECONDS", 0.2)- queue: asyncio.Queue = asyncio.Queue()- adapter._run_streams["run_idle"] = queue++ from gateway.platforms.api_server_runs import _RunStream++ # The run stream is the fanout log every SSE subscriber reads, not a bare queue.++ stream = adapter._run_streams["run_idle"] = _RunStream()+ adapter._set_run_status("run_idle", "running")+ monkeypatch.setattr(adapter, "_request_owns_run", lambda request, run_id: True)++ app = web.Application()+ app["api_server_adapter"] = adapter+ app.router.add_get("/v1/runs/{run_id}/events", adapter._handle_run_events)++ async def _close_after_idle():+ await asyncio.sleep(0.5)- await queue.put(None)++ stream.put_nowait(None)++ async with TestClient(TestServer(app)) as cli:+ closer = asyncio.create_task(_close_after_idle())+ resp = await cli.get("/v1/runs/run_idle/events")+ body = await resp.text()+ await closer++ assert resp.status == 200+ assert body.count(": keepalive\n\n") >= 1diff --cc tests/gateway/test_bot_result_recovery.pyindex 752f6df0c4c,00000000000..b4c9576a228mode 100644,000000..100644--- a/tests/gateway/test_bot_result_recovery.py+++ b/tests/gateway/test_bot_result_recovery.py@@@ -1,86 -1,0 +1,111 @@@+"""Bot receipts recover only their exact committed admission result."""+from types import SimpleNamespace++from hermes_state import SessionDB+from hermes_state_runtime import (+ admit_session_input, begin_runtime_epoch, claim_session_input,+ recover_session_inputs,+)+from gateway.session_results import retain_result+from gateway.session_bot import _result+++def test_bot_reply_recovery_uses_exact_terminal_admission(tmp_path):+ path = tmp_path / 'state.db'+ db = SessionDB(path)+ db.create_session('bot', source='gui')+ epoch = begin_runtime_epoch(db, instance_id='first')+ records = []+ for key, reply, settle in [('one', 'exact first reply', True),+ ('two', 'later reply is not first', True),+ ('three', 'uncommitted reply', False)]:+ admission = admit_session_input(db, epoch=epoch, principal_id='owner', session_id='bot',+ request_id=key, payload={'text': key})+ row = claim_session_input(db, epoch=epoch, session_id='bot')+ # retain_result IS the settlement: the result commits with terminal status or not at all.+ if settle:+ retain_result(db, epoch=epoch, row=row, result={'result': {'final_response': reply}, 'usage': {}})+ records.append(dict(status='canonical', admission_id=admission['admission_id'],+ delivery_id=key, profile_home=str(tmp_path), session_id='bot', message=key))+ db.close()+ db = SessionDB(path)+ try:+ epoch = begin_runtime_epoch(db, instance_id='restart')+ recover_session_inputs(db, epoch=epoch)+ authority = SimpleNamespace(db=db)+ assert [_result(authority, record)['message'] for record in records] == ['one', 'two', 'three']+ assert _result(authority, records[0])['reply'] == 'exact first reply'+ assert _result(authority, records[0])['status'] == 'settled'+ assert _result(authority, records[1])['reply'] == 'later reply is not first'+ assert _result(authority, records[2])['status'] == 'ambiguous'+ assert _result(authority, records[2])['reply'] == ''+ finally:+ db.close()+++def test_cancelled_queued_admission_is_a_terminal_cancelled_receipt_not_ambiguous(tmp_path):+ """A queued Bot admission cancelled before execution definitively did not run: after an+ owner restart, recovery and the exact delivery retry both report ``cancelled`` (terminal),+ never ``ambiguous``; a rejected admission without a result blob is ``failed``."""+ import asyncio+ from hermes_state_runtime import cancel_session_input, settle_session_input+ from tools.bot_live_delivery import _locked, _read, _write+ from gateway.session_bot import recover_bot_deliveries+ path = tmp_path / 'state.db'+ db = SessionDB(path)+ db.create_session('bot', source='gui')+ epoch = begin_runtime_epoch(db, instance_id='first')+ running = admit_session_input(db, epoch=epoch, principal_id='owner', session_id='bot',+ request_id='bot:' + 'a' * 32, payload={'text': 'running'})+ queued = admit_session_input(db, epoch=epoch, principal_id='owner', session_id='bot',+ request_id='bot:' + 'b' * 32, payload={'text': 'queued'})+ row = claim_session_input(db, epoch=epoch, session_id='bot')+ assert row['admission_id'] == running['admission_id']+ cancel_session_input(db, epoch=epoch, admission_id=queued['admission_id'])+ settle_session_input(db, epoch=epoch, admission_id=row['admission_id'], generation=row['generation'], outcome='rejected')+ records = {}+ with _locked(tmp_path) as root:+ for key, admission in (('a' * 32, running), ('b' * 32, queued)):+ records[key] = dict(status='canonical', admission_id=admission['admission_id'], delivery_id=key,+ profile_home=str(tmp_path), session_id='bot', message=key, principal_id='owner')+ _write(root / f'{key}.json', records[key])+ db.close()+ db = SessionDB(path)+ try:+ epoch = begin_runtime_epoch(db, instance_id='restart')+ recover_session_inputs(db, epoch=epoch)+ authority = SimpleNamespace(db=db, waiters={})+ asyncio.run(recover_bot_deliveries(authority))+ with _locked(tmp_path) as root:+ recovered = {key: _read(root / f'{key}.json')['status'] for key in records}+ assert recovered == {'a' * 32: 'failed', 'b' * 32: 'cancelled'}+ # The exact retry reads the same classification from the durable admission row.+ assert _result(authority, records['b' * 32])['status'] == 'cancelled'+ assert _result(authority, records['a' * 32])['status'] == 'failed'+ finally:+ db.close()++++++def test_settled_bot_receipt_relays_empty_reply_for_a_bare_silence_marker(tmp_path):++ """#110782: the authority receipt applies the gateway's silence rule — a successful bare++ marker reaches the sender as "", prose that merely mentions one is relayed verbatim."""++ path = tmp_path / 'state.db'++ db = SessionDB(path)++ try:++ db.create_session('bot', source='gui')++ epoch = begin_runtime_epoch(db, instance_id='first')++ records = []++ for key, reply in [('quiet', ' *NO_REPLY* '), ('prose', 'The NO_REPLY marker means do not answer.')]:++ admission = admit_session_input(db, epoch=epoch, principal_id='owner', session_id='bot',++ request_id=key, payload={'text': key})++ row = claim_session_input(db, epoch=epoch, session_id='bot')++ retain_result(db, epoch=epoch, row=row, result={'result': {'final_response': reply}, 'usage': {}})++ records.append(dict(status='canonical', admission_id=admission['admission_id'],++ delivery_id=key, profile_home=str(tmp_path), session_id='bot', message=key))++ authority = SimpleNamespace(db=db)++ quiet, prose = (_result(authority, record) for record in records)++ assert quiet['status'] == prose['status'] == 'settled'++ assert quiet['reply'] == ''++ assert prose['reply'] == 'The NO_REPLY marker means do not answer.'++ finally:++ db.close()diff --cc tests/gateway/test_clarify_card_retire_on_timeout.pyindex 00000000000,e3480c355a0..4cf15d4979amode 000000,100644..100644--- a/tests/gateway/test_clarify_card_retire_on_timeout.py+++ b/tests/gateway/test_clarify_card_retire_on_timeout.py@@@ -1,0 -1,91 +1,92 @@@+ """A clarify that ends without a click retires the adapter's native card (#110821, #111019).++ Drives the real ``TurnRunner._clarify_callback_sync`` against a duck-typed adapter with a+ persistent card: on timeout the gateway schedules ``retire_clarify_card`` with the expired+ notice; an adapter without that method (text-prompt platforms) gets nothing scheduled.+ """++ import asyncio+ from types import SimpleNamespace+ from unittest.mock import patch++ from gateway.platforms.base import SendResult+++ class _CardAdapter:+ def __init__(self):+ self.retired: list[tuple[str, str]] = []++ def pause_typing_for_chat(self, chat_id):+ return None++ def resume_typing_for_chat(self, chat_id):+ return None++ async def send_clarify(self, **kwargs):+ return SendResult(success=True, message_id="1.2")++ async def retire_clarify_card(self, clarify_id, notice):+ self.retired.append((clarify_id, notice))+++ class _TextAdapter(_CardAdapter):+ retire_clarify_card = None # type: ignore[assignment]+++ def _run_clarify(adapter, answer=None):+ """Returns (clarify response, labels of every coroutine the runner scheduled).+ ``answer`` resolves the pending clarify with that text instead of letting it time out."""+ from gateway.run_turn_runner import TurnRunner++ runner = object.__new__(TurnRunner)++ runner._approval_owner = None # no owning authority: the controls snapshot is skipped+ runner._ctx = SimpleNamespace(+ _status_adapter=adapter, _status_chat_id="C1", _status_thread_metadata={},+ session_key="sk1", stream_consumer_holder=[None])+ labels: list[str] = []++ class _Fut:+ def __init__(self, r): self._r = r+ def result(self, timeout=None): return self._r++ def _schedule(coro, label):+ labels.append(label)+ return _Fut(asyncio.run(coro))++ runner._schedule = _schedule+ runner._close_native_stream_boundary = lambda *a, **k: None+ if answer is not None:+ from tools import clarify_gateway as cm+ real_register = cm.register++ def _register_and_answer(**kwargs):+ entry = real_register(**kwargs)+ cm.resolve_gateway_clarify(kwargs["clarify_id"], answer)+ return entry+ register_patch = patch.object(cm, "register", _register_and_answer)+ else:+ register_patch = patch("tools.clarify_gateway.get_clarify_timeout", return_value=1)+ with register_patch:+ return runner._clarify_callback_sync("Pick one", ["a", "b"]), labels+++ def test_timeout_retires_the_native_card_with_the_expired_notice():+ adapter = _CardAdapter()+ response, _labels = _run_clarify(adapter)+ assert response.startswith("[user did not respond")+ assert len(adapter.retired) == 1+ assert "expired" in adapter.retired[0][1].lower()+++ def test_timeout_schedules_nothing_for_adapters_without_a_card():+ _response, labels = _run_clarify(_TextAdapter())+ assert labels == ["Clarify send failed to schedule"]+++ def test_real_answer_starting_with_a_bracket_is_not_mistaken_for_a_sentinel():+ """'[A] staging' is a user answer, not a timeout: no card retirement, typing re-armed."""+ adapter = _CardAdapter()+ response, labels = _run_clarify(adapter, answer="[A] staging")+ assert response == "[A] staging"+ assert adapter.retired == []+ assert labels == ["Clarify send failed to schedule"]diff --cc tests/gateway/test_webhook_coalescing.pyindex 00000000000,f6479f79b1c..ba9a0cb1d50mode 000000,100644..100644--- a/tests/gateway/test_webhook_coalescing.py+++ b/tests/gateway/test_webhook_coalescing.py@@@ -1,0 -1,126 +1,147 @@@+ """Per-route webhook event coalescing (#92066): rapid distinct events on one entity debounce into+ a single agent run on the latest event's state; unrelated or unkeyed events are never merged."""++ import asyncio+ import json-from unittest.mock import AsyncMock, MagicMock++from types import SimpleNamespace++from unittest.mock import MagicMock++ import pytest++ from gateway.config import PlatformConfig++from gateway.platforms import webhook_ingress+ from gateway.platforms.webhook import WebhookAdapter, _INSECURE_NO_AUTH+++ def _make_adapter(routes=None):+ extra = {"host": "127.0.0.1", "port": 0, "routes": routes or {}, "rate_limit": 100}+ return WebhookAdapter(PlatformConfig(enabled=True, extra=extra))++++def _capture_admissions(adapter, monkeypatch):++ """Stand in for the durable producer: the adapter admits every dispatched event through++ ``admit_producer`` (immediate and coalesced paths alike), never a spawned ``handle_message``.++ Returns the list of admitted events; the finalize task is a no-op."""++ admitted = []++++ async def _admit(_adapter, event):++ admitted.append(event)++ return SimpleNamespace(admission_id=f"adm-{len(admitted)}", ref=SimpleNamespace(profile_id="default"))++++ async def _finalize(event, authority, receipt):++ return None++++ monkeypatch.setattr(webhook_ingress, "admit_producer", _admit)++ monkeypatch.setattr(adapter, "_finalize_delivery", _finalize)++ adapter._message_handler = SimpleNamespace(__self__=SimpleNamespace())++ monkeypatch.setattr("gateway.session_authorities.authority_for_profile_id", lambda runner, pid: object())++ return admitted+++++ def _coalesce_route(**coalesce):+ return {"secret": _INSECURE_NO_AUTH, "prompt": "PR {pull_request.number}: {action}",+ "coalesce": coalesce or {"key": "pull_request.number"}}+++ def _mock_request(body: bytes, route_name: str = "pr", delivery_id: str = ""):+ req = MagicMock()+ req.headers = {"X-GitHub-Delivery": delivery_id} if delivery_id else {}+ req.content_length = len(body)+ req.match_info = {"route_name": route_name}+ req.method = "POST"++ async def _read():+ return body++ req.read = _read+ return req+++ def _payload(pr_number=None, action: str = "synchronize") -> bytes:+ body: dict = {"action": action}+ if pr_number is not None:+ body["pull_request"] = {"number": pr_number}+ return json.dumps(body).encode()+++ @pytest.mark.asyncio+ @pytest.mark.parametrize("route, match", [+ ({**_coalesce_route(), "coalesce": {"window_seconds": 5}}, "coalesce block"),+ ({**_coalesce_route(), "coalesce": "pull_request.number"}, "coalesce block"),+ (_coalesce_route(key="pull_request.number", window_seconds=0), "window_seconds"),+ (_coalesce_route(key="pull_request.number", max_wait_seconds=True), "max_wait_seconds"),+ ({**_coalesce_route(), "deliver_only": True, "deliver": "telegram"}, "deliver_only"),+ ({**_coalesce_route(), "cron_job": "sweeper"}, "cron_job"),+ ])+ async def test_invalid_coalesce_config_rejected_at_connect(route, match, tmp_path, monkeypatch):+ with pytest.raises(ValueError, match=match):+ await _make_adapter(routes={"pr": route}).connect()+ # The same block on a hot-reloaded dynamic route is skipped (warned), never admitted — it would+ # otherwise raise inside the request handler.+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ (tmp_path / "webhook_subscriptions.json").write_text(json.dumps({"dyn": route}), encoding="utf-8")+ adapter = _make_adapter()+ adapter._reload_dynamic_routes()+ assert "dyn" not in adapter._routes+++ @pytest.mark.asyncio-async def test_rapid_same_entity_events_dispatch_once_with_latest():++async def test_rapid_same_entity_events_dispatch_once_with_latest(monkeypatch):+ """Three events on PR 7 → one run carrying the last event's prompt/delivery id and a superseded+ note; a different PR in the same burst is its own group; a provider retry (same delivery id)+ is dropped by idempotency before coalescing and is not counted."""+ adapter = _make_adapter(routes={"pr": _coalesce_route(key="pull_request.number", window_seconds=0.05)})- adapter.handle_message = AsyncMock()++ admitted = _capture_admissions(adapter, monkeypatch)++ statuses = []+ for i, action in enumerate(["opened", "synchronize", "synchronize"]):+ resp = await adapter._handle_webhook(_mock_request(_payload(7, action), delivery_id=f"d{i}"))+ statuses.append((resp.status, json.loads(resp.text)["status"]))+ retry = await adapter._handle_webhook(_mock_request(_payload(7), delivery_id="d2"))+ other = await adapter._handle_webhook(_mock_request(_payload(8), delivery_id="other"))+ assert statuses == [(202, "coalesced")] * 3+ assert json.loads(retry.text)["status"] == "duplicate"+ assert json.loads(other.text)["status"] == "coalesced"- adapter.handle_message.assert_not_called()++ assert admitted == []++ await asyncio.sleep(0.15)+- events = {c.args[0].message_id: c.args[0] for c in adapter.handle_message.call_args_list}++ events = {e.message_id: e for e in admitted}+ assert set(events) == {"d2", "other"}+ assert "PR 7: synchronize" in events["d2"].text and "3 webhook events" in events["d2"].text+ assert "coalesced" not in events["other"].text+ assert adapter._coalescer.pending == {}+++ @pytest.mark.asyncio-async def test_max_wait_caps_starvation_and_unresolved_key_dispatches_immediately():++async def test_max_wait_caps_starvation_and_unresolved_key_dispatches_immediately(monkeypatch):+ adapter = _make_adapter(routes={"pr": _coalesce_route(key="pull_request.number", window_seconds=10,+ max_wait_seconds=0.1)})- adapter.handle_message = AsyncMock()++ admitted = _capture_admissions(adapter, monkeypatch)++ # An event without the key field must not be folded into a shared "{pull_request.number}" group.+ resp = await adapter._handle_webhook(_mock_request(_payload(None, "created"), delivery_id="nokey"))+ assert json.loads(resp.text)["status"] == "accepted"- await asyncio.sleep(0)- assert adapter.handle_message.call_count == 1++ assert len(admitted) == 1++ # A stream faster than the 10s window still dispatches once max_wait (0.1s) elapses.+ for i in range(3):+ await adapter._handle_webhook(_mock_request(_payload(5), delivery_id=f"s{i}"))+ await asyncio.sleep(0.02)+ await asyncio.sleep(0.15)- assert adapter.handle_message.call_count == 2- assert "3 webhook events" in adapter.handle_message.call_args[0][0].text++ assert len(admitted) == 2++ assert "3 webhook events" in admitted[-1].text+++ @pytest.mark.asyncio-async def test_disconnect_flushes_pending_groups():++async def test_disconnect_flushes_pending_groups(monkeypatch):+ adapter = _make_adapter(routes={"pr": _coalesce_route(key="pull_request.number", window_seconds=60)})- adapter.handle_message = AsyncMock()++ admitted = _capture_admissions(adapter, monkeypatch)+ await adapter._handle_webhook(_mock_request(_payload(4), delivery_id="pend"))- adapter.handle_message.assert_not_called()++ assert admitted == []++ await adapter.disconnect()+- assert adapter.handle_message.call_count == 1- assert adapter.handle_message.call_args[0][0].message_id == "pend"++ assert len(admitted) == 1++ assert admitted[0].message_id == "pend"+ assert adapter._coalescer.pending == {}diff --cc tests/hermes_cli/test_cli_insights_command.pyindex 944076ca556,33098e76533..4f7eb98fbf3--- a/tests/hermes_cli/test_cli_insights_command.py+++ b/tests/hermes_cli/test_cli_insights_command.py@@@ -1,15 -1,18 +1,18 @@@from unittest.mock import MagicMock, patchfrom types import SimpleNamespace+ import pytest+from cli import HermesCLIfrom hermes_cli.main_agent_cmds import cmd_insights- import pytest-from hermes_state import _default_db_path@pytest.fixture(autouse=True)-def _state_db_exists():+def existing_store(tmp_path, monkeypatch):+ # insights short-circuits before opening when state.db is absent (fresh install).- _default_db_path().parent.mkdir(parents=True, exist_ok=True)- _default_db_path().touch()+ monkeypatch.setattr("hermes_cli.config.get_hermes_home", lambda: tmp_path)+ (tmp_path / "state.db").touch()++ return tmp_path / "state.db"class _InsightsEngineStub:@@@ -52,6 -55,37 +55,37 @@@ def test_cli_insights_keeps_days_flag_aassert "days=14 source=discord" in capsys.readouterr().out-def test_insights_skips_open_when_store_missing(capsys):++def test_insights_skips_open_when_store_missing(capsys, existing_store):+ # Fresh install: no state.db yet → no open at all (a read-only open needs an existing file).- _default_db_path().unlink()++ existing_store.unlink()+ for run in (lambda: HermesCLI.__new__(HermesCLI)._show_insights("/insights 7"),+ lambda: cmd_insights(SimpleNamespace(days=30, source=None))):+ with patch("hermes_state.SessionDB") as ctor:+ run()+ ctor.assert_not_called()- assert "No session data yet." in capsys.readouterr().out++ assert "No sessions found in the last" in capsys.readouterr().out++-def test_show_insights_opens_read_only():++def test_show_insights_opens_read_only(existing_store):+ cli_obj = HermesCLI.__new__(HermesCLI)+ db = MagicMock()+ with patch("hermes_state.SessionDB", return_value=db) as ctor, \+ patch("agent.insights.InsightsEngine", _InsightsEngineStub):+ _InsightsEngineStub.calls = []+ cli_obj._show_insights("/insights 7")- ctor.assert_called_once_with(read_only=True)++ ctor.assert_called_once_with(db_path=existing_store, read_only=True)+ db.close.assert_called_once()++-def test_subcommand_insights_opens_read_only():++def test_subcommand_insights_opens_read_only(existing_store):+ db = MagicMock()+ with patch("hermes_state.SessionDB", return_value=db) as ctor, \+ patch("agent.insights.InsightsEngine", _InsightsEngineStub):+ cmd_insights(SimpleNamespace(days=30, source=None))- ctor.assert_called_once_with(read_only=True)++ ctor.assert_called_once_with(db_path=existing_store, read_only=True)+ db.close.assert_called_once()++def test_subcommand_insights_closes_database_when_generation_fails(capsys):db = MagicMock()with patch("hermes_state.SessionDB", return_value=db), \diff --cc tests/hermes_cli/test_config.pyindex ef672d54cf7,c83c5e53727..6011fb69dd0--- a/tests/hermes_cli/test_config.py+++ b/tests/hermes_cli/test_config.py@@@ -1058,28 -1058,6 +1058,28 @@@ class TestCuratorFasterPruneassert raw["curator"]["archive_after_days"] == 180+class TestRetiredBotChatDeliveryTimeout:- def test_v44_drops_bot_chat_delivery_timeout_with_a_note(self, tmp_path, monkeypatch):++ def test_v45_drops_bot_chat_delivery_timeout_with_a_note(self, tmp_path, monkeypatch):+ """The removed cron knob is dropped from existing configs with a one-time note;+ sibling cron settings and the rest of the file survive untouched."""+ from hermes_cli.config import DEFAULT_CONFIG+ from hermes_cli.config_migrations import run_migrations++ config_path = tmp_path / "config.yaml"+ config_path.write_text(yaml.safe_dump({- "_config_version": 44,++ "_config_version": 45,+ "cron": {"bot_chat_delivery_timeout_seconds": 900, "max_parallel_jobs": 2},+ }), encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ results = {"env_added": [], "config_added": [], "warnings": []}- run_migrations(44, results, quiet=True)++ run_migrations(45, results, quiet=True)+ raw = yaml.safe_load(config_path.read_text(encoding="utf-8"))+ assert "bot_chat_delivery_timeout_seconds" not in raw["cron"]+ assert raw["cron"]["max_parallel_jobs"] == 2+ assert any("bot_chat_delivery_timeout_seconds" in note for note in results["config_added"])+ assert "bot_chat_delivery_timeout_seconds" not in DEFAULT_CONFIG["cron"]++class TestCustomProviderCompatibility:"""Custom provider compatibility across legacy and v12+ config schemas.diff --cc tests/hermes_cli/test_config_guard_surfaces.pyindex 4c438b501bb,bc596b7f62c..b0c2824a0c0--- a/tests/hermes_cli/test_config_guard_surfaces.py+++ b/tests/hermes_cli/test_config_guard_surfaces.py@@@ -62,36 -62,12 +62,36 @@@ class TestCronRunJobGuardjob.update(overrides)return job- def test_run_job_fails_closed_on_corrupt_config(self, tmp_path):- from cron.scheduler import run_job+ @pytest.mark.asyncio+ async def test_run_job_fails_closed_on_corrupt_config(self, tmp_path):+ import json+ from types import SimpleNamespace- _write_corrupt_config(tmp_path)+ from gateway.session_contract import SessionRef+ from gateway.session_cron import current_execution, execute+ from hermes_state_registry import acquire, release- success, output_doc, final_response, error = run_job(self._job())+ _write_corrupt_config(tmp_path)+ # Agent-backed run_job is now a client. Exercise the scheduler's guard+ # through its owner entry, without launching a daemon or bypassing it.+ db = acquire(tmp_path / "state.db")+ ref = SessionRef("default", "cron-guard")+ db.create_session(ref.session_id, source="cron")+ owner = SimpleNamespace(db=db, pending_results={}, sessions={+ ref.session_id: SimpleNamespace(source=SimpleNamespace(user_id="cron-owner"))})+ admission = {"admission_id": "guard-fire", "request_id": "guard-fire",+ "principal_id": "cron-owner", "payload": {"text": ""}}+ policy = SimpleNamespace(request_json=json.dumps({+ "cron_job": self._job(), "extra_prompt": None, "request_id": "guard-fire"}))+ previous = current_execution()+ try:- with pytest.raises(RuntimeError, match="Refusing non-interactive startup"):++ with pytest.raises(RuntimeError, match="Hermes stopped because your settings file"):+ await execute(owner, ref, admission, policy)+ success, output_doc, final_response, error = owner.pending_results["guard-fire"]["result"]["cron_result"]+ assert current_execution() is previous+ assert not owner._cron_cancellations+ finally:+ release(db)assert success is Falseassert error is not Nonediff --cc tests/tools/test_bot_mode_dm.pyindex b3ba43409d9,963a294814a..2ce06d5ae60--- a/tests/tools/test_bot_mode_dm.py+++ b/tests/tools/test_bot_mode_dm.py@@@ -270,12 -232,12 +270,15 @@@ def _runner_author(command)return json.loads(parts[marker + 2])-def test_local_delivery_command_and_ack(tmp_path, monkeypatch):+def test_local_delivery_admits_canonically_and_acks(tmp_path, monkeypatch):calls = _capture_spawn(monkeypatch)+ # These assertions target the -p/turn-args shape; pin the entrypoint resolution+ # so the test stays hermetic across venvs that do/don't expose a sibling script.+ monkeypatch.setattr(bot_relay, "_hermes_cli", lambda: "hermes")home = _managed_home(tmp_path, teammates=("researcher",))+ target = home / "profiles" / "researcher"+ authority = _canonical_target(monkeypatch, target)+ monkeypatch.setattr(bot_mode_dm, "_dm_dir", lambda: tmp_path)agent = _FakeAgent(home, title="Bot Chat")result = json.loads(@@@ -379,6 -346,40 +384,43 @@@ def test_peer_delivery_command(tmp_pathassert transport_argv == ["hermes", "-p", "default", "peer", "dm", "spark"]+ def test_delivery_pins_the_hermes_entrypoint_beside_this_interpreter(tmp_path, monkeypatch):+ """A background delivery must not rely on PATH: the runner's service context+ lacks the gateway's venv bin dir, so a bare ``hermes`` resolves to a system+ install whose shebang picks the wrong interpreter and dies on import (#108628).+ Both transports must invoke the entrypoint beside this interpreter instead."""+ venv_bin = tmp_path / "venv" / ("Scripts" if sys.platform == "win32" else "bin")+ venv_bin.mkdir(parents=True)+ hermes_entry = venv_bin / ("hermes.exe" if sys.platform == "win32" else "hermes")+ hermes_entry.write_text("#!/bin/sh\n", encoding="utf-8")+ monkeypatch.setattr(sys, "executable", str(venv_bin / "python3"))++ calls = _capture_spawn(monkeypatch)+ home = _managed_home(tmp_path, teammates=("researcher",), peers=("spark",))++ _canonical_target(monkeypatch, home / "profiles" / "researcher")+ agent = _FakeAgent(home, title="Bot Chat")+++ # A local teammate is admitted through the profile authority (no inference child), but the++ # runner argv still names the pinned entrypoint so its basename-matched helpers stay compatible.+ result = json.loads(+ bot_mode_dm.message_agent_tool(target="researcher", message="ping", agent=agent)+ )- assert result["status"] == "sent"- mode, _dm_file, transport_argv = _runner_parts(calls[0]["command"])++ assert result["status"] == "queued"++ mode, _dm_file, transport_argv, _profile_home = _runner_parts(calls[0]["command"])+ assert mode == "query-file"+ assert transport_argv[0] == str(hermes_entry)+ assert transport_argv[1:] == ["-p", "researcher", "chat", "--in", "~", "-c", "Bot Chat",+ "--create-if-missing", "-Q"]++ result2 = json.loads(+ bot_mode_dm.message_agent_tool(target="spark", message="ping", agent=agent)+ )+ assert result2["status"] == "sent"- 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"]++def test_peer_delivery_author_carries_the_sender_hostname_and_local_stays_bare(tmp_path, monkeypatch):"""A peer dm crosses installs, so its author id is ``bot:<hostname>/<profile>``: the peer's own ``coder`` and aremote ``coder`` must not share one id. A teammate on this install still sees the bare ``bot:coder``."""@@@ -639,32 -673,6 +681,32 @@@ def test_delivery_main_child_env_carrieassert not dm_file.exists()[email protected]("author", [{"id": "bot:coder", "name": "coder", "is_bot": True}, None])+def test_local_runner_sends_only_argv_author_to_authority(tmp_path, monkeypatch, author):+ from agent.turn_author import TURN_AUTHOR_ENV++ target = tmp_path / "profiles" / "researcher"+ target.mkdir(parents=True)+ authority = _canonical_target(monkeypatch, target)+ dm_file = tmp_path / "message.txt"+ dm_file.write_text("hello", encoding="utf-8")+ monkeypatch.setenv(TURN_AUTHOR_ENV, json.dumps({"id": "bot:previous", "name": "previous", "is_bot": True}))+ monkeypatch.setattr(subprocess, "run", lambda *a, **k: pytest.fail("no local inference child"))+ waited = []- monkeypatch.setattr(bot_mode_dm, "_wait_live_dm", lambda home, key: waited.append((home, key)) or 0)++ monkeypatch.setattr(bot_mode_dm, "_wait_live_dm", lambda home, key, **_kw: waited.append((home, key)) or 0)+ command = bot_mode_dm._delivery_command(+ ["hermes", "-p", "researcher"], str(dm_file), stdin_file=False,+ profile_home=target, author=author,+ )+ assert bot_mode_dm._delivery_main(shlex.split(command)[2:]) == 0+ [(home, params)] = authority.calls+ assert home == target.resolve()+ assert params.get("author") == author+ assert params["message"] == "hello"+ assert waited == [(str(target.resolve()), params["id"])]+ assert dm_file.exists(), "local admission retains its evidence, not peer-child cleanup"++def test_real_delivery_command_round_trip_carries_author(tmp_path):"""Through a real subprocess, the runner argv built by ``_delivery_command`` sets HERMES_TURN_AUTHOR on the child."""dm_file = tmp_path / "message.txt"diff --cc tools/bot_live_delivery.pyindex 1c6f3b3047c,1ede6188444..530362fa3c6--- a/tools/bot_live_delivery.py+++ b/tools/bot_live_delivery.py@@@ -24,55 -25,36 +24,80 @@@ _OWNER_KEYS = ("profile_home", "session_TERMINAL = frozenset({"settled", "failed", "cancelled", "ambiguous"})-def find_canonical_owner(profile_home: Path | str) -> dict[str, Any] | None:- """Return the exact Bot Chat tip's lease, including unsupported CLI owners."""- from hermes_cli.active_sessions import active_session_registry_snapshot++def _bot_chat_tip(home: Path) -> str | None:++ """Current Bot Chat tip id, or None when the profile has no store or no Bot Chat yet."""+ from hermes_state import SessionDB+- home = Path(profile_home).resolve()- if not (home / "state.db").is_file():++ if not (home / 'state.db').is_file():+ return None- db = SessionDB(db_path=home / "state.db", read_only=True)++ db = SessionDB(db_path=home / 'state.db', read_only=True)+ try:- row = db.get_session_by_title("Bot Chat")- session_id = db.get_compression_tip(row["id"]) if row else None++ row = db.get_session_by_title('Bot Chat')++ return db.get_compression_tip(row['id']) if row else None+ finally:+ db.close()++++++def find_canonical_owner(profile_home: Path | str) -> dict[str, Any] | None:++ """Return the exact Bot Chat tip's active-session lease, including unsupported CLI owners.++++ A CLI process holding the tip live cannot consume authority deliveries (the door refuses with++ ``runtime_coordination_required``); cron uses this to retain output until that owner releases."""++ from hermes_cli.active_sessions import active_session_registry_snapshot++++ home = Path(profile_home).resolve()++ session_id = _bot_chat_tip(home)+ if not session_id:+ return None+ for entry in active_session_registry_snapshot(registry_home=home):+ if entry["session_id"] == session_id:+ return {**entry, "profile_home": str(home)}+ return None++def find_canonical_live_owner(profile_home: Path | str) -> dict[str, Any] | None:- """Only advertised consumers may receive owner-pinned mailbox deliveries."""- entry = find_canonical_owner(profile_home)- meta = (entry or {}).get("metadata") or {}- if entry and meta.get("bot_live_delivery_consumer") is True and meta.get("live_session_id"):- return {key: entry[key] for key in ("profile_home", "session_id", "lease_id")} | {- "live_session_id": meta["live_session_id"]}- return None+ """Discover the profile authority and its exact Bot Chat without acquiring a lease.++ ``session_id`` is the current Bot Chat tip, or ``''`` when the profile has none yet: the+ authority's deliver door creates it on first delivery (main's ``--create-if-missing``),+ so a missing chat is not a refusal. None only when the profile has no store at all."""+ from hermes_cli.gateway_runtime import discover_gateway_endpoint- from hermes_state import SessionDB++ home = Path(profile_home).resolve()+ discovery = discover_gateway_endpoint(home, timeout=5)+ if discovery.state != 'ready' or discovery.endpoint is None:+ raise ValueError('profile authority is not ready')+ if not (home / 'state.db').is_file():+ return None- db = SessionDB(db_path=home / 'state.db', read_only=True)- try:- row = db.get_session_by_title('Bot Chat')- tip = db.get_compression_tip(row['id']) if row else None- finally:- db.close()++ tip = _bot_chat_tip(home)+ return dict(profile_home=str(home), session_id=tip or '', canonical=True,+ lease_id=discovery.endpoint.instance_id, live_session_id=tip or '')+++def authority_delivery(home, params):+ """Call only this home's already-running authority; never start a fallback."""+ import asyncio+ from hermes_cli.gateway_runtime import discover_gateway_endpoint+ from hermes_cli.gateway_client import GatewayClient, _session_ticket+ from websockets.asyncio.client import connect++ home = Path(home).resolve()++ async def request():+ discovery = await asyncio.to_thread(discover_gateway_endpoint, home, timeout=5)+ if discovery.state != 'ready' or discovery.endpoint is None:+ raise ValueError('profile authority is not ready')+ endpoint = discovery.endpoint+ ticket = await asyncio.to_thread(_session_ticket, home, endpoint)+ url = endpoint.api_origin.replace('http:', 'ws:').replace('https:', 'wss:') + '/api/ws'+ async with connect(url, subprotocols=['hermes-gateway-v1', 'hermes-gateway-ticket.' + ticket],+ open_timeout=10) as ws:+ if ws.subprotocol != 'hermes-gateway-v1':+ raise ValueError('authority protocol mismatch')+ async with GatewayClient(ws) as client:+ return await client.rpc('bot_relay.deliver', **params)++ return asyncio.run(request())def _owner(home: Path | str, owner: dict[str, Any]) -> dict[str, str]:diff --cc tools/bot_mode_dm.pyindex 9b089c18c5b,6bd9ebd62d3..eafa41d46b8--- a/tools/bot_mode_dm.py+++ b/tools/bot_mode_dm.py@@@ -444,15 -530,14 +472,15 @@@ def _run_delivery(argv: list[str], dm_f"evidence_file": dm_file}))return 1if record is not None:- return _wait_live_dm(record["profile_home"], record["delivery_id"])+ return _wait_live_dm(record["profile_home"], record["delivery_id"], dm_file=dm_file)+ if not stdin_file:+ print(json.dumps({"reason": "runtime_unavailable", "error": "No canonical Bot Chat authority; payload retained."}))+ return 1try:from tools.bot_relay import delivery_env- env = delivery_env(author)+ env = delivery_env(author, profile_home if not stdin_file else None)with _delivery_lock(argv, stdin_file=stdin_file):- if not stdin_file:- return _run_local_turn(argv, dm_file, env=env)# Keep the file open until the transport exits; cleanup occurs# after subprocess.run returns, not merely after stdin reaches EOF.with open(dm_file, "r", encoding="utf-8") as stream:diff --cc tools/mcp_tool.pyindex 4f80fa12c67,f0dd90813fb..4694d15acbc--- a/tools/mcp_tool.py+++ b/tools/mcp_tool.py@@@ -637,13 -637,14 +637,19 @@@ def _update_death_supervisor(verb: strdef _mcp_registry_scope() -> Optional[str]:- """Registry scope for MCP registrations: a profile overlay under a multiplexer, else None."""- """Registry scope for MCP registrations: a profile overlay when this process serves profiles,- else None. Under ``gateway.multiplex_profiles`` every turn runs scoped; a process that serves a- routed profile through the HERMES_HOME override (dashboard/desktop backend, per-profile cron- ticker) is a multiplexer too, even with the flag off — keying its connections by the bare name- would hand one profile's credentialed connection to every other served profile (#111151).- Single-profile processes (no override, or an override naming their own home) keep bare names."""++ """Registry scope for MCP registrations: the session's own tool scope when one is bound, else a++ profile overlay when this process serves profiles, else None. Under ``gateway.multiplex_profiles``++ every turn runs scoped; a process that serves a routed profile through the HERMES_HOME override++ (dashboard/desktop backend, per-profile cron ticker) is a multiplexer too, even with the flag++ off — keying its connections by the bare name would hand one profile's credentialed connection++ to every other served profile (#111151). Single-profile processes (no override, or an override++ naming their own home) keep bare names."""+ from tools.registry import current_session_tool_scope+ session_scope = current_session_tool_scope()+ if session_scope is not None:+ return session_scope- from agent.secret_scope import is_multiplex_active- if not is_multiplex_active():+ from agent.secret_scope import serves_routed_profile+ if not serves_routed_profile():return Nonefrom tools.registry import registryreturn registry.current_scope_key()diff --cc tools/registry.pyindex bcb5dd9e2d6,aca8baa4c42..629a5f1000d--- a/tools/registry.py+++ b/tools/registry.py@@@ -107,16 -97,7 +116,16 @@@ def discover_builtin_tools(tools_dir: Oper-file AST scan costs ~145 ms over ~100 files, so verdicts are memoized on disk keyedby ``(mtime_ns, size)``; a mismatch or corrupt cache re-scans that file. The write isbest-effort and atomic, so concurrent processes race harmlessly."""+ from agent.safe_worker_policy import safe_worker_enabled+ if safe_worker_enabled():+ # Toolset filtering happens AFTER import. Keep the troubleshooting worker's+ # import graph closed over reviewed core tools, not plugin-backed wrappers+ # or a profile-writable discovery cache. Core approval/redaction stay intact.+ module_names = ["tools.file_tools", "tools.terminal_tool", "tools.process_registry"]+ for module_name in module_names:+ importlib.import_module(module_name)+ return module_names- tools_path = Path(tools_dir) if tools_dir is not None else Path(__file__).resolve().parent+ tools_path = (Path(tools_dir) if tools_dir is not None else Path(__file__).resolve().parent).resolve()cache = _load_discovery_cache()fresh_cache: Dict[str, list] = {}cache_dirty = Falsediff --cc tools/session_search_tool.pyindex 81ba3d31fbf,1b7e60344ad..02dec5b95d0--- a/tools/session_search_tool.py+++ b/tools/session_search_tool.py@@@ -470,8 -563,27 +563,9 @@@ def _scroll(db, session_id: str, arounddef _dispatch(query, role_filter, limit, db, current_session_id, session_id,- around_message_id, window, sort, profile, detail) -> str:- around_message_id, window, sort, profile, detail, owned_dbs,++ around_message_id, window, sort, profile, detail,+ after=None, before=None, exclude_session_ids=None) -> str:- """Mode dispatch (see module docstring); scroll wins when an anchor is set.- Profile DBs opened here are appended to *owned_dbs* for the caller to close."""- # A raw `@session:<profile>/<id>` link as session_id: ids never contain "/", so- # split on it and adopt the embedded profile only when none was passed.- if isinstance(session_id, str) and "/" in session_id:- emb_profile, _, emb_id = session_id.partition("/")- if emb_id:- session_id = emb_id- if emb_profile and (profile is None or not str(profile).strip()):- profile = emb_profile- # Cross-profile: swap in the named profile's DB (read-only) for every shape;- # current-lineage guards key off ids that won't collide, so they stay inert.- try:- profile_db = _resolve_profile_db(profile)- except Exception as e:- return tool_error(f"profile '{profile}': {e}", success=False)- if profile_db is not None:- db, current_session_id = profile_db, None- owned_dbs.append(profile_db)+ """Mode dispatch (see module docstring); scroll wins when an anchor is set."""if isinstance(session_id, str) and session_id.strip():if around_message_id is not None:return _scroll(db, session_id.strip(), around_message_id, window, current_session_id)@@@ -489,40 -606,22 +588,43 @@@def session_search(query: str = "", role_filter: str = None, limit: int = 3, db=None,current_session_id: str = None, session_id: str = None, around_message_id: int = None,- window: int = 5, sort: str = None, profile: str = None, detail: str = "adaptive") -> str:- """Run session search, closing DBs opened here. Positional order is frozen for old callers."""+ window: int = 5, sort: str = None, profile: str = None, detail: str = "adaptive",+ after: str = None, before: str = None, exclude_session_ids: Optional[List[str]] = None) -> str:+ """Run session search, closing DBs opened here. Positional order is frozen for old callers;+ new parameters are appended after ``detail``."""- from hermes_state import format_session_db_unavailable- from hermes_state_registry import acquire, release_or_close+ from hermes_constants import get_hermes_home+ from hermes_state import SessionDB, format_session_db_unavailable+ from hermes_state_registry import release_or_closeowned_dbs: List[Any] = []+ # A raw `@session:<profile>/<id>` link as session_id: ids never contain "/", so+ # split on it and adopt the embedded profile only when none was passed.+ if isinstance(session_id, str) and "/" in session_id:+ emb_profile, _, emb_id = session_id.partition("/")+ if emb_id:+ session_id = emb_id+ if emb_profile and (profile is None or not str(profile).strip()):+ profile = emb_profile+ # Cross-profile: swap in the named profile's DB (read-only) for every shape;+ # current-lineage guards key off ids that won't collide, so they stay inert.+ try:+ profile_db = _resolve_profile_db(profile)+ except Exception as e:+ return tool_error(f"profile '{profile}': {e}", success=False)+ if profile_db is not None:+ db, current_session_id = profile_db, None+ owned_dbs.append(profile_db)if db is None:- db = _quiet(acquire, None, "SessionDB unavailable for session_search")+ db = _quiet(+ lambda: SessionDB(db_path=get_hermes_home() / "state.db", read_only=True),+ None, "SessionDB unavailable for session_search",+ )if db is None:return tool_error(format_session_db_unavailable(), success=False)owned_dbs.append(db)try:return _dispatch(query, role_filter, limit, db, current_session_id, session_id,- around_message_id, window, sort, profile, detail)- around_message_id, window, sort, profile, detail, owned_dbs,++ around_message_id, window, sort, profile, detail,+ after=after, before=before, exclude_session_ids=exclude_session_ids)finally:for owned_db in reversed(owned_dbs):_quiet(lambda: release_or_close(owned_db), None, "Failed to close session_search SessionDB")diff --cc tui_gateway/agent_factory.pyindex c1cc9dace80,00000000000..5b21d86a298mode 100644,000000..100644--- a/tui_gateway/agent_factory.py+++ b/tui_gateway/agent_factory.py@@@ -1,552 -1,0 +1,556 @@@+"""TUI agent_factory seam; functions bind to the server namespace at registration."""++from __future__ import annotations++from .method_ctx import bind_module++def _env_model_seed() -> str:+ """The launch-scoped model seed (``hermes --tui -m``, hosted provisioning); "" when unset."""+ return (os.environ.get("HERMES_MODEL", "") or os.environ.get("HERMES_INFERENCE_MODEL", "")).strip()+++def _resolve_model() -> str:+ if env := _env_model_seed():+ return env+ m = _load_cfg().get("model", "")+ if isinstance(m, dict):+ return str(m.get("default", "") or "").strip()+ if isinstance(m, str) and m:+ return m.strip()+ # No env seed / config preference: the cost-safe silent default (cache-only read), never an unpicked flagship.+ with contextlib.suppress(Exception):+ from hermes_cli.models import get_preferred_silent_default_model+ return get_preferred_silent_default_model()+ return "z-ai/glm-5.2"+++def _resolve_session_platform() -> str:+ """``HERMES_DESKTOP=1`` without ``HERMES_DESKTOP_TERMINAL`` → "desktop" (chat panel; the agent then+ suggests TUI-only slash commands), else "tui" (embedded terminal pane or standalone ``hermes --tui``)."""+ desktop = is_truthy_value(os.environ.get("HERMES_DESKTOP"))+ return "desktop" if desktop and not is_truthy_value(os.environ.get("HERMES_DESKTOP_TERMINAL")) else "tui"+++def _resolve_session_source(explicit: str | None) -> str:+ """Session DB ``source``: an explicit caller value (plugin session tagged ``"telegram"``) is never+ rewritten; only empty/None falls back to the env-resolved platform."""+ return explicit or _resolve_session_platform()+++def _resolve_agent_platform(source: str | None) -> str:+ return _resolve_session_source(source)+++def _config_model_target() -> tuple[str, str]:+ """(model, provider) selected by config.yaml — and ONLY config: the HERMES_MODEL launch seed fed into+ the per-turn sync would be replayed as a /model switch and persisted globally, or pin the session so+ dashboard/CLI model changes never reach an open chat. Empty model = "no preference" → no-op sync."""+ cfg_model = _load_cfg().get("model")+ if isinstance(cfg_model, dict):+ provider = str(cfg_model.get("provider") or "").strip()+ return str(cfg_model.get("default", "") or "").strip(), "" if provider.lower() == "auto" else provider+ return (cfg_model.strip() if isinstance(cfg_model, str) else ""), ""+++def _resolve_startup_runtime() -> tuple[str, str | None]:+ model = _resolve_model()+ if explicit_provider := os.environ.get("HERMES_TUI_PROVIDER", "").strip():+ return model, explicit_provider+ if not (explicit_model := _env_model_seed()):+ return model, None+ with contextlib.suppress(Exception):+ from hermes_cli.models import detect_static_provider_for_model+ cfg = _load_cfg().get("model") or {}+ current_provider = ((str(cfg.get("provider") or "").strip().lower() if isinstance(cfg, dict) else "")+ or os.environ.get("HERMES_INFERENCE_PROVIDER", "").strip().lower() or "auto")+ if detected := detect_static_provider_for_model(explicit_model, current_provider):+ provider, detected_model = detected+ return detected_model, provider+ return model, None+++# Bare billing buckets are not routable provider identities; restoring one as a session provider override+# breaks resume. ``openrouter`` is deliberately NOT in this set (fully routable; agent_init's gate is a different set).+# (agent_init's fail-fast gate is a DIFFERENT set that also skips "openrouter" — there it means "default+# route, don't fail fast", not "unroutable".) ``openrouter`` is deliberately excluded here — it is a fully+# routable provider with its own API key and base_url. Sessions that used OpenRouter store+# ``billing_provider="openrouter"``; dropping it forces resume to the current global model (e.g. a custom+# endpoint), which is the wrong provider for the stored model. See #57588.+++def _is_routable_provider(provider: str) -> bool:+ with contextlib.suppress(Exception):+ from hermes_cli.runtime_provider import is_routable_provider+ return is_routable_provider(provider)+ return False+++def _overrides_have_routable_provider(overrides: dict) -> bool:+ """Whether persisted runtime overrides still name a routable provider (renamed/removed → "Unknown+ provider" at agent init). Empty = NOT routable, so the caller falls back to the session's picked model."""+ provider = str(overrides.get("provider_override") or "").strip()+ if not provider:+ provider = str((overrides.get("model_override") or {}).get("provider") or "").strip()+ return bool(provider) and _is_routable_provider(provider)+++def _parse_model_config(raw, *, quiet: bool = False) -> dict:+ """A row's ``model_config`` (dict or JSON text) as a dict; ``{}`` when absent/invalid."""+ if isinstance(raw, dict):+ return raw+ if isinstance(raw, str) and raw.strip():+ try:+ parsed = json.loads(raw)+ return parsed if isinstance(parsed, dict) else {}+ except Exception:+ if not quiet:+ raise+ logger.debug("failed to parse stored session model_config", exc_info=True)+ return {}+++def _stored_session_runtime_overrides(row: dict | None) -> dict:+ """Runtime fields persisted with a stored session (model column, ``billing_provider``, JSON ``model_config``):+ resume restores the model/provider/reasoning THAT chat used, not the global pick. Plugin-owned Bot-Mode+ sessions are exempt and rebuild from the member profile's CURRENT config (a stale provider pin left+ room bots "out of Nous credits" after a profile switch); signals: ``room_plumbing`` /+ ``follow_profile_config`` markers, the legacy hidden + "Group:" title, the title exactly "Bot Chat"."""+ if not row:+ return {}+ model_config = _parse_model_config(row.get("model_config"), quiet=True)+ _row_title = str(row.get("title") or "").strip()+ if (model_config.get("room_plumbing") or (row.get("hidden") and _row_title.startswith("Group:"))+ or model_config.get("follow_profile_config") or _row_title == "Bot Chat"):+ return {}+ overrides: dict = {}+ field = lambda k: str(model_config.get(k) or "").strip()+ model = str(row.get("model") or model_config.get("model") or "").strip()+ # ``billing_provider`` is only the billing bucket — for a custom endpoint the bare class "custom", which+ # agent_init treats as non-routable. Only restore an explicit provider; else resume uses the configured default.+ provider = field("provider")+ billing_provider = str(model_config.get("billing_provider") or row.get("billing_provider") or "").strip()+ if not provider and billing_provider.lower() not in _BARE_BILLING_PROVIDERS:+ provider = billing_provider+ base_url, api_mode, service_tier = field("base_url"), field("api_mode"), field("service_tier")+ reasoning_config = model_config.get("reasoning_config")+ # Heal a stale provider persisted by an older build (renamed/removed custom provider → "Unknown provider"):+ # recover ``custom:<name>`` from the stored base_url, then from the entry serving the model; else drop it.+ if provider and not _is_routable_provider(provider):+ healed = None+ try:+ from hermes_cli.runtime_provider import canonical_custom_identity+ healed = canonical_custom_identity(base_url=base_url or None, model=model or None)+ except Exception:+ logger.debug("custom provider identity recovery failed", exc_info=True)+ if healed:+ logger.info("healed stale session provider %r to %r", provider, healed)+ provider = healed+ base_url = "" # the healed identity owns a registered endpoint; the snapshot URL must not override it+ else:+ provider = ""+ if model:+ # Same dict-shaped override live /model switches use, so a DB-restored session keeps custom endpoint+ # metadata across resume and rebuilds (/new). Raw api_key is never persisted/restored.+ overrides["model_override"] = {+ "model": model, "provider": provider or None, "base_url": base_url or None, "api_mode": api_mode or None}+ if provider:+ overrides["provider_override"] = provider+ if isinstance(reasoning_config, dict):+ overrides["reasoning_config_override"] = reasoning_config+ if service_tier: # None = "inherit the profile" at _make_agent; "" = real override "no priority tier"+ overrides["service_tier_override"] = "" if service_tier.lower() == "normal" else service_tier+ return overrides+++def _runtime_model_config(agent, existing: dict | None = None) -> dict:+ """Merge the agent's CURRENT runtime identity onto the row's persisted ``model_config``. Falsy agent+ attributes DELETE the key rather than skip the write: resume reads provider/endpoint from this JSON+ (model column written separately), so a stale provider would route the resumed chat to the wrong endpoint."""+ config = dict(existing or {})+ attr = lambda k: str(getattr(agent, k, "") or "").strip()+ model, provider, base_url = attr("model"), attr("provider"), attr("base_url")+ if provider.lower() == "custom":+ # ``agent.provider`` resolves every named custom entry to the literal "custom", losing the entry+ # identity (api_key is never persisted): recover ``custom:<name>`` from the endpoint URL.+ try:+ from hermes_cli.runtime_provider import canonical_custom_identity+ provider = canonical_custom_identity(base_url=base_url, model=model or None) or provider+ except Exception:+ logger.debug("custom provider identity lookup failed", exc_info=True)+ reasoning_config = getattr(agent, "reasoning_config", None)+ live = {+ "model": model, "provider": provider, "base_url": base_url, "api_mode": attr("api_mode"),+ # An empty dict is still a real (present) reasoning config.+ "reasoning_config": reasoning_config if isinstance(reasoning_config, dict) else None,+ "service_tier": getattr(agent, "service_tier", None),+ }+ for key, value in live.items():+ if value or isinstance(value, dict):+ config[key] = value+ else:+ config.pop(key, None)+ return config+++def _persist_live_session_runtime(session: dict | None) -> None:+ """Persist active session runtime so future resumes restore the same footer."""+ live = _live_session_agent_db(session)+ if live is None:+ return+ agent, session_key, db = live+ try:+ row = db.get_session(session_key) or {}+ model_config = _runtime_model_config(agent, _parse_model_config(row.get("model_config")))+ if (tier_override := session.get("create_service_tier_override")) is not None:+ # agent.service_tier is None for explicit normal; without this the distinction is erased on every persist.+ model_config["service_tier"] = tier_override or "normal"+ model = str(getattr(agent, "model", "") or "").strip()+ if hasattr(db, "update_session_meta"):+ db.update_session_meta(session_key, json.dumps(model_config), model or None)+ elif model and hasattr(db, "update_session_model"):+ db.update_session_model(session_key, model)+ except Exception:+ logger.debug("failed to persist live session runtime", exc_info=True)++def _load_approval_mode() -> str:+ """Effective ``approvals.mode`` via the gate's own ``_get_approval_mode`` (a raw re-read missed the+ managed overlay and ``${VAR}`` expansion)."""+ from tools.approval_context import _get_approval_mode+ mode = _get_approval_mode()+ return mode if mode in _APPROVAL_MODES else "manual"+++def _coerce_statusbar(raw) -> str:+ if raw is False:+ return "off"+ return s if isinstance(raw, str) and (s := raw.strip().lower()) in _STATUSBAR_MODES else "top"+++_MOUSE_TRACKING_ALIASES = {+ "0": "off", "1": "all", "all": "all", "any": "all", "button": "buttons", "buttons": "buttons",+ "click": "buttons", "false": "off", "full": "all", "no": "off", "off": "off", "on": "all",+ "scroll": "wheel", "true": "all", "wheel": "wheel", "yes": "all",+}+++def _display_mouse_tracking(display: dict) -> str:+ """display.mouse_tracking → ``off|wheel|buttons|all`` (bools: True → all, False → off); ``wheel`` (DEC+ 1000+1006) is the tmux-friendly subset without hover events. Legacy ``tui_mouse`` only when ``mouse_tracking`` is absent."""+ if not isinstance(display, dict):+ return "all"+ raw = display.get("mouse_tracking") if "mouse_tracking" in display else display.get("tui_mouse", True)+ if isinstance(raw, str):+ return _MOUSE_TRACKING_ALIASES.get(raw.strip().lower(), "all")+ return "off" if raw is False or raw == 0 else "all"+++def _load_reasoning_config(model: str = "") -> dict | None:+ """Via the shared chokepoint :func:`hermes_constants.resolve_reasoning_config` (per-model override >+ global ``agent.reasoning_effort``; YAML False = disabled).++ Closes #21256.+ """+ from hermes_constants import resolve_reasoning_config+ return resolve_reasoning_config(_load_cfg(), model)+++_SERVICE_TIER_ALIASES = {"fast": "priority", "priority": "priority", "on": "priority", "auto": "auto", "cold": "cold"}+++def _load_service_tier() -> str | None:+ raw = str((_load_cfg().get("agent") or {}).get("service_tier", "") or "").strip().lower()+ return _SERVICE_TIER_ALIASES.get(raw)+++def _load_provider_routing() -> dict:+ """OpenRouter ``provider_routing`` prefs (gateway/CLI parity — without them OpenRouter picks an effectively random provider)."""+ with contextlib.suppress(Exception):+ return _load_cfg().get("provider_routing", {}) or {}+ return {}+++def _load_show_reasoning() -> bool:+ # Fallback True — keep in sync with DEFAULT_CONFIG display.show_reasoning (no DEFAULT_CONFIG merge here).+ return bool(_display_cfg().get("show_reasoning", True))+++def _load_memory_notifications() -> str:+ """``display.memory_notifications`` (``off`` / ``on`` default / ``verbose``; bool normalized) — gates the+ "💾 Self-improvement review" summary (gateway/CLI parity)."""+ raw = _display_cfg().get("memory_notifications")+ if isinstance(raw, bool):+ return "on" if raw else "off"+ return str(raw).lower() if raw else "on"+++_TOOL_PROGRESS_MODES = frozenset({"off", "new", "all", "verbose"})+++def _load_tool_progress_mode() -> str:+ env = os.environ.get("HERMES_TUI_TOOL_PROGRESS", "").strip().lower()+ if env in _TOOL_PROGRESS_MODES:+ return env+ raw = _display_cfg().get("tool_progress", "all")+ if isinstance(raw, bool):+ return "all" if raw else "off"+ mode = str(raw or "all").strip().lower()+ return mode if mode in _TOOL_PROGRESS_MODES else "all"+++def _gui_surface_toolsets(platform: str) -> set[str]:+ """Toolsets that exist because of the CLIENT (both off ``_HERMES_CORE_TOOLS``; this is the one gate).+ ``platform`` is the SESSION's source, never a process env var: the desktop may drive a URL/cloud+ backend where ``HERMES_DESKTOP`` is unset (AGENTS.md surface rule)."""+ return {"project", "desktop_ui"} if platform == "desktop" else {"project"}+++def _tui_notice(text: str) -> None:+ print(text, file=sys.stderr, flush=True)+++def _resolve_explicit_toolsets(explicit: list[str], validate_toolset) -> list[str] | None | bool:+ """Resolve a HERMES_TUI_TOOLSETS pin: list, None for "all", False when nothing was valid."""+ built_in = [name for name in explicit if validate_toolset(name)]+ unresolved = [name for name in explicit if name not in built_in]+ if unresolved:+ try:+ from hermes_cli.plugins import discover_plugins+ discover_plugins()+ plugin_valid = [name for name in unresolved if validate_toolset(name)]+ except Exception:+ plugin_valid = []+ built_in.extend(plugin_valid)+ unresolved = [name for name in unresolved if name not in plugin_valid]+ if any(name in {"all", "*"} for name in built_in):+ if ignored := [name for name in explicit if name not in {"all", "*"}]:+ _tui_notice(f"[tui] HERMES_TUI_TOOLSETS=all enables every toolset; ignoring additional entries: {', '.join(ignored)}")+ return None+ if not unresolved:+ return built_in+ try: # (enabled, disabled) MCP server names from raw config; both empty on any failure+ from hermes_cli.config import read_raw_config+ from hermes_cli.tools_config import _parse_enabled_flag+ raw_cfg = read_raw_config()+ mcp_servers = raw_cfg.get("mcp_servers") if isinstance(raw_cfg.get("mcp_servers"), dict) else {}+ mcp_names, mcp_disabled = set(), set()+ for name, server_cfg in mcp_servers.items():+ if isinstance(server_cfg, dict):+ on = _parse_enabled_flag(server_cfg.get("enabled", True), default=True)+ (mcp_names if on else mcp_disabled).add(str(name))+ except Exception:+ mcp_names, mcp_disabled = set(), set()+ mcp_valid = [name for name in unresolved if name in mcp_names]+ disabled = [name for name in unresolved if name in mcp_disabled]+ unknown = [name for name in unresolved if name not in mcp_names and name not in mcp_disabled]+ if unknown:+ _tui_notice(f"[tui] ignoring unknown HERMES_TUI_TOOLSETS entries: {', '.join(unknown)}")+ if disabled:+ _tui_notice("[tui] ignoring disabled MCP servers in HERMES_TUI_TOOLSETS "+ f"(set enabled: true in config.yaml to use): {', '.join(disabled)}")+ return (built_in + mcp_valid) or False+++def _load_enabled_toolsets(platform: str | None = None) -> list[str] | None:+ """The agent's toolsets for this session (None = all): an explicit HERMES_TUI_TOOLSETS pin; else the+ coding posture (coding_context collapses to coding toolset + enabled MCP servers in a code workspace);+ else the configured CLI toolsets. Client-surface toolsets fold in here — only this surface can answer them."""+ session_platform = platform or _resolve_session_platform()+ explicit = [item.strip() for item in os.environ.get("HERMES_TUI_TOOLSETS", "").split(",") if item.strip()]+ fallback_notice = None+ if not explicit:+ with contextlib.suppress(Exception):+ from agent.coding_context import coding_selection+ selection = coding_selection(platform=session_platform)+ if selection is not None:+ return sorted({*selection, *_gui_surface_toolsets(session_platform)})+ try:+ from toolsets import validate_toolset+ except Exception:+ validate_toolset = None+ if explicit and validate_toolset is not None:+ resolved = _resolve_explicit_toolsets(explicit, validate_toolset)+ if resolved is not False:+ return resolved+ fallback_notice = "[tui] no valid HERMES_TUI_TOOLSETS entries; using configured CLI toolsets"+ try:+ from hermes_cli.config import load_config+ from hermes_cli.tools_config import _get_platform_tools+ cfg = load_config()+ # include_default_mcp_servers=True is the runtime variant (the agent must be able to call+ # default MCP servers); the config-editing variant would silently drop MCP tools from the TUI.+ # Passing ``False`` here is the config-editing variant — used when we need to persist a toolset list+ # without baking in implicit MCP defaults. Using the wrong variant at agent creation time makes MCP+ # tools silently missing from the TUI. See PR #3252 for the original design split.+ enabled = _get_platform_tools(cfg, "cli", include_default_mcp_servers=True)+ if fallback_notice is not None:+ _tui_notice(fallback_notice)+ return sorted(enabled | _gui_surface_toolsets(session_platform)) if enabled else None+ except Exception:+ if fallback_notice is not None:+ _tui_notice("[tui] no valid HERMES_TUI_TOOLSETS entries and configured CLI toolsets could not be loaded; enabling all toolsets")+ return None+++def _session_tool_progress_mode(sid: str) -> str:+ return str(_sessions.get(sid, {}).get("tool_progress_mode", "all") or "all")+++def _session_verbose(sid: str) -> bool:+ return _session_tool_progress_mode(sid) == "verbose"+++def _tool_progress_enabled(sid: str) -> bool:+ return _session_tool_progress_mode(sid) != "off"+++def _tool_lifecycle_required_for_ui(name: str) -> bool:- """Interactive UI, not optional chrome: Desktop renders clarify / setup_mcp cards from the tool-call part."""- return name in ("clarify", "setup_mcp")++ """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 resolve_entry_api_key++ 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)+ logging.getLogger(__name__).warning(+ "Primary auth failed (%s), falling back to %s model %s", primary_exc, fb_provider, fb_model)+ return _RuntimeFallbackResolution(runtime, fb_model, True)+ except Exception:+ continue+ raise+++def _resolve_agent_model_runtime(model_override, provider_override) -> tuple[str, dict]:+ """(model, runtime) for a new agent; a per-session override (/model switch or a resumed row's persisted+ runtime) wins over global config/env. Older rows stored the resolved provider "custom" (no named entry+ matches) — recover the identity from the persisted base_url or the rebuild fails "No LLM provider+ configured". Persisted base_url/api_key/api_mode are honored only for the original runtime, never a fallback."""+ if isinstance(model_override, dict) and model_override.get("model"):+ model = str(model_override.get("model") or "")+ requested_provider = model_override.get("provider") or provider_override or None+ override_base_url = model_override.get("base_url")+ resolve_kwargs = {}+ if str(requested_provider or "").strip().lower() == "custom":+ from hermes_cli.runtime_provider import canonical_custom_identity+ if recovered := canonical_custom_identity(base_url=override_base_url or None, model=model or None):+ requested_provider = recovered+ if override_base_url:+ # Failing identity recovery, still hand base_url to the direct-alias branch so pool/env credentials resolve.+ resolve_kwargs["explicit_base_url"] = override_base_url+ resolve_kwargs.update(requested=requested_provider, target_model=model or None)+ overrides = {k: model_override.get(k) for k in ("base_url", "api_key", "api_mode")}+ else:+ model, requested_provider = _resolve_startup_runtime()+ if isinstance(model_override, str) and model_override:+ model = model_override+ if provider_override:+ requested_provider = provider_override+ resolve_kwargs = {"requested": requested_provider, "target_model": model or None}+ overrides = {}+ resolution = _resolve_runtime_with_fallback(resolve_kwargs)+ if resolution.used_fallback:+ if not resolution.selected_model:+ raise RuntimeError("Auth fallback resolved without a model")+ return resolution.selected_model, resolution.runtime+ resolution.runtime.update({k: v for k, v in overrides.items() if v})+ return model, resolution.runtime+++def _startup_system_prompt(cfg: dict, task_id: str) -> str:+ """Config ephemeral system prompt + HERMES_TUI_SKILLS preload block. Hard-fails only when EVERY requested+ skill is missing (cli.py parity): a typo'd name must not auto-block the Kanban task."""+ from hermes_cli.config import resolve_ephemeral_system_prompt_from_config+ system_prompt = resolve_ephemeral_system_prompt_from_config(cfg)+ startup_skills = _parse_tui_skills_env()+ if not startup_skills:+ return system_prompt+ from agent.skill_commands import build_preloaded_skills_prompt+ skills_prompt, loaded_skills, missing_skills = build_preloaded_skills_prompt(startup_skills, task_id=task_id)+ if missing_skills:+ missing_display = ", ".join(missing_skills)+ if not loaded_skills:+ raise ValueError(f"Unknown skill(s): {missing_display}")+ logger.warning("Unknown skill(s) requested, skipping: %s. Continuing with: %s. "+ "List available skills with `hermes skills list`.", missing_display, ", ".join(loaded_skills))+ if skills_prompt:+ system_prompt = "\n\n".join(part for part in (system_prompt, skills_prompt) if part).strip()+ return system_prompt+++def _make_agent(+ sid: str, key: str, session_id: str | None = None, session_db=None,+ model_override: dict | str | None = None, provider_override: str | None = None,+ reasoning_config_override: dict | None = None, service_tier_override: str | None = None,+ platform_override: str | None = None, context_cwd_is_launch_artifact: bool | None = None,- auth_user_id: str | 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)+ _pr = _load_provider_routing()+ platform = _resolve_agent_platform(platform_override)+ ignore_rules = is_truthy_value(os.environ.get("HERMES_IGNORE_RULES"))+ with _sessions_lock:+ session = _sessions.get(sid)+ agent = AIAgent(+ model=model, max_iterations=_cfg_max_turns(cfg, 500), provider=runtime.get("provider"),+ base_url=runtime.get("base_url"), api_key=runtime.get("api_key"), api_mode=runtime.get("api_mode"),+ acp_command=runtime.get("command"), acp_args=runtime.get("args"),+ credential_pool=runtime.get("credential_pool"), quiet_mode=True,+ verbose_logging=False, # DEBUG agent logging; independent of tool_progress_mode+ reasoning_config=(+ reasoning_config_override if reasoning_config_override is not None else _load_reasoning_config(str(model or ""))),+ service_tier=service_tier_override if service_tier_override is not None else _load_service_tier(),+ enabled_toolsets=_load_enabled_toolsets(platform),+ # OpenRouter provider_routing prefs (gateway + CLI parity).+ providers_allowed=_pr.get("only"), providers_ignored=_pr.get("ignore"), providers_order=_pr.get("order"),+ provider_sort=_pr.get("sort"), provider_require_parameters=_pr.get("require_parameters", False),+ provider_data_collection=_pr.get("data_collection"), platform=platform, session_id=session_id or key,++ 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)+ return agent+++def register(server):+ bind_module(globals(), server)diff --cc tui_gateway/methods_config.pyindex 543af5fdd10,c0ed5086590..9b33f3a46d9--- a/tui_gateway/methods_config.py+++ b/tui_gateway/methods_config.py@@@ -292,16 -295,49 +295,28 @@@ def _(rid, params: dict) -> dict@method("setup.runtime_check")def _(rid, params: dict) -> dict:- """Strict provider check via the same resolve_runtime_provider() the agent uses on session- creation (setup.status is True if ANY provider auth state is discoverable): ok=False + the auth- error when the model can't be served, so UIs surface onboarding before a doomed prompt.- ``profile`` answers for THAT profile's pin and ``.env``; unknown -> ``ok=False``."""+ """Readiness probe for the session a client is about to open (setup.status is True if ANY+ provider auth state is discoverable): ok=False + the auth error when the model can't be served,+ so UIs surface onboarding before a doomed prompt. Without ``provider`` it runs the SAME+ resolver as session creation (``_resolve_agent_model_runtime``: startup model + provider pin,+ then the configured fallback chain) — a probe that ignores the chain shows onboarding for a+ backend whose sessions build fine. An explicit ``provider`` stays a strict single-provider+ check so onboarding can verify the provider just connected without another provider's+ fallback masking a failed connection. ``profile`` answers for THAT profile's pin and ``.env``;+ unknown -> ``ok=False``."""try:- from hermes_cli.runtime_provider import resolve_runtime_provider- from hermes_cli.auth import has_usable_secret- from hermes_cli.main import _has_any_provider_configured+ from hermes_cli.runtime_readiness import check_runtime_readinessrequested = str(params.get("provider") or "").strip() or Nonedef probe(profile, scoped):- return {**check_runtime_readiness(requested, strict_profile_scope=bool(profile)), **scoped}- if requested:- model, _startup_provider = _resolve_startup_runtime()- runtime = resolve_runtime_provider(requested=requested, target_model=model or None)- else:- model, runtime = _resolve_agent_model_runtime(None, None)- provider_configured = bool(_has_any_provider_configured(strict_profile_scope=bool(profile)))- provider = runtime.get("provider") or "provider"- source = str(runtime.get("source") or "")-- def fail(error, src):- return {"ok": False, "provider": provider, "model": model,- "source": src, "error": error, **scoped}- if (not provider_configured and provider == "bedrock"- and source in {"iam-role", "aws-sdk-default-chain"}):- return fail("No Hermes provider is configured.", source)- api_key = runtime.get("api_key")- api_key_text = "" if callable(api_key) else str(api_key or "").strip()- if not (callable(api_key) or api_key_text in {"aws-sdk", "no-key-required"}- or has_usable_secret(api_key_text) or bool(runtime.get("command"))):- return fail(f"No usable credentials found for {provider}.", runtime.get("source"))- from hermes_cli.anon_auth import route_is_welcome_host- # free_tier is keyed on the SELECTED route (the welcome host serves only nous/welcome), not- # on profile state: a paid Nous key beside a free-tier identity must not read as free.- return {"ok": True, "provider": runtime.get("provider"), "model": model,- "source": runtime.get("source"),- "free_tier": provider == "nous" and route_is_welcome_host(runtime.get("base_url")),++ def resolve():++ if requested:++ from hermes_cli.runtime_provider import resolve_runtime_provider++ model, _startup_provider = _resolve_startup_runtime()++ return model, resolve_runtime_provider(requested=requested, target_model=model or None)++ return _resolve_agent_model_runtime(None, None)++ return {**check_runtime_readiness(requested, strict_profile_scope=bool(profile), resolve=resolve),+ **scoped}return _readiness_check(rid, params, probe)except Exception as e:return _ok(rid, {"ok": False, "error": str(e)})diff --cc tui_gateway/session_registry.pyindex 42923ce1a35,00000000000..202337b61e9mode 100644,000000..100644--- a/tui_gateway/session_registry.py+++ b/tui_gateway/session_registry.py@@@ -1,706 -1,0 +1,721 @@@+"""TUI session_registry seam; functions bind to the server namespace at registration."""++from __future__ import annotations++from .method_ctx import bind_module++def _wait_agent(session: dict, rid: str, timeout: float = 30.0) -> dict | None:+ ready = session.get("agent_ready")+ if ready is not None and not ready.wait(timeout=timeout):- return _err(rid, 5032, "agent initialization timed out")++ return _err(rid, 5032, 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) -> "_TurnScopes":- """Bind a session profile's HERMES_HOME / secret / terminal scopes for an agent build. Fail-open per- scope (the build must not die on a scope helper); the terminal installer itself fails closed (malformed- policy → refusal scope) so _make_agent's terminal probing / cwd hints resolve the routed profile."""++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()- scopes.home = set_hermes_home_override(profile_home)+ with contextlib.suppress(Exception):- scopes.secret = set_secret_scope(build_profile_secret_scope(Path(profile_home)))- scopes.terminal = None- with contextlib.suppress(Exception):- from tools.terminal_scope import install_profile_terminal_scope- scopes.terminal = install_profile_terminal_scope(Path(profile_home))++ return _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:- if scopes.home is not None:- reset_hermes_home_override(scopes.home)- if scopes.secret is not None:- with contextlib.suppress(Exception):- reset_secret_scope(scopes.secret)- if scopes.terminal is not None:- with contextlib.suppress(Exception):- from tools.terminal_scope import reset_terminal_scope- reset_terminal_scope(scopes.terminal)++def _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)}++ "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)++ 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:- scopes = _bind_build_profile_scopes(profile_home)+ session_db = _open_profile_session_db(profile_home)+ try:+ from tui_gateway.entry import ensure_mcp_discovery_started+ ensure_mcp_discovery_started()+ except Exception:+ logger.warning("MCP discovery startup failed", exc_info=True)+ try:+ agent = _make_agent(sid, key, **_deferred_build_agent_kwargs(current, session_db))+ finally:+ _clear_session_context(tokens)+ _attach_built_agent(current, agent)+ # No eager slash-worker pre-warm (slash.exec spawns on demand): each worker forks the full stdio+ # MCP fleet, and live-transport sessions are never reaped, so fleets would accumulate.+ notify_registered = _wire_session_agent(sid, key, agent)+ _announce_built_agent(sid, key, current, agent)+ except Exception as e:+ current["agent_error"] = str(e)- _emit("error", sid, {"message": f"agent init failed: {e}"})++ _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)++def _init_session(+ sid: str, key: str, agent, history: list, cols: int = 80, cwd: str | None = None,+ session_db=None, source: str | None = None, profile_home: str | None = None,+ explicit_cwd: bool = False):+ now = time.time()+ with _sessions_lock:+ _sessions[sid] = {+ "agent": agent, "session_key": key, "history": history, "history_lock": threading.Lock(),+ "history_version": 0, "inflight_turn": None, "created_at": now, "last_active": now,+ "running": False, "attached_images": [], "image_counter": 0, "cwd": cwd or _completion_cwd(),+ "explicit_cwd": bool(explicit_cwd), "cols": cols, "slash_worker": None,+ "show_reasoning": _load_show_reasoning(), "source": _resolve_session_source(source),+ "tool_progress_mode": _load_tool_progress_mode(), "edit_snapshots": {}, "tool_started_at": {},+ # Profile-scoped HERMES_HOME (None = launch); SessionBranch copies the parent's (same state.db).+ "profile_home": profile_home,+ # In-session /model switch, honored on rebuild (/new, resume) — never leaks to siblings via env vars.+ "model_override": None,+ # Async events go to the transport that created the session (stdio for Ink, WS for the dashboard).+ "transport": current_transport() or _stdio_transport,+ "auth_user_id": _transport_auth_user_id(current_transport()),+ }+ _session_todo_state(_sessions[sid])+ _hydrate_session_cwd(sid, key, session_db, profile_home)+ _register_session_cwd(_sessions[sid])+ _wire_session_agent(sid, key, agent) # no eager slash-worker pre-warm (see _start_agent_build)+ _start_session_services(sid, key, _sessions.get(sid, {}))+ _emit("session.info", sid, _session_info(agent, _sessions.get(sid, {})))+ _schedule_mcp_late_refresh(sid, agent)+++def _new_session_key() -> str:+ return new_session_id()+++def _with_checkpoints(session, fn):+ return fn(session["agent"]._checkpoint_mgr, _session_cwd(session))+++def _resolve_checkpoint_hash(mgr, cwd: str, ref: str) -> str:+ try:+ checkpoints = mgr.list_checkpoints(cwd)+ idx = int(ref) - 1+ except ValueError:+ return ref+ if 0 <= idx < len(checkpoints):+ return checkpoints[idx].get("hash", ref)+ raise ValueError(f"Invalid checkpoint number. Use 1-{len(checkpoints)}.")+++# ── Methods: session ─────────────────────────────────────────────────+++def _lazy_resume_info(cwd: str, *, model: str = "", provider: str = "", profile: str | None = None) -> dict:+ """session.info for a not-yet-built session (session.create's shape); tools/skills land with the deferred build."""+ return {+ "cwd": cwd, "branch": git_probe.branch(cwd), "project": _project_info_for_cwd(cwd),+ "model": model or _resolve_model(), "tools": {}, "skills": {}, "lazy": True,+ "desktop_contract": DESKTOP_BACKEND_CONTRACT, "profile_name": _response_profile_name(profile),+ **({"provider": provider} if provider else {}),+ }+++def _deferred_session_record(+ session_key: str, *, cols: int, cwd: str, history: list, lease, source: str = "tui",+ close_on_disconnect: bool = False, display_history_prefix: list | None = None,+ profile_home: Path | None = None, lazy: bool = False, model_override=None,+ resume_runtime_overrides: dict | None = None, todo_state: dict | None = None,+ explicit_cwd: bool = False) -> dict:+ """A live-session record whose AIAgent is built later (lazy watch / cold resume) — _init_session's shape minus the agent."""+ now = time.time()+ return {+ "agent": None, "agent_error": None, "agent_ready": threading.Event(), "attached_images": [],+ "close_on_disconnect": close_on_disconnect, "active_session_lease": lease, "cols": cols,+ "created_at": now, "cwd": cwd, "display_history_prefix": display_history_prefix or [],+ "edit_snapshots": {}, "explicit_cwd": bool(explicit_cwd), "history": history,+ "history_lock": threading.Lock(), "history_version": 0, "image_counter": 0,+ "inflight_turn": None, "last_active": now, "lazy": lazy, "model_override": model_override,+ "pending_title": None,+ "profile_home": str(profile_home) if profile_home is not None else None,+ "resume_runtime_overrides": resume_runtime_overrides, "resume_session_id": session_key,+ "running": False, "session_key": session_key, "show_reasoning": _load_show_reasoning(),+ "slash_worker": None, "source": source, "tool_progress_mode": _load_tool_progress_mode(),+ "tool_started_at": {}, "todo_state": todo_state,+ "transport": current_transport() or _stdio_transport,+ "auth_user_id": _transport_auth_user_id(current_transport()),+ }+++_ANY_PROFILE = object() # default: match a live session regardless of profile+++def _live_profile_matches(session: dict, profile_home) -> bool:+ """True when ``session`` belongs to ``profile_home`` (None = launch profile; a record with no+ ``profile_home`` is the launch profile's). ``_ANY_PROFILE`` disables the check."""+ if profile_home is _ANY_PROFILE:+ return True+ return (session.get("profile_home") or None) == (str(profile_home) if profile_home else None)+++def _claim_or_reuse_live(sid: str, session_key: str, record: dict, lease) -> tuple[str, dict] | None:+ """Register ``record`` as the live session for ``session_key`` under the resume lock, or — if a+ concurrent resume already won — release ``lease`` and return the winner for the caller to reuse."""+ # A live runtime of the same stored id under ANOTHER profile is not a winner to reuse.+ # See #100029.+ profile_home = record.get("profile_home")+ with _session_resume_lock:+ live = _find_live_session_by_key(session_key, profile_home)+ if live is not None:+ if lease is not None:+ lease.release()+ # The reap is cancelled by the guarded reuse (_reattach_refusal), not here: a rejected+ # reattach must leave an in-flight orphan interrupt polling.+ return live+ with _sessions_lock:+ _sessions[sid] = record+ _register_session_cwd(_sessions[sid])+ # A PRIOR runtime for this stored id may still be sentinel-parked with a reap Timer armed; cancel ++ # finalize it quietly so the reap doesn't broadcast session.reclaimed (storm).+ _cancel_ws_orphan_reap(sid)+ stale = _claim_parked_runtimes(session_key, keep_sid=sid, profile_home=profile_home)+ _finalize_superseded_runtimes(stale) # slow finalization stays OUTSIDE _session_resume_lock+ return None+++def _claim_parked_runtimes(session_key: str, *, keep_sid: str, profile_home=_ANY_PROFILE) -> list[tuple[str, dict]]:+ """Claim sentinel-parked stale runtimes of ``session_key`` for supersession: cancel their orphan-reap+ Timer and pop them here (under the caller's _session_resume_lock); the caller finalizes after release."""+ stale: list[tuple[str, dict]] = []+ with _sessions_lock:+ candidates = [+ (old_sid, old) for old_sid, old in list(_sessions.items())+ if old_sid != keep_sid and not old.get("_finalized")+ and _session_lookup_key(old, fallback=old_sid) == session_key+ and _live_profile_matches(old, profile_home) and old.get("transport") is _detached_ws_transport]+ for old_sid, _old in candidates:+ _cancel_ws_orphan_reap(old_sid)+ if (popped := _pop_session_by_id(old_sid)) is not None:+ stale.append((old_sid, popped))+ return stale+++def _finalize_superseded_runtimes(stale: list[tuple[str, dict]]) -> None:+ """end_reason ``superseded_by_resume`` is deliberately NOT in _RECLAIM_END_REASONS (no ``session.reclaimed``+ broadcast → no reap->broadcast->resume loop) but IN _RECOVERABLE_END_REASONS (Bot Chat resurrection applies)."""+ for old_sid, popped in stale:+ try:+ _teardown_popped_session(popped, end_reason="superseded_by_resume")+ except Exception:+ logger.exception("superseded runtime teardown failed sid=%s", old_sid)+++def _schedule_agent_build(sid: str, delay: float = 0.05) -> None:+ """Pre-warm a deferred session's agent off the response path (session.create + cold resume; _sess() also builds on demand)."""++ def _run():+ if (session := _sessions.get(sid)) is not None:+ _start_agent_build(sid, session)+ timer = threading.Timer(delay, _run)+ timer.daemon = True+ timer.start()++- def _load_resume_transcript(db, stored_id: str) -> tuple[list, list, list]:++def _load_resume_transcript(db, stored_id: str, *, model_history_only: bool = False) -> tuple[list, list, list]:+ """(raw_history, display_history, ancestor_prefix) for a cold resume. The full lineage is materialized+ only while it fits sessions.max_resume_messages (the transcript is REST-paginated), else the tip alone."""+ from hermes_state import SessionResumeTooLargeError++ if model_history_only:++ raw_history = db.get_messages_as_conversation(++ stored_id, repair_alternation=True, include_row_ids=True)++ return raw_history, [], []+ prefix_fits = True+ guard = getattr(db, "assert_resume_safe", None)+ if callable(guard):+ try:+ guard(stored_id)+ except SessionResumeTooLargeError as exc:+ prefix_fits = False+ logger.info("resume %s: compression lineage exceeds the resume limit (%s); hydrating the tip segment only",+ stored_id, exc)+ except Exception:+ logger.debug("resume lineage guard failed; loading full lineage", exc_info=True)+ if prefix_fits:+ raw_history, display_history = db.get_resume_conversations(stored_id)+ return raw_history, display_history, db.get_ancestor_display_prefix(stored_id)+ raw_history = db.get_messages_as_conversation(stored_id, repair_alternation=True, include_row_ids=True)+ return raw_history, raw_history, []++- def _schedule_resume_hydration(sid: str, stored_id: str, db, *, close_db: bool = False) -> None:++def _schedule_resume_hydration(sid: str, stored_id: str, db, *, close_db: bool = False,++ model_history_only: bool = False) -> None:+ """Load a cold resume's transcript off the JSON-RPC response path."""++ def _run() -> None:+ session = _sessions.get(sid)+ try:+ if session is None:+ return+ _emit("session.resume_progress", sid, {"phase": "history", "status": "loading"})+ db.reopen_session(stored_id)- raw_history, display_history, prefix = _load_resume_transcript(db, stored_id)++ raw_history, display_history, prefix = _load_resume_transcript(++ db, stored_id, model_history_only=model_history_only)+ # Display keeps the full transcript; the model-fed history uses the+ # same canonicalization as gateway resume and the send path.+ history = canonicalize_replay_history(raw_history)+ if _sessions.get(sid) is not session:+ return+ with session["history_lock"]:- session.update(history=history, display_history_prefix=prefix, resume_hydrating=False,- resume_message_count=len(display_history))++ session.update(history=history, display_history_prefix=prefix, resume_hydrating=False)++ if not model_history_only:++ session["resume_message_count"] = len(display_history)+ # Deferred resumes answered before the transcript existed; cache the derived todo snapshot now.+ todo_state = _todo_state_from_history(history)+ if todo_state is not None and session.get("todo_state") is None:+ session["todo_state"] = todo_state+ session["resume_history_ready"].set()+ _emit("session.resume_progress", sid,- {"message_count": len(display_history), "phase": "history", "status": "complete"})++ {"message_count": session["resume_message_count"], "phase": "history", "status": "complete"})+ _maybe_schedule_auto_continue(sid, session, stored_id)+ _start_agent_build(sid, session)+ except Exception as exc:+ if _sessions.get(sid) is not session:+ return- message = f"resume failed: {exc}"++ message = resume_failed_message(exc)+ session.update(resume_hydrating=False, resume_history_error=message, agent_error=message)+ session["resume_history_ready"].set()+ session["agent_ready"].set()+ _emit("session.resume_progress", sid, {"message": message, "phase": "history", "status": "failed"})+ _emit("error", sid, {"message": message})+ with _sessions_lock:+ discarded = _sessions.pop(sid, None) if _sessions.get(sid) is session else None+ if (lease := (discarded or {}).get("active_session_lease")) is not None:+ lease.release()+ finally:+ if close_db and hasattr(db, "close"):+ try:+ db.close()+ except Exception:+ logger.debug("failed to close resume db for %s", sid, exc_info=True)+ threading.Thread(target=_run, daemon=True).start()+++def _session_pending_kind(sid: str) -> str:- return next((str(_pending_prompt_payloads.get(rid, ("input.request", {}))[0]).removesuffix(".request")- for rid, (owner_sid, _ev) in list(_pending.items()) if owner_sid == sid), "")++ """Method of the server→client request *sid* is blocked on ("" when none)."""++ from tui_gateway import server_requests++ return server_requests.pending_kind(sid)+++def _session_live_status(sid: str, session: dict) -> str:+ if _session_pending_kind(sid):+ return "waiting"+ ready = session.get("agent_ready")+ # Unset + build never started = a lazy watch session idling, not one stuck mid-construction.+ if ready is not None and not ready.is_set() and session.get("agent_build_started"):+ return "starting"+ return "working" if session.get("running") else "idle"+++def _session_live_title(session: dict, key: str) -> str:+ title = str(session.get("pending_title") or "").strip()+ with contextlib.suppress(Exception), _session_db(session) as db:+ title = str(db.get_session_title(key) or title or "").strip() if db is not None else title+ return title+++def _session_live_item(sid: str, session: dict, current_sid: str = "") -> dict:+ key = _session_lookup_key(session, fallback=sid)+ agent = session.get("agent")+ history = list(session.get("history") or [])+ status = _session_live_status(sid, session)+ inflight = _inflight_snapshot(session)+ queued = _queued_prompt_snapshot(session)+ preview = next((" ".join(text.split())[:160] for msg in reversed(history)+ if (text := _content_display_text(msg.get("content", msg.get("text", ""))).strip())), "")+ if queued:+ preview = " ".join(str(queued.get("user") or preview).split())[:160]+ elif inflight:+ preview = " ".join(str(inflight.get("assistant") or inflight.get("user") or preview).split())[:160]+ now = time.time()+ return {+ "current": sid == current_sid, "id": sid,+ "last_active": float(session.get("last_active") or session.get("created_at") or now),+ "message_count": len(history),+ "model": str(getattr(agent, "model", "") or _resolve_model()), "preview": preview,+ "session_key": key, "started_at": float(session.get("created_at") or now), "status": status,+ "title": _session_live_title(session, key),+ }+++def _session_lookup_key(session: dict, *, fallback: str = "") -> str:+ return str(getattr(session.get("agent"), "session_id", None) or session.get("session_key") or fallback or "")+++def _find_live_session_by_key(session_key: str, profile_home=_ANY_PROFILE) -> tuple[str, dict] | None:+ # Timestamp-based stored ids can exist in several profiles' stores; a bare-id match would hand+ # profile B's resume profile A's runtime, so profile-aware callers match on (profile_home, key).+ # Profile-aware callers pass the home they resolved; the match must then be on (profile_home,+ # session_key). See #100029.+ for sid, session in list(_sessions.items()):+ if (not session.get("_finalized") and _session_lookup_key(session, fallback=sid) == session_key+ and _live_profile_matches(session, profile_home)):+ return sid, session+ return None+++def _fallback_session_info(session: dict) -> dict:+ agent = session.get("agent")+ if agent is not None:+ return _session_info(agent)+ # The SESSION's own workspace, not the launch dir (wrong project in the desktop Files pane). `branch` is+ # always emitted ("" outside git) so a stale label clears; `desktop_contract` missing reads as "out of date".+ # Reporting `_default_session_cwd()` here told a lazily-resumed session's client that its workspace was+ # wherever the gateway process happened to start, so the desktop Files pane painted the wrong project+ # even after the renderer rebound correctly (#71254). `branch` is always emitted ("" outside a git repo)+ # so a client can clear a stale label instead of retaining it — the same contract `_lazy_session_info`+ # above already follows.+ cwd = _session_cwd(session)+ return {+ "cwd": cwd, "branch": git_probe.branch(cwd), "project": _project_info_for_cwd(cwd), "lazy": True,+ "model": _resolve_model(), "skills": {}, "tools": {}, "desktop_contract": DESKTOP_BACKEND_CONTRACT,+ }+++def _reconcile_display_with_live(db_display: list[dict], in_memory: list[dict]) -> list[dict]:+ """Merge the persisted DISPLAY lineage with the in-memory live history: ``db_display`` is verbatim and+ candidate-inclusive (verification rows the model history collapses out) but can lag by a flush;+ ``in_memory`` is the recency authority but the collapsed *model* projection. Keep the DB display as base,+ append only the in-memory tail past the last DB row's ``(role, text)`` anchor — the verification answer+ survives a warm switch AND a not-yet-flushed live turn is kept."""+ if not db_display:+ return in_memory+ if not in_memory:+ return db_display++ def _key(msg: dict) -> tuple:+ return (msg.get("role"), _coerce_message_text(msg.get("content")))+ anchor = _key(db_display[-1])+ last_shared = max((idx for idx, msg in enumerate(in_memory) if isinstance(msg, dict) and _key(msg) == anchor), default=-1)+ if last_shared == -1:+ return db_display # DB tail not in memory (DB ahead, or diverged) — trust it over duplicating+ return list(db_display) + list(in_memory[last_shared + 1 :])+++def _live_visible_history(session: dict, db, in_memory_fallback: list[dict]) -> list[dict]:+ """User-visible DISPLAY projection for a live/warm session: the persisted display lineage (same read as+ resume/REST so the payloads agree) reconciled with the in-memory tail; in-memory when the DB is unavailable."""+ key = session.get("session_key")+ if db is not None and key:+ try:+ # include_compacted: a compacted session's archived turns are still the user's+ # conversation; without them a warm switch repainted the chat as summary + tail only.+ display = db.get_messages_as_conversation(+ key, include_ancestors=True, include_row_ids=True, include_compacted=True)+ # See #92080.+ return _reconcile_display_with_live(display, in_memory_fallback)+ except Exception:+ logger.debug("live display projection read failed", exc_info=True)+ return in_memory_fallback+++def _live_session_payload(+ sid: str, session: dict, *, cols: int | None = None, touch: bool = False,+ transport: Transport | None = None, omit_messages: bool = False) -> dict:+ with session["history_lock"]:+ if cols is not None:+ session["cols"] = cols+ if transport is not None:+ _rebind_live_transport(sid, session, transport)+ if touch:+ # #84417: do not re-fire the live turn's original user text from a stale server-queue+ # self-duplicate after settle.+ session["last_active"] = time.time()+ in_memory_history = list(session.get("display_history_prefix") or []) + list(session.get("history") or [])+ inflight, queued = _inflight_snapshot(session), _queued_prompt_snapshot(session)+ running, turn_started_at = bool(session.get("running")), _turn_started_at(session)+ # Persisted display lineage via the session's profile-aware DB (not the launch ``_get_db()``), read+ # outside the history lock (the DB has its own). ``omit_messages`` skips the read (fast path).+ if omit_messages:+ history = in_memory_history+ else:+ with _session_db(session) as db:+ history = _live_visible_history(session, db, in_memory_history)++ # message_count follows _resume_response: the stored size when messages are omitted, else the wire count++ # (a hidden seed row is in ``history`` but never on the wire).+ messages = [] if omit_messages else _history_to_messages(history)+ payload = {+ "info": _fallback_session_info(session), "message_count": len(history) if omit_messages else len(messages),+ "messages": messages,+ "messages_omitted": omit_messages, "running": running, "turn_started_at": turn_started_at,+ "session_id": sid, "session_key": _session_lookup_key(session, fallback=sid),+ "started_at": float(session.get("created_at") or time.time()),+ "status": _session_live_status(sid, session),+ }+ for key, value in (("inflight", inflight), ("queued", queued),+ ("pending_approval", _pending_approval_request_payload(str(session.get("session_key") or ""))),- ("pending_clarify", _pending_clarify_request_payload(sid))):++ ("open_requests", _open_requests(sid)),++ ("pending_connection", _pending_connection_request_payload(sid))):+ if value:+ payload[key] = value+ return _attach_todo_state(payload, session)+++def _main_runtime_from_agent(agent) -> dict | None:+ """Aux-client main_runtime override from a live agent, so a one-shot inherits the session's runtime."""+ if agent is None:+ return None+ runtime: dict = {}+ for field in ("provider", "model", "base_url", "api_key", "api_mode", "auth_mode"):+ value = getattr(agent, field, None)+ if isinstance(value, str) and value.strip():+ runtime[field] = value.strip()+ elif field == "api_key" and callable(value):+ runtime[field] = value+ return runtime or None+++def register(server):+ bind_module(globals(), server)diff --cc ui-tui/src/__tests__/createGatewayEventHandler.test.tsindex 2973879fd0e,861c2496300..d7cd57968c5--- a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts+++ b/ui-tui/src/__tests__/createGatewayEventHandler.test.ts@@@ -138,26 -104,31 +152,49 @@@ describe('createGatewayEventHandler', (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')})+ it('keeps the durable session id when a session.info payload omits it', () => {+ patchUiState({ sid: 'focused', storedSid: 'durable-1' })+ const onEvent = createGatewayEventHandler(buildCtx([]))++ // Agent-less producers (_fallback_session_info, lazy cwd switch) send no stored_session_id.+ onEvent({+ session_id: 'focused',+ payload: { cwd: '/tmp/a', model: 'test', skills: {}, tools: {} },+ type: 'session.info'+ } as any)+ expect(getUiState().storedSid).toBe('durable-1')+ expect(getUiState().info?.stored_session_id).toBe('durable-1')++ // A payload that carries one is authoritative.+ onEvent({+ session_id: 'focused',+ payload: { model: 'test', skills: {}, stored_session_id: 'durable-2', tools: {} },+ type: 'session.info'+ } as any)+ expect(getUiState().storedSid).toBe('durable-2')+ expect(getUiState().info?.stored_session_id).toBe('durable-2')+ })+it('archives incomplete todos into transcript flow at end of turn so they scroll up', () => {const appended: Msg[] = []diff --cc ui-tui/src/app/createGatewayEventHandler.tsindex eafcd1f6162,25519ada703..386e315281c--- a/ui-tui/src/app/createGatewayEventHandler.ts+++ b/ui-tui/src/app/createGatewayEventHandler.ts@@@ -31,9 -30,8 +31,10 @@@ import type { Msg, SessionInfo, Subagenimport { applyDelegationStatus, getDelegationState } from './delegationStore.js'import type { GatewayEventHandlerContext, NoticeLevel } from './interfaces.js'import { getOverlayState, patchOverlayState } from './overlayStore.js'+import { markBubbleShown, newlyStartedRows } from './pendingBubbles.js'import { flashGoodVibes, flashPet } from './petFlashStore.js'+ import { forgetServerRequest } from './serverRequestStore.js'+import { captureDestination, isCurrentDestination } from './submissionDestination.js'import { turnController } from './turnController.js'import { getTurnState } from './turnStore.js'import { getUiState, patchUiState } from './uiStore.js'@@@ -786,43 -787,6 +799,43 @@@ 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 } })+ }+ }+- const settled = ev as unknown as { type: string; payload?: { prompt_id?: string } }++ if (ev.type === 'approval.settled' || ev.type === 'clarify.settled') {++ const kind = ev.type === 'approval.settled' ? 'approval' : 'clarify'++ const promptId = ev.payload?.prompt_id+- if (settled.type === 'approval.settled' || settled.type === 'clarify.settled') {- const kind = settled.type === 'approval.settled' ? 'approval' : 'clarify'- patchOverlayState(previous => previous[kind]?.sharedControl?.prompt_id === settled.payload?.prompt_id++ patchOverlayState(previous => previous[kind]?.sharedControl?.prompt_id === promptId+ ? { ...previous, [kind]: null } : previous)++ return+ }+switch (ev.type) {case 'gateway.ready':handleReady(ev.payload?.skin)@@@ -843,26 -806,9 +856,26 @@@return}+ if (incoming.profile_name && current?.profile_name && incoming.profile_name !== current.profile_name) {+ return+ }+- const info = { ...current, ...incoming }++ let info: SessionInfo = { ...current, ...incoming }++ // A busy-time admission painted no bubble at submit; paint it when the+ // authority starts it, so it lands after the previous assistant reply.+ for (const started of newlyStartedRows(current?.pending_submissions, incoming.pending_submissions)) {+ markBubbleShown(started.input_id)+ appendMessage({ role: 'user', text: started.user })+ }+// A replayed snapshot can be the only terminal signal after reconnect.// Missing running on older gateways must not clear a live turn.- if (info.running === false) {+ if (incoming.running === true) {+ patchUiState({ busy: true, status: 'running…' })+ }++ if (incoming.running === false) {turnController.clearStatusTimer()turnController.idle()setStatus('ready')@@@ -1356,134 -1299,33 +1393,94 @@@return}- const shared = ev.payload as typeof ev.payload & { prompt_id?: string; execution_generation?: number }+ // A password/secret/vault card that timed out vanished silently; say+ // what happened and how to get it back. Clarify already records its+ // own "(timed out)" line via tool.complete.+ const timeoutNotice = promptTimeoutNotice(ev.payload?.method, ev.payload?.reason)++ if (timeoutNotice) {+ sys(timeoutNotice)+ }++ forgetServerRequest(id)+ patchOverlayState(prev => {+ const next = { ...prev }+ let changed = false++ for (const key of ['approval', 'clarify', 'secret', 'sudo', 'vaultUnlock'] as const) {+ if (prev[key]?.requestId === id) {+ next[key] = null+ changed = true+ }+ }++ return changed ? next : prev+ })++ return+ }+++ // Canonical gateways (`gateway/session_pending_controls.py`) publish++ // generation-bound shared controls as events carrying `prompt_id`; they++ // are answered through approval.respond / clarify.respond, never through++ // a server→client request frame (that is the legacy tui_gateway path in++ // createServerRequestHandler).++ case 'clarify.request': {++ const shared = ev.payload++++ if (!shared?.prompt_id || !ev.session_id || typeof shared.execution_generation !== 'number') {++ return++ }+- const sharedControl = shared.prompt_id && ev.session_id && typeof shared.execution_generation === 'number'- ? { session_id: ev.session_id, execution_generation: shared.execution_generation, prompt_id: shared.prompt_id } : undefined++ const sharedControl = { session_id: ev.session_id, execution_generation: shared.execution_generation, prompt_id: shared.prompt_id }+- const batch = (ev.payload.questions ?? [])++ const batch = (shared.questions ?? [])+ .filter(q => typeof q?.qid === 'string' && q.qid && typeof q?.question === 'string' && q.question.trim())+ .map(q => ({+ choices: q.choices && q.choices.length > 0 ? q.choices : null,+ multiSelect: q.multi_select === true,+ qid: q.qid,+ question: q.question.trim()+ }))++ patchOverlayState({+ clarify: batch.length- ? {- answers: ev.payload.answers ?? {},- choices: null,- question: '',- questions: batch,- requestId: shared.prompt_id ?? ev.payload.request_id, sharedControl- }- : {- choices: ev.payload.choices ?? null,- question: ev.payload.question ?? '',- requestId: shared.prompt_id ?? ev.payload.request_id, sharedControl- }++ ? { answers: shared.answers ?? {}, choices: null, question: '', questions: batch, requestId: shared.prompt_id, sharedControl }++ : { choices: shared.choices ?? null, question: shared.question ?? '', requestId: shared.prompt_id, sharedControl }+ })+ setStatus('waiting for input…')+ ringPromptBell()++ return+ }++ case 'approval.request': {- if (!ev.payload) {++ const shared = ev.payload++++ if (!shared?.prompt_id || !ev.session_id || typeof shared.execution_generation !== 'number') {+ return+ }+- const shared = ev.payload as typeof ev.payload & { prompt_id?: string; execution_generation?: number }-- const sharedControl = shared.prompt_id && ev.session_id && typeof shared.execution_generation === 'number'- ? { session_id: ev.session_id, execution_generation: shared.execution_generation, prompt_id: shared.prompt_id } : undefined-- const description = String(ev.payload.description ?? 'dangerous command')- // Only an explicit false (tirith warning) drops the permanent-allow option.- const allowPermanent = ev.payload.allow_permanent !== false++ const sharedControl = { session_id: ev.session_id, execution_generation: shared.execution_generation, prompt_id: shared.prompt_id }++ patchOverlayState({+ approval: {- allowPermanent,++ // Only an explicit false (tirith warning) drops the permanent-allow option.++ allowPermanent: shared.allow_permanent !== false,++ choices: shared.choices,++ command: String(shared.command ?? ''),++ description: String(shared.description ?? 'dangerous command'),++ requestId: shared.prompt_id,+ sharedControl,- choices: ev.payload.choices,- command: String(ev.payload.command ?? ''),- description,- smartDenied: ev.payload.smart_denied === true++ smartDenied: shared.smart_denied === true+ }+ })+ setStatus('approval needed')+ ringPromptBell()++ return+ }+- case 'sudo.request':- if (!ev.payload) {- return- }-- patchOverlayState({ sudo: { requestId: ev.payload.request_id } })- setStatus('sudo password needed')- ringPromptBell()-- return-- case 'secret.request':- if (!ev.payload) {- return- }-- patchOverlayState({- secret: { envVar: ev.payload.env_var, prompt: ev.payload.prompt, requestId: ev.payload.request_id }- })- setStatus('secret input needed')- ringPromptBell()-- return- case 'sudo.expire': {- const expired = ev.payload?.request_id-- patchOverlayState(prev => (prev.sudo?.requestId === expired ? { ...prev, sudo: null } : prev))-- return- }-- case 'secret.expire': {- const expired = ev.payload?.request_id-- patchOverlayState(prev => (prev.secret?.requestId === expired ? { ...prev, secret: null } : prev))-- return- }-- case 'vault.unlock.request':- if (!ev.payload) {- return- }-- patchOverlayState({- vaultUnlock: {- backend: ev.payload.backend,- displayName: ev.payload.display_name,- requestId: ev.payload.request_id- }- })- setStatus(`unlock ${ev.payload.display_name}`)- ringPromptBell()-- return- case 'vault.unlock.expire': {- const expired = ev.payload?.request_id-- patchOverlayState(prev => (prev.vaultUnlock?.requestId === expired ? { ...prev, vaultUnlock: null } : prev))-- return- }-case 'background.complete':if (!ev.payload) {returndiff --cc ui-tui/src/app/createSlashHandler.tsindex a17bd4105b0,fd8bc359fab..3f782e872b8--- a/ui-tui/src/app/createSlashHandler.ts+++ b/ui-tui/src/app/createSlashHandler.ts@@@ -9,10 -9,10 +9,11 @@@ import type { SlashHandler, SlashHandleimport { scoreSlashMenuItem } from './slash/fuzzyScore.js'import { findSlashCommand } from './slash/registry.js'import type { SlashRunCtx } from './slash/types.js'+import { captureDestination, isCurrentDestination } from './submissionDestination.js'import { getUiState } from './uiStore.js'+ import { describeSlashExecError, shouldFallbackToDispatch } from './userMessages.js'-export function createSlashHandler(ctx: SlashHandlerContext): (cmd: string) => boolean {+export function createSlashHandler(ctx: SlashHandlerContext): SlashHandler {const { gw } = ctx.gatewayconst { catalog } = ctx.localconst { page, send, sys } = ctx.transcript@@@ -174,8 -169,20 +175,22 @@@long ? page(text, parsed.name[0]!.toUpperCase() + parsed.name.slice(1)) : sys(text)})- .catch(() => {- if (stale()) {return}+ .catch((execErr: unknown) => {++ if (stale()) {++ return++ }+++ // Only "slash.exec does not own this command" refusals (4011/4018) may+ // fall through to command.dispatch. A helper timeout/crash (5030) must+ // be shown as itself — the fallback's "not a quick/plugin/bundle/skill+ // command" refusal used to bury the real cause and imply the command+ // did not exist.+ if (!shouldFallbackToDispatch(execErr)) {- if (!stale()) {- sys(`error: ${describeSlashExecError(parsed.name, execErr)}`)- }++ sys(`error: ${describeSlashExecError(parsed.name, execErr)}`)++ return+ }+gw.request('command.dispatch', { arg: parsed.arg, name: parsed.name, session_id: sid }).then((raw: unknown) => {if (stale()) {diff --cc ui-tui/src/app/useInputHandlers.tsindex b099af6f732,9b7abb257d6..f97f6d769bf--- a/ui-tui/src/app/useInputHandlers.ts+++ b/ui-tui/src/app/useInputHandlers.ts@@@ -6,13 -5,7 +6,7 @@@ 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 {- ApprovalRespondResponse,- ConfigSetResponse,- SecretRespondResponse,- SudoRespondResponse,- VoiceRecordResponse- } from '../gatewayTypes.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 { computePrecisionWheelStep, initPrecisionWheel } from '../lib/precisionWheel.js'import { computeWheelStep, initWheelAccelForHost } from '../lib/wheelAccel.js'@@@ -27,7 -20,8 +21,8 @@@ importtype InputHandlerResult,type OverlayState} from './interfaces.js'-import { $isBlocked, $overlayState, patchOverlayState } from './overlayStore.js'+import { $isBlocked, $overlayState, capturePromptResponseGuard, patchOverlayState } from './overlayStore.js'+ import { respondToServerRequest } from './serverRequestStore.js'import { turnController } from './turnController.js'import { patchTurnState } from './turnStore.js'import { getUiState } from './uiStore.js'@@@ -229,15 -227,11 +228,29 @@@ export function useInputHandlers(ctx: I}if (overlay.approval) {+ const fresh = capturePromptResponseGuard('approval', overlay.approval)++ if (!fresh()) {+ return+ }+- return gateway- .rpc<ApprovalRespondResponse>('approval.respond', { choice: 'deny', session_id: getUiState().sid, ...sharedControlParams(overlay.approval) })- .then(r => r && fresh() && (patchOverlayState({ approval: null }), patchTurnState({ outcome: 'denied' })))++ const settle = () => {++ patchOverlayState({ approval: null })++ patchTurnState({ outcome: 'denied' })++ }++++ // Canonical shared controls deny through the generation-bound RPC; a++ // legacy server→client request resolves its response frame locally.++ if (overlay.approval.sharedControl) {++ return gateway++ .rpc<SharedControlRespondResponse>('approval.respond', { choice: 'deny', ...sharedControlParams(overlay.approval) })++ .then(r => r && fresh() && settle())++ }+++ respondToServerRequest(overlay.approval.requestId, { choice: 'deny' })- patchOverlayState({ approval: null })- patchTurnState({ outcome: 'denied' })++ settle()++ return}if (overlay.sudo || overlay.secret || overlay.vaultUnlock) {diff --cc ui-tui/src/app/useMainApp.tsindex 81ca02811ea,b3c6600dcbe..6c054735f22--- a/ui-tui/src/app/useMainApp.ts+++ b/ui-tui/src/app/useMainApp.ts@@@ -26,6 -27,6 +27,7 @@@ import typeConfigSetResponse,SessionActiveListResponse,SessionCloseResponse,++ SharedControlRespondResponse,TerminalResizeResponse} from '../gatewayTypes.js'import { useGitBranch } from '../hooks/useGitBranch.js'@@@ -52,12 -54,11 +55,13 @@@ 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 { 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'@@@ -238,9 -244,10 +251,10 @@@ export function useMainApp(gw: GatewayCconst colsRef = useRef(cols)const scrollRef = useRef<null | ScrollBoxHandle>(null)const onEventRef = useRef<(ev: AnyGatewayEvent) => void>(() => {})+ const onServerRequestRef = useRef<(request: ServerRequest) => boolean>(() => false)const sysRef = useRef<(text: string) => void>(() => {})const submitRef = useRef<(value: string) => void>(() => {})- const submitLiteralRef = useRef<(value: string) => void>(() => {})+ const submitLiteralRef = useRef<(value: string, attachments?: Array<{ path: string; mime: string }>) => void>(() => {})const terminalHintsShownRef = useRef(new Set<string>())const historyItemsRef = useRef(historyItems)const lastUserMsgRef = useRef(lastUserMsg)@@@ -722,11 -725,14 +738,22 @@@turnController.turnTools = turnController.turnTools.filter(line => !sameToolTrailGroup(label, line))patchTurnState({ turnTrail: turnController.turnTools })- rpc<ClarifyRespondResponse>('clarify.respond', { answer, ...(clarify.sharedControl ? sharedControlParams(clarify) : { request_id: clarify.requestId }) }).then(r => {- if (!r || !fresh()) {- if (!respondToServerRequest(clarify.requestId, { answer })) {- // The request already expired (request.cancel raced the keystroke): nothing to answer.- patchOverlayState({ clarify: null })++ // Canonical shared controls answer through the generation-bound RPC; a++ // legacy server→client request resolves its response frame locally.++ const answered = clarify.sharedControl++ ? rpc<SharedControlRespondResponse>('clarify.respond', { answer, ...sharedControlParams(clarify) }).then(r => Boolean(r) && fresh())++ : Promise.resolve(respondToServerRequest(clarify.requestId, { answer }))++++ void answered.then(ok => {++ if (!ok) {++ // The request already expired (request.cancel raced the keystroke): nothing to answer.++ if (!clarify.sharedControl) {++ patchOverlayState({ clarify: null })++ }+- return- }+ return+ }- {if (answer) {turnController.persistedToolLabels.add(label)appendMessage({@@@ -750,14 -756,14 +777,14 @@@}patchOverlayState({ clarify: null })- }+ })},- [appendMessage, overlay.clarify]+ [appendMessage, overlay.clarify, rpc])- // Lock one answer of a batch clarify (clarify.respond + question_id). The- // overlay stays up until the server reports no remaining questions — the- // final lock resolves the tool and the turn continues.+ // Lock one answer of a batch clarify (`clarify.lock` RPC). The overlay stays+ // up until the server reports no remaining questions — the final lock+ // resolves the server request and the turn continues.const answerClarifyQuestion = useCallback((qid: string, answer: string) => {const clarify = overlay.clarify@@@ -766,13 -772,7 +793,13 @@@return}+ const fresh = capturePromptResponseGuard('clarify', clarify)++ if (!fresh()) {+ return+ }+- rpc<ClarifyRespondResponse & { remaining?: string[] }>('clarify.respond', {+ rpc<ClarifyLockResponse>('clarify.lock', {answer,question_id: qid,request_id: clarify.requestId@@@ -928,24 -932,76 +961,74 @@@onEventRef.current = onEvent+ const onServerRequest = useMemo(+ () =>+ createServerRequestHandler({+ ringPromptBell: () => {+ if (bellOnPrompt && stdout?.isTTY) {+ stdout.write('\x07')+ }+ },+ setStatus: status => patchUiState({ status })+ }),+ [bellOnPrompt, stdout]+ )++ onServerRequestRef.current = onServerRequest+useEffect(() => {- const handler = (ev: AnyGatewayEvent) => onEventRef.current(ev)+ const handler = (ev: AnyGatewayEvent) => {+ if (ev.type === 'gateway.ready') {+ gaveUpRef.current = false+ }++ onEventRef.current(ev)+ }- const exitHandler = () => {+ const requestHandler = (request: ServerRequest) => {+ if (!onServerRequestRef.current(request)) {+ request.fail(JSON_RPC_METHOD_NOT_FOUND, `the terminal UI cannot answer ${request.method}`)+ }+ }++ const exitHandler = (code: null | number) => {turnController.reset()+ const state = getUiState()- const storedSid = state.storedSid++ // session.resume takes the durable stored id, not the process-local++ // runtime sid (they coincide on canonical gateways).++ const storedSid = state.storedSid ?? state.sid+- // Attached socket closed: the backend (and any live turn) is still there —++ // Socket closed: the backend (and any live turn) is still there —+ // GatewayClient owns the backoff reconnect, and the next gateway.ready+ // resumes the durable session id. Calling start() here would race that- // reconnect and reset its backoff.++ // reconnect and reset its backoff. Keep sid: durable offline input stays++ // fenced to its destination and drains once `gatewayConnected` returns.+ if (gw.attached) {+ recoverSidRef.current = storedSid ?? recoverSidRef.current- patchUiState({ busy: false, compacting: false, sid: null, status: 'reconnecting…' })++ patchUiState({ busy: false, compacting: false, gatewayConnected: false, status: 'reconnecting…' })++ if (state.sid) {+ turnController.pushActivity(CONNECTION_LOST_ACTIVITY, 'warn')+ sys(CONNECTION_LOST)+ }++ return+ }- // Keep the old destination for durable offline input; discovery retries- // must never silently create a replacement for an ended session.- const plan = planGatewayRecovery(getUiState().sid, recoverSidRef.current, recoveryAtRef.current, Date.now())- // A still-owned child dying while the TUI is alive is an *unexpected*- // death — respawn the gateway and resume the persisted session via the- // next gateway.ready. session.resume takes the durable stored id, not the- // process-local runtime sid. planGatewayRecovery bounds the attempts so a- // crash-looping gateway can't spawn-storm.++ // No socket was ever granted (bootstrap failed): GatewayClient retries++ // discovery on its backoff without starting a stopped owner; discovery++ // retries must never silently create a replacement for an ended session.++ // planGatewayRecovery bounds the resume attempts so a crash-looping++ // gateway can't storm.+ const plan = planGatewayRecovery(storedSid, recoverSidRef.current, recoveryAtRef.current, Date.now())- // Clear sid immediately: while the gateway is down, sid-guarded effects- // (session.active_list poll, queue drain) would otherwise fire RPCs at a- // dead/respawning gateway. recoverSidRef carries the session forward, and- // resumeById restores sid once the fresh gateway is ready.recoveryAtRef.current = plan.attempts- patchUiState({ busy: false, compacting: false, sid: null, status: 'restarting…' })+ patchUiState({ busy: false, compacting: false, gatewayConnected: false, status: 'gateway exited' })- if (plan.sid) {+ if (plan.recover && plan.sid) {recoverSidRef.current = plan.sid- turnController.pushActivity('gateway exited · recovering session…', 'warn')- sys('gateway exited — recovering your session (any in-flight reply was lost)')- // GatewayClient retries discovery without starting a stopped owner.+ turnController.pushActivity(BACKEND_RESTARTING_ACTIVITY, 'warn')+ sys(BACKEND_RESTARTING)- gw.start()return}@@@ -1032,23 -1102,17 +1129,31 @@@const answerApproval = useCallback((choice: string) => {- if (!overlay.approval) {+ const fresh = capturePromptResponseGuard('approval', overlay.approval)+- if (!fresh()) {++ if (!fresh() || !overlay.approval) {return}- return respondWith('approval.respond', { choice, session_id: ui.sid, ...sharedControlParams(overlay.approval) }, () => {- respondWith(overlay.approval.requestId, { choice }, () => {++ const settle = () => {+ if (!fresh()) {- return- }++ return++ }+patchOverlayState({ approval: null })patchTurnState({ outcome: choice === 'deny' ? 'denied' : `approved (${choice})` })patchUiState({ status: 'running…' })-- })++ }++++ // Canonical shared controls answer through the generation-bound RPC; a++ // legacy server→client request resolves its response frame locally.++ if (overlay.approval.sharedControl) {++ return rpc<SharedControlRespondResponse>('approval.respond', { choice, ...sharedControlParams(overlay.approval) }).then(r => r && settle())++ }++++ respondWith(overlay.approval.requestId, { choice }, settle)},- [overlay.approval, respondWith, ui.sid]- [overlay.approval, respondWith]++ [overlay.approval, respondWith, rpc])const answerSudo = useCallback(@@@ -1069,11 -1127,7 +1174,11 @@@patchOverlayState({ sudo: null })}- return respondWith('sudo.respond', { password: pw, request_id: requestId }, () => {+ respondWith(requestId, { value: pw }, () => {+ if (!fresh()) {- return- }++ return++ }+patchOverlayState({ sudo: null })patchUiState({ status: 'running…' })})@@@ -1099,11 -1147,7 +1204,11 @@@patchOverlayState({ secret: null })}- return respondWith('secret.respond', { request_id: requestId, value }, () => {+ respondWith(requestId, { value }, () => {+ if (!fresh()) {- return- }++ return++ }+patchOverlayState({ secret: null })patchUiState({ status: 'running…' })})diff --cc ui-tui/src/app/useSessionLifecycle.tsindex 2e1bf6cb326,ca767736c49..e955e1855b2--- a/ui-tui/src/app/useSessionLifecycle.ts+++ b/ui-tui/src/app/useSessionLifecycle.ts@@@ -3,10 -2,9 +3,10 @@@ import { writeFileSync } from 'node:fsimport type { ScrollBoxHandle } from '@hermes/ink'import { evictInkCaches } from '@hermes/ink'- import type { SessionInflightTurn, SessionResumeResponse, Usage } from '@hermes/shared/gateway-events'+ import type { InflightTurn, SessionResumeResult, Usage } from '@hermes/shared/gateway-events'import { type RefObject, useCallback, useEffect, useMemo, useRef } from 'react'+import { localCreationOptions } from '../canonicalGateway.js'import { buildSetupRequiredSections, SETUP_REQUIRED_TITLE } from '../content/setup.js'import { introMsg, toTranscriptMessages } from '../domain/messages.js'import { ZERO } from '../domain/usage.js'@@@ -267,109 -185,93 +268,113 @@@ export function useSessionLifecycle(optconst startNewSession = useCallback(async (msg?: string, title?: string, keepCurrent = false) => {- const setup = await rpc<SetupStatusResponse>('setup.status', {})-- if (setup?.provider_configured === false) {- panel(SETUP_REQUIRED_TITLE, buildSetupRequiredSections())- patchUiState({ status: 'setup required' })+ const flight = ++attachmentFlight.current+ const previousSid = getUiState().sid+ const previousSubscription = previousSid ? canonicalSubscriptions.current.get(previousSid) : undefined+ pendingAttachments.current.add(flight)- return null- }+ try {+ const setup = gw.isCanonical ? null : await rpc<SetupStatusResponse>('setup.status', {})- const previousSid = getUiState().sid+ if (flight !== attachmentFlight.current) {return null}- if (!keepCurrent) {- await closeSession(previousSid)- }+ if (setup?.provider_configured === false) {+ panel(SETUP_REQUIRED_TITLE, buildSetupRequiredSections())+ patchUiState({ status: 'setup required' })- const r = await rpc<SessionCreateResponse>('session.create', { cols: colsRef.current })+ return null+ }- if (!r) {- patchUiState({ status: 'ready' })+ if (!keepCurrent) {+ await closeSession(previousSid)- return null- }+ if (flight !== attachmentFlight.current) {return null}+ }- // The durable id lives on the create result; the lazy-create `info` does- // not carry it, and session.resume / the exit epilogue need the stored id.- const storedSid = r.stored_session_id || r.session_id- const info = r.info ? { ...r.info, stored_session_id: storedSid } : null- const requestedTitle = title?.trim() ?? ''-- resetSession()- setSessionStartedAt(Date.now())-- writeActiveSessionFile(storedSid)- patchUiState({- info,- sid: r.session_id,- status: info?.version ? 'ready' : 'starting agent…',- storedSid,- usage: usageFrom(info)- })+ const r = await rpc<SessionCreateResponse>('session.create', gw.isCanonical+ ? { request_id: randomUUID(), ...localCreationOptions() } : { cols: colsRef.current })- if (info) {- setHistoryItems([introMsg(info)])- }+ if (flight !== attachmentFlight.current) {+ discardStaleAttachment(r)- if (info?.credential_warning) {- sys(`warning: ${describeCredentialWarning(info.credential_warning)}`)- }+ return null+ }- if (info?.config_warning) {- sys(`warning: ${info.config_warning}`)- }+ if (!r) {+ patchUiState({ status: 'ready' })- if (msg) {- sys(msg)- }+ return null+ }- const info = r.info ? { ...r.info, stored_session_id: r.stored_session_id || r.info.stored_session_id } : null- if (requestedTitle) {- rpc<SessionTitleResponse>('session.title', {- session_id: r.session_id,- title: requestedTitle++ // The durable id lives on the create result; the lazy-create `info` does++ // not carry it, and session.resume / the exit epilogue need the stored id.++ const storedSid = r.stored_session_id || r.info?.stored_session_id || r.session_id++ const info = r.info ? { ...r.info, stored_session_id: storedSid } : null+ const requestedTitle = title?.trim() ?? ''++ resetSession()+ setSessionStartedAt(Date.now())+- writeActiveSessionFile(r.session_id)++ writeActiveSessionFile(storedSid)+ patchUiState({+ info,+ sid: r.session_id,+ status: gw.isCanonical || info?.version ? 'ready' : 'starting agent…',++ storedSid,+ usage: usageFrom(info)})- .then(result => {- if (!result || getUiState().sid !== r.session_id) {- return- }- const nextTitle = (result.title ?? requestedTitle).trim()- const suffix = result.pending ? ' (queued while session initializes)' : ''- patchUiState({ sessionTitle: nextTitle })- sys(`session title set: ${nextTitle}${suffix}`)- })- .catch((err: unknown) => {- if (getUiState().sid !== r.session_id) {- return- }+ if (info) {+ setHistoryItems([introMsg(info)])+ }- const message = err instanceof Error ? err.message : String(err)- sys(`warning: failed to set session title: ${message}`)+ if (info?.credential_warning) {- sys(`warning: ${info.credential_warning}`)++ sys(`warning: ${describeCredentialWarning(info.credential_warning)}`)+ }++ if (info?.config_warning) {+ sys(`warning: ${info.config_warning}`)+ }++ if (msg) {+ sys(msg)+ }++ if (requestedTitle) {+ rpc<SessionTitleResponse>('session.title', {+ session_id: r.session_id,+ title: requestedTitle})- }+ .then(result => {+ if (!result || getUiState().sid !== r.session_id) {+ return+ }++ const nextTitle = (result.title ?? requestedTitle).trim()+ const suffix = result.pending ? ' (queued while session initializes)' : ''+ patchUiState({ sessionTitle: nextTitle })+ sys(`session title set: ${nextTitle}${suffix}`)+ })+ .catch((err: unknown) => {+ if (getUiState().sid !== r.session_id) {+ return+ }++ const message = err instanceof Error ? err.message : String(err)+ sys(`warning: failed to set session title: ${message}`)+ })+ }- signalFreshSessionBoundary(previousSid, r.session_id, onFreshSessionStarted)+ signalFreshSessionBoundary(previousSid, r.session_id, onFreshSessionStarted)+ adoptAttachment(r, previousSid, previousSubscription)- return r.session_id+ return r.session_id+ } finally {+ finishAttachment(flight)+ }},- [closeSession, colsRef, onFreshSessionStarted, panel, resetSession, rpc, setHistoryItems, setSessionStartedAt, sys]+ [adoptAttachment, closeSession, colsRef, discardStaleAttachment, finishAttachment, gw.isCanonical, onFreshSessionStarted, panel,+ resetSession, rpc, setHistoryItems, setSessionStartedAt, sys])const newSession = useCallback(@@@ -418,11 -303,12 +423,13 @@@return patchUiState({ status: 'ready' })}- const info = r.info ? { ...r.info, stored_session_id: r.stored_session_id || r.info.stored_session_id } : null- const info = r.info ?? null+ // Agent-less (lazy) activations answer with `_fallback_session_info`, which- // has no stored_session_id; the durable id is the response's session_key.- const storedSid = r.session_key || r.session_id++ // has no stored_session_id; the durable id is the response's session_key++ // (canonical snapshots carry it as stored_session_id).++ const storedSid = r.session_key || r.stored_session_id || r.info?.stored_session_id || r.session_id++ const info = r.info ? { ...r.info, stored_session_id: storedSid } : nullconst running = Boolean(r.running || r.status === 'working' || r.status === 'waiting')- if (info) {info.stored_session_id = r.session_key || info.stored_session_id}-resetSession()setSessionStartedAt(r.started_at ? r.started_at * 1000 : Date.now())const transcript = [...toTranscriptMessages(r.messages), ...liveSessionInflightMessages(r.inflight)]@@@ -433,11 -319,9 +440,12 @@@info,sid: r.session_id,status: statusFromLiveSession(r.status, running),+ 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)cancelResumeScrollRef.current?.()cancelResumeScrollRef.current = scheduleResumeScrollToBottom(scrollRef)@@@ -467,9 -339,7 +475,9 @@@patchOverlayState({ sessions: false })patchUiState({ status: 'resuming…' })- ;(gw.isCanonical ? Promise.resolve(null) : rpc<SetupStatusResponse>('setup.status', {})).then(setup => {- return rpc<SetupStatusResponse>('setup.status', {}).then(setup => {++ return (gw.isCanonical ? Promise.resolve(null) : rpc<SetupStatusResponse>('setup.status', {})).then(setup => {+ if (flight !== attachmentFlight.current) {return}+if (setup?.provider_configured === false) {panel(SETUP_REQUIRED_TITLE, buildSetupRequiredSections())patchUiState({ status: 'setup required' })@@@ -477,37 -347,23 +485,37 @@@return}- const previousSid = getUiState().sid+ const pendingDetach = canonicalDetachFlights.current.get(id)- return gw.request<SessionResumeResult>('session.resume', { cols: colsRef.current, session_id: id })+ const request = pendingDetach+ ? pendingDetach.then(() => flight === attachmentFlight.current- ? gw.request<SessionResumeResponse<SessionInfo>>('session.resume', { cols: colsRef.current, session_id: id }) : null)- : gw.request<SessionResumeResponse<SessionInfo>>('session.resume', { cols: colsRef.current, session_id: id })++ ? gw.request<SessionResumeResult>('session.resume', { cols: colsRef.current, session_id: id }) : null)++ : gw.request<SessionResumeResult>('session.resume', { cols: colsRef.current, session_id: id })++ return request.then(raw => {- const r = asRpcResult<SessionResumeResponse<SessionInfo>>(raw)+ const r = asRpcResult<SessionResumeResult>(raw)+ if (flight !== attachmentFlight.current) {+ discardStaleAttachment(r)++ return+ }+if (!r) {sys('error: invalid response: session.resume')return patchUiState({ status: 'ready' })}- const info = r.info ? { ...r.info, stored_session_id: r.stored_session_id || r.info.stored_session_id } : null- const running = Boolean(r.running || r.status === 'working' || r.status === 'waiting')- const storedSid = r.info?.stored_session_id || r.stored_session_id || r.resumed || id++ const storedSid = r.session_key || r.info?.stored_session_id || r.stored_session_id || r.resumed || id+ const info = r.info ? { ...r.info, stored_session_id: storedSid } : null- if (info) {info.stored_session_id = r.session_key || info.stored_session_id || r.resumed}+ const running = Boolean(r.running || r.status === 'working' || r.status === 'waiting')+ // A successful resume authorizes the requested source → canonical+ // successor mapping; ordinary focus changes never migrate input.+ migratePendingInputs(destination, r.session_id, info?.stored_session_id)resetSession()setSessionStartedAt(r.started_at ? r.started_at * 1000 : Date.now())@@@ -519,11 -375,10 +527,12 @@@busy: running,info,sid: r.session_id,+ gatewayConnected: true,- status: statusFromLiveSession(r.status, running),+ status: statusFromLiveSession(r.status ?? undefined, running),+ storedSid,usage: usageFrom(info)})+ gw.hydrateSharedPrompts?.(r)hydrateLiveSessionInflight(r.inflight)cancelResumeScrollRef.current?.()cancelResumeScrollRef.current = scheduleResumeScrollToBottom(scrollRef)diff --cc ui-tui/src/components/activeSessionSwitcher.tsxindex db7b5792f03,415d5bfe34d..fee69b6533c--- a/ui-tui/src/components/activeSessionSwitcher.tsx+++ b/ui-tui/src/components/activeSessionSwitcher.tsx@@@ -349,27 -349,11 +349,27 @@@ export function ActiveSessionSwitcher(// Fetch independently (allSettled) so a failing session.list can't// wipe the live-session list: live sessions still render and the// resumable history degrades on its own.+ const canonicalList = gw.isCanonical- ? gw.request<{ scope?: string; sessions?: (SessionListItem & { running?: boolean })[] }>('session.list', {++ ? gw.request<{ scope?: string; sessions?: (SessionListRow & { running?: boolean })[] }>('session.list', {+ limit: 200+ })+ : null+const [liveRes, histRes] = await Promise.allSettled([- gw.request<SessionActiveListResponse>('session.active_list', {- current_session_id: currentSessionId- }),- includeHistory ? gw.request<SessionListResult>('session.list', { limit: 200 }) : Promise.resolve(null)+ canonicalList+ ? canonicalList.then(value => ({+ sessions: value.sessions?.map(row => ({+ ...row,+ current: row.id === currentSessionId,+ status: row.running ? ('working' as const) : ('idle' as const)+ }))+ }))+ : gw.request<SessionActiveListResponse>('session.active_list', { current_session_id: currentSessionId }),+ canonicalList+ ? Promise.resolve({ sessions: [] })+ : includeHistory- ? gw.request<SessionListResponse>('session.list', { limit: 200 })++ ? gw.request<SessionListResult>('session.list', { limit: 200 })+ : Promise.resolve(null)])const r = liveRes.status === 'fulfilled' ? asRpcResult<SessionActiveListResponse>(liveRes.value) : nulldiff --cc ui-tui/src/components/branding.tsxindex 2dbd487bea6,d82375778a4..8590af9cdbf--- a/ui-tui/src/components/branding.tsx+++ b/ui-tui/src/components/branding.tsx@@@ -249,16 -249,10 +249,17 @@@ export function SessionPanel({ info, mareturn line}+ // The canonical authority intentionally returns a narrow metadata snapshot.+ // Do not invent tool/skill inventories or crash while rendering that session.+ if (!info.skills || !info.tools) {+ return <Box flexDirection="column"><Text color={t.color.muted}>Gateway session {sid}</Text>+ <Text color={t.color.muted}>Tool and skill inventory is not exposed by this runtime.</Text></Box>+ }+// ── Collapsible skills section ──- const skillEntries = Object.entries(info.skills).sort()- const skillsTotal = flat(info.skills).length+ const skills = info.skills ?? {}+ const skillEntries = Object.entries(skills).sort()+ const skillsTotal = flat(skills).lengthconst skillsCatCount = skillEntries.lengthconst skillsBody = () => {diff --cc ui-tui/src/gatewayClient.tsindex 208214f7baf,2175def6bc1..b6170bfc669--- a/ui-tui/src/gatewayClient.ts+++ b/ui-tui/src/gatewayClient.ts@@@ -136,8 -133,9 +137,9 @@@ 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({- onEvent: ev => this.publish(ev as AnyGatewayEvent),+ onEvent: ev => this.publishWire(ev as AnyGatewayEvent),onHeartbeatFailure: () => this.onHeartbeatFailure(),+ onUnhandledRequest: req => this.pushLog(`[protocol] unhandled server request: ${req.method}`),requestTimeoutMs: REQUEST_TIMEOUT_MS,unrefTimers: true})@@@ -164,31 -161,19 +170,42 @@@// useInput / createGatewayEventHandler can legitimately attach many// listeners. Default 10-cap triggers spurious warnings.this.setMaxListeners(0)+ this.channel.onRequest(request => {+ if (this.subscribed) {+ this.emit('request', request)+ } else {+ this.bufferedRequests.push(request)+ }+ })+ }++ get attached(): boolean {+ return this.attachUrl !== null}+ /** Frames off the socket. On a canonical gateway the owner's execution stamp rides on+ * the params (`authority_epoch`/`execution_generation`); fold it into the payload the+ * pre-cutover handlers read, and let this client own readiness (it publishes+ * `gateway.ready` itself after `runtime.describe`, so the listener's ready would be a+ * second one) while still negotiating the transport's heartbeat capability. */+ private publishWire(ev: AnyGatewayEvent) {+ if (this.isCanonical && ev.type === 'gateway.ready') {+ if ((ev as GatewayEvent<'gateway.ready'>).payload?.heartbeat && this.ws?.readyState === WS_OPEN) {+ this.channel.startHeartbeat()+ }++ return+ }++ if (this.isCanonical) {+ const shared = ev as AnyGatewayEvent & { authority_epoch?: number; execution_generation?: number }+ ev.payload = { ...canonicalEvent(ev).payload, execution_epoch: String(shared.authority_epoch),+ execution_generation: shared.execution_generation } as never+ }++ this.publish(ev)+ }+private publish(ev: AnyGatewayEvent) {if (ev.type === 'gateway.ready') {this.ready = true@@@ -313,7 -299,12 +332,8 @@@// its queued microtask becomes a no-op (it captured the old generation).this.drainGeneration += 1this.bufferedEvents.clear()+ this.bufferedRequests = []this.pendingExit = undefined- this.stdoutRl?.close()- this.stderrRl?.close()- this.stdoutRl = null- this.stderrRl = nullthis.clearReadyTimer()}@@@ -508,20 -551,7 +534,22 @@@resolve()}- this.clearReconnect()this.connectSidecarMirror()++ if (this.isCanonical) {+ void this.requestOverWebSocket<{session_create: CreationContract}>('runtime.describe').then(description => {+ this.creationContract = description.session_create+- if (this.ws === ws) { this.publish({ type: 'gateway.ready', payload: {} }) }++ // The canonical gateway has no ready frame (readiness is the discovery++ // grant + runtime.describe); publish a client-local ready with no skin so++ // the renderer boots on its default theme.++ if (this.ws === ws) { this.publish({ type: 'gateway.ready', payload: {} } as unknown as AnyGatewayEvent) }+ }).catch(error => {+ this.publish({ type: 'gateway.start_timeout', payload: {+ python: 'runtime.describe', cwd: '', stderr_tail: String(error)+ } })+ })+ }},{ once: true })@@@ -598,8 -633,13 +630,7 @@@this.attachUrl = attachUrlthis.sidecarUrl = sidecarUrlthis.resetStartupState()- this.clearReconnect()- if (this.proc && !this.proc.killed && this.proc.exitCode === null) {- this.lifecycle(`[lifecycle] replacing live gateway child ${describeChild(this.proc)}`)- this.proc.kill()- }-- this.proc = nullthis.closeGatewaySocket()this.closeSidecarSocket()@@@ -736,10 -780,14 +776,11 @@@kill(reason = 'requested') {this.disposed = true+ this.localGeneration++this.clearReconnect()+ this.reconnectAttempts = 0- const proc = this.proc- const killed = proc?.kill()-- this.lifecycle(- `[lifecycle] GatewayClient.kill reason=${reason} ${describeChild(proc)} killResult=${killed ?? 'none'}`- )+ this.channel.stopHeartbeat()+ this.lifecycle(`[lifecycle] GatewayClient.kill reason=${reason} (detach only)`)this.closeGatewaySocket()this.closeSidecarSocket()this.clearReadyTimer()diff --cc ui-tui/src/gatewayTypes.tsindex 17ccede54a5,ec6cc4dea4a..57566f21737--- a/ui-tui/src/gatewayTypes.ts+++ b/ui-tui/src/gatewayTypes.ts@@@ -1,9 -1,9 +1,9 @@@import type { UsageModelData } from '@hermes/shared/billing'import type {GatewayEvent,-- GatewayEventName,- GatewayTranscriptMessage,- SessionInflightTurn,++ GatewayEventMap,+ InflightTurn,+ TranscriptMessage,Usage} from '@hermes/shared/gateway-events'import type { HermesSkin } from '@hermes/shared/skin'@@@ -14,9 -14,9 +14,50 @@@ import type { SessionInfo, SlashCategor* Includes the paired light_colors/dark_colors overlays from #20379. */export type GatewaySkin = HermesSkin--/** Distributive form of the shared `GatewayEvent<K>` so `switch (ev.type)`-- * narrows `ev.payload` per case (the generic-defaulted interface does not). */--export type AnyGatewayEvent = { [K in GatewayEventName]: GatewayEvent<K> }[GatewayEventName]++/** Generation-bound shared control published by a canonical gateway++ * (`gateway/session_pending_controls.py::register` / `register_clarify`). Answered through++ * `approval.respond` / `clarify.respond` with the prompt id, never through a server→client++ * request frame; `execution_epoch` is folded in by `GatewayClient.publishWire`. */++export interface CanonicalSharedPrompt {++ execution_epoch?: string++ execution_generation: number++ kind?: 'approval' | 'clarify'++ prompt_id: string++}++++export interface CanonicalApprovalPrompt extends CanonicalSharedPrompt {++ allow_permanent?: boolean++ choices?: string[]++ command?: string++ description?: string++ smart_denied?: boolean++}++++export interface CanonicalClarifyPrompt extends CanonicalSharedPrompt {++ answers?: Record<string, string>++ choices?: null | string[]++ multi_select?: boolean++ question?: string++ questions?: Array<{ choices?: null | string[]; multi_select?: boolean; qid: string; question: string }>++}++++/** Events the canonical gateway publishes that the generated `tui_gateway` contract does not++ * declare (it has no server→client prompt frames; controls ride the event stream). */++export interface CanonicalGatewayEventMap {++ 'approval.request': CanonicalApprovalPrompt++ 'approval.settled': Pick<CanonicalSharedPrompt, 'execution_generation' | 'prompt_id'>++ 'clarify.request': CanonicalClarifyPrompt++ 'clarify.settled': Pick<CanonicalSharedPrompt, 'execution_generation' | 'prompt_id'>++}++++export type AnyGatewayEventMap = CanonicalGatewayEventMap & GatewayEventMap++export type AnyGatewayEventName = keyof AnyGatewayEventMap & string++++/** Distributive form of the shared `GatewayEvent<K>` (plus the canonical events above) so++ * `switch (ev.type)` narrows `ev.payload` per case (the generic-defaulted interface does not). */++export type AnyGatewayEvent = {++ [K in AnyGatewayEventName]: Omit<GatewayEvent, 'payload' | 'type'> & { payload?: AnyGatewayEventMap[K]; type: K }++}[AnyGatewayEventName]export interface GatewayCompletionItem {display: string@@@ -177,10 -177,11 +218,13 @@@ export interface SystemBatteryResponse// ── Session lifecycle ────────────────────────────────────────────────export interface SessionCreateResponse {- info?: SessionInfo & { config_warning?: string; credential_warning?: string }- session_id: string+ // Durable id (state.db row) — what session.resume takes; `session_id` is the+ // process-local runtime handle.stored_session_id?: string+ info?: SessionInfo & { config_warning?: string; credential_warning?: string }+ session_id: string++ /** Canonical gateways: the actor's subscription token for `session.detach`. */+ subscription_id?: string}export type LiveSessionStatus = 'idle' | 'starting' | 'waiting' | 'working'@@@ -203,11 -204,10 +247,11 @@@ export interface SessionActiveListRespo}export interface SessionActivateResponse {+ stored_session_id?: string- inflight?: null | SessionInflightTurn+ inflight?: null | InflightTurninfo?: SessionInfomessage_count?: number- messages: GatewayTranscriptMessage[]+ messages: TranscriptMessage[]running?: booleansession_id: stringsession_key?: string@@@ -334,22 -319,12 +378,19 @@@ export interface BackgroundStartResponstask_id?: string}- export interface ClarifyRespondResponse {- ok?: boolean- }-- export interface ApprovalRespondResponse {- ok?: boolean+ /** `clarify.lock` — one batch-clarify answer locked; `expired` when the request already ended. */+ export interface ClarifyLockResponse {+ remaining?: string[]+ status: 'expired' | 'ok'}- export interface SudoRespondResponse {- ok?: boolean- }-- export interface SecretRespondResponse {- ok?: boolean++/** Canonical `approval.respond` / `clarify.respond` (`gateway/session_pending_controls.py::respond`):++ * generation-bound shared controls answered by prompt id, not by a server→client request frame. */++export interface SharedControlRespondResponse {++ prompt_id?: string++ status?: 'already_resolved' | 'resolved'+}+// ── Shell / clipboard / input ────────────────────────────────────────export interface ShellExecResponse {diff --cc ui-tui/src/types.tsindex 9ae49d1b92b,5e4f42807b9..3820c19bef6--- a/ui-tui/src/types.ts+++ b/ui-tui/src/types.ts@@@ -1,7 -1,5 +1,7 @@@- import type { SubagentStatus, Usage } from '@hermes/shared/gateway-events'+ import type { ProjectInfo, SessionLiveInfo, SubagentStatus } from '@hermes/shared/gateway-events'+import type { SharedControl } from './canonicalGateway.js'+export interface ActiveTool {context?: stringid: string@@@ -184,47 -182,9 +186,25 @@@ export interface McpServerStatustransport: string}- export interface ProjectInfo {- id: string- name: string- primary_path?: null | string- slug: string- }-- export interface SessionInfo {- stored_session_id?: string- cwd?: string- fast?: boolean-/** The gateway's `session.info` / resume `info` block — generated from `tui_gateway/contracts`. */-export type SessionInfo = SessionLiveInfo++/** The gateway's `session.info` / resume `info` block — generated from `tui_gateway/contracts`,++ * plus the canonical-authority fields the legacy contract does not carry yet++ * (`gateway/session_events.py` owner stamps and the durable admission FIFO). */++export interface SessionInfo extends SessionLiveInfo {++ execution_epoch?: string++ execution_generation?: number++ execution_state?: string+ install_warning?: string- lazy?: boolean- mcp_servers?: McpServerStatus[]- model: string- profile_name?: string- project?: null | ProjectInfo- reasoning_effort?: string+ pending_submissions?: Array<{+ admission_id: string+ input_id?: string+ target_session_id: string+ target_profile_home: string+ status: string+ user: string+ outcome?: string | null+ }>- execution_epoch?: string- execution_generation?: number- execution_state?: string- running?: boolean- release_date?: string- service_tier?: string- skills: Record<string, string[]>- system_prompt?: string- tools: Record<string, string[]>- update_behind?: number | null- update_command?: string- usage?: Usage- version?: string+}+ export type { ProjectInfo }export interface SudoReq {requestId: stringdiff --cc web/src/lib/api.tsindex 889c01f45f0,d65aa11d35e..6c0f7d24962--- a/web/src/lib/api.ts+++ b/web/src/lib/api.ts@@@ -1,11 -1,8 +1,11 @@@import {buildHermesWebSocketUrl,type ModelOptionProvider,- type ModelOptionsResponse,+ type ModelOptionsResult,} from "@hermes/shared";+import { createDashboardSessionMutations } from "./session-mutations";++const mutateSessionHttp = createDashboardSessionMutations(fetchJSON);// The dashboard can be served either at the root of its host (e.g.// https://kanban.tilos.com/) or under a URL prefix when reverse-proxieddiff --cc website/docs/developer-guide/programmatic-integration.mdindex 27464ce04cd,3d1d82cd6be..3cb0335b6da--- a/website/docs/developer-guide/programmatic-integration.md+++ b/website/docs/developer-guide/programmatic-integration.md@@@ -157,29 -168,21 +169,42 @@@ Use `/v1/models` for OpenAI-client comp`/v1/runs/{id}/steer` is only accepted while the run status is `running`. Queued, approval-paused, stopping, cancelled, failed, and completed runs return `409 run_not_accepting_steer`, even if the server still retains internal agent references during cooperative shutdown.- A `200` (and the `run.steered` event) means the text was **queued**, not that the agent consumed it. If a steer lands after the agent's final response — with no later tool boundary to deliver it at — the undelivered text is returned as `pending_steer` on the terminal `run.completed` event and run status, so the client can replay it as the next user turn instead of losing it.+ A `200` (and the `run.steered` event) means the text was **queued**, not that the agent consumed it. If a steer lands after the agent's final response — with no later tool boundary to deliver it at — the undelivered text is returned as `pending_steer` on the terminal event (`run.completed`, `run.failed`, or `run.cancelled`) and run status, so the client can replay it as the next user turn instead of losing it.++ #### Terminal run status++ The terminal status of a run is derived from how the agent's turn actually ended, and the terminal event name always matches it (`run.<status>`):++ | Turn outcome | Status | Terminal event | Flags on the event / status |+ |---|---|---|---|+ | Final answer produced | `completed` | `run.completed` | `completed: true` |+ | Interrupted (`/stop`, or an interrupt inside the agent) | `cancelled` | `run.cancelled` | `completed: false`, `interrupted: true` |+ | Provider/agent failure | `failed` | `run.failed` | `completed: false`, `error` |+ | Ended without finishing (iteration budget, truncated or partial reply) | `failed` | `run.failed` | `completed: false`, `partial` when applicable, `turn_exit_reason` (e.g. `max_iterations_reached(60/60)`), `output` with any fallback text |++ A run is never reported as `completed` with `completed: false` or `partial: true` in the same payload. The same rule applies to `/api/sessions/{id}/chat/stream`, whose `assistant.completed` payload carries the real `completed` / `partial` / `interrupted` flags and whose terminal event is `run.completed`, `run.failed`, or `run.cancelled`.+`POST /v1/runs/{id}/resolve-unknown` is a canonical-authority recovery+operation, not a generic status mutation. Send exactly the `admission_id` and+integer `execution_generation` projected by the run status. The server binds the+authenticated owner, selected profile, path run, API principal, target session,+admission, and generation before the authority performs its compare-and-set.+Resolution settles the lost head as interrupted and releases the next FIFO item;+it never requeues the head. Feature-detect+`features.run_unknown_resolution` because legacy execution mode does not+advertise this endpoint.++New canonical API admissions retain an opaque owner scope in the admission row,+so keyed and non-keyed runs can be authorized after an adapter restart for as+long as that canonical admission remains available. This does not change+non-keyed request semantics: identical submissions still create distinct runs.+Pre-upgrade non-keyed admissions contain no owner scope and remain deliberately+unresolvable after restart; there is no safe credential ownership to backfill.+Existing keyed records retain their replay-ledger recovery path. Explicit+session retirement removes the canonical payload and therefore ends this owner+recovery path. Replay reservation and canonical admission still use separate+databases, so this endpoint does not provide a global exactly-once guarantee.+---## Which one should I use?diff --cc website/docs/reference/cli-commands.mdindex 42b5b030ae5,47538ebe660..dd1c6b74307--- a/website/docs/reference/cli-commands.md+++ b/website/docs/reference/cli-commands.md@@@ -142,12 -143,51 +144,52 @@@ hermes chat --oneshot -q "Summarize thhermes chat --provider openrouter --model anthropic/claude-sonnet-4.6hermes chat --toolsets web,terminal,skillshermes chat --quiet -q "Return only JSON"+ hermes chat -q "Inspect this repository" --format stream-jsonhermes chat --worktree -q "Review this repo and open a PR"hermes chat --ignore-user-config --ignore-rules -q "Repro without my personal setup"-hermes chat --safe-mode -q "Is this bug mine or Hermes'?"+hermes chat --safe-mode --model gpt-4.1 -q "Is this bug mine or Hermes'?"+hermes chat --safe-mode --provider custom --base-url http://127.0.0.1:8000/v1 --model local -q "Isolate against a local server"```+ ### `--format stream-json` — structured JSONL output++ Use `--format stream-json` when a program needs to consume progress without+ scraping terminal output. It requires `-q` / `--query` (or `--query-file`), implies+ quiet non-interactive CLI mode, and rejects an explicit `--tui` request. Every+ stdout line is one JSON object; diagnostics and the `session_id:` line stay on stderr.++ ```bash+ hermes chat -q "Summarize this repository" --format stream-json+ ```++ Every event carries `timestamp` (Unix epoch milliseconds).++ | Event `type` | Fields |+ |---|---|+ | `system` | `subtype: "init"`, `model`, `session_id` |+ | `text` | `text` — a streamed assistant text delta |+ | `tool_use` | `name`; `input` when the tool arguments are available |+ | `tool_result` | `name`, `output` (capped at 5000 chars), `duration_ms`, `is_error` |+ | `result` | `session_id`, `exit_code`, `text`, `tokens` (`input`, `output`, `total`, `cache_read`, `cache_write`), `duration_ms`; `error` when the turn failed |++ Once a conversation starts, its terminal record is always `result` — including+ `exit_code: 130` when it is interrupted with Ctrl-C. Treat that record as the+ completion signal; the process exit code matches its `exit_code`.++ #### Exit codes for one-shot runs++ When chat answers and exits (`-Q`, `chat --oneshot`, or a query with non-TTY+ stdio) the process exit code reports the turn's outcome, on both the quiet and+ the non-quiet path: `0` the turn completed; `1` it failed, stopped partway+ (`partial`), hit the iteration budget, or never ran (credentials / agent init+ failed); `130` it was interrupted. A Kanban dispatcher-spawned worker+ (`HERMES_KANBAN_TASK` set) whose turn failed only because the provider was+ rate-limited, overloaded, returning 5xx, timing out, or the account hit a+ billing/quota wall, exits+ `75` (`EX_TEMPFAIL`) so the dispatcher requeues the task without counting a+ failure. With `--format stream-json` the terminal `result` record carries the+ same `exit_code`.+#### Delegation in finite chat runsWhen chat answers and exits (`-Q`, `chat --oneshot`, or a query with non-TTYdiff --cc website/docs/user-guide/configuring-models.mdindex bf87d33a255,e2f501c8f0d..cf9fa78fe99--- a/website/docs/user-guide/configuring-models.md+++ b/website/docs/user-guide/configuring-models.md@@@ -53,10 -53,19 +53,21 @@@ When you switch models **inside an acti:::warning Mid-session switches reset the prompt cachePrompt caches are keyed to the model serving the request, so any mid-conversation model change — an explicit `/model` switch, an [automatic fallback](./features/fallback-providers.md), or a [credential-pool](./features/credential-pools.md) rotation onto a different account — means the next message re-reads the entire conversation at full input-token price instead of the cached (~75–90% discounted) rate. On a long session this one-time re-read can dwarf the per-token difference between the two models. Switch when you need to, but prefer doing it early in a conversation or right after starting a fresh session.++An explicit `/model` switch also rewrites the `Model:` (and `Provider:`) line inside the system prompt so the agent knows what it is running on. That is a deliberate, one-time change: the first request after the switch misses the cached prefix once, and everything after the system prompt stays byte-identical. Automatic fallbacks rewrite the same line only in memory — the stored session keeps the primary's labels, so a restored primary replays a byte-identical prompt.:::+ Because of that one-time re-read cost, Hermes asks for **explicit confirmation** before applying a mid-session switch when the live session already holds a large context (default: **100,000 tokens**, measured from the latest provider-billed prompt size). The confirmation renders through the same selection-guard prompt as the expensive-model and data-training warnings wherever a live session is switching: the CLI and TUI `/model` command and picker, and a typed gateway `/model` in a chat with an active agent. Tune or disable it in `config.yaml`:++ ```yaml+ model:+ # Ask before mid-session switches when the session exceeds this many+ # context tokens (the next reply re-reads them uncached). 0 disables.+ switch_context_confirm_tokens: 100000+ ```++ Re-selecting the model you're already on never prompts (the cache stays warm), and sessions with no measured context (fresh sessions, non-live surfaces) are exempt.+### Unattended data-training tiersModels with a `-contributor` suffix (e.g. `muse-spark-1.2-contributor`, `muse-spark-1.3-contributor`) are discounted because the vendor may train on your prompts and completions. Interactive model selection always shows a confirmation prompt. Non-interactive startup paths such as Kanban workers and cron agents fail closed because they cannot ask that question.diff --cc website/docs/user-guide/features/api-server.mdindex 49c05fcc119,f46c01ad192..72bd6e8a0b1--- a/website/docs/user-guide/features/api-server.md+++ b/website/docs/user-guide/features/api-server.md@@@ -599,23 -538,7 +610,24 @@@ runningResolve a pending approval for a run that is waiting on a human decision (for example, a tool call gated behind an approval policy). The body carries the approval decision; the run resumes once the decision is recorded. This endpoint is advertised in `/v1/capabilities` as the `run_approval` feature so external UIs can detect support before surfacing an approval prompt.+With the canonical gateway owner, `GET /v1/runs/{run_id}` exposes+`pending_controls`, using the same `prompt_id` and `execution_generation` as+attached WebSocket viewers. Respond with the exact current identity:++```json+{"request_id": "<prompt_id>", "execution_generation": 3, "choice": "once"}+```++Canonical controls do not accept identityless or bulk responses. Stale generations,+foreign prompt IDs, and settled runs return HTTP 409. Existing run authentication+and hosted-room approval restrictions still apply.++### POST /v1/runs/\{run_id\}/clarify++Answer a canonical clarification with `request_id`, `execution_generation`, and+`answer` (a string). This authenticated endpoint and WebSocket `clarify.respond`+resolve the same waiting tool; answering does not submit another inference turn.+ MCP trust-gate consent — a write-capable tool on a server configured `trust: untrusted` — surfaces the same way: the run emits an `approval.request` event and parks in `waiting_for_approval` until this endpoint resolves it (`once` runs the tool, `deny` blocks it).## Jobs API (background scheduled work)