@parcha/agentrun-harness-claude 0.1.0-beta.61 → 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,29 @@
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
+
17
+ ## 0.1.0-beta.62 (2026-11-26)
18
+
19
+ **Breaking:**
20
+
21
+ - `claudeLogout` answers `{ signedOut, leftoverGone }` (the exported type `ClaudeLogout`) where it answered a boolean. `signedOut` is the boolean it answered before: the CLI's own sign-out exited 0 within its limit. `leftoverGone` says whether the Keychain item a sign-in left under the account `unknown` at AgentRun's own folder on macOS is gone. Who breaks: a caller that reads the answer as a boolean, since an object is always truthy. What to do: read `signedOut` where you read the answer, and tell the person to delete the item in Keychain Access when `leftoverGone` is false. <!-- changes/claude-logout-answer-object.md -->
22
+
23
+ **Changes:**
24
+
25
+ - A claude-agent run on a local model (an Ollama model, or any model AgentRun's route translates onto Anthropic's Messages) no longer ends with no answer. On a slow machine such a model can send nothing on its stream for over five minutes while it loads, reads its prompt or thinks. The CLI gave the stream up at five minutes, asked again without streaming, and got the answer whole. AgentRun only heard the streamed text, so the run completed at $0 with `final_answer: null` and no answer on its timeline. The text of a message that comes whole is now said once, as the turn's answer, and a message whose text did stream is never said twice. This holds on any model: a claude-agent run whose CLI fell back to a non-streaming retry on a provider's own Anthropic model lost its answer the same way. On a translated model the CLI now waits up to 30 minutes on a silent stream (`CLAUDE_STREAM_IDLE_TIMEOUT_MS`), so the first request is no longer thrown away. On a provider's own Messages the CLI keeps its default. <!-- changes/claude-local-answer.md -->
26
+ - On macOS, a sign-out that arrives while a status check is deleting the Keychain item a sign-in left under the account `unknown` waits on that delete, and when it fails or is killed at its limit, tries once more itself. Before, the sign-out answered with the item, which holds a refresh token, still in the login keychain. When the item may remain, serve's sign-out is not confirmed, and its words name the item's exact service, to search in Keychain Access or delete with one `security` command, so they never point at the person's own CLI's item. The harness exports that service as `claudeKeychainService`. It hashes the folder in Unicode's composed form (NFC), as the CLI does, so a folder path with a decomposed character no longer sends the delete to a service no item has, which answered the item gone while it stayed. <!-- changes/claude-signout-drop-retry.md -->
27
+
5
28
  ## 0.1.0-beta.61 (2026-11-26)
6
29
 
7
30
  - On macOS, when `security` hangs on the delete of the Keychain item a sign-in left under the account `unknown`, signed-in status checks no longer wait on it each time: checks at once share one delete, and after a delete is killed or fails, status checks leave the item for ten minutes (a sign-in still asks at once). The CLI's own sign-out at AgentRun's own folder now removes that leftover item too. <!-- changes/claude-keychain-drop-backoff.md -->
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,6 +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
  }
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;
116
128
  /** The thinking levels a session runs at: the SDK's effort levels, with adaptive thinking. There is no off. */
117
129
  export type ClaudeAgentThinking = "low" | "medium" | "high" | "xhigh" | "max";
118
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,6 +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 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;
61
64
  const THINKING = new Set(["low", "medium", "high", "xhigh", "max"]);
62
65
  /** A session's level: the node's thinking, else its effort (minimal thinks at low, never at nothing), else the adapter's. */
63
66
  export function thinkingOf(spec, fallback) {
@@ -317,6 +320,9 @@ export function claudeAgentAdapter(options) {
317
320
  // With skills, the model also reads their files (read_skill_file), from the session's own copy of them.
318
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;
319
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);
320
326
  // The CLI's own tools offered to the model: Skill only when the session has skills, WebSearch only when it is on.
321
327
  const builtins = [...(skills.length ? ["Skill"] : []), ...(webSearch ? ["WebSearch"] : [])];
322
328
  const acquire = localMachine({
@@ -327,6 +333,7 @@ export function claudeAgentAdapter(options) {
327
333
  // On a login, no proxy: the CLI calls Anthropic itself.
328
334
  ...(provider ? { proxy: {
329
335
  hooks: io.models,
336
+ ...(budget.resultBudget?.turn ? { turn: budget.resultBudget.turn } : {}),
330
337
  tools: tools.map((t) => t.name),
331
338
  ...(builtins.length ? { builtins } : {}),
332
339
  ...(webSearch ? { webSearch: true, ...(options.webSearchAllowance !== undefined ? { webSearchAllowance: options.webSearchAllowance } : {}) } : {}),
@@ -355,6 +362,7 @@ export function claudeAgentAdapter(options) {
355
362
  },
356
363
  tools: tools.map((tool) => claudeTool(tool, io, maxImageBytes, calls)),
357
364
  ...(spec.deferCatalog === undefined ? {} : { deferCatalog: spec.deferCatalog }),
365
+ ...budget,
358
366
  builtins: false,
359
367
  // Off by name too, besides tools: []: the pinned CLI's tools that neither the harness's allowlist nor its off list
360
368
  // decide (test/tool-off.test.mjs pins the CLI's whole tool set against these lists), but WebSearch when it is on.
@@ -363,6 +371,10 @@ export function claudeAgentAdapter(options) {
363
371
  model: modelFor(spec),
364
372
  ...(skills.length ? { skills: { plugin: join(dir, "plugin"), names: writeSkillsPlugin(join(dir, "plugin"), skills) } } : {}),
365
373
  ...(options.smallModel ? { smallModel: options.smallModel } : {}),
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 } : {}),
366
378
  ...(spec.system.length ? { instructions: spec.system.join("\n\n") } : {}),
367
379
  ...(provider ? { credential: async () => provider.credential(), gatewayUrl: provider.origin } : { login: { at: login, models: io.models } }),
368
380
  executable,
package/dist/env.d.ts CHANGED
@@ -57,6 +57,12 @@ export interface DurableEnvOptions {
57
57
  * `CLAUDE_CODE_MAX_MCP_DESCRIPTION_LENGTH` says more; above that, it's set to this, so the model reads each one whole.
58
58
  */
59
59
  toolDescriptionMax?: number;
60
+ /**
61
+ * How long the CLI waits on a streamed answer that sends nothing (`CLAUDE_STREAM_IDLE_TIMEOUT_MS`; the CLI's own
62
+ * floor is 5 minutes, its ceiling 30). Unset: the CLI's default, 5 minutes, after which it drops the stream and asks
63
+ * again without streaming.
64
+ */
65
+ streamIdleMs?: number;
60
66
  /**
61
67
  * The most tokens an MCP tool's result may take (`MAX_MCP_OUTPUT_TOKENS`). Past it the CLI saves the result to a file
62
68
  * and tells the model to read it, or cuts a result that holds an image; its default is 25,000.
package/dist/env.js CHANGED
@@ -99,6 +99,8 @@ export function durableEnv(options) {
99
99
  });
100
100
  if (options.toolDescriptionMax !== undefined && options.toolDescriptionMax > MCP_DESCRIPTION_CUT)
101
101
  env.CLAUDE_CODE_MAX_MCP_DESCRIPTION_LENGTH = String(options.toolDescriptionMax);
102
+ if (options.streamIdleMs !== undefined)
103
+ env.CLAUDE_STREAM_IDLE_TIMEOUT_MS = String(Math.max(1, Math.floor(options.streamIdleMs)));
102
104
  if (options.mcpOutputTokens !== undefined)
103
105
  env.MAX_MCP_OUTPUT_TOKENS = String(Math.max(1, Math.floor(options.mcpOutputTokens)));
104
106
  if (options.bashTimeoutMs !== undefined) {
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
@@ -191,6 +195,9 @@ export interface ClaudeCodeHarnessOptions {
191
195
  model?: string;
192
196
  /** The model of the CLI's small background calls (`nativeModelId` too). Default `model`. */
193
197
  smallModel?: string;
198
+ /** How long the CLI waits on a silent streamed answer before it gives the stream up (durableEnv's `streamIdleMs`).
199
+ * Default the CLI's own, 5 minutes. */
200
+ streamIdleMs?: number;
194
201
  /** Appended to Claude Code's own system prompt (the `claude_code` preset). */
195
202
  instructions?: string;
196
203
  /** The provider credential, read per model request, in the Function. Default `gatewayCredential`. */
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
  });
@@ -513,6 +517,7 @@ export function claudeCodeHarness(options = {}) {
513
517
  model,
514
518
  ...(smallModel ? { smallModel } : {}),
515
519
  ...(sandbox.commandTimeoutMs ? { bashTimeoutMs: sandbox.commandTimeoutMs } : {}),
520
+ ...(options.streamIdleMs !== undefined ? { streamIdleMs: options.streamIdleMs } : {}),
516
521
  ...(sandbox.env ? { extra: sandbox.env } : {}),
517
522
  toolDescriptionMax: Math.max(0, ...bridge.tools.map((t) => t.description.length)),
518
523
  // A host tool's result within the host's bound reaches the model whole (each tool is listed with it, too).
@@ -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";
@@ -7,8 +7,8 @@ export { findClaudeExecutable as claudeAgentExecutable, platformSuffix as claude
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";
9
9
  export type { ChildCommand, ConfineChild } from "./host/machine.js";
10
- export { ClaudeLoginNoStatus, ClaudeLoginTimedOut, claudeLoginStatus, claudeLogout, LOGIN_TOKEN_REFUSED as CLAUDE_LOGIN_TOKEN_REFUSED, loginByToken as claudeLoginByToken, sweepClaudeStatusFolders, loginCommand as claudeLoginCommand, loginEnv as claudeLoginEnv, parseLoginStatus as parseClaudeLoginStatus, startClaudeLogin } from "./login.js";
11
- export type { ClaudeAgentLogin, ClaudeLoginStatus, ClaudeLoginToken } from "./login.js";
10
+ export { ClaudeLoginNoStatus, ClaudeLoginTimedOut, claudeLoginStatus, claudeLogout, keychainService as claudeKeychainService, LOGIN_TOKEN_REFUSED as CLAUDE_LOGIN_TOKEN_REFUSED, loginByToken as claudeLoginByToken, sweepClaudeStatusFolders, loginCommand as claudeLoginCommand, loginEnv as claudeLoginEnv, parseLoginStatus as parseClaudeLoginStatus, startClaudeLogin } from "./login.js";
11
+ export type { ClaudeAgentLogin, ClaudeLoginStatus, ClaudeLoginToken, ClaudeLogout } from "./login.js";
12
12
  export { LOGIN_REFRESH as CLAUDE_LOGIN_REFRESH } from "./login-refresh.js";
13
13
  export { listedTools, MCP_OUTPUT_TOKENS, RESULT_SIZE_KEY, toolServer, type ToolServerModules } from "./host/tool-server.js";
14
14
  export type { ServedTool } from "./host/tool-server.js";
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
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";
6
6
  export { anthropicPolicy, CLAUDE_WEB_SEARCH_TOOL, OWN_TOOL_PREFIX, thinks, withWebSearches } from "./host/policy.js";
7
- export { ClaudeLoginNoStatus, ClaudeLoginTimedOut, claudeLoginStatus, claudeLogout, LOGIN_TOKEN_REFUSED as CLAUDE_LOGIN_TOKEN_REFUSED, loginByToken as claudeLoginByToken, sweepClaudeStatusFolders, loginCommand as claudeLoginCommand, loginEnv as claudeLoginEnv, parseLoginStatus as parseClaudeLoginStatus, startClaudeLogin } from "./login.js";
7
+ export { ClaudeLoginNoStatus, ClaudeLoginTimedOut, claudeLoginStatus, claudeLogout, keychainService as claudeKeychainService, LOGIN_TOKEN_REFUSED as CLAUDE_LOGIN_TOKEN_REFUSED, loginByToken as claudeLoginByToken, sweepClaudeStatusFolders, loginCommand as claudeLoginCommand, loginEnv as claudeLoginEnv, parseLoginStatus as parseClaudeLoginStatus, startClaudeLogin } from "./login.js";
8
8
  export { LOGIN_REFRESH as CLAUDE_LOGIN_REFRESH } from "./login-refresh.js";
9
9
  export { listedTools, MCP_OUTPUT_TOKENS, RESULT_SIZE_KEY, toolServer } from "./host/tool-server.js";
10
10
  export { SIGN_IN_MS as CLAUDE_SIGN_IN_MS, signInEnv as claudeSignInEnv } from "./login.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. */
@@ -128,24 +129,36 @@ export declare function sweepClaudeStatusFolders(options?: {
128
129
  * the CLI reads its tokens from the login keychain, which is under that home: in any other home (an empty one, a
129
130
  * session's) it finds no keychain and reads signed out, whatever the variables. */
130
131
  export declare const personHome: (login: ClaudeAgentLogin) => string;
132
+ /** The service of `login`'s Keychain items on macOS, as the CLI names it from the login's credentials dir there
133
+ * (loginEnv): `Claude Code-credentials-<first 8 hex of the folder's sha256>`, or undefined where that dir is empty (the
134
+ * item with no suffix, the person's own CLI's on its default folder). The CLI hashes the folder in Unicode's composed
135
+ * form (`.normalize("NFC")`), so a path with a decomposed character (as a folder name from macOS's Finder may have)
136
+ * names the same item as its composed form; hashed as written it would name a service no item has. A hash of the
137
+ * folder, so it holds no path and no secret, and words for a person may name it. */
138
+ export declare function keychainService(login: ClaudeAgentLogin): string | undefined;
131
139
  /** On macOS, at AgentRun's own folder (`own`) alone, delete the login's Keychain item under the account "unknown", which
132
140
  * a sign-in left there when the CLI was started with no USER (loginUser), and which nothing reads now: `security
133
- * delete-generic-password -a unknown -s <the item's service>`, the service the CLI names from the folder (`Claude
134
- * Code-credentials-<first 8 hex of the folder's sha256>`), in the person's home (personHome), whose login keychain holds
141
+ * delete-generic-password -a unknown -s <the item's service>`, the service the CLI names from the folder
142
+ * (keychainService), in the person's home (personHome), whose login keychain holds
135
143
  * it. Called once the item under the person's account is there (the sign-in exited 0, a status check read signed in),
136
144
  * and at the CLI's own sign-out (claudeLogout), after which no status check reads signed in to call it.
137
145
  * Never at the person's own CLI's places, whose "unknown" item may be theirs, never the item with no suffix, never an
138
146
  * item of any other account, and never where the user this server runs as is named "unknown" itself. Nothing is thrown.
139
147
  * An item deleted, or found gone ("not found", exit 44), is not asked again in this process. One delete runs per item at
140
- * a time: a call while it runs waits on that one and starts none. One whose delete was killed at its limit, failed or
141
- * never started is still there: a call that a person made (`asked`: a sign-in that exited 0, a sign-out) asks again at
142
- * once, a status check only DROP_BACKOFF_MS after that delete ended, measured on `now` (Date.now by default). */
148
+ * a time: a call while it runs waits on that one and starts none of its own beside it. One whose delete was killed at its
149
+ * limit, failed or never started is still there: a call that a person made (`asked`: a sign-in that exited 0, a
150
+ * sign-out) asks again at once, and so does one that waited on a delete that left it, once (a status check's, say, that
151
+ * a sign-out arrived during); a status check only DROP_BACKOFF_MS after that delete ended, measured on `now` (Date.now
152
+ * by default), and never after one it waited on.
153
+ * Answers whether no such item is left: true once it was deleted or found gone, in this call or before in this process,
154
+ * and where there is none for it to drop (another platform or place, the user named "unknown" or not named); false
155
+ * where it may remain (its delete was killed, failed or never started, or a status check left it to the back-off). */
143
156
  export declare function dropUnknownItem(login: ClaudeAgentLogin, options: {
144
157
  path: string;
145
158
  platform?: NodeJS.Platform;
146
159
  asked?: boolean;
147
160
  now?: () => number;
148
- }): Promise<void>;
161
+ }): Promise<boolean>;
149
162
  /** Ask the CLI at `cli` whether it is signed in at `login`: `auth status --json`, with only PATH, the user (loginUser)
150
163
  * and the login's variables beside it, in the person's home (personHome) on every place and platform.
151
164
  * The CLI rewrites its account file (`.claude.json`, in its config dir) whenever that file's migration number is not its
@@ -217,25 +230,39 @@ export declare const LOGOUT_MS = 15000;
217
230
  * the person's home (personHome), so it removes what that sign-in kept where it kept it: the credentials file in the
218
231
  * login's credentials dir or, on macOS, the Keychain item named from it under that user's account, and the account in
219
232
  * the config dir's `.claude.json`. Nothing of it
220
- * is read but how it ended: true when it exited 0 within `timeoutMs` (LOGOUT_MS by default), false when it exited
221
- * otherwise, never started, or was ended at the limit (SIGTERM, then SIGKILL a second later). Never throws.
233
+ * is read but how it ended: `signedOut` true when it exited 0 within `timeoutMs` (LOGOUT_MS by default), false when it
234
+ * exited otherwise, never started, or was ended at the limit (SIGTERM, then SIGKILL a second later). Never throws.
222
235
  * Then, at AgentRun's own folder on macOS, the item a sign-in left there under "unknown", which holds a refresh token,
223
236
  * is deleted too (dropUnknownItem, with its refusals), whatever the CLI said and whatever back-off a status check's
224
- * killed delete left, since a person asked and no status check reads signed in after a sign-out to drop it. The answer
225
- * waits on that delete DROP_MS at most. `platform`: as signInEnv's. */
237
+ * killed delete left, since a person asked and no status check reads signed in after a sign-out to drop it; where a
238
+ * status check's delete of it runs, the sign-out waits on that one and asks once more should it leave the item.
239
+ * `leftoverGone` says whether no such item is left (dropUnknownItem's answer: true where there is none to drop, false
240
+ * where its delete was killed or failed, or threw), so the caller can tell the person to delete it by hand. Values
241
+ * only: no name or token. The answer waits on that delete DROP_MS at most, twice that where it waited on a status
242
+ * check's first. `platform`: as signInEnv's. */
226
243
  export declare function claudeLogout(cli: string, login: ClaudeAgentLogin, options?: {
227
244
  timeoutMs?: number;
228
245
  path?: string;
229
246
  platform?: NodeJS.Platform;
230
- }): Promise<boolean>;
247
+ }): Promise<ClaudeLogout>;
248
+ /** claudeLogout's answer: the CLI confirmed its own sign-out (`signedOut`), and no Keychain item a sign-in left under
249
+ * "unknown" at AgentRun's own folder is left (`leftoverGone`). */
250
+ export type ClaudeLogout = {
251
+ signedOut: boolean;
252
+ leftoverGone: boolean;
253
+ };
231
254
  /** How a session on a login books its requests: no proxy sees them, so each response the CLI streams is booked from its
232
255
  * own events, billed to the plan, at no price here. No proxy can hold a request back either, so a request is admitted
233
256
  * before the CLI can send it: when a message goes to the CLI (`sending`), and when a response stops for its tool calls,
234
257
  * whose results the CLI sends straight back. A refusal there (a turn limit, say) halts the drive while the CLI has yet to
235
258
  * send. A response with no admission ahead of it (one the CLI sent on its own) is admitted at its `message_start`. Each
236
259
  * is booked at its `message_stop`; one the turn's end leaves open is booked as it stands, and an admission no request
237
- * took is closed as never sent when the drive ends (`settle(true)`). */
238
- 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): {
239
266
  /** A message is about to go to the CLI: admit the request it will make, and settle when it is admitted (a refusal
240
267
  * rejects, the drive halted already), so the message goes only once its request may. */
241
268
  sending(): Promise<void>;
package/dist/login.js CHANGED
@@ -312,58 +312,81 @@ const dropping = new Map();
312
312
  /** For each item whose last delete was killed or failed, by the same key: when a status check may ask again, on the
313
313
  * clock of the call that started that delete. */
314
314
  const dropAfter = new Map();
315
+ /** The service of `login`'s Keychain items on macOS, as the CLI names it from the login's credentials dir there
316
+ * (loginEnv): `Claude Code-credentials-<first 8 hex of the folder's sha256>`, or undefined where that dir is empty (the
317
+ * item with no suffix, the person's own CLI's on its default folder). The CLI hashes the folder in Unicode's composed
318
+ * form (`.normalize("NFC")`), so a path with a decomposed character (as a folder name from macOS's Finder may have)
319
+ * names the same item as its composed form; hashed as written it would name a service no item has. A hash of the
320
+ * folder, so it holds no path and no secret, and words for a person may name it. */
321
+ export function keychainService(login) {
322
+ const folder = loginEnv(login, "darwin").CLAUDE_SECURESTORAGE_CONFIG_DIR;
323
+ return folder ? `Claude Code-credentials-${createHash("sha256").update(folder.normalize("NFC")).digest("hex").slice(0, 8)}` : undefined;
324
+ }
315
325
  /** On macOS, at AgentRun's own folder (`own`) alone, delete the login's Keychain item under the account "unknown", which
316
326
  * a sign-in left there when the CLI was started with no USER (loginUser), and which nothing reads now: `security
317
- * delete-generic-password -a unknown -s <the item's service>`, the service the CLI names from the folder (`Claude
318
- * Code-credentials-<first 8 hex of the folder's sha256>`), in the person's home (personHome), whose login keychain holds
327
+ * delete-generic-password -a unknown -s <the item's service>`, the service the CLI names from the folder
328
+ * (keychainService), in the person's home (personHome), whose login keychain holds
319
329
  * it. Called once the item under the person's account is there (the sign-in exited 0, a status check read signed in),
320
330
  * and at the CLI's own sign-out (claudeLogout), after which no status check reads signed in to call it.
321
331
  * Never at the person's own CLI's places, whose "unknown" item may be theirs, never the item with no suffix, never an
322
332
  * item of any other account, and never where the user this server runs as is named "unknown" itself. Nothing is thrown.
323
333
  * An item deleted, or found gone ("not found", exit 44), is not asked again in this process. One delete runs per item at
324
- * a time: a call while it runs waits on that one and starts none. One whose delete was killed at its limit, failed or
325
- * never started is still there: a call that a person made (`asked`: a sign-in that exited 0, a sign-out) asks again at
326
- * once, a status check only DROP_BACKOFF_MS after that delete ended, measured on `now` (Date.now by default). */
334
+ * a time: a call while it runs waits on that one and starts none of its own beside it. One whose delete was killed at its
335
+ * limit, failed or never started is still there: a call that a person made (`asked`: a sign-in that exited 0, a
336
+ * sign-out) asks again at once, and so does one that waited on a delete that left it, once (a status check's, say, that
337
+ * a sign-out arrived during); a status check only DROP_BACKOFF_MS after that delete ended, measured on `now` (Date.now
338
+ * by default), and never after one it waited on.
339
+ * Answers whether no such item is left: true once it was deleted or found gone, in this call or before in this process,
340
+ * and where there is none for it to drop (another platform or place, the user named "unknown" or not named); false
341
+ * where it may remain (its delete was killed, failed or never started, or a status check left it to the back-off). */
327
342
  export async function dropUnknownItem(login, options) {
328
343
  if ((options.platform ?? process.platform) !== "darwin" || login.own !== true)
329
- return;
330
- const folder = loginEnv(login, "darwin").CLAUDE_SECURESTORAGE_CONFIG_DIR;
344
+ return true;
345
+ const service = keychainService(login);
331
346
  const user = loginUser();
332
- if (!folder || user.USER === undefined || user.USER === "unknown")
333
- return;
334
- const service = `Claude Code-credentials-${createHash("sha256").update(folder).digest("hex").slice(0, 8)}`;
347
+ if (service === undefined || user.USER === undefined || user.USER === "unknown")
348
+ return true;
335
349
  const HOME = personHome(login);
336
350
  const key = JSON.stringify([HOME, service]);
337
351
  if (dropped.has(key))
338
- return;
339
- const running = dropping.get(key);
340
- if (running)
341
- return running;
352
+ return true;
342
353
  const now = options.now ?? Date.now;
343
- if (options.asked !== true && now() < (dropAfter.get(key) ?? -Infinity))
344
- return;
345
- const deleting = new Promise((resolve) => {
346
- const left = () => {
347
- dropAfter.set(key, now() + DROP_BACKOFF_MS);
348
- resolve();
349
- };
350
- try {
351
- const child = spawn("security", ["delete-generic-password", "-a", "unknown", "-s", service], { env: { PATH: options.path, HOME, ...user }, stdio: "ignore", timeout: DROP_MS, killSignal: "SIGKILL" });
352
- child.once("error", left);
353
- child.once("close", (code) => {
354
- if (code !== 0 && code !== 44)
355
- return left();
356
- dropped.add(key);
357
- dropAfter.delete(key);
354
+ const start = () => {
355
+ const deleting = new Promise((resolve) => {
356
+ const left = () => {
357
+ dropAfter.set(key, now() + DROP_BACKOFF_MS);
358
358
  resolve();
359
- });
360
- }
361
- catch {
362
- left();
363
- }
364
- }).finally(() => dropping.delete(key));
365
- dropping.set(key, deleting);
366
- return deleting;
359
+ };
360
+ try {
361
+ const child = spawn("security", ["delete-generic-password", "-a", "unknown", "-s", service], { env: { PATH: options.path, HOME, ...user }, stdio: "ignore", timeout: DROP_MS, killSignal: "SIGKILL" });
362
+ child.once("error", left);
363
+ child.once("close", (code) => {
364
+ if (code !== 0 && code !== 44)
365
+ return left();
366
+ dropped.add(key);
367
+ dropAfter.delete(key);
368
+ resolve();
369
+ });
370
+ }
371
+ catch {
372
+ left();
373
+ }
374
+ }).finally(() => dropping.delete(key));
375
+ dropping.set(key, deleting);
376
+ return deleting;
377
+ };
378
+ const running = dropping.get(key);
379
+ if (running) {
380
+ await running;
381
+ // A status check only waits. A call a person made, whose wait left the item (that delete was killed or failed), asks
382
+ // once more: after a sign-out no status check reads signed in to ask again. Once, joining a delete another such call
383
+ // started meanwhile rather than starting a second.
384
+ if (options.asked === true && !dropped.has(key))
385
+ await (dropping.get(key) ?? start());
386
+ }
387
+ else if (options.asked === true || now() >= (dropAfter.get(key) ?? -Infinity))
388
+ await start();
389
+ return dropped.has(key);
367
390
  }
368
391
  /** Ask the CLI at `cli` whether it is signed in at `login`: `auth status --json`, with only PATH, the user (loginUser)
369
392
  * and the login's variables beside it, in the person's home (personHome) on every place and platform.
@@ -632,18 +655,22 @@ export const LOGOUT_MS = LOGIN_STATUS_MS;
632
655
  * the person's home (personHome), so it removes what that sign-in kept where it kept it: the credentials file in the
633
656
  * login's credentials dir or, on macOS, the Keychain item named from it under that user's account, and the account in
634
657
  * the config dir's `.claude.json`. Nothing of it
635
- * is read but how it ended: true when it exited 0 within `timeoutMs` (LOGOUT_MS by default), false when it exited
636
- * otherwise, never started, or was ended at the limit (SIGTERM, then SIGKILL a second later). Never throws.
658
+ * is read but how it ended: `signedOut` true when it exited 0 within `timeoutMs` (LOGOUT_MS by default), false when it
659
+ * exited otherwise, never started, or was ended at the limit (SIGTERM, then SIGKILL a second later). Never throws.
637
660
  * Then, at AgentRun's own folder on macOS, the item a sign-in left there under "unknown", which holds a refresh token,
638
661
  * is deleted too (dropUnknownItem, with its refusals), whatever the CLI said and whatever back-off a status check's
639
- * killed delete left, since a person asked and no status check reads signed in after a sign-out to drop it. The answer
640
- * waits on that delete DROP_MS at most. `platform`: as signInEnv's. */
662
+ * killed delete left, since a person asked and no status check reads signed in after a sign-out to drop it; where a
663
+ * status check's delete of it runs, the sign-out waits on that one and asks once more should it leave the item.
664
+ * `leftoverGone` says whether no such item is left (dropUnknownItem's answer: true where there is none to drop, false
665
+ * where its delete was killed or failed, or threw), so the caller can tell the person to delete it by hand. Values
666
+ * only: no name or token. The answer waits on that delete DROP_MS at most, twice that where it waited on a status
667
+ * check's first. `platform`: as signInEnv's. */
641
668
  export async function claudeLogout(cli, login, options = {}) {
642
669
  const path = options.path ?? process.env.PATH ?? "/usr/bin:/bin";
643
670
  // After the CLI's own sign-out, not beside it: both delete in the one login keychain.
644
671
  const signedOut = await cliLogout(cli, login, path, options);
645
- await dropUnknownItem(login, { path, asked: true, ...(options.platform ? { platform: options.platform } : {}) }).catch(() => { });
646
- return signedOut;
672
+ const leftoverGone = await dropUnknownItem(login, { path, asked: true, ...(options.platform ? { platform: options.platform } : {}) }).catch(() => false);
673
+ return { signedOut, leftoverGone };
647
674
  }
648
675
  /** The CLI's own `auth logout` of claudeLogout: true when it exited 0 within its limit. Never throws. */
649
676
  function cliLogout(cli, login, path, options) {
@@ -681,8 +708,12 @@ const count = (value) => (typeof value === "number" && Number.isFinite(value) &&
681
708
  * whose results the CLI sends straight back. A refusal there (a turn limit, say) halts the drive while the CLI has yet to
682
709
  * send. A response with no admission ahead of it (one the CLI sent on its own) is admitted at its `message_start`. Each
683
710
  * is booked at its `message_stop`; one the turn's end leaves open is booked as it stands, and an admission no request
684
- * took is closed as never sent when the drive ends (`settle(true)`). */
685
- 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) {
686
717
  let open;
687
718
  let ahead;
688
719
  let booked = Promise.resolve();
@@ -710,6 +741,8 @@ export function loginBooking(models, model, halt) {
710
741
  open = undefined;
711
742
  if (!entry)
712
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 });
713
746
  after(entry.ticket, { ...entry.usage, usd: null, billing: "plan" }, { end: "answered", usd: null });
714
747
  if (entry.tools)
715
748
  admitAhead();
@@ -738,7 +771,12 @@ export function loginBooking(models, model, halt) {
738
771
  book();
739
772
  const ticket = ahead ?? admit();
740
773
  ahead = undefined;
741
- 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;
742
780
  }
743
781
  else if (event.type === "message_delta" && open) {
744
782
  open.usage = take(open.usage, event.usage);
@@ -387,6 +387,56 @@ 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
+ }
423
+ // `whole <json>` (`{ thinking?, text }`): the answer as Claude Code hands on its non-streaming retry of a stalled
424
+ // stream: the stalled message's start, then the answer's `assistant` messages (its thinking block, then its text
425
+ // block, one message id), with no stream deltas.
426
+ const whole = /^whole (.*)$/s.exec(command);
427
+ if (whole) {
428
+ const answer = JSON.parse(whole[1]);
429
+ yield { type: 'stream_event', parent_tool_use_id: null, event: { type: 'message_start', message: { id: `msg_${uuid().slice(0, 8)}`, role: 'assistant', content: [] } } };
430
+ const id = `msg_${uuid().slice(0, 8)}`;
431
+ const blocks = [...(answer.thinking ? [{ type: 'thinking', thinking: answer.thinking, signature: '' }] : []), { type: 'text', text: answer.text }];
432
+ const b = entry('assistant', { message: { id, role: 'assistant', content: blocks, stop_reason: 'end_turn' } });
433
+ await mirror([b]);
434
+ for (const block of blocks)
435
+ yield { type: 'assistant', parent_tool_use_id: null, uuid: b.uuid, session_id: sessionId, message: { id, role: 'assistant', content: [block] } };
436
+ yield { type: 'result', subtype: 'success', is_error: false, result: answer.text, session_id: sessionId, user_message_uuids: consumed, queued_turn_count: 0 };
437
+ await mirror([{ type: 'last-prompt' }]);
438
+ continue;
439
+ }
390
440
  const batching = /^batch (.*)$/s.exec(command);
391
441
  if (batching) {
392
442
  const spec = JSON.parse(batching[1]);
@@ -8,7 +8,9 @@ import type { TranscriptEntry } from './host/process.js';
8
8
  * (with `includePartialMessages`), and one `result` per turn. This keeps the
9
9
  * text said since the last tool call, writes it with the call that follows it
10
10
  * (`{ role: 'assistant', text, toolCalls }`), and writes the rest and a `turn`
11
- * entry at the result. Text deltas go to the live stream. Subagent messages
11
+ * entry at the result. Text deltas go to the live stream, and the text of a
12
+ * message that came whole (no deltas: the CLI's non-streaming retry of a
13
+ * stalled request) goes there from its blocks. Subagent messages
12
14
  * (`parent_tool_use_id` set) are left out.
13
15
  *
14
16
  * Pure: the drive hands it SDK messages and gets entries back through `sink`,
@@ -57,6 +59,21 @@ export declare class TranscriptBuilder {
57
59
  /** The model's last message was cut at its output limit, and the turn has not ended: the CLI resumes it itself, so the
58
60
  * next text the model says is a message of its own (`text_end` before it). */
59
61
  private cutPending;
62
+ /** The streamed message (its `message_start` id), and the ids of the messages whose text streamed: a message the CLI
63
+ * got whole (its non-streaming retry of a stalled stream) has no deltas, and its text is said live from its blocks. */
64
+ private streaming;
65
+ private readonly streamed;
66
+ /** Text deltas no `assistant` text block has claimed yet: how a message with no id reads as streamed. */
67
+ private unclaimed;
68
+ /** Text was said live since the last message boundary: a whole answer after it is a message of its own. */
69
+ private saying;
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;
60
77
  constructor(sink: TranscriptSink);
61
78
  /** One message from `query()`. Returns how the turn ended for a `result`. */
62
79
  observe(m: SdkMessage): TurnEnd | undefined;
@@ -75,6 +92,15 @@ export declare class TranscriptBuilder {
75
92
  * block before it calls the tool); after `waitMs`, by this.
76
93
  */
77
94
  beforeCall(id: string, name: string, waitMs?: number): Promise<void>;
95
+ /**
96
+ * A text block of an `assistant` message, said live when none of its text streamed: the CLI asks again without
97
+ * streaming when a streamed request stalls, and that answer comes whole. A message with an id streamed when a delta
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.
102
+ */
103
+ private sayUnstreamed;
78
104
  private call;
79
105
  }
80
106
  export {};
@@ -17,6 +17,21 @@ export class TranscriptBuilder {
17
17
  /** The model's last message was cut at its output limit, and the turn has not ended: the CLI resumes it itself, so the
18
18
  * next text the model says is a message of its own (`text_end` before it). */
19
19
  cutPending = false;
20
+ /** The streamed message (its `message_start` id), and the ids of the messages whose text streamed: a message the CLI
21
+ * got whole (its non-streaming retry of a stalled stream) has no deltas, and its text is said live from its blocks. */
22
+ streaming;
23
+ streamed = new Set();
24
+ /** Text deltas no `assistant` text block has claimed yet: how a message with no id reads as streamed. */
25
+ unclaimed = false;
26
+ /** Text was said live since the last message boundary: a whole answer after it is a message of its own. */
27
+ saying = false;
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 = '';
20
35
  constructor(sink) {
21
36
  this.sink = sink;
22
37
  }
@@ -26,23 +41,36 @@ export class TranscriptBuilder {
26
41
  return undefined;
27
42
  if (m.type === 'stream_event') {
28
43
  const ev = m.event;
44
+ if (ev?.type === 'message_start')
45
+ this.streaming = typeof ev.message?.id === 'string' ? ev.message.id : undefined;
29
46
  // A message the model's output limit cut: the CLI resumes it in the same turn ("Output token limit hit"), and the
30
47
  // message that follows is the model's next one, not more of this one.
31
48
  if (ev?.type === 'message_delta' && ev.delta?.stop_reason === 'max_tokens')
32
49
  this.cutPending = true;
33
50
  if (ev?.type === 'content_block_delta' && ev.delta?.type === 'text_delta' && ev.delta.text) {
34
- if (this.cutPending)
51
+ if (this.cutPending) {
35
52
  this.sink.live({ type: 'text_end' });
53
+ this.partial = '';
54
+ }
36
55
  this.cutPending = false;
56
+ if (this.streaming !== undefined)
57
+ this.streamed.add(this.streaming);
58
+ this.partial += ev.delta.text;
59
+ this.unclaimed = true;
60
+ this.saying = true;
61
+ this.whole = undefined;
37
62
  this.sink.live({ type: 'text', delta: ev.delta.text });
38
63
  }
39
64
  return undefined;
40
65
  }
41
66
  if (m.type === 'assistant') {
42
- const content = m.message?.content;
67
+ const message = m.message;
68
+ const content = message?.content;
43
69
  for (const block of Array.isArray(content) ? content : []) {
44
- if (block.type === 'text' && block.text)
70
+ if (block.type === 'text' && block.text) {
45
71
  this.said = this.said ? `${this.said}\n\n${block.text}` : block.text;
72
+ this.sayUnstreamed(typeof message?.id === 'string' ? message.id : undefined, block.text);
73
+ }
46
74
  else if (block.type === 'tool_use' && block.id) {
47
75
  this.asked.set(block.id, { name: bareToolName(block.name ?? 'tool'), input: block.input });
48
76
  this.call(block.id, bareToolName(block.name ?? 'tool'));
@@ -75,6 +103,10 @@ export class TranscriptBuilder {
75
103
  ? [m.user_message_uuid]
76
104
  : undefined;
77
105
  this.cutPending = false;
106
+ this.saying = false;
107
+ this.unclaimed = false;
108
+ this.whole = undefined;
109
+ this.partial = '';
78
110
  // The turn's final answer still cut: the CLI's recovery of it was spent.
79
111
  const output = m.usage?.output_tokens;
80
112
  const cut = !isError && m.stop_reason === 'max_tokens' ? { stopReason: 'length', ...(typeof output === 'number' ? { outputTokens: output } : {}) } : {};
@@ -120,10 +152,43 @@ export class TranscriptBuilder {
120
152
  });
121
153
  this.call(id, name);
122
154
  }
155
+ /**
156
+ * A text block of an `assistant` message, said live when none of its text streamed: the CLI asks again without
157
+ * streaming when a streamed request stalls, and that answer comes whole. A message with an id streamed when a delta
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.
162
+ */
163
+ sayUnstreamed(id, text) {
164
+ const partial = this.partial;
165
+ this.partial = '';
166
+ const streamed = id === undefined ? this.unclaimed && text === partial : this.streamed.has(id);
167
+ this.unclaimed = false;
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 };
172
+ return;
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)))
177
+ this.sink.live({ type: 'text_end' });
178
+ this.cutPending = false;
179
+ this.saying = true;
180
+ this.whole = { id };
181
+ const rest = goesOn ? text.slice(partial.length) : text;
182
+ if (rest)
183
+ this.sink.live({ type: 'text', delta: rest });
184
+ }
123
185
  call(id, name) {
124
186
  if (this.written.has(id))
125
187
  return;
126
188
  this.written.add(id);
189
+ this.saying = false;
190
+ this.whole = undefined;
191
+ this.partial = '';
127
192
  this.sink.message({ type: 'message', role: 'assistant', text: this.said, toolCalls: [{ id, name }] });
128
193
  this.said = '';
129
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.61",
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.61"
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.61"
80
+ "@parcha/agentrun-dsl": "0.1.0-beta.63"
81
81
  }
82
82
  }