@parcha/agentrun-harness-codex 0.1.0-beta.37 → 0.1.0-beta.38
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 +27 -0
- package/README.md +3 -5
- package/dist/adapter.d.ts +7 -0
- package/dist/adapter.js +33 -17
- package/dist/code-mode.d.ts +11 -2
- package/dist/code-mode.js +49 -36
- package/dist/facts.js +4 -4
- package/dist/harness.js +1 -1
- package/dist/host/machine.d.ts +0 -4
- package/dist/host/machine.js +1 -11
- package/dist/host/policy.d.ts +0 -12
- package/dist/host/policy.js +18 -52
- package/dist/host/process.d.ts +0 -10
- package/dist/scripts.d.ts +11 -0
- package/dist/scripts.js +13 -0
- package/package.json +3 -3
- package/dist/mcp.d.ts +0 -15
- package/dist/mcp.js +0 -74
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,33 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## 0.1.0-beta.38 (2026-11-14)
|
|
6
|
+
|
|
7
|
+
- A run's MCP tools are host tools on every harness: each call passes the run's one tool gate before anything is sent, and the runner calls the server with the credential, books the call and records it, as it does any host tool. opencode now runs MCP tools (`features.mcp_client.harnesses` lists it, and an opencode agent granted `mcp:<server>/<tool>` saves and runs). claude-agent offers a granted tool as `mcp__hands__mcp__<server>__<tool>` and codex as `mcp_<server>__<tool>` (Codex refuses a dynamic tool named `mcp__*`); the Timeline, tool settings and approvals still name it `mcp:<server>/<tool>`. A call set to ask on claude-agent, codex or opencode holds the CLI's call while the run waits (no "waits for a person's approval" result row while it is parked); on the person's allow the resumed session gets the call's own result, no `[tool approval]` message. A codex run no longer fails at its start when a granted server can't be reached: the server's error shows at the first call, as on pi. On a code-mode Codex model, a script's tool call held for a person's approval runs once on their allow, under its own call id, and the script's cut-off `exec` reads its result (or, when the `exec` had yielded, the model's `wait` on its cell); before, the resume told the model the call may have run, and the call the model made again asked again, so the allow never reached a call.
|
|
8
|
+
|
|
9
|
+
Who breaks: a run parked on an MCP call at the MCP door before this version does not resume its call: cancel it and start it again. A Codex thread started before this version loses its MCP tools when it resumes (Codex resumes a thread with the dynamic tools it started with): start a new run. Code built on the kernel's MCP door breaks too. Removed: `SessionSpec.mcp`, `SessionMcp`, `McpClient`, `AdapterCapabilities` and `AgentAdapter.capabilities()`, `AdapterFacts.mcp`, `ModelProxyOptions.mcp`, `mcpRoute`, `McpHandler` and `McpRouteOptions` (`@parcha/agentrun-kernel/host`), and `McpCallResult.parked`. Hand a session its MCP tools as host tools in `SessionSpec.tools` instead.
|
|
10
|
+
- A provider-native web search's fee is one constant, `NATIVE_SEARCH_USD` ($0.01, $10 per 1,000), instead of three copies. The price does not change.
|
|
11
|
+
- Kernel: `@parcha/agentrun-kernel/host` exports `NATIVE_SEARCH_USD`. The Claude and Codex proxy policies and the runner's hosted search all read it.
|
|
12
|
+
- `@parcha/agentrun-harness-claude` no longer exports `CLAUDE_WEB_SEARCH_USD`; read `NATIVE_SEARCH_USD` from `@parcha/agentrun-kernel/host`.
|
|
13
|
+
- Every harness (pi, Claude Code, OpenCode and Codex) now offers three host tools over the run's own tools: `tools_search`, `tools_call` and `codemode`. Codex gets the first two and keeps its own code mode. With MCP servers on a Claude Code run, the CLI's own tool search is on.
|
|
14
|
+
- `tools_search {query, limit?}` ranks the run's tools by what they do (BM25 over each tool's description and argument words) and answers each match's name, description and input schema. It lists only tools the run may call: never one set to deny, and never the three tools themselves.
|
|
15
|
+
- `tools_call {name, args}` calls one of the run's tools by name. The call is asked about, recorded and booked as that tool's own call, under `<callId>/call`. An ask parks the run, and once approved the call runs once. A deny refuses it in the gate's words. A call of an unknown name, of `tools_call` itself, of `tools_search` or of `codemode` is refused in words, and nothing runs.
|
|
16
|
+
- `codemode {script}` runs a JavaScript script in a QuickJS sandbox. Its `await tools.<name>(args)` calls are each the run's own call, gated, recorded and booked under `<callId>/s<n>`. The sandbox has the tools and nothing else of the run: no environment, keys, files, network or timers.
|
|
17
|
+
- A call inside a script that needs approval follows Codex's rule. The run parks. Once a person answers, the script runs again: recorded calls answer from their records, the parked call runs once (or is refused), its outcome is the script's answer, and the rest of the script does not run.
|
|
18
|
+
- A call made through `tools_call` or a script answers what a direct call answers: its text and images to the model, and in a script its value (a tool's structured result, else its text). On pi the harness's own tools (an extension's, the browser's) are found and called the same way as the host's.
|
|
19
|
+
- A refused call inside a script ends the script with the refusal's words.
|
|
20
|
+
- After a crash, a call that was cut off is told as possibly done, and it is not run again.
|
|
21
|
+
- A paid call made through `tools_call` or a script books exactly as a direct call does: held before it is sent, under the cap, and settled once. The cap's wrap-up still refuses the model's own next call.
|
|
22
|
+
- The three tools' definitions ride on every model request: about 2,000 bytes, 639 tokens on Sonnet. So the smallest caps the README measures rise. A pi desktop run on Sonnet through a gateway now needs $0.07 for its first request and $0.13 for five steps in `strict` mode, or $0.07 in `expected` mode (it was $0.06, $0.12 and $0.06). Straight to Anthropic, it needs $0.04 for its first request, and five steps still need $0.09 in `strict` mode and $0.06 in `expected` mode.
|
|
23
|
+
- Claude Code: with an MCP server's tools on the run, the CLI runs with `ENABLE_TOOL_SEARCH=true` and its ToolSearch. The run's MCP tools reach the model through `hands` only once ToolSearch finds them, and every other tool of the session loads as before. The session's proxy admits the tool search's beta (`advanced-tool-use-2025-11-20`), ToolSearch and its placeholder. It also admits a `tool_reference` block, inside a tool result only, that names one of the session's own tools. Without MCP tools, all of these stay refused.
|
|
24
|
+
- A server started by `agentrun-serve` (and so by `npx agentrun`) can start a worker thread from a file. The launcher no longer passes Node `--input-type`, which a worker inherits and Node refuses. Before this, a `codemode` script there failed with "--input-type can only be used with string input via --eval, --print, or STDIN", and so did pi's code mode on a desktop or a phone.
|
|
25
|
+
- A capped Codex, OpenCode or pi (on OpenAI's Responses) run's next-step estimate is closer to its real input, so it pauses for a raise later and less often: the input bound counts the text the model reads (a tool's output, a message, a call's arguments) at its own bytes instead of its JSON-escaped ones, some 4 to 6% less on a code-mode body full of fetched pages, which keeps more requests under the 272k-token long-context tier where every rate doubles. On a route straight to OpenAI the input is counted exactly by OpenAI's `POST /v1/responses/input_tokens`, asked with only the credential and account headers and never through a gateway; a count that fails or takes over 3 seconds leaves the byte bound. The cap still never spends past itself: tool definitions and encrypted reasoning keep every byte.
|
|
26
|
+
- A long answer through an OpenAI Responses gateway that writes its JSON with spaces is priced, a request that answered while its runner's claim was lost is booked at its cost when the run resumes, and a run whose spend is unknown never reads as a full cap to its learning.
|
|
27
|
+
- Before, the model proxy read a long answer's usage (its terminal event longer than the 64 KiB it keeps) only when the gateway wrote `"usage":{` with no space. A Python gateway (LiteLLM's `json.dumps`) writes `"usage": {`, so such a request was booked at an unknown cost though the harness counted its tokens: the run's cost read unknown with nothing unmetered. pi on the gateway, Codex and OpenCode read the usage the same way and are all fixed. Kernel: `lastObjectOf(text, key)` reads the last `"<key>": {...}` object of a cut answer, whatever its spacing.
|
|
28
|
+
- Before, a runner that lost a run's claim (its lease lapsed while the box stalled) and took the run again in the same process booked a request that had answered meanwhile as cut, at an unknown cost: the lost claim's write of its cost was refused, so the resumed run read the request unanswered. The run's cost read unknown though the request reported its usage on a priced model. Kernel: `SessionWriter.scope` names a session across claims in one process (serve's `journalSessions` sets the run's id beside the key); a booking whose cost write is refused hands it to the next booking of the same scope, whose `bookCut` waits (at most 10 s) for one still in flight and writes it as it would have been written. A request with no price stays unpriced and counts for the cap at its hold. A process that died hands nothing on: its requests are booked cut, as before. A workflow run's model booking now takes them too: its claim books an earlier claim's requests before the workflow resumes, where before it never did, so a workflow's request that answered under a lost claim stayed counted at its hold.
|
|
29
|
+
- Before, a run cancelled or stopped while its model request was being admitted could still send that request: the proxy forwarded it after its client had left, nothing stopped it, and it was booked only once the provider ended it, after the run had ended, so the run read the request as cut at an unknown cost. The proxy now books such a request at nothing (never left) and never sends it, so a run cancelled before any request reached the model costs $0. A request that reached the model and was cut keeps the cut rule: unpriced, counted for the cap at its hold.
|
|
30
|
+
- Before, a capped run whose shown cost was unknown gave its learning grade a cap of $0 ("Not graded: no room under the cap.") and its look-back a reached cap. The grade's cap and the look-back now read the run's spend as its own cap gates read it: an answer with no price counts at the figure the cap held for it, never $0 and never the whole cap. Only when that figure is unknown too, the grade is not queued and says why: "Not graded: this run's spend is unknown, so its budget can't cover the grade."
|
|
31
|
+
|
|
5
32
|
## 0.1.0-beta.37 (2026-11-13)
|
|
6
33
|
|
|
7
34
|
- Every harness sees a desktop or a phone through one surface: the tools `computer_observe`, `computer_act`, `computer_screenshot` and `computer_script`, the same answers from a script, an MCP client or a tool call. Breaking: the `desktop_*` and `phone_*` tools are gone, replaced by the `computer_*` tools (a desktop's and a phone's alike, held to the `desktop` or `phone` setting), and the script API's `apps.open(id)` returns nothing; bind the app with `computer.app(id)`.
|
package/README.md
CHANGED
|
@@ -49,11 +49,9 @@ const runNode = createHarnessRunner(
|
|
|
49
49
|
Each search a response ran (`tool_usage.web_search.num_requests`) is added to its price at OpenAI's $0.01 a call; a
|
|
50
50
|
model with no known search price books an unknown cost. A request that offers web search has no input bound, so a cap
|
|
51
51
|
treats its input as unknown.
|
|
52
|
-
- **Remote MCP
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
Codex sends a call without waiting for the session, so the proxy holds it until its line (a script's nested call: its
|
|
56
|
-
script's) is in the log, records its intent and only then sends it, through the host's gateway (`src/mcp.ts`).
|
|
52
|
+
- **Remote MCP tools are host tools.** Codex refuses a dynamic tool named `mcp` or `mcp__*` at `thread/start`, so a
|
|
53
|
+
host tool named `mcp__<server>__<tool>` reaches Codex as `mcp_<server>__<tool>`; the session maps the name back for
|
|
54
|
+
the host's gate and its events. Two tools that would reach Codex by one name are refused when the session is checked.
|
|
57
55
|
- **A private machine.** A session runs in its own directories. Its working directory is the host's workspace when the
|
|
58
56
|
host names one (`io.cwd`, where the host's file tools write, an untrusted project to Codex), and otherwise an empty
|
|
59
57
|
directory of the session's. Codex keeps nothing there, and takes no instructions from an `AGENTS.md` in it
|
package/dist/adapter.d.ts
CHANGED
|
@@ -4,6 +4,13 @@ import { type HostTool as KernelTool } from "@parcha/agentrun-kernel/kernel";
|
|
|
4
4
|
import { NativeJournal } from "@parcha/agentrun-kernel/process";
|
|
5
5
|
import { type ConfineChild } from "./host/machine.js";
|
|
6
6
|
import { type ModelProxyOptions } from "@parcha/agentrun-kernel/host";
|
|
7
|
+
/**
|
|
8
|
+
* The name Codex is given a host tool by. App-server reserves `mcp__` names for its own MCP client's tools and refuses a
|
|
9
|
+
* dynamic tool so named at the thread's start (`dynamic tool name is reserved`, 0.164.0, #1586), so a run's MCP tool
|
|
10
|
+
* (`mcp__<server>__<tool>`), a host tool like any other, is offered as `mcp_<server>__<tool>`. Every other name is
|
|
11
|
+
* as given. Inside the session only: the host's gate and the session's events name the call by the host's name.
|
|
12
|
+
*/
|
|
13
|
+
export declare const codexToolName: (name: string) => string;
|
|
7
14
|
/**
|
|
8
15
|
* Codex's `tool_output_token_limit`: the host's result bound (HOST_RESULT_MAX_CHARS), as Codex counts it. Codex keeps a
|
|
9
16
|
* tool's output in the model's history within its truncation policy (10,000 tokens for each model its catalog holds, less
|
package/dist/adapter.js
CHANGED
|
@@ -15,7 +15,6 @@ import { HOST_RESULT_MAX_CHARS, READ_SKILL_FILE, hostedTool, readSkillFileTool,
|
|
|
15
15
|
import { abortedOutcome, openDrive, SessionHalt } from "@parcha/agentrun-kernel/kernel";
|
|
16
16
|
import { pendingSubmissions } from "@parcha/agentrun-kernel/kernel";
|
|
17
17
|
import { NativeJournal, recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
|
|
18
|
-
import { CODEX_MCP_CLIENT } from "./mcp.js";
|
|
19
18
|
import { codexSchemaProblems, describedDescription } from "./schema.js";
|
|
20
19
|
import { markParked } from "./scripts.js";
|
|
21
20
|
import { withCheckedBinary } from "./host/sandbox.js";
|
|
@@ -28,6 +27,13 @@ import { codexPolicy, withWebSearches } from "./host/policy.js";
|
|
|
28
27
|
import { toolImageProblems } from "./tool-images.js";
|
|
29
28
|
/** A name app-server accepts for a dynamic tool. */
|
|
30
29
|
const TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;
|
|
30
|
+
/**
|
|
31
|
+
* The name Codex is given a host tool by. App-server reserves `mcp__` names for its own MCP client's tools and refuses a
|
|
32
|
+
* dynamic tool so named at the thread's start (`dynamic tool name is reserved`, 0.164.0, #1586), so a run's MCP tool
|
|
33
|
+
* (`mcp__<server>__<tool>`), a host tool like any other, is offered as `mcp_<server>__<tool>`. Every other name is
|
|
34
|
+
* as given. Inside the session only: the host's gate and the session's events name the call by the host's name.
|
|
35
|
+
*/
|
|
36
|
+
export const codexToolName = (name) => (name.startsWith("mcp__") ? `mcp_${name.slice("mcp__".length)}` : name);
|
|
31
37
|
/**
|
|
32
38
|
* Codex's `tool_output_token_limit`: the host's result bound (HOST_RESULT_MAX_CHARS), as Codex counts it. Codex keeps a
|
|
33
39
|
* tool's output in the model's history within its truncation policy (10,000 tokens for each model its catalog holds, less
|
|
@@ -42,18 +48,22 @@ export const CODEX_TOOL_OUTPUT_TOKENS = Math.ceil((HOST_RESULT_MAX_CHARS * 3) /
|
|
|
42
48
|
* line before it runs such a tool is a second guard (the transcript Codex resumes from), not the one that protects it. */
|
|
43
49
|
export function kernelTool(tool) {
|
|
44
50
|
return {
|
|
45
|
-
name: tool.name,
|
|
51
|
+
name: codexToolName(tool.name),
|
|
46
52
|
// Codex strips some keywords from the schema its model is given: they are said in plain words in the description
|
|
47
53
|
// (the schema itself is the host's, and every call is checked against it).
|
|
48
54
|
description: describedDescription(tool.description, tool.inputSchema),
|
|
49
55
|
inputSchema: tool.inputSchema,
|
|
50
56
|
replay: tool.replay,
|
|
57
|
+
...(tool.nests ? { nests: true } : {}),
|
|
58
|
+
...(tool.deferred ? { deferred: true } : {}),
|
|
51
59
|
async execute(input, io) {
|
|
52
60
|
// The effect's step is `tool:<Codex call id>#<attempt>`: the host sees Codex's call id.
|
|
53
61
|
const callId = (io.stepId ?? "").replace(/^tool:/, "").replace(/#\d+$/, "");
|
|
54
62
|
// The step's attempt: above 0 when a crash cut an earlier attempt and the kernel runs the call again.
|
|
55
63
|
const attempt = Number(/#(\d+)$/.exec(io.stepId ?? "")?.[1] ?? 0);
|
|
56
|
-
|
|
64
|
+
// A tool that nests calls (tools_call) names them by the host's names: the bridge holds them by Codex's.
|
|
65
|
+
const nested = io.nested && { call: (name, args, key) => io.nested.call(codexToolName(name), args, key), memo: io.nested.memo };
|
|
66
|
+
const result = await tool.call(input, { callId, signal: io.signal, attempt, ...(nested ? { nested } : {}) });
|
|
57
67
|
// A call the host parked for a person's approval did not run: recorded so before its answer, the waiting text.
|
|
58
68
|
if (result.parked)
|
|
59
69
|
await markParked(io.ctx, callId);
|
|
@@ -72,15 +82,15 @@ export function kernelTool(tool) {
|
|
|
72
82
|
},
|
|
73
83
|
};
|
|
74
84
|
}
|
|
75
|
-
/** The adapter's event for a harness live event, if it has one. */
|
|
76
|
-
function adapterEvent(event) {
|
|
85
|
+
/** The adapter's event for a harness live event, if it has one: a tool's by the host's name for it (`hostName`). */
|
|
86
|
+
function adapterEvent(event, hostName) {
|
|
77
87
|
const e = event;
|
|
78
88
|
if (e?.type === "text" && typeof e.delta === "string")
|
|
79
89
|
return { type: "text", delta: e.delta };
|
|
80
90
|
if (e?.type === "tool_start" && typeof e.name === "string")
|
|
81
|
-
return { type: "tool_start", callId: String(e.callId ?? ""), name: e.name, args: e.args };
|
|
91
|
+
return { type: "tool_start", callId: String(e.callId ?? ""), name: hostName(e.name), args: e.args };
|
|
82
92
|
if (e?.type === "tool_end" && typeof e.name === "string")
|
|
83
|
-
return { type: "tool_end", callId: String(e.callId ?? ""), name: e.name, isError: e.isError === true, ...(e.truncated === true ? { truncated: true } : {}) };
|
|
93
|
+
return { type: "tool_end", callId: String(e.callId ?? ""), name: hostName(e.name), isError: e.isError === true, ...(e.truncated === true ? { truncated: true } : {}) };
|
|
84
94
|
return undefined;
|
|
85
95
|
}
|
|
86
96
|
const turnsIn = (drive) => transcriptOf(drive.state()).filter((r) => r.data?.type === "turn");
|
|
@@ -121,20 +131,25 @@ export function codexAdapter(options) {
|
|
|
121
131
|
};
|
|
122
132
|
return {
|
|
123
133
|
id: "codex",
|
|
124
|
-
capabilities: () => ({ mcpClient: CODEX_MCP_CLIENT }),
|
|
125
134
|
check(spec) {
|
|
126
135
|
const problems = [];
|
|
127
136
|
if (spec.context === "fork")
|
|
128
137
|
problems.push("Codex sessions cannot fork another session's transcript; declare context: \"fresh\"");
|
|
129
|
-
|
|
138
|
+
// Each tool by the name Codex is given it (codexToolName): two that would reach Codex by one name are refused.
|
|
139
|
+
const seen = new Map();
|
|
130
140
|
for (const tool of spec.tools) {
|
|
141
|
+
const given = codexToolName(tool.name);
|
|
131
142
|
if (!TOOL_NAME.test(tool.name))
|
|
132
143
|
problems.push(`the tool name ${JSON.stringify(tool.name.slice(0, 80))} is not one Codex accepts (letters, digits, _ and -, at most 64)`);
|
|
133
|
-
|
|
144
|
+
const twin = seen.get(given);
|
|
145
|
+
if (twin === tool.name)
|
|
134
146
|
problems.push(`the tool ${tool.name} is given twice`);
|
|
135
|
-
if (
|
|
147
|
+
else if (twin !== undefined)
|
|
148
|
+
problems.push(`the tools ${twin} and ${tool.name} both reach Codex as ${given}`);
|
|
149
|
+
if (skills.length && given === READ_SKILL_FILE)
|
|
136
150
|
problems.push(`the tool name ${READ_SKILL_FILE} is the adapter's own when it has skills`);
|
|
137
|
-
|
|
151
|
+
if (twin === undefined)
|
|
152
|
+
seen.set(given, tool.name);
|
|
138
153
|
// What no harness takes (an object root, valid 2020-12, no remote $ref), then what Codex would drop or retype in
|
|
139
154
|
// the tool's schema: refused here, by name, not found out mid-turn. A place the first already refused is not
|
|
140
155
|
// refused again by the second.
|
|
@@ -162,6 +177,9 @@ export function codexAdapter(options) {
|
|
|
162
177
|
throw new Error("agentrun-harness-codex: a session needs a private directory: the host lends one (io.dir), or pass sessionsDir");
|
|
163
178
|
// With skills the model also reads their files (read_skill_file), from the session's own copy of them.
|
|
164
179
|
const tools = skills.length ? [...spec.tools, hostedTool(io, readSkillFileTool(join(sessionDir(dir, "codex-home"), SKILLS_DIR), skills.map((skill) => ({ name: skill.name, files: Object.keys(skill.files) }))))] : spec.tools;
|
|
180
|
+
// The host's name for each tool as Codex calls it: the gate and the session's events name a call by it.
|
|
181
|
+
const hostNames = new Map(tools.map((t) => [codexToolName(t.name), t.name]));
|
|
182
|
+
const hostName = (name) => hostNames.get(name) ?? name;
|
|
165
183
|
const effort = spec.effort ?? spec.thinking;
|
|
166
184
|
// The live search runs inside a model request, where no call reaches the gate: it is offered only while the host's
|
|
167
185
|
// web_search setting allows it, read before each request (a deny or ask set mid-run drops it from the next one).
|
|
@@ -169,7 +187,7 @@ export function codexAdapter(options) {
|
|
|
169
187
|
const harnessOptions = {
|
|
170
188
|
tools: tools.map(kernelTool),
|
|
171
189
|
// The host's gate, asked about each host-tool call before its intent is written.
|
|
172
|
-
...(io.gate ? { gate: (call) => io.gate(call) } : {}),
|
|
190
|
+
...(io.gate ? { gate: (call) => io.gate({ ...call, tool: hostName(call.tool) }) } : {}),
|
|
173
191
|
builtins: false,
|
|
174
192
|
// Codex's bundled skills (imagegen, skill-installer, ...), which it writes under `$CODEX_HOME/skills/.system` at every
|
|
175
193
|
// start, are off in every session, skills or not: the model is shown the host's skills and no others.
|
|
@@ -198,11 +216,9 @@ export function codexAdapter(options) {
|
|
|
198
216
|
// (catalog.ts). A stand-in runs no Codex, so it has no catalog to read.
|
|
199
217
|
...(checked !== undefined ? { catalog: { command: checked, ...(options.log ? { log: options.log } : {}) } } : {}),
|
|
200
218
|
...(options.webSearch ? { webSearch: options.webSearch, ...(searchAllowed ? { searchAllowed } : {}) } : {}),
|
|
201
|
-
// A granted MCP server's tools: Codex's own MCP client calls them at the proxy (mcp.ts).
|
|
202
|
-
...(spec.mcp?.servers.length ? { mcp: spec.mcp } : {}),
|
|
203
219
|
proxy: {
|
|
204
220
|
hooks: io.models,
|
|
205
|
-
tools: tools.map((t) => t.name),
|
|
221
|
+
tools: tools.map((t) => codexToolName(t.name)),
|
|
206
222
|
...(options.log ? { log: options.log } : {}),
|
|
207
223
|
...(options.price ? { price: options.price } : {}),
|
|
208
224
|
...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}),
|
|
@@ -213,7 +229,7 @@ export function codexAdapter(options) {
|
|
|
213
229
|
};
|
|
214
230
|
const harness = checked === undefined ? codexHarness(harnessOptions) : withCheckedBinary(checked, () => codexHarness(harnessOptions));
|
|
215
231
|
const live = (event) => {
|
|
216
|
-
const mapped = adapterEvent(event);
|
|
232
|
+
const mapped = adapterEvent(event, hostName);
|
|
217
233
|
if (mapped)
|
|
218
234
|
io.onEvent(mapped);
|
|
219
235
|
};
|
package/dist/code-mode.d.ts
CHANGED
|
@@ -5,6 +5,9 @@ import { type RolloutSummary } from "./rollout.js";
|
|
|
5
5
|
export declare const NESTED_STREAM = "codex.nested";
|
|
6
6
|
/** The stream that records the interrupted turns whose recovery note was injected: `{ since }`, once per interrupted turn. */
|
|
7
7
|
export declare const RECOVERY_NOTE_STREAM = "codex.recovery-note";
|
|
8
|
+
/** A yielded exec's nested call run on a resume (recoverItems), written before it runs: a later recovery of the same turn tells
|
|
9
|
+
* the model's `wait` its outcome from the session's record, never running it again. */
|
|
10
|
+
export declare const RESUMED_STREAM = "codex.nested-resumed";
|
|
8
11
|
interface Journal {
|
|
9
12
|
append(stream: string, record: unknown): void;
|
|
10
13
|
flush(): Promise<void>;
|
|
@@ -33,6 +36,11 @@ export interface CodeModeDeps {
|
|
|
33
36
|
}[];
|
|
34
37
|
structured?: unknown;
|
|
35
38
|
} | undefined;
|
|
39
|
+
/** A call through the bridge (gate, intent, call, result): a resumed nested call that never reached its intent (recoverItems). */
|
|
40
|
+
call?(name: string, args: unknown, callId: string): Promise<{
|
|
41
|
+
text: string;
|
|
42
|
+
isError: boolean;
|
|
43
|
+
}>;
|
|
36
44
|
};
|
|
37
45
|
log(message: string, fields?: Record<string, unknown>): void;
|
|
38
46
|
/** The rollout lines restored from the log. */
|
|
@@ -101,8 +109,9 @@ export declare function codeMode(deps: CodeModeDeps): {
|
|
|
101
109
|
* 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
|
|
102
110
|
* 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
|
|
103
111
|
* 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
|
|
104
|
-
* both repairs (with a recovery note and without) inject what this leaves.
|
|
105
|
-
|
|
112
|
+
* both repairs (with a recovery note and without) inject what this leaves. `resume`: the open turn a recovery note resumes, whose
|
|
113
|
+
* parked nested calls run now; the repair of an ended turn (repairUnnoted) only tells, and runs nothing. */
|
|
114
|
+
recoverItems(items: Record<string, unknown>[], dangling: readonly Dangling[], lines: readonly string[], since: number, resume?: boolean): Promise<void>;
|
|
106
115
|
/** 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
|
|
107
116
|
* them (one interrupted mid-call, or settled instead of resumed) left them dangling, and the provider refuses a history with a call unanswered.
|
|
108
117
|
* Nothing is armed here: a new turn that calls a `never` call the ended turn completed runs it. */
|
package/dist/code-mode.js
CHANGED
|
@@ -3,11 +3,14 @@ import { boundResult, openTurn, recoveryNote, recoverySystemNote, recoveryUserTu
|
|
|
3
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
4
|
import { repairOutput } from "./harness.js";
|
|
5
5
|
import { summarizeRollout } from "./rollout.js";
|
|
6
|
-
import { callKey, completedNested, execRecoveryOutput, NESTED_CALL, outputTextOf, parkedKey, recoveryFacts, Scripts, settle, UNWATCHED } from "./scripts.js";
|
|
6
|
+
import { callKey, completedNested, execRecoveryOutput, NESTED_CALL, outputTextOf, parkedKey, recoveryFacts, Scripts, settle, UNWATCHED, waitResumedText } from "./scripts.js";
|
|
7
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
8
|
export const NESTED_STREAM = "codex.nested";
|
|
9
9
|
/** The stream that records the interrupted turns whose recovery note was injected: `{ since }`, once per interrupted turn. */
|
|
10
10
|
export const RECOVERY_NOTE_STREAM = "codex.recovery-note";
|
|
11
|
+
/** A yielded exec's nested call run on a resume (recoverItems), written before it runs: a later recovery of the same turn tells
|
|
12
|
+
* the model's `wait` its outcome from the session's record, never running it again. */
|
|
13
|
+
export const RESUMED_STREAM = "codex.nested-resumed";
|
|
11
14
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
12
15
|
/** 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
16
|
const isExec = (d) => d.type === "custom_tool_call" && d.name === "exec";
|
|
@@ -40,7 +43,7 @@ function factOf(state, rolled, tie, told = new Map()) {
|
|
|
40
43
|
const status = told.get(tie.callId);
|
|
41
44
|
return {
|
|
42
45
|
callId: tie.callId,
|
|
43
|
-
tool: e ? e.name.replace(/^tool\./, "") : (rolled.get(tie.callId)?.tool ?? "a tool"),
|
|
46
|
+
tool: e ? e.name.replace(/^tool\./, "") : (rolled.get(tie.callId)?.tool ?? tie.tool ?? "a tool"),
|
|
44
47
|
...(e ? { store: { status: e.status === "completed" ? "completed" : e.status === "failed" ? "failed" : "started", text: e.status === "failed" ? (e.error?.message ?? "") : outputTextOf(e.output), ...(e.status === "completed" ? sentOf(e.output) : {}), ...(e.error?.interrupted ? { interrupted: true } : {}) } } : {}),
|
|
45
48
|
...(rolled.has(tie.callId) ? { rollout: rolled.get(tie.callId) } : {}),
|
|
46
49
|
...(status ? { told: status } : {}),
|
|
@@ -112,28 +115,6 @@ export function codeMode(deps) {
|
|
|
112
115
|
machine.onRolloutLine?.((line) => scripts.note(line));
|
|
113
116
|
/** The script a nested call is tied to now, as the log and the proxy's latest answer have it. */
|
|
114
117
|
const tieNow = () => scripts.tie(machine.announcedExec?.(), (id) => logged.has(id));
|
|
115
|
-
/** A call Codex runs without the harness (a remote MCP server's tool, mcp.ts): the barrier it passes before its intent (its
|
|
116
|
-
* own line in the log, as the harness's barrier has it; a script's nested call, its script's, tied to it by `admit`), and
|
|
117
|
-
* after a recovery the log's answer for a `never` call the interrupted turn completed, re-issued under a new id. */
|
|
118
|
-
machine.onCalls?.({ recovered: (tool, args) => answeredAgain(tool, args), barrier: async (callId) => {
|
|
119
|
-
if (NESTED_CALL.test(callId)) {
|
|
120
|
-
if (!(await admit(callId)))
|
|
121
|
-
return false;
|
|
122
|
-
const exec = execOf.get(callId);
|
|
123
|
-
journal.append(NESTED_STREAM, { callId, exec: exec === undefined || exec === UNWATCHED ? null : exec, since: openTurn(ctx.state())?.since ?? -1 });
|
|
124
|
-
await journal.flush();
|
|
125
|
-
return true;
|
|
126
|
-
}
|
|
127
|
-
for (let i = 0; i < deps.tries; i++) {
|
|
128
|
-
if (i)
|
|
129
|
-
await sleep(50 * 2 ** (i - 1));
|
|
130
|
-
await synced();
|
|
131
|
-
if (logged.has(callId))
|
|
132
|
-
return journal.flush().then(() => true);
|
|
133
|
-
}
|
|
134
|
-
deps.log("codex: declined a call whose function_call line is not in the log", { callId });
|
|
135
|
-
return false;
|
|
136
|
-
} });
|
|
137
118
|
/** A `never` nested call: wait for its script's line, as the harness's barrier waits for a call's own. True: admitted. */
|
|
138
119
|
const admit = async (callId) => {
|
|
139
120
|
for (let i = 0;; i++) {
|
|
@@ -209,12 +190,6 @@ export function codeMode(deps) {
|
|
|
209
190
|
/** The app-server's request handler, with a code-mode host tool call handled before the harness's own. */
|
|
210
191
|
request(next) {
|
|
211
192
|
return async (req) => {
|
|
212
|
-
// Codex asking to run a remote MCP server's tool, should it ask (approve mode asks nothing): the session's only MCP
|
|
213
|
-
// servers are its own, at its model proxy, which serves only the granted tools and records each call before it
|
|
214
|
-
// sends it (mcp.ts). Any other elicitation is the harness's to decline.
|
|
215
|
-
const meta = req.params?._meta;
|
|
216
|
-
if (req.method === "mcpServer/elicitation/request" && meta?.codex_approval_kind === "mcp_tool_call")
|
|
217
|
-
return { action: "accept", content: {}, _meta: null };
|
|
218
193
|
if (req.method === "item/tool/call") {
|
|
219
194
|
const p = req.params ?? {};
|
|
220
195
|
const callId = String(p.callId ?? "");
|
|
@@ -232,7 +207,7 @@ export function codeMode(deps) {
|
|
|
232
207
|
if (exec)
|
|
233
208
|
execOf.set(callId, exec);
|
|
234
209
|
// Never the unwatched-answer marker: a call tied to no known exec is journaled with none.
|
|
235
|
-
journal.append(NESTED_STREAM, { callId, exec: exec === undefined || exec === UNWATCHED ? null : exec, since: openTurn(ctx.state())?.since ?? -1 });
|
|
210
|
+
journal.append(NESTED_STREAM, { callId, exec: exec === undefined || exec === UNWATCHED ? null : exec, since: openTurn(ctx.state())?.since ?? -1, tool: String(p.tool), args: p.arguments ?? {} });
|
|
236
211
|
}
|
|
237
212
|
// The harness answers with the result's text; its images follow as `inputImage` items, which Codex 0.164's
|
|
238
213
|
// dynamic tool output takes (DynamicToolCallResponse.contentItems, its app-server schema), each a data: URL.
|
|
@@ -257,16 +232,53 @@ export function codeMode(deps) {
|
|
|
257
232
|
* 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
|
|
258
233
|
* 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
|
|
259
234
|
* 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
|
|
260
|
-
* both repairs (with a recovery note and without) inject what this leaves.
|
|
261
|
-
|
|
262
|
-
|
|
235
|
+
* both repairs (with a recovery note and without) inject what this leaves. `resume`: the open turn a recovery note resumes, whose
|
|
236
|
+
* parked nested calls run now; the repair of an ended turn (repairUnnoted) only tells, and runs nothing. */
|
|
237
|
+
async recoverItems(items, dangling, lines, since, resume = false) {
|
|
263
238
|
const ties = (await journal.read(NESTED_STREAM)).map((r) => r.data);
|
|
264
239
|
const execs = dangling.filter(isExec).map((d) => d.callId);
|
|
265
240
|
const rolled = completedNested(lines);
|
|
241
|
+
// A nested call of a cut-off exec that never reached its intent and that Codex was never answered (its script went with
|
|
242
|
+
// the session: the host's gate parked it for a person's approval, or a crash came before its intent) runs now, through
|
|
243
|
+
// the bridge under its own id, the gate first, so the person's answer on it holds, as a dangling call of the model's own
|
|
244
|
+
// does (resumeUnstartedCalls): its outcome is the exec's output, and nothing runs it again. A gate that parks again
|
|
245
|
+
// rejects out of here, nothing written. Only on the resume of the open turn: an ended turn's repair runs nothing, so a call a
|
|
246
|
+
// person may never have answered does not run on a later turn. A script whose exec had yielded ("Script running") made
|
|
247
|
+
// its call in this turn while the model waited on its cell: that call runs too, and the dangling `wait` tells its
|
|
248
|
+
// outcome (with none dangling there is nowhere to tell it, and it does not run).
|
|
249
|
+
const resumed = new Map();
|
|
250
|
+
const cut = new Set(execs);
|
|
251
|
+
const carrier = dangling.findIndex((c) => !isExec(c) && waitedCell(c) !== undefined);
|
|
252
|
+
const yieldedTies = [];
|
|
253
|
+
const ranBefore = resume ? new Set((await journal.read(RESUMED_STREAM)).map((r) => r.data.callId)) : new Set();
|
|
254
|
+
for (const tie of resume ? ties : []) {
|
|
255
|
+
const cutOff = tie.exec === null ? tie.since === since && execs.length > 0 : cut.has(tie.exec);
|
|
256
|
+
const yielded = !cutOff && carrier >= 0 && tie.since === since;
|
|
257
|
+
const done = ctx.state().effects.get(toolKey(tie.callId));
|
|
258
|
+
// Run on an earlier recovery of this turn that stopped before the wait was answered: told from its record.
|
|
259
|
+
if (yielded && ranBefore.has(tie.callId) && (done?.status === "completed" || done?.status === "failed") && !rolled.has(tie.callId)) {
|
|
260
|
+
resumed.set(tie.callId, { text: done.status === "failed" ? (done.error?.message ?? "") : outputTextOf(done.output), isError: done.status === "failed", ran: true });
|
|
261
|
+
yieldedTies.push(tie);
|
|
262
|
+
continue;
|
|
263
|
+
}
|
|
264
|
+
if ((!cutOff && !yielded) || tie.tool === undefined || done || rolled.has(tie.callId))
|
|
265
|
+
continue;
|
|
266
|
+
if (!deps.bridge.call || !deps.bridge.get(tie.tool))
|
|
267
|
+
continue;
|
|
268
|
+
if (yielded) {
|
|
269
|
+
journal.append(RESUMED_STREAM, { callId: tie.callId });
|
|
270
|
+
await journal.flush();
|
|
271
|
+
}
|
|
272
|
+
const result = await deps.bridge.call(tie.tool, tie.args ?? {}, tie.callId);
|
|
273
|
+
resumed.set(tie.callId, { text: result.text, isError: result.isError, ran: ctx.state().effects.has(toolKey(tie.callId)) });
|
|
274
|
+
if (yielded)
|
|
275
|
+
yieldedTies.push(tie);
|
|
276
|
+
}
|
|
277
|
+
const state = ctx.state();
|
|
266
278
|
// 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)
|
|
267
279
|
// is listed once, apart, in the LAST cut-off exec's output, if it ran in this interrupted turn.
|
|
268
280
|
const told = new Map((recoveryNote(state)?.calls ?? []).map((c) => [c.callId, c.status]));
|
|
269
|
-
const listed = recoveryFacts(execs, ties, since, (tie) => factOf(state, rolled, tie, told));
|
|
281
|
+
const listed = recoveryFacts(execs, ties, since, (tie) => ({ ...factOf(state, rolled, tie, told), ...(resumed.has(tie.callId) ? { resumed: resumed.get(tie.callId) } : {}) }));
|
|
270
282
|
dangling.forEach((c, i) => {
|
|
271
283
|
if (!isExec(c)) {
|
|
272
284
|
// Code mode's `wait` on a cell had started: the generic answer, that the call never started, would be false.
|
|
@@ -276,7 +288,8 @@ export function codeMode(deps) {
|
|
|
276
288
|
// as JSON, so the model would read their base64 as text. Its text and a line on them instead; they are not sent.
|
|
277
289
|
const done = state.effects.get(toolKey(c.callId));
|
|
278
290
|
const pictured = cell === undefined && done?.status === "completed" ? imagesNoted(done.output) : undefined;
|
|
279
|
-
|
|
291
|
+
const waited = cell === undefined ? undefined : i === carrier && yieldedTies.length > 0 ? waitResumedText(cell, yieldedTies.map((tie) => ({ ...factOf(state, rolled, tie, told), resumed: resumed.get(tie.callId) }))) : waitStoppedText(cell);
|
|
292
|
+
items[i] = withOutputKind(waited !== undefined ? { ...item, output: waited } : pictured !== undefined ? { ...item, output: pictured } : item, c);
|
|
280
293
|
return;
|
|
281
294
|
}
|
|
282
295
|
const { own, loose } = listed.get(c.callId);
|
package/dist/facts.js
CHANGED
|
@@ -14,16 +14,16 @@ export const facts = Object.freeze({
|
|
|
14
14
|
// One run's memory, measured with the server's (serve's host.ts): Codex's app-server beside the run's process.
|
|
15
15
|
runMib: 192,
|
|
16
16
|
// OpenAI's reasoning efforts stop at xhigh.
|
|
17
|
-
// Its own MCP client binds the session's remote MCP servers.
|
|
18
|
-
mcp: true,
|
|
19
17
|
thinking: Object.freeze(["low", "medium", "high", "xhigh"]),
|
|
20
18
|
// Codex's own live search, booked per call.
|
|
21
19
|
webSearch: "live",
|
|
22
20
|
ownModel: false,
|
|
21
|
+
// Its own code mode runs the model's scripts, each nested call one of the host's tools through its bridge.
|
|
22
|
+
ownCodemode: true,
|
|
23
23
|
normalizeModel: (model) => model,
|
|
24
24
|
install: Object.freeze({ npmLine: CODEX_INSTALL, spec: `@openai/codex@${CODEX_VERSION}`, codes: Object.freeze({ install: "CODEX_NOT_INSTALLED", pins: "CODEX_PIN_MISMATCH" }) }),
|
|
25
|
-
//
|
|
26
|
-
//
|
|
25
|
+
// The shapes Codex drops or retypes in a host tool's schema (a run's MCP tool's among them), measured on the pinned
|
|
26
|
+
// binary (schema.ts).
|
|
27
27
|
schemaProblems: codexSchemaProblems,
|
|
28
28
|
// Codex's own tools, each the host's table tool it is.
|
|
29
29
|
nativeTools: Object.freeze({ web_search: "web_search", shell: "bash" }),
|
package/dist/harness.js
CHANGED
|
@@ -847,7 +847,7 @@ export function codexHarness(options = {}) {
|
|
|
847
847
|
if (resume && summary.dangling.length > 0) {
|
|
848
848
|
// Calls the rollout has no output for get theirs from the log.
|
|
849
849
|
const items = summary.dangling.map((c) => ({ type: 'function_call_output', call_id: c.callId, output: repairOutput(ctx.state(), c) }));
|
|
850
|
-
await code.recoverItems(items, summary.dangling, lines, note.turn.since);
|
|
850
|
+
await code.recoverItems(items, summary.dangling, lines, note.turn.since, true);
|
|
851
851
|
await guard(rpc.request('thread/inject_items', { threadId, items }));
|
|
852
852
|
await guard(synced());
|
|
853
853
|
}
|
package/dist/host/machine.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import type { AcquireMachine, CacheDir, SessionProcess } from "./process.js";
|
|
2
|
-
import type { SessionMcp } from "@parcha/agentrun-kernel";
|
|
3
2
|
import { type ModelProxyHooks, type ModelProxyOptions, type ParentWatch } from "@parcha/agentrun-kernel/host";
|
|
4
3
|
import { type CodexCommand } from "../catalog.js";
|
|
5
4
|
/** The variables a child takes from this process, when they are set. */
|
|
@@ -38,9 +37,6 @@ export interface LocalMachineOptions {
|
|
|
38
37
|
log?: ModelProxyOptions["log"];
|
|
39
38
|
fetch?: typeof fetch;
|
|
40
39
|
};
|
|
41
|
-
/** The session's remote MCP servers (mcp.ts): each served at the proxy's `/mcp/<server>`, written in Codex's config,
|
|
42
|
-
* and each call recorded in the drive's session before it is sent. */
|
|
43
|
-
mcp?: SessionMcp;
|
|
44
40
|
/** For tests: the process environment the allowlist reads. Default `process.env`. */
|
|
45
41
|
env?: Readonly<Record<string, string | undefined>>;
|
|
46
42
|
/** Files one of the session's private directories holds at the start of every drive: written when the machine is
|
package/dist/host/machine.js
CHANGED
|
@@ -23,7 +23,6 @@ import { brandMachine } from "./process.js";
|
|
|
23
23
|
import { parentWatched, startModelProxy } from "@parcha/agentrun-kernel/host";
|
|
24
24
|
import { codexPolicy, withWebSearches } from "./policy.js";
|
|
25
25
|
import { UNWATCHED } from "../scripts.js";
|
|
26
|
-
import { CODEX_MCP_CLIENT, mcpServersConfig, recorded } from "../mcp.js";
|
|
27
26
|
import { MODEL_CATALOG_FILE, patchlessCatalog } from "../catalog.js";
|
|
28
27
|
/** The variables a child takes from this process, when they are set. */
|
|
29
28
|
export const INHERITED_ENV = Object.freeze(["PATH", "LANG", "TZ"]);
|
|
@@ -208,14 +207,12 @@ export function localMachine(options) {
|
|
|
208
207
|
let open = 0;
|
|
209
208
|
const rolloutListeners = [];
|
|
210
209
|
const cutListeners = [];
|
|
211
|
-
let calls;
|
|
212
210
|
const search = options.webSearch === "live";
|
|
213
211
|
const price = options.proxy.price && search ? withWebSearches(options.proxy.price) : options.proxy.price;
|
|
214
212
|
const proxy = await startModelProxy({
|
|
215
213
|
policy: codexPolicy({
|
|
216
214
|
model: route.models.model,
|
|
217
215
|
tools: options.proxy.tools,
|
|
218
|
-
...(options.mcp ? { mcpTools: options.mcp.servers.flatMap((server) => server.tools.map((tool) => `mcp__${server.name}__${tool.name}`)) } : {}),
|
|
219
216
|
...(options.proxy.maxOutputTokens ? { maxOutputTokens: options.proxy.maxOutputTokens } : {}),
|
|
220
217
|
...(search ? { webSearch: "live", ...(options.searchAllowed ? { searchAllowed: options.searchAllowed } : {}) } : {}),
|
|
221
218
|
announce: {
|
|
@@ -237,8 +234,6 @@ export function localMachine(options) {
|
|
|
237
234
|
origin: route.target,
|
|
238
235
|
credential: async () => (await route.credential()) ?? "",
|
|
239
236
|
...(price ? { price } : {}),
|
|
240
|
-
// The kernel's proxy mounts the session's MCP door for Codex's own client; each call is recorded first (recorded).
|
|
241
|
-
...(options.mcp ? { mcp: { session: recorded(options.mcp, ctx, () => calls), client: CODEX_MCP_CLIENT } } : {}),
|
|
242
237
|
...(options.proxy.log ? { log: options.proxy.log } : {}),
|
|
243
238
|
...(options.proxy.fetch ? { fetch: options.proxy.fetch } : {}),
|
|
244
239
|
// The provider stopped the turn's answer on its content filter: no retry of it can pass, so the turn ends at once.
|
|
@@ -264,15 +259,10 @@ export function localMachine(options) {
|
|
|
264
259
|
onRolloutLine: (listener) => void rolloutListeners.push(listener),
|
|
265
260
|
onCut: (listener) => void cutListeners.push(listener),
|
|
266
261
|
openTurn: () => proxy.openTurn(),
|
|
267
|
-
|
|
268
|
-
...(search || options.mcp || catalog ? {
|
|
262
|
+
...(search || catalog ? {
|
|
269
263
|
configure: (config) => {
|
|
270
264
|
if (search)
|
|
271
265
|
config.web_search = "live";
|
|
272
|
-
// Codex's bearer for the proxy's /mcp/<server> is the key it sends to the proxy's model route.
|
|
273
|
-
const keyEnv = (config.model_providers?.gateway?.env_key ?? "");
|
|
274
|
-
if (options.mcp)
|
|
275
|
-
config.mcp_servers = mcpServersConfig(options.mcp, proxy.url, keyEnv);
|
|
276
266
|
// Only with the built-ins off: with them on, apply_patch runs through the shell.
|
|
277
267
|
const features = config.features;
|
|
278
268
|
if (catalog && features?.shell_tool !== true && features?.unified_exec !== true)
|
package/dist/host/policy.d.ts
CHANGED
|
@@ -15,9 +15,6 @@ export interface CodexPolicyOptions {
|
|
|
15
15
|
model: string;
|
|
16
16
|
/** The session's own tool names: every other tool definition is dropped. */
|
|
17
17
|
tools: readonly string[];
|
|
18
|
-
/** The granted tools of the session's remote MCP servers, `mcp__<server>__<tool>`: the pinned CLI offers a server's tools
|
|
19
|
-
* in a namespace named `mcp__<server>`, each by the server's own name. */
|
|
20
|
-
mcpTools?: readonly string[];
|
|
21
18
|
/** The most output tokens one request may ask for. Default 32 000. */
|
|
22
19
|
maxOutputTokens?: number;
|
|
23
20
|
/** Codex's own web search, live: the live search tool the pinned CLI sends passes, and a `tool_choice` naming it. Each
|
|
@@ -68,15 +65,6 @@ export declare function usageOf(text: string): ProxyUsage | undefined;
|
|
|
68
65
|
/** The web searches a Responses answer ran, as its terminal event reports them (`tool_usage.web_search.num_requests`,
|
|
69
66
|
* what OpenAI bills per call), or undefined when that event's own count cannot be read: an unknown cost, never 0. */
|
|
70
67
|
export declare function webSearchesOf(text: string): number | undefined;
|
|
71
|
-
/**
|
|
72
|
-
* The input tokens the provider bills for `body` that it does not carry (`providerInputOverhead`, with its sources). The
|
|
73
|
-
* Responses API documents no prompt of its own that it adds on these routes (no hosted tool passes the policy but a
|
|
74
|
-
* session's live web search, below), and the framing it puts around each input item and tool definition is a few tokens
|
|
75
|
-
* each, fewer than the bytes of the JSON keys that item already spends in the body. An image is billed by its area, not
|
|
76
|
-
* its bytes: each counts at the most it can be billed as, in place of the bytes its data URL takes in the body. A file input (a PDF, billed by its pages) has no stated bound, so a
|
|
77
|
-
* body with one cannot be measured: this throws, and the request's input is unknown.
|
|
78
|
-
*/
|
|
79
|
-
export declare function responsesServerInputOverhead(body: Record<string, unknown>): number;
|
|
80
68
|
/** The tokens a request keeps for its answer when its output is limited. */
|
|
81
69
|
export declare const ANSWER_TOKENS_LEAST = 1024;
|
|
82
70
|
/** What a reasoning request at each effort is allowed for its reasoning beside its answer, when its output is limited:
|
package/dist/host/policy.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { lastObjectOf, NATIVE_SEARCH_USD, OPENAI_INPUT_COUNTER, ProxyRefusal, responsesInputOverhead } from "@parcha/agentrun-kernel/host";
|
|
2
2
|
export const CODEX_RESPONSES_ROUTES = Object.freeze([
|
|
3
3
|
{ method: "GET", path: "/", local: 404 },
|
|
4
4
|
{ method: "POST", path: "/v1/responses", headers: ["accept"] },
|
|
@@ -31,8 +31,8 @@ const isLiveSearch = (tool) => Object.keys(tool).length === Object.keys(LIVE_SEA
|
|
|
31
31
|
* not listed: their searches, like any model's not listed here (a gateway's own id, say), are an unknown cost, never $0.
|
|
32
32
|
*/
|
|
33
33
|
const WEB_SEARCH_USD = [
|
|
34
|
-
[/^(?:gpt-6|gpt-5|o3|o4-mini)(?:[-.][a-z0-9.-]+)?$/,
|
|
35
|
-
[/^gpt-4(?:o|\.1)(?:-\d{4}-\d{2}-\d{2})?$/,
|
|
34
|
+
[/^(?:gpt-6|gpt-5|o3|o4-mini)(?:[-.][a-z0-9.-]+)?$/, NATIVE_SEARCH_USD],
|
|
35
|
+
[/^gpt-4(?:o|\.1)(?:-\d{4}-\d{2}-\d{2})?$/, NATIVE_SEARCH_USD],
|
|
36
36
|
];
|
|
37
37
|
/** The price of one web search call on `model`, or undefined when it is not known. */
|
|
38
38
|
export function webSearchUsd(model) {
|
|
@@ -53,8 +53,8 @@ export function withWebSearches(price) {
|
|
|
53
53
|
}
|
|
54
54
|
const isPlain = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
55
55
|
/** A list of tool definitions with no provider-hosted tool but the live web search when `search` is on, less any not the
|
|
56
|
-
* session's own
|
|
57
|
-
function ownTools(tools, allowed, search = false
|
|
56
|
+
* session's own (`allowed`, by name). */
|
|
57
|
+
function ownTools(tools, allowed, search = false) {
|
|
58
58
|
if (!Array.isArray(tools))
|
|
59
59
|
throw new ProxyRefusal(400, "tools is not a list");
|
|
60
60
|
const out = [];
|
|
@@ -72,9 +72,9 @@ function ownTools(tools, allowed, search = false, mcp = new Set()) {
|
|
|
72
72
|
if (DROPPED_TOOLS.has(type))
|
|
73
73
|
continue;
|
|
74
74
|
if (type === "namespace") {
|
|
75
|
-
// A namespace holds the tools of a built-in family
|
|
76
|
-
//
|
|
77
|
-
const kept = ownTools(tool.tools, name.startsWith("mcp__") ? new Set(
|
|
75
|
+
// A namespace holds the tools of a built-in family: only the session's own ones stay, and an empty one goes. One of
|
|
76
|
+
// an MCP server's (`mcp__<server>`) holds none of the session's: Codex binds no MCP server of its own.
|
|
77
|
+
const kept = ownTools(tool.tools, name.startsWith("mcp__") ? new Set() : allowed);
|
|
78
78
|
if (kept.length)
|
|
79
79
|
out.push({ ...tool, tools: kept });
|
|
80
80
|
continue;
|
|
@@ -172,8 +172,8 @@ function cutEnd(text) {
|
|
|
172
172
|
* The value of `key` in the response an answer ends with: a stream's `response.completed` (or `response.incomplete`),
|
|
173
173
|
* each `data:` line parsed on its own, or a whole JSON body's. The proxy keeps only the first and last 64 KiB of a long
|
|
174
174
|
* answer, and the completed event carries the whole response (its tools and encrypted reasoning), so its line can be cut
|
|
175
|
-
* at the window's start: then the last `"<key>":{` in the text (the
|
|
176
|
-
* unescaped) is read as one JSON object. The usage is looked for in all the text kept; `tool_usage` only in the cut end
|
|
175
|
+
* at the window's start: then the last `"<key>": {` in the text, whatever its spacing (the kernel's `lastObjectOf`: the
|
|
176
|
+
* response's, which a JSON string cannot contain unescaped), is read as one JSON object. The usage is looked for in all the text kept; `tool_usage` only in the cut end
|
|
177
177
|
* of the last event (`cutEnd`), since the events before the terminal one carry a `tool_usage` of their own (a count of
|
|
178
178
|
* 0 as the response starts). No completed event, or no `key` in it, is undefined.
|
|
179
179
|
*/
|
|
@@ -210,21 +210,7 @@ function endValue(text, key) {
|
|
|
210
210
|
catch { }
|
|
211
211
|
}
|
|
212
212
|
const scope = key === "usage" ? text : cutEnd(text);
|
|
213
|
-
|
|
214
|
-
return undefined;
|
|
215
|
-
const mark = `"${key}":{`;
|
|
216
|
-
const at = scope.lastIndexOf(mark);
|
|
217
|
-
if (at < 0)
|
|
218
|
-
return undefined;
|
|
219
|
-
const json = objectAt(scope, at + mark.length - 1);
|
|
220
|
-
if (json === undefined)
|
|
221
|
-
return undefined;
|
|
222
|
-
try {
|
|
223
|
-
return JSON.parse(json);
|
|
224
|
-
}
|
|
225
|
-
catch {
|
|
226
|
-
return undefined;
|
|
227
|
-
}
|
|
213
|
+
return scope === undefined ? undefined : lastObjectOf(scope, key);
|
|
228
214
|
}
|
|
229
215
|
/**
|
|
230
216
|
* Whether the provider stopped the answer on its content filter: the stream's terminal event (or a whole body) is an
|
|
@@ -347,27 +333,6 @@ export function webSearchesOf(text) {
|
|
|
347
333
|
const count = isPlain(search) ? search.num_requests : undefined;
|
|
348
334
|
return typeof count === "number" && Number.isInteger(count) && count >= 0 ? count : undefined;
|
|
349
335
|
}
|
|
350
|
-
/** The items of `type` in `value`, at any depth (a tool's output holds them). */
|
|
351
|
-
function itemsIn(value, type) {
|
|
352
|
-
if (Array.isArray(value))
|
|
353
|
-
return value.reduce((n, item) => n + itemsIn(item, type), 0);
|
|
354
|
-
if (!isPlain(value))
|
|
355
|
-
return 0;
|
|
356
|
-
return (value.type === type ? 1 : 0) + Object.values(value).reduce((n, item) => n + itemsIn(item, type), 0);
|
|
357
|
-
}
|
|
358
|
-
/**
|
|
359
|
-
* The input tokens the provider bills for `body` that it does not carry (`providerInputOverhead`, with its sources). The
|
|
360
|
-
* Responses API documents no prompt of its own that it adds on these routes (no hosted tool passes the policy but a
|
|
361
|
-
* session's live web search, below), and the framing it puts around each input item and tool definition is a few tokens
|
|
362
|
-
* each, fewer than the bytes of the JSON keys that item already spends in the body. An image is billed by its area, not
|
|
363
|
-
* its bytes: each counts at the most it can be billed as, in place of the bytes its data URL takes in the body. A file input (a PDF, billed by its pages) has no stated bound, so a
|
|
364
|
-
* body with one cannot be measured: this throws, and the request's input is unknown.
|
|
365
|
-
*/
|
|
366
|
-
export function responsesServerInputOverhead(body) {
|
|
367
|
-
if (itemsIn(body.input, "input_file") > 0)
|
|
368
|
-
throw new Error("a file input's billed size has no stated bound");
|
|
369
|
-
return providerInputOverhead("openai-responses", { tools: Array.isArray(body.tools) && body.tools.length > 0, images: responsesImagesIn(body.input), ...(typeof body.model === "string" ? { model: body.model } : {}) });
|
|
370
|
-
}
|
|
371
336
|
/** The text of a tool output item: a string, or the text of each of its parts. */
|
|
372
337
|
/** Codex's status header of a tool output: the text it starts with (its first part), never what the script printed after it. */
|
|
373
338
|
function statusText(item) {
|
|
@@ -569,7 +534,6 @@ export function addResponsesNote(body, text) {
|
|
|
569
534
|
}
|
|
570
535
|
export function codexPolicy(options) {
|
|
571
536
|
const allowed = new Set(options.tools);
|
|
572
|
-
const mcp = new Set(options.mcpTools ?? []);
|
|
573
537
|
const maxOutputTokens = options.maxOutputTokens ?? 32_000;
|
|
574
538
|
const search = options.webSearch === "live";
|
|
575
539
|
return {
|
|
@@ -604,19 +568,21 @@ export function codexPolicy(options) {
|
|
|
604
568
|
watch: options.announce ? () => watchResponse(options.announce) : undefined,
|
|
605
569
|
unwatched: options.announce ? () => options.announce.failed() : undefined,
|
|
606
570
|
modelOf: (body) => (typeof body.model === "string" ? body.model : undefined),
|
|
607
|
-
// The content a web search feeds the model is billed as input, and neither it nor the searches one response runs has a
|
|
608
|
-
// stated bound: a body that offers web search has no input bound (undefined), so its input is unmeasured.
|
|
609
571
|
outputAsked: responsesOutputAsked,
|
|
610
572
|
outputLeast: responsesOutputLeast,
|
|
611
573
|
reasoningHidden: (body) => responsesReasoningHidden(body, maxOutputTokens),
|
|
612
574
|
reasoningBytesOf: responsesReasoningBytes,
|
|
613
575
|
contentBytesOf: responsesContentBytes,
|
|
614
576
|
limitOutput: limitResponsesOutput,
|
|
577
|
+
// The content a web search feeds the model is billed as input, and neither it nor the searches one response runs has a
|
|
578
|
+
// stated bound: a body that offers web search has no input bound (undefined), so its input is unmeasured (and never
|
|
579
|
+
// counted into a number).
|
|
615
580
|
serverInputOverhead: search ? (body) => {
|
|
616
581
|
if (Array.isArray(body.tools) && body.tools.some((tool) => isPlain(tool) && tool.type === "web_search"))
|
|
617
582
|
return undefined;
|
|
618
|
-
return
|
|
619
|
-
} :
|
|
583
|
+
return responsesInputOverhead(body);
|
|
584
|
+
} : responsesInputOverhead,
|
|
585
|
+
countInput: OPENAI_INPUT_COUNTER,
|
|
620
586
|
};
|
|
621
587
|
/** The body the provider gets, the live search offered only when `searchNow`. */
|
|
622
588
|
function shaped(body, context, searchNow) {
|
|
@@ -644,7 +610,7 @@ export function codexPolicy(options) {
|
|
|
644
610
|
out.text = textOptions(out.text);
|
|
645
611
|
// Without the search now, its tool is dropped as a session without one drops it (DROPPED_TOOLS).
|
|
646
612
|
if (out.tools !== undefined)
|
|
647
|
-
out.tools = ownTools(out.tools, own, searchNow
|
|
613
|
+
out.tools = ownTools(out.tools, own, searchNow);
|
|
648
614
|
if (out.tool_choice !== undefined)
|
|
649
615
|
out.tool_choice = toolChoice(out.tool_choice, own, searchNow);
|
|
650
616
|
if (Array.isArray(out.input) && out.input.some((item) => isPlain(item) && item.type === "additional_tools")) {
|
package/dist/host/process.d.ts
CHANGED
|
@@ -81,8 +81,6 @@ export interface SessionMachine {
|
|
|
81
81
|
announcedExec?(): string | undefined;
|
|
82
82
|
/** Told each line the rollout's tail reads, as it reads it: the harness's view of code mode follows the log from here. */
|
|
83
83
|
onRolloutLine?(listener: (line: string) => void): void;
|
|
84
|
-
/** Given the drive's hooks for a call the harness never sees (a remote MCP server's tool, mcp.ts). */
|
|
85
|
-
onCalls?(hooks: CallHooks): void;
|
|
86
84
|
/** Told when the model proxy reads that the provider cut the turn's answer at its output limit, before Codex has the
|
|
87
85
|
* piece that carries the stop (its output tokens, when the answer said them): the harness ends the turn there. */
|
|
88
86
|
onCut?(listener: (stop: {
|
|
@@ -97,14 +95,6 @@ export interface SessionMachine {
|
|
|
97
95
|
fsync(): Promise<void>;
|
|
98
96
|
close(): Promise<void>;
|
|
99
97
|
}
|
|
100
|
-
/** The drive's hooks for a call Codex runs without the harness (code-mode.ts gives them, mcp.ts uses them). */
|
|
101
|
-
export interface CallHooks {
|
|
102
|
-
/** Resolves true once the call's own line (a script's nested call: its script's) is in the log, false when it never came. */
|
|
103
|
-
barrier(callId: string): Promise<boolean>;
|
|
104
|
-
/** After a recovery: what answers a call of `tool` with `args` that already completed in the interrupted turn (a rewritten
|
|
105
|
-
* script re-issues its calls under new ids), taken once; undefined for any other call. */
|
|
106
|
-
recovered(tool: string, args: unknown): string | undefined;
|
|
107
|
-
}
|
|
108
98
|
/** What a harness's drive asks its machine factory for: the drive, the model route its proxy serves, and its deadline. */
|
|
109
99
|
export interface AcquireMachineRequest {
|
|
110
100
|
ctx: DriveContext;
|
package/dist/scripts.d.ts
CHANGED
|
@@ -58,6 +58,14 @@ export interface NestedFact {
|
|
|
58
58
|
rollout?: RolloutNested;
|
|
59
59
|
/** The host parked the call for a person's approval (`parkedKey`'s record): it did not run, whatever its record says. */
|
|
60
60
|
parked?: true;
|
|
61
|
+
/** Asked again on this resume (code-mode.ts recoverItems): it never reached its intent before, as a park at the host's gate
|
|
62
|
+
* leaves a call, and went through the gate now, the person's answer on it: what it answered, and whether it ran (a refusal
|
|
63
|
+
* never does). */
|
|
64
|
+
resumed?: {
|
|
65
|
+
text: string;
|
|
66
|
+
isError: boolean;
|
|
67
|
+
ran: boolean;
|
|
68
|
+
};
|
|
61
69
|
}
|
|
62
70
|
export type Settled = {
|
|
63
71
|
kind: "completed";
|
|
@@ -99,6 +107,9 @@ export declare function recoveryFacts<T>(execs: readonly string[], ties: readonl
|
|
|
99
107
|
/** The output a cut-off `exec` is answered with: its nested calls, in order, each with what it came to, and that nothing was run
|
|
100
108
|
* again. A completed call's effect is done, a never tool's included; a call with no end is interrupted. `loose`: calls of this turn
|
|
101
109
|
* whose script could not be told (given to the last cut-off exec only), listed apart under their own heading. */
|
|
110
|
+
/** What a dangling `wait` on a yielded exec's cell is told when calls of that script that waited for a person's approval
|
|
111
|
+
* were answered on this resume (code-mode.ts recoverItems): each call's outcome, in order. */
|
|
112
|
+
export declare function waitResumedText(cell: string, resumed: readonly NestedFact[]): string;
|
|
102
113
|
export declare function execRecoveryOutput(facts: readonly NestedFact[], loose?: readonly NestedFact[]): string;
|
|
103
114
|
/** The text of a tool's recorded output (a string, or `{ text }` with images). */
|
|
104
115
|
export declare function outputTextOf(output: unknown): string;
|
package/dist/scripts.js
CHANGED
|
@@ -124,6 +124,13 @@ const describeCall = (fact, label) => {
|
|
|
124
124
|
const settled = settle(fact);
|
|
125
125
|
if (settled.kind === "parked")
|
|
126
126
|
return `${label} was waiting for a person's approval and did not run; it was not run again.`;
|
|
127
|
+
const again = fact.resumed;
|
|
128
|
+
if (again && !again.ran)
|
|
129
|
+
return `${label} waited for a person's approval, then: ${quoted(again.text)}. It did not run.`;
|
|
130
|
+
if (again && again.isError)
|
|
131
|
+
return `${label} waited for a person's approval, then ran and failed: ${quoted(again.text)}. It was not run again.`;
|
|
132
|
+
if (again)
|
|
133
|
+
return `${label} waited for a person's approval, then ran: ${quoted(again.text)}. Its effect is done; it was not run again.`;
|
|
127
134
|
if (settled.kind === "completed")
|
|
128
135
|
return `${label} completed: ${quoted(settled.text)}. Its effect is done; it was not run again.`;
|
|
129
136
|
if (settled.kind === "failed")
|
|
@@ -136,6 +143,12 @@ const describeCall = (fact, label) => {
|
|
|
136
143
|
/** The output a cut-off `exec` is answered with: its nested calls, in order, each with what it came to, and that nothing was run
|
|
137
144
|
* again. A completed call's effect is done, a never tool's included; a call with no end is interrupted. `loose`: calls of this turn
|
|
138
145
|
* whose script could not be told (given to the last cut-off exec only), listed apart under their own heading. */
|
|
146
|
+
/** What a dangling `wait` on a yielded exec's cell is told when calls of that script that waited for a person's approval
|
|
147
|
+
* were answered on this resume (code-mode.ts recoverItems): each call's outcome, in order. */
|
|
148
|
+
export function waitResumedText(cell, resumed) {
|
|
149
|
+
const lines = resumed.map((fact, i) => describeCall(fact, `${i + 1}. ${fact.tool}`));
|
|
150
|
+
return `The session stopped while waiting on cell ${cell}; that cell's script was cut off. Its calls that waited for a person's approval were answered since, each once:\n${lines.join("\n")}\nNothing else of the script was run again. Check the actual state before relying on it.`;
|
|
151
|
+
}
|
|
139
152
|
export function execRecoveryOutput(facts, loose = []) {
|
|
140
153
|
const apart = loose.length
|
|
141
154
|
? `\n${loose.length} ${loose.length === 1 ? "call" : "calls"} ran whose script could not be told (an answer of the model's could not be read to its end):\n${loose.map((fact, i) => describeCall(fact, `${i + 1}. ${fact.tool}`)).join("\n")}`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@parcha/agentrun-harness-codex",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.38",
|
|
4
4
|
"description": "Codex as an AgentRun harness: a tool-less Codex app-server behind a loopback model proxy, durable in AgentRun's own store, with the host's tools as its only tools.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agentrun",
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
"test": "node --test --test-concurrency=8 'test/*.test.mjs'"
|
|
45
45
|
},
|
|
46
46
|
"dependencies": {
|
|
47
|
-
"@parcha/agentrun-kernel": "0.1.0-beta.
|
|
47
|
+
"@parcha/agentrun-kernel": "0.1.0-beta.38"
|
|
48
48
|
},
|
|
49
49
|
"peerDependencies": {
|
|
50
50
|
"@openai/codex": "0.164.0"
|
|
@@ -56,7 +56,7 @@
|
|
|
56
56
|
},
|
|
57
57
|
"devDependencies": {
|
|
58
58
|
"@openai/codex": "0.164.0",
|
|
59
|
-
"@parcha/agentrun-dsl": "0.1.0-beta.
|
|
59
|
+
"@parcha/agentrun-dsl": "0.1.0-beta.38"
|
|
60
60
|
},
|
|
61
61
|
"repository": {
|
|
62
62
|
"type": "git",
|
package/dist/mcp.d.ts
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import { type McpClient, type SessionMcp } from "@parcha/agentrun-kernel";
|
|
2
|
-
import type { TomlValue } from "./config.js";
|
|
3
|
-
import type { DriveContext } from "./host/kernel.js";
|
|
4
|
-
import { type CallHooks } from "./host/process.js";
|
|
5
|
-
/** Codex's own MCP client: it sends a call's id in tools/call's `_meta.callId`, its `mcpToolCall` item's id
|
|
6
|
-
* (codex-rs core/src/mcp_tool_call.rs at rust-v0.164.0), the id the drive records the call by. */
|
|
7
|
-
export declare const CODEX_MCP_CLIENT: McpClient;
|
|
8
|
-
/** The `mcp_servers` table for `mcp`'s servers at the proxy `modelUrl`, Codex's bearer read from `keyEnv` (the env var
|
|
9
|
-
* that holds the session's key). No `tool_timeout_sec`: Codex's 300 s default covers the gateway's own bound on one
|
|
10
|
-
* call (120 s), and a call that needs a person parks and ends the turn, never waits at the proxy. */
|
|
11
|
-
export declare function mcpServersConfig(mcp: SessionMcp, modelUrl: string, keyEnv: string): Record<string, TomlValue>;
|
|
12
|
-
/** `mcp` with each call recorded in the drive's session as a built-in's, `mcp__<server>__<tool>` under Codex's call id:
|
|
13
|
-
* its intent once `barrier` has its line in the log and before it is sent, its outcome once it answers. A call id the
|
|
14
|
-
* records already hold is answered from them. */
|
|
15
|
-
export declare function recorded(mcp: SessionMcp, ctx: DriveContext, hooks: () => CallHooks | undefined): SessionMcp;
|
package/dist/mcp.js
DELETED
|
@@ -1,74 +0,0 @@
|
|
|
1
|
-
// A session's remote MCP servers on Codex, written for AgentRun. Codex's own MCP client calls each one at the session's
|
|
2
|
-
// model proxy (`<modelUrl>/mcp/<server>`, which the kernel's proxy mounts from the session's MCP and CODEX_MCP_CLIENT),
|
|
3
|
-
// with the session's key as its bearer, so it never holds a server's credential. The session's machine
|
|
4
|
-
// (host/machine.ts) does both halves:
|
|
5
|
-
// - it writes each server in Codex's `mcp_servers` (an app may not: config.ts RESERVED_CONFIG_KEYS), with only the
|
|
6
|
-
// granted tools. Each call is allowed without asking (`default_tools_approval_mode = "approve"`): the proxy is the
|
|
7
|
-
// one gate, and under Codex's default a tool with no `readOnlyHint` is refused when nobody is there to approve it.
|
|
8
|
-
// Each server is `required`, and its endpoint is the proxy, which answers `initialize` and `tools/list` itself from
|
|
9
|
-
// the grant: the thread starts with every granted tool, and a remote server that can't be reached shows at the first
|
|
10
|
-
// call, as that call's error result. Only a proxy route Codex can't reach fails the thread's start.
|
|
11
|
-
// - it records each call (`recorded`). Codex sends a call to the proxy as soon as it starts the call's item, and waits
|
|
12
|
-
// for nothing of ours, so the proxy writes the call's intent in the session's records itself, by Codex's own call id
|
|
13
|
-
// (`_meta.callId`), before anything is sent, and its outcome after. A call a crash cut off is then answered
|
|
14
|
-
// interrupted from the records, never sent twice.
|
|
15
|
-
import { HOST_RESULT_MAX_CHARS } from "@parcha/agentrun-kernel";
|
|
16
|
-
import { BuiltinCalls, toolKey } from "./host/process.js";
|
|
17
|
-
import { markParked } from "./scripts.js";
|
|
18
|
-
/** Codex's own MCP client: it sends a call's id in tools/call's `_meta.callId`, its `mcpToolCall` item's id
|
|
19
|
-
* (codex-rs core/src/mcp_tool_call.rs at rust-v0.164.0), the id the drive records the call by. */
|
|
20
|
-
export const CODEX_MCP_CLIENT = { callIdMeta: "callId" };
|
|
21
|
-
/** What a call answers when its line never reached the log: nothing was sent, and it may be made again. */
|
|
22
|
-
const LAGGING = "Not sent: the session's log had not caught up with this call yet. Nothing reached the MCP server; make the same call again.";
|
|
23
|
-
/** The `mcp_servers` table for `mcp`'s servers at the proxy `modelUrl`, Codex's bearer read from `keyEnv` (the env var
|
|
24
|
-
* that holds the session's key). No `tool_timeout_sec`: Codex's 300 s default covers the gateway's own bound on one
|
|
25
|
-
* call (120 s), and a call that needs a person parks and ends the turn, never waits at the proxy. */
|
|
26
|
-
export function mcpServersConfig(mcp, modelUrl, keyEnv) {
|
|
27
|
-
return Object.fromEntries(mcp.servers.map((server) => [server.name, {
|
|
28
|
-
url: `${modelUrl}/mcp/${server.name}`,
|
|
29
|
-
bearer_token_env_var: keyEnv,
|
|
30
|
-
enabled_tools: server.tools.map((tool) => tool.name),
|
|
31
|
-
required: true,
|
|
32
|
-
default_tools_approval_mode: "approve",
|
|
33
|
-
}]));
|
|
34
|
-
}
|
|
35
|
-
const said = (text, isError) => ({ content: [{ type: "text", text }], ...(isError ? { isError: true } : {}) });
|
|
36
|
-
/** `mcp` with each call recorded in the drive's session as a built-in's, `mcp__<server>__<tool>` under Codex's call id:
|
|
37
|
-
* its intent once `barrier` has its line in the log and before it is sent, its outcome once it answers. A call id the
|
|
38
|
-
* records already hold is answered from them. */
|
|
39
|
-
export function recorded(mcp, ctx, hooks) {
|
|
40
|
-
// Each outcome is kept whole, up to the host's bound on a tool result, the most the door hands Codex: a call answered
|
|
41
|
-
// again from the records reads what the server said, never the step's default cut.
|
|
42
|
-
const calls = new BuiltinCalls(ctx, { outputChars: HOST_RESULT_MAX_CHARS });
|
|
43
|
-
return {
|
|
44
|
-
servers: mcp.servers,
|
|
45
|
-
async call(server, tool, args, context) {
|
|
46
|
-
const callId = context.callId;
|
|
47
|
-
if (!callId)
|
|
48
|
-
return said("Not sent: the call carried no call id to record it by. Nothing reached the MCP server.", true);
|
|
49
|
-
const name = `mcp__${server}__${tool}`;
|
|
50
|
-
// A call the interrupted turn already completed, re-issued by a rewritten script under a new id: answered from the log.
|
|
51
|
-
const again = hooks()?.recovered(name, args);
|
|
52
|
-
if (again !== undefined)
|
|
53
|
-
return said(again, false);
|
|
54
|
-
let start;
|
|
55
|
-
try {
|
|
56
|
-
// The call's own line in the log before its intent, as a built-in's (code-mode.ts holds the barrier).
|
|
57
|
-
if (!ctx.isMemoized(toolKey(callId)) && !(await (hooks()?.barrier(callId) ?? false)))
|
|
58
|
-
return said(LAGGING, true);
|
|
59
|
-
start = await calls.begin({ callId, name, input: args, replay: "never" });
|
|
60
|
-
}
|
|
61
|
-
catch {
|
|
62
|
-
return said("Not sent: the session could not record the call. Nothing reached the MCP server.", true);
|
|
63
|
-
}
|
|
64
|
-
if (!start.run)
|
|
65
|
-
return said(start.result.text, start.result.isError === true);
|
|
66
|
-
const result = await mcp.call(server, tool, args, context);
|
|
67
|
-
// A call the host parked for a person's approval did not run: recorded so before its answer, the waiting text.
|
|
68
|
-
if (result.parked)
|
|
69
|
-
await markParked(ctx, callId).catch(() => { });
|
|
70
|
-
await calls.end(callId, { text: result.content.map((block) => block.text).join("\n\n"), isError: result.isError === true }).catch(() => { });
|
|
71
|
-
return result;
|
|
72
|
-
},
|
|
73
|
-
};
|
|
74
|
-
}
|