@parcha/agentrun-harness-codex 0.1.0-beta.31 → 0.1.0-beta.32

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.
@@ -13,6 +13,10 @@ const SCHEMA_FORMAT_KEYS = new Set(["type", "name", "schema", "strict"]);
13
13
  const DROPPED_KEYS = new Set(["client_metadata"]);
14
14
  /** What `include` may ask for: the encrypted reasoning the CLI sends back on its next request (`store` is false). */
15
15
  const INCLUDE = new Set(["reasoning.encrypted_content"]);
16
+ /** What the host's own side request (ProxyRequestContext.host) may carry beside: a native search's limit on its hosted
17
+ * calls (`max_tool_calls`, which only narrows it) and the sources its results cite. */
18
+ const SIDE_KEYS = new Set(["max_tool_calls"]);
19
+ const SIDE_INCLUDE = new Set(["web_search_call.action.sources"]);
16
20
  /** Provider-hosted tools the CLI adds to every request whatever its config says: dropped, never offered. */
17
21
  const DROPPED_TOOLS = new Set(["web_search", "web_search_preview"]);
18
22
  /** The web search tool the pinned CLI sends with `web_search = "live"` through the session's provider, recorded
@@ -48,8 +52,8 @@ export function withWebSearches(price) {
48
52
  }
49
53
  const isPlain = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
50
54
  /** 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) {
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()) {
53
57
  if (!Array.isArray(tools))
54
58
  throw new ProxyRefusal(400, "tools is not a list");
55
59
  const out = [];
@@ -67,8 +71,9 @@ function ownTools(tools, allowed, search = false) {
67
71
  if (DROPPED_TOOLS.has(type))
68
72
  continue;
69
73
  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);
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);
72
77
  if (kept.length)
73
78
  out.push({ ...tool, tools: kept });
74
79
  continue;
@@ -80,6 +85,8 @@ function ownTools(tools, allowed, search = false) {
80
85
  }
81
86
  return out;
82
87
  }
88
+ /** The function and custom tools a side request offers, by name (its own client tools). */
89
+ const sideToolNames = (tools) => new Set(Array.isArray(tools) ? tools.filter((tool) => isPlain(tool) && (tool.type === "function" || tool.type === "custom") && typeof tool.name === "string").map((tool) => tool.name) : []);
83
90
  /** `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
91
  function toolChoice(choice, allowed, search = false) {
85
92
  if (choice === "auto" || choice === "none" || choice === "required")
@@ -233,7 +240,27 @@ function endValue(text, key) {
233
240
  * `"incomplete_details":{` after `"response":{` (one JSON object), whatever the JSON's spacing.
234
241
  */
235
242
  export function filtered(text, lineStarts = []) {
236
- let end = terminalResponse(text.split("\n"), false);
243
+ const end = answerEnd(text, lineStarts);
244
+ return isPlain(end) && end.status === "incomplete" && isPlain(end.incomplete_details) && end.incomplete_details.reason === "content_filter";
245
+ }
246
+ /**
247
+ * Whether the provider cut the answer at its output limit: its end is an `incomplete` response whose
248
+ * `incomplete_details.reason` is `max_output_tokens`, with the output tokens its usage reports when the end was read whole.
249
+ * Read as `filtered` reads its stop, but keyed only on the data's own `type` (`response.incomplete`), never on an `event:`
250
+ * line: a gateway's Responses stream is data alone. Any other reason (`content_filter`) is no cut. Codex 0.164 takes a cut
251
+ * answer as a stream error and asks for it again, each time paid; the harness ends the turn first.
252
+ */
253
+ export function cut(text, lineStarts = []) {
254
+ const end = answerEnd(text, lineStarts, false);
255
+ if (!(isPlain(end) && end.status === "incomplete" && isPlain(end.incomplete_details) && end.incomplete_details.reason === "max_output_tokens"))
256
+ return undefined;
257
+ const output = isPlain(end.usage) ? end.usage.output_tokens : undefined;
258
+ return typeof output === "number" && Number.isSafeInteger(output) && output >= 0 ? { outputTokens: output } : {};
259
+ }
260
+ /** The response an answer ends with: its stream's terminal event's, a whole body's, or a kept line start's (`filtered`).
261
+ * `byName`: a kept start an `event: response.incomplete` line names is the stop's too (else only its data's type). */
262
+ function answerEnd(text, lineStarts, byName = true) {
263
+ let end = terminalResponse(text.split("\n"), false, byName);
237
264
  if (end === undefined) {
238
265
  const whole = text.trimStart();
239
266
  if (whole.startsWith("{")) {
@@ -245,18 +272,17 @@ export function filtered(text, lineStarts = []) {
245
272
  catch { }
246
273
  }
247
274
  }
248
- end ??= terminalResponse(lineStarts, true);
249
- return isPlain(end) && end.status === "incomplete" && isPlain(end.incomplete_details) && end.incomplete_details.reason === "content_filter";
275
+ return end ?? terminalResponse(lineStarts, true, byName);
250
276
  }
251
277
  /** 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) {
278
+ * the lines are kept starts, and one that is a `response.incomplete` event's (by its name when `byName`, or its data's
279
+ * type ahead of its response) is read from its start. */
280
+ function terminalResponse(lines, starts, byName = true) {
255
281
  let end;
256
282
  let named = false;
257
283
  for (const line of lines) {
258
284
  if (line.startsWith("event:")) {
259
- named = line.slice(6).trim() === "response.incomplete";
285
+ named = byName && line.slice(6).trim() === "response.incomplete";
260
286
  continue;
261
287
  }
262
288
  if (!line.startsWith("data:"))
@@ -533,30 +559,42 @@ export function limitResponsesOutput(body, max) {
533
559
  const asked = responsesOutputAsked(body);
534
560
  return { ...body, max_output_tokens: asked === undefined ? max : Math.min(asked, max) };
535
561
  }
562
+ /** `body` (a Responses body) with `text` as a note the model reads after everything the client sent: one developer message
563
+ * at the end of `input`. Caching is by prefix, so the earlier items stay a hit; the client's next request, which sends
564
+ * its own input whole, does not carry it. */
565
+ export function addResponsesNote(body, text) {
566
+ const input = Array.isArray(body.input) ? body.input : [];
567
+ return { ...body, input: [...input, { type: "message", role: "developer", content: [{ type: "input_text", text }] }] };
568
+ }
536
569
  export function codexPolicy(options) {
537
570
  const allowed = new Set(options.tools);
571
+ const mcp = new Set(options.mcpTools ?? []);
538
572
  const maxOutputTokens = options.maxOutputTokens ?? 32_000;
539
573
  const search = options.webSearch === "live";
540
574
  return {
541
575
  id: "codex",
542
576
  routes: CODEX_RESPONSES_ROUTES,
577
+ addNote: addResponsesNote,
543
578
  keyOf(headers) {
544
579
  const auth = String(headers.authorization ?? "");
545
580
  return auth.startsWith("Bearer ") ? auth.slice(7) : "";
546
581
  },
547
582
  authHeaders: (credential) => ({ authorization: `Bearer ${credential}` }),
548
- apply(body) {
583
+ apply(body, _route, context) {
549
584
  if (!isPlain(body))
550
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;
551
589
  const out = {};
552
590
  for (const [key, value] of Object.entries(body)) {
553
591
  if (DROPPED_KEYS.has(key))
554
592
  continue;
555
- if (!BODY_KEYS.has(key))
593
+ if (!BODY_KEYS.has(key) && !(context?.host !== undefined && SIDE_KEYS.has(key)))
556
594
  throw new ProxyRefusal(400, "the body has a field the Codex policy does not allow");
557
595
  out[key] = value;
558
596
  }
559
- if (out.include !== undefined && (!Array.isArray(out.include) || !out.include.every((item) => typeof item === "string" && INCLUDE.has(item)))) {
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)))))) {
560
598
  throw new ProxyRefusal(400, "include asks for an item the Codex policy does not allow");
561
599
  }
562
600
  if (out.stream !== undefined && typeof out.stream !== "boolean")
@@ -566,9 +604,9 @@ export function codexPolicy(options) {
566
604
  if (out.text !== undefined)
567
605
  out.text = textOptions(out.text);
568
606
  if (out.tools !== undefined)
569
- out.tools = ownTools(out.tools, allowed, search);
607
+ out.tools = ownTools(out.tools, own, search, mcp);
570
608
  if (out.tool_choice !== undefined)
571
- out.tool_choice = toolChoice(out.tool_choice, allowed, search);
609
+ out.tool_choice = toolChoice(out.tool_choice, own, search);
572
610
  if (Array.isArray(out.input) && out.input.some((item) => isPlain(item) && item.type === "additional_tools")) {
573
611
  // While a script that yielded still runs, the model is offered `wait` and not `exec`: one script is live at a time.
574
612
  const offerExec = !cellRunning(out.input);
@@ -589,6 +627,7 @@ export function codexPolicy(options) {
589
627
  return usage && { ...usage, webSearches: webSearchesOf(text) ?? null };
590
628
  } : usageOf,
591
629
  filtered,
630
+ cut,
592
631
  watch: options.announce ? () => watchResponse(options.announce) : undefined,
593
632
  unwatched: options.announce ? () => options.announce.failed() : undefined,
594
633
  modelOf: (body) => (typeof body.model === "string" ? body.model : undefined),
@@ -1,7 +1,16 @@
1
+ import { toolBridge as kernelToolBridge, type ToolBridge, type ToolBridgeOptions } from "@parcha/agentrun-kernel/process";
2
+ import type { ToolImage } from "@parcha/agentrun-kernel";
1
3
  import type { TomlValue } from "../config.js";
2
4
  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";
5
+ export { boundResult, BuiltinCalls, failureText, Mutex, NativeJournal, openTurn, placeSubmissions, recoveryNote, recoverySystemNote, recoveryUserTurn, restartEvent, resumeUnstartedCalls, toolKey, transcriptOf, } from "@parcha/agentrun-kernel/process";
4
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;
12
+ }
13
+ export declare function toolBridge(ctx: Parameters<typeof kernelToolBridge>[0], tools: Parameters<typeof kernelToolBridge>[1], options?: ToolBridgeOptions): ImageBridge;
5
14
  /** A child's line protocol: one JSON value per line out, lines in. */
6
15
  export interface LineChannel {
7
16
  send(line: unknown): boolean;
@@ -67,12 +76,30 @@ export interface SessionMachine {
67
76
  announcedExec?(): string | undefined;
68
77
  /** 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
78
  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
+ /** Told when the model proxy reads that the provider cut the turn's answer at its output limit, before Codex has the
82
+ * piece that carries the stop (its output tokens, when the answer said them): the harness ends the turn there. */
83
+ onCut?(listener: (stop: {
84
+ outputTokens?: number;
85
+ }) => void): void;
86
+ /** The harness opens a turn: the model proxy, which refuses answer requests once it has told the harness a turn's answer
87
+ * stopped, admits them again (ModelProxy.openTurn). */
88
+ openTurn?(): void;
70
89
  /** Given Codex's `config.toml` settings before the harness writes them, to set what the session's own options decide
71
90
  * and the harness does not (its web search, a key reserved from callers). */
72
91
  configure?(config: Record<string, TomlValue>): void;
73
92
  fsync(): Promise<void>;
74
93
  close(): Promise<void>;
75
94
  }
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
+ }
76
103
  /** What a harness's drive asks its machine factory for: the drive, the model route its proxy serves, and its deadline. */
77
104
  export interface AcquireMachineRequest {
78
105
  ctx: DriveContext;
@@ -93,35 +120,16 @@ export interface GatewayRoute {
93
120
  }
94
121
  /** Codex's one route: the Responses API. */
95
122
  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
123
  /** What the harness says about its model route; the machine's proxy serves it (machine.ts). */
110
124
  export interface GatewayHandlerOptions {
111
125
  routes: readonly GatewayRoute[];
112
126
  models: {
113
127
  model: string;
114
128
  };
115
- budget?: {
116
- turnUsd: number;
117
- sessionUsd: number;
118
- };
119
- ledger?: GatewayLedger;
120
129
  network?: string;
121
130
  credential: () => Promise<string | undefined> | string | undefined;
122
131
  target: string;
123
132
  track?: unknown;
124
- onCap?: (cap: "turnUsd" | "sessionUsd" | "concurrency") => void;
125
133
  log?: (message: string, fields?: Record<string, unknown>) => void;
126
134
  }
127
135
  export interface GatewayHandler {
@@ -1,4 +1,26 @@
1
- export { boundResult, BuiltinCalls, failureText, Mutex, NativeJournal, openTurn, placeSubmissions, recoveryNote, recoverySystemNote, recoveryUserTurn, restartEvent, toolBridge, toolKey, transcriptOf, } from "@parcha/agentrun-kernel/process";
1
+ // The process-harness names the copied Codex harness imports: the copied layer from @parcha/agentrun-kernel/process,
2
+ // and, written for AgentRun, the session machine's types (a local machine, machine.ts), its brand, the model route the
3
+ // harness describes for its model proxy (the policy), and model-step tracking (nothing to track locally).
4
+ import { toolBridge as kernelToolBridge } from "@parcha/agentrun-kernel/process";
5
+ export { boundResult, BuiltinCalls, failureText, Mutex, NativeJournal, openTurn, placeSubmissions, recoveryNote, recoverySystemNote, recoveryUserTurn, restartEvent, resumeUnstartedCalls, toolKey, transcriptOf, } from "@parcha/agentrun-kernel/process";
6
+ export function toolBridge(ctx, tools, options) {
7
+ const bridge = kernelToolBridge(ctx, tools, options);
8
+ const images = new Map();
9
+ return {
10
+ ...bridge,
11
+ call: async (name, args, callId, signal) => {
12
+ const result = await bridge.call(name, args, callId, signal);
13
+ if (callId && result.images?.length)
14
+ images.set(callId, result.images);
15
+ return result;
16
+ },
17
+ takeImages: (callId) => {
18
+ const taken = images.get(callId);
19
+ images.delete(callId);
20
+ return taken;
21
+ },
22
+ };
23
+ }
2
24
  const BRAND = Symbol.for("agentrun.codex.session-machine");
3
25
  /** Mark a machine as made by this package's factory. */
4
26
  export function brandMachine(machine) {
@@ -5,7 +5,8 @@ export declare function attachInDrive(ctx: DriveContext, acquire: AcquireMachine
5
5
  model?: GatewayHandler;
6
6
  deadline?: number;
7
7
  }): Promise<SessionMachine>;
8
- /** A local machine shows the model no notes, so there is nothing to acknowledge. */
8
+ /** A local machine's only note is one it makes again at every acquire (a Codex catalog it could not read, ../catalog.ts),
9
+ * so there is nothing to acknowledge: the harness shows it once per invocation. */
9
10
  export declare function acknowledgeInDrive(_ctx: DriveContext, _key?: string): Promise<void>;
10
11
  /** The pinned Codex binary, as the harness names it. */
11
12
  export interface PinnedCli {
@@ -2,7 +2,8 @@
2
2
  export async function attachInDrive(ctx, acquire, options = {}) {
3
3
  return acquire({ ctx, ...(options.model ? { model: options.model } : {}), ...(options.deadline === undefined ? {} : { deadline: options.deadline }) });
4
4
  }
5
- /** A local machine shows the model no notes, so there is nothing to acknowledge. */
5
+ /** A local machine's only note is one it makes again at every acquire (a Codex catalog it could not read, ../catalog.ts),
6
+ * so there is nothing to acknowledge: the harness shows it once per invocation. */
6
7
  export async function acknowledgeInDrive(_ctx, _key) { }
7
8
  export const CODEX_CLI = Object.freeze({ dir: "", bin: "codex" });
8
9
  /** The binary the harness being made runs: the one the adapter checked against the pins when it was made. */
package/dist/index.d.ts CHANGED
@@ -1,9 +1,13 @@
1
1
  export { CODEX_TOOL_OUTPUT_TOKENS, codexAdapter } from "./adapter.js";
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";
2
4
  /** The check the adapter runs on the host's skills when it is made: @parcha/agentrun-kernel' own, as the Claude adapter's. */
3
5
  export { skillProblems } from "@parcha/agentrun-kernel";
4
6
  export type { HostSkill } from "@parcha/agentrun-kernel";
5
7
  export type { CodexAdapterOptions, CodexProvider, CodexWebSearch } from "./adapter.js";
6
8
  export type { ChildCommand, ConfineChild } from "./host/machine.js";
7
- export { CODEX_VERSION, codexBinary } from "./binary.js";
9
+ export { CODEX_VERSION, codexBinary, codexTarget } from "./binary.js";
10
+ /** The shapes of a tool's schema Codex 0.164 drops or retypes (schema.ts): a host may refuse them sooner (an MCP grant, at its save). */
11
+ export { codexSchemaProblems } from "./schema.js";
8
12
  export { verifyCodex, verifyCodexBinary } from "./verify.js";
9
13
  export { CODEX_BINARY_SHA256, CODEX_INSTALL, CODEX_NPM_INTEGRITY, CodexNotInstalled, CodexPinMismatch } from "./versions.js";
package/dist/index.js CHANGED
@@ -1,6 +1,10 @@
1
1
  export { CODEX_TOOL_OUTPUT_TOKENS, codexAdapter } from "./adapter.js";
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";
2
4
  /** The check the adapter runs on the host's skills when it is made: @parcha/agentrun-kernel' own, as the Claude adapter's. */
3
5
  export { skillProblems } from "@parcha/agentrun-kernel";
4
- export { CODEX_VERSION, codexBinary } from "./binary.js";
6
+ export { CODEX_VERSION, codexBinary, codexTarget } from "./binary.js";
7
+ /** The shapes of a tool's schema Codex 0.164 drops or retypes (schema.ts): a host may refuse them sooner (an MCP grant, at its save). */
8
+ export { codexSchemaProblems } from "./schema.js";
5
9
  export { verifyCodex, verifyCodexBinary } from "./verify.js";
6
10
  export { CODEX_BINARY_SHA256, CODEX_INSTALL, CODEX_NPM_INTEGRITY, CodexNotInstalled, CodexPinMismatch } from "./versions.js";
package/dist/mcp.d.ts ADDED
@@ -0,0 +1,15 @@
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 ADDED
@@ -0,0 +1,74 @@
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
+ }
package/dist/rollout.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
2
2
  // From github.com/vercel-labs/durable-harness, packages/harness-codex/src/rollout.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
3
- // Changed by Parcha, patches: 004-names, 006-comments, 009-rollout-call-type
3
+ // Changed by Parcha, and AgentRun's own since the port from upstream froze on 2026-11-07.
4
4
  /**
5
5
  * Codex's rollout, as the run's log holds it. Pure functions, no Node
6
6
  * imports.
package/dist/scripts.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { DriveContext } from "@parcha/agentrun-kernel/kernel";
1
2
  /** The id Codex gives a host tool called from a code-mode script. */
2
3
  export declare const NESTED_CALL: RegExp;
3
4
  /** What the session is told when the proxy could not watch an answer to its end: the answer may carry an `exec` it did not see, so
@@ -54,6 +55,8 @@ export interface NestedFact {
54
55
  * safe tool's call that a crash cut off, which the note tells the model is safe to repeat. */
55
56
  told?: "completed" | "failed" | "interrupted" | "retryable" | "running";
56
57
  rollout?: RolloutNested;
58
+ /** The host parked the call for a person's approval (`parkedKey`'s record): it did not run, whatever its record says. */
59
+ parked?: true;
57
60
  }
58
61
  export type Settled = {
59
62
  kind: "completed";
@@ -63,8 +66,16 @@ export type Settled = {
63
66
  text: string;
64
67
  } | {
65
68
  kind: "interrupted";
69
+ } | {
70
+ kind: "parked";
66
71
  };
67
- /** What a nested call came to. The store's record first, the rollout's completion second: both complete and agreeing, or
72
+ /** The session's record that the host parked the call `callId` for a person's approval, so it did not run: what the call
73
+ * was answered (the host's waiting text) reads as its outcome, and is none. */
74
+ export declare const parkedKey: (callId: string) => string;
75
+ /** Records that the host parked `callId` (a host tool's or a remote MCP server's), before its answer is recorded: a parked
76
+ * call is never told as completed, after a crash either. */
77
+ export declare const markParked: (ctx: DriveContext, callId: string) => Promise<unknown>;
78
+ /** What a nested call came to. A call the host parked is `parked`, whatever else holds: it never ran. Else the store's record first, the rollout's completion second: both complete and agreeing, or
68
79
  * one of them, is that outcome; both complete and disagreeing, or a call that started and has no end in either, is
69
80
  * interrupted (its effect is unknown), and a failure the store marks interrupted is interrupted. They agree when the
70
81
  * rollout holds what the bridge handed Codex for the stored text: the store's text held to the host's bound
package/dist/scripts.js CHANGED
@@ -1,15 +1,3 @@
1
- // Which code-mode script a host tool's nested call belongs to. Written for AgentRun.
2
- //
3
- // A host tool a code-mode model's script calls arrives on the app-server's stream as a call under an id of Codex's own
4
- // (`exec-<uuid>`) that carries no parent, no cell and no `exec` id, and the rollout holds no line for it until after it is
5
- // answered. So the call is tied to the one script that can be running, and that is read from two places that cannot be
6
- // ahead of Codex:
7
- // - the rollout: an `exec` call line opens a script, and it stays open until an output says it finished: its own, or, when
8
- // that says "Script running with cell ID N" (it yielded and went on), the output of the `wait` that finishes cell N;
9
- // - the model proxy: the `exec` the latest answer carried, which it read before Codex had that part of the answer, so
10
- // before the `exec`'s line could be in the rollout.
11
- // The proxy offers no `exec` while a cell runs and no parallel calls, so one script is live at a time. A model that writes an
12
- // `exec` anyway makes two live, and then a nested call cannot be told from the other's.
13
1
  import { boundResult } from "./host/process.js";
14
2
  import { parseLine } from "./rollout.js";
15
3
  /** The id Codex gives a host tool called from a code-mode script. */
@@ -99,13 +87,21 @@ export function completedNested(lines) {
99
87
  }
100
88
  return out;
101
89
  }
102
- /** What a nested call came to. The store's record first, the rollout's completion second: both complete and agreeing, or
90
+ /** The session's record that the host parked the call `callId` for a person's approval, so it did not run: what the call
91
+ * was answered (the host's waiting text) reads as its outcome, and is none. */
92
+ export const parkedKey = (callId) => `parked:${callId}`;
93
+ /** Records that the host parked `callId` (a host tool's or a remote MCP server's), before its answer is recorded: a parked
94
+ * call is never told as completed, after a crash either. */
95
+ export const markParked = (ctx, callId) => ctx.effect(parkedKey(callId), { name: "parked", replay: "safe", input: null }, async () => true);
96
+ /** What a nested call came to. A call the host parked is `parked`, whatever else holds: it never ran. Else the store's record first, the rollout's completion second: both complete and agreeing, or
103
97
  * one of them, is that outcome; both complete and disagreeing, or a call that started and has no end in either, is
104
98
  * interrupted (its effect is unknown), and a failure the store marks interrupted is interrupted. They agree when the
105
99
  * rollout holds what the bridge handed Codex for the stored text: the store's text held to the host's bound
106
100
  * (`boundResult`), since the store keeps a result whole and Codex got its cut; or the stored text itself, as a session
107
101
  * written before that bound holds it in both records. */
108
102
  export function settle(fact) {
103
+ if (fact.parked)
104
+ return { kind: "parked" };
109
105
  const { store, rollout } = fact;
110
106
  const stored = store?.status === "completed" ? { kind: "completed", text: store.text ?? "" } : store?.status === "failed" && !store.interrupted ? { kind: "failed", text: store.text ?? "" } : undefined;
111
107
  const rolled = rollout ? { kind: rollout.ok ? "completed" : "failed", text: rollout.text } : undefined;
@@ -126,6 +122,8 @@ export function recoveryFacts(execs, ties, since, factOf) {
126
122
  }
127
123
  const describeCall = (fact, label) => {
128
124
  const settled = settle(fact);
125
+ if (settled.kind === "parked")
126
+ return `${label} was waiting for a person's approval and did not run; it was not run again.`;
129
127
  if (settled.kind === "completed")
130
128
  return `${label} completed: ${quoted(settled.text)}. Its effect is done; it was not run again.`;
131
129
  if (settled.kind === "failed")
@@ -0,0 +1,7 @@
1
+ /** An image as a host tool returns it. */
2
+ export type ToolImageShape = {
3
+ readonly mimeType?: unknown;
4
+ readonly data?: unknown;
5
+ };
6
+ /** Why a tool's images can't be sent, naming the tool and the image, or undefined. */
7
+ export declare function toolImageProblems(tool: string, images: readonly ToolImageShape[]): string | undefined;
@@ -0,0 +1,18 @@
1
+ // A host tool's images, checked before Codex's model is sent them, by the rule claude-agent's adapter holds them to
2
+ // (toolImageProblems there): a type the model takes, written as image/<subtype> with no parameters, and base64. Pure and
3
+ // self-contained, so it can move to the kernel's tool answer unchanged.
4
+ /** image/<subtype>: no parameter (no ';'), nothing else. */
5
+ const IMAGE_TYPE = /^image\/[a-z0-9.+-]+$/i;
6
+ const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
7
+ /** Why a tool's images can't be sent, naming the tool and the image, or undefined. */
8
+ export function toolImageProblems(tool, images) {
9
+ for (const [i, image] of images.entries()) {
10
+ const at = `the tool ${tool}'s image ${i + 1}`;
11
+ const type = image?.mimeType;
12
+ if (typeof type !== "string" || !IMAGE_TYPE.test(type))
13
+ return `${at} is ${String(type).slice(0, 40)}, not an image type the model takes (image/<type>, no parameters)`;
14
+ if (typeof image.data !== "string" || !BASE64.test(image.data))
15
+ return `${at} is not base64`;
16
+ }
17
+ return undefined;
18
+ }
@@ -0,0 +1,17 @@
1
+ /** A call Codex made and never got an output for: its own call id, the host's tool name and the arguments the model gave. */
2
+ export type DanglingCall = {
3
+ readonly callId: string;
4
+ readonly tool: string;
5
+ readonly args: unknown;
6
+ };
7
+ /** The bridge's answer for a call: its text, and whether it failed (or was interrupted or refused). */
8
+ export type CallOutcome = {
9
+ readonly text: string;
10
+ readonly isError: boolean;
11
+ };
12
+ /** The host's calls Codex made and never got an output for, in the order it made them. */
13
+ export declare function danglingCalls(lines: readonly string[]): DanglingCall[];
14
+ /** `lines` with the dangling call `callId` given `outcome`: one `function_call_output` line after the last, its output the
15
+ * bridge's text (Codex's rollout keeps no failure flag for a function's output: a failure or refusal is in its words).
16
+ * Throws when the call does not dangle: an answered call is never rewritten. */
17
+ export declare function settleCall(lines: readonly string[], callId: string, outcome: CallOutcome, now?: number): string[];
@@ -0,0 +1,54 @@
1
+ // Codex's transcript rewrite for a resumed run. Written for AgentRun.
2
+ //
3
+ // Codex's transcript is its thread's rollout, mirrored line by line into the session's records (rollout.ts) and written
4
+ // back into an empty CODEX_HOME when its next app-server starts, which resumes the thread from it. A call of the host's
5
+ // tools that Codex made and never got an output for is a dangling call. The resume's shared decision settles each one
6
+ // through the kernel's tool bridge first, under the call's own id: a call with no intent goes gate, intent, run, result;
7
+ // a call with an intent is never run again. This file only writes the outcome the bridge answered into the rollout, as
8
+ // Codex records a call's output itself: a `function_call_output` line, after the last; nothing before it changes. Codex
9
+ // then resumes the thread from the rewritten rollout, and the call reads as answered.
10
+ //
11
+ // Only the host's own tools: the session's dynamic tools, which the thread's `session_meta` lists. Codex's own calls
12
+ // (code mode's `exec`, its `apply_patch`, a built-in) never went through the bridge, and the harness's own recovery
13
+ // answers those.
14
+ import { parseLine } from './rollout.js';
15
+ const isPlain = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
16
+ /** The host's tool names the thread was started with (its `session_meta`'s dynamic tools); none with no `session_meta` first. */
17
+ function hostTools(lines) {
18
+ const first = lines[0] === undefined ? undefined : parseLine(lines[0]);
19
+ const tools = first?.type === 'session_meta' ? first.payload?.dynamic_tools : undefined;
20
+ return new Set(Array.isArray(tools) ? tools.flatMap((tool) => (isPlain(tool) && typeof tool.name === 'string' ? [tool.name] : [])) : []);
21
+ }
22
+ /** The host's calls Codex made and never got an output for, in the order it made them. */
23
+ export function danglingCalls(lines) {
24
+ const tools = hostTools(lines);
25
+ const calls = new Map();
26
+ for (const raw of lines) {
27
+ const line = parseLine(raw);
28
+ const p = line?.type === 'response_item' ? line.payload : undefined;
29
+ if (!p || typeof p.call_id !== 'string')
30
+ continue;
31
+ if (p.type === 'function_call' && typeof p.name === 'string' && tools.has(p.name)) {
32
+ let args = {};
33
+ try {
34
+ args = typeof p.arguments === 'string' && p.arguments ? JSON.parse(p.arguments) : {};
35
+ }
36
+ catch {
37
+ args = {};
38
+ }
39
+ calls.set(p.call_id, { callId: p.call_id, tool: p.name, args });
40
+ }
41
+ else if (p.type === 'function_call_output')
42
+ calls.delete(p.call_id);
43
+ }
44
+ return [...calls.values()];
45
+ }
46
+ /** `lines` with the dangling call `callId` given `outcome`: one `function_call_output` line after the last, its output the
47
+ * bridge's text (Codex's rollout keeps no failure flag for a function's output: a failure or refusal is in its words).
48
+ * Throws when the call does not dangle: an answered call is never rewritten. */
49
+ export function settleCall(lines, callId, outcome, now = Date.now()) {
50
+ if (!danglingCalls(lines).some((call) => call.callId === callId))
51
+ throw new Error(`Codex's rollout has no call ${callId} of the host's that it made and never got an output for`);
52
+ const output = JSON.stringify({ timestamp: new Date(now).toISOString(), type: 'response_item', payload: { type: 'function_call_output', call_id: callId, output: outcome.text } });
53
+ return [...lines, output];
54
+ }