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

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.
@@ -1,4 +1,4 @@
1
- import { type ProviderPolicy, type ProxyRoute, type ProxyUsage } from "@parcha/agentrun-kernel/host";
1
+ import { type ProviderPolicy, type ProxyRequestContext, type ProxyRoute, type ProxyUsage } from "@parcha/agentrun-kernel/host";
2
2
  /** The prefix of the session's own tools, as the CLI names them (its in-process MCP server, `hands`). */
3
3
  export declare const OWN_TOOL_PREFIX = "mcp__hands__";
4
4
  export declare const CLAUDE_MESSAGES_ROUTES: readonly ProxyRoute[];
@@ -74,8 +74,9 @@ export declare function anthropicContentBytes(event: string): number;
74
74
  * and a thinking budget squeezed under it so that 1,024 tokens stay for the answer, never below the provider's least
75
75
  * budget. Only numbers get smaller, so the body is never longer. */
76
76
  export declare function limitAnthropicOutput(body: Record<string, unknown>, max: number): Record<string, unknown>;
77
- /** The body the provider gets for a request on `route`. */
78
- export declare function applyAnthropic(body: unknown, route: ProxyRoute, options: AnthropicPolicyOptions): Record<string, unknown>;
77
+ /** The body the provider gets for a request on `route`. `context.host`: the host's own request beside the CLI's, whose
78
+ * client tools are its own; every other rule is the session's. */
79
+ export declare function applyAnthropic(body: unknown, route: ProxyRoute, options: AnthropicPolicyOptions, context?: ProxyRequestContext): Record<string, unknown>;
79
80
  /** A Messages response's usage as the proxy books it: its tokens, and the web searches the provider ran for it
80
81
  * (`usage.server_tool_use.web_search_requests`), only when there were any. */
81
82
  export interface AnthropicUsage extends ProxyUsage {
@@ -95,12 +96,19 @@ export declare function anthropicUsage(text: string): AnthropicUsage | undefined
95
96
  * on its own, as anthropicUsage reads them. */
96
97
  export declare function anthropicFiltered(text: string): boolean;
97
98
  /** Whether a Messages body (as `apply` kept it) is the turn's answer request: it offers the model one of the session's
98
- * tools. The CLI's side calls (a title, a summary, a web search's own request) offer none of them; in a session with no
99
- * tools no request can be told from one, so each is the turn's. */
100
- export declare function anthropicAnswers(body: Record<string, unknown>, options: Pick<AnthropicPolicyOptions, "tools" | "builtins">): boolean;
99
+ * tools, its own, built-in or remote (a remote MCP server's). The CLI's side calls (a title, a summary, a web search's
100
+ * own request) offer none of them; in a session with no tools no request can be told from one, so each is the turn's. */
101
+ export declare function anthropicAnswers(body: Record<string, unknown>, options: Pick<AnthropicPolicyOptions, "tools" | "builtins" | "mcpTools">): boolean;
101
102
  /** The input tokens the provider bills for `body` that it does not carry (`providerInputOverhead`, with its sources): the
102
103
  * tool-use system prompt when it has tools, and for each image the most it can be billed as, beyond its bytes. None
103
104
  * can be said for a body with the web search tool: the provider bills the pages it finds as input, on each of its
104
105
  * searches, so its input is unmeasured (undefined), never bounded by its bytes. */
105
106
  export declare function anthropicServerInputOverhead(body: Record<string, unknown>, searchAllowance?: number): number | undefined;
107
+ /** `body` (a Messages body) with `text` as a note the model reads after everything the Claude CLI sent: one text block, in
108
+ * a <system-reminder>, at the end of the last user message (after its tool results), or a user message of its own after
109
+ * a last message that is not one. A system message the CLI ends a request with (its environment note at a turn's start)
110
+ * stays last: the API takes one only before an assistant message or at the end, so the note goes in the user message
111
+ * before it. It carries no cache_control: every cache marker stays on the block it was on, so the cached prefix ends
112
+ * where it did. The CLI's transcript never holds it. */
113
+ export declare function addAnthropicNote(body: Record<string, unknown>, text: string): Record<string, unknown>;
106
114
  export declare function anthropicPolicy(options: AnthropicPolicyOptions): ProviderPolicy;
@@ -240,8 +240,12 @@ export function limitAnthropicOutput(body, max) {
240
240
  }
241
241
  return out;
242
242
  }
243
- /** The body the provider gets for a request on `route`. */
244
- export function applyAnthropic(body, route, options) {
243
+ /** The client tools a body offers, by name: the host's own side request (ProxyRequestContext.host) offers its own (a
244
+ * learned workflow node's `submit`), never a provider-hosted one. */
245
+ const clientToolNames = (tools) => (Array.isArray(tools) ? tools.filter((tool) => isPlain(tool) && (tool.type === undefined || tool.type === "custom") && typeof tool.name === "string").map((tool) => tool.name) : []);
246
+ /** The body the provider gets for a request on `route`. `context.host`: the host's own request beside the CLI's, whose
247
+ * client tools are its own; every other rule is the session's. */
248
+ export function applyAnthropic(body, route, options, context = {}) {
245
249
  if (!isPlain(body))
246
250
  return refuse(400, "the body is not an object");
247
251
  const count = route.path === "/v1/messages/count_tokens";
@@ -255,7 +259,7 @@ export function applyAnthropic(body, route, options) {
255
259
  blocks(message.content, "a message's content");
256
260
  }
257
261
  blocks(body.system, "system");
258
- const allowed = new Set([...options.tools.map((name) => `${OWN_TOOL_PREFIX}${name}`), ...(options.builtins ?? []), ...(options.mcpTools ?? [])]);
262
+ const allowed = context.host !== undefined ? new Set(clientToolNames(body.tools)) : new Set([...options.tools.map((name) => `${OWN_TOOL_PREFIX}${name}`), ...(options.builtins ?? []), ...(options.mcpTools ?? [])]);
259
263
  const tools = ownTools(body.tools, allowed, options.webSearch);
260
264
  const choice = body.tool_choice;
261
265
  const chosen = isPlain(choice) && typeof choice.name === "string" && (allowed.has(choice.name) || (options.webSearch === true && choice.name === "web_search"));
@@ -269,7 +273,7 @@ export function applyAnthropic(body, route, options) {
269
273
  return out;
270
274
  // A main-model request that would not think is said, never passed silently (it is still forwarded: the CLI decides
271
275
  // its own requests, and this is the record that one went without reasoning).
272
- if (body.model === options.model && !thinks(body)) {
276
+ if (context.host === undefined && body.model === options.model && !thinks(body)) {
273
277
  try {
274
278
  options.onThinkingDisabled?.({ model: options.model });
275
279
  }
@@ -370,10 +374,10 @@ export function anthropicFiltered(text) {
370
374
  return stop === "refusal";
371
375
  }
372
376
  /** Whether a Messages body (as `apply` kept it) is the turn's answer request: it offers the model one of the session's
373
- * tools. The CLI's side calls (a title, a summary, a web search's own request) offer none of them; in a session with no
374
- * tools no request can be told from one, so each is the turn's. */
377
+ * tools, its own, built-in or remote (a remote MCP server's). The CLI's side calls (a title, a summary, a web search's
378
+ * own request) offer none of them; in a session with no tools no request can be told from one, so each is the turn's. */
375
379
  export function anthropicAnswers(body, options) {
376
- const allowed = new Set([...options.tools.map((name) => `${OWN_TOOL_PREFIX}${name}`), ...(options.builtins ?? [])]);
380
+ const allowed = new Set([...options.tools.map((name) => `${OWN_TOOL_PREFIX}${name}`), ...(options.builtins ?? []), ...(options.mcpTools ?? [])]);
377
381
  if (allowed.size === 0)
378
382
  return true;
379
383
  return Array.isArray(body.tools) && body.tools.some((tool) => isPlain(tool) && typeof tool.name === "string" && allowed.has(tool.name));
@@ -403,10 +407,32 @@ export function anthropicServerInputOverhead(body, searchAllowance) {
403
407
  };
404
408
  return providerInputOverhead("anthropic-messages", shape) + (searches ? searchAllowance : 0);
405
409
  }
410
+ /** `body` (a Messages body) with `text` as a note the model reads after everything the Claude CLI sent: one text block, in
411
+ * a <system-reminder>, at the end of the last user message (after its tool results), or a user message of its own after
412
+ * a last message that is not one. A system message the CLI ends a request with (its environment note at a turn's start)
413
+ * stays last: the API takes one only before an assistant message or at the end, so the note goes in the user message
414
+ * before it. It carries no cache_control: every cache marker stays on the block it was on, so the cached prefix ends
415
+ * where it did. The CLI's transcript never holds it. */
416
+ export function addAnthropicNote(body, text) {
417
+ const messages = Array.isArray(body.messages) ? body.messages : [];
418
+ const note = { type: "text", text: `<system-reminder>${text}</system-reminder>` };
419
+ // The system messages the request ends with, kept after the note.
420
+ let end = messages.length;
421
+ while (end > 0 && isPlain(messages[end - 1]) && messages[end - 1].role === "system")
422
+ end -= 1;
423
+ const trailing = messages.slice(end);
424
+ const last = messages[end - 1];
425
+ if (isPlain(last) && last.role === "user") {
426
+ const content = typeof last.content === "string" ? [{ type: "text", text: last.content }] : Array.isArray(last.content) ? last.content : [];
427
+ return { ...body, messages: [...messages.slice(0, end - 1), { ...last, content: [...content, note] }, ...trailing] };
428
+ }
429
+ return { ...body, messages: [...messages.slice(0, end), { role: "user", content: [note] }, ...trailing] };
430
+ }
406
431
  export function anthropicPolicy(options) {
407
432
  return {
408
433
  id: "anthropic",
409
434
  routes: CLAUDE_MESSAGES_ROUTES,
435
+ addNote: addAnthropicNote,
410
436
  keyOf: (headers) => {
411
437
  const auth = String(headers.authorization ?? "");
412
438
  return auth.startsWith("Bearer ") ? auth.slice(7) : "";
@@ -420,7 +446,7 @@ export function anthropicPolicy(options) {
420
446
  refuse(403, "an anthropic-beta value is not one the pinned CLI sends");
421
447
  return value;
422
448
  },
423
- apply: (body, route) => applyAnthropic(body, route, options),
449
+ apply: (body, route, context) => applyAnthropic(body, route, options, context),
424
450
  // `apply` let through only the session's model or its small one.
425
451
  modelOf: (body) => (typeof body.model === "string" ? body.model : undefined),
426
452
  serverInputOverhead: options.webSearchAllowance === undefined ? anthropicServerInputOverhead : (body) => anthropicServerInputOverhead(body, options.webSearchAllowance),
@@ -1,6 +1,6 @@
1
1
  import type { DriveContext } from "./kernel.js";
2
- export { BuiltinCalls, NativeJournal, openTurn, placeSubmissions, recoveryNote, replayBy, restartEvent, toolBridge, waitForSubmissions, zodShapeFromJsonSchema, } from "@parcha/agentrun-kernel/process";
3
- export type { JournalRecord, TranscriptEntry } from "@parcha/agentrun-kernel/process";
2
+ export { BuiltinCalls, NativeJournal, openTurn, placeSubmissions, recoveryNote, replayBy, restartEvent, resumeUnstartedCalls, toolBridge, waitForSubmissions, zodShapeFromJsonSchema, } from "@parcha/agentrun-kernel/process";
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. */
6
6
  export interface SessionProcess {
@@ -67,8 +67,6 @@ export interface GatewayRoute {
67
67
  export declare const CLAUDE_ROUTES: readonly GatewayRoute[];
68
68
  /** A provider-hosted tool the harness may offer (none here: the policy refuses them all). */
69
69
  export type ProviderTool = "web_search" | "web_fetch";
70
- /** The caps a model route can reach. */
71
- export type GatewayCap = "turnUsd" | "sessionUsd" | "concurrency";
72
70
  /** What the harness says about its model route; the machine's proxy serves it (machine.ts, policy.ts). */
73
71
  export interface GatewayHandlerOptions {
74
72
  routes: readonly GatewayRoute[];
@@ -76,17 +74,10 @@ export interface GatewayHandlerOptions {
76
74
  model: string;
77
75
  smallModel?: string;
78
76
  };
79
- budget?: {
80
- turnUsd: number;
81
- sessionUsd: number;
82
- };
83
- ledger?: unknown;
84
77
  providerTools?: readonly ProviderTool[];
85
78
  network?: string;
86
79
  credential: () => Promise<string | undefined> | string | undefined;
87
80
  target: string;
88
- track?: unknown;
89
- onCap?: (cap: GatewayCap) => void;
90
81
  /** The provider refused the session's key: a paid request answered 401, with the provider's own words. No retry can
91
82
  * pass, so the harness ends the turn at the first rather than let the CLI retry it for minutes. */
92
83
  onKeyRefused?: (detail: string) => void;
@@ -101,30 +92,3 @@ export declare const gatewayHandler: (options: GatewayHandlerOptions) => Gateway
101
92
  export declare const gatewayCredential: () => Promise<string>;
102
93
  /** The provider's base URL when the harness is given none: the adapter always gives one. */
103
94
  export declare const gatewayUrl: () => string;
104
- /** Upstream's model steps (a trace of each request through its gateway). The runner accounts requests here: nothing to trace. */
105
- export declare class ModelSteps {
106
- constructor(_ctx: DriveContext, _options?: {
107
- log?: (message: string, fields?: Record<string, unknown>) => void;
108
- });
109
- readonly request: () => void;
110
- settleAbandoned(): Promise<void>;
111
- close(): Promise<void>;
112
- }
113
- export declare function settleAbandonedModelSteps(_ctx: DriveContext): Promise<void>;
114
- /** Upstream's dollar ledger in the session's journal. The runner accounts spend here: this one records nothing. */
115
- export interface JournalLedger {
116
- turn(key: string): void;
117
- spent(): {
118
- turnUsd: number;
119
- sessionUsd: number;
120
- };
121
- add(usd: number, info: {
122
- method: string;
123
- path: string;
124
- model?: string;
125
- estimated?: boolean;
126
- }): void;
127
- }
128
- export declare function journalLedger(_journal: unknown, _options?: {
129
- records?: readonly unknown[];
130
- }): JournalLedger;
@@ -1,4 +1,4 @@
1
- export { BuiltinCalls, NativeJournal, openTurn, placeSubmissions, recoveryNote, replayBy, restartEvent, toolBridge, waitForSubmissions, zodShapeFromJsonSchema, } from "@parcha/agentrun-kernel/process";
1
+ export { BuiltinCalls, NativeJournal, openTurn, placeSubmissions, recoveryNote, replayBy, restartEvent, resumeUnstartedCalls, toolBridge, 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) {
@@ -18,14 +18,3 @@ export const gatewayCredential = async () => {
18
18
  export const gatewayUrl = () => {
19
19
  throw new Error("agentrun-harness-claude: no provider URL was given to the harness");
20
20
  };
21
- /** Upstream's model steps (a trace of each request through its gateway). The runner accounts requests here: nothing to trace. */
22
- export class ModelSteps {
23
- constructor(_ctx, _options = {}) { }
24
- request = () => { };
25
- async settleAbandoned() { }
26
- async close() { }
27
- }
28
- export async function settleAbandonedModelSteps(_ctx) { }
29
- export function journalLedger(_journal, _options = {}) {
30
- return { turn: () => { }, spent: () => ({ turnUsd: 0, sessionUsd: 0 }), add: () => { } };
31
- }
@@ -36,8 +36,15 @@ export declare const listedTools: (tools: readonly ServedTool[]) => {
36
36
  "anthropic/maxResultSizeChars": number;
37
37
  };
38
38
  }[];
39
- /** The SDK's in-process server config for `tools`: `call(name, args, toolUseId)` answers each call. */
40
- export declare function toolServer(name: string, tools: readonly ServedTool[], call: (tool: string, args: unknown, toolUseId: unknown) => Promise<ServedResult>): Promise<{
39
+ /** The MCP library the server is built with, as a host loaded it from where it installed the Agent SDK (its peer):
40
+ * `@modelcontextprotocol/sdk`'s `server/mcp.js` and `types.js`. */
41
+ export type ToolServerModules = {
42
+ server: unknown;
43
+ types: unknown;
44
+ };
45
+ /** The SDK's in-process server config for `tools`: `call(name, args, toolUseId)` answers each call. Built with `modules`,
46
+ * else with the MCP library imported by name, beside this package. */
47
+ export declare function toolServer(name: string, tools: readonly ServedTool[], call: (tool: string, args: unknown, toolUseId: unknown) => Promise<ServedResult>, modules?: ToolServerModules): Promise<{
41
48
  type: "sdk";
42
49
  name: string;
43
50
  instance: import("@modelcontextprotocol/sdk/server/mcp.js").McpServer;
@@ -27,12 +27,12 @@ export const MCP_OUTPUT_TOKENS = HOST_RESULT_MAX_CHARS;
27
27
  /** `tools` as the server lists them to the CLI (`tools/list`): each as the host gave it, with the host's result bound as
28
28
  * its result size. */
29
29
  export const listedTools = (tools) => tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema, _meta: { [RESULT_SIZE_KEY]: HOST_RESULT_MAX_CHARS } }));
30
- /** The SDK's in-process server config for `tools`: `call(name, args, toolUseId)` answers each call. */
31
- export async function toolServer(name, tools, call) {
32
- const [{ McpServer }, { CallToolRequestSchema, ListToolsRequestSchema }] = await Promise.all([
33
- import("@modelcontextprotocol/sdk/server/mcp.js"),
34
- import("@modelcontextprotocol/sdk/types.js"),
35
- ]);
30
+ /** The SDK's in-process server config for `tools`: `call(name, args, toolUseId)` answers each call. Built with `modules`,
31
+ * else with the MCP library imported by name, beside this package. */
32
+ export async function toolServer(name, tools, call, modules) {
33
+ const [{ McpServer }, { CallToolRequestSchema, ListToolsRequestSchema }] = modules
34
+ ? [modules.server, modules.types]
35
+ : await Promise.all([import("@modelcontextprotocol/sdk/server/mcp.js"), import("@modelcontextprotocol/sdk/types.js")]);
36
36
  const server = new McpServer({ name, version: "1.0.0" }, { capabilities: { tools: {} } });
37
37
  const listed = listedTools(tools);
38
38
  const names = new Set(tools.map((t) => t.name));
package/dist/ids.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
2
2
  // From github.com/vercel-labs/durable-harness, packages/harness-claude-code/src/ids.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
3
- // Changed by Parcha, patches: 002-names
3
+ // Changed by Parcha, and AgentRun's own since the port from upstream froze on 2026-11-07.
4
4
  import { createHash } from 'node:crypto';
5
5
  /**
6
6
  * A deterministic UUID for a string: the session id of a run, the `uuid` of
package/dist/inbox.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
2
2
  // From github.com/vercel-labs/durable-harness, packages/harness-claude-code/src/inbox.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
3
- // Changed by Parcha, patches: 002-names
3
+ // Changed by Parcha, and AgentRun's own since the port from upstream froze on 2026-11-07.
4
4
  /**
5
5
  * The streaming input `query()` reads: an async iterable the drive pushes
6
6
  * user messages into. `end()` closes it, which closes the CLI's stdin, and
package/dist/index.d.ts CHANGED
@@ -3,9 +3,9 @@ export { CLAUDE_AGENT_PACKAGE, ClaudeAgentNotInstalled, ClaudeAgentPinMismatch,
3
3
  export type { ClaudeAgentPin } from "./errors.js";
4
4
  export type { ClaudeAgentAdapterOptions, ClaudeAgentProvider, ClaudeAgentSkill, ClaudeAgentThinking } from "./adapter.js";
5
5
  export { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_CODE_VERSION as CLAUDE_AGENT_CLI_VERSION } from "./versions.js";
6
- export { findClaudeExecutable as claudeAgentExecutable } from "./binary.js";
6
+ export { findClaudeExecutable as claudeAgentExecutable, platformSuffix as claudeAgentPlatform } from "./binary.js";
7
7
  export { anthropicPolicy, CLAUDE_WEB_SEARCH_TOOL, CLAUDE_WEB_SEARCH_USD, OWN_TOOL_PREFIX, thinks } 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 { listedTools, MCP_OUTPUT_TOKENS, RESULT_SIZE_KEY, toolServer } from "./host/tool-server.js";
10
+ export { listedTools, MCP_OUTPUT_TOKENS, RESULT_SIZE_KEY, toolServer, type ToolServerModules } from "./host/tool-server.js";
11
11
  export type { ServedTool } from "./host/tool-server.js";
package/dist/index.js CHANGED
@@ -2,6 +2,6 @@
2
2
  export { CLAUDE_AGENT_ALSO_OFF, CLAUDE_AGENT_CLI_SKILL_NAMES, CLAUDE_AGENT_DIGESTS, CLAUDE_AGENT_ID, CLAUDE_AGENT_MAX_IMAGE_BYTES, CLAUDE_AGENT_SKILLS_PLUGIN, claudeAgentAdapter, claudeAgentCliPins, skillProblems, thinkingOf, toolImageProblems, verifyClaudeAgent, verifyClaudeAgentCli } from "./adapter.js";
3
3
  export { CLAUDE_AGENT_PACKAGE, ClaudeAgentNotInstalled, ClaudeAgentPinMismatch, ClaudeAgentThinkingOff } from "./errors.js";
4
4
  export { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_CODE_VERSION as CLAUDE_AGENT_CLI_VERSION } from "./versions.js";
5
- export { findClaudeExecutable as claudeAgentExecutable } from "./binary.js";
5
+ export { findClaudeExecutable as claudeAgentExecutable, platformSuffix as claudeAgentPlatform } from "./binary.js";
6
6
  export { anthropicPolicy, CLAUDE_WEB_SEARCH_TOOL, CLAUDE_WEB_SEARCH_USD, OWN_TOOL_PREFIX, thinks } from "./host/policy.js";
7
7
  export { listedTools, MCP_OUTPUT_TOKENS, RESULT_SIZE_KEY, toolServer } from "./host/tool-server.js";
@@ -0,0 +1,22 @@
1
+ import { type CallOutcome, type DanglingCall, type ToolBridge } from './host/process.js';
2
+ import type { DriveContext } from './host/kernel.js';
3
+ import type { JournalSessionStore, TranscriptLine } from './store.js';
4
+ /**
5
+ * The host-tool calls the transcript's last turn left without a result, in the order the model made them: the
6
+ * `tool_use` blocks after its last prompt that no `tool_result` answers. A call before that prompt is the CLI's to
7
+ * have answered when it resumed then; it is never taken up here, turns later. Built-ins (no `mcp__hands__` prefix)
8
+ * are the CLI's own.
9
+ */
10
+ export declare function danglingCalls(lines: readonly TranscriptLine[]): DanglingCall[];
11
+ /**
12
+ * The user line that answers `call` with its outcome, as Claude Code writes an MCP tool's result: after the
13
+ * transcript's last line, with the session fields of the assistant line that made the call. Its `uuid` is the call's,
14
+ * so writing it again (a crash before the CLI started) is the same line.
15
+ */
16
+ export declare function resultLine(lines: readonly TranscriptLine[], call: DanglingCall, outcome: CallOutcome): TranscriptLine;
17
+ /**
18
+ * Before the CLI resumes the transcript: each dangling host-tool call that never started runs through `bridge`, and its
19
+ * result is written into the transcript and committed, so the CLI starts again past it. A gate that parks rejects out
20
+ * of here with nothing written, and the call keeps the id the model gave it.
21
+ */
22
+ export declare function resumeDanglingCalls(ctx: DriveContext, bridge: ToolBridge, store: JournalSessionStore): Promise<void>;
package/dist/resume.js ADDED
@@ -0,0 +1,78 @@
1
+ // Claude Code's part of a resume, for a host-tool call its transcript left dangling (a `tool_use` with no `tool_result`):
2
+ // which calls those are, read from the transcript the drive is about to resume, and how one's result is written into
3
+ // it. The decision (run it, or leave it to the CLI's own repair) is the shared one, `resumeUnstartedCalls`: only a call
4
+ // with no effect of its own on the run's journal runs here, through the tool bridge (the host's gate first, then its
5
+ // intent, the call and its result), and only then is its result written here, before the CLI starts again. A call
6
+ // that has an effect is left as before: the CLI answers it "[Tool call interrupted]", and the recovery note says what
7
+ // the log knows of it.
8
+ import { resumeUnstartedCalls } from './host/process.js';
9
+ import { uuidFrom } from './ids.js';
10
+ import { toolResultIds } from './store.js';
11
+ import { MCP_SERVER } from './transcript.js';
12
+ const BRIDGED = `mcp__${MCP_SERVER}__`;
13
+ const toolUses = (line) => {
14
+ if (line.type !== 'assistant')
15
+ return [];
16
+ const content = line.message?.content;
17
+ return Array.isArray(content) ? content.filter((c) => c?.type === 'tool_use' && typeof c.id === 'string' && typeof c.name === 'string') : [];
18
+ };
19
+ /** A user line that is a prompt (the user's words, a recovery's), not a tool result the CLI wrote. */
20
+ const isPrompt = (line) => line.type === 'user' && line.isSidechain !== true && toolResultIds(line).length === 0;
21
+ /**
22
+ * The host-tool calls the transcript's last turn left without a result, in the order the model made them: the
23
+ * `tool_use` blocks after its last prompt that no `tool_result` answers. A call before that prompt is the CLI's to
24
+ * have answered when it resumed then; it is never taken up here, turns later. Built-ins (no `mcp__hands__` prefix)
25
+ * are the CLI's own.
26
+ */
27
+ export function danglingCalls(lines) {
28
+ let from = 0;
29
+ for (let i = lines.length - 1; i >= 0; i--) {
30
+ if (isPrompt(lines[i])) {
31
+ from = i + 1;
32
+ break;
33
+ }
34
+ }
35
+ const tail = lines.slice(from).filter((line) => line.isSidechain !== true);
36
+ const answered = new Set(tail.flatMap((line) => toolResultIds(line)));
37
+ return tail
38
+ .flatMap(toolUses)
39
+ .filter((block) => block.name.startsWith(BRIDGED) && !answered.has(block.id))
40
+ .map((block) => ({ callId: block.id, tool: block.name.slice(BRIDGED.length), args: block.input ?? {} }));
41
+ }
42
+ /**
43
+ * The user line that answers `call` with its outcome, as Claude Code writes an MCP tool's result: after the
44
+ * transcript's last line, with the session fields of the assistant line that made the call. Its `uuid` is the call's,
45
+ * so writing it again (a crash before the CLI started) is the same line.
46
+ */
47
+ export function resultLine(lines, call, outcome) {
48
+ const asked = lines.findLast((line) => toolUses(line).some((block) => block.id === call.callId));
49
+ const parent = lines.findLast((line) => typeof line.uuid === 'string');
50
+ const session = {};
51
+ for (const field of ['sessionId', 'cwd', 'version', 'userType', 'gitBranch'])
52
+ if (asked?.[field] !== undefined)
53
+ session[field] = asked[field];
54
+ return {
55
+ parentUuid: parent?.uuid ?? null,
56
+ isSidechain: false,
57
+ ...session,
58
+ type: 'user',
59
+ message: { role: 'user', content: [{ tool_use_id: call.callId, type: 'tool_result', content: [{ type: 'text', text: outcome.text }], ...(outcome.isError ? { is_error: true } : {}) }] },
60
+ uuid: uuidFrom(`result:${call.callId}`),
61
+ timestamp: new Date().toISOString(),
62
+ ...(asked?.uuid ? { sourceToolAssistantUUID: asked.uuid } : {}),
63
+ };
64
+ }
65
+ /**
66
+ * Before the CLI resumes the transcript: each dangling host-tool call that never started runs through `bridge`, and its
67
+ * result is written into the transcript and committed, so the CLI starts again past it. A gate that parks rejects out
68
+ * of here with nothing written, and the call keeps the id the model gave it.
69
+ */
70
+ export async function resumeDanglingCalls(ctx, bridge, store) {
71
+ const dangling = danglingCalls(store.lines());
72
+ if (dangling.length === 0)
73
+ return;
74
+ await resumeUnstartedCalls(ctx, bridge, dangling, async (call, outcome) => {
75
+ store.extend(resultLine(store.lines(), call, outcome));
76
+ });
77
+ await store.flush();
78
+ }
package/dist/serial.js CHANGED
@@ -6,5 +6,6 @@ export function serialWriter(writer) {
6
6
  chain = run.catch(() => undefined);
7
7
  return run;
8
8
  };
9
- return { key: writer.key, read: () => next(() => writer.read()), append: (records) => next(() => writer.append(records)) };
9
+ // The barrier goes on the same chain: it syncs what the appends before it wrote.
10
+ return { key: writer.key, read: () => next(() => writer.read()), append: (records) => next(() => writer.append(records)), sync: () => next(() => writer.sync()) };
10
11
  }
package/dist/store.d.ts CHANGED
@@ -98,6 +98,13 @@ export declare class JournalSessionStore {
98
98
  flush(): Promise<void>;
99
99
  /** Hand the held entries to the journal (which group-commits them). */
100
100
  private release;
101
+ /** The main transcript as a resume loads it: the log's lines as of the drive's start, and those `extend` added. */
102
+ lines(): readonly TranscriptLine[];
103
+ /**
104
+ * A line the harness writes into the main transcript before the CLI loads it (a dangling call's result on a resume):
105
+ * on the log, deduped by its `uuid` like the CLI's own, and in what `load` returns, after the lines before it.
106
+ */
107
+ extend(entry: TranscriptLine): void;
101
108
  load(key: SessionKey): Promise<TranscriptLine[] | null>;
102
109
  listSubkeys(_key: {
103
110
  projectKey: string;
package/dist/store.js CHANGED
@@ -123,6 +123,20 @@ export class JournalSessionStore {
123
123
  this.journal.append(item.stream, item.entry, item.entry.uuid ? { id: item.entry.uuid } : {});
124
124
  }
125
125
  }
126
+ /** The main transcript as a resume loads it: the log's lines as of the drive's start, and those `extend` added. */
127
+ lines() {
128
+ return this.loaded.get(CLAUDE_STREAM) ?? [];
129
+ }
130
+ /**
131
+ * A line the harness writes into the main transcript before the CLI loads it (a dangling call's result on a resume):
132
+ * on the log, deduped by its `uuid` like the CLI's own, and in what `load` returns, after the lines before it.
133
+ */
134
+ extend(entry) {
135
+ this.loaded.set(CLAUDE_STREAM, [...this.lines(), entry]);
136
+ this.held.push({ stream: CLAUDE_STREAM, entry });
137
+ this.note(entry);
138
+ this.release();
139
+ }
126
140
  async load(key) {
127
141
  const entries = this.loaded.get(streamOf(key));
128
142
  return entries?.length ? entries : null;
@@ -1,6 +1,6 @@
1
1
  // Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
2
2
  // From github.com/vercel-labs/durable-harness, packages/harness-claude-code/test/fake-anthropic.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
3
- // Changed by Parcha, patches: 007-fake-anthropic-real-shape, 015-web-search
3
+ // Changed by Parcha, and AgentRun's own since the port from upstream froze on 2026-11-07.
4
4
  /**
5
5
  * A scripted Anthropic Messages API for the real Claude Code CLI (docs/workspaces.md
6
6
  * §11.4, "the restart-on-a-new-sandbox tests"): what `query()` and the pinned
@@ -30,7 +30,18 @@ export interface FakeSdkOptions {
30
30
  * Commands, one per user message the fake consumes, in place of the message's text: a runner sends its own prompts
31
31
  * (the node's, then a nudge), so a test scripts what the "model" does instead. Past the end, the message's text.
32
32
  */
33
- script?: readonly string[];
33
+ script?: readonly string[] | ((text: string) => string | undefined);
34
+ /**
35
+ * What the "model" says after a `call` returns, in place of `<tool> returned: <result>`: given the tool, its result and
36
+ * the steers folded into the turn. Said as text events too (as with `remoteModel`), so a host's record of what the
37
+ * model said carries it. Also the first reply of a resumed session whose transcript ends on a result the host wrote
38
+ * there (a call that ran on the resume): the model reads that result on its next turn, as the CLI's does.
39
+ */
40
+ reply?: (call: {
41
+ name: string;
42
+ result: string;
43
+ steers: readonly string[];
44
+ }) => string;
34
45
  /** Each `PreToolUse` decision a built-in got (with the input the hook rewrote, if it did). */
35
46
  onDecision?: (call: {
36
47
  id: string;
@@ -1,6 +1,6 @@
1
1
  // Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
2
2
  // From github.com/vercel-labs/durable-harness, packages/harness-claude-code/test/fake-sdk.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
3
- // Changed by Parcha, patches: 006-fake-sdk-script, 012-fake-sdk-lists-tools, 014-fake-sdk-system-prompt
3
+ // Changed by Parcha, and AgentRun's own since the port from upstream froze on 2026-11-07.
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { join } from 'node:path';
6
6
  /**
@@ -53,6 +53,9 @@ rl.on('line', (line) => {
53
53
  });
54
54
  rl.on('close', () => process.exit(0));
55
55
  `;
56
+ /** How many times Claude Code resumes an answer its output limit cut, in the same turn, and the note it resumes with. */
57
+ const RECOVER_CUTS = 3;
58
+ const RECOVERY_NOTE = 'Output token limit hit. Resume directly — no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces.';
56
59
  /** The fake "CLI" with built-ins off: it lives until its stdin closes (the SDK closing the CLI). */
57
60
  const IDLE = `process.stdin.on('data', () => {}).on('end', () => process.exit(0))`;
58
61
  /** The session's tools, read the way the CLI reads them: an MCP client over a linked in-memory pair, on the harness's server. */
@@ -123,6 +126,8 @@ export function fakeSdk(fake = {}) {
123
126
  const signal = options.abortController?.signal;
124
127
  let calls = 0;
125
128
  let parent;
129
+ /** A host-written result the resumed transcript ends on (with `reply`): what the next turn's reply reads. */
130
+ let readBack;
126
131
  const uuid = () => randomUUID();
127
132
  const entry = (type, body) => {
128
133
  const e = { type, uuid: uuid(), parentUuid: parent ?? null, sessionId, message: undefined, ...body };
@@ -167,6 +172,12 @@ export function fakeSdk(fake = {}) {
167
172
  catch { }
168
173
  }
169
174
  });
175
+ // The "CLI" died (its session's machine stopped it): as the SDK's stream does when the CLI exits, a model request
176
+ // still answering ends in an error, never left waiting.
177
+ child.on?.('exit', () => {
178
+ for (const [, request] of said)
179
+ request.end('the CLI exited');
180
+ });
170
181
  }
171
182
  const runBash = (id, command) => {
172
183
  const done = new Promise((r) => reports.set(id, r));
@@ -282,11 +293,17 @@ export function fakeSdk(fake = {}) {
282
293
  // The CLI's own repair of a dangling call.
283
294
  const last = loaded.findLast((e) => e.type === 'assistant');
284
295
  const dangling = last?.message?.content?.find((c) => c.type === 'tool_use');
285
- if (dangling && !loaded.some((e) => e.type === 'user' && e.message?.content?.[0]?.tool_use_id === dangling.id)) {
296
+ const answered = dangling && loaded.findLast((e) => e.type === 'user' && e.message?.content?.[0]?.tool_use_id === dangling.id);
297
+ if (dangling && !answered) {
286
298
  await mirror([
287
299
  entry('user', { message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: dangling.id, is_error: true, content: '[Tool call interrupted]' }] } }),
288
300
  ]);
289
301
  }
302
+ else if (answered && fake.reply && answered === loaded.findLast((e) => e.type === 'user' || e.type === 'assistant')) {
303
+ // A call whose result the host wrote into the transcript before this resume: the model reads it on its next turn.
304
+ const content = answered.message.content[0].content;
305
+ readBack = { name: String(dangling.name ?? '').replace(/^mcp__hands__/, ''), result: Array.isArray(content) ? content.map((c) => c?.text ?? '').join('') : String(content ?? '') };
306
+ }
290
307
  }
291
308
  for (;;) {
292
309
  const m = await nextMessage();
@@ -300,7 +317,10 @@ export function fakeSdk(fake = {}) {
300
317
  parent = u.uuid;
301
318
  await mirror([{ type: 'queue-operation', operation: 'enqueue' }, u]);
302
319
  // A note the harness put before the message (the sandbox's: a lost Drive) is not part of the command.
303
- const command = fake.script && scripted < fake.script.length ? fake.script[scripted++] : text.replace(/^(?!(?:builtin|exit-during-builtin|exit-during|call) )[^\n]*\n\n/, '');
320
+ // A script as a function decides by the message's own text (a resumed CLI is handed the same words again), a
321
+ // list by how many messages this fake consumed.
322
+ const scriptedCommand = typeof fake.script === 'function' ? fake.script(text) : fake.script && scripted < fake.script.length ? fake.script[scripted++] : undefined;
323
+ const command = scriptedCommand ?? text.replace(/^(?!(?:builtin|exit-during-builtin|exit-during|call) )[^\n]*\n\n/, '');
304
324
  const builtin = /^(builtin|exit-during-builtin) (\S+) (.*)$/s.exec(command);
305
325
  if (builtin) {
306
326
  const id = `toolu_${randomUUID().slice(0, 8)}_${++calls}`;
@@ -340,6 +360,33 @@ export function fakeSdk(fake = {}) {
340
360
  void tools.then((t) => t.get(dying[1])?.handler(JSON.parse(dying[2]), { _meta: { 'claudecode/toolUseId': id } }));
341
361
  return;
342
362
  }
363
+ // `cut <json>`: the model's answers in this turn, in order, each `{ text, cut? }`. A cut answer stops at the output
364
+ // limit (stop_reason max_tokens), and the CLI, as Claude Code does, asks again with its recovery note, up to
365
+ // RECOVER_CUTS times; past the list the model is cut again with nothing said. The result says the last answer's
366
+ // stop, with the turn's output tokens.
367
+ const cutting = /^cut (.*)$/s.exec(command);
368
+ if (cutting) {
369
+ const answers = JSON.parse(cutting[1]);
370
+ let recovered = 0;
371
+ let stop = 'end_turn';
372
+ for (let at = 0;; at++) {
373
+ const answer = answers[at] ?? { text: '', cut: true };
374
+ if (answer.text)
375
+ yield* speak(answer.text);
376
+ stop = answer.cut ? 'max_tokens' : 'end_turn';
377
+ yield { type: 'stream_event', parent_tool_use_id: null, event: { type: 'message_delta', delta: { stop_reason: stop, stop_sequence: null }, usage: { output_tokens: 12 } } };
378
+ const b = entry('assistant', { message: { role: 'assistant', content: answer.text ? [{ type: 'text', text: answer.text }] : [], stop_reason: stop } });
379
+ await mirror([b]);
380
+ yield { type: 'assistant', parent_tool_use_id: null, uuid: b.uuid, session_id: sessionId, message: b.message };
381
+ if (!answer.cut || recovered >= RECOVER_CUTS)
382
+ break;
383
+ recovered++;
384
+ await mirror([entry('user', { isMeta: true, message: { role: 'user', content: RECOVERY_NOTE } })]);
385
+ }
386
+ yield { type: 'result', subtype: 'success', is_error: false, result: 'ok', stop_reason: stop, usage: { output_tokens: 12 }, session_id: sessionId, user_message_uuids: consumed, queued_turn_count: 0 };
387
+ await mirror([{ type: 'last-prompt' }]);
388
+ continue;
389
+ }
343
390
  const call = /^call (\S+) (.*)$/s.exec(command);
344
391
  if (call) {
345
392
  const id = `toolu_${randomUUID().slice(0, 8)}_${++calls}`;
@@ -359,9 +406,11 @@ export function fakeSdk(fake = {}) {
359
406
  await mirror([r]);
360
407
  yield { type: 'user', parent_tool_use_id: null, message: r.message };
361
408
  // A steer sent while the call ran is folded into this turn.
409
+ const steers = [];
362
410
  for (let i = inbox.findIndex((x) => x.priority === 'next'); i >= 0; i = inbox.findIndex((x) => x.priority === 'next')) {
363
411
  const s = inbox.splice(i, 1)[0];
364
412
  consumed.push(s.uuid);
413
+ steers.push(s.message.content);
365
414
  fake.onMessage?.({ uuid: s.uuid, text: s.message.content, priority: s.priority });
366
415
  // As the CLI does: a message taken in mid-turn is a queued_command attachment naming it, not a user entry.
367
416
  await mirror([
@@ -369,15 +418,19 @@ export function fakeSdk(fake = {}) {
369
418
  entry('attachment', { attachment: { type: 'queued_command', prompt: s.message.content, source_uuid: s.uuid } }),
370
419
  ]);
371
420
  }
372
- const reply = `${name} returned: ${result.content[0]?.text}${consumed.length > 1 ? ' (and I read your steer)' : ''}`;
373
- if (fake.remoteModel)
421
+ const reply = fake.reply
422
+ ? fake.reply({ name, result: String(result.content[0]?.text ?? ''), steers })
423
+ : `${name} returned: ${result.content[0]?.text}${consumed.length > 1 ? ' (and I read your steer)' : ''}`;
424
+ if (fake.remoteModel || fake.reply)
374
425
  yield* speak(reply);
375
426
  const b = entry('assistant', { message: { role: 'assistant', content: [{ type: 'text', text: reply }] } });
376
427
  await mirror([b]);
377
428
  yield { type: 'assistant', parent_tool_use_id: null, uuid: b.uuid, session_id: sessionId, message: b.message };
378
429
  }
379
430
  else {
380
- const reply = text.startsWith('[Recovery]') ? 'Recovered from the log.' : `echo: ${text}`;
431
+ const read = readBack;
432
+ readBack = undefined;
433
+ const reply = read && fake.reply ? fake.reply({ ...read, steers: [] }) : text.startsWith('[Recovery]') ? 'Recovered from the log.' : `echo: ${text}`;
381
434
  yield* speak(reply);
382
435
  const b = entry('assistant', { message: { role: 'assistant', content: [{ type: 'text', text: reply }] } });
383
436
  await mirror([b]);