@parcha/agentrun-harness-codex 0.0.0-bootstrap.0 → 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 +81 -0
- 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 +74 -1
- package/vendor/durable-harness/UPSTREAM.json +39 -0
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { DriveContext as KernelDriveContext } from "@parcha/agentrun-kernel/kernel";
|
|
2
|
+
export type { EffectRecord, HostTool, ReplayPolicy, SessionState, Submission } from "@parcha/agentrun-kernel/kernel";
|
|
3
|
+
export { Unavailable } from "@parcha/agentrun-kernel/kernel";
|
|
4
|
+
/** A drive context; `docs` is a sandbox's documents reader, which a local session has none of. */
|
|
5
|
+
export type DriveContext = KernelDriveContext & {
|
|
6
|
+
readonly docs?: {
|
|
7
|
+
read(doc: unknown): {
|
|
8
|
+
value: Record<string, unknown>;
|
|
9
|
+
};
|
|
10
|
+
};
|
|
11
|
+
};
|
|
12
|
+
/** The name of the step that records a turn ending unavailable. */
|
|
13
|
+
export declare const UNAVAILABLE_STEP = "unavailable";
|
|
14
|
+
/** A harness: one drive runs its pending input to the end, then returns. */
|
|
15
|
+
export interface Harness {
|
|
16
|
+
name: string;
|
|
17
|
+
/** Who reports model calls: the harness itself (its model proxy), or the kernel. */
|
|
18
|
+
modelCalls?: "effects" | "self";
|
|
19
|
+
drive(ctx: DriveContext): Promise<void>;
|
|
20
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { AcquireMachine, CacheDir, SessionProcess } from "./process.js";
|
|
2
|
+
import { type ModelProxyHooks, type ModelProxyOptions, type ParentWatch } from "@parcha/agentrun-kernel/host";
|
|
3
|
+
import { type CodexCommand } from "../catalog.js";
|
|
4
|
+
/** The variables a child takes from this process, when they are set. */
|
|
5
|
+
export declare const INHERITED_ENV: readonly ["PATH", "LANG", "TZ"];
|
|
6
|
+
/** One of a session's private directories under its own directory `dir`, where the local machine makes it. */
|
|
7
|
+
export declare const sessionDir: (dir: string, which: CacheDir) => string;
|
|
8
|
+
/** Files one of the machine's private directories holds at the start of every drive: each file's text by its path
|
|
9
|
+
* relative to that directory. */
|
|
10
|
+
export interface MachineSeed {
|
|
11
|
+
dir: CacheDir;
|
|
12
|
+
files: Readonly<Record<string, string>>;
|
|
13
|
+
}
|
|
14
|
+
export interface LocalMachineOptions {
|
|
15
|
+
/** The session's own directory. The machine makes its private directories in it and deletes only those. */
|
|
16
|
+
dir: string;
|
|
17
|
+
/** Codex's working directory: the host's workspace (absolute), where its file tools confine. Default `<dir>/work`.
|
|
18
|
+
* Never wiped: a drive wipes only the private directories. */
|
|
19
|
+
cwd?: string;
|
|
20
|
+
/** Start every child of the session (Codex) under the host's confinement. */
|
|
21
|
+
confine?: ConfineChild;
|
|
22
|
+
/** How a child is tied to this process (default what the machine supports; tests force the shim). */
|
|
23
|
+
parentWatch?: ParentWatch;
|
|
24
|
+
/** Codex's own web search, live: Codex's config says `web_search = "live"` (`configure`), and the proxy admits the tool
|
|
25
|
+
* Codex then sends and adds each search to the price. Default off. */
|
|
26
|
+
webSearch?: "live";
|
|
27
|
+
/** With `webSearch`: whether the host lets the session search now, asked before each request that offers it
|
|
28
|
+
* (CodexPolicyOptions.searchAllowed). */
|
|
29
|
+
searchAllowed?: () => Promise<boolean>;
|
|
30
|
+
/** The model proxy: the runner's hooks, the provider's price, and the session's tools and limits; its route comes
|
|
31
|
+
* from the harness. */
|
|
32
|
+
proxy: {
|
|
33
|
+
hooks: ModelProxyHooks;
|
|
34
|
+
/** The session's turn budget (ResultBudget.turn), which the proxy opens with each answer's facts. */
|
|
35
|
+
turn?: ModelProxyOptions["turn"];
|
|
36
|
+
tools: readonly string[];
|
|
37
|
+
price?: ModelProxyOptions["price"];
|
|
38
|
+
maxOutputTokens?: number;
|
|
39
|
+
/** On a person's ChatGPT plan: its rules (CodexPolicyOptions.plan). */
|
|
40
|
+
plan?: boolean;
|
|
41
|
+
credentialRefused?: ModelProxyOptions["credentialRefused"];
|
|
42
|
+
log?: ModelProxyOptions["log"];
|
|
43
|
+
fetch?: typeof fetch;
|
|
44
|
+
/** How long the provider may send nothing on a request before the proxy stops it (ModelProxyOptions.stallMs). */
|
|
45
|
+
stallMs?: number;
|
|
46
|
+
};
|
|
47
|
+
/** For tests: the process environment the allowlist reads. Default `process.env`. */
|
|
48
|
+
env?: Readonly<Record<string, string | undefined>>;
|
|
49
|
+
/** Files one of the session's private directories holds at the start of every drive: written when the machine is
|
|
50
|
+
* acquired and again after every wipe, which the harness runs before it starts Codex. Its paths are checked here. */
|
|
51
|
+
seed?: MachineSeed;
|
|
52
|
+
/** The binary the session runs, when its built-ins are off: Codex's own apply_patch, which then has no environment to run
|
|
53
|
+
* in, is offered to no model. Its bundled catalog without it (../catalog.ts) is read once per binary, written in codex-home
|
|
54
|
+
* with the seed and named in Codex's config (`configure`, `model_catalog_json`); one that can't be read is logged, and the
|
|
55
|
+
* session runs on Codex's own. */
|
|
56
|
+
catalog?: CodexCommand;
|
|
57
|
+
}
|
|
58
|
+
/** A command and its arguments, as the machine starts it. */
|
|
59
|
+
export interface ChildCommand {
|
|
60
|
+
command: string;
|
|
61
|
+
args: string[];
|
|
62
|
+
}
|
|
63
|
+
/** The host's confinement of a child: the same command and arguments, started under the host's own (a
|
|
64
|
+
* `setpriv --no-new-privs` prefix, say). It may only add in front: what it returns must end with the command and its
|
|
65
|
+
* arguments unchanged, and it never sees or changes the child's environment. The prefix must exec the child in place
|
|
66
|
+
* (as setpriv does): a wrapper that forks and stays as the child's parent defeats the parent watch, since the death
|
|
67
|
+
* signal then follows the wrapper, not this process. */
|
|
68
|
+
export type ConfineChild = (child: Readonly<ChildCommand>) => ChildCommand;
|
|
69
|
+
/** The command `confine` makes of `child`, refused unless it ends with the child's command and arguments unchanged. */
|
|
70
|
+
export declare function confined(child: ChildCommand, confine: ConfineChild | undefined): ChildCommand;
|
|
71
|
+
/** The child's environment: the allowlist from `from`, then what the caller names. */
|
|
72
|
+
export declare function childEnv(from: Readonly<Record<string, string | undefined>>, extra?: Readonly<Record<string, string>>): Record<string, string>;
|
|
73
|
+
/**
|
|
74
|
+
* A child's sends with no `turn/start` once the drive is stopped: no turn starts after a stop. Whether a placed prompt
|
|
75
|
+
* reached Codex is its rollout's to say (the settle reads it as the session keeps it): Codex answers turn/start before it
|
|
76
|
+
* writes the user message, so a stop just after the send can kill it with the prompt unrecorded. Every other line goes
|
|
77
|
+
* unchanged, in order, at once (the stop's own `turn/interrupt` too).
|
|
78
|
+
*/
|
|
79
|
+
export declare function withoutTurnsAfterStop<P extends Pick<SessionProcess, "send">>(proc: P, signal: AbortSignal): P;
|
|
80
|
+
/** A machine factory for sessions under `options.dir`: each acquire makes the directories fresh and starts a proxy. */
|
|
81
|
+
export declare function localMachine(options: LocalMachineOptions): AcquireMachine;
|
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
// The local session machine, written for AgentRun: where a session's Codex runs when the host runs it on its own box.
|
|
2
|
+
// - The session gets private directories under its own directory (home, config, codex-home, tmp, cache; mode 0700).
|
|
3
|
+
// Its working directory is the host's workspace when the host names one (`cwd`), where the host's file tools write,
|
|
4
|
+
// and otherwise an empty one of its own (`work`). Codex keeps nothing there (its state is in codex-home), and a
|
|
5
|
+
// tool-less Codex reads nothing there itself.
|
|
6
|
+
// A seed of files the host gives is in one of them at the start of every drive: written at acquire and after each wipe.
|
|
7
|
+
// So is Codex's bundled model catalog without its own apply_patch, when the host asks for it (`catalog`, ../catalog.ts).
|
|
8
|
+
// - A child's environment is an allowlist: PATH, LANG and TZ from this process, plus what the harness names (its homes,
|
|
9
|
+
// and the per-session proxy key). Nothing else is inherited, so no provider key, token or host secret reaches it.
|
|
10
|
+
// - A child's git stops at the session's directory and at a workspace's parent (GIT_CEILING_DIRECTORIES), and the host may start every child under its
|
|
11
|
+
// own confinement, in front of the command.
|
|
12
|
+
// - Each child runs in its own process group, which kill() and close() end whole, and dies with this process: started
|
|
13
|
+
// with a watch on its parent (./host's parentWatched, inside the host's confinement), so a host that is SIGKILLed,
|
|
14
|
+
// and runs no close, leaves no Codex behind.
|
|
15
|
+
// - The model proxy (@parcha/agentrun-kernel/host, with the Codex policy) starts with the machine and stops with it. It
|
|
16
|
+
// checks that the session's key comes from a process this machine spawned, not from one of its children
|
|
17
|
+
// (ModelProxyOptions.peers).
|
|
18
|
+
import { spawn as spawnChild } from "node:child_process";
|
|
19
|
+
import { randomBytes } from "node:crypto";
|
|
20
|
+
import { lstatSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
21
|
+
import { dirname, isAbsolute, join, normalize, sep } from "node:path";
|
|
22
|
+
import { createInterface } from "node:readline";
|
|
23
|
+
import { FileTail } from "@parcha/agentrun-kernel/process";
|
|
24
|
+
import { brandMachine } from "./process.js";
|
|
25
|
+
import { parentWatched, peerModeOf, startModelProxy } from "@parcha/agentrun-kernel/host";
|
|
26
|
+
import { codexPolicy, withWebSearches } from "./policy.js";
|
|
27
|
+
import { UNWATCHED } from "../scripts.js";
|
|
28
|
+
import { MODEL_CATALOG_FILE, patchlessCatalog } from "../catalog.js";
|
|
29
|
+
/** The variables a child takes from this process, when they are set. */
|
|
30
|
+
export const INHERITED_ENV = Object.freeze(["PATH", "LANG", "TZ"]);
|
|
31
|
+
const DIRS = ["home", "config", "codex-home", "tmp", "cache"];
|
|
32
|
+
const STDERR_TAIL = 8 * 1024;
|
|
33
|
+
/** One of a session's private directories under its own directory `dir`, where the local machine makes it. */
|
|
34
|
+
export const sessionDir = (dir, which) => join(normalize(dir), which);
|
|
35
|
+
/** The seed's files as the machine writes them; throws, naming the first path that is not a plain relative path inside
|
|
36
|
+
* its directory (empty, absolute, a backslash or NUL, an empty part, or a part that starts with a dot, `..` among them),
|
|
37
|
+
* or a directory that is not one of the machine's private ones. */
|
|
38
|
+
function seedFiles(seed) {
|
|
39
|
+
if (seed === undefined)
|
|
40
|
+
return [];
|
|
41
|
+
if (!DIRS.includes(seed.dir))
|
|
42
|
+
throw new Error(`agentrun-harness-codex: a seed goes in one of the machine's private directories (${DIRS.join(", ")}), not ${JSON.stringify(String(seed.dir).slice(0, 40))}`);
|
|
43
|
+
const encoder = new TextEncoder();
|
|
44
|
+
return Object.entries(seed.files).map(([path, text]) => {
|
|
45
|
+
if (!path || path.startsWith("/") || /[\\\0]/.test(path) || path.split("/").some((part) => part === "" || part.startsWith(".")))
|
|
46
|
+
throw new Error(`agentrun-harness-codex: the seed path ${JSON.stringify(path.slice(0, 80))} is not a plain relative path inside ${seed.dir}`);
|
|
47
|
+
if (typeof text !== "string")
|
|
48
|
+
throw new Error(`agentrun-harness-codex: the seed file ${JSON.stringify(path.slice(0, 80))} is not text`);
|
|
49
|
+
return { path, bytes: encoder.encode(text) };
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
/** The command `confine` makes of `child`, refused unless it ends with the child's command and arguments unchanged. */
|
|
53
|
+
export function confined(child, confine) {
|
|
54
|
+
if (!confine)
|
|
55
|
+
return child;
|
|
56
|
+
const out = confine({ command: child.command, args: [...child.args] });
|
|
57
|
+
const argv = [out?.command, ...(Array.isArray(out?.args) ? out.args : [])];
|
|
58
|
+
const tail = argv.slice(argv.length - child.args.length - 1);
|
|
59
|
+
const kept = argv.length > child.args.length + 1 && tail.length === child.args.length + 1 && tail.every((a, i) => a === (i === 0 ? child.command : child.args[i - 1]));
|
|
60
|
+
if (typeof out?.command !== "string" || !argv.every((a) => typeof a === "string") || !kept)
|
|
61
|
+
throw new Error("agentrun-harness-codex: the host's confinement must start the child's own command and arguments, after its own");
|
|
62
|
+
return { command: out.command, args: out.args };
|
|
63
|
+
}
|
|
64
|
+
/** The child's environment: the allowlist from `from`, then what the caller names. */
|
|
65
|
+
export function childEnv(from, extra = {}) {
|
|
66
|
+
const env = {};
|
|
67
|
+
for (const name of INHERITED_ENV) {
|
|
68
|
+
const value = from[name];
|
|
69
|
+
if (typeof value === "string")
|
|
70
|
+
env[name] = value;
|
|
71
|
+
}
|
|
72
|
+
return { ...env, ...extra };
|
|
73
|
+
}
|
|
74
|
+
/** A path inside `base`, from a relative one; anything that would leave it throws. */
|
|
75
|
+
function inside(base, rel) {
|
|
76
|
+
if (typeof rel !== "string" || !rel || isAbsolute(rel) || rel.includes("\0"))
|
|
77
|
+
throw new Error(`agentrun-harness-codex: ${JSON.stringify(String(rel).slice(0, 80))} is not a relative path`);
|
|
78
|
+
const path = normalize(join(base, rel));
|
|
79
|
+
if (!path.startsWith(base + sep))
|
|
80
|
+
throw new Error(`agentrun-harness-codex: ${JSON.stringify(rel.slice(0, 80))} leaves the session's directory`);
|
|
81
|
+
return path;
|
|
82
|
+
}
|
|
83
|
+
/** Start a child of the session, ended when this process ends. Its git stops at `ceiling` (the session's directory): it never looks for a repository
|
|
84
|
+
* above the session, in a parent the model could write, whose branch and remote would otherwise reach the records. */
|
|
85
|
+
function start(options, from, cwd, ceiling, confine, watch, admit) {
|
|
86
|
+
// The watch is inside the confinement, so it is set after any switch of user the prefix makes.
|
|
87
|
+
const run = confined(parentWatched({ command: options.command, args: options.args ?? [] }, watch), confine);
|
|
88
|
+
const child = spawnChild(run.command, run.args, {
|
|
89
|
+
cwd: options.cwd ?? cwd,
|
|
90
|
+
env: { ...childEnv(from, options.env), GIT_CEILING_DIRECTORIES: ceiling },
|
|
91
|
+
detached: true,
|
|
92
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
93
|
+
});
|
|
94
|
+
// Named to the model proxy before this turn of the event loop ends, so before the child can have asked it anything.
|
|
95
|
+
if (child.pid !== undefined)
|
|
96
|
+
admit?.(child.pid);
|
|
97
|
+
let stderr = "";
|
|
98
|
+
child.stderr.setEncoding("utf8");
|
|
99
|
+
child.stderr.on("data", (chunk) => {
|
|
100
|
+
stderr = (stderr + chunk).slice(-STDERR_TAIL);
|
|
101
|
+
});
|
|
102
|
+
child.stdin.on("error", () => { });
|
|
103
|
+
let done = false;
|
|
104
|
+
const exited = new Promise((resolve) => {
|
|
105
|
+
child.once("error", (err) => {
|
|
106
|
+
stderr = (stderr + `\n${String(err.message)}`).slice(-STDERR_TAIL);
|
|
107
|
+
done = true;
|
|
108
|
+
resolve({ code: null, signal: null });
|
|
109
|
+
});
|
|
110
|
+
child.once("close", (code, signal) => {
|
|
111
|
+
done = true;
|
|
112
|
+
resolve({ code, signal });
|
|
113
|
+
});
|
|
114
|
+
});
|
|
115
|
+
const kill = (signal = "SIGTERM") => {
|
|
116
|
+
if (done || child.pid === undefined)
|
|
117
|
+
return;
|
|
118
|
+
try {
|
|
119
|
+
process.kill(-child.pid, signal);
|
|
120
|
+
}
|
|
121
|
+
catch {
|
|
122
|
+
try {
|
|
123
|
+
child.kill(signal);
|
|
124
|
+
}
|
|
125
|
+
catch { /* gone */ }
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
if (options.signal) {
|
|
129
|
+
if (options.signal.aborted)
|
|
130
|
+
kill("SIGKILL");
|
|
131
|
+
else
|
|
132
|
+
options.signal.addEventListener("abort", () => kill("SIGKILL"), { once: true });
|
|
133
|
+
}
|
|
134
|
+
const reader = createInterface({ input: child.stdout, crlfDelay: Infinity });
|
|
135
|
+
return {
|
|
136
|
+
send: (line) => {
|
|
137
|
+
if (done || !child.stdin.writable)
|
|
138
|
+
return false;
|
|
139
|
+
return child.stdin.write(`${JSON.stringify(line)}\n`) || true;
|
|
140
|
+
},
|
|
141
|
+
end: () => child.stdin.end(),
|
|
142
|
+
lines: () => reader[Symbol.asyncIterator](),
|
|
143
|
+
exited,
|
|
144
|
+
stderrTail: () => stderr,
|
|
145
|
+
alive: () => !done,
|
|
146
|
+
kill,
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* A child's sends with no `turn/start` once the drive is stopped: no turn starts after a stop. Whether a placed prompt
|
|
151
|
+
* reached Codex is its rollout's to say (the settle reads it as the session keeps it): Codex answers turn/start before it
|
|
152
|
+
* writes the user message, so a stop just after the send can kill it with the prompt unrecorded. Every other line goes
|
|
153
|
+
* unchanged, in order, at once (the stop's own `turn/interrupt` too).
|
|
154
|
+
*/
|
|
155
|
+
export function withoutTurnsAfterStop(proc, signal) {
|
|
156
|
+
const send = proc.send.bind(proc);
|
|
157
|
+
return {
|
|
158
|
+
...proc,
|
|
159
|
+
send(line) {
|
|
160
|
+
if (signal.aborted && line?.method === "turn/start")
|
|
161
|
+
return true;
|
|
162
|
+
return send(line);
|
|
163
|
+
},
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
/** A machine factory for sessions under `options.dir`: each acquire makes the directories fresh and starts a proxy. */
|
|
167
|
+
export function localMachine(options) {
|
|
168
|
+
const from = options.env ?? process.env;
|
|
169
|
+
const seeded = seedFiles(options.seed);
|
|
170
|
+
return async ({ ctx, model }) => {
|
|
171
|
+
if (!model)
|
|
172
|
+
throw new Error("agentrun-harness-codex: the harness gave the machine no model route");
|
|
173
|
+
const base = normalize(options.dir);
|
|
174
|
+
if (!isAbsolute(base))
|
|
175
|
+
throw new Error("agentrun-harness-codex: the session directory must be an absolute path");
|
|
176
|
+
mkdirSync(base, { recursive: true, mode: 0o700 });
|
|
177
|
+
const dirs = Object.fromEntries(DIRS.map((d) => [d, sessionDir(base, d)]));
|
|
178
|
+
if (options.cwd !== undefined && !isAbsolute(options.cwd))
|
|
179
|
+
throw new Error("agentrun-harness-codex: the working directory must be an absolute path");
|
|
180
|
+
const root = options.cwd === undefined ? join(base, "work") : normalize(options.cwd);
|
|
181
|
+
for (const dir of [...Object.values(dirs), root])
|
|
182
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
183
|
+
// git stops at the session's directory and, for a workspace outside it, at the workspace's parent.
|
|
184
|
+
const ceiling = [base, ...(root === base || root.startsWith(base + sep) ? [] : [dirname(root)])].join(":");
|
|
185
|
+
const upload = (dir, files) => {
|
|
186
|
+
for (const file of files) {
|
|
187
|
+
const path = inside(dirs[dir], file.path);
|
|
188
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
189
|
+
writeFileSync(path, file.bytes, { mode: file.mode ?? 0o600 });
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
// Read in a CODEX_HOME of its own, not the session's, before anything else of the session starts.
|
|
193
|
+
const own = join(dirs.cache, "codex-catalog");
|
|
194
|
+
if (options.catalog)
|
|
195
|
+
mkdirSync(own, { recursive: true, mode: 0o700 });
|
|
196
|
+
const read = options.catalog ? await patchlessCatalog((spawnOptions) => start(spawnOptions, from, root, ceiling, options.confine, options.parentWatch), options.catalog, { home: dirs.home, tmp: dirs.tmp, own }, ctx.signal) : undefined;
|
|
197
|
+
const catalog = read?.bytes;
|
|
198
|
+
// A catalog that could not be read is never silent: the run is told why apply_patch stays listed (the machine's notes).
|
|
199
|
+
const notes = read?.why ? [read.why] : [];
|
|
200
|
+
const seed = () => {
|
|
201
|
+
if (options.seed)
|
|
202
|
+
upload(options.seed.dir, seeded);
|
|
203
|
+
if (catalog)
|
|
204
|
+
upload("codex-home", [{ path: MODEL_CATALOG_FILE, bytes: catalog }]);
|
|
205
|
+
};
|
|
206
|
+
// Before the proxy starts: a seed that cannot be written is refused with nothing left running.
|
|
207
|
+
seed();
|
|
208
|
+
const key = randomBytes(32).toString("base64url");
|
|
209
|
+
const route = model.options;
|
|
210
|
+
// The code-mode `exec` the model proxy's latest answer carried: set while the answer passes, before Codex has it.
|
|
211
|
+
let announced;
|
|
212
|
+
// The script of the last `exec` announced, by its call id: what the host's record of that exec shows.
|
|
213
|
+
let script;
|
|
214
|
+
let open = 0;
|
|
215
|
+
const rolloutListeners = [];
|
|
216
|
+
const cutListeners = [];
|
|
217
|
+
const search = options.webSearch === "live";
|
|
218
|
+
const price = options.proxy.price && search ? withWebSearches(options.proxy.price) : options.proxy.price;
|
|
219
|
+
const proxy = await startModelProxy({
|
|
220
|
+
policy: codexPolicy({
|
|
221
|
+
model: route.models.model,
|
|
222
|
+
tools: options.proxy.tools,
|
|
223
|
+
...(options.proxy.maxOutputTokens ? { maxOutputTokens: options.proxy.maxOutputTokens } : {}),
|
|
224
|
+
...(options.proxy.plan ? { plan: true } : {}),
|
|
225
|
+
...(search ? { webSearch: "live", ...(options.searchAllowed ? { searchAllowed: options.searchAllowed } : {}) } : {}),
|
|
226
|
+
announce: {
|
|
227
|
+
// The cost is liveness, not safety: after an overlap a never call is declined until the next single answer, which the model's
|
|
228
|
+
// next wait or exec gives.
|
|
229
|
+
// A second answer that starts while one is open (a background call beside the turn) makes every tie ambiguous until both have
|
|
230
|
+
// ended: which of them carried which exec cannot be told. A failed watch, likewise, stands for an exec not seen.
|
|
231
|
+
response: () => {
|
|
232
|
+
open += 1;
|
|
233
|
+
announced = open > 1 ? UNWATCHED : undefined;
|
|
234
|
+
},
|
|
235
|
+
exec: (callId, input) => {
|
|
236
|
+
script = { callId, input: input ?? "" };
|
|
237
|
+
announced = open > 1 || announced === UNWATCHED ? UNWATCHED : callId;
|
|
238
|
+
},
|
|
239
|
+
failed: () => void (announced = UNWATCHED),
|
|
240
|
+
end: () => void (open = Math.max(0, open - 1)),
|
|
241
|
+
},
|
|
242
|
+
}),
|
|
243
|
+
hooks: options.proxy.hooks,
|
|
244
|
+
...(options.proxy.turn ? { turn: options.proxy.turn } : {}),
|
|
245
|
+
model: route.models.model,
|
|
246
|
+
origin: route.target,
|
|
247
|
+
credential: async () => (await route.credential()) ?? "",
|
|
248
|
+
...(options.proxy.credentialRefused ? { credentialRefused: options.proxy.credentialRefused } : {}),
|
|
249
|
+
...(price ? { price } : {}),
|
|
250
|
+
...(options.proxy.log ? { log: options.proxy.log } : {}),
|
|
251
|
+
...(options.proxy.fetch ? { fetch: options.proxy.fetch } : {}),
|
|
252
|
+
...(options.proxy.stallMs !== undefined ? { stallMs: options.proxy.stallMs } : {}),
|
|
253
|
+
// The provider stopped the turn's answer on its content filter: no retry of it can pass, so the turn ends at once.
|
|
254
|
+
onFiltered: (message) => ctx.halt?.(new Error(message)),
|
|
255
|
+
// The provider's error answer ends the run (a ChatGPT plan's limit reached), or the proxy stopped a request the
|
|
256
|
+
// provider sent nothing on for its stall bound: no retry or other key can pass it.
|
|
257
|
+
onFinal: (message) => ctx.halt?.(new Error(message)),
|
|
258
|
+
// The provider cut the turn's answer at its output limit: Codex would ask for it again (it retries an incomplete
|
|
259
|
+
// stream), so the harness ends the turn there, its answer cut.
|
|
260
|
+
onCut: (stop) => {
|
|
261
|
+
for (const listener of cutListeners)
|
|
262
|
+
listener(stop);
|
|
263
|
+
},
|
|
264
|
+
// The key is in app-server's environment, which every process of its user can read: the proxy checks that it comes
|
|
265
|
+
// from a process this machine spawned (app-server), never from that process's children (its code-mode host, a
|
|
266
|
+
// tool). Logged only, unless the host's environment asks to enforce it (PEER_CHECK_ENV).
|
|
267
|
+
peers: { mode: peerModeOf(from), session: ctx.runId },
|
|
268
|
+
}, key);
|
|
269
|
+
const lost = new AbortController();
|
|
270
|
+
const children = new Set();
|
|
271
|
+
let closed = false;
|
|
272
|
+
const machine = {
|
|
273
|
+
sessionId: ctx.runId,
|
|
274
|
+
root,
|
|
275
|
+
dirs,
|
|
276
|
+
signal: lost.signal,
|
|
277
|
+
modelUrl: proxy.url,
|
|
278
|
+
modelKey: key,
|
|
279
|
+
announcedExec: () => announced,
|
|
280
|
+
announcedInput: (callId) => (script?.callId === callId ? script.input : undefined),
|
|
281
|
+
onRolloutLine: (listener) => void rolloutListeners.push(listener),
|
|
282
|
+
onCut: (listener) => void cutListeners.push(listener),
|
|
283
|
+
openTurn: () => proxy.openTurn(),
|
|
284
|
+
...(search || catalog ? {
|
|
285
|
+
configure: (config) => {
|
|
286
|
+
if (search)
|
|
287
|
+
config.web_search = "live";
|
|
288
|
+
// Only with the built-ins off: with them on, apply_patch runs through the shell.
|
|
289
|
+
const features = config.features;
|
|
290
|
+
if (catalog && features?.shell_tool !== true && features?.unified_exec !== true)
|
|
291
|
+
config.model_catalog_json = join(dirs["codex-home"], MODEL_CATALOG_FILE);
|
|
292
|
+
},
|
|
293
|
+
} : {}),
|
|
294
|
+
notes,
|
|
295
|
+
spawn: async (spawnOptions) => {
|
|
296
|
+
if (closed)
|
|
297
|
+
throw new Error("agentrun-harness-codex: the session machine is closed");
|
|
298
|
+
const proc = withoutTurnsAfterStop(start(spawnOptions, from, root, ceiling, options.confine, options.parentWatch, (pid) => proxy.admitProcess(pid)), ctx.signal);
|
|
299
|
+
children.add(proc);
|
|
300
|
+
void proc.exited.then(() => children.delete(proc));
|
|
301
|
+
return proc;
|
|
302
|
+
},
|
|
303
|
+
files: {
|
|
304
|
+
upload: async (dir, files) => upload(dir, files),
|
|
305
|
+
// Everything goes, then the seed is written again: what a drive starts with is the host's, never an earlier drive's.
|
|
306
|
+
wipe: async () => {
|
|
307
|
+
for (const dir of Object.values(dirs)) {
|
|
308
|
+
rmSync(dir, { recursive: true, force: true });
|
|
309
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
310
|
+
}
|
|
311
|
+
seed();
|
|
312
|
+
},
|
|
313
|
+
},
|
|
314
|
+
tail: async (dir, path, tailOptions = {}) => {
|
|
315
|
+
const file = inside(dirs[dir], path);
|
|
316
|
+
const tail = new FileTail(file, tailOptions.offset ?? 0);
|
|
317
|
+
return {
|
|
318
|
+
get offset() { return tail.offset; },
|
|
319
|
+
read: () => {
|
|
320
|
+
// Only the file Codex wrote: a link put in its place is not followed.
|
|
321
|
+
try {
|
|
322
|
+
if (lstatSync(file).isSymbolicLink())
|
|
323
|
+
throw new Error(`agentrun-harness-codex: ${path} is a link`);
|
|
324
|
+
}
|
|
325
|
+
catch (err) {
|
|
326
|
+
if (err.code !== "ENOENT")
|
|
327
|
+
throw err;
|
|
328
|
+
}
|
|
329
|
+
const fresh = tail.read();
|
|
330
|
+
for (const line of fresh)
|
|
331
|
+
for (const listener of rolloutListeners)
|
|
332
|
+
listener(line);
|
|
333
|
+
return fresh;
|
|
334
|
+
},
|
|
335
|
+
// A local file is read to its end on every read.
|
|
336
|
+
sync: async () => { },
|
|
337
|
+
close: () => { },
|
|
338
|
+
};
|
|
339
|
+
},
|
|
340
|
+
// A tool-less session writes no files of its own to flush.
|
|
341
|
+
fsync: async () => { },
|
|
342
|
+
close: async () => {
|
|
343
|
+
if (closed)
|
|
344
|
+
return;
|
|
345
|
+
closed = true;
|
|
346
|
+
for (const proc of children)
|
|
347
|
+
proc.kill("SIGKILL");
|
|
348
|
+
await Promise.all([...children].map((p) => p.exited));
|
|
349
|
+
lost.abort();
|
|
350
|
+
await proxy.close();
|
|
351
|
+
},
|
|
352
|
+
};
|
|
353
|
+
return brandMachine(machine);
|
|
354
|
+
};
|
|
355
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { type ModelProxyOptions, type ProviderPolicy, type ProxyRoute, type ProxyUsage, type ReasoningSeen } from "@parcha/agentrun-kernel/host";
|
|
2
|
+
export declare const CODEX_RESPONSES_ROUTES: readonly ProxyRoute[];
|
|
3
|
+
/** The price of one web search call on `model`, or undefined when it is not known. */
|
|
4
|
+
export declare function webSearchUsd(model: string): number | undefined;
|
|
5
|
+
/** A response's usage, with the web searches it ran when the session's web search is on (null: the response did not say). */
|
|
6
|
+
export interface CodexUsage extends ProxyUsage {
|
|
7
|
+
webSearches?: number | null;
|
|
8
|
+
}
|
|
9
|
+
/** `price` with each web search a response ran added at its model's per-call price. Unknown (null) when the tokens' price
|
|
10
|
+
* is, when the response did not say how many searches it ran, or when the model's search price is not known; a response
|
|
11
|
+
* that ran none costs what its tokens do. */
|
|
12
|
+
export declare function withWebSearches(price: NonNullable<ModelProxyOptions["price"]>): NonNullable<ModelProxyOptions["price"]>;
|
|
13
|
+
export interface CodexPolicyOptions {
|
|
14
|
+
/** The session's model: the body's model is set to it. */
|
|
15
|
+
model: string;
|
|
16
|
+
/** The session's own tool names: every other tool definition is dropped. */
|
|
17
|
+
tools: readonly string[];
|
|
18
|
+
/** The most output tokens one request may ask for. Default 32 000. */
|
|
19
|
+
maxOutputTokens?: number;
|
|
20
|
+
/** Codex's own web search, live: the live search tool the pinned CLI sends passes, and a `tool_choice` naming it. Each
|
|
21
|
+
* response's usage then carries the searches it ran (`webSearches`), which `withWebSearches` prices. Default off. */
|
|
22
|
+
webSearch?: "live";
|
|
23
|
+
/** With `webSearch`: whether the host lets the session search now (its web_search setting, SessionIO.permission), asked
|
|
24
|
+
* before each request that offers the live search. The provider runs a search inside the request, where no gate sees
|
|
25
|
+
* it, so a request sent while this is false (or throws) offers no search, as a session without one sends it; a
|
|
26
|
+
* `tool_choice` naming the search is then refused. Absent: the live search is offered whenever `webSearch` is on. */
|
|
27
|
+
searchAllowed?: () => Promise<boolean>;
|
|
28
|
+
/** Told, before Codex has the piece of an answer, what the answer carries: `response()` when an answer starts, and
|
|
29
|
+
* `exec(callId, input)` for each code-mode `exec` call it holds, with its script. The session ties a script's nested
|
|
30
|
+
* calls to the `exec` of the latest answer, which is known here before Codex can run anything of it. */
|
|
31
|
+
announce?: {
|
|
32
|
+
response(): void;
|
|
33
|
+
exec(callId: string, input?: string): void;
|
|
34
|
+
failed(): void;
|
|
35
|
+
end(): void;
|
|
36
|
+
};
|
|
37
|
+
/** The route is a person's ChatGPT plan (its access token the credential), whose Responses API keeps rules of its own:
|
|
38
|
+
* no `max_output_tokens` is sent (none is clamped or added: the proxy limits no output and counts no input on it), the
|
|
39
|
+
* keys it does not take are dropped (PLAN_DROPPED_KEYS), a system-role message is refused in words, each request names
|
|
40
|
+
* its originator (`agentrun`), and its usage is booked as the plan's (`billing: "plan"`). */
|
|
41
|
+
plan?: boolean;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Whether the provider stopped the answer on its content filter: the stream's terminal event (or a whole body) is an
|
|
45
|
+
* `incomplete` response whose `incomplete_details.reason` is `content_filter`. Read by parsing each `data:` line on its
|
|
46
|
+
* own, as endValue reads the usage, never by matching text; an answer cut at its output limit (`max_output_tokens`) is not one.
|
|
47
|
+
*
|
|
48
|
+
* The terminal event carries the whole response (its output, encrypted reasoning included), so its line can be longer
|
|
49
|
+
* than the proxy keeps of an answer; then the proxy's start of that line is read. The response's fields come in a fixed
|
|
50
|
+
* order, `id`, `object`, `created_at`, `status`, `background`, `error`, `incomplete_details`, then `instructions`, the
|
|
51
|
+
* tools and the output (OpenAI's; a LiteLLM gateway's, `id`, `created_at`, `incomplete_details`, ..., `output`, keeps it
|
|
52
|
+
* ahead of the output too), so `incomplete_details` is near the line's start. It is read only on a line that is the event's
|
|
53
|
+
* own: one the SSE `event: response.incomplete` names (OpenAI's API), or whose data says `"type":"response.incomplete"`
|
|
54
|
+
* before its `"response":{` (a gateway that sends each event as its data alone: LiteLLM), as the first
|
|
55
|
+
* `"incomplete_details":{` after `"response":{` (one JSON object), whatever the JSON's spacing.
|
|
56
|
+
*/
|
|
57
|
+
export declare function filtered(text: string, lineStarts?: readonly string[]): boolean;
|
|
58
|
+
/**
|
|
59
|
+
* Whether the provider cut the answer at its output limit: its end is an `incomplete` response whose
|
|
60
|
+
* `incomplete_details.reason` is `max_output_tokens`, with the output tokens its usage reports when the end was read whole.
|
|
61
|
+
* Read as `filtered` reads its stop, but keyed only on the data's own `type` (`response.incomplete`), never on an `event:`
|
|
62
|
+
* line: a gateway's Responses stream is data alone. Any other reason (`content_filter`) is no cut. Codex 0.164 takes a cut
|
|
63
|
+
* answer as a stream error and asks for it again, each time paid; the harness ends the turn first.
|
|
64
|
+
*/
|
|
65
|
+
export declare function cut(text: string, lineStarts?: readonly string[]): {
|
|
66
|
+
outputTokens?: number;
|
|
67
|
+
} | undefined;
|
|
68
|
+
/** The usage a Responses answer reports at its end (`endValue`), or undefined, an unknown cost, when it reports none. */
|
|
69
|
+
export declare function usageOf(text: string): ProxyUsage | undefined;
|
|
70
|
+
/** The web searches a Responses answer ran, as its terminal event reports them (`tool_usage.web_search.num_requests`,
|
|
71
|
+
* what OpenAI bills per call), or undefined when that event's own count cannot be read: an unknown cost, never 0. */
|
|
72
|
+
export declare function webSearchesOf(text: string): number | undefined;
|
|
73
|
+
/** The tokens a request keeps for its answer when its output is limited. */
|
|
74
|
+
export declare const ANSWER_TOKENS_LEAST = 1024;
|
|
75
|
+
/** What a reasoning request at each effort is allowed for its reasoning beside its answer, when its output is limited:
|
|
76
|
+
* OpenAI's reasoning shares `max_output_tokens` and takes no budget, so a limit under its reasoning comes back
|
|
77
|
+
* incomplete with no answer. The figures are pi-ai's thinking budgets by level (xhigh at high's). */
|
|
78
|
+
export declare const REASONING_TOKENS_ALLOWED: Readonly<Record<string, number>>;
|
|
79
|
+
/** The output tokens a Responses body asks for at most: its `max_output_tokens` (as `apply` clamped it). */
|
|
80
|
+
export declare function responsesOutputAsked(body: Record<string, unknown>): number | undefined;
|
|
81
|
+
/** The least output a Responses body may be limited to and still answer: 1,024 tokens, plus, when it reasons, its
|
|
82
|
+
* reasoning effort's allowance, or, once the run has seen its model reason (`seen.most`, the most reasoning tokens one
|
|
83
|
+
* of its answers reported), twice that most, never past the allowance. OpenAI's reasoning shares the output limit, so a
|
|
84
|
+
* limit is a least, not a budget: the request is still sent with all the output the cap fits, and an answer the limit
|
|
85
|
+
* cuts is said to be the cap's cut (ModelTicket.capCut). */
|
|
86
|
+
export declare function responsesOutputLeast(body: Record<string, unknown>, seen?: ReasoningSeen): number;
|
|
87
|
+
/** The reasoning effort a Responses body asks its model at (`reasoning.effort`), when it names one. */
|
|
88
|
+
export declare function responsesEffort(body: Record<string, unknown>): string | undefined;
|
|
89
|
+
/** The reasoning tokens a Responses request may bill that its stream never shows (only a summary of its reasoning
|
|
90
|
+
* streams): its effort's budget; none at effort `none`; and with no effort the body says (the model then reasons at its
|
|
91
|
+
* own default, or not at all), its output limit, `fallback` when the body names none: the conservative side. An
|
|
92
|
+
* estimate, as the efforts' budgets are not limits the provider keeps: a stopped request counts the part of it that
|
|
93
|
+
* did not stream (less `responsesReasoningBytes` of what it sent), never past its hold. */
|
|
94
|
+
export declare function responsesReasoningHidden(body: Record<string, unknown>, fallback: number): number;
|
|
95
|
+
/** The bytes of reasoning one Responses stream event carries: a reasoning delta's text, UTF-8; 0 for answer text, a
|
|
96
|
+
* function call's arguments and every other event. */
|
|
97
|
+
export declare function responsesReasoningBytes(event: string): number;
|
|
98
|
+
/** The bytes of content one Responses stream event carries: a content delta's text, UTF-8, never the framing around it
|
|
99
|
+
* (its sequence number, item id, indexes, logprobs, obfuscation); 0 for every other event. */
|
|
100
|
+
export declare function responsesContentBytes(event: string): number;
|
|
101
|
+
/** A Responses body with its output limited to `max` tokens, reasoning included: never raised, and never longer. */
|
|
102
|
+
export declare function limitResponsesOutput(body: Record<string, unknown>, max: number): Record<string, unknown>;
|
|
103
|
+
/** `body` (a Responses body) with `text` as a note the model reads after everything the client sent: one developer message
|
|
104
|
+
* at the end of `input`. Caching is by prefix, so the earlier items stay a hit; the client's next request, which sends
|
|
105
|
+
* its own input whole, does not carry it. */
|
|
106
|
+
export declare function addResponsesNote(body: Record<string, unknown>, text: string): Record<string, unknown>;
|
|
107
|
+
/** A ChatGPT plan's 429 past its limit (PLAN_LIMIT_ERRORS, as the error's `code` or `type`): final, in PLAN_LIMIT_WORDS.
|
|
108
|
+
* Any other error goes through as it came (a 429 for the rate, which its client waits out and asks again). */
|
|
109
|
+
export declare function planLimitOf(status: number, body: string): {
|
|
110
|
+
message: string;
|
|
111
|
+
code: string;
|
|
112
|
+
} | undefined;
|
|
113
|
+
export declare function codexPolicy(options: CodexPolicyOptions): ProviderPolicy;
|