The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Isolate Claude Code and Codex runtime profiles (#1022)
Dee87c8d113f3b4
diff --git a/cli/AGENTS.md b/cli/AGENTS.mdindex 1858cea35..5d0969a46 100644--- a/cli/AGENTS.md+++ b/cli/AGENTS.md@@ -25,7 +25,7 @@ they show as `harnessd`, `harnessd-core` and `harnessd-<process>` (`src/harnessd|---|---|---|| master | supervision only (`src/harnessd/`) | by `harness start`, `harness start -f`, or launchd or systemd after `harness service install` || core | sessions (`src/core/`) | always |-| engine-claude, engine-codex | history, last-turn readers and live transcript parsers | on demand: an attach or read for that engine |+| engine-claude, engine-codex | history, last-turn readers, live transcript parsers and runtime profiles/catalogs | on demand: an attach or read for that engine || search | session search | always || viewers | the harness viewers, their remote streams and rendered surfaces, and the Store | always || edge | the shell service, workspaces, usage, the monitor, the project readers, the change-agent handoff, the recaps | always |diff --git a/cli/e2e/engineReaders.e2e.ts b/cli/e2e/engineReaders.e2e.tsindex 31ce56a08..47b1192ed 100644--- a/cli/e2e/engineReaders.e2e.ts+++ b/cli/e2e/engineReaders.e2e.ts@@ -1,5 +1,5 @@/** Private daemon/home/tmux; real supervised reader processes and the engines' recorded wire format. */-import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'+import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'import { join } from 'node:path'import { afterEach, describe, expect, it, onTestFailed } from 'vitest'import { LocalClient } from './harness/client.js'@@ -7,7 +7,7 @@ import { IsolatedDaemon, until } from './harness/daemon.js'import { alive, harnessdProcesses } from './harness/endurance.js'type Engine = 'claude' | 'codex'-type Agent = { id: string; sessionId: string; engine: Engine; processIdentity: unknown }+type Agent = { id: string; sessionId: string; engine: Engine; processIdentity: unknown; selectedModel: string | null }const rows = async (client: LocalClient) => (await client.request('agents_list', {})).agents as Agent[]const history = (client: LocalClient, agent: Agent) => client.request('session_get', { sessionId: agent.id, limit: 10 }, 15_000)@@ -41,12 +41,25 @@ describe('Claude Code and Codex readers in their own processes', () => {const readerPid = (d: IsolatedDaemon, engine: Engine) => harnessdProcesses(d).get(`engine-${engine}`)const linked = (d: IsolatedDaemon, engine: Engine) => d.log().split(`[services] engine-${engine} connected`).length - 1+ it.each(['claude', 'codex'] as const)('%s keeps native runtime profiles in explicit inline mode', async engine => {+ const { d, c } = await fresh({ HARNESSD_SERVICES: 'none' })+ const agent = await create(d, c, engine)+ await turn(c, agent, `inline-profile-${engine}`)+ const selected = await until('the inline runtime profile', async () => (await rows(c)).find(row => row.id === agent.id)?.selectedModel || null)+ expect(selected.startsWith(`runtime-v1:${agent.id}:${engine}:`)).toBe(true)+ const catalog = await c.request('models_list', { agentId: agent.id }, 15_000)+ expect(catalog.error, JSON.stringify(catalog)).toBeUndefined()+ expect(catalog.models.some((option: { id: string }) => option.id === selected)).toBe(true)+ expect(readerPid(d, engine)).toBeUndefined()+ expect(d.coresStarted()).toBe(1)+ })+it('starts no reader for an empty core, reads pages and recap text on demand, and keeps private requests off the client router', async () => {const { d, c } = await fresh()expect(readerPid(d, 'claude')).toBeUndefined()expect(readerPid(d, 'codex')).toBeUndefined()for (const type of ['engine_history_page', 'engine_last_turn', 'engine_live_capabilities', 'engine_live_prepare',- 'engine_live_read', 'engine_live_part', 'engine_live_close', 'engine_live_forget']) {+ 'engine_live_read', 'engine_live_part', 'engine_live_close', 'engine_live_forget', 'engine_runtime_capabilities', 'engine_runtime_read']) {const answer = await c.request(type, { version: 1, session: { transcriptPath: '/etc/passwd' } })expect(answer.error).toBe('UNSUPPORTED')}@@ -65,6 +78,40 @@ describe('Claude Code and Codex readers in their own processes', () => {expect(d.coresStarted()).toBe(1)})+ it.each(['claude', 'codex'] as const)('%s retains its accepted profile while its worker is frozen and applies pending evidence after recovery', async engine => {+ const { d, c } = await fresh({ HARNESSD_SERVICE_HEARTBEAT_TIMEOUT_MS: '60000', HARNESSD_SERVICE_STOP_GRACE_MS: '100' })+ const agent = await create(d, c, engine)+ await turn(c, agent, `profile-before-${engine}`)+ const before = await until('an accepted runtime profile', async () => (await rows(c)).find(row => row.id === agent.id)?.selectedModel || null)+ const catalog = await c.request('models_list', { agentId: agent.id }, 15_000)+ expect(catalog.error, JSON.stringify(catalog)).toBeUndefined()+ expect(catalog.models.length).toBeGreaterThan(0)+ const core = d.corePid(), pid = readerPid(d, engine)!+ const registry = JSON.parse(readFileSync(join(d.dataDir, 'registry.json'), 'utf8'))+ const bound = registry.find((row: any) => row.agentId === agent.id)+ const evidence = engine === 'claude'+ ? { type: 'system', content: 'Set model to Sonnet\nSet effort level to high' }+ : { type: 'event_msg', payload: { type: 'thread_settings_applied', thread_settings: { model: 'gpt-6-luna', reasoning_effort: 'high' } } }+ process.kill(pid, 'SIGSTOP')+ try {+ appendFileSync(bound.transcriptPath, JSON.stringify(evidence) + '\n')+ const started = Date.now()+ const unavailable = await c.request('models_list', { agentId: agent.id }, 15_000)+ expect(unavailable.error).toBe('INTERNAL')+ expect(Date.now() - started).toBeLessThan(10_000)+ expect((await rows(c)).find(row => row.id === agent.id)?.selectedModel).toBe(before)+ expect(d.corePid()).toBe(core)+ } finally { process.kill(pid, 'SIGCONT') }+ const expected = `runtime-v1:${agent.id}:${engine}:${engine === 'claude' ? 'sonnet' : 'gpt-6-luna'}@high`+ await until('pending profile evidence after worker recovery', async () => (await rows(c)).find(row => row.id === agent.id)?.selectedModel === expected || null, 30_000, 100)+ const recovered = await c.request('models_list', { agentId: agent.id }, 15_000)+ expect(recovered.error, JSON.stringify(recovered)).toBeUndefined()+ expect(recovered.models.some((option: { id: string }) => option.id === expected)).toBe(true)+ expect(d.corePid()).toBe(core)+ expect(d.coresStarted()).toBe(1)+ expect(alive(bound.processIdentity.pid)).toBe(true)+ })+it('contains a killed or frozen reader, bounds failed reads, and recovers without restarting core or either CLI', async () => {const { d, c } = await fresh({ HARNESSD_SERVICE_HEARTBEAT_TIMEOUT_MS: '4000', HARNESSD_SERVICE_STOP_GRACE_MS: '100' })const agents = await Promise.all((['claude', 'codex'] as const).map(engine => create(d, c, engine)))diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex 1e3fc1a9e..6ca28dd62 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -145,6 +145,7 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {const EDGE: RegExp[] = [// The pilot reader implementations and their host are never loaded by supervised core./^engines\/(worker\/process|transcripts|(claude|codex)\/(transcript|\w+ReaderProcess))\.ts$/,+ /^engines\/(runtime|(claude|codex)\/runtimeProfile)\.ts$/, /^lib\/runtimeProfile\.ts$/,/^gateway\//, /^lib\/e2ee\//, /^cable\//, /^device\//, /^lib\/autonomous-device\//, /^sharing\//, /^teams\//, /^orchestrator\//, /^services\//,/^lib\/grid(Attach|Credentials|Derive|Ensure|Envelope|Exec|FleetRpc|Handoff|Install|McpUrl|Models|ModelsPayload|Picture|Presence|Reader|Target|Wake)\.ts$/,/^lib\/localModels\.ts$/,@@ -207,6 +208,14 @@ describe('the daemon\'s shape', () => {}})+ it('runtime profile authority and wire values load contracts without vendor profile implementations', () => {+ for (const entry of ['core/engines/runtimeSessions.ts', 'core/engines/runtimeProfiles.ts',+ 'core/engines/runtimeTransport.ts', 'lib/runtimeProfileWire.ts', 'lib/runtimeProfileManager.ts']) {+ expect([...closureOf(entry).keys()].filter(file => /^engines\/(claude|codex)\//.test(file)), entry).toEqual([])+ expect(closureOf(entry).has('lib/runtimeProfile.ts'), entry).toBe(false)+ }+ })+it('the gateway reaches the core only through core/api.ts: never a core module, the registry, cli.ts or the socket', () => {// It speaks to the core through GatewayPort and GatewayEvents alone, so that it can run in a process of// its own (step 10, R2) without taking any of the core with it.diff --git a/cli/src/core/AGENTS.md b/cli/src/core/AGENTS.mdindex 8c43e5203..fa4688c54 100644--- a/cli/src/core/AGENTS.md+++ b/cli/src/core/AGENTS.md@@ -33,9 +33,11 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGE- `terminals/`: who controls a pane (the control lease), opening a terminal with a literal argv (`open.ts`),and the requests about a terminal itself (`requests.ts`: `terminal_info`, `theme_set`).- `engines/`: hook coordination, reader ports and live worker coordination. Claude Code/Codex- history, last-turn reads and live parsing run in supervised workers; core passes snapshots,+ history, last-turn reads, live parsing and runtime profile interpretation/catalogs run in supervised workers; core passes snapshots,validates bounded replies, retains acknowledged cursors and owns binding/turn state. The explicit- inline/older-master compatibility path is the only live parser composition in core.+ inline/older-master compatibility path is the only live parser or runtime profile implementation+ composition in core. Core keeps accepted profiles and control authority; native picker drivers+ remain to migrate. See [runtime profiles](../../../docs/design/2026-10-08-engine-runtime.md).- `input.ts`, `questions.ts`: messages into a pane; an agent's question and its answer.`deviceInput.ts`: the pane writer lock every write takes, and a device's queued turns behind it.`cardText.ts`: an engine's error, rewritten for a device's card.diff --git a/cli/src/core/agents/retarget.spec.ts b/cli/src/core/agents/retarget.spec.tsindex 5ffaba351..b59cfd8be 100644--- a/cli/src/core/agents/retarget.spec.ts+++ b/cli/src/core/agents/retarget.spec.ts@@ -5,7 +5,7 @@ import { binaryOnPath } from '../../lib/binaryOnPath.js'import { validateLaunchOverrides } from '../../lib/launchOverrides.js'import type { RegisteredSession } from '../../lib/registry.js'import { bypassPermissionFor, restartAgent } from '../../lib/restartAgent.js'-import { parseRuntimeProfile } from '../../lib/runtimeProfile.js'+import { parseRuntimeProfile } from '../../lib/runtimeProfileWire.js'import { inspectRuntimePane } from '../../lib/runtimeProfileController.js'import { probeGridAssignment } from '../../lib/gridAssignment.js'import { clearPaneRemainOnExit } from '../../lib/tmux.js'@@ -28,7 +28,7 @@ vi.mock('../../lib/restartAgent.js', async (real) => ({bypassPermissionFor: vi.fn(async (_s: unknown, live: () => Promise<boolean>) => live()),restartAgent: vi.fn(async () => ({ ok: true, resumed: true, processIdentity: { pid: 2, startMarker: 'new', executable: '/bin/claude' } })),}))-vi.mock('../../lib/runtimeProfile.js', async (real) => ({ ...await real<object>(), parseRuntimeProfile: vi.fn(() => ({ engine: 'claude', model: 'opus' })) }))+vi.mock('../../lib/runtimeProfileWire.js', async (real) => ({ ...await real<object>(), parseRuntimeProfile: vi.fn(() => ({ engine: 'claude', model: 'opus' })) }))vi.mock('../../lib/runtimeProfileController.js', async (real) => ({ ...await real<object>(), inspectRuntimePane: vi.fn(() => ({ idle: true })) }))vi.mock('../../lib/tmux.js', async (real) => ({...await real<object>(), clearPaneRemainOnExit: vi.fn(async () => {}),diff --git a/cli/src/core/agents/retarget.ts b/cli/src/core/agents/retarget.tsindex 9a2a64f81..872b4aba6 100644--- a/cli/src/core/agents/retarget.ts+++ b/cli/src/core/agents/retarget.ts@@ -22,7 +22,8 @@ import { validateLaunchOverrides, type LaunchOverridesDeps, type LaunchSource }import { sid } from '../../lib/log.js'import type { registry, RegisteredSession } from '../../lib/registry.js'import { bypassPermissionFor, restartAgent } from '../../lib/restartAgent.js'-import { parseRuntimeProfile, type RuntimeProfileManager } from '../../lib/runtimeProfile.js'+import type { RuntimeProfileManager } from '../../lib/runtimeProfile.js'+import { parseRuntimeProfile } from '../../lib/runtimeProfileWire.js'import { inspectRuntimePane } from '../../lib/runtimeProfileController.js'import type { TerminalAgentReconciler } from '../../lib/terminalAgentReconciler.js'import { terminalRouteKey } from '../../lib/terminalRuntime.js'diff --git a/cli/src/core/engines/liveSessions.spec.ts b/cli/src/core/engines/liveSessions.spec.tsindex 4c63bf23b..03e2044ad 100644--- a/cli/src/core/engines/liveSessions.spec.ts+++ b/cli/src/core/engines/liveSessions.spec.ts@@ -7,14 +7,14 @@ import type { LiveFrame } from '../../engines/worker/liveProtocol.js'import { LIVE_PREPARE, LIVE_READ } from '../../engines/worker/liveProtocol.js'import { engineLiveRequests } from '../../engines/worker/liveRequests.js'import { createLiveTransport } from './liveTransport.js'-import { createLiveSessions, type LiveSessions } from './liveSessions.js'+import { createLiveSessions, type LiveSessionDeps, type LiveSessions } from './liveSessions.js'const dirs: string[] = [], sessions: LiveSessions[] = []const prompt = (message: string) => JSON.stringify({ type: 'user', message: { role: 'user', content: message } }) + '\n'const done = JSON.stringify({ type: 'assistant', message: { role: 'assistant', content: [{ type: 'text', text: 'finished' }], stop_reason: 'end_turn' } }) + '\n'const deferred = <T>() => { let resolve!: (value: T) => void; const promise = new Promise<T>(r => { resolve = r }); return { promise, resolve } }-async function setup(content = '') {+async function setup(content = '', prepareFrames?: LiveSessionDeps['prepareFrames']) {const dir = await mkdtemp(join(tmpdir(), 'core-engine-stream-')); dirs.push(dir)const file = join(dir, 'transcript.jsonl'); await writeFile(file, content)const session = { agentId: 'agent', sessionId: 'session', engine: 'claude', transcriptPath: file,@@ -32,7 +32,7 @@ async function setup(content = '') {const reattach = vi.fn(async () => {})const watch = vi.fn(), unwatch = vi.fn(), log = vi.fn()const live = createLiveSessions({ handles: engine => engine === 'claude', transport, bySession: () => bound,- frame: (_session, frame) => { frames.push(frame) }, reattach, watch, unwatch, log })+ frame: (_session, frame) => { frames.push(frame) }, prepareFrames, reattach, watch, unwatch, log })sessions.push(live)const prepare = (first = false) => live.prepare(session, { live: first }, () => {})const attach = async (first = false) => {@@ -56,6 +56,52 @@ afterEach(async () => {})describe('core engine stream authority', () => {+ it('keeps a failed profile page unacknowledged and retries it exactly once without another file event', async () => {+ const prepareFrames = vi.fn(async (): Promise<() => boolean> => () => true)+ const t = await setup('', prepareFrames), prepared = await t.attach()+ const initial = prepared.state.ask.cursor+ await appendFile(t.file, prompt('profile first') + done)+ prepareFrames.mockRejectedValueOnce(new Error('ENGINE_UNAVAILABLE'))+ await expect(t.live.pollSession(t.session.sessionId)).rejects.toThrow('ENGINE_UNAVAILABLE')+ expect(prepared.state.ask.cursor).toBe(initial)+ expect(t.frames).toEqual([])+ await vi.waitFor(() => expect(t.events().filter(e => e.type === 'turn_ended')).toHaveLength(1), { timeout: 2500 })+ await t.live.pollSession(t.session.sessionId)+ expect(t.events().filter(e => e.type === 'turn_started')).toHaveLength(1)+ expect(t.events().filter(e => e.type === 'turn_ended')).toHaveLength(1)+ })++ it('does not accept a profile or cursor if a turn closes while profile interpretation is in flight', async () => {+ const prepareFrames = vi.fn(async (): Promise<() => boolean> => () => true)+ const t = await setup(prompt('old'), prepareFrames), prepared = await t.attach()+ const entered = deferred<void>(), resume = deferred<void>(), commit = vi.fn(() => true)+ prepareFrames.mockImplementationOnce(async () => { entered.resolve(); await resume.promise; return commit })+ await appendFile(t.file, prompt('new'))+ const pending = t.live.pollSession(t.session.sessionId)+ await entered.promise; prepared.state.handle.closeTurn('cancel'); resume.resolve(); await pending+ expect(commit).not.toHaveBeenCalled()+ expect(t.frames).toEqual([])+ prepareFrames.mockResolvedValueOnce(() => false)+ await expect(t.live.pollSession(t.session.sessionId)).rejects.toThrow('ENGINE_STALE_REPLY')+ expect(t.frames).toEqual([])+ await t.live.pollSession(t.session.sessionId)+ expect(t.events().filter(e => e.type === 'turn_started')).toHaveLength(1)+ })++ it('awaits profile hydration per page and discards a candidate invalidated while that work runs', async () => {+ const t = await setup(prompt('history') + done)+ const observed = vi.fn(), page = vi.fn(async () => { expect(observed).not.toHaveBeenCalled(); t.unbind() })+ const hydrated = vi.fn(), hydratedPage = vi.fn(async () => { expect(hydrated).not.toHaveBeenCalled() })+ const candidate = await t.live.prepare(t.session, { live: false }, hydrated, hydratedPage)+ expect(hydratedPage).toHaveBeenCalledOnce()+ expect(hydrated).toHaveBeenCalled()+ t.live.discard(candidate)+ await expect(t.live.prepare(t.session, { live: false }, observed, page)).rejects.toThrow('ENGINE_STALE_REPLY')+ expect(page).toHaveBeenCalledOnce()+ expect(observed).not.toHaveBeenCalled()+ expect(t.frames).toEqual([])+ })+it('remembers first-turn delivery when initial preparation fails and a normal retry follows', async () => {const t = await setup(prompt('born after the agent') + done)t.intercept(async (method, reply) => { if (method === LIVE_PREPARE) throw new Error('worker disconnected'); return reply })diff --git a/cli/src/core/engines/liveSessions.ts b/cli/src/core/engines/liveSessions.tsindex ac42eade6..8e7ef6d63 100644--- a/cli/src/core/engines/liveSessions.ts+++ b/cli/src/core/engines/liveSessions.ts@@ -38,6 +38,8 @@ export interface LiveSessionDeps {transport: LiveTransportbySession(id: string): RegisteredSession | undefinedframe(session: RegisteredSession, frame: LiveFrame): void+ /** Reduce side evidence before acknowledging the page; the returned commit must be synchronous. */+ prepareFrames?(session: RegisteredSession, frames: readonly LiveFrame[]): Promise<() => boolean>reattach(session: RegisteredSession): Promise<unknown>watch(path: string): voidunwatch(path: string): void@@ -151,18 +153,24 @@ export function createLiveSessions(deps: LiveSessionDeps) {throw error}if (!valid(state) || states.get(id) !== state || state.epoch !== epoch) return+ const session = deps.bySession(id)!+ if (deps.prepareFrames) {+ const commit = await deps.prepareFrames(session, page.frames)+ if (!valid(state) || states.get(id) !== state || state.epoch !== epoch) return+ if (!commit()) throw new EngineLiveError('ENGINE_STALE_REPLY')+ }state.ask.cursor = page.cursorerrors.delete(id)- const session = deps.bySession(id)!for (const frame of page.frames) {try { deps.frame(session, frame) } catch (error) { report(id, error) }}more = page.more}})()- try { await tail.running } finally {+ let failed = false+ try { await tail.running } catch (error) { failed = true; tail.dirty = true; throw error } finally {tail.running = null- if (tail.dirty) schedule(id)+ if (tail.dirty) schedule(id, failed ? 1_000 : 40)}}const removeSession = async (id: string): Promise<void> => {@@ -182,7 +190,8 @@ export function createLiveSessions(deps: LiveSessionDeps) {return {handles: deps.handles,current(session: RegisteredSession): boolean { return states.get(session.sessionId)?.identity === transcriptReadIdentity(session) },- async prepare(session: RegisteredSession, options: { live: boolean; end?: number }, observe: (frame: LiveFrame) => void): Promise<PreparedLive> {+ async prepare(session: RegisteredSession, options: { live: boolean; end?: number }, observe: (frame: LiveFrame) => void,+ observePage?: (frames: readonly LiveFrame[]) => Promise<void>): Promise<PreparedLive> {// A retry has no original attach flags. Keep first-turn delivery intent until activation;// otherwise a failed first prepare turns the user's completed first response into silent history.if (options.live) firstLive.set(session.sessionId, transcriptReadIdentity(session))@@ -194,6 +203,10 @@ export function createLiveSessions(deps: LiveSessionDeps) {for (;;) {const page = await pull(state.ask)if (!valid(state)) throw new EngineLiveError('ENGINE_STALE_REPLY')+ if (observePage) {+ await observePage(page.frames)+ if (!valid(state)) throw new EngineLiveError('ENGINE_STALE_REPLY')+ }state.ask.cursor = page.cursor; records += page.records; content ||= page.contentfor (const frame of page.frames) observe(frame)if (page.prepared) return { state, parent, parentEpoch, moves, page, records, content }diff --git a/cli/src/core/engines/runtimeProfiles.spec.ts b/cli/src/core/engines/runtimeProfiles.spec.tsnew file mode 100644index 000000000..4e336c367--- /dev/null+++ b/cli/src/core/engines/runtimeProfiles.spec.ts@@ -0,0 +1,130 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { RuntimeContext } from '../../engines/facets/runtime.js'+import { blankRuntimeState, encodeRuntimeProfile } from '../../engines/kit/runtime.js'+import type { LiveFrame } from '../../engines/worker/liveProtocol.js'+import type { RuntimeAnswer, RuntimeOperation } from '../../engines/worker/runtimeProtocol.js'+import { RuntimeProfileManager } from '../../lib/runtimeProfile.js'+import type { RegisteredSession } from '../../lib/registry.js'+import { createRuntimeProfiles, type RuntimeProfiles } from './runtimeProfiles.js'++const active: RuntimeProfiles[] = []+const frame = (runtime: LiveFrame['runtime']): LiveFrame => ({ raw: 'opaque vendor record', runtime, profile: true,+ observe: false, events: [], replay: false, turn: { turnOpen: false, identity: 'turn', continued: false } })+function setup(isolated = true) {+ const session = { agentId: 'agent', sessionId: 'session', engine: 'codex', model: null, cliVersion: '0.144.0',+ cwd: '/tmp', transcriptPath: '/tmp/transcript' } as RegisteredSession+ const target = { sessionId: session.agentId, engine: session.engine, model: 'reported-model', effort: 'high' }+ const id = encodeRuntimeProfile(target)+ const legacy = new RuntimeProfileManager()+ const read = vi.fn(async (_engine: string, context: RuntimeContext, operation: RuntimeOperation): Promise<RuntimeAnswer> => {+ const state = { ...context.state, model: target.model, effort: target.effort }+ return { state, cliVersion: session.cliVersion, selectedModel: id, control: context.control ?? null,+ supportsControl: true, ...(operation.kind === 'models' ? { models: [{ id, displayName: 'Worker choice' }] } : {}),+ ...(operation.kind === 'catalog' ? { catalog: [{ slug: target.model, displayName: 'Worker choice', listed: true, defaultEffort: 'high', efforts: ['high'] }] } : {}),+ ...(operation.kind === 'effort' ? { effortAllowed: operation.effort === 'high' } : {}) }+ })+ const profiles = createRuntimeProfiles({ legacy, handles: engine => isolated && engine === 'codex',+ resolve: value => [session.agentId, session.sessionId].includes(value) ? session : undefined,+ transport: { read, connected: vi.fn(), disconnected: vi.fn() } })+ active.push(profiles)+ return { session, target: { ...target, id }, legacy, read, profiles }+}+afterEach(() => { active.splice(0).forEach(p => p.stop()); vi.useRealTimers(); vi.restoreAllMocks() })++describe('runtime profile routing', () => {+ it('uses only worker reports for isolated observations, catalog and eligibility', async () => {+ const t = setup(), { profiles: p, session: s } = t+ const inline = vi.spyOn(t.legacy, 'ingestPane').mockImplementation(() => { throw new Error('inline reader called') })+ expect(p.selectedModel(s)).toBeNull()+ expect(await p.ingestPane(s, 'vendor UI')).toBe(true)+ expect(p.selectedModel(s)).toBe(t.target.id)+ expect(await p.ingestConfig(s, true)).toBe(false)+ expect(await p.supportsControl(s)).toBe(true)+ expect(await p.effortAllowed(s, t.target.model, 'high', ['high'])).toBe(true)+ expect(await p.effortAllowed(s, t.target.model, 'low', null)).toBe(false)+ expect(await p.codexCatalog(s)).toMatchObject([{ slug: t.target.model }])+ expect(await p.modelsForSessions([s])).toEqual([{ id: t.target.id, displayName: 'Worker choice' }])+ expect(inline).not.toHaveBeenCalled()+ expect(() => p.ingest(s, '{}')).toThrow('ENGINE_INVALID_REQUEST')+ expect(() => p.hydrate(s, [])).toThrow('ENGINE_INVALID_REQUEST')+ expect(() => p.transcriptFields(s, '{}')).toThrow('ENGINE_INVALID_REQUEST')+ t.read.mockRejectedValueOnce(new Error('ENGINE_UNAVAILABLE'))+ await expect(p.ingestConfig(s)).rejects.toThrow('ENGINE_UNAVAILABLE')+ expect(p.selectedModel(s)).toBe(t.target.id)+ })++ it('keeps gateway sessions display-only without asking the worker for picker permissions', async () => {+ const t = setup(); t.session.gateway = {} as RegisteredSession['gateway']+ expect(await t.profiles.modelsForSession(t.session)).toEqual([])+ expect(await t.profiles.supportsControl(t.session)).toBe(false)+ expect(t.read).not.toHaveBeenCalled()+ })++ it('stages compact evidence atomically and rejects frames from unsupported workers', async () => {+ const t = setup(), { profiles: p, session: s } = t+ const stage = p.beginHydrate(s)+ expect(() => stage.ingest('raw')).toThrow('ENGINE_INVALID_REQUEST')+ expect(() => stage.commit()).toThrow('ENGINE_INVALID_REQUEST')+ await stage.ingestFrames!([frame(null), frame({ model: 'opaque' })])+ await stage.config!()+ expect(p.selectedModel(s)).toBeNull()+ expect(stage.commitWith!(() => false)).toBe(false)+ expect(stage.commitWith!(() => true)).toBe(true)+ expect(p.selectedModel(s)).toBe(t.target.id)+ await expect(p.prepareFrames(s, [frame(undefined)])).rejects.toThrow('ENGINE_INVALID_REPLY')+ const commit = await p.prepareFrames(s, [frame(null), frame({ effort: 'high' })])+ expect(commit()).toBe(true)+ expect(t.read.mock.calls.map(c => c[2].kind)).toEqual(['records', 'config', 'records'])+ })++ it('routes generic control authority, accepted state, notifications and cleanup through core', async () => {+ vi.useFakeTimers()+ const t = setup(), { profiles: p, session: s, target } = t+ const changed = vi.fn(); p.onChanged = changed; expect(p.onChanged).toBe(changed)+ await p.withoutChangeEvents(async () => { await p.ingestPane(s, 'pane') })+ await vi.advanceTimersByTimeAsync(120); expect(changed).not.toHaveBeenCalled()+ expect(p.beginControl(s, target)).toBe(true)+ await expect(p.waitForModel(s.sessionId, 100)).resolves.toBe(true)+ await expect(p.waitForProfile(s.sessionId, 100)).resolves.toBe(true)+ p.confirmEffort(s.sessionId, 'high'); p.confirmControlProfile(target)+ p.finishControl(s); await vi.advanceTimersByTimeAsync(120)+ expect(changed).toHaveBeenCalledWith(s.sessionId)+ p.cancelControl(s.sessionId)+ p.forget(s.sessionId); expect(p.getState(s.sessionId)).toEqual(blankRuntimeState())+ t.legacy.onChanged?.('legacy-session'); expect(changed).toHaveBeenLastCalledWith('legacy-session')+ p.stop(); t.legacy.onChanged?.('later'); expect(changed).toHaveBeenLastCalledWith('legacy-session')+ })++ it('preserves explicit inline compatibility and the unchanged other-engine methods', async () => {+ const t = setup(false), { profiles: p, session: s, legacy } = t+ const pane = vi.spyOn(legacy, 'ingestPane').mockReturnValue(true)+ const config = vi.spyOn(legacy, 'ingestConfig').mockResolvedValue(true)+ const raw = vi.spyOn(legacy, 'ingest').mockReturnValue(false)+ const hydrate = vi.spyOn(legacy, 'hydrate').mockImplementation(() => {})+ const fields = vi.spyOn(legacy, 'transcriptFields').mockReturnValue(['model'])+ const stage = { ingest: vi.fn(), commit: vi.fn() }+ vi.spyOn(legacy, 'beginHydrate').mockReturnValue(stage)+ vi.spyOn(legacy, 'supportsControl').mockReturnValue(true)+ vi.spyOn(legacy, 'effortAllowed').mockReturnValue(true)+ vi.spyOn(legacy, 'codexCatalog').mockResolvedValue([])+ vi.spyOn(legacy, 'modelsForSession').mockResolvedValue([])+ expect(p.ingestPane(s, 'pane')).toBe(true); expect(pane).toHaveBeenCalledWith(s, 'pane', false)+ expect(await p.ingestConfig(s)).toBe(true); expect(config).toHaveBeenCalledWith(s, false)+ expect(p.ingest(s, '{}')).toBe(false); expect(raw).toHaveBeenCalledWith(s, '{}', false)+ p.hydrate(s, []); expect(hydrate).toHaveBeenCalledWith(s, [])+ expect(p.transcriptFields(s, '{}')).toEqual(['model']); expect(fields).toHaveBeenCalled()+ expect(p.beginHydrate(s)).toBe(stage)+ expect(await p.supportsControl(s)).toBe(true)+ expect(await p.effortAllowed(s, 'model', 'high', null)).toBe(true)+ expect(await p.codexCatalog(s)).toEqual([])+ expect(await p.modelsForSession(s)).toEqual([])+ expect((await p.prepareFrames(s, [frame(undefined)]))()).toBe(true)+ expect(p.getState('missing')).toEqual(blankRuntimeState())+ expect(p.selectedModel(s)).toBeNull()+ expect(p.cursorTarget('missing', 'id')).toBeNull()+ expect(p.devinTarget('missing', 'id')).toBeNull()+ expect(p.commandcodeTarget('missing', 'id')).toBeNull()+ expect(p.hermesTarget('missing', 'id')).toBeNull()+ expect(t.read).not.toHaveBeenCalled()+ })+})diff --git a/cli/src/core/engines/runtimeProfiles.ts b/cli/src/core/engines/runtimeProfiles.tsnew file mode 100644index 000000000..27297102e--- /dev/null+++ b/cli/src/core/engines/runtimeProfiles.ts@@ -0,0 +1,120 @@+/** Route profile interpretation to workers while keeping accepted state and control authority in core. */+import type { LegacyRuntimeProfileManager } from '../../lib/runtimeProfileManager.js'+import type { RegisteredSession } from '../../lib/registry.js'+import type { LiveFrame } from '../../engines/worker/liveProtocol.js'+import type { RuntimeProfile, RuntimeRecord } from '../../engines/facets/runtime.js'+import { EngineReadError } from '../../engines/worker/protocol.js'+import { createRuntimeSessions } from './runtimeSessions.js'+import type { RuntimeTransport } from './runtimeTransport.js'++export interface ProfileHydration {+ ingest(rawLine: string): void+ commit(): void+ ingestFrames?(frames: readonly LiveFrame[]): Promise<void>+ config?(): Promise<void>+ commitWith?(install: () => boolean): boolean+}++export interface RuntimeProfilesDeps {+ legacy: LegacyRuntimeProfileManager+ handles(engine: string): boolean+ resolve(id: string): RegisteredSession | undefined+ transport: RuntimeTransport+}++function evidence(frames: readonly LiveFrame[]): RuntimeRecord[] {+ const records: RuntimeRecord[] = []+ for (const frame of frames) {+ // A capable worker must explicitly distinguish no evidence from an old, unsupported frame.+ if (frame.runtime === undefined) throw new EngineReadError('ENGINE_INVALID_REPLY')+ if (frame.runtime !== null) records.push(frame.runtime)+ }+ return records+}++export function createRuntimeProfiles({ legacy, handles, resolve, transport }: RuntimeProfilesDeps) {+ let changed: ((id: string) => void) | null = null+ const remote = createRuntimeSessions({ resolve, transport, changed: id => changed?.(id) })+ legacy.onChanged = id => changed?.(id)+ const forId = (id: string) => handles(resolve(id)?.engine ?? '') ? remote : legacy+ const forSession = (session: RegisteredSession) => handles(session.engine) ? remote : legacy+ const rawUnavailable = (): never => { throw new EngineReadError('ENGINE_INVALID_REQUEST') }+ const observe = async (session: RegisteredSession, operation: { kind: 'config' } | { kind: 'pane'; text: string }, silent: boolean): Promise<boolean> => {+ const before = remote.selectedModel(session)+ await remote.read(session, operation, silent)+ return before !== remote.selectedModel(session)+ }+ return {+ handles,+ get onChanged() { return changed },+ set onChanged(value: ((id: string) => void) | null) { changed = value },+ selectedModel: (session: RegisteredSession) => forSession(session).selectedModel(session),+ getState: (id: string) => forId(id).getState(id),+ beginControl: (session: RegisteredSession, target: RuntimeProfile) => forSession(session).beginControl(session, target),+ cancelControl: (id: string) => forId(id).cancelControl(id),+ finishControl: (session: RegisteredSession) => forSession(session).finishControl(session),+ confirmEffort: (id: string, effort: string) => forId(id).confirmEffort(id, effort),+ confirmControlProfile: (target: RuntimeProfile) => forId(target.sessionId).confirmControlProfile(target),+ waitForModel: (id: string, timeout: number) => forId(id).waitForModel(id, timeout),+ waitForProfile: (id: string, timeout: number) => forId(id).waitForProfile(id, timeout),+ forget(id: string): void { remote.forget(id); legacy.forget(id) },+ stop(): void { remote.stop(); changed = null },+ withoutChangeEvents<T>(run: () => Promise<T>): Promise<T> {+ return remote.withoutChangeEvents(() => legacy.withoutChangeEvents(run))+ },+ ingest(session: RegisteredSession, line: string, silent = false): boolean {+ return handles(session.engine) ? rawUnavailable() : legacy.ingest(session, line, silent)+ },+ hydrate(session: RegisteredSession, lines: string[]): void {+ if (handles(session.engine)) rawUnavailable()+ legacy.hydrate(session, lines)+ },+ transcriptFields(session: RegisteredSession, line: string) {+ return handles(session.engine) ? rawUnavailable() : legacy.transcriptFields(session, line)+ },+ beginHydrate(session: RegisteredSession): ProfileHydration {+ if (!handles(session.engine)) return legacy.beginHydrate(session)+ const pending = remote.stage(session, true, true)+ return { ingest: rawUnavailable, commit: rawUnavailable,+ ingestFrames: frames => pending.ingest(evidence(frames)),+ config: () => pending.config(), commitWith: install => pending.commit(install) }+ },+ async prepareFrames(session: RegisteredSession, frames: readonly LiveFrame[]): Promise<() => boolean> {+ if (!handles(session.engine)) return () => true+ return remote.prepare(session, evidence(frames))+ },+ ingestPane(session: RegisteredSession, text: string, silent = false): boolean | Promise<boolean> {+ return handles(session.engine) ? observe(session, { kind: 'pane', text }, silent) : legacy.ingestPane(session, text, silent)+ },+ ingestConfig(session: RegisteredSession, silent = false): Promise<boolean> {+ return handles(session.engine) ? observe(session, { kind: 'config' }, silent) : legacy.ingestConfig(session, silent)+ },+ async supportsControl(session: RegisteredSession): Promise<boolean> {+ if (session.gateway) return false+ return handles(session.engine) ? (await remote.read(session, { kind: 'describe' })).supportsControl : legacy.supportsControl(session)+ },+ async effortAllowed(session: RegisteredSession, model: string, effort: string, listed: readonly string[] | null): Promise<boolean> {+ return handles(session.engine)+ ? (await remote.read(session, { kind: 'effort', model, effort, listed: listed && [...listed] })).effortAllowed!+ : legacy.effortAllowed(session, model, effort, listed)+ },+ async codexCatalog(session: RegisteredSession) {+ return handles(session.engine) ? (await remote.read(session, { kind: 'catalog' })).catalog! : legacy.codexCatalog(session)+ },+ async modelsForSession(session: RegisteredSession) {+ if (session.gateway) return []+ return handles(session.engine) ? (await remote.read(session, { kind: 'models' })).models! : legacy.modelsForSession(session)+ },+ async modelsForSessions(sessions: RegisteredSession[]) {+ return (await Promise.all(sessions.map(session => this.modelsForSession(session)))).flat()+ },+ cursorTarget: legacy.cursorTarget.bind(legacy),+ devinTarget: legacy.devinTarget.bind(legacy),+ commandcodeTarget: legacy.commandcodeTarget.bind(legacy),+ hermesTarget: legacy.hermesTarget.bind(legacy),+ opencodeCatalog: legacy.opencodeCatalog.bind(legacy),+ kiloCatalog: legacy.kiloCatalog.bind(legacy),+ }+}++export type RuntimeProfiles = ReturnType<typeof createRuntimeProfiles>diff --git a/cli/src/core/engines/runtimeSessions.spec.ts b/cli/src/core/engines/runtimeSessions.spec.tsnew file mode 100644index 000000000..989589ad8--- /dev/null+++ b/cli/src/core/engines/runtimeSessions.spec.ts@@ -0,0 +1,296 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { RegisteredSession } from '../../lib/registry.js'+import type { RuntimeContext, RuntimeProfile } from '../../engines/facets/runtime.js'+import type { RuntimeAnswer, RuntimeOperation } from '../../engines/worker/runtimeProtocol.js'+import { blankRuntimeState, encodeRuntimeProfile } from '../../engines/kit/runtime.js'+import { createRuntimeSessions, type RuntimeSessions } from './runtimeSessions.js'++const active: RuntimeSessions[] = []+const deferred = <T>() => { let resolve!: (value: T) => void; const promise = new Promise<T>(r => { resolve = r }); return { promise, resolve } }+const session = (id = 'agent'): RegisteredSession => ({ agentId: id, sessionId: `${id}-conversation`, engine: 'claude',+ model: null, cliVersion: '2.1.209', cwd: '/tmp', transcriptPath: '/tmp/transcript', boundAt: 1 } as RegisteredSession)+const profile = (s: RegisteredSession, model = 'new', effort = 'high'): RuntimeProfile => {+ const value = { sessionId: s.agentId, engine: s.engine, model, effort }+ return { ...value, id: encodeRuntimeProfile(value) }+}+function result(context: RuntimeContext, operation: RuntimeOperation): RuntimeAnswer {+ const copy: RuntimeContext = structuredClone(context)+ if (operation.kind === 'records') for (const r of operation.records) {+ if (typeof r.model === 'string') copy.state.model = r.model+ if (typeof r.effort === 'string') copy.state.effort = r.effort+ if (typeof r.version === 'string') copy.session.cliVersion = copy.state.cliVersion = r.version+ if (copy.control) {+ copy.control.modelConfirmed ||= copy.state.model === copy.control.target.model+ copy.control.effortConfirmed ||= copy.state.effort === copy.control.target.effort+ }+ }+ if (operation.kind === 'pane') copy.state.model = operation.text+ if (operation.kind === 'config') copy.state.effort = 'auto'+ const selectedModel = copy.state.model && copy.state.effort ? encodeRuntimeProfile({ sessionId: copy.session.agentId,+ engine: copy.session.engine, model: copy.state.model, effort: copy.state.effort }) : null+ return { state: copy.state, cliVersion: copy.session.cliVersion, control: copy.control ?? null, selectedModel, supportsControl: true }+}+function setup() {+ const s = session(), bindings = new Map([[s.agentId, s]])+ const changed = vi.fn()+ const read = vi.fn(async (_engine: string, context: RuntimeContext, operation: RuntimeOperation) => result(context, operation))+ const sessions = createRuntimeSessions({ resolve: id => bindings.get(id) ?? [...bindings.values()].find(s => s.sessionId === id),+ transport: { read, connected: vi.fn(), disconnected: vi.fn() }, changed })+ active.push(sessions)+ const seed = () => sessions.read(s, { kind: 'records', records: [{ model: 'old', effort: 'low' }] })+ return { s, bindings, changed, read, sessions, seed }+}+afterEach(() => { active.splice(0).forEach(s => s.stop()); vi.useRealTimers(); vi.restoreAllMocks() })++describe('core runtime profile authority', () => {+ it('stages bounded evidence and installs profile and live cursor together only once', async () => {+ const t = setup(); await t.seed()+ const staged = t.sessions.stage(t.s, true, true)+ const records = Array.from({ length: 1025 }, (_, i) => ({ model: String(i), effort: 'high' }))+ await staged.ingest(records)+ expect(t.read.mock.calls.slice(1).map(c => c[2].kind === 'records' ? c[2].records.length : 0)).toEqual([512, 512, 1])+ expect(t.sessions.getState(t.s.sessionId).model).toBe('old')+ await staged.config()+ expect(staged.commit(() => false)).toBe(false)+ const install = vi.fn(() => { expect(t.sessions.getState(t.s.sessionId).model).toBe('old'); return true })+ expect(staged.commit(install)).toBe(true)+ expect(staged.commit(install)).toBe(false)+ expect(install).toHaveBeenCalledOnce()+ expect(t.sessions.getState(t.s.sessionId)).toMatchObject({ model: '1024', effort: 'auto' })+ expect(t.sessions.selectedModel(t.s)).toBe(profile(t.s, '1024', 'auto').id)+ })++ it('splits byte-heavy evidence and rejects a record larger than the request allowance', async () => {+ const t = setup(), staged = t.sessions.stage(t.s, false, false)+ const large = Object.fromEntries(Array.from({ length: 16 }, (_, i) => [`k${i}`, 'x'.repeat(32_768)]))+ await staged.ingest([large, large, large])+ expect(t.read.mock.calls.map(c => c[2].kind === 'records' ? c[2].records.length : 0)).toEqual([1, 1, 1])+ await expect(staged.ingest([{ large: 'x'.repeat(1024 * 1024) }])).rejects.toThrow('ENGINE_REPLY_TOO_LARGE')+ const empty = t.sessions.stage(t.s, false, true)+ await empty.ingest([])+ expect(empty.commit()).toBe(true)+ })++ it.each(['binding', 'control', 'version', 'forget', 'stop'] as const)('rejects late worker evidence after %s changes', async change => {+ const t = setup(); await t.seed()+ const entered = deferred<void>(), response = deferred<RuntimeAnswer>()+ t.read.mockImplementationOnce(async (_e, context, operation) => {+ entered.resolve(); await response.promise; return result(context, operation)+ })+ const read = t.sessions.read(t.s, { kind: 'pane', text: 'late' })+ const rejected = expect(read).rejects.toThrow('ENGINE_STALE_REPLY')+ await entered.promise+ if (change === 'binding') t.bindings.set(t.s.agentId, { ...t.s, boundAt: 2 })+ if (change === 'control') t.sessions.beginControl(t.s, profile(t.s))+ if (change === 'version') t.bindings.set(t.s.agentId, { ...t.s, cliVersion: '2.1.210' })+ if (change === 'forget') t.sessions.forget(t.s.sessionId)+ if (change === 'stop') t.sessions.stop()+ response.resolve(result({ session: t.s, state: blankRuntimeState() }, { kind: 'describe' }))+ await rejected+ expect(t.sessions.getState(t.s.sessionId).model).not.toBe('late')+ })++ it('does not let an old binding evict a newer view and fences staged configuration', async () => {+ const t = setup(); await t.seed()+ const newer = { ...t.s, sessionId: 'new-conversation', boundAt: 2 }+ t.bindings.set(t.s.agentId, newer)+ await t.sessions.read(newer, { kind: 'records', records: [{ model: 'newer', effort: 'high' }] })+ expect(() => t.sessions.stage(t.s, false, false)).toThrow('ENGINE_STALE_REPLY')+ expect(t.sessions.selectedModel(t.s)).toBeNull()+ expect(t.sessions.getState(newer.sessionId).model).toBe('newer')+ const stage = t.sessions.stage(newer, false, true), entered = deferred<void>(), resume = deferred<void>()+ t.read.mockImplementationOnce(async (_e, c, o) => { entered.resolve(); await resume.promise; return result(c, o) })+ const config = stage.config(), rejected = expect(config).rejects.toThrow('ENGINE_STALE_REPLY')+ await entered.promise+ t.sessions.beginControl(newer, profile(newer))+ resume.resolve(); await rejected+ expect(stage.commit()).toBe(false)+ await expect(stage.ingest([{ model: 'late' }])).rejects.toThrow('ENGINE_STALE_REPLY')+ })++ it('serializes worker observations and uses the accepted state for each next request', async () => {+ const t = setup(), entered = deferred<void>(), resume = deferred<void>()+ t.read.mockImplementationOnce(async (_e, c, o) => { entered.resolve(); await resume.promise; return result(c, o) })+ const one = t.seed(); await entered.promise+ const two = t.sessions.read(t.s, { kind: 'pane', text: 'two' })+ expect(t.read).toHaveBeenCalledOnce()+ resume.resolve(); await Promise.all([one, two])+ expect(t.read.mock.calls[1][1].state).toMatchObject({ model: 'old', effort: 'low' })+ expect(t.sessions.getState(t.s.agentId).model).toBe('two')+ const state = t.sessions.getState(t.s.agentId); state.model = 'caller mutation'+ expect(t.sessions.getState(t.s.agentId).model).toBe('two')+ const before = t.sessions.getState(t.s.agentId)+ await t.sessions.read(t.s, { kind: 'describe' })+ expect(t.sessions.getState(t.s.agentId)).toEqual(before)+ })++ it('bounds queued work and rejects queued calls for a forgotten session', async () => {+ const t = setup(), entered = deferred<void>(), resume = deferred<void>()+ t.read.mockImplementationOnce(async (_e, c, o) => { entered.resolve(); await resume.promise; return result(c, o) })+ const jobs = Array.from({ length: 256 }, () => t.sessions.read(t.s, { kind: 'describe' }).catch(e => e.message))+ await entered.promise+ await expect(t.sessions.read(t.s, { kind: 'describe' })).rejects.toThrow('ENGINE_BUSY')+ t.sessions.forget(t.s.agentId); resume.resolve()+ expect(new Set(await Promise.all(jobs))).toEqual(new Set(['ENGINE_STALE_REPLY']))+ expect(t.read).toHaveBeenCalledOnce()+ })++ it('expires queued work instead of waiting through an entire saturated engine backlog', async () => {+ const t = setup(), entered = deferred<void>(), resume = deferred<void>()+ let time = 0; vi.spyOn(performance, 'now').mockImplementation(() => time)+ t.read.mockImplementationOnce(async (_e, c, o) => { entered.resolve(); await resume.promise; return result(c, o) })+ const first = t.seed(); await entered.promise+ const second = t.sessions.read(t.s, { kind: 'config' }), expired = expect(second).rejects.toThrow('ENGINE_BUSY')+ time = 5000; resume.resolve(); await first; await expired+ expect(t.read).toHaveBeenCalledOnce()+ expect(t.sessions.getState(t.s.sessionId).model).toBe('old')+ })++ it('never commits a partially reduced page after a later worker failure', async () => {+ const t = setup(); await t.seed()+ const stage = t.sessions.stage(t.s, false, false)+ await stage.ingest([{ model: 'partial' }])+ t.read.mockRejectedValueOnce(new Error('ENGINE_UNAVAILABLE'))+ await expect(stage.config()).rejects.toThrow('ENGINE_UNAVAILABLE')+ expect(stage.commit()).toBe(false)+ expect(t.sessions.getState(t.s.sessionId).model).toBe('old')+ })++ it('answers queue expiry while the active request is pending without releasing its successor early', async () => {+ vi.useFakeTimers()+ const t = setup(), firstEntered = deferred<void>(), secondEntered = deferred<void>()+ const firstResume = deferred<void>(), secondResume = deferred<void>()+ t.read.mockImplementationOnce(async (_e, c, o) => { firstEntered.resolve(); await firstResume.promise; return result(c, o) })+ t.read.mockImplementationOnce(async (_e, c, o) => { secondEntered.resolve(); await secondResume.promise; return result(c, o) })+ const first = t.sessions.read(t.s, { kind: 'describe' }); await firstEntered.promise+ await vi.advanceTimersByTimeAsync(1000)+ const second = t.sessions.read(t.s, { kind: 'describe' })+ await vi.advanceTimersByTimeAsync(1000)+ const expired = t.sessions.read(t.s, { kind: 'describe' }).catch(e => e.message)+ await vi.advanceTimersByTimeAsync(2900)+ firstResume.resolve(); await first; await secondEntered.promise+ await vi.advanceTimersByTimeAsync(2100)+ await expect(expired).resolves.toBe('ENGINE_BUSY')+ const next = t.sessions.read(t.s, { kind: 'describe' })+ await vi.advanceTimersByTimeAsync(0)+ expect(t.read).toHaveBeenCalledTimes(2)+ secondResume.resolve(); await second; await next+ expect(t.read).toHaveBeenCalledTimes(3)+ expect(vi.getTimerCount()).toBe(0)+ })++ it('copies control snapshots and invalidates hydration when core confirms a newer profile', async () => {+ const t = setup(), target = profile(t.s)+ t.sessions.beginControl(t.s, target)+ const stage = t.sessions.stage(t.s, true, true)+ target.model = 'mutated by caller'+ await stage.ingest([{ model: 'new', effort: 'high' }])+ expect(t.read.mock.calls[0][1].control!.target.model).toBe('new')+ t.sessions.confirmEffort(t.s.sessionId, 'low')+ expect(stage.commit()).toBe(false)+ t.sessions.confirmControlProfile(profile(t.s, 'different'))+ expect(t.sessions.getState(t.s.agentId).model).toBe('different')+ })++ it('commits prepared live evidence only while its binding and control revision remain current', async () => {+ const t = setup(); await t.seed()+ const commit = await t.sessions.prepare(t.s, [{ model: 'new', effort: 'high', version: '2.1.210' }])+ expect(t.s.cliVersion).toBe('2.1.209')+ expect(commit()).toBe(true)+ expect(t.s.cliVersion).toBe('2.1.210')+ const stale = await t.sessions.prepare(t.s, [{ model: 'stale' }])+ t.sessions.cancelControl(t.s.agentId)+ expect(stale()).toBe(false)+ expect(t.sessions.getState(t.s.agentId).model).toBe('new')+ })++ it('keeps control confirmations, waiters, cancellation and debounced notifications in core', async () => {+ vi.useFakeTimers()+ const t = setup(); await t.seed(); await vi.advanceTimersByTimeAsync(120); t.changed.mockClear()+ const target = profile(t.s)+ expect(t.sessions.beginControl(t.s, target)).toBe(true)+ expect(t.sessions.beginControl(t.s, target)).toBe(false)+ const model = t.sessions.waitForModel(t.s.agentId, 500), full = t.sessions.waitForProfile(t.s.sessionId, 500)+ await t.sessions.read(t.s, { kind: 'records', records: [{ model: 'new' }] })+ await expect(model).resolves.toBe(true)+ t.sessions.confirmEffort(t.s.agentId, 'invalid')+ expect(t.sessions.getState(t.s.agentId).effort).toBe('low')+ t.sessions.confirmEffort(t.s.sessionId, 'high')+ await expect(full).resolves.toBe(true)+ await expect(t.sessions.waitForProfile(t.s.agentId, 100)).resolves.toBe(true)+ await vi.advanceTimersByTimeAsync(120); expect(t.changed).not.toHaveBeenCalled()+ t.sessions.finishControl(t.s); await vi.advanceTimersByTimeAsync(120)+ expect(t.changed).toHaveBeenCalledOnce()+ expect(t.sessions.selectedModel(t.s)).toBe(target.id)+ expect(t.sessions.beginControl(t.s, target)).toBe(true)+ await expect(t.sessions.waitForModel(t.s.sessionId, 100)).resolves.toBe(true)+ t.sessions.cancelControl(t.s.sessionId); t.sessions.cancelControl(t.s.sessionId)+ await vi.advanceTimersByTimeAsync(120); expect(t.changed).toHaveBeenCalledTimes(2)+ })++ it('confirms public-id and legacy-id targets and cleans up waiters on timeout, forget and shutdown', async () => {+ vi.useFakeTimers()+ const t = setup(); await t.seed()+ const target = profile(t.s), legacy = { ...target, sessionId: t.s.sessionId }+ legacy.id = encodeRuntimeProfile(legacy)+ expect(t.sessions.beginControl(t.s, legacy)).toBe(true)+ const waiting = t.sessions.waitForProfile(t.s.sessionId, 100)+ t.sessions.confirmControlProfile(legacy); await expect(waiting).resolves.toBe(true)+ expect(t.sessions.selectedModel(t.s)).toBe(target.id)+ t.sessions.cancelControl(t.s.sessionId)+ const expired = t.sessions.waitForModel(t.s.agentId, 10)+ await vi.advanceTimersByTimeAsync(10); await expect(expired).resolves.toBe(false)+ const forgotten = t.sessions.waitForModel(t.s.agentId, 100)+ t.sessions.forget(t.s.agentId); await expect(forgotten).resolves.toBe(false)+ const unknown = t.sessions.waitForProfile('unknown', 100)+ t.sessions.stop(); await expect(unknown).resolves.toBe(false)+ await expect(t.sessions.waitForProfile('', 100)).resolves.toBe(false)+ await expect(t.sessions.waitForProfile('unknown', 100)).resolves.toBe(false)+ t.sessions.cancelControl('unknown'); t.sessions.finishControl(t.s)+ t.sessions.confirmEffort('unknown', 'high'); t.sessions.confirmControlProfile(target)+ t.sessions.forget('unknown'); t.sessions.forget('')+ })++ it('suppresses reconciliation changes and cancels stale notifications', async () => {+ vi.useFakeTimers()+ const t = setup()+ await t.sessions.withoutChangeEvents(() => t.sessions.withoutChangeEvents(t.seed))+ await vi.advanceTimersByTimeAsync(120); expect(t.changed).not.toHaveBeenCalled()+ await expect(t.sessions.withoutChangeEvents(async () => { throw new Error('failed') })).rejects.toThrow('failed')+ await t.sessions.read(t.s, { kind: 'pane', text: 'a' }, true)+ await vi.advanceTimersByTimeAsync(120); expect(t.changed).not.toHaveBeenCalled()+ await t.sessions.read(t.s, { kind: 'pane', text: 'b' })+ await t.sessions.read(t.s, { kind: 'pane', text: 'c' })+ await vi.advanceTimersByTimeAsync(120); expect(t.changed).toHaveBeenCalledOnce()+ await t.sessions.read(t.s, { kind: 'pane', text: 'd' })+ t.bindings.clear(); await vi.advanceTimersByTimeAsync(120)+ expect(t.changed).toHaveBeenCalledOnce()+ })++ it('allows unbound catalog reads without caching a conversation or crossing agent state', async () => {+ const t = setup(); t.s.sessionId = ''+ const other = { ...session('other'), sessionId: '' }; t.bindings.set(other.agentId, other)+ await t.seed()+ expect(t.sessions.getState(t.s.agentId)).toEqual(blankRuntimeState())+ expect(t.sessions.selectedModel(t.s)).toBeNull()+ expect(t.sessions.getState(other.agentId)).toEqual(blankRuntimeState())+ expect(t.sessions.beginControl(t.s, profile(t.s))).toBe(false)+ t.sessions.confirmEffort(t.s.agentId, 'high')+ t.sessions.finishControl(t.s)+ expect(t.changed).not.toHaveBeenCalled()+ expect(t.sessions.getState('')).toEqual(blankRuntimeState())+ })++ it('seeds hydration from registry facts, handles confirmation without a control, and times out waiters independently', async () => {+ vi.useFakeTimers()+ const t = setup(); t.s.model = 'registry-model'+ const staged = t.sessions.stage(t.s, true, true)+ await staged.config(); expect(staged.commit()).toBe(true)+ expect(t.sessions.getState(t.s.sessionId).model).toBe('registry-model')+ t.sessions.confirmEffort(t.s.sessionId, 'medium')+ expect(t.sessions.selectedModel(t.s)).toBe(profile(t.s, 'registry-model', 'medium').id)+ const early = t.sessions.waitForModel(t.s.sessionId, 10), later = t.sessions.waitForProfile(t.s.sessionId, 20)+ await vi.advanceTimersByTimeAsync(10); await expect(early).resolves.toBe(false)+ await vi.advanceTimersByTimeAsync(10); await expect(later).resolves.toBe(false)+ })+})diff --git a/cli/src/core/engines/runtimeSessions.ts b/cli/src/core/engines/runtimeSessions.tsnew file mode 100644index 000000000..9219e9284--- /dev/null+++ b/cli/src/core/engines/runtimeSessions.ts@@ -0,0 +1,260 @@+/** Core-owned profile snapshots and transactions. Vendor interpretation happens only in the worker. */+import type { RuntimeAnswer, RuntimeOperation } from '../../engines/worker/runtimeProtocol.js'+import { RUNTIME_RECORDS, RUNTIME_REQUEST_BYTES, RUNTIME_WAIT_MS } from '../../engines/worker/runtimeProtocol.js'+import type { RuntimeContext, RuntimeControl, RuntimeProfile, RuntimeRecord, RuntimeSession, RuntimeState } from '../../engines/facets/runtime.js'+import { blankRuntimeState, encodeRuntimeProfile, RUNTIME_EFFORTS } from '../../engines/kit/runtime.js'+import { EngineReadError } from '../../engines/worker/protocol.js'+import type { RegisteredSession } from '../../lib/registry.js'+import { transcriptReadIdentity } from '../transcripts/readIdentity.js'+import { parseRuntimeProfile } from '../../lib/runtimeProfileWire.js'+import type { RuntimeTransport } from './runtimeTransport.js'++interface View {+ agentId: string+ sessionId: string+ identity: string+ revision: number+ state: RuntimeState+ control?: RuntimeControl+ selected: string | null+}+interface Waiter { check(): boolean; resolve(value: boolean): void; timer: ReturnType<typeof setTimeout> }+export interface RuntimeSessionDeps {+ resolve(id: string): RegisteredSession | undefined+ transport: RuntimeTransport+ changed?(sessionId: string): void+}+export interface RuntimeStage {+ ingest(records: readonly RuntimeRecord[]): Promise<void>+ config(): Promise<void>+ /** Atomically install the associated live parser and its reported profile. */+ commit(install?: () => boolean): boolean+}++const binding = (s: RegisteredSession | undefined): string => s ? JSON.stringify([transcriptReadIdentity(s), s.cwd, !!s.gateway]) : ''+const snapshot = (s: RegisteredSession): RuntimeSession => ({ agentId: s.agentId, sessionId: s.sessionId, engine: s.engine,+ model: typeof s.model === 'string' ? s.model : null, cliVersion: s.cliVersion, cwd: s.cwd, transcriptPath: s.transcriptPath, codexHome: s.codexHome })+const controlCopy = (control: RuntimeControl | undefined): RuntimeControl | undefined => control && { ...control, target: { ...control.target } }+const unavailable = (): never => { throw new EngineReadError('ENGINE_STALE_REPLY') }++export function createRuntimeSessions(deps: RuntimeSessionDeps) {+ const views = new Map<string, View>()+ const queues = new Map<string, Promise<void>>()+ const pending = new Map<string, number>()+ const changes = new Map<string, ReturnType<typeof setTimeout>>()+ const waiters = new Map<string, Set<Waiter>>()+ let suppressed = 0+ let stopped = false++ const valid = (view: View): boolean => !stopped && views.get(view.agentId) === view && view.identity === binding(deps.resolve(view.agentId))+ const wake = (id: string): void => {+ for (const waiter of waiters.get(id) ?? []) if (waiter.check()) {+ clearTimeout(waiter.timer); waiters.get(id)!.delete(waiter); waiter.resolve(true)+ }+ if (!waiters.get(id)?.size) waiters.delete(id)+ }+ const forget = (id: string): void => {+ if (!id) return+ const view = [...views.values()].find(v => v.sessionId === id || v.agentId === id)+ if (view) { view.revision++; views.delete(view.agentId) }+ const sid = view?.sessionId ?? id+ const timer = changes.get(sid)+ if (timer) clearTimeout(timer)+ changes.delete(sid)+ for (const waiter of waiters.get(sid) ?? []) { clearTimeout(waiter.timer); waiter.resolve(false) }+ waiters.delete(sid)+ }+ const viewFor = (s: RegisteredSession): View => {+ const previous = views.get(s.agentId)+ const identity = binding(s)+ // A delayed caller holding the old binding must not evict a newer accepted view.+ if (stopped || identity !== binding(deps.resolve(s.agentId))) unavailable()+ if (previous?.identity === identity) return previous+ if (previous) forget(previous.agentId)+ const view: View = { agentId: s.agentId, sessionId: s.sessionId, identity, revision: 0, state: blankRuntimeState(), selected: null }+ views.set(s.agentId, view)+ return view+ }+ const byId = (id: string): View | undefined => {+ if (!id) return undefined+ const session = deps.resolve(id)+ if (!session) return undefined+ const view = views.get(session.agentId)+ return view && valid(view) ? view : undefined+ }+ const notify = (view: View): void => {+ if (!view.sessionId) return+ const old = changes.get(view.sessionId)+ if (old) clearTimeout(old)+ changes.set(view.sessionId, setTimeout(() => {+ changes.delete(view.sessionId)+ if (valid(view) && !view.control) deps.changed?.(view.sessionId)+ }, 120))+ }+ const slot = async <T>(engine: string, run: () => Promise<T>): Promise<T> => {+ if ((pending.get(engine) ?? 0) >= 256) throw new EngineReadError('ENGINE_BUSY')+ const deadline = performance.now() + RUNTIME_WAIT_MS+ pending.set(engine, (pending.get(engine) ?? 0) + 1)+ const before = queues.get(engine) ?? Promise.resolve()+ let release!: () => void+ const tail = new Promise<void>(resolve => { release = resolve })+ queues.set(engine, tail)+ try {+ await new Promise<void>((resolve, reject) => {+ const timer = setTimeout(() => reject(new EngineReadError('ENGINE_BUSY')), RUNTIME_WAIT_MS)+ void before.then(() => { clearTimeout(timer); resolve() })+ })+ if (performance.now() >= deadline) throw new EngineReadError('ENGINE_BUSY')+ return await run()+ } finally {+ // Expiry answers the caller immediately, but its successor still waits for the active call.+ // Keep that reservation in the cap until released so expired queue links cannot grow forever.+ void before.then(() => {+ pending.set(engine, pending.get(engine)! - 1); release()+ if (queues.get(engine) === tail) queues.delete(engine)+ })+ }+ }+ const contextFor = (s: RegisteredSession, view: View): RuntimeContext => ({ session: snapshot(s), state: { ...view.state },+ ...(view.control ? { control: controlCopy(view.control) } : {}) })+ const accept = (view: View, answer: RuntimeAnswer, silent: boolean): void => {+ const before = view.selected+ view.state = view.sessionId ? { ...answer.state } : blankRuntimeState()+ view.control = controlCopy(answer.control ?? undefined)+ view.selected = view.sessionId ? answer.selectedModel : null+ view.revision+++ const current = deps.resolve(view.agentId)!+ current.cliVersion = answer.cliVersion+ wake(view.sessionId)+ if (!silent && !suppressed && before !== view.selected && !view.control) notify(view)+ }+ const read = (s: RegisteredSession, operation: RuntimeOperation, silent = false): Promise<RuntimeAnswer> => {+ const identity = binding(s), view = viewFor(s)+ return slot(s.engine, async () => {+ if (!valid(view) || view.identity !== identity) unavailable()+ const current = deps.resolve(view.agentId)!, version = current.cliVersion, revision = view.revision+ const answer = await deps.transport.read(current.engine, contextFor(current, view), operation)+ if (!valid(view) || revision !== view.revision || deps.resolve(view.agentId)?.cliVersion !== version) unavailable()+ if (operation.kind === 'records' || operation.kind === 'pane' || operation.kind === 'config') accept(view, answer, silent)+ return answer+ })+ }++ const stage = (s: RegisteredSession, hydrate: boolean, silent: boolean): RuntimeStage => {+ const view = viewFor(s), revision = view.revision, version = s.cliVersion+ const context = contextFor(s, view)+ if (hydrate) context.state = { ...blankRuntimeState(), model: typeof s.model === 'string' ? s.model : null, cliVersion: s.cliVersion }+ let answer: RuntimeAnswer | null = null+ let committed = false, failed = false+ const current = (): boolean => !committed && !failed && valid(view) && view.revision === revision && deps.resolve(view.agentId)?.cliVersion === version+ const reduce = (operation: RuntimeOperation): Promise<void> => slot(s.engine, async () => {+ if (!current()) unavailable()+ const next = await deps.transport.read(s.engine, context, operation)+ if (!current()) unavailable()+ context.state = { ...next.state }; context.session.cliVersion = next.cliVersion+ context.control = controlCopy(next.control ?? undefined); answer = next+ }).catch(error => { failed = true; throw error })+ return {+ async ingest(records) {+ let batch: RuntimeRecord[] = [], bytes = Buffer.byteLength(JSON.stringify(context)) + 256+ for (const evidence of records) {+ const size = Buffer.byteLength(JSON.stringify(evidence)) + 1+ if (batch.length && (batch.length >= RUNTIME_RECORDS || bytes + size > RUNTIME_REQUEST_BYTES - 1024)) {+ await reduce({ kind: 'records', records: batch }); batch = []; bytes = Buffer.byteLength(JSON.stringify(context)) + 256+ }+ if (bytes + size > RUNTIME_REQUEST_BYTES - 1024) { failed = true; throw new EngineReadError('ENGINE_REPLY_TOO_LARGE') }+ batch.push(evidence); bytes += size+ }+ if (batch.length) await reduce({ kind: 'records', records: batch })+ },+ config: () => reduce({ kind: 'config' }),+ commit(install = () => true) {+ if (!current() || !install()) return false+ committed = true+ if (answer) accept(view, answer, silent)+ return true+ },+ }+ }+ const waitFor = (id: string, check: () => boolean, timeout: number): Promise<boolean> => {+ id = deps.resolve(id)?.sessionId ?? id+ if (!id || stopped) return Promise.resolve(false)+ if (check()) return Promise.resolve(true)+ return new Promise(resolve => {+ const waiter: Waiter = { check, resolve, timer: setTimeout(() => {+ const set = waiters.get(id)+ set?.delete(waiter)+ if (!set?.size) waiters.delete(id)+ resolve(false)+ }, timeout) }+ const set = waiters.get(id) ?? new Set(); set.add(waiter); waiters.set(id, set)+ })+ }+ return {+ read,+ stage,+ async prepare(s: RegisteredSession, records: readonly RuntimeRecord[]): Promise<() => boolean> {+ const pending = stage(s, false, false)+ await pending.ingest(records)+ return () => pending.commit()+ },+ selectedModel(s: RegisteredSession): string | null {+ return s.sessionId && binding(s) === binding(deps.resolve(s.agentId)) ? byId(s.agentId)?.selected ?? null : null+ },+ getState(id: string): RuntimeState { return { ...(byId(id)?.state ?? blankRuntimeState()) } },+ async withoutChangeEvents<T>(run: () => Promise<T>): Promise<T> { suppressed++; try { return await run() } finally { suppressed-- } },+ beginControl(s: RegisteredSession, target: RuntimeProfile): boolean {+ const view = viewFor(s)+ if (!s.sessionId || view.control || !valid(view)) return false+ const current = parseRuntimeProfile(view.selected)+ view.control = { target: { ...target }, before: view.selected,+ modelConfirmed: current?.model === target.model, effortConfirmed: current?.effort === target.effort }+ view.revision+++ return true+ },+ cancelControl(id: string): void {+ const view = byId(id)+ if (!view) return+ const previous = view.control+ view.control = undefined; view.revision++; wake(view.sessionId)+ if (previous) notify(view)+ },+ finishControl(s: RegisteredSession): void {+ const view = byId(s.agentId)+ if (!view) return+ view.control = undefined; view.revision++; wake(view.sessionId); notify(view)+ },+ confirmEffort(id: string, effort: string): void {+ const view = byId(id)+ if (!view?.sessionId || !RUNTIME_EFFORTS.has(effort)) return+ // Confirmation comes from core's checked control driver, never an arbitrary transcript field.+ view.state = { ...view.state, effort, observedAt: Date.now() }+ const selection = parseRuntimeProfile(view.selected)+ const s = deps.resolve(view.agentId)!+ if (selection) view.selected = encodeRuntimeProfile({ sessionId: s.agentId, engine: s.engine, model: selection.model, effort })+ if (view.control) view.control.effortConfirmed = view.control.target.effort === effort+ view.revision++; wake(view.sessionId)+ },+ confirmControlProfile(target: RuntimeProfile): void {+ const view = byId(target.sessionId)+ if (!view) return+ view.state = { ...view.state, model: target.model, effort: target.effort, observedAt: Date.now() }+ view.selected = encodeRuntimeProfile({ ...target, sessionId: view.agentId })+ if (view.control?.target.id === target.id) { view.control.modelConfirmed = true; view.control.effortConfirmed = true }+ view.revision++; wake(view.sessionId)+ },+ waitForModel(id: string, timeout: number): Promise<boolean> { return waitFor(id, () => byId(id)?.control?.modelConfirmed === true, timeout) },+ waitForProfile(id: string, timeout: number): Promise<boolean> { return waitFor(id, () => {+ const control = byId(id)?.control; return control?.modelConfirmed === true && control.effortConfirmed === true+ }, timeout) },+ forget,+ stop(): void {+ stopped = true+ for (const id of views.keys()) forget(id)+ for (const set of waiters.values()) for (const waiter of set) { clearTimeout(waiter.timer); waiter.resolve(false) }+ waiters.clear()+ },+ }+}++export type RuntimeSessions = ReturnType<typeof createRuntimeSessions>diff --git a/cli/src/core/engines/runtimeTransport.spec.ts b/cli/src/core/engines/runtimeTransport.spec.tsnew file mode 100644index 000000000..9eee1fe3a--- /dev/null+++ b/cli/src/core/engines/runtimeTransport.spec.ts@@ -0,0 +1,94 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { RuntimeContext } from '../../engines/facets/runtime.js'+import { blankRuntimeState } from '../../engines/kit/runtime.js'+import { engineRuntimeRequests } from '../../engines/worker/runtimeRequests.js'+import { RUNTIME_CAPABILITIES, RUNTIME_IN_FLIGHT, RUNTIME_READ, RUNTIME_REPLY_BYTES, RUNTIME_WAIT_MS } from '../../engines/worker/runtimeProtocol.js'+import { createRuntimeTransport, type RuntimeTransport } from './runtimeTransport.js'++const context = (): RuntimeContext => ({ session: { agentId: 'agent', sessionId: 'session', engine: 'claude', model: null,+ cliVersion: '2.1.209', cwd: null, transcriptPath: null }, state: blankRuntimeState() })+const operation = { kind: 'describe' } as const+const capability = { version: 1, runtime: 1, engine: 'claude' }+const answer = { version: 1, answer: { state: blankRuntimeState(), cliVersion: '2.1.209', control: null, selectedModel: null, supportsControl: true } }+const deferred = <T>() => { let resolve!: (v: T) => void; const promise = new Promise<T>(r => { resolve = r }); return { promise, resolve } }+function setup() {+ const call = vi.fn(async (_service: string, method: string, _payload: Record<string, unknown>, _waitMs: number): Promise<Record<string, unknown>> => method === RUNTIME_CAPABILITIES ? capability : answer)+ const transport = createRuntimeTransport({ call })+ transport.connected('engine-claude')+ return { call, transport, read: () => transport.read('claude', context(), operation) }+}+afterEach(() => vi.restoreAllMocks())++describe('core runtime transport', () => {+ it('negotiates once per connection and evaluates profiles in a real worker handler', async () => {+ const handlers = engineRuntimeRequests('claude')+ let transport: RuntimeTransport+ const call = vi.fn(async (service: string, method: string, payload: Record<string, unknown>) => {+ if (call.mock.calls.length === 1) transport.connected(service)+ return await handlers[method](payload, { owner: true, local: true }) as Record<string, unknown>+ })+ transport = createRuntimeTransport({ call })+ const read = () => transport.read('claude', context(), { kind: 'pane', text: 'Opus 5 with high effort' })+ expect((await read()).state).toMatchObject({ model: 'claude-opus-5', effort: 'high' })+ await read()+ expect(call.mock.calls.map(c => c[1])).toEqual([RUNTIME_CAPABILITIES, RUNTIME_READ, RUNTIME_READ])+ transport.disconnected('engine-claude'); transport.connected('engine-claude')+ await read()+ expect(call.mock.calls.filter(c => c[1] === RUNTIME_CAPABILITIES)).toHaveLength(2)+ transport.connected('unrelated'); transport.disconnected('unrelated')+ await expect(transport.read('unknown', context(), operation)).rejects.toThrow('ENGINE_INVALID_REQUEST')+ await expect(transport.read('codex', context(), operation)).rejects.toThrow('ENGINE_INVALID_REQUEST')+ })++ it('bounds in-flight calls and rejects results from a replaced connection', async () => {+ const t = setup(), work = deferred<typeof answer>()+ await t.read()+ t.call.mockImplementation(() => work.promise)+ const tasks = Array.from({ length: RUNTIME_IN_FLIGHT }, () => t.read())+ await expect(t.read()).rejects.toThrow('ENGINE_BUSY')+ t.transport.disconnected('engine-claude'); t.transport.connected('engine-claude')+ work.resolve(answer)+ for (const task of tasks) await expect(task).rejects.toThrow('ENGINE_STALE_REPLY')+ t.call.mockImplementation(async (_service, method) => method === RUNTIME_CAPABILITIES ? capability : answer)+ expect(await t.read()).toEqual(answer.answer)+ })++ it('shares a single deadline across negotiation and the read', async () => {+ const t = setup()+ let time = 10+ vi.spyOn(performance, 'now').mockImplementation(() => time)+ t.call.mockImplementation(async (_service, method, _payload, waitMs) => {+ if (method === RUNTIME_CAPABILITIES) { expect(waitMs).toBe(RUNTIME_WAIT_MS); time += 4_000; return capability }+ expect(waitMs).toBe(1_000)+ return answer+ })+ await t.read()+ t.call.mockImplementation(async () => { time += RUNTIME_WAIT_MS + 1; return answer })+ await expect(t.read()).rejects.toThrow('ENGINE_UNAVAILABLE')+ const noTime = setup()+ let calls = 0+ vi.spyOn(performance, 'now').mockImplementation(() => ++calls === 1 ? 0 : RUNTIME_WAIT_MS)+ await expect(noTime.read()).rejects.toThrow('ENGINE_UNAVAILABLE')+ expect(noTime.call).not.toHaveBeenCalled()+ })++ it('rejects bad capabilities, service errors, malformed and oversized results without fallback', async () => {+ for (const reply of [{ ...capability, runtime: 2 }, { ...capability, engine: 'codex' }, { ...capability, version: 2 },+ { version: 1, error: 'unexpected' }, { version: 1, answer: {} }]) {+ const t = setup(); t.call.mockResolvedValue(reply as typeof capability)+ await expect(t.read()).rejects.toThrow('ENGINE_INVALID_REPLY')+ }+ for (const error of ['SERVICE_FAILED', 'SERVICE_UNAVAILABLE', 'ENGINE_BUSY']) {+ const t = setup(); t.call.mockResolvedValue({ version: 1, error } as unknown as typeof capability)+ await expect(t.read()).rejects.toThrow(error === 'ENGINE_BUSY' ? error : 'ENGINE_UNAVAILABLE')+ }+ const t = setup(); await t.read()+ t.call.mockRejectedValueOnce(new Error('link lost'))+ await expect(t.read()).rejects.toThrow('ENGINE_UNAVAILABLE')+ t.call.mockResolvedValueOnce({ version: 1, answer: {} } as typeof answer)+ await expect(t.read()).rejects.toThrow('ENGINE_INVALID_REPLY')+ t.call.mockResolvedValueOnce({ ...answer, extra: 'x'.repeat(RUNTIME_REPLY_BYTES) })+ await expect(t.read()).rejects.toThrow('ENGINE_INVALID_REPLY')+ expect(await t.read()).toEqual(answer.answer)+ })+})diff --git a/cli/src/core/engines/runtimeTransport.ts b/cli/src/core/engines/runtimeTransport.tsnew file mode 100644index 000000000..20f0aba95--- /dev/null+++ b/cli/src/core/engines/runtimeTransport.ts@@ -0,0 +1,57 @@+/** Core's runtime port: plain snapshots, a single deadline, and connection-generation fencing. */+import type { RuntimeContext } from '../../engines/facets/runtime.js'+import { EngineReadError, readerEngine, READER_ERRORS, READER_SERVICES, type ReaderEngine } from '../../engines/worker/protocol.js'+import { runtimeAnswer, RUNTIME_CAPABILITIES, RUNTIME_IN_FLIGHT, RUNTIME_READ, RUNTIME_REPLY_BYTES,+ RUNTIME_VERSION, RUNTIME_WAIT_MS, type RuntimeAnswer, type RuntimeOperation } from '../../engines/worker/runtimeProtocol.js'++export interface RuntimeTransportDeps {+ call(service: string, method: string, payload: Record<string, unknown>, waitMs: number): Promise<Record<string, unknown>>+}++export function createRuntimeTransport(deps: RuntimeTransportDeps) {+ const states = new Map(Object.values(READER_SERVICES).map(service => [service as string,+ { generation: 0, connected: false, capable: false, pending: 0 }]))+ const fail = (code: EngineReadError['code']): never => { throw new EngineReadError(code) }+ return {+ connected(service: string): void {+ const state = states.get(service)+ if (state) { state.generation++; state.connected = true; state.capable = false }+ },+ disconnected(service: string): void {+ const state = states.get(service)+ if (state) { state.generation++; state.connected = false; state.capable = false }+ },+ async read(engine: string, context: RuntimeContext, operation: RuntimeOperation): Promise<RuntimeAnswer> {+ if (!readerEngine(engine) || context.session.engine !== engine) fail('ENGINE_INVALID_REQUEST')+ const service = READER_SERVICES[engine as ReaderEngine], state = states.get(service)!+ if (state.pending >= RUNTIME_IN_FLIGHT) fail('ENGINE_BUSY')+ const generation = state.generation + (state.connected ? 0 : 1)+ const deadline = performance.now() + RUNTIME_WAIT_MS+ state.pending+++ const call = async (method: string, payload: Record<string, unknown>): Promise<Record<string, unknown>> => {+ const remaining = Math.ceil(deadline - performance.now())+ if (remaining <= 0) fail('ENGINE_UNAVAILABLE')+ const reply = await deps.call(service, method, { version: RUNTIME_VERSION, ...payload }, remaining)+ if (performance.now() > deadline) fail('ENGINE_UNAVAILABLE')+ if (reply.error === 'SERVICE_FAILED' || reply.error === 'SERVICE_UNAVAILABLE') fail('ENGINE_UNAVAILABLE')+ if (state.generation !== generation) fail('ENGINE_STALE_REPLY')+ if (reply.version !== RUNTIME_VERSION) fail('ENGINE_INVALID_REPLY')+ if (reply.error !== undefined) fail(READER_ERRORS.includes(reply.error as EngineReadError['code']) ? reply.error as EngineReadError['code'] : 'ENGINE_INVALID_REPLY')+ return reply+ }+ try {+ if (!state.capable) {+ const capability = await call(RUNTIME_CAPABILITIES, {})+ if (capability.runtime !== RUNTIME_VERSION || capability.engine !== engine) fail('ENGINE_INVALID_REPLY')+ state.capable = true+ }+ const reply = await call(RUNTIME_READ, { context, operation })+ if (Buffer.byteLength(JSON.stringify(reply)) > RUNTIME_REPLY_BYTES || !runtimeAnswer(reply.answer, context, operation)) fail('ENGINE_INVALID_REPLY')+ return reply.answer as RuntimeAnswer+ } catch (error) { throw error instanceof EngineReadError ? error : new EngineReadError('ENGINE_UNAVAILABLE') }+ finally { state.pending-- }+ },+ }+}++export type RuntimeTransport = ReturnType<typeof createRuntimeTransport>diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 9882a2b43..ca503e9f7 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -144,7 +144,7 @@ import { createExperimentHooks, wakeExperiments } from './experiments.js'import { answerExperimentQuery, createForExperiment } from './experimentQueries.js'import { createOrchestratorLink } from './orchestratorLink.js'import { daemonCommand } from '../lib/daemonCommand.js'-import { KNOWN_SERVICES, masterRunsLiveEngines, servicesTheMasterRuns } from '../harnessd/services.js'+import { KNOWN_SERVICES, masterRunsEngineRuntime, masterRunsLiveEngines, servicesTheMasterRuns } from '../harnessd/services.js'import { createTeamsLink, teamsOutOfProcess } from './teamsLink.js'import { createDevicesLink } from './devicesLink.js'import { CORE_EXIT_STOP, CORE_EXIT_UPDATE, PROBE_COMMAND } from '../harnessd/protocol.js'@@ -177,7 +177,9 @@ import { AgentCreationReceipts } from '../lib/agentCreationReceipt.js'import { agentFrame, lastActivityAt, type AgentFrame } from '../lib/agentFrame.js'import { forgetAgentProject } from '../lib/agentProject.js'import { agentTokenUsage } from '../lib/agentTokenUsage.js'-import { RuntimeProfileManager, type RuntimeModelOption } from '../lib/runtimeProfile.js'+import { LegacyRuntimeProfileManager, type RuntimeModelOption } from '../lib/runtimeProfileManager.js'+import { createRuntimeProfiles } from './engines/runtimeProfiles.js'+import { createRuntimeTransport } from './engines/runtimeTransport.js'import { RuntimeProfileController } from '../lib/runtimeProfileController.js'import { installTimestampedConsole, sid, prepareLogFile, trimLogFile, LOG_CHECK_INTERVAL_MS } from '../lib/log.js'import { backendHttpBase } from '../lib/controlPlane.js'@@ -534,7 +536,23 @@ async function runForeground(session: AuthSession | null): Promise<void> {const syncRecapPool = (): void => {ports.devices?.engines(registry.active().map((session) => session.engine))}- const runtimeProfiles = new RuntimeProfileManager()+ const outOfProcess = servicesTheMasterRuns(process.env, KNOWN_SERVICES)+ const liveHosted = masterRunsLiveEngines(process.env, process.ppid)+ const runtimeHosted = liveHosted && masterRunsEngineRuntime(process.env, process.ppid)+ // An older master's explicit capability report selects compatibility. A failed worker never does.+ const isolatedLive = (engine: string): boolean => liveHosted+ && readerEngine(engine) && outOfProcess.has(READER_SERVICES[engine])+ const isolatedRuntime = (engine: string): boolean => runtimeHosted && isolatedLive(engine)+ const inline = KNOWN_SERVICES.some((name) => !outOfProcess.has(name)) || !runtimeHosted+ ? await import('../services/inline.js') : null+ let serviceLinksRef: ServiceLinks | null = null+ const runtimeTransport = createRuntimeTransport({+ call: (service, type, payload, waitMs) => serviceLinksRef?.call(service, type, payload, waitMs) ?? Promise.resolve({ error: 'SERVICE_UNAVAILABLE' }),+ })+ const runtimeProfiles = createRuntimeProfiles({+ legacy: new LegacyRuntimeProfileManager(engine => isolatedRuntime(engine) ? undefined : inline?.runtimeFor(engine)),+ handles: isolatedRuntime,+ resolve: id => registry.resolve(id), transport: runtimeTransport })// An agent's Model/Effort choices, or every live agent's: what `models_list` answers (services/models.ts)// and the dial's picker reads, so neither can show a catalog the machine would not honour.const runtimeModels = (agentId?: string): Promise<RuntimeModelOption[]> => {@@ -778,23 +796,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {// only under a master, which is what gives this core the token they connect with. Their requests are// routed to them, and answered SERVICE_UNAVAILABLE while they are down (core/serviceLinks.ts).const serviceToken = process.env.HARNESSD_SUPERVISED === '1' ? process.env.HARNESSD_SERVICE_TOKEN : undefined- const outOfProcess = servicesTheMasterRuns(process.env, KNOWN_SERVICES)- // The services' own code, for those that run in this process (services/inline.ts): loaded only then, so- // one in its own process, as each is by default, is never loaded here.- // A reader-only older master knows these names but cannot host live parsers. Its explicit version- // report selects compatibility; a worker timeout or crash never activates an inline fallback.- const liveHosted = masterRunsLiveEngines(process.env, process.ppid)- const isolatedLive = (engine: string): boolean => liveHosted- && readerEngine(engine) && outOfProcess.has(READER_SERVICES[engine])- const inline = KNOWN_SERVICES.some((name) => !outOfProcess.has(name)) || !liveHosted- ? await import('../services/inline.js') : nullconst liveFor: LiveFor = (engine) => isolatedLive(engine) ? undefined : inline?.liveFor(engine)// The relay and its E2EE (gateway/): the backend link, the sessions and the keys, which every remote// client's frames go through, held at the same gate. In its own process by default (core/gatewayLink.ts),// or here (gateway/start.ts); the socket hears it through `fromGateway` and speaks to it in the clear.Object.assign(coreApi.terminals, createTerminalSessions({ agents: coreApi.agents, paneState: tmuxPaneState, processState: checkPidRuntime }))const account = (s = readAuthSession()): GatewayAccount => ({ machineId: s?.machineId ?? null, signIn: signInOf(s?.signInEpoch, s?.signInAcct), autonomousEnv: s?.autonomousEnv ?? env.AUTONOMOUS_ENV })- let serviceLinksRef: ServiceLinks | null = nullconst engineReaders = createEngineReaders({ isolated: outOfProcess, inline: inline?.engineTranscriptFor,call: (service, type, payload, waitMs) => serviceLinksRef?.call(service, type, payload, waitMs) ?? Promise.resolve({ error: 'SERVICE_UNAVAILABLE' }) })const liveTransport = createLiveTransport({@@ -916,7 +923,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {handles: isolatedLive,transport: liveTransport,bySession: (id) => registry.bySession(id),- frame: (session, frame) => ingest.acceptFrame(session.sessionId, session.engine, frame),+ prepareFrames: (session, frames) => runtimeProfiles.prepareFrames(session, frames),+ frame: (session, frame) => ingest.acceptFrame(session.sessionId, session.engine, frame, runtimeProfiles.handles(session.engine)),reattach: (session) => attachSession(session, true),})// Whether a turn is really working, beyond its transcript (core/turns/activity.ts).@@ -1190,6 +1198,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {connected: (service) => {engineReaders.connected(service)liveTransport.connected(service)+ runtimeTransport.connected(service)if (service === 'gateway') gatewayLink?.connected()if (service === 'teams') teamsLink.on()if (service === 'devices') devicesLink.connected()@@ -1199,6 +1208,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {disconnected: (service) => {engineReaders.disconnected(service)liveTransport.disconnected(service)+ runtimeTransport.disconnected(service)if (service === 'gateway') gatewayLink?.disconnected()if (service === 'devices') devicesLink.disconnected()if (service === 'wifi') wifiCore.stopped()@@ -1994,7 +2004,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {await watcher.pollAll()await Promise.all(registry.advertised().map(async (session) => {const capture = await captureTerminal(session.agentId, 120)- if (capture) runtimeProfiles.ingestPane(session, capture, true)+ if (capture) await runtimeProfiles.ingestPane(session, capture, true)}))})await syncTerminalTitles()@@ -2041,7 +2051,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {for (const session of registry.list()) {if (!PANE_POLLED_ENGINES.has(session.engine)) continuevoid captureTerminal(session.agentId, 60)- .then((capture) => { if (capture) runtimeProfiles.ingestPane(session, capture) })+ .then((capture) => capture ? runtimeProfiles.ingestPane(session, capture) : undefined).catch(() => undefined)}}, PANE_POLL_MS)@@ -2305,7 +2315,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {['the question watchers', () => questionWatcher.stopAll()],['the turn heartbeats', () => { for (const t of heartbeats.values()) clearInterval(t); heartbeats.clear() }],['the Cursor sub-agents', () => cursorSubagents.stop()], ['the normalizers', () => normalizers.stopPollers()],- ['Cursor discovery', () => cursorDiscovery.stop()], ['the transcript watcher', () => watcher.stop()],+ ['Cursor discovery', () => cursorDiscovery.stop()], ['the runtime profiles', () => runtimeProfiles.stop()], ['the transcript watcher', () => watcher.stop()],// The FIXED hook port, released before the successor binds it (no fallback → EADDRINUSE otherwise).// Process-owned agents stay in the persisted registry and are revalidated by its first discovery passes.['the hook connections', () => (hookServer as unknown as { closeAllConnections?: () => void }).closeAllConnections?.()],@@ -2355,6 +2365,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {normalizers.stopPollers()await cursorDiscovery.stop()await watcher.stop()+ runtimeProfiles.stop()await ports.sharing?.stop()// The data folder's socket first: a successor waiting for this core to leave (lib/localSocket.ts) can// start as soon as it is gone, whatever the clients below take to close.diff --git a/cli/src/core/transcripts/attach.spec.ts b/cli/src/core/transcripts/attach.spec.tsindex 4e3bdd0ad..be3332a09 100644--- a/cli/src/core/transcripts/attach.spec.ts+++ b/cli/src/core/transcripts/attach.spec.ts@@ -117,7 +117,7 @@ function remoteSetup(open = false) {]const remote: NonNullable<AttachDeps['remoteLive']> = {handles: engine => engine === 'claude', current: vi.fn(() => true),- prepare: vi.fn(async (_session, _options, observe) => { frames.forEach(observe); return candidate }),+ prepare: vi.fn(async (_session, _options, observe, observePage) => { await observePage?.(frames); frames.forEach(observe); return candidate }),install: vi.fn(() => true), discard: vi.fn(), retry: vi.fn(),}const p = setup({ remoteLive: remote, liveFor: vi.fn(() => { throw new Error('isolated parser must stay in its worker') }) })@@ -138,7 +138,7 @@ describe('attaching a session', () => {p.service.needsTranscript.mockReturnValue(true)expect(await p.attach.attachSession(s)).toBe(true)expect(p.deps.liveFor).not.toHaveBeenCalled()- expect(p.remote.prepare).toHaveBeenCalledWith(s, { live: false, end: undefined }, expect.any(Function))+ expect(p.remote.prepare).toHaveBeenCalledWith(s, { live: false, end: undefined }, expect.any(Function), undefined)expect(p.profile.ingest).toHaveBeenCalledExactlyOnceWith('metadata')expect(p.service.observeTranscript).toHaveBeenCalledExactlyOnceWith(s.agentId, s.sessionId, s.engine, 'record')expect(p.profile.commit).toHaveBeenCalledOnce()@@ -154,7 +154,7 @@ describe('attaching a session', () => {it('activates a first live worker stream without reading locally, including a session whose path is not announced yet', async () => {const p = remoteSetup(), s = session('claude')expect(await p.attach.attachSession(s, false, false, true)).toBe(true)- expect(p.remote.prepare).toHaveBeenCalledWith(s, { live: true, end: undefined }, expect.any(Function))+ expect(p.remote.prepare).toHaveBeenCalledWith(s, { live: true, end: undefined }, expect.any(Function), undefined)expect(p.deps.watcher.hold).not.toHaveBeenCalled()expect(p.normalizers.liveParsers.get(s.sessionId)).toBe(p.handle)})@@ -198,6 +198,36 @@ describe('attaching a session', () => {expect(p.remote.prepare).not.toHaveBeenCalled()})+ it('commits staged worker profile state with parser installation and never parses its raw records', async () => {+ const p = remoteSetup(), s = session('claude', '/private/transcript')+ const order: string[] = []+ const ingestFrames = vi.fn(async () => { order.push('evidence') })+ const config = vi.fn(async () => { order.push('config') })+ const commitWith = vi.fn((install: () => boolean) => { order.push('commit'); return install() })+ vi.mocked(p.deps.runtimeProfiles.beginHydrate).mockReturnValue({ ...p.profile, ingestFrames, config, commitWith })+ vi.mocked(p.remote.install).mockImplementation(() => { order.push('install'); return true })+ expect(await p.attach.attachSession(s)).toBe(true)+ expect(order).toEqual(['evidence', 'config', 'commit', 'install'])+ expect(ingestFrames).toHaveBeenCalledOnce()+ expect(p.profile.ingest).not.toHaveBeenCalled()+ expect(p.profile.commit).not.toHaveBeenCalled()+ expect(p.deps.runtimeProfiles.ingestConfig).not.toHaveBeenCalled()+ expect(p.normalizers.liveParsers.get(s.sessionId)).toBe(p.handle)+ })++ it.each(['config', 'commit'])('discards and retries a worker profile %s failure without replacing live state', async phase => {+ const p = remoteSetup(), s = session('claude', '/private/transcript'), old = { ...p.handle }+ p.normalizers.liveParsers.set(s.sessionId, old)+ vi.mocked(p.deps.runtimeProfiles.beginHydrate).mockReturnValue({ ...p.profile,+ ingestFrames: async () => {}, config: async () => { if (phase === 'config') throw new Error('worker failed') },+ commitWith: () => false })+ expect(await p.attach.attachSession(s, true)).toBe(true)+ expect(p.remote.install).not.toHaveBeenCalled()+ expect(p.remote.discard).toHaveBeenCalledWith(p.candidate)+ expect(p.remote.retry).toHaveBeenCalledWith(s)+ expect(p.normalizers.liveParsers.get(s.sessionId)).toBe(old)+ })+it('refuses a session whose pane is gone', async () => {const { attach, deps } = setup({ terminalGone: vi.fn(async () => true) })expect(await attach.attachSession(session('pi', transcript()))).toBe(false)diff --git a/cli/src/core/transcripts/attach.ts b/cli/src/core/transcripts/attach.tsindex 2bf2a2fc0..7039c8bec 100644--- a/cli/src/core/transcripts/attach.ts+++ b/cli/src/core/transcripts/attach.ts@@ -32,6 +32,7 @@ import { foldTranscript, TranscriptFold } from '../../engines/kit/transcriptFoldimport type { LiveEvent } from '../../engines/kit/events.js'import type { RegisteredSession } from '../../lib/registry.js'import type { RuntimeField, RuntimeProfileManager } from '../../lib/runtimeProfile.js'+import type { ProfileHydration } from '../engines/runtimeProfiles.js'import { tailFileCapped, WHOLE_READ_CAP_BYTES } from '../../lib/transcriptTail.js'import type { TailHold, Watcher } from '../../watcher/watcher.js'import type { SessionNormalizers } from './normalizers.js'@@ -49,7 +50,10 @@ export interface AttachDeps {cursorDiscovery: Pick<CursorTranscriptDiscovery, 'add'>/** The Wi-Fi device's service, wherever it runs (core/wifi.ts): it proves its turns by the raw transcript. */device: () => Pick<WifiFeed, 'needsTranscript' | 'observeTranscript'> | undefined- runtimeProfiles: Pick<RuntimeProfileManager, 'transcriptFields' | 'beginHydrate' | 'hydrate' | 'ingestConfig' | 'ingestPane'>+ runtimeProfiles: Pick<RuntimeProfileManager, 'transcriptFields' | 'hydrate' | 'ingestConfig'> & {+ beginHydrate(session: RegisteredSession): ProfileHydration+ ingestPane(session: RegisteredSession, text: string, silent?: boolean): boolean | Promise<boolean>+ }captureTerminal: (target: string, historyLines?: number) => Promise<string | null>emit: (sessionId: string, events: LiveEvent[], opts?: { resumed?: boolean }) => voidannounceTurnAborted: (sessionId: string, engine: string, message: string) => void@@ -196,6 +200,7 @@ export function createAttach({: nulllet fromEnd: AttachRead | null = nulllet prepared: PreparedLive | null = null+ let profileHydration: ProfileHydration | null = null// A reset keeps the normalizer it meant to replace when its read failed, or outlasted the hold on the// tail — which then let go, and delivery went back to that normalizer: it has seen every record since,// this one has not.@@ -209,17 +214,20 @@ export function createAttach({if (session.transcriptPath) handover.hold = await watcher.hold(session.sessionId, session.transcriptPath)const live = replayLive && handover.hold === nullconst profile = runtimeProfiles.beginHydrate(session)+ profileHydration = profiletry {prepared = await remote.prepare(session, { live, end: handover.hold?.offset ?? relaunchedAt }, frame => {- if (frame.profile) sideRead('runtime profile', session.sessionId, () => profile.ingest(frame.raw))+ if (frame.profile && !profile.ingestFrames) sideRead('runtime profile', session.sessionId, () => profile.ingest(frame.raw))if (frame.observe && observe) observe(frame.raw)- })+ }, profile.ingestFrames)+ if (profile.config) await profile.config()} catch {+ if (prepared) remote.discard(prepared)remote.retry(session)return handover.hold ? keepLiveNormalizer('could not reach its engine worker') : true}if (handover.hold?.expired) { remote.discard(prepared); return keepLiveNormalizer('outlasted its hold on the tail') }- profile.commit()+ if (!profile.commitWith) profile.commit()fromEnd = { next: prepared.page.cursor.offset, records: prepared.records, content: prepared.content }handover.next = fromEnd.nexthistoryTurnOpen = !live && prepared.state.handle.turnOpen@@ -262,7 +270,7 @@ export function createAttach({if (observe) for (const line of lines) observe(line)sideRead('runtime profile', session.sessionId, () => runtimeProfiles.hydrate(session, lines))}- await runtimeProfiles.ingestConfig(session, true)+ if (!profileHydration?.config) await runtimeProfiles.ingestConfig(session, true)// From here to the release in `attachSession` nothing is awaited for a held tail, so the hold cannot// expire between installing the new normalizer and handing it the tail.if (handover.hold?.expired) {@@ -272,7 +280,11 @@ export function createAttach({const fold = (ingest: (line: string) => LiveEvent[], turnOpenAfter: () => boolean): boolean =>take(foldTranscript(ingest, lines, turnOpenAfter, { live: replayLive }))if (prepared) {- if (!remote!.install(prepared)) { remote!.discard(prepared); return keepLiveNormalizer('was superseded while reading') }+ const install = () => remote!.install(prepared!)+ if (!(profileHydration?.commitWith ? profileHydration.commitWith(install) : install())) {+ remote!.discard(prepared); remote!.retry(session)+ return keepLiveNormalizer('was superseded while reading')+ }liveParsers.set(session.sessionId, prepared.state.handle)} else if (parser) {if (!fromEnd) historyTurnOpen = fold((line) => parser.ingest(line).events, () => parser.turnOpen)@@ -282,7 +294,7 @@ export function createAttach({historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)cursorNormalizers.set(session.sessionId, normalizer)const capture = await captureTerminal(session.agentId, 100)- if (capture) runtimeProfiles.ingestPane(session, capture, true)+ if (capture) await runtimeProfiles.ingestPane(session, capture, true)} else if (session.engine === 'opencode') {// OpenCode has no transcript file — poll its SQLite DB. The reader hydrates silently, then// streams new activity into the funnel (the same one the file engines use).@@ -298,7 +310,7 @@ export function createAttach({// without this a freshly opened agent showed empty chips until the five-minute reconcile came// round — which is exactly how long it looked broken for.const ocPane = await captureTerminal(session.agentId, 100)- if (ocPane) runtimeProfiles.ingestPane(session, ocPane, true)+ if (ocPane) await runtimeProfiles.ingestPane(session, ocPane, true)} else if (session.engine === 'kilo') {// Kilo is opencode's fork and keeps the same store shape, so it is polled the same way — but from// its OWN db and through its own reader, so the two can diverge without one breaking the other.@@ -326,7 +338,7 @@ export function createAttach({historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)grokNormalizers.set(session.sessionId, normalizer)const capture = await captureTerminal(session.agentId, 60)- if (capture) runtimeProfiles.ingestPane(session, capture, true)+ if (capture) await runtimeProfiles.ingestPane(session, capture, true)} else if (session.engine === 'agy') {// A JSONL tail like claude/grok. agy announces its model only in the hook payload and its pane// footer, so the pane is read once on attach to fill the chip before the first turn.@@ -334,7 +346,7 @@ export function createAttach({historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)agyNormalizers.set(session.sessionId, normalizer)const capture = await captureTerminal(session.agentId, 60)- if (capture) runtimeProfiles.ingestPane(session, capture, true)+ if (capture) await runtimeProfiles.ingestPane(session, capture, true)// agy's transcript has no end-of-turn record - only its Stop hook does - so a fold of a FINISHED// conversation still reports the last turn as open, and after a daemon restart nothing is ever// coming to close it. The pane is the one place the answer exists; ask it.@@ -390,7 +402,7 @@ export function createAttach({// Devin's model/effort exist ONLY in its pane footer, so read it now. Without this the chip stayed// on Auto until the 5-minute reconcile happened to run — the attach itself said nothing about it.const devinPane = await captureTerminal(session.agentId, 60)- if (devinPane) runtimeProfiles.ingestPane(session, devinPane, true)+ if (devinPane) await runtimeProfiles.ingestPane(session, devinPane, true)} else if (session.engine === 'commandcode') {const normalizer = new CommandCodeNormalizer('live')// Hydrate state silently; never replay history live — except a turn left open, below.diff --git a/cli/src/core/transcripts/ingest.spec.ts b/cli/src/core/transcripts/ingest.spec.tsindex bfd8f3249..d9e8757e9 100644--- a/cli/src/core/transcripts/ingest.spec.ts+++ b/cli/src/core/transcripts/ingest.spec.ts@@ -61,6 +61,11 @@ describe('ingesting a transcript line', () => {.toBeLessThan(vi.mocked(p.deps.emit).mock.invocationCallOrder[1])expect(p.deps.emit).toHaveBeenLastCalledWith('s1', frame.events, { replay: false })expect(p.normalizers.hasState('s1')).toBe(false)+ vi.mocked(p.deps.runtimeProfiles.ingest).mockClear()+ p.ingest.acceptFrame('s1', 'claude', frame, true)+ expect(p.deps.runtimeProfiles.ingest).not.toHaveBeenCalled()+ expect(p.deps.tokenUsage.changed).toHaveBeenCalledWith(p.sessions.get('s1'))+ expect(p.deps.emit).toHaveBeenLastCalledWith('s1', frame.events, { replay: true })})it('takes lines only for a registered session of the engine that wrote them', () => {diff --git a/cli/src/core/transcripts/ingest.ts b/cli/src/core/transcripts/ingest.tsindex 6fdef44f4..3bd8252b9 100644--- a/cli/src/core/transcripts/ingest.ts+++ b/cli/src/core/transcripts/ingest.ts@@ -53,7 +53,7 @@ export function createIngest({// audiences: web (send, ServerEvents) and device (mirror.ingest → curated commander_event cards)./** One transcript line through its engine's normalizer. The events, not yet emitted — the two* callers below differ only in what they know about the line's age. */- const observeLine = (evt: Pick<LineEvent, 'sessionId' | 'engine' | 'text'>): RegisteredSession | null => {+ const observeLine = (evt: Pick<LineEvent, 'sessionId' | 'engine' | 'text'>, profileAccepted = false): RegisteredSession | null => {if (!has(evt.sessionId)) return null // scope to terminal-registered sessionsconst session = bySession(evt.sessionId)if (!session || session.engine !== evt.engine) return null@@ -64,7 +64,7 @@ export function createIngest({service.observeTranscript(session.agentId, evt.sessionId, session.engine, evt.text)}})- sideRead('runtime profile', evt.sessionId, () => runtimeProfiles.ingest(session, evt.text))+ if (!profileAccepted) sideRead('runtime profile', evt.sessionId, () => runtimeProfiles.ingest(session, evt.text))return session}const ingestLine = (evt: LineEvent): ReturnType<CursorNormalizer['ingest']> | null => {@@ -165,8 +165,8 @@ export function createIngest({}})}- const acceptFrame = (sessionId: string, engine: RegisteredSession['engine'], frame: LiveFrame): void => {- if (!observeLine({ sessionId, engine, text: frame.raw })) return+ const acceptFrame = (sessionId: string, engine: RegisteredSession['engine'], frame: LiveFrame, profileAccepted = false): void => {+ if (!observeLine({ sessionId, engine, text: frame.raw }, profileAccepted)) returnif (frame.failure !== undefined) announceTurnAborted(sessionId, engine, frame.failure)emit(sessionId, frame.events, { replay: frame.replay })}diff --git a/cli/src/engines/README.md b/cli/src/engines/README.mdindex 10392a541..4b0e916b6 100644--- a/cli/src/engines/README.md+++ b/cli/src/engines/README.md@@ -17,8 +17,10 @@ that stream.**The engine interface is being migrated in small batches.** Claude Code and Codex now own theirlaunch contracts, history/last-turn readers and hook behavior behind `Engine` (`engine.ts`). `registry.ts`selects those engines; `launches.ts` and `hooks.ts` expose their respective facets without loading history-readers. Hook transport, process binding and event delivery stay with core. Claude Code and Codex history/last-turn reads run on demand in supervised workers; the other facets-still run in core. Explicit inline mode and older masters retain inline readers. See the+readers. Hook transport, process binding and event delivery stay with core. Claude Code and Codex history/last-turn reads,+live transcript parsing and runtime profile interpretation/catalogs run on demand in supervised workers;+the other facets still run in core. Explicit inline mode and older masters retain inline implementations. See+[runtime profiles](../../../docs/design/2026-10-08-engine-runtime.md) and the[reader pilot](../../../docs/design/2026-10-07-engine-readers.md) for limits and failure behavior. Theremaining facets and engines still use the shared paths below. This is an internal interface, not anexternal plugin API. When extending a migrated facet, put engine behavior in its folder and shareddiff --git a/cli/src/engines/claude/runtimeProfile.ts b/cli/src/engines/claude/runtimeProfile.tsnew file mode 100644index 000000000..6581ba923--- /dev/null+++ b/cli/src/engines/claude/runtimeProfile.ts@@ -0,0 +1,217 @@+/** Claude Code runtime metadata and model policy, extracted without changing its observations. */+import { join } from 'node:path'+import { sessionClaudeHome } from '../../lib/engineHomes.js'+import type { EngineRuntime, RuntimeContext, RuntimeModelOption, RuntimeRecord, RuntimeSession, RuntimeState } from '../facets/runtime.js'+import { addOption, currentPaneUi, encodeRuntimeProfile, flattenContent, parseVersion, readJson, record, stripAnsi, text, versionAtLeast } from '../kit/runtime.js'++const CLAUDE_EFFORTS = new Set(['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])+const BASIC_EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'] as const+const CLAUDE_ALIASES = ['default', 'opus', 'fable', 'sonnet', 'haiku'] as const+const CLAUDE_ULTRACODE_MIN_VERSION: [number, number, number] = [2, 1, 209]++function confirmsClaudeAutoEffort(content: string): boolean {+ return [+ /\b(?:set|reset)\b.{0,40}\b(?:effort level|effort)\b.{0,40}\b(?:auto|model default)\b/i,+ /\b(?:effort level|effort)\b.{0,40}\b(?:set|reset)\b.{0,40}\b(?:auto|model default)\b/i,+ /\busing\b.{0,40}\bauto\b.{0,40}\beffort\b/i,+ ].some((pattern) => pattern.test(content))+}++function normalizeClaudeDisplay(value: string): string | null {+ const cleaned = value+ .replace(/\u001b\[[0-9;]*m/g, '')+ .replace(/\s+\(default\).*$/i, '')+ .replace(/\s+and saved.*$/i, '')+ .replace(/\s+for (?:the )?current session.*$/i, '')+ .trim()+ if (!cleaned) return null+ const alias = /^(default|best|fable|opus|sonnet|haiku)(\[1m\])?$/i.exec(cleaned)+ if (alias) return `${alias[1].toLowerCase()}${alias[2]?.toLowerCase() ?? ''}`+ const family = /^(Fable|Opus|Sonnet|Haiku)\s+(\d+(?:\.\d+)*)(?:\s+\(1M context\))?/i.exec(cleaned)+ if (family) return `claude-${family[1].toLowerCase()}-${family[2].replace(/\./g, '-')}${/1M context/i.test(cleaned) ? '[1m]' : ''}`+ if (/^claude-[a-z0-9._:-]+(?:\[1m\])?$/i.test(cleaned)) return cleaned.toLowerCase()+ return null+}++function claudeAliasForModel(model: string): string | null {+ const normalized = model.toLowerCase()+ if ((CLAUDE_ALIASES as readonly string[]).includes(normalized)) return normalized+ return /^claude-(opus|fable|sonnet|haiku)(?:-|$)/.exec(normalized)?.[1] ?? null+}++function claudeEfforts(model: string, cliVersion: string | null = null): string[] {+ // `[1m]` marks the 1M-context variant, not a different model — strip it so `claude-opus-5[1m]` gets+ // the same efforts as `claude-opus-5` (otherwise a 1M model looked effort-less and a /model switch+ // reset the observed effort to `auto`). The version match is open-ended (4.7/4.8, then 5+) so a new+ // release like Opus 5 works without a code change.+ const normalized = model.toLowerCase().replace(/\[1m\]$/, '')+ let efforts: string[] = []+ if (/^claude-(?:opus|fable|sonnet)-(?:4-[78]|[5-9]|\d{2,})(?:-|$)/.test(normalized)) efforts = [...BASIC_EFFORTS]+ else if (/^claude-(?:opus|sonnet)-4-6(?:-|$)/.test(normalized)) efforts = ['low', 'medium', 'high', 'max']+ else if (/^(?:fable|opus|sonnet)$/.test(normalized)) efforts = [...BASIC_EFFORTS]+ if (efforts.length > 0 && versionAtLeast(cliVersion, CLAUDE_ULTRACODE_MIN_VERSION)) efforts.push('ultracode')+ return efforts+}++function availableModelMatches(model: string, allowed: string[]): boolean {+ if (model === 'default') return true+ if (allowed.length === 0) return true+ const lower = model.toLowerCase()+ const family = lower.replace(/\[1m\]$/, '')+ const wantsLongContext = lower.endsWith('[1m]')+ return allowed.some((item) => {+ const candidate = item.toLowerCase()+ const sameFamily = candidate.includes(`-${family}-`) || candidate.endsWith(`-${family}`)+ const contextMatches = wantsLongContext === /(?:\[1m\]|1m.context)/i.test(candidate)+ return lower === candidate || lower.startsWith(`${candidate}-`) || lower.startsWith(`${candidate}[`) || (sameFamily && contextMatches)+ })+}++function claudeSettingsFiles(session: RuntimeSession): string[] {+ const root = sessionClaudeHome(session)+ const files = [join(root, 'settings.json')]+ if (session.cwd) {+ files.push(join(session.cwd, '.claude', 'settings.json'))+ files.push(join(session.cwd, '.claude', 'settings.local.json'))+ }+ return files+}++async function claudeAvailableModels(session: RuntimeSession): Promise<string[]> {+ const merged: string[] = []+ for (const file of claudeSettingsFiles(session)) {+ const config = await readJson(file)+ const values = config?.availableModels+ if (!Array.isArray(values)) continue+ for (const value of values) if (typeof value === 'string' && !merged.includes(value)) merged.push(value)+ }+ return merged+}++async function claudeConfiguredEffort(session: RuntimeSession): Promise<string> {+ let configured: string | null = null+ for (const file of claudeSettingsFiles(session)) {+ const config = await readJson(file)+ const raw = text(config?.effortLevel) || text(config?.effort)+ const normalized = raw.toLowerCase() === 'default' ? 'auto' : raw.toLowerCase()+ if (CLAUDE_EFFORTS.has(normalized)) configured = normalized+ }+ return configured ?? 'auto'+}++function claudeStartupBanner(pane: string): { model: string; effort?: string } | null {+ const lines = pane.split('\n')+ const start = lines.findLastIndex(line => /\bClaude Code v\d+\.\d+/.test(line))+ if (start < 0) return null+ const banner = lines.slice(start, start + 4).join('\n')+ const match = /\b(Fable|Opus|Sonnet|Haiku)\s+(\d+(?:\.\d+)*)(\s+\(1M context\))?(?:\s+with\s+(low|medium|high|xhigh|max|ultracode)\s+effort)?\s*·\s*Claude\s+(?:Max|Pro|Team|Enterprise)\b/i.exec(banner)+ if (!match) return null+ return {+ model: `claude-${match[1].toLowerCase()}-${match[2].replace(/\./g, '-')}${match[3] ? '[1m]' : ''}`,+ ...(match[4] ? { effort: match[4].toLowerCase() } : {}),+ }+}++function decode(raw: Record<string, unknown>): RuntimeRecord | null {+ const cliVersion = text(raw.version)+ const message = record(raw.message)+ const assistantModel = raw.type === 'assistant' ? text(message?.model) : ''+ // Claude uses this marker for local errors such as exhausted quota.+ // It is not a model change; keep the last real observation.+ const model = assistantModel && assistantModel !== '<synthetic>' ? assistantModel : null+ const content = `${flattenContent(message?.content)}\n${flattenContent(raw.content)}`+ const modelMatch = /Set model to\s+(.+?)(?:\n|$)/i.exec(content)+ const setModel = !!modelMatch+ const nextModel = modelMatch ? normalizeClaudeDisplay(modelMatch[1]) : null+ const effortMatch = /Set effort level to\s+(low|medium|high|xhigh|max|ultracode)/i.exec(content)+ const effort = effortMatch?.[1].toLowerCase() ?? (confirmsClaudeAutoEffort(content) ? 'auto' : null)+ const version = parseVersion(cliVersion) ? cliVersion : null+ return version || model || setModel || effort ? { version, model, setModel, nextModel, effort } : null+}++function reduce({ session, state, control }: RuntimeContext, evidence: RuntimeRecord): void {+ const version = text(evidence.version)+ if (parseVersion(version)) { session.cliVersion = version; state.cliVersion = version }+ const model = text(evidence.model)+ if (model) {+ state.model = model+ state.observedAt = Date.now()+ }+ if (evidence.setModel === true) {+ const nextModel = control?.target.model ?? (text(evidence.nextModel) || state.model)+ state.model = nextModel+ if (!control && nextModel && state.effort && !claudeEfforts(nextModel, session.cliVersion).includes(state.effort)) {+ state.effort = 'auto'+ }+ state.observedAt = Date.now()+ if (control) control.modelConfirmed = true+ }+ const effort = text(evidence.effort)+ if (effort) {+ state.effort = effort+ state.observedAt = Date.now()+ if (control) control.effortConfirmed = control.target.effort === 'auto' || state.effort === control.target.effort+ }+}++function transcript(context: RuntimeContext, raw: Record<string, unknown>): void {+ const evidence = decode(raw)+ if (evidence) reduce(context, evidence)+}++function pane({ state }: RuntimeContext, paneText: string): void {+ paneText = stripAnsi(paneText)+ const currentUi = currentPaneUi(paneText)+ const banner = !state.model ? claudeStartupBanner(paneText) : null+ if (banner) {+ state.model = banner.model+ if (banner.effort) state.effort = banner.effort+ state.observedAt = Date.now()+ }+ const header = /(Fable|Opus|Sonnet|Haiku)\s+(\d+(?:\.\d+)*)(\s+\(1M context\))?\s+with\s+(low|medium|high|xhigh|max|ultracode)\s+effort/gi+ const matches = [...paneText.matchAll(header)]+ const latest = matches[matches.length - 1]+ if (latest) {+ state.model = `claude-${latest[1].toLowerCase()}-${latest[2].replace(/\./g, '-')}${latest[3] ? '[1m]' : ''}`+ state.effort = latest[4].toLowerCase()+ state.observedAt = Date.now()+ }+ const footer = paneText.split('\n').slice(-8).join('\n')+ if (/─+\s*ultracode\s*─+/i.test(footer)) {+ state.effort = 'ultracode'+ state.observedAt = Date.now()+ }+ if (/\bplan mode on\b/i.test(currentUi)) state.mode = 'plan'+ else if (/\b(?:auto|default) mode on\b/i.test(currentUi)) state.mode = 'default'+}++async function models(session: RuntimeSession, state: RuntimeState | undefined): Promise<RuntimeModelOption[]> {+ const output: RuntimeModelOption[] = []+ const seen = new Set<string>()+ const allowed = await claudeAvailableModels(session)+ for (const model of CLAUDE_ALIASES) {+ if (model === 'fable' && !versionAtLeast(session.cliVersion, [2, 1, 170])) continue+ if (!availableModelMatches(model, allowed)) continue+ addOption(output, seen, session, model, 'auto')+ for (const effort of claudeEfforts(model, session.cliVersion)) addOption(output, seen, session, model, effort)+ }+ if (state?.model) {+ const model = claudeAliasForModel(state.model) ?? state.model+ addOption(output, seen, session, model, 'auto')+ for (const effort of claudeEfforts(model, session.cliVersion)) addOption(output, seen, session, model, effort)+ if (state.effort) addOption(output, seen, session, model, state.effort)+ }+ return output+}++export const runtime: EngineRuntime = {+ decode, reduce, transcript, pane, models,+ configuredEffort: claudeConfiguredEffort,+ supportsControl: session => versionAtLeast(session.cliVersion, [2, 1, 153]),+ selectedModel(session, state) {+ if (!state.model) return null+ const model = claudeAliasForModel(state.model) ?? state.model+ const effort = state.effort ?? (claudeEfforts(model).length === 0 ? 'auto' : null)+ return effort ? encodeRuntimeProfile({ sessionId: session.agentId, engine: session.engine, model, effort }) : null+ },+}diff --git a/cli/src/engines/codex/runtimeProfile.ts b/cli/src/engines/codex/runtimeProfile.tsnew file mode 100644index 000000000..844717715--- /dev/null+++ b/cli/src/engines/codex/runtimeProfile.ts@@ -0,0 +1,124 @@+/** Codex runtime metadata and model policy. Model catalogs stay scoped to the bound engine home. */+import { readFile } from 'node:fs/promises'+import { join } from 'node:path'+import { sessionCodexHome } from '../../lib/engineHomes.js'+import { parseCodexCatalog, type CodexCatalogModel } from './modelPicker.js'+import type { EngineRuntime, RuntimeContext, RuntimeModelOption, RuntimeRecord, RuntimeSession, RuntimeState } from '../facets/runtime.js'+import { addOption, currentPaneUi, encodeRuntimeProfile, parseVersion, record, runtimeModelLabel, stripAnsi, text, versionAtLeast } from '../kit/runtime.js'++/** Persistent arrived in Codex 0.160; older transcripts and catalog fallbacks retain their existing behavior. */+const CODEX_EFFORTS = new Set(['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra', 'persistent'])+const CODEX_CONTROL_MIN_VERSION: [number, number, number] = [0, 144, 0]++interface CodexCacheModel {+ slug?: unknown+ display_name?: unknown+ visibility?: unknown+ supported_reasoning_levels?: Array<{ effort?: unknown }>+}++interface CodexCache {+ models?: CodexCacheModel[]+}++/** Max and Ultra follow the catalog; the historical slug rule is only the missing-catalog fallback. */+export function codexEffortAllowed(model: string, effort: string, listed: readonly string[] | null = null): boolean {+ if (!CODEX_EFFORTS.has(effort)) return false+ if (effort !== 'max' && effort !== 'ultra') return true+ if (listed) return listed.includes(effort)+ return /^gpt-5\.6(?:-|$)/i.test(model) || model.toLowerCase() === 'codex-auto-review'+}++function decode(raw: Record<string, unknown>): RuntimeRecord | null {+ const payload = record(raw.payload)+ const cliVersion = raw.type === 'session_meta' ? text(payload?.cli_version) : ''+ let source: Record<string, unknown> | null = null+ if (raw.type === 'event_msg' && payload?.type === 'thread_settings_applied') source = record(payload.thread_settings)+ else if (raw.type === 'turn_context') source = payload+ const version = parseVersion(cliVersion) ? cliVersion : null+ if (!source && !version) return null+ return { version, source: !!source, model: text(source?.model),+ effort: text(source?.reasoning_effort) || text(source?.effort), mode: text(record(source?.collaboration_mode)?.mode) }+}++function reduce({ session, state, control }: RuntimeContext, evidence: RuntimeRecord): void {+ const version = text(evidence.version)+ if (parseVersion(version)) { session.cliVersion = version; state.cliVersion = version }+ if (evidence.source !== true) return+ const model = text(evidence.model)+ const effort = text(evidence.effort)+ const mode = text(evidence.mode)+ if (model) state.model = model+ if (CODEX_EFFORTS.has(effort.toLowerCase())) state.effort = effort.toLowerCase()+ if (mode === 'plan' || mode === 'default') state.mode = mode+ if (model || effort || mode) state.observedAt = Date.now()+ if (control && state.model === control.target.model) {+ control.modelConfirmed = true+ if (control.target.effort === 'auto' || state.effort === control.target.effort) control.effortConfirmed = true+ }+}++function transcript(context: RuntimeContext, raw: Record<string, unknown>): void {+ const evidence = decode(raw)+ if (evidence) reduce(context, evidence)+}++function pane({ state }: RuntimeContext, paneText: string): void {+ paneText = stripAnsi(paneText)+ const currentUi = currentPaneUi(paneText)+ const matches = [...paneText.matchAll(/\b(gpt-[a-z0-9][a-z0-9._-]*)\s+(low|medium|high|xhigh|max|ultra|persistent|default)\s*[·│]/gi)]+ const latest = matches[matches.length - 1]+ if (latest) {+ state.model = latest[1].toLowerCase()+ state.effort = latest[2].toLowerCase() === 'default' ? 'auto' : latest[2].toLowerCase()+ state.observedAt = Date.now()+ }+ if (/\bplan mode\b/i.test(currentUi)) state.mode = 'plan'+ else if (/\b(?:default|work) mode\b/i.test(currentUi)) state.mode = 'default'+}++async function readCodexCache(session: RuntimeSession): Promise<CodexCache> {+ try {+ const cache: unknown = JSON.parse(await readFile(join(sessionCodexHome(session), 'models_cache.json'), 'utf8'))+ return record(cache) ?? {}+ } catch {+ return {}+ }+}++export async function codexCatalog(session: RuntimeSession): Promise<CodexCatalogModel[]> {+ return parseCodexCatalog(await readCodexCache(session))+}++async function models(session: RuntimeSession, state: RuntimeState | undefined): Promise<RuntimeModelOption[]> {+ const output: RuntimeModelOption[] = []+ const seen = new Set<string>()+ const cache = await readCodexCache(session)+ const catalog = parseCodexCatalog(cache)+ for (const item of Array.isArray(cache.models) ? cache.models : []) {+ const model = text(item.slug)+ if (!model || item.visibility === 'hide') continue+ const label = text(item.display_name) || runtimeModelLabel(model)+ addOption(output, seen, session, model, 'auto', label)+ const listed = catalog.find((entry) => entry.slug === model)?.efforts ?? []+ for (const effort of listed) {+ if (effort !== 'auto' && codexEffortAllowed(model, effort, listed)) addOption(output, seen, session, model, effort, label)+ }+ }+ if (state?.model) {+ addOption(output, seen, session, state.model, 'auto')+ const listed = catalog.find((entry) => entry.slug === state.model)?.efforts ?? null+ if (state.effort && codexEffortAllowed(state.model, state.effort, listed)) {+ addOption(output, seen, session, state.model, state.effort)+ }+ }+ return output+}++export const runtime: EngineRuntime = {+ decode, reduce, transcript, pane, models, catalog: codexCatalog, effortAllowed: codexEffortAllowed,+ supportsControl: session => versionAtLeast(session.cliVersion, CODEX_CONTROL_MIN_VERSION),+ selectedModel(session, state) {+ return state.model && state.effort ? encodeRuntimeProfile({ sessionId: session.agentId, engine: session.engine, model: state.model, effort: state.effort }) : null+ },+}diff --git a/cli/src/engines/engine.ts b/cli/src/engines/engine.tsindex c2a07510f..f8cef261c 100644--- a/cli/src/engines/engine.ts+++ b/cli/src/engines/engine.ts@@ -3,6 +3,7 @@ import type { EngineTranscript } from './facets/transcript.js'import type { EngineLaunch } from './facets/launch.js'import type { EngineHooks } from './facets/hooks.js'import type { EngineLive } from './facets/live.js'+import type { EngineRuntime } from './facets/runtime.js'/** The engine's own contracts. Claude Code and Codex migrate one small batch at a time. */export interface Engine {@@ -11,4 +12,5 @@ export interface Engine {readonly launch: EngineLaunchreadonly hooks: EngineHooksreadonly live: EngineLive+ readonly runtime: EngineRuntime}diff --git a/cli/src/engines/facets/live.ts b/cli/src/engines/facets/live.tsindex deb1e4e6f..5fbd70b10 100644--- a/cli/src/engines/facets/live.ts+++ b/cli/src/engines/facets/live.ts@@ -1,6 +1,6 @@import type { AttachRules } from '../../lib/attachTranscript.js'import type { RegisteredSession } from '../../lib/registry.js'-import type { RuntimeField } from '../../lib/runtimeProfile.js'+import type { RuntimeField } from './runtime.js'import type { LiveEvent } from '../kit/events.js'/** A value, not an engine's mutable parser state. Identity changes with both parser and turn. */diff --git a/cli/src/engines/facets/runtime.ts b/cli/src/engines/facets/runtime.tsnew file mode 100644index 000000000..139181b08--- /dev/null+++ b/cli/src/engines/facets/runtime.ts@@ -0,0 +1,65 @@+import type { AgentEngine } from '../types.js'+import type { RegisteredSession } from '../../lib/registry.js'++export interface RuntimeProfile {+ id: string+ sessionId: string+ engine: AgentEngine+ model: string+ effort: string+}++export interface RuntimeModelOption { id: string; displayName: string }++export interface RuntimeState {+ model: string | null+ effort: string | null+ mode: 'default' | 'plan' | 'unknown'+ cliVersion: string | null+ observedAt: number | null+}++export type RuntimeField = 'model' | 'effort' | 'mode'+export type RuntimeSession = Pick<RegisteredSession, 'agentId' | 'sessionId' | 'engine' | 'model'+ | 'cliVersion' | 'cwd' | 'transcriptPath' | 'codexHome'>++/** The transaction belongs to core. An engine interprets evidence against a supplied snapshot. */+export interface RuntimeControl {+ target: RuntimeProfile+ before: string | null+ modelConfirmed: boolean+ effortConfirmed: boolean+}++/** Plain values only: a worker can reduce a copy, and core can fence the result before committing. */+export interface RuntimeContext {+ session: RuntimeSession+ state: RuntimeState+ control?: RuntimeControl+}++/** Engine-private evidence. Core transports it but never interprets its keys. */+export type RuntimeRecord = Record<string, string | boolean | null>++export interface RuntimeCatalogModel {+ slug: string+ displayName: string+ listed: boolean+ defaultEffort: string+ efforts: string[]+}++export interface EngineRuntime {+ decode(record: Record<string, unknown>): RuntimeRecord | null+ reduce(context: RuntimeContext, record: RuntimeRecord): void+ transcript(context: RuntimeContext, record: Record<string, unknown>): void+ pane(context: RuntimeContext, text: string): void+ configuredEffort?(session: RuntimeSession): Promise<string>+ selectedModel(session: RuntimeSession, state: RuntimeState): string | null+ models(session: RuntimeSession, state: RuntimeState | undefined): Promise<RuntimeModelOption[]>+ supportsControl(session: RuntimeSession): boolean+ catalog?(session: RuntimeSession): Promise<RuntimeCatalogModel[]>+ effortAllowed?(model: string, effort: string, listed: readonly string[] | null): boolean+}++export type RuntimeFor = (engine: string) => EngineRuntime | undefineddiff --git a/cli/src/engines/kit/runtime.ts b/cli/src/engines/kit/runtime.tsnew file mode 100644index 000000000..84900c8ab--- /dev/null+++ b/cli/src/engines/kit/runtime.ts@@ -0,0 +1,110 @@+/** Shared runtime value and formatting mechanics; no engine registry or profile manager. */+import { readFile } from 'node:fs/promises'+import type { EngineRuntime, RuntimeField, RuntimeModelOption, RuntimeProfile, RuntimeSession, RuntimeState } from '../facets/runtime.js'++export const blankRuntimeState = (): RuntimeState => ({ model: null, effort: null, mode: 'unknown', cliVersion: null, observedAt: null })++/** Wire vocabulary only. Eligibility for a particular model belongs to its engine. */+export const RUNTIME_EFFORTS: ReadonlySet<string> = new Set([+ 'auto', 'none', 'off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra', 'persistent', 'ultracode',+])++export function record(value: unknown): Record<string, unknown> | null {+ return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null+}++export function text(value: unknown): string {+ return typeof value === 'string' ? value : ''+}++export function stripAnsi(value: string): string {+ return value.replace(/\u001b\[[0-9;:]*[A-Za-z]/g, '')+}++export function flattenContent(value: unknown): string {+ if (typeof value === 'string') return value+ if (!Array.isArray(value)) return ''+ return value.map((item) => {+ if (typeof item === 'string') return item+ const obj = record(item)+ return text(obj?.text) || text(obj?.content)+ }).filter(Boolean).join('\n')+}++export function parseVersion(value: string | null): [number, number, number] | null {+ const match = /(?:^|\D)(\d+)\.(\d+)\.(\d+)(?:\D|$)/.exec(value ?? '')+ return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null+}++export function versionAtLeast(value: string | null, wanted: [number, number, number]): boolean {+ const parsed = parseVersion(value)+ if (!parsed) return false+ for (let i = 0; i < wanted.length; i++) {+ if (parsed[i] !== wanted[i]) return parsed[i] > wanted[i]+ }+ return true+}++export function encodeRuntimeProfile(profile: Omit<RuntimeProfile, 'id'>): string {+ return `runtime-v1:${encodeURIComponent(profile.sessionId)}:${profile.engine}:${encodeURIComponent(profile.model)}@${profile.effort}`+}++export function runtimeModelLabel(model: string): string {+ const alias = /^(default|best|fable|opus|sonnet|haiku)(\[1m\])?$/i.exec(model)+ if (alias) return `${titlePart(alias[1].toLowerCase())}${alias[2] ?? ''}`+ return model.split(/[-_]/).filter(Boolean).map(titlePart).join(' ')+}++export function titlePart(value: string): string {+ if (/^gpt$/i.test(value)) return 'GPT'+ if (/^xhigh$/i.test(value)) return 'XHigh'+ return value.charAt(0).toUpperCase() + value.slice(1)+}++export function effortLabel(effort: string): string {+ return effort === 'xhigh' ? 'XHigh' : titlePart(effort)+}++export function currentPaneUi(paneText: string): string {+ const lines = paneText.split('\n')+ const promptIndex = lines.findLastIndex((line) => {+ const marker = line.search(/[›❯→]/u)+ return marker >= 0 && !/^\s*\d+\.\s/.test(line.slice(marker + 1))+ })+ return (promptIndex >= 0 ? lines.slice(promptIndex) : lines).join('\n')+}++export async function readJson(file: string): Promise<Record<string, unknown> | null> {+ try { return record(JSON.parse(await readFile(file, 'utf8'))) } catch { return null }+}++export function addOption(+ output: RuntimeModelOption[],+ seen: Set<string>,+ session: RuntimeSession,+ model: string,+ effort: string,+ modelLabel = runtimeModelLabel(model),+): void {+ // The id inside a `runtime-v1:` string is what the web/device echoes back on a pick, so it is the+ // AGENT id — the public one — not the engine session that happens to be bound right now.+ const id = encodeRuntimeProfile({ sessionId: session.agentId, engine: session.engine, model, effort })+ if (seen.has(id)) return+ seen.add(id)+ output.push({ id, displayName: `${modelLabel} / ${effortLabel(effort)}` })+}++/** Use the engine's actual reducer on an isolated value. No live session or control is mutated. */+export function transcriptFields(adapter: EngineRuntime | undefined, session: RuntimeSession, line: string): RuntimeField[] {+ if (!adapter) return []+ let raw: Record<string, unknown> | null+ try { raw = record(JSON.parse(line)) } catch { return [] }+ if (!raw) return []+ const state = blankRuntimeState()+ adapter.transcript({ session: { ...session }, state }, raw)+ const fields: RuntimeField[] = []+ if (state.model !== null) fields.push('model')+ if (state.effort !== null) fields.push('effort')+ if (state.mode !== 'unknown') fields.push('mode')+ return fields+}diff --git a/cli/src/engines/registry.ts b/cli/src/engines/registry.tsindex 7ad6906c7..6ec9b238e 100644--- a/cli/src/engines/registry.ts+++ b/cli/src/engines/registry.ts@@ -5,11 +5,13 @@ import { transcript as claudeTranscript } from './claude/transcript.js'import { transcript as codexTranscript } from './codex/transcript.js'import { live as claudeLive } from './claude/live.js'import { live as codexLive } from './codex/live.js'+import { runtime as claudeRuntime } from './claude/runtimeProfile.js'+import { runtime as codexRuntime } from './codex/runtimeProfile.js'/** Only the migrated engines. Others keep their existing handlers until their own small batch. */const engines = {- claude: { name: 'claude', launch: engineLaunches.claude, transcript: claudeTranscript, hooks: engineHooks.claude, live: claudeLive },- codex: { name: 'codex', launch: engineLaunches.codex, transcript: codexTranscript, hooks: engineHooks.codex, live: codexLive },+ claude: { name: 'claude', launch: engineLaunches.claude, transcript: claudeTranscript, hooks: engineHooks.claude, live: claudeLive, runtime: claudeRuntime },+ codex: { name: 'codex', launch: engineLaunches.codex, transcript: codexTranscript, hooks: engineHooks.codex, live: codexLive, runtime: codexRuntime },} satisfies Record<string, Engine>type MigratedEngine = keyof typeof enginesexport function engineFor(name: string | null | undefined): Engine | undefined {diff --git a/cli/src/engines/runtime.ts b/cli/src/engines/runtime.tsnew file mode 100644index 000000000..4747dcfa3--- /dev/null+++ b/cli/src/engines/runtime.ts@@ -0,0 +1,6 @@+/** Inline runtime composition. Supervised workers load only their own engine's facet. */+import { runtime as claude } from './claude/runtimeProfile.js'+import { runtime as codex } from './codex/runtimeProfile.js'+import type { RuntimeFor } from './facets/runtime.js'+const runtimes = { claude, codex }+export const runtimeFor: RuntimeFor = engine => Object.hasOwn(runtimes, engine) ? runtimes[engine as keyof typeof runtimes] : undefineddiff --git a/cli/src/engines/worker/liveProtocol.ts b/cli/src/engines/worker/liveProtocol.tsindex c33db831b..3946ab872 100644--- a/cli/src/engines/worker/liveProtocol.ts+++ b/cli/src/engines/worker/liveProtocol.ts@@ -3,6 +3,8 @@ import type { LiveEvent } from '../kit/events.js'import type { LiveTurn } from '../facets/live.js'import type { RegisteredSession } from '../../lib/registry.js'import { record, sessionEvent } from './protocol.js'+import type { RuntimeRecord } from '../facets/runtime.js'+import { runtimeRecord } from './runtimeProtocol.js'export const LIVE_VERSION = 1export const LIVE_CAPABILITIES = 'engine_live_capabilities'@@ -47,6 +49,8 @@ export interface LiveCursor {}export interface LiveFrame {raw: string+ /** Compact, engine-private profile evidence; core forwards it without interpreting vendor fields. */+ runtime?: RuntimeRecord | null/** Profile metadata can begin before the turn's parser window. */profile: booleanobserve: boolean@@ -109,6 +113,7 @@ export function livePage(value: unknown): value is LivePage {&& (value.lastStarted === null || (liveEvent(value.lastStarted) && value.lastStarted.type === 'turn_started'))&& value.frames.every(f => record(f) && typeof f.raw === 'string' && typeof f.profile === 'boolean'&& typeof f.observe === 'boolean' && typeof f.replay === 'boolean' && liveTurn(f.turn)+ && (f.runtime === undefined || f.runtime === null || runtimeRecord(f.runtime))&& (f.failure === undefined || typeof f.failure === 'string') && Array.isArray(f.events) && f.events.every(liveEvent))}diff --git a/cli/src/engines/worker/liveRequests.spec.ts b/cli/src/engines/worker/liveRequests.spec.tsindex 2d9f49511..f1f8f6934 100644--- a/cli/src/engines/worker/liveRequests.spec.ts+++ b/cli/src/engines/worker/liveRequests.spec.ts@@ -8,6 +8,8 @@ import type { LivePage, LiveSession } from './liveProtocol.js'import { LIVE_CAPABILITIES, LIVE_CLOSE, LIVE_FORGET, LIVE_PART, LIVE_PREPARE, LIVE_READ, LIVE_WAIT_MS } from './liveProtocol.js'import { engineLiveRequests, type LiveRequestDeps } from './liveRequests.js'+vi.mock('../../lib/runtimeProfile.js', () => { throw new Error('Engine workers must not load the monolithic runtime profile manager') })+const dirs: string[] = []const who = { owner: true, local: true }const prompt = (engine: string, text: string) => JSON.stringify(engine === 'claude'@@ -37,6 +39,15 @@ async function setup(engine: 'claude' | 'codex' = 'claude', lines = '', limits?:afterEach(async () => { vi.useRealTimers(); vi.restoreAllMocks(); await Promise.all(dirs.splice(0).map(dir => rm(dir, { recursive: true, force: true }))) })describe('engine live checkpoints', () => {+ it('emits compact profile evidence without loading the shared runtime manager', async () => {+ const raw = JSON.stringify({ type: 'assistant', version: '2.1.209', message: { role: 'assistant', model: 'claude-opus-5',+ content: [{ type: 'text', text: 'x'.repeat(2_000_000) }], stop_reason: 'end_turn' } }) + '\n'+ const t = await setup('claude', raw)+ const page = await t.page()+ const evidence = page.frames.find(frame => frame.runtime?.model === 'claude-opus-5')?.runtime+ expect(evidence).toMatchObject({ model: 'claude-opus-5', version: '2.1.209' })+ expect(JSON.stringify(evidence).length).toBeLessThan(200)+ })it.each(['claude', 'codex'] as const)('%s preserves thinking identities and cross-turn state across a restart', async engine => {const thinking = (text: string) => JSON.stringify(engine === 'claude'? { type: 'assistant', message: { role: 'assistant', content: [{ type: 'thinking', thinking: text }] } }diff --git a/cli/src/engines/worker/liveRequests.ts b/cli/src/engines/worker/liveRequests.tsindex db694ab04..451b765fb 100644--- a/cli/src/engines/worker/liveRequests.ts+++ b/cli/src/engines/worker/liveRequests.ts@@ -1,9 +1,9 @@import { createHash, randomUUID } from 'node:crypto'import { isAbsolute } from 'node:path'import type { ServiceRequests } from '../../core/api.js'-import type { RegisteredSession } from '../../lib/registry.js'-import type { RuntimeField } from '../../lib/runtimeProfile.js'+import type { RuntimeField } from '../facets/runtime.js'import type { EngineLive } from '../facets/live.js'+import { transcriptFields } from '../kit/runtime.js'import { record, READER_REPLY_BYTES, type ReaderEngine } from './protocol.js'import { LiveStreams } from './liveStreams.js'import {@@ -16,6 +16,10 @@ const loadLive = {claude: async () => (await import('../claude/live.js')).live,codex: async () => (await import('../codex/live.js')).live,}+const loadRuntime = {+ claude: async () => (await import('../claude/runtimeProfile.js')).runtime,+ codex: async () => (await import('../codex/runtimeProfile.js')).runtime,+}const path = (value: unknown): value is string => typeof value === 'string' && value.length <= 32_768&& !value.includes('\0') && isAbsolute(value)const label = (value: unknown): value is string => typeof value === 'string' && value.length > 0 && value.length <= 200@@ -72,11 +76,13 @@ export function engineLiveRequests(engine: ReaderEngine, deps: LiveRequestDeps =let streams: Promise<LiveStreams> | null = nullconst get = (): Promise<LiveStreams> => streams ??= (async () => {const adapter = await (deps.load ?? loadLive[engine])()- // The runtime-profile facet is the next boundary: reuse its exact field probe during this- // migration rather than introducing a second, disagreeing interpretation of model metadata.- const profiles = deps.fields ? null : new (await import('../../lib/runtimeProfile.js')).RuntimeProfileManager()- const fields = deps.fields ?? ((session: LiveSession, raw: string) => profiles!.transcriptFields(session as RegisteredSession, raw))- return new LiveStreams(adapter, fields)+ const runtime = deps.fields ? undefined : await loadRuntime[engine]()+ const fields = deps.fields ?? ((session: LiveSession, raw: string) => transcriptFields(runtime, session, raw))+ return new LiveStreams(adapter, fields, runtime ? (line) => {+ let value: unknown+ try { value = JSON.parse(line) } catch { return null }+ return record(value) ? runtime.decode(value) : null+ } : undefined)})().catch((error) => { streams = null; throw error })const forget = async (token: string): Promise<void> => {const old = replies.get(token)diff --git a/cli/src/engines/worker/liveStreams.ts b/cli/src/engines/worker/liveStreams.tsindex f57521a8f..f664832ce 100644--- a/cli/src/engines/worker/liveStreams.ts+++ b/cli/src/engines/worker/liveStreams.ts@@ -3,7 +3,7 @@ import { stat } from 'node:fs/promises'import type { EngineLive, LiveParser, LiveTurn } from '../facets/live.js'import type { LiveEvent } from '../kit/events.js'import { isWholeRecord, locateAttachSpan, type AttachSpan } from '../../lib/attachTranscript.js'-import type { RuntimeField } from '../../lib/runtimeProfile.js'+import type { RuntimeField, RuntimeRecord } from '../facets/runtime.js'import { streamRecords } from '../../lib/transcriptTail.js'import { sameStamp, stampAt } from './liveFiles.js'import { LIVE_HISTORY_BYTES, LIVE_PAGE_BYTES, type LiveCursor, type LiveFrame, type LivePage, type LiveSession, type LivePull } from './liveProtocol.js'@@ -27,7 +27,12 @@ function changed(): never { throw new Error('ENGINE_TRANSCRIPT_CHANGED') }export class LiveStreams {private readonly streams = new Map<string, Stream>()- constructor(private readonly adapter: EngineLive, private readonly fields: (session: LiveSession, raw: string) => readonly RuntimeField[]) {}+ constructor(private readonly adapter: EngineLive, private readonly fields: (session: LiveSession, raw: string) => readonly RuntimeField[],+ private readonly runtime?: (raw: string) => RuntimeRecord | null) {}++ private frame(frame: LiveFrame): LiveFrame {+ return this.runtime ? { ...frame, runtime: this.runtime(frame.raw) } : frame+ }forget(token: string): void { this.streams.delete(token) }@@ -129,7 +134,7 @@ export class LiveStreams {let records = 0if (preparing && stream.head && stream.span.head !== null) {const raw = stream.span.head- frames.push({ raw, profile: true, observe: false, events: [], replay: false, turn: { ...stream.turn } })+ frames.push(this.frame({ raw, profile: true, observe: false, events: [], replay: false, turn: { ...stream.turn } }))bytes += Buffer.byteLength(raw)}stream.head = false@@ -139,11 +144,12 @@ export class LiveStreams {const result = fold ? this.ingest(stream, ask.token, raw, offset) : { events: [] }if (fold) records++const events = preparing && !ask.replay ? [] : result.events- frames.push({ raw, profile: true, observe: fold, events, replay: offset < (ask.cursor?.historyUntil ?? 0), turn: { ...stream.turn },+ const frame = this.frame({ raw, profile: true, observe: fold, events, replay: offset < (ask.cursor?.historyUntil ?? 0), turn: { ...stream.turn },...(!preparing && result.failure !== undefined ? { failure: result.failure } : {}) })+ frames.push(frame)// Account for normalized output as well as raw input. A large record occupies its own page;// the reply transport fragments it and enforces the independent hard result bound.- bytes += Buffer.byteLength(raw) + Buffer.byteLength(JSON.stringify(events))+ bytes += Buffer.byteLength(raw) + Buffer.byteLength(JSON.stringify(events)) + Buffer.byteLength(JSON.stringify(frame.runtime ?? null))return stopped = bytes >= LIVE_PAGE_BYTES}, preparing || ask.cursor?.completeUntil != null ? isWholeRecord : () => false) : { next: start, partial: false, records: 0 }if (!read) changed()diff --git a/cli/src/engines/worker/process.ts b/cli/src/engines/worker/process.tsindex d63332115..c0ba46326 100644--- a/cli/src/engines/worker/process.ts+++ b/cli/src/engines/worker/process.ts@@ -6,6 +6,7 @@ import { runServiceProcess, type ServiceProcess } from '../../services/process.jimport type { ServiceProcessOptions } from '../../serviceProcess.js'import type { EngineTranscript, HistoryAsk, TranscriptSession } from '../facets/transcript.js'import { engineLiveRequests } from './liveRequests.js'+import { engineRuntimeRequests } from './runtimeRequests.js'import {EngineReadError, record, READER_HISTORY, READER_IN_FLIGHT, READER_LAST_TURN, READER_REPLY_BYTES,READER_SERVICES, READER_VERSION, READER_WAIT_MS, type ReaderEngine, type ReaderErrorCode,@@ -85,6 +86,6 @@ export interface EngineProcessOptions extends ServiceProcessOptions {export function runEngineReader(engine: ReaderEngine, options: EngineProcessOptions): ServiceProcess {return (options.run ?? runServiceProcess)({name: READER_SERVICES[engine], socketPath: options.socketPath, machineId: options.machineId,- token: options.token, requests: options.requests ?? { ...engineReaderRequests(engine), ...engineLiveRequests(engine) },+ token: options.token, requests: options.requests ?? { ...engineReaderRequests(engine), ...engineLiveRequests(engine), ...engineRuntimeRequests(engine) },})}diff --git a/cli/src/engines/worker/runtimeProtocol.ts b/cli/src/engines/worker/runtimeProtocol.tsnew file mode 100644index 000000000..148202e2f--- /dev/null+++ b/cli/src/engines/worker/runtimeProtocol.ts@@ -0,0 +1,113 @@+/** Private runtime-profile reads and reductions. No registry or terminal capabilities cross this link. */+import { isAbsolute } from 'node:path'+import type { RuntimeCatalogModel, RuntimeContext, RuntimeControl, RuntimeModelOption, RuntimeRecord, RuntimeSession, RuntimeState } from '../facets/runtime.js'+import { encodeRuntimeProfile } from '../kit/runtime.js'+import { record, type ReaderEngine } from './protocol.js'++export const RUNTIME_VERSION = 1+export const RUNTIME_READ = 'engine_runtime_read'+export const RUNTIME_CAPABILITIES = 'engine_runtime_capabilities'+export const RUNTIME_WAIT_MS = 5_000+export const RUNTIME_IN_FLIGHT = 2+export const RUNTIME_REQUEST_BYTES = 1024 * 1024+export const RUNTIME_REPLY_BYTES = 1024 * 1024+export const RUNTIME_RECORDS = 512++export type RuntimeOperation =+ | { kind: 'records'; records: RuntimeRecord[] }+ | { kind: 'pane'; text: string }+ | { kind: 'config' | 'models' | 'catalog' | 'describe' }+ | { kind: 'effort'; model: string; effort: string; listed: string[] | null }++export interface RuntimeAnswer {+ state: RuntimeState+ cliVersion: string | null+ control: RuntimeControl | null+ selectedModel: string | null+ supportsControl: boolean+ models?: RuntimeModelOption[]+ catalog?: RuntimeCatalogModel[]+ effortAllowed?: boolean+}++const text = (value: unknown, max = 2_000): value is string => typeof value === 'string' && value.length <= max+const nullable = (value: unknown): value is string | null => value === null || text(value)+const label = (value: unknown): value is string => text(value, 200) && value.length > 0+const path = (value: unknown): value is string => text(value, 32_768) && !value.includes('\0') && isAbsolute(value)+const fields = (value: Record<string, unknown>, allowed: readonly string[]): boolean => Object.keys(value).every(key => allowed.includes(key))++export function runtimeState(value: unknown): value is RuntimeState {+ return record(value) && nullable(value.model) && nullable(value.effort) && nullable(value.cliVersion)+ && ['unknown', 'default', 'plan'].includes(value.mode as string)+ && (value.observedAt === null || (typeof value.observedAt === 'number' && Number.isFinite(value.observedAt) && Math.abs(value.observedAt) <= 8.64e15))+}++function controlOf(value: unknown, session: RuntimeSession): RuntimeControl | undefined | null {+ if (value === undefined || value === null) return undefined+ if (!session.sessionId || !record(value) || !record(value.target) || typeof value.modelConfirmed !== 'boolean' || typeof value.effortConfirmed !== 'boolean'+ || (value.before !== null && !text(value.before, 32_768))) return null+ const target = value.target+ // Older clients encoded the conversation id; core's controller still accepts that bound alias.+ if ((target.sessionId !== session.agentId && target.sessionId !== session.sessionId) || target.engine !== session.engine || !text(target.model) || !target.model || !label(target.effort)+ || target.id !== encodeRuntimeProfile({ sessionId: target.sessionId, engine: session.engine, model: target.model, effort: target.effort })) return null+ return { target: { id: target.id, sessionId: target.sessionId, engine: session.engine, model: target.model, effort: target.effort },+ before: value.before, modelConfirmed: value.modelConfirmed, effortConfirmed: value.effortConfirmed }+}++/** Copy only the facts an engine needs. Workers cannot mutate core's caller-owned snapshot. */+export function runtimeContext(value: unknown, engine: ReaderEngine): RuntimeContext | null {+ if (!record(value) || !record(value.session) || !runtimeState(value.state)) return null+ const s = value.session+ // Catalogs can be requested before a conversation binds. Core never caches conversation state at ''.+ if (s.engine !== engine || !label(s.agentId) || !text(s.sessionId, 200) || !nullable(s.model) || !nullable(s.cliVersion)+ || (s.transcriptPath !== null && !path(s.transcriptPath)) || (s.cwd !== null && !path(s.cwd))+ || (s.codexHome != null && !path(s.codexHome))) return null+ const session: RuntimeSession = { agentId: s.agentId, sessionId: s.sessionId, engine, model: s.model, cliVersion: s.cliVersion,+ cwd: s.cwd, transcriptPath: s.transcriptPath, ...(s.codexHome === undefined ? {} : { codexHome: s.codexHome }) }+ const control = controlOf(value.control, session)+ if (control === null) return null+ const { model, effort, mode, cliVersion, observedAt } = value.state+ return { session, state: { model, effort, mode, cliVersion, observedAt }, ...(control ? { control } : {}) }+}++export function runtimeRecord(value: unknown): value is RuntimeRecord {+ return record(value) && Object.keys(value).length <= 16+ && Object.entries(value).every(([key, v]) => label(key) && (v === null || typeof v === 'boolean' || text(v, 32_768)))+}++export function runtimeOperation(value: unknown): RuntimeOperation | null {+ if (!record(value)) return null+ if (value.kind === 'records' && fields(value, ['kind', 'records']) && Array.isArray(value.records)+ && value.records.length <= RUNTIME_RECORDS && value.records.every(runtimeRecord)) {+ return { kind: value.kind, records: value.records.map(r => ({ ...r })) }+ }+ if (value.kind === 'pane' && fields(value, ['kind', 'text']) && text(value.text, 256 * 1024)) return { kind: value.kind, text: value.text }+ if (['config', 'models', 'catalog', 'describe'].includes(value.kind as string) && fields(value, ['kind'])) return { kind: value.kind as 'config' | 'models' | 'catalog' | 'describe' }+ if (value.kind === 'effort' && fields(value, ['kind', 'model', 'effort', 'listed']) && label(value.model) && label(value.effort)+ && (value.listed === null || (Array.isArray(value.listed) && value.listed.length <= 64 && value.listed.every(label)))) {+ return { kind: value.kind, model: value.model, effort: value.effort, listed: value.listed === null ? null : [...value.listed] }+ }+ return null+}++export function runtimeAnswer(value: unknown, context: RuntimeContext, operation: RuntimeOperation): value is RuntimeAnswer {+ const prefix = `runtime-v1:${encodeURIComponent(context.session.agentId)}:${context.session.engine}:`+ const profile = (id: unknown): boolean => {+ if (!text(id, 32_768) || !id.startsWith(prefix)) return false+ const split = id.lastIndexOf('@')+ if (split <= prefix.length || !/^[a-z0-9_-]+$/.test(id.slice(split + 1))) return false+ try {+ const model = decodeURIComponent(id.slice(prefix.length, split))+ return !!model && id === encodeRuntimeProfile({ sessionId: context.session.agentId, engine: context.session.engine, model, effort: id.slice(split + 1) })+ } catch { return false }+ }+ if (!record(value) || !runtimeState(value.state) || !nullable(value.cliVersion) || typeof value.supportsControl !== 'boolean'+ || (value.selectedModel !== null && !profile(value.selectedModel)) || (value.control !== null && !record(value.control))) return false+ const control = controlOf(value.control, context.session)+ if (control === null || !!control !== !!context.control+ || (control && (control.target.id !== context.control!.target.id || control.before !== context.control!.before))) return false+ if (operation.kind === 'models') return Array.isArray(value.models) && value.models.every(m => record(m) && profile(m.id) && text(m.displayName, 32_768))+ if (operation.kind === 'catalog') return Array.isArray(value.catalog) && value.catalog.every(m => record(m) && label(m.slug)+ && text(m.displayName) && typeof m.listed === 'boolean' && text(m.defaultEffort) && Array.isArray(m.efforts) && m.efforts.every(label))+ return operation.kind !== 'effort' || typeof value.effortAllowed === 'boolean'+}diff --git a/cli/src/engines/worker/runtimeRequests.spec.ts b/cli/src/engines/worker/runtimeRequests.spec.tsnew file mode 100644index 000000000..9edf0b2f5--- /dev/null+++ b/cli/src/engines/worker/runtimeRequests.spec.ts@@ -0,0 +1,183 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { EngineRuntime, RuntimeContext } from '../facets/runtime.js'+import { runtimeFor } from '../runtime.js'+import { blankRuntimeState, encodeRuntimeProfile, transcriptFields } from '../kit/runtime.js'+import { engineRuntimeRequests } from './runtimeRequests.js'+import { RUNTIME_CAPABILITIES, RUNTIME_IN_FLIGHT, RUNTIME_READ, RUNTIME_REPLY_BYTES, RUNTIME_WAIT_MS,+ runtimeAnswer, runtimeContext, runtimeOperation, type RuntimeOperation } from './runtimeProtocol.js'++const who = { owner: true, local: true }+const context = (engine: 'claude' | 'codex' = 'claude'): RuntimeContext => ({+ session: { agentId: 'agent', sessionId: 'session', engine, model: null, cliVersion: '2.1.209', cwd: null, transcriptPath: null, codexHome: null },+ state: blankRuntimeState(),+})+const failure = (error: string, retryable = true) => ({ version: 1, error, retryable })+const deferred = <T>() => { let resolve!: (value: T) => void; const promise = new Promise<T>(r => { resolve = r }); return { promise, resolve } }+const target = (ctx: RuntimeContext, model = 'opus', effort = 'high') => {+ const data = { sessionId: ctx.session.agentId, engine: ctx.session.engine, model, effort }+ return { id: encodeRuntimeProfile(data), ...data }+}+function setup() {+ const adapter = { ...runtimeFor('claude')!, configuredEffort: vi.fn(async () => 'high'), models: vi.fn(async () => []),+ catalog: vi.fn(async () => []), effortAllowed: vi.fn(() => true) }+ const load = vi.fn(async () => adapter), recycle = vi.fn()+ const requests = engineRuntimeRequests('claude', { load, recycle })+ const payload = { version: 1, context: context(), operation: { kind: 'describe' } }+ const send = async (overrides: Record<string, unknown> = {}, asker = who, signal?: AbortSignal): Promise<Record<string, any>> =>+ await requests[RUNTIME_READ]({ ...payload, ...overrides }, asker, signal) as Record<string, any>+ return { adapter, load, recycle, requests, payload, send }+}++afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks() })++describe('runtime worker contract', () => {+ it('serves a catalog for an unbound agent but refuses conversation controls without a binding', async () => {+ const t = setup(), ctx = context(); ctx.session.sessionId = ''+ expect((await t.send({ context: ctx, operation: { kind: 'models' } })).answer.models).toEqual([])+ ctx.control = { target: target(ctx), before: null, modelConfirmed: false, effortConfirmed: false }+ expect(await t.send({ context: ctx })).toEqual(failure('ENGINE_INVALID_REQUEST', false))+ })++ it('reduces a supplied snapshot and survives a fresh worker without mutating the caller', async () => {+ for (const engine of ['claude', 'codex'] as const) {+ const ctx = context(engine), adapter = runtimeFor(engine)!+ const raw = engine === 'claude'+ ? { type: 'assistant', version: '2.1.209', message: { model: 'claude-opus-5', content: 'Set effort level to high' } }+ : { type: 'turn_context', payload: { model: 'gpt-6-astra', effort: 'persistent', collaboration_mode: { mode: 'plan' } } }+ const operation: RuntimeOperation = { kind: 'records', records: [adapter.decode(raw)!] }+ const before = structuredClone(ctx)+ const worker = engineRuntimeRequests(engine)+ const first = await worker[RUNTIME_READ]({ version: 1, context: ctx, operation }, who) as any+ expect(first.answer.state.model).toBe(engine === 'claude' ? 'claude-opus-5' : 'gpt-6-astra')+ expect(first.answer.state.effort).toBe(engine === 'claude' ? 'high' : 'persistent')+ expect(runtimeAnswer(first.answer, ctx, operation)).toBe(true)+ expect(ctx).toEqual(before)+ const resumed = { ...ctx, state: first.answer.state, session: { ...ctx.session, cliVersion: first.answer.cliVersion } }+ const fresh = engineRuntimeRequests(engine)+ expect(await fresh[RUNTIME_READ]({ version: 1, context: resumed, operation: { kind: 'describe' } }, who)).toEqual(first)+ }+ })++ it('keeps compact engine evidence and metadata probes independent of live controls', () => {+ const ctx = context(), adapter = runtimeFor('claude')!+ ctx.control = { target: target(ctx), before: null, modelConfirmed: false, effortConfirmed: false }+ const raw = { type: 'assistant', version: '2.1.209', message: { model: 'claude-opus-5', content: 'x'.repeat(2_000_000) } }+ expect(JSON.stringify(adapter.decode(raw)).length).toBeLessThan(200)+ expect(transcriptFields(adapter, ctx.session, JSON.stringify(raw))).toEqual(['model'])+ expect(ctx.state.model).toBeNull()+ expect(ctx.control.modelConfirmed).toBe(false)+ const unknown = adapter.decode({ content: 'Set model to ' + 'x'.repeat(2_000_000) })!+ expect(JSON.stringify(unknown).length).toBeLessThan(200)+ adapter.reduce(ctx, unknown)+ expect(ctx.state.model).toBe('opus')+ expect(ctx.control.modelConfirmed).toBe(true)+ expect(adapter.decode({ type: 'assistant', message: { model: '<synthetic>', content: 'Quota exceeded' } })).toBeNull()+ expect(transcriptFields(undefined, ctx.session, '{}')).toEqual([])+ expect(transcriptFields(adapter, ctx.session, 'bad')).toEqual([])+ expect(transcriptFields(adapter, ctx.session, '[]')).toEqual([])+ })++ it('negotiates without loading, reads only in workers, and returns only supplied transaction evidence', async () => {+ const t = setup(), ctx = context()+ ctx.control = { target: target(ctx), before: null, modelConfirmed: false, effortConfirmed: false }+ expect(await t.requests[RUNTIME_CAPABILITIES]({ version: 1 }, who)).toEqual({ version: 1, runtime: 1, engine: 'claude' })+ expect(t.load).not.toHaveBeenCalled()+ const data = t.adapter.decode({ content: 'Set model to Opus\nSet effort level to high' })!+ const reply = await t.send({ context: ctx, operation: { kind: 'records', records: [data] } })+ expect(reply.answer.control).toMatchObject({ modelConfirmed: true, effortConfirmed: true })+ expect(ctx.control.modelConfirmed).toBe(false)+ const legacyTarget = { ...ctx.control.target, sessionId: ctx.session.sessionId }+ legacyTarget.id = encodeRuntimeProfile(legacyTarget)+ const legacy = { ...ctx, control: { ...ctx.control, target: legacyTarget } }+ const legacyReply = await t.send({ context: legacy, operation: { kind: 'records', records: [data] } })+ expect(legacyReply.answer.control.target).toEqual(legacyTarget)+ expect(runtimeAnswer(legacyReply.answer, legacy, { kind: 'records', records: [data] })).toBe(true)+ expect((await t.send({ operation: { kind: 'config' } })).answer.state.effort).toBe('high')+ expect((await t.send({ operation: { kind: 'pane', text: 'Opus 5 with high effort' } })).answer.state.model).toBe('claude-opus-5')+ expect((await t.send({ operation: { kind: 'models' } })).answer.models).toEqual([])+ expect((await t.send({ operation: { kind: 'catalog' } })).answer.catalog).toEqual([])+ expect((await t.send({ operation: { kind: 'effort', model: 'opus', effort: 'high', listed: ['high'] } })).answer.effortAllowed).toBe(true)+ expect(t.load).toHaveBeenCalledOnce()+ delete (t.adapter as Partial<EngineRuntime>).configuredEffort+ delete (t.adapter as Partial<EngineRuntime>).catalog+ delete (t.adapter as Partial<EngineRuntime>).effortAllowed+ expect((await t.send({ operation: { kind: 'config' } })).answer.state.effort).toBeNull()+ expect((await t.send({ operation: { kind: 'catalog' } })).answer.catalog).toEqual([])+ expect((await t.send({ operation: { kind: 'effort', model: 'opus', effort: 'high', listed: null } })).answer.effortAllowed).toBe(false)+ })++ it('refuses public callers and malformed snapshots before loading any engine', async () => {+ const t = setup()+ for (const asker of [{ owner: false, local: true }, { owner: true, local: false }, { ...who, connection: 'client' }]) {+ expect(await t.send({}, asker)).toEqual(failure('ENGINE_INVALID_REQUEST', false))+ }+ expect(await t.send({ version: 2 })).toEqual(failure('ENGINE_INVALID_REQUEST', false))+ const ctx = context()+ for (const bad of [undefined, [], {}, { ...ctx, session: { ...ctx.session, engine: 'codex' } },+ { ...ctx, session: { ...ctx.session, cwd: 'relative' } }, { ...ctx, state: { ...ctx.state, observedAt: Infinity } },+ { ...ctx, control: { target: target(ctx), before: null, modelConfirmed: true } },+ { ...ctx, control: { target: { ...target(ctx), sessionId: 'other' }, before: null, modelConfirmed: false, effortConfirmed: false } }]) {+ expect(await t.send({ context: bad })).toEqual(failure('ENGINE_INVALID_REQUEST', false))+ }+ for (const operation of [undefined, [], {}, { kind: 'unknown' }, { kind: 'describe', extra: true }, { kind: 'pane', text: 'x'.repeat(256 * 1024 + 1) },+ { kind: 'records', records: Array(513).fill({}) }, { kind: 'records', records: [{ nested: {} }] }, { kind: 'effort', model: 'opus', effort: 'high', listed: [1] }]) {+ expect(await t.send({ operation })).toEqual(failure('ENGINE_INVALID_REQUEST', false))+ }+ expect(await t.send({ surplus: 'x'.repeat(1024 * 1024) })).toEqual(failure('ENGINE_INVALID_REQUEST', false))+ expect(t.load).not.toHaveBeenCalled()+ const copied = runtimeContext({ ...ctx, session: { ...ctx.session, processIdentity: { pid: 1 } }, control: null }, 'claude')!+ expect(copied.session).not.toHaveProperty('processIdentity')+ expect(copied.state).not.toBe(ctx.state)+ })++ it('bounds concurrent work and drops results after a connection closes', async () => {+ const t = setup(), work = deferred<EngineRuntime>()+ t.load.mockImplementation(() => work.promise as Promise<typeof t.adapter>)+ const gone = new AbortController(); gone.abort()+ expect(await t.send({}, who, gone.signal)).toEqual(failure('ENGINE_UNAVAILABLE'))+ const closed = new AbortController()+ const tasks = Array.from({ length: RUNTIME_IN_FLIGHT }, () => t.send({}, who, closed.signal))+ expect(await t.send()).toEqual(failure('ENGINE_BUSY'))+ closed.abort(); work.resolve(t.adapter)+ for (const reply of await Promise.all(tasks)) expect(reply).toEqual(failure('ENGINE_UNAVAILABLE'))+ expect((await t.send()).answer).toBeDefined()+ })++ it('retries failed loads, bounds replies, and recycles an asynchronous operation past its deadline', async () => {+ vi.useFakeTimers()+ const t = setup()+ t.load.mockRejectedValueOnce(new Error('load failed'))+ expect(await t.send()).toEqual(failure('ENGINE_UNAVAILABLE'))+ expect((await t.send()).answer).toBeDefined()+ expect(t.load).toHaveBeenCalledTimes(2)+ t.adapter.models.mockResolvedValue([{ id: 'large', displayName: 'x'.repeat(RUNTIME_REPLY_BYTES) }] as never[])+ expect(await t.send({ operation: { kind: 'models' } })).toEqual(failure('ENGINE_REPLY_TOO_LARGE', false))+ const work = deferred<string>()+ t.adapter.configuredEffort.mockImplementation(() => work.promise)+ const slow = t.send({ operation: { kind: 'config' } })+ await vi.advanceTimersByTimeAsync(RUNTIME_WAIT_MS)+ expect(await slow).toEqual(failure('ENGINE_UNAVAILABLE'))+ expect(t.recycle).toHaveBeenCalledOnce()+ work.resolve('high')+ })++ it('validates results against the same agent and control transaction', async () => {+ const t = setup(), ctx = context()+ ctx.control = { target: target(ctx), before: null, modelConfirmed: false, effortConfirmed: false }+ const operation: RuntimeOperation = { kind: 'describe' }+ const good = (await t.send({ context: ctx })).answer+ expect(runtimeAnswer(good, ctx, operation)).toBe(true)+ for (const bad of [null, {}, { ...good, control: null }, { ...good, control: undefined }, { ...good, supportsControl: 1 },+ { ...good, selectedModel: 'runtime-v1:other:claude:opus@high' },+ ...['runtime-v1:agent:claude:opus', 'runtime-v1:agent:claude:%ZZ@high', 'runtime-v1:agent:claude:opus@HIGH', 'runtime-v1:agent:claude:@high']+ .map(selectedModel => ({ ...good, selectedModel })),+ { ...good, control: { ...good.control, before: 'another' } },+ { ...good, control: { ...good.control, target: target(ctx, 'sonnet') } }]) expect(runtimeAnswer(bad, ctx, operation)).toBe(false)+ expect(runtimeAnswer({ ...good, models: [{ id: target(ctx).id, displayName: 'Opus' }] }, ctx, { kind: 'models' })).toBe(true)+ expect(runtimeAnswer({ ...good, models: [{ id: 'another', displayName: 'Opus' }] }, ctx, { kind: 'models' })).toBe(false)+ expect(runtimeAnswer({ ...good, catalog: [{ slug: 'model', displayName: 'Model', listed: true, defaultEffort: 'high', efforts: ['high'] }] }, ctx, { kind: 'catalog' })).toBe(true)+ expect(runtimeAnswer({ ...good, catalog: [{}] }, ctx, { kind: 'catalog' })).toBe(false)+ expect(runtimeAnswer({ ...good, effortAllowed: true }, ctx, { kind: 'effort', model: 'opus', effort: 'high', listed: null })).toBe(true)+ expect(runtimeOperation({ kind: 'effort', model: 'opus', effort: 'high', listed: null })).not.toBeNull()+ })+})diff --git a/cli/src/engines/worker/runtimeRequests.ts b/cli/src/engines/worker/runtimeRequests.tsnew file mode 100644index 000000000..8411d1f3f--- /dev/null+++ b/cli/src/engines/worker/runtimeRequests.ts@@ -0,0 +1,59 @@+import type { ServiceRequests } from '../../core/api.js'+import type { EngineRuntime } from '../facets/runtime.js'+import { type ReaderEngine } from './protocol.js'+import { runtimeContext, runtimeOperation, RUNTIME_CAPABILITIES, RUNTIME_IN_FLIGHT, RUNTIME_READ,+ RUNTIME_REPLY_BYTES, RUNTIME_REQUEST_BYTES, RUNTIME_VERSION, RUNTIME_WAIT_MS, type RuntimeAnswer } from './runtimeProtocol.js'++const loadRuntime = {+ claude: async () => (await import('../claude/runtimeProfile.js')).runtime,+ codex: async () => (await import('../codex/runtimeProfile.js')).runtime,+}++export interface RuntimeRequestDeps {+ load?: () => Promise<EngineRuntime>+ recycle?: () => void+}++/** Each operation starts from a supplied value, so reconnecting never loses an acknowledged profile. */+export function engineRuntimeRequests(engine: ReaderEngine, deps: RuntimeRequestDeps = {}): ServiceRequests {+ let loaded: Promise<EngineRuntime> | null = null+ let pending = 0+ const failure = (error: string) => ({ version: RUNTIME_VERSION, error,+ retryable: error !== 'ENGINE_INVALID_REQUEST' && error !== 'ENGINE_REPLY_TOO_LARGE' })+ const handler = (type: string): ServiceRequests[string] => async (payload, asker, closed) => {+ if (!asker.owner || !asker.local || asker.connection !== undefined || payload.version !== RUNTIME_VERSION) return failure('ENGINE_INVALID_REQUEST')+ if (closed?.aborted) return failure('ENGINE_UNAVAILABLE')+ if (type === RUNTIME_CAPABILITIES) return { version: RUNTIME_VERSION, runtime: RUNTIME_VERSION, engine }+ const context = runtimeContext(payload.context, engine)+ const operation = runtimeOperation(payload.operation)+ if (!context || !operation || Buffer.byteLength(JSON.stringify(payload)) > RUNTIME_REQUEST_BYTES) return failure('ENGINE_INVALID_REQUEST')+ if (pending >= RUNTIME_IN_FLIGHT) return failure('ENGINE_BUSY')+ pending+++ let timer: ReturnType<typeof setTimeout> | undefined+ const deadline = new Promise<Record<string, unknown>>(resolve => {+ timer = setTimeout(() => { resolve(failure('ENGINE_UNAVAILABLE')); (deps.recycle ?? (() => process.exit(1)))() }, RUNTIME_WAIT_MS)+ })+ try {+ return await Promise.race([deadline, (async () => {+ const adapter = await (loaded ??= (deps.load ?? loadRuntime[engine])().catch(error => { loaded = null; throw error }))+ const { session, state, control } = context+ const extra: Partial<RuntimeAnswer> = {}+ if (operation.kind === 'records') for (const evidence of operation.records) adapter.reduce(context, evidence)+ else if (operation.kind === 'pane') adapter.pane(context, operation.text)+ else if (operation.kind === 'config' && adapter.configuredEffort) {+ state.effort = await adapter.configuredEffort(session)+ state.observedAt = Date.now()+ } else if (operation.kind === 'models') extra.models = await adapter.models(session, state)+ else if (operation.kind === 'catalog') extra.catalog = await adapter.catalog?.(session) ?? []+ else if (operation.kind === 'effort') extra.effortAllowed = adapter.effortAllowed?.(operation.model, operation.effort, operation.listed) ?? false+ if (closed?.aborted) return failure('ENGINE_UNAVAILABLE')+ const answer: RuntimeAnswer = { state, cliVersion: session.cliVersion, control: control ?? null,+ selectedModel: adapter.selectedModel(session, state), supportsControl: adapter.supportsControl(session), ...extra }+ const reply = { version: RUNTIME_VERSION, answer }+ return Buffer.byteLength(JSON.stringify(reply)) <= RUNTIME_REPLY_BYTES ? reply : failure('ENGINE_REPLY_TOO_LARGE')+ })()])+ } catch { return failure('ENGINE_UNAVAILABLE') }+ finally { clearTimeout(timer); pending-- }+ }+ return { [RUNTIME_CAPABILITIES]: handler(RUNTIME_CAPABILITIES), [RUNTIME_READ]: handler(RUNTIME_READ) }+}diff --git a/cli/src/harnessd/services.spec.ts b/cli/src/harnessd/services.spec.tsindex 08ae000aa..fa3ecc721 100644--- a/cli/src/harnessd/services.spec.ts+++ b/cli/src/harnessd/services.spec.ts@@ -1,6 +1,6 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import {- DEFAULT_SERVICE_OPTIONS, ENGINE_LIVE_ENV, KNOWN_SERVICES, SERVICE_HOSTS, SERVICE_PROCESSES_ENV, ServiceSupervisor, UPDATER_HOST, masterRunsLiveEngines, serviceOptions, serviceProcessesEnv, serviceSpecs, servicesTheMasterRuns,+ DEFAULT_SERVICE_OPTIONS, ENGINE_LIVE_ENV, ENGINE_RUNTIME_ENV, KNOWN_SERVICES, SERVICE_HOSTS, SERVICE_PROCESSES_ENV, ServiceSupervisor, UPDATER_HOST, masterRunsLiveEngines, masterRunsEngineRuntime, serviceOptions, serviceProcessesEnv, serviceSpecs, servicesTheMasterRuns,type ServiceSpec, type ServiceSupervisorOptions,} from './services.js'import type { CoreHandle } from './supervisor.js'@@ -472,15 +472,15 @@ describe('which services the core leaves to its master', () => {it('is what the master says it runs, told in a form a core from before the list reads too', () => {const specs = serviceSpecs({ HARNESSD_SERVICES: 'search,workspaces' }, SERVICE_HOSTS)- expect(serviceProcessesEnv(specs, 42)).toEqual({ [SERVICE_PROCESSES_ENV]: 'search,workspaces', HARNESSD_SERVICES: 'search,workspaces', [ENGINE_LIVE_ENV]: '42:1' })+ expect(serviceProcessesEnv(specs, 42)).toEqual({ [SERVICE_PROCESSES_ENV]: 'search,workspaces', HARNESSD_SERVICES: 'search,workspaces', [ENGINE_LIVE_ENV]: '42:1', [ENGINE_RUNTIME_ENV]: '42:1' })// A process named as one of its services is named whole: the viewers' process runs the Store beside them.expect(serviceProcessesEnv(serviceSpecs({ HARNESSD_SERVICES: 'viewers' }, SERVICE_HOSTS), 42)).toMatchObject({ [SERVICE_PROCESSES_ENV]: 'viewers,store' })expect(serviceProcessesEnv(serviceSpecs({ HARNESSD_SERVICES: 'store' }, SERVICE_HOSTS), 42)).toMatchObject({ [SERVICE_PROCESSES_ENV]: 'store' })// By service, not by process: a core from before the edge host routes the services it knows of it.const hosted = serviceSpecs({ HARNESSD_SERVICES: 'edge' }, SERVICE_HOSTS)- expect(serviceProcessesEnv(hosted, 42)).toEqual({ [SERVICE_PROCESSES_ENV]: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell', HARNESSD_SERVICES: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell', [ENGINE_LIVE_ENV]: '42:1' })+ expect(serviceProcessesEnv(hosted, 42)).toEqual({ [SERVICE_PROCESSES_ENV]: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell', HARNESSD_SERVICES: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell', [ENGINE_LIVE_ENV]: '42:1', [ENGINE_RUNTIME_ENV]: '42:1' })expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv(hosted, 42) }, known)]).toEqual(['workspaces'])- expect(serviceProcessesEnv([], 42)).toEqual({ [SERVICE_PROCESSES_ENV]: '', HARNESSD_SERVICES: 'none', [ENGINE_LIVE_ENV]: '42:1' })+ expect(serviceProcessesEnv([], 42)).toEqual({ [SERVICE_PROCESSES_ENV]: '', HARNESSD_SERVICES: 'none', [ENGINE_LIVE_ENV]: '42:1', [ENGINE_RUNTIME_ENV]: '42:1' })expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv(specs, 42) }, known)]).toEqual(['search', 'workspaces'])expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv([], 42) }, known)]).toEqual([])// What the master says wins over whatever HARNESSD_SERVICES the core inherited; names it does not know are its own.@@ -505,6 +505,18 @@ describe('which services the core leaves to its master', () => {expect(masterRunsLiveEngines({ ...env, HARNESSD_SERVICE_TOKEN: undefined }, 42)).toBe(false)})+ it('accepts runtime profile support only from the actual supervising parent, independently of live support', () => {+ const env = { ...supervised, ...serviceProcessesEnv([], 42) }+ expect(masterRunsEngineRuntime(env, 42)).toBe(true)+ expect(masterRunsEngineRuntime(env, 43)).toBe(false)+ expect(masterRunsEngineRuntime(supervised, 42)).toBe(false)+ expect(masterRunsEngineRuntime({ ...env, [ENGINE_RUNTIME_ENV]: '1' }, 42)).toBe(false)+ expect(masterRunsEngineRuntime({ ...env, [ENGINE_RUNTIME_ENV]: '42:2' }, 42)).toBe(false)+ expect(masterRunsEngineRuntime({ ...env, HARNESSD_SUPERVISED: undefined }, 42)).toBe(false)+ expect(masterRunsEngineRuntime({ ...env, HARNESSD_SERVICE_TOKEN: undefined }, 42)).toBe(false)+ expect(masterRunsLiveEngines({ ...env, [ENGINE_RUNTIME_ENV]: undefined }, 42)).toBe(true)+ })+it('is none without a master, or without the token its services would connect with', () => {expect([...servicesTheMasterRuns({ [SERVICE_PROCESSES_ENV]: 'search' }, known)]).toEqual([])expect([...servicesTheMasterRuns({ HARNESSD_SUPERVISED: '1', [SERVICE_PROCESSES_ENV]: 'search' }, known)]).toEqual([])diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.tsindex 86ffd54b0..aeca007d9 100644--- a/cli/src/harnessd/services.ts+++ b/cli/src/harnessd/services.ts@@ -457,6 +457,8 @@ export function serviceOptions(env: NodeJS.ProcessEnv): ServiceSupervisorOptionsexport const SERVICE_PROCESSES_ENV = 'HARNESSD_SERVICE_PROCESSES'/** Version of the live engine methods hosted by this master, independent of reader-only hosts. */export const ENGINE_LIVE_ENV = 'HARNESSD_ENGINE_LIVE'+/** Runtime profile methods, negotiated independently from live transcript parsing. */+export const ENGINE_RUNTIME_ENV = 'HARNESSD_ENGINE_RUNTIME'/*** What a master puts in its core's environment about the services it runs in their own processes: the@@ -468,7 +470,7 @@ export function serviceProcessesEnv(specs: readonly ServiceSpec[], masterPid: nu// The services, not the processes: a core knows what it routes by service, and one from before the// edge host still finds the services it knows here (workspaces) and runs the rest itself.const names = specs.flatMap((spec) => spec.services).join(',')- return { [SERVICE_PROCESSES_ENV]: names, HARNESSD_SERVICES: names || 'none', [ENGINE_LIVE_ENV]: `${masterPid}:1` }+ return { [SERVICE_PROCESSES_ENV]: names, HARNESSD_SERVICES: names || 'none', [ENGINE_LIVE_ENV]: `${masterPid}:1`, [ENGINE_RUNTIME_ENV]: `${masterPid}:1` }}/** An older master may inherit a newer master's environment after rollback. Trust only this parent. */@@ -477,6 +479,11 @@ export function masterRunsLiveEngines(env: NodeJS.ProcessEnv, parentPid: number)&& env[ENGINE_LIVE_ENV] === `${parentPid}:1`}+export function masterRunsEngineRuntime(env: NodeJS.ProcessEnv, parentPid: number): boolean {+ return env.HARNESSD_SUPERVISED === '1' && !!env.HARNESSD_SERVICE_TOKEN+ && env[ENGINE_RUNTIME_ENV] === `${parentPid}:1`+}+/*** The services the core's master runs in their own processes, which the core routes to and does not* run itself: what the master says it runs (`serviceProcessesEnv`), never what this build would choose.diff --git a/cli/src/lib/runtimeProfile.ts b/cli/src/lib/runtimeProfile.tsindex 3be519b02..1b24e29b0 100644--- a/cli/src/lib/runtimeProfile.ts+++ b/cli/src/lib/runtimeProfile.ts@@ -1,1791 +1,15 @@-import { readFile } from 'fs/promises'-import { join } from 'path'-import { execFile } from 'child_process'-import { promisify } from 'util'-import { env } from '../config/env.js'-import { sessionClaudeHome, sessionCodexHome } from './engineHomes.js'-import { parseMuseSettings } from '../engines/muse/runtimeProfile.js'-import { parseAmpSession } from '../engines/amp/runtimeProfile.js'-import type { AgentEngine } from '../engines/types.js'+/** Inline compatibility composition. Supervised core must not import this module. */import type { RegisteredSession } from './registry.js'-import {- DEVIN_EFFORTS,- devinFooterModel,- parseDevinModelsOutput,- type DevinModelTarget,-} from '../engines/devin/runtimeProfile.js'-import {- HERMES_EFFORTS,- hermesStatusModel,- parseHermesConfig,- parseHermesModelsCache,- type HermesModelTarget,-} from '../engines/hermes/runtimeProfile.js'-import {- COMMANDCODE_EFFORTS,- commandcodeBannerModel,- COMMANDCODE_EFFORT_LEVELS,- parseCommandcodeModelsOutput,- type CommandcodeModelTarget,-} from '../engines/commandcode/runtimeProfile.js'-import {- opencodeFooterModelId,- parseOpencodeFooter,- parseOpencodeModelsOutput,- type OpencodeModelTarget,-} from '../engines/opencode/runtimeProfile.js'-import {- kiloFooterModelId,- parseKiloModelsOutput,- type KiloModelTarget,-} from '../engines/kilo/runtimeProfile.js'-import {- PI_EFFORTS,- PI_THINKING_LEVELS,- parsePiFooterProfile,- parsePiModelsOutput,-} from '../engines/pi/runtimeProfile.js'-import { parseGrokFooterProfile } from '../engines/grok/runtimeProfile.js'-import { parseAgyFooterProfile } from '../engines/agy/runtimeProfile.js'-import { parseCodexCatalog, type CodexCatalogModel } from '../engines/codex/modelPicker.js'+import { runtimeFor } from '../engines/runtime.js'+import { LegacyRuntimeProfileManager } from './runtimeProfileManager.js'-export interface RuntimeProfile {- id: string- sessionId: string- engine: AgentEngine- model: string- effort: string-}--export interface RuntimeModelOption {- id: string- displayName: string-}--export interface RuntimeState {- model: string | null- effort: string | null- mode: 'default' | 'plan' | 'unknown'- cliVersion: string | null- observedAt: number | null-}--/** The runtime axes a transcript record can set — see `RuntimeProfileManager.transcriptFields`. */-export type RuntimeField = 'model' | 'effort' | 'mode'--/** The session `transcriptFields` reads as — never a real one, so no model-switch control applies.- * No engine session id is empty or starts with NUL. */-const FIELD_PROBE = '\u0000transcript-fields'--const blankState = (): RuntimeState => ({ model: null, effort: null, mode: 'unknown', cliVersion: null, observedAt: null })--/** Where a session's runtime state starts before its transcript is read. */-function freshState(session: RegisteredSession): RuntimeState {- return {- ...blankState(),- // Registries written by older builds can hold a non-string model; treat it as unknown instead of- // letting it reach claudeAliasForModel and abort startup.- model: typeof session.model === 'string' ? session.model : null,- cliVersion: session.cliVersion,- }-}--export interface CursorModelTarget {- rawId: string- modelKey: string- familyLabel: string- context: string | null- reasoning: string | null- fast: boolean | null- thinking: boolean | null- /** Effort text rendered in the idle footer; null means Cursor omits its native default. */- footerEffort?: string | null-}--interface CursorCatalogEntry {- target: CursorModelTarget- effort: string- modelLabel: string-}--interface RuntimeControl {- target: RuntimeProfile- before: string | null- modelConfirmed: boolean- effortConfirmed: boolean-}--interface StateWaiter {- check: () => boolean- resolve: (matched: boolean) => void- timer: NodeJS.Timeout-}--interface CodexCacheModel {- slug?: unknown- display_name?: unknown- visibility?: unknown- supported_reasoning_levels?: Array<{ effort?: unknown }>-}--interface CodexCache {- models?: CodexCacheModel[]-}--const PROFILE_RE = /^runtime-v1:([^:]+):(claude|codex|cursor|commandcode|pi|devin|opencode|hermes|muse|amp|kilo|grok|agy|copilot):([^@]+)@([a-z0-9_-]+)$/i-/**- * `persistent` came with Codex 0.160 (`ReasoningEffort::Persistent`, "Continue working until put to- * sleep"): without it here a thread on it read as no effort at all, so its chip showed nothing and a- * switch to it could never be confirmed.- */-const CODEX_EFFORTS = new Set(['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra', 'persistent'])-const CLAUDE_EFFORTS = new Set(['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultracode'])-const CURSOR_EFFORTS = new Set(['auto', 'none', 'low', 'medium', 'high', 'xhigh', 'max'])-const EFFORTS = new Set([- ...CODEX_EFFORTS, ...CLAUDE_EFFORTS, ...CURSOR_EFFORTS, ...PI_EFFORTS, ...DEVIN_EFFORTS,- ...COMMANDCODE_EFFORTS, ...HERMES_EFFORTS,-])-/**- * Versions whose model UI was driven by hand before wiring it up. Open-ended upward: a newer CLI is- * assumed compatible (the alternative — refusing to switch after every auto-update — is worse), but a- * KNOWN-older one is refused rather than driven blind.- */-const DEVIN_CONTROL_MIN_VERSION: [number, number, number] = [3000, 3, 22]-const PI_CONTROL_MIN_VERSION: [number, number, number] = [0, 82, 0]-const OPENCODE_CONTROL_MIN_VERSION: [number, number, number] = [1, 18, 7]-/**- * 1.6.0 is the first Command Code that can be driven at all: it added `--list-models` (a catalog on- * stdout) and made `/model <id>` and `/effort <level>` take arguments. On 1.5 and older the only route was- * arrow-driving a 49-row picker, which is exactly what got the first attempt reverted — so older builds- * are refused rather than driven.- */-const COMMANDCODE_CONTROL_MIN_VERSION: [number, number, number] = [1, 6, 0]-/**- * Hermes ships no version its hook payload exposes, and its `/model` picker has been the same two-level- * arrow list throughout — so it is gated on the picker being recognisable rather than on a number. The- * driver refuses to move if it cannot read the cursor (see setHermes), which is the real safety net.- */-const HERMES_CONTROL_UNVERSIONED = true-/**- * Cap on how many rows an engine's catalog may contribute. Devin publishes 166 across 72 families, and a- * 49-row picker was enough to stall the device's the device UI task into a watchdog reset (see the Command Code- * revert, 2026-07-30). The device already truncates at CATALOG_MAX/PICK_MAX, but truncation there is- * arbitrary — bounding here keeps the rows we DO send meaningful (see devinModels).- */-const CATALOG_LIMIT = 96-const BASIC_EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'] as const-const CLAUDE_ALIASES = ['default', 'opus', 'fable', 'sonnet', 'haiku'] as const-const CHANGE_DEBOUNCE_MS = 120-const CLAUDE_ULTRACODE_MIN_VERSION: [number, number, number] = [2, 1, 209]-/** The first Codex whose `/model` picker was driven by hand (see supportsNativeRuntimeControl). */-const CODEX_CONTROL_MIN_VERSION: [number, number, number] = [0, 144, 0]-const CURSOR_CONTROLLED_BUILD = '2026.07.20-8cc9c0b'-const CURSOR_CATALOG_TTL_MS = 5 * 60_000-/** Shared TTL for the stdout catalogs (devin, pi) — same rationale as the cursor one. */-const CATALOG_TTL_MS = 5 * 60_000-import { opencodeBin } from './engineBin.js'--const execFileAsync = promisify(execFile)--function decode(value: string): string | null {- try {- const out = decodeURIComponent(value)- return out ? out : null- } catch {- return null- }-}--export function encodeRuntimeProfile(profile: Omit<RuntimeProfile, 'id'>): string {- return `runtime-v1:${encodeURIComponent(profile.sessionId)}:${profile.engine}:${encodeURIComponent(profile.model)}@${profile.effort}`-}--export function parseRuntimeProfile(value: unknown): RuntimeProfile | null {- if (typeof value !== 'string') return null- const match = PROFILE_RE.exec(value)- if (!match) return null- const sessionId = decode(match[1])- const model = decode(match[3])- const effort = match[4].toLowerCase()- if (!sessionId || !model || !EFFORTS.has(effort)) return null- return {- id: value,- sessionId,- engine: match[2].toLowerCase() as AgentEngine,- model,- effort,- }-}--function record(value: unknown): Record<string, unknown> | null {- return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : null-}--function text(value: unknown): string {- return typeof value === 'string' ? value : ''-}--function stripAnsi(value: string): string {- return value.replace(/\u001b\[[0-9;:]*[A-Za-z]/g, '')-}--function flattenContent(value: unknown): string {- if (typeof value === 'string') return value- if (!Array.isArray(value)) return ''- return value.map((item) => {- if (typeof item === 'string') return item- const obj = record(item)- return text(obj?.text) || text(obj?.content)- }).filter(Boolean).join('\n')-}--function confirmsClaudeAutoEffort(content: string): boolean {- return [- /\b(?:set|reset)\b.{0,40}\b(?:effort level|effort)\b.{0,40}\b(?:auto|model default)\b/i,- /\b(?:effort level|effort)\b.{0,40}\b(?:set|reset)\b.{0,40}\b(?:auto|model default)\b/i,- /\busing\b.{0,40}\bauto\b.{0,40}\beffort\b/i,- ].some((pattern) => pattern.test(content))-}--function parseVersion(value: string | null): [number, number, number] | null {- const match = /(?:^|\D)(\d+)\.(\d+)\.(\d+)(?:\D|$)/.exec(value ?? '')- return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null-}--function versionAtLeast(value: string | null, wanted: [number, number, number]): boolean {- const parsed = parseVersion(value)- if (!parsed) return false- for (let i = 0; i < wanted.length; i++) {- if (parsed[i] !== wanted[i]) return parsed[i] > wanted[i]- }- return true-}+export * from './runtimeProfileManager.js'+export { codexEffortAllowed } from '../engines/codex/runtimeProfile.js'export function supportsNativeRuntimeControl(session: RegisteredSession): boolean {- // A gateway agent (`ori claude`, `ori codex`) is DISPLAY-ONLY (owner, 2026-08-17). Its CLI runs with- // gateway model discovery, so the picker holds the user's OpenRouter catalog rather than the native- // aliases this controller knows how to type — and a `/model opus` typed into that pane would be a- // guess. The chip still names what it is running; nothing offers to change it.- if (session.gateway) return false- // Switching is Claude and Codex only (owner, 2026-07-31); everything else is view-only, so it never gets- // here with anything to apply. This is the second gate rather than the only one — modelsForSession- // already returns an empty catalogue for those engines — because a stale profile id from an older device- // would otherwise still drive a CLI the owner took off the switchable list.- if (session.engine === 'claude') return versionAtLeast(session.cliVersion, [2, 1, 153])- if (session.engine !== 'codex') return false- // Open upward, like Claude Code's. It allowed exactly 0.144 and 0.145, the two releases whose picker- // was driven by hand, so every Codex kept up to date (0.160 on 2026-10-05) could not be switched at- // all. The controller now reads the picker by what it says rather than by release: rows by slug or- // catalog display name, the rows read again before a digit, and nothing pressed when the row is not- // found exactly (engines/codex/modelPicker.ts).- return versionAtLeast(session.cliVersion, CODEX_CONTROL_MIN_VERSION)-}--/**- * Whether Codex can be asked for this effort on this model. `listed` is what Codex's own catalog- * (`models_cache.json`) gives the model, or null when the catalog cannot be read or does not have it.- *- * Max and Ultra follow the catalog: Codex offers them in its picker exactly where the catalog lists them- * (model_popups.rs), and 0.160's lists them for gpt-6-astra, gpt-6.1-sol and gpt-6-sol, which the slug- * list below left out of reach (owner, 2026-10-05). The slug list is what was known from 0.145, kept for- * when there is no catalog to ask.- */-export function codexEffortAllowed(model: string, effort: string, listed: readonly string[] | null = null): boolean {- if (!CODEX_EFFORTS.has(effort)) return false- if (effort !== 'max' && effort !== 'ultra') return true- if (listed) return listed.includes(effort)- return /^gpt-5\.6(?:-|$)/i.test(model) || model.toLowerCase() === 'codex-auto-review'-}--function titlePart(value: string): string {- if (/^gpt$/i.test(value)) return 'GPT'- if (/^xhigh$/i.test(value)) return 'XHigh'- return value.charAt(0).toUpperCase() + value.slice(1)-}--export function runtimeModelLabel(model: string): string {- const alias = /^(default|best|fable|opus|sonnet|haiku)(\[1m\])?$/i.exec(model)- if (alias) return `${titlePart(alias[1].toLowerCase())}${alias[2] ?? ''}`- return model.split(/[-_]/).filter(Boolean).map(titlePart).join(' ')-}--function effortLabel(effort: string): string {- return effort === 'xhigh' ? 'XHigh' : titlePart(effort)-}--function cursorEffortFromId(rawId: string): { effort: string | null; modelKey: string } {- const parts = rawId.split('-')- let index = -1- let width = 1- for (let i = 2; i < parts.length; i++) {- if (parts[i] === 'extra' && parts[i + 1] === 'high') {- index = i- width = 2- i++- } else if (['none', 'low', 'medium', 'high', 'xhigh', 'max'].includes(parts[i])) {- index = i- width = 1- }- }- if (index < 0) return { effort: null, modelKey: rawId }- const rawEffort = parts.slice(index, index + width).join('-')- parts.splice(index, width)- return {- effort: rawEffort === 'extra-high' ? 'xhigh' : rawEffort,- modelKey: parts.join('-'),- }-}--function cursorEffortFromDisplay(value: string): string | null {- const match = /\b(Extra High|None|Low|Medium|High|Max)\b/i.exec(value)- if (!match) return null- return match[1].toLowerCase().replace(/\s+/g, '') === 'extrahigh'- ? 'xhigh'- : match[1].toLowerCase()+ return !session.gateway && (runtimeFor(session.engine)?.supportsControl(session) ?? false)}-function cursorDisplayParts(displayName: string): {- familyLabel: string- context: string | null- fast: boolean- thinking: boolean-} {- let value = displayName- .replace(/\s+\((?:current|default)(?:,\s*(?:current|default))?\)\s*$/i, '')- .replace(/\s+\(NO ZDR\)\s*$/i, '')- .replace(/\s*[·│]\s*\d+(?:\.\d+)?%.*$/i, '')- .trim()- const contextMatch = /\b(\d+(?:\.\d+)?[KM])\b/i.exec(value)- const context = contextMatch?.[1].toLowerCase() ?? null- const fast = /\bFast\b/i.test(value)- const thinking = !/\bNo\s+Thinking\b/i.test(value) && /\bThinking\b/i.test(value)- value = value- .replace(/\b\d+(?:\.\d+)?[KM]\b/gi, '')- .replace(/\bExtra High\b/gi, '')- .replace(/\b(?:None|Low|Medium|High|Max)\b/gi, '')- .replace(/\bNo\s+Thinking\b/gi, '')- .replace(/\b(?:Fast|Thinking)\b/gi, '')- .replace(/\s+/g, ' ')- .trim()- return { familyLabel: value, context, fast, thinking }-}--/** Strictly parse `agent models`; headings, tips and malformed rows are ignored. */-export function parseCursorModelsOutput(output: string): CursorCatalogEntry[] {- const candidates: Array<CursorCatalogEntry & { explicitEffort: boolean }> = []- for (const rawLine of output.split('\n')) {- const match = /^([a-z0-9][a-z0-9._-]*) - (.+?)\s*$/i.exec(rawLine)- if (!match) continue- const rawId = match[1]- const displayName = match[2].trim()- const display = cursorDisplayParts(displayName)- if (!display.familyLabel) continue- if (rawId === 'auto') {- candidates.push({- target: {- rawId,- modelKey: rawId,- familyLabel: 'Auto',- context: null,- reasoning: null,- fast: null,- thinking: null,- footerEffort: 'auto',- },- effort: 'auto',- modelLabel: 'Auto',- explicitEffort: true,- })- continue- }- const parsed = cursorEffortFromId(rawId)- const effort = parsed.effort- const footerEffort = cursorEffortFromDisplay(displayName)- candidates.push({- target: {- rawId,- modelKey: parsed.modelKey,- familyLabel: display.familyLabel,- context: display.context,- reasoning: effort,- fast: display.fast,- thinking: display.thinking,- footerEffort,- },- effort: effort ?? 'auto',- modelLabel: [- display.familyLabel,- display.context ? `(${display.context.toUpperCase()})` : '',- display.thinking ? 'Thinking' : '',- display.fast ? 'Fast' : '',- ].filter(Boolean).join(' '),- explicitEffort: effort !== null,- })- }-- // Some medium/default rows omit the effort segment (for example `gpt-5.3-codex`).- // Infer medium only when explicit siblings prove that the same exact model group has efforts.- const effortfulGroups = new Set(candidates.filter((item) => item.explicitEffort).map((item) => item.target.modelKey))- for (const item of candidates) {- if (item.target.rawId === 'auto' || item.effort !== 'auto' || !effortfulGroups.has(item.target.modelKey)) continue- item.effort = 'medium'- item.target.reasoning = 'medium'- }- return candidates.map(({ explicitEffort: _explicitEffort, ...item }) => item)-}--function parseCursorFooter(value: string): {- familyLabel: string- context: string | null- effort: string | null- fast: boolean- thinking: boolean-} | null {- const line = stripAnsi(value).trim()- if (/^Auto(?:\s*$|\s*[·│])/i.test(line)) {- return { familyLabel: 'Auto', context: null, effort: 'auto', fast: false, thinking: false }- }- const effort = cursorEffortFromDisplay(line)- const hasUsage = /[·│]\s*\d+(?:\.\d+)?%/i.test(line)- const hasThinkingMode = /\b(?:No\s+Thinking|Thinking)\b/i.test(line)- if (!effort && !hasUsage && !hasThinkingMode) return null- const parts = cursorDisplayParts(line)- if (!parts.familyLabel || !/\d/.test(parts.familyLabel)) return null- return {- ...parts,- effort,- }-}--function cursorSyntheticTarget(- parsed: NonNullable<ReturnType<typeof parseCursorFooter>>,- effort: string,-): CursorModelTarget {- if (parsed.familyLabel.toLowerCase() === 'auto' && parsed.effort === 'auto') {- return {- rawId: 'auto',- modelKey: 'auto',- familyLabel: 'Auto',- context: null,- reasoning: null,- fast: null,- thinking: null,- footerEffort: 'auto',- }- }- const family = parsed.familyLabel.toLowerCase().replace(/[^a-z0-9.]+/g, '-').replace(/^-|-$/g, '') || 'model'- // Keep the public runtime-v1 model key compatible with every client formatter. The Cursor routing- // details remain on CursorModelTarget (and rawId) for selection/confirmation; they do not belong in- // the user-facing profile key as a percent-encoded "[fast=...,thinking=...]" implementation detail.- const modelKey = [- family,- parsed.context?.toLowerCase() ?? '',- parsed.thinking ? 'thinking' : '',- parsed.fast ? 'fast' : '',- ].filter(Boolean).join('-')- const parameters = [- parsed.context ? `context=${parsed.context}` : '',- `fast=${parsed.fast}`,- `thinking=${parsed.thinking}`,- ].filter(Boolean).join(',')- return {- rawId: `cursor-${family}[${parameters},effort=${effort}]`,- modelKey,- familyLabel: parsed.familyLabel,- context: parsed.context,- reasoning: effort === 'auto' ? null : effort,- fast: parsed.fast,- thinking: parsed.thinking,- footerEffort: parsed.effort,- }-}--function normalizeClaudeDisplay(value: string): string | null {- const cleaned = value- .replace(/\u001b\[[0-9;]*m/g, '')- .replace(/\s+\(default\).*$/i, '')- .replace(/\s+and saved.*$/i, '')- .replace(/\s+for (?:the )?current session.*$/i, '')- .trim()- if (!cleaned) return null- const alias = /^(default|best|fable|opus|sonnet|haiku)(\[1m\])?$/i.exec(cleaned)- if (alias) return `${alias[1].toLowerCase()}${alias[2]?.toLowerCase() ?? ''}`- const family = /^(Fable|Opus|Sonnet|Haiku)\s+(\d+(?:\.\d+)*)(?:\s+\(1M context\))?/i.exec(cleaned)- if (family) return `claude-${family[1].toLowerCase()}-${family[2].replace(/\./g, '-')}${/1M context/i.test(cleaned) ? '[1m]' : ''}`- if (/^claude-[a-z0-9._:-]+(?:\[1m\])?$/i.test(cleaned)) return cleaned.toLowerCase()- return null-}--function claudeAliasForModel(model: string): string | null {- const normalized = model.toLowerCase()- if ((CLAUDE_ALIASES as readonly string[]).includes(normalized)) return normalized- return /^claude-(opus|fable|sonnet|haiku)(?:-|$)/.exec(normalized)?.[1] ?? null-}--function claudeEfforts(model: string, cliVersion: string | null = null): string[] {- // `[1m]` marks the 1M-context variant, not a different model — strip it so `claude-opus-5[1m]` gets- // the same efforts as `claude-opus-5` (otherwise a 1M model looked effort-less and a /model switch- // reset the observed effort to `auto`). The version match is open-ended (4.7/4.8, then 5+) so a new- // release like Opus 5 works without a code change.- const normalized = model.toLowerCase().replace(/\[1m\]$/, '')- let efforts: string[] = []- if (/^claude-(?:opus|fable|sonnet)-(?:4-[78]|[5-9]|\d{2,})(?:-|$)/.test(normalized)) efforts = [...BASIC_EFFORTS]- else if (/^claude-(?:opus|sonnet)-4-6(?:-|$)/.test(normalized)) efforts = ['low', 'medium', 'high', 'max']- else if (/^(?:fable|opus|sonnet)$/.test(normalized)) efforts = [...BASIC_EFFORTS]- if (efforts.length > 0 && versionAtLeast(cliVersion, CLAUDE_ULTRACODE_MIN_VERSION)) efforts.push('ultracode')- return efforts-}--function availableModelMatches(model: string, allowed: string[]): boolean {- if (model === 'default') return true- if (allowed.length === 0) return true- const lower = model.toLowerCase()- const family = lower.replace(/\[1m\]$/, '')- const wantsLongContext = lower.endsWith('[1m]')- return allowed.some((item) => {- const candidate = item.toLowerCase()- const sameFamily = candidate.includes(`-${family}-`) || candidate.endsWith(`-${family}`)- const contextMatches = wantsLongContext === /(?:\[1m\]|1m.context)/i.test(candidate)- return lower === candidate || lower.startsWith(`${candidate}-`) || lower.startsWith(`${candidate}[`) || (sameFamily && contextMatches)- })-}--function currentPaneUi(paneText: string): string {- const lines = paneText.split('\n')- const promptIndex = lines.findLastIndex((line) => {- const marker = line.search(/[›❯→]/u)- return marker >= 0 && !/^\s*\d+\.\s/.test(line.slice(marker + 1))- })- return (promptIndex >= 0 ? lines.slice(promptIndex) : lines).join('\n')-}--async function readJson(file: string): Promise<Record<string, unknown> | null> {- try { return record(JSON.parse(await readFile(file, 'utf8'))) } catch { return null }-}--/** Raw file text, or '' when it cannot be read — hermes' config is YAML, not JSON. */-async function readText(file: string): Promise<string> {- try { return await readFile(file, 'utf8') } catch { return '' }-}--function claudeSettingsFiles(session: RegisteredSession): string[] {- const root = sessionClaudeHome(session)- const files = [join(root, 'settings.json')]- if (session.cwd) {- files.push(join(session.cwd, '.claude', 'settings.json'))- files.push(join(session.cwd, '.claude', 'settings.local.json'))- }- return files-}--async function claudeAvailableModels(session: RegisteredSession): Promise<string[]> {- const merged: string[] = []- for (const file of claudeSettingsFiles(session)) {- const config = await readJson(file)- const values = config?.availableModels- if (!Array.isArray(values)) continue- for (const value of values) if (typeof value === 'string' && !merged.includes(value)) merged.push(value)- }- return merged-}--/** Command Code ids are "vendor/name"; everything we store and show uses the name alone. */-function shortCommandcodeModel(id: string): string {- return id.slice(id.lastIndexOf('/') + 1)-}--/**- * Command Code keeps the reasoning level in its GLOBAL config, keyed by the FULL gateway id:- * { "model": "deepseek/deepseek-v4-flash", "reasoningEffort": { "deepseek/deepseek-v4-flash": "high" } }- * Nothing in the transcript, the pane footer or the session header carries it, so this file is the only- * source. It is per MACHINE rather than per session: two agents on the same model necessarily read the same- * level. Matching is done on the short name because that is what the running model is stored as.- */-/** The configured level for `model`, or 'auto' when the model has none set. */-async function commandcodeConfiguredEffort(model: string | null): Promise<{ effort: string; defaultModel: string }> {- const config = await readJson(join(env.COMMANDCODE_HOME, 'config.json'))- const defaultModel = shortCommandcodeModel(text(config?.model))- const efforts = record(config?.reasoningEffort)- const wanted = model || defaultModel- if (!efforts || !wanted) return { effort: 'auto', defaultModel }- for (const [id, level] of Object.entries(efforts)) {- if (shortCommandcodeModel(id) !== wanted) continue- const normalized = text(level).toLowerCase()- if (normalized && normalized !== 'default' && EFFORTS.has(normalized)) return { effort: normalized, defaultModel }- }- return { effort: 'auto', defaultModel }-}--async function claudeConfiguredEffort(session: RegisteredSession): Promise<string> {- let configured: string | null = null- for (const file of claudeSettingsFiles(session)) {- const config = await readJson(file)- const raw = text(config?.effortLevel) || text(config?.effort)- const normalized = raw.toLowerCase() === 'default' ? 'auto' : raw.toLowerCase()- if (CLAUDE_EFFORTS.has(normalized)) configured = normalized- }- return configured ?? 'auto'-}--/** The first-run banner names the model before Claude writes a conversation transcript. */-function claudeStartupBanner(pane: string): { model: string; effort?: string } | null {- const lines = pane.split('\n')- const start = lines.findLastIndex(line => /\bClaude Code v\d+\.\d+/.test(line))- if (start < 0) return null- const banner = lines.slice(start, start + 4).join('\n')- const match = /\b(Fable|Opus|Sonnet|Haiku)\s+(\d+(?:\.\d+)*)(\s+\(1M context\))?(?:\s+with\s+(low|medium|high|xhigh|max|ultracode)\s+effort)?\s*·\s*Claude\s+(?:Max|Pro|Team|Enterprise)\b/i.exec(banner)- if (!match) return null- return {- model: `claude-${match[1].toLowerCase()}-${match[2].replace(/\./g, '-')}${match[3] ? '[1m]' : ''}`,- ...(match[4] ? { effort: match[4].toLowerCase() } : {}),- }-}--function addOption(- output: RuntimeModelOption[],- seen: Set<string>,- session: RegisteredSession,- model: string,- effort: string,- modelLabel = runtimeModelLabel(model),-): void {- // The id inside a `runtime-v1:` string is what the web/device echoes back on a pick, so it is the- // AGENT id — the public one — not the engine session that happens to be bound right now.- const id = encodeRuntimeProfile({ sessionId: session.agentId, engine: session.engine, model, effort })- if (seen.has(id)) return- seen.add(id)- output.push({ id, displayName: `${modelLabel} / ${effortLabel(effort)}` })-}--export class RuntimeProfileManager {- private readonly states = new Map<string, RuntimeState>()- private readonly controls = new Map<string, RuntimeControl>()- private readonly waiters = new Map<string, Set<StateWaiter>>()- private readonly changeTimers = new Map<string, NodeJS.Timeout>()- private readonly cursorTargets = new Map<string, Map<string, CursorModelTarget>>()- /** profile id → the exact `/model` argument, per session (devin ids are not derivable from the key). */- private readonly devinTargets = new Map<string, Map<string, DevinModelTarget>>()- private devinCatalogCache: { key: string; expiresAt: number; entries: DevinModelTarget[] } | null = null- private piCatalogCache: { key: string; expiresAt: number; entries: ReturnType<typeof parsePiModelsOutput> } | null = null- private opencodeCatalogCache: { key: string; expiresAt: number; entries: OpencodeModelTarget[] } | null = null- private kiloCatalogCache: { key: string; expiresAt: number; entries: KiloModelTarget[] } | null = null- private commandcodeCatalogCache: { key: string; expiresAt: number; entries: CommandcodeModelTarget[] } | null = null- /** profile id → the full `/model` argument (the profile carries the SHORT name the device labels by). */- private readonly commandcodeTargets = new Map<string, Map<string, CommandcodeModelTarget>>()- /** Per HOME, not one slot: a desk with a default-home agent and a profile agent would otherwise- * evict each other's catalog on every menu open (`hermes -p <name>` has its own providers). */- private hermesCatalogCache = new Map<string, { expiresAt: number; entries: HermesModelTarget[] }>()- /** profile id → the picker page + row a hermes model sits on. */- private readonly hermesTargets = new Map<string, Map<string, HermesModelTarget>>()- private cursorCatalogCache: { key: string; expiresAt: number; entries: CursorCatalogEntry[] } | null = null- private suppressNotifications = 0- onChanged: ((sessionId: string) => void) | null = null-- hydrate(session: RegisteredSession, rawLines: string[]): void {- if (this.unbound(session.sessionId)) return- this.states.set(session.sessionId, freshState(session))- for (const line of rawLines) this.ingest(session, line, true)- }-- /**- * `hydrate`, for a Claude Code or Codex transcript streamed in rather than loaded- * (lib/attachTranscript.ts): records are read into a staged state, and what the session shows only- * changes at `commit` — never an empty chip while the read runs, never a live record overwritten by- * an older one read after it.- */- beginHydrate(session: RegisteredSession): { ingest(rawLine: string): void; commit(): void } {- const staged = freshState(session)- return {- ingest: (rawLine) => {- let raw: Record<string, unknown> | null- try { raw = record(JSON.parse(rawLine)) } catch { return }- if (!raw) return- if (session.engine === 'codex') this.ingestCodex(session, raw, staged)- else this.ingestClaude(session, raw, staged)- },- commit: () => {- if (this.unbound(session.sessionId)) return- this.states.set(session.sessionId, staged)- this.wake(session.sessionId)- },- }- }-- ingest(session: RegisteredSession, rawLine: string, silent = false): boolean {- let raw: Record<string, unknown> | null- try { raw = record(JSON.parse(rawLine)) } catch { return false }- if (!raw) return false- const before = this.selectedModel(session)- if (session.engine === 'codex') this.ingestCodex(session, raw)- else if (session.engine === 'cursor') this.ingestCursor(session, raw)- else if (session.engine === 'commandcode') {- const model = this.states.get(session.sessionId)?.model ?? null- this.ingestCommandcode(session, raw)- // The reasoning level is stored PER MODEL, so a model change makes the level we are holding wrong.- // Re-read it now instead of showing the previous model's level until the next poll.- if ((this.states.get(session.sessionId)?.model ?? null) !== model) {- void this.ingestConfig(session, silent).catch(() => undefined)- }- }- else if (session.engine === 'grok') this.ingestGrok(session, raw)- else this.ingestClaude(session, raw)- const after = this.selectedModel(session)- this.wake(session.sessionId)- if (!silent && this.suppressNotifications === 0 && before !== after && !this.controls.has(session.sessionId)) this.scheduleChanged(session.sessionId)- return before !== after- }-- /**- * Which of model, effort and mode one Claude or Codex transcript record sets — asked of the same- * readers `ingest` uses, on a scratch state, so the two cannot disagree. An attach that reads only the- * end of a transcript (lib/attachTranscript.ts) reaches back to the newest record that set each one.- *- * It can only under-report (the session's own model-switch control is not consulted), and the attach- * replays every record from the oldest one it reached, so under-reporting costs a longer reach, never- * a wrong value.- */- transcriptFields(session: RegisteredSession, rawLine: string): RuntimeField[] {- if (session.engine !== 'claude' && session.engine !== 'codex') return []- let raw: Record<string, unknown> | null- try { raw = record(JSON.parse(rawLine)) } catch { return [] }- if (!raw) return []- const probe: RegisteredSession = { ...session, sessionId: FIELD_PROBE }- const state = blankState()- if (session.engine === 'codex') this.ingestCodex(probe, raw, state)- else this.ingestClaude(probe, raw, state)- const fields: RuntimeField[] = []- if (state.model !== null) fields.push('model')- if (state.effort !== null) fields.push('effort')- if (state.mode !== 'unknown') fields.push('mode')- return fields- }-- async ingestConfig(session: RegisteredSession, silent = false): Promise<boolean> {- if (session.engine === 'hermes') {- // Both axes are scalars in config.yaml and neither is announced, so this poll is the only reader.- const before = this.selectedModel(session)- const state = this.state(session.sessionId)- // This agent's OWN home: `hermes -p <name>` keeps its model and effort in the profile's- // config.yaml, and reading the default one reported the wrong model on every profile agent.- const parsed = parseHermesConfig(await readText(join(session.hermesHome || env.HERMES_HOME, 'config.yaml')))- if (parsed.model) state.model = parsed.model.slice(parsed.model.lastIndexOf('/') + 1)- state.effort = parsed.effort ?? 'auto'- state.observedAt = Date.now()- const after = this.selectedModel(session)- this.wake(session.sessionId)- if (!silent && this.suppressNotifications === 0 && before !== after && !this.controls.has(session.sessionId)) {- this.scheduleChanged(session.sessionId)- }- return before !== after- }- if (session.engine === 'muse') {- // Both axes are plain scalars in ~/.config/muse/settings.json (`model`, `reasoning_effort`) and- // neither is announced anywhere, so reading the file IS the only way the chip is ever populated.- // `reasoning_effort` is muse's own vocabulary (none|minimal|low|medium|high|xhigh|ultra); the- // absence of the key means the CLI default, which its own --help documents as `high`.- const before = this.selectedModel(session)- const state = this.state(session.sessionId)- const parsed = parseMuseSettings(await readText(join(env.MUSE_CONFIG_DIR, 'settings.json')))- if (parsed.model) state.model = parsed.model- state.effort = parsed.effort ?? 'auto'- state.observedAt = Date.now()- const after = this.selectedModel(session)- this.wake(session.sessionId)- if (!silent && this.suppressNotifications === 0 && before !== after && !this.controls.has(session.sessionId)) {- this.scheduleChanged(session.sessionId)- }- return before !== after- }- if (session.engine === 'amp') {- // Amp has no models — only agent MODES — so the mode is reported as the model and there is no- // second axis to report. `~/.local/share/amp/session.json` is the only local place it is written.- const before = this.selectedModel(session)- const state = this.state(session.sessionId)- const parsed = parseAmpSession(await readText(join(env.AMP_STATE_DIR, 'session.json')))- if (parsed.mode) state.model = parsed.mode- state.effort = 'auto'- state.observedAt = Date.now()- const after = this.selectedModel(session)- this.wake(session.sessionId)- if (!silent && this.suppressNotifications === 0 && before !== after && !this.controls.has(session.sessionId)) {- this.scheduleChanged(session.sessionId)- }- return before !== after- }- if (session.engine === 'opencode') {- // The footer only resolves against the catalog, so warm it here — `ingestPane` is synchronous and- // cannot fetch, and without this the chip stays blank until the web happens to ask for models.- await this.opencodeCatalog()- return false- }- if (session.engine === 'kilo') {- // Same reason as opencode: kilo names its model only in the composer footer, which resolves only- // against the catalog, and `ingestPane` is synchronous.- await this.kiloCatalog()- return false- }- if (session.engine === 'devin') {- // Same shape: devin's model exists only as a DISPLAY name in its pane footer, and only the catalog- // maps that back to a model key + effort. Warm it on attach so the first pane read resolves.- await this.devinCatalog()- return false- }- if (session.engine !== 'claude' && session.engine !== 'commandcode') return false- const before = this.selectedModel(session)- const state = this.state(session.sessionId)- if (session.engine === 'commandcode') {- const config = await commandcodeConfiguredEffort(state.model)- state.effort = config.effort- // Before the agent has answered once there is no transcript line to read the model from; the config's- // own model is what a fresh session starts on, so the chip names it instead of falling back to Auto.- if (!state.model && config.defaultModel) state.model = config.defaultModel- } else {- state.effort = await claudeConfiguredEffort(session)- }- state.observedAt = Date.now()- const after = this.selectedModel(session)- this.wake(session.sessionId)- if (!silent && this.suppressNotifications === 0 && before !== after && !this.controls.has(session.sessionId)) {- this.scheduleChanged(session.sessionId)- }- return before !== after- }-- ingestPane(session: RegisteredSession, paneText: string, silent = false): boolean {- const before = this.selectedModel(session)- const state = this.state(session.sessionId)- paneText = stripAnsi(paneText)- const currentUi = currentPaneUi(paneText)- if (session.engine === 'codex') {- const matches = [...paneText.matchAll(/\b(gpt-[a-z0-9][a-z0-9._-]*)\s+(low|medium|high|xhigh|max|ultra|persistent|default)\s*[·│]/gi)]- const latest = matches[matches.length - 1]- if (latest) {- state.model = latest[1].toLowerCase()- state.effort = latest[2].toLowerCase() === 'default' ? 'auto' : latest[2].toLowerCase()- state.observedAt = Date.now()- }- if (/\bplan mode\b/i.test(currentUi)) state.mode = 'plan'- else if (/\b(?:default|work) mode\b/i.test(currentUi)) state.mode = 'default'- } else if (session.engine === 'cursor') {- if (/Available models|Models matching|— Edit Parameters|Type to filter.*Tab to edit|Esc to go back/i.test(currentUi)) return false- const footerLines = currentUi.split('\n')- .filter((line) => stripAnsi(line).trim())- .slice(-12)- .reverse()- const parsed = footerLines.map(parseCursorFooter).find((item) => item !== null)- if (parsed) {- const targets = this.cursorTargets.get(session.sessionId) ?? new Map<string, CursorModelTarget>()- let target = [...targets.values()].find((candidate) =>- candidate.familyLabel.toLowerCase() === parsed.familyLabel.toLowerCase()- && (parsed.effort- ? (candidate.reasoning ?? 'auto') === parsed.effort- : candidate.footerEffort === null)- && (candidate.fast ?? false) === parsed.fast- && (candidate.thinking ?? false) === parsed.thinking- && (!candidate.context || candidate.context === parsed.context))- const effort = parsed.effort ?? target?.reasoning ?? 'auto'- if (!target) {- target = cursorSyntheticTarget(parsed, effort)- const id = encodeRuntimeProfile({- sessionId: session.agentId,- engine: 'cursor',- model: target.modelKey,- effort,- })- targets.set(id, target)- this.cursorTargets.set(session.sessionId, targets)- }- state.model = target.modelKey- state.effort = effort- state.observedAt = Date.now()- const control = this.controls.get(session.sessionId)- if (control && target?.modelKey === control.target.model && effort === control.target.effort) {- control.modelConfirmed = true- control.effortConfirmed = true- }- }- if (/\bPlan\b/i.test(currentUi)) state.mode = 'plan'- else if (/Plan, search, build anything/i.test(currentUi)) state.mode = 'default'- } else if (session.engine === 'devin') {- // Devin writes no transcript unless the user passes `--export`, so the footer's bottom-left cell is- // the only per-session record of the running model. It is a DISPLAY name (`SWE-1.6 Slow`); the- // catalog resolves it back to a model key so the chip and the picker agree.- const label = devinFooterModel(paneText)- const model = label ? this.devinModelKeyForLabel(session.sessionId, label) : null- if (model) {- state.model = model.modelKey- state.effort = model.effort- state.observedAt = Date.now()- this.confirmObserved(session.sessionId, model.modelKey, model.effort)- }- } else if (session.engine === 'hermes') {- // `⚕ minimax-m3 │ ctx --` — the status line is how a switch is seen immediately; config.yaml is- // rewritten too, but the poll that reads it runs on its own schedule.- const model = hermesStatusModel(paneText)- if (model && model !== state.model) {- state.model = model- state.observedAt = Date.now()- }- } else if (session.engine === 'commandcode') {- // `/model` reprints the session banner (`# models: kimi-k2.6 · taste-1`) with the new model. The- // transcript would say the same thing, but only after the NEXT turn runs — too late to confirm a- // switch, and long enough for the chip to look stuck.- const model = commandcodeBannerModel(paneText)- if (model && model !== state.model) {- state.model = model- state.observedAt = Date.now()- // Effort is stored per model in the CLI's global config, so the level we hold belongs to the old- // one. Re-read rather than carry it across.- void this.ingestConfig(session, true).catch(() => undefined)- }- } else if (session.engine === 'opencode') {- // OpenCode names what is running in its composer footer- // (`Build · MiniMax M3 (vibe) Vibe Gateway · high`). Prefer the catalog entry it resolves to,- // because that id is also what a SWITCH is addressed to — the cached entries rather than a- // fresh (async) fetch, since this runs on the pane poll.- //- // Fall back to the footer's own words when the catalog does not list it. That is not a corner- // case: with no provider connected OpenCode runs a built-in free model that `opencode models`- // never prints, so insisting on a catalog match left the chips blank on a freshly opened agent- // — showing nothing about a model the terminal was naming two lines below.- const footer = parseOpencodeFooter(paneText)- const id = opencodeFooterModelId(paneText, this.opencodeCatalogCache?.entries ?? [])- const model = id ?? footer?.target ?? null- if (model) {- // 'auto' remains the default: early builds had no reasoning axis at all, and inventing a- // level for them would put a wrong value on the chip instead of an empty one.- const effort = footer?.effort ?? 'auto'- state.model = model- state.effort = effort- state.observedAt = Date.now()- this.confirmObserved(session.sessionId, model, effort)- }- } else if (session.engine === 'kilo') {- // Kilo names the model in its composer footer too, but the line is shaped differently enough that- // its resolver had to be rewritten rather than renamed — see engines/kilo/runtimeProfile.ts.- const id = kiloFooterModelId(paneText, this.kiloCatalogCache?.entries ?? [])- if (id) {- state.model = id- state.effort = 'auto'- state.observedAt = Date.now()- this.confirmObserved(session.sessionId, id, 'auto')- }- } else if (session.engine === 'pi') {- // Pi puts both axes in one footer cell: `minimax/minimax-m3 • high`.- const footer = parsePiFooterProfile(paneText)- if (footer) {- state.model = footer.model- state.effort = footer.effort- state.observedAt = Date.now()- this.confirmObserved(session.sessionId, footer.model, footer.effort)- }- } else if (session.engine === 'grok') {- const footer = parseGrokFooterProfile(paneText)- if (footer) {- state.model = footer.model- state.effort = footer.effort- state.observedAt = Date.now()- }- } else if (session.engine === 'agy') {- // agy's transcript never names the model, so the pane footer is the only continuous source; the- // hook payload's `modelName` seeds it at session start.- const footer = parseAgyFooterProfile(paneText)- if (footer) {- state.model = footer.model- state.effort = footer.effort- state.observedAt = Date.now()- }- } else {- const banner = !state.model ? claudeStartupBanner(paneText) : null- if (banner) {- state.model = banner.model- if (banner.effort) state.effort = banner.effort- state.observedAt = Date.now()- }- const header = /(Fable|Opus|Sonnet|Haiku)\s+(\d+(?:\.\d+)*)(\s+\(1M context\))?\s+with\s+(low|medium|high|xhigh|max|ultracode)\s+effort/gi- const matches = [...paneText.matchAll(header)]- const latest = matches[matches.length - 1]- if (latest) {- state.model = `claude-${latest[1].toLowerCase()}-${latest[2].replace(/\./g, '-')}${latest[3] ? '[1m]' : ''}`- state.effort = latest[4].toLowerCase()- state.observedAt = Date.now()- }- const footer = paneText.split('\n').slice(-8).join('\n')- if (/─+\s*ultracode\s*─+/i.test(footer)) {- state.effort = 'ultracode'- state.observedAt = Date.now()- }- if (/\bplan mode on\b/i.test(currentUi)) state.mode = 'plan'- else if (/\b(?:auto|default) mode on\b/i.test(currentUi)) state.mode = 'default'- }- const after = this.selectedModel(session)- this.wake(session.sessionId)- if (!silent && this.suppressNotifications === 0 && before !== after && !this.controls.has(session.sessionId)) this.scheduleChanged(session.sessionId)- return before !== after- }-- getState(sessionId: string): RuntimeState {- return { ...this.state(sessionId) }- }-- async withoutChangeEvents<T>(operation: () => Promise<T>): Promise<T> {- this.suppressNotifications++- try { return await operation() } finally { this.suppressNotifications-- }- }-- selectedModel(session: RegisteredSession): string | null {- if (this.unbound(session.sessionId)) return null- const state = this.states.get(session.sessionId)- if (!state?.model) return null- const model = session.engine === 'claude' ? claudeAliasForModel(state.model) ?? state.model : state.model- const effort = state.effort ?? (session.engine === 'claude' && claudeEfforts(model).length === 0 ? 'auto' : null)- if (!effort) return null- return encodeRuntimeProfile({- sessionId: session.agentId,- engine: session.engine,- model,- effort,- })- }-- beginControl(session: RegisteredSession, target: RuntimeProfile): boolean {- if (this.controls.has(session.sessionId)) return false- const before = this.selectedModel(session)- const current = parseRuntimeProfile(before)- this.controls.set(session.sessionId, {- target,- before,- modelConfirmed: current?.model === target.model,- effortConfirmed: current?.effort === target.effort,- })- return true- }-- cancelControl(sessionId: string): void {- const control = this.controls.get(sessionId)- this.controls.delete(sessionId)- this.wake(sessionId)- if (control) this.scheduleChanged(sessionId)- }-- finishControl(session: RegisteredSession): void {- const control = this.controls.get(session.sessionId)- this.controls.delete(session.sessionId)- this.wake(session.sessionId)- this.scheduleChanged(session.sessionId)- }-- confirmEffort(sessionId: string, effort: string): void {- if (!EFFORTS.has(effort)) return- const state = this.state(sessionId)- state.effort = effort- state.observedAt = Date.now()- const control = this.controls.get(sessionId)- if (control) control.effortConfirmed = control.target.effort === effort- this.wake(sessionId)- }-- confirmControlProfile(target: RuntimeProfile): void {- const state = this.state(target.sessionId)- state.model = target.model- state.effort = target.effort- state.observedAt = Date.now()- const control = this.controls.get(target.sessionId)- if (control?.target.id === target.id) {- control.modelConfirmed = true- control.effortConfirmed = true- }- this.wake(target.sessionId)- }-- waitForModel(sessionId: string, timeoutMs: number): Promise<boolean> {- return this.waitFor(sessionId, () => this.controls.get(sessionId)?.modelConfirmed === true, timeoutMs)- }-- waitForProfile(sessionId: string, timeoutMs: number): Promise<boolean> {- return this.waitFor(sessionId, () => {- const control = this.controls.get(sessionId)- return control?.modelConfirmed === true && control.effortConfirmed === true- }, timeoutMs)- }-- forget(sessionId: string): void {- this.states.delete(sessionId)- this.controls.delete(sessionId)- const timer = this.changeTimers.get(sessionId)- if (timer) clearTimeout(timer)- this.changeTimers.delete(sessionId)- this.cursorTargets.delete(sessionId)- for (const waiter of this.waiters.get(sessionId) ?? []) {- clearTimeout(waiter.timer)- waiter.resolve(false)- }- this.waiters.delete(sessionId)- }-- async modelsForSessions(sessions: RegisteredSession[]): Promise<RuntimeModelOption[]> {- const groups = await Promise.all(sessions.map((session) => this.modelsForSession(session)))- return groups.flat()- }-- /**- * Only Claude and Codex can be SWITCHED from the device (owner, 2026-07-31). Every other engine is- * view-only: its chip still names the model and effort it is running — that comes from the ingest paths,- * not from here — but it offers nothing to pick.- *- * An empty catalogue is the whole mechanism: the device's picker returns to the projects screen when the- * list comes back empty, so this policy lives in one place and needs no firmware change to revise.- * The per-engine builders (cursor/opencode/pi/hermes/commandcode/devin) are kept, unused by this path,- * because the catalogues they fetch are what the ingest paths resolve pane footers against.- */- async modelsForSession(session: RegisteredSession): Promise<RuntimeModelOption[]> {- // Display-only through a gateway: the empty catalogue IS the mechanism (see the note above), so web- // renders a static chip and the device picker closes instead of offering a list we cannot enumerate.- if (session.gateway) return []- if (session.engine === 'codex') return this.codexModels(session)- if (session.engine === 'claude') return this.claudeModels(session)- return []- }-- cursorTarget(sessionId: string, profileId: string): CursorModelTarget | null {- return this.cursorTargets.get(sessionId)?.get(profileId) ?? null- }-- /** The `/model` argument for a devin profile id — devin's ids do not follow from the model key. */- devinTarget(sessionId: string, profileId: string): DevinModelTarget | null {- return this.devinTargets.get(sessionId)?.get(profileId) ?? null- }-- /** Mark an in-flight control confirmed once the pane shows the profile it asked for. */- private confirmObserved(sessionId: string, model: string, effort: string): void {- const control = this.controls.get(sessionId)- if (!control || control.target.model !== model || control.target.effort !== effort) return- control.modelConfirmed = true- control.effortConfirmed = true- }-- /** Resolve devin's footer display name (`SWE-1.6 Slow`) back to the catalog row it names. */- private devinModelKeyForLabel(sessionId: string, label: string): DevinModelTarget | null {- // Resolve against the CATALOG, not the per-session id map. That map is only built when something opens- // the model picker, so a session nobody had picked on could not read its own footer and the chip stayed- // blank. The catalog is the same data minus the per-session ids, and ingestConfig warms it on attach.- // The session map stays first: its rows are the ones the picker will offer.- const targets = this.devinTargets.get(sessionId)- const pool: Iterable<DevinModelTarget> = targets?.size- ? targets.values()- : this.devinCatalogCache?.entries ?? []- const wanted = label.trim().toLowerCase()- for (const target of pool) {- // A row whose id carries no effort keeps the effort word in its label ("GLM-5.2 High"), so an exact- // label match is what identifies it; anything looser would tie the footer to the wrong sibling.- if (target.label.toLowerCase() === wanted) return target- if (target.effort !== 'auto' && `${target.label} ${effortLabel(target.effort)}`.toLowerCase() === wanted) {- return target- }- }- return null- }-- /**- * An agent that has not bound an engine session yet. Its `sessionId` is the EMPTY STRING, which is- * not an identity — every unbound agent would share one entry in a map keyed on it, across engines.- *- * That is not hypothetical. A claude agent ten seconds old was retargeted onto a grid, and the- * "what model was it on?" read that the retarget keeps — so a later move home can restore it —- * answered `opencode/big-pickle`: an OpenCode agent sitting at `''` had written its footer there- * first. The claude pane came home with `ANTHROPIC_MODEL=opencode/big-pickle` and Claude Code- * answered "There's an issue with the selected model (opencode/big-pickle). It may not exist".- *- * So `''` gets no entry in this conversation cache, and writes land in a throwaway rather than a- * bucket the next agent will read. Transcript state is re-read once a real conversation binds.- */- private unbound(sessionId: string): boolean {- return !sessionId- }-- private state(sessionId: string): RuntimeState {- if (this.unbound(sessionId)) return blankState()- let state = this.states.get(sessionId)- if (!state) {- state = blankState()- this.states.set(sessionId, state)- }- return state- }-- private ingestCodex(session: RegisteredSession, raw: Record<string, unknown>, state = this.state(session.sessionId)): void {- const payload = record(raw.payload)- const cliVersion = raw.type === 'session_meta' ? text(payload?.cli_version) : ''- if (parseVersion(cliVersion)) {- session.cliVersion = cliVersion- state.cliVersion = cliVersion- }- let source: Record<string, unknown> | null = null- if (raw.type === 'event_msg' && payload?.type === 'thread_settings_applied') source = record(payload.thread_settings)- else if (raw.type === 'turn_context') source = payload- if (!source) return- const model = text(source.model)- const effort = text(source.reasoning_effort) || text(source.effort)- const collaboration = record(source.collaboration_mode)- const mode = text(collaboration?.mode)- if (model) state.model = model- if (CODEX_EFFORTS.has(effort.toLowerCase())) state.effort = effort.toLowerCase()- if (mode === 'plan' || mode === 'default') state.mode = mode- if (model || effort || mode) state.observedAt = Date.now()- const control = this.controls.get(session.sessionId)- if (control && state.model === control.target.model) {- control.modelConfirmed = true- if (control.target.effort === 'auto' || state.effort === control.target.effort) control.effortConfirmed = true- }- }-- private ingestCursor(session: RegisteredSession, raw: Record<string, unknown>): void {- const state = this.state(session.sessionId)- const version = text(raw.version) || text(raw.cursor_version)- if (version) {- session.cliVersion = version- state.cliVersion = version- }- const model = text(raw.model)- if (model) {- state.model = model- // Default the effort to 'auto' when we do not have one yet. selectedModel() returns null unless BOTH- // axes are known, so without this a Cursor session whose model we DO know shows nothing at all on- // the device — the model is thrown away because the effort is missing.- //- // Cursor reports its model in the transcript but its reasoning level only in the pane footer, so- // the effort arrives later (ingestPane) or not at all for a model that has no reasoning levels.- // 'auto' is not a guess about Cursor's behaviour: it is exactly how the device renders "not- // specified", and the pane path overwrites it with the real value the moment one is read.- state.effort ??= 'auto'- state.observedAt = Date.now()- }- }-- private ingestClaude(session: RegisteredSession, raw: Record<string, unknown>, state = this.state(session.sessionId)): void {- const cliVersion = text(raw.version)- if (parseVersion(cliVersion)) {- session.cliVersion = cliVersion- state.cliVersion = cliVersion- }- const message = record(raw.message)- const assistantModel = raw.type === 'assistant' ? text(message?.model) : ''- // Claude uses this marker for local errors such as exhausted quota.- // It is not a model change; keep the last real observation.- if (assistantModel && assistantModel !== '<synthetic>') {- state.model = assistantModel- state.observedAt = Date.now()- }- const content = `${flattenContent(message?.content)}\n${flattenContent(raw.content)}`- const control = this.controls.get(session.sessionId)- const modelMatch = /Set model to\s+(.+?)(?:\n|$)/i.exec(content)- if (modelMatch) {- const nextModel = control?.target.model ?? normalizeClaudeDisplay(modelMatch[1]) ?? state.model- state.model = nextModel- if (!control && nextModel && state.effort && !claudeEfforts(nextModel, session.cliVersion).includes(state.effort)) {- state.effort = 'auto'- }- state.observedAt = Date.now()- if (control) control.modelConfirmed = true- }- const effortMatch = /Set effort level to\s+(low|medium|high|xhigh|max|ultracode)/i.exec(content)- const effortAuto = confirmsClaudeAutoEffort(content)- if (effortMatch || effortAuto) {- state.effort = effortMatch?.[1].toLowerCase() ?? 'auto'- state.observedAt = Date.now()- if (control) control.effortConfirmed = control.target.effort === 'auto' || state.effort === control.target.effort- }- }-- private ingestGrok(session: RegisteredSession, raw: Record<string, unknown>): void {- const params = record(raw.params)- const update = record(params?.update)- const meta = record(update?._meta)- const model = text(meta?.modelId)- if (!model) return- const state = this.state(session.sessionId)- state.model = model- state.observedAt = Date.now()- }-- private async claudeModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {- const output: RuntimeModelOption[] = []- const seen = new Set<string>()- const allowed = await claudeAvailableModels(session)- for (const model of CLAUDE_ALIASES) {- if (model === 'fable' && !versionAtLeast(session.cliVersion, [2, 1, 170])) continue- if (!availableModelMatches(model, allowed)) continue- addOption(output, seen, session, model, 'auto')- for (const effort of claudeEfforts(model, session.cliVersion)) addOption(output, seen, session, model, effort)- }- const state = this.states.get(session.sessionId)- if (state?.model) {- const model = claudeAliasForModel(state.model) ?? state.model- addOption(output, seen, session, model, 'auto')- for (const effort of claudeEfforts(model, session.cliVersion)) addOption(output, seen, session, model, effort)- if (state.effort) addOption(output, seen, session, model, state.effort)- }- return output- }-- /**- * The catalog Codex builds its own `/model` picker from, read fresh: what the controller matches the- * picker's rows against (engines/codex/modelPicker.ts). Empty when there is no cache to read.- */- async codexCatalog(session: RegisteredSession): Promise<CodexCatalogModel[]> {- return parseCodexCatalog(await this.readCodexCache(session))- }-- /**- * Found by QA on a quiet machine: the picker read the daemon's login instead of the agent's.- * Use the bound conversation's home, or the launch shell's, with an explicit Codex profile first.- */- private async readCodexCache(session: RegisteredSession): Promise<CodexCache> {- try {- const cache: unknown = JSON.parse(await readFile(join(sessionCodexHome(session), 'models_cache.json'), 'utf8'))- return record(cache) ?? {}- } catch {- return {}- }- }-- private async codexModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {- const output: RuntimeModelOption[] = []- const seen = new Set<string>()- const cache = await this.readCodexCache(session)- const catalog = parseCodexCatalog(cache)- for (const item of Array.isArray(cache.models) ? cache.models : []) {- const model = text(item.slug)- if (!model || item.visibility === 'hide') continue- const label = text(item.display_name) || runtimeModelLabel(model)- addOption(output, seen, session, model, 'auto', label)- const listed = catalog.find((entry) => entry.slug === model)?.efforts ?? []- for (const effort of listed) {- if (effort !== 'auto' && codexEffortAllowed(model, effort, listed)) addOption(output, seen, session, model, effort, label)- }- }- const state = this.states.get(session.sessionId)- if (state?.model) {- addOption(output, seen, session, state.model, 'auto')- const listed = catalog.find((entry) => entry.slug === state.model)?.efforts ?? null- if (state.effort && codexEffortAllowed(state.model, state.effort, listed)) {- addOption(output, seen, session, state.model, state.effort)- }- }- return output- }-- /** Command Code stamps the model on every assistant line as the full gateway id- * ("deepseek/deepseek-v4-flash"). Store the short name so it matches the catalogue and the chip label.- * `raw.version` here is the transcript SCHEMA version (3), not a CLI version — never read it as one. */- private ingestCommandcode(session: RegisteredSession, raw: Record<string, unknown>): void {- const model = text(raw.model)- if (!model) return- const state = this.state(session.sessionId)- state.model = shortCommandcodeModel(model)- // Effort is NOT touched here: it comes from the CLI config (ingestConfig), and stamping 'auto' on every- // assistant line would wipe a configured level a second after it was read.- state.observedAt = Date.now()- }-- private async cursorModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {- const key = `${session.cliVersion ?? 'unknown'}\0${process.env.HOME ?? ''}`- let entries = this.cursorCatalogCache?.key === key && this.cursorCatalogCache.expiresAt > Date.now()- ? this.cursorCatalogCache.entries- : null- if (!entries) {- try {- const result = await execFileAsync('agent', ['models'], {- env: process.env,- timeout: 5_000,- maxBuffer: 1024 * 1024,- })- entries = parseCursorModelsOutput(result.stdout)- this.cursorCatalogCache = { key, entries, expiresAt: Date.now() + CURSOR_CATALOG_TTL_MS }- } catch (err) {- console.warn('[runtime-profile] Cursor model catalog failed:', err instanceof Error ? err.message : err)- entries = []- }- }-- const output: RuntimeModelOption[] = []- const previousTargets = this.cursorTargets.get(session.sessionId) ?? new Map<string, CursorModelTarget>()- const targets = new Map<string, CursorModelTarget>()- const seen = new Set<string>()- for (const entry of entries) {- if (!CURSOR_EFFORTS.has(entry.effort)) continue- const id = encodeRuntimeProfile({- sessionId: session.agentId,- engine: 'cursor',- model: entry.target.modelKey,- effort: entry.effort,- })- if (seen.has(id)) continue- seen.add(id)- targets.set(id, entry.target)- output.push({ id, displayName: `${entry.modelLabel} / ${effortLabel(entry.effort)}` })- }- const state = this.states.get(session.sessionId)- const current = state?.model && state.effort- ? encodeRuntimeProfile({- sessionId: session.agentId,- engine: 'cursor',- model: state.model,- effort: state.effort,- })- : null- const observed = current ? previousTargets.get(current) : null- if (observed) {- const familyEfforts = [...new Set(entries- .filter((entry) => entry.target.familyLabel.toLowerCase() === observed.familyLabel.toLowerCase())- .map((entry) => entry.effort)- .filter((effort) => effort !== 'auto'))]- const efforts = familyEfforts.length ? familyEfforts : [state!.effort!]- for (const effort of efforts) {- const id = encodeRuntimeProfile({- sessionId: session.agentId,- engine: 'cursor',- model: observed.modelKey,- effort,- })- if (seen.has(id)) continue- seen.add(id)- targets.set(id, { ...observed, reasoning: effort, footerEffort: effort })- const label = [- observed.familyLabel,- observed.context ? `(${observed.context.toUpperCase()})` : '',- observed.thinking ? 'Thinking' : '',- observed.fast ? 'Fast' : '',- ].filter(Boolean).join(' ')- output.push({ id, displayName: `${label} / ${effortLabel(effort)}` })- }- }- this.cursorTargets.set(session.sessionId, targets)- return output- }-- /**- * Devin's catalog comes from `devin models list` on stdout — no picker to scrape. It is big (166 rows- * across 72 models on this account), so it is trimmed to CATALOG_LIMIT, and the model the session is- * ACTUALLY running is pinned to the front so trimming can never hide it.- */- private async devinModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {- const entries = await this.devinCatalog()- const targets = new Map<string, DevinModelTarget>()- const state = this.states.get(session.sessionId)- // Keep every row of the running model together with it, so its effort list stays complete.- const ordered = state?.model- ? [...entries].sort((a, b) => Number(b.modelKey === state.model) - Number(a.modelKey === state.model))- : entries-- const output: RuntimeModelOption[] = []- const seen = new Set<string>()- for (const entry of ordered) {- if (output.length >= CATALOG_LIMIT) break- if (!DEVIN_EFFORTS.has(entry.effort)) continue- const id = encodeRuntimeProfile({- sessionId: session.agentId,- engine: 'devin',- model: entry.modelKey,- effort: entry.effort,- })- if (seen.has(id)) continue- seen.add(id)- targets.set(id, entry)- output.push({ id, displayName: `${entry.label} / ${effortLabel(entry.effort)}` })- }- this.devinTargets.set(session.sessionId, targets)- return output- }-- private async devinCatalog(): Promise<DevinModelTarget[]> {- const key = env.DEVIN_HOME- if (this.devinCatalogCache?.key === key && this.devinCatalogCache.expiresAt > Date.now()) {- return this.devinCatalogCache.entries- }- let entries: DevinModelTarget[] = []- try {- const result = await execFileAsync('devin', ['models', 'list'], {- env: process.env,- timeout: 10_000,- maxBuffer: 1024 * 1024,- })- entries = parseDevinModelsOutput(result.stdout)- } catch (err) {- console.warn('[runtime-profile] Devin model catalog failed:', err instanceof Error ? err.message : err)- }- this.devinCatalogCache = { key, entries, expiresAt: Date.now() + CATALOG_TTL_MS }- return entries- }-- /**- * Pi lists models on stdout too, and its `thinking` column says which of them accept a reasoning depth —- * so effort rows are attached per model instead of assumed. A model that is configured but absent from- * the table (the state fallback) still gets its own row so the chip never goes blank.- */- private async piModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {- const entries = await this.piCatalog()- const output: RuntimeModelOption[] = []- const seen = new Set<string>()- for (const entry of entries) {- addOption(output, seen, session, entry.model, 'auto', entry.model)- if (!entry.thinking) continue- for (const level of PI_THINKING_LEVELS) addOption(output, seen, session, entry.model, level, entry.model)- }- const state = this.states.get(session.sessionId)- if (entries.length && state?.model) {- addOption(output, seen, session, state.model, 'auto', state.model)- if (state.effort && PI_EFFORTS.has(state.effort)) {- addOption(output, seen, session, state.model, state.effort, state.model)- }- }- return output- }-- /** The picker page + row a hermes profile id points at. */- hermesTarget(sessionId: string, profileId: string): HermesModelTarget | null {- return this.hermesTargets.get(sessionId)?.get(profileId) ?? null- }-- /**- * Hermes offers MODELS only. Its reasoning effort lives in `agent.reasoning_effort` in config.yaml with- * no in-session command to change it (`/config` only prints), and a running session does not re-read the- * file — so an effort row would be a control that silently does nothing. The level is still OBSERVED, so- * the chip names it truthfully; it just cannot be picked.- */- private async hermesModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {- const entries = await this.hermesCatalog(session.hermesHome || env.HERMES_HOME)- const state = this.states.get(session.sessionId)- const targets = new Map<string, HermesModelTarget>()- const output: RuntimeModelOption[] = []- const seen = new Set<string>()- const effort = state?.effort && HERMES_EFFORTS.has(state.effort) ? state.effort : 'auto'- const add = (entry: HermesModelTarget): void => {- const short = entry.id.slice(entry.id.lastIndexOf('/') + 1)- const id = encodeRuntimeProfile({- sessionId: session.agentId, engine: 'hermes', model: short, effort,- })- if (seen.has(id)) return- seen.add(id)- targets.set(id, entry)- output.push({ id, displayName: runtimeModelLabel(short) })- }- for (const entry of entries) add(entry)- // The provider in use is often absent from the picker cache (a `custom` gateway is its own one-model- // page), so the configured model is always offered — otherwise the running model is missing from its- // own list.- if (state?.model && !seen.size) add({ id: state.model, provider: '' })- else if (state?.model && ![...targets.values()].some((t) => t.id.endsWith(state.model!))) {- add({ id: state.model, provider: '' })- }- this.hermesTargets.set(session.sessionId, targets)- return output- }-- private async hermesCatalog(home = env.HERMES_HOME): Promise<HermesModelTarget[]> {- // Keyed by home, and now actually asked per home: a profile has its own providers, so the cache- // key was already right and only the path it read was not.- const cached = this.hermesCatalogCache.get(home)- if (cached && cached.expiresAt > Date.now()) return cached.entries- const cache = await readJson(join(home, 'provider_models_cache.json'))- const entries = parseHermesModelsCache(cache)- this.hermesCatalogCache.set(home, { entries, expiresAt: Date.now() + CATALOG_TTL_MS })- return entries- }-- /** The full `/model` argument for a Command Code profile id — the profile itself holds the short name. */- commandcodeTarget(sessionId: string, profileId: string): CommandcodeModelTarget | null {- return this.commandcodeTargets.get(sessionId)?.get(profileId) ?? null- }-- /**- * Command Code's catalog comes from `--list-models`. Effort rows are attached to every model because the- * CLI does not publish which models take one; an unsupported pick is refused in words at apply time- * (see COMMANDCODE_EFFORT_LEVELS).- */- private async commandcodeModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {- const entries = await this.commandcodeCatalog()- const targets = new Map<string, CommandcodeModelTarget>()- const output: RuntimeModelOption[] = []- const seen = new Set<string>()- const add = (entry: CommandcodeModelTarget, effort: string): void => {- const id = encodeRuntimeProfile({- sessionId: session.agentId, engine: 'commandcode', model: entry.shortId, effort,- })- if (seen.has(id)) return- seen.add(id)- targets.set(id, entry)- output.push({ id, displayName: `${runtimeModelLabel(entry.shortId)} / ${effortLabel(effort)}` })- }- for (const entry of entries) {- add(entry, 'auto')- for (const level of COMMANDCODE_EFFORT_LEVELS) add(entry, level)- }- const state = this.states.get(session.sessionId)- // `entries.length` guards the fallback: a model row is worth adding when the catalogue is readable but- // does not list what the session runs (a pinned build, a just-removed model). When the catalogue could- // not be read at all, one lone row is a picker that cannot pick anything — better to offer none.- if (entries.length && state?.model && !entries.some((entry) => entry.shortId === state.model)) {- const own: CommandcodeModelTarget = { id: state.model, shortId: state.model, section: '', isDefault: false }- add(own, 'auto')- if (state.effort && COMMANDCODE_EFFORTS.has(state.effort)) add(own, state.effort)- }- this.commandcodeTargets.set(session.sessionId, targets)- return output- }-- private async commandcodeCatalog(): Promise<CommandcodeModelTarget[]> {- const key = env.COMMANDCODE_HOME- if (this.commandcodeCatalogCache?.key === key && this.commandcodeCatalogCache.expiresAt > Date.now()) {- return this.commandcodeCatalogCache.entries- }- let entries: CommandcodeModelTarget[] = []- try {- const result = await execFileAsync('commandcode', ['--list-models'], {- env: process.env, timeout: 15_000, maxBuffer: 1024 * 1024,- })- entries = parseCommandcodeModelsOutput(result.stdout)- } catch (err) {- console.warn('[runtime-profile] Command Code model catalog failed:', err instanceof Error ? err.message : err)- }- this.commandcodeCatalogCache = { key, entries, expiresAt: Date.now() + CATALOG_TTL_MS }- return entries- }-- /** OpenCode has no effort axis, so every model is one `auto` row and the label carries no effort. */- private async opencodeModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {- const entries = await this.opencodeCatalog()- const output: RuntimeModelOption[] = []- const seen = new Set<string>()- for (const entry of entries) {- const id = encodeRuntimeProfile({- sessionId: session.agentId, engine: 'opencode', model: entry.id, effort: 'auto',- })- if (seen.has(id)) continue- seen.add(id)- output.push({ id, displayName: entry.id })- }- const state = this.states.get(session.sessionId)- // See commandcodeModels: only worth a row when the catalogue itself came back.- if (entries.length && state?.model && !entries.some((entry) => entry.id === state.model)) {- const id = encodeRuntimeProfile({- sessionId: session.agentId, engine: 'opencode', model: state.model, effort: 'auto',- })- if (!seen.has(id)) output.push({ id, displayName: state.model })- }- return output- }-- async opencodeCatalog(): Promise<OpencodeModelTarget[]> {- const key = env.OPENCODE_DATA_DIR- if (this.opencodeCatalogCache?.key === key && this.opencodeCatalogCache.expiresAt > Date.now()) {- return this.opencodeCatalogCache.entries- }- let entries: OpencodeModelTarget[] = []- try {- const result = await execFileAsync(opencodeBin(), ['models'], {- env: process.env, timeout: 10_000, maxBuffer: 1024 * 1024,- })- entries = parseOpencodeModelsOutput(result.stdout)- } catch (err) {- console.warn('[runtime-profile] OpenCode model catalog failed:', err instanceof Error ? err.message : err)- }- this.opencodeCatalogCache = { key, entries, expiresAt: Date.now() + CATALOG_TTL_MS }- return entries- }-- /** Kilo has no effort axis either, so every model is one `auto` row. */- private async kiloModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {- const entries = await this.kiloCatalog()- const output: RuntimeModelOption[] = []- const seen = new Set<string>()- for (const entry of entries) {- const id = encodeRuntimeProfile({- sessionId: session.agentId, engine: 'kilo', model: entry.id, effort: 'auto',- })- if (seen.has(id)) continue- seen.add(id)- output.push({ id, displayName: entry.id })- }- return output- }-- async kiloCatalog(): Promise<KiloModelTarget[]> {- const key = env.KILO_DATA_DIR- if (this.kiloCatalogCache?.key === key && this.kiloCatalogCache.expiresAt > Date.now()) {- return this.kiloCatalogCache.entries- }- let entries: KiloModelTarget[] = []- try {- // Measured: `kilo models` answers WITHOUT the user being logged in (unlike `kilo profile`), and- // prints 299 ids on this machine — so an empty catalog here means the binary is missing, not that- // the account is signed out.- const result = await execFileAsync(env.KILO_PATH || 'kilo', ['models'], {- env: process.env, timeout: 10_000, maxBuffer: 1024 * 1024,- })- entries = parseKiloModelsOutput(result.stdout)- } catch (err) {- console.warn('[runtime-profile] Kilo model catalog failed:', err instanceof Error ? err.message : err)- }- this.kiloCatalogCache = { key, entries, expiresAt: Date.now() + CATALOG_TTL_MS }- return entries- }-- private async piCatalog(): Promise<ReturnType<typeof parsePiModelsOutput>> {- const key = env.PI_HOME- if (this.piCatalogCache?.key === key && this.piCatalogCache.expiresAt > Date.now()) {- return this.piCatalogCache.entries- }- let entries: ReturnType<typeof parsePiModelsOutput> = []- try {- const result = await execFileAsync('pi', ['--list-models'], {- env: process.env,- timeout: 10_000,- maxBuffer: 1024 * 1024,- })- entries = parsePiModelsOutput(result.stdout)- } catch (err) {- console.warn('[runtime-profile] Pi model catalog failed:', err instanceof Error ? err.message : err)- }- this.piCatalogCache = { key, entries, expiresAt: Date.now() + CATALOG_TTL_MS }- return entries- }-- private scheduleChanged(sessionId: string): void {- const previous = this.changeTimers.get(sessionId)- if (previous) clearTimeout(previous)- this.changeTimers.set(sessionId, setTimeout(() => {- this.changeTimers.delete(sessionId)- if (!this.controls.has(sessionId)) this.onChanged?.(sessionId)- }, CHANGE_DEBOUNCE_MS))- }-- private waitFor(sessionId: string, check: () => boolean, timeoutMs: number): Promise<boolean> {- if (check()) return Promise.resolve(true)- return new Promise((resolve) => {- const waiter: StateWaiter = {- check,- resolve,- timer: setTimeout(() => {- this.waiters.get(sessionId)?.delete(waiter)- resolve(false)- }, timeoutMs),- }- const set = this.waiters.get(sessionId) ?? new Set<StateWaiter>()- set.add(waiter)- this.waiters.set(sessionId, set)- })- }-- private wake(sessionId: string): void {- const set = this.waiters.get(sessionId)- if (!set) return- for (const waiter of [...set]) {- if (!waiter.check()) continue- clearTimeout(waiter.timer)- set.delete(waiter)- waiter.resolve(true)- }- if (set.size === 0) this.waiters.delete(sessionId)- }+export class RuntimeProfileManager extends LegacyRuntimeProfileManager {+ constructor() { super(runtimeFor) }}diff --git a/cli/src/lib/runtimeProfileController.ts b/cli/src/lib/runtimeProfileController.tsindex 83259fbe8..cd56a49db 100644--- a/cli/src/lib/runtimeProfileController.ts+++ b/cli/src/lib/runtimeProfileController.ts@@ -1,3 +1,4 @@+import { parseRuntimeProfile } from './runtimeProfileWire.js'import type { RegisteredSession } from './registry.js'import { devinModelCommandResult } from '../engines/devin/runtimeProfile.js'import { countCommandcodeRefusals } from '../engines/commandcode/runtimeProfile.js'@@ -21,9 +22,6 @@ import {type CodexPicker,} from '../engines/codex/modelPicker.js'import {- codexEffortAllowed,- parseRuntimeProfile,- supportsNativeRuntimeControl,type CursorModelTarget,type RuntimeProfile,type RuntimeProfileManager,@@ -74,7 +72,13 @@ export interface PaneInspection {}export interface RuntimeProfileControllerDeps {- manager: RuntimeProfileManager+ manager: Pick<RuntimeProfileManager, 'getState' | 'selectedModel' | 'codexCatalog' | 'modelsForSession'+ | 'beginControl' | 'finishControl' | 'cancelControl' | 'confirmEffort' | 'waitForProfile' | 'waitForModel'+ | 'devinTarget' | 'opencodeCatalog' | 'commandcodeTarget' | 'ingestConfig' | 'hermesTarget' | 'cursorTarget' | 'confirmControlProfile'> & {+ supportsControl(session: RegisteredSession): boolean | Promise<boolean>+ effortAllowed(session: RegisteredSession, model: string, effort: string, listed: readonly string[] | null): boolean | Promise<boolean>+ ingestPane(session: RegisteredSession, text: string, silent?: boolean): boolean | Promise<boolean>+ }getSession: (sessionId: string) => RegisteredSession | undefinedvalidateRuntime: (session: RegisteredSession) => Promise<boolean>capture: (terminalTarget: string, historyLines?: number) => Promise<string | null>@@ -721,7 +725,7 @@ export class RuntimeProfileController {}const current = parseRuntimeProfile(this.deps.manager.selectedModel(session))if (current?.id === target.id) return- if (!supportsNativeRuntimeControl(session)) {+ if (!await this.deps.manager.supportsControl(session)) {console.warn(`[runtime-profile] unsupported ${session.engine} CLI version ${session.cliVersion ?? 'unknown'} for ${sessionId.slice(0, 8)}`)throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')}@@ -729,7 +733,7 @@ export class RuntimeProfileController {const codexCatalog = session.engine === 'codex' ? await this.deps.manager.codexCatalog(session) : []if (session.engine === 'codex') {const listed = codexCatalog.find((entry) => entry.slug === target.model)?.efforts ?? null- if (!codexEffortAllowed(target.model, target.effort, listed)) throw new RuntimeProfileControlError('EFFORT_UNSUPPORTED')+ if (!await this.deps.manager.effortAllowed(session, target.model, target.effort, listed)) throw new RuntimeProfileControlError('EFFORT_UNSUPPORTED')}const options = await this.deps.manager.modelsForSession(session)if (!options.some((option) => option.id === target.id)) {@@ -968,8 +972,8 @@ export class RuntimeProfileController {/** Poll the pane INTO the manager until it reports the profile we asked for. */private async waitObservedProfile(session: RegisteredSession, target: RuntimeProfile): Promise<boolean> {- const confirmed = await this.waitPane(session.agentId, (value) => {- this.deps.manager.ingestPane(session, value, true)+ const confirmed = await this.waitPane(session.agentId, async (value) => {+ await this.deps.manager.ingestPane(session, value, true)return this.deps.manager.selectedModel(session) === target.id}, COMMAND_CONFIRM_MS)return !!confirmed@@ -1182,8 +1186,8 @@ export class RuntimeProfileController {/** Like waitObservedProfile, but only the model half — used where effort is applied separately. */private async waitObservedModel(session: RegisteredSession, target: RuntimeProfile): Promise<boolean> {- const confirmed = await this.waitPane(session.agentId, (value) => {- this.deps.manager.ingestPane(session, value, true)+ const confirmed = await this.waitPane(session.agentId, async (value) => {+ await this.deps.manager.ingestPane(session, value, true)return parseRuntimeProfile(this.deps.manager.selectedModel(session))?.model === target.model}, COMMAND_CONFIRM_MS)return !!confirmed@@ -1360,8 +1364,8 @@ export class RuntimeProfileController {if (!await this.deps.sendKey(session.agentId, 'Enter')) throw new RuntimeProfileControlError('TMUX_FAILED')}- const confirmed = await this.waitPane(session.agentId, (value) => {- this.deps.manager.ingestPane(session, value, true)+ const confirmed = await this.waitPane(session.agentId, async (value) => {+ await this.deps.manager.ingestPane(session, value, true)return this.deps.manager.selectedModel(session) === target.id|| this.cursorFooterMatches(value, cursorTarget, target.effort)}, COMMAND_CONFIRM_MS)@@ -1426,11 +1430,11 @@ export class RuntimeProfileController {})}- private async waitPane(terminalTarget: string, predicate: (capture: string) => boolean, timeoutMs: number): Promise<string | null> {+ private async waitPane(terminalTarget: string, predicate: (capture: string) => boolean | Promise<boolean>, timeoutMs: number): Promise<string | null> {const deadline = Date.now() + timeoutMswhile (Date.now() < deadline) {const capture = await this.deps.capture(terminalTarget, 100)- if (capture && predicate(capture)) return capture+ if (capture && await predicate(capture)) return captureawait sleep(100)}return nulldiff --git a/cli/src/lib/runtimeProfileManager.spec.ts b/cli/src/lib/runtimeProfileManager.spec.tsnew file mode 100644index 000000000..17bacbf36--- /dev/null+++ b/cli/src/lib/runtimeProfileManager.spec.ts@@ -0,0 +1,103 @@+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { env } from '../config/env.js'+import { runtime as claudeRuntime } from '../engines/claude/runtimeProfile.js'+import type { RegisteredSession } from './registry.js'+import { LegacyRuntimeProfileManager } from './runtimeProfileManager.js'+import { RuntimeProfileManager } from './runtimeProfile.js'+import { parseRuntimeProfile } from './runtimeProfileWire.js'++const fixture = (name: string): string => readFileSync(join(import.meta.dirname, '__fixtures__', name), 'utf8')+const session = (engine: RegisteredSession['engine']): RegisteredSession => ({+ agentId: 'agent', sessionId: 'conversation', engine, model: 'registered-model', cliVersion: '1.0.0',+ cwd: '/tmp', transcriptPath: '/tmp/profile-recording.jsonl',+} as RegisteredSession)+afterEach(() => { vi.restoreAllMocks(); vi.useRealTimers() })++describe('runtime profiles without the pilot implementations', () => {+ it.each([+ ['amp', 'amp-session.jsonl'], ['amp', 'amp-session-queued.jsonl'],+ ['muse', 'muse-session.jsonl'], ['copilot', 'copilot-session.jsonl'], ['agy', 'agy-session.jsonl'],+ ] as const)('preserves the registry seed when replaying the recorded %s transcript %s', (engine, file) => {+ const lines = fixture(file).trim().split('\n')+ // Audit the removed fallback against recordings, not formats inferred from Claude. None of these+ // native records contributed profile metadata through that reader; their own config/panes do.+ expect(lines.map(line => claudeRuntime.decode(JSON.parse(line))).filter(Boolean)).toEqual([])+ const manager = new LegacyRuntimeProfileManager(() => undefined)+ const agent = session(engine)+ manager.hydrate(agent, lines)+ expect(manager.getState(agent.sessionId)).toEqual({+ model: 'registered-model', effort: null, mode: 'unknown', cliVersion: '1.0.0', observedAt: null,+ })+ })++ it('keeps Pi metadata in its native footer and never treats answer text as Claude commands', () => {+ const manager = new LegacyRuntimeProfileManager(() => undefined)+ const agent = session('pi')+ // These metadata records are copied from the Pi 0.82.1 recording in pi/normalizer.spec.ts.+ const lines = [+ '{"type":"session","version":3,"id":"019fa2a5-a26d-700c-bf8c-97af19ae3d5f","timestamp":"2026-07-27T08:16:31.854Z","cwd":"/tmp/pi-probe"}',+ '{"type":"model_change","id":"45215278","parentId":null,"model":"minimax/minimax-m3"}',+ '{"type":"thinking_level_change","id":"1da16955","parentId":"45215278","level":"medium"}',+ ]+ expect(lines.map(line => claudeRuntime.decode(JSON.parse(line)))).toEqual([null, null, null])+ manager.hydrate(agent, lines)+ manager.ingestPane(agent, '0.0%/500k (auto) minimax/minimax-m3 • high', true)+ const before = manager.getState(agent.sessionId)+ expect(parseRuntimeProfile(manager.selectedModel(agent))).toMatchObject({+ engine: 'pi', model: 'minimax/minimax-m3', effort: 'high',+ })+ // An answer explaining another CLI uses ordinary text in Pi's recorded message envelope.+ expect(manager.ingest(agent, JSON.stringify({ type: 'message', message: {+ role: 'assistant', content: [{ type: 'text', text: 'Set model to Opus 5\nSet effort level to low' }],+ } }), true)).toBe(false)+ expect(manager.getState(agent.sessionId)).toEqual(before)+ })++ it.each(['amp', 'muse', 'copilot', 'terminal'] as const)('does not interpret Claude UI quoted in a %s pane', engine => {+ // Apply the same boundary in explicit inline mode. Supplying a Claude facet must not make it a+ // fallback for engines whose profile source is their own config or registration.+ const manager = new RuntimeProfileManager(), agent = session(engine)+ manager.hydrate(agent, [])+ const before = manager.getState(agent.sessionId)+ expect(manager.ingestPane(agent, 'Claude Code v2.1.212\nOpus 5 with high effort · Claude Max\nplan mode on', true)).toBe(false)+ expect(manager.getState(agent.sessionId)).toEqual(before)+ })++ it('retains the native Muse and Amp config sources without loading either pilot facet', async () => {+ const root = mkdtempSync(join(tmpdir(), 'legacy-profile-'))+ const defaults = { muse: env.MUSE_CONFIG_DIR, amp: env.AMP_STATE_DIR }+ try {+ env.MUSE_CONFIG_DIR = join(root, 'muse'); env.AMP_STATE_DIR = join(root, 'amp')+ mkdirSync(env.MUSE_CONFIG_DIR); mkdirSync(env.AMP_STATE_DIR)+ // Verified config shapes documented in each engine's runtimeProfile.ts.+ writeFileSync(join(env.MUSE_CONFIG_DIR, 'settings.json'), JSON.stringify({+ schema_version: 1, provider: 'meta', model: 'muse-spark-1.2-contributor',+ }))+ writeFileSync(join(env.AMP_STATE_DIR, 'session.json'), JSON.stringify({ agentMode: 'medium' }))+ const manager = new LegacyRuntimeProfileManager(() => undefined)+ for (const [engine, model, effort] of [+ ['muse', 'muse-spark-1.2-contributor', 'high'], ['amp', 'medium', 'auto'],+ ] as const) {+ const agent = { ...session(engine), sessionId: engine }+ await manager.ingestConfig(agent, true)+ expect(parseRuntimeProfile(manager.selectedModel(agent))).toMatchObject({ engine, model, effort })+ }+ } finally {+ env.MUSE_CONFIG_DIR = defaults.muse; env.AMP_STATE_DIR = defaults.amp+ rmSync(root, { recursive: true, force: true })+ }+ })++ it('still reads the captured agy footer and the registry-supplied CLI version', () => {+ const manager = new LegacyRuntimeProfileManager(() => undefined), agent = session('agy')+ manager.hydrate(agent, [])+ manager.ingestPane(agent, fixture('permission-agy.txt'), true)+ expect(parseRuntimeProfile(manager.selectedModel(agent))).toMatchObject({+ engine: 'agy', model: 'gemini-3.7-flash-high', effort: 'high',+ })+ expect(manager.getState(agent.sessionId).cliVersion).toBe('1.0.0')+ })+})diff --git a/cli/src/lib/runtimeProfileManager.ts b/cli/src/lib/runtimeProfileManager.tsnew file mode 100644index 000000000..4067e8325--- /dev/null+++ b/cli/src/lib/runtimeProfileManager.ts@@ -0,0 +1,1335 @@+import { parseRuntimeProfile } from './runtimeProfileWire.js'+export { parseRuntimeProfile } from './runtimeProfileWire.js'+import { readFile } from 'fs/promises'+import { join } from 'path'+import { execFile } from 'child_process'+import { promisify } from 'util'+import { env } from '../config/env.js'+import { parseMuseSettings } from '../engines/muse/runtimeProfile.js'+import { parseAmpSession } from '../engines/amp/runtimeProfile.js'+import type { AgentEngine } from '../engines/types.js'+import type { RegisteredSession } from './registry.js'+import {+ DEVIN_EFFORTS,+ devinFooterModel,+ parseDevinModelsOutput,+ type DevinModelTarget,+} from '../engines/devin/runtimeProfile.js'+import {+ HERMES_EFFORTS,+ hermesStatusModel,+ parseHermesConfig,+ parseHermesModelsCache,+ type HermesModelTarget,+} from '../engines/hermes/runtimeProfile.js'+import {+ COMMANDCODE_EFFORTS,+ commandcodeBannerModel,+ COMMANDCODE_EFFORT_LEVELS,+ parseCommandcodeModelsOutput,+ type CommandcodeModelTarget,+} from '../engines/commandcode/runtimeProfile.js'+import {+ opencodeFooterModelId,+ parseOpencodeFooter,+ parseOpencodeModelsOutput,+ type OpencodeModelTarget,+} from '../engines/opencode/runtimeProfile.js'+import {+ kiloFooterModelId,+ parseKiloModelsOutput,+ type KiloModelTarget,+} from '../engines/kilo/runtimeProfile.js'+import {+ PI_EFFORTS,+ PI_THINKING_LEVELS,+ parsePiFooterProfile,+ parsePiModelsOutput,+} from '../engines/pi/runtimeProfile.js'+import { parseGrokFooterProfile } from '../engines/grok/runtimeProfile.js'+import { parseAgyFooterProfile } from '../engines/agy/runtimeProfile.js'+import type { RuntimeFor } from '../engines/facets/runtime.js'+import type { RuntimeProfile, RuntimeModelOption, RuntimeState, RuntimeField, RuntimeControl, RuntimeCatalogModel } from '../engines/facets/runtime.js'+export type { RuntimeProfile, RuntimeModelOption, RuntimeState, RuntimeField } from '../engines/facets/runtime.js'+import { addOption, currentPaneUi, effortLabel, encodeRuntimeProfile, parseVersion, readJson, record, runtimeModelLabel, stripAnsi, text, transcriptFields, versionAtLeast, RUNTIME_EFFORTS } from '../engines/kit/runtime.js'+export { encodeRuntimeProfile, runtimeModelLabel } from '../engines/kit/runtime.js'++const blankState = (): RuntimeState => ({ model: null, effort: null, mode: 'unknown', cliVersion: null, observedAt: null })++/** Where a session's runtime state starts before its transcript is read. */+function freshState(session: RegisteredSession): RuntimeState {+ return {+ ...blankState(),+ // Registries written by older builds can hold a non-string model; treat it as unknown instead of+ // letting it reach claudeAliasForModel and abort startup.+ model: typeof session.model === 'string' ? session.model : null,+ cliVersion: session.cliVersion,+ }+}++export interface CursorModelTarget {+ rawId: string+ modelKey: string+ familyLabel: string+ context: string | null+ reasoning: string | null+ fast: boolean | null+ thinking: boolean | null+ /** Effort text rendered in the idle footer; null means Cursor omits its native default. */+ footerEffort?: string | null+}++interface CursorCatalogEntry {+ target: CursorModelTarget+ effort: string+ modelLabel: string+}++interface StateWaiter {+ check: () => boolean+ resolve: (matched: boolean) => void+ timer: NodeJS.Timeout+}++const CURSOR_EFFORTS = new Set(['auto', 'none', 'low', 'medium', 'high', 'xhigh', 'max'])+/** Wire parsing accepts all known effort labels; each engine owns its support policy. */+const EFFORTS = RUNTIME_EFFORTS+/**+ * Versions whose model UI was driven by hand before wiring it up. Open-ended upward: a newer CLI is+ * assumed compatible (the alternative — refusing to switch after every auto-update — is worse), but a+ * KNOWN-older one is refused rather than driven blind.+ */+const DEVIN_CONTROL_MIN_VERSION: [number, number, number] = [3000, 3, 22]+const PI_CONTROL_MIN_VERSION: [number, number, number] = [0, 82, 0]+const OPENCODE_CONTROL_MIN_VERSION: [number, number, number] = [1, 18, 7]+/**+ * 1.6.0 is the first Command Code that can be driven at all: it added `--list-models` (a catalog on+ * stdout) and made `/model <id>` and `/effort <level>` take arguments. On 1.5 and older the only route was+ * arrow-driving a 49-row picker, which is exactly what got the first attempt reverted — so older builds+ * are refused rather than driven.+ */+const COMMANDCODE_CONTROL_MIN_VERSION: [number, number, number] = [1, 6, 0]+/**+ * Hermes ships no version its hook payload exposes, and its `/model` picker has been the same two-level+ * arrow list throughout — so it is gated on the picker being recognisable rather than on a number. The+ * driver refuses to move if it cannot read the cursor (see setHermes), which is the real safety net.+ */+const HERMES_CONTROL_UNVERSIONED = true+/**+ * Cap on how many rows an engine's catalog may contribute. Devin publishes 166 across 72 families, and a+ * 49-row picker was enough to stall the device's the device UI task into a watchdog reset (see the Command Code+ * revert, 2026-07-30). The device already truncates at CATALOG_MAX/PICK_MAX, but truncation there is+ * arbitrary — bounding here keeps the rows we DO send meaningful (see devinModels).+ */+const CATALOG_LIMIT = 96+const CHANGE_DEBOUNCE_MS = 120+const CURSOR_CONTROLLED_BUILD = '2026.07.20-8cc9c0b'+const CURSOR_CATALOG_TTL_MS = 5 * 60_000+/** Shared TTL for the stdout catalogs (devin, pi) — same rationale as the cursor one. */+const CATALOG_TTL_MS = 5 * 60_000+import { opencodeBin } from './engineBin.js'++const execFileAsync = promisify(execFile)+++function cursorEffortFromId(rawId: string): { effort: string | null; modelKey: string } {+ const parts = rawId.split('-')+ let index = -1+ let width = 1+ for (let i = 2; i < parts.length; i++) {+ if (parts[i] === 'extra' && parts[i + 1] === 'high') {+ index = i+ width = 2+ i+++ } else if (['none', 'low', 'medium', 'high', 'xhigh', 'max'].includes(parts[i])) {+ index = i+ width = 1+ }+ }+ if (index < 0) return { effort: null, modelKey: rawId }+ const rawEffort = parts.slice(index, index + width).join('-')+ parts.splice(index, width)+ return {+ effort: rawEffort === 'extra-high' ? 'xhigh' : rawEffort,+ modelKey: parts.join('-'),+ }+}++function cursorEffortFromDisplay(value: string): string | null {+ const match = /\b(Extra High|None|Low|Medium|High|Max)\b/i.exec(value)+ if (!match) return null+ return match[1].toLowerCase().replace(/\s+/g, '') === 'extrahigh'+ ? 'xhigh'+ : match[1].toLowerCase()+}++function cursorDisplayParts(displayName: string): {+ familyLabel: string+ context: string | null+ fast: boolean+ thinking: boolean+} {+ let value = displayName+ .replace(/\s+\((?:current|default)(?:,\s*(?:current|default))?\)\s*$/i, '')+ .replace(/\s+\(NO ZDR\)\s*$/i, '')+ .replace(/\s*[·│]\s*\d+(?:\.\d+)?%.*$/i, '')+ .trim()+ const contextMatch = /\b(\d+(?:\.\d+)?[KM])\b/i.exec(value)+ const context = contextMatch?.[1].toLowerCase() ?? null+ const fast = /\bFast\b/i.test(value)+ const thinking = !/\bNo\s+Thinking\b/i.test(value) && /\bThinking\b/i.test(value)+ value = value+ .replace(/\b\d+(?:\.\d+)?[KM]\b/gi, '')+ .replace(/\bExtra High\b/gi, '')+ .replace(/\b(?:None|Low|Medium|High|Max)\b/gi, '')+ .replace(/\bNo\s+Thinking\b/gi, '')+ .replace(/\b(?:Fast|Thinking)\b/gi, '')+ .replace(/\s+/g, ' ')+ .trim()+ return { familyLabel: value, context, fast, thinking }+}++/** Strictly parse `agent models`; headings, tips and malformed rows are ignored. */+export function parseCursorModelsOutput(output: string): CursorCatalogEntry[] {+ const candidates: Array<CursorCatalogEntry & { explicitEffort: boolean }> = []+ for (const rawLine of output.split('\n')) {+ const match = /^([a-z0-9][a-z0-9._-]*) - (.+?)\s*$/i.exec(rawLine)+ if (!match) continue+ const rawId = match[1]+ const displayName = match[2].trim()+ const display = cursorDisplayParts(displayName)+ if (!display.familyLabel) continue+ if (rawId === 'auto') {+ candidates.push({+ target: {+ rawId,+ modelKey: rawId,+ familyLabel: 'Auto',+ context: null,+ reasoning: null,+ fast: null,+ thinking: null,+ footerEffort: 'auto',+ },+ effort: 'auto',+ modelLabel: 'Auto',+ explicitEffort: true,+ })+ continue+ }+ const parsed = cursorEffortFromId(rawId)+ const effort = parsed.effort+ const footerEffort = cursorEffortFromDisplay(displayName)+ candidates.push({+ target: {+ rawId,+ modelKey: parsed.modelKey,+ familyLabel: display.familyLabel,+ context: display.context,+ reasoning: effort,+ fast: display.fast,+ thinking: display.thinking,+ footerEffort,+ },+ effort: effort ?? 'auto',+ modelLabel: [+ display.familyLabel,+ display.context ? `(${display.context.toUpperCase()})` : '',+ display.thinking ? 'Thinking' : '',+ display.fast ? 'Fast' : '',+ ].filter(Boolean).join(' '),+ explicitEffort: effort !== null,+ })+ }++ // Some medium/default rows omit the effort segment (for example `gpt-5.3-codex`).+ // Infer medium only when explicit siblings prove that the same exact model group has efforts.+ const effortfulGroups = new Set(candidates.filter((item) => item.explicitEffort).map((item) => item.target.modelKey))+ for (const item of candidates) {+ if (item.target.rawId === 'auto' || item.effort !== 'auto' || !effortfulGroups.has(item.target.modelKey)) continue+ item.effort = 'medium'+ item.target.reasoning = 'medium'+ }+ return candidates.map(({ explicitEffort: _explicitEffort, ...item }) => item)+}++function parseCursorFooter(value: string): {+ familyLabel: string+ context: string | null+ effort: string | null+ fast: boolean+ thinking: boolean+} | null {+ const line = stripAnsi(value).trim()+ if (/^Auto(?:\s*$|\s*[·│])/i.test(line)) {+ return { familyLabel: 'Auto', context: null, effort: 'auto', fast: false, thinking: false }+ }+ const effort = cursorEffortFromDisplay(line)+ const hasUsage = /[·│]\s*\d+(?:\.\d+)?%/i.test(line)+ const hasThinkingMode = /\b(?:No\s+Thinking|Thinking)\b/i.test(line)+ if (!effort && !hasUsage && !hasThinkingMode) return null+ const parts = cursorDisplayParts(line)+ if (!parts.familyLabel || !/\d/.test(parts.familyLabel)) return null+ return {+ ...parts,+ effort,+ }+}++function cursorSyntheticTarget(+ parsed: NonNullable<ReturnType<typeof parseCursorFooter>>,+ effort: string,+): CursorModelTarget {+ if (parsed.familyLabel.toLowerCase() === 'auto' && parsed.effort === 'auto') {+ return {+ rawId: 'auto',+ modelKey: 'auto',+ familyLabel: 'Auto',+ context: null,+ reasoning: null,+ fast: null,+ thinking: null,+ footerEffort: 'auto',+ }+ }+ const family = parsed.familyLabel.toLowerCase().replace(/[^a-z0-9.]+/g, '-').replace(/^-|-$/g, '') || 'model'+ // Keep the public runtime-v1 model key compatible with every client formatter. The Cursor routing+ // details remain on CursorModelTarget (and rawId) for selection/confirmation; they do not belong in+ // the user-facing profile key as a percent-encoded "[fast=...,thinking=...]" implementation detail.+ const modelKey = [+ family,+ parsed.context?.toLowerCase() ?? '',+ parsed.thinking ? 'thinking' : '',+ parsed.fast ? 'fast' : '',+ ].filter(Boolean).join('-')+ const parameters = [+ parsed.context ? `context=${parsed.context}` : '',+ `fast=${parsed.fast}`,+ `thinking=${parsed.thinking}`,+ ].filter(Boolean).join(',')+ return {+ rawId: `cursor-${family}[${parameters},effort=${effort}]`,+ modelKey,+ familyLabel: parsed.familyLabel,+ context: parsed.context,+ reasoning: effort === 'auto' ? null : effort,+ fast: parsed.fast,+ thinking: parsed.thinking,+ footerEffort: parsed.effort,+ }+}++/** Raw file text, or '' when it cannot be read — hermes' config is YAML, not JSON. */+async function readText(file: string): Promise<string> {+ try { return await readFile(file, 'utf8') } catch { return '' }+}++/** Command Code ids are "vendor/name"; everything we store and show uses the name alone. */+function shortCommandcodeModel(id: string): string {+ return id.slice(id.lastIndexOf('/') + 1)+}++/**+ * Command Code keeps the reasoning level in its GLOBAL config, keyed by the FULL gateway id:+ * { "model": "deepseek/deepseek-v4-flash", "reasoningEffort": { "deepseek/deepseek-v4-flash": "high" } }+ * Nothing in the transcript, the pane footer or the session header carries it, so this file is the only+ * source. It is per MACHINE rather than per session: two agents on the same model necessarily read the same+ * level. Matching is done on the short name because that is what the running model is stored as.+ */+/** The configured level for `model`, or 'auto' when the model has none set. */+async function commandcodeConfiguredEffort(model: string | null): Promise<{ effort: string; defaultModel: string }> {+ const config = await readJson(join(env.COMMANDCODE_HOME, 'config.json'))+ const defaultModel = shortCommandcodeModel(text(config?.model))+ const efforts = record(config?.reasoningEffort)+ const wanted = model || defaultModel+ if (!efforts || !wanted) return { effort: 'auto', defaultModel }+ for (const [id, level] of Object.entries(efforts)) {+ if (shortCommandcodeModel(id) !== wanted) continue+ const normalized = text(level).toLowerCase()+ if (normalized && normalized !== 'default' && EFFORTS.has(normalized)) return { effort: normalized, defaultModel }+ }+ return { effort: 'auto', defaultModel }+}++/** Other engines retain their native readers. Pilot facets are injected only for inline compatibility. */+export class LegacyRuntimeProfileManager {+ constructor(private readonly runtimeFor: RuntimeFor) {}++ supportsControl(session: RegisteredSession): boolean {+ return !session.gateway && (this.runtimeFor(session.engine)?.supportsControl(session) ?? false)+ }++ effortAllowed(session: RegisteredSession, model: string, effort: string, listed: readonly string[] | null): boolean {+ return this.runtimeFor(session.engine)?.effortAllowed?.(model, effort, listed) ?? false+ }++ private readonly states = new Map<string, RuntimeState>()+ private readonly controls = new Map<string, RuntimeControl>()+ private readonly waiters = new Map<string, Set<StateWaiter>>()+ private readonly changeTimers = new Map<string, NodeJS.Timeout>()+ private readonly cursorTargets = new Map<string, Map<string, CursorModelTarget>>()+ /** profile id → the exact `/model` argument, per session (devin ids are not derivable from the key). */+ private readonly devinTargets = new Map<string, Map<string, DevinModelTarget>>()+ private devinCatalogCache: { key: string; expiresAt: number; entries: DevinModelTarget[] } | null = null+ private piCatalogCache: { key: string; expiresAt: number; entries: ReturnType<typeof parsePiModelsOutput> } | null = null+ private opencodeCatalogCache: { key: string; expiresAt: number; entries: OpencodeModelTarget[] } | null = null+ private kiloCatalogCache: { key: string; expiresAt: number; entries: KiloModelTarget[] } | null = null+ private commandcodeCatalogCache: { key: string; expiresAt: number; entries: CommandcodeModelTarget[] } | null = null+ /** profile id → the full `/model` argument (the profile carries the SHORT name the device labels by). */+ private readonly commandcodeTargets = new Map<string, Map<string, CommandcodeModelTarget>>()+ /** Per HOME, not one slot: a desk with a default-home agent and a profile agent would otherwise+ * evict each other's catalog on every menu open (`hermes -p <name>` has its own providers). */+ private hermesCatalogCache = new Map<string, { expiresAt: number; entries: HermesModelTarget[] }>()+ /** profile id → the picker page + row a hermes model sits on. */+ private readonly hermesTargets = new Map<string, Map<string, HermesModelTarget>>()+ private cursorCatalogCache: { key: string; expiresAt: number; entries: CursorCatalogEntry[] } | null = null+ private suppressNotifications = 0+ onChanged: ((sessionId: string) => void) | null = null++ hydrate(session: RegisteredSession, rawLines: string[]): void {+ if (this.unbound(session.sessionId)) return+ this.states.set(session.sessionId, freshState(session))+ for (const line of rawLines) this.ingest(session, line, true)+ }++ /**+ * `hydrate`, for a Claude Code or Codex transcript streamed in rather than loaded+ * (lib/attachTranscript.ts): records are read into a staged state, and what the session shows only+ * changes at `commit` — never an empty chip while the read runs, never a live record overwritten by+ * an older one read after it.+ */+ beginHydrate(session: RegisteredSession): { ingest(rawLine: string): void; commit(): void } {+ const staged = freshState(session)+ return {+ ingest: (rawLine) => {+ let raw: Record<string, unknown> | null+ try { raw = record(JSON.parse(rawLine)) } catch { return }+ if (!raw) return+ this.runtimeFor(session.engine)?.transcript({ session, state: staged, control: this.controls.get(session.sessionId) }, raw)+ },+ commit: () => {+ if (this.unbound(session.sessionId)) return+ this.states.set(session.sessionId, staged)+ this.wake(session.sessionId)+ },+ }+ }++ ingest(session: RegisteredSession, rawLine: string, silent = false): boolean {+ let raw: Record<string, unknown> | null+ try { raw = record(JSON.parse(rawLine)) } catch { return false }+ if (!raw) return false+ const before = this.selectedModel(session)+ const runtime = this.runtimeFor(session.engine)+ if (runtime) runtime.transcript({ session, state: this.state(session.sessionId), control: this.controls.get(session.sessionId) }, raw)+ else if (session.engine === 'cursor') this.ingestCursor(session, raw)+ else if (session.engine === 'commandcode') {+ const model = this.states.get(session.sessionId)?.model ?? null+ this.ingestCommandcode(session, raw)+ // The reasoning level is stored PER MODEL, so a model change makes the level we are holding wrong.+ // Re-read it now instead of showing the previous model's level until the next poll.+ if ((this.states.get(session.sessionId)?.model ?? null) !== model) {+ void this.ingestConfig(session, silent).catch(() => undefined)+ }+ }+ else if (session.engine === 'grok') this.ingestGrok(session, raw)+ // A different engine's answer can quote Claude commands. Only its own format may change its profile.+ const after = this.selectedModel(session)+ this.wake(session.sessionId)+ if (!silent && this.suppressNotifications === 0 && before !== after && !this.controls.has(session.sessionId)) this.scheduleChanged(session.sessionId)+ return before !== after+ }++ /**+ * Which of model, effort and mode one Claude or Codex transcript record sets — asked of the same+ * readers `ingest` uses, on a scratch state, so the two cannot disagree. An attach that reads only the+ * end of a transcript (lib/attachTranscript.ts) reaches back to the newest record that set each one.+ *+ * It can only under-report (the session's own model-switch control is not consulted), and the attach+ * replays every record from the oldest one it reached, so under-reporting costs a longer reach, never+ * a wrong value.+ */+ transcriptFields(session: RegisteredSession, rawLine: string): RuntimeField[] {+ return transcriptFields(this.runtimeFor(session.engine), session, rawLine)+ }++ async ingestConfig(session: RegisteredSession, silent = false): Promise<boolean> {+ if (session.engine === 'hermes') {+ // Both axes are scalars in config.yaml and neither is announced, so this poll is the only reader.+ const before = this.selectedModel(session)+ const state = this.state(session.sessionId)+ // This agent's OWN home: `hermes -p <name>` keeps its model and effort in the profile's+ // config.yaml, and reading the default one reported the wrong model on every profile agent.+ const parsed = parseHermesConfig(await readText(join(session.hermesHome || env.HERMES_HOME, 'config.yaml')))+ if (parsed.model) state.model = parsed.model.slice(parsed.model.lastIndexOf('/') + 1)+ state.effort = parsed.effort ?? 'auto'+ state.observedAt = Date.now()+ const after = this.selectedModel(session)+ this.wake(session.sessionId)+ if (!silent && this.suppressNotifications === 0 && before !== after && !this.controls.has(session.sessionId)) {+ this.scheduleChanged(session.sessionId)+ }+ return before !== after+ }+ if (session.engine === 'muse') {+ // Both axes are plain scalars in ~/.config/muse/settings.json (`model`, `reasoning_effort`) and+ // neither is announced anywhere, so reading the file IS the only way the chip is ever populated.+ // `reasoning_effort` is muse's own vocabulary (none|minimal|low|medium|high|xhigh|ultra); the+ // absence of the key means the CLI default, which its own --help documents as `high`.+ const before = this.selectedModel(session)+ const state = this.state(session.sessionId)+ const parsed = parseMuseSettings(await readText(join(env.MUSE_CONFIG_DIR, 'settings.json')))+ if (parsed.model) state.model = parsed.model+ state.effort = parsed.effort ?? 'auto'+ state.observedAt = Date.now()+ const after = this.selectedModel(session)+ this.wake(session.sessionId)+ if (!silent && this.suppressNotifications === 0 && before !== after && !this.controls.has(session.sessionId)) {+ this.scheduleChanged(session.sessionId)+ }+ return before !== after+ }+ if (session.engine === 'amp') {+ // Amp has no models — only agent MODES — so the mode is reported as the model and there is no+ // second axis to report. `~/.local/share/amp/session.json` is the only local place it is written.+ const before = this.selectedModel(session)+ const state = this.state(session.sessionId)+ const parsed = parseAmpSession(await readText(join(env.AMP_STATE_DIR, 'session.json')))+ if (parsed.mode) state.model = parsed.mode+ state.effort = 'auto'+ state.observedAt = Date.now()+ const after = this.selectedModel(session)+ this.wake(session.sessionId)+ if (!silent && this.suppressNotifications === 0 && before !== after && !this.controls.has(session.sessionId)) {+ this.scheduleChanged(session.sessionId)+ }+ return before !== after+ }+ if (session.engine === 'opencode') {+ // The footer only resolves against the catalog, so warm it here — `ingestPane` is synchronous and+ // cannot fetch, and without this the chip stays blank until the web happens to ask for models.+ await this.opencodeCatalog()+ return false+ }+ if (session.engine === 'kilo') {+ // Same reason as opencode: kilo names its model only in the composer footer, which resolves only+ // against the catalog, and `ingestPane` is synchronous.+ await this.kiloCatalog()+ return false+ }+ if (session.engine === 'devin') {+ // Same shape: devin's model exists only as a DISPLAY name in its pane footer, and only the catalog+ // maps that back to a model key + effort. Warm it on attach so the first pane read resolves.+ await this.devinCatalog()+ return false+ }+ if (session.engine !== 'claude' && session.engine !== 'commandcode') return false+ const before = this.selectedModel(session)+ const state = this.state(session.sessionId)+ if (session.engine === 'commandcode') {+ const config = await commandcodeConfiguredEffort(state.model)+ state.effort = config.effort+ // Before the agent has answered once there is no transcript line to read the model from; the config's+ // own model is what a fresh session starts on, so the chip names it instead of falling back to Auto.+ if (!state.model && config.defaultModel) state.model = config.defaultModel+ } else {+ state.effort = await this.runtimeFor(session.engine)?.configuredEffort?.(session) ?? state.effort+ }+ state.observedAt = Date.now()+ const after = this.selectedModel(session)+ this.wake(session.sessionId)+ if (!silent && this.suppressNotifications === 0 && before !== after && !this.controls.has(session.sessionId)) {+ this.scheduleChanged(session.sessionId)+ }+ return before !== after+ }++ ingestPane(session: RegisteredSession, paneText: string, silent = false): boolean {+ const before = this.selectedModel(session)+ const state = this.state(session.sessionId)+ paneText = stripAnsi(paneText)+ const currentUi = currentPaneUi(paneText)+ const runtime = this.runtimeFor(session.engine)+ if (runtime) {+ runtime.pane({ session, state, control: this.controls.get(session.sessionId) }, paneText)+ } else if (session.engine === 'cursor') {+ if (/Available models|Models matching|— Edit Parameters|Type to filter.*Tab to edit|Esc to go back/i.test(currentUi)) return false+ const footerLines = currentUi.split('\n')+ .filter((line) => stripAnsi(line).trim())+ .slice(-12)+ .reverse()+ const parsed = footerLines.map(parseCursorFooter).find((item) => item !== null)+ if (parsed) {+ const targets = this.cursorTargets.get(session.sessionId) ?? new Map<string, CursorModelTarget>()+ let target = [...targets.values()].find((candidate) =>+ candidate.familyLabel.toLowerCase() === parsed.familyLabel.toLowerCase()+ && (parsed.effort+ ? (candidate.reasoning ?? 'auto') === parsed.effort+ : candidate.footerEffort === null)+ && (candidate.fast ?? false) === parsed.fast+ && (candidate.thinking ?? false) === parsed.thinking+ && (!candidate.context || candidate.context === parsed.context))+ const effort = parsed.effort ?? target?.reasoning ?? 'auto'+ if (!target) {+ target = cursorSyntheticTarget(parsed, effort)+ const id = encodeRuntimeProfile({+ sessionId: session.agentId,+ engine: 'cursor',+ model: target.modelKey,+ effort,+ })+ targets.set(id, target)+ this.cursorTargets.set(session.sessionId, targets)+ }+ state.model = target.modelKey+ state.effort = effort+ state.observedAt = Date.now()+ const control = this.controls.get(session.sessionId)+ if (control && target?.modelKey === control.target.model && effort === control.target.effort) {+ control.modelConfirmed = true+ control.effortConfirmed = true+ }+ }+ if (/\bPlan\b/i.test(currentUi)) state.mode = 'plan'+ else if (/Plan, search, build anything/i.test(currentUi)) state.mode = 'default'+ } else if (session.engine === 'devin') {+ // Devin writes no transcript unless the user passes `--export`, so the footer's bottom-left cell is+ // the only per-session record of the running model. It is a DISPLAY name (`SWE-1.6 Slow`); the+ // catalog resolves it back to a model key so the chip and the picker agree.+ const label = devinFooterModel(paneText)+ const model = label ? this.devinModelKeyForLabel(session.sessionId, label) : null+ if (model) {+ state.model = model.modelKey+ state.effort = model.effort+ state.observedAt = Date.now()+ this.confirmObserved(session.sessionId, model.modelKey, model.effort)+ }+ } else if (session.engine === 'hermes') {+ // `⚕ minimax-m3 │ ctx --` — the status line is how a switch is seen immediately; config.yaml is+ // rewritten too, but the poll that reads it runs on its own schedule.+ const model = hermesStatusModel(paneText)+ if (model && model !== state.model) {+ state.model = model+ state.observedAt = Date.now()+ }+ } else if (session.engine === 'commandcode') {+ // `/model` reprints the session banner (`# models: kimi-k2.6 · taste-1`) with the new model. The+ // transcript would say the same thing, but only after the NEXT turn runs — too late to confirm a+ // switch, and long enough for the chip to look stuck.+ const model = commandcodeBannerModel(paneText)+ if (model && model !== state.model) {+ state.model = model+ state.observedAt = Date.now()+ // Effort is stored per model in the CLI's global config, so the level we hold belongs to the old+ // one. Re-read rather than carry it across.+ void this.ingestConfig(session, true).catch(() => undefined)+ }+ } else if (session.engine === 'opencode') {+ // OpenCode names what is running in its composer footer+ // (`Build · MiniMax M3 (vibe) Vibe Gateway · high`). Prefer the catalog entry it resolves to,+ // because that id is also what a SWITCH is addressed to — the cached entries rather than a+ // fresh (async) fetch, since this runs on the pane poll.+ //+ // Fall back to the footer's own words when the catalog does not list it. That is not a corner+ // case: with no provider connected OpenCode runs a built-in free model that `opencode models`+ // never prints, so insisting on a catalog match left the chips blank on a freshly opened agent+ // — showing nothing about a model the terminal was naming two lines below.+ const footer = parseOpencodeFooter(paneText)+ const id = opencodeFooterModelId(paneText, this.opencodeCatalogCache?.entries ?? [])+ const model = id ?? footer?.target ?? null+ if (model) {+ // 'auto' remains the default: early builds had no reasoning axis at all, and inventing a+ // level for them would put a wrong value on the chip instead of an empty one.+ const effort = footer?.effort ?? 'auto'+ state.model = model+ state.effort = effort+ state.observedAt = Date.now()+ this.confirmObserved(session.sessionId, model, effort)+ }+ } else if (session.engine === 'kilo') {+ // Kilo names the model in its composer footer too, but the line is shaped differently enough that+ // its resolver had to be rewritten rather than renamed — see engines/kilo/runtimeProfile.ts.+ const id = kiloFooterModelId(paneText, this.kiloCatalogCache?.entries ?? [])+ if (id) {+ state.model = id+ state.effort = 'auto'+ state.observedAt = Date.now()+ this.confirmObserved(session.sessionId, id, 'auto')+ }+ } else if (session.engine === 'pi') {+ // Pi puts both axes in one footer cell: `minimax/minimax-m3 • high`.+ const footer = parsePiFooterProfile(paneText)+ if (footer) {+ state.model = footer.model+ state.effort = footer.effort+ state.observedAt = Date.now()+ this.confirmObserved(session.sessionId, footer.model, footer.effort)+ }+ } else if (session.engine === 'grok') {+ const footer = parseGrokFooterProfile(paneText)+ if (footer) {+ state.model = footer.model+ state.effort = footer.effort+ state.observedAt = Date.now()+ }+ } else if (session.engine === 'agy') {+ // agy's transcript never names the model, so the pane footer is the only continuous source; the+ // hook payload's `modelName` seeds it at session start.+ const footer = parseAgyFooterProfile(paneText)+ if (footer) {+ state.model = footer.model+ state.effort = footer.effort+ state.observedAt = Date.now()+ }+ }+ const after = this.selectedModel(session)+ this.wake(session.sessionId)+ if (!silent && this.suppressNotifications === 0 && before !== after && !this.controls.has(session.sessionId)) this.scheduleChanged(session.sessionId)+ return before !== after+ }++ getState(sessionId: string): RuntimeState {+ return { ...this.state(sessionId) }+ }++ async withoutChangeEvents<T>(operation: () => Promise<T>): Promise<T> {+ this.suppressNotifications+++ try { return await operation() } finally { this.suppressNotifications-- }+ }++ selectedModel(session: RegisteredSession): string | null {+ if (this.unbound(session.sessionId)) return null+ const state = this.states.get(session.sessionId)+ if (!state?.model) return null+ const adapter = this.runtimeFor(session.engine)+ if (adapter) return adapter.selectedModel(session, state)+ const model = state.model+ const effort = state.effort+ if (!effort) return null+ return encodeRuntimeProfile({+ sessionId: session.agentId,+ engine: session.engine,+ model,+ effort,+ })+ }++ beginControl(session: RegisteredSession, target: RuntimeProfile): boolean {+ if (this.controls.has(session.sessionId)) return false+ const before = this.selectedModel(session)+ const current = parseRuntimeProfile(before)+ this.controls.set(session.sessionId, {+ target,+ before,+ modelConfirmed: current?.model === target.model,+ effortConfirmed: current?.effort === target.effort,+ })+ return true+ }++ cancelControl(sessionId: string): void {+ const control = this.controls.get(sessionId)+ this.controls.delete(sessionId)+ this.wake(sessionId)+ if (control) this.scheduleChanged(sessionId)+ }++ finishControl(session: RegisteredSession): void {+ const control = this.controls.get(session.sessionId)+ this.controls.delete(session.sessionId)+ this.wake(session.sessionId)+ this.scheduleChanged(session.sessionId)+ }++ confirmEffort(sessionId: string, effort: string): void {+ if (!EFFORTS.has(effort)) return+ const state = this.state(sessionId)+ state.effort = effort+ state.observedAt = Date.now()+ const control = this.controls.get(sessionId)+ if (control) control.effortConfirmed = control.target.effort === effort+ this.wake(sessionId)+ }++ confirmControlProfile(target: RuntimeProfile): void {+ const state = this.state(target.sessionId)+ state.model = target.model+ state.effort = target.effort+ state.observedAt = Date.now()+ const control = this.controls.get(target.sessionId)+ if (control?.target.id === target.id) {+ control.modelConfirmed = true+ control.effortConfirmed = true+ }+ this.wake(target.sessionId)+ }++ waitForModel(sessionId: string, timeoutMs: number): Promise<boolean> {+ return this.waitFor(sessionId, () => this.controls.get(sessionId)?.modelConfirmed === true, timeoutMs)+ }++ waitForProfile(sessionId: string, timeoutMs: number): Promise<boolean> {+ return this.waitFor(sessionId, () => {+ const control = this.controls.get(sessionId)+ return control?.modelConfirmed === true && control.effortConfirmed === true+ }, timeoutMs)+ }++ forget(sessionId: string): void {+ this.states.delete(sessionId)+ this.controls.delete(sessionId)+ const timer = this.changeTimers.get(sessionId)+ if (timer) clearTimeout(timer)+ this.changeTimers.delete(sessionId)+ this.cursorTargets.delete(sessionId)+ for (const waiter of this.waiters.get(sessionId) ?? []) {+ clearTimeout(waiter.timer)+ waiter.resolve(false)+ }+ this.waiters.delete(sessionId)+ }++ async modelsForSessions(sessions: RegisteredSession[]): Promise<RuntimeModelOption[]> {+ const groups = await Promise.all(sessions.map((session) => this.modelsForSession(session)))+ return groups.flat()+ }++ /**+ * Only Claude and Codex can be SWITCHED from the device (owner, 2026-07-31). Every other engine is+ * view-only: its chip still names the model and effort it is running — that comes from the ingest paths,+ * not from here — but it offers nothing to pick.+ *+ * An empty catalogue is the whole mechanism: the device's picker returns to the projects screen when the+ * list comes back empty, so this policy lives in one place and needs no firmware change to revise.+ * The per-engine builders (cursor/opencode/pi/hermes/commandcode/devin) are kept, unused by this path,+ * because the catalogues they fetch are what the ingest paths resolve pane footers against.+ */+ async modelsForSession(session: RegisteredSession): Promise<RuntimeModelOption[]> {+ // Display-only through a gateway: the empty catalogue IS the mechanism (see the note above), so web+ // renders a static chip and the device picker closes instead of offering a list we cannot enumerate.+ if (session.gateway) return []+ return this.runtimeFor(session.engine)?.models(session, this.states.get(session.sessionId)) ?? []+ }++ cursorTarget(sessionId: string, profileId: string): CursorModelTarget | null {+ return this.cursorTargets.get(sessionId)?.get(profileId) ?? null+ }++ /** The `/model` argument for a devin profile id — devin's ids do not follow from the model key. */+ devinTarget(sessionId: string, profileId: string): DevinModelTarget | null {+ return this.devinTargets.get(sessionId)?.get(profileId) ?? null+ }++ /** Mark an in-flight control confirmed once the pane shows the profile it asked for. */+ private confirmObserved(sessionId: string, model: string, effort: string): void {+ const control = this.controls.get(sessionId)+ if (!control || control.target.model !== model || control.target.effort !== effort) return+ control.modelConfirmed = true+ control.effortConfirmed = true+ }++ /** Resolve devin's footer display name (`SWE-1.6 Slow`) back to the catalog row it names. */+ private devinModelKeyForLabel(sessionId: string, label: string): DevinModelTarget | null {+ // Resolve against the CATALOG, not the per-session id map. That map is only built when something opens+ // the model picker, so a session nobody had picked on could not read its own footer and the chip stayed+ // blank. The catalog is the same data minus the per-session ids, and ingestConfig warms it on attach.+ // The session map stays first: its rows are the ones the picker will offer.+ const targets = this.devinTargets.get(sessionId)+ const pool: Iterable<DevinModelTarget> = targets?.size+ ? targets.values()+ : this.devinCatalogCache?.entries ?? []+ const wanted = label.trim().toLowerCase()+ for (const target of pool) {+ // A row whose id carries no effort keeps the effort word in its label ("GLM-5.2 High"), so an exact+ // label match is what identifies it; anything looser would tie the footer to the wrong sibling.+ if (target.label.toLowerCase() === wanted) return target+ if (target.effort !== 'auto' && `${target.label} ${effortLabel(target.effort)}`.toLowerCase() === wanted) {+ return target+ }+ }+ return null+ }++ /**+ * An agent that has not bound an engine session yet. Its `sessionId` is the EMPTY STRING, which is+ * not an identity — every unbound agent would share one entry in a map keyed on it, across engines.+ *+ * That is not hypothetical. A claude agent ten seconds old was retargeted onto a grid, and the+ * "what model was it on?" read that the retarget keeps — so a later move home can restore it —+ * answered `opencode/big-pickle`: an OpenCode agent sitting at `''` had written its footer there+ * first. The claude pane came home with `ANTHROPIC_MODEL=opencode/big-pickle` and Claude Code+ * answered "There's an issue with the selected model (opencode/big-pickle). It may not exist".+ *+ * So `''` gets no entry in this conversation cache, and writes land in a throwaway rather than a+ * bucket the next agent will read. Transcript state is re-read once a real conversation binds.+ */+ private unbound(sessionId: string): boolean {+ return !sessionId+ }++ private state(sessionId: string): RuntimeState {+ if (this.unbound(sessionId)) return blankState()+ let state = this.states.get(sessionId)+ if (!state) {+ state = blankState()+ this.states.set(sessionId, state)+ }+ return state+ }++ private ingestCursor(session: RegisteredSession, raw: Record<string, unknown>): void {+ const state = this.state(session.sessionId)+ const version = text(raw.version) || text(raw.cursor_version)+ if (version) {+ session.cliVersion = version+ state.cliVersion = version+ }+ const model = text(raw.model)+ if (model) {+ state.model = model+ // Default the effort to 'auto' when we do not have one yet. selectedModel() returns null unless BOTH+ // axes are known, so without this a Cursor session whose model we DO know shows nothing at all on+ // the device — the model is thrown away because the effort is missing.+ //+ // Cursor reports its model in the transcript but its reasoning level only in the pane footer, so+ // the effort arrives later (ingestPane) or not at all for a model that has no reasoning levels.+ // 'auto' is not a guess about Cursor's behaviour: it is exactly how the device renders "not+ // specified", and the pane path overwrites it with the real value the moment one is read.+ state.effort ??= 'auto'+ state.observedAt = Date.now()+ }+ }++ private ingestGrok(session: RegisteredSession, raw: Record<string, unknown>): void {+ const params = record(raw.params)+ const update = record(params?.update)+ const meta = record(update?._meta)+ const model = text(meta?.modelId)+ if (!model) return+ const state = this.state(session.sessionId)+ state.model = model+ state.observedAt = Date.now()+ }++ /**+ * The catalog Codex builds its own `/model` picker from, read fresh: what the controller matches the+ * picker's rows against (engines/codex/modelPicker.ts). Empty when there is no cache to read.+ */+ async codexCatalog(session: RegisteredSession): Promise<RuntimeCatalogModel[]> {+ return this.runtimeFor(session.engine)?.catalog?.(session) ?? []+ }++ /** Command Code stamps the model on every assistant line as the full gateway id+ * ("deepseek/deepseek-v4-flash"). Store the short name so it matches the catalogue and the chip label.+ * `raw.version` here is the transcript SCHEMA version (3), not a CLI version — never read it as one. */+ private ingestCommandcode(session: RegisteredSession, raw: Record<string, unknown>): void {+ const model = text(raw.model)+ if (!model) return+ const state = this.state(session.sessionId)+ state.model = shortCommandcodeModel(model)+ // Effort is NOT touched here: it comes from the CLI config (ingestConfig), and stamping 'auto' on every+ // assistant line would wipe a configured level a second after it was read.+ state.observedAt = Date.now()+ }++ private async cursorModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {+ const key = `${session.cliVersion ?? 'unknown'}\0${process.env.HOME ?? ''}`+ let entries = this.cursorCatalogCache?.key === key && this.cursorCatalogCache.expiresAt > Date.now()+ ? this.cursorCatalogCache.entries+ : null+ if (!entries) {+ try {+ const result = await execFileAsync('agent', ['models'], {+ env: process.env,+ timeout: 5_000,+ maxBuffer: 1024 * 1024,+ })+ entries = parseCursorModelsOutput(result.stdout)+ this.cursorCatalogCache = { key, entries, expiresAt: Date.now() + CURSOR_CATALOG_TTL_MS }+ } catch (err) {+ console.warn('[runtime-profile] Cursor model catalog failed:', err instanceof Error ? err.message : err)+ entries = []+ }+ }++ const output: RuntimeModelOption[] = []+ const previousTargets = this.cursorTargets.get(session.sessionId) ?? new Map<string, CursorModelTarget>()+ const targets = new Map<string, CursorModelTarget>()+ const seen = new Set<string>()+ for (const entry of entries) {+ if (!CURSOR_EFFORTS.has(entry.effort)) continue+ const id = encodeRuntimeProfile({+ sessionId: session.agentId,+ engine: 'cursor',+ model: entry.target.modelKey,+ effort: entry.effort,+ })+ if (seen.has(id)) continue+ seen.add(id)+ targets.set(id, entry.target)+ output.push({ id, displayName: `${entry.modelLabel} / ${effortLabel(entry.effort)}` })+ }+ const state = this.states.get(session.sessionId)+ const current = state?.model && state.effort+ ? encodeRuntimeProfile({+ sessionId: session.agentId,+ engine: 'cursor',+ model: state.model,+ effort: state.effort,+ })+ : null+ const observed = current ? previousTargets.get(current) : null+ if (observed) {+ const familyEfforts = [...new Set(entries+ .filter((entry) => entry.target.familyLabel.toLowerCase() === observed.familyLabel.toLowerCase())+ .map((entry) => entry.effort)+ .filter((effort) => effort !== 'auto'))]+ const efforts = familyEfforts.length ? familyEfforts : [state!.effort!]+ for (const effort of efforts) {+ const id = encodeRuntimeProfile({+ sessionId: session.agentId,+ engine: 'cursor',+ model: observed.modelKey,+ effort,+ })+ if (seen.has(id)) continue+ seen.add(id)+ targets.set(id, { ...observed, reasoning: effort, footerEffort: effort })+ const label = [+ observed.familyLabel,+ observed.context ? `(${observed.context.toUpperCase()})` : '',+ observed.thinking ? 'Thinking' : '',+ observed.fast ? 'Fast' : '',+ ].filter(Boolean).join(' ')+ output.push({ id, displayName: `${label} / ${effortLabel(effort)}` })+ }+ }+ this.cursorTargets.set(session.sessionId, targets)+ return output+ }++ /**+ * Devin's catalog comes from `devin models list` on stdout — no picker to scrape. It is big (166 rows+ * across 72 models on this account), so it is trimmed to CATALOG_LIMIT, and the model the session is+ * ACTUALLY running is pinned to the front so trimming can never hide it.+ */+ private async devinModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {+ const entries = await this.devinCatalog()+ const targets = new Map<string, DevinModelTarget>()+ const state = this.states.get(session.sessionId)+ // Keep every row of the running model together with it, so its effort list stays complete.+ const ordered = state?.model+ ? [...entries].sort((a, b) => Number(b.modelKey === state.model) - Number(a.modelKey === state.model))+ : entries++ const output: RuntimeModelOption[] = []+ const seen = new Set<string>()+ for (const entry of ordered) {+ if (output.length >= CATALOG_LIMIT) break+ if (!DEVIN_EFFORTS.has(entry.effort)) continue+ const id = encodeRuntimeProfile({+ sessionId: session.agentId,+ engine: 'devin',+ model: entry.modelKey,+ effort: entry.effort,+ })+ if (seen.has(id)) continue+ seen.add(id)+ targets.set(id, entry)+ output.push({ id, displayName: `${entry.label} / ${effortLabel(entry.effort)}` })+ }+ this.devinTargets.set(session.sessionId, targets)+ return output+ }++ private async devinCatalog(): Promise<DevinModelTarget[]> {+ const key = env.DEVIN_HOME+ if (this.devinCatalogCache?.key === key && this.devinCatalogCache.expiresAt > Date.now()) {+ return this.devinCatalogCache.entries+ }+ let entries: DevinModelTarget[] = []+ try {+ const result = await execFileAsync('devin', ['models', 'list'], {+ env: process.env,+ timeout: 10_000,+ maxBuffer: 1024 * 1024,+ })+ entries = parseDevinModelsOutput(result.stdout)+ } catch (err) {+ console.warn('[runtime-profile] Devin model catalog failed:', err instanceof Error ? err.message : err)+ }+ this.devinCatalogCache = { key, entries, expiresAt: Date.now() + CATALOG_TTL_MS }+ return entries+ }++ /**+ * Pi lists models on stdout too, and its `thinking` column says which of them accept a reasoning depth —+ * so effort rows are attached per model instead of assumed. A model that is configured but absent from+ * the table (the state fallback) still gets its own row so the chip never goes blank.+ */+ private async piModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {+ const entries = await this.piCatalog()+ const output: RuntimeModelOption[] = []+ const seen = new Set<string>()+ for (const entry of entries) {+ addOption(output, seen, session, entry.model, 'auto', entry.model)+ if (!entry.thinking) continue+ for (const level of PI_THINKING_LEVELS) addOption(output, seen, session, entry.model, level, entry.model)+ }+ const state = this.states.get(session.sessionId)+ if (entries.length && state?.model) {+ addOption(output, seen, session, state.model, 'auto', state.model)+ if (state.effort && PI_EFFORTS.has(state.effort)) {+ addOption(output, seen, session, state.model, state.effort, state.model)+ }+ }+ return output+ }++ /** The picker page + row a hermes profile id points at. */+ hermesTarget(sessionId: string, profileId: string): HermesModelTarget | null {+ return this.hermesTargets.get(sessionId)?.get(profileId) ?? null+ }++ /**+ * Hermes offers MODELS only. Its reasoning effort lives in `agent.reasoning_effort` in config.yaml with+ * no in-session command to change it (`/config` only prints), and a running session does not re-read the+ * file — so an effort row would be a control that silently does nothing. The level is still OBSERVED, so+ * the chip names it truthfully; it just cannot be picked.+ */+ private async hermesModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {+ const entries = await this.hermesCatalog(session.hermesHome || env.HERMES_HOME)+ const state = this.states.get(session.sessionId)+ const targets = new Map<string, HermesModelTarget>()+ const output: RuntimeModelOption[] = []+ const seen = new Set<string>()+ const effort = state?.effort && HERMES_EFFORTS.has(state.effort) ? state.effort : 'auto'+ const add = (entry: HermesModelTarget): void => {+ const short = entry.id.slice(entry.id.lastIndexOf('/') + 1)+ const id = encodeRuntimeProfile({+ sessionId: session.agentId, engine: 'hermes', model: short, effort,+ })+ if (seen.has(id)) return+ seen.add(id)+ targets.set(id, entry)+ output.push({ id, displayName: runtimeModelLabel(short) })+ }+ for (const entry of entries) add(entry)+ // The provider in use is often absent from the picker cache (a `custom` gateway is its own one-model+ // page), so the configured model is always offered — otherwise the running model is missing from its+ // own list.+ if (state?.model && !seen.size) add({ id: state.model, provider: '' })+ else if (state?.model && ![...targets.values()].some((t) => t.id.endsWith(state.model!))) {+ add({ id: state.model, provider: '' })+ }+ this.hermesTargets.set(session.sessionId, targets)+ return output+ }++ private async hermesCatalog(home = env.HERMES_HOME): Promise<HermesModelTarget[]> {+ // Keyed by home, and now actually asked per home: a profile has its own providers, so the cache+ // key was already right and only the path it read was not.+ const cached = this.hermesCatalogCache.get(home)+ if (cached && cached.expiresAt > Date.now()) return cached.entries+ const cache = await readJson(join(home, 'provider_models_cache.json'))+ const entries = parseHermesModelsCache(cache)+ this.hermesCatalogCache.set(home, { entries, expiresAt: Date.now() + CATALOG_TTL_MS })+ return entries+ }++ /** The full `/model` argument for a Command Code profile id — the profile itself holds the short name. */+ commandcodeTarget(sessionId: string, profileId: string): CommandcodeModelTarget | null {+ return this.commandcodeTargets.get(sessionId)?.get(profileId) ?? null+ }++ /**+ * Command Code's catalog comes from `--list-models`. Effort rows are attached to every model because the+ * CLI does not publish which models take one; an unsupported pick is refused in words at apply time+ * (see COMMANDCODE_EFFORT_LEVELS).+ */+ private async commandcodeModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {+ const entries = await this.commandcodeCatalog()+ const targets = new Map<string, CommandcodeModelTarget>()+ const output: RuntimeModelOption[] = []+ const seen = new Set<string>()+ const add = (entry: CommandcodeModelTarget, effort: string): void => {+ const id = encodeRuntimeProfile({+ sessionId: session.agentId, engine: 'commandcode', model: entry.shortId, effort,+ })+ if (seen.has(id)) return+ seen.add(id)+ targets.set(id, entry)+ output.push({ id, displayName: `${runtimeModelLabel(entry.shortId)} / ${effortLabel(effort)}` })+ }+ for (const entry of entries) {+ add(entry, 'auto')+ for (const level of COMMANDCODE_EFFORT_LEVELS) add(entry, level)+ }+ const state = this.states.get(session.sessionId)+ // `entries.length` guards the fallback: a model row is worth adding when the catalogue is readable but+ // does not list what the session runs (a pinned build, a just-removed model). When the catalogue could+ // not be read at all, one lone row is a picker that cannot pick anything — better to offer none.+ if (entries.length && state?.model && !entries.some((entry) => entry.shortId === state.model)) {+ const own: CommandcodeModelTarget = { id: state.model, shortId: state.model, section: '', isDefault: false }+ add(own, 'auto')+ if (state.effort && COMMANDCODE_EFFORTS.has(state.effort)) add(own, state.effort)+ }+ this.commandcodeTargets.set(session.sessionId, targets)+ return output+ }++ private async commandcodeCatalog(): Promise<CommandcodeModelTarget[]> {+ const key = env.COMMANDCODE_HOME+ if (this.commandcodeCatalogCache?.key === key && this.commandcodeCatalogCache.expiresAt > Date.now()) {+ return this.commandcodeCatalogCache.entries+ }+ let entries: CommandcodeModelTarget[] = []+ try {+ const result = await execFileAsync('commandcode', ['--list-models'], {+ env: process.env, timeout: 15_000, maxBuffer: 1024 * 1024,+ })+ entries = parseCommandcodeModelsOutput(result.stdout)+ } catch (err) {+ console.warn('[runtime-profile] Command Code model catalog failed:', err instanceof Error ? err.message : err)+ }+ this.commandcodeCatalogCache = { key, entries, expiresAt: Date.now() + CATALOG_TTL_MS }+ return entries+ }++ /** OpenCode has no effort axis, so every model is one `auto` row and the label carries no effort. */+ private async opencodeModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {+ const entries = await this.opencodeCatalog()+ const output: RuntimeModelOption[] = []+ const seen = new Set<string>()+ for (const entry of entries) {+ const id = encodeRuntimeProfile({+ sessionId: session.agentId, engine: 'opencode', model: entry.id, effort: 'auto',+ })+ if (seen.has(id)) continue+ seen.add(id)+ output.push({ id, displayName: entry.id })+ }+ const state = this.states.get(session.sessionId)+ // See commandcodeModels: only worth a row when the catalogue itself came back.+ if (entries.length && state?.model && !entries.some((entry) => entry.id === state.model)) {+ const id = encodeRuntimeProfile({+ sessionId: session.agentId, engine: 'opencode', model: state.model, effort: 'auto',+ })+ if (!seen.has(id)) output.push({ id, displayName: state.model })+ }+ return output+ }++ async opencodeCatalog(): Promise<OpencodeModelTarget[]> {+ const key = env.OPENCODE_DATA_DIR+ if (this.opencodeCatalogCache?.key === key && this.opencodeCatalogCache.expiresAt > Date.now()) {+ return this.opencodeCatalogCache.entries+ }+ let entries: OpencodeModelTarget[] = []+ try {+ const result = await execFileAsync(opencodeBin(), ['models'], {+ env: process.env, timeout: 10_000, maxBuffer: 1024 * 1024,+ })+ entries = parseOpencodeModelsOutput(result.stdout)+ } catch (err) {+ console.warn('[runtime-profile] OpenCode model catalog failed:', err instanceof Error ? err.message : err)+ }+ this.opencodeCatalogCache = { key, entries, expiresAt: Date.now() + CATALOG_TTL_MS }+ return entries+ }++ /** Kilo has no effort axis either, so every model is one `auto` row. */+ private async kiloModels(session: RegisteredSession): Promise<RuntimeModelOption[]> {+ const entries = await this.kiloCatalog()+ const output: RuntimeModelOption[] = []+ const seen = new Set<string>()+ for (const entry of entries) {+ const id = encodeRuntimeProfile({+ sessionId: session.agentId, engine: 'kilo', model: entry.id, effort: 'auto',+ })+ if (seen.has(id)) continue+ seen.add(id)+ output.push({ id, displayName: entry.id })+ }+ return output+ }++ async kiloCatalog(): Promise<KiloModelTarget[]> {+ const key = env.KILO_DATA_DIR+ if (this.kiloCatalogCache?.key === key && this.kiloCatalogCache.expiresAt > Date.now()) {+ return this.kiloCatalogCache.entries+ }+ let entries: KiloModelTarget[] = []+ try {+ // Measured: `kilo models` answers WITHOUT the user being logged in (unlike `kilo profile`), and+ // prints 299 ids on this machine — so an empty catalog here means the binary is missing, not that+ // the account is signed out.+ const result = await execFileAsync(env.KILO_PATH || 'kilo', ['models'], {+ env: process.env, timeout: 10_000, maxBuffer: 1024 * 1024,+ })+ entries = parseKiloModelsOutput(result.stdout)+ } catch (err) {+ console.warn('[runtime-profile] Kilo model catalog failed:', err instanceof Error ? err.message : err)+ }+ this.kiloCatalogCache = { key, entries, expiresAt: Date.now() + CATALOG_TTL_MS }+ return entries+ }++ private async piCatalog(): Promise<ReturnType<typeof parsePiModelsOutput>> {+ const key = env.PI_HOME+ if (this.piCatalogCache?.key === key && this.piCatalogCache.expiresAt > Date.now()) {+ return this.piCatalogCache.entries+ }+ let entries: ReturnType<typeof parsePiModelsOutput> = []+ try {+ const result = await execFileAsync('pi', ['--list-models'], {+ env: process.env,+ timeout: 10_000,+ maxBuffer: 1024 * 1024,+ })+ entries = parsePiModelsOutput(result.stdout)+ } catch (err) {+ console.warn('[runtime-profile] Pi model catalog failed:', err instanceof Error ? err.message : err)+ }+ this.piCatalogCache = { key, entries, expiresAt: Date.now() + CATALOG_TTL_MS }+ return entries+ }++ private scheduleChanged(sessionId: string): void {+ const previous = this.changeTimers.get(sessionId)+ if (previous) clearTimeout(previous)+ this.changeTimers.set(sessionId, setTimeout(() => {+ this.changeTimers.delete(sessionId)+ if (!this.controls.has(sessionId)) this.onChanged?.(sessionId)+ }, CHANGE_DEBOUNCE_MS))+ }++ private waitFor(sessionId: string, check: () => boolean, timeoutMs: number): Promise<boolean> {+ if (check()) return Promise.resolve(true)+ return new Promise((resolve) => {+ const waiter: StateWaiter = {+ check,+ resolve,+ timer: setTimeout(() => {+ this.waiters.get(sessionId)?.delete(waiter)+ resolve(false)+ }, timeoutMs),+ }+ const set = this.waiters.get(sessionId) ?? new Set<StateWaiter>()+ set.add(waiter)+ this.waiters.set(sessionId, set)+ })+ }++ private wake(sessionId: string): void {+ const set = this.waiters.get(sessionId)+ if (!set) return+ for (const waiter of [...set]) {+ if (!waiter.check()) continue+ clearTimeout(waiter.timer)+ set.delete(waiter)+ waiter.resolve(true)+ }+ if (set.size === 0) this.waiters.delete(sessionId)+ }+}diff --git a/cli/src/lib/runtimeProfileWire.ts b/cli/src/lib/runtimeProfileWire.tsnew file mode 100644index 000000000..31c84144c--- /dev/null+++ b/cli/src/lib/runtimeProfileWire.ts@@ -0,0 +1,32 @@+/** Public profile ids and effort vocabulary, independent of engine implementations. */+import type { AgentEngine } from '../engines/types.js'+import type { RuntimeProfile } from '../engines/facets/runtime.js'+import { RUNTIME_EFFORTS } from '../engines/kit/runtime.js'++const PROFILE_RE = /^runtime-v1:([^:]+):(claude|codex|cursor|commandcode|pi|devin|opencode|hermes|muse|amp|kilo|grok|agy|copilot):([^@]+)@([a-z0-9_-]+)$/i++function decode(value: string): string | null {+ try {+ const out = decodeURIComponent(value)+ return out ? out : null+ } catch {+ return null+ }+}++export function parseRuntimeProfile(value: unknown): RuntimeProfile | null {+ if (typeof value !== 'string') return null+ const match = PROFILE_RE.exec(value)+ if (!match) return null+ const sessionId = decode(match[1])+ const model = decode(match[3])+ const effort = match[4].toLowerCase()+ if (!sessionId || !model || !RUNTIME_EFFORTS.has(effort)) return null+ return {+ id: value,+ sessionId,+ engine: match[2].toLowerCase() as AgentEngine,+ model,+ effort,+ }+}diff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.tsindex 1c061f523..11136ad8e 100644--- a/cli/src/services/inline.spec.ts+++ b/cli/src/services/inline.spec.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest'import { engineTranscriptFor } from '../engines/transcripts.js'import { liveFor } from '../engines/live.js'+import { runtimeFor } from '../engines/runtime.js'import { startGateway } from '../gateway/start.js'import { startCommandBar } from './commandBar.js'import { startDevices } from './devices.js'@@ -24,6 +25,6 @@ import { startWorkspaces } from './workspaces.js'describe('the services the core runs in its own process only when they do not run in theirs', () => {it('are their own starts, unchanged: the same services either way', () => {- expect({ ...inline }).toEqual({ engineTranscriptFor, liveFor, startCommandBar, startDevices, startHandoff, startGateway, startModels, startMonitor, startOrchestrator, startProjects, startRecaps, startSearch, startSharing, startShell, startStore, startTeamsInCore, startUsage, startViewers, startWifi, startWindowNames, startWorkspaces })+ expect({ ...inline }).toEqual({ engineTranscriptFor, liveFor, runtimeFor, startCommandBar, startDevices, startHandoff, startGateway, startModels, startMonitor, startOrchestrator, startProjects, startRecaps, startSearch, startSharing, startShell, startStore, startTeamsInCore, startUsage, startViewers, startWifi, startWindowNames, startWorkspaces })})})diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.tsindex 2639d20bb..9c7086042 100644--- a/cli/src/services/inline.ts+++ b/cli/src/services/inline.ts@@ -14,6 +14,7 @@*/export { engineTranscriptFor } from '../engines/transcripts.js'export { liveFor } from '../engines/live.js'+export { runtimeFor } from '../engines/runtime.js'export { startGateway } from '../gateway/start.js'export { startCommandBar } from './commandBar.js'export { startDevices } from './devices.js'diff --git a/cli/src/services/models.ts b/cli/src/services/models.tsindex 8da9489ff..70cc167b0 100644--- a/cli/src/services/models.ts+++ b/cli/src/services/models.ts@@ -36,7 +36,8 @@ import { gridModelsPayload } from '../lib/gridModelsPayload.js'import { resolveGridTarget } from '../lib/gridTarget.js'import { LocalModels } from '../lib/localModels.js'import type { NewAgentModel } from '../lib/newAgentModel.js'-import { parseRuntimeProfile, type RuntimeModelOption } from '../lib/runtimeProfile.js'+import type { RuntimeModelOption } from '../lib/runtimeProfile.js'+import { parseRuntimeProfile } from '../lib/runtimeProfileWire.js'import { ensureManagedGrid, startGridPinRecheck } from '../lib/runtimeInstall.js'import { internalOnThrow } from './requestErrors.js'diff --git a/docs/design/2026-10-08-engine-runtime.md b/docs/design/2026-10-08-engine-runtime.mdnew file mode 100644index 000000000..9d2ef2ed8--- /dev/null+++ b/docs/design/2026-10-08-engine-runtime.md@@ -0,0 +1,110 @@+# Engine runtime profiles++Status: implemented for Claude Code and Codex. This continues [engine isolation](2026-10-05-engine-interface.md)+after [live transcript isolation](2026-10-07-engine-streams.md). The supervised Claude Code/Codex profile+path now executes in workers. Its profile implementations are also excluded from normal core's+import closure. This boundary covers runtime profiles; the wider engine migration remains in progress.++## Ownership++Claude Code and Codex own transcript and pane interpretation, native model and effort policy,+configuration reads, and model catalogs. Core's runtime coordinator keeps accepted profile state,+notification timing, and control transactions. Its routing facade uses the inline manager only for+other engines or explicit compatibility. Supervised Claude Code/Codex observations, catalogs and+native-control eligibility go through their workers, with no inline fallback after failure.++The runtime facet takes plain session, state, and optional control values. Its reducers mutate those+supplied values, not a registry or terminal. The private worker handler copies only declared fields+before evaluation. A restarted worker can evaluate the next operation entirely from core's last+accepted snapshot.++Live transcript pages carry compact, opaque runtime evidence beside normalized events. The engine+extracts that evidence from the vendor record. Core transports it without interpreting its keys.+For example, a large assistant record contributes its model/version facts without carrying its entire+answer into another profile request. An unrecognized model acknowledgement still retains its existing+control meaning. The metadata-field probe uses the same engine reducer on an isolated scratch state;+it no longer loads the monolithic runtime manager inside a worker.++## Private protocol++`engine_runtime_capabilities` and `engine_runtime_read` require core's authenticated owner link.+They are not public request routes. Each worker loads its own runtime facet on demand.++- Version 1 supports compact record batches, pane observations, configuration, model lists,+ native catalogs, effort eligibility, and a current profile description.+- Requests and replies are bounded at 1 MiB. Batches contain at most 512 compact records; pane text+ is bounded at 256 KiB. There are at most two runtime requests executing per engine worker.+- One five-second core deadline covers negotiation and execution. A worker also recycles when an+ asynchronous operation exceeds its execution deadline, containing abandoned file reads.+- The core transport rejects stale connection generations, malformed results, and profile ids for+ another agent. A control result must describe the same supplied transaction. Both the current+ agent-id encoding and the previously supported bound conversation-id encoding remain accepted.+- Calls do not fall back to core after worker failure. Caller wiring must preserve the last accepted+ profile and retry pending evidence under the same binding checks used by live transcripts.++## Core authority and handover++Core serializes runtime requests per engine, with a 256-entry queue and a five-second queue wait+budget in addition to the transport deadline. Each operation carries copied state and control facts.+Replies are rejected if the conversation/process binding, control revision, or observed CLI version+changed. A stale caller cannot replace a newer binding's accepted profile. Empty conversation ids+never become shared cached state; unbound agents can still request their own catalogs.++Live pages reduce compact evidence in bounded batches before acknowledging their cursor or delivering+events. Failed reductions retain the previous cursor and retry even without another file change.+Cancellation is checked again after awaiting the profile worker. Attach hydration has its own staged+state, including configuration; it installs that state and the live parser in one synchronous commit+under the existing binding, turn, tail-movement and hold guards. A failed stage cannot commit a+partially reduced page.++Synchronous display reads use accepted state. Control waiters, cancellation, nested notification+suppression and debounce remain in core. Gateway sessions remain display-only. The parent-bound+`HARNESSD_ENGINE_RUNTIME=<master-pid>:1` report selects runtime isolation separately from live parsing;+an older master selects explicit compatibility instead of discovering the missing protocol on a+user's first request. The wire profile parser no longer imports the runtime manager.++## Compatibility and validation++The legacy manager takes injected runtime facets. Normal supervised core supplies no Claude/Codex+facet; explicit inline mode or an older master's capability report loads them through+`services/inline.ts`. Architecture checks reject either profile implementation in normal core's import+closure. Worker failure never changes this composition.++The old catch-all interpreted other engines' records and panes as Claude. Auditing recorded Amp,+Muse, Copilot, agy and Pi transcripts found no native profile metadata supplied by that fallback.+Their registry seeds and native config/footer readers remain. Claude commands quoted in their answers+or panes no longer change their profiles. Tests replay the recordings and cover these native sources;+this does not add new engines to the worker migration.++Development evidence: 1,447 core/services tests with 100% coverage in every file; the supervisor+gate with 100% coverage in every file; 583 focused profile/controller/home/protocol/attach and boundary+tests; typechecking and architecture checks. Eight selected private daemon/tmux cases passed with fake+vendor CLIs: Codex model/effort switching, both engines' moved-home catalogs, private-route denial,+both engines' accepted-profile preservation and pending-evidence recovery while their worker was+frozen, and both engines' explicit inline profiles/catalogs. The name filter excluded 25 other cases.+The queue regression also verifies that an expired caller returns while the preceding request remains+pending, without letting its successor bypass that active request.++A paired macOS run compared main `023ae4117` with runtime code `b1000873d`, using Node 22.23.2,+four agents (two active), two windows, four terminal streams, 1 MiB histories and history requests+every two seconds. Each phase measured 30 seconds after warmup. CPU is a percentage of one logical+CPU; RSS below includes core and both engine workers. Master, other services, vendor CLIs and tmux+are excluded. The engines and backend are disposable local fakes.++| Active workload | Main | Runtime isolation |+|---|---:|---:|+| Core + worker CPU | 8.73% | 8.80% |+| Core + worker mean RSS | 319.30 MiB | 314.61 MiB |+| Core mean RSS | 140.44 MiB | 141.78 MiB |+| Core event-loop p99 | 14.01 ms | 14.25 ms |+| History read p95 | 42.70 ms | 36.12 ms |+| Fake turn p95 | 6000 ms | 6142 ms |+| Completed turns | 10 | 10 |++Empty CPU/RSS was 1.07%/90.75 MiB versus 1.16%/89.99 MiB; populated-idle was+4.17%/306.33 MiB versus 4.02%/306.82 MiB. This is one paired measurement, not a new numerical gate+or evidence about real model latency. The PR records CI/review evidence separately from these local+checks and measurements.++Hooks, launch/discovery/resume, input interpretation, and the other boundaries tracked by the engine+isolation work remain in scope after runtime profiles. This increment does not close the full goal.