@parcha/agentrun-harness-codex 0.0.0-stage → 0.1.0-beta.30

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,609 @@
1
+ import { providerInputOverhead, ProxyRefusal } from "@parcha/agentrun-kernel/host";
2
+ export const CODEX_RESPONSES_ROUTES = Object.freeze([
3
+ { method: "GET", path: "/", local: 404 },
4
+ { method: "POST", path: "/v1/responses", headers: ["accept"] },
5
+ ]);
6
+ /** The keys a Responses request from the pinned CLI may carry; `client_metadata` is dropped, anything else refused. */
7
+ const BODY_KEYS = new Set(["model", "input", "tools", "tool_choice", "parallel_tool_calls", "reasoning", "store", "stream", "include", "prompt_cache_key", "max_output_tokens", "text"]);
8
+ /** What `text` may say: the output's format (plain text, or the JSON schema a node's output schema becomes) and its
9
+ * verbosity. */
10
+ const TEXT_KEYS = new Set(["format", "verbosity"]);
11
+ const VERBOSITY = new Set(["low", "medium", "high"]);
12
+ const SCHEMA_FORMAT_KEYS = new Set(["type", "name", "schema", "strict"]);
13
+ const DROPPED_KEYS = new Set(["client_metadata"]);
14
+ /** What `include` may ask for: the encrypted reasoning the CLI sends back on its next request (`store` is false). */
15
+ const INCLUDE = new Set(["reasoning.encrypted_content"]);
16
+ /** Provider-hosted tools the CLI adds to every request whatever its config says: dropped, never offered. */
17
+ const DROPPED_TOOLS = new Set(["web_search", "web_search_preview"]);
18
+ /** The web search tool the pinned CLI sends with `web_search = "live"` through the session's provider, recorded
19
+ * (test/fixtures/responses-request-web-search-live.json): its keys and their values, and nothing else. */
20
+ const LIVE_SEARCH = Object.freeze({ type: "web_search", external_web_access: true });
21
+ const isLiveSearch = (tool) => Object.keys(tool).length === Object.keys(LIVE_SEARCH).length && Object.entries(LIVE_SEARCH).every(([key, value]) => tool[key] === value);
22
+ /**
23
+ * OpenAI's price of one web search call by model: "Web search (all models)", $10.00 / 1k calls, with its search content
24
+ * tokens billed at the model's rates in the response's own usage (https://developers.openai.com/api/docs/pricing, Tools).
25
+ * gpt-4o-mini and gpt-4.1-mini bill each call's search content as a fixed block of 8,000 input tokens instead, so they are
26
+ * not listed: their searches, like any model's not listed here (a gateway's own id, say), are an unknown cost, never $0.
27
+ */
28
+ const WEB_SEARCH_USD = [
29
+ [/^(?:gpt-5|o3|o4-mini)(?:[-.][a-z0-9.-]+)?$/, 0.01],
30
+ [/^gpt-4(?:o|\.1)(?:-\d{4}-\d{2}-\d{2})?$/, 0.01],
31
+ ];
32
+ /** The price of one web search call on `model`, or undefined when it is not known. */
33
+ export function webSearchUsd(model) {
34
+ return WEB_SEARCH_USD.find(([pattern]) => pattern.test(model))?.[1];
35
+ }
36
+ /** `price` with each web search a response ran added at its model's per-call price. Unknown (null) when the tokens' price
37
+ * is, when the response did not say how many searches it ran, or when the model's search price is not known; a response
38
+ * that ran none costs what its tokens do. */
39
+ export function withWebSearches(price) {
40
+ return (model, usage) => {
41
+ const tokens = price(model, usage);
42
+ const searches = usage.webSearches;
43
+ if (searches === 0 || tokens === null)
44
+ return tokens;
45
+ const each = webSearchUsd(model);
46
+ return typeof searches === "number" && each !== undefined ? tokens + searches * each : null;
47
+ };
48
+ }
49
+ const isPlain = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
50
+ /** A list of tool definitions with no provider-hosted tool but the live web search when `search` is on, less any not the
51
+ * session's own. */
52
+ function ownTools(tools, allowed, search = false) {
53
+ if (!Array.isArray(tools))
54
+ throw new ProxyRefusal(400, "tools is not a list");
55
+ const out = [];
56
+ for (const tool of tools) {
57
+ if (!isPlain(tool))
58
+ throw new ProxyRefusal(400, "a tool definition is not an object");
59
+ const type = typeof tool.type === "string" ? tool.type : "";
60
+ const name = typeof tool.name === "string" ? tool.name : "";
61
+ if (search && type === "web_search") {
62
+ if (!isLiveSearch(tool))
63
+ throw new ProxyRefusal(403, "a web search tool other than the live one this session offers is not offered to its model");
64
+ out.push(tool);
65
+ continue;
66
+ }
67
+ if (DROPPED_TOOLS.has(type))
68
+ continue;
69
+ if (type === "namespace") {
70
+ // A namespace holds the tools of a built-in family: only the session's own ones stay, and an empty one goes.
71
+ const kept = ownTools(tool.tools, allowed);
72
+ if (kept.length)
73
+ out.push({ ...tool, tools: kept });
74
+ continue;
75
+ }
76
+ if (type !== "function" && type !== "custom")
77
+ throw new ProxyRefusal(403, "a provider-hosted or unknown kind of tool is not offered to this session's model");
78
+ if (allowed.has(name))
79
+ out.push(tool);
80
+ }
81
+ return out;
82
+ }
83
+ /** `tool_choice` as the provider gets it: a mode, a function of the session's own, or the web search when it is on. */
84
+ function toolChoice(choice, allowed, search = false) {
85
+ if (choice === "auto" || choice === "none" || choice === "required")
86
+ return choice;
87
+ if (isPlain(choice) && choice.type === "function" && typeof choice.name === "string" && allowed.has(choice.name))
88
+ return choice;
89
+ if (search && isPlain(choice) && choice.type === "web_search" && Object.keys(choice).length === 1)
90
+ return choice;
91
+ throw new ProxyRefusal(400, "tool_choice names a mode or tool this session does not offer");
92
+ }
93
+ /** `text` as the provider gets it: only a format (`{ type: "text" }`, or `{ type: "json_schema", name, schema, strict? }`)
94
+ * and a verbosity. */
95
+ function textOptions(text) {
96
+ const refuse = () => { throw new ProxyRefusal(400, "text carries something other than a plain-text or JSON-schema format and a verbosity"); };
97
+ if (!isPlain(text) || !Object.keys(text).every((key) => TEXT_KEYS.has(key)))
98
+ refuse();
99
+ const { format, verbosity } = text;
100
+ if (verbosity !== undefined && !(typeof verbosity === "string" && VERBOSITY.has(verbosity)))
101
+ refuse();
102
+ if (format !== undefined) {
103
+ if (!isPlain(format))
104
+ refuse();
105
+ const f = format;
106
+ if (f.type === "text") {
107
+ if (Object.keys(f).length !== 1)
108
+ refuse();
109
+ }
110
+ else if (f.type === "json_schema") {
111
+ if (!Object.keys(f).every((key) => SCHEMA_FORMAT_KEYS.has(key)))
112
+ refuse();
113
+ if (typeof f.name !== "string" || !isPlain(f.schema) || (f.strict !== undefined && typeof f.strict !== "boolean"))
114
+ refuse();
115
+ }
116
+ else
117
+ refuse();
118
+ }
119
+ return text;
120
+ }
121
+ /** A Responses usage object in the proxy's terms, or undefined when it is not one. */
122
+ function usageFrom(usage) {
123
+ if (!isPlain(usage))
124
+ return undefined;
125
+ const count = (value) => (typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : undefined);
126
+ const input = count(usage.input_tokens);
127
+ const output = count(usage.output_tokens);
128
+ if (input === undefined || output === undefined)
129
+ return undefined;
130
+ const details = isPlain(usage.input_tokens_details) ? usage.input_tokens_details : {};
131
+ const cacheRead = count(details.cached_tokens) ?? 0;
132
+ const cacheWrite = count(details.cache_write_tokens) ?? 0;
133
+ return { input: Math.max(0, input - cacheRead - cacheWrite), output, cacheRead, cacheWrite };
134
+ }
135
+ /** The object starting at `text[start]` (a `{`), as JSON text, or undefined when it does not close in `text`. Strings are
136
+ * skipped whole, so a brace inside one is not counted. */
137
+ function objectAt(text, start) {
138
+ let depth = 0;
139
+ for (let i = start; i < text.length; i++) {
140
+ const c = text[i];
141
+ if (c === "\"") {
142
+ for (i++; i < text.length && text[i] !== "\""; i++)
143
+ if (text[i] === "\\")
144
+ i++;
145
+ }
146
+ else if (c === "{")
147
+ depth++;
148
+ else if (c === "}" && --depth === 0)
149
+ return text.slice(start, i + 1);
150
+ }
151
+ return undefined;
152
+ }
153
+ const PAID_END = new Set(["response.completed", "response.incomplete"]);
154
+ /**
155
+ * The end of the stream's last event when its line was cut at the window's start (a line longer than the window): the
156
+ * text after the last line break, past a closing `data: [DONE]`. A line kept from its start (`data:`) is not one: it was
157
+ * read whole, or it was cut short at the stream's end, and is not read. Undefined when there is none.
158
+ */
159
+ function cutEnd(text) {
160
+ const last = text.split("\n").map((line) => line.trim()).filter((line) => line && line !== "data: [DONE]" && !line.startsWith("event:") && !line.startsWith(":")).at(-1);
161
+ return last === undefined || last.startsWith("data:") ? undefined : last;
162
+ }
163
+ /**
164
+ * The value of `key` in the response an answer ends with: a stream's `response.completed` (or `response.incomplete`),
165
+ * each `data:` line parsed on its own, or a whole JSON body's. The proxy keeps only the first and last 64 KiB of a long
166
+ * answer, and the completed event carries the whole response (its tools and encrypted reasoning), so its line can be cut
167
+ * at the window's start: then the last `"<key>":{` in the text (the response's, which a JSON string cannot contain
168
+ * unescaped) is read as one JSON object. The usage is looked for in all the text kept; `tool_usage` only in the cut end
169
+ * of the last event (`cutEnd`), since the events before the terminal one carry a `tool_usage` of their own (a count of
170
+ * 0 as the response starts). No completed event, or no `key` in it, is undefined.
171
+ */
172
+ function endValue(text, key) {
173
+ let found;
174
+ let ended = false;
175
+ for (const line of text.split("\n")) {
176
+ if (!line.startsWith("data:"))
177
+ continue;
178
+ const data = line.slice(5).trim();
179
+ if (!data.startsWith("{"))
180
+ continue;
181
+ let event;
182
+ try {
183
+ event = JSON.parse(data);
184
+ }
185
+ catch {
186
+ continue; // a line the window cut
187
+ }
188
+ if (isPlain(event) && typeof event.type === "string" && PAID_END.has(event.type)) {
189
+ ended = true;
190
+ found = isPlain(event.response) ? event.response[key] : undefined;
191
+ }
192
+ }
193
+ if (ended)
194
+ return found;
195
+ const whole = text.trimStart();
196
+ if (whole.startsWith("{")) {
197
+ try {
198
+ const body = JSON.parse(whole);
199
+ if (isPlain(body) && body.object === "response")
200
+ return body[key];
201
+ }
202
+ catch { }
203
+ }
204
+ const scope = key === "usage" ? text : cutEnd(text);
205
+ if (scope === undefined)
206
+ return undefined;
207
+ const mark = `"${key}":{`;
208
+ const at = scope.lastIndexOf(mark);
209
+ if (at < 0)
210
+ return undefined;
211
+ const json = objectAt(scope, at + mark.length - 1);
212
+ if (json === undefined)
213
+ return undefined;
214
+ try {
215
+ return JSON.parse(json);
216
+ }
217
+ catch {
218
+ return undefined;
219
+ }
220
+ }
221
+ /**
222
+ * Whether the provider stopped the answer on its content filter: the stream's terminal event (or a whole body) is an
223
+ * `incomplete` response whose `incomplete_details.reason` is `content_filter`. Read by parsing each `data:` line on its
224
+ * own, as endValue reads the usage, never by matching text; an answer cut at its output limit (`max_output_tokens`) is not one.
225
+ *
226
+ * The terminal event carries the whole response (its output, encrypted reasoning included), so its line can be longer
227
+ * than the proxy keeps of an answer; then the proxy's start of that line is read. The response's fields come in a fixed
228
+ * order, `id`, `object`, `created_at`, `status`, `background`, `error`, `incomplete_details`, then `instructions`, the
229
+ * tools and the output (OpenAI's; a LiteLLM gateway's, `id`, `created_at`, `incomplete_details`, ..., `output`, keeps it
230
+ * ahead of the output too), so `incomplete_details` is near the line's start. It is read only on a line that is the event's
231
+ * own: one the SSE `event: response.incomplete` names (OpenAI's API), or whose data says `"type":"response.incomplete"`
232
+ * before its `"response":{` (a gateway that sends each event as its data alone: LiteLLM), as the first
233
+ * `"incomplete_details":{` after `"response":{` (one JSON object), whatever the JSON's spacing.
234
+ */
235
+ export function filtered(text, lineStarts = []) {
236
+ let end = terminalResponse(text.split("\n"), false);
237
+ if (end === undefined) {
238
+ const whole = text.trimStart();
239
+ if (whole.startsWith("{")) {
240
+ try {
241
+ const body = JSON.parse(whole);
242
+ if (isPlain(body) && body.object === "response")
243
+ end = body;
244
+ }
245
+ catch { }
246
+ }
247
+ }
248
+ end ??= terminalResponse(lineStarts, true);
249
+ return isPlain(end) && end.status === "incomplete" && isPlain(end.incomplete_details) && end.incomplete_details.reason === "content_filter";
250
+ }
251
+ /** The response of the last terminal event in `lines` (`filtered`), each `data:` line parsed on its own; with `starts`,
252
+ * the lines are kept starts, and one that is a `response.incomplete` event's (by its name, or its data's type ahead of
253
+ * its response) is read from its start. */
254
+ function terminalResponse(lines, starts) {
255
+ let end;
256
+ let named = false;
257
+ for (const line of lines) {
258
+ if (line.startsWith("event:")) {
259
+ named = line.slice(6).trim() === "response.incomplete";
260
+ continue;
261
+ }
262
+ if (!line.startsWith("data:"))
263
+ continue;
264
+ const data = line.slice(5).trim();
265
+ const incomplete = named || ownIncomplete(data);
266
+ named = false;
267
+ if (!data.startsWith("{"))
268
+ continue;
269
+ try {
270
+ const event = JSON.parse(data);
271
+ if (isPlain(event) && typeof event.type === "string" && PAID_END.has(event.type))
272
+ end = event.response;
273
+ }
274
+ catch {
275
+ // A line the window cut (skipped), or a kept start the event's name says is the stop's.
276
+ if (starts && incomplete)
277
+ end = startOfResponse(data) ?? end;
278
+ }
279
+ }
280
+ return end;
281
+ }
282
+ const RESPONSE_KEY = /"response"\s*:\s*\{/;
283
+ const INCOMPLETE_TYPE = /"type"\s*:\s*"response\.incomplete"/;
284
+ const DETAILS_KEY = /"incomplete_details"\s*:\s*\{/;
285
+ /** Whether a kept start's data is a `response.incomplete` event's own: its `type` says so ahead of its `response` (a
286
+ * quote of it in an answer's text is escaped, so it never reads as one). */
287
+ function ownIncomplete(data) {
288
+ const type = data.search(INCOMPLETE_TYPE);
289
+ const response = data.search(RESPONSE_KEY);
290
+ return type >= 0 && (response < 0 || type < response);
291
+ }
292
+ /** The status and `incomplete_details` of the response a `response.incomplete` event's line starts with (`filtered`), or
293
+ * undefined when the line's kept start does not hold them. */
294
+ function startOfResponse(data) {
295
+ const response = data.search(RESPONSE_KEY);
296
+ if (response < 0)
297
+ return undefined;
298
+ const found = DETAILS_KEY.exec(data.slice(response));
299
+ if (!found)
300
+ return undefined;
301
+ const json = objectAt(data, response + found.index + found[0].length - 1);
302
+ if (json === undefined)
303
+ return undefined;
304
+ try {
305
+ return { status: "incomplete", incomplete_details: JSON.parse(json) };
306
+ }
307
+ catch {
308
+ return undefined;
309
+ }
310
+ }
311
+ /** The usage a Responses answer reports at its end (`endValue`), or undefined, an unknown cost, when it reports none. */
312
+ export function usageOf(text) {
313
+ return usageFrom(endValue(text, "usage"));
314
+ }
315
+ /** The web searches a Responses answer ran, as its terminal event reports them (`tool_usage.web_search.num_requests`,
316
+ * what OpenAI bills per call), or undefined when that event's own count cannot be read: an unknown cost, never 0. */
317
+ export function webSearchesOf(text) {
318
+ const used = endValue(text, "tool_usage");
319
+ const search = isPlain(used) ? used.web_search : undefined;
320
+ const count = isPlain(search) ? search.num_requests : undefined;
321
+ return typeof count === "number" && Number.isInteger(count) && count >= 0 ? count : undefined;
322
+ }
323
+ /** The items of `type` in `value`, at any depth (a tool's output holds them). */
324
+ function itemsIn(value, type) {
325
+ if (Array.isArray(value))
326
+ return value.reduce((n, item) => n + itemsIn(item, type), 0);
327
+ if (!isPlain(value))
328
+ return 0;
329
+ return (value.type === type ? 1 : 0) + Object.values(value).reduce((n, item) => n + itemsIn(item, type), 0);
330
+ }
331
+ /**
332
+ * The input tokens the provider bills for `body` that it does not carry (`providerInputOverhead`, with its sources). The
333
+ * Responses API documents no prompt of its own that it adds on these routes (no hosted tool passes the policy but a
334
+ * session's live web search, below), and the framing it puts around each input item and tool definition is a few tokens
335
+ * each, fewer than the bytes of the JSON keys that item already spends in the body. An image is billed by its area, not
336
+ * its bytes: each adds the most it can be billed as. A file input (a PDF, billed by its pages) has no stated bound, so a
337
+ * body with one cannot be measured: this throws, and the request's input is unknown.
338
+ */
339
+ export function responsesServerInputOverhead(body) {
340
+ if (itemsIn(body.input, "input_file") > 0)
341
+ throw new Error("a file input's billed size has no stated bound");
342
+ return providerInputOverhead("openai-responses", { tools: Array.isArray(body.tools) && body.tools.length > 0, images: itemsIn(body.input, "input_image") });
343
+ }
344
+ /** The text of a tool output item: a string, or the text of each of its parts. */
345
+ /** Codex's status header of a tool output: the text it starts with (its first part), never what the script printed after it. */
346
+ function statusText(item) {
347
+ if (typeof item.output === "string")
348
+ return item.output;
349
+ const first = Array.isArray(item.output) ? item.output[0] : undefined;
350
+ return isPlain(first) && typeof first.text === "string" ? first.text : "";
351
+ }
352
+ /** Whether a script of code mode is still running, from the request's input alone: an `exec` whose output said "Script running
353
+ * with cell ID N" (it yielded and went on), and no later `wait` on N whose output says the script ended. */
354
+ function cellRunning(input) {
355
+ const execs = new Set();
356
+ const waits = new Map();
357
+ const cells = new Set();
358
+ for (const item of input) {
359
+ if (!isPlain(item) || typeof item.call_id !== "string")
360
+ continue;
361
+ const running = /^Script running with cell ID (\S+)/.exec(statusText(item));
362
+ if (item.type === "custom_tool_call" && item.name === "exec")
363
+ execs.add(item.call_id);
364
+ else if (item.type === "custom_tool_call_output" && execs.has(item.call_id) && running)
365
+ cells.add(running[1]);
366
+ else if (item.type === "function_call" && item.name === "wait" && typeof item.arguments === "string") {
367
+ try {
368
+ const cell = JSON.parse(item.arguments).cell_id;
369
+ if (cell !== undefined)
370
+ waits.set(item.call_id, String(cell));
371
+ }
372
+ catch { }
373
+ }
374
+ else if (item.type === "function_call_output" && waits.has(item.call_id) && !running)
375
+ cells.delete(waits.get(item.call_id));
376
+ }
377
+ return cells.size > 0;
378
+ }
379
+ /** The code-mode runtime a request may carry: Codex's `exec` (a custom tool) and `wait` (a function), in the `functions`
380
+ * namespace of an `additional_tools` item. Every other tool the item lists is dropped, and an item of any other shape is
381
+ * refused. Other input items pass as they are. */
382
+ const CODE_MODE_TOOLS = new Map([["exec", "custom"], ["wait", "function"]]);
383
+ function codeModeCarrier(item, offerExec) {
384
+ if (!isPlain(item) || item.type !== "additional_tools")
385
+ return item;
386
+ if (!Array.isArray(item.tools))
387
+ throw new ProxyRefusal(400, "an additional_tools item has no tools list");
388
+ const kept = [];
389
+ for (const namespace of item.tools) {
390
+ if (!isPlain(namespace) || namespace.type !== "namespace" || !Array.isArray(namespace.tools))
391
+ throw new ProxyRefusal(400, "an additional_tools item holds something other than a namespace");
392
+ if (namespace.name !== "functions")
393
+ continue;
394
+ const own = namespace.tools.filter((tool) => isPlain(tool) && typeof tool.name === "string" && CODE_MODE_TOOLS.get(tool.name) === tool.type && (offerExec || tool.name !== "exec"));
395
+ kept.push({ ...namespace, tools: own });
396
+ }
397
+ return { ...item, tools: kept };
398
+ }
399
+ /** An event that is not whole by this many characters is not read: the answer is then reported as not watched. */
400
+ const EVENT_CAP = 4 * 1024 * 1024;
401
+ /** Reads an answer's server-sent events as they pass (lines end in LF, CRLF or a bare CR; an event is its `data:` lines joined
402
+ * with LF, ended by a blank line), and tells `announce` of each code-mode `exec` call it holds. One that cannot be read to its
403
+ * end (an event over the cap) is reported as failed. `end` closes the answer. */
404
+ function watchResponse(announce) {
405
+ announce.response();
406
+ let line = "";
407
+ let held = false; // a CR ended the last piece: an LF that starts the next belongs to it
408
+ let data = [];
409
+ let size = 0;
410
+ let broken = false;
411
+ const fail = () => {
412
+ if (broken)
413
+ return;
414
+ broken = true;
415
+ announce.failed();
416
+ };
417
+ const dispatch = () => {
418
+ const text = data.join("\n");
419
+ data = [];
420
+ size = 0;
421
+ if (!text.includes("custom_tool_call"))
422
+ return;
423
+ let event;
424
+ try {
425
+ event = JSON.parse(text);
426
+ }
427
+ catch {
428
+ return;
429
+ }
430
+ const item = isPlain(event) && event.type === "response.output_item.done" && isPlain(event.item) ? event.item : undefined;
431
+ if (item?.type === "custom_tool_call" && item.name === "exec" && typeof item.call_id === "string")
432
+ announce.exec(item.call_id);
433
+ };
434
+ const endLine = () => {
435
+ const done = line;
436
+ line = "";
437
+ if (done === "")
438
+ return dispatch();
439
+ if (done.startsWith("data:")) {
440
+ const value = done.slice(done.startsWith("data: ") ? 6 : 5);
441
+ size += value.length + 1;
442
+ if (size > EVENT_CAP)
443
+ return fail();
444
+ data.push(value);
445
+ }
446
+ };
447
+ return {
448
+ failed: () => fail(),
449
+ end: () => announce.end(),
450
+ chunk(text) {
451
+ if (broken)
452
+ return;
453
+ for (let i = 0; i < text.length; i++) {
454
+ const ch = text[i];
455
+ if (held) {
456
+ held = false;
457
+ if (ch === "\n")
458
+ continue;
459
+ }
460
+ if (ch === "\n")
461
+ endLine();
462
+ else if (ch === "\r") {
463
+ endLine();
464
+ held = true;
465
+ }
466
+ else {
467
+ line += ch;
468
+ if (line.length > EVENT_CAP)
469
+ return fail();
470
+ }
471
+ if (broken)
472
+ return;
473
+ }
474
+ },
475
+ };
476
+ }
477
+ /** The tokens a request keeps for its answer when its output is limited. */
478
+ export const ANSWER_TOKENS_LEAST = 1024;
479
+ /** What a reasoning request at each effort is allowed for its reasoning beside its answer, when its output is limited:
480
+ * OpenAI's reasoning shares `max_output_tokens` and takes no budget, so a limit under its reasoning comes back
481
+ * incomplete with no answer. The figures are pi-ai's thinking budgets by level (xhigh at high's). */
482
+ export const REASONING_TOKENS_ALLOWED = Object.freeze({ minimal: 1024, low: 2048, medium: 8192, high: 16384, xhigh: 16384 });
483
+ /** The output tokens a Responses body asks for at most: its `max_output_tokens` (as `apply` clamped it). */
484
+ export function responsesOutputAsked(body) {
485
+ const asked = body.max_output_tokens;
486
+ return typeof asked === "number" && Number.isSafeInteger(asked) && asked > 0 ? asked : undefined;
487
+ }
488
+ /** The least output a Responses body may be limited to and still answer: 1,024 tokens, plus its reasoning effort's
489
+ * allowance when it reasons. */
490
+ export function responsesOutputLeast(body) {
491
+ const effort = isPlain(body.reasoning) && typeof body.reasoning.effort === "string" ? body.reasoning.effort : undefined;
492
+ return ANSWER_TOKENS_LEAST + (effort === undefined ? 0 : REASONING_TOKENS_ALLOWED[effort] ?? 0);
493
+ }
494
+ /** The reasoning tokens a Responses request may bill that its stream never shows (only a summary of its reasoning
495
+ * streams): its effort's budget; none at effort `none`; and with no effort the body says (the model then reasons at its
496
+ * own default, or not at all), its output limit, `fallback` when the body names none: the conservative side. An
497
+ * estimate, as the efforts' budgets are not limits the provider keeps: a stopped request counts the part of it that
498
+ * did not stream (less `responsesReasoningBytes` of what it sent), never past its hold. */
499
+ export function responsesReasoningHidden(body, fallback) {
500
+ const effort = isPlain(body.reasoning) && typeof body.reasoning.effort === "string" ? body.reasoning.effort : undefined;
501
+ if (effort === "none")
502
+ return 0;
503
+ const budget = effort === undefined ? undefined : REASONING_TOKENS_ALLOWED[effort];
504
+ return budget ?? responsesOutputAsked(body) ?? fallback;
505
+ }
506
+ /** The Responses stream's events whose deltas are reasoning: its summary, and its reasoning text where a model sends it. */
507
+ const REASONING_DELTAS = new Set(["response.reasoning_summary_text.delta", "response.reasoning_text.delta"]);
508
+ /** The bytes of reasoning one Responses stream event carries: a reasoning delta's text, UTF-8; 0 for answer text, a
509
+ * function call's arguments and every other event. */
510
+ export function responsesReasoningBytes(event) {
511
+ const data = event.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
512
+ if (!data.startsWith("{"))
513
+ return 0;
514
+ const parsed = JSON.parse(data);
515
+ return typeof parsed.type === "string" && REASONING_DELTAS.has(parsed.type) && typeof parsed.delta === "string" ? Buffer.byteLength(parsed.delta, "utf8") : 0;
516
+ }
517
+ /** The Responses stream's events whose deltas are content: answer text, reasoning, and a tool call's input. */
518
+ const CONTENT_DELTAS = new Set([
519
+ "response.output_text.delta", "response.reasoning_summary_text.delta", "response.reasoning_text.delta",
520
+ "response.function_call_arguments.delta", "response.custom_tool_call_input.delta",
521
+ ]);
522
+ /** The bytes of content one Responses stream event carries: a content delta's text, UTF-8, never the framing around it
523
+ * (its sequence number, item id, indexes, logprobs, obfuscation); 0 for every other event. */
524
+ export function responsesContentBytes(event) {
525
+ const data = event.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
526
+ if (!data.startsWith("{"))
527
+ return 0;
528
+ const parsed = JSON.parse(data);
529
+ return typeof parsed.type === "string" && CONTENT_DELTAS.has(parsed.type) && typeof parsed.delta === "string" ? Buffer.byteLength(parsed.delta, "utf8") : 0;
530
+ }
531
+ /** A Responses body with its output limited to `max` tokens, reasoning included: never raised, and never longer. */
532
+ export function limitResponsesOutput(body, max) {
533
+ const asked = responsesOutputAsked(body);
534
+ return { ...body, max_output_tokens: asked === undefined ? max : Math.min(asked, max) };
535
+ }
536
+ export function codexPolicy(options) {
537
+ const allowed = new Set(options.tools);
538
+ const maxOutputTokens = options.maxOutputTokens ?? 32_000;
539
+ const search = options.webSearch === "live";
540
+ return {
541
+ id: "codex",
542
+ routes: CODEX_RESPONSES_ROUTES,
543
+ keyOf(headers) {
544
+ const auth = String(headers.authorization ?? "");
545
+ return auth.startsWith("Bearer ") ? auth.slice(7) : "";
546
+ },
547
+ authHeaders: (credential) => ({ authorization: `Bearer ${credential}` }),
548
+ apply(body) {
549
+ if (!isPlain(body))
550
+ throw new ProxyRefusal(400, "the body is not a JSON object");
551
+ const out = {};
552
+ for (const [key, value] of Object.entries(body)) {
553
+ if (DROPPED_KEYS.has(key))
554
+ continue;
555
+ if (!BODY_KEYS.has(key))
556
+ throw new ProxyRefusal(400, "the body has a field the Codex policy does not allow");
557
+ out[key] = value;
558
+ }
559
+ if (out.include !== undefined && (!Array.isArray(out.include) || !out.include.every((item) => typeof item === "string" && INCLUDE.has(item)))) {
560
+ throw new ProxyRefusal(400, "include asks for an item the Codex policy does not allow");
561
+ }
562
+ if (out.stream !== undefined && typeof out.stream !== "boolean")
563
+ throw new ProxyRefusal(400, "stream is not a boolean");
564
+ if (out.reasoning !== undefined && !isPlain(out.reasoning))
565
+ throw new ProxyRefusal(400, "reasoning is not an object");
566
+ if (out.text !== undefined)
567
+ out.text = textOptions(out.text);
568
+ if (out.tools !== undefined)
569
+ out.tools = ownTools(out.tools, allowed, search);
570
+ if (out.tool_choice !== undefined)
571
+ out.tool_choice = toolChoice(out.tool_choice, allowed, search);
572
+ if (Array.isArray(out.input) && out.input.some((item) => isPlain(item) && item.type === "additional_tools")) {
573
+ // While a script that yielded still runs, the model is offered `wait` and not `exec`: one script is live at a time.
574
+ const offerExec = !cellRunning(out.input);
575
+ out.input = out.input.map((item) => codeModeCarrier(item, offerExec));
576
+ // One `exec` is open at a time (the session's barrier for a code-mode call rests on it): a code-mode request that allows
577
+ // parallel calls is refused, and one that says nothing is sent with them off. A classic request is as the CLI sent it.
578
+ if (out.parallel_tool_calls !== undefined && typeof out.parallel_tool_calls !== "boolean")
579
+ throw new ProxyRefusal(400, "parallel_tool_calls is not a boolean");
580
+ if (out.parallel_tool_calls === true)
581
+ throw new ProxyRefusal(400, "parallel tool calls are not allowed in code mode: the model writes one exec at a time");
582
+ out.parallel_tool_calls = false;
583
+ }
584
+ const asked = typeof out.max_output_tokens === "number" && out.max_output_tokens > 0 ? out.max_output_tokens : maxOutputTokens;
585
+ return { ...out, model: options.model, store: false, max_output_tokens: Math.min(asked, maxOutputTokens) };
586
+ },
587
+ usageOf: search ? (text) => {
588
+ const usage = usageOf(text);
589
+ return usage && { ...usage, webSearches: webSearchesOf(text) ?? null };
590
+ } : usageOf,
591
+ filtered,
592
+ watch: options.announce ? () => watchResponse(options.announce) : undefined,
593
+ unwatched: options.announce ? () => options.announce.failed() : undefined,
594
+ modelOf: (body) => (typeof body.model === "string" ? body.model : undefined),
595
+ // The content a web search feeds the model is billed as input, and neither it nor the searches one response runs has a
596
+ // stated bound: a body that offers web search has no input bound (undefined), so its input is unmeasured.
597
+ outputAsked: responsesOutputAsked,
598
+ outputLeast: responsesOutputLeast,
599
+ reasoningHidden: (body) => responsesReasoningHidden(body, maxOutputTokens),
600
+ reasoningBytesOf: responsesReasoningBytes,
601
+ contentBytesOf: responsesContentBytes,
602
+ limitOutput: limitResponsesOutput,
603
+ serverInputOverhead: search ? (body) => {
604
+ if (Array.isArray(body.tools) && body.tools.some((tool) => isPlain(tool) && tool.type === "web_search"))
605
+ return undefined;
606
+ return responsesServerInputOverhead(body);
607
+ } : responsesServerInputOverhead,
608
+ };
609
+ }