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

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,32 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## 0.1.0-beta.30 (2026-11-05)
6
+
7
+ - A run whose model provider stops the answer on its content filter now ends `failed` with `error.code` `moderated` and
8
+ says so in plain words: "The model provider stopped this answer (its content filter). Rephrase the request, or try
9
+ another model." Before, it ended `run_failed` with the provider's jargon ("Response incomplete: content_filter"). The
10
+ Timeline's error row keeps the harness's words for the stop (pi-ai's on pi, the kernel's on claude-agent and codex). On pi the run reads pi-ai's words for the stop on each API. On
11
+ claude-agent and codex the session's model proxy reads the provider's stop (Anthropic's `refusal`, an OpenAI answer
12
+ `incomplete` for `content_filter`) and the harness ends the turn at once: the CLI no longer asks for the refused answer
13
+ again, turn after turn. Only the turn's own answer request ends it: a side call the CLI makes beside the turn (one
14
+ without the session's tools) that the provider stops is logged and left to the CLI. The refused request is booked at
15
+ the usage its end reports. The kernel exports `CONTENT_FILTERED`, the text such a turn ends with; a provider policy may
16
+ say a stop through `filtered` and a side call through `answers`, and the model proxy tells its machine through
17
+ `onFiltered`.
18
+ - A request you stop under a cap counts the reasoning it never streamed. A model whose reasoning streams only as a summary (the Responses API's reasoning, Claude 4-class thinking) is billed for far more than the summary's bytes. A stop after about 10,000 hidden reasoning tokens on a gpt-5-class model with a 20 KB context cost about $0.106 and counted $0.038, so deliberate stops could pass a cap. A stopped request that reasons now also counts the part of its reasoning budget that did not stream: input + streamed + 1,024 + max(0, reasoning budget - reasoning streamed), never more than its hold. Real usage still replaces the figure when it comes.
19
+ - **On pi:** a reasoning model's stopped request counts its thinking level's budget (on Anthropic's API, the `budget_tokens` it was sent with, for a model whose thinking takes one). A Claude model that thinks adaptively (every current one on Anthropic's API) is sent no budget, and its thinking is bounded only by its output limit, so it counts that limit less 1,024 tokens: in practice its hold. A stop after a 300-byte thinking summary on Sonnet 5.5 with a 20 KB context under a $1 cap counted $0.142 at medium and $0.224 at high, against about $0.45 for 40,000 adaptive thinking tokens. The request's output limit is now the one actually sent: the cap had taken a thinking budget out of it that pi-ai never sends (8,192 tokens at medium), so the request was held at more than it was sent with. With no level, on an API whose model reasons at its own default, it counts its whole output limit. With thinking off on Anthropic's API, on a model whose thinking can be off, nothing more.
20
+ - **Adaptive thinking counts up to the hold.** On every current Claude model, on pi and on `claude-agent`, the provider is given no thinking budget, so a stopped request counts up to the hold the cap took for it. Under a cap with little left beside that hold, the request after the stop can be refused.
21
+ - **On `codex`:** the effort's budget (minimal 1,024, low 2,048, medium 8,192, high 16,384), none at effort `none`, and the output limit when the body names no effort.
22
+ - **On `opencode`:** the same as `codex` (the same Responses API): what a stop counts as streamed is the content its deltas carried, not the wire, plus the unstreamed part of its effort's budget. On the walk through OpenCode's proxy (a request at $100 a million output tokens under a $0.50 cap, stopped after 1,146 characters of answer text after the stream's echo of the request) the stop booked 106,831 bytes, its whole $0.50 hold, and refused "Go on."; it now counts $0.217, and "Go on." goes.
23
+ - **On `claude-agent`:** the thinking budget, or `max_tokens` when thinking is adaptive, for every request that thinks; none with thinking off. Thinking that streamed is subtracted, so a stop after a budget's worth of visible thinking counts nothing on top.
24
+ - **Kernel:** a provider policy may read a request's hidden reasoning from its body (`reasoningHidden`). It may also read the reasoning in each streamed event (`reasoningBytesOf`). The model proxy books a stopped response with both (`stoppedHiddenTokens`, `stoppedReasoningBytes`), and the runner counts all it sent plus the part of the budget its reasoning did not cover.
25
+ - **What streamed is the content, not the wire.** On `claude-agent` and `codex` a stop counted the response's bytes as sent, the provider's framing included: about 11.7 bytes a character of text on the Responses API and 24 on the Messages API. A codex request at $100 a million output under a $0.50 cap, stopped after 1,146 characters, booked its whole hold and refused "Go on.". It now counts each text, reasoning and tool-argument delta's UTF-8 bytes, as pi counts its streamed blocks: $0.217, and the next request goes. A provider policy reads them (`contentBytesOf`).
26
+ - **A stop before the provider's first header** on `claude-agent` and `codex` now counts as a stop with nothing streamed (its input and 1,024 tokens, as on pi), not its whole hold. A response the provider answered with an error status still counts at its hold.
27
+ - A message the person stopped the instant it was sent is no longer lost on claude-agent, and the same window is closed on Codex and OpenCode. Asked "Reply with exactly this code and nothing else: CARRY-CLAUDE-7", stopped within its first second, then told "Go on.", a claude-agent run answered "There's nothing earlier in this conversation for me to continue from": Claude takes a message within its first second, so the stop landed after the harness placed it and before the CLI was handed it, and nothing carried it. Now a stop's settle carries a placed message its CLI never took into the next one, as it carries one stopped before it was placed. On claude-agent that is a message the CLI's own transcript, as the session keeps it, does not hold: that transcript is the history a resumed CLI is given, so a carried message is never sent twice. On Codex it is a message Codex's own rollout, as the session keeps it, does not hold. OpenCode marks a message just before it sends it (`prompt_async`), and a marked message is never carried: a crash between the mark and the send loses it rather than sending it twice. After a stop, no new turn is started.
28
+ - **A recovered message is not carried again.** After a crash between a message's placement and its CLI's record, the recovery message carries its words. It now records which messages it carries, before it goes (a kernel effect by its id on claude-agent, its `PROMPT_STREAM` record on OpenCode). Once the CLI holds the recovery message, a stop's settle and a later recovery both count those messages sent, so nothing is sent twice, even after a second crash. Codex's recovery already did this through its client id.
29
+ - **A follow-up's own prompt** (the host's, named to the settle) is withdrawn and never carried into the person's next message, as the follow-up says: a host prompt that never ran is not sent. A person's message waiting beside it is left as it is.
30
+
5
31
  ## 0.1.0-beta.29 (2026-11-04)
6
32
 
7
33
  - `ClaudeAgentNotInstalled` says, in one line, what is missing and how to install it: the message keeps its prefix ("Claude Agent SDK not installed"), names the SDK, its platform package with the CLI, or the MCP library it brings as a peer, and ends with `; install it with: npm install --save-exact @anthropic-ai/claude-agent-sdk@0.3.286`, which is also on the error as `install` (and exported as `CLAUDE_AGENT_SDK_INSTALL`). A `cliPath` that holds nothing keeps its own message, with no install line. A host that matched the whole message exactly now matches its prefix.
package/dist/adapter.d.ts CHANGED
@@ -93,6 +93,12 @@ export interface ClaudeAgentAdapterOptions {
93
93
  export type ClaudeAgentThinking = "low" | "medium" | "high" | "xhigh" | "max";
94
94
  /** A session's level: the node's thinking, else its effort (minimal thinks at low, never at nothing), else the adapter's. */
95
95
  export declare function thinkingOf(spec: Pick<SessionSpec, "thinking" | "effort">, fallback: ClaudeAgentThinking): ClaudeAgentThinking;
96
+ /**
97
+ * The SDK that is handed no message once the drive is stopped: its prompt stream ends instead, so no turn starts after a
98
+ * stop. Whether a placed message reached the CLI is the CLI's own record, not this hand-over: the SDK writes a message to
99
+ * the CLI's stdin at once, and a stop can kill the CLI before it reads it (settleOpenTurn reads the transcript).
100
+ */
101
+ export declare function withStopEndingPrompts(sdk: ClaudeAgentSdk, signal: () => AbortSignal): ClaudeAgentSdk;
96
102
  /** The pins a CLI is checked against: its sha256 on this platform (where one is recorded) and its version. */
97
103
  export declare function claudeAgentCliPins(): {
98
104
  sha256?: string;
package/dist/adapter.js CHANGED
@@ -15,11 +15,12 @@ import { dirname, join } from "node:path";
15
15
  import { READ_SKILL_FILE, readSkillFileTool, skillProblems } from "@parcha/agentrun-kernel";
16
16
  import { abortedOutcome, openDrive, pendingSubmissions, Restart, SessionHalt } from "@parcha/agentrun-kernel/kernel";
17
17
  import { toolSchemaProblems } from "@parcha/agentrun-kernel";
18
- import { recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
18
+ import { NativeJournal, recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
19
19
  import { checkedOnce, hostHeaderProblems, sha256OfFile } from "@parcha/agentrun-kernel/host";
20
20
  import { findClaudeExecutable, platformSuffix } from "./binary.js";
21
21
  import { CLAUDE_AGENT_PACKAGE, ClaudeAgentNotInstalled, ClaudeAgentPinMismatch, ClaudeAgentThinkingOff } from "./errors.js";
22
- import { claudeCodeHarness } from "./harness.js";
22
+ import { claudeCodeHarness, lostPrompts } from "./harness.js";
23
+ import { JournalSessionStore } from "./store.js";
23
24
  import { localMachine } from "./host/machine.js";
24
25
  import { serialWriter } from "./serial.js";
25
26
  import { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_CODE_VERSION, installedVersion } from "./versions.js";
@@ -64,6 +65,24 @@ export function thinkingOf(spec, fallback) {
64
65
  return "low";
65
66
  return asked && THINKING.has(asked) ? asked : fallback;
66
67
  }
68
+ /**
69
+ * The SDK that is handed no message once the drive is stopped: its prompt stream ends instead, so no turn starts after a
70
+ * stop. Whether a placed message reached the CLI is the CLI's own record, not this hand-over: the SDK writes a message to
71
+ * the CLI's stdin at once, and a stop can kill the CLI before it reads it (settleOpenTurn reads the transcript).
72
+ */
73
+ export function withStopEndingPrompts(sdk, signal) {
74
+ const until = async function* (prompt) {
75
+ for await (const message of prompt) {
76
+ if (signal().aborted)
77
+ return;
78
+ yield message;
79
+ }
80
+ };
81
+ return {
82
+ ...sdk,
83
+ query: ((args) => sdk.query({ ...args, prompt: (typeof args.prompt === "string" ? args.prompt : until(args.prompt)) })),
84
+ };
85
+ }
67
86
  /** The SDK with every query thinking at `level`: adaptive thinking, at that effort. */
68
87
  function thinkingAt(sdk, level) {
69
88
  return {
@@ -322,7 +341,8 @@ export function claudeAgentAdapter(options) {
322
341
  });
323
342
  // The SDK this session runs on (the host's, or the one installed beside this package, checked above), thinking at
324
343
  // the session's level.
325
- const sdk = thinkingAt(options.sdk ?? (await import("@anthropic-ai/claude-agent-sdk")), thinkingOf(spec, thinking));
344
+ // Handed nothing once the drive of the moment is stopped (withStopEndingPrompts).
345
+ const sdk = withStopEndingPrompts(thinkingAt(options.sdk ?? (await import("@anthropic-ai/claude-agent-sdk")), thinkingOf(spec, thinking)), () => drive.signal);
326
346
  const harness = claudeCodeHarness({
327
347
  name: CLAUDE_AGENT_ID,
328
348
  sandbox: {
@@ -437,13 +457,20 @@ export function claudeAgentAdapter(options) {
437
457
  await ready();
438
458
  void run();
439
459
  },
440
- async settleOpenTurn() {
460
+ async settleOpenTurn(options = {}) {
441
461
  if (state !== "open_turn")
442
462
  throw new Error("agentrun-harness-claude: there is no turn to settle");
443
463
  await ready();
444
464
  // The turn's end in the session's own transcript, as a turn that ends writes it: the next open finds no open turn,
445
- // and the next turn carries no recovery of this one. Nothing is sent.
446
- await settleTurn(drive);
465
+ // and the next turn carries no recovery of this one. Nothing is sent. A prompt the turn placed that the CLI never
466
+ // recorded (the stop came before the CLI read it) is carried into the next message, as an unplaced one is; a
467
+ // follow-up's own is not. The record is the CLI's transcript as the session keeps it (lostPrompts over the
468
+ // journal's transcript store), the history a resumed CLI is given: a message it lacks the next turn's model never
469
+ // saw, so carrying it never sends it twice.
470
+ const folded = drive.state();
471
+ const transcript = new JournalSessionStore(new NativeJournal(drive), { records: await new NativeJournal(drive).read() });
472
+ const unsent = lostPrompts(folded, recoveryNote(folded)?.turn.placed ?? [], transcript);
473
+ await settleTurn(drive, { unsent, ...(options.opening === undefined ? {} : { host: options.opening }) });
447
474
  state = "idle";
448
475
  },
449
476
  async turnEnd() {
package/dist/harness.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
2
2
  // From github.com/vercel-labs/durable-harness, packages/harness-claude-code/src/harness.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
3
- // Changed by Parcha, imports rewritten for AgentRun; patches: 001-gate-always-on, 002-names, 003-comments, 008-tool-description-max, 009-tool-result-barrier-and-refusals, 010-served-tools-with-images, 011-session-skills, 013-recovery-note-system-prompt, 015-web-search, 016-mcp-output-tokens, 017-key-refused
3
+ // Changed by Parcha, imports rewritten for AgentRun; patches: 001-gate-always-on, 002-names, 003-comments, 008-tool-description-max, 009-tool-result-barrier-and-refusals, 010-served-tools-with-images, 011-session-skills, 013-recovery-note-system-prompt, 015-web-search, 016-mcp-output-tokens, 017-key-refused, 019-recovery-covers
4
4
  import { AsyncLocalStorage } from 'node:async_hooks';
5
5
  import { randomUUID } from 'node:crypto';
6
6
  import { mkdtemp, rm } from 'node:fs/promises';
@@ -526,6 +526,9 @@ export function claudeCodeHarness(options = {}) {
526
526
  if (first && how.priority !== 'next' && !how.synthetic)
527
527
  ledger.turn(first);
528
528
  const uuid = !first ? randomUUID() : how.synthetic ? uuidFrom(`note:${first}`) : uuidFrom(first);
529
+ // A recovery message carries placed prompts' words: which, under its uuid, before it goes (lostPrompts reads it).
530
+ if (how.covers?.length)
531
+ await ctx.effect(`covers:${uuid}`, { name: 'covers', replay: 'safe', input: { ids: how.covers } }, async () => true);
529
532
  outstanding.add(uuid);
530
533
  input.push({
531
534
  type: 'user',
@@ -658,7 +661,8 @@ export function claudeCodeHarness(options = {}) {
658
661
  ledger.turn(open.placed[0] ?? `open:${open.since}`);
659
662
  // The CLI answers again from the interrupted step: what a reader saw of its reply is replaced by what the log kept.
660
663
  ctx.live(restartEvent(note.turn));
661
- await send(recoveryUserTurn(ctx.state(), store, note.pending), note.pending, { synthetic: 'recovery' });
664
+ const covers = [...(open ? lostPrompts(ctx.state(), open.placed, store) : []), ...note.pending.map((s) => s.id)];
665
+ await send(recoveryUserTurn(ctx.state(), store, note.pending), note.pending, { synthetic: 'recovery', covers });
662
666
  await runTurn();
663
667
  }
664
668
  // The inbox, one submission per turn.
@@ -810,8 +814,10 @@ const RECOVERY_STATUS = {
810
814
  */
811
815
  export function lostPrompts(state, placed, store) {
812
816
  const said = new Set(state.submissions.filter((s) => s.kind === 'prompt' || s.kind === 'steer' || s.kind === 'followUp').map((s) => s.id));
817
+ // A prompt a recovery message carried (its cover, by the message's uuid) is recorded once the transcript holds that message.
818
+ const covered = new Set(state.effectOrder.filter((e) => e.name === 'covers' && e.key.startsWith('covers:') && store.hasUser(e.key.slice('covers:'.length))).flatMap((e) => e.input?.ids ?? []));
813
819
  return placed.filter((id) => {
814
- if (!said.has(id))
820
+ if (!said.has(id) || covered.has(id))
815
821
  return false;
816
822
  const placement = state.effectOrder.find((e) => e.name === 'place' && e.key.startsWith('place:') && e.placed.includes(id));
817
823
  const first = placement ? placement.key.slice('place:'.length) : id;
@@ -142,6 +142,8 @@ export function localMachine(options) {
142
142
  ...(options.proxy.price ? { price: withWebSearches(options.proxy.price) } : {}),
143
143
  ...(options.proxy.headers ? { headers: options.proxy.headers } : {}),
144
144
  ...(options.proxy.log ? { log: options.proxy.log } : {}),
145
+ // The provider stopped the turn's answer on its content filter: no retry of it can pass, so the turn ends at once.
146
+ onFiltered: (message) => ctx.halt?.(new Error(message)),
145
147
  onResponse: ({ path, status }) => {
146
148
  if (path !== "/v1/messages/count_tokens" || counted)
147
149
  return;
@@ -57,6 +57,17 @@ export declare function anthropicOutputAsked(body: Record<string, unknown>): num
57
57
  /** The least output a Messages body may be limited to and still answer: 1,024 tokens, and with extended thinking on (a
58
58
  * budget) the provider's least budget beside them. Adaptive thinking takes no budget, so it needs none. */
59
59
  export declare function anthropicOutputLeast(body: Record<string, unknown>): number;
60
+ /** The thinking tokens a Messages request may bill that its stream never shows: Claude 4-class models stream only a
61
+ * summary of their thinking (and a redacted block shows none of it), so a request that thinks counts its thinking
62
+ * budget, or its `max_tokens` when its thinking is adaptive (no budget); one with thinking off, none. A stopped request
63
+ * counts the part of it that did not stream (less `anthropicReasoningBytes` of what it sent), never past its hold. */
64
+ export declare function anthropicReasoningHidden(body: Record<string, unknown>): number;
65
+ /** The bytes of thinking one Messages stream event carries: a thinking delta's text, UTF-8; 0 for text, a tool call's
66
+ * JSON, a signature and every other event. */
67
+ export declare function anthropicReasoningBytes(event: string): number;
68
+ /** The bytes of content one Messages stream event carries: a text, thinking or tool-input delta's text, UTF-8, never
69
+ * the framing around it; 0 for a signature and every other event. */
70
+ export declare function anthropicContentBytes(event: string): number;
60
71
  /** A Messages body with its output limited to `max` tokens, thinking included: `max_tokens` at most `max`, never raised,
61
72
  * and a thinking budget squeezed under it so that 1,024 tokens stay for the answer, never below the provider's least
62
73
  * budget. Only numbers get smaller, so the body is never longer. */
@@ -77,6 +88,14 @@ export declare function withWebSearches(price: (model: string, usage: ProxyUsage
77
88
  * 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
89
  * never stopped, or an answer with no readable usage, is unknown. */
79
90
  export declare function anthropicUsage(text: string): AnthropicUsage | undefined;
91
+ /** Whether a Messages answer ended on the provider's refusal (`stop_reason: "refusal"`, its content filter): a whole body's
92
+ * `stop_reason`, or a stream's last `message_delta` stop. Read by parsing, never by matching text, each SSE `data:` line
93
+ * on its own, as anthropicUsage reads them. */
94
+ export declare function anthropicFiltered(text: string): boolean;
95
+ /** Whether a Messages body (as `apply` kept it) is the turn's answer request: it offers the model one of the session's
96
+ * tools. The CLI's side calls (a title, a summary, a web search's own request) offer none of them; in a session with no
97
+ * tools no request can be told from one, so each is the turn's. */
98
+ export declare function anthropicAnswers(body: Record<string, unknown>, options: Pick<AnthropicPolicyOptions, "tools" | "builtins">): boolean;
80
99
  /** The input tokens the provider bills for `body` that it does not carry (`providerInputOverhead`, with its sources): the
81
100
  * tool-use system prompt when it has tools, and for each image the most it can be billed as, beyond its bytes. None
82
101
  * can be said for a body with the web search tool: the provider bills the pages it finds as input, on each of its
@@ -185,6 +185,42 @@ export function anthropicOutputAsked(body) {
185
185
  export function anthropicOutputLeast(body) {
186
186
  return isPlain(body.thinking) && body.thinking.type === "enabled" ? ANSWER_TOKENS_LEAST + THINKING_BUDGET_LEAST : ANSWER_TOKENS_LEAST;
187
187
  }
188
+ /** The thinking tokens a Messages request may bill that its stream never shows: Claude 4-class models stream only a
189
+ * summary of their thinking (and a redacted block shows none of it), so a request that thinks counts its thinking
190
+ * budget, or its `max_tokens` when its thinking is adaptive (no budget); one with thinking off, none. A stopped request
191
+ * counts the part of it that did not stream (less `anthropicReasoningBytes` of what it sent), never past its hold. */
192
+ export function anthropicReasoningHidden(body) {
193
+ const thinking = body.thinking;
194
+ if (!isPlain(thinking))
195
+ return 0;
196
+ if (thinking.type === "enabled")
197
+ return typeof thinking.budget_tokens === "number" && Number.isFinite(thinking.budget_tokens) && thinking.budget_tokens > 0 ? thinking.budget_tokens : anthropicOutputAsked(body) ?? 0;
198
+ if (thinking.type === "adaptive")
199
+ return anthropicOutputAsked(body) ?? 0;
200
+ return 0;
201
+ }
202
+ /** The bytes of thinking one Messages stream event carries: a thinking delta's text, UTF-8; 0 for text, a tool call's
203
+ * JSON, a signature and every other event. */
204
+ export function anthropicReasoningBytes(event) {
205
+ const data = event.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
206
+ if (!data.startsWith("{"))
207
+ return 0;
208
+ const parsed = JSON.parse(data);
209
+ return parsed.type === "content_block_delta" && parsed.delta?.type === "thinking_delta" && typeof parsed.delta.thinking === "string" ? Buffer.byteLength(parsed.delta.thinking, "utf8") : 0;
210
+ }
211
+ /** The bytes of content one Messages stream event carries: a text, thinking or tool-input delta's text, UTF-8, never
212
+ * the framing around it; 0 for a signature and every other event. */
213
+ export function anthropicContentBytes(event) {
214
+ const data = event.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
215
+ if (!data.startsWith("{"))
216
+ return 0;
217
+ const parsed = JSON.parse(data);
218
+ if (parsed.type !== "content_block_delta" || !parsed.delta)
219
+ return 0;
220
+ const { type, text, thinking, partial_json: json } = parsed.delta;
221
+ const piece = type === "text_delta" ? text : type === "thinking_delta" ? thinking : type === "input_json_delta" ? json : undefined;
222
+ return typeof piece === "string" ? Buffer.byteLength(piece, "utf8") : 0;
223
+ }
188
224
  /** A Messages body with its output limited to `max` tokens, thinking included: `max_tokens` at most `max`, never raised,
189
225
  * and a thinking budget squeezed under it so that 1,024 tokens stay for the answer, never below the provider's least
190
226
  * budget. Only numbers get smaller, so the body is never longer. */
@@ -305,6 +341,43 @@ export function anthropicUsage(text) {
305
341
  const lastDelta = events.filter((e) => e.type === "message_delta").at(-1)?.usage;
306
342
  return bookedUsage({ ...startUsage, ...(isPlain(lastDelta) ? lastDelta : {}) });
307
343
  }
344
+ /** Whether a Messages answer ended on the provider's refusal (`stop_reason: "refusal"`, its content filter): a whole body's
345
+ * `stop_reason`, or a stream's last `message_delta` stop. Read by parsing, never by matching text, each SSE `data:` line
346
+ * on its own, as anthropicUsage reads them. */
347
+ export function anthropicFiltered(text) {
348
+ const lines = text.split(/\r?\n/);
349
+ if (!lines.some((line) => line.startsWith("data:") || line.startsWith("event:"))) {
350
+ let body;
351
+ try {
352
+ body = JSON.parse(text);
353
+ }
354
+ catch {
355
+ return false;
356
+ }
357
+ return isPlain(body) && body.stop_reason === "refusal";
358
+ }
359
+ let stop;
360
+ for (const line of lines) {
361
+ if (!line.startsWith("data:"))
362
+ continue;
363
+ try {
364
+ const event = JSON.parse(line.slice(5));
365
+ if (isPlain(event) && event.type === "message_delta" && isPlain(event.delta) && "stop_reason" in event.delta)
366
+ stop = event.delta.stop_reason;
367
+ }
368
+ catch { /* cut at the kept window's edge, or not JSON: skipped */ }
369
+ }
370
+ return stop === "refusal";
371
+ }
372
+ /** Whether a Messages body (as `apply` kept it) is the turn's answer request: it offers the model one of the session's
373
+ * tools. The CLI's side calls (a title, a summary, a web search's own request) offer none of them; in a session with no
374
+ * tools no request can be told from one, so each is the turn's. */
375
+ export function anthropicAnswers(body, options) {
376
+ const allowed = new Set([...options.tools.map((name) => `${OWN_TOOL_PREFIX}${name}`), ...(options.builtins ?? [])]);
377
+ if (allowed.size === 0)
378
+ return true;
379
+ return Array.isArray(body.tools) && body.tools.some((tool) => isPlain(tool) && typeof tool.name === "string" && allowed.has(tool.name));
380
+ }
308
381
  /** The Claude Agent CLI's provider policy for one session. */
309
382
  /** The image blocks in `value`, at any depth (a tool's result holds them). */
310
383
  function imagesIn(value) {
@@ -353,7 +426,12 @@ export function anthropicPolicy(options) {
353
426
  serverInputOverhead: options.webSearchAllowance === undefined ? anthropicServerInputOverhead : (body) => anthropicServerInputOverhead(body, options.webSearchAllowance),
354
427
  outputAsked: anthropicOutputAsked,
355
428
  outputLeast: anthropicOutputLeast,
429
+ reasoningHidden: anthropicReasoningHidden,
430
+ reasoningBytesOf: anthropicReasoningBytes,
431
+ contentBytesOf: anthropicContentBytes,
356
432
  limitOutput: limitAnthropicOutput,
357
433
  usageOf: anthropicUsage,
434
+ filtered: anthropicFiltered,
435
+ answers: (body) => anthropicAnswers(body, options),
358
436
  };
359
437
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-harness-claude",
3
- "version": "0.1.0-beta.29",
3
+ "version": "0.1.0-beta.30",
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",
@@ -44,8 +44,8 @@
44
44
  "test": "node --test --test-concurrency=8 'test/*.test.mjs'"
45
45
  },
46
46
  "dependencies": {
47
- "@parcha/agentrun-dsl": "0.1.0-beta.29",
48
- "@parcha/agentrun-kernel": "0.1.0-beta.29"
47
+ "@parcha/agentrun-dsl": "0.1.0-beta.30",
48
+ "@parcha/agentrun-kernel": "0.1.0-beta.30"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "@anthropic-ai/claude-agent-sdk": "0.3.286",