@parcha/agentrun-harness-codex 0.1.0-beta.37 → 0.1.0-beta.39

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/dist/scripts.js CHANGED
@@ -1,3 +1,16 @@
1
+ // Which code-mode script a host tool's nested call belongs to. Written for AgentRun.
2
+ //
3
+ // A host tool a code-mode model's script calls arrives on the app-server's stream as a call under an id of Codex's own
4
+ // (`exec-<uuid>`) that carries no parent, no cell and no `exec` id, and the rollout holds no line for it until after it is
5
+ // answered. So the call is tied to the one script that can be running, and that is read from two places that cannot be
6
+ // ahead of Codex:
7
+ // - the rollout: an `exec` call line opens a script, and it stays open until an output says it finished: its own, or, when
8
+ // that says "Script running with cell ID N" (it yielded and went on), the output of the `wait` that finishes cell N;
9
+ // - the model proxy: the `exec` the latest answer carried, which it read before Codex had that part of the answer, so
10
+ // before the `exec`'s line could be in the rollout.
11
+ // The proxy offers no `exec` while a cell runs and no parallel calls, so one script is live at a time. A model that writes an
12
+ // `exec` anyway makes two live, and then a nested call cannot be told from the other's.
13
+ import { HOST_RESULT_MAX_CHARS } from "@parcha/agentrun-kernel";
1
14
  import { boundResult } from "./host/process.js";
2
15
  import { parseLine } from "./rollout.js";
3
16
  /** The id Codex gives a host tool called from a code-mode script. */
@@ -9,6 +22,9 @@ export const UNWATCHED = "(unwatched answer)";
9
22
  const statusOf = (output) => typeof output === "string" ? output : Array.isArray(output) && typeof output[0]?.text === "string" ? output[0].text : "";
10
23
  /** A cell that yielded and still runs, as its status header says. */
11
24
  const RUNNING = /^Script running with cell ID (\S+)/;
25
+ /** A script that failed (it threw, or its cell was gone), as its status header says. The rollout's output line has no
26
+ * status field of its own: this header is the only place Codex says how a script ended. */
27
+ const FAILED = /^Script failed\b/;
12
28
  const textOf = (output) => typeof output === "string" ? output : Array.isArray(output) ? output.map((part) => (typeof part?.text === "string" ? part.text : "")).join("\n") : "";
13
29
  export class Scripts {
14
30
  open = [];
@@ -16,27 +32,31 @@ export class Scripts {
16
32
  done = new Set();
17
33
  /** The cell each `wait` call in the rollout resumes. */
18
34
  waitsOn = new Map();
19
- /** Reads one rollout line. */
35
+ /** Reads one rollout line: what it says of a script, if anything. A script opened (its `exec` line, with its input, the
36
+ * script) or finished (the output that ended it: its own, or the `wait`'s on its cell). */
20
37
  note(line) {
21
38
  if (!line.includes("call_id"))
22
- return;
39
+ return undefined;
23
40
  const p = parseLine(line)?.payload;
24
41
  if (!p || typeof p.call_id !== "string")
25
- return;
42
+ return undefined;
26
43
  const id = p.call_id;
27
44
  const running = RUNNING.exec(statusOf(p.output));
28
45
  if (p.type === "custom_tool_call" && p.name === "exec") {
29
- if (!this.open.some((x) => x.exec === id))
30
- this.open.push({ exec: id });
46
+ if (this.open.some((x) => x.exec === id))
47
+ return undefined;
48
+ const input = typeof p.input === "string" ? p.input : "";
49
+ this.open.push({ exec: id, input });
50
+ return { kind: "opened", exec: id, input };
31
51
  }
32
52
  else if (p.type === "custom_tool_call_output") {
33
53
  const at = this.open.findIndex((x) => x.exec === id);
34
54
  if (at < 0)
35
- return;
55
+ return undefined;
36
56
  if (running)
37
57
  this.open[at].cell = running[1];
38
58
  else
39
- this.done.add(this.open.splice(at, 1)[0].exec);
59
+ return this.finish(at, p.output);
40
60
  }
41
61
  else if (p.type === "function_call" && p.name === "wait") {
42
62
  try {
@@ -49,8 +69,22 @@ export class Scripts {
49
69
  else if (p.type === "function_call_output" && this.waitsOn.has(id) && !running) {
50
70
  const at = this.open.findIndex((x) => x.cell === this.waitsOn.get(id));
51
71
  if (at >= 0)
52
- this.done.add(this.open.splice(at, 1)[0].exec);
72
+ return this.finish(at, p.output);
53
73
  }
74
+ return undefined;
75
+ }
76
+ finish(at, output) {
77
+ const exec = this.open.splice(at, 1)[0].exec;
78
+ this.done.add(exec);
79
+ return { kind: "finished", exec, output: textOf(output), failed: FAILED.test(statusOf(output)) };
80
+ }
81
+ /** The unfinished `exec` that yielded on cell `cell`, if any. */
82
+ execOn(cell) {
83
+ return this.open.find((x) => x.cell === cell)?.exec;
84
+ }
85
+ /** The script of an unfinished `exec` whose line the rollout holds; none for any other. */
86
+ inputOf(exec) {
87
+ return this.open.find((x) => x.exec === exec)?.input;
54
88
  }
55
89
  /** The scripts that may call a host tool now: the rollout's unfinished ones, and the `exec` the proxy's latest answer carried
56
90
  * if it is not among them and has not finished (its line may not be in the rollout yet). */
@@ -109,7 +143,71 @@ export function settle(fact) {
109
143
  return stored.kind === rolled.kind && (rolled.text === stored.text || rolled.text === boundResult(stored.text).text || (store?.sent !== undefined && rolled.text === store.sent)) ? stored : { kind: "interrupted" };
110
144
  return stored ?? rolled ?? { kind: "interrupted" };
111
145
  }
112
- const quoted = (text) => JSON.stringify(text.length > 2000 ? `${text.slice(0, 2000)}… [${text.length - 2000} more characters]` : text);
146
+ /** The most a recovered script's output holds (a cut-off `exec`'s, or the `wait` on its cell): one result at the host's bound, as
147
+ * the script was handed it, and the words that tell each call's outcome around it. It stands in for the script's own output,
148
+ * which the model reads as one tool result. Past it, every result it quotes is cut to the same share, each keeping its start
149
+ * and its last line (a filed answer's says where the whole is) and saying where it was cut (`cut`): never silently, and every
150
+ * call's outcome is still told. Only when the lines alone pass it is the output itself cut, with its note: the calls past
151
+ * the cut are not in it, and the recovery note does not say they are (`Recovered.shown`). */
152
+ export const EXEC_RECOVERY_MAX_CHARS = HOST_RESULT_MAX_CHARS + 2_000;
153
+ /** A last line longer than this is not kept when a result is cut: it is the result's own text, not a pointer to the rest. */
154
+ const LAST_LINE_MAX = 1_000;
155
+ /** `text` within `cap` characters: whole when it fits; else its start, a line saying where it was cut (as `boundResult`'s
156
+ * does), and its last line when that is short (a filed answer's, which says where the whole is), never splitting a
157
+ * character written as a surrogate pair. Whole, too, when the cut would be no shorter (a short result is never swapped
158
+ * for a longer line saying it was cut). `kept`: how much of the start of `text` is there. */
159
+ function cut(text, cap) {
160
+ if (text.length <= cap)
161
+ return { text, kept: text.length };
162
+ const at = text.lastIndexOf("\n");
163
+ const last = at >= 0 && text.length - at <= LAST_LINE_MAX ? text.slice(at) : "";
164
+ const note = (kept) => `\n[cut at ${kept} of ${text.length} characters]`;
165
+ let kept = Math.max(0, cap - note(cap).length - last.length);
166
+ if (kept > 0 && (text.charCodeAt(kept - 1) & 0xfc00) === 0xd800 && (text.charCodeAt(kept) & 0xfc00) === 0xdc00)
167
+ kept -= 1;
168
+ const short = `${text.slice(0, kept)}${note(kept)}${last}`;
169
+ return short.length < text.length ? { text: short, kept } : { text, kept: text.length };
170
+ }
171
+ /** A told call's line, the text it quotes held to `cap`. */
172
+ const lineOf = (told, cap) => (told.text === undefined ? `${told.head}${told.tail}` : `${told.head}${JSON.stringify(cut(told.text, cap).text)}${told.tail}`);
173
+ /** A recovered output built by `build` from its calls' lines (`told`, in the order `build` writes them) at a cap on each
174
+ * quoted text: whole when it fits in EXEC_RECOVERY_MAX_CHARS; else at the largest cap that fits (the same for every quoted
175
+ * text); else, the lines alone passing the bound, the output cut to the bound with its note, and the calls past the cut
176
+ * not in it. */
177
+ function fitted(told, build) {
178
+ const at = (cap, output, limit = output.length) => {
179
+ const shown = [];
180
+ let from = 0;
181
+ for (const t of told) {
182
+ const line = lineOf(t, cap);
183
+ const pos = output.indexOf(line, from);
184
+ if (pos < 0 || pos + line.length > limit)
185
+ break;
186
+ from = pos + line.length;
187
+ if (t.shows && t.callId !== undefined && (t.text === undefined || t.text === "" || cut(t.text, cap).kept > 0))
188
+ shown.push(t.callId);
189
+ }
190
+ return { output, shown };
191
+ };
192
+ const whole = build(Number.POSITIVE_INFINITY);
193
+ if (whole.length <= EXEC_RECOVERY_MAX_CHARS)
194
+ return at(Number.POSITIVE_INFINITY, whole);
195
+ const least = build(0);
196
+ if (least.length > EXEC_RECOVERY_MAX_CHARS) {
197
+ const { text, kept } = cut(least, EXEC_RECOVERY_MAX_CHARS);
198
+ return at(0, text, kept);
199
+ }
200
+ let lo = 0;
201
+ let hi = whole.length;
202
+ while (lo < hi) {
203
+ const mid = Math.ceil((lo + hi) / 2);
204
+ if (build(mid).length <= EXEC_RECOVERY_MAX_CHARS)
205
+ lo = mid;
206
+ else
207
+ hi = mid - 1;
208
+ }
209
+ return at(lo, build(lo));
210
+ }
113
211
  /** The nested calls to list for each cut-off `exec` of the interrupted turn `since`: its own, in order; and the calls whose
114
212
  * script could not be told, which ran in that turn, under the LAST cut-off exec only, apart from its own, so each is listed once. */
115
213
  export function recoveryFacts(execs, ties, since, factOf) {
@@ -120,32 +218,94 @@ export function recoveryFacts(execs, ties, since, factOf) {
120
218
  out.set(exec, { own: ties.filter((t) => t.exec === exec).map(factOf), loose: exec === last ? loose : [] });
121
219
  return out;
122
220
  }
221
+ /** What a call of a recovered script came to, as its line tells it. A result or an error it quotes is the one the script was
222
+ * handed live: held to the host's bound as the bridge holds it (`boundResult`); the session's record keeps it whole. */
123
223
  const describeCall = (fact, label) => {
124
224
  const settled = settle(fact);
225
+ const shows = outcomeShown(fact);
226
+ const told = (head, text, tail) => ({ head, text: boundResult(text).text, tail, callId: fact.callId, shows });
125
227
  if (settled.kind === "parked")
126
- return `${label} was waiting for a person's approval and did not run; it was not run again.`;
228
+ return { head: `${label} was waiting for a person's approval and did not run; it was not run again.`, tail: "" };
229
+ const again = fact.resumed;
230
+ if (again && !again.ran)
231
+ return told(`${label} waited for a person's approval, then: `, again.text, ". It did not run.");
232
+ if (again && again.isError)
233
+ return told(`${label} waited for a person's approval, then ran and failed: `, again.text, ". It was not run again.");
234
+ if (again)
235
+ return told(`${label} waited for a person's approval, then ran: `, again.text, ". Its effect is done; it was not run again.");
127
236
  if (settled.kind === "completed")
128
- return `${label} completed: ${quoted(settled.text)}. Its effect is done; it was not run again.`;
237
+ return told(`${label} completed: `, settled.text, ". Its effect is done; it was not run again.");
129
238
  if (settled.kind === "failed")
130
- return `${label} failed: ${quoted(settled.text)}. It was not run again.`;
239
+ return told(`${label} failed: `, settled.text, ". It was not run again.");
131
240
  // Told as the recovery note of the same turn tells it, which reaches the model with this output: a safe tool's call a crash cut off.
132
241
  if (fact.told === "retryable")
133
- return `${label} was started and did not report a result. It is safe to repeat. It was not run again.`;
134
- return `${label} was started and did not report a result, so it may have taken effect: check before calling it again. It was not run again.`;
242
+ return { head: `${label} was started and did not report a result. It is safe to repeat. It was not run again.`, tail: "" };
243
+ return { head: `${label} was started and did not report a result, so it may have taken effect: check before calling it again. It was not run again.`, tail: "" };
135
244
  };
245
+ /** Whether a recovered script's output tells what the call came to, its result or its error (a call that waited for a person's
246
+ * approval, then was answered, included): the recovery note then says the outcome is there, not that it is not shown. */
247
+ export function outcomeShown(fact) {
248
+ if (fact.resumed)
249
+ return true;
250
+ const kind = settle(fact).kind;
251
+ return kind === "completed" || kind === "failed";
252
+ }
136
253
  /** 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
254
  * 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
255
  * whose script could not be told (given to the last cut-off exec only), listed apart under their own heading. */
256
+ /** What a dangling `wait` on a yielded exec's cell is told when calls of that script that waited for a person's approval
257
+ * were answered on this resume (code-mode.ts recoverItems): each call's outcome, in order. */
258
+ export function waitResumedText(cell, resumed) {
259
+ return waitResumed(cell, resumed).output;
260
+ }
261
+ /** waitResumedText, and the calls whose outcome it tells. */
262
+ export function waitResumed(cell, resumed) {
263
+ const told = resumed.map((fact, i) => describeCall(fact, `${i + 1}. ${fact.tool}`));
264
+ return fitted(told, (cap) => `${waitCutOpener(cell)}${told.map((t) => lineOf(t, cap)).join("\n")}\nNothing else of the script was run again. Check the actual state before relying on it.`);
265
+ }
266
+ /** The words a resumed `wait`'s output opens with (waitResumed): the model is told its cell's script went with the session. */
267
+ const waitCutOpener = (cell) => `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`;
268
+ /** The words a cut-off `exec`'s output opens with when it lists its own calls (execRecovery). */
269
+ const EXEC_CUT_OPENER = "The exec was cut short after these calls (the session stopped), and nothing was run again. Their outcomes, in order:\n";
270
+ /** What the host's row of an `exec` a recovery answered shows: the model is told its script was cut short, but on the record
271
+ * those words belong to an exec that failed (recoveredFailed). One that ended ok shows its calls' outcomes alone. */
272
+ export function recoveredRowText(output, failed) {
273
+ if (failed)
274
+ return output;
275
+ const cell = /^The session stopped while waiting on cell (\S+);/.exec(output)?.[1];
276
+ const opener = cell === undefined ? EXEC_CUT_OPENER : waitCutOpener(cell);
277
+ return output.startsWith(opener) ? output.slice(opener.length) : output;
278
+ }
279
+ /** Whether a cut-off `exec` answered with its recovered output (execRecovery) failed, by the rule a codemode script stopped
280
+ * and run again follows on every other harness (serve's runner/meta-tools.ts endedWith): it failed when its last call did
281
+ * not run (a person refused it, or a park was never answered), was cut off before it reported, or failed; or when it made
282
+ * no call of its own. A script whose last call ran and answered (one that parked and was allowed, too) was stopped and
283
+ * resumed, not failed. `own`: its calls, in order. */
284
+ export function recoveredFailed(own) {
285
+ const last = own.at(-1);
286
+ if (!last)
287
+ return true;
288
+ if (last.resumed)
289
+ return !last.resumed.ran || last.resumed.isError;
290
+ return settle(last).kind !== "completed";
291
+ }
139
292
  export function execRecoveryOutput(facts, loose = []) {
140
- const apart = loose.length
141
- ? `\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")}`
142
- : "";
143
- if (facts.length === 0 && loose.length > 0)
144
- return `The exec was cut short, and no call of its own was recorded; the calls below ran, though which script made them could not be told, so do not run it again to find out.${apart}`;
145
- if (facts.length === 0)
146
- return `The exec was cut short before any tool call of it was recorded; it ran none. Run it again if it is still needed.`;
147
- const lines = facts.map((fact, i) => describeCall(fact, `${i + 1}. ${fact.tool}`));
148
- return `The exec was cut short after these calls (the session stopped), and nothing was run again. Their outcomes, in order:\n${lines.join("\n")}${apart}`;
293
+ return execRecovery(facts, loose).output;
294
+ }
295
+ /** execRecoveryOutput, and the calls whose outcome it tells: only those the recovery note may say are above. */
296
+ export function execRecovery(facts, loose = []) {
297
+ if (facts.length === 0 && loose.length === 0)
298
+ return { output: `The exec was cut short before any tool call of it was recorded; it ran none. Run it again if it is still needed.`, shown: [] };
299
+ const own = facts.map((fact, i) => describeCall(fact, `${i + 1}. ${fact.tool}`));
300
+ const others = loose.map((fact, i) => describeCall(fact, `${i + 1}. ${fact.tool}`));
301
+ return fitted([...own, ...others], (cap) => {
302
+ const apart = others.length
303
+ ? `\n${others.length} ${others.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${others.map((t) => lineOf(t, cap)).join("\n")}`
304
+ : "";
305
+ if (own.length === 0)
306
+ return `The exec was cut short, and no call of its own was recorded; the calls below ran, though which script made them could not be told, so do not run it again to find out.${apart}`;
307
+ return `${EXEC_CUT_OPENER}${own.map((t) => lineOf(t, cap)).join("\n")}${apart}`;
308
+ });
149
309
  }
150
310
  /** The text of a tool's recorded output (a string, or `{ text }` with images). */
151
311
  export function outputTextOf(output) {
@@ -4,6 +4,11 @@ import { CODEX_VERSION } from "./binary.js";
4
4
  export { CODEX_VERSION };
5
5
  /** The install line for the pinned release (npm installs this platform's binary package with it). */
6
6
  export declare const CODEX_INSTALL = "npm install --save-exact @openai/codex@0.164.0";
7
+ /** The input tokens the pinned Codex (0.164.0) sends in its first model request before the agent's own prompt: its own
8
+ * instructions and tool definitions. Measured from billing, not counted: a Codex run on gpt-6.1-sol wrote 12,198 tokens
9
+ * to the provider's cache on its first request, so about 12,200. The facts' `baseInputTokens`: a save under a cap
10
+ * prices a least step on it. Re-measure on a Codex bump. */
11
+ export declare const CODEX_BASE_INPUT_TOKENS = 12200;
7
12
  /**
8
13
  * npm's integrity of the pinned launcher and of each platform package (an npm alias of
9
14
  * `@openai/codex@<version>-<platform>`), as the registry publishes them. npm checks a download against the lockfile's
package/dist/versions.js CHANGED
@@ -6,6 +6,11 @@ import { CODEX_VERSION } from "./binary.js";
6
6
  export { CODEX_VERSION };
7
7
  /** The install line for the pinned release (npm installs this platform's binary package with it). */
8
8
  export const CODEX_INSTALL = `npm install --save-exact @openai/codex@${CODEX_VERSION}`;
9
+ /** The input tokens the pinned Codex (0.164.0) sends in its first model request before the agent's own prompt: its own
10
+ * instructions and tool definitions. Measured from billing, not counted: a Codex run on gpt-6.1-sol wrote 12,198 tokens
11
+ * to the provider's cache on its first request, so about 12,200. The facts' `baseInputTokens`: a save under a cap
12
+ * prices a least step on it. Re-measure on a Codex bump. */
13
+ export const CODEX_BASE_INPUT_TOKENS = 12_200;
9
14
  /**
10
15
  * npm's integrity of the pinned launcher and of each platform package (an npm alias of
11
16
  * `@openai/codex@<version>-<platform>`), as the registry publishes them. npm checks a download against the lockfile's
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-harness-codex",
3
- "version": "0.1.0-beta.37",
3
+ "version": "0.1.0-beta.39",
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.37"
47
+ "@parcha/agentrun-kernel": "0.1.0-beta.39"
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.37"
59
+ "@parcha/agentrun-dsl": "0.1.0-beta.39"
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
- }