Skip to content

The agent that grows with you

Merge origin/main into feat/unified-gateway-runtime

Teknium0715474bfdde
diff --cc .github/workflows/ci.yaml
index 4e4a21804af,bebfc22ecaf..22e1e6f2f04
--- a/.github/workflows/ci.yaml
+++ b/.github/workflows/ci.yaml
@@@ -90,10 -94,7 +94,11 @@@ jobs
steps:
- uses: actions/checkout@f548e57e544e1ff5a4c46bf1e1b8685f8e4a348a # v7.0.1
with:
+ ref: ${{ inputs.commit }}
+ sparse-checkout: |
+ .github/actions/detect-changes
+ scripts/ci/classify_changes.py
+ sparse-checkout-cone-mode: false
- name: Detect affected areas
id: classify
uses: ./.github/actions/detect-changes
diff --cc agent/auxiliary_client.py
index 6c8eee1651b,5f90dd890f2..d438b306fa5
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@@ -32,7 -32,7 +32,7 @@@ from agent.error_classifier import
is_reasoning_required_rejection,
)
from agent.auxiliary_reasoning_floor import remember_reasoning_floor, with_reasoning_floor
- from agent.auxiliary_structured_output import _without_structured_output_format, remember_structured_output_rejection
-from agent.auxiliary_structured_output import _route_key, remember_structured_output_rejection
++from agent.auxiliary_structured_output import _route_key, _without_structured_output_format, remember_structured_output_rejection
from agent.codex_headers import (
CODEX_AUX_BASE_URL as _CODEX_AUX_BASE_URL,
apply_required_codex_headers as _apply_required_codex_headers,
diff --cc apps/desktop/electron/main.ts
index d87a142fd2b,1aa614e238e..c4d48481288
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@@ -283,10 -284,9 +284,9 @@@ import
import { downloadViaOauthSessionToFile, downloadViaTokenToFile } from './gateway-file-download-transport'
import { stopGatewayBeforeUpdate } from './gateway-stop-before-update'
import { resolveGatewayVersion } from './gateway-version'
-import { probeGatewayWebSocket, spawnedBackendProbeOptions } from './gateway-ws-probe'
+import { probeGatewayWebSocket } from './gateway-ws-probe'
import { windowsGitCandidates } from './git-binary-candidates'
import { registerGitIpc } from './git-ipc'
- import { desktopBackendSpawnEnv, guestOnboardingEnabled } from './guest-onboarding'
import {
assertExistingPathForOpen,
ATTACHMENT_UPLOAD_DEFAULT_MAX_BYTES,
@@@ -11757,121 -12091,358 +11754,121 @@@ async function dialPoolBackend(profile
}
}
- // Everything below starts a LOCAL `hermes serve` child. Multiplex-only says
- // the host has exactly one, and routing (resolveProfileBackendRoute case 6)
- // keeps local profiles off this path — this is the backstop that makes the
- // pool spawn path genuinely unreachable rather than merely unused.
- // Same options object the router reads, so the guard cannot drift from it
- // (profileRouteOptions folds the per-profile SSH override into
- // profileRemoteOverride; a hand-rolled term here missed that).
- const guardRoute = profileRouteOptions(profile)
+ assertLocalProfileCanStart(profile, profileDeletionGate, key =>
+ directoryExists(path.join(HERMES_HOME, 'profiles', key))
+ )
- assertNoSecondLocalBackend(poolKey, {
- isolated: guardRoute.isolatedBackend,
- primaryRemoteActive: guardRoute.primaryRemoteActive,
- profileRemoteOverride: opts.forceLocal ? false : guardRoute.profileRemoteOverride,
- unscopableRequest: opts.unscopableRequest
- })
+ const connection = await ensureLocalGateway(async () => {
+ const backend = await ensureRuntime(
+ await resolveHermesBackend(['--profile', profile, 'gateway', 'ensure', '--json']),
+ () => assertPoolEntryStillOwned(poolKey, entry)
+ )
- // Bound the slot wait BELOW the renderer's backend-boot budget (45s): once
- // the renderer has given up on this spawn, a ticket still queued for the
- // pool-idle window (10 min) would hold the pool key hostage and every
- // later click on the profile would join that stale wait. Failing here
- // surfaces the "all N slots busy" reason instead of a generic boot timeout.
- // The caller stamped entry.spawnPriority from its own request; a foreground
- // dial that joined the claim before this entry existed left a mark instead.
- if (takeForegroundSpawn(poolKey, profile)) {
- entry.spawnPriority = 'foreground'
- }
+ profileDeletionGate.assertCanStart(profile)
+ assertPoolEntryStillOwned(poolKey, entry)
- const spawnPriority: LocalBackendSpawnPriority = spawnPriorityFrom(entry.spawnPriority)
+ // Never another profile's dotenv credentials from the Desktop env (#68367).
+ return runGatewayEnsure(
- { ...backend, env: desktopBackendSpawnEnv(backend.env || {}, GUEST_ONBOARDING) },
++ { ...backend, env: desktopBackendSpawnEnv(backend.env || {}) },
+ resolveHermesCwd(),
+ HERMES_HOME,
+ profileBackendParentEnv({ hermesHome: HERMES_HOME, profile })
+ )
+ }, async () => {
+ // Same update mutual exclusion as the primary's waitForLocalStart (#73822);
+ // a held update shows the window's blocked screen for this profile too.
+ await waitForPoolUpdateClearance({
+ profile,
+ poolKey,
+ gateDeps: updateGateDeps,
+ signal: localBackendLifecycle.signal,
+ isCancelled: (): boolean => backendPool.get(poolKey) !== entry,
+ log: rememberLog,
+ showHold: showUpdateHold,
+ clearHold: clearUpdateHold,
+ 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)))
+ }, restartStaleLocalGateway)
- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
+ assertPoolEntryStillOwned(poolKey, entry)
- if (spawnPriority === 'background' && !backgroundSlotRetryBackoff.canAttempt(poolKey)) {
- throw new BackgroundSlotRetryDeferredError(profile)
- }
+ return { ...connection, profile, logs: hermesLog.slice(-80), ...getWindowState() }
+}
- // The arbiter subscribes to the actual coordinator queue, so a later
- // foreground promotion receives reclamation too, not just fresh starts.
- const spawnRequest = localBackendSpawnCoordinator.request(poolKey, {
- timeoutMs: POOL_SLOT_WAIT_MS,
- priority: spawnPriority
- })
+// `hermes gateway restart` drains in-flight turns before the owner exits; the CLI client is
+// bounded so a wedged drain cannot hang Restart. The gateway's own drain is unaffected by the kill.
+const GATEWAY_RESTART_CLIENT_TIMEOUT_MS = 120_000
- entry.localBackendSlotKey = poolKey
- entry.localBackendSpawnRequest = spawnRequest
+// Supervised restart of the per-host gateway Desktop attaches to (it never owns that process):
+// the same resolver, spawn helper and Windows quoting as `gateway ensure`, against the profile
+// that owns the gateway process. A non-zero exit is logged, not thrown: the re-ensure that
+// follows reports what actually answers.
+async function restartLocalGatewayOwner(ownerProfile: string): Promise<void> {
+ const backend = await ensureRuntime(
+ await resolveHermesBackend(['--profile', ownerProfile, 'gateway', 'restart']),
+ () => undefined
+ )
- if (spawnRequest.queued) {
- rememberLog(
- `Profile backend "${profile}" waiting for a free local slot (${localBackendSpawnCoordinator.activeCount}/${poolMaxBackends()} busy, ${localBackendSpawnCoordinator.queuedCount} queued)`
- )
- }
+ const result = await runGatewayEnsure(
- { ...backend, env: desktopBackendSpawnEnv(backend.env || {}, GUEST_ONBOARDING) },
++ { ...backend, env: desktopBackendSpawnEnv(backend.env || {}) },
+ resolveHermesCwd(),
+ HERMES_HOME,
+ profileBackendParentEnv({ hermesHome: HERMES_HOME, profile: ownerProfile }),
+ { timeoutMs: GATEWAY_RESTART_CLIENT_TIMEOUT_MS, label: 'hermes gateway restart' }
+ )
- const cancelRequest = (): void => {
- spawnRequest.cancel()
- }
+ const reason = `${result.stdout}\n${result.stderr}`.trim().split(/\r?\n/).filter(Boolean).pop()
+ rememberLog(`[gateway] hermes --profile ${ownerProfile} gateway restart exited ${result.code}${reason ? `: ${reason}` : ''}`)
+}
- localBackendLifecycle.signal.addEventListener('abort', cancelRequest, { once: true })
+// A ready gateway whose boot commit differs from this Hermes (it outlived `hermes update`) is
+// restarted once before attaching instead of being re-attached on every dial.
+const restartStaleLocalGateway = createStaleGatewayRestarter(restartLocalGatewayOwner, rememberLog)
- try {
- entry.releaseLocalBackendSlot = await spawnRequest.acquired
- backgroundSlotRetryBackoff.clear(poolKey)
- } catch (error) {
- if (isBackgroundSlotWaitTimeout(error)) {
- backgroundSlotRetryBackoff.recordFailure(poolKey)
- }
+// Models-page "Restart Hermes": restart the local gateway behind `profile`'s cached descriptor.
+// A remote/SSH descriptor has no gatewayEndpoint, so nothing local is touched for it.
+async function restartAttachedLocalGateway(profile: string): Promise<void> {
+ const pending = profile === primaryProfileKey()
+ ? backendConnectionState.getPromise()
+ : localProfilePoolKeys(profile).map(key => backendPool.get(key)?.connectionPromise).find(Boolean)
- throw error
- } finally {
- localBackendLifecycle.signal.removeEventListener('abort', cancelRequest)
- }
+ const connection = await pending?.catch(() => null)
+ const endpoint = connection?.gatewayEndpoint
- if (entry.localBackendSpawnRequest === spawnRequest) {
- entry.localBackendSpawnRequest = null
+ if (endpoint) {
+ await restartLocalGatewayOwner(gatewayOwnerProfile(endpoint))
}
+}
- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
+// Forget a cached descriptor. Nothing is killed: the gateway behind it owns its
+// own lifetime (`hermes gateway ensure` attach semantics), so the next
+// ensure*() for this key simply re-dials. Every retire path — dispatch probe
+// failure, resume revalidation, registry removal, profile delete/rename, quit —
+// funnels through here so the verb stays in one place.
+async function stopPoolBackend(profile: string) {
+ backendPool.delete(profile)
+}
- const token = crypto.randomBytes(32).toString('base64url')
+// Profile delete/rename also drops a per-profile SSH remote's tunnel/server
+// (main's pool-stop fence ran this for every key, #106935). Teardown runs inside
+// the bootstrap drain barrier; a failure is logged, never thrown, so it cannot
+// block the delete/rename it belongs to.
+async function teardownPoolBackendAndWait(profile) {
+ await Promise.all(
+ localProfilePoolKeys(profile).map(async key => {
+ await stopPoolBackend(key)
- // Same update mutual exclusion as the primary window's waitForLocalStart
- // (#73822): pool backends spawn from the same venv, so an ungated respawn
- // during applyUpdates' critical section starts a backend on the runtime
- // being replaced. No boot-progress UI here — pool backends boot
- // silently for background profiles — so we only log while parked.
- await waitForPoolUpdateClearance({
- profile,
- poolKey,
- gateDeps: updateGateDeps,
- signal: localBackendLifecycle.signal,
- isCancelled: (): boolean => backendPool.get(poolKey) !== entry,
- log: rememberLog,
- showHold: showUpdateHold,
- clearHold: clearUpdateHold,
- pollMs: UPDATE_WAIT_POLL_MS,
- timeoutMs: UPDATE_WAIT_TIMEOUT_MS
- })
-
- profileDeletionGate.assertCanStart(profile)
-
- // --profile wins over the inherited HERMES_HOME env (see _apply_profile_override
- // step 3 in hermes_cli/main.py), so the child re-homes to this profile.
- // --port 0: the OS assigns an ephemeral port; the child announces it on stdout.
- const backendArgs = ['--profile', profile, 'serve', '--host', '127.0.0.1', '--port', '0']
-
- const backend = await ensureRuntime(await resolveHermesBackend(backendArgs), () =>
- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
- )
-
- // Route old runtimes (no `serve`) through the legacy `dashboard --no-open`.
- backend.args = await getBackendArgsForRuntime(backend)
- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
- const hermesCwd = resolveHermesCwd()
-
- const webDist = resolveDashboardWebDist({
- activeHermesRoot: ACTIVE_HERMES_ROOT,
- appRoot: APP_ROOT,
- env: process.env
- })
-
- const readyFile = backend.readyFile ? makeDashboardReadyFile() : null
-
- // Guard BEFORE the "Starting" line: a profile that only exists on a remote
- // backend (remote-primary desktop asked for a forced-local child) rejects
- // here, and logging "Starting" first left an orphaned line with no READY
- // and no exit — the exact undiagnosable burst signature in remote-gateway
- // user bundles (Aug 2026, Dash's report).
- assertLocalProfileCanStart(profile, profileDeletionGate, key =>
- directoryExists(path.join(HERMES_HOME, 'profiles', key))
- )
- rememberLog(`Starting Hermes backend for profile "${profile}" via ${backend.label}`)
-
- const parentStartMarker = await desktopParentStartMarker()
- const backendNonce = crypto.randomBytes(16).toString('hex')
- const parentIdentityEnv = parentWatchdogEnv(process.pid, parentStartMarker, backendNonce)
- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
-
- const child = spawnOwnedBackend(
- windowsShellCommand(backend.command, Boolean(backend.shell)),
- backend.args,
- hiddenWindowsChildOptions({
- cwd: hermesCwd,
- env: desktopBackendSpawnEnv({
- // Never another profile's dotenv credentials from the Desktop env (#68367), and never
- // the launch profile's TERMINAL_CWD: a pooled backend serves THIS --profile, whose
- // placeholder/unset terminal.cwd sessions must resolve their own workspace, not the
- // app-global one (#87584). The child re-resolves from its profile config like a
- // standalone `hermes -p X serve`.
- ...pooledProfileBackendEnv({ hermesHome: HERMES_HOME, profile, backendEnv: backend.env }),
- 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 } : {})
- }),
- shell: backend.shell,
- stdio: ['ignore', 'pipe', 'pipe']
- })
- )
-
- entry.process = child
- entry.token = token
- registerLocalBackendExitFinalizer(backendPool, poolKey, entry, () => releaseLocalBackendSlot(entry))
- // Buffer stdout+stderr from the instant of spawn (#93608): an early crash's
- // traceback must survive into the claim error and the before-ready exit
- // message instead of a bare exit code. rememberLog attaches later, after
- // the claim, and would miss anything printed before it.
- const outputTail = createBackendOutputTail()
- outputTail.attach(child)
-
- let ready = false
- let rejectStart = null
-
- const startFailed = new Promise((_resolve, reject) => {
- rejectStart = reject
- })
-
- // Exit/error can now arrive while the ownership claim is still pending.
- startFailed.catch(() => {})
-
- child.once('error', error => {
- rememberLog(`Hermes backend for profile "${profile}" failed to start: ${error.message}`)
- void teardownFailedLocalBackend(poolKey, entry).catch(cleanupError => {
- rememberLog(
- `Hermes backend for profile "${profile}" cleanup failed: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`
- )
+ try {
+ await sshBootstrapCoordinator.cancelAndWait(key, () => teardownSshConnection(key))
+ } catch (err) {
+ sshRememberLog(`[ssh-teardown] ${key}: ${String(err)}`)
+ }
})
- rejectStart?.(error)
- })
- child.once('exit', (code, signal) => {
- rememberLog(formatBackendExitLine(`Hermes backend for profile "${profile}" exited`, code, signal, outputTail))
- releaseBackendChild(child)
-
- if (!ready) {
- rejectStart?.(
- new Error(
- `Hermes backend for profile "${profile}" exited before it became ready (${signal || code}).${outputTail.describe()}`
- )
- )
- }
- })
-
- // Start watching for the READY announcement BEFORE any await (#60323):
- // stdout is already flowing into the tail, and Node streams never replay
- // consumed chunks to late listeners — a sentinel printed while
- // claimBackendChild runs would otherwise be lost forever, timing out a
- // healthy backend. The tail-buffer accessor covers any residual gap.
- const portAnnouncement = waitForDashboardPortAnnouncement(child, {
- bufferedOutput: () => outputTail.text(),
- describeOutputTail: () => outputTail.describe(),
- readyFile
- })
-
- portAnnouncement.catch(() => {})
- await claimBackendChild(child, `${backend.command} ${backend.args.join(' ')}`, profile, backendNonce, outputTail)
- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
-
- child.stdout.on('data', rememberLog)
- child.stderr.on('data', rememberLog)
-
- const port = await Promise.race([portAnnouncement, startFailed])
- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
-
- if (readyFile) {
- fs.unlink(readyFile, () => {})
- }
-
- entry.port = port
-
- const baseUrl = `http://127.0.0.1:${port}`
- await Promise.race([waitForHermes(baseUrl, token), startFailed])
- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
- ready = true
-
- const childAlive = () => child.exitCode === null && !child.killed
-
- const authToken = await adoptServedDashboardToken(baseUrl, token, {
- childAlive,
- label: `Hermes backend for profile "${profile}"`,
- rememberLog
- })
-
- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
-
- 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)}`
-
- // Our own child: a cold start can stall its loop past the base budget (#96177).
- const wsProbe = await probeGatewayWebSocket(wsUrl, {
- WebSocketImpl: globalThis.WebSocket,
- ...spawnedBackendProbeOptions(childAlive)
- })
-
- assertPoolEntryStillOwned(poolKey, entry, backendPool, localBackendLifecycle.signal)
-
- if (!wsProbe.ok) {
- throw new Error(
- `Hermes backend for profile "${profile}" is HTTP-reachable but the WebSocket (/api/ws) rejected the session token: ${wsProbe.reason}`
- )
- }
-
- return {
- baseUrl,
- mode: 'local',
- source: 'local',
- authMode: 'token',
- token: authToken,
- profile,
- wsUrl,
- logs: hermesLog.slice(-80),
- ...getWindowState()
- }
-}
-
-// Bounded, deduplicated pool teardown (see pool-stop.ts): every stop path —
-// idle reaper, LRU eviction, profile delete/rename, quit — shares one
-// in-flight stop per key and retains the process handle until the bounded
-// physical shutdown promise resolves. Previously
-// SIGTERM + immediate entry delete dropped the handle and a slow child
-// survived detached under PID 1.
-const poolStopper = createPoolStopper({
- pool: backendPool,
- // localBackendLifecycle is the single owner of local child stop semantics:
- // stopChild triggers its stop (stop + bounded exit wait + slot release);
- // waitForExit resolves when that same stop promise settles. Remote /
- // SSH-isolated pool entries keep `process: null` — child exit is immediate
- // there, so the same in-flight fence carries only the bootstrap drain +
- // SSH teardown below (#106935).
- stopChild: child => {
- void localBackendLifecycle.stop(child as ChildProcess | null | undefined)
- },
- waitForExit: child => localBackendLifecycle.stop(child as ChildProcess | null | undefined),
- afterStop: async key => {
- try {
- await sshBootstrapCoordinator.cancelAndWait(key, () => teardownSshConnection(key))
- } catch (err) {
- // The idle reaper calls stopPoolBackend un-awaited; a failed SSH teardown
- // must not surface as an unhandled rejection or block the pool fence.
- sshRememberLog(`[ssh-teardown] ${key}: ${String(err)}`)
- }
- }
-})
-
-function stopPoolBackend(profile: string): Promise<void> {
- const entry = backendPool.get(profile)
-
- const stopping = releaseLocalBackendSlotAfterExit(
- () => releaseLocalBackendSlot(entry),
- () => poolStopper.stop(profile)
)
-
- // Fire-and-forget callers still need diagnostics; awaiters receive the
- // rejection, while physical ownership and the exit finalizer remain live.
- void stopping.catch(error => {
- rememberLog(`Profile backend "${profile}" stop failed: ${error instanceof Error ? error.message : String(error)}`)
- })
-
- return stopping
-}
-
-// Tell every window the pooled backend under `poolKey` is being retired so the
-// renderer parks that scope (wantOpen=false) instead of redialing into the
-// slot it just vacated. Fired BEFORE the SIGTERM (pool-retire.ts contract).
-function broadcastPoolBackendRetiring(poolKey: string) {
- for (const win of BrowserWindow.getAllWindows()) {
- const { webContents } = win
-
- if (webContents && !webContents.isDestroyed()) {
- webContents.send('hermes:pool:retiring', { poolKey })
- }
- }
-}
-
-const poolRetirer = createPoolRetirer({
- pool: backendPool,
- coordinator: localBackendSpawnCoordinator,
- ...createPoolRetirementClient(fetchJson),
- stopBackend: stopPoolBackend,
- onRetiring: broadcastPoolBackendRetiring,
- log: rememberLog
-})
-
-localBackendLifecycle.signal.addEventListener('abort', poolRetirer.dispose, { once: true })
-
-async function teardownPoolBackendAndWait(profile) {
- await Promise.all(localProfilePoolKeys(profile).map(key => stopPoolBackend(key)))
}
async function stopAllPoolBackends() {
@@@ -12239,25 -13111,274 +12236,25 @@@ async function startHermes(requestedPro
// Local WSL backend — paths are bridgeable.
setWslBridgeProfileState(primaryProfile, true)
- stopAttachedBackendMonitor()
-
- const backend = setup.backend
- // Route old runtimes (no `serve`) through the legacy `dashboard --no-open`.
- backend.args = await getBackendArgsForRuntime(backend)
- backendConnectionState.assertCurrentAttempt(connectionAttempt)
- const hermesCwd = resolveHermesCwd()
-
- const webDist = resolveDashboardWebDist({
- activeHermesRoot: ACTIVE_HERMES_ROOT,
- appRoot: APP_ROOT,
- env: process.env
- })
-
- 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 = primaryProfile
- const parentStartMarker = await desktopParentStartMarker()
- const backendNonce = crypto.randomBytes(16).toString('hex')
- const parentIdentityEnv = parentWatchdogEnv(process.pid, parentStartMarker, backendNonce)
-
- backendConnectionState.assertCurrentAttempt(connectionAttempt)
-
- const hermesProcess = spawnOwnedBackend(
- windowsShellCommand(backend.command, Boolean(backend.shell)),
- backend.args,
- hiddenWindowsChildOptions({
- cwd: hermesCwd,
- env: desktopBackendSpawnEnv({
- // Never another profile's dotenv credentials from the Desktop env (#68367).
- ...profileBackendParentEnv({ hermesHome: HERMES_HOME, profile: activeProfile }),
- // 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 } : {})
- }),
- 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(() => {})
-
- const processOwner = await backendConnectionState.claimProcess(
- connectionAttempt,
- hermesProcess,
- (child: ChildProcess): ReturnType<typeof claimBackendChild> =>
- claimBackendChild(
- child,
- `${backend.command} ${backend.args.join(' ')}`,
- profile,
- backendNonce,
- primaryOutputTail
- )
- )
-
- if (!processOwner) {
- await localBackendLifecycle.stop(hermesProcess)
- releaseBackendChild(hermesProcess)
- throw new Error('Hermes backend start was superseded by a newer connection attempt.')
- }
-
- hermesProcess.stdout.on('data', rememberLog)
- hermesProcess.stderr.on('data', rememberLog)
- let backendReady = false
- let rejectBackendStart = null
-
- const backendStartFailed = new Promise((_resolve, reject) => {
- rejectBackendStart = reject
- })
-
- hermesProcess.once('error', error => {
- releaseBackendChild(hermesProcess)
-
- if (!backendConnectionState.clearForCurrentProcess(processOwner)) {
- rememberLog(`Ignoring stale Hermes backend error: ${error.message}`)
- scheduleUnexpectedPrimaryRecovery({ error: error.message, ready: backendReady })
- rejectBackendStart?.(new Error('Hermes backend start was superseded by a newer connection attempt.'))
-
- return
- }
-
- // The CURRENT owner failed to start: its routing identity must not
- // outlive it. A newer attempt already re-pins on its own decision
- // (#108417), and the stale branch above never reaches this clear.
- primaryProfilePin.clear()
-
- rememberLog(`Hermes backend failed to start: ${error.message}`)
- updateBootProgress(
- {
- error: error.message,
- message: `Hermes backend failed to start: ${error.message}`,
- phase: 'backend.error',
- running: false
- },
- { allowDecrease: true }
- )
- sendBackendExit({ code: null, signal: null, error: error.message })
- rejectBackendStart?.(error)
- })
- hermesProcess.once('exit', (code, signal) => {
- releaseBackendChild(hermesProcess)
-
- if (!backendConnectionState.clearForCurrentProcess(processOwner)) {
- rememberLog(formatBackendExitLine('Ignoring stale Hermes backend exit', code, signal, primaryOutputTail))
-
- scheduleUnexpectedPrimaryRecovery({ code, signal, ready: backendReady })
-
- if (!backendReady) {
- rejectBackendStart?.(new Error('Hermes backend start was superseded by a newer connection attempt.'))
- }
-
- return
- }
-
- rememberLog(formatBackendExitLine('Hermes backend exited', code, signal, primaryOutputTail))
-
- // The current primary child is gone; release its routing pin so the
- // next startHermes() re-reads active-profile.json instead of re-pinning
- // the dead child's profile (#108417). Supervisor respawns go through
- // startHermes, which makes a fresh decision — a respawn cannot inherit
- // a pin from a process that no longer exists.
- primaryProfilePin.clear()
-
- if (!scheduleUnexpectedPrimaryRecovery({ code, signal, ready: backendReady })) {
- sendBackendExit({ code, signal })
- }
-
- if (!backendReady) {
- const message = `Hermes backend exited before it became ready (${signal || code}).${primaryOutputTail.describe()}`
- updateBootProgress(
- {
- error: message,
- message,
- phase: 'backend.error',
- running: false
- },
- { allowDecrease: true }
- )
- rejectBackendStart?.(
- new Error(
- `Hermes backend exited before it became ready (${signal || code}). Log: ${DESKTOP_LOG_PATH}\n${recentHermesLog()}`
- )
- )
- }
- })
-
- await advanceBootProgress('backend.port', 'Waiting for Hermes backend to launch', 86)
- backendConnectionState.assertCurrentAttempt(connectionAttempt)
+ const connection = await ensureLocalGateway(() => runGatewayEnsure(
- { ...setup.backend, env: desktopBackendSpawnEnv(setup.backend.env || {}, GUEST_ONBOARDING) },
++ { ...setup.backend, env: desktopBackendSpawnEnv(setup.backend.env || {}) },
+ resolveHermesCwd(),
+ HERMES_HOME,
+ profileBackendParentEnv({ hermesHome: HERMES_HOME, profile: primaryProfile })
+ ), undefined, restartStaleLocalGateway)
- // Discover the ephemeral port the child bound to
- const port = await Promise.race([portAnnouncement, backendStartFailed])
backendConnectionState.assertCurrentAttempt(connectionAttempt)
- if (readyFile) {
- fs.unlink(readyFile, () => {})
- }
-
- const baseUrl = `http://127.0.0.1:${port}`
- await advanceBootProgress('backend.wait', 'Waiting for Hermes backend to become ready', 90)
- backendConnectionState.assertCurrentAttempt(connectionAttempt)
- await Promise.race([waitForHermes(baseUrl, token), backendStartFailed])
- backendConnectionState.assertCurrentAttempt(connectionAttempt)
- backendReady = true
- // The host now has a bound, registered backend: the next launcher will
- // discover and attach to it, so the spawn gate is done.
- releaseHostSpawnReservation()
- primaryExitRecovery.reset()
backendStartFailure = null
-
- const childAlive = () => hermesProcess.exitCode === null && !hermesProcess.killed
-
- const authToken = await adoptServedDashboardToken(baseUrl, token, {
- childAlive,
- rememberLog
- })
-
- backendConnectionState.assertCurrentAttempt(connectionAttempt)
-
- // Verify the WebSocket session token before declaring backend ready.
- const wsUrl = `ws://127.0.0.1:${port}/api/ws?token=${encodeURIComponent(authToken)}`
-
- // Same policy as the pool path: our own child may still be cold-starting (#96177).
- const wsProbe = await probeGatewayWebSocket(wsUrl, {
- WebSocketImpl: globalThis.WebSocket,
- ...spawnedBackendProbeOptions(childAlive)
- })
-
- backendConnectionState.assertCurrentAttempt(connectionAttempt)
-
- if (!wsProbe.ok) {
- throw new Error(
- `Local Hermes backend is HTTP-reachable but the WebSocket (/api/ws) rejected the session token: ${wsProbe.reason}`
- )
- }
-
- updateBootProgress({
- phase: 'backend.ready',
- message: 'Hermes backend is ready. Finalizing desktop startup',
- progress: 94,
- running: true,
- error: null
- })
-
- // A successful boot (including a soft restart that the repair-guard
- // chose over a hard reinstall, see #74874) means any in-flight repair
- // attempt counter has been honoured — reset it so the next genuine
- // failure starts fresh from attempt 1 instead of inheriting the
- // accumulated count of the resolved episode.
+ rememberLog('[backend] Hermes gateway is ready')
+ updateBootProgress({ phase: 'backend.ready', message: 'Hermes gateway is ready', progress: 94, running: true, error: null })
bootstrapRepairAttempt = 0
- return {
- baseUrl,
- mode: 'local',
- source: 'local',
- authMode: 'token',
- token: authToken,
- profile,
- wsUrl,
- logs: hermesLog.slice(-80),
- ...getWindowState()
- }
+ // The primary descriptor names its own profile: a profile-less descriptor
+ // reads as "default" downstream and breaks per-source profile memory when
+ // the primary actually booted as another profile (#825324fd).
+ return { ...connection, profile: primaryProfile, logs: hermesLog.slice(-80), ...getWindowState() }
})().catch(async error => {
- releaseHostSpawnReservation()
-
if (!backendConnectionState.clearPromiseForAttempt(connectionAttempt)) {
throw error
}
diff --cc apps/desktop/package.json
index b52e2a84725,e9ad4d305a7..81f94de14f8
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@@ -192,8 -192,7 +192,8 @@@
"tsx": "4.23.1",
"typescript": "6.0.3",
"vite": "8.2.0",
- "vitest": "4.1.10",
+ "vitest": "4.1.11",
- "wait-on": "9.0.10"
+ "wait-on": "9.0.10",
+ "ws": "8.21.1"
}
}
diff --cc apps/desktop/src/app/chat/composer/controls.test.tsx
index 04e88abfa62,49724a29dab..0b74c3c52a0
--- a/apps/desktop/src/app/chat/composer/controls.test.tsx
+++ b/apps/desktop/src/app/chat/composer/controls.test.tsx
@@@ -153,8 -153,22 +153,22 @@@ describe('ComposerControls shortcut too
await expectShortcutTooltip('Stop', '↵')
})
+ it('answers a waiting card with Send when the draft has text, and offers no Queue', () => {
+ renderControls({ busy: true, busyAction: 'queue', cardWaiting: true, hasComposerPayload: true })
+
+ expect(screen.getByLabelText('Send')).toBeTruthy()
+ expect(screen.queryByLabelText('Stop')).toBeNull()
+ expect(screen.queryByLabelText('Queue message')).toBeNull()
+ })
+
+ it('keeps Stop enabled while a card waits and the draft is empty', () => {
+ renderControls({ busy: true, busyAction: 'stop', canSubmit: true, cardWaiting: true, hasComposerPayload: false })
+
+ expect(screen.getByLabelText('Stop').hasAttribute('disabled')).toBe(false)
+ })
+
it('shows Ctrl+Enter for Queue as the secondary mid-turn action', async () => {
- renderControls({ busy: true, busyAction: 'queue' })
+ renderControls({ busy: true, busyAction: 'interrupt' })
await expectShortcutTooltip('Queue message', 'Ctrl+↵')
})
diff --cc apps/desktop/src/app/chat/composer/controls.tsx
index 9495475ccc3,851eb2ee35b..609cf51a443
--- a/apps/desktop/src/app/chat/composer/controls.tsx
+++ b/apps/desktop/src/app/chat/composer/controls.tsx
@@@ -56,8 -56,10 +57,10 @@@ export function ComposerControls(
}: {
autoSpeak: boolean
busy: boolean
- busyAction: 'steer' | 'queue' | 'stop'
+ busyAction: 'interrupt' | 'steer' | 'queue' | 'stop'
canSubmit: boolean
+ /** A card parked on the session takes typed text as its answer, so queueing that text would leave the card waiting. */
+ cardWaiting?: boolean
compactModelPill?: boolean
conversation: ConversationProps
disabled: boolean
@@@ -81,13 -82,10 +84,14 @@@
}
const showVoicePrimary = !busy && !hasComposerPayload
- // Steer is just send: a payload keeps the Send affordance mid-turn. Stop
- // only when the composer is empty and a turn is running.
+ // Steer is just send: a payload keeps the Send affordance mid-turn (it answers
+ // a waiting card). Stop only when the composer is empty and a turn is running.
const showStop = busy && !hasComposerPayload
- const showQueueButton = busy && busyAction !== 'stop' && busyAction !== 'queue' && hasComposerPayload
- const showQueueButton = busy && busyAction !== 'stop' && hasComposerPayload && !cardWaiting
++ const showQueueButton =
++ busy && busyAction !== 'stop' && busyAction !== 'queue' && hasComposerPayload && !cardWaiting
+
+ const sendLabel = composerSendLabel(busy, busyAction, c)
+
// The HUD is a Spotlight bar a few hundred pixels wide, so the four separate
// voice toggles fold into one menu there and leave the row to the input. A
// narrow tile hits the same wall from the other direction and folds for the
diff --cc apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
index b3e0cb8484e,25c56d6074c..d929e041de6
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx
@@@ -10,9 -10,11 +10,11 @@@ import
type ComposerAttachment,
setComposerTerminalSelection
} from '@/store/composer'
-import { clearQueuedPrompts, getQueuedPrompts } from '@/store/composer-queue'
+import { $queuedPromptsBySession, clearQueuedPrompts, getQueuedPrompts } from '@/store/composer-queue'
import { $connectionRequests, type ConnectionRequest } from '@/store/connection-request'
import { $gateway } from '@/store/gateway'
+ import { $onboardingPhase } from '@/store/onboarding-phase'
+ import { $onboardingSession } from '@/store/onboarding-session'
import {
clearAllPrompts,
hasBlockingPromptRequest,
@@@ -21,7 -23,7 +23,8 @@@
setSudoRequest
} from '@/store/prompts'
import { hasOpenServerRequest, rememberServerRequest, resetServerRequestsForTests } from '@/store/server-requests'
+import { $connection } from '@/store/session'
+ import { $setupBeatRequests, parkSetupBeat } from '@/store/setup-beat'
import { type ComposerTarget, requestComposerSubmit } from '../focus'
import { ComposerScopeProvider, ComposerSurfaceProvider, MAIN_COMPOSER_SCOPE } from '../scope'
diff --cc apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
index cabee7f3139,73ad18fa960..c9ad1304796
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts
@@@ -14,12 -13,11 +14,12 @@@ import
freezeComposerTransportPayload,
isFreshDraftScope
} from '@/store/composer'
+import { type ComposerDraftRetry, draftRetry } from '@/store/composer-draft-retry'
import { resetBrowseState } from '@/store/composer-input-history'
-import { enqueueQueuedPrompt, type QueuedPromptEntry } from '@/store/composer-queue'
+import { enqueueQueuedPrompt, type QueuedPromptEntry, serverOwnsComposerQueue } from '@/store/composer-queue'
import { hasConnectionRequest, skipConnectionRequest } from '@/store/connection-request'
import { notify } from '@/store/notifications'
- import { answerParkedCard } from '@/store/parked-card-answers'
+ import { answerParkedCard, skipParkedCards, yieldParkedCardsToMessage } from '@/store/parked-card-answers'
import { hasBlockingPromptRequest } from '@/store/prompts'
import { cloneAttachments, type QueueEditState } from '../composer-utils'
diff --cc apps/desktop/src/app/chat/composer/index.tsx
index 6b94cecc843,6cb55463b2a..6ac5f1a8722
--- a/apps/desktop/src/app/chat/composer/index.tsx
+++ b/apps/desktop/src/app/chat/composer/index.tsx
@@@ -12,12 -12,11 +12,12 @@@ import
} from 'react'
import { useTourMarker } from '@/app/chat/tour-marker'
+import type { GatewayRequester } from '@/app/contrib/types'
import { useHudComposerDrag } from '@/app/hud/composer-drag'
+import { useBusyInputMode } from '@/app/session/hooks/use-busy-input-mode'
import { composerFloatingStrip, composerInputBacking } from '@/components/chat/composer-dock'
- import { useSetupChatView } from '@/components/onboarding-chat/assembly'
- import { OnboardingSkip } from '@/components/onboarding-chat/skip'
+ import { useSetupChatView } from '@/components/onboarding/first-run/assembly'
+ import { OnboardingSkip } from '@/components/onboarding/skip-setup'
-import { Button } from '@/components/ui/button'
import { Slot as ContribSlot } from '@/contrib/react/slot'
import { useI18n } from '@/i18n'
import { chatMessageText } from '@/lib/chat-messages'
@@@ -400,17 -382,22 +400,18 @@@ export function ChatBar(
})
const hasComposerPayload = hasText || attachments.length > 0
- const { canSubmit, cardWaiting } = useCardWaitingSubmit(sessionId ?? null, busy, hasComposerPayload)
-
- // Steer only makes sense mid-turn, text-only (the gateway can't carry images
- // into a tool result) and never for a slash command (those execute inline).
- // A blocking prompt (approval/sudo/secret) also rules it out: the tool batch
- // is parked on the user, so a steer can't reach the model — text queues.
- // Compaction does not: the gateway holds the correction until it finishes.
- const canSteer = busy && !blockingPrompt && !!onSteer && attachments.length === 0 && isSteerableText
-
- // While busy: text redirects the live turn (Cursor-style stop-and-correct),
- // attachments queue for the next turn, an empty composer stops.
- const busyAction: 'steer' | 'queue' | 'stop' = canSteer
- ? 'steer'
- : compacting || hasComposerPayload
- ? 'queue'
- : 'stop'
++ const { cardWaiting } = useCardWaitingSubmit(sessionId ?? null, busy, hasComposerPayload)
+
+ const { busyAction, canSteer, canSubmit } = deriveBusySubmitState({
+ attachmentCount: attachments.length,
+ blockingPrompt,
+ busy,
+ busyInputMode,
+ compacting,
+ hasComposerPayload,
+ hasSteerHandler: !!onSteer,
+ isSteerableText
+ })
// The submit engine — the orchestration seam where draft + queue meet. Owns
// the submit decision tree, the send-with-restore primitive, and steer.
@@@ -1299,16 -1302,7 +1301,16 @@@
<div className={cn(composerFloatingStrip, 'px-[5px] pb-1.5 empty:hidden')}>
<ActionBadges sessionId={statusSessionId} />
<SuggestionPills sessionId={statusSessionId} />
+ <PreparedImageRecovery
+ occupied={hasText || attachments.length > 0 || busy || disabled}
+ onRestore={(text, restored, id) => {
+ loadIntoComposer(text, restored)
+ rememberDraftRetry(activeQueueSessionKey, draftRetry(id, text, restored))
+ }}
+ request={requestBusyConfig}
+ sessionKey={activeQueueSessionKey}
+ />
- <OnboardingSkip />
+ <OnboardingSkip sessionId={statusSessionId} />
</div>
{/* Session-scoped status stack (todos, subagents, background tasks,
queue). An in-flow dock child: the dock is bottom-anchored, so it
diff --cc apps/desktop/src/app/contrib/wiring.tsx
index c4304412b60,4bb64229e28..954975fa63a
--- a/apps/desktop/src/app/contrib/wiring.tsx
+++ b/apps/desktop/src/app/contrib/wiring.tsx
@@@ -52,6 -53,14 +53,13 @@@ import { reconnectGateway } from '@/sto
import { $interfaceMode, shownInMode } from '@/store/interface-mode'
import { $pinnedSessionIds, pinSession, restoreWorktree, unpinSession } from '@/store/layout'
import { notifyError } from '@/store/notifications'
+ import { markOnboardingDecided } from '@/store/onboarding-presence'
+ import {
+ $onboardingChatOpener,
+ decideOnboarding,
+ type OnboardingRequest,
+ type OnboardingResume
+ } from '@/store/onboarding-run'
-import { $poolLimitsSettingsRequest } from '@/store/pool-limits'
import { $previewTarget } from '@/store/preview'
import {
$activeGatewayProfile,
@@@ -211,8 -220,31 +218,31 @@@ function useRouteRequestNavigation(navi
}, [navigate, routeRequest])
}
+ // The main window asks the backend whether first-run onboarding is due and opens it with main's
+ // intro around it; every other window never runs it, so its first-run surfaces are free at once.
+ // Settings' Run onboarding again opens its chat through the same opener.
+ function useFirstRunOnboarding(request: OnboardingRequest, open: OnboardingResume, gatewayOpen: boolean): void {
+ useEffect(() => {
+ if (!isMainWindow()) {
+ markOnboardingDecided()
+ } else if (gatewayOpen) {
+ void decideOnboarding(request, open, { intro: firstRunIntro() })
+ }
+ }, [gatewayOpen, open, request])
+
+ useEffect(() => {
+ if (!isMainWindow()) {
+ return
+ }
+
+ $onboardingChatOpener.set(open)
+
+ return () => $onboardingChatOpener.set(null)
+ }, [open])
+ }
+
-// Recovery actions raised by toast buttons (Restart Hermes, Open Billing, pool
-// caps, cron review) fire from stores with no router context. Each counter is
+// Recovery actions raised by toast buttons (Restart Hermes, Open Billing, cron
+// review) fire from stores with no router context. Each counter is
// consumed here: the ref skips the initial mount value, and only a fresh
// request navigates or recycles the backend.
function useRecoveryRequestToasts(): void {
diff --cc apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts
index 00a87db4008,a6f242573cc..9f453d6b298
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts
@@@ -250,5 -193,15 +252,13 @@@ function cancelParkedCredentialRequest(
clearVaultSaveLoginRequest(sessionId, id)
} else if ($vaultUnlockRequests.get()[key]?.requestId === id) {
clearVaultUnlockRequest(sessionId, id)
+ } else {
+ clearParkedCard(ctx, id)
+ }
-
- return true
+ }
+
+ function clearParkedCard({ deps, sessionId }: GatewayEventContext, requestId: string) {
+ if (sessionId && (clearThemePick(requestId, sessionId) || clearSetupBeat(requestId, sessionId))) {
+ deps.updateSessionState(sessionId, state => ({ ...state, needsInput: false }))
}
}
diff --cc apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts
index 1ec2b66ff7e,a297b0b6005..f00704d72b5
--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts
+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/lifecycle.ts
@@@ -2,9 -2,9 +2,10 @@@ import type { GatewayEvent } from '@her
import type { HermesSkin } from '@hermes/shared/skin'
import { invalidateContextBreakdown } from '@/app/shell/hooks/use-context-breakdown'
+import { eventSourceMatchesOwner, gatewayEventSource } from '@/lib/replay-gap-owner'
import { clearClarifyRequest } from '@/store/clarify'
import {
+ noteGatewayReady,
notifyCronChanged,
notifyPairingChanged,
notifyPetChanged,
diff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
index cc73e017635,e6d9296b1a5..036c096a555
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts
@@@ -211,69 -206,7 +211,63 @@@ export function useSlashCommand(deps: S
const compressInFlightRef = useRef(new Set<string>())
return useCallback(
- async (rawCommand: string, options?: { sessionId?: string; recordInput?: boolean; typed?: boolean }) => {
+ async (
+ rawCommand: string,
- options?: SubmitTextOptions & { hidden?: boolean; recordInput?: boolean; typed?: boolean }
++ options?: SubmitTextOptions & { recordInput?: boolean; typed?: boolean }
+ ) => {
+ const initialRuntimeId = options?.sessionId ?? activeSessionIdRef.current
+ const initialSelectedId = selectedStoredSessionIdRef.current
+ const initialRoutedId = getRoutedStoredSessionId()
+
+ let submitted = true
+
+ const initialStoredId =
+ options?.storedSessionId ??
+ (options?.sessionId
+ ? ($sessionStates.get()[options.sessionId]?.storedSessionId ?? null)
+ : (initialRoutedId ?? initialSelectedId))
+
+ const destination =
+ options?.destination ?? captureSubmissionDestination(initialStoredId ?? initialRuntimeId, ambientRequestGateway)
+
+ const requestGateway = destination.requestGateway
+
- // `hidden` (the first-run `/initiate-setup`) types the saved user row hidden: no bubble, live
- // or after a reload. It rides retryOptions so a prepared-submission retry stays hidden too.
- const retryOptions = {
- ...options,
- retryText: rawCommand,
- ...(options?.hidden && { displayKind: 'hidden' as const })
- }
++ const retryOptions = { ...options, retryText: rawCommand }
+
+ try {
+ // An explicit retry of this exact invocation reuses its retained expansion; the same
+ // command typed again is a new invocation.
+ const prepared = options?.submission_id
+ ? (await adoptPreparedSubmission(
+ preparedSubmissionKey(
+ resolveComposerSessionKey(initialStoredId ?? initialRuntimeId, $sessions.get()),
+ destination,
+ rawCommand,
+ options?.attachments ?? $composerAttachments.get(),
+ retryOptions
+ ),
+ options.submission_id
+ ))?.entry
+ : undefined
+
+ if (prepared) {
+ return await submitPromptText(prepared.text, {
+ ...retryOptions,
+ sessionId: initialRuntimeId ?? undefined,
+ storedSessionId: initialStoredId,
+ displayText: prepared.displayText,
+ submission_id: prepared.id,
+ destination
+ })
+ }
+ } catch (err) {
+ notifyError(err, copy.promptFailed)
+
+ return false
+ }
+
+ const submissionId = options?.submission_id ?? crypto.randomUUID()
+
// Resolve the session this command targets through the SHARED ladder that
// submit.ts uses. A slash command runs backend commands against a runtime
// session, and per-session state (`/goal`, `/usage`, `/status`) is keyed by
@@@ -511,15 -404,7 +505,14 @@@
// its kickoff as a user message into whatever conversation was on
// screen. Every other target the dispatcher serves (tile, background
// queue drain, a session created by this very call) had the same leak.
- // retryOptions carries main's `hidden` → displayKind 'hidden' for the first-run kickoff.
- await submitPromptText(message, { sessionId, storedSessionId, displayText })
+ submitted = await submitPromptText(message, {
+ ...retryOptions,
+ sessionId,
+ storedSessionId,
+ displayText,
+ submission_id: submissionId,
+ destination
+ })
}
try {
diff --cc apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
index 9bb084f5bb4,668309eb771..a8121f9a742
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts
@@@ -880,28 -770,12 +880,28 @@@ export function useSubmitPrompt(deps: S
return abortForSessionSwitch(null)
}
- seedOptimistic(sessionId)
+ seedOptimistic(resumedSessionId)
+
+ return resumedSessionId
}
- if (!sessionId) {
+ if (!sessionId && targetStoredSessionId) {
+ const resumedRuntimeId = await resumeTargetStoredSession(targetStoredSessionId)
+
+ if (resumedRuntimeId === false) {
+ return false
+ }
+
+ sessionId = resumedRuntimeId
+ }
+
+ // Genuine new-chat draft: create the backend session it submits into.
+ // Resolves to the created runtime id, or false when the submit must stop.
+ const createSessionForSubmit = async (): Promise<false | string> => {
+ let createdId: null | string
+
try {
- createdId = await createBackendSessionForSend(bubbleText, undefined, {
- sessionId = await createBackendSessionForSend(bubbleText, {
++ createdId = await createBackendSessionForSend(bubbleText, {
onComposerScopeAssigned: options?.onComposerScopeAssigned
})
} catch (err) {
diff --cc apps/desktop/src/app/session/hooks/use-session-actions/index.ts
index 016e3d29b65,3052e48c684..883c034b05e
--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
@@@ -153,9 -161,8 +153,9 @@@ import
} from '../session-context-drift'
import { singleFlightSessionResume } from '../use-prompt-actions/single-flight-resume'
+import { branchThroughRowId } from './branch-boundary'
import { branchCreateKey } from './branch-create-key'
- import { sessionCreateOverrideParams, type SessionCreateOverrides, type SessionSeedMessage } from './create-overrides'
+ import type { SessionCreateOverrides } from './create-overrides'
import { markSessionCreatedThisRun, sessionCreatedThisRun } from './created-this-run'
import { captureDisplayHydration } from './display-hydration'
import { reconcilePersistedLiveTurn } from './persisted-live-turn'
@@@ -650,19 -648,9 +650,10 @@@ export function useSessionActions(
)
const createBackendSessionForSend = useCallback(
- async (
- preview: string | null = null,
- seedMessages?: SessionSeedMessage[],
- // Create the session titled or at a pinned reasoning effort (guided
- // onboarding mints its welcome chat this way). The owning profile is NOT
- // an override — point $newChatProfile at it first (selectProfile-style)
- // so the create lands on that profile's own backend and every later
- // ambient RPC follows.
- createOverrides?: SessionCreateOverrides
- ): Promise<string | null> => {
+ async (preview: string | null = null, createOverrides?: SessionCreateOverrides): Promise<string | null> => {
const startingStoredSessionId = selectedStoredSessionIdRef.current
const startingRouteToken = getRouteToken()
+ const createIntent = (createIntentRef.current ??= crypto.randomUUID())
creatingSessionRef.current = true
@@@ -693,11 -681,7 +684,10 @@@
const capturedProfile = $newChatProfile.get() || normalizeProfileKey($activeGatewayProfile.get())
const legacyProfileIntent = isLegacyNewChatProfile(capturedProfile)
- const params = await desktopSessionCreateParams(cwd, capturedRoute, capturedProfile, legacyProfileIntent)
+ const params = {
+ ...(await desktopSessionCreateParams(cwd, capturedRoute, capturedProfile, legacyProfileIntent)),
- ...sessionCreateOverrideParams(createOverrides, seedMessages),
+ request_id: createIntent
+ }
// Lease the owner socket for the whole create → owner-publication
// sequence (#93602 primitive). The per-request lease inside
diff --cc apps/desktop/src/app/settings/config-settings.tsx
index 658ceffba86,10b6b3318e2..a112b3eea36
--- a/apps/desktop/src/app/settings/config-settings.tsx
+++ b/apps/desktop/src/app/settings/config-settings.tsx
@@@ -51,6 -50,8 +50,7 @@@ import
import { MemoryConnect } from './memory/connect'
import { ProviderConfigPanel } from './memory/provider-config-panel'
import { ModelSettings, ModelSettingsSkeleton } from './model-settings'
+ import { OnboardingSettings } from './onboarding-settings'
-import { PoolLimitsSetting } from './pool-limits-setting'
import { EmptyState, ListRow, SettingsContent, SettingsSkeleton, ToggleRow } from './primitives'
import { SettingsProfileScope } from './profile-scope'
import { QuickEntrySettings } from './quick-entry-settings'
@@@ -483,8 -484,9 +483,8 @@@ function ConfigSettingsInner(
label={c.alwaysExternalLinksTitle}
onChange={setAlwaysExternalLinks}
/>
- <PoolLimitsSetting />
<QuickEntrySettings />
- <DeveloperSettings />
+ <OnboardingSettings />
</>
)}
{/* Device-local attach/preview byte cap (main-process IPC guard). Chat is
diff --cc apps/desktop/src/i18n/ja.ts
index aaa8753a225,12a58eb3ee3..0fc16310a06
--- a/apps/desktop/src/i18n/ja.ts
+++ b/apps/desktop/src/i18n/ja.ts
@@@ -3,8 -3,9 +3,10 @@@ import { defineFieldCopy } from '@/app/
import { defineLocale, type TranslationOverrides } from './define-locale'
import { introJa } from './intro-ja'
import { jaAuxTasks } from './ja_aux_tasks'
+import { jaBoot } from './ja_boot'
+ import { jaClarify } from './ja_clarify'
import { jaConnectors } from './ja_connectors'
+ import { jaFirstRun } from './ja_first_run'
import { jaLocalModels } from './ja_local_models'
import { jaModelMenu } from './ja_model_menu'
import { jaNotices } from './ja_notices'
diff --cc apps/desktop/src/i18n/ru.ts
index 271fb94162b,f2a9345b5a0..4eff2b5cc1e
--- a/apps/desktop/src/i18n/ru.ts
+++ b/apps/desktop/src/i18n/ru.ts
@@@ -2,8 -2,9 +2,10 @@@ import { defineFieldCopy } from '@/app/
import { defineLocale, type TranslationOverrides } from './define-locale'
import { ruAuxTasks } from './ru_aux_tasks'
+import { ruBoot } from './ru_boot'
+ import { ruClarify } from './ru_clarify'
import { ruConnectors } from './ru_connectors'
+ import { ruFirstRun } from './ru_first_run'
import { ruModelMenu } from './ru_model_menu'
import { ruNotices } from './ru_notices'
import { ruOnboarding } from './ru_onboarding'
diff --cc apps/desktop/src/plugins/hermes-bots/i18n-messages.ts
index 58bce98b853,00000000000..ba04a09039c
mode 100644,000000..100644
--- a/apps/desktop/src/plugins/hermes-bots/i18n-messages.ts
+++ b/apps/desktop/src/plugins/hermes-bots/i18n-messages.ts
@@@ -1,455 -1,0 +1,457 @@@
+/**
+ * Message SHAPE for Bot Mode's plugin-scoped i18n bundles (see `./i18n.ts`).
+ */
+
+import { type CanonicalGroupMessages } from './canonical-group-locales'
+
+export type BotsMessages = {
+ canonical: { [K in keyof CanonicalGroupMessages]: string }
+ /** Left rail: the bot + group-chat roster. */
+ editor: {
+ fullConfigHint: string
+ liveCapabilities: string
+ editSoul: string
+ remoteCapabilitiesHint: string
+ skillsEnabled: (enabled: number, total: number) => string
+ toolsetsEnabled: (enabled: number, total: number) => string
+ mcpServers: string
+ providerCustom: string
+ modelCustom: string
+ backToDropdowns: string
+ inheritLaunch: string
+ enterManually: string
+ gatewayDefault: string
+ modelNameExample: string
+ modelSwitchFailed: string
+ newDescription: string
+ name: string
+ title: string
+ description: string
+ createOn: string
+ general: string
+ capabilities: string
+ skills: string
+ tools: string
+ cloneFrom: string
+ freshProfile: string
+ inheritedModel: string
+ soul: string
+ shareKeys: string
+ shareKeysOn: (target: string) => string
+ shareKeysHint: string
+ needsModel: string
+ configureModel: string
+ createEmpty: string
+ nameTakenHint: string
+ nameFirstHint: string
+ newerDesktop: string
+ newerGateway: string
+ emptySkillsHint: string
+ defaultToolsHint: string
+ catalog: string
+ catalogInstalled: string
+ mcpHint: string
+ creating: string
+ createBot: string
+ auto: string
+ autoHint: string
+ unlock: string
+ lockFace: string
+ lockedHint: string
+ unlockedHint: string
+ noImageModel: string
+ checkingImage: string
+ chooseImage: string
+ editDescription: (name: string, profile: string) => string
+ nameTaken: (name: string) => string
+ nameTakenOn: (name: string, target: string) => string
+ currentConnection: (name: string) => string
+ remoteHint: (target: string) => string
+ cloneFromOn: (target: string) => string
+ catalogHint: (source: string) => string
+ sectionsFailed: (sections: string) => string
+ updated: (name: string) => string
+ created: (name: string) => string
+ createdOn: (name: string, target: string) => string
+ }
+ roster: {
+ search: string
+ searchPlaceholder: string
+ newBotOrGroup: string
+ groupChats: string
+ emptyTitle: string
+ emptyDesc: string
+ noMatchQuery: (query: string) => string
+ noMatchQueryOn: (query: string, gateway: string) => string
+ noMatchFiltersOn: (gateway: string) => string
+ noMatchFilters: string
+ clearFilters: string
+ allHidden: string
+ allHiddenDesc: string
+ showHidden: string
+ noHiddenMatch: string
+ hiddenFromRoster: string
+ pinned: string
+ needsAttention: string
+ needsInput: string
+ /** The kind filter's three options, in menu order. */
+ botsAndGroups: string
+ botsOnly: string
+ groupsOnly: string
+ /** The activity filter's four options, in menu order. */
+ anyActivity: string
+ activeNow: string
+ recentlyActive: string
+ older: string
+ /** How a row's owning gateway is doing — see `botSourceStatus`. */
+ gatewayRemoved: string
+ onDemand: string
+ ready: string
+ statusUnknown: string
+ unavailable: string
+ retryNow: string
+ rosterUnavailable: (reason: string) => string
+ waitingForGateway: string
+ }
+ /** User-made roster sections (folders the user files bots into). */
+ sections: {
+ newSection: string
+ newTitle: string
+ renameTitle: string
+ nameLabel: string
+ namePlaceholder: string
+ create: string
+ rename: string
+ moveUp: string
+ moveDown: string
+ unassigned: string
+ options: (name: string) => string
+ headingTip: string
+ emptyHint: string
+ moveTo: string
+ newSectionEllipsis: string
+ removeFromSection: string
+ deleted: (name: string, count: number) => string
+ undo: string
+ }
+ /** Creating, editing and removing a bot. */
+ bot: {
+ newTitle: string
+ editTitle: string
+ editMenu: string
+ helpPromptPlaceholder: string
+ descriptionHint: string
+ newChatWith: string
+ /** Re-opens the forever-chat on purpose. A plain row click only returns to
+ * the tabs already open, so a closed Bot Chat needs an explicit ask. */
+ openBotChat: string
+ /** Screen-reader label for the row spinner while a cold bot chat opens. */
+ openingChat: string
+ /** Row context menu: pin/hide toggles, their toasts, and the groups entry. */
+ pinToTop: string
+ unpin: string
+ pinnedToast: (name: string) => string
+ unpinnedToast: (name: string) => string
+ hide: string
+ unhide: string
+ hiddenToast: (name: string) => string
+ unhiddenToast: (name: string) => string
+ groupsMenu: (groups: string) => string
+ manageGroups: string
+ metadataLoadFailed: string
+ loadFailed: string
+ groupsLoadFailed: string
+ thisDevice: string
+ /** Roster badge tooltips per attention class; `attentionFallback` when the class is unknown. */
+ attentionFallback: string
+ attentionProviderAuth: string
+ attentionQuota: string
+ attentionMissingConfig: string
+ attentionBlocked: string
+ duplicate: string
+ duplicateFailed: string
+ deleteTitle: string
+ removeFromAllGroups: string
+ createFirstHint: string
+ createFailed: string
+ advanced: string
+ advancedHint: string
+ advancedFailed: string
+ openAnotherChatUnsupported: string
+ remoteConnectionsUnsupported: string
+ /** Bot-open failure toasts (canonical-chat.ts notifyBotOpenFailure). The
+ * raw RPC/connection error travels in the toast `detail`, never here. */
+ openNeedsUpdateTitle: string
+ openNeedsUpdateMessage: (connectionLabel: string) => string
+ openUnreachableTitle: string
+ openUnreachableMessage: string
+ openChatFailedTitle: (botName: string) => string
+ openChatFailedMessage: string
+ openGateways: string
+ /** Stands under the bot's name in a chat it has not spoken in yet. */
+ chatEmpty: string
+ /** First line of a brand-new bot's forever-chat — see `kickoffText`. */
+ kickoff: string
+ }
+ /** Avatar picker: shapes, blobs, pets, uploads, generation. */
+ avatar: {
+ classicShapes: string
+ blobFromName: string
+ unlockFollowsName: string
+ randomize: string
+ /** The picker's four tabs, in order. */
+ tabBot: string
+ tabGenerate: string
+ upload: string
+ tabPet: string
+ removeImage: string
+ removeBackToShape: string
+ describePlaceholder: string
+ describeHint: string
+ matchTheName: string
+ pickPet: string
+ petLoadFailed: string
+ imageTooLarge: string
+ generationFailed: string
+ savedLocally: string
+ savedLocallyDescriptionFailed: string
+ generate: string
+ generating: string
+ }
+ /** Group chats: the room, its composer, threads and activity feed. */
+ group: {
+ newTitle: string
+ manageDesc: string
+ manageTitle: string
+ settingsTitle: string
+ settingsDesc: string
+ nameLabel: string
+ holdDetection: string
+ holdDetectionHint: string
+ compressHistory: string
+ compressHistoryHint: (member: string) => string
+ compressing: (member: string) => string
+ compressDone: (member: string, compressed: number, detail: string) => string
+ compressNothing: (member: string) => string
+ compressFailed: (member: string, error: string) => string
+ searchToAdd: string
+ searchToAddPlaceholder: string
+ removeFromSelection: string
+ disbandTitle: string
+ deleteTitle: string
+ deleteAction: string
+ composerPlaceholder: string
+ slashCommandsUnsupported: string
+ attachHint: string
+ newThread: string
+ reply: string
+ replyInThread: string
+ replyInThreadPlaceholder: string
+ openThread: string
+ collapseThread: string
+ collapseThreadLabel: string
+ activity: string
+ noActivityYet: string
+ showActivity: string
+ hideActivity: string
+ stop: string
+ stopHint: string
+ allHeldStatus: (count: number) => string
+ heldMembersStatus: (members: string) => string
+ holdReleaseHint: string
+ needsYourInput: string
+ noMembersToSend: (group: string) => string
+ pictureGenerationFailed: string
+ nameTaken: (name: string) => string
+ memberCount: (count: number) => string
+ /** The reader's own lines in a room: the transcript speaker and the roster preview. */
+ you: string
+ /** How many of a room's members are reachable right now. */
+ availableCount: (available: number, total: number) => string
+ settingsHint: (group: string) => string
+ settingsLabel: (group: string) => string
+ disbandHint: (group: string) => string
+ disbandLabel: (group: string) => string
+ disbandAction: string
+ disbanding: string
+ disbandDone: string
+ disbanded: (group: string) => string
+ /** Wraps the bolded group name, so the name can lead the sentence in
+ * languages that put it there — see core's cron.deleteDesc* pair. */
+ disbandDescPrefix: string
+ disbandDescSuffix: (count: number) => string
+ stopped: (group: string) => string
+ removeAttachment: string
+ threadFallback: string
+ replyCount: (replies: number) => string
+ dropToThread: string
+ dropToRoom: string
+ waitingForAnswer: string
+ memberThinking: (name: string) => string
+ roomWorking: string
+ messageRoom: (group: string) => string
+ newThreadPlaceholder: (group: string) => string
+ everyoneMeta: string
+ commandApproval: string
+ answerFailed: (handle: string, error: string) => string
+ wantsToRunCommand: (handle: string) => string
+ asks: (handle: string) => string
+ answerTo: (member: string) => string
+ }
+ /** Skills hub + MCP setup surfaces embedded in the bot editor. */
+ tools: {
+ installHint: (name: string) => string
+ installed: (name: string) => string
+ installFailed: (name: string) => string
+ searchHint: string
+ resizeHint: string
+ addServerFailed: string
+ noTarget: string
+ setKeyFailed: (name: string) => string
+ configured: (name: string) => string
+ authenticated: (name: string) => string
+ testFailed: string
+ completeSignIn: string
+ needsSetup: (name: string) => string
+ setUpDone: string
+ saveTest: string
+ authorizing: string
+ working: string
+ setupFailed: string
+ signIn: string
+ setUp: string
+ skillsHub: string
+ filterSkills: string
+ searchHub: string
+ noMcpServers: string
+ }
+
+ /** Bot Screen: the bot's headless desktop on the gateway host, live in a pane. */
+ screen: {
+ title: string
+ menu: string
+ unsupportedTitle: string
+ unsupportedBody: string
+ notInstalledTitle: string
+ notInstalledBody: string
+ installHint: string
+ install: string
+ installing: string
+ installCancelled: string
+ installFailed: string
+ noPackageManager: string
+ portalTitle: string
+ portalOpen: string
+ heroStopped: string
+ heroNotInstalled: string
+ heroConnecting: string
+ heroStale: string
+ heroSuppressed: string
+ heroOpenLive: string
+ heroInstall: string
+ heroStart: string
+ portalWatching: string
+ portalYouControl: string
+ portalOtherControls: string
+ portalStopped: string
+ portalNotInstalled: string
+ portalUnsupported: string
+ portalUnavailable: string
+ /** Managed runtimes (Hermes Cloud): updates are the platform's job, not the user's. */
+ portalUnavailableManaged: string
++ managedNotIncludedTitle: string
++ managedNotIncludedBody: string
+ unavailableTitle: string
+ autoOpenMenu: string
+ autoOpenOnToast: (name: string) => string
+ autoOpenOffToast: (name: string) => string
+ stoppedTitle: string
+ stoppedBody: string
+ placementSandbox: (backend: string) => string
+ imageSwitchTitle: string
+ imageSwitchBody: (current: string, target: string) => string
+ imageSwitchApprove: string
+ imageSwitchKeep: string
+ start: string
+ attaching: string
+ streamLost: string
+ reconnect: string
+ takeOver: string
+ handBack: string
+ handBackForce: string
+ handBackForceHint: string
+ openNeedsUpdate: string
+ youControl: string
+ otherControls: string
+ agentControls: string
+ controlTaken: string
+ }
+
+ /** Bot-scoped scheduled jobs. Generic scheduling chrome (weekday names,
+ * Daily/Hourly, the job verbs) resolves against core's `cron` section. */
+ cron: {
+ untitled: string
+ nameNul: string
+ instructionNul: string
+ minutesFromNow: string
+ hoursFromNow: string
+ daysFromNow: string
+ stopAfter: string
+ runsHint: string
+ detailDescription: string
+ status: string
+ active: string
+ paused: string
+ schedule: string
+ rawSchedule: string
+ repeat: string
+ nextRun: string
+ overdueSince: string
+ lastRun: string
+ lastResult: string
+ workdir: string
+ succeeded: string
+ failed: string
+ deliveryFailed: string
+ blockedConfig: string
+ legacyUnsafe: string
+ filterHint: string
+ needsRosterFirst: string
+ staleNotice: string
+ readFailure: string
+ createDesc: (bot: string) => string
+ instruction: string
+ whenToRun: string
+ dayOfMonth: string
+ sendResultsTo: string
+ runHistoryOnly: string
+ botChatTarget: (bot: string) => string
+ continuity: string
+ onceIn: (when: string) => string
+ everyNDays: (days: number) => string
+ everyNHours: (hours: number) => string
+ everyNMinutes: (minutes: number) => string
+ /** The frequency picker's eight options, in menu order. */
+ freqOnce: string
+ freqHourly: string
+ freqDaily: string
+ freqWeekdays: string
+ freqWeekly: string
+ freqMonthly: string
+ freqInterval: string
+ freqAdvanced: string
+ unitMinutes: string
+ unitHours: string
+ unitDays: string
+ /** One-line plain-language read-back of the picker's current state. */
+ runsOnce: (count: number, unit: string) => string
+ runsHourly: string
+ runsDaily: (time: string) => string
+ runsWeekdays: (time: string) => string
+ runsWeekly: (day: string, time: string) => string
+ runsMonthly: (day: string, time: string) => string
+ runsInterval: (count: number, unit: string) => string
+ runsRaw: string
+ timesTotal: (count: number) => string
+ }
+}
diff --cc apps/desktop/src/plugins/hermes-bots/i18n.ts
index 83e5bca6347,27d7579a3e8..786c53778c9
--- a/apps/desktop/src/plugins/hermes-bots/i18n.ts
+++ b/apps/desktop/src/plugins/hermes-bots/i18n.ts
@@@ -32,12 -32,461 +32,13 @@@
import { type PluginLocaleBundles, type PluginTranslate, usePluginI18n } from '@hermes/plugin-sdk'
import { useMemo } from 'react'
+import { CANONICAL_GROUP_LOCALES } from './canonical-group-locales'
+ import { bind, type Bound } from './i18n-bind'
+import { type BotsMessages } from './i18n-messages'
import { getPluginCtx } from './shared'
-type BotsMessages = {
- /** Left rail: the bot + group-chat roster. */
- editor: {
- fullConfigHint: string
- liveCapabilities: string
- editSoul: string
- remoteCapabilitiesHint: string
- skillsEnabled: (enabled: number, total: number) => string
- toolsetsEnabled: (enabled: number, total: number) => string
- mcpServers: string
- providerCustom: string
- modelCustom: string
- backToDropdowns: string
- inheritLaunch: string
- enterManually: string
- gatewayDefault: string
- modelNameExample: string
- modelSwitchFailed: string
- newDescription: string
- name: string
- title: string
- description: string
- createOn: string
- general: string
- capabilities: string
- skills: string
- tools: string
- cloneFrom: string
- freshProfile: string
- inheritedModel: string
- soul: string
- shareKeys: string
- shareKeysOn: (target: string) => string
- shareKeysHint: string
- needsModel: string
- configureModel: string
- createEmpty: string
- nameTakenHint: string
- nameFirstHint: string
- newerDesktop: string
- newerGateway: string
- emptySkillsHint: string
- defaultToolsHint: string
- catalog: string
- catalogInstalled: string
- mcpHint: string
- creating: string
- createBot: string
- auto: string
- autoHint: string
- unlock: string
- lockFace: string
- lockedHint: string
- unlockedHint: string
- noImageModel: string
- checkingImage: string
- chooseImage: string
- editDescription: (name: string, profile: string) => string
- nameTaken: (name: string) => string
- nameTakenOn: (name: string, target: string) => string
- currentConnection: (name: string) => string
- remoteHint: (target: string) => string
- cloneFromOn: (target: string) => string
- catalogHint: (source: string) => string
- sectionsFailed: (sections: string) => string
- updated: (name: string) => string
- created: (name: string) => string
- createdOn: (name: string, target: string) => string
- }
- roster: {
- search: string
- searchPlaceholder: string
- newBotOrGroup: string
- groupChats: string
- emptyTitle: string
- emptyDesc: string
- noMatchQuery: (query: string) => string
- noMatchQueryOn: (query: string, gateway: string) => string
- noMatchFiltersOn: (gateway: string) => string
- noMatchFilters: string
- clearFilters: string
- allHidden: string
- allHiddenDesc: string
- showHidden: string
- noHiddenMatch: string
- hiddenFromRoster: string
- pinned: string
- needsAttention: string
- needsInput: string
- /** The kind filter's three options, in menu order. */
- botsAndGroups: string
- botsOnly: string
- groupsOnly: string
- /** The activity filter's four options, in menu order. */
- anyActivity: string
- activeNow: string
- recentlyActive: string
- older: string
- /** How a row's owning gateway is doing — see `botSourceStatus`. */
- gatewayRemoved: string
- onDemand: string
- ready: string
- statusUnknown: string
- unavailable: string
- retryNow: string
- rosterUnavailable: (reason: string) => string
- waitingForGateway: string
- }
- /** User-made roster sections (folders the user files bots into). */
- sections: {
- newSection: string
- newTitle: string
- renameTitle: string
- nameLabel: string
- namePlaceholder: string
- create: string
- rename: string
- moveUp: string
- moveDown: string
- unassigned: string
- options: (name: string) => string
- headingTip: string
- emptyHint: string
- moveTo: string
- newSectionEllipsis: string
- removeFromSection: string
- deleted: (name: string, count: number) => string
- undo: string
- }
- /** Creating, editing and removing a bot. */
- bot: {
- newTitle: string
- editTitle: string
- editMenu: string
- helpPromptPlaceholder: string
- descriptionHint: string
- newChatWith: string
- /** Re-opens the forever-chat on purpose. A plain row click only returns to
- * the tabs already open, so a closed Bot Chat needs an explicit ask. */
- openBotChat: string
- /** Screen-reader label for the row spinner while a cold bot chat opens. */
- openingChat: string
- /** Row context menu: pin/hide toggles, their toasts, and the groups entry. */
- pinToTop: string
- unpin: string
- pinnedToast: (name: string) => string
- unpinnedToast: (name: string) => string
- hide: string
- unhide: string
- hiddenToast: (name: string) => string
- unhiddenToast: (name: string) => string
- groupsMenu: (groups: string) => string
- manageGroups: string
- metadataLoadFailed: string
- loadFailed: string
- groupsLoadFailed: string
- thisDevice: string
- /** Roster badge tooltips per attention class; `attentionFallback` when the class is unknown. */
- attentionFallback: string
- attentionProviderAuth: string
- attentionQuota: string
- attentionMissingConfig: string
- attentionBlocked: string
- duplicate: string
- duplicateFailed: string
- deleteTitle: string
- removeFromAllGroups: string
- createFirstHint: string
- createFailed: string
- advanced: string
- advancedHint: string
- advancedFailed: string
- openAnotherChatUnsupported: string
- remoteConnectionsUnsupported: string
- /** Bot-open failure toasts (canonical-chat.ts notifyBotOpenFailure). The
- * raw RPC/connection error travels in the toast `detail`, never here. */
- openNeedsUpdateTitle: string
- openNeedsUpdateMessage: (connectionLabel: string) => string
- openUnreachableTitle: string
- openUnreachableMessage: string
- openChatFailedTitle: (botName: string) => string
- openChatFailedMessage: string
- openGateways: string
- /** Stands under the bot's name in a chat it has not spoken in yet. */
- chatEmpty: string
- /** First line of a brand-new bot's forever-chat — see `kickoffText`. */
- kickoff: string
- }
- /** Avatar picker: shapes, blobs, pets, uploads, generation. */
- avatar: {
- classicShapes: string
- blobFromName: string
- unlockFollowsName: string
- randomize: string
- /** The picker's four tabs, in order. */
- tabBot: string
- tabGenerate: string
- upload: string
- tabPet: string
- removeImage: string
- removeBackToShape: string
- describePlaceholder: string
- describeHint: string
- matchTheName: string
- pickPet: string
- petLoadFailed: string
- imageTooLarge: string
- generationFailed: string
- savedLocally: string
- savedLocallyDescriptionFailed: string
- generate: string
- generating: string
- }
- /** Group chats: the room, its composer, threads and activity feed. */
- group: {
- newTitle: string
- manageDesc: string
- manageTitle: string
- settingsTitle: string
- settingsDesc: string
- nameLabel: string
- holdDetection: string
- holdDetectionHint: string
- compressHistory: string
- compressHistoryHint: (member: string) => string
- compressing: (member: string) => string
- compressDone: (member: string, compressed: number, detail: string) => string
- compressNothing: (member: string) => string
- compressFailed: (member: string, error: string) => string
- searchToAdd: string
- searchToAddPlaceholder: string
- removeFromSelection: string
- disbandTitle: string
- deleteTitle: string
- deleteAction: string
- composerPlaceholder: string
- slashCommandsUnsupported: string
- attachHint: string
- newThread: string
- reply: string
- replyInThread: string
- replyInThreadPlaceholder: string
- openThread: string
- collapseThread: string
- collapseThreadLabel: string
- activity: string
- noActivityYet: string
- showActivity: string
- hideActivity: string
- stop: string
- stopHint: string
- allHeldStatus: (count: number) => string
- heldMembersStatus: (members: string) => string
- holdReleaseHint: string
- needsYourInput: string
- noMembersToSend: (group: string) => string
- pictureGenerationFailed: string
- nameTaken: (name: string) => string
- memberCount: (count: number) => string
- /** The reader's own lines in a room: the transcript speaker and the roster preview. */
- you: string
- /** How many of a room's members are reachable right now. */
- availableCount: (available: number, total: number) => string
- settingsHint: (group: string) => string
- settingsLabel: (group: string) => string
- disbandHint: (group: string) => string
- disbandLabel: (group: string) => string
- disbandAction: string
- disbanding: string
- disbandDone: string
- disbanded: (group: string) => string
- /** Wraps the bolded group name, so the name can lead the sentence in
- * languages that put it there — see core's cron.deleteDesc* pair. */
- disbandDescPrefix: string
- disbandDescSuffix: (count: number) => string
- stopped: (group: string) => string
- removeAttachment: string
- threadFallback: string
- replyCount: (replies: number) => string
- dropToThread: string
- dropToRoom: string
- waitingForAnswer: string
- memberThinking: (name: string) => string
- roomWorking: string
- messageRoom: (group: string) => string
- newThreadPlaceholder: (group: string) => string
- everyoneMeta: string
- commandApproval: string
- answerFailed: (handle: string, error: string) => string
- wantsToRunCommand: (handle: string) => string
- asks: (handle: string) => string
- answerTo: (member: string) => string
- }
- /** Skills hub + MCP setup surfaces embedded in the bot editor. */
- tools: {
- installHint: (name: string) => string
- installed: (name: string) => string
- installFailed: (name: string) => string
- searchHint: string
- resizeHint: string
- addServerFailed: string
- noTarget: string
- setKeyFailed: (name: string) => string
- configured: (name: string) => string
- authenticated: (name: string) => string
- testFailed: string
- completeSignIn: string
- needsSetup: (name: string) => string
- setUpDone: string
- saveTest: string
- authorizing: string
- working: string
- setupFailed: string
- signIn: string
- setUp: string
- skillsHub: string
- filterSkills: string
- searchHub: string
- noMcpServers: string
- }
-
- /** Bot Screen: the bot's headless desktop on the gateway host, live in a pane. */
- screen: {
- title: string
- menu: string
- unsupportedTitle: string
- unsupportedBody: string
- notInstalledTitle: string
- notInstalledBody: string
- installHint: string
- install: string
- installing: string
- installCancelled: string
- installFailed: string
- noPackageManager: string
- portalTitle: string
- portalOpen: string
- heroStopped: string
- heroNotInstalled: string
- heroConnecting: string
- heroStale: string
- heroSuppressed: string
- heroOpenLive: string
- heroInstall: string
- heroStart: string
- portalWatching: string
- portalYouControl: string
- portalOtherControls: string
- portalStopped: string
- portalNotInstalled: string
- portalUnsupported: string
- portalUnavailable: string
- /** Managed runtimes (Hermes Cloud): updates are the platform's job, not the user's. */
- portalUnavailableManaged: string
- managedNotIncludedTitle: string
- managedNotIncludedBody: string
- unavailableTitle: string
- autoOpenMenu: string
- autoOpenOnToast: (name: string) => string
- autoOpenOffToast: (name: string) => string
- stoppedTitle: string
- stoppedBody: string
- placementSandbox: (backend: string) => string
- imageSwitchTitle: string
- imageSwitchBody: (current: string, target: string) => string
- imageSwitchApprove: string
- imageSwitchKeep: string
- start: string
- attaching: string
- streamLost: string
- reconnect: string
- takeOver: string
- handBack: string
- handBackForce: string
- handBackForceHint: string
- openNeedsUpdate: string
- youControl: string
- otherControls: string
- agentControls: string
- controlTaken: string
- }
-
- /** Bot-scoped scheduled jobs. Generic scheduling chrome (weekday names,
- * Daily/Hourly, the job verbs) resolves against core's `cron` section. */
- cron: {
- untitled: string
- nameNul: string
- instructionNul: string
- minutesFromNow: string
- hoursFromNow: string
- daysFromNow: string
- stopAfter: string
- runsHint: string
- detailDescription: string
- status: string
- active: string
- paused: string
- schedule: string
- rawSchedule: string
- repeat: string
- nextRun: string
- overdueSince: string
- lastRun: string
- lastResult: string
- workdir: string
- succeeded: string
- failed: string
- deliveryFailed: string
- blockedConfig: string
- legacyUnsafe: string
- filterHint: string
- needsRosterFirst: string
- staleNotice: string
- readFailure: string
- createDesc: (bot: string) => string
- instruction: string
- whenToRun: string
- dayOfMonth: string
- sendResultsTo: string
- runHistoryOnly: string
- botChatTarget: (bot: string) => string
- continuity: string
- onceIn: (when: string) => string
- everyNDays: (days: number) => string
- everyNHours: (hours: number) => string
- everyNMinutes: (minutes: number) => string
- /** The frequency picker's eight options, in menu order. */
- freqOnce: string
- freqHourly: string
- freqDaily: string
- freqWeekdays: string
- freqWeekly: string
- freqMonthly: string
- freqInterval: string
- freqAdvanced: string
- unitMinutes: string
- unitHours: string
- unitDays: string
- /** One-line plain-language read-back of the picker's current state. */
- runsOnce: (count: number, unit: string) => string
- runsHourly: string
- runsDaily: (time: string) => string
- runsWeekdays: (time: string) => string
- runsWeekly: (day: string, time: string) => string
- runsMonthly: (day: string, time: string) => string
- runsInterval: (count: number, unit: string) => string
- runsRaw: string
- timesTotal: (count: number) => string
- }
-}
-
const en: BotsMessages = {
+ canonical: CANONICAL_GROUP_LOCALES.en,
editor: {
fullConfigHint: 'Full configuration needs a newer gateway (restart it after updating Hermes).',
liveCapabilities: 'Capabilities (applies immediately — skills, tools, MCP)',
@@@ -1765,44 -2221,8 +1776,18 @@@ const zhHant: BotsMessages =
}
/** Registered via `ctx.i18n.register` at plugin load (disposer tracked). */
-export const BOTS_LOCALES: PluginLocaleBundles = { en, ja, zh, 'zh-hant': zhHant }
+export const BOTS_LOCALES: PluginLocaleBundles = {
+ en,
+ ja,
+ zh,
+ 'zh-hant': zhHant,
+ ar: { canonical: CANONICAL_GROUP_LOCALES.ar },
+ ru: { canonical: CANONICAL_GROUP_LOCALES.ru },
+ fr: { canonical: CANONICAL_GROUP_LOCALES.fr },
+ de: { canonical: CANONICAL_GROUP_LOCALES.de },
+ es: { canonical: CANONICAL_GROUP_LOCALES.es }
+}
- // Bind the message SHAPE to a plugin translator: string leaves resolve now,
- // function leaves forward their args through t(path, …).
- type Bound<T> = {
- [K in keyof T]: T[K] extends (...args: infer A) => string
- ? (...args: A) => string
- : T[K] extends object
- ? Bound<T[K]>
- : string
- }
-
- function bind<T extends object>(t: PluginTranslate, template: T, prefix = ''): Bound<T> {
- const out = {} as Record<string, unknown>
-
- for (const [key, value] of Object.entries(template)) {
- const path = prefix ? `${prefix}.${key}` : key
- out[key] =
- typeof value === 'function'
- ? (...args: unknown[]) => t(path, ...args)
- : value && typeof value === 'object'
- ? bind(t, value as object, path)
- : t(path)
- }
-
- return out as Bound<T>
- }
-
export type BotsText = Bound<BotsMessages>
/** The Bot Mode strings for the active locale — one hook every component reads. */
diff --cc apps/shared/src/gateway-contract.generated.ts
index b09e6fa6b92,61cd9bcd4e9..f3c3c2dcb9e
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@@ -5177,29 -4489,69 +5196,70 @@@ export interface ClarifyQuestion
choices?: string[] | null
multi_select?: boolean
}
-/** ``{answers}`` for the whole set (early locks go through the ``clarify.lock`` RPC); a response without ``answers`` is cancel-all. */
+/** ``{answers}`` for the whole set (early locks go through the ``clarify.lock`` RPC); a response without ``answers`` is cancel-all. ``outcome`` (optional): how the viewer's own panel ended, as main's classic CLI reports it (``timed_out`` keeps the answers locked before its deadline). */
export interface ClarifyResult {
answers?: Record<string, string | null> | null
+ outcome?: 'submitted' | 'timed_out' | 'cancelled' | null
}
- export interface SetupChooseRequestParams {
+ /** ``card`` is the beat's data (``agent/onboarding_flow.py::BEATS``): name, theme, connectors and plugins have their own shape; layout, tour and build carry ``options``. ``tool_call_id`` is the setup_beat call the card belongs to: only that transcript row draws it. */
+ export interface SetupBeatRequestParams {
session_id: string
- kind: SetupChooseKind
- question: string
- options?: SetupChooseOption[] | null
- multi_select?: boolean
- preselected?: string[] | null
+ beat: SetupBeat
+ question?: string | null
+ tool_call_id?: string | null
+ card: SetupNameCard | SetupThemeCard | SetupOptionsCard | SetupConnectorsCard | SetupPluginsCard
}
- export type SetupChooseKind = 'question' | 'accent' | 'theme' | 'layout' | 'connectors' | 'plugins' | 'tour' | 'fork' | 'machine_use'
- export interface SetupChooseOption {
+ export type SetupBeat = 'name' | 'theme' | 'layout' | 'connectors' | 'plugins' | 'tour' | 'build'
+ export interface SetupNameCard {
+ suggested?: string | null
+ }
+ export interface SetupThemeCard {
+ picker: string
+ }
+ export interface SetupOptionsCard {
+ options: SetupOption[]
+ }
+ export interface SetupOption {
id: string
label: string
- detail?: string | null
}
- export interface SetupChooseResult {
- picked?: string | string[] | null
- label?: string | string[] | null
+ export interface SetupConnectorsCard {
+ suggested: string[]
+ }
+ export interface SetupPluginsCard {
+ plugins: string[]
+ }
+ /** ``answer`` holds the shown beat's picks; ids must be one of the card's options (the backend rejects any other answer). ``said`` is composer text typed while the name card waited: the name. ``wrote_instead``: the user sent a message instead of answering; the backend ends the turn and the client sends that message as the next one. A response with none of these, or none within 300 s, closes the card unanswered. */
+ export interface SetupBeatResult {
+ answer?: SetupNameAnswer | SetupThemeAnswer | SetupLayoutAnswer | SetupConnectorsAnswer | SetupPluginsAnswer | SetupTourAnswer | SetupBuildAnswer | null
said?: string | null
+ wrote_instead?: boolean
+ }
+ export interface SetupNameAnswer {
+ name: string
+ }
+ export interface SetupThemeAnswer {
+ accent?: string | null
+ mode?: string | null
+ }
+ export interface SetupLayoutAnswer {
+ layout: string
+ }
+ export interface SetupConnectorsAnswer {
+ connected: string[]
+ newly_connected?: string[]
+ }
+ export interface SetupPluginsAnswer {
+ installed: string[]
+ label?: string | null
+ }
+ export interface SetupTourAnswer {
+ tour: string
+ label?: string | null
+ }
+ export interface SetupBuildAnswer {
+ build: string
+ label?: string | null
}
/** ``tui_gateway/server.py::_approval_request_payload`` — the command is redacted server-side. */
export interface ApprovalRequestParams {
@@@ -5360,8 -4737,28 +5445,15 @@@ export interface GatewayReadyPayload
change_events: boolean
replay_epoch: string
heartbeat?: boolean | null
-}
-/** ``tui_gateway/change_watcher.py::resolve_skin`` — the resolved active skin (``HermesSkin``). ``{}`` when the skin engine failed to load. Colour maps are token → colour string. */
-export interface SkinPayload {
- name?: string
- description?: string
- colors?: Record<string, string>
- light_colors?: Record<string, string>
- dark_colors?: Record<string, string>
- branding?: Record<string, string>
- banner_logo?: string
- banner_hero?: string
- tool_prefix?: string
- help_header?: string
- [key: string]: unknown
+ session_authority?: boolean | null
}
+ /** ``agent/onboarding_record.py::_transition``: the run ``run_id`` stopped being in progress. ``stored_session_id`` is its chat at the compression tip. ``done``: the first-task card was answered; ``skipped``: Skip setup; ``replaced``: a rerun opened a new run; ``deleted``: its chat was deleted. */
+ export interface OnboardingEndedPayload {
+ run_id: string
+ stored_session_id: string
+ outcome: OnboardingOutcome
+ }
+ export type OnboardingOutcome = 'done' | 'skipped' | 'replaced' | 'deleted'
/** ``hermes_cli/free_tier_bootstrap.py::SetupRecord.as_payload``. */
export interface SetupReadyPayload {
provider_configured: boolean
@@@ -6750,12 -5990,10 +6842,10 @@@ export interface BackendGatewayEventMa
'free_tier.challenge': FreeTierChallengePayload
/** First frame of a connection: the resolved skin, the change-event capability and the replay epoch. */
'gateway.ready': GatewayReadyPayload
- /** Apply a named desktop layout preset. */
- 'layout.apply': LayoutApplyPayload
/** The turn ended: final text, usage and outcome. */
'message.complete': MessageCompletePayload
- /** One streamed chunk of the assistant reply. */
- 'message.delta': StreamDeltaPayload
+ /** One streamed chunk of the assistant reply (null text: segment boundary). */
+ 'message.delta': MessageDeltaPayload
/** Interim assistant commentary (text beside tool calls) sealed as its own segment. */
'message.interim': MessageInterimPayload
/** The agent reacted to a message; paint it live. */
diff --cc apps/shared/src/gateway-contract.openrpc.json
index 8de6276a741,ba761e0f919..149feb197b9
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@@ -11206,22 -11086,103 +11170,56 @@@
}
},
"required": [
- "connector",
- "enabled",
- "connected",
- "connection_status",
- "status_reason",
- "gateway_disabled_tools"
+ "force",
+ "enable"
],
- "title": "ConnectorRow",
+ "title": "CatalogApproved",
"type": "object"
},
- "ConnectorToolFacet": {
- "enum": [
- "read",
- "write",
- "destructive",
- "unclassified"
- ],
- "title": "ConnectorToolFacet",
- "type": "string"
- },
- "ConnectorToolRow": {
++ "CatalogPluginPresence": {
+ "additionalProperties": false,
++ "description": "A named catalog plugin this OS runs. ``state`` is the pinned ``plugin.json`` app declaration judged\non this host; ``sentence`` names what is missing (empty when present or unknown); ``disclosure`` is the\ncatalog description's ``Disclosure:`` sentence (empty when it has none).",
+ "properties": {
- "slug": {
- "title": "Slug",
- "type": "string"
- },
+ "name": {
+ "title": "Name",
+ "type": "string"
+ },
- "description": {
- "title": "Description",
++ "title": {
++ "title": "Title",
+ "type": "string"
+ },
- "facet": {
- "$ref": "#/components/schemas/ConnectorToolFacet"
- },
- "hints": {
- "items": {
- "type": "string"
- },
- "title": "Hints",
- "type": "array"
- },
- "categories": {
- "items": {
- "type": "string"
- },
- "title": "Categories",
- "type": "array"
++ "state": {
++ "$ref": "#/components/schemas/CatalogAppState"
+ },
- "no_auth": {
- "title": "No Auth",
- "type": "boolean"
++ "sentence": {
++ "title": "Sentence",
++ "type": "string"
+ },
- "deprecated": {
- "title": "Deprecated",
- "type": "boolean"
++ "disclosure": {
++ "title": "Disclosure",
++ "type": "string"
+ }
+ },
+ "required": [
- "slug",
+ "name",
- "description",
- "facet",
- "hints",
- "categories",
- "no_auth",
- "deprecated"
++ "title",
++ "state",
++ "sentence",
++ "disclosure"
+ ],
- "title": "ConnectorToolRow",
++ "title": "CatalogPluginPresence",
+ "type": "object"
+ },
- "ConnectorToolsParams": {
+ "CatalogScan": {
"additionalProperties": false,
+ "description": "The catalog's security scan of the pinned commit; read-only on the card.",
"properties": {
- "profile": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Profile"
+ "status": {
+ "$ref": "#/components/schemas/CatalogScanStatus"
},
- "slug": {
- "title": "Slug",
+ "summary": {
+ "title": "Summary",
"type": "string"
- },
- "refresh": {
- "default": false,
- "title": "Refresh",
- "type": "boolean"
}
},
"required": [
@@@ -12801,33 -12626,34 +12799,45 @@@
"type": "null"
}
],
- "default": null,
- "title": "Extra Files"
+ "default": null
+ },
- "log_lines": {
++ "said": {
+ "anyOf": [
+ {
- "type": "integer"
++ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
- "title": "Log Lines"
++ "title": "Said"
}
},
- "title": "DiagnosticsShareNousParams",
+ "title": "ConnectionAnswer",
"type": "object"
},
- "DiagnosticsShareNousResult": {
+ "ConnectionAnswerStatus": {
+ "description": "What the card says about one row: ``tools/connectors/mcp.py::apply_answer``.",
+ "enum": [
+ "approved",
+ "skipped"
+ ],
+ "title": "ConnectionAnswerStatus",
+ "type": "string"
+ },
+ "ConnectionAnswerTarget": {
"additionalProperties": false,
- "description": "Structured envelope: ``ok=False`` + ``error`` renders inline instead of failing the RPC.",
+ "description": "One row's answer from the card. ``env`` carries the credential values an install asked for\nthrough ``required_env``.",
"properties": {
- "ok": {
- "title": "Ok",
- "type": "boolean"
+ "name": {
+ "title": "Name",
+ "type": "string"
},
- "view_url": {
+ "status": {
+ "$ref": "#/components/schemas/ConnectionAnswerStatus"
+ },
+ "detail": {
"anyOf": [
{
"type": "string"
@@@ -21007,79 -21421,37 +21017,64 @@@
}
},
"required": [
- "ok",
- "filename",
- "zipBase64"
+ "id",
+ "endonym",
+ "rtl",
+ "source"
],
- "title": "PetExportResult",
+ "title": "LanguageOption",
"type": "object"
},
- "LayoutApplyPayload": {
- "additionalProperties": true,
- "description": "``tools/apply_layout_tool.py``.",
- "properties": {
- "preset": {
- "title": "Preset",
- "type": "string"
- }
- },
- "required": [
- "preset"
- ],
- "title": "LayoutApplyPayload",
- "type": "object"
- },
- "PetGalleryEntry": {
+ "LearningAxis": {
"additionalProperties": false,
"properties": {
- "slug": {
- "title": "Slug",
+ "start": {
+ "title": "Start",
"type": "string"
},
- "displayName": {
- "title": "Displayname",
+ "end": {
+ "title": "End",
"type": "string"
+ }
+ },
+ "required": [
+ "start",
+ "end"
+ ],
+ "title": "LearningAxis",
+ "type": "object"
+ },
+ "LearningBucketRow": {
+ "additionalProperties": false,
+ "properties": {
+ "index": {
+ "title": "Index",
+ "type": "integer"
},
- "installed": {
- "title": "Installed",
- "type": "boolean"
+ "label": {
+ "title": "Label",
+ "type": "string"
},
- "spritesheetUrl": {
- "default": "",
- "title": "Spritesheeturl",
+ "date": {
+ "title": "Date",
"type": "string"
},
- "curated": {
+ "skills": {
+ "title": "Skills",
+ "type": "integer"
+ },
+ "memories": {
+ "title": "Memories",
+ "type": "integer"
+ },
+ "total": {
+ "title": "Total",
+ "type": "integer"
+ },
+ "category": {
"anyOf": [
{
- "type": "boolean"
+ "type": "string"
},
{
"type": "null"
@@@ -21781,39 -22203,232 +21776,208 @@@
}
},
"required": [
- "enabled"
+ "prompt",
+ "status",
+ "mode",
+ "interval_seconds",
+ "current_delay",
+ "times",
+ "until",
+ "max_ticks",
+ "ticks_fired",
+ "created_at",
+ "last_fired_at",
+ "next_due_at",
+ "awaiting_response",
+ "deferred_by_goal"
],
- "title": "PetInfoResult",
+ "title": "LoopSnapshot",
"type": "object"
},
- "PetRenameParams": {
++ "MachineFactsResult": {
+ "additionalProperties": false,
++ "description": "``machine_kind`` is ``Spark``, ``Mac``, ``PC`` or ``computer``. ``nvidia_platform`` is\n``products.nvidia_platform()``: ``rtx_spark``, ``dgx_spark``, ``discrete`` or null. ``locale`` is the OS\naccount's first UI language, null when the OS has none.",
+ "properties": {
- "profile": {
++ "machine": {
++ "$ref": "#/components/schemas/MachineInfo"
++ },
++ "machine_kind": {
++ "title": "Machine Kind",
++ "type": "string"
++ },
++ "has_nvidia_gpu": {
++ "title": "Has Nvidia Gpu",
++ "type": "boolean"
++ },
++ "nvidia_platform": {
+ "anyOf": [
+ {
++ "enum": [
++ "rtx_spark",
++ "dgx_spark",
++ "discrete"
++ ],
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
- "title": "Profile"
- },
- "slug": {
- "title": "Slug",
- "type": "string"
++ "title": "Nvidia Platform"
+ },
- "name": {
- "title": "Name",
- "type": "string"
- }
- },
- "required": [
- "slug",
- "name"
- ],
- "title": "PetRenameParams",
- "type": "object"
- },
- "PetScaleParams": {
- "additionalProperties": false,
- "properties": {
- "profile": {
++ "locale": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
- "title": "Profile"
- },
- "scale": {
- "default": null,
- "title": "Scale"
- }
- },
- "title": "PetScaleParams",
- "type": "object"
- },
- "PetScaleResult": {
- "additionalProperties": false,
- "properties": {
- "ok": {
- "title": "Ok",
- "type": "boolean"
- },
- "scale": {
- "title": "Scale",
- "type": "number"
++ "title": "Locale"
+ }
+ },
+ "required": [
- "ok",
- "scale"
++ "machine",
++ "machine_kind",
++ "has_nvidia_gpu"
+ ],
- "title": "PetScaleResult",
++ "title": "MachineFactsResult",
+ "type": "object"
+ },
- "PetSlugParams": {
++ "MachineInfo": {
+ "additionalProperties": false,
++ "description": "Measured hardware; a key that was not measured is absent.",
+ "properties": {
- "profile": {
++ "os_family": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
- "title": "Profile"
- },
- "slug": {
- "title": "Slug",
- "type": "string"
- }
- },
- "required": [
- "slug"
- ],
- "title": "PetSlugParams",
- "type": "object"
- },
- "PetSlugResult": {
- "additionalProperties": false,
- "properties": {
- "ok": {
- "title": "Ok",
- "type": "boolean"
- },
- "slug": {
- "title": "Slug",
- "type": "string"
++ "title": "Os Family"
+ },
- "displayName": {
++ "os_release": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
- "title": "Displayname"
- }
- },
- "required": [
- "ok",
- "slug"
- ],
- "title": "PetSlugResult",
- "type": "object"
- },
- "PetSpritePayload": {
- "additionalProperties": false,
- "properties": {
- "slug": {
++ "title": "Os Release"
++ },
++ "native_arch": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
- "title": "Slug"
++ "title": "Native Arch"
+ },
- "displayName": {
++ "cpu_model": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
- "title": "Displayname"
++ "title": "Cpu Model"
+ },
- "mime": {
++ "ram_gb": {
+ "anyOf": [
+ {
- "type": "string"
++ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
- "title": "Mime"
++ "title": "Ram Gb"
+ },
- "spritesheetBase64": {
++ "gpu_class": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
- "title": "Spritesheetbase64"
++ "title": "Gpu Class"
+ },
- "spritesheetRevision": {
++ "vendor": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
- "title": "Spritesheetrevision"
++ "title": "Vendor"
+ },
- "frameW": {
++ "wsl": {
+ "anyOf": [
+ {
- "type": "integer"
++ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
- "title": "Framew"
++ "title": "Wsl"
+ },
- "frameH": {
++ "container": {
+ "anyOf": [
+ {
- "type": "integer"
++ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
- "title": "Frameh"
++ "title": "Container"
++ }
++ },
++ "title": "MachineInfo",
++ "type": "object"
++ },
+ "McpCatalogEntry": {
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string"
},
- "framesPerState": {
+ "description": {
+ "title": "Description",
+ "type": "string"
+ },
+ "connector_slug": {
"anyOf": [
{
- "type": "integer"
+ "type": "string"
},
{
"type": "null"
@@@ -24057,202 -24268,146 +24221,241 @@@
}
},
"required": [
- "id",
- "resolved_id"
+ "text",
+ "level",
+ "kind"
],
- "title": "ProfileCanonicalSession",
+ "title": "NotificationShowPayload",
"type": "object"
},
- "ProfileMirrored": {
+ "OkResult": {
"additionalProperties": false,
- "description": "What was copied from the launch profile; ``auth`` is ``\"shared\"`` under ``share_auth``.",
"properties": {
- "env": {
- "default": false,
- "title": "Env",
+ "ok": {
+ "default": true,
+ "title": "Ok",
"type": "boolean"
+ }
+ },
+ "title": "OkResult",
+ "type": "object"
+ },
+ "OnboardingCatalogPlugin": {
+ "additionalProperties": false,
+ "description": "A catalog plugin curated for the onboarding card (``onboarding: true``) that this OS runs.\n``app_state`` is the pinned ``plugin.json`` declaration judged on this host; ``sentence`` names what\nis missing (empty when present or unknown).",
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string"
},
- "auth": {
- "anyOf": [
- {
- "type": "boolean"
- },
- {
- "const": "shared",
- "type": "string"
- }
- ],
- "default": false,
- "title": "Auth"
+ "title": {
+ "title": "Title",
+ "type": "string"
},
- "model_inherited": {
- "default": false,
- "title": "Model Inherited",
- "type": "boolean"
+ "description": {
+ "title": "Description",
+ "type": "string"
},
- "voice": {
- "default": false,
- "title": "Voice",
- "type": "boolean"
+ "tier": {
+ "$ref": "#/components/schemas/CatalogTier"
+ },
+ "platforms": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Platforms",
+ "type": "array"
+ },
+ "app_state": {
+ "$ref": "#/components/schemas/CatalogAppState"
+ },
+ "sentence": {
+ "title": "Sentence",
+ "type": "string"
}
},
- "title": "ProfileMirrored",
+ "required": [
+ "name",
+ "title",
+ "description",
+ "tier",
+ "platforms",
+ "app_state",
+ "sentence"
+ ],
+ "title": "OnboardingCatalogPlugin",
"type": "object"
},
- "OnboardingEnsureSetupProfileResult": {
- "ProfileModelPin": {
++ "OnboardingEndedPayload": {
"additionalProperties": false,
- "description": "``created`` is false when an existing setup profile was found (and returned untouched).",
++ "description": "``agent/onboarding_record.py::_transition``: the run ``run_id`` stopped being in progress.\n``stored_session_id`` is its chat at the compression tip. ``done``: the first-task card was answered;\n``skipped``: Skip setup; ``replaced``: a rerun opened a new run; ``deleted``: its chat was deleted.",
"properties": {
- "name": {
- "title": "Name",
- "provider": {
- "default": "",
- "title": "Provider",
++ "run_id": {
++ "title": "Run Id",
"type": "string"
},
- "path": {
- "title": "Path",
- "default": {
- "type": "string",
- "default": "",
- "title": "Default"
++ "stored_session_id": {
++ "title": "Stored Session Id",
+ "type": "string"
+ },
- "created": {
- "title": "Created",
- "type": "boolean"
++ "outcome": {
++ "$ref": "#/components/schemas/OnboardingOutcome"
}
},
- "title": "ProfileModelPin",
+ "required": [
- "name",
- "path",
- "created"
++ "run_id",
++ "stored_session_id",
++ "outcome"
+ ],
- "title": "OnboardingEnsureSetupProfileResult",
++ "title": "OnboardingEndedPayload",
"type": "object"
},
- "OnboardingEnsureSetupSessionParams": {
- "ProfileNameParams": {
++ "OnboardingFactsSource": {
++ "enum": [
++ "local",
++ "remote"
++ ],
++ "title": "OnboardingFactsSource",
++ "type": "string"
++ },
++ "OnboardingOutcome": {
++ "enum": [
++ "done",
++ "skipped",
++ "replaced",
++ "deleted"
++ ],
++ "title": "OnboardingOutcome",
++ "type": "string"
++ },
++ "OnboardingRunStateResult": {
"additionalProperties": false,
++ "description": "``run``: onboarding opens on this launch (root config ``onboarding.run``, else a machine that\nnever used Hermes). ``eligible``: this is the desktop's local backend and the welcome trial or a\nconfigured provider can carry the first chat.\n``session_id``: the stored id of the onboarding chat still in progress, so a relaunch reopens it;\n``run_id``: that run's id, which ``onboarding.ended`` names.",
"properties": {
- "messages": {
- "profile": {
++ "run": {
++ "title": "Run",
++ "type": "boolean"
++ },
++ "eligible": {
++ "title": "Eligible",
++ "type": "boolean"
++ },
++ "session_id": {
"anyOf": [
{
- "items": {
- "additionalProperties": true,
- "type": "object"
- },
- "type": "array"
+ "type": "string"
},
{
"type": "null"
}
],
"default": null,
- "title": "Messages"
- "title": "Profile"
++ "title": "Session Id"
+ },
- "name": {
++ "run_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
- "title": "Name"
++ "title": "Run Id"
}
},
- "title": "OnboardingEnsureSetupSessionParams",
- "title": "ProfileNameParams",
++ "required": [
++ "run",
++ "eligible"
++ ],
++ "title": "OnboardingRunStateResult",
"type": "object"
},
- "OnboardingEnsureSetupSessionResult": {
- "ProfileParams": {
++ "OnboardingSetRunParams": {
+ "additionalProperties": false,
++ "description": "``mark_profile_offered`` also latches ``onboarding.seen.profile_build_offered`` in the root config,\nso the first chat after onboarding gets the plain intro instead of the profile offer.",
+ "properties": {
- "profile": {
- "title": "Profile",
- "type": "string"
++ "run": {
++ "title": "Run",
++ "type": "boolean"
+ },
++ "mark_profile_offered": {
++ "default": false,
++ "title": "Mark Profile Offered",
++ "type": "boolean"
++ }
++ },
++ "required": [
++ "run"
++ ],
++ "title": "OnboardingSetRunParams",
++ "type": "object"
++ },
++ "OnboardingSkipParams": {
+ "additionalProperties": false,
- "description": "Any method the desktop may route to a named profile (``requestGatewayForProfile`` adds ``profile``).",
+ "properties": {
+ "session_id": {
+ "title": "Session Id",
+ "type": "string"
+ },
- "empty": {
- "title": "Empty",
- "type": "boolean"
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
}
},
- "title": "ProfileParams",
+ "required": [
- "profile",
- "session_id",
- "empty"
++ "session_id"
+ ],
- "title": "OnboardingEnsureSetupSessionResult",
++ "title": "OnboardingSkipParams",
"type": "object"
},
- "OnboardingIntro": {
- "enum": [
- "unseen",
- "seen"
- ],
- "title": "OnboardingIntro",
- "type": "string"
- },
- "OnboardingResetSetupProfileResult": {
- "ProfileRow": {
++ "OnboardingSkipResult": {
"additionalProperties": false,
- "description": "One roster row; the session fields are present only with ``include_sessions``.",
"properties": {
-- "name": {
-- "title": "Name",
- "type": "string"
- },
- "path": {
- "title": "Path",
-- "type": "string"
- },
- "reset": {
- "default": true,
- "title": "Reset",
++ "skipped": {
++ "title": "Skipped",
+ "type": "boolean"
+ }
+ },
+ "required": [
- "name",
- "path"
++ "skipped"
+ ],
- "title": "OnboardingResetSetupProfileResult",
++ "title": "OnboardingSkipResult",
+ "type": "object"
+ },
- "OnboardingStateResult": {
++ "OnboardingStartParams": {
+ "additionalProperties": false,
++ "description": "``rerun``: start a new onboarding chat even when one is in progress (Settings, Run onboarding\nagain; it never claims the welcome trial). ``fresh_launch``: the app's once-per-launch start; a run\nthe app was closed on does not count, so its chat is deleted and the run starts over.\n``facts_source``: whether the backend runs on the user's own computer. ``locale``: the desktop's UI\nlanguage, preferred over the backend OS locale. ``assume_fresh``: as on ``onboarding.state``. A new\nrun on a first install claims the welcome trial before its chat exists; a failed claim is error\n5079 and leaves no guest and no chat. A claim that is blocked (another install took the trial) with\nno trial or provider to run on is error 5080 and opens no chat.",
+ "properties": {
- "eligible": {
- "title": "Eligible",
++ "rerun": {
++ "default": false,
++ "title": "Rerun",
+ "type": "boolean"
},
- "intro": {
- "$ref": "#/components/schemas/OnboardingIntro"
- "path": {
- "title": "Path",
- "type": "string"
++ "fresh_launch": {
++ "default": false,
++ "title": "Fresh Launch",
++ "type": "boolean"
},
- "failed_starts": {
- "title": "Failed Starts",
- "type": "integer"
- "is_default": {
++ "assume_fresh": {
+ "default": false,
- "title": "Is Default",
++ "title": "Assume Fresh",
+ "type": "boolean"
},
- "completed_at": {
- "model": {
-- "anyOf": [
-- {
-- "type": "string"
-- },
-- {
-- "type": "null"
-- }
-- ],
-- "default": null,
- "title": "Completed At"
- "title": "Model"
++ "facts_source": {
++ "$ref": "#/components/schemas/OnboardingFactsSource",
++ "default": "local"
},
- "profile": {
- "provider": {
++ "locale": {
"anyOf": [
{
"type": "string"
@@@ -24262,20 -24417,99 +24465,58 @@@
}
],
"default": null,
- "title": "Profile"
- "title": "Provider"
- },
- "description": {
- "default": "",
- "title": "Description",
++ "title": "Locale"
++ }
++ },
++ "title": "OnboardingStartParams",
++ "type": "object"
++ },
++ "OnboardingStartResult": {
++ "additionalProperties": false,
++ "description": "``session_id`` is the runtime id the client attaches to; ``resumed`` is true when an onboarding\nchat already in progress was reopened instead of a new one started. ``run_id`` names the run in\n``onboarding.ended``.",
++ "properties": {
++ "session_id": {
++ "title": "Session Id",
+ "type": "string"
+ },
- "display_name": {
- "default": "",
- "title": "Display Name",
++ "stored_session_id": {
++ "title": "Stored Session Id",
+ "type": "string"
+ },
- "skill_count": {
- "default": 0,
- "title": "Skill Count",
- "type": "integer"
- },
- "previous_names": {
- "items": {
- "type": "string"
- },
- "title": "Previous Names",
- "type": "array"
- },
- "last_session": {
- "anyOf": [
- {
- "$ref": "#/components/schemas/ProfileSessionPreview"
- },
- {
- "type": "null"
- }
- ],
- "default": null
- },
- "worker_session": {
- "anyOf": [
- {
- "$ref": "#/components/schemas/ProfileWorkerSession"
- },
- {
- "type": "null"
- }
- ],
- "default": null
- },
- "canonical_session": {
- "anyOf": [
- {
- "$ref": "#/components/schemas/ProfileCanonicalSession"
- },
- {
- "type": "null"
- }
- ],
- "default": null
- },
- "ui_meta_revisions": {
- "additionalProperties": {
- "type": "integer"
- },
- "title": "Ui Meta Revisions",
- "type": "object"
- },
- "ui_meta": {
- "anyOf": [
- {
- "additionalProperties": true,
- "type": "object"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Ui Meta"
- },
- "has_avatar": {
- "default": false,
- "title": "Has Avatar",
++ "resumed": {
++ "title": "Resumed",
+ "type": "boolean"
++ },
++ "run_id": {
++ "title": "Run Id",
++ "type": "string"
}
},
"required": [
- "eligible",
- "intro",
- "failed_starts"
- "name",
- "path"
++ "session_id",
++ "stored_session_id",
++ "resumed",
++ "run_id"
],
- "title": "OnboardingStateResult",
- "title": "ProfileRow",
++ "title": "OnboardingStartResult",
+ "type": "object"
+ },
- "ProfileSessionPreview": {
++ "OnboardingStateParams": {
+ "additionalProperties": false,
- "description": "Newest human-facing session of a profile (``_latest_profile_session_rows``).",
++ "description": "``assume_fresh``: the unpackaged desktop's ``--fresh-install`` launch; the backend treats this\nmachine as one that never used Hermes. Packaged builds never send it.",
++ "properties": {
++ "assume_fresh": {
++ "default": false,
++ "title": "Assume Fresh",
++ "type": "boolean"
++ }
++ },
++ "title": "OnboardingStateParams",
+ "type": "object"
+ },
+ "OpenRequestEntry": {
+ "additionalProperties": false,
+ "description": "One unanswered server\u2192client request (``server_requests.Request.snapshot``); the reconnecting\nclient re-delivers it to its request handlers.",
"properties": {
"id": {
"title": "Id",
@@@ -26722,71 -26781,48 +26963,72 @@@
"type": "null"
}
],
- "default": null
+ "default": null,
+ "title": "Has Value"
}
},
- "title": "ProjectsRecordReposParams",
+ "required": [
+ "key",
+ "type",
+ "label",
+ "description",
+ "required"
+ ],
+ "title": "PluginSettingField",
"type": "object"
},
- "ProjectsRecordReposResult": {
+ "PluginSettingFieldType": {
+ "enum": [
+ "string",
+ "number",
+ "boolean",
+ "enum",
+ "secret",
+ "json"
+ ],
+ "title": "PluginSettingFieldType",
+ "type": "string"
+ },
+ "PluginsAction": {
+ "enum": [
+ "list",
+ "toggle",
+ "install",
+ "update",
+ "remove",
+ "settings",
- "onboarding"
++ "onboarding",
++ "presence"
+ ],
+ "title": "PluginsAction",
+ "type": "string"
+ },
+ "PluginsListParams": {
+ "additionalProperties": false,
+ "properties": {},
+ "title": "PluginsListParams",
+ "type": "object"
+ },
+ "PluginsListResult": {
"additionalProperties": false,
"properties": {
- "repos": {
+ "plugins": {
"items": {
- "$ref": "#/components/schemas/DiscoveredRepo"
+ "$ref": "#/components/schemas/LegacyPluginRow"
},
- "title": "Repos",
+ "title": "Plugins",
"type": "array"
- },
- "discovery_policy": {
- "anyOf": [
- {
- "$ref": "#/components/schemas/RepoDiscoveryPolicy"
- },
- {
- "type": "null"
- }
- ],
- "default": null
- },
- "accepted": {
- "title": "Accepted",
- "type": "boolean"
}
},
"required": [
- "repos",
- "accepted"
+ "plugins"
],
- "title": "ProjectsRecordReposResult",
+ "title": "PluginsListResult",
"type": "object"
},
- "ProjectsSetActiveParams": {
+ "PluginsManageParams": {
"additionalProperties": false,
- "description": "``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name``\n(+ ``force``, ``enable``, ``ref``); ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pin\nthat widened the plugin after the user confirmed the ``delta``); ``remove``: ``name`` (user installs only);\n``settings``: ``key`` + ``values`` (``{setting_key: value}``, non-secret schema keys only).",
- "description": "No ``id`` (or null) clears the active project.",
++ "description": "``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name``\n(+ ``force``, ``enable``, ``ref``); ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pin\nthat widened the plugin after the user confirmed the ``delta``); ``remove``: ``name`` (user installs only);\n``settings``: ``key`` + ``values`` (``{setting_key: value}``, non-secret schema keys only);\n``presence``: ``names`` (catalog names, answered in that order).",
"properties": {
"profile": {
"anyOf": [
@@@ -26923,23 -26997,39 +27165,38 @@@
}
],
"default": null,
- "title": "Color"
+ "title": "Values"
+ },
- "board_slug": {
++ "names": {
+ "anyOf": [
+ {
- "type": "string"
++ "items": {
++ "type": "string"
++ },
++ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
- "title": "Board Slug"
++ "title": "Names"
}
},
- "required": [
- "id"
- ],
- "title": "ProjectsUpdateParams",
+ "title": "PluginsManageParams",
"type": "object"
},
- "PromptSubmitParams": {
+ "PluginsManageResult": {
"additionalProperties": false,
- "description": "``text`` is normally a string; the relay / hosted paths may hand a structured (parts list)\npayload, and the busy path renders it. Truncation (rewind / edit / regenerate) needs explicit\nconsent: ``confirm_truncate`` plus one durable target (``truncate_before_row_id`` preferred,\n``truncate_before_message_id``, or the legacy ``truncate_before_user_ordinal``).",
+ "description": "``list`` \u2192 ``plugins`` + counts; ``toggle`` \u2192 ``ok``/``unchanged``/``restart_required``/``name``\n(the canonical key written)/``plugin``; ``install`` \u2192 ``hermes_cli.plugins_cmd.dashboard_install_plugin``'s\nok payload; ``toggle``/``install``/``update`` that loaded a plugin also carry ``gateway_reloaded`` (the\nrunning gateway picked it up and re-wired its handlers) and ``activation`` \u2014 the honest split of what is\nlive now vs deferred, so ``restart_required`` is True only when no gateway answered; ``update`` \u2192 ``ok``/``unchanged``/``sha``, or ``ok=false`` + ``consent_required`` with the\n``delta`` (``{surface: [added...]}``) / ``delta_lines`` a widened pin adds \u2014 nothing changed until the\nclient retries with ``accept_capabilities``; ``remove`` \u2192 ``ok``/``name`` plus\n``cleared_memory_provider`` when the removed plugin was the live ``memory.provider``.",
"properties": {
- "session_id": {
- "title": "Session Id",
- "type": "string"
- },
- "profile": {
+ "plugins": {
"anyOf": [
{
- "type": "string"
+ "items": {
+ "$ref": "#/components/schemas/AgentPluginRow"
+ },
+ "type": "array"
},
{
"type": "null"
@@@ -27259,25 -27399,75 +27516,40 @@@
}
],
"default": null,
- "title": "Accounts"
- }
- },
- "title": "ProviderUsage",
- "type": "object"
- },
- "ProviderUsageAccount": {
- "additionalProperties": false,
- "description": "One account of a provider's credential pool (``hermes_cli/inventory.py::_pool_usage_accounts``).\n``id`` is a stable non-secret account identity (never a key or URL); ``label`` may be empty (UI\nfalls back to a localized \"Account N\"). ``windows`` is empty while the account's usage is not\nyet known \u2014 state carries the meaning, never a fabricated gauge.\n\n``state``: ``ready`` \u2014 live quota below the cap (numeric windows present); ``limited`` \u2014 a live\ncredential-wide cooldown or exhausted account-scoped quota windows; ``unknown`` \u2014 no live\nnumeric windows (failed/empty fetch, stale snapshot, provider without a usage API);\n``unavailable`` \u2014 DEAD auth row (kept visible, never a quota row).\n\n``resets_at``: for a limited account, the LATEST of its exhausted account-scoped windows (or a\nlive cooldown when later); ``None`` when unknown (the frontend renders its own advisory, e.g.\nthe earliest limited sibling).",
- "properties": {
- "id": {
- "title": "Id",
- "type": "string"
- },
- "label": {
- "default": "",
- "title": "Label",
- "type": "string"
- },
- "windows": {
- "items": {
- "$ref": "#/components/schemas/ProviderUsageWindow"
- },
- "title": "Windows",
- "type": "array"
- },
- "state": {
- "enum": [
- "ready",
- "limited",
- "unknown",
- "unavailable"
- ],
- "title": "State",
- "type": "string"
+ "title": "Onboarding"
+ },
- "resets_at": {
++ "presence": {
+ "anyOf": [
+ {
- "type": "string"
++ "items": {
++ "$ref": "#/components/schemas/CatalogPluginPresence"
++ },
++ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
- "title": "Resets At"
++ "title": "Presence"
}
},
- "required": [
- "id",
- "state"
- ],
- "title": "ProviderUsageAccount",
+ "title": "PluginsManageResult",
"type": "object"
},
- "ProviderUsageWindow": {
+ "PreviewActRequestParams": {
"additionalProperties": false,
- "description": "One subscription usage window (``agent/account_usage.py::AccountUsageWindow``): e.g. the 5-hour\nsession or the weekly cap, with how much of it is spent and when it rolls over (ISO).\n\n``scope``: ``account`` \u2014 exhausting the window exhausts the whole login (Codex session/weekly,\nso a limited account's resets_at must wait for it); ``model`` \u2014 the window caps only one model\nfamily (Anthropic Opus/Sonnet weekly) and can never imply the account itself is out of quota.",
+ "description": "``tools/drive_preview_tool.py`` and ``tools/annotate_preview_tool.py`` field sets.",
"properties": {
- "label": {
- "title": "Label",
+ "session_id": {
+ "title": "Session Id",
"type": "string"
},
- "used_percent": {
- "title": "Used Percent",
- "type": "number"
+ "action": {
+ "title": "Action",
+ "type": "string"
},
- "resets_at": {
+ "ref": {
"anyOf": [
{
"type": "string"
@@@ -37140,186 -37433,41 +37412,64 @@@
}
},
"required": [
- "todos",
- "revision"
+ "hidden",
+ "session_key"
],
- "title": "TodoUpdatedPayload",
+ "title": "SessionSetHiddenResult",
"type": "object"
},
- "SessionStartChatParams": {
- "additionalProperties": false,
- "description": "``tool_call_id`` names the rejected call; its saved tool row records a started retry (display-only).",
- "properties": {
- "session_id": {
- "title": "Session Id",
- "type": "string"
- },
- "profile": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Profile"
- },
- "tool_call_id": {
- "title": "Tool Call Id",
- "type": "string"
- },
- "args": {
- "$ref": "#/components/schemas/StartChatArgs"
- }
- },
- "required": [
- "session_id",
- "tool_call_id",
- "args"
- ],
- "title": "SessionStartChatParams",
- "type": "object"
- },
- "SessionStartChatResult": {
- "additionalProperties": false,
- "description": "``tui_gateway/start_chat.py``: ``started`` carries the new chat, ``rejected`` a reason and whether the same\narguments may succeed on another try (``retryable``). A call already retried returns that retry's result.",
- "properties": {
- "status": {
- "$ref": "#/components/schemas/StartChatStatus"
- },
- "session_id": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Session Id"
- },
- "profile": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Profile"
- },
- "title": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Title"
- },
- "message": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Message"
- },
- "reason": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Reason"
- },
- "retryable": {
- "anyOf": [
- {
- "type": "boolean"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Retryable"
- }
- },
- "required": [
- "status"
- ],
- "title": "SessionStartChatResult",
- "type": "object"
- },
- "ToolCompletePayload": {
+ "SessionStats": {
"additionalProperties": false,
- "description": "``tool_progress._on_tool_complete``; ``todos``/``revision`` merged in for the todo tools.",
+ "description": "``gateway/session_usage.py::usage_stats``: session-cumulative counters (the agent's ``session_*``),\ncontext / compressor figures, rolling latency and throughput, rate-limit state, live subagents.",
"properties": {
- "tool_id": {
- "title": "Tool Id",
- "type": "string"
+ "input_tokens": {
+ "title": "Input Tokens",
+ "type": "integer"
},
- "name": {
- "title": "Name",
- "type": "string"
+ "output_tokens": {
+ "title": "Output Tokens",
+ "type": "integer"
},
- "args": {
- "anyOf": [
- {
- "additionalProperties": true,
- "type": "object"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Args"
+ "cache_read_tokens": {
+ "title": "Cache Read Tokens",
+ "type": "integer"
},
- "duration_s": {
+ "cache_write_tokens": {
+ "title": "Cache Write Tokens",
+ "type": "integer"
+ },
+ "prompt_tokens": {
+ "title": "Prompt Tokens",
+ "type": "integer"
+ },
+ "completion_tokens": {
+ "title": "Completion Tokens",
+ "type": "integer"
+ },
+ "total_tokens": {
+ "title": "Total Tokens",
+ "type": "integer"
+ },
+ "reasoning_tokens": {
+ "title": "Reasoning Tokens",
+ "type": "integer"
+ },
+ "api_calls": {
+ "title": "Api Calls",
+ "type": "integer"
+ },
+ "last_prompt_tokens": {
+ "title": "Last Prompt Tokens",
+ "type": "integer"
+ },
+ "context_tokens": {
+ "title": "Context Tokens",
+ "type": "integer"
+ },
+ "context_length": {
"anyOf": [
{
- "type": "number"
+ "type": "integer"
},
{
"type": "null"
@@@ -38268,42 -38765,21 +38418,40 @@@
}
],
"default": null,
- "title": "Renews At"
+ "title": "Git Repo Root"
+ }
+ },
+ "required": [
+ "cwd"
+ ],
+ "title": "SessionWorkspaceMoveResult",
+ "type": "object"
+ },
- "SetupChooseKind": {
++ "SetupBeat": {
+ "enum": [
- "question",
- "accent",
++ "name",
+ "theme",
+ "layout",
+ "connectors",
+ "plugins",
+ "tour",
- "fork",
- "machine_use"
++ "build"
+ ],
- "title": "SetupChooseKind",
++ "title": "SetupBeat",
+ "type": "string"
+ },
- "SetupChooseOption": {
++ "SetupBeatRequestParams": {
+ "additionalProperties": false,
++ "description": "``card`` is the beat's data (``agent/onboarding_flow.py::BEATS``): name, theme, connectors and\nplugins have their own shape; layout, tour and build carry ``options``. ``tool_call_id`` is the\nsetup_beat call the card belongs to: only that transcript row draws it.",
+ "properties": {
- "id": {
- "title": "Id",
++ "session_id": {
++ "title": "Session Id",
+ "type": "string"
},
- "label": {
- "title": "Label",
- "type": "string"
- "renews_display": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Renews Display"
++ "beat": {
++ "$ref": "#/components/schemas/SetupBeat"
},
- "detail": {
- "subscription_remaining_display": {
++ "question": {
"anyOf": [
{
"type": "string"
@@@ -38313,96 -38789,190 +38461,203 @@@
}
],
"default": null,
- "title": "Detail"
- "title": "Subscription Remaining Display"
++ "title": "Question"
+ },
- "topup_remaining_display": {
++ "tool_call_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
- "title": "Topup Remaining Display"
++ "title": "Tool Call Id"
+ },
- "total_spendable_display": {
++ "card": {
+ "anyOf": [
+ {
- "type": "string"
++ "$ref": "#/components/schemas/SetupNameCard"
+ },
+ {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Total Spendable Display"
- },
- "has_topup": {
- "anyOf": [
- {
- "type": "boolean"
++ "$ref": "#/components/schemas/SetupThemeCard"
+ },
+ {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Has Topup"
- },
- "plan_bar": {
- "anyOf": [
- {
- "$ref": "#/components/schemas/UsageBar"
++ "$ref": "#/components/schemas/SetupOptionsCard"
+ },
+ {
- "type": "null"
- }
- ],
- "default": null
- },
- "topup_bar": {
- "anyOf": [
- {
- "$ref": "#/components/schemas/UsageBar"
++ "$ref": "#/components/schemas/SetupConnectorsCard"
+ },
+ {
- "type": "null"
++ "$ref": "#/components/schemas/SetupPluginsCard"
+ }
+ ],
- "default": null
- }
- },
- "required": [
- "available"
- ],
- "title": "UsageModel",
- "type": "object"
- },
- "ValueResult": {
- "additionalProperties": false,
- "description": "The answer to any one-string prompt (sudo, secret, vault prompts, desktop bridges):\n``''`` means skipped / declined.",
- "properties": {
- "value": {
- "title": "Value",
- "type": "string"
++ "title": "Card"
}
},
"required": [
- "id",
- "label"
- "value"
++ "session_id",
++ "beat",
++ "card"
],
- "title": "SetupChooseOption",
- "title": "ValueResult",
++ "title": "SetupBeatRequestParams",
"type": "object"
},
- "SetupChooseRequestParams": {
- "VaultAddParams": {
++ "SetupBeatResult": {
"additionalProperties": false,
- "description": "``secret`` goes straight into the encrypted store; the result carries only the new id.",
++ "description": "``answer`` holds the shown beat's picks; ids must be one of the card's options (the backend\nrejects any other answer). ``said`` is composer text typed while the name card waited: the name.\n``wrote_instead``: the user sent a message instead of answering; the backend ends the turn and the\nclient sends that message as the next one. A response with none of these, or none within 300 s,\ncloses the card unanswered.",
"properties": {
- "session_id": {
- "title": "Session Id",
- "type": "string"
- },
- "kind": {
- "$ref": "#/components/schemas/SetupChooseKind"
- },
- "question": {
- "title": "Question",
- "type": "string"
- },
- "options": {
- "profile": {
++ "answer": {
"anyOf": [
{
- "items": {
- "$ref": "#/components/schemas/SetupChooseOption"
- },
- "type": "array"
- "type": "string"
++ "$ref": "#/components/schemas/SetupNameAnswer"
+ },
+ {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Profile"
- },
- "kind": {
- "anyOf": [
++ "$ref": "#/components/schemas/SetupThemeAnswer"
++ },
+ {
- "$ref": "#/components/schemas/VaultKind"
++ "$ref": "#/components/schemas/SetupLayoutAnswer"
+ },
+ {
- "type": "null"
- }
- ],
- "default": null
- },
- "label": {
- "anyOf": [
++ "$ref": "#/components/schemas/SetupConnectorsAnswer"
++ },
+ {
- "type": "string"
++ "$ref": "#/components/schemas/SetupPluginsAnswer"
++ },
++ {
++ "$ref": "#/components/schemas/SetupTourAnswer"
++ },
++ {
++ "$ref": "#/components/schemas/SetupBuildAnswer"
},
{
"type": "null"
}
],
"default": null,
- "title": "Options"
- },
- "multi_select": {
- "default": false,
- "title": "Multi Select",
- "type": "boolean"
- "title": "Label"
++ "title": "Answer"
},
- "preselected": {
- "origin": {
++ "said": {
"anyOf": [
{
- "items": {
- "type": "string"
- },
- "type": "array"
+ "type": "string"
},
{
"type": "null"
}
],
"default": null,
- "title": "Preselected"
- "title": "Origin"
++ "title": "Said"
+ },
- "secret": {
++ "wrote_instead": {
++ "default": false,
++ "title": "Wrote Instead",
++ "type": "boolean"
+ }
+ },
- "required": [
- "session_id",
- "kind",
- "question"
- ],
- "title": "SetupChooseRequestParams",
++ "title": "SetupBeatResult",
+ "type": "object"
+ },
- "SetupChooseResult": {
++ "SetupBuildAnswer": {
+ "additionalProperties": false,
+ "properties": {
- "picked": {
++ "build": {
++ "title": "Build",
++ "type": "string"
++ },
++ "label": {
"anyOf": [
{
- "additionalProperties": true,
- "type": "object"
+ "type": "string"
},
- {
- "items": {
- "type": "string"
- },
- "type": "array"
- },
{
"type": "null"
}
],
"default": null,
- "title": "Picked"
- "title": "Secret"
++ "title": "Label"
+ }
+ },
- "title": "VaultAddParams",
++ "required": [
++ "build"
++ ],
++ "title": "SetupBuildAnswer",
+ "type": "object"
+ },
- "VaultAddResult": {
++ "SetupConnectorsAnswer": {
+ "additionalProperties": false,
+ "properties": {
- "id": {
- "title": "Id",
++ "connected": {
++ "items": {
++ "type": "string"
++ },
++ "title": "Connected",
++ "type": "array"
+ },
- "label": {
++ "newly_connected": {
++ "items": {
++ "type": "string"
++ },
++ "title": "Newly Connected",
++ "type": "array"
++ }
++ },
++ "required": [
++ "connected"
++ ],
++ "title": "SetupConnectorsAnswer",
++ "type": "object"
++ },
++ "SetupConnectorsCard": {
++ "additionalProperties": false,
++ "properties": {
++ "suggested": {
++ "items": {
++ "type": "string"
++ },
++ "title": "Suggested",
++ "type": "array"
++ }
++ },
++ "required": [
++ "suggested"
++ ],
++ "title": "SetupConnectorsCard",
++ "type": "object"
++ },
++ "SetupLayoutAnswer": {
++ "additionalProperties": false,
++ "properties": {
++ "layout": {
++ "title": "Layout",
+ "type": "string"
+ }
+ },
+ "required": [
- "id"
++ "layout"
+ ],
- "title": "VaultAddResult",
++ "title": "SetupLayoutAnswer",
+ "type": "object"
+ },
- "VaultCodeRequestParams": {
++ "SetupNameAnswer": {
+ "additionalProperties": false,
+ "properties": {
- "session_id": {
- "title": "Session Id",
++ "name": {
++ "title": "Name",
+ "type": "string"
- },
- "site": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Site"
- },
- "hint": {
++ }
++ },
++ "required": [
++ "name"
++ ],
++ "title": "SetupNameAnswer",
++ "type": "object"
++ },
++ "SetupNameCard": {
++ "additionalProperties": false,
++ "properties": {
++ "suggested": {
"anyOf": [
{
"type": "string"
@@@ -38418,9 -38982,32 +38667,59 @@@
}
],
"default": null,
- "title": "Label"
- "title": "Hint"
++ "title": "Suggested"
+ }
+ },
- "required": [
- "session_id"
- ],
- "title": "VaultCodeRequestParams",
++ "title": "SetupNameCard",
+ "type": "object"
+ },
- "VaultItem": {
++ "SetupOption": {
+ "additionalProperties": false,
- "description": "Metadata-only view (``VaultItemMeta.to_dict`` + ``backend``); never a secret.",
+ "properties": {
+ "id": {
+ "title": "Id",
+ "type": "string"
},
- "said": {
- "kind": {
- "title": "Kind",
- "type": "string"
- },
+ "label": {
+ "title": "Label",
+ "type": "string"
++ }
++ },
++ "required": [
++ "id",
++ "label"
++ ],
++ "title": "SetupOption",
++ "type": "object"
++ },
++ "SetupOptionsCard": {
++ "additionalProperties": false,
++ "properties": {
++ "options": {
++ "items": {
++ "$ref": "#/components/schemas/SetupOption"
++ },
++ "title": "Options",
++ "type": "array"
++ }
++ },
++ "required": [
++ "options"
++ ],
++ "title": "SetupOptionsCard",
++ "type": "object"
++ },
++ "SetupPluginsAnswer": {
++ "additionalProperties": false,
++ "properties": {
++ "installed": {
++ "items": {
++ "type": "string"
++ },
++ "title": "Installed",
++ "type": "array"
+ },
- "origin": {
++ "label": {
"anyOf": [
{
"type": "string"
@@@ -38430,46 -39017,14 +38729,66 @@@
}
],
"default": null,
- "title": "Said"
- "title": "Origin"
++ "title": "Label"
+ }
+ },
- "title": "SetupChooseResult",
++ "required": [
++ "installed"
++ ],
++ "title": "SetupPluginsAnswer",
++ "type": "object"
++ },
++ "SetupPluginsCard": {
++ "additionalProperties": false,
++ "properties": {
++ "plugins": {
++ "items": {
++ "type": "string"
++ },
++ "title": "Plugins",
++ "type": "array"
++ }
++ },
++ "required": [
++ "plugins"
++ ],
++ "title": "SetupPluginsCard",
+ "type": "object"
+ },
+ "SetupReadyPayload": {
+ "additionalProperties": true,
+ "description": "``hermes_cli/free_tier_bootstrap.py::SetupRecord.as_payload``.",
+ "properties": {
+ "provider_configured": {
+ "title": "Provider Configured",
+ "type": "boolean"
},
- "created_at": {
+ "inference_provider": {
+ "title": "Inference Provider",
+ "type": "string"
+ },
+ "free_tier_account": {
+ "title": "Free Tier Account",
+ "type": "boolean"
+ },
+ "free_tier_route": {
+ "title": "Free Tier Route",
+ "type": "boolean"
+ },
+ "has_identity": {
+ "title": "Has Identity",
+ "type": "boolean"
+ },
+ "other_providers": {
+ "title": "Other Providers",
+ "type": "boolean"
+ },
+ "error": {
"default": "",
- "title": "Created At",
+ "title": "Error",
"type": "string"
},
- "identifier": {
+ "error_code": {
"anyOf": [
{
"type": "string"
@@@ -38786,32 -39557,137 +39105,103 @@@
}
],
"default": null,
- "title": "Output Summary"
+ "title": "Retry After"
}
},
- "title": "VerificationEvidenceRow",
+ "title": "SetupStatusResult",
"type": "object"
},
- "VerificationStatusInfo": {
++ "SetupThemeAnswer": {
+ "additionalProperties": false,
- "description": "``verification_status()``: ``disabled`` / ``not_applicable`` / ``unverified`` / ``stale`` or the\nlatest event's own status; ``root`` and friends only once a workspace was identified.",
+ "properties": {
- "status": {
- "title": "Status",
- "type": "string"
- },
- "evidence": {
- "anyOf": [
- {
- "$ref": "#/components/schemas/VerificationEvidenceRow"
- },
- {
- "type": "null"
- }
- ],
- "default": null
- },
- "root": {
++ "accent": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
- "title": "Root"
++ "title": "Accent"
+ },
- "session_id": {
++ "mode": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
- "title": "Session Id"
- },
- "changed_paths": {
- "anyOf": [
- {
- "items": {
- "type": "string"
- },
- "type": "array"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Changed Paths"
++ "title": "Mode"
++ }
++ },
++ "title": "SetupThemeAnswer",
++ "type": "object"
++ },
++ "SetupThemeCard": {
++ "additionalProperties": false,
++ "properties": {
++ "picker": {
++ "title": "Picker",
++ "type": "string"
+ }
+ },
+ "required": [
- "status"
++ "picker"
+ ],
- "title": "VerificationStatusInfo",
++ "title": "SetupThemeCard",
+ "type": "object"
+ },
- "VerificationStatusParams": {
++ "SetupTourAnswer": {
+ "additionalProperties": false,
+ "properties": {
- "profile": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Profile"
- },
- "session_id": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Session Id"
- },
- "session_key": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Session Key"
++ "tour": {
++ "title": "Tour",
++ "type": "string"
+ },
- "cwd": {
++ "label": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
- "title": "Cwd"
++ "title": "Label"
+ }
+ },
- "title": "VerificationStatusParams",
++ "required": [
++ "tour"
++ ],
++ "title": "SetupTourAnswer",
+ "type": "object"
+ },
- "VerificationStatusResult": {
+ "SharedMetricsConsentResult": {
"additionalProperties": false,
+ "description": "The focused profile's ``telemetry.shared_metrics`` opt-ins. ``send`` is never true while\n``enabled`` is false; ``decided`` = either key is written in config.yaml (the shipped defaults\nare not an answer) and it is not a ``reask``: an \"off\" from before the type-ahead fix, offered\nonce more with the reason.",
"properties": {
- "verification": {
- "$ref": "#/components/schemas/VerificationStatusInfo"
+ "enabled": {
+ "title": "Enabled",
+ "type": "boolean"
+ },
+ "send": {
+ "title": "Send",
+ "type": "boolean"
+ },
+ "decided": {
+ "title": "Decided",
+ "type": "boolean"
+ },
+ "reask": {
+ "default": false,
+ "title": "Reask",
+ "type": "boolean"
}
},
"required": [
@@@ -40078,6405 -40419,382 +40468,6529 @@@
}
],
"default": null,
- "title": "Profile"
+ "title": "Notice"
+ },
+ "display": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Display"
+ },
+ "name": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Name"
+ },
+ "status": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Status"
+ }
+ },
+ "title": "SlashExecResult",
+ "type": "object"
+ },
+ "SpawnTreeEntry": {
+ "additionalProperties": true,
+ "description": "Index row (``server._append_spawn_tree_index``) or a legacy file scan.",
+ "properties": {
+ "path": {
+ "title": "Path",
+ "type": "string"
+ },
+ "session_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Session Id"
+ },
+ "started_at": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Started At"
+ },
+ "finished_at": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Finished At"
+ },
+ "label": {
+ "default": "",
+ "title": "Label",
+ "type": "string"
+ },
+ "count": {
+ "default": 0,
+ "title": "Count",
+ "type": "integer"
+ }
+ },
+ "required": [
+ "path"
+ ],
+ "title": "SpawnTreeEntry",
+ "type": "object"
+ },
+ "SpawnTreeListParams": {
+ "additionalProperties": false,
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "session_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Session Id"
+ },
+ "cross_session": {
+ "default": false,
+ "title": "Cross Session",
+ "type": "boolean"
+ },
+ "limit": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Limit"
+ }
+ },
+ "title": "SpawnTreeListParams",
+ "type": "object"
+ },
+ "SpawnTreeListResult": {
+ "additionalProperties": false,
+ "properties": {
+ "entries": {
+ "items": {
+ "$ref": "#/components/schemas/SpawnTreeEntry"
+ },
+ "title": "Entries",
+ "type": "array"
+ }
+ },
+ "required": [
+ "entries"
+ ],
+ "title": "SpawnTreeListResult",
+ "type": "object"
+ },
+ "SpawnTreeLoadParams": {
+ "additionalProperties": false,
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "path": {
+ "title": "Path",
+ "type": "string"
+ }
+ },
+ "required": [
+ "path"
+ ],
+ "title": "SpawnTreeLoadParams",
+ "type": "object"
+ },
+ "SpawnTreeLoadResult": {
+ "additionalProperties": true,
+ "description": "The snapshot file as written by ``spawn_tree.save`` (open: the file is the contract).",
+ "properties": {
+ "session_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Session Id"
+ },
+ "started_at": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Started At"
+ },
+ "finished_at": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Finished At"
+ },
+ "label": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Label"
+ },
+ "subagents": {
+ "items": {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ "title": "Subagents",
+ "type": "array"
+ }
+ },
+ "title": "SpawnTreeLoadResult",
+ "type": "object"
+ },
+ "SpawnTreeSaveParams": {
+ "additionalProperties": false,
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "subagents": {
+ "items": {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ "title": "Subagents",
+ "type": "array"
+ },
+ "session_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Session Id"
+ },
+ "started_at": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Started At"
+ },
+ "finished_at": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Finished At"
+ },
+ "label": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Label"
+ }
+ },
+ "required": [
+ "subagents"
+ ],
+ "title": "SpawnTreeSaveParams",
+ "type": "object"
+ },
+ "SpawnTreeSaveResult": {
+ "additionalProperties": false,
+ "properties": {
+ "path": {
+ "title": "Path",
+ "type": "string"
+ },
+ "session_id": {
+ "title": "Session Id",
+ "type": "string"
+ }
+ },
+ "required": [
+ "path",
+ "session_id"
+ ],
+ "title": "SpawnTreeSaveResult",
+ "type": "object"
+ },
- "StartChatArgs": {
- "additionalProperties": false,
- "description": "The ``start_chat`` tool's arguments (``tools/start_chat_tool.py``).",
- "properties": {
- "message": {
- "title": "Message",
- "type": "string"
- },
- "title": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Title"
- },
- "profile": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Profile"
- }
- },
- "required": [
- "message"
- ],
- "title": "StartChatArgs",
- "type": "object"
- },
- "StartChatStatus": {
- "enum": [
- "started",
- "rejected"
- ],
- "title": "StartChatStatus",
- "type": "string"
- },
+ "StatusUpdatePayload": {
+ "additionalProperties": false,
+ "description": "``server._status_update`` and the direct emitters (goal / loop / heartbeat / process).",
+ "properties": {
+ "kind": {
+ "title": "Kind",
+ "type": "string"
+ },
+ "text": {
+ "title": "Text",
+ "type": "string"
+ }
+ },
+ "required": [
+ "kind",
+ "text"
+ ],
+ "title": "StatusUpdatePayload",
+ "type": "object"
+ },
+ "SteerStatus": {
+ "enum": [
+ "queued",
+ "rejected"
+ ],
+ "title": "SteerStatus",
+ "type": "string"
+ },
+ "StreamDeltaPayload": {
+ "additionalProperties": false,
+ "description": "``prompt_turn._invoke_agent._stream`` (message.delta: ``text`` + optional ``rendered``),\n``agent_callbacks._agent_cbs`` (reasoning.delta / thinking.delta), ``tool_progress._progress_reasoning``\n(reasoning.available). ``verbose`` rides only when the session's verbose reasoning mode is on.",
+ "properties": {
+ "text": {
+ "title": "Text",
+ "type": "string"
+ },
+ "rendered": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Rendered"
+ },
+ "verbose": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Verbose"
+ }
+ },
+ "required": [
+ "text"
+ ],
+ "title": "StreamDeltaPayload",
+ "type": "object"
+ },
+ "SubagentEventPayload": {
+ "additionalProperties": false,
+ "description": "``tool_progress._progress_subagent`` \u2014 every ``subagent.*`` frame; identity fields are optional\nbecause older emitters omit them and the TUI spawn tree falls back to flat rendering.",
+ "properties": {
+ "goal": {
+ "title": "Goal",
+ "type": "string"
+ },
+ "task_count": {
+ "title": "Task Count",
+ "type": "integer"
+ },
+ "task_index": {
+ "title": "Task Index",
+ "type": "integer"
+ },
+ "subagent_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Subagent Id"
+ },
+ "parent_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Parent Id"
+ },
+ "child_session_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Child Session Id"
+ },
+ "delegation_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Delegation Id"
+ },
+ "depth": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Depth"
+ },
+ "model": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Model"
+ },
+ "tool_count": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Tool Count"
+ },
+ "toolsets": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Toolsets"
+ },
+ "input_tokens": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Input Tokens"
+ },
+ "output_tokens": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Output Tokens"
+ },
+ "reasoning_tokens": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Reasoning Tokens"
+ },
+ "api_calls": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Api Calls"
+ },
+ "files_read": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Files Read"
+ },
+ "files_written": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Files Written"
+ },
+ "output_tail": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/SubagentOutputTailEntry"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Output Tail"
+ },
+ "tool_name": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Tool Name"
+ },
+ "text": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Text"
+ },
+ "status": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/SubagentStatus"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ },
+ "summary": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Summary"
+ },
+ "duration_seconds": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Duration Seconds"
+ },
+ "tool_preview": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Tool Preview"
+ }
+ },
+ "required": [
+ "goal",
+ "task_count",
+ "task_index"
+ ],
+ "title": "SubagentEventPayload",
+ "type": "object"
+ },
+ "SubagentIdParams": {
+ "additionalProperties": false,
+ "properties": {
+ "session_id": {
+ "title": "Session Id",
+ "type": "string"
+ },
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "subagent_id": {
+ "title": "Subagent Id",
+ "type": "string"
+ }
+ },
+ "required": [
+ "session_id",
+ "subagent_id"
+ ],
+ "title": "SubagentIdParams",
+ "type": "object"
+ },
+ "SubagentInterruptResult": {
+ "additionalProperties": false,
+ "properties": {
+ "found": {
+ "title": "Found",
+ "type": "boolean"
+ },
+ "subagent_id": {
+ "title": "Subagent Id",
+ "type": "string"
+ }
+ },
+ "required": [
+ "found",
+ "subagent_id"
+ ],
+ "title": "SubagentInterruptResult",
+ "type": "object"
+ },
+ "SubagentListResult": {
+ "additionalProperties": false,
+ "description": "``delegations``: recently failed async delegation tasks for the session (durable store), newest first.",
+ "properties": {
+ "subagents": {
+ "items": {
+ "$ref": "#/components/schemas/SubagentSnapshot"
+ },
+ "title": "Subagents",
+ "type": "array"
+ },
+ "delegations": {
+ "items": {
+ "$ref": "#/components/schemas/FailedDelegation"
+ },
+ "title": "Delegations",
+ "type": "array"
+ }
+ },
+ "title": "SubagentListResult",
+ "type": "object"
+ },
+ "SubagentOutputTailEntry": {
+ "additionalProperties": false,
+ "description": "``tools/delegate_tool_results.py::_extract_output_tail`` row.",
+ "properties": {
+ "tool": {
+ "title": "Tool",
+ "type": "string"
+ },
+ "preview": {
+ "title": "Preview",
+ "type": "string"
+ },
+ "is_error": {
+ "title": "Is Error",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "tool",
+ "preview",
+ "is_error"
+ ],
+ "title": "SubagentOutputTailEntry",
+ "type": "object"
+ },
+ "SubagentSnapshot": {
+ "additionalProperties": false,
+ "description": "``methods_subagents._SUBAGENT_SNAPSHOT_FIELDS`` projection of one live child record.",
+ "properties": {
+ "subagent_id": {
+ "title": "Subagent Id",
+ "type": "string"
+ },
+ "parent_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Parent Id"
+ },
+ "depth": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Depth"
+ },
+ "goal": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Goal"
+ },
+ "delegation_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Delegation Id"
+ },
+ "model": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Model"
+ },
+ "started_at": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Started At"
+ },
+ "status": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/SubagentStatus"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ },
+ "tool_count": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Tool Count"
+ },
+ "last_tool": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Last Tool"
+ },
+ "accepting_steer": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Accepting Steer"
+ }
+ },
+ "required": [
+ "subagent_id"
+ ],
+ "title": "SubagentSnapshot",
+ "type": "object"
+ },
+ "SubagentStatus": {
+ "description": "Lifecycle of one delegated child (``tools/delegate_tool_child_run.py``); ``failed`` /\n``error`` / ``timeout`` / ``interrupted`` / ``completed`` are terminal.",
+ "enum": [
+ "queued",
+ "running",
+ "completed",
+ "failed",
+ "error",
+ "timeout",
+ "interrupted"
+ ],
+ "title": "SubagentStatus",
+ "type": "string"
+ },
+ "SubagentSteerParams": {
+ "additionalProperties": false,
+ "properties": {
+ "session_id": {
+ "title": "Session Id",
+ "type": "string"
+ },
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "subagent_id": {
+ "title": "Subagent Id",
+ "type": "string"
+ },
+ "text": {
+ "title": "Text",
+ "type": "string"
+ }
+ },
+ "required": [
+ "session_id",
+ "subagent_id",
+ "text"
+ ],
+ "title": "SubagentSteerParams",
+ "type": "object"
+ },
+ "SubagentSteerResult": {
+ "additionalProperties": false,
+ "description": "``queued`` is not ``delivered``: a child past its final tool batch surfaces ``missed_steer``.",
+ "properties": {
+ "status": {
+ "$ref": "#/components/schemas/SteerStatus"
+ },
+ "subagent_id": {
+ "title": "Subagent Id",
+ "type": "string"
+ },
+ "text": {
+ "title": "Text",
+ "type": "string"
+ }
+ },
+ "required": [
+ "status",
+ "subagent_id",
+ "text"
+ ],
+ "title": "SubagentSteerResult",
+ "type": "object"
+ },
+ "SubagentTailResult": {
+ "additionalProperties": false,
+ "description": "``available`` is false while the child has no live transcript yet (or it was cleaned up).",
+ "properties": {
+ "subagent_id": {
+ "title": "Subagent Id",
+ "type": "string"
+ },
+ "available": {
+ "default": false,
+ "title": "Available",
+ "type": "boolean"
+ },
+ "text": {
+ "default": "",
+ "title": "Text",
+ "type": "string"
+ },
+ "truncated": {
+ "default": false,
+ "title": "Truncated",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "subagent_id"
+ ],
+ "title": "SubagentTailResult",
+ "type": "object"
+ },
+ "SubscriptionChangeEffect": {
+ "enum": [
+ "charge_now",
+ "scheduled",
+ "no_op",
+ "blocked"
+ ],
+ "title": "SubscriptionChangeEffect",
+ "type": "string"
+ },
+ "SubscriptionChangeParams": {
+ "additionalProperties": false,
+ "description": "Either a target tier (downgrade / same-price change) or ``cancel`` (period-end cancellation).",
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "subscription_type_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Subscription Type Id"
+ },
+ "cancel": {
+ "default": false,
+ "title": "Cancel",
+ "type": "boolean"
+ }
+ },
+ "title": "SubscriptionChangeParams",
+ "type": "object"
+ },
+ "SubscriptionContext": {
+ "enum": [
+ "personal",
+ "team"
+ ],
+ "title": "SubscriptionContext",
+ "type": "string"
+ },
+ "SubscriptionPreviewParams": {
+ "additionalProperties": false,
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "subscription_type_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Subscription Type Id"
+ }
+ },
+ "title": "SubscriptionPreviewParams",
+ "type": "object"
+ },
+ "SubscriptionPreviewResult": {
+ "additionalProperties": false,
+ "description": "``_serialize_subscription_preview`` on success; ``effect`` drives the confirm copy.",
+ "properties": {
+ "ok": {
+ "title": "Ok",
+ "type": "boolean"
+ },
+ "error": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Error"
+ },
+ "message": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Message"
+ },
+ "portal_url": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Portal Url"
+ },
+ "retry_after": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Retry After"
+ },
+ "payload": {
+ "anyOf": [
+ {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Payload"
+ },
+ "actor": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Actor"
+ },
+ "code": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Code"
+ },
+ "recovery": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Recovery"
+ },
+ "effect": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/SubscriptionChangeEffect"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ },
+ "reason": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Reason"
+ },
+ "current_tier_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Current Tier Id"
+ },
+ "current_tier_name": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Current Tier Name"
+ },
+ "target_tier_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Target Tier Id"
+ },
+ "target_tier_name": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Target Tier Name"
+ },
+ "monthly_credits_delta": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Monthly Credits Delta"
+ },
+ "amount_due_now_cents": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Amount Due Now Cents"
+ },
+ "effective_at": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Effective At"
+ }
+ },
+ "required": [
+ "ok"
+ ],
+ "title": "SubscriptionPreviewResult",
+ "type": "object"
+ },
+ "SubscriptionStateResult": {
+ "additionalProperties": false,
+ "description": "``_serialize_subscription_state``; the view's fallback emits only ``ok / logged_in / error``.",
+ "properties": {
+ "ok": {
+ "title": "Ok",
+ "type": "boolean"
+ },
+ "logged_in": {
+ "title": "Logged In",
+ "type": "boolean"
+ },
+ "is_admin": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Is Admin"
+ },
+ "can_change_plan": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Can Change Plan"
+ },
+ "org_name": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Org Name"
+ },
+ "org_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Org Id"
+ },
+ "role": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Role"
+ },
+ "context": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/SubscriptionContext"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ },
+ "current": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/CurrentSubscription"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ },
+ "tiers": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/SubscriptionTierOption"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Tiers"
+ },
+ "portal_url": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Portal Url"
+ },
+ "error": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Error"
+ },
+ "usage": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/UsageModel"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ }
+ },
+ "required": [
+ "ok",
+ "logged_in"
+ ],
+ "title": "SubscriptionStateResult",
+ "type": "object"
+ },
+ "SubscriptionTierOption": {
+ "additionalProperties": false,
+ "properties": {
+ "tier_id": {
+ "title": "Tier Id",
+ "type": "string"
+ },
+ "name": {
+ "title": "Name",
+ "type": "string"
+ },
+ "tier_order": {
+ "title": "Tier Order",
+ "type": "integer"
+ },
+ "dollars_per_month_display": {
+ "title": "Dollars Per Month Display",
+ "type": "string"
+ },
+ "monthly_credits": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Monthly Credits"
+ },
+ "is_current": {
+ "title": "Is Current",
+ "type": "boolean"
+ },
+ "is_enabled": {
+ "title": "Is Enabled",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "tier_id",
+ "name",
+ "tier_order",
+ "dollars_per_month_display",
+ "is_current",
+ "is_enabled"
+ ],
+ "title": "SubscriptionTierOption",
+ "type": "object"
+ },
+ "SubscriptionUpgradeParams": {
+ "additionalProperties": false,
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "subscription_type_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Subscription Type Id"
+ },
+ "idempotency_key": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Idempotency Key"
+ }
+ },
+ "title": "SubscriptionUpgradeParams",
+ "type": "object"
+ },
+ "SubscriptionUpgradeResult": {
+ "additionalProperties": false,
+ "description": "The money route: ``status`` separates a completed upgrade from an SCA / decline that must\nfinish in the portal at ``recovery_url``; ``idempotency_key`` is echoed (also on error) so a\nretry reuses it.",
+ "properties": {
+ "ok": {
+ "title": "Ok",
+ "type": "boolean"
+ },
+ "error": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Error"
+ },
+ "message": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Message"
+ },
+ "portal_url": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Portal Url"
+ },
+ "retry_after": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Retry After"
+ },
+ "payload": {
+ "anyOf": [
+ {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Payload"
+ },
+ "actor": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Actor"
+ },
+ "code": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Code"
+ },
+ "recovery": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Recovery"
+ },
+ "status": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Status"
+ },
+ "target_tier_name": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Target Tier Name"
+ },
+ "recovery_url": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Recovery Url"
+ },
+ "reason": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Reason"
+ },
+ "idempotency_key": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Idempotency Key"
+ }
+ },
+ "required": [
+ "ok"
+ ],
+ "title": "SubscriptionUpgradeResult",
+ "type": "object"
+ },
+ "SudoRequestParams": {
+ "additionalProperties": false,
+ "description": "Original command, redacted server-side before any password-injection rewrite.",
+ "properties": {
+ "session_id": {
+ "title": "Session Id",
+ "type": "string"
+ },
+ "command": {
+ "default": "",
+ "title": "Command",
+ "type": "string"
+ }
+ },
+ "required": [
+ "session_id"
+ ],
+ "title": "SudoRequestParams",
+ "type": "object"
+ },
+ "SystemBatteryParams": {
+ "additionalProperties": false,
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ }
+ },
+ "title": "SystemBatteryParams",
+ "type": "object"
+ },
+ "SystemBatteryResult": {
+ "additionalProperties": false,
+ "properties": {
+ "available": {
+ "title": "Available",
+ "type": "boolean"
+ },
+ "percent": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Percent"
+ },
+ "plugged": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Plugged"
+ },
+ "category": {
+ "$ref": "#/components/schemas/BatteryCategory",
+ "default": "dim"
+ }
+ },
+ "required": [
+ "available"
+ ],
+ "title": "SystemBatteryResult",
+ "type": "object"
+ },
+ "TaskIdResult": {
+ "additionalProperties": false,
+ "description": "The side agent runs detached; its answer lands on the parent session as an event carrying\nthis ``task_id``.",
+ "properties": {
+ "task_id": {
+ "title": "Task Id",
+ "type": "string"
+ }
+ },
+ "required": [
+ "task_id"
+ ],
+ "title": "TaskIdResult",
+ "type": "object"
+ },
+ "TerminalClosePayload": {
+ "additionalProperties": false,
+ "properties": {
+ "process_id": {
+ "title": "Process Id",
+ "type": "string"
+ }
+ },
+ "required": [
+ "process_id"
+ ],
+ "title": "TerminalClosePayload",
+ "type": "object"
+ },
+ "TerminalOutputPayload": {
+ "additionalProperties": false,
+ "description": "``session_notifications`` process_registry.on_output.",
+ "properties": {
+ "process_id": {
+ "title": "Process Id",
+ "type": "string"
+ },
+ "chunk": {
+ "title": "Chunk",
+ "type": "string"
+ }
+ },
+ "required": [
+ "process_id",
+ "chunk"
+ ],
+ "title": "TerminalOutputPayload",
+ "type": "object"
+ },
+ "TerminalResizeParams": {
+ "additionalProperties": false,
+ "properties": {
+ "session_id": {
+ "title": "Session Id",
+ "type": "string"
+ },
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "cols": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Cols"
+ }
+ },
+ "required": [
+ "session_id"
+ ],
+ "title": "TerminalResizeParams",
+ "type": "object"
+ },
+ "TerminalResizeResult": {
+ "additionalProperties": false,
+ "properties": {
+ "cols": {
+ "title": "Cols",
+ "type": "integer"
+ }
+ },
+ "required": [
+ "cols"
+ ],
+ "title": "TerminalResizeResult",
+ "type": "object"
+ },
++ "ThemeApplyRequestParams": {
++ "additionalProperties": false,
++ "description": "``tools/set_theme_tool.py`` values; accent is a swatch id, ``theme`` or ``#rrggbb``.",
++ "properties": {
++ "session_id": {
++ "title": "Session Id",
++ "type": "string"
++ },
++ "accent": {
++ "anyOf": [
++ {
++ "type": "string"
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "default": null,
++ "title": "Accent"
++ },
++ "mode": {
++ "anyOf": [
++ {
++ "$ref": "#/components/schemas/ThemeMode"
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "default": null
++ },
++ "layout": {
++ "anyOf": [
++ {
++ "type": "string"
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "default": null,
++ "title": "Layout"
++ }
++ },
++ "required": [
++ "session_id"
++ ],
++ "title": "ThemeApplyRequestParams",
++ "type": "object"
++ },
++ "ThemeMode": {
++ "enum": [
++ "light",
++ "dark",
++ "system"
++ ],
++ "title": "ThemeMode",
++ "type": "string"
++ },
++ "ThemePickRequestParams": {
++ "additionalProperties": false,
++ "properties": {
++ "session_id": {
++ "title": "Session Id",
++ "type": "string"
++ },
++ "picker": {
++ "$ref": "#/components/schemas/ThemePicker"
++ }
++ },
++ "required": [
++ "session_id",
++ "picker"
++ ],
++ "title": "ThemePickRequestParams",
++ "type": "object"
++ },
++ "ThemePickResult": {
++ "additionalProperties": false,
++ "description": "``picked`` once the user chose (already applied); ``cancelled`` when the card was dismissed. A response\nwith neither is a cancel.",
++ "properties": {
++ "picked": {
++ "anyOf": [
++ {
++ "$ref": "#/components/schemas/ThemeValues"
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "default": null
++ },
++ "said": {
++ "anyOf": [
++ {
++ "type": "string"
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "default": null,
++ "title": "Said"
++ },
++ "cancelled": {
++ "anyOf": [
++ {
++ "type": "boolean"
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "default": null,
++ "title": "Cancelled"
++ }
++ },
++ "title": "ThemePickResult",
++ "type": "object"
++ },
++ "ThemePicker": {
++ "enum": [
++ "accent",
++ "layout"
++ ],
++ "title": "ThemePicker",
++ "type": "string"
++ },
++ "ThemeValues": {
++ "additionalProperties": false,
++ "description": "What the renderer applied. ``accent`` is a swatch id, ``custom:#rrggbb``, or null for the theme's own.",
++ "properties": {
++ "accent": {
++ "anyOf": [
++ {
++ "type": "string"
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "default": null,
++ "title": "Accent"
++ },
++ "mode": {
++ "anyOf": [
++ {
++ "$ref": "#/components/schemas/ThemeMode"
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "default": null
++ },
++ "layout": {
++ "anyOf": [
++ {
++ "type": "string"
++ },
++ {
++ "type": "null"
++ }
++ ],
++ "default": null,
++ "title": "Layout"
++ }
++ },
++ "title": "ThemeValues",
++ "type": "object"
++ },
+ "TipShowPayload": {
+ "additionalProperties": false,
+ "description": "``tools/tip_tool.py``.",
+ "properties": {
+ "selector": {
+ "title": "Selector",
+ "type": "string"
+ },
+ "text": {
+ "title": "Text",
+ "type": "string"
+ },
+ "title": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Title"
+ },
+ "side": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Side"
+ }
+ },
+ "required": [
+ "selector",
+ "text"
+ ],
+ "title": "TipShowPayload",
+ "type": "object"
+ },
+ "TodoState": {
+ "additionalProperties": false,
+ "description": "``tool_progress._normalize_todo_state``: the authoritative todo snapshot.",
+ "properties": {
+ "todos": {
+ "items": {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ "title": "Todos",
+ "type": "array"
+ },
+ "revision": {
+ "title": "Revision",
+ "type": "integer"
+ }
+ },
+ "required": [
+ "todos",
+ "revision"
+ ],
+ "title": "TodoState",
+ "type": "object"
+ },
+ "TodoUpdatedPayload": {
+ "additionalProperties": false,
+ "description": "``tool_progress._normalize_todo_state`` \u2014 full task snapshot.",
+ "properties": {
+ "todos": {
+ "items": {},
+ "title": "Todos",
+ "type": "array"
+ },
+ "revision": {
+ "title": "Revision",
+ "type": "integer"
+ }
+ },
+ "required": [
+ "todos",
+ "revision"
+ ],
+ "title": "TodoUpdatedPayload",
+ "type": "object"
+ },
+ "ToolCompletePayload": {
+ "additionalProperties": false,
+ "description": "``tool_progress._on_tool_complete``; ``todos``/``revision`` merged in for the todo tools.",
+ "properties": {
+ "tool_id": {
+ "title": "Tool Id",
+ "type": "string"
+ },
+ "name": {
+ "title": "Name",
+ "type": "string"
+ },
+ "args": {
+ "anyOf": [
+ {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Args"
+ },
+ "duration_s": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Duration S"
+ },
+ "result": {
+ "default": null,
+ "title": "Result"
+ },
+ "summary": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Summary"
+ },
+ "result_text": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Result Text"
+ },
+ "inline_diff": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Inline Diff"
+ },
+ "todos": {
+ "anyOf": [
+ {
+ "items": {},
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Todos"
+ },
+ "revision": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Revision"
+ },
+ "labels": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/ToolLabel"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Labels"
+ }
+ },
+ "required": [
+ "tool_id",
+ "name"
+ ],
+ "title": "ToolCompletePayload",
+ "type": "object"
+ },
+ "ToolGeneratingPayload": {
+ "additionalProperties": false,
+ "description": "``agent_callbacks`` tool_gen_callback.",
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string"
+ }
+ },
+ "required": [
+ "name"
+ ],
+ "title": "ToolGeneratingPayload",
+ "type": "object"
+ },
+ "ToolLabel": {
+ "additionalProperties": false,
+ "description": "``tools.tool_labels.ToolLabel`` \u2014 what one call executed through the tool_search bridge is,\nin words. Clients render ``text`` (or ``app``/``action`` in their own columns) and never parse\nthe tool name themselves.",
+ "properties": {
+ "kind": {
+ "$ref": "#/components/schemas/ToolLabelKind"
+ },
+ "app": {
+ "title": "App",
+ "type": "string"
+ },
+ "action": {
+ "title": "Action",
+ "type": "string"
+ },
+ "emoji": {
+ "title": "Emoji",
+ "type": "string"
+ },
+ "text": {
+ "title": "Text",
+ "type": "string"
+ },
+ "name": {
+ "title": "Name",
+ "type": "string"
+ },
+ "preview": {
+ "default": "",
+ "title": "Preview",
+ "type": "string"
+ }
+ },
+ "required": [
+ "kind",
+ "app",
+ "action",
+ "emoji",
+ "text",
+ "name"
+ ],
+ "title": "ToolLabel",
+ "type": "object"
+ },
+ "ToolLabelKind": {
+ "description": "Which surface one inner call of a bridged ``tool_call`` runs on.",
+ "enum": [
+ "connector",
+ "mcp",
+ "tool"
+ ],
+ "title": "ToolLabelKind",
+ "type": "string"
+ },
+ "ToolOutputRiskPayload": {
+ "additionalProperties": false,
+ "description": "``tool_progress._progress_output_risk``.",
+ "properties": {
+ "tool_id": {
+ "title": "Tool Id",
+ "type": "string"
+ },
+ "name": {
+ "title": "Name",
+ "type": "string"
+ },
+ "risk": {
+ "title": "Risk",
+ "type": "string"
+ },
+ "findings": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Findings",
+ "type": "array"
+ },
+ "redacted": {
+ "title": "Redacted",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "tool_id",
+ "name",
+ "risk",
+ "findings",
+ "redacted"
+ ],
+ "title": "ToolOutputRiskPayload",
+ "type": "object"
+ },
+ "ToolShowRow": {
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string"
+ },
+ "description": {
+ "title": "Description",
+ "type": "string"
+ }
+ },
+ "required": [
+ "name",
+ "description"
+ ],
+ "title": "ToolShowRow",
+ "type": "object"
+ },
+ "ToolShowSection": {
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string"
+ },
+ "tools": {
+ "items": {
+ "$ref": "#/components/schemas/ToolShowRow"
+ },
+ "title": "Tools",
+ "type": "array"
+ }
+ },
+ "required": [
+ "name",
+ "tools"
+ ],
+ "title": "ToolShowSection",
+ "type": "object"
+ },
+ "ToolStartPayload": {
+ "additionalProperties": false,
+ "description": "``tool_progress._on_tool_start`` (+ ``agent_callbacks._mirror_subagent_to_child`` rows with\n``preview`` and empty ``args``). ``todos``/``revision`` are NOT set by the emitter; kept optional\nbecause tool.start rows may pass through connector redaction unchanged.",
+ "properties": {
+ "tool_id": {
+ "title": "Tool Id",
+ "type": "string"
+ },
+ "name": {
+ "title": "Name",
+ "type": "string"
+ },
+ "context": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Context"
+ },
+ "args": {
+ "anyOf": [
+ {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Args"
+ },
+ "args_text": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Args Text"
+ },
+ "preview": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Preview"
+ },
+ "labels": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/ToolLabel"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Labels"
+ }
+ },
+ "required": [
+ "tool_id",
+ "name"
+ ],
+ "title": "ToolStartPayload",
+ "type": "object"
+ },
+ "ToolsAction": {
+ "enum": [
+ "enable",
+ "disable"
+ ],
+ "title": "ToolsAction",
+ "type": "string"
+ },
+ "ToolsChange": {
+ "additionalProperties": false,
+ "properties": {
+ "type": {
+ "const": "tools",
+ "title": "Type",
+ "type": "string"
+ },
+ "connector": {
+ "title": "Connector",
+ "type": "string"
+ },
+ "disabled_tools": {
+ "items": {
+ "type": "string"
+ },
+ "maxItems": 2000,
+ "title": "Disabled Tools",
+ "type": "array"
+ }
+ },
+ "required": [
+ "type",
+ "connector",
+ "disabled_tools"
+ ],
+ "title": "ToolsChange",
+ "type": "object"
+ },
+ "ToolsConfigureParams": {
+ "additionalProperties": false,
+ "description": "``names`` are toolset keys or ``server:tool`` MCP targets; with ``session_id`` the live session's\nprofile is authoritative and its agent is rebuilt.",
+ "properties": {
+ "action": {
+ "$ref": "#/components/schemas/ToolsAction"
+ },
+ "names": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Names",
+ "type": "array"
+ },
+ "session_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Session Id"
+ },
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ }
+ },
+ "required": [
+ "action",
+ "names"
+ ],
+ "title": "ToolsConfigureParams",
+ "type": "object"
+ },
+ "ToolsConfigureResult": {
+ "additionalProperties": false,
+ "properties": {
+ "changed": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Changed",
+ "type": "array"
+ },
+ "enabled_toolsets": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Enabled Toolsets",
+ "type": "array"
+ },
+ "info": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/SessionLiveInfo"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ },
+ "missing_servers": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Missing Servers",
+ "type": "array"
+ },
+ "reset": {
+ "title": "Reset",
+ "type": "boolean"
+ },
+ "unknown": {
+ "items": {
+ "type": "string"
+ },
+ "title": "Unknown",
+ "type": "array"
+ }
+ },
+ "required": [
+ "changed",
+ "enabled_toolsets",
+ "missing_servers",
+ "reset",
+ "unknown"
+ ],
+ "title": "ToolsConfigureResult",
+ "type": "object"
+ },
+ "ToolsShowResult": {
+ "additionalProperties": false,
+ "properties": {
+ "sections": {
+ "items": {
+ "$ref": "#/components/schemas/ToolShowSection"
+ },
+ "title": "Sections",
+ "type": "array"
+ },
+ "total": {
+ "title": "Total",
+ "type": "integer"
+ }
+ },
+ "required": [
+ "sections",
+ "total"
+ ],
+ "title": "ToolsShowResult",
+ "type": "object"
+ },
+ "ToolsetEntry": {
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string"
+ },
+ "enabled": {
+ "default": true,
+ "title": "Enabled",
+ "type": "boolean"
+ },
+ "label": {
+ "default": "",
+ "title": "Label",
+ "type": "string"
+ },
+ "description": {
+ "default": "",
+ "title": "Description",
+ "type": "string"
+ },
+ "tool_count": {
+ "default": 0,
+ "title": "Tool Count",
+ "type": "integer"
+ }
+ },
+ "required": [
+ "name"
+ ],
+ "title": "ToolsetEntry",
+ "type": "object"
+ },
+ "ToolsetRow": {
+ "additionalProperties": false,
+ "description": "One row of ``methods_tools._toolset_rows``; ``tools`` only when the caller asked for them\n(``tools.list``).",
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string"
+ },
+ "description": {
+ "title": "Description",
+ "type": "string"
+ },
+ "tool_count": {
+ "title": "Tool Count",
+ "type": "integer"
+ },
+ "enabled": {
+ "title": "Enabled",
+ "type": "boolean"
+ },
+ "tools": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Tools"
+ }
+ },
+ "required": [
+ "name",
+ "description",
+ "tool_count",
+ "enabled"
+ ],
+ "title": "ToolsetRow",
+ "type": "object"
+ },
+ "ToolsetsListResult": {
+ "additionalProperties": false,
+ "properties": {
+ "toolsets": {
+ "items": {
+ "$ref": "#/components/schemas/ToolsetRow"
+ },
+ "title": "Toolsets",
+ "type": "array"
+ }
+ },
+ "required": [
+ "toolsets"
+ ],
+ "title": "ToolsetsListResult",
+ "type": "object"
+ },
+ "TourPreset": {
+ "description": "Which built-in tour ``start`` without steps runs.",
+ "enum": [
+ "quick",
+ "full"
+ ],
+ "title": "TourPreset",
+ "type": "string"
+ },
+ "TourRequestParams": {
+ "additionalProperties": false,
+ "description": "``tools/tour_tool.py`` field set.",
+ "properties": {
+ "session_id": {
+ "title": "Session Id",
+ "type": "string"
+ },
+ "action": {
+ "title": "Action",
+ "type": "string"
+ },
+ "surface": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Surface"
+ },
+ "selector": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Selector"
+ },
+ "title": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Title"
+ },
+ "text": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Text"
+ },
+ "side": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Side"
+ },
+ "steps": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/TourStep"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Steps"
+ },
+ "step_index": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Step Index"
+ },
+ "preset": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/TourPreset"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ }
+ },
+ "required": [
+ "session_id",
+ "action"
+ ],
+ "title": "TourRequestParams",
+ "type": "object"
+ },
+ "TourStep": {
+ "additionalProperties": true,
+ "properties": {
+ "selector": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Selector"
+ },
+ "title": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Title"
+ },
+ "text": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Text"
+ },
+ "side": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Side"
+ }
+ },
+ "title": "TourStep",
+ "type": "object"
+ },
+ "TranscriptMessage": {
+ "additionalProperties": true,
+ "description": "One transcript row as the gateway PROJECTS it for renderers (``session_history._project_history``):\n``text``, display-only ``timestamp`` / ``display_kind`` / ``display_metadata``, the durable ``row_id``\nrewind targets, and for tool rows raw ``content``, ``tool_call_id``, ``name``, ``context`` and ``args``.\nAssistant detail sidecars (``reasoning``, \u2026) ride as extra keys.",
+ "properties": {
+ "role": {
+ "title": "Role",
+ "type": "string"
+ },
+ "text": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Text"
+ },
+ "content": {
+ "anyOf": [
+ {},
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Content"
+ },
+ "tool_call_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Tool Call Id"
+ },
+ "timestamp": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Timestamp"
+ },
+ "row_id": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Row Id"
+ },
+ "display_kind": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Display Kind"
+ },
+ "display_metadata": {
+ "anyOf": [
+ {},
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Display Metadata"
+ },
+ "name": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Name"
+ },
+ "context": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Context"
+ },
+ "args": {
+ "anyOf": [
+ {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Args"
+ },
+ "labels": {
+ "anyOf": [
+ {
+ "items": {
+ "$ref": "#/components/schemas/ToolLabel"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Labels"
+ },
+ "reasoning": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Reasoning"
+ }
+ },
+ "required": [
+ "role"
+ ],
+ "title": "TranscriptMessage",
+ "type": "object"
+ },
+ "TurnStatus": {
+ "description": "``prompt_turn._result_status``.",
+ "enum": [
+ "complete",
+ "error",
+ "interrupted"
+ ],
+ "title": "TurnStatus",
+ "type": "string"
+ },
+ "UiMetaConflict": {
+ "additionalProperties": false,
+ "properties": {
+ "expected": {
+ "default": null,
+ "title": "Expected"
+ },
+ "actual": {
+ "default": 0,
+ "title": "Actual",
+ "type": "integer"
+ }
+ },
+ "title": "UiMetaConflict",
+ "type": "object"
+ },
+ "UndoIntent": {
+ "enum": [
+ "retry",
+ "undo"
+ ],
+ "title": "UndoIntent",
+ "type": "string"
+ },
+ "Usage": {
+ "additionalProperties": true,
+ "description": "``tui_gateway/server.py::_get_usage`` + ``agent/context_breakdown.py::context_usage_fields``.",
+ "properties": {
+ "model": {
+ "default": "",
+ "title": "Model",
+ "type": "string"
+ },
+ "input": {
+ "default": 0,
+ "title": "Input",
+ "type": "integer"
+ },
+ "output": {
+ "default": 0,
+ "title": "Output",
+ "type": "integer"
+ },
+ "reasoning": {
+ "default": 0,
+ "title": "Reasoning",
+ "type": "integer"
+ },
+ "prompt": {
+ "default": 0,
+ "title": "Prompt",
+ "type": "integer"
+ },
+ "completion": {
+ "default": 0,
+ "title": "Completion",
+ "type": "integer"
+ },
+ "total": {
+ "default": 0,
+ "title": "Total",
+ "type": "integer"
+ },
+ "calls": {
+ "default": 0,
+ "title": "Calls",
+ "type": "integer"
+ },
+ "compressions": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Compressions"
+ },
+ "context_used": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Context Used"
+ },
+ "context_max": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Context Max"
+ },
+ "context_percent": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Context Percent"
+ },
+ "context_source": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Context Source"
+ },
+ "context_estimated": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Context Estimated"
+ },
+ "cache_hit_pct": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Cache Hit Pct"
+ },
+ "cache_read": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Cache Read"
+ },
+ "cache_write": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Cache Write"
+ },
+ "avg_latency_s": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Avg Latency S"
+ },
+ "avg_tps": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Avg Tps"
+ },
+ "active_subagents": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Active Subagents"
+ },
+ "dev_credits_spent_micros": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Dev Credits Spent Micros"
+ },
+ "cost_usd": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Cost Usd"
+ },
+ "cost_status": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Cost Status"
+ }
+ },
+ "title": "Usage",
+ "type": "object"
+ },
+ "UsageBar": {
+ "additionalProperties": false,
+ "description": "``_serialize_usage_bar``: one bar, magnitudes pre-formatted; ``pct_used`` only for ``plan``.",
+ "properties": {
+ "kind": {
+ "$ref": "#/components/schemas/UsageBarKind"
+ },
+ "remaining_display": {
+ "title": "Remaining Display",
+ "type": "string"
+ },
+ "total_display": {
+ "title": "Total Display",
+ "type": "string"
+ },
+ "spent_display": {
+ "title": "Spent Display",
+ "type": "string"
+ },
+ "pct_used": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Pct Used"
+ },
+ "fill_fraction": {
+ "title": "Fill Fraction",
+ "type": "number"
+ }
+ },
+ "required": [
+ "kind",
+ "remaining_display",
+ "total_display",
+ "spent_display",
+ "fill_fraction"
+ ],
+ "title": "UsageBar",
+ "type": "object"
+ },
+ "UsageBarKind": {
+ "enum": [
+ "plan",
+ "topup"
+ ],
+ "title": "UsageBarKind",
+ "type": "string"
+ },
+ "UsageModel": {
+ "additionalProperties": false,
+ "description": "``_serialize_usage_model`` \u2014 also embedded as ``usage`` in the billing / subscription states,\nwhere the fail-open form is a bare ``{available: false}`` (no ``ok``).",
+ "properties": {
+ "ok": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Ok"
+ },
+ "available": {
+ "title": "Available",
+ "type": "boolean"
+ },
+ "status": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Status"
+ },
+ "plan_name": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Plan Name"
+ },
+ "renews_at": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Renews At"
+ },
+ "renews_display": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Renews Display"
+ },
+ "subscription_remaining_display": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Subscription Remaining Display"
+ },
+ "topup_remaining_display": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Topup Remaining Display"
+ },
+ "total_spendable_display": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Total Spendable Display"
+ },
+ "has_topup": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Has Topup"
+ },
+ "plan_bar": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/UsageBar"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ },
+ "topup_bar": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/UsageBar"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ }
+ },
+ "required": [
+ "available"
+ ],
+ "title": "UsageModel",
+ "type": "object"
+ },
+ "ValueResult": {
+ "additionalProperties": false,
+ "description": "The answer to any one-string prompt (sudo, secret, vault prompts, desktop bridges):\n``''`` means skipped / declined.",
+ "properties": {
+ "value": {
+ "title": "Value",
+ "type": "string"
+ }
+ },
+ "required": [
+ "value"
+ ],
+ "title": "ValueResult",
+ "type": "object"
+ },
+ "VaultAddParams": {
+ "additionalProperties": false,
+ "description": "``secret`` goes straight into the encrypted store; the result carries only the new id.",
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "kind": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/VaultKind"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ },
+ "label": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Label"
+ },
+ "origin": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Origin"
+ },
+ "secret": {
+ "anyOf": [
+ {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Secret"
+ }
+ },
+ "title": "VaultAddParams",
+ "type": "object"
+ },
+ "VaultAddResult": {
+ "additionalProperties": false,
+ "properties": {
+ "id": {
+ "title": "Id",
+ "type": "string"
+ }
+ },
+ "required": [
+ "id"
+ ],
+ "title": "VaultAddResult",
+ "type": "object"
+ },
+ "VaultCodeRequestParams": {
+ "additionalProperties": false,
+ "properties": {
+ "session_id": {
+ "title": "Session Id",
+ "type": "string"
+ },
+ "site": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Site"
+ },
+ "hint": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Hint"
+ }
+ },
+ "required": [
+ "session_id"
+ ],
+ "title": "VaultCodeRequestParams",
+ "type": "object"
+ },
+ "VaultItem": {
+ "additionalProperties": false,
+ "description": "Metadata-only view (``VaultItemMeta.to_dict`` + ``backend``); never a secret.",
+ "properties": {
+ "id": {
+ "title": "Id",
+ "type": "string"
+ },
+ "kind": {
+ "title": "Kind",
+ "type": "string"
+ },
+ "label": {
+ "title": "Label",
+ "type": "string"
+ },
+ "origin": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Origin"
+ },
+ "created_at": {
+ "default": "",
+ "title": "Created At",
+ "type": "string"
+ },
+ "identifier": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Identifier"
+ },
+ "identifier_type": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Identifier Type"
+ },
+ "has_otp": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Has Otp"
+ },
+ "backend": {
+ "title": "Backend",
+ "type": "string"
+ }
+ },
+ "required": [
+ "id",
+ "kind",
+ "label",
+ "backend"
+ ],
+ "title": "VaultItem",
+ "type": "object"
+ },
+ "VaultKind": {
+ "enum": [
+ "login",
+ "payment",
+ "address"
+ ],
+ "title": "VaultKind",
+ "type": "string"
+ },
+ "VaultListResult": {
+ "additionalProperties": false,
+ "properties": {
+ "items": {
+ "items": {
+ "$ref": "#/components/schemas/VaultItem"
+ },
+ "title": "Items",
+ "type": "array"
+ }
+ },
+ "title": "VaultListResult",
+ "type": "object"
+ },
+ "VaultLockParams": {
+ "additionalProperties": false,
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "name": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Name"
+ }
+ },
+ "title": "VaultLockParams",
+ "type": "object"
+ },
+ "VaultLockResult": {
+ "additionalProperties": false,
+ "properties": {
+ "locked": {
+ "default": true,
+ "title": "Locked",
+ "type": "boolean"
+ }
+ },
+ "title": "VaultLockResult",
+ "type": "object"
+ },
+ "VaultRemoveParams": {
+ "additionalProperties": false,
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Id"
+ }
+ },
+ "title": "VaultRemoveParams",
+ "type": "object"
+ },
+ "VaultRemoveResult": {
+ "additionalProperties": false,
+ "properties": {
+ "removed": {
+ "title": "Removed",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "removed"
+ ],
+ "title": "VaultRemoveResult",
+ "type": "object"
+ },
+ "VaultSaveLoginRequestParams": {
+ "additionalProperties": false,
+ "properties": {
+ "session_id": {
+ "title": "Session Id",
+ "type": "string"
+ },
+ "origin": {
+ "title": "Origin",
+ "type": "string"
+ },
+ "site": {
+ "title": "Site",
+ "type": "string"
+ }
+ },
+ "required": [
+ "session_id",
+ "origin",
+ "site"
+ ],
+ "title": "VaultSaveLoginRequestParams",
+ "type": "object"
+ },
+ "VaultSource": {
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string"
+ },
+ "display_name": {
+ "title": "Display Name",
+ "type": "string"
+ },
+ "enabled": {
+ "title": "Enabled",
+ "type": "boolean"
+ },
+ "needs_unlock": {
+ "title": "Needs Unlock",
+ "type": "boolean"
+ },
+ "unlocked": {
+ "title": "Unlocked",
+ "type": "boolean"
+ },
+ "installed": {
+ "title": "Installed",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "name",
+ "display_name",
+ "enabled",
+ "needs_unlock",
+ "unlocked",
+ "installed"
+ ],
+ "title": "VaultSource",
+ "type": "object"
+ },
+ "VaultSourceSetParams": {
+ "additionalProperties": false,
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "name": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Name"
+ },
+ "enabled": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Enabled"
+ }
+ },
+ "title": "VaultSourceSetParams",
+ "type": "object"
+ },
+ "VaultSourceSetResult": {
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string"
+ },
+ "enabled": {
+ "title": "Enabled",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "name",
+ "enabled"
+ ],
+ "title": "VaultSourceSetResult",
+ "type": "object"
+ },
+ "VaultSourcesResult": {
+ "additionalProperties": false,
+ "properties": {
+ "sources": {
+ "items": {
+ "$ref": "#/components/schemas/VaultSource"
+ },
+ "title": "Sources",
+ "type": "array"
+ }
+ },
+ "title": "VaultSourcesResult",
+ "type": "object"
+ },
+ "VaultUnlockParams": {
+ "additionalProperties": false,
+ "description": "The master password is consumed by the manager CLI and never stored or logged.",
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "name": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Name"
+ },
+ "password": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Password"
+ }
+ },
+ "title": "VaultUnlockParams",
+ "type": "object"
+ },
+ "VaultUnlockRequestParams": {
+ "additionalProperties": false,
+ "properties": {
+ "session_id": {
+ "title": "Session Id",
+ "type": "string"
+ },
+ "backend": {
+ "title": "Backend",
+ "type": "string"
+ },
+ "display_name": {
+ "title": "Display Name",
+ "type": "string"
+ }
+ },
+ "required": [
+ "session_id",
+ "backend",
+ "display_name"
+ ],
+ "title": "VaultUnlockRequestParams",
+ "type": "object"
+ },
+ "VaultUnlockResult": {
+ "additionalProperties": false,
+ "properties": {
+ "name": {
+ "title": "Name",
+ "type": "string"
+ },
+ "unlocked": {
+ "default": true,
+ "title": "Unlocked",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "name"
+ ],
+ "title": "VaultUnlockResult",
+ "type": "object"
+ },
+ "VerificationEvidenceRow": {
+ "additionalProperties": true,
+ "description": "One ``verification_events`` row (``agent/verification_evidence.py``).",
+ "properties": {
+ "id": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Id"
+ },
+ "created_at": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Created At"
+ },
+ "session_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Session Id"
+ },
+ "cwd": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Cwd"
+ },
+ "root": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Root"
+ },
+ "command": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Command"
+ },
+ "canonical_command": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Canonical Command"
+ },
+ "kind": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Kind"
+ },
+ "scope": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Scope"
+ },
+ "status": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Status"
+ },
+ "exit_code": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Exit Code"
+ },
+ "output_summary": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Output Summary"
+ }
+ },
+ "title": "VerificationEvidenceRow",
+ "type": "object"
+ },
+ "VerificationStatusInfo": {
+ "additionalProperties": false,
+ "description": "``verification_status()``: ``disabled`` / ``not_applicable`` / ``unverified`` / ``stale`` or the\nlatest event's own status; ``root`` and friends only once a workspace was identified.",
+ "properties": {
+ "status": {
+ "title": "Status",
+ "type": "string"
+ },
+ "evidence": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/VerificationEvidenceRow"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
+ },
+ "root": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Root"
+ },
+ "session_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Session Id"
+ },
+ "changed_paths": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Changed Paths"
+ }
+ },
+ "required": [
+ "status"
+ ],
+ "title": "VerificationStatusInfo",
+ "type": "object"
+ },
+ "VerificationStatusParams": {
+ "additionalProperties": false,
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "session_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Session Id"
+ },
+ "session_key": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Session Key"
+ },
+ "cwd": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Cwd"
+ }
+ },
+ "title": "VerificationStatusParams",
+ "type": "object"
+ },
+ "VerificationStatusResult": {
+ "additionalProperties": false,
+ "properties": {
+ "verification": {
+ "$ref": "#/components/schemas/VerificationStatusInfo"
+ }
+ },
+ "required": [
+ "verification"
+ ],
+ "title": "VerificationStatusResult",
+ "type": "object"
+ },
+ "VoicePartialPayload": {
+ "additionalProperties": false,
+ "description": "``methods_voice`` voice.record ``on_partial`` \u2014 live STT text so far (``stt.streaming``).",
+ "properties": {
+ "text": {
+ "title": "Text",
+ "type": "string"
+ }
+ },
+ "required": [
+ "text"
+ ],
+ "title": "VoicePartialPayload",
+ "type": "object"
+ },
+ "VoiceRecordAction": {
+ "enum": [
+ "start",
+ "stop"
+ ],
+ "title": "VoiceRecordAction",
+ "type": "string"
+ },
+ "VoiceRecordParams": {
+ "additionalProperties": false,
+ "properties": {
+ "action": {
+ "$ref": "#/components/schemas/VoiceRecordAction",
+ "default": "start"
+ },
+ "session_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Session Id"
+ },
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ }
+ },
+ "title": "VoiceRecordParams",
+ "type": "object"
+ },
+ "VoiceRecordResult": {
+ "additionalProperties": false,
+ "properties": {
+ "status": {
+ "$ref": "#/components/schemas/VoiceRecordStatus"
+ },
+ "reason": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Reason"
+ }
+ },
+ "required": [
+ "status"
+ ],
+ "title": "VoiceRecordResult",
+ "type": "object"
+ },
+ "VoiceRecordStatus": {
+ "enum": [
+ "recording",
+ "stopped",
+ "busy"
+ ],
+ "title": "VoiceRecordStatus",
+ "type": "string"
+ },
+ "VoiceStatusPayload": {
+ "additionalProperties": false,
+ "description": "``methods_voice._vr_on_status``; states come from the recorder (idle / listening / transcribing \u2026).",
+ "properties": {
+ "state": {
+ "title": "State",
+ "type": "string"
+ }
+ },
+ "required": [
+ "state"
+ ],
+ "title": "VoiceStatusPayload",
+ "type": "object"
+ },
+ "VoiceToggleAction": {
+ "enum": [
+ "status",
+ "on",
+ "off",
+ "tts"
+ ],
+ "title": "VoiceToggleAction",
+ "type": "string"
+ },
+ "VoiceToggleParams": {
+ "additionalProperties": false,
+ "properties": {
+ "action": {
+ "$ref": "#/components/schemas/VoiceToggleAction",
+ "default": "status"
+ },
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ }
+ },
+ "title": "VoiceToggleParams",
+ "type": "object"
+ },
+ "VoiceToggleResult": {
+ "additionalProperties": false,
+ "description": "``methods_voice.py::_voice_status_payload`` (+ the requirements probe on ``status``, the spoken\nstop hint on ``on``).",
+ "properties": {
+ "enabled": {
+ "title": "Enabled",
+ "type": "boolean"
+ },
+ "record_key": {
+ "title": "Record Key",
+ "type": "string"
+ },
+ "tts": {
+ "title": "Tts",
+ "type": "boolean"
+ },
+ "stop_hint": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Stop Hint"
+ },
+ "available": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Available"
+ },
+ "audio_available": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Audio Available"
+ },
+ "stt_available": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Stt Available"
+ },
+ "details": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Details"
+ }
+ },
+ "required": [
+ "enabled",
+ "record_key",
+ "tts"
+ ],
+ "title": "VoiceToggleResult",
+ "type": "object"
+ },
+ "VoiceTranscriptPayload": {
+ "additionalProperties": false,
+ "description": "``methods_voice._vr_transcript`` / ``_deliver_fd_transcript`` / typed stop phrase in methods_prompt.",
+ "properties": {
+ "text": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Text"
+ },
+ "stop_phrase": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Stop Phrase"
+ },
+ "typed": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Typed"
+ },
+ "no_speech_limit": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "No Speech Limit"
+ }
+ },
+ "title": "VoiceTranscriptPayload",
+ "type": "object"
+ },
+ "VoiceTtsParams": {
+ "additionalProperties": false,
+ "properties": {
+ "text": {
+ "title": "Text",
+ "type": "string"
+ },
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ }
+ },
+ "required": [
+ "text"
+ ],
+ "title": "VoiceTtsParams",
+ "type": "object"
+ },
+ "VoiceTtsResult": {
+ "additionalProperties": false,
+ "properties": {
+ "status": {
+ "title": "Status",
+ "type": "string"
+ }
+ },
+ "required": [
+ "status"
+ ],
+ "title": "VoiceTtsResult",
+ "type": "object"
+ },
+ "WaitBarrierTarget": {
+ "additionalProperties": false,
+ "properties": {
+ "type": {
+ "enum": [
+ "session",
+ "pid"
+ ],
+ "title": "Type",
+ "type": "string"
+ },
+ "target": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "integer"
+ }
+ ],
+ "title": "Target"
+ },
+ "reason": {
+ "default": "",
+ "title": "Reason",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "target"
+ ],
+ "title": "WaitBarrierTarget",
+ "type": "object"
+ },
+ "WaitBarrierUntil": {
+ "additionalProperties": false,
+ "properties": {
+ "type": {
+ "const": "until",
+ "title": "Type",
+ "type": "string"
+ },
+ "until_at": {
+ "title": "Until At",
+ "type": "number"
+ },
+ "reason": {
+ "default": "",
+ "title": "Reason",
+ "type": "string"
+ }
+ },
+ "required": [
+ "type",
+ "until_at"
+ ],
+ "title": "WaitBarrierUntil",
+ "type": "object"
+ },
+ "WakeControlParams": {
+ "additionalProperties": false,
+ "properties": {
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ }
+ },
+ "title": "WakeControlParams",
+ "type": "object"
+ },
+ "WakeDetectedPayload": {
+ "additionalProperties": false,
+ "description": "``methods_voice`` wake detector ``_on_detect``.",
+ "properties": {
+ "phrase": {
+ "title": "Phrase",
+ "type": "string"
+ },
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ },
+ "start_new_session": {
+ "title": "Start New Session",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "phrase",
+ "start_new_session"
+ ],
+ "title": "WakeDetectedPayload",
+ "type": "object"
+ },
+ "WakeFeedParams": {
+ "additionalProperties": false,
+ "description": "``pcm`` (or the ``pcm_b64`` alias): base64 int16 mono little-endian, 16 kHz only.",
+ "properties": {
+ "pcm": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Pcm"
+ },
+ "pcm_b64": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Pcm B64"
+ },
+ "sample_rate": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Sample Rate"
+ },
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ }
+ },
+ "title": "WakeFeedParams",
+ "type": "object"
+ },
+ "WakeFeedResult": {
+ "additionalProperties": false,
+ "properties": {
+ "reason": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Reason"
+ },
+ "fed": {
+ "title": "Fed",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "fed"
+ ],
+ "title": "WakeFeedResult",
+ "type": "object"
+ },
+ "WakeInputDevice": {
+ "additionalProperties": true,
+ "description": "``tools/wake_word.py::_describe_input_device`` \u2014 PortAudio diagnostics for the configured mic.",
+ "properties": {
+ "selector": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Selector"
+ },
+ "name": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Name"
+ },
+ "error": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Error"
+ },
+ "max_input_channels": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Max Input Channels"
+ },
+ "default_samplerate": {
+ "anyOf": [
+ {
+ "type": "number"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Default Samplerate"
+ },
+ "hostapi_index": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Hostapi Index"
+ },
+ "hostapi": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Hostapi"
+ }
+ },
+ "title": "WakeInputDevice",
+ "type": "object"
+ },
+ "WakePauseResult": {
+ "additionalProperties": false,
+ "properties": {
+ "reason": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Reason"
+ },
+ "paused": {
+ "title": "Paused",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "paused"
+ ],
+ "title": "WakePauseResult",
+ "type": "object"
+ },
+ "WakeResumeResult": {
+ "additionalProperties": false,
+ "properties": {
+ "reason": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Reason"
+ },
+ "resumed": {
+ "title": "Resumed",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "resumed"
+ ],
+ "title": "WakeResumeResult",
+ "type": "object"
+ },
+ "WakeStartParams": {
+ "additionalProperties": false,
+ "description": "``surface`` names the caller (\"tui\" | \"gui\"); ``persist`` is the explicit gesture that also\nflips ``wake_word.enabled`` on; ``client_capture`` asks for PCM streamed via wake.feed.",
+ "properties": {
+ "surface": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Surface"
+ },
+ "persist": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Persist"
+ },
+ "client_capture": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Client Capture"
+ },
+ "session_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Session Id"
+ },
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ }
+ },
+ "title": "WakeStartParams",
+ "type": "object"
+ },
+ "WakeStartResult": {
+ "additionalProperties": false,
+ "description": "``started: false`` carries ``reason`` (unavailable / disabled / disabled_for_surface / owned);\n``sample_rate`` / ``frame_length`` describe the PCM frames the armed detector expects.",
+ "properties": {
+ "started": {
+ "title": "Started",
+ "type": "boolean"
+ },
+ "reason": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Reason"
+ },
+ "hint": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Hint"
+ },
+ "phrase": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Phrase"
+ },
+ "provider": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Provider"
+ },
+ "owner_surface": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Owner Surface"
+ },
+ "enabled_persisted": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Enabled Persisted"
+ },
+ "capture": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Capture"
+ },
+ "sample_rate": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Sample Rate"
+ },
+ "frame_length": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Frame Length"
+ }
+ },
+ "required": [
+ "started"
+ ],
+ "title": "WakeStartResult",
+ "type": "object"
+ },
+ "WakeStatusParams": {
+ "additionalProperties": false,
+ "properties": {
+ "surface": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Surface"
+ },
+ "client_capture": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Client Capture"
+ },
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ }
+ },
+ "title": "WakeStatusParams",
+ "type": "object"
+ },
+ "WakeStatusResult": {
+ "additionalProperties": false,
+ "description": "``enabled`` is config truth; ``listening`` is this caller's armed detector; ``audio_silent``\nmeans armed but deaf (see ``hint``).",
+ "properties": {
+ "listening": {
+ "title": "Listening",
+ "type": "boolean"
+ },
+ "owned_by_caller": {
+ "title": "Owned By Caller",
+ "type": "boolean"
+ },
+ "owner_surface": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Owner Surface"
+ },
+ "phrase": {
+ "title": "Phrase",
+ "type": "string"
+ },
+ "provider": {
+ "title": "Provider",
+ "type": "string"
+ },
+ "configured_surface": {
+ "title": "Configured Surface",
+ "type": "string"
+ },
+ "input_device": {
+ "$ref": "#/components/schemas/WakeInputDevice"
+ },
+ "available": {
+ "title": "Available",
+ "type": "boolean"
+ },
+ "hint": {
+ "title": "Hint",
+ "type": "string"
+ },
+ "enabled": {
+ "title": "Enabled",
+ "type": "boolean"
+ },
+ "audio_silent": {
+ "title": "Audio Silent",
+ "type": "boolean"
+ },
+ "capture": {
+ "title": "Capture",
+ "type": "string"
+ },
+ "local_input_available": {
+ "title": "Local Input Available",
+ "type": "boolean"
+ },
+ "sample_rate": {
+ "title": "Sample Rate",
+ "type": "integer"
+ },
+ "frame_length": {
+ "title": "Frame Length",
+ "type": "integer"
+ }
+ },
+ "required": [
+ "listening",
+ "owned_by_caller",
+ "phrase",
+ "provider",
+ "configured_surface",
+ "input_device",
+ "available",
+ "hint",
+ "enabled",
+ "audio_silent",
+ "capture",
+ "local_input_available",
+ "sample_rate",
+ "frame_length"
+ ],
+ "title": "WakeStatusResult",
+ "type": "object"
+ },
+ "WakeStopParams": {
+ "additionalProperties": false,
+ "properties": {
+ "persist": {
+ "anyOf": [
+ {
+ "type": "boolean"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Persist"
+ },
+ "profile": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Profile"
+ }
+ },
+ "title": "WakeStopParams",
+ "type": "object"
+ },
+ "WakeStopResult": {
+ "additionalProperties": false,
+ "properties": {
+ "reason": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Reason"
+ },
+ "stopped": {
+ "title": "Stopped",
+ "type": "boolean"
+ },
+ "disabled_persisted": {
+ "title": "Disabled Persisted",
+ "type": "boolean"
+ }
+ },
+ "required": [
+ "stopped",
+ "disabled_persisted"
+ ],
+ "title": "WakeStopResult",
+ "type": "object"
+ },
+ "WorkerExecution": {
+ "additionalProperties": true,
+ "description": "A ``worker_executions`` row without its adoption digest.",
+ "properties": {
+ "execution_id": {
+ "title": "Execution Id",
+ "type": "string"
+ },
+ "session_id": {
+ "title": "Session Id",
+ "type": "string"
+ },
+ "kind": {
+ "title": "Kind",
+ "type": "string"
+ },
+ "owner_epoch": {
+ "title": "Owner Epoch",
+ "type": "integer"
+ },
+ "generation": {
+ "title": "Generation",
+ "type": "integer"
+ },
+ "status": {
+ "title": "Status",
+ "type": "string"
+ },
+ "last_sequence": {
+ "title": "Last Sequence",
+ "type": "integer"
+ }
+ },
+ "required": [
+ "execution_id",
+ "session_id",
+ "kind",
+ "owner_epoch",
+ "generation",
+ "status",
+ "last_sequence"
+ ],
+ "title": "WorkerExecution",
+ "type": "object"
+ },
+ "WorkerPersistParams": {
+ "additionalProperties": false,
+ "properties": {
+ "profile_id": {
+ "title": "Profile Id",
+ "type": "string"
+ },
+ "session_id": {
+ "title": "Session Id",
+ "type": "string"
+ },
+ "execution_id": {
+ "title": "Execution Id",
+ "type": "string"
+ },
+ "generation": {
+ "title": "Generation",
+ "type": "integer"
+ },
+ "pid": {
+ "title": "Pid",
+ "type": "integer"
+ },
+ "birth": {
+ "title": "Birth",
+ "type": "number"
+ },
+ "secret": {
+ "title": "Secret",
+ "type": "string"
+ },
+ "epoch": {
+ "title": "Epoch",
+ "type": "integer"
+ },
+ "sequence": {
+ "title": "Sequence",
+ "type": "integer"
+ },
+ "operation": {
+ "title": "Operation",
+ "type": "string"
+ },
+ "payload": {
+ "additionalProperties": true,
+ "title": "Payload",
+ "type": "object"
+ }
+ },
+ "required": [
+ "profile_id",
+ "session_id",
+ "execution_id",
+ "generation",
+ "pid",
+ "birth",
+ "secret",
+ "epoch",
+ "sequence",
+ "operation",
+ "payload"
+ ],
+ "title": "WorkerPersistParams",
+ "type": "object"
+ },
+ "WorkerPersistResult": {
+ "additionalProperties": true,
+ "description": "The operation's durable receipt (``message_id`` for an append, delegation results, \u2026).",
+ "properties": {},
+ "title": "WorkerPersistResult",
+ "type": "object"
+ },
+ "WorkerRegisterParams": {
+ "additionalProperties": false,
+ "properties": {
+ "profile_id": {
+ "title": "Profile Id",
+ "type": "string"
+ },
+ "session_id": {
+ "title": "Session Id",
+ "type": "string"
+ },
+ "execution_id": {
+ "title": "Execution Id",
+ "type": "string"
+ },
+ "generation": {
+ "title": "Generation",
+ "type": "integer"
+ },
+ "pid": {
+ "title": "Pid",
+ "type": "integer"
+ },
+ "birth": {
+ "title": "Birth",
+ "type": "number"
+ },
+ "secret": {
+ "title": "Secret",
+ "type": "string"
+ },
+ "kind": {
+ "title": "Kind",
+ "type": "string"
+ }
+ },
+ "required": [
+ "profile_id",
+ "session_id",
+ "execution_id",
+ "generation",
+ "pid",
+ "birth",
+ "secret",
+ "kind"
+ ],
+ "title": "WorkerRegisterParams",
+ "type": "object"
+ },
+ "WorkerScopeParams": {
+ "additionalProperties": false,
+ "description": "The producer claim every worker verb proves (``gateway/session_worker.py::_SCOPE``).",
+ "properties": {
+ "profile_id": {
+ "title": "Profile Id",
+ "type": "string"
+ },
+ "session_id": {
+ "title": "Session Id",
+ "type": "string"
+ },
+ "execution_id": {
+ "title": "Execution Id",
+ "type": "string"
+ },
+ "generation": {
+ "title": "Generation",
+ "type": "integer"
+ },
+ "pid": {
+ "title": "Pid",
+ "type": "integer"
+ },
+ "birth": {
+ "title": "Birth",
+ "type": "number"
+ },
+ "secret": {
+ "title": "Secret",
+ "type": "string"
+ }
+ },
+ "required": [
+ "profile_id",
+ "session_id",
+ "execution_id",
+ "generation",
+ "pid",
+ "birth",
+ "secret"
+ ],
+ "title": "WorkerScopeParams",
+ "type": "object"
+ },
+ "_SessionScoped": {
+ "additionalProperties": false,
+ "description": "Handlers that look a live session up with ``_sessions.get(params.get(\"session_id\"))``: an\nabsent / unknown id falls back to the launch profile's config, so it is never required.",
+ "properties": {
+ "session_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Session Id"
+ }
+ },
+ "title": "_SessionScoped",
+ "type": "object"
+ },
+ "ConnectorErrorReason": {
+ "type": "string",
+ "enum": [
+ "INVALID_PARAMS",
+ "NOT_OWNER",
+ "UNSUPPORTED_RUNTIME",
+ "CONNECTOR_REQUEST_FAILED",
+ "INVALID_CONNECTOR_RESPONSE",
+ "UNKNOWN_TARGET",
+ "LINK_STILL_VALID",
+ "REISSUE_REFUSED",
+ "UNKNOWN_OPERATION",
+ "INVALID_ANSWER",
+ "NEEDS_NOUS_AUTH",
+ "CONNECTOR_NOT_FOUND",
+ "TOOLS_UNAVAILABLE",
+ "CONNECTORS_UNAVAILABLE",
+ "CATALOG_UNAVAILABLE",
+ "ACCOUNTS_UNAVAILABLE",
+ "CONNECTION_NOT_FOUND",
+ "POLICY_UNAVAILABLE",
+ "POLICY_CONFLICT",
+ "FORBIDDEN_SCOPE",
+ "ORG_REQUIRED",
+ "ORG_ACCESS_DENIED",
+ "INVALID_POLICY",
+ "ALIAS_TAKEN"
+ ]
+ }
+ }
+ },
+ "x-canonical-methods": [
+ {
+ "name": "a2a.forward",
+ "summary": "Forward one A2A input into the conversation its identity tuple names.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/A2aForwardParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/A2aForwardResult"
+ }
+ }
+ },
+ {
+ "name": "approval.respond",
+ "summary": "",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalApprovalParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/PromptResponseResult"
+ }
+ }
+ },
+ {
+ "name": "bot_relay.deliver",
+ "summary": "",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalBotDeliverParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalBotDeliverResult"
+ }
+ }
+ },
+ {
+ "name": "clarify.respond",
+ "summary": "Generation-fenced answer to a pending clarify prompt (empty answer = skipped).",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/ClarifyRespondParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/PromptResponseResult"
+ }
+ }
+ },
+ {
+ "name": "config.get",
+ "summary": "",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/ConfigGetParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalConfigGetResult"
+ }
+ }
+ },
+ {
+ "name": "config.set",
+ "summary": "",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalConfigSetParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/ConfigSetResult"
+ }
+ }
+ },
+ {
+ "name": "cron.cancel",
+ "summary": "Cancel a queued cron admission or latch cancellation on a started one.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CronAdmissionParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/CronCancelResult"
+ }
+ }
+ },
+ {
+ "name": "cron.recover",
+ "summary": "Re-observe a firing after a scheduler restart (same request identity).",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CronRunParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/CronStatusResult"
+ }
+ }
+ },
+ {
+ "name": "cron.status",
+ "summary": "Status and, once terminal, the result of one cron admission.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CronAdmissionParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/CronStatusResult"
+ }
+ }
+ },
+ {
+ "name": "cron.submit",
+ "summary": "Admit one cron firing into the owning profile's durable FIFO.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CronRunParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/CronSubmitResult"
+ }
+ }
+ },
+ {
+ "name": "groups.approve",
+ "summary": "",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalRoomApproveParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/GroupsApproveResult"
+ }
+ }
+ },
+ {
+ "name": "groups.attachment.download",
+ "summary": "Read one committed attachment for a live room viewer.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/GroupsAttachmentDownloadParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/RoomAttachmentBytes"
+ }
+ }
+ },
+ {
+ "name": "groups.attachment.upload",
+ "summary": "Store one attachment for a later groups.send manifest (idempotent per upload_id).",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/GroupsAttachmentUploadParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/RoomAttachment"
+ }
+ }
+ },
+ {
+ "name": "groups.create",
+ "summary": "",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalRoomCreateParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/GroupsCreateResult"
+ }
+ }
+ },
+ {
+ "name": "groups.discard",
+ "summary": "Discard one indeterminate room task after explicit user confirmation.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/GroupsDiscardParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/GroupsDiscardResult"
+ }
+ }
+ },
+ {
+ "name": "groups.retry",
+ "summary": "",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalRoomAttemptParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/GroupsRetryResult"
+ }
+ }
+ },
+ {
+ "name": "image.attach_bytes",
+ "summary": "",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/ImageAttachBytesParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalAttachedImageResult"
+ }
+ }
+ },
+ {
+ "name": "kanban.run",
+ "summary": "Native-owner only: admit the dispatcher's current claim on a kanban task.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/KanbanRunParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/KanbanRunResult"
+ }
+ }
+ },
+ {
+ "name": "profiles.list",
+ "summary": "",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalProfilesParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalProfilesResult"
+ }
+ }
+ },
+ {
+ "name": "prompt.cancel",
+ "summary": "Retire a still-queued admission; a started one is unaffected.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/PromptCancelParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/AdmissionStatus"
+ }
+ }
+ },
+ {
+ "name": "prompt.receipt",
+ "summary": "Current receipt of one admission the caller submitted (or controls).",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/PromptReceiptParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/PromptReceiptResult"
+ }
+ }
+ },
+ {
+ "name": "prompt.resolve_unknown",
+ "summary": "Acknowledge a turn lost across an owner restart; the FIFO behind it resumes. Never requeues the lost input.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/PromptResolveUnknownParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/AdmissionStatus"
+ }
+ }
+ },
+ {
+ "name": "prompt.submit",
+ "summary": "",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalSubmitParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/AdmissionStatus"
+ }
+ }
+ },
+ {
+ "name": "runtime.describe",
+ "summary": "Owner identity and the canonical capabilities a client may rely on.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/RuntimeDescribeParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/RuntimeDescribeResult"
+ }
+ }
+ },
+ {
+ "name": "session.automation",
+ "summary": "The classic CLI's /goal, /subgoal, /loop, /heartbeat manager calls (state writes, the goal judge, quality gates), run by the owner on the session's row.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/SessionAutomationParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/SessionAutomationResult"
+ }
+ }
+ },
+ {
+ "name": "session.create",
+ "summary": "",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalCreateParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalSnapshot"
+ }
+ }
+ },
+ {
+ "name": "session.detach",
+ "summary": "Drop this connection's subscription; a stale subscription id answers detached=false. end_reason (snake_case): the viewer is closing the conversation; the last viewer leaving an idle local session ends its row with that reason.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/SessionDetachParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/SessionDetachResult"
+ }
+ }
+ },
+ {
+ "name": "session.events.since",
+ "summary": "",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalEventsParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalEventsResult"
+ }
+ }
+ },
+ {
+ "name": "session.info",
+ "summary": "Frozen launch policy projection of one local session.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalSessionInfoParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalSessionInfo"
+ }
+ }
+ },
+ {
+ "name": "session.interrupt",
+ "summary": "",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalControlParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalSessionHandle"
+ }
+ }
+ },
+ {
+ "name": "session.list",
+ "summary": "",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalListParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalListResult"
+ }
+ }
+ },
+ {
+ "name": "session.mutate",
+ "summary": "Revision-fenced, retry-idempotent session edit (rename, archive, sidebar, branch, delete, rewind, reset, model, reasoning, workspace, compress, import).",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/SessionMutateParams"
}
- },
- "title": "WakeStartParams",
- "type": "object"
- },
- "WakeStartResult": {
- "additionalProperties": false,
- "description": "``started: false`` carries ``reason`` (unavailable / disabled / disabled_for_surface / owned);\n``sample_rate`` / ``frame_length`` describe the PCM frames the armed detector expects.",
- "properties": {
- "started": {
- "title": "Started",
- "type": "boolean"
- },
- "reason": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Reason"
- },
- "hint": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Hint"
- },
- "phrase": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Phrase"
- },
- "provider": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Provider"
- },
- "owner_surface": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Owner Surface"
- },
- "enabled_persisted": {
- "anyOf": [
- {
- "type": "boolean"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Enabled Persisted"
- },
- "capture": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Capture"
- },
- "sample_rate": {
- "anyOf": [
- {
- "type": "integer"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Sample Rate"
- },
- "frame_length": {
- "anyOf": [
- {
- "type": "integer"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Frame Length"
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/SessionMutateResult"
+ }
+ }
+ },
+ {
+ "name": "session.prune",
+ "summary": "Local operator only: the owner deletes the ended sessions `hermes sessions prune` selected, skipping busy sessions and retained reset owners.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/SessionPruneParams"
}
- },
- "required": [
- "started"
- ],
- "title": "WakeStartResult",
- "type": "object"
- },
- "WakeStatusParams": {
- "additionalProperties": false,
- "properties": {
- "surface": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Surface"
- },
- "client_capture": {
- "anyOf": [
- {
- "type": "boolean"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Client Capture"
- },
- "profile": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Profile"
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/SessionPruneResult"
+ }
+ }
+ },
+ {
+ "name": "session.redirect",
+ "summary": "",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalCorrectionParams"
}
- },
- "title": "WakeStatusParams",
- "type": "object"
- },
- "WakeStatusResult": {
- "additionalProperties": false,
- "description": "``enabled`` is config truth; ``listening`` is this caller's armed detector; ``audio_silent``\nmeans armed but deaf (see ``hint``).",
- "properties": {
- "listening": {
- "title": "Listening",
- "type": "boolean"
- },
- "owned_by_caller": {
- "title": "Owned By Caller",
- "type": "boolean"
- },
- "owner_surface": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Owner Surface"
- },
- "phrase": {
- "title": "Phrase",
- "type": "string"
- },
- "provider": {
- "title": "Provider",
- "type": "string"
- },
- "configured_surface": {
- "title": "Configured Surface",
- "type": "string"
- },
- "input_device": {
- "$ref": "#/components/schemas/WakeInputDevice"
- },
- "available": {
- "title": "Available",
- "type": "boolean"
- },
- "hint": {
- "title": "Hint",
- "type": "string"
- },
- "enabled": {
- "title": "Enabled",
- "type": "boolean"
- },
- "audio_silent": {
- "title": "Audio Silent",
- "type": "boolean"
- },
- "capture": {
- "title": "Capture",
- "type": "string"
- },
- "local_input_available": {
- "title": "Local Input Available",
- "type": "boolean"
- },
- "sample_rate": {
- "title": "Sample Rate",
- "type": "integer"
- },
- "frame_length": {
- "title": "Frame Length",
- "type": "integer"
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalCorrectionResult"
+ }
+ }
+ },
+ {
+ "name": "session.resume",
+ "summary": "",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalResumeParams"
}
- },
- "required": [
- "listening",
- "owned_by_caller",
- "phrase",
- "provider",
- "configured_surface",
- "input_device",
- "available",
- "hint",
- "enabled",
- "audio_silent",
- "capture",
- "local_input_available",
- "sample_rate",
- "frame_length"
- ],
- "title": "WakeStatusResult",
- "type": "object"
- },
- "WakeStopParams": {
- "additionalProperties": false,
- "properties": {
- "persist": {
- "anyOf": [
- {
- "type": "boolean"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Persist"
- },
- "profile": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Profile"
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalSnapshot"
+ }
+ }
+ },
+ {
+ "name": "session.stats",
+ "summary": "The session.usage dict on demand: what main's classic CLI read off its agent.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/SessionStatsParams"
}
- },
- "title": "WakeStopParams",
- "type": "object"
- },
- "WakeStopResult": {
- "additionalProperties": false,
- "properties": {
- "reason": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Reason"
- },
- "stopped": {
- "title": "Stopped",
- "type": "boolean"
- },
- "disabled_persisted": {
- "title": "Disabled Persisted",
- "type": "boolean"
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/SessionStats"
+ }
+ }
+ },
+ {
+ "name": "session.steer",
+ "summary": "",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalCorrectionParams"
}
- },
- "required": [
- "stopped",
- "disabled_persisted"
- ],
- "title": "WakeStopResult",
- "type": "object"
- },
- "_SessionScoped": {
- "additionalProperties": false,
- "description": "Handlers that look a live session up with ``_sessions.get(params.get(\"session_id\"))``: an\nabsent / unknown id falls back to the launch profile's config, so it is never required.",
- "properties": {
- "session_id": {
- "anyOf": [
- {
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "default": null,
- "title": "Session Id"
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalCorrectionResult"
+ }
+ }
+ },
+ {
+ "name": "shell.exec",
+ "summary": "Ink ``!cmd`` / ``{!cmd}`` on the shared owner: one safe command for a local session, in its frozen launch cwd (``gateway/session_shell.py``).",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/CanonicalShellExecParams"
}
- },
- "title": "_SessionScoped",
- "type": "object"
- },
- "ConnectorErrorReason": {
- "type": "string",
- "enum": [
- "INVALID_PARAMS",
- "NOT_OWNER",
- "UNSUPPORTED_RUNTIME",
- "CONNECTOR_REQUEST_FAILED",
- "INVALID_CONNECTOR_RESPONSE",
- "UNKNOWN_TARGET",
- "LINK_STILL_VALID",
- "REISSUE_REFUSED",
- "UNKNOWN_OPERATION",
- "INVALID_ANSWER",
- "NEEDS_NOUS_AUTH",
- "CONNECTOR_NOT_FOUND",
- "TOOLS_UNAVAILABLE",
- "CONNECTORS_UNAVAILABLE",
- "CATALOG_UNAVAILABLE",
- "ACCOUNTS_UNAVAILABLE",
- "CONNECTION_NOT_FOUND",
- "POLICY_UNAVAILABLE",
- "POLICY_CONFLICT",
- "FORBIDDEN_SCOPE",
- "ORG_REQUIRED",
- "ORG_ACCESS_DENIED",
- "INVALID_POLICY",
- "ALIAS_TAKEN"
- ]
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/ShellExecResult"
+ }
+ }
+ },
+ {
+ "name": "worker.adopt",
+ "summary": "Adopt a registered execution after verifying the live producer claim.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/WorkerScopeParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/WorkerExecution"
+ }
+ }
+ },
+ {
+ "name": "worker.persist",
+ "summary": "Sequence-fenced typed persistence write from an adopted worker.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/WorkerPersistParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/WorkerPersistResult"
+ }
+ }
+ },
+ {
+ "name": "worker.register",
+ "summary": "Register a compute worker execution on an idle session.",
+ "params": [
+ {
+ "name": "params",
+ "schema": {
+ "$ref": "#/components/schemas/WorkerRegisterParams"
+ }
+ }
+ ],
+ "result": {
+ "name": "result",
+ "schema": {
+ "$ref": "#/components/schemas/WorkerExecution"
+ }
}
}
- },
+ ],
"x-server-requests": [
{
"name": "approval",
diff --cc gateway/run_inbound.py
index 846838e6f68,c6d47ae5467..a6f26d98c91
--- a/gateway/run_inbound.py
+++ b/gateway/run_inbound.py
@@@ -978,9 -1021,89 +978,9 @@@ class GatewayInboundMixin(GatewayInboun
async with self._async_profile_scope_for_source(source):
return True, await plain_handler(event)
if canonical in self._HM_CANONICAL_COMMANDS:
- return await getattr(self, f"_hm_cmd_{canonical.replace('-', '_')}")(event, source, _quick_key)
+ return await getattr(self, f"_hm_cmd_{canonical}")(event, source, _quick_key)
return False, None
- async def _hm_run_exec_quick_command(self, command: str, exec_cmd: str) -> str:
- """Run a ``type: exec`` quick command in the gateway process (30 s cap, sanitized env — the
- gateway process has every API key in os.environ; output is redacted too)."""
- try:
- from tools.environments.local import build_subprocess_env
- proc = await asyncio.create_subprocess_shell(
- exec_cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
- env=build_subprocess_env(),
- )
- stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout=30)
- output = (stdout or stderr).decode().strip()
- if output:
- from agent.redact import redact_sensitive_text
- output = redact_sensitive_text(output)
- return output or t("gateway.quick_command.no_output")
- except TimeoutError:
- return t("gateway.quick_command.timed_out")
- except Exception as e:
- return t("gateway.quick_command.error", error=e)
-
- async def _hm_dispatch_quick_and_plugin_commands(
- self, event: MessageEvent, source: SessionSource, command: Optional[str]
- ) -> tuple[bool, Optional[str], Optional[str]]:
- """Drain gate, user-defined quick commands (exec/alias) and plugin slash commands →
- ``(handled, result, command)``; an alias quick command rewrites ``command``."""
- if self._draining:
- return True, t("gateway.busy.drain_rejected_new_work", action=self._status_action_gerund()), command
-
- # User-defined quick commands (bypass agent loop, no LLM call)
- qcmd = self._hm_quick_commands().get(command) if command else None
- if qcmd is not None:
- # Quick commands are slash capabilities too — and type:exec ones run a shell command in
- # the gateway process. They are never in the registry, so the early gate never fires for
- # them; apply the same admin/user policy to the raw typed name here.
- # The early gate above only fires for registry-known commands, so quick commands (never in the
- # registry) would otherwise reach this dispatch sink unchecked. (#44727)
- _denied = self._check_slash_access(source, command)
- if _denied is not None:
- return True, _denied, command
- qtype = qcmd.get("type")
- if qtype == "exec":
- exec_cmd = qcmd.get("command", "")
- if not exec_cmd:
- return True, t("gateway.quick_command.no_command", command=command), command
- return True, await self._hm_run_exec_quick_command(command, exec_cmd), command
- if qtype != "alias":
- return True, t("gateway.quick_command.unsupported_type", command=command), command
- new_command = self._hm_expand_alias_quick_command(event, qcmd)
- if new_command is None:
- return True, t("gateway.quick_command.no_target", command=command), command
- command = new_command # Fall through to normal command dispatch below
-
- # Plugin-registered slash commands. Underscores normalize to hyphens so Telegram's
- # underscored autocomplete form matches plugin commands registered with hyphens.
- if command:
- try:
- from hermes_cli.plugins import get_plugin_command_handler
- plugin_handler = get_plugin_command_handler(command.replace("_", "-"))
- if plugin_handler:
- # The agent-turn path binds HERMES_SESSION_* via _set_session_env; this dispatch
- # sits before it, so a handler reading get_session_env() would see an empty or a
- # foreign (cron agent's os.environ) session (#108698). No session_entry exists yet,
- # so session_key is derived from source. Sync handlers run on the gateway pool
- # (contextvars carried), never the loop thread: blocking I/O there starves the
- # liveness watchdog and the process exits 75 mid-handler (#105279).
- _plugin_context = build_session_context(source, self.config)
- _plugin_context.session_key = self._session_key_for_source(source)
- user_args = event.get_command_args().strip()
- with self._session_env_scope(_plugin_context):
- if asyncio.iscoroutinefunction(plugin_handler):
- result = await plugin_handler(user_args)
- else:
- result = await self._run_in_executor_with_context(plugin_handler, user_args)
- if asyncio.iscoroutine(result):
- result = await result
- return True, str(result) if result else None, command
- except Exception as e:
- logger.warning("Plugin command dispatch failed: %s", e)
- return False, None, command
-
def _hm_bundle_slash_rewrite(
self, event: MessageEvent, source: SessionSource, _quick_key: str, command: str
) -> bool:
diff --cc gateway/run_turn_prepare.py
index 35228e0814e,00000000000..8248736d33f
mode 100644,000000..100644
--- a/gateway/run_turn_prepare.py
+++ b/gateway/run_turn_prepare.py
@@@ -1,739 -1,0 +1,739 @@@
+"""Gateway turn prepare phases; inherited by GatewayTurnMixin."""
+from __future__ import annotations
+
+import logging
+from typing import TYPE_CHECKING
+import asyncio
+import dataclasses
+import inspect
+import json
+import os
+import queue
+import threading
+import time
+from agent.i18n import t
+from agent.session_activity import format_iteration_progress
+from contextlib import nullcontext, suppress
+from contextvars import copy_context
+from gateway.config import Platform
+from gateway.media_repair import repair_explicit_computer_use_media_paths
+from gateway.platforms.base import BasePlatformAdapter
+from gateway.platforms.event import MessageEvent
+from gateway.session import (
+ SessionSource, _session_key_namespace, build_channel_continuity_note,
+ build_session_context,
+)
+from gateway.session_transcript import TranscriptReadError
+from gateway.turn_context import TurnContext
+from gateway.turn_lease import DEFAULT_LEASE_WAIT, TurnLeaseTimeoutError
+from hermes_constants import get_hermes_home_override
+from pathlib import Path
+from typing import Any, Callable, Dict, List, Optional, Tuple
+from utils import base_url_hostname
+
+if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)
+ from gateway.run import GatewayRunner
+ from gateway.run_turn_runner import TurnRunner
+
+# Log-record parity with the origin module.
+logger = logging.getLogger("gateway.run")
+
+
+def _resolve_policy_agent_runtime(runner, policy) -> tuple[str, dict]:
+ """``_resolve_session_agent_runtime`` for a session bound to a launch policy: the route's FROZEN
+ config and launch credential, walking its own fallback chain on an AuthError. Module-level so
+ tests that bind the method onto bare namespaces still reach it."""
+ from gateway.run import _runtime_agent_kwargs
+ from gateway.session_policy import launch_key
+ from hermes_cli.runtime_provider import frozen_runtime_config, resolve_runtime_with_fallback
+ from hermes_cli.runtime_provider_custom import _resolve_named_custom_runtime
+ from gateway.session_authorities import active_authority
+ authority = active_authority(runner)
+ # A follow_profile_config session's route is the profile's current one, model and endpoint from one read.
+ frozen, model = policy.effective(authority)
+ provider = (frozen.get('model') or {}).get('provider')
+ key = launch_key(authority, policy)
+ launch_url = json.loads(policy.request_json).get('base_url')
+ if launch_url:
+ # The creation request is immutable identity, not the current selection: once a canonical
+ # model mutation moved the route off the launch endpoint, the policy's selection wins.
+ from hermes_cli.route_identity import normalize_route_base_url
+ if normalize_route_base_url(launch_url) != normalize_route_base_url((frozen.get('model') or {}).get('base_url')):
+ launch_url = None
+ # Every rung reads the session's FROZEN config, never live config.yaml: a later
+ # ``model.base_url`` edit must not carry this route's frozen credential to the new host
+ # (R2-M2). The auth-store pool is not config, so refresh/rotation still applies.
+ with frozen_runtime_config(frozen):
+ runtime = _resolve_named_custom_runtime(requested_provider=provider,
+ explicit_api_key=key, explicit_base_url=launch_url,
+ target_model=model, config=frozen)
+ if runtime is None:
+ # Only a bound launch key is explicit: the frozen ``model.api_key`` is config, which the
+ # resolver already reads from the frozen scope, so a URL-matched credential pool still
+ # serves (and rotates on) the frozen endpoint.
+ # Same resolution-time walker the in-process one-shot used (#81209): an AuthError
+ # from the frozen primary (expired token, Portal down, exhausted pool) tries the
+ # route's own ``fallback_providers`` before the turn is refused. Only a launch URL is
+ # explicit (classic one-shot parity): the frozen ``model.base_url`` is resolved by
+ # the provider chain, which keeps the credential pool an explicit URL would drop.
+ runtime, fallback_entry = resolve_runtime_with_fallback(frozen, requested=provider,
+ explicit_api_key=key, explicit_base_url=launch_url, target_model=model)
+ else:
+ fallback_entry = None
+ if fallback_entry is not None:
+ from hermes_cli.fallback_config import pre_agent_fallback_notice
+ runner._pre_agent_fallback_notice = pre_agent_fallback_notice(
+ provider or '', model or '',
+ runtime.get('provider') or fallback_entry.get('provider') or 'unknown',
+ fallback_entry.get('model') or 'default')
+ return fallback_entry['model'], _runtime_agent_kwargs(runtime)
+ return model, _runtime_agent_kwargs(runtime)
+
+
+def _recover_or_remember_model(runner, skey, model):
+ """Last step of ``_resolve_session_agent_runtime``: remember a good model, recover an empty one."""
+ # 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 = runner._peek_session_state(skey) if skey else None
+ _lr_star = runner._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:
+ runner._session_state(skey).conversation.last_resolved_model = model
+ runner._session_state("*").conversation.last_resolved_model = model
+ return model
+
+
+class GatewayTurnPrepareMixin:
+ def _resolve_session_agent_runtime(
+ self, *, source: Optional[SessionSource] = None, session_key: Optional[str] = None,
+ user_config: Optional[dict] = None,
+ ) -> tuple[str, dict]:
+ """Resolve model/runtime for a session.
+
+ Priority (highest first): session ``/model`` → ``channel_overrides`` → global config/env
+ (``_resolve_gateway_model(user_config)`` and default provider resolution)."""
+ from gateway.run import (
+ _credential_pool_for_provider, _get_channel_override, _resolve_gateway_model,
+ _resolve_runtime_agent_kwargs, _resolve_runtime_agent_kwargs_for_provider,
+ )
+ from gateway.session_policy import policy_for_source
+ # Every exit path starts clean: a stale notice must never attach to another session's next
+ # turn (#74349). Set again below only when THIS resolution fell back.
+ self._pre_agent_fallback_notice = None
+ policy = policy_for_source(self, source) if source is not None else None
+ if policy is not None:
+ return _resolve_policy_agent_runtime(self, policy)
+ 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 (credentials failed to re-resolve at rehydrate): resolve them
+ # for the override's own provider below, never layer it over the default provider's runtime.
+ logger.debug(
+ "Session model override (no api_key, fallback): session=%s config_model=%s override_model=%s",
+ skey or "", model, override_model,
+ )
+ elif logger.isEnabledFor(logging.DEBUG):
+ # The override_keys scan walks every session; only pay for it when DEBUG is on.
+ 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, unavailable_override = None, None
+ if override and override.get("provider"):
+ try:
+ runtime_kwargs = _resolve_runtime_agent_kwargs_for_provider(
+ override["provider"], target_model=override.get("model") or None)
+ except Exception as exc:
+ # Layering the override on the default runtime sent its model to the default provider's
+ # endpoint (openai-codex on the Nous URL). Run this turn on the whole default route and say
+ # so; the persisted override is kept, so the next turn retries it.
+ logger.warning("Session /model override provider %s unavailable: %s", override["provider"], exc,
+ exc_info=True)
+ unavailable_override, override = override, None
+ if runtime_kwargs is None:
+ runtime_kwargs = _resolve_runtime_agent_kwargs()
+ # Private notice metadata must never reach an ``AIAgent(**runtime_kwargs)`` spread; the turn
+ # runner surfaces it through the agent's one-shot fallback notice (#74349).
+ self._pre_agent_fallback_notice = runtime_kwargs.pop("_fallback_notice", None)
+ runtime_model = runtime_kwargs.pop("model", None)
+ if runtime_model:
+ logger.info("Runtime provider supplied explicit model override: %s -> %s", model, runtime_model)
+ model = runtime_model
+ if unavailable_override and not self._pre_agent_fallback_notice:
+ from hermes_cli.fallback_config import pre_agent_fallback_notice
+ self._pre_agent_fallback_notice = pre_agent_fallback_notice(
+ unavailable_override["provider"], unavailable_override.get("model"), runtime_kwargs.get("provider"), model)
+
+ cfg = getattr(self, "config", None) # getattr: bare object.__new__ test runners
+ if cfg and source is not None:
+ ch = _get_channel_override(
+ cfg, source.platform, str(source.chat_id) if source.chat_id else "",
+ thread_id=str(source.thread_id) if getattr(source, "thread_id", None) else None,
+ parent_id=str(source.parent_chat_id) if getattr(source, "parent_chat_id", None) else None,
+ )
+ if ch:
+ if ch.model:
+ model = ch.model
+ if ch.provider:
+ runtime_kwargs = _resolve_runtime_agent_kwargs_for_provider(ch.provider, target_model=model or None)
+ ch_runtime_model = runtime_kwargs.pop("model", None)
+ # Adopt the provider's bundled model only when the override named none.
+ if ch_runtime_model and not ch.model:
+ model = ch_runtime_model
+
+ if override and skey:
+ model, runtime_kwargs = self._apply_session_model_override(skey, model, runtime_kwargs)
+
+ # Provider resolved but no model.default (`hermes auth add` without `hermes model`): use the
+ # provider's first catalog model.
+ if not model and runtime_kwargs.get("provider"):
+ with suppress(Exception):
+ from hermes_cli.models import get_default_model_for_provider
+ model = get_default_model_for_provider(runtime_kwargs["provider"])
+ if model:
+ logger.info(
+ "No model configured — defaulting to %s for provider %s", model, runtime_kwargs["provider"],
+ )
+
+ return _recover_or_remember_model(self, skey, 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 agent.fast_mode import STATIC_TIERS
+ 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"]),
+ ),
+ }
+ tier = getattr(self, "_service_tier", None)
+ if tier not in STATIC_TIERS:
+ # 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"], tier=tier,
+ )
+ except Exception:
+ overrides = None
+ # Fast-mode keys (service_tier / speed) are top-level and don't collide with extra_body.
+ route["request_overrides"] = _deep_merge_request_overrides(base_request_overrides, overrides or {})
+ return route
+
+ def _sync_session_model_from_agent(self, session_id: str, agent: Any) -> None:
+ """Persist the runtime model/provider a gateway turn actually used (provider fallback can
+ switch them after the row was created). Runs in the ``run_sync`` executor thread, so it
+ uses the sync ``SessionDB`` (``_db``), not the AsyncSessionDB forwarder."""
+ if not session_id or agent is None or self._session_db is None:
+ return
+ model = getattr(agent, "model", None)
+ if not model:
+ return
+ runtime = {k: getattr(agent, k, None) for k in ("provider", "base_url", "api_mode")}
+ runtime["fallback_active"] = bool(getattr(agent, "_fallback_activated", False))
+ runtime = {k: v for k, v in runtime.items() if v not in (None, "")}
+ try:
+ db = self._session_db._db
+ row = db.get_session(session_id)
+ if not row:
+ return
+ # Legacy backfill: canonical Bot Chats created BEFORE the follow_profile_config contract existed
+ # carry no marker, yet they are still the plugin-owned forever-DM. The plugin's own identity
+ # rule is "the profile's session titled exactly 'Bot Chat'" (UNIQUE(title) makes that an exact
+ # registry, and pre-policy rows may be visible OR hidden), so mirror that rule here. Without
+ # this, every Bot Chat that already exists in the field stays pinned to its stale stored
+ # provider until the user deletes it — the exact live-report shape (#89497 / #94818).
+ raw_config = row.get("model_config")
+ config = {}
+ with suppress(Exception):
+ config = json.loads(raw_config) if raw_config else {}
+ if not isinstance(config, dict):
+ config = {}
+ gateway_runtime = dict(config.get("gateway_runtime") or {})
+ if row.get("model") == model and all(gateway_runtime.get(k) == v for k, v in runtime.items()):
+ return
+ config["gateway_runtime"] = runtime
+ db.update_session_meta(session_id, json.dumps(config), model=model)
+ except Exception:
+ logger.debug("Failed to sync gateway session model metadata", exc_info=True)
+
+ async def _hmwa_resolve_session(self, event, source):
+ """Resolve ``source`` to its session entry (topic recovery, internal-route guards, Telegram
+ topic-binding heal). Returns ``(source, session_entry, session_key)`` or ``None`` to drop
+ the event."""
+ # Topic-mode DMs: rewrite a stale/foreign thread_id to the user's last-active topic so a
+ # cross-topic Reply doesn't fragment the conversation.
+ event_metadata = getattr(event, "metadata", None) or {}
+ expected_session_key = str(event_metadata.get("gateway_session_key") or "").strip()
+ recovered = (await asyncio.to_thread(self._recover_telegram_topic_thread_id, source)
+ if not expected_session_key else None)
+ if recovered is not None:
+ logger.info(
+ "telegram topic recovery: chat=%s user=%s %r -> %s",
+ source.chat_id, source.user_id, source.thread_id, recovered,
+ )
+ source = dataclasses.replace(source, thread_id=recovered)
+ with suppress(Exception):
+ event.source = source
+
+ if expected_session_key:
+ derived_session_key = self._session_key_for_source(source)
+ if derived_session_key != expected_session_key:
+ logger.warning(
+ "Dropping internally routed event after route recovery: expected session=%s derived=%s",
+ expected_session_key, derived_session_key,
+ )
+ return
+
+ strict_session = bool(event_metadata.get("gateway_session_strict"))
+ pinned_session_id = str(event_metadata.get("gateway_session_id") or "").strip()
+ if strict_session:
+ session_entry = await self.async_session_store.lookup_by_session_key(expected_session_key)
+ if session_entry is None or not pinned_session_id or session_entry.session_id != pinned_session_id:
+ logger.warning(
+ "Dropping internally routed event: expected session id=%s is no longer current for key=%s",
+ pinned_session_id or "missing", expected_session_key or "missing",
+ )
+ return
+ else:
+ # Internal wakes observe reset policy without counting as user activity, or periodic
+ # notifications keep the routing key alive across every daily/idle boundary.
+ session_entry = await self.async_session_store.get_or_create_session(
+ source, touch_activity=not bool(getattr(event, "internal", False)),
+ )
+ session_key = session_entry.session_key
+ if not strict_session and pinned_session_id:
+ resolved_entry = await self._resolve_async_delegation_session(session_entry, pinned_session_id, event_metadata.get("gateway_proven_session_id") or "", event_metadata.get("gateway_completion_ids") or ())
+ if resolved_entry is None:
+ return
+ session_entry = resolved_entry
+ self._cache_session_source(session_key, source)
+ if await asyncio.to_thread(self._is_telegram_topic_lane, source):
+ session_entry = await self._hmwa_heal_telegram_topic_binding(source, session_entry, session_key)
+ from gateway.run_heartbeat_acceptance import resolve_heartbeat_owner
+ if not await resolve_heartbeat_owner(self, event, session_entry):
+ return
+ return source, session_entry, session_key
+
+ async def _hmwa_heal_telegram_topic_binding(self, source, session_entry, session_key):
+ """Follow the (chat_id, thread_id) topic binding — healed to its compression tip — or record
+ a fresh one. Returns the (possibly switched) session entry."""
+ binding = None
+ try:
+ if self._session_db:
+ binding = await self._session_db.get_telegram_topic_binding(
+ chat_id=str(source.chat_id), thread_id=str(source.thread_id),
+ profile_name=self._telegram_topic_profile_name(source),
+ )
+ except Exception:
+ logger.debug("Failed to read Telegram topic binding", exc_info=True)
+ if not binding:
+ try:
+ await asyncio.to_thread(self._record_telegram_topic_binding, source, session_entry)
+ except Exception:
+ logger.debug("Failed to record Telegram topic binding", exc_info=True)
+ return session_entry
+ stored_session_id = str(binding.get("session_id") or "")
+ bound_session_id = stored_session_id
+ # A binding pointing at a pre-compression parent is walked forward to the tip so the next
+ # message resumes the compressed child instead of reloading the oversized parent.
+ # Returns the input unchanged when the session isn't a compression parent, so this is cheap and
+ # safe. See #20470, #29712, #33414.
+ if bound_session_id and self._session_db is not None:
+ try:
+ canonical_session_id = await self._session_db.get_compression_tip(bound_session_id)
+ except Exception:
+ logger.debug("compression-tip lookup failed for %s", bound_session_id, exc_info=True)
+ canonical_session_id = bound_session_id
+ if canonical_session_id and canonical_session_id != bound_session_id:
+ bound_session_id = canonical_session_id
+ if bound_session_id and bound_session_id != session_entry.session_id:
+ # Route through SessionStore so the key → id mapping persists and the previous lane
+ # session ends cleanly (in-place mutation split-brained the JSON index). The two DB
+ # awaits above are a window for /new or /resume to move the route; the CAS on the
+ # snapshot id lets that win instead of being clobbered by a stale binding.
+ switched = await self.async_session_store.switch_session(
+ session_key, bound_session_id, expected_session_id=session_entry.session_id,
+ )
+ if switched is not None:
+ session_entry = switched
+ if bound_session_id and bound_session_id != stored_session_id:
+ # The stored binding pointed at a parent: rewrite it to the canonical descendant.
+ await asyncio.to_thread(
+ self._sync_telegram_topic_binding, source, session_entry, reason="compression-tip-walk",
+ )
+ return session_entry
+
+ async def _hmwa_open_session(self, session_entry, session_key, source):
+ """Consume auto-reset / fresh-reset flags and emit ``session:start`` for new sessions.
+ Returns ``(_was_auto_reset, _is_new_session)``."""
+ # Capture and immediately consume was_auto_reset so it does not re-fire on subsequent messages —
+ # preventing the cleanup from wiping model/reasoning overrides set between turns (Closes #48031).
+ _was_auto_reset = getattr(session_entry, "was_auto_reset", False)
+ if _was_auto_reset:
+ # Conversation boundary: the funnel clears every conversation-scoped dict; evict the cached
+ # agent so context_compressor._previous_summary cannot leak into new summaries.
+ # Treat auto-reset as a full conversation boundary — clear every conversation-scoped per-session
+ # dict in one funnel call so the fresh session does not inherit the previous conversation's
+ # model/reasoning overrides, a queued "/model switched" note, or a stale resolved-model cache
+ # (#48031, #58403). See _CONVERSATION_SCOPED_STATE.
+ self._clear_conversation_scope(session_key, reason="auto_reset")
+ self._evict_cached_agent(session_key)
+ session_entry.was_auto_reset = False
+
+ _is_fresh_reset = getattr(session_entry, "is_fresh_reset", False)
+ _is_new_session = session_entry.created_at == session_entry.updated_at or _was_auto_reset or _is_fresh_reset
+ # Consume is_fresh_reset so it doesn't leak onto later messages in the same session.
+ if _is_fresh_reset:
+ # See #6508.
+ session_entry.is_fresh_reset = False
+ if _is_new_session:
+ await self.hooks.emit("session:start", {
+ "platform": source.platform.value if source.platform else "",
+ "user_id": source.user_id,
+ "session_id": session_entry.session_id,
+ "session_key": session_key,
+ })
+ return _was_auto_reset, _is_new_session
+
+ async def _hmwa_deliver_auto_reset_notice(self, session_entry, source, turn_sidecar_notes):
+ """Stage the auto-reset sidecar note for the agent and notify the user (policy-gated)."""
+ from gateway.run import _AUTO_RESET_CONTEXT_NOTES
+ reset_reason = getattr(session_entry, 'auto_reset_reason', None) or 'suspended'
+ context_note = _AUTO_RESET_CONTEXT_NOTES.get(reset_reason, _AUTO_RESET_CONTEXT_NOTES["suspended"])
+ # Long-lived channels: point the agent at the prior same-channel session for session_search.
+ try:
+ # Returns None (appends nothing) for other platforms or when there's no prior activity to
+ # recall. Deterministic — no extra API/DB calls (#36220).
+ continuity_note = build_channel_continuity_note(session_entry, source)
+ except Exception:
+ continuity_note = None
+ if continuity_note:
+ context_note = context_note + "\n\n" + continuity_note
+ turn_sidecar_notes.append(context_note)
+
+ try:
+ should_notify = reset_reason == "suspended"
+ adapter = self._delivery_adapter_for(source) if should_notify else None
+ if adapter:
+ notice = t("gateway.session.auto_reset_notice")
+ with suppress(Exception):
+ session_info = await asyncio.to_thread(self._reset_notice_session_info, source)
+ if session_info:
+ notice = f"{notice}\n\n{session_info}"
+ await adapter.send(source.chat_id, notice, metadata=self._thread_metadata_for_source(source))
+ except Exception as e:
+ logger.debug("Auto-reset notification failed (non-fatal): %s", e)
+
+ # was_auto_reset was consumed in _hmwa_open_session; only the reason needs clearing.
+ session_entry.auto_reset_reason = None
+
+ def _hmwa_auto_load_skills(self, event, _auto, _quick_key, session_key):
+ """Prepend topic/channel-bound skill payload(s) to ``event.text`` on a new session."""
+ _skill_names = [_auto] if isinstance(_auto, str) else list(_auto)
+ try:
+ from agent.skill_commands import _load_skill_payload, _build_skill_message
+ _combined_parts: list[str] = []
+ _loaded_names: list[str] = []
+ for _sname in _skill_names:
+ _loaded = _load_skill_payload(_sname, task_id=_quick_key)
+ if not _loaded:
+ logger.warning("[Gateway] Auto-skill '%s' not found", _sname)
+ continue
+ _loaded_skill, _skill_dir, _display_name = _loaded
+ _part = _build_skill_message(
+ _loaded_skill, _skill_dir,
+ f'[IMPORTANT: The "{_display_name}" skill is auto-loaded. '
+ f"Follow its instructions for this session.]",
+ )
+ if _part:
+ _combined_parts.append(_part)
+ _loaded_names.append(_sname)
+ if _combined_parts:
+ _combined_parts.append(event.text) # user's original text after the payloads
+ event.text = "\n\n".join(_combined_parts)
+ logger.info("[Gateway] Auto-loaded skill(s) %s for session %s", _loaded_names, session_key)
+ except Exception as e:
+ logger.warning("[Gateway] Failed to auto-load skill(s) %s: %s", _skill_names, e)
+
+ async def _hmwa_acquire_turn_lease(self, _quick_key, run_generation, session_entry, _session_env_tokens):
+ """Serialize [load history → run → flush] per resolved SESSION_ID so another routing key on
+ the same session waits for the prior flush. Fail-closed on timeout (outer dispatch returns
+ a resend notice). Released in _handle_message's finally, granted per (routing key, run
+ generation) so a stale unwind can't release a newer turn's."""
+ from gateway.run import _float_env
+ _lease_registry = getattr(self, "_turn_leases", None)
+ if _lease_registry is None:
+ return
+ try:
+ _lease_token = await _lease_registry.acquire(
+ session_entry.session_id, owner_key=_quick_key, generation=run_generation,
+ timeout=_float_env("HERMES_TURN_LEASE_TIMEOUT", DEFAULT_LEASE_WAIT),
+ )
+ except TurnLeaseTimeoutError:
+ # The cleanup finally starts later; restore the tokens here or this exit leaks identity.
+ self._clear_session_env(_session_env_tokens)
+ raise
+ if _lease_token is not None:
+ self._session_state(_quick_key).turn.lease_tokens[run_generation] = _lease_token
+
- async def _hmwa_first_contact_notes(self, source, history, turn_sidecar_notes, message, internal=False):
++ async def _hmwa_first_contact_notes(self, source, history, turn_sidecar_notes, internal=False):
+ """First-ever-message onboarding note + one-time 'no home channel' prompt (both only when
+ the session has no history). Delivered on the user message (sidecar), NOT the ephemeral
+ system prompt: present-on-turn-1/absent-on-turn-2 was a guaranteed prompt diff + rebuild."""
+ from gateway.run import _gateway_config_home, _home_target_env_var, _load_gateway_config
+ if history or internal: # internal = plugin/system turn: no human made first contact
+ return
+ # LOCAL sessions (one-shot, chat -q, ACP, TUI attach) are the classic in-process CLI's
+ # surfaces: it never appended this note, and mark_seen would rewrite config.yaml under
+ # an ordinary launch that promises to leave the profile's files untouched.
+ human_platform = bool(source.platform) and source.platform not in (Platform.LOCAL, Platform.WEBHOOK)
+ if human_platform and source.chat_type == "dm" and not await self.async_session_store.has_any_sessions():
- # Same branch logic as the TUI (offer once when "ask", else plain intro);
++ # Same branch logic as the TUI (profile-build offer once when "ask", else plain intro);
+ # first_contact_turn_note already falls back to the plain intro on error.
- from agent.onboarding import first_contact_turn_note, setup_command
++ from agent.onboarding import first_contact_turn_note
+ note = first_contact_turn_note(
+ _load_gateway_config(), _gateway_config_home() / "config.yaml",
- session_history_empty=True, install_has_prior_sessions=False, message=message,
- command=setup_command(source.platform.value))
++ session_history_empty=True, install_has_prior_sessions=False,
++ )
+ if note:
+ turn_sidecar_notes.append(note)
+
+ # One-time prompt if no home channel is set (webhooks deliver to configured targets instead).
+ if not human_platform:
+ return
+ platform_name = source.platform.value
+ env_key = _home_target_env_var(platform_name)
+ # Multiplex: the home channel may live only in the profile secret scope, not os.environ.
+ home_env = ""
+ if env_key:
+ # A secondary with no home channel must not borrow the default profile's from
+ # os.environ; only an UNSCOPED single-profile read may fall back to the process env.
+ from agent.secret_scope import UnscopedSecretError, get_secret
+ try:
+ home_env = (get_secret(env_key) or "").strip()
+ except UnscopedSecretError:
+ home_env = (os.getenv(env_key) or "").strip()
+ except Exception:
+ logger.debug("Home-channel secret %s unreadable; treating it as unset", env_key, exc_info=True)
+ home_env = ""
+ # Also honor in-memory / yaml home_channel on this platform.
+ with suppress(Exception):
+ if not home_env and self.config.get_home_channel(source.platform):
+ home_env = "set"
+ # Secondary-profile platforms may only exist under that profile's config — re-read in scope.
+ if not home_env:
+ with suppress(Exception):
+ from gateway.config import load_gateway_config as _lgc
+ prof = (getattr(source, "profile", None) or "").strip()
+ if prof and prof != "default" and _lgc().get_home_channel(source.platform):
+ home_env = "set"
+ if not home_env:
+ # Slack routes every command through the parent `/hermes`; bare `/sethome` would fail.
+ sethome_cmd = "/hermes sethome" if source.platform == Platform.SLACK else "/sethome"
+ await self._deliver_platform_notice(
+ source, t("gateway.notify.no_home_channel", platform=platform_name.title(), sethome_cmd=sethome_cmd),
+ )
+
+ def _hmwa_apply_message_timestamp(self, event, message_text):
+ """Capture the platform event time as message metadata and keep the persisted transcript
+ clean — strip any leading timestamp prefix and the Discord triggering-message note (a
+ model instruction, not authored text) — regardless of the toggle; only the in-context
+ RENDER is gated behind gateway.message_timestamps.enabled (default OFF)."""
+ from gateway.run import _load_gateway_config, _message_timestamps_enabled
+ from gateway.run_inbound import strip_discord_triggering_note
+ persist_user_message = None
+ persist_user_timestamp = None
+ try:
+ from hermes_time import get_timezone as _get_evt_tz
+ from gateway.message_timestamps import (
+ coerce_message_timestamp as _coerce_msg_ts,
+ render_user_content_with_timestamp as _render_msg_ts,
+ strip_leading_message_timestamps as _strip_msg_ts,
+ )
+ _evt_tz = _get_evt_tz()
+ if message_text and isinstance(message_text, str):
+ _clean_message_text, _embedded_ts = _strip_msg_ts(message_text, tz=_evt_tz)
+ persist_user_message = strip_discord_triggering_note(event, _clean_message_text)
+ _event_epoch = _coerce_msg_ts(getattr(event, "timestamp", None), tz=_evt_tz)
+ persist_user_timestamp = _event_epoch if _event_epoch is not None else _embedded_ts
+ if _message_timestamps_enabled(_load_gateway_config()):
+ message_text = _render_msg_ts(_clean_message_text, persist_user_timestamp, tz=_evt_tz)
+ else:
+ # Toggle off: the model sees the clean message; timestamp stored for later opt-in.
+ message_text = _clean_message_text
+ except Exception as _ts_err:
+ logger.debug("Message timestamp injection failed (non-fatal): %s", _ts_err)
+ return message_text, persist_user_message, persist_user_timestamp
+
+ @dataclasses.dataclass
+ class _PreparedTurn:
+ """Inputs to the agent run assembled by ``_hmwa_prepare_turn``."""
+
+ history: Any
+ context_prompt: str
+ message_text: Any
+ persist_user_message: Any
+ persist_user_timestamp: Any
+ persist_user_display_kind: Optional[str]
+ persistence_session_id: Optional[str] = None
+ persistence_owner: Optional[str] = None
+ title_user_message: Optional[str] = None
+
+ async def _hmwa_prepare_turn(self, event, source, session_entry, session_key, _quick_key, run_generation):
+ """Everything between session resolution and the agent run: session open, task-local env,
+ context prompt, sidecar notes, turn lease, transcript load + hygiene, inbound text. Returns
+ ``(_PreparedTurn, env_tokens)``; a ``str`` first element is a reply to send instead of
+ running (history unreadable); ``None`` drops the turn (inbound text rejected)."""
+ from gateway.run import _load_gateway_config
+ from tools.approval_yolo import restore_gateway_yolo
+ _was_auto_reset, _is_new_session = await self._hmwa_open_session(session_entry, session_key, source)
+ restore_gateway_yolo(session_key, session_entry.yolo) # None: TurnRunner seeds the launch policy
+ context = build_session_context(source, self.config, session_entry)
+ # Session context variables for tools (task-local, concurrency-safe)
+ _session_env_tokens = self._set_session_env(context)
+ # Self-injected turns (internal=True) persist with a DB-only display_kind: timeline notices, not user bubbles.
+ from gateway.response_filters import display_kind_for_event
+ persist_user_display_kind = display_kind_for_event(event)
+ _redact_pii = False # privacy.redact_pii, re-read per message
+ with suppress(Exception):
+ _redact_pii = bool((_load_gateway_config().get("privacy") or {}).get("redact_pii", False))
+
+ # The context prompt render is pinned per session, keyed by a hash of the renderer inputs, so
+ # the system prompt cannot drift turn-over-turn; a miss (thread rename, /sethome) re-renders.
+ # A LOCAL session (CLI one-shot, ACP, cron run-now, TUI attach) is the operator's own machine:
+ # the messaging block ("Source: Local", connected platforms, cron delivery targets) was never
+ # part of the classic in-process prompt, and the TUI gateway still builds that prompt in-process.
+ # Rendering it here would make every surface hop of one durable session a system-prompt
+ # (and prompt-cache) break.
+ if source.platform != Platform.LOCAL and event.internal and session_key:
+ await self._rehydrate_prompt_pins(session_key, session_entry.session_id)
+ context_prompt = "" if source.platform == Platform.LOCAL else \
+ self._pinned_session_context_prompt(context, _redact_pii, session_key, internal=event.internal)
+
+ # Per-turn notes ride the user message via the api_content sidecar, NOT context_prompt
+ # (appending to the ephemeral system prompt forced a full agent rebuild).
+ turn_sidecar_notes: list[str] = []
+ if _was_auto_reset:
+ await self._hmwa_deliver_auto_reset_notice(session_entry, source, turn_sidecar_notes)
+
+ # Keep human text separate from skills, sender metadata, and other model context.
+ # With no text (e.g. voice-only), retain the existing enriched-message title fallback.
+ title_user_message = event.text or None
+
+ # Auto-load bound skill(s) only on NEW sessions; ongoing ones carry the content in history.
+ _auto = getattr(event, "auto_skill", None)
+ if _is_new_session and _auto:
+ self._hmwa_auto_load_skills(event, _auto, _quick_key, session_key)
+
+ await self._hmwa_acquire_turn_lease(_quick_key, run_generation, session_entry, _session_env_tokens)
+
+ # A turn becomes durable recovery work only after it owns the per-session lease; marking
+ # earlier would falsely recover a message that never began processing.
+ await self._mark_durable_active_turn(event, session_entry.session_key)
+
+ # An unreadable store is not an empty conversation: stop before the agent invents continuity
+ # from []. Restore task-local context here (before the broad cleanup finally).
+ try:
+ history = await self.async_session_store.load_transcript(session_entry.session_id)
+ history = await self._hmwa_run_session_hygiene(
+ event, source, session_entry, session_key, history, _quick_key, run_generation,
+ )
+ except TranscriptReadError:
+ self._clear_session_env(_session_env_tokens)
+ from gateway.session_results import record_unexecuted_failure
+ return record_unexecuted_failure(t("gateway.errors.history_unavailable")), _session_env_tokens
+
- await self._hmwa_first_contact_notes(source, history, turn_sidecar_notes, event.text, internal=event.internal)
++ await self._hmwa_first_contact_notes(source, history, turn_sidecar_notes, internal=event.internal)
+
+ # Voice channel state rides the user message ONLY when changed (in the system prompt it
+ # forced a rebuild + prompt-cache re-key per message).
+ _vc_note = self._voice_channel_sidecar_note(event, source, session_key)
+ if _vc_note:
+ turn_sidecar_notes.append(_vc_note)
+
+ # Auto-analyze user images so the model gets a description plus the local path.
+ message_text = await self._prepare_profile_scoped_inbound_message_text(
+ event=event, source=source, history=history, session_key=session_key,
+ )
+ if message_text is None:
+ return None, _session_env_tokens
+
+ message_text, persist_user_message, persist_user_timestamp = (
+ self._hmwa_apply_message_timestamp(event, message_text)
+ )
+
+ # Stage the notes (one-shot; consumed in run_sync) AFTER the early-out so an aborted turn
+ # cannot leak them into the next turn.
+ if turn_sidecar_notes and session_key:
+ self._set_pending_turn_sidecar_notes(session_key, turn_sidecar_notes)
+
+ # Bind this run generation to the adapter so deferred post-delivery callbacks are released
+ # by the run that registered them.
+ self._bind_adapter_run_generation(self._delivery_adapter_for(source), session_key, run_generation)
+ # Delivery IDs are only unique in their transport namespace. Keyless turns
+ # need their own identity, even when another process writes to this session.
+ import uuid
+ namespace = [source.platform.value, source.profile, source.scope_id,
+ source.chat_id, source.thread_id, str(event.message_id)]
+ owner = (str(uuid.uuid5(uuid.NAMESPACE_URL, json.dumps(namespace)))
+ if event.message_id else str(uuid.uuid4()))
+ return self._PreparedTurn(
+ history, context_prompt, message_text, persist_user_message, persist_user_timestamp,
+ persist_user_display_kind, session_entry.session_id, owner,
+ title_user_message=title_user_message,
+ ), _session_env_tokens
diff --cc gateway/session_commands.py
index 552f69a7b30,00000000000..8954d279b23
mode 100644,000000..100644
--- a/gateway/session_commands.py
+++ b/gateway/session_commands.py
@@@ -1,249 -1,0 +1,249 @@@
+"""Bound local slash commands; prompt directives use the client's durable submit.
+
+Desktop and Ink both submit ``skill``/``send`` results with their own input ID.
+Executing those here would double-submit and bypass their retry identity.
+"""
+import asyncio
+from contextlib import contextmanager
+from pathlib import Path
+import shlex
+
+from hermes_state_runtime import RuntimeStoreError
+
+
+# Reviewed gateway handlers only: listing a command is not permission to run it. Each read was
+# run through its real handler against a local session (website/docs/developer-guide/
+# gateway-command-parity.md); a handler that reads messaging-only state or writes config is not here.
+_READ_COMMANDS = frozenset({'help', 'commands', 'status', 'context', 'version', 'whoami',
+ 'usage', 'insights', 'profile', 'diff', 'memory', 'kanban', 'topup',
+ 'suggestions', 'bundles', 'skills'})
+_CONTROL_COMMANDS = frozenset({'title'})
+# Authoring/workflow commands whose messaging handler (``_command_handler_table``) runs as-is for a
+# local session: goal/loop/heartbeat state on the session's row, the review/refine forks of its
+# cached agent, the /debug summary upload, /blueprint's job creation. A turn the handler would have
+# pushed onto the adapter FIFO comes back as a ``send`` directive (gateway/session_command_sink.py).
+_HANDLER_CONTROLS = frozenset({'goal', 'subgoal', 'loop', 'heartbeat', 'review', 'refine', 'debug', 'curator',
+ 'login'})
+# Idle-path commands the messaging gateway answers by rewriting the turn (``_hm_cmd_<name>``,
+# gateway/run_inbound.py): the rewritten text is returned as the client's ``send`` directive.
- _PROMPT_COMMANDS = frozenset({'plan', 'learn', 'init', 'initiate-setup', 'moa', 'blueprint', 'egress'})
++_PROMPT_COMMANDS = frozenset({'plan', 'learn', 'init', 'moa', 'blueprint', 'egress'})
+# Per-session settings: the messaging handler itself, made session-correct for a local session
+# (gateway/session_setting_commands.py). Admission-fenced like any control.
+_SETTING_COMMANDS = frozenset({'reasoning', 'voice', 'approvals', 'codex-runtime', 'footer', 'busy', 'verbose',
+ 'yolo', 'fast', 'personality'})
+# Typed `/approve` / `/deny`: the messaging handler resolves THIS session's waiting approval (its
+# route is the session key), the same waiter `approval.respond` answers by prompt id.
+_APPROVAL_COMMANDS = frozenset({'approve', 'deny'})
+# Reports with no messaging handler: the classic CLI's own text, built by the owner for this
+# session (gateway/session_info_reads.py).
+_INFO_READS = frozenset({'toolsets', 'platforms'})
+
+# Kanban verbs that only read the board. ``create`` would also subscribe the LOCAL chat to
+# messaging notifications, and every other verb mutates the board.
+_KANBAN_READS = frozenset({'', 'help', '--help', '-h', '?', 'list', 'ls', 'show', 'stats', 'assignees',
+ 'context', 'runs', 'log', 'diagnostics', 'diag'})
+
+
+def _first_token(arg):
+ tokens = iter(shlex.split(arg) if arg.strip() else [])
+ for token in tokens:
+ if token == '--board':
+ next(tokens, None)
+ elif not token.startswith('--board='):
+ return token.lower()
+ return ''
+
+
+# The read-only argument forms of a read command whose other subcommands write: ``/usage reset``
+# redeems a credit, ``/memory approve|approval`` applies writes / edits config.yaml,
+# ``/suggestions accept|catalog`` schedules cron jobs delivering to this (non-messaging) chat.
+_READ_ARGUMENTS = {
+ 'skills': lambda arg: _first_token(arg) in {'', 'pending', 'diff'},
+ 'usage': lambda arg: not arg.strip(),
+ 'memory': lambda arg: arg.strip().lower() in {'', 'pending'},
+ 'suggestions': lambda arg: not arg.strip(),
+ 'kanban': lambda arg: _first_token(arg) in _KANBAN_READS,
+}
+
+
+# The write forms of a command whose reads are above: the messaging handler's own review verbs,
+# applied for this session's profile (`/skills approve|reject` the staged queue, `/skills approval`
+# its config.yaml switch, as main's CLI wrote it).
+_CONTROL_ARGUMENTS = {
+ 'skills': lambda arg: _first_token(arg) in {'approve', 'apply', 'reject', 'deny', 'drop', 'approval', 'mode'},
+}
+
+
+def command_verdict(name, arg=''):
+ """``read`` / ``control`` / ``refused`` for a canonical registry command on a local session."""
+ if (name in _CONTROL_COMMANDS or name in _HANDLER_CONTROLS or name in _PROMPT_COMMANDS
+ or name in _SETTING_COMMANDS or name in _APPROVAL_COMMANDS
+ or _CONTROL_ARGUMENTS.get(name, lambda _a: False)(arg)):
+ return 'control'
+ if name in _INFO_READS or (name in _READ_COMMANDS and _READ_ARGUMENTS.get(name, lambda _arg: True)(arg)):
+ return 'read'
+ return 'refused'
+
+
+def _parse(params, dispatch):
+ allowed = {'session_id', 'profile', 'name', 'arg'} if dispatch else {'session_id', 'profile', 'command'}
+ if (set(params) - allowed or any(not isinstance(v, str) for v in params.values())):
+ raise RuntimeStoreError('invalid_params')
+ text = params.get('name', '') if dispatch else params.get('command', '')
+ parts = text.strip().lstrip('/').split(None, 1)
+ if not parts or (dispatch and len(parts) != 1):
+ raise RuntimeStoreError('invalid_params')
+ return parts[0], params.get('arg', '') if dispatch else (parts[1] if len(parts) > 1 else '')
+
+
+def _resolve_alias(name, arg):
+ from gateway.run import _load_gateway_config
+ from hermes_cli.commands import resolve_command
+ quick = _load_gateway_config().get('quick_commands') or {}
+ seen = set()
+ while resolve_command(name) is None and name in quick:
+ if name in seen:
+ raise RuntimeStoreError('invalid_params')
+ seen.add(name)
+ entry = quick[name]
+ # Shell/plugin execution has no canonical approval or retry contract here.
+ if not isinstance(entry, dict) or entry.get('type') != 'alias':
+ raise RuntimeStoreError('unsupported_command')
+ target = entry.get('target')
+ if not isinstance(target, str) or not target.strip():
+ raise RuntimeStoreError('invalid_params')
+ parts = target.strip().lstrip('/').split(None, 1)
+ name = parts[0]
+ arg = ' '.join(p for p in (*parts[1:], arg) if p)
+ return name, arg
+
+
+def _skill_directive(name, arg, route):
+ from agent.skill_commands import (
+ build_skill_invocation_message, describe_skill_invocation, get_skill_commands,
+ )
+ key = '/' + name
+ skills = get_skill_commands()
+ if key not in skills:
+ raise RuntimeStoreError('unsupported_command')
+ message = build_skill_invocation_message(key, arg, task_id=route)
+ if not message:
+ raise RuntimeStoreError('command_unavailable')
+ return {'type': 'skill', 'name': skills[key]['name'], 'message': message,
+ 'display': describe_skill_invocation(message, separator=' ')}
+
+
+async def _tui_read(authority, actor, ref, name, arg):
+ """Main's TUI sidecar text for a TUI session's /status, /context or /cron read, else None."""
+ from gateway.session_local import authorize_local_source
+ from gateway.session_policy import policy_for_source
+ from gateway.session_tui_reads import run_tui_read, tui_read
+ live = authority.sessions[ref.session_id]
+ if authorize_local_source(authority.runner, live.source) is not True:
+ return None
+ policy = policy_for_source(authority.runner, live.source)
+ render = tui_read(policy, name, arg)
+ if render is None:
+ return None
+ authority.authorize(actor, ref, 'session:read')
+ return await run_tui_read(authority, ref, live, policy, render, arg)
+
+
+@contextmanager
+def _session_workspace(runner, source):
+ """The session's frozen terminal policy (``TERMINAL_CWD`` = its launch cwd), so ``/diff``
+ reads the caller's checkout instead of the gateway process's configured directory."""
+ import json
+ from agent.runtime_cwd import reset_session_cwd, set_session_cwd
+ from gateway.session_policy import policy_for_source
+ from tools.terminal_scope import reset_terminal_scope, set_terminal_scope
+ policy = policy_for_source(runner, source)
+ if policy is None:
+ yield
+ return
+ cwd_token = set_session_cwd(policy.cwd)
+ terminal_token = set_terminal_scope(json.loads(policy.terminal_json))
+ try:
+ yield
+ finally:
+ reset_terminal_scope(terminal_token)
+ reset_session_cwd(cwd_token)
+
+
+async def execute_command(connection, ref, params, *, dispatch=False):
+ authority, actor = connection.authority, connection.actor
+ authority.authorize(actor, ref, 'session:read')
+ name, arg = _parse(params, dispatch)
+ from hermes_cli.commands import resolve_command
+ from hermes_cli.profiles import profile_matches_home
+ home = Path(authority.profile_id)
+ if params.get('profile') and not profile_matches_home(params['profile'], home):
+ raise RuntimeStoreError('profile_mismatch')
+
+ from gateway.run import _profile_runtime_scope
+ def resolve():
+ with _profile_runtime_scope(home):
+ return _resolve_alias(name, arg)
+ name, arg = await asyncio.to_thread(resolve)
+ definition = resolve_command(name)
+ canonical = definition.name if definition else name
+ verdict = command_verdict(canonical, arg) if definition else None
+ if definition is not None and (tui := await _tui_read(authority, actor, ref, canonical, arg)) is not None:
+ return tui
+ capability = ('session:read' if verdict == 'read' else
+ 'session:approve' if canonical in _APPROVAL_COMMANDS else
+ 'session:control' if definition else 'session:submit')
+ authority.authorize(actor, ref, capability)
+ if verdict == 'refused':
+ raise RuntimeStoreError('unsupported_command')
+ from gateway.session_local import authorize_local_source
+ live = authority.sessions[ref.session_id]
+ if authorize_local_source(authority.runner, live.source) is not True:
+ raise RuntimeStoreError('permission_denied')
+ if capability != 'session:read':
+ authority._require_admission_open()
+ if definition is None:
+ def build():
+ with _profile_runtime_scope(home):
+ return _skill_directive(name, arg, live.route)
+ return await asyncio.to_thread(build)
+
+ if canonical in _INFO_READS:
+ from gateway.session_info_reads import run_info_read
+ return await run_info_read(authority, live, canonical)
+
+ from gateway.platforms.base import MessageEvent
+ from gateway.session_command_sink import capture
+ typed = '/' + canonical + (' ' + arg if arg else '')
+ event = MessageEvent(text=typed, source=live.source)
+ runner = authority.runner
+ prompt = None
+ # Use the registry's existing busy contract, not a local approximation.
+ with _profile_runtime_scope(home), _session_workspace(runner, live.source), capture() as sink:
+ if authority._handle(ref).execution_state != 'idle':
+ output = await runner._dispatch_busy_slash_command(event, definition, live.route, live.source)
+ elif canonical in _PROMPT_COMMANDS:
+ handled, output = await getattr(runner, '_hm_cmd_' + canonical.replace('-', '_'))(
+ event, live.source, live.route)
+ if not handled:
+ prompt = event.text
+ else:
+ handler = runner._command_handler_table((canonical,))[canonical]
+ output = await handler(event)
+ if canonical in _APPROVAL_COMMANDS:
+ # Settle the answered prompt for every viewer now (`approval.settled`), as approval.respond does.
+ handle = authority._handle(ref)
+ live.controls.snapshot(ref.session_id, handle.execution_generation
+ if handle.execution_state == 'running' else None)
+ prompt = prompt if prompt is not None else sink.prompt
+ if prompt:
+ # The client submits the turn with its own durable input id; the gateway never does.
+ notice = '\n'.join(filter(None, [*sink.notices, str(output or '')]))
+ return {'type': 'send', 'message': prompt, 'display': sink.display or typed,
+ **({'notice': notice} if notice else {})}
+ return {'type': 'exec', 'output': '\n'.join(filter(None, [*sink.notices, _text(output)]))}
+
+
+def _text(output):
+ """A handler reply as text: ``/blueprint``'s result object carries it in ``.text``."""
+ return str(getattr(output, 'text', output) or '')
diff --cc hermes_cli/gateway_tools.py
index fd8f0e79989,00000000000..cb207e99d71
mode 100644,000000..100644
--- a/hermes_cli/gateway_tools.py
+++ b/hermes_cli/gateway_tools.py
@@@ -1,206 -1,0 +1,206 @@@
+"""The background-process registry main's classic CLI reads, served by the gateway session.
+
+On main the CLI process ran every ``terminal(background=true)`` itself, so the live-work dock,
+the status bar's ``⚙ N`` segment, ``/stop`` and the dock's tail view read
+``tools.process_registry`` in-process. Rewired, the processes run in the gateway: this view
+answers the same calls (``list_sessions`` / ``get`` / ``count_running`` / ``kill_process`` /
+``kill_all``) from the session's ``process.list`` / ``process.kill`` / ``process.stop`` verbs, so
+main's dock and command code render unchanged.
+
+Polling: the dock ticks once a second. The view only asks the gateway while it has a reason to
+(a tool finished since the last poll, or a listed process is still running or recently
+exited); the status bar reads the cached count and never blocks a repaint on an RPC.
+"""
+from __future__ import annotations
+
+import logging
+import threading
+import time
+
+from hermes_cli.gateway_client import GatewayClientError
+
+logger = logging.getLogger(__name__)
+
+_POLL_SECONDS = 1.0
+# A finished process stays interesting this long (main's dock RETAIN_SECONDS).
+_RETAIN_SECONDS = 60
+
+_view = None
+
+
+class _Proc:
+ """The ``ProcessSession`` attributes main's dock reads."""
+
+ def __init__(self, row):
+ self.id = row.get("session_id") or ""
+ self.command = row.get("command") or ""
+ self.exit_code = row.get("exit_code")
+ self.started_at = float(row.get("started_epoch") or 0.0)
+ self.exited_at = float(row.get("exited_at") or 0.0)
+ self.output_buffer = row.get("output_tail") or ""
+ self.completion_reason = row.get("completion_reason") or "exited"
+ self.exited = row.get("status") == "exited"
+
+
+class GatewayProcessView:
+ def __init__(self, agent):
+ self.agent = agent
+ self.connection = agent.connection
+ self.rows: list = []
+ self.dirty = True
+ self.delegations = 0
+ self._polled = 0.0
+ self._lock = threading.Lock()
+
+ @property
+ def session_id(self):
+ return self.agent.session_id # follows /new, /resume and compression rotations
+
+ # -- polling ---------------------------------------------------------------------------
+ def mark_dirty(self):
+ self.dirty = True
+
+ def _interesting(self, now):
+ return any(not p.exited or (p.exited_at and now - p.exited_at <= _RETAIN_SECONDS) for p in self.rows)
+
+ def refresh(self, *, force=False):
+ now = time.time()
+ if not force and (now - self._polled < _POLL_SECONDS or not (self.dirty or self._interesting(now))):
+ return
+ if not self._lock.acquire(blocking=False):
+ return
+ try:
+ self._polled = now
+ self.dirty = False
+ result = self.connection.call("process.list", session_id=self.session_id, timeout=5)
+ self.rows = [_Proc(row) for row in (result or {}).get("processes") or []]
+ except (GatewayClientError, RuntimeError) as exc:
+ logger.debug("process.list failed: %s", exc)
+ finally:
+ self._lock.release()
+
+ # -- the tools.process_registry surface main's CLI calls ---------------------------------
+ def list_sessions(self):
+ self.refresh()
+ now = time.time()
+ return [{"session_id": p.id, "command": p.command[:200],
+ "status": "exited" if p.exited else "running", "exit_code": p.exit_code,
+ "completion_reason": p.completion_reason if p.exited else None,
+ "uptime_seconds": int(now - p.started_at) if p.started_at else 0} for p in self.rows]
+
+ def get(self, process_id):
+ return next((p for p in self.rows if p.id == process_id), None)
+
+ def count_running(self):
+ """Cached (the status bar repaints off the render thread)."""
+ return sum(1 for p in self.rows if not p.exited)
+
+ def kill_process(self, process_id, **_kw):
+ try:
+ result = self.connection.call("process.kill", session_id=self.session_id, process_id=process_id)
+ except GatewayClientError as exc:
+ return {"status": "error", "error": str(exc)}
+ self.refresh(force=True)
+ return result
+
+ def kill_all(self, **_kw):
+ """``/stop``: the session's own processes plus its background delegations (``process.stop``)."""
+ result = self.connection.call("process.stop", session_id=self.session_id) or {}
+ self.delegations = int(result.get("delegations") or 0)
+ self.refresh(force=True)
+ return int(result.get("killed") or 0)
+
+ def interrupt_delegations(self):
+ """The delegation half of ``/stop`` (``kill_all`` already ran it when processes were live)."""
+ if self.delegations:
+ count, self.delegations = self.delegations, 0
+ return count
+ self.kill_all()
+ count, self.delegations = self.delegations, 0
+ return count
+
+ def active_delegations(self):
+ """Running background subagents (the gateway's ``session.usage.active_subagents``)."""
+ try:
+ usage = self.connection.state(self.session_id).usage or {}
+ except Exception: # health: allow BLE001 -- a missing usage cache reads as none running
+ return 0
+ value = usage.get("active_subagents")
+ return value if isinstance(value, int) else 0
+
+
+def bind(agent):
+ """Called when the CLI's gateway-backed agent is built."""
+ global _view
+ _view = GatewayProcessView(agent) if getattr(agent, "connection", None) is not None else None
+ return _view
+
+
+def mark_dirty():
+ if _view is not None:
+ _view.mark_dirty()
+
+
+def process_view():
+ """The gateway-backed registry, or None when this process runs its own tools (not rewired) or
+ its gateway connection is gone."""
+ view = _view
+ return view if view is not None and not view.connection.closed else None
+
+
+def process_registry():
+ """``tools.process_registry.process_registry`` for main's dock, status bar and ``/stop``."""
+ view = process_view()
+ if view is not None:
+ return view
+ from tools.process_registry import process_registry as local
+ return local
+
+
+def background_counts():
+ """The status bar's ``⚙ N`` processes and running background subagents (cached, no RPC)."""
+ view = process_view()
+ if view is not None:
+ return {"active_background_processes": view.count_running(),
+ "active_background_subagents": view.active_delegations()}
+ from tools.async_delegation import active_count
+ from tools.process_registry import process_registry as local
+ return {"active_background_processes": local.count_running(), "active_background_subagents": active_count()}
+
+
+def session_tools():
- """``/tools`` / ``/initiate-setup``: the gateway session's tool catalog (``tools.show``) as
++ """``/tools``: the gateway session's tool catalog (``tools.show``) as
+ ``(tools, toolset_of)``: ``get_tool_definitions``-shaped rows (first description sentence) and
+ a name -> toolset lookup. None when the CLI is not gateway-backed."""
+ view = process_view()
+ if view is None:
+ return None
+ result = view.connection.call("tools.show", session_id=view.session_id) or {}
+ tools, toolset_of = [], {}
+ for section in result.get("sections") or []:
+ for row in section.get("tools") or []:
+ toolset_of[row["name"]] = section.get("name")
+ tools.append({"type": "function", "function": {"name": row["name"],
+ "description": row.get("description") or ""}})
+ return tools, toolset_of.get
+
+
+def reload_gateway_skills():
+ """Rescan skills in the gateway session too (its skill-command map serves this session's
+ ``/<skill>`` and bundle invocations); the CLI's own rescan still drives main's output."""
+ view = process_view()
+ if view is None:
+ return None
+ try:
+ return (view.connection.call("skills.reload", session_id=view.session_id) or {}).get("result")
+ except GatewayClientError as exc:
+ logger.debug("skills.reload failed: %s", exc)
+ return None
+
+
+def handle_skills_slash(cmd, console):
+ """Main's ``/skills`` (hub search / install / uninstall write the local skills tree), then the
+ gateway's rescan so an install reaches the skill map the session's turns use."""
+ from hermes_cli.skills_hub import handle_skills_slash as local
+ local(cmd, console)
+ reload_gateway_skills()
diff --cc hermes_cli/web_server.py
index 47ad1e1491a,2c22cc36c2c..07900c04b25
--- a/hermes_cli/web_server.py
+++ b/hermes_cli/web_server.py
@@@ -176,7 -176,188 +176,20 @@@ def _start_desktop_cron_ticker(stop_eve
_DESKTOP_MCP_DISCOVERY_DELAY_S = 1.0
+ def _probe_install_before_state_db() -> None:
+ from hermes_cli.anon_auth import on_local_desktop_backend
+
+ if not on_local_desktop_backend():
+ return
+ try:
+ from hermes_cli.install_state import probe
+
+ probe()
+ except (OSError, ValueError): # what the probe's own guards leave; onboarding.state probes again
+ _log.warning("first-install check at boot failed", exc_info=True)
+
+
-@asynccontextmanager
-async def _lifespan(app: FastAPI):
- app.state.event_channels = {} # dict[str, set]
- app.state.event_lock = asyncio.Lock()
- app.state.pty_active_session_files = {} # dict[str, Path]
- # Serializes chat-argv resolution so concurrent /api/pty connections don't
- # overlap ``npm install`` / ``npm run build``. Locks live on app.state (not
- # module globals) so they bind to the running loop, not the import-time one.
- app.state.chat_argv_lock = asyncio.Lock()
-
- # Bring state.db schema current BEFORE the first session-list poll
- # (#79531/#80037): a store left behind by `hermes update` otherwise 500s
- # every poll while the read-probe heal loses to sibling lock contention.
- # Off-thread so a locked store never delays the socket (Desktop
- # ready-probe times out at 10s, GH-73083). NOT a daemon, and joined at
- # shutdown: its sqlite connection must be closed by the thread that is
- # stepping it. A daemon copy that outlived the lifespan had its
- # connection closed from the main thread mid-probe (pytest's leaked-DB
- # sweep) and segfaulted the interpreter. The worker is time-bounded by
- # SessionDB's lock patience, so the join cannot hang shutdown.
- # The first-install check reads the default root's state.db: on the desktop's own backend it runs
- # before this process starts creating or healing that database, and its answer is kept.
- _probe_install_before_state_db()
-
- eager_reconcile_thread = threading.Thread(
- target=_eager_reconcile_own_session_db,
- name="statedb-eager-reconcile",
- )
- eager_reconcile_thread.start()
-
- # Import hermes_cli.gateway *before* the yield: on Windows + 3.11 the
- # import holds the GIL, so run_in_executor still froze the loop 15-22s and
- # the Desktop's 10s ready-probe timed out (GH-73083).
- _warm_gateway_module()
-
- # Snapshot the checkout revision so lazy-import paths (model picker) can
- # refuse with "restart required" after `hermes update` replaced the code
- # (#86207); the update flow does not reliably restart the dashboard.
- from gateway.code_skew import record_boot_fingerprint
-
- record_boot_fingerprint()
-
- # Hosted Bot rooms belong to the backend process. Recovery may need a
- # contended state.db migration, so keep it off the pre-yield path: Group
- # Chat must degrade on its own rather than block every Desktop feature.
- from tui_gateway import methods_groups as _hosted_groups
- import tui_gateway.server
-
- try:
- tui_gateway.server.install_tui_message_injector()
- except Exception:
- _log.warning("TUI message injector did not install", exc_info=True)
-
- hosted_room_start_cancel = threading.Event()
-
- def _start_hosted_rooms() -> None:
- try:
- _hosted_groups.start_hosted_room_service()
- except Exception:
- _log.exception("Hosted Group Chat recovery failed during backend startup")
- finally:
- if hosted_room_start_cancel.is_set():
- _hosted_groups.stop_hosted_room_service(timeout=1.0)
-
- hosted_room_start_thread = threading.Thread(
- target=_start_hosted_rooms,
- daemon=True,
- name="hosted-room-startup",
- )
- hosted_room_start_thread.start()
-
- # Desktop-spawned backends fire cron jobs themselves, since the app has no
- # gateway running the scheduler. Server `hermes dashboard` is unaffected —
- # it relies on its own gateway.
- cron_stop: threading.Event | None = None
- cron_thread: threading.Thread | None = None
- desktop_owned = is_desktop_owned_backend()
- if desktop_owned:
- # Reap an orphaned gateway from an abnormal previous exit (reparented to
- # launchd, still holding the platform WebSocket) before forking a fresh
- # one that would race the same credential (#77276). Runs
- # unconditionally; protection of a healthy standalone gateway lives
- # INSIDE the reaper (registration probed with cleanup_stale=False).
- # Startup grace: spare a gateway still claiming gateway.pid/lock (#122533).
- try:
- from hermes_cli.dashboard_procs import _REAP_MIN_AGE_SECONDS
- from hermes_cli.gateway import _reap_unsupervised_gateway_orphans
-
- _reap_unsupervised_gateway_orphans(min_age_s=_REAP_MIN_AGE_SECONDS)
- except Exception:
- _log.exception("Desktop startup: orphan gateway reap failed")
-
- cron_stop = threading.Event()
- cron_thread = threading.Thread(
- target=_start_desktop_cron_ticker,
- args=(cron_stop,),
- daemon=True,
- name="desktop-cron-ticker",
- )
- cron_thread.start()
-
- # Reap idle/dead keep-alive PTY sessions (30-min TTL).
- pty_reaper_task = asyncio.create_task(run_reaper(PTY_REGISTRY))
- # Periodic authenticated self-test feeding the ``dashboard`` component on /api/status.
- selftest_task = asyncio.create_task(_dashboard_selftest_loop())
- # Live auto-archive timer, independent of list requests.
- auto_archive_task = asyncio.create_task(_auto_archive_ticker_loop())
-
- # Managed local runtime (local_runtime.enabled): bring llama-server back so a
- # restart doesn't strand a llamacpp main model. Off-thread and best-effort;
- # failure falls back to cloud providers like a cold start. Server only —
- # models load on first inference (an empty router holds no VRAM).
- def _boot_local_runtime():
- try:
- from hermes_cli.config import load_config
- from hermes_cli.local_runtime.bootstrap import ensure_local_runtime
-
- ensure_local_runtime(load_config())
- except Exception as exc:
- logging.getLogger(__name__).warning("local runtime boot failed: %s", exc)
-
- threading.Thread(target=_boot_local_runtime, daemon=True, name="local-runtime-boot").start()
-
- # Records who carries inference for setup.status / free_tier.status and broadcasts `setup.ready`
- # (no identity is created at boot). Off-thread; the desktop's first setup.status waits on the
- # record (bounded) instead.
- from hermes_cli.free_tier_bootstrap import start_background_bootstrap
-
- start_background_bootstrap()
- # The desktop's onboarding due answer, worked out after that bootstrap and before it is asked.
- # Through the server: methods_* functions run with the server's globals (``bind_module``).
- tui_gateway.server.start_due_boot()
-
- try:
- yield
- finally:
- try:
- tui_gateway.server.clear_tui_message_injector()
- except Exception:
- _log.debug("TUI message injector clear skipped", exc_info=True)
- hosted_room_start_cancel.set()
- _hosted_groups.stop_hosted_room_service(timeout=5.0)
- hosted_room_start_thread.join(timeout=1.0)
- if cron_stop is not None:
- cron_stop.set()
- pty_reaper_task.cancel()
- selftest_task.cancel()
- auto_archive_task.cancel()
- await PTY_REGISTRY.close_all()
-
- # PtySession.close() removes markers owned by live registry sessions.
- # This second pass cleans any channel markers left in app state,
- # including stale paths from sessions reaped earlier.
- for marker in set(_get_pty_active_session_files(app).values()):
- try:
- marker.unlink(missing_ok=True)
- except OSError:
- pass
-
- # Stop the managed llama-server with its parent (an orphan pins VRAM).
- try:
- from hermes_cli.local_runtime.bootstrap import shutdown_local_runtime
-
- shutdown_local_runtime()
- except Exception:
- pass
- if desktop_owned:
- _terminate_desktop_managed_gateway()
- eager_reconcile_thread.join()
+from hermes_cli.web_server_app import app_lifespan
def _app_state_default(app: FastAPI, name: str, factory):
diff --cc hermes_cli/web_server_app.py
index abd93f67def,00000000000..98099ff5774
mode 100644,000000..100644
--- a/hermes_cli/web_server_app.py
+++ b/hermes_cli/web_server_app.py
@@@ -1,227 -1,0 +1,233 @@@
+"""HTTP lifespan composition; standalone backend services remain opt-in owners."""
+
+from contextlib import asynccontextmanager
+import asyncio
+import logging
+import os
+import threading
+
+from fastapi import FastAPI
+from hermes_cli.pty_session import run_reaper
+
+logger = logging.getLogger("hermes_cli.web_server")
+
+
+def _unlink_pty_markers(app: FastAPI) -> None:
+ """Second pass after ``PTY_REGISTRY.close_all()``: drop channel markers left in app state,
+ including stale paths from sessions reaped earlier (``PtySession.close()`` only removes
+ markers owned by live registry sessions)."""
+ from hermes_cli.web_server import _get_pty_active_session_files
+
+ for marker in set(_get_pty_active_session_files(app).values()):
+ try:
+ marker.unlink(missing_ok=True)
+ except OSError:
+ pass
+
+
+@asynccontextmanager
+async def standalone_lifespan(app: "FastAPI"):
+ from hermes_cli.web_server import (
+ _eager_reconcile_own_session_db, _warm_gateway_module,
+ _start_desktop_cron_ticker, _dashboard_selftest_loop,
- _auto_archive_ticker_loop, _terminate_desktop_managed_gateway,
++ _auto_archive_ticker_loop, _terminate_desktop_managed_gateway, _probe_install_before_state_db,
+ )
+ from hermes_cli.web_server_chat import PTY_REGISTRY
+
+ app.state.event_channels = {} # dict[str, set]
+ app.state.event_lock = asyncio.Lock()
+ app.state.pty_active_session_files = {} # dict[str, Path]
+ # Serializes chat-argv resolution so concurrent /api/pty connections don't
+ # overlap ``npm install`` / ``npm run build``. Locks live on app.state (not
+ # module globals) so they bind to the running loop, not the import-time one.
+ app.state.chat_argv_lock = asyncio.Lock()
+
+ # Bring state.db schema current BEFORE the first session-list poll
+ # (#79531/#80037): a store left behind by `hermes update` otherwise 500s
+ # every poll until its owner completes schema reconciliation.
+ # Off-thread so a locked store never delays the socket (Desktop
+ # ready-probe times out at 10s, GH-73083). NOT a daemon, and joined at
+ # shutdown: its sqlite connection must be closed by the thread that is
+ # stepping it. A daemon copy that outlived the lifespan had its
+ # connection closed from the main thread mid-probe (pytest's leaked-DB
+ # sweep) and segfaulted the interpreter. The worker is time-bounded by
+ # SessionDB's lock patience, so the join cannot hang shutdown.
++ # The first-install check reads the default root's state.db: on the desktop's own backend it runs
++ # before this process starts creating or healing that database, and its answer is kept.
++ _probe_install_before_state_db()
++
+ eager_reconcile_thread = threading.Thread(
+ target=_eager_reconcile_own_session_db,
+ name="statedb-eager-reconcile",
+ )
+ eager_reconcile_thread.start()
+
+ # Import hermes_cli.gateway *before* the yield: on Windows + 3.11 the
+ # import holds the GIL, so run_in_executor still froze the loop 15-22s and
+ # the Desktop's 10s ready-probe timed out (GH-73083).
+ _warm_gateway_module()
+
+ # Snapshot the checkout revision so lazy-import paths (model picker) can
+ # refuse with "restart required" after `hermes update` replaced the code
+ # (#86207); the update flow does not reliably restart the dashboard.
+ from gateway.code_skew import record_boot_fingerprint
+
+ record_boot_fingerprint()
+
+ # Hosted Bot rooms belong to the backend process. Recovery may need a
+ # contended state.db migration, so keep it off the pre-yield path: Group
+ # Chat must degrade on its own rather than block every Desktop feature.
+ from tui_gateway import methods_groups as _hosted_groups
+ import tui_gateway.server
+
+ try:
+ tui_gateway.server.install_tui_message_injector()
+ except Exception:
+ logger.warning("TUI message injector did not install", exc_info=True)
+
+ hosted_room_start_cancel = threading.Event()
+
+ def _start_hosted_rooms() -> None:
+ try:
+ _hosted_groups.start_hosted_room_service()
+ except Exception:
+ logger.exception("Hosted Group Chat recovery failed during backend startup")
+ finally:
+ if hosted_room_start_cancel.is_set():
+ _hosted_groups.stop_hosted_room_service(timeout=1.0)
+
+ hosted_room_start_thread = threading.Thread(
+ target=_start_hosted_rooms,
+ daemon=True,
+ name="hosted-room-startup",
+ )
+ hosted_room_start_thread.start()
+
+ # Desktop-spawned backends fire cron jobs themselves, since the app has no
+ # gateway running the scheduler. Server `hermes dashboard` is unaffected —
+ # it relies on its own gateway.
+ from hermes_cli.process_identity import is_desktop_owned_backend
+ cron_stop: threading.Event | None = None
+ cron_thread: threading.Thread | None = None
+ desktop_owned = is_desktop_owned_backend()
+ if desktop_owned:
+ # Reap an orphaned gateway from an abnormal previous exit (reparented to
+ # launchd, still holding the platform WebSocket) before forking a fresh
+ # one that would race the same credential (#77276). Runs
+ # unconditionally; protection of a healthy standalone gateway lives
+ # INSIDE the reaper (registration probed with cleanup_stale=False).
+ # Startup grace: spare a gateway still claiming gateway.pid/lock (#122533).
+ try:
+ from hermes_cli.dashboard_procs import _REAP_MIN_AGE_SECONDS
+ from hermes_cli.gateway import _reap_unsupervised_gateway_orphans
+
+ _reap_unsupervised_gateway_orphans(min_age_s=_REAP_MIN_AGE_SECONDS)
+ except Exception:
+ logger.exception("Desktop startup: orphan gateway reap failed")
+
+ cron_stop = threading.Event()
+ cron_thread = threading.Thread(
+ target=_start_desktop_cron_ticker,
+ args=(cron_stop,),
+ daemon=True,
+ name="desktop-cron-ticker",
+ )
+ cron_thread.start()
+
+ # Reap idle/dead keep-alive PTY sessions (30-min TTL).
+ pty_reaper_task = asyncio.create_task(run_reaper(PTY_REGISTRY))
+ # Periodic authenticated self-test feeding the ``dashboard`` component on /api/status.
+ selftest_task = asyncio.create_task(_dashboard_selftest_loop())
+ # Live auto-archive timer, independent of list requests.
+ auto_archive_task = asyncio.create_task(_auto_archive_ticker_loop())
+
+ # Managed local runtime (local_runtime.enabled): bring llama-server back so a
+ # restart doesn't strand a llamacpp main model. Off-thread and best-effort;
+ # failure falls back to cloud providers like a cold start. Server only —
+ # models load on first inference (an empty router holds no VRAM).
+ def _boot_local_runtime():
+ try:
+ from hermes_cli.config import load_config
+ from hermes_cli.local_runtime.bootstrap import ensure_local_runtime
+
+ ensure_local_runtime(load_config())
+ except Exception as exc:
+ logging.getLogger(__name__).warning("local runtime boot failed: %s", exc)
+
+ threading.Thread(target=_boot_local_runtime, daemon=True, name="local-runtime-boot").start()
+
- # Nous free tier: the one boot-time creator of its identity. Inventories credentials, mints only
- # when HERMES_GUEST_ONBOARDING=1, records the answer for setup.status / free_tier.status and
- # broadcasts `setup.ready`. Off-thread so a slow portal never delays the socket; the desktop's
- # first setup.status waits on the record (bounded) instead.
++ # Records who carries inference for setup.status / free_tier.status and broadcasts `setup.ready`
++ # (no identity is created at boot). Off-thread; the desktop's first setup.status waits on the
++ # record (bounded) instead.
+ from hermes_cli.free_tier_bootstrap import start_background_bootstrap
+
+ start_background_bootstrap()
++ # The desktop's onboarding due answer, worked out after that bootstrap and before it is asked.
++ # Through the server: methods_* functions run with the server's globals (``bind_module``).
++ tui_gateway.server.start_due_boot()
+
+ try:
+ yield
+ finally:
+ try:
+ tui_gateway.server.clear_tui_message_injector()
+ except Exception:
+ logger.debug("TUI message injector clear skipped", exc_info=True)
+ hosted_room_start_cancel.set()
+ _hosted_groups.stop_hosted_room_service(timeout=5.0)
+ hosted_room_start_thread.join(timeout=1.0)
+ if cron_stop is not None:
+ cron_stop.set()
+ pty_reaper_task.cancel()
+ selftest_task.cancel()
+ auto_archive_task.cancel()
+ eager_reconcile_thread.join()
+ await PTY_REGISTRY.close_all()
+
+ # PtySession.close() removes markers owned by live registry sessions.
+ # This second pass cleans any channel markers left in app state,
+ # including stale paths from sessions reaped earlier.
+ _unlink_pty_markers(app)
+
+ # Stop the managed llama-server with its parent (an orphan pins VRAM).
+ try:
+ from hermes_cli.local_runtime.bootstrap import shutdown_local_runtime
+
+ shutdown_local_runtime()
+ except Exception:
+ # Shutdown boundary: a supervisor that fails to stop must not skip the
+ # managed-gateway teardown below; log it so the orphan is diagnosable.
+ logger.warning("managed local runtime shutdown failed", exc_info=True)
+ if desktop_owned:
+ _terminate_desktop_managed_gateway()
+
+
+@asynccontextmanager
+async def http_lifespan(app: FastAPI):
+ """The gateway already owns schema, rooms, scheduler and model services."""
+ from hermes_cli.web_server import _dashboard_selftest_loop
+ from hermes_cli.web_server_chat import PTY_REGISTRY
+
+ app.state.event_channels = {}
+ app.state.event_lock = asyncio.Lock()
+ app.state.pty_active_session_files = {}
+ app.state.chat_argv_lock = asyncio.Lock()
+ tasks = [
+ asyncio.create_task(run_reaper(PTY_REGISTRY), name="gateway-api-pty-reaper"),
+ asyncio.create_task(_dashboard_selftest_loop(), name="gateway-api-selftest"),
+ ]
+ try:
+ yield
+ finally:
+ for task in tasks:
+ task.cancel()
+ await asyncio.gather(*tasks, return_exceptions=True)
+ await PTY_REGISTRY.close_all()
+ _unlink_pty_markers(app)
+
+
+@asynccontextmanager
+async def app_lifespan(app: FastAPI):
+ lifespan = http_lifespan if getattr(app.state, "gateway_runner", None) is not None else standalone_lifespan
+ async with lifespan(app):
+ yield
diff --cc hermes_state_compression.py
index 1395d6d36ef,49d02ded151..3d54d537ce8
--- a/hermes_state_compression.py
+++ b/hermes_state_compression.py
@@@ -217,10 -241,11 +241,14 @@@ class SessionCompressionMixin
"""INSERT the compression child's ``sessions`` row copied from *parent*. Same contract as
_insert_session_row's compression-fork backfill: the child stays on the parent's profile and keeps
gateway routing/origin columns; no owner on either side -> this store's profile."""
+ from hermes_state_sessions import _parse_model_config
+ carried = {key: value for key, value in _parse_model_config(parent["model_config"]).items()
+ if key in _CONVERSATION_MODEL_CONFIG_KEYS}
+ model_config = {**carried, **(model_config or {})}
system_prompt_hash = self._store_system_prompt(conn, system_prompt)
+ # Pin/archive are compression-lineage flags; canonical branch/reset verbs also publish through
+ # here, and their child is its own conversation, so it starts unpinned and visible.
+ continuation = not any(k in (model_config or {}) for k in ("_branched_from", "_reset_from"))
# The child continues the parent's tools[] pin (the compaction refresh re-pinned it just
# before publish), or its first hop to another surface re-derives the array.
conn.execute(
@@@ -269,93 -293,77 +297,93 @@@
See #75316.
``None`` = unbounded (no internal flush happened). See #47202.
"""
+ self._execute_transcript_write(lambda conn: self._publish_compression_child_on_conn(
+ conn, parent_session_id=parent_session_id, child_session_id=child_session_id, source=source,
+ messages=messages, model=model, model_config=model_config, system_prompt=system_prompt,
+ cwd=cwd, profile_name=profile_name, compression_lock_holder=compression_lock_holder,
+ require_compression_lease=require_compression_lease, require_lease_refresh=require_lease_refresh,
+ lease_ttl_seconds=lease_ttl_seconds, watermark=watermark, watermark_ceiling=watermark_ceiling), messages)
+
+ def _publish_compression_child_on_conn(
+ self, conn, *, parent_session_id: str, child_session_id: str, source: str,
+ messages: list[dict[str, Any]], model: str | None = None, model_config: dict[str, Any] | None = None,
+ system_prompt: str | None = None, cwd: str | None = None, profile_name: str | None = None,
+ compression_lock_holder: str | None = None, require_compression_lease: bool = True,
+ require_lease_refresh: bool = False, lease_ttl_seconds: float = 300.0,
+ watermark: Optional[int] = None, watermark_ceiling: Optional[int] = None) -> None:
+ """:meth:`publish_compression_child` on the caller's write transaction (never commits). The
+ owner and the worker/canonical-mutation verbs share this one body so they cannot drift."""
from hermes_state_errors import CompressionSessionBusyError
- def _do(conn):
- if require_lease_refresh and compression_lock_holder:
- conn.execute(
- "UPDATE compression_locks SET expires_at = ? WHERE session_id = ? AND holder = ?",
- (time.time() + lease_ttl_seconds, parent_session_id, compression_lock_holder))
- lock_row = conn.execute(_LOCK_ROW_SQL, (parent_session_id,)).fetchone()
- if require_compression_lease and (
- lock_row is None or not compression_lock_holder
- or lock_row["holder"] != compression_lock_holder
- or float(lock_row["expires_at"]) <= time.time()
- ):
- raise CompressionSessionBusyError(
- f"Compression lease lost before publication: {parent_session_id}")
- parent = conn.execute(
- """SELECT ended_at, end_reason, cwd, git_branch, git_repo_root,
- user_id, session_key, chat_id, chat_type,
- thread_id, display_name, origin_json, profile_name, tool_names,
- archived, auto_archived, pinned, model_config
- FROM sessions WHERE id = ?""",
- (parent_session_id,),
- ).fetchone()
- if parent is None:
- raise RuntimeError(f"Compression parent not found: {parent_session_id}")
- if parent["ended_at"] is not None:
- # An AUTOMATIC end stamp (tui_shutdown, ws_disconnect, orphan reap, idle/LRU
- # evict) is stale by construction — this lease holder is still continuing the
- # conversation, and left alone it wedges rotation forever. Clear it; the closure
- # UPDATE below re-stamps end_reason='compression'. Deliberate boundaries fail closed.
- if not is_automatic_end_reason(parent["end_reason"]):
- raise RuntimeError(f"Compression parent already ended: {parent_session_id}")
- conn.execute(
- "UPDATE sessions SET ended_at = NULL, end_reason = NULL WHERE id = ?",
- (parent_session_id,))
- if not messages:
- raise RuntimeError("Compression child handoff must not be empty")
- self._publish_child_session_row(
- conn, parent, parent_session_id=parent_session_id, child_session_id=child_session_id,
- source=source, model=model, model_config=model_config, system_prompt=system_prompt,
- cwd=cwd, profile_name=profile_name)
- # Carried handoff tail rows arrive without a timestamp and would otherwise be stamped
- # `now`, breaking their _display_dedupe_key identity with the parent's durable originals
- # and duplicating them in the lineage display read (#59661).
- self._carry_parent_timestamps(conn, parent_session_id, messages)
- total_messages, total_tool_calls = self._insert_message_rows(conn, child_session_id, messages)
- if watermark is not None:
- # Clone the parent's concurrent tail into the child after the handoff;
- # originals stay in the closed parent for lineage recovery.
- bounded = watermark_ceiling is not None
- tail_ids, tail_tool_calls = self._tail_rows_after_watermark(
- conn, "SELECT id, tool_calls FROM messages "
- "WHERE session_id = ? AND active = 1 AND id > ?"
- f"{' AND id <= ?' if bounded else ''} ORDER BY id",
- [parent_session_id, int(watermark), *([int(watermark_ceiling)] if bounded else [])])
- if tail_ids:
- self._clone_message_rows(conn, tail_ids, session_id=child_session_id)
- total_messages += len(tail_ids)
- total_tool_calls += tail_tool_calls
+ if require_lease_refresh and compression_lock_holder:
conn.execute(
- "UPDATE sessions SET message_count = ?, tool_call_count = ? WHERE id = ?",
- (total_messages, total_tool_calls, child_session_id))
- updated = conn.execute(
- "UPDATE sessions SET ended_at = ?, end_reason = 'compression' "
- "WHERE id = ? AND ended_at IS NULL", (time.time(), parent_session_id))
- if updated.rowcount != 1:
- raise RuntimeError(f"Compression parent changed during publication: {parent_session_id}")
- if parent["archived"]:
- # A live continuation under an idle-sweep archive re-activates the chat; after the
- # closure above the child is linked into the lineage walk (#117713).
- self._unarchive_auto_archived_lineage(conn, child_session_id)
- self._execute_transcript_write(_do, messages)
+ "UPDATE compression_locks SET expires_at = ? WHERE session_id = ? AND holder = ?",
+ (time.time() + lease_ttl_seconds, parent_session_id, compression_lock_holder))
+ lock_row = conn.execute(_LOCK_ROW_SQL, (parent_session_id,)).fetchone()
+ if require_compression_lease and (
+ lock_row is None or not compression_lock_holder
+ or lock_row["holder"] != compression_lock_holder
+ or float(lock_row["expires_at"]) <= time.time()
+ ):
+ raise CompressionSessionBusyError(
+ f"Compression lease lost before publication: {parent_session_id}")
+ parent = conn.execute(
+ """SELECT ended_at, end_reason, cwd, git_branch, git_repo_root,
+ user_id, session_key, chat_id, chat_type,
+ thread_id, display_name, origin_json, profile_name, tool_names,
- archived, auto_archived, pinned
++ archived, auto_archived, pinned, model_config
+ FROM sessions WHERE id = ?""",
+ (parent_session_id,),
+ ).fetchone()
+ if parent is None:
+ raise RuntimeError(f"Compression parent not found: {parent_session_id}")
+ if parent["ended_at"] is not None:
+ # An AUTOMATIC end stamp (tui_shutdown, ws_disconnect, orphan reap, idle/LRU
+ # evict) is stale by construction — this lease holder is still continuing the
+ # conversation, and left alone it wedges rotation forever. Clear it; the closure
+ # UPDATE below re-stamps end_reason='compression'. Deliberate boundaries fail closed.
+ if not is_automatic_end_reason(parent["end_reason"]):
+ raise RuntimeError(f"Compression parent already ended: {parent_session_id}")
+ conn.execute(
+ "UPDATE sessions SET ended_at = NULL, end_reason = NULL WHERE id = ?",
+ (parent_session_id,))
+ if not messages:
+ raise RuntimeError("Compression child handoff must not be empty")
+ self._publish_child_session_row(
+ conn, parent, parent_session_id=parent_session_id, child_session_id=child_session_id,
+ source=source, model=model, model_config=model_config, system_prompt=system_prompt,
+ cwd=cwd, profile_name=profile_name)
+ # Carried handoff tail rows arrive without a timestamp and would otherwise be stamped
+ # `now`, breaking their _display_dedupe_key identity with the parent's durable originals
+ # and duplicating them in the lineage display read (#59661).
+ self._carry_parent_timestamps(conn, parent_session_id, messages)
+ total_messages, total_tool_calls = self._insert_message_rows(conn, child_session_id, messages)
+ if watermark is not None:
+ # Clone the parent's concurrent tail into the child after the handoff;
+ # originals stay in the closed parent for lineage recovery.
+ bounded = watermark_ceiling is not None
+ tail_ids, tail_tool_calls = self._tail_rows_after_watermark(
+ conn, "SELECT id, tool_calls FROM messages "
+ "WHERE session_id = ? AND active = 1 AND id > ?"
+ f"{' AND id <= ?' if bounded else ''} ORDER BY id",
+ [parent_session_id, int(watermark), *([int(watermark_ceiling)] if bounded else [])])
+ if tail_ids:
+ self._clone_message_rows(conn, tail_ids, session_id=child_session_id)
+ total_messages += len(tail_ids)
+ total_tool_calls += tail_tool_calls
+ conn.execute(
+ "UPDATE sessions SET message_count = ?, tool_call_count = ? WHERE id = ?",
+ (total_messages, total_tool_calls, child_session_id))
+ updated = conn.execute(
+ "UPDATE sessions SET ended_at = ?, end_reason = 'compression' "
+ "WHERE id = ? AND ended_at IS NULL", (time.time(), parent_session_id))
+ if updated.rowcount != 1:
+ raise RuntimeError(f"Compression parent changed during publication: {parent_session_id}")
+ from hermes_state_local_lineage import advance_local_target
+ advance_local_target(conn, parent_session_id, child_session_id)
+ if parent["archived"]:
+ # A live continuation under an idle-sweep archive re-activates the chat; after the
+ # closure above the child is linked into the lineage walk (#117713).
+ self._unarchive_auto_archived_lineage(conn, child_session_id)
def _write_sql_logged(self, op: str, session_id: str, sql: str, params) -> None:
"""``_write_sql`` that logs (never raises) on ``sqlite3.Error``."""
diff --cc package-lock.json
index 4f7a056971a,dfc028f5c32..262f32e1b60
--- a/package-lock.json
+++ b/package-lock.json
@@@ -185,9 -185,8 +185,9 @@@
"tsx": "4.23.1",
"typescript": "6.0.3",
"vite": "8.2.0",
- "vitest": "4.1.10",
+ "vitest": "4.1.11",
- "wait-on": "9.0.10"
+ "wait-on": "9.0.10",
+ "ws": "8.21.1"
},
"engines": {
"node": "^22.22.0 || ^24.11.0 || >=26.0.0"
diff --cc tests/gateway/test_session_authoring_commands.py
index a9686ba085a,00000000000..71f92508846
mode 100644,000000..100644
--- a/tests/gateway/test_session_authoring_commands.py
+++ b/tests/gateway/test_session_authoring_commands.py
@@@ -1,226 -1,0 +1,223 @@@
+"""Authoring/workflow slash commands run the messaging gateway's own handler for a LOCAL session.
+
- ``slash.exec`` on a real daemon: /plan /learn /init /initiate-setup /moa /blueprint answer with
++``slash.exec`` on a real daemon: /plan /learn /init /moa /blueprint answer with
+the turn the messaging gateway would have rewritten (a ``send`` directive the client submits with
+its own input id; nothing is admitted by the gateway), /goal sets the session's goal row and
+returns its kickoff the same way, /subgoal /loop /heartbeat write the session's own row, /review
+/refine answer from the session's cached agent, /curator /egress print their report.
+"""
+import asyncio
+import json
+from http.server import ThreadingHTTPServer
+from pathlib import Path
+import signal
+import sqlite3
+import threading
+import time
+
+import pytest
+
+from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon, rpc, websocket
+
+
+def test_local_session_authoring_commands_run_the_gateway_handler(tmp_path):
+ root = Path(__file__).resolve().parents[2]
+ home, user, work = tmp_path / 'state', tmp_path / 'user', tmp_path / 'work'
+ home.mkdir(mode=0o700)
+ user.mkdir()
+ work.mkdir()
+ (work / 'AGENTS.md').write_text('# existing instructions\n')
+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)
+ peer.requests = []
+ peer.blocked, peer.release = threading.Event(), threading.Event()
+ thread = threading.Thread(target=peer.serve_forever, daemon=True)
+ thread.start()
+ url = f'http://127.0.0.1:{peer.server_port}/v1'
+ config = json.dumps({'gateway': {'multiplex_profiles': False},
+ 'model': {'provider': 'custom', 'default': 'authoring-model', 'base_url': url},
+ 'auxiliary': {'title_generation': {'enabled': False}}})
+ (home / 'config.yaml').write_text(config)
+ env = child_env()
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url, PYTHONUNBUFFERED='1')
+ out, sid = {}, {}
+
+ def admissions():
+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:
+ return [r[0] for r in db.execute('SELECT request_id FROM session_admissions')]
+
+ def meta(key):
+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:
+ row = db.execute('SELECT value FROM state_meta WHERE key = ?', (key,)).fetchone()
+ return json.loads(row[0]) if row else None
+
+ async def probe(desc):
+ async with websocket(home, desc) as ws:
+ created = await rpc(ws, 'session.create', request_id='authoring', source='cli', toolsets=[],
+ cwd=str(work))
+ sid['id'] = created['result']['session_id']
+ info = (await rpc(ws, 'session.info', session_id=sid['id']))['result']
+ sid['row'] = info.get('stored_session_id') or sid['id']
+ # Before any turn: /review and /refine have no cached agent yet.
+ for command in ('review', 'refine'):
+ out['cold ' + command] = await exec_(ws, command)
+ await rpc(ws, 'prompt.submit', session_id=sid['id'], input_id='warm', text='WARM_AUTHORING')
+ deadline = time.monotonic() + 45
+ while True:
+ snap = (await rpc(ws, 'session.resume', session_id=sid['id']))['result']
+ if not snap['running'] and not snap['pending'] and 'RECOVERY_ACK_WARM_AUTHORING' in json.dumps(
+ snap['messages']):
+ break
+ assert time.monotonic() < deadline, ('warm turn never settled', snap)
+ await asyncio.sleep(.1)
+ out['admitted before'] = admissions()
+ # Before /moa: its one-shot model swap evicts the cached agent (messaging behaviour).
+ out['refine focus on naming'] = await exec_(ws, 'refine focus on naming')
- for command in ('plan add a cache', 'learn', 'init', 'initiate-setup', 'moa', 'moa compare',
++ for command in ('plan add a cache', 'learn', 'init', 'moa', 'moa compare',
+ 'blueprint', 'egress', 'curator', 'goal ship the cache', 'subgoal add tests',
+ 'goal status', 'loop every 30m check the queue', 'loop', 'heartbeat every 10m ping',
+ 'heartbeat', 'goal clear', 'loop clear', 'heartbeat clear'):
+ out[command] = await exec_(ws, command)
+ out['admitted after'] = admissions()
+
+ async def exec_(ws, command):
+ try:
+ reply = await rpc(ws, 'slash.exec', session_id=sid['id'], command=command)
+ except TimeoutError:
+ raise AssertionError(f'slash.exec {command!r} did not answer within the rpc bound') from None
+ return reply.get('result') or reply.get('error')
+
+ try:
+ with daemon(root, home, env, barrier=False) as (proc, desc):
+ asyncio.run(probe(desc))
+ proc.send_signal(signal.SIGINT)
+ proc.wait(timeout=20)
+ finally:
+ peer.shutdown()
+ peer.server_close()
+ thread.join(timeout=5)
+
+ def send(command):
+ reply = out[command]
+ assert reply.get('type') == 'send' and reply.get('message'), (command, reply)
+ return reply
+
+ # Prompt builders: the messaging gateway's rewritten turn, returned for the client to submit.
+ plan = send('plan add a cache')
+ assert 'add a cache' in plan['message'] and plan['display'] == '/plan add a cache', plan
+ assert 'add a cache' in plan.get('notice', ''), plan
+ assert send('learn')['notice'], out['learn']
+ init = send('init')
+ assert str(work) in init['message'] and 'UPDATE the existing AGENTS.md' in init['message'], init
- setup = send('initiate-setup')
- # The session's own surface (a `cli` launch runs the cli surface), not the LOCAL transport name.
- assert setup['notice'] and '"surface": "cli"' in setup['message'], setup
+ assert send('moa compare')['message'] == 'compare', out['moa compare']
+ assert out['moa']['type'] == 'exec' and '/moa' in out['moa']['output'], out['moa']
+ assert out['blueprint']['type'] == 'exec' and out['blueprint']['output'], out['blueprint']
+ assert out['egress']['type'] == 'exec' and out['egress']['output'], out['egress']
+ assert out['curator']['type'] == 'exec' and 'curator' in out['curator']['output'].lower(), out['curator']
+ # /goal: the session's own goal row, and its kickoff returned (never self-admitted).
+ goal = send('goal ship the cache')
+ assert 'ship the cache' in goal['message'] and 'ship the cache' in goal['notice'], goal
+ assert 'add tests' in out['subgoal add tests']['output'], out['subgoal add tests']
+ assert 'ship the cache' in out['goal status']['output'], out['goal status']
+ # Nothing the commands returned was admitted by the gateway; /loop's first wake (fires now) is the
+ # loop scheduler's own producer admission, not a command's.
+ added = [r for r in out['admitted after'] if r not in out['admitted before'] and not r.startswith('["loop-tick"')]
+ assert added == [], added
+ # /loop, /heartbeat: state on the session's row.
+ assert '30m' in out['loop every 30m check the queue']['output'], out['loop every 30m check the queue']
+ assert 'check the queue' in out['loop']['output'], out['loop']
+ assert 'ping' in out['heartbeat every 10m ping']['output'], out['heartbeat every 10m ping']
+ assert 'ping' in out['heartbeat']['output'], out['heartbeat']
+ # /review and /refine: the session's cached agent (none before the first turn).
+ for command in ('review', 'refine'):
+ assert out['cold ' + command]['type'] == 'exec', out['cold ' + command]
+ assert out['refine focus on naming']['type'] == 'exec', out['refine focus on naming']
+ assert 'naming' in out['refine focus on naming']['output'], out['refine focus on naming']
+ for command in ('goal clear', 'loop clear', 'heartbeat clear'):
+ assert out[command]['type'] == 'exec' and out[command]['output'], (command, out[command])
+ assert (home / 'config.yaml').read_text() == config
+
+
+class _JudgeModel(Model):
+ """Echo model whose goal-judge calls answer ``continue`` once, then ``done``."""
+
+ def do_POST(self):
+ body = json.loads(self.rfile.read(int(self.headers['Content-Length'])))
+ text = json.dumps(body.get('messages', []))
+ if 'goal' in text.lower() and 'judge' in text.lower():
+ self.server.verdicts += 1
+ content = json.dumps({'done': self.server.verdicts > 1, 'reason': 'probe verdict'})
+ else:
+ content = 'ACK'
+ message = {'role': 'assistant', 'content': content}
+ if body.get('stream'):
+ payload = ('data: ' + json.dumps({'id': 'j', 'choices': [
+ {'index': 0, 'delta': message, 'finish_reason': 'stop'}]}) + '\n\ndata: [DONE]\n\n').encode()
+ kind = 'text/event-stream'
+ else:
+ payload = json.dumps({'id': 'j', 'choices': [{'index': 0, 'message': message, 'finish_reason': 'stop'}],
+ 'usage': {'prompt_tokens': 1, 'completion_tokens': 1, 'total_tokens': 2}}).encode()
+ kind = 'application/json'
+ self.send_response(200)
+ self.send_header('Content-Type', kind)
+ self.send_header('Content-Length', str(len(payload)))
+ self.end_headers()
+ self.wfile.write(payload)
+
+
+def test_local_goal_kickoff_is_judged_and_continued_by_the_gateway(tmp_path):
+ """The client submits /goal's kickoff; the gateway's post-turn judge then admits the continuation
+ into the session's own FIFO (the local adapter has no FIFO reader) until the judge says done."""
+ root = Path(__file__).resolve().parents[2]
+ home, user, work = tmp_path / 'state', tmp_path / 'user', tmp_path / 'work'
+ home.mkdir(mode=0o700)
+ user.mkdir()
+ work.mkdir()
+ peer = ThreadingHTTPServer(('127.0.0.1', 0), _JudgeModel)
+ peer.verdicts = 0
+ thread = threading.Thread(target=peer.serve_forever, daemon=True)
+ thread.start()
+ url = f'http://127.0.0.1:{peer.server_port}/v1'
+ (home / 'config.yaml').write_text(json.dumps({
+ 'gateway': {'multiplex_profiles': False}, 'model': {'provider': 'custom', 'default': 'm', 'base_url': url},
+ 'auxiliary': {'title_generation': {'enabled': False}}}))
+ env = child_env()
+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),
+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url, PYTHONUNBUFFERED='1')
+ out = {}
+
+ async def probe(desc):
+ async with websocket(home, desc) as ws:
+ sid = (await rpc(ws, 'session.create', request_id='goal', source='tui', toolsets=[],
+ cwd=str(work)))['result']['session_id']
+ kickoff = (await rpc(ws, 'slash.exec', session_id=sid, command='goal write the probe'))['result']
+ await rpc(ws, 'prompt.submit', session_id=sid, input_id='kick', text=kickoff['message'])
+ deadline = time.monotonic() + 60
+ while True:
+ status = (await rpc(ws, 'slash.exec', session_id=sid, command='goal status'))['result']['output']
+ if status.startswith('✓'):
+ break
+ assert time.monotonic() < deadline, status
+ await asyncio.sleep(.2)
+ out['status'] = status
+ out['messages'] = (await rpc(ws, 'session.resume', session_id=sid))['result']['messages']
+ try:
+ with daemon(root, home, env, barrier=False) as (proc, desc):
+ asyncio.run(probe(desc))
+ proc.send_signal(signal.SIGINT)
+ proc.wait(timeout=20)
+ finally:
+ peer.shutdown()
+ peer.server_close()
+ thread.join(timeout=5)
+ assert out['status'].startswith('✓ Goal done (2/20 turns)'), out['status']
+ users = [m['content'] for m in out['messages'] if m.get('role') == 'user']
+ assert users[0] == 'write the probe' and 'standing goal' in users[1], users
+ with sqlite3.connect(f'file:{home / "state.db"}?mode=ro', uri=True) as db:
+ rows = db.execute('SELECT request_id, principal_id FROM session_admissions').fetchall()
+ kick = [r for r in rows if r[0] == 'kick']
+ continuation = [r for r in rows if r[0] != 'kick']
+ assert len(kick) == 1 and len(continuation) == 1, rows
+ assert continuation[0][1].startswith('automation:') and 'goal-continuation' in continuation[0][0], rows
diff --cc tests/hermes_cli/test_stream_json.py
index f42815ea26f,3e872faf8cd..3ef1164e080
--- a/tests/hermes_cli/test_stream_json.py
+++ b/tests/hermes_cli/test_stream_json.py
@@@ -42,46 -43,56 +42,48 @@@ def test_emitter_event_stream_is_valid_
assert all("timestamp" in e for e in events)
-def _run_stream_json_chat(monkeypatch, capsys, run_conversation, credentials_ok=True):
- """parser → cmd_chat → cli.main → quiet single-query path with a deterministic fake agent."""
- import cli
- import hermes_cli.main as cli_entry
- from hermes_cli._parser import build_top_level_parser
-
- class FakeAgent:
- model = "test-model"
- session_id = "session-123"
-
- def run_conversation(self, **_kwargs):
- return run_conversation(self)
-
- class FakeCLI:
- def __init__(self, **_kwargs):
- self.session_id = "session-123"
- self.conversation_history = []
- self.agent = None
- self._active_agent_route_signature = None
- self.tool_progress_mode = None
+def _run_stream_json_chat(monkeypatch, capsys, run_turn, credentials_ok=True):
+ """parser → cmd_chat → gateway transport with a deterministic fake authority peer.
- def _claim_active_session(self, *_a, **_k):
- return True
+ ``run_turn(peer)`` plays the authority: it queues the execution events a turn would publish and
+ returns the terminal ``message.complete`` payload (or raises ``KeyboardInterrupt`` for Ctrl-C).
+ """
+ import asyncio
+ from contextlib import asynccontextmanager
- def _ensure_runtime_credentials(self):
- return credentials_ok
-
- def _resolve_turn_agent_config(self, _query):
- return {"signature": "r", "model": None, "runtime": None, "request_overrides": None}
-
- def _init_agent(self, **_kwargs):
- self.agent = FakeAgent()
- return True
-
- def chat(self, _query, images=None):
- print("human output") # must never reach stdout under stream-json
+ import hermes_cli.main as cli_entry
+ from hermes_cli import gateway_chat, gateway_chat_startup
+ from hermes_cli._parser import build_top_level_parser
- monkeypatch.setattr(cli, "HermesCLI", FakeCLI)
- monkeypatch.setattr(cli, "_finalize_single_query", lambda _cli: None)
- monkeypatch.setattr(cli, "_emit_interrupted_session_end", lambda *_a, **_k: None)
- monkeypatch.setattr(cli, "_start_worktree_setup", lambda *_a, **_k: None)
- monkeypatch.setattr(cli.atexit, "register", lambda *_a, **_k: None)
- monkeypatch.setattr(signal, "signal", lambda *_a, **_k: None)
+ class Peer:
+ def __init__(self):
+ self.events = asyncio.Queue()
+
+ def emit(self, kind, payload, admission="adm-1"):
+ self.events.put_nowait({"method": "event", "params": {
+ "type": kind, "session_id": "session-123", "admission_id": admission, "payload": payload}})
+
+ async def rpc(self, method, **params):
+ if method == "runtime.describe":
+ return {"session_create": {"sources": ["cli"], "parameters": ["cwd", "model", "request_id", "source"]}}
+ if method == "session.create":
+ return {"stored_session_id": "session-123", "info": {"model": "test-model"}}
+ if method == "prompt.receipt": # the settled result the exit code is judged from
+ return {"status": "terminal", "result": {"completed": True, "final_response": "hello"}}
+ assert method == "prompt.submit"
+ self.emit("message.complete", {**run_turn(self), "admission_id": "adm-1"})
+ return {"admission_id": "adm-1"}
+
+ @asynccontextmanager
+ async def connected():
+ yield Peer()
+
+ monkeypatch.setattr(gateway_chat, "connect_gateway", connected)
+ monkeypatch.setattr(gateway_chat_startup, "ensure_launch_provider", lambda _args: credentials_ok)
monkeypatch.setattr(cli_entry, "_resolve_use_tui", lambda _args: pytest.fail("TUI resolution consulted"))
- monkeypatch.setattr(cli_entry, "_has_any_provider_configured", lambda: True)
- monkeypatch.setattr(cli_entry, "_start_chat_background_prefetch", lambda: None)
- monkeypatch.setattr(cli_entry, "_pin_kanban_board_env", lambda: None)
monkeypatch.setattr(cli_entry, "_confirm_startup_expensive_model_override", lambda _a: None)
+ monkeypatch.setattr(cli_entry, "_warn_retired_xai_models", lambda: None)
+ monkeypatch.setattr("hermes_cli.quiet_single_query.continue_quiet_notify_completions", lambda *_a, **_k: None)
parser, _, _ = build_top_level_parser()
args = parser.parse_args(["chat", "-q", "hello", "--format", "stream-json"])
diff --cc tests/hermes_cli/test_web_server_boot_handshake.py
index 91e5625feb6,e58c64ac97d..39ef9ad9b59
--- a/tests/hermes_cli/test_web_server_boot_handshake.py
+++ b/tests/hermes_cli/test_web_server_boot_handshake.py
@@@ -62,6 -62,24 +62,24 @@@ def test_lifespan_warmup_is_synchronous
)
+ def test_lifespan_enters_and_exits_as_an_async_context_manager(monkeypatch):
- """FastAPI gets ``_lifespan`` as an async context manager, never a bare async generator
++ """FastAPI gets ``app_lifespan`` as an async context manager, never a bare async generator
+ (Starlette's deprecated path), and entering it runs the desktop's first-install check."""
+ from hermes_cli import anon_auth, install_state
+
+ probed: list[bool] = []
+ monkeypatch.setattr(web_server_mod, "_warm_gateway_module", lambda: None)
+ monkeypatch.setattr(web_server_mod, "_eager_reconcile_own_session_db", lambda: None)
+ monkeypatch.setattr(anon_auth, "on_local_desktop_backend", lambda: True)
+ monkeypatch.setattr(install_state, "probe", lambda: probed.append(True))
+
+ async def _run() -> None:
- async with web_server_mod._lifespan(web_server_mod.app):
++ async with web_server_mod.app_lifespan(web_server_mod.app):
+ assert probed == [True]
+
+ asyncio.run(_run())
+
+
def test_hosted_room_recovery_cannot_block_or_abort_backend_startup(monkeypatch):
from fastapi.testclient import TestClient
from tui_gateway import methods_groups
diff --cc tui_gateway/agent_factory.py
index 7587e4449fa,00000000000..2dd8e6ef305
mode 100644,000000..100644
--- a/tui_gateway/agent_factory.py
+++ b/tui_gateway/agent_factory.py
@@@ -1,693 -1,0 +1,689 @@@
+"""TUI agent_factory seam; functions bind to the server namespace at registration."""
+
+from __future__ import annotations
+
+from .method_ctx import bind_module
+
+def _env_model_seed() -> str:
+ """The launch-scoped model seed (``hermes --tui -m``, hosted provisioning); "" when unset."""
+ return (os.environ.get("HERMES_MODEL", "") or os.environ.get("HERMES_INFERENCE_MODEL", "")).strip()
+
+
+def _resolve_model() -> str:
+ if env := _env_model_seed():
+ return env
+ m = _load_cfg().get("model", "")
+ if isinstance(m, dict):
+ return str(m.get("default", "") or "").strip()
+ if isinstance(m, str) and m:
+ return m.strip()
+ # No env seed / config preference: the cost-safe silent default (cache-only read), never an unpicked flagship.
+ with contextlib.suppress(Exception):
+ from hermes_cli.models import get_preferred_silent_default_model
+ return get_preferred_silent_default_model()
+ return "z-ai/glm-5.2"
+
+
+def _resolve_session_platform() -> str:
+ """``HERMES_DESKTOP=1`` without ``HERMES_DESKTOP_TERMINAL`` → "desktop" (chat panel; the agent then
+ suggests TUI-only slash commands), else "tui" (embedded terminal pane or standalone ``hermes --tui``)."""
+ desktop = is_truthy_value(os.environ.get("HERMES_DESKTOP"))
+ return "desktop" if desktop and not is_truthy_value(os.environ.get("HERMES_DESKTOP_TERMINAL")) else "tui"
+
+
+def _resolve_session_source(explicit: str | None) -> str:
+ """Session DB ``source``: an explicit caller value (plugin session tagged ``"telegram"``) is never
+ rewritten; only empty/None falls back to the env-resolved platform."""
+ return explicit or _resolve_session_platform()
+
+
+def _resolve_agent_platform(source: str | None) -> str:
+ return _resolve_session_source(source)
+
+
+def _config_model_target() -> tuple[str, str]:
+ """(model, provider) selected by config.yaml — and ONLY config: the HERMES_MODEL launch seed fed into
+ the per-turn sync would be replayed as a /model switch and persisted globally, or pin the session so
+ dashboard/CLI model changes never reach an open chat. Empty model = "no preference" → no-op sync."""
+ cfg_model = _load_cfg().get("model")
+ if isinstance(cfg_model, dict):
+ provider = str(cfg_model.get("provider") or "").strip()
+ return str(cfg_model.get("default", "") or "").strip(), "" if provider.lower() == "auto" else provider
+ return (cfg_model.strip() if isinstance(cfg_model, str) else ""), ""
+
+
+def _resolve_startup_runtime() -> tuple[str, str | None]:
+ model = _resolve_model()
+ if explicit_provider := os.environ.get("HERMES_TUI_PROVIDER", "").strip():
+ return model, explicit_provider
+ if not (explicit_model := _env_model_seed()):
+ return model, None
+ with contextlib.suppress(Exception):
+ from hermes_cli.model_switch import resolve_startup_model_route
+ from hermes_cli.models import detect_static_provider_for_model
+ full_cfg = _load_cfg()
+ cfg = full_cfg.get("model") or {}
+ current_provider = ((str(cfg.get("provider") or "").strip().lower() if isinstance(cfg, dict) else "")
+ or os.environ.get("HERMES_INFERENCE_PROVIDER", "").strip().lower() or "auto")
+ # Same owner as HermesCLI/oneshot: ``custom:<name>:<model>`` selects that provider (#73943).
+ if route := resolve_startup_model_route(
+ explicit_model, current_provider=current_provider,
+ user_providers=full_cfg.get("providers"), custom_providers=full_cfg.get("custom_providers")):
+ return route.model, route.provider
+ if detected := detect_static_provider_for_model(explicit_model, current_provider):
+ provider, detected_model = detected
+ return detected_model, provider
+ return model, None
+
+
+def _is_routable_provider(provider: str) -> bool:
+ with contextlib.suppress(Exception):
+ from hermes_cli.runtime_provider import is_routable_provider
+ return is_routable_provider(provider)
+ return False
+
+
+def _overrides_have_routable_provider(overrides: dict) -> bool:
+ """Whether persisted runtime overrides still name a routable provider (renamed/removed → "Unknown
+ provider" at agent init). Empty = NOT routable, so the caller falls back to the session's picked model."""
+ provider = str(overrides.get("provider_override") or "").strip()
+ if not provider:
+ provider = str((overrides.get("model_override") or {}).get("provider") or "").strip()
+ return bool(provider) and _is_routable_provider(provider)
+
+
+def _parse_model_config(raw, *, quiet: bool = False) -> dict:
+ """A row's ``model_config`` (dict or JSON text) as a dict; ``{}`` when absent/invalid."""
+ if isinstance(raw, dict):
+ return raw
+ if isinstance(raw, str) and raw.strip():
+ try:
+ parsed = json.loads(raw)
+ return parsed if isinstance(parsed, dict) else {}
+ except Exception:
+ if not quiet:
+ raise
+ logger.debug("failed to parse stored session model_config", exc_info=True)
+ return {}
+
+
+def _row_follows_profile(row: dict | None) -> bool:
+ """Whether a stored row is a canonical Bot Chat whose runtime follows the member profile's config.
+ Identity is the persisted ``follow_profile_config`` marker; the bare title compare stays ONLY here as
+ the legacy fallback for rows written before the marker existed."""
+ if not row:
+ return False
+ model_config = _parse_model_config(row.get("model_config"), quiet=True)
+ return bool(model_config.get("follow_profile_config") or str(row.get("title") or "").strip() == "Bot Chat")
+
+
+def _stored_session_runtime_overrides(row: dict | None) -> dict:
+ """Runtime fields persisted with a stored session (model column, ``billing_provider``, JSON ``model_config``):
+ resume restores the model/provider/reasoning THAT chat used, not the global pick. Plugin-owned Bot-Mode
+ sessions normally rebuild from the member profile's CURRENT config (a stale provider pin left room bots
+ "out of Nous credits" after a profile switch). A canonical Bot Chat may instead restore an explicit
+ composer pick while the profile model it diverged from remains unchanged."""
+ if not row:
+ return {}
+ model_config = _parse_model_config(row.get("model_config"), quiet=True)
+ _row_title = str(row.get("title") or "").strip()
+ room_plumbing = model_config.get("room_plumbing") or (row.get("hidden") and _row_title.startswith("Group:"))
+ composer_profile = model_config.get("composer_override_profile")
+ composer_profile_matches = isinstance(composer_profile, dict) and (
+ str(composer_profile.get("model") or "").strip(),
+ str(composer_profile.get("provider") or "").strip(),
+ ) == _config_model_target()
+ if room_plumbing or (_row_follows_profile(row) and not composer_profile_matches):
+ return {}
+ overrides: dict = {}
+ model = str(row.get("model") or model_config.get("model") or "").strip()
+ # Canonical route reader shared with CLI --resume: nested ``gateway_runtime`` (the route the messaging
+ # gateway last ran) before the TUI's top-level keys, then a routable ``billing_provider`` (#125942).
+ from hermes_state import SessionDB
+ route = SessionDB.session_gateway_runtime(row)
+ provider, base_url, api_mode = (str(route.get(k) or "").strip() for k in ("provider", "base_url", "api_mode"))
+ service_tier = str(model_config.get("service_tier") or "").strip()
+ reasoning_config = model_config.get("reasoning_config")
+ from hermes_cli.runtime_provider import is_foreign_provider_endpoint
+ if is_foreign_provider_endpoint(provider, base_url):
+ # The endpoint and its wire belong to the provider this chat left; resolve the stored one's own.
+ base_url = api_mode = ""
+ # Heal a stale provider persisted by an older build (renamed/removed custom provider → "Unknown provider"):
+ # recover ``custom:<name>`` from the stored base_url, then from the entry serving the model; else drop it.
+ if provider and not _is_routable_provider(provider):
+ healed = None
+ try:
+ from hermes_cli.runtime_provider import canonical_custom_identity
+ healed = canonical_custom_identity(base_url=base_url or None, model=model or None)
+ except Exception:
+ logger.debug("custom provider identity recovery failed", exc_info=True)
+ if healed:
+ logger.info("healed stale session provider %r to %r", provider, healed)
+ provider = healed
+ base_url = "" # the healed identity owns a registered endpoint; the snapshot URL must not override it
+ else:
+ provider = ""
+ if model:
+ # Same dict-shaped override live /model switches use, so a DB-restored session keeps custom endpoint
+ # metadata across resume and rebuilds (/new). Raw api_key is never persisted/restored.
+ overrides["model_override"] = {
+ "model": model, "provider": provider or None, "base_url": base_url or None, "api_mode": api_mode or None}
+ if provider:
+ overrides["provider_override"] = provider
+ if isinstance(reasoning_config, dict):
+ overrides["reasoning_config_override"] = reasoning_config
+ if service_tier: # None = "inherit the profile" at _make_agent; "" = real override "no priority tier"
+ overrides["service_tier_override"] = "" if service_tier.lower() == "normal" else service_tier
+ return overrides
+
+
+def _runtime_model_config(agent, existing: dict | None = None) -> dict:
+ """Merge the agent's CURRENT runtime identity onto the row's persisted ``model_config``. Falsy agent
+ attributes DELETE the key rather than skip the write: resume reads provider/endpoint from this JSON
+ (model column written separately), so a stale provider would route the resumed chat to the wrong endpoint."""
+ config = dict(existing or {})
+ from agent.voice_turn_route import session_runtime_view
+ agent = session_runtime_view(agent)
+ attr = lambda k: str(getattr(agent, k, "") or "").strip()
+ model, provider, base_url = attr("model"), attr("provider"), attr("base_url")
+ if provider.lower() == "custom":
+ # ``agent.provider`` resolves every named custom entry to the literal "custom", losing the entry
+ # identity (api_key is never persisted): recover ``custom:<name>`` from the endpoint URL.
+ try:
+ from hermes_cli.runtime_provider import canonical_custom_identity
+ provider = canonical_custom_identity(base_url=base_url, model=model or None) or provider
+ except Exception:
+ logger.debug("custom provider identity lookup failed", exc_info=True)
+ reasoning_config = getattr(agent, "reasoning_config", None)
+ live = {
+ "model": model, "provider": provider, "base_url": base_url, "api_mode": attr("api_mode"),
+ # An empty dict is still a real (present) reasoning config.
+ "reasoning_config": reasoning_config if isinstance(reasoning_config, dict) else None,
+ "service_tier": getattr(agent, "service_tier", None),
+ }
+ for key, value in live.items():
+ if value or isinstance(value, dict):
+ config[key] = value
+ else:
+ config.pop(key, None)
+ return config
+
+
+def _persist_live_session_runtime(session: dict | None) -> None:
+ """Persist active session runtime so future resumes restore the same footer."""
+ live = _live_session_agent_db(session)
+ if live is None:
+ return
+ agent, session_key, db = live
+ try:
+ row = db.get_session(session_key) or {}
+ model_config = _runtime_model_config(agent, _parse_model_config(row.get("model_config")))
+ if isinstance(composer_profile := session.get("composer_override_profile"), dict):
+ model_config["composer_override_profile"] = composer_profile
+ elif "composer_override_profile" in session:
+ model_config.pop("composer_override_profile", None)
+ if (tier_override := session.get("create_service_tier_override")) is not None:
+ # agent.service_tier is None for explicit normal; without this the distinction is erased on every persist.
+ model_config["service_tier"] = tier_override or "normal"
+ model = str(model_config.get("model") or "").strip()
+ if hasattr(db, "update_session_meta"):
+ db.update_session_meta(session_key, json.dumps(model_config), model or None)
+ elif model and hasattr(db, "update_session_model"):
+ db.update_session_model(session_key, model)
+ except Exception:
+ logger.debug("failed to persist live session runtime", exc_info=True)
+
+def _load_approval_mode() -> str:
+ """Effective ``approvals.mode`` via the gate's own ``_get_approval_mode`` (a raw re-read missed the
+ managed overlay and ``${VAR}`` expansion)."""
+ from tools.approval_context import _get_approval_mode
+ mode = _get_approval_mode()
+ return mode if mode in _APPROVAL_MODES else "manual"
+
+
+def _coerce_statusbar(raw) -> str:
+ if raw is False:
+ return "off"
+ return s if isinstance(raw, str) and (s := raw.strip().lower()) in _STATUSBAR_MODES else "top"
+
+
+_MOUSE_TRACKING_ALIASES = {
+ "0": "off", "1": "all", "all": "all", "any": "all", "button": "buttons", "buttons": "buttons",
+ "click": "buttons", "false": "off", "full": "all", "no": "off", "off": "off", "on": "all",
+ "scroll": "wheel", "true": "all", "wheel": "wheel", "yes": "all",
+}
+
+
+def _display_mouse_tracking(display: dict) -> str:
+ """display.mouse_tracking → ``off|wheel|buttons|all`` (bools: True → all, False → off); ``wheel`` (DEC
+ 1000+1006) is the tmux-friendly subset without hover events. Legacy ``tui_mouse`` only when ``mouse_tracking`` is absent."""
+ if not isinstance(display, dict):
+ return "all"
+ raw = display.get("mouse_tracking") if "mouse_tracking" in display else display.get("tui_mouse", True)
+ if isinstance(raw, str):
+ return _MOUSE_TRACKING_ALIASES.get(raw.strip().lower(), "all")
+ return "off" if raw is False or raw == 0 else "all"
+
+
+def _load_reasoning_config(model: str = "") -> dict | None:
+ """Via the shared chokepoint :func:`hermes_constants.resolve_reasoning_config` (per-model override >
+ global ``agent.reasoning_effort``; YAML False = disabled).
+
+ Closes #21256.
+ """
+ from hermes_constants import resolve_reasoning_config
+ return resolve_reasoning_config(_load_cfg(), model)
+
+
+def _load_service_tier() -> str | None:
+ from agent.fast_mode import parse_service_tier
+
+ return parse_service_tier((_load_cfg().get("agent") or {}).get("service_tier", ""))
+
+
+def _load_provider_routing() -> dict:
+ """OpenRouter ``provider_routing`` prefs (gateway/CLI parity — without them OpenRouter picks an effectively random provider)."""
+ with contextlib.suppress(Exception):
+ return _load_cfg().get("provider_routing", {}) or {}
+ return {}
+
+
+def _load_show_reasoning() -> bool:
+ # Fallback True — keep in sync with DEFAULT_CONFIG display.show_reasoning (no DEFAULT_CONFIG merge here).
+ return bool(_display_cfg().get("show_reasoning", True))
+
+
+def _load_memory_notifications() -> str:
+ """``display.memory_notifications`` (``off`` / ``on`` default / ``verbose``; bool normalized) — gates the
+ "💾 Self-improvement review" summary (gateway/CLI parity)."""
+ raw = _display_cfg().get("memory_notifications")
+ if isinstance(raw, bool):
+ return "on" if raw else "off"
+ return str(raw).lower() if raw else "on"
+
+
+_TOOL_PROGRESS_MODES = frozenset({"off", "new", "all", "verbose"})
+
+
+def _load_tool_progress_mode() -> str:
+ env = os.environ.get("HERMES_TUI_TOOL_PROGRESS", "").strip().lower()
+ if env in _TOOL_PROGRESS_MODES:
+ return env
+ raw = _display_cfg().get("tool_progress", "all")
+ if isinstance(raw, bool):
+ return "all" if raw else "off"
+ mode = str(raw or "all").strip().lower()
+ return mode if mode in _TOOL_PROGRESS_MODES else "all"
+
+
+def _gui_surface_toolsets(platform: str) -> set[str]:
+ """Toolsets that exist because of the CLIENT (off ``_HERMES_CORE_TOOLS``; this is the one gate).
+ ``platform`` is the SESSION's source, never a process env var: the desktop may drive a URL/cloud
+ backend where ``HERMES_DESKTOP`` is unset (AGENTS.md surface rule)."""
+ from toolsets import CLIENT_SURFACE_TOOLSETS
+ return set(CLIENT_SURFACE_TOOLSETS) if platform == "desktop" else {"project"}
+
+
+def _with_session_toolsets(selection, platform: str) -> list[str]:
+ """*selection* plus the client surface's toolsets the session carries whatever its config says.
+
+ The fold-in happens after ``_get_platform_tools`` already subtracted ``agent.disabled_toolsets``,
+ so the same subtraction is applied to the fold-in itself — otherwise ``disabled_toolsets:
+ [project]`` is a no-op on desktop/TUI, the only surfaces where the client toolsets exist
+ (#54433). ``desktop_ui`` is kept regardless: it is the client's own control surface, not a
+ model toolset."""
+ fold_in = _gui_surface_toolsets(platform) - set(selection)
+ disabled = set(_load_disabled_toolsets() or [])
+ if disabled:
+ fold_in -= disabled - {"desktop_ui"}
+ return [*selection, *sorted(fold_in)]
+
+
+def _tui_notice(text: str) -> None:
+ print(text, file=sys.stderr, flush=True)
+
+
+def _resolve_explicit_toolsets(explicit: list[str], validate_toolset) -> list[str] | None | bool:
+ """Resolve a HERMES_TUI_TOOLSETS pin: list, None for "all", False when nothing was valid."""
+ built_in = [name for name in explicit if validate_toolset(name)]
+ unresolved = [name for name in explicit if name not in built_in]
+ if unresolved:
+ try:
+ from hermes_cli.plugins import discover_plugins
+ discover_plugins()
+ plugin_valid = [name for name in unresolved if validate_toolset(name)]
+ except Exception:
+ plugin_valid = []
+ built_in.extend(plugin_valid)
+ unresolved = [name for name in unresolved if name not in plugin_valid]
+ if any(name in {"all", "*"} for name in built_in):
+ if ignored := [name for name in explicit if name not in {"all", "*"}]:
+ _tui_notice(f"[tui] HERMES_TUI_TOOLSETS=all enables every toolset; ignoring additional entries: {', '.join(ignored)}")
+ return None
+ if not unresolved:
+ return built_in
+ try: # (enabled, disabled) MCP server names from raw config; both empty on any failure
+ from hermes_cli.config import read_raw_config
+ from tools.mcp_tool_common import mcp_server_enabled
+ raw_cfg = read_raw_config()
+ mcp_servers = raw_cfg.get("mcp_servers") if isinstance(raw_cfg.get("mcp_servers"), dict) else {}
+ mcp_names, mcp_disabled = set(), set()
+ for name, server_cfg in mcp_servers.items():
+ if isinstance(server_cfg, dict):
+ on = mcp_server_enabled(server_cfg)
+ (mcp_names if on else mcp_disabled).add(str(name))
+ except Exception:
+ mcp_names, mcp_disabled = set(), set()
+ mcp_valid = [name for name in unresolved if name in mcp_names]
+ disabled = [name for name in unresolved if name in mcp_disabled]
+ unknown = [name for name in unresolved if name not in mcp_names and name not in mcp_disabled]
+ if unknown:
+ _tui_notice(f"[tui] ignoring unknown HERMES_TUI_TOOLSETS entries: {', '.join(unknown)}")
+ if disabled:
+ _tui_notice("[tui] ignoring disabled MCP servers in HERMES_TUI_TOOLSETS "
+ f"(set enabled: true in config.yaml to use): {', '.join(disabled)}")
+ return (built_in + mcp_valid) or False
+
+
+def _load_enabled_toolsets(platform: str | None = None) -> list[str] | None:
+ """The agent's toolsets for this session (None = all): an explicit HERMES_TUI_TOOLSETS pin; else the
+ coding posture (coding_context collapses to coding toolset + enabled MCP servers in a code workspace);
+ else the configured CLI toolsets. Client-surface toolsets fold in here — only this surface can answer them.
+ An explicitly saved EMPTY list (``platform_toolsets.cli: []`` that resolves to nothing) is a
+ zero-tool state and returns [] — never None, which would mean unrestricted (#82010)."""
+ session_platform = platform or _resolve_session_platform()
+ explicit = [item.strip() for item in os.environ.get("HERMES_TUI_TOOLSETS", "").split(",") if item.strip()]
+ fallback_notice = None
+ if not explicit:
+ with contextlib.suppress(Exception):
+ from agent.coding_context import coding_selection
+ selection = coding_selection(platform=session_platform)
+ if selection is not None:
- from hermes_cli.config import load_config
- from hermes_cli.tools_config import _get_platform_tools
- from toolsets import TOOLSET_SESSION_PLATFORMS
- selection += sorted(_get_platform_tools(load_config(), "cli") & TOOLSET_SESSION_PLATFORMS.keys())
+ return sorted(_with_session_toolsets(selection, session_platform))
+ try:
+ from toolsets import validate_toolset
+ except Exception:
+ validate_toolset = None
+ if explicit and validate_toolset is not None:
+ resolved = _resolve_explicit_toolsets(explicit, validate_toolset)
+ if resolved is not False:
+ # An operator pin replaces the surface fold-in.
+ return resolved
+ fallback_notice = "[tui] no valid HERMES_TUI_TOOLSETS entries; using configured CLI toolsets"
+ try:
+ from hermes_cli.config import load_config
+ from hermes_cli.tools_config import _get_platform_tools, _platform_toolsets_explicitly_saved
+ cfg = load_config()
+ # include_default_mcp_servers=True is the runtime variant (the agent must be able to call
+ # default MCP servers); the config-editing variant would silently drop MCP tools from the TUI.
+ # Passing ``False`` here is the config-editing variant — used when we need to persist a toolset list
+ # without baking in implicit MCP defaults. Using the wrong variant at agent creation time makes MCP
+ # tools silently missing from the TUI. See PR #3252 for the original design split.
+ enabled = _get_platform_tools(cfg, "cli", include_default_mcp_servers=True)
+ if fallback_notice is not None:
+ _tui_notice(fallback_notice)
+ if enabled:
+ return sorted(_with_session_toolsets(enabled, session_platform))
+ # An explicitly saved list that resolves to nothing (``platform_toolsets.cli: []`` with no
+ # enabled MCP servers) is an explicit zero-tool state, not "no filter": fail closed with []
+ # instead of None (#82010). The client-surface fold-in must not resurrect tools the user
+ # explicitly switched off, so [] is returned bare. Only an ABSENT/unset key keeps the
+ # None = "no restriction" default below.
+ if _platform_toolsets_explicitly_saved(cfg, "cli"):
+ return []
+ return None
+ except Exception:
+ if fallback_notice is not None:
+ _tui_notice("[tui] no valid HERMES_TUI_TOOLSETS entries and configured CLI toolsets could not be loaded; enabling all toolsets")
+ return None
+
+
+def _load_disabled_toolsets() -> list[str] | None:
+ """``agent.disabled_toolsets`` from config.yaml, or ``None``.
+
+ The classic CLI (``cli_init_mixin``) and the messaging gateway both forward this list to
+ AIAgent, where ``get_tool_definitions`` strips the named toolsets even out of composite
+ defaults like ``hermes-cli`` (#17309). The desktop/TUI gateway historically dropped it, so
+ e.g. ``disabled_toolsets: [browser]`` silently had no effect on Desktop — the only consumer
+ was ``_get_platform_tools``'s name-level subtraction, which can't reach inside a composite
+ default toolset (#44499).
+ """
+ try:
+ from agent.skill_utils import parse_config_string_list
+
+ from hermes_cli.config import load_config
+
+ agent_cfg = load_config().get("agent") or {}
+ disabled = parse_config_string_list(agent_cfg.get("disabled_toolsets"))
+ return [str(ts) for ts in disabled] or None
+ except Exception:
+ return None
+
+
+def _session_tool_progress_mode(sid: str) -> str:
+ return str(_sessions.get(sid, {}).get("tool_progress_mode", "all") or "all")
+
+
+def _session_verbose(sid: str) -> bool:
+ return _session_tool_progress_mode(sid) == "verbose"
+
+
+def _session_show_reasoning(sid: str) -> bool:
+ """Session display flag. Missing means the config default, not hidden."""
+ session = _sessions.get(sid) or {}
+ if "show_reasoning" in session:
+ return bool(session["show_reasoning"])
+ return _load_show_reasoning()
+
+
+def _tool_progress_enabled(sid: str) -> bool:
+ return _session_tool_progress_mode(sid) != "off"
+
+
+_TOOL_LIFECYCLE_UI_TOOLS = frozenset({
+ "clarify", "manage_connections", "setup_mcp",
- "image_generate", "manage_catalog", "delegate_task", "setup_choose", "start_chat",
++ "image_generate", "manage_catalog", "delegate_task", "setup_beat", "set_theme",
+ # File edits are the turn's deliverable — the diff card the user reviews.
+ "edit_file", "patch", "write_file",
+})
+
+
+def _tool_lifecycle_required_for_ui(name: str) -> bool:
+ """Interactive UI / card surfaces, not optional chrome.
+
+ Desktop renders these from the tool-call part itself, so suppressing the
+ lifecycle hides the turn's deliverable entirely (`isCardTool` /
+ `isFileEditTool` in apps/desktop/src/lib/tool-render-class.ts must stay in
+ sync with `_TOOL_LIFECYCLE_UI_TOOLS`): clarify / connection cards are
+ consent surfaces, image_generate / manage_catalog / delegate_task draw the
+ thing the user asked for, and file edits are the diff the user reviews.
+ The start and complete guards both consult this set, so a card's
+ `tool.complete` can never arrive without its `tool.start`.
+ """
+ return name in _TOOL_LIFECYCLE_UI_TOOLS
+
+def _resolve_runtime_with_fallback(resolve_kwargs: dict | None = None) -> _RuntimeFallbackResolution:
+ """Resolve the primary runtime or one complete provider/model fallback. Provider-only fallback entries
+ are skipped so the unavailable primary model can never leak into a different runtime."""
+ from hermes_cli.auth import AuthError
+ from hermes_cli.runtime_provider import resolve_runtime_provider
+ try:
+ return _RuntimeFallbackResolution(resolve_runtime_provider(**(resolve_kwargs or {})), None, False)
+ except AuthError as primary_exc:
+ for entry in _load_fallback_model() or []:
+ fb_provider = str(entry.get("provider") or "").strip() if isinstance(entry, dict) else ""
+ fb_model = str(entry.get("model") or "").strip() if isinstance(entry, dict) else ""
+ if not fb_provider or not fb_model:
+ continue
+ try:
+ from hermes_cli.fallback_config import effective_runtime_provider, resolve_entry_api_key
+ fb_kwargs: dict = {"requested": fb_provider, "target_model": fb_model,
+ **({"explicit_base_url": entry["base_url"]} if entry.get("base_url") else {})}
+ if fb_api_key := resolve_entry_api_key(entry):
+ fb_kwargs["explicit_api_key"] = fb_api_key
+ runtime = resolve_runtime_provider(**fb_kwargs)
+ # Named custom entries resolve to the bare "custom" billing class; keep the configured
+ # identity so the session/UI shows the provider name, matching the manual-switch path (#98739).
+ runtime["provider"] = effective_runtime_provider(entry, runtime)
+ from hermes_cli.auth import primary_failure_wording
+ logging.getLogger(__name__).warning(
+ "Primary %s (%s), falling back to %s model %s",
+ primary_failure_wording(primary_exc)[0], primary_exc, fb_provider, fb_model)
+ return _RuntimeFallbackResolution(runtime, fb_model, True)
+ except Exception:
+ continue
+ raise
+
+
+def _resolve_agent_model_runtime(model_override, provider_override) -> tuple[str, dict]:
+ """(model, runtime) for a new agent; a per-session override (/model switch or a resumed row's persisted
+ runtime) wins over global config/env. Older rows stored the resolved provider "custom" (no named entry
+ matches) — recover the identity from the persisted base_url or the rebuild fails "No LLM provider
+ configured". Persisted base_url/api_key/api_mode are honored only for the original runtime, never a fallback."""
+ if isinstance(model_override, dict) and model_override.get("model"):
+ model = str(model_override.get("model") or "")
+ requested_provider = model_override.get("provider") or provider_override or None
+ override_base_url = model_override.get("base_url")
+ resolve_kwargs = {}
+ if str(requested_provider or "").strip().lower() == "custom":
+ from hermes_cli.runtime_provider import canonical_custom_identity
+ if recovered := canonical_custom_identity(base_url=override_base_url or None, model=model or None):
+ requested_provider = recovered
+ if override_base_url:
+ # Failing identity recovery, still hand base_url to the direct-alias branch so pool/env credentials resolve.
+ resolve_kwargs["explicit_base_url"] = override_base_url
+ resolve_kwargs.update(requested=requested_provider, target_model=model or None)
+ overrides = {k: model_override.get(k) for k in ("base_url", "api_key", "api_mode")}
+ else:
+ model, requested_provider = _resolve_startup_runtime()
+ if isinstance(model_override, str) and model_override:
+ model = model_override
+ if provider_override:
+ requested_provider = provider_override
+ resolve_kwargs = {"requested": requested_provider, "target_model": model or None}
+ overrides = {}
+ resolution = _resolve_runtime_with_fallback(resolve_kwargs)
+ if resolution.used_fallback:
+ if not resolution.selected_model:
+ raise RuntimeError("Auth fallback resolved without a model")
+ # Same pre-agent switch the messaging gateway surfaces (#74349); _make_agent pops it onto the
+ # agent's one-shot notice so the TUI/Desktop user sees which provider actually answered.
+ from hermes_cli.fallback_config import pre_agent_fallback_notice
+ # requested_provider=None means resolve_runtime_provider read the persisted config provider;
+ # ``model: <id>`` (string shorthand) names no provider.
+ cfg_model = _load_cfg().get("model")
+ primary_provider = requested_provider or (cfg_model.get("provider") if isinstance(cfg_model, dict) else None)
+ resolution.runtime["_fallback_notice"] = pre_agent_fallback_notice(
+ primary_provider, model, resolution.runtime.get("provider"), resolution.selected_model)
+ return resolution.selected_model, resolution.runtime
+ if resolution.runtime.get("source") == "local-runtime":
+ # Live supervisor beat any persisted loopback URL for this identity.
+ overrides.pop("base_url", None)
+ resolution.runtime.update({k: v for k, v in overrides.items() if v})
+ if any(overrides.values()):
+ _rederive_per_model_route(model, resolution.runtime)
+ return model, resolution.runtime
+
+
+def _rederive_per_model_route(model: str, runtime: dict) -> None:
+ """A row's persisted api_mode/base_url were written for whichever model the session last ran. Providers
+ that pick the wire per model (OpenCode Zen/Go, Copilot, Nous) must re-derive both from the target model,
+ or a resumed opencode-go session keeps a MiniMax-era anthropic_messages route (and its /v1-stripped or
+ other-family relay URL) for a chat_completions model like deepseek-v4-flash-vision-exp (#96066)."""
+ from hermes_cli.model_switch import model_derived_api_mode
+ from hermes_cli.models import normalize_opencode_base_url
+ provider = str(runtime.get("requested_provider") or runtime.get("provider") or "")
+ api_mode = model_derived_api_mode(provider, model)
+ if api_mode is None:
+ return
+ runtime["api_mode"] = api_mode
+ runtime["base_url"] = normalize_opencode_base_url(provider, api_mode, runtime.get("base_url"))
+
+
+def _startup_system_prompt(cfg: dict, task_id: str) -> str:
+ """Config ephemeral system prompt + HERMES_TUI_SKILLS preload block. Hard-fails only when EVERY requested
+ skill is missing (cli.py parity): a typo'd name must not auto-block the Kanban task."""
+ from hermes_cli.config import resolve_ephemeral_system_prompt_from_config
+ system_prompt = resolve_ephemeral_system_prompt_from_config(cfg)
+ startup_skills = _parse_tui_skills_env()
+ if not startup_skills:
+ return system_prompt
+ from agent.skill_commands import build_preloaded_skills_prompt, format_missing_skills
+ skills_prompt, loaded_skills, missing_skills = build_preloaded_skills_prompt(startup_skills, task_id=task_id)
+ if missing_skills:
+ if not loaded_skills:
+ raise ValueError(format_missing_skills(missing_skills))
+ logger.warning("Skipping %s. Continuing with: %s. List available skills with `hermes skills list`.",
+ format_missing_skills(missing_skills), ", ".join(loaded_skills))
+ if skills_prompt:
+ system_prompt = "\n\n".join(part for part in (system_prompt, skills_prompt) if part).strip()
+ return system_prompt
+
+
+def _make_agent(
+ sid: str, key: str, session_id: str | None = None, session_db=None,
+ model_override: dict | str | None = None, provider_override: str | None = None,
+ reasoning_config_override: dict | None = None, service_tier_override: str | None = None,
+ platform_override: str | None = None, context_cwd_is_launch_artifact: bool | None = None,
+ cwd_override: str | None = None, auth_user_id: str | None = None):
+ # AC-4 test seam: dead unless armed by the isolated certify harness.
+ from tui_gateway.synthetic_turn import maybe_build_synthetic_agent
+ synthetic = maybe_build_synthetic_agent(session_id or key, model_override)
+ if synthetic is not None:
+ return synthetic
+ from run_agent import AIAgent
+ # MCP discovery runs in a daemon thread (a dead server can't freeze the shell); the agent snapshots its tool
+ # list once, so briefly wait for in-flight discovery. Dashboard /api/ws uses mcp_startup; TUI stdio uses entry.
+ for _mod in ("hermes_cli.mcp_startup", "tui_gateway.entry"):
+ with contextlib.suppress(Exception):
+ importlib.import_module(_mod).wait_for_mcp_discovery()
+ cfg = _load_cfg()
+ # Load hooks alongside the same profile config used to construct this agent.
+ from agent.shell_hooks import register_from_config
+ register_from_config(cfg)
+ system_prompt = _startup_system_prompt(cfg, session_id or key)
+ model, runtime = _resolve_agent_model_runtime(model_override, provider_override)
+ fallback_notice = runtime.pop("_fallback_notice", None)
+ _pr = _load_provider_routing()
+ platform = _resolve_agent_platform(platform_override)
+ ignore_rules = is_truthy_value(os.environ.get("HERMES_IGNORE_RULES"))
+ with _sessions_lock:
+ session = _sessions.get(sid)
+ agent = AIAgent(
+ model=model, max_iterations=_cfg_max_turns(cfg, 500), provider=runtime.get("provider"),
+ requested_provider=runtime.get("requested_provider"),
+ base_url=runtime.get("base_url"), api_key=runtime.get("api_key"), api_mode=runtime.get("api_mode"),
+ acp_command=runtime.get("command"), acp_args=runtime.get("args"),
+ credential_pool=runtime.get("credential_pool"), quiet_mode=True,
+ verbose_logging=False, # DEBUG agent logging; independent of tool_progress_mode
+ reasoning_config=(
+ reasoning_config_override if reasoning_config_override is not None else _load_reasoning_config(str(model or ""))),
+ service_tier=service_tier_override if service_tier_override is not None else _load_service_tier(),
- enabled_toolsets=_load_enabled_toolsets(platform),
++ enabled_toolsets=_onboarding_toolsets(_load_enabled_toolsets(platform), session_db, session_id or key),
+ disabled_toolsets=_load_disabled_toolsets(),
+ # OpenRouter provider_routing prefs (gateway + CLI parity).
+ providers_allowed=_pr.get("only"), providers_ignored=_pr.get("ignore"), providers_order=_pr.get("order"),
+ provider_sort=_pr.get("sort"), provider_require_parameters=_pr.get("require_parameters", False),
+ provider_data_collection=_pr.get("data_collection"), platform=platform, session_id=session_id or key,
+ cwd=cwd_override,
+ # The dashboard login identity reaches memory providers as the runtime user, like a gateway user id.
+ # Builds that run before the record exists (branch, eager resume, compute host) pass it explicitly.
+ user_id=auth_user_id if auth_user_id is not None else _session_auth_user_id(session),
+ session_db=session_db if session_db is not None else _get_db(), ephemeral_system_prompt=system_prompt or None,
+ checkpoints_enabled=_resolve_checkpoints_enabled(cfg),
+ pass_session_id=is_truthy_value(os.environ.get("HERMES_TUI_PASS_SESSION_ID")),
+ skip_context_files=ignore_rules, skip_memory=ignore_rules, fallback_model=_load_fallback_model(),
+ # The resolved provider's request body (a custom entry's extra_body), as the CLI/cron/gateway pass it.
+ request_overrides=runtime.get("request_overrides"),
+ prefill_messages=_load_prefill_messages() or None, **_agent_cbs(sid))
+ if context_cwd_is_launch_artifact is None:
+ context_cwd_is_launch_artifact = _context_cwd_is_launch_artifact(session)
+ agent._context_cwd_is_launch_artifact = bool(context_cwd_is_launch_artifact)
+ if fallback_notice:
+ # Emitted once on the first successful reply via _emit_pending_fallback_notice -> status_callback.
+ agent._pending_fallback_notice = fallback_notice
+ return agent
+
+
+def register(server):
+ bind_module(globals(), server)
diff --cc tui_gateway/server.py
index ad890312118,83b1ff52f4e..e4a18e4ff40
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@@ -2168,12 -3670,10 +2166,11 @@@ from . import
methods_vault as _methods_vault, methods_free_tier as _methods_free_tier,
methods_connectors as _methods_connectors, methods_connectors_account as _methods_connectors_account,
methods_display as _methods_display, methods_display_watch as _methods_display_watch,
- methods_onboarding as _methods_onboarding, methods_i18n as _methods_i18n,
- methods_shared_metrics as _methods_shared_metrics, methods_start_chat as _methods_start_chat,
- methods_plugin_catalog as _methods_plugin_catalog)
+ methods_onboarding as _methods_onboarding, methods_i18n as _methods_i18n, methods_machine as _methods_machine,
+ methods_shared_metrics as _methods_shared_metrics, methods_plugin_catalog as _methods_plugin_catalog)
for _m in (
+ _session_registry, _agent_factory,
_session_transports, _session_reaper, _session_lifecycle, _session_workdir, _compute_host_bridge, _model_switch,
_session_compression, _change_watcher, _tool_progress, _session_notifications,
_prompt_attachments, _session_history, _agent_callbacks, _session_auto_continue, _plugin_inject, _rpc_dispatch,
diff --cc website/docs/developer-guide/gateway-command-parity.md
index 1eda58ad24e,00000000000..6e3891ee11a
mode 100644,000000..100644
--- a/website/docs/developer-guide/gateway-command-parity.md
+++ b/website/docs/developer-guide/gateway-command-parity.md
@@@ -1,135 -1,0 +1,134 @@@
+---
+title: Gateway command parity
+description: What each local client does with every slash command on the shared gateway
+---
+
+<!-- GENERATED by scripts/gen_gateway_command_parity.py — DO NOT EDIT. -->
+<!-- tests/hermes_cli/test_gateway_command_parity.py fails when this table is stale. -->
+
+# Gateway command parity (local sessions)
+
+Every local client (classic CLI, Ink TUI, Desktop, ACP) attaches to the one gateway that owns
+the session. A slash command either runs in the client against a canonical verb
+(`session.mutate`, `session.create`, `prompt.receipt`, ...), or goes to the owner as
+`slash.exec`, where `gateway/session_commands.py` runs only the reviewed reads below and refuses
+the rest (`unsupported_command`). The classic CLI (`hermes chat`) is main's `HermesCLI` with a
+gateway-backed agent and session store: its column names the main handler it runs in-process
+(turns, tools and session writes go to the gateway through `hermes_cli/gateway_agent.py` /
+`gateway_session_store.py`). The `--stream-json` / safe-mode transport client keeps its own
+narrower routes (`hermes_cli/gateway_chat_commands.py`).
+
+**Gateway (`slash.exec`)**: `read` = the real handler runs for a local session (proved by
+`tests/gateway/test_session_read_commands.py`); `control` = admission-fenced write (`/approve`
+`/deny` resolve this session's waiting approval, `tests/gateway/test_session_approval_commands.py`);
+`refused`.
+**Notes**: `per-session setting (gateway handler)` = the messaging handler runs and applies the
+setting to this local session (its next turn and `config.get`), saving config.yaml only where the
+handler does; `client-local (cli_only)` commands are terminal/UI features of a client.
+
- 103 registry commands: 29 control, 18 read, 56 refused.
++102 registry commands: 28 control, 18 read, 56 refused.
+
+| Command | Gateway (`slash.exec`) | Classic CLI | Ink | Desktop | ACP | Notes |
+|---|---|---|---|---|---|---|
+| `/agents` (/tasks) | refused | HermesCLI._handle_agents_command | delegation.pause | slash.exec: refused | refused | gateway-wide: lists every chat's running agents and the process's async jobs |
+| `/approvals` | control | HermesCLI._handle_approvals_command | slash.exec | slash.exec | refused | per-session setting (gateway handler) |
+| `/approve` | control | messaging-only: unknown command | slash.exec | slash.exec | refused | messaging-only |
+| `/battery` | refused | HermesCLI._handle_battery_command | sidecar: system.battery (preference not saved) | slash.exec: refused | refused | client-local (cli_only) |
+| `/bg` | refused | HermesCLI._handle_background_command | prompt.background | action: background | refused | |
+| `/blueprint` (/bp) | control | HermesCLI._handle_blueprint_command | slash.exec | slash.exec | refused | |
+| `/branch` (/fork) | refused | HermesCLI._handle_branch_command | canonical route | action: branch | ACP fork_session | |
+| `/browser` | refused | HermesCLI._handle_browser_command | sidecar: browser.manage | action: browser | refused | client-local (cli_only) |
+| `/btw` | refused | HermesCLI._handle_btw_command | prompt.btw | action: btw | refused | |
+| `/bundles` | read | HermesCLI._handle_bundles_command | slash.exec | slash.exec | refused | |
+| `/busy` | control | HermesCLI._handle_busy_command | canonical route | unavailable: terminal | refused | per-session setting (gateway handler) |
+| `/clear` | refused | HermesCLI._cmd_clear | local | action: new | refused | client-local (cli_only) |
+| `/codex-runtime` (/codex_runtime) | control | HermesCLI._handle_codex_runtime | slash.exec | slash.exec | refused | per-session setting (gateway handler) |
+| `/commands` | read | messaging-only: unknown command | slash.exec | action: help | refused | messaging-only |
+| `/compress` (/compact) | refused | HermesCLI._manual_compress | canonical route | action: compress | session.mutate compress | |
+| `/config` | refused | HermesCLI.show_config | slash.exec: refused | unavailable: terminal | refused | client-local (cli_only) |
+| `/context` (/ctx) | read | HermesCLI._show_context_breakdown | slash.exec | slash.exec | refused | TUI session: main's live /context with the category table |
+| `/copy` | refused | HermesCLI._handle_copy_command | local | unavailable: terminal | refused | client-local (cli_only) |
+| `/cron` | refused | HermesCLI._handle_cron_command | slash.exec | unavailable: terminal | refused | TUI session: bare `/cron` and `/cron list [--all]` read the profile's jobs; client-local (cli_only) |
+| `/curator` | control | HermesCLI._handle_curator_command | slash.exec | unavailable: advanced | refused | |
+| `/debug` | control | HermesCLI._handle_debug_command | slash.exec | slash.exec | refused | uploads logs to a public paste |
+| `/deny` | control | messaging-only: unknown command | slash.exec | slash.exec | refused | messaging-only |
+| `/diff` | read | HermesCLI._handle_diff_command | slash.exec | slash.exec | refused | |
+| `/egress` | control | HermesCLI._cmd_egress | slash.exec | slash.exec | refused | |
+| `/export` | refused | HermesCLI._handle_export_command | slash.exec: refused | slash.exec: refused | refused | client-local (cli_only) |
+| `/fast` | control | HermesCLI._handle_fast_command | config.get, config.set | unavailable: advanced | refused | per-session setting (gateway handler) |
+| `/focus` | refused | HermesCLI._handle_focus_command | local (preference not saved) | slash.exec: refused | refused | client-local (cli_only) |
+| `/footer` | control | HermesCLI._handle_footer_command | slash.exec | unavailable: terminal | refused | per-session setting (gateway handler) |
+| `/goal` | control | HermesCLI._handle_goal_command | slash.exec | slash.exec | refused | |
+| `/handoff` | refused | HermesCLI._handle_handoff_command | slash.exec: refused | action: handoff | refused | client-local (cli_only) |
+| `/hatch` (/generate-pet) | refused | HermesCLI._handle_hatch_command | slash.exec: refused | action: hatch | refused | client-local (cli_only) |
+| `/heartbeat` (/hb) | control | HermesCLI._handle_heartbeat_command | slash.exec | slash.exec | refused | |
+| `/help` | read | HermesCLI._cmd_help | local | action: help | refused | |
+| `/history` | refused | HermesCLI.show_history | local | unavailable: terminal | refused | client-local (cli_only) |
+| `/image` | refused | HermesCLI._handle_image_command | local | unavailable: terminal | refused | client-local (cli_only) |
+| `/import` | refused | HermesCLI._handle_import_command | slash.exec: refused | slash.exec: refused | refused | client-local (cli_only) |
+| `/indicator` | refused | HermesCLI._handle_indicator_command | config.get, config.set | unavailable: terminal | refused | client-local (cli_only) |
+| `/init` | control | HermesCLI._handle_init_command | slash.exec | slash.exec | refused | |
- | `/initiate-setup` (/initiate_setup) | control | HermesCLI._handle_initiate_setup_command | slash.exec | slash.exec | refused | |
+| `/insights` | read | HermesCLI._show_insights | slash.exec | unavailable: advanced | refused | |
+| `/journey` (/learning, /memory-graph) | refused | HermesCLI._handle_journey_command | local | action: journey | refused | client-local (cli_only) |
+| `/kanban` | read (list/show/stats/assignees/context/runs/log/diagnostics) | HermesCLI._handle_kanban_command | slash.exec | unavailable: advanced | refused | |
+| `/learn` | control | HermesCLI._handle_learn_command | slash.exec | slash.exec | refused | |
+| `/login` | control | HermesCLI._handle_login_command | slash.exec | unavailable: settings | refused | |
+| `/loop` (/proactive) | control | HermesCLI._handle_loop_command | slash.exec | slash.exec | refused | |
+| `/memory` | read (bare / `pending`) | HermesCLI._handle_memory_command | slash.exec | slash.exec | refused | |
+| `/moa` | control | HermesCLI._cmd_moa | slash.exec | slash.exec | refused | |
+| `/model` | refused | HermesCLI._handle_model_switch | canonical route | picker: model | session.mutate model | |
+| `/new` (/reset) | refused | HermesCLI._cmd_new | local | action: new | refused | |
+| `/palette` | refused | HermesCLI._open_command_palette | slash.exec: refused | slash.exec: refused | refused | client-local (cli_only) |
+| `/paste` | refused | HermesCLI._handle_paste_command | local | unavailable: terminal | refused | client-local (cli_only) |
+| `/pause` | refused | messaging-only: unknown command | slash.exec: refused | slash.exec: refused | refused | messaging-only |
+| `/personality` | control | HermesCLI._handle_personality_command | canonical route | slash.exec | refused | per-session setting (gateway handler) |
+| `/pet` | refused | HermesCLI._handle_pet_command | slash.exec | action: pet | refused | client-local (cli_only) |
+| `/plan` | control | HermesCLI._handle_plan_command | slash.exec | slash.exec | refused | |
+| `/platform` | refused | messaging-only: unknown command | slash.exec: refused | slash.exec: refused | refused | messaging adapters; `pause`/`resume` mutate them |
+| `/platforms` (/gateway) | read | HermesCLI._show_gateway_status | slash.exec | unavailable: terminal | refused | client-local (cli_only) |
+| `/plugins` | refused | HermesCLI._cmd_plugins | slash.exec | unavailable: terminal | refused | client-local (cli_only) |
+| `/profile` | read | HermesCLI._handle_profile_command | slash.exec | action: profile | refused | |
+| `/prompt` (/compose) | refused | HermesCLI._handle_prompt_compose_command | local | slash.exec: refused | refused | client-local (cli_only) |
+| `/queue` (/q) | refused | HermesCLI._cmd_queue | local | action: queue | refused | |
+| `/quit` (/exit) | refused | HermesCLI._cmd_exit | local | unavailable: terminal | refused | client-local (cli_only) |
+| `/reasoning` | control | HermesCLI._handle_reasoning_command | canonical route | action: reasoning | refused | per-session setting (gateway handler) |
+| `/redraw` | refused | HermesCLI._cmd_redraw | local | unavailable: terminal | refused | client-local (cli_only) |
+| `/refine` | control | HermesCLI._handle_refine_command | slash.exec | slash.exec | refused | |
+| `/reload` | refused | HermesCLI._cmd_reload | canonical route | unavailable: terminal | refused | client-local (cli_only) |
+| `/reload-mcp` (/reload_mcp) | refused | HermesCLI._confirm_and_reload_mcp | refused: not available yet | unavailable: advanced | refused | |
+| `/reload-skills` (/reload_skills) | refused | HermesCLI._cmd_reload_skills | commands.catalog, skills.reload | unavailable: advanced | refused | |
+| `/restart` | refused | messaging-only: unknown command | slash.exec: refused | unavailable: terminal | refused | messaging-only |
+| `/resume` | refused | HermesCLI._handle_resume_command | local | picker: session | refused | switches the messaging chat's session; local clients resume by id |
+| `/retry` | refused | HermesCLI._cmd_retry | canonical route | action: retry | refused | |
+| `/review` | control | HermesCLI._handle_review_command | slash.exec | slash.exec | refused | |
+| `/rollback` | refused | HermesCLI._handle_rollback_command | rollback.diff, rollback.list, rollback.restore | slash.exec: refused | refused | restores filesystem checkpoints |
+| `/save` | refused | HermesCLI.save_conversation | session.save | rpc session.save | refused | writes an export file on the gateway host |
+| `/sessions` | refused | HermesCLI._handle_sessions_command | local | picker: session | refused | messaging origin-scoped listing (`/sessions all` needs a messaging admin) |
+| `/sethome` (/set-home) | refused | messaging-only: unknown command | slash.exec: refused | unavailable: terminal | refused | messaging-only |
+| `/skills` | read (bare/`pending`/`diff`; `approve`/`reject`/`approval` control; hub refused) | HermesCLI._cmd_skills | slash.exec; sidecar: skills.manage | slash.exec | refused | client-local (cli_only) |
+| `/skin` | refused | HermesCLI._handle_skin_command | config.get, config.set | action: skin | refused | client-local (cli_only) |
+| `/snapshot` (/snap) | refused | HermesCLI._handle_snapshot_command | slash.exec: refused | unavailable: terminal | refused | client-local (cli_only) |
+| `/start` | refused | messaging-only: unknown command | slash.exec: refused | slash.exec: refused | refused | messaging-only |
+| `/status` | read | HermesCLI._show_session_status | canonical route | slash.exec (rpc fallback) | refused | TUI session: main's `Hermes TUI Status` |
+| `/statusbar` (/sb) | refused | HermesCLI._cmd_statusbar | local (preference not saved) | unavailable: terminal | refused | client-local (cli_only) |
+| `/steer` (/s) | refused | HermesCLI._cmd_steer | canonical route | action: steer | refused | |
+| `/stop` | refused | HermesCLI._handle_stop_command | canonical route | action: stop | refused | |
+| `/subgoal` | control | HermesCLI._handle_subgoal_command | slash.exec | slash.exec | refused | |
+| `/subscription` (/upgrade) | refused | HermesCLI._show_subscription | sidecar: subscription.state | slash.exec: refused | refused | client-local (cli_only) |
+| `/suggestions` (/suggest) | read (bare only) | HermesCLI._handle_suggestions_command | slash.exec | slash.exec | refused | |
+| `/timestamps` (/ts) | refused | HermesCLI._handle_timestamps_command | slash.exec: refused | slash.exec: refused | refused | client-local (cli_only) |
+| `/title` | control | HermesCLI._cmd_title | canonical route | action: title | refused | |
+| `/tools` | refused | HermesCLI._handle_tools_command | canonical route | slash.exec: refused | refused | client-local (cli_only) |
+| `/toolsets` | read | HermesCLI.show_toolsets | slash.exec | unavailable: terminal | refused | client-local (cli_only) |
+| `/topic` | refused | messaging-only: unknown command | slash.exec: refused | slash.exec: refused | refused | messaging-only |
+| `/topup` | read | HermesCLI._show_billing | sidecar: billing.state | slash.exec | refused | |
+| `/undo` | refused | HermesCLI._cmd_undo | canonical route | action: undo | refused | |
+| `/update` | refused | HermesCLI._cmd_update | local | unavailable: terminal | refused | |
+| `/usage` | read (bare only (`reset` refused)) | HermesCLI._handle_usage_command | canonical route | slash.exec | refused | |
+| `/verbose` | control | HermesCLI._toggle_verbose | config.set | unavailable: terminal | refused | per-session setting (gateway handler) |
+| `/version` (/v) | read | HermesCLI._cmd_version | slash.exec | slash.exec | refused | |
+| `/voice` | control | HermesCLI._handle_voice_command | canonical route | unavailable: composer-voice | refused | per-session setting (gateway handler) |
+| `/wake` | refused | HermesCLI._handle_wake_command | local | action: wake | refused | client-local (cli_only) |
+| `/whoami` | read | HermesCLI._handle_whoami_command | slash.exec | slash.exec | refused | |
+| `/worktree` | refused | HermesCLI._handle_worktree_command | slash.exec: refused | slash.exec: refused | refused | client-local (cli_only) |
+| `/yolo` | control | HermesCLI._toggle_yolo | config.set | action: yolo | refused | per-session setting (gateway handler) |