@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/CHANGELOG.md CHANGED
@@ -2,6 +2,55 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## 0.1.0-beta.39 (2026-11-16)
6
+
7
+ - A Codex or OpenCode request straight to OpenAI is no longer counted by OpenAI before it is sent: it is held at the kernel's local o200k_base count with its margin, as a request through a gateway already is, so it never waits up to 3 seconds on `POST /v1/responses/input_tokens` first. A capped run on such a route may pause a little sooner than it did on OpenAI's exact count; the cap is still never passed.
8
+ - Breaking, for a host of the kernel: `OPENAI_INPUT_COUNTER` is gone. A `ProviderPolicy` that named it as `countInput` drops it and sets `countInputLocally: responsesLocalInputTokens`. Anthropic's count (`countInput` on the claude-agent policy) is unchanged.
9
+ - A server with no model key can run codex and pi on a person's ChatGPT plan. The owner signs in under `/settings/chatgpt` (OpenAI's Sign in with ChatGPT through pi-ai's own flow, finished by the loopback callback or by pasting the address the sign-in tab ended on), and models named `chatgpt/<id>` go to OpenAI's Responses API on the plan's token, billed to the plan with no price here.
10
+ - `GET /settings/chatgpt`, `POST /settings/chatgpt/sign-in`, `POST /settings/chatgpt/sign-in/finish` and `DELETE /settings/chatgpt` (owner session only). A bad or stale pasted address is a 400 in words. Sign-out revokes the session at OpenAI, then removes it.
11
+ - The sign-in is sealed in one row and read per request by the server and every runner, in their own processes or containers. A token renews once across all of them, 5 minutes before it ends: one holder takes a lease on the row (a compare-and-set on its sealed bytes, `SealedKeys.replaceIf`), and the others adopt the pair it writes back, so a refresh token is never used twice. A renewal sent with no answer read holds the lease to its end, since its refresh token may be spent; a fault OpenAI answers gives it back. A sign-out during a renewal stays. A refused renewal marks the sign-in expired, and runs on it fail at once in words. A 401 from OpenAI, in a pi turn or a workflow's model node, renews the token on the next request when the row still holds it.
12
+ - Capabilities say per harness whether it runs on the plan: pi and codex do, Claude Agent and OpenCode still need a key. Models list `source: "chatgpt"`.
13
+ - On the plan, the Codex policy sends no `max_output_tokens` and none of the keys the plan does not take, refuses a system-role message in words, and names its originator. Its turns are booked with `billing: "plan"` and no cost.
14
+ - Kernel: a model proxy's credential may throw `CredentialUnavailable` to refuse a request in the host's words (`code: "credential_unavailable"`), and `credentialRefused` tells the host the credential a provider answered 401 to.
15
+ - A capped run on a model whose tokenizer is o200k_base, reached over Messages without Anthropic's count (pi on GPT-6.1 Sol through OpenRouter, sent through serve's translation), bounds each request's input by a local count with its stated margin, as a Responses request to a gateway already does. Before, its bytes were the bound: after a few long pages the body passed 272,000 bytes, every rate was priced at Sol's long-context tier, and a $1.50 run stopped at $0.10-0.27 because the cap refused to send a step it could pay for. A Claude model, a body with a document, or one that offers the hosted search keeps the provider count or the byte bound.
16
+ When a run's cap is below what its model needs for one more step and an answer, the wrap-up's words now say so with both amounts, and the effort the model's request asked for when it named one ("This run's cap of $0.25 is below what gpt-6.1-sol at medium effort needs for one more step and an answer, about $0.32."), so a run that stopped its tools at its first call shows the cap was the cause. The rule that decides when a run wraps up has not changed.
17
+ Saving an agent with a cap below that figure (POST /agents, an edit of its definition, or a package install with a per-run budget) now saves with a warning on `definition.max_cost_usd` ("This agent's cap of $0.25 is below what gpt-6.1-sol at medium effort needs for one more step and an answer, about $0.32: a run will wrap up at its first tool call."). It is never refused. The figure is priced on the first request the agent's harness sends: the harness's own input before the agent's prompt (Codex about 12,200 tokens, from billing; Claude Agent, OpenCode and pi measured on their pinned builds, each stated beside its pin), the agent's prompt where the model's tokenizer is o200k_base, and the least output at the agent's effort, its thinking included: a pi agent on a Claude model that thinks with a budget is priced with Claude's 1,024-token thinking minimum, as its first request asks for it.
18
+ - Two fixes to how a Codex code-mode `exec` reads on the timeline, and one line in the desktop and phone skills. An exec that ends ok after its call parked on a person's approval and then ran shows its calls' outcomes alone, without "The exec was cut short after these calls (the session stopped)" or a resumed wait's "that cell's script was cut off". The model is still told those words, and an exec that failed still shows them. An exec the run's end closes, because nothing else ended it (the run stopped while its call waited for approval, or a crash whose next claim never resumed Codex's thread), now reads "Using tool: exec interrupted" with no status (`tool_status` null), never failed: a park or a stop failed nothing. A call a crash cut off still reads failed. The skills' "On Codex" paragraph now says Codex's exec has no top-level `return`, so a script's output goes through `text(...)`.
19
+ - Two fixes to how a Codex code-mode `exec` reads after a park or a crash, and one to pi's wording. A Codex exec's end row now sorts after the rows of the calls its script made: a crash leaves the exec open on the run's record, and Codex's recovered answer to it ends it after the resume. An exec whose call parked on a person's approval and then ran reads ok, with the stopped-and-resumed text, as a codemode script that parked reads on pi and claude-agent, never failed. An exec cut off mid-call still reads failed, after its cut call's row. The same holds for an exec that yielded and was finished by the model's pending `wait` on its cell: it reads ok when its parked call was allowed and ran, and failed when that call was refused or the wait was told the script was cut off. A recovered exec's outcome is saved in the session's log before Codex is answered, so a second crash before its end is recorded still ends it as that outcome says. An exec that no answer of Codex's ends (its run stopped while its call waited for approval, or a crash whose next drive never resumed Codex's thread) is closed with the run, "interrupted", after its calls' rows, never left open or shown failed ahead of them. A computer_op refused before it ran is named on the timeline by its op ("Refused: files.write"), never by "computer_op" or by its arguments, on every harness. On pi, a script's call a crash cut off now reads "interrupted: the process running it stopped before it reported an outcome; it may or may not have taken effect", the words claude-agent, opencode and Codex already give it. On Codex, a computer_op answer stays text, because Codex 0.164.0's code mode hands a script one string and never throws on a tool's reply. The desktop and phone kind skills now say how to read it: an op that ran answers JSON to parse, and a refused op answers the gate's words, which open with `Permission denied:` or `The user denied this`, or give the tool's name then `is read-only for this agent, so this call was refused:` or `can't be called:`.
20
+ - On Codex in code mode, a tool call that finished in the same script as a call waiting for approval now keeps its whole result when the run goes on. Before, the script was cut when the run paused, and on the resume the model got each finished call's result cut to its first 2,000 characters, with a note saying the output of those calls was not shown. So it ran a long read again.
21
+ - A finished call's result, or a failed call's error, comes back as the script got it live: up to the same 120,000-character bound every tool result has, with the usual line saying where it was cut past that.
22
+ - The recovered script output as a whole stays within that bound plus 2,000 characters for the words around the results. Past it, every result in it is cut to the same share, each keeping its start and its last line (a long MCP answer's last line says where the whole answer was filed) and saying where it was cut. Every call's outcome is still told, unless the script made so many calls that their lines alone pass the bound: then the output is cut with the same note, and the recovery note says only the calls still in it are shown above.
23
+ - The recovery note says a finished or failed call's outcome is in the output of the script that made it, instead of "not shown here". A call whose outcome is not in that output (one cut mid-way) keeps the old words.
24
+ - `recoverySystemNote` takes the calls whose outcome is already shown as an optional second argument. Without it the note reads as before, so Claude Code, OpenCode and pi are unchanged.
25
+ - Three fixes to codemode's computer calls. A script call a person allowed carries its computer calls on its own result row only, not on its approval and "ran once you allowed it" rows too, so summing a run's rows counts each computer call once. A script rerun after a crash tells a recorded call whose answer has no value (a file write) by its answer's words, as it was answered live, not as `completed: null`. On Codex, a code-mode `exec` has its own rows, and each host tool call its script makes sits under it (`parent_tool_use_id`, the exec's call id), as a codemode script's calls do on pi, claude-agent and opencode; a host lends this through the new optional `SessionIO.ownCalls`. A Codex script that failed reads failed on its exec's row, never `exec: ok`.
26
+
27
+ ## 0.1.0-beta.38 (2026-11-14)
28
+
29
+ - 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.
30
+
31
+ 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.
32
+ - 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.
33
+ - Kernel: `@parcha/agentrun-kernel/host` exports `NATIVE_SEARCH_USD`. The Claude and Codex proxy policies and the runner's hosted search all read it.
34
+ - `@parcha/agentrun-harness-claude` no longer exports `CLAUDE_WEB_SEARCH_USD`; read `NATIVE_SEARCH_USD` from `@parcha/agentrun-kernel/host`.
35
+ - 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.
36
+ - `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.
37
+ - `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.
38
+ - `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.
39
+ - 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.
40
+ - 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.
41
+ - A refused call inside a script ends the script with the refusal's words.
42
+ - After a crash, a call that was cut off is told as possibly done, and it is not run again.
43
+ - 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.
44
+ - 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.
45
+ - 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.
46
+ - 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.
47
+ - 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.
48
+ - 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.
49
+ - 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.
50
+ - 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.
51
+ - 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.
52
+ - 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."
53
+
5
54
  ## 0.1.0-beta.37 (2026-11-13)
6
55
 
7
56
  - 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
@@ -26,8 +26,8 @@ const runNode = createHarnessRunner(
26
26
  answers the tool's value as JSON text, its images' data in it, for the script to `JSON.parse`; any other tool answers
27
27
  its words and a line saying how many images it returned were not sent, since in code mode an image reaches a script only
28
28
  as text (`test/code-mode-images-taken.test.mjs`). Codex's runtime takes no
29
- binding of ours, so a script that wants the `computer` object itself calls `computer_script`, which runs in the host's
30
- isolate with `computer` bound. The proxy passes `exec` and
29
+ binding of ours, so a computer run offers `computer_op` (`{op, args}`: apps, shell, files, processes, raw input)
30
+ beside the computer's tools, and a script calls it as a nested call like any other, held to the run's gate. The proxy passes `exec` and
31
31
  `wait` and drops the sub-agent and user-input tools Codex lists beside them; it keeps parallel tool calls off for a
32
32
  code-mode request, and offers no `exec` while a script that yielded still runs, so one script is live at a time. A
33
33
  nested call has an id of Codex's own (`exec-<uuid>`) that no line of the rollout carries and that names no `exec`, so
@@ -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 servers, when granted.** A session given `spec.mcp` (a host's MCP gateway) writes each server in Codex's
53
- `mcp_servers` at the proxy's `/mcp/<server>`, with the proxy key as Codex's bearer, only the granted tools enabled,
54
- approve mode and `required = true`; the proxy admits those tools in the `mcp__<server>` namespace Codex sends them in.
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
@@ -1,9 +1,15 @@
1
1
  import { type HostSkill } from "@parcha/agentrun-kernel";
2
- import type { AgentAdapter, HostTool } from "@parcha/agentrun-kernel";
3
- import { type HostTool as KernelTool } from "@parcha/agentrun-kernel/kernel";
2
+ import type { AgentAdapter } from "@parcha/agentrun-kernel";
4
3
  import { NativeJournal } from "@parcha/agentrun-kernel/process";
5
4
  import { type ConfineChild } from "./host/machine.js";
6
5
  import { type ModelProxyOptions } from "@parcha/agentrun-kernel/host";
6
+ /**
7
+ * The name Codex is given a host tool by. App-server reserves `mcp__` names for its own MCP client's tools and refuses a
8
+ * dynamic tool so named at the thread's start (`dynamic tool name is reserved`, 0.164.0, #1586), so a run's MCP tool
9
+ * (`mcp__<server>__<tool>`), a host tool like any other, is offered as `mcp_<server>__<tool>`. Every other name is
10
+ * as given. Inside the session only: the host's gate and the session's events name the call by the host's name.
11
+ */
12
+ export declare const codexToolName: (name: string) => string;
7
13
  /**
8
14
  * Codex's `tool_output_token_limit`: the host's result bound (HOST_RESULT_MAX_CHARS), as Codex counts it. Codex keeps a
9
15
  * tool's output in the model's history within its truncation policy (10,000 tokens for each model its catalog holds, less
@@ -17,6 +23,10 @@ export interface CodexProvider {
17
23
  origin: string;
18
24
  /** The provider key, read per request in this process. It never reaches Codex's process. */
19
25
  credential: () => Promise<string> | string;
26
+ /** A person's ChatGPT plan (`credential` its access token), whose rules the proxy keeps (codexPolicy's `plan`). */
27
+ plan?: boolean;
28
+ /** Told the credential a request was sent with when the provider answered 401 to it (ModelProxyOptions.credentialRefused). */
29
+ refused?: (credential: string) => void | Promise<void>;
20
30
  }
21
31
  /** Codex's own web search, as a session may turn it on: `live` (it searches the web as it runs). */
22
32
  export type CodexWebSearch = "live";
@@ -64,11 +74,6 @@ export interface CodexAdapterOptions {
64
74
  /** For tests: the fetch the model proxy forwards with. */
65
75
  fetch?: typeof fetch;
66
76
  }
67
- /** The kernel's tool for a host tool: the same name, schema and replay policy; a host's error result is the call's failure.
68
- * The call runs as a kernel effect, whose intent is durable in the session's records before `execute` is entered, so a
69
- * crash inside a `never` tool is always reported, never repeated. The copied harness's wait for Codex's own `function_call`
70
- * line before it runs such a tool is a second guard (the transcript Codex resumes from), not the one that protects it. */
71
- export declare function kernelTool(tool: HostTool): KernelTool;
72
77
  /**
73
78
  * The mirrored rollout the next drive resumes Codex from, by the harness's own rule (harness.ts, `resume`: the last
74
79
  * thread, its first line `session_meta`, its path the one the harness derives); none when it would start a new thread.
package/dist/adapter.js CHANGED
@@ -14,8 +14,7 @@ import { join } from "node:path";
14
14
  import { HOST_RESULT_MAX_CHARS, READ_SKILL_FILE, hostedTool, readSkillFileTool, skillProblems, toolSchemaProblems } from "@parcha/agentrun-kernel";
15
15
  import { abortedOutcome, openDrive, SessionHalt } from "@parcha/agentrun-kernel/kernel";
16
16
  import { pendingSubmissions } from "@parcha/agentrun-kernel/kernel";
17
- import { NativeJournal, recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
18
- import { CODEX_MCP_CLIENT } from "./mcp.js";
17
+ import { bridgeTool, NativeJournal, recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
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
@@ -36,51 +42,15 @@ const TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;
36
42
  * three quarters of a token a character: not a quarter, which holds for ASCII alone.
37
43
  */
38
44
  export const CODEX_TOOL_OUTPUT_TOKENS = Math.ceil((HOST_RESULT_MAX_CHARS * 3) / 4);
39
- /** The kernel's tool for a host tool: the same name, schema and replay policy; a host's error result is the call's failure.
40
- * The call runs as a kernel effect, whose intent is durable in the session's records before `execute` is entered, so a
41
- * crash inside a `never` tool is always reported, never repeated. The copied harness's wait for Codex's own `function_call`
42
- * line before it runs such a tool is a second guard (the transcript Codex resumes from), not the one that protects it. */
43
- export function kernelTool(tool) {
44
- return {
45
- name: tool.name,
46
- // Codex strips some keywords from the schema its model is given: they are said in plain words in the description
47
- // (the schema itself is the host's, and every call is checked against it).
48
- description: describedDescription(tool.description, tool.inputSchema),
49
- inputSchema: tool.inputSchema,
50
- replay: tool.replay,
51
- async execute(input, io) {
52
- // The effect's step is `tool:<Codex call id>#<attempt>`: the host sees Codex's call id.
53
- const callId = (io.stepId ?? "").replace(/^tool:/, "").replace(/#\d+$/, "");
54
- // The step's attempt: above 0 when a crash cut an earlier attempt and the kernel runs the call again.
55
- const attempt = Number(/#(\d+)$/.exec(io.stepId ?? "")?.[1] ?? 0);
56
- const result = await tool.call(input, { callId, signal: io.signal, attempt });
57
- // A call the host parked for a person's approval did not run: recorded so before its answer, the waiting text.
58
- if (result.parked)
59
- await markParked(io.ctx, callId);
60
- if (result.isError)
61
- throw new Error(result.text);
62
- // A computer tool's value, recorded with the outcome: a script's nested call is answered it (code-mode.ts scriptAnswer).
63
- const structured = result.structured !== undefined ? { structured: result.structured } : {};
64
- if (!result.images?.length)
65
- return result.structured === undefined ? result.text : { text: result.text, ...structured };
66
- // An image the model can't be sent is the call's error, by the tool's name and the image, not a request refused later.
67
- const wrong = toolImageProblems(tool.name, result.images);
68
- if (wrong)
69
- throw new Error(wrong);
70
- // With its images, recorded with the outcome: the answer to Codex carries them after the text (code-mode.ts withImages).
71
- return { text: result.text, images: result.images.map((image) => ({ mimeType: image.mimeType, data: image.data })), ...structured };
72
- },
73
- };
74
- }
75
- /** The adapter's event for a harness live event, if it has one. */
76
- function adapterEvent(event) {
45
+ /** The adapter's event for a harness live event, if it has one: a tool's by the host's name for it (`hostName`). */
46
+ function adapterEvent(event, hostName) {
77
47
  const e = event;
78
48
  if (e?.type === "text" && typeof e.delta === "string")
79
49
  return { type: "text", delta: e.delta };
80
50
  if (e?.type === "tool_start" && typeof e.name === "string")
81
- return { type: "tool_start", callId: String(e.callId ?? ""), name: e.name, args: e.args };
51
+ return { type: "tool_start", callId: String(e.callId ?? ""), name: hostName(e.name), args: e.args };
82
52
  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 } : {}) };
53
+ return { type: "tool_end", callId: String(e.callId ?? ""), name: hostName(e.name), isError: e.isError === true, ...(e.truncated === true ? { truncated: true } : {}) };
84
54
  return undefined;
85
55
  }
86
56
  const turnsIn = (drive) => transcriptOf(drive.state()).filter((r) => r.data?.type === "turn");
@@ -121,20 +91,25 @@ export function codexAdapter(options) {
121
91
  };
122
92
  return {
123
93
  id: "codex",
124
- capabilities: () => ({ mcpClient: CODEX_MCP_CLIENT }),
125
94
  check(spec) {
126
95
  const problems = [];
127
96
  if (spec.context === "fork")
128
97
  problems.push("Codex sessions cannot fork another session's transcript; declare context: \"fresh\"");
129
- const seen = new Set();
98
+ // Each tool by the name Codex is given it (codexToolName): two that would reach Codex by one name are refused.
99
+ const seen = new Map();
130
100
  for (const tool of spec.tools) {
101
+ const given = codexToolName(tool.name);
131
102
  if (!TOOL_NAME.test(tool.name))
132
103
  problems.push(`the tool name ${JSON.stringify(tool.name.slice(0, 80))} is not one Codex accepts (letters, digits, _ and -, at most 64)`);
133
- if (seen.has(tool.name))
104
+ const twin = seen.get(given);
105
+ if (twin === tool.name)
134
106
  problems.push(`the tool ${tool.name} is given twice`);
135
- if (skills.length && tool.name === READ_SKILL_FILE)
107
+ else if (twin !== undefined)
108
+ problems.push(`the tools ${twin} and ${tool.name} both reach Codex as ${given}`);
109
+ if (skills.length && given === READ_SKILL_FILE)
136
110
  problems.push(`the tool name ${READ_SKILL_FILE} is the adapter's own when it has skills`);
137
- seen.add(tool.name);
111
+ if (twin === undefined)
112
+ seen.set(given, tool.name);
138
113
  // What no harness takes (an object root, valid 2020-12, no remote $ref), then what Codex would drop or retype in
139
114
  // the tool's schema: refused here, by name, not found out mid-turn. A place the first already refused is not
140
115
  // refused again by the second.
@@ -162,14 +137,33 @@ export function codexAdapter(options) {
162
137
  throw new Error("agentrun-harness-codex: a session needs a private directory: the host lends one (io.dir), or pass sessionsDir");
163
138
  // With skills the model also reads their files (read_skill_file), from the session's own copy of them.
164
139
  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;
140
+ // The host's name for each tool as Codex calls it: the gate and the session's events name a call by it.
141
+ const hostNames = new Map(tools.map((t) => [codexToolName(t.name), t.name]));
142
+ const hostName = (name) => hostNames.get(name) ?? name;
165
143
  const effort = spec.effort ?? spec.thinking;
166
144
  // The live search runs inside a model request, where no call reaches the gate: it is offered only while the host's
167
145
  // web_search setting allows it, read before each request (a deny or ask set mid-run drops it from the next one).
168
146
  const searchAllowed = options.webSearch && io.permission ? async () => (await io.permission("web_search")) === "allow" : undefined;
169
147
  const harnessOptions = {
170
- tools: tools.map(kernelTool),
148
+ // The kernel's tool for each host tool (bridgeTool): the same schema and replay policy, a host's error result the
149
+ // call's failure. The call runs as a kernel effect, whose intent is durable before it is entered, so a crash inside
150
+ // a `never` tool is always reported, never repeated (the copied harness's wait for Codex's own `function_call` line
151
+ // before it runs such a tool is a second guard, not the one that protects it).
152
+ tools: tools.map((tool) => bridgeTool(tool, {
153
+ name: codexToolName(tool.name),
154
+ // Codex strips some keywords from the schema its model is given: they are said in plain words in the
155
+ // description (the schema itself is the host's, and every call is checked against it).
156
+ description: describedDescription(tool.description, tool.inputSchema),
157
+ // A tool that nests calls (tools_call) names them by the host's names: the bridge holds them by Codex's.
158
+ nestedName: codexToolName,
159
+ // A call the host parked for a person's approval did not run: recorded so before its answer, the waiting text.
160
+ parked: markParked,
161
+ imageProblems: (images) => toolImageProblems(tool.name, images),
162
+ })),
171
163
  // The host's gate, asked about each host-tool call before its intent is written.
172
- ...(io.gate ? { gate: (call) => io.gate(call) } : {}),
164
+ ...(io.gate ? { gate: (call) => io.gate({ ...call, tool: hostName(call.tool) }) } : {}),
165
+ // The host's record of a code-mode `exec`: its row, and its script's calls under it.
166
+ ...(io.ownCalls ? { ownCalls: io.ownCalls } : {}),
173
167
  builtins: false,
174
168
  // Codex's bundled skills (imagegen, skill-installer, ...), which it writes under `$CODEX_HOME/skills/.system` at every
175
169
  // start, are off in every session, skills or not: the model is shown the host's skills and no others.
@@ -198,14 +192,14 @@ export function codexAdapter(options) {
198
192
  // (catalog.ts). A stand-in runs no Codex, so it has no catalog to read.
199
193
  ...(checked !== undefined ? { catalog: { command: checked, ...(options.log ? { log: options.log } : {}) } } : {}),
200
194
  ...(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
195
  proxy: {
204
196
  hooks: io.models,
205
- tools: tools.map((t) => t.name),
197
+ tools: tools.map((t) => codexToolName(t.name)),
206
198
  ...(options.log ? { log: options.log } : {}),
207
199
  ...(options.price ? { price: options.price } : {}),
208
200
  ...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}),
201
+ ...(options.provider.plan ? { plan: true } : {}),
202
+ ...(options.provider.refused ? { credentialRefused: options.provider.refused } : {}),
209
203
  ...(options.fetch ? { fetch: options.fetch } : {}),
210
204
  },
211
205
  }),
@@ -213,7 +207,7 @@ export function codexAdapter(options) {
213
207
  };
214
208
  const harness = checked === undefined ? codexHarness(harnessOptions) : withCheckedBinary(checked, () => codexHarness(harnessOptions));
215
209
  const live = (event) => {
216
- const mapped = adapterEvent(event);
210
+ const mapped = adapterEvent(event, hostName);
217
211
  if (mapped)
218
212
  io.onEvent(mapped);
219
213
  };
@@ -280,11 +274,12 @@ export function codexAdapter(options) {
280
274
  // Started once the session's drive is open, the last step that can fail: an open that fails leaves no listener.
281
275
  const search = options.webSearch === "live";
282
276
  const hostPort = await startModelProxy({
283
- policy: codexPolicy({ model: modelFor(spec), tools: [], ...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}), ...(search ? { webSearch: "live", ...(searchAllowed ? { searchAllowed } : {}) } : {}) }),
277
+ policy: codexPolicy({ model: modelFor(spec), tools: [], ...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}), ...(options.provider.plan ? { plan: true } : {}), ...(search ? { webSearch: "live", ...(searchAllowed ? { searchAllowed } : {}) } : {}) }),
284
278
  hooks: io.models,
285
279
  model: modelFor(spec),
286
280
  origin: options.provider.origin,
287
281
  credential: async () => (await options.provider.credential()) ?? "",
282
+ ...(options.provider.refused ? { credentialRefused: options.provider.refused } : {}),
288
283
  ...(options.price ? { price: search ? withWebSearches(options.price) : options.price } : {}),
289
284
  ...(options.log ? { log: options.log } : {}),
290
285
  ...(options.fetch ? { fetch: options.fetch } : {}),
@@ -1,3 +1,4 @@
1
+ import type { OwnCalls } from "@parcha/agentrun-kernel";
1
2
  import type { DriveContext } from "./host/kernel.js";
2
3
  import type { SessionMachine } from "./host/process.js";
3
4
  import { type RolloutSummary } from "./rollout.js";
@@ -5,6 +6,16 @@ import { type RolloutSummary } from "./rollout.js";
5
6
  export declare const NESTED_STREAM = "codex.nested";
6
7
  /** The stream that records the interrupted turns whose recovery note was injected: `{ since }`, once per interrupted turn. */
7
8
  export declare const RECOVERY_NOTE_STREAM = "codex.recovery-note";
9
+ /** A yielded exec's nested call run on a resume (recoverItems), written before it runs: a later recovery of the same turn tells
10
+ * the model's `wait` its outcome from the session's record, never running it again. */
11
+ export declare const RESUMED_STREAM = "codex.nested-resumed";
12
+ /** The nested calls whose outcome a resume's recovered script output tells (recoverItems): `{ since, callIds }`, written before
13
+ * that output is injected, so the turn's recovery note says the outcome is there, after a crash between the two as well. */
14
+ export declare const SHOWN_STREAM = "codex.nested-shown";
15
+ /** Each `exec` a recovery answered (recoverItems), directly or through the `wait` on its cell, and whether that answer tells a
16
+ * script that failed (recoveredFailed): `{ exec, failed }`, written before the answer is injected. That answer carries no status
17
+ * header for its rollout line to be read by, so the exec's end on the host's record, live or replayed after a later crash, reads this. */
18
+ export declare const RECOVERED_END_STREAM = "codex.exec-recovered-end";
8
19
  interface Journal {
9
20
  append(stream: string, record: unknown): void;
10
21
  flush(): Promise<void>;
@@ -33,6 +44,11 @@ export interface CodeModeDeps {
33
44
  }[];
34
45
  structured?: unknown;
35
46
  } | undefined;
47
+ /** A call through the bridge (gate, intent, call, result): a resumed nested call that never reached its intent (recoverItems). */
48
+ call?(name: string, args: unknown, callId: string): Promise<{
49
+ text: string;
50
+ isError: boolean;
51
+ }>;
36
52
  };
37
53
  log(message: string, fields?: Record<string, unknown>): void;
38
54
  /** The rollout lines restored from the log. */
@@ -45,6 +61,9 @@ export interface CodeModeDeps {
45
61
  /** How often the barrier looks again for a script's line, and what a declined call is told. */
46
62
  tries: number;
47
63
  declined: string;
64
+ /** The host's record of each `exec` (SessionIO.ownCalls): its row from its rollout lines, and each nested call it makes
65
+ * named under it before the call reaches the gate. */
66
+ ownCalls?: OwnCalls;
48
67
  }
49
68
  interface Dangling {
50
69
  callId: string;
@@ -63,7 +82,7 @@ export declare function withOutputKind<T extends {
63
82
  };
64
83
  /** What a dangling `wait` of code mode is told: it had started, on the cell named, when the session stopped and took the cell's script with it. */
65
84
  export declare const waitStoppedText: (cell: string) => string;
66
- /** A recorded result that held images (kernelTool's `{ text, images }`) as its text and a line saying how many, which are not
85
+ /** A recorded result that held images (bridgeTool's `{ text, images }`) as its text and a line saying how many, which are not
67
86
  * shown again after the interruption; undefined for a result with none, whose repaired output stays as it is. */
68
87
  export declare function imagesNoted(output: unknown): string | undefined;
69
88
  type Image = {
@@ -101,8 +120,11 @@ export declare function codeMode(deps: CodeModeDeps): {
101
120
  * 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
121
  * 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
122
  * 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
- recoverItems(items: Record<string, unknown>[], dangling: readonly Dangling[], lines: readonly string[], since: number): Promise<void>;
123
+ * both repairs (with a recovery note and without) inject what this leaves. A recovered script's output (a cut-off exec's, a resumed
124
+ * `wait`'s) quotes each finished call's result as the script was handed it and holds its whole to its own bound
125
+ * (scripts.ts EXEC_RECOVERY_MAX_CHARS); on a resume, the calls it tells the outcome of are recorded for the note (SHOWN_STREAM). `resume`: the open turn a recovery note resumes, whose
126
+ * parked nested calls run now; the repair of an ended turn (repairUnnoted) only tells, and runs nothing. */
127
+ recoverItems(items: Record<string, unknown>[], dangling: readonly Dangling[], lines: readonly string[], since: number, resume?: boolean): Promise<void>;
106
128
  /** 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
129
  * them (one interrupted mid-call, or settled instead of resumed) left them dangling, and the provider refuses a history with a call unanswered.
108
130
  * Nothing is armed here: a new turn that calls a `never` call the ended turn completed runs it. */