@parcha/agentrun-harness-claude 0.1.0-beta.37 → 0.1.0-beta.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +46 -0
- package/README.md +1 -1
- package/dist/adapter.d.ts +3 -1
- package/dist/adapter.js +20 -54
- package/dist/facts.js +9 -4
- package/dist/harness.d.ts +27 -17
- package/dist/harness.js +43 -41
- package/dist/host/machine.d.ts +2 -9
- package/dist/host/machine.js +1 -4
- package/dist/host/policy.d.ts +19 -10
- package/dist/host/policy.js +48 -16
- package/dist/host/tool-server.d.ts +5 -1
- package/dist/host/tool-server.js +5 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/resume.d.ts +4 -3
- package/dist/resume.js +4 -3
- package/dist/testing/fake-anthropic.d.ts +9 -0
- package/dist/testing/fake-anthropic.js +4 -3
- package/dist/versions.d.ts +9 -0
- package/dist/versions.js +9 -0
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,52 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## 0.1.0-beta.39 (2026-11-16)
|
|
6
|
+
|
|
7
|
+
- A capped Claude Agent run on a Claude model reached through a gateway (Sonnet 5.5 through OpenRouter) no longer stops at its second step with most of its cap left. The provider's count is asked for only at Anthropic, and no local tokenizer counts Claude, so each request was bounded by its bytes: about four times its tokens. An inbox agent's second request read as about 32,000 tokens, so at a $0.10 cap the step after one that cost $0.01-0.02 "needs at least $0.10" and the run paused, where a real step costs about $0.03. The model proxy now keeps each model's last request whose answer reported its whole input, and bounds a later request that carries it unchanged by that billed input plus the bytes of the messages it adds, when that is lower. That request must match the earlier one in everything that bills input apart from the added messages (system, tools, thinking, effort, model); a moved cache marker (a `cache_control` key on a tool, a system or message content block, or a block of a tool result's content) does not count as a change, and a `cache_control` key anywhere else is compared as text. The wrap-up note is asked for on that bound. A first request, a request that changes its tools or prompt, one that adds a document, or one that offers the hosted search keeps its byte bound, and a step that does not fit is still refused.
|
|
8
|
+
|
|
9
|
+
pi on a Claude model takes the same bound, through the same policy. Through a gateway, the smallest cap that takes a pi desktop run on Sonnet through its four screenshots to its answer goes from $0.12 to $0.09, the same as straight to Anthropic: the run needs $0.082, where it needed $0.110 on its bytes. Its first request keeps its byte bound ($0.052).
|
|
10
|
+
- A capped run on a model whose tokenizer is o200k_base, reached over Messages without Anthropic's count (pi on GPT-6.1 Sol through OpenRouter, sent through serve's translation), bounds each request's input by a local count with its stated margin, as a Responses request to a gateway already does. Before, its bytes were the bound: after a few long pages the body passed 272,000 bytes, every rate was priced at Sol's long-context tier, and a $1.50 run stopped at $0.10-0.27 because the cap refused to send a step it could pay for. A Claude model, a body with a document, or one that offers the hosted search keeps the provider count or the byte bound.
|
|
11
|
+
When a run's cap is below what its model needs for one more step and an answer, the wrap-up's words now say so with both amounts, and the effort the model's request asked for when it named one ("This run's cap of $0.25 is below what gpt-6.1-sol at medium effort needs for one more step and an answer, about $0.32."), so a run that stopped its tools at its first call shows the cap was the cause. The rule that decides when a run wraps up has not changed.
|
|
12
|
+
Saving an agent with a cap below that figure (POST /agents, an edit of its definition, or a package install with a per-run budget) now saves with a warning on `definition.max_cost_usd` ("This agent's cap of $0.25 is below what gpt-6.1-sol at medium effort needs for one more step and an answer, about $0.32: a run will wrap up at its first tool call."). It is never refused. The figure is priced on the first request the agent's harness sends: the harness's own input before the agent's prompt (Codex about 12,200 tokens, from billing; Claude Agent, OpenCode and pi measured on their pinned builds, each stated beside its pin), the agent's prompt where the model's tokenizer is o200k_base, and the least output at the agent's effort, its thinking included: a pi agent on a Claude model that thinks with a budget is priced with Claude's 1,024-token thinking minimum, as its first request asks for it.
|
|
13
|
+
- A claude-agent session with skills now tells its model that the Skill tool is its own and when to load a skill. The tools note said the app's `mcp__hands__` tools were the model's only ones, so a model that read it had no reason to call Skill, and template agents often skipped their SKILL.md. Measured on two watch templates (Claude Sonnet 5.5, 6 runs each): skill loads went from 2 of 6 and 0 of 6 to 6 of 6 and 4 of 6.
|
|
14
|
+
- A run's environment line now tells the date in the run's time zone, by weekday, day, month and year, and names the zone (`Today is Sunday 15 November 2026 (America/Los_Angeles).`), where it told the UTC date, a day ahead of the person's in an evening west of UTC. A run a schedule trigger started takes that trigger's zone; every other run takes the server's zone (`TZ`), and a zone the server does not know reads as UTC. The line carries no hour, so it changes once a day and the prompt cache holds within the day. A template eval's clock line to its graders says its date the same way.
|
|
15
|
+
- OpenRouter runs book what OpenRouter charged; routers need no cap or a read-back cost; a provider's error inside a stream is booked by what it reported.
|
|
16
|
+
- A request on an OpenRouter model is booked at the cost OpenRouter states in the answer's usage (with your own provider key, its fee plus the provider's charge). The price table's figure is kept beside it (`tableUsd`). A cap still holds each request at list price before it leaves. A stated cost that is missing, not a number, or above that hold is not used: the table's figure is booked instead.
|
|
17
|
+
- OpenRouter's routers (`openrouter/auto`, `openrouter/free` and the others) have no price here, because the model they pick is not known in advance. A run with a spend cap is refused before it starts. A run without one is booked at the cost OpenRouter reports, else unknown, never $0.
|
|
18
|
+
- A provider's error inside a successful (200) stream (Anthropic's `overloaded_error`, `api_error` or `rate_limit_error`, OpenRouter's mid-stream errors, a Responses `response.failed`) is booked by one rule. If the stream reported tokens before the error, they are booked at list price, or at the cost OpenRouter stated, and the run's cost stays known: before, such a request was booked at the cap's hold and made the run's cost unknown. If it reported no tokens, it is booked as refused at $0, and the run's record keeps the provider's message (`refusal`, or `providerError` beside a booked figure). That holds only while the model generated nothing: once the stream shows the model began its output (a content block, a Responses output item, hidden reasoning included, or a text-tools model's reply the runner had not sent yet), an error with no usage is booked at an unknown cost, never $0.
|
|
19
|
+
- Kernel: `startModelProxy` books a cost stated in the answer's usage when its origin is OpenRouter's or serve's translation route's (`statesUsageCost`, `ROUTE_ORIGIN`), on every harness: claude-agent, codex and opencode runs on OpenRouter book what OpenRouter charged too. `Ended` gains `tableUsd` on an answer, `{ end: "answered", label: "error", reason }` and `{ end: "nothing", label: "refused", reason }`. `bookRequest` books the table's figure (rule `answered:over_hold`) when a reported figure is above the hold. The claude-agent policy's usage reads a stream that ends in an `error` event as whole. Routers and in-stream errors are handled on those harnesses too.
|
|
20
|
+
- On Claude Agent, a tool call that ran beside a call waiting for approval keeps its result. Before, when one answer from the model made two MCP calls, a read that runs on its own and a write that asks, and the run paused on the write, the read's result was lost once the run went on. The model was told the read was interrupted, so it ran the read again.
|
|
21
|
+
- The read had finished and its result was in the run's journal, but the Claude Agent CLI had not written it to its own transcript before the pause let it go. On the resume, every call left without a result in that transcript whose end the journal holds now gets that recorded result before the CLI starts again. Nothing runs twice and nothing is asked again.
|
|
22
|
+
- A call the pause or a crash cut off before it ended is answered as interrupted, as before. A call the pause held before it started still runs once it is approved.
|
|
23
|
+
- The same rule covers every CLI harness that resumes from its own transcript (Codex, OpenCode). Codex already kept the result in its own transcript.
|
|
24
|
+
|
|
25
|
+
## 0.1.0-beta.38 (2026-11-14)
|
|
26
|
+
|
|
27
|
+
- 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.
|
|
28
|
+
|
|
29
|
+
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.
|
|
30
|
+
- 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.
|
|
31
|
+
- Kernel: `@parcha/agentrun-kernel/host` exports `NATIVE_SEARCH_USD`. The Claude and Codex proxy policies and the runner's hosted search all read it.
|
|
32
|
+
- `@parcha/agentrun-harness-claude` no longer exports `CLAUDE_WEB_SEARCH_USD`; read `NATIVE_SEARCH_USD` from `@parcha/agentrun-kernel/host`.
|
|
33
|
+
- 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.
|
|
34
|
+
- 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.
|
|
35
|
+
- `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.
|
|
36
|
+
- `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.
|
|
37
|
+
- `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.
|
|
38
|
+
- 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.
|
|
39
|
+
- 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.
|
|
40
|
+
- A refused call inside a script ends the script with the refusal's words.
|
|
41
|
+
- After a crash, a call that was cut off is told as possibly done, and it is not run again.
|
|
42
|
+
- 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.
|
|
43
|
+
- 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.
|
|
44
|
+
- 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.
|
|
45
|
+
- 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.
|
|
46
|
+
- Three follow-ups to the tools_search / tools_call / codemode rule, found in a live walk.
|
|
47
|
+
- 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.
|
|
48
|
+
- 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.
|
|
49
|
+
- 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.
|
|
50
|
+
|
|
5
51
|
## 0.1.0-beta.37 (2026-11-13)
|
|
6
52
|
|
|
7
53
|
- 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.
|
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
|
|
@@ -95,6 +95,8 @@ export interface ClaudeAgentAdapterOptions {
|
|
|
95
95
|
fetch?: typeof fetch;
|
|
96
96
|
/** For tests: the clock a user turn's day is read from (harness.ts dateLine). Default the system's. */
|
|
97
97
|
now?: () => Date;
|
|
98
|
+
/** The IANA zone a user turn's day is read in (harness.ts dateLine), the one the host's environment line names. Default UTC. */
|
|
99
|
+
zone?: string;
|
|
98
100
|
}
|
|
99
101
|
/** The thinking levels a session runs at: the SDK's effort levels, with adaptive thinking. There is no off. */
|
|
100
102
|
export type ClaudeAgentThinking = "low" | "medium" | "high" | "xhigh" | "max";
|
package/dist/adapter.js
CHANGED
|
@@ -14,16 +14,15 @@ import { dirname, join } from "node:path";
|
|
|
14
14
|
import { READ_SKILL_FILE, hostedTool, readSkillFileTool, skillProblems } from "@parcha/agentrun-kernel";
|
|
15
15
|
import { abortedOutcome, openDrive, pendingSubmissions, Restart, SessionHalt } from "@parcha/agentrun-kernel/kernel";
|
|
16
16
|
import { toolSchemaProblems } from "@parcha/agentrun-kernel";
|
|
17
|
-
import { NativeJournal, recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
|
|
17
|
+
import { bridgeTool, NativeJournal, recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
|
|
18
18
|
import { checkedOnce, checkedOnceAsync, hostHeaderProblems, startModelProxy } from "@parcha/agentrun-kernel/host";
|
|
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`). */
|
|
@@ -223,38 +222,24 @@ class CallsInFlight {
|
|
|
223
222
|
});
|
|
224
223
|
}
|
|
225
224
|
}
|
|
226
|
-
/** The
|
|
227
|
-
* records, and of its end only once the outcome is (the live `tool_end` the tool bridge sends after the effect). */
|
|
228
|
-
function
|
|
229
|
-
return {
|
|
230
|
-
|
|
231
|
-
description: tool.description,
|
|
232
|
-
inputSchema: tool.inputSchema,
|
|
233
|
-
replay: tool.replay,
|
|
234
|
-
async execute(input, effect) {
|
|
235
|
-
// The effect's step is `tool:<the CLI's tool_use id>#<attempt>`: the host sees the CLI's call id.
|
|
236
|
-
const callId = (effect.stepId ?? "").replace(/^tool:/, "").replace(/#\d+$/, "");
|
|
237
|
-
// The step's attempt: above 0 when a crash cut an earlier attempt and the kernel runs the call again.
|
|
238
|
-
const attempt = Number(/#(\d+)$/.exec(effect.stepId ?? "")?.[1] ?? 0);
|
|
225
|
+
/** The bridge's tool for a host tool (bridgeTool). The host hears of the call (`tool_start`) once its intent is in the
|
|
226
|
+
* session's records, and of its end only once the outcome is (the live `tool_end` the tool bridge sends after the effect). */
|
|
227
|
+
function claudeTool(tool, io, maxImageBytes, calls) {
|
|
228
|
+
return bridgeTool(tool, {
|
|
229
|
+
start: ({ callId, args }) => {
|
|
239
230
|
// In flight, and past the pause's check, before the host hears of it: a pause the host starts on this tool_start
|
|
240
231
|
// waits for this call rather than refusing it.
|
|
241
|
-
calls
|
|
232
|
+
// 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
|
|
233
|
+
// never waits on it, so a nested call that parks the run does not hold the pause.
|
|
234
|
+
if (!tool.nests)
|
|
235
|
+
calls.begin(callId);
|
|
242
236
|
// 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
237
|
if (calls.draining)
|
|
244
238
|
throw new Error(`${tool.name} was not run: the session is pausing`);
|
|
245
|
-
io.onEvent({ type: "tool_start", callId, name: tool.name, args
|
|
246
|
-
const result = await tool.call(input, { callId, signal: effect.signal, attempt });
|
|
247
|
-
if (result.isError)
|
|
248
|
-
throw new Error(result.text);
|
|
249
|
-
if (!result.images?.length)
|
|
250
|
-
return result.text;
|
|
251
|
-
// 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
|
-
const wrong = toolImageProblems(tool.name, result.images, maxImageBytes);
|
|
253
|
-
if (wrong)
|
|
254
|
-
throw new Error(wrong);
|
|
255
|
-
return { text: result.text, images: result.images.map((image) => ({ mimeType: image.mimeType, data: image.data })) };
|
|
239
|
+
io.onEvent({ type: "tool_start", callId, name: tool.name, args });
|
|
256
240
|
},
|
|
257
|
-
|
|
241
|
+
imageProblems: (images) => toolImageProblems(tool.name, images, maxImageBytes),
|
|
242
|
+
});
|
|
258
243
|
}
|
|
259
244
|
const turnsIn = (drive) => transcriptOf(drive.state()).filter((r) => r.data?.type === "turn");
|
|
260
245
|
/** Root keywords the pinned CLI (2.1.286) drops a tool for, with no word to the model or the host: measured, a root
|
|
@@ -299,7 +284,6 @@ export function claudeAgentAdapter(options) {
|
|
|
299
284
|
};
|
|
300
285
|
return {
|
|
301
286
|
id: CLAUDE_AGENT_ID,
|
|
302
|
-
capabilities: () => ({ mcpClient: CLAUDE_MCP_CLIENT }),
|
|
303
287
|
check(spec) {
|
|
304
288
|
const problems = [];
|
|
305
289
|
if (spec.context === "fork")
|
|
@@ -317,18 +301,6 @@ export function claudeAgentAdapter(options) {
|
|
|
317
301
|
const common = toolSchemaProblems(tool.name, tool.inputSchema);
|
|
318
302
|
problems.push(...common, ...(common.length ? [] : claudeSchemaProblems(tool.name, tool.inputSchema)));
|
|
319
303
|
}
|
|
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
304
|
return problems;
|
|
333
305
|
},
|
|
334
306
|
async open(spec, io) {
|
|
@@ -341,9 +313,6 @@ export function claudeAgentAdapter(options) {
|
|
|
341
313
|
// With skills, the model also reads their files (read_skill_file), from the session's own copy of them.
|
|
342
314
|
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
315
|
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
316
|
// The CLI's own tools offered to the model: Skill only when the session has skills, WebSearch only when it is on.
|
|
348
317
|
const builtins = [...(skills.length ? ["Skill"] : []), ...(webSearch ? ["WebSearch"] : [])];
|
|
349
318
|
const acquire = localMachine({
|
|
@@ -356,13 +325,14 @@ export function claudeAgentAdapter(options) {
|
|
|
356
325
|
tools: tools.map((t) => t.name),
|
|
357
326
|
...(builtins.length ? { builtins } : {}),
|
|
358
327
|
...(webSearch ? { webSearch: true, ...(options.webSearchAllowance !== undefined ? { webSearchAllowance: options.webSearchAllowance } : {}) } : {}),
|
|
328
|
+
// What the CLI sends with its own tool search on, which the harness turns on as this does (claudeToolSearch).
|
|
329
|
+
...(claudeToolSearch(tools.map((t) => t.name), spec.deferCatalog) === "true" ? { toolSearch: true } : {}),
|
|
359
330
|
...(options.price ? { price: options.price } : {}),
|
|
360
331
|
...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}),
|
|
361
332
|
...(options.provider.auth ? { auth: options.provider.auth } : {}),
|
|
362
333
|
...(options.provider.headers ? { headers: options.provider.headers } : {}),
|
|
363
334
|
...(options.log ? { log: options.log } : {}),
|
|
364
335
|
...(options.fetch ? { fetch: options.fetch } : {}),
|
|
365
|
-
...(spec.mcp ? { mcp: { session: spec.mcp, tools: [...mcpNames] } } : {}),
|
|
366
336
|
},
|
|
367
337
|
});
|
|
368
338
|
// The SDK this session runs on (the host's, or the one installed beside this package, checked above), thinking at
|
|
@@ -376,13 +346,13 @@ export function claudeAgentAdapter(options) {
|
|
|
376
346
|
// No command of its own: the CLI reaches nothing but its model proxy (a web search, when on, is the provider's).
|
|
377
347
|
network: "deny-all",
|
|
378
348
|
},
|
|
379
|
-
tools: tools.map((tool) =>
|
|
349
|
+
tools: tools.map((tool) => claudeTool(tool, io, maxImageBytes, calls)),
|
|
350
|
+
...(spec.deferCatalog === undefined ? {} : { deferCatalog: spec.deferCatalog }),
|
|
380
351
|
builtins: false,
|
|
381
352
|
// Off by name too, besides tools: []: the pinned CLI's tools that neither the harness's allowlist nor its off list
|
|
382
353
|
// decide (test/tool-off.test.mjs pins the CLI's whole tool set against these lists), but WebSearch when it is on.
|
|
383
354
|
disallowedTools: CLAUDE_AGENT_ALSO_OFF.filter((name) => !(webSearch && name === "WebSearch")),
|
|
384
355
|
...(webSearch ? { providerTools: ["web_search"] } : {}),
|
|
385
|
-
...(mcpServers.length ? { mcpServers: mcpServers.map((server) => ({ name: server.name, tools: server.tools.map((tool) => tool.name) })) } : {}),
|
|
386
356
|
model: modelFor(spec),
|
|
387
357
|
...(skills.length ? { skills: { plugin: join(dir, "plugin"), names: writeSkillsPlugin(join(dir, "plugin"), skills) } } : {}),
|
|
388
358
|
...(options.smallModel ? { smallModel: options.smallModel } : {}),
|
|
@@ -394,6 +364,7 @@ export function claudeAgentAdapter(options) {
|
|
|
394
364
|
...(options.mcp ? { toolServerModules: options.mcp } : {}),
|
|
395
365
|
...(options.log ? { log: options.log } : {}),
|
|
396
366
|
...(options.now ? { now: options.now } : {}),
|
|
367
|
+
...(options.zone ? { zone: options.zone } : {}),
|
|
397
368
|
// The host's gate, asked about each host-tool call and each WebSearch before it is written or run.
|
|
398
369
|
...(io.gate ? { gate: (call) => io.gate(call) } : {}),
|
|
399
370
|
});
|
|
@@ -404,11 +375,6 @@ export function claudeAgentAdapter(options) {
|
|
|
404
375
|
// The model's message ended inside the turn (the CLI resumes a cut answer itself): what it said so far is one message.
|
|
405
376
|
if (e?.type === "text_end")
|
|
406
377
|
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
378
|
// The tool bridge's `tool_end` comes once the call's outcome is in the session's records: only then does the host
|
|
413
379
|
// hear the call ended, with the text recorded.
|
|
414
380
|
if (e?.type === "tool_end" && typeof e.callId === "string" && typeof e.name === "string") {
|
package/dist/facts.js
CHANGED
|
@@ -3,22 +3,23 @@
|
|
|
3
3
|
// machine on.
|
|
4
4
|
import { toolSchemaProblems } from "@parcha/agentrun-kernel";
|
|
5
5
|
import { anthropicPolicy } from "./host/policy.js";
|
|
6
|
-
import { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION } from "./versions.js";
|
|
6
|
+
import { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_AGENT_BASE_INPUT_TOKENS } from "./versions.js";
|
|
7
7
|
export const facts = Object.freeze({
|
|
8
8
|
id: "claude-agent",
|
|
9
9
|
label: "Claude",
|
|
10
10
|
wire: "anthropic-messages",
|
|
11
11
|
// A message that comes mid-turn waits for the turn's end.
|
|
12
12
|
steer: false,
|
|
13
|
-
// A call that started is never run again (the CLI answers
|
|
13
|
+
// A call that started is never run again (one cut off the CLI answers "[Tool call interrupted]"; one that ended gets its
|
|
14
|
+
// recorded result); only the model calls again.
|
|
14
15
|
rerunsStarted: false,
|
|
16
|
+
// 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.
|
|
17
|
+
ownToolSearch: true,
|
|
15
18
|
// An answer its output limit cut, the CLI resumes itself in the same turn ("Output token limit hit. Resume directly"),
|
|
16
19
|
// up to 3 times; only a cut it no longer resumes ends the turn cut.
|
|
17
20
|
recoversCutAnswers: 3,
|
|
18
21
|
// One run's memory, measured with the server's (serve's host.ts): the CLI and its SDK beside the run's process.
|
|
19
22
|
runMib: 288,
|
|
20
|
-
// Its own MCP client binds the session's remote MCP servers.
|
|
21
|
-
mcp: true,
|
|
22
23
|
thinking: Object.freeze(["low", "medium", "high", "xhigh", "max"]),
|
|
23
24
|
// Anthropic's web search, through the session's proxy, as the pinned CLI's WebSearch asks for it.
|
|
24
25
|
webSearch: "native",
|
|
@@ -31,6 +32,10 @@ export const facts = Object.freeze({
|
|
|
31
32
|
// the pinned CLI), without a word.
|
|
32
33
|
// The CLI's own tools, each the host's table tool it is.
|
|
33
34
|
nativeTools: Object.freeze({ WebSearch: "web_search", WebFetch: "web_fetch", Bash: "bash", Read: "read", Write: "write", Edit: "edit" }),
|
|
35
|
+
// The SDK's in-process server serves every host tool as `mcp__hands__<host tool>`.
|
|
36
|
+
hostName: (given) => given.replace(/^mcp__hands__/, ""),
|
|
37
|
+
// Its first request's own input before the agent's prompt, measured on the pinned CLI (versions.ts).
|
|
38
|
+
baseInputTokens: CLAUDE_AGENT_BASE_INPUT_TOKENS,
|
|
34
39
|
schemaProblems: (tool, schema) => [...toolSchemaProblems(tool, schema), ...["anyOf", "allOf", "oneOf"].filter((key) => key in schema).map((key) => `/${key}: the Claude Agent CLI drops a tool whose root has ${key}`)],
|
|
35
40
|
policy: (options) => anthropicPolicy({ model: options.model, tools: options.tools, ...(options.auth ? { auth: options.auth } : {}), ...(options.webSearch === true ? { webSearch: true, ...(options.webSearchAllowance ? { webSearchAllowance: options.webSearchAllowance } : {}) } : {}), ...(options.maxOutputTokens ? { maxOutputTokens: options.maxOutputTokens } : {}) }),
|
|
36
41
|
});
|
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
|
|
@@ -241,9 +232,11 @@ export interface ClaudeCodeHarnessOptions {
|
|
|
241
232
|
gate?: (call: GateCall) => Promise<GateAnswer>;
|
|
242
233
|
/** The clock a user turn's day is read from (dateLine). Default the system's. */
|
|
243
234
|
now?: () => Date;
|
|
235
|
+
/** The IANA zone the day is read in (dateLine). Default UTC. */
|
|
236
|
+
zone?: string;
|
|
244
237
|
}
|
|
245
238
|
/**
|
|
246
|
-
* The line a user turn starts with when the session's model was not yet told its day: today's date, in UTC.
|
|
239
|
+
* The line a user turn starts with when the session's model was not yet told its day: today's date, in `zone` (UTC by default).
|
|
247
240
|
*
|
|
248
241
|
* The CLI records a session's system prompt at its first request and every resume sends that record, so a date the
|
|
249
242
|
* host put there (serve's environment line) stays the first day's. Re-rendering it (`snapshot: false`) records nothing
|
|
@@ -251,15 +244,19 @@ export interface ClaudeCodeHarnessOptions {
|
|
|
251
244
|
* not been told carries this line, in the CLI's transcript only (the host's log keeps the person's words). The
|
|
252
245
|
* session's first launch sends no line on its first day: its fresh system prompt is the one recorded.
|
|
253
246
|
*/
|
|
254
|
-
export declare function dateLine(now: Date): string;
|
|
247
|
+
export declare function dateLine(now: Date, zone?: string): string;
|
|
255
248
|
/** The default model. */
|
|
256
249
|
export declare const DEFAULT_MODEL = "claude-sonnet-5-5";
|
|
257
250
|
/** What the harness appends to the system prompt about the tools, before `instructions`, with the built-ins off and the app's tools there. */
|
|
258
251
|
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.";
|
|
259
252
|
/** `TOOLS_NOTE` with WebSearch on (`providerTools: ['web_search']`) and the other built-ins off. */
|
|
260
253
|
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.";
|
|
261
|
-
/**
|
|
262
|
-
|
|
254
|
+
/**
|
|
255
|
+
* What follows the tools note when the session has skills. The notes above say the app's tools are the model's only ones,
|
|
256
|
+
* and Skill is not one of those: a model that reads them has no reason to reach for it. This names Skill as its tool and
|
|
257
|
+
* says when to use it, as the on-demand listing does for a harness that reads its skills' files (serve's ON_DEMAND).
|
|
258
|
+
*/
|
|
259
|
+
export declare const SKILLS_NOTE = "The Skill tool is also yours: it loads one of this app's skills, listed to you as agentrun:<name> with what each is for. When a skill fits the step you are on, or your instructions name one, load it with Skill before you act on that step, and follow it; read its other files with read_skill_file.";
|
|
263
260
|
/** `TOOLS_NOTE` for a session with no tools at all (built-ins off, no `tools`). */
|
|
264
261
|
export declare const NO_TOOLS_NOTE = "You have no tools in this session: no shell, file, search or web tools. Answer from the conversation.";
|
|
265
262
|
/** With the built-ins on (docs/workspaces.md §5.6 "Workspace note"): what `/workspace` is. */
|
|
@@ -283,6 +280,19 @@ export declare const CLAUDE_BUILTINS_OFF: string[];
|
|
|
283
280
|
export declare const CLAUDE_BUILTINS: readonly ["Bash", "Read", "Edit", "Write", "NotebookEdit", "WebFetch"];
|
|
284
281
|
/** Built-ins that only read: "safe to repeat" after a crash, and no flush before their outcome. Everything else: "may have taken effect". */
|
|
285
282
|
export declare const CLAUDE_SAFE_BUILTINS: string[];
|
|
283
|
+
/**
|
|
284
|
+
* ENABLE_TOOL_SEARCH for a session whose tools are `toolNames` (the host's names): when the run's catalog tools are
|
|
285
|
+
* deferred (the kernel's defersCatalog: more than DEFER_CATALOG_OVER of them; the host's own tools_search and tools_call
|
|
286
|
+
* are never offered beside it), `true`: the CLI's own tool search is on, its ToolSearch among its tools, and those tools are
|
|
287
|
+
* deferred (served through `hands`, the rest of the session's tools listed to load always: tool-server.ts listedTools),
|
|
288
|
+
* each sent to the model once ToolSearch finds it. Without, `false`. The pinned CLI (2.1.286) leaves it off behind a
|
|
289
|
+
* proxy unless told, and its `auto` defers only past a tenth of the model's context (on a 1M-token model, never in
|
|
290
|
+
* practice); set either way, so a CLI that changes that default changes nothing here. The session's proxy admits what the
|
|
291
|
+
* CLI sends with it on (anthropicPolicy `toolSearch`).
|
|
292
|
+
*/
|
|
293
|
+
export declare const claudeToolSearch: (toolNames: readonly string[], deferCatalog?: boolean) => "true" | "false";
|
|
294
|
+
/** The CLI's own tool that finds a deferred tool: it only reads the CLI's list of the session's tools. */
|
|
295
|
+
export declare const CLAUDE_TOOL_SEARCH = "ToolSearch";
|
|
286
296
|
/** The default `builtinReplay`. */
|
|
287
297
|
export declare const claudeBuiltinReplay: (name: string) => ReplayPolicy;
|
|
288
298
|
/** The `builtins` option, resolved: the `tools` option for `query()` (undefined: the preset, all of them). */
|
package/dist/harness.js
CHANGED
|
@@ -6,6 +6,7 @@ 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
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';
|
|
@@ -19,7 +20,7 @@ import { MCP_SERVER, TranscriptBuilder } from './transcript.js';
|
|
|
19
20
|
import { CLAUDE_AGENT_CLI_SKILL_NAMES } from './cli-names.js';
|
|
20
21
|
import { assertAgentSdkVersion, CLAUDE_VM_EXECUTABLE } from './versions.js';
|
|
21
22
|
/**
|
|
22
|
-
* The line a user turn starts with when the session's model was not yet told its day: today's date, in UTC.
|
|
23
|
+
* The line a user turn starts with when the session's model was not yet told its day: today's date, in `zone` (UTC by default).
|
|
23
24
|
*
|
|
24
25
|
* The CLI records a session's system prompt at its first request and every resume sends that record, so a date the
|
|
25
26
|
* host put there (serve's environment line) stays the first day's. Re-rendering it (`snapshot: false`) records nothing
|
|
@@ -27,10 +28,11 @@ import { assertAgentSdkVersion, CLAUDE_VM_EXECUTABLE } from './versions.js';
|
|
|
27
28
|
* not been told carries this line, in the CLI's transcript only (the host's log keeps the person's words). The
|
|
28
29
|
* session's first launch sends no line on its first day: its fresh system prompt is the one recorded.
|
|
29
30
|
*/
|
|
30
|
-
export function dateLine(now) {
|
|
31
|
-
return `Today is ${dayOf(now)}
|
|
31
|
+
export function dateLine(now, zone = 'UTC') {
|
|
32
|
+
return `Today is ${dayOf(now, zone)}.`;
|
|
32
33
|
}
|
|
33
|
-
|
|
34
|
+
/** `now`'s day as a person in `zone` reads it, the zone's name after it ("Sunday 15 November 2026 (America/Los_Angeles)"). */
|
|
35
|
+
const dayOf = (now, zone = 'UTC') => `${new Intl.DateTimeFormat('en-GB', { timeZone: zone, weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' }).format(now).replace(',', '')} (${zone})`;
|
|
34
36
|
/** The effect a user message that told its model the day is recorded under (`date:<message uuid>`, input `{ day }`). */
|
|
35
37
|
const DATE_EFFECT = 'date';
|
|
36
38
|
/** The default model. */
|
|
@@ -39,8 +41,12 @@ export const DEFAULT_MODEL = 'claude-sonnet-5-5';
|
|
|
39
41
|
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
42
|
/** `TOOLS_NOTE` with WebSearch on (`providerTools: ['web_search']`) and the other built-ins off. */
|
|
41
43
|
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
|
-
/**
|
|
43
|
-
|
|
44
|
+
/**
|
|
45
|
+
* What follows the tools note when the session has skills. The notes above say the app's tools are the model's only ones,
|
|
46
|
+
* and Skill is not one of those: a model that reads them has no reason to reach for it. This names Skill as its tool and
|
|
47
|
+
* says when to use it, as the on-demand listing does for a harness that reads its skills' files (serve's ON_DEMAND).
|
|
48
|
+
*/
|
|
49
|
+
export const SKILLS_NOTE = `The Skill tool is also yours: it loads one of this app's skills, listed to you as agentrun:<name> with what each is for. When a skill fits the step you are on, or your instructions name one, load it with Skill before you act on that step, and follow it; read its other files with read_skill_file.`;
|
|
44
50
|
/** `TOOLS_NOTE` for a session with no tools at all (built-ins off, no `tools`). */
|
|
45
51
|
export const NO_TOOLS_NOTE = 'You have no tools in this session: no shell, file, search or web tools. Answer from the conversation.';
|
|
46
52
|
/** With the built-ins on (docs/workspaces.md §5.6 "Workspace note"): what `/workspace` is. */
|
|
@@ -90,6 +96,19 @@ export const CLAUDE_BUILTINS_OFF = [
|
|
|
90
96
|
export const CLAUDE_BUILTINS = ['Bash', 'Read', 'Edit', 'Write', 'NotebookEdit', 'WebFetch'];
|
|
91
97
|
/** Built-ins that only read: "safe to repeat" after a crash, and no flush before their outcome. Everything else: "may have taken effect". */
|
|
92
98
|
export const CLAUDE_SAFE_BUILTINS = ['Read', 'Glob', 'Grep', 'LS', 'NotebookRead', 'WebFetch', 'WebSearch', 'ToolSearch', 'Skill'];
|
|
99
|
+
/**
|
|
100
|
+
* ENABLE_TOOL_SEARCH for a session whose tools are `toolNames` (the host's names): when the run's catalog tools are
|
|
101
|
+
* deferred (the kernel's defersCatalog: more than DEFER_CATALOG_OVER of them; the host's own tools_search and tools_call
|
|
102
|
+
* are never offered beside it), `true`: the CLI's own tool search is on, its ToolSearch among its tools, and those tools are
|
|
103
|
+
* deferred (served through `hands`, the rest of the session's tools listed to load always: tool-server.ts listedTools),
|
|
104
|
+
* each sent to the model once ToolSearch finds it. Without, `false`. The pinned CLI (2.1.286) leaves it off behind a
|
|
105
|
+
* proxy unless told, and its `auto` defers only past a tenth of the model's context (on a 1M-token model, never in
|
|
106
|
+
* practice); set either way, so a CLI that changes that default changes nothing here. The session's proxy admits what the
|
|
107
|
+
* CLI sends with it on (anthropicPolicy `toolSearch`).
|
|
108
|
+
*/
|
|
109
|
+
export const claudeToolSearch = (toolNames, deferCatalog) => ((deferCatalog ?? defersCatalog(toolNames)) ? 'true' : 'false');
|
|
110
|
+
/** The CLI's own tool that finds a deferred tool: it only reads the CLI's list of the session's tools. */
|
|
111
|
+
export const CLAUDE_TOOL_SEARCH = 'ToolSearch';
|
|
93
112
|
/** The default `builtinReplay`. */
|
|
94
113
|
export const claudeBuiltinReplay = replayBy(CLAUDE_SAFE_BUILTINS);
|
|
95
114
|
/** 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 +178,6 @@ async function bwrapWorks(machine, signal) {
|
|
|
159
178
|
return false;
|
|
160
179
|
}
|
|
161
180
|
}
|
|
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
181
|
export function claudeCodeHarness(options = {}) {
|
|
180
182
|
const tools = options.tools ?? [];
|
|
181
183
|
const allowed = builtinTools(options.builtins);
|
|
@@ -188,8 +190,8 @@ export function claudeCodeHarness(options = {}) {
|
|
|
188
190
|
const replay = typeof options.builtinReplay === 'function' ? options.builtinReplay : options.builtinReplay ? (name) => options.builtinReplay[name] ?? claudeBuiltinReplay(name) : claudeBuiltinReplay;
|
|
189
191
|
const providerTools = options.providerTools ?? [];
|
|
190
192
|
const webSearch = providerTools.includes('web_search');
|
|
191
|
-
|
|
192
|
-
const
|
|
193
|
+
/** The CLI's own tool search is on: a run's MCP servers' tools deferred behind its ToolSearch (claudeToolSearch). */
|
|
194
|
+
const toolSearch = claudeToolSearch(tools.map((tool) => tool.name), options.deferCatalog) === 'true';
|
|
193
195
|
const log = options.log ?? (() => { });
|
|
194
196
|
let sdk;
|
|
195
197
|
const loadSdk = () => {
|
|
@@ -295,14 +297,17 @@ export function claudeCodeHarness(options = {}) {
|
|
|
295
297
|
// The host's gate before the intent, so a refused or parked call leaves nothing of its own written. The assistant
|
|
296
298
|
// line that made the call is in the log before the gate is asked: a park ends the claim, and the resume finds the
|
|
297
299
|
// call it held dangling in the transcript, under the same id (resumeDanglingCalls, resumeDanglingSearches).
|
|
298
|
-
|
|
300
|
+
// A call a tool makes inside its own (tools_call, codemode) has the id `<tool_use id>/<key>`: no line of the
|
|
301
|
+
// transcript names it, so it waits on the line that made the call it runs inside.
|
|
302
|
+
const logged = (callId) => store.barrier(callId.split('/')[0], barrierMs);
|
|
303
|
+
const gated = gate ? async (call) => (await logged(call.callId), gate(call)) : undefined;
|
|
299
304
|
/** The WebSearch calls the gate held and a person let run that no search has taken up yet (releasedSearches, read
|
|
300
305
|
* from the transcript at the resume): the model's next search with one's input is put to the gate under its id. */
|
|
301
306
|
const released = [];
|
|
302
307
|
const bridge = toolBridge(ctx, tools, {
|
|
303
308
|
...(gated ? { gate: gated } : {}),
|
|
304
309
|
// A `never` tool runs only once the assistant entry that asked for it is in the log.
|
|
305
|
-
beforeNever: ({ callId }) =>
|
|
310
|
+
beforeNever: ({ callId }) => logged(callId),
|
|
306
311
|
});
|
|
307
312
|
// The built-ins: each call an intent before it runs, its outcome after (the hooks below).
|
|
308
313
|
const builtins = new BuiltinCalls(ctx, { replay, beforeNever: ({ callId }) => store.barrier(callId, barrierMs), live: true });
|
|
@@ -381,9 +386,9 @@ export function claudeCodeHarness(options = {}) {
|
|
|
381
386
|
return deny(`Not run: ${JSON.stringify(String(asked).slice(0, 80))} is not one of this session's skills.`);
|
|
382
387
|
return name === asked ? allow() : allow({ ...input, skill: name });
|
|
383
388
|
}
|
|
384
|
-
// WebSearch, when on, takes the built-ins' path below: its intent recorded before it runs.
|
|
385
|
-
//
|
|
386
|
-
if (!builtinsOn && !(webSearch && hook.tool_name === 'WebSearch') && !
|
|
389
|
+
// WebSearch, when on, takes the built-ins' path below: its intent recorded before it runs. So does
|
|
390
|
+
// ToolSearch with the tool search on: it reads only the CLI's list of the session's own tools.
|
|
391
|
+
if (!builtinsOn && !(webSearch && hook.tool_name === 'WebSearch') && !(toolSearch && hook.tool_name === CLAUDE_TOOL_SEARCH))
|
|
387
392
|
return deny("Not run: this session's only tools are its own.");
|
|
388
393
|
if (ctx.signal.aborted)
|
|
389
394
|
return deny('the session stopped');
|
|
@@ -493,9 +498,8 @@ export function claudeCodeHarness(options = {}) {
|
|
|
493
498
|
// A host tool's result within the host's bound reaches the model whole (each tool is listed with it, too).
|
|
494
499
|
mcpOutputTokens: MCP_OUTPUT_TOKENS,
|
|
495
500
|
});
|
|
496
|
-
//
|
|
497
|
-
|
|
498
|
-
vmEnv.ENABLE_TOOL_SEARCH = 'false';
|
|
501
|
+
// The CLI's own tool search: on with MCP servers among the session's tools, off without (claudeToolSearch).
|
|
502
|
+
vmEnv.ENABLE_TOOL_SEARCH = toolSearch ? 'true' : 'false';
|
|
499
503
|
const sdkEnv = { ...vmEnv, CLAUDE_CONFIG_DIR: configDir };
|
|
500
504
|
const disallowed = [...CLAUDE_BUILTINS_OFF, ...(providerTools.includes('web_search') ? [] : ['WebSearch']), ...(options.disallowedTools ?? [])].filter((name) => !(skills && name === 'Skill'));
|
|
501
505
|
const sessionId = uuidFrom(ctx.runId);
|
|
@@ -520,7 +524,7 @@ export function claudeCodeHarness(options = {}) {
|
|
|
520
524
|
// nothing). Once a record exists a resume sends it, whatever day it names, and a recovery's own fresh prompt is
|
|
521
525
|
// never recorded: every other day reaches the model in its turn (dateLine).
|
|
522
526
|
const now = options.now ?? (() => new Date());
|
|
523
|
-
const recordedDay = !store.hasSession ? dayOf(now()) : undefined;
|
|
527
|
+
const recordedDay = !store.hasSession ? dayOf(now(), options.zone) : undefined;
|
|
524
528
|
/** A message the CLI's transcript holds told the model `day`. */
|
|
525
529
|
const told = (day) => ctx.state().effectOrder.some((e) => e.name === DATE_EFFECT && e.input?.day === day && store.hasUser(e.key.slice(DATE_EFFECT.length + 1)));
|
|
526
530
|
const queryOptions = {
|
|
@@ -530,14 +534,14 @@ export function claudeCodeHarness(options = {}) {
|
|
|
530
534
|
// Built-ins on: the allowed ones (less those whose state the log does not carry), each let through by
|
|
531
535
|
// the PreToolUse hook once its intent is in the log. Off: the bridged tools are the only ones. Either
|
|
532
536
|
// way nothing is asked of a user, and nothing else is permitted.
|
|
533
|
-
...(allowed !== undefined ? { tools: [...allowed, ...(skills ? ['Skill'] : []), ...(webSearch && !allowed.includes('WebSearch') ? ['WebSearch'] : [])] } : {}),
|
|
537
|
+
...(allowed !== undefined ? { tools: [...allowed, ...(skills ? ['Skill'] : []), ...(webSearch && !allowed.includes('WebSearch') ? ['WebSearch'] : []), ...(toolSearch && !allowed.includes(CLAUDE_TOOL_SEARCH) ? [CLAUDE_TOOL_SEARCH] : [])] } : {}),
|
|
534
538
|
// The session's skills, from its own plugin: listed to the model and loadable, and no other.
|
|
535
539
|
...(skills ? { plugins: [{ type: 'local', path: skills.plugin }], skills: [...skills.names] } : {}),
|
|
536
540
|
disallowedTools: disallowed,
|
|
537
541
|
hooks,
|
|
538
542
|
...(ownSandbox ? { sandbox: claudeSandboxSettings(machine, sandbox.network) } : {}),
|
|
539
543
|
...(bridge.tools.length ? { mcpServers: { [MCP_SERVER]: server } } : {}),
|
|
540
|
-
allowedTools:
|
|
544
|
+
allowedTools: bridge.tools.map((t) => `mcp__${MCP_SERVER}__${t.name}`),
|
|
541
545
|
permissionMode: 'dontAsk',
|
|
542
546
|
strictMcpConfig: true,
|
|
543
547
|
// No user, project or local settings (and so no CLAUDE.md): a model-planted .claude/ on the Drive is ignored.
|
|
@@ -549,7 +553,7 @@ export function claudeCodeHarness(options = {}) {
|
|
|
549
553
|
systemPrompt: {
|
|
550
554
|
type: 'preset',
|
|
551
555
|
preset: 'claude_code',
|
|
552
|
-
append: [builtinsOn ? DRIVE_NOTE : webSearch ? WEB_SEARCH_NOTE :
|
|
556
|
+
append: [builtinsOn ? DRIVE_NOTE : webSearch ? WEB_SEARCH_NOTE : bridge.tools.length ? TOOLS_NOTE : NO_TOOLS_NOTE, skills ? SKILLS_NOTE : undefined, options.instructions, recovered].filter(Boolean).join('\n\n'),
|
|
553
557
|
snapshot: !recovered,
|
|
554
558
|
},
|
|
555
559
|
...(store.hasSession ? { resume: sessionId } : { sessionId }),
|
|
@@ -571,8 +575,6 @@ export function claudeCodeHarness(options = {}) {
|
|
|
571
575
|
};
|
|
572
576
|
const q = query({ prompt: input, options: queryOptions });
|
|
573
577
|
const messages = q[Symbol.asyncIterator]();
|
|
574
|
-
if (mcpServers.length)
|
|
575
|
-
await connectMcp(q, machine, mcpServers.map((server) => server.name), bridge.tools.length ? { [MCP_SERVER]: server } : {}, Math.max(1_000, deadline - Date.now()));
|
|
576
578
|
const send = async (text, placed, how = {}) => {
|
|
577
579
|
// The drive's first message says, once, what the sandbox told it (a lost Drive).
|
|
578
580
|
if (notes) {
|
|
@@ -600,10 +602,10 @@ export function claudeCodeHarness(options = {}) {
|
|
|
600
602
|
// The first message on a day the model was not told carries that day (dateLine), the session's recorded first
|
|
601
603
|
// day aside. Recorded under the message's uuid: the day counts as told once the transcript holds the message.
|
|
602
604
|
const at = now();
|
|
603
|
-
const day = dayOf(at);
|
|
605
|
+
const day = dayOf(at, options.zone);
|
|
604
606
|
if (!told(day)) {
|
|
605
607
|
if (day !== recordedDay)
|
|
606
|
-
text = `${dateLine(at)}\n\n${text}`;
|
|
608
|
+
text = `${dateLine(at, options.zone)}\n\n${text}`;
|
|
607
609
|
await ctx.effect(`${DATE_EFFECT}:${uuid}`, { name: DATE_EFFECT, replay: 'safe', input: { day } }, async () => day);
|
|
608
610
|
}
|
|
609
611
|
outstanding.add(uuid);
|
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
|
|
@@ -59,6 +64,8 @@ export declare function anthropicOutputAsked(body: Record<string, unknown>): num
|
|
|
59
64
|
/** The least output a Messages body may be limited to and still answer: 1,024 tokens, and with extended thinking on (a
|
|
60
65
|
* budget) the provider's least budget beside them. Adaptive thinking takes no budget, so it needs none. */
|
|
61
66
|
export declare function anthropicOutputLeast(body: Record<string, unknown>): number;
|
|
67
|
+
/** The effort a Messages body asks its model at (`output_config.effort`), when it names one. */
|
|
68
|
+
export declare function anthropicEffort(body: Record<string, unknown>): string | undefined;
|
|
62
69
|
/** The thinking tokens a Messages request may bill that its stream never shows: Claude 4-class models stream only a
|
|
63
70
|
* summary of their thinking (and a redacted block shows none of it), so a request that thinks counts its thinking
|
|
64
71
|
* budget, or its `max_tokens` when its thinking is adaptive (no budget); one with thinking off, none. A stopped request
|
|
@@ -82,23 +89,25 @@ export declare function applyAnthropic(body: unknown, route: ProxyRoute, options
|
|
|
82
89
|
export interface AnthropicUsage extends ProxyUsage {
|
|
83
90
|
webSearches?: number;
|
|
84
91
|
}
|
|
85
|
-
/** `price` with each web search a response reports added at `
|
|
92
|
+
/** `price` with each web search a response reports added at `NATIVE_SEARCH_USD`: the host prices the tokens, the
|
|
86
93
|
* searches are Anthropic's flat rate. An unknown price stays unknown. */
|
|
87
94
|
export declare function withWebSearches(price: (model: string, usage: ProxyUsage) => number | null): (model: string, usage: ProxyUsage) => number | null;
|
|
88
95
|
/** The usage a Messages response reports, read by parsing it, never by matching its text (the API nests objects in
|
|
89
96
|
* `usage`): a whole body's `usage`, or a stream's `message_start` usage (input and cache tokens) with its last
|
|
90
97
|
* `message_delta` usage over it (the final counts, the web searches among them). Each SSE `data:` line is parsed on its
|
|
91
|
-
* own and one that does not parse is skipped (the proxy keeps only the head and tail of a long answer). A stream
|
|
92
|
-
*
|
|
98
|
+
* own and one that does not parse is skipped (the proxy keeps only the head and tail of a long answer). A stream the
|
|
99
|
+
* provider ended in its `error` event (an overload, a rate limit) is whole too: the counts it reported before it, which
|
|
100
|
+
* the proxy books at list (a `message_start`'s input). A stream that never stopped, or an answer with no readable usage,
|
|
101
|
+
* is unknown. */
|
|
93
102
|
export declare function anthropicUsage(text: string): AnthropicUsage | undefined;
|
|
94
103
|
/** Whether a Messages answer ended on the provider's refusal (`stop_reason: "refusal"`, its content filter): a whole body's
|
|
95
104
|
* `stop_reason`, or a stream's last `message_delta` stop. Read by parsing, never by matching text, each SSE `data:` line
|
|
96
105
|
* on its own, as anthropicUsage reads them. */
|
|
97
106
|
export declare function anthropicFiltered(text: string): boolean;
|
|
98
107
|
/** 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
|
|
108
|
+
* 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
109
|
* 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"
|
|
110
|
+
export declare function anthropicAnswers(body: Record<string, unknown>, options: Pick<AnthropicPolicyOptions, "tools" | "builtins">): boolean;
|
|
102
111
|
/**
|
|
103
112
|
* Anthropic's own count of a Messages request's input tokens: POST /v1/messages/count_tokens, free, on api.anthropic.com
|
|
104
113
|
* 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, messagesInputAfter, messagesLocalInputTokens, 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
|
|
@@ -185,6 +196,11 @@ export function anthropicOutputAsked(body) {
|
|
|
185
196
|
export function anthropicOutputLeast(body) {
|
|
186
197
|
return isPlain(body.thinking) && body.thinking.type === "enabled" ? ANSWER_TOKENS_LEAST + THINKING_BUDGET_LEAST : ANSWER_TOKENS_LEAST;
|
|
187
198
|
}
|
|
199
|
+
/** The effort a Messages body asks its model at (`output_config.effort`), when it names one. */
|
|
200
|
+
export function anthropicEffort(body) {
|
|
201
|
+
const config = body.output_config;
|
|
202
|
+
return isPlain(config) && typeof config.effort === "string" && config.effort.length > 0 ? config.effort : undefined;
|
|
203
|
+
}
|
|
188
204
|
/** The thinking tokens a Messages request may bill that its stream never shows: Claude 4-class models stream only a
|
|
189
205
|
* summary of their thinking (and a redacted block shows none of it), so a request that thinks counts its thinking
|
|
190
206
|
* budget, or its `max_tokens` when its thinking is adaptive (no budget); one with thinking off, none. A stopped request
|
|
@@ -251,15 +267,19 @@ export function applyAnthropic(body, route, options, context = {}) {
|
|
|
251
267
|
const count = route.path === "/v1/messages/count_tokens";
|
|
252
268
|
onlyKeys(body, count ? COUNT_TOKENS_KEYS : MESSAGES_KEYS, count ? "count_tokens" : "messages");
|
|
253
269
|
outputConfig(body.output_config);
|
|
270
|
+
const own = options.tools.map((name) => `${OWN_TOOL_PREFIX}${name}`);
|
|
271
|
+
const search = options.toolSearch === true && context.host === undefined;
|
|
272
|
+
// The tools a tool search's answer may name: the session's own (a reference names no built-in).
|
|
273
|
+
const references = search ? new Set(own) : undefined;
|
|
254
274
|
if (!Array.isArray(body.messages))
|
|
255
275
|
refuse(400, "messages must be a list");
|
|
256
276
|
for (const message of body.messages) {
|
|
257
277
|
if (!isPlain(message))
|
|
258
278
|
refuse(400, "a message must be an object");
|
|
259
|
-
blocks(message.content, "a message's content");
|
|
279
|
+
blocks(message.content, "a message's content", false, references);
|
|
260
280
|
}
|
|
261
281
|
blocks(body.system, "system");
|
|
262
|
-
const allowed = context.host !== undefined ? new Set(clientToolNames(body.tools)) : new Set([...
|
|
282
|
+
const allowed = context.host !== undefined ? new Set(clientToolNames(body.tools)) : new Set([...own, ...(options.builtins ?? []), ...(search ? CLAUDE_TOOL_SEARCH_TOOLS : [])]);
|
|
263
283
|
const tools = ownTools(body.tools, allowed, options.webSearch);
|
|
264
284
|
const choice = body.tool_choice;
|
|
265
285
|
const chosen = isPlain(choice) && typeof choice.name === "string" && (allowed.has(choice.name) || (options.webSearch === true && choice.name === "web_search"));
|
|
@@ -301,20 +321,22 @@ function bookedUsage(usage) {
|
|
|
301
321
|
return undefined;
|
|
302
322
|
return { input, output, cacheRead: tokenCount(usage.cache_read_input_tokens) ?? 0, cacheWrite: tokenCount(usage.cache_creation_input_tokens) ?? 0, ...(webSearches ? { webSearches } : {}) };
|
|
303
323
|
}
|
|
304
|
-
/** `price` with each web search a response reports added at `
|
|
324
|
+
/** `price` with each web search a response reports added at `NATIVE_SEARCH_USD`: the host prices the tokens, the
|
|
305
325
|
* searches are Anthropic's flat rate. An unknown price stays unknown. */
|
|
306
326
|
export function withWebSearches(price) {
|
|
307
327
|
return (model, usage) => {
|
|
308
328
|
const usd = price(model, usage);
|
|
309
329
|
const count = usage.webSearches ?? 0;
|
|
310
|
-
return usd === null || count === 0 ? usd : usd + count *
|
|
330
|
+
return usd === null || count === 0 ? usd : usd + count * NATIVE_SEARCH_USD;
|
|
311
331
|
};
|
|
312
332
|
}
|
|
313
333
|
/** The usage a Messages response reports, read by parsing it, never by matching its text (the API nests objects in
|
|
314
334
|
* `usage`): a whole body's `usage`, or a stream's `message_start` usage (input and cache tokens) with its last
|
|
315
335
|
* `message_delta` usage over it (the final counts, the web searches among them). Each SSE `data:` line is parsed on its
|
|
316
|
-
* own and one that does not parse is skipped (the proxy keeps only the head and tail of a long answer). A stream
|
|
317
|
-
*
|
|
336
|
+
* own and one that does not parse is skipped (the proxy keeps only the head and tail of a long answer). A stream the
|
|
337
|
+
* provider ended in its `error` event (an overload, a rate limit) is whole too: the counts it reported before it, which
|
|
338
|
+
* the proxy books at list (a `message_start`'s input). A stream that never stopped, or an answer with no readable usage,
|
|
339
|
+
* is unknown. */
|
|
318
340
|
export function anthropicUsage(text) {
|
|
319
341
|
const lines = text.split(/\r?\n/);
|
|
320
342
|
if (!lines.some((line) => line.startsWith("data:") || line.startsWith("event:"))) {
|
|
@@ -338,7 +360,7 @@ export function anthropicUsage(text) {
|
|
|
338
360
|
}
|
|
339
361
|
catch { /* cut at the kept window's edge, or not JSON: skipped */ }
|
|
340
362
|
}
|
|
341
|
-
if (!events.some((e) => e.type === "message_stop"))
|
|
363
|
+
if (!events.some((e) => e.type === "message_stop" || e.type === "error"))
|
|
342
364
|
return undefined;
|
|
343
365
|
const started = events.find((e) => e.type === "message_start")?.message;
|
|
344
366
|
const startUsage = isPlain(started) && isPlain(started.usage) ? started.usage : {};
|
|
@@ -374,10 +396,10 @@ export function anthropicFiltered(text) {
|
|
|
374
396
|
return stop === "refusal";
|
|
375
397
|
}
|
|
376
398
|
/** 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
|
|
399
|
+
* 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
400
|
* 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
401
|
export function anthropicAnswers(body, options) {
|
|
380
|
-
const allowed = new Set([...options.tools.map((name) => `${OWN_TOOL_PREFIX}${name}`), ...(options.builtins ?? [])
|
|
402
|
+
const allowed = new Set([...options.tools.map((name) => `${OWN_TOOL_PREFIX}${name}`), ...(options.builtins ?? [])]);
|
|
381
403
|
if (allowed.size === 0)
|
|
382
404
|
return true;
|
|
383
405
|
return Array.isArray(body.tools) && body.tools.some((tool) => isPlain(tool) && typeof tool.name === "string" && allowed.has(tool.name));
|
|
@@ -459,7 +481,7 @@ export function anthropicPolicy(options) {
|
|
|
459
481
|
header: (name, value) => {
|
|
460
482
|
if (name !== "anthropic-beta")
|
|
461
483
|
return value;
|
|
462
|
-
const unknown = value.split(",").map((v) => v.trim()).filter((v) => v && !CLAUDE_BETAS.has(v));
|
|
484
|
+
const unknown = value.split(",").map((v) => v.trim()).filter((v) => v && !CLAUDE_BETAS.has(v) && !(options.toolSearch === true && v === CLAUDE_TOOL_SEARCH_BETA));
|
|
463
485
|
if (unknown.length)
|
|
464
486
|
refuse(403, "an anthropic-beta value is not one the pinned CLI sends");
|
|
465
487
|
return value;
|
|
@@ -470,7 +492,17 @@ export function anthropicPolicy(options) {
|
|
|
470
492
|
serverInputOverhead: options.webSearchAllowance === undefined ? anthropicServerInputOverhead : (body) => anthropicServerInputOverhead(body, options.webSearchAllowance),
|
|
471
493
|
outputAsked: anthropicOutputAsked,
|
|
472
494
|
countInput: ANTHROPIC_INPUT_COUNTER,
|
|
495
|
+
// A request Anthropic does not count (a gateway, serve's translation to a model of another API): a model whose
|
|
496
|
+
// tokenizer is o200k_base is counted locally with its stated margin (pi on gpt-6.1-sol through OpenRouter, whose
|
|
497
|
+
// bytes would bound it at four times its tokens and, past 272,000, at the long-context price). A Claude model, a body
|
|
498
|
+
// with a document, or one offering the hosted search (its allowance is part of the byte bound) keeps the byte bound.
|
|
499
|
+
countInputLocally: (body) => (offersWebSearch(body) ? undefined : messagesLocalInputTokens(body)),
|
|
500
|
+
// A request that carries the session's earlier one its provider billed: that bill and the bytes it adds, on any model
|
|
501
|
+
// (Claude through OpenRouter, which counts nothing, held at its bytes four times what it bills). Not with the hosted
|
|
502
|
+
// search offered: what its searches read in has no bound.
|
|
503
|
+
inputAfter: (earlier, body) => (offersWebSearch(body) ? undefined : messagesInputAfter(earlier, body)),
|
|
473
504
|
outputLeast: anthropicOutputLeast,
|
|
505
|
+
effortOf: anthropicEffort,
|
|
474
506
|
reasoningHidden: anthropicReasoningHidden,
|
|
475
507
|
reasoningBytesOf: anthropicReasoningBytes,
|
|
476
508
|
contentBytesOf: anthropicContentBytes,
|
|
@@ -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
|
@@ -2,9 +2,9 @@ export { CLAUDE_AGENT_ALSO_OFF, CLAUDE_AGENT_CLI_SKILL_NAMES, CLAUDE_AGENT_DIGES
|
|
|
2
2
|
export { CLAUDE_AGENT_PACKAGE, ClaudeAgentNotInstalled, ClaudeAgentPinMismatch, ClaudeAgentThinkingOff } from "./errors.js";
|
|
3
3
|
export type { ClaudeAgentPin } from "./errors.js";
|
|
4
4
|
export type { ClaudeAgentAdapterOptions, ClaudeAgentProvider, ClaudeAgentSkill, ClaudeAgentThinking } from "./adapter.js";
|
|
5
|
-
export { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_CODE_VERSION as CLAUDE_AGENT_CLI_VERSION } from "./versions.js";
|
|
5
|
+
export { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_AGENT_BASE_INPUT_TOKENS, 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
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// The Claude Agent SDK as an AgentRun harness adapter (id `claude-agent`). Written for AgentRun.
|
|
2
2
|
export { CLAUDE_AGENT_ALSO_OFF, CLAUDE_AGENT_CLI_SKILL_NAMES, CLAUDE_AGENT_DIGESTS, CLAUDE_AGENT_ID, CLAUDE_AGENT_MAX_IMAGE_BYTES, CLAUDE_AGENT_SKILLS_PLUGIN, claudeAgentAdapter, claudeAgentCliPins, skillProblems, thinkingOf, toolImageProblems, verifyClaudeAgent, verifyClaudeAgentCli, verifyClaudeAgentCliAsync } from "./adapter.js";
|
|
3
3
|
export { CLAUDE_AGENT_PACKAGE, ClaudeAgentNotInstalled, ClaudeAgentPinMismatch, ClaudeAgentThinkingOff } from "./errors.js";
|
|
4
|
-
export { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_CODE_VERSION as CLAUDE_AGENT_CLI_VERSION } from "./versions.js";
|
|
4
|
+
export { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_AGENT_BASE_INPUT_TOKENS, 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
|
@@ -44,8 +44,9 @@ export declare function releasedSearches(lines: readonly TranscriptLine[]): {
|
|
|
44
44
|
*/
|
|
45
45
|
export declare function resultLine(lines: readonly TranscriptLine[], call: DanglingCall, outcome: CallOutcome): TranscriptLine;
|
|
46
46
|
/**
|
|
47
|
-
* Before the CLI resumes the transcript: each dangling host-tool call that never started runs through `bridge`, and
|
|
48
|
-
*
|
|
49
|
-
*
|
|
47
|
+
* Before the CLI resumes the transcript: each dangling host-tool call that never started runs through `bridge`, and each
|
|
48
|
+
* one that ended before the CLI wrote its result is read back through it (the journal's result: nothing runs again);
|
|
49
|
+
* either result is written into the transcript and committed, so the CLI starts again past it. A gate that parks rejects
|
|
50
|
+
* out of here with nothing written, and the call keeps the id the model gave it.
|
|
50
51
|
*/
|
|
51
52
|
export declare function resumeDanglingCalls(ctx: DriveContext, bridge: ToolBridge, store: JournalSessionStore): Promise<void>;
|
package/dist/resume.js
CHANGED
|
@@ -122,9 +122,10 @@ export function resultLine(lines, call, outcome) {
|
|
|
122
122
|
};
|
|
123
123
|
}
|
|
124
124
|
/**
|
|
125
|
-
* Before the CLI resumes the transcript: each dangling host-tool call that never started runs through `bridge`, and
|
|
126
|
-
*
|
|
127
|
-
*
|
|
125
|
+
* Before the CLI resumes the transcript: each dangling host-tool call that never started runs through `bridge`, and each
|
|
126
|
+
* one that ended before the CLI wrote its result is read back through it (the journal's result: nothing runs again);
|
|
127
|
+
* either result is written into the transcript and committed, so the CLI starts again past it. A gate that parks rejects
|
|
128
|
+
* out of here with nothing written, and the call keeps the id the model gave it.
|
|
128
129
|
*/
|
|
129
130
|
export async function resumeDanglingCalls(ctx, bridge, store) {
|
|
130
131
|
const dangling = danglingCalls(store.lines());
|
|
@@ -43,6 +43,15 @@ export type FakeReply = ({
|
|
|
43
43
|
};
|
|
44
44
|
text?: string;
|
|
45
45
|
} & Thought)
|
|
46
|
+
/** Several calls in one answer, in this order (the model's parallel calls). */
|
|
47
|
+
| ({
|
|
48
|
+
tools: {
|
|
49
|
+
name: string;
|
|
50
|
+
input: unknown;
|
|
51
|
+
id?: string;
|
|
52
|
+
}[];
|
|
53
|
+
text?: string;
|
|
54
|
+
} & Thought)
|
|
46
55
|
/** The provider's own web search (the answer to a request with its web search tool): its call and results, then
|
|
47
56
|
* `text`, with `searches` (default 1) in `usage.server_tool_use.web_search_requests`. */
|
|
48
57
|
| {
|
|
@@ -206,15 +206,16 @@ export async function fakeAnthropic(options) {
|
|
|
206
206
|
blocks.push({ type: 'redacted_thinking', data: reply.redacted });
|
|
207
207
|
if ('text' in reply && reply.text)
|
|
208
208
|
blocks.push({ type: 'text', text: reply.text });
|
|
209
|
-
|
|
210
|
-
|
|
209
|
+
const calls = 'tool' in reply ? [reply.tool] : 'tools' in reply ? reply.tools : [];
|
|
210
|
+
for (const call of calls)
|
|
211
|
+
blocks.push({ type: 'tool_use', id: call.id ?? `toolu_fake_${String(++toolSeq).padStart(4, '0')}_${Date.now().toString(36)}`, name: call.name, input: call.input });
|
|
211
212
|
if ('search' in reply) {
|
|
212
213
|
const id = `srvtoolu_fake_${String(++toolSeq).padStart(4, '0')}`;
|
|
213
214
|
blocks.push({ type: 'server_tool_use', id, name: 'web_search', input: { query: reply.search.query } });
|
|
214
215
|
blocks.push({ type: 'web_search_tool_result', tool_use_id: id, content: reply.search.results.map((r) => ({ type: 'web_search_result', title: r.title, url: r.url, encrypted_content: 'ZmFrZQ==', page_age: null })) });
|
|
215
216
|
blocks.push({ type: 'text', text: reply.search.text });
|
|
216
217
|
}
|
|
217
|
-
const stopReason =
|
|
218
|
+
const stopReason = calls.length ? 'tool_use' : 'end_turn';
|
|
218
219
|
// The real API's shape, nested objects included (a recorded response is in test/fixtures/).
|
|
219
220
|
const searched = 'search' in reply ? { server_tool_use: { web_search_requests: reply.search.searches ?? 1 } } : {};
|
|
220
221
|
const usage = { input_tokens: Math.ceil(text.length / 4), cache_creation_input_tokens: 0, cache_read_input_tokens: 0, cache_creation: { ephemeral_5m_input_tokens: 0, ephemeral_1h_input_tokens: 0 }, output_tokens: 12, output_tokens_details: { thinking_tokens: 0 }, service_tier: 'standard', ...searched };
|
package/dist/versions.d.ts
CHANGED
|
@@ -12,6 +12,15 @@ import { Unavailable } from './host/kernel.js';
|
|
|
12
12
|
export declare const CLAUDE_AGENT_SDK_VERSION = "0.3.286";
|
|
13
13
|
/** The Claude Code CLI the pinned SDK release bundles (its package.json's `claudeCodeVersion`), installed in the VM image. */
|
|
14
14
|
export declare const CLAUDE_CODE_VERSION = "2.1.286";
|
|
15
|
+
/**
|
|
16
|
+
* The input tokens the pinned CLI (2.1.286, from Agent SDK 0.3.286) sends in its first model request before the
|
|
17
|
+
* agent's own prompt: its system prompt, with no tool of its own (the harness turns its built-ins off). Counted with
|
|
18
|
+
* o200k_base on the first request the pinned CLI sent to a scripted provider, 786 tokens (less the line it adds when a
|
|
19
|
+
* session has no tool at all), stated at 780 so a line it words differently on another machine never puts it over
|
|
20
|
+
* (test/tool-off.test.mjs keeps it at or under that count). Claude bills by its own tokenizer; this is o200k_base's count
|
|
21
|
+
* of the same text. The facts' `baseInputTokens`: a save under a cap prices a least step on it.
|
|
22
|
+
*/
|
|
23
|
+
export declare const CLAUDE_AGENT_BASE_INPUT_TOKENS = 780;
|
|
15
24
|
/** Where the pinned CLI is in a session VM booted from the base (harness-world-sandbox's `CLAUDE_CLI`). */
|
|
16
25
|
export declare const CLAUDE_VM_EXECUTABLE = "/opt/dh/claude/2.1.286/claude";
|
|
17
26
|
/** The install line for the pinned SDK. */
|
package/dist/versions.js
CHANGED
|
@@ -18,6 +18,15 @@ import { Unavailable } from './host/kernel.js';
|
|
|
18
18
|
export const CLAUDE_AGENT_SDK_VERSION = '0.3.286';
|
|
19
19
|
/** The Claude Code CLI the pinned SDK release bundles (its package.json's `claudeCodeVersion`), installed in the VM image. */
|
|
20
20
|
export const CLAUDE_CODE_VERSION = '2.1.286';
|
|
21
|
+
/**
|
|
22
|
+
* The input tokens the pinned CLI (2.1.286, from Agent SDK 0.3.286) sends in its first model request before the
|
|
23
|
+
* agent's own prompt: its system prompt, with no tool of its own (the harness turns its built-ins off). Counted with
|
|
24
|
+
* o200k_base on the first request the pinned CLI sent to a scripted provider, 786 tokens (less the line it adds when a
|
|
25
|
+
* session has no tool at all), stated at 780 so a line it words differently on another machine never puts it over
|
|
26
|
+
* (test/tool-off.test.mjs keeps it at or under that count). Claude bills by its own tokenizer; this is o200k_base's count
|
|
27
|
+
* of the same text. The facts' `baseInputTokens`: a save under a cap prices a least step on it.
|
|
28
|
+
*/
|
|
29
|
+
export const CLAUDE_AGENT_BASE_INPUT_TOKENS = 780;
|
|
21
30
|
/** Where the pinned CLI is in a session VM booted from the base (harness-world-sandbox's `CLAUDE_CLI`). */
|
|
22
31
|
export const CLAUDE_VM_EXECUTABLE = `/opt/dh/claude/${CLAUDE_CODE_VERSION}/claude`;
|
|
23
32
|
/** The install line for the pinned SDK. */
|
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.39",
|
|
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.39"
|
|
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.39"
|
|
81
81
|
}
|
|
82
82
|
}
|