@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.
- package/CHANGELOG.md +349 -0
- package/LICENSE +202 -0
- package/NOTICE +6 -0
- package/README.md +80 -2
- package/dist/adapter.d.ts +93 -0
- package/dist/adapter.js +375 -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/catalog.d.ts +35 -0
- package/dist/catalog.js +104 -0
- package/dist/code-mode.d.ts +171 -0
- package/dist/code-mode.js +514 -0
- package/dist/config.d.ts +84 -0
- package/dist/config.js +214 -0
- package/dist/facts.d.ts +2 -0
- package/dist/facts.js +40 -0
- package/dist/harness.d.ts +210 -0
- package/dist/harness.js +1112 -0
- package/dist/host/kernel.d.ts +20 -0
- package/dist/host/kernel.js +3 -0
- package/dist/host/machine.d.ts +81 -0
- package/dist/host/machine.js +355 -0
- package/dist/host/policy.d.ts +113 -0
- package/dist/host/policy.js +683 -0
- package/dist/host/process.d.ts +151 -0
- package/dist/host/process.js +50 -0
- package/dist/host/sandbox.d.ts +36 -0
- package/dist/host/sandbox.js +35 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +10 -0
- package/dist/rollout.d.ts +96 -0
- package/dist/rollout.js +170 -0
- package/dist/schema.d.ts +14 -0
- package/dist/schema.js +178 -0
- package/dist/scripts.d.ts +218 -0
- package/dist/scripts.js +409 -0
- package/dist/tool-images.d.ts +7 -0
- package/dist/tool-images.js +18 -0
- package/dist/transcript.d.ts +20 -0
- package/dist/transcript.js +73 -0
- package/dist/verify.d.ts +62 -0
- package/dist/verify.js +155 -0
- package/dist/versions.d.ts +43 -0
- package/dist/versions.js +72 -0
- package/package.json +72 -4
- package/vendor/durable-harness/UPSTREAM.json +39 -0
package/dist/adapter.js
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
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, randomBytes, randomUUID } from "node:crypto";
|
|
13
|
+
import { join } from "node:path";
|
|
14
|
+
import { HOST_RESULT_MAX_CHARS, READ_SKILL_FILE, hostedTool, 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 { bridgeTool, NativeJournal, recoveryNote, settleTurn, transcriptOf, windowBudget } from "@parcha/agentrun-kernel/process";
|
|
18
|
+
import { codexSchemaProblems, describedDescription } from "./schema.js";
|
|
19
|
+
import { markParked } from "./scripts.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, startModelProxy } from "@parcha/agentrun-kernel/host";
|
|
26
|
+
import { codexPolicy, withWebSearches } from "./host/policy.js";
|
|
27
|
+
import { toolImageProblems } from "./tool-images.js";
|
|
28
|
+
/** A name app-server accepts for a dynamic tool. */
|
|
29
|
+
const TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;
|
|
30
|
+
/**
|
|
31
|
+
* The name Codex is given a host tool by. App-server reserves `mcp__` names for its own MCP client's tools and refuses a
|
|
32
|
+
* dynamic tool so named at the thread's start (`dynamic tool name is reserved`, 0.164.0, #1586), so a run's MCP tool
|
|
33
|
+
* (`mcp__<server>__<tool>`), a host tool like any other, is offered as `mcp_<server>__<tool>`. Every other name is
|
|
34
|
+
* as given. Inside the session only: the host's gate and the session's events name the call by the host's name.
|
|
35
|
+
*/
|
|
36
|
+
export const codexToolName = (name) => (name.startsWith("mcp__") ? `mcp_${name.slice("mcp__".length)}` : name);
|
|
37
|
+
/**
|
|
38
|
+
* Codex's `tool_output_token_limit`: the host's result bound (HOST_RESULT_MAX_CHARS), as Codex counts it. Codex keeps a
|
|
39
|
+
* tool's output in the model's history within its truncation policy (10,000 tokens for each model its catalog holds, less
|
|
40
|
+
* 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
|
|
41
|
+
* 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
|
|
42
|
+
* three quarters of a token a character: not a quarter, which holds for ASCII alone.
|
|
43
|
+
*/
|
|
44
|
+
export const CODEX_TOOL_OUTPUT_TOKENS = Math.ceil((HOST_RESULT_MAX_CHARS * 3) / 4);
|
|
45
|
+
/** How long Codex waits on a silent stream from a model on the host's own machine (an Ollama model the route
|
|
46
|
+
* translates), which says nothing while it loads or reads a long prompt: 30 minutes, as claude-agent's CLI waits
|
|
47
|
+
* (its LOCAL_STREAM_IDLE_MS). Any other route keeps Codex's own five minutes. */
|
|
48
|
+
export const LOCAL_STREAM_IDLE_MS = 30 * 60_000;
|
|
49
|
+
/** The adapter's event for a harness live event, if it has one: a tool's by the host's name for it (`hostName`). */
|
|
50
|
+
function adapterEvent(event, hostName) {
|
|
51
|
+
const e = event;
|
|
52
|
+
if (e?.type === "text" && typeof e.delta === "string")
|
|
53
|
+
return { type: "text", delta: e.delta };
|
|
54
|
+
if (e?.type === "tool_start" && typeof e.name === "string")
|
|
55
|
+
return { type: "tool_start", callId: String(e.callId ?? ""), name: hostName(e.name), args: e.args };
|
|
56
|
+
if (e?.type === "tool_end" && typeof e.name === "string")
|
|
57
|
+
return { type: "tool_end", callId: String(e.callId ?? ""), name: hostName(e.name), isError: e.isError === true, ...(e.truncated === true ? { truncated: true } : {}) };
|
|
58
|
+
return undefined;
|
|
59
|
+
}
|
|
60
|
+
/** A turn entry's `capCut` when it is one (two money figures), as `{ capCut }`. */
|
|
61
|
+
const capCutOf = (value) => {
|
|
62
|
+
if (typeof value !== "object" || value === null)
|
|
63
|
+
return undefined;
|
|
64
|
+
const { capUsd, raiseToUsd } = value;
|
|
65
|
+
return typeof capUsd === "number" && Number.isFinite(capUsd) && typeof raiseToUsd === "number" && Number.isFinite(raiseToUsd) ? { capCut: { capUsd, raiseToUsd } } : undefined;
|
|
66
|
+
};
|
|
67
|
+
const turnsIn = (drive) => transcriptOf(drive.state()).filter((r) => r.data?.type === "turn");
|
|
68
|
+
/** Where Codex finds a user's skills: `$CODEX_HOME/skills`. It lists those to the model in a turn with no environment
|
|
69
|
+
* (this adapter's, with the built-ins off), where it lists none of a working directory's `.agents/skills`. */
|
|
70
|
+
const SKILLS_DIR = "skills";
|
|
71
|
+
/** The skills as the files the session's CODEX_HOME holds (`skills/<name>/<path>`): the machine's seed. */
|
|
72
|
+
function skillsSeed(skills) {
|
|
73
|
+
return { dir: "codex-home", files: Object.fromEntries(skills.flatMap((skill) => Object.entries(skill.files).map(([path, text]) => [`${SKILLS_DIR}/${skill.name}/${path}`, text]))) };
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The mirrored rollout the next drive resumes Codex from, by the harness's own rule (harness.ts, `resume`: the last
|
|
77
|
+
* thread, its first line `session_meta`, its path the one the harness derives); none when it would start a new thread.
|
|
78
|
+
* The settle reads only this, so it and the next Codex agree on what Codex has. The copied harness keeps its own copy
|
|
79
|
+
* of the rule: its own patch budget has no room for a call here.
|
|
80
|
+
*/
|
|
81
|
+
export async function resumedRollout(journal) {
|
|
82
|
+
const thread = journal.records(THREAD_STREAM).at(-1)?.data;
|
|
83
|
+
const restored = thread ? (await journal.read(rolloutStream(thread.threadId))).map((r) => r.data) : [];
|
|
84
|
+
return thread && isSessionMeta(restored[0]) && isRolloutPath(thread.path, thread.threadId) ? restored : [];
|
|
85
|
+
}
|
|
86
|
+
export function codexAdapter(options) {
|
|
87
|
+
if (options.webSearch !== undefined && options.webSearch !== "live")
|
|
88
|
+
throw new TypeError("agentrun-harness-codex: webSearch is \"live\" or absent");
|
|
89
|
+
// The skills first: a skill Codex would skip or list under another name is the host's to fix, binary or not.
|
|
90
|
+
const skills = options.skills ?? [];
|
|
91
|
+
const skillsWrong = skillProblems(skills);
|
|
92
|
+
if (skillsWrong.length)
|
|
93
|
+
throw new Error(`agentrun-harness-codex: ${skillsWrong.join("; ")}`);
|
|
94
|
+
const seed = skills.length ? skillsSeed(skills) : undefined;
|
|
95
|
+
// The binary is checked once, here, against the pins: a mismatch or a missing binary is the host's to report, before
|
|
96
|
+
// any run starts (CodexPinMismatch, CodexNotInstalled). A test's stand-in runs no Codex.
|
|
97
|
+
const checked = options.standIn ? undefined : verifyCodex(options.binary).path;
|
|
98
|
+
const modelFor = (spec) => {
|
|
99
|
+
if (typeof options.model === "string")
|
|
100
|
+
return options.model;
|
|
101
|
+
return (spec.tier && spec.tier !== "default" ? options.model[spec.tier] : undefined) ?? options.model.default;
|
|
102
|
+
};
|
|
103
|
+
return {
|
|
104
|
+
id: "codex",
|
|
105
|
+
check(spec) {
|
|
106
|
+
const problems = [];
|
|
107
|
+
if (spec.context === "fork")
|
|
108
|
+
problems.push("Codex sessions cannot fork another session's transcript; declare context: \"fresh\"");
|
|
109
|
+
// Each tool by the name Codex is given it (codexToolName): two that would reach Codex by one name are refused.
|
|
110
|
+
const seen = new Map();
|
|
111
|
+
for (const tool of spec.tools) {
|
|
112
|
+
const given = codexToolName(tool.name);
|
|
113
|
+
if (!TOOL_NAME.test(tool.name))
|
|
114
|
+
problems.push(`the tool name ${JSON.stringify(tool.name.slice(0, 80))} is not one Codex accepts (letters, digits, _ and -, at most 64)`);
|
|
115
|
+
const twin = seen.get(given);
|
|
116
|
+
if (twin === tool.name)
|
|
117
|
+
problems.push(`the tool ${tool.name} is given twice`);
|
|
118
|
+
else if (twin !== undefined)
|
|
119
|
+
problems.push(`the tools ${twin} and ${tool.name} both reach Codex as ${given}`);
|
|
120
|
+
if (skills.length && given === READ_SKILL_FILE)
|
|
121
|
+
problems.push(`the tool name ${READ_SKILL_FILE} is the adapter's own when it has skills`);
|
|
122
|
+
if (twin === undefined)
|
|
123
|
+
seen.set(given, tool.name);
|
|
124
|
+
// What no harness takes (an object root, valid 2020-12, no remote $ref), then what Codex would drop or retype in
|
|
125
|
+
// the tool's schema: refused here, by name, not found out mid-turn. A place the first already refused is not
|
|
126
|
+
// refused again by the second.
|
|
127
|
+
// Nothing in it may throw: a tool whose schema cannot be checked is a problem at "/", naming the tool.
|
|
128
|
+
try {
|
|
129
|
+
const shared = toolSchemaProblems(tool.name, tool.inputSchema);
|
|
130
|
+
// A schema the shared check refuses as a whole (its root, or that it is not JSON: a cycle only code can build)
|
|
131
|
+
// is not walked again: Codex's rules would never reach the end of a cycle.
|
|
132
|
+
const wholly = shared.some((problem) => problem.startsWith(`${tool.name}: /:`));
|
|
133
|
+
const refusedAt = new Set(shared.map((problem) => /^[^:]*: (\S+):/.exec(problem)?.[1]));
|
|
134
|
+
problems.push(...shared, ...(wholly ? [] : codexSchemaProblems(tool.name, tool.inputSchema).filter((problem) => !refusedAt.has(/^[^:]*: (\S+):/.exec(problem)?.[1]))));
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
problems.push(`${tool.name}: /: the tool's schema could not be checked (${String(error?.message ?? error).slice(0, 120)})`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return problems;
|
|
141
|
+
},
|
|
142
|
+
async open(spec, io) {
|
|
143
|
+
const problems = this.check(spec);
|
|
144
|
+
if (problems.length)
|
|
145
|
+
throw new Error(`agentrun-harness-codex: ${problems.join("; ")}`);
|
|
146
|
+
const dir = io.dir ?? (options.sessionsDir ? join(options.sessionsDir, createHash("sha256").update(spec.key).digest("hex").slice(0, 32)) : undefined);
|
|
147
|
+
if (!dir)
|
|
148
|
+
throw new Error("agentrun-harness-codex: a session needs a private directory: the host lends one (io.dir), or pass sessionsDir");
|
|
149
|
+
// With skills the model also reads their files (read_skill_file), from the session's own copy of them.
|
|
150
|
+
const tools = skills.length ? [...spec.tools, hostedTool(io, readSkillFileTool(join(sessionDir(dir, "codex-home"), SKILLS_DIR), skills.map((skill) => ({ name: skill.name, files: Object.keys(skill.files) }))))] : spec.tools;
|
|
151
|
+
// The host's name for each tool as Codex calls it: the gate and the session's events name a call by it.
|
|
152
|
+
const hostNames = new Map(tools.map((t) => [codexToolName(t.name), t.name]));
|
|
153
|
+
const hostName = (name) => hostNames.get(name) ?? name;
|
|
154
|
+
const effort = spec.effort ?? spec.thinking;
|
|
155
|
+
const window = spec.contextWindow ?? options.contextWindow;
|
|
156
|
+
// Each tool result held to the model's share of the window, and a turn's results to what it has left, which the
|
|
157
|
+
// session's model proxy reads from each answer (its turn).
|
|
158
|
+
const budget = windowBudget(window, spec.system);
|
|
159
|
+
// The live search runs inside a model request, where no call reaches the gate: it is offered only while the host's
|
|
160
|
+
// web_search setting allows it, read before each request (a deny or ask set mid-run drops it from the next one).
|
|
161
|
+
const searchAllowed = options.webSearch && io.permission ? async () => (await io.permission("web_search")) === "allow" : undefined;
|
|
162
|
+
const harnessOptions = {
|
|
163
|
+
// The kernel's tool for each host tool (bridgeTool): the same schema and replay policy, a host's error result the
|
|
164
|
+
// call's failure. The call runs as a kernel effect, whose intent is durable before it is entered, so a crash inside
|
|
165
|
+
// a `never` tool is always reported, never repeated (the copied harness's wait for Codex's own `function_call` line
|
|
166
|
+
// before it runs such a tool is a second guard, not the one that protects it).
|
|
167
|
+
tools: tools.map((tool) => bridgeTool(tool, {
|
|
168
|
+
name: codexToolName(tool.name),
|
|
169
|
+
// Codex strips some keywords from the schema its model is given: they are said in plain words in the
|
|
170
|
+
// description (the schema itself is the host's, and every call is checked against it).
|
|
171
|
+
description: describedDescription(tool.description, tool.inputSchema),
|
|
172
|
+
// A tool that nests calls (tools_call) names them by the host's names: the bridge holds them by Codex's.
|
|
173
|
+
nestedName: codexToolName,
|
|
174
|
+
// A call the host parked for a person's approval did not run: recorded so before its answer, the waiting text.
|
|
175
|
+
parked: markParked,
|
|
176
|
+
imageProblems: (images) => toolImageProblems(tool.name, images),
|
|
177
|
+
})),
|
|
178
|
+
// The host's gate, asked about each host-tool call before its intent is written.
|
|
179
|
+
...(io.gate ? { gate: (call) => io.gate({ ...call, tool: hostName(call.tool) }) } : {}),
|
|
180
|
+
// The host's record of a code-mode `exec`: its row, and its script's calls under it.
|
|
181
|
+
...(io.ownCalls ? { ownCalls: io.ownCalls } : {}),
|
|
182
|
+
builtins: false,
|
|
183
|
+
// Codex's bundled skills (imagegen, skill-installer, ...), which it writes under `$CODEX_HOME/skills/.system` at every
|
|
184
|
+
// start, are off in every session, skills or not: the model is shown the host's skills and no others.
|
|
185
|
+
// Codex's `<permissions instructions>` message is off too. It describes Codex's own sandbox ("`sandbox_mode` is
|
|
186
|
+
// `read-only`: The sandbox only permits reading files"), which binds only Codex's built-in tools, and those are off
|
|
187
|
+
// here. The host's tools write, and a model that believed the message refused to write at all (autoqa F13).
|
|
188
|
+
// A host tool's result within the host's bound reaches the model whole (CODEX_TOOL_OUTPUT_TOKENS).
|
|
189
|
+
config: { skills: { bundled: { enabled: false } }, include_permissions_instructions: false, tool_output_token_limit: CODEX_TOOL_OUTPUT_TOKENS },
|
|
190
|
+
model: modelFor(spec),
|
|
191
|
+
...(spec.system.length ? { instructions: spec.system.join("\n\n") } : {}),
|
|
192
|
+
...(effort ? { effort } : {}),
|
|
193
|
+
credential: async () => options.provider.credential(),
|
|
194
|
+
gatewayUrl: options.provider.origin,
|
|
195
|
+
// The window the host knows (the session's, from its catalog; else this adapter's). Only with neither is Codex told
|
|
196
|
+
// 272,000, a guess at a large OpenAI model's, and then no tool result is held to it: the host's bound alone.
|
|
197
|
+
contextWindow: window ?? 272_000,
|
|
198
|
+
...(options.streamIdleMs !== undefined ? { streamIdleMs: options.streamIdleMs } : {}),
|
|
199
|
+
...budget,
|
|
200
|
+
...(options.log ? { log: options.log } : {}),
|
|
201
|
+
...(options.standIn ? { test: { command: options.standIn.command, args: options.standIn.args ?? [] } } : {}),
|
|
202
|
+
machine: {
|
|
203
|
+
...(options.standIn?.env ? { env: options.standIn.env } : {}),
|
|
204
|
+
acquire: localMachine({
|
|
205
|
+
dir,
|
|
206
|
+
// The host's workspace, when it names one: Codex works where the host's file tools write (io.cwd).
|
|
207
|
+
...(io.cwd ? { cwd: io.cwd } : {}),
|
|
208
|
+
...(options.confine ? { confine: options.confine } : {}),
|
|
209
|
+
...(seed ? { seed } : {}),
|
|
210
|
+
// The built-ins are off: Codex's own apply_patch, with no environment to run in, is offered to no model
|
|
211
|
+
// (catalog.ts). A stand-in runs no Codex, so it has no catalog to read.
|
|
212
|
+
...(checked !== undefined ? { catalog: { command: checked, ...(options.log ? { log: options.log } : {}) } } : {}),
|
|
213
|
+
...(options.webSearch ? { webSearch: options.webSearch, ...(searchAllowed ? { searchAllowed } : {}) } : {}),
|
|
214
|
+
proxy: {
|
|
215
|
+
hooks: io.models,
|
|
216
|
+
...(budget.resultBudget?.turn ? { turn: budget.resultBudget.turn } : {}),
|
|
217
|
+
tools: tools.map((t) => codexToolName(t.name)),
|
|
218
|
+
...(options.log ? { log: options.log } : {}),
|
|
219
|
+
...(options.price ? { price: options.price } : {}),
|
|
220
|
+
...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}),
|
|
221
|
+
...(options.provider.plan ? { plan: true } : {}),
|
|
222
|
+
...(options.provider.refused ? { credentialRefused: options.provider.refused } : {}),
|
|
223
|
+
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
224
|
+
// The proxy waits on a silent model as long as Codex does on one (a model on the host's own machine).
|
|
225
|
+
...(options.streamIdleMs !== undefined ? { stallMs: options.streamIdleMs } : {}),
|
|
226
|
+
},
|
|
227
|
+
}),
|
|
228
|
+
},
|
|
229
|
+
};
|
|
230
|
+
const harness = checked === undefined ? codexHarness(harnessOptions) : withCheckedBinary(checked, () => codexHarness(harnessOptions));
|
|
231
|
+
const live = (event) => {
|
|
232
|
+
const mapped = adapterEvent(event, hostName);
|
|
233
|
+
if (mapped)
|
|
234
|
+
io.onEvent(mapped);
|
|
235
|
+
};
|
|
236
|
+
// Every drive of this session writes through one serialized writer, so a drive opened after an interrupt reads only
|
|
237
|
+
// once the halted drive's last writes are in.
|
|
238
|
+
const writer = serialWriter(io.writer);
|
|
239
|
+
const open = () => openDrive({ writer, signal: io.signal, live });
|
|
240
|
+
let drive = await open();
|
|
241
|
+
const initial = drive.state();
|
|
242
|
+
// A turn is open while the session holds input no turn placed, or a turn with no end (its recovery note).
|
|
243
|
+
const holdsTurn = (folded) => Boolean(recoveryNote(folded)) || pendingSubmissions(folded).length > 0;
|
|
244
|
+
let state = holdsTurn(initial)
|
|
245
|
+
? "open_turn"
|
|
246
|
+
: initial.submissions.length === 0 && turnsIn(drive).length === 0 ? "new" : "idle";
|
|
247
|
+
let running;
|
|
248
|
+
let closed = false;
|
|
249
|
+
const run = () => {
|
|
250
|
+
const before = turnsIn(drive).length;
|
|
251
|
+
const current = drive;
|
|
252
|
+
state = "idle";
|
|
253
|
+
running = (async () => {
|
|
254
|
+
let outcome;
|
|
255
|
+
// A turn whose answer the model cut at its output limit says so on its turn_end: stopReason "length", with the cut
|
|
256
|
+
// answer's output tokens when the provider said them, and the cap's figures when the limit was the cap's.
|
|
257
|
+
let stop = {};
|
|
258
|
+
try {
|
|
259
|
+
await harness.drive(current);
|
|
260
|
+
const ended = turnsIn(current).slice(before).at(-1)?.data;
|
|
261
|
+
if (ended?.stopReason === "length")
|
|
262
|
+
stop = { stopReason: "length", ...(typeof ended.outputTokens === "number" ? { outputTokens: ended.outputTokens } : {}), ...(capCutOf(ended.capCut) ?? {}) };
|
|
263
|
+
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" };
|
|
264
|
+
}
|
|
265
|
+
catch (error) {
|
|
266
|
+
// Stopped by the session or its host: interrupted. Halted by anything else: failed, naming why.
|
|
267
|
+
outcome = current.signal.aborted
|
|
268
|
+
? abortedOutcome(current.signal, io.signal)
|
|
269
|
+
: { status: "failed", error: String(error?.message ?? error).slice(0, 500) };
|
|
270
|
+
// A stop that landed before this turn ran (while send() was still recording its prompt) found no turn to stop,
|
|
271
|
+
// and reads the session as it was: the turn is open now, its prompt pending, so it reads open_turn.
|
|
272
|
+
if (current.signal.aborted)
|
|
273
|
+
state = holdsTurn(current.state()) ? "open_turn" : "idle";
|
|
274
|
+
}
|
|
275
|
+
io.onEvent({ type: "turn_end", status: outcome.status, ...stop });
|
|
276
|
+
return outcome;
|
|
277
|
+
})();
|
|
278
|
+
return running;
|
|
279
|
+
};
|
|
280
|
+
// A drive that was halted (an interrupt) holds the session no more: the next turn opens a fresh one, on the same
|
|
281
|
+
// writer (the adapter never opens the session itself).
|
|
282
|
+
const ready = async () => {
|
|
283
|
+
if (closed)
|
|
284
|
+
throw new Error("agentrun-harness-codex: the session is closed");
|
|
285
|
+
if (running)
|
|
286
|
+
await running;
|
|
287
|
+
if (drive.signal.aborted && !io.signal.aborted)
|
|
288
|
+
drive = await open();
|
|
289
|
+
};
|
|
290
|
+
// The session's host port (AdapterSession.port): the host's own requests beside Codex's (a learned workflow's node)
|
|
291
|
+
// on the session's route, built from the drive proxy's own pieces (the same policy, origin, credential, price and the
|
|
292
|
+
// session's booking, io.models), but on a listener the session holds: a drive's machine closes its proxy when the
|
|
293
|
+
// drive ends (a park ends the turn; a restart opens none), and an approved call runs before any turn. It serves side
|
|
294
|
+
// keys only: Codex never holds its key, and the policy's exec watch (announce) never sees these requests. Its policy
|
|
295
|
+
// object is its own, as a side call's should be. Closed with the session, or when the host lets the session go.
|
|
296
|
+
// Started once the session's drive is open, the last step that can fail: an open that fails leaves no listener.
|
|
297
|
+
const search = options.webSearch === "live";
|
|
298
|
+
const hostPort = await startModelProxy({
|
|
299
|
+
policy: codexPolicy({ model: modelFor(spec), tools: [], ...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}), ...(options.provider.plan ? { plan: true } : {}), ...(search ? { webSearch: "live", ...(searchAllowed ? { searchAllowed } : {}) } : {}) }),
|
|
300
|
+
hooks: io.models,
|
|
301
|
+
model: modelFor(spec),
|
|
302
|
+
origin: options.provider.origin,
|
|
303
|
+
credential: async () => (await options.provider.credential()) ?? "",
|
|
304
|
+
...(options.provider.refused ? { credentialRefused: options.provider.refused } : {}),
|
|
305
|
+
...(options.price ? { price: search ? withWebSearches(options.price) : options.price } : {}),
|
|
306
|
+
...(options.log ? { log: options.log } : {}),
|
|
307
|
+
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
308
|
+
}, randomBytes(32).toString("base64url"));
|
|
309
|
+
let hostClosed = false;
|
|
310
|
+
const closeHost = async () => {
|
|
311
|
+
if (hostClosed)
|
|
312
|
+
return;
|
|
313
|
+
hostClosed = true;
|
|
314
|
+
await hostPort.close().catch(() => { });
|
|
315
|
+
};
|
|
316
|
+
io.signal.addEventListener("abort", () => void closeHost(), { once: true });
|
|
317
|
+
if (io.signal.aborted)
|
|
318
|
+
await closeHost();
|
|
319
|
+
return {
|
|
320
|
+
get state() { return state; },
|
|
321
|
+
async send(text) {
|
|
322
|
+
await ready();
|
|
323
|
+
await drive.submit({ id: randomUUID(), kind: "prompt", text });
|
|
324
|
+
void run();
|
|
325
|
+
},
|
|
326
|
+
async recover() {
|
|
327
|
+
if (state !== "open_turn")
|
|
328
|
+
throw new Error("agentrun-harness-codex: there is no turn to recover");
|
|
329
|
+
await ready();
|
|
330
|
+
void run();
|
|
331
|
+
},
|
|
332
|
+
async settleOpenTurn(options = {}) {
|
|
333
|
+
if (state !== "open_turn")
|
|
334
|
+
throw new Error("agentrun-harness-codex: there is no turn to settle");
|
|
335
|
+
await ready();
|
|
336
|
+
// The turn's end in the session's own transcript, as a turn that ends writes it: the next open finds no open turn,
|
|
337
|
+
// and the next turn carries no recovery of this one. Nothing is sent. A prompt the turn placed that Codex never
|
|
338
|
+
// recorded (the stop came before its rollout held it: Codex answers turn/start first) is carried into the next
|
|
339
|
+
// message, as an unplaced one is; a follow-up's own is not. The record is the rollout as the session keeps it (its
|
|
340
|
+
// mirror, which a stopped drive adds nothing to), the rollout the next Codex is resumed from: a prompt it lacks the
|
|
341
|
+
// next turn's model never saw, so carrying it never sends it twice.
|
|
342
|
+
const folded = drive.state();
|
|
343
|
+
const rollout = await resumedRollout(new NativeJournal(drive));
|
|
344
|
+
const unsent = owedSubmissions(folded, recoveryNote(folded)?.turn.placed ?? [], summarizeRollout(rollout).clientIds).map((s) => s.id);
|
|
345
|
+
await settleTurn(drive, { unsent, ...(options.opening === undefined ? {} : { host: options.opening }) });
|
|
346
|
+
state = "idle";
|
|
347
|
+
},
|
|
348
|
+
async turnEnd() {
|
|
349
|
+
if (!running)
|
|
350
|
+
throw new Error("agentrun-harness-codex: no turn is in flight");
|
|
351
|
+
return running;
|
|
352
|
+
},
|
|
353
|
+
async interrupt() {
|
|
354
|
+
drive.halt?.(new SessionHalt("interrupted"));
|
|
355
|
+
await running?.catch(() => { });
|
|
356
|
+
// The turn it stopped is still open in the session (an interrupt writes no end, and a prompt it stopped before
|
|
357
|
+
// the harness placed it is still pending): open_turn, so a host that is done with it settles it here.
|
|
358
|
+
if (holdsTurn(drive.state()))
|
|
359
|
+
state = "open_turn";
|
|
360
|
+
},
|
|
361
|
+
async close() {
|
|
362
|
+
if (closed)
|
|
363
|
+
return;
|
|
364
|
+
closed = true;
|
|
365
|
+
drive.halt?.(new SessionHalt("closed"));
|
|
366
|
+
await running?.catch(() => { });
|
|
367
|
+
await closeHost();
|
|
368
|
+
},
|
|
369
|
+
// The session's one model route, for the host's own request beside Codex's: the session's host port, which never
|
|
370
|
+
// restarts once closed.
|
|
371
|
+
port: (label) => (closed || hostClosed ? undefined : { url: hostPort.url, key: hostPort.sideKey(label), model: modelFor(spec), api: "openai-responses" }),
|
|
372
|
+
};
|
|
373
|
+
},
|
|
374
|
+
};
|
|
375
|
+
}
|
|
@@ -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, and AgentRun's own since the port from upstream froze on 2026-11-07.
|
|
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
|
+
}
|