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,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())
@@ -0,0 +1,71 @@
1
+ // The Claude Code models pico offers, and whether this machine can run
2
+ // them. They are reached through the local `claude` command and its own
3
+ // claude.ai sign-in, never through an API key.
4
+
5
+ import { execFile } from 'node:child_process'
6
+ import { accessSync, constants } from 'node:fs'
7
+ import { homedir } from 'node:os'
8
+ import { delimiter, join } from 'node:path'
9
+ import { promisify } from 'node:util'
10
+ import { claudeEnv } from './cli.js'
11
+
12
+ const exec = promisify(execFile)
13
+
14
+ export const CLAUDE_CODE_PROVIDER = 'claude-code'
15
+
16
+ // the CLI's model aliases always name the newest model of each family;
17
+ // every one of them has a 1M token context window
18
+ const FAMILIES = [
19
+ { alias: 'fable', label: 'Fable' },
20
+ { alias: 'opus', label: 'Opus' },
21
+ { alias: 'sonnet', label: 'Sonnet' },
22
+ { alias: 'haiku', label: 'Haiku' },
23
+ ]
24
+
25
+ export function claudeCodeModels({ available = true } = {}) {
26
+ return FAMILIES.map(({ alias, label }) => ({
27
+ name: `${CLAUDE_CODE_PROVIDER}/${alias}`,
28
+ label: `${label} (Claude Code)`,
29
+ provider: CLAUDE_CODE_PROVIDER,
30
+ context: 1000000,
31
+ effort: true,
32
+ vision: true,
33
+ speed: false,
34
+ available,
35
+ keyHint: 'claude auth login',
36
+ }))
37
+ }
38
+
39
+ // the alias the CLI takes for a pico model name
40
+ export function cliModel(name) {
41
+ return String(name).startsWith(`${CLAUDE_CODE_PROVIDER}/`) ? name.slice(CLAUDE_CODE_PROVIDER.length + 1) : name
42
+ }
43
+
44
+ // the `claude` executable. A host started from a desktop launcher does not
45
+ // have the user's shell PATH, so Claude Code's own install locations are
46
+ // looked in too
47
+ export function claudeCommand(env = process.env) {
48
+ const candidates = [
49
+ ...String(env.PATH ?? '').split(delimiter).filter(Boolean).map((dir) => join(dir, 'claude')),
50
+ join(homedir(), '.local', 'bin', 'claude'),
51
+ join(homedir(), '.claude', 'local', 'claude'),
52
+ ]
53
+ for (const path of candidates) {
54
+ try { accessSync(path, constants.X_OK); return path } catch {}
55
+ }
56
+ return 'claude'
57
+ }
58
+
59
+ // whether `claude` is installed and signed in to claude.ai. A machine with
60
+ // only an API key configured does not count: that is what pico's own
61
+ // Anthropic models are for
62
+ export async function claudeCodeStatus({ command = claudeCommand() } = {}) {
63
+ try {
64
+ const { stdout } = await exec(command, ['auth', 'status', '--json'], { env: claudeEnv(), timeout: 15000 })
65
+ const status = JSON.parse(stdout)
66
+ const subscribed = status.loggedIn === true && status.authMethod === 'claude.ai'
67
+ return { installed: true, connected: subscribed, email: subscribed ? status.email ?? null : null, plan: subscribed ? status.subscriptionType ?? null : null }
68
+ } catch (error) {
69
+ return { installed: error.code !== 'ENOENT', connected: false, email: null, plan: null }
70
+ }
71
+ }
@@ -0,0 +1,220 @@
1
+ // Pure translation between Claude Code's stream-json and pico's shapes.
2
+ // Nothing here touches a process or the file system, so every rule about
3
+ // how a Claude turn becomes pico history, tool rows and usage is testable
4
+ // against recorded output.
5
+
6
+ import { createHash } from 'node:crypto'
7
+ import { isAbsolute, relative } from 'node:path'
8
+ import { makeDiff } from '../tools/diff.js'
9
+ import { makeWriteEdit } from '../reversible-edit.js'
10
+ import { toolResultOutput } from '../tools/recorder.js'
11
+ import { commitLabel, elementLabel, fileLabel, selectionLabel } from '../attachments.js'
12
+
13
+ // pico's own tools run inside Claude Code through the MCP bridge under
14
+ // this server name, so Claude sees them as mcp__pico__<name>
15
+ export const BRIDGE_SERVER = 'pico'
16
+ const BRIDGE_PREFIX = `mcp__${BRIDGE_SERVER}__`
17
+
18
+ // pico tools Claude Code already has its own version of; offering both
19
+ // would only make the model choose between equivalent tools
20
+ export const COVERED_TOOLS = new Set([
21
+ 'read', 'write', 'edit', 'bash', 'glob', 'grep', 'view', 'shell_output', 'shell_kill', 'tool_result',
22
+ 'agent_plan', 'agent_start', 'agent_list', 'agent_collect', 'agent_cancel', 'deliberate',
23
+ 'skill', 'remember', 'recall',
24
+ ])
25
+
26
+ const SEED_CHARS = 600000
27
+ const SEED_TOOL_CHARS = 2000
28
+
29
+ function shortPath(path, cwd) {
30
+ if (typeof path !== 'string' || !cwd || !isAbsolute(path)) return path
31
+ const rel = relative(cwd, path)
32
+ return rel && !rel.startsWith('..') && !isAbsolute(rel) ? rel : path
33
+ }
34
+
35
+ // Claude's tool calls under the names and argument shapes pico renders:
36
+ // a Bash call shows its command, an Edit its path and diff
37
+ export function picoTool(name, input = {}, cwd) {
38
+ if (name.startsWith(BRIDGE_PREFIX)) return { name: name.slice(BRIDGE_PREFIX.length), args: input, bridged: true }
39
+ const path = shortPath(input.file_path ?? input.notebook_path, cwd)
40
+ switch (name) {
41
+ case 'Bash': return { name: 'bash', args: { command: input.command, description: input.description, ...(input.run_in_background ? { background: true } : {}), ...(input.timeout ? { timeout: input.timeout } : {}) } }
42
+ case 'Read': return { name: 'read', args: { path, ...(input.offset != null ? { offset: input.offset } : {}), ...(input.limit != null ? { limit: input.limit } : {}) } }
43
+ case 'Edit': return { name: 'edit', args: { path, oldText: input.old_string, newText: input.new_string, ...(input.replace_all ? { replaceAll: true } : {}) } }
44
+ case 'MultiEdit': return { name: 'edit', args: { path, edits: input.edits } }
45
+ case 'Write': return { name: 'write', args: { path, content: input.content } }
46
+ case 'Glob': return { name: 'glob', args: { pattern: input.pattern, ...(input.path ? { path: shortPath(input.path, cwd) } : {}) } }
47
+ case 'Grep': return { name: 'grep', args: { ...input, ...(input.path ? { path: shortPath(input.path, cwd) } : {}) } }
48
+ case 'Task':
49
+ case 'Agent': return { name: 'Task', args: { description: input.description, prompt: input.prompt, ...(input.subagent_type ? { subagent_type: input.subagent_type } : {}) } }
50
+ default: return { name, args: input }
51
+ }
52
+ }
53
+
54
+ export function toolResultText(content) {
55
+ if (content == null) return ''
56
+ if (typeof content === 'string') return content
57
+ if (Array.isArray(content)) return content.map((part) => part.type === 'text' ? part.text : part.type === 'image' ? '[image]' : '').filter(Boolean).join('\n')
58
+ return JSON.stringify(content)
59
+ }
60
+
61
+ // what the transcript keeps for one finished Claude tool call: output,
62
+ // errors, and for file changes a diff plus the record rewind needs to undo
63
+ // them. `after` is the file as it stands once the call returned; a call
64
+ // that failed because the turn was interrupted shows as interrupted
65
+ export function toolEntry({ id, name, input }, block, extra, { cwd, after = null, interrupted = false } = {}) {
66
+ const { name: picoName, args } = picoTool(name, input, cwd)
67
+ const entry = {
68
+ callId: id,
69
+ name: picoName,
70
+ args,
71
+ title: typeof args.path === 'string' ? args.path : undefined,
72
+ description: args.description,
73
+ status: block.is_error ? (interrupted ? 'interrupted' : 'error') : 'done',
74
+ durationMs: null,
75
+ }
76
+ if (block.is_error && !interrupted) entry.error = toolResultText(block.content).replace(/^<tool_use_error>|<\/tool_use_error>$/g, '')
77
+ if (picoName === 'bash' && extra && typeof extra === 'object') {
78
+ entry.fullOutput = toolResultOutput('bash', extra)
79
+ if (extra.interrupted) entry.status = 'interrupted'
80
+ } else {
81
+ entry.fullOutput = toolResultText(block.content)
82
+ }
83
+ if (!block.is_error && extra && typeof extra === 'object' && typeof extra.filePath === 'string' && (picoName === 'edit' || picoName === 'write')) {
84
+ const before = typeof extra.originalFile === 'string' ? extra.originalFile : null
85
+ const now = after ?? (picoName === 'write' ? extra.content : null)
86
+ if (typeof now === 'string') {
87
+ const shown = shortPath(extra.filePath, cwd)
88
+ entry.diff = makeDiff(shown, before ?? '', now)
89
+ entry.revert = makeWriteEdit(extra.filePath, before ?? '', now, before !== null)
90
+ if (before === null) entry.created = true
91
+ }
92
+ }
93
+ return entry
94
+ }
95
+
96
+ // pico usage from one Claude API response; prompt counts every input
97
+ // token the request carried, cached or not, since that is its context size
98
+ export function usageOf(usage = {}) {
99
+ const cached = usage.cache_read_input_tokens || 0
100
+ const prompt = (usage.input_tokens || 0) + cached + (usage.cache_creation_input_tokens || 0)
101
+ const completion = usage.output_tokens || 0
102
+ return { promptTokens: prompt, completionTokens: completion, totalTokens: prompt + completion, cachedTokens: cached, thoughtTokens: usage.output_tokens_details?.thinking_tokens || 0 }
103
+ }
104
+
105
+ export function addUsage(a, b) {
106
+ return {
107
+ promptTokens: a.promptTokens + b.promptTokens,
108
+ completionTokens: a.completionTokens + b.completionTokens,
109
+ totalTokens: a.totalTokens + b.totalTokens,
110
+ cachedTokens: a.cachedTokens + b.cachedTokens,
111
+ thoughtTokens: a.thoughtTokens + b.thoughtTokens,
112
+ }
113
+ }
114
+
115
+ export const emptyUsage = () => ({ promptTokens: 0, completionTokens: 0, totalTokens: 0, cachedTokens: 0, thoughtTokens: 0 })
116
+
117
+ // ---- pico history to Claude input ----
118
+
119
+ // the messages a turn adds: everything after the last thing the model
120
+ // said. pico appends the user's message, system notes and peer input
121
+ // before a turn starts, so these trail the history
122
+ export function splitTurn(history) {
123
+ let at = history.length
124
+ while (at > 0 && history[at - 1].role === 'user') at--
125
+ return { prior: history.slice(0, at), input: history.slice(at) }
126
+ }
127
+
128
+ // a hash of what a conversation said, blind to what pico rewrites in place
129
+ // later: old tool results get elided or trimmed, so only their ids count
130
+ export function fingerprint(history) {
131
+ const hash = createHash('sha256')
132
+ for (const message of history) {
133
+ hash.update(message.role)
134
+ if (message.role === 'tool') hash.update(String(message.tool_call_id))
135
+ else hash.update(typeof message.content === 'string' ? message.content : JSON.stringify(message.content ?? ''))
136
+ for (const call of message.tool_calls ?? []) hash.update(String(call.id))
137
+ hash.update('\u0000')
138
+ }
139
+ return hash.digest('hex')
140
+ }
141
+
142
+ function partText(part) {
143
+ if (part.type === 'text') return part.text
144
+ if (part.type === 'file') return fileLabel(part.path)
145
+ if (part.type === 'selection') return selectionLabel(part)
146
+ if (part.type === 'commit') return commitLabel(part)
147
+ if (part.type === 'element') return elementLabel(part)
148
+ return null
149
+ }
150
+
151
+ // one pico user message as Claude content blocks; `hydrated` is the same
152
+ // message after pico's image preparation, which reads images into base64
153
+ export function userBlocks(message) {
154
+ if (typeof message.content === 'string') return [{ type: 'text', text: message.content }]
155
+ const blocks = []
156
+ for (const part of message.content ?? []) {
157
+ if (part.type === 'image' && part.source?.kind === 'base64') {
158
+ blocks.push({ type: 'image', source: { type: 'base64', media_type: part.source.mediaType, data: part.source.data } })
159
+ continue
160
+ }
161
+ const text = partText(part)
162
+ if (text) blocks.push({ type: 'text', text })
163
+ }
164
+ return blocks
165
+ }
166
+
167
+ function messageText(message) {
168
+ if (typeof message.content === 'string') return message.content
169
+ return (message.content ?? []).map((part) => partText(part) ?? (part.type === 'image' ? '[image]' : '')).filter(Boolean).join('')
170
+ }
171
+
172
+ // a conversation as plain text, for a model that cannot be handed the
173
+ // messages themselves. The most recent part is kept when it is too long
174
+ export function transcriptText(history) {
175
+ const lines = []
176
+ for (const message of history) {
177
+ if (message.role === 'user') lines.push(`User:\n${messageText(message)}`)
178
+ else if (message.role === 'assistant') {
179
+ if (message.content) lines.push(`Assistant:\n${typeof message.content === 'string' ? message.content : messageText(message)}`)
180
+ for (const call of message.tool_calls ?? []) lines.push(`Assistant called ${call.function.name}: ${call.function.arguments}`)
181
+ } else if (message.role === 'tool') {
182
+ const text = String(message.content ?? '')
183
+ lines.push(`Tool result:\n${text.length > SEED_TOOL_CHARS ? `${text.slice(0, SEED_TOOL_CHARS)}\n[clipped]` : text}`)
184
+ }
185
+ }
186
+ let body = lines.join('\n\n')
187
+ if (body.length > SEED_CHARS) body = `[earlier conversation omitted]\n\n${body.slice(-SEED_CHARS)}`
188
+ return body
189
+ }
190
+
191
+ // a conversation Claude Code never saw (another model's, or one pico
192
+ // rewound, steered or compacted) as a transcript it can pick up from
193
+ export function seedText(history) {
194
+ return `[system notification] This conversation began before this Claude Code session started, in pico with another model or an earlier context. Its transcript follows so you can continue it. Treat it as history: do not redo work it shows as done, and do not reply to it directly; the newest messages after it are what to respond to.\n\n<transcript>\n${transcriptText(history)}\n</transcript>`
195
+ }
196
+
197
+ // ---- pico tool schemas to JSON Schema, for the MCP bridge ----
198
+
199
+ function jsonProperty(prop) {
200
+ const out = { type: prop.type }
201
+ if (prop.description) out.description = prop.description
202
+ if (prop.enum) out.enum = prop.enum
203
+ if (prop.items) out.items = jsonProperty(prop.items)
204
+ if (prop.properties) {
205
+ out.properties = Object.fromEntries(Object.entries(prop.properties).map(([key, child]) => [key, jsonProperty(child)]))
206
+ if (prop.required) out.required = prop.required
207
+ }
208
+ return out
209
+ }
210
+
211
+ export function inputSchema(schema = {}) {
212
+ if (schema.type === 'object' && schema.properties) return schema
213
+ const properties = {}
214
+ const required = []
215
+ for (const [key, prop] of Object.entries(schema)) {
216
+ properties[key] = jsonProperty(prop)
217
+ if (!prop.optional) required.push(key)
218
+ }
219
+ return { type: 'object', properties, ...(required.length ? { required } : {}) }
220
+ }
package/src/controller.js CHANGED
@@ -13,6 +13,7 @@ import { deriveState, userEntries, rewindStats } from './derive.js'
13
13
  import { appendPrompt } from './history.js'
14
14
  import { runTurn, summarizeText, compactHistory, compactProgress } from './agent.js'
15
15
  import { createAgentManager } from './agents.js'
16
+ import { engineFor, releaseEngines } from './engines.js'
16
17
  import { automaticPeerName, createPeers } from './peers.js'
17
18
  import { runDeliberation, validateDeliberation } from './deliberation.js'
18
19
  import { deliberationsFromEvents } from './deliberation-history.js'
@@ -345,12 +346,14 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
345
346
  concurrency: 8,
346
347
  defaults: () => ({ model: boot.researchModel }),
347
348
  onChange: bumpActivity,
348
- onCreate: (agent) => persist(makeEvent('agent_start', { agentId: agent.id, description: agent.description, prompt: agent.prompt, model: agent.model, role: agent.role, sessionId: agent.sessionId, sessionFile: agent.sessionFile, tools: agent.tools })),
349
+ onCreate: (agent) => persist(makeEvent('agent_start', { agentId: agent.id, description: agent.description, prompt: agent.prompt, model: agent.model, role: agent.role, sessionId: agent.sessionId, sessionFile: agent.sessionFile, tools: agent.tools, ...(agent.external ? { external: true } : {}) })),
349
350
  onEvent: (agent, event) => {
350
351
  if (['tool_executing', 'tool_complete', 'tool_error', 'usage'].includes(event.type)) persist(makeEvent('agent_event', { agentId: agent.id, event }))
351
352
  },
352
353
  onFinish: (agent) => {
353
354
  persist(makeEvent('agent_result', { agentId: agent.id, result: agent.result, usage: agent.usage, interrupted: agent.status === 'cancelled', error: agent.error }))
355
+ // an external agent's result already went to whatever ran it
356
+ if (agent.external) return
354
357
  noteSystem(`Agent ${agent.id} (${agent.description}) finished with status ${agent.status}. Its result is ready. Call agent_collect with id ${agent.id} before finishing your response.`, { wake: true, agentId: agent.id, sessionId: agent.sessionId, sessionFile: agent.sessionFile })
355
358
  },
356
359
  // this closure outlives any single boot: /connect and project switches
@@ -649,7 +652,7 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
649
652
  const keepFrom = compactionKeepFrom(current, state.model.context)
650
653
  let streamed = ''
651
654
  try {
652
- const raw = await compactRun({
655
+ const raw = await (engineFor(state.model)?.compact ?? compactRun)({
653
656
  history: current.providerHistory,
654
657
  modelName: state.model.name,
655
658
  ...(state.model.provider === 'codex' && { speed: speedApplies() ? state.speed : 'standard' }),
@@ -698,7 +701,7 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
698
701
  }
699
702
 
700
703
  function maybeAutoCompact() {
701
- if (boot.autoCompact === false || state.busy || state.compacting) return
704
+ if (boot.autoCompact === false || engineFor(state.model)?.autoCompact === false || state.busy || state.compacting) return
702
705
  const limit = state.model.context
703
706
  const used = state.derived.lastPromptTokens
704
707
  if (!limit || !used || state.derived.lastPromptModel !== state.model.name) return
@@ -709,6 +712,23 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
709
712
  }
710
713
  }
711
714
 
715
+ // what an engine (engines.js) is told about the session it runs a turn for
716
+ function engineHost(engine) {
717
+ return {
718
+ sessionId: state.session?.id ?? null,
719
+ cwd: boot.cwd,
720
+ env: boot.env,
721
+ contextFiles: boot.startupContext?.files ?? [],
722
+ engineState: savedEngineState(engine),
723
+ // subagents the engine runs itself, shown in the activity list
724
+ subagents: { start: (options) => agents.track({ ...options, sessionId: state.session?.id, sessionFile: state.session?.file }) },
725
+ }
726
+ }
727
+
728
+ function savedEngineState(engine) {
729
+ return state.events.findLast((event) => event.type === 'engine_state' && event.data.engine === engine.name)?.data.state ?? null
730
+ }
731
+
712
732
  async function refreshProjectIndexes() {
713
733
  boot.skills = await createSkillIndex(boot.root, { host: boot.hostSkills ?? [] }).catch(() => boot.skills) ?? boot.skills
714
734
  boot.commands = await createCommandIndex(boot.root).catch(() => boot.commands) ?? boot.commands
@@ -795,7 +815,8 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
795
815
  })
796
816
  } else if (event.type === 'tool_complete' || event.type === 'tool_error') {
797
817
  boot.git.refresh()
798
- const entry = recorder.entries.at(-1)
818
+ // an engine may finish calls out of order, so match by id
819
+ const entry = recorder.entries.findLast((candidate) => candidate.callId === event.call.id)
799
820
  updateOverlay((items) =>
800
821
  items.map((item) =>
801
822
  item.kind === 'tool' && item.callId === event.call.id
@@ -875,9 +896,10 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
875
896
  reDerive()
876
897
  }
877
898
  sendAfterToolTriggered = false
899
+ const engine = engineFor(state.model)
878
900
  let result
879
901
  try {
880
- result = await run({
902
+ result = await (engine?.run ?? run)({
881
903
  history: state.derived.providerHistory,
882
904
  tools,
883
905
  recorder,
@@ -889,6 +911,7 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
889
911
  signal: controller.signal,
890
912
  onStream: streamHandler(recorder, controller),
891
913
  beforeRequest: () => takeTurnNotes(controller.signal),
914
+ ...(engine && { host: engineHost(engine) }),
892
915
  })
893
916
  } catch (err) {
894
917
  abort = null
@@ -911,6 +934,9 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
911
934
  }
912
935
  if (result.usage) persist(makeEvent('usage', { model: state.model.name, usage: result.usage, lastPrompt: result.lastPromptTokens }))
913
936
  if (result.interrupted && !sendAfterToolTriggered) persist(makeEvent('interrupt', {}))
937
+ if (engine && result.engineState && JSON.stringify(result.engineState) !== JSON.stringify(savedEngineState(engine))) {
938
+ persist(makeEvent('engine_state', { engine: engine.name, state: result.engineState }))
939
+ }
914
940
 
915
941
  abort = null
916
942
  state.overlay = []
@@ -1794,6 +1820,7 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
1794
1820
  }
1795
1821
  await agents.collect(agents.list().filter(agent => ['queued', 'running'].includes(agent.status)).map(agent => agent.id))
1796
1822
  await disconnectPeers()
1823
+ if (state.session) releaseEngines(state.session.id)
1797
1824
  await state.session?.flush()
1798
1825
  await boot.mcp.terminateAll()
1799
1826
  boot.git?.dispose?.()
package/src/engines.js ADDED
@@ -0,0 +1,29 @@
1
+ // Turn engines. A turn normally runs through runTurn, which calls the
2
+ // model's provider API with pico's tools and history. An engine replaces
3
+ // that for the models of one provider: it takes the same turn arguments,
4
+ // emits the same stream events and returns provider-shaped messages, so
5
+ // the controller, session log, transcript, peers and tools work the same
6
+ // whichever engine ran the turn.
7
+ //
8
+ // An engine is { name, run, compact, autoCompact?, release? }. `run` also
9
+ // receives `host` (the pico session id, cwd, env, context files, and the
10
+ // engine's own state saved with the session) and may return `engineState`
11
+ // to be saved. `release(sessionId)` frees what an engine holds for a
12
+ // session that has shut down.
13
+
14
+ import { createClaudeCodeEngine } from './claude-code/engine.js'
15
+ import { CLAUDE_CODE_PROVIDER } from './claude-code/models.js'
16
+
17
+ const factories = { [CLAUDE_CODE_PROVIDER]: createClaudeCodeEngine }
18
+ const engines = new Map()
19
+
20
+ export function engineFor(model) {
21
+ const provider = model?.provider
22
+ if (!factories[provider]) return null
23
+ if (!engines.has(provider)) engines.set(provider, factories[provider]())
24
+ return engines.get(provider)
25
+ }
26
+
27
+ export function releaseEngines(sessionId) {
28
+ for (const engine of engines.values()) engine.release?.(sessionId)
29
+ }