picocode-core 0.9.210 → 0.9.211

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
+
35
+ ## Not covered
36
+
37
+ - What happens inside a Claude `Task` subagent: only the call and its result are shown.
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, 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,120 @@
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
+ ]
37
+ if (oneShot) args.push('--tools', '', '--no-session-persistence', '--strict-mcp-config')
38
+ if (model) args.push('--model', model)
39
+ if (effort) args.push('--effort', effort)
40
+ if (resume) args.push('--resume', resume)
41
+ if (resume && fork) args.push('--fork-session')
42
+ if (mcpConfig) args.push('--mcp-config', JSON.stringify(mcpConfig))
43
+ if (appendSystemPrompt) args.push('--append-system-prompt', appendSystemPrompt)
44
+ return args
45
+ }
46
+
47
+ export function spawnClaude({ command = 'claude', cwd, env, onMessage, onExit, ...options }) {
48
+ const child = spawn(command, claudeArgs(options), { cwd, env: claudeEnv({ ...process.env, ...env }), stdio: ['pipe', 'pipe', 'pipe'] })
49
+ const pending = new Map()
50
+ let stderr = ''
51
+ let exited = false
52
+
53
+ const write = (message) => {
54
+ if (exited || !child.stdin.writable) return false
55
+ child.stdin.write(`${JSON.stringify(message)}\n`)
56
+ return true
57
+ }
58
+
59
+ createInterface({ input: child.stdout }).on('line', (line) => {
60
+ let message
61
+ try { message = JSON.parse(line) } catch { return }
62
+ if (message.type === 'control_response') {
63
+ const id = message.response?.request_id
64
+ const waiter = pending.get(id)
65
+ pending.delete(id)
66
+ if (message.response.subtype === 'error') waiter?.reject(new Error(message.response.error || 'control request failed'))
67
+ else waiter?.resolve(message.response.response ?? null)
68
+ return
69
+ }
70
+ if (message.type === 'control_request') {
71
+ // permissions are skipped, so a tool request should never come; if
72
+ // one does, it is allowed rather than left to hang the turn
73
+ const request = message.request ?? {}
74
+ const response = request.subtype === 'can_use_tool'
75
+ ? { subtype: 'success', request_id: message.request_id, response: { behavior: 'allow', updatedInput: request.input } }
76
+ : { subtype: 'error', request_id: message.request_id, error: `pico does not handle ${request.subtype}` }
77
+ write({ type: 'control_response', response })
78
+ return
79
+ }
80
+ onMessage(message)
81
+ })
82
+ child.stderr.setEncoding('utf8')
83
+ child.stderr.on('data', (chunk) => { stderr = (stderr + chunk).slice(-4000) })
84
+ child.stdin.on('error', () => {})
85
+
86
+ const finish = (error) => {
87
+ if (exited) return
88
+ exited = true
89
+ for (const waiter of pending.values()) waiter.reject(new Error('Claude Code exited'))
90
+ pending.clear()
91
+ onExit?.({ error, stderr: stderr.trim() })
92
+ }
93
+ child.on('error', (error) => finish(error.code === 'ENOENT' ? new Error(`${command} not found; install Claude Code and sign in with claude auth login`) : error))
94
+ child.on('exit', (code, signal) => finish(code === 0 || signal === 'SIGTERM' ? null : new Error(`Claude Code exited with ${signal ?? `code ${code}`}`)))
95
+
96
+ function request(subtype, payload = {}) {
97
+ const id = randomUUID()
98
+ return new Promise((resolve, reject) => {
99
+ pending.set(id, { resolve, reject })
100
+ if (!write({ type: 'control_request', request_id: id, request: { subtype, ...payload } })) {
101
+ pending.delete(id)
102
+ reject(new Error('Claude Code is not running'))
103
+ }
104
+ })
105
+ }
106
+
107
+ request('initialize').catch(() => {})
108
+
109
+ return {
110
+ get alive() { return !exited },
111
+ get stderr() { return stderr.trim() },
112
+ send: (content) => write({ type: 'user', message: { role: 'user', content } }),
113
+ interrupt: () => request('interrupt'),
114
+ close() {
115
+ if (exited) return
116
+ child.stdin.end()
117
+ setTimeout(() => { if (!exited) child.kill('SIGTERM') }, 3000).unref()
118
+ },
119
+ }
120
+ }
@@ -0,0 +1,343 @@
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
+ // how long an interrupted turn may take to wind down before the process
24
+ // is stopped instead
25
+ const INTERRUPT_GRACE_MS = 10000
26
+
27
+ 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.`
28
+
29
+ function systemPrompt(contextFiles = []) {
30
+ // Claude Code reads CLAUDE.md files itself; any other instructions pico
31
+ // would give its own models (AGENTS.md) are passed along
32
+ const files = contextFiles.filter((file) => basename(file.path) !== 'CLAUDE.md' && file.content?.trim())
33
+ if (!files.length) return HOST_NOTE
34
+ return `${HOST_NOTE}\n\nProject instructions:\n\n${files.map((file) => `<file path="${file.path}">\n${file.content.trim()}\n</file>`).join('\n\n')}`
35
+ }
36
+
37
+ // the trailing user messages of `history` that Claude Code has not seen,
38
+ // given the fingerprint of what it has: null when the history diverged
39
+ function unseen(history, synced) {
40
+ if (!synced) return null
41
+ for (let at = history.length; at >= 0; at--) {
42
+ if (at < history.length && history[at].role !== 'user') break
43
+ if (fingerprint(history.slice(0, at)) === synced) return history.slice(at)
44
+ }
45
+ return null
46
+ }
47
+
48
+ export function createClaudeCodeEngine({ command = claudeCommand(), idleMs = IDLE_MS, spawn = spawnClaude, bridge = createBridge } = {}) {
49
+ // per pico session: its process, bridge, and which Claude session holds
50
+ // which history
51
+ const sessions = new Map()
52
+
53
+ function stop(entry) {
54
+ clearTimeout(entry.idle)
55
+ entry.proc?.close()
56
+ entry.proc = null
57
+ entry.bridge?.close().catch(() => {})
58
+ entry.bridge = null
59
+ }
60
+
61
+ async function start(entry, { cwd, env, model, effort, resume, fork, contextFiles }) {
62
+ entry.bridge = await bridge()
63
+ entry.model = model
64
+ entry.effort = effort
65
+ entry.proc = spawn({
66
+ command,
67
+ cwd,
68
+ env,
69
+ model,
70
+ effort,
71
+ resume,
72
+ fork,
73
+ mcpConfig: entry.bridge.mcpConfig(),
74
+ appendSystemPrompt: systemPrompt(contextFiles),
75
+ onMessage: (message) => entry.onMessage?.(message),
76
+ onExit: (exit) => {
77
+ entry.proc = null
78
+ entry.lastExit = exit
79
+ entry.onExit?.(exit)
80
+ },
81
+ })
82
+ }
83
+
84
+ async function run({ history, tools, recorder, modelName, effort, signal, onStream = () => {}, beforeRequest, host = {} }) {
85
+ const key = host.sessionId ?? 'ephemeral'
86
+ const entry = sessions.get(key) ?? { claudeSessionId: null, owner: key, synced: null }
87
+ sessions.set(key, entry)
88
+ clearTimeout(entry.idle)
89
+ const model = cliModel(modelName)
90
+ const level = effort && effort !== 'auto' ? effort : null
91
+
92
+ // what Claude Code already holds: this process's session, or the one
93
+ // the controller saved, as long as the history has not moved under it
94
+ const known = entry.claudeSessionId ? entry : host.engineState?.claudeSessionId ? host.engineState : null
95
+ const fresh = known ? unseen(history, known.synced) : null
96
+ if (entry.proc && (!fresh || entry.model !== model || entry.effort !== level)) stop(entry)
97
+ let seed = null
98
+ let input = fresh
99
+ if (!entry.proc) {
100
+ if (!fresh) {
101
+ const turn = splitTurn(history)
102
+ input = turn.input
103
+ if (turn.prior.length) seed = seedText(turn.prior)
104
+ }
105
+ }
106
+
107
+ const content = []
108
+ if (seed) content.push({ type: 'text', text: seed })
109
+ for (const message of await hydrateImages(input)) content.push(...userBlocks(message))
110
+ if (!content.length) content.push({ type: 'text', text: '[system notification] continue.' })
111
+
112
+ if (!entry.proc) {
113
+ entry.lastExit = null
114
+ try {
115
+ 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 })
116
+ } catch (error) {
117
+ stop(entry)
118
+ return { messages: [], usage: null, lastPromptTokens: 0, interrupted: true, stalled: false, error: String(error.message || error) }
119
+ }
120
+ if (!fresh) entry.claudeSessionId = null
121
+ entry.owner = key
122
+ }
123
+
124
+ const collected = []
125
+ const uses = new Map()
126
+ const unclaimed = []
127
+ const responses = new Map()
128
+ let assistant = null
129
+ let usage = emptyUsage()
130
+ let lastPrompt = 0
131
+ let interrupted = false
132
+ let error = null
133
+ let graceTimer = null
134
+
135
+ const flushAssistant = () => {
136
+ if (!assistant) return
137
+ if (assistant.text || assistant.calls.length) collected.push({ role: 'assistant', content: assistant.text, ...(assistant.calls.length ? { tool_calls: assistant.calls } : {}) })
138
+ assistant = null
139
+ }
140
+
141
+ // a response's usage arrives in parts: input at its start, output
142
+ // growing until its end
143
+ const raws = new Map()
144
+ let streaming = null
145
+ const countUsage = (id, raw) => {
146
+ if (!id || !raw) return
147
+ raws.set(id, { ...raws.get(id), ...raw })
148
+ responses.set(id, usageOf(raws.get(id)))
149
+ usage = [...responses.values()].reduce(addUsage, emptyUsage())
150
+ lastPrompt = responses.get(id).promptTokens
151
+ onStream({ type: 'usage', usage })
152
+ }
153
+
154
+ // Claude Code's messages are handled one at a time, in order
155
+ let chain = Promise.resolve()
156
+
157
+ // offered: pico's tools that Claude Code has no version of its own. A
158
+ // call through the bridge lands on the tool_use Claude announced for
159
+ // it (same name, same arguments, oldest first), once every message
160
+ // before it has been handled, since it reaches pico by another channel
161
+ entry.bridge.setTurn(tools.filter((tool) => !COVERED_TOOLS.has(tool.name)), async (name, args) => {
162
+ await chain
163
+ const at = unclaimed.findIndex((use) => use.name === name && JSON.stringify(use.args) === JSON.stringify(args ?? {}))
164
+ const use = at >= 0 ? unclaimed.splice(at, 1)[0] : null
165
+ recorder.currentCall = use ? { id: use.id } : null
166
+ })
167
+
168
+ const onAssistant = (message) => {
169
+ const id = message.message?.id
170
+ if (assistant && assistant.id !== id) flushAssistant()
171
+ assistant ??= { id, text: '', calls: [] }
172
+ for (const block of message.message?.content ?? []) {
173
+ if (block.type === 'text') assistant.text += block.text
174
+ if (block.type !== 'tool_use') continue
175
+ const { name, args, bridged } = picoTool(block.name, block.input, host.cwd)
176
+ const call = { id: block.id, type: 'function', function: { name, arguments: JSON.stringify(args) } }
177
+ assistant.calls.push(call)
178
+ uses.set(block.id, { id: block.id, name: block.name, input: block.input, call, bridged })
179
+ if (bridged) unclaimed.push({ id: block.id, name, args: block.input ?? {} })
180
+ onStream({ type: 'tool_calls_ready', calls: [call] })
181
+ onStream({ type: 'tool_executing', call })
182
+ }
183
+ if (!raws.has(id)) countUsage(id, message.message?.usage)
184
+ }
185
+
186
+ const onResults = async (message) => {
187
+ const blocks = (Array.isArray(message.message?.content) ? message.message.content : []).filter((block) => block.type === 'tool_result')
188
+ if (!blocks.length) return
189
+ flushAssistant()
190
+ for (const block of blocks) {
191
+ const use = uses.get(block.tool_use_id)
192
+ if (!use) continue
193
+ uses.delete(block.tool_use_id)
194
+ const waiting = unclaimed.findIndex((candidate) => candidate.id === use.id)
195
+ if (waiting >= 0) unclaimed.splice(waiting, 1)
196
+ const text = toolResultText(block.content)
197
+ collected.push({ role: 'tool', tool_call_id: use.id, content: text })
198
+ // a bridged call the bridge never ran (Claude refused it first)
199
+ // has no entry yet, so it gets one like any other call
200
+ if (!use.bridged || !recorder.entries.some((candidate) => candidate.callId === use.id)) {
201
+ // the structured result describes the message's only call
202
+ const extra = blocks.length === 1 ? message.tool_use_result : null
203
+ const path = extra?.filePath
204
+ const after = path && existsSync(path) ? readFileSync(path, 'utf8') : null
205
+ recorder.entries.push(toolEntry(use, block, extra, { cwd: host.cwd, after, interrupted }))
206
+ }
207
+ onStream({ type: block.is_error ? 'tool_error' : 'tool_complete', call: use.call, ...(block.is_error ? { error: text } : { result: text }) })
208
+ }
209
+ // between tool rounds is where pico delivers notes that arrived
210
+ // mid-turn; Claude Code folds a message sent now into the same turn
211
+ if (interrupted || !beforeRequest) return
212
+ const notes = await beforeRequest()
213
+ if (!notes?.length) return
214
+ collected.push(...notes)
215
+ entry.proc?.send(notes.flatMap(userBlocks))
216
+ }
217
+
218
+ let outcomeCleanup = () => {}
219
+ const outcome = new Promise((resolve) => {
220
+ entry.onMessage = (message) => {
221
+ chain = chain.then(async () => {
222
+ // a subagent's own traffic stays inside its Task call
223
+ if (message.parent_tool_use_id) return
224
+ if (message.type === 'system' && message.subtype === 'init') entry.claudeSessionId = message.session_id
225
+ else if (message.type === 'stream_event') {
226
+ const event = message.event
227
+ if (event.type === 'message_start') {
228
+ streaming = event.message?.id ?? null
229
+ countUsage(streaming, event.message?.usage)
230
+ } else if (event.type === 'message_delta') countUsage(streaming, event.usage)
231
+ else if (event.type === 'content_block_delta' && event.delta?.type === 'text_delta' && event.delta.text) onStream({ type: 'content', content: event.delta.text })
232
+ else if (event.type === 'content_block_delta' && event.delta?.type === 'thinking_delta' && event.delta.thinking) onStream({ type: 'thinking', content: event.delta.thinking })
233
+ } else if (message.type === 'assistant') onAssistant(message)
234
+ else if (message.type === 'user') await onResults(message)
235
+ else if (message.type === 'result') {
236
+ entry.claudeSessionId = message.session_id ?? entry.claudeSessionId
237
+ if (message.is_error && !interrupted) error = message.result || message.errors?.join('; ') || message.subtype
238
+ resolve()
239
+ }
240
+ }).catch((failure) => { error = String(failure.message || failure); resolve() })
241
+ }
242
+ entry.onExit = (exit) => {
243
+ if (!interrupted) error = exit.error?.message || exit.stderr || 'Claude Code stopped'
244
+ resolve()
245
+ }
246
+ const onAbort = () => {
247
+ interrupted = true
248
+ entry.proc?.interrupt().catch(() => {})
249
+ graceTimer = setTimeout(() => { stop(entry); resolve() }, INTERRUPT_GRACE_MS)
250
+ }
251
+ if (signal?.aborted) onAbort()
252
+ else signal?.addEventListener('abort', onAbort, { once: true })
253
+ outcomeCleanup = () => signal?.removeEventListener('abort', onAbort)
254
+ })
255
+
256
+ // a process that failed to start takes its input nowhere, and says
257
+ // why as it exits, which may already have happened
258
+ const sent = !!entry.proc?.send(content)
259
+ await (sent ? outcome : Promise.race([outcome, new Promise((resolve) => setTimeout(resolve, 2000))]))
260
+ if (!sent) error ??= entry.lastExit?.error?.message || entry.lastExit?.stderr || 'Claude Code is not running'
261
+ clearTimeout(graceTimer)
262
+ outcomeCleanup()
263
+ entry.onMessage = null
264
+ entry.onExit = null
265
+ flushAssistant()
266
+ // a call cut off by an interrupt still needs a result, or the history
267
+ // is invalid for whichever model reads it next
268
+ for (const use of uses.values()) collected.push({ role: 'tool', tool_call_id: use.id, content: '[interrupted before it finished]' })
269
+
270
+ if (entry.proc) {
271
+ entry.synced = fingerprint([...history, ...collected])
272
+ entry.idle = setTimeout(() => stop(entry), idleMs)
273
+ entry.idle.unref?.()
274
+ } else {
275
+ // the process died: what Claude Code saved may not match, so the
276
+ // next turn starts over from pico's history
277
+ entry.claudeSessionId = null
278
+ entry.synced = null
279
+ }
280
+ return {
281
+ messages: collected,
282
+ usage: responses.size ? usage : null,
283
+ lastPromptTokens: lastPrompt,
284
+ interrupted: interrupted || !!error,
285
+ stalled: false,
286
+ ...(error ? { error } : {}),
287
+ engineState: { claudeSessionId: entry.claudeSessionId, owner: entry.owner, synced: entry.synced },
288
+ }
289
+ }
290
+
291
+ // pico's compaction, done by the same model: one bare Claude Code run
292
+ // that reads the conversation and writes the summary
293
+ async function compact({ history, modelName, prompt, signal, onStream = () => {} }) {
294
+ let text = ''
295
+ let failure = null
296
+ let proc = null
297
+ await new Promise((resolve) => {
298
+ proc = spawn({
299
+ command,
300
+ cwd: process.cwd(),
301
+ model: cliModel(modelName),
302
+ oneShot: true,
303
+ onMessage: (message) => {
304
+ if (message.type === 'stream_event' && message.event?.delta?.type === 'text_delta') {
305
+ text += message.event.delta.text
306
+ onStream({ type: 'content', content: message.event.delta.text })
307
+ } else if (message.type === 'result') {
308
+ if (message.is_error) failure = message.result || message.subtype
309
+ else text = message.result ?? text
310
+ proc.close()
311
+ resolve()
312
+ }
313
+ },
314
+ onExit: (exit) => { failure ??= exit.error?.message ?? null; resolve() },
315
+ })
316
+ signal?.addEventListener('abort', () => { proc.close(); resolve() }, { once: true })
317
+ proc.send(`<transcript>\n${transcriptText(history)}\n</transcript>\n\n${prompt}`)
318
+ })
319
+ if (signal?.aborted) throw new Error('compaction cancelled')
320
+ if (failure) throw new Error(failure)
321
+ return text.trim()
322
+ }
323
+
324
+ return {
325
+ name: CLAUDE_CODE_PROVIDER,
326
+ // Claude Code compacts its own context as it fills; pico compacting
327
+ // too would only restart the Claude session from a summary
328
+ autoCompact: false,
329
+ run,
330
+ compact,
331
+ // the pico session is done with: its process and bridge go
332
+ release(sessionId) {
333
+ const entry = sessions.get(sessionId)
334
+ if (!entry) return
335
+ stop(entry)
336
+ sessions.delete(sessionId)
337
+ },
338
+ releaseAll() {
339
+ for (const entry of sessions.values()) stop(entry)
340
+ sessions.clear()
341
+ },
342
+ }
343
+ }
@@ -0,0 +1,48 @@
1
+ // The stdio MCP server Claude Code starts for pico's tools. It holds no
2
+ // tools itself: every list and call goes over the socket named in its
3
+ // environment to the bridge in the pico process (see bridge.js).
4
+
5
+ import { createConnection } from 'node:net'
6
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js'
7
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
8
+ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'
9
+
10
+ const socket = createConnection(process.env.PICO_BRIDGE_SOCKET)
11
+ socket.setEncoding('utf8')
12
+ socket.write(`${JSON.stringify({ token: process.env.PICO_BRIDGE_TOKEN })}\n`)
13
+
14
+ const waiting = new Map()
15
+ let seq = 0
16
+ let buffer = ''
17
+ const server = new Server({ name: 'pico', version: '1.0.0' }, { capabilities: { tools: { listChanged: true } } })
18
+
19
+ socket.on('data', (chunk) => {
20
+ buffer += chunk
21
+ let index
22
+ while ((index = buffer.indexOf('\n')) >= 0) {
23
+ const message = JSON.parse(buffer.slice(0, index))
24
+ buffer = buffer.slice(index + 1)
25
+ if (message.event === 'changed') server.sendToolListChanged().catch(() => {})
26
+ else waiting.get(message.id)?.(message)
27
+ waiting.delete(message.id)
28
+ }
29
+ })
30
+ socket.on('error', () => process.exit(1))
31
+ socket.on('close', () => process.exit(0))
32
+
33
+ function ask(message) {
34
+ const id = ++seq
35
+ return new Promise((resolve) => {
36
+ waiting.set(id, resolve)
37
+ socket.write(`${JSON.stringify({ id, ...message })}\n`)
38
+ })
39
+ }
40
+
41
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: (await ask({ op: 'list' })).tools ?? [] }))
42
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
43
+ const reply = await ask({ op: 'call', name: request.params.name, args: request.params.arguments ?? {} })
44
+ if (reply.error) return { content: [{ type: 'text', text: reply.error }], isError: true }
45
+ return { content: [{ type: 'text', text: reply.result }] }
46
+ })
47
+
48
+ await server.connect(new StdioServerTransport())