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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1100 @@
1
+ // Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
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
4
+ import { AsyncLocalStorage } from 'node:async_hooks';
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';
7
+ import { acknowledgeInDrive, attachInDrive, cliPath, CODEX_CLI, DriveFiles, SANDBOX_DOC } from './host/sandbox.js';
8
+ import { AppServer } from './app-server.js';
9
+ import { codeMode } from './code-mode.js';
10
+ import { BUILTINS_ON, checkConfig, codexConfig, toToml } from './config.js';
11
+ import { callIdOf, endsTurn, isRolloutPath, isSessionMeta, rolloutPathIn, rolloutStream, rolloutText, summarizeRollout, THREAD_STREAM, } from './rollout.js';
12
+ 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
+ const SANDBOX_MODES = new Set(['read-only', 'workspace-write', 'danger-full-access']);
24
+ /** Codex's command actions that only read: a command made of these alone is `safe` (the note says "safe to repeat"). */
25
+ const READ_ACTIONS = new Set(['read', 'listFiles', 'search']);
26
+ /** A Codex item's replay policy: a command whose every action reads is `safe`; any other command, and every patch, `never`. */
27
+ export function codexItemReplay(item) {
28
+ if (item.type !== 'commandExecution')
29
+ return 'never';
30
+ const actions = item.commandActions ?? [];
31
+ return actions.length > 0 && actions.every((a) => READ_ACTIONS.has(String(a.type))) ? 'safe' : 'never';
32
+ }
33
+ /**
34
+ * The env var Codex reads its provider key from (`env_key`; it sends it as
35
+ * `authorization: Bearer`). It holds the attach's model key
36
+ * (`SessionMachine.modelKey`), never a credential: the gateway handler adds
37
+ * that in the Function. Hidden from the
38
+ * model's commands by `shell_environment_policy` (`HARNESS_*`), and exempt
39
+ * from the spawn check's credential-name rule (harness-world-sandbox's
40
+ * `PLACEHOLDER_NAMES`), never from its value rules.
41
+ */
42
+ export const KEY_ENV = 'HARNESS_CODEX_GATEWAY_KEY';
43
+ /** How long the drive waits for a call's `function_call` line before it declines the call: `SYNC` and look again, this many times, with a growing pause. */
44
+ const BARRIER_TRIES = 5;
45
+ /** What the model is told when a call was declined because its line wasn't in the log yet. */
46
+ export const LAGGING_NOTE = "[harness] The previous tool call was not run: the session's log had not caught up with it yet. Nothing happened; make the same call again.";
47
+ /** A dynamic tool's result when its call was declined for the same reason. */
48
+ export const LAGGING_RESULT = "Not run: the session's log had not caught up with this call yet. Nothing happened; make the same call again.";
49
+ /** A command still running this close to the invocation's end is stopped, with a definite outcome (the kernel's 15 s margin, and time to record it). */
50
+ const COMMAND_MARGIN_MS = 25_000;
51
+ /** The kernel's own bound on an invocation when the World reports no deadline (`DriverOptions.maxInvocationMs`'s default). */
52
+ const DEFAULT_INVOCATION_MS = 10 * 60_000;
53
+ /** Re-attaches after a lost link within one invocation (the session factory has its own bound too). */
54
+ const MAX_RELINKS = 3;
55
+ /** The outcome of a command the invocation's deadline stopped. */
56
+ export 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.';
57
+ /** The outcome of a command approved too close to the invocation's end: declined, never run. */
58
+ 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
+ /** Rollout tail failures in one turn before the turn ends with an `Unavailable` instead of another redelivery. */
60
+ 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
+ /** The journal stream of the bubblewrap self-test's verdict: `{ sandboxMode, reason? }`, the first one kept. */
64
+ export const SANDBOX_STREAM = 'codex.sandbox';
65
+ /** The journal stream of rollout tail failures: `{ turn, error }`. */
66
+ export const TAIL_STREAM = 'codex.tail';
67
+ /** Where app-server's git looks for a repository: nowhere (it would otherwise read `/workspace/.git`'s config, which the model writes, outside bwrap). */
68
+ const NO_GIT_DIR = '/nonexistent/dh-no-git';
69
+ /** A built-in call whose `function_call` line never reached the log: declined, never run. */
70
+ const LAGGING = Object.freeze({ run: false, lagging: true });
71
+ /** The rollout tail failed (the file shrank, was replaced, or is not the session user's): what the drive halts with. */
72
+ export class RolloutTailError extends Error {
73
+ constructor(cause) {
74
+ super(`agentrun-harness-codex: the rollout can no longer be mirrored (${String(cause?.message ?? cause).slice(0, 200)}): the drive stops, and the next one rebuilds CODEX_HOME from the log`, { cause });
75
+ this.name = 'RolloutTailError';
76
+ }
77
+ }
78
+ function testGuard() {
79
+ if (process.env.AGENTRUN_CODEX_STANDIN !== '1')
80
+ 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')
82
+ throw new TypeError('agentrun-harness-codex: a stand-in app-server runs only under a test runner');
83
+ if (process.env.NODE_ENV === 'production')
84
+ throw new TypeError('agentrun-harness-codex: a stand-in app-server refuses to run in production');
85
+ }
86
+ /** When this invocation ends: the World's runtime deadline if it reports one, at most the kernel's default bound away. */
87
+ async function invocationDeadline(ctx) {
88
+ const reported = await ctx.world.getRuntimeDeadline?.().catch(() => undefined);
89
+ const cap = Date.now() + DEFAULT_INVOCATION_MS;
90
+ const at = reported instanceof Date ? reported.getTime() : NaN;
91
+ return Number.isFinite(at) ? Math.min(at, cap) : cap;
92
+ }
93
+ function sandboxRequired(why) {
94
+ return new Unavailable(`Codex runs only on a session machine its adapter made: ${why}`, {
95
+ code: 'sandbox_required',
96
+ hint: "Run Codex through @parcha/agentrun-harness-codex's codexAdapter(), which makes the session machine.",
97
+ });
98
+ }
99
+ /** The session turn the log is in: turns ended (a `turn` entry, or an `unavailable` fact), so the open turn's index. */
100
+ function turnIndex(state) {
101
+ return transcriptOf(state).filter((r) => r.data?.type === 'turn').length + state.effectOrder.filter((e) => e.name === UNAVAILABLE_STEP).length;
102
+ }
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
+ 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
+ const builtinsOn = options.builtins ?? false;
144
+ if (options.sandboxMode !== undefined) {
145
+ if (!SANDBOX_MODES.has(options.sandboxMode))
146
+ throw new TypeError(`agentrun-harness-codex: sandboxMode must be 'read-only', 'workspace-write' or 'danger-full-access'`);
147
+ if (!builtinsOn)
148
+ throw new TypeError('agentrun-harness-codex: sandboxMode needs builtins: true (with the built-ins off, Codex runs no command)');
149
+ }
150
+ checkConfig(options.config);
151
+ if (options.test)
152
+ testGuard();
153
+ const model = options.model ?? DEFAULT_MODEL;
154
+ const log = options.log ?? (() => { });
155
+ const tools = options.tools ?? [];
156
+ const spec = options.machine;
157
+ const codex = options.test ? { command: options.test.command, args: options.test.args ?? [] } : { command: cliPath(CODEX_CLI), args: [] };
158
+ 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
+ /** Nothing left to do: no turn a crash cut off, nothing in the inbox. */
161
+ const idle = (ctx) => !recoveryNote(ctx.state()) && ctx.pending().length === 0;
162
+ return {
163
+ name: options.name ?? 'codex',
164
+ modelCalls: 'self',
165
+ async drive(ctx) {
166
+ // Nothing to do (an idle wake, a chaos arming): no VM. A model step a
167
+ // crash left open after its turn ended is closed (no request will retry it).
168
+ if (idle(ctx)) {
169
+ await settleAbandonedModelSteps(ctx);
170
+ return;
171
+ }
172
+ if (!spec)
173
+ throw sandboxRequired('this harness was given no sandbox machine.');
174
+ const deadline = await invocationDeadline(ctx);
175
+ const invocation = { fg: new Mutex(), inflight: new Set(), notesShown: false, notesAcknowledged: false };
176
+ // A link to the VM lost mid-drive: the drive is rebuilt from the log on a re-attached machine, in this invocation.
177
+ for (let relinks = 0;; relinks++) {
178
+ const held = {};
179
+ try {
180
+ return await driveOn(ctx, spec, deadline, invocation, held);
181
+ }
182
+ catch (err) {
183
+ const lost = held.lost === true && !ctx.signal.aborted;
184
+ if (!lost || relinks >= MAX_RELINKS)
185
+ throw err;
186
+ // The link dropped after the work was done (the last turn's end is in the log): nothing to re-attach for.
187
+ await ctx.refresh();
188
+ if (idle(ctx))
189
+ return;
190
+ log('codex: the link to the sandbox was lost; re-attaching', { relinks: relinks + 1, error: String(err?.message ?? err).slice(0, 200) });
191
+ // Notes shown in a turn that never committed may not be in the rollout the thread resumes from: shown again, until a turn that carried them is in the log.
192
+ if (!invocation.notesAcknowledged)
193
+ invocation.notesShown = false;
194
+ }
195
+ }
196
+ },
197
+ };
198
+ /** One drive on one attach of the session's VM. */
199
+ async function driveOn(ctx, spec, deadline, invocation, held) {
200
+ const journal = new NativeJournal(ctx);
201
+ // A rollout that keeps being tampered with (only possible under
202
+ // danger-full-access): the turn ends, instead of a redelivery that boots
203
+ // the VM and spends model calls again.
204
+ const turnAt = turnIndex(ctx.state());
205
+ const tailFailures = journal.records(TAIL_STREAM).filter((r) => r.data?.turn === turnAt).length;
206
+ if (tailFailures >= MAX_TAIL_FAILURES) {
207
+ throw new Unavailable(`The turn stopped: Codex's rollout in the session's sandbox was replaced or shrunk ${tailFailures} times, so the log can no longer mirror it.`, {
208
+ code: 'unavailable',
209
+ hint: 'Something in the VM rewrites $CODEX_HOME (possible only with sandboxMode danger-full-access): run the session with workspace-write.',
210
+ });
211
+ }
212
+ // The handler asks for the credential per request, in this drive's async
213
+ // context.
214
+ const credential = options.credential ?? gatewayCredential;
215
+ const inDrive = AsyncLocalStorage.snapshot();
216
+ // Every model request, through the handler: the drive's model steps, written around a "Crash during: model" drill.
217
+ 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
+ const handler = gatewayHandler({
222
+ routes: CODEX_ROUTES,
223
+ models: { model },
224
+ budget,
225
+ ledger,
226
+ network,
227
+ credential: () => inDrive(credential),
228
+ target: options.gatewayUrl ?? gatewayUrl(),
229
+ track: steps.request,
230
+ onCap: (cap) => {
231
+ if (cap !== 'concurrency')
232
+ capped = cap;
233
+ },
234
+ // 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
+ ...(options.log ? { log: (message, fields) => log(`codex gateway: ${message}`, fields) } : {}),
236
+ });
237
+ let machine;
238
+ try {
239
+ machine = await attachInDrive(ctx, spec.acquire, { model: handler, deadline });
240
+ }
241
+ catch (err) {
242
+ ledger.close();
243
+ await steps.close();
244
+ throw err;
245
+ }
246
+ if (!isBrandedMachine(machine)) {
247
+ ledger.close();
248
+ await Promise.resolve(machine?.close?.()).catch(() => { });
249
+ await steps.close();
250
+ throw sandboxRequired("the machine it was given is not one the sandbox tier's session factory made.");
251
+ }
252
+ const { dirs, root: cwd } = machine;
253
+ const home = dirs.home;
254
+ const codexHome = dirs['codex-home'];
255
+ // The Drive's manifest (`hw.sandbox-files`): what the Files panel shows, kept in the log so it reads with no VM.
256
+ const driveId = ctx.docs?.read(SANDBOX_DOC).value.driveId;
257
+ const driveFiles = new DriveFiles(ctx, machine, { ...(typeof driveId === 'string' ? { driveId } : {}), log });
258
+ // The session's thread and its rollout, as the log has them. A thread
259
+ // whose first line (session_meta) never reached the log cannot be
260
+ // resumed: the drive starts a new one. A path the log holds is checked
261
+ // again: only a canonical one is ever uploaded or tailed.
262
+ const thread = journal.records(THREAD_STREAM).at(-1)?.data;
263
+ const restored = thread ? (await journal.read(rolloutStream(thread.threadId))).map((r) => r.data) : [];
264
+ 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));
267
+ // 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
+ const key = machine.modelKey;
269
+ // 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() });
271
+ /** What the model must hear about this attach (a lost Drive), once per invocation, with its first message; acknowledged after that turn. */
272
+ let notes = machine.notes.length && !invocation.notesShown ? machine.notes.map((n) => `[Sandbox] ${n}`).join('\n') : undefined;
273
+ let proc;
274
+ let tail;
275
+ let tailBroken = false;
276
+ let poll;
277
+ let builtins;
278
+ const clamps = new Map();
279
+ try {
280
+ // The log wins: the VM's cache dirs are wiped, and CODEX_HOME rebuilt from the log.
281
+ await machine.files.wipe();
282
+ let sandboxMode = 'read-only';
283
+ if (builtinsOn)
284
+ sandboxMode = options.sandboxMode ?? (await sandboxVerdict(ctx, spec, machine, journal));
285
+ const config = codexConfig({
286
+ model,
287
+ baseUrl: `${machine.modelUrl}/v1`,
288
+ envKey: KEY_ENV,
289
+ contextWindow: options.contextWindow ?? 272_000,
290
+ cwd,
291
+ ...(spec.env ? { commandEnv: spec.env } : {}),
292
+ extra: {
293
+ sandbox_mode: sandboxMode,
294
+ ...(sandboxMode === 'workspace-write' ? { sandbox_workspace_write: { network_access: true, writable_roots: [cwd, home] } } : {}),
295
+ ...(builtinsOn ? { features: { ...BUILTINS_ON } } : {}),
296
+ ...(options.config ?? {}),
297
+ },
298
+ });
299
+ machine.configure?.(config);
300
+ await machine.files.upload('codex-home', [
301
+ { path: 'config.toml', bytes: new TextEncoder().encode(toToml(config)) },
302
+ ...(resume ? [{ path: resume.path, bytes: rolloutBytes }] : []),
303
+ ]);
304
+ proc = await machine.spawn({
305
+ command: codex.command,
306
+ args: [...codex.args, 'app-server', '--stdio'],
307
+ cwd,
308
+ signal: ctx.signal,
309
+ env: {
310
+ ...(spec.env ?? {}),
311
+ HOME: home,
312
+ CODEX_HOME: codexHome,
313
+ TMPDIR: dirs.tmp,
314
+ XDG_CONFIG_HOME: `${home}/.config`,
315
+ XDG_DATA_HOME: `${home}/.local/share`,
316
+ XDG_STATE_HOME: `${home}/.local/state`,
317
+ XDG_CACHE_HOME: dirs.cache,
318
+ NO_COLOR: '1',
319
+ // app-server runs git itself, outside bwrap, with the key in its env:
320
+ // no repository (the Drive's `.git/config` is the model's to write,
321
+ // `core.fsmonitor` among it) and no global or system config (the
322
+ // global one is under HOME, a writable root of the model's commands).
323
+ // The commands' own env is the policy's, without these.
324
+ GIT_DIR: NO_GIT_DIR,
325
+ GIT_CONFIG_GLOBAL: '/dev/null',
326
+ GIT_CONFIG_NOSYSTEM: '1',
327
+ // Last: the provider key.
328
+ [KEY_ENV]: key,
329
+ },
330
+ // With the built-ins off it runs no command. With them on, the model port's peer check rests on app-server not being
331
+ // dumpable (its binary is execute-only in the base), never on a claim.
332
+ ...(builtinsOn ? {} : { isolatedCommands: true }),
333
+ });
334
+ const child = proc;
335
+ // Everything the drive waits on also ends when the child dies, the link is lost or the drive stops.
336
+ const stopped = new Promise((_, reject) => {
337
+ const fail = () => reject(ctx.signal.reason ?? new Error('agentrun-harness-codex: the drive stopped'));
338
+ if (ctx.signal.aborted)
339
+ fail();
340
+ else
341
+ ctx.signal.addEventListener('abort', fail, { once: true });
342
+ });
343
+ const lost = new Promise((_, reject) => {
344
+ const fail = () => reject(new Error("agentrun-harness-codex: the link to the session's sandbox was lost"));
345
+ if (machine.signal.aborted)
346
+ fail();
347
+ else
348
+ machine.signal.addEventListener('abort', fail, { once: true });
349
+ });
350
+ let rpc;
351
+ let active;
352
+ let turnEnds = 0;
353
+ let stream = '';
354
+ let threadId = '';
355
+ /** The calls whose `function_call` (or `custom_tool_call`) line is in the log: what the barrier looks for. */
356
+ const logged = new Set();
357
+ for (const line of lines) {
358
+ const id = callIdOf(line);
359
+ if (id)
360
+ logged.add(id);
361
+ }
362
+ /**
363
+ * The tail failed: the file was replaced or shrank (tampered with), or
364
+ * is not the agent's. Nothing more is mirrored; the failure is in the
365
+ * log (a turn ends after `MAX_TAIL_FAILURES`), then the drive stops.
366
+ */
367
+ const broken = (err) => {
368
+ if (tailBroken)
369
+ return;
370
+ tailBroken = true;
371
+ const error = String(err?.message ?? err).slice(0, 200);
372
+ log('codex: the rollout tail failed: the drive stops', { error });
373
+ journal.append(TAIL_STREAM, { turn: turnAt, error });
374
+ void journal
375
+ .flush()
376
+ .catch(() => { })
377
+ .finally(() => ctx.halt?.(new RolloutTailError(err)));
378
+ };
379
+ // The rollout, mirrored line by line: every 2 s while lines arrive
380
+ // (group commit keeps that to a batch or so), and at every barrier
381
+ // (a tool call, a turn's end), where it is drained (`SYNC`) and flushed.
382
+ const mirror = () => {
383
+ if (!tail || tailBroken || journal.poisoned || ctx.signal.aborted)
384
+ return;
385
+ let fresh;
386
+ try {
387
+ fresh = tail.read();
388
+ }
389
+ catch (err) {
390
+ if (!machine.signal.aborted)
391
+ broken(err);
392
+ return;
393
+ }
394
+ for (const line of fresh) {
395
+ if (!line)
396
+ continue;
397
+ journal.append(stream, line);
398
+ const id = callIdOf(line);
399
+ if (id)
400
+ logged.add(id);
401
+ if (endsTurn(line))
402
+ turnEnds++;
403
+ }
404
+ };
405
+ /** Drain the tail to the end of the file (`SYNC`), then mirror what came. */
406
+ const synced = async () => {
407
+ if (!tail)
408
+ return;
409
+ try {
410
+ await tail.sync();
411
+ }
412
+ catch (err) {
413
+ if (!machine.signal.aborted)
414
+ broken(err);
415
+ throw err;
416
+ }
417
+ mirror();
418
+ };
419
+ const code = codeMode({ ctx, machine, journal, logged, synced, bridge, log, lines, rpc: () => rpc, guard: (p) => guard(p), threadId: () => threadId, tries: BARRIER_TRIES, declined: LAGGING_RESULT });
420
+ /**
421
+ * The hard barrier before a `never` call (§5.6): its `function_call`
422
+ * line in the log, flushed, before its intent. Codex's rollout writer is
423
+ * asynchronous, so the line is looked for again after each drain, a
424
+ * bounded number of times. False: it never came, and the call must be
425
+ * declined (it never ran; the model is told to make it again).
426
+ */
427
+ const barrier = async (callId) => {
428
+ for (let i = 0;; i++) {
429
+ await synced();
430
+ if (logged.has(callId)) {
431
+ await journal.flush();
432
+ return true;
433
+ }
434
+ if (i + 1 >= BARRIER_TRIES)
435
+ break;
436
+ await sleep(50 * 2 ** i);
437
+ }
438
+ log('codex: declined a call whose function_call line is not in the log', { callId });
439
+ return false;
440
+ };
441
+ /** After a declined call: the model hears it was not run and may try again (a steer into the running turn; in the transcript once Codex took it). */
442
+ const retryNote = (callId) => {
443
+ const t = active;
444
+ if (!t?.id || !threadId)
445
+ return;
446
+ void rpc
447
+ .request('turn/steer', { threadId, expectedTurnId: t.id, clientUserMessageId: `harness:retry:${callId}`, input: [{ type: 'text', text: LAGGING_NOTE, text_elements: [] }] })
448
+ .then(() => void journal.message({ type: 'message', role: 'user', text: LAGGING_NOTE, synthetic: 'retry' }), () => { });
449
+ };
450
+ const takeSaid = (t) => {
451
+ if (!t)
452
+ return '';
453
+ // The model sometimes repeats a message verbatim (its commentary, then the same as its answer): say it once.
454
+ const text = [...t.said, ...t.partial.values()].filter((m, i, all) => !!m && m !== all[i - 1]).join('\n\n');
455
+ t.said = [];
456
+ t.partial.clear();
457
+ return text;
458
+ };
459
+ // The built-ins: each command and patch an intent before Codex runs it, its outcome when the item completes.
460
+ const calls = (builtins = new BuiltinCalls(ctx, {
461
+ live: true,
462
+ // The barrier ran before `begin` (and declined the call without its line): flush what it mirrored.
463
+ beforeNever: async () => {
464
+ await journal.flush();
465
+ },
466
+ }));
467
+ const starting = new Map();
468
+ /** Items an approval was asked for: at most one approval per item. */
469
+ const asked = new Set();
470
+ /** And those it was accepted for. */
471
+ const accepted = new Set();
472
+ /** Commands the deadline stopped: their outcome says so. */
473
+ const timedOut = new Set();
474
+ /** A running command past the time this invocation has left: its turn is interrupted, and its outcome (when the item completes) says it was stopped. */
475
+ const clamp = (id, turnId) => {
476
+ if (clamps.has(id))
477
+ return;
478
+ const limit = Math.min(spec.commandTimeoutMs ?? Infinity, deadline - Date.now() - COMMAND_MARGIN_MS);
479
+ clamps.set(id, setTimeout(() => {
480
+ clamps.delete(id);
481
+ // Not running: its call ended, or its approval is pending or was declined (the approval re-arms it when accepted).
482
+ if (!calls.has(id) || (asked.has(id) && !accepted.has(id)))
483
+ return;
484
+ const t = active;
485
+ // Only its own turn is interrupted: a command that outlived its turn (unified exec) is stopped with the drive.
486
+ if (!t?.id || (turnId && t.id !== turnId)) {
487
+ log('codex: a command ran out of time after its turn ended: it is stopped with the drive', { callId: id });
488
+ return;
489
+ }
490
+ log('codex: a command ran out of time in this invocation: stopped', { callId: id });
491
+ timedOut.add(id);
492
+ void rpc.request('turn/interrupt', { threadId, turnId: t.id }).catch((err) => {
493
+ timedOut.delete(id);
494
+ log('codex: the turn could not be interrupted', { callId: id, error: String(err?.message ?? err).slice(0, 200) });
495
+ });
496
+ }, Math.max(0, Math.min(limit, 2 ** 31 - 1))));
497
+ };
498
+ /** An item of a built-in (a command or a patch): its intent, once, after its `function_call` line is in the log. */
499
+ const beginItem = (item, turnId) => {
500
+ if (!builtinsOn || (item.type !== 'commandExecution' && item.type !== 'fileChange') || typeof item.id !== 'string')
501
+ return undefined;
502
+ let started = starting.get(item.id);
503
+ if (!started) {
504
+ const callId = item.id;
505
+ started = (async () => {
506
+ const replay = codexItemReplay(item);
507
+ if (replay === 'never' && !ctx.isMemoized(toolKey(callId)) && !(await barrier(callId)))
508
+ return LAGGING;
509
+ const name = item.type === 'commandExecution' ? 'shell' : 'apply_patch';
510
+ const text = takeSaid(active);
511
+ journal.message({ type: 'message', role: 'assistant', text, toolCalls: [{ id: callId, name }] });
512
+ const input = item.type === 'commandExecution' ? { command: item.command, cwd: item.cwd } : { changes: item.changes };
513
+ const start = await calls.begin({ callId, name, input, replay });
514
+ // Every command that runs is bounded by the invocation, asked about or not (Codex runs a known-safe one without asking).
515
+ if (start.run && item.type === 'commandExecution')
516
+ clamp(callId, turnId);
517
+ return start;
518
+ })();
519
+ started.catch(() => { });
520
+ starting.set(item.id, started);
521
+ }
522
+ return started;
523
+ };
524
+ const endItem = async (item) => {
525
+ const started = beginItem(item);
526
+ if (!started)
527
+ return;
528
+ const start = await started.catch(() => undefined);
529
+ if (!start?.run)
530
+ return;
531
+ clearTimeout(clamps.get(item.id));
532
+ clamps.delete(item.id);
533
+ // What the call wrote is on the Drive before its outcome is in the log (§5.6 FSYNC); a flush that can't run leaves the call open ("may have half-run").
534
+ try {
535
+ await machine.fsync();
536
+ }
537
+ catch (err) {
538
+ log('codex: the Drive flush failed; the call is left open', { callId: item.id, error: String(err?.message ?? err).slice(0, 200) });
539
+ return;
540
+ }
541
+ const failed = item.status === 'failed' || item.status === 'declined' || (typeof item.exitCode === 'number' && item.exitCode !== 0);
542
+ let text = item.type === 'commandExecution'
543
+ ? `${typeof item.exitCode === 'number' ? `exit code ${item.exitCode}\n` : ''}${item.aggregatedOutput ?? ''}`.trim() || `(${item.status ?? 'no output'})`
544
+ : (item.changes ?? []).map((c) => `${c.kind?.type ?? 'change'} ${c.path ?? ''}`).join('\n') || `(${item.status ?? 'no changes'})`;
545
+ // The deadline stopped it: one writer of its outcome, here, once the item reports it ended.
546
+ if (timedOut.has(item.id))
547
+ text = `${TIMEOUT_TEXT}\n\n${text}`;
548
+ await calls.end(item.id, { text, isError: failed || timedOut.has(item.id) }).catch(() => { });
549
+ // The Drive's manifest hears of it: a live event, and the paths a patch named (a command may have changed anything).
550
+ const paths = item.type === 'fileChange' ? (item.changes ?? []).map((c) => c.path).filter((p) => typeof p === 'string') : [];
551
+ driveFiles.changed({ tool: item.type === 'commandExecution' ? 'shell' : 'apply_patch', callId: item.id, ...(paths.length ? { paths } : {}) });
552
+ };
553
+ /** Built-in outcomes being recorded (after their Drive flush): a turn ends only once they are in the log. */
554
+ const ending = new Set();
555
+ const onNotification = (n) => {
556
+ const p = n.params ?? {};
557
+ if (n.method === 'item/started' && p.item)
558
+ void beginItem(p.item, typeof p.turnId === 'string' ? p.turnId : undefined);
559
+ else if (n.method === 'item/completed' && p.item) {
560
+ const done = endItem(p.item).catch(() => { });
561
+ ending.add(done);
562
+ void done.finally(() => ending.delete(done));
563
+ }
564
+ const t = active;
565
+ if (n.method === 'item/agentMessage/delta') {
566
+ if (t && typeof p.delta === 'string') {
567
+ t.partial.set(p.itemId, (t.partial.get(p.itemId) ?? '') + p.delta);
568
+ ctx.live({ type: 'text', delta: p.delta });
569
+ }
570
+ return;
571
+ }
572
+ if (!t)
573
+ return;
574
+ if (n.method === 'turn/started' && typeof p.turn?.id === 'string')
575
+ t.id ??= p.turn.id;
576
+ else if (n.method === 'item/completed' && p.item?.type === 'agentMessage') {
577
+ t.partial.delete(p.item.id);
578
+ if (p.item.text)
579
+ t.said.push(String(p.item.text));
580
+ }
581
+ else if (n.method === 'error' && !p.willRetry)
582
+ t.error = p.error?.message ?? 'Codex reported an error';
583
+ else if (n.method === 'turn/completed' && (!t.id || p.turn?.id === t.id))
584
+ t.done(p.turn ?? {});
585
+ };
586
+ /**
587
+ * Why an approval is declined before its intent is looked at, if it is:
588
+ * the drive approves one call once, as its intent names it, and nothing
589
+ * that would run something else or run it outside bwrap.
590
+ */
591
+ const refusal = (p) => {
592
+ // Input to a running command (`write_stdin`), or a shell's sub-command: they share the parent's item id, but are not the call its intent names.
593
+ if (p.kind === 'writeStdin')
594
+ return 'writeStdin';
595
+ if (p.approvalId != null)
596
+ return 'approvalId';
597
+ if (typeof p.reason === 'string' && /without (the )?sandbox/i.test(p.reason))
598
+ return 'unsandboxed';
599
+ // Codex 0.160 asks again for the same item to rerun a command bwrap denied without the sandbox ("command failed; retry without sandbox?").
600
+ if (asked.has(String(p.itemId)))
601
+ return 'repeat';
602
+ if (p.networkApprovalContext != null || (Array.isArray(p.proposedNetworkPolicyAmendments) && p.proposedNetworkPolicyAmendments.length > 0))
603
+ return 'network';
604
+ // More than the sandbox gives (extra permissions, a write root): bwrap is the boundary, not advice.
605
+ if (p.additionalPermissions != null)
606
+ return 'additionalPermissions';
607
+ if (p.grantRoot != null)
608
+ return 'grantRoot';
609
+ return undefined;
610
+ };
611
+ const onRequest = async (req) => {
612
+ const p = req.params ?? {};
613
+ switch (req.method) {
614
+ case 'item/tool/call': {
615
+ const callId = String(p.callId ?? '');
616
+ 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))) {
619
+ return { contentItems: [{ type: 'inputText', text: LAGGING_RESULT }], success: false };
620
+ }
621
+ mirror();
622
+ const text = takeSaid(active);
623
+ journal.message({ type: 'message', role: 'assistant', text, toolCalls: [{ id: callId, name: String(p.tool) }] });
624
+ // Tracked for the invocation: a re-attach waits for it, so the next drive reads its real outcome.
625
+ const run = invocation.fg.run(() => bridge.call(String(p.tool), p.arguments ?? {}, callId));
626
+ invocation.inflight.add(run);
627
+ void run.then(() => invocation.inflight.delete(run), () => invocation.inflight.delete(run));
628
+ const result = await run;
629
+ return { contentItems: [{ type: 'inputText', text: result.text }], success: !result.isError };
630
+ }
631
+ case 'item/tool/requestUserInput':
632
+ // In Default mode Codex answers the model's request_user_input
633
+ // itself, without asking. Should it ask, no one is here to answer.
634
+ return { answers: {} };
635
+ case 'item/commandExecution/requestApproval':
636
+ case 'item/fileChange/requestApproval': {
637
+ // Built-ins off: one slipped past the config; refuse it.
638
+ if (!builtinsOn) {
639
+ log('codex: declined a built-in tool', { method: req.method, itemId: p.itemId });
640
+ return { decision: 'decline' };
641
+ }
642
+ const itemId = String(p.itemId ?? '');
643
+ const why = refusal(p);
644
+ asked.add(itemId);
645
+ if (why) {
646
+ log('codex: declined an approval asking for more than its call', { method: req.method, itemId, escalation: why });
647
+ return { decision: 'decline' };
648
+ }
649
+ const item = { ...p, id: itemId, type: req.method.includes('fileChange') ? 'fileChange' : 'commandExecution' };
650
+ const turnId = typeof p.turnId === 'string' ? p.turnId : undefined;
651
+ try {
652
+ // Too close to the invocation's end to run a command and record its outcome: declined, never run (an intent already written gets that outcome).
653
+ if (item.type === 'commandExecution' && deadline - Date.now() < COMMAND_MARGIN_MS) {
654
+ const begun = await starting.get(itemId)?.catch(() => undefined);
655
+ if (begun && !('lagging' in begun) && begun.run)
656
+ await calls.end(itemId, { text: NO_TIME_TEXT, isError: true });
657
+ log('codex: declined a command too close to the end of the invocation', { itemId });
658
+ return { decision: 'decline' };
659
+ }
660
+ // Approved once its intent is in the log (its item/started came first; else from here).
661
+ const start = await (starting.get(itemId) ?? beginItem(item, turnId));
662
+ if ('lagging' in start) {
663
+ retryNote(itemId);
664
+ return { decision: 'decline' };
665
+ }
666
+ if (start.run) {
667
+ accepted.add(itemId);
668
+ if (item.type === 'commandExecution')
669
+ clamp(itemId, turnId);
670
+ return { decision: 'accept' };
671
+ }
672
+ log('codex: declined a call the log already has', { itemId });
673
+ return { decision: 'decline' };
674
+ }
675
+ catch (err) {
676
+ log('codex: declined a call whose intent could not be committed', { itemId, error: String(err) });
677
+ return { decision: 'decline' };
678
+ }
679
+ }
680
+ case 'item/permissions/requestApproval':
681
+ // More permissions for the rest of the turn: none granted.
682
+ log('codex: granted no extra permissions', { itemId: p.itemId });
683
+ return { permissions: {}, scope: 'turn' };
684
+ case 'execCommandApproval':
685
+ case 'applyPatchApproval':
686
+ // The same, in the protocol's older names.
687
+ log('codex: declined a built-in tool', { method: req.method });
688
+ return { decision: { denied: { rejection: 'Built-in tools are off in this session: use the tools you are given.' } } };
689
+ case 'mcpServer/elicitation/request':
690
+ return { action: 'decline', content: null, _meta: null };
691
+ default:
692
+ throw Object.assign(new Error(`harness-world-codex does not support ${req.method}`), { code: -32601 });
693
+ }
694
+ };
695
+ rpc = new AppServer(child, {
696
+ onNotification,
697
+ onRequest: code.request(onRequest),
698
+ onNoise: (line) => log('codex: stdout noise', { line: line.slice(0, 200) }),
699
+ });
700
+ const died = rpc.closed.then((err) => {
701
+ throw err;
702
+ });
703
+ stopped.catch(() => { });
704
+ lost.catch(() => { });
705
+ died.catch(() => { });
706
+ const guard = (p) => Promise.race([p, stopped, lost, died]);
707
+ const init = await guard(rpc.initialize());
708
+ const homes = [codexHome, ...(typeof init?.codexHome === 'string' ? [init.codexHome] : [])];
709
+ const threadParams = {
710
+ model,
711
+ cwd,
712
+ approvalPolicy: 'untrusted',
713
+ approvalsReviewer: 'user',
714
+ sandbox: sandboxMode,
715
+ ...(options.instructions ? { developerInstructions: options.instructions } : {}),
716
+ ...(options.baseInstructions ? { baseInstructions: options.baseInstructions } : {}),
717
+ };
718
+ if (resume) {
719
+ await guard(rpc.request('thread/resume', { threadId: resume.threadId, ...threadParams, excludeTurns: true }));
720
+ threadId = resume.threadId;
721
+ tail = await machine.tail('codex-home', resume.path, { offset: rolloutBytes.length });
722
+ }
723
+ else {
724
+ const started = await guard(rpc.request('thread/start', {
725
+ ...threadParams,
726
+ dynamicTools: bridge.tools.map((t) => ({ type: 'function', name: t.name, description: t.description, inputSchema: t.inputSchema })),
727
+ }));
728
+ const id = String(started?.thread?.id ?? '');
729
+ // The path is the VM's word: the driver tails only the one it would derive itself (no file is no thread to mirror: every later drive would start over).
730
+ const path = rolloutPathIn(homes, String(started?.thread?.path ?? ''), id);
731
+ threadId = id;
732
+ journal.append(THREAD_STREAM, { threadId, path }, { id: `thread:${threadId}` });
733
+ tail = await machine.tail('codex-home', path, { offset: 0 });
734
+ }
735
+ stream = rolloutStream(threadId);
736
+ poll = setInterval(mirror, 2000);
737
+ mirror();
738
+ // Steers Codex refused (their turn ended first): each gets the next Codex turn of the same session turn.
739
+ const carry = [];
740
+ /** One Codex turn, to its end line. The session's turn ends in `turn`. */
741
+ const codexTurn = async (text, clientId) => {
742
+ // The invocation's first message carries, once, what the model must hear about the sandbox (its files were lost).
743
+ if (notes) {
744
+ if (!clientId.startsWith(RECOVER_PREFIX))
745
+ journal.message({ type: 'message', role: 'user', text: notes, synthetic: 'environment' });
746
+ text = `${notes}\n\n${text}`;
747
+ notes = undefined;
748
+ invocation.notesShown = true;
749
+ invocation.notesKey = machine.notesKey;
750
+ }
751
+ let done;
752
+ const completed = new Promise((r) => (done = r));
753
+ const t = { said: [], partial: new Map(), done, completed };
754
+ active = t;
755
+ const endsBefore = turnEnds;
756
+ const started = await guard(rpc.request('turn/start', {
757
+ threadId,
758
+ clientUserMessageId: clientId,
759
+ input: [{ type: 'text', text, text_elements: [] }],
760
+ // No environment is no shell and no apply_patch: the built-ins off.
761
+ ...(builtinsOn ? {} : { environments: [] }),
762
+ approvalPolicy: 'untrusted',
763
+ ...(options.effort ? { effort: options.effort } : {}),
764
+ }));
765
+ t.id ??= started?.turn?.id;
766
+ const steering = steer(t);
767
+ let result;
768
+ try {
769
+ result = await guard(completed);
770
+ }
771
+ finally {
772
+ await steering.stop();
773
+ }
774
+ // The outcomes of the turn's built-ins first: a turn never ends before them.
775
+ await guard(Promise.all([...ending]));
776
+ // Its end line (task_complete) follows the notification closely: drained, then looked for.
777
+ for (let i = 0; i < 20 && turnEnds <= endsBefore; i++) {
778
+ await guard(synced());
779
+ if (turnEnds <= endsBefore)
780
+ await sleep(100);
781
+ }
782
+ const said = takeSaid(t);
783
+ if (said)
784
+ journal.message({ type: 'message', role: 'assistant', text: said });
785
+ 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
+ }
792
+ const status = result.status === 'completed' ? 'completed' : result.status === 'interrupted' ? 'interrupted' : 'failed';
793
+ const error = status === 'completed' ? undefined : (t.error ?? result.error?.message ?? undefined);
794
+ return { status, ...(error ? { error } : {}) };
795
+ };
796
+ const endTurn = async (outcome) => {
797
+ code.turnEnded();
798
+ journal.message({ type: 'turn', ...outcome });
799
+ await guard(journal.flush());
800
+ ledger.turnEnded();
801
+ // 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
+ if (invocation.notesShown && !invocation.notesAcknowledged && machine.notes.length) {
803
+ await guard(acknowledgeInDrive(ctx, invocation.notesKey));
804
+ invocation.notesAcknowledged = true;
805
+ }
806
+ ctx.live({ type: 'idle' });
807
+ // The Drive as the turn left it, for the Files panel (best effort: bounded by the invocation's time left).
808
+ await driveFiles.snapshot();
809
+ };
810
+ /**
811
+ * A turn of the session: Codex's turn, then one more Codex turn per
812
+ * steer it refused because its turn had just ended. Those steers were
813
+ * placed in this turn, so the turn ends only after them: a crash in
814
+ * one of them is recovered as part of it.
815
+ */
816
+ const turn = async (text, clientId) => {
817
+ let outcome = await codexTurn(text, clientId);
818
+ for (let s = carry.shift(); s; s = carry.shift())
819
+ outcome = await codexTurn(s.text ?? '', s.id);
820
+ await endTurn(outcome);
821
+ };
822
+ // Steers that arrive while a turn runs go into it (`turn/steer`).
823
+ const steer = (t) => {
824
+ let stopped = false;
825
+ let running;
826
+ const check = () => {
827
+ if (stopped || running || !t.id)
828
+ return;
829
+ running = (async () => {
830
+ try {
831
+ await ctx.refresh();
832
+ for (const s of ctx.pending().filter((x) => x.kind === 'steer')) {
833
+ if (stopped)
834
+ return;
835
+ await invocation.fg.run(() => placeSubmissions(ctx, [s]));
836
+ try {
837
+ await rpc.request('turn/steer', { threadId, expectedTurnId: t.id, clientUserMessageId: s.id, input: [{ type: 'text', text: s.text ?? '', text_elements: [] }] });
838
+ }
839
+ catch {
840
+ carry.push(s);
841
+ }
842
+ }
843
+ }
844
+ catch (err) {
845
+ // A placement the log refused (a withdraw won it, the drive lost the session): stop.
846
+ if (!ctx.signal.aborted)
847
+ ctx.halt?.(err);
848
+ }
849
+ finally {
850
+ running = undefined;
851
+ }
852
+ })();
853
+ };
854
+ const off = ctx.onHint?.((h) => {
855
+ if (h.eventType === 'hook_received' || h.eventType === 'reconnect')
856
+ check();
857
+ });
858
+ const timer = setInterval(check, options.inboxPollMs ?? (off ? 5000 : 500));
859
+ return {
860
+ async stop() {
861
+ stopped = true;
862
+ off?.();
863
+ clearInterval(timer);
864
+ await running;
865
+ },
866
+ };
867
+ };
868
+ // An earlier invocation that ended before its snapshot: the manifest catches up first.
869
+ await driveFiles.catchUp();
870
+ // A turn a crash cut off.
871
+ const note = recoveryNote(ctx.state());
872
+ // With no recovery note, calls the rollout left unanswered still get their outputs before any turn is sent.
873
+ if (!note && resume)
874
+ await code.repairUnnoted(lines);
875
+ if (note) {
876
+ const summary = summarizeRollout(lines);
877
+ const owed = owedSubmissions(ctx.state(), note.turn.placed, summary.clientIds);
878
+ if (resume && summary.dangling.length > 0) {
879
+ // Calls the rollout has no output for get theirs from the log.
880
+ const items = summary.dangling.map((c) => ({ type: 'function_call_output', call_id: c.callId, output: repairOutput(ctx.state(), c) }));
881
+ await code.recoverItems(items, summary.dangling, lines, note.turn.since);
882
+ await guard(rpc.request('thread/inject_items', { threadId, items }));
883
+ await guard(synced());
884
+ }
885
+ // Codex finished the turn (its last turn was this one's, and completed): only the end was not in the log yet.
886
+ const finished = resume &&
887
+ summary.idle &&
888
+ summary.lastTurn === 'completed' &&
889
+ summary.dangling.length === 0 &&
890
+ owed.length === 0 &&
891
+ [...summary.lastTurnClientIds].some((id) => note.turn.placed.includes(id) || id.startsWith(RECOVER_PREFIX));
892
+ if (finished) {
893
+ const last = summary.lastAgentMessage;
894
+ const said = note.turn.entries.some((e) => e.data.type === 'message' && e.data.role === 'assistant' && e.data.text === last);
895
+ if (last && !said)
896
+ journal.message({ type: 'message', role: 'assistant', text: last });
897
+ await endTurn({ status: 'completed' });
898
+ }
899
+ else {
900
+ let text = note.text;
901
+ if (owed.length) {
902
+ text += `\n\nMessages that may not have reached you before the interruption:\n${owed.map((s) => quote(s.text ?? '')).join('\n')}`;
903
+ }
904
+ text = await code.resumeTurn(note, owed);
905
+ const n = transcriptOf(ctx.state()).filter((r) => r.data.type === 'message' && r.data.role === 'user').length;
906
+ journal.message({ type: 'message', role: 'user', text: notes ? `${notes}\n\n${text}` : text, synthetic: 'recovery' });
907
+ await placeSubmissions(ctx, note.pending);
908
+ // Codex answers again from the interrupted step: what a reader saw of its reply is replaced by what the log kept.
909
+ ctx.live(restartEvent(note.turn));
910
+ // Its client id names the submissions the note carries: once Codex has recorded it, they are not owed again.
911
+ await turn(text, recoveryClientId(n, [...owed, ...note.pending]));
912
+ }
913
+ }
914
+ // The inbox: one submission per turn, steers mid-turn.
915
+ for (;;) {
916
+ await guard(ctx.refresh());
917
+ const [s] = ctx.pending();
918
+ if (!s)
919
+ break;
920
+ await placeSubmissions(ctx, [s]);
921
+ await turn(s.text ?? '', s.id);
922
+ }
923
+ // A model step a crash left open that no request of this drive made again: closed.
924
+ await guard(steps.settleAbandoned());
925
+ // Done: let app-server exit, keep whatever it wrote last (its exit is no failure now).
926
+ child.end();
927
+ await Promise.race([child.exited, sleep(2000)]);
928
+ if (!ctx.signal.aborted && !machine.signal.aborted) {
929
+ const live = (p) => Promise.race([p, stopped, lost]);
930
+ await live(synced());
931
+ await live(journal.flush());
932
+ }
933
+ }
934
+ finally {
935
+ if (poll)
936
+ clearInterval(poll);
937
+ for (const t of clamps.values())
938
+ clearTimeout(t);
939
+ tail?.close();
940
+ // Whether the link was lost before this drive let go of it (a re-attach), and what the mirror read meanwhile, in the log.
941
+ held.lost = machine.signal.aborted;
942
+ // The app's tools still running in the Function (an email confirming) settle first, within the invocation: the next drive reads their real outcome, and no retry runs beside them.
943
+ if (invocation.inflight.size && !ctx.signal.aborted) {
944
+ let timer;
945
+ await Promise.race([Promise.allSettled([...invocation.inflight]), new Promise((r) => (timer = setTimeout(r, Math.max(0, deadline - Date.now()))))]);
946
+ clearTimeout(timer);
947
+ }
948
+ if (held.lost && !ctx.signal.aborted)
949
+ await journal.flush().catch(() => { });
950
+ ledger.close();
951
+ // No model step outlives the drive.
952
+ await steps.close();
953
+ // Nothing the model started outlives the drive (§5.4 "Ending an invocation"): the session's processes are killed, the VM and the Drive stay.
954
+ if (proc?.alive())
955
+ proc.kill('SIGKILL');
956
+ await machine.close().catch(() => { });
957
+ // A command or patch Codex never reported (it died mid-call, the link
958
+ // was lost, or the turn ended with a command still running):
959
+ // interrupted, "may or may not have taken effect", after the kill. A
960
+ // stopped drive's are left to the kernel.
961
+ if (builtins?.size)
962
+ await builtins.interruptAll('the command was still running when its drive ended: it may or may not have taken effect');
963
+ }
964
+ }
965
+ /**
966
+ * Codex's sandbox for its commands, decided once per session: the first
967
+ * drive with the built-ins runs bubblewrap's self-test in the VM and
968
+ * records its verdict in the log (`codex.sandbox`); every later drive keeps
969
+ * it, so nothing the model leaves on the Drive (or a slow VM) can move the
970
+ * session to `danger-full-access`. On a later VM where bwrap fails, Codex's
971
+ * commands fail closed: its offer to rerun one without the sandbox is
972
+ * declined.
973
+ */
974
+ async function sandboxVerdict(ctx, spec, machine, journal) {
975
+ const recorded = journal.records(SANDBOX_STREAM).find((r) => r.data?.sandboxMode === 'workspace-write' || r.data?.sandboxMode === 'danger-full-access')?.data?.sandboxMode;
976
+ if (recorded === 'workspace-write' || recorded === 'danger-full-access')
977
+ return recorded;
978
+ const verdict = await selfTest(ctx, spec, machine);
979
+ journal.append(SANDBOX_STREAM, verdict);
980
+ return verdict.sandboxMode;
981
+ }
982
+ /**
983
+ * Codex's bubblewrap self-test in the VM (P0.10, §12 question 6): `codex
984
+ * sandbox` with the workspace-write profile, as the session's user, in an
985
+ * empty directory of its own (the Drive has no say in it). Exit 0:
986
+ * `workspace-write`. A definite failure (a non-zero exit): `danger-full-
987
+ * access` (the VM is the boundary, and holds no credential). One that
988
+ * didn't finish or couldn't start is tried once more, then fails the turn:
989
+ * it is no verdict.
990
+ */
991
+ async function selfTest(ctx, spec, machine) {
992
+ // A CODEX_HOME and a working directory of its own, under the cache dir: nothing it writes is near the session's.
993
+ const selfHome = 'codex-selftest';
994
+ await machine.files.upload('cache', [
995
+ { path: `${selfHome}/home/.keep`, bytes: new Uint8Array() },
996
+ { path: `${selfHome}/cwd/.keep`, bytes: new Uint8Array() },
997
+ ]);
998
+ const dir = `${machine.dirs.cache}/${selfHome}`;
999
+ let why = '';
1000
+ for (let attempt = 1; attempt <= 2; attempt++) {
1001
+ let test;
1002
+ try {
1003
+ test = await machine.spawn({
1004
+ command: codex.command,
1005
+ args: [...codex.args, 'sandbox', '-P', ':workspace', '-C', `${dir}/cwd`, '--', 'true'],
1006
+ cwd: `${dir}/cwd`,
1007
+ signal: ctx.signal,
1008
+ env: { ...(spec.env ?? {}), HOME: machine.dirs.home, CODEX_HOME: `${dir}/home`, TMPDIR: machine.dirs.tmp, NO_COLOR: '1' },
1009
+ });
1010
+ }
1011
+ catch (err) {
1012
+ if (ctx.signal.aborted || machine.signal.aborted)
1013
+ throw err;
1014
+ why = `it did not start (${String(err?.message ?? err).slice(0, 120)})`;
1015
+ continue;
1016
+ }
1017
+ test.end();
1018
+ void (async () => {
1019
+ for await (const _ of test.lines())
1020
+ ;
1021
+ })().catch(() => { });
1022
+ let timer;
1023
+ const exit = await Promise.race([test.exited, new Promise((r) => (timer = setTimeout(r, 20_000, undefined)))]);
1024
+ clearTimeout(timer);
1025
+ if (!exit) {
1026
+ test.kill('SIGKILL');
1027
+ await test.exited;
1028
+ }
1029
+ if (exit?.code === 0)
1030
+ return { sandboxMode: 'workspace-write' };
1031
+ if (typeof exit?.code === 'number') {
1032
+ const reason = `bubblewrap's self-test failed (exit code ${exit.code})`;
1033
+ log("codex: bubblewrap's self-test failed in the VM: commands run with danger-full-access (the VM is the boundary)", { reason, stderr: test.stderrTail().slice(-500) });
1034
+ return { sandboxMode: 'danger-full-access', reason };
1035
+ }
1036
+ why = exit ? `it was killed (${exit.signal})` : 'it did not finish in 20 s';
1037
+ log("codex: bubblewrap's self-test gave no verdict", { attempt, why });
1038
+ }
1039
+ throw new Unavailable(`Codex's sandbox self-test gave no verdict in the session's sandbox: ${why}.`, {
1040
+ code: 'unavailable',
1041
+ hint: 'The VM may be slow to start: the next message retries it.',
1042
+ });
1043
+ }
1044
+ }
1045
+ /** The client id prefix of a recovery note's turn: `recover:<n>`, then `:<id>,<id>` for the submissions it carries. */
1046
+ export const RECOVER_PREFIX = 'recover:';
1047
+ /** The client id a recovery note's turn is sent with. */
1048
+ export function recoveryClientId(n, carried) {
1049
+ return `${RECOVER_PREFIX}${n}${carried.length ? `:${carried.map((s) => s.id).join(',')}` : ''}`;
1050
+ }
1051
+ /**
1052
+ * Placed submissions of the open turn that Codex never recorded: no user
1053
+ * message in the rollout has their id as its `client_id`, alone or among
1054
+ * the ids a recovery note's turn carried. A crash between placing and
1055
+ * sending, or a steer it accepted but had not written yet.
1056
+ */
1057
+ export function owedSubmissions(state, placed, clientIds) {
1058
+ const recorded = new Set();
1059
+ for (const id of clientIds) {
1060
+ recorded.add(id);
1061
+ if (!id.startsWith(RECOVER_PREFIX))
1062
+ continue;
1063
+ const at = id.indexOf(':', RECOVER_PREFIX.length);
1064
+ if (at >= 0)
1065
+ for (const carried of id.slice(at + 1).split(','))
1066
+ recorded.add(carried);
1067
+ }
1068
+ return placed
1069
+ .filter((id) => !recorded.has(id))
1070
+ .map((id) => state.submissions.find((s) => s.id === id))
1071
+ .filter((s) => !!s && (s.kind === 'prompt' || s.kind === 'steer' || s.kind === 'followUp'));
1072
+ }
1073
+ /**
1074
+ * The output injected for a call the rollout left dangling, from what the
1075
+ * log knows: the committed result (exactly once), the recorded failure, or
1076
+ * that it never started.
1077
+ */
1078
+ export function repairOutput(state, call) {
1079
+ const e = state.effects.get(toolKey(call.callId));
1080
+ // Input to a running command (unified exec): that process went with the drive that ran it.
1081
+ if (!e && call.name === 'write_stdin')
1082
+ return 'Interrupted: the session stopped, and the process this input was for was stopped with it. Check the state its command left before running it again.';
1083
+ if (!e)
1084
+ return 'Not executed: the session stopped before this call started. Call it again if it is still needed.';
1085
+ if (e.status === 'completed')
1086
+ return typeof e.output === 'string' ? e.output : JSON.stringify(e.output);
1087
+ if (recoveryNote(state)?.calls.find((c) => c.callId === call.callId)?.status === 'retryable')
1088
+ return 'Interrupted before it reported a result. It is safe to repeat.';
1089
+ if (e.status === 'failed' && e.error) {
1090
+ if (e.error.interrupted && e.replay === 'safe')
1091
+ return 'Interrupted before it reported a result. It is safe to repeat.';
1092
+ return failureText(e.error);
1093
+ }
1094
+ return 'Interrupted: the session stopped while this call ran. It may have taken effect: check before repeating it.';
1095
+ }
1096
+ const quote = (t) => t
1097
+ .split('\n')
1098
+ .map((l) => `> ${l}`)
1099
+ .join('\n');
1100
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));