@parcha/agentrun-harness-codex 0.0.0-stage → 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 +80 -2
  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 +72 -4
  48. package/vendor/durable-harness/UPSTREAM.json +39 -0
@@ -0,0 +1,35 @@
1
+ import type { MachineSpawn, SessionProcess } from './host/process.js';
2
+ /** The catalog's file in `CODEX_HOME`. */
3
+ export declare const MODEL_CATALOG_FILE = "model-catalog.json";
4
+ /**
5
+ * Codex's bundled model catalog with `apply_patch_tool_type` null on every
6
+ * model, every other field as Codex ships it; undefined when the text is not
7
+ * a catalog (an object whose `models` is a non-empty list of objects, each
8
+ * with a `slug`).
9
+ */
10
+ export declare function withoutApplyPatch(bundled: string): string | undefined;
11
+ /** The binary a session runs: its command and the arguments before Codex's own. */
12
+ export interface CodexCommand {
13
+ command: string;
14
+ args?: readonly string[];
15
+ /** Told when the catalog can't be read. */
16
+ log?: (message: string, fields?: Record<string, unknown>) => void;
17
+ }
18
+ /**
19
+ * The catalog without apply_patch for `codex`, read once per binary with
20
+ * `spawn` (`codex debug models --bundled`, its CODEX_HOME `dirs.own`, a
21
+ * directory of its own): its `bytes`, or `why` it can't be read, never
22
+ * silence. The session then runs on Codex's own catalog, apply_patch listed;
23
+ * a failure is not remembered, so the next drive tries again.
24
+ */
25
+ export declare function patchlessCatalog(spawn: (options: MachineSpawn) => SessionProcess | Promise<SessionProcess>, codex: CodexCommand, dirs: {
26
+ home: string;
27
+ tmp: string;
28
+ own: string;
29
+ }, signal?: AbortSignal): Promise<{
30
+ bytes: Uint8Array;
31
+ why?: undefined;
32
+ } | {
33
+ bytes?: undefined;
34
+ why: string;
35
+ }>;
@@ -0,0 +1,104 @@
1
+ // Codex's own apply_patch, off with the built-ins. Written for AgentRun.
2
+ //
3
+ // With the built-ins off, code mode (`code_mode_host`) still lists Codex's `apply_patch` as a nested tool of `exec`, though it
4
+ // has no environment to run in: every call fails "No usable execution environment is available". Codex 0.164 has no feature
5
+ // that removes it (`apply_patch_freeform` is removed); its model catalog's `apply_patch_tool_type` does. So the session's
6
+ // machine (host/machine.ts) reads Codex's own bundled catalog from the binary the session runs (`codex debug models --bundled`),
7
+ // sets that one field null on every model, keeps it in CODEX_HOME beside the seed and names it in Codex's config
8
+ // (`model_catalog_json`, a key an app may not set: config.ts). With the built-ins on, apply_patch runs through the shell and
9
+ // stays.
10
+ import { basename } from 'node:path';
11
+ /** The catalog's file in `CODEX_HOME`. */
12
+ export const MODEL_CATALOG_FILE = 'model-catalog.json';
13
+ /**
14
+ * Codex's bundled model catalog with `apply_patch_tool_type` null on every
15
+ * model, every other field as Codex ships it; undefined when the text is not
16
+ * a catalog (an object whose `models` is a non-empty list of objects, each
17
+ * with a `slug`).
18
+ */
19
+ export function withoutApplyPatch(bundled) {
20
+ let catalog;
21
+ try {
22
+ catalog = JSON.parse(bundled);
23
+ }
24
+ catch {
25
+ return undefined;
26
+ }
27
+ const isObject = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
28
+ if (!isObject(catalog))
29
+ return undefined;
30
+ const models = catalog.models;
31
+ if (!Array.isArray(models) || models.length === 0 || !models.every((m) => isObject(m) && typeof m.slug === 'string'))
32
+ return undefined;
33
+ return JSON.stringify({ ...catalog, models: models.map((m) => ({ ...m, apply_patch_tool_type: null })) });
34
+ }
35
+ /** The catalog each binary gave, once read: one binary, one catalog. */
36
+ const read = new Map();
37
+ /** How long `codex debug models --bundled` may take (it takes milliseconds). */
38
+ const DUMP_MS = 20_000;
39
+ /** Why the session runs on Codex's own catalog, in words for the run (the machine's notes): `cause`, what went wrong. */
40
+ const stillListed = (cause) => `Codex's own apply_patch stays listed: its bundled model catalog could not be read (${cause}). It has no environment to run in here, so a call to it fails: edit files with the host's edit and write tools.`;
41
+ /**
42
+ * The catalog without apply_patch for `codex`, read once per binary with
43
+ * `spawn` (`codex debug models --bundled`, its CODEX_HOME `dirs.own`, a
44
+ * directory of its own): its `bytes`, or `why` it can't be read, never
45
+ * silence. The session then runs on Codex's own catalog, apply_patch listed;
46
+ * a failure is not remembered, so the next drive tries again.
47
+ */
48
+ export async function patchlessCatalog(spawn, codex, dirs, signal) {
49
+ const key = JSON.stringify([codex.command, ...(codex.args ?? [])]);
50
+ const known = read.get(key);
51
+ if (known)
52
+ return { bytes: known };
53
+ const failed = (cause, fields) => {
54
+ // The run's words (the machine's notes) name the binary by its file name and none of the session's directories: no host
55
+ // path, no CODEX_HOME. The host's log keeps them whole (`fields`).
56
+ const named = [[codex.command, basename(codex.command)], [dirs.own, "its own directory"], [dirs.home, "its home"], [dirs.tmp, "its tmp"]];
57
+ const said = named.filter(([path]) => path.length > 1).sort((a, b) => b[0].length - a[0].length).reduce((text, [path, as]) => text.replaceAll(path, as), cause);
58
+ const why = stillListed(said);
59
+ codex.log?.(`codex: ${why}`, fields);
60
+ return { why };
61
+ };
62
+ let child;
63
+ try {
64
+ child = await spawn({
65
+ command: codex.command,
66
+ args: [...(codex.args ?? []), 'debug', 'models', '--bundled'],
67
+ cwd: dirs.own,
68
+ ...(signal ? { signal } : {}),
69
+ env: { HOME: dirs.home, CODEX_HOME: dirs.own, TMPDIR: dirs.tmp, NO_COLOR: '1' },
70
+ isolatedCommands: true,
71
+ });
72
+ }
73
+ catch (err) {
74
+ if (signal?.aborted)
75
+ throw err;
76
+ const error = String(err?.message ?? err).slice(0, 200);
77
+ return failed(`it did not start: ${error}`, { error });
78
+ }
79
+ child.end();
80
+ const out = [];
81
+ const reading = (async () => {
82
+ for await (const line of child.lines())
83
+ out.push(line);
84
+ })().catch(() => { });
85
+ let timer;
86
+ const exit = await Promise.race([child.exited, new Promise((r) => (timer = setTimeout(r, DUMP_MS, undefined)))]);
87
+ clearTimeout(timer);
88
+ if (!exit) {
89
+ child.kill('SIGKILL');
90
+ await child.exited;
91
+ }
92
+ await reading;
93
+ if (signal?.aborted)
94
+ throw signal.reason ?? new Error('agentrun-harness-codex: the drive stopped');
95
+ const catalog = exit?.code === 0 ? withoutApplyPatch(out.join('\n')) : undefined;
96
+ if (!catalog) {
97
+ const stderr = child.stderrTail().trim().slice(-300);
98
+ const cause = !exit ? `no answer in ${DUMP_MS / 1000} s` : exit.code === 0 ? 'its answer is not a catalog' : `exit ${exit.code === null ? `signal ${exit.signal}` : `code ${exit.code}`}${stderr ? `: ${stderr.split('\n').at(-1)}` : ''}`;
99
+ return failed(cause, { exit: exit ?? 'none', stderr });
100
+ }
101
+ const bytes = new TextEncoder().encode(catalog);
102
+ read.set(key, bytes);
103
+ return { bytes };
104
+ }
@@ -0,0 +1,171 @@
1
+ import type { OwnCalls } from "@parcha/agentrun-kernel";
2
+ import type { DriveContext } from "./host/kernel.js";
3
+ import type { ResultBudget, SessionMachine } from "./host/process.js";
4
+ import { type RolloutSummary } from "./rollout.js";
5
+ /** 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. */
6
+ export declare const NESTED_STREAM = "codex.nested";
7
+ /** The stream that records the interrupted turns whose recovery note was injected: `{ since }`, once per interrupted turn. */
8
+ export declare const RECOVERY_NOTE_STREAM = "codex.recovery-note";
9
+ /** A yielded exec's nested call run on a resume (recoverItems), written before it runs: a later recovery of the same turn tells
10
+ * the model's `wait` its outcome from the session's record, never running it again. */
11
+ export declare const RESUMED_STREAM = "codex.nested-resumed";
12
+ /** The nested calls whose outcome a resume's recovered script output tells (recoverItems): `{ since, callIds }`, written before
13
+ * that output is injected, so the turn's recovery note says the outcome is there, after a crash between the two as well. */
14
+ export declare const SHOWN_STREAM = "codex.nested-shown";
15
+ /** Each `exec` a recovery answered (recoverItems), directly or through the `wait` on its cell, and whether that answer tells a
16
+ * script that failed (recoveredFailed): `{ exec, failed }`, written before the answer is injected. That answer carries no status
17
+ * 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. */
18
+ export declare const RECOVERED_END_STREAM = "codex.exec-recovered-end";
19
+ interface Journal {
20
+ append(stream: string, record: unknown): void;
21
+ flush(): Promise<void>;
22
+ read<T>(stream: string): Promise<{
23
+ data: T;
24
+ }[]>;
25
+ }
26
+ export interface CodeModeDeps {
27
+ ctx: DriveContext;
28
+ machine: SessionMachine;
29
+ journal: Journal;
30
+ /** The calls whose line is in the log: the harness's barrier looks here, so a call admitted here passes it. */
31
+ logged: Set<string>;
32
+ /** Drain the rollout's tail into the log. */
33
+ synced(): Promise<void>;
34
+ /** The tool bridge; `take` gives a call's images and value once (host/process.ts), for the answer to Codex. */
35
+ bridge: {
36
+ get(name: string): {
37
+ name: string;
38
+ replay: string;
39
+ } | undefined;
40
+ take?(callId: string): {
41
+ images?: readonly {
42
+ mimeType: string;
43
+ data: string;
44
+ }[];
45
+ structured?: unknown;
46
+ } | undefined;
47
+ /** A call through the bridge (gate, intent, call, result): a resumed nested call that never reached its intent (recoverItems). */
48
+ call?(name: string, args: unknown, callId: string): Promise<{
49
+ text: string;
50
+ isError: boolean; /** The gate refused it: it never ran. */
51
+ refused?: true;
52
+ }>;
53
+ };
54
+ log(message: string, fields?: Record<string, unknown>): void;
55
+ /** The rollout lines restored from the log. */
56
+ lines: readonly string[];
57
+ rpc(): {
58
+ request(method: string, params: Record<string, unknown>): Promise<unknown>;
59
+ };
60
+ guard<T>(promise: Promise<T>): Promise<T>;
61
+ threadId(): string;
62
+ /** How often the barrier looks again for a script's line, and what a declined call is told. */
63
+ tries: number;
64
+ declined: string;
65
+ /** The host's record of each `exec` (SessionIO.ownCalls): its row from its rollout lines, and each nested call it makes
66
+ * named under it before the call reaches the gate. */
67
+ ownCalls?: OwnCalls;
68
+ /** The bridge's budget (CodexHarnessOptions.resultBudget): a result handed Codex from the log is held to it as the
69
+ * bridge holds one it runs. */
70
+ budget?: ResultBudget;
71
+ /** Told, live, when the code-mode host did not run a script to its end, and the turn fails on it: Codex answered its `exec`
72
+ * (or the `wait` on its cell) with no script status (ScriptEvent.unrun, Codex's words; scripts.ts SCRIPT_STATUS), whether or
73
+ * not a nested call of it ran first (a script that lost its host part way is no completed turn); or the host left the
74
+ * `exec` or `wait` unanswered for `ms` (HOST_SILENCE_MS past its yield), with no nested call of it running. Not for an
75
+ * output this drive wrote itself (a recovered exec's). `text`: what to say of it. */
76
+ hostFailed?(text: string): void;
77
+ /** When the invocation ends (the harness's deadline): a script's wait is not bounded past it. */
78
+ deadline?: number;
79
+ }
80
+ /** How long past its yield (the time Codex waits on an `exec` or a `wait` before it answers "Script running") the code-mode host
81
+ * may leave one unanswered, no nested call of it running, before the turn fails. The first `exec` of a session also starts
82
+ * the host: Codex gives up on its handshake by itself at about 30 s, inside this. Codex itself waits on the host without
83
+ * bound: a host that took the session and then went quiet held the turn open until the invocation was stopped. */
84
+ export declare const HOST_SILENCE_MS = 60000;
85
+ interface Dangling {
86
+ callId: string;
87
+ name: string;
88
+ /** `function_call` or `custom_tool_call` (code mode's `exec`, Codex's own `apply_patch`). */
89
+ type: string;
90
+ arguments?: string;
91
+ }
92
+ /** 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
93
+ * wrong kind), a custom tool call output for a custom tool call such as `apply_patch`, a function call output for any other. */
94
+ export declare function withOutputKind<T extends {
95
+ call_id?: unknown;
96
+ output?: unknown;
97
+ }>(item: T, call: Dangling): T & {
98
+ type: string;
99
+ };
100
+ /** 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. */
101
+ export declare const waitStoppedText: (cell: string) => string;
102
+ /** A recorded result that held images (bridgeTool's `{ text, images }`) as its text and a line saying how many, which are not
103
+ * shown again after the interruption; undefined for a result with none, whose repaired output stays as it is. */
104
+ export declare function imagesNoted(output: unknown): string | undefined;
105
+ type Image = {
106
+ mimeType: string;
107
+ data: string;
108
+ };
109
+ /** `value` with `images`' data put back, in order, into its image objects (`{ type: "image", mimeType }` with no data,
110
+ * as a computer tool's value leaves them): the value whole, as serve's own script isolate gives a script. */
111
+ export declare function withImageData(value: unknown, images: readonly Image[]): unknown;
112
+ /** A nested call's answer from a tool with no value: its items, then a line saying how many images the tool returned,
113
+ * 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
114
+ * result would send the model the base64 as words); an answer of any other shape, or no images, as it is. */
115
+ export declare function withImagesHeld(answer: unknown, images: readonly unknown[] | undefined): unknown;
116
+ /** A code-mode script's nested call's answer. A tool with a value (a computer tool's) answers the value as JSON text,
117
+ * its images' data back in it, so the script reads it with JSON.parse and holds each image whole, to compute on or
118
+ * pass on; any other tool answers its words and a line on its images, which are not sent (`withImagesHeld`). A failed
119
+ * call's answer, or one of any other shape, as it is. */
120
+ export declare function scriptAnswer(answer: unknown, extras: {
121
+ images?: readonly Image[];
122
+ structured?: unknown;
123
+ } | undefined): unknown;
124
+ /** A dynamic tool call's answer with `images` after its items, each `{ type: "inputImage", imageUrl }` with a data: URL
125
+ * (Codex 0.164's DynamicToolCallOutputContentItem); an answer of any other shape, or no images, as it is. */
126
+ export declare function withImages(answer: unknown, images: readonly {
127
+ mimeType: string;
128
+ data: string;
129
+ }[] | undefined): unknown;
130
+ export declare function codeMode(deps: CodeModeDeps): {
131
+ /** The app-server's request handler, with a code-mode host tool call handled before the harness's own. */
132
+ request<R extends {
133
+ method: string;
134
+ params?: Record<string, unknown>;
135
+ }>(next: (req: R) => Promise<unknown>): (req: R) => Promise<unknown>;
136
+ /** 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`';
137
+ * 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
138
+ * 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
139
+ * 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
140
+ * both repairs (with a recovery note and without) inject what this leaves. A recovered script's output (a cut-off exec's, a resumed
141
+ * `wait`'s) quotes each finished call's result as the script was handed it and holds its whole to its own bound
142
+ * (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
143
+ * parked nested calls run now; the repair of an ended turn (repairUnnoted) only tells, and runs nothing. */
144
+ recoverItems(items: Record<string, unknown>[], dangling: readonly Dangling[], lines: readonly string[], since: number, resume?: boolean): Promise<void>;
145
+ /** 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
146
+ * them (one interrupted mid-call, or settled instead of resumed) left them dangling, and the provider refuses a history with a call unanswered.
147
+ * Nothing is armed here: a new turn that calls a `never` call the ended turn completed runs it. */
148
+ repairUnnoted(lines: readonly string[]): Promise<void>;
149
+ /** 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
150
+ * the model as a developer message, injected once for this interrupted turn (every turn opens with `thread/resume`, so injecting on each
151
+ * 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. */
152
+ resumeTurn(note: {
153
+ turn: {
154
+ since: number;
155
+ };
156
+ pending: {
157
+ text?: string;
158
+ }[];
159
+ }, owed: {
160
+ text?: string;
161
+ }[]): Promise<string>;
162
+ /** After a crash, in a turn Codex ended completed: what is said of the first `exec` of its last Codex turn that Codex answered
163
+ * with no script status (as hostFailed says it live), if one is there and no recovery answered it (RECOVERED_END_STREAM: that
164
+ * answer is the adapter's, with no header of its own). Codex can end its turn completed before the harness's interrupt
165
+ * 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
166
+ * leave the recovery to end completed a turn whose script the host never ran. */
167
+ unrunInLastTurn(lines: readonly string[]): Promise<string | undefined>;
168
+ /** A turn ended: the calls answered from the log were for it alone. */
169
+ turnEnded(): void;
170
+ };
171
+ export type { RolloutSummary };