@parcha/agentrun-harness-codex 0.0.0-stage → 0.1.0-beta.29
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 +58 -0
- package/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +72 -2
- package/dist/adapter.d.ts +59 -0
- package/dist/adapter.js +276 -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 +58 -0
- package/dist/host/machine.js +284 -0
- package/dist/host/policy.d.ts +60 -0
- package/dist/host/policy.js +478 -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
|
@@ -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,58 @@
|
|
|
1
|
+
import type { AcquireMachine, CacheDir } from "./process.js";
|
|
2
|
+
import { type ModelProxyHooks, type ModelProxyOptions, type ParentWatch } from "@parcha/agentrun-kernel/host";
|
|
3
|
+
/** The variables a child takes from this process, when they are set. */
|
|
4
|
+
export declare const INHERITED_ENV: readonly ["PATH", "LANG", "TZ"];
|
|
5
|
+
/** One of a session's private directories under its own directory `dir`, where the local machine makes it. */
|
|
6
|
+
export declare const sessionDir: (dir: string, which: CacheDir) => string;
|
|
7
|
+
/** Files one of the machine's private directories holds at the start of every drive: each file's text by its path
|
|
8
|
+
* relative to that directory. */
|
|
9
|
+
export interface MachineSeed {
|
|
10
|
+
dir: CacheDir;
|
|
11
|
+
files: Readonly<Record<string, string>>;
|
|
12
|
+
}
|
|
13
|
+
export interface LocalMachineOptions {
|
|
14
|
+
/** The session's own directory. The machine makes its private directories in it and deletes only those. */
|
|
15
|
+
dir: string;
|
|
16
|
+
/** Codex's working directory: the host's workspace (absolute), where its file tools confine. Default `<dir>/work`.
|
|
17
|
+
* Never wiped: a drive wipes only the private directories. */
|
|
18
|
+
cwd?: string;
|
|
19
|
+
/** Start every child of the session (Codex) under the host's confinement. */
|
|
20
|
+
confine?: ConfineChild;
|
|
21
|
+
/** How a child is tied to this process (default what the machine supports; tests force the shim). */
|
|
22
|
+
parentWatch?: ParentWatch;
|
|
23
|
+
/** Codex's own web search, live: Codex's config says `web_search = "live"` (`configure`), and the proxy admits the tool
|
|
24
|
+
* Codex then sends and adds each search to the price. Default off. */
|
|
25
|
+
webSearch?: "live";
|
|
26
|
+
/** The model proxy: the runner's hooks, the provider's price, and the session's tools and limits; its route comes
|
|
27
|
+
* from the harness. */
|
|
28
|
+
proxy: {
|
|
29
|
+
hooks: ModelProxyHooks;
|
|
30
|
+
tools: readonly string[];
|
|
31
|
+
price?: ModelProxyOptions["price"];
|
|
32
|
+
maxOutputTokens?: number;
|
|
33
|
+
log?: ModelProxyOptions["log"];
|
|
34
|
+
fetch?: typeof fetch;
|
|
35
|
+
};
|
|
36
|
+
/** For tests: the process environment the allowlist reads. Default `process.env`. */
|
|
37
|
+
env?: Readonly<Record<string, string | undefined>>;
|
|
38
|
+
/** Files one of the session's private directories holds at the start of every drive: written when the machine is
|
|
39
|
+
* acquired and again after every wipe, which the harness runs before it starts Codex. Its paths are checked here. */
|
|
40
|
+
seed?: MachineSeed;
|
|
41
|
+
}
|
|
42
|
+
/** A command and its arguments, as the machine starts it. */
|
|
43
|
+
export interface ChildCommand {
|
|
44
|
+
command: string;
|
|
45
|
+
args: string[];
|
|
46
|
+
}
|
|
47
|
+
/** The host's confinement of a child: the same command and arguments, started under the host's own (a
|
|
48
|
+
* `setpriv --no-new-privs` prefix, say). It may only add in front: what it returns must end with the command and its
|
|
49
|
+
* arguments unchanged, and it never sees or changes the child's environment. The prefix must exec the child in place
|
|
50
|
+
* (as setpriv does): a wrapper that forks and stays as the child's parent defeats the parent watch, since the death
|
|
51
|
+
* signal then follows the wrapper, not this process. */
|
|
52
|
+
export type ConfineChild = (child: Readonly<ChildCommand>) => ChildCommand;
|
|
53
|
+
/** The command `confine` makes of `child`, refused unless it ends with the child's command and arguments unchanged. */
|
|
54
|
+
export declare function confined(child: ChildCommand, confine: ConfineChild | undefined): ChildCommand;
|
|
55
|
+
/** The child's environment: the allowlist from `from`, then what the caller names. */
|
|
56
|
+
export declare function childEnv(from: Readonly<Record<string, string | undefined>>, extra?: Readonly<Record<string, string>>): Record<string, string>;
|
|
57
|
+
/** A machine factory for sessions under `options.dir`: each acquire makes the directories fresh and starts a proxy. */
|
|
58
|
+
export declare function localMachine(options: LocalMachineOptions): AcquireMachine;
|
|
@@ -0,0 +1,284 @@
|
|
|
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
|
+
// - A child's environment is an allowlist: PATH, LANG and TZ from this process, plus what the harness names (its homes,
|
|
8
|
+
// and the per-session proxy key). Nothing else is inherited, so no provider key, token or host secret reaches it.
|
|
9
|
+
// - 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
|
|
10
|
+
// own confinement, in front of the command.
|
|
11
|
+
// - Each child runs in its own process group, which kill() and close() end whole, and dies with this process: started
|
|
12
|
+
// with a watch on its parent (./host's parentWatched, inside the host's confinement), so a host that is SIGKILLed,
|
|
13
|
+
// and runs no close, leaves no Codex behind.
|
|
14
|
+
// - The model proxy (@parcha/agentrun-kernel/host, with the Codex policy) starts with the machine and stops with it.
|
|
15
|
+
import { spawn as spawnChild } from "node:child_process";
|
|
16
|
+
import { randomBytes } from "node:crypto";
|
|
17
|
+
import { lstatSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
18
|
+
import { dirname, isAbsolute, join, normalize, sep } from "node:path";
|
|
19
|
+
import { createInterface } from "node:readline";
|
|
20
|
+
import { FileTail } from "@parcha/agentrun-kernel/process";
|
|
21
|
+
import { brandMachine } from "./process.js";
|
|
22
|
+
import { parentWatched, startModelProxy } from "@parcha/agentrun-kernel/host";
|
|
23
|
+
import { codexPolicy, withWebSearches } from "./policy.js";
|
|
24
|
+
import { UNWATCHED } from "../scripts.js";
|
|
25
|
+
/** The variables a child takes from this process, when they are set. */
|
|
26
|
+
export const INHERITED_ENV = Object.freeze(["PATH", "LANG", "TZ"]);
|
|
27
|
+
const DIRS = ["home", "config", "codex-home", "tmp", "cache"];
|
|
28
|
+
const STDERR_TAIL = 8 * 1024;
|
|
29
|
+
/** One of a session's private directories under its own directory `dir`, where the local machine makes it. */
|
|
30
|
+
export const sessionDir = (dir, which) => join(normalize(dir), which);
|
|
31
|
+
/** The seed's files as the machine writes them; throws, naming the first path that is not a plain relative path inside
|
|
32
|
+
* its directory (empty, absolute, a backslash or NUL, an empty part, or a part that starts with a dot, `..` among them),
|
|
33
|
+
* or a directory that is not one of the machine's private ones. */
|
|
34
|
+
function seedFiles(seed) {
|
|
35
|
+
if (seed === undefined)
|
|
36
|
+
return [];
|
|
37
|
+
if (!DIRS.includes(seed.dir))
|
|
38
|
+
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))}`);
|
|
39
|
+
const encoder = new TextEncoder();
|
|
40
|
+
return Object.entries(seed.files).map(([path, text]) => {
|
|
41
|
+
if (!path || path.startsWith("/") || /[\\\0]/.test(path) || path.split("/").some((part) => part === "" || part.startsWith(".")))
|
|
42
|
+
throw new Error(`agentrun-harness-codex: the seed path ${JSON.stringify(path.slice(0, 80))} is not a plain relative path inside ${seed.dir}`);
|
|
43
|
+
if (typeof text !== "string")
|
|
44
|
+
throw new Error(`agentrun-harness-codex: the seed file ${JSON.stringify(path.slice(0, 80))} is not text`);
|
|
45
|
+
return { path, bytes: encoder.encode(text) };
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
/** The command `confine` makes of `child`, refused unless it ends with the child's command and arguments unchanged. */
|
|
49
|
+
export function confined(child, confine) {
|
|
50
|
+
if (!confine)
|
|
51
|
+
return child;
|
|
52
|
+
const out = confine({ command: child.command, args: [...child.args] });
|
|
53
|
+
const argv = [out?.command, ...(Array.isArray(out?.args) ? out.args : [])];
|
|
54
|
+
const tail = argv.slice(argv.length - child.args.length - 1);
|
|
55
|
+
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]));
|
|
56
|
+
if (typeof out?.command !== "string" || !argv.every((a) => typeof a === "string") || !kept)
|
|
57
|
+
throw new Error("agentrun-harness-codex: the host's confinement must start the child's own command and arguments, after its own");
|
|
58
|
+
return { command: out.command, args: out.args };
|
|
59
|
+
}
|
|
60
|
+
/** The child's environment: the allowlist from `from`, then what the caller names. */
|
|
61
|
+
export function childEnv(from, extra = {}) {
|
|
62
|
+
const env = {};
|
|
63
|
+
for (const name of INHERITED_ENV) {
|
|
64
|
+
const value = from[name];
|
|
65
|
+
if (typeof value === "string")
|
|
66
|
+
env[name] = value;
|
|
67
|
+
}
|
|
68
|
+
return { ...env, ...extra };
|
|
69
|
+
}
|
|
70
|
+
/** A path inside `base`, from a relative one; anything that would leave it throws. */
|
|
71
|
+
function inside(base, rel) {
|
|
72
|
+
if (typeof rel !== "string" || !rel || isAbsolute(rel) || rel.includes("\0"))
|
|
73
|
+
throw new Error(`agentrun-harness-codex: ${JSON.stringify(String(rel).slice(0, 80))} is not a relative path`);
|
|
74
|
+
const path = normalize(join(base, rel));
|
|
75
|
+
if (!path.startsWith(base + sep))
|
|
76
|
+
throw new Error(`agentrun-harness-codex: ${JSON.stringify(rel.slice(0, 80))} leaves the session's directory`);
|
|
77
|
+
return path;
|
|
78
|
+
}
|
|
79
|
+
/** 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
|
|
80
|
+
* above the session, in a parent the model could write, whose branch and remote would otherwise reach the records. */
|
|
81
|
+
function start(options, from, cwd, ceiling, confine, watch) {
|
|
82
|
+
// The watch is inside the confinement, so it is set after any switch of user the prefix makes.
|
|
83
|
+
const run = confined(parentWatched({ command: options.command, args: options.args ?? [] }, watch), confine);
|
|
84
|
+
const child = spawnChild(run.command, run.args, {
|
|
85
|
+
cwd: options.cwd ?? cwd,
|
|
86
|
+
env: { ...childEnv(from, options.env), GIT_CEILING_DIRECTORIES: ceiling },
|
|
87
|
+
detached: true,
|
|
88
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
89
|
+
});
|
|
90
|
+
let stderr = "";
|
|
91
|
+
child.stderr.setEncoding("utf8");
|
|
92
|
+
child.stderr.on("data", (chunk) => {
|
|
93
|
+
stderr = (stderr + chunk).slice(-STDERR_TAIL);
|
|
94
|
+
});
|
|
95
|
+
child.stdin.on("error", () => { });
|
|
96
|
+
let done = false;
|
|
97
|
+
const exited = new Promise((resolve) => {
|
|
98
|
+
child.once("error", (err) => {
|
|
99
|
+
stderr = (stderr + `\n${String(err.message)}`).slice(-STDERR_TAIL);
|
|
100
|
+
done = true;
|
|
101
|
+
resolve({ code: null, signal: null });
|
|
102
|
+
});
|
|
103
|
+
child.once("close", (code, signal) => {
|
|
104
|
+
done = true;
|
|
105
|
+
resolve({ code, signal });
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
const kill = (signal = "SIGTERM") => {
|
|
109
|
+
if (done || child.pid === undefined)
|
|
110
|
+
return;
|
|
111
|
+
try {
|
|
112
|
+
process.kill(-child.pid, signal);
|
|
113
|
+
}
|
|
114
|
+
catch {
|
|
115
|
+
try {
|
|
116
|
+
child.kill(signal);
|
|
117
|
+
}
|
|
118
|
+
catch { /* gone */ }
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
if (options.signal) {
|
|
122
|
+
if (options.signal.aborted)
|
|
123
|
+
kill("SIGKILL");
|
|
124
|
+
else
|
|
125
|
+
options.signal.addEventListener("abort", () => kill("SIGKILL"), { once: true });
|
|
126
|
+
}
|
|
127
|
+
const reader = createInterface({ input: child.stdout, crlfDelay: Infinity });
|
|
128
|
+
return {
|
|
129
|
+
send: (line) => {
|
|
130
|
+
if (done || !child.stdin.writable)
|
|
131
|
+
return false;
|
|
132
|
+
return child.stdin.write(`${JSON.stringify(line)}\n`) || true;
|
|
133
|
+
},
|
|
134
|
+
end: () => child.stdin.end(),
|
|
135
|
+
lines: () => reader[Symbol.asyncIterator](),
|
|
136
|
+
exited,
|
|
137
|
+
stderrTail: () => stderr,
|
|
138
|
+
alive: () => !done,
|
|
139
|
+
kill,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
/** A machine factory for sessions under `options.dir`: each acquire makes the directories fresh and starts a proxy. */
|
|
143
|
+
export function localMachine(options) {
|
|
144
|
+
const from = options.env ?? process.env;
|
|
145
|
+
const seeded = seedFiles(options.seed);
|
|
146
|
+
return async ({ ctx, model }) => {
|
|
147
|
+
if (!model)
|
|
148
|
+
throw new Error("agentrun-harness-codex: the harness gave the machine no model route");
|
|
149
|
+
const base = normalize(options.dir);
|
|
150
|
+
if (!isAbsolute(base))
|
|
151
|
+
throw new Error("agentrun-harness-codex: the session directory must be an absolute path");
|
|
152
|
+
mkdirSync(base, { recursive: true, mode: 0o700 });
|
|
153
|
+
const dirs = Object.fromEntries(DIRS.map((d) => [d, sessionDir(base, d)]));
|
|
154
|
+
if (options.cwd !== undefined && !isAbsolute(options.cwd))
|
|
155
|
+
throw new Error("agentrun-harness-codex: the working directory must be an absolute path");
|
|
156
|
+
const root = options.cwd === undefined ? join(base, "work") : normalize(options.cwd);
|
|
157
|
+
for (const dir of [...Object.values(dirs), root])
|
|
158
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
159
|
+
// git stops at the session's directory and, for a workspace outside it, at the workspace's parent.
|
|
160
|
+
const ceiling = [base, ...(root === base || root.startsWith(base + sep) ? [] : [dirname(root)])].join(":");
|
|
161
|
+
const upload = (dir, files) => {
|
|
162
|
+
for (const file of files) {
|
|
163
|
+
const path = inside(dirs[dir], file.path);
|
|
164
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
165
|
+
writeFileSync(path, file.bytes, { mode: file.mode ?? 0o600 });
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
const seed = () => {
|
|
169
|
+
if (options.seed)
|
|
170
|
+
upload(options.seed.dir, seeded);
|
|
171
|
+
};
|
|
172
|
+
// Before the proxy starts: a seed that cannot be written is refused with nothing left running.
|
|
173
|
+
seed();
|
|
174
|
+
const key = randomBytes(32).toString("base64url");
|
|
175
|
+
const route = model.options;
|
|
176
|
+
// The code-mode `exec` the model proxy's latest answer carried: set while the answer passes, before Codex has it.
|
|
177
|
+
let announced;
|
|
178
|
+
let open = 0;
|
|
179
|
+
const rolloutListeners = [];
|
|
180
|
+
const search = options.webSearch === "live";
|
|
181
|
+
const price = options.proxy.price && search ? withWebSearches(options.proxy.price) : options.proxy.price;
|
|
182
|
+
const proxy = await startModelProxy({
|
|
183
|
+
policy: codexPolicy({
|
|
184
|
+
model: route.models.model,
|
|
185
|
+
tools: options.proxy.tools,
|
|
186
|
+
...(options.proxy.maxOutputTokens ? { maxOutputTokens: options.proxy.maxOutputTokens } : {}),
|
|
187
|
+
...(search ? { webSearch: "live" } : {}),
|
|
188
|
+
announce: {
|
|
189
|
+
// The cost is liveness, not safety: after an overlap a never call is declined until the next single answer, which the model's
|
|
190
|
+
// next wait or exec gives.
|
|
191
|
+
// A second answer that starts while one is open (a background call beside the turn) makes every tie ambiguous until both have
|
|
192
|
+
// ended: which of them carried which exec cannot be told. A failed watch, likewise, stands for an exec not seen.
|
|
193
|
+
response: () => {
|
|
194
|
+
open += 1;
|
|
195
|
+
announced = open > 1 ? UNWATCHED : undefined;
|
|
196
|
+
},
|
|
197
|
+
exec: (callId) => void (announced = open > 1 || announced === UNWATCHED ? UNWATCHED : callId),
|
|
198
|
+
failed: () => void (announced = UNWATCHED),
|
|
199
|
+
end: () => void (open = Math.max(0, open - 1)),
|
|
200
|
+
},
|
|
201
|
+
}),
|
|
202
|
+
hooks: options.proxy.hooks,
|
|
203
|
+
model: route.models.model,
|
|
204
|
+
origin: route.target,
|
|
205
|
+
credential: async () => (await route.credential()) ?? "",
|
|
206
|
+
...(price ? { price } : {}),
|
|
207
|
+
...(options.proxy.log ? { log: options.proxy.log } : {}),
|
|
208
|
+
...(options.proxy.fetch ? { fetch: options.proxy.fetch } : {}),
|
|
209
|
+
}, key);
|
|
210
|
+
const lost = new AbortController();
|
|
211
|
+
const children = new Set();
|
|
212
|
+
let closed = false;
|
|
213
|
+
const machine = {
|
|
214
|
+
sessionId: ctx.runId,
|
|
215
|
+
root,
|
|
216
|
+
dirs,
|
|
217
|
+
signal: lost.signal,
|
|
218
|
+
modelUrl: proxy.url,
|
|
219
|
+
modelKey: key,
|
|
220
|
+
announcedExec: () => announced,
|
|
221
|
+
onRolloutLine: (listener) => void rolloutListeners.push(listener),
|
|
222
|
+
...(search ? { configure: (config) => void (config.web_search = "live") } : {}),
|
|
223
|
+
notes: [],
|
|
224
|
+
spawn: async (spawnOptions) => {
|
|
225
|
+
if (closed)
|
|
226
|
+
throw new Error("agentrun-harness-codex: the session machine is closed");
|
|
227
|
+
const proc = start(spawnOptions, from, root, ceiling, options.confine, options.parentWatch);
|
|
228
|
+
children.add(proc);
|
|
229
|
+
void proc.exited.then(() => children.delete(proc));
|
|
230
|
+
return proc;
|
|
231
|
+
},
|
|
232
|
+
files: {
|
|
233
|
+
upload: async (dir, files) => upload(dir, files),
|
|
234
|
+
// Everything goes, then the seed is written again: what a drive starts with is the host's, never an earlier drive's.
|
|
235
|
+
wipe: async () => {
|
|
236
|
+
for (const dir of Object.values(dirs)) {
|
|
237
|
+
rmSync(dir, { recursive: true, force: true });
|
|
238
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
239
|
+
}
|
|
240
|
+
seed();
|
|
241
|
+
},
|
|
242
|
+
},
|
|
243
|
+
tail: async (dir, path, tailOptions = {}) => {
|
|
244
|
+
const file = inside(dirs[dir], path);
|
|
245
|
+
const tail = new FileTail(file, tailOptions.offset ?? 0);
|
|
246
|
+
return {
|
|
247
|
+
get offset() { return tail.offset; },
|
|
248
|
+
read: () => {
|
|
249
|
+
// Only the file Codex wrote: a link put in its place is not followed.
|
|
250
|
+
try {
|
|
251
|
+
if (lstatSync(file).isSymbolicLink())
|
|
252
|
+
throw new Error(`agentrun-harness-codex: ${path} is a link`);
|
|
253
|
+
}
|
|
254
|
+
catch (err) {
|
|
255
|
+
if (err.code !== "ENOENT")
|
|
256
|
+
throw err;
|
|
257
|
+
}
|
|
258
|
+
const fresh = tail.read();
|
|
259
|
+
for (const line of fresh)
|
|
260
|
+
for (const listener of rolloutListeners)
|
|
261
|
+
listener(line);
|
|
262
|
+
return fresh;
|
|
263
|
+
},
|
|
264
|
+
// A local file is read to its end on every read.
|
|
265
|
+
sync: async () => { },
|
|
266
|
+
close: () => { },
|
|
267
|
+
};
|
|
268
|
+
},
|
|
269
|
+
// A tool-less session writes no files of its own to flush.
|
|
270
|
+
fsync: async () => { },
|
|
271
|
+
close: async () => {
|
|
272
|
+
if (closed)
|
|
273
|
+
return;
|
|
274
|
+
closed = true;
|
|
275
|
+
for (const proc of children)
|
|
276
|
+
proc.kill("SIGKILL");
|
|
277
|
+
await Promise.all([...children].map((p) => p.exited));
|
|
278
|
+
lost.abort();
|
|
279
|
+
await proxy.close();
|
|
280
|
+
},
|
|
281
|
+
};
|
|
282
|
+
return brandMachine(machine);
|
|
283
|
+
};
|
|
284
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { type ModelProxyOptions, type ProviderPolicy, type ProxyRoute, type ProxyUsage } 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
|
+
/** Told, before Codex has the piece of an answer, what the answer carries: `response()` when an answer starts, and
|
|
24
|
+
* `exec(callId)` for each code-mode `exec` call it holds. The session ties a script's nested calls to the `exec` of the
|
|
25
|
+
* latest answer, which is known here before Codex can run anything of it. */
|
|
26
|
+
announce?: {
|
|
27
|
+
response(): void;
|
|
28
|
+
exec(callId: string): void;
|
|
29
|
+
failed(): void;
|
|
30
|
+
end(): void;
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** The usage a Responses answer reports at its end (`endValue`), or undefined, an unknown cost, when it reports none. */
|
|
34
|
+
export declare function usageOf(text: string): ProxyUsage | undefined;
|
|
35
|
+
/** The web searches a Responses answer ran, as its terminal event reports them (`tool_usage.web_search.num_requests`,
|
|
36
|
+
* what OpenAI bills per call), or undefined when that event's own count cannot be read: an unknown cost, never 0. */
|
|
37
|
+
export declare function webSearchesOf(text: string): number | undefined;
|
|
38
|
+
/**
|
|
39
|
+
* The input tokens the provider bills for `body` that it does not carry (`providerInputOverhead`, with its sources). The
|
|
40
|
+
* Responses API documents no prompt of its own that it adds on these routes (no hosted tool passes the policy but a
|
|
41
|
+
* session's live web search, below), and the framing it puts around each input item and tool definition is a few tokens
|
|
42
|
+
* each, fewer than the bytes of the JSON keys that item already spends in the body. An image is billed by its area, not
|
|
43
|
+
* its bytes: each adds the most it can be billed as. A file input (a PDF, billed by its pages) has no stated bound, so a
|
|
44
|
+
* body with one cannot be measured: this throws, and the request's input is unknown.
|
|
45
|
+
*/
|
|
46
|
+
export declare function responsesServerInputOverhead(body: Record<string, unknown>): number;
|
|
47
|
+
/** The tokens a request keeps for its answer when its output is limited. */
|
|
48
|
+
export declare const ANSWER_TOKENS_LEAST = 1024;
|
|
49
|
+
/** What a reasoning request at each effort is allowed for its reasoning beside its answer, when its output is limited:
|
|
50
|
+
* OpenAI's reasoning shares `max_output_tokens` and takes no budget, so a limit under its reasoning comes back
|
|
51
|
+
* incomplete with no answer. The figures are pi-ai's thinking budgets by level (xhigh at high's). */
|
|
52
|
+
export declare const REASONING_TOKENS_ALLOWED: Readonly<Record<string, number>>;
|
|
53
|
+
/** The output tokens a Responses body asks for at most: its `max_output_tokens` (as `apply` clamped it). */
|
|
54
|
+
export declare function responsesOutputAsked(body: Record<string, unknown>): number | undefined;
|
|
55
|
+
/** The least output a Responses body may be limited to and still answer: 1,024 tokens, plus its reasoning effort's
|
|
56
|
+
* allowance when it reasons. */
|
|
57
|
+
export declare function responsesOutputLeast(body: Record<string, unknown>): number;
|
|
58
|
+
/** A Responses body with its output limited to `max` tokens, reasoning included: never raised, and never longer. */
|
|
59
|
+
export declare function limitResponsesOutput(body: Record<string, unknown>, max: number): Record<string, unknown>;
|
|
60
|
+
export declare function codexPolicy(options: CodexPolicyOptions): ProviderPolicy;
|