@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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,40 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## 0.1.0-beta.32 (2026-11-10)
6
+
7
+ - The code copied from the upstream durable harness is now AgentRun's own: the port froze, and the pristine upstream copies, the named patches, the import tables, `scripts/port-durable-harness.mjs` and `npm run verify:port` are gone. `vendor/durable-harness/UPSTREAM.json` still records where each copy came from, and each copy keeps its header and NOTICE its attribution. With it go the kernel's paths that never run:
8
+ - `AgentAdapter.version` and `AdapterCapabilities.fork` (no adapter forks; a node that asks for `context: "fork"` is refused as before).
9
+ - `DriveContext.config`, and `requires`/`needs` on a host tool and an effect's options; `kernel/types.ts` is no longer pinned to upstream's types.
10
+ - The Codex harness's `codex.spend` ledger and its dollar caps (`sandbox({ budget })`, `GatewayLedger`, the gateway handler's `budget`, `ledger` and `onCap`), which never fired, and its table of removed options.
11
+ - `Box`, `BoxSpec`, `BoxedChild`, `Isolation` and `boxSlot` (`@parcha/agentrun-kernel/host`), which nothing implemented or used.
12
+ - The model proxy's parts only tests used (`inputTokensMaxOf`, `matchRoute`, `parseStrict`, `reportedCostOf`) move to `@parcha/agentrun-kernel/testing`; `providerIdsOf` and `MCP_ROUTE_VERSIONS` leave the host API.
13
+ - The box egress proxy (`startEgressProxy`, `parseAllow`, the address table) moves into agentrun-serve, its one user.
14
+
15
+ Fixed: a run on Claude Code or Codex now closes its harness session when its process lets the run go, as the adapter's `close()` contract asks; before, serve never called it. On today's adapters an idle session's `close()` stops no process of its own (each drive already ends its CLI or app-server when its turn ends), so this keeps the contract for an adapter whose session holds one. For it, pi-durable-disk's `DoorHook` has a required `close()`: the door's stop calls it once, busy or idle (on a drain after the abort, on a fence alongside the kill, within the abort's bound). A hook with nothing of its own to stop resolves at once. `DoorHook` also has a required `harness` id: a `close()` that throws, rejects or overruns its bound is logged with it ("door close failed" / "door close timed out") through `serveRun`'s new optional `log`, which the run CLI passes its log line to. A harness session that lands after the door's close (a stop while it was still opening) is closed too, once.
16
+ - Each adapter states what its harness is, and serve reads that instead of the harness's name. `@parcha/agentrun-harness-claude/facts` and `@parcha/agentrun-harness-codex/facts` export `facts` (the kernel's `AdapterFacts`): the API its proxy speaks (`wire`), whether it takes a message mid-turn, the memory one run reserves, its thinking levels, its own web search (`native` or `live`), whether its model is its own, how it names a model, its install line and pins, the schemas its MCP client drops, whether it binds the session's MCP servers, an MCP tool alias, and its proxy policy. Serve keeps one table from a harness id to its entry and one `providerFor(wire, env, model)`: opencode and codex take one route because both speak the Responses API, and the gateway base rule is written once, so pi's runs take it too. Nothing else changes for a run, a capability or a refusal's words.
17
+ Upgrading: an AGENT_MODEL_BASE_URL that is plain http to a non-loopback host, names a user, or has a query, fragment or dot segment is now refused on pi, as on Codex and OpenCode (a backslash or whitespace too); the refusal names the setting, and the gateway's key is never sent there. `startServe`'s `fauxHarness` option is gone; a test passes `harnessTable`, a module of harness table entries (`entries(builtins)`), in its place. `AGENTRUN_SERVE_FAUX_HARNESS` is no longer read; `AGENTRUN_HARNESS_TABLE` is set from `harnessTable` alone and dropped from the server's own environment.
18
+ - Agents on codex call a saved MCP server's tools: grant `mcp:<server>/<tool>` in `definition.tools`, as on pi and claude-agent, and `features.mcp_client.harnesses` now lists codex. The harness writes each granted server in Codex's `mcp_servers` itself, at the session's model proxy (`/mcp/<server>`, behind the session key), with only the granted tools enabled and approve mode, so Codex never holds the credential. The proxy records each call in the session before it sends it, by Codex's own call id, so a call a crash cut off is answered interrupted and never sent again. A server that does not start fails the turn (`required`). The Codex proxy policy admits the granted tools in the `mcp__<server>` namespace Codex 0.164 sends them in, and the timeline reads `<server> · <tool>`. The kernel's model proxy mounts `/mcp/<server>` itself, once for every harness with an MCP client of its own, from the session's MCP and the client fact its adapter declares (`capabilities().mcpClient`, the `_meta` key of a call's id: `claudecode/toolUseId` on Claude Code, `callId` on Codex); `ModelProxyOptions.mcp` takes `{ session, client }` in place of a handler.
19
+ - Codex installs itself on first use, as Claude Code does, through one table of the harnesses that install on first use (`src/harness-install.ts`). The first run on codex, or the first agent saved on it, installs the version AgentRun pins (`@openai/codex@0.164.0`, with this platform's binary package) from npm into `<data>/harnesses/codex`; Claude Code's install moves to `<data>/harnesses/claude-agent`: an install an earlier build left at the top of `<data>/harnesses` (its package.json, lock and node_modules, read-only) is removed before the first install, with one log line, and Claude Code installs again; a `harnesses` directory that holds anything else is left as it is. Each is pinned by a lock the server ships (`harnesses/codex/`, every package by sha512) and installs the same way: `npm ci --ignore-scripts --include=optional` into a fresh directory, checked there (for Codex, that its platform package and binary landed, whatever the person's npm config omits), renamed into place and made read-only; a server that stops mid-install stops its npm. A codex run waits for the install and shows `Installing Codex (first use)…` while it does; until it is installed, `GET /v2/capabilities` lists codex with `installs: "on_first_use"`. Codex runs only the binary in that tree, never a copy beside the server; when npm fails, the run's error names the command that installs it by hand. Codex's npx hint (`-p @openai/codex@0.164.0`) is gone. The server image no longer carries a Codex CLI: its build removes `@openai/codex`, its platform packages and its bin link, and `docker/image-check.sh` refuses an image that holds any of them. The hint that restarts AgentRun with OpenCode keeps how it was started: npx's `-y`, `--port` and `--no-open`. `node scripts/harness-locks.mjs` (formerly `claude-lock.mjs`) makes both locks again. `@parcha/agentrun-harness-codex` takes the binary a host installed (`binary: { path, packageVersion }`, checked against the pins) and exports `codexTarget()`.
20
+ Upgrading: Codex installs itself on first use, and the server image no longer carries a Codex CLI. Claude Code installs again on its first run, under `<data>/harnesses/claude-agent`; an earlier install at the top of `<data>/harnesses` is removed.
21
+ - The last data serve kept by a harness's name moves to the adapters' facts: a CLI's own tools and the table tool each one is (`AdapterFacts.nativeTools`, stated by claude-agent and codex), the harnesses each model key runs (from their wires' vendors; OpenRouter's key runs every one) and OpenRouter's default model for each wire's vendor. Nothing changes for a run, a capability or a refusal's words.
22
+ - A run near its spend cap is told once to finish: when what is left is under three times its typical request (the median of the run's own model's priced requests after the first), the model's next request carries "About $X left of this run's budget: finish now with your answer.", and the Timeline shows it as the server's row. On pi it goes into that request's context; on claude-agent, codex and opencode the model proxy adds it to the request's body after everything the CLI sent, so the cached prefix is unchanged. No message is queued, so nothing runs after the model's answer. Once per cap, across restarts; a raise re-arms it.
23
+ - With the built-ins off, a code-mode model (luna, sol) is no longer offered Codex's own `apply_patch`. Code mode listed it as a nested tool of `exec` with no environment to run it, so every call failed with "No usable execution environment is available". The harness now hands Codex its own bundled model catalog with `apply_patch_tool_type` set to null (`model_catalog_json`). `model_catalog_json` is now reserved: an app's `config` may not set it. With `builtins: true`, `apply_patch` stays. If the binary gives no catalog, the session runs on Codex's own and says so: the sandbox note the model gets with its first message reads "Codex's own apply_patch stays listed: …" with the reason.
24
+
25
+ A host tool's images now reach a Codex model as images. The tool's answer to Codex carries each one as an `inputImage` item (a data: URL) after its text, where before only the text went.
26
+ - On Codex, a call that returned images and completed just before the session stopped, before Codex recorded its answer, is now repaired as its text plus a line saying how many images it returned, which are not shown again. Before, the model got the images' base64 as JSON text.
27
+ - A host tool's images on Codex are checked before the model is sent them, by the rule claude-agent holds them to: a type written image/<subtype> with no parameters, and base64. One that can't be sent is the call's error, naming the tool and the image, not a request refused later. In code mode, a script's nested tool call sends no image: Codex hands a script an image as its data: URL inside the result's text, so a script that printed it sent the model the base64 as words. The script now gets the tool's text and a line saying how many images were not sent. When Codex's bundled catalog can't be read, the run's note names the binary by its file name only, with no host path and none of the session's own directories.
28
+ A tool call whose answer to Codex fails to build no longer leaves its images held for the rest of the session.
29
+ - Every deny the model reads now says plainly that the call never left: "It was not run: nothing was sent and nothing was charged." It covers a tool set to deny, an ask refused because no one can approve, the owner's deny of a parked call, and a person's declining message. After a deny, a model no longer tells the person it can't confirm whether a charge was made.
30
+
31
+ An approved call that ran before a crash keeps its saved result when its tool is set to deny before the run reopens: the model gets that result, never "nothing was charged", and it is booked once. A call cut after it started but before its outcome is denied with no claim either way ("It had started before the deny, and whether it took effect is not known.").
32
+
33
+ The same holds for a replay-safe host tool on claude-agent and codex (web_fetch, web_search) that the kernel runs again after a crash cut its first attempt: if it is now denied, or refused for want of an approver, the words say it had started and whether it took effect is not known, never that nothing was charged. If it now asks and PARKS, the request keeps that it is a replay in the run's store (`replayed` on the approval request), so the owner's Deny or a declining message says the same, after a restart too. Host tools now hear the kernel's attempt (`HostTool.call`'s `attempt`). On pi, which reruns a cut replay-safe call with the same call id and no sign of a rerun, the gate keeps its own mark of each replay-safe call it let through that can bill (web_fetch, web_search: an `agentrun.gate_passed` entry, written before the tool runs), and reads its marks before the run resumes, on an agentic run and a workflow's model node alike, so a rerun of one is treated the same way.
34
+ - On codex and claude-agent, a tool call (a remote MCP server's included) has its Timeline row while it runs, from the moment the session records its intent, and a call a crash cut off gets its result row at the next open from the session's record of it: "interrupted ... it may or may not have taken effect" for one that is not safe to repeat. Before, a running call had no row, and a cut call never got one.
35
+ - On codex, a code-mode script's call the host parked for a person's approval (an MCP tool's or a host tool's) is never told to the model as completed: the cut script's output says it "was waiting for a person's approval and did not run". The host marks such an answer `parked` (`HostTool` and `McpCallResult`), which the MCP door never sends the harness's client.
36
+ - A learned workflow's model nodes, its `llm` call nodes and a call node's native search, on claude-agent, codex and opencode, are requests on the run's one route: the session's own model proxy, under a side key the proxy mints for the host (`ModelProxy.sideKey`, `AdapterSession.port`). They get the harness's own body rules, provider, key, price and booking, labelled `learned_workflow` on the session's records (`runner.request.host`), under the run's one cap, as a side call: the spend cap's wrap-up never counts it toward a typical request, and it never takes the wrap-up's note. They reach an operator's gateway at ANTHROPIC_BASE_URL or AGENT_MODEL_BASE_URL as the harness's requests do, and never go around it, so a run there is offered its learned workflows (the learning pin's `workflows_off` is gone). A side request is never the turn's answer request: a content-filter stop on it does not halt the turn.
37
+ Upgrading: Finish or cancel capped runs that used learned workflows before upgrading: their earlier learned-workflow spend is not counted against the cap after it. A pin written before this keeps the workflows it left out, and its `workflows_off` is no longer read.
38
+
5
39
  ## 0.1.0-beta.30 (2026-11-05)
6
40
 
7
41
  - On codex, a content-filter stop whose final Responses event is longer than the model proxy keeps of it now ends the turn
package/README.md CHANGED
@@ -44,6 +44,11 @@ const runNode = createHarnessRunner(
44
44
  Each search a response ran (`tool_usage.web_search.num_requests`) is added to its price at OpenAI's $0.01 a call; a
45
45
  model with no known search price books an unknown cost. A request that offers web search has no input bound, so a cap
46
46
  treats its input as unknown.
47
+ - **Remote MCP servers, when granted.** A session given `spec.mcp` (a host's MCP gateway) writes each server in Codex's
48
+ `mcp_servers` at the proxy's `/mcp/<server>`, with the proxy key as Codex's bearer, only the granted tools enabled,
49
+ approve mode and `required = true`; the proxy admits those tools in the `mcp__<server>` namespace Codex sends them in.
50
+ Codex sends a call without waiting for the session, so the proxy holds it until its line (a script's nested call: its
51
+ script's) is in the log, records its intent and only then sends it, through the host's gateway (`src/mcp.ts`).
47
52
  - **A private machine.** A session runs in its own directories. Its working directory is the host's workspace when the
48
53
  host names one (`io.cwd`, where the host's file tools write, an untrusted project to Codex), and otherwise an empty
49
54
  directory of the session's. Codex keeps nothing there, and takes no instructions from an `AGENTS.md` in it
package/dist/adapter.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type HostSkill } from "@parcha/agentrun-kernel";
2
- import type { AgentAdapter } from "@parcha/agentrun-kernel";
2
+ import type { AgentAdapter, HostTool } from "@parcha/agentrun-kernel";
3
+ import { type HostTool as KernelTool } from "@parcha/agentrun-kernel/kernel";
3
4
  import { NativeJournal } from "@parcha/agentrun-kernel/process";
4
5
  import { type ConfineChild } from "./host/machine.js";
5
6
  import { type ModelProxyOptions } from "@parcha/agentrun-kernel/host";
@@ -54,9 +55,20 @@ export interface CodexAdapterOptions {
54
55
  args?: string[];
55
56
  env?: Record<string, string>;
56
57
  };
58
+ /** The Codex binary to run, as the host installed it (its path, and its platform package's version): checked against
59
+ * the pins as one found here is. Default: found beside this package (findCodex). */
60
+ binary?: {
61
+ path: string;
62
+ packageVersion?: string;
63
+ };
57
64
  /** For tests: the fetch the model proxy forwards with. */
58
65
  fetch?: typeof fetch;
59
66
  }
67
+ /** The kernel's tool for a host tool: the same name, schema and replay policy; a host's error result is the call's failure.
68
+ * The call runs as a kernel effect, whose intent is durable in the session's records before `execute` is entered, so a
69
+ * crash inside a `never` tool is always reported, never repeated. The copied harness's wait for Codex's own `function_call`
70
+ * line before it runs such a tool is a second guard (the transcript Codex resumes from), not the one that protects it. */
71
+ export declare function kernelTool(tool: HostTool): KernelTool;
60
72
  /**
61
73
  * The mirrored rollout the next drive resumes Codex from, by the harness's own rule (harness.ts, `resume`: the last
62
74
  * thread, its first line `session_meta`, its path the one the harness derives); none when it would start a new thread.
package/dist/adapter.js CHANGED
@@ -9,20 +9,23 @@
9
9
  // The host's skills (`skills`) are the only skills Codex lists to the model: written into the session's CODEX_HOME at the
10
10
  // start of every drive, where Codex finds a user's skills even in a turn with no environment, and Codex's own bundled
11
11
  // skills turned off. With no shell, the model reads a skill's files with `read_skill_file`.
12
- import { createHash, randomUUID } from "node:crypto";
12
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
13
13
  import { join } from "node:path";
14
14
  import { HOST_RESULT_MAX_CHARS, READ_SKILL_FILE, readSkillFileTool, skillProblems, toolSchemaProblems } from "@parcha/agentrun-kernel";
15
15
  import { abortedOutcome, openDrive, SessionHalt } from "@parcha/agentrun-kernel/kernel";
16
16
  import { pendingSubmissions } from "@parcha/agentrun-kernel/kernel";
17
17
  import { NativeJournal, recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
18
- import { CODEX_VERSION } from "./binary.js";
18
+ import { CODEX_MCP_CLIENT } from "./mcp.js";
19
19
  import { codexSchemaProblems, describedDescription } from "./schema.js";
20
+ import { markParked } from "./scripts.js";
20
21
  import { withCheckedBinary } from "./host/sandbox.js";
21
22
  import { verifyCodex } from "./verify.js";
22
23
  import { codexHarness, owedSubmissions } from "./harness.js";
23
24
  import { isRolloutPath, isSessionMeta, rolloutStream, summarizeRollout, THREAD_STREAM } from "./rollout.js";
24
25
  import { localMachine, sessionDir } from "./host/machine.js";
25
- import { serialWriter } from "@parcha/agentrun-kernel/host";
26
+ import { serialWriter, startModelProxy } from "@parcha/agentrun-kernel/host";
27
+ import { codexPolicy, withWebSearches } from "./host/policy.js";
28
+ import { toolImageProblems } from "./tool-images.js";
26
29
  /** A name app-server accepts for a dynamic tool. */
27
30
  const TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;
28
31
  /**
@@ -37,7 +40,7 @@ export const CODEX_TOOL_OUTPUT_TOKENS = Math.ceil((HOST_RESULT_MAX_CHARS * 3) /
37
40
  * The call runs as a kernel effect, whose intent is durable in the session's records before `execute` is entered, so a
38
41
  * crash inside a `never` tool is always reported, never repeated. The copied harness's wait for Codex's own `function_call`
39
42
  * line before it runs such a tool is a second guard (the transcript Codex resumes from), not the one that protects it. */
40
- function kernelTool(tool) {
43
+ export function kernelTool(tool) {
41
44
  return {
42
45
  name: tool.name,
43
46
  // Codex strips some keywords from the schema its model is given: they are said in plain words in the description
@@ -48,10 +51,22 @@ function kernelTool(tool) {
48
51
  async execute(input, io) {
49
52
  // The effect's step is `tool:<Codex call id>#<attempt>`: the host sees Codex's call id.
50
53
  const callId = (io.stepId ?? "").replace(/^tool:/, "").replace(/#\d+$/, "");
51
- const result = await tool.call(input, { callId, signal: io.signal });
54
+ // The step's attempt: above 0 when a crash cut an earlier attempt and the kernel runs the call again.
55
+ const attempt = Number(/#(\d+)$/.exec(io.stepId ?? "")?.[1] ?? 0);
56
+ const result = await tool.call(input, { callId, signal: io.signal, attempt });
57
+ // A call the host parked for a person's approval did not run: recorded so before its answer, the waiting text.
58
+ if (result.parked)
59
+ await markParked(io.ctx, callId);
52
60
  if (result.isError)
53
61
  throw new Error(result.text);
54
- return result.text;
62
+ if (!result.images?.length)
63
+ return result.text;
64
+ // An image the model can't be sent is the call's error, by the tool's name and the image, not a request refused later.
65
+ const wrong = toolImageProblems(tool.name, result.images);
66
+ if (wrong)
67
+ throw new Error(wrong);
68
+ // With its images, recorded with the outcome: the answer to Codex carries them after the text (code-mode.ts withImages).
69
+ return { text: result.text, images: result.images.map((image) => ({ mimeType: image.mimeType, data: image.data })) };
55
70
  },
56
71
  };
57
72
  }
@@ -96,7 +111,7 @@ export function codexAdapter(options) {
96
111
  const seed = skills.length ? skillsSeed(skills) : undefined;
97
112
  // The binary is checked once, here, against the pins: a mismatch or a missing binary is the host's to report, before
98
113
  // any run starts (CodexPinMismatch, CodexNotInstalled). A test's stand-in runs no Codex.
99
- const checked = options.standIn ? undefined : verifyCodex().path;
114
+ const checked = options.standIn ? undefined : verifyCodex(options.binary).path;
100
115
  const modelFor = (spec) => {
101
116
  if (typeof options.model === "string")
102
117
  return options.model;
@@ -104,8 +119,7 @@ export function codexAdapter(options) {
104
119
  };
105
120
  return {
106
121
  id: "codex",
107
- version: CODEX_VERSION,
108
- capabilities: () => ({ fork: false }),
122
+ capabilities: () => ({ mcpClient: CODEX_MCP_CLIENT }),
109
123
  check(spec) {
110
124
  const problems = [];
111
125
  if (spec.context === "fork")
@@ -149,6 +163,8 @@ export function codexAdapter(options) {
149
163
  const effort = spec.effort ?? spec.thinking;
150
164
  const harnessOptions = {
151
165
  tools: tools.map(kernelTool),
166
+ // The host's gate, asked about each host-tool call before its intent is written.
167
+ ...(io.gate ? { gate: (call) => io.gate(call) } : {}),
152
168
  builtins: false,
153
169
  // Codex's bundled skills (imagegen, skill-installer, ...), which it writes under `$CODEX_HOME/skills/.system` at every
154
170
  // start, are off in every session, skills or not: the model is shown the host's skills and no others.
@@ -173,7 +189,12 @@ export function codexAdapter(options) {
173
189
  ...(io.cwd ? { cwd: io.cwd } : {}),
174
190
  ...(options.confine ? { confine: options.confine } : {}),
175
191
  ...(seed ? { seed } : {}),
192
+ // The built-ins are off: Codex's own apply_patch, with no environment to run in, is offered to no model
193
+ // (catalog.ts). A stand-in runs no Codex, so it has no catalog to read.
194
+ ...(checked !== undefined ? { catalog: { command: checked, ...(options.log ? { log: options.log } : {}) } } : {}),
176
195
  ...(options.webSearch ? { webSearch: options.webSearch } : {}),
196
+ // A granted MCP server's tools: Codex's own MCP client calls them at the proxy (mcp.ts).
197
+ ...(spec.mcp?.servers.length ? { mcp: spec.mcp } : {}),
177
198
  proxy: {
178
199
  hooks: io.models,
179
200
  tools: tools.map((t) => t.name),
@@ -210,9 +231,14 @@ export function codexAdapter(options) {
210
231
  state = "idle";
211
232
  running = (async () => {
212
233
  let outcome;
234
+ // A turn whose answer the model cut at its output limit says so on its turn_end: stopReason "length", with the cut
235
+ // answer's output tokens when the provider said them.
236
+ let stop = {};
213
237
  try {
214
238
  await harness.drive(current);
215
239
  const ended = turnsIn(current).slice(before).at(-1)?.data;
240
+ if (ended?.stopReason === "length")
241
+ stop = { stopReason: "length", ...(typeof ended.outputTokens === "number" ? { outputTokens: ended.outputTokens } : {}) };
216
242
  outcome = ended?.status ? { status: ended.status, ...(ended.error ? { error: ended.error } : {}) } : { status: "failed", error: "the turn ended with no outcome in the session's records" };
217
243
  }
218
244
  catch (error) {
@@ -225,7 +251,7 @@ export function codexAdapter(options) {
225
251
  if (current.signal.aborted)
226
252
  state = holdsTurn(current.state()) ? "open_turn" : "idle";
227
253
  }
228
- io.onEvent({ type: "turn_end", status: outcome.status });
254
+ io.onEvent({ type: "turn_end", status: outcome.status, ...stop });
229
255
  return outcome;
230
256
  })();
231
257
  return running;
@@ -240,6 +266,34 @@ export function codexAdapter(options) {
240
266
  if (drive.signal.aborted && !io.signal.aborted)
241
267
  drive = await open();
242
268
  };
269
+ // The session's host port (AdapterSession.port): the host's own requests beside Codex's (a learned workflow's node)
270
+ // on the session's route, built from the drive proxy's own pieces (the same policy, origin, credential, price and the
271
+ // session's booking, io.models), but on a listener the session holds: a drive's machine closes its proxy when the
272
+ // drive ends (a park ends the turn; a restart opens none), and an approved call runs before any turn. It serves side
273
+ // keys only: Codex never holds its key, and the policy's exec watch (announce) never sees these requests. Its policy
274
+ // object is its own, as a side call's should be. Closed with the session, or when the host lets the session go.
275
+ // Started once the session's drive is open, the last step that can fail: an open that fails leaves no listener.
276
+ const search = options.webSearch === "live";
277
+ const hostPort = await startModelProxy({
278
+ policy: codexPolicy({ model: modelFor(spec), tools: [], ...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}), ...(search ? { webSearch: "live" } : {}) }),
279
+ hooks: io.models,
280
+ model: modelFor(spec),
281
+ origin: options.provider.origin,
282
+ credential: async () => (await options.provider.credential()) ?? "",
283
+ ...(options.price ? { price: search ? withWebSearches(options.price) : options.price } : {}),
284
+ ...(options.log ? { log: options.log } : {}),
285
+ ...(options.fetch ? { fetch: options.fetch } : {}),
286
+ }, randomBytes(32).toString("base64url"));
287
+ let hostClosed = false;
288
+ const closeHost = async () => {
289
+ if (hostClosed)
290
+ return;
291
+ hostClosed = true;
292
+ await hostPort.close().catch(() => { });
293
+ };
294
+ io.signal.addEventListener("abort", () => void closeHost(), { once: true });
295
+ if (io.signal.aborted)
296
+ await closeHost();
243
297
  return {
244
298
  get state() { return state; },
245
299
  async send(text) {
@@ -288,7 +342,11 @@ export function codexAdapter(options) {
288
342
  closed = true;
289
343
  drive.halt?.(new SessionHalt("closed"));
290
344
  await running?.catch(() => { });
345
+ await closeHost();
291
346
  },
347
+ // The session's one model route, for the host's own request beside Codex's: the session's host port, which never
348
+ // restarts once closed.
349
+ port: (label) => (closed || hostClosed ? undefined : { url: hostPort.url, key: hostPort.sideKey(label), model: modelFor(spec), api: "openai-responses" }),
292
350
  };
293
351
  },
294
352
  };
package/dist/binary.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/binary.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
3
- // Changed by Parcha, patches: 003-pinned-binary, 006-comments
3
+ // Changed by Parcha, and AgentRun's own since the port from upstream froze on 2026-11-07.
4
4
  import { existsSync, readFileSync } from 'node:fs';
5
5
  import { createRequire } from 'node:module';
6
6
  import { dirname, join } from 'node:path';
@@ -0,0 +1,35 @@
1
+ import type { MachineSpawn, SessionProcess } from './host/process.js';
2
+ /** The catalog's file in `CODEX_HOME`. */
3
+ export declare const MODEL_CATALOG_FILE = "model-catalog.json";
4
+ /**
5
+ * Codex's bundled model catalog with `apply_patch_tool_type` null on every
6
+ * model, every other field as Codex ships it; undefined when the text is not
7
+ * a catalog (an object whose `models` is a non-empty list of objects, each
8
+ * with a `slug`).
9
+ */
10
+ export declare function withoutApplyPatch(bundled: string): string | undefined;
11
+ /** The binary a session runs: its command and the arguments before Codex's own. */
12
+ export interface CodexCommand {
13
+ command: string;
14
+ args?: readonly string[];
15
+ /** Told when the catalog can't be read. */
16
+ log?: (message: string, fields?: Record<string, unknown>) => void;
17
+ }
18
+ /**
19
+ * The catalog without apply_patch for `codex`, read once per binary with
20
+ * `spawn` (`codex debug models --bundled`, its CODEX_HOME `dirs.own`, a
21
+ * directory of its own): its `bytes`, or `why` it can't be read, never
22
+ * silence. The session then runs on Codex's own catalog, apply_patch listed;
23
+ * a failure is not remembered, so the next drive tries again.
24
+ */
25
+ export declare function patchlessCatalog(spawn: (options: MachineSpawn) => SessionProcess | Promise<SessionProcess>, codex: CodexCommand, dirs: {
26
+ home: string;
27
+ tmp: string;
28
+ own: string;
29
+ }, signal?: AbortSignal): Promise<{
30
+ bytes: Uint8Array;
31
+ why?: undefined;
32
+ } | {
33
+ bytes?: undefined;
34
+ why: string;
35
+ }>;
@@ -0,0 +1,104 @@
1
+ // Codex's own apply_patch, off with the built-ins. Written for AgentRun.
2
+ //
3
+ // With the built-ins off, code mode (`code_mode_host`) still lists Codex's `apply_patch` as a nested tool of `exec`, though it
4
+ // has no environment to run in: every call fails "No usable execution environment is available". Codex 0.164 has no feature
5
+ // that removes it (`apply_patch_freeform` is removed); its model catalog's `apply_patch_tool_type` does. So the session's
6
+ // machine (host/machine.ts) reads Codex's own bundled catalog from the binary the session runs (`codex debug models --bundled`),
7
+ // sets that one field null on every model, keeps it in CODEX_HOME beside the seed and names it in Codex's config
8
+ // (`model_catalog_json`, a key an app may not set: config.ts). With the built-ins on, apply_patch runs through the shell and
9
+ // stays.
10
+ import { basename } from 'node:path';
11
+ /** The catalog's file in `CODEX_HOME`. */
12
+ export const MODEL_CATALOG_FILE = 'model-catalog.json';
13
+ /**
14
+ * Codex's bundled model catalog with `apply_patch_tool_type` null on every
15
+ * model, every other field as Codex ships it; undefined when the text is not
16
+ * a catalog (an object whose `models` is a non-empty list of objects, each
17
+ * with a `slug`).
18
+ */
19
+ export function withoutApplyPatch(bundled) {
20
+ let catalog;
21
+ try {
22
+ catalog = JSON.parse(bundled);
23
+ }
24
+ catch {
25
+ return undefined;
26
+ }
27
+ const isObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
28
+ if (!isObject(catalog))
29
+ return undefined;
30
+ const models = catalog.models;
31
+ if (!Array.isArray(models) || models.length === 0 || !models.every((m) => isObject(m) && typeof m.slug === 'string'))
32
+ return undefined;
33
+ return JSON.stringify({ ...catalog, models: models.map((m) => ({ ...m, apply_patch_tool_type: null })) });
34
+ }
35
+ /** The catalog each binary gave, once read: one binary, one catalog. */
36
+ const read = new Map();
37
+ /** How long `codex debug models --bundled` may take (it takes milliseconds). */
38
+ const DUMP_MS = 20_000;
39
+ /** Why the session runs on Codex's own catalog, in words for the run (the machine's notes): `cause`, what went wrong. */
40
+ const stillListed = (cause) => `Codex's own apply_patch stays listed: its bundled model catalog could not be read (${cause}). It has no environment to run in here, so a call to it fails: edit files with the host's edit and write tools.`;
41
+ /**
42
+ * The catalog without apply_patch for `codex`, read once per binary with
43
+ * `spawn` (`codex debug models --bundled`, its CODEX_HOME `dirs.own`, a
44
+ * directory of its own): its `bytes`, or `why` it can't be read, never
45
+ * silence. The session then runs on Codex's own catalog, apply_patch listed;
46
+ * a failure is not remembered, so the next drive tries again.
47
+ */
48
+ export async function patchlessCatalog(spawn, codex, dirs, signal) {
49
+ const key = JSON.stringify([codex.command, ...(codex.args ?? [])]);
50
+ const known = read.get(key);
51
+ if (known)
52
+ return { bytes: known };
53
+ const failed = (cause, fields) => {
54
+ // The run's words (the machine's notes) name the binary by its file name and none of the session's directories: no host
55
+ // path, no CODEX_HOME. The host's log keeps them whole (`fields`).
56
+ const named = [[codex.command, basename(codex.command)], [dirs.own, "its own directory"], [dirs.home, "its home"], [dirs.tmp, "its tmp"]];
57
+ const said = named.filter(([path]) => path.length > 1).sort((a, b) => b[0].length - a[0].length).reduce((text, [path, as]) => text.replaceAll(path, as), cause);
58
+ const why = stillListed(said);
59
+ codex.log?.(`codex: ${why}`, fields);
60
+ return { why };
61
+ };
62
+ let child;
63
+ try {
64
+ child = await spawn({
65
+ command: codex.command,
66
+ args: [...(codex.args ?? []), 'debug', 'models', '--bundled'],
67
+ cwd: dirs.own,
68
+ ...(signal ? { signal } : {}),
69
+ env: { HOME: dirs.home, CODEX_HOME: dirs.own, TMPDIR: dirs.tmp, NO_COLOR: '1' },
70
+ isolatedCommands: true,
71
+ });
72
+ }
73
+ catch (err) {
74
+ if (signal?.aborted)
75
+ throw err;
76
+ const error = String(err?.message ?? err).slice(0, 200);
77
+ return failed(`it did not start: ${error}`, { error });
78
+ }
79
+ child.end();
80
+ const out = [];
81
+ const reading = (async () => {
82
+ for await (const line of child.lines())
83
+ out.push(line);
84
+ })().catch(() => { });
85
+ let timer;
86
+ const exit = await Promise.race([child.exited, new Promise((r) => (timer = setTimeout(r, DUMP_MS, undefined)))]);
87
+ clearTimeout(timer);
88
+ if (!exit) {
89
+ child.kill('SIGKILL');
90
+ await child.exited;
91
+ }
92
+ await reading;
93
+ if (signal?.aborted)
94
+ throw signal.reason ?? new Error('agentrun-harness-codex: the drive stopped');
95
+ const catalog = exit?.code === 0 ? withoutApplyPatch(out.join('\n')) : undefined;
96
+ if (!catalog) {
97
+ const stderr = child.stderrTail().trim().slice(-300);
98
+ const cause = !exit ? `no answer in ${DUMP_MS / 1000} s` : exit.code === 0 ? 'its answer is not a catalog' : `exit ${exit.code === null ? `signal ${exit.signal}` : `code ${exit.code}`}${stderr ? `: ${stderr.split('\n').at(-1)}` : ''}`;
99
+ return failed(cause, { exit: exit ?? 'none', stderr });
100
+ }
101
+ const bytes = new TextEncoder().encode(catalog);
102
+ read.set(key, bytes);
103
+ return { bytes };
104
+ }
@@ -20,11 +20,16 @@ export interface CodeModeDeps {
20
20
  logged: Set<string>;
21
21
  /** Drain the rollout's tail into the log. */
22
22
  synced(): Promise<void>;
23
+ /** The tool bridge; `takeImages` gives a call's images once (host/process.ts), for the answer to Codex. */
23
24
  bridge: {
24
25
  get(name: string): {
25
26
  name: string;
26
27
  replay: string;
27
28
  } | undefined;
29
+ takeImages?(callId: string): readonly {
30
+ mimeType: string;
31
+ data: string;
32
+ }[] | undefined;
28
33
  };
29
34
  log(message: string, fields?: Record<string, unknown>): void;
30
35
  /** The rollout lines restored from the log. */
@@ -55,6 +60,19 @@ export declare function withOutputKind<T extends {
55
60
  };
56
61
  /** What a dangling `wait` of code mode is told: it had started, on the cell named, when the session stopped and took the cell's script with it. */
57
62
  export declare const waitStoppedText: (cell: string) => string;
63
+ /** A recorded result that held images (kernelTool's `{ text, images }`) as its text and a line saying how many, which are not
64
+ * shown again after the interruption; undefined for a result with none, whose repaired output stays as it is. */
65
+ export declare function imagesNoted(output: unknown): string | undefined;
66
+ /** A code-mode script's nested call's answer: its items, then a line saying how many images the tool returned, which are
67
+ * not sent (Codex gives a script an image as its data: URL in the result's text); an answer of any other shape, or no
68
+ * images, as it is. */
69
+ export declare function withImagesHeld(answer: unknown, images: readonly unknown[] | undefined): unknown;
70
+ /** A dynamic tool call's answer with `images` after its items, each `{ type: "inputImage", imageUrl }` with a data: URL
71
+ * (Codex 0.164's DynamicToolCallOutputContentItem); an answer of any other shape, or no images, as it is. */
72
+ export declare function withImages(answer: unknown, images: readonly {
73
+ mimeType: string;
74
+ data: string;
75
+ }[] | undefined): unknown;
58
76
  export declare function codeMode(deps: CodeModeDeps): {
59
77
  /** The app-server's request handler, with a code-mode host tool call handled before the harness's own. */
60
78
  request<R extends {
package/dist/code-mode.js CHANGED
@@ -3,7 +3,7 @@ import { boundResult, openTurn, recoveryNote, recoverySystemNote, recoveryUserTu
3
3
  // load in either order and the repair reads repairOutput"). A host loads harness.js first, so at that point none of its const bindings is set.
4
4
  import { repairOutput } from "./harness.js";
5
5
  import { summarizeRollout } from "./rollout.js";
6
- import { callKey, completedNested, execRecoveryOutput, NESTED_CALL, outputTextOf, recoveryFacts, Scripts, settle, UNWATCHED } from "./scripts.js";
6
+ import { callKey, completedNested, execRecoveryOutput, NESTED_CALL, outputTextOf, parkedKey, recoveryFacts, Scripts, settle, UNWATCHED } from "./scripts.js";
7
7
  /** The stream that ties each nested call to the `exec` it ran under: `{ callId, exec, since }` (`since`: the turn it ran in), written before the call runs. */
8
8
  export const NESTED_STREAM = "codex.nested";
9
9
  /** The stream that records the interrupted turns whose recovery note was injected: `{ since }`, once per interrupted turn. */
@@ -36,8 +36,36 @@ function factOf(state, rolled, tie, told = new Map()) {
36
36
  ...(e ? { store: { status: e.status === "completed" ? "completed" : e.status === "failed" ? "failed" : "started", text: e.status === "failed" ? (e.error?.message ?? "") : outputTextOf(e.output), ...(e.error?.interrupted ? { interrupted: true } : {}) } } : {}),
37
37
  ...(rolled.has(tie.callId) ? { rollout: rolled.get(tie.callId) } : {}),
38
38
  ...(status ? { told: status } : {}),
39
+ ...(state.effects.get(parkedKey(tie.callId))?.status === "completed" ? { parked: true } : {}),
39
40
  };
40
41
  }
42
+ /** A recorded result that held images (kernelTool's `{ text, images }`) as its text and a line saying how many, which are not
43
+ * shown again after the interruption; undefined for a result with none, whose repaired output stays as it is. */
44
+ export function imagesNoted(output) {
45
+ const images = output?.images;
46
+ const count = Array.isArray(images) ? images.length : 0;
47
+ if (!count)
48
+ return undefined;
49
+ return `${outputTextOf(output)}\n\nIt also returned ${count} image${count === 1 ? "" : "s"} (not shown again after the interruption).`;
50
+ }
51
+ /** A code-mode script's nested call's answer: its items, then a line saying how many images the tool returned, which are
52
+ * not sent (Codex gives a script an image as its data: URL in the result's text); an answer of any other shape, or no
53
+ * images, as it is. */
54
+ export function withImagesHeld(answer, images) {
55
+ const items = answer?.contentItems;
56
+ if (!images?.length || !Array.isArray(items))
57
+ return answer;
58
+ const count = images.length;
59
+ return { ...answer, contentItems: [...items, { type: "inputText", text: `${count} image${count === 1 ? "" : "s"} it returned ${count === 1 ? "was" : "were"} not sent: in code mode a tool's image reaches the script only as text.` }] };
60
+ }
61
+ /** A dynamic tool call's answer with `images` after its items, each `{ type: "inputImage", imageUrl }` with a data: URL
62
+ * (Codex 0.164's DynamicToolCallOutputContentItem); an answer of any other shape, or no images, as it is. */
63
+ export function withImages(answer, images) {
64
+ const items = answer?.contentItems;
65
+ if (!images?.length || !Array.isArray(items))
66
+ return answer;
67
+ return { ...answer, contentItems: [...items, ...images.map((image) => ({ type: "inputImage", imageUrl: `data:${image.mimeType};base64,${image.data}` }))] };
68
+ }
41
69
  export function codeMode(deps) {
42
70
  const { ctx, machine, journal, logged, synced } = deps;
43
71
  const scripts = new Scripts();
@@ -50,6 +78,28 @@ export function codeMode(deps) {
50
78
  machine.onRolloutLine?.((line) => scripts.note(line));
51
79
  /** The script a nested call is tied to now, as the log and the proxy's latest answer have it. */
52
80
  const tieNow = () => scripts.tie(machine.announcedExec?.(), (id) => logged.has(id));
81
+ /** A call Codex runs without the harness (a remote MCP server's tool, mcp.ts): the barrier it passes before its intent (its
82
+ * own line in the log, as the harness's barrier has it; a script's nested call, its script's, tied to it by `admit`), and
83
+ * after a recovery the log's answer for a `never` call the interrupted turn completed, re-issued under a new id. */
84
+ machine.onCalls?.({ recovered: (tool, args) => answeredAgain(tool, args), barrier: async (callId) => {
85
+ if (NESTED_CALL.test(callId)) {
86
+ if (!(await admit(callId)))
87
+ return false;
88
+ const exec = execOf.get(callId);
89
+ journal.append(NESTED_STREAM, { callId, exec: exec === undefined || exec === UNWATCHED ? null : exec, since: openTurn(ctx.state())?.since ?? -1 });
90
+ await journal.flush();
91
+ return true;
92
+ }
93
+ for (let i = 0; i < deps.tries; i++) {
94
+ if (i)
95
+ await sleep(50 * 2 ** (i - 1));
96
+ await synced();
97
+ if (logged.has(callId))
98
+ return journal.flush().then(() => true);
99
+ }
100
+ deps.log("codex: declined a call whose function_call line is not in the log", { callId });
101
+ return false;
102
+ } });
53
103
  /** A `never` nested call: wait for its script's line, as the harness's barrier waits for a call's own. True: admitted. */
54
104
  const admit = async (callId) => {
55
105
  for (let i = 0;; i++) {
@@ -94,6 +144,15 @@ export function codeMode(deps) {
94
144
  recovered.set(key, [...(recovered.get(key) ?? []), { tool: fact.tool, text: settled.text }]);
95
145
  }
96
146
  };
147
+ /** A `never` call the log holds a completed outcome for, re-issued after a recovery: its answer from the log, taken once. Held
148
+ * to the host's bound as the bridge holds a call's result (`boundResult`): the log keeps the result whole. */
149
+ function answeredAgain(tool, args, callId) {
150
+ const again = recovered.get(callKey(tool, args))?.shift();
151
+ if (!again)
152
+ return undefined;
153
+ deps.log("codex: answered a never call from the log: it completed before the interruption", { ...(callId ? { callId } : {}), tool: again.tool });
154
+ return boundResult(`Recorded earlier in this turn, not run again: ${again.text}`).text;
155
+ }
97
156
  /** The cell a dangling call waited on, when it is code mode's `wait` (a function call named `wait` with a `cell_id`, and no host tool of
98
157
  * that name); otherwise `undefined`. */
99
158
  const waitedCell = (c) => {
@@ -112,18 +171,21 @@ export function codeMode(deps) {
112
171
  /** The app-server's request handler, with a code-mode host tool call handled before the harness's own. */
113
172
  request(next) {
114
173
  return async (req) => {
174
+ // Codex asking to run a remote MCP server's tool, should it ask (approve mode asks nothing): the session's only MCP
175
+ // servers are its own, at its model proxy, which serves only the granted tools and records each call before it
176
+ // sends it (mcp.ts). Any other elicitation is the harness's to decline.
177
+ const meta = req.params?._meta;
178
+ if (req.method === "mcpServer/elicitation/request" && meta?.codex_approval_kind === "mcp_tool_call")
179
+ return { action: "accept", content: {}, _meta: null };
115
180
  if (req.method === "item/tool/call") {
116
181
  const p = req.params ?? {};
117
182
  const callId = String(p.callId ?? "");
118
183
  const tool = deps.bridge.get(String(p.tool));
119
184
  // After a recovery, a `never` call the log already holds a completed outcome for, called again (a script that was cut short and
120
185
  // written again re-issues every call it made): answered from the log, run no more.
121
- const again = tool?.replay === "never" ? recovered.get(callKey(tool.name, p.arguments))?.shift() : undefined;
122
- if (again) {
123
- deps.log("codex: answered a never call from the log: it completed before the interruption", { callId, tool: again.tool });
124
- // Held to the host's bound as the bridge holds a call's result (`boundResult`): the log keeps the result whole.
125
- return { contentItems: [{ type: "inputText", text: boundResult(`Recorded earlier in this turn, not run again: ${again.text}`).text }], success: true };
126
- }
186
+ const again = tool?.replay === "never" ? answeredAgain(tool.name, p.arguments, callId) : undefined;
187
+ if (again !== undefined)
188
+ return { contentItems: [{ type: "inputText", text: again }], success: true };
127
189
  if (NESTED_CALL.test(callId)) {
128
190
  if (tool?.replay === "never" && !ctx.isMemoized(toolKey(callId)) && !(await admit(callId)))
129
191
  return declined;
@@ -134,6 +196,21 @@ export function codeMode(deps) {
134
196
  // Never the unwatched-answer marker: a call tied to no known exec is journaled with none.
135
197
  journal.append(NESTED_STREAM, { callId, exec: exec === undefined || exec === UNWATCHED ? null : exec, since: openTurn(ctx.state())?.since ?? -1 });
136
198
  }
199
+ // The harness answers with the result's text; its images follow as `inputImage` items, which Codex 0.164's
200
+ // dynamic tool output takes (DynamicToolCallResponse.contentItems, its app-server schema), each a data: URL.
201
+ // The call runs first (`next`): its images are kept by the bridge as it answers, and taken after, whether or not
202
+ // the answer was built, so a call whose answer throws leaves none in the bridge for the session's life.
203
+ let images;
204
+ let answer;
205
+ try {
206
+ answer = await next(req);
207
+ }
208
+ finally {
209
+ images = deps.bridge.takeImages?.(callId);
210
+ }
211
+ // A script's nested call: Codex hands the script an inputImage as its data: URL inside the result's text, so a
212
+ // script that prints the result would send the model the base64 as words. No image goes to code mode; a line says so.
213
+ return NESTED_CALL.test(callId) ? withImagesHeld(answer, images) : withImages(answer, images);
137
214
  }
138
215
  return next(req);
139
216
  };
@@ -157,7 +234,11 @@ export function codeMode(deps) {
157
234
  // Code mode's `wait` on a cell had started: the generic answer, that the call never started, would be false.
158
235
  const cell = waitedCell(c);
159
236
  const item = items[i];
160
- items[i] = withOutputKind(cell === undefined ? item : { ...item, output: waitStoppedText(cell) }, c);
237
+ // A completed call whose result held images (kernelTool records { text, images }): repairOutput gives the record
238
+ // as JSON, so the model would read their base64 as text. Its text and a line on them instead; they are not sent.
239
+ const done = state.effects.get(toolKey(c.callId));
240
+ const pictured = cell === undefined && done?.status === "completed" ? imagesNoted(done.output) : undefined;
241
+ items[i] = withOutputKind(cell !== undefined ? { ...item, output: waitStoppedText(cell) } : pictured !== undefined ? { ...item, output: pictured } : item, c);
161
242
  return;
162
243
  }
163
244
  const { own, loose } = listed.get(c.callId);
package/dist/config.d.ts CHANGED
@@ -70,7 +70,7 @@ export declare function codexConfig(options: CodexConfigOptions): Record<string,
70
70
  * the model (`model`). Also what would swap the binary or shell that does the
71
71
  * sandboxing, send traffic outside the log (`otel`, `chatgpt_base_url`), grant
72
72
  * permission profiles, keep history or snapshots outside the rollout, or read
73
- * a file the app names (`RESERVED_CONFIG_SUFFIXES`).
73
+ * a file the app names (`model_catalog_json`, `RESERVED_CONFIG_SUFFIXES`).
74
74
  */
75
75
  export declare const RESERVED_CONFIG_KEYS: readonly string[];
76
76
  /** Key suffixes reserved at any depth: a binary, a file or a directory Codex would use (`codex_linux_sandbox_exe`, `zsh_path`, `model_instructions_file`, `experimental_compact_prompt_file`, `sqlite_home`, `log_dir`, ...). */