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,34 +1,9 @@
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.
1
+ // Pure translation between Claude Code's stream-json and ACP, as the
2
+ // adapter speaks it. Nothing here touches a process or the file system, so
3
+ // every rule about how Claude's messages read in ACP is testable against
4
+ // recorded output.
5
5
 
6
- import { createHash } from 'node:crypto'
7
6
  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. Memory is
20
- // not among them: Claude Code's own is switched off, so every model in a
21
- // project keeps one store, pico's. Deliberation is not either: Claude
22
- // Code has nothing like it. A host that decides this itself passes its
23
- // own list (boot.engineOwnTools)
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
- ])
29
-
30
- const SEED_CHARS = 600000
31
- const SEED_TOOL_CHARS = 2000
32
7
 
33
8
  function shortPath(path, cwd) {
34
9
  if (typeof path !== 'string' || !cwd || !isAbsolute(path)) return path
@@ -36,11 +11,29 @@ function shortPath(path, cwd) {
36
11
  return rel && !rel.startsWith('..') && !isAbsolute(rel) ? rel : path
37
12
  }
38
13
 
39
- // Claude's tool calls under the names and argument shapes pico renders:
40
- // a Bash call shows its command, an Edit its path and diff
41
- export function picoTool(name, input = {}, cwd) {
42
- if (name.startsWith(BRIDGE_PREFIX)) return { name: name.slice(BRIDGE_PREFIX.length), args: input, bridged: true }
43
- const path = shortPath(input.file_path ?? input.notebook_path, cwd)
14
+ // the file a Claude tool works on
15
+ export const toolPath = (input = {}) => input.file_path ?? input.notebook_path ?? null
16
+
17
+ // ACP's kind for a Claude tool, which ACP apps use to choose how to show it
18
+ export function acpKind(name) {
19
+ if (name === 'Bash') return 'execute'
20
+ if (['Edit', 'MultiEdit', 'Write', 'NotebookEdit'].includes(name)) return 'edit'
21
+ if (['Read', 'NotebookRead'].includes(name)) return 'read'
22
+ if (['Grep', 'Glob'].includes(name)) return 'search'
23
+ if (['WebFetch', 'WebSearch'].includes(name)) return 'fetch'
24
+ return 'other'
25
+ }
26
+
27
+ // the pico tool a Claude tool call amounts to: a Bash call shows its
28
+ // command, an Edit its path and change. A call to one of the client's own
29
+ // MCP servers (`servers`), which Claude names mcp__<server>__<tool>, is
30
+ // that tool
31
+ export function picoTool(name, input = {}, cwd, servers = []) {
32
+ for (const server of servers) {
33
+ const prefix = `mcp__${server}__`
34
+ if (name.startsWith(prefix)) return { name: name.slice(prefix.length), args: input, bridged: true }
35
+ }
36
+ const path = shortPath(toolPath(input), cwd)
44
37
  switch (name) {
45
38
  case 'Bash': return { name: 'bash', args: { command: input.command, description: input.description, ...(input.run_in_background ? { background: true } : {}), ...(input.timeout ? { timeout: input.timeout } : {}) } }
46
39
  case 'Read': return { name: 'read', args: { path, ...(input.offset != null ? { offset: input.offset } : {}), ...(input.limit != null ? { limit: input.limit } : {}) } }
@@ -55,6 +48,17 @@ export function picoTool(name, input = {}, cwd) {
55
48
  }
56
49
  }
57
50
 
51
+ // Claude's tools that start a subagent
52
+ export const SUBAGENT_TOOLS = new Set(['Task', 'Agent'])
53
+
54
+ // a call's title, as an ACP app shows it
55
+ export function callTitle(name, input = {}, cwd) {
56
+ if (name === 'Bash') return input.description || input.command || 'Bash'
57
+ if (SUBAGENT_TOOLS.has(name)) return input.description || 'Subagent'
58
+ const path = toolPath(input)
59
+ return path ? `${name} ${shortPath(path, cwd)}` : name
60
+ }
61
+
58
62
  export function toolResultText(content) {
59
63
  if (content == null) return ''
60
64
  if (typeof content === 'string') return content
@@ -62,164 +66,45 @@ export function toolResultText(content) {
62
66
  return JSON.stringify(content)
63
67
  }
64
68
 
65
- // what the transcript keeps for one finished Claude tool call: output,
66
- // errors, and for file changes a diff plus the record rewind needs to undo
67
- // them. `after` is the file as it stands once the call returned; a call
68
- // that failed because the turn was interrupted shows as interrupted
69
- export function toolEntry({ id, name, input }, block, extra, { cwd, after = null, interrupted = false } = {}) {
70
- const { name: picoName, args } = picoTool(name, input, cwd)
71
- const entry = {
72
- callId: id,
73
- name: picoName,
74
- args,
75
- title: typeof args.path === 'string' ? args.path : undefined,
76
- description: args.description,
77
- status: block.is_error ? (interrupted ? 'interrupted' : 'error') : 'done',
78
- durationMs: null,
79
- }
80
- if (block.is_error && !interrupted) entry.error = toolResultText(block.content).replace(/^<tool_use_error>|<\/tool_use_error>$/g, '')
81
- if (picoName === 'bash' && extra && typeof extra === 'object') {
82
- entry.fullOutput = toolResultOutput('bash', extra)
83
- if (extra.interrupted) entry.status = 'interrupted'
84
- } else {
85
- entry.fullOutput = toolResultText(block.content)
86
- }
87
- if (!block.is_error && extra && typeof extra === 'object' && typeof extra.filePath === 'string' && (picoName === 'edit' || picoName === 'write')) {
88
- const before = typeof extra.originalFile === 'string' ? extra.originalFile : null
89
- const now = after ?? (picoName === 'write' ? extra.content : null)
90
- if (typeof now === 'string') {
91
- const shown = shortPath(extra.filePath, cwd)
92
- entry.diff = makeDiff(shown, before ?? '', now)
93
- entry.revert = makeWriteEdit(extra.filePath, before ?? '', now, before !== null)
94
- if (before === null) entry.created = true
95
- }
96
- }
97
- return entry
98
- }
99
-
100
- // pico usage from one Claude API response; prompt counts every input
101
- // token the request carried, cached or not, since that is its context size
69
+ // usage from one Claude API response, as ACP counts it
102
70
  export function usageOf(usage = {}) {
103
- const cached = usage.cache_read_input_tokens || 0
104
- const prompt = (usage.input_tokens || 0) + cached + (usage.cache_creation_input_tokens || 0)
105
- const completion = usage.output_tokens || 0
106
- return { promptTokens: prompt, completionTokens: completion, totalTokens: prompt + completion, cachedTokens: cached, thoughtTokens: usage.output_tokens_details?.thinking_tokens || 0 }
107
- }
108
-
109
- export function addUsage(a, b) {
110
71
  return {
111
- promptTokens: a.promptTokens + b.promptTokens,
112
- completionTokens: a.completionTokens + b.completionTokens,
113
- totalTokens: a.totalTokens + b.totalTokens,
114
- cachedTokens: a.cachedTokens + b.cachedTokens,
115
- thoughtTokens: a.thoughtTokens + b.thoughtTokens,
72
+ inputTokens: usage.input_tokens || 0,
73
+ cachedReadTokens: usage.cache_read_input_tokens || 0,
74
+ cachedWriteTokens: usage.cache_creation_input_tokens || 0,
75
+ outputTokens: usage.output_tokens || 0,
76
+ thoughtTokens: 0,
116
77
  }
117
78
  }
118
79
 
119
- export const emptyUsage = () => ({ promptTokens: 0, completionTokens: 0, totalTokens: 0, cachedTokens: 0, thoughtTokens: 0 })
120
-
121
- // ---- pico history to Claude input ----
122
-
123
- // the messages a turn adds: everything after the last thing the model
124
- // said. pico appends the user's message, system notes and peer input
125
- // before a turn starts, so these trail the history
126
- export function splitTurn(history) {
127
- let at = history.length
128
- while (at > 0 && history[at - 1].role === 'user') at--
129
- return { prior: history.slice(0, at), input: history.slice(at) }
130
- }
131
-
132
- // a hash of what a conversation said, blind to what pico rewrites in place
133
- // later: old tool results get elided or trimmed, so only their ids count
134
- export function fingerprint(history) {
135
- const hash = createHash('sha256')
136
- for (const message of history) {
137
- hash.update(message.role)
138
- if (message.role === 'tool') hash.update(String(message.tool_call_id))
139
- else hash.update(typeof message.content === 'string' ? message.content : JSON.stringify(message.content ?? ''))
140
- for (const call of message.tool_calls ?? []) hash.update(String(call.id))
141
- hash.update('\u0000')
142
- }
143
- return hash.digest('hex')
144
- }
145
-
146
- function partText(part) {
147
- if (part.type === 'text') return part.text
148
- if (part.type === 'file') return fileLabel(part.path)
149
- if (part.type === 'selection') return selectionLabel(part)
150
- if (part.type === 'commit') return commitLabel(part)
151
- if (part.type === 'element') return elementLabel(part)
152
- return null
153
- }
154
-
155
- // one pico user message as Claude content blocks; `hydrated` is the same
156
- // message after pico's image preparation, which reads images into base64
157
- export function userBlocks(message) {
158
- if (typeof message.content === 'string') return [{ type: 'text', text: message.content }]
159
- const blocks = []
160
- for (const part of message.content ?? []) {
161
- if (part.type === 'image' && part.source?.kind === 'base64') {
162
- blocks.push({ type: 'image', source: { type: 'base64', media_type: part.source.mediaType, data: part.source.data } })
163
- continue
164
- }
165
- const text = partText(part)
166
- if (text) blocks.push({ type: 'text', text })
167
- }
168
- return blocks
169
- }
170
-
171
- function messageText(message) {
172
- if (typeof message.content === 'string') return message.content
173
- return (message.content ?? []).map((part) => partText(part) ?? (part.type === 'image' ? '[image]' : '')).filter(Boolean).join('')
174
- }
175
-
176
- // a conversation as plain text, for a model that cannot be handed the
177
- // messages themselves. The most recent part is kept when it is too long
178
- export function transcriptText(history) {
179
- const lines = []
180
- for (const message of history) {
181
- if (message.role === 'user') lines.push(`User:\n${messageText(message)}`)
182
- else if (message.role === 'assistant') {
183
- if (message.content) lines.push(`Assistant:\n${typeof message.content === 'string' ? message.content : messageText(message)}`)
184
- for (const call of message.tool_calls ?? []) lines.push(`Assistant called ${call.function.name}: ${call.function.arguments}`)
185
- } else if (message.role === 'tool') {
186
- const text = String(message.content ?? '')
187
- lines.push(`Tool result:\n${text.length > SEED_TOOL_CHARS ? `${text.slice(0, SEED_TOOL_CHARS)}\n[clipped]` : text}`)
188
- }
189
- }
190
- let body = lines.join('\n\n')
191
- if (body.length > SEED_CHARS) body = `[earlier conversation omitted]\n\n${body.slice(-SEED_CHARS)}`
192
- return body
80
+ export function addUsage(a, b) {
81
+ const sum = Object.fromEntries(Object.keys(a).map((key) => [key, (a[key] || 0) + (b[key] || 0)]))
82
+ return { ...sum, totalTokens: sum.inputTokens + sum.cachedReadTokens + sum.cachedWriteTokens + sum.outputTokens }
193
83
  }
194
84
 
195
- // a conversation Claude Code never saw (another model's, or one pico
196
- // rewound, steered or compacted) as a transcript it can pick up from
197
- export function seedText(history) {
198
- 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>`
199
- }
85
+ export const emptyUsage = () => ({ inputTokens: 0, cachedReadTokens: 0, cachedWriteTokens: 0, outputTokens: 0, thoughtTokens: 0, totalTokens: 0 })
200
86
 
201
- // ---- pico tool schemas to JSON Schema, for the MCP bridge ----
87
+ // the prompt a request carried, cached or not: its context size
88
+ export const promptSize = (usage) => usage.inputTokens + usage.cachedReadTokens + usage.cachedWriteTokens
202
89
 
203
- function jsonProperty(prop) {
204
- const out = { type: prop.type }
205
- if (prop.description) out.description = prop.description
206
- if (prop.enum) out.enum = prop.enum
207
- if (prop.items) out.items = jsonProperty(prop.items)
208
- if (prop.properties) {
209
- out.properties = Object.fromEntries(Object.entries(prop.properties).map(([key, child]) => [key, jsonProperty(child)]))
210
- if (prop.required) out.required = prop.required
90
+ // ACP content blocks as Claude's
91
+ export function claudeContent(blocks = []) {
92
+ const out = []
93
+ for (const block of blocks) {
94
+ if (block.type === 'text') out.push({ type: 'text', text: block.text })
95
+ else if (block.type === 'image' && block.data) out.push({ type: 'image', source: { type: 'base64', media_type: block.mimeType, data: block.data } })
96
+ else if (block.type === 'resource' && block.resource?.text != null) out.push({ type: 'text', text: `<file path="${block.resource.uri}">\n${block.resource.text}\n</file>` })
97
+ else if (block.type === 'resource_link') out.push({ type: 'text', text: `[file: ${block.uri}]` })
211
98
  }
212
99
  return out
213
100
  }
214
101
 
215
- export function inputSchema(schema = {}) {
216
- // a whole JSON Schema (an MCP server's) goes as it is
217
- if (typeof schema.type === 'string') return schema
218
- const properties = {}
219
- const required = []
220
- for (const [key, prop] of Object.entries(schema)) {
221
- properties[key] = jsonProperty(prop)
222
- if (!prop.optional) required.push(key)
102
+ // the MCP servers an ACP client offers, as Claude Code's --mcp-config takes them
103
+ export function mcpConfig(servers = []) {
104
+ const pairs = (list = []) => Object.fromEntries(list.map(({ name, value }) => [name, value]))
105
+ return {
106
+ mcpServers: Object.fromEntries(servers.map((server) => [server.name, server.type === 'http' || server.type === 'sse'
107
+ ? { type: server.type, url: server.url, headers: pairs(server.headers) }
108
+ : { type: 'stdio', command: server.command, args: server.args ?? [], env: pairs(server.env) }])),
223
109
  }
224
- return { type: 'object', properties, ...(required.length ? { required } : {}) }
225
110
  }
package/src/controller.js CHANGED
@@ -848,13 +848,16 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
848
848
 
849
849
  function streamHandler(recorder, controller) {
850
850
  return (event) => {
851
+ // a host that relays a turn as it happens (pico's ACP server) hears every event, whichever model runs it
852
+ boot.onTurnEvent?.(event, recorder)
851
853
  if (event.type === 'thinking') {
852
854
  updateOverlay((items) => {
853
855
  const next = [...items]
854
856
  flushStream(next)
855
857
  const last = next.at(-1)
856
- if (last?.kind === 'thoughts') last.text += event.content
857
- else next.push({ kind: 'thoughts', text: event.content })
858
+ // when the thinking began and when its latest piece came, so a transcript can say how long it went on
859
+ if (last?.kind === 'thoughts') { last.text += event.content; last.endedAt = Date.now() }
860
+ else next.push({ kind: 'thoughts', text: event.content, startedAt: Date.now(), endedAt: Date.now() })
858
861
  return next
859
862
  })
860
863
  set({ turnPhase: 'thinking' })
@@ -0,0 +1,87 @@
1
+ // pico history as an engine (engines.js) hands it to a program that keeps
2
+ // its own context. pico's log stays the source of truth and the program's
3
+ // context is a cache of it: a turn sends only what the program has not
4
+ // seen, and a history that moved underneath it (a rewind, a steer, a
5
+ // clear, a compaction, a conversation begun with another model) starts
6
+ // the program over from a transcript.
7
+
8
+ import { createHash } from 'node:crypto'
9
+ import { commitLabel, elementLabel, fileLabel, selectionLabel } from './attachments.js'
10
+
11
+ const SEED_CHARS = 600000
12
+ const SEED_TOOL_CHARS = 2000
13
+
14
+ // the messages a turn adds: everything after the last thing the model
15
+ // said. pico appends the user's message, system notes and peer input
16
+ // before a turn starts, so these trail the history
17
+ export function splitTurn(history) {
18
+ let at = history.length
19
+ while (at > 0 && history[at - 1].role === 'user') at--
20
+ return { prior: history.slice(0, at), input: history.slice(at) }
21
+ }
22
+
23
+ // a hash of what a conversation said, blind to what pico rewrites in place
24
+ // later: old tool results get elided or trimmed, so only their ids count
25
+ export function fingerprint(history) {
26
+ const hash = createHash('sha256')
27
+ for (const message of history) {
28
+ hash.update(message.role)
29
+ if (message.role === 'tool') hash.update(String(message.tool_call_id))
30
+ else hash.update(typeof message.content === 'string' ? message.content : JSON.stringify(message.content ?? ''))
31
+ for (const call of message.tool_calls ?? []) hash.update(String(call.id))
32
+ hash.update('\u0000')
33
+ }
34
+ return hash.digest('hex')
35
+ }
36
+
37
+ // the trailing user messages of `history` the program has not seen, given
38
+ // the fingerprint of what it has: null when the history diverged
39
+ export 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
+ // a non-image part of a pico user message as the text a model reads
49
+ export function partText(part) {
50
+ if (part.type === 'text') return part.text
51
+ if (part.type === 'file') return fileLabel(part.path)
52
+ if (part.type === 'selection') return selectionLabel(part)
53
+ if (part.type === 'commit') return commitLabel(part)
54
+ if (part.type === 'element') return elementLabel(part)
55
+ return null
56
+ }
57
+
58
+ function messageText(message) {
59
+ if (typeof message.content === 'string') return message.content
60
+ return (message.content ?? []).map((part) => partText(part) ?? (part.type === 'image' ? '[image]' : '')).filter(Boolean).join('')
61
+ }
62
+
63
+ // a conversation as plain text, for a model that cannot be handed the
64
+ // messages themselves. The most recent part is kept when it is too long
65
+ export function transcriptText(history) {
66
+ const lines = []
67
+ for (const message of history) {
68
+ if (message.role === 'user') lines.push(`User:\n${messageText(message)}`)
69
+ else if (message.role === 'assistant') {
70
+ if (message.content) lines.push(`Assistant:\n${typeof message.content === 'string' ? message.content : messageText(message)}`)
71
+ for (const call of message.tool_calls ?? []) lines.push(`Assistant called ${call.function.name}: ${call.function.arguments}`)
72
+ } else if (message.role === 'tool') {
73
+ const text = String(message.content ?? '')
74
+ lines.push(`Tool result:\n${text.length > SEED_TOOL_CHARS ? `${text.slice(0, SEED_TOOL_CHARS)}\n[clipped]` : text}`)
75
+ }
76
+ }
77
+ let body = lines.join('\n\n')
78
+ if (body.length > SEED_CHARS) body = `[earlier conversation omitted]\n\n${body.slice(-SEED_CHARS)}`
79
+ return body
80
+ }
81
+
82
+ // a conversation the program never saw (another model's, or one pico
83
+ // rewound, steered or compacted) as a transcript it can pick up from;
84
+ // `program` names it, as in "this Claude Code session"
85
+ export function seedText(history, program) {
86
+ return `[system notification] This conversation began before this ${program} 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>`
87
+ }
package/src/engines.js CHANGED
@@ -14,8 +14,10 @@
14
14
 
15
15
  import { createClaudeCodeEngine } from './claude-code/engine.js'
16
16
  import { CLAUDE_CODE_PROVIDER } from './claude-code/models.js'
17
+ import { createAntigravityEngine } from './antigravity/engine.js'
18
+ import { ANTIGRAVITY_PROVIDER } from './antigravity/models.js'
17
19
 
18
- const factories = { [CLAUDE_CODE_PROVIDER]: createClaudeCodeEngine }
20
+ const factories = { [CLAUDE_CODE_PROVIDER]: createClaudeCodeEngine, [ANTIGRAVITY_PROVIDER]: createAntigravityEngine }
19
21
  const engines = new Map()
20
22
 
21
23
  export function engineFor(model) {
@@ -0,0 +1,49 @@
1
+ // A pico session on this machine, everything it runs with put together:
2
+ // the project's boot, the models, the shells, wake-ups and git it uses,
3
+ // and pico's settings. The terminal app's daemon and the ACP server open
4
+ // sessions the same way. `extra` adds what one host keeps on the boot.
5
+
6
+ import { buildProjectBoot } from './boot.js'
7
+ import { createController } from './controller.js'
8
+ import { createShellManager } from './shells.js'
9
+ import { createWakeupManager } from './wakeups.js'
10
+ import { createGitService } from './git.js'
11
+ import { readConfig } from './config.js'
12
+ import { defaultModel } from './models.js'
13
+ import { loadModelRuntime } from './model-runtime.js'
14
+
15
+ // `mcpServers` are the session's own MCP servers (name to command)
16
+ export async function createLocalSession({ cwd = process.cwd(), runtime = null, mcpServers = {}, extra = {}, gitFooter = true } = {}) {
17
+ const { models, providers, loadModels } = runtime ?? await loadModelRuntime()
18
+ if (!providers.length) throw new Error('no model credentials found')
19
+ const config = await readConfig()
20
+ const notify = {}
21
+ const shells = createShellManager({ onChange: () => notify.shells?.(), onExit: shell => notify.shellExit?.(shell) })
22
+ const wakeups = createWakeupManager({ onChange: () => notify.wakeups?.(), onFire: wakeup => notify.wakeupFire?.(wakeup) })
23
+ const git = createGitService({ onChange: () => notify.git?.() })
24
+ const rebuild = cwd => buildProjectBoot(cwd, { onMcpChange: () => notify.mcp?.(), mcpServers })
25
+ let boot
26
+ try {
27
+ boot = {
28
+ ...await rebuild(cwd),
29
+ models, providers, initialModel: models.find(m => m.name === config.defaultModel && m.available !== false) || defaultModel(models),
30
+ researchModel: config.models?.researchWorker || null, shellModel: config.models?.shell || null,
31
+ participantAModel: config.models?.participantA || null, participantBModel: config.models?.participantB || null,
32
+ deliberationModel: config.models?.deliberation || config.models?.researchWorker || null,
33
+ prompts: config.prompts ?? null,
34
+ initialEffort: ['low', 'medium', 'high', 'max'].includes(config.defaultEffort) ? config.defaultEffort : null, speedDefaults: config.speedDefaults,
35
+ autoCompact: config.autoCompact !== false,
36
+ refs: {}, shells, wakeups, git, rebuild,
37
+ refreshModels: () => loadModels({ force: true }),
38
+ setMcpNotify: fn => { notify.mcp = fn }, setGitNotify: fn => { notify.git = fn },
39
+ setShellsNotify: fn => { notify.shells = fn }, setShellsExit: fn => { notify.shellExit = fn },
40
+ setWakeupsNotify: fn => { notify.wakeups = fn }, setWakeupsFire: fn => { notify.wakeupFire = fn },
41
+ ...extra,
42
+ }
43
+ git.retarget(boot.root)
44
+ git.setEnabled(gitFooter)
45
+ const controller = createController({ boot })
46
+ boot.mcp.connectAll()
47
+ return { controller, boot, config, dispose: () => { git.dispose(); wakeups.cancelAll(); shells.killAll() } }
48
+ } catch (error) { git.dispose(); shells.killAll(); boot?.mcp.terminateAll(); throw error }
49
+ }
package/src/mcp.js CHANGED
@@ -130,7 +130,16 @@ export async function createMcpTransport(command) {
130
130
  })
131
131
  }
132
132
 
133
- export async function createMcpRuntime({ root, onChange = () => {} }) {
133
+ // a server as parseServerSpec reads it, from its parts
134
+ export function formatServerSpec(spec) {
135
+ const quote = (value) => (/^[^\s"']+$/.test(value) ? value : value.includes('"') ? `'${value}'` : `"${value}"`)
136
+ if (spec.type === 'http') return [spec.url, ...Object.entries(spec.headers ?? {}).map(([name, value]) => `${name}=${quote(value)}`)].join(' ')
137
+ return [...Object.entries(spec.env ?? {}).map(([name, value]) => `${name}=${quote(value)}`), quote(spec.command), ...(spec.args ?? []).map(quote)].join(' ')
138
+ }
139
+
140
+ // `sessionServers` (name to command) are this session's own, from the
141
+ // app that opened it, and kept whatever the files say
142
+ export async function createMcpRuntime({ root, onChange = () => {}, sessionServers = {} }) {
134
143
  let registry = await readRegistry()
135
144
  let projectConfig = await readProjectConfig(root)
136
145
  const servers = new Map()
@@ -148,6 +157,7 @@ export async function createMcpRuntime({ root, onChange = () => {} }) {
148
157
  }
149
158
  for (const [name, command] of Object.entries(registry.servers)) register(name, command, 'global')
150
159
  for (const [name, command] of Object.entries(projectConfig.servers)) register(name, command, 'project')
160
+ for (const [name, command] of Object.entries(sessionServers)) register(name, command, 'session')
151
161
 
152
162
  // the connections under way, which a turn about to start waits for
153
163
  const connecting = new Set()
@@ -267,6 +277,7 @@ export async function createMcpRuntime({ root, onChange = () => {} }) {
267
277
  const wanted = new Map([
268
278
  ...Object.entries(registry.servers).map(([name, command]) => [name, { command, scope: 'global' }]),
269
279
  ...Object.entries(projectConfig.servers).map(([name, command]) => [name, { command, scope: 'project' }]),
280
+ ...Object.entries(sessionServers).map(([name, command]) => [name, { command, scope: 'session' }]),
270
281
  ])
271
282
  for (const name of [...servers.keys()]) {
272
283
  if (wanted.has(name)) continue
@@ -0,0 +1,94 @@
1
+ // Every model this machine can run, and what each runs with: API keys,
2
+ // the ChatGPT and SuperGrok sign-ins pico calls models with itself, and the
3
+ // agents pico drives over ACP on their own sign-ins (Claude Code,
4
+ // Antigravity). One list, whichever way pico is used.
5
+
6
+ import { discoverKeys, applyKeys, keyHint } from './keys.js'
7
+ import { loadCatalog, extractModels, adhocModel } from './catalog.js'
8
+ import { loadXAIModels } from './xai-models.js'
9
+ import { xaiConnected, xaiCredentials } from './xai-auth.js'
10
+ import { loadCodexModels } from './codex-models.js'
11
+ import { loadOpenRouterModels } from './openrouter-models.js'
12
+ import { openaiConnected, openaiCredentials } from './openai-auth.js'
13
+ import { defaultModel } from './models.js'
14
+ import { fuzzyScore } from './fuzzy.js'
15
+ import { CLAUDE_CODE_PROVIDER, claudeCodeModels, claudeCodeStatus } from './claude-code/models.js'
16
+ import { ANTIGRAVITY_PROVIDER, antigravityModels, antigravityStatus } from './antigravity/models.js'
17
+
18
+ const CATALOG_PROVIDERS = ['google', 'anthropic', 'openai', 'xai']
19
+
20
+ function codexContext(catalogData, model) {
21
+ const entry = catalogData.openai?.models?.[model.name.split('/')[1]]
22
+ return model.context ?? entry?.limit?.input ?? entry?.limit?.context ?? null
23
+ }
24
+
25
+ // the models of `providers` (the providers this machine has keys or
26
+ // sign-ins for), each marked available or not
27
+ export async function buildModels({ providers, force = false, agy = null }) {
28
+ if (providers.includes(ANTIGRAVITY_PROVIDER) && !agy) agy = await antigravityStatus().catch(() => ({ models: [] }))
29
+ const has = (provider) => providers.includes(provider)
30
+ const codexCredentials = has('codex') ? await openaiCredentials().catch(() => null) : null
31
+ const subscriptionCredentials = has('grok') ? await xaiCredentials().catch(() => null) : null
32
+ const [catalogData, codex, openrouter, grok] = await Promise.all([
33
+ loadCatalog({ force }),
34
+ loadCodexModels(codexCredentials, { force }),
35
+ has('openrouter') ? loadOpenRouterModels({ force }) : [],
36
+ loadXAIModels(subscriptionCredentials, { force }),
37
+ ])
38
+ return [
39
+ ...extractModels(catalogData, CATALOG_PROVIDERS).map((model) => ({
40
+ ...model,
41
+ available: has(model.provider),
42
+ keyHint: keyHint(model.provider),
43
+ })),
44
+ ...codex.map((model) => ({
45
+ ...model,
46
+ context: codexContext(catalogData, model),
47
+ available: has('codex'),
48
+ keyHint: '/connect',
49
+ })),
50
+ ...grok.map(model => ({ ...model, available: has('grok'), keyHint: '/connect' })),
51
+ ...openrouter.map((model) => ({ ...model, available: true, keyHint: keyHint('openrouter') })),
52
+ ...(has(CLAUDE_CODE_PROVIDER) ? claudeCodeModels() : []),
53
+ ...(has(ANTIGRAVITY_PROVIDER) ? antigravityModels(agy.models) : []),
54
+ ]
55
+ }
56
+
57
+ export async function loadModelRuntime() {
58
+ const [chatgpt, grok, claude, agy] = await Promise.all([
59
+ openaiConnected(),
60
+ xaiConnected(),
61
+ claudeCodeStatus().catch(() => ({ connected: false })),
62
+ antigravityStatus().catch(() => ({ connected: false, models: [] })),
63
+ ])
64
+ const providers = [
65
+ ...applyKeys(discoverKeys()),
66
+ ...(chatgpt ? ['codex'] : []),
67
+ ...(grok.connected ? ['grok'] : []),
68
+ ...(claude.connected ? [CLAUDE_CODE_PROVIDER] : []),
69
+ ...(agy.connected ? [ANTIGRAVITY_PROVIDER] : []),
70
+ ]
71
+ const codexCredentials = chatgpt ? await openaiCredentials().catch(() => null) : null
72
+ const loadModels = ({ force = false } = {}) => buildModels({ providers, force, agy })
73
+ const subscriptionCredentials = grok.connected ? await xaiCredentials().catch(() => null) : null
74
+ return { providers, models: await loadModels(), codexCredentials, xaiCredentials: subscriptionCredentials, loadModels }
75
+ }
76
+
77
+ export function resolveModel(models, providers, name) {
78
+ if (!name) return null
79
+ const exact = models.find((model) => model.name === name)
80
+ if (exact) return exact
81
+ if (name.includes('/')) return adhocModel(name, providers)
82
+ const available = models.filter((model) => model.available !== false)
83
+ return available
84
+ .map((model) => [fuzzyScore(name, model.name), model])
85
+ .filter(([score]) => score >= 0)
86
+ .sort((a, b) => b[0] - a[0])[0]?.[1]
87
+ || null
88
+ }
89
+
90
+ export function selectModel({ models, providers, requested, configured }) {
91
+ return resolveModel(models, providers, requested)
92
+ || (configured && models.find((model) => model.name === configured && model.available))
93
+ || defaultModel(models)
94
+ }
@@ -82,7 +82,8 @@ function storeTokens(auth, tokens) {
82
82
  return auth
83
83
  }
84
84
 
85
- export async function connectOpenAI({ openBrowser = true, timeoutMs = 5 * 60 * 1000, onUrl = () => {} } = {}) {
85
+ // `signal` cancels a sign-in under way
86
+ export async function connectOpenAI({ openBrowser = true, timeoutMs = 5 * 60 * 1000, onUrl = () => {}, signal } = {}) {
86
87
  const verifier = base64url(randomBytes(64))
87
88
  const challenge = base64url(createHash('sha256').update(verifier).digest())
88
89
  const state = base64url(randomBytes(24))
@@ -130,8 +131,15 @@ export async function connectOpenAI({ openBrowser = true, timeoutMs = 5 * 60 * 1
130
131
 
131
132
  function cleanup() {
132
133
  clearTimeout(timer)
134
+ signal?.removeEventListener('abort', cancelled)
133
135
  server.close()
134
136
  }
137
+ function cancelled() {
138
+ cleanup()
139
+ reject(new Error('cancelled'))
140
+ }
141
+ if (signal?.aborted) return cancelled()
142
+ signal?.addEventListener('abort', cancelled, { once: true })
135
143
 
136
144
  server.on('error', (err) => {
137
145
  cleanup()