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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +4 -0
  4. package/README.md +56 -2
  5. package/dist/adapter.d.ts +123 -0
  6. package/dist/adapter.js +487 -0
  7. package/dist/binary.d.ts +25 -0
  8. package/dist/binary.js +71 -0
  9. package/dist/cli-names.d.ts +7 -0
  10. package/dist/cli-names.js +17 -0
  11. package/dist/env.d.ts +81 -0
  12. package/dist/env.js +92 -0
  13. package/dist/errors.d.ts +27 -0
  14. package/dist/errors.js +42 -0
  15. package/dist/harness.d.ts +287 -0
  16. package/dist/harness.js +881 -0
  17. package/dist/host/kernel.d.ts +10 -0
  18. package/dist/host/kernel.js +1 -0
  19. package/dist/host/machine.d.ts +77 -0
  20. package/dist/host/machine.js +259 -0
  21. package/dist/host/policy.d.ts +85 -0
  22. package/dist/host/policy.js +359 -0
  23. package/dist/host/process.d.ts +130 -0
  24. package/dist/host/process.js +31 -0
  25. package/dist/host/tool-server.d.ts +44 -0
  26. package/dist/host/tool-server.js +47 -0
  27. package/dist/ids.d.ts +9 -0
  28. package/dist/ids.js +17 -0
  29. package/dist/inbox.d.ts +14 -0
  30. package/dist/inbox.js +36 -0
  31. package/dist/index.d.ts +11 -0
  32. package/dist/index.js +7 -0
  33. package/dist/serial.d.ts +3 -0
  34. package/dist/serial.js +10 -0
  35. package/dist/spawn.d.ts +51 -0
  36. package/dist/spawn.js +131 -0
  37. package/dist/store.d.ts +119 -0
  38. package/dist/store.js +202 -0
  39. package/dist/testing/fake-anthropic.d.ts +97 -0
  40. package/dist/testing/fake-anthropic.js +279 -0
  41. package/dist/testing/fake-sdk.d.ts +60 -0
  42. package/dist/testing/fake-sdk.js +402 -0
  43. package/dist/testing/index.d.ts +3 -0
  44. package/dist/testing/index.js +5 -0
  45. package/dist/transcript.d.ts +73 -0
  46. package/dist/transcript.js +116 -0
  47. package/dist/versions.d.ts +34 -0
  48. package/dist/versions.js +76 -0
  49. package/package.json +76 -4
  50. package/vendor/durable-harness/UPSTREAM.json +59 -0
@@ -0,0 +1,10 @@
1
+ export type { DriveContext, EffectRecord, HostTool, ReplayPolicy, SessionState, Submission } from "@parcha/agentrun-kernel/kernel";
2
+ export { Restart, Unavailable } from "@parcha/agentrun-kernel/kernel";
3
+ import type { DriveContext } from "@parcha/agentrun-kernel/kernel";
4
+ /** A harness: one drive runs its pending input to the end, then returns. */
5
+ export interface Harness {
6
+ name: string;
7
+ /** Who reports model calls: the harness itself (its model proxy), or the kernel. */
8
+ modelCalls?: "effects" | "self";
9
+ drive(ctx: DriveContext): Promise<void>;
10
+ }
@@ -0,0 +1 @@
1
+ export { Restart, Unavailable } from "@parcha/agentrun-kernel/kernel";
@@ -0,0 +1,77 @@
1
+ import { type ChildProcess } from "node:child_process";
2
+ import { type ModelProxyHooks, type ModelProxyOptions, type ParentWatch } from "@parcha/agentrun-kernel/host";
3
+ import type { AcquireMachine, MachineSpawn, SessionMachine, SessionProcess } from "./process.js";
4
+ import { type AnthropicPolicyOptions } from "./policy.js";
5
+ /** The variables a child takes from this process, when they are set. */
6
+ export declare const INHERITED_ENV: readonly ["PATH", "LANG", "TZ"];
7
+ /** A command and its arguments, as the machine starts it. */
8
+ export interface ChildCommand {
9
+ command: string;
10
+ args: string[];
11
+ }
12
+ /** The host's confinement of a child: the same command and arguments, started under the host's own (a
13
+ * `setpriv --no-new-privs` prefix, say). It may only add in front: what it returns must end with the command and its
14
+ * arguments unchanged, and it never sees or changes the child's environment. The prefix must exec the child in place
15
+ * (as setpriv does): a wrapper that forks and stays as the child's parent defeats the parent watch, since the death
16
+ * signal then follows the wrapper, not this process. */
17
+ export type ConfineChild = (child: Readonly<ChildCommand>) => ChildCommand;
18
+ export interface LocalMachineOptions {
19
+ /** The session's own directory. The machine makes its private directories in it. */
20
+ dir: string;
21
+ /** The CLI's working directory: the host's workspace (absolute), where its file tools confine. Default `<dir>/work`. */
22
+ cwd?: string;
23
+ /** Start every child of the session (the CLI) under the host's confinement. */
24
+ confine?: ConfineChild;
25
+ /** How a child is tied to this process (default what the machine supports; tests force the shim). */
26
+ parentWatch?: ParentWatch;
27
+ /** The model proxy: the runner's hooks, the provider's price, and the session's tools and limits. */
28
+ proxy: {
29
+ hooks: ModelProxyHooks;
30
+ tools: readonly string[];
31
+ /** The CLI's own tools the session has (`Skill`, with skills; `WebSearch`), offered beside its tools. */
32
+ builtins?: readonly string[];
33
+ /** Admit Anthropic's web search server tool, the one the CLI's WebSearch asks for. */
34
+ webSearch?: boolean;
35
+ /** The input a request carrying it may read in beyond its body, for its input bound (anthropicPolicy). */
36
+ webSearchAllowance?: number;
37
+ /** The tokens' price; each web search a response reports is added to it (`withWebSearches`). */
38
+ price?: ModelProxyOptions["price"];
39
+ maxOutputTokens?: number;
40
+ auth?: AnthropicPolicyOptions["auth"];
41
+ /** Headers the host adds to every forwarded request (a gateway's spend tags). */
42
+ headers?: ModelProxyOptions["headers"];
43
+ log?: ModelProxyOptions["log"];
44
+ fetch?: typeof fetch;
45
+ };
46
+ /** For tests: the process environment the allowlist reads. Default `process.env`. */
47
+ env?: Readonly<Record<string, string | undefined>>;
48
+ }
49
+ /** The child's environment: the allowlist from `from`, then what the caller names. */
50
+ export declare function childEnv(from: Readonly<Record<string, string | undefined>>, extra?: Readonly<Record<string, string>>): Record<string, string>;
51
+ /** A machine's child: started detached (its own process group), with the allowlisted environment. */
52
+ export interface MachineChild extends SessionProcess {
53
+ readonly child: ChildProcess;
54
+ }
55
+ /** The command `confine` makes of `child`, refused unless it ends with the child's command and arguments unchanged. */
56
+ export declare function confined(child: ChildCommand, confine: ConfineChild | undefined): ChildCommand;
57
+ /** The command a child is started with: the child, watched by this process (it dies with it), under the host's
58
+ * confinement. The watch is inside the confinement, so it is set after any switch of user the prefix makes. */
59
+ export declare function launchCommand(child: ChildCommand, confine: ConfineChild | undefined, watch?: ParentWatch): ChildCommand;
60
+ /** Start a child of the session: `env` beyond the allowlist, in its own process group, killed whole, and ended when
61
+ * this process ends. Its git stops at `ceiling` (the session's directory): it never looks for a repository above the
62
+ * session, in a parent the model could write. */
63
+ export declare function startChild(options: MachineSpawn, from: Readonly<Record<string, string | undefined>>, cwd: string, ceiling?: string, confine?: ConfineChild, watch?: ParentWatch): MachineChild;
64
+ /** A local machine also lets its spawner adopt a child it started itself (the CLI, through the SDK's spawn hook). */
65
+ export interface LocalSessionMachine extends SessionMachine {
66
+ /** The environment the allowlist reads. */
67
+ readonly from: Readonly<Record<string, string | undefined>>;
68
+ /** Start a child of the session, ended with it. */
69
+ start(options: MachineSpawn): MachineChild;
70
+ }
71
+ /** A machine factory for sessions under `options.dir`: each acquire makes the directories and starts a proxy. */
72
+ export declare function localMachine(options: LocalMachineOptions): AcquireMachine;
73
+ /** The provider's words in a 401's body: its error's message (Anthropic's `{error: {message}}`, OpenRouter's too), a
74
+ * string `error`, or a top-level `message`; a body that is no JSON, its text; a cut body, its message if that much came.
75
+ * Never JSON itself: a body with no string message says nothing, and the run's error is the plain refused-key words.
76
+ * The first line, with no control character (C0 or C1), at most 200 characters. */
77
+ export declare function refusalDetail(text: string): string;
@@ -0,0 +1,259 @@
1
+ // The local session machine, written for AgentRun: where a session's Claude Agent CLI runs when the host runs it on its
2
+ // own box (an operator's machine, or a sandbox box the host runs in). Nothing here assumes where that is:
3
+ // - the session gets private directories under its own directory (home, config, tmp, cache; mode 0700). Its working
4
+ // directory is the host's workspace when the host names one (`cwd`), where the host's file tools write, and otherwise
5
+ // an empty one of its own (`work`). The CLI keeps nothing there: its state is in the private directories;
6
+ // - a child's environment is an allowlist: PATH, LANG and TZ from this process, plus what the harness names (its
7
+ // homes, and the per-session proxy key). Nothing else is inherited, so no provider key, token, sign-in or another
8
+ // session's state reaches it;
9
+ // - each child runs in its own process group, which kill() and close() end whole, and dies with this process: started
10
+ // with a watch on its parent (./host's parentWatched, inside the host's confinement), so a host that is SIGKILLed,
11
+ // and runs no close, leaves no CLI behind;
12
+ // - the model proxy (@parcha/agentrun-kernel/host, with the Anthropic policy) starts with the machine and stops with it.
13
+ import { spawn as spawnChild } from "node:child_process";
14
+ import { randomBytes } from "node:crypto";
15
+ import { mkdirSync } from "node:fs";
16
+ import { dirname, isAbsolute, join, normalize, sep } from "node:path";
17
+ import { parentWatched, startModelProxy } from "@parcha/agentrun-kernel/host";
18
+ import { brandMachine } from "./process.js";
19
+ import { anthropicPolicy, withWebSearches } from "./policy.js";
20
+ /** The variables a child takes from this process, when they are set. */
21
+ export const INHERITED_ENV = Object.freeze(["PATH", "LANG", "TZ"]);
22
+ const DIRS = ["home", "config", "tmp", "cache"];
23
+ const STDERR_TAIL = 8 * 1024;
24
+ /** The child's environment: the allowlist from `from`, then what the caller names. */
25
+ export function childEnv(from, extra = {}) {
26
+ const env = {};
27
+ for (const name of INHERITED_ENV) {
28
+ const value = from[name];
29
+ if (typeof value === "string")
30
+ env[name] = value;
31
+ }
32
+ return { ...env, ...extra };
33
+ }
34
+ /** The command `confine` makes of `child`, refused unless it ends with the child's command and arguments unchanged. */
35
+ export function confined(child, confine) {
36
+ if (!confine)
37
+ return child;
38
+ const out = confine({ command: child.command, args: [...child.args] });
39
+ const argv = [out?.command, ...(Array.isArray(out?.args) ? out.args : [])];
40
+ const tail = argv.slice(argv.length - child.args.length - 1);
41
+ const kept = argv.length > child.args.length + 1 && tail.length === child.args.length + 1 && tail.every((a, i) => a === (i === 0 ? child.command : child.args[i - 1]));
42
+ if (typeof out?.command !== "string" || !argv.every((a) => typeof a === "string") || !kept)
43
+ throw new Error("agentrun-harness-claude: the host's confinement must start the child's own command and arguments, after its own");
44
+ return { command: out.command, args: out.args };
45
+ }
46
+ /** The command a child is started with: the child, watched by this process (it dies with it), under the host's
47
+ * confinement. The watch is inside the confinement, so it is set after any switch of user the prefix makes. */
48
+ export function launchCommand(child, confine, watch) {
49
+ return confined(parentWatched(child, watch), confine);
50
+ }
51
+ /** Start a child of the session: `env` beyond the allowlist, in its own process group, killed whole, and ended when
52
+ * this process ends. Its git stops at `ceiling` (the session's directory): it never looks for a repository above the
53
+ * session, in a parent the model could write. */
54
+ export function startChild(options, from, cwd, ceiling, confine, watch) {
55
+ const run = launchCommand({ command: options.command, args: options.args ?? [] }, confine, watch);
56
+ const child = spawnChild(run.command, run.args, {
57
+ cwd: options.cwd ?? cwd,
58
+ env: { ...childEnv(from, options.env), ...(ceiling ? { GIT_CEILING_DIRECTORIES: ceiling } : {}) },
59
+ detached: true,
60
+ stdio: ["pipe", "pipe", "pipe"],
61
+ });
62
+ let stderr = "";
63
+ child.stderr.setEncoding("utf8");
64
+ child.stderr.on("data", (chunk) => {
65
+ stderr = (stderr + chunk).slice(-STDERR_TAIL);
66
+ });
67
+ child.stdin.on("error", () => { });
68
+ let done = false;
69
+ const exited = new Promise((resolve) => {
70
+ child.once("error", (err) => {
71
+ stderr = (stderr + `\n${String(err.message)}`).slice(-STDERR_TAIL);
72
+ done = true;
73
+ resolve({ code: null, signal: null });
74
+ });
75
+ child.once("close", (code, signal) => {
76
+ done = true;
77
+ resolve({ code, signal });
78
+ });
79
+ });
80
+ const kill = (signal = "SIGTERM") => {
81
+ if (done || child.pid === undefined)
82
+ return;
83
+ try {
84
+ process.kill(-child.pid, signal);
85
+ }
86
+ catch {
87
+ try {
88
+ child.kill(signal);
89
+ }
90
+ catch { /* gone */ }
91
+ }
92
+ };
93
+ if (options.signal) {
94
+ if (options.signal.aborted)
95
+ kill("SIGKILL");
96
+ else
97
+ options.signal.addEventListener("abort", () => kill("SIGKILL"), { once: true });
98
+ }
99
+ return { child, exited, stderrTail: () => stderr, alive: () => !done, kill };
100
+ }
101
+ /** Whether `path` is `base` or below it. */
102
+ const inside = (path, base) => path === base || path.startsWith(base + sep);
103
+ /** A machine factory for sessions under `options.dir`: each acquire makes the directories and starts a proxy. */
104
+ export function localMachine(options) {
105
+ const from = options.env ?? process.env;
106
+ return async ({ ctx, model }) => {
107
+ if (!model)
108
+ throw new Error("agentrun-harness-claude: the harness gave the machine no model route");
109
+ const base = normalize(options.dir);
110
+ if (!isAbsolute(base))
111
+ throw new Error("agentrun-harness-claude: the session directory must be an absolute path");
112
+ mkdirSync(base, { recursive: true, mode: 0o700 });
113
+ const dirs = Object.fromEntries(DIRS.map((d) => [d, join(base, d)]));
114
+ if (options.cwd !== undefined && !isAbsolute(options.cwd))
115
+ throw new Error("agentrun-harness-claude: the working directory must be an absolute path");
116
+ const root = options.cwd === undefined ? join(base, "work") : normalize(options.cwd);
117
+ for (const dir of [...Object.values(dirs), root])
118
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
119
+ // git stops at the session's directory and, for a workspace outside it, at the workspace's parent.
120
+ const ceiling = [base, ...(inside(root, base) ? [] : [dirname(root)])].join(":");
121
+ const route = model.options;
122
+ const key = randomBytes(32).toString("base64url");
123
+ // What the provider does with a token count (a free route it may not serve), said once per session, a status only.
124
+ let counted = false;
125
+ // Whether the provider has refused the session's key (one paid 401): said once.
126
+ let refused = false;
127
+ const proxy = await startModelProxy({
128
+ policy: anthropicPolicy({
129
+ model: route.models.model,
130
+ ...(route.models.smallModel ? { smallModel: route.models.smallModel } : {}),
131
+ tools: options.proxy.tools,
132
+ ...(options.proxy.builtins?.length ? { builtins: options.proxy.builtins } : {}),
133
+ ...(options.proxy.maxOutputTokens ? { maxOutputTokens: options.proxy.maxOutputTokens } : {}),
134
+ ...(options.proxy.webSearch ? { webSearch: true, ...(options.proxy.webSearchAllowance !== undefined ? { webSearchAllowance: options.proxy.webSearchAllowance } : {}) } : {}),
135
+ ...(options.proxy.auth ? { auth: options.proxy.auth } : {}),
136
+ onThinkingDisabled: ({ model: main }) => options.proxy.log?.("claude-agent: thinking.disabled", { model: main }),
137
+ }),
138
+ hooks: options.proxy.hooks,
139
+ model: route.models.model,
140
+ origin: route.target,
141
+ credential: async () => (await route.credential()) ?? "",
142
+ ...(options.proxy.price ? { price: withWebSearches(options.proxy.price) } : {}),
143
+ ...(options.proxy.headers ? { headers: options.proxy.headers } : {}),
144
+ ...(options.proxy.log ? { log: options.proxy.log } : {}),
145
+ onResponse: ({ path, status }) => {
146
+ if (path !== "/v1/messages/count_tokens" || counted)
147
+ return;
148
+ counted = true;
149
+ options.proxy.log?.("claude-agent: the provider answered count_tokens", { status });
150
+ },
151
+ fetch: async (input, init) => {
152
+ const answer = await (options.proxy.fetch ?? fetch)(input, init);
153
+ // A paid request the provider answers 401 is the key refused: said to the harness once, with the provider's words
154
+ // (what of its body comes within REFUSAL_WAIT_MS, never waiting on one that does not end).
155
+ if (answer.status === 401 && route.onKeyRefused && !refused && new URL(String(input instanceof Request ? input.url : input)).pathname.endsWith("/v1/messages")) {
156
+ refused = true;
157
+ route.onKeyRefused(refusalDetail(await bodyStart(answer)));
158
+ }
159
+ return answer;
160
+ },
161
+ }, key);
162
+ const lost = new AbortController();
163
+ const children = new Set();
164
+ let closed = false;
165
+ const start = (spawnOptions) => {
166
+ if (closed)
167
+ throw new Error("agentrun-harness-claude: the session machine is closed");
168
+ const proc = startChild(spawnOptions, from, root, ceiling, options.confine, options.parentWatch);
169
+ children.add(proc);
170
+ void proc.exited.then(() => children.delete(proc));
171
+ return proc;
172
+ };
173
+ const machine = {
174
+ sessionId: ctx.runId,
175
+ root,
176
+ dirs,
177
+ signal: lost.signal,
178
+ modelUrl: proxy.url,
179
+ modelKey: key,
180
+ notes: [],
181
+ from,
182
+ start,
183
+ spawn: async (spawnOptions) => start(spawnOptions),
184
+ // A session with its built-ins off writes no files of its own to flush.
185
+ fsync: async () => { },
186
+ close: async () => {
187
+ if (closed)
188
+ return;
189
+ closed = true;
190
+ for (const proc of children)
191
+ proc.kill("SIGKILL");
192
+ await Promise.all([...children].map((p) => p.exited));
193
+ lost.abort();
194
+ await proxy.close();
195
+ },
196
+ };
197
+ return brandMachine(machine);
198
+ };
199
+ }
200
+ /** A JSON string's body as JSON reads it, from a capture that a cut may have ended mid-escape (a lone backslash, or a
201
+ * \\u with fewer than four digits, is dropped); the capture as it came if it still does not read. */
202
+ function jsonString(body) {
203
+ const whole = body.replace(/((?:^|[^\\])(?:\\\\)*)\\(?:u[0-9a-fA-F]{0,3})?$/, "$1");
204
+ try {
205
+ return JSON.parse(`"${whole}"`);
206
+ }
207
+ catch {
208
+ return whole;
209
+ }
210
+ }
211
+ /** How much of a refusal's body is read for its words, and how long it is waited for: the turn ends either way. */
212
+ const REFUSAL_BYTES = 4096;
213
+ const REFUSAL_WAIT_MS = 2000;
214
+ /** The start of `answer`'s body, from a copy (the client still reads the original whole): at most REFUSAL_BYTES, and
215
+ * what came within REFUSAL_WAIT_MS. */
216
+ async function bodyStart(answer) {
217
+ const reader = answer.clone().body?.getReader();
218
+ if (!reader)
219
+ return "";
220
+ const decoder = new TextDecoder();
221
+ let text = "";
222
+ let timer;
223
+ const waited = new Promise((resolve) => (timer = setTimeout(resolve, REFUSAL_WAIT_MS, undefined)));
224
+ try {
225
+ while (text.length < REFUSAL_BYTES) {
226
+ const next = await Promise.race([reader.read(), waited]);
227
+ if (!next || next.done)
228
+ break;
229
+ text += decoder.decode(next.value, { stream: true });
230
+ }
231
+ }
232
+ catch {
233
+ // What came is what is said.
234
+ }
235
+ finally {
236
+ clearTimeout(timer);
237
+ reader.cancel().catch(() => { });
238
+ }
239
+ return text.slice(0, REFUSAL_BYTES);
240
+ }
241
+ /** The provider's words in a 401's body: its error's message (Anthropic's `{error: {message}}`, OpenRouter's too), a
242
+ * string `error`, or a top-level `message`; a body that is no JSON, its text; a cut body, its message if that much came.
243
+ * Never JSON itself: a body with no string message says nothing, and the run's error is the plain refused-key words.
244
+ * The first line, with no control character (C0 or C1), at most 200 characters. */
245
+ export function refusalDetail(text) {
246
+ let said = "";
247
+ try {
248
+ const body = JSON.parse(text);
249
+ const error = body?.error;
250
+ const message = error !== null && typeof error === "object" ? error.message : error ?? body?.message;
251
+ said = typeof message === "string" ? message : "";
252
+ }
253
+ catch {
254
+ // A body cut before its end: its message, if that much came.
255
+ const caught = /"message"\s*:\s*"((?:[^"\\]|\\.)*)/.exec(text)?.[1];
256
+ said = caught === undefined ? (text.trimStart().startsWith("{") ? "" : text) : jsonString(caught);
257
+ }
258
+ return said.split("\n")[0].replace(/[\u0000-\u001f\u007f-\u009f]/g, "").trim().slice(0, 200);
259
+ }
@@ -0,0 +1,85 @@
1
+ import { type ProviderPolicy, type ProxyRoute, type ProxyUsage } from "@parcha/agentrun-kernel/host";
2
+ /** The prefix of the session's own tools, as the CLI names them (its in-process MCP server, `hands`). */
3
+ export declare const OWN_TOOL_PREFIX = "mcp__hands__";
4
+ export declare const CLAUDE_MESSAGES_ROUTES: readonly ProxyRoute[];
5
+ /** The `anthropic-beta` values the pinned CLI (2.1.286) sends, recorded per model behind this proxy (the real-CLI test
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
+ * model. Any other is refused, so a CLI or a model that starts sending a new one is seen before it is trusted. */
8
+ export declare const CLAUDE_BETAS: ReadonlySet<string>;
9
+ /** The content blocks the pinned CLI (2.1.286) sends in a session, recorded behind this proxy (the real-CLI test, with
10
+ * a model that thinks): any other type is refused, so a block the provider runs or resolves on its own (a server
11
+ * tool's call or result, an MCP block, a container upload, an image or document it would fetch) never passes, under
12
+ * whatever name the API gives it. A session's tools answer in text and its prompt is text, so it sends no image or
13
+ * document. */
14
+ export declare const CLAUDE_BLOCKS: ReadonlySet<string>;
15
+ /** Anthropic's web search server tool as the pinned CLI (2.1.286) asks for it: when the model calls the CLI's WebSearch,
16
+ * the CLI sends a request of its own on the session's model with this one tool (recorded behind a local server,
17
+ * test/fixtures/web-search-request-cli-2.1.286.json): its type and name, `max_uses: 8`, and the domains the model named.
18
+ * A later version (dynamic filtering runs code execution) or any other field is refused. */
19
+ 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
+ export interface AnthropicPolicyOptions {
24
+ /** The session's model, and the one the CLI's small background calls use (default: the session's). */
25
+ model: string;
26
+ smallModel?: string;
27
+ /** The session's own tool names (`spec.tools`): every other tool definition is dropped. */
28
+ tools: readonly string[];
29
+ /** The CLI's own tools the session has, offered by their own names beside its tools (`Skill`, when it has skills). */
30
+ builtins?: readonly string[];
31
+ /** The most output tokens one request may ask for. Default 128 000, what the pinned CLI asks for on current models. */
32
+ maxOutputTokens?: number;
33
+ /** Admit Anthropic's web search server tool (`CLAUDE_WEB_SEARCH_TOOL`), exactly as the pinned CLI asks for it; every
34
+ * other hosted tool stays refused, and so does every server tool's block (the CLI's WebSearch answers the model in
35
+ * text, so it never sends one back). Default off. */
36
+ webSearch?: boolean;
37
+ /** With the web search on: the input tokens a request carrying the search tool may read in beyond its body (the
38
+ * pages each search feeds the model, billed as input), added to that request's input bound. Absent, such a request
39
+ * has no input bound, so a cap that holds each request's worst case refuses it. */
40
+ webSearchAllowance?: number;
41
+ /** How the provider takes its credential. Default `x-api-key` (Anthropic's API). */
42
+ auth?: "x-api-key" | "bearer";
43
+ /** Told when a request on the session's main model carries no thinking and no effort: the model would answer without
44
+ * reasoning, which a session never asks for (the small model's background calls are not told). */
45
+ onThinkingDisabled?: (request: {
46
+ model: string;
47
+ }) => void;
48
+ }
49
+ /** Whether a Messages body asks the model to think: thinking on (adaptive, or a budget), or an effort level. */
50
+ export declare function thinks(body: Record<string, unknown>): boolean;
51
+ /** The tokens a request keeps for its answer when its output is limited, and the least thinking budget the provider
52
+ * takes: a request that thinks may be limited to no less than both. */
53
+ export declare const ANSWER_TOKENS_LEAST = 1024;
54
+ export declare const THINKING_BUDGET_LEAST = 1024;
55
+ /** The output tokens a Messages body asks for at most: its `max_tokens` (as `apply` clamped it). */
56
+ export declare function anthropicOutputAsked(body: Record<string, unknown>): number | undefined;
57
+ /** The least output a Messages body may be limited to and still answer: 1,024 tokens, and with extended thinking on (a
58
+ * budget) the provider's least budget beside them. Adaptive thinking takes no budget, so it needs none. */
59
+ export declare function anthropicOutputLeast(body: Record<string, unknown>): number;
60
+ /** A Messages body with its output limited to `max` tokens, thinking included: `max_tokens` at most `max`, never raised,
61
+ * and a thinking budget squeezed under it so that 1,024 tokens stay for the answer, never below the provider's least
62
+ * budget. Only numbers get smaller, so the body is never longer. */
63
+ export declare function limitAnthropicOutput(body: Record<string, unknown>, max: number): Record<string, unknown>;
64
+ /** The body the provider gets for a request on `route`. */
65
+ export declare function applyAnthropic(body: unknown, route: ProxyRoute, options: AnthropicPolicyOptions): Record<string, unknown>;
66
+ /** A Messages response's usage as the proxy books it: its tokens, and the web searches the provider ran for it
67
+ * (`usage.server_tool_use.web_search_requests`), only when there were any. */
68
+ export interface AnthropicUsage extends ProxyUsage {
69
+ webSearches?: number;
70
+ }
71
+ /** `price` with each web search a response reports added at `CLAUDE_WEB_SEARCH_USD`: the host prices the tokens, the
72
+ * searches are Anthropic's flat rate. An unknown price stays unknown. */
73
+ export declare function withWebSearches(price: (model: string, usage: ProxyUsage) => number | null): (model: string, usage: ProxyUsage) => number | null;
74
+ /** The usage a Messages response reports, read by parsing it, never by matching its text (the API nests objects in
75
+ * `usage`): a whole body's `usage`, or a stream's `message_start` usage (input and cache tokens) with its last
76
+ * `message_delta` usage over it (the final counts, the web searches among them). Each SSE `data:` line is parsed on its
77
+ * own and one that does not parse is skipped (the proxy keeps only the head and tail of a long answer). A stream that
78
+ * never stopped, or an answer with no readable usage, is unknown. */
79
+ export declare function anthropicUsage(text: string): AnthropicUsage | undefined;
80
+ /** The input tokens the provider bills for `body` that it does not carry (`providerInputOverhead`, with its sources): the
81
+ * tool-use system prompt when it has tools, and for each image the most it can be billed as, beyond its bytes. None
82
+ * can be said for a body with the web search tool: the provider bills the pages it finds as input, on each of its
83
+ * searches, so its input is unmeasured (undefined), never bounded by its bytes. */
84
+ export declare function anthropicServerInputOverhead(body: Record<string, unknown>, searchAllowance?: number): number | undefined;
85
+ export declare function anthropicPolicy(options: AnthropicPolicyOptions): ProviderPolicy;