@parcha/agentrun-harness-claude 0.0.0-stage → 0.1.0-beta.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +92 -0
- package/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +56 -2
- package/dist/adapter.d.ts +129 -0
- package/dist/adapter.js +514 -0
- package/dist/binary.d.ts +25 -0
- package/dist/binary.js +71 -0
- package/dist/cli-names.d.ts +7 -0
- package/dist/cli-names.js +17 -0
- package/dist/env.d.ts +81 -0
- package/dist/env.js +92 -0
- package/dist/errors.d.ts +27 -0
- package/dist/errors.js +42 -0
- package/dist/harness.d.ts +287 -0
- package/dist/harness.js +887 -0
- package/dist/host/kernel.d.ts +10 -0
- package/dist/host/kernel.js +1 -0
- package/dist/host/machine.d.ts +77 -0
- package/dist/host/machine.js +261 -0
- package/dist/host/policy.d.ts +104 -0
- package/dist/host/policy.js +437 -0
- package/dist/host/process.d.ts +130 -0
- package/dist/host/process.js +31 -0
- package/dist/host/tool-server.d.ts +44 -0
- package/dist/host/tool-server.js +47 -0
- package/dist/ids.d.ts +9 -0
- package/dist/ids.js +17 -0
- package/dist/inbox.d.ts +14 -0
- package/dist/inbox.js +36 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +7 -0
- package/dist/serial.d.ts +3 -0
- package/dist/serial.js +10 -0
- package/dist/spawn.d.ts +51 -0
- package/dist/spawn.js +131 -0
- package/dist/store.d.ts +119 -0
- package/dist/store.js +202 -0
- package/dist/testing/fake-anthropic.d.ts +97 -0
- package/dist/testing/fake-anthropic.js +279 -0
- package/dist/testing/fake-sdk.d.ts +60 -0
- package/dist/testing/fake-sdk.js +402 -0
- package/dist/testing/index.d.ts +3 -0
- package/dist/testing/index.js +5 -0
- package/dist/transcript.d.ts +73 -0
- package/dist/transcript.js +116 -0
- package/dist/versions.d.ts +34 -0
- package/dist/versions.js +76 -0
- package/package.json +76 -4
- package/vendor/durable-harness/UPSTREAM.json +59 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// The session's host tools, served to the CLI as an in-process MCP server. Written for AgentRun.
|
|
2
|
+
//
|
|
3
|
+
// The Agent SDK's own `tool(name, description, shape)` takes a zod shape and builds a closed object from it, so a tool's
|
|
4
|
+
// schema reached the model as whatever that zod gave back (an open object came out closed, `properties: {}`) and its
|
|
5
|
+
// arguments were parsed through it (an open object's keys arrived as `{}`). This server answers `tools/list` with each
|
|
6
|
+
// tool's JSON Schema as the host gave it, unchanged, and hands `tools/call`'s arguments to the tool as the model sent
|
|
7
|
+
// them: the host (its executor) validates them, as it does for every other harness. The CLI's tool_use id comes in the
|
|
8
|
+
// call's `_meta`, which the durable call record is keyed by.
|
|
9
|
+
//
|
|
10
|
+
// A host tool's result within the host's bound (HOST_RESULT_MAX_CHARS) reaches the model whole. The pinned CLI checks an
|
|
11
|
+
// MCP tool's result twice: past its character limit (50,000 by default, the tool's `anthropic/maxResultSizeChars` up to
|
|
12
|
+
// 500,000 where it gives one) it saves the result to tool-results/<tool_use_id>.json in its config dir and tells the
|
|
13
|
+
// model to read that file, which a confined session cannot; past MAX_MCP_OUTPUT_TOKENS (25,000 by default) it saves the
|
|
14
|
+
// result the same way, or cuts one that holds an image. Each tool is listed with the bound as its maxResultSizeChars,
|
|
15
|
+
// which also spares a text result the token check, and the harness sets MAX_MCP_OUTPUT_TOKENS from it (env.ts).
|
|
16
|
+
import { HOST_RESULT_MAX_CHARS } from "@parcha/agentrun-kernel";
|
|
17
|
+
/** The CLI's tool_use id, in a call's `_meta`. */
|
|
18
|
+
export const TOOL_USE_ID = "claudecode/toolUseId";
|
|
19
|
+
/** The `_meta` key of a listed tool by which the CLI takes the most characters of its result it passes whole. */
|
|
20
|
+
export const RESULT_SIZE_KEY = "anthropic/maxResultSizeChars";
|
|
21
|
+
/**
|
|
22
|
+
* MAX_MCP_OUTPUT_TOKENS: the host's bound, as tokens. The CLI estimates a result at a quarter of a token a character and
|
|
23
|
+
* 1,600 an image, and counts it exactly only past half its limit, so a result within the bound (with up to fifteen
|
|
24
|
+
* images) is never counted, let alone saved or cut.
|
|
25
|
+
*/
|
|
26
|
+
export const MCP_OUTPUT_TOKENS = HOST_RESULT_MAX_CHARS;
|
|
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
|
+
* its result size. */
|
|
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
|
+
]);
|
|
36
|
+
const server = new McpServer({ name, version: "1.0.0" }, { capabilities: { tools: {} } });
|
|
37
|
+
const listed = listedTools(tools);
|
|
38
|
+
const names = new Set(tools.map((t) => t.name));
|
|
39
|
+
server.server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: listed }));
|
|
40
|
+
server.server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
41
|
+
const { name: tool, arguments: args, _meta } = request.params;
|
|
42
|
+
if (!names.has(tool))
|
|
43
|
+
return { content: [{ type: "text", text: `${tool} is not one of this session's tools` }], isError: true };
|
|
44
|
+
return call(tool, args ?? {}, _meta?.[TOOL_USE_ID]);
|
|
45
|
+
});
|
|
46
|
+
return { type: "sdk", name, instance: server };
|
|
47
|
+
}
|
package/dist/ids.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A deterministic UUID for a string: the session id of a run, the `uuid` of
|
|
3
|
+
* the user message a submission becomes. Claude Code wants UUID-shaped ids
|
|
4
|
+
* (`sessionId` must be one), and the same input always gives the same id, so
|
|
5
|
+
* a later drive can find a submission's user entry in the transcript by it.
|
|
6
|
+
*
|
|
7
|
+
* Name-based (SHA-256, formatted with the version-5 and RFC 4122 variant bits).
|
|
8
|
+
*/
|
|
9
|
+
export declare function uuidFrom(name: string): string;
|
package/dist/ids.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
|
|
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
|
|
4
|
+
import { createHash } from 'node:crypto';
|
|
5
|
+
/**
|
|
6
|
+
* A deterministic UUID for a string: the session id of a run, the `uuid` of
|
|
7
|
+
* the user message a submission becomes. Claude Code wants UUID-shaped ids
|
|
8
|
+
* (`sessionId` must be one), and the same input always gives the same id, so
|
|
9
|
+
* a later drive can find a submission's user entry in the transcript by it.
|
|
10
|
+
*
|
|
11
|
+
* Name-based (SHA-256, formatted with the version-5 and RFC 4122 variant bits).
|
|
12
|
+
*/
|
|
13
|
+
export function uuidFrom(name) {
|
|
14
|
+
const h = createHash('sha256').update(`agentrun-claude-agent:${name}`).digest('hex');
|
|
15
|
+
const variant = ((Number.parseInt(h[16], 16) & 0x3) | 0x8).toString(16);
|
|
16
|
+
return `${h.slice(0, 8)}-${h.slice(8, 12)}-5${h.slice(13, 16)}-${variant}${h.slice(17, 20)}-${h.slice(20, 32)}`;
|
|
17
|
+
}
|
package/dist/inbox.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The streaming input `query()` reads: an async iterable the drive pushes
|
|
3
|
+
* user messages into. `end()` closes it, which closes the CLI's stdin, and
|
|
4
|
+
* the CLI exits once it is idle.
|
|
5
|
+
*/
|
|
6
|
+
export declare class MessageQueue<T> implements AsyncIterable<T> {
|
|
7
|
+
private readonly items;
|
|
8
|
+
private ended;
|
|
9
|
+
private wake;
|
|
10
|
+
push(item: T): void;
|
|
11
|
+
end(): void;
|
|
12
|
+
get closed(): boolean;
|
|
13
|
+
[Symbol.asyncIterator](): AsyncIterator<T>;
|
|
14
|
+
}
|
package/dist/inbox.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// Copyright 2026 Vercel Inc. Licensed under the Apache License, Version 2.0; see LICENSE in this package.
|
|
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
|
|
4
|
+
/**
|
|
5
|
+
* The streaming input `query()` reads: an async iterable the drive pushes
|
|
6
|
+
* user messages into. `end()` closes it, which closes the CLI's stdin, and
|
|
7
|
+
* the CLI exits once it is idle.
|
|
8
|
+
*/
|
|
9
|
+
export class MessageQueue {
|
|
10
|
+
items = [];
|
|
11
|
+
ended = false;
|
|
12
|
+
wake;
|
|
13
|
+
push(item) {
|
|
14
|
+
if (this.ended)
|
|
15
|
+
throw new Error('agentrun-harness-claude: the input is closed');
|
|
16
|
+
this.items.push(item);
|
|
17
|
+
this.wake?.();
|
|
18
|
+
}
|
|
19
|
+
end() {
|
|
20
|
+
this.ended = true;
|
|
21
|
+
this.wake?.();
|
|
22
|
+
}
|
|
23
|
+
get closed() {
|
|
24
|
+
return this.ended;
|
|
25
|
+
}
|
|
26
|
+
async *[Symbol.asyncIterator]() {
|
|
27
|
+
for (;;) {
|
|
28
|
+
while (this.items.length)
|
|
29
|
+
yield this.items.shift();
|
|
30
|
+
if (this.ended)
|
|
31
|
+
return;
|
|
32
|
+
await new Promise((resolve) => (this.wake = resolve));
|
|
33
|
+
this.wake = undefined;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
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 } from "./adapter.js";
|
|
2
|
+
export { CLAUDE_AGENT_PACKAGE, ClaudeAgentNotInstalled, ClaudeAgentPinMismatch, ClaudeAgentThinkingOff } from "./errors.js";
|
|
3
|
+
export type { ClaudeAgentPin } from "./errors.js";
|
|
4
|
+
export type { ClaudeAgentAdapterOptions, ClaudeAgentProvider, ClaudeAgentSkill, ClaudeAgentThinking } from "./adapter.js";
|
|
5
|
+
export { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_CODE_VERSION as CLAUDE_AGENT_CLI_VERSION } from "./versions.js";
|
|
6
|
+
export { findClaudeExecutable as claudeAgentExecutable } from "./binary.js";
|
|
7
|
+
export { anthropicPolicy, CLAUDE_WEB_SEARCH_TOOL, CLAUDE_WEB_SEARCH_USD, OWN_TOOL_PREFIX, thinks } from "./host/policy.js";
|
|
8
|
+
export type { AnthropicPolicyOptions, AnthropicUsage } from "./host/policy.js";
|
|
9
|
+
export type { ChildCommand, ConfineChild } from "./host/machine.js";
|
|
10
|
+
export { listedTools, MCP_OUTPUT_TOKENS, RESULT_SIZE_KEY, toolServer } from "./host/tool-server.js";
|
|
11
|
+
export type { ServedTool } from "./host/tool-server.js";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
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 } from "./adapter.js";
|
|
3
|
+
export { CLAUDE_AGENT_PACKAGE, ClaudeAgentNotInstalled, ClaudeAgentPinMismatch, ClaudeAgentThinkingOff } from "./errors.js";
|
|
4
|
+
export { CLAUDE_AGENT_SDK_INSTALL, CLAUDE_AGENT_SDK_VERSION, CLAUDE_CODE_VERSION as CLAUDE_AGENT_CLI_VERSION } from "./versions.js";
|
|
5
|
+
export { findClaudeExecutable as claudeAgentExecutable } from "./binary.js";
|
|
6
|
+
export { anthropicPolicy, CLAUDE_WEB_SEARCH_TOOL, CLAUDE_WEB_SEARCH_USD, OWN_TOOL_PREFIX, thinks } from "./host/policy.js";
|
|
7
|
+
export { listedTools, MCP_OUTPUT_TOKENS, RESULT_SIZE_KEY, toolServer } from "./host/tool-server.js";
|
package/dist/serial.d.ts
ADDED
package/dist/serial.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** `writer` with every read and append run one at a time, in call order. A failed one rejects for its caller only. */
|
|
2
|
+
export function serialWriter(writer) {
|
|
3
|
+
let chain = Promise.resolve();
|
|
4
|
+
const next = (work) => {
|
|
5
|
+
const run = chain.then(work);
|
|
6
|
+
chain = run.catch(() => undefined);
|
|
7
|
+
return run;
|
|
8
|
+
};
|
|
9
|
+
return { key: writer.key, read: () => next(() => writer.read()), append: (records) => next(() => writer.append(records)) };
|
|
10
|
+
}
|
package/dist/spawn.d.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { type Readable, type Writable } from "node:stream";
|
|
2
|
+
import type { SessionMachine, SessionProcess } from "./host/process.js";
|
|
3
|
+
/** The SDK's `SpawnOptions`, structurally. */
|
|
4
|
+
export interface SdkSpawnOptions {
|
|
5
|
+
command: string;
|
|
6
|
+
args: string[];
|
|
7
|
+
cwd?: string;
|
|
8
|
+
env: Record<string, string | undefined>;
|
|
9
|
+
signal: AbortSignal;
|
|
10
|
+
}
|
|
11
|
+
/** The SDK's `SpawnedProcess`, structurally. */
|
|
12
|
+
export interface SdkSpawnedProcess {
|
|
13
|
+
stdin: Writable;
|
|
14
|
+
stdout: Readable;
|
|
15
|
+
readonly killed: boolean;
|
|
16
|
+
readonly exitCode: number | null;
|
|
17
|
+
readonly signalCode: NodeJS.Signals | null;
|
|
18
|
+
kill(signal: NodeJS.Signals): boolean;
|
|
19
|
+
on(event: "exit" | "error", listener: (...args: any[]) => void): void;
|
|
20
|
+
once(event: "exit" | "error", listener: (...args: any[]) => void): void;
|
|
21
|
+
off(event: "exit" | "error", listener: (...args: any[]) => void): void;
|
|
22
|
+
}
|
|
23
|
+
/** The variables the SDK adds to the env it was given: its own markers, which the CLI reads. */
|
|
24
|
+
export declare const SDK_ENV_MARKERS: ReadonlySet<string>;
|
|
25
|
+
export interface SandboxSpawnOptions {
|
|
26
|
+
/** The session's machine (branded: the harness checked it). */
|
|
27
|
+
machine: SessionMachine;
|
|
28
|
+
/** The pinned binary: the only command this spawns. */
|
|
29
|
+
executable: string;
|
|
30
|
+
/** The env the harness gave the SDK (`query()`'s `env`). */
|
|
31
|
+
env: Readonly<Record<string, string>>;
|
|
32
|
+
/** The drive's signal: aborting it kills the child. */
|
|
33
|
+
signal: AbortSignal;
|
|
34
|
+
/** The child could not be started. */
|
|
35
|
+
onError: (err: unknown) => void;
|
|
36
|
+
/** The child is running. */
|
|
37
|
+
onSpawn?: (proc: SessionProcess) => void;
|
|
38
|
+
/** A transcript mirror line that doesn't map. Locally every line maps, so this is never called. */
|
|
39
|
+
onUnmapped?: (why: string) => void;
|
|
40
|
+
/** Runs before the spawn. */
|
|
41
|
+
prepare?: () => Promise<void> | void;
|
|
42
|
+
isolatedCommands?: boolean;
|
|
43
|
+
}
|
|
44
|
+
/** Whether `path` is a resume dir the SDK made (a `claude-resume-*` directly under `os.tmpdir()`). */
|
|
45
|
+
export declare function isResumeDir(path: string): boolean;
|
|
46
|
+
/** Why a resume dir holds more than the transcript (`projects/**`, regular files), if it does. */
|
|
47
|
+
export declare function resumeProblem(dir: string): string | undefined;
|
|
48
|
+
/** Why the SDK's spawn request is not the one the harness named, if it isn't. */
|
|
49
|
+
export declare function spawnProblem(request: SdkSpawnOptions, options: Pick<SandboxSpawnOptions, "executable" | "env">): string | undefined;
|
|
50
|
+
/** The spawn hook for the session's machine. */
|
|
51
|
+
export declare function sandboxSpawn(options: SandboxSpawnOptions): (request: SdkSpawnOptions) => SdkSpawnedProcess;
|
package/dist/spawn.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// The Claude Agent SDK's `spawnClaudeCodeProcess` on the session's local machine, written for AgentRun. The CLI runs on
|
|
2
|
+
// the machine the SDK runs on, so its transcript paths need no mapping; the hook's job is to start exactly the child the
|
|
3
|
+
// harness named, with exactly its environment:
|
|
4
|
+
// - the command is the pinned binary (`executable`), nothing else;
|
|
5
|
+
// - the SDK's env must be there, and hold only the variables the harness gave it (each with the harness's value) and the
|
|
6
|
+
// SDK's own markers. Its `CLAUDE_CONFIG_DIR` is the harness's, or, on a resume, the `claude-resume-*` dir the SDK made
|
|
7
|
+
// under this process's temporary dir, which may hold only the transcript (`projects/**`, regular files): a
|
|
8
|
+
// credential or settings file in it is refused;
|
|
9
|
+
// - the child starts through the machine (machine.ts): the allowlisted environment, its own process group, the session's
|
|
10
|
+
// working directory, ended with the drive and with the machine.
|
|
11
|
+
// A child that can't start is reported to `onError` (the harness halts the drive) and as the process's `error` event.
|
|
12
|
+
import { EventEmitter } from "node:events";
|
|
13
|
+
import { lstatSync, readdirSync } from "node:fs";
|
|
14
|
+
import { tmpdir } from "node:os";
|
|
15
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
16
|
+
import { PassThrough } from "node:stream";
|
|
17
|
+
import { ClaudeAgentPinMismatch } from "./errors.js";
|
|
18
|
+
import { CLAUDE_AGENT_SDK_VERSION } from "./versions.js";
|
|
19
|
+
/** The variables the SDK adds to the env it was given: its own markers, which the CLI reads. */
|
|
20
|
+
export const SDK_ENV_MARKERS = new Set(["CLAUDE_AGENT_SDK_VERSION", "CLAUDE_CODE_ENTRYPOINT", "CLAUDE_CODE_SDK_READS_SESSION_STATE"]);
|
|
21
|
+
/** Whether `path` is a resume dir the SDK made (a `claude-resume-*` directly under `os.tmpdir()`). */
|
|
22
|
+
export function isResumeDir(path) {
|
|
23
|
+
return resolve(dirname(path)) === resolve(tmpdir()) && basename(path).startsWith("claude-resume-");
|
|
24
|
+
}
|
|
25
|
+
/** Why a resume dir holds more than the transcript (`projects/**`, regular files), if it does. */
|
|
26
|
+
export function resumeProblem(dir) {
|
|
27
|
+
const walk = (rel) => {
|
|
28
|
+
for (const entry of readdirSync(join(dir, rel), { withFileTypes: true })) {
|
|
29
|
+
const path = rel ? `${rel}/${entry.name}` : entry.name;
|
|
30
|
+
const stat = lstatSync(join(dir, path));
|
|
31
|
+
if (!rel && path !== "projects")
|
|
32
|
+
return `${path} is beside the transcript`;
|
|
33
|
+
if (stat.isSymbolicLink())
|
|
34
|
+
return `${path} is a link`;
|
|
35
|
+
if (stat.isDirectory()) {
|
|
36
|
+
const inner = walk(path);
|
|
37
|
+
if (inner)
|
|
38
|
+
return inner;
|
|
39
|
+
}
|
|
40
|
+
else if (!stat.isFile())
|
|
41
|
+
return `${path} is not a regular file`;
|
|
42
|
+
}
|
|
43
|
+
return undefined;
|
|
44
|
+
};
|
|
45
|
+
try {
|
|
46
|
+
return walk("");
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
return `it could not be read: ${String(error?.message ?? error).slice(0, 120)}`;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** Why the SDK's spawn request is not the one the harness named, if it isn't. */
|
|
53
|
+
export function spawnProblem(request, options) {
|
|
54
|
+
if (request.command !== options.executable)
|
|
55
|
+
return `the command ${JSON.stringify(String(request.command).slice(0, 120))} is not the pinned binary`;
|
|
56
|
+
if (!request.env || typeof request.env !== "object")
|
|
57
|
+
return "the SDK passed no env";
|
|
58
|
+
for (const [name, value] of Object.entries(request.env)) {
|
|
59
|
+
if (value === undefined || SDK_ENV_MARKERS.has(name))
|
|
60
|
+
continue;
|
|
61
|
+
if (!(name in options.env))
|
|
62
|
+
return `the variable ${name.slice(0, 60)} is not one the harness gave`;
|
|
63
|
+
if (name === "CLAUDE_CONFIG_DIR" && value !== options.env[name]) {
|
|
64
|
+
if (!isResumeDir(value))
|
|
65
|
+
return "CLAUDE_CONFIG_DIR is neither the session's nor the SDK's resume dir";
|
|
66
|
+
const problem = resumeProblem(value);
|
|
67
|
+
if (problem)
|
|
68
|
+
return `the resume dir holds more than the transcript: ${problem}`;
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (value !== options.env[name])
|
|
72
|
+
return `the variable ${name.slice(0, 60)} does not have the harness's value`;
|
|
73
|
+
}
|
|
74
|
+
for (const name of Object.keys(options.env))
|
|
75
|
+
if (request.env[name] === undefined)
|
|
76
|
+
return `the variable ${name.slice(0, 60)} is missing`;
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
/** A process that never started: its streams are empty, and it reports `error` then `exit`. */
|
|
80
|
+
function failed(error) {
|
|
81
|
+
const events = new EventEmitter();
|
|
82
|
+
const stdout = new PassThrough();
|
|
83
|
+
setImmediate(() => {
|
|
84
|
+
events.emit("error", error);
|
|
85
|
+
stdout.end();
|
|
86
|
+
events.emit("exit", 1, null);
|
|
87
|
+
});
|
|
88
|
+
return {
|
|
89
|
+
stdin: new PassThrough(),
|
|
90
|
+
stdout,
|
|
91
|
+
killed: false,
|
|
92
|
+
exitCode: 1,
|
|
93
|
+
signalCode: null,
|
|
94
|
+
kill: () => false,
|
|
95
|
+
on: (event, listener) => void events.on(event, listener),
|
|
96
|
+
once: (event, listener) => void events.once(event, listener),
|
|
97
|
+
off: (event, listener) => void events.off(event, listener),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
/** The spawn hook for the session's machine. */
|
|
101
|
+
export function sandboxSpawn(options) {
|
|
102
|
+
return (request) => {
|
|
103
|
+
const refuse = (why) => {
|
|
104
|
+
const error = new Error(`agentrun-harness-claude: the CLI was not started: ${why}`);
|
|
105
|
+
options.onError(error);
|
|
106
|
+
return failed(error);
|
|
107
|
+
};
|
|
108
|
+
const machine = options.machine;
|
|
109
|
+
if (typeof machine.start !== "function")
|
|
110
|
+
return refuse("the session's machine is not a local one");
|
|
111
|
+
// The SDK says its own version to the CLI it starts: one that is not the pinned release starts nothing.
|
|
112
|
+
const sdkVersion = request.env?.CLAUDE_AGENT_SDK_VERSION;
|
|
113
|
+
if (sdkVersion !== undefined && sdkVersion !== CLAUDE_AGENT_SDK_VERSION) {
|
|
114
|
+
const error = new ClaudeAgentPinMismatch("sdk_version", CLAUDE_AGENT_SDK_VERSION, String(sdkVersion).slice(0, 40));
|
|
115
|
+
options.onError(error);
|
|
116
|
+
return failed(error);
|
|
117
|
+
}
|
|
118
|
+
const problem = spawnProblem(request, options);
|
|
119
|
+
if (problem)
|
|
120
|
+
return refuse(problem);
|
|
121
|
+
const env = Object.fromEntries(Object.entries(request.env).filter((e) => typeof e[1] === "string"));
|
|
122
|
+
try {
|
|
123
|
+
const proc = machine.start({ command: options.executable, args: request.args ?? [], env, cwd: options.machine.root, signal: AbortSignal.any([options.signal, request.signal]) });
|
|
124
|
+
options.onSpawn?.(proc);
|
|
125
|
+
return proc.child;
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
return refuse(String(error?.message ?? error).slice(0, 200));
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
}
|
package/dist/store.d.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import type { JournalRecord, NativeJournal, TranscriptEntry } from './host/process.js';
|
|
2
|
+
/**
|
|
3
|
+
* Claude Code's transcript, mirrored into the run's log.
|
|
4
|
+
*
|
|
5
|
+
* Claude Code writes its session as an append-only JSONL transcript. The
|
|
6
|
+
* Agent SDK mirrors every line it writes to a `SessionStore` (`append`), and a
|
|
7
|
+
* resume loads the session back from it (`load`) before the CLI starts. This
|
|
8
|
+
* store is that adapter over the drive's `NativeJournal`: each entry is one
|
|
9
|
+
* journal record (group-committed with everything else the drive writes),
|
|
10
|
+
* deduped by the entry's `uuid`, so the transcript is a fold of the log and
|
|
11
|
+
* any machine can resume it.
|
|
12
|
+
*
|
|
13
|
+
* The entries are opaque: their shape is CLI-internal. Two things are read
|
|
14
|
+
* from them: an assistant entry's `tool_use` ids (for the barrier below), and
|
|
15
|
+
* the `uuid` of a user message the drive sent (to tell whether a placed
|
|
16
|
+
* prompt reached the transcript): a user entry's own `uuid`, or, for a
|
|
17
|
+
* message the CLI took in mid-turn (a steer), the `source_uuid` of the
|
|
18
|
+
* `queued_command` attachment it became.
|
|
19
|
+
*/
|
|
20
|
+
/** The SDK's `SessionKey` (structurally; the SDK is a peer dependency). */
|
|
21
|
+
export interface SessionKey {
|
|
22
|
+
projectKey: string;
|
|
23
|
+
sessionId: string;
|
|
24
|
+
subpath?: string;
|
|
25
|
+
}
|
|
26
|
+
/** One transcript line, as the SDK hands it over: JSON with a string `type`. */
|
|
27
|
+
export interface TranscriptLine {
|
|
28
|
+
type: string;
|
|
29
|
+
uuid?: string;
|
|
30
|
+
[k: string]: unknown;
|
|
31
|
+
}
|
|
32
|
+
/** The journal stream of the main transcript. */
|
|
33
|
+
export declare const CLAUDE_STREAM = "claude";
|
|
34
|
+
/** The journal stream of a subagent transcript (`subpath` like `subagents/agent-<id>`). */
|
|
35
|
+
export declare const subStream: (subpath: string) => string;
|
|
36
|
+
/** The `tool_use` ids an assistant entry carries. */
|
|
37
|
+
export declare function toolUseIds(entry: TranscriptLine | undefined): string[];
|
|
38
|
+
/** The `tool_use_id`s a user entry answers (its `tool_result` blocks). */
|
|
39
|
+
export declare function toolResultIds(entry: TranscriptLine | undefined): string[];
|
|
40
|
+
export interface JournalSessionStoreOptions {
|
|
41
|
+
/** The journal's records as of the drive's start, blobs resolved (`journal.read()`). */
|
|
42
|
+
records: JournalRecord[];
|
|
43
|
+
/**
|
|
44
|
+
* Hold appended entries this long before they go to the journal, so the
|
|
45
|
+
* SDK's frames (one `append` per line with eager flushing) ride in fewer
|
|
46
|
+
* batches. `barrier` and `flush` send them at once. Default 0.
|
|
47
|
+
*/
|
|
48
|
+
coalesceMs?: number;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* A `SessionStore` (the SDK's `@alpha` mirror interface) whose storage is the
|
|
52
|
+
* drive's journal.
|
|
53
|
+
*
|
|
54
|
+
* - `append` queues the entries on the journal and returns: the journal is
|
|
55
|
+
* the durable writer (one batch in flight, the rest in the next), so the
|
|
56
|
+
* SDK's own retries and timeouts never come into play. A journal that
|
|
57
|
+
* failed has already halted the drive.
|
|
58
|
+
* - `load` returns what the log holds, as of the drive's start. Every
|
|
59
|
+
* session's key is the run, so `projectKey` (the CLI's cwd, which differs
|
|
60
|
+
* from machine to machine) is ignored.
|
|
61
|
+
* - `barrier(toolUseId)` resolves once the assistant entry that made that
|
|
62
|
+
* call is committed: before a `replay: 'never'` tool runs, the call that
|
|
63
|
+
* asked for it is in the log.
|
|
64
|
+
*/
|
|
65
|
+
export declare class JournalSessionStore {
|
|
66
|
+
private readonly journal;
|
|
67
|
+
private readonly loaded;
|
|
68
|
+
private readonly calls;
|
|
69
|
+
private readonly users;
|
|
70
|
+
private readonly waiters;
|
|
71
|
+
private readonly results;
|
|
72
|
+
private readonly resultWaiters;
|
|
73
|
+
private held;
|
|
74
|
+
private timer;
|
|
75
|
+
private readonly coalesceMs;
|
|
76
|
+
/** Entries this drive appended (for tests and diagnostics). */
|
|
77
|
+
appended: number;
|
|
78
|
+
constructor(journal: NativeJournal, options: JournalSessionStoreOptions);
|
|
79
|
+
/**
|
|
80
|
+
* Whether the log holds a transcript to resume: one with a message in it.
|
|
81
|
+
* Lines committed before a crash may be only queue operations, and the CLI
|
|
82
|
+
* refuses to resume those ("No conversation found"), every time: such a
|
|
83
|
+
* session starts again as a new one, under the same id.
|
|
84
|
+
*/
|
|
85
|
+
get hasSession(): boolean;
|
|
86
|
+
/**
|
|
87
|
+
* Whether the user message sent with this `uuid` is in the transcript (the
|
|
88
|
+
* log's, or appended since): as its own user entry, or as the
|
|
89
|
+
* `queued_command` attachment a mid-turn message becomes.
|
|
90
|
+
*/
|
|
91
|
+
hasUser(uuid: string): boolean;
|
|
92
|
+
/** Whether an assistant entry that made this tool call is in the transcript. */
|
|
93
|
+
hasCall(toolUseId: string): boolean;
|
|
94
|
+
append(key: SessionKey, entries: TranscriptLine[]): Promise<void>;
|
|
95
|
+
/** An entry of the normalized transcript, held and committed with the lines around it. */
|
|
96
|
+
message(entry: TranscriptEntry): void;
|
|
97
|
+
/** Everything appended so far is committed. */
|
|
98
|
+
flush(): Promise<void>;
|
|
99
|
+
/** Hand the held entries to the journal (which group-commits them). */
|
|
100
|
+
private release;
|
|
101
|
+
load(key: SessionKey): Promise<TranscriptLine[] | null>;
|
|
102
|
+
listSubkeys(_key: {
|
|
103
|
+
projectKey: string;
|
|
104
|
+
sessionId: string;
|
|
105
|
+
}): Promise<string[]>;
|
|
106
|
+
/**
|
|
107
|
+
* Resolve once the assistant entry that made `toolUseId` is committed. The
|
|
108
|
+
* SDK delivers an entry about 100 ms after the CLI wrote it, and the tool
|
|
109
|
+
* runs right after the CLI wrote it, so this usually waits for the mirror
|
|
110
|
+
* first. Rejects after `timeoutMs` (the caller does not run the tool).
|
|
111
|
+
*/
|
|
112
|
+
barrier(toolUseId: string, timeoutMs: number): Promise<void>;
|
|
113
|
+
private note;
|
|
114
|
+
/**
|
|
115
|
+
* Resolve once the user entry that answers `toolUseId` (its `tool_result`) is committed: a call the CLI answered
|
|
116
|
+
* itself (a refusal) is told to the host only once the log holds the answer. Rejects after `timeoutMs`.
|
|
117
|
+
*/
|
|
118
|
+
resultBarrier(toolUseId: string, timeoutMs: number): Promise<void>;
|
|
119
|
+
}
|