@lyupro/codex-bridge 0.5.3 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,398 +1,268 @@
1
- /**
2
- * Everything about invoking the `codex` CLI: which flags a run gets, whether the CLI is
3
- * there at all, and how its JSONL stdout reaches events.jsonl while stderr stays separate.
4
- *
5
- * The flag sets below are the ones the three agent files carried before, verbatim.
6
- * Sandboxes especially must not drift: codex-scout and codex-review are read-only through an
7
- * explicit --sandbox read-only, and codex-build needs workspace-write and must NOT get
8
- * --ignore-user-config. What --ignore-user-config buys the two read-only agents is isolation
9
- * from the operator's config, never the sandbox itself — reading it as the read-only guarantee
10
- * is how the 2026-08-23 breakage stayed misdiagnosed as "read-only is broken" (see
11
- * sandbox-flags.mjs for what actually stops a run from starting a process on Windows).
12
- */
13
- import fs from 'node:fs';
14
- import path from 'node:path';
15
- import { spawn, spawnSync } from 'node:child_process';
16
- import { createHeartbeat, HEARTBEAT_INTERVAL_MS } from '../heartbeat.mjs';
17
- import { writeFailure } from '../write-meta.mjs';
18
- import { MAX_LOG } from './git-state.mjs';
19
- import { CLEAN_ENV, RUN_ENV } from './run-env.mjs';
20
- import { platformSandboxArgs } from './sandbox-flags.mjs';
21
-
22
- // Thirty seconds, not a fraction of one: after `exit` the pipe still holds whatever Codex wrote
23
- // last, and that tail carries `item.completed` — the result the verdict is read from. A quarter
24
- // of a second is enough to lose it on a loaded Windows host, turning a finished run into "the run
25
- // left no event". The grace exists to bound a grandchild holding stdio open forever (2026-08-06,
26
- // run 2026-08-06_204007_build waited 25 minutes), and thirty seconds bounds that just as well.
27
- const STDIO_DRAIN_GRACE_MS = 30_000;
28
-
29
- /**
30
- * An argument cmd.exe cannot be handed safely, or undefined. `%` is fatal because cmd
31
- * expands variables even inside quotes. The launcher asks first, so the refusal costs
32
- * nothing; the worker asks again on its own copy, because a process whose stderr goes
33
- * nowhere must not be the one to discover this.
34
- */
35
- export const unsafeForCmd = (args) =>
36
- ['codex', ...args].find((a) => a.includes('%') || a.includes('"'));
37
-
38
- /**
39
- * Stop the process that owns the Codex invocation. On Windows that process is cmd.exe, so
40
- * child.kill() would reap only the shell and leave Codex spending quota as its grandchild —
41
- * the exact orphan left by the killed caller on 2026-07-31. taskkill's tree flag is required;
42
- * POSIX has no shell wrapper here, so killing the child itself is the honest boundary.
43
- */
44
- export function stopCodex(child, onWindows = process.platform === 'win32') {
45
- if (!onWindows) {
46
- child.kill('SIGKILL');
47
- return;
48
- }
49
- const killed = spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], {
50
- stdio: 'ignore',
51
- windowsHide: true,
52
- });
53
- if (killed.error || killed.status !== 0) child.kill();
54
- }
55
-
56
- /**
57
- * Windows npm ships `codex` as codex.cmd, and Node refuses to spawn .cmd without a
58
- * shell. One command line through cmd.exe keeps a single code path; every argument is
59
- * quoted here, and unsafeForCmd() has already refused the ones that cannot be.
60
- *
61
- * Stdout is streamed, not collected: spawnSync kept every byte in memory and wrote the file
62
- * only on return, so a worker killed at minute twelve left events.jsonl missing entirely and
63
- * the run became unexplainable (2026-07-31, run 114736). Now whatever Codex has already said
64
- * is on disk, and the task text is pushed into stdin by hand since there is no `input` option
65
- * outside spawnSync. MAX_LOG stays the ceiling; past it the stream is cut rather than the run
66
- * being killed — a huge stream is a diagnosis, not a reason to lose the work. stderr has its
67
- * own bounded file because text outside the JSONL protocol must remain distinguishable from
68
- * protocol events, and a line cut in half cannot be parsed back safely.
69
- */
70
- export function runCodex(args, taskText, eventsPath, budgetMinutes, graceMs = STDIO_DRAIN_GRACE_MS) {
71
- const onWindows = process.platform === 'win32';
72
- const deadlineMs =
73
- typeof budgetMinutes === 'number' && Number.isFinite(budgetMinutes) && budgetMinutes > 0
74
- ? budgetMinutes * 60 * 1000
75
- : null;
76
- let exited = false;
77
- const heartbeat = createHeartbeat(path.dirname(eventsPath));
78
- const stampHeartbeat = () => {
79
- if (!exited) heartbeat.stamp();
80
- };
81
- const stderrLog = fs.createWriteStream(path.join(path.dirname(eventsPath), 'stderr.log'), { flags: 'a' });
82
- const eventsLog = fs.createWriteStream(eventsPath, { flags: 'a' });
83
- const appendTo = (stream, label) => {
84
- let written = 0;
85
- let cut = false;
86
- return (chunk) => {
87
- stampHeartbeat();
88
- const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8');
89
- if (written >= MAX_LOG) {
90
- if (!cut) {
91
- cut = true;
92
- stream.write(`\nrun-codex: ${label} truncated at ${MAX_LOG} bytes; further output is not saved\n`);
93
- }
94
- return;
95
- }
96
- const room = MAX_LOG - written;
97
- const slice = buf.length > room ? buf.subarray(0, room) : buf;
98
- written += slice.length;
99
- stream.write(slice);
100
- };
101
- };
102
- const appendStderr = appendTo(stderrLog, 'stderr log');
103
- const appendEvents = (() => {
104
- let pending = Buffer.alloc(0);
105
- let written = 0;
106
- let cut = false;
107
- const append = (chunk) => {
108
- stampHeartbeat();
109
- if (cut) return;
110
- const incoming = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8');
111
- pending = pending.length ? Buffer.concat([pending, incoming]) : incoming;
112
- let newline = pending.indexOf(0x0a);
113
- while (newline !== -1) {
114
- const line = pending.subarray(0, newline + 1);
115
- pending = pending.subarray(newline + 1);
116
- if (written + line.length > MAX_LOG) {
117
- cut = true;
118
- pending = Buffer.alloc(0);
119
- return;
120
- }
121
- written += line.length;
122
- eventsLog.write(line);
123
- newline = pending.indexOf(0x0a);
124
- }
125
- if (pending.length > MAX_LOG - written) {
126
- cut = true;
127
- pending = Buffer.alloc(0);
128
- }
129
- };
130
- const finish = () => {
131
- if (!cut && pending.length && written + pending.length <= MAX_LOG) eventsLog.write(pending);
132
- pending = Buffer.alloc(0);
133
- };
134
- return { append, finish };
135
- })();
136
-
137
- let child;
138
- if (onWindows) {
139
- // Thrown rather than died: in the worker a bare exit would leave the run open, while a
140
- // throw goes through the crash handler and closes it with meta.json like any failure.
141
- const bad = unsafeForCmd(args);
142
- if (bad) throw new Error(`argument unsafe for cmd.exe (contains % or "): ${bad}`);
143
- const cmdline = ['codex', ...args].map((a) => (/[\s&|<>^]/.test(a) ? `"${a}"` : a)).join(' ');
144
- child = spawn(process.env.ComSpec || 'cmd.exe', ['/d', '/s', '/c', `"${cmdline}"`], {
145
- windowsVerbatimArguments: true,
146
- windowsHide: true,
147
- stdio: ['pipe', 'pipe', 'pipe'],
148
- });
149
- } else {
150
- child = spawn('codex', args, { stdio: ['pipe', 'pipe', 'pipe'] });
151
- }
152
-
153
- return new Promise((resolve) => {
154
- let failed = false;
155
- let deadlineTimer;
156
- let heartbeatTimer;
157
- let stdioGraceTimer;
158
- let stoppedOnDeadline = false;
159
- let exitCode;
160
- let settled = false;
161
- let elapsedMs = 0;
162
- const startedAt = Date.now();
163
- stampHeartbeat();
164
- heartbeatTimer = setInterval(stampHeartbeat, HEARTBEAT_INTERVAL_MS);
165
- child.stdout.on('data', appendEvents.append);
166
- child.stdout.on('end', appendEvents.finish);
167
- child.stderr.on('data', (chunk) => {
168
- appendStderr(chunk);
169
- });
170
- // A log file that cannot be opened must not leave Codex spending quota unattended. Without
171
- // a listener the stream's 'error' event throws inside the worker, and the crash handler
172
- // closes the run folder while the CLI keeps running — the orphan of 2026-07-31 with an
173
- // extra step. The run dies, but it dies with its child: killing first, recording second.
174
- const onStreamError = (which) => (err) => {
175
- failed = true;
176
- const note = `\nrun-codex: cannot write ${which}: ${err.message}\n`;
177
- if (which !== 'stderr.log' && stderrLog.writable) stderrLog.write(note);
178
- stopCodex(child, onWindows);
179
- };
180
- stderrLog.on('error', onStreamError('stderr.log'));
181
- eventsLog.on('error', onStreamError('events.jsonl'));
182
- child.on('error', (err) => {
183
- failed = true;
184
- appendStderr(`\nrun-codex: ${err.message}\n`);
185
- });
186
- // Codex that dies before reading the order leaves an EPIPE here; the exit code and the
187
- // log already say what happened, and an unhandled stream error would replace that with
188
- // a crash of the runner.
189
- child.stdin.on('error', () => {});
190
- child.stdin.end(Buffer.from(taskText, 'utf8'));
191
- if (deadlineMs !== null) {
192
- deadlineTimer = setTimeout(() => {
193
- const elapsed = Date.now() - startedAt;
194
- // The tree is stopped either way — a grandchild still holding stdio is exactly what
195
- // the budget exists to end — but only a process that was still alive was killed by
196
- // the deadline, and only that run may say so.
197
- if (!exited) {
198
- stoppedOnDeadline = true;
199
- elapsedMs = elapsed;
200
- stderrLog.write(
201
- `\nrun-codex: run stopped on its deadline after ${elapsed} ms (budget ${deadlineMs} ms)\n`,
202
- );
203
- }
204
- stopCodex(child, onWindows);
205
- }, deadlineMs);
206
- }
207
- // A stream that already failed never calls back from end(), so waiting on both callbacks in
208
- // sequence hangs the worker until its own deadline — the run then costs a full budget and
209
- // answers nothing. Closing is best-effort; the verdict is not.
210
- const close = (stream) =>
211
- new Promise((done) => {
212
- if (stream.destroyed || stream.errored) {
213
- stream.destroy();
214
- done();
215
- return;
216
- }
217
- stream.end(done);
218
- });
219
-
220
- // 'exit' fires when Codex is gone; 'close' waits for stdio, which the 2026-08-06 incident
221
- // showed a grandchild can hold open forever. A bounded drain grace keeps normal logs intact,
222
- // then closes the run with an explicit marker instead of waiting for an unbounded pipe.
223
- const finish = async (code, stdioDrained) => {
224
- if (settled) return;
225
- settled = true;
226
- if (deadlineTimer) clearTimeout(deadlineTimer);
227
- if (heartbeatTimer) clearInterval(heartbeatTimer);
228
- if (stdioGraceTimer) clearTimeout(stdioGraceTimer);
229
- if (!stoppedOnDeadline) elapsedMs = Date.now() - startedAt;
230
- const exit = failed || code === null ? 1 : code;
231
- appendEvents.finish();
232
- if (!stdioDrained) {
233
- try { child.stdout.destroy(); } catch {}
234
- try { child.stderr.destroy(); } catch {}
235
- }
236
- await close(stderrLog);
237
- await close(eventsLog);
238
- resolve({ exit, stoppedOnDeadline, elapsedMs, stdioDrained });
239
- };
240
-
241
- child.on('exit', (code) => {
242
- exited = true;
243
- exitCode = code;
244
- if (deadlineTimer) clearTimeout(deadlineTimer);
245
- if (heartbeatTimer) clearInterval(heartbeatTimer);
246
- // The grace is an argument only so tests can prove the fallback without waiting it out;
247
- // a run never passes one, because a per-run grace is a second place to configure a
248
- // contract that must be identical for every run.
249
- stdioGraceTimer = setTimeout(() => finish(exitCode, false), graceMs);
250
- });
251
- child.on('close', (code) => finish(code, true));
252
- });
253
- }
254
-
255
- /**
256
- * Codex missing or not authorised is a deterministic FAIL, never a reason to improvise.
257
- * Runs after the folder exists so this failure is recorded like any other.
258
- */
259
- export function requireCodex(runDir, agent) {
260
- const probe = spawnSync(
261
- process.platform === 'win32' ? process.env.ComSpec || 'cmd.exe' : 'codex',
262
- process.platform === 'win32' ? ['/d', '/s', '/c', 'codex --version'] : ['--version'],
263
- { encoding: 'utf8' },
264
- );
265
- if (probe.error || probe.status !== 0) {
266
- const why = (probe.stderr || probe.error?.message || 'codex --version is not responding').trim();
267
- const { reply } = writeFailure(runDir, agent, `Codex CLI unavailable: ${why}`, [
268
- 'Operator check: codex --version (and codex login if authorization is rejected)',
269
- ], true);
270
- console.log(reply);
271
- process.exit(1);
272
- }
273
- }
274
-
275
- /**
276
- * Which model runs a mode, and how deep it reasons.
277
- *
278
- * Three sources, in this order: what the dispatcher asked for this one task, the mode's
279
- * configured profile, and finally a depth to fall back on. The order is the whole point —
280
- * pinning a model without its depth leaves every run at the fallback, which is how a mode
281
- * configured for maximum reasoning would quietly keep working at the shallowest setting.
282
- */
283
- const FALLBACK_EFFORT = 'medium';
284
-
285
- /**
286
- * A run is one worker, not a team it recruits for itself.
287
- *
288
- * Codex can spawn subagents when a prompt asks it to, and their edits land in the same
289
- * worktree — so they arrive in the snapshot as the run's own work, outside the scope check
290
- * that grades it, on quota nobody budgeted. The prompts say not to; this is why they cannot.
291
- */
292
- const NO_SUBAGENTS = ['-c', 'agents.enabled=false'];
293
-
294
- /**
295
- * Which configured mode an agent is. One table, because the launcher needs the same answer to
296
- * pick a run's time budget: a second copy of this mapping is a second place to forget a mode.
297
- */
298
- export const runMode = (agent) =>
299
- ({
300
- 'codex-scout': 'scout',
301
- 'codex-build': 'build',
302
- 'codex-review': 'review',
303
- })[agent];
304
-
305
- function runProfile(opts) {
306
- const mode = runMode(opts.agent);
307
- // opts.models is how tests state a configuration; a real run reads the one loaded for it.
308
- const configured = (opts.models || RUN_ENV?.models || {})[mode] || {};
309
- return {
310
- model: configured.model || '',
311
- effort: opts.effort || configured.effort || FALLBACK_EFFORT,
312
- };
313
- }
314
-
315
- export function codexArgs(opts, runDir, isGitRepo) {
316
- const schema = path.join(runDir, 'schema.json');
317
- const profile = runProfile(opts);
318
- const effort = `model_reasoning_effort=${profile.effort}`;
319
- const modelArgs = profile.model ? ['-m', profile.model] : [];
320
- if (opts.agent === 'codex-scout') {
321
- return [
322
- 'exec',
323
- '--json',
324
- ...CLEAN_ENV,
325
- '--ignore-user-config',
326
- '-c',
327
- effort,
328
- ...NO_SUBAGENTS,
329
- ...platformSandboxArgs(),
330
- ...modelArgs,
331
- '--sandbox',
332
- 'read-only',
333
- '--skip-git-repo-check',
334
- '-C',
335
- opts.repo,
336
- '--output-schema',
337
- schema,
338
- '-o',
339
- path.join(runDir, 'result.json'),
340
- '-',
341
- ];
342
- }
343
- if (opts.agent === 'codex-build') {
344
- // --ignore-user-config is deliberately absent: with it Codex forces read-only and
345
- // every edit is rejected ("writing is blocked by read-only sandbox").
346
- return [
347
- 'exec',
348
- '--json',
349
- ...CLEAN_ENV,
350
- '-c',
351
- effort,
352
- ...NO_SUBAGENTS,
353
- ...platformSandboxArgs(),
354
- ...modelArgs,
355
- '--sandbox',
356
- 'workspace-write',
357
- '-C',
358
- opts.repo,
359
- ...(isGitRepo ? [] : ['--skip-git-repo-check']),
360
- '--output-schema',
361
- schema,
362
- '-o',
363
- path.join(runDir, 'result.json'),
364
- '-',
365
- ];
366
- }
367
- // codex-review deliberately does NOT use the `review` subcommand. Two of its traits
368
- // break the contract this design rests on: it rejects a scope flag together with a
369
- // prompt ("the argument '--uncommitted' cannot be used with '[PROMPT]'"), so task.md
370
- // was silently discarded and the review rules never arrived; and it ignores
371
- // --output-schema, writing prose into -o, so the old JSON parsing of review.json could
372
- // only ever fail — which is what pushed a dispatcher into reviewing the diff itself.
373
- //
374
- // Plain `codex exec` honours the schema (proven by codex-scout), so the review comes
375
- // back as machine-checkable JSON. Scope lives in the prompt as a file list plus the
376
- // exact diff command computed by reviewScope(). Read-only through
377
- // --ignore-user-config, same as scout: review never needs write access.
378
- return [
379
- 'exec',
380
- '--json',
381
- ...CLEAN_ENV,
382
- '--ignore-user-config',
383
- '-c',
384
- effort,
385
- ...NO_SUBAGENTS,
386
- ...platformSandboxArgs(),
387
- ...modelArgs,
388
- '--sandbox',
389
- 'read-only',
390
- '-C',
391
- opts.repo,
392
- '--output-schema',
393
- schema,
394
- '-o',
395
- path.join(runDir, 'review.json'),
396
- '-',
397
- ];
398
- }
1
+ /**
2
+ * Invoking the `codex` CLI: starting it, stopping its whole tree, telling whether it is there at
3
+ * all, and keeping its JSONL stdout in events.jsonl while stderr stays separate.
4
+ *
5
+ * Which flags a run gets is the neighbouring codex-args.mjs: this file starts the process and
6
+ * stops it, and knows nothing about what the arguments mean. The two were one module until it
7
+ * outgrew the size limit, and the seam is the honest one — "how we run Codex" against "what we
8
+ * ask it to run".
9
+ */
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { spawn, spawnSync } from 'node:child_process';
13
+ import { createHeartbeat, HEARTBEAT_INTERVAL_MS } from '../heartbeat.mjs';
14
+ import { writeFailure } from '../write-meta.mjs';
15
+ import { MAX_LOG } from './git-state.mjs';
16
+
17
+ // Thirty seconds, not a fraction of one: after `exit` the pipe still holds whatever Codex wrote
18
+ // last, and that tail carries `item.completed` — the result the verdict is read from. A quarter
19
+ // of a second is enough to lose it on a loaded Windows host, turning a finished run into "the run
20
+ // left no event". The grace exists to bound a grandchild holding stdio open forever (2026-08-06,
21
+ // run 2026-08-06_204007_build waited 25 minutes), and thirty seconds bounds that just as well.
22
+ const STDIO_DRAIN_GRACE_MS = 30_000;
23
+
24
+ /**
25
+ * An argument cmd.exe cannot be handed safely, or undefined. `%` is fatal because cmd
26
+ * expands variables even inside quotes. The launcher asks first, so the refusal costs
27
+ * nothing; the worker asks again on its own copy, because a process whose stderr goes
28
+ * nowhere must not be the one to discover this.
29
+ */
30
+ export const unsafeForCmd = (args) =>
31
+ ['codex', ...args].find((a) => a.includes('%') || a.includes('"'));
32
+
33
+ /**
34
+ * Stop the process that owns the Codex invocation. On Windows that process is cmd.exe, so
35
+ * child.kill() would reap only the shell and leave Codex spending quota as its grandchild —
36
+ * the exact orphan left by the killed caller on 2026-07-31. taskkill's tree flag is required;
37
+ * POSIX has no shell wrapper here, so killing the child itself is the honest boundary.
38
+ */
39
+ export function stopCodex(child, onWindows = process.platform === 'win32') {
40
+ if (!onWindows) {
41
+ child.kill('SIGKILL');
42
+ return;
43
+ }
44
+ const killed = spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], {
45
+ stdio: 'ignore',
46
+ windowsHide: true,
47
+ });
48
+ if (killed.error || killed.status !== 0) child.kill();
49
+ }
50
+
51
+ /**
52
+ * Windows npm ships `codex` as codex.cmd, and Node refuses to spawn .cmd without a
53
+ * shell. One command line through cmd.exe keeps a single code path; every argument is
54
+ * quoted here, and unsafeForCmd() has already refused the ones that cannot be.
55
+ *
56
+ * Stdout is streamed, not collected: spawnSync kept every byte in memory and wrote the file
57
+ * only on return, so a worker killed at minute twelve left events.jsonl missing entirely and
58
+ * the run became unexplainable (2026-07-31, run 114736). Now whatever Codex has already said
59
+ * is on disk, and the task text is pushed into stdin by hand since there is no `input` option
60
+ * outside spawnSync. MAX_LOG stays the ceiling; past it the stream is cut rather than the run
61
+ * being killed — a huge stream is a diagnosis, not a reason to lose the work. stderr has its
62
+ * own bounded file because text outside the JSONL protocol must remain distinguishable from
63
+ * protocol events, and a line cut in half cannot be parsed back safely.
64
+ */
65
+ export function runCodex(args, taskText, eventsPath, budgetMinutes, graceMs = STDIO_DRAIN_GRACE_MS) {
66
+ const onWindows = process.platform === 'win32';
67
+ const deadlineMs =
68
+ typeof budgetMinutes === 'number' && Number.isFinite(budgetMinutes) && budgetMinutes > 0
69
+ ? budgetMinutes * 60 * 1000
70
+ : null;
71
+ let exited = false;
72
+ const heartbeat = createHeartbeat(path.dirname(eventsPath));
73
+ const stampHeartbeat = () => {
74
+ if (!exited) heartbeat.stamp();
75
+ };
76
+ const stderrLog = fs.createWriteStream(path.join(path.dirname(eventsPath), 'stderr.log'), { flags: 'a' });
77
+ const eventsLog = fs.createWriteStream(eventsPath, { flags: 'a' });
78
+ const appendTo = (stream, label) => {
79
+ let written = 0;
80
+ let cut = false;
81
+ return (chunk) => {
82
+ stampHeartbeat();
83
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8');
84
+ if (written >= MAX_LOG) {
85
+ if (!cut) {
86
+ cut = true;
87
+ stream.write(`\nrun-codex: ${label} truncated at ${MAX_LOG} bytes; further output is not saved\n`);
88
+ }
89
+ return;
90
+ }
91
+ const room = MAX_LOG - written;
92
+ const slice = buf.length > room ? buf.subarray(0, room) : buf;
93
+ written += slice.length;
94
+ stream.write(slice);
95
+ };
96
+ };
97
+ const appendStderr = appendTo(stderrLog, 'stderr log');
98
+ const appendEvents = (() => {
99
+ let pending = Buffer.alloc(0);
100
+ let written = 0;
101
+ let cut = false;
102
+ const append = (chunk) => {
103
+ stampHeartbeat();
104
+ if (cut) return;
105
+ const incoming = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8');
106
+ pending = pending.length ? Buffer.concat([pending, incoming]) : incoming;
107
+ let newline = pending.indexOf(0x0a);
108
+ while (newline !== -1) {
109
+ const line = pending.subarray(0, newline + 1);
110
+ pending = pending.subarray(newline + 1);
111
+ if (written + line.length > MAX_LOG) {
112
+ cut = true;
113
+ pending = Buffer.alloc(0);
114
+ return;
115
+ }
116
+ written += line.length;
117
+ eventsLog.write(line);
118
+ newline = pending.indexOf(0x0a);
119
+ }
120
+ if (pending.length > MAX_LOG - written) {
121
+ cut = true;
122
+ pending = Buffer.alloc(0);
123
+ }
124
+ };
125
+ const finish = () => {
126
+ if (!cut && pending.length && written + pending.length <= MAX_LOG) eventsLog.write(pending);
127
+ pending = Buffer.alloc(0);
128
+ };
129
+ return { append, finish };
130
+ })();
131
+
132
+ let child;
133
+ if (onWindows) {
134
+ // Thrown rather than died: in the worker a bare exit would leave the run open, while a
135
+ // throw goes through the crash handler and closes it with meta.json like any failure.
136
+ const bad = unsafeForCmd(args);
137
+ if (bad) throw new Error(`argument unsafe for cmd.exe (contains % or "): ${bad}`);
138
+ const cmdline = ['codex', ...args].map((a) => (/[\s&|<>^]/.test(a) ? `"${a}"` : a)).join(' ');
139
+ child = spawn(process.env.ComSpec || 'cmd.exe', ['/d', '/s', '/c', `"${cmdline}"`], {
140
+ windowsVerbatimArguments: true,
141
+ windowsHide: true,
142
+ stdio: ['pipe', 'pipe', 'pipe'],
143
+ });
144
+ } else {
145
+ child = spawn('codex', args, { stdio: ['pipe', 'pipe', 'pipe'] });
146
+ }
147
+
148
+ return new Promise((resolve) => {
149
+ let failed = false;
150
+ let deadlineTimer;
151
+ let heartbeatTimer;
152
+ let stdioGraceTimer;
153
+ let stoppedOnDeadline = false;
154
+ let exitCode;
155
+ let settled = false;
156
+ let elapsedMs = 0;
157
+ const startedAt = Date.now();
158
+ stampHeartbeat();
159
+ heartbeatTimer = setInterval(stampHeartbeat, HEARTBEAT_INTERVAL_MS);
160
+ child.stdout.on('data', appendEvents.append);
161
+ child.stdout.on('end', appendEvents.finish);
162
+ child.stderr.on('data', (chunk) => {
163
+ appendStderr(chunk);
164
+ });
165
+ // A log file that cannot be opened must not leave Codex spending quota unattended. Without
166
+ // a listener the stream's 'error' event throws inside the worker, and the crash handler
167
+ // closes the run folder while the CLI keeps running — the orphan of 2026-07-31 with an
168
+ // extra step. The run dies, but it dies with its child: killing first, recording second.
169
+ const onStreamError = (which) => (err) => {
170
+ failed = true;
171
+ const note = `\nrun-codex: cannot write ${which}: ${err.message}\n`;
172
+ if (which !== 'stderr.log' && stderrLog.writable) stderrLog.write(note);
173
+ stopCodex(child, onWindows);
174
+ };
175
+ stderrLog.on('error', onStreamError('stderr.log'));
176
+ eventsLog.on('error', onStreamError('events.jsonl'));
177
+ child.on('error', (err) => {
178
+ failed = true;
179
+ appendStderr(`\nrun-codex: ${err.message}\n`);
180
+ });
181
+ // Codex that dies before reading the order leaves an EPIPE here; the exit code and the
182
+ // log already say what happened, and an unhandled stream error would replace that with
183
+ // a crash of the runner.
184
+ child.stdin.on('error', () => {});
185
+ child.stdin.end(Buffer.from(taskText, 'utf8'));
186
+ if (deadlineMs !== null) {
187
+ deadlineTimer = setTimeout(() => {
188
+ const elapsed = Date.now() - startedAt;
189
+ // The tree is stopped either way — a grandchild still holding stdio is exactly what
190
+ // the budget exists to end — but only a process that was still alive was killed by
191
+ // the deadline, and only that run may say so.
192
+ if (!exited) {
193
+ stoppedOnDeadline = true;
194
+ elapsedMs = elapsed;
195
+ stderrLog.write(
196
+ `\nrun-codex: run stopped on its deadline after ${elapsed} ms (budget ${deadlineMs} ms)\n`,
197
+ );
198
+ }
199
+ stopCodex(child, onWindows);
200
+ }, deadlineMs);
201
+ }
202
+ // A stream that already failed never calls back from end(), so waiting on both callbacks in
203
+ // sequence hangs the worker until its own deadline — the run then costs a full budget and
204
+ // answers nothing. Closing is best-effort; the verdict is not.
205
+ const close = (stream) =>
206
+ new Promise((done) => {
207
+ if (stream.destroyed || stream.errored) {
208
+ stream.destroy();
209
+ done();
210
+ return;
211
+ }
212
+ stream.end(done);
213
+ });
214
+
215
+ // 'exit' fires when Codex is gone; 'close' waits for stdio, which the 2026-08-06 incident
216
+ // showed a grandchild can hold open forever. A bounded drain grace keeps normal logs intact,
217
+ // then closes the run with an explicit marker instead of waiting for an unbounded pipe.
218
+ const finish = async (code, stdioDrained) => {
219
+ if (settled) return;
220
+ settled = true;
221
+ if (deadlineTimer) clearTimeout(deadlineTimer);
222
+ if (heartbeatTimer) clearInterval(heartbeatTimer);
223
+ if (stdioGraceTimer) clearTimeout(stdioGraceTimer);
224
+ if (!stoppedOnDeadline) elapsedMs = Date.now() - startedAt;
225
+ const exit = failed || code === null ? 1 : code;
226
+ appendEvents.finish();
227
+ if (!stdioDrained) {
228
+ try { child.stdout.destroy(); } catch {}
229
+ try { child.stderr.destroy(); } catch {}
230
+ }
231
+ await close(stderrLog);
232
+ await close(eventsLog);
233
+ resolve({ exit, stoppedOnDeadline, elapsedMs, stdioDrained });
234
+ };
235
+
236
+ child.on('exit', (code) => {
237
+ exited = true;
238
+ exitCode = code;
239
+ if (deadlineTimer) clearTimeout(deadlineTimer);
240
+ if (heartbeatTimer) clearInterval(heartbeatTimer);
241
+ // The grace is an argument only so tests can prove the fallback without waiting it out;
242
+ // a run never passes one, because a per-run grace is a second place to configure a
243
+ // contract that must be identical for every run.
244
+ stdioGraceTimer = setTimeout(() => finish(exitCode, false), graceMs);
245
+ });
246
+ child.on('close', (code) => finish(code, true));
247
+ });
248
+ }
249
+
250
+ /**
251
+ * Codex missing or not authorised is a deterministic FAIL, never a reason to improvise.
252
+ * Runs after the folder exists so this failure is recorded like any other.
253
+ */
254
+ export function requireCodex(runDir, agent) {
255
+ const probe = spawnSync(
256
+ process.platform === 'win32' ? process.env.ComSpec || 'cmd.exe' : 'codex',
257
+ process.platform === 'win32' ? ['/d', '/s', '/c', 'codex --version'] : ['--version'],
258
+ { encoding: 'utf8' },
259
+ );
260
+ if (probe.error || probe.status !== 0) {
261
+ const why = (probe.stderr || probe.error?.message || 'codex --version is not responding').trim();
262
+ const { reply } = writeFailure(runDir, agent, `Codex CLI unavailable: ${why}`, [
263
+ 'Operator check: codex --version (and codex login if authorization is rejected)',
264
+ ], true);
265
+ console.log(reply);
266
+ process.exit(1);
267
+ }
268
+ }