@parcha/agentrun-harness-claude 0.1.0-beta.33 → 0.1.0-beta.35

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 CHANGED
@@ -2,6 +2,29 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## 0.1.0-beta.35 (2026-11-11)
6
+
7
+ - A capped run straight to Anthropic is no longer paused by a cap it could work under. Before each answer request on a route to `https://api.anthropic.com` (pi and claude-agent), the model proxy asks Anthropic's free token count (`POST /v1/messages/count_tokens`). It sends only the credential and version headers, and never goes through a gateway or any other base. The request's input bound is then that count plus the tool-use prompt, where before it was the body's bytes (about two to three times the tokens billed). A count that fails, says nothing or takes over 3 seconds leaves the byte bound, and the request goes on. Through OpenRouter or any other gateway the bound stays the bytes, so the cap still never passes.
8
+
9
+ The serve README's spend-cap section now states the smallest cap that works, by cap mode, measured on a pi desktop run on Sonnet. In `strict` mode (and in `expected`, the default, until the runner prices a step from the previous request's cache, #2504) it is $0.05 for the first request and $0.11 for a five-step run through a gateway, and $0.03 and $0.09 straight to Anthropic. The console's cap fields say it in a line, with a link. A cap below these still pauses with `Not sent: ... the next step needs at least $X`. A policy may count a request through `ProviderPolicy.countInput` (`InputCounter`, `countedInputOf` in the kernel host).
10
+ - A capped run that reads screenshots is no longer refused at its cap after the first one. A model request's input bound counted an image's base64 as one token per byte, and then the image's billed maximum on top. A 1280x720 screenshot (about a megabyte of base64) read as some 1.3 million input tokens, so a Sonnet step under a $1.50 cap "needed at least $4.83" when Claude bills it a few cents.
11
+
12
+ Each image, in every turn, now counts at what the routed model's provider can bill it as, in place of its data's bytes, whatever API carries it. The size comes from the image's own header (PNG, JPEG, GIF or WebP):
13
+ - Anthropic: its 28-pixel patches or its area at 750 pixels a token, whichever is more, at most 4,784.
14
+ - OpenAI: its 512-pixel tiles after resizing (85 + 170 each; 85 at detail low), or for a patch-billed mini or nano model its 32-pixel patches at that model's multiplier when more, at most 73,800.
15
+ - Google: 258 per 768-pixel tile, at least 1,120.
16
+ - Any other provider: the most of the three.
17
+ An image whose size can't be read counts at its provider's per-image maximum, never at its bytes. An image-shaped object outside where the API reads images (a tool call's arguments) is counted at its bytes, as text.
18
+
19
+ `InputShape.images` (the kernel host's `providerInputOverhead`) is now a list of images, each with the bytes its data takes and its size when known; `InputShape.model` names the routed model; the figure can be below 0, and so can a policy's `serverInputOverhead`, never past the body's bytes. Upgrading: pass `images: [{ bytes, width?, height? }]`, built with `imageInputOf`, `messagesImagesIn` or `responsesImagesIn`, and the model, in place of a count.
20
+
21
+ ## 0.1.0-beta.34 (2026-11-11)
22
+
23
+ - The server checks a harness's pinned binary (claude-agent's CLI, Codex, OpenCode: its sha256, then the version it reports) without holding its event loop, so requests, timers and store answers go on while a binary of hundreds of MiB is hashed and run. Before, the first check in a process held every request for one to several seconds (GET /v2/capabilities, a server's start, an adapter made for a run). The binary is now hashed off the loop a chunk at a time and run as a child the loop does not wait on. A pass is kept for the adapter's own check, which then reads nothing, and two checks of one binary at once read it once. New: `checkedOnceAsync` and `sha256OfFileAsync` (kernel host), `verifyClaudeAgentCliAsync` (claude-agent), and `verifyCodexAsync` and `verifyCodexBinaryAsync` (Codex). Who breaks: a program that calls the kernel's `checkedOnce` with its own check. A check is now a `BinaryCheck`, a generator that yields each probe (`{ kind: "sha256", path }` or `{ kind: "run", path, args, env, timeoutMs }`) and is given back its answer, so one check runs either way.
24
+ - A codex, opencode or claude-agent run that reads one of its skills' files (`read_skill_file`) now shows the call and its result on the run's Timeline, as pi's tool calls are shown. On the runner, the adapter's own skill reader ran outside the run's record, so the Timeline had no row for it. The read now goes through the host's tool path (the record, the rule before a side effect, the host's hooks on its result); a new `SessionIO.hostTool` hands an adapter's own tool to the host, and the kernel's `hostedTool(io, tool)` applies it.
25
+ - Upgrading: nothing to change.
26
+ - A run's effort is its own, else its agent revision's saved `thinking`, else the host's `AGENT_THINKING`, as documented: before, a run started with no `effort` dropped the other two, so its harness thought at its default, it got no effort note and its metrics named no effort. A pi run now thinks at that level too: its agent was given none, so even a run's own `effort` changed only its note. A CLI run's metrics now name the level its harness ran at (`max` on Codex or OpenCode runs at `xhigh`, and says so). A claude-agent session resumed on a later day is now told that day: the CLI resends the system prompt recorded at its first request, so the first message on each later day starts with `Today is <date> (UTC).`, in the CLI's transcript only (fixes #2416). `thinkingOf` and `EFFORT_ENV` are gone from the server's `model` module: `thinkingLevel` checks a level.
27
+
5
28
  ## 0.1.0-beta.32 (2026-11-10)
6
29
 
7
30
  - The code copied from the upstream durable harness is now AgentRun's own: the port froze, and the pristine upstream copies, the named patches, the import tables, `scripts/port-durable-harness.mjs` and `npm run verify:port` are gone. `vendor/durable-harness/UPSTREAM.json` still records where each copy came from, and each copy keeps its header and NOTICE its attribution. With it go the kernel's paths that never run:
package/dist/adapter.d.ts CHANGED
@@ -93,6 +93,8 @@ export interface ClaudeAgentAdapterOptions {
93
93
  thinking?: ClaudeAgentThinking;
94
94
  /** For tests: the fetch the model proxy forwards with. */
95
95
  fetch?: typeof fetch;
96
+ /** For tests: the clock a user turn's day is read from (harness.ts dateLine). Default the system's. */
97
+ now?: () => Date;
96
98
  }
97
99
  /** The thinking levels a session runs at: the SDK's effort levels, with adaptive thinking. There is no off. */
98
100
  export type ClaudeAgentThinking = "low" | "medium" | "high" | "xhigh" | "max";
@@ -119,6 +121,14 @@ export declare function verifyClaudeAgentCli(path: string | undefined, pins?: {
119
121
  }): {
120
122
  path: string;
121
123
  } | ClaudeAgentPinMismatch | ClaudeAgentNotInstalled;
124
+ /** verifyClaudeAgentCli without holding the event loop (the kernel's checkedOnceAsync): what a host awaits before it
125
+ * makes the adapter, whose own check then answers from what this kept. */
126
+ export declare function verifyClaudeAgentCliAsync(path: string | undefined, pins?: {
127
+ sha256?: string;
128
+ version: string;
129
+ }): Promise<{
130
+ path: string;
131
+ } | ClaudeAgentPinMismatch | ClaudeAgentNotInstalled>;
122
132
  /** What the adapter runs with, or the typed reason it cannot: the SDK (injected or installed) and its CLI, each the
123
133
  * pinned build. `installed` looks a package's version up (default: where Node would import it from here). */
124
134
  export declare function verifyClaudeAgent(options: Pick<ClaudeAgentAdapterOptions, "sdk" | "sdkVersion" | "cliPath" | "mcp">, installed?: (name: string) => string | undefined): {
package/dist/adapter.js CHANGED
@@ -9,14 +9,13 @@
9
9
  //
10
10
  // The Agent SDK is the host's: an exact optional peer dependency (`CLAUDE_AGENT_SDK_VERSION`), never shipped here.
11
11
  import { createHash, randomBytes, randomUUID } from "node:crypto";
12
- import { execFileSync } from "node:child_process";
13
12
  import { accessSync, constants, mkdirSync, rmSync, statSync, writeFileSync } from "node:fs";
14
13
  import { dirname, join } from "node:path";
15
- import { READ_SKILL_FILE, readSkillFileTool, skillProblems } from "@parcha/agentrun-kernel";
14
+ import { READ_SKILL_FILE, hostedTool, readSkillFileTool, skillProblems } from "@parcha/agentrun-kernel";
16
15
  import { abortedOutcome, openDrive, pendingSubmissions, Restart, SessionHalt } from "@parcha/agentrun-kernel/kernel";
17
16
  import { toolSchemaProblems } from "@parcha/agentrun-kernel";
18
17
  import { NativeJournal, recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
19
- import { checkedOnce, hostHeaderProblems, sha256OfFile, startModelProxy } from "@parcha/agentrun-kernel/host";
18
+ import { checkedOnce, checkedOnceAsync, hostHeaderProblems, startModelProxy } from "@parcha/agentrun-kernel/host";
20
19
  import { anthropicPolicy, withWebSearches } from "./host/policy.js";
21
20
  import { findClaudeExecutable, platformSuffix } from "./binary.js";
22
21
  import { CLAUDE_AGENT_PACKAGE, ClaudeAgentNotInstalled, ClaudeAgentPinMismatch, ClaudeAgentThinkingOff } from "./errors.js";
@@ -107,8 +106,15 @@ export function verifyClaudeAgentCli(path, pins = claudeAgentCliPins()) {
107
106
  // Hashed a chunk at a time, and once per CLI in this process while it stays the same file (the kernel's pinned-binary).
108
107
  return checkedOnce(path, JSON.stringify(pins), () => checkCli(path, pins), (result) => !(result instanceof Error));
109
108
  }
110
- /** The CLI at `path` against `pins`' sha256 and version. */
111
- function checkCli(path, pins) {
109
+ /** verifyClaudeAgentCli without holding the event loop (the kernel's checkedOnceAsync): what a host awaits before it
110
+ * makes the adapter, whose own check then answers from what this kept. */
111
+ export async function verifyClaudeAgentCliAsync(path, pins = claudeAgentCliPins()) {
112
+ if (!path)
113
+ return verifyClaudeAgentCli(path, pins);
114
+ return checkedOnceAsync(path, JSON.stringify(pins), () => checkCli(path, pins), (result) => !(result instanceof Error));
115
+ }
116
+ /** The CLI at `path` against `pins`' sha256 and version, as the steps it reads (the kernel's BinaryCheck). */
117
+ function* checkCli(path, pins) {
112
118
  try {
113
119
  if (!statSync(path).isFile())
114
120
  throw new Error("not a file");
@@ -120,7 +126,7 @@ function checkCli(path, pins) {
120
126
  if (pins.sha256) {
121
127
  let found;
122
128
  try {
123
- found = sha256OfFile(path);
129
+ found = yield { kind: "sha256", path };
124
130
  }
125
131
  catch {
126
132
  return new ClaudeAgentNotInstalled(`no CLI at ${path}`);
@@ -130,7 +136,7 @@ function checkCli(path, pins) {
130
136
  }
131
137
  let version;
132
138
  try {
133
- version = execFileSync(path, ["--version"], { env: { PATH: process.env.PATH ?? "/usr/bin:/bin", DISABLE_AUTOUPDATER: "1" }, encoding: "utf8", timeout: 15_000 }).trim().split(/\s/)[0] ?? "";
139
+ version = (yield { kind: "run", path, args: ["--version"], env: { PATH: process.env.PATH ?? "/usr/bin:/bin", DISABLE_AUTOUPDATER: "1" }, timeoutMs: 15_000 }).trim().split(/\s/)[0] ?? "";
134
140
  }
135
141
  catch (error) {
136
142
  return new ClaudeAgentPinMismatch("cli_version", pins.version, `unreadable (${String(error?.message ?? error).slice(0, 120)})`, path);
@@ -333,7 +339,7 @@ export function claudeAgentAdapter(options) {
333
339
  if (!dir)
334
340
  throw new Error("agentrun-harness-claude: a session needs a private directory: the host lends one (io.dir), or pass sessionsDir");
335
341
  // With skills, the model also reads their files (read_skill_file), from the session's own copy of them.
336
- const tools = skills.length ? [...spec.tools, readSkillFileTool(join(dir, "plugin", "skills"), skills.map((skill) => ({ name: skill.name, files: Object.keys(skill.files) })))] : spec.tools;
342
+ 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;
337
343
  const calls = new CallsInFlight();
338
344
  // The remote MCP servers' granted tools, as the CLI names them: its own MCP client calls them at the proxy.
339
345
  const mcpServers = spec.mcp?.servers ?? [];
@@ -387,6 +393,7 @@ export function claudeAgentAdapter(options) {
387
393
  sdk,
388
394
  ...(options.mcp ? { toolServerModules: options.mcp } : {}),
389
395
  ...(options.log ? { log: options.log } : {}),
396
+ ...(options.now ? { now: options.now } : {}),
390
397
  // The host's gate, asked about each host-tool call before it is written or run.
391
398
  ...(io.gate ? { gate: (call) => io.gate(call) } : {}),
392
399
  });
package/dist/harness.d.ts CHANGED
@@ -238,7 +238,19 @@ export interface ClaudeCodeHarnessOptions {
238
238
  log?: (message: string, fields?: Record<string, unknown>) => void;
239
239
  /** The host's gate (SessionIO.gate), asked by the tool bridge about each call of `tools` before its intent. */
240
240
  gate?: (call: GateCall) => Promise<GateAnswer>;
241
+ /** The clock a user turn's day is read from (dateLine). Default the system's. */
242
+ now?: () => Date;
241
243
  }
244
+ /**
245
+ * The line a user turn starts with when the session's model was not yet told its day: today's date, in UTC.
246
+ *
247
+ * The CLI records a session's system prompt at its first request and every resume sends that record, so a date the
248
+ * host put there (serve's environment line) stays the first day's. Re-rendering it (`snapshot: false`) records nothing
249
+ * and drops the prompt-cache prefix, so the day rides in the turn instead: the first message sent on a day the model has
250
+ * not been told carries this line, in the CLI's transcript only (the host's log keeps the person's words). The
251
+ * session's first launch sends no line on its first day: its fresh system prompt is the one recorded.
252
+ */
253
+ export declare function dateLine(now: Date): string;
242
254
  /** The default model. */
243
255
  export declare const DEFAULT_MODEL = "claude-sonnet-4-5";
244
256
  /** What the harness appends to the system prompt about the tools, before `instructions`, with the built-ins off and the app's tools there. */
package/dist/harness.js CHANGED
@@ -18,6 +18,21 @@ import { JournalSessionStore } from './store.js';
18
18
  import { MCP_SERVER, TranscriptBuilder } from './transcript.js';
19
19
  import { CLAUDE_AGENT_CLI_SKILL_NAMES } from './cli-names.js';
20
20
  import { assertAgentSdkVersion, CLAUDE_VM_EXECUTABLE } from './versions.js';
21
+ /**
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
+ *
24
+ * The CLI records a session's system prompt at its first request and every resume sends that record, so a date the
25
+ * host put there (serve's environment line) stays the first day's. Re-rendering it (`snapshot: false`) records nothing
26
+ * and drops the prompt-cache prefix, so the day rides in the turn instead: the first message sent on a day the model has
27
+ * not been told carries this line, in the CLI's transcript only (the host's log keeps the person's words). The
28
+ * session's first launch sends no line on its first day: its fresh system prompt is the one recorded.
29
+ */
30
+ export function dateLine(now) {
31
+ return `Today is ${dayOf(now)} (UTC).`;
32
+ }
33
+ const dayOf = (now) => now.toISOString().slice(0, 10);
34
+ /** The effect a user message that told its model the day is recorded under (`date:<message uuid>`, input `{ day }`). */
35
+ const DATE_EFFECT = 'date';
21
36
  /** The default model. */
22
37
  export const DEFAULT_MODEL = 'claude-sonnet-4-5';
23
38
  /** What the harness appends to the system prompt about the tools, before `instructions`, with the built-ins off and the app's tools there. */
@@ -477,6 +492,14 @@ export function claudeCodeHarness(options = {}) {
477
492
  // session sends the system prompt recorded at its start (`snapshot`), whatever a later launch passes, so this
478
493
  // drive alone renders its own (`snapshot: false`, which records nothing: the next drive's is the recorded one).
479
494
  const recovered = recoverySystemNote(ctx.state());
495
+ // The day this drive's system prompt names, while the CLI holds no record of the session: its first launch's
496
+ // prompt is fresh, and the first launch with snapshot on records its own (a first launch that recovers records
497
+ // nothing). Once a record exists a resume sends it, whatever day it names, and a recovery's own fresh prompt is
498
+ // never recorded: every other day reaches the model in its turn (dateLine).
499
+ const now = options.now ?? (() => new Date());
500
+ const recordedDay = !store.hasSession ? dayOf(now()) : undefined;
501
+ /** A message the CLI's transcript holds told the model `day`. */
502
+ 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)));
480
503
  const queryOptions = {
481
504
  model,
482
505
  cwd: machine.root,
@@ -551,6 +574,15 @@ export function claudeCodeHarness(options = {}) {
551
574
  // A recovery message carries placed prompts' words: which, under its uuid, before it goes (lostPrompts reads it).
552
575
  if (how.covers?.length)
553
576
  await ctx.effect(`covers:${uuid}`, { name: 'covers', replay: 'safe', input: { ids: how.covers } }, async () => true);
577
+ // The first message on a day the model was not told carries that day (dateLine), the session's recorded first
578
+ // day aside. Recorded under the message's uuid: the day counts as told once the transcript holds the message.
579
+ const at = now();
580
+ const day = dayOf(at);
581
+ if (!told(day)) {
582
+ if (day !== recordedDay)
583
+ text = `${dateLine(at)}\n\n${text}`;
584
+ await ctx.effect(`${DATE_EFFECT}:${uuid}`, { name: DATE_EFFECT, replay: 'safe', input: { day } }, async () => day);
585
+ }
554
586
  outstanding.add(uuid);
555
587
  input.push({
556
588
  type: 'user',
@@ -1,4 +1,4 @@
1
- import { type ProviderPolicy, type ProxyRequestContext, type ProxyRoute, type ProxyUsage } from "@parcha/agentrun-kernel/host";
1
+ import { type InputCounter, type ProviderPolicy, type ProxyRequestContext, type ProxyRoute, type ProxyUsage } from "@parcha/agentrun-kernel/host";
2
2
  /** The prefix of the session's own tools, as the CLI names them (its in-process MCP server, `hands`). */
3
3
  export declare const OWN_TOOL_PREFIX = "mcp__hands__";
4
4
  export declare const CLAUDE_MESSAGES_ROUTES: readonly ProxyRoute[];
@@ -99,10 +99,14 @@ export declare function anthropicFiltered(text: string): boolean;
99
99
  * tools, its own, built-in or remote (a remote MCP server's). The CLI's side calls (a title, a summary, a web search's
100
100
  * 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
101
  export declare function anthropicAnswers(body: Record<string, unknown>, options: Pick<AnthropicPolicyOptions, "tools" | "builtins" | "mcpTools">): boolean;
102
- /** The input tokens the provider bills for `body` that it does not carry (`providerInputOverhead`, with its sources): the
103
- * tool-use system prompt when it has tools, and for each image the most it can be billed as, beyond its bytes. None
104
- * can be said for a body with the web search tool: the provider bills the pages it finds as input, on each of its
105
- * searches, so its input is unmeasured (undefined), never bounded by its bytes. */
102
+ /**
103
+ * Anthropic's own count of a Messages request's input tokens: POST /v1/messages/count_tokens, free, on api.anthropic.com
104
+ * only ("Token counting", https://platform.claude.com/docs/en/build-with-claude/token-counting). The proxy asks it before
105
+ * each answer request on that origin (never through a gateway). Its `input_tokens` covers the request's
106
+ * system, messages, tools and images; the tool-use system prompt is added beside it (`margin`), in case the count leaves
107
+ * it out, so the bound never falls under what the request is billed.
108
+ */
109
+ export declare const ANTHROPIC_INPUT_COUNTER: InputCounter;
106
110
  export declare function anthropicServerInputOverhead(body: Record<string, unknown>, searchAllowance?: number): number | undefined;
107
111
  /** `body` (a Messages body) with `text` as a note the model reads after everything the Claude CLI sent: one text block, in
108
112
  * a <system-reminder>, at the end of the last user message (after its tool results), or a user message of its own after
@@ -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 { providerInputOverhead, ProxyRefusal } from "@parcha/agentrun-kernel/host";
21
+ import { messagesImagesIn, providerInputOverhead, 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"];
@@ -383,18 +383,34 @@ export function anthropicAnswers(body, options) {
383
383
  return Array.isArray(body.tools) && body.tools.some((tool) => isPlain(tool) && typeof tool.name === "string" && allowed.has(tool.name));
384
384
  }
385
385
  /** The Claude Agent CLI's provider policy for one session. */
386
- /** The image blocks in `value`, at any depth (a tool's result holds them). */
387
- function imagesIn(value) {
388
- if (Array.isArray(value))
389
- return value.reduce((n, item) => n + imagesIn(item), 0);
390
- if (!isPlain(value))
391
- return 0;
392
- return (value.type === "image" ? 1 : 0) + Object.values(value).reduce((n, item) => n + imagesIn(item), 0);
393
- }
394
- /** The input tokens the provider bills for `body` that it does not carry (`providerInputOverhead`, with its sources): the
395
- * tool-use system prompt when it has tools, and for each image the most it can be billed as, beyond its bytes. None
386
+ /** The input tokens the provider bills for `body` beyond its bytes (`providerInputOverhead`, with its sources): the
387
+ * tool-use system prompt when it has tools, and each image at the most it can be billed as by its size, in place of the
388
+ * bytes its base64 takes in the body (below 0 for a screenshot, whose megabyte of base64 Claude bills as some 1,200
389
+ * tokens). None
396
390
  * can be said for a body with the web search tool: the provider bills the pages it finds as input, on each of its
397
391
  * searches, so its input is unmeasured (undefined), never bounded by its bytes. */
392
+ /** The fields of a Messages body the token-count endpoint takes (the rest, such as max_tokens and stream, it refuses). */
393
+ const COUNTED_FIELDS = ["model", "messages", "system", "tools", "tool_choice", "thinking"];
394
+ /** The request headers the count is sent with: the credential's and the API's version and betas, nothing else. */
395
+ const COUNT_HEADERS = new Set(["x-api-key", "authorization", "anthropic-version", "anthropic-beta"]);
396
+ /**
397
+ * Anthropic's own count of a Messages request's input tokens: POST /v1/messages/count_tokens, free, on api.anthropic.com
398
+ * only ("Token counting", https://platform.claude.com/docs/en/build-with-claude/token-counting). The proxy asks it before
399
+ * each answer request on that origin (never through a gateway). Its `input_tokens` covers the request's
400
+ * system, messages, tools and images; the tool-use system prompt is added beside it (`margin`), in case the count leaves
401
+ * it out, so the bound never falls under what the request is billed.
402
+ */
403
+ export const ANTHROPIC_INPUT_COUNTER = Object.freeze({
404
+ origin: "https://api.anthropic.com",
405
+ path: "/v1/messages/count_tokens",
406
+ body: (body) => Object.fromEntries(COUNTED_FIELDS.filter((field) => body[field] !== undefined).map((field) => [field, body[field]])),
407
+ headers: (sent) => Object.fromEntries(Object.entries(sent).filter(([name]) => COUNT_HEADERS.has(name.toLowerCase()))),
408
+ tokensOf: (answer) => (isPlain(answer) && typeof answer.input_tokens === "number" ? answer.input_tokens : undefined),
409
+ margin: (body) => {
410
+ const choice = isPlain(body.tool_choice) ? body.tool_choice.type : undefined;
411
+ return providerInputOverhead("anthropic-messages", { tools: Array.isArray(body.tools) && body.tools.length > 0, ...(choice === "auto" || choice === "none" || choice === "any" || choice === "tool" ? { toolChoice: choice } : {}), images: [] });
412
+ },
413
+ });
398
414
  export function anthropicServerInputOverhead(body, searchAllowance) {
399
415
  const searches = offersWebSearch(body);
400
416
  if (searches && searchAllowance === undefined)
@@ -403,7 +419,9 @@ export function anthropicServerInputOverhead(body, searchAllowance) {
403
419
  const shape = {
404
420
  tools: Array.isArray(body.tools) && body.tools.length > 0,
405
421
  ...(choice === "auto" || choice === "none" || choice === "any" || choice === "tool" ? { toolChoice: choice } : {}),
406
- images: imagesIn(body.messages),
422
+ images: messagesImagesIn(body.messages),
423
+ // Its images at the routed model's provider's rule (a gateway may route the Messages API to another vendor's model).
424
+ ...(typeof body.model === "string" ? { model: body.model } : {}),
407
425
  };
408
426
  return providerInputOverhead("anthropic-messages", shape) + (searches ? searchAllowance : 0);
409
427
  }
@@ -451,6 +469,7 @@ export function anthropicPolicy(options) {
451
469
  modelOf: (body) => (typeof body.model === "string" ? body.model : undefined),
452
470
  serverInputOverhead: options.webSearchAllowance === undefined ? anthropicServerInputOverhead : (body) => anthropicServerInputOverhead(body, options.webSearchAllowance),
453
471
  outputAsked: anthropicOutputAsked,
472
+ countInput: ANTHROPIC_INPUT_COUNTER,
454
473
  outputLeast: anthropicOutputLeast,
455
474
  reasoningHidden: anthropicReasoningHidden,
456
475
  reasoningBytesOf: anthropicReasoningBytes,
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- 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 } from "./adapter.js";
1
+ 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";
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";
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // The Claude Agent SDK as an AgentRun harness adapter (id `claude-agent`). Written for AgentRun.
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 } from "./adapter.js";
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
4
  export { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_CODE_VERSION as CLAUDE_AGENT_CLI_VERSION } from "./versions.js";
5
5
  export { findClaudeExecutable as claudeAgentExecutable, platformSuffix as claudeAgentPlatform } from "./binary.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-harness-claude",
3
- "version": "0.1.0-beta.33",
3
+ "version": "0.1.0-beta.35",
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",
@@ -13,7 +13,7 @@
13
13
  "license": "Apache-2.0",
14
14
  "author": "Parcha Labs, Inc.",
15
15
  "engines": {
16
- "node": ">=24.11.0"
16
+ "node": ">=24.22.3"
17
17
  },
18
18
  "main": "./dist/index.js",
19
19
  "types": "./dist/index.d.ts",
@@ -48,8 +48,8 @@
48
48
  "test": "node --test --test-concurrency=8 'test/*.test.mjs'"
49
49
  },
50
50
  "dependencies": {
51
- "@parcha/agentrun-dsl": "0.1.0-beta.33",
52
- "@parcha/agentrun-kernel": "0.1.0-beta.33"
51
+ "@parcha/agentrun-dsl": "0.1.0-beta.35",
52
+ "@parcha/agentrun-kernel": "0.1.0-beta.35"
53
53
  },
54
54
  "peerDependencies": {
55
55
  "@anthropic-ai/claude-agent-sdk": "0.3.286",