picocode-core 0.9.210 → 0.9.212

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,43 @@
1
+ # Claude Code engine
2
+
3
+ Runs a pico session's turns through Claude Code, on the user's own Claude subscription, instead of through a model API.
4
+
5
+ ## Why
6
+
7
+ A Claude subscription can't be used as an API key. The supported way to use it is the `claude` command. This engine drives that command headless, so a pico session (and any kagent agent) can use Claude models, with Claude Code's own tools, at subscription cost. pico still owns the session: its log, transcript, peers, questions and host tools work the same as with any other model.
8
+
9
+ ## How
10
+
11
+ `engines.js` is the seam. When a session's model has the provider `claude-code`, the controller calls this engine's `run` and `compact` in place of `runTurn` and `compactHistory`. The engine takes the same arguments, emits the same stream events and returns provider-shaped messages, so nothing downstream knows the difference.
12
+
13
+ | File | Role |
14
+ | --- | --- |
15
+ | `engine.js` | One long-lived `claude` process per pico session; plays a turn, returns pico history |
16
+ | `cli.js` | Spawns `claude -p` with stream-json in and out; the control requests (initialize, interrupt) |
17
+ | `translate.js` | Pure mapping: Claude events and tools to pico's, pico history to Claude input |
18
+ | `bridge.js`, `mcp-server.js` | pico's own tools (ask_user, peers, wake-ups, host tools such as kagent's terminals and browser) offered to Claude Code as the MCP server `pico` |
19
+ | `models.js` | The model catalog (`claude-code/fable`, `opus`, `sonnet`, `haiku`) and the sign-in check |
20
+
21
+ **History.** pico's log is the source of truth, and Claude Code's context is a cache of it. After each turn the engine records a fingerprint of the history Claude Code holds, and saves it with the session as an `engine_state` event, together with the Claude session id. On the next turn:
22
+
23
+ - if pico's history is that history plus new messages, only the new messages are sent;
24
+ - if pico's history changed underneath it (rewind, steer, clear, compaction, or a conversation started with another model), a fresh Claude session starts with the earlier conversation as a transcript;
25
+ - after a restart, the saved Claude session is resumed with `--resume`, and a forked pico session forks it with `--fork-session`.
26
+
27
+ **Tools.** Claude Code's tools are recorded as pico's equivalents (`Bash` as `bash`, `Edit` as `edit`, with diffs), so the transcript renders them and rewind can undo Claude's edits. pico tools that Claude Code has its own version of (read, edit, bash, agents and so on) are not offered over the bridge.
28
+
29
+ ## Rules
30
+
31
+ - **Subscription only.** `ANTHROPIC_API_KEY` and `ANTHROPIC_AUTH_TOKEN` are removed from the child's environment. Either one would make Claude Code bill the API, silently. The models only appear when `claude auth status` reports a claude.ai sign-in.
32
+ - **No permission prompts.** Claude Code runs with `--dangerously-skip-permissions`, as pico does. Questions go through pico's `ask_user`, so `AskUserQuestion` is disallowed, and so are `EnterWorktree` and `ExitWorktree` because the host owns worktrees.
33
+ - **Compaction.** Claude Code compacts its own context, so pico doesn't auto-compact these sessions. A manual compact summarizes with the same model and restarts the Claude session from that summary.
34
+ - **Subagents.** Claude's subagents show in pico's activity list, with their tool calls and reports, through the agent manager's `track`. Background tasks are turned off (`CLAUDE_CODE_DISABLE_BACKGROUND_TASKS`): work that outlives a turn would be invisible to pico, and the idle stop would kill it. Subagents still run in parallel, and the turn waits for them.
35
+
36
+ ## Not covered
37
+
38
+ - pico's own subagents and deliberation. Claude Code has its own.
39
+ - The subscription's rate-limit status.
40
+
41
+ ## Checking it
42
+
43
+ `test/claude-code.test.js` runs the engine against a scripted Claude Code; no model is called. `node scripts/claude-code-smoke.js [model]` runs real turns through the installed `claude` (haiku by default): an edit, bash, ask_user, an interrupt, parallel subagents, and a resume after restart. Run it after upgrading Claude Code, since the stream-json control protocol is the Agent SDK's and isn't separately documented.
@@ -0,0 +1,104 @@
1
+ // pico's own tools (peers, questions, wake-ups, and whatever the host adds,
2
+ // like kagent's terminals and browser) offered to Claude Code over MCP.
3
+ // Claude Code starts mcp-server.js as a stdio MCP server; that process
4
+ // relays each list and call over a private Unix socket back to this one,
5
+ // where the tool runs with the live turn's toolset and recorder. The tool
6
+ // set changes turn to turn, so the bridge holds whichever turn is current.
7
+
8
+ import { createServer } from 'node:net'
9
+ import { mkdtemp, rm, chmod } from 'node:fs/promises'
10
+ import { tmpdir } from 'node:os'
11
+ import { join } from 'node:path'
12
+ import { randomBytes } from 'node:crypto'
13
+ import { fileURLToPath } from 'node:url'
14
+ import { BRIDGE_SERVER, inputSchema } from './translate.js'
15
+
16
+ const SHIM = fileURLToPath(new URL('./mcp-server.js', import.meta.url))
17
+
18
+ export async function createBridge() {
19
+ const dir = await mkdtemp(join(tmpdir(), 'pico-claude-'))
20
+ await chmod(dir, 0o700)
21
+ const path = join(dir, 'bridge.sock')
22
+ const token = randomBytes(24).toString('hex')
23
+ const sockets = new Set()
24
+ let tools = []
25
+ let names = ''
26
+ let claim = () => null
27
+ // calls run one at a time: pico's recorder holds one pending call
28
+ let queue = Promise.resolve()
29
+
30
+ const server = createServer((socket) => {
31
+ let buffer = ''
32
+ let authed = false
33
+ socket.setEncoding('utf8')
34
+ socket.on('error', () => {})
35
+ socket.on('close', () => sockets.delete(socket))
36
+ socket.on('data', (chunk) => {
37
+ buffer += chunk
38
+ let index
39
+ while ((index = buffer.indexOf('\n')) >= 0) {
40
+ const line = buffer.slice(0, index)
41
+ buffer = buffer.slice(index + 1)
42
+ let message
43
+ try { message = JSON.parse(line) } catch { socket.destroy(); return }
44
+ if (!authed) {
45
+ if (message.token !== token) { socket.destroy(); return }
46
+ authed = true
47
+ sockets.add(socket)
48
+ continue
49
+ }
50
+ handle(message).then((reply) => socket.write(`${JSON.stringify({ id: message.id, ...reply })}\n`))
51
+ }
52
+ })
53
+ })
54
+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(path, resolve) })
55
+
56
+ function list() {
57
+ // always loaded, not deferred behind Claude Code's tool search: they
58
+ // are few, and a deferred tool fails its first call
59
+ return tools.map((tool) => ({ name: tool.name, description: tool.description, inputSchema: inputSchema(tool.schema), _meta: { 'anthropic/alwaysLoad': true } }))
60
+ }
61
+
62
+ async function handle(message) {
63
+ if (message.op === 'list') return { tools: list() }
64
+ if (message.op !== 'call') return { error: `unknown operation ${message.op}` }
65
+ const tool = tools.find((t) => t.name === message.name)
66
+ if (!tool) return { error: `no tool named ${message.name}` }
67
+ const run = queue.then(async () => {
68
+ // the recorder files this call under Claude's id for it, so its row
69
+ // and result land on the tool call the transcript already shows
70
+ await claim(message.name, message.args)
71
+ try {
72
+ const result = await tool.execute(message.args ?? {})
73
+ return { result: typeof result === 'string' ? result : JSON.stringify(result ?? null) }
74
+ } catch (error) {
75
+ return { error: String(error.message || error) }
76
+ }
77
+ })
78
+ queue = run.catch(() => {})
79
+ return run
80
+ }
81
+
82
+ return {
83
+ // the MCP server entry Claude Code is started with
84
+ mcpConfig() {
85
+ return { mcpServers: { [BRIDGE_SERVER]: { type: 'stdio', command: process.execPath, args: [SHIM], env: { PICO_BRIDGE_SOCKET: path, PICO_BRIDGE_TOKEN: token } } } }
86
+ },
87
+ // the tools a turn offers; `onClaim` ties an incoming call to the
88
+ // tool_use Claude announced for it
89
+ setTurn(next, onClaim) {
90
+ tools = next
91
+ claim = onClaim
92
+ const now = tools.map((t) => t.name).sort().join()
93
+ if (now !== names) {
94
+ names = now
95
+ for (const socket of sockets) socket.write(`${JSON.stringify({ event: 'changed' })}\n`)
96
+ }
97
+ },
98
+ async close() {
99
+ for (const socket of sockets) socket.destroy()
100
+ await new Promise((resolve) => server.close(resolve))
101
+ await rm(dir, { recursive: true, force: true })
102
+ },
103
+ }
104
+ }
@@ -0,0 +1,127 @@
1
+ // One headless Claude Code process speaking stream-json on stdin and
2
+ // stdout: user messages go in, every event comes out as a line of JSON.
3
+ // Control requests (initialize, interrupt) use the same protocol the
4
+ // Claude Agent SDK uses to drive the CLI.
5
+
6
+ import { spawn } from 'node:child_process'
7
+ import { createInterface } from 'node:readline'
8
+ import { randomUUID } from 'node:crypto'
9
+
10
+ // these make Claude Code bill an API key instead of the claude.ai login,
11
+ // silently; a Claude Code session in pico always runs on the subscription
12
+ const API_AUTH_VARIABLES = ['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN']
13
+
14
+ export function claudeEnv(env = process.env) {
15
+ const out = { ...env }
16
+ for (const key of API_AUTH_VARIABLES) delete out[key]
17
+ // set inside a Claude Code session; the child is its own session
18
+ delete out.CLAUDECODE
19
+ return out
20
+ }
21
+
22
+ // tools Claude Code would otherwise use in place of pico's: questions go
23
+ // through ask_user so they reach pico's question card, and worktrees are
24
+ // the host's to manage
25
+ const DISALLOWED = ['AskUserQuestion', 'EnterWorktree', 'ExitWorktree']
26
+
27
+ // `oneShot` is a bare run with no tools and nothing saved, for work like
28
+ // summarizing that is not part of the conversation
29
+ export function claudeArgs({ model, effort, resume, fork, mcpConfig, appendSystemPrompt, oneShot = false }) {
30
+ const args = [
31
+ '-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', '--include-partial-messages',
32
+ // pico and its hosts run without permission prompts, as the user runs
33
+ // Claude Code itself
34
+ '--dangerously-skip-permissions',
35
+ '--disallowedTools', DISALLOWED.join(','),
36
+ // a subagent's text and thinking, not only its tool calls, so pico can
37
+ // show what it is doing
38
+ '--forward-subagent-text',
39
+ ]
40
+ if (oneShot) args.push('--tools', '', '--no-session-persistence', '--strict-mcp-config')
41
+ if (model) args.push('--model', model)
42
+ if (effort) args.push('--effort', effort)
43
+ if (resume) args.push('--resume', resume)
44
+ if (resume && fork) args.push('--fork-session')
45
+ if (mcpConfig) args.push('--mcp-config', JSON.stringify(mcpConfig))
46
+ if (appendSystemPrompt) args.push('--append-system-prompt', appendSystemPrompt)
47
+ return args
48
+ }
49
+
50
+ export function spawnClaude({ command = 'claude', cwd, env, onMessage, onExit, ...options }) {
51
+ // background tasks keep running after a turn ends, where pico cannot see
52
+ // them and the idle stop would kill them; in the foreground, subagents
53
+ // still run in parallel, and the turn waits for them
54
+ const childEnv = { ...claudeEnv({ ...process.env, ...env }), CLAUDE_CODE_DISABLE_BACKGROUND_TASKS: '1' }
55
+ const child = spawn(command, claudeArgs(options), { cwd, env: childEnv, stdio: ['pipe', 'pipe', 'pipe'] })
56
+ const pending = new Map()
57
+ let stderr = ''
58
+ let exited = false
59
+
60
+ const write = (message) => {
61
+ if (exited || !child.stdin.writable) return false
62
+ child.stdin.write(`${JSON.stringify(message)}\n`)
63
+ return true
64
+ }
65
+
66
+ createInterface({ input: child.stdout }).on('line', (line) => {
67
+ let message
68
+ try { message = JSON.parse(line) } catch { return }
69
+ if (message.type === 'control_response') {
70
+ const id = message.response?.request_id
71
+ const waiter = pending.get(id)
72
+ pending.delete(id)
73
+ if (message.response.subtype === 'error') waiter?.reject(new Error(message.response.error || 'control request failed'))
74
+ else waiter?.resolve(message.response.response ?? null)
75
+ return
76
+ }
77
+ if (message.type === 'control_request') {
78
+ // permissions are skipped, so a tool request should never come; if
79
+ // one does, it is allowed rather than left to hang the turn
80
+ const request = message.request ?? {}
81
+ const response = request.subtype === 'can_use_tool'
82
+ ? { subtype: 'success', request_id: message.request_id, response: { behavior: 'allow', updatedInput: request.input } }
83
+ : { subtype: 'error', request_id: message.request_id, error: `pico does not handle ${request.subtype}` }
84
+ write({ type: 'control_response', response })
85
+ return
86
+ }
87
+ onMessage(message)
88
+ })
89
+ child.stderr.setEncoding('utf8')
90
+ child.stderr.on('data', (chunk) => { stderr = (stderr + chunk).slice(-4000) })
91
+ child.stdin.on('error', () => {})
92
+
93
+ const finish = (error) => {
94
+ if (exited) return
95
+ exited = true
96
+ for (const waiter of pending.values()) waiter.reject(new Error('Claude Code exited'))
97
+ pending.clear()
98
+ onExit?.({ error, stderr: stderr.trim() })
99
+ }
100
+ child.on('error', (error) => finish(error.code === 'ENOENT' ? new Error(`${command} not found; install Claude Code and sign in with claude auth login`) : error))
101
+ child.on('exit', (code, signal) => finish(code === 0 || signal === 'SIGTERM' ? null : new Error(`Claude Code exited with ${signal ?? `code ${code}`}`)))
102
+
103
+ function request(subtype, payload = {}) {
104
+ const id = randomUUID()
105
+ return new Promise((resolve, reject) => {
106
+ pending.set(id, { resolve, reject })
107
+ if (!write({ type: 'control_request', request_id: id, request: { subtype, ...payload } })) {
108
+ pending.delete(id)
109
+ reject(new Error('Claude Code is not running'))
110
+ }
111
+ })
112
+ }
113
+
114
+ request('initialize').catch(() => {})
115
+
116
+ return {
117
+ get alive() { return !exited },
118
+ get stderr() { return stderr.trim() },
119
+ send: (content) => write({ type: 'user', message: { role: 'user', content } }),
120
+ interrupt: () => request('interrupt'),
121
+ close() {
122
+ if (exited) return
123
+ child.stdin.end()
124
+ setTimeout(() => { if (!exited) child.kill('SIGTERM') }, 3000).unref()
125
+ },
126
+ }
127
+ }
@@ -0,0 +1,387 @@
1
+ // The Claude Code turn engine: pico's controller hands it a turn exactly
2
+ // as it would hand pico's own runTurn one, and it plays the turn through a
3
+ // long-lived headless `claude` process instead of calling a model API.
4
+ //
5
+ // pico's session log stays the source of truth. Claude Code keeps its own
6
+ // context, which this engine treats as a cache of pico's history: when
7
+ // the history the controller passes in is what Claude Code last saw, only
8
+ // the new messages are sent; when it is not (a rewind, a steer, a clear, a
9
+ // compaction, or a conversation begun with another model), a fresh Claude
10
+ // Code session starts with the earlier conversation as a transcript. Which
11
+ // Claude session holds which history is returned as `engineState`, which
12
+ // the controller saves with the session so a restart resumes it.
13
+
14
+ import { existsSync, readFileSync } from 'node:fs'
15
+ import { basename } from 'node:path'
16
+ import { hydrateImages } from '../agent.js'
17
+ import { spawnClaude } from './cli.js'
18
+ import { createBridge } from './bridge.js'
19
+ import { claudeCommand, cliModel, CLAUDE_CODE_PROVIDER } from './models.js'
20
+ import { addUsage, COVERED_TOOLS, emptyUsage, fingerprint, picoTool, seedText, splitTurn, toolEntry, transcriptText, toolResultText, usageOf, userBlocks } from './translate.js'
21
+
22
+ const IDLE_MS = 10 * 60 * 1000
23
+ // Claude Code's tools that run a subagent
24
+ const SUBAGENT_TOOLS = new Set(['Task', 'Agent'])
25
+ // how long an interrupted turn may take to wind down before the process
26
+ // is stopped instead
27
+ const INTERRUPT_GRACE_MS = 10000
28
+
29
+ const HOST_NOTE = `You are running inside pico, an agent runtime, possibly within kagent, a desktop workspace where several agent sessions work side by side. Besides your own tools, the host's tools are available under mcp__pico__: ask_user asks the user questions (use it instead of AskUserQuestion), peer_list and peer_send message other agent sessions, schedule_wakeup schedules a note to your future self, and the host may add more, such as terminals and a browser. Messages that begin with [system notification] or [peer input ...] come from the host or from other agents, not from the user.`
30
+
31
+ function systemPrompt(contextFiles = []) {
32
+ // Claude Code reads CLAUDE.md files itself; any other instructions pico
33
+ // would give its own models (AGENTS.md) are passed along
34
+ const files = contextFiles.filter((file) => basename(file.path) !== 'CLAUDE.md' && file.content?.trim())
35
+ if (!files.length) return HOST_NOTE
36
+ return `${HOST_NOTE}\n\nProject instructions:\n\n${files.map((file) => `<file path="${file.path}">\n${file.content.trim()}\n</file>`).join('\n\n')}`
37
+ }
38
+
39
+ // the trailing user messages of `history` that Claude Code has not seen,
40
+ // given the fingerprint of what it has: null when the history diverged
41
+ function unseen(history, synced) {
42
+ if (!synced) return null
43
+ for (let at = history.length; at >= 0; at--) {
44
+ if (at < history.length && history[at].role !== 'user') break
45
+ if (fingerprint(history.slice(0, at)) === synced) return history.slice(at)
46
+ }
47
+ return null
48
+ }
49
+
50
+ export function createClaudeCodeEngine({ command = claudeCommand(), idleMs = IDLE_MS, spawn = spawnClaude, bridge = createBridge } = {}) {
51
+ // per pico session: its process, bridge, and which Claude session holds
52
+ // which history
53
+ const sessions = new Map()
54
+
55
+ function stop(entry) {
56
+ clearTimeout(entry.idle)
57
+ entry.proc?.close()
58
+ entry.proc = null
59
+ entry.bridge?.close().catch(() => {})
60
+ entry.bridge = null
61
+ }
62
+
63
+ async function start(entry, { cwd, env, model, effort, resume, fork, contextFiles }) {
64
+ entry.bridge = await bridge()
65
+ entry.model = model
66
+ entry.effort = effort
67
+ entry.proc = spawn({
68
+ command,
69
+ cwd,
70
+ env,
71
+ model,
72
+ effort,
73
+ resume,
74
+ fork,
75
+ mcpConfig: entry.bridge.mcpConfig(),
76
+ appendSystemPrompt: systemPrompt(contextFiles),
77
+ onMessage: (message) => entry.onMessage?.(message),
78
+ onExit: (exit) => {
79
+ entry.proc = null
80
+ entry.lastExit = exit
81
+ entry.onExit?.(exit)
82
+ },
83
+ })
84
+ }
85
+
86
+ async function run({ history, tools, recorder, modelName, effort, signal, onStream = () => {}, beforeRequest, host = {} }) {
87
+ const key = host.sessionId ?? 'ephemeral'
88
+ const entry = sessions.get(key) ?? { claudeSessionId: null, owner: key, synced: null }
89
+ sessions.set(key, entry)
90
+ clearTimeout(entry.idle)
91
+ const model = cliModel(modelName)
92
+ const level = effort && effort !== 'auto' ? effort : null
93
+
94
+ // what Claude Code already holds: this process's session, or the one
95
+ // the controller saved, as long as the history has not moved under it
96
+ const known = entry.claudeSessionId ? entry : host.engineState?.claudeSessionId ? host.engineState : null
97
+ const fresh = known ? unseen(history, known.synced) : null
98
+ if (entry.proc && (!fresh || entry.model !== model || entry.effort !== level)) stop(entry)
99
+ let seed = null
100
+ let input = fresh
101
+ if (!entry.proc) {
102
+ if (!fresh) {
103
+ const turn = splitTurn(history)
104
+ input = turn.input
105
+ if (turn.prior.length) seed = seedText(turn.prior)
106
+ }
107
+ }
108
+
109
+ const content = []
110
+ if (seed) content.push({ type: 'text', text: seed })
111
+ for (const message of await hydrateImages(input)) content.push(...userBlocks(message))
112
+ if (!content.length) content.push({ type: 'text', text: '[system notification] continue.' })
113
+
114
+ if (!entry.proc) {
115
+ entry.lastExit = null
116
+ try {
117
+ await start(entry, { cwd: host.cwd, env: host.env, model, effort: level, resume: fresh ? known.claudeSessionId : null, fork: !!fresh && known.owner !== key, contextFiles: host.contextFiles })
118
+ } catch (error) {
119
+ stop(entry)
120
+ return { messages: [], usage: null, lastPromptTokens: 0, interrupted: true, stalled: false, error: String(error.message || error) }
121
+ }
122
+ if (!fresh) entry.claudeSessionId = null
123
+ entry.owner = key
124
+ }
125
+
126
+ const collected = []
127
+ const uses = new Map()
128
+ const unclaimed = []
129
+ const responses = new Map()
130
+ let assistant = null
131
+ let usage = emptyUsage()
132
+ let lastPrompt = 0
133
+ let interrupted = false
134
+ let error = null
135
+ let graceTimer = null
136
+
137
+ const flushAssistant = () => {
138
+ if (!assistant) return
139
+ if (assistant.text || assistant.calls.length) collected.push({ role: 'assistant', content: assistant.text, ...(assistant.calls.length ? { tool_calls: assistant.calls } : {}) })
140
+ assistant = null
141
+ }
142
+
143
+ // a response's usage arrives in parts: input at its start, output
144
+ // growing until its end
145
+ const raws = new Map()
146
+ let streaming = null
147
+ const countUsage = (id, raw) => {
148
+ if (!id || !raw) return
149
+ raws.set(id, { ...raws.get(id), ...raw })
150
+ responses.set(id, usageOf(raws.get(id)))
151
+ usage = [...responses.values()].reduce(addUsage, emptyUsage())
152
+ lastPrompt = responses.get(id).promptTokens
153
+ onStream({ type: 'usage', usage })
154
+ }
155
+
156
+ // Claude Code's messages are handled one at a time, in order
157
+ let chain = Promise.resolve()
158
+
159
+ // Claude's subagents, by the id of the Task call that started each,
160
+ // shown in pico's activity list as they work. A subagent's own traffic
161
+ // carries that id as its parent; it may start subagents of its own
162
+ const subagents = new Map()
163
+ const startSubagent = (block) => {
164
+ if (!host.subagents || !SUBAGENT_TOOLS.has(block.name)) return
165
+ // a subagent runs on the session's model unless its call names another
166
+ const handle = host.subagents.start({ description: block.input?.description, prompt: block.input?.prompt ?? '', model: `${CLAUDE_CODE_PROVIDER}/${block.input?.model ?? model}` })
167
+ subagents.set(block.id, { handle })
168
+ }
169
+ // `extra` is the structured result, whose report is free of the frame
170
+ // Claude Code wraps it in for the model
171
+ const finishSubagent = (block, extra) => {
172
+ const sub = subagents.get(block.tool_use_id)
173
+ if (!sub) return
174
+ subagents.delete(block.tool_use_id)
175
+ const text = Array.isArray(extra?.content) ? toolResultText(extra.content) : toolResultText(block.content)
176
+ sub.handle.finish(block.is_error ? { error: text || 'failed', interrupted } : { result: text })
177
+ }
178
+ const onSubagent = (message) => {
179
+ const sub = subagents.get(message.parent_tool_use_id)
180
+ if (!sub) return
181
+ if (message.type === 'assistant') {
182
+ for (const block of message.message?.content ?? []) {
183
+ if (block.type === 'text' && block.text) sub.handle.event({ type: 'content', content: block.text })
184
+ if (block.type !== 'tool_use') continue
185
+ const { name, args } = picoTool(block.name, block.input, host.cwd)
186
+ sub.handle.event({ type: 'tool_executing', call: { id: block.id, type: 'function', function: { name, arguments: JSON.stringify(args) } }, at: Date.now() })
187
+ startSubagent(block)
188
+ }
189
+ } else if (message.type === 'user') {
190
+ const blocks = (Array.isArray(message.message?.content) ? message.message.content : []).filter((block) => block.type === 'tool_result')
191
+ for (const block of blocks) {
192
+ const text = toolResultText(block.content)
193
+ sub.handle.event(block.is_error ? { type: 'tool_error', call: { id: block.tool_use_id }, error: text } : { type: 'tool_complete', call: { id: block.tool_use_id }, result: text })
194
+ finishSubagent(block, blocks.length === 1 ? message.tool_use_result : null)
195
+ }
196
+ }
197
+ }
198
+
199
+ // offered: pico's tools that Claude Code has no version of its own. A
200
+ // call through the bridge lands on the tool_use Claude announced for
201
+ // it (same name, same arguments, oldest first), once every message
202
+ // before it has been handled, since it reaches pico by another channel
203
+ entry.bridge.setTurn(tools.filter((tool) => !COVERED_TOOLS.has(tool.name)), async (name, args) => {
204
+ await chain
205
+ const at = unclaimed.findIndex((use) => use.name === name && JSON.stringify(use.args) === JSON.stringify(args ?? {}))
206
+ const use = at >= 0 ? unclaimed.splice(at, 1)[0] : null
207
+ recorder.currentCall = use ? { id: use.id } : null
208
+ })
209
+
210
+ const onAssistant = (message) => {
211
+ const id = message.message?.id
212
+ if (assistant && assistant.id !== id) flushAssistant()
213
+ assistant ??= { id, text: '', calls: [] }
214
+ for (const block of message.message?.content ?? []) {
215
+ if (block.type === 'text') assistant.text += block.text
216
+ if (block.type !== 'tool_use') continue
217
+ const { name, args, bridged } = picoTool(block.name, block.input, host.cwd)
218
+ const call = { id: block.id, type: 'function', function: { name, arguments: JSON.stringify(args) } }
219
+ assistant.calls.push(call)
220
+ uses.set(block.id, { id: block.id, name: block.name, input: block.input, call, bridged })
221
+ if (bridged) unclaimed.push({ id: block.id, name, args: block.input ?? {} })
222
+ onStream({ type: 'tool_calls_ready', calls: [call] })
223
+ onStream({ type: 'tool_executing', call })
224
+ startSubagent(block)
225
+ }
226
+ if (!raws.has(id)) countUsage(id, message.message?.usage)
227
+ }
228
+
229
+ const onResults = async (message) => {
230
+ const blocks = (Array.isArray(message.message?.content) ? message.message.content : []).filter((block) => block.type === 'tool_result')
231
+ if (!blocks.length) return
232
+ flushAssistant()
233
+ for (const block of blocks) {
234
+ const use = uses.get(block.tool_use_id)
235
+ if (!use) continue
236
+ uses.delete(block.tool_use_id)
237
+ const waiting = unclaimed.findIndex((candidate) => candidate.id === use.id)
238
+ if (waiting >= 0) unclaimed.splice(waiting, 1)
239
+ const text = toolResultText(block.content)
240
+ finishSubagent(block, blocks.length === 1 ? message.tool_use_result : null)
241
+ collected.push({ role: 'tool', tool_call_id: use.id, content: text })
242
+ // a bridged call the bridge never ran (Claude refused it first)
243
+ // has no entry yet, so it gets one like any other call
244
+ if (!use.bridged || !recorder.entries.some((candidate) => candidate.callId === use.id)) {
245
+ // the structured result describes the message's only call
246
+ const extra = blocks.length === 1 ? message.tool_use_result : null
247
+ const path = extra?.filePath
248
+ const after = path && existsSync(path) ? readFileSync(path, 'utf8') : null
249
+ recorder.entries.push(toolEntry(use, block, extra, { cwd: host.cwd, after, interrupted }))
250
+ }
251
+ onStream({ type: block.is_error ? 'tool_error' : 'tool_complete', call: use.call, ...(block.is_error ? { error: text } : { result: text }) })
252
+ }
253
+ // between tool rounds is where pico delivers notes that arrived
254
+ // mid-turn; Claude Code folds a message sent now into the same turn
255
+ if (interrupted || !beforeRequest) return
256
+ const notes = await beforeRequest()
257
+ if (!notes?.length) return
258
+ collected.push(...notes)
259
+ entry.proc?.send(notes.flatMap(userBlocks))
260
+ }
261
+
262
+ let outcomeCleanup = () => {}
263
+ const outcome = new Promise((resolve) => {
264
+ entry.onMessage = (message) => {
265
+ chain = chain.then(async () => {
266
+ if (message.parent_tool_use_id) return onSubagent(message)
267
+ if (message.type === 'system' && message.subtype === 'init') entry.claudeSessionId = message.session_id
268
+ else if (message.type === 'stream_event') {
269
+ const event = message.event
270
+ if (event.type === 'message_start') {
271
+ streaming = event.message?.id ?? null
272
+ countUsage(streaming, event.message?.usage)
273
+ } else if (event.type === 'message_delta') countUsage(streaming, event.usage)
274
+ else if (event.type === 'content_block_delta' && event.delta?.type === 'text_delta' && event.delta.text) onStream({ type: 'content', content: event.delta.text })
275
+ else if (event.type === 'content_block_delta' && event.delta?.type === 'thinking_delta' && event.delta.thinking) onStream({ type: 'thinking', content: event.delta.thinking })
276
+ } else if (message.type === 'assistant') onAssistant(message)
277
+ else if (message.type === 'user') await onResults(message)
278
+ else if (message.type === 'result') {
279
+ entry.claudeSessionId = message.session_id ?? entry.claudeSessionId
280
+ if (message.is_error && !interrupted) error = message.result || message.errors?.join('; ') || message.subtype
281
+ resolve()
282
+ }
283
+ }).catch((failure) => { error = String(failure.message || failure); resolve() })
284
+ }
285
+ entry.onExit = (exit) => {
286
+ if (!interrupted) error = exit.error?.message || exit.stderr || 'Claude Code stopped'
287
+ resolve()
288
+ }
289
+ const onAbort = () => {
290
+ interrupted = true
291
+ entry.proc?.interrupt().catch(() => {})
292
+ graceTimer = setTimeout(() => { stop(entry); resolve() }, INTERRUPT_GRACE_MS)
293
+ }
294
+ if (signal?.aborted) onAbort()
295
+ else signal?.addEventListener('abort', onAbort, { once: true })
296
+ outcomeCleanup = () => signal?.removeEventListener('abort', onAbort)
297
+ })
298
+
299
+ // a process that failed to start takes its input nowhere, and says
300
+ // why as it exits, which may already have happened
301
+ const sent = !!entry.proc?.send(content)
302
+ await (sent ? outcome : Promise.race([outcome, new Promise((resolve) => setTimeout(resolve, 2000))]))
303
+ if (!sent) error ??= entry.lastExit?.error?.message || entry.lastExit?.stderr || 'Claude Code is not running'
304
+ clearTimeout(graceTimer)
305
+ outcomeCleanup()
306
+ entry.onMessage = null
307
+ entry.onExit = null
308
+ flushAssistant()
309
+ for (const sub of subagents.values()) sub.handle.finish({ interrupted: true })
310
+ // a call cut off by an interrupt still needs a result, or the history
311
+ // is invalid for whichever model reads it next
312
+ for (const use of uses.values()) collected.push({ role: 'tool', tool_call_id: use.id, content: '[interrupted before it finished]' })
313
+
314
+ if (entry.proc) {
315
+ entry.synced = fingerprint([...history, ...collected])
316
+ entry.idle = setTimeout(() => stop(entry), idleMs)
317
+ entry.idle.unref?.()
318
+ } else {
319
+ // the process died: what Claude Code saved may not match, so the
320
+ // next turn starts over from pico's history
321
+ entry.claudeSessionId = null
322
+ entry.synced = null
323
+ }
324
+ return {
325
+ messages: collected,
326
+ usage: responses.size ? usage : null,
327
+ lastPromptTokens: lastPrompt,
328
+ interrupted: interrupted || !!error,
329
+ stalled: false,
330
+ ...(error ? { error } : {}),
331
+ engineState: { claudeSessionId: entry.claudeSessionId, owner: entry.owner, synced: entry.synced },
332
+ }
333
+ }
334
+
335
+ // pico's compaction, done by the same model: one bare Claude Code run
336
+ // that reads the conversation and writes the summary
337
+ async function compact({ history, modelName, prompt, signal, onStream = () => {} }) {
338
+ let text = ''
339
+ let failure = null
340
+ let proc = null
341
+ await new Promise((resolve) => {
342
+ proc = spawn({
343
+ command,
344
+ cwd: process.cwd(),
345
+ model: cliModel(modelName),
346
+ oneShot: true,
347
+ onMessage: (message) => {
348
+ if (message.type === 'stream_event' && message.event?.delta?.type === 'text_delta') {
349
+ text += message.event.delta.text
350
+ onStream({ type: 'content', content: message.event.delta.text })
351
+ } else if (message.type === 'result') {
352
+ if (message.is_error) failure = message.result || message.subtype
353
+ else text = message.result ?? text
354
+ proc.close()
355
+ resolve()
356
+ }
357
+ },
358
+ onExit: (exit) => { failure ??= exit.error?.message ?? null; resolve() },
359
+ })
360
+ signal?.addEventListener('abort', () => { proc.close(); resolve() }, { once: true })
361
+ proc.send(`<transcript>\n${transcriptText(history)}\n</transcript>\n\n${prompt}`)
362
+ })
363
+ if (signal?.aborted) throw new Error('compaction cancelled')
364
+ if (failure) throw new Error(failure)
365
+ return text.trim()
366
+ }
367
+
368
+ return {
369
+ name: CLAUDE_CODE_PROVIDER,
370
+ // Claude Code compacts its own context as it fills; pico compacting
371
+ // too would only restart the Claude session from a summary
372
+ autoCompact: false,
373
+ run,
374
+ compact,
375
+ // the pico session is done with: its process and bridge go
376
+ release(sessionId) {
377
+ const entry = sessions.get(sessionId)
378
+ if (!entry) return
379
+ stop(entry)
380
+ sessions.delete(sessionId)
381
+ },
382
+ releaseAll() {
383
+ for (const entry of sessions.values()) stop(entry)
384
+ sessions.clear()
385
+ },
386
+ }
387
+ }