@parcha/agentrun-harness-claude 0.1.0-beta.62 → 0.1.0-beta.63

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,18 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## 0.1.0-beta.63 (2026-11-26)
6
+
7
+ - A tool result is held to the model's context window, not only to the fixed 120,000-character bound: a model with a small window (an Ollama model at 65,536 tokens, a 16k one) is never handed a result that fills its context. <!-- changes/tool-result-window-bound.md -->
8
+ - `boundResult(text, budget?)` takes the model's window (`{ contextWindow, baseInputTokens? }`): a result may take at most a quarter of what the window leaves (`RESULT_WINDOW_SHARE`), at three characters a token (`RESULT_CHARS_PER_TOKEN`), and never more than `HOST_RESULT_MAX_CHARS`. Past that it is cut with a note saying it was cut to fit the window and how to read on; a window too small for any cut refuses the result in words, and a result of at most 400 characters (`RESULT_ALWAYS_WHOLE_CHARS`) always stands whole, so bounding a bound changes nothing. With no window the bound is exactly as before. `resultMaxChars(budget)` gives the bound, and `boundTo(text, max)` cuts to a given bound, saying how (`ResultBound`: the characters kept, the whole length, the bound).
9
+ - `SessionSpec.contextWindow` carries the session model's window, and each harness adapter (Claude, Codex, ACP, OpenCode) takes a `contextWindow` option for when the host passes none; Codex and OpenCode are told that window in place of their 272,000 guess. A Codex script cut off by a crash is answered within the same bound (`recoveryMaxChars`), not `EXEC_RECOVERY_MAX_CHARS`.
10
+ - agentrun-serve puts the run's model window from its catalog on every session, and pi now holds every tool result to it too: a host tool's and a pi-native one's (web_fetch, web_search, the browser's), which before reached the model up to pi's own output limits. What a host tool streams while it runs is held to the bound too (`boundedProgress`), since pi writes a call cut off past its restart limit from that text, without its hooks.
11
+ - A turn's results together fit what the window has left (`TurnBudget`, `ResultBudget.turn`): from what the context already holds (the last request's input tokens and its answer's output, else the session's system prompt and tool schemas counted with o200k), less the room kept for the model's answer (`answerReserve`: a quarter of the window, at most `ANSWER_RESERVE_MAX_TOKENS`, 16,384 tokens), each call the model made takes the smaller of its own bound and what is left over the calls still unanswered, so parallel calls split it, and below the least a cut keeps a result is refused in words. The kernel owns the rule; the session's model proxy reports each answer's facts (`ModelProxyOptions.turn`, its calls counted from the stream by `toolCallsIn`) for Claude, Codex, OpenCode and Goose, and pi and claude-agent on a person's login report them from their own hooks (pi's afterResponse, the login's stream booking). `windowBudget(window, system?)` builds the budget with its turn. A call whose result goes to the harness's own tool rather than the model (`ToolBridgeOptions.outsideTurn`: Codex's code-mode script calls) takes the per-result bound alone, outside the turn's split.
12
+ - The bridge records each cut it hands a harness (`bound:<callId>`, `boundKey`), and a replay of the call is cut by that record. Codex compares a nested call's two records on those lengths, never on the note's words; `boundOf` is gone. A session written before the record still agrees where Codex got the host's bound's cut, as before.
13
+ - On Claude, Codex, ACP and OpenCode, a turn's budget outlasts a process that stops in the turn (a park, a crash): each answer's facts and each result's length as it was handed go to the session's journal as they happen (`journalTurn`, `TURN_STREAM`), and a budget that has read no answer yet takes them back before any call claims (`TurnBudget.restore`). The calls a resume answers split what their answer left, and a result handed before the stop keeps its part. Codex's recovered script outputs claim their room in the turn too and are held to that claim (`ResultBudget.maxChars`). pi's turn budget is not journaled yet: a pi session opened again starts a fresh one, and each result there keeps its per-result bound.
14
+ - A claude-agent answer whose stream stalled partway, and that the Claude CLI then got whole, is said once: when the whole answer begins with what streamed, only the rest is said, so the timeline shows one message where it showed the streamed part and then the whole answer again. A whole retry's blocks stay one message too, including when the first block says exactly what streamed. The 30-minute wait on a silent stream (`CLAUDE_STREAM_IDLE_TIMEOUT_MS`), which 0.1.0-beta.62 gave every model AgentRun's route translates, now applies to a model on the server's own machine (an Ollama model) alone. A paid model AgentRun translates keeps the CLI's five minutes again, so a hung stream holds the run's slot and cap no longer than that. <!-- changes/claude-local-answer-followup.md -->
15
+ - A CLI run's end-of-run turn (its learning step) now reads the turn's last message as its answer, as a pi run's always has. Before, it ran every message of the turn together, so a claude-agent turn whose stream stalled and was asked again whole stored the stalled part and the whole answer as one. The Claude adapter takes the stream idle limit from its host (`streamIdleMs`, `LOCAL_STREAM_IDLE_MS`) rather than from a route's `fetch`, and serve sets it only for a model on its own machine. <!-- changes/cli-end-of-run-answer.md -->
16
+
5
17
  ## 0.1.0-beta.62 (2026-11-26)
6
18
 
7
19
  **Breaking:**
package/dist/adapter.d.ts CHANGED
@@ -58,6 +58,10 @@ export interface ClaudeAgentAdapterOptions {
58
58
  price?: ModelProxyOptions["price"];
59
59
  /** The most output tokens one request may ask for. Default 128 000, what the pinned CLI asks for on current models. */
60
60
  maxOutputTokens?: number;
61
+ /** The model's context window, in tokens: the host's bound on one tool result is its share of it (the kernel's
62
+ * resultMaxChars), under HOST_RESULT_MAX_CHARS. A session's own (SessionSpec.contextWindow) wins. Absent, and none on
63
+ * the session: the host's bound alone. */
64
+ contextWindow?: number;
61
65
  /** The most one image a tool answers with may be, as base64 (default 5 MB, `CLAUDE_AGENT_MAX_IMAGE_BYTES`; at most
62
66
  * 10 MB, Anthropic's API's own limit). A larger one is the call's error. */
63
67
  maxImageBytes?: number;
@@ -105,6 +109,11 @@ export interface ClaudeAgentAdapterOptions {
105
109
  /** The fetch the model proxy forwards with: the host's route for a model it translates onto this wire (a test's
106
110
  * recorder, too); absent, the network. Forwarding it is the harness contract (HARNESS.md, the facts' `wire`). */
107
111
  fetch?: typeof fetch;
112
+ /** How long the CLI waits on a silent stream before it gives the stream up and asks again without one
113
+ * (CLAUDE_STREAM_IDLE_TIMEOUT_MS). A host sets it for a model on its own machine (LOCAL_STREAM_IDLE_MS), which says
114
+ * nothing while it loads, reads its prompt or thinks. Absent: the CLI's own limit (5 minutes), which a paid provider's
115
+ * hung stream is held to. */
116
+ streamIdleMs?: number;
108
117
  /** The run's clock, when the host sets one (serve: a template eval case's `now`): a user turn's day is read from it
109
118
  * (harness.ts dateLine), and the CLI's own date lines, which it reads from the machine's clock, are made to say its
110
119
  * day in `zone` at the session's model proxy (policy.ts `day`). A session on a login has no proxy: there the CLI's
@@ -113,9 +122,9 @@ export interface ClaudeAgentAdapterOptions {
113
122
  /** The IANA zone a user turn's day is read in (harness.ts dateLine), the one the host's environment line names. Default UTC. */
114
123
  zone?: string;
115
124
  }
116
- /** How long the CLI waits on a silent stream from a model the host's route translates: the longest the CLI takes
117
- * (CLAUDE_STREAM_IDLE_TIMEOUT_MS, 30 minutes). */
118
- export declare const TRANSLATED_STREAM_IDLE_MS: number;
125
+ /** How long the CLI waits on a silent stream from a model on the host's own machine (an Ollama model): the longest the
126
+ * CLI takes (CLAUDE_STREAM_IDLE_TIMEOUT_MS, 30 minutes). */
127
+ export declare const LOCAL_STREAM_IDLE_MS: number;
119
128
  /** The thinking levels a session runs at: the SDK's effort levels, with adaptive thinking. There is no off. */
120
129
  export type ClaudeAgentThinking = "low" | "medium" | "high" | "xhigh" | "max";
121
130
  /** A session's level: the node's thinking, else its effort (minimal thinks at low, never at nothing), else the adapter's. */
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 { bridgeTool, NativeJournal, recoveryNote, settleTurn, transcriptOf } from "@parcha/agentrun-kernel/process";
17
+ import { bridgeTool, NativeJournal, recoveryNote, settleTurn, transcriptOf, windowBudget } from "@parcha/agentrun-kernel/process";
18
18
  import { checkedOnce, checkedOnceAsync, hostHeaderProblems, startModelProxy } from "@parcha/agentrun-kernel/host";
19
19
  import { anthropicPolicy, isoDay, withWebSearches } from "./host/policy.js";
20
20
  import { findClaudeExecutable, platformSuffix } from "./binary.js";
@@ -58,9 +58,9 @@ export const CLAUDE_AGENT_DIGESTS = Object.freeze({
58
58
  const TOOL_NAME = /^[A-Za-z0-9_-]{1,64}$/;
59
59
  /** How often one send rebuilds a drive whose CLI exited mid-turn. */
60
60
  const RESTARTS = 3;
61
- /** How long the CLI waits on a silent stream from a model the host's route translates: the longest the CLI takes
62
- * (CLAUDE_STREAM_IDLE_TIMEOUT_MS, 30 minutes). */
63
- export const TRANSLATED_STREAM_IDLE_MS = 30 * 60_000;
61
+ /** How long the CLI waits on a silent stream from a model on the host's own machine (an Ollama model): the longest the
62
+ * CLI takes (CLAUDE_STREAM_IDLE_TIMEOUT_MS, 30 minutes). */
63
+ export const LOCAL_STREAM_IDLE_MS = 30 * 60_000;
64
64
  const THINKING = new Set(["low", "medium", "high", "xhigh", "max"]);
65
65
  /** A session's level: the node's thinking, else its effort (minimal thinks at low, never at nothing), else the adapter's. */
66
66
  export function thinkingOf(spec, fallback) {
@@ -320,6 +320,9 @@ export function claudeAgentAdapter(options) {
320
320
  // With skills, the model also reads their files (read_skill_file), from the session's own copy of them.
321
321
  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;
322
322
  const calls = new CallsInFlight();
323
+ // Each tool result held to the model's share of its window (the session's, else this adapter's; none: the host's
324
+ // bound), and a turn's results to what the window has left, which the session's model proxy reads from each answer.
325
+ const budget = windowBudget(spec.contextWindow ?? options.contextWindow, spec.system);
323
326
  // The CLI's own tools offered to the model: Skill only when the session has skills, WebSearch only when it is on.
324
327
  const builtins = [...(skills.length ? ["Skill"] : []), ...(webSearch ? ["WebSearch"] : [])];
325
328
  const acquire = localMachine({
@@ -330,6 +333,7 @@ export function claudeAgentAdapter(options) {
330
333
  // On a login, no proxy: the CLI calls Anthropic itself.
331
334
  ...(provider ? { proxy: {
332
335
  hooks: io.models,
336
+ ...(budget.resultBudget?.turn ? { turn: budget.resultBudget.turn } : {}),
333
337
  tools: tools.map((t) => t.name),
334
338
  ...(builtins.length ? { builtins } : {}),
335
339
  ...(webSearch ? { webSearch: true, ...(options.webSearchAllowance !== undefined ? { webSearchAllowance: options.webSearchAllowance } : {}) } : {}),
@@ -358,6 +362,7 @@ export function claudeAgentAdapter(options) {
358
362
  },
359
363
  tools: tools.map((tool) => claudeTool(tool, io, maxImageBytes, calls)),
360
364
  ...(spec.deferCatalog === undefined ? {} : { deferCatalog: spec.deferCatalog }),
365
+ ...budget,
361
366
  builtins: false,
362
367
  // Off by name too, besides tools: []: the pinned CLI's tools that neither the harness's allowlist nor its off list
363
368
  // decide (test/tool-off.test.mjs pins the CLI's whole tool set against these lists), but WebSearch when it is on.
@@ -366,10 +371,10 @@ export function claudeAgentAdapter(options) {
366
371
  model: modelFor(spec),
367
372
  ...(skills.length ? { skills: { plugin: join(dir, "plugin"), names: writeSkillsPlugin(join(dir, "plugin"), skills) } } : {}),
368
373
  ...(options.smallModel ? { smallModel: options.smallModel } : {}),
369
- // A model the host's route translates (an Ollama model) sends nothing while it loads, reads its prompt or thinks
370
- // (the route holds its thinking to redact it whole): the CLI waits its longest on it, never dropping the stream
371
- // at 5 minutes to ask again without one.
372
- ...(options.fetch ? { streamIdleMs: TRANSLATED_STREAM_IDLE_MS } : {}),
374
+ // A model on the host's own machine (an Ollama model) sends nothing while it loads, reads its prompt or thinks (the
375
+ // route holds its thinking to redact it whole): the host has the CLI wait longer on it (streamIdleMs), never
376
+ // dropping the stream at 5 minutes to ask again without one. Any other route keeps the CLI's own limit.
377
+ ...(options.streamIdleMs ? { streamIdleMs: options.streamIdleMs } : {}),
373
378
  ...(spec.system.length ? { instructions: spec.system.join("\n\n") } : {}),
374
379
  ...(provider ? { credential: async () => provider.credential(), gatewayUrl: provider.origin } : { login: { at: login, models: io.models } }),
375
380
  executable,
package/dist/harness.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type GateAnswer, type GateCall } from '@parcha/agentrun-kernel';
2
+ import type { ResultBudget } from '@parcha/agentrun-kernel/process';
2
3
  import { type DriveContext, type Harness, type HostTool, type ReplayPolicy, type SessionState, type Submission } from './host/kernel.js';
3
4
  import { type GatewayHandler, type ProviderTool, type SessionMachine } from './host/process.js';
4
5
  import { type ClaudeAgentLogin, type ClaudeLoginToken } from './login.js';
@@ -147,6 +148,9 @@ export interface ClaudeCodeHarnessOptions {
147
148
  /** The host's verdict on whether the catalog tools are deferred (SessionSpec.deferCatalog), which turns the CLI's own
148
149
  * tool search on or off; absent, the tools' names decide (claudeToolSearch). */
149
150
  deferCatalog?: boolean;
151
+ /** What the session's model can take of one tool result (its context window): the tool bridge holds every result to
152
+ * it (boundResult's budget). Absent: the host's bound alone (HOST_RESULT_MAX_CHARS). */
153
+ resultBudget?: ResultBudget;
150
154
  /**
151
155
  * Claude Code's own tools, in the VM, on `/workspace`. Default false
152
156
  * (tool-less: `tools` are the CLI's only tools). `true`: the pinned
package/dist/harness.js CHANGED
@@ -8,7 +8,7 @@ import { tmpdir } from 'node:os';
8
8
  import { dirname, join, posix } from 'node:path';
9
9
  import { defersCatalog } from '@parcha/agentrun-kernel';
10
10
  import { Restart, Unavailable } from './host/kernel.js';
11
- import { askGate, BuiltinCalls, CLAUDE_ROUTES, gatewayCredential, gatewayHandler, gatewayUrl, isBrandedMachine, NativeJournal, openTurn, placeSubmissions, recoveryNote, restartEvent, replayBy, toolBridge, toolKey, waitForSubmissions, } from './host/process.js';
11
+ import { askGate, BuiltinCalls, CLAUDE_ROUTES, gatewayCredential, gatewayHandler, gatewayUrl, isBrandedMachine, journalTurn, NativeJournal, openTurn, placeSubmissions, recoveryNote, restartEvent, replayBy, toolBridge, toolKey, waitForSubmissions, } from './host/process.js';
12
12
  import { durableEnv, nativeModelId } from './env.js';
13
13
  import { LOGIN_TOKEN_REFUSED, loginBooking, loginByToken, loginEnv } from './login.js';
14
14
  import { uuidFrom } from './ids.js';
@@ -233,6 +233,8 @@ export function claudeCodeHarness(options = {}) {
233
233
  throw sandboxRequired();
234
234
  const { query } = await loadSdk();
235
235
  const journal = new NativeJournal(ctx);
236
+ // The turn's budget kept on this drive's journal: a resume answers the calls it left on its answer's facts.
237
+ journalTurn(options.resultBudget?.turn, journal);
236
238
  const records = await journal.read();
237
239
  const store = new JournalSessionStore(journal, { records, coalesceMs: options.coalesceMs ?? 150, ...(options.barrierTimers ? { timers: options.barrierTimers } : {}) });
238
240
  // The handler reads the credential per request, in the drive's async
@@ -244,9 +246,9 @@ export function claudeCodeHarness(options = {}) {
244
246
  log('claude-agent: the kernel gave no deadline; assuming a 300 s invocation', {});
245
247
  const deadline = ctx.deadline ?? Date.now() + ASSUMED_INVOCATION_MS;
246
248
  // On a person's login there is no model route: the CLI calls Anthropic itself, and its responses are booked from
247
- // its stream (loginBooking).
249
+ // its stream (loginBooking), which also reports each answer to the turn budget, as a model proxy does.
248
250
  const login = options.login;
249
- const booking = login ? loginBooking(login.models, model, (error) => ctx.halt?.(error)) : undefined;
251
+ const booking = login ? loginBooking(login.models, model, (error) => ctx.halt?.(error), options.resultBudget?.turn) : undefined;
250
252
  const handler = login ? undefined : gatewayHandler({
251
253
  routes: CLAUDE_ROUTES,
252
254
  models: { model, ...(smallModel ? { smallModel } : {}) },
@@ -321,6 +323,8 @@ export function claudeCodeHarness(options = {}) {
321
323
  const released = [];
322
324
  const bridge = toolBridge(ctx, tools, {
323
325
  ...(gated ? { gate: gated } : {}),
326
+ // Each result held to the session model's share of its window, when the adapter passed it.
327
+ ...(options.resultBudget ? { budget: options.resultBudget } : {}),
324
328
  // A `never` tool runs only once the assistant entry that asked for it is in the log.
325
329
  beforeNever: ({ callId }) => logged(callId),
326
330
  });
@@ -28,6 +28,8 @@ export interface LocalMachineOptions {
28
28
  * runs on a person's own login (login.ts): the machine then starts no proxy, and holds no model URL or key. */
29
29
  proxy?: {
30
30
  hooks: ModelProxyHooks;
31
+ /** The session's turn budget (ResultBudget.turn), which the proxy opens with each answer's facts. */
32
+ turn?: ModelProxyOptions["turn"];
31
33
  tools: readonly string[];
32
34
  /** The CLI's own tools the session has (`Skill`, with skills; `WebSearch`), offered beside its tools. */
33
35
  builtins?: readonly string[];
@@ -143,6 +143,7 @@ export function localMachine(options) {
143
143
  onThinkingDisabled: ({ model: main }) => po.log?.("claude-agent: thinking.disabled", { model: main }),
144
144
  }),
145
145
  hooks: po.hooks,
146
+ ...(po.turn ? { turn: po.turn } : {}),
146
147
  model: route.models.model,
147
148
  origin: route.target,
148
149
  credential: async () => (await route.credential()) ?? "",
@@ -1,5 +1,5 @@
1
1
  import type { DriveContext } from "./kernel.js";
2
- export { askGate, BuiltinCalls, NativeJournal, openTurn, placeSubmissions, recoveryNote, replayBy, restartEvent, resumeUnstartedCalls, toolBridge, toolKey, unstartedCalls, waitForSubmissions, zodShapeFromJsonSchema, } from "@parcha/agentrun-kernel/process";
2
+ export { askGate, BuiltinCalls, journalTurn, NativeJournal, openTurn, placeSubmissions, recoveryNote, replayBy, restartEvent, resumeUnstartedCalls, toolBridge, toolKey, unstartedCalls, waitForSubmissions, zodShapeFromJsonSchema, } from "@parcha/agentrun-kernel/process";
3
3
  export type { CallOutcome, DanglingCall, JournalRecord, ToolBridge, TranscriptEntry } from "@parcha/agentrun-kernel/process";
4
4
  export type KillSignal = "SIGTERM" | "SIGKILL" | "SIGINT";
5
5
  /** A running child of the session. */
@@ -1,4 +1,4 @@
1
- export { askGate, BuiltinCalls, NativeJournal, openTurn, placeSubmissions, recoveryNote, replayBy, restartEvent, resumeUnstartedCalls, toolBridge, toolKey, unstartedCalls, waitForSubmissions, zodShapeFromJsonSchema, } from "@parcha/agentrun-kernel/process";
1
+ export { askGate, BuiltinCalls, journalTurn, NativeJournal, openTurn, placeSubmissions, recoveryNote, replayBy, restartEvent, resumeUnstartedCalls, toolBridge, toolKey, unstartedCalls, waitForSubmissions, zodShapeFromJsonSchema, } from "@parcha/agentrun-kernel/process";
2
2
  const BRAND = Symbol.for("agentrun.claude-agent.session-machine");
3
3
  /** Mark a machine as made by this package's factory. */
4
4
  export function brandMachine(machine) {
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, verifyClaudeAgentCliAsync } 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, LOCAL_STREAM_IDLE_MS, 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, verifyClaudeAgentCliAsync } 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, LOCAL_STREAM_IDLE_MS, 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_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";
package/dist/login.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { ModelPort } from "@parcha/agentrun-kernel";
2
+ import type { TurnBudget } from "@parcha/agentrun-kernel/process";
2
3
  import { type ParentWatch } from "@parcha/agentrun-kernel/host";
3
4
  /** Where the pinned CLI keeps a login: its credentials file's directory (`CLAUDE_SECURESTORAGE_CONFIG_DIR`) and its
4
5
  * Anthropic profiles (`ANTHROPIC_CONFIG_DIR`). The CLI reads and writes both; nothing else does. */
@@ -256,8 +257,12 @@ export type ClaudeLogout = {
256
257
  * whose results the CLI sends straight back. A refusal there (a turn limit, say) halts the drive while the CLI has yet to
257
258
  * send. A response with no admission ahead of it (one the CLI sent on its own) is admitted at its `message_start`. Each
258
259
  * is booked at its `message_stop`; one the turn's end leaves open is booked as it stands, and an admission no request
259
- * took is closed as never sent when the drive ends (`settle(true)`). */
260
- export declare function loginBooking(models: Pick<ModelPort, "beforeRequest" | "afterRequest">, model: string, halt: (error: Error) => void): {
260
+ * took is closed as never sent when the drive ends (`settle(true)`).
261
+ *
262
+ * With `turn`, each response is the kernel's turn too, as a model proxy reports it: begun at its `message_start` (a
263
+ * tool call waits for it), and opened at its end with the input its request held (cached input included), its output
264
+ * and the client tool calls it made (its `tool_use` blocks). */
265
+ export declare function loginBooking(models: Pick<ModelPort, "beforeRequest" | "afterRequest">, model: string, halt: (error: Error) => void, turn?: TurnBudget): {
261
266
  /** A message is about to go to the CLI: admit the request it will make, and settle when it is admitted (a refusal
262
267
  * rejects, the drive halted already), so the message goes only once its request may. */
263
268
  sending(): Promise<void>;
package/dist/login.js CHANGED
@@ -708,8 +708,12 @@ const count = (value) => (typeof value === "number" && Number.isFinite(value) &&
708
708
  * whose results the CLI sends straight back. A refusal there (a turn limit, say) halts the drive while the CLI has yet to
709
709
  * send. A response with no admission ahead of it (one the CLI sent on its own) is admitted at its `message_start`. Each
710
710
  * is booked at its `message_stop`; one the turn's end leaves open is booked as it stands, and an admission no request
711
- * took is closed as never sent when the drive ends (`settle(true)`). */
712
- export function loginBooking(models, model, halt) {
711
+ * took is closed as never sent when the drive ends (`settle(true)`).
712
+ *
713
+ * With `turn`, each response is the kernel's turn too, as a model proxy reports it: begun at its `message_start` (a
714
+ * tool call waits for it), and opened at its end with the input its request held (cached input included), its output
715
+ * and the client tool calls it made (its `tool_use` blocks). */
716
+ export function loginBooking(models, model, halt, turn) {
713
717
  let open;
714
718
  let ahead;
715
719
  let booked = Promise.resolve();
@@ -737,6 +741,8 @@ export function loginBooking(models, model, halt) {
737
741
  open = undefined;
738
742
  if (!entry)
739
743
  return;
744
+ const { usage } = entry;
745
+ entry.span?.open({ inputTokens: usage.input + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0), outputTokens: usage.output, calls: entry.calls });
740
746
  after(entry.ticket, { ...entry.usage, usd: null, billing: "plan" }, { end: "answered", usd: null });
741
747
  if (entry.tools)
742
748
  admitAhead();
@@ -765,7 +771,12 @@ export function loginBooking(models, model, halt) {
765
771
  book();
766
772
  const ticket = ahead ?? admit();
767
773
  ahead = undefined;
768
- open = { ticket, usage: take({ input: 0, output: 0, billing: "plan" }, event.message?.usage), tools: false };
774
+ const span = turn?.begin();
775
+ open = { ticket, usage: take({ input: 0, output: 0, billing: "plan" }, event.message?.usage), tools: false, calls: 0, ...(span ? { span } : {}) };
776
+ }
777
+ else if (event.type === "content_block_start" && open) {
778
+ if (event.content_block?.type === "tool_use")
779
+ open.calls += 1;
769
780
  }
770
781
  else if (event.type === "message_delta" && open) {
771
782
  open.usage = take(open.usage, event.usage);
@@ -387,6 +387,39 @@ export function fakeSdk(fake = {}) {
387
387
  await mirror([{ type: 'last-prompt' }]);
388
388
  continue;
389
389
  }
390
+ const parallel = /^parallel (.*)$/s.exec(command);
391
+ if (parallel) {
392
+ const answer = JSON.parse(parallel[1]);
393
+ const made = answer.calls.map((c) => ({ id: `toolu_${randomUUID().slice(0, 8)}_${++calls}`, name: c.name, args: c.args ?? {} }));
394
+ const event = (e) => ({ type: 'stream_event', parent_tool_use_id: null, event: e });
395
+ yield event({ type: 'message_start', message: { id: `msg_${randomUUID().slice(0, 8)}`, type: 'message', role: 'assistant', content: [], usage: { ...answer.usage, output_tokens: 1 } } });
396
+ for (const [index, c] of made.entries()) {
397
+ yield event({ type: 'content_block_start', index, content_block: { type: 'tool_use', id: c.id, name: `mcp__hands__${c.name}`, input: {} } });
398
+ yield event({ type: 'content_block_stop', index });
399
+ }
400
+ yield event({ type: 'message_delta', delta: { stop_reason: 'tool_use', stop_sequence: null }, usage: { output_tokens: answer.usage?.output_tokens ?? 12 } });
401
+ yield event({ type: 'message_stop' });
402
+ const a = entry('assistant', { message: { role: 'assistant', content: made.map((c) => ({ type: 'tool_use', id: c.id, name: `mcp__hands__${c.name}`, input: c.args })) } });
403
+ yield { type: 'assistant', parent_tool_use_id: null, uuid: a.uuid, session_id: sessionId, message: a.message };
404
+ await mirror([a], lag);
405
+ const toolset = await tools;
406
+ const results = await Promise.all(made.map(async (c) => {
407
+ const tool = toolset.get(c.name);
408
+ return tool ? await tool.handler(c.args, { _meta: { 'claudecode/toolUseId': c.id } }) : { content: [{ type: 'text', text: `no tool ${c.name}` }], isError: true };
409
+ }));
410
+ if (signal?.aborted)
411
+ return;
412
+ const r = entry('user', { message: { role: 'user', content: made.map((c, i) => ({ type: 'tool_result', tool_use_id: c.id, is_error: !!results[i].isError, content: results[i].content[0]?.text })) } });
413
+ await mirror([r]);
414
+ yield { type: 'user', parent_tool_use_id: null, message: r.message };
415
+ const reply = made.map((c, i) => `${c.name} returned ${String(results[i].content[0]?.text ?? '').length} characters.`).join(' ');
416
+ const b = entry('assistant', { message: { role: 'assistant', content: [{ type: 'text', text: reply }] } });
417
+ await mirror([b]);
418
+ yield { type: 'assistant', parent_tool_use_id: null, uuid: b.uuid, session_id: sessionId, message: b.message };
419
+ yield { type: 'result', subtype: 'success', is_error: false, result: 'ok', session_id: sessionId, user_message_uuids: consumed, queued_turn_count: 0 };
420
+ await mirror([{ type: 'last-prompt' }]);
421
+ continue;
422
+ }
390
423
  // `whole <json>` (`{ thinking?, text }`): the answer as Claude Code hands on its non-streaming retry of a stalled
391
424
  // stream: the stalled message's start, then the answer's `assistant` messages (its thinking block, then its text
392
425
  // block, one message id), with no stream deltas.
@@ -67,9 +67,13 @@ export declare class TranscriptBuilder {
67
67
  private unclaimed;
68
68
  /** Text was said live since the last message boundary: a whole answer after it is a message of its own. */
69
69
  private saying;
70
- /** The message whose whole text was said last: its next text block is more of that message, as a streamed message's
71
- * blocks are, never a message of its own. */
72
- private wholeId;
70
+ /** The message whose whole text was said last (`id` its id, if it has one): its next text block is more of that
71
+ * message, as a streamed message's blocks are, never a message of its own. With no id, the next whole block before any
72
+ * delta, call or cut is taken as more of it: a model's next message in one turn follows a call or a cut. */
73
+ private whole;
74
+ /** What the stream said live since its message's text was last claimed or cut: a whole retry that begins with it (the
75
+ * CLI asking again after the stream stalled) says only the rest, so the stalled part is not said twice. */
76
+ private partial;
73
77
  constructor(sink: TranscriptSink);
74
78
  /** One message from `query()`. Returns how the turn ended for a `result`. */
75
79
  observe(m: SdkMessage): TurnEnd | undefined;
@@ -91,8 +95,10 @@ export declare class TranscriptBuilder {
91
95
  /**
92
96
  * A text block of an `assistant` message, said live when none of its text streamed: the CLI asks again without
93
97
  * streaming when a streamed request stalls, and that answer comes whole. A message with an id streamed when a delta
94
- * came under its `message_start`; one with none, when deltas came since the last text block. A whole message's text
95
- * blocks are one message live, as a streamed one's are.
98
+ * came under its `message_start`; one with none, when the deltas since the last text block say its text exactly (a
99
+ * streamed block's text is its deltas; a whole retry's runs past them). A whole message's text
100
+ * blocks are one message live, as a streamed one's are. A whole retry that begins with what its stalled stream already
101
+ * said goes on from there, as the same message: only the rest is said.
96
102
  */
97
103
  private sayUnstreamed;
98
104
  private call;
@@ -25,9 +25,13 @@ export class TranscriptBuilder {
25
25
  unclaimed = false;
26
26
  /** Text was said live since the last message boundary: a whole answer after it is a message of its own. */
27
27
  saying = false;
28
- /** The message whose whole text was said last: its next text block is more of that message, as a streamed message's
29
- * blocks are, never a message of its own. */
30
- wholeId;
28
+ /** The message whose whole text was said last (`id` its id, if it has one): its next text block is more of that
29
+ * message, as a streamed message's blocks are, never a message of its own. With no id, the next whole block before any
30
+ * delta, call or cut is taken as more of it: a model's next message in one turn follows a call or a cut. */
31
+ whole;
32
+ /** What the stream said live since its message's text was last claimed or cut: a whole retry that begins with it (the
33
+ * CLI asking again after the stream stalled) says only the rest, so the stalled part is not said twice. */
34
+ partial = '';
31
35
  constructor(sink) {
32
36
  this.sink = sink;
33
37
  }
@@ -44,14 +48,17 @@ export class TranscriptBuilder {
44
48
  if (ev?.type === 'message_delta' && ev.delta?.stop_reason === 'max_tokens')
45
49
  this.cutPending = true;
46
50
  if (ev?.type === 'content_block_delta' && ev.delta?.type === 'text_delta' && ev.delta.text) {
47
- if (this.cutPending)
51
+ if (this.cutPending) {
48
52
  this.sink.live({ type: 'text_end' });
53
+ this.partial = '';
54
+ }
49
55
  this.cutPending = false;
50
56
  if (this.streaming !== undefined)
51
57
  this.streamed.add(this.streaming);
58
+ this.partial += ev.delta.text;
52
59
  this.unclaimed = true;
53
60
  this.saying = true;
54
- this.wholeId = undefined;
61
+ this.whole = undefined;
55
62
  this.sink.live({ type: 'text', delta: ev.delta.text });
56
63
  }
57
64
  return undefined;
@@ -98,7 +105,8 @@ export class TranscriptBuilder {
98
105
  this.cutPending = false;
99
106
  this.saying = false;
100
107
  this.unclaimed = false;
101
- this.wholeId = undefined;
108
+ this.whole = undefined;
109
+ this.partial = '';
102
110
  // The turn's final answer still cut: the CLI's recovery of it was spent.
103
111
  const output = m.usage?.output_tokens;
104
112
  const cut = !isError && m.stop_reason === 'max_tokens' ? { stopReason: 'length', ...(typeof output === 'number' ? { outputTokens: output } : {}) } : {};
@@ -147,28 +155,40 @@ export class TranscriptBuilder {
147
155
  /**
148
156
  * A text block of an `assistant` message, said live when none of its text streamed: the CLI asks again without
149
157
  * streaming when a streamed request stalls, and that answer comes whole. A message with an id streamed when a delta
150
- * came under its `message_start`; one with none, when deltas came since the last text block. A whole message's text
151
- * blocks are one message live, as a streamed one's are.
158
+ * came under its `message_start`; one with none, when the deltas since the last text block say its text exactly (a
159
+ * streamed block's text is its deltas; a whole retry's runs past them). A whole message's text
160
+ * blocks are one message live, as a streamed one's are. A whole retry that begins with what its stalled stream already
161
+ * said goes on from there, as the same message: only the rest is said.
152
162
  */
153
163
  sayUnstreamed(id, text) {
154
- const streamed = id === undefined ? this.unclaimed : this.streamed.has(id);
164
+ const partial = this.partial;
165
+ this.partial = '';
166
+ const streamed = id === undefined ? this.unclaimed && text === partial : this.streamed.has(id);
155
167
  this.unclaimed = false;
156
- if (streamed)
168
+ // A block whose text streamed is said already, and is still this message's: a whole block after it, with no delta
169
+ // between, is more of it (a retry's first block that says exactly what its stalled stream did, then the rest).
170
+ if (streamed) {
171
+ this.whole = { id };
157
172
  return;
158
- const more = id !== undefined && id === this.wholeId;
159
- if (this.cutPending || (this.saying && !more))
173
+ }
174
+ const more = this.whole !== undefined && this.whole.id === id;
175
+ const goesOn = !more && !this.cutPending && partial !== '' && text.startsWith(partial);
176
+ if (!goesOn && (this.cutPending || (this.saying && !more)))
160
177
  this.sink.live({ type: 'text_end' });
161
178
  this.cutPending = false;
162
179
  this.saying = true;
163
- this.wholeId = id;
164
- this.sink.live({ type: 'text', delta: text });
180
+ this.whole = { id };
181
+ const rest = goesOn ? text.slice(partial.length) : text;
182
+ if (rest)
183
+ this.sink.live({ type: 'text', delta: rest });
165
184
  }
166
185
  call(id, name) {
167
186
  if (this.written.has(id))
168
187
  return;
169
188
  this.written.add(id);
170
189
  this.saying = false;
171
- this.wholeId = undefined;
190
+ this.whole = undefined;
191
+ this.partial = '';
172
192
  this.sink.message({ type: 'message', role: 'assistant', text: this.said, toolCalls: [{ id, name }] });
173
193
  this.said = '';
174
194
  for (const w of this.waiters.get(id) ?? [])
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-harness-claude",
3
- "version": "0.1.0-beta.62",
3
+ "version": "0.1.0-beta.63",
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.62"
51
+ "@parcha/agentrun-kernel": "0.1.0-beta.63"
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.62"
80
+ "@parcha/agentrun-dsl": "0.1.0-beta.63"
81
81
  }
82
82
  }