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

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.
Files changed (48) hide show
  1. package/CHANGELOG.md +349 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +6 -0
  4. package/README.md +81 -0
  5. package/dist/adapter.d.ts +93 -0
  6. package/dist/adapter.js +375 -0
  7. package/dist/app-server.d.ts +53 -0
  8. package/dist/app-server.js +105 -0
  9. package/dist/binary.d.ts +31 -0
  10. package/dist/binary.js +74 -0
  11. package/dist/catalog.d.ts +35 -0
  12. package/dist/catalog.js +104 -0
  13. package/dist/code-mode.d.ts +171 -0
  14. package/dist/code-mode.js +514 -0
  15. package/dist/config.d.ts +84 -0
  16. package/dist/config.js +214 -0
  17. package/dist/facts.d.ts +2 -0
  18. package/dist/facts.js +40 -0
  19. package/dist/harness.d.ts +210 -0
  20. package/dist/harness.js +1112 -0
  21. package/dist/host/kernel.d.ts +20 -0
  22. package/dist/host/kernel.js +3 -0
  23. package/dist/host/machine.d.ts +81 -0
  24. package/dist/host/machine.js +355 -0
  25. package/dist/host/policy.d.ts +113 -0
  26. package/dist/host/policy.js +683 -0
  27. package/dist/host/process.d.ts +151 -0
  28. package/dist/host/process.js +50 -0
  29. package/dist/host/sandbox.d.ts +36 -0
  30. package/dist/host/sandbox.js +35 -0
  31. package/dist/index.d.ts +13 -0
  32. package/dist/index.js +10 -0
  33. package/dist/rollout.d.ts +96 -0
  34. package/dist/rollout.js +170 -0
  35. package/dist/schema.d.ts +14 -0
  36. package/dist/schema.js +178 -0
  37. package/dist/scripts.d.ts +218 -0
  38. package/dist/scripts.js +409 -0
  39. package/dist/tool-images.d.ts +7 -0
  40. package/dist/tool-images.js +18 -0
  41. package/dist/transcript.d.ts +20 -0
  42. package/dist/transcript.js +73 -0
  43. package/dist/verify.d.ts +62 -0
  44. package/dist/verify.js +155 -0
  45. package/dist/versions.d.ts +43 -0
  46. package/dist/versions.js +72 -0
  47. package/package.json +74 -1
  48. package/vendor/durable-harness/UPSTREAM.json +39 -0
@@ -0,0 +1,514 @@
1
+ import { boundKey, boundResult, failureText, openTurn, recoveryNote, recoverySystemNote, recoveryUserTurn, toolKey, transcriptOf } from "./host/process.js";
2
+ // cycle with harness.ts: read repairOutput only inside functions, never at module top level (pinned by "code mode and the harness
3
+ // load in either order and the repair reads repairOutput"). A host loads harness.js first, so at that point none of its const bindings is set.
4
+ import { repairOutput } from "./harness.js";
5
+ import { parseLine, summarizeRollout } from "./rollout.js";
6
+ import { callKey, completedNested, execRecovery, NESTED_CALL, outputTextOf, parkedKey, recoveredFailed, recoveredRowText, recoveryFacts, Scripts, settle, UNWATCHED, waitResumed } from "./scripts.js";
7
+ /** The stream that ties each nested call to the `exec` it ran under: `{ callId, exec, since }` (`since`: the turn it ran in), written before the call runs. */
8
+ export const NESTED_STREAM = "codex.nested";
9
+ /** The stream that records the interrupted turns whose recovery note was injected: `{ since }`, once per interrupted turn. */
10
+ export const RECOVERY_NOTE_STREAM = "codex.recovery-note";
11
+ /** A yielded exec's nested call run on a resume (recoverItems), written before it runs: a later recovery of the same turn tells
12
+ * the model's `wait` its outcome from the session's record, never running it again. */
13
+ export const RESUMED_STREAM = "codex.nested-resumed";
14
+ /** The nested calls whose outcome a resume's recovered script output tells (recoverItems): `{ since, callIds }`, written before
15
+ * that output is injected, so the turn's recovery note says the outcome is there, after a crash between the two as well. */
16
+ export const SHOWN_STREAM = "codex.nested-shown";
17
+ /** Each `exec` a recovery answered (recoverItems), directly or through the `wait` on its cell, and whether that answer tells a
18
+ * script that failed (recoveredFailed): `{ exec, failed }`, written before the answer is injected. That answer carries no status
19
+ * header for its rollout line to be read by, so the exec's end on the host's record, live or replayed after a later crash, reads this. */
20
+ export const RECOVERED_END_STREAM = "codex.exec-recovered-end";
21
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
22
+ /** How long past its yield (the time Codex waits on an `exec` or a `wait` before it answers "Script running") the code-mode host
23
+ * may leave one unanswered, no nested call of it running, before the turn fails. The first `exec` of a session also starts
24
+ * the host: Codex gives up on its handshake by itself at about 30 s, inside this. Codex itself waits on the host without
25
+ * bound: a host that took the session and then went quiet held the turn open until the invocation was stopped. */
26
+ export const HOST_SILENCE_MS = 60_000;
27
+ /** Only a custom tool call named `exec` is code mode's: a host tool that happens to be called `exec` is a function call. */
28
+ const isExec = (d) => d.type === "custom_tool_call" && d.name === "exec";
29
+ /** The item that answers a dangling call that is not an `exec`: of the kind the call asks for (the Responses API refuses an output of the
30
+ * wrong kind), a custom tool call output for a custom tool call such as `apply_patch`, a function call output for any other. */
31
+ export function withOutputKind(item, call) {
32
+ return { ...item, type: call.type === "custom_tool_call" ? "custom_tool_call_output" : "function_call_output" };
33
+ }
34
+ /** Where the turn that ended last began, as `openTurn` gave it while that turn was open: the end before its own (a `turn` entry, or a turn the
35
+ * harness could not run), or -1. With no open turn, the calls whose script could not be told that ran in it are tied to this. */
36
+ function endedTurnSince(state) {
37
+ const ends = [...transcriptOf(state).filter((r) => r.data?.type === "turn").map((r) => r.at), ...state.effectOrder.flatMap((e, i) => (e.name === "unavailable" ? [i] : []))];
38
+ ends.sort((a, b) => a - b);
39
+ return ends.length >= 2 ? ends[ends.length - 2] : -1;
40
+ }
41
+ /** What a dangling `wait` of code mode is told: it had started, on the cell named, when the session stopped and took the cell's script with it. */
42
+ export const waitStoppedText = (cell) => `The session stopped while waiting on cell ${cell}; that cell's script was cut off, and nothing was run again. Check the actual state before relying on it.`;
43
+ /** What the log holds of one nested call: the session's record, the rollout's completion line, and what the turn's recovery note
44
+ * calls it (`told`, by call id). */
45
+ /** What a script's nested call of a tool with a value was sent (scriptAnswer's text), from the tool's stored answer: the rollout
46
+ * holds that text, not the words the store keeps, so recovery compares the two. None for a tool with no value. */
47
+ function sentOf(output) {
48
+ const kept = output;
49
+ if (kept === null || typeof kept !== "object" || kept.structured === undefined)
50
+ return {};
51
+ return { sent: JSON.stringify(withImageData(kept.structured, kept.images ?? [])) };
52
+ }
53
+ /** A failed call's error as the bridge handed it (`failureText`: its message, or words saying it had none). */
54
+ const failedText = (error) => (error ? failureText(error) : "");
55
+ function factOf(state, rolled, tie, told = new Map()) {
56
+ const e = state.effects.get(toolKey(tie.callId));
57
+ const status = told.get(tie.callId);
58
+ // The bridge's record of the cut it handed Codex, if it cut the result: what settle compares the two records on.
59
+ const cut = state.effects.get(boundKey(tie.callId));
60
+ const bound = cut?.status === "completed" ? cut.output : undefined;
61
+ const lengths = bound && typeof bound.kept === "number" && typeof bound.whole === "number" ? { bound: { kept: bound.kept, whole: bound.whole } } : {};
62
+ return {
63
+ callId: tie.callId,
64
+ tool: e ? e.name.replace(/^tool\./, "") : (rolled.get(tie.callId)?.tool ?? tie.tool ?? "a tool"),
65
+ ...(e ? { store: { status: e.status === "completed" ? "completed" : e.status === "failed" ? "failed" : "started", text: e.status === "failed" ? failedText(e.error) : outputTextOf(e.output), ...(e.status === "completed" ? sentOf(e.output) : {}), ...(e.error?.interrupted ? { interrupted: true } : {}), ...lengths } } : {}),
66
+ ...(rolled.has(tie.callId) ? { rollout: rolled.get(tie.callId) } : {}),
67
+ ...(status ? { told: status } : {}),
68
+ ...(state.effects.get(parkedKey(tie.callId))?.status === "completed" ? { parked: true } : {}),
69
+ };
70
+ }
71
+ /** A recorded result that held images (bridgeTool's `{ text, images }`) as its text and a line saying how many, which are not
72
+ * shown again after the interruption; undefined for a result with none, whose repaired output stays as it is. */
73
+ export function imagesNoted(output) {
74
+ const images = output?.images;
75
+ const count = Array.isArray(images) ? images.length : 0;
76
+ if (!count)
77
+ return undefined;
78
+ return `${outputTextOf(output)}\n\nIt also returned ${count} image${count === 1 ? "" : "s"} (not shown again after the interruption).`;
79
+ }
80
+ /** `value` with `images`' data put back, in order, into its image objects (`{ type: "image", mimeType }` with no data,
81
+ * as a computer tool's value leaves them): the value whole, as serve's own script isolate gives a script. */
82
+ export function withImageData(value, images) {
83
+ let next = 0;
84
+ const fill = (part) => {
85
+ if (Array.isArray(part))
86
+ return part.map(fill);
87
+ if (part === null || typeof part !== "object")
88
+ return part;
89
+ const record = part;
90
+ if (record.type === "image" && record.data === undefined && next < images.length)
91
+ return { ...record, data: images[next++].data };
92
+ return Object.fromEntries(Object.entries(record).map(([key, entry]) => [key, fill(entry)]));
93
+ };
94
+ return fill(value);
95
+ }
96
+ /** A nested call's answer from a tool with no value: its items, then a line saying how many images the tool returned,
97
+ * which are not sent (Codex gives a script an image as its data: URL in the result's text, so a script that prints the
98
+ * result would send the model the base64 as words); an answer of any other shape, or no images, as it is. */
99
+ export function withImagesHeld(answer, images) {
100
+ const items = answer?.contentItems;
101
+ if (!images?.length || !Array.isArray(items))
102
+ return answer;
103
+ const count = images.length;
104
+ return { ...answer, contentItems: [...items, { type: "inputText", text: `${count} image${count === 1 ? "" : "s"} it returned ${count === 1 ? "was" : "were"} not sent: in code mode a tool's image reaches the script only as text.` }] };
105
+ }
106
+ /** A code-mode script's nested call's answer. A tool with a value (a computer tool's) answers the value as JSON text,
107
+ * its images' data back in it, so the script reads it with JSON.parse and holds each image whole, to compute on or
108
+ * pass on; any other tool answers its words and a line on its images, which are not sent (`withImagesHeld`). A failed
109
+ * call's answer, or one of any other shape, as it is. */
110
+ export function scriptAnswer(answer, extras) {
111
+ const shaped = answer;
112
+ if (extras?.structured === undefined || !Array.isArray(shaped?.contentItems) || shaped.success === false)
113
+ return withImagesHeld(answer, extras?.images);
114
+ return { ...shaped, contentItems: [{ type: "inputText", text: JSON.stringify(withImageData(extras.structured, extras.images ?? [])) }] };
115
+ }
116
+ /** A dynamic tool call's answer with `images` after its items, each `{ type: "inputImage", imageUrl }` with a data: URL
117
+ * (Codex 0.164's DynamicToolCallOutputContentItem); an answer of any other shape, or no images, as it is. */
118
+ export function withImages(answer, images) {
119
+ const items = answer?.contentItems;
120
+ if (!images?.length || !Array.isArray(items))
121
+ return answer;
122
+ return { ...answer, contentItems: [...items, ...images.map((image) => ({ type: "inputImage", imageUrl: `data:${image.mimeType};base64,${image.data}` }))] };
123
+ }
124
+ export function codeMode(deps) {
125
+ const { ctx, machine, journal, logged, synced } = deps;
126
+ const scripts = new Scripts();
127
+ /** The exec each nested call was admitted under. */
128
+ const execOf = new Map();
129
+ /** The execs this drive answered itself (recoverItems): their output is the session's words, with no script status. */
130
+ const answeredHere = new Set();
131
+ /** The `exec` or `wait` waiting on the code-mode host now (its script, and how long Codex waits before it yields), the
132
+ * nested calls of a script running now, and the timer on the host's silence (HOST_SILENCE_MS). */
133
+ let awaited;
134
+ let nestedLive = 0;
135
+ let silence;
136
+ /** Times the host's silence again: from now, while an `exec` or `wait` waits on it and no nested call runs. */
137
+ const watch = () => {
138
+ if (silence)
139
+ clearTimeout(silence);
140
+ silence = undefined;
141
+ if (!awaited || nestedLive > 0 || !deps.hostFailed)
142
+ return;
143
+ const left = deps.deadline === undefined ? Infinity : Math.max(0, deps.deadline - Date.now());
144
+ const ms = Math.min(awaited.yieldMs, left) + HOST_SILENCE_MS;
145
+ silence = setTimeout(() => {
146
+ silence = undefined;
147
+ deps.hostFailed?.(`the host left it unanswered for ${Math.round(ms / 1000)} s`);
148
+ }, ms);
149
+ silence.unref?.();
150
+ };
151
+ machine.signal?.addEventListener?.("abort", () => {
152
+ awaited = undefined;
153
+ watch();
154
+ }, { once: true });
155
+ /** After a recovery: the `never` calls the log holds a completed outcome for, by tool and arguments, until the turn ends. Each answers one re-issue. */
156
+ const recovered = new Map();
157
+ /** Each `exec` whose row this drive opened on the host's record (SessionIO.ownCalls): its end waits for that write. */
158
+ const rows = new Map();
159
+ /** The host's record of `exec`'s end, once its row is written: `output`, failed as a recovery recorded it (RECOVERED_END_STREAM)
160
+ * or else as its status header says (`failed`). A crash leaves an exec open on the record (its start is marked as one its
161
+ * harness answers), so its end is always one of these. A recovered exec that ended ok shows its calls' outcomes without
162
+ * the words telling the model its script was cut short (recoveredRowText): on the record, those are a failed exec's. */
163
+ const endRow = (exec, output, failed) => {
164
+ const own = deps.ownCalls;
165
+ if (!own)
166
+ return;
167
+ void (rows.get(exec) ?? Promise.resolve())
168
+ .then(() => journal.read(RECOVERED_END_STREAM))
169
+ .then((kept) => {
170
+ const recovered = kept.findLast((r) => r.data.exec === exec)?.data;
171
+ return recovered ? own.ended(exec, recoveredRowText(output, recovered.failed), recovered.failed) : own.ended(exec, output, failed);
172
+ })
173
+ .catch((error) => deps.log("codex: an exec's end was not written", { exec, error: String(error) }));
174
+ };
175
+ // An `exec` of the log restored that Codex finished before the session stopped: its end, which a crash may have kept off
176
+ // the host's record (a call ended there already says nothing).
177
+ for (const line of deps.lines) {
178
+ const said = scripts.note(line);
179
+ if (said?.kind === "finished")
180
+ endRow(said.exec, said.output, said.failed);
181
+ }
182
+ /** The host's row of the `exec` `exec`, opened once with its script (`{ script }`, as codemode's own input is held), from
183
+ * its rollout line or, before that line is in the rollout, from the proxy's announcement. */
184
+ const openRow = (exec, input) => {
185
+ const own = deps.ownCalls;
186
+ if (!own)
187
+ return Promise.resolve();
188
+ let row = rows.get(exec);
189
+ if (!row)
190
+ rows.set(exec, (row = own.opened(exec, "exec", input === undefined ? {} : { script: input })));
191
+ return row;
192
+ };
193
+ // The lines read live open an `exec`'s row and end it. An `exec` of the log restored is on the host's record already; a
194
+ // cut-off one ends here too, when its recovered output (recoverItems) reaches the rollout: after the rows of the calls the
195
+ // recovery ran or found cut off, failed as the recovery recorded (RECOVERED_END_STREAM).
196
+ machine.onRolloutLine?.((line) => {
197
+ const said = scripts.note(line);
198
+ if (!said)
199
+ return;
200
+ // Codex waits on the host from an exec's line or a wait's on its cell, until an output answers it.
201
+ awaited = said.kind === "opened" || said.kind === "waiting" ? { exec: said.exec, yieldMs: said.yieldMs } : awaited?.exec === said.exec ? undefined : awaited;
202
+ watch();
203
+ if (said.kind === "finished" && said.unrun !== undefined && !answeredHere.has(said.exec))
204
+ deps.hostFailed?.(`Codex answered it with no script status: ${said.unrun}`);
205
+ if (!deps.ownCalls)
206
+ return;
207
+ if (said.kind === "opened")
208
+ void openRow(said.exec, said.input).catch((error) => deps.log("codex: an exec's row was not written", { exec: said.exec, error: String(error) }));
209
+ else if (said.kind === "finished")
210
+ endRow(said.exec, said.output, said.failed);
211
+ });
212
+ /** The script a nested call is tied to now, as the log and the proxy's latest answer have it. */
213
+ const tieNow = () => scripts.tie(machine.announcedExec?.(), (id) => logged.has(id));
214
+ /** A `never` nested call: wait for its script's line, as the harness's barrier waits for a call's own. True: admitted. */
215
+ const admit = async (callId) => {
216
+ for (let i = 0;; i++) {
217
+ await synced();
218
+ const tie = tieNow();
219
+ if (tie.kind === "ambiguous") {
220
+ deps.log("codex: declined a nested call while two scripts are live", { callId, live: tie.live });
221
+ return false;
222
+ }
223
+ if (tie.kind === "tied") {
224
+ execOf.set(callId, tie.exec);
225
+ logged.add(callId);
226
+ await journal.flush();
227
+ return true;
228
+ }
229
+ if (i + 1 >= deps.tries)
230
+ break;
231
+ await sleep(50 * 2 ** i);
232
+ }
233
+ deps.log("codex: declined a call whose function_call line is not in the log", { callId });
234
+ return false;
235
+ };
236
+ /** After a recovery: every `never` call of the interrupted turn the log holds a completed outcome for (the session's record or, when it
237
+ * lost the end, the rollout's: Codex writes that line only after our tool answered, so the effect happened), each answering one
238
+ * re-issue. Read from the turn's tie records, not from the outputs a recovery repairs: a turn recovered once already has its exec
239
+ * answered, and a script that yielded has its exec answered by the running-cell output, yet their calls ran. */
240
+ const arm = async (since) => {
241
+ recovered.clear();
242
+ const state = ctx.state();
243
+ const rolled = completedNested(deps.lines);
244
+ for (const tie of (await journal.read(NESTED_STREAM)).map((r) => r.data)) {
245
+ if (tie.since !== since)
246
+ continue;
247
+ const e = state.effects.get(toolKey(tie.callId));
248
+ if (e?.replay !== "never")
249
+ continue;
250
+ const fact = factOf(state, rolled, tie);
251
+ const settled = settle(fact);
252
+ if (settled.kind !== "completed")
253
+ continue;
254
+ const key = callKey(fact.tool, e.input);
255
+ recovered.set(key, [...(recovered.get(key) ?? []), { tool: fact.tool, text: settled.text, ...(fact.store?.sent !== undefined ? { sent: fact.store.sent } : {}) }]);
256
+ }
257
+ };
258
+ /** A `never` call the log holds a completed outcome for, re-issued after a recovery: its answer from the log, taken once. Held
259
+ * to the host's bound as the bridge holds a call's result (`boundResult`): the log keeps the result whole. */
260
+ function answeredAgain(tool, args, callId) {
261
+ const again = recovered.get(callKey(tool, args))?.shift();
262
+ if (!again)
263
+ return undefined;
264
+ deps.log("codex: answered a never call from the log: it completed before the interruption", { ...(callId ? { callId } : {}), tool: again.tool });
265
+ // A script's call of a tool with a value gets that value's JSON again, as the first call did (scriptAnswer): the script
266
+ // parses it, so no words go before it.
267
+ if (callId !== undefined && NESTED_CALL.test(callId) && again.sent !== undefined)
268
+ return again.sent;
269
+ return boundResult(`Recorded earlier in this turn, not run again: ${again.text}`, deps.budget).text;
270
+ }
271
+ /** The cell a dangling call waited on, when it is code mode's `wait` (a function call named `wait` with a `cell_id`, and no host tool of
272
+ * that name); otherwise `undefined`. */
273
+ const waitedCell = (c) => {
274
+ if (c.type !== "function_call" || c.name !== "wait" || deps.bridge.get("wait"))
275
+ return undefined;
276
+ try {
277
+ const cell = JSON.parse(c.arguments ?? "").cell_id;
278
+ return typeof cell === "string" || typeof cell === "number" ? String(cell) : undefined;
279
+ }
280
+ catch {
281
+ return undefined;
282
+ }
283
+ };
284
+ const declined = { contentItems: [{ type: "inputText", text: deps.declined }], success: false };
285
+ return {
286
+ /** The app-server's request handler, with a code-mode host tool call handled before the harness's own. */
287
+ request(next) {
288
+ return async (req) => {
289
+ if (req.method === "item/tool/call") {
290
+ const p = req.params ?? {};
291
+ const callId = String(p.callId ?? "");
292
+ const tool = deps.bridge.get(String(p.tool));
293
+ // After a recovery, a `never` call the log already holds a completed outcome for, called again (a script that was cut short and
294
+ // written again re-issues every call it made): answered from the log, run no more.
295
+ const again = tool?.replay === "never" ? answeredAgain(tool.name, p.arguments, callId) : undefined;
296
+ if (again !== undefined)
297
+ return { contentItems: [{ type: "inputText", text: again }], success: true };
298
+ if (NESTED_CALL.test(callId)) {
299
+ if (tool?.replay === "never" && !ctx.isMemoized(toolKey(callId)) && !(await admit(callId)))
300
+ return declined;
301
+ const tie = tieNow();
302
+ const exec = execOf.get(callId) ?? (tie.kind === "tied" || tie.kind === "held" ? tie.exec : undefined);
303
+ if (exec)
304
+ execOf.set(callId, exec);
305
+ // On the host's record the call sits under its exec's row, written first (from the proxy's announcement when the
306
+ // exec's line is not in the rollout yet), as a codemode script's calls sit under its call on every other harness.
307
+ // A call tied to no known exec names none: no parent is made up.
308
+ if (exec && exec !== UNWATCHED && deps.ownCalls) {
309
+ await openRow(exec, scripts.inputOf(exec) ?? machine.announcedInput?.(exec)).catch((error) => deps.log("codex: an exec's row was not written", { exec, error: String(error) }));
310
+ deps.ownCalls.nestedIn(callId, exec);
311
+ }
312
+ // Never the unwatched-answer marker: a call tied to no known exec is journaled with none.
313
+ journal.append(NESTED_STREAM, { callId, exec: exec === undefined || exec === UNWATCHED ? null : exec, since: openTurn(ctx.state())?.since ?? -1, tool: String(p.tool), args: p.arguments ?? {} });
314
+ }
315
+ // The harness answers with the result's text; its images follow as `inputImage` items, which Codex 0.164's
316
+ // dynamic tool output takes (DynamicToolCallResponse.contentItems, its app-server schema), each a data: URL.
317
+ // The call runs first (`next`): its images and value are kept by the bridge as it answers, and taken after,
318
+ // whether or not the answer was built, so a call whose answer throws leaves none in the bridge for the session's life.
319
+ let extras;
320
+ let answer;
321
+ // A script's nested call running is no silence of the host's: its timer starts again once the call is answered.
322
+ const nested = NESTED_CALL.test(callId);
323
+ if (nested) {
324
+ nestedLive += 1;
325
+ watch();
326
+ }
327
+ try {
328
+ answer = await next(req);
329
+ }
330
+ finally {
331
+ extras = deps.bridge.take?.(callId);
332
+ if (nested) {
333
+ nestedLive -= 1;
334
+ watch();
335
+ }
336
+ }
337
+ // A script's nested call gets the tool's value, images and all, to compute on (scriptAnswer); the model's own
338
+ // call gets the words and the images to look at.
339
+ return NESTED_CALL.test(callId) ? scriptAnswer(answer, extras) : withImages(answer, extras?.images);
340
+ }
341
+ return next(req);
342
+ };
343
+ },
344
+ /** The outputs injected for the calls the rollout left dangling: a cut-off `exec` gets a custom tool call output from the log, in place of `items`';
345
+ * any other call keeps its generic output, as an item of its own kind, and code mode's `wait` is told that it had started. `since`: the
346
+ * turn the dangling calls ran in: the interrupted one a recovery note resumes, or with none, the turn that ended last. Every output is then
347
+ * held to the host's bound as the tool bridge holds a call's result (`boundResult`): these come from the log, not through the bridge, and
348
+ * both repairs (with a recovery note and without) inject what this leaves. A recovered script's output (a cut-off exec's, a resumed
349
+ * `wait`'s) quotes each finished call's result as the script was handed it and holds its whole to its own bound
350
+ * (scripts.ts recoveryMaxChars, at the session's window); on a resume, the calls it tells the outcome of are recorded for the note (SHOWN_STREAM). `resume`: the open turn a recovery note resumes, whose
351
+ * parked nested calls run now; the repair of an ended turn (repairUnnoted) only tells, and runs nothing. */
352
+ async recoverItems(items, dangling, lines, since, resume = false) {
353
+ const ties = (await journal.read(NESTED_STREAM)).map((r) => r.data);
354
+ const execs = dangling.filter(isExec).map((d) => d.callId);
355
+ const rolled = completedNested(lines);
356
+ // A nested call of a cut-off exec that never reached its intent and that Codex was never answered (its script went with
357
+ // the session: the host's gate parked it for a person's approval, or a crash came before its intent) runs now, through
358
+ // the bridge under its own id, the gate first, so the person's answer on it holds, as a dangling call of the model's own
359
+ // does (resumeUnstartedCalls): its outcome is the exec's output, and nothing runs it again. A gate that parks again
360
+ // rejects out of here, nothing written. Only on the resume of the open turn: an ended turn's repair runs nothing, so a call a
361
+ // person may never have answered does not run on a later turn. A script whose exec had yielded ("Script running") made
362
+ // its call in this turn while the model waited on its cell: that call runs too, and the dangling `wait` tells its
363
+ // outcome (with none dangling there is nowhere to tell it, and it does not run).
364
+ const resumed = new Map();
365
+ const cut = new Set(execs);
366
+ const carrier = dangling.findIndex((c) => !isExec(c) && waitedCell(c) !== undefined);
367
+ const yieldedTies = [];
368
+ const ranBefore = resume ? new Set((await journal.read(RESUMED_STREAM)).map((r) => r.data.callId)) : new Set();
369
+ for (const tie of resume ? ties : []) {
370
+ const cutOff = tie.exec === null ? tie.since === since && execs.length > 0 : cut.has(tie.exec);
371
+ const yielded = !cutOff && carrier >= 0 && tie.since === since;
372
+ const done = ctx.state().effects.get(toolKey(tie.callId));
373
+ // Run on an earlier recovery of this turn that stopped before the wait was answered: told from its record.
374
+ if (yielded && ranBefore.has(tie.callId) && (done?.status === "completed" || done?.status === "failed") && !rolled.has(tie.callId)) {
375
+ resumed.set(tie.callId, { text: done.status === "failed" ? failedText(done.error) : outputTextOf(done.output), isError: done.status === "failed", ran: true });
376
+ yieldedTies.push(tie);
377
+ continue;
378
+ }
379
+ if ((!cutOff && !yielded) || tie.tool === undefined || done || rolled.has(tie.callId))
380
+ continue;
381
+ if (!deps.bridge.call || !deps.bridge.get(tie.tool))
382
+ continue;
383
+ if (yielded) {
384
+ journal.append(RESUMED_STREAM, { callId: tie.callId });
385
+ await journal.flush();
386
+ }
387
+ const result = await deps.bridge.call(tie.tool, tie.args ?? {}, tie.callId);
388
+ // Whether it ran is the gate's answer, not its record: a tool that `nests` (a learned workflow) leaves no effect of its own.
389
+ resumed.set(tie.callId, { text: result.text, isError: result.isError, ran: !result.refused });
390
+ if (yielded)
391
+ yieldedTies.push(tie);
392
+ }
393
+ const state = ctx.state();
394
+ // Each cut-off exec lists its own calls. A call whose script could not be told when it ran (an answer the proxy did not see to its end)
395
+ // is listed once, apart, in the LAST cut-off exec's output, if it ran in this interrupted turn.
396
+ const told = new Map((recoveryNote(state)?.calls ?? []).map((c) => [c.callId, c.status]));
397
+ const fact = (tie) => ({ ...factOf(state, rolled, tie, told), ...(resumed.has(tie.callId) ? { resumed: resumed.get(tie.callId) } : {}) });
398
+ const listed = recoveryFacts(execs, ties, since, fact);
399
+ // The exec each dangling `wait`'s cell belongs to, as the rollout has it.
400
+ const yielders = new Scripts();
401
+ for (const line of lines)
402
+ yielders.note(line);
403
+ // The outputs built here hold their quoted results to their own bound (scripts.ts recoveryMaxChars, at the session's window): every other is
404
+ // held to the host's below. The calls whose outcome they tell, for the turn's recovery note.
405
+ const built = new Set();
406
+ const shown = [];
407
+ // Each output is one result the model reads in this turn: it claims its room in the turn's budget (the answer's facts,
408
+ // taken back from the journal by a new process), as a call through the bridge does, and is held to that claim.
409
+ const turn = deps.budget?.turn;
410
+ await turn?.ready();
411
+ const budgets = dangling.map((c) => (deps.budget && turn ? { ...deps.budget, maxChars: turn.claim(c.callId, deps.budget.contextWindow) } : deps.budget));
412
+ dangling.forEach((c, i) => {
413
+ if (!isExec(c)) {
414
+ // Code mode's `wait` on a cell had started: the generic answer, that the call never started, would be false.
415
+ const cell = waitedCell(c);
416
+ const item = items[i];
417
+ // A completed call whose result held images (bridgeTool records { text, images }): repairOutput gives the record
418
+ // as JSON, so the model would read their base64 as text. Its text and a line on them instead; they are not sent.
419
+ const done = state.effects.get(toolKey(c.callId));
420
+ const pictured = cell === undefined && done?.status === "completed" ? imagesNoted(done.output) : undefined;
421
+ const answered = cell !== undefined && i === carrier && yieldedTies.length > 0 ? yieldedTies.map((tie) => ({ ...factOf(state, rolled, tie, told), resumed: resumed.get(tie.callId) })) : undefined;
422
+ const recovered = answered && cell !== undefined ? waitResumed(cell, answered, budgets[i]) : undefined;
423
+ const waited = cell === undefined ? undefined : recovered ? recovered.output : waitStoppedText(cell);
424
+ if (recovered) {
425
+ built.add(i);
426
+ shown.push(...recovered.shown);
427
+ }
428
+ // This output finishes the cell's exec, and it carries no status header: that exec ends as its last call says.
429
+ const exec = cell === undefined ? undefined : yielders.execOn(cell);
430
+ if (exec !== undefined) {
431
+ journal.append(RECOVERED_END_STREAM, { exec, failed: recoveredFailed(ties.filter((tie) => tie.exec === exec).map(fact)) });
432
+ answeredHere.add(exec);
433
+ }
434
+ items[i] = withOutputKind(waited !== undefined ? { ...item, output: waited } : pictured !== undefined ? { ...item, output: pictured } : item, c);
435
+ return;
436
+ }
437
+ const { own, loose } = listed.get(c.callId);
438
+ // Only the calls the output still tells after its bound: a call cut from it is not said to be above.
439
+ const recovered = execRecovery(own, loose, budgets[i]);
440
+ items[i] = { type: "custom_tool_call_output", call_id: c.callId, output: recovered.output };
441
+ journal.append(RECOVERED_END_STREAM, { exec: c.callId, failed: recoveredFailed(own) });
442
+ answeredHere.add(c.callId);
443
+ built.add(i);
444
+ shown.push(...recovered.shown);
445
+ });
446
+ items.forEach((item, i) => {
447
+ if (!built.has(i) && typeof item.output === "string")
448
+ item.output = boundResult(item.output, budgets[i]).text;
449
+ if (typeof item.output === "string")
450
+ turn?.settle(dangling[i].callId, item.output.length);
451
+ });
452
+ if (resume && shown.length > 0)
453
+ journal.append(SHOWN_STREAM, { since, callIds: shown });
454
+ // Every record above is in the log before the outputs are injected.
455
+ await journal.flush();
456
+ },
457
+ /** With no recovery note, the calls the rollout has no output for get theirs from the log before any turn is sent: a turn that ended without
458
+ * them (one interrupted mid-call, or settled instead of resumed) left them dangling, and the provider refuses a history with a call unanswered.
459
+ * Nothing is armed here: a new turn that calls a `never` call the ended turn completed runs it. */
460
+ async repairUnnoted(lines) {
461
+ const dangling = summarizeRollout(lines).dangling;
462
+ if (dangling.length === 0)
463
+ return;
464
+ const items = dangling.map((c) => ({ type: "function_call_output", call_id: c.callId, output: repairOutput(ctx.state(), c) }));
465
+ // A cut-off exec of the ended turn still lists the calls of that turn whose script could not be told: they ran.
466
+ await this.recoverItems(items, dangling, lines, endedTurnSince(ctx.state()));
467
+ await deps.guard(deps.rpc().request("thread/inject_items", { threadId: deps.threadId(), items }));
468
+ await deps.guard(synced());
469
+ },
470
+ /** The user's turn that resumes an interrupted one: only the user's own words, or a bare nudge. The harness's note about the turn goes to
471
+ * the model as a developer message, injected once for this interrupted turn (every turn opens with `thread/resume`, so injecting on each
472
+ * would repeat it). With no statuses-only note to give, nothing is injected: the full note carries tool outputs and goes in no slot of the model's. */
473
+ async resumeTurn(note, owed) {
474
+ await arm(note.turn.since);
475
+ // The calls whose outcome a recovered script output of this turn tells: the note says it is there, not that it is not shown.
476
+ const shown = new Set((await journal.read(SHOWN_STREAM)).filter((r) => r.data.since === note.turn.since).flatMap((r) => r.data.callIds));
477
+ const system = recoverySystemNote(ctx.state(), shown);
478
+ const noted = (await journal.read(RECOVERY_NOTE_STREAM)).some((r) => r.data.since === note.turn.since);
479
+ if (system !== undefined && !noted) {
480
+ await deps.guard(deps.rpc().request("thread/inject_items", { threadId: deps.threadId(), items: [{ type: "message", role: "developer", content: [{ type: "input_text", text: system }] }] }));
481
+ // The injected item is in the log before it is recorded as injected: a record without it would leave the note out of every later resume.
482
+ await deps.guard(synced());
483
+ journal.append(RECOVERY_NOTE_STREAM, { since: note.turn.since });
484
+ await deps.guard(journal.flush());
485
+ }
486
+ return recoveryUserTurn(owed.map((s) => s.text ?? ""), note.pending.map((s) => s.text ?? ""));
487
+ },
488
+ /** After a crash, in a turn Codex ended completed: what is said of the first `exec` of its last Codex turn that Codex answered
489
+ * with no script status (as hostFailed says it live), if one is there and no recovery answered it (RECOVERED_END_STREAM: that
490
+ * answer is the adapter's, with no header of its own). Codex can end its turn completed before the harness's interrupt
491
+ * reaches it, and its end line is in the log before the turn's failed end is written: a crash between the two must not
492
+ * leave the recovery to end completed a turn whose script the host never ran. */
493
+ async unrunInLastTurn(lines) {
494
+ const answered = new Set((await journal.read(RECOVERED_END_STREAM)).map((r) => r.data.exec));
495
+ const read = new Scripts();
496
+ let unrun;
497
+ for (const line of lines) {
498
+ const l = parseLine(line);
499
+ if (l?.type === "event_msg" && l.payload?.type === "task_started")
500
+ unrun = undefined;
501
+ const said = read.note(line);
502
+ if (unrun === undefined && said?.kind === "finished" && said.unrun !== undefined && !answered.has(said.exec))
503
+ unrun = `Codex answered it with no script status: ${said.unrun}`;
504
+ }
505
+ return unrun;
506
+ },
507
+ /** A turn ended: the calls answered from the log were for it alone. */
508
+ turnEnded() {
509
+ recovered.clear();
510
+ awaited = undefined;
511
+ watch();
512
+ },
513
+ };
514
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * The `config.toml` a session's `CODEX_HOME` gets: the model and its
3
+ * provider (the session's model proxy), and Codex's built-in tools and side
4
+ * features turned off.
5
+ */
6
+ export type TomlValue = string | number | boolean | TomlValue[] | {
7
+ [key: string]: TomlValue;
8
+ };
9
+ /**
10
+ * Codex features turned off (`codex features list`). With these off, a
11
+ * classic model is offered only the harness's dynamic tools and
12
+ * `request_user_input` (which Codex itself answers "unavailable in Default
13
+ * mode"): no shell, no `apply_patch`, no images, no web, no sub-agents. A
14
+ * code-mode model (luna) is offered code mode's `exec` and `wait`; see
15
+ * `code_mode_host`. The rest are side features that would download plugins,
16
+ * call chatgpt.com or start a daemon.
17
+ */
18
+ export declare const BUILTINS_OFF: Record<string, boolean>;
19
+ /**
20
+ * The features on top of `BUILTINS_OFF` with the built-ins on: the shell
21
+ * (unified exec: `exec_command`, `write_stdin`; `apply_patch` runs through
22
+ * it) and `view_image`. Sub-agents, goals, images, the browser and plugins
23
+ * stay off: their state is not in the rollout, or they reach outside.
24
+ */
25
+ export declare const BUILTINS_ON: Record<string, boolean>;
26
+ export interface CodexConfigOptions {
27
+ model: string;
28
+ /** The Responses API base URL (`…/v1`): the VM's model port, relayed to the driver's gateway handler. */
29
+ baseUrl: string;
30
+ /** The env var holding the provider key (a placeholder: the driver adds the credential). */
31
+ envKey: string;
32
+ /** Gateway model ids are unknown to Codex, so its context window must be given. */
33
+ contextWindow: number;
34
+ /**
35
+ * The thread's working directory (`/workspace`): marked untrusted, so a
36
+ * project config the model plants there (`.codex/config.toml`, a trust
37
+ * entry) is never loaded.
38
+ */
39
+ cwd?: string;
40
+ /**
41
+ * `sandbox({ env })`: set for the model's commands too
42
+ * (`shell_environment_policy.set`; `inherit = "core"` passes them nothing
43
+ * else), less any name the policy excludes.
44
+ */
45
+ commandEnv?: Readonly<Record<string, string>>;
46
+ /** How long Codex waits on a streamed answer that sends nothing (`stream_idle_timeout_ms` on its provider). Absent:
47
+ * Codex's own limit, five minutes. A host sets it for a model on its own machine (LOCAL_STREAM_IDLE_MS). */
48
+ streamIdleMs?: number;
49
+ /** Merged over the generated config, last. */
50
+ extra?: Record<string, TomlValue>;
51
+ }
52
+ /**
53
+ * What a command Codex runs inherits: the core variables only (`HOME`,
54
+ * `LOGNAME`, `PATH`, `SHELL`, `USER`, `USERNAME`, `TMPDIR`, `TEMP`, `TMP`),
55
+ * plus `sandbox({ env })` (`set`, `codexConfig`), and never one named like
56
+ * the harness's own (`HARNESS_*`, the provider key's placeholder among them)
57
+ * or a token. Codex 0.160 otherwise passes its whole environment on
58
+ * (docs/workspaces.md §5.6).
59
+ */
60
+ export declare const SHELL_ENVIRONMENT_POLICY: Readonly<{
61
+ inherit: 'core';
62
+ exclude: readonly string[];
63
+ }>;
64
+ /** Whether `name` matches one of the policy's `exclude` patterns (`*` globs, case-insensitive, as Codex matches them). */
65
+ export declare function excludedName(name: string): boolean;
66
+ export declare function codexConfig(options: CodexConfigOptions): Record<string, TomlValue>;
67
+ /**
68
+ * `config` keys the harness sets itself and an app may not (docs/workspaces.md
69
+ * §3.3): the sandbox and approvals (which bwrap and the log's barrier rest
70
+ * on), the commands' environment, the provider and its key (the model port),
71
+ * trust and project config, MCP servers and notifications (they reach outside
72
+ * the log), the features (the built-ins' switch: `builtins`), web search, and
73
+ * the model (`model`). Also what would swap the binary or shell that does the
74
+ * sandboxing, send traffic outside the log (`otel`, `chatgpt_base_url`), grant
75
+ * permission profiles, keep history or snapshots outside the rollout, or read
76
+ * a file the app names (`model_catalog_json`, `RESERVED_CONFIG_SUFFIXES`).
77
+ */
78
+ export declare const RESERVED_CONFIG_KEYS: readonly string[];
79
+ /** Key suffixes reserved at any depth: a binary, a file or a directory Codex would use (`codex_linux_sandbox_exe`, `zsh_path`, `model_instructions_file`, `experimental_compact_prompt_file`, `sqlite_home`, `log_dir`, ...). */
80
+ export declare const RESERVED_CONFIG_SUFFIXES: readonly string[];
81
+ /** Throw a `TypeError` naming the first key of `config` the harness reserves (a dotted key is a nested table's: `tools.web_search`). */
82
+ export declare function checkConfig(config: Record<string, TomlValue> | undefined): void;
83
+ /** TOML text for a config object: plain values first, then one `[table]` per nested object. */
84
+ export declare function toToml(config: Record<string, TomlValue>, prefix?: string[]): string;