vectorbench 0.0.0-stage → 3.0.0

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.
@@ -0,0 +1,933 @@
1
+ // The OpenAI models with tools on the owner's ChatGPT subscription: Codex CLI
2
+ // asks the model, and the one tool is ours, so the model gets the same
3
+ // request, the same tool, the same sandbox and the same budget as
4
+ // harness/loop.mjs gives it through the API. The model of this file is
5
+ // harness/claude-code.mjs, which does the same for Claude Code.
6
+ //
7
+ // What the model has (Codex 0.169.1, 18 November 2026): one tool, `bash`,
8
+ // a plain function with our description and schema, and nothing else. No
9
+ // instructions are sent at all, and the input is our request alone, then the
10
+ // model's own items, our results and the loop's "That reply ran no command"
11
+ // messages. Seen in the requests Codex sent to a stand-in for the Responses
12
+ // API, over HTTP and over a WebSocket, with this config and the live
13
+ // catalog entry for gpt-6.2-sol, and on ChatGPT in the probe's first reply:
14
+ // 215 input tokens for the probe's request and the tool, where Codex's own
15
+ // instructions for gpt-6.2-sol are 27,750 characters. Every run also reads
16
+ // the first request Codex sends from its log and checks it (`request`: the
17
+ // run fails if Codex offers another tool, sends instructions or adds a
18
+ // message); a frame it can't read (compressed) is counted in the session
19
+ // record as `requestsUnread`, not taken as checked. Nothing was left that
20
+ // Codex can't switch off. With the
21
+ // catalog entry as ChatGPT gives it (seen with gpt-6.1-terra's; gpt-6.2-sol's
22
+ // says the same and lists more experimental tools), Codex, `codex exec` as
23
+ // much as the app-server, gives the model one JavaScript `exec` tool with
24
+ // every other tool inside it (the shell, apply_patch, goals, MCP tools),
25
+ // beside sub-agent, clock (sleep) and request_user_input tools, and its
26
+ // own instructions as a developer message; with the config alone and not
27
+ // the catalog change, the clock's curr_time stayed.
28
+ //
29
+ // Pictures reach the model: in the probe it wrote back the number in the
30
+ // picture `view` showed it and described its own drawing, and Codex's
31
+ // record of what it sent has both pictures in the results, byte for byte,
32
+ // with no `detail` (as loop.mjs sends them).
33
+ //
34
+ // What Codex sends that loop.mjs does not:
35
+ // - Settings: `text.verbosity` "medium" (the API's default, set here; the
36
+ // catalog's is "low"); `store: false` with the model's encrypted reasoning
37
+ // sent back in each request (the API runs chain stored responses
38
+ // instead); `prompt_cache_key` and `client_metadata` (Codex's session,
39
+ // turn and installation ids); `strict: false` on the tool. No
40
+ // `max_output_tokens`: the API runs ask for 128,000, here ChatGPT's cap
41
+ // applies. Over the WebSocket, a warm-up message (`generate: false`)
42
+ // before the first request, which asks the model nothing.
43
+ // - Results: one with only text goes as a plain string, one with pictures
44
+ // as text and image parts (loop.mjs always sends parts).
45
+ // - A call whose arguments are not JSON is answered by Codex itself
46
+ // ("failed to parse function arguments: ..."), not in the loop's words;
47
+ // the transcript marks that result `by: 'codex'`.
48
+ // - No compaction (its threshold is set out of reach); if Codex compacts
49
+ // anyway the transcript says so, as claude-code.mjs does.
50
+ // - Codex retries a dropped stream itself; the retry is in `raw` as an
51
+ // `error` notification, and only a response that ends counts as a reply.
52
+ //
53
+ // Which Codex: the catalog ChatGPT gives a Codex depends on its version.
54
+ // 0.154.0 (on PATH here) lists no GPT-6.1 or 6.2 model; 0.169.1 (in
55
+ // ~/.cache/vectorbench/codex-cli, which the queue runs through CODEX_BIN)
56
+ // does. A model the catalog doesn't list fails the run, rather
57
+ // than run on Codex's fallback settings.
58
+ //
59
+ // How it runs. `codex app-server` (JSON-RPC over stdio), not `codex exec`:
60
+ // - The tool is a dynamic tool (thread/start `dynamicTools`): Codex sends
61
+ // each call to this process (`item/tool/call`, with the call's id) and puts
62
+ // our answer in the conversation as it is. Served over MCP instead (as
63
+ // claude-code.mjs does), the tool came to the model as `bash` in an
64
+ // `mcp__vb` namespace, beside three MCP resource tools (list_mcp_resources,
65
+ // list_mcp_resource_templates, read_mcp_resource) that no setting removes,
66
+ // and Codex put "Wall time: 0.0009 seconds\nOutput:" in front of every result.
67
+ // - With `experimentalRawEvents`, Codex reports every item the model gave
68
+ // back (`rawResponseItem/completed`) and the end of every response, with
69
+ // its id and usage (`rawResponse/completed`): one reply each, counted as
70
+ // loop.mjs counts them. `codex exec --json` shows neither, and ends at the
71
+ // first reply with no command, where the loop says so and goes on.
72
+ // - A call is answered only once its reply has ended, as loop.mjs runs a
73
+ // reply's commands, one at a time in the reply's order (Codex sends a
74
+ // reply's calls all at once). The run is stopped there, between a reply's
75
+ // last result and the next request: Codex is killed before it has the
76
+ // result, so the next request is never made.
77
+ // - Codex logs each request it sends, at trace: ChatGPT is asked over a
78
+ // WebSocket, whose frames the socket library logs (tungstenite::protocol;
79
+ // the handshake and auth targets stay off), and a stand-in over HTTP
80
+ // (codex_http_client::transport). The first request is checked and kept
81
+ // in the log's session record: the tools, the settings and the input it
82
+ // actually sent. Nothing else of that log is kept.
83
+ //
84
+ // What is switched off. Each run gets a Codex home of its own (CODEX_HOME)
85
+ // holding only the config below, a model catalog and a link to the ChatGPT
86
+ // login: none of the owner's config,
87
+ // instructions, AGENTS.md, skills, rules, memories, plugins or MCP servers.
88
+ // Codex's own tools, instructions and context come from two places, and
89
+ // both are set here:
90
+ // - The model's catalog entry, which Codex fetches from ChatGPT
91
+ // (`codex debug models`, no model call) and is given back changed
92
+ // (`catalogEntry`): no instructions (no `instructions` field is sent at
93
+ // all), tools as plain functions rather than inside Codex's JavaScript
94
+ // `exec` tool (the entry says `tool_mode: "code_mode_only"`), no tool
95
+ // search, no sub-agents, no apply_patch, no clock tools, and the Responses
96
+ // request in the API's own shape (tools in `tools`, parallel calls
97
+ // allowed, as the API's default is) rather than Codex's "lite" one, which
98
+ // sends the tools inside the input and parallel_tool_calls false.
99
+ // - The config: shell, exec, view_image, web search, apps, plugins,
100
+ // browser, computer use, image generation, skills, hooks, goals, memories,
101
+ // request_user_input and sub-agents off; no permissions, environment,
102
+ // apps or collaboration-mode messages; approval policy never.
103
+
104
+ import { spawn } from 'node:child_process';
105
+ import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises';
106
+ import { homedir, tmpdir } from 'node:os';
107
+ import { join } from 'node:path';
108
+ import { ProviderError } from '../src/model-apis.js';
109
+ import { describe, readLimits } from './codex-account.mjs';
110
+ import { budgetLine, resultText } from './loop.mjs';
111
+ import { noCommand } from './request.mjs';
112
+
113
+ const bin = () => process.env.CODEX_BIN || 'codex';
114
+
115
+ // What Codex and the model's commands inherit is only what a shell needs:
116
+ // nothing from the runner's environment (keys, tokens, the owner's CODEX_HOME).
117
+ const PASSED = ['PATH', 'HOME', 'USER', 'LOGNAME', 'SHELL', 'LANG', 'LANGUAGE', 'TERM', 'TZ', 'XDG_RUNTIME_DIR'];
118
+
119
+ /** The environment Codex runs in. */
120
+ export function codexEnvironment({ root }, from = process.env) {
121
+ const env = {};
122
+ for (const name of PASSED) if (from[name] != null) env[name] = from[name];
123
+ for (const [name, value] of Object.entries(from)) if (name.startsWith('LC_')) env[name] = value;
124
+ return { ...env, TERM: 'dumb', TMPDIR: join(root, 'tmp'), CODEX_HOME: join(root, 'home') };
125
+ }
126
+
127
+ /** The reason a run that failed isn't an answer, or null if it is one. Errors that end the batch are `fatal`. */
128
+ export function codexFailure(read, stderr = '') {
129
+ const said = [read.failed, ...read.errors].filter(Boolean).join(' ');
130
+ if (!said && read.completed) return null;
131
+ const why = said || stderr.trim().split('\n').slice(-3).join(' ') || 'Codex exited without finishing';
132
+ // A message that is a JSON error body: read its message.
133
+ let text = why;
134
+ try {
135
+ text = JSON.parse(why.slice(why.indexOf('{')))?.error?.message ?? why;
136
+ } catch {}
137
+ return {
138
+ message: `Codex: ${text.slice(0, 500)}`,
139
+ limit: /usage limit|rate limit|too many requests|429|quota|try again (in|at|later)/i.test(text),
140
+ fatal: /not supported when using codex|model_not_found|does not exist|unauthori[sz]ed|401|log ?in|authenticat|sandbox|bubblewrap/i.test(text),
141
+ };
142
+ }
143
+
144
+ /** `codex --version`, for the log. */
145
+ export function codexVersion() {
146
+ return new Promise((done) => {
147
+ const child = spawn(bin(), ['--version'], { stdio: ['ignore', 'pipe', 'ignore'] });
148
+ let out = '';
149
+ child.stdout.on('data', (chunk) => (out += chunk));
150
+ child.on('error', () => done(null));
151
+ child.on('close', () => done(out.trim().replace(/^codex-cli\s+/, '') || null));
152
+ });
153
+ }
154
+ // How far past the time budget a run may go (a long last reply, retries)
155
+ // before it is taken for stuck.
156
+ const GRACE_MINUTES = 30;
157
+ const RPC_TIMEOUT_MS = 120_000;
158
+ // What Codex logs: warnings, and at trace each request it sends, over HTTP
159
+ // or as a WebSocket frame (only the frames: not the handshake, not auth).
160
+ const LOG_LEVELS = 'warn,codex_http_client::transport=trace,tungstenite::protocol=trace,tungstenite::protocol::frame=warn';
161
+ export const CHATGPT_URL = 'https://chatgpt.com/backend-api/codex/responses';
162
+ const CHATGPT_SOCKET = 'wss://chatgpt.com/backend-api/codex/responses';
163
+
164
+ /** The plan's usage as Codex last reported it, for every run in this process. */
165
+ export const plan = { limits: null };
166
+
167
+ /* What Codex is given ------------------------------------------------------ */
168
+
169
+ /**
170
+ * The model's catalog entry as Codex fetched it, changed so that Codex adds
171
+ * nothing to the request: no instructions, our tool alone and as itself.
172
+ */
173
+ export function catalogEntry(live) {
174
+ const entry = structuredClone(live);
175
+ // Tools as plain functions, not inside Codex's JavaScript `exec` tool.
176
+ delete entry.tool_mode;
177
+ // No team of sub-agents, no apply_patch.
178
+ delete entry.multi_agent_version;
179
+ delete entry.multi_agent_reasoning_effort;
180
+ delete entry.apply_patch_tool_type;
181
+ return {
182
+ ...entry,
183
+ // No clock tools (curr_time, sleep) and no send_user_message_async.
184
+ experimental_supported_tools: [],
185
+ supports_search_tool: false,
186
+ include_skills_usage_instructions: false,
187
+ include_plugin_usage_instructions: false,
188
+ include_apps_usage_instructions: false,
189
+ // No system prompt: with no template, Codex sends no instructions.
190
+ base_instructions: '',
191
+ model_messages: { ...entry.model_messages, instructions_template: null, instructions_variables: null, persistent_instructions: null },
192
+ // The Responses request in the API's shape: tools in `tools`, and
193
+ // parallel calls allowed, the API's default.
194
+ use_responses_lite: false,
195
+ supports_parallel_tool_calls: true,
196
+ };
197
+ }
198
+
199
+ /** What catalogEntry changed, for the log: each key as it was and as it went in (long texts by length). */
200
+ export function catalogChanges(live) {
201
+ const changed = catalogEntry(live);
202
+ const shown = (value) => (typeof value === 'string' && value.length > 80 ? `[${value.length} characters]` : (value ?? null));
203
+ const changes = {};
204
+ for (const key of new Set([...Object.keys(live), ...Object.keys(changed)])) {
205
+ if (key === 'model_messages') continue;
206
+ if (JSON.stringify(live[key]) !== JSON.stringify(changed[key])) changes[key] = { was: shown(live[key]), now: key in changed ? shown(changed[key]) : '(removed)' };
207
+ }
208
+ for (const key of ['instructions_template', 'instructions_variables', 'persistent_instructions']) {
209
+ const was = live.model_messages?.[key];
210
+ if (was != null) changes[`model_messages.${key}`] = { was: shown(typeof was === 'string' ? was : JSON.stringify(was)), now: null };
211
+ }
212
+ return changes;
213
+ }
214
+
215
+ const toml = (value) => JSON.stringify(value); // a TOML basic string is a JSON string for everything we write
216
+
217
+ // Codex's built-in features that would give the model something besides our tool.
218
+ export const FEATURES_OFF = [
219
+ 'shell_tool', 'unified_exec', 'view_image', 'multi_agent_v2', 'sleep_tool', 'apps', 'plugins', 'remote_plugin',
220
+ 'browser_use', 'browser_use_external', 'browser_use_full_cdp_access', 'computer_use', 'image_generation',
221
+ 'in_app_browser', 'in_app_chat', 'skill_search', 'tool_suggest', 'hooks', 'goals', 'memories',
222
+ 'code_mode', 'code_mode_only', 'code_mode_host',
223
+ ];
224
+
225
+ /** The config.toml for one run. `provider` (a base URL) is for tests against a stand-in for the API. */
226
+ export function configFor({ model, effort, catalog, summaries = false, provider = null }) {
227
+ return `# VectorBench standard-harness run through Codex (harness/codex.mjs). Not the owner's Codex config.
228
+ ${provider ? 'model_provider = "stand-in"\n' : ''}model = ${toml(model)}
229
+ model_catalog_json = ${toml(catalog)}
230
+ ${effort ? `model_reasoning_effort = ${toml(effort)}\n` : ''}model_reasoning_summary = ${toml(summaries ? 'auto' : 'none')}
231
+ # The API's default, which the API runs get by sending none.
232
+ model_verbosity = "medium"
233
+ # No compaction: the conversation is the model's alone, as through the API.
234
+ model_auto_compact_token_limit = 1000000000
235
+ approval_policy = "never"
236
+ sandbox_mode = "read-only"
237
+ web_search = "disabled"
238
+ check_for_update_on_startup = false
239
+ include_permissions_instructions = false
240
+ include_environment_context = false
241
+ include_apps_instructions = false
242
+ include_collaboration_mode_instructions = false
243
+
244
+ [history]
245
+ persistence = "none"
246
+
247
+ [skills]
248
+ include_instructions = false
249
+
250
+ [skills.bundled]
251
+ enabled = false
252
+
253
+ [agents]
254
+ enabled = false
255
+
256
+ [tools.experimental_request_user_input]
257
+ enabled = false
258
+
259
+ [features]
260
+ ${FEATURES_OFF.map((name) => `${name} = false`).join('\n')}
261
+ ${provider ? `\n[model_providers.stand-in]\nname = "stand-in"\nbase_url = ${toml(provider)}\nwire_api = "responses"\n` : ''}`;
262
+ }
263
+
264
+ /** The thread/start parameters: our tool, raw events, nothing kept on disk. */
265
+ export function threadParams({ model, cwd, tool }) {
266
+ return {
267
+ model,
268
+ cwd,
269
+ approvalPolicy: 'never',
270
+ sandbox: 'read-only',
271
+ ephemeral: true,
272
+ experimentalRawEvents: true,
273
+ dynamicTools: [{ type: 'function', name: tool.name, description: tool.description, inputSchema: tool.parameters }],
274
+ };
275
+ }
276
+
277
+ /** The plan's limit as a sentence, if a window of it is used up. */
278
+ export function atLimit(limits) {
279
+ const buckets = limits?.rateLimitsByLimitId ?? (limits?.rateLimits ? { codex: limits.rateLimits } : {});
280
+ for (const [id, bucket] of Object.entries(buckets)) {
281
+ if (bucket?.rateLimitReachedType) return `the ChatGPT plan's ${id} limit is reached (${bucket.rateLimitReachedType})`;
282
+ for (const window of [bucket?.primary, bucket?.secondary]) if (window?.usedPercent >= 100) return `the ChatGPT plan's ${id} ${window.windowDurationMins}-minute window is used up`;
283
+ }
284
+ return null;
285
+ }
286
+
287
+ /* Reading what Codex reports --------------------------------------------- */
288
+
289
+ /** A call's arguments read as strictly as harness/adapters/responses.mjs reads them. */
290
+ function readCall(item, tool) {
291
+ const id = item.call_id;
292
+ if (item.type !== 'function_call' || item.name !== tool.name || item.namespace)
293
+ return { id, error: `There is no tool named "${item.namespace ? `${item.namespace}.` : ''}${item.name}", so nothing was run. The only tool is ${tool.name}, which takes {"command": "..."}.` };
294
+ let input;
295
+ try {
296
+ input = JSON.parse(item.arguments);
297
+ } catch {
298
+ return { id, error: `The arguments of that call were not valid JSON, so nothing was run. They began: ${String(item.arguments).slice(0, 200)}` };
299
+ }
300
+ if (input === null || typeof input !== 'object' || Array.isArray(input))
301
+ return { id, error: 'The arguments of that call were not a JSON object, so nothing was run. The tool takes {"command": "..."}.' };
302
+ if (typeof input.command !== 'string') return { id, error: 'That call had no "command" string, so nothing was run. The tool takes {"command": "..."}.' };
303
+ return { id, command: input.command };
304
+ }
305
+
306
+ /** An item that went in to the model (echoed by Codex), not one it gave back. */
307
+ const isInput = (item) => ['function_call_output', 'custom_tool_call_output', 'additional_tools'].includes(item?.type) || (item?.type === 'message' && item.role !== 'assistant');
308
+
309
+ const CALLS = new Set(['function_call', 'custom_tool_call', 'local_shell_call', 'web_search_call', 'tool_search_call', 'image_generation_call']);
310
+
311
+ /** An item for the log: Codex's own bookkeeping and the encrypted reasoning left out. */
312
+ function forLog(item) {
313
+ const { internal_chat_message_metadata_passthrough, encrypted_content, ...rest } = item;
314
+ return encrypted_content ? { ...rest, encrypted_content: `[${encrypted_content.length} characters]` } : rest;
315
+ }
316
+
317
+ /** A function_call_output's text and pictures. */
318
+ function outputOf(output) {
319
+ if (typeof output === 'string') return { text: output, images: [] };
320
+ const parts = Array.isArray(output) ? output : [];
321
+ return {
322
+ text: parts.filter((part) => part.type === 'input_text').map((part) => part.text).join('\n'),
323
+ images: parts.filter((part) => part.type === 'input_image').map((part) => {
324
+ const [, mime = 'image/png', data = ''] = /^data:([^;]+);base64,(.*)$/s.exec(part.image_url ?? '') ?? [];
325
+ return { mime, data };
326
+ }),
327
+ };
328
+ }
329
+
330
+ /** What Codex's usage counts make of a reply: input includes what the cache held. */
331
+ const usageOf = (counts = {}) => ({
332
+ input: counts.inputTokens ?? 0,
333
+ output: counts.outputTokens ?? 0,
334
+ cached: counts.cachedInputTokens ?? 0,
335
+ reasoning: counts.reasoningOutputTokens ?? 0,
336
+ });
337
+
338
+ /** One request Codex logged, as kept: everything but the conversation, which is summarised. */
339
+ export function requestRecord(url, body) {
340
+ const { input = [], client_metadata, prompt_cache_key, ...settings } = body;
341
+ return {
342
+ url,
343
+ ...settings,
344
+ input: input.map((item) => ({
345
+ type: item.type ?? 'message',
346
+ ...(item.role && { role: item.role }),
347
+ ...(item.type === 'message' && { text: (Array.isArray(item.content) ? item.content.map((part) => part.text ?? `[${part.type}]`).join('') : String(item.content ?? '')).slice(0, 300) }),
348
+ })),
349
+ };
350
+ }
351
+
352
+ /** A Rust byte-string literal's contents (b"..." as Debug prints it), as bytes. */
353
+ function rustBytes(literal) {
354
+ const bytes = [];
355
+ for (let i = 0; i < literal.length; i++) {
356
+ const c = literal[i];
357
+ if (c !== '\\') {
358
+ bytes.push(...Buffer.from(c, 'utf8'));
359
+ continue;
360
+ }
361
+ const next = literal[++i];
362
+ if (next === 'x') {
363
+ bytes.push(parseInt(literal.slice(i + 1, i + 3), 16));
364
+ i += 2;
365
+ } else bytes.push({ n: 10, r: 13, t: 9, 0: 0 }[next] ?? next.charCodeAt(0));
366
+ }
367
+ return Buffer.from(bytes);
368
+ }
369
+
370
+ /**
371
+ * A request in Codex's trace log, or null. Over HTTP (a stand-in, or Codex
372
+ * falling back): "... codex_http_client::transport: POST to <url>: <json>".
373
+ * Over the WebSocket ChatGPT is asked on: the frame the socket library
374
+ * logs sending, "... tungstenite::protocol: Sending frame: Frame { ...
375
+ * payload: b"<json>" }", a `response.create` message. A compressed frame
376
+ * can't be read here: { compressed: true }.
377
+ */
378
+ export function requestLine(line) {
379
+ let at = line.indexOf('codex_http_client::transport');
380
+ if (at >= 0) {
381
+ const match = /POST to (\S+?): (\{.*)$/s.exec(line.slice(at).replace(/\x1b\[[0-9;]*m/g, ''));
382
+ if (!match || !/\/responses$/.test(match[1])) return null;
383
+ try {
384
+ return { url: match[1], body: JSON.parse(match[2]) };
385
+ } catch {
386
+ return null;
387
+ }
388
+ }
389
+ at = line.indexOf('tungstenite::protocol: Sending frame');
390
+ if (at < 0) return null;
391
+ const frame = line.slice(at);
392
+ if (!frame.includes('opcode: Data(Text)')) return null;
393
+ if (/rsv1: true/.test(frame)) return { compressed: true };
394
+ const payload = /payload: b"(.*)" \}\s*$/s.exec(frame)?.[1];
395
+ if (payload == null) return null;
396
+ try {
397
+ const { type, generate, ...body } = JSON.parse(rustBytes(payload).toString('utf8'));
398
+ // A warm-up message (generate: false) asks for nothing.
399
+ if (type !== 'response.create' || generate === false) return null;
400
+ return { url: CHATGPT_SOCKET, body };
401
+ } catch {
402
+ return null;
403
+ }
404
+ }
405
+
406
+ /* One run ------------------------------------------------------------------ */
407
+
408
+ /**
409
+ * One run's state, fed Codex's notifications (`handle`), the requests it
410
+ * logged (`request`) and our tool's calls (`call`). It decides when the run
411
+ * is over, the way loop.mjs does, and calls `end()` once when it is;
412
+ * `say(text)` starts a turn with a user message.
413
+ */
414
+ export function session({ tool, sandbox, limits, say, end, text = null, clock = Date.now }) {
415
+ const startedAt = clock();
416
+ const replies = [];
417
+ const owners = new Map(); // call id → its reply
418
+ const raw = [];
419
+ const waiters = new Set();
420
+ const sent = { requests: 0, first: null, images: 0, unread: 0 };
421
+ let current = null; // the reply being streamed
422
+ let servedModel = null;
423
+ let misses = 0;
424
+ let looks = 0;
425
+ let submitted = false;
426
+ let exit = null;
427
+ let failure = null;
428
+ let commands = Promise.resolve(); // one command at a time
429
+
430
+ const poke = () => {
431
+ for (const waiter of waiters) waiter();
432
+ };
433
+
434
+ const finish = (how) => {
435
+ if (exit || failure) return;
436
+ exit = how;
437
+ poke();
438
+ end();
439
+ };
440
+
441
+ const fail = (error) => {
442
+ if (exit || failure) return;
443
+ failure = error;
444
+ poke();
445
+ end();
446
+ };
447
+
448
+ // The loop's check before it asks again.
449
+ const overBudget = () => {
450
+ if (replies.length >= limits.replies) finish('replies');
451
+ else if (clock() - startedAt >= limits.minutes * 60000) finish('time');
452
+ return Boolean(exit);
453
+ };
454
+
455
+ // Every call of a finished reply has its result: where the loop would ask again.
456
+ const settle = (reply) => {
457
+ if (exit || failure || !reply.stopped || !reply.calls.length) return;
458
+ if (reply.uses.some((use) => !reply.results.has(use))) return;
459
+ if (submitted) finish('submitted');
460
+ else overBudget();
461
+ };
462
+
463
+ /** Waits until `find()` returns something or the run is over (or `ms` pass, if given). */
464
+ function until(find, ms) {
465
+ const found = find();
466
+ if (found || exit || failure) return Promise.resolve(found);
467
+ return new Promise((done) => {
468
+ let timer = null;
469
+ const waiter = () => {
470
+ const value = find();
471
+ if (!value && !exit && !failure) return;
472
+ waiters.delete(waiter);
473
+ clearTimeout(timer);
474
+ done(value);
475
+ };
476
+ if (ms) {
477
+ timer = setTimeout(() => {
478
+ waiters.delete(waiter);
479
+ done(find());
480
+ }, ms);
481
+ }
482
+ waiters.add(waiter);
483
+ });
484
+ }
485
+
486
+ // An item the model gave back, in the reply being streamed (begun by its first item).
487
+ function output(item) {
488
+ if (exit || failure) return;
489
+ if (!current) {
490
+ // Codex asked again after the budget was spent: we were too slow to stop it.
491
+ if (replies.length >= limits.replies) {
492
+ raw.push({ type: 'harness', text: 'stopped a request past the budget' });
493
+ return finish('replies');
494
+ }
495
+ current = { n: replies.length + 1, id: null, items: [], all: [], calls: [], uses: [], results: new Map(), notes: [], counts: null, stopped: false };
496
+ replies.push(current);
497
+ }
498
+ current.items.push(item);
499
+ if (CALLS.has(item.type)) {
500
+ const call = readCall(item, tool);
501
+ current.all.push(call);
502
+ current.uses.push(call.id);
503
+ owners.set(call.id, current);
504
+ poke();
505
+ }
506
+ }
507
+
508
+ // An item that went in: a result Codex made itself, or ours as Codex sent it on.
509
+ function input(item) {
510
+ if (item.type !== 'function_call_output' && item.type !== 'custom_tool_call_output') return;
511
+ const reply = owners.get(item.call_id);
512
+ const { text: said, images } = outputOf(item.output);
513
+ if (!reply) return;
514
+ if (reply.results.has(item.call_id)) {
515
+ sent.images += images.length;
516
+ return;
517
+ }
518
+ reply.results.set(item.call_id, { id: item.call_id, by: 'codex', text: said, images });
519
+ poke();
520
+ settle(reply);
521
+ }
522
+
523
+ // The response is over: one reply.
524
+ function completed({ responseId, usage }) {
525
+ if (exit || failure) return;
526
+ if (!current) {
527
+ if (replies.length >= limits.replies) return finish('replies');
528
+ current = { n: replies.length + 1, id: null, items: [], all: [], calls: [], uses: [], results: new Map(), notes: [], counts: null, stopped: false };
529
+ replies.push(current);
530
+ }
531
+ const reply = current;
532
+ current = null;
533
+ reply.id = responseId ?? null;
534
+ reply.counts = usage ?? {};
535
+ reply.stopped = true;
536
+ reply.at = new Date(clock()).toISOString();
537
+ const refused = reply.items.some((item) => item.type === 'message' && (item.content ?? []).some((part) => part.type === 'refusal'));
538
+ reply.ended = refused ? 'refused' : reply.all.length ? 'calls' : 'complete';
539
+ reply.calls = reply.ended === 'calls' ? reply.all : [];
540
+ reply.budget = budgetLine(reply.n, startedAt, limits, clock());
541
+ raw.push({ type: 'reply', id: reply.id, usage: reply.counts, output: reply.items.map(forLog) });
542
+
543
+ if (refused) return finish('refused');
544
+ if (reply.calls.length) misses = 0;
545
+ else if (++misses >= limits.misses) return finish('no-commands');
546
+ poke();
547
+ settle(reply);
548
+ }
549
+
550
+ // The turn is over: Codex waits for the next user message.
551
+ function turnEnded(turn = {}) {
552
+ raw.push({ type: 'turn', id: turn.id ?? null, status: turn.status, error: turn.error ?? null, durationMs: turn.durationMs ?? null });
553
+ if (exit || failure) return;
554
+ if (turn.status === 'failed') {
555
+ const info = turn.error?.codexErrorInfo;
556
+ if (info === 'cyberPolicy' || info === 'misalignmentPolicyViolation') return finish('refused');
557
+ const why = [turn.error?.message, turn.error?.additionalDetails].filter(Boolean).join(' ') || 'the turn failed';
558
+ const read = codexFailure({ failed: why, errors: [], completed: false });
559
+ const error = new ProviderError(read.message, { fatal: read.fatal || ['unauthorized', 'modelNotFound', 'badRequest'].includes(info) });
560
+ error.limit = read.limit || info === 'usageLimitExceeded' || info === 'rateLimitExceeded';
561
+ return fail(error);
562
+ }
563
+ if (turn.status !== 'completed') return fail(new ProviderError(`Codex ended the turn ${turn.status ?? 'without a status'}`));
564
+ const last = replies.at(-1);
565
+ if (current || !last || last.calls.length) return fail(new ProviderError("Codex ended the turn before the reply's results were back"));
566
+ if (overBudget()) return;
567
+ last.said = noCommand;
568
+ say(last.said);
569
+ }
570
+
571
+ return {
572
+ get exit() {
573
+ return exit;
574
+ },
575
+ get failure() {
576
+ return failure;
577
+ },
578
+ fail,
579
+
580
+ /** One notification from the app-server. */
581
+ handle(message) {
582
+ const params = message.params ?? {};
583
+ switch (message.method) {
584
+ case 'rawResponseItem/completed':
585
+ return isInput(params.item) ? input(params.item) : output(params.item ?? {});
586
+ case 'rawResponse/completed':
587
+ return completed(params);
588
+ case 'turn/completed':
589
+ return turnEnded(params.turn);
590
+ case 'model/rerouted':
591
+ servedModel = params.toModel ?? servedModel;
592
+ (current ?? replies.at(-1))?.notes.push({ role: 'harness', by: 'codex', text: `Codex says the request went to ${params.toModel}, not ${params.fromModel} (${params.reason}).` });
593
+ return raw.push({ type: 'rerouted', ...params });
594
+ case 'thread/compacted':
595
+ (current ?? replies.at(-1))?.notes.push({ role: 'harness', by: 'codex', text: 'Codex compacted the conversation here.' });
596
+ return raw.push({ type: 'compacted' });
597
+ case 'account/rateLimits/updated':
598
+ plan.limits = { rateLimits: params.rateLimits };
599
+ return;
600
+ case 'error':
601
+ case 'warning':
602
+ case 'configWarning':
603
+ case 'deprecationNotice':
604
+ // Retries and anything else Codex said on its own, for the record.
605
+ return raw.push({ type: message.method, ...params });
606
+ default:
607
+ return;
608
+ }
609
+ },
610
+
611
+ /** One request Codex logged sending (`body` null: it was compressed). The first is checked against what we mean to send. */
612
+ request(url, body) {
613
+ sent.requests += 1;
614
+ if (!body) sent.unread += 1;
615
+ if (sent.first || !body) return;
616
+ sent.first = requestRecord(url, body);
617
+ raw.unshift({ type: 'request', n: 1, ...sent.first });
618
+ const names = (body.tools ?? []).map((spec) => (spec.type === 'function' ? spec.name : `${spec.type}${spec.name ? ` ${spec.name}` : ''}`));
619
+ const extra = names.filter((name) => name !== tool.name);
620
+ if (extra.length || !names.includes(tool.name)) return fail(new ProviderError(`Codex offered the model ${extra.length ? `tools besides ours: ${extra.join(', ')}` : 'no tool of ours'}`, { fatal: true }));
621
+ if (body.instructions) return fail(new ProviderError(`Codex sent instructions of its own (${body.instructions.length} characters)`, { fatal: true }));
622
+ const added = (body.input ?? []).filter((item) => !(item.role === 'user' && outputOf(item.content).text === text));
623
+ if (text != null && added.length) return fail(new ProviderError(`Codex sent more than our request: ${added.map((item) => item.role ?? item.type).join(', ')}`, { fatal: true }));
624
+ },
625
+
626
+ /**
627
+ * One call of our tool, as Codex passed it on. Resolves to the result to
628
+ * send back: { text, images, isError }. Answered once its reply has
629
+ * ended, in the reply's order.
630
+ */
631
+ async call({ id }) {
632
+ const reply = await until(() => {
633
+ const owner = owners.get(id);
634
+ return owner?.stopped ? owner : null;
635
+ });
636
+ if (!reply) return { text: 'Not run: the run is over.', images: [], isError: true };
637
+ const index = reply.uses.indexOf(id);
638
+ await until(() => reply.uses.slice(0, index).every((use) => reply.results.has(use)) || null);
639
+
640
+ const job = commands.then(async () => {
641
+ const call = reply.calls.find((c) => c.id === id);
642
+ let result;
643
+ if (submitted) result = { text: 'Not run: the drawing was already submitted.', images: [] };
644
+ else if (exit || failure || !call) result = { text: 'Not run: the run is over.', images: [] };
645
+ else if (call.error) result = { text: `${call.error}\n[${reply.budget}]`, images: [], isError: true };
646
+ else {
647
+ const done = await sandbox.run(call.command);
648
+ looks += done.images.length;
649
+ if (done.submitted) submitted = true;
650
+ result = { text: resultText(done, reply.budget, limits), images: done.images };
651
+ }
652
+ reply.results.set(id, { id, text: result.text, images: result.images });
653
+ poke();
654
+ // May end the run: then Codex is stopped before it has this result.
655
+ settle(reply);
656
+ return result;
657
+ });
658
+ commands = job.catch(() => {});
659
+ try {
660
+ return await job;
661
+ } catch (error) {
662
+ fail(error);
663
+ return { text: `Not run: ${error.message}`, images: [], isError: true };
664
+ }
665
+ },
666
+
667
+ /** Everything draw() in loop.mjs returns, less the drawing, and what the run had. */
668
+ outcome() {
669
+ const usage = { input: 0, output: 0, cached: 0, reasoning: 0, cost: null };
670
+ const transcript = [];
671
+ for (const reply of replies) {
672
+ const counted = usageOf(reply.counts ?? {});
673
+ for (const key of Object.keys(counted)) usage[key] += counted[key];
674
+ transcript.push({
675
+ role: 'model',
676
+ id: reply.id,
677
+ ended: reply.ended ?? 'truncated',
678
+ text: reply.items
679
+ .filter((item) => item.type === 'message')
680
+ .flatMap((item) => item.content ?? [])
681
+ .filter((part) => part.type === 'output_text')
682
+ .map((part) => part.text)
683
+ .join(''),
684
+ calls: reply.calls,
685
+ usage: counted,
686
+ at: reply.at ?? null,
687
+ });
688
+ if (reply.uses.length) transcript.push({ role: 'results', results: reply.uses.map((use) => reply.results.get(use) ?? { id: use, text: 'Not run: the run ended first.', images: [] }) });
689
+ transcript.push(...reply.notes);
690
+ if (reply.said) transcript.push({ role: 'harness', text: reply.said });
691
+ }
692
+ return {
693
+ exit,
694
+ replies: replies.length,
695
+ looks,
696
+ seconds: Math.round((clock() - startedAt) / 1000),
697
+ usage,
698
+ responseIds: replies.map((reply) => reply.id).filter(Boolean),
699
+ servedModel,
700
+ transcript,
701
+ raw,
702
+ sent,
703
+ };
704
+ },
705
+ };
706
+ }
707
+
708
+ /* The app-server ----------------------------------------------------------- */
709
+
710
+ /** Runs `codex <args>` with `env` and returns what it printed, or throws. */
711
+ function codexOutput(args, env, timeoutMs = 60_000) {
712
+ return new Promise((resolve, reject) => {
713
+ const child = spawn(bin(), args, { env, stdio: ['ignore', 'pipe', 'pipe'] });
714
+ let out = '';
715
+ let err = '';
716
+ const timer = setTimeout(() => child.kill('SIGKILL'), timeoutMs);
717
+ child.stdout.on('data', (chunk) => (out += chunk));
718
+ child.stderr.on('data', (chunk) => (err = (err + chunk).slice(-4000)));
719
+ child.on('error', (error) => {
720
+ clearTimeout(timer);
721
+ reject(error);
722
+ });
723
+ child.on('close', (code) => {
724
+ clearTimeout(timer);
725
+ code === 0 ? resolve(out) : reject(new Error(`codex ${args.join(' ')} exited (${code}): ${err.trim().split('\n').filter((line) => !line.startsWith('WARNING')).at(-1) ?? ''}`));
726
+ });
727
+ });
728
+ }
729
+
730
+ /** Lines of a stream, one at a time. */
731
+ function lines(stream, each) {
732
+ let pending = '';
733
+ stream.setEncoding('utf8');
734
+ stream.on('data', (chunk) => {
735
+ pending += chunk;
736
+ let newline;
737
+ while ((newline = pending.indexOf('\n')) >= 0) {
738
+ const line = pending.slice(0, newline);
739
+ pending = pending.slice(newline + 1);
740
+ if (line.trim()) each(line);
741
+ }
742
+ });
743
+ }
744
+
745
+ /**
746
+ * Runs one drawing through Codex. Returns what draw() in loop.mjs returns,
747
+ * plus `route` and `session` (what the run had). Throws ProviderError when
748
+ * the run isn't an answer (`limit` set when the plan's usage limit is why).
749
+ */
750
+ export async function drawWithCodex({ model, effort, text, tool, sandbox, limits, summaries = false, provider = null }) {
751
+ const auth = join(process.env.CODEX_AUTH_HOME || join(homedir(), '.codex'), 'auth.json');
752
+ try {
753
+ if (JSON.parse(await readFile(auth, 'utf8')).auth_mode !== 'chatgpt') throw new Error('not a ChatGPT login');
754
+ } catch (error) {
755
+ throw new ProviderError(`Codex isn't logged in with ChatGPT (${auth}: ${error.message}); run \`codex login\``, { fatal: true });
756
+ }
757
+
758
+ // The plan's usage first: a run started at the limit fails on its first request. (A stand-in doesn't use it.)
759
+ let usageBefore = null;
760
+ try {
761
+ if (!provider) usageBefore = await readLimits();
762
+ plan.limits = usageBefore ?? plan.limits;
763
+ } catch {}
764
+ const limited = provider ? null : atLimit(plan.limits);
765
+ if (limited) {
766
+ const error = new ProviderError(`${limited}\n${describe(plan.limits)}`);
767
+ error.limit = true;
768
+ throw error;
769
+ }
770
+
771
+ const root = await mkdtemp(join(tmpdir(), 'vb-codex-std-'));
772
+ const work = join(root, 'work');
773
+ const home = join(root, 'home');
774
+ await Promise.all([mkdir(work), mkdir(join(root, 'tmp')), mkdir(home)]);
775
+ await symlink(auth, join(home, 'auth.json'));
776
+ const env = { ...codexEnvironment({ root }), NO_COLOR: '1' };
777
+
778
+ let child = null;
779
+ let stopping = false;
780
+ const stop = () => {
781
+ if (stopping || !child) return;
782
+ stopping = true;
783
+ child.kill('SIGTERM');
784
+ setTimeout(() => child.exitCode === null && child.signalCode === null && child.kill('SIGKILL'), 5000).unref();
785
+ };
786
+
787
+ try {
788
+ // The model's catalog entry as ChatGPT gives it to this Codex (no model call), changed.
789
+ await writeFile(join(home, 'config.toml'), 'check_for_update_on_startup = false\n');
790
+ const version = await codexVersion();
791
+ let live;
792
+ try {
793
+ live = JSON.parse(await codexOutput(['debug', 'models'], env)).models?.find((entry) => entry.slug === model);
794
+ } catch (error) {
795
+ throw new ProviderError(`couldn't read Codex's model catalog: ${error.message}`, { fatal: true });
796
+ }
797
+ if (!live) throw new ProviderError(`Codex ${version ?? ''} has no ${model} in its model catalog on this plan; a newer Codex may (CODEX_BIN)`, { fatal: true });
798
+ const catalog = join(home, 'catalog.json');
799
+ await writeFile(catalog, JSON.stringify({ models: [catalogEntry(live)] }, null, 1));
800
+ await writeFile(join(home, 'config.toml'), configFor({ model, effort, catalog, summaries, provider }));
801
+
802
+ let nextId = 1;
803
+ const pending = new Map();
804
+ const send = (message) => child?.stdin.writable && child.stdin.write(JSON.stringify(message) + '\n');
805
+ const rpc = (method, params) =>
806
+ new Promise((resolve, reject) => {
807
+ const id = nextId++;
808
+ const timer = setTimeout(() => {
809
+ pending.delete(id);
810
+ reject(new ProviderError(`Codex didn't answer ${method} within ${RPC_TIMEOUT_MS / 1000} s`));
811
+ }, RPC_TIMEOUT_MS);
812
+ pending.set(id, (message) => {
813
+ clearTimeout(timer);
814
+ message.error ? reject(new ProviderError(`Codex ${method}: ${message.error.message}`, { fatal: /auth|log ?in|model/i.test(message.error.message ?? '') })) : resolve(message.result);
815
+ });
816
+ send({ method, id, params });
817
+ });
818
+
819
+ let threadId = null;
820
+ const say = (said) =>
821
+ rpc('turn/start', { threadId, input: [{ type: 'text', text: said, text_elements: [] }] }).catch((error) => run.fail(error));
822
+ const run = session({ tool, sandbox, limits, say, end: stop, text });
823
+ const watchdog = setTimeout(() => run.fail(new ProviderError(`Codex was still going ${GRACE_MINUTES} minutes past the time budget`)), (limits.minutes + GRACE_MINUTES) * 60000);
824
+
825
+ let stderr = '';
826
+ const closed = new Promise((done) => {
827
+ try {
828
+ child = spawn(bin(), ['app-server'], { cwd: work, env: { ...env, RUST_LOG: LOG_LEVELS }, stdio: ['pipe', 'pipe', 'pipe'] });
829
+ } catch (error) {
830
+ run.fail(new ProviderError(`couldn't start codex: ${error.message}`, { fatal: true }));
831
+ return done({});
832
+ }
833
+ child.stdin.on('error', () => {});
834
+ child.on('error', (error) => run.fail(new ProviderError(`couldn't start codex: ${error.message}`, { fatal: true })));
835
+ child.on('close', (code, signal) => done({ code, signal }));
836
+ lines(child.stderr, (line) => {
837
+ const logged = requestLine(line);
838
+ if (logged) {
839
+ try {
840
+ logged.compressed ? run.request(null, null) : run.request(logged.url, logged.body);
841
+ } catch (error) {
842
+ run.fail(error);
843
+ }
844
+ return;
845
+ }
846
+ // Nothing of the transports' own log is kept.
847
+ if (!line.includes('codex_http_client') && !line.includes('tungstenite')) stderr = (stderr + line.replace(/\x1b\[[0-9;]*m/g, '').replace(/Bearer \S+/g, 'Bearer [hidden]') + '\n').slice(-20_000);
848
+ });
849
+ lines(child.stdout, (line) => {
850
+ let message;
851
+ try {
852
+ message = JSON.parse(line);
853
+ } catch {
854
+ return;
855
+ }
856
+ if (message.id !== undefined && !message.method) {
857
+ pending.get(message.id)?.(message);
858
+ pending.delete(message.id);
859
+ } else if (message.method === 'item/tool/call' && message.id !== undefined) {
860
+ run.call({ id: message.params?.callId }).then((result) =>
861
+ send({
862
+ id: message.id,
863
+ result: {
864
+ contentItems: [
865
+ { type: 'inputText', text: result.text },
866
+ ...(result.images ?? []).map((image) => ({ type: 'inputImage', imageUrl: `data:${image.mime};base64,${image.data}` })),
867
+ ],
868
+ success: !result.isError,
869
+ },
870
+ }),
871
+ );
872
+ } else if (message.id !== undefined && message.method) {
873
+ // Approvals, questions for a person and anything else: there is no one to ask.
874
+ send({ id: message.id, error: { code: -32601, message: `${message.method} is not available in this run` } });
875
+ } else {
876
+ try {
877
+ run.handle(message);
878
+ } catch (error) {
879
+ run.fail(error);
880
+ }
881
+ }
882
+ });
883
+ });
884
+
885
+ try {
886
+ await rpc('initialize', { clientInfo: { name: 'vectorbench_harness', title: 'VectorBench standard harness', version: '1.0.0' }, capabilities: { experimentalApi: true, requestAttestation: false } });
887
+ send({ method: 'initialized', params: {} });
888
+ const started = await rpc('thread/start', threadParams({ model, cwd: work, tool }));
889
+ threadId = started?.thread?.id;
890
+ if (!threadId) throw new ProviderError('Codex started no thread');
891
+ await rpc('turn/start', { threadId, input: [{ type: 'text', text, text_elements: [] }] });
892
+ } catch (error) {
893
+ run.fail(error instanceof ProviderError ? error : new ProviderError(error.message));
894
+ }
895
+ const ended = await closed;
896
+ clearTimeout(watchdog);
897
+
898
+ // Everything the run made, whether or not it is an answer.
899
+ const made = async () => {
900
+ const { sent, ...result } = run.outcome();
901
+ return {
902
+ ...result,
903
+ svg: await sandbox.read('drawing.svg'),
904
+ route: { via: 'codex', style: 'codex', url: sent.first?.url ?? CHATGPT_URL },
905
+ session: {
906
+ codex: version,
907
+ catalog: catalogChanges(live),
908
+ requests: sent.requests,
909
+ ...(sent.unread && { requestsUnread: sent.unread }),
910
+ firstRequest: sent.first,
911
+ imagesSentBack: sent.images,
912
+ planBefore: usageBefore ? describe(usageBefore) : null,
913
+ planAfter: plan.limits ? describe(plan.limits) : null,
914
+ },
915
+ };
916
+ };
917
+
918
+ let failure = run.failure;
919
+ if (!failure && !run.exit) {
920
+ const why = stderr.trim().split('\n').slice(-3).join(' ') || `it exited (${ended.signal ?? ended.code}) before the run was over`;
921
+ failure = new ProviderError(`Codex: ${why}`, { fatal: /authenticat|log ?in|not logged/i.test(why) });
922
+ }
923
+ if (failure) {
924
+ // Not an answer, but what it got to is kept for a look (scripts/harness.mjs saves it beside no log).
925
+ failure.partial = await made().catch(() => null);
926
+ throw failure;
927
+ }
928
+ return await made();
929
+ } finally {
930
+ stop();
931
+ await rm(root, { recursive: true, force: true });
932
+ }
933
+ }