@parcha/agentrun-harness-claude 0.0.0-bootstrap.0 → 0.1.0-beta.29

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 (50) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +4 -0
  4. package/README.md +57 -0
  5. package/dist/adapter.d.ts +123 -0
  6. package/dist/adapter.js +487 -0
  7. package/dist/binary.d.ts +25 -0
  8. package/dist/binary.js +71 -0
  9. package/dist/cli-names.d.ts +7 -0
  10. package/dist/cli-names.js +17 -0
  11. package/dist/env.d.ts +81 -0
  12. package/dist/env.js +92 -0
  13. package/dist/errors.d.ts +27 -0
  14. package/dist/errors.js +42 -0
  15. package/dist/harness.d.ts +287 -0
  16. package/dist/harness.js +881 -0
  17. package/dist/host/kernel.d.ts +10 -0
  18. package/dist/host/kernel.js +1 -0
  19. package/dist/host/machine.d.ts +77 -0
  20. package/dist/host/machine.js +259 -0
  21. package/dist/host/policy.d.ts +85 -0
  22. package/dist/host/policy.js +359 -0
  23. package/dist/host/process.d.ts +130 -0
  24. package/dist/host/process.js +31 -0
  25. package/dist/host/tool-server.d.ts +44 -0
  26. package/dist/host/tool-server.js +47 -0
  27. package/dist/ids.d.ts +9 -0
  28. package/dist/ids.js +17 -0
  29. package/dist/inbox.d.ts +14 -0
  30. package/dist/inbox.js +36 -0
  31. package/dist/index.d.ts +11 -0
  32. package/dist/index.js +7 -0
  33. package/dist/serial.d.ts +3 -0
  34. package/dist/serial.js +10 -0
  35. package/dist/spawn.d.ts +51 -0
  36. package/dist/spawn.js +131 -0
  37. package/dist/store.d.ts +119 -0
  38. package/dist/store.js +202 -0
  39. package/dist/testing/fake-anthropic.d.ts +97 -0
  40. package/dist/testing/fake-anthropic.js +279 -0
  41. package/dist/testing/fake-sdk.d.ts +60 -0
  42. package/dist/testing/fake-sdk.js +402 -0
  43. package/dist/testing/index.d.ts +3 -0
  44. package/dist/testing/index.js +5 -0
  45. package/dist/transcript.d.ts +73 -0
  46. package/dist/transcript.js +116 -0
  47. package/dist/versions.d.ts +34 -0
  48. package/dist/versions.js +76 -0
  49. package/package.json +78 -1
  50. package/vendor/durable-harness/UPSTREAM.json +59 -0
@@ -0,0 +1,487 @@
1
+ // The Claude Agent SDK as an AgentRun harness adapter (id `claude-agent`). Written for AgentRun.
2
+ //
3
+ // A session is the copied Claude Agent harness (harness.ts) driven over the session's own records: the kernel's
4
+ // openDrive on the writer the runner lends (`io.writer`), on a local machine (host/machine.ts). The CLI's built-in tools
5
+ // are off, so the host's tools, exactly those `spec.tools` names, are its only tools: each runs through the shared tool
6
+ // bridge as a kernel effect, and a PreToolUse hook denies every other call. Its model is the session's loopback proxy
7
+ // (@parcha/agentrun-kernel/host, with the Anthropic policy in host/policy.ts): every paid request passes the runner's
8
+ // `beforeRequest` first, and its usage comes back through `afterRequest`. The runner alone accounts model spend.
9
+ //
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";
12
+ import { execFileSync } from "node:child_process";
13
+ import { accessSync, constants, mkdirSync, rmSync, statSync, writeFileSync } from "node:fs";
14
+ import { dirname, join } from "node:path";
15
+ import { READ_SKILL_FILE, readSkillFileTool, skillProblems } from "@parcha/agentrun-kernel";
16
+ import { abortedOutcome, openDrive, pendingSubmissions, Restart, SessionHalt } from "@parcha/agentrun-kernel/kernel";
17
+ import { toolSchemaProblems } from "@parcha/agentrun-kernel";
18
+ import { recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
19
+ import { checkedOnce, hostHeaderProblems, sha256OfFile } from "@parcha/agentrun-kernel/host";
20
+ import { findClaudeExecutable, platformSuffix } from "./binary.js";
21
+ import { CLAUDE_AGENT_PACKAGE, ClaudeAgentNotInstalled, ClaudeAgentPinMismatch, ClaudeAgentThinkingOff } from "./errors.js";
22
+ import { claudeCodeHarness } from "./harness.js";
23
+ import { localMachine } from "./host/machine.js";
24
+ import { serialWriter } from "./serial.js";
25
+ import { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_CODE_VERSION, installedVersion } from "./versions.js";
26
+ export { CLAUDE_AGENT_CLI_SKILL_NAMES } from "./cli-names.js";
27
+ /** The pinned CLI's tools the copied harness leaves undecided, off by name in every session (WebSearch unless `webSearch`). */
28
+ export const CLAUDE_AGENT_ALSO_OFF = Object.freeze(["Skill", "WebSearch"]);
29
+ /** The local plugin the session's skills are served from: the model sees each as `agentrun:<name>`, and may load it by
30
+ * that name or, unless the CLI has a command or skill of that name (`CLAUDE_AGENT_CLI_SKILL_NAMES`), by its bare one. */
31
+ export const CLAUDE_AGENT_SKILLS_PLUGIN = "agentrun";
32
+ /** The skills, checked: each a name, a `SKILL.md` whose front matter has that name and a description, and files at plain
33
+ * relative paths, 1 MiB in all; or the problems. @parcha/agentrun-kernel' own check, which the Codex adapter runs too. */
34
+ export { skillProblems };
35
+ /** Writes the skills as the local plugin at `dir` (replacing what was there), and returns their plugin-qualified names. */
36
+ function writeSkillsPlugin(dir, skills) {
37
+ rmSync(dir, { recursive: true, force: true });
38
+ mkdirSync(join(dir, ".claude-plugin"), { recursive: true, mode: 0o700 });
39
+ writeFileSync(join(dir, ".claude-plugin", "plugin.json"), JSON.stringify({ name: CLAUDE_AGENT_SKILLS_PLUGIN, version: "0.0.0", description: "The host's skills for this session." }), { mode: 0o600 });
40
+ for (const skill of skills) {
41
+ for (const [path, text] of Object.entries(skill.files)) {
42
+ const file = join(dir, "skills", skill.name, path);
43
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
44
+ writeFileSync(file, text, { mode: 0o600 });
45
+ }
46
+ }
47
+ return skills.map((skill) => `${CLAUDE_AGENT_SKILLS_PLUGIN}:${skill.name}`);
48
+ }
49
+ /** The adapter's id, as a host's `harness` field names it. */
50
+ export const CLAUDE_AGENT_ID = "claude-agent";
51
+ /** The pinned CLI's sha256, per platform package, where it is recorded; any other platform is checked by its version. */
52
+ export const CLAUDE_AGENT_DIGESTS = Object.freeze({
53
+ "linux-x64": "fe503f65c6289d59c23e5b21ae44f03583f997dd33a2cbfc75ab4f96fb8fc73f",
54
+ });
55
+ /** A tool name the Agent SDK's in-process MCP server takes (the CLI calls it `mcp__hands__<name>`). */
56
+ const TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;
57
+ /** How often one send rebuilds a drive whose CLI exited mid-turn. */
58
+ const RESTARTS = 3;
59
+ const THINKING = new Set(["low", "medium", "high", "xhigh", "max"]);
60
+ /** A session's level: the node's thinking, else its effort (minimal thinks at low, never at nothing), else the adapter's. */
61
+ export function thinkingOf(spec, fallback) {
62
+ const asked = (spec.thinking ?? spec.effort);
63
+ if (asked === "minimal")
64
+ return "low";
65
+ return asked && THINKING.has(asked) ? asked : fallback;
66
+ }
67
+ /** The SDK with every query thinking at `level`: adaptive thinking, at that effort. */
68
+ function thinkingAt(sdk, level) {
69
+ return {
70
+ ...sdk,
71
+ query: ((args) => sdk.query({ ...args, options: { ...args.options, thinking: { type: "adaptive" }, effort: level } })),
72
+ };
73
+ }
74
+ /** The pins a CLI is checked against: its sha256 on this platform (where one is recorded) and its version. */
75
+ export function claudeAgentCliPins() {
76
+ const sha256 = CLAUDE_AGENT_DIGESTS[platformSuffix()];
77
+ return sha256 ? { sha256, version: CLAUDE_CODE_VERSION } : { version: CLAUDE_CODE_VERSION };
78
+ }
79
+ /** The CLI at `path`, checked against the pins: its path, or the typed reason it is not the pinned build. Its sha256 is
80
+ * read a chunk at a time, never the whole CLI in memory, and a check that passed holds for this process while the CLI
81
+ * stays the same file, unchanged (the kernel's checkedOnce): a host that checks it for each model it resolves, and a
82
+ * run's process that makes its adapter, check it once. */
83
+ export function verifyClaudeAgentCli(path, pins = claudeAgentCliPins()) {
84
+ if (!path)
85
+ return new ClaudeAgentNotInstalled(`no CLI of @anthropic-ai/claude-agent-sdk ${CLAUDE_AGENT_SDK_VERSION} for ${platformSuffix()} (its platform package, an optional dependency npm installs with it), and no cliPath`, CLAUDE_AGENT_SDK_INSTALL);
86
+ // Hashed a chunk at a time, and once per CLI in this process while it stays the same file (the kernel's pinned-binary).
87
+ return checkedOnce(path, JSON.stringify(pins), () => checkCli(path, pins), (result) => !(result instanceof Error));
88
+ }
89
+ /** The CLI at `path` against `pins`' sha256 and version. */
90
+ function checkCli(path, pins) {
91
+ try {
92
+ if (!statSync(path).isFile())
93
+ throw new Error("not a file");
94
+ accessSync(path, constants.R_OK);
95
+ }
96
+ catch {
97
+ return new ClaudeAgentNotInstalled(`no CLI at ${path}`);
98
+ }
99
+ if (pins.sha256) {
100
+ let found;
101
+ try {
102
+ found = sha256OfFile(path);
103
+ }
104
+ catch {
105
+ return new ClaudeAgentNotInstalled(`no CLI at ${path}`);
106
+ }
107
+ if (found !== pins.sha256)
108
+ return new ClaudeAgentPinMismatch("cli_sha256", pins.sha256, found, path);
109
+ }
110
+ let version;
111
+ try {
112
+ version = execFileSync(path, ["--version"], { env: { PATH: process.env.PATH ?? "/usr/bin:/bin", DISABLE_AUTOUPDATER: "1" }, encoding: "utf8", timeout: 15_000 }).trim().split(/\s/)[0] ?? "";
113
+ }
114
+ catch (error) {
115
+ return new ClaudeAgentPinMismatch("cli_version", pins.version, `unreadable (${String(error?.message ?? error).slice(0, 120)})`, path);
116
+ }
117
+ if (version !== pins.version)
118
+ return new ClaudeAgentPinMismatch("cli_version", pins.version, version.slice(0, 40), path);
119
+ return { path };
120
+ }
121
+ /** What the adapter runs with, or the typed reason it cannot: the SDK (injected or installed) and its CLI, each the
122
+ * pinned build. `installed` looks a package's version up (default: where Node would import it from here). */
123
+ export function verifyClaudeAgent(options, installed = installedVersion) {
124
+ const sdkVersion = options.sdk ? options.sdkVersion : installed("@anthropic-ai/claude-agent-sdk");
125
+ if (!options.sdk && sdkVersion === undefined)
126
+ throw new ClaudeAgentNotInstalled(`@anthropic-ai/claude-agent-sdk ${CLAUDE_AGENT_SDK_VERSION} is not installed beside ${CLAUDE_AGENT_PACKAGE}, and no module was given (sdk)`, CLAUDE_AGENT_SDK_INSTALL);
127
+ if (sdkVersion !== undefined && sdkVersion !== CLAUDE_AGENT_SDK_VERSION)
128
+ throw new ClaudeAgentPinMismatch("sdk_version", CLAUDE_AGENT_SDK_VERSION, sdkVersion);
129
+ // The session's tools are served by an MCP server built here (host/tool-server.ts), whichever SDK runs: an injected
130
+ // SDK does not bring the MCP library, so a missing one is refused now, not at the first turn.
131
+ if (installed("@modelcontextprotocol/sdk") === undefined)
132
+ 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);
133
+ const cli = verifyClaudeAgentCli(options.cliPath ?? findClaudeExecutable());
134
+ if (cli instanceof Error)
135
+ throw cli;
136
+ return { cliPath: cli.path };
137
+ }
138
+ /** A stand-in CLI is for a test runner only. */
139
+ const standInAllowed = () => process.env.AGENTRUN_CLAUDE_AGENT_STANDIN === "1" && Boolean(process.env.NODE_TEST_CONTEXT || process.env.NODE_ENV === "test") && process.env.NODE_ENV !== "production";
140
+ /** The kernel's tool for a host tool: the same name, schema and replay policy, reported to the host under that name. */
141
+ /** The most a tool's image may be, as base64, by default: the strictest of the platforms Claude runs on (Anthropic's API
142
+ * takes 10 MB, Amazon Bedrock 5 MB), so one setting holds everywhere. */
143
+ export const CLAUDE_AGENT_MAX_IMAGE_BYTES = 5 * 1024 * 1024;
144
+ /** The most `maxImageBytes` may be: Anthropic's API's own limit for one image, as base64. */
145
+ const MAX_IMAGE_BYTES_CEILING = 10 * 1024 * 1024;
146
+ /** The image types Anthropic's API takes. */
147
+ const IMAGE_TYPES = new Set(["image/jpeg", "image/png", "image/gif", "image/webp"]);
148
+ const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
149
+ /** Why a tool's images can't be sent, naming the tool and the image, or undefined: a type the API takes, base64, and at
150
+ * most `maxBytes` of it. */
151
+ export function toolImageProblems(tool, images, maxBytes = CLAUDE_AGENT_MAX_IMAGE_BYTES) {
152
+ for (const [i, image] of images.entries()) {
153
+ const at = `the tool ${tool}'s image ${i + 1}`;
154
+ if (!IMAGE_TYPES.has(image?.mimeType))
155
+ return `${at} is ${String(image?.mimeType).slice(0, 40)}, not one the model takes (${[...IMAGE_TYPES].join(", ")})`;
156
+ if (typeof image.data !== "string" || !BASE64.test(image.data))
157
+ return `${at} is not base64`;
158
+ if (image.data.length > maxBytes)
159
+ return `${at} is ${image.data.length} bytes of base64, more than ${maxBytes}`;
160
+ }
161
+ return undefined;
162
+ }
163
+ /** A session's calls in flight: begun (their intent recorded), their outcome not yet. A pause waits for these to have
164
+ * their outcomes recorded; the host refuses new work meanwhile (the runner's stop does). */
165
+ class CallsInFlight {
166
+ draining = false;
167
+ open = new Set();
168
+ waiters = new Set();
169
+ begin(callId) {
170
+ this.open.add(callId);
171
+ }
172
+ /** The call's outcome is recorded, or it never will be (the drive stopped). */
173
+ end(callId) {
174
+ if (this.open.delete(callId) && this.open.size === 0)
175
+ for (const done of [...this.waiters])
176
+ done();
177
+ }
178
+ clear() {
179
+ this.open.clear();
180
+ for (const done of [...this.waiters])
181
+ done();
182
+ }
183
+ /** Every call in flight has its outcome recorded, or `ms` passed. */
184
+ idle(ms) {
185
+ if (this.open.size === 0)
186
+ return Promise.resolve();
187
+ return new Promise((resolve) => {
188
+ const done = () => {
189
+ clearTimeout(timer);
190
+ this.waiters.delete(done);
191
+ resolve();
192
+ };
193
+ const timer = setTimeout(done, ms);
194
+ this.waiters.add(done);
195
+ });
196
+ }
197
+ }
198
+ /** The kernel's tool for a host tool. The host hears of the call (`tool_start`) once its intent is in the session's
199
+ * records, and of its end only once the outcome is (the live `tool_end` the tool bridge sends after the effect). */
200
+ function kernelTool(tool, io, maxImageBytes, calls) {
201
+ return {
202
+ name: tool.name,
203
+ description: tool.description,
204
+ inputSchema: tool.inputSchema,
205
+ replay: tool.replay,
206
+ async execute(input, effect) {
207
+ // The effect's step is `tool:<the CLI's tool_use id>#<attempt>`: the host sees the CLI's call id.
208
+ const callId = (effect.stepId ?? "").replace(/^tool:/, "").replace(/#\d+$/, "");
209
+ // In flight, and past the pause's check, before the host hears of it: a pause the host starts on this tool_start
210
+ // waits for this call rather than refusing it.
211
+ calls.begin(callId);
212
+ // A guard: a call begun during a pause is not run; the bridge's per-drive mutex keeps it unreachable while calls are serial, and its test lands with the fan-out PR.
213
+ if (calls.draining)
214
+ throw new Error(`${tool.name} was not run: the session is pausing`);
215
+ io.onEvent({ type: "tool_start", callId, name: tool.name, args: input });
216
+ const result = await tool.call(input, { callId, signal: effect.signal });
217
+ if (result.isError)
218
+ throw new Error(result.text);
219
+ if (!result.images?.length)
220
+ return result.text;
221
+ // An image the model can't be sent is the call's error, by the tool's name and the image, not a request refused later.
222
+ const wrong = toolImageProblems(tool.name, result.images, maxImageBytes);
223
+ if (wrong)
224
+ throw new Error(wrong);
225
+ return { text: result.text, images: result.images.map((image) => ({ mimeType: image.mimeType, data: image.data })) };
226
+ },
227
+ };
228
+ }
229
+ const turnsIn = (drive) => transcriptOf(drive.state()).filter((r) => r.data?.type === "turn");
230
+ /** Root keywords the pinned CLI (2.1.286) drops a tool for, with no word to the model or the host: measured, a root
231
+ * `{ "type": "object", "anyOf": [...] }` (or allOf, oneOf) never reaches the model while the session's other tools do. */
232
+ const CLI_DROPS_ROOT = ["anyOf", "allOf", "oneOf"];
233
+ /** What the Claude path refuses in a tool's input schema beyond `toolSchemaProblems`, measured on the pinned CLI and
234
+ * Anthropic's API (tuple `items`, the one shape the API rejects, is already invalid 2020-12). */
235
+ function claudeSchemaProblems(tool, schema) {
236
+ return CLI_DROPS_ROOT.filter((key) => key in schema).map((key) => `${tool}: /${key}: the Claude Agent CLI drops a tool whose root has ${key}; put the alternatives under a property`);
237
+ }
238
+ export function claudeAgentAdapter(options) {
239
+ const thinking = options.thinking ?? "medium";
240
+ if (!THINKING.has(thinking))
241
+ throw new ClaudeAgentThinkingOff(thinking);
242
+ const maxImageBytes = options.maxImageBytes ?? CLAUDE_AGENT_MAX_IMAGE_BYTES;
243
+ if (!Number.isSafeInteger(maxImageBytes) || maxImageBytes < 1 || maxImageBytes > MAX_IMAGE_BYTES_CEILING)
244
+ throw new Error(`agentrun-harness-claude: maxImageBytes must be a whole number of bytes from 1 to ${MAX_IMAGE_BYTES_CEILING}`);
245
+ const skills = options.skills ?? [];
246
+ const webSearch = options.webSearch === true;
247
+ const skillsWrong = skillProblems(skills);
248
+ if (skillsWrong.length)
249
+ throw new Error(`agentrun-harness-claude: ${skillsWrong.join("; ")}`);
250
+ const headersWrong = hostHeaderProblems(options.provider.headers);
251
+ if (headersWrong.length)
252
+ throw new Error(`agentrun-harness-claude: provider.headers: ${headersWrong.join("; ")}`);
253
+ // The SDK and its CLI are checked once, here: a mismatch is the host's to report, before any run starts.
254
+ let executable;
255
+ if (options.standIn) {
256
+ if (!standInAllowed())
257
+ throw new Error("agentrun-harness-claude: a stand-in CLI is for tests only (AGENTRUN_CLAUDE_AGENT_STANDIN=1 under a test runner)");
258
+ if (!options.sdk)
259
+ throw new Error("agentrun-harness-claude: a stand-in CLI needs a scripted SDK (sdk)");
260
+ executable = options.standIn.command;
261
+ }
262
+ else {
263
+ executable = verifyClaudeAgent(options).cliPath;
264
+ }
265
+ const modelFor = (spec) => {
266
+ if (typeof options.model === "string")
267
+ return options.model;
268
+ return (spec.tier && spec.tier !== "default" ? options.model[spec.tier] : undefined) ?? options.model.default;
269
+ };
270
+ return {
271
+ id: CLAUDE_AGENT_ID,
272
+ version: CLAUDE_AGENT_SDK_VERSION,
273
+ capabilities: () => ({ fork: false }),
274
+ check(spec) {
275
+ const problems = [];
276
+ if (spec.context === "fork")
277
+ problems.push("Claude Agent sessions cannot fork another session's transcript; declare context: \"fresh\"");
278
+ const seen = new Set();
279
+ for (const tool of spec.tools) {
280
+ if (!TOOL_NAME.test(tool.name))
281
+ problems.push(`the tool name ${JSON.stringify(tool.name.slice(0, 80))} is not one the Claude Agent SDK takes (letters, digits, _ and -, at most 64)`);
282
+ if (seen.has(tool.name))
283
+ problems.push(`the tool ${tool.name} is given twice`);
284
+ if (skills.length && tool.name === READ_SKILL_FILE)
285
+ problems.push(`the tool name ${READ_SKILL_FILE} is the adapter's own when it has skills`);
286
+ seen.add(tool.name);
287
+ // What every harness refuses (the root, JSON Schema 2020-12, a remote $ref), then what this one measured.
288
+ const common = toolSchemaProblems(tool.name, tool.inputSchema);
289
+ problems.push(...common, ...(common.length ? [] : claudeSchemaProblems(tool.name, tool.inputSchema)));
290
+ }
291
+ return problems;
292
+ },
293
+ async open(spec, io) {
294
+ const problems = this.check(spec);
295
+ if (problems.length)
296
+ throw new Error(`agentrun-harness-claude: ${problems.join("; ")}`);
297
+ const dir = io.dir ?? (options.sessionsDir ? join(options.sessionsDir, createHash("sha256").update(spec.key).digest("hex").slice(0, 32)) : undefined);
298
+ if (!dir)
299
+ throw new Error("agentrun-harness-claude: a session needs a private directory: the host lends one (io.dir), or pass sessionsDir");
300
+ // With skills, the model also reads their files (read_skill_file), from the session's own copy of them.
301
+ const tools = skills.length ? [...spec.tools, readSkillFileTool(join(dir, "plugin", "skills"), skills.map((skill) => ({ name: skill.name, files: Object.keys(skill.files) })))] : spec.tools;
302
+ const calls = new CallsInFlight();
303
+ // The CLI's own tools offered to the model: Skill only when the session has skills, WebSearch only when it is on.
304
+ const builtins = [...(skills.length ? ["Skill"] : []), ...(webSearch ? ["WebSearch"] : [])];
305
+ const acquire = localMachine({
306
+ dir,
307
+ // The host's workspace, when it names one: the CLI works where the host's file tools write (io.cwd).
308
+ ...(io.cwd ? { cwd: io.cwd } : {}),
309
+ ...(options.confine ? { confine: options.confine } : {}),
310
+ proxy: {
311
+ hooks: io.models,
312
+ tools: tools.map((t) => t.name),
313
+ ...(builtins.length ? { builtins } : {}),
314
+ ...(webSearch ? { webSearch: true, ...(options.webSearchAllowance !== undefined ? { webSearchAllowance: options.webSearchAllowance } : {}) } : {}),
315
+ ...(options.price ? { price: options.price } : {}),
316
+ ...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}),
317
+ ...(options.provider.auth ? { auth: options.provider.auth } : {}),
318
+ ...(options.provider.headers ? { headers: options.provider.headers } : {}),
319
+ ...(options.log ? { log: options.log } : {}),
320
+ ...(options.fetch ? { fetch: options.fetch } : {}),
321
+ },
322
+ });
323
+ // The SDK this session runs on (the host's, or the one installed beside this package, checked above), thinking at
324
+ // the session's level.
325
+ const sdk = thinkingAt(options.sdk ?? (await import("@anthropic-ai/claude-agent-sdk")), thinkingOf(spec, thinking));
326
+ const harness = claudeCodeHarness({
327
+ name: CLAUDE_AGENT_ID,
328
+ sandbox: {
329
+ attach: (ctx, request) => acquire({ ctx, ...(request.model ? { model: request.model } : {}), ...(request.deadline === undefined ? {} : { deadline: request.deadline }) }),
330
+ // No command of its own: the CLI reaches nothing but its model proxy (a web search, when on, is the provider's).
331
+ network: "deny-all",
332
+ // The runner's turn cap and the host's beforeRequest bound the spend.
333
+ budget: { turnUsd: Infinity, sessionUsd: Infinity },
334
+ },
335
+ tools: tools.map((tool) => kernelTool(tool, io, maxImageBytes, calls)),
336
+ builtins: false,
337
+ // Off by name too, besides tools: []: the pinned CLI's tools that neither the harness's allowlist nor its off list
338
+ // decide (test/tool-off.test.mjs pins the CLI's whole tool set against these lists), but WebSearch when it is on.
339
+ disallowedTools: CLAUDE_AGENT_ALSO_OFF.filter((name) => !(webSearch && name === "WebSearch")),
340
+ ...(webSearch ? { providerTools: ["web_search"] } : {}),
341
+ model: modelFor(spec),
342
+ ...(skills.length ? { skills: { plugin: join(dir, "plugin"), names: writeSkillsPlugin(join(dir, "plugin"), skills) } } : {}),
343
+ ...(options.smallModel ? { smallModel: options.smallModel } : {}),
344
+ ...(spec.system.length ? { instructions: spec.system.join("\n\n") } : {}),
345
+ credential: async () => options.provider.credential(),
346
+ gatewayUrl: options.provider.origin,
347
+ executable,
348
+ sdk,
349
+ ...(options.log ? { log: options.log } : {}),
350
+ });
351
+ const live = (event) => {
352
+ const e = event;
353
+ if (e?.type === "text" && typeof e.delta === "string")
354
+ io.onEvent({ type: "text", delta: e.delta });
355
+ // The tool bridge's `tool_end` comes once the call's outcome is in the session's records: only then does the host
356
+ // hear the call ended, with the text recorded.
357
+ if (e?.type === "tool_end" && typeof e.callId === "string" && typeof e.name === "string") {
358
+ calls.end(e.callId);
359
+ io.onEvent({ type: "tool_end", callId: e.callId, name: e.name, isError: e.isError === true, ...(typeof e.result === "string" ? { result: e.result } : {}), ...(e.truncated === true ? { truncated: true } : {}) });
360
+ }
361
+ // A call the CLI refused itself (a tool the session doesn't have): shown as a call that failed, by the name the
362
+ // model gave. The CLI's transcript, mirrored to the store, keeps the refusal.
363
+ if (e?.type === "tool_refused" && typeof e.callId === "string" && typeof e.name === "string") {
364
+ io.onEvent({ type: "tool_start", callId: e.callId, name: e.name, args: e.args ?? {} });
365
+ io.onEvent({ type: "tool_end", callId: e.callId, name: e.name, isError: true });
366
+ options.log?.("claude-agent: the CLI turned down a call to a tool this session does not have", { name: e.name, reason: e.reason });
367
+ }
368
+ };
369
+ // Every drive of this session writes through one serialized writer, so a drive opened after an interrupt reads only
370
+ // once the halted drive's last writes are in (serial.ts).
371
+ const writer = serialWriter(io.writer);
372
+ const open = (attempt = 0) => openDrive({ writer, signal: io.signal, live, attempt });
373
+ let drive = await open();
374
+ const initial = drive.state();
375
+ // A turn is open while the session holds input no turn placed, or a turn with no end (its recovery note).
376
+ const holdsTurn = (folded) => Boolean(recoveryNote(folded)) || pendingSubmissions(folded).length > 0;
377
+ let state = holdsTurn(initial)
378
+ ? "open_turn"
379
+ : initial.submissions.length === 0 && turnsIn(drive).length === 0 ? "new" : "idle";
380
+ let running;
381
+ let closed = false;
382
+ const run = () => {
383
+ const before = turnsIn(drive).length;
384
+ state = "idle";
385
+ running = (async () => {
386
+ let outcome;
387
+ for (let attempt = 0; !outcome; attempt += 1) {
388
+ const current = drive;
389
+ try {
390
+ await harness.drive(current);
391
+ const ended = turnsIn(current).slice(before).at(-1)?.data;
392
+ 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" };
393
+ }
394
+ catch (error) {
395
+ // Stopped by the session or its host: interrupted. Halted by anything else (a spend cap, the mirror, a refused
396
+ // spawn): failed, naming why.
397
+ if (current.signal.aborted) {
398
+ outcome = abortedOutcome(current.signal, io.signal);
399
+ // A stop that landed before this turn ran (while send() was still recording its prompt) found no turn to
400
+ // stop, and reads the session as it was: the turn is open now, its prompt pending, so it reads open_turn.
401
+ state = holdsTurn(current.state()) ? "open_turn" : "idle";
402
+ }
403
+ // The CLI exited mid-turn: the drive is rebuilt from the log and the turn resumes, a few times.
404
+ else if (error instanceof Restart && attempt < RESTARTS)
405
+ drive = await open(attempt + 1);
406
+ else
407
+ outcome = { status: "failed", error: String(error?.message ?? error).slice(0, 500) };
408
+ }
409
+ }
410
+ io.onEvent({ type: "turn_end", status: outcome.status });
411
+ return outcome;
412
+ })();
413
+ return running;
414
+ };
415
+ // A drive that was halted (an interrupt) holds the session no more: the next turn opens a fresh one, on the same
416
+ // writer (the adapter never opens the session itself).
417
+ const ready = async () => {
418
+ if (closed)
419
+ throw new Error("agentrun-harness-claude: the session is closed");
420
+ if (running)
421
+ await running;
422
+ if (drive.signal.aborted && !io.signal.aborted)
423
+ drive = await open();
424
+ };
425
+ return {
426
+ get state() { return state; },
427
+ async send(text) {
428
+ if (calls.draining)
429
+ throw new Error("agentrun-harness-claude: the session is pausing; no new turn");
430
+ await ready();
431
+ await drive.submit({ id: randomUUID(), kind: "prompt", text });
432
+ void run();
433
+ },
434
+ async recover() {
435
+ if (state !== "open_turn")
436
+ throw new Error("agentrun-harness-claude: there is no turn to recover");
437
+ await ready();
438
+ void run();
439
+ },
440
+ async settleOpenTurn() {
441
+ if (state !== "open_turn")
442
+ throw new Error("agentrun-harness-claude: there is no turn to settle");
443
+ await ready();
444
+ // The turn's end in the session's own transcript, as a turn that ends writes it: the next open finds no open turn,
445
+ // and the next turn carries no recovery of this one. Nothing is sent.
446
+ await settleTurn(drive);
447
+ state = "idle";
448
+ },
449
+ async turnEnd() {
450
+ if (!running)
451
+ throw new Error("agentrun-harness-claude: no turn is in flight");
452
+ return running;
453
+ },
454
+ async interrupt(interruptOptions = {}) {
455
+ const drainMs = interruptOptions.drainMs ?? 0;
456
+ if (!Number.isFinite(drainMs) || drainMs < 0)
457
+ throw new Error("agentrun-harness-claude: drainMs must be a non-negative number of milliseconds");
458
+ // A pause: no new turn here (the host refuses new calls and requests); the calls in flight run on until their
459
+ // outcomes are recorded.
460
+ calls.draining = true;
461
+ try {
462
+ if (drainMs > 0)
463
+ await calls.idle(drainMs);
464
+ drive.halt?.(new SessionHalt("interrupted"));
465
+ await running?.catch(() => { });
466
+ // The turn it stopped is still open in the session (an interrupt writes no end, and a prompt it stopped before
467
+ // the harness placed it is still pending): open_turn, so a host that is done with it settles it here.
468
+ if (holdsTurn(drive.state()))
469
+ state = "open_turn";
470
+ }
471
+ finally {
472
+ // Calls the halt cut off have no outcome to wait for; the next turn starts clean.
473
+ calls.clear();
474
+ calls.draining = false;
475
+ }
476
+ },
477
+ async close() {
478
+ if (closed)
479
+ return;
480
+ closed = true;
481
+ drive.halt?.(new SessionHalt("closed"));
482
+ await running?.catch(() => { });
483
+ },
484
+ };
485
+ },
486
+ };
487
+ }
@@ -0,0 +1,25 @@
1
+ import { CLAUDE_AGENT_SDK_VERSION } from './versions.js';
2
+ /**
3
+ * Where the pinned `claude` binary is on **this** machine. The harness never
4
+ * runs it here (Claude Code runs only in the session's sandbox VM, from
5
+ * the image's copy, `CLAUDE_VM_EXECUTABLE`); this finds the host build for the
6
+ * private stand-in VM (`localMachine()` in harness-world-sandbox's tests),
7
+ * which runs the CLI on the test machine. It is `harness-world-claude-code/binary`,
8
+ * never the package's index, so no published entry carries it and no
9
+ * Function looks a binary up. The Agent SDK ships it in one optional
10
+ * package per platform (`@anthropic-ai/claude-agent-sdk-<platform>-<arch>`,
11
+ * a single file, `claude`). This walks up from `cwd` and looks for the file
12
+ * itself: in a hoisted `node_modules` (npm, yarn), then in a pnpm store
13
+ * (`node_modules/.pnpm/<pkg>@<version>/...`).
14
+ *
15
+ * Only the binary of the pinned SDK version counts (`CLAUDE_AGENT_SDK_VERSION`):
16
+ * the transcript the mirror carries is CLI-internal, and a store that holds
17
+ * several versions must not hand the SDK another one.
18
+ *
19
+ * `HARNESS_CLAUDE_CODE_EXECUTABLE` wins. Returns `undefined` when it finds
20
+ * nothing (the tests that need it skip), never a `claude` on `PATH`.
21
+ */
22
+ export { CLAUDE_AGENT_SDK_VERSION };
23
+ export declare function findClaudeExecutable(cwd?: string, version?: string): string | undefined;
24
+ /** `linux-x64`, `darwin-arm64`, `linux-x64-musl`, ... as the SDK names its platform packages. */
25
+ export declare function platformSuffix(): string;
package/dist/binary.js ADDED
@@ -0,0 +1,71 @@
1
+ // Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
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, patches: 003-comments, 005-binary-lookup
4
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
5
+ import { dirname, join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { CLAUDE_AGENT_SDK_VERSION } from './versions.js';
8
+ /**
9
+ * Where the pinned `claude` binary is on **this** machine. The harness never
10
+ * runs it here (Claude Code runs only in the session's sandbox VM, from
11
+ * the image's copy, `CLAUDE_VM_EXECUTABLE`); this finds the host build for the
12
+ * private stand-in VM (`localMachine()` in harness-world-sandbox's tests),
13
+ * which runs the CLI on the test machine. It is `harness-world-claude-code/binary`,
14
+ * never the package's index, so no published entry carries it and no
15
+ * Function looks a binary up. The Agent SDK ships it in one optional
16
+ * package per platform (`@anthropic-ai/claude-agent-sdk-<platform>-<arch>`,
17
+ * a single file, `claude`). This walks up from `cwd` and looks for the file
18
+ * itself: in a hoisted `node_modules` (npm, yarn), then in a pnpm store
19
+ * (`node_modules/.pnpm/<pkg>@<version>/...`).
20
+ *
21
+ * Only the binary of the pinned SDK version counts (`CLAUDE_AGENT_SDK_VERSION`):
22
+ * the transcript the mirror carries is CLI-internal, and a store that holds
23
+ * several versions must not hand the SDK another one.
24
+ *
25
+ * `HARNESS_CLAUDE_CODE_EXECUTABLE` wins. Returns `undefined` when it finds
26
+ * nothing (the tests that need it skip), never a `claude` on `PATH`.
27
+ */
28
+ export { CLAUDE_AGENT_SDK_VERSION };
29
+ export function findClaudeExecutable(cwd = dirname(fileURLToPath(import.meta.url)), version = CLAUDE_AGENT_SDK_VERSION) {
30
+ const fromEnv = process.env.AGENTRUN_CLAUDE_AGENT_EXECUTABLE;
31
+ if (fromEnv)
32
+ return fromEnv;
33
+ const pkg = ['@anthropic-ai', `claude-agent-sdk-${platformSuffix()}`];
34
+ const bin = process.platform === 'win32' ? 'claude.exe' : 'claude';
35
+ const storeDir = `${pkg[0]}+${pkg[1]}@${version}`;
36
+ for (let d = cwd;; d = dirname(d)) {
37
+ const hoisted = join(d, 'node_modules', ...pkg);
38
+ if (existsSync(join(hoisted, bin)) && versionOf(hoisted) !== 'other')
39
+ return join(hoisted, bin);
40
+ const store = join(d, 'node_modules', '.pnpm');
41
+ if (existsSync(store)) {
42
+ for (const name of readdirSync(store)) {
43
+ // `<pkg>@<version>` or `<pkg>@<version>_<peers>`, never another version.
44
+ if (name !== storeDir && !name.startsWith(`${storeDir}_`))
45
+ continue;
46
+ const p = join(store, name, 'node_modules', ...pkg, bin);
47
+ if (existsSync(p))
48
+ return p;
49
+ }
50
+ }
51
+ if (dirname(d) === d)
52
+ return undefined;
53
+ }
54
+ /** `same` / `other` from the package's `package.json`; `unknown` when it is not there (a tracer copied only the binary). */
55
+ function versionOf(dir) {
56
+ try {
57
+ return JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).version === version ? 'same' : 'other';
58
+ }
59
+ catch {
60
+ return 'unknown';
61
+ }
62
+ }
63
+ }
64
+ /** `linux-x64`, `darwin-arm64`, `linux-x64-musl`, ... as the SDK names its platform packages. */
65
+ export function platformSuffix() {
66
+ const base = `${process.platform}-${process.arch}`;
67
+ if (process.platform !== 'linux')
68
+ return base;
69
+ const report = process.report?.getReport?.();
70
+ return report?.header?.glibcVersionRuntime ? base : `${base}-musl`;
71
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The names the pinned CLI (2.1.286) answers `Skill("<name>")` with itself, whatever the session's skills: its commands
3
+ * and bundled skills. A host skill by one of these names is reachable only as `agentrun:<name>`, never by the bare name a
4
+ * prompt writes: the Skill hook never maps a bare one of these to the session's skill. Measured: each name's call is
5
+ * answered by the CLI's own check, before any hook (test/skills.test.mjs pins the list against the CLI's own).
6
+ */
7
+ export declare const CLAUDE_AGENT_CLI_SKILL_NAMES: ReadonlySet<string>;
@@ -0,0 +1,17 @@
1
+ // The names the pinned Claude Agent CLI keeps for itself. Written for AgentRun.
2
+ /**
3
+ * The names the pinned CLI (2.1.286) answers `Skill("<name>")` with itself, whatever the session's skills: its commands
4
+ * and bundled skills. A host skill by one of these names is reachable only as `agentrun:<name>`, never by the bare name a
5
+ * prompt writes: the Skill hook never maps a bare one of these to the session's skill. Measured: each name's call is
6
+ * answered by the CLI's own check, before any hook (test/skills.test.mjs pins the list against the CLI's own).
7
+ */
8
+ export const CLAUDE_AGENT_CLI_SKILL_NAMES = new Set([
9
+ "__remote-workflow", "add-dir", "agents", "auto-mode-setup", "autocompact", "batch", "btw", "bug", "claude-api",
10
+ "clear", "code-review", "color", "compact", "config", "context", "copy", "cost", "dataviz", "debug", "doctor",
11
+ "effort", "exit", "export", "fast", "feedback", "fewer-permission-prompts", "focus", "goal", "heapdump", "help",
12
+ "hooks", "ide", "init", "insights", "keybindings-help", "list-agents", "login", "logout", "mcp", "memory", "model",
13
+ "output-style", "permissions", "plugin", "plugin-authoring", "plugin-types", "plugins", "quit", "recap",
14
+ "release-notes", "reload-plugins", "reload-skills", "rename", "resume", "review", "rewind", "run",
15
+ "run-skill-generator", "sandbox", "security-review", "simplify", "skills", "stats", "status", "statusline",
16
+ "tasks", "team-onboarding", "terminal-setup", "theme", "update-config", "usage", "verify", "workflow-launch-exec",
17
+ ]);