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,233 @@
|
|
|
1
|
+
// The xAI models with tools on a Grok plan: Grok Build's headless mode asks
|
|
2
|
+
// the model, and the one tool that runs anything is ours, served from this
|
|
3
|
+
// process over MCP, so the model gets the same request, the same tool, the
|
|
4
|
+
// same sandbox and the same budget as harness/loop.mjs gives it through the
|
|
5
|
+
// API. The model of this file is harness/claude-code.mjs: Grok Build writes
|
|
6
|
+
// the same stream of events, so the run's state is that file's `session`.
|
|
7
|
+
//
|
|
8
|
+
// What the model has (Grok Build 1.0.100, 4 December 2026): three tools.
|
|
9
|
+
// `vb__bash` is ours, with our description and schema. `search_tool` and
|
|
10
|
+
// `use_tool` are Grok Build's way to MCP tools and can't be switched off:
|
|
11
|
+
// the model usually looks our tool up with the first and calls it through
|
|
12
|
+
// the second ({"tool_name": "vb__bash", "tool_input": {...}}), which reaches
|
|
13
|
+
// us as the same call. A reply spent on `search_tool` counts against the
|
|
14
|
+
// budget of replies like any other, so a run here may have one or two fewer
|
|
15
|
+
// for drawing than the same run through the API. Every built-in that reads,
|
|
16
|
+
// writes or runs anything on this machine, the web and X search, sub-agents,
|
|
17
|
+
// plans, memory and skills are off; the first event of each run lists the
|
|
18
|
+
// tools the session had, and the run fails if there is one more.
|
|
19
|
+
//
|
|
20
|
+
// What Grok Build sends that our loop does not: a short system prompt of its
|
|
21
|
+
// own (about 1,300 input tokens with the tools; an agent file with an empty
|
|
22
|
+
// body is as bare as it goes), the working directory (an empty temp folder)
|
|
23
|
+
// and the date. No output cap is ours to set. Pictures reach the model as
|
|
24
|
+
// pictures (`expose_image_base64 = false`): in the probe it described the
|
|
25
|
+
// stripes `view` showed it.
|
|
26
|
+
//
|
|
27
|
+
// Grok Build runs a call before it has written the end of the reply that
|
|
28
|
+
// made it, so a call is matched to its reply (by its command: the MCP call
|
|
29
|
+
// carries no id) as soon as the block is whole.
|
|
30
|
+
//
|
|
31
|
+
// Headless mode takes one prompt and reads nothing after it, so the loop's
|
|
32
|
+
// "That reply ran no command" message is sent by resuming the session in a
|
|
33
|
+
// new process.
|
|
34
|
+
|
|
35
|
+
import { spawn } from 'node:child_process';
|
|
36
|
+
import { randomUUID } from 'node:crypto';
|
|
37
|
+
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
|
|
38
|
+
import { homedir, tmpdir } from 'node:os';
|
|
39
|
+
import { join } from 'node:path';
|
|
40
|
+
import { ProviderError } from '../src/model-apis.js';
|
|
41
|
+
import { answerRpc, serve, session } from './claude-code.mjs';
|
|
42
|
+
|
|
43
|
+
const SERVER = 'vb';
|
|
44
|
+
const GRACE_MINUTES = 30;
|
|
45
|
+
|
|
46
|
+
/** The name the model calls our tool by, directly or inside `use_tool`. */
|
|
47
|
+
export const toolName = (tool) => `${SERVER}__${tool.name}`;
|
|
48
|
+
|
|
49
|
+
// Every tool Grok Build has of its own that a flag can take away. A name it
|
|
50
|
+
// doesn't know only earns a warning, and one that is missing here stops the
|
|
51
|
+
// run at its first event, so the list errs long.
|
|
52
|
+
export const BUILT_INS = [
|
|
53
|
+
'run_terminal_command', 'read_file', 'search_replace', 'list_dir', 'grep', 'write', 'kill_command_or_subagent',
|
|
54
|
+
'get_command_or_subagent_output', 'wait_commands_or_subagents', 'monitor', 'workflow', 'todo_write',
|
|
55
|
+
'scheduler_create', 'scheduler_delete', 'scheduler_list', 'enter_plan_mode', 'exit_plan_mode', 'ask_user_question',
|
|
56
|
+
'send_feedback', 'image_gen', 'image_edit', 'image_to_video', 'reference_to_video', 'Agent', 'x_search',
|
|
57
|
+
];
|
|
58
|
+
|
|
59
|
+
/** What harness/claude-code.mjs's session needs to know about Grok Build. */
|
|
60
|
+
export const GROK_BUILD = {
|
|
61
|
+
by: 'grok-build',
|
|
62
|
+
name: 'Grok Build',
|
|
63
|
+
allowed: (tool) => ['search_tool', 'use_tool', toolName(tool)],
|
|
64
|
+
// The first event comes before the MCP server has answered: it may not list our tool yet.
|
|
65
|
+
listsOurTool: false,
|
|
66
|
+
onPlan: (source) => source === 'oauth',
|
|
67
|
+
// Seen on 1.0.100: the tool is called once its block is whole, and the reply's end is written after the result.
|
|
68
|
+
eager: true,
|
|
69
|
+
unwrap(block, input, tool) {
|
|
70
|
+
if (block.name === toolName(tool)) return input;
|
|
71
|
+
if (block.name !== 'use_tool' || ![toolName(tool), tool.name].includes(input?.tool_name)) return null;
|
|
72
|
+
let args = input.tool_input;
|
|
73
|
+
if (typeof args === 'string') {
|
|
74
|
+
try {
|
|
75
|
+
args = JSON.parse(args);
|
|
76
|
+
} catch {}
|
|
77
|
+
}
|
|
78
|
+
return args ?? {};
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
/** Where the plan's sign-in is kept. Used in place, never copied: Grok Build refreshes it. */
|
|
83
|
+
export const authPath = (from = process.env) => from.GROK_AUTH_PATH || join(from.GROK_HOME || join(homedir(), '.grok'), 'auth.json');
|
|
84
|
+
|
|
85
|
+
/** Grok Build's own settings for one run, as config.toml in a home of its own. */
|
|
86
|
+
export const config = ({ mcpUrl, limits }) =>
|
|
87
|
+
[
|
|
88
|
+
'[cli]',
|
|
89
|
+
'auto_update = false',
|
|
90
|
+
'',
|
|
91
|
+
`[mcp_servers.${SERVER}]`,
|
|
92
|
+
`url = ${JSON.stringify(mcpUrl)}`,
|
|
93
|
+
// Long enough for a command that runs to its limit, and the collection after it.
|
|
94
|
+
`tool_timeout_sec = ${limits.commandSeconds + 120}`,
|
|
95
|
+
// Pictures go to the model as pictures, not as base64 text.
|
|
96
|
+
'expose_image_base64 = false',
|
|
97
|
+
'',
|
|
98
|
+
].join('\n');
|
|
99
|
+
|
|
100
|
+
/** An agent with no instructions of ours and none of Grok Build's skills. */
|
|
101
|
+
export const AGENT = ['---', 'name: vb', 'description: One tool, served over MCP.', 'promptMode: full', 'discoverSkills: false', 'inheritSkills: false', '---', ''].join('\n');
|
|
102
|
+
|
|
103
|
+
/** The environment Grok Build runs in: ours, less anything that would change who pays or what it sends. */
|
|
104
|
+
export function environment({ home }, from = process.env) {
|
|
105
|
+
const env = {};
|
|
106
|
+
for (const [name, value] of Object.entries(from)) {
|
|
107
|
+
if (/^(XAI_|GROK_)/.test(name)) continue;
|
|
108
|
+
env[name] = value;
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
...env,
|
|
112
|
+
// A home of its own: no settings, sessions, skills or MCP servers of the user's (Grok Build also reads ~/.claude).
|
|
113
|
+
HOME: home,
|
|
114
|
+
GROK_HOME: home,
|
|
115
|
+
GROK_AUTH_PATH: authPath(from),
|
|
116
|
+
GROK_MEMORY: '0',
|
|
117
|
+
GROK_DISABLE_AUTOUPDATER: '1',
|
|
118
|
+
// Every image `view` made reaches the model, however many one command makes.
|
|
119
|
+
GROK_MAX_MCP_OUTPUT_BYTES: '50000000',
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Grok Build's flags: as bare as it allows. `resume` goes on with the session instead of starting it. */
|
|
124
|
+
export function flags({ model, effort, limits, agentFile, promptFile, cwd, sessionId, resume = false }) {
|
|
125
|
+
return [
|
|
126
|
+
...(resume ? ['--resume', sessionId] : ['--session-id', sessionId]),
|
|
127
|
+
'--prompt-file', promptFile, '--verbatim',
|
|
128
|
+
'-m', model, ...(effort ? ['--reasoning-effort', effort] : []),
|
|
129
|
+
'--agent', agentFile, '--disallowed-tools', BUILT_INS.join(','),
|
|
130
|
+
'--always-approve', '--no-subagents', '--no-plan', '--no-memory', '--disable-web-search',
|
|
131
|
+
// A backstop only: the run is stopped by its own count of replies first.
|
|
132
|
+
'--max-turns', String(limits.replies + 1),
|
|
133
|
+
'--output-format', 'streaming-messages-json', '--include-partial-messages',
|
|
134
|
+
'--cwd', cwd,
|
|
135
|
+
];
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Runs one drawing through Grok Build. Returns what draw() in loop.mjs
|
|
140
|
+
* returns, plus `route`. Throws ProviderError when the run isn't an answer.
|
|
141
|
+
*/
|
|
142
|
+
export async function drawWithGrokBuild({ model, effort, text, tool, sandbox, limits }) {
|
|
143
|
+
const bin = process.env.GROK_BIN || 'grok';
|
|
144
|
+
const home = await mkdtemp(join(tmpdir(), 'vb-grok-'));
|
|
145
|
+
// An empty folder of its own: Grok Build tells the model its working directory.
|
|
146
|
+
const cwd = join(home, 'work');
|
|
147
|
+
await mkdir(cwd);
|
|
148
|
+
const agentFile = join(home, 'vb-agent.md');
|
|
149
|
+
await writeFile(agentFile, AGENT);
|
|
150
|
+
const sessionId = randomUUID();
|
|
151
|
+
|
|
152
|
+
let child = null;
|
|
153
|
+
let next = null; // what to say when the process that heard the last turn has gone
|
|
154
|
+
let stopping = false;
|
|
155
|
+
const stop = () => {
|
|
156
|
+
stopping = true;
|
|
157
|
+
if (!child) return;
|
|
158
|
+
const ending = child;
|
|
159
|
+
ending.kill('SIGTERM');
|
|
160
|
+
setTimeout(() => ending.exitCode === null && ending.signalCode === null && ending.kill('SIGKILL'), 5000).unref();
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
const run = session({ tool, sandbox, limits, say: (said) => (next = said), end: stop, agent: GROK_BUILD });
|
|
164
|
+
const server = await serve((message) => answerRpc(message, { tool, call: run.call }));
|
|
165
|
+
await writeFile(join(home, 'config.toml'), config({ mcpUrl: server.url, limits }));
|
|
166
|
+
const watchdog = setTimeout(() => run.fail(new ProviderError(`Grok Build was still going ${GRACE_MINUTES} minutes past the time budget`)), (limits.minutes + GRACE_MINUTES) * 60000);
|
|
167
|
+
|
|
168
|
+
let stderr = '';
|
|
169
|
+
let turn = 0;
|
|
170
|
+
/** One process: one user message and everything the model does until it stops calling tools. */
|
|
171
|
+
const ask = async (said, resume) => {
|
|
172
|
+
const promptFile = join(home, `prompt-${++turn}.txt`);
|
|
173
|
+
await writeFile(promptFile, said);
|
|
174
|
+
return new Promise((done) => {
|
|
175
|
+
try {
|
|
176
|
+
child = spawn(bin, flags({ model, effort, limits, agentFile, promptFile, cwd, sessionId, resume }), { cwd, env: environment({ home }), stdio: ['ignore', 'pipe', 'pipe'] });
|
|
177
|
+
} catch (error) {
|
|
178
|
+
run.fail(new ProviderError(`couldn't start grok: ${error.message}`, { fatal: true }));
|
|
179
|
+
return done({});
|
|
180
|
+
}
|
|
181
|
+
let pending = '';
|
|
182
|
+
child.stdout.setEncoding('utf8');
|
|
183
|
+
child.stdout.on('data', (chunk) => {
|
|
184
|
+
pending += chunk;
|
|
185
|
+
let newline;
|
|
186
|
+
while ((newline = pending.indexOf('\n')) >= 0) {
|
|
187
|
+
const line = pending.slice(0, newline);
|
|
188
|
+
pending = pending.slice(newline + 1);
|
|
189
|
+
if (!line.trim()) continue;
|
|
190
|
+
let event;
|
|
191
|
+
try {
|
|
192
|
+
event = JSON.parse(line);
|
|
193
|
+
} catch {
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
196
|
+
try {
|
|
197
|
+
run.handle(event);
|
|
198
|
+
} catch (error) {
|
|
199
|
+
run.fail(error);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
child.stderr.setEncoding('utf8');
|
|
204
|
+
child.stderr.on('data', (chunk) => (stderr = (stderr + chunk).slice(-20_000)));
|
|
205
|
+
child.on('error', (error) => run.fail(new ProviderError(`couldn't start grok: ${error.message}`, { fatal: true })));
|
|
206
|
+
child.on('close', (code, signal) => done({ code, signal }));
|
|
207
|
+
});
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
let closed;
|
|
211
|
+
try {
|
|
212
|
+
closed = await ask(text, false);
|
|
213
|
+
while (next && !stopping && !run.exit && !run.failure) {
|
|
214
|
+
const said = next;
|
|
215
|
+
next = null;
|
|
216
|
+
closed = await ask(said, true);
|
|
217
|
+
}
|
|
218
|
+
} finally {
|
|
219
|
+
clearTimeout(watchdog);
|
|
220
|
+
await server.close();
|
|
221
|
+
await rm(home, { recursive: true, force: true });
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
if (run.failure) throw run.failure;
|
|
225
|
+
if (!run.exit) {
|
|
226
|
+
const why = stderr.trim().split('\n').slice(-3).join(' ') || `it exited (${closed.signal ?? closed.code}) before the run was over`;
|
|
227
|
+
throw new ProviderError(`Grok Build: ${why}`, { fatal: /authenticat|log ?in|signed in|sign in|usage limit|rate limit/i.test(why) });
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const svg = await sandbox.read('drawing.svg');
|
|
231
|
+
const { init, ...result } = run.outcome();
|
|
232
|
+
return { ...result, svg, route: { via: 'grok-build', style: 'grok-build', url: 'https://cli-chat-proxy.grok.com/v1' } };
|
|
233
|
+
}
|
package/harness/loop.mjs
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// The loop: ask the model, run the commands it calls, give back what they
|
|
2
|
+
// printed and showed, and stop when it submits or its budget is spent. The
|
|
3
|
+
// same for every model; what differs by provider is in harness/adapters/.
|
|
4
|
+
//
|
|
5
|
+
// A conversation (from an adapter) has:
|
|
6
|
+
// ask() → { calls: [{ id, command } | { id, error }], text, ended, id, servedModel, usage, raw }
|
|
7
|
+
// ended: 'calls' | 'complete' | 'refused' | 'truncated'
|
|
8
|
+
// usage: { input, output, cached, reasoning, cost? } (input includes cached)
|
|
9
|
+
// answer(results) results: [{ id, text, images: [{ mime, data }] }], one per call, in order
|
|
10
|
+
// say(text) a plain user message, for a reply that ran no command
|
|
11
|
+
// close() forget anything the provider stored for this conversation
|
|
12
|
+
|
|
13
|
+
import { ProviderError } from '../src/model-apis.js';
|
|
14
|
+
import { cutOff, noCommand } from './request.mjs';
|
|
15
|
+
|
|
16
|
+
const ASK_ATTEMPTS = 3;
|
|
17
|
+
|
|
18
|
+
/** What the model reads back after a command. */
|
|
19
|
+
export function resultText(done, budget, limits) {
|
|
20
|
+
let output = done.output;
|
|
21
|
+
if (output.length > limits.outputChars) {
|
|
22
|
+
const half = limits.outputChars / 2;
|
|
23
|
+
output = `${output.slice(0, half)}\n[... ${output.length - limits.outputChars} characters left out; send long output to a file and read the part you need ...]\n${output.slice(-half)}`;
|
|
24
|
+
}
|
|
25
|
+
const status = done.timedOut ? `stopped after ${limits.commandSeconds} seconds` : `exit code ${done.code}`;
|
|
26
|
+
return `${status}\n${output}${output.endsWith('\n') || !output ? '' : '\n'}[${budget}]`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** "reply 7 of 30, minute 12 of 60": what is used, so what is left is plain. */
|
|
30
|
+
export const budgetLine = (replies, startedAt, limits, now = Date.now()) =>
|
|
31
|
+
`reply ${replies} of ${limits.replies}, minute ${Math.min(limits.minutes, Math.floor((now - startedAt) / 60000))} of ${limits.minutes}`;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Runs one drawing. Returns
|
|
35
|
+
* { exit, replies, looks, seconds, usage, responseIds, servedModel, svg, transcript, raw }
|
|
36
|
+
* `exit` is 'submitted', 'replies' or 'time' (budget spent), 'refused', or
|
|
37
|
+
* 'no-commands'. A ProviderError means the API failed past its retries: the
|
|
38
|
+
* run is not an answer and can be made again.
|
|
39
|
+
*/
|
|
40
|
+
export async function draw({ conversation, sandbox, limits, onReply }) {
|
|
41
|
+
const startedAt = Date.now();
|
|
42
|
+
const usage = { input: 0, output: 0, cached: 0, reasoning: 0, cost: 0 };
|
|
43
|
+
const transcript = [];
|
|
44
|
+
const raw = [];
|
|
45
|
+
const responseIds = [];
|
|
46
|
+
let servedModel = null;
|
|
47
|
+
let replies = 0;
|
|
48
|
+
let looks = 0;
|
|
49
|
+
let misses = 0;
|
|
50
|
+
let exit = null;
|
|
51
|
+
|
|
52
|
+
while (!exit) {
|
|
53
|
+
if (replies >= limits.replies) exit = 'replies';
|
|
54
|
+
else if (Date.now() - startedAt >= limits.minutes * 60000) exit = 'time';
|
|
55
|
+
if (exit) break;
|
|
56
|
+
|
|
57
|
+
let turn;
|
|
58
|
+
for (let attempt = 1; ; attempt++) {
|
|
59
|
+
try {
|
|
60
|
+
turn = await conversation.ask();
|
|
61
|
+
break;
|
|
62
|
+
} catch (error) {
|
|
63
|
+
// A dropped connection loses the reply, not the conversation: ask again.
|
|
64
|
+
if (!(error instanceof ProviderError) || error.fatal || attempt >= ASK_ATTEMPTS) throw error;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
replies += 1;
|
|
68
|
+
for (const key of Object.keys(usage)) usage[key] += turn.usage?.[key] ?? 0;
|
|
69
|
+
if (turn.id) responseIds.push(turn.id);
|
|
70
|
+
servedModel = turn.servedModel ?? servedModel;
|
|
71
|
+
raw.push(turn.raw ?? null);
|
|
72
|
+
transcript.push({ role: 'model', id: turn.id ?? null, ended: turn.ended, text: turn.text ?? '', calls: turn.calls, usage: turn.usage ?? null, at: new Date().toISOString() });
|
|
73
|
+
onReply?.({ replies, looks, turn });
|
|
74
|
+
|
|
75
|
+
if (turn.ended === 'refused') {
|
|
76
|
+
exit = 'refused';
|
|
77
|
+
break;
|
|
78
|
+
}
|
|
79
|
+
if (!turn.calls.length) {
|
|
80
|
+
misses += 1;
|
|
81
|
+
if (misses >= limits.misses) {
|
|
82
|
+
exit = 'no-commands';
|
|
83
|
+
break;
|
|
84
|
+
}
|
|
85
|
+
const said = turn.ended === 'truncated' ? cutOff : noCommand;
|
|
86
|
+
conversation.say(said);
|
|
87
|
+
transcript.push({ role: 'harness', text: said });
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
misses = 0;
|
|
91
|
+
|
|
92
|
+
const budget = budgetLine(replies, startedAt, limits);
|
|
93
|
+
const results = [];
|
|
94
|
+
for (const call of turn.calls) {
|
|
95
|
+
if (exit === 'submitted') {
|
|
96
|
+
results.push({ id: call.id, text: 'Not run: the drawing was already submitted.', images: [] });
|
|
97
|
+
} else if (call.error) {
|
|
98
|
+
results.push({ id: call.id, text: `${call.error}\n[${budget}]`, images: [] });
|
|
99
|
+
} else {
|
|
100
|
+
const done = await sandbox.run(call.command);
|
|
101
|
+
looks += done.images.length;
|
|
102
|
+
results.push({ id: call.id, text: resultText(done, budget, limits), images: done.images });
|
|
103
|
+
if (done.submitted) exit = 'submitted';
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
transcript.push({ role: 'results', results });
|
|
107
|
+
if (!exit) conversation.answer(results);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const svg = await sandbox.read('drawing.svg');
|
|
111
|
+
await conversation.close?.().catch(() => {});
|
|
112
|
+
usage.cost = usage.cost ? Math.round(usage.cost * 10000) / 10000 : null;
|
|
113
|
+
return { exit, replies, looks, seconds: Math.round((Date.now() - startedAt) / 1000), usage, responseIds, servedModel, svg, transcript, raw };
|
|
114
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// List prices in dollars per million tokens, for the summary line and the
|
|
2
|
+
// log when a provider doesn't report what a run cost (OpenRouter does). An
|
|
3
|
+
// estimate: cached input is taken at a tenth of the input price, and
|
|
4
|
+
// Anthropic's surcharge for writing to its cache is left out. Prices as
|
|
5
|
+
// LiteLLM listed them on 16 November 2026; Claude Haiku 5.5 from Anthropic's
|
|
6
|
+
// list and the GPT-6.1 and 6.2 models from OpenAI's (credits at 25 to the
|
|
7
|
+
// dollar), 18 November 2026; GPT-6 Luna from the Codex rate card, 30 November.
|
|
8
|
+
const PRICES = {
|
|
9
|
+
'claude-fable-5-2': { input: 8, output: 40 },
|
|
10
|
+
'claude-opus-5-5': { input: 4, output: 20 },
|
|
11
|
+
'claude-sonnet-5-5': { input: 2, output: 10 },
|
|
12
|
+
'claude-haiku-5-5': { input: 0.1, output: 0.5 },
|
|
13
|
+
'gemini-4-carbon': { input: 2, output: 10 },
|
|
14
|
+
'gemini-4-hydrogen': { input: 1.5, output: 7.5 },
|
|
15
|
+
'gpt-6-astra': { input: 10, output: 50 },
|
|
16
|
+
'gpt-6.1-sol': { input: 2, output: 10 },
|
|
17
|
+
'gpt-6.1-terra': { input: 1, output: 5 },
|
|
18
|
+
'gpt-6-luna': { input: 0.1, output: 0.5 },
|
|
19
|
+
'gpt-6.2-sol': { input: 2, output: 10 },
|
|
20
|
+
'gpt-6.2-astra': { input: 8, output: 40 },
|
|
21
|
+
'grok-4-7': { input: 2, output: 6 },
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
/** Dollars for `usage` ({ input, output, cached }, input including cached), or null if the model's price isn't known. */
|
|
25
|
+
export function estimate(modelId, usage) {
|
|
26
|
+
const price = PRICES[modelId];
|
|
27
|
+
if (!price) return null;
|
|
28
|
+
const fresh = Math.max(0, usage.input - usage.cached);
|
|
29
|
+
return Math.round(((fresh * price.input + usage.cached * price.input * 0.1 + usage.output * price.output) / 1e6) * 10000) / 10000;
|
|
30
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// What a model is told when it draws with tools, and the one tool it gets.
|
|
2
|
+
// The same words, tool and budget for every model and every prompt.
|
|
3
|
+
//
|
|
4
|
+
// The first three blocks are the plain request's (bench.config.mjs
|
|
5
|
+
// `instruction`), word for word, which test/harness.test.mjs holds them to.
|
|
6
|
+
// "How you work" takes the place of its last two paragraphs. Nothing else is
|
|
7
|
+
// sent: no system prompt.
|
|
8
|
+
|
|
9
|
+
/** Written to every log. Bump `version` when the request, the tool, the loop or the budget changes. */
|
|
10
|
+
export const HARNESS = { name: 'vectorbench-harness', version: 3 };
|
|
11
|
+
|
|
12
|
+
/** The same budget for every model. A reply is one answer from the model, with as many commands in it as it likes. */
|
|
13
|
+
export const limits = {
|
|
14
|
+
// 40 since version 2 (18 November 2026): with 30, one run in six used 29
|
|
15
|
+
// or 30 replies and nine ran out before they submitted.
|
|
16
|
+
replies: 40,
|
|
17
|
+
minutes: 60,
|
|
18
|
+
commandSeconds: 120,
|
|
19
|
+
// More output than this from one command is cut to its start and end.
|
|
20
|
+
outputChars: 10_000,
|
|
21
|
+
// Replies in a row with no command before the run is given up.
|
|
22
|
+
misses: 3,
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** The budget of version 1 (17 November 2026). */
|
|
26
|
+
export const firstLimits = { ...limits, replies: 30 };
|
|
27
|
+
|
|
28
|
+
/** The one tool. Its result is what the command printed, with any picture `view` made. */
|
|
29
|
+
export const tool = {
|
|
30
|
+
name: 'bash',
|
|
31
|
+
description: 'Run a bash command in the sandbox. Returns its exit code and what it printed, with any image `view` made.',
|
|
32
|
+
parameters: {
|
|
33
|
+
type: 'object',
|
|
34
|
+
properties: { command: { type: 'string', description: 'The bash command to run.' } },
|
|
35
|
+
required: ['command'],
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
// Version 3 (18 November 2026, sandbox image 7), from test runs of version 2:
|
|
40
|
+
// a bullet of its own for 3D and vb3d, import names, font files, no diagram
|
|
41
|
+
// marks (the owner's choice, for the pulsar's spin arrows), a close check of
|
|
42
|
+
// every part before submitting, and /work/README.md.
|
|
43
|
+
//
|
|
44
|
+
// Version 2 (18 November 2026, sandbox image 4). The owner wanted the models
|
|
45
|
+
// to lean on the tools for what code does better than hand-written markup:
|
|
46
|
+
// structure, repetition, organic form, light and lettering, the way GPT-6.2
|
|
47
|
+
// Astra drew its jellyfish under version 1: a 380-line generator (splines,
|
|
48
|
+
// a curve fitter, lighting worked out per fold) refined over 12 versions.
|
|
49
|
+
export const request = (prompt, budget = limits) => `Draw this as an SVG: ${prompt}
|
|
50
|
+
|
|
51
|
+
This drawing is your entry in VectorBench, a blind contest between AI models. People will see it next to another model's drawing of the same subject, without being told which model made which, and vote for the better one. Make it as good as you possibly can. Go all out.
|
|
52
|
+
|
|
53
|
+
What wins votes:
|
|
54
|
+
- It shows exactly what was asked. Every part of the request is there and correct: the subject, what it is doing, and any number, time, words or arrangement the request names.
|
|
55
|
+
- It is beautifully made: a strong composition that fills the frame, a setting that suits the subject, a deliberate colour palette, and depth, light and shadow, with gradients and texture where they help.
|
|
56
|
+
- It holds up when looked at closely: true proportions, anatomy and mechanics, and fine detail that rewards a second look.
|
|
57
|
+
|
|
58
|
+
How it will be shown:
|
|
59
|
+
- In a square frame, anywhere from a phone thumbnail to most of a screen. Give it a square viewBox (for example 0 0 1024 1024) and make it read well at every size.
|
|
60
|
+
- In a browser's <img> tag: no scripts or links, and nothing loaded from outside the file. Draw with vector shapes only, not embedded bitmaps. For any words, use a generic font family such as sans-serif or serif.
|
|
61
|
+
- Animation is welcome where the subject has motion of its own: wings beating, water rippling, smoke rising, light pulsing, something turning. SVG animation plays in the <img> tag: SMIL elements such as <animate> and <animateTransform>, or CSS animation in a <style> element. Make it a smooth, seamless loop, animate transforms and opacity rather than filters so it plays smoothly on a phone, and keep every moment a complete picture, the first included. A subject with no motion of its own is better left still.
|
|
62
|
+
|
|
63
|
+
How you work:
|
|
64
|
+
- You have one tool, bash, in a Linux sandbox with no network, two CPU cores and 4 GB of memory. Every reply must call it at least once. Each command runs in a fresh shell in /work, so \`cd\` and variables do not carry over to the next command, but files do. A command is stopped after ${budget.commandSeconds} seconds.
|
|
65
|
+
- Your entry is the file /work/drawing.svg. It has to be under 200 KB and pass the site's check for anything that is not a plain drawing; \`check drawing.svg\` tells you whether it does.
|
|
66
|
+
- You have ${budget.replies} replies and ${budget.minutes} minutes in all, and each result says how much is left. When the drawing is as good as you can make it, run \`submit\`; after that nothing can be changed. If your replies or your time run out first, drawing.svg as it stands is your entry, so save a complete drawing early and improve it from there. A missing file, or one that fails the check, counts as no drawing.
|
|
67
|
+
|
|
68
|
+
Build it with code:
|
|
69
|
+
A program that models the subject can draw far more, and far more accurately, than markup written by hand, so give the hard parts to code and spend your own effort on judgement. Code is the better hand wherever there is structure, repetition or calculation:
|
|
70
|
+
- The subject's real structure: proportions, anatomy, mechanisms, perspective, symmetry and the way parts fit. Write what you know of the real thing into your code as numbers (its measurements, where each part sits and how big it is) and place every part from them, not by eye.
|
|
71
|
+
- Solid objects in 3D: machines, devices, vehicles, buildings and anything whose parts hide and shade one another can be built as 3D meshes (trimesh, manifold3d) and drawn with the Python module \`vb3d\`, which removes hidden surfaces, shades each part from your lights with cast shadows and highlights, and gives you each part's exact outline to draw over (\`python3 -c 'import vb3d; help(vb3d)'\` shows how).
|
|
72
|
+
- Repetition with variation: scales, feathers, fur, leaves, bricks, stones, ripples, stars, cables, buttons, rivets and any crowd of small parts, each a little different, as real ones are.
|
|
73
|
+
- Organic form and surface: curves through splines, edges and textures shaped by noise, wear, grain and pattern that follow the form.
|
|
74
|
+
- Light and colour: shading worked out from where the light comes from, highlights, reflections, cast shadows and soft glows, with gradients and palettes chosen in a perceptual colour space.
|
|
75
|
+
- Animation, where the subject moves: timing worked out in code, with phases offset so parts don't move in lockstep, and loops that join without a jump.
|
|
76
|
+
- Lettering set in a real typeface and turned into outlines, so it looks the same in every browser.
|
|
77
|
+
Work from what the real thing looks like, part by part: what it is made of, how it is put together, and the small details someone who knows it would look for. There are no reference pictures in the sandbox, so work from what you know. Draw the thing itself, not a diagram of it: leave out arrows, axis lines, callouts and other marks that are not part of the scene, unless the request asks for them or the subject is itself a diagram, such as a flowchart. Write a long program in several commands (for example \`cat >> gen.py\`) rather than in one reply. Keep a copy of every version you are happy with before you change it.
|
|
78
|
+
|
|
79
|
+
Look at it and fix it:
|
|
80
|
+
- \`view drawing.svg\` shows you the drawing as voters will see it: drawn by Chromium in an <img> tag on a white square frame, 1024 pixels wide. \`view FILE SIZE\` uses another width (128 is a thumbnail), and \`view\` also shows PNG and JPEG files.
|
|
81
|
+
- \`zoom drawing.svg X Y W H\` shows the region from (X, Y), W wide and H high in the drawing's own coordinates, close up: look at the details people will look at. \`compare old.svg drawing.svg\` shows two to four versions side by side. \`render IN.svg OUT.png [SIZE]\` saves the picture as a file, to crop, enlarge or measure.
|
|
82
|
+
- \`view\` shows whatever moment the browser happens to draw. \`frames drawing.svg\` shows four moments of the drawing's motion side by side, and \`frames drawing.svg 0 0.4 1.5\` the moments you name, in seconds, to check that it moves as it should and is complete at every moment.
|
|
83
|
+
- Generated detail adds up quickly. \`weigh drawing.svg\` says where the bytes go, and \`shrink IN.svg OUT.svg\` makes a file smaller with SVGO and tells you whether the picture changed. Round coordinates to a decimal place or none, draw a repeated shape once and place it with <use>, and spend the bytes where people will look.
|
|
84
|
+
- After each change, look again, find what still looks wrong, flat or unfinished, and fix it in the code. Get the subject right before you polish the setting around it. Don't stop at the first good version: before you submit, go over every part close up against what you know of the real thing, and keep fixing what is wrong or missing while you have replies left.
|
|
85
|
+
|
|
86
|
+
Also installed: Python 3 with numpy, scipy, sympy, Pillow, lxml, shapely, skia-pathops (\`import pathops\`; boolean operations on curved paths), opensimplex (noise), coloraide (perceptual colour), trimesh and manifold3d (3D meshes and solids) and vb3d (drawing them), networkx, fontTools, matplotlib, scikit-image, OpenCV (\`import cv2\`), cairosvg, vtracer and potrace (tracing a raster you have computed into paths), svgpathtools, svgwrite and svgelements; Node.js; Inkscape (\`inkscape --export-text-to-path\` outlines lettering); Graphviz; SVGO; ImageMagick; rsvg-convert; xmllint; and open-licence typefaces, which \`fc-list : family file\` lists with their files. /work/README.md is a short guide to all of it.`;
|
|
87
|
+
|
|
88
|
+
// What version 2 (18 November 2026, sandbox image 6) sent, word for word, for
|
|
89
|
+
// the method page and the record: Claude Haiku 5.5's and GPT-6.1 Terra's first
|
|
90
|
+
// drawings were made with it.
|
|
91
|
+
export const secondRequest = (prompt, budget = limits) => `Draw this as an SVG: ${prompt}
|
|
92
|
+
|
|
93
|
+
This drawing is your entry in VectorBench, a blind contest between AI models. People will see it next to another model's drawing of the same subject, without being told which model made which, and vote for the better one. Make it as good as you possibly can. Go all out.
|
|
94
|
+
|
|
95
|
+
What wins votes:
|
|
96
|
+
- It shows exactly what was asked. Every part of the request is there and correct: the subject, what it is doing, and any number, time, words or arrangement the request names.
|
|
97
|
+
- It is beautifully made: a strong composition that fills the frame, a setting that suits the subject, a deliberate colour palette, and depth, light and shadow, with gradients and texture where they help.
|
|
98
|
+
- It holds up when looked at closely: true proportions, anatomy and mechanics, and fine detail that rewards a second look.
|
|
99
|
+
|
|
100
|
+
How it will be shown:
|
|
101
|
+
- In a square frame, anywhere from a phone thumbnail to most of a screen. Give it a square viewBox (for example 0 0 1024 1024) and make it read well at every size.
|
|
102
|
+
- In a browser's <img> tag: no scripts or links, and nothing loaded from outside the file. Draw with vector shapes only, not embedded bitmaps. For any words, use a generic font family such as sans-serif or serif.
|
|
103
|
+
- Animation is welcome where the subject has motion of its own: wings beating, water rippling, smoke rising, light pulsing, something turning. SVG animation plays in the <img> tag: SMIL elements such as <animate> and <animateTransform>, or CSS animation in a <style> element. Make it a smooth, seamless loop, animate transforms and opacity rather than filters so it plays smoothly on a phone, and keep every moment a complete picture, the first included. A subject with no motion of its own is better left still.
|
|
104
|
+
|
|
105
|
+
How you work:
|
|
106
|
+
- You have one tool, bash, in a Linux sandbox with no network, two CPU cores and 4 GB of memory. Every reply must call it at least once. Each command runs in a fresh shell in /work, so \`cd\` and variables do not carry over to the next command, but files do. A command is stopped after ${budget.commandSeconds} seconds.
|
|
107
|
+
- Your entry is the file /work/drawing.svg. It has to be under 200 KB and pass the site's check for anything that is not a plain drawing; \`check drawing.svg\` tells you whether it does.
|
|
108
|
+
- You have ${budget.replies} replies and ${budget.minutes} minutes in all, and each result says how much is left. When the drawing is as good as you can make it, run \`submit\`; after that nothing can be changed. If your replies or your time run out first, drawing.svg as it stands is your entry, so save a complete drawing early and improve it from there. A missing file, or one that fails the check, counts as no drawing.
|
|
109
|
+
|
|
110
|
+
Build it with code:
|
|
111
|
+
A program that models the subject can draw far more, and far more accurately, than markup written by hand, so give the hard parts to code and spend your own effort on judgement. Code is the better hand wherever there is structure, repetition or calculation:
|
|
112
|
+
- The subject's real structure: proportions, anatomy, mechanisms, perspective, symmetry and the way parts fit. Write what you know of the real thing into your code as numbers (its measurements, where each part sits and how big it is) and place every part from them, not by eye. Model a solid object in 3D and project it if that is easier.
|
|
113
|
+
- Repetition with variation: scales, feathers, fur, leaves, bricks, stones, ripples, stars, cables, buttons, rivets and any crowd of small parts, each a little different, as real ones are.
|
|
114
|
+
- Organic form and surface: curves through splines, edges and textures shaped by noise, wear, grain and pattern that follow the form.
|
|
115
|
+
- Light and colour: shading worked out from where the light comes from, highlights, reflections, cast shadows and soft glows, with gradients and palettes chosen in a perceptual colour space.
|
|
116
|
+
- Animation, where the subject moves: timing worked out in code, with phases offset so parts don't move in lockstep, and loops that join without a jump.
|
|
117
|
+
- Lettering set in a real typeface and turned into outlines, so it looks the same in every browser.
|
|
118
|
+
Work from what the real thing looks like, part by part: what it is made of, how it is put together, and the small details someone who knows it would look for. There are no reference pictures in the sandbox, so work from what you know. Write a long program in several commands (for example \`cat >> gen.py\`) rather than in one reply. Keep a copy of every version you are happy with before you change it.
|
|
119
|
+
|
|
120
|
+
Look at it and fix it:
|
|
121
|
+
- \`view drawing.svg\` shows you the drawing as voters will see it: drawn by Chromium in an <img> tag on a white square frame, 1024 pixels wide. \`view FILE SIZE\` uses another width (128 is a thumbnail), and \`view\` also shows PNG and JPEG files.
|
|
122
|
+
- \`zoom drawing.svg X Y W H\` shows the region from (X, Y), W wide and H high in the drawing's own coordinates, close up: look at the details people will look at. \`compare old.svg drawing.svg\` shows two to four versions side by side. \`render IN.svg OUT.png [SIZE]\` saves the picture as a file, to crop, enlarge or measure.
|
|
123
|
+
- \`view\` shows whatever moment the browser happens to draw. \`frames drawing.svg\` shows four moments of the drawing's motion side by side, and \`frames drawing.svg 0 0.4 1.5\` the moments you name, in seconds, to check that it moves as it should and is complete at every moment.
|
|
124
|
+
- Generated detail adds up quickly. \`weigh drawing.svg\` says where the bytes go, and \`shrink IN.svg OUT.svg\` makes a file smaller with SVGO and tells you whether the picture changed. Round coordinates to a decimal place or none, draw a repeated shape once and place it with <use>, and spend the bytes where people will look.
|
|
125
|
+
- After each change, look again, find what still looks wrong, flat or unfinished, and fix it in the code. Get the subject right before you polish the setting around it.
|
|
126
|
+
|
|
127
|
+
Also installed: Python 3 with numpy, scipy, sympy, Pillow, lxml, shapely, skia-pathops (boolean operations on curved paths), opensimplex (noise), coloraide (perceptual colour), trimesh and manifold3d (3D meshes and solids), networkx, fontTools, matplotlib, scikit-image, cairosvg, vtracer and potrace (tracing a raster you have computed into paths), svgpathtools, svgwrite and svgelements; Node.js; Inkscape (\`inkscape --export-text-to-path\` outlines lettering); Graphviz; SVGO; ImageMagick; rsvg-convert; xmllint; and open-licence typefaces, which \`fc-list : family\` lists.`;
|
|
128
|
+
|
|
129
|
+
// What version 1 (17 November 2026, sandbox image 3) sent, word for word, for
|
|
130
|
+
// the method page and the record. Each drawing's log keeps its own request.
|
|
131
|
+
export const firstRequest = (prompt, budget = firstLimits) => `Draw this as an SVG: ${prompt}
|
|
132
|
+
|
|
133
|
+
This drawing is your entry in VectorBench, a blind contest between AI models. People will see it next to another model's drawing of the same subject, without being told which model made which, and vote for the better one. Make it as good as you possibly can. Go all out.
|
|
134
|
+
|
|
135
|
+
What wins votes:
|
|
136
|
+
- It shows exactly what was asked. Every part of the request is there and correct: the subject, what it is doing, and any number, time, words or arrangement the request names.
|
|
137
|
+
- It is beautifully made: a strong composition that fills the frame, a setting that suits the subject, a deliberate colour palette, and depth, light and shadow, with gradients and texture where they help.
|
|
138
|
+
- It holds up when looked at closely: true proportions, anatomy and mechanics, and fine detail that rewards a second look.
|
|
139
|
+
|
|
140
|
+
How it will be shown:
|
|
141
|
+
- In a square frame, anywhere from a phone thumbnail to most of a screen. Give it a square viewBox (for example 0 0 1024 1024) and make it read well at every size.
|
|
142
|
+
- As a still image in a browser's <img> tag: no scripts, animation or links, and nothing loaded from outside the file. Draw with vector shapes only, not embedded bitmaps. For any words, use a generic font family such as sans-serif or serif.
|
|
143
|
+
|
|
144
|
+
How you work:
|
|
145
|
+
- You have one tool, bash, in a Linux sandbox with no network. Every reply must call it at least once. Each command runs in a fresh shell in /work, so \`cd\` and variables do not carry over to the next command, and a command is stopped after ${budget.commandSeconds} seconds.
|
|
146
|
+
- \`view drawing.svg\` shows you the drawing as voters will see it: drawn by Chromium in an <img> tag on a white square frame, 1024 pixels wide. \`view FILE SIZE\` uses another width (128 is a thumbnail), and \`view\` also shows PNG and JPEG files. \`render IN.svg OUT.png [SIZE]\` saves the same picture as a file, to crop, enlarge or measure.
|
|
147
|
+
- Also installed: Python 3 with numpy, scipy, Pillow, lxml, shapely, fontTools, matplotlib, scikit-image, cairosvg, svgpathtools, svgwrite and svgelements; Node.js; Inkscape; ImageMagick; rsvg-convert; potrace; xmllint. Use any of them, or none.
|
|
148
|
+
- Your entry is the file /work/drawing.svg. Write it by hand, generate it with code, or both. It has to be under 200 KB and pass the site's check for anything that is not a plain drawing; \`check drawing.svg\` tells you whether it does.
|
|
149
|
+
- You have ${budget.replies} replies and ${budget.minutes} minutes in all, and each result says how much is left. When the drawing is as good as you can make it, run \`submit\`; after that nothing can be changed. If your replies or your time run out first, drawing.svg as it stands is your entry, so save a complete drawing early and improve it from there. A missing file, or one that fails the check, counts as no drawing.`;
|
|
150
|
+
|
|
151
|
+
/** Said when a reply calls no command. */
|
|
152
|
+
export const noCommand = 'That reply ran no command. Every reply has to call the bash tool at least once. When the drawing is finished, run `submit`.';
|
|
153
|
+
|
|
154
|
+
/** Said when a reply hit its output limit before it called the tool. */
|
|
155
|
+
export const cutOff = 'That reply reached your output limit before it ran a command, so it was cut off and nothing was done. Call the bash tool in every reply, and write a long file in several commands if you need to.';
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// One container per drawing: no network, the same image for every model
|
|
2
|
+
// (harness/Dockerfile). A command runs in a fresh shell in /work; whatever
|
|
3
|
+
// `view` left in the spool comes back with it as images.
|
|
4
|
+
|
|
5
|
+
import { execFile } from 'node:child_process';
|
|
6
|
+
|
|
7
|
+
export const IMAGE = 'vectorbench-sandbox:7';
|
|
8
|
+
const WORK = '/work';
|
|
9
|
+
const MAX_BUFFER = 256 * 1024 * 1024;
|
|
10
|
+
|
|
11
|
+
function docker(args, { input, timeoutMs = 60_000 } = {}) {
|
|
12
|
+
return new Promise((resolve) => {
|
|
13
|
+
const child = execFile('docker', args, { maxBuffer: MAX_BUFFER, timeout: timeoutMs, encoding: 'utf8' }, (error, stdout, stderr) => {
|
|
14
|
+
resolve({ code: error ? (typeof error.code === 'number' ? error.code : -1) : 0, stdout, stderr, killed: Boolean(error?.killed) });
|
|
15
|
+
});
|
|
16
|
+
if (input !== undefined) child.stdin.end(input);
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The image's id, for the log: the tag can be rebuilt, the id can't. */
|
|
21
|
+
export async function imageId(image = IMAGE) {
|
|
22
|
+
const { code, stdout } = await docker(['image', 'inspect', '--format', '{{.Id}}', image]);
|
|
23
|
+
return code === 0 ? stdout.trim() : null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Starts a sandbox. `commandSeconds` is how long one command may run.
|
|
28
|
+
* Returns { run(command), read(path), close() }.
|
|
29
|
+
*/
|
|
30
|
+
export async function openSandbox({ image = IMAGE, commandSeconds = 120 } = {}) {
|
|
31
|
+
// --init: a real PID 1 that reaps exited processes. Under plain `sleep` every
|
|
32
|
+
// browser a command started stayed in the process table as a zombie, and
|
|
33
|
+
// enough of them would reach the --pids-limit and stop the sandbox forking.
|
|
34
|
+
const started = await docker(['run', '-d', '--rm', '--init', '--network', 'none', '--memory', '4g', '--cpus', '2', '--pids-limit', '512', '-w', WORK, image, 'sleep', '6h']);
|
|
35
|
+
if (started.code !== 0) throw new Error(`couldn't start the sandbox: ${started.stderr.trim()}`);
|
|
36
|
+
return sandboxFor(started.stdout.trim(), { image, commandSeconds });
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The same handle for a sandbox that is already running (by container id). */
|
|
40
|
+
export function sandboxFor(id, { image = IMAGE, commandSeconds = 120 } = {}) {
|
|
41
|
+
return {
|
|
42
|
+
id,
|
|
43
|
+
image,
|
|
44
|
+
commandSeconds,
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Runs one command as the model wrote it. Returns
|
|
48
|
+
* { code, output, timedOut, images: [{ mime, data }], submitted }
|
|
49
|
+
* `output` is stdout and stderr together, in the order they were written.
|
|
50
|
+
*/
|
|
51
|
+
async run(command) {
|
|
52
|
+
// `timeout` inside the container, so the command itself is stopped,
|
|
53
|
+
// not just our wait for it.
|
|
54
|
+
const done = await docker(
|
|
55
|
+
['exec', '-w', WORK, '-e', 'PAGER=cat', '-e', 'MANPAGER=cat', '-e', 'LESS=-R', id, 'timeout', '-k', '5', `${commandSeconds}s`, 'bash', '-lc', `exec 2>&1\n${command}`],
|
|
56
|
+
{ timeoutMs: (commandSeconds + 30) * 1000 },
|
|
57
|
+
);
|
|
58
|
+
const timedOut = done.code === 124 || done.code === 137 || done.killed;
|
|
59
|
+
const collected = await docker(['exec', id, 'python3', '/opt/vb/tools.py', 'collect']);
|
|
60
|
+
let extra = { images: [], submitted: false };
|
|
61
|
+
try {
|
|
62
|
+
extra = JSON.parse(collected.stdout);
|
|
63
|
+
} catch {}
|
|
64
|
+
return { code: done.code, output: done.stdout + done.stderr, timedOut, images: extra.images, submitted: extra.submitted };
|
|
65
|
+
},
|
|
66
|
+
|
|
67
|
+
/** A file's text, or null if it isn't there. */
|
|
68
|
+
async read(path) {
|
|
69
|
+
const done = await docker(['exec', '-w', WORK, id, 'cat', path]);
|
|
70
|
+
return done.code === 0 ? done.stdout : null;
|
|
71
|
+
},
|
|
72
|
+
|
|
73
|
+
async close() {
|
|
74
|
+
await docker(['rm', '-f', id]);
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
}
|