@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.
@@ -0,0 +1,204 @@
1
+ import { boundResult, openTurn, recoveryNote, recoverySystemNote, recoveryUserTurn, toolKey, transcriptOf } from "./host/process.js";
2
+ // cycle with harness.ts: read repairOutput only inside functions, never at module top level (pinned by "code mode and the harness
3
+ // load in either order and the repair reads repairOutput"). A host loads harness.js first, so at that point none of its const bindings is set.
4
+ import { repairOutput } from "./harness.js";
5
+ import { summarizeRollout } from "./rollout.js";
6
+ import { callKey, completedNested, execRecoveryOutput, NESTED_CALL, outputTextOf, recoveryFacts, Scripts, settle, UNWATCHED } from "./scripts.js";
7
+ /** The stream that ties each nested call to the `exec` it ran under: `{ callId, exec, since }` (`since`: the turn it ran in), written before the call runs. */
8
+ export const NESTED_STREAM = "codex.nested";
9
+ /** The stream that records the interrupted turns whose recovery note was injected: `{ since }`, once per interrupted turn. */
10
+ export const RECOVERY_NOTE_STREAM = "codex.recovery-note";
11
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
12
+ /** Only a custom tool call named `exec` is code mode's: a host tool that happens to be called `exec` is a function call. */
13
+ const isExec = (d) => d.type === "custom_tool_call" && d.name === "exec";
14
+ /** The item that answers a dangling call that is not an `exec`: of the kind the call asks for (the Responses API refuses an output of the
15
+ * wrong kind), a custom tool call output for a custom tool call such as `apply_patch`, a function call output for any other. */
16
+ export function withOutputKind(item, call) {
17
+ return { ...item, type: call.type === "custom_tool_call" ? "custom_tool_call_output" : "function_call_output" };
18
+ }
19
+ /** Where the turn that ended last began, as `openTurn` gave it while that turn was open: the end before its own (a `turn` entry, or a turn the
20
+ * harness could not run), or -1. With no open turn, the calls whose script could not be told that ran in it are tied to this. */
21
+ function endedTurnSince(state) {
22
+ const ends = [...transcriptOf(state).filter((r) => r.data?.type === "turn").map((r) => r.at), ...state.effectOrder.flatMap((e, i) => (e.name === "unavailable" ? [i] : []))];
23
+ ends.sort((a, b) => a - b);
24
+ return ends.length >= 2 ? ends[ends.length - 2] : -1;
25
+ }
26
+ /** What a dangling `wait` of code mode is told: it had started, on the cell named, when the session stopped and took the cell's script with it. */
27
+ export const waitStoppedText = (cell) => `The session stopped while waiting on cell ${cell}; that cell's script was cut off, and nothing was run again. Check the actual state before relying on it.`;
28
+ /** What the log holds of one nested call: the session's record, the rollout's completion line, and what the turn's recovery note
29
+ * calls it (`told`, by call id). */
30
+ function factOf(state, rolled, tie, told = new Map()) {
31
+ const e = state.effects.get(toolKey(tie.callId));
32
+ const status = told.get(tie.callId);
33
+ return {
34
+ callId: tie.callId,
35
+ tool: e ? e.name.replace(/^tool\./, "") : (rolled.get(tie.callId)?.tool ?? "a tool"),
36
+ ...(e ? { store: { status: e.status === "completed" ? "completed" : e.status === "failed" ? "failed" : "started", text: e.status === "failed" ? (e.error?.message ?? "") : outputTextOf(e.output), ...(e.error?.interrupted ? { interrupted: true } : {}) } } : {}),
37
+ ...(rolled.has(tie.callId) ? { rollout: rolled.get(tie.callId) } : {}),
38
+ ...(status ? { told: status } : {}),
39
+ };
40
+ }
41
+ export function codeMode(deps) {
42
+ const { ctx, machine, journal, logged, synced } = deps;
43
+ const scripts = new Scripts();
44
+ /** The exec each nested call was admitted under. */
45
+ const execOf = new Map();
46
+ /** After a recovery: the `never` calls the log holds a completed outcome for, by tool and arguments, until the turn ends. Each answers one re-issue. */
47
+ const recovered = new Map();
48
+ for (const line of deps.lines)
49
+ scripts.note(line);
50
+ machine.onRolloutLine?.((line) => scripts.note(line));
51
+ /** The script a nested call is tied to now, as the log and the proxy's latest answer have it. */
52
+ const tieNow = () => scripts.tie(machine.announcedExec?.(), (id) => logged.has(id));
53
+ /** A `never` nested call: wait for its script's line, as the harness's barrier waits for a call's own. True: admitted. */
54
+ const admit = async (callId) => {
55
+ for (let i = 0;; i++) {
56
+ await synced();
57
+ const tie = tieNow();
58
+ if (tie.kind === "ambiguous") {
59
+ deps.log("codex: declined a nested call while two scripts are live", { callId, live: tie.live });
60
+ return false;
61
+ }
62
+ if (tie.kind === "tied") {
63
+ execOf.set(callId, tie.exec);
64
+ logged.add(callId);
65
+ await journal.flush();
66
+ return true;
67
+ }
68
+ if (i + 1 >= deps.tries)
69
+ break;
70
+ await sleep(50 * 2 ** i);
71
+ }
72
+ deps.log("codex: declined a call whose function_call line is not in the log", { callId });
73
+ return false;
74
+ };
75
+ /** After a recovery: every `never` call of the interrupted turn the log holds a completed outcome for (the session's record or, when it
76
+ * lost the end, the rollout's: Codex writes that line only after our tool answered, so the effect happened), each answering one
77
+ * re-issue. Read from the turn's tie records, not from the outputs a recovery repairs: a turn recovered once already has its exec
78
+ * answered, and a script that yielded has its exec answered by the running-cell output, yet their calls ran. */
79
+ const arm = async (since) => {
80
+ recovered.clear();
81
+ const state = ctx.state();
82
+ const rolled = completedNested(deps.lines);
83
+ for (const tie of (await journal.read(NESTED_STREAM)).map((r) => r.data)) {
84
+ if (tie.since !== since)
85
+ continue;
86
+ const e = state.effects.get(toolKey(tie.callId));
87
+ if (e?.replay !== "never")
88
+ continue;
89
+ const fact = factOf(state, rolled, tie);
90
+ const settled = settle(fact);
91
+ if (settled.kind !== "completed")
92
+ continue;
93
+ const key = callKey(fact.tool, e.input);
94
+ recovered.set(key, [...(recovered.get(key) ?? []), { tool: fact.tool, text: settled.text }]);
95
+ }
96
+ };
97
+ /** The cell a dangling call waited on, when it is code mode's `wait` (a function call named `wait` with a `cell_id`, and no host tool of
98
+ * that name); otherwise `undefined`. */
99
+ const waitedCell = (c) => {
100
+ if (c.type !== "function_call" || c.name !== "wait" || deps.bridge.get("wait"))
101
+ return undefined;
102
+ try {
103
+ const cell = JSON.parse(c.arguments ?? "").cell_id;
104
+ return typeof cell === "string" || typeof cell === "number" ? String(cell) : undefined;
105
+ }
106
+ catch {
107
+ return undefined;
108
+ }
109
+ };
110
+ const declined = { contentItems: [{ type: "inputText", text: deps.declined }], success: false };
111
+ return {
112
+ /** The app-server's request handler, with a code-mode host tool call handled before the harness's own. */
113
+ request(next) {
114
+ return async (req) => {
115
+ if (req.method === "item/tool/call") {
116
+ const p = req.params ?? {};
117
+ const callId = String(p.callId ?? "");
118
+ const tool = deps.bridge.get(String(p.tool));
119
+ // After a recovery, a `never` call the log already holds a completed outcome for, called again (a script that was cut short and
120
+ // written again re-issues every call it made): answered from the log, run no more.
121
+ const again = tool?.replay === "never" ? recovered.get(callKey(tool.name, p.arguments))?.shift() : undefined;
122
+ if (again) {
123
+ deps.log("codex: answered a never call from the log: it completed before the interruption", { callId, tool: again.tool });
124
+ // Held to the host's bound as the bridge holds a call's result (`boundResult`): the log keeps the result whole.
125
+ return { contentItems: [{ type: "inputText", text: boundResult(`Recorded earlier in this turn, not run again: ${again.text}`).text }], success: true };
126
+ }
127
+ if (NESTED_CALL.test(callId)) {
128
+ if (tool?.replay === "never" && !ctx.isMemoized(toolKey(callId)) && !(await admit(callId)))
129
+ return declined;
130
+ const tie = tieNow();
131
+ const exec = execOf.get(callId) ?? (tie.kind === "tied" || tie.kind === "held" ? tie.exec : undefined);
132
+ if (exec)
133
+ execOf.set(callId, exec);
134
+ // Never the unwatched-answer marker: a call tied to no known exec is journaled with none.
135
+ journal.append(NESTED_STREAM, { callId, exec: exec === undefined || exec === UNWATCHED ? null : exec, since: openTurn(ctx.state())?.since ?? -1 });
136
+ }
137
+ }
138
+ return next(req);
139
+ };
140
+ },
141
+ /** The outputs injected for the calls the rollout left dangling: a cut-off `exec` gets a custom tool call output from the log, in place of `items`';
142
+ * any other call keeps its generic output, as an item of its own kind, and code mode's `wait` is told that it had started. `since`: the
143
+ * turn the dangling calls ran in: the interrupted one a recovery note resumes, or with none, the turn that ended last. Every output is then
144
+ * held to the host's bound as the tool bridge holds a call's result (`boundResult`): these come from the log, not through the bridge, and
145
+ * both repairs (with a recovery note and without) inject what this leaves. */
146
+ async recoverItems(items, dangling, lines, since) {
147
+ const state = ctx.state();
148
+ const ties = (await journal.read(NESTED_STREAM)).map((r) => r.data);
149
+ const execs = dangling.filter(isExec).map((d) => d.callId);
150
+ const rolled = completedNested(lines);
151
+ // Each cut-off exec lists its own calls. A call whose script could not be told when it ran (an answer the proxy did not see to its end)
152
+ // is listed once, apart, in the LAST cut-off exec's output, if it ran in this interrupted turn.
153
+ const told = new Map((recoveryNote(state)?.calls ?? []).map((c) => [c.callId, c.status]));
154
+ const listed = recoveryFacts(execs, ties, since, (tie) => factOf(state, rolled, tie, told));
155
+ dangling.forEach((c, i) => {
156
+ if (!isExec(c)) {
157
+ // Code mode's `wait` on a cell had started: the generic answer, that the call never started, would be false.
158
+ const cell = waitedCell(c);
159
+ const item = items[i];
160
+ items[i] = withOutputKind(cell === undefined ? item : { ...item, output: waitStoppedText(cell) }, c);
161
+ return;
162
+ }
163
+ const { own, loose } = listed.get(c.callId);
164
+ items[i] = { type: "custom_tool_call_output", call_id: c.callId, output: execRecoveryOutput(own, loose) };
165
+ });
166
+ for (const item of items)
167
+ if (typeof item.output === "string")
168
+ item.output = boundResult(item.output).text;
169
+ },
170
+ /** With no recovery note, the calls the rollout has no output for get theirs from the log before any turn is sent: a turn that ended without
171
+ * them (one interrupted mid-call, or settled instead of resumed) left them dangling, and the provider refuses a history with a call unanswered.
172
+ * Nothing is armed here: a new turn that calls a `never` call the ended turn completed runs it. */
173
+ async repairUnnoted(lines) {
174
+ const dangling = summarizeRollout(lines).dangling;
175
+ if (dangling.length === 0)
176
+ return;
177
+ const items = dangling.map((c) => ({ type: "function_call_output", call_id: c.callId, output: repairOutput(ctx.state(), c) }));
178
+ // A cut-off exec of the ended turn still lists the calls of that turn whose script could not be told: they ran.
179
+ await this.recoverItems(items, dangling, lines, endedTurnSince(ctx.state()));
180
+ await deps.guard(deps.rpc().request("thread/inject_items", { threadId: deps.threadId(), items }));
181
+ await deps.guard(synced());
182
+ },
183
+ /** The user's turn that resumes an interrupted one: only the user's own words, or a bare nudge. The harness's note about the turn goes to
184
+ * the model as a developer message, injected once for this interrupted turn (every turn opens with `thread/resume`, so injecting on each
185
+ * would repeat it). With no statuses-only note to give, nothing is injected: the full note carries tool outputs and goes in no slot of the model's. */
186
+ async resumeTurn(note, owed) {
187
+ await arm(note.turn.since);
188
+ const system = recoverySystemNote(ctx.state());
189
+ const noted = (await journal.read(RECOVERY_NOTE_STREAM)).some((r) => r.data.since === note.turn.since);
190
+ if (system !== undefined && !noted) {
191
+ await deps.guard(deps.rpc().request("thread/inject_items", { threadId: deps.threadId(), items: [{ type: "message", role: "developer", content: [{ type: "input_text", text: system }] }] }));
192
+ // The injected item is in the log before it is recorded as injected: a record without it would leave the note out of every later resume.
193
+ await deps.guard(synced());
194
+ journal.append(RECOVERY_NOTE_STREAM, { since: note.turn.since });
195
+ await deps.guard(journal.flush());
196
+ }
197
+ return recoveryUserTurn(owed.map((s) => s.text ?? ""), note.pending.map((s) => s.text ?? ""));
198
+ },
199
+ /** A turn ended: the calls answered from the log were for it alone. */
200
+ turnEnded() {
201
+ recovered.clear();
202
+ },
203
+ };
204
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The `config.toml` a session's `CODEX_HOME` gets: the model and its
3
+ * provider (the session's model proxy), and Codex's built-in tools and side
4
+ * features turned off.
5
+ */
6
+ export type TomlValue = string | number | boolean | TomlValue[] | {
7
+ [key: string]: TomlValue;
8
+ };
9
+ /**
10
+ * Codex features turned off (`codex features list`). With these off, a
11
+ * classic model is offered only the harness's dynamic tools and
12
+ * `request_user_input` (which Codex itself answers "unavailable in Default
13
+ * mode"): no shell, no `apply_patch`, no images, no web, no sub-agents. A
14
+ * code-mode model (luna) is offered code mode's `exec` and `wait`; see
15
+ * `code_mode_host`. The rest are side features that would download plugins,
16
+ * call chatgpt.com or start a daemon.
17
+ */
18
+ export declare const BUILTINS_OFF: Record<string, boolean>;
19
+ /**
20
+ * The features on top of `BUILTINS_OFF` with the built-ins on: the shell
21
+ * (unified exec: `exec_command`, `write_stdin`; `apply_patch` runs through
22
+ * it) and `view_image`. Sub-agents, goals, images, the browser and plugins
23
+ * stay off: their state is not in the rollout, or they reach outside.
24
+ */
25
+ export declare const BUILTINS_ON: Record<string, boolean>;
26
+ export interface CodexConfigOptions {
27
+ model: string;
28
+ /** The Responses API base URL (`…/v1`): the VM's model port, relayed to the driver's gateway handler. */
29
+ baseUrl: string;
30
+ /** The env var holding the provider key (a placeholder: the driver adds the credential). */
31
+ envKey: string;
32
+ /** Gateway model ids are unknown to Codex, so its context window must be given. */
33
+ contextWindow: number;
34
+ /**
35
+ * The thread's working directory (`/workspace`): marked untrusted, so a
36
+ * project config the model plants there (`.codex/config.toml`, a trust
37
+ * entry) is never loaded.
38
+ */
39
+ cwd?: string;
40
+ /**
41
+ * `sandbox({ env })`: set for the model's commands too
42
+ * (`shell_environment_policy.set`; `inherit = "core"` passes them nothing
43
+ * else), less any name the policy excludes.
44
+ */
45
+ commandEnv?: Readonly<Record<string, string>>;
46
+ /** Merged over the generated config, last. */
47
+ extra?: Record<string, TomlValue>;
48
+ }
49
+ /**
50
+ * What a command Codex runs inherits: the core variables only (`HOME`,
51
+ * `LOGNAME`, `PATH`, `SHELL`, `USER`, `USERNAME`, `TMPDIR`, `TEMP`, `TMP`),
52
+ * plus `sandbox({ env })` (`set`, `codexConfig`), and never one named like
53
+ * the harness's own (`HARNESS_*`, the provider key's placeholder among them)
54
+ * or a token. Codex 0.160 otherwise passes its whole environment on
55
+ * (docs/workspaces.md §5.6).
56
+ */
57
+ export declare const SHELL_ENVIRONMENT_POLICY: Readonly<{
58
+ inherit: 'core';
59
+ exclude: readonly string[];
60
+ }>;
61
+ /** Whether `name` matches one of the policy's `exclude` patterns (`*` globs, case-insensitive, as Codex matches them). */
62
+ export declare function excludedName(name: string): boolean;
63
+ export declare function codexConfig(options: CodexConfigOptions): Record<string, TomlValue>;
64
+ /**
65
+ * `config` keys the harness sets itself and an app may not (docs/workspaces.md
66
+ * §3.3): the sandbox and approvals (which bwrap and the log's barrier rest
67
+ * on), the commands' environment, the provider and its key (the model port),
68
+ * trust and project config, MCP servers and notifications (they reach outside
69
+ * the log), the features (the built-ins' switch: `builtins`), web search, and
70
+ * the model (`model`). Also what would swap the binary or shell that does the
71
+ * sandboxing, send traffic outside the log (`otel`, `chatgpt_base_url`), grant
72
+ * permission profiles, keep history or snapshots outside the rollout, or read
73
+ * a file the app names (`RESERVED_CONFIG_SUFFIXES`).
74
+ */
75
+ export declare const RESERVED_CONFIG_KEYS: readonly string[];
76
+ /** Key suffixes reserved at any depth: a binary, a file or a directory Codex would use (`codex_linux_sandbox_exe`, `zsh_path`, `model_instructions_file`, `experimental_compact_prompt_file`, `sqlite_home`, `log_dir`, ...). */
77
+ export declare const RESERVED_CONFIG_SUFFIXES: readonly string[];
78
+ /** Throw a `TypeError` naming the first key of `config` the harness reserves (a dotted key is a nested table's: `tools.web_search`). */
79
+ export declare function checkConfig(config: Record<string, TomlValue> | undefined): void;
80
+ /** TOML text for a config object: plain values first, then one `[table]` per nested object. */
81
+ export declare function toToml(config: Record<string, TomlValue>, prefix?: string[]): string;
package/dist/config.js ADDED
@@ -0,0 +1,208 @@
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/config.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
3
+ // Changed by Parcha, patches: 001-code-mode-host, 004-names, 006-comments, 013-agents-off
4
+ /**
5
+ * The `config.toml` a session's `CODEX_HOME` gets: the model and its
6
+ * provider (the session's model proxy), and Codex's built-in tools and side
7
+ * features turned off.
8
+ */
9
+ /**
10
+ * Codex features turned off (`codex features list`). With these off, a
11
+ * classic model is offered only the harness's dynamic tools and
12
+ * `request_user_input` (which Codex itself answers "unavailable in Default
13
+ * mode"): no shell, no `apply_patch`, no images, no web, no sub-agents. A
14
+ * code-mode model (luna) is offered code mode's `exec` and `wait`; see
15
+ * `code_mode_host`. The rest are side features that would download plugins,
16
+ * call chatgpt.com or start a daemon.
17
+ */
18
+ export const BUILTINS_OFF = {
19
+ shell_tool: false,
20
+ unified_exec: false,
21
+ view_image: false,
22
+ image_generation: false,
23
+ multi_agent: false,
24
+ goals: false,
25
+ sleep_tool: false,
26
+ browser_use: false,
27
+ browser_use_external: false,
28
+ computer_use: false,
29
+ in_app_browser: false,
30
+ // Code mode's JavaScript runtime (no Node, no file system, no network): the only way a code-mode model such as luna
31
+ // calls a tool. Its nested tools are the dynamic tools plus Codex's own apply_patch and MCP resource readers, which
32
+ // run nothing here (read-only, approvals declined, no MCP server); its sub-agent tools are removed by agents.enabled.
33
+ code_mode_host: true,
34
+ tool_suggest: false,
35
+ skill_search: false,
36
+ skill_mcp_dependency_install: false,
37
+ tool_call_mcp_elicitation: false,
38
+ realtime_conversation: false,
39
+ workspace_dependencies: false,
40
+ worktrees: false,
41
+ hooks: false,
42
+ plugins: false,
43
+ remote_plugin: false,
44
+ apps: false,
45
+ shell_snapshot: false,
46
+ daemon_auto_start: false,
47
+ // A shell or sub-command path Codex would approve per sub-command (an `approvalId` the drive declines), and the git undo snapshots app-server took itself (outside bwrap): off, though 0.160 has these off or removed already.
48
+ shell_zsh_fork: false,
49
+ unified_exec_zsh_fork: false,
50
+ undo: false,
51
+ };
52
+ /**
53
+ * The features on top of `BUILTINS_OFF` with the built-ins on: the shell
54
+ * (unified exec: `exec_command`, `write_stdin`; `apply_patch` runs through
55
+ * it) and `view_image`. Sub-agents, goals, images, the browser and plugins
56
+ * stay off: their state is not in the rollout, or they reach outside.
57
+ */
58
+ export const BUILTINS_ON = {
59
+ ...BUILTINS_OFF,
60
+ shell_tool: true,
61
+ unified_exec: true,
62
+ view_image: true,
63
+ };
64
+ /**
65
+ * What a command Codex runs inherits: the core variables only (`HOME`,
66
+ * `LOGNAME`, `PATH`, `SHELL`, `USER`, `USERNAME`, `TMPDIR`, `TEMP`, `TMP`),
67
+ * plus `sandbox({ env })` (`set`, `codexConfig`), and never one named like
68
+ * the harness's own (`HARNESS_*`, the provider key's placeholder among them)
69
+ * or a token. Codex 0.160 otherwise passes its whole environment on
70
+ * (docs/workspaces.md §5.6).
71
+ */
72
+ export const SHELL_ENVIRONMENT_POLICY = Object.freeze({ inherit: 'core', exclude: Object.freeze(['HARNESS_*', '*TOKEN*']) });
73
+ /** Whether `name` matches one of the policy's `exclude` patterns (`*` globs, case-insensitive, as Codex matches them). */
74
+ export function excludedName(name) {
75
+ return SHELL_ENVIRONMENT_POLICY.exclude.some((p) => new RegExp(`^${p.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replaceAll('*', '.*')}$`, 'i').test(name));
76
+ }
77
+ export function codexConfig(options) {
78
+ const commandEnv = options.commandEnv ? Object.fromEntries(Object.entries(options.commandEnv).filter(([k]) => !excludedName(k))) : undefined;
79
+ const base = {
80
+ model: options.model,
81
+ model_provider: 'gateway',
82
+ model_context_window: options.contextWindow,
83
+ sandbox_mode: 'read-only',
84
+ web_search: 'disabled',
85
+ check_for_update_on_startup: false,
86
+ shell_environment_policy: {
87
+ inherit: SHELL_ENVIRONMENT_POLICY.inherit,
88
+ exclude: [...SHELL_ENVIRONMENT_POLICY.exclude],
89
+ ...(commandEnv && Object.keys(commandEnv).length ? { set: commandEnv } : {}),
90
+ },
91
+ model_providers: {
92
+ gateway: {
93
+ name: 'AgentRun model proxy',
94
+ base_url: options.baseUrl,
95
+ env_key: options.envKey,
96
+ wire_api: 'responses',
97
+ supports_websockets: false,
98
+ },
99
+ },
100
+ ...(options.cwd ? { projects: { [options.cwd]: { trust_level: 'untrusted' } } } : {}),
101
+ features: { ...BUILTINS_OFF },
102
+ analytics: { enabled: false },
103
+ // No sub-agents. `multi_agent = false` turns off only V1, and a model Codex's catalog marks V2 (luna, sol) still gets V2's
104
+ // collaboration tools and a developer message saying it can spawn sub-agents: `enabled = false` turns off both.
105
+ agents: { enabled: false, max_depth: 0 },
106
+ };
107
+ return merge(base, options.extra ?? {});
108
+ }
109
+ /**
110
+ * `config` keys the harness sets itself and an app may not (docs/workspaces.md
111
+ * §3.3): the sandbox and approvals (which bwrap and the log's barrier rest
112
+ * on), the commands' environment, the provider and its key (the model port),
113
+ * trust and project config, MCP servers and notifications (they reach outside
114
+ * the log), the features (the built-ins' switch: `builtins`), web search, and
115
+ * the model (`model`). Also what would swap the binary or shell that does the
116
+ * sandboxing, send traffic outside the log (`otel`, `chatgpt_base_url`), grant
117
+ * permission profiles, keep history or snapshots outside the rollout, or read
118
+ * a file the app names (`RESERVED_CONFIG_SUFFIXES`).
119
+ */
120
+ export const RESERVED_CONFIG_KEYS = Object.freeze([
121
+ 'model',
122
+ 'model_provider',
123
+ 'model_providers',
124
+ 'base_url',
125
+ 'env_key',
126
+ 'sandbox_mode',
127
+ 'sandbox_workspace_write',
128
+ 'approval_policy',
129
+ 'shell_environment_policy',
130
+ 'projects',
131
+ 'profile',
132
+ 'profiles',
133
+ 'mcp_servers',
134
+ 'notify',
135
+ 'features',
136
+ 'web_search',
137
+ 'tools.web_search',
138
+ 'default_permissions',
139
+ 'permissions',
140
+ 'ghost_snapshot',
141
+ 'otel',
142
+ 'chatgpt_base_url',
143
+ 'history',
144
+ 'project_root_markers',
145
+ 'allow_symlinked_codex_home',
146
+ 'agents',
147
+ ]);
148
+ /** Key suffixes reserved at any depth: a binary, a file or a directory Codex would use (`codex_linux_sandbox_exe`, `zsh_path`, `model_instructions_file`, `experimental_compact_prompt_file`, `sqlite_home`, `log_dir`, ...). */
149
+ export const RESERVED_CONFIG_SUFFIXES = Object.freeze(['_exe', '_path', '_file', '_home', '_dir']);
150
+ /** Throw a `TypeError` naming the first key of `config` the harness reserves (a dotted key is a nested table's: `tools.web_search`). */
151
+ export function checkConfig(config) {
152
+ if (config === undefined)
153
+ return;
154
+ if (!isTable(config))
155
+ throw new TypeError('agentrun-harness-codex: config must be an object of config.toml settings');
156
+ const check = (table, prefix) => {
157
+ for (const [k, v] of Object.entries(table)) {
158
+ const path = `${prefix}${k}`;
159
+ // A dotted key in one string (`"tools.web_search"`) is the same setting as the nested one.
160
+ const last = path.slice(path.lastIndexOf('.') + 1);
161
+ if (RESERVED_CONFIG_KEYS.includes(path) || RESERVED_CONFIG_KEYS.some((r) => path.startsWith(`${r}.`)) || RESERVED_CONFIG_SUFFIXES.some((x) => last.endsWith(x))) {
162
+ throw new TypeError(`agentrun-harness-codex: config.${path} is set by the harness (docs/workspaces.md §3.3: ${RESERVED_CONFIG_KEYS.join(', ')} and any key ending ${RESERVED_CONFIG_SUFFIXES.join(', ')} are reserved)`);
163
+ }
164
+ if (isTable(v))
165
+ check(v, `${path}.`);
166
+ }
167
+ };
168
+ check(config, '');
169
+ }
170
+ function merge(a, b) {
171
+ const out = { ...a };
172
+ for (const [k, v] of Object.entries(b)) {
173
+ const prev = out[k];
174
+ out[k] = isTable(prev) && isTable(v) ? merge(prev, v) : v;
175
+ }
176
+ return out;
177
+ }
178
+ const isTable = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
179
+ /** TOML text for a config object: plain values first, then one `[table]` per nested object. */
180
+ export function toToml(config, prefix = []) {
181
+ const plain = [];
182
+ const tables = [];
183
+ for (const [k, v] of Object.entries(config)) {
184
+ if (isTable(v))
185
+ tables.push(toToml(v, [...prefix, k]));
186
+ else
187
+ plain.push(`${key(k)} = ${value(v)}`);
188
+ }
189
+ const head = prefix.length && plain.length ? `[${prefix.map(key).join('.')}]\n` : '';
190
+ return [plain.length ? `${head}${plain.join('\n')}\n` : '', ...tables].filter(Boolean).join('\n');
191
+ }
192
+ const key = (k) => (/^[A-Za-z0-9_-]+$/.test(k) ? k : JSON.stringify(k));
193
+ function value(v) {
194
+ if (typeof v === 'string')
195
+ return JSON.stringify(v);
196
+ if (typeof v === 'number') {
197
+ if (!Number.isFinite(v))
198
+ throw new TypeError(`agentrun-harness-codex: not a TOML number: ${v}`);
199
+ return String(v);
200
+ }
201
+ if (typeof v === 'boolean')
202
+ return String(v);
203
+ if (Array.isArray(v))
204
+ return `[${v.map(value).join(', ')}]`;
205
+ return `{ ${Object.entries(v)
206
+ .map(([k, x]) => `${key(k)} = ${value(x)}`)
207
+ .join(', ')} }`;
208
+ }