@parcha/agentrun-harness-claude 0.1.0-beta.31 → 0.1.0-beta.33
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 +36 -0
- package/dist/adapter.d.ts +6 -1
- package/dist/adapter.js +64 -13
- package/dist/binary.js +1 -1
- package/dist/env.js +1 -1
- package/dist/facts.d.ts +2 -0
- package/dist/facts.js +36 -0
- package/dist/harness.d.ts +19 -12
- package/dist/harness.js +16 -33
- package/dist/host/machine.d.ts +7 -3
- package/dist/host/machine.js +3 -1
- package/dist/host/policy.d.ts +14 -6
- package/dist/host/policy.js +34 -8
- package/dist/host/process.d.ts +2 -38
- package/dist/host/process.js +1 -12
- package/dist/host/tool-server.d.ts +9 -2
- package/dist/host/tool-server.js +6 -6
- package/dist/ids.js +1 -1
- package/dist/inbox.js +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/resume.d.ts +22 -0
- package/dist/resume.js +78 -0
- package/dist/serial.js +2 -1
- package/dist/store.d.ts +7 -0
- package/dist/store.js +14 -0
- package/dist/testing/fake-anthropic.js +1 -1
- package/dist/testing/fake-sdk.d.ts +12 -1
- package/dist/testing/fake-sdk.js +59 -6
- package/dist/transcript.d.ts +8 -1
- package/dist/transcript.js +19 -2
- package/dist/versions.js +1 -1
- package/package.json +8 -4
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,42 @@
|
|
|
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 Agent 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
|
+
- 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.
|
|
19
|
+
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.
|
|
20
|
+
- 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.
|
|
21
|
+
- `@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).
|
|
22
|
+
- `@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.
|
|
23
|
+
- `@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.
|
|
24
|
+
- 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.
|
|
25
|
+
- 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.
|
|
26
|
+
- 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.
|
|
27
|
+
- 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.
|
|
28
|
+
- 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.
|
|
29
|
+
- 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.
|
|
30
|
+
- The harness takes the MCP library a host loaded (`mcp`, passed to its tool server) and exports `claudeAgentPlatform()`, the suffix of the Claude Agent SDK's CLI package for this machine. A host can now install the Claude Agent SDK on first use and load it from its own directory; this package still ships none.
|
|
31
|
+
- 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.
|
|
32
|
+
- A capped Claude Agent run told to wrap up at the start of a turn no longer fails that turn. The CLI ends a turn's first request with a system message of its own, and the provider takes one only before an assistant message or at the end, so the note sent as a user message after it was refused (400) and the turn failed. The note now goes as the last block of the last user message, and the CLI's system message stays last.
|
|
33
|
+
- 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.
|
|
34
|
+
|
|
35
|
+
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.").
|
|
36
|
+
|
|
37
|
+
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.
|
|
38
|
+
- 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.
|
|
39
|
+
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.
|
|
40
|
+
|
|
5
41
|
## 0.1.0-beta.31 (2026-11-06)
|
|
6
42
|
|
|
7
43
|
- 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.
|
package/dist/adapter.d.ts
CHANGED
|
@@ -3,6 +3,7 @@ import { type ModelProxyOptions } from "@parcha/agentrun-kernel/host";
|
|
|
3
3
|
import { ClaudeAgentNotInstalled, ClaudeAgentPinMismatch } from "./errors.js";
|
|
4
4
|
import { type ClaudeAgentSdk } from "./harness.js";
|
|
5
5
|
import { type ConfineChild } from "./host/machine.js";
|
|
6
|
+
import type { ToolServerModules } from "./host/tool-server.js";
|
|
6
7
|
export { CLAUDE_AGENT_CLI_SKILL_NAMES } from "./cli-names.js";
|
|
7
8
|
/** The pinned CLI's tools the copied harness leaves undecided, off by name in every session (WebSearch unless `webSearch`). */
|
|
8
9
|
export declare const CLAUDE_AGENT_ALSO_OFF: readonly string[];
|
|
@@ -75,6 +76,10 @@ export interface ClaudeAgentAdapterOptions {
|
|
|
75
76
|
sdk?: ClaudeAgentSdk;
|
|
76
77
|
/** The injected module's version, as its package.json says: checked when the adapter is made. */
|
|
77
78
|
sdkVersion?: string;
|
|
79
|
+
/** The MCP library the session's tools are served with (`@modelcontextprotocol/sdk`'s `server/mcp.js` and
|
|
80
|
+
* `types.js`), loaded by the host from where it installed the SDK, its peer. Default: imported by name, beside this
|
|
81
|
+
* package. */
|
|
82
|
+
mcp?: ToolServerModules;
|
|
78
83
|
/** The CLI to run (the SDK's platform package's `claude`). Default: found beside the SDK. Its sha256 and version are
|
|
79
84
|
* checked against the pins when the adapter is made. */
|
|
80
85
|
cliPath?: string;
|
|
@@ -116,7 +121,7 @@ export declare function verifyClaudeAgentCli(path: string | undefined, pins?: {
|
|
|
116
121
|
} | ClaudeAgentPinMismatch | ClaudeAgentNotInstalled;
|
|
117
122
|
/** What the adapter runs with, or the typed reason it cannot: the SDK (injected or installed) and its CLI, each the
|
|
118
123
|
* pinned build. `installed` looks a package's version up (default: where Node would import it from here). */
|
|
119
|
-
export declare function verifyClaudeAgent(options: Pick<ClaudeAgentAdapterOptions, "sdk" | "sdkVersion" | "cliPath">, installed?: (name: string) => string | undefined): {
|
|
124
|
+
export declare function verifyClaudeAgent(options: Pick<ClaudeAgentAdapterOptions, "sdk" | "sdkVersion" | "cliPath" | "mcp">, installed?: (name: string) => string | undefined): {
|
|
120
125
|
cliPath: string;
|
|
121
126
|
};
|
|
122
127
|
/** The kernel's tool for a host tool: the same name, schema and replay policy, reported to the host under that name. */
|
package/dist/adapter.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
// `beforeRequest` first, and its usage comes back through `afterRequest`. The runner alone accounts model spend.
|
|
9
9
|
//
|
|
10
10
|
// The Agent SDK is the host's: an exact optional peer dependency (`CLAUDE_AGENT_SDK_VERSION`), never shipped here.
|
|
11
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
11
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
12
12
|
import { execFileSync } from "node:child_process";
|
|
13
13
|
import { accessSync, constants, mkdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
14
14
|
import { dirname, join } from "node:path";
|
|
@@ -16,12 +16,13 @@ import { READ_SKILL_FILE, readSkillFileTool, skillProblems } from "@parcha/agent
|
|
|
16
16
|
import { abortedOutcome, openDrive, pendingSubmissions, Restart, SessionHalt } from "@parcha/agentrun-kernel/kernel";
|
|
17
17
|
import { toolSchemaProblems } from "@parcha/agentrun-kernel";
|
|
18
18
|
import { NativeJournal, recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
|
|
19
|
-
import { checkedOnce, hostHeaderProblems,
|
|
19
|
+
import { checkedOnce, hostHeaderProblems, sha256OfFile, startModelProxy } from "@parcha/agentrun-kernel/host";
|
|
20
|
+
import { anthropicPolicy, withWebSearches } from "./host/policy.js";
|
|
20
21
|
import { findClaudeExecutable, platformSuffix } from "./binary.js";
|
|
21
22
|
import { CLAUDE_AGENT_PACKAGE, ClaudeAgentNotInstalled, ClaudeAgentPinMismatch, ClaudeAgentThinkingOff } from "./errors.js";
|
|
22
23
|
import { claudeCodeHarness, lostPrompts } from "./harness.js";
|
|
23
24
|
import { JournalSessionStore } from "./store.js";
|
|
24
|
-
import { localMachine } from "./host/machine.js";
|
|
25
|
+
import { CLAUDE_MCP_CLIENT, localMachine } from "./host/machine.js";
|
|
25
26
|
import { serialWriter } from "./serial.js";
|
|
26
27
|
import { MCP_SERVER } from "./transcript.js";
|
|
27
28
|
import { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_CODE_VERSION, installedVersion } from "./versions.js";
|
|
@@ -148,15 +149,16 @@ export function verifyClaudeAgent(options, installed = installedVersion) {
|
|
|
148
149
|
throw new ClaudeAgentPinMismatch("sdk_version", CLAUDE_AGENT_SDK_VERSION, sdkVersion);
|
|
149
150
|
// The session's tools are served by an MCP server built here (host/tool-server.ts), whichever SDK runs: an injected
|
|
150
151
|
// SDK does not bring the MCP library, so a missing one is refused now, not at the first turn.
|
|
151
|
-
if (installed("@modelcontextprotocol/sdk") === undefined)
|
|
152
|
+
if (!options.mcp && installed("@modelcontextprotocol/sdk") === undefined)
|
|
152
153
|
throw new ClaudeAgentNotInstalled(`@modelcontextprotocol/sdk is not installed beside ${CLAUDE_AGENT_PACKAGE} (the Agent SDK's peer, which serves the session's tools; npm installs it with the SDK)`, CLAUDE_AGENT_SDK_INSTALL);
|
|
153
154
|
const cli = verifyClaudeAgentCli(options.cliPath ?? findClaudeExecutable());
|
|
154
155
|
if (cli instanceof Error)
|
|
155
156
|
throw cli;
|
|
156
157
|
return { cliPath: cli.path };
|
|
157
158
|
}
|
|
158
|
-
/** A stand-in CLI is for a test runner only
|
|
159
|
-
|
|
159
|
+
/** A stand-in CLI is for a test runner only: node --test's own mark (NODE_TEST_CONTEXT), never NODE_ENV=test, which a
|
|
160
|
+
* production server can carry. */
|
|
161
|
+
const standInAllowed = () => process.env.AGENTRUN_CLAUDE_AGENT_STANDIN === "1" && Boolean(process.env.NODE_TEST_CONTEXT) && process.env.NODE_ENV !== "production";
|
|
160
162
|
/** The kernel's tool for a host tool: the same name, schema and replay policy, reported to the host under that name. */
|
|
161
163
|
/** The most a tool's image may be, as base64, by default: the strictest of the platforms Claude runs on (Anthropic's API
|
|
162
164
|
* takes 10 MB, Amazon Bedrock 5 MB), so one setting holds everywhere. */
|
|
@@ -226,6 +228,8 @@ function kernelTool(tool, io, maxImageBytes, calls) {
|
|
|
226
228
|
async execute(input, effect) {
|
|
227
229
|
// The effect's step is `tool:<the CLI's tool_use id>#<attempt>`: the host sees the CLI's call id.
|
|
228
230
|
const callId = (effect.stepId ?? "").replace(/^tool:/, "").replace(/#\d+$/, "");
|
|
231
|
+
// The step's attempt: above 0 when a crash cut an earlier attempt and the kernel runs the call again.
|
|
232
|
+
const attempt = Number(/#(\d+)$/.exec(effect.stepId ?? "")?.[1] ?? 0);
|
|
229
233
|
// In flight, and past the pause's check, before the host hears of it: a pause the host starts on this tool_start
|
|
230
234
|
// waits for this call rather than refusing it.
|
|
231
235
|
calls.begin(callId);
|
|
@@ -233,7 +237,7 @@ function kernelTool(tool, io, maxImageBytes, calls) {
|
|
|
233
237
|
if (calls.draining)
|
|
234
238
|
throw new Error(`${tool.name} was not run: the session is pausing`);
|
|
235
239
|
io.onEvent({ type: "tool_start", callId, name: tool.name, args: input });
|
|
236
|
-
const result = await tool.call(input, { callId, signal: effect.signal });
|
|
240
|
+
const result = await tool.call(input, { callId, signal: effect.signal, attempt });
|
|
237
241
|
if (result.isError)
|
|
238
242
|
throw new Error(result.text);
|
|
239
243
|
if (!result.images?.length)
|
|
@@ -289,8 +293,7 @@ export function claudeAgentAdapter(options) {
|
|
|
289
293
|
};
|
|
290
294
|
return {
|
|
291
295
|
id: CLAUDE_AGENT_ID,
|
|
292
|
-
|
|
293
|
-
capabilities: () => ({ fork: false }),
|
|
296
|
+
capabilities: () => ({ mcpClient: CLAUDE_MCP_CLIENT }),
|
|
294
297
|
check(spec) {
|
|
295
298
|
const problems = [];
|
|
296
299
|
if (spec.context === "fork")
|
|
@@ -353,7 +356,7 @@ export function claudeAgentAdapter(options) {
|
|
|
353
356
|
...(options.provider.headers ? { headers: options.provider.headers } : {}),
|
|
354
357
|
...(options.log ? { log: options.log } : {}),
|
|
355
358
|
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
356
|
-
...(spec.mcp ? { mcp: {
|
|
359
|
+
...(spec.mcp ? { mcp: { session: spec.mcp, tools: [...mcpNames] } } : {}),
|
|
357
360
|
},
|
|
358
361
|
});
|
|
359
362
|
// The SDK this session runs on (the host's, or the one installed beside this package, checked above), thinking at
|
|
@@ -366,8 +369,6 @@ export function claudeAgentAdapter(options) {
|
|
|
366
369
|
attach: (ctx, request) => acquire({ ctx, ...(request.model ? { model: request.model } : {}), ...(request.deadline === undefined ? {} : { deadline: request.deadline }) }),
|
|
367
370
|
// No command of its own: the CLI reaches nothing but its model proxy (a web search, when on, is the provider's).
|
|
368
371
|
network: "deny-all",
|
|
369
|
-
// The runner's turn cap and the host's beforeRequest bound the spend.
|
|
370
|
-
budget: { turnUsd: Infinity, sessionUsd: Infinity },
|
|
371
372
|
},
|
|
372
373
|
tools: tools.map((tool) => kernelTool(tool, io, maxImageBytes, calls)),
|
|
373
374
|
builtins: false,
|
|
@@ -384,12 +385,18 @@ export function claudeAgentAdapter(options) {
|
|
|
384
385
|
gatewayUrl: options.provider.origin,
|
|
385
386
|
executable,
|
|
386
387
|
sdk,
|
|
388
|
+
...(options.mcp ? { toolServerModules: options.mcp } : {}),
|
|
387
389
|
...(options.log ? { log: options.log } : {}),
|
|
390
|
+
// The host's gate, asked about each host-tool call before it is written or run.
|
|
391
|
+
...(io.gate ? { gate: (call) => io.gate(call) } : {}),
|
|
388
392
|
});
|
|
389
393
|
const live = (event) => {
|
|
390
394
|
const e = event;
|
|
391
395
|
if (e?.type === "text" && typeof e.delta === "string")
|
|
392
396
|
io.onEvent({ type: "text", delta: e.delta });
|
|
397
|
+
// The model's message ended inside the turn (the CLI resumes a cut answer itself): what it said so far is one message.
|
|
398
|
+
if (e?.type === "text_end")
|
|
399
|
+
io.onEvent({ type: "text_end" });
|
|
393
400
|
// An MCP call, recorded as a built-in's: the host hears of it once its intent is in the session's records.
|
|
394
401
|
if (e?.type === "tool_start" && typeof e.callId === "string" && typeof e.name === "string" && mcpNames.has(e.name)) {
|
|
395
402
|
calls.begin(e.callId);
|
|
@@ -427,11 +434,16 @@ export function claudeAgentAdapter(options) {
|
|
|
427
434
|
state = "idle";
|
|
428
435
|
running = (async () => {
|
|
429
436
|
let outcome;
|
|
437
|
+
// A turn whose final answer the model cut at its output limit, the CLI's recovery of it spent, says so on its
|
|
438
|
+
// turn_end: stopReason "length", with the output tokens its result reports.
|
|
439
|
+
let stop = {};
|
|
430
440
|
for (let attempt = 0; !outcome; attempt += 1) {
|
|
431
441
|
const current = drive;
|
|
432
442
|
try {
|
|
433
443
|
await harness.drive(current);
|
|
434
444
|
const ended = turnsIn(current).slice(before).at(-1)?.data;
|
|
445
|
+
if (ended?.stopReason === "length")
|
|
446
|
+
stop = { stopReason: "length", ...(typeof ended.outputTokens === "number" ? { outputTokens: ended.outputTokens } : {}) };
|
|
435
447
|
outcome = ended?.status ? { status: ended.status, ...(ended.error ? { error: ended.error } : {}) } : { status: "failed", error: "the turn ended with no outcome in the session's records" };
|
|
436
448
|
}
|
|
437
449
|
catch (error) {
|
|
@@ -450,7 +462,7 @@ export function claudeAgentAdapter(options) {
|
|
|
450
462
|
outcome = { status: "failed", error: String(error?.message ?? error).slice(0, 500) };
|
|
451
463
|
}
|
|
452
464
|
}
|
|
453
|
-
io.onEvent({ type: "turn_end", status: outcome.status });
|
|
465
|
+
io.onEvent({ type: "turn_end", status: outcome.status, ...stop });
|
|
454
466
|
return outcome;
|
|
455
467
|
})();
|
|
456
468
|
return running;
|
|
@@ -465,6 +477,41 @@ export function claudeAgentAdapter(options) {
|
|
|
465
477
|
if (drive.signal.aborted && !io.signal.aborted)
|
|
466
478
|
drive = await open();
|
|
467
479
|
};
|
|
480
|
+
// The session's host port (AdapterSession.port): the host's own requests beside the CLI's (a learned workflow's node)
|
|
481
|
+
// on the session's route, built from the drive proxy's own pieces (the same policy, origin, credential, price, headers
|
|
482
|
+
// and the session's booking, io.models), but on a listener the session holds: a drive's proxy closes with its drive
|
|
483
|
+
// (a park ends the turn; a restart opens none), and an approved call runs before any turn. It serves side keys only:
|
|
484
|
+
// the CLI never holds its key. Its policy object is its own: anything a policy keeps per instance stays apart from the
|
|
485
|
+
// drive's, as a side call's should. Closed with the session, or when the host lets the session go (io.signal).
|
|
486
|
+
// Started once the session's drive is open, the last step that can fail: an open that fails leaves no listener.
|
|
487
|
+
const hostPort = await startModelProxy({
|
|
488
|
+
policy: anthropicPolicy({
|
|
489
|
+
model: modelFor(spec),
|
|
490
|
+
...(options.smallModel ? { smallModel: options.smallModel } : {}),
|
|
491
|
+
tools: [],
|
|
492
|
+
...(webSearch ? { webSearch: true, ...(options.webSearchAllowance !== undefined ? { webSearchAllowance: options.webSearchAllowance } : {}) } : {}),
|
|
493
|
+
...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}),
|
|
494
|
+
...(options.provider.auth ? { auth: options.provider.auth } : {}),
|
|
495
|
+
}),
|
|
496
|
+
hooks: io.models,
|
|
497
|
+
model: modelFor(spec),
|
|
498
|
+
origin: options.provider.origin,
|
|
499
|
+
credential: async () => (await options.provider.credential()) ?? "",
|
|
500
|
+
...(options.price ? { price: withWebSearches(options.price) } : {}),
|
|
501
|
+
...(options.provider.headers ? { headers: options.provider.headers } : {}),
|
|
502
|
+
...(options.log ? { log: options.log } : {}),
|
|
503
|
+
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
504
|
+
}, randomBytes(32).toString("base64url"));
|
|
505
|
+
let hostClosed = false;
|
|
506
|
+
const closeHost = async () => {
|
|
507
|
+
if (hostClosed)
|
|
508
|
+
return;
|
|
509
|
+
hostClosed = true;
|
|
510
|
+
await hostPort.close().catch(() => { });
|
|
511
|
+
};
|
|
512
|
+
io.signal.addEventListener("abort", () => void closeHost(), { once: true });
|
|
513
|
+
if (io.signal.aborted)
|
|
514
|
+
await closeHost();
|
|
468
515
|
return {
|
|
469
516
|
get state() { return state; },
|
|
470
517
|
async send(text) {
|
|
@@ -530,7 +577,11 @@ export function claudeAgentAdapter(options) {
|
|
|
530
577
|
closed = true;
|
|
531
578
|
drive.halt?.(new SessionHalt("closed"));
|
|
532
579
|
await running?.catch(() => { });
|
|
580
|
+
await closeHost();
|
|
533
581
|
},
|
|
582
|
+
// The session's one model route, for the host's own request beside the CLI's: the session's host port, which
|
|
583
|
+
// never restarts once closed.
|
|
584
|
+
port: (label) => (closed || hostClosed ? undefined : { url: hostPort.url, key: hostPort.sideKey(label), model: modelFor(spec), api: "anthropic-messages" }),
|
|
534
585
|
};
|
|
535
586
|
},
|
|
536
587
|
};
|
package/dist/binary.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
|
|
2
2
|
// From github.com/vercel-labs/durable-harness, packages/harness-claude-code/src/binary.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
|
|
3
|
-
// Changed by Parcha,
|
|
3
|
+
// Changed by Parcha, and AgentRun's own since the port from upstream froze on 2026-11-07.
|
|
4
4
|
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
5
5
|
import { dirname, join } from 'node:path';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
package/dist/env.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
|
|
2
2
|
// From github.com/vercel-labs/durable-harness, packages/harness-claude-code/src/env.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
|
|
3
|
-
// Changed by Parcha,
|
|
3
|
+
// Changed by Parcha, and AgentRun's own since the port from upstream froze on 2026-11-07.
|
|
4
4
|
/**
|
|
5
5
|
* The durable environment of the `claude` CLI in the session's VM
|
|
6
6
|
* (docs/workspaces.md §5.6 "Env"). It replaces the parent's environment
|
package/dist/facts.d.ts
ADDED
package/dist/facts.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// What claude-agent is, as its adapter states it (AdapterFacts): a host reads these and never branches on its name. They
|
|
2
|
+
// describe the harness; none renames or reshapes what its model sees, and none turns its built-ins, sandbox or session
|
|
3
|
+
// machine on.
|
|
4
|
+
import { toolSchemaProblems } from "@parcha/agentrun-kernel";
|
|
5
|
+
import { anthropicPolicy } from "./host/policy.js";
|
|
6
|
+
import { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION } from "./versions.js";
|
|
7
|
+
export const facts = Object.freeze({
|
|
8
|
+
id: "claude-agent",
|
|
9
|
+
label: "Claude",
|
|
10
|
+
wire: "anthropic-messages",
|
|
11
|
+
// A message that comes mid-turn waits for the turn's end.
|
|
12
|
+
steer: false,
|
|
13
|
+
// A call that started is never run again (the CLI answers it "[Tool call interrupted]"); only the model calls again.
|
|
14
|
+
rerunsStarted: false,
|
|
15
|
+
// An answer its output limit cut, the CLI resumes itself in the same turn ("Output token limit hit. Resume directly"),
|
|
16
|
+
// up to 3 times; only a cut it no longer resumes ends the turn cut.
|
|
17
|
+
recoversCutAnswers: 3,
|
|
18
|
+
// One run's memory, measured with the server's (serve's host.ts): the CLI and its SDK beside the run's process.
|
|
19
|
+
runMib: 288,
|
|
20
|
+
// Its own MCP client binds the session's remote MCP servers.
|
|
21
|
+
mcp: true,
|
|
22
|
+
thinking: Object.freeze(["low", "medium", "high", "xhigh", "max"]),
|
|
23
|
+
// Anthropic's web search, through the session's proxy, as the pinned CLI's WebSearch asks for it.
|
|
24
|
+
webSearch: "native",
|
|
25
|
+
// Its model is Anthropic's, on its own settings, never the gateway's default for the other harnesses.
|
|
26
|
+
ownModel: true,
|
|
27
|
+
// Anthropic's ids hold no dot; OpenRouter names the same models with dots (anthropic/claude-sonnet-5.5).
|
|
28
|
+
normalizeModel: (model) => (model.provider === "anthropic" ? { ...model, modelId: model.modelId.replaceAll(".", "-") } : model),
|
|
29
|
+
install: Object.freeze({ npmLine: CLAUDE_AGENT_SDK_INSTALL, spec: `@anthropic-ai/claude-agent-sdk@${CLAUDE_AGENT_SDK_VERSION}`, codes: Object.freeze({ install: "CLAUDE_AGENT_NOT_INSTALLED", pins: "CLAUDE_AGENT_PIN_MISMATCH" }) }),
|
|
30
|
+
// The CLI drops a tool whose schema fails the kernel's check, or whose root holds anyOf, allOf or oneOf (measured on
|
|
31
|
+
// the pinned CLI), without a word.
|
|
32
|
+
// The CLI's own tools, each the host's table tool it is.
|
|
33
|
+
nativeTools: Object.freeze({ WebSearch: "web_search", WebFetch: "web_fetch", Bash: "bash", Read: "read", Write: "write", Edit: "edit" }),
|
|
34
|
+
schemaProblems: (tool, schema) => [...toolSchemaProblems(tool, schema), ...["anyOf", "allOf", "oneOf"].filter((key) => key in schema).map((key) => `/${key}: the Claude Agent CLI drops a tool whose root has ${key}`)],
|
|
35
|
+
policy: (options) => anthropicPolicy({ model: options.model, tools: options.tools, ...(options.auth ? { auth: options.auth } : {}), ...(options.webSearch === true ? { webSearch: true, ...(options.webSearchAllowance ? { webSearchAllowance: options.webSearchAllowance } : {}) } : {}), ...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}) }),
|
|
36
|
+
});
|
package/dist/harness.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import type { GateAnswer, GateCall } from '@parcha/agentrun-kernel';
|
|
1
2
|
import { type DriveContext, type Harness, type HostTool, type ReplayPolicy, type SessionState, type Submission } from './host/kernel.js';
|
|
2
3
|
import { type GatewayHandler, type ProviderTool, type SessionMachine } from './host/process.js';
|
|
4
|
+
import { toolServer } from './host/tool-server.js';
|
|
3
5
|
import { JournalSessionStore } from './store.js';
|
|
4
6
|
/**
|
|
5
7
|
* Claude Code on harness-world: a kernel `Harness` that drives the Claude
|
|
@@ -34,10 +36,9 @@ import { JournalSessionStore } from './store.js';
|
|
|
34
36
|
* **The model.** The CLI's base URL is the VM's model port, its key the
|
|
35
37
|
* attach's model key (`SessionMachine.modelKey`); every request it sends is
|
|
36
38
|
* relayed to this drive's `gatewayHandler` (Claude's fixed table, the body
|
|
37
|
-
* policy, the model allowlist, the
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
* session cap ends the turn at once with an `Unavailable` naming the cap.
|
|
39
|
+
* policy, the model allowlist, the credential), so the VM never holds a
|
|
40
|
+
* credential (decision 6). The spend is the runner's: each request is booked
|
|
41
|
+
* through the host's model port, and the host's cap bounds it.
|
|
41
42
|
*
|
|
42
43
|
* **Tools.** Tool-less by default: the app's `HostTool`s (`tools`) are the
|
|
43
44
|
* CLI's only tools (`tools: []`), and the system prompt says so. With
|
|
@@ -50,7 +51,10 @@ import { JournalSessionStore } from './store.js';
|
|
|
50
51
|
* in the log; `PostToolUse` / `PostToolUseFailure` the outcome, after the
|
|
51
52
|
* Drive's writes are flushed for a mutating call), so after a crash the
|
|
52
53
|
* recovery note says which calls completed and which were interrupted ("may
|
|
53
|
-
* have half-run"); nothing reruns one.
|
|
54
|
+
* have half-run"); nothing reruns one. A host-tool call the transcript left
|
|
55
|
+
* with no result and no intent (a park held it at the host's gate) runs on
|
|
56
|
+
* the resume, gate first, and its result is in the transcript before the CLI
|
|
57
|
+
* starts (`resumeDanglingCalls`). Bash's timeout is clamped to what is
|
|
54
58
|
* left of the invocation, so a command never outlives it: one the clamp ends
|
|
55
59
|
* is recorded as out of time, never left open. Claude Code runs its commands
|
|
56
60
|
* under its own sandbox (bubblewrap, checked by a self-test in the VM before
|
|
@@ -94,11 +98,6 @@ export interface ClaudeSandbox {
|
|
|
94
98
|
readonly env?: Readonly<Record<string, string>>;
|
|
95
99
|
/** `sandbox({ network })`: what the CLI's own sandbox lets commands reach, and whether provider-hosted tools may run. */
|
|
96
100
|
readonly network: ClaudeSandboxNetwork;
|
|
97
|
-
/** `sandbox({ budget })`'s dollar caps (`Infinity` turns one off). */
|
|
98
|
-
readonly budget: {
|
|
99
|
-
readonly turnUsd: number;
|
|
100
|
-
readonly sessionUsd: number;
|
|
101
|
-
};
|
|
102
101
|
/** `sandbox({ commandTimeoutMs })`: the longest a Bash command may run. */
|
|
103
102
|
readonly commandTimeoutMs?: number;
|
|
104
103
|
/**
|
|
@@ -175,13 +174,19 @@ export interface ClaudeCodeHarnessOptions {
|
|
|
175
174
|
* model proxy (`<modelUrl>/mcp/<name>`, behind the session's key), with the
|
|
176
175
|
* tools granted on each: those are allowed by name (`mcp__<name>__<tool>`)
|
|
177
176
|
* and each call is recorded as a built-in's. They are set over the CLI's
|
|
178
|
-
* stdin (`setMcpServers`), never in its argv.
|
|
179
|
-
*
|
|
177
|
+
* stdin (`setMcpServers`), never in its argv. The proxy answers the
|
|
178
|
+
* handshake: an unreachable server shows at its first call. Default none.
|
|
180
179
|
*/
|
|
181
180
|
mcpServers?: readonly {
|
|
182
181
|
readonly name: string;
|
|
183
182
|
readonly tools: readonly string[];
|
|
184
183
|
}[];
|
|
184
|
+
/**
|
|
185
|
+
* The MCP library the session's tool server is built with, as the host
|
|
186
|
+
* loaded it from where it installed the Agent SDK. Default: imported by
|
|
187
|
+
* name.
|
|
188
|
+
*/
|
|
189
|
+
toolServerModules?: Parameters<typeof toolServer>[3];
|
|
185
190
|
/** Provider-hosted tools the model may use; default none. `web_search` turns the CLI's WebSearch on, built-ins off or
|
|
186
191
|
* not: each call recorded as a built-in's (the session's model proxy decides what the provider may run). */
|
|
187
192
|
providerTools?: readonly ProviderTool[];
|
|
@@ -231,6 +236,8 @@ export interface ClaudeCodeHarnessOptions {
|
|
|
231
236
|
unsandboxedCommands?: boolean;
|
|
232
237
|
/** Called with the child's stderr tail when it exits mid-turn, the gateway's refusals, and SDK diagnostics. */
|
|
233
238
|
log?: (message: string, fields?: Record<string, unknown>) => void;
|
|
239
|
+
/** The host's gate (SessionIO.gate), asked by the tool bridge about each call of `tools` before its intent. */
|
|
240
|
+
gate?: (call: GateCall) => Promise<GateAnswer>;
|
|
234
241
|
}
|
|
235
242
|
/** The default model. */
|
|
236
243
|
export declare const DEFAULT_MODEL = "claude-sonnet-4-5";
|
package/dist/harness.js
CHANGED
|
@@ -1,18 +1,19 @@
|
|
|
1
1
|
// Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
|
|
2
2
|
// From github.com/vercel-labs/durable-harness, packages/harness-claude-code/src/harness.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
|
|
3
|
-
// Changed by Parcha,
|
|
3
|
+
// Changed by Parcha, and AgentRun's own since the port from upstream froze on 2026-11-07.
|
|
4
4
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
5
5
|
import { randomUUID } from 'node:crypto';
|
|
6
6
|
import { mkdtemp, rm } from 'node:fs/promises';
|
|
7
7
|
import { tmpdir } from 'node:os';
|
|
8
8
|
import { dirname, join, posix } from 'node:path';
|
|
9
9
|
import { Restart, Unavailable } from './host/kernel.js';
|
|
10
|
-
import { BuiltinCalls, CLAUDE_ROUTES, gatewayCredential, gatewayHandler, gatewayUrl, isBrandedMachine,
|
|
10
|
+
import { BuiltinCalls, CLAUDE_ROUTES, gatewayCredential, gatewayHandler, gatewayUrl, isBrandedMachine, NativeJournal, openTurn, placeSubmissions, recoveryNote, restartEvent, replayBy, toolBridge, waitForSubmissions, } from './host/process.js';
|
|
11
11
|
import { durableEnv, nativeModelId } from './env.js';
|
|
12
12
|
import { uuidFrom } from './ids.js';
|
|
13
13
|
import { MessageQueue } from './inbox.js';
|
|
14
14
|
import { sandboxSpawn } from './spawn.js';
|
|
15
15
|
import { MCP_OUTPUT_TOKENS, toolServer } from './host/tool-server.js';
|
|
16
|
+
import { resumeDanglingCalls } from './resume.js';
|
|
16
17
|
import { JournalSessionStore } from './store.js';
|
|
17
18
|
import { MCP_SERVER, TranscriptBuilder } from './transcript.js';
|
|
18
19
|
import { CLAUDE_AGENT_CLI_SKILL_NAMES } from './cli-names.js';
|
|
@@ -192,15 +193,13 @@ export function claudeCodeHarness(options = {}) {
|
|
|
192
193
|
};
|
|
193
194
|
return {
|
|
194
195
|
name: options.name ?? 'claude-agent',
|
|
195
|
-
// Each model request reaches the provider through the session's proxy
|
|
196
|
+
// Each model request reaches the provider through the session's proxy, which books it through the host's model port.
|
|
196
197
|
modelCalls: 'self',
|
|
197
198
|
async drive(ctx) {
|
|
198
199
|
// Nothing to do (an idle wake, a chaos arming): no VM. A model step a
|
|
199
200
|
// crash left open after its turn ended is closed (no request will retry it).
|
|
200
|
-
if (!recoveryNote(ctx.state()) && ctx.pending().length === 0)
|
|
201
|
-
await settleAbandonedModelSteps(ctx);
|
|
201
|
+
if (!recoveryNote(ctx.state()) && ctx.pending().length === 0)
|
|
202
202
|
return;
|
|
203
|
-
}
|
|
204
203
|
const sandbox = options.sandbox;
|
|
205
204
|
if (!sandbox)
|
|
206
205
|
throw sandboxRequired();
|
|
@@ -213,27 +212,16 @@ export function claudeCodeHarness(options = {}) {
|
|
|
213
212
|
// that started the drive.
|
|
214
213
|
const inDrive = AsyncLocalStorage.snapshot();
|
|
215
214
|
const credential = options.credential ?? gatewayCredential;
|
|
216
|
-
// The handler also sees each model request start and end: the drive's
|
|
217
|
-
// model steps, written around a "Crash during: model" drill.
|
|
218
|
-
const steps = new ModelSteps(ctx, options.log ? { log: options.log } : {});
|
|
219
|
-
const ledger = journalLedger(journal, { records });
|
|
220
215
|
if (ctx.deadline === undefined)
|
|
221
216
|
log('claude-agent: the kernel gave no deadline; assuming a 300 s invocation', {});
|
|
222
217
|
const deadline = ctx.deadline ?? Date.now() + ASSUMED_INVOCATION_MS;
|
|
223
218
|
const handler = gatewayHandler({
|
|
224
219
|
routes: CLAUDE_ROUTES,
|
|
225
220
|
models: { model, ...(smallModel ? { smallModel } : {}) },
|
|
226
|
-
budget: sandbox.budget,
|
|
227
|
-
ledger,
|
|
228
221
|
providerTools,
|
|
229
222
|
network: sandbox.network === 'allow-all' || sandbox.network === 'deny-all' ? sandbox.network : 'custom',
|
|
230
223
|
credential: () => inDrive(credential),
|
|
231
224
|
target: options.gatewayUrl ?? gatewayUrl(),
|
|
232
|
-
track: steps.request,
|
|
233
|
-
onCap: (cap) => {
|
|
234
|
-
if (cap !== 'concurrency')
|
|
235
|
-
ctx.halt?.(spendCapped(cap));
|
|
236
|
-
},
|
|
237
225
|
// A refused key fails the turn at the provider's first 401, in the words the CLI would end on after its retries.
|
|
238
226
|
onKeyRefused: (detail) => ctx.halt?.(new Error(`Failed to authenticate. API Error: 401${detail ? ` ${detail}` : ''}`)),
|
|
239
227
|
// Without the app's own log, the handler's default: a refused model call is a warning in the Function's logs, not silence.
|
|
@@ -288,7 +276,12 @@ export function claudeCodeHarness(options = {}) {
|
|
|
288
276
|
void store.resultBarrier(refused.callId, barrierMs).then(() => ctx.live(e), (error) => log('claude-agent: a refused call is not shown: its answer never reached the log', { callId: refused.callId, error: String(error?.message ?? error).slice(0, 200) }));
|
|
289
277
|
},
|
|
290
278
|
});
|
|
279
|
+
const gate = options.gate;
|
|
291
280
|
const bridge = toolBridge(ctx, tools, {
|
|
281
|
+
// The host's gate before the intent, so a refused or parked call leaves nothing of its own written. The
|
|
282
|
+
// assistant line that made the call is in the log before the gate is asked: a park ends the claim, and the
|
|
283
|
+
// resume finds the call it held dangling in the transcript, under the same id (resumeDanglingCalls).
|
|
284
|
+
...(gate ? { gate: async (call) => (await store.barrier(call.callId, barrierMs), gate(call)) } : {}),
|
|
292
285
|
// A `never` tool runs only once the assistant entry that asked for it is in the log.
|
|
293
286
|
beforeNever: ({ callId }) => store.barrier(callId, barrierMs),
|
|
294
287
|
});
|
|
@@ -317,7 +310,7 @@ export function claudeCodeHarness(options = {}) {
|
|
|
317
310
|
finally {
|
|
318
311
|
calls.delete(running);
|
|
319
312
|
}
|
|
320
|
-
});
|
|
313
|
+
}, options.toolServerModules);
|
|
321
314
|
const allow = (updatedInput) => ({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow', ...(updatedInput ? { updatedInput } : {}) } });
|
|
322
315
|
const deny = (reason) => ({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reason } });
|
|
323
316
|
/**
|
|
@@ -474,6 +467,11 @@ export function claudeCodeHarness(options = {}) {
|
|
|
474
467
|
const sdkEnv = { ...vmEnv, CLAUDE_CONFIG_DIR: configDir };
|
|
475
468
|
const disallowed = [...CLAUDE_BUILTINS_OFF, ...(providerTools.includes('web_search') ? [] : ['WebSearch']), ...(options.disallowedTools ?? [])].filter((name) => !(skills && name === 'Skill'));
|
|
476
469
|
const sessionId = uuidFrom(ctx.runId);
|
|
470
|
+
// A host-tool call the transcript left dangling that never started (a park held it, or the process died before
|
|
471
|
+
// its intent): it runs now, the host's gate first, and its result is in the transcript before the CLI resumes it.
|
|
472
|
+
// One with an intent is left to the CLI's repair and the recovery note, as before; nothing ever runs one twice.
|
|
473
|
+
if (store.hasSession)
|
|
474
|
+
await resumeDanglingCalls(ctx, bridge, store);
|
|
477
475
|
// A turn a crash cut off: the harness's own account of it (which calls completed, which may have half-run) goes
|
|
478
476
|
// in this drive's system prompt, not in a user message the model might answer back to the user. A resumed
|
|
479
477
|
// session sends the system prompt recorded at its start (`snapshot`), whatever a later launch passes, so this
|
|
@@ -549,9 +547,6 @@ export function claudeCodeHarness(options = {}) {
|
|
|
549
547
|
// (the key of its placement), so a recovery can find it in the
|
|
550
548
|
// transcript (`lostPrompts`).
|
|
551
549
|
const first = placed[0]?.id;
|
|
552
|
-
// A new turn's spend is keyed by its first submission; a steer joins the turn it steers, and a recovery note keeps the key of the turn it resumes (set before).
|
|
553
|
-
if (first && how.priority !== 'next' && !how.synthetic)
|
|
554
|
-
ledger.turn(first);
|
|
555
550
|
const uuid = !first ? randomUUID() : how.synthetic ? uuidFrom(`note:${first}`) : uuidFrom(first);
|
|
556
551
|
// A recovery message carries placed prompts' words: which, under its uuid, before it goes (lostPrompts reads it).
|
|
557
552
|
if (how.covers?.length)
|
|
@@ -684,8 +679,6 @@ export function claudeCodeHarness(options = {}) {
|
|
|
684
679
|
const open = openTurn(ctx.state());
|
|
685
680
|
const note = recovered && recoveryNote(ctx.state());
|
|
686
681
|
if (note) {
|
|
687
|
-
if (open)
|
|
688
|
-
ledger.turn(open.placed[0] ?? `open:${open.since}`);
|
|
689
682
|
// The CLI answers again from the interrupted step: what a reader saw of its reply is replaced by what the log kept.
|
|
690
683
|
ctx.live(restartEvent(note.turn));
|
|
691
684
|
const covers = [...(open ? lostPrompts(ctx.state(), open.placed, store) : []), ...note.pending.map((s) => s.id)];
|
|
@@ -703,8 +696,6 @@ export function claudeCodeHarness(options = {}) {
|
|
|
703
696
|
await send(s.text ?? '', [s]);
|
|
704
697
|
await runTurn();
|
|
705
698
|
}
|
|
706
|
-
// A model step a crash left open that no request of this drive made again: closed.
|
|
707
|
-
await steps.settleAbandoned();
|
|
708
699
|
// Let the CLI exit (stdin closed) and the SDK deliver its last mirror frames.
|
|
709
700
|
input.end();
|
|
710
701
|
await drain(messages, 10_000);
|
|
@@ -737,8 +728,6 @@ export function claudeCodeHarness(options = {}) {
|
|
|
737
728
|
// Nothing the model started outlives the drive: the session's processes in the VM are killed (the VM and the Drive stay).
|
|
738
729
|
if (held)
|
|
739
730
|
await held.close().catch(() => { });
|
|
740
|
-
// No model step outlives the drive.
|
|
741
|
-
await steps.close();
|
|
742
731
|
if (configDir)
|
|
743
732
|
await rm(configDir, { recursive: true, force: true }).catch(() => { });
|
|
744
733
|
}
|
|
@@ -770,12 +759,6 @@ export function protectedPath(root, path) {
|
|
|
770
759
|
return abs === base || abs.startsWith(`${base}/`);
|
|
771
760
|
});
|
|
772
761
|
}
|
|
773
|
-
/** A spend cap the model calls reached: the turn ends, saying which (§5.5 step 6). */
|
|
774
|
-
function spendCapped(cap) {
|
|
775
|
-
return new Unavailable(`The turn stopped: the ${cap === 'turnUsd' ? "turn's" : "session's"} model spend reached its cap (sandbox({ budget: { ${cap} } })).`, {
|
|
776
|
-
hint: `Raise sandbox({ budget: { ${cap} } }) to let the session spend more.`,
|
|
777
|
-
});
|
|
778
|
-
}
|
|
779
762
|
/** The mirror guard (§5.6 "Mirror"): the turn ends, the session is kept. */
|
|
780
763
|
function mirrorUnmapped(why) {
|
|
781
764
|
return new Unavailable(`agentrun-harness-claude: mirror_unmapped: the CLI's transcript mirror sent ${why}, so the transcript can't be kept in the log; this turn ends and the session is kept`, {
|
package/dist/host/machine.d.ts
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { type ChildProcess } from "node:child_process";
|
|
2
|
-
import { type
|
|
2
|
+
import { type ModelProxyHooks, type ModelProxyOptions, type ParentWatch } from "@parcha/agentrun-kernel/host";
|
|
3
|
+
import type { McpClient, SessionMcp } from "@parcha/agentrun-kernel";
|
|
3
4
|
import type { AcquireMachine, MachineSpawn, SessionMachine, SessionProcess } from "./process.js";
|
|
4
5
|
import { type AnthropicPolicyOptions } from "./policy.js";
|
|
6
|
+
/** Claude Code's own MCP client: it sends a call's tool use id in tools/call's `_meta["claudecode/toolUseId"]`. */
|
|
7
|
+
export declare const CLAUDE_MCP_CLIENT: McpClient;
|
|
5
8
|
/** The variables a child takes from this process, when they are set. */
|
|
6
9
|
export declare const INHERITED_ENV: readonly ["PATH", "LANG", "TZ"];
|
|
7
10
|
/** A command and its arguments, as the machine starts it. */
|
|
@@ -32,9 +35,10 @@ export interface LocalMachineOptions {
|
|
|
32
35
|
builtins?: readonly string[];
|
|
33
36
|
/** Admit Anthropic's web search server tool, the one the CLI's WebSearch asks for. */
|
|
34
37
|
webSearch?: boolean;
|
|
35
|
-
/** The session's remote MCP servers,
|
|
38
|
+
/** The session's remote MCP servers, which the kernel's proxy serves at `/mcp/<server>` for the CLI's own MCP client
|
|
39
|
+
* (CLAUDE_MCP_CLIENT), and their granted tools as the CLI names them. */
|
|
36
40
|
mcp?: {
|
|
37
|
-
|
|
41
|
+
session: SessionMcp;
|
|
38
42
|
tools: readonly string[];
|
|
39
43
|
};
|
|
40
44
|
/** The input a request carrying it may read in beyond its body, for its input bound (anthropicPolicy). */
|
package/dist/host/machine.js
CHANGED
|
@@ -17,6 +17,8 @@ import { dirname, isAbsolute, join, normalize, sep } from "node:path";
|
|
|
17
17
|
import { parentWatched, startModelProxy } from "@parcha/agentrun-kernel/host";
|
|
18
18
|
import { brandMachine } from "./process.js";
|
|
19
19
|
import { anthropicPolicy, withWebSearches } from "./policy.js";
|
|
20
|
+
/** Claude Code's own MCP client: it sends a call's tool use id in tools/call's `_meta["claudecode/toolUseId"]`. */
|
|
21
|
+
export const CLAUDE_MCP_CLIENT = { callIdMeta: "claudecode/toolUseId" };
|
|
20
22
|
/** The variables a child takes from this process, when they are set. */
|
|
21
23
|
export const INHERITED_ENV = Object.freeze(["PATH", "LANG", "TZ"]);
|
|
22
24
|
const DIRS = ["home", "config", "tmp", "cache"];
|
|
@@ -142,7 +144,7 @@ export function localMachine(options) {
|
|
|
142
144
|
credential: async () => (await route.credential()) ?? "",
|
|
143
145
|
...(options.proxy.price ? { price: withWebSearches(options.proxy.price) } : {}),
|
|
144
146
|
...(options.proxy.headers ? { headers: options.proxy.headers } : {}),
|
|
145
|
-
...(options.proxy.mcp ? { mcp: options.proxy.mcp.
|
|
147
|
+
...(options.proxy.mcp ? { mcp: { session: options.proxy.mcp.session, client: CLAUDE_MCP_CLIENT } } : {}),
|
|
146
148
|
...(options.proxy.log ? { log: options.proxy.log } : {}),
|
|
147
149
|
// The provider stopped the turn's answer on its content filter: no retry of it can pass, so the turn ends at once.
|
|
148
150
|
onFiltered: (message) => ctx.halt?.(new Error(message)),
|