@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/CHANGELOG.md +89 -0
- package/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +72 -2
- package/dist/adapter.d.ts +67 -0
- package/dist/adapter.js +295 -0
- package/dist/app-server.d.ts +53 -0
- package/dist/app-server.js +105 -0
- package/dist/binary.d.ts +31 -0
- package/dist/binary.js +74 -0
- package/dist/code-mode.d.ts +90 -0
- package/dist/code-mode.js +204 -0
- package/dist/config.d.ts +81 -0
- package/dist/config.js +208 -0
- package/dist/harness.d.ts +200 -0
- package/dist/harness.js +1100 -0
- package/dist/host/kernel.d.ts +20 -0
- package/dist/host/kernel.js +3 -0
- package/dist/host/machine.d.ts +65 -0
- package/dist/host/machine.js +303 -0
- package/dist/host/policy.d.ts +87 -0
- package/dist/host/policy.js +609 -0
- package/dist/host/process.d.ts +145 -0
- package/dist/host/process.js +28 -0
- package/dist/host/sandbox.d.ts +35 -0
- package/dist/host/sandbox.js +34 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +6 -0
- package/dist/rollout.d.ts +102 -0
- package/dist/rollout.js +185 -0
- package/dist/schema.d.ts +14 -0
- package/dist/schema.js +178 -0
- package/dist/scripts.d.ts +94 -0
- package/dist/scripts.js +162 -0
- package/dist/verify.d.ts +37 -0
- package/dist/verify.js +67 -0
- package/dist/versions.d.ts +33 -0
- package/dist/versions.js +57 -0
- package/package.json +68 -4
- package/vendor/durable-harness/UPSTREAM.json +39 -0
package/dist/adapter.js
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
// Codex as an AgentRun harness adapter. Written for AgentRun.
|
|
2
|
+
//
|
|
3
|
+
// A session is the copied Codex harness (harness.ts) driven over the session's own records (the kernel's openDrive on
|
|
4
|
+
// the writer the runner lends, `io.writer`), on a local machine (host/machine.ts): Codex's app-server with its built-in tools off, its
|
|
5
|
+
// model behind the session's loopback proxy (@parcha/agentrun-kernel/host), and the host's tools, exactly those `spec.tools` names,
|
|
6
|
+
// as its only tools (beside the provider's own web search, when `webSearch` turns it on). Every paid request passes the
|
|
7
|
+
// runner's `beforeRequest` first, and its usage comes back through `afterRequest`.
|
|
8
|
+
//
|
|
9
|
+
// The host's skills (`skills`) are the only skills Codex lists to the model: written into the session's CODEX_HOME at the
|
|
10
|
+
// start of every drive, where Codex finds a user's skills even in a turn with no environment, and Codex's own bundled
|
|
11
|
+
// skills turned off. With no shell, the model reads a skill's files with `read_skill_file`.
|
|
12
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
13
|
+
import { join } from "node:path";
|
|
14
|
+
import { HOST_RESULT_MAX_CHARS, READ_SKILL_FILE, readSkillFileTool, skillProblems, toolSchemaProblems } from "@parcha/agentrun-kernel";
|
|
15
|
+
import { abortedOutcome, openDrive, SessionHalt } from "@parcha/agentrun-kernel/kernel";
|
|
16
|
+
import { pendingSubmissions } from "@parcha/agentrun-kernel/kernel";
|
|
17
|
+
import { NativeJournal, recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
|
|
18
|
+
import { CODEX_VERSION } from "./binary.js";
|
|
19
|
+
import { codexSchemaProblems, describedDescription } from "./schema.js";
|
|
20
|
+
import { withCheckedBinary } from "./host/sandbox.js";
|
|
21
|
+
import { verifyCodex } from "./verify.js";
|
|
22
|
+
import { codexHarness, owedSubmissions } from "./harness.js";
|
|
23
|
+
import { isRolloutPath, isSessionMeta, rolloutStream, summarizeRollout, THREAD_STREAM } from "./rollout.js";
|
|
24
|
+
import { localMachine, sessionDir } from "./host/machine.js";
|
|
25
|
+
import { serialWriter } from "@parcha/agentrun-kernel/host";
|
|
26
|
+
/** A name app-server accepts for a dynamic tool. */
|
|
27
|
+
const TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;
|
|
28
|
+
/**
|
|
29
|
+
* Codex's `tool_output_token_limit`: the host's result bound (HOST_RESULT_MAX_CHARS), as Codex counts it. Codex keeps a
|
|
30
|
+
* tool's output in the model's history within its truncation policy (10,000 tokens for each model its catalog holds, less
|
|
31
|
+
* for one it does not) and cuts the middle of a longer one; this sets the policy. Codex counts a token as four bytes of
|
|
32
|
+
* UTF-8, and a character (a UTF-16 unit) takes at most three, so a result within the bound in any script takes at most
|
|
33
|
+
* three quarters of a token a character: not a quarter, which holds for ASCII alone.
|
|
34
|
+
*/
|
|
35
|
+
export const CODEX_TOOL_OUTPUT_TOKENS = Math.ceil((HOST_RESULT_MAX_CHARS * 3) / 4);
|
|
36
|
+
/** The kernel's tool for a host tool: the same name, schema and replay policy; a host's error result is the call's failure.
|
|
37
|
+
* The call runs as a kernel effect, whose intent is durable in the session's records before `execute` is entered, so a
|
|
38
|
+
* crash inside a `never` tool is always reported, never repeated. The copied harness's wait for Codex's own `function_call`
|
|
39
|
+
* line before it runs such a tool is a second guard (the transcript Codex resumes from), not the one that protects it. */
|
|
40
|
+
function kernelTool(tool) {
|
|
41
|
+
return {
|
|
42
|
+
name: tool.name,
|
|
43
|
+
// Codex strips some keywords from the schema its model is given: they are said in plain words in the description
|
|
44
|
+
// (the schema itself is the host's, and every call is checked against it).
|
|
45
|
+
description: describedDescription(tool.description, tool.inputSchema),
|
|
46
|
+
inputSchema: tool.inputSchema,
|
|
47
|
+
replay: tool.replay,
|
|
48
|
+
async execute(input, io) {
|
|
49
|
+
// The effect's step is `tool:<Codex call id>#<attempt>`: the host sees Codex's call id.
|
|
50
|
+
const callId = (io.stepId ?? "").replace(/^tool:/, "").replace(/#\d+$/, "");
|
|
51
|
+
const result = await tool.call(input, { callId, signal: io.signal });
|
|
52
|
+
if (result.isError)
|
|
53
|
+
throw new Error(result.text);
|
|
54
|
+
return result.text;
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
/** The adapter's event for a harness live event, if it has one. */
|
|
59
|
+
function adapterEvent(event) {
|
|
60
|
+
const e = event;
|
|
61
|
+
if (e?.type === "text" && typeof e.delta === "string")
|
|
62
|
+
return { type: "text", delta: e.delta };
|
|
63
|
+
if (e?.type === "tool_start" && typeof e.name === "string")
|
|
64
|
+
return { type: "tool_start", callId: String(e.callId ?? ""), name: e.name, args: e.args };
|
|
65
|
+
if (e?.type === "tool_end" && typeof e.name === "string")
|
|
66
|
+
return { type: "tool_end", callId: String(e.callId ?? ""), name: e.name, isError: e.isError === true, ...(e.truncated === true ? { truncated: true } : {}) };
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
const turnsIn = (drive) => transcriptOf(drive.state()).filter((r) => r.data?.type === "turn");
|
|
70
|
+
/** Where Codex finds a user's skills: `$CODEX_HOME/skills`. It lists those to the model in a turn with no environment
|
|
71
|
+
* (this adapter's, with the built-ins off), where it lists none of a working directory's `.agents/skills`. */
|
|
72
|
+
const SKILLS_DIR = "skills";
|
|
73
|
+
/** The skills as the files the session's CODEX_HOME holds (`skills/<name>/<path>`): the machine's seed. */
|
|
74
|
+
function skillsSeed(skills) {
|
|
75
|
+
return { dir: "codex-home", files: Object.fromEntries(skills.flatMap((skill) => Object.entries(skill.files).map(([path, text]) => [`${SKILLS_DIR}/${skill.name}/${path}`, text]))) };
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* The mirrored rollout the next drive resumes Codex from, by the harness's own rule (harness.ts, `resume`: the last
|
|
79
|
+
* thread, its first line `session_meta`, its path the one the harness derives); none when it would start a new thread.
|
|
80
|
+
* The settle reads only this, so it and the next Codex agree on what Codex has. The copied harness keeps its own copy
|
|
81
|
+
* of the rule: its own patch budget has no room for a call here.
|
|
82
|
+
*/
|
|
83
|
+
export async function resumedRollout(journal) {
|
|
84
|
+
const thread = journal.records(THREAD_STREAM).at(-1)?.data;
|
|
85
|
+
const restored = thread ? (await journal.read(rolloutStream(thread.threadId))).map((r) => r.data) : [];
|
|
86
|
+
return thread && isSessionMeta(restored[0]) && isRolloutPath(thread.path, thread.threadId) ? restored : [];
|
|
87
|
+
}
|
|
88
|
+
export function codexAdapter(options) {
|
|
89
|
+
if (options.webSearch !== undefined && options.webSearch !== "live")
|
|
90
|
+
throw new TypeError("agentrun-harness-codex: webSearch is \"live\" or absent");
|
|
91
|
+
// The skills first: a skill Codex would skip or list under another name is the host's to fix, binary or not.
|
|
92
|
+
const skills = options.skills ?? [];
|
|
93
|
+
const skillsWrong = skillProblems(skills);
|
|
94
|
+
if (skillsWrong.length)
|
|
95
|
+
throw new Error(`agentrun-harness-codex: ${skillsWrong.join("; ")}`);
|
|
96
|
+
const seed = skills.length ? skillsSeed(skills) : undefined;
|
|
97
|
+
// The binary is checked once, here, against the pins: a mismatch or a missing binary is the host's to report, before
|
|
98
|
+
// any run starts (CodexPinMismatch, CodexNotInstalled). A test's stand-in runs no Codex.
|
|
99
|
+
const checked = options.standIn ? undefined : verifyCodex().path;
|
|
100
|
+
const modelFor = (spec) => {
|
|
101
|
+
if (typeof options.model === "string")
|
|
102
|
+
return options.model;
|
|
103
|
+
return (spec.tier && spec.tier !== "default" ? options.model[spec.tier] : undefined) ?? options.model.default;
|
|
104
|
+
};
|
|
105
|
+
return {
|
|
106
|
+
id: "codex",
|
|
107
|
+
version: CODEX_VERSION,
|
|
108
|
+
capabilities: () => ({ fork: false }),
|
|
109
|
+
check(spec) {
|
|
110
|
+
const problems = [];
|
|
111
|
+
if (spec.context === "fork")
|
|
112
|
+
problems.push("Codex sessions cannot fork another session's transcript; declare context: \"fresh\"");
|
|
113
|
+
const seen = new Set();
|
|
114
|
+
for (const tool of spec.tools) {
|
|
115
|
+
if (!TOOL_NAME.test(tool.name))
|
|
116
|
+
problems.push(`the tool name ${JSON.stringify(tool.name.slice(0, 80))} is not one Codex accepts (letters, digits, _ and -, at most 64)`);
|
|
117
|
+
if (seen.has(tool.name))
|
|
118
|
+
problems.push(`the tool ${tool.name} is given twice`);
|
|
119
|
+
if (skills.length && tool.name === READ_SKILL_FILE)
|
|
120
|
+
problems.push(`the tool name ${READ_SKILL_FILE} is the adapter's own when it has skills`);
|
|
121
|
+
seen.add(tool.name);
|
|
122
|
+
// What no harness takes (an object root, valid 2020-12, no remote $ref), then what Codex would drop or retype in
|
|
123
|
+
// the tool's schema: refused here, by name, not found out mid-turn. A place the first already refused is not
|
|
124
|
+
// refused again by the second.
|
|
125
|
+
// Nothing in it may throw: a tool whose schema cannot be checked is a problem at "/", naming the tool.
|
|
126
|
+
try {
|
|
127
|
+
const shared = toolSchemaProblems(tool.name, tool.inputSchema);
|
|
128
|
+
// A schema the shared check refuses as a whole (its root, or that it is not JSON: a cycle only code can build)
|
|
129
|
+
// is not walked again: Codex's rules would never reach the end of a cycle.
|
|
130
|
+
const wholly = shared.some((problem) => problem.startsWith(`${tool.name}: /:`));
|
|
131
|
+
const refusedAt = new Set(shared.map((problem) => /^[^:]*: (\S+):/.exec(problem)?.[1]));
|
|
132
|
+
problems.push(...shared, ...(wholly ? [] : codexSchemaProblems(tool.name, tool.inputSchema).filter((problem) => !refusedAt.has(/^[^:]*: (\S+):/.exec(problem)?.[1]))));
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
problems.push(`${tool.name}: /: the tool's schema could not be checked (${String(error?.message ?? error).slice(0, 120)})`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return problems;
|
|
139
|
+
},
|
|
140
|
+
async open(spec, io) {
|
|
141
|
+
const problems = this.check(spec);
|
|
142
|
+
if (problems.length)
|
|
143
|
+
throw new Error(`agentrun-harness-codex: ${problems.join("; ")}`);
|
|
144
|
+
const dir = io.dir ?? (options.sessionsDir ? join(options.sessionsDir, createHash("sha256").update(spec.key).digest("hex").slice(0, 32)) : undefined);
|
|
145
|
+
if (!dir)
|
|
146
|
+
throw new Error("agentrun-harness-codex: a session needs a private directory: the host lends one (io.dir), or pass sessionsDir");
|
|
147
|
+
// With skills the model also reads their files (read_skill_file), from the session's own copy of them.
|
|
148
|
+
const tools = skills.length ? [...spec.tools, readSkillFileTool(join(sessionDir(dir, "codex-home"), SKILLS_DIR), skills.map((skill) => ({ name: skill.name, files: Object.keys(skill.files) })))] : spec.tools;
|
|
149
|
+
const effort = spec.effort ?? spec.thinking;
|
|
150
|
+
const harnessOptions = {
|
|
151
|
+
tools: tools.map(kernelTool),
|
|
152
|
+
builtins: false,
|
|
153
|
+
// Codex's bundled skills (imagegen, skill-installer, ...), which it writes under `$CODEX_HOME/skills/.system` at every
|
|
154
|
+
// start, are off in every session, skills or not: the model is shown the host's skills and no others.
|
|
155
|
+
// Codex's `<permissions instructions>` message is off too. It describes Codex's own sandbox ("`sandbox_mode` is
|
|
156
|
+
// `read-only`: The sandbox only permits reading files"), which binds only Codex's built-in tools, and those are off
|
|
157
|
+
// here. The host's tools write, and a model that believed the message refused to write at all (autoqa F13).
|
|
158
|
+
// A host tool's result within the host's bound reaches the model whole (CODEX_TOOL_OUTPUT_TOKENS).
|
|
159
|
+
config: { skills: { bundled: { enabled: false } }, include_permissions_instructions: false, tool_output_token_limit: CODEX_TOOL_OUTPUT_TOKENS },
|
|
160
|
+
model: modelFor(spec),
|
|
161
|
+
...(spec.system.length ? { instructions: spec.system.join("\n\n") } : {}),
|
|
162
|
+
...(effort ? { effort } : {}),
|
|
163
|
+
credential: async () => options.provider.credential(),
|
|
164
|
+
gatewayUrl: options.provider.origin,
|
|
165
|
+
contextWindow: options.contextWindow ?? 272_000,
|
|
166
|
+
...(options.log ? { log: options.log } : {}),
|
|
167
|
+
...(options.standIn ? { test: { command: options.standIn.command, args: options.standIn.args ?? [] } } : {}),
|
|
168
|
+
machine: {
|
|
169
|
+
...(options.standIn?.env ? { env: options.standIn.env } : {}),
|
|
170
|
+
acquire: localMachine({
|
|
171
|
+
dir,
|
|
172
|
+
// The host's workspace, when it names one: Codex works where the host's file tools write (io.cwd).
|
|
173
|
+
...(io.cwd ? { cwd: io.cwd } : {}),
|
|
174
|
+
...(options.confine ? { confine: options.confine } : {}),
|
|
175
|
+
...(seed ? { seed } : {}),
|
|
176
|
+
...(options.webSearch ? { webSearch: options.webSearch } : {}),
|
|
177
|
+
proxy: {
|
|
178
|
+
hooks: io.models,
|
|
179
|
+
tools: tools.map((t) => t.name),
|
|
180
|
+
...(options.log ? { log: options.log } : {}),
|
|
181
|
+
...(options.price ? { price: options.price } : {}),
|
|
182
|
+
...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}),
|
|
183
|
+
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
184
|
+
},
|
|
185
|
+
}),
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
const harness = checked === undefined ? codexHarness(harnessOptions) : withCheckedBinary(checked, () => codexHarness(harnessOptions));
|
|
189
|
+
const live = (event) => {
|
|
190
|
+
const mapped = adapterEvent(event);
|
|
191
|
+
if (mapped)
|
|
192
|
+
io.onEvent(mapped);
|
|
193
|
+
};
|
|
194
|
+
// Every drive of this session writes through one serialized writer, so a drive opened after an interrupt reads only
|
|
195
|
+
// once the halted drive's last writes are in.
|
|
196
|
+
const writer = serialWriter(io.writer);
|
|
197
|
+
const open = () => openDrive({ writer, signal: io.signal, live });
|
|
198
|
+
let drive = await open();
|
|
199
|
+
const initial = drive.state();
|
|
200
|
+
// A turn is open while the session holds input no turn placed, or a turn with no end (its recovery note).
|
|
201
|
+
const holdsTurn = (folded) => Boolean(recoveryNote(folded)) || pendingSubmissions(folded).length > 0;
|
|
202
|
+
let state = holdsTurn(initial)
|
|
203
|
+
? "open_turn"
|
|
204
|
+
: initial.submissions.length === 0 && turnsIn(drive).length === 0 ? "new" : "idle";
|
|
205
|
+
let running;
|
|
206
|
+
let closed = false;
|
|
207
|
+
const run = () => {
|
|
208
|
+
const before = turnsIn(drive).length;
|
|
209
|
+
const current = drive;
|
|
210
|
+
state = "idle";
|
|
211
|
+
running = (async () => {
|
|
212
|
+
let outcome;
|
|
213
|
+
try {
|
|
214
|
+
await harness.drive(current);
|
|
215
|
+
const ended = turnsIn(current).slice(before).at(-1)?.data;
|
|
216
|
+
outcome = ended?.status ? { status: ended.status, ...(ended.error ? { error: ended.error } : {}) } : { status: "failed", error: "the turn ended with no outcome in the session's records" };
|
|
217
|
+
}
|
|
218
|
+
catch (error) {
|
|
219
|
+
// Stopped by the session or its host: interrupted. Halted by anything else: failed, naming why.
|
|
220
|
+
outcome = current.signal.aborted
|
|
221
|
+
? abortedOutcome(current.signal, io.signal)
|
|
222
|
+
: { status: "failed", error: String(error?.message ?? error).slice(0, 500) };
|
|
223
|
+
// A stop that landed before this turn ran (while send() was still recording its prompt) found no turn to stop,
|
|
224
|
+
// and reads the session as it was: the turn is open now, its prompt pending, so it reads open_turn.
|
|
225
|
+
if (current.signal.aborted)
|
|
226
|
+
state = holdsTurn(current.state()) ? "open_turn" : "idle";
|
|
227
|
+
}
|
|
228
|
+
io.onEvent({ type: "turn_end", status: outcome.status });
|
|
229
|
+
return outcome;
|
|
230
|
+
})();
|
|
231
|
+
return running;
|
|
232
|
+
};
|
|
233
|
+
// A drive that was halted (an interrupt) holds the session no more: the next turn opens a fresh one, on the same
|
|
234
|
+
// writer (the adapter never opens the session itself).
|
|
235
|
+
const ready = async () => {
|
|
236
|
+
if (closed)
|
|
237
|
+
throw new Error("agentrun-harness-codex: the session is closed");
|
|
238
|
+
if (running)
|
|
239
|
+
await running;
|
|
240
|
+
if (drive.signal.aborted && !io.signal.aborted)
|
|
241
|
+
drive = await open();
|
|
242
|
+
};
|
|
243
|
+
return {
|
|
244
|
+
get state() { return state; },
|
|
245
|
+
async send(text) {
|
|
246
|
+
await ready();
|
|
247
|
+
await drive.submit({ id: randomUUID(), kind: "prompt", text });
|
|
248
|
+
void run();
|
|
249
|
+
},
|
|
250
|
+
async recover() {
|
|
251
|
+
if (state !== "open_turn")
|
|
252
|
+
throw new Error("agentrun-harness-codex: there is no turn to recover");
|
|
253
|
+
await ready();
|
|
254
|
+
void run();
|
|
255
|
+
},
|
|
256
|
+
async settleOpenTurn(options = {}) {
|
|
257
|
+
if (state !== "open_turn")
|
|
258
|
+
throw new Error("agentrun-harness-codex: there is no turn to settle");
|
|
259
|
+
await ready();
|
|
260
|
+
// The turn's end in the session's own transcript, as a turn that ends writes it: the next open finds no open turn,
|
|
261
|
+
// and the next turn carries no recovery of this one. Nothing is sent. A prompt the turn placed that Codex never
|
|
262
|
+
// recorded (the stop came before its rollout held it: Codex answers turn/start first) is carried into the next
|
|
263
|
+
// message, as an unplaced one is; a follow-up's own is not. The record is the rollout as the session keeps it (its
|
|
264
|
+
// mirror, which a stopped drive adds nothing to), the rollout the next Codex is resumed from: a prompt it lacks the
|
|
265
|
+
// next turn's model never saw, so carrying it never sends it twice.
|
|
266
|
+
const folded = drive.state();
|
|
267
|
+
const rollout = await resumedRollout(new NativeJournal(drive));
|
|
268
|
+
const unsent = owedSubmissions(folded, recoveryNote(folded)?.turn.placed ?? [], summarizeRollout(rollout).clientIds).map((s) => s.id);
|
|
269
|
+
await settleTurn(drive, { unsent, ...(options.opening === undefined ? {} : { host: options.opening }) });
|
|
270
|
+
state = "idle";
|
|
271
|
+
},
|
|
272
|
+
async turnEnd() {
|
|
273
|
+
if (!running)
|
|
274
|
+
throw new Error("agentrun-harness-codex: no turn is in flight");
|
|
275
|
+
return running;
|
|
276
|
+
},
|
|
277
|
+
async interrupt() {
|
|
278
|
+
drive.halt?.(new SessionHalt("interrupted"));
|
|
279
|
+
await running?.catch(() => { });
|
|
280
|
+
// The turn it stopped is still open in the session (an interrupt writes no end, and a prompt it stopped before
|
|
281
|
+
// the harness placed it is still pending): open_turn, so a host that is done with it settles it here.
|
|
282
|
+
if (holdsTurn(drive.state()))
|
|
283
|
+
state = "open_turn";
|
|
284
|
+
},
|
|
285
|
+
async close() {
|
|
286
|
+
if (closed)
|
|
287
|
+
return;
|
|
288
|
+
closed = true;
|
|
289
|
+
drive.halt?.(new SessionHalt("closed"));
|
|
290
|
+
await running?.catch(() => { });
|
|
291
|
+
},
|
|
292
|
+
};
|
|
293
|
+
},
|
|
294
|
+
};
|
|
295
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { LineChannel } from './host/process.js';
|
|
2
|
+
/**
|
|
3
|
+
* A JSON-RPC 2.0 client for `codex app-server --stdio`, over a child's stdio
|
|
4
|
+
* as a `LineChannel`: one JSON object per line each way. In a session's VM
|
|
5
|
+
* the channel is the relay's `RemoteProcess` (docs/workspaces.md §5.6); a
|
|
6
|
+
* test can hand it any channel.
|
|
7
|
+
*
|
|
8
|
+
* Three kinds of message arrive: responses to our requests, notifications
|
|
9
|
+
* (`item/*`, `turn/*`, deltas), and requests from the server that block
|
|
10
|
+
* until we answer them (`item/tool/call`, approvals). `onRequest` answers
|
|
11
|
+
* the latter; a handler that throws is answered with a JSON-RPC error.
|
|
12
|
+
*/
|
|
13
|
+
export interface RpcNotification {
|
|
14
|
+
method: string;
|
|
15
|
+
params?: any;
|
|
16
|
+
}
|
|
17
|
+
export interface RpcServerRequest extends RpcNotification {
|
|
18
|
+
id: number | string;
|
|
19
|
+
}
|
|
20
|
+
/** A JSON-RPC error app-server answered with. */
|
|
21
|
+
export declare class RpcError extends Error {
|
|
22
|
+
readonly method: string;
|
|
23
|
+
readonly code: number;
|
|
24
|
+
readonly data?: unknown | undefined;
|
|
25
|
+
constructor(method: string, code: number, message: string, data?: unknown | undefined);
|
|
26
|
+
}
|
|
27
|
+
export interface AppServerOptions {
|
|
28
|
+
onNotification?: (n: RpcNotification) => void;
|
|
29
|
+
onRequest?: (r: RpcServerRequest) => Promise<unknown>;
|
|
30
|
+
/** A line that is not JSON (app-server logs go to stderr; this should not happen). */
|
|
31
|
+
onNoise?: (line: string) => void;
|
|
32
|
+
}
|
|
33
|
+
export declare class AppServer {
|
|
34
|
+
readonly proc: LineChannel;
|
|
35
|
+
private readonly options;
|
|
36
|
+
private nextId;
|
|
37
|
+
private readonly pending;
|
|
38
|
+
private closedWith;
|
|
39
|
+
/** Resolves with the reason once stdout ends (the child exited or closed it). */
|
|
40
|
+
readonly closed: Promise<Error>;
|
|
41
|
+
constructor(proc: LineChannel, options?: AppServerOptions);
|
|
42
|
+
private read;
|
|
43
|
+
private settle;
|
|
44
|
+
private answer;
|
|
45
|
+
/** Send a request and wait for its result. Rejects with `RpcError`, or when the child goes away. */
|
|
46
|
+
request<T = any>(method: string, params: unknown): Promise<T>;
|
|
47
|
+
notify(method: string, params?: unknown): void;
|
|
48
|
+
/** `initialize` with the experimental API (dynamic tools, `thread/inject_items`), then `initialized`. */
|
|
49
|
+
initialize(clientName?: string, version?: string): Promise<{
|
|
50
|
+
userAgent?: string;
|
|
51
|
+
codexHome?: string;
|
|
52
|
+
}>;
|
|
53
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/** A JSON-RPC error app-server answered with. */
|
|
2
|
+
export class RpcError extends Error {
|
|
3
|
+
method;
|
|
4
|
+
code;
|
|
5
|
+
data;
|
|
6
|
+
constructor(method, code, message, data) {
|
|
7
|
+
super(`codex app-server ${method}: ${message} (${code})`);
|
|
8
|
+
this.method = method;
|
|
9
|
+
this.code = code;
|
|
10
|
+
this.data = data;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
export class AppServer {
|
|
14
|
+
proc;
|
|
15
|
+
options;
|
|
16
|
+
nextId = 1;
|
|
17
|
+
pending = new Map();
|
|
18
|
+
closedWith;
|
|
19
|
+
/** Resolves with the reason once stdout ends (the child exited or closed it). */
|
|
20
|
+
closed;
|
|
21
|
+
constructor(proc, options = {}) {
|
|
22
|
+
this.proc = proc;
|
|
23
|
+
this.options = options;
|
|
24
|
+
this.closed = this.read();
|
|
25
|
+
}
|
|
26
|
+
async read() {
|
|
27
|
+
try {
|
|
28
|
+
for await (const line of this.proc.lines()) {
|
|
29
|
+
if (!line.trim())
|
|
30
|
+
continue;
|
|
31
|
+
let msg;
|
|
32
|
+
try {
|
|
33
|
+
msg = JSON.parse(line);
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
this.options.onNoise?.(line);
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (msg.id != null && msg.method == null)
|
|
40
|
+
this.settle(msg);
|
|
41
|
+
else if (msg.id != null)
|
|
42
|
+
void this.answer(msg);
|
|
43
|
+
else if (typeof msg.method === 'string')
|
|
44
|
+
this.options.onNotification?.(msg);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
catch { }
|
|
48
|
+
const exit = await Promise.race([this.proc.exited, new Promise((r) => setTimeout(r, 1000, undefined))]);
|
|
49
|
+
const how = exit ? (exit.signal ?? `code ${exit.code}`) : 'stdout closed';
|
|
50
|
+
const err = new Error(`codex app-server exited (${how}): ${this.proc.stderrTail().trim().slice(-800)}`);
|
|
51
|
+
this.closedWith = err;
|
|
52
|
+
for (const p of this.pending.values())
|
|
53
|
+
p.reject(err);
|
|
54
|
+
this.pending.clear();
|
|
55
|
+
return err;
|
|
56
|
+
}
|
|
57
|
+
settle(msg) {
|
|
58
|
+
const p = this.pending.get(msg.id);
|
|
59
|
+
if (!p)
|
|
60
|
+
return;
|
|
61
|
+
this.pending.delete(msg.id);
|
|
62
|
+
if (msg.error)
|
|
63
|
+
p.reject(new RpcError(p.method, msg.error.code, msg.error.message, msg.error.data));
|
|
64
|
+
else
|
|
65
|
+
p.resolve(msg.result);
|
|
66
|
+
}
|
|
67
|
+
async answer(req) {
|
|
68
|
+
try {
|
|
69
|
+
const handler = this.options.onRequest;
|
|
70
|
+
if (!handler)
|
|
71
|
+
throw Object.assign(new Error(`unhandled ${req.method}`), { code: -32601 });
|
|
72
|
+
const result = await handler(req);
|
|
73
|
+
this.proc.send({ id: req.id, result });
|
|
74
|
+
}
|
|
75
|
+
catch (err) {
|
|
76
|
+
const code = typeof err.code === 'number' ? err.code : -32000;
|
|
77
|
+
this.proc.send({ id: req.id, error: { code, message: err.message ?? String(err) } });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/** Send a request and wait for its result. Rejects with `RpcError`, or when the child goes away. */
|
|
81
|
+
request(method, params) {
|
|
82
|
+
if (this.closedWith)
|
|
83
|
+
return Promise.reject(this.closedWith);
|
|
84
|
+
const id = this.nextId++;
|
|
85
|
+
return new Promise((resolve, reject) => {
|
|
86
|
+
this.pending.set(id, { method, resolve, reject });
|
|
87
|
+
if (!this.proc.send({ id, method, params })) {
|
|
88
|
+
this.pending.delete(id);
|
|
89
|
+
reject(new Error(`codex app-server: stdin is closed (${method})`));
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
notify(method, params = {}) {
|
|
94
|
+
this.proc.send({ method, params });
|
|
95
|
+
}
|
|
96
|
+
/** `initialize` with the experimental API (dynamic tools, `thread/inject_items`), then `initialized`. */
|
|
97
|
+
async initialize(clientName = 'agentrun-codex', version = '0') {
|
|
98
|
+
const result = await this.request('initialize', {
|
|
99
|
+
clientInfo: { name: clientName, version, title: null },
|
|
100
|
+
capabilities: { experimentalApi: true },
|
|
101
|
+
});
|
|
102
|
+
this.notify('initialized', {});
|
|
103
|
+
return result;
|
|
104
|
+
}
|
|
105
|
+
}
|
package/dist/binary.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where this machine's `codex` binary is, for the stand-in VM's tests and the
|
|
3
|
+
* live tests on a laptop (`@parcha/agentrun-harness-codex's binary.ts`, never the package's
|
|
4
|
+
* index: in a session, Codex is the pinned build in the sandbox's base image,
|
|
5
|
+
* `CODEX_CLI`, and no Function looks a binary up). `@openai/codex` is a small
|
|
6
|
+
* launcher plus one optional package per platform (`@openai/codex-<platform>`,
|
|
7
|
+
* an npm alias of `@openai/codex@<version>-<platform>`) that carries the
|
|
8
|
+
* native binary at `vendor/<target>/bin/codex`.
|
|
9
|
+
*/
|
|
10
|
+
/** The Codex version this package is built and tested against. */
|
|
11
|
+
export declare const CODEX_VERSION = "0.164.0";
|
|
12
|
+
/** This platform's target and platform package, if Codex ships one. */
|
|
13
|
+
export declare function codexTarget(platform?: NodeJS.Platform, arch?: NodeJS.Architecture): {
|
|
14
|
+
target: string;
|
|
15
|
+
pkg: string;
|
|
16
|
+
} | undefined;
|
|
17
|
+
/**
|
|
18
|
+
* The binary to run, and its platform package's version when it came from one,
|
|
19
|
+
* or `undefined` if none is installed:
|
|
20
|
+
*
|
|
21
|
+
* 1. `CODEX_BIN`;
|
|
22
|
+
* 2. the platform package next to the `@openai/codex` this package depends on;
|
|
23
|
+
* 3. the same package by its pnpm store path, walking up from the working
|
|
24
|
+
* directory.
|
|
25
|
+
*/
|
|
26
|
+
export declare function findCodex(): {
|
|
27
|
+
path: string;
|
|
28
|
+
packageVersion?: string;
|
|
29
|
+
} | undefined;
|
|
30
|
+
/** The binary to run, or `undefined` if none is installed (see `findCodex`). */
|
|
31
|
+
export declare function codexBinary(): string | undefined;
|
package/dist/binary.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
|
|
2
|
+
// From github.com/vercel-labs/durable-harness, packages/harness-codex/src/binary.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
|
|
3
|
+
// Changed by Parcha, patches: 003-pinned-binary, 006-comments
|
|
4
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
5
|
+
import { createRequire } from 'node:module';
|
|
6
|
+
import { dirname, join } from 'node:path';
|
|
7
|
+
import { env } from 'node:process';
|
|
8
|
+
/**
|
|
9
|
+
* Where this machine's `codex` binary is, for the stand-in VM's tests and the
|
|
10
|
+
* live tests on a laptop (`@parcha/agentrun-harness-codex's binary.ts`, never the package's
|
|
11
|
+
* index: in a session, Codex is the pinned build in the sandbox's base image,
|
|
12
|
+
* `CODEX_CLI`, and no Function looks a binary up). `@openai/codex` is a small
|
|
13
|
+
* launcher plus one optional package per platform (`@openai/codex-<platform>`,
|
|
14
|
+
* an npm alias of `@openai/codex@<version>-<platform>`) that carries the
|
|
15
|
+
* native binary at `vendor/<target>/bin/codex`.
|
|
16
|
+
*/
|
|
17
|
+
/** The Codex version this package is built and tested against. */
|
|
18
|
+
export const CODEX_VERSION = '0.164.0';
|
|
19
|
+
const TARGETS = {
|
|
20
|
+
'linux-x64': { target: 'x86_64-unknown-linux-musl', pkg: 'linux-x64' },
|
|
21
|
+
'linux-arm64': { target: 'aarch64-unknown-linux-musl', pkg: 'linux-arm64' },
|
|
22
|
+
'darwin-x64': { target: 'x86_64-apple-darwin', pkg: 'darwin-x64' },
|
|
23
|
+
'darwin-arm64': { target: 'aarch64-apple-darwin', pkg: 'darwin-arm64' },
|
|
24
|
+
};
|
|
25
|
+
/** This platform's target and platform package, if Codex ships one. */
|
|
26
|
+
export function codexTarget(platform = process.platform, arch = process.arch) {
|
|
27
|
+
return TARGETS[`${platform}-${arch}`];
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The binary to run, and its platform package's version when it came from one,
|
|
31
|
+
* or `undefined` if none is installed:
|
|
32
|
+
*
|
|
33
|
+
* 1. `CODEX_BIN`;
|
|
34
|
+
* 2. the platform package next to the `@openai/codex` this package depends on;
|
|
35
|
+
* 3. the same package by its pnpm store path, walking up from the working
|
|
36
|
+
* directory.
|
|
37
|
+
*/
|
|
38
|
+
export function findCodex() {
|
|
39
|
+
if (env.CODEX_BIN)
|
|
40
|
+
return { path: env.CODEX_BIN };
|
|
41
|
+
const t = codexTarget();
|
|
42
|
+
if (!t)
|
|
43
|
+
return undefined;
|
|
44
|
+
const rel = join('vendor', t.target, 'bin', 'codex');
|
|
45
|
+
try {
|
|
46
|
+
const require = createRequire(import.meta.url);
|
|
47
|
+
const launcher = dirname(require.resolve('@openai/codex/package.json'));
|
|
48
|
+
const platformPkg = dirname(createRequire(join(launcher, 'package.json')).resolve(`@openai/codex-${t.pkg}/package.json`));
|
|
49
|
+
const bin = join(platformPkg, rel);
|
|
50
|
+
if (existsSync(bin))
|
|
51
|
+
return { path: bin, packageVersion: packageVersion(platformPkg) };
|
|
52
|
+
}
|
|
53
|
+
catch { }
|
|
54
|
+
const store = join('node_modules', '.pnpm', `@openai+codex@${CODEX_VERSION}-${t.pkg}`, 'node_modules', '@openai', 'codex', rel);
|
|
55
|
+
for (let d = process.cwd();; d = dirname(d)) {
|
|
56
|
+
const bin = join(d, store);
|
|
57
|
+
if (existsSync(bin))
|
|
58
|
+
return { path: bin, packageVersion: packageVersion(join(d, store, '..', '..', '..', '..')) };
|
|
59
|
+
if (d === dirname(d))
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/** The binary to run, or `undefined` if none is installed (see `findCodex`). */
|
|
64
|
+
export function codexBinary() {
|
|
65
|
+
return findCodex()?.path;
|
|
66
|
+
}
|
|
67
|
+
function packageVersion(dir) {
|
|
68
|
+
try {
|
|
69
|
+
return JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).version;
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import type { DriveContext } from "./host/kernel.js";
|
|
2
|
+
import type { SessionMachine } from "./host/process.js";
|
|
3
|
+
import { type RolloutSummary } from "./rollout.js";
|
|
4
|
+
/** 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. */
|
|
5
|
+
export declare const NESTED_STREAM = "codex.nested";
|
|
6
|
+
/** The stream that records the interrupted turns whose recovery note was injected: `{ since }`, once per interrupted turn. */
|
|
7
|
+
export declare const RECOVERY_NOTE_STREAM = "codex.recovery-note";
|
|
8
|
+
interface Journal {
|
|
9
|
+
append(stream: string, record: unknown): void;
|
|
10
|
+
flush(): Promise<void>;
|
|
11
|
+
read<T>(stream: string): Promise<{
|
|
12
|
+
data: T;
|
|
13
|
+
}[]>;
|
|
14
|
+
}
|
|
15
|
+
export interface CodeModeDeps {
|
|
16
|
+
ctx: DriveContext;
|
|
17
|
+
machine: SessionMachine;
|
|
18
|
+
journal: Journal;
|
|
19
|
+
/** The calls whose line is in the log: the harness's barrier looks here, so a call admitted here passes it. */
|
|
20
|
+
logged: Set<string>;
|
|
21
|
+
/** Drain the rollout's tail into the log. */
|
|
22
|
+
synced(): Promise<void>;
|
|
23
|
+
bridge: {
|
|
24
|
+
get(name: string): {
|
|
25
|
+
name: string;
|
|
26
|
+
replay: string;
|
|
27
|
+
} | undefined;
|
|
28
|
+
};
|
|
29
|
+
log(message: string, fields?: Record<string, unknown>): void;
|
|
30
|
+
/** The rollout lines restored from the log. */
|
|
31
|
+
lines: readonly string[];
|
|
32
|
+
rpc(): {
|
|
33
|
+
request(method: string, params: Record<string, unknown>): Promise<unknown>;
|
|
34
|
+
};
|
|
35
|
+
guard<T>(promise: Promise<T>): Promise<T>;
|
|
36
|
+
threadId(): string;
|
|
37
|
+
/** How often the barrier looks again for a script's line, and what a declined call is told. */
|
|
38
|
+
tries: number;
|
|
39
|
+
declined: string;
|
|
40
|
+
}
|
|
41
|
+
interface Dangling {
|
|
42
|
+
callId: string;
|
|
43
|
+
name: string;
|
|
44
|
+
/** `function_call` or `custom_tool_call` (code mode's `exec`, Codex's own `apply_patch`). */
|
|
45
|
+
type: string;
|
|
46
|
+
arguments?: string;
|
|
47
|
+
}
|
|
48
|
+
/** 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
|
|
49
|
+
* wrong kind), a custom tool call output for a custom tool call such as `apply_patch`, a function call output for any other. */
|
|
50
|
+
export declare function withOutputKind<T extends {
|
|
51
|
+
call_id?: unknown;
|
|
52
|
+
output?: unknown;
|
|
53
|
+
}>(item: T, call: Dangling): T & {
|
|
54
|
+
type: string;
|
|
55
|
+
};
|
|
56
|
+
/** 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. */
|
|
57
|
+
export declare const waitStoppedText: (cell: string) => string;
|
|
58
|
+
export declare function codeMode(deps: CodeModeDeps): {
|
|
59
|
+
/** The app-server's request handler, with a code-mode host tool call handled before the harness's own. */
|
|
60
|
+
request<R extends {
|
|
61
|
+
method: string;
|
|
62
|
+
params?: Record<string, unknown>;
|
|
63
|
+
}>(next: (req: R) => Promise<unknown>): (req: R) => Promise<unknown>;
|
|
64
|
+
/** 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`';
|
|
65
|
+
* 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
|
|
66
|
+
* 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
|
|
67
|
+
* 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
|
|
68
|
+
* both repairs (with a recovery note and without) inject what this leaves. */
|
|
69
|
+
recoverItems(items: Record<string, unknown>[], dangling: readonly Dangling[], lines: readonly string[], since: number): Promise<void>;
|
|
70
|
+
/** 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
|
|
71
|
+
* them (one interrupted mid-call, or settled instead of resumed) left them dangling, and the provider refuses a history with a call unanswered.
|
|
72
|
+
* Nothing is armed here: a new turn that calls a `never` call the ended turn completed runs it. */
|
|
73
|
+
repairUnnoted(lines: readonly string[]): Promise<void>;
|
|
74
|
+
/** 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
|
|
75
|
+
* the model as a developer message, injected once for this interrupted turn (every turn opens with `thread/resume`, so injecting on each
|
|
76
|
+
* 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. */
|
|
77
|
+
resumeTurn(note: {
|
|
78
|
+
turn: {
|
|
79
|
+
since: number;
|
|
80
|
+
};
|
|
81
|
+
pending: {
|
|
82
|
+
text?: string;
|
|
83
|
+
}[];
|
|
84
|
+
}, owed: {
|
|
85
|
+
text?: string;
|
|
86
|
+
}[]): Promise<string>;
|
|
87
|
+
/** A turn ended: the calls answered from the log were for it alone. */
|
|
88
|
+
turnEnded(): void;
|
|
89
|
+
};
|
|
90
|
+
export type { RolloutSummary };
|