The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Merge main preserving canonical ownership and current client changes
Tekniumcf2e1a00444d
diff --cc apps/desktop/electron/main.tsindex 65ec1b02660,bb26dd487d3..8225f9f4139--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@@ -43,7 -30,14 +43,13 @@@ import} from 'electron'import { classifyActiveRuntime } from './active-runtime-state'- import { destroyKeepaliveAgents, jsonAgentFor, withRetry } from './api-transport'+ import {+ destroyKeepaliveAgents,- downloadAgentFor,+ httpStatusError,+ jsonAgentFor,+ readStatusCode,+ withRetry+ } from './api-transport'import { appIconCandidates, resolveAppIcon } from './app-icon'import { stopBackendChild as stopBackendChildImpl, stopBackendTreesForUpdate } from './backend-child'import {@@@ -1438,13 -1494,142 +1444,20 @@@ let desktopLogBuffer = 'let desktopLogFlushTimer = nulllet desktopLogFlushPromise = Promise.resolve()-let poolLimits = readPersistedPoolLimits()-// Hard cap on local backends that are starting OR running (the LRU eviction-// above is soft — it spares keepalive-fresh entries). Follows the live-// preference: setPoolLimits() pushes a new max into the coordinator.-const localBackendSpawnCoordinator = new LocalBackendSpawnCoordinator(poolLimits.maxBackends)-// How long a spawn may wait for a free local slot. Must stay under the-// renderer's BACKEND_BOOT_WAIT_TIMEOUT_MS (45s, src/lib/with-timeout.ts) so-// the queued ticket fails before the renderer does and the user sees why.-const POOL_SLOT_WAIT_MS = 30_000--function spawnPriorityFrom(value: unknown): LocalBackendSpawnPriority {- return value === 'foreground' ? 'foreground' : 'background'-}--// Foreground intent for a dial whose pool entry does not exist yet: a user-// click that joins an in-flight backendDialClaims claim never re-enters-// ensureBackend(), and the claim owner may still be awaiting poolStopper /-// registry resolution before backendPool.set(). The local spawn takes the mark-// right before its slot request; the IPC handler that set it clears it once-// the claim settles, so a dial that never reaches a slot request (primary-// route, remote scope, a guard rejection) cannot leave it for a later-// hydration spawn of the same key to pick up.-const pendingForegroundSpawns = new Set<string>()--function takeForegroundSpawn(...poolKeys: string[]): boolean {- let marked = false-- for (const poolKey of poolKeys) {- marked = pendingForegroundSpawns.delete(poolKey) || marked- }-- return marked-}--// Upgrade a pooled entry (running, spawning, or queued for a slot) to-// foreground so a queued slot wait can take the reserved foreground slot.-function promotePoolEntry(entry: any): void {- entry.spawnPriority = 'foreground'- entry.localBackendSpawnRequest?.promote?.('foreground')-}--// A passive read (background tile reconcile, #103375) may only be served by a-// backend that already exists: it never cold-starts a pooled child, never-// takes a slot, and never refreshes lastActiveAt, so an open-but-unviewed tile-// cannot keep the pool saturated. Callers treat the rejection as "nothing to-// refresh yet"; primary-routed profiles are always warm and never reach here.++// Passive reads may reuse a cached descriptor, but never start an owner.+ function assertNotPassiveSpawn(passive: boolean, poolKey: string): void {+ if (passive) {+ throw new Error(`Passive read: no warm backend for "${poolKey}"`)+ }+ }+-// Land a spawn failure in desktop.log. A background slot-wait timeout is-// routine under a saturated pool (the next hydration pass retries), so it is-// logged as such instead of as a backend-start failure.+// Land a spawn failure in desktop.log.function logPoolSpawnFailure(label: string, error: unknown): void {- if (isBackgroundSlotWaitTimeout(error)) {- rememberLog(`Profile backend ${label} slot wait timed out (background); will retry on the next hydration`)- } else {- rememberLog(- `Hermes backend for profile ${label} failed to start: ${error instanceof Error ? error.message : String(error)}`- )- }-}--// Apply foreground intent to the dial claim for `scopeKey`: an entry already-// in the pool is promoted directly, otherwise the intent is marked for the-// spawn the claim owner is about to start. Returns the cleanup that clears a-// mark the dial never consumed.-function applySpawnPriority(scopeKey: string, spawnPriority: LocalBackendSpawnPriority): () => void {- if (spawnPriority !== 'foreground') {- return () => undefined- }-- const existing = backendPool.get(scopeKey)-- if (existing) {- promotePoolEntry(existing)- } else {- pendingForegroundSpawns.add(scopeKey)- }-- return () => void pendingForegroundSpawns.delete(scopeKey)-}--function poolMaxBackends() {- return poolLimits.maxBackends-}--function poolIdleMs() {- return poolLimits.idleMs-}--/**- * Apply new limits live: persist, then converge the running pool — evict- * LRU backends down to the new max, and let the (already running) idle- * reaper handle a shortened idle window on its next tick. Returns the- * limits actually in force (post-clamp).- */-function setPoolLimits(raw) {- poolLimits = clampPoolLimits(raw)- persistPoolLimits(poolLimits)- localBackendSpawnCoordinator.setLimit(poolLimits.maxBackends)- evictLruPoolBackends(poolMaxBackends())- startPoolIdleReaper()-- return { ...poolLimits }+ rememberLog(+ `Hermes backend for profile ${label} failed to start: ${error instanceof Error ? error.message : String(error)}`+ )}-// A backend touched within this window has a live renderer socket (the keepalive-// pings every 60s for every open profile). LRU eviction must spare these — a-// concurrent multi-profile session keeps several backends "fresh" at once, and-// killing one to honor the soft cap would abort a running agent.-//-// The window is intentionally MUCH wider than the 60s ping cadence:-// * 1 missed ping = +60s of apparent silence-// * WSL2 IPC stall = the renderer's `hermes:backend:touch` roundtrips-// through 9p; a single brief 9p hiccup can stretch a-// ping to ~30s of observed silence (#95189: gateways-// exited every ~2 min on WSL2 because the previous-// 90s window left no headroom — one delayed ping-// pushed a live backend past the threshold and the-// cap-driven eviction killed the active profile's-// backend mid-session, re-minting runtime ids and-// re-allocating pooled gateway secondaries ~700×/day).-// * 3× ping + 60s headroom = ~4 min, comfortable margin for two missed-// pings + WSL2 IPC stall. The hard ceiling for the cap-eligible set is-// pool idle window above (default 10 min) — this constant only governs the-// "is this backend plausibly still alive" question for LRU eviction,-// not when the idle reaper definitively tears a backend down.-const POOL_KEEPALIVE_FRESH_MS = Math.max(- 120_000,- Number(process.env.HERMES_DESKTOP_POOL_KEEPALIVE_FRESH_MS) || 4 * 60_000-)--let poolIdleReaper = nulllet backendOrphanReapPromise = null// Auto-reload budget for renderer crashes, shared by EVERY window (primary,// secondary session, instance) so a crash loop anywhere is suppressed after@@@ -11283,30 -11580,10 +11356,31 @@@ function profileRouteOptions(profile, r// Resolve a backend connection for the given profile, per the routing table in// resolveProfileBackendRoute(). An empty / unknown profile resolves to the// primary, so legacy callers are unchanged.-async function ensureBackend(profile, opts: { passive?: boolean; spawnPriority?: LocalBackendSpawnPriority } = {}) {+// Drop the cached descriptor for a canonical local gateway whose owner is gone+// so the next ensureBackend() re-runs `gateway ensure` (attach or start) instead+// of minting tickets against a dead control socket. Nothing is killed: the+// descriptor never owned the runtime.+async function forgetLocalGatewayDescriptor(profile) {+ const key = profile && String(profile).trim() ? String(profile).trim() : primaryProfileKey()+ const route = resolveProfileBackendRoute(key, profileRouteOptions(key))++ if (route.backend === 'primary') {+ const attempt = backendConnectionState.startAttempt()+ attempt.promise = backendConnectionState.getPromise()+ backendConnectionState.clearPromiseForAttempt(attempt)+ rememberLog(`[gateway] forgot stale canonical endpoint for primary "${key}"; re-ensuring`)++ return+ }++ if (backendPool.delete(key)) {+ rememberLog(`[gateway] forgot stale canonical endpoint for profile "${key}"; re-ensuring`)+ }+}+- async function ensureBackend(profile) {++async function ensureBackend(profile, opts: { passive?: boolean } = {}) {const key = profile && String(profile).trim() ? String(profile).trim() : primaryProfileKey()- const spawnPriority = spawnPriorityFrom(opts.spawnPriority)+ const passive = Boolean(opts.passive)profileDeletionGate.assertCanStart(key)@@@ -11334,14 -11628,29 +11408,15 @@@return connection}+ assertNotPassiveSpawn(passive, key)- evictLruPoolBackends(poolMaxBackends() - 1)-- const entry = {- process: null,- port: null,- token: null,- connectionPromise: null,- lastActiveAt: Date.now(),- remoteBaseUrl: null,- releaseLocalBackendSlot: null,- localBackendSlotKey: null,- localBackendSpawnRequest: null,- spawnPriority- }-- entry.connectionPromise = spawnPoolBackend(key, entry).catch(async error => {- // Land the failure in desktop.log: without this a spawn that dies before- // its child exists (guard rejection, runtime resolution) leaves no trace+ const entry = newPoolEntry()++ entry.connectionPromise = dialPoolBackend(key, entry).catch(error => {+ // Land the failure in desktop.log: without this a dial that fails before+ // the gateway answers (guard rejection, runtime resolution) leaves no trace// beyond renderer-side rejections users never see in a bundle.logPoolSpawnFailure(`"${key}"`, error)-- await teardownFailedLocalBackend(key, entry)+ forgetFailedPoolEntry(key, entry)throw error})backendPool.set(key, entry)@@@ -11362,8 -11672,11 +11437,10 @@@async function ensureRegistryBackend(connectionId,profile,- managedUpdateCorrelation = ''+ managedUpdateCorrelation = '',- opts: { passive?: boolean; spawnPriority?: LocalBackendSpawnPriority } = {}++ opts: { passive?: boolean } = {}) {- const spawnPriority = spawnPriorityFrom(opts.spawnPriority)+ const passive = Boolean(opts.passive)const registry = readDesktopConnectionsRegistry()const id = String(connectionId || '').trim() || registry.primaryconst source = registry.connections.find(c => c.id === id)@@@ -11420,7 -11733,7 +11497,7 @@@const primary = await reuseMatchingPrimarySshBackend({connectionId: id,effectiveFingerprint: resolveRegistryEffectiveFingerprint,- ensurePrimary: () => ensureBackend(profile),- ensurePrimary: () => ensureBackend(profile, { passive, spawnPriority }),++ ensurePrimary: () => ensureBackend(profile, { passive }),profile,registry,source@@@ -11471,7 -11784,13 +11548,7 @@@})if (localRoute.delegate) {- return ensureBackend(profile)- return ensureBackend(profile, { passive, spawnPriority })- }-- const stoppingLocal = poolStopper.inFlight(localRoute.poolKey)-- if (stoppingLocal) {- await stoppingLocal++ return ensureBackend(profile, { passive })}const existingLocal = backendPool.get(localRoute.poolKey)@@@ -11480,16 -11799,39 +11557,17 @@@return existingLocal.connectionPromise}+ assertNotPassiveSpawn(passive, localRoute.poolKey)- evictLruPoolBackends(poolMaxBackends() - 1)-- const localEntry = {- process: null,- port: null,- token: null,- connectionPromise: null,- lastActiveAt: Date.now(),- remoteBaseUrl: null,- releaseLocalBackendSlot: null,- localBackendSlotKey: null,- localBackendSpawnRequest: null,- spawnPriority- }+ const localEntry = newPoolEntry()- localEntry.connectionPromise = spawnPoolBackend(profileKey, localEntry, {+ localEntry.connectionPromise = dialPoolBackend(profileKey, localEntry, {forceLocal: true,poolKey: localRoute.poolKey- }).catch(async error => {- // Same trace rule as the v1 pool path: a forced-local child whose spawn- // rejects before the child exists must still land in desktop.log.+ }).catch(error => {+ // Same trace rule as the v1 path: a forced-local dial that rejects must+ // still land in desktop.log.logPoolSpawnFailure(`"${profileKey}" (forced-local)`, error)-- await teardownFailedLocalBackend(localRoute.poolKey, localEntry)+ forgetFailedPoolEntry(localRoute.poolKey, localEntry)throw error})backendPool.set(localRoute.poolKey, localEntry)@@@ -11534,7 -11881,17 +11612,8 @@@)}+ assertNotPassiveSpawn(passive, key)- evictLruPoolBackends(poolMaxBackends() - 1)-- const entry = {- process: null,- port: null,- token: null,- connectionPromise: null,- lastActiveAt: Date.now(),- remoteBaseUrl: null- }+ const entry = newPoolEntry()entry.connectionPromise = connectRegistryBackend(source,@@@ -12184,32 -12669,244 +12263,32 @@@ 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 = spawn(- 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+ const connection = await ensureLocalGateway(async () => {+ const backend = await ensureRuntime(resolveHermesBackend(['--profile', profile, 'gateway', 'ensure', '--json']))+ profileDeletionGate.assertCanStart(profile)+ assertPoolEntryStillOwned(poolKey, entry)+- return runGatewayEnsure(backend, resolveHermesCwd(), HERMES_HOME)++ 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)))})- // 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)- 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])-- if (readyFile) {- fs.unlink(readyFile, () => {})- }-- entry.port = port-- const baseUrl = `http://127.0.0.1:${port}`- await Promise.race([waitForHermes(baseUrl, token), startFailed])- ready = true-- const authToken = await adoptServedDashboardToken(baseUrl, token, {- childAlive: () => child.exitCode === null && !child.killed,- label: `Hermes backend for profile "${profile}"`,- rememberLog- })-- 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 })-- if (!wsProbe.ok) {- throw new Error(- `Hermes backend for profile "${profile}" is HTTP-reachable but the WebSocket (/api/ws) rejected the session token: ${wsProbe.reason}`- )- }-- return {- baseUrl,- mode: 'local',- source: 'local',- authMode: 'token',- token: authToken,- profile,- wsUrl,- logs: hermesLog.slice(-80),- ...getWindowState()- }+ 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)-})-+// 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) {@@@ -12448,10 -13156,95 +12527,10 @@@ async function startHermes(requestedPro// Local WSL backend — paths are bridgeable.setWslBridgeProfileState(primaryProfile, true)- const connection = await ensureLocalGateway(() => runGatewayEnsure(setup.backend, resolveHermesCwd(), HERMES_HOME))- const backend = setup.backend- // Route old runtimes (no `serve`) through the legacy `dashboard --no-open`.- backend.args = getBackendArgsForRuntime(backend)- 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)-- const hermesProcess = spawn(- 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)++ const connection = await ensureLocalGateway(() => runGatewayEnsure({ ...setup.backend, env: desktopBackendSpawnEnv(setup.backend.env || {}, GUEST_ONBOARDING) }, resolveHermesCwd(), HERMES_HOME))+ void showPluginCompatNoticeOnce()- if (!processOwner) {- stopBackendChild(hermesProcess)- await waitForBackendExit(hermesProcess)- releaseBackendChild(hermesProcess)+ if (!backendConnectionState.isCurrentAttempt(connectionAttempt)) {throw new Error('Hermes backend start was superseded by a newer connection attempt.')}diff --cc apps/desktop/src/api/sessions.tsindex 6ac323f760b,c909d1381d3..229622bfa61--- a/apps/desktop/src/api/sessions.ts+++ b/apps/desktop/src/api/sessions.ts@@@ -10,9 -10,16 +10,18 @@@ import typeSessionSearchResponse} from '@/types/hermes'+import { createSessionMutationClient, type SessionMutationSnapshot } from '../../../shared/src/session-http-mutations'+- import { capabilityScoped, getApiRequestConnection, hermesApi, type ProfileScope, profileScoped } from './client'+ import {+ ambientOwnerConnectionId,+ capabilityScoped,+ connectionScoped,+ getApiRequestConnection,+ getApiRequestProfile,+ hermesApi,+ type ProfileScope,+ profileScoped+ } from './client'const SESSION_LIST_REQUEST_TIMEOUT_MS = 60_000diff --cc apps/desktop/src/plugins/hermes-bots/relay.test.tsindex 747bb3fd4ea,84cd45a7a6f..c782171437a--- a/apps/desktop/src/plugins/hermes-bots/relay.test.ts+++ b/apps/desktop/src/plugins/hermes-bots/relay.test.ts@@@ -512,64 -511,31 +512,89 @@@ describe('the drain loop wires drain �stopBotRelay()})+ it('drains every sender profile and delivers on the exact target profile', async () => {+ const ops = { ...route('a'), profile: 'ops', targetProfile: 'ops' }+ hostMock.profileRoutes = vi.fn(async () => [route('a'), ops, route('b')])++ const calls = respondWith(call => {+ if (call.method === 'bot_relay.outbox.drain') {return { envelopes: call.route.profile === 'ops' ? [envelope] : [] }}++ if (call.method === 'bot_relay.deliver') {return {status: 'settled', delivery_id: envelope.id, admission_id: 'admission', reply: 'isolated'}}++ return {}+ })++ const {startBotRelay, stopBotRelay} = await loadRelay()+ startBotRelay()+ await pushAndSettle()+ expect(calls.find(call => call.method === 'bot_relay.deliver')?.route).toEqual({...route('b'), profile: 'ops', targetProfile: 'ops'})+ expect(calls.find(call => call.method === 'bot_relay.reply')?.route).toEqual(ops)+ stopBotRelay()+ })++ it('retries the same envelope after pending or lost ACK without replying early', async () => {+ let attempts = 0+ let drained = false++ const calls = respondWith(call => {+ if (call.method === 'bot_relay.outbox.drain') {+ if (call.connectionId !== 'a' || drained) {return { envelopes: [] }}+ drained = true++ return { envelopes: [envelope] }+ }++ if (call.method === 'bot_relay.deliver') {+ attempts += 1++ if (attempts === 1) {throw new Error('socket lost after commit')}++ return { status: attempts === 2 ? 'queued' : 'settled', delivery_id: envelope.id,+ admission_id: 'exact-admission', reply: attempts === 2 ? '' : 'exact reply' }+ }++ return {}+ })++ const { startBotRelay, stopBotRelay } = await loadRelay()+ startBotRelay()+ await pushAndSettle()+ expect(calls.filter(call => call.method === 'bot_relay.reply')).toHaveLength(0)+ await pushAndSettle()+ expect(calls.filter(call => call.method === 'bot_relay.reply')).toHaveLength(0)+ await pushAndSettle()+ const deliveries = calls.filter(call => call.method === 'bot_relay.deliver')+ expect(deliveries).toHaveLength(3)+ expect(deliveries.every(call => call.params.id === envelope.id)).toBe(true)+ expect(calls.find(call => call.method === 'bot_relay.reply')?.params).toEqual({id: envelope.id, reply: 'exact reply'})+ stopBotRelay()+ })++ it('tells the target which connection the sender is on, so its author id names the machine', async () => {+ const calls = respondWith(call => {+ if (call.method === 'bot_relay.outbox.drain') {+ return {+ envelopes: call.connectionId === 'a' ? [{ ...envelope, from_handle: 'scout', from_profile: 'scout' }] : []+ }+ }++ return { reply: 'ok' }+ })++ const { startBotRelay, stopBotRelay } = await loadRelay()++ startBotRelay()+ await pushAndSettle()++ expect(calls.find(call => call.method === 'bot_relay.deliver')?.params).toMatchObject({+ from_connection: 'a',+ from_handle: 'scout',+ from_profile: 'scout'+ })++ stopBotRelay()+ })+it('still posts a reply when the target connection is gone — the waiter must never dangle', async () => {const calls = respondWith(call =>call.method === 'bot_relay.outbox.drain'diff --cc apps/desktop/src/plugins/hermes-bots/relay.tsindex ae3b0f91040,91adf8f7f79..b0674bfcde1--- a/apps/desktop/src/plugins/hermes-bots/relay.ts+++ b/apps/desktop/src/plugins/hermes-bots/relay.ts@@@ -407,13 -396,15 +410,16 @@@ async function drainRelayOutboxes()const attentionKey = `${target.id}::${String(envelope?.target_profile || '')}`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 || '')+ 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)diff --cc apps/desktop/src/store/gateway.tsindex b824d3a74ae,d84208b5963..e0a98a6813a--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@@ -1595,6 -1696,40 +1646,44 @@@ export function reconnectSecondaryGatew}}+ // How many non-primary backends currently hold an open socket. Hover-intent+ // prewarming consults this before spawning: a speculative spawn that pushes+ // the pool past its cap causes the Electron main to LRU-evict a warm backend+ // — often one the user is about to click — turning the prewarm into churn+ // (the #91545 evict/respawn cascade). The active gateway's backend is+ // primary-routed and never counts toward the pool cap.+ export function openSecondaryCount(): number {+ let count = 0++ for (const entry of g.secondaries.values()) {+ if (isOpen(entry.gateway)) {+ count += 1+ }+ }++ return count+ }++ // Keep the idle reaper from killing a backend we still need: ping every live+ // secondary. The active one is pinged separately (touchActiveGatewayBackend).+ // "Live" means the socket is OPEN: a wantOpen entry stuck in its reconnect+ // backoff has no consumer on that backend, and pinging it anyway kept a+ // tile-pinned backend keepalive-fresh forever, so LRU eviction and the idle+ // reaper never freed its pool slot (#103375).+ export function touchSecondaryGateways(): void {- const desktop = window.hermesDesktop++ // Older Desktop hosts own pooled children. Canonical hosts expose no touch++ // capability: their gateway lifetime is independent of renderer keepalives.++ const desktop = window.hermesDesktop as (typeof window.hermesDesktop & {++ touchBackend?: (scope: string) => Promise<unknown>++ })++ for (const entry of g.secondaries.values()) {+ if (entry.wantOpen && isOpen(entry.gateway)) {+ void desktop?.touchBackend?.(entry.scope).catch(() => undefined)+ }+ }+ }+// Tear a secondary down: stop its reconnect loop, detach listeners, close the// socket. Caller handles removal from the map.function disposeSecondary(entry: Secondary): void {diff --cc gateway/authz_mixin.pyindex c9f1499b35e,eb57a7f3343..c91f56d4e36--- a/gateway/authz_mixin.py+++ b/gateway/authz_mixin.py@@@ -475,13 -510,18 +510,23 @@@ class GatewayAuthorizationMixinOrder: trusted-upstream delegation, chat-scoped group allowlists, ``{PLATFORM}_ALLOW_BOTS``,per-platform allow-all, adapter role auth, pairing store, env/config allowlists,- ``GATEWAY_ALLOW_ALL_USERS``, default deny.+ ``GATEWAY_ALLOW_ALL_USERS``, default deny. A bot-authored message that any of these admits+ is still refused while its chat's loop guard is cooling down."""+ if not self._principal_authorized(source, allow_adapter_delegation=allow_adapter_delegation):+ return False+ if not getattr(source, "is_bot", False):+ return True+ # The guard judges the final verdict: a chat allowlist admits a bot before the ALLOW_BOTS block runs.+ return not self._bot_loop_guard_instance().blocked(self._bot_loop_guard_conversation(source))++ def _principal_authorized(self, source: SessionSource, *, allow_adapter_delegation: bool) -> bool:+ """The allowlist verdict alone, before the bot loop guard."""+ from gateway.session_local import authorize_local_source+ local_verdict = authorize_local_source(self, source)+ if local_verdict is not None:+ return local_verdict+# HA events are system-generated (HASS_TOKEN); webhook events are HMAC-verified.if source.platform in {Platform.HOMEASSISTANT, Platform.WEBHOOK}:return Truediff --cc gateway/platforms/api_server.pyindex 69fc5a7d945,72fc9a045b4..62c64bc50ab--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@@ -3644,27 -3645,15 +3663,29 @@@ class APIServerAdapter(OpenAICompatRoutroute: Optional[Dict[str, Any]] = None, session_model: Optional[str] = None,requested_runtime: Optional[Dict[str, Any]] = None, route_source: str = "global",confirmed_runtime_lock: bool = False, bind_declared_conversation: bool = False,+ request_id: Optional[str] = None, history_from_session: bool = False,- session_history_delivery: str = "") -> tuple:+ session_history_delivery: str = "", turn_author: Optional[Dict[str, Any]] = None) -> tuple:"""Create an agent and run one turn in a thread executor -> ``(result, usage)``.``agent_ref[0]`` receives the agent so SSE writers can interrupt it; ``active_run_id``registers it in ``_active_run_agents``. Under a confirmed model lock the actualprovider/model must match or the turn fails; ``runtime`` metadata is attached.``session_history_delivery`` declares #98619 session-id provenance and default-denies: only auditedproducers whose client can address the id again pass "1" (see- ``_bind_api_server_session``)."""+ ``_bind_api_server_session``).+ ``turn_author`` only labels the turn for memory attribution. It grants nothing."""+ if getattr(self.gateway_runner, "session_authority", None) is not None:+ from gateway.session_api_turn import run_api_turn+ return await run_api_turn(self, user_message=user_message, conversation_history=conversation_history,+ ephemeral_system_prompt=ephemeral_system_prompt, session_id=session_id,+ stream_delta_callback=stream_delta_callback, tool_progress_callback=tool_progress_callback,+ tool_start_callback=tool_start_callback, tool_complete_callback=tool_complete_callback,+ agent_ref=agent_ref, active_run_id=active_run_id, gateway_session_key=gateway_session_key,+ requested_model=requested_model, requested_provider=requested_provider, model_options=model_options,+ route=route, session_model=session_model, requested_runtime=requested_runtime,+ route_source=route_source, confirmed_runtime_lock=confirmed_runtime_lock,+ bind_declared_conversation=bind_declared_conversation, request_id=request_id,- history_from_session=history_from_session, session_history_delivery=session_history_delivery)++ history_from_session=history_from_session, session_history_delivery=session_history_delivery,++ turn_author=turn_author)loop = asyncio.get_running_loop()# ContextVars do not follow run_in_executor threads: capture here, re-enter in _run().request_profile = _api_request_profile.get()diff --cc gateway/platforms/api_server_runs.pyindex 6f13dfe2a1f,29025ed27ed..22ffc32a7be--- a/gateway/platforms/api_server_runs.py+++ b/gateway/platforms/api_server_runs.py@@@ -332,7 -327,7 +332,8 @@@ class _RunLaunchrequest_profile: Anybrowser_control_principal: Anybrowser_control_transport_family: Any+ turn_author: Optional[Dict[str, Any]] = None # memory-attribution label only; grants nothing+ admission: Any = None@propertydef approval_session_key(self) -> str:@@@ -494,27 -493,8 +499,29 @@@ async def _handle_runs(self, request: "**{k: agent_overrides.get(k) for k in ("requested_model", "requested_provider", "model_options")}),request_profile=_api_server._api_request_profile.get(),browser_control_principal=_api_server._api_request_browser_control_principal.get(),- browser_control_transport_family=_api_server._api_request_browser_control_transport_family.get())+ browser_control_transport_family=_api_server._api_request_browser_control_transport_family.get(),+ turn_author=turn_author)+ if getattr(self.gateway_runner, 'session_authority', None) is not None:+ from gateway.session_api_turn import admit_api_turn+ from hermes_state_runtime import RuntimeStoreError+ try:+ with self._profile_scope(launch.request_profile):+ launch.admission = admit_api_turn(self, user_message=launch.user_message,+ conversation_history=launch.conversation_history, active_run_id=run_id,++ turn_author=launch.turn_author,+ history_from_session=session_history_delivery,+ session_history_delivery='1' if session_history_delivery else '',+ bind_declared_conversation=_declared_selected,+ **launch.agent_kwargs)+ except RuntimeStoreError as exc:+ # A refused admission owns no run: drop every reservation so an exact+ # retry is refused again instead of replaying a run nobody executes.+ _forget_run(+ self, run_id, self._run_streams, self._run_streams_created, self._run_approval_sessions,+ self._run_statuses, self._run_owners, self._run_idempotency_ids)+ if idempotency_key:+ self._run_idempotency_store.forget(idempotency_scope, idempotency_key)+ return _json_error(_openai_error, exc.reason, code=exc.reason, status=409)self._activate_admitted_request()task = self._active_run_tasks[run_id] = asyncio.create_task(_execute_run(self, launch, _api_server=_api_server))with suppress(TypeError):diff --cc gateway/platforms/webhook.pyindex 8235e8c7079,1a34f58a5d5..0c017ea5117--- a/gateway/platforms/webhook.py+++ b/gateway/platforms/webhook.py@@@ -557,17 -559,20 +560,20 @@@ class WebhookAdapter(BasePlatformAdaptelogger.info("[webhook] Skipping duplicate delivery %s", delivery_id)return web.json_response({"status": "duplicate", "delivery_id": delivery_id}, status=200)if route_config.get("deliver_only"):- return await self._handle_deliver_only(prompt, payload, route_config, route_name, event_type, delivery_id)+ return await self._handle_deliver_only(prompt, payload, route_config, route_name, event_type, delivery_id,+ profile)- 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":- """Record delivery info, spawn the agent run, and return 202 immediately."""+ """Acknowledge only after the authority commits the immutable delivery."""# 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+ # THIS profile's adapter, home channel and secrets — not the first profile that has the platform.self._delivery_info[session_chat_id] = {- "deliver": route_config.get("deliver", "log"),+ "deliver": route_config.get("deliver", "log"), "profile": profile,"deliver_extra": self._render_delivery_extra(route_config.get("deliver_extra", {}), payload)}self._delivery_info_created[session_chat_id] = nowself._delivery_info_order.append((now, session_chat_id))diff --cc gateway/run.pyindex 8e979019eda,34934d24ac7..e8d2cb8e8bc--- a/gateway/run.py+++ b/gateway/run.py@@@ -3288,7 -3281,7 +3292,7 @@@ class GatewayRunnerGatewayVoiceMixin, GatewayAdapterLifecycleMixin, GatewayTopicThreadsMixin, GatewayTurnMixin,GatewayShutdownMixin, GatewayBusySessionMixin, GatewayConfigLoadersMixin, GatewayStartupMixin,GatewaySessionWatchersMixin, GatewayNotificationsMixin, GatewayInboundMixin, GatewayGoalsMixin,- GatewayAgentCacheMixin, GatewayRuntimeInitMixin):- GatewayAgentCacheMixin, GatewayWisdomMixin):++ GatewayAgentCacheMixin, GatewayRuntimeInitMixin, GatewayWisdomMixin):"""Main gateway controller: manages adapter lifecycles, routes messages to/from the agent."""# Class-level defaults so partial construction in tests doesn't blow up on attribute access.diff --cc gateway/run_turn.pyindex 62371a36a55,195e42c642d..bb5f11b3c13--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@@ -43,14 -43,217 +43,37 @@@ if TYPE_CHECKING: # string annotationlogger = logging.getLogger("gateway.run")+ _CONTEXT_OVERFLOW_ERROR_PHRASES = (+ "context length", "context size", "context window",+ "maximum context", "token limit", "too many tokens",+ "reduce the length", "exceeds the limit",+ "request entity too large", "prompt is too long",+ "payload too large", "input is too long",+ )+++ def is_context_overflow_failure_result(agent_result: dict, history_len: int) -> bool:+ """One verdict for "this failed turn is a context overflow", shared by transcript persistence+ (#1630 skip) and the user-facing reply so the two can never disagree.++ Multi-word phrases (not bare "exceed"/"token") avoid matching "rate limit exceeded" or+ "invalid authentication token"; a bare 400 only counts on a long session."""+ if not agent_result.get("failed"):+ return False+ if agent_result.get("compression_exhausted"):+ return True+ err = str(agent_result.get("error") or "").lower()+ return any(p in err for p in _CONTEXT_OVERFLOW_ERROR_PHRASES) or ("400" in err and history_len > 50)++-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``."""diff --cc tests/gateway/test_webhook_integration.pyindex 3ddd2534ec0,0f3adc0d1aa..fff62dfe32c--- a/tests/gateway/test_webhook_integration.py+++ b/tests/gateway/test_webhook_integration.py@@@ -234,8 -232,8 +234,9 @@@ class TestCrossPlatformDeliverymock_tg_adapter.send = AsyncMock(return_value=SendResult(success=True))mock_runner = MagicMock()+ mock_runner._profile_name_for_source.return_value = Nonemock_runner.adapters = {Platform.TELEGRAM: mock_tg_adapter}+ mock_runner._authorization_adapter = lambda platform, profile=None: mock_runner.adapters.get(platform)mock_runner.config = GatewayConfig(platforms={Platform.TELEGRAM: PlatformConfig(enabled=True, token="fake")})diff --cc tests/tools/test_bot_live_owner_delivery.pyindex a947f27422a,c35d5d8fd29..e1aea238dcb--- a/tests/tools/test_bot_live_owner_delivery.py+++ b/tests/tools/test_bot_live_owner_delivery.py@@@ -78,41 -42,67 +78,54 @@@ def test_terminal_receipt_is_immutable(assert mailbox.complete_delivery(tmp_path, delivery_id, status=terminal_status, reply="answer") == receiptwith pytest.raises(ValueError):mailbox.complete_delivery(tmp_path, delivery_id, status=terminal_status, reply="rewrite")- assert mailbox.deliver_to_live_owner(tmp_path, owner, "hello", delivery_id=delivery_id) == receipt- assert mailbox.claim_pending_delivery(tmp_path, owner) is None- if os.name != "nt":- for path in (tmp_path / "runtime" / mailbox.DELIVERY_DIR_NAME).iterdir():- assert path.stat().st_mode & 0o077 == 0+ with pytest.raises(ValueError):+ mailbox.complete_delivery(tmp_path, "d" * 32, status="not-terminal")-def test_fifo_survives_clock_rollback(tmp_path, monkeypatch):- from tools import bot_live_delivery as mailbox+def _ready(instance_id):+ from types import SimpleNamespace- owner = dict(profile_home=str(tmp_path.resolve()), session_id="chat",- lease_id="lease", live_session_id="live")- for timestamp, message in ((100, "first"), (90, "second")):- monkeypatch.setattr(mailbox.time, "time_ns", lambda: timestamp)- mailbox.deliver_to_live_owner(tmp_path, owner, message)- assert mailbox.claim_pending_delivery(tmp_path, owner)["message"] == "first"- assert mailbox.claim_pending_delivery(tmp_path, owner)["message"] == "second"+ return lambda home, timeout: SimpleNamespace(state="ready", endpoint=SimpleNamespace(instance_id=instance_id))[email protected]("capable", [True, False])-def test_only_canonical_capable_owner_receives_across_compression(tmp_path, capable):+def test_canonical_owner_is_the_authority_and_follows_compression(tmp_path, monkeypatch):from hermes_state import SessionDB- from hermes_cli.active_sessions import try_acquire_active_session, transfer_active_session- from tools import bot_live_delivery as mailbox+ import hermes_cli.gateway_runtime as runtime++ from types import SimpleNamespace++ monkeypatch.setattr(runtime, "discover_gateway_endpoint",+ lambda home, timeout: SimpleNamespace(state="absent", endpoint=None))+ with pytest.raises(ValueError, match="authority"):+ mailbox.find_canonical_live_owner(tmp_path)+ monkeypatch.setattr(runtime, "discover_gateway_endpoint", _ready("authority-1"))+ assert mailbox.find_canonical_live_owner(tmp_path) is None # no state.db yetdb = SessionDB(db_path=tmp_path / "state.db")- db.create_session(session_id="chat", source="cli")- db.set_session_title("chat", "Bot Chat")- meta = dict(live_session_id="live", bot_live_delivery_consumer=capable)- lease, refusal = try_acquire_active_session(session_id="chat", surface="desktop", config={},- registry_home=tmp_path, metadata=meta)- assert refusal is Nonetry:+ db.create_session(session_id="scratch", source="cli")+ db.set_session_title("scratch", "Scratch")+ assert mailbox.find_canonical_live_owner(tmp_path) is None # no Bot Chat+ db.create_session(session_id="chat", source="cli")+ db.set_session_title("chat", "Bot Chat")owner = mailbox.find_canonical_live_owner(tmp_path)- if not capable:- assert owner is None- return- assert owner["lease_id"] == lease.lease_id- queued = mailbox.deliver_to_live_owner(tmp_path, owner, "before compression")+ assert owner["canonical"] is True and owner["lease_id"] == "authority-1"+ assert owner["session_id"] == owner["live_session_id"] == "chat"db.end_session("chat", "compression")db.create_session(session_id="tip", source="cli", parent_session_id="chat")- assert transfer_active_session(lease, session_id="tip", metadata=meta)- current = mailbox.find_canonical_live_owner(tmp_path)- assert current["session_id"] == "tip"- claim = mailbox.claim_pending_delivery(tmp_path, current)- assert claim["delivery_id"] == queued["delivery_id"]- assert claim["session_id"] == "chat"- assert mailbox.claim_pending_delivery(tmp_path, current) is None+ assert mailbox.find_canonical_live_owner(tmp_path)["session_id"] == "tip"finally:- lease.release()db.close()+++ def test_delivery_keeps_the_sender_and_refuses_a_different_one_under_the_same_id(tmp_path):+ from tools import bot_live_delivery as mailbox++ owner = dict(profile_home=str(tmp_path.resolve()), session_id="chat", lease_id="lease", live_session_id="live")+ author = {"id": "bot:coder", "name": "coder", "is_bot": True}+ queued = mailbox.deliver_to_live_owner(tmp_path, owner, "hello", delivery_id="b" * 32, author=author)+ assert queued["author"] == author+ assert mailbox.deliver_to_live_owner(tmp_path, owner, "hello", delivery_id="b" * 32, author=author) == queued+ with pytest.raises(ValueError):+ mailbox.deliver_to_live_owner(tmp_path, owner, "hello", delivery_id="b" * 32, author={**author, "id": "bot:other"})+ assert "author" not in mailbox.deliver_to_live_owner(tmp_path, owner, "no sender", delivery_id="c" * 32)diff --cc tests/tools/test_bot_mode_dm.pyindex 7e9797bcf50,f2b3a8a7dee..536c5ff9d90--- a/tests/tools/test_bot_mode_dm.py+++ b/tests/tools/test_bot_mode_dm.py@@@ -211,59 -211,30 +211,71 @@@ def _capture_spawn(monkeypatch)return calls+class _FakeAuthority:+ """The target profile's canonical ``bot_relay.deliver`` door: one admission per+ envelope id, exact retries inspect it, a changed payload conflicts."""++ def __init__(self):+ self.calls = []+ self.records = {}++ def __call__(self, home, params):+ from tools import bot_live_delivery as live++ self.calls.append((Path(home).resolve(), dict(params)))+ record = self.records.get(params["id"])+ if record is None:+ record = self.records[params["id"]] = dict(+ status="queued", delivery_id=params["id"], profile_home=str(Path(home).resolve()),+ session_id="local-bot", message=params["message"], admission_id="adm-" + params["id"][:8],+ reply="")+ with live._locked(home) as root:+ live._write(root / f"{params['id']}.json", record)+ elif record["message"] != params["message"]:+ raise ValueError("admission_conflict")+ return {k: record[k] for k in ("status", "delivery_id", "profile_home", "session_id", "reply")}+++def _canonical_target(monkeypatch, target: Path) -> _FakeAuthority:+ from tools import bot_live_delivery as live++ owner = dict(profile_home=str(target.resolve()), session_id="local-bot", canonical=True,+ lease_id="authority-1", live_session_id="local-bot")+ monkeypatch.setattr(live, "find_canonical_live_owner",+ lambda home: owner if Path(home).resolve() == target.resolve() else None)+ authority = _FakeAuthority()+ monkeypatch.setattr(live, "authority_delivery", authority)+ return authority++def _runner_parts(command):+ """(mode, dm_file, transport argv) of a runner command. The optional ``--author <json>`` pair is skipped."""parts = shlex.split(command)marker = parts.index("--run-delivery")+ if parts[marker + 1] == "--author":+ marker += 2argv = parts[marker + 3 :]+ profile_home = Noneif argv[:1] == ["--profile-home"]:- argv = argv[2:]- return parts[marker + 1], parts[marker + 2], argv+ profile_home, argv = argv[1], argv[2:]+ return parts[marker + 1], parts[marker + 2], argv, profile_home+ def _runner_author(command):+ """The parsed ``--author`` payload of a runner command, or None when the pair is absent."""+ parts = shlex.split(command)+ marker = parts.index("--run-delivery")+ if parts[marker + 1] != "--author":+ return None+ 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)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(@@@ -301,8 -276,10 +313,10 @@@# message body rides the temp file, never the command lineassert "PAYLOAD_SENTINEL_7A91" not in commandassert "$(" not in command+ # the sender rides the runner argv as a stable id plus display handle+ assert _runner_author(command) == {"id": "bot:default", "name": "hermes", "is_bot": True}- # attribution prefix applied server-side; body verbatim inside the file+ # attribution prefix applied server-side; body verbatim in the admitted messagecontent = Path(dm_file).read_text(encoding="utf-8")assert content.startswith("Message from 🤖 hermes (@hermes): ")assert '$(and this is not shell)' in content@@@ -348,9 -325,11 +363,11 @@@ def test_peer_delivery_command(tmp_path)assert result["status"] == "sent"assert "spark" in result["to"]- mode, _dm_file, transport_argv = _runner_parts(calls[0]["command"])+ mode, _dm_file, transport_argv, _home = _runner_parts(calls[0]["command"])assert mode == "stdin"assert transport_argv == ["hermes", "-p", "default", "peer", "dm", "spark/researcher"]+ # the peer child reads the author from its env and forwards it in the request body+ assert _runner_author(calls[0]["command"]) == {"id": "bot:eri-mac.local/default", "name": "hermes", "is_bot": True}# bare peer name targets the peer's main agentresult2 = json.loads(@@@ -362,53 -341,67 +379,93 @@@assert transport_argv == ["hermes", "-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 a+ remote ``coder`` must not share one id. A teammate on this install still sees the bare ``bot:coder``."""+ calls = _capture_spawn(monkeypatch)+ monkeypatch.setattr("socket.gethostname", lambda: " eri/mac\x00.local ")+ home = _managed_home(tmp_path, teammates=("researcher", "coder"), peers=("spark",))+ agent = _FakeAgent(home / "profiles" / "coder", title="Bot Chat")++ assert json.loads(bot_mode_dm.message_agent_tool(target="spark", message="ping", agent=agent))["status"] == "sent"+ assert json.loads(bot_mode_dm.message_agent_tool(target="researcher", message="ping", agent=agent))["status"] == "sent"++ assert _runner_author(calls[0]["command"]) == {"id": "bot:erimac.local/coder", "name": "coder", "is_bot": True}+ assert _runner_author(calls[1]["command"]) == {"id": "bot:coder", "name": "coder", "is_bot": True}++def test_named_profile_sender_prefix(tmp_path, monkeypatch):"""A named-profile bot signs with its own handle, not @hermes."""- calls = _capture_spawn(monkeypatch)+ _capture_spawn(monkeypatch)home = _managed_home(tmp_path, teammates=("researcher", "coder"))- profile_home = home / "profiles" / "coder"- agent = _FakeAgent(profile_home, title="Bot Chat")+ authority = _canonical_target(monkeypatch, home / "profiles" / "researcher")+ monkeypatch.setattr(bot_mode_dm, "_dm_dir", lambda: tmp_path)+ agent = _FakeAgent(home / "profiles" / "coder", title="Bot Chat")result = json.loads(bot_mode_dm.message_agent_tool(target="researcher", message="hi", agent=agent))- assert result["status"] == "sent"- _mode, dm_file, _transport_argv = _runner_parts(calls[0]["command"])- assert Path(dm_file).read_text(encoding="utf-8").startswith(- "Message from 🤖 coder (@coder): "- )+ assert result["status"] == "queued"+ assert authority.calls[0][1]["message"].startswith("Message from 🤖 coder (@coder): ")+ assert _runner_author(calls[0]["command"]) == {"id": "bot:coder", "name": "coder", "is_bot": True}+++ def test_delivery_command_author_json_survives_quoting_and_windows_slash_rewrite(tmp_path, monkeypatch):+ """The author JSON sits between ``--run-delivery`` and the mode, survives shlex, and the Windows slash rewrite skips it."""+ author = {"id": "bot:default", "name": "hermes", "is_bot": True}+ command = bot_mode_dm._delivery_command(["hermes", "-p", "x"], str(tmp_path / "dm.txt"),+ stdin_file=False, author=author)+ parts = shlex.split(command)+ assert parts[2:4] == ["--run-delivery", "--author"]+ assert json.loads(parts[4]) == author+ assert parts[5] == "query-file"+ assert _runner_parts(command) == ("query-file", str(tmp_path / "dm.txt"), ["hermes", "-p", "x"])++ monkeypatch.setattr(sys, "platform", "win32")+ command = bot_mode_dm._delivery_command(["hermes", "-p", "x"], "C:\\Users\\me\\dm.txt",+ stdin_file=False, author={"id": "bot:default", "name": 'q"q', "is_bot": True})+ parts = shlex.split(command)+ assert json.loads(parts[4]) == {"id": "bot:default", "name": 'q"q', "is_bot": True}+ assert parts[6] == "C:/Users/me/dm.txt"++ # without an author the legacy shape is produced unchanged+ command = bot_mode_dm._delivery_command(["hermes"], "dm.txt", stdin_file=True)+ assert shlex.split(command)[2:4] == ["--run-delivery", "stdin"]+ assert _runner_author(command) is None-def test_spawn_failure_reports_error(tmp_path, monkeypatch):+def test_unavailable_authority_is_reported_never_worked_around(tmp_path, monkeypatch):+ """No canonical target: the sender learns the outcome is unknown and nothing+ else (no CLI, no background runner) is started."""home = _managed_home(tmp_path)agent = _FakeAgent(home, title="Bot Chat")+ from tools import bot_live_delivery as live+ def unavailable(home):+ raise ValueError("profile authority is not ready")++ monkeypatch.setattr(live, "find_canonical_live_owner", unavailable)+ monkeypatch.setattr(bot_mode_dm, "_dm_dir", lambda: tmp_path)+ import tools.terminal_tool as terminal_tool_module++ monkeypatch.setattr(terminal_tool_module, "terminal_tool",+ lambda *a, **k: pytest.fail("no runner may start without admission"))+ monkeypatch.setattr(subprocess, "run", lambda *a, **k: pytest.fail("no CLI turn may start"))+ result = json.loads(+ bot_mode_dm.message_agent_tool(target="researcher", message="hi", agent=agent)+ )+ assert result["status"] == "ambiguous"+ assert "not ready" in result["error"] and "Do not resend" in result["error"]+ assert Path(result["evidence_file"]).read_text(encoding="utf-8").endswith("hi")+++def test_notification_spawn_failure_is_reported_after_admission(tmp_path, monkeypatch):+ """The receipt waiter failing to start is a notification problem, surfaced+ beside the (already committed) admission — never a reason to re-admit."""+ home = _managed_home(tmp_path)+ target = home / "profiles" / "researcher"+ authority = _canonical_target(monkeypatch, target)+ monkeypatch.setattr(bot_mode_dm, "_dm_dir", lambda: tmp_path)import tools.terminal_tool as terminal_tool_moduledef boom(command, **kwargs):@@@ -438,9 -431,9 +495,10 @@@ def test_live_dm_admitted_before_waiterassert result["status"] == "queued"record = live.read_delivery_result(target, result["delivery_id"])assert record is not None- assert record["owner"] == owner- assert record["message"] == "Message from 🤖 hermes (@hermes): hello"- assert record["author"] == {"id": "bot:default", "name": "hermes", "is_bot": True}+ assert record["delivery_id"] == result["delivery_id"]+ assert record["profile_home"] == str(target.resolve())+ assert authority.records[result["delivery_id"]]["message"] == "Message from 🤖 hermes (@hermes): hello"++ assert authority.calls[0][1]["author"] == {"id": "bot:default", "name": "hermes", "is_bot": True}assert "notification_error" in result@@@ -540,17 -550,99 +598,69 @@@ def test_local_delivery_runner_surfacesassert returncode == 1payload = json.loads(capsys.readouterr().out)- assert payload["reason"] == "target_busy"- assert "NOT delivered" in payload["error"]---def test_query_file_delivery_closes_stdin_for_initial_attempt_and_retry(- tmp_path, monkeypatch-):- dm_file = tmp_path / "message.txt"- dm_file.write_text("secret", encoding="utf-8")- calls = []- responses = [- subprocess.CompletedProcess([], 1, stdout="", stderr="HTTP 429 rate limit"),- subprocess.CompletedProcess([], 0, stdout="", stderr=""),- ]-- def fake_run(argv, **kwargs):- calls.append((argv, kwargs))- return responses.pop(0)-- monkeypatch.setattr(subprocess, "run", fake_run)-- returncode = bot_mode_dm._run_delivery(- ["hermes", "-p", "researcher"], str(dm_file), stdin_file=False- )-- assert returncode == 0- assert len(calls) == 2- assert [kwargs["stdin"] for _argv, kwargs in calls] == [- subprocess.DEVNULL,- subprocess.DEVNULL,- ]- assert not dm_file.exists()+ assert payload["reason"] == "runtime_unavailable"+ assert "retained" in payload["error"]+ assert dm_file.read_text(encoding="utf-8") == "hi"- @pytest.mark.parametrize("args", [[], ["--run-delivery"], ["--run-delivery", "bad", "x"]])- def test_delivery_main_rejects_invalid_cli(args):- assert bot_mode_dm._delivery_main(args) == 2+ @pytest.mark.parametrize("mode, author", [+ ("stdin", {"id": "bot:eri-mac.local/coder", "name": "coder", "is_bot": True}),+ ("query-file", {"id": "bot:coder", "name": "coder", "is_bot": True}),+ ("query-file", None),+ ], ids=["stdin", "query-file", "no author"])+ def test_delivery_main_child_env_carries_only_the_argv_author(tmp_path, monkeypatch, mode, author):+ """The ``--author`` payload becomes HERMES_TURN_AUTHOR on the child. Without it the runner drops the+ variable it inherited from the sending bot's own turn instead of passing it on as the recipient's author."""+ from agent.turn_author import TURN_AUTHOR_ENV++ dm_file = tmp_path / "message.txt"+ dm_file.write_text("secret", encoding="utf-8")+ calls = []++ def fake_run(argv, **kwargs):+ calls.append((argv, kwargs))+ return subprocess.CompletedProcess(argv, 0, stdout="", stderr="")++ monkeypatch.setattr(subprocess, "run", fake_run)+ monkeypatch.setenv("HERMES_DM_TEST_MARKER", "kept")+ monkeypatch.setenv(TURN_AUTHOR_ENV, json.dumps({"id": "bot:previous", "name": "previous", "is_bot": True}))+ author_args = ["--author", json.dumps(author)] if author else []++ returncode = bot_mode_dm._delivery_main(+ ["--run-delivery", *author_args, mode, str(dm_file), "hermes", "-p", "researcher"])++ assert returncode == 0+ [(argv, kwargs)] = calls+ assert argv[:3] == ["hermes", "-p", "researcher"]+ assert kwargs["env"]["HERMES_DM_TEST_MARKER"] == "kept"+ assert (json.loads(kwargs["env"][TURN_AUTHOR_ENV]) if TURN_AUTHOR_ENV in kwargs["env"] else None) == author+ assert not dm_file.exists()+++ 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"+ dm_file.write_text("secret", encoding="utf-8")+ observed = tmp_path / "observed.txt"+ child = tmp_path / "child.py"+ child.write_text(+ "import os, pathlib, sys\n"+ "pathlib.Path(sys.argv[1]).write_text(os.environ.get('HERMES_TURN_AUTHOR', 'unset'), encoding='utf-8')\n",+ encoding="utf-8",+ )+ author = {"id": "bot:default", "name": "hermes", "is_bot": True}+ command = bot_mode_dm._delivery_command(+ [sys.executable, str(child), str(observed)], str(dm_file), stdin_file=False, author=author+ )++ result = subprocess.run(shlex.split(command), check=False)++ assert result.returncode == 0+ assert json.loads(observed.read_text(encoding="utf-8")) == author+ assert not dm_file.exists()[email protected]("mode", ["stdin", "query-file"])-def test_delivery_main_runs_valid_cli_and_unlinks(tmp_path, mode):+def test_delivery_main_runs_peer_transport_and_unlinks(tmp_path):dm_file = tmp_path / "message.txt"dm_file.write_text("secret", encoding="utf-8")observed = tmp_path / "observed.txt"diff --cc tests/tui_gateway/test_bot_live_owner_delivery.pyindex bf611763c06,c79e9c6787e..09d7b5297cc--- a/tests/tui_gateway/test_bot_live_owner_delivery.py+++ b/tests/tui_gateway/test_bot_live_owner_delivery.py@@@ -61,28 -59,35 +61,29 @@@ def test_imported_crash_marker_never_auassert schedule("live", {}, "chat") is None-def test_local_work_blocks_mailbox_claim_without_consuming_envelope(monkeypatch, tmp_path):+def test_viewer_poller_never_discovers_or_claims_bot_execution(monkeypatch, tmp_path):+ import queue+ import timeimport tools.bot_live_delivery as mailbox- owner = {"lease_id": "lease", "live_session_id": "live", "session_id": "chat"}- author = {"id": "bot:coder", "name": "coder", "is_bot": True}- pending = [{"id": "receipt", "message": "imported", "author": author}]- monkeypatch.setattr(mailbox, "find_canonical_live_owner", lambda home: owner)- monkeypatch.setattr(mailbox, "claim_pending_delivery", lambda home, pinned: pending.pop(0))- receipts = []- monkeypatch.setattr(mailbox, "complete_delivery", lambda *args, **kwargs: receipts.append((args, kwargs)))- submitted = []- def submit(rid, sid, session, text, **kwargs):- submitted.append((text, kwargs.get("turn_author")))- kwargs["terminal_callback"]({"status": "settled", "text": "reply"})- return True- poll = rebind(session_notifications._poll_bot_live_delivery_once, {- "_session_home": lambda session: tmp_path,- "_run_prompt_submit": submit,- "_notif_release_turn": lambda session: session.update(running=False),+ from tools.process_registry import process_registry+ calls = []+ monkeypatch.setattr(mailbox, 'find_canonical_live_owner', lambda home: calls.append(home))+ stop = threading.Event()+ events = queue.Queue()+ events.put({'type': 'owned-completion'})+ monkeypatch.setattr(process_registry, 'completion_queue', events)+ delivered = []+ poll = rebind(session_notifications._notification_poller_loop, {+ 'time': time, '_LOOP_POLL_SECONDS': 0, '_KANBAN_POLL_SECONDS': 0,++ '_WISDOM_POLL_SECONDS': 0, '_sync_wisdom_activity_notice': lambda *a: None,+ '_poll_bot_live_delivery_once': lambda *a: calls.append('legacy-claim'),+ '_maybe_fire_tui_loop_tick': lambda *a: None,+ '_maybe_fire_tui_heartbeat_tick': lambda *a: None,+ '_notif_poll_kanban': lambda *a: None,+ '_session_home': lambda session: tmp_path,+ '_notif_handle_ready': lambda sid, session, ready, *a, **kw: (delivered.extend(ready), stop.set()),})- session = {"history_lock": threading.RLock(), "agent": object(), "session_key": "chat",- "active_session_lease": SimpleNamespace(lease_id="lease", released=False)}- for blocker in ("running", "queued_prompt", "queued_prompts", "_auto_continue_scheduled"):- session[blocker] = True- assert poll("live", session) is False- assert pending and not submitted- session.pop(blocker)- assert poll("other-live", session) is False- assert pending- assert poll("live", session) is True- assert submitted == [("imported", author)] and not pending- assert receipts[0][0][1] == "receipt"- assert receipts[0][1]["reply"] == "reply"+ poll(stop, 'live', {'agent': object(), 'history_lock': threading.RLock(), 'session_key': 'chat',+ 'active_session_lease': SimpleNamespace(lease_id='lease', released=False)})+ assert delivered == [{'type': 'owned-completion'}]+ assert calls == []diff --cc tests/tui_gateway/test_bot_relay_methods.pyindex 56cfaa288f6,b8ab90e4a8f..ec1b0a136d2--- a/tests/tui_gateway/test_bot_relay_methods.py+++ b/tests/tui_gateway/test_bot_relay_methods.py@@@ -138,3 -161,137 +139,51 @@@ def test_reply_roundtrip_and_id_validaterr = srv._methods["bot_relay.reply"](2, {"id": "../evil"})assert "error" in err++-def test_deliver_write_failure_still_removes_tempfile(home, monkeypatch, tmp_path):- """A failed payload write must not leak the relay DM tempfile."""- import glob- import os- import tempfile as _tempfile-- made = []- real_mkstemp = _tempfile.mkstemp-- def _tracking_mkstemp(*args, **kwargs):- kwargs["dir"] = str(tmp_path)- fd, path = real_mkstemp(*args, **kwargs)- made.append(path)- return fd, path-- class _BrokenWriter:- def __enter__(self):- return self-- def __exit__(self, *exc_info):- return False-- def write(self, content):- raise OSError("disk full")-- monkeypatch.setattr("tempfile.mkstemp", _tracking_mkstemp)- monkeypatch.setattr("os.fdopen", lambda *a, **k: _BrokenWriter())- err = srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": "x"})- assert "error" in err- assert made, "mkstemp was never reached"- assert not glob.glob(str(tmp_path / "hermes-relay-dm-*")), "tempfile leaked"---def fake_runs(monkeypatch):- """Fake ``subprocess.run`` that records each call's kwargs; ``outcomes`` holds (returncode, stderr) per call."""- calls, outcomes = [], []-- def _fake_run(argv, **kwargs):- calls.append(kwargs)- code, err = outcomes.pop(0) if outcomes else (0, "")-- class _Proc:- returncode, stdout, stderr = code, "ok" if code == 0 else "", err-- return _Proc()-- monkeypatch.setattr("subprocess.run", _fake_run)- return calls, outcomes--[email protected]("sender, expected", [- ({"from_profile": "scout", "from_handle": "scout"}, {"id": "bot:scout", "name": "scout", "is_bot": True}),- ({"from_profile": "scout", "from_handle": "scout", "from_connection": "cloud-1"},- {"id": "bot:cloud-1/scout", "name": "scout", "is_bot": True}),- ({}, None),-], ids=["sender fields", "sender on another connection", "no sender fields"])-def test_deliver_child_env_carries_the_envelope_sender_on_every_attempt(home, monkeypatch, fake_runs, sender, expected):- """HERMES_TURN_AUTHOR on the child comes from the envelope's sender fields alone: the retry gets the same- author, and without sender fields a stale author on the gateway's own environment never reaches the child."""- from agent.turn_author import TURN_AUTHOR_ENV-- calls, outcomes = fake_runs- outcomes.extend([(1, "HTTP 429 rate limit"), (0, "")])- monkeypatch.setenv("HERMES_RELAY_TEST_MARKER", "kept")- monkeypatch.setenv(TURN_AUTHOR_ENV, json.dumps({"id": "bot:stale", "name": "stale", "is_bot": True}))-- _result(srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": "ping", **sender}))-- envs = [c["env"] for c in calls]- assert len(envs) == 2- assert [json.loads(e[TURN_AUTHOR_ENV]) if TURN_AUTHOR_ENV in e else None for e in envs] == [expected, expected]- assert all(e["HERMES_RELAY_TEST_MARKER"] == "kept" for e in envs)--+ class _Client:+ def __init__(self, auth_identity=None):+ self.auth_identity = auth_identity++ def write(self, obj):+ return True++ def close(self):+ return None+++ @pytest.fixture+ def bound_client(monkeypatch):+ """Bind a fake calling transport for the handler; yields a setter for its ``auth_identity``."""+ client = _Client()+ token = srv.bind_transport(client)+ try:+ yield client+ finally:+ srv.reset_transport(token)+++ SENDER = {"from_profile": "scout", "from_handle": "scout", "from_connection": "cloud-1"}+ SENDER_AUTHOR = {"id": "bot:cloud-1/scout", "name": "scout", "is_bot": True}++[email protected]("identity", [- None,- {"user_id": INTERNAL_USER_ID, "provider": INTERNAL_PROVIDER},-], ids=["no identity", "server-internal identity"])-def test_deliver_accepts_a_sender_from_an_admitted_non_login_client(home, fake_runs, bound_client, identity):- """The Desktop and server-internal callers carry no login identity; their sender fields become the author."""- from agent.turn_author import TURN_AUTHOR_ENV-- calls, _outcomes = fake_runs[email protected]("identity, refused", [++ (None, False),++ ({"user_id": INTERNAL_USER_ID, "provider": INTERNAL_PROVIDER}, False),++ ({"user_id": "alice", "provider": "google"}, True),++])++def test_relay_sender_attribution_obeys_transport_identity(home, monkeypatch, bound_client, identity, refused):++ from tools import bot_live_delivery as live++ forwarded = []++ monkeypatch.setattr(live, "authority_delivery",++ lambda home, params: forwarded.append(params) or {"status": "queued"})+ bound_client.auth_identity = identity-- _result(srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": "ping", **SENDER}))-- assert [json.loads(c["env"][TURN_AUTHOR_ENV]) for c in calls] == [SENDER_AUTHOR]---def test_deliver_refuses_a_sender_from_a_logged_in_client(home, fake_runs, bound_client):- """A browser login never relays for another connection, so its from_* fields are refused before any turn runs.- Without sender fields the same client still delivers, unattributed."""- from agent.turn_author import TURN_AUTHOR_ENV-- calls, _outcomes = fake_runs- bound_client.auth_identity = {"user_id": "alice", "provider": "google"}-- for sender in ({"from_profile": "scout"}, {"from_connection": "cloud-1"}, SENDER):- err = srv._methods["bot_relay.deliver"](1, {"profile": "ops", "message": "ping", **sender})- assert err["error"]["code"] == 4095- assert not calls-- _result(srv._methods["bot_relay.deliver"](2, {"profile": "ops", "message": "ping"}))- assert len(calls) == 1 and TURN_AUTHOR_ENV not in calls[0]["env"]++ result = srv._methods["bot_relay.deliver"](1, {++ "id": "f" * 32, "profile": "ops", "message": "ping", **SENDER})++ if refused:++ assert result["error"]["code"] == 4095++ assert not forwarded++ else:++ assert _result(result)["status"] == "queued"++ assert forwarded[0]["author"] == SENDER_AUTHOR++ assert not any(key in forwarded[0] for key in SENDER)diff --cc tools/bot_live_delivery.pyindex 3d2f6839efe,981346c779e..83e0a177739--- a/tools/bot_live_delivery.py+++ b/tools/bot_live_delivery.py@@@ -147,19 -129,68 +147,22 @@@ def deliver_to_live_ownerstate. Reusing an id with a different payload is an error, never an overwrite."""pinned = _owner(profile_home, owner)+ if not isinstance(message, str):+ raise ValueError("message must be a string")- key = _delivery_id(delivery_id if delivery_id is not None else uuid.uuid4().hex)- with _locked(profile_home) as root:- path = root / f"{key}.json"- existing = _read(path)- if existing is not None:- if existing["owner"] != pinned or existing["message"] != message or existing.get("author") != author:- raise ValueError("delivery id already belongs to a different payload")- return existing- # Wall time can roll back. Permanent receipts retain the admission- # high-water mark, allocated while holding the cross-process lock.- sequence = max((record.get("sequence", record["created_at"])- for candidate in root.glob("*.json")- if (record := _read(candidate)) is not None), default=0) + 1- record = dict(delivery_id=key, id=key, owner=pinned, **pinned,- message=message, status="queued", created_at=time.time_ns(),- sequence=sequence, **({"author": dict(author)} if author else {}))- _write(path, record)- return record---def _matches(home: Path | str, record: dict, owner: dict) -> bool:- pinned = record["owner"]- if any(pinned[key] != owner[key] for key in ("profile_home", "lease_id", "live_session_id")):- return False- if pinned["session_id"] == owner["session_id"]:- return True- from hermes_state import SessionDB-- db = SessionDB(db_path=Path(home) / "state.db", read_only=True)- try:- return db.get_compression_tip(pinned["session_id"]) == owner["session_id"]- finally:- db.close()+ home = Path(profile_home).resolve()- return authority_delivery(home, dict(id=_delivery_id(delivery_id or uuid.uuid4().hex),++ return authority_delivery(home, dict(id=_delivery_id(delivery_id if delivery_id is not None else uuid.uuid4().hex),+ profile=home.name if home.parent.name == "profiles" else "default",- message=message, session_id=pinned["session_id"]))++ message=message, session_id=pinned["session_id"],++ **({"author": dict(author)} if author else {})))-def claim_pending_delivery(- profile_home: Path | str, owner: dict[str, Any],-) -> dict[str, Any] | None:- """Claim oldest matching input exactly once; caller supplies its current lease.+def claim_pending_delivery(profile_home, owner):+ """Retired UI poller: only session_bot may migrate and admit queued records.- A lease transfer across compression is accepted only along the original- stored session's compression chain. A new lease/live session cannot steal it.- Caller must hold its normal turn-admission guard before invoking this.+ Keep this refusal until the legacy notification poller's call site is removed.+ A previously claimed record can still publish its terminal receipt below."""- current = _owner(profile_home, owner)- if not _root(profile_home).is_dir():- return None- with _locked(profile_home) as root:- pending = []- for path in root.glob("*.json"):- record = _read(path)- if record is not None and record["status"] == "queued" and _matches(profile_home, record, current):- pending.append(record)- if not pending:- return None- record = min(pending, key=lambda item: (- item.get("sequence", item["created_at"]), item["delivery_id"]))- record.update(status="claimed", claimed_at=time.time_ns())- _write(root / f"{record['delivery_id']}.json", record)- return record+ return Nonedef complete_delivery(diff --cc tools/bot_mode_dm.pyindex 7aafbad0ba3,8366a8a4fad..09a4da2d853--- a/tools/bot_mode_dm.py+++ b/tools/bot_mode_dm.py@@@ -355,7 -361,51 +361,7 @@@ def _delivery_lock(argv: list[str], *,return acquire_turn_lock(_hermes_root(Path(_default_home())), argv[2])- def _admit_live_dm(profile_home: Path | None, dm_file: str) -> dict | None:-def _run_local_turn(argv: list[str], dm_file: str, *, env: Optional[dict[str, str]] = None) -> int:- """One Bot Chat turn via ``--query-file`` (plus one policy-gated retry); re-emits- the transport's streams and returns its exit code. Transient failures re-run the- same session; a context_overflow re-run lets the retried turn's pre-API compaction- compact the transcript first (no fresh session is ever minted). Auth/quota/config never retry."""-- def _turn():- return subprocess.run([*argv, "--query-file", dm_file], check=False, stdin=subprocess.DEVNULL,- capture_output=True, text=True, env=env)-- proc = _turn()- if proc.returncode != 0:- from tools.bot_failure_reasons import RETRY_NONE, classify_agent_error, retry_action-- if retry_action(classify_agent_error((proc.stderr or proc.stdout or "").strip()[-500:])) != RETRY_NONE:- proc = _turn()- stderr_text = proc.stderr or ""- reason = next((line.removeprefix("hermes-refusal-reason: ").strip()- for line in stderr_text.splitlines()- if line.startswith("hermes-refusal-reason: ")), None)- # A code wins over prose, including unknown codes from newer CLIs.- # Only older CLIs without a marker need the historical wording fallback.- refused_not_owned = (reason == "SESSION_NOT_OWNED" if reason is not None- else "already has a live owner" in stderr_text)- if proc.returncode != 0 and refused_not_owned:- # The target's Bot Chat is held live by another surface (Desktop); the turn- # never ran — tell the sender plainly instead of leaking a raw lease error.- # See #100523.- who = argv[argv.index("-p") + 1] if "-p" in argv[:-1] else "the teammate"- print(json.dumps({- "error": f"Delivery failed: @{who}'s Bot Chat is open on another "- "surface right now, so your message was NOT delivered. Try again later.",- "reason": "target_busy",- }))- return 1- # Re-emit the transport's streams: stdout is the reply text the- # completion notification carries back to the sending agent.- for stream, text in ((sys.stdout, proc.stdout), (sys.stderr, proc.stderr)):- if text:- stream.write(text)- stream.flush()- return proc.returncode--+ def _admit_live_dm(profile_home: Path | None, dm_file: str, author: Optional[dict] = None) -> dict | None:"""Pin intent before admission; retries may inspect, never change transport."""from tools.bot_live_delivery import (_fsync_dir, deliver_to_live_owner, find_canonical_live_owner, read_delivery_result,@@@ -369,9 -419,10 +375,10 @@@assert profile_home is not Noneowner = find_canonical_live_owner(profile_home)if owner is None:- return None+ raise ValueError("canonical Bot Chat target is unavailable; no local fallback")intent = dict(owner=owner, message=Path(dm_file).read_text(encoding="utf-8"),- delivery_id=hashlib.sha256(str(Path(dm_file).resolve()).encode()).hexdigest())+ delivery_id=hashlib.sha256(str(Path(dm_file).resolve()).encode()).hexdigest(),+ **({"author": author} if author else {}))try:fd = os.open(intent_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)except FileExistsError:@@@ -384,9 -435,9 +391,9 @@@_fsync_dir(intent_path.parent)home = intent["owner"]["profile_home"]record = read_delivery_result(home, intent["delivery_id"])- if record is None:+ if record is None or intent["owner"].get("canonical"):record = deliver_to_live_owner(home, intent["owner"], intent["message"],- delivery_id=intent["delivery_id"])+ delivery_id=intent["delivery_id"], author=intent.get("author"))return record@@@ -418,11 -469,18 +425,11 @@@ def _local_delivery_home(argv: list[strdef _run_delivery(argv: list[str], dm_file: str, *, stdin_file: bool,- profile_home: Path | None = None) -> int:+ profile_home: Path | None = None, author: Optional[dict] = None) -> int:- """Route to the live owner before attempting a CLI transport. Live deliveries- retain their intent/payload and immutable receipt; only CLI/peer payloads are- removed after consumption. The CLI turn window holds the profile lock, so two- deliveries into one profile queue; a bounded wait ends in a 'target_busy' refusal.- ``author`` rides to the child as HERMES_TURN_AUTHOR; ``hermes peer dm`` forwards it in the request body.-- Local (query-file) turns get one policy-gated retry (#93091 item 5): transient failures re-run the same- session; a context_overflow re-run lets the retried turn's pre-API compaction pass compact the Bot Chat- transcript first (agent/conversation_loop.py) — the sanctioned compression lever; no fresh session is- ever minted. Auth/quota/config failures never retry. Peer transports (stdin mode) retry on their own- gateway's deliver path, not here.+ """Admit local DMs only through the profile authority; retain uncertain intent.++ The optional peer stdin transport remains an explicit remote route, never a+ fallback after local admission. Background processes wait for delivery only."""# The live consumer owns turn admission; never compete for its CLI lease.if not stdin_file:@@@ -438,11 -496,13 +445,14 @@@return 1if record is not None:return _wait_live_dm(record["profile_home"], record["delivery_id"])+ 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)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 tui_gateway/methods_bot_relay.pyindex 68ae0b1b401,5a675746e5b..dfb1810bfa6--- a/tui_gateway/methods_bot_relay.py+++ b/tui_gateway/methods_bot_relay.py@@@ -7,8 -7,12 +7,11 @@@ the SENDER gateway for its waiter). Pluserver.py's globals (method_ctx.py) and reference ``_ok``/``_err`` bare."""import os-import subprocessfrom pathlib import Path+ # Defined beside the sender-side waiter budget so the two Python sides cannot drift (#93911).+ from tools.bot_relay import TURN_ATTEMPT_TIMEOUT_SECONDS+from .method_ctx import HandlerRegistry_registry = HandlerRegistry()@@@ -21,10 -25,11 +24,9 @@@ def _relay_root() -> Pathreturn home.parent.parent if home.parent.name == "profiles" else home-def _run_delivery(profile: str, tmp: str, env: dict | None = None) -> subprocess.CompletedProcess:- from tools.bot_relay import local_delivery_command- return subprocess.run(- local_delivery_command(profile, tmp), capture_output=True, text=True, encoding="utf-8",- errors="replace", timeout=TURN_ATTEMPT_TIMEOUT_SECONDS, env=env)+# Historical Desktop deadline mirrors; no subprocess retry is performed here.+# Remove with the renderer relay deadline/receipt migration.- TURN_ATTEMPT_TIMEOUT_SECONDS = 600+TURN_MAX_ATTEMPTS = 2 # first attempt + the policy-gated re-run@method("bot_relay.roster.sync")@@@ -50,24 -55,102 +52,34 @@@ def _(rid, params: dict, _root=_relay_r@method("bot_relay.deliver")-def _(rid, params: dict, _root=_relay_root, _run=_run_delivery) -> dict:- """Deliver a relayed DM (``profile``, attribution-prefixed ``message``) into a Bot Chat ON THIS- GATEWAY via the one-turn ``hermes -p <profile> chat -c "Bot Chat"`` transport local DMs use →- ``{reply}``. Blocking by design (Desktop relay worker; the RPC pool keeps it off the reader)."""- import tempfile- profile = str(params.get("profile") or "").strip()- message = str(params.get("message") or "").strip()- if not profile or not message:- return _err(rid, 4090, "profile and message required")+def _(rid, params: dict, _root=_relay_root) -> dict:+ """Legacy transport bridge only: canonical admission or an explicit refusal."""+ from tools.bot_live_delivery import _delivery_id, authority_delivery+ from tools.bot_relay import _HANDLE_REtry:- from tools.bot_mode_dm import MESSAGE_MAX_CHARS- from tools.bot_relay import acquire_turn_lock- if len(message) > MESSAGE_MAX_CHARS + 200: # + attribution headroom- return _err(rid, 4091, "message too long")- root = _root()- known = {"default"}- if (root / "profiles").is_dir():- known.update(c.name for c in (root / "profiles").iterdir() if c.is_dir())- resolved = "default" if profile.lower() == "hermes" else profile- if resolved not in known:- return _err(rid, 4092, f"no profile '{profile}' on this gateway")-- # When THIS gateway already hosts the target's Bot Chat live, the subprocess transport is- # fenced out by the single-owner lease and the payload dropped. Land the DM in the live- # session via prompt.submit — the composer's choke point, so role alternation, persistence- # and streaming behave as a typed message would.- # (Nested per method_ctx rebinding.) See #100523.- from tools.bot_mode_probe import BOT_CHAT_TITLE- live_home = _profile_home(resolved)- want_home = str(live_home) if live_home is not None else None- live_sid = next((- live_sid for live_sid, record in list(_sessions.items())- if isinstance(record, dict) and (record.get("profile_home") or None) == want_home- and _session_live_title(- record, _session_lookup_key(record, fallback=live_sid)) == BOT_CHAT_TITLE), "")- # The sender fields are whatever the relaying client says. The author labels memory only and grants nothing.- from tools.bot_relay import DeliveryAuthor, delivery_env, delivery_turn_author- from tui_gateway.methods_browser_control import _is_authenticated_identity- sender_fields = ("from_profile", "from_handle", "from_connection")- # A logged-in browser never relays for another connection; only the Desktop and server-internal callers do.- if (any(params.get(k) for k in sender_fields)- and _is_authenticated_identity(getattr(current_transport(), "auth_identity", None))):- return _err(rid, 4095, "a logged-in client cannot name the sender of a relayed dm")- author = delivery_turn_author(*(params.get(k) for k in sender_fields))- if live_sid:- # queued=True: a teammate's DM runs as the NEXT turn and never interrupts or steers a- # turn in flight (the default busy mode does); arrivals queue in order.- submit_params: dict = {"session_id": live_sid, "text": message, "queued": True}- if author:- submit_params["_turn_author"] = DeliveryAuthor(author)- submitted = _methods["prompt.submit"](rid, submit_params)- if "error" in submitted:- return submitted- reply = f"Delivered into @{resolved}'s open Bot Chat; the reply will appear there."- return _ok(rid, {"reply": reply})-- def _detail(p) -> str:- return (p.stderr or p.stdout or "").strip()[-500:]-- turn_env = delivery_env(author)-- fd, tmp = tempfile.mkstemp(prefix="hermes-relay-dm-", suffix=".txt", text=True)- try:- with os.fdopen(fd, "w", encoding="utf-8") as f:- f.write(message)- # Per-profile turn lock serializes with any other delivery turn into this profile and- # covers only the turn window. Worst-case hold is lock wait (bot_mode.turn_wait_seconds,- # default 120s) + the 600s turn timeout, doubled on one retry — callers tolerate ~1320s.- # Worst-case handler hold is lock wait (bot_mode.turn_wait_seconds, default 120s) + the 600s- # turn timeout below — doubled when the retry policy grants one bounded re-run — so clients- # calling bot_relay.deliver must tolerate ~1320s before assuming failure. See #93091.- with acquire_turn_lock(root, resolved):- proc = _run(resolved, tmp, turn_env)- if proc.returncode != 0:- # Retry policy: transient classes re-run the SAME session once; context_overflow- # too — the retried turn's pre-API compaction pass compacts the over-threshold- # transcript first (no fresh session is minted). Auth/quota/config never retry.- # See #93091.- from tools.bot_failure_reasons import (- RETRY_NONE, classify_agent_error, retry_action)- if retry_action(classify_agent_error(_detail(proc))) != RETRY_NONE:- proc = _run(resolved, tmp, turn_env)- finally:- with contextlib.suppress(OSError):- os.unlink(tmp)- if proc.returncode != 0:- from tools.bot_failure_reasons import classify_agent_error- detail = _detail(proc)- return _err(rid, 5092, f"delivery turn failed: {detail or proc.returncode}",- data={"reason": classify_agent_error(detail)})- return _ok(rid, {"reply": (proc.stdout or "").strip()})- except subprocess.TimeoutExpired:- return _err(rid, 5093, "delivery turn timed out")- except Exception as e:- # 'target_busy' extends the structured refusal enum.- return _err(rid, 5096 if getattr(e, "reason", "") == "target_busy" else 5094, str(e))+ _delivery_id(params.get('id'))+ profile = params.get('profile')+ if not isinstance(profile, str) or not _HANDLE_RE.fullmatch(profile):+ raise ValueError('invalid profile')+ except ValueError:+ return _err(rid, 4090, 'invalid_params', data={'reason': 'invalid_params'})- resolved = 'default' if profile == 'hermes' else profile++ from tools.bot_relay import delivery_turn_author++ from tui_gateway.methods_browser_control import _is_authenticated_identity++ sender_fields = ("from_profile", "from_handle", "from_connection")++ if (any(params.get(key) for key in sender_fields)++ and _is_authenticated_identity(getattr(current_transport(), "auth_identity", None))):++ return _err(rid, 4095, "a logged-in client cannot name the sender of a relayed dm")++ author = delivery_turn_author(*(params.get(key) for key in sender_fields))++ forwarded = {key: value for key, value in params.items() if key not in sender_fields}++ if author:++ forwarded["author"] = author++ resolved = 'default' if profile.lower() == 'hermes' else profile+ root = _root()+ home = root if resolved == 'default' else root / 'profiles' / resolved+ try:- return _ok(rid, authority_delivery(home, {**params, 'profile': resolved}))++ return _ok(rid, authority_delivery(home, {**forwarded, 'profile': resolved}))+ except Exception as exc:+ return _err(rid, 5094, str(exc), data={'reason': 'runtime_unavailable'})@method("bot_relay.reply")diff --cc tui_gateway/methods_complete.pyindex 9b1b2c5cca9,0752b3317ca..126114a221f--- a/tui_gateway/methods_complete.py+++ b/tui_gateway/methods_complete.py@@@ -215,10 -221,54 +215,11 @@@ def _(rid, params: dict) -> dict@method("complete.slash")+ @_profile_scoped@_catch(5020)def _(rid, params: dict) -> dict:- text = params.get("text", "")- if not text.startswith("/"):- return _ok(rid, {"items": []})- from hermes_cli.commands_completion import SlashCommandCompleter- from prompt_toolkit.document import Document- from prompt_toolkit.formatted_text import to_plain_text- from agent.skill_commands import get_skill_commands- from agent.skill_bundles import get_skill_bundles- completer = SlashCommandCompleter(- skill_commands_provider=lambda: get_skill_commands(), skill_bundles_provider=lambda: get_skill_bundles())- # `kind` reaches the TUI as data (from the providers, not sniffed from ⚡/▣ glyphs):- # skills/bundles are the only completions for an inline `/skill` typed mid-message.- skill_names = {key.lstrip("/").lower() for key in (*get_skill_commands(), *get_skill_bundles())}-- def to_items(doc: Document) -> list[dict]:- # display/display_meta are FormattedText; the TUI contract is a plain string- # (the raw list trips Ink's row layout into 1-char truncation).- return [- {- "text": c.text, "display": to_plain_text(c.display) if c.display else c.text,- "meta": to_plain_text(c.display_meta) if c.display_meta else "",- "kind": "skill" if c.text.strip().lstrip("/").lower() in skill_names else "command"}- for c in completer.get_completions(doc, None)]- items = to_items(Document(text, len(text)))- # Rank + bound while a `/token` is under the cursor (the one stage skills are- # offered at); an argument stage (`/personality `) keeps its command's order.- if text.rsplit(" ", 1)[-1].startswith("/"):- score_of = None- # Command-token stage: the completer only emits name-prefix matches, so merge in- # catalog entries whose name SUBSTRING or DESCRIPTION words match (name outranks description).- if " " not in text and len(text) > 1:- from tui_gateway.slash_fuzzy import fuzzy_rank_slash_items, normalize_slash_search_query- items, score_of = fuzzy_rank_slash_items(- items, to_items(Document("/", 1)), normalize_slash_search_query(text))- usage, origin_of = _skill_usage_lookup()- items = _rank_slash_completions(items, usage, origin_of, browsing=text == "/", score_of=score_of)- else:- items = items[:_SLASH_COMPLETION_LIMIT]- text_lower = text.lower()- for extra_text, extra_meta in _SLASH_EXTRAS:- if extra_text.startswith(text_lower) and not any(item["text"] == extra_text for item in items):- items.append({**_item(extra_text, extra_meta), "kind": "command"})- if (details_items := _details_completions(text)) is not None:- return _ok(rid, {"items": details_items, "replace_from": text.rfind(" ") + 1 if " " in text else len(text)})- return _ok(rid, {"items": items, "replace_from": text.rfind(" ") + 1 if " " in text else 1})+ from tui_gateway.command_discovery import slash_completions+ return _ok(rid, slash_completions(params.get("text", "")))def _session_agent(params: dict):diff --cc tui_gateway/methods_tools.pyindex 72ebdcb0b7f,3cf85f3ef14..800957cb2d1--- a/tui_gateway/methods_tools.py+++ b/tui_gateway/methods_tools.py@@@ -330,10 -330,107 +330,10 @@@ def _(rid, params: dict) -> dict# ─── Command catalog / dispatch ──────────────────────────────────────────────- @_rpc("commands.catalog", 5020)-class _Catalog:- """Accumulator for commands.catalog: ``pairs`` (every [key, desc]), ``canon`` (lowercase- key/alias → canonical key), ``commands`` (key → desktop meta) and ordered categories."""-- def __init__(self) -> None:- self.pairs: list[list[str]] = []- self.canon: dict[str, str] = {}- self.commands: dict[str, dict[str, str | None]] = {}- self.cat_map: dict[str, list[list[str]]] = {} # insertion order = category order-- def add(self, key: str, desc: str, cat: str) -> None:- self.canon[key.lower()] = key- self.pairs.append([key, desc])- self.cat_map.setdefault(cat, []).append([key, desc])---def _catalog_registry(cat: _Catalog) -> None:- commands = _tools_mod("hermes_cli.commands")- for cmd in commands.COMMAND_REGISTRY:- if not commands.command_available(cmd):- continue- meta = commands.command_desktop_meta(cmd)- cat.commands.update({f"/{key}": dict(meta) for key in (cmd.name, *cmd.aliases)})- if cmd.name in _TUI_HIDDEN or cmd.gateway_only:- continue- cat.add(f"/{cmd.name}", commands._build_description(cmd), cmd.category)- for a in cmd.aliases:- cat.canon[f"/{a}".lower()] = f"/{cmd.name}"- for name, desc, category in _TUI_EXTRA:- # Registry command/alias wins over a colliding TUI extra (e.g. /compact, /sessions).- if name.lower() not in cat.canon:- cat.add(name, desc, category)---def _catalog_quick_commands(cat: _Catalog) -> None:- qcmds = _load_cfg().get("quick_commands", {}) or {}- if not (isinstance(qcmds, dict) and qcmds):- return- cat.cat_map.setdefault("User commands", []) # category exists even when every entry is malformed- for qname, qc in sorted(qcmds.items()):- if not isinstance(qc, dict):- continue- qtype = qc.get("type", "")- default_desc = {"exec": f"exec: {qc.get('command', '')}", "alias": f"alias → {qc.get('target', '')}"}- desc = str(qc.get("description") or default_desc.get(qtype, qtype or "quick command"))- cat.add(f"/{qname}", desc, "User commands")---def _catalog_plugin_commands(cat: _Catalog) -> None:- plugin_cmds = _tools_mod("hermes_cli.plugins").get_plugin_commands() or {}- if plugin_cmds:- cat.cat_map.setdefault("Plugin commands", [])- for pname, info in sorted(plugin_cmds.items()):- key = f"/{pname}"- if not isinstance(info, dict) or key.lower() in cat.canon:- continue- cat.add(key, str(info.get("description") or "Plugin command"), "Plugin commands")- mode = info.get("argument_mode")- if mode not in {"options", "text", "mixed"}:- mode = "text" if str(info.get("args_hint") or "").strip() else None- cat.commands[key] = {"argument_mode": mode, "desktop": None}---def _catalog_skills(cat: _Catalog, skills: dict[str, dict]) -> None:- """Append skill pairs and fill ``skills`` = ``{key: {usage, origin}}`` (every consumer ranks by them)."""- usage, origin_of = _skill_usage_lookup()- for k, info in sorted(_tools_mod("agent.skill_commands").scan_skill_commands().items()):- cat.pairs.append([k, str(info.get("description", "Skill"))])- name = str(info.get("name") or k.lstrip("/"))- skills[k] = {"usage": usage(name), "origin": origin_of(name)}--+ @_scoped_rpc("commands.catalog", 5020)def _(rid, params: dict) -> dict:- """Registry-backed slash metadata, categorized, no aliases. Discovery failures land in ``warning``- (skills' message wins, then quick commands', then plugins')."""- cat = _Catalog()- _catalog_registry(cat)- warning = ""- try:- _catalog_quick_commands(cat)- except Exception as e:- warning = f"quick_commands discovery unavailable: {e}"- try:- _catalog_plugin_commands(cat)- except Exception as e:- warning = warning or f"plugin command discovery unavailable: {e}"- skills: dict[str, dict] = {}- try:- _catalog_skills(cat, skills)- except Exception as e:- warning = f"skill discovery unavailable: {e}"- return _ok(rid, {- "pairs": cat.pairs, "sub": {- k: v[:] for k, v in _tools_mod("hermes_cli.commands").SUBCOMMANDS.items()- if _tools_mod("hermes_cli.commands").command_available(k)- },- "canon": cat.canon,- "commands": cat.commands,- "categories": [{"name": c, "pairs": rows} for c, rows in cat.cat_map.items()],- "skills": skills, "skill_count": len(skills), "warning": warning})+ from tui_gateway.command_discovery import command_catalog+ return _ok(rid, command_catalog(_load_cfg, _tools_mod))@method("cli.exec")diff --cc tui_gateway/server.pyindex 57eda744785,6abd0412cc8..75c5e233869--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@@ -1939,12 -3229,12 +1952,13 @@@ from . import ( # noqa: E40methods_profiles as _methods_profiles, methods_prompt as _methods_prompt, methods_session as _methods_session,methods_tools as _methods_tools, prompt_turn as _prompt_turn, billing_view as _billing_view,methods_projects as _methods_projects, methods_session_foreign as _methods_session_foreign,- methods_session_control as _methods_session_control, methods_subagents as _methods_subagents)+ methods_session_control as _methods_session_control, methods_subagents as _methods_subagents,+ methods_vault as _methods_vault, methods_free_tier as _methods_free_tier)for _m in (+ _session_registry, _agent_factory,_session_transports, _session_reaper, _session_lifecycle, _session_workdir, _compute_host_bridge, _model_switch,- _session_compression, _change_watcher, _tool_progress, _session_notifications,+ _session_compression, _change_watcher, _tool_progress, _session_wisdom, _session_notifications,_prompt_attachments, _session_history, _agent_callbacks, _session_auto_continue,_methods_complete_helpers, _methods_slash, _methods_voice, _methods_browser,_methods_browser_control, _methods_session, _methods_prompt, _methods_config,diff --cc tui_gateway/session_notifications.pyindex 668f807c015,8fb1c137e08..1f3ef7a2a8c--- a/tui_gateway/session_notifications.py+++ b/tui_gateway/session_notifications.py@@@ -525,8 -557,16 +525,12 @@@ def _notification_poller_loop(stop_evenhandle = lambda events, deferred: _notif_handle_ready( # noqa: E731sid, session, events, emitted, process_registry, format_process_notification, deferred)last_kanban_poll = last_loop_poll = 0.0+ last_wisdom_poll = 0.0while not stop_event.is_set() and not session.get("_finalized"):now = time.monotonic()+ if not session.get("running") and now - last_wisdom_poll >= _WISDOM_POLL_SECONDS:+ last_wisdom_poll = now+ _sync_wisdom_activity_notice(sid, session)- try:- _poll_bot_live_delivery_once(sid, session)- except Exception:- logger.warning("Bot live-owner delivery poll failed", exc_info=True)# /loop and /heartbeat wakeup drivers: fire a due tick for THIS session while idle (same claim-under-lock# as kanban dispatch). An active non-parked /goal owns the idle boundary and defers the loop tick.if now - last_loop_poll >= _LOOP_POLL_SECONDS:diff --cc ui-tui/src/app/interfaces.tsindex f8dac1a81d9,5d9c050a7f6..673ed3376ad--- a/ui-tui/src/app/interfaces.ts+++ b/ui-tui/src/app/interfaces.ts@@@ -29,11 -29,10 +29,12 @@@ import typeSessionInfo,SlashCatalog,SudoReq,- Usage+ Usage,+ VaultUnlockReq} from '../types.js'+import type { SubmissionDestination } from './submissionDestination.js'+export interface StateSetter<T> {(value: SetStateAction<T>): void}diff --cc ui-tui/src/app/useInputHandlers.tsindex b8698770c77,27c8694b9d8..b099af6f732--- a/ui-tui/src/app/useInputHandlers.ts+++ b/ui-tui/src/app/useInputHandlers.ts@@@ -220,18 -228,12 +229,18 @@@ 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 })- .then(r => r && (patchOverlayState({ approval: null }), patchTurnState({ outcome: 'denied' })))+ .rpc<ApprovalRespondResponse>('approval.respond', { choice: 'deny', session_id: getUiState().sid, ...sharedControlParams(overlay.approval) })+ .then(r => r && fresh() && (patchOverlayState({ approval: null }), patchTurnState({ outcome: 'denied' })))}- if (overlay.sudo || overlay.secret) {+ if (overlay.sudo || overlay.secret || overlay.vaultUnlock) {return dismissSensitivePrompt(overlay, gateway.rpc, actions.sys)}diff --cc web/src/lib/api.tsindex b7b651ae058,8a448ae0c91..d67575a0070--- a/web/src/lib/api.ts+++ b/web/src/lib/api.ts@@@ -1,7 -1,5 +1,8 @@@-import { buildHermesWebSocketUrl } from '@hermes/shared'+import { buildHermesWebSocketUrl } from "@hermes/shared";+import { createDashboardSessionMutations } from "./session-mutations";++const mutateSessionHttp = createDashboardSessionMutations(fetchJSON);+ import type { WisdomMuteControl, WisdomMuteDuration, WisdomMuteSnapshot, WisdomSyncSnapshot } from '@hermes/shared'// The dashboard can be served either at the root of its host (e.g.// https://kanban.tilos.com/) or under a URL prefix when reverse-proxied@@@ -392,80 -368,61 +371,64 @@@ export const api =},getSessionMessages: (id: string, profile = getManagementProfile()) =>fetchJSON<SessionMessagesResponse>(- appendProfileParam(- `/api/sessions/${encodeURIComponent(id)}/messages?limit=500&order=latest`,- profile,- ),+ appendProfileParam(`/api/sessions/${encodeURIComponent(id)}/messages?limit=500&order=latest`, profile)),getSessionDetail: (id: string, profile = getManagementProfile()) =>- fetchJSON<SessionInfo>(- appendProfileParam(`/api/sessions/${encodeURIComponent(id)}`, profile),- ),+ fetchJSON<SessionInfo>(appendProfileParam(`/api/sessions/${encodeURIComponent(id)}`, profile)),getSessionLatestDescendant: (id: string, profile = getManagementProfile()) =>fetchJSON<SessionLatestDescendantResponse>(- appendProfileParam(- `/api/sessions/${encodeURIComponent(id)}/latest-descendant`,- profile,- ),+ appendProfileParam(`/api/sessions/${encodeURIComponent(id)}/latest-descendant`, profile)),deleteSession: (id: string, profile = getManagementProfile()) =>- fetchJSON<{ ok: boolean }>(appendProfileParam(`/api/sessions/${encodeURIComponent(id)}`, profile), {- method: 'DELETE'- }),+ mutateSessionHttp<{ ok: boolean }>(id, "DELETE", {}, profile),getEmptySessionsCount: (profile = getManagementProfile()) =>- fetchJSON<{ count: number }>(- appendProfileParam("/api/sessions/empty/count", profile),- ),+ fetchJSON<{ count: number }>(appendProfileParam('/api/sessions/empty/count', profile)),deleteEmptySessions: (profile = getManagementProfile()) =>- fetchJSON<{ ok: boolean; deleted: number }>(- appendProfileParam("/api/sessions/empty", profile),- {- method: "DELETE",- },- ),+ fetchJSON<{ ok: boolean; deleted: number }>(appendProfileParam('/api/sessions/empty', profile), {+ method: 'DELETE'+ }),bulkDeleteSessions: (ids: string[], profile = getManagementProfile()) =>- fetchJSON<{ ok: boolean; deleted: number }>("/api/sessions/bulk-delete", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ ids, profile: profile || undefined }),+ fetchJSON<{ ok: boolean; deleted: number }>('/api/sessions/bulk-delete', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ ids, profile: profile || undefined })}),renameSession: (id: string, title: string, profile = getManagementProfile()) =>- fetchJSON<{ ok: boolean; title: string }>(`/api/sessions/${encodeURIComponent(id)}`, {- method: 'PATCH',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ title, profile: profile || undefined })- }),+ mutateSessionHttp<{ ok: boolean; title: string }>(id, "PATCH", { title }, profile),getSessionStats: (profile = getManagementProfile()) =>- fetchJSON<SessionStoreStats>(appendProfileParam("/api/sessions/stats", profile)),+ fetchJSON<SessionStoreStats>(appendProfileParam('/api/sessions/stats', profile)),exportSessionUrl: (id: string, profile = getManagementProfile()) =>appendProfileParam(`/api/sessions/${encodeURIComponent(id)}/export`, profile),- importSessions: (sessions: Array<Record<string, unknown>>, profile = getManagementProfile()) =>- fetchJSON<SessionImportResponse>('/api/sessions/import', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ sessions, profile: profile || undefined })- }),- pruneSessions: (older_than_days: number, source?: string, profile = getManagementProfile()) =>- fetchJSON<{ ok: boolean; removed: number; skipped_open: number }>('/api/sessions/prune', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- older_than_days,- source,- profile: profile || undefined- })- }),+ importSessions: (+ sessions: Array<Record<string, unknown>>,+ profile = getManagementProfile(),+ ) => {+ const id = sessions[0]?.id;+ if (typeof id !== "string" || !id) return Promise.reject(new Error("session id is required"));+ return mutateSessionHttp<SessionImportResponse>(id, "POST", { sessions }, profile);+ },+ pruneSessions: (+ older_than_days: number,+ source?: string,+ profile = getManagementProfile(),+ ) =>+ fetchJSON<{ ok: boolean; removed: number; skipped_open: number }>(+ "/api/sessions/prune",+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ older_than_days,+ source,+ profile: profile || undefined,+ }),+ },+ ),listFiles: (path?: string) => {- const query = path ? `?path=${encodeURIComponent(path)}` : "";- return fetchJSON<ManagedFilesResponse>(`/api/files${query}`);+ const query = path ? `?path=${encodeURIComponent(path)}` : ''+ return fetchJSON<ManagedFilesResponse>(`/api/files${query}`)},- readFile: (path: string) =>- fetchJSON<ManagedFileReadResponse>(- `/api/files/read?path=${encodeURIComponent(path)}`,- ),+ readFile: (path: string) => fetchJSON<ManagedFileReadResponse>(`/api/files/read?path=${encodeURIComponent(path)}`),uploadFile: (path: string, file: File, overwrite = true) => {// Stream the raw bytes as multipart/form-data. Do NOT set Content-Type —// the browser adds the multipart boundary automatically. Sending the file