@parcha/agentrun-harness-claude 0.1.0-beta.38 → 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 CHANGED
@@ -2,6 +2,26 @@
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
+
5
25
  ## 0.1.0-beta.38 (2026-11-14)
6
26
 
7
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.
package/dist/adapter.d.ts CHANGED
@@ -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,7 +14,7 @@ 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";
@@ -222,20 +222,11 @@ class CallsInFlight {
222
222
  });
223
223
  }
224
224
  }
225
- /** The kernel's tool for a host tool. The host hears of the call (`tool_start`) once its intent is in the session's
226
- * records, and of its end only once the outcome is (the live `tool_end` the tool bridge sends after the effect). */
227
- function kernelTool(tool, io, maxImageBytes, calls) {
228
- return {
229
- name: tool.name,
230
- description: tool.description,
231
- inputSchema: tool.inputSchema,
232
- replay: tool.replay,
233
- ...(tool.nests ? { nests: true } : {}),
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
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
@@ -245,22 +236,10 @@ function kernelTool(tool, io, maxImageBytes, calls) {
245
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.
246
237
  if (calls.draining)
247
238
  throw new Error(`${tool.name} was not run: the session is pausing`);
248
- io.onEvent({ type: "tool_start", callId, name: tool.name, args: input });
249
- // A tool that nests calls (tools_call, codemode) gets the session's tools as its nested calls, through the bridge.
250
- const result = await tool.call(input, { callId, signal: effect.signal, attempt, ...(effect.nested ? { nested: effect.nested } : {}) });
251
- if (result.isError)
252
- throw new Error(result.text);
253
- // Its value, recorded with the outcome: a script's nested call is answered it (meta-tools.ts), as Codex's adapter keeps it.
254
- const structured = result.structured !== undefined ? { structured: result.structured } : {};
255
- if (!result.images?.length)
256
- return result.structured === undefined ? result.text : { text: result.text, ...structured };
257
- // An image the model can't be sent is the call's error, by the tool's name and the image, not a request refused later.
258
- const wrong = toolImageProblems(tool.name, result.images, maxImageBytes);
259
- if (wrong)
260
- throw new Error(wrong);
261
- return { text: result.text, images: result.images.map((image) => ({ mimeType: image.mimeType, data: image.data })), ...structured };
239
+ io.onEvent({ type: "tool_start", callId, name: tool.name, args });
262
240
  },
263
- };
241
+ imageProblems: (images) => toolImageProblems(tool.name, images, maxImageBytes),
242
+ });
264
243
  }
265
244
  const turnsIn = (drive) => transcriptOf(drive.state()).filter((r) => r.data?.type === "turn");
266
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
@@ -367,7 +346,7 @@ export function claudeAgentAdapter(options) {
367
346
  // No command of its own: the CLI reaches nothing but its model proxy (a web search, when on, is the provider's).
368
347
  network: "deny-all",
369
348
  },
370
- tools: tools.map((tool) => kernelTool(tool, io, maxImageBytes, calls)),
349
+ tools: tools.map((tool) => claudeTool(tool, io, maxImageBytes, calls)),
371
350
  ...(spec.deferCatalog === undefined ? {} : { deferCatalog: spec.deferCatalog }),
372
351
  builtins: false,
373
352
  // Off by name too, besides tools: []: the pinned CLI's tools that neither the harness's allowlist nor its off list
@@ -385,6 +364,7 @@ export function claudeAgentAdapter(options) {
385
364
  ...(options.mcp ? { toolServerModules: options.mcp } : {}),
386
365
  ...(options.log ? { log: options.log } : {}),
387
366
  ...(options.now ? { now: options.now } : {}),
367
+ ...(options.zone ? { zone: options.zone } : {}),
388
368
  // The host's gate, asked about each host-tool call and each WebSearch before it is written or run.
389
369
  ...(io.gate ? { gate: (call) => io.gate(call) } : {}),
390
370
  });
package/dist/facts.js CHANGED
@@ -3,14 +3,15 @@
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 it "[Tool call interrupted]"); only the model calls again.
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,
15
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.
16
17
  ownToolSearch: true,
@@ -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
@@ -232,9 +232,11 @@ export interface ClaudeCodeHarnessOptions {
232
232
  gate?: (call: GateCall) => Promise<GateAnswer>;
233
233
  /** The clock a user turn's day is read from (dateLine). Default the system's. */
234
234
  now?: () => Date;
235
+ /** The IANA zone the day is read in (dateLine). Default UTC. */
236
+ zone?: string;
235
237
  }
236
238
  /**
237
- * 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).
238
240
  *
239
241
  * The CLI records a session's system prompt at its first request and every resume sends that record, so a date the
240
242
  * host put there (serve's environment line) stays the first day's. Re-rendering it (`snapshot: false`) records nothing
@@ -242,13 +244,19 @@ export interface ClaudeCodeHarnessOptions {
242
244
  * not been told carries this line, in the CLI's transcript only (the host's log keeps the person's words). The
243
245
  * session's first launch sends no line on its first day: its fresh system prompt is the one recorded.
244
246
  */
245
- export declare function dateLine(now: Date): string;
247
+ export declare function dateLine(now: Date, zone?: string): string;
246
248
  /** The default model. */
247
249
  export declare const DEFAULT_MODEL = "claude-sonnet-5-5";
248
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. */
249
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.";
250
252
  /** `TOOLS_NOTE` with WebSearch on (`providerTools: ['web_search']`) and the other built-ins off. */
251
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.";
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.";
252
260
  /** `TOOLS_NOTE` for a session with no tools at all (built-ins off, no `tools`). */
253
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.";
254
262
  /** With the built-ins on (docs/workspaces.md §5.6 "Workspace note"): what `/workspace` is. */
package/dist/harness.js CHANGED
@@ -20,7 +20,7 @@ import { MCP_SERVER, TranscriptBuilder } from './transcript.js';
20
20
  import { CLAUDE_AGENT_CLI_SKILL_NAMES } from './cli-names.js';
21
21
  import { assertAgentSdkVersion, CLAUDE_VM_EXECUTABLE } from './versions.js';
22
22
  /**
23
- * 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).
24
24
  *
25
25
  * The CLI records a session's system prompt at its first request and every resume sends that record, so a date the
26
26
  * host put there (serve's environment line) stays the first day's. Re-rendering it (`snapshot: false`) records nothing
@@ -28,10 +28,11 @@ import { assertAgentSdkVersion, CLAUDE_VM_EXECUTABLE } from './versions.js';
28
28
  * not been told carries this line, in the CLI's transcript only (the host's log keeps the person's words). The
29
29
  * session's first launch sends no line on its first day: its fresh system prompt is the one recorded.
30
30
  */
31
- export function dateLine(now) {
32
- return `Today is ${dayOf(now)} (UTC).`;
31
+ export function dateLine(now, zone = 'UTC') {
32
+ return `Today is ${dayOf(now, zone)}.`;
33
33
  }
34
- const dayOf = (now) => now.toISOString().slice(0, 10);
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})`;
35
36
  /** The effect a user message that told its model the day is recorded under (`date:<message uuid>`, input `{ day }`). */
36
37
  const DATE_EFFECT = 'date';
37
38
  /** The default model. */
@@ -40,6 +41,12 @@ export const DEFAULT_MODEL = 'claude-sonnet-5-5';
40
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.`;
41
42
  /** `TOOLS_NOTE` with WebSearch on (`providerTools: ['web_search']`) and the other built-ins off. */
42
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.`;
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.`;
43
50
  /** `TOOLS_NOTE` for a session with no tools at all (built-ins off, no `tools`). */
44
51
  export const NO_TOOLS_NOTE = 'You have no tools in this session: no shell, file, search or web tools. Answer from the conversation.';
45
52
  /** With the built-ins on (docs/workspaces.md §5.6 "Workspace note"): what `/workspace` is. */
@@ -517,7 +524,7 @@ export function claudeCodeHarness(options = {}) {
517
524
  // nothing). Once a record exists a resume sends it, whatever day it names, and a recovery's own fresh prompt is
518
525
  // never recorded: every other day reaches the model in its turn (dateLine).
519
526
  const now = options.now ?? (() => new Date());
520
- const recordedDay = !store.hasSession ? dayOf(now()) : undefined;
527
+ const recordedDay = !store.hasSession ? dayOf(now(), options.zone) : undefined;
521
528
  /** A message the CLI's transcript holds told the model `day`. */
522
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)));
523
530
  const queryOptions = {
@@ -546,7 +553,7 @@ export function claudeCodeHarness(options = {}) {
546
553
  systemPrompt: {
547
554
  type: 'preset',
548
555
  preset: 'claude_code',
549
- append: [builtinsOn ? DRIVE_NOTE : webSearch ? WEB_SEARCH_NOTE : bridge.tools.length ? TOOLS_NOTE : NO_TOOLS_NOTE, options.instructions, recovered].filter(Boolean).join('\n\n'),
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'),
550
557
  snapshot: !recovered,
551
558
  },
552
559
  ...(store.hasSession ? { resume: sessionId } : { sessionId }),
@@ -595,10 +602,10 @@ export function claudeCodeHarness(options = {}) {
595
602
  // The first message on a day the model was not told carries that day (dateLine), the session's recorded first
596
603
  // day aside. Recorded under the message's uuid: the day counts as told once the transcript holds the message.
597
604
  const at = now();
598
- const day = dayOf(at);
605
+ const day = dayOf(at, options.zone);
599
606
  if (!told(day)) {
600
607
  if (day !== recordedDay)
601
- text = `${dateLine(at)}\n\n${text}`;
608
+ text = `${dateLine(at, options.zone)}\n\n${text}`;
602
609
  await ctx.effect(`${DATE_EFFECT}:${uuid}`, { name: DATE_EFFECT, replay: 'safe', input: { day } }, async () => day);
603
610
  }
604
611
  outstanding.add(uuid);
@@ -64,6 +64,8 @@ export declare function anthropicOutputAsked(body: Record<string, unknown>): num
64
64
  /** The least output a Messages body may be limited to and still answer: 1,024 tokens, and with extended thinking on (a
65
65
  * budget) the provider's least budget beside them. Adaptive thinking takes no budget, so it needs none. */
66
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;
67
69
  /** The thinking tokens a Messages request may bill that its stream never shows: Claude 4-class models stream only a
68
70
  * summary of their thinking (and a redacted block shows none of it), so a request that thinks counts its thinking
69
71
  * budget, or its `max_tokens` when its thinking is adaptive (no budget); one with thinking off, none. A stopped request
@@ -93,8 +95,10 @@ export declare function withWebSearches(price: (model: string, usage: ProxyUsage
93
95
  /** The usage a Messages response reports, read by parsing it, never by matching its text (the API nests objects in
94
96
  * `usage`): a whole body's `usage`, or a stream's `message_start` usage (input and cache tokens) with its last
95
97
  * `message_delta` usage over it (the final counts, the web searches among them). Each SSE `data:` line is parsed on its
96
- * own and one that does not parse is skipped (the proxy keeps only the head and tail of a long answer). A stream that
97
- * never stopped, or an answer with no readable usage, is unknown. */
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. */
98
102
  export declare function anthropicUsage(text: string): AnthropicUsage | undefined;
99
103
  /** Whether a Messages answer ended on the provider's refusal (`stop_reason: "refusal"`, its content filter): a whole body's
100
104
  * `stop_reason`, or a stream's last `message_delta` stop. Read by parsing, never by matching text, each SSE `data:` line
@@ -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, NATIVE_SEARCH_USD, 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"];
@@ -196,6 +196,11 @@ export function anthropicOutputAsked(body) {
196
196
  export function anthropicOutputLeast(body) {
197
197
  return isPlain(body.thinking) && body.thinking.type === "enabled" ? ANSWER_TOKENS_LEAST + THINKING_BUDGET_LEAST : ANSWER_TOKENS_LEAST;
198
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
+ }
199
204
  /** The thinking tokens a Messages request may bill that its stream never shows: Claude 4-class models stream only a
200
205
  * summary of their thinking (and a redacted block shows none of it), so a request that thinks counts its thinking
201
206
  * budget, or its `max_tokens` when its thinking is adaptive (no budget); one with thinking off, none. A stopped request
@@ -328,8 +333,10 @@ export function withWebSearches(price) {
328
333
  /** The usage a Messages response reports, read by parsing it, never by matching its text (the API nests objects in
329
334
  * `usage`): a whole body's `usage`, or a stream's `message_start` usage (input and cache tokens) with its last
330
335
  * `message_delta` usage over it (the final counts, the web searches among them). Each SSE `data:` line is parsed on its
331
- * own and one that does not parse is skipped (the proxy keeps only the head and tail of a long answer). A stream that
332
- * never stopped, or an answer with no readable usage, is unknown. */
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. */
333
340
  export function anthropicUsage(text) {
334
341
  const lines = text.split(/\r?\n/);
335
342
  if (!lines.some((line) => line.startsWith("data:") || line.startsWith("event:"))) {
@@ -353,7 +360,7 @@ export function anthropicUsage(text) {
353
360
  }
354
361
  catch { /* cut at the kept window's edge, or not JSON: skipped */ }
355
362
  }
356
- if (!events.some((e) => e.type === "message_stop"))
363
+ if (!events.some((e) => e.type === "message_stop" || e.type === "error"))
357
364
  return undefined;
358
365
  const started = events.find((e) => e.type === "message_start")?.message;
359
366
  const startUsage = isPlain(started) && isPlain(started.usage) ? started.usage : {};
@@ -485,7 +492,17 @@ export function anthropicPolicy(options) {
485
492
  serverInputOverhead: options.webSearchAllowance === undefined ? anthropicServerInputOverhead : (body) => anthropicServerInputOverhead(body, options.webSearchAllowance),
486
493
  outputAsked: anthropicOutputAsked,
487
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)),
488
504
  outputLeast: anthropicOutputLeast,
505
+ effortOf: anthropicEffort,
489
506
  reasoningHidden: anthropicReasoningHidden,
490
507
  reasoningBytesOf: anthropicReasoningBytes,
491
508
  contentBytesOf: anthropicContentBytes,
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ 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
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";
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
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 its
48
- * result is written into the transcript and committed, so the CLI starts again past it. A gate that parks rejects out
49
- * of here with nothing written, and the call keeps the id the model gave it.
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 its
126
- * result is written into the transcript and committed, so the CLI starts again past it. A gate that parks rejects out
127
- * of here with nothing written, and the call keeps the id the model gave it.
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
- if ('tool' in reply)
210
- blocks.push({ type: 'tool_use', id: reply.tool.id ?? `toolu_fake_${String(++toolSeq).padStart(4, '0')}_${Date.now().toString(36)}`, name: reply.tool.name, input: reply.tool.input });
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 = 'tool' in reply ? 'tool_use' : 'end_turn';
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 };
@@ -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.38",
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.38"
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.38"
80
+ "@parcha/agentrun-dsl": "0.1.0-beta.39"
81
81
  }
82
82
  }