@parcha/agentrun-harness-codex 0.1.0-beta.37 → 0.1.0-beta.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +49 -0
- package/README.md +5 -7
- package/dist/adapter.d.ts +12 -7
- package/dist/adapter.js +49 -54
- package/dist/code-mode.d.ts +25 -3
- package/dist/code-mode.js +154 -47
- package/dist/facts.js +9 -5
- package/dist/harness.d.ts +7 -1
- package/dist/harness.js +2 -2
- package/dist/host/machine.d.ts +3 -4
- package/dist/host/machine.js +12 -12
- package/dist/host/policy.d.ts +16 -15
- package/dist/host/policy.js +74 -67
- package/dist/host/process.d.ts +2 -10
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/scripts.d.ts +60 -2
- package/dist/scripts.js +183 -23
- package/dist/versions.d.ts +5 -0
- package/dist/versions.js +5 -0
- package/package.json +3 -3
- package/dist/mcp.d.ts +0 -15
- package/dist/mcp.js +0 -74
package/dist/code-mode.js
CHANGED
|
@@ -1,13 +1,23 @@
|
|
|
1
|
-
import { boundResult, openTurn, recoveryNote, recoverySystemNote, recoveryUserTurn, toolKey, transcriptOf } from "./host/process.js";
|
|
1
|
+
import { boundResult, failureText, openTurn, recoveryNote, recoverySystemNote, recoveryUserTurn, toolKey, transcriptOf } from "./host/process.js";
|
|
2
2
|
// cycle with harness.ts: read repairOutput only inside functions, never at module top level (pinned by "code mode and the harness
|
|
3
3
|
// load in either order and the repair reads repairOutput"). A host loads harness.js first, so at that point none of its const bindings is set.
|
|
4
4
|
import { repairOutput } from "./harness.js";
|
|
5
5
|
import { summarizeRollout } from "./rollout.js";
|
|
6
|
-
import { callKey, completedNested,
|
|
6
|
+
import { callKey, completedNested, execRecovery, NESTED_CALL, outputTextOf, parkedKey, recoveredFailed, recoveredRowText, recoveryFacts, Scripts, settle, UNWATCHED, waitResumed } from "./scripts.js";
|
|
7
7
|
/** The stream that ties each nested call to the `exec` it ran under: `{ callId, exec, since }` (`since`: the turn it ran in), written before the call runs. */
|
|
8
8
|
export const NESTED_STREAM = "codex.nested";
|
|
9
9
|
/** The stream that records the interrupted turns whose recovery note was injected: `{ since }`, once per interrupted turn. */
|
|
10
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";
|
|
11
21
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
12
22
|
/** Only a custom tool call named `exec` is code mode's: a host tool that happens to be called `exec` is a function call. */
|
|
13
23
|
const isExec = (d) => d.type === "custom_tool_call" && d.name === "exec";
|
|
@@ -35,19 +45,21 @@ function sentOf(output) {
|
|
|
35
45
|
return {};
|
|
36
46
|
return { sent: JSON.stringify(withImageData(kept.structured, kept.images ?? [])) };
|
|
37
47
|
}
|
|
48
|
+
/** A failed call's error as the bridge handed it (`failureText`: its message, or words saying it had none). */
|
|
49
|
+
const failedText = (error) => (error ? failureText(error) : "");
|
|
38
50
|
function factOf(state, rolled, tie, told = new Map()) {
|
|
39
51
|
const e = state.effects.get(toolKey(tie.callId));
|
|
40
52
|
const status = told.get(tie.callId);
|
|
41
53
|
return {
|
|
42
54
|
callId: tie.callId,
|
|
43
|
-
tool: e ? e.name.replace(/^tool\./, "") : (rolled.get(tie.callId)?.tool ?? "a tool"),
|
|
44
|
-
...(e ? { store: { status: e.status === "completed" ? "completed" : e.status === "failed" ? "failed" : "started", text: e.status === "failed" ? (e.error
|
|
55
|
+
tool: e ? e.name.replace(/^tool\./, "") : (rolled.get(tie.callId)?.tool ?? tie.tool ?? "a tool"),
|
|
56
|
+
...(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 } : {}) } } : {}),
|
|
45
57
|
...(rolled.has(tie.callId) ? { rollout: rolled.get(tie.callId) } : {}),
|
|
46
58
|
...(status ? { told: status } : {}),
|
|
47
59
|
...(state.effects.get(parkedKey(tie.callId))?.status === "completed" ? { parked: true } : {}),
|
|
48
60
|
};
|
|
49
61
|
}
|
|
50
|
-
/** A recorded result that held images (
|
|
62
|
+
/** A recorded result that held images (bridgeTool's `{ text, images }`) as its text and a line saying how many, which are not
|
|
51
63
|
* shown again after the interruption; undefined for a result with none, whose repaired output stays as it is. */
|
|
52
64
|
export function imagesNoted(output) {
|
|
53
65
|
const images = output?.images;
|
|
@@ -107,33 +119,56 @@ export function codeMode(deps) {
|
|
|
107
119
|
const execOf = new Map();
|
|
108
120
|
/** 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. */
|
|
109
121
|
const recovered = new Map();
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
122
|
+
/** Each `exec` whose row this drive opened on the host's record (SessionIO.ownCalls): its end waits for that write. */
|
|
123
|
+
const rows = new Map();
|
|
124
|
+
/** The host's record of `exec`'s end, once its row is written: `output`, failed as a recovery recorded it (RECOVERED_END_STREAM)
|
|
125
|
+
* or else as its status header says (`failed`). A crash leaves an exec open on the record (its start is marked as one its
|
|
126
|
+
* harness answers), so its end is always one of these. A recovered exec that ended ok shows its calls' outcomes without
|
|
127
|
+
* the words telling the model its script was cut short (recoveredRowText): on the record, those are a failed exec's. */
|
|
128
|
+
const endRow = (exec, output, failed) => {
|
|
129
|
+
const own = deps.ownCalls;
|
|
130
|
+
if (!own)
|
|
131
|
+
return;
|
|
132
|
+
void (rows.get(exec) ?? Promise.resolve())
|
|
133
|
+
.then(() => journal.read(RECOVERED_END_STREAM))
|
|
134
|
+
.then((kept) => {
|
|
135
|
+
const recovered = kept.findLast((r) => r.data.exec === exec)?.data;
|
|
136
|
+
return recovered ? own.ended(exec, recoveredRowText(output, recovered.failed), recovered.failed) : own.ended(exec, output, failed);
|
|
137
|
+
})
|
|
138
|
+
.catch((error) => deps.log("codex: an exec's end was not written", { exec, error: String(error) }));
|
|
139
|
+
};
|
|
140
|
+
// An `exec` of the log restored that Codex finished before the session stopped: its end, which a crash may have kept off
|
|
141
|
+
// the host's record (a call ended there already says nothing).
|
|
142
|
+
for (const line of deps.lines) {
|
|
143
|
+
const said = scripts.note(line);
|
|
144
|
+
if (said?.kind === "finished")
|
|
145
|
+
endRow(said.exec, said.output, said.failed);
|
|
146
|
+
}
|
|
147
|
+
/** The host's row of the `exec` `exec`, opened once with its script (`{ script }`, as codemode's own input is held), from
|
|
148
|
+
* its rollout line or, before that line is in the rollout, from the proxy's announcement. */
|
|
149
|
+
const openRow = (exec, input) => {
|
|
150
|
+
const own = deps.ownCalls;
|
|
151
|
+
if (!own)
|
|
152
|
+
return Promise.resolve();
|
|
153
|
+
let row = rows.get(exec);
|
|
154
|
+
if (!row)
|
|
155
|
+
rows.set(exec, (row = own.opened(exec, "exec", input === undefined ? {} : { script: input })));
|
|
156
|
+
return row;
|
|
157
|
+
};
|
|
158
|
+
// 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
|
|
159
|
+
// cut-off one ends here too, when its recovered output (recoverItems) reaches the rollout: after the rows of the calls the
|
|
160
|
+
// recovery ran or found cut off, failed as the recovery recorded (RECOVERED_END_STREAM).
|
|
161
|
+
machine.onRolloutLine?.((line) => {
|
|
162
|
+
const said = scripts.note(line);
|
|
163
|
+
if (!said || !deps.ownCalls)
|
|
164
|
+
return;
|
|
165
|
+
if (said.kind === "opened")
|
|
166
|
+
void openRow(said.exec, said.input).catch((error) => deps.log("codex: an exec's row was not written", { exec: said.exec, error: String(error) }));
|
|
167
|
+
else
|
|
168
|
+
endRow(said.exec, said.output, said.failed);
|
|
169
|
+
});
|
|
113
170
|
/** The script a nested call is tied to now, as the log and the proxy's latest answer have it. */
|
|
114
171
|
const tieNow = () => scripts.tie(machine.announcedExec?.(), (id) => logged.has(id));
|
|
115
|
-
/** A call Codex runs without the harness (a remote MCP server's tool, mcp.ts): the barrier it passes before its intent (its
|
|
116
|
-
* own line in the log, as the harness's barrier has it; a script's nested call, its script's, tied to it by `admit`), and
|
|
117
|
-
* after a recovery the log's answer for a `never` call the interrupted turn completed, re-issued under a new id. */
|
|
118
|
-
machine.onCalls?.({ recovered: (tool, args) => answeredAgain(tool, args), barrier: async (callId) => {
|
|
119
|
-
if (NESTED_CALL.test(callId)) {
|
|
120
|
-
if (!(await admit(callId)))
|
|
121
|
-
return false;
|
|
122
|
-
const exec = execOf.get(callId);
|
|
123
|
-
journal.append(NESTED_STREAM, { callId, exec: exec === undefined || exec === UNWATCHED ? null : exec, since: openTurn(ctx.state())?.since ?? -1 });
|
|
124
|
-
await journal.flush();
|
|
125
|
-
return true;
|
|
126
|
-
}
|
|
127
|
-
for (let i = 0; i < deps.tries; i++) {
|
|
128
|
-
if (i)
|
|
129
|
-
await sleep(50 * 2 ** (i - 1));
|
|
130
|
-
await synced();
|
|
131
|
-
if (logged.has(callId))
|
|
132
|
-
return journal.flush().then(() => true);
|
|
133
|
-
}
|
|
134
|
-
deps.log("codex: declined a call whose function_call line is not in the log", { callId });
|
|
135
|
-
return false;
|
|
136
|
-
} });
|
|
137
172
|
/** A `never` nested call: wait for its script's line, as the harness's barrier waits for a call's own. True: admitted. */
|
|
138
173
|
const admit = async (callId) => {
|
|
139
174
|
for (let i = 0;; i++) {
|
|
@@ -209,12 +244,6 @@ export function codeMode(deps) {
|
|
|
209
244
|
/** The app-server's request handler, with a code-mode host tool call handled before the harness's own. */
|
|
210
245
|
request(next) {
|
|
211
246
|
return async (req) => {
|
|
212
|
-
// Codex asking to run a remote MCP server's tool, should it ask (approve mode asks nothing): the session's only MCP
|
|
213
|
-
// servers are its own, at its model proxy, which serves only the granted tools and records each call before it
|
|
214
|
-
// sends it (mcp.ts). Any other elicitation is the harness's to decline.
|
|
215
|
-
const meta = req.params?._meta;
|
|
216
|
-
if (req.method === "mcpServer/elicitation/request" && meta?.codex_approval_kind === "mcp_tool_call")
|
|
217
|
-
return { action: "accept", content: {}, _meta: null };
|
|
218
247
|
if (req.method === "item/tool/call") {
|
|
219
248
|
const p = req.params ?? {};
|
|
220
249
|
const callId = String(p.callId ?? "");
|
|
@@ -231,8 +260,15 @@ export function codeMode(deps) {
|
|
|
231
260
|
const exec = execOf.get(callId) ?? (tie.kind === "tied" || tie.kind === "held" ? tie.exec : undefined);
|
|
232
261
|
if (exec)
|
|
233
262
|
execOf.set(callId, exec);
|
|
263
|
+
// On the host's record the call sits under its exec's row, written first (from the proxy's announcement when the
|
|
264
|
+
// exec's line is not in the rollout yet), as a codemode script's calls sit under its call on every other harness.
|
|
265
|
+
// A call tied to no known exec names none: no parent is made up.
|
|
266
|
+
if (exec && exec !== UNWATCHED && deps.ownCalls) {
|
|
267
|
+
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) }));
|
|
268
|
+
deps.ownCalls.nestedIn(callId, exec);
|
|
269
|
+
}
|
|
234
270
|
// Never the unwatched-answer marker: a call tied to no known exec is journaled with none.
|
|
235
|
-
journal.append(NESTED_STREAM, { callId, exec: exec === undefined || exec === UNWATCHED ? null : exec, since: openTurn(ctx.state())?.since ?? -1 });
|
|
271
|
+
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 ?? {} });
|
|
236
272
|
}
|
|
237
273
|
// The harness answers with the result's text; its images follow as `inputImage` items, which Codex 0.164's
|
|
238
274
|
// dynamic tool output takes (DynamicToolCallResponse.contentItems, its app-server schema), each a data: URL.
|
|
@@ -257,34 +293,103 @@ export function codeMode(deps) {
|
|
|
257
293
|
* 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
|
|
258
294
|
* 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
|
|
259
295
|
* 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
|
|
260
|
-
* both repairs (with a recovery note and without) inject what this leaves.
|
|
261
|
-
|
|
262
|
-
|
|
296
|
+
* both repairs (with a recovery note and without) inject what this leaves. A recovered script's output (a cut-off exec's, a resumed
|
|
297
|
+
* `wait`'s) quotes each finished call's result as the script was handed it and holds its whole to its own bound
|
|
298
|
+
* (scripts.ts EXEC_RECOVERY_MAX_CHARS); 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
|
|
299
|
+
* parked nested calls run now; the repair of an ended turn (repairUnnoted) only tells, and runs nothing. */
|
|
300
|
+
async recoverItems(items, dangling, lines, since, resume = false) {
|
|
263
301
|
const ties = (await journal.read(NESTED_STREAM)).map((r) => r.data);
|
|
264
302
|
const execs = dangling.filter(isExec).map((d) => d.callId);
|
|
265
303
|
const rolled = completedNested(lines);
|
|
304
|
+
// A nested call of a cut-off exec that never reached its intent and that Codex was never answered (its script went with
|
|
305
|
+
// the session: the host's gate parked it for a person's approval, or a crash came before its intent) runs now, through
|
|
306
|
+
// 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
|
|
307
|
+
// does (resumeUnstartedCalls): its outcome is the exec's output, and nothing runs it again. A gate that parks again
|
|
308
|
+
// 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
|
|
309
|
+
// person may never have answered does not run on a later turn. A script whose exec had yielded ("Script running") made
|
|
310
|
+
// its call in this turn while the model waited on its cell: that call runs too, and the dangling `wait` tells its
|
|
311
|
+
// outcome (with none dangling there is nowhere to tell it, and it does not run).
|
|
312
|
+
const resumed = new Map();
|
|
313
|
+
const cut = new Set(execs);
|
|
314
|
+
const carrier = dangling.findIndex((c) => !isExec(c) && waitedCell(c) !== undefined);
|
|
315
|
+
const yieldedTies = [];
|
|
316
|
+
const ranBefore = resume ? new Set((await journal.read(RESUMED_STREAM)).map((r) => r.data.callId)) : new Set();
|
|
317
|
+
for (const tie of resume ? ties : []) {
|
|
318
|
+
const cutOff = tie.exec === null ? tie.since === since && execs.length > 0 : cut.has(tie.exec);
|
|
319
|
+
const yielded = !cutOff && carrier >= 0 && tie.since === since;
|
|
320
|
+
const done = ctx.state().effects.get(toolKey(tie.callId));
|
|
321
|
+
// Run on an earlier recovery of this turn that stopped before the wait was answered: told from its record.
|
|
322
|
+
if (yielded && ranBefore.has(tie.callId) && (done?.status === "completed" || done?.status === "failed") && !rolled.has(tie.callId)) {
|
|
323
|
+
resumed.set(tie.callId, { text: done.status === "failed" ? failedText(done.error) : outputTextOf(done.output), isError: done.status === "failed", ran: true });
|
|
324
|
+
yieldedTies.push(tie);
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
327
|
+
if ((!cutOff && !yielded) || tie.tool === undefined || done || rolled.has(tie.callId))
|
|
328
|
+
continue;
|
|
329
|
+
if (!deps.bridge.call || !deps.bridge.get(tie.tool))
|
|
330
|
+
continue;
|
|
331
|
+
if (yielded) {
|
|
332
|
+
journal.append(RESUMED_STREAM, { callId: tie.callId });
|
|
333
|
+
await journal.flush();
|
|
334
|
+
}
|
|
335
|
+
const result = await deps.bridge.call(tie.tool, tie.args ?? {}, tie.callId);
|
|
336
|
+
resumed.set(tie.callId, { text: result.text, isError: result.isError, ran: ctx.state().effects.has(toolKey(tie.callId)) });
|
|
337
|
+
if (yielded)
|
|
338
|
+
yieldedTies.push(tie);
|
|
339
|
+
}
|
|
340
|
+
const state = ctx.state();
|
|
266
341
|
// 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)
|
|
267
342
|
// is listed once, apart, in the LAST cut-off exec's output, if it ran in this interrupted turn.
|
|
268
343
|
const told = new Map((recoveryNote(state)?.calls ?? []).map((c) => [c.callId, c.status]));
|
|
269
|
-
const
|
|
344
|
+
const fact = (tie) => ({ ...factOf(state, rolled, tie, told), ...(resumed.has(tie.callId) ? { resumed: resumed.get(tie.callId) } : {}) });
|
|
345
|
+
const listed = recoveryFacts(execs, ties, since, fact);
|
|
346
|
+
// The exec each dangling `wait`'s cell belongs to, as the rollout has it.
|
|
347
|
+
const yielders = new Scripts();
|
|
348
|
+
for (const line of lines)
|
|
349
|
+
yielders.note(line);
|
|
350
|
+
// The outputs built here hold their quoted results to their own bound (scripts.ts EXEC_RECOVERY_MAX_CHARS): every other is
|
|
351
|
+
// held to the host's below. The calls whose outcome they tell, for the turn's recovery note.
|
|
352
|
+
const built = new Set();
|
|
353
|
+
const shown = [];
|
|
270
354
|
dangling.forEach((c, i) => {
|
|
271
355
|
if (!isExec(c)) {
|
|
272
356
|
// Code mode's `wait` on a cell had started: the generic answer, that the call never started, would be false.
|
|
273
357
|
const cell = waitedCell(c);
|
|
274
358
|
const item = items[i];
|
|
275
|
-
// A completed call whose result held images (
|
|
359
|
+
// A completed call whose result held images (bridgeTool records { text, images }): repairOutput gives the record
|
|
276
360
|
// as JSON, so the model would read their base64 as text. Its text and a line on them instead; they are not sent.
|
|
277
361
|
const done = state.effects.get(toolKey(c.callId));
|
|
278
362
|
const pictured = cell === undefined && done?.status === "completed" ? imagesNoted(done.output) : undefined;
|
|
279
|
-
|
|
363
|
+
const answered = cell !== undefined && i === carrier && yieldedTies.length > 0 ? yieldedTies.map((tie) => ({ ...factOf(state, rolled, tie, told), resumed: resumed.get(tie.callId) })) : undefined;
|
|
364
|
+
const recovered = answered && cell !== undefined ? waitResumed(cell, answered) : undefined;
|
|
365
|
+
const waited = cell === undefined ? undefined : recovered ? recovered.output : waitStoppedText(cell);
|
|
366
|
+
if (recovered) {
|
|
367
|
+
built.add(i);
|
|
368
|
+
shown.push(...recovered.shown);
|
|
369
|
+
}
|
|
370
|
+
// This output finishes the cell's exec, and it carries no status header: that exec ends as its last call says.
|
|
371
|
+
const exec = cell === undefined ? undefined : yielders.execOn(cell);
|
|
372
|
+
if (exec !== undefined)
|
|
373
|
+
journal.append(RECOVERED_END_STREAM, { exec, failed: recoveredFailed(ties.filter((tie) => tie.exec === exec).map(fact)) });
|
|
374
|
+
items[i] = withOutputKind(waited !== undefined ? { ...item, output: waited } : pictured !== undefined ? { ...item, output: pictured } : item, c);
|
|
280
375
|
return;
|
|
281
376
|
}
|
|
282
377
|
const { own, loose } = listed.get(c.callId);
|
|
283
|
-
|
|
378
|
+
// Only the calls the output still tells after its bound: a call cut from it is not said to be above.
|
|
379
|
+
const recovered = execRecovery(own, loose);
|
|
380
|
+
items[i] = { type: "custom_tool_call_output", call_id: c.callId, output: recovered.output };
|
|
381
|
+
journal.append(RECOVERED_END_STREAM, { exec: c.callId, failed: recoveredFailed(own) });
|
|
382
|
+
built.add(i);
|
|
383
|
+
shown.push(...recovered.shown);
|
|
284
384
|
});
|
|
285
|
-
|
|
286
|
-
if (typeof item.output === "string")
|
|
385
|
+
items.forEach((item, i) => {
|
|
386
|
+
if (!built.has(i) && typeof item.output === "string")
|
|
287
387
|
item.output = boundResult(item.output).text;
|
|
388
|
+
});
|
|
389
|
+
if (resume && shown.length > 0)
|
|
390
|
+
journal.append(SHOWN_STREAM, { since, callIds: shown });
|
|
391
|
+
// Every record above is in the log before the outputs are injected.
|
|
392
|
+
await journal.flush();
|
|
288
393
|
},
|
|
289
394
|
/** 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
|
|
290
395
|
* them (one interrupted mid-call, or settled instead of resumed) left them dangling, and the provider refuses a history with a call unanswered.
|
|
@@ -304,7 +409,9 @@ export function codeMode(deps) {
|
|
|
304
409
|
* 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. */
|
|
305
410
|
async resumeTurn(note, owed) {
|
|
306
411
|
await arm(note.turn.since);
|
|
307
|
-
|
|
412
|
+
// The calls whose outcome a recovered script output of this turn tells: the note says it is there, not that it is not shown.
|
|
413
|
+
const shown = new Set((await journal.read(SHOWN_STREAM)).filter((r) => r.data.since === note.turn.since).flatMap((r) => r.data.callIds));
|
|
414
|
+
const system = recoverySystemNote(ctx.state(), shown);
|
|
308
415
|
const noted = (await journal.read(RECOVERY_NOTE_STREAM)).some((r) => r.data.since === note.turn.since);
|
|
309
416
|
if (system !== undefined && !noted) {
|
|
310
417
|
await deps.guard(deps.rpc().request("thread/inject_items", { threadId: deps.threadId(), items: [{ type: "message", role: "developer", content: [{ type: "input_text", text: system }] }] }));
|
package/dist/facts.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { codexPolicy } from "./host/policy.js";
|
|
2
2
|
import { codexSchemaProblems } from "./schema.js";
|
|
3
|
-
import { CODEX_INSTALL, CODEX_VERSION } from "./versions.js";
|
|
3
|
+
import { CODEX_BASE_INPUT_TOKENS, CODEX_INSTALL, CODEX_VERSION } from "./versions.js";
|
|
4
4
|
export const facts = Object.freeze({
|
|
5
5
|
id: "codex",
|
|
6
6
|
label: "Codex",
|
|
@@ -14,18 +14,22 @@ export const facts = Object.freeze({
|
|
|
14
14
|
// One run's memory, measured with the server's (serve's host.ts): Codex's app-server beside the run's process.
|
|
15
15
|
runMib: 192,
|
|
16
16
|
// OpenAI's reasoning efforts stop at xhigh.
|
|
17
|
-
// Its own MCP client binds the session's remote MCP servers.
|
|
18
|
-
mcp: true,
|
|
19
17
|
thinking: Object.freeze(["low", "medium", "high", "xhigh"]),
|
|
20
18
|
// Codex's own live search, booked per call.
|
|
21
19
|
webSearch: "live",
|
|
22
20
|
ownModel: false,
|
|
21
|
+
// Its own code mode runs the model's scripts, each nested call one of the host's tools through its bridge.
|
|
22
|
+
ownCodemode: true,
|
|
23
23
|
normalizeModel: (model) => model,
|
|
24
24
|
install: Object.freeze({ npmLine: CODEX_INSTALL, spec: `@openai/codex@${CODEX_VERSION}`, codes: Object.freeze({ install: "CODEX_NOT_INSTALLED", pins: "CODEX_PIN_MISMATCH" }) }),
|
|
25
|
-
//
|
|
26
|
-
//
|
|
25
|
+
// The shapes Codex drops or retypes in a host tool's schema (a run's MCP tool's among them), measured on the pinned
|
|
26
|
+
// binary (schema.ts).
|
|
27
27
|
schemaProblems: codexSchemaProblems,
|
|
28
28
|
// Codex's own tools, each the host's table tool it is.
|
|
29
29
|
nativeTools: Object.freeze({ web_search: "web_search", shell: "bash" }),
|
|
30
|
+
// A run's MCP tool reaches Codex as `mcp_<server>__<tool>` (adapter.ts codexToolName): the host's is `mcp__<server>__<tool>`.
|
|
31
|
+
hostName: (given) => given.replace(/^mcp_(?!_)/, "mcp__"),
|
|
32
|
+
// Its first request's own input before the agent's prompt, from a Codex run's billing (versions.ts).
|
|
33
|
+
baseInputTokens: CODEX_BASE_INPUT_TOKENS,
|
|
30
34
|
policy: (options) => codexPolicy({ model: options.model, tools: options.tools, ...(options.webSearch === "live" ? { webSearch: "live" } : {}), ...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}) }),
|
|
31
35
|
});
|
package/dist/harness.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { GateAnswer, GateCall } from '@parcha/agentrun-kernel';
|
|
1
|
+
import type { GateAnswer, GateCall, OwnCalls } from '@parcha/agentrun-kernel';
|
|
2
2
|
import { type Harness, type HostTool, type ReplayPolicy, type SessionState, type Submission } from './host/kernel.js';
|
|
3
3
|
import { type AcquireMachine } from './host/process.js';
|
|
4
4
|
import { type TomlValue } from './config.js';
|
|
@@ -80,6 +80,12 @@ export interface CodexHarnessOptions {
|
|
|
80
80
|
* words, nothing written and nothing run; a park holds it. Default none.
|
|
81
81
|
*/
|
|
82
82
|
gate?: (call: GateCall) => Promise<GateAnswer>;
|
|
83
|
+
/**
|
|
84
|
+
* The host's record of a code-mode `exec` (SessionIO.ownCalls): its row
|
|
85
|
+
* from its rollout lines, and each host tool call its script makes named
|
|
86
|
+
* under it. Default none.
|
|
87
|
+
*/
|
|
88
|
+
ownCalls?: OwnCalls;
|
|
83
89
|
/**
|
|
84
90
|
* Codex's own shell and `apply_patch` (and `view_image`), on `/workspace`
|
|
85
91
|
* in the session's VM. Default false (tool-less: `tools` are its only
|
package/dist/harness.js
CHANGED
|
@@ -371,7 +371,7 @@ export function codexHarness(options = {}) {
|
|
|
371
371
|
}
|
|
372
372
|
mirror();
|
|
373
373
|
};
|
|
374
|
-
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 });
|
|
374
|
+
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, ...(options.ownCalls ? { ownCalls: options.ownCalls } : {}) });
|
|
375
375
|
/**
|
|
376
376
|
* The hard barrier before a `never` call (§5.6): its `function_call`
|
|
377
377
|
* line in the log, flushed, before its intent. Codex's rollout writer is
|
|
@@ -847,7 +847,7 @@ export function codexHarness(options = {}) {
|
|
|
847
847
|
if (resume && summary.dangling.length > 0) {
|
|
848
848
|
// Calls the rollout has no output for get theirs from the log.
|
|
849
849
|
const items = summary.dangling.map((c) => ({ type: 'function_call_output', call_id: c.callId, output: repairOutput(ctx.state(), c) }));
|
|
850
|
-
await code.recoverItems(items, summary.dangling, lines, note.turn.since);
|
|
850
|
+
await code.recoverItems(items, summary.dangling, lines, note.turn.since, true);
|
|
851
851
|
await guard(rpc.request('thread/inject_items', { threadId, items }));
|
|
852
852
|
await guard(synced());
|
|
853
853
|
}
|
package/dist/host/machine.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import type { AcquireMachine, CacheDir, SessionProcess } from "./process.js";
|
|
2
|
-
import type { SessionMcp } from "@parcha/agentrun-kernel";
|
|
3
2
|
import { type ModelProxyHooks, type ModelProxyOptions, type ParentWatch } from "@parcha/agentrun-kernel/host";
|
|
4
3
|
import { type CodexCommand } from "../catalog.js";
|
|
5
4
|
/** The variables a child takes from this process, when they are set. */
|
|
@@ -35,12 +34,12 @@ export interface LocalMachineOptions {
|
|
|
35
34
|
tools: readonly string[];
|
|
36
35
|
price?: ModelProxyOptions["price"];
|
|
37
36
|
maxOutputTokens?: number;
|
|
37
|
+
/** On a person's ChatGPT plan: its rules (CodexPolicyOptions.plan). */
|
|
38
|
+
plan?: boolean;
|
|
39
|
+
credentialRefused?: ModelProxyOptions["credentialRefused"];
|
|
38
40
|
log?: ModelProxyOptions["log"];
|
|
39
41
|
fetch?: typeof fetch;
|
|
40
42
|
};
|
|
41
|
-
/** The session's remote MCP servers (mcp.ts): each served at the proxy's `/mcp/<server>`, written in Codex's config,
|
|
42
|
-
* and each call recorded in the drive's session before it is sent. */
|
|
43
|
-
mcp?: SessionMcp;
|
|
44
43
|
/** For tests: the process environment the allowlist reads. Default `process.env`. */
|
|
45
44
|
env?: Readonly<Record<string, string | undefined>>;
|
|
46
45
|
/** Files one of the session's private directories holds at the start of every drive: written when the machine is
|
package/dist/host/machine.js
CHANGED
|
@@ -23,7 +23,6 @@ import { brandMachine } from "./process.js";
|
|
|
23
23
|
import { parentWatched, startModelProxy } from "@parcha/agentrun-kernel/host";
|
|
24
24
|
import { codexPolicy, withWebSearches } from "./policy.js";
|
|
25
25
|
import { UNWATCHED } from "../scripts.js";
|
|
26
|
-
import { CODEX_MCP_CLIENT, mcpServersConfig, recorded } from "../mcp.js";
|
|
27
26
|
import { MODEL_CATALOG_FILE, patchlessCatalog } from "../catalog.js";
|
|
28
27
|
/** The variables a child takes from this process, when they are set. */
|
|
29
28
|
export const INHERITED_ENV = Object.freeze(["PATH", "LANG", "TZ"]);
|
|
@@ -205,18 +204,19 @@ export function localMachine(options) {
|
|
|
205
204
|
const route = model.options;
|
|
206
205
|
// The code-mode `exec` the model proxy's latest answer carried: set while the answer passes, before Codex has it.
|
|
207
206
|
let announced;
|
|
207
|
+
// The script of the last `exec` announced, by its call id: what the host's record of that exec shows.
|
|
208
|
+
let script;
|
|
208
209
|
let open = 0;
|
|
209
210
|
const rolloutListeners = [];
|
|
210
211
|
const cutListeners = [];
|
|
211
|
-
let calls;
|
|
212
212
|
const search = options.webSearch === "live";
|
|
213
213
|
const price = options.proxy.price && search ? withWebSearches(options.proxy.price) : options.proxy.price;
|
|
214
214
|
const proxy = await startModelProxy({
|
|
215
215
|
policy: codexPolicy({
|
|
216
216
|
model: route.models.model,
|
|
217
217
|
tools: options.proxy.tools,
|
|
218
|
-
...(options.mcp ? { mcpTools: options.mcp.servers.flatMap((server) => server.tools.map((tool) => `mcp__${server.name}__${tool.name}`)) } : {}),
|
|
219
218
|
...(options.proxy.maxOutputTokens ? { maxOutputTokens: options.proxy.maxOutputTokens } : {}),
|
|
219
|
+
...(options.proxy.plan ? { plan: true } : {}),
|
|
220
220
|
...(search ? { webSearch: "live", ...(options.searchAllowed ? { searchAllowed: options.searchAllowed } : {}) } : {}),
|
|
221
221
|
announce: {
|
|
222
222
|
// The cost is liveness, not safety: after an overlap a never call is declined until the next single answer, which the model's
|
|
@@ -227,7 +227,10 @@ export function localMachine(options) {
|
|
|
227
227
|
open += 1;
|
|
228
228
|
announced = open > 1 ? UNWATCHED : undefined;
|
|
229
229
|
},
|
|
230
|
-
exec: (callId) =>
|
|
230
|
+
exec: (callId, input) => {
|
|
231
|
+
script = { callId, input: input ?? "" };
|
|
232
|
+
announced = open > 1 || announced === UNWATCHED ? UNWATCHED : callId;
|
|
233
|
+
},
|
|
231
234
|
failed: () => void (announced = UNWATCHED),
|
|
232
235
|
end: () => void (open = Math.max(0, open - 1)),
|
|
233
236
|
},
|
|
@@ -236,13 +239,14 @@ export function localMachine(options) {
|
|
|
236
239
|
model: route.models.model,
|
|
237
240
|
origin: route.target,
|
|
238
241
|
credential: async () => (await route.credential()) ?? "",
|
|
242
|
+
...(options.proxy.credentialRefused ? { credentialRefused: options.proxy.credentialRefused } : {}),
|
|
239
243
|
...(price ? { price } : {}),
|
|
240
|
-
// The kernel's proxy mounts the session's MCP door for Codex's own client; each call is recorded first (recorded).
|
|
241
|
-
...(options.mcp ? { mcp: { session: recorded(options.mcp, ctx, () => calls), client: CODEX_MCP_CLIENT } } : {}),
|
|
242
244
|
...(options.proxy.log ? { log: options.proxy.log } : {}),
|
|
243
245
|
...(options.proxy.fetch ? { fetch: options.proxy.fetch } : {}),
|
|
244
246
|
// The provider stopped the turn's answer on its content filter: no retry of it can pass, so the turn ends at once.
|
|
245
247
|
onFiltered: (message) => ctx.halt?.(new Error(message)),
|
|
248
|
+
// The provider's error answer ends the run (a ChatGPT plan's limit reached): no retry or other key can pass it.
|
|
249
|
+
onFinal: (message) => ctx.halt?.(new Error(message)),
|
|
246
250
|
// The provider cut the turn's answer at its output limit: Codex would ask for it again (it retries an incomplete
|
|
247
251
|
// stream), so the harness ends the turn there, its answer cut.
|
|
248
252
|
onCut: (stop) => {
|
|
@@ -261,18 +265,14 @@ export function localMachine(options) {
|
|
|
261
265
|
modelUrl: proxy.url,
|
|
262
266
|
modelKey: key,
|
|
263
267
|
announcedExec: () => announced,
|
|
268
|
+
announcedInput: (callId) => (script?.callId === callId ? script.input : undefined),
|
|
264
269
|
onRolloutLine: (listener) => void rolloutListeners.push(listener),
|
|
265
270
|
onCut: (listener) => void cutListeners.push(listener),
|
|
266
271
|
openTurn: () => proxy.openTurn(),
|
|
267
|
-
|
|
268
|
-
...(search || options.mcp || catalog ? {
|
|
272
|
+
...(search || catalog ? {
|
|
269
273
|
configure: (config) => {
|
|
270
274
|
if (search)
|
|
271
275
|
config.web_search = "live";
|
|
272
|
-
// Codex's bearer for the proxy's /mcp/<server> is the key it sends to the proxy's model route.
|
|
273
|
-
const keyEnv = (config.model_providers?.gateway?.env_key ?? "");
|
|
274
|
-
if (options.mcp)
|
|
275
|
-
config.mcp_servers = mcpServersConfig(options.mcp, proxy.url, keyEnv);
|
|
276
276
|
// Only with the built-ins off: with them on, apply_patch runs through the shell.
|
|
277
277
|
const features = config.features;
|
|
278
278
|
if (catalog && features?.shell_tool !== true && features?.unified_exec !== true)
|
package/dist/host/policy.d.ts
CHANGED
|
@@ -15,9 +15,6 @@ export interface CodexPolicyOptions {
|
|
|
15
15
|
model: string;
|
|
16
16
|
/** The session's own tool names: every other tool definition is dropped. */
|
|
17
17
|
tools: readonly string[];
|
|
18
|
-
/** The granted tools of the session's remote MCP servers, `mcp__<server>__<tool>`: the pinned CLI offers a server's tools
|
|
19
|
-
* in a namespace named `mcp__<server>`, each by the server's own name. */
|
|
20
|
-
mcpTools?: readonly string[];
|
|
21
18
|
/** The most output tokens one request may ask for. Default 32 000. */
|
|
22
19
|
maxOutputTokens?: number;
|
|
23
20
|
/** Codex's own web search, live: the live search tool the pinned CLI sends passes, and a `tool_choice` naming it. Each
|
|
@@ -29,14 +26,19 @@ export interface CodexPolicyOptions {
|
|
|
29
26
|
* `tool_choice` naming the search is then refused. Absent: the live search is offered whenever `webSearch` is on. */
|
|
30
27
|
searchAllowed?: () => Promise<boolean>;
|
|
31
28
|
/** Told, before Codex has the piece of an answer, what the answer carries: `response()` when an answer starts, and
|
|
32
|
-
* `exec(callId)` for each code-mode `exec` call it holds. The session ties a script's nested
|
|
33
|
-
* latest answer, which is known here before Codex can run anything of it. */
|
|
29
|
+
* `exec(callId, input)` for each code-mode `exec` call it holds, with its script. The session ties a script's nested
|
|
30
|
+
* calls to the `exec` of the latest answer, which is known here before Codex can run anything of it. */
|
|
34
31
|
announce?: {
|
|
35
32
|
response(): void;
|
|
36
|
-
exec(callId: string): void;
|
|
33
|
+
exec(callId: string, input?: string): void;
|
|
37
34
|
failed(): void;
|
|
38
35
|
end(): void;
|
|
39
36
|
};
|
|
37
|
+
/** The route is a person's ChatGPT plan (its access token the credential), whose Responses API keeps rules of its own:
|
|
38
|
+
* no `max_output_tokens` is sent (none is clamped or added: the proxy limits no output and counts no input on it), the
|
|
39
|
+
* keys it does not take are dropped (PLAN_DROPPED_KEYS), a system-role message is refused in words, each request names
|
|
40
|
+
* its originator (`agentrun`), and its usage is booked as the plan's (`billing: "plan"`). */
|
|
41
|
+
plan?: boolean;
|
|
40
42
|
}
|
|
41
43
|
/**
|
|
42
44
|
* Whether the provider stopped the answer on its content filter: the stream's terminal event (or a whole body) is an
|
|
@@ -68,15 +70,6 @@ export declare function usageOf(text: string): ProxyUsage | undefined;
|
|
|
68
70
|
/** The web searches a Responses answer ran, as its terminal event reports them (`tool_usage.web_search.num_requests`,
|
|
69
71
|
* what OpenAI bills per call), or undefined when that event's own count cannot be read: an unknown cost, never 0. */
|
|
70
72
|
export declare function webSearchesOf(text: string): number | undefined;
|
|
71
|
-
/**
|
|
72
|
-
* The input tokens the provider bills for `body` that it does not carry (`providerInputOverhead`, with its sources). The
|
|
73
|
-
* Responses API documents no prompt of its own that it adds on these routes (no hosted tool passes the policy but a
|
|
74
|
-
* session's live web search, below), and the framing it puts around each input item and tool definition is a few tokens
|
|
75
|
-
* each, fewer than the bytes of the JSON keys that item already spends in the body. An image is billed by its area, not
|
|
76
|
-
* its bytes: each counts at the most it can be billed as, in place of the bytes its data URL takes in the body. A file input (a PDF, billed by its pages) has no stated bound, so a
|
|
77
|
-
* body with one cannot be measured: this throws, and the request's input is unknown.
|
|
78
|
-
*/
|
|
79
|
-
export declare function responsesServerInputOverhead(body: Record<string, unknown>): number;
|
|
80
73
|
/** The tokens a request keeps for its answer when its output is limited. */
|
|
81
74
|
export declare const ANSWER_TOKENS_LEAST = 1024;
|
|
82
75
|
/** What a reasoning request at each effort is allowed for its reasoning beside its answer, when its output is limited:
|
|
@@ -88,6 +81,8 @@ export declare function responsesOutputAsked(body: Record<string, unknown>): num
|
|
|
88
81
|
/** The least output a Responses body may be limited to and still answer: 1,024 tokens, plus its reasoning effort's
|
|
89
82
|
* allowance when it reasons. */
|
|
90
83
|
export declare function responsesOutputLeast(body: Record<string, unknown>): number;
|
|
84
|
+
/** The reasoning effort a Responses body asks its model at (`reasoning.effort`), when it names one. */
|
|
85
|
+
export declare function responsesEffort(body: Record<string, unknown>): string | undefined;
|
|
91
86
|
/** The reasoning tokens a Responses request may bill that its stream never shows (only a summary of its reasoning
|
|
92
87
|
* streams): its effort's budget; none at effort `none`; and with no effort the body says (the model then reasons at its
|
|
93
88
|
* own default, or not at all), its output limit, `fallback` when the body names none: the conservative side. An
|
|
@@ -106,4 +101,10 @@ export declare function limitResponsesOutput(body: Record<string, unknown>, max:
|
|
|
106
101
|
* at the end of `input`. Caching is by prefix, so the earlier items stay a hit; the client's next request, which sends
|
|
107
102
|
* its own input whole, does not carry it. */
|
|
108
103
|
export declare function addResponsesNote(body: Record<string, unknown>, text: string): Record<string, unknown>;
|
|
104
|
+
/** A ChatGPT plan's 429 past its limit (PLAN_LIMIT_ERRORS, as the error's `code` or `type`): final, in PLAN_LIMIT_WORDS.
|
|
105
|
+
* Any other error goes through as it came (a 429 for the rate, which its client waits out and asks again). */
|
|
106
|
+
export declare function planLimitOf(status: number, body: string): {
|
|
107
|
+
message: string;
|
|
108
|
+
code: string;
|
|
109
|
+
} | undefined;
|
|
109
110
|
export declare function codexPolicy(options: CodexPolicyOptions): ProviderPolicy;
|