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
@@ -1,417 +1,49 @@
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.
1
+ // Claude Code as pico's sessions run it: the ACP engine (../acp/engine.js)
2
+ // over the Claude Code adapter (adapter.js), in this process.
13
3
 
14
- import { existsSync, readFileSync } from 'node:fs'
15
4
  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
5
+ import { connectAgent } from '../acp/connect.js'
6
+ import { createAcpEngine } from '../acp/engine.js'
7
+ import { createClaudeCodeAgent } from './adapter.js'
8
+ import { CLAUDE_CODE_PROVIDER } from './models.js'
28
9
 
29
10
  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
11
 
31
- function systemPrompt(contextFiles = [], memoryIndexText = '') {
32
- // Claude Code reads CLAUDE.md files itself; any other instructions pico
33
- // would give its own models (AGENTS.md) are passed along
12
+ // Claude Code reads CLAUDE.md files itself; any other instructions pico
13
+ // would give its own models (AGENTS.md) are passed along. pico's memories
14
+ // stand in for Claude Code's own, which is switched off
15
+ export function systemPrompt({ contextFiles = [], memoryIndexText = '' } = {}) {
34
16
  const files = contextFiles.filter((file) => basename(file.path) !== 'CLAUDE.md' && file.content?.trim())
35
17
  const parts = [HOST_NOTE]
36
- // pico's memories stand in for Claude Code's own, which is switched off;
37
- // they are saved and loaded with mcp__pico__remember and recall
38
18
  if (memoryIndexText) parts.push(memoryIndexText.replace(/\bthe (remember|recall) tool\b/g, 'the mcp__pico__$1 tool'))
39
19
  if (files.length) parts.push(`Project instructions:\n\n${files.map((file) => `<file path="${file.path}">\n${file.content.trim()}\n</file>`).join('\n\n')}`)
40
20
  return parts.join('\n\n')
41
21
  }
42
22
 
43
- // the trailing user messages of `history` that Claude Code has not seen,
44
- // given the fingerprint of what it has: null when the history diverged
45
- function unseen(history, synced) {
46
- if (!synced) return null
47
- for (let at = history.length; at >= 0; at--) {
48
- if (at < history.length && history[at].role !== 'user') break
49
- if (fingerprint(history.slice(0, at)) === synced) return history.slice(at)
50
- }
51
- return null
52
- }
23
+ // pico's tools Claude Code has its own version of, its subagents included
24
+ export const COVERED_TOOLS = new Set([
25
+ 'read', 'write', 'edit', 'bash', 'glob', 'grep', 'view', 'shell_output', 'shell_kill', 'tool_result',
26
+ 'agent_start', 'agent_list', 'agent_collect', 'agent_cancel',
27
+ 'skill',
28
+ ])
53
29
 
54
30
  // what Claude Code is told about a pico tool that overlaps one of its own: pico's subagents run on other models, so
55
31
  // Claude reaches for them only for that, and keeps its own Task tool for Claude's work
56
32
  const FOR_CLAUDE = {
57
33
  agent_start: 'For a worker on a model other than Claude, such as another provider\'s, when the user asked for one or a task needs it. For a subagent on Claude, use your own Task tool instead. ',
58
34
  }
59
- const forClaude = (tool) => (FOR_CLAUDE[tool.name] ? { ...tool, description: FOR_CLAUDE[tool.name] + tool.description } : tool)
60
-
61
- export function createClaudeCodeEngine({ command = claudeCommand(), idleMs = IDLE_MS, spawn = spawnClaude, bridge = createBridge } = {}) {
62
- // per pico session: its process, bridge, and which Claude session holds
63
- // which history
64
- const sessions = new Map()
65
-
66
- function stop(entry) {
67
- clearTimeout(entry.idle)
68
- entry.proc?.close()
69
- entry.proc = null
70
- entry.bridge?.close().catch(() => {})
71
- entry.bridge = null
72
- }
73
-
74
- async function start(entry, { cwd, env, model, effort, resume, fork, contextFiles, memoryIndexText }) {
75
- entry.bridge = await bridge()
76
- entry.model = model
77
- entry.effort = effort
78
- // a process that was replaced still exits, and may still speak, after
79
- // the next one starts; only the current process reaches the turn
80
- const proc = spawn({
81
- command,
82
- cwd,
83
- env,
84
- model,
85
- effort,
86
- resume,
87
- fork,
88
- mcpConfig: entry.bridge.mcpConfig(),
89
- appendSystemPrompt: systemPrompt(contextFiles, memoryIndexText),
90
- onMessage: (message) => { if (entry.proc === proc) entry.onMessage?.(message) },
91
- onExit: (exit) => {
92
- if (entry.proc !== proc) return
93
- entry.proc = null
94
- entry.lastExit = exit
95
- entry.onExit?.(exit)
96
- },
97
- })
98
- entry.proc = proc
99
- }
100
-
101
- async function run({ history, tools, recorder, modelName, effort, signal, onStream = () => {}, beforeRequest, host = {} }) {
102
- const key = host.sessionId ?? 'ephemeral'
103
- const entry = sessions.get(key) ?? { claudeSessionId: null, owner: key, synced: null }
104
- sessions.set(key, entry)
105
- clearTimeout(entry.idle)
106
- const model = cliModel(modelName)
107
- const level = effort && effort !== 'auto' ? effort : null
108
-
109
- // what Claude Code already holds: this process's session, or the one
110
- // the controller saved, as long as the history has not moved under it
111
- const known = entry.claudeSessionId ? entry : host.engineState?.claudeSessionId ? host.engineState : null
112
- const fresh = known ? unseen(history, known.synced) : null
113
- if (entry.proc && (!fresh || entry.model !== model || entry.effort !== level)) stop(entry)
114
- let seed = null
115
- let input = fresh
116
- if (!entry.proc) {
117
- if (!fresh) {
118
- const turn = splitTurn(history)
119
- input = turn.input
120
- if (turn.prior.length) seed = seedText(turn.prior)
121
- }
122
- }
123
-
124
- const content = []
125
- if (seed) content.push({ type: 'text', text: seed })
126
- for (const message of await hydrateImages(input)) content.push(...userBlocks(message))
127
- if (!content.length) content.push({ type: 'text', text: '[system notification] continue.' })
128
-
129
- if (!entry.proc) {
130
- entry.lastExit = null
131
- try {
132
- 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, memoryIndexText: host.memoryIndexText })
133
- } catch (error) {
134
- stop(entry)
135
- return { messages: [], usage: null, lastPromptTokens: 0, interrupted: true, stalled: false, error: String(error.message || error) }
136
- }
137
- if (!fresh) entry.claudeSessionId = null
138
- entry.owner = key
139
- }
140
-
141
- const collected = []
142
- const uses = new Map()
143
- const unclaimed = []
144
- const responses = new Map()
145
- let assistant = null
146
- let usage = emptyUsage()
147
- let lastPrompt = 0
148
- let interrupted = false
149
- let error = null
150
- let graceTimer = null
151
-
152
- const flushAssistant = () => {
153
- if (!assistant) return
154
- if (assistant.text || assistant.calls.length) collected.push({ role: 'assistant', content: assistant.text, ...(assistant.calls.length ? { tool_calls: assistant.calls } : {}) })
155
- assistant = null
156
- }
157
-
158
- // a response's usage arrives in parts: input at its start, output
159
- // growing until its end
160
- const raws = new Map()
161
- let streaming = null
162
- const countUsage = (id, raw) => {
163
- if (!id || !raw) return
164
- raws.set(id, { ...raws.get(id), ...raw })
165
- responses.set(id, usageOf(raws.get(id)))
166
- usage = [...responses.values()].reduce(addUsage, emptyUsage())
167
- lastPrompt = responses.get(id).promptTokens
168
- onStream({ type: 'usage', usage })
169
- }
170
-
171
- // Claude Code's messages are handled one at a time, in order
172
- let chain = Promise.resolve()
173
-
174
- // Claude's subagents, by the id of the Task call that started each,
175
- // shown in pico's activity list as they work. A subagent's own traffic
176
- // carries that id as its parent; it may start subagents of its own
177
- const subagents = new Map()
178
- const startSubagent = (block) => {
179
- if (!host.subagents || !SUBAGENT_TOOLS.has(block.name)) return
180
- // a subagent runs on the session's model unless its call names another
181
- // the Task call that started it goes with it, so a host can show the subagent where the call is
182
- const handle = host.subagents.start({ description: block.input?.description, prompt: block.input?.prompt ?? '', model: `${CLAUDE_CODE_PROVIDER}/${block.input?.model ?? model}`, callId: block.id })
183
- subagents.set(block.id, { handle, said: '' })
184
- }
185
- // `extra` is the structured result, whose report is free of the frame
186
- // Claude Code wraps it in for the model
187
- const finishSubagent = (block, extra) => {
188
- const sub = subagents.get(block.tool_use_id)
189
- if (!sub) return
190
- subagents.delete(block.tool_use_id)
191
- const text = Array.isArray(extra?.content) ? toolResultText(extra.content) : toolResultText(block.content)
192
- // what it found is its own last message, as it wrote it; the call's result only when it wrote none
193
- sub.handle.finish(block.is_error ? { error: text || 'failed', interrupted } : { result: sub.said.trim() ? sub.said : text })
194
- }
195
- const onSubagent = (message) => {
196
- const sub = subagents.get(message.parent_tool_use_id)
197
- if (!sub) return
198
- if (message.type === 'assistant') {
199
- for (const block of message.message?.content ?? []) {
200
- if (block.type === 'text' && block.text) { sub.said = block.text; sub.handle.event({ type: 'content', content: block.text }) }
201
- if (block.type !== 'tool_use') continue
202
- const { name, args } = picoTool(block.name, block.input, host.cwd)
203
- sub.handle.event({ type: 'tool_executing', call: { id: block.id, type: 'function', function: { name, arguments: JSON.stringify(args) } }, at: Date.now() })
204
- startSubagent(block)
205
- }
206
- } else if (message.type === 'user') {
207
- const blocks = (Array.isArray(message.message?.content) ? message.message.content : []).filter((block) => block.type === 'tool_result')
208
- for (const block of blocks) {
209
- const text = toolResultText(block.content)
210
- 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 })
211
- finishSubagent(block, blocks.length === 1 ? message.tool_use_result : null)
212
- }
213
- }
214
- }
215
-
216
- // offered: pico's tools that Claude Code has no version of its own. A
217
- // call through the bridge lands on the tool_use Claude announced for
218
- // it (same name, same arguments, oldest first), once every message
219
- // before it has been handled, since it reaches pico by another channel
220
- const covered = host.ownTools ? new Set(host.ownTools) : COVERED_TOOLS
221
- entry.bridge.setTurn(tools.filter((tool) => !covered.has(tool.name)).map(forClaude), async (name, args) => {
222
- await chain
223
- const at = unclaimed.findIndex((use) => use.name === name && JSON.stringify(use.args) === JSON.stringify(args ?? {}))
224
- const use = at >= 0 ? unclaimed.splice(at, 1)[0] : null
225
- recorder.currentCall = use ? { id: use.id } : null
226
- })
227
-
228
- const onAssistant = (message) => {
229
- const id = message.message?.id
230
- if (assistant && assistant.id !== id) flushAssistant()
231
- assistant ??= { id, text: '', calls: [] }
232
- for (const block of message.message?.content ?? []) {
233
- if (block.type === 'text') assistant.text += block.text
234
- if (block.type !== 'tool_use') continue
235
- const { name, args, bridged } = picoTool(block.name, block.input, host.cwd)
236
- const call = { id: block.id, type: 'function', function: { name, arguments: JSON.stringify(args) } }
237
- assistant.calls.push(call)
238
- uses.set(block.id, { id: block.id, name: block.name, input: block.input, call, bridged })
239
- if (bridged) unclaimed.push({ id: block.id, name, args: block.input ?? {} })
240
- onStream({ type: 'tool_calls_ready', calls: [call] })
241
- onStream({ type: 'tool_executing', call })
242
- startSubagent(block)
243
- }
244
- if (!raws.has(id)) countUsage(id, message.message?.usage)
245
- }
246
-
247
- const onResults = async (message) => {
248
- const blocks = (Array.isArray(message.message?.content) ? message.message.content : []).filter((block) => block.type === 'tool_result')
249
- if (!blocks.length) return
250
- flushAssistant()
251
- for (const block of blocks) {
252
- const use = uses.get(block.tool_use_id)
253
- if (!use) continue
254
- uses.delete(block.tool_use_id)
255
- const waiting = unclaimed.findIndex((candidate) => candidate.id === use.id)
256
- if (waiting >= 0) unclaimed.splice(waiting, 1)
257
- const text = toolResultText(block.content)
258
- finishSubagent(block, blocks.length === 1 ? message.tool_use_result : null)
259
- collected.push({ role: 'tool', tool_call_id: use.id, content: text })
260
- // a bridged call the bridge never ran (Claude refused it first)
261
- // has no entry yet, so it gets one like any other call
262
- if (!use.bridged || !recorder.entries.some((candidate) => candidate.callId === use.id)) {
263
- // the structured result describes the message's only call
264
- const extra = blocks.length === 1 ? message.tool_use_result : null
265
- const path = extra?.filePath
266
- const after = path && existsSync(path) ? readFileSync(path, 'utf8') : null
267
- recorder.entries.push(toolEntry(use, block, extra, { cwd: host.cwd, after, interrupted }))
268
- }
269
- onStream({ type: block.is_error ? 'tool_error' : 'tool_complete', call: use.call, ...(block.is_error ? { error: text } : { result: text }) })
270
- }
271
- // between tool rounds is where pico delivers notes that arrived
272
- // mid-turn; Claude Code folds a message sent now into the same turn,
273
- // but cancels any call still running, a subagent's included, as if
274
- // the user had cut in, so notes wait until every call has finished
275
- if (interrupted || !beforeRequest || uses.size) return
276
- const notes = await beforeRequest()
277
- if (!notes?.length) return
278
- collected.push(...notes)
279
- entry.proc?.send(notes.flatMap(userBlocks))
280
- }
281
-
282
- let outcomeCleanup = () => {}
283
- const outcome = new Promise((resolve) => {
284
- entry.onMessage = (message) => {
285
- chain = chain.then(async () => {
286
- if (message.parent_tool_use_id) return onSubagent(message)
287
- if (message.type === 'system' && message.subtype === 'init') entry.claudeSessionId = message.session_id
288
- else if (message.type === 'stream_event') {
289
- const event = message.event
290
- if (event.type === 'message_start') {
291
- streaming = event.message?.id ?? null
292
- countUsage(streaming, event.message?.usage)
293
- } else if (event.type === 'message_delta') countUsage(streaming, event.usage)
294
- else if (event.type === 'content_block_delta' && event.delta?.type === 'text_delta' && event.delta.text) onStream({ type: 'content', content: event.delta.text })
295
- else if (event.type === 'content_block_delta' && event.delta?.type === 'thinking_delta' && event.delta.thinking) onStream({ type: 'thinking', content: event.delta.thinking })
296
- } else if (message.type === 'assistant') onAssistant(message)
297
- else if (message.type === 'user') await onResults(message)
298
- else if (message.type === 'result') {
299
- entry.claudeSessionId = message.session_id ?? entry.claudeSessionId
300
- if (message.is_error && !interrupted) error = message.result || message.errors?.join('; ') || message.subtype
301
- resolve()
302
- }
303
- }).catch((failure) => { error = String(failure.message || failure); resolve() })
304
- }
305
- entry.onExit = (exit) => {
306
- if (!interrupted) error = exit.error?.message || exit.stderr || 'Claude Code stopped'
307
- resolve()
308
- }
309
- const onAbort = () => {
310
- interrupted = true
311
- entry.proc?.interrupt().catch(() => {})
312
- graceTimer = setTimeout(() => { stop(entry); resolve() }, INTERRUPT_GRACE_MS)
313
- }
314
- if (signal?.aborted) onAbort()
315
- else signal?.addEventListener('abort', onAbort, { once: true })
316
- outcomeCleanup = () => signal?.removeEventListener('abort', onAbort)
317
- })
318
-
319
- // a process that failed to start takes its input nowhere, and says
320
- // why as it exits, which may already have happened
321
- const sent = !!entry.proc?.send(content)
322
- await (sent ? outcome : Promise.race([outcome, new Promise((resolve) => setTimeout(resolve, 2000))]))
323
- if (!sent) error ??= entry.lastExit?.error?.message || entry.lastExit?.stderr || 'Claude Code is not running'
324
- clearTimeout(graceTimer)
325
- outcomeCleanup()
326
- entry.onMessage = null
327
- entry.onExit = null
328
- flushAssistant()
329
- for (const sub of subagents.values()) sub.handle.finish({ interrupted: true })
330
- // a call cut off by an interrupt still needs a result, or the history
331
- // is invalid for whichever model reads it next
332
- for (const use of uses.values()) collected.push({ role: 'tool', tool_call_id: use.id, content: '[interrupted before it finished]' })
333
-
334
- if (entry.proc) {
335
- entry.synced = fingerprint([...history, ...collected])
336
- entry.idle = setTimeout(() => stop(entry), idleMs)
337
- entry.idle.unref?.()
338
- } else {
339
- // the process died: what Claude Code saved may not match, so the
340
- // next turn starts over from pico's history
341
- entry.claudeSessionId = null
342
- entry.synced = null
343
- }
344
- return {
345
- messages: collected,
346
- usage: responses.size ? usage : null,
347
- lastPromptTokens: lastPrompt,
348
- interrupted: interrupted || !!error,
349
- stalled: false,
350
- ...(error ? { error } : {}),
351
- engineState: { claudeSessionId: entry.claudeSessionId, owner: entry.owner, synced: entry.synced },
352
- }
353
- }
354
-
355
- // one question answered as text by a bare Claude Code run: no tools, no
356
- // session kept, `system` added to Claude Code's own prompt
357
- async function ask({ modelName, system = '', prompt, effort = null, signal, onStream = () => {} }) {
358
- let text = ''
359
- let failure = null
360
- let proc = null
361
- await new Promise((resolve) => {
362
- proc = spawn({
363
- command,
364
- cwd: process.cwd(),
365
- model: cliModel(modelName),
366
- ...(effort ? { effort } : {}),
367
- ...(system ? { appendSystemPrompt: system } : {}),
368
- oneShot: true,
369
- onMessage: (message) => {
370
- if (message.type === 'stream_event' && message.event?.delta?.type === 'text_delta') {
371
- text += message.event.delta.text
372
- onStream({ type: 'content', content: message.event.delta.text })
373
- } else if (message.type === 'result') {
374
- if (message.is_error) failure = message.result || message.subtype
375
- else text = message.result ?? text
376
- proc.close()
377
- resolve()
378
- }
379
- },
380
- onExit: (exit) => { failure ??= exit.error?.message ?? null; resolve() },
381
- })
382
- signal?.addEventListener('abort', () => { proc.close(); resolve() }, { once: true })
383
- proc.send(prompt)
384
- })
385
- if (signal?.aborted) throw new Error('cancelled')
386
- if (failure) throw new Error(failure)
387
- return text.trim()
388
- }
389
-
390
- // pico's compaction, done by the same model: one bare run that reads the
391
- // conversation and writes the summary
392
- function compact({ history, modelName, prompt, signal, onStream }) {
393
- return ask({ modelName, prompt: `<transcript>\n${transcriptText(history)}\n</transcript>\n\n${prompt}`, signal, onStream })
394
- .catch((error) => { throw signal?.aborted ? new Error('compaction cancelled') : error })
395
- }
396
-
397
- return {
398
- name: CLAUDE_CODE_PROVIDER,
399
- // Claude Code compacts its own context as it fills; pico compacting
400
- // too would only restart the Claude session from a summary
401
- autoCompact: false,
402
- run,
403
- ask,
404
- compact,
405
- // the pico session is done with: its process and bridge go
406
- release(sessionId) {
407
- const entry = sessions.get(sessionId)
408
- if (!entry) return
409
- stop(entry)
410
- sessions.delete(sessionId)
411
- },
412
- releaseAll() {
413
- for (const entry of sessions.values()) stop(entry)
414
- sessions.clear()
415
- },
416
- }
35
+ const offer = (tool) => (FOR_CLAUDE[tool.name] ? { ...tool, description: FOR_CLAUDE[tool.name] + tool.description } : tool)
36
+
37
+ // `spawn` and `command` reach the adapter, for a test's scripted Claude Code
38
+ export function createClaudeCodeEngine({ agent = createClaudeCodeAgent, spawn, command, ...options } = {}) {
39
+ const process = { ...(spawn ? { spawn } : {}), ...(command ? { command } : {}) }
40
+ return createAcpEngine({
41
+ provider: CLAUDE_CODE_PROVIDER,
42
+ label: 'Claude Code',
43
+ connect: ({ cwd, env, ...handlers }) => connectAgent((client, control) => agent(client, control, { cwd, env, ...process }), handlers),
44
+ systemPrompt,
45
+ covered: COVERED_TOOLS,
46
+ offer,
47
+ ...options,
48
+ })
417
49
  }
@@ -8,6 +8,7 @@ import { homedir } from 'node:os'
8
8
  import { delimiter, join } from 'node:path'
9
9
  import { promisify } from 'node:util'
10
10
  import { claudeEnv } from './cli.js'
11
+ import { claudeToken } from './token.js'
11
12
 
12
13
  const exec = promisify(execFile)
13
14
 
@@ -15,7 +16,7 @@ export const CLAUDE_CODE_PROVIDER = 'claude-code'
15
16
 
16
17
  // the CLI's model aliases always name the newest model of each family;
17
18
  // every one of them has a 1M token context window
18
- const FAMILIES = [
19
+ export const FAMILIES = [
19
20
  { alias: 'fable', label: 'Fable' },
20
21
  { alias: 'opus', label: 'Opus' },
21
22
  { alias: 'sonnet', label: 'Sonnet' },
@@ -56,16 +57,18 @@ export function claudeCommand(env = process.env) {
56
57
  return 'claude'
57
58
  }
58
59
 
59
- // whether `claude` is installed and signed in to claude.ai. A machine with
60
+ // whether `claude` is installed and runs on a Claude subscription: its
61
+ // own claude.ai login, or a long-lived token (token.js). A machine with
60
62
  // only an API key configured does not count: that is what pico's own
61
63
  // Anthropic models are for
62
64
  export async function claudeCodeStatus({ command = claudeCommand() } = {}) {
65
+ const token = !!claudeToken()
63
66
  try {
64
67
  const { stdout } = await exec(command, ['auth', 'status', '--json'], { env: claudeEnv(), timeout: 15000 })
65
68
  const status = JSON.parse(stdout)
66
69
  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 }
70
+ return { installed: true, connected: subscribed || token, email: subscribed ? status.email ?? null : null, plan: subscribed ? status.subscriptionType ?? null : null }
68
71
  } catch (error) {
69
- return { installed: error.code !== 'ENOENT', connected: false, email: null, plan: null }
72
+ return { installed: error.code !== 'ENOENT', connected: error.code !== 'ENOENT' && token, email: null, plan: null }
70
73
  }
71
74
  }
@@ -0,0 +1,23 @@
1
+ // The long-lived token Claude Code runs with, where pico keeps one: made
2
+ // by `claude setup-token` (sign-in/claude-code.js) for machines that
3
+ // cannot sign in interactively. A host that holds the token elsewhere
4
+ // passes it as CLAUDE_CODE_OAUTH_TOKEN instead, and Claude Code's own
5
+ // login is used when there is neither.
6
+
7
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
8
+ import { join } from 'node:path'
9
+ import { picoHome } from '../paths.js'
10
+
11
+ const tokenFile = () => join(picoHome(), 'claude-token')
12
+
13
+ export function claudeToken(env = process.env) {
14
+ if (env.CLAUDE_CODE_OAUTH_TOKEN) return env.CLAUDE_CODE_OAUTH_TOKEN
15
+ try { return readFileSync(tokenFile(), 'utf8').trim() || null } catch { return null }
16
+ }
17
+
18
+ export function keepClaudeToken(token) {
19
+ mkdirSync(picoHome(), { recursive: true })
20
+ writeFileSync(tokenFile(), token, { mode: 0o600 })
21
+ }
22
+
23
+ export const forgetClaudeToken = () => rmSync(tokenFile(), { force: true })