@parcha/agentrun-harness-codex 0.1.0-beta.36 → 0.1.0-beta.38

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.
@@ -1,4 +1,4 @@
1
- import { providerInputOverhead, ProxyRefusal, responsesImagesIn } from "@parcha/agentrun-kernel/host";
1
+ import { lastObjectOf, NATIVE_SEARCH_USD, OPENAI_INPUT_COUNTER, ProxyRefusal, responsesInputOverhead } from "@parcha/agentrun-kernel/host";
2
2
  export const CODEX_RESPONSES_ROUTES = Object.freeze([
3
3
  { method: "GET", path: "/", local: 404 },
4
4
  { method: "POST", path: "/v1/responses", headers: ["accept"] },
@@ -26,12 +26,13 @@ const isLiveSearch = (tool) => Object.keys(tool).length === Object.keys(LIVE_SEA
26
26
  /**
27
27
  * OpenAI's price of one web search call by model: "Web search (all models)", $10.00 / 1k calls, with its search content
28
28
  * tokens billed at the model's rates in the response's own usage (https://developers.openai.com/api/docs/pricing, Tools).
29
+ * The GPT-6 family (gpt-6-luna, gpt-6.1-sol, gpt-6.1-terra, ...) is among "all models", as GPT-5 is.
29
30
  * 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
30
31
  * not listed: their searches, like any model's not listed here (a gateway's own id, say), are an unknown cost, never $0.
31
32
  */
32
33
  const WEB_SEARCH_USD = [
33
- [/^(?:gpt-5|o3|o4-mini)(?:[-.][a-z0-9.-]+)?$/, 0.01],
34
- [/^gpt-4(?:o|\.1)(?:-\d{4}-\d{2}-\d{2})?$/, 0.01],
34
+ [/^(?:gpt-6|gpt-5|o3|o4-mini)(?:[-.][a-z0-9.-]+)?$/, NATIVE_SEARCH_USD],
35
+ [/^gpt-4(?:o|\.1)(?:-\d{4}-\d{2}-\d{2})?$/, NATIVE_SEARCH_USD],
35
36
  ];
36
37
  /** The price of one web search call on `model`, or undefined when it is not known. */
37
38
  export function webSearchUsd(model) {
@@ -52,8 +53,8 @@ export function withWebSearches(price) {
52
53
  }
53
54
  const isPlain = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
54
55
  /** A list of tool definitions with no provider-hosted tool but the live web search when `search` is on, less any not the
55
- * session's own: `allowed` by name, `mcp` (`mcp__<server>__<tool>`) in a server's namespace. */
56
- function ownTools(tools, allowed, search = false, mcp = new Set()) {
56
+ * session's own (`allowed`, by name). */
57
+ function ownTools(tools, allowed, search = false) {
57
58
  if (!Array.isArray(tools))
58
59
  throw new ProxyRefusal(400, "tools is not a list");
59
60
  const out = [];
@@ -71,9 +72,9 @@ function ownTools(tools, allowed, search = false, mcp = new Set()) {
71
72
  if (DROPPED_TOOLS.has(type))
72
73
  continue;
73
74
  if (type === "namespace") {
74
- // A namespace holds the tools of a built-in family, or of an MCP server (`mcp__<server>`): only the session's own ones
75
- // stay, and an empty one goes.
76
- const kept = ownTools(tool.tools, name.startsWith("mcp__") ? new Set([...mcp].flatMap((own) => (own.startsWith(`${name}__`) ? [own.slice(name.length + 2)] : []))) : allowed);
75
+ // A namespace holds the tools of a built-in family: only the session's own ones stay, and an empty one goes. One of
76
+ // an MCP server's (`mcp__<server>`) holds none of the session's: Codex binds no MCP server of its own.
77
+ const kept = ownTools(tool.tools, name.startsWith("mcp__") ? new Set() : allowed);
77
78
  if (kept.length)
78
79
  out.push({ ...tool, tools: kept });
79
80
  continue;
@@ -171,8 +172,8 @@ function cutEnd(text) {
171
172
  * The value of `key` in the response an answer ends with: a stream's `response.completed` (or `response.incomplete`),
172
173
  * 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
173
174
  * answer, and the completed event carries the whole response (its tools and encrypted reasoning), so its line can be cut
174
- * at the window's start: then the last `"<key>":{` in the text (the response's, which a JSON string cannot contain
175
- * unescaped) is read as one JSON object. The usage is looked for in all the text kept; `tool_usage` only in the cut end
175
+ * at the window's start: then the last `"<key>": {` in the text, whatever its spacing (the kernel's `lastObjectOf`: the
176
+ * response's, which a JSON string cannot contain unescaped), is read as one JSON object. The usage is looked for in all the text kept; `tool_usage` only in the cut end
176
177
  * of the last event (`cutEnd`), since the events before the terminal one carry a `tool_usage` of their own (a count of
177
178
  * 0 as the response starts). No completed event, or no `key` in it, is undefined.
178
179
  */
@@ -209,21 +210,7 @@ function endValue(text, key) {
209
210
  catch { }
210
211
  }
211
212
  const scope = key === "usage" ? text : cutEnd(text);
212
- if (scope === undefined)
213
- return undefined;
214
- const mark = `"${key}":{`;
215
- const at = scope.lastIndexOf(mark);
216
- if (at < 0)
217
- return undefined;
218
- const json = objectAt(scope, at + mark.length - 1);
219
- if (json === undefined)
220
- return undefined;
221
- try {
222
- return JSON.parse(json);
223
- }
224
- catch {
225
- return undefined;
226
- }
213
+ return scope === undefined ? undefined : lastObjectOf(scope, key);
227
214
  }
228
215
  /**
229
216
  * Whether the provider stopped the answer on its content filter: the stream's terminal event (or a whole body) is an
@@ -346,27 +333,6 @@ export function webSearchesOf(text) {
346
333
  const count = isPlain(search) ? search.num_requests : undefined;
347
334
  return typeof count === "number" && Number.isInteger(count) && count >= 0 ? count : undefined;
348
335
  }
349
- /** The items of `type` in `value`, at any depth (a tool's output holds them). */
350
- function itemsIn(value, type) {
351
- if (Array.isArray(value))
352
- return value.reduce((n, item) => n + itemsIn(item, type), 0);
353
- if (!isPlain(value))
354
- return 0;
355
- return (value.type === type ? 1 : 0) + Object.values(value).reduce((n, item) => n + itemsIn(item, type), 0);
356
- }
357
- /**
358
- * The input tokens the provider bills for `body` that it does not carry (`providerInputOverhead`, with its sources). The
359
- * Responses API documents no prompt of its own that it adds on these routes (no hosted tool passes the policy but a
360
- * session's live web search, below), and the framing it puts around each input item and tool definition is a few tokens
361
- * each, fewer than the bytes of the JSON keys that item already spends in the body. An image is billed by its area, not
362
- * its bytes: each counts at the most it can be billed as, in place of the bytes its data URL takes in the body. A file input (a PDF, billed by its pages) has no stated bound, so a
363
- * body with one cannot be measured: this throws, and the request's input is unknown.
364
- */
365
- export function responsesServerInputOverhead(body) {
366
- if (itemsIn(body.input, "input_file") > 0)
367
- throw new Error("a file input's billed size has no stated bound");
368
- return providerInputOverhead("openai-responses", { tools: Array.isArray(body.tools) && body.tools.length > 0, images: responsesImagesIn(body.input), ...(typeof body.model === "string" ? { model: body.model } : {}) });
369
- }
370
336
  /** The text of a tool output item: a string, or the text of each of its parts. */
371
337
  /** Codex's status header of a tool output: the text it starts with (its first part), never what the script printed after it. */
372
338
  function statusText(item) {
@@ -568,7 +534,6 @@ export function addResponsesNote(body, text) {
568
534
  }
569
535
  export function codexPolicy(options) {
570
536
  const allowed = new Set(options.tools);
571
- const mcp = new Set(options.mcpTools ?? []);
572
537
  const maxOutputTokens = options.maxOutputTokens ?? 32_000;
573
538
  const search = options.webSearch === "live";
574
539
  return {
@@ -581,49 +546,21 @@ export function codexPolicy(options) {
581
546
  },
582
547
  authHeaders: (credential) => ({ authorization: `Bearer ${credential}` }),
583
548
  apply(body, _route, context) {
584
- if (!isPlain(body))
585
- throw new ProxyRefusal(400, "the body is not a JSON object");
586
- // The host's own request beside Codex's (ProxyRequestContext.host) offers its own client tools (a learned workflow
587
- // node's `submit`); every other rule is the session's, a provider-hosted tool refused as ever.
588
- const own = context?.host !== undefined ? sideToolNames(body.tools) : allowed;
589
- const out = {};
590
- for (const [key, value] of Object.entries(body)) {
591
- if (DROPPED_KEYS.has(key))
592
- continue;
593
- if (!BODY_KEYS.has(key) && !(context?.host !== undefined && SIDE_KEYS.has(key)))
594
- throw new ProxyRefusal(400, "the body has a field the Codex policy does not allow");
595
- out[key] = value;
596
- }
597
- if (out.include !== undefined && (!Array.isArray(out.include) || !out.include.every((item) => typeof item === "string" && (INCLUDE.has(item) || (context?.host !== undefined && SIDE_INCLUDE.has(item)))))) {
598
- throw new ProxyRefusal(400, "include asks for an item the Codex policy does not allow");
599
- }
600
- if (out.stream !== undefined && typeof out.stream !== "boolean")
601
- throw new ProxyRefusal(400, "stream is not a boolean");
602
- if (out.reasoning !== undefined && !isPlain(out.reasoning))
603
- throw new ProxyRefusal(400, "reasoning is not an object");
604
- if (out.text !== undefined)
605
- out.text = textOptions(out.text);
606
- if (out.tools !== undefined)
607
- out.tools = ownTools(out.tools, own, search, mcp);
608
- if (out.tool_choice !== undefined)
609
- out.tool_choice = toolChoice(out.tool_choice, own, search);
610
- if (Array.isArray(out.input) && out.input.some((item) => isPlain(item) && item.type === "additional_tools")) {
611
- // While a script that yielded still runs, the model is offered `wait` and not `exec`: one script is live at a time.
612
- const offerExec = !cellRunning(out.input);
613
- out.input = out.input.map((item) => codeModeCarrier(item, offerExec));
614
- // 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
615
- // parallel calls is refused, and one that says nothing is sent with them off. A classic request is as the CLI sent it.
616
- if (out.parallel_tool_calls !== undefined && typeof out.parallel_tool_calls !== "boolean")
617
- throw new ProxyRefusal(400, "parallel_tool_calls is not a boolean");
618
- if (out.parallel_tool_calls === true)
619
- throw new ProxyRefusal(400, "parallel tool calls are not allowed in code mode: the model writes one exec at a time");
620
- out.parallel_tool_calls = false;
621
- }
622
- const asked = typeof out.max_output_tokens === "number" && out.max_output_tokens > 0 ? out.max_output_tokens : maxOutputTokens;
623
- return { ...out, model: options.model, store: false, max_output_tokens: Math.min(asked, maxOutputTokens) };
549
+ // The live search, offered by the request, goes only while the host says web_search may run now: read before this
550
+ // request is shaped, never once for the session. A read that fails offers none.
551
+ const asking = search && options.searchAllowed && isPlain(body) && Array.isArray(body.tools) && body.tools.some((tool) => isPlain(tool) && tool.type === "web_search");
552
+ if (!asking)
553
+ return shaped(body, context, search);
554
+ return options.searchAllowed().then((now) => shaped(body, context, now === true), () => shaped(body, context, false));
624
555
  },
625
- usageOf: search ? (text) => {
556
+ usageOf: search ? (text, body) => {
626
557
  const usage = usageOf(text);
558
+ // A request that offered no search (`body`, the one it was sent with: a host's side request through the session's
559
+ // port, a learned workflow's node that offers only `submit`) ran none: 0, read from the request, never an unknown
560
+ // count that would make its whole known cost unknown (withWebSearches). One that offered it reads its answer.
561
+ const offered = Array.isArray(body?.tools) && body.tools.some((tool) => typeof tool === "object" && tool !== null && isLiveSearch(tool));
562
+ if (usage && body && !offered)
563
+ return { ...usage, webSearches: 0 };
627
564
  return usage && { ...usage, webSearches: webSearchesOf(text) ?? null };
628
565
  } : usageOf,
629
566
  filtered,
@@ -631,18 +568,64 @@ export function codexPolicy(options) {
631
568
  watch: options.announce ? () => watchResponse(options.announce) : undefined,
632
569
  unwatched: options.announce ? () => options.announce.failed() : undefined,
633
570
  modelOf: (body) => (typeof body.model === "string" ? body.model : undefined),
634
- // The content a web search feeds the model is billed as input, and neither it nor the searches one response runs has a
635
- // stated bound: a body that offers web search has no input bound (undefined), so its input is unmeasured.
636
571
  outputAsked: responsesOutputAsked,
637
572
  outputLeast: responsesOutputLeast,
638
573
  reasoningHidden: (body) => responsesReasoningHidden(body, maxOutputTokens),
639
574
  reasoningBytesOf: responsesReasoningBytes,
640
575
  contentBytesOf: responsesContentBytes,
641
576
  limitOutput: limitResponsesOutput,
577
+ // The content a web search feeds the model is billed as input, and neither it nor the searches one response runs has a
578
+ // stated bound: a body that offers web search has no input bound (undefined), so its input is unmeasured (and never
579
+ // counted into a number).
642
580
  serverInputOverhead: search ? (body) => {
643
581
  if (Array.isArray(body.tools) && body.tools.some((tool) => isPlain(tool) && tool.type === "web_search"))
644
582
  return undefined;
645
- return responsesServerInputOverhead(body);
646
- } : responsesServerInputOverhead,
583
+ return responsesInputOverhead(body);
584
+ } : responsesInputOverhead,
585
+ countInput: OPENAI_INPUT_COUNTER,
647
586
  };
587
+ /** The body the provider gets, the live search offered only when `searchNow`. */
588
+ function shaped(body, context, searchNow) {
589
+ if (!isPlain(body))
590
+ throw new ProxyRefusal(400, "the body is not a JSON object");
591
+ // The host's own request beside Codex's (ProxyRequestContext.host) offers its own client tools (a learned workflow
592
+ // node's `submit`); every other rule is the session's, a provider-hosted tool refused as ever.
593
+ const own = context?.host !== undefined ? sideToolNames(body.tools) : allowed;
594
+ const out = {};
595
+ for (const [key, value] of Object.entries(body)) {
596
+ if (DROPPED_KEYS.has(key))
597
+ continue;
598
+ if (!BODY_KEYS.has(key) && !(context?.host !== undefined && SIDE_KEYS.has(key)))
599
+ throw new ProxyRefusal(400, "the body has a field the Codex policy does not allow");
600
+ out[key] = value;
601
+ }
602
+ if (out.include !== undefined && (!Array.isArray(out.include) || !out.include.every((item) => typeof item === "string" && (INCLUDE.has(item) || (context?.host !== undefined && SIDE_INCLUDE.has(item)))))) {
603
+ throw new ProxyRefusal(400, "include asks for an item the Codex policy does not allow");
604
+ }
605
+ if (out.stream !== undefined && typeof out.stream !== "boolean")
606
+ throw new ProxyRefusal(400, "stream is not a boolean");
607
+ if (out.reasoning !== undefined && !isPlain(out.reasoning))
608
+ throw new ProxyRefusal(400, "reasoning is not an object");
609
+ if (out.text !== undefined)
610
+ out.text = textOptions(out.text);
611
+ // Without the search now, its tool is dropped as a session without one drops it (DROPPED_TOOLS).
612
+ if (out.tools !== undefined)
613
+ out.tools = ownTools(out.tools, own, searchNow);
614
+ if (out.tool_choice !== undefined)
615
+ out.tool_choice = toolChoice(out.tool_choice, own, searchNow);
616
+ if (Array.isArray(out.input) && out.input.some((item) => isPlain(item) && item.type === "additional_tools")) {
617
+ // While a script that yielded still runs, the model is offered `wait` and not `exec`: one script is live at a time.
618
+ const offerExec = !cellRunning(out.input);
619
+ out.input = out.input.map((item) => codeModeCarrier(item, offerExec));
620
+ // 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
621
+ // parallel calls is refused, and one that says nothing is sent with them off. A classic request is as the CLI sent it.
622
+ if (out.parallel_tool_calls !== undefined && typeof out.parallel_tool_calls !== "boolean")
623
+ throw new ProxyRefusal(400, "parallel_tool_calls is not a boolean");
624
+ if (out.parallel_tool_calls === true)
625
+ throw new ProxyRefusal(400, "parallel tool calls are not allowed in code mode: the model writes one exec at a time");
626
+ out.parallel_tool_calls = false;
627
+ }
628
+ const asked = typeof out.max_output_tokens === "number" && out.max_output_tokens > 0 ? out.max_output_tokens : maxOutputTokens;
629
+ return { ...out, model: options.model, store: false, max_output_tokens: Math.min(asked, maxOutputTokens) };
630
+ }
648
631
  }
@@ -1,16 +1,21 @@
1
1
  import { toolBridge as kernelToolBridge, type ToolBridge, type ToolBridgeOptions } from "@parcha/agentrun-kernel/process";
2
- import type { ToolImage } from "@parcha/agentrun-kernel";
2
+ import type { JsonValue, ToolImage } from "@parcha/agentrun-kernel";
3
3
  import type { TomlValue } from "../config.js";
4
4
  import type { DriveContext } from "./kernel.js";
5
5
  export { boundResult, BuiltinCalls, failureText, Mutex, NativeJournal, openTurn, placeSubmissions, recoveryNote, recoverySystemNote, recoveryUserTurn, restartEvent, resumeUnstartedCalls, toolKey, transcriptOf, } from "@parcha/agentrun-kernel/process";
6
6
  export type { BuiltinStart, ToolResult, TranscriptEntry } from "@parcha/agentrun-kernel/process";
7
- /** The kernel's tool bridge, keeping each call's images by its call id until the answer to Codex takes them
8
- * (`takeImages`, code-mode.ts): the harness answers Codex with a result's text, and code mode's request handler adds
9
- * the images as `inputImage` items. */
10
- export interface ImageBridge extends ToolBridge {
11
- takeImages(callId: string): readonly ToolImage[] | undefined;
7
+ /** What a call answered beside its text: its images, and its value (a computer tool's, its images' data left out). */
8
+ export type CallExtras = {
9
+ readonly images?: readonly ToolImage[];
10
+ readonly structured?: JsonValue;
11
+ };
12
+ /** The kernel's tool bridge, keeping each call's images and value by its call id until the answer to Codex takes them
13
+ * (`take`, code-mode.ts): the harness answers Codex with a result's text, and code mode's request handler adds the
14
+ * images as `inputImage` items, or, for a script's nested call of a tool with a value, answers the value. */
15
+ export interface ExtrasBridge extends ToolBridge {
16
+ take(callId: string): CallExtras | undefined;
12
17
  }
13
- export declare function toolBridge(ctx: Parameters<typeof kernelToolBridge>[0], tools: Parameters<typeof kernelToolBridge>[1], options?: ToolBridgeOptions): ImageBridge;
18
+ export declare function toolBridge(ctx: Parameters<typeof kernelToolBridge>[0], tools: Parameters<typeof kernelToolBridge>[1], options?: ToolBridgeOptions): ExtrasBridge;
14
19
  /** A child's line protocol: one JSON value per line out, lines in. */
15
20
  export interface LineChannel {
16
21
  send(line: unknown): boolean;
@@ -76,8 +81,6 @@ export interface SessionMachine {
76
81
  announcedExec?(): string | undefined;
77
82
  /** Told each line the rollout's tail reads, as it reads it: the harness's view of code mode follows the log from here. */
78
83
  onRolloutLine?(listener: (line: string) => void): void;
79
- /** Given the drive's hooks for a call the harness never sees (a remote MCP server's tool, mcp.ts). */
80
- onCalls?(hooks: CallHooks): void;
81
84
  /** Told when the model proxy reads that the provider cut the turn's answer at its output limit, before Codex has the
82
85
  * piece that carries the stop (its output tokens, when the answer said them): the harness ends the turn there. */
83
86
  onCut?(listener: (stop: {
@@ -92,14 +95,6 @@ export interface SessionMachine {
92
95
  fsync(): Promise<void>;
93
96
  close(): Promise<void>;
94
97
  }
95
- /** The drive's hooks for a call Codex runs without the harness (code-mode.ts gives them, mcp.ts uses them). */
96
- export interface CallHooks {
97
- /** Resolves true once the call's own line (a script's nested call: its script's) is in the log, false when it never came. */
98
- barrier(callId: string): Promise<boolean>;
99
- /** After a recovery: what answers a call of `tool` with `args` that already completed in the interrupted turn (a rewritten
100
- * script re-issues its calls under new ids), taken once; undefined for any other call. */
101
- recovered(tool: string, args: unknown): string | undefined;
102
- }
103
98
  /** What a harness's drive asks its machine factory for: the drive, the model route its proxy serves, and its deadline. */
104
99
  export interface AcquireMachineRequest {
105
100
  ctx: DriveContext;
@@ -5,18 +5,18 @@ import { toolBridge as kernelToolBridge } from "@parcha/agentrun-kernel/process"
5
5
  export { boundResult, BuiltinCalls, failureText, Mutex, NativeJournal, openTurn, placeSubmissions, recoveryNote, recoverySystemNote, recoveryUserTurn, restartEvent, resumeUnstartedCalls, toolKey, transcriptOf, } from "@parcha/agentrun-kernel/process";
6
6
  export function toolBridge(ctx, tools, options) {
7
7
  const bridge = kernelToolBridge(ctx, tools, options);
8
- const images = new Map();
8
+ const extras = new Map();
9
9
  return {
10
10
  ...bridge,
11
11
  call: async (name, args, callId, signal) => {
12
12
  const result = await bridge.call(name, args, callId, signal);
13
- if (callId && result.images?.length)
14
- images.set(callId, result.images);
13
+ if (callId && (result.images?.length || result.structured !== undefined))
14
+ extras.set(callId, { ...(result.images?.length ? { images: result.images } : {}), ...(result.structured !== undefined ? { structured: result.structured } : {}) });
15
15
  return result;
16
16
  },
17
- takeImages: (callId) => {
18
- const taken = images.get(callId);
19
- images.delete(callId);
17
+ take: (callId) => {
18
+ const taken = extras.get(callId);
19
+ extras.delete(callId);
20
20
  return taken;
21
21
  },
22
22
  };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { CODEX_TOOL_OUTPUT_TOKENS, codexAdapter } from "./adapter.js";
2
2
  /** The policy a Codex session's model proxy applies, for a host that serves the same route itself (a faux harness's). */
3
- export { codexPolicy } from "./host/policy.js";
3
+ export { codexPolicy, webSearchUsd, withWebSearches } from "./host/policy.js";
4
4
  /** The check the adapter runs on the host's skills when it is made: @parcha/agentrun-kernel' own, as the Claude adapter's. */
5
5
  export { skillProblems } from "@parcha/agentrun-kernel";
6
6
  export type { HostSkill } from "@parcha/agentrun-kernel";
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  export { CODEX_TOOL_OUTPUT_TOKENS, codexAdapter } from "./adapter.js";
2
2
  /** The policy a Codex session's model proxy applies, for a host that serves the same route itself (a faux harness's). */
3
- export { codexPolicy } from "./host/policy.js";
3
+ export { codexPolicy, webSearchUsd, withWebSearches } from "./host/policy.js";
4
4
  /** The check the adapter runs on the host's skills when it is made: @parcha/agentrun-kernel' own, as the Claude adapter's. */
5
5
  export { skillProblems } from "@parcha/agentrun-kernel";
6
6
  export { CODEX_VERSION, codexBinary, codexTarget } from "./binary.js";
package/dist/scripts.d.ts CHANGED
@@ -49,7 +49,8 @@ export interface NestedFact {
49
49
  store?: {
50
50
  status: "completed" | "failed" | "started";
51
51
  text?: string;
52
- interrupted?: boolean;
52
+ interrupted?: boolean; /** What a script's nested call was sent for a tool with a value (scriptAnswer: the value as JSON, its images' data in it), which the rollout holds instead of `text`. */
53
+ sent?: string;
53
54
  };
54
55
  /** What the harness's recovery note of the same turn calls it (the kernel's one rule, process/recovery.ts): `retryable` is a
55
56
  * safe tool's call that a crash cut off, which the note tells the model is safe to repeat. */
@@ -57,6 +58,14 @@ export interface NestedFact {
57
58
  rollout?: RolloutNested;
58
59
  /** The host parked the call for a person's approval (`parkedKey`'s record): it did not run, whatever its record says. */
59
60
  parked?: true;
61
+ /** Asked again on this resume (code-mode.ts recoverItems): it never reached its intent before, as a park at the host's gate
62
+ * leaves a call, and went through the gate now, the person's answer on it: what it answered, and whether it ran (a refusal
63
+ * never does). */
64
+ resumed?: {
65
+ text: string;
66
+ isError: boolean;
67
+ ran: boolean;
68
+ };
60
69
  }
61
70
  export type Settled = {
62
71
  kind: "completed";
@@ -98,6 +107,9 @@ export declare function recoveryFacts<T>(execs: readonly string[], ties: readonl
98
107
  /** The output a cut-off `exec` is answered with: its nested calls, in order, each with what it came to, and that nothing was run
99
108
  * again. A completed call's effect is done, a never tool's included; a call with no end is interrupted. `loose`: calls of this turn
100
109
  * whose script could not be told (given to the last cut-off exec only), listed apart under their own heading. */
110
+ /** What a dangling `wait` on a yielded exec's cell is told when calls of that script that waited for a person's approval
111
+ * were answered on this resume (code-mode.ts recoverItems): each call's outcome, in order. */
112
+ export declare function waitResumedText(cell: string, resumed: readonly NestedFact[]): string;
101
113
  export declare function execRecoveryOutput(facts: readonly NestedFact[], loose?: readonly NestedFact[]): string;
102
114
  /** The text of a tool's recorded output (a string, or `{ text }` with images). */
103
115
  export declare function outputTextOf(output: unknown): string;
package/dist/scripts.js CHANGED
@@ -106,7 +106,7 @@ export function settle(fact) {
106
106
  const stored = store?.status === "completed" ? { kind: "completed", text: store.text ?? "" } : store?.status === "failed" && !store.interrupted ? { kind: "failed", text: store.text ?? "" } : undefined;
107
107
  const rolled = rollout ? { kind: rollout.ok ? "completed" : "failed", text: rollout.text } : undefined;
108
108
  if (stored && rolled)
109
- return stored.kind === rolled.kind && (rolled.text === stored.text || rolled.text === boundResult(stored.text).text) ? stored : { kind: "interrupted" };
109
+ return stored.kind === rolled.kind && (rolled.text === stored.text || rolled.text === boundResult(stored.text).text || (store?.sent !== undefined && rolled.text === store.sent)) ? stored : { kind: "interrupted" };
110
110
  return stored ?? rolled ?? { kind: "interrupted" };
111
111
  }
112
112
  const quoted = (text) => JSON.stringify(text.length > 2000 ? `${text.slice(0, 2000)}… [${text.length - 2000} more characters]` : text);
@@ -124,6 +124,13 @@ const describeCall = (fact, label) => {
124
124
  const settled = settle(fact);
125
125
  if (settled.kind === "parked")
126
126
  return `${label} was waiting for a person's approval and did not run; it was not run again.`;
127
+ const again = fact.resumed;
128
+ if (again && !again.ran)
129
+ return `${label} waited for a person's approval, then: ${quoted(again.text)}. It did not run.`;
130
+ if (again && again.isError)
131
+ return `${label} waited for a person's approval, then ran and failed: ${quoted(again.text)}. It was not run again.`;
132
+ if (again)
133
+ return `${label} waited for a person's approval, then ran: ${quoted(again.text)}. Its effect is done; it was not run again.`;
127
134
  if (settled.kind === "completed")
128
135
  return `${label} completed: ${quoted(settled.text)}. Its effect is done; it was not run again.`;
129
136
  if (settled.kind === "failed")
@@ -136,6 +143,12 @@ const describeCall = (fact, label) => {
136
143
  /** The output a cut-off `exec` is answered with: its nested calls, in order, each with what it came to, and that nothing was run
137
144
  * again. A completed call's effect is done, a never tool's included; a call with no end is interrupted. `loose`: calls of this turn
138
145
  * whose script could not be told (given to the last cut-off exec only), listed apart under their own heading. */
146
+ /** What a dangling `wait` on a yielded exec's cell is told when calls of that script that waited for a person's approval
147
+ * were answered on this resume (code-mode.ts recoverItems): each call's outcome, in order. */
148
+ export function waitResumedText(cell, resumed) {
149
+ const lines = resumed.map((fact, i) => describeCall(fact, `${i + 1}. ${fact.tool}`));
150
+ return `The session stopped while waiting on cell ${cell}; that cell's script was cut off. Its calls that waited for a person's approval were answered since, each once:\n${lines.join("\n")}\nNothing else of the script was run again. Check the actual state before relying on it.`;
151
+ }
139
152
  export function execRecoveryOutput(facts, loose = []) {
140
153
  const apart = loose.length
141
154
  ? `\n${loose.length} ${loose.length === 1 ? "call" : "calls"} ran whose script could not be told (an answer of the model's could not be read to its end):\n${loose.map((fact, i) => describeCall(fact, `${i + 1}. ${fact.tool}`)).join("\n")}`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-harness-codex",
3
- "version": "0.1.0-beta.36",
3
+ "version": "0.1.0-beta.38",
4
4
  "description": "Codex as an AgentRun harness: a tool-less Codex app-server behind a loopback model proxy, durable in AgentRun's own store, with the host's tools as its only tools.",
5
5
  "keywords": [
6
6
  "agentrun",
@@ -44,7 +44,7 @@
44
44
  "test": "node --test --test-concurrency=8 'test/*.test.mjs'"
45
45
  },
46
46
  "dependencies": {
47
- "@parcha/agentrun-kernel": "0.1.0-beta.36"
47
+ "@parcha/agentrun-kernel": "0.1.0-beta.38"
48
48
  },
49
49
  "peerDependencies": {
50
50
  "@openai/codex": "0.164.0"
@@ -56,7 +56,7 @@
56
56
  },
57
57
  "devDependencies": {
58
58
  "@openai/codex": "0.164.0",
59
- "@parcha/agentrun-dsl": "0.1.0-beta.36"
59
+ "@parcha/agentrun-dsl": "0.1.0-beta.38"
60
60
  },
61
61
  "repository": {
62
62
  "type": "git",
package/dist/mcp.d.ts DELETED
@@ -1,15 +0,0 @@
1
- import { type McpClient, type SessionMcp } from "@parcha/agentrun-kernel";
2
- import type { TomlValue } from "./config.js";
3
- import type { DriveContext } from "./host/kernel.js";
4
- import { type CallHooks } from "./host/process.js";
5
- /** Codex's own MCP client: it sends a call's id in tools/call's `_meta.callId`, its `mcpToolCall` item's id
6
- * (codex-rs core/src/mcp_tool_call.rs at rust-v0.164.0), the id the drive records the call by. */
7
- export declare const CODEX_MCP_CLIENT: McpClient;
8
- /** The `mcp_servers` table for `mcp`'s servers at the proxy `modelUrl`, Codex's bearer read from `keyEnv` (the env var
9
- * that holds the session's key). No `tool_timeout_sec`: Codex's 300 s default covers the gateway's own bound on one
10
- * call (120 s), and a call that needs a person parks and ends the turn, never waits at the proxy. */
11
- export declare function mcpServersConfig(mcp: SessionMcp, modelUrl: string, keyEnv: string): Record<string, TomlValue>;
12
- /** `mcp` with each call recorded in the drive's session as a built-in's, `mcp__<server>__<tool>` under Codex's call id:
13
- * its intent once `barrier` has its line in the log and before it is sent, its outcome once it answers. A call id the
14
- * records already hold is answered from them. */
15
- export declare function recorded(mcp: SessionMcp, ctx: DriveContext, hooks: () => CallHooks | undefined): SessionMcp;
package/dist/mcp.js DELETED
@@ -1,74 +0,0 @@
1
- // A session's remote MCP servers on Codex, written for AgentRun. Codex's own MCP client calls each one at the session's
2
- // model proxy (`<modelUrl>/mcp/<server>`, which the kernel's proxy mounts from the session's MCP and CODEX_MCP_CLIENT),
3
- // with the session's key as its bearer, so it never holds a server's credential. The session's machine
4
- // (host/machine.ts) does both halves:
5
- // - it writes each server in Codex's `mcp_servers` (an app may not: config.ts RESERVED_CONFIG_KEYS), with only the
6
- // granted tools. Each call is allowed without asking (`default_tools_approval_mode = "approve"`): the proxy is the
7
- // one gate, and under Codex's default a tool with no `readOnlyHint` is refused when nobody is there to approve it.
8
- // Each server is `required`, and its endpoint is the proxy, which answers `initialize` and `tools/list` itself from
9
- // the grant: the thread starts with every granted tool, and a remote server that can't be reached shows at the first
10
- // call, as that call's error result. Only a proxy route Codex can't reach fails the thread's start.
11
- // - it records each call (`recorded`). Codex sends a call to the proxy as soon as it starts the call's item, and waits
12
- // for nothing of ours, so the proxy writes the call's intent in the session's records itself, by Codex's own call id
13
- // (`_meta.callId`), before anything is sent, and its outcome after. A call a crash cut off is then answered
14
- // interrupted from the records, never sent twice.
15
- import { HOST_RESULT_MAX_CHARS } from "@parcha/agentrun-kernel";
16
- import { BuiltinCalls, toolKey } from "./host/process.js";
17
- import { markParked } from "./scripts.js";
18
- /** Codex's own MCP client: it sends a call's id in tools/call's `_meta.callId`, its `mcpToolCall` item's id
19
- * (codex-rs core/src/mcp_tool_call.rs at rust-v0.164.0), the id the drive records the call by. */
20
- export const CODEX_MCP_CLIENT = { callIdMeta: "callId" };
21
- /** What a call answers when its line never reached the log: nothing was sent, and it may be made again. */
22
- const LAGGING = "Not sent: the session's log had not caught up with this call yet. Nothing reached the MCP server; make the same call again.";
23
- /** The `mcp_servers` table for `mcp`'s servers at the proxy `modelUrl`, Codex's bearer read from `keyEnv` (the env var
24
- * that holds the session's key). No `tool_timeout_sec`: Codex's 300 s default covers the gateway's own bound on one
25
- * call (120 s), and a call that needs a person parks and ends the turn, never waits at the proxy. */
26
- export function mcpServersConfig(mcp, modelUrl, keyEnv) {
27
- return Object.fromEntries(mcp.servers.map((server) => [server.name, {
28
- url: `${modelUrl}/mcp/${server.name}`,
29
- bearer_token_env_var: keyEnv,
30
- enabled_tools: server.tools.map((tool) => tool.name),
31
- required: true,
32
- default_tools_approval_mode: "approve",
33
- }]));
34
- }
35
- const said = (text, isError) => ({ content: [{ type: "text", text }], ...(isError ? { isError: true } : {}) });
36
- /** `mcp` with each call recorded in the drive's session as a built-in's, `mcp__<server>__<tool>` under Codex's call id:
37
- * its intent once `barrier` has its line in the log and before it is sent, its outcome once it answers. A call id the
38
- * records already hold is answered from them. */
39
- export function recorded(mcp, ctx, hooks) {
40
- // Each outcome is kept whole, up to the host's bound on a tool result, the most the door hands Codex: a call answered
41
- // again from the records reads what the server said, never the step's default cut.
42
- const calls = new BuiltinCalls(ctx, { outputChars: HOST_RESULT_MAX_CHARS });
43
- return {
44
- servers: mcp.servers,
45
- async call(server, tool, args, context) {
46
- const callId = context.callId;
47
- if (!callId)
48
- return said("Not sent: the call carried no call id to record it by. Nothing reached the MCP server.", true);
49
- const name = `mcp__${server}__${tool}`;
50
- // A call the interrupted turn already completed, re-issued by a rewritten script under a new id: answered from the log.
51
- const again = hooks()?.recovered(name, args);
52
- if (again !== undefined)
53
- return said(again, false);
54
- let start;
55
- try {
56
- // The call's own line in the log before its intent, as a built-in's (code-mode.ts holds the barrier).
57
- if (!ctx.isMemoized(toolKey(callId)) && !(await (hooks()?.barrier(callId) ?? false)))
58
- return said(LAGGING, true);
59
- start = await calls.begin({ callId, name, input: args, replay: "never" });
60
- }
61
- catch {
62
- return said("Not sent: the session could not record the call. Nothing reached the MCP server.", true);
63
- }
64
- if (!start.run)
65
- return said(start.result.text, start.result.isError === true);
66
- const result = await mcp.call(server, tool, args, context);
67
- // A call the host parked for a person's approval did not run: recorded so before its answer, the waiting text.
68
- if (result.parked)
69
- await markParked(ctx, callId).catch(() => { });
70
- await calls.end(callId, { text: result.content.map((block) => block.text).join("\n\n"), isError: result.isError === true }).catch(() => { });
71
- return result;
72
- },
73
- };
74
- }