picocode-core 0.9.237 → 0.9.239

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.
Files changed (39) hide show
  1. package/README.md +1 -1
  2. package/package.json +1 -1
  3. package/src/acp/README.md +41 -0
  4. package/src/acp/connect.js +108 -0
  5. package/src/acp/engine.js +531 -0
  6. package/src/acp/pico-agent.js +295 -0
  7. package/src/acp/rpc.js +75 -0
  8. package/src/acp/translate.js +163 -0
  9. package/src/antigravity/README.md +42 -0
  10. package/src/antigravity/adapter.js +146 -0
  11. package/src/antigravity/conversations.js +22 -0
  12. package/src/antigravity/engine.js +27 -0
  13. package/src/antigravity/models.js +91 -0
  14. package/src/antigravity/process.js +60 -0
  15. package/src/boot.js +3 -2
  16. package/src/catalog-snapshot.json +1 -1
  17. package/src/claude-code/README.md +14 -20
  18. package/src/claude-code/adapter.js +278 -0
  19. package/src/claude-code/cli.js +6 -2
  20. package/src/claude-code/engine.js +30 -398
  21. package/src/claude-code/models.js +7 -4
  22. package/src/claude-code/token.js +23 -0
  23. package/src/claude-code/translate.js +65 -180
  24. package/src/controller.js +5 -2
  25. package/src/engine-history.js +87 -0
  26. package/src/engines.js +3 -1
  27. package/src/local-session.js +49 -0
  28. package/src/mcp.js +12 -1
  29. package/src/model-runtime.js +94 -0
  30. package/src/openai-auth.js +9 -1
  31. package/src/sign-in/antigravity.js +123 -0
  32. package/src/sign-in/chatgpt.js +32 -0
  33. package/src/sign-in/claude-code.js +73 -0
  34. package/src/sign-in/index.js +32 -0
  35. package/src/sign-in/screen.js +56 -0
  36. package/src/sign-in/supergrok.js +21 -0
  37. package/src/{claude-code/mcp-server.js → tool-bridge-server.js} +3 -3
  38. package/src/{claude-code/bridge.js → tool-bridge.js} +42 -12
  39. package/src/xai-auth.js +6 -1
@@ -0,0 +1,531 @@
1
+ // The turn engine for every agent pico reaches over ACP (engines.js):
2
+ // Claude Code and Antigravity, through their adapters. pico's controller
3
+ // hands it a turn exactly as it would hand pico's own runTurn one, and it
4
+ // plays the turn through the agent's ACP session instead of calling a
5
+ // model API.
6
+ //
7
+ // pico's session log stays the source of truth, and the agent's
8
+ // conversation is a cache of it (engine-history.js): when the history the
9
+ // controller passes in is what the agent last saw, only the new messages
10
+ // are sent; when it is not, a fresh session starts with the earlier
11
+ // conversation as a transcript. Which agent session holds which history is
12
+ // returned as `engineState`, which the controller saves with the session
13
+ // so a restart resumes it, and a forked pico session forks it where the
14
+ // agent can.
15
+
16
+ import { existsSync, readFileSync } from 'node:fs'
17
+ import { hydrateImages } from '../agent.js'
18
+ import { makeDiff } from '../tools/diff.js'
19
+ import { makeWriteEdit } from '../reversible-edit.js'
20
+ import { createBridge } from '../tool-bridge.js'
21
+ import { initialize } from './connect.js'
22
+ import { fingerprint, seedText, splitTurn, transcriptText, unseen } from '../engine-history.js'
23
+ import { allowOption, callPath, changesFile, chosenOption, diffsOf, modelOption, picoMeta, questionOf, resultText, thoughtOption, thoughtValue, toolOf, usageOf, userBlocks } from './translate.js'
24
+
25
+ const IDLE_MS = 10 * 60 * 1000
26
+ // how long a cancelled turn may take to wind down before the agent is
27
+ // stopped instead
28
+ const CANCEL_GRACE_MS = 15000
29
+ // how long a call through the bridge waits for the agent to announce it
30
+ const CLAIM_WAIT_MS = 2000
31
+
32
+ // pico's tools an agent with its own coding tools does not need; offering
33
+ // both would only make the model choose between equivalent tools. A host
34
+ // that decides this itself passes its own list (boot.engineOwnTools)
35
+ export const COVERED_TOOLS = new Set([
36
+ 'read', 'write', 'edit', 'bash', 'glob', 'grep', 'view', 'shell_output', 'shell_kill', 'tool_result',
37
+ 'skill',
38
+ ])
39
+
40
+ export const HOST_NOTE = `You are running inside pico, an agent runtime, possibly within a desktop workspace where several agent sessions work side by side. Besides your own tools, the host's tools are available from the MCP server named pico: ask_user asks the user questions, 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.`
41
+
42
+ // ACP's answer that the agent has no sign-in to use
43
+ export const isSignInRequired = (error) => error?.code === -32000 || /^No browser is available here/.test(String(error?.message ?? ''))
44
+
45
+ // pico's tool bridge as ACP names an MCP server
46
+ const acpServer = ({ name, command, args, env }) => ({ name, command, args, env: Object.entries(env).map(([key, value]) => ({ name: key, value })) })
47
+
48
+ const readText = (path) => {
49
+ try { return existsSync(path) ? readFileSync(path, 'utf8') : null } catch { return null }
50
+ }
51
+
52
+ // `provider` names the models this engine runs (`<provider>/<model>`),
53
+ // `label` the agent as the person knows it, `connect(handlers)` opens a
54
+ // connection to it, `systemPrompt(host)` is what pico adds to the agent's
55
+ // own instructions, `covered` the pico tools the agent has its own of, and
56
+ // `offer(tool)` how a pico tool is described to it
57
+ export function createAcpEngine({ provider, label, connect, systemPrompt, covered: ownTools = COVERED_TOOLS, offer = (tool) => tool, idleMs = IDLE_MS, bridge = createBridge }) {
58
+ const signInRequired = `${label} is not signed in on this machine`
59
+ const local = (name) => (String(name).startsWith(`${provider}/`) ? name.slice(provider.length + 1) : name)
60
+ // per pico session: its connection, bridge, agent session, and which
61
+ // history that session holds
62
+ const sessions = new Map()
63
+
64
+ function stop(entry) {
65
+ clearTimeout(entry.idle)
66
+ entry.conn?.close()
67
+ entry.conn = null
68
+ entry.bridge?.close().catch(() => {})
69
+ entry.bridge = null
70
+ }
71
+
72
+ // a connection with an agent session in it: the saved one resumed, or
73
+ // forked for a forked pico session, where the agent can; else a new one
74
+ async function start(entry, { host, resume, fork }) {
75
+ entry.bridge = await bridge()
76
+ // a connection that was replaced may still speak after the next one
77
+ // opens; only the current one reaches the turn
78
+ const conn = connect({
79
+ cwd: host.cwd,
80
+ env: host.env,
81
+ onNotification: (method, params) => { if (entry.conn === conn) entry.onNotification?.(method, params) },
82
+ onRequest: async (method, params) => {
83
+ if (entry.conn === conn && entry.onRequest) return entry.onRequest(method, params)
84
+ if (method === 'session/request_permission') return { outcome: { outcome: 'cancelled' } }
85
+ throw Object.assign(new Error(`pico does not handle ${method}`), { code: -32601 })
86
+ },
87
+ onExit: (exit) => {
88
+ if (entry.conn !== conn) return
89
+ entry.conn = null
90
+ entry.lastExit = exit
91
+ entry.onExit?.(exit)
92
+ },
93
+ })
94
+ entry.conn = conn
95
+ const hello = await initialize(conn)
96
+ const can = hello?.agentCapabilities?.sessionCapabilities ?? {}
97
+ const params = { cwd: host.cwd, mcpServers: [acpServer(entry.bridge.server())], _meta: { pico: { systemPrompt: systemPrompt(host) } } }
98
+ const refused = (error) => { throw isSignInRequired(error) ? new Error(signInRequired) : error }
99
+ let session = null
100
+ let resumed = false
101
+ if (resume && fork && can.fork) session = await conn.request('session/fork', { sessionId: resume, ...params }).catch((error) => { if (isSignInRequired(error)) refused(error); return null })
102
+ else if (resume && !fork && can.resume) {
103
+ session = await conn.request('session/resume', { sessionId: resume, ...params }).catch((error) => { if (isSignInRequired(error)) refused(error); return null })
104
+ if (session) session.sessionId ??= resume
105
+ }
106
+ if (session) resumed = true
107
+ session ??= await conn.request('session/new', params).catch(refused)
108
+ entry.sessionId = session.sessionId
109
+ entry.configOptions = session.configOptions ?? []
110
+ return { resumed }
111
+ }
112
+
113
+ // the model and thinking level asked for, set on the session where they differ
114
+ async function configure(entry, model, effort) {
115
+ const set = async (option, value) => {
116
+ if (!option || value == null || String(option.currentValue) === String(value)) return
117
+ const reply = await entry.conn.request('session/set_config_option', { sessionId: entry.sessionId, configId: option.id, value })
118
+ entry.configOptions = reply?.configOptions ?? entry.configOptions.map((o) => (o.id === option.id ? { ...o, currentValue: value } : o))
119
+ }
120
+ // a resumed session may not report its options; the model is still set by its usual name
121
+ await set(modelOption(entry.configOptions) ?? (entry.configOptions.length ? null : { id: 'model' }), model)
122
+ await set(thoughtOption(entry.configOptions), thoughtValue(entry.configOptions, effort))
123
+ }
124
+
125
+ async function run({ history, tools, recorder, modelName, effort, signal, onStream = () => {}, beforeRequest, host = {} }) {
126
+ const key = host.sessionId ?? 'ephemeral'
127
+ const entry = sessions.get(key) ?? { sessionId: null, owner: key, synced: null }
128
+ sessions.set(key, entry)
129
+ clearTimeout(entry.idle)
130
+ const model = local(modelName)
131
+
132
+ // what the agent already holds: this connection's session, or the one
133
+ // the controller saved, as long as the history has not moved under it
134
+ const saved = host.engineState ? { ...host.engineState, sessionId: host.engineState.sessionId ?? host.engineState.claudeSessionId } : null
135
+ const known = entry.sessionId ? entry : saved?.sessionId ? saved : null
136
+ const fresh = known ? unseen(history, known.synced) : null
137
+ if (entry.conn && !fresh) stop(entry)
138
+ let input = fresh
139
+ let seed = null
140
+ const failed = (error) => ({ messages: [], usage: null, lastPromptTokens: 0, interrupted: true, stalled: false, error: String(error.message || error) })
141
+
142
+ if (!entry.conn) {
143
+ entry.lastExit = null
144
+ try {
145
+ const { resumed } = await start(entry, { host, resume: fresh ? known.sessionId : null, fork: !!fresh && known.owner !== key })
146
+ if (!resumed) {
147
+ const turn = splitTurn(history)
148
+ input = turn.input
149
+ seed = turn.prior.length ? seedText(turn.prior, label) : null
150
+ }
151
+ } catch (error) {
152
+ stop(entry)
153
+ entry.sessionId = null
154
+ return failed(entry.lastExit?.error ?? error)
155
+ }
156
+ entry.owner = key
157
+ }
158
+ try {
159
+ await configure(entry, model, effort)
160
+ } catch (error) {
161
+ return failed(new Error(`${label} could not switch to ${model}: ${error.message}`))
162
+ }
163
+
164
+ const content = []
165
+ if (seed) content.push({ type: 'text', text: seed })
166
+ for (const message of await hydrateImages(input)) content.push(...userBlocks(message))
167
+ if (!content.length) content.push({ type: 'text', text: '[system notification] continue.' })
168
+
169
+ // the turn as rounds: what the model said, the calls it made then, and
170
+ // their results. A round ends once a result arrives, and the next text
171
+ // or call begins another, so every call's result follows the message
172
+ // that made it
173
+ const rounds = []
174
+ const calls = new Map()
175
+ let usage = null
176
+ let lastPrompt = 0
177
+ let interrupted = false
178
+ let error = null
179
+ const round = () => {
180
+ const last = rounds.at(-1)
181
+ if (last && !last.notes && !last.answered) return last
182
+ const next = { text: '', calls: [], answered: false }
183
+ rounds.push(next)
184
+ return next
185
+ }
186
+
187
+ // offered: pico's tools the agent has no version of its own. A call
188
+ // through the bridge lands on the call the agent announced for it
189
+ // (same name, oldest first), which may arrive just after the call itself
190
+ const covered = host.ownTools ? new Set(host.ownTools) : ownTools
191
+ const offered = tools.filter((tool) => !covered.has(tool.name)).map(offer)
192
+ const unclaimed = []
193
+ const claimWaiters = new Set()
194
+ entry.bridge.setTurn(offered, async (name) => {
195
+ const take = () => {
196
+ const at = unclaimed.findIndex((call) => call.name === name)
197
+ return at >= 0 ? unclaimed.splice(at, 1)[0] : null
198
+ }
199
+ let call = take()
200
+ if (!call) {
201
+ await new Promise((resolve) => {
202
+ const waiter = () => { if ((call = take())) { claimWaiters.delete(waiter); resolve() } }
203
+ claimWaiters.add(waiter)
204
+ setTimeout(() => { claimWaiters.delete(waiter); resolve() }, CLAIM_WAIT_MS)
205
+ })
206
+ }
207
+ recorder.currentCall = call ? { id: call.id } : null
208
+ })
209
+
210
+ // the agent's subagents, by the id of the call that started each,
211
+ // shown in pico's activity list while they work, with their own
212
+ // traffic; a subagent may start subagents of its own
213
+ const subagents = new Map()
214
+ const startSubagent = (update, spec) => {
215
+ if (!host.subagents) return
216
+ const handle = host.subagents.start({ description: spec.description, prompt: spec.prompt ?? '', model: spec.model ? `${provider}/${spec.model}` : `${provider}/${model}`, callId: update.toolCallId })
217
+ subagents.set(update.toolCallId, { handle, said: '' })
218
+ }
219
+ const finishSubagent = (id, { failed: broke, text }) => {
220
+ const sub = subagents.get(id)
221
+ if (!sub) return
222
+ subagents.delete(id)
223
+ // what it found is its own last message, as it wrote it; the call's result only when it wrote none
224
+ sub.handle.finish(broke ? { error: text || 'failed', interrupted } : { result: sub.said.trim() ? sub.said : text })
225
+ }
226
+ const subCalls = new Map()
227
+ const onSubagentUpdate = (sub, update) => {
228
+ if (update.sessionUpdate === 'agent_message_chunk' && update.content?.type === 'text') {
229
+ sub.said += update.content.text
230
+ sub.handle.event({ type: 'content', content: update.content.text })
231
+ } else if (update.sessionUpdate === 'tool_call' && !subCalls.has(update.toolCallId)) {
232
+ const { name, args, subagent } = toolOf(update, host.cwd)
233
+ subCalls.set(update.toolCallId, update)
234
+ sub.said = ''
235
+ sub.handle.event({ type: 'tool_executing', call: { id: update.toolCallId, type: 'function', function: { name, arguments: JSON.stringify(args) } }, at: Date.now() })
236
+ if (subagent) startSubagent(update, subagent)
237
+ }
238
+ if ((update.sessionUpdate === 'tool_call' || update.sessionUpdate === 'tool_call_update') && (update.status === 'completed' || update.status === 'failed')) {
239
+ const merged = { ...subCalls.get(update.toolCallId), ...update }
240
+ subCalls.delete(update.toolCallId)
241
+ const text = resultText(merged)
242
+ sub.handle.event(update.status === 'failed' ? { type: 'tool_error', call: { id: update.toolCallId }, error: text } : { type: 'tool_complete', call: { id: update.toolCallId }, result: text })
243
+ finishSubagent(update.toolCallId, { failed: update.status === 'failed', text })
244
+ }
245
+ }
246
+
247
+ const announce = (update) => {
248
+ const { name, args, bridged, subagent } = toolOf(update, host.cwd)
249
+ const call = { id: update.toolCallId, type: 'function', function: { name, arguments: JSON.stringify(args) } }
250
+ const path = callPath(update)
251
+ const state = { id: update.toolCallId, name, args, bridged: !!bridged, call, startedAt: Date.now(), path: null, before: null, update }
252
+ if (path && changesFile(name)) { state.path = path; state.before = readText(path) }
253
+ calls.set(update.toolCallId, state)
254
+ round().calls.push(state)
255
+ if (bridged) { unclaimed.push({ id: update.toolCallId, name }); for (const waiter of claimWaiters) waiter() }
256
+ onStream({ type: 'tool_calls_ready', calls: [call] })
257
+ onStream({ type: 'tool_executing', call })
258
+ if (subagent) startSubagent(update, subagent)
259
+ }
260
+
261
+ // the change a finished call made to a file: the adapter's whole-file
262
+ // diff where it has one, else the file as it was when the call was
263
+ // announced and as it is now, else the snippets the agent reported
264
+ const fileChange = (state, merged, shown) => {
265
+ const [diff] = diffsOf(merged)
266
+ if (picoMeta(merged).wholeFile && diff && typeof diff.newText === 'string') {
267
+ const before = diff.oldText ?? null
268
+ return { diff: makeDiff(shown, before ?? '', diff.newText), revert: makeWriteEdit(diff.path, before ?? '', diff.newText, before !== null), created: before === null }
269
+ }
270
+ const path = state.path ?? callPath(merged)
271
+ if (state.path) {
272
+ const after = readText(path)
273
+ if (after !== state.before) return { diff: makeDiff(shown, state.before ?? '', after ?? ''), ...(after !== null ? { revert: makeWriteEdit(path, state.before ?? '', after, state.before !== null) } : {}), created: state.before === null }
274
+ }
275
+ return diff ? { diff: makeDiff(shown, diff.oldText ?? '', diff.newText ?? '') } : null
276
+ }
277
+
278
+ // a call the agent finished: its result into the history, and its row
279
+ const settle = (state, update) => {
280
+ calls.delete(state.id)
281
+ const merged = { ...state.update, ...update, _meta: { ...state.update._meta, ...update._meta, pico: { ...picoMeta(state.update), ...picoMeta(update) } } }
282
+ const broke = merged.status === 'failed'
283
+ const text = resultText(merged)
284
+ state.result = broke ? `Error: ${text || 'failed'}` : text
285
+ const owner = rounds.find((r) => r.calls.includes(state))
286
+ if (owner) owner.answered = true
287
+ const at = unclaimed.findIndex((call) => call.id === state.id)
288
+ if (at >= 0) unclaimed.splice(at, 1)
289
+ finishSubagent(state.id, { failed: broke, text })
290
+ if (!state.bridged || !recorder.entries.some((candidate) => candidate.callId === state.id)) {
291
+ const row = {
292
+ callId: state.id,
293
+ name: state.name,
294
+ args: state.args,
295
+ title: typeof state.args.path === 'string' ? state.args.path : merged.title,
296
+ description: state.args.description,
297
+ status: broke ? (interrupted ? 'interrupted' : 'error') : 'done',
298
+ durationMs: Date.now() - state.startedAt,
299
+ fullOutput: text,
300
+ }
301
+ if (broke && !interrupted) row.error = text || 'failed'
302
+ if (!broke && changesFile(state.name)) {
303
+ const change = fileChange(state, merged, typeof state.args.path === 'string' ? state.args.path : callPath(merged))
304
+ if (change?.diff) row.diff = change.diff
305
+ if (change?.revert) row.revert = change.revert
306
+ if (change?.created) row.created = true
307
+ }
308
+ recorder.entries.push(row)
309
+ }
310
+ onStream({ type: broke ? 'tool_error' : 'tool_complete', call: state.call, ...(broke ? { error: text } : { result: text }) })
311
+ }
312
+
313
+ // notes that arrived mid-turn reach the agent between tool rounds, as
314
+ // a prompt sent while the turn runs, which the agent folds into it
315
+ const prompts = []
316
+ let delivery = null
317
+ const deliverNotes = () => {
318
+ if (interrupted || delivery || !beforeRequest || calls.size || !entry.conn) return
319
+ delivery = (async () => {
320
+ const notes = await beforeRequest()
321
+ if (!notes?.length || interrupted || !entry.conn) return
322
+ rounds.push({ notes })
323
+ prompts.push(entry.conn.request('session/prompt', { sessionId: entry.sessionId, prompt: (await hydrateImages(notes)).flatMap(userBlocks) }))
324
+ })().catch(() => {}).finally(() => { delivery = null })
325
+ }
326
+
327
+ entry.onNotification = (method, params) => {
328
+ if (method !== 'session/update' || params.sessionId !== entry.sessionId) return
329
+ const update = params.update ?? {}
330
+ const parent = picoMeta(update).parentToolCallId
331
+ if (parent && subagents.has(parent)) return onSubagentUpdate(subagents.get(parent), update)
332
+ if (parent) return
333
+ switch (update.sessionUpdate) {
334
+ case 'agent_message_chunk':
335
+ if (update.content?.type === 'text' && update.content.text) { round().text += update.content.text; onStream({ type: 'content', content: update.content.text }) }
336
+ break
337
+ case 'agent_thought_chunk':
338
+ if (update.content?.type === 'text' && update.content.text) onStream({ type: 'thinking', content: update.content.text })
339
+ break
340
+ case 'tool_call':
341
+ if (!calls.has(update.toolCallId)) announce(update)
342
+ else calls.get(update.toolCallId).update = { ...calls.get(update.toolCallId).update, ...update }
343
+ if (update.status === 'completed' || update.status === 'failed') { settle(calls.get(update.toolCallId), update); deliverNotes() }
344
+ break
345
+ case 'tool_call_update': {
346
+ const state = calls.get(update.toolCallId)
347
+ if (!state) break
348
+ state.update = { ...state.update, ...update }
349
+ if (!state.path && changesFile(state.name) && callPath(update)) { state.path = callPath(update); state.before = readText(state.path) }
350
+ if (update.status === 'completed' || update.status === 'failed') { settle(state, update); deliverNotes() }
351
+ break
352
+ }
353
+ case 'usage_update':
354
+ if (update.used) lastPrompt = update.used
355
+ if (picoMeta(update).usage) { usage = picoMeta(update).usage; onStream({ type: 'usage', usage }) }
356
+ break
357
+ case 'config_option_update':
358
+ if (Array.isArray(update.configOptions)) entry.configOptions = update.configOptions
359
+ break
360
+ }
361
+ }
362
+
363
+ // the agent asks for nothing pico would not allow; it asks the person
364
+ // only what it means to ask them
365
+ const askTool = tools.find((tool) => tool.name === 'ask_user')
366
+ entry.onRequest = async (method, params) => {
367
+ if (method !== 'session/request_permission') throw Object.assign(new Error(`pico does not handle ${method}`), { code: -32601 })
368
+ const options = params.options ?? []
369
+ if (picoMeta(params).question) {
370
+ if (!askTool || interrupted) return { outcome: { outcome: 'cancelled' } }
371
+ recorder.currentCall = { id: params.toolCall?.toolCallId }
372
+ const answer = await askTool.execute({ questions: [questionOf(params)] }).catch(() => null)
373
+ const chosen = chosenOption(answer, options)
374
+ return chosen ? { outcome: { outcome: 'selected', optionId: chosen.optionId } } : { outcome: { outcome: 'cancelled' } }
375
+ }
376
+ const allow = allowOption(options)
377
+ return allow ? { outcome: { outcome: 'selected', optionId: allow.optionId } } : { outcome: { outcome: 'cancelled' } }
378
+ }
379
+
380
+ let graceTimer = null
381
+ let cleanupAbort = () => {}
382
+ const ended = new Promise((resolve) => {
383
+ entry.onExit = (exit) => {
384
+ if (!interrupted) error = exit.error?.message || exit.stderr || `${label} stopped`
385
+ resolve()
386
+ }
387
+ const onAbort = () => {
388
+ interrupted = true
389
+ entry.conn?.notify('session/cancel', { sessionId: entry.sessionId })
390
+ graceTimer = setTimeout(() => { stop(entry); resolve() }, CANCEL_GRACE_MS)
391
+ }
392
+ if (signal?.aborted) onAbort()
393
+ else signal?.addEventListener('abort', onAbort, { once: true })
394
+ cleanupAbort = () => signal?.removeEventListener('abort', onAbort)
395
+ })
396
+
397
+ // a reply's usage counts in full only where the agent did not already
398
+ // report it as it went
399
+ let reported = null
400
+ const settlePrompt = (reply) => {
401
+ if (reply?.usage) {
402
+ const next = usageOf(reply.usage)
403
+ reported = reported ? Object.fromEntries(Object.keys(next).map((k) => [k, reported[k] + next[k]])) : next
404
+ if (!lastPrompt) lastPrompt = next.promptTokens
405
+ }
406
+ if (reply?.stopReason === 'refusal' && !interrupted) error = `${label} refused to go on; the plan's usage limit may have been reached`
407
+ }
408
+ const promptFailed = (failure) => { if (!interrupted) error = isSignInRequired(failure) ? signInRequired : String(failure.message || failure) }
409
+
410
+ // the turn ends once the agent has answered every prompt it was sent
411
+ prompts.push(entry.conn.request('session/prompt', { sessionId: entry.sessionId, prompt: content }))
412
+ const allAnswered = (async () => {
413
+ let answered = 0
414
+ while (answered < prompts.length || delivery) {
415
+ if (answered < prompts.length) await prompts[answered++].then(settlePrompt, promptFailed)
416
+ else await delivery
417
+ }
418
+ })()
419
+ await Promise.race([allAnswered, ended])
420
+ clearTimeout(graceTimer)
421
+ cleanupAbort()
422
+ entry.onNotification = null
423
+ entry.onRequest = null
424
+ entry.onExit = null
425
+ for (const waiter of claimWaiters) waiter()
426
+ for (const sub of subagents.values()) sub.handle.finish({ interrupted: true })
427
+ usage = reported ?? usage
428
+ if (usage) onStream({ type: 'usage', usage })
429
+
430
+ // the turn as pico history: each round's message, then its calls'
431
+ // results; a call cut off by an interrupt still needs one, or the
432
+ // history is invalid for whichever model reads it next
433
+ const collected = []
434
+ for (const r of rounds) {
435
+ if (r.notes) { collected.push(...r.notes); continue }
436
+ if (!r.text && !r.calls.length) continue
437
+ collected.push({ role: 'assistant', content: r.text, ...(r.calls.length ? { tool_calls: r.calls.map((c) => c.call) } : {}) })
438
+ for (const c of r.calls) collected.push({ role: 'tool', tool_call_id: c.id, content: c.result ?? '[interrupted before it finished]' })
439
+ }
440
+
441
+ if (entry.conn) {
442
+ entry.synced = fingerprint([...history, ...collected])
443
+ entry.idle = setTimeout(() => stop(entry), idleMs)
444
+ entry.idle.unref?.()
445
+ } else {
446
+ // the agent stopped: what it kept may not match, so the next turn
447
+ // starts over from pico's history
448
+ entry.sessionId = null
449
+ entry.synced = null
450
+ }
451
+ return {
452
+ messages: collected,
453
+ usage,
454
+ lastPromptTokens: lastPrompt,
455
+ interrupted: interrupted || !!error,
456
+ stalled: false,
457
+ ...(error ? { error } : {}),
458
+ engineState: { sessionId: entry.sessionId, owner: entry.owner, synced: entry.synced },
459
+ }
460
+ }
461
+
462
+ // one question answered as text by a session of its own, with no tool
463
+ // allowed and nothing kept afterward; `system` is added to the agent's
464
+ // own instructions
465
+ async function ask({ modelName, system = '', prompt, effort = null, signal, onStream = () => {} }) {
466
+ let text = ''
467
+ let sessionId = null
468
+ let exit = null
469
+ const conn = connect({
470
+ cwd: process.cwd(),
471
+ onNotification: (method, params) => {
472
+ const update = params.update ?? {}
473
+ if (method === 'session/update' && params.sessionId === sessionId && update.sessionUpdate === 'agent_message_chunk' && update.content?.type === 'text' && !picoMeta(update).parentToolCallId) {
474
+ text += update.content.text
475
+ onStream({ type: 'content', content: update.content.text })
476
+ }
477
+ },
478
+ onRequest: async (method) => {
479
+ if (method === 'session/request_permission') return { outcome: { outcome: 'cancelled' } }
480
+ throw Object.assign(new Error(`pico does not handle ${method}`), { code: -32601 })
481
+ },
482
+ onExit: (e) => { exit = e },
483
+ })
484
+ const onAbort = () => conn.close()
485
+ signal?.addEventListener('abort', onAbort, { once: true })
486
+ try {
487
+ await initialize(conn)
488
+ const session = await conn.request('session/new', { cwd: process.cwd(), mcpServers: [], _meta: { pico: { ephemeral: true, ...(system ? { systemPrompt: system } : {}) } } })
489
+ .catch((error) => { throw isSignInRequired(error) ? new Error(signInRequired) : error })
490
+ sessionId = session.sessionId
491
+ await configure({ conn, sessionId, configOptions: session.configOptions ?? [] }, local(modelName), effort)
492
+ await conn.request('session/prompt', { sessionId, prompt: [{ type: 'text', text: prompt }] })
493
+ } catch (error) {
494
+ if (signal?.aborted) throw new Error('cancelled')
495
+ throw exit?.error ?? error
496
+ } finally {
497
+ signal?.removeEventListener('abort', onAbort)
498
+ if (sessionId) await conn.request('session/close', { sessionId }).catch(() => {})
499
+ conn.close()
500
+ }
501
+ return text.trim()
502
+ }
503
+
504
+ // pico's compaction, done by the same model: one bare run that reads the
505
+ // conversation and writes the summary
506
+ function compact({ history, modelName, prompt, signal, onStream }) {
507
+ return ask({ modelName, prompt: `<transcript>\n${transcriptText(history)}\n</transcript>\n\n${prompt}`, signal, onStream })
508
+ .catch((error) => { throw signal?.aborted ? new Error('compaction cancelled') : error })
509
+ }
510
+
511
+ return {
512
+ name: provider,
513
+ // these agents compact their own context as it fills; pico compacting
514
+ // too would only restart their session from a summary
515
+ autoCompact: false,
516
+ run,
517
+ ask,
518
+ compact,
519
+ // the pico session is done with: its connection and bridge go
520
+ release(sessionId) {
521
+ const entry = sessions.get(sessionId)
522
+ if (!entry) return
523
+ stop(entry)
524
+ sessions.delete(sessionId)
525
+ },
526
+ releaseAll() {
527
+ for (const entry of sessions.values()) stop(entry)
528
+ sessions.clear()
529
+ },
530
+ }
531
+ }