@parcha/agentrun-harness-claude 0.1.0-beta.36 → 0.1.0-beta.38
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 +41 -0
- package/README.md +1 -1
- package/dist/adapter.d.ts +1 -1
- package/dist/adapter.js +17 -31
- package/dist/facts.js +2 -2
- package/dist/harness.d.ts +19 -16
- package/dist/harness.js +57 -39
- package/dist/host/machine.d.ts +2 -9
- package/dist/host/machine.js +1 -4
- package/dist/host/policy.d.ts +13 -8
- package/dist/host/policy.js +28 -13
- package/dist/host/process.d.ts +1 -1
- package/dist/host/process.js +1 -1
- package/dist/host/tool-server.d.ts +5 -1
- package/dist/host/tool-server.js +5 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/resume.d.ts +29 -0
- package/dist/resume.js +71 -12
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,47 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## 0.1.0-beta.38 (2026-11-14)
|
|
6
|
+
|
|
7
|
+
- A run's MCP tools are host tools on every harness: each call passes the run's one tool gate before anything is sent, and the runner calls the server with the credential, books the call and records it, as it does any host tool. opencode now runs MCP tools (`features.mcp_client.harnesses` lists it, and an opencode agent granted `mcp:<server>/<tool>` saves and runs). claude-agent offers a granted tool as `mcp__hands__mcp__<server>__<tool>` and codex as `mcp_<server>__<tool>` (Codex refuses a dynamic tool named `mcp__*`); the Timeline, tool settings and approvals still name it `mcp:<server>/<tool>`. A call set to ask on claude-agent, codex or opencode holds the CLI's call while the run waits (no "waits for a person's approval" result row while it is parked); on the person's allow the resumed session gets the call's own result, no `[tool approval]` message. A codex run no longer fails at its start when a granted server can't be reached: the server's error shows at the first call, as on pi. On a code-mode Codex model, a script's tool call held for a person's approval runs once on their allow, under its own call id, and the script's cut-off `exec` reads its result (or, when the `exec` had yielded, the model's `wait` on its cell); before, the resume told the model the call may have run, and the call the model made again asked again, so the allow never reached a call.
|
|
8
|
+
|
|
9
|
+
Who breaks: a run parked on an MCP call at the MCP door before this version does not resume its call: cancel it and start it again. A Codex thread started before this version loses its MCP tools when it resumes (Codex resumes a thread with the dynamic tools it started with): start a new run. Code built on the kernel's MCP door breaks too. Removed: `SessionSpec.mcp`, `SessionMcp`, `McpClient`, `AdapterCapabilities` and `AgentAdapter.capabilities()`, `AdapterFacts.mcp`, `ModelProxyOptions.mcp`, `mcpRoute`, `McpHandler` and `McpRouteOptions` (`@parcha/agentrun-kernel/host`), and `McpCallResult.parked`. Hand a session its MCP tools as host tools in `SessionSpec.tools` instead.
|
|
10
|
+
- A provider-native web search's fee is one constant, `NATIVE_SEARCH_USD` ($0.01, $10 per 1,000), instead of three copies. The price does not change.
|
|
11
|
+
- Kernel: `@parcha/agentrun-kernel/host` exports `NATIVE_SEARCH_USD`. The Claude and Codex proxy policies and the runner's hosted search all read it.
|
|
12
|
+
- `@parcha/agentrun-harness-claude` no longer exports `CLAUDE_WEB_SEARCH_USD`; read `NATIVE_SEARCH_USD` from `@parcha/agentrun-kernel/host`.
|
|
13
|
+
- One discovery system. A run lists every tool until its catalog tools (MCP and monid) pass 20; then they are deferred, found with `tools_search` and run with `tools_call`. Under 20 there is no search or call, and Claude Agent's own tool search follows the same threshold and gets neither of ours. `codemode`, `tools_search` and `tools_call` each have a tool-settings key (allow by default); a tool set to deny is not offered at all.
|
|
14
|
+
- Every harness (pi, Claude Agent, OpenCode and Codex) now offers three host tools over the run's own tools: `tools_search`, `tools_call` and `codemode`. Codex gets the first two and keeps its own code mode. With MCP servers on a Claude Agent run, the CLI's own tool search is on.
|
|
15
|
+
- `tools_search {query, limit?}` ranks the run's tools by what they do (BM25 over each tool's description and argument words) and answers each match's name, description and input schema. It lists only tools the run may call: never one set to deny, and never the three tools themselves.
|
|
16
|
+
- `tools_call {name, args}` calls one of the run's tools by name. The call is asked about, recorded and booked as that tool's own call, under `<callId>/call`. An ask parks the run, and once approved the call runs once. A deny refuses it in the gate's words. A call of an unknown name, of `tools_call` itself, of `tools_search` or of `codemode` is refused in words, and nothing runs.
|
|
17
|
+
- `codemode {script}` runs a JavaScript script in a QuickJS sandbox. Its `await tools.<name>(args)` calls are each the run's own call, gated, recorded and booked under `<callId>/s<n>`. The sandbox has the tools and nothing else of the run: no environment, keys, files, network or timers.
|
|
18
|
+
- A call inside a script that needs approval follows Codex's rule. The run parks. Once a person answers, the script runs again: recorded calls answer from their records, the parked call runs once (or is refused), its outcome is the script's answer, and the rest of the script does not run.
|
|
19
|
+
- A call made through `tools_call` or a script answers what a direct call answers: its text and images to the model, and in a script its value (a tool's structured result, else its text). On pi the harness's own tools (an extension's, the browser's) are found and called the same way as the host's.
|
|
20
|
+
- A refused call inside a script ends the script with the refusal's words.
|
|
21
|
+
- After a crash, a call that was cut off is told as possibly done, and it is not run again.
|
|
22
|
+
- A paid call made through `tools_call` or a script books exactly as a direct call does: held before it is sent, under the cap, and settled once. The cap's wrap-up still refuses the model's own next call.
|
|
23
|
+
- The three tools' definitions ride on every model request: about 2,000 bytes, 639 tokens on Sonnet. So the smallest caps the README measures rise. A pi desktop run on Sonnet through a gateway now needs $0.07 for its first request and $0.13 for five steps in `strict` mode, or $0.07 in `expected` mode (it was $0.06, $0.12 and $0.06). Straight to Anthropic, it needs $0.04 for its first request, and five steps still need $0.09 in `strict` mode and $0.06 in `expected` mode.
|
|
24
|
+
- Claude Agent: with an MCP server's tools on the run, the CLI runs with `ENABLE_TOOL_SEARCH=true` and its ToolSearch. The run's MCP tools reach the model through `hands` only once ToolSearch finds them, and every other tool of the session loads as before. The session's proxy admits the tool search's beta (`advanced-tool-use-2025-11-20`), ToolSearch and its placeholder. It also admits a `tool_reference` block, inside a tool result only, that names one of the session's own tools. Without MCP tools, all of these stay refused.
|
|
25
|
+
- A server started by `agentrun-serve` (and so by `npx agentrun`) can start a worker thread from a file. The launcher no longer passes Node `--input-type`, which a worker inherits and Node refuses. Before this, a `codemode` script there failed with "--input-type can only be used with string input via --eval, --print, or STDIN", and so did pi's code mode on a desktop or a phone.
|
|
26
|
+
- Three follow-ups to the tools_search / tools_call / codemode rule, found in a live walk.
|
|
27
|
+
- Claude Agent now follows the same switch as every other harness. With `tools_search` or `tools_call` set to deny, its own tool search is off and every tool is listed; before, it deferred a run's catalog tools behind its own ToolSearch whatever the setting said. The server makes the one decision (`SessionSpec.deferCatalog`) and Claude Agent's adapter obeys it.
|
|
28
|
+
- Settings → Tools lists `tools_search`, `tools_call` and `codemode`, each allow or deny, allow by default. They are in `capabilities.tools` with `meta: true` (no grant: the agent editor does not offer them) and a one-line blurb.
|
|
29
|
+
- codemode's description names real functions of the run (`tools.<name>`, the first three) and says to leave off the prefix a harness shows in the model's own tool list (`hands_`, `mcp__hands__`). On OpenCode a script wrote `tools.hands_mcp__hn__…` five times in five runs and failed.
|
|
30
|
+
|
|
31
|
+
## 0.1.0-beta.37 (2026-11-13)
|
|
32
|
+
|
|
33
|
+
- A web_search setting of deny or ask now applies to a Claude Agent or Codex run's own web search at its next search, including a run that started while it was allow. Before, the setting was read only when the run started, so a run that started with native search kept searching after the setting changed.
|
|
34
|
+
- Claude Agent: each WebSearch asks the run's gate before it runs, as a host tool's call does. A deny refuses it in the gate's words. An ask parks the run on the person with nothing searched; once they allow it, the model's next search with the same query runs once, with no second card.
|
|
35
|
+
- Codex: its search runs inside the provider's model request, so its proxy reads web_search's setting before each request and offers the provider its search only while the setting is allow. A failed read offers no search.
|
|
36
|
+
- `SessionIO.permission(tool)` (agentrun-kernel) is the host's setting for a harness's own tool at the time of the read. The runner reads it from the store each time. `ProviderPolicy.apply` may return a promise.
|
|
37
|
+
- A runner run whose plane resolves web_search to native now gets the harness's own search (#2458). The runner had built the run's environment without its plane, so Claude Agent and Codex runs on a runner never had it on.
|
|
38
|
+
- A web_search that resolves to the model provider's own search works again on the runner for pi (#2458). It used to answer "web_search has no model to search on" every time:
|
|
39
|
+
- A pi run's own web_search on an Anthropic or OpenAI model. That is what `auto` picks for pi, and `native` too. Each search now goes through the run's model proxy with the provider's search tool, and its searches are booked at the provider's price on top of its tokens.
|
|
40
|
+
- A learned workflow's call node whose web_search resolves native, on any harness.
|
|
41
|
+
|
|
42
|
+
Each run's search uses that run's own model route, never one shared by the whole process. Hand-written workflow agents were not affected: their web_search never resolves native. Both harness packages now export their `withWebSearches` price wrapper, and the Codex one its `webSearchUsd`. A claude-agent or codex run's own search is not switched on by this change.
|
|
43
|
+
|
|
44
|
+
A capped run holds a hosted search's fees with its tokens before the request is sent, at the most searches the request allows, so the fees can't pass the cap. The kernel's model proxy takes a policy's `feeMaxUsd(body)` and holds it as the request's `feeUsd`; a fee it can't bound leaves the request unmeasured. The proxy also hands `usageOf` the sent body as a second argument, so a pi request on OpenAI's Responses that offered no search reads 0 searches from its body, even when its answer names a search call.
|
|
45
|
+
|
|
5
46
|
## 0.1.0-beta.36 (2026-11-13)
|
|
6
47
|
|
|
7
48
|
- Model defaults move to the current models. The OpenAI default (and OpenRouter's, for pi, codex and opencode) is now gpt-6.1-sol, where OpenRouter's was gpt-6-sol. The Claude Agent adapter's default is now claude-sonnet-5-5 (was claude-sonnet-4-5) and the Codex adapter's is openai/gpt-6-luna (was openai/gpt-5.4-mini). A host that relied on a default names its model; the READMEs' examples name the current ones.
|
package/README.md
CHANGED
|
@@ -35,7 +35,7 @@ const runNode = createHarnessRunner(
|
|
|
35
35
|
of them: nothing runs, writes or fetches.
|
|
36
36
|
- **Claude's own WebSearch, by option.** `webSearch: true` turns on the CLI's WebSearch and nothing else of its own: the
|
|
37
37
|
proxy then admits Anthropic's web search server tool exactly as the pinned CLI sends it, every other hosted tool stays
|
|
38
|
-
refused, and each search the provider reports is booked at $10 per 1,000 (`
|
|
38
|
+
refused, and each search the provider reports is booked at $10 per 1,000 (`NATIVE_SEARCH_USD`) beside the tokens,
|
|
39
39
|
into the session's cost and spend cap. A search request has no input bound unless `webSearchAllowance` gives the input
|
|
40
40
|
tokens it may read in beyond its body. WebFetch stays off. Default off.
|
|
41
41
|
- **The model behind a proxy.** The CLI talks to a model proxy on the loopback interface with a key of its session's
|
package/dist/adapter.d.ts
CHANGED
|
@@ -60,7 +60,7 @@ export interface ClaudeAgentAdapterOptions {
|
|
|
60
60
|
skills?: readonly ClaudeAgentSkill[];
|
|
61
61
|
/** Claude's own WebSearch, and nothing else of the CLI's: the model may call it, and the CLI runs each call as a request
|
|
62
62
|
* of its own through the session's model proxy with Anthropic's web search server tool, the one hosted tool that proxy
|
|
63
|
-
* then admits. Each search the provider reports is booked at `
|
|
63
|
+
* then admits. Each search the provider reports is booked at `NATIVE_SEARCH_USD` (kernel/host) on top of `price`, into the
|
|
64
64
|
* session's cost and so its spend cap. WebFetch stays off (it would fetch from the CLI's own process). Default off. */
|
|
65
65
|
webSearch?: boolean;
|
|
66
66
|
/** With `webSearch`: the input tokens a search request may read in beyond its body, added to its input bound, so a cap
|
package/dist/adapter.js
CHANGED
|
@@ -19,11 +19,10 @@ import { checkedOnce, checkedOnceAsync, hostHeaderProblems, startModelProxy } fr
|
|
|
19
19
|
import { anthropicPolicy, withWebSearches } from "./host/policy.js";
|
|
20
20
|
import { findClaudeExecutable, platformSuffix } from "./binary.js";
|
|
21
21
|
import { CLAUDE_AGENT_PACKAGE, ClaudeAgentNotInstalled, ClaudeAgentPinMismatch, ClaudeAgentThinkingOff } from "./errors.js";
|
|
22
|
-
import { claudeCodeHarness, lostPrompts } from "./harness.js";
|
|
22
|
+
import { claudeCodeHarness, claudeToolSearch, lostPrompts } from "./harness.js";
|
|
23
23
|
import { JournalSessionStore } from "./store.js";
|
|
24
|
-
import {
|
|
24
|
+
import { localMachine } from "./host/machine.js";
|
|
25
25
|
import { serialWriter } from "./serial.js";
|
|
26
|
-
import { MCP_SERVER } from "./transcript.js";
|
|
27
26
|
import { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_CODE_VERSION, installedVersion } from "./versions.js";
|
|
28
27
|
export { CLAUDE_AGENT_CLI_SKILL_NAMES } from "./cli-names.js";
|
|
29
28
|
/** The pinned CLI's tools the copied harness leaves undecided, off by name in every session (WebSearch unless `webSearch`). */
|
|
@@ -231,6 +230,7 @@ function kernelTool(tool, io, maxImageBytes, calls) {
|
|
|
231
230
|
description: tool.description,
|
|
232
231
|
inputSchema: tool.inputSchema,
|
|
233
232
|
replay: tool.replay,
|
|
233
|
+
...(tool.nests ? { nests: true } : {}),
|
|
234
234
|
async execute(input, effect) {
|
|
235
235
|
// The effect's step is `tool:<the CLI's tool_use id>#<attempt>`: the host sees the CLI's call id.
|
|
236
236
|
const callId = (effect.stepId ?? "").replace(/^tool:/, "").replace(/#\d+$/, "");
|
|
@@ -238,21 +238,27 @@ function kernelTool(tool, io, maxImageBytes, calls) {
|
|
|
238
238
|
const attempt = Number(/#(\d+)$/.exec(effect.stepId ?? "")?.[1] ?? 0);
|
|
239
239
|
// In flight, and past the pause's check, before the host hears of it: a pause the host starts on this tool_start
|
|
240
240
|
// waits for this call rather than refusing it.
|
|
241
|
-
calls
|
|
241
|
+
// A tool that nests calls has no intent of its own to wait for (each of its calls begins here as its own): a pause
|
|
242
|
+
// never waits on it, so a nested call that parks the run does not hold the pause.
|
|
243
|
+
if (!tool.nests)
|
|
244
|
+
calls.begin(callId);
|
|
242
245
|
// 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.
|
|
243
246
|
if (calls.draining)
|
|
244
247
|
throw new Error(`${tool.name} was not run: the session is pausing`);
|
|
245
248
|
io.onEvent({ type: "tool_start", callId, name: tool.name, args: input });
|
|
246
|
-
|
|
249
|
+
// A tool that nests calls (tools_call, codemode) gets the session's tools as its nested calls, through the bridge.
|
|
250
|
+
const result = await tool.call(input, { callId, signal: effect.signal, attempt, ...(effect.nested ? { nested: effect.nested } : {}) });
|
|
247
251
|
if (result.isError)
|
|
248
252
|
throw new Error(result.text);
|
|
253
|
+
// Its value, recorded with the outcome: a script's nested call is answered it (meta-tools.ts), as Codex's adapter keeps it.
|
|
254
|
+
const structured = result.structured !== undefined ? { structured: result.structured } : {};
|
|
249
255
|
if (!result.images?.length)
|
|
250
|
-
return result.text;
|
|
256
|
+
return result.structured === undefined ? result.text : { text: result.text, ...structured };
|
|
251
257
|
// 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.
|
|
252
258
|
const wrong = toolImageProblems(tool.name, result.images, maxImageBytes);
|
|
253
259
|
if (wrong)
|
|
254
260
|
throw new Error(wrong);
|
|
255
|
-
return { text: result.text, images: result.images.map((image) => ({ mimeType: image.mimeType, data: image.data })) };
|
|
261
|
+
return { text: result.text, images: result.images.map((image) => ({ mimeType: image.mimeType, data: image.data })), ...structured };
|
|
256
262
|
},
|
|
257
263
|
};
|
|
258
264
|
}
|
|
@@ -299,7 +305,6 @@ export function claudeAgentAdapter(options) {
|
|
|
299
305
|
};
|
|
300
306
|
return {
|
|
301
307
|
id: CLAUDE_AGENT_ID,
|
|
302
|
-
capabilities: () => ({ mcpClient: CLAUDE_MCP_CLIENT }),
|
|
303
308
|
check(spec) {
|
|
304
309
|
const problems = [];
|
|
305
310
|
if (spec.context === "fork")
|
|
@@ -317,18 +322,6 @@ export function claudeAgentAdapter(options) {
|
|
|
317
322
|
const common = toolSchemaProblems(tool.name, tool.inputSchema);
|
|
318
323
|
problems.push(...common, ...(common.length ? [] : claudeSchemaProblems(tool.name, tool.inputSchema)));
|
|
319
324
|
}
|
|
320
|
-
for (const server of spec.mcp?.servers ?? []) {
|
|
321
|
-
if (server.name === MCP_SERVER)
|
|
322
|
-
problems.push(`the MCP server name ${MCP_SERVER} is the adapter's own`);
|
|
323
|
-
for (const tool of server.tools) {
|
|
324
|
-
const name = `mcp__${server.name}__${tool.name}`;
|
|
325
|
-
if (!TOOL_NAME.test(name))
|
|
326
|
-
problems.push(`the MCP tool ${name.slice(0, 80)} is not a name the Claude Agent CLI takes (letters, digits, _ and -, at most 64)`);
|
|
327
|
-
// A remote tool's schema meets the same checks as the host's: the CLI would drop it without a word.
|
|
328
|
-
const common = toolSchemaProblems(name, tool.inputSchema);
|
|
329
|
-
problems.push(...common, ...(common.length ? [] : claudeSchemaProblems(name, tool.inputSchema)));
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
325
|
return problems;
|
|
333
326
|
},
|
|
334
327
|
async open(spec, io) {
|
|
@@ -341,9 +334,6 @@ export function claudeAgentAdapter(options) {
|
|
|
341
334
|
// With skills, the model also reads their files (read_skill_file), from the session's own copy of them.
|
|
342
335
|
const tools = skills.length ? [...spec.tools, hostedTool(io, readSkillFileTool(join(dir, "plugin", "skills"), skills.map((skill) => ({ name: skill.name, files: Object.keys(skill.files) }))))] : spec.tools;
|
|
343
336
|
const calls = new CallsInFlight();
|
|
344
|
-
// The remote MCP servers' granted tools, as the CLI names them: its own MCP client calls them at the proxy.
|
|
345
|
-
const mcpServers = spec.mcp?.servers ?? [];
|
|
346
|
-
const mcpNames = new Set(mcpServers.flatMap((server) => server.tools.map((tool) => `mcp__${server.name}__${tool.name}`)));
|
|
347
337
|
// The CLI's own tools offered to the model: Skill only when the session has skills, WebSearch only when it is on.
|
|
348
338
|
const builtins = [...(skills.length ? ["Skill"] : []), ...(webSearch ? ["WebSearch"] : [])];
|
|
349
339
|
const acquire = localMachine({
|
|
@@ -356,13 +346,14 @@ export function claudeAgentAdapter(options) {
|
|
|
356
346
|
tools: tools.map((t) => t.name),
|
|
357
347
|
...(builtins.length ? { builtins } : {}),
|
|
358
348
|
...(webSearch ? { webSearch: true, ...(options.webSearchAllowance !== undefined ? { webSearchAllowance: options.webSearchAllowance } : {}) } : {}),
|
|
349
|
+
// What the CLI sends with its own tool search on, which the harness turns on as this does (claudeToolSearch).
|
|
350
|
+
...(claudeToolSearch(tools.map((t) => t.name), spec.deferCatalog) === "true" ? { toolSearch: true } : {}),
|
|
359
351
|
...(options.price ? { price: options.price } : {}),
|
|
360
352
|
...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}),
|
|
361
353
|
...(options.provider.auth ? { auth: options.provider.auth } : {}),
|
|
362
354
|
...(options.provider.headers ? { headers: options.provider.headers } : {}),
|
|
363
355
|
...(options.log ? { log: options.log } : {}),
|
|
364
356
|
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
365
|
-
...(spec.mcp ? { mcp: { session: spec.mcp, tools: [...mcpNames] } } : {}),
|
|
366
357
|
},
|
|
367
358
|
});
|
|
368
359
|
// The SDK this session runs on (the host's, or the one installed beside this package, checked above), thinking at
|
|
@@ -377,12 +368,12 @@ export function claudeAgentAdapter(options) {
|
|
|
377
368
|
network: "deny-all",
|
|
378
369
|
},
|
|
379
370
|
tools: tools.map((tool) => kernelTool(tool, io, maxImageBytes, calls)),
|
|
371
|
+
...(spec.deferCatalog === undefined ? {} : { deferCatalog: spec.deferCatalog }),
|
|
380
372
|
builtins: false,
|
|
381
373
|
// Off by name too, besides tools: []: the pinned CLI's tools that neither the harness's allowlist nor its off list
|
|
382
374
|
// decide (test/tool-off.test.mjs pins the CLI's whole tool set against these lists), but WebSearch when it is on.
|
|
383
375
|
disallowedTools: CLAUDE_AGENT_ALSO_OFF.filter((name) => !(webSearch && name === "WebSearch")),
|
|
384
376
|
...(webSearch ? { providerTools: ["web_search"] } : {}),
|
|
385
|
-
...(mcpServers.length ? { mcpServers: mcpServers.map((server) => ({ name: server.name, tools: server.tools.map((tool) => tool.name) })) } : {}),
|
|
386
377
|
model: modelFor(spec),
|
|
387
378
|
...(skills.length ? { skills: { plugin: join(dir, "plugin"), names: writeSkillsPlugin(join(dir, "plugin"), skills) } } : {}),
|
|
388
379
|
...(options.smallModel ? { smallModel: options.smallModel } : {}),
|
|
@@ -394,7 +385,7 @@ export function claudeAgentAdapter(options) {
|
|
|
394
385
|
...(options.mcp ? { toolServerModules: options.mcp } : {}),
|
|
395
386
|
...(options.log ? { log: options.log } : {}),
|
|
396
387
|
...(options.now ? { now: options.now } : {}),
|
|
397
|
-
// The host's gate, asked about each host-tool call before it is written or run.
|
|
388
|
+
// The host's gate, asked about each host-tool call and each WebSearch before it is written or run.
|
|
398
389
|
...(io.gate ? { gate: (call) => io.gate(call) } : {}),
|
|
399
390
|
});
|
|
400
391
|
const live = (event) => {
|
|
@@ -404,11 +395,6 @@ export function claudeAgentAdapter(options) {
|
|
|
404
395
|
// The model's message ended inside the turn (the CLI resumes a cut answer itself): what it said so far is one message.
|
|
405
396
|
if (e?.type === "text_end")
|
|
406
397
|
io.onEvent({ type: "text_end" });
|
|
407
|
-
// An MCP call, recorded as a built-in's: the host hears of it once its intent is in the session's records.
|
|
408
|
-
if (e?.type === "tool_start" && typeof e.callId === "string" && typeof e.name === "string" && mcpNames.has(e.name)) {
|
|
409
|
-
calls.begin(e.callId);
|
|
410
|
-
io.onEvent({ type: "tool_start", callId: e.callId, name: e.name, args: e.args ?? {} });
|
|
411
|
-
}
|
|
412
398
|
// The tool bridge's `tool_end` comes once the call's outcome is in the session's records: only then does the host
|
|
413
399
|
// hear the call ended, with the text recorded.
|
|
414
400
|
if (e?.type === "tool_end" && typeof e.callId === "string" && typeof e.name === "string") {
|
package/dist/facts.js
CHANGED
|
@@ -12,13 +12,13 @@ export const facts = Object.freeze({
|
|
|
12
12
|
steer: false,
|
|
13
13
|
// A call that started is never run again (the CLI answers it "[Tool call interrupted]"); only the model calls again.
|
|
14
14
|
rerunsStarted: false,
|
|
15
|
+
// Its own tool search defers an MCP server's tools (ENABLE_TOOL_SEARCH, on under the kernel's defersCatalog), so the host offers no tools_search or tools_call beside it.
|
|
16
|
+
ownToolSearch: true,
|
|
15
17
|
// An answer its output limit cut, the CLI resumes itself in the same turn ("Output token limit hit. Resume directly"),
|
|
16
18
|
// up to 3 times; only a cut it no longer resumes ends the turn cut.
|
|
17
19
|
recoversCutAnswers: 3,
|
|
18
20
|
// One run's memory, measured with the server's (serve's host.ts): the CLI and its SDK beside the run's process.
|
|
19
21
|
runMib: 288,
|
|
20
|
-
// Its own MCP client binds the session's remote MCP servers.
|
|
21
|
-
mcp: true,
|
|
22
22
|
thinking: Object.freeze(["low", "medium", "high", "xhigh", "max"]),
|
|
23
23
|
// Anthropic's web search, through the session's proxy, as the pinned CLI's WebSearch asks for it.
|
|
24
24
|
webSearch: "native",
|
package/dist/harness.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type GateAnswer, type GateCall } from '@parcha/agentrun-kernel';
|
|
2
2
|
import { type DriveContext, type Harness, type HostTool, type ReplayPolicy, type SessionState, type Submission } from './host/kernel.js';
|
|
3
3
|
import { type GatewayHandler, type ProviderTool, type SessionMachine } from './host/process.js';
|
|
4
4
|
import { toolServer } from './host/tool-server.js';
|
|
@@ -142,6 +142,9 @@ export interface ClaudeCodeHarnessOptions {
|
|
|
142
142
|
* none.
|
|
143
143
|
*/
|
|
144
144
|
tools?: HostTool[];
|
|
145
|
+
/** The host's verdict on whether the catalog tools are deferred (SessionSpec.deferCatalog), which turns the CLI's own
|
|
146
|
+
* tool search on or off; absent, the tools' names decide (claudeToolSearch). */
|
|
147
|
+
deferCatalog?: boolean;
|
|
145
148
|
/**
|
|
146
149
|
* Claude Code's own tools, in the VM, on `/workspace`. Default false
|
|
147
150
|
* (tool-less: `tools` are the CLI's only tools). `true`: the pinned
|
|
@@ -169,18 +172,6 @@ export interface ClaudeCodeHarnessOptions {
|
|
|
169
172
|
* `claudeBuiltinReplay` (reads safe).
|
|
170
173
|
*/
|
|
171
174
|
builtinReplay?: Record<string, ReplayPolicy> | ((name: string) => ReplayPolicy);
|
|
172
|
-
/**
|
|
173
|
-
* Remote MCP servers the CLI's own MCP client calls, each at the session's
|
|
174
|
-
* model proxy (`<modelUrl>/mcp/<name>`, behind the session's key), with the
|
|
175
|
-
* tools granted on each: those are allowed by name (`mcp__<name>__<tool>`)
|
|
176
|
-
* and each call is recorded as a built-in's. They are set over the CLI's
|
|
177
|
-
* stdin (`setMcpServers`), never in its argv. The proxy answers the
|
|
178
|
-
* handshake: an unreachable server shows at its first call. Default none.
|
|
179
|
-
*/
|
|
180
|
-
mcpServers?: readonly {
|
|
181
|
-
readonly name: string;
|
|
182
|
-
readonly tools: readonly string[];
|
|
183
|
-
}[];
|
|
184
175
|
/**
|
|
185
176
|
* The MCP library the session's tool server is built with, as the host
|
|
186
177
|
* loaded it from where it installed the Agent SDK. Default: imported by
|
|
@@ -236,7 +227,8 @@ export interface ClaudeCodeHarnessOptions {
|
|
|
236
227
|
unsandboxedCommands?: boolean;
|
|
237
228
|
/** Called with the child's stderr tail when it exits mid-turn, the gateway's refusals, and SDK diagnostics. */
|
|
238
229
|
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
|
|
230
|
+
/** The host's gate (SessionIO.gate), asked by the tool bridge about each call of `tools` before its intent, and by the
|
|
231
|
+
* PreToolUse hook about each WebSearch (`providerTools: ['web_search']`) before its intent, by the CLI's name for it. */
|
|
240
232
|
gate?: (call: GateCall) => Promise<GateAnswer>;
|
|
241
233
|
/** The clock a user turn's day is read from (dateLine). Default the system's. */
|
|
242
234
|
now?: () => Date;
|
|
@@ -257,8 +249,6 @@ export declare const DEFAULT_MODEL = "claude-sonnet-5-5";
|
|
|
257
249
|
export declare const TOOLS_NOTE = "Your only tools are this app's, the mcp__hands__ tools; you have no shell, file, search or web tools of your own.";
|
|
258
250
|
/** `TOOLS_NOTE` with WebSearch on (`providerTools: ['web_search']`) and the other built-ins off. */
|
|
259
251
|
export declare const WEB_SEARCH_NOTE = "Your only tools are this app's (the mcp__hands__ tools, if it has any) and WebSearch; you have no shell, file or fetch tools of your own.";
|
|
260
|
-
/** `TOOLS_NOTE` with the app's remote MCP servers (`mcpServers`) and the built-ins off. */
|
|
261
|
-
export declare const MCP_NOTE = "Your only tools are this app's: the mcp__hands__ tools, if it has any, and those of its MCP servers (the other mcp__ tools); you have no shell, file, search or web tools of your own.";
|
|
262
252
|
/** `TOOLS_NOTE` for a session with no tools at all (built-ins off, no `tools`). */
|
|
263
253
|
export declare const NO_TOOLS_NOTE = "You have no tools in this session: no shell, file, search or web tools. Answer from the conversation.";
|
|
264
254
|
/** With the built-ins on (docs/workspaces.md §5.6 "Workspace note"): what `/workspace` is. */
|
|
@@ -282,6 +272,19 @@ export declare const CLAUDE_BUILTINS_OFF: string[];
|
|
|
282
272
|
export declare const CLAUDE_BUILTINS: readonly ["Bash", "Read", "Edit", "Write", "NotebookEdit", "WebFetch"];
|
|
283
273
|
/** Built-ins that only read: "safe to repeat" after a crash, and no flush before their outcome. Everything else: "may have taken effect". */
|
|
284
274
|
export declare const CLAUDE_SAFE_BUILTINS: string[];
|
|
275
|
+
/**
|
|
276
|
+
* ENABLE_TOOL_SEARCH for a session whose tools are `toolNames` (the host's names): when the run's catalog tools are
|
|
277
|
+
* deferred (the kernel's defersCatalog: more than DEFER_CATALOG_OVER of them; the host's own tools_search and tools_call
|
|
278
|
+
* are never offered beside it), `true`: the CLI's own tool search is on, its ToolSearch among its tools, and those tools are
|
|
279
|
+
* deferred (served through `hands`, the rest of the session's tools listed to load always: tool-server.ts listedTools),
|
|
280
|
+
* each sent to the model once ToolSearch finds it. Without, `false`. The pinned CLI (2.1.286) leaves it off behind a
|
|
281
|
+
* proxy unless told, and its `auto` defers only past a tenth of the model's context (on a 1M-token model, never in
|
|
282
|
+
* practice); set either way, so a CLI that changes that default changes nothing here. The session's proxy admits what the
|
|
283
|
+
* CLI sends with it on (anthropicPolicy `toolSearch`).
|
|
284
|
+
*/
|
|
285
|
+
export declare const claudeToolSearch: (toolNames: readonly string[], deferCatalog?: boolean) => "true" | "false";
|
|
286
|
+
/** The CLI's own tool that finds a deferred tool: it only reads the CLI's list of the session's tools. */
|
|
287
|
+
export declare const CLAUDE_TOOL_SEARCH = "ToolSearch";
|
|
285
288
|
/** The default `builtinReplay`. */
|
|
286
289
|
export declare const claudeBuiltinReplay: (name: string) => ReplayPolicy;
|
|
287
290
|
/** The `builtins` option, resolved: the `tools` option for `query()` (undefined: the preset, all of them). */
|
package/dist/harness.js
CHANGED
|
@@ -6,14 +6,15 @@ 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
|
+
import { defersCatalog } from '@parcha/agentrun-kernel';
|
|
9
10
|
import { Restart, Unavailable } from './host/kernel.js';
|
|
10
|
-
import { BuiltinCalls, CLAUDE_ROUTES, gatewayCredential, gatewayHandler, gatewayUrl, isBrandedMachine, NativeJournal, openTurn, placeSubmissions, recoveryNote, restartEvent, replayBy, toolBridge, waitForSubmissions, } from './host/process.js';
|
|
11
|
+
import { askGate, BuiltinCalls, CLAUDE_ROUTES, gatewayCredential, gatewayHandler, gatewayUrl, isBrandedMachine, NativeJournal, openTurn, placeSubmissions, recoveryNote, restartEvent, replayBy, toolBridge, toolKey, waitForSubmissions, } from './host/process.js';
|
|
11
12
|
import { durableEnv, nativeModelId } from './env.js';
|
|
12
13
|
import { uuidFrom } from './ids.js';
|
|
13
14
|
import { MessageQueue } from './inbox.js';
|
|
14
15
|
import { sandboxSpawn } from './spawn.js';
|
|
15
16
|
import { MCP_OUTPUT_TOKENS, toolServer } from './host/tool-server.js';
|
|
16
|
-
import { resumeDanglingCalls } from './resume.js';
|
|
17
|
+
import { releasedSearches, resumeDanglingCalls, resumeDanglingSearches, searchKey, WEB_SEARCH } from './resume.js';
|
|
17
18
|
import { JournalSessionStore } from './store.js';
|
|
18
19
|
import { MCP_SERVER, TranscriptBuilder } from './transcript.js';
|
|
19
20
|
import { CLAUDE_AGENT_CLI_SKILL_NAMES } from './cli-names.js';
|
|
@@ -39,8 +40,6 @@ export const DEFAULT_MODEL = 'claude-sonnet-5-5';
|
|
|
39
40
|
export const TOOLS_NOTE = `Your only tools are this app's, the mcp__${MCP_SERVER}__ tools; you have no shell, file, search or web tools of your own.`;
|
|
40
41
|
/** `TOOLS_NOTE` with WebSearch on (`providerTools: ['web_search']`) and the other built-ins off. */
|
|
41
42
|
export const WEB_SEARCH_NOTE = `Your only tools are this app's (the mcp__${MCP_SERVER}__ tools, if it has any) and WebSearch; you have no shell, file or fetch tools of your own.`;
|
|
42
|
-
/** `TOOLS_NOTE` with the app's remote MCP servers (`mcpServers`) and the built-ins off. */
|
|
43
|
-
export const MCP_NOTE = `Your only tools are this app's: the mcp__${MCP_SERVER}__ tools, if it has any, and those of its MCP servers (the other mcp__ tools); you have no shell, file, search or web tools of your own.`;
|
|
44
43
|
/** `TOOLS_NOTE` for a session with no tools at all (built-ins off, no `tools`). */
|
|
45
44
|
export const NO_TOOLS_NOTE = 'You have no tools in this session: no shell, file, search or web tools. Answer from the conversation.';
|
|
46
45
|
/** With the built-ins on (docs/workspaces.md §5.6 "Workspace note"): what `/workspace` is. */
|
|
@@ -90,6 +89,19 @@ export const CLAUDE_BUILTINS_OFF = [
|
|
|
90
89
|
export const CLAUDE_BUILTINS = ['Bash', 'Read', 'Edit', 'Write', 'NotebookEdit', 'WebFetch'];
|
|
91
90
|
/** Built-ins that only read: "safe to repeat" after a crash, and no flush before their outcome. Everything else: "may have taken effect". */
|
|
92
91
|
export const CLAUDE_SAFE_BUILTINS = ['Read', 'Glob', 'Grep', 'LS', 'NotebookRead', 'WebFetch', 'WebSearch', 'ToolSearch', 'Skill'];
|
|
92
|
+
/**
|
|
93
|
+
* ENABLE_TOOL_SEARCH for a session whose tools are `toolNames` (the host's names): when the run's catalog tools are
|
|
94
|
+
* deferred (the kernel's defersCatalog: more than DEFER_CATALOG_OVER of them; the host's own tools_search and tools_call
|
|
95
|
+
* are never offered beside it), `true`: the CLI's own tool search is on, its ToolSearch among its tools, and those tools are
|
|
96
|
+
* deferred (served through `hands`, the rest of the session's tools listed to load always: tool-server.ts listedTools),
|
|
97
|
+
* each sent to the model once ToolSearch finds it. Without, `false`. The pinned CLI (2.1.286) leaves it off behind a
|
|
98
|
+
* proxy unless told, and its `auto` defers only past a tenth of the model's context (on a 1M-token model, never in
|
|
99
|
+
* practice); set either way, so a CLI that changes that default changes nothing here. The session's proxy admits what the
|
|
100
|
+
* CLI sends with it on (anthropicPolicy `toolSearch`).
|
|
101
|
+
*/
|
|
102
|
+
export const claudeToolSearch = (toolNames, deferCatalog) => ((deferCatalog ?? defersCatalog(toolNames)) ? 'true' : 'false');
|
|
103
|
+
/** The CLI's own tool that finds a deferred tool: it only reads the CLI's list of the session's tools. */
|
|
104
|
+
export const CLAUDE_TOOL_SEARCH = 'ToolSearch';
|
|
93
105
|
/** The default `builtinReplay`. */
|
|
94
106
|
export const claudeBuiltinReplay = replayBy(CLAUDE_SAFE_BUILTINS);
|
|
95
107
|
/** What a Bash command keeps of the invocation for its outcome to be recorded and the drive to end (the kernel's end-of-drive margin is 15 s). */
|
|
@@ -159,23 +171,6 @@ async function bwrapWorks(machine, signal) {
|
|
|
159
171
|
return false;
|
|
160
172
|
}
|
|
161
173
|
}
|
|
162
|
-
/**
|
|
163
|
-
* The session's remote MCP servers, each an http entry at the model proxy's
|
|
164
|
-
* `/mcp/<name>` with the session's key, sent over the CLI's stdin (an entry
|
|
165
|
-
* in `options.mcpServers` would be in its argv). The in-process server
|
|
166
|
-
* (`own`) goes with them, since the call replaces the dynamic set. A server
|
|
167
|
-
* that did not connect throws: the turn fails rather than run without its
|
|
168
|
-
* tools. Each call may take `timeoutMs`, what is left of the invocation.
|
|
169
|
-
*/
|
|
170
|
-
async function connectMcp(q, machine, names, own, timeoutMs) {
|
|
171
|
-
const entry = (name) => ({ type: 'http', url: `${machine.modelUrl}/mcp/${name}`, headers: { authorization: `Bearer ${machine.modelKey}` }, timeout: Math.floor(timeoutMs), alwaysLoad: true });
|
|
172
|
-
const set = await q.setMcpServers({ ...own, ...Object.fromEntries(names.map((name) => [name, entry(name)])) });
|
|
173
|
-
const status = new Map((await q.mcpServerStatus()).map((server) => [server.name, server]));
|
|
174
|
-
const error = (name) => (set.errors && Object.hasOwn(set.errors, name) ? set.errors[name] : undefined);
|
|
175
|
-
const failed = names.filter((name) => error(name) !== undefined || status.get(name)?.status !== 'connected');
|
|
176
|
-
if (failed.length)
|
|
177
|
-
throw new Error(`the MCP server${failed.length > 1 ? 's' : ''} ${failed.join(', ')} did not connect: ${failed.map((name) => error(name) ?? status.get(name)?.error ?? status.get(name)?.status ?? 'no status').join('; ').slice(0, 300)}`);
|
|
178
|
-
}
|
|
179
174
|
export function claudeCodeHarness(options = {}) {
|
|
180
175
|
const tools = options.tools ?? [];
|
|
181
176
|
const allowed = builtinTools(options.builtins);
|
|
@@ -188,8 +183,8 @@ export function claudeCodeHarness(options = {}) {
|
|
|
188
183
|
const replay = typeof options.builtinReplay === 'function' ? options.builtinReplay : options.builtinReplay ? (name) => options.builtinReplay[name] ?? claudeBuiltinReplay(name) : claudeBuiltinReplay;
|
|
189
184
|
const providerTools = options.providerTools ?? [];
|
|
190
185
|
const webSearch = providerTools.includes('web_search');
|
|
191
|
-
|
|
192
|
-
const
|
|
186
|
+
/** The CLI's own tool search is on: a run's MCP servers' tools deferred behind its ToolSearch (claudeToolSearch). */
|
|
187
|
+
const toolSearch = claudeToolSearch(tools.map((tool) => tool.name), options.deferCatalog) === 'true';
|
|
193
188
|
const log = options.log ?? (() => { });
|
|
194
189
|
let sdk;
|
|
195
190
|
const loadSdk = () => {
|
|
@@ -292,13 +287,20 @@ export function claudeCodeHarness(options = {}) {
|
|
|
292
287
|
},
|
|
293
288
|
});
|
|
294
289
|
const gate = options.gate;
|
|
290
|
+
// The host's gate before the intent, so a refused or parked call leaves nothing of its own written. The assistant
|
|
291
|
+
// line that made the call is in the log before the gate is asked: a park ends the claim, and the resume finds the
|
|
292
|
+
// call it held dangling in the transcript, under the same id (resumeDanglingCalls, resumeDanglingSearches).
|
|
293
|
+
// A call a tool makes inside its own (tools_call, codemode) has the id `<tool_use id>/<key>`: no line of the
|
|
294
|
+
// transcript names it, so it waits on the line that made the call it runs inside.
|
|
295
|
+
const logged = (callId) => store.barrier(callId.split('/')[0], barrierMs);
|
|
296
|
+
const gated = gate ? async (call) => (await logged(call.callId), gate(call)) : undefined;
|
|
297
|
+
/** The WebSearch calls the gate held and a person let run that no search has taken up yet (releasedSearches, read
|
|
298
|
+
* from the transcript at the resume): the model's next search with one's input is put to the gate under its id. */
|
|
299
|
+
const released = [];
|
|
295
300
|
const bridge = toolBridge(ctx, tools, {
|
|
296
|
-
|
|
297
|
-
// assistant line that made the call is in the log before the gate is asked: a park ends the claim, and the
|
|
298
|
-
// resume finds the call it held dangling in the transcript, under the same id (resumeDanglingCalls).
|
|
299
|
-
...(gate ? { gate: async (call) => (await store.barrier(call.callId, barrierMs), gate(call)) } : {}),
|
|
301
|
+
...(gated ? { gate: gated } : {}),
|
|
300
302
|
// A `never` tool runs only once the assistant entry that asked for it is in the log.
|
|
301
|
-
beforeNever: ({ callId }) =>
|
|
303
|
+
beforeNever: ({ callId }) => logged(callId),
|
|
302
304
|
});
|
|
303
305
|
// The built-ins: each call an intent before it runs, its outcome after (the hooks below).
|
|
304
306
|
const builtins = new BuiltinCalls(ctx, { replay, beforeNever: ({ callId }) => store.barrier(callId, barrierMs), live: true });
|
|
@@ -377,12 +379,25 @@ export function claudeCodeHarness(options = {}) {
|
|
|
377
379
|
return deny(`Not run: ${JSON.stringify(String(asked).slice(0, 80))} is not one of this session's skills.`);
|
|
378
380
|
return name === asked ? allow() : allow({ ...input, skill: name });
|
|
379
381
|
}
|
|
380
|
-
// WebSearch, when on, takes the built-ins' path below: its intent recorded before it runs.
|
|
381
|
-
//
|
|
382
|
-
if (!builtinsOn && !(webSearch && hook.tool_name === 'WebSearch') && !
|
|
382
|
+
// WebSearch, when on, takes the built-ins' path below: its intent recorded before it runs. So does
|
|
383
|
+
// ToolSearch with the tool search on: it reads only the CLI's list of the session's own tools.
|
|
384
|
+
if (!builtinsOn && !(webSearch && hook.tool_name === 'WebSearch') && !(toolSearch && hook.tool_name === CLAUDE_TOOL_SEARCH))
|
|
383
385
|
return deny("Not run: this session's only tools are its own.");
|
|
384
386
|
if (ctx.signal.aborted)
|
|
385
387
|
return deny('the session stopped');
|
|
388
|
+
// The host's gate decides every native search, as it does a host tool's call, before anything of it
|
|
389
|
+
// is written: a deny refuses it in the gate's words, an ask holds it until the person answers (the
|
|
390
|
+
// run parks), each read at this call, so a setting changed mid-run reaches the next search. The model's
|
|
391
|
+
// search again of one the gate held and a person let run is asked under the held call's id, which their
|
|
392
|
+
// answer covers: no second card, and a deny set since still refuses it.
|
|
393
|
+
if (webSearch && hook.tool_name === WEB_SEARCH && gated && !ctx.isMemoized(toolKey(hook.tool_use_id))) {
|
|
394
|
+
const at = released.findIndex((one) => one.key === searchKey(hook.tool_input));
|
|
395
|
+
const callId = at >= 0 ? released.splice(at, 1)[0].callId : hook.tool_use_id;
|
|
396
|
+
const replayed = ctx.state().effects.has(toolKey(hook.tool_use_id));
|
|
397
|
+
const refused = await askGate(gated, { callId, tool: hook.tool_name, args: (hook.tool_input ?? {}), ...(replayed ? { replayed: true } : {}) }, ctx.signal);
|
|
398
|
+
if (refused)
|
|
399
|
+
return deny(refused.deny);
|
|
400
|
+
}
|
|
386
401
|
let updated;
|
|
387
402
|
const field = FILE_TOOLS[hook.tool_name];
|
|
388
403
|
if (field) {
|
|
@@ -476,9 +491,8 @@ export function claudeCodeHarness(options = {}) {
|
|
|
476
491
|
// A host tool's result within the host's bound reaches the model whole (each tool is listed with it, too).
|
|
477
492
|
mcpOutputTokens: MCP_OUTPUT_TOKENS,
|
|
478
493
|
});
|
|
479
|
-
//
|
|
480
|
-
|
|
481
|
-
vmEnv.ENABLE_TOOL_SEARCH = 'false';
|
|
494
|
+
// The CLI's own tool search: on with MCP servers among the session's tools, off without (claudeToolSearch).
|
|
495
|
+
vmEnv.ENABLE_TOOL_SEARCH = toolSearch ? 'true' : 'false';
|
|
482
496
|
const sdkEnv = { ...vmEnv, CLAUDE_CONFIG_DIR: configDir };
|
|
483
497
|
const disallowed = [...CLAUDE_BUILTINS_OFF, ...(providerTools.includes('web_search') ? [] : ['WebSearch']), ...(options.disallowedTools ?? [])].filter((name) => !(skills && name === 'Skill'));
|
|
484
498
|
const sessionId = uuidFrom(ctx.runId);
|
|
@@ -487,6 +501,12 @@ export function claudeCodeHarness(options = {}) {
|
|
|
487
501
|
// One with an intent is left to the CLI's repair and the recovery note, as before; nothing ever runs one twice.
|
|
488
502
|
if (store.hasSession)
|
|
489
503
|
await resumeDanglingCalls(ctx, bridge, store);
|
|
504
|
+
// A WebSearch the gate held (an ask): put to it again, under its own id, before the CLI resumes. Then every release
|
|
505
|
+
// the transcript holds that no search has taken up, this resume's and one a restart cut off before the search.
|
|
506
|
+
if (store.hasSession && webSearch && gated) {
|
|
507
|
+
await resumeDanglingSearches(ctx, store, gated);
|
|
508
|
+
released.push(...releasedSearches(store.lines()));
|
|
509
|
+
}
|
|
490
510
|
// A turn a crash cut off: the harness's own account of it (which calls completed, which may have half-run) goes
|
|
491
511
|
// in this drive's system prompt, not in a user message the model might answer back to the user. A resumed
|
|
492
512
|
// session sends the system prompt recorded at its start (`snapshot`), whatever a later launch passes, so this
|
|
@@ -507,14 +527,14 @@ export function claudeCodeHarness(options = {}) {
|
|
|
507
527
|
// Built-ins on: the allowed ones (less those whose state the log does not carry), each let through by
|
|
508
528
|
// the PreToolUse hook once its intent is in the log. Off: the bridged tools are the only ones. Either
|
|
509
529
|
// way nothing is asked of a user, and nothing else is permitted.
|
|
510
|
-
...(allowed !== undefined ? { tools: [...allowed, ...(skills ? ['Skill'] : []), ...(webSearch && !allowed.includes('WebSearch') ? ['WebSearch'] : [])] } : {}),
|
|
530
|
+
...(allowed !== undefined ? { tools: [...allowed, ...(skills ? ['Skill'] : []), ...(webSearch && !allowed.includes('WebSearch') ? ['WebSearch'] : []), ...(toolSearch && !allowed.includes(CLAUDE_TOOL_SEARCH) ? [CLAUDE_TOOL_SEARCH] : [])] } : {}),
|
|
511
531
|
// The session's skills, from its own plugin: listed to the model and loadable, and no other.
|
|
512
532
|
...(skills ? { plugins: [{ type: 'local', path: skills.plugin }], skills: [...skills.names] } : {}),
|
|
513
533
|
disallowedTools: disallowed,
|
|
514
534
|
hooks,
|
|
515
535
|
...(ownSandbox ? { sandbox: claudeSandboxSettings(machine, sandbox.network) } : {}),
|
|
516
536
|
...(bridge.tools.length ? { mcpServers: { [MCP_SERVER]: server } } : {}),
|
|
517
|
-
allowedTools:
|
|
537
|
+
allowedTools: bridge.tools.map((t) => `mcp__${MCP_SERVER}__${t.name}`),
|
|
518
538
|
permissionMode: 'dontAsk',
|
|
519
539
|
strictMcpConfig: true,
|
|
520
540
|
// No user, project or local settings (and so no CLAUDE.md): a model-planted .claude/ on the Drive is ignored.
|
|
@@ -526,7 +546,7 @@ export function claudeCodeHarness(options = {}) {
|
|
|
526
546
|
systemPrompt: {
|
|
527
547
|
type: 'preset',
|
|
528
548
|
preset: 'claude_code',
|
|
529
|
-
append: [builtinsOn ? DRIVE_NOTE : webSearch ? WEB_SEARCH_NOTE :
|
|
549
|
+
append: [builtinsOn ? DRIVE_NOTE : webSearch ? WEB_SEARCH_NOTE : bridge.tools.length ? TOOLS_NOTE : NO_TOOLS_NOTE, options.instructions, recovered].filter(Boolean).join('\n\n'),
|
|
530
550
|
snapshot: !recovered,
|
|
531
551
|
},
|
|
532
552
|
...(store.hasSession ? { resume: sessionId } : { sessionId }),
|
|
@@ -548,8 +568,6 @@ export function claudeCodeHarness(options = {}) {
|
|
|
548
568
|
};
|
|
549
569
|
const q = query({ prompt: input, options: queryOptions });
|
|
550
570
|
const messages = q[Symbol.asyncIterator]();
|
|
551
|
-
if (mcpServers.length)
|
|
552
|
-
await connectMcp(q, machine, mcpServers.map((server) => server.name), bridge.tools.length ? { [MCP_SERVER]: server } : {}, Math.max(1_000, deadline - Date.now()));
|
|
553
571
|
const send = async (text, placed, how = {}) => {
|
|
554
572
|
// The drive's first message says, once, what the sandbox told it (a lost Drive).
|
|
555
573
|
if (notes) {
|
package/dist/host/machine.d.ts
CHANGED
|
@@ -1,10 +1,7 @@
|
|
|
1
1
|
import { type ChildProcess } from "node:child_process";
|
|
2
2
|
import { type ModelProxyHooks, type ModelProxyOptions, type ParentWatch } from "@parcha/agentrun-kernel/host";
|
|
3
|
-
import type { McpClient, SessionMcp } from "@parcha/agentrun-kernel";
|
|
4
3
|
import type { AcquireMachine, MachineSpawn, SessionMachine, SessionProcess } from "./process.js";
|
|
5
4
|
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;
|
|
8
5
|
/** The variables a child takes from this process, when they are set. */
|
|
9
6
|
export declare const INHERITED_ENV: readonly ["PATH", "LANG", "TZ"];
|
|
10
7
|
/** A command and its arguments, as the machine starts it. */
|
|
@@ -35,14 +32,10 @@ export interface LocalMachineOptions {
|
|
|
35
32
|
builtins?: readonly string[];
|
|
36
33
|
/** Admit Anthropic's web search server tool, the one the CLI's WebSearch asks for. */
|
|
37
34
|
webSearch?: boolean;
|
|
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. */
|
|
40
|
-
mcp?: {
|
|
41
|
-
session: SessionMcp;
|
|
42
|
-
tools: readonly string[];
|
|
43
|
-
};
|
|
44
35
|
/** The input a request carrying it may read in beyond its body, for its input bound (anthropicPolicy). */
|
|
45
36
|
webSearchAllowance?: number;
|
|
37
|
+
/** The CLI's own tool search is on: its beta, its tools and its tool references pass (anthropicPolicy). */
|
|
38
|
+
toolSearch?: boolean;
|
|
46
39
|
/** The tokens' price; each web search a response reports is added to it (`withWebSearches`). */
|
|
47
40
|
price?: ModelProxyOptions["price"];
|
|
48
41
|
maxOutputTokens?: number;
|
package/dist/host/machine.js
CHANGED
|
@@ -17,8 +17,6 @@ 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" };
|
|
22
20
|
/** The variables a child takes from this process, when they are set. */
|
|
23
21
|
export const INHERITED_ENV = Object.freeze(["PATH", "LANG", "TZ"]);
|
|
24
22
|
const DIRS = ["home", "config", "tmp", "cache"];
|
|
@@ -132,10 +130,10 @@ export function localMachine(options) {
|
|
|
132
130
|
...(route.models.smallModel ? { smallModel: route.models.smallModel } : {}),
|
|
133
131
|
tools: options.proxy.tools,
|
|
134
132
|
...(options.proxy.builtins?.length ? { builtins: options.proxy.builtins } : {}),
|
|
135
|
-
...(options.proxy.mcp ? { mcpTools: options.proxy.mcp.tools } : {}),
|
|
136
133
|
...(options.proxy.maxOutputTokens ? { maxOutputTokens: options.proxy.maxOutputTokens } : {}),
|
|
137
134
|
...(options.proxy.webSearch ? { webSearch: true, ...(options.proxy.webSearchAllowance !== undefined ? { webSearchAllowance: options.proxy.webSearchAllowance } : {}) } : {}),
|
|
138
135
|
...(options.proxy.auth ? { auth: options.proxy.auth } : {}),
|
|
136
|
+
...(options.proxy.toolSearch ? { toolSearch: true } : {}),
|
|
139
137
|
onThinkingDisabled: ({ model: main }) => options.proxy.log?.("claude-agent: thinking.disabled", { model: main }),
|
|
140
138
|
}),
|
|
141
139
|
hooks: options.proxy.hooks,
|
|
@@ -144,7 +142,6 @@ export function localMachine(options) {
|
|
|
144
142
|
credential: async () => (await route.credential()) ?? "",
|
|
145
143
|
...(options.proxy.price ? { price: withWebSearches(options.proxy.price) } : {}),
|
|
146
144
|
...(options.proxy.headers ? { headers: options.proxy.headers } : {}),
|
|
147
|
-
...(options.proxy.mcp ? { mcp: { session: options.proxy.mcp.session, client: CLAUDE_MCP_CLIENT } } : {}),
|
|
148
145
|
...(options.proxy.log ? { log: options.proxy.log } : {}),
|
|
149
146
|
// The provider stopped the turn's answer on its content filter: no retry of it can pass, so the turn ends at once.
|
|
150
147
|
onFiltered: (message) => ctx.halt?.(new Error(message)),
|
package/dist/host/policy.d.ts
CHANGED
|
@@ -6,6 +6,12 @@ export declare const CLAUDE_MESSAGES_ROUTES: readonly ProxyRoute[];
|
|
|
6
6
|
* and a probe of claude-sonnet-4-5, claude-sonnet-5-5, claude-opus-5-5 and claude-haiku-5-5): the set depends on the
|
|
7
7
|
* model. Any other is refused, so a CLI or a model that starts sending a new one is seen before it is trusted. */
|
|
8
8
|
export declare const CLAUDE_BETAS: ReadonlySet<string>;
|
|
9
|
+
/** The beta the pinned CLI (2.1.286) adds with its own tool search on (ENABLE_TOOL_SEARCH, `toolSearch`): its tools sent
|
|
10
|
+
* with `defer_loading`, and its ToolSearch's answer as `tool_reference` blocks naming them. Admitted only then. */
|
|
11
|
+
export declare const CLAUDE_TOOL_SEARCH_BETA = "advanced-tool-use-2025-11-20";
|
|
12
|
+
/** The CLI's own tools its tool search adds (recorded behind a local server, CLI 2.1.286): ToolSearch, which runs in the
|
|
13
|
+
* CLI and answers with the deferred tools it found, and a deferred placeholder it never calls. */
|
|
14
|
+
export declare const CLAUDE_TOOL_SEARCH_TOOLS: readonly string[];
|
|
9
15
|
/** The content blocks the pinned CLI (2.1.286) sends in a session, recorded behind this proxy (the real-CLI test, with
|
|
10
16
|
* a model that thinks): any other type is refused, so a block the provider runs or resolves on its own (a server
|
|
11
17
|
* tool's call or result, an MCP block, a container upload, an image or document it would fetch) never passes, under
|
|
@@ -17,9 +23,6 @@ export declare const CLAUDE_BLOCKS: ReadonlySet<string>;
|
|
|
17
23
|
* test/fixtures/web-search-request-cli-2.1.286.json): its type and name, `max_uses: 8`, and the domains the model named.
|
|
18
24
|
* A later version (dynamic filtering runs code execution) or any other field is refused. */
|
|
19
25
|
export declare const CLAUDE_WEB_SEARCH_TOOL = "web_search_20250305";
|
|
20
|
-
/** What one web search costs on Anthropic's API, in USD, beside the tokens: $10 per 1,000 searches, "Web search tool" in
|
|
21
|
-
* https://platform.claude.com/docs/en/about-claude/pricing (a search that errs is not billed). */
|
|
22
|
-
export declare const CLAUDE_WEB_SEARCH_USD = 0.01;
|
|
23
26
|
export interface AnthropicPolicyOptions {
|
|
24
27
|
/** The session's model, and the one the CLI's small background calls use (default: the session's). */
|
|
25
28
|
model: string;
|
|
@@ -28,8 +31,6 @@ export interface AnthropicPolicyOptions {
|
|
|
28
31
|
tools: readonly string[];
|
|
29
32
|
/** The CLI's own tools the session has, offered by their own names beside its tools (`Skill`, when it has skills). */
|
|
30
33
|
builtins?: readonly string[];
|
|
31
|
-
/** The granted tools of the session's remote MCP servers, as the CLI names them (`mcp__<server>__<tool>`). */
|
|
32
|
-
mcpTools?: readonly string[];
|
|
33
34
|
/** The most output tokens one request may ask for. Default 128 000, what the pinned CLI asks for on current models. */
|
|
34
35
|
maxOutputTokens?: number;
|
|
35
36
|
/** Admit Anthropic's web search server tool (`CLAUDE_WEB_SEARCH_TOOL`), exactly as the pinned CLI asks for it; every
|
|
@@ -40,6 +41,10 @@ export interface AnthropicPolicyOptions {
|
|
|
40
41
|
* pages each search feeds the model, billed as input), added to that request's input bound. Absent, such a request
|
|
41
42
|
* has no input bound, so a cap that holds each request's worst case refuses it. */
|
|
42
43
|
webSearchAllowance?: number;
|
|
44
|
+
/** The CLI's own tool search is on (its MCP tools deferred until it finds them): its beta, its two tools
|
|
45
|
+
* (CLAUDE_TOOL_SEARCH_TOOLS) and, inside a tool result, a `tool_reference` block naming one of the session's own tools
|
|
46
|
+
* pass. A reference names a tool the request offers; the provider resolves it to nothing else. Default off. */
|
|
47
|
+
toolSearch?: boolean;
|
|
43
48
|
/** How the provider takes its credential. Default `x-api-key` (Anthropic's API). */
|
|
44
49
|
auth?: "x-api-key" | "bearer";
|
|
45
50
|
/** Told when a request on the session's main model carries no thinking and no effort: the model would answer without
|
|
@@ -82,7 +87,7 @@ export declare function applyAnthropic(body: unknown, route: ProxyRoute, options
|
|
|
82
87
|
export interface AnthropicUsage extends ProxyUsage {
|
|
83
88
|
webSearches?: number;
|
|
84
89
|
}
|
|
85
|
-
/** `price` with each web search a response reports added at `
|
|
90
|
+
/** `price` with each web search a response reports added at `NATIVE_SEARCH_USD`: the host prices the tokens, the
|
|
86
91
|
* searches are Anthropic's flat rate. An unknown price stays unknown. */
|
|
87
92
|
export declare function withWebSearches(price: (model: string, usage: ProxyUsage) => number | null): (model: string, usage: ProxyUsage) => number | null;
|
|
88
93
|
/** The usage a Messages response reports, read by parsing it, never by matching its text (the API nests objects in
|
|
@@ -96,9 +101,9 @@ export declare function anthropicUsage(text: string): AnthropicUsage | undefined
|
|
|
96
101
|
* on its own, as anthropicUsage reads them. */
|
|
97
102
|
export declare function anthropicFiltered(text: string): boolean;
|
|
98
103
|
/** Whether a Messages body (as `apply` kept it) is the turn's answer request: it offers the model one of the session's
|
|
99
|
-
* tools, its own
|
|
104
|
+
* tools, its own (a run's remote MCP tools among them) or built-in. The CLI's side calls (a title, a summary, a web search's
|
|
100
105
|
* own request) offer none of them; in a session with no tools no request can be told from one, so each is the turn's. */
|
|
101
|
-
export declare function anthropicAnswers(body: Record<string, unknown>, options: Pick<AnthropicPolicyOptions, "tools" | "builtins"
|
|
106
|
+
export declare function anthropicAnswers(body: Record<string, unknown>, options: Pick<AnthropicPolicyOptions, "tools" | "builtins">): boolean;
|
|
102
107
|
/**
|
|
103
108
|
* Anthropic's own count of a Messages request's input tokens: POST /v1/messages/count_tokens, free, on api.anthropic.com
|
|
104
109
|
* only ("Token counting", https://platform.claude.com/docs/en/build-with-claude/token-counting). The proxy asks it before
|
package/dist/host/policy.js
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
// is dropped, so the model is offered exactly the host's tools. With `webSearch`, one hosted tool passes: Anthropic's web
|
|
19
19
|
// search, exactly as the pinned CLI asks for it in the request its WebSearch tool makes. Usage is read from the stream's
|
|
20
20
|
// `message_start` (input and cache tokens) and its last `message_delta` (output, and the searches the provider ran).
|
|
21
|
-
import { messagesImagesIn, providerInputOverhead, ProxyRefusal } from "@parcha/agentrun-kernel/host";
|
|
21
|
+
import { messagesImagesIn, providerInputOverhead, NATIVE_SEARCH_USD, ProxyRefusal } from "@parcha/agentrun-kernel/host";
|
|
22
22
|
/** The prefix of the session's own tools, as the CLI names them (its in-process MCP server, `hands`). */
|
|
23
23
|
export const OWN_TOOL_PREFIX = "mcp__hands__";
|
|
24
24
|
const ANTHROPIC_HEADERS = ["anthropic-version", "anthropic-beta"];
|
|
@@ -41,6 +41,14 @@ export const CLAUDE_BETAS = new Set([
|
|
|
41
41
|
"prompt-caching-scope-2026-01-05",
|
|
42
42
|
"thinking-token-count-2026-05-13",
|
|
43
43
|
]);
|
|
44
|
+
/** The beta the pinned CLI (2.1.286) adds with its own tool search on (ENABLE_TOOL_SEARCH, `toolSearch`): its tools sent
|
|
45
|
+
* with `defer_loading`, and its ToolSearch's answer as `tool_reference` blocks naming them. Admitted only then. */
|
|
46
|
+
export const CLAUDE_TOOL_SEARCH_BETA = "advanced-tool-use-2025-11-20";
|
|
47
|
+
/** The CLI's own tools its tool search adds (recorded behind a local server, CLI 2.1.286): ToolSearch, which runs in the
|
|
48
|
+
* CLI and answers with the deferred tools it found, and a deferred placeholder it never calls. */
|
|
49
|
+
export const CLAUDE_TOOL_SEARCH_TOOLS = Object.freeze(["ToolSearch", "DeferredToolPlaceholder"]);
|
|
50
|
+
/** The keys of a `tool_reference` block, as the CLI's ToolSearch answers. */
|
|
51
|
+
const TOOL_REFERENCE_KEYS = new Set(["type", "tool_name"]);
|
|
44
52
|
/** The keys a Messages request may carry, and a token count's. */
|
|
45
53
|
const MESSAGES_KEYS = new Set(["model", "messages", "system", "max_tokens", "metadata", "stop_sequences", "stream", "temperature", "top_k", "top_p", "tools", "tool_choice", "thinking", "context_management", "output_config"]);
|
|
46
54
|
const COUNT_TOKENS_KEYS = new Set(["model", "messages", "system", "tools", "tool_choice", "thinking", "context_management", "output_config"]);
|
|
@@ -59,9 +67,6 @@ export const CLAUDE_WEB_SEARCH_TOOL = "web_search_20250305";
|
|
|
59
67
|
const WEB_SEARCH_KEYS = new Set(["type", "name", "max_uses", "allowed_domains", "blocked_domains"]);
|
|
60
68
|
/** The most searches one request may ask the provider for: the pinned CLI's `max_uses`. */
|
|
61
69
|
const WEB_SEARCH_MAX_USES = 8;
|
|
62
|
-
/** What one web search costs on Anthropic's API, in USD, beside the tokens: $10 per 1,000 searches, "Web search tool" in
|
|
63
|
-
* https://platform.claude.com/docs/en/about-claude/pricing (a search that errs is not billed). */
|
|
64
|
-
export const CLAUDE_WEB_SEARCH_USD = 0.01;
|
|
65
70
|
/** Whether a Messages body asks the model to think: thinking on (adaptive, or a budget), or an effort level. */
|
|
66
71
|
export function thinks(body) {
|
|
67
72
|
const thinking = body.thinking;
|
|
@@ -84,7 +89,7 @@ const LOCAL_IMAGE_NOTE = /^\[Image: source: [^\]\n]+\]$/;
|
|
|
84
89
|
/** A content list (a message's, the system prompt's, a tool result's): only the block types this session sends. An
|
|
85
90
|
* image only as a host tool answered it: inside its result, inline, of a type the API takes (never one the provider
|
|
86
91
|
* would fetch). */
|
|
87
|
-
function blocks(content, where, inResult = false) {
|
|
92
|
+
function blocks(content, where, inResult = false, references) {
|
|
88
93
|
if (content === undefined || typeof content === "string")
|
|
89
94
|
return;
|
|
90
95
|
if (!Array.isArray(content))
|
|
@@ -92,6 +97,12 @@ function blocks(content, where, inResult = false) {
|
|
|
92
97
|
for (const block of content) {
|
|
93
98
|
if (!isPlain(block) || typeof block.type !== "string")
|
|
94
99
|
return refuse(400, `a block in ${where} must be an object with a type`);
|
|
100
|
+
// With the CLI's tool search on: its ToolSearch's answer, a reference to one of the session's own tools, nothing else.
|
|
101
|
+
if (inResult && references && block.type === "tool_reference") {
|
|
102
|
+
if (!Object.keys(block).every((key) => TOOL_REFERENCE_KEYS.has(key)) || typeof block.tool_name !== "string" || !references.has(block.tool_name))
|
|
103
|
+
refuse(403, `${where} holds a tool reference to a tool this session does not have`);
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
95
106
|
if (inResult && block.type === "image") {
|
|
96
107
|
const source = block.source;
|
|
97
108
|
if (!isPlain(source) || source.type !== "base64" || typeof source.media_type !== "string" || !IMAGE_TYPES.has(source.media_type) || typeof source.data !== "string")
|
|
@@ -101,7 +112,7 @@ function blocks(content, where, inResult = false) {
|
|
|
101
112
|
if (!CLAUDE_BLOCKS.has(block.type))
|
|
102
113
|
refuse(403, `${where} holds a block of a type this session does not send`);
|
|
103
114
|
if (block.type === "tool_result")
|
|
104
|
-
blocks(block.content, "a tool result's content", true);
|
|
115
|
+
blocks(block.content, "a tool result's content", true, references);
|
|
105
116
|
}
|
|
106
117
|
}
|
|
107
118
|
/** A message with the CLI's note of its own image file left out of each tool result that holds the image itself: the
|
|
@@ -251,15 +262,19 @@ export function applyAnthropic(body, route, options, context = {}) {
|
|
|
251
262
|
const count = route.path === "/v1/messages/count_tokens";
|
|
252
263
|
onlyKeys(body, count ? COUNT_TOKENS_KEYS : MESSAGES_KEYS, count ? "count_tokens" : "messages");
|
|
253
264
|
outputConfig(body.output_config);
|
|
265
|
+
const own = options.tools.map((name) => `${OWN_TOOL_PREFIX}${name}`);
|
|
266
|
+
const search = options.toolSearch === true && context.host === undefined;
|
|
267
|
+
// The tools a tool search's answer may name: the session's own (a reference names no built-in).
|
|
268
|
+
const references = search ? new Set(own) : undefined;
|
|
254
269
|
if (!Array.isArray(body.messages))
|
|
255
270
|
refuse(400, "messages must be a list");
|
|
256
271
|
for (const message of body.messages) {
|
|
257
272
|
if (!isPlain(message))
|
|
258
273
|
refuse(400, "a message must be an object");
|
|
259
|
-
blocks(message.content, "a message's content");
|
|
274
|
+
blocks(message.content, "a message's content", false, references);
|
|
260
275
|
}
|
|
261
276
|
blocks(body.system, "system");
|
|
262
|
-
const allowed = context.host !== undefined ? new Set(clientToolNames(body.tools)) : new Set([...
|
|
277
|
+
const allowed = context.host !== undefined ? new Set(clientToolNames(body.tools)) : new Set([...own, ...(options.builtins ?? []), ...(search ? CLAUDE_TOOL_SEARCH_TOOLS : [])]);
|
|
263
278
|
const tools = ownTools(body.tools, allowed, options.webSearch);
|
|
264
279
|
const choice = body.tool_choice;
|
|
265
280
|
const chosen = isPlain(choice) && typeof choice.name === "string" && (allowed.has(choice.name) || (options.webSearch === true && choice.name === "web_search"));
|
|
@@ -301,13 +316,13 @@ function bookedUsage(usage) {
|
|
|
301
316
|
return undefined;
|
|
302
317
|
return { input, output, cacheRead: tokenCount(usage.cache_read_input_tokens) ?? 0, cacheWrite: tokenCount(usage.cache_creation_input_tokens) ?? 0, ...(webSearches ? { webSearches } : {}) };
|
|
303
318
|
}
|
|
304
|
-
/** `price` with each web search a response reports added at `
|
|
319
|
+
/** `price` with each web search a response reports added at `NATIVE_SEARCH_USD`: the host prices the tokens, the
|
|
305
320
|
* searches are Anthropic's flat rate. An unknown price stays unknown. */
|
|
306
321
|
export function withWebSearches(price) {
|
|
307
322
|
return (model, usage) => {
|
|
308
323
|
const usd = price(model, usage);
|
|
309
324
|
const count = usage.webSearches ?? 0;
|
|
310
|
-
return usd === null || count === 0 ? usd : usd + count *
|
|
325
|
+
return usd === null || count === 0 ? usd : usd + count * NATIVE_SEARCH_USD;
|
|
311
326
|
};
|
|
312
327
|
}
|
|
313
328
|
/** The usage a Messages response reports, read by parsing it, never by matching its text (the API nests objects in
|
|
@@ -374,10 +389,10 @@ export function anthropicFiltered(text) {
|
|
|
374
389
|
return stop === "refusal";
|
|
375
390
|
}
|
|
376
391
|
/** Whether a Messages body (as `apply` kept it) is the turn's answer request: it offers the model one of the session's
|
|
377
|
-
* tools, its own
|
|
392
|
+
* tools, its own (a run's remote MCP tools among them) or built-in. The CLI's side calls (a title, a summary, a web search's
|
|
378
393
|
* own request) offer none of them; in a session with no tools no request can be told from one, so each is the turn's. */
|
|
379
394
|
export function anthropicAnswers(body, options) {
|
|
380
|
-
const allowed = new Set([...options.tools.map((name) => `${OWN_TOOL_PREFIX}${name}`), ...(options.builtins ?? [])
|
|
395
|
+
const allowed = new Set([...options.tools.map((name) => `${OWN_TOOL_PREFIX}${name}`), ...(options.builtins ?? [])]);
|
|
381
396
|
if (allowed.size === 0)
|
|
382
397
|
return true;
|
|
383
398
|
return Array.isArray(body.tools) && body.tools.some((tool) => isPlain(tool) && typeof tool.name === "string" && allowed.has(tool.name));
|
|
@@ -459,7 +474,7 @@ export function anthropicPolicy(options) {
|
|
|
459
474
|
header: (name, value) => {
|
|
460
475
|
if (name !== "anthropic-beta")
|
|
461
476
|
return value;
|
|
462
|
-
const unknown = value.split(",").map((v) => v.trim()).filter((v) => v && !CLAUDE_BETAS.has(v));
|
|
477
|
+
const unknown = value.split(",").map((v) => v.trim()).filter((v) => v && !CLAUDE_BETAS.has(v) && !(options.toolSearch === true && v === CLAUDE_TOOL_SEARCH_BETA));
|
|
463
478
|
if (unknown.length)
|
|
464
479
|
refuse(403, "an anthropic-beta value is not one the pinned CLI sends");
|
|
465
480
|
return value;
|
package/dist/host/process.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { DriveContext } from "./kernel.js";
|
|
2
|
-
export { BuiltinCalls, NativeJournal, openTurn, placeSubmissions, recoveryNote, replayBy, restartEvent, resumeUnstartedCalls, toolBridge, waitForSubmissions, zodShapeFromJsonSchema, } from "@parcha/agentrun-kernel/process";
|
|
2
|
+
export { askGate, BuiltinCalls, NativeJournal, openTurn, placeSubmissions, recoveryNote, replayBy, restartEvent, resumeUnstartedCalls, toolBridge, toolKey, unstartedCalls, waitForSubmissions, zodShapeFromJsonSchema, } from "@parcha/agentrun-kernel/process";
|
|
3
3
|
export type { CallOutcome, DanglingCall, JournalRecord, ToolBridge, TranscriptEntry } from "@parcha/agentrun-kernel/process";
|
|
4
4
|
export type KillSignal = "SIGTERM" | "SIGKILL" | "SIGINT";
|
|
5
5
|
/** A running child of the session. */
|
package/dist/host/process.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { BuiltinCalls, NativeJournal, openTurn, placeSubmissions, recoveryNote, replayBy, restartEvent, resumeUnstartedCalls, toolBridge, waitForSubmissions, zodShapeFromJsonSchema, } from "@parcha/agentrun-kernel/process";
|
|
1
|
+
export { askGate, BuiltinCalls, NativeJournal, openTurn, placeSubmissions, recoveryNote, replayBy, restartEvent, resumeUnstartedCalls, toolBridge, toolKey, unstartedCalls, waitForSubmissions, zodShapeFromJsonSchema, } from "@parcha/agentrun-kernel/process";
|
|
2
2
|
const BRAND = Symbol.for("agentrun.claude-agent.session-machine");
|
|
3
3
|
/** Mark a machine as made by this package's factory. */
|
|
4
4
|
export function brandMachine(machine) {
|
|
@@ -26,13 +26,17 @@ export declare const RESULT_SIZE_KEY = "anthropic/maxResultSizeChars";
|
|
|
26
26
|
* images) is never counted, let alone saved or cut.
|
|
27
27
|
*/
|
|
28
28
|
export declare const MCP_OUTPUT_TOKENS = 120000;
|
|
29
|
+
/** The `_meta` key of a listed tool by which the CLI never defers it behind its tool search. */
|
|
30
|
+
export declare const ALWAYS_LOAD_KEY = "anthropic/alwaysLoad";
|
|
29
31
|
/** `tools` as the server lists them to the CLI (`tools/list`): each as the host gave it, with the host's result bound as
|
|
30
|
-
* its result size.
|
|
32
|
+
* its result size. With the CLI's tool search on (harness.ts claudeToolSearch), only a run's MCP servers' tools
|
|
33
|
+
* (`mcp__<server>__<tool>`) wait behind it: every other tool of the session is listed to load always. */
|
|
31
34
|
export declare const listedTools: (tools: readonly ServedTool[]) => {
|
|
32
35
|
name: string;
|
|
33
36
|
description: string;
|
|
34
37
|
inputSchema: Record<string, unknown>;
|
|
35
38
|
_meta: {
|
|
39
|
+
"anthropic/alwaysLoad"?: boolean | undefined;
|
|
36
40
|
"anthropic/maxResultSizeChars": number;
|
|
37
41
|
};
|
|
38
42
|
}[];
|
package/dist/host/tool-server.js
CHANGED
|
@@ -24,9 +24,12 @@ export const RESULT_SIZE_KEY = "anthropic/maxResultSizeChars";
|
|
|
24
24
|
* images) is never counted, let alone saved or cut.
|
|
25
25
|
*/
|
|
26
26
|
export const MCP_OUTPUT_TOKENS = HOST_RESULT_MAX_CHARS;
|
|
27
|
+
/** The `_meta` key of a listed tool by which the CLI never defers it behind its tool search. */
|
|
28
|
+
export const ALWAYS_LOAD_KEY = "anthropic/alwaysLoad";
|
|
27
29
|
/** `tools` as the server lists them to the CLI (`tools/list`): each as the host gave it, with the host's result bound as
|
|
28
|
-
* its result size.
|
|
29
|
-
|
|
30
|
+
* its result size. With the CLI's tool search on (harness.ts claudeToolSearch), only a run's MCP servers' tools
|
|
31
|
+
* (`mcp__<server>__<tool>`) wait behind it: every other tool of the session is listed to load always. */
|
|
32
|
+
export const listedTools = (tools) => tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema, _meta: { [RESULT_SIZE_KEY]: HOST_RESULT_MAX_CHARS, ...(t.name.startsWith("mcp__") ? {} : { [ALWAYS_LOAD_KEY]: true }) } }));
|
|
30
33
|
/** The SDK's in-process server config for `tools`: `call(name, args, toolUseId)` answers each call. Built with `modules`,
|
|
31
34
|
* else with the MCP library imported by name, beside this package. */
|
|
32
35
|
export async function toolServer(name, tools, call, modules) {
|
package/dist/index.d.ts
CHANGED
|
@@ -4,7 +4,7 @@ export type { ClaudeAgentPin } from "./errors.js";
|
|
|
4
4
|
export type { ClaudeAgentAdapterOptions, ClaudeAgentProvider, ClaudeAgentSkill, ClaudeAgentThinking } from "./adapter.js";
|
|
5
5
|
export { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_CODE_VERSION as CLAUDE_AGENT_CLI_VERSION } from "./versions.js";
|
|
6
6
|
export { findClaudeExecutable as claudeAgentExecutable, platformSuffix as claudeAgentPlatform } from "./binary.js";
|
|
7
|
-
export { anthropicPolicy, CLAUDE_WEB_SEARCH_TOOL,
|
|
7
|
+
export { anthropicPolicy, CLAUDE_WEB_SEARCH_TOOL, OWN_TOOL_PREFIX, thinks, withWebSearches } from "./host/policy.js";
|
|
8
8
|
export type { AnthropicPolicyOptions, AnthropicUsage } from "./host/policy.js";
|
|
9
9
|
export type { ChildCommand, ConfineChild } from "./host/machine.js";
|
|
10
10
|
export { listedTools, MCP_OUTPUT_TOKENS, RESULT_SIZE_KEY, toolServer, type ToolServerModules } from "./host/tool-server.js";
|
package/dist/index.js
CHANGED
|
@@ -3,5 +3,5 @@ export { CLAUDE_AGENT_ALSO_OFF, CLAUDE_AGENT_CLI_SKILL_NAMES, CLAUDE_AGENT_DIGES
|
|
|
3
3
|
export { CLAUDE_AGENT_PACKAGE, ClaudeAgentNotInstalled, ClaudeAgentPinMismatch, ClaudeAgentThinkingOff } from "./errors.js";
|
|
4
4
|
export { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_CODE_VERSION as CLAUDE_AGENT_CLI_VERSION } from "./versions.js";
|
|
5
5
|
export { findClaudeExecutable as claudeAgentExecutable, platformSuffix as claudeAgentPlatform } from "./binary.js";
|
|
6
|
-
export { anthropicPolicy, CLAUDE_WEB_SEARCH_TOOL,
|
|
6
|
+
export { anthropicPolicy, CLAUDE_WEB_SEARCH_TOOL, OWN_TOOL_PREFIX, thinks, withWebSearches } from "./host/policy.js";
|
|
7
7
|
export { listedTools, MCP_OUTPUT_TOKENS, RESULT_SIZE_KEY, toolServer } from "./host/tool-server.js";
|
package/dist/resume.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { GateAnswer, GateCall } from '@parcha/agentrun-kernel';
|
|
1
2
|
import { type CallOutcome, type DanglingCall, type ToolBridge } from './host/process.js';
|
|
2
3
|
import type { DriveContext } from './host/kernel.js';
|
|
3
4
|
import type { JournalSessionStore, TranscriptLine } from './store.js';
|
|
@@ -8,6 +9,34 @@ import type { JournalSessionStore, TranscriptLine } from './store.js';
|
|
|
8
9
|
* are the CLI's own.
|
|
9
10
|
*/
|
|
10
11
|
export declare function danglingCalls(lines: readonly TranscriptLine[]): DanglingCall[];
|
|
12
|
+
/** The CLI's own WebSearch calls the transcript's last turn left without a result, as `danglingCalls` finds host-tool
|
|
13
|
+
* ones (tool: `WebSearch`). */
|
|
14
|
+
export declare function danglingSearches(lines: readonly TranscriptLine[]): DanglingCall[];
|
|
15
|
+
/** The CLI's name for its own web search. */
|
|
16
|
+
export declare const WEB_SEARCH = "WebSearch";
|
|
17
|
+
/** The answer a held WebSearch gets on the resume once the host's gate lets it run: the CLI ran nothing of it, and the
|
|
18
|
+
* model's next search with the same input runs on that answer (resumeDanglingSearches, releasedSearches). */
|
|
19
|
+
export declare const SEARCH_RELEASED = "Not searched yet: this search was held before it ran, and it may run now. Search again with the same query to run it.";
|
|
20
|
+
/**
|
|
21
|
+
* Before the CLI resumes the transcript: each dangling WebSearch that never started (the host's gate held it: its run
|
|
22
|
+
* parked on a person) is put to the gate again, under the id the model gave it. A deny answers it in the gate's words; an
|
|
23
|
+
* allow answers it SEARCH_RELEASED, since the provider runs a search only inside the CLI's own model request: the
|
|
24
|
+
* model's next search with the same input is then put to the gate under this call's id (releasedSearches), which the
|
|
25
|
+
* person's answer covers, so it asks no second card. A gate that parks again rejects out of here; what it wrote is the
|
|
26
|
+
* same lines again on the next resume.
|
|
27
|
+
*/
|
|
28
|
+
export declare function resumeDanglingSearches(ctx: DriveContext, store: JournalSessionStore, gate: (call: GateCall) => Promise<GateAnswer>): Promise<void>;
|
|
29
|
+
/** The key a WebSearch's input is matched by: the model's next search "with the same query" is one with this input. */
|
|
30
|
+
export declare const searchKey: (input: unknown) => string;
|
|
31
|
+
/**
|
|
32
|
+
* The WebSearch calls the transcript answered SEARCH_RELEASED that no later WebSearch with the same input has taken up
|
|
33
|
+
* yet, oldest first: each `{ callId, key }`, so the model's next search with that input is put to the gate under the held
|
|
34
|
+
* call's id. Read from the transcript, so a release survives a restart between its answer and the model's search.
|
|
35
|
+
*/
|
|
36
|
+
export declare function releasedSearches(lines: readonly TranscriptLine[]): {
|
|
37
|
+
callId: string;
|
|
38
|
+
key: string;
|
|
39
|
+
}[];
|
|
11
40
|
/**
|
|
12
41
|
* The user line that answers `call` with its outcome, as Claude Code writes an MCP tool's result: after the
|
|
13
42
|
* transcript's last line, with the session fields of the assistant line that made the call. Its `uuid` is the call's,
|
package/dist/resume.js
CHANGED
|
@@ -1,11 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
// which calls those are, read from the transcript the drive is about to resume, and how one's result is written into
|
|
3
|
-
// it. The decision (run it, or leave it to the CLI's own repair) is the shared one, `resumeUnstartedCalls`: only a call
|
|
4
|
-
// with no effect of its own on the run's journal runs here, through the tool bridge (the host's gate first, then its
|
|
5
|
-
// intent, the call and its result), and only then is its result written here, before the CLI starts again. A call
|
|
6
|
-
// that has an effect is left as before: the CLI answers it "[Tool call interrupted]", and the recovery note says what
|
|
7
|
-
// the log knows of it.
|
|
8
|
-
import { resumeUnstartedCalls } from './host/process.js';
|
|
1
|
+
import { askGate, resumeUnstartedCalls, unstartedCalls } from './host/process.js';
|
|
9
2
|
import { uuidFrom } from './ids.js';
|
|
10
3
|
import { toolResultIds } from './store.js';
|
|
11
4
|
import { MCP_SERVER } from './transcript.js';
|
|
@@ -25,6 +18,72 @@ const isPrompt = (line) => line.type === 'user' && line.isSidechain !== true &&
|
|
|
25
18
|
* are the CLI's own.
|
|
26
19
|
*/
|
|
27
20
|
export function danglingCalls(lines) {
|
|
21
|
+
return danglingOf(lines, (name) => (name.startsWith(BRIDGED) ? name.slice(BRIDGED.length) : undefined));
|
|
22
|
+
}
|
|
23
|
+
/** The CLI's own WebSearch calls the transcript's last turn left without a result, as `danglingCalls` finds host-tool
|
|
24
|
+
* ones (tool: `WebSearch`). */
|
|
25
|
+
export function danglingSearches(lines) {
|
|
26
|
+
return danglingOf(lines, (name) => (name === WEB_SEARCH ? name : undefined));
|
|
27
|
+
}
|
|
28
|
+
/** The CLI's name for its own web search. */
|
|
29
|
+
export const WEB_SEARCH = 'WebSearch';
|
|
30
|
+
/** The answer a held WebSearch gets on the resume once the host's gate lets it run: the CLI ran nothing of it, and the
|
|
31
|
+
* model's next search with the same input runs on that answer (resumeDanglingSearches, releasedSearches). */
|
|
32
|
+
export const SEARCH_RELEASED = 'Not searched yet: this search was held before it ran, and it may run now. Search again with the same query to run it.';
|
|
33
|
+
/**
|
|
34
|
+
* Before the CLI resumes the transcript: each dangling WebSearch that never started (the host's gate held it: its run
|
|
35
|
+
* parked on a person) is put to the gate again, under the id the model gave it. A deny answers it in the gate's words; an
|
|
36
|
+
* allow answers it SEARCH_RELEASED, since the provider runs a search only inside the CLI's own model request: the
|
|
37
|
+
* model's next search with the same input is then put to the gate under this call's id (releasedSearches), which the
|
|
38
|
+
* person's answer covers, so it asks no second card. A gate that parks again rejects out of here; what it wrote is the
|
|
39
|
+
* same lines again on the next resume.
|
|
40
|
+
*/
|
|
41
|
+
export async function resumeDanglingSearches(ctx, store, gate) {
|
|
42
|
+
const held = unstartedCalls(ctx, danglingSearches(store.lines()));
|
|
43
|
+
for (const call of held) {
|
|
44
|
+
const refused = await askGate(gate, { callId: call.callId, tool: call.tool, args: (call.args ?? {}) }, ctx.signal);
|
|
45
|
+
store.extend(resultLine(store.lines(), call, refused ? { text: refused.deny, isError: true } : { text: SEARCH_RELEASED, isError: true }));
|
|
46
|
+
}
|
|
47
|
+
if (held.length)
|
|
48
|
+
await store.flush();
|
|
49
|
+
}
|
|
50
|
+
/** The key a WebSearch's input is matched by: the model's next search "with the same query" is one with this input. */
|
|
51
|
+
export const searchKey = (input) => JSON.stringify(input ?? {});
|
|
52
|
+
/**
|
|
53
|
+
* The WebSearch calls the transcript answered SEARCH_RELEASED that no later WebSearch with the same input has taken up
|
|
54
|
+
* yet, oldest first: each `{ callId, key }`, so the model's next search with that input is put to the gate under the held
|
|
55
|
+
* call's id. Read from the transcript, so a release survives a restart between its answer and the model's search.
|
|
56
|
+
*/
|
|
57
|
+
export function releasedSearches(lines) {
|
|
58
|
+
const inputs = new Map();
|
|
59
|
+
const pending = [];
|
|
60
|
+
for (const line of lines) {
|
|
61
|
+
if (line.isSidechain === true)
|
|
62
|
+
continue;
|
|
63
|
+
for (const block of toolUses(line)) {
|
|
64
|
+
if (block.name !== WEB_SEARCH)
|
|
65
|
+
continue;
|
|
66
|
+
const key = searchKey(block.input);
|
|
67
|
+
inputs.set(block.id, key);
|
|
68
|
+
const taken = pending.findIndex((one) => one.key === key);
|
|
69
|
+
if (taken >= 0)
|
|
70
|
+
pending.splice(taken, 1);
|
|
71
|
+
}
|
|
72
|
+
for (const id of toolResultIds(line))
|
|
73
|
+
if (inputs.has(id) && resultText(line, id) === SEARCH_RELEASED)
|
|
74
|
+
pending.push({ callId: id, key: inputs.get(id) });
|
|
75
|
+
}
|
|
76
|
+
return pending;
|
|
77
|
+
}
|
|
78
|
+
/** The text of the result `line` gives the call `id`. */
|
|
79
|
+
function resultText(line, id) {
|
|
80
|
+
const content = line.message?.content;
|
|
81
|
+
const result = Array.isArray(content) ? content.find((c) => c?.type === 'tool_result' && c.tool_use_id === id) : undefined;
|
|
82
|
+
const body = result?.content;
|
|
83
|
+
return typeof body === 'string' ? body : Array.isArray(body) ? body.map((c) => (typeof c?.text === 'string' ? c.text : '')).join('') : undefined;
|
|
84
|
+
}
|
|
85
|
+
/** The tool uses after the last prompt that no result answers, each named by `named` (undefined: not one of these). */
|
|
86
|
+
function danglingOf(lines, named) {
|
|
28
87
|
let from = 0;
|
|
29
88
|
for (let i = lines.length - 1; i >= 0; i--) {
|
|
30
89
|
if (isPrompt(lines[i])) {
|
|
@@ -34,10 +93,10 @@ export function danglingCalls(lines) {
|
|
|
34
93
|
}
|
|
35
94
|
const tail = lines.slice(from).filter((line) => line.isSidechain !== true);
|
|
36
95
|
const answered = new Set(tail.flatMap((line) => toolResultIds(line)));
|
|
37
|
-
return tail
|
|
38
|
-
.
|
|
39
|
-
|
|
40
|
-
|
|
96
|
+
return tail.flatMap(toolUses).flatMap((block) => {
|
|
97
|
+
const tool = answered.has(block.id) ? undefined : named(block.name);
|
|
98
|
+
return tool === undefined ? [] : [{ callId: block.id, tool, args: block.input ?? {} }];
|
|
99
|
+
});
|
|
41
100
|
}
|
|
42
101
|
/**
|
|
43
102
|
* The user line that answers `call` with its outcome, as Claude Code writes an MCP tool's result: after the
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@parcha/agentrun-harness-claude",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.38",
|
|
4
4
|
"description": "The Claude Agent SDK as an AgentRun harness: the host's tools as its only tools, its model behind a loopback proxy, durable in AgentRun's own store.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agentrun",
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
"test": "node --test --test-concurrency=8 'test/*.test.mjs'"
|
|
49
49
|
},
|
|
50
50
|
"dependencies": {
|
|
51
|
-
"@parcha/agentrun-kernel": "0.1.0-beta.
|
|
51
|
+
"@parcha/agentrun-kernel": "0.1.0-beta.38"
|
|
52
52
|
},
|
|
53
53
|
"peerDependencies": {
|
|
54
54
|
"@anthropic-ai/claude-agent-sdk": "0.3.286",
|
|
@@ -77,6 +77,6 @@
|
|
|
77
77
|
},
|
|
78
78
|
"devDependencies": {
|
|
79
79
|
"@anthropic-ai/claude-agent-sdk": "0.3.286",
|
|
80
|
-
"@parcha/agentrun-dsl": "0.1.0-beta.
|
|
80
|
+
"@parcha/agentrun-dsl": "0.1.0-beta.38"
|
|
81
81
|
}
|
|
82
82
|
}
|