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

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,478 @@
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
+ /** The usage a Responses answer reports at its end (`endValue`), or undefined, an unknown cost, when it reports none. */
222
+ export function usageOf(text) {
223
+ return usageFrom(endValue(text, "usage"));
224
+ }
225
+ /** The web searches a Responses answer ran, as its terminal event reports them (`tool_usage.web_search.num_requests`,
226
+ * what OpenAI bills per call), or undefined when that event's own count cannot be read: an unknown cost, never 0. */
227
+ export function webSearchesOf(text) {
228
+ const used = endValue(text, "tool_usage");
229
+ const search = isPlain(used) ? used.web_search : undefined;
230
+ const count = isPlain(search) ? search.num_requests : undefined;
231
+ return typeof count === "number" && Number.isInteger(count) && count >= 0 ? count : undefined;
232
+ }
233
+ /** The items of `type` in `value`, at any depth (a tool's output holds them). */
234
+ function itemsIn(value, type) {
235
+ if (Array.isArray(value))
236
+ return value.reduce((n, item) => n + itemsIn(item, type), 0);
237
+ if (!isPlain(value))
238
+ return 0;
239
+ return (value.type === type ? 1 : 0) + Object.values(value).reduce((n, item) => n + itemsIn(item, type), 0);
240
+ }
241
+ /**
242
+ * The input tokens the provider bills for `body` that it does not carry (`providerInputOverhead`, with its sources). The
243
+ * Responses API documents no prompt of its own that it adds on these routes (no hosted tool passes the policy but a
244
+ * session's live web search, below), and the framing it puts around each input item and tool definition is a few tokens
245
+ * each, fewer than the bytes of the JSON keys that item already spends in the body. An image is billed by its area, not
246
+ * 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
247
+ * body with one cannot be measured: this throws, and the request's input is unknown.
248
+ */
249
+ export function responsesServerInputOverhead(body) {
250
+ if (itemsIn(body.input, "input_file") > 0)
251
+ throw new Error("a file input's billed size has no stated bound");
252
+ return providerInputOverhead("openai-responses", { tools: Array.isArray(body.tools) && body.tools.length > 0, images: itemsIn(body.input, "input_image") });
253
+ }
254
+ /** The text of a tool output item: a string, or the text of each of its parts. */
255
+ /** Codex's status header of a tool output: the text it starts with (its first part), never what the script printed after it. */
256
+ function statusText(item) {
257
+ if (typeof item.output === "string")
258
+ return item.output;
259
+ const first = Array.isArray(item.output) ? item.output[0] : undefined;
260
+ return isPlain(first) && typeof first.text === "string" ? first.text : "";
261
+ }
262
+ /** Whether a script of code mode is still running, from the request's input alone: an `exec` whose output said "Script running
263
+ * with cell ID N" (it yielded and went on), and no later `wait` on N whose output says the script ended. */
264
+ function cellRunning(input) {
265
+ const execs = new Set();
266
+ const waits = new Map();
267
+ const cells = new Set();
268
+ for (const item of input) {
269
+ if (!isPlain(item) || typeof item.call_id !== "string")
270
+ continue;
271
+ const running = /^Script running with cell ID (\S+)/.exec(statusText(item));
272
+ if (item.type === "custom_tool_call" && item.name === "exec")
273
+ execs.add(item.call_id);
274
+ else if (item.type === "custom_tool_call_output" && execs.has(item.call_id) && running)
275
+ cells.add(running[1]);
276
+ else if (item.type === "function_call" && item.name === "wait" && typeof item.arguments === "string") {
277
+ try {
278
+ const cell = JSON.parse(item.arguments).cell_id;
279
+ if (cell !== undefined)
280
+ waits.set(item.call_id, String(cell));
281
+ }
282
+ catch { }
283
+ }
284
+ else if (item.type === "function_call_output" && waits.has(item.call_id) && !running)
285
+ cells.delete(waits.get(item.call_id));
286
+ }
287
+ return cells.size > 0;
288
+ }
289
+ /** The code-mode runtime a request may carry: Codex's `exec` (a custom tool) and `wait` (a function), in the `functions`
290
+ * namespace of an `additional_tools` item. Every other tool the item lists is dropped, and an item of any other shape is
291
+ * refused. Other input items pass as they are. */
292
+ const CODE_MODE_TOOLS = new Map([["exec", "custom"], ["wait", "function"]]);
293
+ function codeModeCarrier(item, offerExec) {
294
+ if (!isPlain(item) || item.type !== "additional_tools")
295
+ return item;
296
+ if (!Array.isArray(item.tools))
297
+ throw new ProxyRefusal(400, "an additional_tools item has no tools list");
298
+ const kept = [];
299
+ for (const namespace of item.tools) {
300
+ if (!isPlain(namespace) || namespace.type !== "namespace" || !Array.isArray(namespace.tools))
301
+ throw new ProxyRefusal(400, "an additional_tools item holds something other than a namespace");
302
+ if (namespace.name !== "functions")
303
+ continue;
304
+ const own = namespace.tools.filter((tool) => isPlain(tool) && typeof tool.name === "string" && CODE_MODE_TOOLS.get(tool.name) === tool.type && (offerExec || tool.name !== "exec"));
305
+ kept.push({ ...namespace, tools: own });
306
+ }
307
+ return { ...item, tools: kept };
308
+ }
309
+ /** An event that is not whole by this many characters is not read: the answer is then reported as not watched. */
310
+ const EVENT_CAP = 4 * 1024 * 1024;
311
+ /** 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
312
+ * 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
313
+ * end (an event over the cap) is reported as failed. `end` closes the answer. */
314
+ function watchResponse(announce) {
315
+ announce.response();
316
+ let line = "";
317
+ let held = false; // a CR ended the last piece: an LF that starts the next belongs to it
318
+ let data = [];
319
+ let size = 0;
320
+ let broken = false;
321
+ const fail = () => {
322
+ if (broken)
323
+ return;
324
+ broken = true;
325
+ announce.failed();
326
+ };
327
+ const dispatch = () => {
328
+ const text = data.join("\n");
329
+ data = [];
330
+ size = 0;
331
+ if (!text.includes("custom_tool_call"))
332
+ return;
333
+ let event;
334
+ try {
335
+ event = JSON.parse(text);
336
+ }
337
+ catch {
338
+ return;
339
+ }
340
+ const item = isPlain(event) && event.type === "response.output_item.done" && isPlain(event.item) ? event.item : undefined;
341
+ if (item?.type === "custom_tool_call" && item.name === "exec" && typeof item.call_id === "string")
342
+ announce.exec(item.call_id);
343
+ };
344
+ const endLine = () => {
345
+ const done = line;
346
+ line = "";
347
+ if (done === "")
348
+ return dispatch();
349
+ if (done.startsWith("data:")) {
350
+ const value = done.slice(done.startsWith("data: ") ? 6 : 5);
351
+ size += value.length + 1;
352
+ if (size > EVENT_CAP)
353
+ return fail();
354
+ data.push(value);
355
+ }
356
+ };
357
+ return {
358
+ failed: () => fail(),
359
+ end: () => announce.end(),
360
+ chunk(text) {
361
+ if (broken)
362
+ return;
363
+ for (let i = 0; i < text.length; i++) {
364
+ const ch = text[i];
365
+ if (held) {
366
+ held = false;
367
+ if (ch === "\n")
368
+ continue;
369
+ }
370
+ if (ch === "\n")
371
+ endLine();
372
+ else if (ch === "\r") {
373
+ endLine();
374
+ held = true;
375
+ }
376
+ else {
377
+ line += ch;
378
+ if (line.length > EVENT_CAP)
379
+ return fail();
380
+ }
381
+ if (broken)
382
+ return;
383
+ }
384
+ },
385
+ };
386
+ }
387
+ /** The tokens a request keeps for its answer when its output is limited. */
388
+ export const ANSWER_TOKENS_LEAST = 1024;
389
+ /** What a reasoning request at each effort is allowed for its reasoning beside its answer, when its output is limited:
390
+ * OpenAI's reasoning shares `max_output_tokens` and takes no budget, so a limit under its reasoning comes back
391
+ * incomplete with no answer. The figures are pi-ai's thinking budgets by level (xhigh at high's). */
392
+ export const REASONING_TOKENS_ALLOWED = Object.freeze({ minimal: 1024, low: 2048, medium: 8192, high: 16384, xhigh: 16384 });
393
+ /** The output tokens a Responses body asks for at most: its `max_output_tokens` (as `apply` clamped it). */
394
+ export function responsesOutputAsked(body) {
395
+ const asked = body.max_output_tokens;
396
+ return typeof asked === "number" && Number.isSafeInteger(asked) && asked > 0 ? asked : undefined;
397
+ }
398
+ /** The least output a Responses body may be limited to and still answer: 1,024 tokens, plus its reasoning effort's
399
+ * allowance when it reasons. */
400
+ export function responsesOutputLeast(body) {
401
+ const effort = isPlain(body.reasoning) && typeof body.reasoning.effort === "string" ? body.reasoning.effort : undefined;
402
+ return ANSWER_TOKENS_LEAST + (effort === undefined ? 0 : REASONING_TOKENS_ALLOWED[effort] ?? 0);
403
+ }
404
+ /** A Responses body with its output limited to `max` tokens, reasoning included: never raised, and never longer. */
405
+ export function limitResponsesOutput(body, max) {
406
+ const asked = responsesOutputAsked(body);
407
+ return { ...body, max_output_tokens: asked === undefined ? max : Math.min(asked, max) };
408
+ }
409
+ export function codexPolicy(options) {
410
+ const allowed = new Set(options.tools);
411
+ const maxOutputTokens = options.maxOutputTokens ?? 32_000;
412
+ const search = options.webSearch === "live";
413
+ return {
414
+ id: "codex",
415
+ routes: CODEX_RESPONSES_ROUTES,
416
+ keyOf(headers) {
417
+ const auth = String(headers.authorization ?? "");
418
+ return auth.startsWith("Bearer ") ? auth.slice(7) : "";
419
+ },
420
+ authHeaders: (credential) => ({ authorization: `Bearer ${credential}` }),
421
+ apply(body) {
422
+ if (!isPlain(body))
423
+ throw new ProxyRefusal(400, "the body is not a JSON object");
424
+ const out = {};
425
+ for (const [key, value] of Object.entries(body)) {
426
+ if (DROPPED_KEYS.has(key))
427
+ continue;
428
+ if (!BODY_KEYS.has(key))
429
+ throw new ProxyRefusal(400, "the body has a field the Codex policy does not allow");
430
+ out[key] = value;
431
+ }
432
+ if (out.include !== undefined && (!Array.isArray(out.include) || !out.include.every((item) => typeof item === "string" && INCLUDE.has(item)))) {
433
+ throw new ProxyRefusal(400, "include asks for an item the Codex policy does not allow");
434
+ }
435
+ if (out.stream !== undefined && typeof out.stream !== "boolean")
436
+ throw new ProxyRefusal(400, "stream is not a boolean");
437
+ if (out.reasoning !== undefined && !isPlain(out.reasoning))
438
+ throw new ProxyRefusal(400, "reasoning is not an object");
439
+ if (out.text !== undefined)
440
+ out.text = textOptions(out.text);
441
+ if (out.tools !== undefined)
442
+ out.tools = ownTools(out.tools, allowed, search);
443
+ if (out.tool_choice !== undefined)
444
+ out.tool_choice = toolChoice(out.tool_choice, allowed, search);
445
+ if (Array.isArray(out.input) && out.input.some((item) => isPlain(item) && item.type === "additional_tools")) {
446
+ // While a script that yielded still runs, the model is offered `wait` and not `exec`: one script is live at a time.
447
+ const offerExec = !cellRunning(out.input);
448
+ out.input = out.input.map((item) => codeModeCarrier(item, offerExec));
449
+ // 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
450
+ // parallel calls is refused, and one that says nothing is sent with them off. A classic request is as the CLI sent it.
451
+ if (out.parallel_tool_calls !== undefined && typeof out.parallel_tool_calls !== "boolean")
452
+ throw new ProxyRefusal(400, "parallel_tool_calls is not a boolean");
453
+ if (out.parallel_tool_calls === true)
454
+ throw new ProxyRefusal(400, "parallel tool calls are not allowed in code mode: the model writes one exec at a time");
455
+ out.parallel_tool_calls = false;
456
+ }
457
+ const asked = typeof out.max_output_tokens === "number" && out.max_output_tokens > 0 ? out.max_output_tokens : maxOutputTokens;
458
+ return { ...out, model: options.model, store: false, max_output_tokens: Math.min(asked, maxOutputTokens) };
459
+ },
460
+ usageOf: search ? (text) => {
461
+ const usage = usageOf(text);
462
+ return usage && { ...usage, webSearches: webSearchesOf(text) ?? null };
463
+ } : usageOf,
464
+ watch: options.announce ? () => watchResponse(options.announce) : undefined,
465
+ unwatched: options.announce ? () => options.announce.failed() : undefined,
466
+ modelOf: (body) => (typeof body.model === "string" ? body.model : undefined),
467
+ // The content a web search feeds the model is billed as input, and neither it nor the searches one response runs has a
468
+ // stated bound: a body that offers web search has no input bound (undefined), so its input is unmeasured.
469
+ outputAsked: responsesOutputAsked,
470
+ outputLeast: responsesOutputLeast,
471
+ limitOutput: limitResponsesOutput,
472
+ serverInputOverhead: search ? (body) => {
473
+ if (Array.isArray(body.tools) && body.tools.some((tool) => isPlain(tool) && tool.type === "web_search"))
474
+ return undefined;
475
+ return responsesServerInputOverhead(body);
476
+ } : responsesServerInputOverhead,
477
+ };
478
+ }
@@ -0,0 +1,145 @@
1
+ import type { TomlValue } from "../config.js";
2
+ import type { DriveContext } from "./kernel.js";
3
+ export { boundResult, BuiltinCalls, failureText, Mutex, NativeJournal, openTurn, placeSubmissions, recoveryNote, recoverySystemNote, recoveryUserTurn, restartEvent, toolBridge, toolKey, transcriptOf, } from "@parcha/agentrun-kernel/process";
4
+ export type { BuiltinStart, ToolResult, TranscriptEntry } from "@parcha/agentrun-kernel/process";
5
+ /** A child's line protocol: one JSON value per line out, lines in. */
6
+ export interface LineChannel {
7
+ send(line: unknown): boolean;
8
+ end(): void;
9
+ lines(): AsyncIterable<string>;
10
+ readonly exited: Promise<{
11
+ code: number | null;
12
+ signal: string | null;
13
+ }>;
14
+ stderrTail(): string;
15
+ }
16
+ export type KillSignal = "SIGTERM" | "SIGKILL" | "SIGINT";
17
+ export interface SessionProcess extends LineChannel {
18
+ alive(): boolean;
19
+ kill(signal?: KillSignal): void;
20
+ }
21
+ /** A session machine's private directories. */
22
+ export type CacheDir = "home" | "config" | "codex-home" | "tmp" | "cache";
23
+ export interface CacheFile {
24
+ path: string;
25
+ bytes: Uint8Array;
26
+ mode?: number;
27
+ }
28
+ export interface MachineSpawn {
29
+ command: string;
30
+ args?: string[];
31
+ /** The child's environment beyond the machine's allowlist (PATH, LANG, TZ). Nothing else is inherited. */
32
+ env?: Record<string, string>;
33
+ cwd?: string;
34
+ signal?: AbortSignal;
35
+ isolatedCommands?: boolean;
36
+ }
37
+ /** A line-complete tail of a file in one of the machine's directories. */
38
+ export interface MachineTail {
39
+ readonly offset: number;
40
+ read(): string[];
41
+ sync(): Promise<void>;
42
+ close(): void;
43
+ }
44
+ /** Where a session's harness runs: here, a local machine with private directories and a loopback model proxy. */
45
+ export interface SessionMachine {
46
+ readonly sessionId: string;
47
+ readonly root: string;
48
+ readonly dirs: Readonly<Record<CacheDir, string>>;
49
+ readonly signal: AbortSignal;
50
+ /** The model proxy's base URL (loopback), and the per-session key it admits. */
51
+ readonly modelUrl: string;
52
+ readonly modelKey: string;
53
+ /** What the model must hear about this machine (none locally), and its acknowledgement key. */
54
+ readonly notes: readonly string[];
55
+ readonly notesKey?: string;
56
+ spawn(options: MachineSpawn): Promise<SessionProcess>;
57
+ readonly files: {
58
+ upload(dir: CacheDir, files: readonly CacheFile[]): Promise<void>;
59
+ wipe(): Promise<void>;
60
+ };
61
+ tail(dir: CacheDir, path: string, options?: {
62
+ offset?: number;
63
+ }): Promise<MachineTail>;
64
+ /** Per acquire: a machine re-attached for a later drive announces nothing until its proxy has seen an answer.
65
+ * The code-mode `exec` call the model proxy's latest answer carried, read before Codex could act on it (none when that
66
+ * answer held none): what a nested call of a script is tied to, even before the `exec`'s line is in the rollout. */
67
+ announcedExec?(): string | undefined;
68
+ /** Told each line the rollout's tail reads, as it reads it: the harness's view of code mode follows the log from here. */
69
+ onRolloutLine?(listener: (line: string) => void): void;
70
+ /** Given Codex's `config.toml` settings before the harness writes them, to set what the session's own options decide
71
+ * and the harness does not (its web search, a key reserved from callers). */
72
+ configure?(config: Record<string, TomlValue>): void;
73
+ fsync(): Promise<void>;
74
+ close(): Promise<void>;
75
+ }
76
+ /** What a harness's drive asks its machine factory for: the drive, the model route its proxy serves, and its deadline. */
77
+ export interface AcquireMachineRequest {
78
+ ctx: DriveContext;
79
+ model?: GatewayHandler;
80
+ deadline?: number;
81
+ }
82
+ export type AcquireMachine = (request: AcquireMachineRequest) => Promise<SessionMachine>;
83
+ /** Mark a machine as made by this package's factory. */
84
+ export declare function brandMachine<T extends object>(machine: T): T;
85
+ /** Whether a machine was made by this package's factory: the harness refuses any other. */
86
+ export declare const isBrandedMachine: (machine: unknown) => machine is SessionMachine;
87
+ /** One route the model proxy forwards. */
88
+ export interface GatewayRoute {
89
+ method: string;
90
+ path: string;
91
+ /** Request headers passed on to the provider. */
92
+ headers?: readonly string[];
93
+ }
94
+ /** Codex's one route: the Responses API. */
95
+ export declare const CODEX_ROUTES: readonly GatewayRoute[];
96
+ /** The session's dollar ledger, kept by the harness in its records. */
97
+ export interface GatewayLedger {
98
+ spent(): {
99
+ turnUsd: number;
100
+ sessionUsd: number;
101
+ };
102
+ add(usd: number, info: {
103
+ method: string;
104
+ path: string;
105
+ model?: string;
106
+ estimated?: boolean;
107
+ }): void;
108
+ }
109
+ /** What the harness says about its model route; the machine's proxy serves it (machine.ts). */
110
+ export interface GatewayHandlerOptions {
111
+ routes: readonly GatewayRoute[];
112
+ models: {
113
+ model: string;
114
+ };
115
+ budget?: {
116
+ turnUsd: number;
117
+ sessionUsd: number;
118
+ };
119
+ ledger?: GatewayLedger;
120
+ network?: string;
121
+ credential: () => Promise<string | undefined> | string | undefined;
122
+ target: string;
123
+ track?: unknown;
124
+ onCap?: (cap: "turnUsd" | "sessionUsd" | "concurrency") => void;
125
+ log?: (message: string, fields?: Record<string, unknown>) => void;
126
+ }
127
+ export interface GatewayHandler {
128
+ readonly kind: "agentrun-model-route";
129
+ readonly options: GatewayHandlerOptions;
130
+ }
131
+ export declare const gatewayHandler: (options: GatewayHandlerOptions) => GatewayHandler;
132
+ /** The provider credential when the harness is given none: the adapter always gives one, so this refuses. */
133
+ export declare const gatewayCredential: () => Promise<string>;
134
+ /** The provider's base URL when the harness is given none: the adapter always gives one. */
135
+ export declare const gatewayUrl: () => string;
136
+ /** Model steps: a sandbox's tracing of each request. A local session reports usage through its proxy instead. */
137
+ export declare class ModelSteps {
138
+ constructor(_ctx: DriveContext, _options?: {
139
+ log?: (message: string, fields?: Record<string, unknown>) => void;
140
+ });
141
+ readonly request: () => void;
142
+ settleAbandoned(): Promise<void>;
143
+ close(): Promise<void>;
144
+ }
145
+ export declare function settleAbandonedModelSteps(_ctx: DriveContext): Promise<void>;
@@ -0,0 +1,28 @@
1
+ export { boundResult, BuiltinCalls, failureText, Mutex, NativeJournal, openTurn, placeSubmissions, recoveryNote, recoverySystemNote, recoveryUserTurn, restartEvent, toolBridge, toolKey, transcriptOf, } from "@parcha/agentrun-kernel/process";
2
+ const BRAND = Symbol.for("agentrun.codex.session-machine");
3
+ /** Mark a machine as made by this package's factory. */
4
+ export function brandMachine(machine) {
5
+ Object.defineProperty(machine, BRAND, { value: true });
6
+ return machine;
7
+ }
8
+ /** Whether a machine was made by this package's factory: the harness refuses any other. */
9
+ export const isBrandedMachine = (machine) => typeof machine === "object" && machine !== null && machine[BRAND] === true;
10
+ /** Codex's one route: the Responses API. */
11
+ export const CODEX_ROUTES = Object.freeze([{ method: "POST", path: "/v1/responses", headers: ["originator", "x-client-request-id"] }]);
12
+ export const gatewayHandler = (options) => ({ kind: "agentrun-model-route", options });
13
+ /** The provider credential when the harness is given none: the adapter always gives one, so this refuses. */
14
+ export const gatewayCredential = async () => {
15
+ throw new Error("agentrun-harness-codex: no provider credential was given to the Codex harness");
16
+ };
17
+ /** The provider's base URL when the harness is given none: the adapter always gives one. */
18
+ export const gatewayUrl = () => {
19
+ throw new Error("agentrun-harness-codex: no provider URL was given to the Codex harness");
20
+ };
21
+ /** Model steps: a sandbox's tracing of each request. A local session reports usage through its proxy instead. */
22
+ export class ModelSteps {
23
+ constructor(_ctx, _options = {}) { }
24
+ request = () => { };
25
+ async settleAbandoned() { }
26
+ async close() { }
27
+ }
28
+ export async function settleAbandonedModelSteps(_ctx) { }