@parcha/agentrun-harness-codex 0.0.0-stage → 0.1.0-beta.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/schema.js ADDED
@@ -0,0 +1,178 @@
1
+ // What the Codex adapter does about the schema of a tool, written for AgentRun. Codex 0.164.0 sanitizes the JSON Schema
2
+ // of every tool it offers its model (measured on the pinned binary, test/fixtures/schema-column.json): it drops a set of
3
+ // keywords and it drops or retypes a few shapes. So that no difference is silent:
4
+ // - a shape Codex drops or retypes is REFUSED when the session is checked, by tool, JSON pointer and keyword;
5
+ // - a keyword Codex only strips (a bound, a pattern, a format, a title, a default) is DESCRIBED, in plain words, in the
6
+ // tool's description, which Codex forwards whole. The host and the DSL still validate against the original schema;
7
+ // only the model's copy is described.
8
+ /** The keywords Codex strips and the adapter describes, with the words for each. */
9
+ const DESCRIBED = Object.freeze({
10
+ minLength: (v) => `at least ${show(v)} characters`,
11
+ maxLength: (v) => `at most ${show(v)} characters`,
12
+ maxItems: (v) => `at most ${show(v)} items`,
13
+ minProperties: (v) => `at least ${show(v)} properties`,
14
+ maxProperties: (v) => `at most ${show(v)} properties`,
15
+ minimum: (v) => `at least ${show(v)}`,
16
+ maximum: (v) => `at most ${show(v)}`,
17
+ exclusiveMinimum: (v) => `greater than ${show(v)}`,
18
+ exclusiveMaximum: (v) => `less than ${show(v)}`,
19
+ multipleOf: (v) => `a multiple of ${show(v)}`,
20
+ pattern: (v) => `matches ${show(v)}`,
21
+ format: (v) => `format ${show(v)}`,
22
+ uniqueItems: (v) => (v === true ? "items are unique" : undefined),
23
+ title: (v) => `titled ${JSON.stringify(v)}`,
24
+ default: (v) => `default ${show(v)}`,
25
+ examples: (v) => `examples ${show(v)}`,
26
+ nullable: (v) => (v === true ? "may be null" : undefined),
27
+ deprecated: (v) => (v === true ? "deprecated" : undefined),
28
+ readOnly: (v) => (v === true ? "read only" : undefined),
29
+ writeOnly: (v) => (v === true ? "write only" : undefined),
30
+ });
31
+ /** Keywords Codex strips that mean nothing to a model: a comment for people, the dialect marker `$schema` (Codex drops it
32
+ * whatever it names, and the shared check has already refused one that names no dialect the harnesses take), and the
33
+ * DSL's own `criteria`, which the DSL removes from the model's copy itself. Dropped without a word. */
34
+ const NOISE = Object.freeze(["$comment", "$schema", "criteria"]);
35
+ /** The order the words of one position are written in. */
36
+ const ORDER = ["pattern", "format", "exclusiveMinimum", "exclusiveMaximum", "minimum", "maximum", "multipleOf", "minLength", "maxLength", "maxItems", "minProperties", "maxProperties", "uniqueItems", "nullable", "readOnly", "writeOnly", "deprecated", "default", "examples", "title"];
37
+ export const CODEX_DESCRIBED_KEYWORDS = Object.freeze(Object.keys(DESCRIBED));
38
+ /** The heading the described constraints go under, in the tool's description. */
39
+ export const DESCRIBED_HEADING = "Constraints on the arguments (checked on every call; not part of the schema you were given):";
40
+ const show = (v) => (typeof v === "string" ? v : JSON.stringify(v));
41
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
42
+ const SCALAR = (v) => v === null || ["string", "number", "boolean"].includes(typeof v);
43
+ /** The keywords whose value is a map of schemas, a schema, or a list of schemas: where a schema position is. */
44
+ const SCHEMA_MAPS = ["properties", "$defs", "definitions", "dependentSchemas"];
45
+ const SCHEMA_LISTS = ["anyOf", "oneOf", "allOf"];
46
+ const SCHEMA_ONES = ["items", "additionalProperties", "contains", "propertyNames", "unevaluatedItems", "unevaluatedProperties"];
47
+ const esc = (key) => key.replace(/~/g, "~0").replace(/\//g, "~1");
48
+ /** The schema positions directly below `node`, in the order they are visited. */
49
+ function childrenOf({ pointer, path, node, inAllOf }) {
50
+ const out = [];
51
+ const add = (sub, at, readable, allOf = inAllOf) => {
52
+ if (isObject(sub))
53
+ out.push({ pointer: at, path: readable, node: sub, inAllOf: allOf });
54
+ };
55
+ for (const key of SCHEMA_MAPS) {
56
+ const map = node[key];
57
+ if (isObject(map))
58
+ for (const [name, sub] of Object.entries(map))
59
+ add(sub, `${pointer}/${key}/${esc(name)}`, key === "properties" ? `${path ? `${path}.` : ""}${name}` : `${path ? `${path}.` : ""}${key}.${name}`);
60
+ }
61
+ for (const key of SCHEMA_LISTS) {
62
+ const list = node[key];
63
+ if (Array.isArray(list))
64
+ list.forEach((sub, i) => add(sub, `${pointer}/${key}/${i}`, `${path}${path ? " " : ""}(${key} ${i + 1})`, inAllOf || key === "allOf"));
65
+ }
66
+ for (const key of SCHEMA_ONES) {
67
+ const sub = node[key];
68
+ if (isObject(sub))
69
+ add(sub, `${pointer}/${key}`, key === "items" ? `${path}[]` : `${path}${path ? "." : ""}(${key})`);
70
+ else if (Array.isArray(sub))
71
+ sub.forEach((s, i) => add(s, `${pointer}/${key}/${i}`, `${path}[${i}]`));
72
+ }
73
+ for (const key of ["not", "if", "then", "else"])
74
+ add(node[key], `${pointer}/${key}`, `${path}${path ? "." : ""}(${key})`);
75
+ if (Array.isArray(node.prefixItems))
76
+ node.prefixItems.forEach((s, i) => add(s, `${pointer}/prefixItems/${i}`, `${path}[${i}]`));
77
+ if (isObject(node.patternProperties))
78
+ for (const [name, sub] of Object.entries(node.patternProperties))
79
+ add(sub, `${pointer}/patternProperties/${esc(name)}`, `${path}.(${name})`);
80
+ return out;
81
+ }
82
+ /** Every schema position of `schema`, depth first, with `$defs` and union branches. A loop with its own stack, so no
83
+ * depth of schema overflows the call stack. */
84
+ function positions(schema) {
85
+ const out = [];
86
+ if (!isObject(schema))
87
+ return out;
88
+ const stack = [{ pointer: "", path: "", node: schema, inAllOf: false }];
89
+ // A node already visited is skipped, so a cycle (an object that contains itself, which only code can build) ends
90
+ // here whichever caller reaches it. A node shared by two places (not a cycle) is walked at the first.
91
+ const seen = new WeakSet();
92
+ for (let here = stack.pop(); here; here = stack.pop()) {
93
+ if (seen.has(here.node))
94
+ continue;
95
+ seen.add(here.node);
96
+ out.push(here);
97
+ const below = childrenOf(here);
98
+ for (let i = below.length - 1; i >= 0; i -= 1)
99
+ stack.push(below[i]);
100
+ }
101
+ return out;
102
+ }
103
+ /** The shapes of `schema` Codex would drop or retype, as one refusal each: `<tool>: <pointer>: <keyword> is not supported by
104
+ * Codex 0.164.0 (it drops or retypes it)`. Empty when Codex carries the schema (less what is described). */
105
+ export function codexSchemaProblems(tool, schema) {
106
+ const problems = [];
107
+ const refuse = (pointer, keyword) => problems.push(`${tool}: ${pointer || "/"}: ${keyword} is not supported by Codex 0.164.0 (it drops or retypes it)`);
108
+ for (const { pointer, node } of positions(schema)) {
109
+ if (Array.isArray(node.items))
110
+ refuse(`${pointer}/items`, "items (an array)");
111
+ if (node.prefixItems !== undefined)
112
+ refuse(`${pointer}/prefixItems`, "prefixItems");
113
+ if (node.patternProperties !== undefined)
114
+ refuse(`${pointer}/patternProperties`, "patternProperties");
115
+ const conditional = ["if", "then", "else"].find((key) => node[key] !== undefined);
116
+ if (conditional)
117
+ refuse(`${pointer}/${conditional}`, "if/then/else");
118
+ if (node.not !== undefined)
119
+ refuse(`${pointer}/not`, "not");
120
+ if ((Array.isArray(node.enum) && node.enum.some((v) => !SCALAR(v))) || (node.const !== undefined && !SCALAR(node.const)))
121
+ refuse(`${pointer}/${node.const !== undefined && !SCALAR(node.const) ? "const" : "enum"}`, "enum with a non-scalar value");
122
+ // With no `type`, Codex types an enum or a const `string`: a number, a boolean or a null in it would be mistyped.
123
+ const values = Array.isArray(node.enum) ? node.enum : node.const !== undefined ? [node.const] : [];
124
+ if (node.type === undefined && values.every(SCALAR) && values.some((v) => typeof v !== "string"))
125
+ refuse(`${pointer}/${Array.isArray(node.enum) ? "enum" : "const"}`, "enum with non-string values and no type (Codex types it string)");
126
+ for (const key of ["contains", "dependentRequired", "propertyNames"])
127
+ if (node[key] !== undefined)
128
+ refuse(`${pointer}/${key}`, key);
129
+ if (node.items === true || node.items === false)
130
+ refuse(`${pointer}/items`, "items (a boolean)");
131
+ if (Array.isArray(node.allOf) && node.allOf.some((member) => isObject(member) && positions(member).some((p) => CODEX_DESCRIBED_KEYWORDS.some((k) => k !== "title" && k !== "default" && p.node[k] !== undefined))))
132
+ refuse(`${pointer}/allOf`, "allOf with constraints in its members");
133
+ }
134
+ return problems;
135
+ }
136
+ /** One line per position that has a stripped keyword, sorted by JSON pointer: `<path>: <type>, <words>`. */
137
+ export function describeDropped(schema) {
138
+ const lines = [];
139
+ for (const { pointer, path, node } of positions(schema)) {
140
+ const words = ORDER.flatMap((key) => (node[key] === undefined ? [] : [DESCRIBED[key](node[key])].filter((w) => w !== undefined)));
141
+ if (!words.length)
142
+ continue;
143
+ const type = typeof node.type === "string" ? [node.type] : [];
144
+ lines.push([pointer, `${path || "(the whole value)"}: ${[...type, ...words].join(", ")}`]);
145
+ }
146
+ return lines.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([, line]) => line);
147
+ }
148
+ /** The description Codex forwards for a tool: its own, then the described constraints under one heading. */
149
+ export function describedDescription(description, schema) {
150
+ const lines = describeDropped(schema);
151
+ return lines.length ? `${description}\n\n${DESCRIBED_HEADING}\n${lines.map((l) => `- ${l}`).join("\n")}` : description;
152
+ }
153
+ /** `schema` as Codex forwards it, once its strippable keywords are gone: the original less the described keywords, a position
154
+ * left empty typed `{ "type": "string" }` and an object position with no `properties` given `properties: {}`, as measured.
155
+ * For tests, and the recorded column. */
156
+ export function stripDescribed(schema) {
157
+ const copy = structuredClone(schema);
158
+ for (const { node } of positions(copy)) {
159
+ let stripped = false;
160
+ for (const key of [...CODEX_DESCRIBED_KEYWORDS, ...NOISE])
161
+ if (key in node) {
162
+ delete node[key];
163
+ stripped = true;
164
+ }
165
+ // A const is an enum of one; an enum or const with no type is typed string (strings only: the others are refused).
166
+ if (node.const !== undefined) {
167
+ node.enum = [node.const];
168
+ delete node.const;
169
+ }
170
+ if (Array.isArray(node.enum) && node.type === undefined)
171
+ node.type = "string";
172
+ if (stripped && Object.keys(node).length === 0)
173
+ node.type = "string";
174
+ if (node.type === "object" && node.properties === undefined)
175
+ node.properties = {};
176
+ }
177
+ return copy;
178
+ }
@@ -0,0 +1,94 @@
1
+ /** The id Codex gives a host tool called from a code-mode script. */
2
+ export declare const NESTED_CALL: RegExp;
3
+ /** What the session is told when the proxy could not watch an answer to its end: the answer may carry an `exec` it did not see, so
4
+ * no script can be told from it. It counts as a script of its own, one that is never in the log. */
5
+ export declare const UNWATCHED = "(unwatched answer)";
6
+ /** What to do with a nested call: run it under `exec`; hold it until `exec`'s line is in the rollout; refuse it, as two scripts
7
+ * are live; or hold it, as no script is known yet. */
8
+ export type Tie = {
9
+ kind: "tied";
10
+ exec: string;
11
+ } | {
12
+ kind: "held";
13
+ exec: string;
14
+ } | {
15
+ kind: "ambiguous";
16
+ live: string[];
17
+ } | {
18
+ kind: "none";
19
+ };
20
+ export declare class Scripts {
21
+ private readonly open;
22
+ /** The `exec` calls whose script finished. */
23
+ private readonly done;
24
+ /** The cell each `wait` call in the rollout resumes. */
25
+ private readonly waitsOn;
26
+ /** Reads one rollout line. */
27
+ note(line: string): void;
28
+ /** The scripts that may call a host tool now: the rollout's unfinished ones, and the `exec` the proxy's latest answer carried
29
+ * if it is not among them and has not finished (its line may not be in the rollout yet). */
30
+ live(announced?: string): string[];
31
+ /** What to do with a nested call now, given the exec the proxy announced and whether a call id is in the rollout. */
32
+ tie(announced: string | undefined, logged: (callId: string) => boolean): Tie;
33
+ }
34
+ /** What the rollout's `item_completed` line says of a nested call: Codex writes it after the call was answered, so a crash
35
+ * before it leaves none. */
36
+ export interface RolloutNested {
37
+ tool: string;
38
+ ok: boolean;
39
+ text: string;
40
+ }
41
+ /** The nested calls the rollout's lines hold a completion for, by their `exec-<uuid>` id. */
42
+ export declare function completedNested(lines: readonly string[]): Map<string, RolloutNested>;
43
+ /** One nested call of a cut-off `exec`, as the two sources have it. */
44
+ export interface NestedFact {
45
+ callId: string;
46
+ tool: string;
47
+ /** The session's own record (the effect of `tool:<id>`): none when the call never started. */
48
+ store?: {
49
+ status: "completed" | "failed" | "started";
50
+ text?: string;
51
+ interrupted?: boolean;
52
+ };
53
+ /** What the harness's recovery note of the same turn calls it (the kernel's one rule, process/recovery.ts): `retryable` is a
54
+ * safe tool's call that a crash cut off, which the note tells the model is safe to repeat. */
55
+ told?: "completed" | "failed" | "interrupted" | "retryable" | "running";
56
+ rollout?: RolloutNested;
57
+ }
58
+ export type Settled = {
59
+ kind: "completed";
60
+ text: string;
61
+ } | {
62
+ kind: "failed";
63
+ text: string;
64
+ } | {
65
+ kind: "interrupted";
66
+ };
67
+ /** What a nested call came to. The store's record first, the rollout's completion second: both complete and agreeing, or
68
+ * one of them, is that outcome; both complete and disagreeing, or a call that started and has no end in either, is
69
+ * interrupted (its effect is unknown), and a failure the store marks interrupted is interrupted. They agree when the
70
+ * rollout holds what the bridge handed Codex for the stored text: the store's text held to the host's bound
71
+ * (`boundResult`), since the store keeps a result whole and Codex got its cut; or the stored text itself, as a session
72
+ * written before that bound holds it in both records. */
73
+ export declare function settle(fact: NestedFact): Settled;
74
+ /** A tie record of a nested call: the `exec` it ran under (none when the answer that wrote the script could not be read to its end,
75
+ * so which script it was cannot be told) and the turn it ran in. */
76
+ export interface NestedTie {
77
+ callId: string;
78
+ exec: string | null;
79
+ since?: number;
80
+ }
81
+ /** The nested calls to list for each cut-off `exec` of the interrupted turn `since`: its own, in order; and the calls whose
82
+ * script could not be told, which ran in that turn, under the LAST cut-off exec only, apart from its own, so each is listed once. */
83
+ export declare function recoveryFacts<T>(execs: readonly string[], ties: readonly NestedTie[], since: number, factOf: (tie: NestedTie) => T): Map<string, {
84
+ own: T[];
85
+ loose: T[];
86
+ }>;
87
+ /** The output a cut-off `exec` is answered with: its nested calls, in order, each with what it came to, and that nothing was run
88
+ * again. A completed call's effect is done, a never tool's included; a call with no end is interrupted. `loose`: calls of this turn
89
+ * whose script could not be told (given to the last cut-off exec only), listed apart under their own heading. */
90
+ export declare function execRecoveryOutput(facts: readonly NestedFact[], loose?: readonly NestedFact[]): string;
91
+ /** The text of a tool's recorded output (a string, or `{ text }` with images). */
92
+ export declare function outputTextOf(output: unknown): string;
93
+ /** A call by its tool and arguments, whatever the order of the arguments' keys: what a `never` tool's call is matched on. */
94
+ export declare const callKey: (tool: string, args: unknown) => string;
@@ -0,0 +1,162 @@
1
+ // Which code-mode script a host tool's nested call belongs to. Written for AgentRun.
2
+ //
3
+ // A host tool a code-mode model's script calls arrives on the app-server's stream as a call under an id of Codex's own
4
+ // (`exec-<uuid>`) that carries no parent, no cell and no `exec` id, and the rollout holds no line for it until after it is
5
+ // answered. So the call is tied to the one script that can be running, and that is read from two places that cannot be
6
+ // ahead of Codex:
7
+ // - the rollout: an `exec` call line opens a script, and it stays open until an output says it finished: its own, or, when
8
+ // that says "Script running with cell ID N" (it yielded and went on), the output of the `wait` that finishes cell N;
9
+ // - the model proxy: the `exec` the latest answer carried, which it read before Codex had that part of the answer, so
10
+ // before the `exec`'s line could be in the rollout.
11
+ // The proxy offers no `exec` while a cell runs and no parallel calls, so one script is live at a time. A model that writes an
12
+ // `exec` anyway makes two live, and then a nested call cannot be told from the other's.
13
+ import { boundResult } from "./host/process.js";
14
+ import { parseLine } from "./rollout.js";
15
+ /** The id Codex gives a host tool called from a code-mode script. */
16
+ export const NESTED_CALL = /^exec-[0-9a-f-]{36}$/;
17
+ /** What the session is told when the proxy could not watch an answer to its end: the answer may carry an `exec` it did not see, so
18
+ * no script can be told from it. It counts as a script of its own, one that is never in the log. */
19
+ export const UNWATCHED = "(unwatched answer)";
20
+ /** Codex's status header of an exec's or a wait's output: the text it starts with (its first part), never what the script printed after it. */
21
+ const statusOf = (output) => typeof output === "string" ? output : Array.isArray(output) && typeof output[0]?.text === "string" ? output[0].text : "";
22
+ /** A cell that yielded and still runs, as its status header says. */
23
+ const RUNNING = /^Script running with cell ID (\S+)/;
24
+ const textOf = (output) => typeof output === "string" ? output : Array.isArray(output) ? output.map((part) => (typeof part?.text === "string" ? part.text : "")).join("\n") : "";
25
+ export class Scripts {
26
+ open = [];
27
+ /** The `exec` calls whose script finished. */
28
+ done = new Set();
29
+ /** The cell each `wait` call in the rollout resumes. */
30
+ waitsOn = new Map();
31
+ /** Reads one rollout line. */
32
+ note(line) {
33
+ if (!line.includes("call_id"))
34
+ return;
35
+ const p = parseLine(line)?.payload;
36
+ if (!p || typeof p.call_id !== "string")
37
+ return;
38
+ const id = p.call_id;
39
+ const running = RUNNING.exec(statusOf(p.output));
40
+ if (p.type === "custom_tool_call" && p.name === "exec") {
41
+ if (!this.open.some((x) => x.exec === id))
42
+ this.open.push({ exec: id });
43
+ }
44
+ else if (p.type === "custom_tool_call_output") {
45
+ const at = this.open.findIndex((x) => x.exec === id);
46
+ if (at < 0)
47
+ return;
48
+ if (running)
49
+ this.open[at].cell = running[1];
50
+ else
51
+ this.done.add(this.open.splice(at, 1)[0].exec);
52
+ }
53
+ else if (p.type === "function_call" && p.name === "wait") {
54
+ try {
55
+ const cell = JSON.parse(String(p.arguments)).cell_id;
56
+ if (cell !== undefined)
57
+ this.waitsOn.set(id, String(cell));
58
+ }
59
+ catch { }
60
+ }
61
+ else if (p.type === "function_call_output" && this.waitsOn.has(id) && !running) {
62
+ const at = this.open.findIndex((x) => x.cell === this.waitsOn.get(id));
63
+ if (at >= 0)
64
+ this.done.add(this.open.splice(at, 1)[0].exec);
65
+ }
66
+ }
67
+ /** The scripts that may call a host tool now: the rollout's unfinished ones, and the `exec` the proxy's latest answer carried
68
+ * if it is not among them and has not finished (its line may not be in the rollout yet). */
69
+ live(announced) {
70
+ const live = this.open.map((x) => x.exec);
71
+ if (announced && !this.done.has(announced) && !live.includes(announced))
72
+ live.push(announced);
73
+ return live;
74
+ }
75
+ /** What to do with a nested call now, given the exec the proxy announced and whether a call id is in the rollout. */
76
+ tie(announced, logged) {
77
+ const live = this.live(announced);
78
+ if (live.length > 1)
79
+ return { kind: "ambiguous", live };
80
+ if (live.length === 0)
81
+ return { kind: "none" };
82
+ return logged(live[0]) ? { kind: "tied", exec: live[0] } : { kind: "held", exec: live[0] };
83
+ }
84
+ }
85
+ /** The nested calls the rollout's lines hold a completion for, by their `exec-<uuid>` id. */
86
+ export function completedNested(lines) {
87
+ const out = new Map();
88
+ for (const raw of lines) {
89
+ if (!raw.includes("DynamicToolCall"))
90
+ continue;
91
+ const line = parseLine(raw);
92
+ const p = line?.payload;
93
+ const item = p?.item;
94
+ if (line?.type !== "event_msg" || p?.type !== "item_completed" || item?.type !== "DynamicToolCall" || typeof item.id !== "string")
95
+ continue;
96
+ if (item.status !== "completed" && item.status !== "failed")
97
+ continue;
98
+ out.set(item.id, { tool: String(item.tool ?? ""), ok: item.success !== false && item.status === "completed", text: textOf(item.content_items) });
99
+ }
100
+ return out;
101
+ }
102
+ /** What a nested call came to. The store's record first, the rollout's completion second: both complete and agreeing, or
103
+ * one of them, is that outcome; both complete and disagreeing, or a call that started and has no end in either, is
104
+ * interrupted (its effect is unknown), and a failure the store marks interrupted is interrupted. They agree when the
105
+ * rollout holds what the bridge handed Codex for the stored text: the store's text held to the host's bound
106
+ * (`boundResult`), since the store keeps a result whole and Codex got its cut; or the stored text itself, as a session
107
+ * written before that bound holds it in both records. */
108
+ export function settle(fact) {
109
+ const { store, rollout } = fact;
110
+ const stored = store?.status === "completed" ? { kind: "completed", text: store.text ?? "" } : store?.status === "failed" && !store.interrupted ? { kind: "failed", text: store.text ?? "" } : undefined;
111
+ const rolled = rollout ? { kind: rollout.ok ? "completed" : "failed", text: rollout.text } : undefined;
112
+ if (stored && rolled)
113
+ return stored.kind === rolled.kind && (rolled.text === stored.text || rolled.text === boundResult(stored.text).text) ? stored : { kind: "interrupted" };
114
+ return stored ?? rolled ?? { kind: "interrupted" };
115
+ }
116
+ const quoted = (text) => JSON.stringify(text.length > 2000 ? `${text.slice(0, 2000)}… [${text.length - 2000} more characters]` : text);
117
+ /** The nested calls to list for each cut-off `exec` of the interrupted turn `since`: its own, in order; and the calls whose
118
+ * script could not be told, which ran in that turn, under the LAST cut-off exec only, apart from its own, so each is listed once. */
119
+ export function recoveryFacts(execs, ties, since, factOf) {
120
+ const out = new Map();
121
+ const last = execs.at(-1);
122
+ const loose = ties.filter((t) => t.exec === null && t.since === since).map(factOf);
123
+ for (const exec of execs)
124
+ out.set(exec, { own: ties.filter((t) => t.exec === exec).map(factOf), loose: exec === last ? loose : [] });
125
+ return out;
126
+ }
127
+ const describeCall = (fact, label) => {
128
+ const settled = settle(fact);
129
+ if (settled.kind === "completed")
130
+ return `${label} completed: ${quoted(settled.text)}. Its effect is done; it was not run again.`;
131
+ if (settled.kind === "failed")
132
+ return `${label} failed: ${quoted(settled.text)}. It was not run again.`;
133
+ // Told as the recovery note of the same turn tells it, which reaches the model with this output: a safe tool's call a crash cut off.
134
+ if (fact.told === "retryable")
135
+ return `${label} was started and did not report a result. It is safe to repeat. It was not run again.`;
136
+ return `${label} was started and did not report a result, so it may have taken effect: check before calling it again. It was not run again.`;
137
+ };
138
+ /** The output a cut-off `exec` is answered with: its nested calls, in order, each with what it came to, and that nothing was run
139
+ * again. A completed call's effect is done, a never tool's included; a call with no end is interrupted. `loose`: calls of this turn
140
+ * whose script could not be told (given to the last cut-off exec only), listed apart under their own heading. */
141
+ export function execRecoveryOutput(facts, loose = []) {
142
+ const apart = loose.length
143
+ ? `\n${loose.length} ${loose.length === 1 ? "call" : "calls"} ran whose script could not be told (an answer of the model's could not be read to its end):\n${loose.map((fact, i) => describeCall(fact, `${i + 1}. ${fact.tool}`)).join("\n")}`
144
+ : "";
145
+ if (facts.length === 0 && loose.length > 0)
146
+ return `The exec was cut short, and no call of its own was recorded; the calls below ran, though which script made them could not be told, so do not run it again to find out.${apart}`;
147
+ if (facts.length === 0)
148
+ return `The exec was cut short before any tool call of it was recorded; it ran none. Run it again if it is still needed.`;
149
+ const lines = facts.map((fact, i) => describeCall(fact, `${i + 1}. ${fact.tool}`));
150
+ return `The exec was cut short after these calls (the session stopped), and nothing was run again. Their outcomes, in order:\n${lines.join("\n")}${apart}`;
151
+ }
152
+ /** The text of a tool's recorded output (a string, or `{ text }` with images). */
153
+ export function outputTextOf(output) {
154
+ if (typeof output === "string")
155
+ return output;
156
+ if (output && typeof output === "object" && typeof output.text === "string")
157
+ return output.text;
158
+ return JSON.stringify(output ?? null);
159
+ }
160
+ const canonical = (value) => Array.isArray(value) ? value.map(canonical) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => (a < b ? -1 : 1)).map(([k, v]) => [k, canonical(v)])) : value;
161
+ /** A call by its tool and arguments, whatever the order of the arguments' keys: what a `never` tool's call is matched on. */
162
+ export const callKey = (tool, args) => `${tool}\0${JSON.stringify(canonical(args ?? {}))}`;
@@ -0,0 +1,37 @@
1
+ import { CodexNotInstalled, CodexPinMismatch } from "./versions.js";
2
+ export interface CodexPins {
3
+ /** The release `codex --version` must report. */
4
+ version: string;
5
+ /** The binary's sha256; unchecked when undefined (a target the pins do not list). */
6
+ sha256?: string;
7
+ /** The platform package's version (`<version>-<platform>`), when the binary came from one. */
8
+ packageVersion?: string;
9
+ }
10
+ /** The pins for this platform's binary. */
11
+ export declare function codexPins(target?: {
12
+ target: string;
13
+ pkg: string;
14
+ } | undefined): CodexPins;
15
+ /**
16
+ * The binary at `found.path` checked against `pins`, in order: the platform package's version, the binary's sha256,
17
+ * then the version it reports. Returns the path, or the typed error (not thrown) naming the pin, what was expected and
18
+ * what was found. No path, or a binary that cannot be read or run, is `CodexNotInstalled`. The path is made absolute
19
+ * first, from this process's working directory, and that is the one checked and returned: a session starts the binary
20
+ * from its own directory, where a relative `CODEX_BIN` names nothing. The sha256 is read a chunk at a time, never the
21
+ * whole binary in memory, and a check that passed holds for this process while the binary stays the same file, unchanged
22
+ * (the kernel's checkedOnce): a host that checks it for each model it resolves, and a run's process that makes its
23
+ * adapter, check it once.
24
+ */
25
+ export declare function verifyCodexBinary(found: {
26
+ path: string;
27
+ packageVersion?: string;
28
+ } | undefined, pins?: CodexPins): {
29
+ path: string;
30
+ } | CodexPinMismatch | CodexNotInstalled;
31
+ /** This machine's Codex checked against the pins: its path, or the typed error thrown. */
32
+ export declare function verifyCodex(found?: {
33
+ path: string;
34
+ packageVersion?: string;
35
+ } | undefined, pins?: CodexPins): {
36
+ path: string;
37
+ };
package/dist/verify.js ADDED
@@ -0,0 +1,67 @@
1
+ // The installed Codex checked against the pins (src/versions.ts) before anything runs, with the typed errors a host maps
2
+ // to a run's failure line. Written for AgentRun.
3
+ import { execFileSync } from "node:child_process";
4
+ import { existsSync } from "node:fs";
5
+ import { resolve } from "node:path";
6
+ import { env } from "node:process";
7
+ import { checkedOnce, sha256OfFile } from "@parcha/agentrun-kernel/host";
8
+ import { codexTarget, findCodex } from "./binary.js";
9
+ import { CODEX_BINARY_SHA256, CODEX_VERSION, CodexNotInstalled, CodexPinMismatch } from "./versions.js";
10
+ /** The pins for this platform's binary. */
11
+ export function codexPins(target = codexTarget()) {
12
+ return { version: CODEX_VERSION, sha256: target ? CODEX_BINARY_SHA256[target.target] : undefined, packageVersion: target ? `${CODEX_VERSION}-${target.pkg}` : undefined };
13
+ }
14
+ /**
15
+ * The binary at `found.path` checked against `pins`, in order: the platform package's version, the binary's sha256,
16
+ * then the version it reports. Returns the path, or the typed error (not thrown) naming the pin, what was expected and
17
+ * what was found. No path, or a binary that cannot be read or run, is `CodexNotInstalled`. The path is made absolute
18
+ * first, from this process's working directory, and that is the one checked and returned: a session starts the binary
19
+ * from its own directory, where a relative `CODEX_BIN` names nothing. The sha256 is read a chunk at a time, never the
20
+ * whole binary in memory, and a check that passed holds for this process while the binary stays the same file, unchanged
21
+ * (the kernel's checkedOnce): a host that checks it for each model it resolves, and a run's process that makes its
22
+ * adapter, check it once.
23
+ */
24
+ export function verifyCodexBinary(found, pins = codexPins()) {
25
+ if (!found)
26
+ return new CodexNotInstalled("no Codex binary found for this platform, and CODEX_BIN is not set");
27
+ const path = resolve(found.path);
28
+ if (!existsSync(path))
29
+ return new CodexNotInstalled(`no file at ${path}`);
30
+ if (pins.packageVersion && found.packageVersion !== undefined && found.packageVersion !== pins.packageVersion) {
31
+ return new CodexPinMismatch("package_version", pins.packageVersion, found.packageVersion, path);
32
+ }
33
+ // Hashed a chunk at a time, and once per binary in this process while it stays the same file.
34
+ return checkedOnce(path, JSON.stringify(pins), () => checkBinary(path, pins), (result) => !(result instanceof Error));
35
+ }
36
+ /** The binary at `path` (absolute, there) against `pins`' sha256 and version. */
37
+ function checkBinary(path, pins) {
38
+ if (pins.sha256) {
39
+ let sha256;
40
+ try {
41
+ sha256 = sha256OfFile(path);
42
+ }
43
+ catch (error) {
44
+ return new CodexNotInstalled(`${path} could not be read: ${String(error?.message ?? error).slice(0, 120)}`);
45
+ }
46
+ if (sha256 !== pins.sha256)
47
+ return new CodexPinMismatch("binary_sha256", pins.sha256, sha256, path);
48
+ }
49
+ let reported;
50
+ try {
51
+ reported = execFileSync(path, ["--version"], { env: { PATH: env.PATH ?? "/usr/bin:/bin" }, encoding: "utf8", timeout: 10_000 }).trim();
52
+ }
53
+ catch (error) {
54
+ return new CodexNotInstalled(`${path} could not be run: ${String(error?.message ?? error).slice(0, 120)}`);
55
+ }
56
+ const version = /^codex-cli (\S+)$/.exec(reported)?.[1] ?? JSON.stringify(reported.slice(0, 60));
57
+ if (version !== pins.version)
58
+ return new CodexPinMismatch("version", pins.version, version, path);
59
+ return { path };
60
+ }
61
+ /** This machine's Codex checked against the pins: its path, or the typed error thrown. */
62
+ export function verifyCodex(found = findCodex(), pins = codexPins()) {
63
+ const result = verifyCodexBinary(found, pins);
64
+ if (result instanceof Error)
65
+ throw result;
66
+ return result;
67
+ }
@@ -0,0 +1,33 @@
1
+ import { CODEX_VERSION } from "./binary.js";
2
+ /** The Codex CLI release this adapter is built and tested with (`codex --version` prints `codex-cli <it>`); binary.ts,
3
+ * a copy of upstream's, holds it. */
4
+ export { CODEX_VERSION };
5
+ /** The install line for the pinned release (npm installs this platform's binary package with it). */
6
+ export declare const CODEX_INSTALL = "npm install --save-exact @openai/codex@0.164.0";
7
+ /**
8
+ * npm's integrity of the pinned launcher and of each platform package (an npm alias of
9
+ * `@openai/codex@<version>-<platform>`), as the registry publishes them. npm checks a download against the lockfile's
10
+ * copy of these; test/pins.test.mjs keeps the repository's lockfile equal to them.
11
+ */
12
+ export declare const CODEX_NPM_INTEGRITY: Readonly<Record<string, string>>;
13
+ /** The sha256 of the pinned native binary (`vendor/<target>/bin/codex` in the platform package), per target, read from
14
+ * the published packages those integrities name. A binary for a target listed here runs only if it matches. */
15
+ export declare const CODEX_BINARY_SHA256: Readonly<Record<string, string>>;
16
+ /** Which pin a mismatch is about: the binary's sha256, the version it reports, or the platform package's version. */
17
+ export type CodexPin = "binary_sha256" | "version" | "package_version";
18
+ /** The installed Codex is not the build this adapter is pinned to and checked with: nothing runs. */
19
+ export declare class CodexPinMismatch extends Error {
20
+ readonly pin: CodexPin;
21
+ readonly expected: string;
22
+ readonly found: string;
23
+ readonly path?: string | undefined;
24
+ readonly code = "CODEX_PIN_MISMATCH";
25
+ constructor(pin: CodexPin, expected: string, found: string, path?: string | undefined);
26
+ }
27
+ /** No Codex binary to run: the host has not installed `@openai/codex` (or this platform's package), or the binary named
28
+ * could not be run. */
29
+ export declare class CodexNotInstalled extends Error {
30
+ readonly detail?: string | undefined;
31
+ readonly code = "CODEX_NOT_INSTALLED";
32
+ constructor(detail?: string | undefined);
33
+ }
@@ -0,0 +1,57 @@
1
+ // The Codex build this adapter is pinned to and checked against, and the typed errors a host maps to a run's failure
2
+ // line when the installed build is not it. Written for AgentRun.
3
+ import { CODEX_VERSION } from "./binary.js";
4
+ /** The Codex CLI release this adapter is built and tested with (`codex --version` prints `codex-cli <it>`); binary.ts,
5
+ * a copy of upstream's, holds it. */
6
+ export { CODEX_VERSION };
7
+ /** The install line for the pinned release (npm installs this platform's binary package with it). */
8
+ export const CODEX_INSTALL = `npm install --save-exact @openai/codex@${CODEX_VERSION}`;
9
+ /**
10
+ * npm's integrity of the pinned launcher and of each platform package (an npm alias of
11
+ * `@openai/codex@<version>-<platform>`), as the registry publishes them. npm checks a download against the lockfile's
12
+ * copy of these; test/pins.test.mjs keeps the repository's lockfile equal to them.
13
+ */
14
+ export const CODEX_NPM_INTEGRITY = Object.freeze({
15
+ "@openai/codex": "sha512-TWj7UGyPRe3Pj/A3ddNAxs1te3a/W/xAd+J0LHrrFTmsSfahGMOLF/vn88D3QCIgAT3B1rm1y/Z3NYE0rx6cZQ==",
16
+ "@openai/codex-linux-x64": "sha512-XLAoaWsGOT2khzl+P4FYDPTkzAr9W0VFXFaVkqlFdkM0soa1gH/4S0wSD57Ek3HHwkirAEGz2/Mwehseh+l5Mg==",
17
+ "@openai/codex-linux-arm64": "sha512-LL5iTQjyDL4YRX44EWqhIfEQ5uGnmgxkQBJSxjZSeJ8L1Og83pdlzUJW/PRJ76oaVwOVgh6HXwuPEiBNEHU4lg==",
18
+ "@openai/codex-darwin-x64": "sha512-lIe+udnguPGzBezkgbkj2Eaz0YqOhNXT7jja136Fj0sXfI+UKNS2icmaK14GcoRAgeVEpDTtC1ftamWBPmD1zg==",
19
+ "@openai/codex-darwin-arm64": "sha512-pDizgOUAtq3/k3AbUFHbaU19WpYKCja+oFpNSTLKrDQj4lTUNSDuTPJip4uQVn2/1EipQdpQrGMOQBVuI1znAA==",
20
+ "@openai/codex-win32-x64": "sha512-urWPhwh9YavuoAPIkmVYKBTtd5OtGVL4Ki0Fb28dhK/Mz6Pt4LSy+gbRrZFz5+RXrw9ubvXuXDCcd8beYcWhDg==",
21
+ "@openai/codex-win32-arm64": "sha512-Zkzt8HNmB/vOnlDo5D7IOlrt5rHaxYQB7iGbNP7bHcXZtrk6gaD7UriwaieGYJpcf8DqAT/0tqzY4xbs8ZwbmQ==",
22
+ });
23
+ /** The sha256 of the pinned native binary (`vendor/<target>/bin/codex` in the platform package), per target, read from
24
+ * the published packages those integrities name. A binary for a target listed here runs only if it matches. */
25
+ export const CODEX_BINARY_SHA256 = Object.freeze({
26
+ "x86_64-unknown-linux-musl": "b93f6811d3f653f0fb83be4050d857fb9abbb111dfa2ce160563327daff7f306",
27
+ "aarch64-unknown-linux-musl": "8813c8d8a4cea2eeba271b72ab22f49628b184b24ab18dbef06b4ce41e9a8d39",
28
+ "x86_64-apple-darwin": "d7e19691e0c1945612475ee8ab32e59ead55472e976b5cea1682d827d34dbba1",
29
+ "aarch64-apple-darwin": "d8990e3ee7acfbc26f91265b12a1a83f0fee40d0e0f8f1f40a37d4ec21f499cf",
30
+ });
31
+ /** The installed Codex is not the build this adapter is pinned to and checked with: nothing runs. */
32
+ export class CodexPinMismatch extends Error {
33
+ pin;
34
+ expected;
35
+ found;
36
+ path;
37
+ code = "CODEX_PIN_MISMATCH";
38
+ constructor(pin, expected, found, path) {
39
+ super(`agentrun-harness-codex: the Codex ${pin === "package_version" ? "platform package" : "binary"}${path ? ` at ${path}` : ""} is not the pinned build: its ${pin.replace("_", " ")} is ${found}, not ${expected}`);
40
+ this.pin = pin;
41
+ this.expected = expected;
42
+ this.found = found;
43
+ this.path = path;
44
+ this.name = "CodexPinMismatch";
45
+ }
46
+ }
47
+ /** No Codex binary to run: the host has not installed `@openai/codex` (or this platform's package), or the binary named
48
+ * could not be run. */
49
+ export class CodexNotInstalled extends Error {
50
+ detail;
51
+ code = "CODEX_NOT_INSTALLED";
52
+ constructor(detail) {
53
+ super(`agentrun-harness-codex: Codex ${CODEX_VERSION} is not installed${detail ? ` (${detail})` : ""}; ${CODEX_INSTALL}`);
54
+ this.detail = detail;
55
+ this.name = "CodexNotInstalled";
56
+ }
57
+ }