@parcha/agentrun-kernel 0.1.0-beta.30 → 0.1.0-beta.32

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.
Files changed (102) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/README.md +5 -0
  3. package/dist/errors.d.ts +7 -0
  4. package/dist/errors.js +10 -0
  5. package/dist/host/box.d.ts +0 -58
  6. package/dist/host/box.js +7 -0
  7. package/dist/host/index.d.ts +5 -9
  8. package/dist/host/index.js +2 -4
  9. package/dist/host/mcp-route.d.ts +14 -0
  10. package/dist/host/mcp-route.js +125 -0
  11. package/dist/host/proxy.d.ts +96 -2
  12. package/dist/host/proxy.js +533 -41
  13. package/dist/host/serial.js +2 -1
  14. package/dist/index.d.ts +5 -4
  15. package/dist/index.js +3 -2
  16. package/dist/kernel/cap/admit.d.ts +35 -0
  17. package/dist/kernel/cap/admit.js +186 -0
  18. package/dist/kernel/cap/errors.d.ts +20 -0
  19. package/dist/kernel/cap/errors.js +25 -0
  20. package/dist/kernel/cap/index.d.ts +14 -0
  21. package/dist/kernel/cap/index.js +15 -0
  22. package/dist/kernel/cap/ledger.d.ts +37 -0
  23. package/dist/kernel/cap/ledger.js +83 -0
  24. package/dist/kernel/cap/marks.d.ts +50 -0
  25. package/dist/kernel/cap/marks.js +28 -0
  26. package/dist/kernel/cap/park.d.ts +80 -0
  27. package/dist/kernel/cap/park.js +57 -0
  28. package/dist/kernel/cap/port.d.ts +21 -0
  29. package/dist/kernel/cap/port.js +95 -0
  30. package/dist/kernel/cap/price.d.ts +54 -0
  31. package/dist/kernel/cap/price.js +117 -0
  32. package/dist/kernel/cap/recover.d.ts +18 -0
  33. package/dist/kernel/cap/recover.js +71 -0
  34. package/dist/kernel/cap/rule.d.ts +55 -0
  35. package/dist/kernel/cap/rule.js +93 -0
  36. package/dist/kernel/cap/run-cap.d.ts +80 -0
  37. package/dist/kernel/cap/run-cap.js +132 -0
  38. package/dist/kernel/cap/steps.d.ts +36 -0
  39. package/dist/kernel/cap/steps.js +64 -0
  40. package/dist/kernel/cap/stopped.d.ts +17 -0
  41. package/dist/kernel/cap/stopped.js +34 -0
  42. package/dist/kernel/cap/types.d.ts +151 -0
  43. package/dist/kernel/cap/types.js +1 -0
  44. package/dist/kernel/cap/words.d.ts +39 -0
  45. package/dist/kernel/cap/words.js +75 -0
  46. package/dist/kernel/cap/wrap-up.d.ts +17 -0
  47. package/dist/kernel/cap/wrap-up.js +37 -0
  48. package/dist/kernel/drive.d.ts +0 -1
  49. package/dist/kernel/drive.js +9 -2
  50. package/dist/kernel/index.d.ts +1 -0
  51. package/dist/kernel/index.js +1 -0
  52. package/dist/kernel/registry/background.d.ts +12 -0
  53. package/dist/kernel/registry/background.js +342 -0
  54. package/dist/kernel/registry/bash.d.ts +3 -0
  55. package/dist/kernel/registry/bash.js +23 -0
  56. package/dist/kernel/registry/browser.d.ts +11 -0
  57. package/dist/kernel/registry/browser.js +14 -0
  58. package/dist/kernel/registry/defs.d.ts +42 -0
  59. package/dist/kernel/registry/defs.js +153 -0
  60. package/dist/kernel/registry/desktop.d.ts +11 -0
  61. package/dist/kernel/registry/desktop.js +90 -0
  62. package/dist/kernel/registry/gate.d.ts +20 -0
  63. package/dist/kernel/registry/gate.js +32 -0
  64. package/dist/kernel/registry/handoff.d.ts +11 -0
  65. package/dist/kernel/registry/handoff.js +51 -0
  66. package/dist/kernel/registry/hands.d.ts +280 -0
  67. package/dist/kernel/registry/hands.js +28 -0
  68. package/dist/kernel/registry/index.d.ts +17 -0
  69. package/dist/kernel/registry/index.js +14 -0
  70. package/dist/kernel/registry/limits.d.ts +27 -0
  71. package/dist/kernel/registry/limits.js +29 -0
  72. package/dist/kernel/registry/phone.d.ts +15 -0
  73. package/dist/kernel/registry/phone.js +135 -0
  74. package/dist/kernel/registry/registry.d.ts +22 -0
  75. package/dist/kernel/registry/registry.js +75 -0
  76. package/dist/kernel/types.d.ts +0 -7
  77. package/dist/process/builtins.js +1 -1
  78. package/dist/process/index.d.ts +1 -0
  79. package/dist/process/index.js +1 -0
  80. package/dist/process/journal.js +1 -1
  81. package/dist/process/recovery.js +1 -1
  82. package/dist/process/resume.d.ts +20 -0
  83. package/dist/process/resume.js +16 -0
  84. package/dist/process/tail.js +1 -1
  85. package/dist/process/tools.d.ts +8 -1
  86. package/dist/process/tools.js +20 -3
  87. package/dist/process/zod.js +1 -1
  88. package/dist/run-booking.d.ts +9 -0
  89. package/dist/run-booking.js +50 -0
  90. package/dist/runner.d.ts +91 -17
  91. package/dist/runner.js +132 -41
  92. package/dist/testing.d.ts +79 -12
  93. package/dist/testing.js +106 -13
  94. package/dist/types.d.ts +235 -10
  95. package/package.json +8 -4
  96. package/vendor/durable-harness/UPSTREAM.json +0 -9
  97. package/dist/host/box-slot.d.ts +0 -26
  98. package/dist/host/box-slot.js +0 -112
  99. package/dist/host/egress-proxy.d.ts +0 -45
  100. package/dist/host/egress-proxy.js +0 -416
  101. package/dist/host/egress-table.d.ts +0 -24
  102. package/dist/host/egress-table.js +0 -165
package/CHANGELOG.md CHANGED
@@ -2,6 +2,74 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## 0.1.0-beta.32 (2026-11-10)
6
+
7
+ - The code copied from the upstream durable harness is now AgentRun's own: the port froze, and the pristine upstream copies, the named patches, the import tables, `scripts/port-durable-harness.mjs` and `npm run verify:port` are gone. `vendor/durable-harness/UPSTREAM.json` still records where each copy came from, and each copy keeps its header and NOTICE its attribution. With it go the kernel's paths that never run:
8
+ - `AgentAdapter.version` and `AdapterCapabilities.fork` (no adapter forks; a node that asks for `context: "fork"` is refused as before).
9
+ - `DriveContext.config`, and `requires`/`needs` on a host tool and an effect's options; `kernel/types.ts` is no longer pinned to upstream's types.
10
+ - The Codex harness's `codex.spend` ledger and its dollar caps (`sandbox({ budget })`, `GatewayLedger`, the gateway handler's `budget`, `ledger` and `onCap`), which never fired, and its table of removed options.
11
+ - `Box`, `BoxSpec`, `BoxedChild`, `Isolation` and `boxSlot` (`@parcha/agentrun-kernel/host`), which nothing implemented or used.
12
+ - The model proxy's parts only tests used (`inputTokensMaxOf`, `matchRoute`, `parseStrict`, `reportedCostOf`) move to `@parcha/agentrun-kernel/testing`; `providerIdsOf` and `MCP_ROUTE_VERSIONS` leave the host API.
13
+ - The box egress proxy (`startEgressProxy`, `parseAllow`, the address table) moves into agentrun-serve, its one user.
14
+
15
+ Fixed: a run on Claude Code or Codex now closes its harness session when its process lets the run go, as the adapter's `close()` contract asks; before, serve never called it. On today's adapters an idle session's `close()` stops no process of its own (each drive already ends its CLI or app-server when its turn ends), so this keeps the contract for an adapter whose session holds one. For it, pi-durable-disk's `DoorHook` has a required `close()`: the door's stop calls it once, busy or idle (on a drain after the abort, on a fence alongside the kill, within the abort's bound). A hook with nothing of its own to stop resolves at once. `DoorHook` also has a required `harness` id: a `close()` that throws, rejects or overruns its bound is logged with it ("door close failed" / "door close timed out") through `serveRun`'s new optional `log`, which the run CLI passes its log line to. A harness session that lands after the door's close (a stop while it was still opening) is closed too, once.
16
+ - `SessionWriter.sync()` is required. The kernel calls it after an effect's start record and before an effect that may not run twice, so the start is durable through a lost box. A writer that has none is refused at that effect, with words saying so, before the effect's start is written, and the effect does not run. Anyone who implements `SessionWriter` adds `sync()`: a writer whose appends are already durable resolves at once, and a wrapper passes it on to the writer it wraps (`serialWriter` does).
17
+ - pi-durable-disk's barriers table: the side-request mark names its box-loss proof, and the kernel's required sync is done among the conditions for a run's store to go NORMAL.
18
+ - The pi family is 1.5.0 exactly (pi-durable, pi-ai, pi-coding-agent, chord), with one typebox (1.3.27); the older-pi CI legs are gone. A pi 1.5 run store is SQLite schema 2, which pi 1.3.0 or earlier cannot open again, so there is no rollback past this release. Tool results are under `output` only. A browser charge serve fails to count makes the run's spend unknown, and a capped run then refuses its next paid call until the spend is known again. The door's `GET /events` and a recording's live lines read through an adapter on pi 1.5's `observeCommits` (pi-durable-disk `./internals` `watchEvents`, with no compatibility promise) until they move to `conversation.watch`. A failed run store's close releases this process's live browser sessions again; a normal close keeps them for the next run. A claude-agent, codex or opencode run opens on pi 1.5, and an image it reads through pi's read tool is read. particle-1's cap hold keeps Particle's list price over pi-ai's promotional catalog price; a request is still booked at OpenRouter's billed total. The agent store reader reads pi-durable schema 2.
19
+ - Each adapter states what its harness is, and serve reads that instead of the harness's name. `@parcha/agentrun-harness-claude/facts` and `@parcha/agentrun-harness-codex/facts` export `facts` (the kernel's `AdapterFacts`): the API its proxy speaks (`wire`), whether it takes a message mid-turn, the memory one run reserves, its thinking levels, its own web search (`native` or `live`), whether its model is its own, how it names a model, its install line and pins, the schemas its MCP client drops, whether it binds the session's MCP servers, an MCP tool alias, and its proxy policy. Serve keeps one table from a harness id to its entry and one `providerFor(wire, env, model)`: opencode and codex take one route because both speak the Responses API, and the gateway base rule is written once, so pi's runs take it too. Nothing else changes for a run, a capability or a refusal's words.
20
+ Upgrading: an AGENT_MODEL_BASE_URL that is plain http to a non-loopback host, names a user, or has a query, fragment or dot segment is now refused on pi, as on Codex and OpenCode (a backslash or whitespace too); the refusal names the setting, and the gateway's key is never sent there. `startServe`'s `fauxHarness` option is gone; a test passes `harnessTable`, a module of harness table entries (`entries(builtins)`), in its place. `AGENTRUN_SERVE_FAUX_HARNESS` is no longer read; `AGENTRUN_HARNESS_TABLE` is set from `harnessTable` alone and dropped from the server's own environment.
21
+ - `AdapterSession.steer?(text, id?, mode?)`: an adapter whose harness takes a person's message mid-turn places it in the turn in flight, at its next boundary. `id` is the request id the placement carries, so a host can tell the commit that placed it. `mode` is `"steer"` (the default) or `"followUp"`, which waits for the turn's end and runs as a turn of its own (a message that answers nothing, such as a trigger's). An adapter without it takes no message mid-turn, and the host refuses the steer in words.
22
+ - A call that never started now runs on resume instead of reading "interrupted". When a claude-agent run resumes a transcript that ends in a host-tool call with no result, and the run's journal holds no intent for that call (the host's gate parked it for a person's approval, or the process died before the call was written), the call now goes through the host's gate again under the id the model gave it, runs once, and its result goes into the transcript before the CLI starts again. Before, the CLI answered such a call "[Tool call interrupted]". A call whose intent is in the journal is never run again: the CLI answers it as before, and the recovery note says what the log knows of it. A gate that parks again writes nothing.
23
+ - `@parcha/agentrun-kernel`: `SessionIO.gate` (the host's gate before a host-tool call's intent: allow, deny in the host's words, or park), the tool bridge's `gate` option, and `resumeUnstartedCalls` / `unstartedCalls` in `./process`, the decision every CLI harness shares on a resume. `AdapterFacts.rerunsStarted` (false for a harness that never runs a started call again).
24
+ - `@parcha/agentrun-harness-claude`: the gate is asked only once the assistant entry that made the call is in the log, so a parked call is found dangling on the resume under the same id.
25
+ - `@parcha/agentrun-serve`: the harness conformance suite skips the cases an adapter's facts rule out (`factsRuleOut`), saying they are by design. The claude-agent subject runs through the runner and passes the park-and-resume cases.
26
+ - Agents on codex call a saved MCP server's tools: grant `mcp:<server>/<tool>` in `definition.tools`, as on pi and claude-agent, and `features.mcp_client.harnesses` now lists codex. The harness writes each granted server in Codex's `mcp_servers` itself, at the session's model proxy (`/mcp/<server>`, behind the session key), with only the granted tools enabled and approve mode, so Codex never holds the credential. The proxy records each call in the session before it sends it, by Codex's own call id, so a call a crash cut off is answered interrupted and never sent again. A server that does not start fails the turn (`required`). The Codex proxy policy admits the granted tools in the `mcp__<server>` namespace Codex 0.164 sends them in, and the timeline reads `<server> · <tool>`. The kernel's model proxy mounts `/mcp/<server>` itself, once for every harness with an MCP client of its own, from the session's MCP and the client fact its adapter declares (`capabilities().mcpClient`, the `_meta` key of a call's id: `claudecode/toolUseId` on Claude Code, `callId` on Codex); `ModelProxyOptions.mcp` takes `{ session, client }` in place of a handler.
27
+ - An agent's computer is one setting, `computer: { kind, provider? }`, with kind `none`, `sandbox`, `desktop`, `phone` or `browser`. The v2 `place` stays readable and writable as its view (`{mode: "runner"}` is `{kind: "none"}`, `{mode: "sandbox", box}` is `{kind: "sandbox", provider: box}`), and writing either sets both. With no setting, Mode 1 runs Docker's sandbox where Docker is ready and none otherwise; Mode 2 runs none.
28
+
29
+ Settings → Computers lists what the server offers: each kind with its providers, their capabilities, and whether each declared key is saved, never its value. A provider's keys are saved by the names it declares, sealed in the store, and never echoed back. "Test connection" makes one account-level read that never creates a computer, and gives `ok` or the provider's words. At a run's claim the setting is checked against the server's mode and the provider's keys: Mode 1 runs a sandbox only on Docker, Mode 2 refuses Docker's sandbox, and a desktop, a phone or a browser is allowed in both. A provider with a required key missing is refused in words that name Settings → Computers. A run's read gains `computer: {kind, provider, state, why?}`.
30
+
31
+ A run's tools follow its computer's kind. A desktop adds `desktop_screen` and `desktop_input`; a phone adds `phone_screen`, `phone_tree`, `phone_tap`, `phone_swipe`, `phone_type`, `phone_key`, `phone_apps` and `phone_open`; a browser adds pi-browser's browser tools; each comes after the file and shell tools. The run's folder is mounted in the computer only when the kind has files and exec and its provider mounts the folder: a sandbox always, and a desktop when its provider does. Otherwise bash runs in the run's folder on the runner, asking first. Screenshots come back as images. `phone_tree` lists what on the phone's screen can be tapped or typed into, from the screen's structure, each node with its center and bounds in screenshot pixels, at most 150 nodes and 12,000 characters (a last line counts any more); `phone_key` presses back, home or enter. Both are under the "phone" permission. A run whose computer is a desktop or a phone gets that kind's skill (`desktop-computer` or `phone-computer`) in its `.agents/skills/`, beside the agent's own; an agent skill of the same name is kept and the kind's is not laid. The background tools' refusal with no computer now names the setting.
32
+
33
+ A run's desktop or phone can be watched and taken over by its owner. `GET /v2/runs/{id}/computer` gives its kind, its state (`live`, `none` or `off`, with `why` when there is nothing to watch), whether the owner holds it, and the provider's live stream of its screen (view-only while the agent works). `POST /v2/runs/{id}/computer/take-over` gives the owner a stream that drives it and parks the agent's screen, input and phone calls; `POST .../hand-back` gives it back. At the hand-back a parked look runs on the screen as the owner left it, and a parked act is not done: the agent is told the person had the computer and to look again. A take-over goes back to the agent on its own after 15 minutes, or at the run's end, and the run's read says `taken_over` while it lasts. These routes are owner-only, as a run's browser view is: they take the console's password session, never a token. The browser keeps its own routes.
34
+ - The last data serve kept by a harness's name moves to the adapters' facts: a CLI's own tools and the table tool each one is (`AdapterFacts.nativeTools`, stated by claude-agent and codex), the harnesses each model key runs (from their wires' vendors; OpenRouter's key runs every one) and OpenRouter's default model for each wire's vendor. Nothing changes for a run, a capability or a refusal's words.
35
+ - A run's store can now run at `synchronous = NORMAL` and still never repeat a side effect after a box is lost. `syncNow(store, BARRIER.<name>)` makes every commit the store has made durable with one small commit at FULL. A FULL commit syncs the write-ahead log, so it makes every earlier commit durable too, not only its own. The barriers and the stores they guard are listed in one table (`barriers.ts`). A test holds that table to the source: every barrier call is named and in its listed file, every store that is opened is listed, a store with no effects runs no tool or model, and no barrier may still be planned once the run's store runs at NORMAL.
36
+ - The run's store still opens at FULL (`JOURNAL_SYNCHRONOUS`), so nothing is synced twice yet. `openArchilStore` and `openDurableRun` take `synchronous: "NORMAL"` for a store that should run at NORMAL.
37
+ - A pi tool call that is not replay-safe (or a billed replay-safe one) goes out only after the server's tool gate synced the store, once pi-durable has committed its intent. A kernel effect (claude-agent, codex, opencode) that is not replay-safe runs only after its start record is synced: `SessionWriter` has an optional `sync()`, and `serialWriter` passes it on.
38
+ - A non-pi harness's model request leaves only once the server's start mark for it is committed and synced. `ModelPortOptions.onEvent` may return a promise for `request_start`; the runner awaits it, and a rejection refuses the request, which is booked withdrawn at $0 and never taken for an open one.
39
+ - A run syncs its store after each status it writes and when it is released. The server's checkpoint of a run it takes back stays at FULL, whatever level the run's store runs at.
40
+ - A run's spend cap prices each model request's input from the previous request's cache (`cap_mode` `expected`, the default): the input the previous request of its conversation read from or wrote to the cache counts at the cache-read price when it ended less than 4 minutes before, so a cap pays for about what the run really spends instead of pausing near half of it. Output never passes the cap; a cache miss can, by at most the request's bound, served as `cost.overshoot_bound_usd` while it is in flight (and as `pending.overshoot_bound_usd` on a run paused at its cap). The real cost is booked, one timeline row says `Went $X over its cap on a cache miss (at most $Y).`, and the run pauses at its cap instead of failing. `cap_mode: "strict"`, on a run's body or an agent's definition, keeps the worst case: every input token uncached.
41
+ - A run near its spend cap is told once to finish: when what is left is under three times its typical request (the median of the run's own model's priced requests after the first), the model's next request carries "About $X left of this run's budget: finish now with your answer.", and the Timeline shows it as the server's row. On pi it goes into that request's context; on claude-agent, codex and opencode the model proxy adds it to the request's body after everything the CLI sent, so the cached prefix is unchanged. No message is queued, so nothing runs after the model's answer. Once per cap, across restarts; a raise re-arms it.
42
+ - A capped run is told to wrap up when it is really near its cap, and Claude Code, Codex and OpenCode runs are told as pi runs are. Step 0 (nothing priced yet) is judged on the request taking the note itself, its input and a 4,096-token answer, and told in that request, as pi's is. A CLI run used to judge it at a request's admission, after that request's note was taken, and kept the judgement after the first real cost came in, so a run spending about a cent a request could hear "finish now" from its second request on. From the first priced request on, the run's measured typical request cost decides. On every harness, a run is also told once what is left falls under twice the least admission of the request taking the note, the figure the cap refuses it below, so a run whose requests need far more output than they cost is warned before the cap stops it.
43
+
44
+ Upgrading: the kernel's model port and model proxy note hooks (`ModelPort.note`, `ModelProxyHooks.note`) take a second argument, the request about to take the note as its client sent it (`NoteRequest`: its input bound and output asks). The model proxy measures the request before it asks for the note. A host that implements the hook may ignore the argument.
45
+ - Every deny the model reads now says plainly that the call never left: "It was not run: nothing was sent and nothing was charged." It covers a tool set to deny, an ask refused because no one can approve, the owner's deny of a parked call, and a person's declining message. After a deny, a model no longer tells the person it can't confirm whether a charge was made.
46
+
47
+ An approved call that ran before a crash keeps its saved result when its tool is set to deny before the run reopens: the model gets that result, never "nothing was charged", and it is booked once. A call cut after it started but before its outcome is denied with no claim either way ("It had started before the deny, and whether it took effect is not known.").
48
+
49
+ The same holds for a replay-safe host tool on claude-agent and codex (web_fetch, web_search) that the kernel runs again after a crash cut its first attempt: if it is now denied, or refused for want of an approver, the words say it had started and whether it took effect is not known, never that nothing was charged. If it now asks and PARKS, the request keeps that it is a replay in the run's store (`replayed` on the approval request), so the owner's Deny or a declining message says the same, after a restart too. Host tools now hear the kernel's attempt (`HostTool.call`'s `attempt`). On pi, which reruns a cut replay-safe call with the same call id and no sign of a rerun, the gate keeps its own mark of each replay-safe call it let through that can bill (web_fetch, web_search: an `agentrun.gate_passed` entry, written before the tool runs), and reads its marks before the run resumes, on an agentic run and a workflow's model node alike, so a rerun of one is treated the same way.
50
+ - On codex and claude-agent, a tool call (a remote MCP server's included) has its Timeline row while it runs, from the moment the session records its intent, and a call a crash cut off gets its result row at the next open from the session's record of it: "interrupted ... it may or may not have taken effect" for one that is not safe to repeat. Before, a running call had no row, and a cut call never got one.
51
+ - On codex, a code-mode script's call the host parked for a person's approval (an MCP tool's or a host tool's) is never told to the model as completed: the cut script's output says it "was waiting for a person's approval and did not run". The host marks such an answer `parked` (`HostTool` and `McpCallResult`), which the MCP door never sends the harness's client.
52
+ - A learned workflow's model nodes, its `llm` call nodes and a call node's native search, on claude-agent, codex and opencode, are requests on the run's one route: the session's own model proxy, under a side key the proxy mints for the host (`ModelProxy.sideKey`, `AdapterSession.port`). They get the harness's own body rules, provider, key, price and booking, labelled `learned_workflow` on the session's records (`runner.request.host`), under the run's one cap, as a side call: the spend cap's wrap-up never counts it toward a typical request, and it never takes the wrap-up's note. They reach an operator's gateway at ANTHROPIC_BASE_URL or AGENT_MODEL_BASE_URL as the harness's requests do, and never go around it, so a run there is offered its learned workflows (the learning pin's `workflows_off` is gone). A side request is never the turn's answer request: a content-filter stop on it does not halt the turn.
53
+ Upgrading: Finish or cancel capped runs that used learned workflows before upgrading: their earlier learned-workflow spend is not counted against the cap after it. A pin written before this keeps the workflows it left out, and its `workflows_off` is no longer read.
54
+ - A run with no computer that mounts its folder no longer gets a shell on the server. Before, such a run (an agent with no computer on a server without Docker, a browser, a phone or a desktop that does not mount the folder, or a runner place) was given bash in its folder on the server's own machine, where a command could read the server's data and keys. Now, in a server whose run folders are on its own disk, that run gets the file tools alone, confined to its folder: bash and the background tools are not offered, and a bash call answers that it is not available and that a sandbox computer gives a shell. A sandbox, or a desktop whose provider mounts the folder, keeps its shell, and with Archil storage a run with no computer keeps bash on Archil's serverless exec, which runs outside the server. `runShellOf(setting, mode, registry)` says where a run of a computer setting has its shell, before it starts.
55
+ - A Claude Code, Codex or OpenCode turn parked on a call that waits for a person no longer hides a request whose cost could not be recorded. Such a request now stops the booking as it does at any other time: the run fails with the cost-write error instead of going on past a request it did not record. The kernel exports `TurnParked`, the stop a host gives for a parked turn (`ModelPortOptions.stopped`): it refuses new requests but is no stop of the booking.
56
+ - A provider's error no longer hands a harness the provider's credential. The session's model proxy relayed every answer as it came, so a provider that echoes the key it was sent ("Incorrect API key provided: <key>") gave it to the harness, which on a CLI harness runs in the sandbox. Now, in an answer with an error status, and in an error event inside a streamed answer (Messages' `error`; Responses' `error` and `response.failed`), the credential the proxy sent and the values of the headers it added are cut out ("[redacted]") as sent, JSON-escaped, and with "/" escaped. Then the host's redactor runs, when it gives one (`ModelProxyOptions.redact`). An event's name never exempts its data: an error under a healthy event name is cut as an error event, and every other event of a streamed answer has the credential cut too and passes otherwise byte for byte. A header value shorter than eight characters is cut only from an error, and only where it stands as a whole word inside the error's own text, so a value of "1" never touches a status code. An error body still reaches the client as it comes.
57
+ - The model proxy reads an answer's content-filter stop and output-limit cut off each stream line once, as the line ends, instead of reading the last 64 KiB of the answer again for every piece. A long answer (about 1 MB, some 65,000 pieces) no longer holds the runner's thread for most of a minute, starving the run's store commits and claim renewals until the run never ended. A whole JSON body is read whole while it fits the window, so a stop in a pretty-printed body is still told before its client has it.
58
+ - A capped run's wrap-up note counts as told only once a request carrying it is answered, on every harness. A request the provider never answers, one lost on the way, one cut, one stopped part way, or one that never leaves, leaves the note for the next request, which carries it. Before, the note counted as told as soon as a request carrying it was admitted, so a retry after a failed request went without it, and the run could reach its cap unwarned. On another harness, a note told in an answered request is never told again in a later process, even if the row that shows it was lost: the row is rebuilt from the answered request's own record. On pi, the run's wrap-up row, written once the carrying request is answered, is what a later process reads.
59
+
60
+ Upgrading: a host that implements the kernel's `ModelPort` may return `note` in a request's admission (written on its `runner.turn` record when it ends) and read `ended` on `request_end`; both are optional.
61
+ - A capped Claude Code run's wrap-up note goes in the turn's own request. With no small model set, a Claude Code title or summary call goes on the session's model, and such a call could take the note once it was due, so the model never saw it. The model proxy now gives the note only to a request its policy counts as the turn's answer request (`ProviderPolicy.answers`), and a side call goes as its client sent it. A session with no tools offers nothing to tell its requests apart by, so each of its requests still counts as the turn's, as before.
62
+ - The kernel's spend cap, still unused until the cutover, counts a request that has no answer (its claim lost before the answer was written, or its turn cut) at its hold plus its bound, the worst it can have cost, and the run's cost then reads unknown with the known part beside it. Before, such a request counted at its hold alone, so a request that missed the cache could pass the cap unseen. `runner.request` keeps the bound the host gave beside the hold; a host that gives none is unchanged.
63
+ - The kernel's spend cap, still unused until the cutover, prices a request the host sends beside the harness's own (a learned workflow's node) as a cache miss: the session's previous request never stands for it. A request carrying the wrap-up's note that fits only without the note is sent without it (`withoutNote`), and one that fits neither way is refused in the words for its client's own body. The note never refuses what fits.
64
+ - The kernel's spend cap, still unused until the cutover, refuses to admit a step id again while its last end mark is unwritten, so a retried settle can't book the new step at the old step's figure. It reads a host hook's spend or hold that isn't a finite figure of 0 or more as unknown and refuses the request, and never counts it as $0 or as room. It won't price a request in flight at 0 output when it has no hold, no output limit and no ceiling.
65
+ - The kernel's spend cap, still unused until the cutover, prices a model with tiers as its provider bills it: a request whose whole input (fresh and cached) passes a tier's threshold is held, and booked where the cap prices it, at that tier's rates, as pi-ai's calculateCost prices it on the catalog's own table. Before, it held such a request at the base rates, half the bill for gpt-6-sol past 272,000 input tokens, so a run could pass its cap by up to 2x. `ModelPrice` takes the catalog's `tiers` as given.
66
+ - The kernel gains its spend cap, unused until the cutover and not exported from the package: one rule decides every paid step for every harness (a model request, a priced tool, a decision), the same pricing, clamp, refusal words, wrap-up note, park and raise, with marks that let a reopened run read what it spent. No code path uses it yet.
67
+ - The kernel has one registry of host tools, still unused until the cutover: read, write, edit, bash and the five background tools, each with main's name, words, schema and replay, in main's order. It also holds their limits, the tool gate's shell family, and the run's hands port. bash is bounded to the hands' ceiling. The background tools run on the computer's processes, eight at once, each started, counted and given its id in one step, and reach only processes they started; with no computer they are refused in words. An executor answers a failure in words apart from its output, so a timed-out bash keeps what it printed, and only an abort throws. The host gives read, write, edit and bash's own run, and a registry missing one of them is refused when it is built. With no computer, bash runs in the run's folder and is asked first.
68
+
69
+ ## 0.1.0-beta.31 (2026-11-06)
70
+
71
+ - Agents call a saved MCP server's tools on pi and claude-agent: grant `mcp:<server>/<tool>` in `definition.tools`. A save checks the name against the server's saved tools (`422` naming them). A run's first launch pins the granted tools as saved and the server's URL; its credential reaches only runs that grant one of its tools, over the run's secrets pipe. pi binds each tool in the run's process; claude-agent's own MCP client calls it at the session's model proxy (`/mcp/<server>`, behind the session key), so the CLI never holds the credential. A call follows no redirect, a crash-cut call is answered interrupted and never sent again, a moved server is sent nothing, and the timeline reads `<server> · <tool>`. `features.mcp_client.harnesses` lists the harnesses that run them. Every call passes the run's tool gate and its spend cap.
72
+
5
73
  ## 0.1.0-beta.30 (2026-11-05)
6
74
 
7
75
  - A Codex run stopped just after its message was sent to Codex no longer loses the message. Codex answers `turn/start` before it writes the message to its rollout: on the real app-server, killed at the answer or 20 ms after it, the rollout held no user message; 100 ms after, it did. A stop in that window kills Codex with the message sent and never recorded, and the next Codex, resumed from the session's rollout, never has it. The stop's settle now reads Codex's rollout as the session keeps it, the rollout the next Codex is resumed from, and carries a placed message it lacks into the next one, as claude-agent's settle reads its CLI's transcript. The `turn/start` send mark is gone (the kernel's `markSent` and `sentMarks` with it); a stopped drive still starts no turn.
package/README.md CHANGED
@@ -49,6 +49,11 @@ harness adapter the way they run on Pi, durable in AgentRun's own store.
49
49
  recovery note, the tool bridge, the built-ins' hook-pair calls, the inbox (and `waitForSubmissions`, for a harness that
50
50
  waits for input while a turn runs), `zodShapeFromJsonSchema`, for harness SDKs whose tool APIs take zod, and
51
51
  `settleTurn`, the transcript's end for a turn a session settles (`settleOpenTurn`).
52
+ - `./kernel/cap` is the one spend cap every harness books through, the same rule and words for each: it admits a paid step
53
+ (a model request on any harness, a decision, a priced tool) under the run's cap at the catalog's price, tiers included,
54
+ holds and books it, and a step that does not fit parks the run for a raise. `beforeRequestOf` is the check on the
55
+ runner's booking (the model proxy's requests); `createCap`/`openCap` is the host's own ledger (decisions, priced tools);
56
+ `parkOf`, `checkRaise` and `followUpOf` decide what a refusal and a raise do to the run.
52
57
  - `./host` is the session's model proxy, provider-neutral: on the loopback interface, it admits only the session's key,
53
58
  only the routes a `ProviderPolicy` lists (by exact path text, with no query or one the route lists exactly; a route
54
59
  may also be answered by the proxy, or be free, like a token count), and strict JSON, has the policy shape or refuse the
package/dist/errors.d.ts CHANGED
@@ -15,6 +15,13 @@ export declare class SessionFenced extends Error {
15
15
  readonly code = "SESSION_FENCED";
16
16
  constructor(key: string);
17
17
  }
18
+ /** A host's stop for a turn parked on a call that waits for a person (`ModelPortOptions.stopped`): it ends the turn and
19
+ * refuses new requests until the park lets go, but it is no stop of the booking itself, so a paid request whose cost
20
+ * can't be recorded meanwhile still stops it. */
21
+ export declare class TurnParked extends Error {
22
+ readonly code = "TURN_PARKED";
23
+ constructor(message: string);
24
+ }
18
25
  /** A node that delivered no record. `final` says a second attempt would end the same way, so a recovery driver gives
19
26
  * it none: the runner's own bounds (the turn cap, no progress, a refusal) are final; an abort, a timeout or a model
20
27
  * error is not. */
package/dist/errors.js CHANGED
@@ -8,6 +8,16 @@ export class SessionFenced extends Error {
8
8
  this.name = "SessionFenced";
9
9
  }
10
10
  }
11
+ /** A host's stop for a turn parked on a call that waits for a person (`ModelPortOptions.stopped`): it ends the turn and
12
+ * refuses new requests until the park lets go, but it is no stop of the booking itself, so a paid request whose cost
13
+ * can't be recorded meanwhile still stops it. */
14
+ export class TurnParked extends Error {
15
+ code = "TURN_PARKED";
16
+ constructor(message) {
17
+ super(message);
18
+ this.name = "TurnParked";
19
+ }
20
+ }
11
21
  /** A node that delivered no record. `final` says a second attempt would end the same way, so a recovery driver gives
12
22
  * it none: the runner's own bounds (the turn cap, no progress, a refusal) are final; an abort, a timeout or a model
13
23
  * error is not. */
@@ -1,24 +1,3 @@
1
- import type { ChildProcess } from "node:child_process";
2
- /** What a box may reach. Everything else of the host is absent inside it. */
3
- export interface BoxSpec {
4
- /** Bound read-write at its own host path, which is the box's working directory (--chdir), and at /workspace too. */
5
- workspace: string;
6
- /** The harness's homes (per-run directories, never the server's $HOME), each bound read-write at its own path. */
7
- homes: Record<string, string>;
8
- /** Read-only, at their own paths, beside the system allowlist: node and the pinned CLIs. */
9
- readOnly: readonly string[];
10
- /** The model front's Unix socket, bound at /run/agentrun/model.sock. */
11
- modelSocket: string;
12
- /** The forwarder's loopback port in the box (the forwarder is the caller's to start). */
13
- modelPort: number;
14
- /** The egress proxy's Unix socket, bound at /run/agentrun/egress.sock; absent when the box has no egress. */
15
- egressSocket?: string;
16
- egressPort?: number;
17
- /** The box's whole environment: --clearenv, then one --setenv each. Nothing is inherited. */
18
- env: Record<string, string>;
19
- /** On a shared server: the run's cgroup v2, a path under the delegated subtree. */
20
- cgroup?: string;
21
- }
22
1
  /** A box as it is recorded on disk: its id and cgroup before it starts, then its pid 1, that pid's start time (clock
23
2
  * ticks since boot, /proc/<pid>/stat field 22) and its pid namespace (`pid:[<inode>]`). */
24
3
  export interface BoxRecord {
@@ -40,23 +19,6 @@ export interface BoxRecorder {
40
19
  ahead(record: BoxRecord): void;
41
20
  started(record: BoxRecord): Promise<void>;
42
21
  }
43
- /** A started box: the bwrap process (its stdio is the harness's), and its record, complete once `ready` resolves. */
44
- export interface BoxedChild {
45
- readonly child: ChildProcess;
46
- readonly exited: Promise<{
47
- code: number | null;
48
- signal: NodeJS.Signals | null;
49
- }>;
50
- stderrTail(): string;
51
- alive(): boolean;
52
- /** Ends the box: SIGKILL to its pid 1 (start time checked), which takes every process of its namespace with it. */
53
- kill(): void;
54
- /** The record so far: the id and cgroup at once, the pid, start time and pid namespace once `ready` resolves. */
55
- readonly record: BoxRecord;
56
- /** Resolves once the pid is recorded and the box released; rejects (bwrap killed, the harness never ran) when bwrap
57
- * could not start or `started` failed. */
58
- readonly ready: Promise<BoxRecord>;
59
- }
60
22
  /** What a reap found, by the kernel's own count: the processes left in the recorded pid namespace, or the cgroup's.
61
23
  * `none`: the record names neither a pid nor a cgroup, so there was nothing to count (a crash before the pid was
62
24
  * known; --die-with-parent ends such a box with its parent). */
@@ -65,31 +27,11 @@ export interface Reaped {
65
27
  left: number;
66
28
  by: "pidns" | "cgroup" | "none";
67
29
  }
68
- export type Isolation = {
69
- mode: "bwrap" | "seatbelt" | "provider";
70
- cgroup: boolean;
71
- }
72
- /** Only from AGENTRUN_BOX=unsandboxed, the operator's setting. */
73
- | {
74
- mode: "unsandboxed";
75
- } | {
76
- mode: "unavailable";
77
- error: BoxErrorCode;
78
- detail: string;
79
- };
80
30
  export type BoxErrorCode = "bwrap_missing" | "bwrap_setuid" | "bwrap_userns_denied" | "box_probe_failed" | "box_refused" | "box_record_failed" | "box_start_failed"
81
31
  /** A start while the session's last box is live, being reaped, or was not confirmed empty. */
82
32
  | "box_busy"
83
33
  /** A reap whose own count was not 0. */
84
34
  | "box_not_empty";
85
- export interface Box {
86
- readonly isolation: Isolation;
87
- start(spec: BoxSpec, child: {
88
- command: string;
89
- args: string[];
90
- }, record: BoxRecorder): BoxedChild;
91
- reap(record: BoxRecord): Promise<Reaped>;
92
- }
93
35
  /** A box refused or failed, with its named cause. */
94
36
  export declare class BoxError extends Error {
95
37
  readonly code: BoxErrorCode;
package/dist/host/box.js CHANGED
@@ -1,3 +1,10 @@
1
+ // The box a harness process runs in, as the kernel names it: the record that names a box on disk before it runs, what a
2
+ // reap found, and the error a box is refused or fails with. Written for AgentRun.
3
+ //
4
+ // A box is the standard isolation (bubblewrap on Linux): the harness runs as the server's own uid inside its own user,
5
+ // pid, mount and network namespaces, and sees only what the spec binds. Its exit code and its output are never evidence
6
+ // of anything: only the kernel's own count (the processes in the box's pid namespace, or its cgroup's population) says
7
+ // a box is empty.
1
8
  /** A box refused or failed, with its named cause. */
2
9
  export class BoxError extends Error {
3
10
  code;
@@ -1,16 +1,12 @@
1
1
  export { ANTHROPIC_IMAGE_TOKENS_MAX, ANTHROPIC_TOOL_USE_SYSTEM_PROMPT_TOKENS, ASSUMED_TOOL_PROMPT_TOKENS, INPUT_OVERHEAD_APIS, OPENAI_IMAGE_TOKENS_MAX, providerInputOverhead, type InputShape } from "./overhead.js";
2
- export { hostHeaderProblems, inputTokensMaxOf, matchRoute, parseStrict, providerIdsOf, ProxyRefusal, reportedCostOf, sameKey, startModelProxy } from "./proxy.js";
3
- export type { ModelProxy, ModelProxyHooks, ModelProxyOptions, ModelUsageReport, ProviderPolicy, ProxyRequest, ProxyRoute, ProxyUsage } from "./proxy.js";
2
+ export { hostHeaderProblems, ProxyRefusal, sameKey, startModelProxy } from "./proxy.js";
3
+ export type { ModelProxy, ModelProxyHooks, ModelProxyOptions, ModelUsageReport, ProviderPolicy, ProxyRequest, ProxyRequestContext, ProxyRoute, ProxyUsage } from "./proxy.js";
4
+ export { mcpRoute } from "./mcp-route.js";
5
+ export type { McpHandler, McpRouteOptions } from "./mcp-route.js";
4
6
  export { processAlive } from "./alive.js";
5
7
  export { serialWriter } from "./serial.js";
6
- export { addressBytes, checkAddress, EGRESS_RANGES } from "./egress-table.js";
7
- export type { EgressClass, EgressVerdict } from "./egress-table.js";
8
- export { parseAllow, startEgressProxy } from "./egress-proxy.js";
9
- export type { EgressLookup, EgressProxy, EgressProxyOptions } from "./egress-proxy.js";
10
8
  export { PARENT_WATCH_SHIM, parentWatched, parentWatchHere, SETPRIV } from "./parent-death.js";
11
9
  export type { LaunchCommand, ParentWatch } from "./parent-death.js";
12
10
  export { BoxError } from "./box.js";
13
- export type { Box, BoxedChild, BoxErrorCode, BoxRecord, BoxRecorder, BoxSpec, Isolation, Reaped } from "./box.js";
14
- export { boxSlot } from "./box-slot.js";
15
- export type { BoxSlot, BoxSlotState, BoxStart, SlotChild } from "./box-slot.js";
11
+ export type { BoxErrorCode, BoxRecord, BoxRecorder, Reaped } from "./box.js";
16
12
  export { checkedOnce, sha256OfFile } from "./pinned-binary.js";
@@ -1,12 +1,10 @@
1
1
  // What a harness adapter runs beside its harness on the host: the session's model proxy, provider-neutral, with each
2
2
  // provider's rules in a `ProviderPolicy`. Written for AgentRun.
3
3
  export { ANTHROPIC_IMAGE_TOKENS_MAX, ANTHROPIC_TOOL_USE_SYSTEM_PROMPT_TOKENS, ASSUMED_TOOL_PROMPT_TOKENS, INPUT_OVERHEAD_APIS, OPENAI_IMAGE_TOKENS_MAX, providerInputOverhead } from "./overhead.js";
4
- export { hostHeaderProblems, inputTokensMaxOf, matchRoute, parseStrict, providerIdsOf, ProxyRefusal, reportedCostOf, sameKey, startModelProxy } from "./proxy.js";
4
+ export { hostHeaderProblems, ProxyRefusal, sameKey, startModelProxy } from "./proxy.js";
5
+ export { mcpRoute } from "./mcp-route.js";
5
6
  export { processAlive } from "./alive.js";
6
7
  export { serialWriter } from "./serial.js";
7
- export { addressBytes, checkAddress, EGRESS_RANGES } from "./egress-table.js";
8
- export { parseAllow, startEgressProxy } from "./egress-proxy.js";
9
8
  export { PARENT_WATCH_SHIM, parentWatched, parentWatchHere, SETPRIV } from "./parent-death.js";
10
9
  export { BoxError } from "./box.js";
11
- export { boxSlot } from "./box-slot.js";
12
10
  export { checkedOnce, sha256OfFile } from "./pinned-binary.js";
@@ -0,0 +1,14 @@
1
+ import type { IncomingMessage, ServerResponse } from "node:http";
2
+ import type { SessionMcp } from "../types.js";
3
+ /** The protocol revisions answered, newest first: a client asking for another gets the newest. */
4
+ export declare const MCP_ROUTE_VERSIONS: readonly string[];
5
+ export interface McpRouteOptions {
6
+ /** How often a call in flight sends a keepalive. Default 15 s. */
7
+ keepaliveMs?: number;
8
+ /** The `_meta` key of a `tools/call` that carries the harness's own id for the call (McpClient.callIdMeta); none, the
9
+ * call has no id. */
10
+ callIdMeta?: string;
11
+ }
12
+ /** The handler a model proxy mounts at `/mcp/<server>` (ModelProxyOptions.mcp). */
13
+ export type McpHandler = (server: string, req: IncomingMessage, res: ServerResponse) => Promise<void>;
14
+ export declare function mcpRoute(mcp: SessionMcp, options?: McpRouteOptions): McpHandler;
@@ -0,0 +1,125 @@
1
+ import { parseStrict } from "./proxy.js";
2
+ /** The protocol revisions answered, newest first: a client asking for another gets the newest. */
3
+ export const MCP_ROUTE_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26"];
4
+ const MAX_BODY = 4 * 1024 * 1024;
5
+ const KEEPALIVE_MS = 15_000;
6
+ const isPlain = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
7
+ const isId = (v) => typeof v === "string" || (typeof v === "number" && Number.isSafeInteger(v));
8
+ export function mcpRoute(mcp, options = {}) {
9
+ const keepaliveMs = options.keepaliveMs ?? KEEPALIVE_MS;
10
+ const servers = new Map(mcp.servers.map((server) => [server.name, server]));
11
+ /** Calls in flight, by server and JSON-RPC id. */
12
+ const running = new Map();
13
+ const keyOf = (server, id) => `${server}\0${typeof id}:${id}`;
14
+ const json = (res, status, body) => {
15
+ res.writeHead(status, body === undefined ? { "content-length": "0" } : { "content-type": "application/json" });
16
+ res.end(body === undefined ? undefined : JSON.stringify(body));
17
+ };
18
+ const failure = (id, code, message) => ({ jsonrpc: "2.0", id, error: { code, message } });
19
+ return async (server, req, res) => {
20
+ const served = servers.get(server);
21
+ if (!served)
22
+ return json(res, 404, failure(null, -32601, `this session has no MCP server ${server}`));
23
+ if (req.method !== "POST") {
24
+ res.writeHead(405, { allow: "POST", "content-length": "0" });
25
+ return void res.end();
26
+ }
27
+ const chunks = [];
28
+ let size = 0;
29
+ for await (const chunk of req) {
30
+ size += chunk.length;
31
+ if (size > MAX_BODY)
32
+ return json(res, 413, failure(null, -32600, "the request is too large"));
33
+ chunks.push(chunk);
34
+ }
35
+ let message;
36
+ try {
37
+ const parsed = parseStrict(Buffer.concat(chunks).toString("utf8"));
38
+ if (!isPlain(parsed))
39
+ return json(res, 400, failure(null, -32600, "one JSON-RPC message per request; no batches"));
40
+ message = parsed;
41
+ }
42
+ catch {
43
+ return json(res, 400, failure(null, -32700, "the body is not JSON"));
44
+ }
45
+ const params = isPlain(message.params) ? message.params : {};
46
+ // A notification, or the client's answer to a request: nothing to say back.
47
+ if (typeof message.method !== "string" || message.id === undefined) {
48
+ if (message.method === "notifications/cancelled" && isId(params.requestId))
49
+ running.get(keyOf(server, params.requestId))?.abort();
50
+ return json(res, 202);
51
+ }
52
+ if (!isId(message.id))
53
+ return json(res, 400, failure(null, -32600, "the request's id must be a string or an integer"));
54
+ const id = message.id;
55
+ const answer = (result) => json(res, 200, { jsonrpc: "2.0", id, result });
56
+ switch (message.method) {
57
+ case "initialize": {
58
+ const asked = params.protocolVersion;
59
+ const protocolVersion = typeof asked === "string" && MCP_ROUTE_VERSIONS.includes(asked) ? asked : MCP_ROUTE_VERSIONS[0];
60
+ return answer({ protocolVersion, capabilities: { tools: {} }, serverInfo: { name: `agentrun-${server}`, version: "1.0.0" } });
61
+ }
62
+ case "ping":
63
+ return answer({});
64
+ case "tools/list":
65
+ return answer({ tools: served.tools.map((tool) => ({ name: tool.name, ...(tool.title ? { title: tool.title } : {}), description: tool.description ?? "", inputSchema: tool.inputSchema, ...(tool.annotations ? { annotations: tool.annotations } : {}) })) });
66
+ case "tools/call":
67
+ return call(server, id, params, req, res);
68
+ default:
69
+ return json(res, 200, failure(id, -32601, `${String(message.method).slice(0, 64)} is not a method this server answers`));
70
+ }
71
+ };
72
+ async function call(server, id, params, req, res) {
73
+ const meta = isPlain(params._meta) ? params._meta : {};
74
+ const progressToken = isId(meta.progressToken) ? meta.progressToken : undefined;
75
+ // The harness's own id for the call, under the key its adapter declared (McpClient.callIdMeta), and no other.
76
+ const own = options.callIdMeta !== undefined && Object.hasOwn(meta, options.callIdMeta) ? meta[options.callIdMeta] : undefined;
77
+ const callId = typeof own === "string" ? own : undefined;
78
+ const stream = String(req.headers.accept ?? "").includes("text/event-stream");
79
+ const controller = new AbortController();
80
+ const key = keyOf(server, id);
81
+ running.set(key, controller);
82
+ // A client gone before the answer: its call is aborted, upstream too.
83
+ res.once("close", () => { if (!res.writableFinished)
84
+ controller.abort(); });
85
+ const send = (body) => res.write(`event: message\ndata: ${JSON.stringify(body)}\n\n`);
86
+ let timer;
87
+ if (stream) {
88
+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" });
89
+ res.flushHeaders();
90
+ let beat = 0;
91
+ timer = setInterval(() => {
92
+ beat += 1;
93
+ if (progressToken === undefined)
94
+ res.write(": keepalive\n\n");
95
+ else
96
+ send({ jsonrpc: "2.0", method: "notifications/progress", params: { progressToken, progress: beat } });
97
+ }, keepaliveMs);
98
+ }
99
+ let result;
100
+ try {
101
+ const name = params.name;
102
+ const args = isPlain(params.arguments) ? params.arguments : {};
103
+ const granted = typeof name === "string" && servers.get(server).tools.some((tool) => tool.name === name);
104
+ result = granted
105
+ // The door calls the session's MCP (serve's gateway.call); its target is the tool plane's one invoke() (fix 2).
106
+ ? await mcp.call(server, name, args, { signal: controller.signal, ...(callId ? { callId } : {}) })
107
+ : { content: [{ type: "text", text: `${String(name).slice(0, 64)} is not a tool of the MCP server ${server} in this session.` }], isError: true };
108
+ }
109
+ catch (error) {
110
+ result = { content: [{ type: "text", text: `The MCP server ${server}'s call failed: ${String(error?.message ?? error).slice(0, 300)}` }], isError: true };
111
+ }
112
+ finally {
113
+ clearInterval(timer);
114
+ running.delete(key);
115
+ }
116
+ if (res.destroyed)
117
+ return;
118
+ // What the client reads of the answer: its content, and whether it failed (never the host's `parked`).
119
+ const body = { jsonrpc: "2.0", id, result: { content: result.content, ...(result.isError ? { isError: true } : {}) } };
120
+ if (!stream)
121
+ return json(res, 200, body);
122
+ send(body);
123
+ res.end();
124
+ }
125
+ }
@@ -1,4 +1,5 @@
1
1
  import { type IncomingHttpHeaders } from "node:http";
2
+ import { type McpClient, type NoteRequest, type SessionMcp } from "../types.js";
2
3
  import { type Ended } from "../booking.js";
3
4
  /** A route a policy admits: its method, its exact path, and the request headers forwarded with it. */
4
5
  export interface ProxyRoute {
@@ -31,8 +32,10 @@ export interface ProviderPolicy {
31
32
  /** A listed request header's value as forwarded, or undefined to drop it; a `ProxyRefusal` refuses the request before
32
33
  * the runner is asked (a beta the policy does not know). Default: as sent. */
33
34
  header?(name: string, value: string): string | undefined;
34
- /** The body the provider gets for a request on `route`: throw a `ProxyRefusal` to refuse it. */
35
- apply(body: unknown, route: ProxyRoute): Record<string, unknown>;
35
+ /** The body the provider gets for a request on `route`: throw a `ProxyRefusal` to refuse it. `context.host`: the
36
+ * request is the host's own, beside the harness's (ModelProxy.sideKey), whose tools are its own client-side ones, not
37
+ * the session's. */
38
+ apply(body: unknown, route: ProxyRoute, context?: ProxyRequestContext): Record<string, unknown>;
36
39
  /** The usage a completed response reports, if it reports one: from its whole text, or, for a long one, its first and
37
40
  * last 64 KiB (a provider may report input tokens as a stream starts and output tokens as it ends). */
38
41
  usageOf(text: string): ProxyUsage | undefined;
@@ -40,6 +43,11 @@ export interface ProviderPolicy {
40
43
  * reads it, never by matching its words, and from `lineStarts`, the start of each of its last whole lines (16 KiB of
41
44
  * each, for a line longer than the text kept). Absent: the policy cannot tell, and no answer is read as stopped. */
42
45
  filtered?(text: string, lineStarts: readonly string[]): boolean;
46
+ /** Whether the provider cut an answer at its output limit (stopReason "length"), read as `filtered` reads its stop, with
47
+ * the output tokens the answer reports when it says them. Absent: the policy cannot tell, and no answer is read as cut. */
48
+ cut?(text: string, lineStarts: readonly string[]): {
49
+ outputTokens?: number;
50
+ } | undefined;
43
51
  /** Whether a request is the turn's answer request (the client's own turn, which offers the model the session's tools),
44
52
  * and not a side call its client makes beside the turn (a title, a summary): only an answer request's content-filter
45
53
  * stop ends the turn; a side call's is logged and left to the client. Absent: every request is the turn's. */
@@ -89,6 +97,10 @@ export interface ProviderPolicy {
89
97
  * can buy): never more than it asked for, and never longer as sent, since its input bound was measured on it. A host
90
98
  * that limits a request's output needs it: without it such a request is refused, never sent unlimited. */
91
99
  limitOutput?(body: Record<string, unknown>, max: number): Record<string, unknown>;
100
+ /** `body` with `text` added as a note the provider reads after everything the client sent (the spend cap's wrap-up),
101
+ * carrying no cache marker of its own, so the prefix the client built, and cached, stays byte for byte as sent. Absent:
102
+ * the policy cannot place one, and a note waits for a request whose policy can. */
103
+ addNote?(body: Record<string, unknown>, text: string): Record<string, unknown>;
92
104
  /** The status a request the runner refused gets: one the client does not retry. Default 400. */
93
105
  readonly refusedStatus?: number;
94
106
  }
@@ -113,6 +125,43 @@ export interface ModelUsageReport extends ProxyUsage {
113
125
  * beside `stoppedAfterBytes`. */
114
126
  stoppedReasoningBytes?: number;
115
127
  }
128
+ /** What of a response reached its client, event by event: each whole server-sent event (up to a blank line) read by
129
+ * each of `readers`, its bytes added to that reader's sum; a reader the policy does not have counts none. */
130
+ /** What a secret this proxy sent reads as in a provider's error the harness gets. */
131
+ export declare const REDACTED = "[redacted]";
132
+ /** The forms a provider may echo `secrets` in: as sent, JSON-escaped, with "/" escaped as "\/" (some JSON encoders do), and
133
+ * both at once, the longest first, so a form that holds a shorter one is cut whole. */
134
+ export declare function echoForms(secrets: readonly string[]): string[];
135
+ /** The most of an error the cut holds back while the host's redactor may still be reading a value it knows across the
136
+ * pieces: no secret it holds is longer. */
137
+ export declare const REDACT_WINDOW = 4096;
138
+ /** The most of an event the relay holds while it cannot yet tell whether the event is an error's: past it, the event is
139
+ * told from what came of it, and nothing of it is held whole. */
140
+ export declare const EVENT_HOLD: number;
141
+ /**
142
+ * What the harness gets of a provider's answer: as it came, but for the provider's own words in an error, where a secret
143
+ * this proxy sent (`forms`, echoForms) is cut out and then the host's `redact` runs.
144
+ * - `error` (an answer with an error status): cut as it comes. What goes out is what can no longer change: the end that
145
+ * could still begin a form is held, and, with a host redactor, the last REDACT_WINDOW characters too, so a value it
146
+ * knows is never split between two of its readings. An error body the provider never finishes still reaches the
147
+ * client as it comes, past what is held. The body's end is cut, and a start of a form it ends on is cut too.
148
+ * - `events` (a successful streamed answer): each event is told from its fields, whatever their order: an `event:` name
149
+ * of an error, or its data's JSON (a type of `error` or `response.failed`, or an `error`), an `id:`, `retry:` or
150
+ * comment line read past; a healthy name exempts nothing, its data is still read. An error event is cut as an error
151
+ * answer is, as it comes; every other event has the credential's forms of MIN_ECHO characters or more cut and passes
152
+ * otherwise byte for byte, only
153
+ * the start of a form held back (never past a line end). An event is held only until it can be told (an error's
154
+ * name, or its data line whole), and at most EVENT_HOLD of it: past that it is told from what came (a data line whose
155
+ * type comes first), and one that still cannot be is cut as an error's. Nothing a healthy event sent is kept.
156
+ * - `as-is`: every piece as it came.
157
+ * `tokens` (the forms of values too short to tell from text by chance) are cut in an error alone, and only as a whole
158
+ * token: in an error body anywhere, in an error event only inside a data line's value, never a field's name.
159
+ * A `redact` that throws leaves the cut, and is said.
160
+ */
161
+ export declare function errorCut(mode: "error" | "events" | "as-is", forms: readonly string[], redact: ((text: string) => string) | undefined, say: (message: string) => void, tokens?: readonly string[]): {
162
+ push(text: string): string;
163
+ end(): string;
164
+ };
116
165
  /** A paid request as the host is asked about it, before it leaves. */
117
166
  export interface ProxyRequest {
118
167
  model: string;
@@ -122,6 +171,13 @@ export interface ProxyRequest {
122
171
  outputTokensAsked?: number;
123
172
  /** The least output it may be limited to and still answer (the policy's `outputLeast`). */
124
173
  outputTokensLeast?: number;
174
+ /** A side call, never its turn's own: on another model than the session's (a client's small-model call: a title, a
175
+ * summary), or the host's own request beside the harness's (`host`). */
176
+ side?: true;
177
+ /** It carries the host's note (`ModelProxyHooks.note`), placed in its body: the host's to record once it is admitted. */
178
+ noted?: true;
179
+ /** The label of the side key it came under (ModelProxy.sideKey): the host's own request, beside the harness's. */
180
+ host?: string;
125
181
  }
126
182
  export interface ModelProxyHooks {
127
183
  /** Before a paid request leaves; a throw refuses it. What it returns (a ticket) is handed back to this request's
@@ -134,6 +190,10 @@ export interface ModelProxyHooks {
134
190
  /** When a paid request's response headers arrive, before its body: the ids they give it (`providerIdsOf`), so a
135
191
  * request a crash cuts off after this point is known to have reached the provider, under those ids. */
136
192
  responded?(ids: Record<string, string>, ticket?: unknown): Promise<void>;
193
+ /** A note the host has for the session's next main-model request (the spend cap's wrap-up), taken by this call: the
194
+ * proxy asks only for a paid request on the session's model whose policy can place one (`addNote`), with that request
195
+ * as its client sent it (NoteRequest: its input bound and output asks, measured before the note is placed). */
196
+ note?(model: string, request?: NoteRequest): string | undefined;
137
197
  }
138
198
  export interface ModelProxyOptions {
139
199
  policy: ProviderPolicy;
@@ -146,6 +206,11 @@ export interface ModelProxyOptions {
146
206
  origin: string;
147
207
  /** The provider's credential, read for each request. */
148
208
  credential: () => string | Promise<string>;
209
+ /** The host's redactor, for a provider's own words in an error (an answer with an error status, or an error event inside
210
+ * a streamed answer): the harness keeps them, so they pass through it. Before it, and whatever it does, the credential
211
+ * this proxy sent and the values of the headers it added are cut out of them (a provider echoes a wrong key back):
212
+ * the harness never holds the provider's credential. */
213
+ redact?: (text: string) => string;
149
214
  /** The price of a response, or null when it is unknown. */
150
215
  price?: (model: string, usage: ProxyUsage) => number | null;
151
216
  log?: (message: string, detail?: Record<string, unknown>) => void;
@@ -161,11 +226,25 @@ export interface ModelProxyOptions {
161
226
  * after the client's, so the client can neither set nor override them, and before the credential's. Checked when the
162
227
  * proxy starts (`hostHeaderProblems`). */
163
228
  headers?: Readonly<Record<string, string>>;
229
+ /** The session's remote MCP servers, each mounted here at `/mcp/<server>` behind the session's key (mcp-route.ts),
230
+ * for the harness's own MCP client as its adapter declares it (`client`, AdapterCapabilities.mcpClient). One mount for
231
+ * every harness: an adapter hands the session's MCP, never a route of its own. */
232
+ mcp?: {
233
+ session: SessionMcp;
234
+ client: McpClient;
235
+ keepaliveMs?: number;
236
+ };
164
237
  /** For tests: the fetch the proxy forwards with. */
165
238
  fetch?: typeof fetch;
166
239
  /** Told, with CONTENT_FILTERED, once an answer the provider stopped on its content filter has been passed and booked
167
240
  * (`ProviderPolicy.filtered`): the harness halts the turn with it, before its client asks for the answer again. */
168
241
  onFiltered?: (message: string) => void;
242
+ /** Told, once an answer request's answer, once its stop says the provider cut it at its output limit
243
+ * (`ProviderPolicy.cut`), before its client has the piece that carries the stop: a harness whose client would ask for
244
+ * the answer again (Codex retries an incomplete stream) ends the turn there, the answer cut ("length"). */
245
+ onCut?: (stop: {
246
+ outputTokens?: number;
247
+ }) => void;
169
248
  }
170
249
  /** What is wrong with headers a host would add to forwarded requests: a name that is not a token or is reserved, a value
171
250
  * an HTTP header cannot carry (a line break or other control character, or a character beyond Latin-1, which the fetch
@@ -176,8 +255,23 @@ export interface ModelProxy {
176
255
  readonly url: string;
177
256
  /** The key the harness sends, which the proxy admits. */
178
257
  readonly key: string;
258
+ /** A key of the host's own for the requests it sends beside the harness's on this session's route (a learned
259
+ * workflow's model node, `label` "learned_workflow"): one per label, random, minted here and never handed to the
260
+ * harness. A request under it goes through the same policy, origin, credential, price and hooks as the harness's;
261
+ * its admission names the label (ModelRequest.host), the policy applies it as the host's (`ProxyRequestContext`),
262
+ * it is never the turn's answer request (a content-filter stop on it never halts the turn) and never watched. It opens
263
+ * the model routes only: the session's MCP door stays behind the session's key. */
264
+ sideKey(label: string): string;
265
+ /** The harness opened its next turn: once the proxy has told it a turn's answer stopped (onCut, onFiltered), it refuses
266
+ * the session's answer requests, unsent and unbooked, until this is called. */
267
+ openTurn(): void;
179
268
  close(): Promise<void>;
180
269
  }
270
+ /** What a policy is told of the request it applies: the label of the side key it came under (ModelProxy.sideKey), when
271
+ * it is the host's own request. */
272
+ export interface ProxyRequestContext {
273
+ readonly host?: string;
274
+ }
181
275
  /** The ids a response's headers give its request, by header name, so a run's books can be joined to the provider's (or
182
276
  * a gateway's) request by request; undefined when there are none. Only id-named headers with id-shaped values. */
183
277
  export declare function providerIdsOf(headers: Headers): Record<string, string> | undefined;