picocode-core 0.9.209 → 0.9.211
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/catalog-snapshot.json +1 -1
- package/src/claude-code/README.md +43 -0
- package/src/claude-code/bridge.js +104 -0
- package/src/claude-code/cli.js +120 -0
- package/src/claude-code/engine.js +343 -0
- package/src/claude-code/mcp-server.js +48 -0
- package/src/claude-code/models.js +71 -0
- package/src/claude-code/translate.js +220 -0
- package/src/controller.js +27 -4
- package/src/engines.js +29 -0
- package/src/mcp.js +119 -47
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// The Claude Code models pico offers, and whether this machine can run
|
|
2
|
+
// them. They are reached through the local `claude` command and its own
|
|
3
|
+
// claude.ai sign-in, never through an API key.
|
|
4
|
+
|
|
5
|
+
import { execFile } from 'node:child_process'
|
|
6
|
+
import { accessSync, constants } from 'node:fs'
|
|
7
|
+
import { homedir } from 'node:os'
|
|
8
|
+
import { delimiter, join } from 'node:path'
|
|
9
|
+
import { promisify } from 'node:util'
|
|
10
|
+
import { claudeEnv } from './cli.js'
|
|
11
|
+
|
|
12
|
+
const exec = promisify(execFile)
|
|
13
|
+
|
|
14
|
+
export const CLAUDE_CODE_PROVIDER = 'claude-code'
|
|
15
|
+
|
|
16
|
+
// the CLI's model aliases always name the newest model of each family;
|
|
17
|
+
// every one of them has a 1M token context window
|
|
18
|
+
const FAMILIES = [
|
|
19
|
+
{ alias: 'fable', label: 'Fable' },
|
|
20
|
+
{ alias: 'opus', label: 'Opus' },
|
|
21
|
+
{ alias: 'sonnet', label: 'Sonnet' },
|
|
22
|
+
{ alias: 'haiku', label: 'Haiku' },
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
export function claudeCodeModels({ available = true } = {}) {
|
|
26
|
+
return FAMILIES.map(({ alias, label }) => ({
|
|
27
|
+
name: `${CLAUDE_CODE_PROVIDER}/${alias}`,
|
|
28
|
+
label: `${label} (Claude Code)`,
|
|
29
|
+
provider: CLAUDE_CODE_PROVIDER,
|
|
30
|
+
context: 1000000,
|
|
31
|
+
effort: true,
|
|
32
|
+
vision: true,
|
|
33
|
+
speed: false,
|
|
34
|
+
available,
|
|
35
|
+
keyHint: 'claude auth login',
|
|
36
|
+
}))
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// the alias the CLI takes for a pico model name
|
|
40
|
+
export function cliModel(name) {
|
|
41
|
+
return String(name).startsWith(`${CLAUDE_CODE_PROVIDER}/`) ? name.slice(CLAUDE_CODE_PROVIDER.length + 1) : name
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// the `claude` executable. A host started from a desktop launcher does not
|
|
45
|
+
// have the user's shell PATH, so Claude Code's own install locations are
|
|
46
|
+
// looked in too
|
|
47
|
+
export function claudeCommand(env = process.env) {
|
|
48
|
+
const candidates = [
|
|
49
|
+
...String(env.PATH ?? '').split(delimiter).filter(Boolean).map((dir) => join(dir, 'claude')),
|
|
50
|
+
join(homedir(), '.local', 'bin', 'claude'),
|
|
51
|
+
join(homedir(), '.claude', 'local', 'claude'),
|
|
52
|
+
]
|
|
53
|
+
for (const path of candidates) {
|
|
54
|
+
try { accessSync(path, constants.X_OK); return path } catch {}
|
|
55
|
+
}
|
|
56
|
+
return 'claude'
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// whether `claude` is installed and signed in to claude.ai. A machine with
|
|
60
|
+
// only an API key configured does not count: that is what pico's own
|
|
61
|
+
// Anthropic models are for
|
|
62
|
+
export async function claudeCodeStatus({ command = claudeCommand() } = {}) {
|
|
63
|
+
try {
|
|
64
|
+
const { stdout } = await exec(command, ['auth', 'status', '--json'], { env: claudeEnv(), timeout: 15000 })
|
|
65
|
+
const status = JSON.parse(stdout)
|
|
66
|
+
const subscribed = status.loggedIn === true && status.authMethod === 'claude.ai'
|
|
67
|
+
return { installed: true, connected: subscribed, email: subscribed ? status.email ?? null : null, plan: subscribed ? status.subscriptionType ?? null : null }
|
|
68
|
+
} catch (error) {
|
|
69
|
+
return { installed: error.code !== 'ENOENT', connected: false, email: null, plan: null }
|
|
70
|
+
}
|
|
71
|
+
}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
// Pure translation between Claude Code's stream-json and pico's shapes.
|
|
2
|
+
// Nothing here touches a process or the file system, so every rule about
|
|
3
|
+
// how a Claude turn becomes pico history, tool rows and usage is testable
|
|
4
|
+
// against recorded output.
|
|
5
|
+
|
|
6
|
+
import { createHash } from 'node:crypto'
|
|
7
|
+
import { isAbsolute, relative } from 'node:path'
|
|
8
|
+
import { makeDiff } from '../tools/diff.js'
|
|
9
|
+
import { makeWriteEdit } from '../reversible-edit.js'
|
|
10
|
+
import { toolResultOutput } from '../tools/recorder.js'
|
|
11
|
+
import { commitLabel, elementLabel, fileLabel, selectionLabel } from '../attachments.js'
|
|
12
|
+
|
|
13
|
+
// pico's own tools run inside Claude Code through the MCP bridge under
|
|
14
|
+
// this server name, so Claude sees them as mcp__pico__<name>
|
|
15
|
+
export const BRIDGE_SERVER = 'pico'
|
|
16
|
+
const BRIDGE_PREFIX = `mcp__${BRIDGE_SERVER}__`
|
|
17
|
+
|
|
18
|
+
// pico tools Claude Code already has its own version of; offering both
|
|
19
|
+
// would only make the model choose between equivalent tools
|
|
20
|
+
export const COVERED_TOOLS = new Set([
|
|
21
|
+
'read', 'write', 'edit', 'bash', 'glob', 'grep', 'view', 'shell_output', 'shell_kill', 'tool_result',
|
|
22
|
+
'agent_plan', 'agent_start', 'agent_list', 'agent_collect', 'agent_cancel', 'deliberate',
|
|
23
|
+
'skill', 'remember', 'recall',
|
|
24
|
+
])
|
|
25
|
+
|
|
26
|
+
const SEED_CHARS = 600000
|
|
27
|
+
const SEED_TOOL_CHARS = 2000
|
|
28
|
+
|
|
29
|
+
function shortPath(path, cwd) {
|
|
30
|
+
if (typeof path !== 'string' || !cwd || !isAbsolute(path)) return path
|
|
31
|
+
const rel = relative(cwd, path)
|
|
32
|
+
return rel && !rel.startsWith('..') && !isAbsolute(rel) ? rel : path
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Claude's tool calls under the names and argument shapes pico renders:
|
|
36
|
+
// a Bash call shows its command, an Edit its path and diff
|
|
37
|
+
export function picoTool(name, input = {}, cwd) {
|
|
38
|
+
if (name.startsWith(BRIDGE_PREFIX)) return { name: name.slice(BRIDGE_PREFIX.length), args: input, bridged: true }
|
|
39
|
+
const path = shortPath(input.file_path ?? input.notebook_path, cwd)
|
|
40
|
+
switch (name) {
|
|
41
|
+
case 'Bash': return { name: 'bash', args: { command: input.command, description: input.description, ...(input.run_in_background ? { background: true } : {}), ...(input.timeout ? { timeout: input.timeout } : {}) } }
|
|
42
|
+
case 'Read': return { name: 'read', args: { path, ...(input.offset != null ? { offset: input.offset } : {}), ...(input.limit != null ? { limit: input.limit } : {}) } }
|
|
43
|
+
case 'Edit': return { name: 'edit', args: { path, oldText: input.old_string, newText: input.new_string, ...(input.replace_all ? { replaceAll: true } : {}) } }
|
|
44
|
+
case 'MultiEdit': return { name: 'edit', args: { path, edits: input.edits } }
|
|
45
|
+
case 'Write': return { name: 'write', args: { path, content: input.content } }
|
|
46
|
+
case 'Glob': return { name: 'glob', args: { pattern: input.pattern, ...(input.path ? { path: shortPath(input.path, cwd) } : {}) } }
|
|
47
|
+
case 'Grep': return { name: 'grep', args: { ...input, ...(input.path ? { path: shortPath(input.path, cwd) } : {}) } }
|
|
48
|
+
case 'Task':
|
|
49
|
+
case 'Agent': return { name: 'Task', args: { description: input.description, prompt: input.prompt, ...(input.subagent_type ? { subagent_type: input.subagent_type } : {}) } }
|
|
50
|
+
default: return { name, args: input }
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function toolResultText(content) {
|
|
55
|
+
if (content == null) return ''
|
|
56
|
+
if (typeof content === 'string') return content
|
|
57
|
+
if (Array.isArray(content)) return content.map((part) => part.type === 'text' ? part.text : part.type === 'image' ? '[image]' : '').filter(Boolean).join('\n')
|
|
58
|
+
return JSON.stringify(content)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// what the transcript keeps for one finished Claude tool call: output,
|
|
62
|
+
// errors, and for file changes a diff plus the record rewind needs to undo
|
|
63
|
+
// them. `after` is the file as it stands once the call returned; a call
|
|
64
|
+
// that failed because the turn was interrupted shows as interrupted
|
|
65
|
+
export function toolEntry({ id, name, input }, block, extra, { cwd, after = null, interrupted = false } = {}) {
|
|
66
|
+
const { name: picoName, args } = picoTool(name, input, cwd)
|
|
67
|
+
const entry = {
|
|
68
|
+
callId: id,
|
|
69
|
+
name: picoName,
|
|
70
|
+
args,
|
|
71
|
+
title: typeof args.path === 'string' ? args.path : undefined,
|
|
72
|
+
description: args.description,
|
|
73
|
+
status: block.is_error ? (interrupted ? 'interrupted' : 'error') : 'done',
|
|
74
|
+
durationMs: null,
|
|
75
|
+
}
|
|
76
|
+
if (block.is_error && !interrupted) entry.error = toolResultText(block.content).replace(/^<tool_use_error>|<\/tool_use_error>$/g, '')
|
|
77
|
+
if (picoName === 'bash' && extra && typeof extra === 'object') {
|
|
78
|
+
entry.fullOutput = toolResultOutput('bash', extra)
|
|
79
|
+
if (extra.interrupted) entry.status = 'interrupted'
|
|
80
|
+
} else {
|
|
81
|
+
entry.fullOutput = toolResultText(block.content)
|
|
82
|
+
}
|
|
83
|
+
if (!block.is_error && extra && typeof extra === 'object' && typeof extra.filePath === 'string' && (picoName === 'edit' || picoName === 'write')) {
|
|
84
|
+
const before = typeof extra.originalFile === 'string' ? extra.originalFile : null
|
|
85
|
+
const now = after ?? (picoName === 'write' ? extra.content : null)
|
|
86
|
+
if (typeof now === 'string') {
|
|
87
|
+
const shown = shortPath(extra.filePath, cwd)
|
|
88
|
+
entry.diff = makeDiff(shown, before ?? '', now)
|
|
89
|
+
entry.revert = makeWriteEdit(extra.filePath, before ?? '', now, before !== null)
|
|
90
|
+
if (before === null) entry.created = true
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return entry
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// pico usage from one Claude API response; prompt counts every input
|
|
97
|
+
// token the request carried, cached or not, since that is its context size
|
|
98
|
+
export function usageOf(usage = {}) {
|
|
99
|
+
const cached = usage.cache_read_input_tokens || 0
|
|
100
|
+
const prompt = (usage.input_tokens || 0) + cached + (usage.cache_creation_input_tokens || 0)
|
|
101
|
+
const completion = usage.output_tokens || 0
|
|
102
|
+
return { promptTokens: prompt, completionTokens: completion, totalTokens: prompt + completion, cachedTokens: cached, thoughtTokens: usage.output_tokens_details?.thinking_tokens || 0 }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function addUsage(a, b) {
|
|
106
|
+
return {
|
|
107
|
+
promptTokens: a.promptTokens + b.promptTokens,
|
|
108
|
+
completionTokens: a.completionTokens + b.completionTokens,
|
|
109
|
+
totalTokens: a.totalTokens + b.totalTokens,
|
|
110
|
+
cachedTokens: a.cachedTokens + b.cachedTokens,
|
|
111
|
+
thoughtTokens: a.thoughtTokens + b.thoughtTokens,
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export const emptyUsage = () => ({ promptTokens: 0, completionTokens: 0, totalTokens: 0, cachedTokens: 0, thoughtTokens: 0 })
|
|
116
|
+
|
|
117
|
+
// ---- pico history to Claude input ----
|
|
118
|
+
|
|
119
|
+
// the messages a turn adds: everything after the last thing the model
|
|
120
|
+
// said. pico appends the user's message, system notes and peer input
|
|
121
|
+
// before a turn starts, so these trail the history
|
|
122
|
+
export function splitTurn(history) {
|
|
123
|
+
let at = history.length
|
|
124
|
+
while (at > 0 && history[at - 1].role === 'user') at--
|
|
125
|
+
return { prior: history.slice(0, at), input: history.slice(at) }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// a hash of what a conversation said, blind to what pico rewrites in place
|
|
129
|
+
// later: old tool results get elided or trimmed, so only their ids count
|
|
130
|
+
export function fingerprint(history) {
|
|
131
|
+
const hash = createHash('sha256')
|
|
132
|
+
for (const message of history) {
|
|
133
|
+
hash.update(message.role)
|
|
134
|
+
if (message.role === 'tool') hash.update(String(message.tool_call_id))
|
|
135
|
+
else hash.update(typeof message.content === 'string' ? message.content : JSON.stringify(message.content ?? ''))
|
|
136
|
+
for (const call of message.tool_calls ?? []) hash.update(String(call.id))
|
|
137
|
+
hash.update('\u0000')
|
|
138
|
+
}
|
|
139
|
+
return hash.digest('hex')
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function partText(part) {
|
|
143
|
+
if (part.type === 'text') return part.text
|
|
144
|
+
if (part.type === 'file') return fileLabel(part.path)
|
|
145
|
+
if (part.type === 'selection') return selectionLabel(part)
|
|
146
|
+
if (part.type === 'commit') return commitLabel(part)
|
|
147
|
+
if (part.type === 'element') return elementLabel(part)
|
|
148
|
+
return null
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// one pico user message as Claude content blocks; `hydrated` is the same
|
|
152
|
+
// message after pico's image preparation, which reads images into base64
|
|
153
|
+
export function userBlocks(message) {
|
|
154
|
+
if (typeof message.content === 'string') return [{ type: 'text', text: message.content }]
|
|
155
|
+
const blocks = []
|
|
156
|
+
for (const part of message.content ?? []) {
|
|
157
|
+
if (part.type === 'image' && part.source?.kind === 'base64') {
|
|
158
|
+
blocks.push({ type: 'image', source: { type: 'base64', media_type: part.source.mediaType, data: part.source.data } })
|
|
159
|
+
continue
|
|
160
|
+
}
|
|
161
|
+
const text = partText(part)
|
|
162
|
+
if (text) blocks.push({ type: 'text', text })
|
|
163
|
+
}
|
|
164
|
+
return blocks
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function messageText(message) {
|
|
168
|
+
if (typeof message.content === 'string') return message.content
|
|
169
|
+
return (message.content ?? []).map((part) => partText(part) ?? (part.type === 'image' ? '[image]' : '')).filter(Boolean).join('')
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// a conversation as plain text, for a model that cannot be handed the
|
|
173
|
+
// messages themselves. The most recent part is kept when it is too long
|
|
174
|
+
export function transcriptText(history) {
|
|
175
|
+
const lines = []
|
|
176
|
+
for (const message of history) {
|
|
177
|
+
if (message.role === 'user') lines.push(`User:\n${messageText(message)}`)
|
|
178
|
+
else if (message.role === 'assistant') {
|
|
179
|
+
if (message.content) lines.push(`Assistant:\n${typeof message.content === 'string' ? message.content : messageText(message)}`)
|
|
180
|
+
for (const call of message.tool_calls ?? []) lines.push(`Assistant called ${call.function.name}: ${call.function.arguments}`)
|
|
181
|
+
} else if (message.role === 'tool') {
|
|
182
|
+
const text = String(message.content ?? '')
|
|
183
|
+
lines.push(`Tool result:\n${text.length > SEED_TOOL_CHARS ? `${text.slice(0, SEED_TOOL_CHARS)}\n[clipped]` : text}`)
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
let body = lines.join('\n\n')
|
|
187
|
+
if (body.length > SEED_CHARS) body = `[earlier conversation omitted]\n\n${body.slice(-SEED_CHARS)}`
|
|
188
|
+
return body
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// a conversation Claude Code never saw (another model's, or one pico
|
|
192
|
+
// rewound, steered or compacted) as a transcript it can pick up from
|
|
193
|
+
export function seedText(history) {
|
|
194
|
+
return `[system notification] This conversation began before this Claude Code session started, in pico with another model or an earlier context. Its transcript follows so you can continue it. Treat it as history: do not redo work it shows as done, and do not reply to it directly; the newest messages after it are what to respond to.\n\n<transcript>\n${transcriptText(history)}\n</transcript>`
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// ---- pico tool schemas to JSON Schema, for the MCP bridge ----
|
|
198
|
+
|
|
199
|
+
function jsonProperty(prop) {
|
|
200
|
+
const out = { type: prop.type }
|
|
201
|
+
if (prop.description) out.description = prop.description
|
|
202
|
+
if (prop.enum) out.enum = prop.enum
|
|
203
|
+
if (prop.items) out.items = jsonProperty(prop.items)
|
|
204
|
+
if (prop.properties) {
|
|
205
|
+
out.properties = Object.fromEntries(Object.entries(prop.properties).map(([key, child]) => [key, jsonProperty(child)]))
|
|
206
|
+
if (prop.required) out.required = prop.required
|
|
207
|
+
}
|
|
208
|
+
return out
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export function inputSchema(schema = {}) {
|
|
212
|
+
if (schema.type === 'object' && schema.properties) return schema
|
|
213
|
+
const properties = {}
|
|
214
|
+
const required = []
|
|
215
|
+
for (const [key, prop] of Object.entries(schema)) {
|
|
216
|
+
properties[key] = jsonProperty(prop)
|
|
217
|
+
if (!prop.optional) required.push(key)
|
|
218
|
+
}
|
|
219
|
+
return { type: 'object', properties, ...(required.length ? { required } : {}) }
|
|
220
|
+
}
|
package/src/controller.js
CHANGED
|
@@ -13,6 +13,7 @@ import { deriveState, userEntries, rewindStats } from './derive.js'
|
|
|
13
13
|
import { appendPrompt } from './history.js'
|
|
14
14
|
import { runTurn, summarizeText, compactHistory, compactProgress } from './agent.js'
|
|
15
15
|
import { createAgentManager } from './agents.js'
|
|
16
|
+
import { engineFor, releaseEngines } from './engines.js'
|
|
16
17
|
import { automaticPeerName, createPeers } from './peers.js'
|
|
17
18
|
import { runDeliberation, validateDeliberation } from './deliberation.js'
|
|
18
19
|
import { deliberationsFromEvents } from './deliberation-history.js'
|
|
@@ -649,7 +650,7 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
|
|
|
649
650
|
const keepFrom = compactionKeepFrom(current, state.model.context)
|
|
650
651
|
let streamed = ''
|
|
651
652
|
try {
|
|
652
|
-
const raw = await compactRun({
|
|
653
|
+
const raw = await (engineFor(state.model)?.compact ?? compactRun)({
|
|
653
654
|
history: current.providerHistory,
|
|
654
655
|
modelName: state.model.name,
|
|
655
656
|
...(state.model.provider === 'codex' && { speed: speedApplies() ? state.speed : 'standard' }),
|
|
@@ -698,7 +699,7 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
|
|
|
698
699
|
}
|
|
699
700
|
|
|
700
701
|
function maybeAutoCompact() {
|
|
701
|
-
if (boot.autoCompact === false || state.busy || state.compacting) return
|
|
702
|
+
if (boot.autoCompact === false || engineFor(state.model)?.autoCompact === false || state.busy || state.compacting) return
|
|
702
703
|
const limit = state.model.context
|
|
703
704
|
const used = state.derived.lastPromptTokens
|
|
704
705
|
if (!limit || !used || state.derived.lastPromptModel !== state.model.name) return
|
|
@@ -709,6 +710,21 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
|
|
|
709
710
|
}
|
|
710
711
|
}
|
|
711
712
|
|
|
713
|
+
// what an engine (engines.js) is told about the session it runs a turn for
|
|
714
|
+
function engineHost(engine) {
|
|
715
|
+
return {
|
|
716
|
+
sessionId: state.session?.id ?? null,
|
|
717
|
+
cwd: boot.cwd,
|
|
718
|
+
env: boot.env,
|
|
719
|
+
contextFiles: boot.startupContext?.files ?? [],
|
|
720
|
+
engineState: savedEngineState(engine),
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
function savedEngineState(engine) {
|
|
725
|
+
return state.events.findLast((event) => event.type === 'engine_state' && event.data.engine === engine.name)?.data.state ?? null
|
|
726
|
+
}
|
|
727
|
+
|
|
712
728
|
async function refreshProjectIndexes() {
|
|
713
729
|
boot.skills = await createSkillIndex(boot.root, { host: boot.hostSkills ?? [] }).catch(() => boot.skills) ?? boot.skills
|
|
714
730
|
boot.commands = await createCommandIndex(boot.root).catch(() => boot.commands) ?? boot.commands
|
|
@@ -795,7 +811,8 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
|
|
|
795
811
|
})
|
|
796
812
|
} else if (event.type === 'tool_complete' || event.type === 'tool_error') {
|
|
797
813
|
boot.git.refresh()
|
|
798
|
-
|
|
814
|
+
// an engine may finish calls out of order, so match by id
|
|
815
|
+
const entry = recorder.entries.findLast((candidate) => candidate.callId === event.call.id)
|
|
799
816
|
updateOverlay((items) =>
|
|
800
817
|
items.map((item) =>
|
|
801
818
|
item.kind === 'tool' && item.callId === event.call.id
|
|
@@ -875,9 +892,10 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
|
|
|
875
892
|
reDerive()
|
|
876
893
|
}
|
|
877
894
|
sendAfterToolTriggered = false
|
|
895
|
+
const engine = engineFor(state.model)
|
|
878
896
|
let result
|
|
879
897
|
try {
|
|
880
|
-
result = await run({
|
|
898
|
+
result = await (engine?.run ?? run)({
|
|
881
899
|
history: state.derived.providerHistory,
|
|
882
900
|
tools,
|
|
883
901
|
recorder,
|
|
@@ -889,6 +907,7 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
|
|
|
889
907
|
signal: controller.signal,
|
|
890
908
|
onStream: streamHandler(recorder, controller),
|
|
891
909
|
beforeRequest: () => takeTurnNotes(controller.signal),
|
|
910
|
+
...(engine && { host: engineHost(engine) }),
|
|
892
911
|
})
|
|
893
912
|
} catch (err) {
|
|
894
913
|
abort = null
|
|
@@ -911,6 +930,9 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
|
|
|
911
930
|
}
|
|
912
931
|
if (result.usage) persist(makeEvent('usage', { model: state.model.name, usage: result.usage, lastPrompt: result.lastPromptTokens }))
|
|
913
932
|
if (result.interrupted && !sendAfterToolTriggered) persist(makeEvent('interrupt', {}))
|
|
933
|
+
if (engine && result.engineState && JSON.stringify(result.engineState) !== JSON.stringify(savedEngineState(engine))) {
|
|
934
|
+
persist(makeEvent('engine_state', { engine: engine.name, state: result.engineState }))
|
|
935
|
+
}
|
|
914
936
|
|
|
915
937
|
abort = null
|
|
916
938
|
state.overlay = []
|
|
@@ -1794,6 +1816,7 @@ export function createController({ boot, run = runTurn, compactRun = compactHist
|
|
|
1794
1816
|
}
|
|
1795
1817
|
await agents.collect(agents.list().filter(agent => ['queued', 'running'].includes(agent.status)).map(agent => agent.id))
|
|
1796
1818
|
await disconnectPeers()
|
|
1819
|
+
if (state.session) releaseEngines(state.session.id)
|
|
1797
1820
|
await state.session?.flush()
|
|
1798
1821
|
await boot.mcp.terminateAll()
|
|
1799
1822
|
boot.git?.dispose?.()
|
package/src/engines.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Turn engines. A turn normally runs through runTurn, which calls the
|
|
2
|
+
// model's provider API with pico's tools and history. An engine replaces
|
|
3
|
+
// that for the models of one provider: it takes the same turn arguments,
|
|
4
|
+
// emits the same stream events and returns provider-shaped messages, so
|
|
5
|
+
// the controller, session log, transcript, peers and tools work the same
|
|
6
|
+
// whichever engine ran the turn.
|
|
7
|
+
//
|
|
8
|
+
// An engine is { name, run, compact, autoCompact?, release? }. `run` also
|
|
9
|
+
// receives `host` (the pico session id, cwd, env, context files, and the
|
|
10
|
+
// engine's own state saved with the session) and may return `engineState`
|
|
11
|
+
// to be saved. `release(sessionId)` frees what an engine holds for a
|
|
12
|
+
// session that has shut down.
|
|
13
|
+
|
|
14
|
+
import { createClaudeCodeEngine } from './claude-code/engine.js'
|
|
15
|
+
import { CLAUDE_CODE_PROVIDER } from './claude-code/models.js'
|
|
16
|
+
|
|
17
|
+
const factories = { [CLAUDE_CODE_PROVIDER]: createClaudeCodeEngine }
|
|
18
|
+
const engines = new Map()
|
|
19
|
+
|
|
20
|
+
export function engineFor(model) {
|
|
21
|
+
const provider = model?.provider
|
|
22
|
+
if (!factories[provider]) return null
|
|
23
|
+
if (!engines.has(provider)) engines.set(provider, factories[provider]())
|
|
24
|
+
return engines.get(provider)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function releaseEngines(sessionId) {
|
|
28
|
+
for (const engine of engines.values()) engine.release?.(sessionId)
|
|
29
|
+
}
|
package/src/mcp.js
CHANGED
|
@@ -79,8 +79,11 @@ async function readJson(file, fallback) {
|
|
|
79
79
|
}
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
-
|
|
83
|
-
|
|
82
|
+
// the global file: every project's servers, and the ones switched off
|
|
83
|
+
// everywhere unless a project switches them back on
|
|
84
|
+
export async function readRegistry() {
|
|
85
|
+
const registry = await readJson(globalMcpFile(), {})
|
|
86
|
+
return { servers: registry.servers || {}, disabled: registry.disabled || {} }
|
|
84
87
|
}
|
|
85
88
|
|
|
86
89
|
export async function writeRegistry(registry) {
|
|
@@ -88,6 +91,8 @@ export async function writeRegistry(registry) {
|
|
|
88
91
|
await writeFile(globalMcpFile(), JSON.stringify(registry, null, 2) + '\n')
|
|
89
92
|
}
|
|
90
93
|
|
|
94
|
+
// a project's file: its own servers, and a switch per server where the
|
|
95
|
+
// project differs from the global setting (true off, false on)
|
|
91
96
|
export async function readProjectConfig(root) {
|
|
92
97
|
const config = await readJson(projectMcpFile(root), {})
|
|
93
98
|
return { disabled: config.disabled || {}, servers: config.servers || {} }
|
|
@@ -120,21 +125,20 @@ export async function createMcpTransport(command) {
|
|
|
120
125
|
}
|
|
121
126
|
|
|
122
127
|
export async function createMcpRuntime({ root, onChange = () => {} }) {
|
|
123
|
-
|
|
124
|
-
|
|
128
|
+
let registry = await readRegistry()
|
|
129
|
+
let projectConfig = await readProjectConfig(root)
|
|
125
130
|
const servers = new Map()
|
|
131
|
+
// switches for this session alone, never written anywhere
|
|
132
|
+
const sessionSettings = new Map()
|
|
133
|
+
|
|
134
|
+
const projectSetting = (name) => (Object.hasOwn(projectConfig.disabled, name) ? !projectConfig.disabled[name] : null)
|
|
135
|
+
const globalEnabled = (name) => !registry.disabled[name]
|
|
136
|
+
// the session's switch wins, then the project's, then the global one
|
|
137
|
+
const effective = (name) => sessionSettings.has(name) ? sessionSettings.get(name) : projectSetting(name) ?? globalEnabled(name)
|
|
126
138
|
|
|
127
139
|
const register = (name, command, scope) => {
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
command,
|
|
131
|
-
scope,
|
|
132
|
-
enabled: !projectConfig.disabled[name],
|
|
133
|
-
status: projectConfig.disabled[name] ? 'disabled' : 'idle',
|
|
134
|
-
error: null,
|
|
135
|
-
connection: null,
|
|
136
|
-
transport: null,
|
|
137
|
-
})
|
|
140
|
+
const enabled = effective(name)
|
|
141
|
+
servers.set(name, { name, command, scope, enabled, status: enabled ? 'idle' : 'disabled', error: null, connection: null, transport: null })
|
|
138
142
|
}
|
|
139
143
|
for (const [name, command] of Object.entries(registry.servers)) register(name, command, 'global')
|
|
140
144
|
for (const [name, command] of Object.entries(projectConfig.servers)) register(name, command, 'project')
|
|
@@ -146,13 +150,21 @@ export async function createMcpRuntime({ root, onChange = () => {} }) {
|
|
|
146
150
|
server.error = null
|
|
147
151
|
onChange()
|
|
148
152
|
try {
|
|
149
|
-
|
|
150
|
-
server.
|
|
153
|
+
const transport = await createMcpTransport(server.command)
|
|
154
|
+
server.transport = transport
|
|
155
|
+
const connection = await connectMCP({
|
|
151
156
|
name,
|
|
152
|
-
transport: () =>
|
|
157
|
+
transport: () => transport,
|
|
153
158
|
})
|
|
159
|
+
// switched off or replaced while it was connecting
|
|
160
|
+
if (servers.get(name) !== server || !server.enabled || server.transport !== transport) {
|
|
161
|
+
await connection.close().catch(() => {})
|
|
162
|
+
return
|
|
163
|
+
}
|
|
164
|
+
server.connection = connection
|
|
154
165
|
server.status = 'connected'
|
|
155
166
|
} catch (err) {
|
|
167
|
+
if (servers.get(name) !== server || !server.enabled) return
|
|
156
168
|
server.status = 'error'
|
|
157
169
|
server.error = String(err.message || err).slice(0, 300)
|
|
158
170
|
server.connection = null
|
|
@@ -163,10 +175,28 @@ export async function createMcpRuntime({ root, onChange = () => {} }) {
|
|
|
163
175
|
|
|
164
176
|
async function disconnect(name) {
|
|
165
177
|
const server = servers.get(name)
|
|
166
|
-
if (server
|
|
167
|
-
|
|
168
|
-
|
|
178
|
+
if (!server) return
|
|
179
|
+
const connection = server.connection
|
|
180
|
+
server.connection = null
|
|
181
|
+
server.transport = null
|
|
182
|
+
if (connection) await connection.close().catch(() => {})
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// brings one server in line with its switches; connecting and closing
|
|
186
|
+
// run in the background, so nothing waits on a slow server
|
|
187
|
+
function apply(name) {
|
|
188
|
+
const server = servers.get(name)
|
|
189
|
+
if (!server) return
|
|
190
|
+
const enabled = effective(name)
|
|
191
|
+
if (enabled === server.enabled && (enabled ? server.status !== 'disabled' : true)) return
|
|
192
|
+
server.enabled = enabled
|
|
193
|
+
if (enabled) connect(name).catch(() => {})
|
|
194
|
+
else {
|
|
195
|
+
server.status = 'disabled'
|
|
196
|
+
server.error = null
|
|
197
|
+
disconnect(name).catch(() => {})
|
|
169
198
|
}
|
|
199
|
+
onChange()
|
|
170
200
|
}
|
|
171
201
|
|
|
172
202
|
return {
|
|
@@ -177,18 +207,59 @@ export async function createMcpRuntime({ root, onChange = () => {} }) {
|
|
|
177
207
|
}
|
|
178
208
|
return Promise.allSettled(pending)
|
|
179
209
|
},
|
|
210
|
+
// reads both files again and follows them: servers added, removed or
|
|
211
|
+
// changed elsewhere, and switches flipped in another session
|
|
212
|
+
async sync() {
|
|
213
|
+
registry = await readRegistry()
|
|
214
|
+
projectConfig = await readProjectConfig(root)
|
|
215
|
+
const wanted = new Map([
|
|
216
|
+
...Object.entries(registry.servers).map(([name, command]) => [name, { command, scope: 'global' }]),
|
|
217
|
+
...Object.entries(projectConfig.servers).map(([name, command]) => [name, { command, scope: 'project' }]),
|
|
218
|
+
])
|
|
219
|
+
for (const name of [...servers.keys()]) {
|
|
220
|
+
if (wanted.has(name)) continue
|
|
221
|
+
disconnect(name).catch(() => {})
|
|
222
|
+
servers.delete(name)
|
|
223
|
+
}
|
|
224
|
+
for (const [name, { command, scope }] of wanted) {
|
|
225
|
+
const server = servers.get(name)
|
|
226
|
+
if (!server) {
|
|
227
|
+
register(name, command, scope)
|
|
228
|
+
if (servers.get(name).enabled) connect(name).catch(() => {})
|
|
229
|
+
continue
|
|
230
|
+
}
|
|
231
|
+
server.scope = scope
|
|
232
|
+
if (server.command !== command) {
|
|
233
|
+
server.command = command
|
|
234
|
+
disconnect(name).catch(() => {})
|
|
235
|
+
server.status = server.enabled ? 'idle' : 'disabled'
|
|
236
|
+
if (server.enabled) connect(name).catch(() => {})
|
|
237
|
+
}
|
|
238
|
+
apply(name)
|
|
239
|
+
}
|
|
240
|
+
onChange()
|
|
241
|
+
},
|
|
242
|
+
// on or off for this session only; null follows the project and global
|
|
243
|
+
setSessionEnabled(name, enabled) {
|
|
244
|
+
if (enabled === null || enabled === undefined) sessionSettings.delete(name)
|
|
245
|
+
else sessionSettings.set(name, !!enabled)
|
|
246
|
+
apply(name)
|
|
247
|
+
},
|
|
180
248
|
async add(name, command, scope = 'global') {
|
|
181
249
|
if (scope === 'project') {
|
|
182
250
|
const config = await readProjectConfig(root)
|
|
183
251
|
config.servers[name] = command
|
|
184
252
|
await writeProjectConfig(root, config)
|
|
253
|
+
projectConfig = config
|
|
185
254
|
} else {
|
|
186
|
-
const
|
|
187
|
-
|
|
188
|
-
await writeRegistry(
|
|
255
|
+
const next = await readRegistry()
|
|
256
|
+
next.servers[name] = command
|
|
257
|
+
await writeRegistry(next)
|
|
258
|
+
registry = next
|
|
189
259
|
}
|
|
190
|
-
|
|
191
|
-
await connect(name)
|
|
260
|
+
register(name, command, scope)
|
|
261
|
+
if (servers.get(name).enabled) await connect(name)
|
|
262
|
+
else onChange()
|
|
192
263
|
},
|
|
193
264
|
async update(name, command) {
|
|
194
265
|
const server = servers.get(name)
|
|
@@ -197,10 +268,12 @@ export async function createMcpRuntime({ root, onChange = () => {} }) {
|
|
|
197
268
|
const config = await readProjectConfig(root)
|
|
198
269
|
config.servers[name] = command
|
|
199
270
|
await writeProjectConfig(root, config)
|
|
271
|
+
projectConfig = config
|
|
200
272
|
} else {
|
|
201
|
-
const
|
|
202
|
-
|
|
203
|
-
await writeRegistry(
|
|
273
|
+
const next = await readRegistry()
|
|
274
|
+
next.servers[name] = command
|
|
275
|
+
await writeRegistry(next)
|
|
276
|
+
registry = next
|
|
204
277
|
}
|
|
205
278
|
await disconnect(name)
|
|
206
279
|
server.command = command
|
|
@@ -215,34 +288,30 @@ export async function createMcpRuntime({ root, onChange = () => {} }) {
|
|
|
215
288
|
const config = await readProjectConfig(root)
|
|
216
289
|
delete config.servers[name]
|
|
217
290
|
await writeProjectConfig(root, config)
|
|
291
|
+
projectConfig = config
|
|
218
292
|
} else {
|
|
219
|
-
const
|
|
220
|
-
delete
|
|
221
|
-
|
|
293
|
+
const next = await readRegistry()
|
|
294
|
+
delete next.servers[name]
|
|
295
|
+
delete next.disabled[name]
|
|
296
|
+
await writeRegistry(next)
|
|
297
|
+
registry = next
|
|
222
298
|
}
|
|
223
299
|
await disconnect(name)
|
|
224
300
|
servers.delete(name)
|
|
225
301
|
onChange()
|
|
226
302
|
},
|
|
303
|
+
// the project's switch: off here, or back to on (overriding a global off)
|
|
227
304
|
async toggle(name) {
|
|
228
305
|
const server = servers.get(name)
|
|
229
306
|
if (!server) return
|
|
230
307
|
const config = await readProjectConfig(root)
|
|
231
|
-
if (server.enabled)
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
await writeProjectConfig(root, config)
|
|
239
|
-
disconnect(name).catch(() => {})
|
|
240
|
-
} else {
|
|
241
|
-
server.enabled = true
|
|
242
|
-
delete config.disabled[name]
|
|
243
|
-
await writeProjectConfig(root, config)
|
|
244
|
-
await connect(name)
|
|
245
|
-
}
|
|
308
|
+
if (server.enabled) config.disabled[name] = true
|
|
309
|
+
else if (globalEnabled(name)) delete config.disabled[name]
|
|
310
|
+
else config.disabled[name] = false
|
|
311
|
+
await writeProjectConfig(root, config)
|
|
312
|
+
projectConfig = config
|
|
313
|
+
sessionSettings.delete(name)
|
|
314
|
+
apply(name)
|
|
246
315
|
},
|
|
247
316
|
reconnect(name) {
|
|
248
317
|
return disconnect(name).then(() => connect(name))
|
|
@@ -253,6 +322,9 @@ export async function createMcpRuntime({ root, onChange = () => {} }) {
|
|
|
253
322
|
command: s.command,
|
|
254
323
|
scope: s.scope,
|
|
255
324
|
enabled: s.enabled,
|
|
325
|
+
globalEnabled: globalEnabled(s.name),
|
|
326
|
+
projectEnabled: projectSetting(s.name),
|
|
327
|
+
sessionEnabled: sessionSettings.has(s.name) ? sessionSettings.get(s.name) : null,
|
|
256
328
|
status: s.status,
|
|
257
329
|
error: s.error,
|
|
258
330
|
toolCount: s.connection?.tools.length || 0,
|
|
@@ -261,7 +333,7 @@ export async function createMcpRuntime({ root, onChange = () => {} }) {
|
|
|
261
333
|
},
|
|
262
334
|
tools() {
|
|
263
335
|
return [...servers.values()]
|
|
264
|
-
.filter((s) => s.connection)
|
|
336
|
+
.filter((s) => s.connection && s.enabled)
|
|
265
337
|
.flatMap((s) => s.connection.tools)
|
|
266
338
|
},
|
|
267
339
|
closeAll() {
|