Skip to content

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.

Isolate Claude Code and Codex model controls (#1038)

Dee6020c99373bc
diff --git a/cli/AGENTS.md b/cli/AGENTS.md
index 2058f59b0..b2522246a 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, live transcript parsers, runtime profiles/catalogs and screen interpretation | on demand: an attach or read for that engine |
+| engine-claude, engine-codex | history, last-turn readers, live transcript parsers, runtime profiles/catalogs, screen interpretation and model control | 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/engineModelControl.e2e.ts b/cli/e2e/engineModelControl.e2e.ts
new file mode 100644
index 000000000..61a76f0fd
--- /dev/null
+++ b/cli/e2e/engineModelControl.e2e.ts
@@ -0,0 +1,92 @@
+/** Real private daemon, tmux, engine workers and RPC; deterministic CLIs, no model accounts. */
+import { existsSync, 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'
+import { CLI_ROOT, IsolatedDaemon, until, type DaemonOptions } from './harness/daemon.js'
+import { harnessdProcesses } from './harness/endurance.js'
+
+type Engine = 'claude' | 'codex'
+const profile = (agent: string, engine: Engine, model: string, effort: string) => `runtime-v1:${agent}:${engine}:${model}@${effort}`
+
+describe('engine model-control workers', () => {
+ let daemon: IsolatedDaemon | undefined, client: LocalClient | undefined
+ afterEach(async () => { client?.close(); await daemon?.close(); client = undefined; daemon = undefined })
+ async function fresh(engine: Engine, options: DaemonOptions = {}) {
+ const d = daemon = await IsolatedDaemon.create(options)
+ writeFileSync(join(d.engineConfig.codexHome, 'models_cache.json'), readFileSync(join(CLI_ROOT, 'src/lib/__fixtures__/codex-home-0.160/models_cache.json')))
+ onTestFailed(() => console.log(d.log()))
+ await d.start()
+ const c = client = await LocalClient.connect(d)
+ const cwd = join(d.projectsDir, engine); mkdirSync(cwd, { recursive: true })
+ const created = await c.request('agent_create', { engine, cwd, bypassPermission: true }, 90_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ const agent = await until('bound engine', async () => (await c.request('agents_list', {})).agents.find((row: any) => row.id === created.agent.id && row.sessionId), 60_000, 100)
+ const turn = async (content: string) => {
+ const ended = c.next(frame => frame.type === 'turn_ended' && frame.agentId === agent.id, 30_000, content)
+ c.send('message', { agentId: agent.id, content }); await ended
+ }
+ await turn('before model control')
+ const commandsPath = join(d.engineConfig.root, 'model-control-commands')
+ const commands = () => existsSync(commandsPath) ? readFileSync(commandsPath, 'utf8').trim().split('\n') : []
+ const selected = profile(agent.id, engine, engine === 'claude' ? 'sonnet' : 'gpt-6-luna', 'high')
+ const offered = await c.request('models_list', { agentId: agent.id }, 15_000)
+ expect(offered.models.some((option: { id: string }) => option.id === selected)).toBe(true)
+ return { d, c, agent, selected, turn, commands, commandsPath }
+ }
+
+ it.each([false, true])('switches Claude Code model and effort with inline=%s', async inline => {
+ const { d, c, agent, selected, turn, commands } = await fresh('claude', inline ? { env: { HARNESSD_SERVICES: 'none' } } : {})
+ const result = await c.request('agent_update', { agentId: agent.id, selectedModel: selected }, 45_000)
+ expect(result.error, JSON.stringify(result)).toBeUndefined()
+ expect(result.agent.selectedModel).toBe(selected)
+ expect(commands()).toEqual(['claude /model sonnet', 'claude /effort high'])
+ const lower = profile(agent.id, 'claude', 'sonnet', 'low')
+ const changed = await c.request('agent_update', { agentId: agent.id, selectedModel: lower }, 45_000)
+ expect(changed.error, JSON.stringify(changed)).toBeUndefined()
+ expect(changed.agent.selectedModel).toBe(lower)
+ expect(commands().at(-1)).toBe('claude /effort low')
+ await turn('after model control')
+ expect(d.coresStarted()).toBe(1)
+ expect(!!harnessdProcesses(d).get('engine-claude')).toBe(!inline)
+ })
+
+ it.each(['claude', 'codex'] as const)('revokes an interrupted %s model change, keeps the CLI alive, and accepts a new intent after recovery', async engine => {
+ const { d, c, agent, selected, turn, commands, commandsPath } = await fresh(engine, { modelControlGate: true,
+ env: { HARNESSD_SERVICE_HEARTBEAT_TIMEOUT_MS: '4000', HARNESSD_SERVICE_STOP_GRACE_MS: '100' } })
+ const core = d.corePid(), worker = harnessdProcesses(d).get(`engine-${engine}`)!
+ const panePid = (await d.tmux.run('display-message', '-p', '-t', agent.tmuxPane, '#{pane_pid}')).trim()
+ const pending = c.request('agent_update', { agentId: agent.id, selectedModel: selected }, 45_000)
+ // The native CLI has received the command, but has not answered it. Core must revoke this
+ // operation when the engine worker stops, even though the CLI's later answer is still real.
+ await until('command reached the engine', () => commands().length > 0 || null, 15_000, 20)
+ process.kill(worker, 'SIGSTOP')
+ const answer = await pending
+ expect(answer.error, JSON.stringify(answer)).toBe('BUSY')
+ await until('replacement worker', () => {
+ const pid = harnessdProcesses(d).get(`engine-${engine}`)
+ return pid && pid !== worker ? pid : null
+ }, 20_000, 100)
+ writeFileSync(`${commandsPath}.release`, 'continue')
+ if (engine === 'codex') {
+ await until('still-open picker, with no late digit', async () => /Select Model|Select a model/.test(await d.capture(agent.tmuxPane)) || null, 15_000, 100)
+ await new Promise(resolve => setTimeout(resolve, 500))
+ expect(await d.capture(agent.tmuxPane)).toMatch(/Select Model|Select a model/)
+ // The user closes an interrupted picker before making a new request. Core never guesses an Escape.
+ await d.tmux.run('send-keys', '-t', agent.tmuxPane, 'Escape')
+ } else {
+ await until('actual model evidence after the worker recovers', async () => {
+ const row = (await c.request('agents_list', {})).agents.find((row: any) => row.id === agent.id)
+ return row?.selectedModel?.includes(':sonnet@') || null
+ }, 15_000, 100)
+ expect(commands()).toEqual(['claude /model sonnet']) // no resumed /effort from the cancelled worker
+ }
+ const retried = await c.request('agent_update', { agentId: agent.id, selectedModel: selected }, 45_000)
+ expect(retried.error, JSON.stringify(retried)).toBeUndefined()
+ expect(retried.agent.selectedModel).toBe(selected)
+ await turn('after worker recovery')
+ expect((await d.tmux.run('display-message', '-p', '-t', agent.tmuxPane, '#{pane_pid}')).trim()).toBe(panePid)
+ expect(d.corePid()).toBe(core)
+ expect(d.coresStarted()).toBe(1)
+ })
+})
diff --git a/cli/e2e/engineReaders.e2e.ts b/cli/e2e/engineReaders.e2e.ts
index 463aaebed..ed593352b 100644
--- a/cli/e2e/engineReaders.e2e.ts
+++ b/cli/e2e/engineReaders.e2e.ts
@@ -59,7 +59,7 @@ describe('Claude Code and Codex readers in their own processes', () => {
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_runtime_capabilities', 'engine_runtime_read', 'engine_screen_capabilities', 'engine_screen_read']) {
+ 'engine_live_read', 'engine_live_part', 'engine_live_close', 'engine_live_forget', 'engine_runtime_capabilities', 'engine_runtime_read', 'engine_screen_capabilities', 'engine_screen_read', 'engine_model_control_capabilities', 'engine_model_control_validate', 'engine_model_control_apply']) {
const answer = await c.request(type, { version: 1, session: { transcriptPath: '/etc/passwd' } })
expect(answer.error).toBe('UNSUPPORTED')
}
diff --git a/cli/e2e/harness/daemon.ts b/cli/e2e/harness/daemon.ts
index 40a823859..9230ccb42 100644
--- a/cli/e2e/harness/daemon.ts
+++ b/cli/e2e/harness/daemon.ts
@@ -32,6 +32,8 @@ export interface EngineConfig {
claudeProjectsDir: string
codexHome: string
claudeModel?: string
+ /** Pause model commands at a disposable file gate for worker failure tests. */
+ modelControlGate?: boolean
codexModel?: string
/** The test's throwaway root: the engine runs no hooks from settings outside it. */
root: string
@@ -55,6 +57,8 @@ export interface DaemonOptions {
heapMiB?: number
/** Models the fake engines report. */
claudeModel?: string
+ /** Pause model commands at a disposable file gate for worker failure tests. */
+ modelControlGate?: boolean
codexModel?: string
/** Boot the core on its own (`__run`) instead of under harnessd's master (`__harnessd`). */
noMaster?: boolean
@@ -210,7 +214,7 @@ export class IsolatedDaemon {
await writeFile(join(dirs.home, '.zshrc'), '', { flag: 'a' })
const config: EngineConfig = {
port, dataDir: dirs.data, claudeProjectsDir: dirs.claudeProjects, codexHome: dirs.codexHome,
- claudeModel: options.claudeModel, codexModel: options.codexModel,
+ claudeModel: options.claudeModel, codexModel: options.codexModel, modelControlGate: options.modelControlGate,
root, hookLog: join(own, 'fake-engine-hooks.log'),
...(options.trustPrompt ? { trustPrompt: true } : {}),
}
diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjs
index 6643b49af..5d82d3b73 100644
--- a/cli/e2e/harness/fakeEngine.mjs
+++ b/cli/e2e/harness/fakeEngine.mjs
@@ -366,6 +366,16 @@ export async function run(engine, config = {}, { native = false } = {}) {
// (subscriptionModel.ts).
const modelAt = engine === 'codex' ? args.findIndex((arg) => arg === '-m' || arg === '--model') : -1
let current = { model: (modelAt >= 0 && args[modelAt + 1]) || config.codexModel || 'gpt-6', effort: 'high' }
+ let claudeModel = config.claudeModel ?? 'claude-opus-5-5'
+ // Test-owned file gate, used to stop an engine worker after its command reached the live CLI.
+ const modelGate = async command => {
+ const log = join(config.root, 'model-control-commands')
+ appendFileSync(log, `${engine} ${command}\n`)
+ if (config.modelControlGate) {
+ while (!existsSync(`${log}.release`)) await new Promise(resolve => setTimeout(resolve, 20))
+ }
+ }
+
/**
* The JSON an event hands its hooks on stdin, in each CLI's own shape: what notify.mjs reads (session,
* transcript, folder, the event and its source, prompt or reason) and the rest of what the real CLIs
@@ -984,7 +994,7 @@ export async function run(engine, config = {}, { native = false } = {}) {
}
const finish = async (text) => {
if (engine === 'claude') {
- claude({ type: 'assistant', message: { id: `msg_${turn}`, role: 'assistant', model: config.claudeModel ?? 'claude-opus-5-5', content: [{ type: 'text', text }], stop_reason: 'end_turn' } })
+ claude({ type: 'assistant', message: { id: `msg_${turn}`, role: 'assistant', model: claudeModel, content: [{ type: 'text', text }], stop_reason: 'end_turn' } })
} else {
codex('event_msg', { type: 'item_completed', item: { type: 'AgentMessage', content: [{ type: 'Text', text }], phase: 'final_answer' } })
codex('event_msg', { type: 'task_complete', turn_id: open, last_agent_message: text })
@@ -1003,7 +1013,7 @@ export async function run(engine, config = {}, { native = false } = {}) {
const id = `call_${turnOf}_p`
if (allowed) {
if (engine === 'claude') {
- claude({ type: 'assistant', message: { id: `msg_${turnOf}_p`, role: 'assistant', model: config.claudeModel ?? 'claude-opus-5-5', content: [{ type: 'tool_use', id, name: 'Bash', input: { command } }], stop_reason: 'tool_use' } })
+ claude({ type: 'assistant', message: { id: `msg_${turnOf}_p`, role: 'assistant', model: claudeModel, content: [{ type: 'tool_use', id, name: 'Bash', input: { command } }], stop_reason: 'tool_use' } })
claude({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: id, content: `ran ${command}` }] } })
} else {
codex('response_item', { type: 'function_call', call_id: id, name: 'exec_command', arguments: JSON.stringify({ cmd: command }) })
@@ -1039,6 +1049,17 @@ export async function run(engine, config = {}, { native = false } = {}) {
process.stdout.write('\x1b[?2004l\r\n')
process.exit(0)
}
+ if (engine === 'claude' && /^\/(?:model|effort) \S+$/.test(prompt)) {
+ await modelGate(prompt)
+ const [, command, value] = /^\/(model|effort) (\S+)$/.exec(prompt)
+ if (command === 'model') claudeModel = value
+ // The same control confirmations used in runtimeProfileController.spec.ts and engineReaders.e2e.ts.
+ // This fake tests the process boundary; it is not real-model acceptance evidence.
+ const output = command === 'model' ? `Set model to ${value}` : `Set effort level to ${value}`
+ claude({ type: 'system', content: output })
+ say(`${output}\r\n`)
+ return
+ }
if (prompt === '!compact') {
// `/compact` is a command, not a turn: a summary replaces the history, and Claude Code announces
// the same session again (SessionStart, source compact), which makes the daemon re-read it.
@@ -1092,7 +1113,7 @@ export async function run(engine, config = {}, { native = false } = {}) {
open = `turn-${turn}`
if (engine === 'claude') {
claude({ type: 'user', message: { role: 'user', content: prompt } })
- claude({ type: 'assistant', message: { id: `msg_${turn}_t`, role: 'assistant', model: config.claudeModel ?? 'claude-opus-5-5', content: [{ type: 'thinking', thinking: `considering: ${prompt}` }], stop_reason: null } })
+ claude({ type: 'assistant', message: { id: `msg_${turn}_t`, role: 'assistant', model: claudeModel, content: [{ type: 'thinking', thinking: `considering: ${prompt}` }], stop_reason: null } })
} else {
codex('event_msg', { type: 'task_started', turn_id: open })
codex('turn_context', { turn_id: open, model: current.model, reasoning_effort: current.effort, collaboration_mode: { mode: 'default' } })
@@ -1114,7 +1135,7 @@ export async function run(engine, config = {}, { native = false } = {}) {
if (directive?.[1] === 'tool') {
const id = `call_${turn}`
if (engine === 'claude') {
- claude({ type: 'assistant', message: { id: `msg_${turn}_u`, role: 'assistant', model: config.claudeModel ?? 'claude-opus-5-5', content: [{ type: 'tool_use', id, name: 'Bash', input: { command: directive[2] } }], stop_reason: 'tool_use' } })
+ claude({ type: 'assistant', message: { id: `msg_${turn}_u`, role: 'assistant', model: claudeModel, content: [{ type: 'tool_use', id, name: 'Bash', input: { command: directive[2] } }], stop_reason: 'tool_use' } })
claude({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: id, content: `ran ${directive[2]}` }] } })
} else {
codex('response_item', { type: 'function_call', call_id: id, name: 'exec_command', arguments: JSON.stringify({ cmd: directive[2] }) })
@@ -1128,10 +1149,10 @@ export async function run(engine, config = {}, { native = false } = {}) {
// user record Claude Code writes when the parent is idle.
const name = directive[2] || 'scout'
const id = `toolu_${turn}_bg`
- claude({ type: 'assistant', message: { id: `msg_${turn}_bg`, role: 'assistant', model: config.claudeModel ?? 'claude-opus-5-5', content: [{ type: 'tool_use', id, name: 'Agent', input: { description: `Count for ${name}`, prompt: `Count the files for ${name}.`, run_in_background: true } }], stop_reason: 'tool_use' } })
+ claude({ type: 'assistant', message: { id: `msg_${turn}_bg`, role: 'assistant', model: claudeModel, content: [{ type: 'tool_use', id, name: 'Agent', input: { description: `Count for ${name}`, prompt: `Count the files for ${name}.`, run_in_background: true } }], stop_reason: 'tool_use' } })
claude({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: id, content: 'Async agent launched successfully.\nagentId: a0f1e2d3c4b5a6978' }] }, toolUseResult: { isAsync: true, status: 'async_launched', agentId: 'a0f1e2d3c4b5a6978' } })
const edit = `toolu_${turn}_ed`
- claude({ type: 'assistant', message: { id: `msg_${turn}_ed`, role: 'assistant', model: config.claudeModel ?? 'claude-opus-5-5', content: [{ type: 'tool_use', id: edit, name: 'Bash', input: { command: 'true' } }], stop_reason: 'tool_use' } })
+ claude({ type: 'assistant', message: { id: `msg_${turn}_ed`, role: 'assistant', model: claudeModel, content: [{ type: 'tool_use', id: edit, name: 'Bash', input: { command: 'true' } }], stop_reason: 'tool_use' } })
claude({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: edit, content: 'ran true' }] } })
const notification = `<task-notification>\n<task-id>a0f1e2d3c4b5a6978</task-id>\n<tool-use-id>${id}</tool-use-id>\n<output-file>${join(cwd, '.tasks', 'a0f1e2d3c4b5a6978.output')}</output-file>\n<status>completed</status>\n<summary>Agent "Count for ${name}" finished</summary>\n<result>${name} found 3 files</result>\n</task-notification>`
claude({ type: 'attachment', attachment: { type: 'queued_command', prompt: notification, commandMode: 'task-notification', origin: { kind: 'task-notification', producer: 'session-task' } } })
@@ -1190,7 +1211,7 @@ export async function run(engine, config = {}, { native = false } = {}) {
// A tool still running when the person interrupts. Both CLIs write its output, marked aborted, only
// AFTER the interrupt and just before the turn's end: what a real Codex 0.160 did in daemon QA.
const id = `call_${turn}`
- if (engine === 'claude') claude({ type: 'assistant', message: { id: `msg_${turn}_u`, role: 'assistant', model: config.claudeModel ?? 'claude-opus-5-5', content: [{ type: 'tool_use', id, name: 'Bash', input: { command: directive[2] } }], stop_reason: 'tool_use' } })
+ if (engine === 'claude') claude({ type: 'assistant', message: { id: `msg_${turn}_u`, role: 'assistant', model: claudeModel, content: [{ type: 'tool_use', id, name: 'Bash', input: { command: directive[2] } }], stop_reason: 'tool_use' } })
else codex('response_item', { type: 'function_call', call_id: id, name: 'exec_command', arguments: JSON.stringify({ cmd: directive[2] }) })
runningTool = id
return
@@ -1222,7 +1243,7 @@ export async function run(engine, config = {}, { native = false } = {}) {
const questions = [{ question: QUESTION, header: 'Drink', multiSelect: false, options: CHOICES.map(([label, description]) => ({ label, description })) }]
if (engine === 'claude') {
const id = `toolu_${turn}`
- claude({ type: 'assistant', message: { id: `msg_${turn}_q`, role: 'assistant', model: config.claudeModel ?? 'claude-opus-5-5', content: [{ type: 'tool_use', id, name: 'AskUserQuestion', input: { questions } }], stop_reason: 'tool_use' } })
+ claude({ type: 'assistant', message: { id: `msg_${turn}_q`, role: 'assistant', model: claudeModel, content: [{ type: 'tool_use', id, name: 'AskUserQuestion', input: { questions } }], stop_reason: 'tool_use' } })
claude({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: id, content: `User has answered your questions: "${QUESTION}"="${choice}"` }] } })
say(`⏺ User answered Claude's questions:\r\n ⎿ · ${QUESTION} → ${choice}\r\n`)
} else {
@@ -1252,7 +1273,7 @@ export async function run(engine, config = {}, { native = false } = {}) {
// The same refusal, after which Claude Code pauses the goal instead of working on (real 2.1.283): two
// notices and its turn_duration, with no output and no further Stop hook.
const condition = directive[2] || 'the work is done'
- claude({ type: 'assistant', message: { id: `msg_${turn}_p1`, role: 'assistant', model: config.claudeModel ?? 'claude-opus-5-5', content: [{ type: 'text', text: `first pass at: ${condition}` }], stop_reason: 'end_turn' } })
+ claude({ type: 'assistant', message: { id: `msg_${turn}_p1`, role: 'assistant', model: claudeModel, content: [{ type: 'text', text: `first pass at: ${condition}` }], stop_reason: 'end_turn' } })
say(`\r\nfirst pass at: ${condition}\r\n`)
await runHooks('Stop', { stop_hook_active: false })
claude({ type: 'user', isMeta: true, promptId: randomUUID(), message: { role: 'user', content: `Stop hook feedback:\n[goal]: not met yet: ${condition}` } })
@@ -1275,7 +1296,7 @@ export async function run(engine, config = {}, { native = false } = {}) {
// it in a full end-to-end run (520 ms after that pass started): the CLI waits for its hook commands,
// but the hook's request can be read after it has gone on. So the hooks run once the pass has begun.
const condition = directive[2] || 'the work is done'
- const model = config.claudeModel ?? 'claude-opus-5-5'
+ const model = claudeModel
const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
claude({ type: 'assistant', message: { id: `msg_${turn}_g1`, role: 'assistant', model, content: [{ type: 'text', text: `first pass at: ${condition}` }], stop_reason: 'end_turn' } })
say(`\r\nfirst pass at: ${condition}\r\n`)
@@ -1496,9 +1517,11 @@ export async function run(engine, config = {}, { native = false } = {}) {
if (engine === 'codex' && popup.found[0][0] === '/model' && popup.token.startsWith('/')) {
buffer = ''
pastes.clear()
- openModelPicker()
- const rest = parts.slice(index + 1).join('')
- if (rest && picker) { const left = pickerKeys(rest); if (left) process.stdin.emit('data', left) }
+ void modelGate('/model').then(() => {
+ openModelPicker()
+ const rest = parts.slice(index + 1).join('')
+ if (rest && picker) { const left = pickerKeys(rest); if (left) process.stdin.emit('data', left) }
+ })
return
}
// Otherwise Enter with suggestions open takes the highlighted one into the draft, and sends nothing.
@@ -1529,9 +1552,11 @@ export async function run(engine, config = {}, { native = false } = {}) {
// Codex's `/model` is a command, not a prompt: its picker takes the composer's place at once and
// nothing is sent. The keys after it in this read are the picker's.
if (engine === 'codex' && line.trim() === '/model') {
- openModelPicker()
- const rest = parts.slice(index + 1).join('')
- if (rest && picker) { const left = pickerKeys(rest); if (left) process.stdin.emit('data', left) }
+ void modelGate('/model').then(() => {
+ openModelPicker()
+ const rest = parts.slice(index + 1).join('')
+ if (rest && picker) { const left = pickerKeys(rest); if (left) process.stdin.emit('data', left) }
+ })
return
}
queue = queue.then(() => handle(line))
diff --git a/cli/e2e/perf.e2e.ts b/cli/e2e/perf.e2e.ts
index 629692cf9..29f92afb9 100644
--- a/cli/e2e/perf.e2e.ts
+++ b/cli/e2e/perf.e2e.ts
@@ -5,6 +5,7 @@
* PERF_REPORT=<file> writes JSON; raw artifacts stay in its recorded private temporary directory.
* Run alone. CPU is the core's process CPU (100% = one logical CPU), never the master's/children's.
* PERF_READERS=1 additionally measures reader PIDs and history pages every 2 s; totals include them.
+ * PERF_MODEL_CONTROLS=1 adds a window of alternating model changes in the two engine types.
* PERF_BUNDLE_SOURCE identifies an externally built baseline bundle; its bytes are hashed either way.
* On macOS set HARNESS_PROCESS_IMAGES_ARTIFACT to a verified local build for release-like discovery.
*/
@@ -98,6 +99,7 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
const warmup = knob('PERF_WARMUP_SECONDS', 20, 0, 120)
const historyMiB = knob('PERF_HISTORY_MIB', 1, 0, 8)
const measureReaders = process.env.PERF_READERS === '1'
+ const measureControls = process.env.PERF_MODEL_CONTROLS === '1'
const profile = process.env.PERF_PROFILE === '1'
const heaps = process.env.PERF_HEAP === '1'
const bundle = process.env.E2E_BUNDLE_PATH
@@ -116,7 +118,7 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
dirty: Boolean(git('status', '--porcelain')), bundleSource: process.env.PERF_BUNDLE_SOURCE ?? git('rev-parse', 'HEAD'), bundleSha256: sha(bundle), preloadSha256: sha(preload) },
machine: { platform: platform(), release: release(), node: process.version, logicalCpus: cpus().length,
cpu: cpus()[0]?.model, ramBytes: totalmem(), tmux: execFileSync('tmux', ['-V'], { encoding: 'utf8', timeout: 5_000 }).trim() },
- workload: { readerPageEveryMs: measureReaders ? 2000 : null, agents, active, windows: 2, terminalStreams: 4, seconds, warmup, historyMiB,
+ workload: { modelControls: measureControls, readerPageEveryMs: measureReaders ? 2000 : null, agents, active, windows: 2, terminalStreams: 4, seconds, warmup, historyMiB,
turnDelayMs: '5000 + a unique round offset', inventoryEveryMs: 60_000, heartbeatEveryMs: 5_000, ackEveryMs: 16 },
instrumentation: { profile, heaps, delayResolutionMs: 10, rssSampleEveryMs: 1_000, cpuPercentBasis: 'one logical CPU',
scope: measureReaders ? 'core PID and both reader PIDs; excludes master, other services, engines and tmux' : 'core PID only; excludes master, services, engines and tmux', heapPausesOutsideWindows: true },
@@ -134,6 +136,8 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
machine = await startPhoneMachine({ env: { NODE_OPTIONS: nodeOptions.join(' '),
HARNESS_E2E_PERF_READERS: measureReaders ? '1' : '0', HARNESS_E2E_PERF_DIR: artifactDir, HARNESS_E2E_PERF_TOKEN: token } })
const d = machine.machine.daemon
+ if (measureControls) writeFileSync(join(d.engineConfig.codexHome, 'models_cache.json'),
+ readFileSync(join(CLI_ROOT, 'src/lib/__fixtures__/codex-home-0.160/models_cache.json')))
corePid = d.corePid()
if (!corePid) throw new Error('no owned core PID')
report.corePid = corePid
@@ -174,11 +178,12 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
client.send('message', { agentId: id, content })
await ended
}
- const phase = async (label: string, turning: boolean) => {
+ const phase = async (label: string, turning: boolean, controlling = false) => {
await checkDesk()
const before = windows.map(w => w.stats())
const turns = Array.from({ length: turning ? active : 0 }, () => 0)
const latencies: number[] = []
+ const controlLatencies: Record<string, number[]> = { claude: [], codex: [] }
let running = true
let problem: unknown
const readers = measureReaders ? [...harnessdProcesses(d)].filter(([name]) => name.startsWith('engine-')) : []
@@ -204,6 +209,21 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
if (running) { turns[i]++; latencies.push(performance.now() - began) }
}
})
+ const controls = (controlling ? saved.slice(0, active) : []).map(async agent => {
+ let changes = 0
+ while (running) {
+ const model = agent.engine === 'claude' ? (changes % 2 ? 'opus' : 'sonnet') : (changes % 2 ? 'gpt-5.5' : 'gpt-6-luna')
+ const selectedModel = `runtime-v1:${agent.id}:${agent.engine}:${model}@high`
+ const began = performance.now()
+ try {
+ const answer = await client.request('agent_update', { agentId: agent.id, selectedModel }, 45_000)
+ if (answer.error || answer.agent?.selectedModel !== selectedModel) throw new Error(`model control: ${JSON.stringify(answer)}`)
+ if (running) controlLatencies[agent.engine].push(performance.now() - began)
+ changes++
+ } catch (error) { problem ??= error; return }
+ await sleep(250)
+ }
+ })
let readerMetrics: Record<string, any>[] = []
let metrics: Record<string, any>
try { await sleep(seconds * 1000) }
@@ -213,16 +233,21 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
metrics = measured[0]; readerMetrics = measured.slice(1)
}
const after = windows.map(w => w.stats())
- await Promise.all([...workers, reads])
+ await Promise.all([...workers, ...controls, reads])
if (problem) throw problem
expect(metrics!.cpu.percent).toBeGreaterThanOrEqual(0)
expect(Number.isFinite(metrics!.cpu.percent)).toBe(true)
expect(metrics!.memory.rssMax).toBeGreaterThan(0)
expect(metrics!.eventLoop.delaySamples).toBeGreaterThan(0)
if (turning) for (const count of turns) expect(count).toBeGreaterThan(0)
+ if (controlling) for (const agent of saved.slice(0, active)) expect(controlLatencies[agent.engine].length).toBeGreaterThan(0)
latencies.sort((a, b) => a - b)
readLatencies.sort((a, b) => a - b)
report.phases.push({ ...metrics!, readers: readerMetrics,
+ modelControls: Object.fromEntries(Object.entries(controlLatencies).map(([engine, values]) => {
+ values.sort((a, b) => a - b)
+ return [engine, { count: values.length, p50Ms: values[Math.floor(values.length * .5)] ?? null, p95Ms: values[Math.floor(values.length * .95)] ?? null }]
+ })),
historyReads: { count: readLatencies.length, p50Ms: readLatencies[Math.floor(readLatencies.length * .5)] ?? null, p95Ms: readLatencies[Math.floor(readLatencies.length * .95)] ?? null },
coreAndReaders: { cpuPercent: metrics!.cpu.percent + readerMetrics.reduce((sum, m) => sum + m.cpu.percent, 0), rssMean: metrics!.memory.rssMean + readerMetrics.reduce((sum, m) => sum + m.memory.rssMean, 0) }, turns, completedTurns: turns.reduce((a, b) => a + b, 0),
turnLatencyMs: { p50: latencies[Math.floor(latencies.length * .5)] ?? null, p95: latencies[Math.floor(latencies.length * .95)] ?? null },
@@ -268,6 +293,7 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
await sleep(warmup * 1000)
await phase('populated-idle', false)
await phase('active', true)
+ if (measureControls) await phase('model-control', false, true)
report.agents = saved
report.state = 'passed'
} catch (error) {
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.ts
index dc6a1d103..3084bf8e3 100644
--- a/cli/src/architecture.spec.ts
+++ b/cli/src/architecture.spec.ts
@@ -143,9 +143,9 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {
/** What is not the core's, by path: each goes to a service or its own process, in the plan's order. */
const EDGE: RegExp[] = [
- /^engines\/(claude|codex)\/(screen|composer|activity|stoppedGoal)\.ts$/,
+ /^engines\/(claude|codex)\/(screen|composer|activity|stoppedGoal|modelControl|modelPicker)\.ts$/,
/^lib\/(askQuestion|runtimeProfileController|composerScreen|teamWriteHold|messageHold|terminalActivity|codexTurnRecovery)\.ts$/,
- /^engines\/screens\.ts$/,
+ /^engines\/(screens|modelControls)\.ts$/,
// 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$/,
diff --git a/cli/src/core/AGENTS.md b/cli/src/core/AGENTS.md
index c576f414c..b6f4e1380 100644
--- a/cli/src/core/AGENTS.md
+++ b/cli/src/core/AGENTS.md
@@ -37,8 +37,7 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGE
validates bounded replies, retains acknowledged cursors and owns binding/turn state. The explicit
inline/older-master compatibility path is the only live parser or runtime profile implementation
composition in core. Screen reads are bounded and fenced to the worker connection and session binding
- ([screen boundary](../../../docs/design/2026-10-08-engine-screen.md)). Core keeps accepted profiles and control authority; native picker drivers
- remain to migrate. See [runtime profiles](../../../docs/design/2026-10-08-engine-runtime.md).
+ ([screen boundary](../../../docs/design/2026-10-08-engine-screen.md)). Core keeps accepted profiles and control authority; native model drivers run in workers through [revocable control grants](../../../docs/design/2026-10-08-engine-model-control.md). 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/engines/modelControls.spec.ts b/cli/src/core/engines/modelControls.spec.ts
new file mode 100644
index 000000000..b6a0c75ad
--- /dev/null
+++ b/cli/src/core/engines/modelControls.spec.ts
@@ -0,0 +1,288 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { RegisteredSession } from '../../lib/registry.js'
+import { encodeRuntimeProfile } from '../../engines/kit/runtime.js'
+import { RuntimeProfileControlError, type EngineModelControl, type ModelControlHost } from '../../engines/facets/modelControl.js'
+import { engineModelControlRequests } from '../../engines/worker/modelControlRequests.js'
+import { MODEL_CONTROL_APPLY, MODEL_CONTROL_CAPABILITIES, MODEL_CONTROL_HOST, MODEL_CONTROL_WAIT_MS, MODEL_CONTROL_CHECK_MS } from '../../engines/worker/modelControlProtocol.js'
+import { createModelControls } from './modelControls.js'
+
+const state = { model: null, effort: null, cliVersion: null, observedAt: null, mode: 'default' as const }
+const denied = { version: 1, error: 'BUSY' }
+const catalog = [{ slug: 'next', displayName: 'Next', listed: true, defaultEffort: 'high', efforts: ['high'] }]
+const deferred = <T>() => { let resolve!: (value: T) => void; const promise = new Promise<T>(yes => { resolve = yes }); return { promise, resolve } }
+function setup(engine: 'claude' | 'codex' = 'claude', isolated = true, connected = true) {
+ let session: RegisteredSession | undefined = {
+ agentId: 'agent', sessionId: 'session', engine, model: 'old', cliVersion: '1.0.0', cwd: '/tmp', transcriptPath: '/tmp/session',
+ active: true, registeredAt: 1, boundAt: 1, tmuxPane: '%1', runtimes: [], primaryRuntimeKey: 'tmux:%1', processIdentity: null,
+ } as unknown as RegisteredSession
+ const target = { sessionId: 'agent', engine, model: 'next', effort: 'high', id: '' }
+ target.id = encodeRuntimeProfile(target)
+ const input = { target, current: null, options: [{ id: target.id, displayName: 'Next' }] }
+ const check = { stage: 'target' as const, target, state }
+ const native: EngineModelControl = { validate: vi.fn(async () => {}), apply: vi.fn(async () => {}) }
+ const service = `engine-${engine}`
+ let token = ''
+ const asks: Record<string, unknown>[] = []
+ const deps = {
+ handles: () => isolated, inline: vi.fn(() => native as EngineModelControl | undefined), resolve: () => session,
+ call: vi.fn(async (_service: string, method: string, payload: Record<string, unknown>, _ms: number): Promise<Record<string, unknown>> => {
+ if (payload.token) token = payload.token as string
+ asks.push(payload)
+ if (!connected) { controls.connected(service); connected = true }
+ // The real link adds requestId. Keep that metadata in this fixture.
+ return { ...await requests[method]({ ...payload, requestId: 'core-request' }, { owner: true, local: true }), requestId: 'routed-reply' }
+ }),
+ catalog: vi.fn(async () => catalog), capture: vi.fn(async () => 'screen' as string | null),
+ text: vi.fn(async (_id: string, _text: string, allowed: () => boolean) => allowed()),
+ key: vi.fn(async (_id: string, _key: string, allowed: () => boolean) => allowed()),
+ waitForModel: vi.fn(async () => true), waitForProfile: vi.fn(async () => false), confirmEffort: vi.fn(),
+ }
+ const controls = createModelControls(deps)
+ const request = (action: unknown, extra: Record<string, unknown> = {}, source = service) => controls.answer(source, MODEL_CONTROL_HOST,
+ { version: 1, token, action, query: MODEL_CONTROL_HOST, requestId: 'worker-query', ...extra })!
+ const requests = engineModelControlRequests(engine, { load: async () => native, recycle: vi.fn(),
+ query: (query, payload) => controls.answer(service, query, { ...payload, query, requestId: 'worker-query' })! })
+ if (connected) controls.connected(service)
+ return { controls, deps, target, check, input, native, asks, service, request,
+ session: () => session!, replace: (value?: RegisteredSession) => { session = value },
+ port: () => controls.forSession(session!)!,
+ }
+}
+
+describe('model-control authority', () => {
+ beforeEach(() => vi.useFakeTimers())
+ afterEach(() => vi.useRealTimers())
+
+ it.each(['claude', 'codex'] as const)('routes %s validation and each effect through the real private envelopes', async engine => {
+ const s = setup(engine, true, false), p = s.port()
+ let owned: ModelControlHost | undefined
+ s.native.apply = vi.fn(async (input, host) => {
+ owned = host
+ expect(input.session).not.toHaveProperty('tmuxPane')
+ expect(input.catalog).toEqual(catalog)
+ expect(await host.catalog()).toEqual(catalog)
+ expect(await host.capture(80)).toBe('screen')
+ expect(await host.text('/model next')).toBe(true)
+ expect(await host.key('Enter')).toBe(true)
+ expect(await host.waitForModel(1200)).toBe(true)
+ expect(await host.waitForProfile(8000)).toBe(false)
+ await host.confirmEffort('high')
+ })
+ await p.validate(s.check)
+ await p.validate({ ...s.check, stage: 'scope', pane: { idle: true, draft: false, dialog: false, plan: false } })
+ await p.apply(s.input)
+ expect(s.deps.catalog).toHaveBeenCalledTimes(2) // preflight + the explicit refresh
+ expect(s.deps.confirmEffort).toHaveBeenCalledWith('session', 'high')
+ expect(s.deps.text).toHaveBeenCalledWith('agent', '/model next', expect.any(Function))
+ expect(s.deps.inline).not.toHaveBeenCalled()
+ expect(s.deps.call.mock.calls.filter(c => c[1] === MODEL_CONTROL_CAPABILITIES)).toHaveLength(1)
+ await expect(owned!.key('Escape')).rejects.toMatchObject({ code: 'BUSY' })
+ expect(await s.request({ kind: 'key', key: 'Enter' })).toEqual(denied)
+ })
+
+ it('uses the same revocable broker in explicit inline mode, and leaves other engines alone', async () => {
+ const s = setup('claude', false), p = s.port()
+ let host!: ModelControlHost
+ s.native.apply = vi.fn(async (_input, value) => { host = value; await value.key('Enter') })
+ await p.validate(s.check)
+ await p.apply(s.input)
+ expect(s.deps.call).not.toHaveBeenCalled()
+ await expect(host.text('/model late')).rejects.toMatchObject({ code: 'BUSY' })
+ expect(s.controls.forSession({ ...s.session(), engine: 'cursor' })).toBeUndefined()
+ expect(s.controls.answer(s.service, 'live', {})).toBeNull()
+ s.controls.connected('other'); s.controls.disconnected('other')
+ s.deps.inline.mockReturnValue(undefined)
+ await expect(s.port().validate(s.check)).rejects.toMatchObject({ code: 'BUSY' })
+ await expect(s.port().apply(s.input)).rejects.toMatchObject({ code: 'BUSY' })
+ })
+
+ it('rejects an inline result after replacement and leaves other engines’ grants intact', async () => {
+ const s = setup('claude', false)
+ s.native.apply = vi.fn(async (_input, host) => {
+ s.controls.disconnected('engine-codex')
+ expect(await host.key('Enter')).toBe(true)
+ })
+ await s.port().apply(s.input)
+ s.native.validate = vi.fn(async () => { s.session().boundAt = 2 })
+ await expect(s.port().validate(s.check)).rejects.toMatchObject({ code: 'BUSY' })
+ })
+
+ it('preserves engine refusal codes and contains unexpected exceptions', async () => {
+ const s = setup(), p = s.port()
+ s.native.validate = vi.fn(async () => { throw new RuntimeProfileControlError('EFFORT_UNSUPPORTED') })
+ await expect(p.validate(s.check)).rejects.toMatchObject({ code: 'EFFORT_UNSUPPORTED' })
+ s.deps.call.mockRejectedValueOnce(new Error('broken pipe'))
+ await expect(p.validate(s.check)).rejects.toMatchObject({ code: 'BUSY' })
+ s.deps.call.mockResolvedValueOnce({ version: 1, error: 'UNKNOWN' })
+ await expect(p.validate(s.check)).rejects.toMatchObject({ code: 'BUSY' })
+ s.deps.call.mockResolvedValueOnce({ version: 1, ok: false })
+ await expect(p.validate(s.check)).rejects.toMatchObject({ code: 'BUSY' })
+ s.deps.call.mockResolvedValueOnce({ version: 2, ok: true })
+ await expect(p.validate(s.check)).rejects.toMatchObject({ code: 'BUSY' })
+ expect(s.deps.inline).not.toHaveBeenCalled()
+ })
+
+ it.each(['version', 'modelControl', 'engine'])('rejects an incompatible capability %s without an inline fallback', async field => {
+ const s = setup()
+ s.deps.call.mockResolvedValueOnce({ version: 1, modelControl: 1, engine: 'claude', [field]: 'wrong' })
+ await expect(s.port().validate(s.check)).rejects.toMatchObject({ code: 'BUSY' })
+ expect(s.native.validate).not.toHaveBeenCalled()
+ expect(s.deps.inline).not.toHaveBeenCalled()
+ })
+
+ it.each(['capability', 'validation', 'apply'] as const)('rejects unexpected fields in a worker %s reply', async phase => {
+ const s = setup(), p = s.port()
+ if (phase !== 'capability') await p.validate(s.check)
+ s.deps.call.mockResolvedValueOnce({ version: 1, ...(phase === 'capability' ? { modelControl: 1, engine: 'claude' } : { ok: true }), terminal: '%9' })
+ await expect(phase === 'apply' ? p.apply(s.input) : p.validate(s.check)).rejects.toMatchObject({ code: 'BUSY' })
+ expect(s.deps.inline).not.toHaveBeenCalled()
+ expect(s.deps.key).not.toHaveBeenCalled()
+ })
+
+ it('fences in-place rebinding during catalog reads and before any request starts', async () => {
+ const s = setup(), p = s.port()
+ s.deps.catalog.mockImplementationOnce(async () => { s.session().sessionId = 'replacement'; return catalog })
+ await expect(p.validate(s.check)).rejects.toMatchObject({ code: 'BUSY' })
+ expect(s.native.validate).not.toHaveBeenCalled()
+ await expect(p.apply(s.input)).rejects.toMatchObject({ code: 'BUSY' })
+ s.replace()
+ await expect(p.validate(s.check)).rejects.toMatchObject({ code: 'BUSY' })
+ })
+
+ it('does not resume UI intent after a worker reconnect or while disconnected', async () => {
+ const s = setup(), p = s.port()
+ await p.validate(s.check)
+ s.controls.disconnected(s.service)
+ await expect(p.apply(s.input)).rejects.toMatchObject({ code: 'BUSY' })
+ s.controls.connected(s.service)
+ await expect(p.apply(s.input)).rejects.toMatchObject({ code: 'BUSY' })
+ await s.port().apply(s.input)
+ await expect(p.apply(s.input)).rejects.toMatchObject({ code: 'BUSY' }) // new worker's capability cache cannot rescue an old intent
+ s.controls.connected(s.service) // replacement connection, without an observed close
+ await expect(p.validate(s.check)).rejects.toMatchObject({ code: 'BUSY' })
+ })
+
+ it('rejects invalid snapshots before native interpretation', async () => {
+ const s = setup(), p = s.port()
+ await expect(p.validate({ ...s.check, target: { ...s.target, model: 'other' } })).rejects.toMatchObject({ code: 'BUSY' })
+ await expect(p.apply({ ...s.input, target: { ...s.target, engine: 'codex' } })).rejects.toMatchObject({ code: 'BUSY' })
+ expect(s.native.apply).not.toHaveBeenCalled()
+ expect(s.native.validate).not.toHaveBeenCalled()
+ })
+
+ it('bounds hung startup and refuses overflow without queuing a later UI action', async () => {
+ const s = setup()
+ s.deps.call.mockImplementation(() => new Promise(() => {}))
+ const results = Array.from({ length: 4 }, () => s.port().validate(s.check).catch(e => e.code))
+ await expect(s.port().apply(s.input)).rejects.toMatchObject({ code: 'BUSY' })
+ await vi.advanceTimersByTimeAsync(MODEL_CONTROL_CHECK_MS + 1)
+ expect(await Promise.all(results)).toEqual(['BUSY', 'BUSY', 'BUSY', 'BUSY'])
+ expect(s.deps.call).toHaveBeenCalledTimes(4)
+ expect(s.deps.key).not.toHaveBeenCalled()
+ })
+
+ it.each(['timeout', 'disconnect', 'rebind', 'completed'] as const)('revokes delayed terminal validation on %s', async reason => {
+ const s = setup(), p = s.port(), dispatched: string[] = [], done = deferred<void>(), started = deferred<void>()
+ let permitted!: () => boolean
+ s.deps.key.mockImplementation(async (_id, key, allowed) => {
+ permitted = allowed; started.resolve()
+ await done.promise
+ if (allowed()) dispatched.push(key)
+ return allowed()
+ })
+ s.deps.call.mockImplementation(async (_service, method, payload) => {
+ if (method === MODEL_CONTROL_CAPABILITIES) return { version: 1, modelControl: 1, engine: 'claude' }
+ const answer = s.controls.answer(s.service, MODEL_CONTROL_HOST, { version: 1, token: payload.token, action: { kind: 'key', key: 'Enter' } })!
+ if (reason === 'completed') { void answer; return { version: 1, ok: true } }
+ await answer
+ return { version: 1, ok: true }
+ })
+ const outcome = p.apply(s.input).then(() => 'ok', e => e.code)
+ await started.promise
+ if (reason === 'timeout') await vi.advanceTimersByTimeAsync(MODEL_CONTROL_WAIT_MS + 1)
+ if (reason === 'disconnect') s.controls.disconnected(s.service)
+ if (reason === 'rebind') s.session().processIdentity = { pid: 999, startTime: 'new' } as any
+ if (reason === 'completed') await outcome
+ expect(permitted()).toBe(false)
+ done.resolve()
+ expect(await outcome).toBe('BUSY')
+ expect(dispatched).toEqual([])
+ })
+
+ it('bounds the complete operation even when the worker never answers, then denies its late query', async () => {
+ const s = setup(), p = s.port(), entered = deferred<void>()
+ await p.validate(s.check)
+ let payload: Record<string, unknown> = {}
+ s.deps.call.mockImplementation(async (_service, _method, value) => { payload = value; entered.resolve(); return new Promise(() => {}) })
+ const result = p.apply(s.input).catch(e => e.code)
+ await entered.promise
+ await vi.advanceTimersByTimeAsync(MODEL_CONTROL_WAIT_MS + 1)
+ expect(await result).toBe('BUSY')
+ expect(await s.controls.answer(s.service, MODEL_CONTROL_HOST, { version: 1, token: payload.token, action: { kind: 'key', key: 'Enter' } })).toEqual(denied)
+ })
+
+ it('does not grant other services, targets, operations or effects without an active request', async () => {
+ const s = setup()
+ expect(await s.request({ kind: 'key', key: 'Enter' })).toEqual(denied)
+ s.native.apply = vi.fn(async () => {
+ expect(await s.request({ kind: 'key', key: 'Enter' }, {}, 'engine-codex')).toEqual(denied)
+ expect(await s.request({ kind: 'key', key: 'Enter' }, { token: 'guess' })).toEqual(denied)
+ for (const action of [{ kind: 'key', key: 'C-c' }, { kind: 'text', text: '/model next\nother' }, { kind: 'capture', lines: 101 }, { kind: 'key', key: 'Enter', target: '%9' }]) {
+ expect(await s.request(action)).toEqual(denied)
+ }
+ expect(await s.request({ kind: 'key', key: 'Enter' }, { extra: true })).toEqual(denied)
+ expect(s.deps.key).not.toHaveBeenCalled()
+ expect(await s.request({ kind: 'confirmEffort', effort: 'ultra' })).toEqual(denied)
+ expect(await s.request({ kind: 'key', key: 'Enter' })).toEqual(denied)
+ })
+ await expect(s.port().apply(s.input)).rejects.toMatchObject({ code: 'BUSY' })
+ expect(s.deps.confirmEffort).not.toHaveBeenCalled()
+ })
+
+ it.each(['query', 'write'] as const)('limits the %s budget for one granted control', async kind => {
+ const s = setup()
+ s.native.apply = vi.fn(async () => {
+ const action = kind === 'query' ? { kind: 'capture', lines: 100 } : { kind: 'key', key: 'Enter' }
+ for (let i = 0; i < (kind === 'query' ? 128 : 32); i++) expect(await s.request(action)).not.toHaveProperty('error')
+ expect(await s.request(action)).toEqual(denied)
+ expect(await s.request({ kind: 'key', key: 'Escape' })).toEqual(denied)
+ })
+ await expect(s.port().apply(s.input)).rejects.toMatchObject({ code: 'BUSY' })
+ })
+
+ it('revokes overlapping host requests before the delayed effect can dispatch', async () => {
+ const s = setup(), effect = deferred<void>()
+ s.deps.key.mockImplementation(async (_id, _key, allowed) => { await effect.promise; return allowed() })
+ s.native.apply = vi.fn(async () => {
+ const first = s.request({ kind: 'key', key: 'Enter' })
+ expect(await s.request({ kind: 'capture', lines: 10 })).toEqual(denied)
+ effect.resolve()
+ expect(await first).toEqual(denied)
+ })
+ await expect(s.port().apply(s.input)).rejects.toMatchObject({ code: 'BUSY' })
+ })
+
+ it.each(['throw', 'oversize'] as const)('contains a %s from the host and revokes subsequent effects', async kind => {
+ const s = setup()
+ if (kind === 'throw') s.deps.capture.mockRejectedValueOnce(new Error('gone'))
+ else s.deps.capture.mockResolvedValueOnce('x'.repeat(256 * 1024 + 1))
+ s.native.apply = vi.fn(async () => {
+ expect(await s.request({ kind: 'capture', lines: 10 })).toEqual(denied)
+ expect(await s.request({ kind: 'key', key: 'Enter' })).toEqual(denied)
+ })
+ await expect(s.port().apply(s.input)).rejects.toMatchObject({ code: 'BUSY' })
+ })
+
+ it('bounds the aggregate catalog reply even when every entry fits, then revokes the grant', async () => {
+ const s = setup()
+ s.deps.catalog.mockResolvedValueOnce(Array.from({ length: 512 }, (_, i) => ({
+ ...catalog[0], slug: `model-${i}`, displayName: 'x'.repeat(2000), efforts: ['high', 'x'.repeat(2000)],
+ })))
+ s.native.apply = vi.fn(async () => {
+ expect(await s.request({ kind: 'catalog' })).toEqual(denied)
+ expect(await s.request({ kind: 'key', key: 'Enter' })).toEqual(denied)
+ })
+ await expect(s.port().apply(s.input)).rejects.toMatchObject({ code: 'BUSY' })
+ expect(s.deps.key).not.toHaveBeenCalled()
+ })
+})
diff --git a/cli/src/core/engines/modelControls.ts b/cli/src/core/engines/modelControls.ts
new file mode 100644
index 000000000..50ba0407a
--- /dev/null
+++ b/cli/src/core/engines/modelControls.ts
@@ -0,0 +1,148 @@
+import { randomBytes } from 'node:crypto'
+import type { EngineModelControl } from '../../engines/facets/modelControl.js'
+import { RuntimeProfileControlError, type RuntimeProfileErrorCode } from '../../engines/facets/modelControl.js'
+import type { RuntimeCatalogModel, RuntimeProfile } from '../../engines/facets/runtime.js'
+import { readerEngine, READER_SERVICES } from '../../engines/worker/protocol.js'
+import { createModelControlHost } from '../../engines/worker/modelControlHost.js'
+import { modelControlAction, modelControlAnswer, modelControlCheck, modelControlEnvelope, modelControlInput, modelControlSize,
+ MODEL_CONTROL_APPLY, MODEL_CONTROL_CAPABILITIES, MODEL_CONTROL_CHECK_MS, MODEL_CONTROL_ERRORS, MODEL_CONTROL_HOST,
+ MODEL_CONTROL_IN_FLIGHT, MODEL_CONTROL_QUERIES, MODEL_CONTROL_QUERY_MS, MODEL_CONTROL_VALIDATE,
+ MODEL_CONTROL_VERSION, MODEL_CONTROL_WAIT_MS, MODEL_CONTROL_WRITES } from '../../engines/worker/modelControlProtocol.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import type { ModelControlFor } from '../../lib/modelControl.js'
+import { sessionBinding } from './sessionBinding.js'
+
+export interface ModelControlsDeps {
+ handles(engine: string): boolean
+ inline(engine: string): EngineModelControl | undefined
+ resolve(id: string): RegisteredSession | undefined
+ call(service: string, method: string, payload: Record<string, unknown>, waitMs: number): Promise<Record<string, unknown>>
+ catalog(session: RegisteredSession): Promise<RuntimeCatalogModel[]>
+ capture(target: string, lines: number): Promise<string | null>
+ text(target: string, text: string, allowed: () => boolean): Promise<boolean>
+ key(target: string, key: string, allowed: () => boolean): Promise<boolean>
+ waitForModel(sessionId: string, ms: number): Promise<boolean>
+ waitForProfile(sessionId: string, ms: number): Promise<boolean>
+ confirmEffort(sessionId: string, effort: string): void
+}
+function fail(): never { throw new RuntimeProfileControlError('BUSY') }
+async function bounded<T>(work: Promise<T>, ms: number): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined
+ try { return await Promise.race([work, new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new RuntimeProfileControlError('BUSY')), ms) })]) }
+ finally { clearTimeout(timer) }
+}
+interface Grant {
+ service: string
+ session: RegisteredSession
+ target: RuntimeProfile
+ allowed(): boolean
+ pending: boolean
+ queries: number
+ writes: number
+}
+
+/** Core holds identity, input authority and confirmation state. Workers receive none of those handles. */
+export function createModelControls(deps: ModelControlsDeps) {
+ const states = new Map(Object.values(READER_SERVICES).map(service => [service as string, { generation: 0, connected: false, capable: false, pending: 0 }]))
+ const grants = new Map<string, Grant>()
+ const answer = (service: string, query: string, payload: Record<string, unknown>): Promise<Record<string, unknown>> | null => {
+ if (query !== MODEL_CONTROL_HOST) return null
+ return (async () => {
+ const denied = { version: MODEL_CONTROL_VERSION, error: 'BUSY' }
+ // query/requestId are supplied by the authenticated link, not terminal authority.
+ if (!modelControlEnvelope(payload, ['query', 'token', 'action']) || typeof payload.token !== 'string' || !modelControlAction(payload.action)) return denied
+ const grant = grants.get(payload.token), action = payload.action
+ if (!grant || grant.service !== service) return denied
+ if (!grant.allowed() || grant.pending || ++grant.queries > MODEL_CONTROL_QUERIES
+ || ((action.kind === 'text' || action.kind === 'key') && ++grant.writes > MODEL_CONTROL_WRITES)
+ || (action.kind === 'confirmEffort' && action.effort !== grant.target.effort)) { grants.delete(payload.token); return denied }
+ grant.pending = true
+ try {
+ const { session, allowed } = grant
+ const value = await bounded((async () => {
+ if (action.kind === 'catalog') return deps.catalog(session)
+ if (action.kind === 'capture') return deps.capture(session.agentId, action.lines)
+ if (action.kind === 'text') return deps.text(session.agentId, action.text, allowed)
+ if (action.kind === 'key') return deps.key(session.agentId, action.key, allowed)
+ if (action.kind === 'waitForModel') return deps.waitForModel(session.sessionId, action.ms)
+ if (action.kind === 'waitForProfile') return deps.waitForProfile(session.sessionId, action.ms)
+ deps.confirmEffort(session.sessionId, action.effort)
+ return true
+ })(), MODEL_CONTROL_QUERY_MS)
+ const reply = { version: MODEL_CONTROL_VERSION, value }
+ if (!allowed() || !modelControlAnswer(action, value) || !modelControlSize(reply)) { grants.delete(payload.token); return denied }
+ return reply
+ } catch { grants.delete(payload.token); return denied }
+ finally { grant.pending = false }
+ })()
+ }
+ const forSession: ModelControlFor = registered => {
+ const engine = registered.engine
+ if (!readerEngine(engine)) return undefined
+ // Snapshot before the controller's first await: in-place registry edits cannot retarget this request.
+ const session = structuredClone(registered), binding = sessionBinding(registered), service = READER_SERVICES[engine]
+ const isolated = deps.handles(engine), state = states.get(service)!
+ const generation = state.generation + (state.connected ? 0 : 1)
+ const sameSession = () => sessionBinding(deps.resolve(session.agentId)) === binding
+ const current = () => sameSession() && (!isolated || (state.connected && state.generation === generation))
+ let catalog: RuntimeCatalogModel[] = []
+ const run = async (ms: number, work: (allowed: () => boolean, call: (method: string, payload: Record<string, unknown>) => Promise<void>) => Promise<void>) => {
+ if (!sameSession() || state.pending >= MODEL_CONTROL_IN_FLIGHT) fail()
+ state.pending++
+ let active = true
+ const deadline = performance.now() + ms
+ const allowed = () => active && performance.now() < deadline && current()
+ const call = async (method: string, payload: Record<string, unknown>) => {
+ const reply = await deps.call(service, method, { version: MODEL_CONTROL_VERSION, ...payload }, Math.max(1, Math.ceil(deadline - performance.now())))
+ if (!allowed() || !modelControlEnvelope(reply, ['ok', 'error'])) fail()
+ if (reply.error !== undefined) throw new RuntimeProfileControlError(MODEL_CONTROL_ERRORS.includes(reply.error as RuntimeProfileErrorCode) ? reply.error as RuntimeProfileErrorCode : 'BUSY')
+ if (reply.ok !== true) fail()
+ }
+ try {
+ await bounded((async () => {
+ if (isolated && !state.capable) {
+ // Allow only the first startup connection. A replacement cannot resume an old UI intent.
+ if (state.generation !== generation && (state.connected || state.generation !== generation - 1)) fail()
+ const reply = await deps.call(service, MODEL_CONTROL_CAPABILITIES, { version: MODEL_CONTROL_VERSION }, ms)
+ if (!allowed() || !modelControlEnvelope(reply, ['modelControl', 'engine']) || reply.modelControl !== MODEL_CONTROL_VERSION || reply.engine !== engine) fail()
+ state.capable = true
+ }
+ if (!allowed()) fail()
+ await work(allowed, call)
+ if (!allowed()) fail()
+ })(), ms)
+ } catch (error) { throw error instanceof RuntimeProfileControlError ? error : new RuntimeProfileControlError('BUSY') }
+ finally { active = false; state.pending-- }
+ }
+ return {
+ validate: check => run(MODEL_CONTROL_CHECK_MS, async (allowed, call) => {
+ if (check.stage === 'target') catalog = await deps.catalog(session)
+ const value = modelControlCheck({ ...check, session, catalog }, engine)
+ if (!allowed() || !value) fail()
+ if (isolated) await call(MODEL_CONTROL_VALIDATE, { check: value })
+ else { const control = deps.inline(engine); if (!control) fail(); await control.validate(value!) }
+ }),
+ apply: async input => {
+ const token = randomBytes(32).toString('hex')
+ try { await run(MODEL_CONTROL_WAIT_MS, async (allowed, call) => {
+ const value = modelControlInput({ ...input, session, catalog }, engine)
+ if (!value) fail()
+ grants.set(token, { service, session, target: value!.target, allowed: () => allowed() && grants.has(token), pending: false, queries: 0, writes: 0 })
+ if (isolated) await call(MODEL_CONTROL_APPLY, { input: value, token })
+ else {
+ const control = deps.inline(engine); if (!control) fail()
+ await control.apply(value!, createModelControlHost(action => answer(service, MODEL_CONTROL_HOST, { version: MODEL_CONTROL_VERSION, token, action })!))
+ }
+ const grant = grants.get(token)
+ if (!grant || grant.pending) fail()
+ }) } finally { grants.delete(token) }
+ },
+ }
+ }
+ const connection = (service: string, connected: boolean) => {
+ const state = states.get(service)
+ if (state) { state.generation++; state.connected = connected; state.capable = false }
+ for (const [token, grant] of grants) if (grant.service === service) grants.delete(token)
+ }
+ return { forSession, answer, connected: (service: string) => connection(service, true), disconnected: (service: string) => connection(service, false) }
+}
diff --git a/cli/src/core/engines/runtimeSessions.spec.ts b/cli/src/core/engines/runtimeSessions.spec.ts
index 989589ad8..25e8bb657 100644
--- a/cli/src/core/engines/runtimeSessions.spec.ts
+++ b/cli/src/core/engines/runtimeSessions.spec.ts
@@ -228,6 +228,19 @@ describe('core runtime profile authority', () => {
await vi.advanceTimersByTimeAsync(120); expect(t.changed).toHaveBeenCalledTimes(2)
})
+ it('does not finish a replacement binding’s model transaction with an old session snapshot', async () => {
+ const t = setup(); await t.seed()
+ const previous = structuredClone(t.s)
+ expect(t.sessions.beginControl(previous, profile(previous))).toBe(true)
+ t.s.boundAt = 2
+ await t.seed()
+ expect(t.sessions.beginControl(t.s, profile(t.s))).toBe(true)
+ t.sessions.finishControl(previous)
+ expect(t.sessions.beginControl(t.s, profile(t.s))).toBe(false)
+ t.sessions.finishControl(t.s)
+ expect(t.sessions.beginControl(t.s, profile(t.s))).toBe(true)
+ })
+
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()
diff --git a/cli/src/core/engines/runtimeSessions.ts b/cli/src/core/engines/runtimeSessions.ts
index 9219e9284..9921296af 100644
--- a/cli/src/core/engines/runtimeSessions.ts
+++ b/cli/src/core/engines/runtimeSessions.ts
@@ -221,7 +221,7 @@ export function createRuntimeSessions(deps: RuntimeSessionDeps) {
},
finishControl(s: RegisteredSession): void {
const view = byId(s.agentId)
- if (!view) return
+ if (!view || view.identity !== binding(s)) return
view.control = undefined; view.revision++; wake(view.sessionId); notify(view)
},
confirmEffort(id: string, effort: string): void {
diff --git a/cli/src/core/engines/screens.ts b/cli/src/core/engines/screens.ts
index d183cfe90..982798817 100644
--- a/cli/src/core/engines/screens.ts
+++ b/cli/src/core/engines/screens.ts
@@ -1,3 +1,4 @@
+import { sessionBinding as identity } from './sessionBinding.js'
import type { ScreenReading } from '../../engines/facets/screen.js'
import type { AgentEngine } from '../../engines/types.js'
import { screenCapture } from '../../engines/worker/screenProtocol.js'
@@ -13,13 +14,6 @@ export interface ScreenDeps {
inline(engine: AgentEngine, capture: string | null): ScreenReading | undefined
}
-/** Snapshot scalars: registry records may be edited in place while a worker answers. */
-function identity(session: RegisteredSession | undefined): string {
- return session ? JSON.stringify([session.agentId, session.sessionId, session.engine, session.active,
- session.registeredAt, session.boundAt, session.transcriptPath, session.tmuxPane,
- session.primaryRuntimeKey, session.runtimes, session.processIdentity]) : ''
-}
-
export function createScreens(deps: ScreenDeps) {
const read: ScreenReader = async (session, capture) => {
if (capture !== null && !screenCapture(capture)) return null
diff --git a/cli/src/core/engines/sessionBinding.ts b/cli/src/core/engines/sessionBinding.ts
new file mode 100644
index 000000000..5fa0c0e89
--- /dev/null
+++ b/cli/src/core/engines/sessionBinding.ts
@@ -0,0 +1,7 @@
+import type { RegisteredSession } from '../../lib/registry.js'
+/** Registry records can change in place while an engine answers. Retain scalar identity, never an alias. */
+export function sessionBinding(session: RegisteredSession | undefined): string {
+ return session ? JSON.stringify([session.agentId, session.sessionId, session.engine, session.active,
+ session.registeredAt, session.boundAt, session.transcriptPath, session.tmuxPane,
+ session.primaryRuntimeKey, session.runtimes, session.processIdentity]) : ''
+}
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index f11d78793..fddd6261f 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -1,3 +1,5 @@
+import { createModelControls } from './engines/modelControls.js'
+import { masterRunsEngineModelControl } from '../harnessd/services.js'
import { createScreens } from './engines/screens.js'
import { createScreenTransport } from './engines/screenTransport.js'
import { legacyScreen } from '../lib/legacyScreen.js'
@@ -545,10 +547,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// 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 modelControlHosted = masterRunsEngineModelControl(process.env, process.ppid)
+ const isolatedModelControl = (engine: string): boolean => modelControlHosted && isolatedLive(engine)
const screenHosted = masterRunsEngineScreen(process.env, process.ppid)
const isolatedScreen = (engine: string): boolean => screenHosted && isolatedLive(engine)
const isolatedRuntime = (engine: string): boolean => runtimeHosted && isolatedLive(engine)
- const inline = KNOWN_SERVICES.some((name) => !outOfProcess.has(name)) || !runtimeHosted || !screenHosted
+ const inline = KNOWN_SERVICES.some((name) => !outOfProcess.has(name)) || !runtimeHosted || !screenHosted || !modelControlHosted
? await import('../services/inline.js') : null
let serviceLinksRef: ServiceLinks | null = null
const runtimeTransport = createRuntimeTransport({
@@ -563,6 +567,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {
legacy: new LegacyRuntimeProfileManager(engine => isolatedRuntime(engine) ? undefined : inline?.runtimeFor(engine)),
handles: isolatedRuntime,
resolve: id => registry.resolve(id), transport: runtimeTransport })
+ const modelControls = createModelControls({
+ handles: isolatedModelControl, inline: engine => inline?.modelControlFor(engine), resolve: id => registry.resolve(id),
+ call: (service, method, payload, waitMs) => serviceLinksRef?.call(service, method, payload, waitMs) ?? Promise.resolve({ error: 'SERVICE_UNAVAILABLE' }),
+ catalog: session => runtimeProfiles.codexCatalog(session), capture: captureTerminal,
+ text: (target, text, allowed) => submitTerminal(target, text, { allowed }), key: keyTerminal,
+ waitForModel: (id, ms) => runtimeProfiles.waitForModel(id, ms), waitForProfile: (id, ms) => runtimeProfiles.waitForProfile(id, ms),
+ confirmEffort: (id, effort) => runtimeProfiles.confirmEffort(id, effort),
+ })
// 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[]> => {
@@ -1190,7 +1202,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
onDemand: new Set([...experiments, ...DEVICES_ON_DEMAND, ...Object.values(READER_SERVICES), 'models', 'gateway', 'shell']),
want: (service) => experimentHooks.want(service),
// The gateway's first: its `backend` reads (the device key log) were refused below as NOT_AN_EXPERIMENT.
- answer: async (service, query, payload) => engineReaders.answer(service) ?? (service === 'gateway' && gatewayLink ? gatewayLink.answer(query, payload) : null) ?? deliveries.answer(service, query, payload)
+ answer: async (service, query, payload) => await modelControls.answer(service, query, payload) ?? engineReaders.answer(service) ?? (service === 'gateway' && gatewayLink ? gatewayLink.answer(query, payload) : null) ?? deliveries.answer(service, query, payload)
?? await answerExperimentQuery(coreApi, experiments, service, query, payload)
?? await terminalWatch.answer(service, query, payload)
?? (service === 'orchestrator' ? orchestratorLink.answer(query, payload) : null)
@@ -1213,6 +1225,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
liveTransport.connected(service)
runtimeTransport.connected(service)
screenTransport.connected(service)
+ modelControls.connected(service)
if (service === 'gateway') gatewayLink?.connected()
if (service === 'teams') teamsLink.on()
if (service === 'devices') devicesLink.connected()
@@ -1224,6 +1237,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
liveTransport.disconnected(service)
runtimeTransport.disconnected(service)
screenTransport.disconnected(service)
+ modelControls.disconnected(service)
if (service === 'gateway') gatewayLink?.disconnected()
if (service === 'devices') devicesLink.disconnected()
if (service === 'wifi') wifiCore.stopped()
@@ -1300,6 +1314,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
backend.models = () => ports.models ?? MODELS_OFF
const runtimeController = new RuntimeProfileController({
+ modelControlFor: modelControls.forSession,
readScreen: screens.read,
manager: runtimeProfiles,
getSession: (id) => registry.resolve(id),
diff --git a/cli/src/core/terminals/control.spec.ts b/cli/src/core/terminals/control.spec.ts
index 8a9cecef3..44e33e9ec 100644
--- a/cli/src/core/terminals/control.spec.ts
+++ b/cli/src/core/terminals/control.spec.ts
@@ -224,3 +224,26 @@ describe('terminal control', () => {
expect(await control.validateTerminal(session)).toBe(false)
})
})
+
+it.each(['key', 'submit'] as const)('checks revoked %s authority after awaited terminal validation', async kind => {
+ const { terminals } = backend()
+ const control = createTerminalControl({ resolve, terminals })
+ const release = control.pinTerminalControl('agent-1')!
+ await control.keyTerminal('agent-1', 'Enter')
+ let permitted = true
+ vi.mocked(terminals.validateLease).mockImplementationOnce(async () => { permitted = false; return true })
+ const result = kind === 'key'
+ ? await control.keyTerminalAction('agent-1', 'Enter', () => permitted)
+ : await control.submitTerminalAction('agent-1', '/model next', { allowed: () => permitted })
+ expect(result).toMatchObject({ state: 'failed', dispatch: 'not_started', reason: 'terminal control revoked' })
+ expect(terminals.sendLegacyKeyLease).toHaveBeenCalledTimes(1)
+ expect(terminals.submitTextLease).not.toHaveBeenCalled()
+ release()
+})
+
+it('passes a live submission guard through to paste/Enter, and permits a guarded key', async () => {
+ const { terminals } = backend(), control = createTerminalControl({ resolve, terminals }), allowed = () => true
+ expect(await control.submitTerminal('agent-1', '/model next', { allowed })).toBe(true)
+ expect(terminals.submitTextForLease).toHaveBeenCalledWith(session, expect.anything(), '/model next', { allowed })
+ expect(await control.keyTerminal('agent-1', 'Enter', allowed)).toBe(true)
+})
diff --git a/cli/src/core/terminals/control.ts b/cli/src/core/terminals/control.ts
index cf4b40031..0d9c55901 100644
--- a/cli/src/core/terminals/control.ts
+++ b/cli/src/core/terminals/control.ts
@@ -86,14 +86,15 @@ export function createTerminalControl({ resolve, terminals }: TerminalControlDep
if (!session) return terminalActionNotStarted('terminal agent is unavailable')
const lease = await leasedTerminal(session)
if (!lease) return terminalActionNotStarted(TERMINAL_LEASE_REFUSED)
+ if (options?.allowed && !options.allowed()) return terminalActionNotStarted('terminal control revoked')
const result = pinnedControls.has(session.agentId)
? await terminals.submitTextLease(lease.value, text, options)
: await terminals.submitTextForLease(session, lease.value, text, options)
if (result.state !== 'succeeded' && pinnedControls.has(session.agentId)) invalidateTerminalControl(session.agentId)
return result
}
- const submitTerminal = async (target: string, text: string): Promise<boolean> => {
- return terminalActionSucceeded(await submitTerminalAction(target, text))
+ const submitTerminal = async (target: string, text: string, options?: SubmitOptions): Promise<boolean> => {
+ return terminalActionSucceeded(await submitTerminalAction(target, text, options))
}
const typeTerminal = async (target: string, text: string): Promise<boolean> => {
const session = terminalSession(target)
@@ -104,17 +105,18 @@ export function createTerminalControl({ resolve, terminals }: TerminalControlDep
if (!succeeded && pinnedControls.has(session.agentId)) invalidateTerminalControl(session.agentId)
return succeeded
}
- const keyTerminalAction = async (target: string, key: string): Promise<TerminalActionResult> => {
+ const keyTerminalAction = async (target: string, key: string, allowed?: () => boolean): Promise<TerminalActionResult> => {
const session = terminalSession(target)
if (!session) return terminalActionNotStarted('terminal session is unavailable')
const lease = await leasedTerminal(session)
if (!lease) return terminalActionNotStarted(TERMINAL_LEASE_REFUSED)
+ if (allowed && !allowed()) return terminalActionNotStarted('terminal control revoked')
const result = await terminals.sendLegacyKeyLease(lease.value, key)
if (result.state !== 'succeeded' && pinnedControls.has(session.agentId)) invalidateTerminalControl(session.agentId)
return result
}
- const keyTerminal = async (target: string, key: string): Promise<boolean> => {
- return terminalActionSucceeded(await keyTerminalAction(target, key))
+ const keyTerminal = async (target: string, key: string, allowed?: () => boolean): Promise<boolean> => {
+ return terminalActionSucceeded(await keyTerminalAction(target, key, allowed))
}
const validateTerminal = async (session: RegisteredSession): Promise<boolean> =>
(await terminals.validate(session)).state === 'alive'
diff --git a/cli/src/engines/README.md b/cli/src/engines/README.md
index 7049fce0f..8166bf78a 100644
--- a/cli/src/engines/README.md
+++ b/cli/src/engines/README.md
@@ -18,8 +18,9 @@ that stream.
launch 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,
-live transcript parsing, runtime profiles/catalogs and screen interpretation run on demand in supervised workers;
+live transcript parsing, runtime profiles/catalogs, screen interpretation and model-control drivers run on demand in supervised workers;
the other facets still run in core. Explicit inline mode and older masters retain inline implementations. See
+[model control](../../../docs/design/2026-10-08-engine-model-control.md),
[screen interpretation](../../../docs/design/2026-10-08-engine-screen.md),
[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. The
diff --git a/cli/src/engines/claude/modelControl.ts b/cli/src/engines/claude/modelControl.ts
new file mode 100644
index 000000000..d827b02c3
--- /dev/null
+++ b/cli/src/engines/claude/modelControl.ts
@@ -0,0 +1,66 @@
+/** Claude Code's model/effort commands. Core supplies one operation's guarded host. */
+import { parseRuntimeProfile } from '../../lib/runtimeProfileWire.js'
+import { stripAnsi } from '../kit/pane.js'
+import { RuntimeProfileControlError, type EngineModelControl, type ModelControlHost, type ModelControlInput } from '../facets/modelControl.js'
+import type { RuntimeProfile } from '../facets/runtime.js'
+const COMMAND_CONFIRM_MS = 8_000
+
+export const modelControl: EngineModelControl = {
+ async validate() {},
+ apply: (input, host) => new ClaudeModelControl(host).apply(input),
+}
+
+class ClaudeModelControl {
+ constructor(private readonly host: ModelControlHost) {}
+ async apply({ target, current, options }: ModelControlInput): Promise<void> {
+ await this.setClaude(target, current, options)
+ }
+
+ private async setClaude(
+ target: RuntimeProfile,
+ current: RuntimeProfile | null,
+ options: Array<{ id: string }>,
+ ): Promise<void> {
+ if (current?.model !== target.model) {
+ if (!await this.host.text(`/model ${target.model}`)) {
+ throw new RuntimeProfileControlError('TMUX_FAILED')
+ }
+ if (!await this.waitClaudeModel()) throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
+ }
+
+ if (current?.effort === target.effort) {
+ await this.host.confirmEffort(target.effort)
+ return
+ }
+
+ const hasExplicitEffort = options.some((option) => {
+ const profile = parseRuntimeProfile(option.id)
+ return profile?.model === target.model && profile.effort !== 'auto'
+ })
+ if (!hasExplicitEffort && target.effort === 'auto') {
+ await this.host.confirmEffort('auto')
+ return
+ }
+ if (!await this.host.text(`/effort ${target.effort}`)) {
+ throw new RuntimeProfileControlError('TMUX_FAILED')
+ }
+ if (!await this.host.waitForProfile(COMMAND_CONFIRM_MS)) {
+ await this.host.key('Enter')
+ if (!await this.host.waitForProfile(2_000)) {
+ throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
+ }
+ }
+ }
+
+ private async waitClaudeModel(): Promise<boolean> {
+ if (await this.host.waitForModel(1_200)) return true
+ const capture = await this.host.capture(80)
+ if (capture && /switch model|change model|continue.*model|re-read.*history/i.test(stripAnsi(capture))) {
+ await this.host.key('Enter')
+ } else {
+ // Claude and Codex can swallow the first Enter immediately after a terminal literal write.
+ await this.host.key('Enter')
+ }
+ return this.host.waitForModel(COMMAND_CONFIRM_MS)
+ }
+}
diff --git a/cli/src/engines/codex/modelControl.ts b/cli/src/engines/codex/modelControl.ts
new file mode 100644
index 000000000..18429178c
--- /dev/null
+++ b/cli/src/engines/codex/modelControl.ts
@@ -0,0 +1,184 @@
+/** Codex owns its picker walk and cleanup; the host can revoke every requested effect. */
+import { chooseCodexRow, codexDigitPressable, codexEffortRows, parseCodexPicker, sameCodexPicker, type CodexCatalogModel, type CodexPicker } from './modelPicker.js'
+import { runtime } from './runtimeProfile.js'
+import { screen } from './screen.js'
+import { RuntimeProfileControlError, type EngineModelControl, type ModelControlHost, type ModelControlInput } from '../facets/modelControl.js'
+import type { RuntimeProfile } from '../facets/runtime.js'
+const COMMAND_CONFIRM_MS = 8_000
+const PICKER_OPEN_MS = 3_000
+const PICKER_STEP_MS = 2_000
+// A refreshed catalog can renumber a picker in place. A digit needs two matching reads.
+const CODEX_SETTLE_MS = 250
+function sleep(ms: number): Promise<void> { return new Promise(resolve => setTimeout(resolve, ms)) }
+function isCodexList(picker: CodexPicker): boolean {
+ return picker.kind === 'quick' || picker.kind === 'models' || picker.kind === 'reserve'
+}
+
+export const modelControl: EngineModelControl = {
+ async validate({ stage, target, catalog, state, pane }) {
+ if (stage === 'target') {
+ const listed = catalog.find(entry => entry.slug === target.model)?.efforts ?? null
+ if (!runtime.effortAllowed!(target.model, target.effort, listed)) throw new RuntimeProfileControlError('EFFORT_UNSUPPORTED')
+ } else if (state.mode === 'plan' || pane?.plan) throw new RuntimeProfileControlError('PLAN_SCOPE_AMBIGUOUS')
+ },
+ apply: (input, host) => new CodexModelControl(host).apply(input),
+}
+
+class CodexModelControl {
+ constructor(private readonly host: ModelControlHost) {}
+ async apply({ target, catalog }: ModelControlInput): Promise<void> {
+ try {
+ await this.setCodex(target, catalog)
+ } catch (error) {
+ // Cleanup still goes through the same grant. A dead or revoked host cannot
+ // press Escape later, into a different question or a replacement engine.
+ for (let attempt = 0; attempt < 3; attempt++) {
+ if (!await this.host.key('Escape').catch(() => false)) break
+ await sleep(100)
+ const next = await this.host.capture(100).catch(() => null)
+ if (!next || !screen.inspect(next).pane.dialog) break
+ }
+ throw error
+ }
+ }
+
+ /**
+ * Codex's `/model`: a quick menu of auto presets with an `All models` row (0.145 and later), the full
+ * list (`Select Model and Effort`), then the chosen model's reasoning picker, each row pressed by its
+ * digit, which selects the row and accepts it. How a row is read and chosen, and why, is in
+ * engines/codex/modelPicker.ts. Confirmed, as it always was, by the `thread_settings_applied` record
+ * Codex writes once the choice is applied (RuntimeProfileManager `ingestCodex`).
+ */
+ private async setCodex(target: RuntimeProfile, catalog: CodexCatalogModel[]): Promise<void> {
+ if (!await this.host.text('/model')) throw new RuntimeProfileControlError('TMUX_FAILED')
+ let picker = await this.waitCodexPicker(() => true, 900)
+ if (!picker) {
+ await this.host.key('Enter')
+ picker = await this.waitCodexPicker(() => true, PICKER_OPEN_MS)
+ }
+ if (!picker) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
+ if (!isCodexList(picker)) {
+ // Opened on a reasoning screen: back to the list it was opened from, so the model is chosen too.
+ if (!await this.host.key('Escape')) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
+ if (!await this.waitCodexPicker(isCodexList, PICKER_STEP_MS)) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
+ }
+ const reached = await this.reachCodexEfforts(target, catalog)
+ if (reached !== 'applied') await this.pickCodexEffort(target, reached)
+ if (!await this.host.waitForProfile(COMMAND_CONFIRM_MS)) {
+ throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
+ }
+ }
+
+ /**
+ * From the list on screen to the target model's reasoning picker, through `All models` when the quick
+ * menu is first; or 'applied' when the model's row applied it at once (a model with one effort).
+ *
+ * Every digit is pressed from a list read twice, CODEX_SETTLE_MS apart, the same both times. Codex
+ * 0.160 draws the list from its cache and redraws it in place when the server answers, and a model
+ * added or reordered then renumbers the rows: a digit read off the first drawing lands on another
+ * model. The reasoning picker that opens names its model in its title, and a title naming any other
+ * model than the row pressed means the list moved anyway, so nothing more is pressed.
+ */
+ private async reachCodexEfforts(
+ target: RuntimeProfile,
+ catalog: CodexCatalogModel[],
+ ): Promise<CodexPicker | 'applied'> {
+ let reread = false
+ for (let lists = 0; lists < 2; lists++) {
+ const list = await this.settledCodexList()
+ if (!list) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
+ let choice = chooseCodexRow(list, target, catalog)
+ if ('error' in choice && choice.error === 'MODEL_UNAVAILABLE' && !reread) {
+ // Codex saves the catalog its picker refreshed from to models_cache.json, so a model or a name
+ // that came with the refresh is there to read now.
+ reread = true
+ catalog = await this.host.catalog()
+ choice = chooseCodexRow(list, target, catalog)
+ }
+ if ('error' in choice) throw new RuntimeProfileControlError(choice.error)
+ if (!await this.host.key(String(choice.row.number))) throw new RuntimeProfileControlError('TMUX_FAILED')
+ if (choice.opens === 'list') {
+ if (!await this.waitCodexPicker((next) => next.kind === 'models', PICKER_STEP_MS)) {
+ throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
+ }
+ continue
+ }
+ if (choice.opens === 'applied') return 'applied'
+ const next = await this.waitCodexAfterModelRow()
+ if (next === 'closed') return 'applied'
+ if (!next) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
+ if (next.model !== choice.row.name) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
+ return next
+ }
+ throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
+ }
+
+ /** The target's effort in its reasoning picker, through Advanced Reasoning for Max and Ultra. */
+ private async pickCodexEffort(target: RuntimeProfile, picker: CodexPicker): Promise<void> {
+ const rows = codexEffortRows(picker)
+ let row = target.effort === 'auto' ? rows.defaultRow : rows.efforts.get(target.effort) ?? null
+ if (row === null && (target.effort === 'max' || target.effort === 'ultra') && rows.advancedRow !== null
+ && codexDigitPressable(rows.advancedRow)) {
+ if (!await this.host.key(String(rows.advancedRow))) throw new RuntimeProfileControlError('TMUX_FAILED')
+ const advanced = await this.waitCodexPicker((next) => next.kind === 'advanced', PICKER_STEP_MS)
+ row = advanced ? codexEffortRows(advanced).efforts.get(target.effort) ?? null : null
+ }
+ if (row === null || !codexDigitPressable(row)) throw new RuntimeProfileControlError('EFFORT_UNSUPPORTED')
+ if (!await this.host.key(String(row))) throw new RuntimeProfileControlError('TMUX_FAILED')
+ }
+
+ /** The first Codex picker on the pane that `wanted` takes, polled until `timeoutMs`. */
+ private async waitCodexPicker(
+ wanted: (picker: CodexPicker) => boolean,
+ timeoutMs: number,
+ ): Promise<CodexPicker | null> {
+ const capture = await this.waitPane((value) => {
+ const picker = parseCodexPicker(value)
+ return !!picker && wanted(picker)
+ }, timeoutMs)
+ return capture ? parseCodexPicker(capture) : null
+ }
+
+ /** A model list that reads the same twice, CODEX_SETTLE_MS apart (see reachCodexEfforts). */
+ private async settledCodexList(): Promise<CodexPicker | null> {
+ let previous: CodexPicker | null = null
+ const deadline = Date.now() + PICKER_STEP_MS
+ while (Date.now() < deadline) {
+ const capture = await this.host.capture(100)
+ const picker = capture ? parseCodexPicker(capture) : null
+ const list = picker && isCodexList(picker) ? picker : null
+ if (list && previous && sameCodexPicker(previous, list)) return list
+ previous = list
+ await sleep(CODEX_SETTLE_MS)
+ }
+ return null
+ }
+
+ /**
+ * After a model's row: its reasoning picker, or 'closed' when the picker went away and the composer
+ * is back, which is a model the catalog did not describe applying its one effort at once.
+ */
+ private async waitCodexAfterModelRow(): Promise<CodexPicker | 'closed' | null> {
+ const deadline = Date.now() + PICKER_STEP_MS
+ while (Date.now() < deadline) {
+ const capture = await this.host.capture(100)
+ if (capture) {
+ const picker = parseCodexPicker(capture)
+ if (picker?.kind === 'efforts') return picker
+ if (!picker && screen.inspect(capture).pane.idle) return 'closed'
+ }
+ await sleep(100)
+ }
+ return null
+ }
+
+ private async waitPane(predicate: (capture: string) => boolean | Promise<boolean>, timeoutMs: number): Promise<string | null> {
+ const deadline = Date.now() + timeoutMs
+ while (Date.now() < deadline) {
+ const capture = await this.host.capture(100)
+ if (capture && await predicate(capture)) return capture
+ await sleep(100)
+ }
+ return null
+ }
+}
diff --git a/cli/src/engines/engine.ts b/cli/src/engines/engine.ts
index 707058fc0..afa854220 100644
--- a/cli/src/engines/engine.ts
+++ b/cli/src/engines/engine.ts
@@ -1,4 +1,5 @@
import type { EngineScreen } from './facets/screen.js'
+import type { EngineModelControl } from './facets/modelControl.js'
import type { ProcessEngine } from './types.js'
import type { EngineTranscript } from './facets/transcript.js'
import type { EngineLaunch } from './facets/launch.js'
@@ -15,4 +16,5 @@ export interface Engine {
readonly live: EngineLive
readonly runtime: EngineRuntime
readonly screen: EngineScreen
+ readonly modelControl: EngineModelControl
}
diff --git a/cli/src/engines/facets/modelControl.ts b/cli/src/engines/facets/modelControl.ts
new file mode 100644
index 000000000..c9c5538cd
--- /dev/null
+++ b/cli/src/engines/facets/modelControl.ts
@@ -0,0 +1,45 @@
+import type { RuntimeCatalogModel, RuntimeModelOption, RuntimeProfile, RuntimeSession, RuntimeState } from './runtime.js'
+import type { PaneInspection } from './screen.js'
+
+export type RuntimeProfileErrorCode =
+ | 'AGENT_NOT_FOUND' | 'INVALID_RUNTIME_PROFILE' | 'BUSY' | 'UNSUPPORTED_CLI_VERSION'
+ | 'MODEL_UNAVAILABLE' | 'EFFORT_UNSUPPORTED' | 'PLAN_SCOPE_AMBIGUOUS' | 'CONFIRM_TIMEOUT' | 'TMUX_FAILED'
+
+export class RuntimeProfileControlError extends Error {
+ constructor(readonly code: RuntimeProfileErrorCode) { super(code) }
+}
+
+/** Core validates the requested target and owns the profile transaction. */
+export interface ModelControlInput {
+ session: RuntimeSession
+ target: RuntimeProfile
+ current: RuntimeProfile | null
+ options: RuntimeModelOption[]
+ catalog: RuntimeCatalogModel[]
+}
+
+/** Before taking the pane, then again with the captured pane under its input lease. */
+export interface ModelControlCheck {
+ stage: 'target' | 'scope'
+ session: RuntimeSession
+ target: RuntimeProfile
+ state: RuntimeState
+ catalog: RuntimeCatalogModel[]
+ pane?: PaneInspection
+}
+
+/** A single operation's revocable authority, never a terminal locator or arbitrary core API. */
+export interface ModelControlHost {
+ catalog(): Promise<RuntimeCatalogModel[]>
+ capture(historyLines: number): Promise<string | null>
+ text(text: string): Promise<boolean>
+ key(key: string): Promise<boolean>
+ waitForModel(timeoutMs: number): Promise<boolean>
+ waitForProfile(timeoutMs: number): Promise<boolean>
+ confirmEffort(effort: string): Promise<void>
+}
+
+export interface EngineModelControl {
+ validate(check: ModelControlCheck): Promise<void>
+ apply(input: ModelControlInput, host: ModelControlHost): Promise<void>
+}
diff --git a/cli/src/engines/modelControls.ts b/cli/src/engines/modelControls.ts
new file mode 100644
index 000000000..53cafa8f6
--- /dev/null
+++ b/cli/src/engines/modelControls.ts
@@ -0,0 +1,4 @@
+/** Explicit inline composition only. Normal core loads these facets in supervised workers. */
+import { modelControl as claude } from './claude/modelControl.js'
+import { modelControl as codex } from './codex/modelControl.js'
+export const modelControlFor = (engine: string) => engine === 'claude' ? claude : engine === 'codex' ? codex : undefined
diff --git a/cli/src/engines/registry.ts b/cli/src/engines/registry.ts
index 25bc2ff18..07ae04c33 100644
--- a/cli/src/engines/registry.ts
+++ b/cli/src/engines/registry.ts
@@ -1,4 +1,6 @@
import { screen as claudeScreen } from './claude/screen.js'
+import { modelControl as claudeModelControl } from './claude/modelControl.js'
+import { modelControl as codexModelControl } from './codex/modelControl.js'
import { screen as codexScreen } from './codex/screen.js'
import type { Engine } from './engine.js'
import { engineLaunches } from './launches.js'
@@ -12,8 +14,8 @@ 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, runtime: claudeRuntime, screen: claudeScreen },
- codex: { name: 'codex', launch: engineLaunches.codex, transcript: codexTranscript, hooks: engineHooks.codex, live: codexLive, runtime: codexRuntime, screen: codexScreen },
+ claude: { name: 'claude', launch: engineLaunches.claude, transcript: claudeTranscript, hooks: engineHooks.claude, live: claudeLive, runtime: claudeRuntime, screen: claudeScreen, modelControl: claudeModelControl },
+ codex: { name: 'codex', launch: engineLaunches.codex, transcript: codexTranscript, hooks: engineHooks.codex, live: codexLive, runtime: codexRuntime, screen: codexScreen, modelControl: codexModelControl },
} satisfies Record<string, Engine>
type MigratedEngine = keyof typeof engines
export function engineFor(name: string | null | undefined): Engine | undefined {
diff --git a/cli/src/engines/worker/modelControlHost.ts b/cli/src/engines/worker/modelControlHost.ts
new file mode 100644
index 000000000..f63252fb3
--- /dev/null
+++ b/cli/src/engines/worker/modelControlHost.ts
@@ -0,0 +1,24 @@
+import type { ModelControlHost } from '../facets/modelControl.js'
+import { RuntimeProfileControlError } from '../facets/modelControl.js'
+import type { RuntimeCatalogModel } from '../facets/runtime.js'
+import { modelControlAnswer, modelControlEnvelope, type ModelControlAction } from './modelControlProtocol.js'
+
+/** Shared by worker and explicit inline mode. Each call still passes through core's grant broker. */
+export function createModelControlHost(ask: (action: ModelControlAction) => Promise<Record<string, unknown>>): ModelControlHost {
+ const call = async (action: ModelControlAction) => {
+ const reply = await ask(action)
+ if (!modelControlEnvelope(reply, ['value', 'error']) || reply.error !== undefined || !modelControlAnswer(action, reply.value)) {
+ throw new RuntimeProfileControlError('BUSY')
+ }
+ return reply.value
+ }
+ return {
+ catalog: async () => await call({ kind: 'catalog' }) as RuntimeCatalogModel[],
+ capture: async lines => await call({ kind: 'capture', lines }) as string | null,
+ text: async text => await call({ kind: 'text', text }) as boolean,
+ key: async key => await call({ kind: 'key', key }) as boolean,
+ waitForModel: async ms => await call({ kind: 'waitForModel', ms }) as boolean,
+ waitForProfile: async ms => await call({ kind: 'waitForProfile', ms }) as boolean,
+ confirmEffort: async effort => { if (!await call({ kind: 'confirmEffort', effort })) throw new RuntimeProfileControlError('BUSY') },
+ }
+}
diff --git a/cli/src/engines/worker/modelControlProtocol.ts b/cli/src/engines/worker/modelControlProtocol.ts
new file mode 100644
index 000000000..c0687fcea
--- /dev/null
+++ b/cli/src/engines/worker/modelControlProtocol.ts
@@ -0,0 +1,95 @@
+/** Private model-control messages. All terminal effects need a separate, revocable core grant. */
+import type { ModelControlCheck, ModelControlInput, RuntimeProfileErrorCode } from '../facets/modelControl.js'
+import type { RuntimeCatalogModel, RuntimeProfile, RuntimeSession } from '../facets/runtime.js'
+import { record, type ReaderEngine } from './protocol.js'
+import { runtimeContext } from './runtimeProtocol.js'
+import { screenCapture } from './screenProtocol.js'
+
+export const MODEL_CONTROL_VERSION = 1
+export const MODEL_CONTROL_CAPABILITIES = 'engine_model_control_capabilities'
+export const MODEL_CONTROL_VALIDATE = 'engine_model_control_validate'
+export const MODEL_CONTROL_APPLY = 'engine_model_control_apply'
+export const MODEL_CONTROL_HOST = 'engine.modelControl'
+export const MODEL_CONTROL_WAIT_MS = 30_000
+export const MODEL_CONTROL_CHECK_MS = 5_000
+export const MODEL_CONTROL_QUERY_MS = 10_000
+export const MODEL_CONTROL_IN_FLIGHT = 4
+export const MODEL_CONTROL_QUERIES = 128
+export const MODEL_CONTROL_WRITES = 32
+export const MODEL_CONTROL_BYTES = 1024 * 1024
+export const MODEL_CONTROL_ERRORS: readonly RuntimeProfileErrorCode[] = ['AGENT_NOT_FOUND', 'INVALID_RUNTIME_PROFILE', 'BUSY',
+ 'UNSUPPORTED_CLI_VERSION', 'MODEL_UNAVAILABLE', 'EFFORT_UNSUPPORTED', 'PLAN_SCOPE_AMBIGUOUS', 'CONFIRM_TIMEOUT', 'TMUX_FAILED']
+const EMPTY_STATE = { model: null, effort: null, mode: 'unknown' as const, cliVersion: null, observedAt: null }
+const fields = (value: Record<string, unknown>, names: string[]) => Object.keys(value).every(key => names.includes(key))
+const text = (v: unknown, max: number): v is string => typeof v === 'string' && v.length <= max
+const label = (v: unknown): v is string => text(v, 2000) && !!v && !/[\x00-\x1f\x7f]/.test(v)
+export const modelControlToken = (value: unknown): value is string => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value)
+export const modelControlSize = (value: unknown) => Buffer.byteLength(JSON.stringify(value)) <= MODEL_CONTROL_BYTES
+
+export function modelControlCatalog(value: unknown): value is RuntimeCatalogModel[] {
+ return Array.isArray(value) && value.length <= 512 && value.every(m => record(m)
+ && fields(m, ['slug', 'displayName', 'listed', 'defaultEffort', 'efforts']) && label(m.slug) && text(m.displayName, 2000)
+ && typeof m.listed === 'boolean' && text(m.defaultEffort, 200) && Array.isArray(m.efforts) && m.efforts.length <= 64 && m.efforts.every(label))
+}
+
+function profile(value: unknown, session: RuntimeSession, engine: ReaderEngine): RuntimeProfile | null {
+ const context = runtimeContext({ session, state: EMPTY_STATE,
+ control: { target: value, before: null, modelConfirmed: false, effortConfirmed: false } }, engine)
+ const target = context?.control?.target
+ return target && label(target.model) && label(target.effort) ? target : null
+}
+
+export function modelControlInput(value: unknown, engine: ReaderEngine): ModelControlInput | null {
+ if (!record(value) || !fields(value, ['session', 'target', 'current', 'options', 'catalog'])) return null
+ const context = runtimeContext({ session: value.session, state: EMPTY_STATE }, engine)
+ if (!context) return null
+ const target = profile(value.target, context.session, engine)
+ const current = value.current === null ? null : profile(value.current, context.session, engine)
+ if (!target || !modelControlCatalog(value.catalog) || (value.current !== null && !current) || !Array.isArray(value.options) || value.options.length > 4096
+ || !value.options.every(o => record(o) && fields(o, ['id', 'displayName']) && text(o.id, 32768) && text(o.displayName, 32768))) return null
+ return { session: context.session, target, current, catalog: structuredClone(value.catalog), options: value.options.map(o => ({ id: o.id, displayName: o.displayName })) }
+}
+
+export function modelControlCheck(value: unknown, engine: ReaderEngine): ModelControlCheck | null {
+ if (!record(value) || !fields(value, ['session', 'target', 'stage', 'state', 'catalog', 'pane'])
+ || (value.stage !== 'target' && value.stage !== 'scope') || !modelControlCatalog(value.catalog)) return null
+ const context = runtimeContext({ session: value.session, state: value.state }, engine)
+ if (!context) return null
+ const target = profile(value.target, context.session, engine)
+ const pane = value.pane
+ if (!target || (pane !== undefined && (!record(pane) || !fields(pane, ['idle', 'plan', 'dialog', 'draft'])
+ || !['idle', 'plan', 'dialog', 'draft'].every(k => typeof pane[k] === 'boolean')))) return null
+ return { session: context.session, state: context.state, target, stage: value.stage, catalog: structuredClone(value.catalog),
+ ...(pane === undefined ? {} : { pane: { idle: pane.idle as boolean, plan: pane.plan as boolean, dialog: pane.dialog as boolean, draft: pane.draft as boolean } }) }
+}
+
+export type ModelControlAction =
+ | { kind: 'catalog' }
+ | { kind: 'capture'; lines: number }
+ | { kind: 'text'; text: string }
+ | { kind: 'key'; key: string }
+ | { kind: 'waitForModel'; ms: number }
+ | { kind: 'waitForProfile'; ms: number }
+ | { kind: 'confirmEffort'; effort: string }
+
+export function modelControlAction(value: unknown): value is ModelControlAction {
+ if (!record(value)) return false
+ if (value.kind === 'catalog') return fields(value, ['kind'])
+ if (value.kind === 'capture') return fields(value, ['kind', 'lines']) && Number.isInteger(value.lines) && Number(value.lines) >= 1 && Number(value.lines) <= 100
+ if (value.kind === 'text') return fields(value, ['kind', 'text']) && label(value.text)
+ if (value.kind === 'key') return fields(value, ['kind', 'key']) && typeof value.key === 'string' && /^(?:Enter|Escape|[1-9])$/.test(value.key)
+ if (value.kind === 'confirmEffort') return fields(value, ['kind', 'effort']) && label(value.effort)
+ return (value.kind === 'waitForModel' || value.kind === 'waitForProfile') && fields(value, ['kind', 'ms'])
+ && Number.isInteger(value.ms) && Number(value.ms) > 0 && Number(value.ms) <= 8000
+}
+
+export function modelControlAnswer(action: ModelControlAction, value: unknown): boolean {
+ if (action.kind === 'catalog') return modelControlCatalog(value)
+ if (action.kind === 'capture') return value === null || screenCapture(value)
+ return typeof value === 'boolean'
+}
+
+export function modelControlEnvelope(payload: Record<string, unknown>, names: string[]): boolean {
+ return payload.version === MODEL_CONTROL_VERSION && fields(payload, ['version', 'requestId', ...names])
+ && (payload.requestId === undefined || text(payload.requestId, 200)) && modelControlSize(payload)
+}
diff --git a/cli/src/engines/worker/modelControlRequests.spec.ts b/cli/src/engines/worker/modelControlRequests.spec.ts
new file mode 100644
index 000000000..73a6e9b43
--- /dev/null
+++ b/cli/src/engines/worker/modelControlRequests.spec.ts
@@ -0,0 +1,106 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { encodeRuntimeProfile } from '../kit/runtime.js'
+import { RuntimeProfileControlError, type EngineModelControl, type ModelControlHost } from '../facets/modelControl.js'
+import { engineModelControlRequests } from './modelControlRequests.js'
+import { createModelControlHost } from './modelControlHost.js'
+import { MODEL_CONTROL_APPLY as APPLY, MODEL_CONTROL_CAPABILITIES as CAP, MODEL_CONTROL_VALIDATE as CHECK,
+ MODEL_CONTROL_CHECK_MS, MODEL_CONTROL_WAIT_MS, MODEL_CONTROL_QUERY_MS, modelControlCheck, modelControlInput } from './modelControlProtocol.js'
+
+const session = { agentId: 'agent', sessionId: 'session', engine: 'claude' as const, model: null, cliVersion: null, cwd: '/tmp', transcriptPath: null }
+const state = { model: null, effort: null, mode: 'default' as const, cliVersion: null, observedAt: null }
+const target = { id: '', sessionId: 'agent', engine: 'claude' as const, model: 'sonnet', effort: 'high' }
+target.id = encodeRuntimeProfile(target)
+const input = { session, target, current: null, options: [{ id: target.id, displayName: 'Sonnet / High' }], catalog: [] }
+const check = { session, target, state, stage: 'target' as const, catalog: [] }
+const asker = { owner: true, local: true }
+const apply = { version: 1, input, token: 'a'.repeat(64), requestId: 'core-route' }
+function setup() {
+ const control: EngineModelControl = { validate: vi.fn(async () => {}), apply: vi.fn(async () => {}) }
+ const deps = { load: vi.fn(async () => control), recycle: vi.fn(), query: vi.fn(async () => ({ version: 1, value: true, requestId: 'core-reply' } as Record<string, unknown>)) }
+ const requests = engineModelControlRequests('claude', deps)
+ return { requests, control, deps }
+}
+
+describe('private model-control worker', () => {
+ beforeEach(() => vi.useFakeTimers())
+ afterEach(() => vi.useRealTimers())
+
+ it('accepts only the core owner envelope and uses a lazy, retryable facet import', async () => {
+ const s = setup()
+ expect(await s.requests[CAP]({ version: 1 }, asker)).toEqual({ version: 1, modelControl: 1, engine: 'claude' })
+ expect(s.deps.load).not.toHaveBeenCalled()
+ for (const caller of [{ owner: false, local: true }, { owner: true, local: false }, { ...asker, connection: 'client' }]) {
+ expect(await s.requests[APPLY](apply, caller)).toHaveProperty('error', 'BUSY')
+ }
+ for (const payload of [{ ...apply, version: 2 }, { ...apply, terminal: '%1' }, { ...apply, token: 'guess' }, { ...apply, requestId: 7 }, { ...apply, input: { ...input, target: { ...target, engine: 'codex' } } }]) {
+ expect(await s.requests[APPLY](payload, asker)).toHaveProperty('error', 'INVALID_RUNTIME_PROFILE')
+ }
+ s.deps.load.mockRejectedValueOnce(new Error('import failed'))
+ expect(await s.requests[APPLY](apply, asker)).toHaveProperty('error', 'BUSY')
+ expect(await s.requests[APPLY](apply, asker)).toEqual({ version: 1, ok: true })
+ expect(await s.requests[CHECK]({ version: 1, check }, asker)).toEqual({ version: 1, ok: true })
+ expect(s.deps.load).toHaveBeenCalledTimes(2)
+ expect(s.control.apply).toHaveBeenCalledOnce()
+ })
+
+ it('rejects mismatched profiles, unbounded evidence and extra terminal authority', () => {
+ for (const value of [null, { ...input, terminal: '%1' }, { ...input, current: {} }, { ...input, session: { ...session, cwd: 'relative' } },
+ { ...input, options: [{ id: target.id, displayName: 4 }] }, { ...input, options: Array(4097).fill(input.options[0]) }, { ...input, catalog: [{}] },
+ { ...input, target: { ...target, model: 'sonnet\nanswer', id: encodeRuntimeProfile({ ...target, model: 'sonnet\nanswer' }) } }]) {
+ expect(modelControlInput(value, 'claude')).toBeNull()
+ }
+ for (const value of [null, { ...check, stage: 'write' }, { ...check, state: {} }, { ...check, catalog: null }, { ...check, pane: { idle: true } },
+ { ...check, pane: { idle: true, draft: false, plan: false, dialog: false, tmuxPane: '%1' } }]) expect(modelControlCheck(value, 'claude')).toBeNull()
+ expect(modelControlInput({ ...input, current: target }, 'claude')?.current).toEqual(target)
+ expect(modelControlCheck({ ...check, pane: { idle: true, draft: false, plan: false, dialog: false } }, 'claude')?.pane?.idle).toBe(true)
+ })
+
+ it('propagates known refusals, and makes no late request after abort or completion', async () => {
+ const s = setup(), closed = new AbortController()
+ closed.abort()
+ expect(await s.requests[APPLY](apply, asker, closed.signal)).toHaveProperty('error', 'BUSY')
+ s.control.validate = vi.fn(async () => { throw new RuntimeProfileControlError('PLAN_SCOPE_AMBIGUOUS') })
+ expect(await s.requests[CHECK]({ version: 1, check }, asker)).toHaveProperty('error', 'PLAN_SCOPE_AMBIGUOUS')
+ let host!: ModelControlHost
+ s.control.apply = vi.fn(async (_input, value) => { host = value; await value.key('Enter') })
+ expect(await s.requests[APPLY](apply, asker)).toHaveProperty('ok', true)
+ await expect(host.key('Escape')).rejects.toMatchObject({ code: 'BUSY' })
+ expect(s.deps.query).toHaveBeenCalledTimes(1)
+ expect(s.deps.query).toHaveBeenCalledWith('engine.modelControl', { version: 1, token: apply.token, action: { kind: 'key', key: 'Enter' } })
+ const second = new AbortController()
+ s.control.apply = vi.fn(async (_input, value) => { host = value; second.abort(); await value.text('/model late') })
+ expect(await s.requests[APPLY](apply, asker, second.signal)).toHaveProperty('error', 'BUSY')
+ expect(s.deps.query).toHaveBeenCalledTimes(1)
+ })
+
+ it.each([['load', MODEL_CONTROL_CHECK_MS], ['apply', MODEL_CONTROL_WAIT_MS], ['query', MODEL_CONTROL_QUERY_MS]] as const)('bounds and recycles a hung %s', async (kind, timeout) => {
+ const s = setup()
+ let host!: ModelControlHost
+ if (kind === 'load') s.deps.load.mockImplementation(() => new Promise(() => {}))
+ else s.control.apply = vi.fn(async (_input, value) => { host = value; if (kind === 'query') await value.capture(100); else await new Promise(() => {}) })
+ if (kind === 'query') s.deps.query.mockImplementation(() => new Promise(() => {}))
+ const result = kind === 'load' ? s.requests[CHECK]({ version: 1, check }, asker) : s.requests[APPLY](apply, asker)
+ await vi.advanceTimersByTimeAsync(timeout + 1)
+ expect(await result).toHaveProperty('error', 'BUSY')
+ expect(s.deps.recycle).toHaveBeenCalledOnce()
+ if (host) await expect(host.key('Escape')).rejects.toMatchObject({ code: 'BUSY' })
+ })
+
+ it('bounds simultaneous operations and aborts all work tied to the old core', async () => {
+ const s = setup(), closed = new AbortController()
+ s.control.apply = vi.fn(() => new Promise<void>(() => {}))
+ const calls = Array.from({ length: 4 }, () => s.requests[APPLY](apply, asker, closed.signal))
+ expect(await s.requests[APPLY](apply, asker)).toHaveProperty('error', 'BUSY')
+ closed.abort()
+ expect(await Promise.all(calls)).toEqual(Array(4).fill({ version: 1, error: 'BUSY' }))
+ expect(s.deps.recycle).not.toHaveBeenCalled()
+ })
+
+ it('refuses malformed or denied host answers, including false effort confirmation', async () => {
+ for (const reply of [{ version: 2, value: true }, { version: 1, error: 'BUSY', value: true }, { version: 1, value: 1 },
+ { version: 1, value: true, terminal: '%9' }, { version: 1, value: true, requestId: 1 }, { version: 1, value: 'x'.repeat(1024 * 1024) }]) {
+ await expect(createModelControlHost(async () => reply).key('Enter')).rejects.toMatchObject({ code: 'BUSY' })
+ }
+ await expect(createModelControlHost(async () => ({ version: 1, value: false })).confirmEffort('high')).rejects.toMatchObject({ code: 'BUSY' })
+ })
+})
diff --git a/cli/src/engines/worker/modelControlRequests.ts b/cli/src/engines/worker/modelControlRequests.ts
new file mode 100644
index 000000000..a86997b04
--- /dev/null
+++ b/cli/src/engines/worker/modelControlRequests.ts
@@ -0,0 +1,72 @@
+import type { ServiceRequests } from '../../core/api.js'
+import { RuntimeProfileControlError, type EngineModelControl } from '../facets/modelControl.js'
+import type { ReaderEngine } from './protocol.js'
+import { createModelControlHost } from './modelControlHost.js'
+import { modelControlCheck, modelControlEnvelope, modelControlInput, modelControlToken,
+ MODEL_CONTROL_APPLY, MODEL_CONTROL_CAPABILITIES, MODEL_CONTROL_CHECK_MS, MODEL_CONTROL_HOST, MODEL_CONTROL_IN_FLIGHT,
+ MODEL_CONTROL_QUERY_MS, MODEL_CONTROL_VALIDATE, MODEL_CONTROL_VERSION, MODEL_CONTROL_WAIT_MS } from './modelControlProtocol.js'
+
+const loadControl = {
+ claude: async () => (await import('../claude/modelControl.js')).modelControl,
+ codex: async () => (await import('../codex/modelControl.js')).modelControl,
+}
+export interface ModelControlRequestDeps {
+ query(query: string, payload: Record<string, unknown>): Promise<Record<string, unknown>>
+ load?: () => Promise<EngineModelControl>
+ recycle?: () => void
+}
+
+export function engineModelControlRequests(engine: ReaderEngine, deps: ModelControlRequestDeps): ServiceRequests {
+ let loaded: Promise<EngineModelControl> | null = null
+ let pending = 0
+ const failure = (error: string) => ({ version: MODEL_CONTROL_VERSION, error })
+ const recycle = deps.recycle ?? (() => process.exit(1))
+ const handler = (method: string): ServiceRequests[string] => async (payload, asker, closed) => {
+ if (!asker.owner || !asker.local || asker.connection !== undefined) return failure('BUSY')
+ const names = method === MODEL_CONTROL_CAPABILITIES ? [] : method === MODEL_CONTROL_VALIDATE ? ['check'] : ['input', 'token']
+ if (!modelControlEnvelope(payload, names)) return failure('INVALID_RUNTIME_PROFILE')
+ if (closed?.aborted) return failure('BUSY')
+ if (method === MODEL_CONTROL_CAPABILITIES) return { version: MODEL_CONTROL_VERSION, modelControl: MODEL_CONTROL_VERSION, engine }
+ const check = method === MODEL_CONTROL_VALIDATE ? modelControlCheck(payload.check, engine) : null
+ const input = method === MODEL_CONTROL_APPLY ? modelControlInput(payload.input, engine) : null
+ if (!(check || (input && modelControlToken(payload.token)))) return failure('INVALID_RUNTIME_PROFILE')
+ if (pending >= MODEL_CONTROL_IN_FLIGHT) return failure('BUSY')
+ pending++
+ let active = true
+ let timer: ReturnType<typeof setTimeout> | undefined
+ let abort: (() => void) | undefined
+ const stopped = new Promise<Record<string, unknown>>(resolve => {
+ abort = () => { active = false; resolve(failure('BUSY')) }
+ closed?.addEventListener('abort', abort, { once: true })
+ timer = setTimeout(() => { abort!(); recycle() }, input ? MODEL_CONTROL_WAIT_MS : MODEL_CONTROL_CHECK_MS)
+ })
+ const valid = () => { if (!active) throw new RuntimeProfileControlError('BUSY') }
+ const host = createModelControlHost(async action => {
+ valid()
+ let timeout: ReturnType<typeof setTimeout> | undefined
+ try {
+ const reply = await Promise.race([
+ deps.query(MODEL_CONTROL_HOST, { version: MODEL_CONTROL_VERSION, token: payload.token, action }),
+ new Promise<never>((_, reject) => { timeout = setTimeout(() => {
+ active = false; reject(new RuntimeProfileControlError('BUSY')); recycle()
+ }, MODEL_CONTROL_QUERY_MS) }),
+ ])
+ valid()
+ return reply
+ } finally { clearTimeout(timeout) }
+ })
+ try {
+ return await Promise.race([stopped, (async () => {
+ const control = await (loaded ??= (deps.load ?? loadControl[engine])().catch(error => { loaded = null; throw error }))
+ valid()
+ if (check) await control.validate(check)
+ else await control.apply(input!, host)
+ valid()
+ return { version: MODEL_CONTROL_VERSION, ok: true }
+ })()])
+ } catch (error) { return failure(error instanceof RuntimeProfileControlError ? error.code : 'BUSY') }
+ finally { active = false; clearTimeout(timer); closed?.removeEventListener('abort', abort!); pending-- }
+ }
+ return { [MODEL_CONTROL_CAPABILITIES]: handler(MODEL_CONTROL_CAPABILITIES),
+ [MODEL_CONTROL_VALIDATE]: handler(MODEL_CONTROL_VALIDATE), [MODEL_CONTROL_APPLY]: handler(MODEL_CONTROL_APPLY) }
+}
diff --git a/cli/src/engines/worker/process.spec.ts b/cli/src/engines/worker/process.spec.ts
index 71dbd3c09..b746132a8 100644
--- a/cli/src/engines/worker/process.spec.ts
+++ b/cli/src/engines/worker/process.spec.ts
@@ -122,7 +122,7 @@ describe('read-only engine worker', () => {
const run = vi.fn(() => ({ stop: vi.fn() }))
for (const [name, start] of [['claude', runClaudeReader], ['codex', runCodexReader]] as const) {
const process = start({ ...opts, requests, run })
- expect(run).toHaveBeenLastCalledWith({ name: `engine-${name}`, socketPath: opts.socketPath, machineId: opts.machineId, token: opts.token, requests })
+ expect(run).toHaveBeenLastCalledWith({ name: `engine-${name}`, socketPath: opts.socketPath, machineId: opts.machineId, token: opts.token, requests, onConnected: expect.any(Function), onDisconnected: expect.any(Function) })
expect(process.stop).toBeTypeOf('function')
}
expect(runEngineReader('claude', opts).stop).toBeTypeOf('function')
diff --git a/cli/src/engines/worker/process.ts b/cli/src/engines/worker/process.ts
index 6d734b984..e1b70d9f2 100644
--- a/cli/src/engines/worker/process.ts
+++ b/cli/src/engines/worker/process.ts
@@ -1,4 +1,6 @@
-/** One engine's read-only adapter, hosted by the master's existing service supervisor. */
+import type { CoreConnection } from '../../services/process.js'
+import { engineModelControlRequests } from './modelControlRequests.js'
+/** One engine's facets, hosted by the master's existing service supervisor. */
import { isAbsolute } from 'node:path'
import type { ServiceRequests } from '../../core/api.js'
import { TranscriptPager } from '../../lib/transcriptPages.js'
@@ -85,8 +87,12 @@ export interface EngineProcessOptions extends ServiceProcessOptions {
}
export function runEngineReader(engine: ReaderEngine, options: EngineProcessOptions): ServiceProcess {
+ let core: CoreConnection | null = null
return (options.run ?? runServiceProcess)({
name: READER_SERVICES[engine], socketPath: options.socketPath, machineId: options.machineId,
- token: options.token, requests: options.requests ?? { ...engineReaderRequests(engine), ...engineLiveRequests(engine), ...engineRuntimeRequests(engine), ...engineScreenRequests(engine) },
+ token: options.token, requests: options.requests ?? { ...engineReaderRequests(engine), ...engineLiveRequests(engine), ...engineRuntimeRequests(engine), ...engineScreenRequests(engine), ...engineModelControlRequests(engine, {
+ query: (query, payload) => core ? core.query(query, payload) : Promise.reject(new Error('core disconnected')),
+ }) },
+ onConnected: connected => { core = connected }, onDisconnected: () => { core = null },
})
}
diff --git a/cli/src/harnessd/services.spec.ts b/cli/src/harnessd/services.spec.ts
index c91e7612e..81feeee96 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, ENGINE_RUNTIME_ENV, ENGINE_SCREEN_ENV, KNOWN_SERVICES, SERVICE_HOSTS, SERVICE_PROCESSES_ENV, ServiceSupervisor, UPDATER_HOST, masterRunsLiveEngines, masterRunsEngineRuntime, masterRunsEngineScreen, serviceOptions, serviceProcessesEnv, serviceSpecs, servicesTheMasterRuns,
+ DEFAULT_SERVICE_OPTIONS, ENGINE_LIVE_ENV, ENGINE_RUNTIME_ENV, ENGINE_SCREEN_ENV, ENGINE_MODEL_CONTROL_ENV, masterRunsEngineModelControl, KNOWN_SERVICES, SERVICE_HOSTS, SERVICE_PROCESSES_ENV, ServiceSupervisor, UPDATER_HOST, masterRunsLiveEngines, masterRunsEngineRuntime, masterRunsEngineScreen, 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', [ENGINE_RUNTIME_ENV]: '42:1', [ENGINE_SCREEN_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', [ENGINE_SCREEN_ENV]: '42:1', [ENGINE_MODEL_CONTROL_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', [ENGINE_RUNTIME_ENV]: '42:1', [ENGINE_SCREEN_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', [ENGINE_SCREEN_ENV]: '42:1', [ENGINE_MODEL_CONTROL_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', [ENGINE_RUNTIME_ENV]: '42:1', [ENGINE_SCREEN_ENV]: '42:1' })
+ expect(serviceProcessesEnv([], 42)).toEqual({ [SERVICE_PROCESSES_ENV]: '', HARNESSD_SERVICES: 'none', [ENGINE_LIVE_ENV]: '42:1', [ENGINE_RUNTIME_ENV]: '42:1', [ENGINE_SCREEN_ENV]: '42:1', [ENGINE_MODEL_CONTROL_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.
@@ -517,6 +517,15 @@ describe('which services the core leaves to its master', () => {
expect(masterRunsLiveEngines({ ...env, [ENGINE_RUNTIME_ENV]: undefined }, 42)).toBe(true)
})
+ it('negotiates model controls only from a capable supervising parent', () => {
+ const env = { ...supervised, ...serviceProcessesEnv([], 42) }
+ expect(masterRunsEngineModelControl(env, 42)).toBe(true)
+ expect(masterRunsEngineModelControl(env, 43)).toBe(false)
+ expect(masterRunsEngineModelControl({ ...env, [ENGINE_MODEL_CONTROL_ENV]: undefined }, 42)).toBe(false)
+ expect(masterRunsEngineModelControl({ ...env, [ENGINE_LIVE_ENV]: undefined }, 42)).toBe(false)
+ expect(masterRunsEngineModelControl({ ...env, HARNESSD_SERVICE_TOKEN: undefined }, 42)).toBe(false)
+ })
+
it('negotiates screen readers only from a capable supervising parent', () => {
const env = { ...supervised, ...serviceProcessesEnv([], 42) }
expect(masterRunsEngineScreen(env, 42)).toBe(true)
diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.ts
index f243e8606..93a1d1ec4 100644
--- a/cli/src/harnessd/services.ts
+++ b/cli/src/harnessd/services.ts
@@ -365,7 +365,7 @@ export type ServiceHostSpec = Omit<ServiceSpec, 'name'>
* would cost that four times.
*/
export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {
- // New read-only workers have no older-core startup obligation: old cores read inline and never ask.
+ // Engine workers have no older-core startup obligation: old cores run these facets inline and never ask.
// Each holds at most four reads, a 128-entry pager and replies capped at 4 MiB. The heap limit
// contains transient parsing; RSS additionally bounds file buffers outside V8's heap.
'engine-claude': { services: ['engine-claude'], heapLimitMiB: 512, rssLimitMiB: 1_024, onDemand: true, askedSince: 0 },
@@ -460,6 +460,7 @@ 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'
export const ENGINE_SCREEN_ENV = 'HARNESSD_ENGINE_SCREEN'
+export const ENGINE_MODEL_CONTROL_ENV = 'HARNESSD_ENGINE_MODEL_CONTROL'
/**
* What a master puts in its core's environment about the services it runs in their own processes: the
@@ -471,7 +472,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`, [ENGINE_RUNTIME_ENV]: `${masterPid}:1`, [ENGINE_SCREEN_ENV]: `${masterPid}:1` }
+ return { [SERVICE_PROCESSES_ENV]: names, HARNESSD_SERVICES: names || 'none', [ENGINE_LIVE_ENV]: `${masterPid}:1`, [ENGINE_RUNTIME_ENV]: `${masterPid}:1`, [ENGINE_SCREEN_ENV]: `${masterPid}:1`, [ENGINE_MODEL_CONTROL_ENV]: `${masterPid}:1` }
}
/** An older master may inherit a newer master's environment after rollback. Trust only this parent. */
@@ -526,3 +527,8 @@ export function serviceSpecs(env: NodeJS.ProcessEnv, hosts: Readonly<Record<stri
export function masterRunsEngineScreen(env: NodeJS.ProcessEnv, parentPid: number): boolean {
return masterRunsLiveEngines(env, parentPid) && env[ENGINE_SCREEN_ENV] === `${parentPid}:1`
}
+
+/** A new core must not route controls through an older worker host. */
+export function masterRunsEngineModelControl(env: NodeJS.ProcessEnv, parentPid: number): boolean {
+ return masterRunsLiveEngines(env, parentPid) && env[ENGINE_MODEL_CONTROL_ENV] === `${parentPid}:1`
+}
diff --git a/cli/src/lib/modelControl.ts b/cli/src/lib/modelControl.ts
new file mode 100644
index 000000000..805a3c94a
--- /dev/null
+++ b/cli/src/lib/modelControl.ts
@@ -0,0 +1,9 @@
+import type { ModelControlCheck, ModelControlInput } from '../engines/facets/modelControl.js'
+import type { RegisteredSession } from './registry.js'
+
+/** Bound before the controller's first await. No worker owns the transaction or its input lease. */
+export interface ModelControlSession {
+ validate(check: Omit<ModelControlCheck, 'session' | 'catalog'>): Promise<void>
+ apply(input: Omit<ModelControlInput, 'session' | 'catalog'>): Promise<void>
+}
+export type ModelControlFor = (session: RegisteredSession) => ModelControlSession | undefined
diff --git a/cli/src/lib/runtimeControl.ts b/cli/src/lib/runtimeControl.ts
index 8446d5a00..57e0f15f2 100644
--- a/cli/src/lib/runtimeControl.ts
+++ b/cli/src/lib/runtimeControl.ts
@@ -1,3 +1,6 @@
+import type { ModelControlFor } from './modelControl.js'
+import { RuntimeProfileControlError } from '../engines/facets/modelControl.js'
+export { RuntimeProfileControlError, type RuntimeProfileErrorCode } from '../engines/facets/modelControl.js'
import type { ScreenReader } from './screenReader.js'
import { stripAnsi } from '../engines/kit/pane.js'
export type { PaneInspection, PaneTakeover } from '../engines/facets/screen.js'
@@ -15,15 +18,6 @@ import {
type OpencodeModelTarget,
type OpencodePickerRow,
} from '../engines/opencode/runtimeProfile.js'
-import {
- chooseCodexRow,
- codexDigitPressable,
- codexEffortRows,
- parseCodexPicker,
- sameCodexPicker,
- type CodexCatalogModel,
- type CodexPicker,
-} from '../engines/codex/modelPicker.js'
import {
type CursorModelTarget,
type RuntimeProfile,
@@ -33,12 +27,6 @@ import {
const COMMAND_CONFIRM_MS = 8_000
const PICKER_OPEN_MS = 3_000
const PICKER_STEP_MS = 2_000
-/**
- * How far apart the two reads of a Codex model list are, which must agree before a digit is pressed on
- * it (see reachCodexEfforts): long enough for a redraw in flight to land, short beside the seconds a
- * switch takes to confirm.
- */
-const CODEX_SETTLE_MS = 250
/** Hard bound on ladder keystrokes — twice pi's seven levels, so a desynchronised walk still terminates. */
const PI_LADDER_MAX_STEPS = 14
/** Hermes' longest picker page is a provider's model list; twice its size still terminates. */
@@ -50,30 +38,13 @@ function hermesProviderMatches(row: string, provider: string): boolean {
return name === key || name.replace(/[^a-z0-9]/g, '').includes(key.replace(/[^a-z0-9]/g, ''))
}
-export type RuntimeProfileErrorCode =
- | 'AGENT_NOT_FOUND'
- | 'INVALID_RUNTIME_PROFILE'
- | 'BUSY'
- | 'UNSUPPORTED_CLI_VERSION'
- | 'MODEL_UNAVAILABLE'
- | 'EFFORT_UNSUPPORTED'
- | 'PLAN_SCOPE_AMBIGUOUS'
- | 'CONFIRM_TIMEOUT'
- | 'TMUX_FAILED'
-
-export class RuntimeProfileControlError extends Error {
- constructor(readonly code: RuntimeProfileErrorCode) {
- super(code)
- }
-}
-
export interface RuntimeProfileControllerDeps {
+ modelControlFor: ModelControlFor
readScreen: ScreenReader
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 | undefined
@@ -147,11 +118,6 @@ export function parseCursorParameterRows(capture: string): CursorParameterRow[]
return rows.length ? rows : null
}
-/** The lists a model is chosen from, as against the reasoning screens that follow them. */
-function isCodexList(picker: CodexPicker): boolean {
- return picker.kind === 'quick' || picker.kind === 'models' || picker.kind === 'reserve'
-}
-
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
@@ -163,9 +129,11 @@ export class RuntimeProfileController {
const registeredSession = this.deps.getSession(sessionId)
if (!registeredSession) throw new RuntimeProfileControlError('AGENT_NOT_FOUND')
const observed = this.deps.manager.getState(registeredSession.sessionId)
- const session: RegisteredSession = registeredSession.cliVersion || !observed.cliVersion
- ? registeredSession
- : { ...registeredSession, cliVersion: observed.cliVersion }
+ // Keep transaction cleanup on the conversation that began it, even if the registry row
+ // is rebound in place while a native driver awaits its worker.
+ const session: RegisteredSession = structuredClone(registeredSession)
+ session.cliVersion ||= observed.cliVersion
+ const native = this.deps.modelControlFor(session)
const target = parseRuntimeProfile(encoded)
// Either id identifies the agent: the encoded profile now carries the agent id, but one minted
// before the id cutover (or by a client that still knows the session) must keep working.
@@ -178,18 +146,13 @@ export class RuntimeProfileController {
console.warn(`[runtime-profile] unsupported ${session.engine} CLI version ${session.cliVersion ?? 'unknown'} for ${sessionId.slice(0, 8)}`)
throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
}
- // Codex's own catalog: which efforts each model takes, and the names its picker shows them by.
- 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 (!await this.deps.manager.effortAllowed(session, target.model, target.effort, listed)) throw new RuntimeProfileControlError('EFFORT_UNSUPPORTED')
- }
+ await native?.validate({ stage: 'target', target, state: observed })
const options = await this.deps.manager.modelsForSession(session)
if (!options.some((option) => option.id === target.id)) {
const sameModel = options.some((option) => parseRuntimeProfile(option.id)?.model === target.model)
throw new RuntimeProfileControlError(sameModel ? 'EFFORT_UNSUPPORTED' : 'MODEL_UNAVAILABLE')
}
- if (session.engine === 'codex' && observed.mode === 'plan') throw new RuntimeProfileControlError('PLAN_SCOPE_AMBIGUOUS')
+ await native?.validate({ stage: 'scope', target, state: observed })
const release = this.deps.acquireInput(session.agentId)
if (!release) throw new RuntimeProfileControlError('BUSY')
let controlStarted = false
@@ -200,16 +163,12 @@ export class RuntimeProfileController {
if (!capture) throw new RuntimeProfileControlError('TMUX_FAILED')
const inspection = (await this.deps.readScreen(session, capture))?.pane
if (!inspection) throw new RuntimeProfileControlError('BUSY')
- if (session.engine === 'codex' && inspection.plan) throw new RuntimeProfileControlError('PLAN_SCOPE_AMBIGUOUS')
+ await native?.validate({ stage: 'scope', target, state: observed, pane: inspection })
if (!inspection.idle) throw new RuntimeProfileControlError('BUSY')
if (!this.deps.manager.beginControl(session, target)) throw new RuntimeProfileControlError('BUSY')
controlStarted = true
- if (session.engine === 'claude') {
- await this.setClaude(session, target, current, options)
- } else if (session.engine === 'codex') {
- pickerOpen = true
- await this.setCodex(session, target, codexCatalog)
- pickerOpen = false
+ if (native) {
+ await native.apply({ target, current, options })
} else if (session.engine === 'devin') {
// No picker is ever opened — `/model <id>` is a single command — so there is nothing to Escape out
// of if this throws.
@@ -261,55 +220,6 @@ export class RuntimeProfileController {
}
}
- private async setClaude(
- session: RegisteredSession,
- target: RuntimeProfile,
- current: RuntimeProfile | null,
- options: Array<{ id: string }>,
- ): Promise<void> {
- if (current?.model !== target.model) {
- if (!await this.deps.sendText(session.agentId, `/model ${target.model}`)) {
- throw new RuntimeProfileControlError('TMUX_FAILED')
- }
- if (!await this.waitClaudeModel(session)) throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
- }
-
- if (current?.effort === target.effort) {
- this.deps.manager.confirmEffort(session.sessionId, target.effort)
- return
- }
-
- const hasExplicitEffort = options.some((option) => {
- const profile = parseRuntimeProfile(option.id)
- return profile?.model === target.model && profile.effort !== 'auto'
- })
- if (!hasExplicitEffort && target.effort === 'auto') {
- this.deps.manager.confirmEffort(session.sessionId, 'auto')
- return
- }
- if (!await this.deps.sendText(session.agentId, `/effort ${target.effort}`)) {
- throw new RuntimeProfileControlError('TMUX_FAILED')
- }
- if (!await this.deps.manager.waitForProfile(session.sessionId, COMMAND_CONFIRM_MS)) {
- await this.deps.sendKey(session.agentId, 'Enter')
- if (!await this.deps.manager.waitForProfile(session.sessionId, 2_000)) {
- throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
- }
- }
- }
-
- private async waitClaudeModel(session: RegisteredSession): Promise<boolean> {
- if (await this.deps.manager.waitForModel(session.sessionId, 1_200)) return true
- const capture = await this.deps.capture(session.agentId, 80)
- if (capture && /switch model|change model|continue.*model|re-read.*history/i.test(stripAnsi(capture))) {
- await this.deps.sendKey(session.agentId, 'Enter')
- } else {
- // Claude and Codex can swallow the first Enter immediately after a terminal literal write.
- await this.deps.sendKey(session.agentId, 'Enter')
- }
- return this.deps.manager.waitForModel(session.sessionId, COMMAND_CONFIRM_MS)
- }
-
/**
* Devin takes the whole profile in one command: `/model <id>` accepts the exact id from
* `devin models list` (effort included), and answers in the pane — `✓ Model set to <name>` or
@@ -643,138 +553,6 @@ export class RuntimeProfileController {
return !!confirmed
}
- /**
- * Codex's `/model`: a quick menu of auto presets with an `All models` row (0.145 and later), the full
- * list (`Select Model and Effort`), then the chosen model's reasoning picker, each row pressed by its
- * digit, which selects the row and accepts it. How a row is read and chosen, and why, is in
- * engines/codex/modelPicker.ts. Confirmed, as it always was, by the `thread_settings_applied` record
- * Codex writes once the choice is applied (RuntimeProfileManager `ingestCodex`).
- */
- private async setCodex(session: RegisteredSession, target: RuntimeProfile, catalog: CodexCatalogModel[]): Promise<void> {
- if (!await this.deps.sendText(session.agentId, '/model')) throw new RuntimeProfileControlError('TMUX_FAILED')
- let picker = await this.waitCodexPicker(session, () => true, 900)
- if (!picker) {
- await this.deps.sendKey(session.agentId, 'Enter')
- picker = await this.waitCodexPicker(session, () => true, PICKER_OPEN_MS)
- }
- if (!picker) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
- if (!isCodexList(picker)) {
- // Opened on a reasoning screen: back to the list it was opened from, so the model is chosen too.
- if (!await this.deps.sendKey(session.agentId, 'Escape')) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
- if (!await this.waitCodexPicker(session, isCodexList, PICKER_STEP_MS)) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
- }
- const reached = await this.reachCodexEfforts(session, target, catalog)
- if (reached !== 'applied') await this.pickCodexEffort(session, target, reached)
- if (!await this.deps.manager.waitForProfile(session.sessionId, COMMAND_CONFIRM_MS)) {
- throw new RuntimeProfileControlError('CONFIRM_TIMEOUT')
- }
- }
-
- /**
- * From the list on screen to the target model's reasoning picker, through `All models` when the quick
- * menu is first; or 'applied' when the model's row applied it at once (a model with one effort).
- *
- * Every digit is pressed from a list read twice, CODEX_SETTLE_MS apart, the same both times. Codex
- * 0.160 draws the list from its cache and redraws it in place when the server answers, and a model
- * added or reordered then renumbers the rows: a digit read off the first drawing lands on another
- * model. The reasoning picker that opens names its model in its title, and a title naming any other
- * model than the row pressed means the list moved anyway, so nothing more is pressed.
- */
- private async reachCodexEfforts(
- session: RegisteredSession,
- target: RuntimeProfile,
- catalog: CodexCatalogModel[],
- ): Promise<CodexPicker | 'applied'> {
- let reread = false
- for (let lists = 0; lists < 2; lists++) {
- const list = await this.settledCodexList(session)
- if (!list) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
- let choice = chooseCodexRow(list, target, catalog)
- if ('error' in choice && choice.error === 'MODEL_UNAVAILABLE' && !reread) {
- // Codex saves the catalog its picker refreshed from to models_cache.json, so a model or a name
- // that came with the refresh is there to read now.
- reread = true
- catalog = await this.deps.manager.codexCatalog(session)
- choice = chooseCodexRow(list, target, catalog)
- }
- if ('error' in choice) throw new RuntimeProfileControlError(choice.error)
- if (!await this.deps.sendKey(session.agentId, String(choice.row.number))) throw new RuntimeProfileControlError('TMUX_FAILED')
- if (choice.opens === 'list') {
- if (!await this.waitCodexPicker(session, (next) => next.kind === 'models', PICKER_STEP_MS)) {
- throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
- }
- continue
- }
- if (choice.opens === 'applied') return 'applied'
- const next = await this.waitCodexAfterModelRow(session)
- if (next === 'closed') return 'applied'
- if (!next) throw new RuntimeProfileControlError('UNSUPPORTED_CLI_VERSION')
- if (next.model !== choice.row.name) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
- return next
- }
- throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
- }
-
- /** The target's effort in its reasoning picker, through Advanced Reasoning for Max and Ultra. */
- private async pickCodexEffort(session: RegisteredSession, target: RuntimeProfile, picker: CodexPicker): Promise<void> {
- const rows = codexEffortRows(picker)
- let row = target.effort === 'auto' ? rows.defaultRow : rows.efforts.get(target.effort) ?? null
- if (row === null && (target.effort === 'max' || target.effort === 'ultra') && rows.advancedRow !== null
- && codexDigitPressable(rows.advancedRow)) {
- if (!await this.deps.sendKey(session.agentId, String(rows.advancedRow))) throw new RuntimeProfileControlError('TMUX_FAILED')
- const advanced = await this.waitCodexPicker(session, (next) => next.kind === 'advanced', PICKER_STEP_MS)
- row = advanced ? codexEffortRows(advanced).efforts.get(target.effort) ?? null : null
- }
- if (row === null || !codexDigitPressable(row)) throw new RuntimeProfileControlError('EFFORT_UNSUPPORTED')
- if (!await this.deps.sendKey(session.agentId, String(row))) throw new RuntimeProfileControlError('TMUX_FAILED')
- }
-
- /** The first Codex picker on the pane that `wanted` takes, polled until `timeoutMs`. */
- private async waitCodexPicker(
- session: RegisteredSession,
- wanted: (picker: CodexPicker) => boolean,
- timeoutMs: number,
- ): Promise<CodexPicker | null> {
- const capture = await this.waitPane(session.agentId, (value) => {
- const picker = parseCodexPicker(value)
- return !!picker && wanted(picker)
- }, timeoutMs)
- return capture ? parseCodexPicker(capture) : null
- }
-
- /** A model list that reads the same twice, CODEX_SETTLE_MS apart (see reachCodexEfforts). */
- private async settledCodexList(session: RegisteredSession): Promise<CodexPicker | null> {
- let previous: CodexPicker | null = null
- const deadline = Date.now() + PICKER_STEP_MS
- while (Date.now() < deadline) {
- const capture = await this.deps.capture(session.agentId, 100)
- const picker = capture ? parseCodexPicker(capture) : null
- const list = picker && isCodexList(picker) ? picker : null
- if (list && previous && sameCodexPicker(previous, list)) return list
- previous = list
- await sleep(CODEX_SETTLE_MS)
- }
- return null
- }
-
- /**
- * After a model's row: its reasoning picker, or 'closed' when the picker went away and the composer
- * is back, which is a model the catalog did not describe applying its one effort at once.
- */
- private async waitCodexAfterModelRow(session: RegisteredSession): Promise<CodexPicker | 'closed' | null> {
- const deadline = Date.now() + PICKER_STEP_MS
- while (Date.now() < deadline) {
- const capture = await this.deps.capture(session.agentId, 100)
- if (capture) {
- const picker = parseCodexPicker(capture)
- if (picker?.kind === 'efforts') return picker
- if (!picker && (await this.deps.readScreen(session, capture))?.pane.idle) return 'closed'
- }
- await sleep(100)
- }
- return null
- }
-
private async setCursor(session: RegisteredSession, target: RuntimeProfile): Promise<void> {
const cursorTarget = this.deps.manager.cursorTarget(session.sessionId, target.id)
if (!cursorTarget) throw new RuntimeProfileControlError('MODEL_UNAVAILABLE')
diff --git a/cli/src/lib/runtimeProfileController.spec.ts b/cli/src/lib/runtimeProfileController.spec.ts
index 2514fe03a..66d46b7b1 100644
--- a/cli/src/lib/runtimeProfileController.spec.ts
+++ b/cli/src/lib/runtimeProfileController.spec.ts
@@ -11,6 +11,7 @@ import {
parseCursorParameterRows,
paneModal,
RuntimeProfileController,
+ RuntimeProfileControlError,
} from './runtimeProfileController.js'
import {
CLAUDE_PROMPT, CLAUDE_REWIND_CONFIRM, CLAUDE_REWIND_EMPTY, CLAUDE_REWIND_LIST, CLAUDE_REWIND_LIST_MESSAGE_FOCUSED,
@@ -432,6 +433,32 @@ describe('runtime pane parsing', () => {
})
describe('RuntimeProfileController', () => {
+ it('cancels the original conversation transaction after the registry row is rebound in place', async () => {
+ const value = session('claude'), original = structuredClone(value), manager = new RuntimeProfileManager()
+ manager.hydrate(value, [])
+ manager.ingestPane(value, 'Sonnet 5 with low effort\n❯ ', true)
+ const target = encodeRuntimeProfile({ sessionId: 'h1', engine: 'claude', model: 'opus', effort: 'high' })
+ const cancelled = vi.spyOn(manager, 'cancelControl'), finished = vi.spyOn(manager, 'finishControl'), release = vi.fn()
+ const controller = new RuntimeProfileController({
+ manager, getSession: () => value, validateRuntime: async () => true, capture: async () => CLAUDE_PROMPT,
+ sendText: vi.fn(async () => true), sendLiteral: vi.fn(async () => true), sendKey: vi.fn(async () => true), acquireInput: () => release,
+ modelControlFor: bound => ({ validate: async () => {}, apply: async () => {
+ value.sessionId = 'replacement'
+ value.tmuxPane = '%2'
+ value.runtimes[0] = { backend: 'tmux', paneId: '%2' }
+ expect(bound.sessionId).toBe('s1')
+ expect(bound.runtimes).toEqual(original.runtimes)
+ throw new RuntimeProfileControlError('BUSY')
+ } }),
+ })
+ await expect(controller.setProfile('h1', target)).rejects.toMatchObject({ code: 'BUSY' })
+ expect(cancelled).toHaveBeenCalledExactlyOnceWith('s1')
+ expect(finished).not.toHaveBeenCalled()
+ expect(release).toHaveBeenCalledOnce()
+ expect(manager.beginControl(original, parseRuntimeProfile(target)!)).toBe(true)
+ manager.cancelControl('s1')
+ })
+
it('sets Claude model and effort only after transcript confirmations', async () => {
const value = session('claude')
const manager = new RuntimeProfileManager()
diff --git a/cli/src/lib/runtimeProfileController.ts b/cli/src/lib/runtimeProfileController.ts
index 73b0e72c8..ca5304b8e 100644
--- a/cli/src/lib/runtimeProfileController.ts
+++ b/cli/src/lib/runtimeProfileController.ts
@@ -2,9 +2,31 @@
export * from './runtimeControl.js'
export { inspectRuntimePane, paneModal } from '../engines/screens.js'
import { screenFor } from '../engines/screens.js'
+import { modelControlFor } from '../engines/modelControls.js'
import { RuntimeProfileController as Controller, type RuntimeProfileControllerDeps } from './runtimeControl.js'
export class RuntimeProfileController extends Controller {
- constructor(deps: Omit<RuntimeProfileControllerDeps, 'readScreen'> & Partial<Pick<RuntimeProfileControllerDeps, 'readScreen'>>) {
- super({ readScreen: async (session, capture) => capture === null ? null : screenFor(session.engine).inspect(capture), ...deps })
+ constructor(deps: Omit<RuntimeProfileControllerDeps, 'readScreen' | 'modelControlFor'> & Partial<Pick<RuntimeProfileControllerDeps, 'readScreen' | 'modelControlFor'>>) {
+ super({
+ readScreen: async (session, capture) => capture === null ? null : screenFor(session.engine).inspect(capture),
+ modelControlFor: session => {
+ const control = modelControlFor(session.engine)
+ if (!control) return undefined
+ const catalog = () => deps.manager.codexCatalog(session)
+ let snapshot: Awaited<ReturnType<typeof catalog>> = []
+ return {
+ validate: async check => {
+ if (check.stage === 'target') snapshot = await catalog()
+ await control.validate({ ...check, session, catalog: snapshot })
+ },
+ apply: input => control.apply({ ...input, session, catalog: snapshot }, {
+ catalog, capture: lines => deps.capture(session.agentId, lines),
+ text: text => deps.sendText(session.agentId, text), key: key => deps.sendKey(session.agentId, key),
+ waitForModel: ms => deps.manager.waitForModel(session.sessionId, ms),
+ waitForProfile: ms => deps.manager.waitForProfile(session.sessionId, ms),
+ confirmEffort: async effort => { deps.manager.confirmEffort(session.sessionId, effort) },
+ }),
+ }
+ }, ...deps,
+ })
}
}
diff --git a/cli/src/lib/terminalBackendCoordinator.spec.ts b/cli/src/lib/terminalBackendCoordinator.spec.ts
index 2e4498d90..847fa41fa 100644
--- a/cli/src/lib/terminalBackendCoordinator.spec.ts
+++ b/cli/src/lib/terminalBackendCoordinator.spec.ts
@@ -203,6 +203,19 @@ describe('TerminalBackendCoordinator', () => {
expect(submit).toHaveBeenCalledWith(tmux, 'hello', undefined)
})
+ it('refuses a revoked submit after the locator validation awaited', async () => {
+ const submit = submitBy({ state: 'succeeded', dispatch: 'executed' })
+ const terminal = backend('tmux:default', submit)
+ const coordinator = new TerminalBackendCoordinator([terminal], ['tmux'])
+ const current = session(), acquired = await coordinator.acquireLease(current)
+ if (acquired.state !== 'succeeded') throw new Error('no lease')
+ let allowed = true
+ terminal.validate = vi.fn(async () => { allowed = false; return { state: 'alive' as const } })
+ expect(await coordinator.submitTextForLease(current, acquired.value, 'hello', { allowed: () => allowed }))
+ .toMatchObject({ state: 'failed', dispatch: 'not_started', reason: 'terminal control revoked' })
+ expect(submit).not.toHaveBeenCalled()
+ })
+
it('hands the check before the Enter to the backend, on every way a text is submitted', async () => {
const submit = submitBy({ state: 'succeeded', dispatch: 'executed' })
const coordinator = new TerminalBackendCoordinator([backend('tmux:default', submit)], ['tmux'])
diff --git a/cli/src/lib/terminalBackendCoordinator.ts b/cli/src/lib/terminalBackendCoordinator.ts
index ceca5dac5..958cbe41b 100644
--- a/cli/src/lib/terminalBackendCoordinator.ts
+++ b/cli/src/lib/terminalBackendCoordinator.ts
@@ -287,6 +287,7 @@ export class TerminalBackendCoordinator {
if (!backend) continue
const validation = await this.validateRuntime(backend, runtime, session)
if (validation.state !== 'alive') continue
+ if (options?.allowed && !options.allowed()) return terminalActionNotStarted('terminal control revoked')
const result = await backend.submitText(runtime, text, options)
if (result.state === 'succeeded') {
lease.runtime = runtime
diff --git a/cli/src/lib/terminalTypes.ts b/cli/src/lib/terminalTypes.ts
index cc24969f3..bd5b10ba8 100644
--- a/cli/src/lib/terminalTypes.ts
+++ b/cli/src/lib/terminalTypes.ts
@@ -211,7 +211,11 @@ export function terminalActionRejected(reason: string): {
* engine can open a dialog between a paste and its Enter (a long or multi-line one waits up to 1.5 s for
* the engine to take it in, tmux.ts), and that Enter would answer the dialog.
*/
-export interface SubmitOptions { beforeEnter?: () => Promise<string | null> }
+export interface SubmitOptions {
+ beforeEnter?: () => Promise<string | null>
+ /** Synchronous authority fence, checked immediately before paste/Enter dispatch, including queues. */
+ allowed?: () => boolean
+}
/** The text was typed and its Enter not pressed, for `reason`: it waits in the composer, unsent. */
export function terminalEnterWithheld(reason: string): { state: 'unknown'; dispatch: 'possibly_executed'; reason: string } {
diff --git a/cli/src/lib/tmux.spec.ts b/cli/src/lib/tmux.spec.ts
index c4f810d75..ea3a91fd9 100644
--- a/cli/src/lib/tmux.spec.ts
+++ b/cli/src/lib/tmux.spec.ts
@@ -628,6 +628,34 @@ if [ "$1" = "paste-buffer" ] && [ "$TMUX_SUBMIT_FAIL" = "1" ]; then exit 2; fi
expect(await sendToTmux('%7', 'clear to send', async () => null)).toBe(true)
expect(commands().at(-1)).toBe('send-keys -t %7 Enter')
+ // A revoked engine operation must not paste after waiting for a tmux room or buffer load.
+ writeFileSync(argsFile, '')
+ expect(await sendToTmux('%7', '/model next', undefined, () => false)).toBe(false)
+ expect(readFileSync(argsFile, 'utf8')).toBe('')
+ writeFileSync(argsFile, '')
+ expect(await sendToTmux('%7', '/model next', undefined, () => readFileSync(argsFile, 'utf8') === '')).toBe(false)
+ expect(commands()).toEqual(['load-buffer -b buffer -', 'delete-buffer -b buffer'])
+
+ // Revocation while the caller awaits a final admission check must withhold Enter.
+ writeFileSync(argsFile, '')
+ let allowed = true
+ expect(await sendToTmux('%7', '/model next', async () => { allowed = false; return null }, () => allowed))
+ .toEqual({ withheld: 'terminal control revoked' })
+ expect(commands()).toEqual(['load-buffer -b buffer -', 'paste-buffer -t %7 -b buffer -p -d'])
+
+ // tmux 3.4 can queue a paste behind a terminal attach. Revocation follows it through that queue.
+ writeFileSync(argsFile, '')
+ assumeTmuxVersion({ major: 3, minor: 4 })
+ allowed = true
+ const leave = await tmuxControlGate.enter('attach')
+ const queued = sendToTmux('%7', '/model next', undefined, () => allowed)
+ await new Promise(resolve => setTimeout(resolve, 10))
+ allowed = false
+ leave()
+ expect(await queued).toBe(false)
+ expect(readFileSync(argsFile, 'utf8')).toBe('')
+ assumeTmuxVersion(null)
+
writeFileSync(argsFile, '')
process.env.TMUX_SUBMIT_FAIL = '1'
expect(await sendToTmux('%7', 'must not send')).toBe(false)
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index 0f726348d..047a571cf 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -1377,17 +1377,19 @@ function tmuxDeleteBuffer(name: string): Promise<void> {
*
* A buffer set and deleted is a notification to every control client, which on a tmux before 3.7
* crashed the server while one was attaching: the paste waits for none to be (tmuxControlGate.ts). */
-function tmuxPasteText(pane: string, content: string, bracketed: boolean): Promise<boolean> {
- return inTmuxRoom('notify', () => pasteThroughBuffer(pane, content, bracketed))
+function tmuxPasteText(pane: string, content: string, bracketed: boolean, allowed?: () => boolean): Promise<boolean> {
+ return inTmuxRoom('notify', () => pasteThroughBuffer(pane, content, bracketed, allowed))
}
-async function pasteThroughBuffer(pane: string, content: string, bracketed: boolean): Promise<boolean> {
+async function pasteThroughBuffer(pane: string, content: string, bracketed: boolean, allowed?: () => boolean): Promise<boolean> {
+ if (allowed && !allowed()) return false
const bufferName = `machinemsg-${process.pid}-${++injectBufferSequence}`
if (!(await tmuxLoadBuffer(bufferName, bracketed ? neutralizePasteControls(content) : content))) {
await tmuxDeleteBuffer(bufferName)
console.error(`[tmux] load-buffer for ${pane} failed`)
return false
}
+ if (allowed && !allowed()) { await tmuxDeleteBuffer(bufferName); return false }
const args = ['paste-buffer', '-t', pane, '-b', bufferName]
if (bracketed) args.push('-p')
args.push('-d')
@@ -1415,14 +1417,15 @@ async function pasteThroughBuffer(pane: string, content: string, bracketed: bool
* from being pressed, and comes back as `{ withheld }`, the text left typed. An engine can open a dialog
* in that gap, mid-turn, and the Enter would answer it.
*/
-export function sendToTmux(pane: string, text: string, beforeEnter?: () => Promise<string | null>): Promise<boolean | { withheld: string }> {
+export function sendToTmux(pane: string, text: string, beforeEnter?: () => Promise<string | null>, allowed?: () => boolean): Promise<boolean | { withheld: string }> {
const content = text.replace(/[\r\n]+$/, '') // strip trailing newlines so the submit Enter isn't doubled
return (async () => {
const needsSettle = content.length > INJECT_FASTPATH_MAXLEN || /[\r\n]/.test(content)
- if (!(await tmuxPasteText(pane, content, true))) return false
+ if (!(await tmuxPasteText(pane, content, true, allowed))) return false
if (needsSettle) await sleep(Math.min(1500, INJECT_PASTE_DELAY_BASE_MS + Math.floor(content.length / 60)))
const withheld = beforeEnter ? await beforeEnter() : null
if (withheld) return { withheld }
+ if (allowed && !allowed()) return { withheld: 'terminal control revoked' }
return tmuxEnter(pane)
})()
}
diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.ts
index 58270eb10..254b84cf8 100644
--- a/cli/src/lib/tmuxBackend.ts
+++ b/cli/src/lib/tmuxBackend.ts
@@ -438,7 +438,7 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
}
async submitText(runtime: TmuxRuntimeRef, text: string, options?: SubmitOptions): Promise<TerminalActionResult> {
- const sent = await sendToTmux(runtime.paneId, text, options?.beforeEnter)
+ const sent = await sendToTmux(runtime.paneId, text, options?.beforeEnter, options?.allowed)
return typeof sent === 'boolean' ? legacyActionResult(sent, 'tmux submission') : terminalEnterWithheld(sent.withheld)
}
diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.md
index 8f88e956d..29067036e 100644
--- a/cli/src/services/AGENTS.md
+++ b/cli/src/services/AGENTS.md
@@ -51,7 +51,7 @@ that process. A process per risk, not per feature (`SERVICE_HOSTS` in `src/harne
| Process | Services | Why its own | Started |
|---|---|---|---|
-| `engine-claude`, `engine-codex` | history/last-turn readers and live parsers (`src/engines/worker/`) | engine parsing outside core; read-only snapshots and no core capabilities | on demand |
+| `engine-claude`, `engine-codex` | history, live parsers, runtime profiles, screens and model control (`src/engines/worker/`) | engine behavior outside core; snapshots and revocable model-control grants | on demand |
| `search` | search | native `node:sqlite`, the index's memory | always |
| `viewers` | viewers, store | the viewer servers, the remote viewer streams and rendered surfaces, minutes-long installs | always |
| `edge` | workspaces, usage, monitor, projects, handoff, recaps, windowNames, shell | light pure-JS services: isolated from the core, not from each other | always |
diff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.ts
index 614c95f34..ef8db7f68 100644
--- a/cli/src/services/inline.spec.ts
+++ b/cli/src/services/inline.spec.ts
@@ -1,3 +1,4 @@
+import { modelControlFor } from '../engines/modelControls.js'
import { screenFor } from '../engines/screens.js'
import { describe, expect, it } from 'vitest'
import { engineTranscriptFor } from '../engines/transcripts.js'
@@ -26,6 +27,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, runtimeFor, screenFor, 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, screenFor, modelControlFor, 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.ts
index 2977f7afe..532f1b7e4 100644
--- a/cli/src/services/inline.ts
+++ b/cli/src/services/inline.ts
@@ -15,6 +15,7 @@
export { engineTranscriptFor } from '../engines/transcripts.js'
export { liveFor } from '../engines/live.js'
export { screenFor } from '../engines/screens.js'
+export { modelControlFor } from '../engines/modelControls.js'
export { runtimeFor } from '../engines/runtime.js'
export { startGateway } from '../gateway/start.js'
export { startCommandBar } from './commandBar.js'
diff --git a/docs/design/2026-10-08-engine-model-control.md b/docs/design/2026-10-08-engine-model-control.md
new file mode 100644
index 000000000..17007f053
--- /dev/null
+++ b/docs/design/2026-10-08-engine-model-control.md
@@ -0,0 +1,66 @@
+# Engine model control
+
+Claude Code and Codex choose model commands and walk model/effort pickers in their engine workers.
+The native drivers live in `engines/<engine>/modelControl.ts`, behind `Engine.modelControl`.
+Core still owns the user's requested target, accepted profile, session identity and exclusive input lease.
+Other engines keep their existing controller implementations for their own migration batches.
+
+## One request, one grant
+
+`lib/runtimeControl.ts` validates a requested profile and takes the agent's input lease. Its native
+control port is bound before its first await. Core snapshots the agent/conversation, process and
+terminal binding as scalar data; editing the registry row in place cannot retarget an old request.
+Native preflight rules (Codex's effort policy and plan scope) run in the worker against supplied facts.
+The catalog snapshot used for preflight is also used for the first picker walk; the native driver can
+request its existing single refresh if the picker has a model missing from that snapshot.
+
+After generic admission and `beginControl`, `core/engines/modelControls.ts` gives the authenticated
+engine service a random, single-operation grant. The worker receives a plain session and target,
+never a tmux locator, registry handle or general core API. Its host permits bounded capture, text,
+keys, catalog refresh and waits for core's profile confirmation. An effort confirmation must match
+the target. Core uses its own bound agent for every terminal effect and its own conversation for
+confirmation state. The ordinary denial of all other engine-worker queries remains in place.
+
+Both ends validate the private v1 messages and routing metadata. Core checks the connection generation,
+current binding, deadline and grant on each operation. It rejects overlapping host requests, more
+than 128 queries or 32 writes, captures beyond 100 lines/256 KiB, control bytes in text, and requests
+outside the finite key vocabulary. Four controls per engine may run concurrently; excess UI intent
+is refused without queuing it for later. Validation has a five-second budget, apply has 30 seconds,
+and a host query has ten seconds. Worker deadlines recycle that worker, never core.
+
+A disconnect, replacement, timeout, completion or invalid host response revokes the grant. Core checks
+that revocation after awaited terminal validation. The tmux submission pipeline also checks it after
+its room queue, after loading a buffer, and immediately before Enter. A delayed callback cannot dispatch
+another command after revocation. An OS command already dispatched can have an uncertain outcome;
+revocation does not undo it, and core never retries an uncertain model change automatically.
+
+Native Codex cleanup uses the same grant. Losing the worker can therefore leave its picker open.
+Core does not guess an Escape after that loss. The user can close the picker and make a new request;
+newly observed CLI settings remain real evidence even when the requesting control failed.
+
+## Compatibility and composition
+
+The parent-bound `HARNESSD_ENGINE_MODEL_CONTROL=<master-pid>:1` capability is additive. An older master
+or explicit inline mode selects inline native facets at composition time, using the same core grant
+broker. An unavailable worker never selects inline execution. `lib/runtimeProfileController.ts` is an
+explicit compatibility wrapper for direct embedders and recorded controller fixtures; normal core
+imports only `lib/runtimeControl.ts`. Architecture tests exclude native model drivers and picker
+interpretation from the normal core import closure.
+
+## Validation scope
+
+Recorded controller/picker cases preserve command selection, catalog refresh and refusal behavior.
+Broker/worker tests exercise malformed requests, grant limits, disconnects, timeouts, in-place rebinding,
+late effects, missing capabilities and explicit inline mode. Terminal tests cover revocation during
+validation, buffer loading, queue admission and the final Enter check.
+
+`e2e/engineModelControl.e2e.ts` runs real supervised workers, core and tmux under private homes. It checks
+Claude commands in isolated and inline mode, freezes either worker after its model command reaches the
+fake CLI, and verifies failure, no resumed control, continued CLI/core processes and a new explicit
+request after recovery. `e2e/models.e2e.ts` keeps Codex's model-list/effort/refreshed-catalog cases.
+These are deterministic CLI fixtures, not real-model/account acceptance evidence. The opt-in
+`PERF_MODEL_CONTROLS=1 PERF_READERS=1` workload measures model-change latency and core plus both workers
+alongside the existing empty/idle/active windows; compare identical fixtures/toolchains on both builds.
+
+This completes only model control. Native question-answer navigation, submission verification,
+hook admission/installers, launch/discovery/resume and native control connections remain to migrate.