diff --git a/README.md b/README.md index 2bfe319..b1d13c4 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,10 @@ Claudiu is a native desktop app, written in Rust with [Rune](https://github.com/ Each session is your own `claude` process in a real terminal, and sign-in stays with Claude Code. Around it, Claudiu adds a sidebar of running and recent sessions, notifications when a background session finishes or asks something, an editor mode (Ctrl+Shift+E), usage meters, a GitHub pane, cards Claude draws inline, sessions that move between git worktrees, extra accounts that share one configuration, and Codex and OpenCode subagents (Settings → Custom subagents). Codex subagents need Node and a `codex login`, OpenCode subagents need `opencode` on PATH, and with Allow edits on, either acts without Claude Code's permission rules. With Codex subagents on, the sidebar also shows Codex's 5-hour and 7-day limits, which Claudiu reads from the session logs in `~/.codex`. Settings lists the rest. +While a custom subagent works, the main conversation shows a line for each plan and tool step, and the subagent's own view in Claude Code's tasks list streams its messages, reasoning and command output. The first Codex run takes longer while npm downloads the adapter. Claude can choose a Codex subagent's effort when it starts one (`max` runs as Codex's `xhigh`); otherwise Codex uses the effort in `~/.codex/config.toml`. + +A message Claude sends a running Codex subagent reaches it in the task it is working on, and its answer streams like the rest. OpenCode takes such messages too if its version supports them. Otherwise, and once the subagent has finished, Claude Code sends the message as a follow-up. + ## What it touches Claudiu never calls the Anthropic API or deletes a transcript, and it changes Claude Code's settings only when you flip a switch. Its network use is GitHub (the update check and the GitHub pane), plus npm and OpenAI once you turn on Codex subagents, and the providers you set up in OpenCode once you turn on OpenCode subagents. Terminal contents are never logged. diff --git a/mod/hooks/register.js b/mod/hooks/register.js index 3d504f6..88ec5f8 100644 --- a/mod/hooks/register.js +++ b/mod/hooks/register.js @@ -33,6 +33,7 @@ const MODELS = { } const CARD_ROWS = 6 // reserved for a card until Claudiu has measured it const PROMPT_MAX = 20000 // characters of a message Claudiu asks the session to send (the editor's Ask Claude) +const INBOX_TEXT_MAX = 20000 // UTF-16 units, matching the ACP helper const EFFORTS = ['low', 'medium', 'high', 'xhigh', 'max'] const ASK_MODELS = ['haiku', 'sonnet', 'opus'] const VISUAL_TOOL = 'mcp__claudiu__show_visual' @@ -58,7 +59,8 @@ const cardRows = new Map() // show_visual call id -> rows reserved for its card const AGENT_NAMES = { codex: 'Codex', opencode: 'OpenCode' } // the agents of `claude/subagents.rs`, by their key const AGENT_PREFIX = 'Claudiu:' // what Claude Code puts before an agent type this plugin registers const customTypes = new Map() // agent type name -> { agent, model, edits } of each custom agent type Claudiu defined -const customRuns = new Map() // agent id -> { type, prompt, turnId, report, steps } of each custom subagent started +const customRuns = new Map() // agent id -> { type, prompt, effort, turnId, report, steps } of each custom subagent started +const agentCalls = new Map() // Agent call id -> { type, description, effort } of each running call that asked for an effort const published = new Set() // call ids whose card file this process wrote from the transcript let rowsPoll // watches the heights Claudiu measures let visualChain = Promise.resolve() // visual writes in order, without holding up the stream @@ -375,11 +377,25 @@ async function registerSubagents($) { } } -// Notes the task of each custom subagent as it starts; its turns are answered by customStep. +// Notes the effort an Agent call asks for, which the spawn it leads to doesn't carry, while the call runs. +async function onAgentCall($, e, next) { + if (typeof e.effort === 'string') agentCalls.set(e.tool_use_id, { type: e.subagent_type, description: e.description, effort: e.effort }) + try { + return await next(e) + } finally { + agentCalls.delete(e.tool_use_id) + } +} + +// Notes the task and effort of each custom subagent as it starts; its turns are answered by customStep. async function onAgentSpawn($, e, next) { + const effort = agentCalls.get(e.tool_use_id)?.effort ?? null const r = await next(e) if (r.agentId && customTypes.has(e.subagentType)) { - customRuns.set(r.agentId, { type: e.subagentType, prompt: e.prompt, turnId: null, report: null, handedBack: 0, steps: [] }) + // The agent's first turn can start before this returns, taking the run up from the agent list; it keeps that run. + const run = customRuns.get(r.agentId) + if (run) Object.assign(run, { prompt: e.prompt, effort: effort ?? run.effort }) + else customRuns.set(r.agentId, { type: e.subagentType, prompt: e.prompt, effort, turnId: null, report: null, handedBack: 0, steps: [] }) } return r } @@ -389,8 +405,12 @@ async function onAgentSpawn($, e, next) { async function customRun($, agentId) { if (customRuns.has(agentId) || customTypes.size === 0) return customRuns.get(agentId) const agent = (await $.agent.list().catch(() => [])).find(a => a.id === agentId) + // The spawn may have noted the run while the list was read. + if (customRuns.has(agentId)) return customRuns.get(agentId) if (!agent || !customTypes.has(agent.type)) return undefined - const run = { type: agent.type, prompt: null, turnId: null, report: null, handedBack: 0, steps: [] } + // A first turn that starts before its spawn hook returns finds its Agent call's effort by what the list shows of it. + const call = [...agentCalls.values()].find(c => c.type === agent.type && c.description === agent.description) + const run = { type: agent.type, prompt: null, effort: call?.effort ?? null, turnId: null, report: null, handedBack: 0, steps: [] } customRuns.set(agentId, run) return run } @@ -426,6 +446,45 @@ function withSteps(report, name, steps) { return `${report}\n\n---\nSteps ${name} ran (${steps.length}):\n${listed.join('\n')}` } +function showActivity($, label, text) { + const line = displayText(text).replace(/\s+/g, ' ').trim() + $.ui.log(`${label} · ${line.length > 200 ? line.slice(0, 199) + '…' : line}`) +} + +function displayText(text) { + // Color and cursor codes first: removing only their escape character would leave `[31m` behind. + return text.replace(/\x1b\[[0-9;:?]*[ -/]*[@-~]/g, '').replace(/\r\n?/g, '\n').replace(/[\x00-\x08\x0b-\x1f\x7f-\x9f]/g, '') +} + +// Only one write can be awaiting acknowledgement. Otherwise a second delivery could overwrite the first +// between polls. Until the helper takes the delivery, Claude Code can still queue it the usual way. +function onSessionReceive($, e, next) { + const run = customRuns.get(e.agentId) + const inbox = run?.inbox + if (!inbox || inbox.closed || !['coordinator', 'peer', 'peer-send-message'].includes(e.origin?.kind) + || typeof e.text !== 'string' || !e.text.trim() || !/\P{White_Space}/u.test(e.text) || e.text.length > INBOX_TEXT_MAX) return next(e) + + const delivered = inbox.tail.then(async () => { + if (inbox.closed) return false + const seq = inbox.seq + 1 + const accepted = new Promise(resolve => { inbox.ack = resolve }) + inbox.write = $.fs.write(inbox.path, JSON.stringify({ seq, text: e.text })).then(() => true, () => false) + if (!(await inbox.write)) { + closeInbox(inbox) + return inbox.seq === seq + } + return accepted + }) + inbox.tail = delivered + return delivered.then(ok => ok ? { consumed: 'Delivered to the subagent helper' } : next(e)) +} + +function closeInbox(inbox) { + if (!inbox) return + inbox.closed = true + inbox.ack?.(false) +} + // Answers one step of a custom subagent: runs the task in its agent, streams what the agent writes and does as the // subagent's own text (saved in its transcript, which only the person reads), and hands back the agent's last message // and the steps it took as the report. The agent runs once per turn; a later step of the same turn (a refused hand-back) @@ -439,18 +498,64 @@ async function* customStep($, e, next, run) { run.steps = [] const { agent, model, edits } = customTypes.get(run.type) const name = AGENT_NAMES[agent] + const label = `${name} (${e.agentId})` + const starting = agent === 'codex' ? 'Starting Codex adapter. On first run, npm may need to download it.' : 'Starting OpenCode.' + showActivity($, label, starting) yield { kind: 'text', index: 0, text: `${name} on ${model}, ${edits ? 'edits allowed' : 'read-only'}\n\n` } run.report = null - for await (const event of helperEvents($, { agent, model, edits, cwd: await $.session.cwd(), prompt }, next.signal)) { - if (event.kind === 'text') yield { kind: 'text', index: 0, text: event.text } - else if (event.kind === 'step') { - run.steps.push(event.text) - yield { kind: 'text', index: 0, text: `\n▸ ${event.text}\n` } - } else if (event.kind === 'report') run.report = event.text - else if (event.kind === 'failed') run.report = `${name} failed: ${event.reason}` + let previousKind + let inbox + let helperEnded = false + const exe = await $.env.get('CLAUDIU_EXE') + const cwd = await $.session.cwd() + // Read after the awaits above, by which time a spawn still finishing has noted the effort. + const request = { agent, model, effort: run.effort, edits, cwd, prompt, live_messages: true } + try { + for await (const event of helperEvents($, exe, request, next.signal)) { + if (event.kind === 'inbox') { + if (!inbox && !helperEnded) { + inbox = { id: event.id, path: event.path, seq: 0, tail: Promise.resolve() } + run.inbox = inbox + } + continue + } + if (event.kind === 'accepted') { + if (inbox?.ack && !inbox.closed && event.seq === inbox.seq + 1) { + inbox.seq = event.seq + inbox.ack(true) + inbox.ack = null + } + continue + } + if (event.kind === 'text' || event.kind === 'thought' || event.kind === 'output') { + if (event.kind === 'thought' && previousKind !== 'thought') showActivity($, label, 'Thinking') + if (event.kind === 'text' && previousKind !== 'text') showActivity($, label, 'Writing a response') + const prefix = previousKind === event.kind ? '' : { text: previousKind ? '\n\n' : '', thought: '\n\nThinking\n', output: '\n\nTool output\n' }[event.kind] + yield { kind: 'text', index: 0, text: prefix + displayText(event.text) } + } else if (event.kind === 'step' || event.kind === 'progress') { + if (event.kind === 'step') run.steps.push(event.text) + showActivity($, label, event.text) + yield { kind: 'text', index: 0, text: `\n▸ ${displayText(event.text)}\n` } + } else if (event.kind === 'report' || event.kind === 'failed') { + helperEnded = !event.spawnError + closeInbox(inbox) + run.report = event.kind === 'report' ? event.text : `${name} failed: ${event.reason}` + } + previousKind = event.kind + } + } finally { + if (run.inbox === inbox) run.inbox = null + const needsCleanup = inbox?.ack || !helperEnded + closeInbox(inbox) + // The normal exit removes the file in Rust. An interrupted child or a write racing exit can leave it behind. + if (needsCleanup && inbox?.write) { + await inbox.write + await $.process.run([exe, '--acp', '--cleanup', inbox.id]).catch(() => {}) + } } if (next.signal?.aborted) return run.report ??= `${name} failed: the helper stopped without an answer.` + if (run.report.startsWith(`${name} failed:`)) showActivity($, label, run.report) } const message = withSteps(run.report, AGENT_NAMES[customTypes.get(run.type).agent], run.steps) if (run.handedBack >= 2) { @@ -468,8 +573,7 @@ async function* customStep($, e, next, run) { // The helper's events, one per line of its output. Stops early, ending the helper and the agent, when the turn is // interrupted. -async function* helperEvents($, request, signal) { - const exe = await $.env.get('CLAUDIU_EXE') +async function* helperEvents($, exe, request, signal) { let pending = '' try { for await (const chunk of $.process.spawn({ argv: [exe, '--acp'], input: JSON.stringify(request) })) { @@ -484,14 +588,18 @@ async function* helperEvents($, request, signal) { } } } catch (err) { - yield { kind: 'failed', reason: 'the helper could not run (' + String(err?.message ?? err).slice(0, 200) + ')' } + yield { kind: 'failed', spawnError: true, reason: 'the helper could not run (' + String(err?.message ?? err).slice(0, 200) + ')' } } } function parseEvent(line) { try { const event = JSON.parse(line) - return typeof event?.kind === 'string' ? event : null + if (event?.kind === 'failed') return typeof event.reason === 'string' ? event : null + if (event?.kind === 'inbox' && typeof event.id === 'string' && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(event.id) && typeof event.path === 'string' && event.path) return event + if (event?.kind === 'accepted' && Number.isSafeInteger(event.seq) && event.seq > 0) return event + if (['text', 'thought', 'output', 'step', 'progress', 'report'].includes(event?.kind) && typeof event.text === 'string') return event + return null } catch { return null } @@ -690,6 +798,8 @@ export function register(on) { on('ui.render', { component: 'ToolUse' }, onVisualRow) on('ui.render', { component: 'ToolGroup' }, onVisualGroup) on('turn.step', onTurnStep) + on('tool.call', { tool: 'Agent' }, onAgentCall) on('agent.spawn', onAgentSpawn) + on('session.receive', onSessionReceive) on('session.start', onSessionStart) } diff --git a/mod/hooks/subagents.test.ts b/mod/hooks/subagents.test.ts index f8bd1ba..7f25f28 100644 --- a/mod/hooks/subagents.test.ts +++ b/mod/hooks/subagents.test.ts @@ -9,11 +9,10 @@ const SUBAGENTS = JSON.stringify({ codex: { edits: false, types: [type('codex-gp // What the engine answers beneath the mod for a session with Codex on. `helper` is what `claudiu --acp` writes; // `requests` collects what the mod sent it. -function engine(on: any, helper: string[], requests: unknown[], subagents = SUBAGENTS) { +function engine(on: any, helper: string[] | (() => AsyncGenerator<{ stream: string, text: string }, unknown>), requests: unknown[], subagents = SUBAGENTS) { mock.env(on, { CLAUDIU_SUBAGENTS: subagents, CLAUDIU_EXE: '/apps/claudiu' }) mock.clock(on) on('fs.read', () => ({ value: '' })) - on('fs.write', () => ({ value: undefined })) on('session.id', () => ({ value: 's1' })) on('session.model', () => ({ value: 'claude-haiku-5-5' })) on('session.cwd', () => ({ value: '/work/sub' })) @@ -28,6 +27,7 @@ function engine(on: any, helper: string[], requests: unknown[], subagents = SUBA on('agent.spawn', () => ({ model: 'haiku', agentId: 'a1' })) on('process.spawn', async function* (_$: any, e: any) { requests.push({ argv: e.argv, input: JSON.parse(e.input) }) + if (typeof helper === 'function') return yield* helper() // Pieces cut mid-line, as a pipe delivers them. const out = helper.join('\n') + '\n' yield { stream: 'stdout', text: out.slice(0, 7) } @@ -42,6 +42,33 @@ function engine(on: any, helper: string[], requests: unknown[], subagents = SUBA return registered } +test('startup and activity reach the transcript while the helper is still running', async ($, on) => { + const log: string[] = [] + let logAtSpawn: string[] = [] + let logBeforeReport: string[] = [] + on('ui.log', (_$: any, e: any) => { log.push(e.text); return { value: undefined } }) + engine(on, async function* () { + logAtSpawn = [...log] + yield { stream: 'stdout', text: '{"kind":"progress","tex' } + yield { stream: 'stdout', text: 't":"Session ready."}\n{"kind":"thought","text":"Checking "}\n' } + yield { stream: 'stdout', text: '{"kind":"thought","text":"the parser."}\n{"kind":"step","text":"Run tests"}\n' } + yield { stream: 'stdout', text: '{"kind":"progress","text":"Run tests · failed"}\n{"kind":"output","text":"\\u001b[31mtest failed\\u001b[0m"}\n' } + logBeforeReport = [...log] + yield { stream: 'stdout', text: '{"kind":"report","text":"Parser test failed."}\n' } + return { value: { code: 0, signal: null } } + }, []) + await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true }) + await $.agent.spawn({ subagentType: 'Claudiu:codex-gpt-5-5', prompt: 'Find the bug' }) + const chunks = await step($, 't1', 0, 'a1') + + expect(logAtSpawn).toEqual(['Codex (a1) · Starting Codex adapter. On first run, npm may need to download it.']) + expect(logBeforeReport).toEqual([...logAtSpawn, 'Codex (a1) · Session ready.', 'Codex (a1) · Thinking', 'Codex (a1) · Run tests', 'Codex (a1) · Run tests · failed']) + const text = chunks.filter(c => c.kind === 'text').map(c => c.text).join('') + expect(text).toContain('Thinking\nChecking the parser.') + expect(text).toContain('Tool output\ntest failed') + expect(JSON.parse(chunks.find(c => c.kind === 'input').json).message).toBe('Parser test failed.\n\n---\nSteps Codex ran (1):\n- Run tests') +}) + async function step($: any, turnId: string, index: number, agentId?: string) { const chunks: any[] = [] const stream = $.turn.step({ turnId, index, model: 'haiku', messageCount: 1, agentId }) @@ -49,6 +76,103 @@ async function step($: any, turnId: string, index: number, agentId?: string) { return chunks } +function gate() { + let resolve!: (value: T) => void + const promise = new Promise(r => { resolve = r }) + return { promise, resolve } +} + +const INBOX_ID = 'be4bebed-a8ee-4afb-b7a1-c06d33ff3083' +const INBOX_PATH = `/data/acp/${INBOX_ID}.json` +const helperChunk = (event: object) => ({ stream: 'stdout', text: JSON.stringify(event) + '\n' }) +const messageTo = (agentId: string, text: string) => ({ agentId, origin: { kind: 'coordinator' as const }, text }) + +test('SendMessage reaches only the running Codex helper and its reaction streams before handback', async ($, on) => { + const ready = gate() + const first = gate() + const second = gate() + const finish = gate() + const reaction = gate() + const writes: any[] = [] + let finished = false + engine(on, async function* () { + yield helperChunk({ kind: 'inbox', id: INBOX_ID, path: INBOX_PATH }) + yield helperChunk({ kind: 'progress', text: 'Waiting for input.' }) + await first.promise + yield helperChunk({ kind: 'accepted', seq: 1 }) + await second.promise + yield helperChunk({ kind: 'accepted', seq: 2 }) + yield helperChunk({ kind: 'progress', text: 'Codex received the message in its current turn.' }) + yield helperChunk({ kind: 'text', text: 'I will check both files.' }) + await finish.promise + yield helperChunk({ kind: 'report', text: 'Checked both files.' }) + return { value: { code: 0, signal: null } } + }, []) + on('fs.write', (_$: any, e: any) => { + writes.push({ path: e.path.replace(/\\/g, '/').replace(/^[A-Za-z]:/, ''), body: JSON.parse(e.text) }) + const written = writes.length === 1 ? first : second + written.resolve() + return { value: undefined } + }) + on('ui.log', (_$: any, e: any) => { + if (e.text.endsWith('Waiting for input.')) ready.resolve() + if (e.text.endsWith('Writing a response')) reaction.resolve() + return { value: undefined } + }) + on('session.receive', (_$: any, e: any) => ({ text: e.text })) + await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true }) + await $.agent.spawn({ subagentType: 'Claudiu:codex-gpt-5-5', prompt: 'Find the bug' }) + const running = step($, 't1', 0, 'a1').then(chunks => { finished = true; return chunks }) + await ready.promise + expect(await $.session.receive(messageTo('someone-else', 'Other task'))).toEqual({ text: 'Other task' }) + expect(await $.session.receive(messageTo('a1', 'x'.repeat(20_001)))).toEqual({ text: 'x'.repeat(20_001) }) + const deliveries = await Promise.all([ + $.session.receive(messageTo('a1', 'Check the parser.')), + $.session.receive(messageTo('a1', 'Check the tests too.')), + ]) + expect(deliveries).toEqual([{ consumed: 'Delivered to the subagent helper' }, { consumed: 'Delivered to the subagent helper' }]) + expect(writes).toEqual([ + { path: INBOX_PATH, body: { seq: 1, text: 'Check the parser.' } }, + { path: INBOX_PATH, body: { seq: 2, text: 'Check the tests too.' } }, + ]) + await reaction.promise + expect(finished).toBe(false) + finish.resolve() + const chunks = await running + expect(chunks.filter(c => c.kind === 'text').map(c => c.text).join('')).toContain('I will check both files.') + expect(await $.session.receive(messageTo('a1', 'Now summarize.'))).toEqual({ text: 'Now summarize.' }) +}) + +test('a delivery racing helper exit is queued by Claude and its inbox is cleaned up', async ($, on) => { + const ready = gate() + const wrote = gate() + const cleanup: string[][] = [] + engine(on, async function* () { + yield helperChunk({ kind: 'inbox', id: INBOX_ID, path: INBOX_PATH }) + yield helperChunk({ kind: 'progress', text: 'Waiting for input.' }) + await wrote.promise + yield helperChunk({ kind: 'report', text: 'Finished first.' }) + return { value: { code: 0, signal: null } } + }, []) + on('ui.log', (_$: any, e: any) => { + if (e.text.endsWith('Waiting for input.')) ready.resolve() + return { value: undefined } + }) + on('fs.write', () => { wrote.resolve(); return { value: undefined } }) + on('process.run', (_$: any, e: any) => { + cleanup.push(e.argv) + return { value: { exitCode: 0, stdout: '', stderr: '', isStdoutTruncated: false, isStderrTruncated: false } } + }) + on('session.receive', (_$: any, e: any) => ({ text: e.text })) + await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true }) + await $.agent.spawn({ subagentType: 'Claudiu:codex-gpt-5-5', prompt: 'Find the bug' }) + const running = step($, 't1', 0, 'a1') + await ready.promise + expect(await $.session.receive(messageTo('a1', 'Check one more file.'))).toEqual({ text: 'Check one more file.' }) + await running + expect(cleanup).toEqual([['/apps/claudiu', '--acp', '--cleanup', INBOX_ID]]) +}) + test('a Codex subagent runs the task in Codex and hands back its last message', async ($, on) => { const requests: any[] = [] const registered = engine(on, [ @@ -63,7 +187,7 @@ test('a Codex subagent runs the task in Codex and hands back its last message', await $.agent.spawn({ subagentType: 'Claudiu:codex-gpt-5-5', prompt: 'Find the bug' }) const chunks = await step($, 't1', 0, 'a1') - expect(requests).toEqual([{ argv: ['/apps/claudiu', '--acp'], input: { agent: 'codex', model: 'gpt-5.5', edits: false, cwd: '/work/sub', prompt: 'Find the bug' } }]) + expect(requests).toEqual([{ argv: ['/apps/claudiu', '--acp'], input: { agent: 'codex', model: 'gpt-5.5', effort: null, edits: false, cwd: '/work/sub', prompt: 'Find the bug', live_messages: true } }]) // What Codex writes and does is the agent's own text, which its transcript keeps; Claude gets only the report. const text = chunks.filter(c => c.kind === 'text').map(c => c.text).join('') expect(text).toBe('Codex on gpt-5.5, read-only\n\nLooking.\n▸ Read src/a.rs\n') @@ -86,6 +210,54 @@ test('a Codex subagent runs the task in Codex and hands back its last message', expect(requests.length).toBe(1) }) +test('the effort Claude asks for in its Agent call reaches Codex', async ($, on) => { + const requests: any[] = [] + engine(on, [JSON.stringify({ kind: 'report', text: 'Done.' })], requests) + // Claude Code's Agent tool spawns the agent while the call runs. + let spawned = gate() + let callId = '' + on('tool.call', { tool: 'Agent' }, async (_$: any, e: any) => { + callId = e.tool_use_id + await spawned.promise + return { result: 'started' } + }) + async function agentCall(effort: string) { + callId = '' + spawned = gate() + const call = $.tool.call({ tool: 'Agent', subagent_type: 'Claudiu:codex-gpt-5-5', prompt: 'Find the bug', description: 'Find it', effort }) + while (!callId) await new Promise(r => setTimeout(r, 1)) + await $.agent.spawn({ subagentType: 'Claudiu:codex-gpt-5-5', prompt: 'Find the bug', tool_use_id: callId } as any) + spawned.resolve() + await call + } + await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true }) + await agentCall('high') + await step($, 't1', 0, 'a1') + // The same agent spawned again asks for its own effort. + await agentCall('low') + await step($, 't2', 0, 'a1') + expect(requests.map(r => r.input.effort)).toEqual(['high', 'low']) +}) + +test('a first turn that starts before its spawn is noted still gets the effort its Agent call asked for', async ($, on) => { + const requests: any[] = [] + engine(on, [JSON.stringify({ kind: 'report', text: 'Done.' })], requests) + on('agent.list', () => ({ value: [{ id: 'a1', type: 'Claudiu:codex-gpt-5-5', description: 'Find it' }] })) + const finished = gate() + on('tool.call', { tool: 'Agent' }, async () => { + await finished.promise + return { result: 'done' } + }) + await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true }) + const call = $.tool.call({ tool: 'Agent', subagent_type: 'Claudiu:codex-gpt-5-5', prompt: 'Find the bug', description: 'Find it', effort: 'high' }) + // The agent's turn runs while the call does, before this module has seen its spawn. + await new Promise(r => setTimeout(r, 1)) + await step($, 't1', 0, 'a1') + finished.resolve() + await call + expect(requests.map(r => r.input.effort)).toEqual(['high']) +}) + test('a report with many steps lists the first ones, each cut short', async ($, on) => { const steps = Array.from({ length: 32 }, (_, i) => JSON.stringify({ kind: 'step', text: `Read src/f${i + 1}.rs` })) steps[0] = JSON.stringify({ kind: 'step', text: 'x'.repeat(130) }) @@ -146,7 +318,7 @@ test('an OpenCode subagent runs the task in OpenCode and names it', async ($, on await $.agent.spawn({ subagentType: 'Claudiu:opencode-openai-gpt-6-1-sol', prompt: 'Find the bug' }) const chunks = await step($, 't1', 0, 'a1') - expect(requests.map(r => r.input)).toEqual([{ agent: 'opencode', model: 'openai/gpt-6.1-sol', edits: true, cwd: '/work/sub', prompt: 'Find the bug' }]) + expect(requests.map(r => r.input)).toEqual([{ agent: 'opencode', model: 'openai/gpt-6.1-sol', effort: null, edits: true, cwd: '/work/sub', prompt: 'Find the bug', live_messages: true }]) expect(chunks.filter(c => c.kind === 'text').map(c => c.text).join('')).toBe('OpenCode on openai/gpt-6.1-sol, edits allowed\n\n') const input = JSON.parse(chunks.filter(c => c.kind === 'input').map(c => c.json).join('')) expect(input.message).toBe('OpenCode failed: opencode was not found on PATH. OpenCode subagents need OpenCode installed.\n\n---\nOpenCode ran no steps.') @@ -162,7 +334,7 @@ test('a failure is handed back as the report', async ($, on) => { }) test('a helper that ends without an answer is a failure too', async ($, on) => { - engine(on, ['not json'], []) + engine(on, ['not json', '{"kind":"thought"}', '{"kind":"report","text":null}'], []) await $.session.start({ cwd: '/work', surface: 'terminal', isInteractive: true }) await $.agent.spawn({ subagentType: 'Claudiu:codex-gpt-5-5', prompt: 'Find the bug' }) const chunks = await step($, 't1', 0, 'a1') diff --git a/src/claude/acp.rs b/src/claude/acp.rs index de66695..286b321 100644 --- a/src/claude/acp.rs +++ b/src/claude/acp.rs @@ -4,6 +4,7 @@ //! The mod starts this once per subagent turn and writes the task to stdin as JSON (`Request`). A mod can write a //! child's stdin only once, and ACP is a conversation in both directions, so the conversation happens here. Progress //! goes to stdout as JSON lines (`Event`), ending with the report or the reason it failed. +//! During a run, the mod can also deliver messages through a per-run JSON file polled here. //! //! Codex runs through `npx codex-acp`, which uses the user's own `codex login`; OpenCode runs as the user's own //! `opencode acp`, with their providers. The agent's stdin is a pipe from this process, so when the mod stops this @@ -12,10 +13,13 @@ use std::io::{BufRead, BufReader, Read, Write}; use std::path::{Path, PathBuf}; use std::process::{Child, ChildStdin, ChildStdout, Command, Stdio}; +use std::sync::mpsc::{RecvTimeoutError, sync_channel}; use std::thread::JoinHandle; +use std::time::{Duration, Instant}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; +use uuid::Uuid; use crate::claude::subagents::{Agent, AgentModel}; use crate::platform::{find_executable, reload_path}; @@ -29,6 +33,10 @@ const AUTH_REQUIRED: i64 = -32000; const STDERR_LINES: usize = 5; /// How long the settings page waits for the agent's models; Codex's first run downloads codex-acp through npx. const MODELS_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60); +const INBOX_POLL: Duration = Duration::from_millis(100); +const INBOX_TEXT_MAX: usize = 20_000; // UTF-16 units, matching the mod +/// JSON can use six bytes per unit, plus the envelope. +const INBOX_BYTES: u64 = INBOX_TEXT_MAX as u64 * 6 + 1_000; /// What the mod asks for. #[derive(Debug, Deserialize)] @@ -38,12 +46,19 @@ pub struct Request { pub agent: Agent, /// The agent's model; none for the agent's own default. pub model: Option, + /// The effort Claude's Agent call asked for; none for the agent's own default. OpenCode doesn't get it, since + /// its effort is an option of each provider's models rather than one setting. + #[serde(default)] + pub effort: Option, /// Whether the agent may edit files and run commands, or only read. pub edits: bool, /// The folder the agent works in. pub cwd: PathBuf, /// The task, as Claude wrote it. pub prompt: String, + /// Whether this mod understands the helper's live inbox events. + #[serde(default)] + pub live_messages: bool, } /// One line of stdout. @@ -52,6 +67,16 @@ pub struct Request { pub enum Event { /// A piece of a message the agent is writing. Text { text: String }, + /// A piece of the reasoning summary the agent chose to share. + Thought { text: String }, + /// A plan, tool status or other activity notice shown while the task runs. + Progress { text: String }, + /// New output from a tool call, separate from the agent's report. + Output { text: String }, + /// Where the mod can write messages for this run. + Inbox { id: String, path: PathBuf }, + /// The helper took ownership of this message, so Claude need not queue it. + Accepted { seq: u64 }, /// A tool call the agent started: a command, a read, an edit. Step { text: String }, /// The last message the agent wrote: the subagent's report. @@ -60,6 +85,9 @@ pub enum Event { } pub fn run() -> i32 { + if std::env::args().nth(2).as_deref() == Some("--cleanup") { + return cleanup_inbox(); + } let mut out = std::io::stdout().lock(); let mut emit = |event: Event| { if let Ok(line) = serde_json::to_string(&event) { @@ -84,22 +112,99 @@ pub fn run() -> i32 { 0 } +fn inbox_path(id: Uuid) -> PathBuf { + crate::datadir::data_dir().join("acp").join(format!("{id}.json")) +} + +fn cleanup_inbox() -> i32 { + let Some(id) = std::env::args().nth(3).and_then(|id| Uuid::parse_str(&id).ok()) else { return 1 }; + match std::fs::remove_file(inbox_path(id)) { + Ok(()) => 0, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0, + Err(_) => 1, + } +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +struct Delivery { + seq: u64, + text: String, +} + +struct Inbox { + id: Uuid, + path: PathBuf, + seen: u64, +} + +impl Inbox { + /// The next message the mod wrote, with its number. It is acknowledged (`Event::Accepted`) only once it has + /// reached the agent: until then the mod still holds it, and gives it back to Claude Code's own queue if this + /// helper ends first. + fn take(&mut self) -> Option<(u64, String)> { + // The mod writes the whole JSON value. A poll during that write can read a partial value and retries it. + if !std::fs::symlink_metadata(&self.path).ok()?.file_type().is_file() { + return None; + } + let mut body = Vec::new(); + std::fs::File::open(&self.path).ok()?.take(INBOX_BYTES + 1).read_to_end(&mut body).ok()?; + if body.len() as u64 > INBOX_BYTES { + return None; + } + let delivery: Delivery = serde_json::from_slice(&body).ok()?; + if delivery.seq != self.seen + 1 || delivery.text.trim().is_empty() || delivery.text.encode_utf16().count() > INBOX_TEXT_MAX { + return None; + } + self.seen = delivery.seq; + // The mod won't write the next message until it sees the acknowledgement. + let _ = std::fs::remove_file(&self.path); + Some((delivery.seq, delivery.text)) + } +} + +impl Drop for Inbox { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.path); + } +} + fn run_task(request: &Request, emit: &mut impl FnMut(Event)) -> Result { let env = match request.agent { Agent::Codex => { let mut env = vec![("INITIAL_AGENT_MODE", (if request.edits { "workspace-write" } else { "read-only" }).to_string())]; - if let Some(model) = &request.model { - env.push(("CODEX_CONFIG", json!({ "model": model }).to_string())); + if let Some(config) = codex_config(request.model.as_deref(), request.effort.as_deref()) { + env.push(("CODEX_CONFIG", config.to_string())); } env } Agent::OpenCode => vec![("OPENCODE_CONFIG_CONTENT", opencode_config(request.model.as_deref(), request.edits).to_string())], }; let connection = Connection::start(request.agent, &request.cwd, &env)?; - let result = converse(connection.from_agent, connection.to_agent, request, emit); + let id = Uuid::new_v4(); + let inbox = request.live_messages.then(|| Inbox { id, path: inbox_path(id), seen: 0 }); + let result = converse(connection.from_agent, connection.to_agent, request, inbox, emit); connection.process.finish(result) } +/// The config Codex gets on top of the user's own: the model and the reasoning effort, where given. Codex has no `max`, +/// so `max` becomes its highest level, `xhigh`; a level Codex doesn't know is left to the user's config. +fn codex_config(model: Option<&str>, effort: Option<&str>) -> Option { + let mut config = serde_json::Map::new(); + if let Some(model) = model { + config.insert("model".into(), json!(model)); + } + let effort = match effort { + Some("max") => Some("xhigh"), + Some(level @ ("low" | "medium" | "high" | "xhigh")) => Some(level), + _ => None, + }; + if let Some(effort) = effort { + config.insert("model_reasoning_effort".into(), json!(effort)); + } + (!config.is_empty()).then_some(Value::Object(config)) +} + /// The tools OpenCode may use read-only: reading and searching files. Everything else, the shell included, is denied, /// since OpenCode has no sandbox that would let a command run without changing anything. fn opencode_read_only() -> Value { @@ -275,68 +380,170 @@ fn list_models(agent: Agent, from_agent: impl BufRead, mut to_agent: impl Write, if models.is_empty() { Err(format!("{} listed no models", server(agent))) } else { Ok(models) } } -/// The ACP conversation for one task: start, open a session in the task's folder, send the task, and follow the -/// session's updates until the agent answers. Returns the last message the agent wrote. -fn converse(from_agent: impl BufRead, mut to_agent: impl Write, request: &Request, emit: &mut impl FnMut(Event)) -> Result { +/// Sends a task and its live messages in one ACP session, streaming updates as they arrive. +fn converse(from_agent: impl BufRead + Send + 'static, mut to_agent: impl Write, request: &Request, mut inbox: Option, emit: &mut impl FnMut(Event)) -> Result { let agent = request.agent; let name = agent.name(); - let mut lines = from_agent.lines(); + // ACP can go quiet during a long tool call. Reading stdout on its own thread lets the inbox still wake us. + let (tx, rx) = sync_channel(32); + std::thread::spawn(move || { + for line in from_agent.lines().map_while(Result::ok) { + if tx.send(line).is_err() { + break; + } + } + }); let send = |to_agent: &mut dyn Write, message: Value| -> Result<(), String> { writeln!(to_agent, "{message}").and_then(|_| to_agent.flush()).map_err(|_| exited(agent)) }; let mut messages = Messages::default(); - // What read-only refused last: codex-acp offers only "cancel" for some commands, which ends Codex's turn. - let mut refused: Option = None; - // Waits for the answer to request `id`, handling what the agent sends meanwhile. Only updates of `session` count: - // OpenCode also reports the sessions of its own subagents, whose messages are not this task's report. - let mut answer = |to_agent: &mut dyn Write, id: i64, session: Option<&str>, messages: &mut Messages, emit: &mut dyn FnMut(Event)| -> Result { - for line in lines.by_ref() { - let line = line.map_err(|_| exited(agent))?; - let Ok(msg) = serde_json::from_str::(&line) else { continue }; - if msg.get("method").is_none() && msg["id"].as_i64() == Some(id) { - return match msg.get("error") { - Some(error) => Err(error_reason(agent, error)), - None => Ok(msg["result"].clone()), - }; - } - match msg["method"].as_str() { - Some("session/update") => { - if session.is_some_and(|s| msg["params"]["sessionId"] == s) { - messages.update(&msg["params"]["update"], emit); - } - } - Some("session/request_permission") => { - let outcome = permission(&msg["params"]["options"], request.edits); - if !request.edits { - refused = Some(msg["params"]["toolCall"]["title"].as_str().unwrap_or("an action").to_string()); - } - send(to_agent, json!({ "jsonrpc": "2.0", "id": msg["id"], "result": { "outcome": outcome } }))?; + // OpenCode also reports its own subagents' sessions. Their updates aren't this task's report. + let read = |to_agent: &mut dyn Write, session: Option<&str>, messages: &mut Messages, emit: &mut dyn FnMut(Event), timeout: Option| -> Result, String> { + let line = match timeout { + Some(wait) => match rx.recv_timeout(wait) { + Ok(line) => line, + Err(RecvTimeoutError::Timeout) => return Ok(None), + Err(RecvTimeoutError::Disconnected) => return Err(exited(agent)), + }, + None => rx.recv().map_err(|_| exited(agent))?, + }; + let Ok(msg) = serde_json::from_str::(&line) else { return Ok(None) }; + match msg["method"].as_str() { + Some("session/update") => { + if session.is_some_and(|s| msg["params"]["sessionId"] == s) { + messages.update(agent, &msg["params"]["update"], emit); } - // A request this client doesn't serve: it offered no file or terminal access. - Some(_) if msg.get("id").is_some() => { - send(to_agent, json!({ "jsonrpc": "2.0", "id": msg["id"], "error": { "code": -32601, "message": "method not found" } }))?; + } + Some("session/request_permission") => { + let outcome = permission(&msg["params"]["options"], request.edits); + if !request.edits { + messages.refused = Some(msg["params"]["toolCall"]["title"].as_str().unwrap_or("an action").to_string()); } - _ => {} + send(to_agent, json!({ "jsonrpc": "2.0", "id": msg["id"], "result": { "outcome": outcome } }))?; } + // A request this client doesn't serve: it offered no file or terminal access. + Some(_) if msg.get("id").is_some() => { + send(to_agent, json!({ "jsonrpc": "2.0", "id": msg["id"], "error": { "code": -32601, "message": "method not found" } }))?; + } + None if msg["id"].is_i64() => return Ok(Some(msg)), + _ => {} } - Err(exited(agent)) + Ok(None) }; + let result = |msg: Value| match msg.get("error") { + Some(error) => Err(error_reason(agent, error)), + None => Ok(msg["result"].clone()), + }; + let answer = |to_agent: &mut dyn Write, id: i64, messages: &mut Messages, emit: &mut dyn FnMut(Event)| -> Result { + loop { + if let Some(msg) = read(to_agent, None, messages, emit, None)? + && msg["id"] == id + { + return result(msg); + } + } + }; send(&mut to_agent, initialize())?; - answer(&mut to_agent, 0, None, &mut messages, emit)?; + let initialized = answer(&mut to_agent, 0, &mut messages, emit)?; + let supports_steering = initialized["_meta"]["steering"]["supported"] == true; + let mut steer = supports_steering; + if agent == Agent::OpenCode && !supports_steering { + inbox = None; // Claude Code keeps its usual queued delivery on older OpenCode versions. + } send(&mut to_agent, new_session(&request.cwd))?; - let session = answer(&mut to_agent, 1, None, &mut messages, emit)?; + let session = answer(&mut to_agent, 1, &mut messages, emit)?; let session_id = session["sessionId"].as_str().ok_or(format!("{} opened no session", server(agent)))?.to_string(); + emit(Event::Progress { text: "Session ready. Sending the task.".into() }); + + let prompt = |id, texts: Vec| { + let blocks: Vec<_> = texts.into_iter().map(|text| json!({ "type": "text", "text": text })).collect(); + json!({ "jsonrpc": "2.0", "id": id, "method": "session/prompt", "params": { "sessionId": session_id, "prompt": blocks } }) + }; + let mut prompt_id = 2; + let mut next_id = 3; + send(&mut to_agent, prompt(prompt_id, vec![request.prompt.clone()]))?; + if let Some(inbox) = &inbox { + emit(Event::Inbox { id: inbox.id.to_string(), path: inbox.path.clone() }); + } - send(&mut to_agent, json!({ "jsonrpc": "2.0", "id": 2, "method": "session/prompt", "params": { - "sessionId": session_id, - "prompt": [{ "type": "text", "text": request.prompt }], - }}))?; - let done = answer(&mut to_agent, 2, Some(&session_id), &mut messages, emit)?; + let mut pending = std::collections::VecDeque::new(); + let mut steering = None; + let mut done = None; + let mut next_poll = Instant::now(); + let done = loop { + if let Some(inbox) = &mut inbox + && (Instant::now() >= next_poll || done.is_some()) + { + next_poll = Instant::now() + INBOX_POLL; + if let Some((seq, text)) = inbox.take() { + pending.push_back((Some(seq), text)); + } + } + + if steering.is_none() { + if let Some(reply) = done.take() { + if pending.is_empty() { + break reply; + } + // The client owns the next prompt so it can stream the reply and wait for its stop reason. + prompt_id = next_id; + next_id += 1; + let (seqs, texts): (Vec>, Vec) = pending.drain(..).unzip(); + send(&mut to_agent, prompt(prompt_id, texts))?; + for seq in seqs.into_iter().flatten() { + emit(Event::Accepted { seq }); + } + messages = Messages::default(); + steer = supports_steering; + emit(Event::Progress { text: format!("{name} is continuing with the follow-up message.") }); + } else if steer && let Some((seq, text)) = pending.pop_front() { + let mut params = json!({ + "sessionId": session_id, + "prompt": [{ "type": "text", "text": text }], + }); + if agent == Agent::Codex { + params["_meta"] = json!({ "steering": { "idleBehavior": "promptRequired" } }); + } + send(&mut to_agent, json!({ "jsonrpc": "2.0", "id": next_id, "method": "_session/steering", "params": params }))?; + steering = Some((next_id, seq, text)); + next_id += 1; + } + } + + let timeout = inbox.as_ref().map(|_| next_poll.saturating_duration_since(Instant::now())); + let Some(msg) = read(&mut to_agent, Some(&session_id), &mut messages, emit, timeout)? else { continue }; + if msg["id"] == prompt_id { + done = Some(result(msg)?); + } else if steering.as_ref().is_some_and(|(id, _, _)| msg["id"] == *id) { + let (_, seq, text) = steering.take().unwrap(); + match msg["result"]["outcome"].as_str() { + Some("injected") => { + if let Some(seq) = seq { + emit(Event::Accepted { seq }); + } + emit(Event::Progress { text: format!("{name} received the message in its current turn.") }); + } + // If a different adapter started a turn despite the opt-in, don't send the message twice. + Some("startedNewTurn") => return Err(format!("{name} started an untracked turn while steering")), + // The agent answered that its turn is idle, so the follow-up prompt will carry the message; Claude's + // message can't wait on that for the rest of the turn. After an error it waits for the follow-up. + _ => { + let answered = msg.get("error").is_none(); + if answered && let Some(seq) = seq { + emit(Event::Accepted { seq }); + } + pending.push_front((if answered { None } else { seq }, text)); + steer = false; + emit(Event::Progress { text: format!("{name} will take the message after its current turn.") }); + } + } + } + }; let stop = done["stopReason"].as_str().unwrap_or("end_turn"); match (stop, messages.last()) { ("end_turn", Some(text)) => Ok(text), ("end_turn", None) => Err(format!("{name} finished without writing a report")), - ("cancelled", _) => Err(match refused { + ("cancelled", _) => Err(match messages.refused { Some(action) => format!("{name} stopped when read-only mode refused `{action}`. Turn on Allow edits in Settings → Custom subagents to let it."), None => format!("{name}'s turn was cancelled"), }), @@ -354,8 +561,17 @@ struct Messages { current: String, current_id: Option, last: Option, - /// Tool calls named only by their tool, by id, waiting for the update that says what they act on. - unnamed: std::collections::HashMap, + tools: std::collections::HashMap, + // Codex sometimes offers only "cancel" for a refusal, which stops the turn. + refused: Option, +} + +#[derive(Default)] +struct ToolProgress { + title: String, + waiting_for_target: bool, + status: String, + output: String, } /// What a tool call acts on, from its input: the command, the pattern searched for, the address, or else the file. @@ -364,7 +580,7 @@ fn tool_target(input: &Value) -> Option<&str> { } impl Messages { - fn update(&mut self, update: &Value, emit: &mut dyn FnMut(Event)) { + fn update(&mut self, agent: Agent, update: &Value, emit: &mut dyn FnMut(Event)) { match update["sessionUpdate"].as_str() { Some("agent_message_chunk") => { let Some(text) = update["content"]["text"].as_str() else { return }; @@ -376,29 +592,94 @@ impl Messages { self.current.push_str(text); emit(Event::Text { text: text.to_string() }); } + Some("agent_thought_chunk") => { + if let Some(text) = update["content"]["text"].as_str() { + emit(Event::Thought { text: text.into() }); + } + } + Some("plan") => { + let entries: Vec<_> = update["entries"] + .as_array() + .into_iter() + .flatten() + .filter_map(|entry| Some(format!("- {} ({})", entry["content"].as_str()?, entry["status"].as_str().unwrap_or("pending").replace('_', " ")))) + .collect(); + if !entries.is_empty() { + emit(Event::Progress { text: format!("Plan\n{}", entries.join("\n")) }); + } + } Some("tool_call") => { self.close(); - let title = update["title"].as_str().unwrap_or("a tool"); - // Codex's titles say what the call acts on ("Read src/parse.rs"). OpenCode's are the bare tool name, and - // the call's first update has the input. - let bare = !title.contains(' '); - match (bare, tool_target(&update["rawInput"]), update["toolCallId"].as_str()) { - (true, Some(target), _) => emit(Event::Step { text: format!("{title} {target}") }), - (true, None, Some(id)) => { - self.unnamed.insert(id.to_string(), title.to_string()); - } - _ => emit(Event::Step { text: title.to_string() }), + self.tool_progress(agent, update, true, emit); + } + Some("tool_call_update") => self.tool_progress(agent, update, false, emit), + _ => {} + } + } + + fn tool_progress(&mut self, agent: Agent, update: &Value, started: bool, emit: &mut dyn FnMut(Event)) { + let id = update["toolCallId"].as_str(); + let mut untracked = ToolProgress::default(); + let tool = match id { + Some(id) => self.tools.entry(id.into()).or_default(), + None => &mut untracked, + }; + let target = tool_target(&update["rawInput"]); + if started { + let title = update["title"].as_str().filter(|title| !title.is_empty()).unwrap_or("a tool"); + tool.title = title.into(); + // OpenCode may start with only the tool name and supply its target in the first update. + tool.waiting_for_target = agent == Agent::OpenCode && !title.contains(' ') && target.is_none() && id.is_some(); + if !tool.waiting_for_target { + if let Some(target) = target.filter(|_| !title.contains(' ')) { + tool.title = format!("{title} {target}"); } + emit(Event::Step { text: tool.title.clone() }); } - Some("tool_call_update") => { - let Some(title) = update["toolCallId"].as_str().and_then(|id| self.unnamed.remove(id)) else { return }; - let text = match tool_target(&update["rawInput"]) { - Some(target) => format!("{title} {target}"), - None => title, - }; - emit(Event::Step { text }); + } else if tool.waiting_for_target { + tool.waiting_for_target = false; + if let Some(target) = target { + tool.title = format!("{} {target}", tool.title); } - _ => {} + emit(Event::Step { text: tool.title.clone() }); + } else if let Some(title) = update["title"].as_str().filter(|title| !title.is_empty()) { + tool.title = title.into(); + } + if let Some(status) = update["status"].as_str().filter(|status| *status != tool.status) { + tool.status = status.into(); + if !started || status == "failed" { + let title = if tool.title.is_empty() { id.unwrap_or("Tool") } else { &tool.title }; + emit(Event::Progress { text: format!("{title} · {}", status.replace('_', " ")) }); + } + } + let metadata = &update["_meta"]; + for key in ["terminal_output_delta", "mcp_output_delta"] { + if let Some(text) = metadata[key]["data"].as_str().filter(|text| !text.is_empty()) { + emit(Event::Output { text: text.into() }); + } + } + let content: Vec<_> = update["content"] + .as_array() + .into_iter() + .flatten() + .filter(|item| item["type"] == "content" && item["content"]["type"] == "text") + .filter_map(|item| item["content"]["text"].as_str()) + .collect(); + // On Codex starts, ACP content may describe the input. Result snapshots arrive in updates. + let output = if started || metadata["terminal_output_delta"].is_object() || metadata["mcp_output_delta"].is_object() { + None + } else if content.is_empty() { + let raw = &update["rawOutput"]; + raw.as_str().or_else(|| raw["formatted_output"].as_str()).or_else(|| raw["output"].as_str()).map(str::to_owned) + } else { + Some(content.join("\n")) + }; + if let Some(output) = output { + let added = output.strip_prefix(&tool.output).unwrap_or(&output); + if !added.is_empty() { + emit(Event::Output { text: added.into() }); + } + tool.output = output; } } @@ -453,7 +734,15 @@ mod tests { use super::*; fn request(agent: Agent, edits: bool) -> Request { - Request { agent, model: Some("gpt-5.5".into()), edits, cwd: PathBuf::from("/work"), prompt: "Find the bug".into() } + Request { agent, model: Some("gpt-5.5".into()), edits, cwd: PathBuf::from("/work"), prompt: "Find the bug".into(), effort: None, live_messages: false } + } + + #[test] + fn codex_gets_the_effort_claude_asked_for_and_max_becomes_xhigh() { + assert_eq!(codex_config(Some("gpt-5.5"), Some("high")), Some(json!({ "model": "gpt-5.5", "model_reasoning_effort": "high" }))); + assert_eq!(codex_config(None, Some("max")), Some(json!({ "model_reasoning_effort": "xhigh" }))); + assert_eq!(codex_config(Some("gpt-5.5"), Some("turbo")), Some(json!({ "model": "gpt-5.5" })), "an unknown level is left to the user's config"); + assert_eq!(codex_config(None, None), None); } fn update(update: Value) -> Value { @@ -474,7 +763,7 @@ mod tests { let script: String = agent_says.iter().map(|m| format!("{m}\n")).collect(); let mut sent = Vec::new(); let mut events = vec![]; - let result = converse(script.as_bytes(), &mut sent, &request(agent, edits), &mut |e| events.push(e)); + let result = converse(std::io::Cursor::new(script), &mut sent, &request(agent, edits), None, &mut |e| events.push(e)); let sent = String::from_utf8(sent).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect(); (result, sent, events) } @@ -487,6 +776,175 @@ mod tests { vec![reply(0, json!({ "protocolVersion": 1 })), reply(1, json!({ "sessionId": "s1" }))] } + fn test_inbox(dir: &Path) -> Inbox { + Inbox { id: Uuid::new_v4(), path: dir.join("inbox.json"), seen: 0 } + } + + #[test] + fn the_inbox_rejects_partial_oversized_out_of_order_and_replayed_deliveries() { + let dir = tempfile::tempdir().unwrap(); + let mut inbox = test_inbox(dir.path()); + for body in [ + r#"{"seq":1,"text":"unfinished"#.to_string(), + json!({ "seq": 1, "text": " " }).to_string(), + json!({ "seq": 1, "text": 15 }).to_string(), + json!({ "seq": 2, "text": "skipped one" }).to_string(), + json!({ "seq": 1, "text": "a".repeat(INBOX_TEXT_MAX + 1) }).to_string(), + " ".repeat(INBOX_BYTES as usize + 1), + ] { + std::fs::write(&inbox.path, body).unwrap(); + assert_eq!(inbox.take(), None); + } + let message = json!({ "seq": 1, "text": "Check the tests too" }).to_string(); + std::fs::write(&inbox.path, &message).unwrap(); + assert_eq!(inbox.take(), Some((1, "Check the tests too".to_string()))); + assert!(!inbox.path.exists()); + std::fs::write(&inbox.path, message).unwrap(); + assert_eq!(inbox.take(), None); + let path = inbox.path.clone(); + drop(inbox); + assert!(!path.exists()); + } + + /// Wait for a steer without sending any ACP output after the original prompt. + fn steer_a_quiet_turn(agent: Agent, parks_message: bool) { + let dir = tempfile::tempdir().unwrap(); + let inbox = test_inbox(dir.path()); + let path = inbox.path.clone(); + let (from_agent, mut replies) = std::io::pipe().unwrap(); + let (commands, to_agent) = std::io::pipe().unwrap(); + let (sent, received) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + for line in BufReader::new(commands).lines().map_while(Result::ok) { + if sent.send(serde_json::from_str::(&line).unwrap()).is_err() { + break; + } + } + }); + let task = std::thread::spawn(move || { + let mut events = Vec::new(); + let report = converse(BufReader::new(from_agent), to_agent, &request(agent, false), Some(inbox), &mut |event| events.push(event)); + (report, events) + }); + let next = || received.recv_timeout(Duration::from_secs(5)).unwrap(); + assert_eq!(next()["method"], "initialize"); + writeln!(replies, "{}", reply(0, json!({ "protocolVersion": 1, "_meta": { "steering": { "supported": true } } }))).unwrap(); + assert_eq!(next()["method"], "session/new"); + writeln!(replies, "{}", opening()[1]).unwrap(); + assert_eq!(next()["method"], "session/prompt"); + std::fs::write(&path, json!({ "seq": 1, "text": "Check the tests too" }).to_string()).unwrap(); + let steer = next(); + assert_eq!(steer["method"], "_session/steering"); + assert_eq!(steer["params"]["sessionId"], "s1"); + assert_eq!(steer["params"]["prompt"], json!([{ "type": "text", "text": "Check the tests too" }])); + let idle_behavior = &steer["params"]["_meta"]["steering"]["idleBehavior"]; + if agent == Agent::Codex { + assert_eq!(idle_behavior, "promptRequired"); + } else { + assert!(idle_behavior.is_null()); + } + let steer_id = steer["id"].as_i64().unwrap(); + let finished = json!({ "stopReason": "end_turn" }); + let final_id = if parks_message { + // The original prompt may finish before the adapter replies to the steer. + writeln!(replies, "{}", chunk("m1", "Original answer.")).unwrap(); + writeln!(replies, "{}", reply(2, finished.clone())).unwrap(); + writeln!(replies, "{}", reply(steer_id, json!({ "outcome": "promptRequired", "reason": "noRunningTurn" }))).unwrap(); + let follow_up = next(); + assert_eq!(follow_up["method"], "session/prompt"); + assert_eq!(follow_up["params"]["sessionId"], "s1"); + assert_eq!(follow_up["params"]["prompt"], steer["params"]["prompt"]); + follow_up["id"].as_i64().unwrap() + } else { + writeln!(replies, "{}", reply(steer_id, json!({ "outcome": "injected" }))).unwrap(); + 2 + }; + writeln!(replies, "{}", chunk("m2", "Checked the tests too.")).unwrap(); + writeln!(replies, "{}", reply(final_id, finished)).unwrap(); + drop(replies); + let (report, events) = task.join().unwrap(); + assert_eq!(report.as_deref(), Ok("Checked the tests too.")); + assert!(events.contains(&Event::Accepted { seq: 1 })); + assert!(events.contains(&Event::Text { text: "Checked the tests too.".into() })); + assert!(!path.exists()); + } + + /// The mod gives a message back to Claude Code's queue unless it is acknowledged, so one that never reached the + /// agent must not be: the agent exits before answering the steer, or refuses it with an error and then exits. + fn exit_before_taking_a_message(refuses_first: bool) { + let dir = tempfile::tempdir().unwrap(); + let inbox = test_inbox(dir.path()); + let path = inbox.path.clone(); + let (from_agent, mut replies) = std::io::pipe().unwrap(); + let (commands, to_agent) = std::io::pipe().unwrap(); + let (sent, received) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + for line in BufReader::new(commands).lines().map_while(Result::ok) { + if sent.send(serde_json::from_str::(&line).unwrap()).is_err() { + break; + } + } + }); + let task = std::thread::spawn(move || { + let mut events = Vec::new(); + let report = converse(BufReader::new(from_agent), to_agent, &request(Agent::Codex, false), Some(inbox), &mut |event| events.push(event)); + (report, events) + }); + let next = || received.recv_timeout(Duration::from_secs(5)).unwrap(); + assert_eq!(next()["method"], "initialize"); + writeln!(replies, "{}", reply(0, json!({ "protocolVersion": 1, "_meta": { "steering": { "supported": true } } }))).unwrap(); + assert_eq!(next()["method"], "session/new"); + writeln!(replies, "{}", opening()[1]).unwrap(); + assert_eq!(next()["method"], "session/prompt"); + std::fs::write(&path, json!({ "seq": 1, "text": "Check the tests too" }).to_string()).unwrap(); + let steer = next(); + assert_eq!(steer["method"], "_session/steering"); + if refuses_first { + writeln!(replies, "{}", json!({ "jsonrpc": "2.0", "id": steer["id"], "error": { "code": -32603, "message": "busy" } })).unwrap(); + } + drop(replies); + let (report, events) = task.join().unwrap(); + assert!(report.is_err()); + assert!(!events.iter().any(|e| matches!(e, Event::Accepted { .. })), "{events:?}"); + } + + #[test] + fn a_message_is_not_acknowledged_when_the_agent_exits_before_taking_it() { + exit_before_taking_a_message(false); + } + + #[test] + fn a_message_is_not_acknowledged_when_the_agent_refuses_the_steer_and_exits() { + exit_before_taking_a_message(true); + } + + #[test] + fn codex_can_be_steered_while_acp_is_quiet() { + steer_a_quiet_turn(Agent::Codex, false); + } + + #[test] + fn codex_follows_up_in_the_same_session_when_steering_finds_an_idle_turn() { + steer_a_quiet_turn(Agent::Codex, true); + } + + #[test] + fn opencode_can_be_steered_when_it_advertises_support() { + steer_a_quiet_turn(Agent::OpenCode, false); + } + + #[test] + fn opencode_without_steering_leaves_delivery_to_claude() { + let dir = tempfile::tempdir().unwrap(); + let mut says = opening(); + says.extend([chunk("m1", "Original answer."), reply(2, json!({ "stopReason": "end_turn" }))]); + let script: String = says.iter().map(|m| format!("{m}\n")).collect(); + let mut events = Vec::new(); + let report = converse(std::io::Cursor::new(script), std::io::sink(), &request(Agent::OpenCode, false), Some(test_inbox(dir.path())), &mut |event| events.push(event)); + assert_eq!(report.as_deref(), Ok("Original answer.")); + assert!(!events.iter().any(|event| matches!(event, Event::Inbox { .. }))); + } + #[test] fn the_report_is_the_last_message_and_every_piece_streams() { let mut says = opening(); @@ -502,6 +960,7 @@ mod tests { assert_eq!( events, vec![ + Event::Progress { text: "Session ready. Sending the task.".into() }, Event::Text { text: "Looking at ".into() }, Event::Text { text: "the parser.".into() }, Event::Step { text: "Read src/parse.rs".into() }, @@ -515,6 +974,39 @@ mod tests { assert_eq!(sent[0]["params"]["clientCapabilities"]["terminal"], false); } + #[test] + fn thoughts_plans_and_tool_updates_stream_without_replacing_the_report() { + let mut says = opening(); + says.extend([ + update(json!({ "sessionUpdate": "agent_thought_chunk", "content": { "type": "text", "text": "Check the parser." } })), + update(json!({ "sessionUpdate": "plan", "entries": [{ "content": "Run tests", "status": "in_progress" }] })), + update(json!({ "sessionUpdate": "tool_call", "toolCallId": "c1", "title": "Run tests", "status": "in_progress" })), + update(json!({ "sessionUpdate": "tool_call_update", "toolCallId": "c1", "_meta": { "terminal_output_delta": { "data": "running\n" } } })), + update(json!({ "sessionUpdate": "tool_call_update", "toolCallId": "c1", "rawOutput": { "formatted_output": "started\n" } })), + update(json!({ "sessionUpdate": "tool_call_update", "toolCallId": "c1", "status": "failed", "content": [ + { "type": "content", "content": { "type": "text", "text": "started\nfailed\n" } }, + ] })), + update(json!({ "sessionUpdate": "tool_call_update", "toolCallId": "c1", "status": "failed", "rawOutput": "started\nfailed\n" })), + chunk("m1", "The parser test failed."), + update(json!({ "sessionUpdate": "agent_thought_chunk", "content": { "type": "text", "text": "Thought after the report." } })), + reply(2, json!({ "stopReason": "end_turn" })), + ]); + let (report, _, events) = talk(&says, false); + assert_eq!(report, Ok("The parser test failed.".into())); + assert_eq!(events, [ + Event::Progress { text: "Session ready. Sending the task.".into() }, + Event::Thought { text: "Check the parser.".into() }, + Event::Progress { text: "Plan\n- Run tests (in progress)".into() }, + Event::Step { text: "Run tests".into() }, + Event::Output { text: "running\n".into() }, + Event::Output { text: "started\n".into() }, + Event::Progress { text: "Run tests · failed".into() }, + Event::Output { text: "failed\n".into() }, + Event::Text { text: "The parser test failed.".into() }, + Event::Thought { text: "Thought after the report.".into() }, + ]); + } + /// OpenCode names only the tool when the call starts and sends what it acts on in the call's first update. #[test] fn a_step_named_only_by_its_tool_waits_for_what_it_acts_on() { @@ -536,7 +1028,7 @@ mod tests { chunk("m1", "Done."), reply(2, json!({ "stopReason": "end_turn" })), ]); - let steps: Vec = talk(&says, false).2.into_iter().filter_map(|e| if let Event::Step { text } = e { Some(text) } else { None }).collect(); + let steps: Vec = talk_to(Agent::OpenCode, &says, false).2.into_iter().filter_map(|e| if let Event::Step { text } = e { Some(text) } else { None }).collect(); assert_eq!(steps, ["grep fn main", "read note.json", "shell echo hi", "todowrite"]); } @@ -563,7 +1055,7 @@ mod tests { ]); let (result, _, events) = talk_to(Agent::OpenCode, &says, true); assert_eq!(result, Ok("Asked a helper.".into())); - assert_eq!(events, vec![Event::Text { text: "Asked a helper.".into() }]); + assert_eq!(events, vec![Event::Progress { text: "Session ready. Sending the task.".into() }, Event::Text { text: "Asked a helper.".into() }]); } fn asks_permission() -> Vec {