vectorbench 0.0.0-stage → 3.0.2
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/.env.example +10 -0
- package/LICENSE +201 -0
- package/NOTICE +49 -0
- package/README.md +164 -2
- package/bench.config.mjs +255 -0
- package/bin/vectorbench.mjs +68 -0
- package/harness/Dockerfile +104 -0
- package/harness/adapters/chat.mjs +192 -0
- package/harness/adapters/index.mjs +77 -0
- package/harness/adapters/interactions.mjs +212 -0
- package/harness/adapters/messages.mjs +190 -0
- package/harness/adapters/responses.mjs +179 -0
- package/harness/box/README.md +46 -0
- package/harness/box/check.mjs +18 -0
- package/harness/box/tools.py +638 -0
- package/harness/box/vb3d.py +556 -0
- package/harness/claude-code.mjs +629 -0
- package/harness/codex-account.mjs +122 -0
- package/harness/codex.mjs +933 -0
- package/harness/grok-build.mjs +233 -0
- package/harness/loop.mjs +114 -0
- package/harness/prices.mjs +30 -0
- package/harness/request.mjs +155 -0
- package/harness/sandbox.mjs +77 -0
- package/package.json +76 -4
- package/scripts/doctor.mjs +113 -0
- package/scripts/harness.mjs +547 -0
- package/scripts/partner.mjs +140 -0
- package/scripts/zip.mjs +77 -0
- package/src/model-apis.js +516 -0
- package/worker/svg.js +350 -0
|
@@ -0,0 +1,629 @@
|
|
|
1
|
+
// The Anthropic models with tools on the owner's Claude subscription: Claude
|
|
2
|
+
// Code's headless mode asks the model, and the one tool is ours, served from
|
|
3
|
+
// this process over MCP, so the model gets the same request, the same tool,
|
|
4
|
+
// the same sandbox and the same budget as harness/loop.mjs gives the others.
|
|
5
|
+
//
|
|
6
|
+
// Why an MCP server inside this process (HTTP on 127.0.0.1, a free port, a
|
|
7
|
+
// random path) and not one Claude Code spawns: everything the budget needs is
|
|
8
|
+
// here already. The runner reads Claude Code's stream-json output, so it sees
|
|
9
|
+
// every reply as it ends; the tool call arrives with the id of the tool_use
|
|
10
|
+
// block it answers (`_meta["claudecode/toolUseId"]`), so each result carries
|
|
11
|
+
// the right reply number, and the run can be stopped between a reply's last
|
|
12
|
+
// result and the next request.
|
|
13
|
+
//
|
|
14
|
+
// The model sees the tool as `mcp__vb__bash` (Claude Code prefixes MCP tools
|
|
15
|
+
// with `mcp__<server>__`), with our description and input schema. Claude
|
|
16
|
+
// Code's own tools, settings, hooks, skills, CLAUDE.md files, memory and
|
|
17
|
+
// other MCP servers are all switched off; the init event, kept as the first
|
|
18
|
+
// line of `raw`, records what the session actually had.
|
|
19
|
+
//
|
|
20
|
+
// What Claude Code still sends that our loop does not (seen on 2.1.325 by
|
|
21
|
+
// logging its requests): a short system prompt of its own ("You are a Claude
|
|
22
|
+
// agent, built on Anthropic's Claude Agent SDK." and a billing line, which a
|
|
23
|
+
// subscription request has to carry), a system-reminder before our request
|
|
24
|
+
// with the account's email address, and a system turn after it with the
|
|
25
|
+
// working directory (an empty temp folder), platform, OS, the model's name
|
|
26
|
+
// and today's date. If a reply hits the output cap, Claude Code asks the
|
|
27
|
+
// model to resume in its own words.
|
|
28
|
+
|
|
29
|
+
import { spawn } from 'node:child_process';
|
|
30
|
+
import { randomBytes } from 'node:crypto';
|
|
31
|
+
import { mkdtemp, rm } from 'node:fs/promises';
|
|
32
|
+
import { createServer } from 'node:http';
|
|
33
|
+
import { tmpdir } from 'node:os';
|
|
34
|
+
import { join } from 'node:path';
|
|
35
|
+
import { ProviderError } from '../src/model-apis.js';
|
|
36
|
+
import { budgetLine, resultText } from './loop.mjs';
|
|
37
|
+
import { cutOff, noCommand } from './request.mjs';
|
|
38
|
+
|
|
39
|
+
const SERVER = 'vb';
|
|
40
|
+
const ENDED = { tool_use: 'calls', end_turn: 'complete', refusal: 'refused' };
|
|
41
|
+
// A tool call is answered only once stdout has shown its reply whole; this
|
|
42
|
+
// long for the pipe to catch up is far more than it ever needs.
|
|
43
|
+
const CATCH_UP_MS = 60_000;
|
|
44
|
+
// How far past the time budget a run may go (a long last reply, retries)
|
|
45
|
+
// before it is taken for stuck.
|
|
46
|
+
const GRACE_MINUTES = 30;
|
|
47
|
+
|
|
48
|
+
/** The plan's weekly use as Claude Code last reported it (0..1), for every run in this process. */
|
|
49
|
+
export const plan = { weeklyUse: 0, ceiling: Number(process.env.CLAUDE_USAGE_CEILING ?? 0.9) };
|
|
50
|
+
|
|
51
|
+
/** The name the model calls our tool by. */
|
|
52
|
+
export const toolName = (tool) => `mcp__${SERVER}__${tool.name}`;
|
|
53
|
+
|
|
54
|
+
/** What the Messages adapter makes of a reply's usage: input includes what the cache held and took. */
|
|
55
|
+
function usageOf(counts = {}) {
|
|
56
|
+
const cached = counts.cache_read_input_tokens ?? 0;
|
|
57
|
+
return {
|
|
58
|
+
input: (counts.input_tokens ?? 0) + (counts.cache_creation_input_tokens ?? 0) + cached,
|
|
59
|
+
output: counts.output_tokens ?? 0,
|
|
60
|
+
cached,
|
|
61
|
+
reasoning: counts.output_tokens_details?.thinking_tokens ?? 0,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** A call's arguments read as strictly as harness/adapters/messages.mjs reads them. */
|
|
66
|
+
function readArguments(input) {
|
|
67
|
+
if (input === null || typeof input !== 'object' || Array.isArray(input))
|
|
68
|
+
return { error: 'The arguments of that call were not a JSON object, so nothing was run. The tool takes {"command": "..."}.' };
|
|
69
|
+
if (typeof input.command !== 'string') return { error: 'That call had no "command" string, so nothing was run. The tool takes {"command": "..."}.' };
|
|
70
|
+
return { command: input.command };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* What differs between the agents that speak this stream format. Claude Code
|
|
75
|
+
* is the default; harness/grok-build.mjs passes its own.
|
|
76
|
+
*/
|
|
77
|
+
const CLAUDE_CODE = {
|
|
78
|
+
by: 'claude-code',
|
|
79
|
+
name: 'Claude Code',
|
|
80
|
+
/** The tools a session may offer the model. */
|
|
81
|
+
allowed: (tool) => [toolName(tool)],
|
|
82
|
+
/** Whether our tool has to be in the session's first list of tools. */
|
|
83
|
+
listsOurTool: true,
|
|
84
|
+
/** Whether `apiKeySource` says the plan pays, not a key. */
|
|
85
|
+
onPlan: (source) => !source || source === 'none',
|
|
86
|
+
/** A tool_use block's arguments for our tool, or null when the call is one the agent answers itself. */
|
|
87
|
+
unwrap: (block, input) => input,
|
|
88
|
+
/** Whether the agent runs a call as soon as its block is whole, before the reply has ended. */
|
|
89
|
+
eager: false,
|
|
90
|
+
};
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* One run's state, fed the agent's stream-json events (`handle`) and our
|
|
94
|
+
* tool's calls (`call`). It decides when the run is over, the way loop.mjs
|
|
95
|
+
* does, and calls `end()` once when it is; `say(text)` sends a user message.
|
|
96
|
+
*/
|
|
97
|
+
export function session({ tool, sandbox, limits, say, end, clock = Date.now, agent = CLAUDE_CODE }) {
|
|
98
|
+
const startedAt = clock();
|
|
99
|
+
const replies = [];
|
|
100
|
+
const owners = new Map(); // tool_use id → its reply
|
|
101
|
+
const raw = [];
|
|
102
|
+
const waiters = new Set();
|
|
103
|
+
let current = null;
|
|
104
|
+
let init = null;
|
|
105
|
+
let misses = 0;
|
|
106
|
+
let looks = 0;
|
|
107
|
+
let submitted = false;
|
|
108
|
+
let exit = null;
|
|
109
|
+
let failure = null;
|
|
110
|
+
let commands = Promise.resolve(); // one command at a time, in the order called
|
|
111
|
+
|
|
112
|
+
const poke = () => {
|
|
113
|
+
for (const waiter of waiters) waiter();
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
const finish = (how) => {
|
|
117
|
+
if (exit || failure) return;
|
|
118
|
+
exit = how;
|
|
119
|
+
poke();
|
|
120
|
+
end();
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
const fail = (error) => {
|
|
124
|
+
if (exit || failure) return;
|
|
125
|
+
failure = error;
|
|
126
|
+
poke();
|
|
127
|
+
end();
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
// The loop's check before it asks again.
|
|
131
|
+
const overBudget = () => {
|
|
132
|
+
if (replies.length >= limits.replies) finish('replies');
|
|
133
|
+
else if (clock() - startedAt >= limits.minutes * 60000) finish('time');
|
|
134
|
+
return Boolean(exit);
|
|
135
|
+
};
|
|
136
|
+
|
|
137
|
+
// Every call of a finished reply has its result: where the loop would ask again.
|
|
138
|
+
const settle = (reply) => {
|
|
139
|
+
if (exit || failure || !reply.stopped) return;
|
|
140
|
+
// A reply that only used the agent's own tools: the agent asks again once they are answered.
|
|
141
|
+
if (!reply.calls.length && reply.own.length && reply.own.every((id) => reply.results.has(id))) return void overBudget();
|
|
142
|
+
if (!reply.calls.length) return;
|
|
143
|
+
if (reply.calls.some((call) => !reply.results.has(call.id))) return;
|
|
144
|
+
if (submitted) finish('submitted');
|
|
145
|
+
else overBudget();
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
function started(message) {
|
|
149
|
+
if (exit || failure) return;
|
|
150
|
+
// Claude Code asked again after the budget was spent: we were too slow to stop it.
|
|
151
|
+
if (replies.length >= limits.replies) {
|
|
152
|
+
raw.push({ type: 'harness', text: `stopped a request past the budget (${message.id})` });
|
|
153
|
+
finish('replies');
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
current = { n: replies.length + 1, id: message.id ?? null, model: message.model ?? null, blocks: [], json: [], stop: null, counts: message.usage ?? {}, calls: [], uses: [], own: [], results: new Map(), notes: [], stopped: false };
|
|
157
|
+
replies.push(current);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// The call a tool_use block makes of our tool, or null when the agent answers it itself.
|
|
161
|
+
function callOf(reply, index) {
|
|
162
|
+
const block = reply.blocks[index];
|
|
163
|
+
let input = block.input ?? {};
|
|
164
|
+
if (reply.json[index]) {
|
|
165
|
+
try {
|
|
166
|
+
input = JSON.parse(reply.json[index]);
|
|
167
|
+
} catch {
|
|
168
|
+
block.partial_json = reply.json[index];
|
|
169
|
+
return { id: block.id, error: `The arguments of that call were not valid JSON, so nothing was run. They began: ${reply.json[index].slice(0, 200)}` };
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
block.input = input;
|
|
173
|
+
const ours = agent.unwrap(block, input, tool);
|
|
174
|
+
if (ours === null) return null;
|
|
175
|
+
const read = readArguments(ours);
|
|
176
|
+
return read.error ? { id: block.id, error: read.error } : { id: block.id, command: read.command };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// An eager agent calls us when the block is whole: the call is known then, with the reply still open.
|
|
180
|
+
function blockEnded(reply, index) {
|
|
181
|
+
if (!agent.eager || reply.blocks[index]?.type !== 'tool_use') return;
|
|
182
|
+
const call = callOf(reply, index);
|
|
183
|
+
if (!call) return;
|
|
184
|
+
reply.all = [...(reply.all ?? []), call];
|
|
185
|
+
reply.calls = reply.all;
|
|
186
|
+
reply.budget ??= budgetLine(reply.n, startedAt, limits, clock());
|
|
187
|
+
poke();
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function stopped(reply) {
|
|
191
|
+
reply.stopped = true;
|
|
192
|
+
reply.at = new Date(clock()).toISOString();
|
|
193
|
+
reply.ended = ENDED[reply.stop] ?? 'truncated';
|
|
194
|
+
reply.budget ??= budgetLine(reply.n, startedAt, limits, clock());
|
|
195
|
+
const calls = [];
|
|
196
|
+
reply.own = [];
|
|
197
|
+
reply.blocks.forEach((block, index) => {
|
|
198
|
+
if (block?.type !== 'tool_use') return;
|
|
199
|
+
const call = callOf(reply, index);
|
|
200
|
+
if (call) calls.push(call);
|
|
201
|
+
else reply.own.push(block.id);
|
|
202
|
+
});
|
|
203
|
+
reply.uses = calls.map((call) => call.id);
|
|
204
|
+
reply.all = calls;
|
|
205
|
+
// As in the Messages adapter: only a reply that stopped to call the tool has calls to run.
|
|
206
|
+
reply.calls = reply.ended === 'calls' ? calls : [];
|
|
207
|
+
raw.push({ type: 'reply', id: reply.id, model: reply.model, stop_reason: reply.stop, usage: reply.counts, content: reply.blocks.filter(Boolean) });
|
|
208
|
+
|
|
209
|
+
if (reply.ended === 'refused') return finish('refused');
|
|
210
|
+
if (reply.ended === 'truncated')
|
|
211
|
+
reply.notes.push({ role: 'harness', by: agent.by, text: `The reply hit the output cap. ${agent.name} goes on with such a turn itself, asking the model in its own words to resume.` });
|
|
212
|
+
if (reply.own.length) reply.notes.push({ role: 'harness', by: agent.by, text: `This reply used ${agent.name}'s own tools (${reply.blocks.filter((block) => reply.own.includes(block?.id)).map((block) => block.name).join(', ')}), which ${agent.name} answered itself.` });
|
|
213
|
+
if (reply.calls.length) misses = 0;
|
|
214
|
+
// A reply spent on the agent's own tools ran no command, but it is not a reply without a call.
|
|
215
|
+
else if (reply.own.length && reply.ended === 'calls') poke();
|
|
216
|
+
else if (++misses >= limits.misses) return finish('no-commands');
|
|
217
|
+
poke();
|
|
218
|
+
settle(reply);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function streamed(event) {
|
|
222
|
+
if (event.type === 'message_start') return started(event.message ?? {});
|
|
223
|
+
const reply = current;
|
|
224
|
+
if (!reply || reply.stopped) return;
|
|
225
|
+
if (event.type === 'content_block_start') {
|
|
226
|
+
reply.blocks[event.index] = { ...event.content_block };
|
|
227
|
+
if (event.content_block?.type === 'tool_use') {
|
|
228
|
+
owners.set(event.content_block.id, reply);
|
|
229
|
+
poke();
|
|
230
|
+
}
|
|
231
|
+
} else if (event.type === 'content_block_delta') {
|
|
232
|
+
const block = reply.blocks[event.index];
|
|
233
|
+
const delta = event.delta ?? {};
|
|
234
|
+
if (!block) return;
|
|
235
|
+
if (delta.type === 'text_delta') block.text = (block.text ?? '') + delta.text;
|
|
236
|
+
else if (delta.type === 'thinking_delta') block.thinking = (block.thinking ?? '') + delta.thinking;
|
|
237
|
+
else if (delta.type === 'signature_delta') block.signature = delta.signature;
|
|
238
|
+
else if (delta.type === 'input_json_delta') reply.json[event.index] = (reply.json[event.index] ?? '') + delta.partial_json;
|
|
239
|
+
} else if (event.type === 'content_block_stop') {
|
|
240
|
+
blockEnded(reply, event.index);
|
|
241
|
+
} else if (event.type === 'message_delta') {
|
|
242
|
+
if (event.delta?.stop_reason) reply.stop = event.delta.stop_reason;
|
|
243
|
+
const counted = Object.entries(event.usage ?? {}).filter(([, value]) => value != null);
|
|
244
|
+
reply.counts = { ...reply.counts, ...Object.fromEntries(counted) };
|
|
245
|
+
} else if (event.type === 'message_stop') {
|
|
246
|
+
stopped(reply);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// The turn is over: Claude Code waits for the next user message.
|
|
251
|
+
function turnEnded(result) {
|
|
252
|
+
raw.push({ type: 'result', subtype: result.subtype, is_error: result.is_error, stop_reason: result.stop_reason, num_turns: result.num_turns, duration_ms: result.duration_ms, usage: result.usage, result: result.result });
|
|
253
|
+
if (exit || failure) return;
|
|
254
|
+
const last = replies.at(-1);
|
|
255
|
+
if (result.is_error || result.subtype !== 'success') {
|
|
256
|
+
if (result.subtype === 'error_max_turns' && replies.length >= limits.replies) return finish('replies');
|
|
257
|
+
const why = result.result || (result.errors ?? []).join('; ') || result.subtype || 'no answer';
|
|
258
|
+
return fail(new ProviderError(`${agent.name}: ${why}`, { fatal: /authenticate|log ?in|signed in|time limit|usage limit/i.test(why) }));
|
|
259
|
+
}
|
|
260
|
+
if (!last || last.calls.length) return fail(new ProviderError(`${agent.name} ended the turn before the reply's results were back (${result.stop_reason ?? result.subtype})`));
|
|
261
|
+
if (overBudget()) return;
|
|
262
|
+
last.said = last.ended === 'truncated' ? cutOff : noCommand;
|
|
263
|
+
say(last.said);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
// Results Claude Code made itself, without calling us (a call it refused to pass on, say).
|
|
267
|
+
function answeredByClaudeCode(message) {
|
|
268
|
+
for (const block of Array.isArray(message?.content) ? message.content : []) {
|
|
269
|
+
if (block.type !== 'tool_result') continue;
|
|
270
|
+
const reply = owners.get(block.tool_use_id);
|
|
271
|
+
if (!reply || reply.results.has(block.tool_use_id)) continue;
|
|
272
|
+
const content = typeof block.content === 'string' ? [{ type: 'text', text: block.content }] : (block.content ?? []);
|
|
273
|
+
reply.results.set(block.tool_use_id, {
|
|
274
|
+
id: block.tool_use_id,
|
|
275
|
+
by: agent.by,
|
|
276
|
+
text: content.filter((part) => part.type === 'text').map((part) => part.text).join('\n'),
|
|
277
|
+
images: content.filter((part) => part.type === 'image').map((part) => ({ mime: part.source?.media_type, data: part.source?.data })),
|
|
278
|
+
});
|
|
279
|
+
settle(reply);
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** Waits until `find()` returns something, the run is over, or `ms` pass. */
|
|
284
|
+
function until(find, ms) {
|
|
285
|
+
const found = find();
|
|
286
|
+
if (found || exit || failure) return Promise.resolve(found);
|
|
287
|
+
return new Promise((done) => {
|
|
288
|
+
const waiter = () => {
|
|
289
|
+
const value = find();
|
|
290
|
+
if (!value && !exit && !failure) return;
|
|
291
|
+
waiters.delete(waiter);
|
|
292
|
+
clearTimeout(timer);
|
|
293
|
+
done(value);
|
|
294
|
+
};
|
|
295
|
+
const timer = setTimeout(() => {
|
|
296
|
+
waiters.delete(waiter);
|
|
297
|
+
done(find());
|
|
298
|
+
}, ms);
|
|
299
|
+
waiters.add(waiter);
|
|
300
|
+
});
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
return {
|
|
304
|
+
get exit() {
|
|
305
|
+
return exit;
|
|
306
|
+
},
|
|
307
|
+
get failure() {
|
|
308
|
+
return failure;
|
|
309
|
+
},
|
|
310
|
+
fail,
|
|
311
|
+
|
|
312
|
+
/** One stream-json event from Claude Code's stdout. */
|
|
313
|
+
handle(event) {
|
|
314
|
+
if (event.parent_tool_use_id) return;
|
|
315
|
+
if (event.type === 'system' && event.subtype === 'init') {
|
|
316
|
+
init = {
|
|
317
|
+
model: event.model,
|
|
318
|
+
tools: event.tools,
|
|
319
|
+
mcp_servers: event.mcp_servers,
|
|
320
|
+
apiKeySource: event.apiKeySource,
|
|
321
|
+
permissionMode: event.permissionMode,
|
|
322
|
+
slash_commands: event.slash_commands,
|
|
323
|
+
skills: event.skills,
|
|
324
|
+
agents: event.agents,
|
|
325
|
+
plugins: event.plugins,
|
|
326
|
+
output_style: event.output_style,
|
|
327
|
+
claude_code_version: event.claude_code_version,
|
|
328
|
+
};
|
|
329
|
+
raw.unshift({ type: 'session', init });
|
|
330
|
+
if (!agent.onPlan(event.apiKeySource))
|
|
331
|
+
return fail(new ProviderError(`${agent.name} used an API key (${event.apiKeySource}), not the subscription`, { fatal: true }));
|
|
332
|
+
const allowed = agent.allowed(tool);
|
|
333
|
+
const extra = (event.tools ?? []).filter((name) => !allowed.includes(name));
|
|
334
|
+
if (extra.length) return fail(new ProviderError(`${agent.name} offered the model tools besides ours: ${extra.join(', ')}`, { fatal: true }));
|
|
335
|
+
const status = (event.mcp_servers ?? []).find((server) => server.name === SERVER)?.status ?? 'missing';
|
|
336
|
+
if (agent.listsOurTool ? !(event.tools ?? []).includes(toolName(tool)) : status === 'missing')
|
|
337
|
+
return fail(new ProviderError(`${agent.name} didn't get our tool (MCP server ${status})`));
|
|
338
|
+
} else if (event.type === 'stream_event') {
|
|
339
|
+
streamed(event.event ?? {});
|
|
340
|
+
} else if (event.type === 'user') {
|
|
341
|
+
answeredByClaudeCode(event.message);
|
|
342
|
+
} else if (event.type === 'result') {
|
|
343
|
+
turnEnded(event);
|
|
344
|
+
} else if (event.type === 'rate_limit_event') {
|
|
345
|
+
const weekly = event.rate_limit_info?.unifiedWindows?.seven_day;
|
|
346
|
+
if (weekly?.utilization != null) plan.weeklyUse = weekly.utilization;
|
|
347
|
+
raw.push(event);
|
|
348
|
+
} else if (event.type === 'system' && event.subtype !== 'status') {
|
|
349
|
+
// Retries, compaction and anything else Claude Code did on its own, for the record.
|
|
350
|
+
raw.push(event);
|
|
351
|
+
if (event.subtype === 'compact_boundary') current?.notes.push({ role: 'harness', by: agent.by, text: `${agent.name} compacted the conversation here.` });
|
|
352
|
+
}
|
|
353
|
+
},
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* One call of our tool, as Claude Code passed it on: the tool_use id (from
|
|
357
|
+
* `_meta`) and the arguments. Resolves to the result to send back:
|
|
358
|
+
* { text, images, isError }.
|
|
359
|
+
*/
|
|
360
|
+
async call({ id, input }) {
|
|
361
|
+
// Wait for stdout to show the whole reply the call belongs to.
|
|
362
|
+
const read = readArguments(input);
|
|
363
|
+
// Without an id (an older Claude Code), the first unanswered call with the same command.
|
|
364
|
+
const unanswered = (r) => r.all?.find((c) => !r.results.has(c.id) && c.command === read.command);
|
|
365
|
+
const reply = await until(() => {
|
|
366
|
+
const owner = id ? owners.get(id) : replies.findLast((r) => (r.stopped || agent.eager) && unanswered(r));
|
|
367
|
+
return owner?.stopped || (agent.eager && owner) ? owner : null;
|
|
368
|
+
}, CATCH_UP_MS);
|
|
369
|
+
if (!reply) return { text: 'Not run: the harness could not match this call to a reply.', images: [], isError: true };
|
|
370
|
+
const useId = id ?? unanswered(reply).id;
|
|
371
|
+
|
|
372
|
+
const job = commands.then(async () => {
|
|
373
|
+
let result;
|
|
374
|
+
if (!reply.calls.some((call) => call.id === useId)) result = { text: cutOff, images: [] };
|
|
375
|
+
else if (submitted) result = { text: 'Not run: the drawing was already submitted.', images: [] };
|
|
376
|
+
else if (exit || failure) result = { text: 'Not run: the run is over.', images: [] };
|
|
377
|
+
else if (read.error) result = { text: `${read.error}\n[${reply.budget}]`, images: [], isError: true };
|
|
378
|
+
else {
|
|
379
|
+
const done = await sandbox.run(read.command);
|
|
380
|
+
looks += done.images.length;
|
|
381
|
+
if (done.submitted) submitted = true;
|
|
382
|
+
result = { text: resultText(done, reply.budget, limits), images: done.images };
|
|
383
|
+
}
|
|
384
|
+
reply.results.set(useId, { id: useId, text: result.text, images: result.images });
|
|
385
|
+
// May end the run: then Claude Code is stopped before it reads this result.
|
|
386
|
+
settle(reply);
|
|
387
|
+
return result;
|
|
388
|
+
});
|
|
389
|
+
commands = job.catch(() => {});
|
|
390
|
+
try {
|
|
391
|
+
return await job;
|
|
392
|
+
} catch (error) {
|
|
393
|
+
fail(error);
|
|
394
|
+
return { text: `Not run: ${error.message}`, images: [], isError: true };
|
|
395
|
+
}
|
|
396
|
+
},
|
|
397
|
+
|
|
398
|
+
/** Everything draw() in loop.mjs returns, less the drawing. */
|
|
399
|
+
outcome() {
|
|
400
|
+
const usage = { input: 0, output: 0, cached: 0, reasoning: 0, cost: null };
|
|
401
|
+
const transcript = [];
|
|
402
|
+
for (const reply of replies) {
|
|
403
|
+
const counted = usageOf(reply.counts);
|
|
404
|
+
for (const key of Object.keys(counted)) usage[key] += counted[key];
|
|
405
|
+
transcript.push({
|
|
406
|
+
role: 'model',
|
|
407
|
+
id: reply.id,
|
|
408
|
+
ended: reply.ended ?? 'truncated',
|
|
409
|
+
text: reply.blocks.filter((block) => block?.type === 'text').map((block) => block.text).join(''),
|
|
410
|
+
calls: reply.calls,
|
|
411
|
+
usage: counted,
|
|
412
|
+
at: reply.at ?? null,
|
|
413
|
+
});
|
|
414
|
+
const answered = reply.uses.filter((use) => reply.results.has(use) || reply.calls.some((call) => call.id === use));
|
|
415
|
+
if (answered.length)
|
|
416
|
+
transcript.push({ role: 'results', results: answered.map((use) => reply.results.get(use) ?? { id: use, text: 'Not run: the run ended first.', images: [] }) });
|
|
417
|
+
transcript.push(...reply.notes);
|
|
418
|
+
if (reply.said) transcript.push({ role: 'harness', text: reply.said });
|
|
419
|
+
}
|
|
420
|
+
return {
|
|
421
|
+
exit,
|
|
422
|
+
replies: replies.length,
|
|
423
|
+
looks,
|
|
424
|
+
seconds: Math.round((clock() - startedAt) / 1000),
|
|
425
|
+
usage,
|
|
426
|
+
responseIds: replies.map((reply) => reply.id).filter(Boolean),
|
|
427
|
+
servedModel: replies.findLast((reply) => reply.model)?.model ?? null,
|
|
428
|
+
transcript,
|
|
429
|
+
raw,
|
|
430
|
+
init,
|
|
431
|
+
};
|
|
432
|
+
},
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* Answers one JSON-RPC message from Claude Code's MCP client: the handshake,
|
|
438
|
+
* the list with our one tool, and its calls. Returns the response, or null
|
|
439
|
+
* for a notification.
|
|
440
|
+
*/
|
|
441
|
+
export async function answerRpc(message, { tool, call }) {
|
|
442
|
+
if (message?.id === undefined || message.id === null) return null;
|
|
443
|
+
const reply = (result) => ({ jsonrpc: '2.0', id: message.id, result });
|
|
444
|
+
const error = (code, text) => ({ jsonrpc: '2.0', id: message.id, error: { code, message: text } });
|
|
445
|
+
switch (message.method) {
|
|
446
|
+
case 'initialize':
|
|
447
|
+
return reply({ protocolVersion: message.params?.protocolVersion ?? '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: SERVER, version: '1' } });
|
|
448
|
+
case 'ping':
|
|
449
|
+
return reply({});
|
|
450
|
+
case 'tools/list':
|
|
451
|
+
return reply({ tools: [{ name: tool.name, description: tool.description, inputSchema: tool.parameters }] });
|
|
452
|
+
case 'tools/call': {
|
|
453
|
+
if (message.params?.name !== tool.name) return error(-32602, `There is no tool "${message.params?.name}".`);
|
|
454
|
+
const result = await call({ id: message.params?._meta?.['claudecode/toolUseId'] ?? null, input: message.params?.arguments ?? {} });
|
|
455
|
+
return reply({
|
|
456
|
+
content: [
|
|
457
|
+
...(result.text ? [{ type: 'text', text: result.text }] : []),
|
|
458
|
+
...(result.images ?? []).map((image) => ({ type: 'image', data: image.data, mimeType: image.mime })),
|
|
459
|
+
],
|
|
460
|
+
...(result.isError && { isError: true }),
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
default:
|
|
464
|
+
return error(-32601, `Method not found: ${message.method}`);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** Serves our tool to one Claude Code process: 127.0.0.1, a free port, a path no one else knows. */
|
|
469
|
+
export async function serve(handler) {
|
|
470
|
+
const path = `/mcp/${randomBytes(16).toString('hex')}`;
|
|
471
|
+
const server = createServer(async (request, response) => {
|
|
472
|
+
if (request.url !== path) return response.writeHead(404).end();
|
|
473
|
+
// No server-to-client stream: everything is answered in the POST it came in.
|
|
474
|
+
if (request.method !== 'POST') return response.writeHead(405, { allow: 'POST' }).end();
|
|
475
|
+
let body = '';
|
|
476
|
+
for await (const chunk of request) body += chunk;
|
|
477
|
+
let message;
|
|
478
|
+
try {
|
|
479
|
+
message = JSON.parse(body);
|
|
480
|
+
} catch {
|
|
481
|
+
return response.writeHead(400, { 'content-type': 'application/json' }).end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }));
|
|
482
|
+
}
|
|
483
|
+
const answer = await handler(message);
|
|
484
|
+
if (!answer) return response.writeHead(202).end();
|
|
485
|
+
if (!response.destroyed) response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(answer));
|
|
486
|
+
});
|
|
487
|
+
// A command may run for minutes; the request must not time out under it.
|
|
488
|
+
server.requestTimeout = 0;
|
|
489
|
+
server.headersTimeout = 0;
|
|
490
|
+
await new Promise((done, failed) => server.once('error', failed).listen(0, '127.0.0.1', done));
|
|
491
|
+
return {
|
|
492
|
+
url: `http://127.0.0.1:${server.address().port}${path}`,
|
|
493
|
+
close: () => {
|
|
494
|
+
const closed = new Promise((done) => server.close(done));
|
|
495
|
+
server.closeAllConnections();
|
|
496
|
+
return closed;
|
|
497
|
+
},
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/** The environment Claude Code runs in: ours, less anything that would change who pays or what it sends. */
|
|
502
|
+
export function environment({ maxOutputTokens, limits }, from = process.env) {
|
|
503
|
+
const env = {};
|
|
504
|
+
for (const [name, value] of Object.entries(from)) {
|
|
505
|
+
// Keys, base URLs and a parent Claude Code's own settings (this may run
|
|
506
|
+
// inside a Claude Code session) all stay out; a subscription token stays in.
|
|
507
|
+
if (/^(ANTHROPIC_|CLAUDE|MCP_|ENABLE_|DISABLE_|MAX_MCP_)/.test(name) && name !== 'CLAUDE_CODE_OAUTH_TOKEN' && name !== 'CLAUDE_CONFIG_DIR') continue;
|
|
508
|
+
env[name] = value;
|
|
509
|
+
}
|
|
510
|
+
return {
|
|
511
|
+
...env,
|
|
512
|
+
CLAUDE_CODE_MAX_OUTPUT_TOKENS: String(maxOutputTokens),
|
|
513
|
+
// One command at a time, in order, as loop.mjs runs them.
|
|
514
|
+
CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY: '1',
|
|
515
|
+
// Long enough for a command that runs to its limit, and the collection after it.
|
|
516
|
+
MCP_TOOL_TIMEOUT: String((limits.commandSeconds + 120) * 1000),
|
|
517
|
+
// Every image `view` made reaches the model, however many one command makes.
|
|
518
|
+
MAX_MCP_OUTPUT_TOKENS: '1000000',
|
|
519
|
+
// No compaction, no tool search, no advisor, no reminders or memory, no
|
|
520
|
+
// retry or fallback model after a refusal: the conversation is ours alone.
|
|
521
|
+
DISABLE_AUTO_COMPACT: '1',
|
|
522
|
+
ENABLE_TOOL_SEARCH: 'false',
|
|
523
|
+
CLAUDE_CODE_DISABLE_ADVISOR_TOOL: '1',
|
|
524
|
+
CLAUDE_CODE_DISABLE_ATTACHMENTS: '1',
|
|
525
|
+
CLAUDE_CODE_DISABLE_CLAUDE_MDS: '1',
|
|
526
|
+
CLAUDE_CODE_DISABLE_AUTO_MEMORY: '1',
|
|
527
|
+
CLAUDE_CODE_DISABLE_REFUSAL_RETRY: '1',
|
|
528
|
+
CLAUDE_CODE_DISABLE_REFUSAL_FALLBACK: '1',
|
|
529
|
+
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1',
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/** Claude Code's flags: as bare as it allows, with our tool as its only one. */
|
|
534
|
+
export function flags({ model, effort, limits, tool, mcpUrl }) {
|
|
535
|
+
return [
|
|
536
|
+
'-p', '--model', model, ...(effort ? ['--effort', effort] : []),
|
|
537
|
+
'--system-prompt', '', '--tools', '', '--setting-sources', '', '--disable-slash-commands', '--no-session-persistence',
|
|
538
|
+
'--strict-mcp-config', '--mcp-config', JSON.stringify({ mcpServers: { [SERVER]: { type: 'http', url: mcpUrl } } }),
|
|
539
|
+
'--allowedTools', toolName(tool),
|
|
540
|
+
// A backstop only: the run is stopped by its own count of replies first.
|
|
541
|
+
'--max-turns', String(limits.replies + 1),
|
|
542
|
+
'--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', '--include-partial-messages',
|
|
543
|
+
];
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/**
|
|
547
|
+
* Runs one drawing through Claude Code. Returns what draw() in loop.mjs
|
|
548
|
+
* returns, plus `route`. Throws ProviderError when the run isn't an answer.
|
|
549
|
+
*/
|
|
550
|
+
export async function drawWithClaudeCode({ model, effort, maxOutputTokens, text, tool, sandbox, limits }) {
|
|
551
|
+
if (plan.weeklyUse >= plan.ceiling)
|
|
552
|
+
throw new ProviderError(`the Claude plan is at ${Math.round(plan.weeklyUse * 100)}% of its weekly limit (ceiling ${Math.round(plan.ceiling * 100)}%)`);
|
|
553
|
+
|
|
554
|
+
// An empty folder of its own: Claude Code tells the model its working directory.
|
|
555
|
+
const cwd = await mkdtemp(join(tmpdir(), 'vb-claude-'));
|
|
556
|
+
let child = null;
|
|
557
|
+
let stopping = false;
|
|
558
|
+
const stop = () => {
|
|
559
|
+
if (stopping || !child) return;
|
|
560
|
+
stopping = true;
|
|
561
|
+
child.stdin.end();
|
|
562
|
+
child.kill('SIGTERM');
|
|
563
|
+
setTimeout(() => child.exitCode === null && child.signalCode === null && child.kill('SIGKILL'), 5000).unref();
|
|
564
|
+
};
|
|
565
|
+
const send = (said) => child?.stdin.writable && child.stdin.write(JSON.stringify({ type: 'user', message: { role: 'user', content: said } }) + '\n');
|
|
566
|
+
|
|
567
|
+
const run = session({ tool, sandbox, limits, say: send, end: stop });
|
|
568
|
+
const server = await serve((message) => answerRpc(message, { tool, call: run.call }));
|
|
569
|
+
const watchdog = setTimeout(() => run.fail(new ProviderError(`Claude Code was still going ${GRACE_MINUTES} minutes past the time budget`)), (limits.minutes + GRACE_MINUTES) * 60000);
|
|
570
|
+
|
|
571
|
+
let stderr = '';
|
|
572
|
+
let closed;
|
|
573
|
+
try {
|
|
574
|
+
closed = await new Promise((done) => {
|
|
575
|
+
try {
|
|
576
|
+
child = spawn('claude', flags({ model, effort, limits, tool, mcpUrl: server.url }), {
|
|
577
|
+
cwd,
|
|
578
|
+
env: environment({ maxOutputTokens, limits }),
|
|
579
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
580
|
+
});
|
|
581
|
+
} catch (error) {
|
|
582
|
+
run.fail(new ProviderError(`couldn't start claude: ${error.message}`, { fatal: true }));
|
|
583
|
+
return done({});
|
|
584
|
+
}
|
|
585
|
+
let pending = '';
|
|
586
|
+
child.stdout.setEncoding('utf8');
|
|
587
|
+
child.stdout.on('data', (chunk) => {
|
|
588
|
+
pending += chunk;
|
|
589
|
+
let newline;
|
|
590
|
+
while ((newline = pending.indexOf('\n')) >= 0) {
|
|
591
|
+
const line = pending.slice(0, newline);
|
|
592
|
+
pending = pending.slice(newline + 1);
|
|
593
|
+
if (!line.trim()) continue;
|
|
594
|
+
let event;
|
|
595
|
+
try {
|
|
596
|
+
event = JSON.parse(line);
|
|
597
|
+
} catch {
|
|
598
|
+
continue;
|
|
599
|
+
}
|
|
600
|
+
try {
|
|
601
|
+
run.handle(event);
|
|
602
|
+
} catch (error) {
|
|
603
|
+
run.fail(error);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
});
|
|
607
|
+
child.stderr.setEncoding('utf8');
|
|
608
|
+
child.stderr.on('data', (chunk) => (stderr = (stderr + chunk).slice(-20_000)));
|
|
609
|
+
child.stdin.on('error', () => {});
|
|
610
|
+
child.on('error', (error) => run.fail(new ProviderError(`couldn't start claude: ${error.message}`, { fatal: true })));
|
|
611
|
+
child.on('close', (code, signal) => done({ code, signal }));
|
|
612
|
+
send(text);
|
|
613
|
+
});
|
|
614
|
+
} finally {
|
|
615
|
+
clearTimeout(watchdog);
|
|
616
|
+
await server.close();
|
|
617
|
+
await rm(cwd, { recursive: true, force: true });
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
if (run.failure) throw run.failure;
|
|
621
|
+
if (!run.exit) {
|
|
622
|
+
const why = stderr.trim().split('\n').slice(-3).join(' ') || `it exited (${closed.signal ?? closed.code}) before the run was over`;
|
|
623
|
+
throw new ProviderError(`Claude Code: ${why}`, { fatal: /authenticate|log ?in|not logged/i.test(why) });
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
const svg = await sandbox.read('drawing.svg');
|
|
627
|
+
const { init, ...result } = run.outcome();
|
|
628
|
+
return { ...result, svg, route: { via: 'claude-code', style: 'claude-code', url: 'https://api.anthropic.com/v1/messages' } };
|
|
629
|
+
}
|