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.
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/acp/README.md +41 -0
- package/src/acp/connect.js +108 -0
- package/src/acp/engine.js +531 -0
- package/src/acp/pico-agent.js +295 -0
- package/src/acp/rpc.js +75 -0
- package/src/acp/translate.js +163 -0
- package/src/antigravity/README.md +42 -0
- package/src/antigravity/adapter.js +146 -0
- package/src/antigravity/conversations.js +22 -0
- package/src/antigravity/engine.js +27 -0
- package/src/antigravity/models.js +91 -0
- package/src/antigravity/process.js +60 -0
- package/src/boot.js +3 -2
- package/src/catalog-snapshot.json +1 -1
- package/src/claude-code/README.md +14 -20
- package/src/claude-code/adapter.js +278 -0
- package/src/claude-code/cli.js +6 -2
- package/src/claude-code/engine.js +30 -398
- package/src/claude-code/models.js +7 -4
- package/src/claude-code/token.js +23 -0
- package/src/claude-code/translate.js +65 -180
- package/src/controller.js +5 -2
- package/src/engine-history.js +87 -0
- package/src/engines.js +3 -1
- package/src/local-session.js +49 -0
- package/src/mcp.js +12 -1
- package/src/model-runtime.js +94 -0
- package/src/openai-auth.js +9 -1
- package/src/sign-in/antigravity.js +123 -0
- package/src/sign-in/chatgpt.js +32 -0
- package/src/sign-in/claude-code.js +73 -0
- package/src/sign-in/index.js +32 -0
- package/src/sign-in/screen.js +56 -0
- package/src/sign-in/supergrok.js +21 -0
- package/src/{claude-code/mcp-server.js → tool-bridge-server.js} +3 -3
- package/src/{claude-code/bridge.js → tool-bridge.js} +42 -12
- package/src/xai-auth.js +6 -1
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
// pico as an ACP agent, for any ACP app: each ACP session is a whole pico
|
|
2
|
+
// session (its log, tools, compaction, memories, MCP servers), on any model
|
|
3
|
+
// this machine can run, whether pico calls the model itself (API keys,
|
|
4
|
+
// ChatGPT, SuperGrok) or drives an agent over ACP (Claude Code,
|
|
5
|
+
// Antigravity). The app picks the model and thinking effort as session
|
|
6
|
+
// options, and signs in to a subscription with `authenticate`.
|
|
7
|
+
//
|
|
8
|
+
// What ACP has no words for, pico says under its own names:
|
|
9
|
+
// - `_pico/sign_in` (notification): a sign-in begun by `authenticate`
|
|
10
|
+
// shows its page, { methodId, url, code?, input }; `input` says what the
|
|
11
|
+
// person brings back from it by hand ('code', 'redirect' or null)
|
|
12
|
+
// - `_pico/sign_in/finish` { methodId, input }: hands that in
|
|
13
|
+
// - `_pico/sign_in/cancel` { methodId }
|
|
14
|
+
// - `usage_update` carries the turn's usage so far under `_meta.pico.usage`
|
|
15
|
+
|
|
16
|
+
import { mkdtempSync, writeFileSync } from 'node:fs'
|
|
17
|
+
import { tmpdir } from 'node:os'
|
|
18
|
+
import { basename, isAbsolute, join } from 'node:path'
|
|
19
|
+
import { RpcError } from './rpc.js'
|
|
20
|
+
import { acpUsage, picoContent } from './translate.js'
|
|
21
|
+
import { createLocalSession } from '../local-session.js'
|
|
22
|
+
import { loadModelRuntime } from '../model-runtime.js'
|
|
23
|
+
import { formatServerSpec } from '../mcp.js'
|
|
24
|
+
import { listSessions } from '../session.js'
|
|
25
|
+
import { findProjectRoot, sessionsDir } from '../paths.js'
|
|
26
|
+
import { defaultTitle } from '../tools/recorder.js'
|
|
27
|
+
import { SIGN_INS, signInFor } from '../sign-in/index.js'
|
|
28
|
+
|
|
29
|
+
const EFFORTS = ['low', 'medium', 'high', 'max']
|
|
30
|
+
|
|
31
|
+
const PROVIDER_LABELS = { 'claude-code': 'Claude Code', antigravity: 'Antigravity', codex: 'ChatGPT', grok: 'SuperGrok', anthropic: 'Anthropic', openai: 'OpenAI', google: 'Google', xai: 'xAI', openrouter: 'OpenRouter' }
|
|
32
|
+
|
|
33
|
+
// the kind ACP apps show a pico tool call as
|
|
34
|
+
export function kindOf(name) {
|
|
35
|
+
if (name === 'bash') return 'execute'
|
|
36
|
+
if (['read', 'view'].includes(name)) return 'read'
|
|
37
|
+
if (['edit', 'write'].includes(name)) return 'edit'
|
|
38
|
+
if (['glob', 'grep'].includes(name)) return 'search'
|
|
39
|
+
if (/^(web_|browser_)/.test(name)) return 'fetch'
|
|
40
|
+
return 'other'
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// the MCP servers an ACP app gives a session, as pico names them
|
|
44
|
+
export function sessionServers(servers = []) {
|
|
45
|
+
const pairs = (list = []) => Object.fromEntries(list.map(({ name, value }) => [name, value]))
|
|
46
|
+
return Object.fromEntries(servers.map((s) => [s.name, formatServerSpec(s.type === 'http' || s.type === 'sse'
|
|
47
|
+
? { type: 'http', url: s.url, headers: pairs(s.headers) }
|
|
48
|
+
: { type: 'stdio', command: s.command, args: s.args ?? [], env: pairs(s.env) })]))
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// a finished pico tool call as an ACP update
|
|
52
|
+
export function callUpdate(entry, { id, cwd }) {
|
|
53
|
+
const failed = entry?.status === 'error'
|
|
54
|
+
const text = String(entry?.fullOutput ?? entry?.resultText ?? entry?.error ?? '')
|
|
55
|
+
const content = [{ type: 'content', content: { type: 'text', text } }]
|
|
56
|
+
const args = entry?.args ?? {}
|
|
57
|
+
const path = typeof args.path === 'string' ? (isAbsolute(args.path) ? args.path : join(cwd, args.path)) : null
|
|
58
|
+
if (!failed && path && entry.name === 'edit' && typeof args.newText === 'string') content.push({ type: 'diff', path, oldText: args.oldText ?? '', newText: args.newText })
|
|
59
|
+
if (!failed && path && entry.name === 'write' && typeof args.content === 'string') content.push({ type: 'diff', path, oldText: entry.created ? null : '', newText: args.content })
|
|
60
|
+
return { sessionUpdate: 'tool_call_update', toolCallId: id, status: failed ? 'failed' : entry?.status === 'interrupted' ? 'failed' : 'completed', content }
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function createPicoAgent(client, { exit = () => {} } = {}, { openSession = createLocalSession, loadRuntime = loadModelRuntime, version = '1' } = {}) {
|
|
64
|
+
const sessions = new Map()
|
|
65
|
+
const signIns = new Map()
|
|
66
|
+
let runtime = null
|
|
67
|
+
const models = () => (runtime ??= loadRuntime())
|
|
68
|
+
|
|
69
|
+
function session(id) {
|
|
70
|
+
const found = sessions.get(id)
|
|
71
|
+
if (!found) throw new RpcError(`no session ${id}`, -32602)
|
|
72
|
+
return found
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const send = (entry, update) => client.notify('session/update', { sessionId: entry.id, update })
|
|
76
|
+
|
|
77
|
+
function configOptions(entry) {
|
|
78
|
+
const ctl = entry.ctl
|
|
79
|
+
const available = ctl.boot.models.filter((m) => m.available !== false)
|
|
80
|
+
const groups = new Map()
|
|
81
|
+
for (const m of available) {
|
|
82
|
+
if (!groups.has(m.provider)) groups.set(m.provider, { group: m.provider, name: PROVIDER_LABELS[m.provider] ?? m.provider, options: [] })
|
|
83
|
+
groups.get(m.provider).options.push({ value: m.name, name: m.label ?? m.name })
|
|
84
|
+
}
|
|
85
|
+
const options = [{ id: 'model', name: 'Model', category: 'model', type: 'select', currentValue: ctl.state.model.name, options: [...groups.values()] }]
|
|
86
|
+
if (ctl.effortApplies()) options.push({ id: 'effort', name: 'Effort', category: 'thought_level', type: 'select', currentValue: ctl.state.effort ?? 'auto', options: [{ value: 'auto', name: 'Auto' }, ...EFFORTS.map((value) => ({ value, name: value }))] })
|
|
87
|
+
return options
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// a turn's events, as ACP updates as they happen
|
|
91
|
+
function relay(entry, event, recorder) {
|
|
92
|
+
if (event.type === 'content') send(entry, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: event.content } })
|
|
93
|
+
else if (event.type === 'thinking') send(entry, { sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: event.content } })
|
|
94
|
+
else if (event.type === 'tool_executing') {
|
|
95
|
+
let args = {}
|
|
96
|
+
try { args = JSON.parse(event.call.function.arguments) } catch {}
|
|
97
|
+
const name = event.call.function.name
|
|
98
|
+
const path = typeof args.path === 'string' ? (isAbsolute(args.path) ? args.path : join(entry.cwd, args.path)) : null
|
|
99
|
+
send(entry, { sessionUpdate: 'tool_call', toolCallId: event.call.id, title: args.description || defaultTitle(name, args), kind: kindOf(name), status: 'in_progress', rawInput: args, ...(path ? { locations: [{ path }] } : {}) })
|
|
100
|
+
} else if (event.type === 'tool_complete' || event.type === 'tool_error') {
|
|
101
|
+
const row = recorder.entries.findLast((candidate) => candidate.callId === event.call.id)
|
|
102
|
+
send(entry, callUpdate(row ?? { name: event.call.function?.name, status: event.type === 'tool_error' ? 'error' : 'done', fullOutput: event.error ?? event.result }, { id: event.call.id, cwd: entry.cwd }))
|
|
103
|
+
} else if (event.type === 'usage') {
|
|
104
|
+
send(entry, { sessionUpdate: 'usage_update', used: entry.ctl.state.derived.lastPromptTokens || 0, size: entry.ctl.state.model.context || 0, _meta: { pico: { usage: event.usage } } })
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// pico's questions, asked of the person through the app: a choice as a
|
|
109
|
+
// permission with the choices as its options. ACP has no way to ask for
|
|
110
|
+
// a written answer, so such a question is answered as unanswerable
|
|
111
|
+
async function ask(entry, question) {
|
|
112
|
+
const answers = []
|
|
113
|
+
for (const [n, q] of question.questions.entries()) {
|
|
114
|
+
if (q.type === 'text' || !q.options?.length) { answers.push('(no answer: this app cannot take a written answer)'); continue }
|
|
115
|
+
const reply = await client.request('session/request_permission', {
|
|
116
|
+
sessionId: entry.id,
|
|
117
|
+
toolCall: { toolCallId: `question-${Date.now()}-${n}`, title: q.question, kind: 'other', status: 'pending', rawInput: { question: q.question } },
|
|
118
|
+
options: q.options.map((o) => ({ optionId: o.label, name: o.label, kind: 'allow_once' })),
|
|
119
|
+
}).catch(() => null)
|
|
120
|
+
if (reply?.outcome?.outcome !== 'selected') { entry.ctl.cancelQuestion(); return }
|
|
121
|
+
answers.push(reply.outcome.optionId)
|
|
122
|
+
}
|
|
123
|
+
entry.ctl.answerQuestion(answers)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
async function open(params) {
|
|
127
|
+
const cwd = params.cwd ?? process.cwd()
|
|
128
|
+
const holder = { id: null, cwd, turn: null, ctl: null }
|
|
129
|
+
const opened = await openSession({ cwd, runtime: await models(), mcpServers: sessionServers(params.mcpServers), extra: { onTurnEvent: (event, recorder) => relay(holder, event, recorder) } })
|
|
130
|
+
holder.ctl = opened.controller
|
|
131
|
+
holder.dispose = opened.dispose
|
|
132
|
+
holder.ctl.on('question', (question) => { ask(holder, question).catch(() => holder.ctl.cancelQuestion()) })
|
|
133
|
+
holder.ctl.on('flash', (text) => { if (holder.turn && /^error:/.test(text)) holder.turn.error = text.replace(/^error:\s*/, '') })
|
|
134
|
+
holder.ctl.on('change', () => {
|
|
135
|
+
const turn = holder.turn
|
|
136
|
+
if (!turn) return
|
|
137
|
+
if (holder.ctl.state.busy) turn.started = true
|
|
138
|
+
else if (turn.started && !holder.ctl.isWorking()) finishTurn(holder)
|
|
139
|
+
})
|
|
140
|
+
return holder
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function finishTurn(entry) {
|
|
144
|
+
const turn = entry.turn
|
|
145
|
+
entry.turn = null
|
|
146
|
+
const now = entry.ctl.state.derived.usage
|
|
147
|
+
const usage = Object.fromEntries(Object.keys(now).map((key) => [key, (now[key] || 0) - (turn.before[key] || 0)]))
|
|
148
|
+
const interrupted = turn.cancelled || entry.ctl.state.events.at(-1)?.type === 'interrupt'
|
|
149
|
+
if (turn.error && !turn.cancelled) turn.reject(new RpcError(turn.error))
|
|
150
|
+
else turn.resolve({ stopReason: interrupted ? 'cancelled' : 'end_turn', usage: acpUsage(usage) })
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const fileOf = (cwd, sessionId) => join(sessionsDir(findProjectRoot(cwd)), `${basename(String(sessionId))}.jsonl`)
|
|
154
|
+
|
|
155
|
+
async function reopen(params, { replay }) {
|
|
156
|
+
const entry = await open(params)
|
|
157
|
+
const file = fileOf(entry.cwd, params.sessionId)
|
|
158
|
+
await entry.ctl.resume({ file, header: { root: entry.ctl.boot.root, cwd: entry.cwd } })
|
|
159
|
+
entry.id = entry.ctl.state.session?.id
|
|
160
|
+
if (entry.id !== params.sessionId) { entry.dispose(); throw new RpcError(`no session ${params.sessionId} here`, -32602) }
|
|
161
|
+
sessions.set(entry.id, entry)
|
|
162
|
+
if (replay) {
|
|
163
|
+
for (const item of entry.ctl.state.derived.transcript) {
|
|
164
|
+
if (item.kind === 'user') send(entry, { sessionUpdate: 'user_message_chunk', content: { type: 'text', text: String(item.text ?? '') } })
|
|
165
|
+
else if (item.kind === 'assistant') send(entry, { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: String(item.text ?? '') } })
|
|
166
|
+
else if (item.kind === 'tool' && item.callId) {
|
|
167
|
+
send(entry, { sessionUpdate: 'tool_call', toolCallId: item.callId, title: item.title ?? item.name, kind: kindOf(item.name), status: 'in_progress', rawInput: item.args ?? {} })
|
|
168
|
+
send(entry, callUpdate({ ...item, status: item.status === 'error' ? 'error' : 'done' }, { id: item.callId, cwd: entry.cwd }))
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return entry
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const methods = {
|
|
176
|
+
initialize: () => ({
|
|
177
|
+
protocolVersion: 1,
|
|
178
|
+
agentCapabilities: {
|
|
179
|
+
loadSession: true,
|
|
180
|
+
promptCapabilities: { image: true, audio: false, embeddedContext: true },
|
|
181
|
+
sessionCapabilities: { resume: {}, close: {}, list: {} },
|
|
182
|
+
auth: { logout: {} },
|
|
183
|
+
},
|
|
184
|
+
agentInfo: { name: 'pico', title: 'pico', version },
|
|
185
|
+
authMethods: Object.entries(SIGN_INS).map(([id, s]) => ({ id, name: `Sign in to ${s.label}` })),
|
|
186
|
+
}),
|
|
187
|
+
|
|
188
|
+
authenticate: async ({ methodId }) => {
|
|
189
|
+
const signIn = signInFor(methodId)
|
|
190
|
+
signIns.get(methodId)?.cancel()
|
|
191
|
+
const flow = await signIn.start()
|
|
192
|
+
signIns.set(methodId, flow)
|
|
193
|
+
try {
|
|
194
|
+
const page = await flow.page
|
|
195
|
+
client.notify('_pico/sign_in', { methodId, url: page.url, ...(page.code ? { code: page.code } : {}), input: flow.input })
|
|
196
|
+
await flow.done
|
|
197
|
+
runtime = null
|
|
198
|
+
return {}
|
|
199
|
+
} finally {
|
|
200
|
+
if (signIns.get(methodId) === flow) signIns.delete(methodId)
|
|
201
|
+
}
|
|
202
|
+
},
|
|
203
|
+
'_pico/sign_in/finish': async ({ methodId, input }) => {
|
|
204
|
+
const flow = signIns.get(methodId)
|
|
205
|
+
if (!flow) throw new RpcError('no sign-in is under way', -32602)
|
|
206
|
+
await flow.finish(input)
|
|
207
|
+
return {}
|
|
208
|
+
},
|
|
209
|
+
'_pico/sign_in/cancel': ({ methodId }) => {
|
|
210
|
+
signIns.get(methodId)?.cancel()
|
|
211
|
+
return {}
|
|
212
|
+
},
|
|
213
|
+
logout: async ({ methodId }) => {
|
|
214
|
+
await signInFor(methodId).signOut()
|
|
215
|
+
runtime = null
|
|
216
|
+
return {}
|
|
217
|
+
},
|
|
218
|
+
|
|
219
|
+
'session/new': async (params) => {
|
|
220
|
+
const entry = await open(params)
|
|
221
|
+
entry.ctl.ensureSession()
|
|
222
|
+
entry.id = entry.ctl.state.session.id
|
|
223
|
+
sessions.set(entry.id, entry)
|
|
224
|
+
return { sessionId: entry.id, configOptions: configOptions(entry) }
|
|
225
|
+
},
|
|
226
|
+
'session/load': async (params) => {
|
|
227
|
+
const entry = sessions.get(params.sessionId) ?? await reopen(params, { replay: true })
|
|
228
|
+
return { configOptions: configOptions(entry) }
|
|
229
|
+
},
|
|
230
|
+
'session/resume': async (params) => {
|
|
231
|
+
const entry = sessions.get(params.sessionId) ?? await reopen(params, { replay: false })
|
|
232
|
+
return { configOptions: configOptions(entry) }
|
|
233
|
+
},
|
|
234
|
+
'session/list': async ({ cwd = process.cwd() } = {}) => {
|
|
235
|
+
const listed = await listSessions({ scope: 'project', root: findProjectRoot(cwd) })
|
|
236
|
+
return { sessions: listed.map((s) => ({ sessionId: s.header?.id ?? basename(s.file, '.jsonl'), cwd: s.header?.cwd ?? cwd, title: s.title, updatedAt: new Date(s.at).toISOString() })) }
|
|
237
|
+
},
|
|
238
|
+
'session/set_config_option': ({ sessionId, configId, value }) => {
|
|
239
|
+
const entry = session(sessionId)
|
|
240
|
+
if (configId === 'model') entry.ctl.switchModelByName(String(value))
|
|
241
|
+
else if (configId === 'effort') entry.ctl.setEffortByName(value === 'auto' ? 'default' : String(value))
|
|
242
|
+
else throw new RpcError(`no option ${configId}`, -32602)
|
|
243
|
+
return { configOptions: configOptions(entry) }
|
|
244
|
+
},
|
|
245
|
+
'session/prompt': ({ sessionId, prompt }) => {
|
|
246
|
+
const entry = session(sessionId)
|
|
247
|
+
if (entry.turn) throw new RpcError('a turn is already running in this session', -32602)
|
|
248
|
+
const content = picoContent(prompt)
|
|
249
|
+
const parts = typeof content === 'string' ? [{ type: 'text', text: content }] : content
|
|
250
|
+
// an image comes in as data; pico attaches images by file
|
|
251
|
+
const text = parts.map((part) => {
|
|
252
|
+
if (part.type === 'text') return part.text
|
|
253
|
+
const dir = mkdtempSync(join(tmpdir(), 'pico-acp-image-'))
|
|
254
|
+
const file = join(dir, `image.${(part.source.mediaType.split('/')[1] ?? 'png').replace('jpeg', 'jpg')}`)
|
|
255
|
+
writeFileSync(file, Buffer.from(part.source.data, 'base64'))
|
|
256
|
+
return entry.ctl.attachImage(file) ?? ''
|
|
257
|
+
}).join('\n')
|
|
258
|
+
return new Promise((resolve, reject) => {
|
|
259
|
+
entry.turn = { resolve, reject, started: false, cancelled: false, error: null, before: { ...entry.ctl.state.derived.usage } }
|
|
260
|
+
entry.ctl.send(text)
|
|
261
|
+
// nothing to do: the controller took no turn
|
|
262
|
+
setTimeout(() => { if (entry.turn && !entry.turn.started && !entry.ctl.isWorking()) finishTurn(entry) }, 1000)
|
|
263
|
+
})
|
|
264
|
+
},
|
|
265
|
+
'session/close': async ({ sessionId }) => {
|
|
266
|
+
const entry = sessions.get(sessionId)
|
|
267
|
+
if (!entry) return {}
|
|
268
|
+
sessions.delete(sessionId)
|
|
269
|
+
await entry.ctl.shutdown()
|
|
270
|
+
entry.dispose()
|
|
271
|
+
return {}
|
|
272
|
+
},
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
return {
|
|
276
|
+
async handle(method, params) {
|
|
277
|
+
if (!methods[method]) throw new RpcError(`${method} is not handled here`, -32601)
|
|
278
|
+
return methods[method](params ?? {})
|
|
279
|
+
},
|
|
280
|
+
notification(method, params) {
|
|
281
|
+
if (method !== 'session/cancel') return
|
|
282
|
+
const entry = sessions.get(params.sessionId)
|
|
283
|
+
if (!entry?.turn) return
|
|
284
|
+
entry.turn.cancelled = true
|
|
285
|
+
entry.ctl.interrupt()
|
|
286
|
+
},
|
|
287
|
+
// every session ends with all it said written down
|
|
288
|
+
async close() {
|
|
289
|
+
for (const flow of signIns.values()) flow.cancel()
|
|
290
|
+
const open = [...sessions.values()]
|
|
291
|
+
sessions.clear()
|
|
292
|
+
await Promise.all(open.map(async (entry) => { await entry.ctl.shutdown().catch(() => {}); entry.dispose() }))
|
|
293
|
+
},
|
|
294
|
+
}
|
|
295
|
+
}
|
package/src/acp/rpc.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// JSON-RPC 2.0 as the Agent Client Protocol (ACP) uses it: one message per
|
|
2
|
+
// line, either side may ask the other and be asked. A peer is the same
|
|
3
|
+
// whichever side it is on; what it does with what it is asked is its own.
|
|
4
|
+
|
|
5
|
+
import { createInterface } from 'node:readline'
|
|
6
|
+
|
|
7
|
+
export class RpcError extends Error {
|
|
8
|
+
constructor(message, code = -32603, data = undefined) {
|
|
9
|
+
super(message)
|
|
10
|
+
this.code = code
|
|
11
|
+
if (data !== undefined) this.data = data
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export const methodNotFound = (method) => new RpcError(`${method} is not handled here`, -32601)
|
|
16
|
+
|
|
17
|
+
// a peer that sends with `write(message)` and is handed what arrives with
|
|
18
|
+
// `receive(message)`. `onRequest(method, params)` answers what the other
|
|
19
|
+
// side asks; `onNotification(method, params)` hears what it reports
|
|
20
|
+
export function createPeer({ write, onRequest = (method) => { throw methodNotFound(method) }, onNotification = () => {} }) {
|
|
21
|
+
const pending = new Map()
|
|
22
|
+
let seq = 0
|
|
23
|
+
let closed = null
|
|
24
|
+
|
|
25
|
+
async function answer(message) {
|
|
26
|
+
try {
|
|
27
|
+
const result = await onRequest(message.method, message.params ?? {})
|
|
28
|
+
write({ jsonrpc: '2.0', id: message.id, result: result ?? null })
|
|
29
|
+
} catch (error) {
|
|
30
|
+
write({ jsonrpc: '2.0', id: message.id, error: { code: error.code ?? -32603, message: String(error.message || error), ...(error.data !== undefined ? { data: error.data } : {}) } })
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return {
|
|
35
|
+
receive(message) {
|
|
36
|
+
if (message.method && message.id !== undefined) { answer(message); return }
|
|
37
|
+
if (message.method) { onNotification(message.method, message.params ?? {}); return }
|
|
38
|
+
const waiter = pending.get(message.id)
|
|
39
|
+
pending.delete(message.id)
|
|
40
|
+
if (!waiter) return
|
|
41
|
+
if (message.error) waiter.reject(new RpcError(message.error.message || 'request refused', message.error.code, message.error.data))
|
|
42
|
+
else waiter.resolve(message.result ?? null)
|
|
43
|
+
},
|
|
44
|
+
request(method, params = {}) {
|
|
45
|
+
if (closed) return Promise.reject(closed)
|
|
46
|
+
const id = ++seq
|
|
47
|
+
return new Promise((resolve, reject) => {
|
|
48
|
+
pending.set(id, { resolve, reject })
|
|
49
|
+
write({ jsonrpc: '2.0', id, method, params })
|
|
50
|
+
})
|
|
51
|
+
},
|
|
52
|
+
notify(method, params = {}) {
|
|
53
|
+
if (!closed) write({ jsonrpc: '2.0', method, params })
|
|
54
|
+
},
|
|
55
|
+
// the other side is gone: whatever was asked of it fails
|
|
56
|
+
close(error = new Error('the other side stopped')) {
|
|
57
|
+
if (closed) return
|
|
58
|
+
closed = error
|
|
59
|
+
for (const waiter of pending.values()) waiter.reject(error)
|
|
60
|
+
pending.clear()
|
|
61
|
+
},
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// a peer over a pair of streams, one JSON message per line; a line that is
|
|
66
|
+
// not JSON (a program's stray output) is ignored
|
|
67
|
+
export function streamPeer({ input, output, ...handlers }) {
|
|
68
|
+
const peer = createPeer({ ...handlers, write: (message) => { if (output.writable) output.write(`${JSON.stringify(message)}\n`) } })
|
|
69
|
+
createInterface({ input }).on('line', (line) => {
|
|
70
|
+
let message
|
|
71
|
+
try { message = JSON.parse(line) } catch { return }
|
|
72
|
+
if (message && typeof message === 'object') peer.receive(message)
|
|
73
|
+
})
|
|
74
|
+
return peer
|
|
75
|
+
}
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// Pure translation between ACP messages and pico's shapes. Nothing here
|
|
2
|
+
// touches a process or the file system.
|
|
3
|
+
//
|
|
4
|
+
// pico's adapters say more than ACP does about a few things, under
|
|
5
|
+
// `_meta.pico` (ACP leaves `_meta` to extensions):
|
|
6
|
+
//
|
|
7
|
+
// - on session/new: `systemPrompt` (instructions added to the agent's
|
|
8
|
+
// own) and `ephemeral` (one question answered with no tools, nothing
|
|
9
|
+
// kept afterward)
|
|
10
|
+
// - on a tool call: `tool` ({ name, args }, the pico tool it amounts to),
|
|
11
|
+
// `bridged` (a call to the client's own MCP server), `subagent`
|
|
12
|
+
// ({ description, prompt, model }, a call that starts one), and
|
|
13
|
+
// `wholeFile` (its diff holds the whole file before and after)
|
|
14
|
+
// - on any update: `parentToolCallId`, for a subagent's own traffic
|
|
15
|
+
// - on a permission request: `question`, one meant for the person
|
|
16
|
+
// - on usage_update: `usage`, the turn's usage so far in pico's shape
|
|
17
|
+
|
|
18
|
+
import { isAbsolute, relative } from 'node:path'
|
|
19
|
+
import { partText } from '../engine-history.js'
|
|
20
|
+
|
|
21
|
+
export const picoMeta = (message) => message?._meta?.pico ?? {}
|
|
22
|
+
|
|
23
|
+
export function shortPath(path, cwd) {
|
|
24
|
+
if (typeof path !== 'string' || !cwd || !isAbsolute(path)) return path
|
|
25
|
+
const rel = relative(cwd, path)
|
|
26
|
+
return rel && !rel.startsWith('..') && !isAbsolute(rel) ? rel : path
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// the file a call is about
|
|
30
|
+
export const callPath = (call = {}) => call.locations?.[0]?.path ?? call.rawInput?.path ?? call.rawInput?.file_path ?? null
|
|
31
|
+
|
|
32
|
+
// an ACP tool call as the pico tool pico renders it as: the one the
|
|
33
|
+
// adapter named, else one read from ACP's own kind and fields
|
|
34
|
+
export function toolOf(call = {}, cwd) {
|
|
35
|
+
const meta = picoMeta(call)
|
|
36
|
+
const extra = { ...(meta.bridged ? { bridged: true } : {}), ...(meta.subagent ? { subagent: meta.subagent } : {}) }
|
|
37
|
+
if (meta.tool?.name) return { name: meta.tool.name, args: meta.tool.args ?? {}, ...extra }
|
|
38
|
+
const input = call.rawInput ?? {}
|
|
39
|
+
const path = shortPath(callPath(call), cwd)
|
|
40
|
+
switch (call.kind) {
|
|
41
|
+
case 'execute': return { name: 'bash', args: { command: input.command ?? call.title }, ...extra }
|
|
42
|
+
case 'edit': return { name: 'edit', args: { path }, ...extra }
|
|
43
|
+
case 'delete': return { name: 'delete', args: { path }, ...extra }
|
|
44
|
+
case 'move': return { name: 'move', args: { path, ...(call.locations?.[1]?.path ? { to: shortPath(call.locations[1].path, cwd) } : {}) }, ...extra }
|
|
45
|
+
case 'read': return { name: 'read', args: { path }, ...extra }
|
|
46
|
+
case 'search': return { name: 'grep', args: { pattern: input.pattern ?? input.query ?? call.title, ...(path ? { path } : {}) }, ...extra }
|
|
47
|
+
case 'fetch': return { name: 'web_fetch', args: { url: input.url ?? call.title }, ...extra }
|
|
48
|
+
default: return { name: call.title || call.kind || 'tool', args: input, ...extra }
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// a change to a file, whose before and after rewind can restore
|
|
53
|
+
export const changesFile = (name) => ['edit', 'write', 'delete', 'move'].includes(name)
|
|
54
|
+
|
|
55
|
+
function blockText(block) {
|
|
56
|
+
if (!block) return ''
|
|
57
|
+
if (block.type === 'text') return block.text ?? ''
|
|
58
|
+
if (block.type === 'resource') return block.resource?.text ?? ''
|
|
59
|
+
if (block.type === 'resource_link') return block.uri ?? ''
|
|
60
|
+
if (block.type === 'image') return '[image]'
|
|
61
|
+
return ''
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// what a finished call returned, as text: what it said, else what it changed
|
|
65
|
+
export function resultText(call = {}) {
|
|
66
|
+
const items = call.content ?? []
|
|
67
|
+
const said = items.filter((item) => item.type === 'content').map((item) => blockText(item.content)).filter(Boolean).join('\n')
|
|
68
|
+
if (said) return said
|
|
69
|
+
const changed = items.filter((item) => item.type === 'diff').map((item) => `edited ${item.path}`).join('\n')
|
|
70
|
+
if (changed) return changed
|
|
71
|
+
const output = call.rawOutput
|
|
72
|
+
if (output == null) return ''
|
|
73
|
+
if (typeof output === 'string') return output
|
|
74
|
+
for (const key of ['output', 'result', 'error']) if (typeof output[key] === 'string') return output[key]
|
|
75
|
+
return JSON.stringify(output)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export const diffsOf = (call = {}) => (call.content ?? []).filter((item) => item.type === 'diff')
|
|
79
|
+
|
|
80
|
+
// pico usage from ACP's: input counted without what was cached, output
|
|
81
|
+
// without the thinking
|
|
82
|
+
export function usageOf(usage = {}) {
|
|
83
|
+
const cached = usage.cachedReadTokens || 0
|
|
84
|
+
const prompt = (usage.inputTokens || 0) + cached + (usage.cachedWriteTokens || 0)
|
|
85
|
+
const thought = usage.thoughtTokens || 0
|
|
86
|
+
const completion = (usage.outputTokens || 0) + thought
|
|
87
|
+
return { promptTokens: prompt, completionTokens: completion, totalTokens: prompt + completion, cachedTokens: cached, thoughtTokens: thought }
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// pico usage as ACP's
|
|
91
|
+
export function acpUsage(usage = {}) {
|
|
92
|
+
const cached = usage.cachedTokens || 0
|
|
93
|
+
const thought = usage.thoughtTokens || 0
|
|
94
|
+
return { inputTokens: Math.max(0, (usage.promptTokens || 0) - cached), cachedReadTokens: cached, outputTokens: Math.max(0, (usage.completionTokens || 0) - thought), thoughtTokens: thought, totalTokens: usage.totalTokens || 0 }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// one pico user message as ACP content blocks; `message` comes after
|
|
98
|
+
// pico's image preparation, which reads images into base64
|
|
99
|
+
export function userBlocks(message) {
|
|
100
|
+
if (typeof message.content === 'string') return [{ type: 'text', text: message.content }]
|
|
101
|
+
const blocks = []
|
|
102
|
+
for (const part of message.content ?? []) {
|
|
103
|
+
if (part.type === 'image' && part.source?.kind === 'base64') {
|
|
104
|
+
blocks.push({ type: 'image', data: part.source.data, mimeType: part.source.mediaType })
|
|
105
|
+
continue
|
|
106
|
+
}
|
|
107
|
+
const text = partText(part)
|
|
108
|
+
if (text) blocks.push({ type: 'text', text })
|
|
109
|
+
}
|
|
110
|
+
return blocks
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// ACP content blocks as a pico user message's content
|
|
114
|
+
export function picoContent(blocks = []) {
|
|
115
|
+
const parts = []
|
|
116
|
+
for (const block of blocks) {
|
|
117
|
+
if (block.type === 'text') parts.push({ type: 'text', text: block.text })
|
|
118
|
+
else if (block.type === 'image' && block.data) parts.push({ type: 'image', source: { kind: 'base64', mediaType: block.mimeType, data: block.data } })
|
|
119
|
+
else if (block.type === 'resource' && block.resource?.text != null) parts.push({ type: 'text', text: `<file path="${block.resource.uri}">\n${block.resource.text}\n</file>` })
|
|
120
|
+
else if (block.type === 'resource_link') parts.push({ type: 'text', text: `[file: ${block.uri}]` })
|
|
121
|
+
}
|
|
122
|
+
return parts.length === 1 && parts[0].type === 'text' ? parts[0].text : parts
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// a permission an agent asks for, answered as pico runs: allowed, once
|
|
126
|
+
export const allowOption = (options = []) => options.find((o) => o.kind === 'allow_once') ?? options.find((o) => o.kind === 'allow_always') ?? null
|
|
127
|
+
|
|
128
|
+
// an agent's question to the person, as pico's ask_user takes it
|
|
129
|
+
export function questionOf({ toolCall = {}, options = [] }) {
|
|
130
|
+
const input = toolCall.rawInput ?? {}
|
|
131
|
+
const question = input.question ?? input.Question ?? input.prompt ?? input.message ?? toolCall.title ?? 'The agent has a question.'
|
|
132
|
+
return { id: 'answer', question: String(question), type: 'single', options: options.map((o) => ({ label: o.name })), allowOther: false }
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// the option the person chose, from ask_user's answer
|
|
136
|
+
export function chosenOption(answer, options = []) {
|
|
137
|
+
const text = typeof answer === 'string' ? answer : JSON.stringify(answer ?? '')
|
|
138
|
+
return [...options].sort((a, b) => b.name.length - a.name.length).find((o) => text.includes(o.name)) ?? null
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// the select options a session offers: a model, a thinking level
|
|
142
|
+
const choices = (option) => (option?.options ?? []).flatMap((choice) => (Array.isArray(choice.options) ? choice.options : [choice]))
|
|
143
|
+
export const modelOption = (configOptions = []) => configOptions.find((o) => o.id === 'model' || o.category === 'model') ?? null
|
|
144
|
+
export const thoughtOption = (configOptions = []) => configOptions.find((o) => o.category === 'thought_level') ?? null
|
|
145
|
+
|
|
146
|
+
export function modelsOffered(configOptions) {
|
|
147
|
+
return choices(modelOption(configOptions)).filter((c) => c.value).map((c) => ({ id: String(c.value), label: c.name || String(c.value) }))
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// the thinking level to ask for, given pico's effort: the level of that
|
|
151
|
+
// name, or the nearest the model has
|
|
152
|
+
const LADDER = ['minimal', 'low', 'medium', 'high', 'xhigh', 'max']
|
|
153
|
+
export function thoughtValue(configOptions, effort) {
|
|
154
|
+
const option = thoughtOption(configOptions)
|
|
155
|
+
if (!option || !effort) return null
|
|
156
|
+
const values = choices(option).map((c) => String(c.value))
|
|
157
|
+
// the agent's own choice, where it offers one
|
|
158
|
+
if (effort === 'auto') return values.includes('auto') ? 'auto' : null
|
|
159
|
+
if (values.includes(effort)) return effort
|
|
160
|
+
const want = LADDER.indexOf(effort)
|
|
161
|
+
const ranked = values.filter((v) => LADDER.includes(v)).sort((a, b) => Math.abs(LADDER.indexOf(a) - want) - Math.abs(LADDER.indexOf(b) - want) || LADDER.indexOf(b) - LADDER.indexOf(a))
|
|
162
|
+
return ranked[0] ?? null
|
|
163
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# Antigravity engine
|
|
2
|
+
|
|
3
|
+
Runs a pico session's turns through Google's Antigravity agent, on the user's own Google AI plan, instead of through a model API.
|
|
4
|
+
|
|
5
|
+
## Why
|
|
6
|
+
|
|
7
|
+
A Google AI Pro or Ultra plan can't be used as an API key, and handing the Google sign-in to another program breaks Antigravity's terms. The supported way to use the plan from another app is to run Google's own, unmodified agent, `agy acp`, and talk to it over the Agent Client Protocol (ACP): the app sends prompts and reads what comes back, and agy signs in, keeps its login and talks to Google itself. This engine does that, so a pico session can use Antigravity's models with agy's own tools at plan cost. pico still owns the session: its log, transcript, peers, questions and host tools work the same as with any other model.
|
|
8
|
+
|
|
9
|
+
## How
|
|
10
|
+
|
|
11
|
+
Antigravity is one of the agents pico reaches over ACP (`../acp/README.md`). `agy acp` already speaks ACP, so the adapter passes it through with pico's rules applied, and the ACP engine plays pico's turns through it.
|
|
12
|
+
|
|
13
|
+
| File | Role |
|
|
14
|
+
| --- | --- |
|
|
15
|
+
| `adapter.js` | `agy acp` passed through: pico's instructions as agy's system prompt extension, each tool call labelled with the pico tool it amounts to, agy's questions marked for the person, one-question sessions removed from agy's history |
|
|
16
|
+
| `process.js` | What agy runs with: its arguments, an environment without API keys, the stand-in browser openers that catch the sign-in page |
|
|
17
|
+
| `engine.js` | The ACP engine over the adapter, with what pico tells agy |
|
|
18
|
+
| `models.js` | The `agy` command, whether it is signed in (`agy models`), and the model catalog |
|
|
19
|
+
| `conversations.js` | Removes the sessions pico opens only to sign in or answer one question from agy's history |
|
|
20
|
+
| `../sign-in/antigravity.js` | Signing agy in and out |
|
|
21
|
+
|
|
22
|
+
**Sign-in.** agy runs the Google sign-in itself, as in a terminal, and keeps its login where it always does, so one sign-in serves `agy` in a terminal and pico alike. The sign-in catches the page agy opens so a host can show it wherever the person is; from another device, the address the page ended on is handed back to agy's listener on this machine. A sign-in counts only once agy opens a session with it. pico never reads agy's login.
|
|
23
|
+
|
|
24
|
+
**Sessions.** As with any ACP agent: a turn whose history agy has seen sends only the new messages, any other history starts a fresh agy session from a transcript, and a restart resumes the saved session with `session/resume`. agy cannot fork a session, so a forked pico session starts its own from a transcript.
|
|
25
|
+
|
|
26
|
+
**Models.** The catalog is the model list agy reports when a session opens, kept in pico's home, with `agy models` filling in before any session has. The model and thinking level are session options.
|
|
27
|
+
|
|
28
|
+
## Rules
|
|
29
|
+
|
|
30
|
+
- **Plan only.** API keys and Google Cloud settings (`GEMINI_API_KEY`, `GOOGLE_API_KEY`, `GOOGLE_CLOUD_PROJECT` and the like) are removed from agy's environment, or agy would bill them instead.
|
|
31
|
+
- **No permission prompts.** agy runs with `--dangerously-skip-permissions`, as pico does. A question agy means for the person (a permission request whose call id starts `interaction_`) goes through pico's `ask_user`; any other permission is allowed once.
|
|
32
|
+
- **Compaction.** agy compacts its own context, so pico doesn't auto-compact these sessions. A manual compact summarizes with the same model in a session of its own.
|
|
33
|
+
- **Notes mid-turn** reach agy between tool rounds as a prompt sent while the turn runs, which agy folds into it.
|
|
34
|
+
|
|
35
|
+
## Not covered
|
|
36
|
+
|
|
37
|
+
- The plan's usage limits: agy reports them only through its own login, which pico doesn't read.
|
|
38
|
+
- Claude and GPT models: Google offers those through ACP only to its own apps.
|
|
39
|
+
|
|
40
|
+
## Checking it
|
|
41
|
+
|
|
42
|
+
`test/antigravity.test.js` runs the adapter against a stand-in agy program; no model is called.
|