@parcha/agentrun-harness-codex 0.1.0-beta.30 → 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/dist/config.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/config.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
3
- // Changed by Parcha, patches: 001-code-mode-host, 004-names, 006-comments, 013-agents-off
3
+ // Changed by Parcha, and AgentRun's own since the port from upstream froze on 2026-11-07.
4
4
  /**
5
5
  * The `config.toml` a session's `CODEX_HOME` gets: the model and its
6
6
  * provider (the session's model proxy), and Codex's built-in tools and side
@@ -28,8 +28,9 @@ export const BUILTINS_OFF = {
28
28
  computer_use: false,
29
29
  in_app_browser: false,
30
30
  // Code mode's JavaScript runtime (no Node, no file system, no network): the only way a code-mode model such as luna
31
- // calls a tool. Its nested tools are the dynamic tools plus Codex's own apply_patch and MCP resource readers, which
32
- // run nothing here (read-only, approvals declined, no MCP server); its sub-agent tools are removed by agents.enabled.
31
+ // calls a tool. Its nested tools are the dynamic tools plus Codex's own MCP resource readers, which run nothing here
32
+ // (read-only, approvals declined, no MCP server); its sub-agent tools are removed by agents.enabled, its apply_patch by
33
+ // the harness's model catalog (catalog.ts).
33
34
  code_mode_host: true,
34
35
  tool_suggest: false,
35
36
  skill_search: false,
@@ -115,10 +116,11 @@ export function codexConfig(options) {
115
116
  * the model (`model`). Also what would swap the binary or shell that does the
116
117
  * sandboxing, send traffic outside the log (`otel`, `chatgpt_base_url`), grant
117
118
  * permission profiles, keep history or snapshots outside the rollout, or read
118
- * a file the app names (`RESERVED_CONFIG_SUFFIXES`).
119
+ * a file the app names (`model_catalog_json`, `RESERVED_CONFIG_SUFFIXES`).
119
120
  */
120
121
  export const RESERVED_CONFIG_KEYS = Object.freeze([
121
122
  'model',
123
+ 'model_catalog_json',
122
124
  'model_provider',
123
125
  'model_providers',
124
126
  'base_url',
@@ -0,0 +1,2 @@
1
+ import type { AdapterFacts } from "@parcha/agentrun-kernel";
2
+ export declare const facts: AdapterFacts;
package/dist/facts.js ADDED
@@ -0,0 +1,31 @@
1
+ import { codexPolicy } from "./host/policy.js";
2
+ import { codexSchemaProblems } from "./schema.js";
3
+ import { CODEX_INSTALL, CODEX_VERSION } from "./versions.js";
4
+ export const facts = Object.freeze({
5
+ id: "codex",
6
+ label: "Codex",
7
+ wire: "openai-responses",
8
+ // A message that comes mid-turn waits for the turn's end.
9
+ steer: false,
10
+ // A call that started is never run again (the harness answers it from the log); only the model calls again.
11
+ rerunsStarted: false,
12
+ // An answer its output limit cut ends the turn: the harness ends it there, before Codex asks for the answer again.
13
+ recoversCutAnswers: 0,
14
+ // One run's memory, measured with the server's (serve's host.ts): Codex's app-server beside the run's process.
15
+ runMib: 192,
16
+ // OpenAI's reasoning efforts stop at xhigh.
17
+ // Its own MCP client binds the session's remote MCP servers.
18
+ mcp: true,
19
+ thinking: Object.freeze(["low", "medium", "high", "xhigh"]),
20
+ // Codex's own live search, booked per call.
21
+ webSearch: "live",
22
+ ownModel: false,
23
+ normalizeModel: (model) => model,
24
+ install: Object.freeze({ npmLine: CODEX_INSTALL, spec: `@openai/codex@${CODEX_VERSION}`, codes: Object.freeze({ install: "CODEX_NOT_INSTALLED", pins: "CODEX_PIN_MISMATCH" }) }),
25
+ // Its MCP client builds the model's copy of a server's tool with parse_tool_input_schema (codex-rs
26
+ // tools/src/mcp_tool.rs at rust-v0.164.0): the shapes it drops or retypes, measured on the pinned binary.
27
+ schemaProblems: codexSchemaProblems,
28
+ // Codex's own tools, each the host's table tool it is.
29
+ nativeTools: Object.freeze({ web_search: "web_search", shell: "bash" }),
30
+ policy: (options) => codexPolicy({ model: options.model, tools: options.tools, ...(options.webSearch === "live" ? { webSearch: "live" } : {}), ...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}) }),
31
+ });
package/dist/harness.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { GateAnswer, GateCall } from '@parcha/agentrun-kernel';
1
2
  import { type Harness, type HostTool, type ReplayPolicy, type SessionState, type Submission } from './host/kernel.js';
2
3
  import { type AcquireMachine } from './host/process.js';
3
4
  import { type TomlValue } from './config.js';
@@ -58,13 +59,11 @@ import { type RolloutCall } from './rollout.js';
58
59
  *
59
60
  * Model traffic goes from the VM's loopback model port through the relay to
60
61
  * this drive's `gatewayHandler` (`CODEX_ROUTES`: the fixed path table, the
61
- * body policy, the model, the budget), which adds the credential: the VM
62
+ * body policy, the model), which adds the credential: the VM
62
63
  * never holds it. Codex's provider key is the attach's model key
63
64
  * (`SessionMachine.modelKey`, which the relay checks with the caller's pid),
64
65
  * hidden from the model's commands
65
- * (`shell_environment_policy`). Each response's cost is a record in the log
66
- * (`codex.spend`), so the dollar caps hold over the turn and the session,
67
- * across invocations. app-server runs no git of the Drive's: `GIT_DIR`
66
+ * (`shell_environment_policy`). app-server runs no git of the Drive's: `GIT_DIR`
68
67
  * points nowhere and no git config is read.
69
68
  */
70
69
  export interface CodexHarnessOptions {
@@ -75,6 +74,12 @@ export interface CodexHarnessOptions {
75
74
  * next to the built-ins. Default none.
76
75
  */
77
76
  tools?: HostTool[];
77
+ /**
78
+ * The host's gate (SessionIO.gate), asked by the tool bridge about each call
79
+ * of `tools` before its intent: a deny is the call's result in the host's
80
+ * words, nothing written and nothing run; a park holds it. Default none.
81
+ */
82
+ gate?: (call: GateCall) => Promise<GateAnswer>;
78
83
  /**
79
84
  * Codex's own shell and `apply_patch` (and `view_image`), on `/workspace`
80
85
  * in the session's VM. Default false (tool-less: `tools` are its only
@@ -136,11 +141,6 @@ export interface CodexMachine {
136
141
  network?: 'allow-all' | 'deny-all' | {
137
142
  readonly allow: readonly string[];
138
143
  };
139
- /** `sandbox({ budget })`'s dollar caps, over the turn and the session (each response's cost is in the log). Default none (`Infinity`). */
140
- budget?: {
141
- readonly turnUsd?: number;
142
- readonly sessionUsd?: number;
143
- };
144
144
  /** `sandbox({ commandTimeoutMs })`: a built-in command's longest run, within the time left in the invocation. */
145
145
  commandTimeoutMs?: number;
146
146
  }
@@ -170,8 +170,6 @@ export declare const LAGGING_RESULT = "Not run: the session's log had not caught
170
170
  export declare const TIMEOUT_TEXT = "The command ran out of time in this invocation and was stopped: it may have partly taken effect. Check the state it left before running it again.";
171
171
  /** The outcome of a command approved too close to the invocation's end: declined, never run. */
172
172
  export declare const NO_TIME_TEXT = "Not run: too little time was left in this invocation to run it and record its outcome. Nothing happened; make the same call again.";
173
- /** The journal stream of response costs: `{ usd, turn, estimated? }` (`turn`: the session turn it was spent in). */
174
- export declare const SPEND_STREAM = "codex.spend";
175
173
  /** The journal stream of the bubblewrap self-test's verdict: `{ sandboxMode, reason? }`, the first one kept. */
176
174
  export declare const SANDBOX_STREAM = "codex.sandbox";
177
175
  /** The journal stream of rollout tail failures: `{ turn, error }`. */
package/dist/harness.js CHANGED
@@ -1,25 +1,16 @@
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/harness.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
3
- // Changed by Parcha, imports rewritten for AgentRun; patches: 002-standin-guard, 004-names, 006-comments, 007-code-mode-nested, 008-recovery-note-developer, 010-repair-without-a-note, 011-web-search-live, 012-cut-off-safe-call
3
+ // Changed by Parcha, and AgentRun's own since the port from upstream froze on 2026-11-07.
4
4
  import { AsyncLocalStorage } from 'node:async_hooks';
5
5
  import { Unavailable, UNAVAILABLE_STEP } from './host/kernel.js';
6
- import { BuiltinCalls, CODEX_ROUTES, failureText, gatewayCredential, gatewayHandler, gatewayUrl, isBrandedMachine, ModelSteps, Mutex, NativeJournal, placeSubmissions, recoveryNote, restartEvent, settleAbandonedModelSteps, toolBridge, toolKey, transcriptOf, } from './host/process.js';
6
+ import { BuiltinCalls, CODEX_ROUTES, failureText, gatewayCredential, gatewayHandler, gatewayUrl, isBrandedMachine, ModelSteps, Mutex, NativeJournal, placeSubmissions, recoveryNote, restartEvent, resumeUnstartedCalls, settleAbandonedModelSteps, toolBridge, toolKey, transcriptOf, } from './host/process.js';
7
7
  import { acknowledgeInDrive, attachInDrive, cliPath, CODEX_CLI, DriveFiles, SANDBOX_DOC } from './host/sandbox.js';
8
8
  import { AppServer } from './app-server.js';
9
9
  import { codeMode } from './code-mode.js';
10
+ import { danglingCalls, settleCall } from './transcript.js';
10
11
  import { BUILTINS_ON, checkConfig, codexConfig, toToml } from './config.js';
11
12
  import { callIdOf, endsTurn, isRolloutPath, isSessionMeta, rolloutPathIn, rolloutStream, rolloutText, summarizeRollout, THREAD_STREAM, } from './rollout.js';
12
13
  export const DEFAULT_MODEL = 'openai/gpt-5.4-mini';
13
- /** Options this harness no longer takes, with what replaced them (docs/workspaces.md §3.4). */
14
- const REMOVED = {
15
- sandbox: "`sandbox` is now `sandboxMode` (Codex's own sandbox for its commands; `sandbox()` is the session's environment, `workspace: sandbox()`)",
16
- host: "Codex runs only on the session machine its adapter makes: pass `machine`, not a host",
17
- cwd: "the working directory is always /workspace, the session's Drive",
18
- bin: 'the codex binary is the one the sandbox image pins',
19
- env: 'pass non-secret variables with sandbox({ env })',
20
- keepSessionDir: "CODEX_HOME is in the session's VM and is rebuilt from the log every drive",
21
- workspaceNote: "/workspace is the session's Drive, the same on every VM",
22
- };
23
14
  const SANDBOX_MODES = new Set(['read-only', 'workspace-write', 'danger-full-access']);
24
15
  /** Codex's command actions that only read: a command made of these alone is `safe` (the note says "safe to repeat"). */
25
16
  const READ_ACTIONS = new Set(['read', 'listFiles', 'search']);
@@ -58,8 +49,6 @@ export const TIMEOUT_TEXT = 'The command ran out of time in this invocation and
58
49
  export const NO_TIME_TEXT = 'Not run: too little time was left in this invocation to run it and record its outcome. Nothing happened; make the same call again.';
59
50
  /** Rollout tail failures in one turn before the turn ends with an `Unavailable` instead of another redelivery. */
60
51
  const MAX_TAIL_FAILURES = 3;
61
- /** The journal stream of response costs: `{ usd, turn, estimated? }` (`turn`: the session turn it was spent in). */
62
- export const SPEND_STREAM = 'codex.spend';
63
52
  /** The journal stream of the bubblewrap self-test's verdict: `{ sandboxMode, reason? }`, the first one kept. */
64
53
  export const SANDBOX_STREAM = 'codex.sandbox';
65
54
  /** The journal stream of rollout tail failures: `{ turn, error }`. */
@@ -78,7 +67,7 @@ export class RolloutTailError extends Error {
78
67
  function testGuard() {
79
68
  if (process.env.AGENTRUN_CODEX_STANDIN !== '1')
80
69
  throw new TypeError('agentrun-harness-codex: a stand-in app-server needs AGENTRUN_CODEX_STANDIN=1');
81
- if (!process.env.NODE_TEST_CONTEXT && process.env.NODE_ENV !== 'test')
70
+ if (!process.env.NODE_TEST_CONTEXT)
82
71
  throw new TypeError('agentrun-harness-codex: a stand-in app-server runs only under a test runner');
83
72
  if (process.env.NODE_ENV === 'production')
84
73
  throw new TypeError('agentrun-harness-codex: a stand-in app-server refuses to run in production');
@@ -100,46 +89,7 @@ function sandboxRequired(why) {
100
89
  function turnIndex(state) {
101
90
  return transcriptOf(state).filter((r) => r.data?.type === 'turn').length + state.effectOrder.filter((e) => e.name === UNAVAILABLE_STEP).length;
102
91
  }
103
- /**
104
- * The dollar ledger, from the log: every response's cost is a `codex.spend`
105
- * record tagged with its session turn, so the session's total and the open
106
- * turn's hold across invocations and redeliveries (docs/workspaces.md §5.5).
107
- * A crash can lose the costs of the last group commit's responses (a
108
- * couple of seconds), never more.
109
- */
110
- function logLedger(journal, turn) {
111
- let session = 0;
112
- let thisTurn = 0;
113
- let open = true;
114
- for (const r of journal.records(SPEND_STREAM)) {
115
- const usd = Number(r.data?.usd);
116
- if (!Number.isFinite(usd) || usd < 0)
117
- continue;
118
- session += usd;
119
- if (r.data?.turn === turn)
120
- thisTurn += usd;
121
- }
122
- return {
123
- spent: () => ({ turnUsd: thisTurn, sessionUsd: session }),
124
- add: (usd, info) => {
125
- thisTurn += usd;
126
- session += usd;
127
- // A late response after the drive let go of the log: counted in memory only.
128
- if (open)
129
- journal.append(SPEND_STREAM, { usd, turn, ...(info.estimated ? { estimated: true } : {}) });
130
- },
131
- turnEnded: () => {
132
- turn++;
133
- thisTurn = 0;
134
- },
135
- close: () => void (open = false),
136
- };
137
- }
138
92
  export function codexHarness(options = {}) {
139
- for (const [key, why] of Object.entries(REMOVED)) {
140
- if (options[key] !== undefined)
141
- throw new TypeError(`agentrun-harness-codex: the ${key} option is gone: ${why}`);
142
- }
143
93
  const builtinsOn = options.builtins ?? false;
144
94
  if (options.sandboxMode !== undefined) {
145
95
  if (!SANDBOX_MODES.has(options.sandboxMode))
@@ -156,7 +106,6 @@ export function codexHarness(options = {}) {
156
106
  const spec = options.machine;
157
107
  const codex = options.test ? { command: options.test.command, args: options.test.args ?? [] } : { command: cliPath(CODEX_CLI), args: [] };
158
108
  const network = spec?.network === undefined || spec.network === 'allow-all' ? 'allow-all' : spec.network === 'deny-all' ? 'deny-all' : 'custom';
159
- const budget = { turnUsd: spec?.budget?.turnUsd ?? Infinity, sessionUsd: spec?.budget?.sessionUsd ?? Infinity };
160
109
  /** Nothing left to do: no turn a crash cut off, nothing in the inbox. */
161
110
  const idle = (ctx) => !recoveryNote(ctx.state()) && ctx.pending().length === 0;
162
111
  return {
@@ -215,22 +164,13 @@ export function codexHarness(options = {}) {
215
164
  const inDrive = AsyncLocalStorage.snapshot();
216
165
  // Every model request, through the handler: the drive's model steps, written around a "Crash during: model" drill.
217
166
  const steps = new ModelSteps(ctx, { log });
218
- /** The spend cap a model call of this drive was refused for, if one was. */
219
- let capped;
220
- const ledger = logLedger(journal, turnAt);
221
167
  const handler = gatewayHandler({
222
168
  routes: CODEX_ROUTES,
223
169
  models: { model },
224
- budget,
225
- ledger,
226
170
  network,
227
171
  credential: () => inDrive(credential),
228
172
  target: options.gatewayUrl ?? gatewayUrl(),
229
173
  track: steps.request,
230
- onCap: (cap) => {
231
- if (cap !== 'concurrency')
232
- capped = cap;
233
- },
234
174
  // Without the app's own log, the handler's default: a refused model call is a warning in the Function's logs, not silence.
235
175
  ...(options.log ? { log: (message, fields) => log(`codex gateway: ${message}`, fields) } : {}),
236
176
  });
@@ -239,12 +179,10 @@ export function codexHarness(options = {}) {
239
179
  machine = await attachInDrive(ctx, spec.acquire, { model: handler, deadline });
240
180
  }
241
181
  catch (err) {
242
- ledger.close();
243
182
  await steps.close();
244
183
  throw err;
245
184
  }
246
185
  if (!isBrandedMachine(machine)) {
247
- ledger.close();
248
186
  await Promise.resolve(machine?.close?.()).catch(() => { });
249
187
  await steps.close();
250
188
  throw sandboxRequired("the machine it was given is not one the sandbox tier's session factory made.");
@@ -262,12 +200,15 @@ export function codexHarness(options = {}) {
262
200
  const thread = journal.records(THREAD_STREAM).at(-1)?.data;
263
201
  const restored = thread ? (await journal.read(rolloutStream(thread.threadId))).map((r) => r.data) : [];
264
202
  const resume = thread && isSessionMeta(restored[0]) && isRolloutPath(thread.path, thread.threadId) ? thread : undefined;
265
- const lines = resume ? restored : [];
266
- const rolloutBytes = new TextEncoder().encode(rolloutText(lines));
203
+ // Settled before Codex starts (below): a host call the rollout left with no output gets one.
204
+ let lines = resume ? restored : [];
205
+ let rolloutBytes = new TextEncoder().encode(rolloutText(lines));
267
206
  // Codex's key: the attach's model key, which the relay checks (its hash armed the relay; only the attach's processes may use it). Never a credential: the handler adds that.
268
207
  const key = machine.modelKey;
269
208
  // A `never` tool waits for the journal: its call is in the log before its intent (the barrier ran first, below).
270
- const bridge = toolBridge(ctx, tools, { beforeNever: () => journal.flush() });
209
+ // The host's gate first, inside the bridge: after the call's line is in the log (the barrier) and before its intent, so
210
+ // a refused or parked call leaves no intent, and a parked one's line is there for the resume to settle it.
211
+ const bridge = toolBridge(ctx, tools, { beforeNever: () => journal.flush(), ...(options.gate ? { gate: options.gate } : {}) });
271
212
  /** What the model must hear about this attach (a lost Drive), once per invocation, with its first message; acknowledged after that turn. */
272
213
  let notes = machine.notes.length && !invocation.notesShown ? machine.notes.map((n) => `[Sandbox] ${n}`).join('\n') : undefined;
273
214
  let proc;
@@ -277,6 +218,20 @@ export function codexHarness(options = {}) {
277
218
  let builtins;
278
219
  const clamps = new Map();
279
220
  try {
221
+ if (resume) {
222
+ // A resumed thread's host calls with no output, before Codex starts on it: one that never started (no intent in
223
+ // the session's records) runs now through the bridge under its own id (gate, intent, run, result); one the log
224
+ // finished is answered with its recorded result; one with an intent and no outcome is left to the recovery below,
225
+ // never run again. Each answer is its function_call_output line in the mirrored rollout, which Codex resumes from.
226
+ // A call the gate parks rejects here, nothing written.
227
+ await resumeUnstartedCalls(ctx, bridge, danglingCalls(lines), async (call, outcome) => {
228
+ const settled = settleCall(lines, call.callId, outcome);
229
+ journal.append(rolloutStream(resume.threadId), settled.at(-1));
230
+ await journal.flush();
231
+ lines = settled;
232
+ });
233
+ rolloutBytes = new TextEncoder().encode(rolloutText(lines));
234
+ }
280
235
  // The log wins: the VM's cache dirs are wiped, and CODEX_HOME rebuilt from the log.
281
236
  await machine.files.wipe();
282
237
  let sandboxMode = 'read-only';
@@ -456,6 +411,18 @@ export function codexHarness(options = {}) {
456
411
  t.partial.clear();
457
412
  return text;
458
413
  };
414
+ // The provider cut the turn's answer at its output limit, read by the model proxy before Codex has the stop. Codex
415
+ // takes an incomplete answer as a stream error and asks for it again (each time paid), so the turn is interrupted
416
+ // here, and its outcome is the cut answer's: completed, stopReason "length", the text it said so far kept.
417
+ machine.onCut?.((stop) => {
418
+ const t = active;
419
+ if (!t?.id || t.cut)
420
+ return;
421
+ t.cut = stop;
422
+ void rpc.request('turn/interrupt', { threadId, turnId: t.id }).catch((err) => {
423
+ log('codex: the turn whose answer was cut could not be interrupted', { error: String(err?.message ?? err).slice(0, 200) });
424
+ });
425
+ });
459
426
  // The built-ins: each command and patch an intent before Codex runs it, its outcome when the item completes.
460
427
  const calls = (builtins = new BuiltinCalls(ctx, {
461
428
  live: true,
@@ -614,8 +581,12 @@ export function codexHarness(options = {}) {
614
581
  case 'item/tool/call': {
615
582
  const callId = String(p.callId ?? '');
616
583
  const tool = bridge.get(String(p.tool));
617
- // A `never` tool's call: its own line in the log first (the barrier), else it is declined, never run.
618
- if (tool?.replay === 'never' && callId && !ctx.isMemoized(toolKey(callId)) && !(await barrier(callId))) {
584
+ // A `never` tool's call: its own line in the log first (the barrier), else it is declined, never run. With the
585
+ // host's gate, every fresh call's line goes in first too: a park seals the run's log, and a resume settles a
586
+ // parked call only from its line (a replay-safe call whose line lags is still asked, as before).
587
+ const fresh = Boolean(callId) && !ctx.isMemoized(toolKey(callId));
588
+ const inLog = fresh && (tool?.replay === 'never' || options.gate) ? await barrier(callId) : true;
589
+ if (tool?.replay === 'never' && !inLog) {
619
590
  return { contentItems: [{ type: 'inputText', text: LAGGING_RESULT }], success: false };
620
591
  }
621
592
  mirror();
@@ -739,6 +710,8 @@ export function codexHarness(options = {}) {
739
710
  const carry = [];
740
711
  /** One Codex turn, to its end line. The session's turn ends in `turn`. */
741
712
  const codexTurn = async (text, clientId) => {
713
+ // A Codex turn of its own: the model proxy, which refuses answer requests once a turn's answer stopped, admits them.
714
+ machine.openTurn?.();
742
715
  // The invocation's first message carries, once, what the model must hear about the sandbox (its files were lost).
743
716
  if (notes) {
744
717
  if (!clientId.startsWith(RECOVER_PREFIX))
@@ -783,12 +756,9 @@ export function codexHarness(options = {}) {
783
756
  if (said)
784
757
  journal.message({ type: 'message', role: 'assistant', text: said });
785
758
  active = undefined;
786
- // A model call the budget refused: the turn ends here, saying which cap (no redelivery spends more).
787
- if (capped) {
788
- throw new Unavailable(`The turn stopped: the ${capped === 'turnUsd' ? "turn's" : "session's"} model spend reached its cap (sandbox({ budget: { ${capped} } })).`, {
789
- hint: `Raise sandbox({ budget: { ${capped} } }) to let the session spend more.`,
790
- });
791
- }
759
+ // Its answer cut at the output limit: the turn was interrupted for it, and ended there, its answer unfinished.
760
+ if (t.cut)
761
+ return { status: 'completed', stopReason: 'length', ...(t.cut.outputTokens !== undefined ? { outputTokens: t.cut.outputTokens } : {}) };
792
762
  const status = result.status === 'completed' ? 'completed' : result.status === 'interrupted' ? 'interrupted' : 'failed';
793
763
  const error = status === 'completed' ? undefined : (t.error ?? result.error?.message ?? undefined);
794
764
  return { status, ...(error ? { error } : {}) };
@@ -797,7 +767,6 @@ export function codexHarness(options = {}) {
797
767
  code.turnEnded();
798
768
  journal.message({ type: 'turn', ...outcome });
799
769
  await guard(journal.flush());
800
- ledger.turnEnded();
801
770
  // The turn that showed the model its notes is in the log: the record stops repeating them. Notes that never reached the model stay owed.
802
771
  if (invocation.notesShown && !invocation.notesAcknowledged && machine.notes.length) {
803
772
  await guard(acknowledgeInDrive(ctx, invocation.notesKey));
@@ -947,7 +916,6 @@ export function codexHarness(options = {}) {
947
916
  }
948
917
  if (held.lost && !ctx.signal.aborted)
949
918
  await journal.flush().catch(() => { });
950
- ledger.close();
951
919
  // No model step outlives the drive.
952
920
  await steps.close();
953
921
  // Nothing the model started outlives the drive (§5.4 "Ending an invocation"): the session's processes are killed, the VM and the Drive stay.
@@ -1,5 +1,7 @@
1
1
  import type { AcquireMachine, CacheDir, SessionProcess } from "./process.js";
2
+ import type { SessionMcp } from "@parcha/agentrun-kernel";
2
3
  import { type ModelProxyHooks, type ModelProxyOptions, type ParentWatch } from "@parcha/agentrun-kernel/host";
4
+ import { type CodexCommand } from "../catalog.js";
3
5
  /** The variables a child takes from this process, when they are set. */
4
6
  export declare const INHERITED_ENV: readonly ["PATH", "LANG", "TZ"];
5
7
  /** One of a session's private directories under its own directory `dir`, where the local machine makes it. */
@@ -33,11 +35,19 @@ export interface LocalMachineOptions {
33
35
  log?: ModelProxyOptions["log"];
34
36
  fetch?: typeof fetch;
35
37
  };
38
+ /** The session's remote MCP servers (mcp.ts): each served at the proxy's `/mcp/<server>`, written in Codex's config,
39
+ * and each call recorded in the drive's session before it is sent. */
40
+ mcp?: SessionMcp;
36
41
  /** For tests: the process environment the allowlist reads. Default `process.env`. */
37
42
  env?: Readonly<Record<string, string | undefined>>;
38
43
  /** Files one of the session's private directories holds at the start of every drive: written when the machine is
39
44
  * acquired and again after every wipe, which the harness runs before it starts Codex. Its paths are checked here. */
40
45
  seed?: MachineSeed;
46
+ /** The binary the session runs, when its built-ins are off: Codex's own apply_patch, which then has no environment to run
47
+ * in, is offered to no model. Its bundled catalog without it (../catalog.ts) is read once per binary, written in codex-home
48
+ * with the seed and named in Codex's config (`configure`, `model_catalog_json`); one that can't be read is logged, and the
49
+ * session runs on Codex's own. */
50
+ catalog?: CodexCommand;
41
51
  }
42
52
  /** A command and its arguments, as the machine starts it. */
43
53
  export interface ChildCommand {
@@ -4,6 +4,7 @@
4
4
  // and otherwise an empty one of its own (`work`). Codex keeps nothing there (its state is in codex-home), and a
5
5
  // tool-less Codex reads nothing there itself.
6
6
  // A seed of files the host gives is in one of them at the start of every drive: written at acquire and after each wipe.
7
+ // So is Codex's bundled model catalog without its own apply_patch, when the host asks for it (`catalog`, ../catalog.ts).
7
8
  // - A child's environment is an allowlist: PATH, LANG and TZ from this process, plus what the harness names (its homes,
8
9
  // and the per-session proxy key). Nothing else is inherited, so no provider key, token or host secret reaches it.
9
10
  // - A child's git stops at the session's directory and at a workspace's parent (GIT_CEILING_DIRECTORIES), and the host may start every child under its
@@ -22,6 +23,8 @@ import { brandMachine } from "./process.js";
22
23
  import { parentWatched, startModelProxy } from "@parcha/agentrun-kernel/host";
23
24
  import { codexPolicy, withWebSearches } from "./policy.js";
24
25
  import { UNWATCHED } from "../scripts.js";
26
+ import { CODEX_MCP_CLIENT, mcpServersConfig, recorded } from "../mcp.js";
27
+ import { MODEL_CATALOG_FILE, patchlessCatalog } from "../catalog.js";
25
28
  /** The variables a child takes from this process, when they are set. */
26
29
  export const INHERITED_ENV = Object.freeze(["PATH", "LANG", "TZ"]);
27
30
  const DIRS = ["home", "config", "codex-home", "tmp", "cache"];
@@ -182,9 +185,19 @@ export function localMachine(options) {
182
185
  writeFileSync(path, file.bytes, { mode: file.mode ?? 0o600 });
183
186
  }
184
187
  };
188
+ // Read in a CODEX_HOME of its own, not the session's, before anything else of the session starts.
189
+ const own = join(dirs.cache, "codex-catalog");
190
+ if (options.catalog)
191
+ mkdirSync(own, { recursive: true, mode: 0o700 });
192
+ const read = options.catalog ? await patchlessCatalog((spawnOptions) => start(spawnOptions, from, root, ceiling, options.confine, options.parentWatch), options.catalog, { home: dirs.home, tmp: dirs.tmp, own }, ctx.signal) : undefined;
193
+ const catalog = read?.bytes;
194
+ // A catalog that could not be read is never silent: the run is told why apply_patch stays listed (the machine's notes).
195
+ const notes = read?.why ? [read.why] : [];
185
196
  const seed = () => {
186
197
  if (options.seed)
187
198
  upload(options.seed.dir, seeded);
199
+ if (catalog)
200
+ upload("codex-home", [{ path: MODEL_CATALOG_FILE, bytes: catalog }]);
188
201
  };
189
202
  // Before the proxy starts: a seed that cannot be written is refused with nothing left running.
190
203
  seed();
@@ -194,12 +207,15 @@ export function localMachine(options) {
194
207
  let announced;
195
208
  let open = 0;
196
209
  const rolloutListeners = [];
210
+ const cutListeners = [];
211
+ let calls;
197
212
  const search = options.webSearch === "live";
198
213
  const price = options.proxy.price && search ? withWebSearches(options.proxy.price) : options.proxy.price;
199
214
  const proxy = await startModelProxy({
200
215
  policy: codexPolicy({
201
216
  model: route.models.model,
202
217
  tools: options.proxy.tools,
218
+ ...(options.mcp ? { mcpTools: options.mcp.servers.flatMap((server) => server.tools.map((tool) => `mcp__${server.name}__${tool.name}`)) } : {}),
203
219
  ...(options.proxy.maxOutputTokens ? { maxOutputTokens: options.proxy.maxOutputTokens } : {}),
204
220
  ...(search ? { webSearch: "live" } : {}),
205
221
  announce: {
@@ -221,10 +237,18 @@ export function localMachine(options) {
221
237
  origin: route.target,
222
238
  credential: async () => (await route.credential()) ?? "",
223
239
  ...(price ? { price } : {}),
240
+ // The kernel's proxy mounts the session's MCP door for Codex's own client; each call is recorded first (recorded).
241
+ ...(options.mcp ? { mcp: { session: recorded(options.mcp, ctx, () => calls), client: CODEX_MCP_CLIENT } } : {}),
224
242
  ...(options.proxy.log ? { log: options.proxy.log } : {}),
225
243
  ...(options.proxy.fetch ? { fetch: options.proxy.fetch } : {}),
226
244
  // The provider stopped the turn's answer on its content filter: no retry of it can pass, so the turn ends at once.
227
245
  onFiltered: (message) => ctx.halt?.(new Error(message)),
246
+ // The provider cut the turn's answer at its output limit: Codex would ask for it again (it retries an incomplete
247
+ // stream), so the harness ends the turn there, its answer cut.
248
+ onCut: (stop) => {
249
+ for (const listener of cutListeners)
250
+ listener(stop);
251
+ },
228
252
  }, key);
229
253
  const lost = new AbortController();
230
254
  const children = new Set();
@@ -238,8 +262,24 @@ export function localMachine(options) {
238
262
  modelKey: key,
239
263
  announcedExec: () => announced,
240
264
  onRolloutLine: (listener) => void rolloutListeners.push(listener),
241
- ...(search ? { configure: (config) => void (config.web_search = "live") } : {}),
242
- notes: [],
265
+ onCut: (listener) => void cutListeners.push(listener),
266
+ openTurn: () => proxy.openTurn(),
267
+ onCalls: (given) => void (calls = given),
268
+ ...(search || options.mcp || catalog ? {
269
+ configure: (config) => {
270
+ if (search)
271
+ config.web_search = "live";
272
+ // Codex's bearer for the proxy's /mcp/<server> is the key it sends to the proxy's model route.
273
+ const keyEnv = (config.model_providers?.gateway?.env_key ?? "");
274
+ if (options.mcp)
275
+ config.mcp_servers = mcpServersConfig(options.mcp, proxy.url, keyEnv);
276
+ // Only with the built-ins off: with them on, apply_patch runs through the shell.
277
+ const features = config.features;
278
+ if (catalog && features?.shell_tool !== true && features?.unified_exec !== true)
279
+ config.model_catalog_json = join(dirs["codex-home"], MODEL_CATALOG_FILE);
280
+ },
281
+ } : {}),
282
+ notes,
243
283
  spawn: async (spawnOptions) => {
244
284
  if (closed)
245
285
  throw new Error("agentrun-harness-codex: the session machine is closed");
@@ -15,6 +15,9 @@ export interface CodexPolicyOptions {
15
15
  model: string;
16
16
  /** The session's own tool names: every other tool definition is dropped. */
17
17
  tools: readonly string[];
18
+ /** The granted tools of the session's remote MCP servers, `mcp__<server>__<tool>`: the pinned CLI offers a server's tools
19
+ * in a namespace named `mcp__<server>`, each by the server's own name. */
20
+ mcpTools?: readonly string[];
18
21
  /** The most output tokens one request may ask for. Default 32 000. */
19
22
  maxOutputTokens?: number;
20
23
  /** Codex's own web search, live: the live search tool the pinned CLI sends passes, and a `tool_choice` naming it. Each
@@ -45,6 +48,16 @@ export interface CodexPolicyOptions {
45
48
  * `"incomplete_details":{` after `"response":{` (one JSON object), whatever the JSON's spacing.
46
49
  */
47
50
  export declare function filtered(text: string, lineStarts?: readonly string[]): boolean;
51
+ /**
52
+ * Whether the provider cut the answer at its output limit: its end is an `incomplete` response whose
53
+ * `incomplete_details.reason` is `max_output_tokens`, with the output tokens its usage reports when the end was read whole.
54
+ * Read as `filtered` reads its stop, but keyed only on the data's own `type` (`response.incomplete`), never on an `event:`
55
+ * line: a gateway's Responses stream is data alone. Any other reason (`content_filter`) is no cut. Codex 0.164 takes a cut
56
+ * answer as a stream error and asks for it again, each time paid; the harness ends the turn first.
57
+ */
58
+ export declare function cut(text: string, lineStarts?: readonly string[]): {
59
+ outputTokens?: number;
60
+ } | undefined;
48
61
  /** The usage a Responses answer reports at its end (`endValue`), or undefined, an unknown cost, when it reports none. */
49
62
  export declare function usageOf(text: string): ProxyUsage | undefined;
50
63
  /** The web searches a Responses answer ran, as its terminal event reports them (`tool_usage.web_search.num_requests`,
@@ -84,4 +97,8 @@ export declare function responsesReasoningBytes(event: string): number;
84
97
  export declare function responsesContentBytes(event: string): number;
85
98
  /** A Responses body with its output limited to `max` tokens, reasoning included: never raised, and never longer. */
86
99
  export declare function limitResponsesOutput(body: Record<string, unknown>, max: number): Record<string, unknown>;
100
+ /** `body` (a Responses body) with `text` as a note the model reads after everything the client sent: one developer message
101
+ * at the end of `input`. Caching is by prefix, so the earlier items stay a hit; the client's next request, which sends
102
+ * its own input whole, does not carry it. */
103
+ export declare function addResponsesNote(body: Record<string, unknown>, text: string): Record<string, unknown>;
87
104
  export declare function codexPolicy(options: CodexPolicyOptions): ProviderPolicy;