@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.
Files changed (50) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +4 -0
  4. package/README.md +56 -2
  5. package/dist/adapter.d.ts +129 -0
  6. package/dist/adapter.js +514 -0
  7. package/dist/binary.d.ts +25 -0
  8. package/dist/binary.js +71 -0
  9. package/dist/cli-names.d.ts +7 -0
  10. package/dist/cli-names.js +17 -0
  11. package/dist/env.d.ts +81 -0
  12. package/dist/env.js +92 -0
  13. package/dist/errors.d.ts +27 -0
  14. package/dist/errors.js +42 -0
  15. package/dist/harness.d.ts +287 -0
  16. package/dist/harness.js +887 -0
  17. package/dist/host/kernel.d.ts +10 -0
  18. package/dist/host/kernel.js +1 -0
  19. package/dist/host/machine.d.ts +77 -0
  20. package/dist/host/machine.js +261 -0
  21. package/dist/host/policy.d.ts +104 -0
  22. package/dist/host/policy.js +437 -0
  23. package/dist/host/process.d.ts +130 -0
  24. package/dist/host/process.js +31 -0
  25. package/dist/host/tool-server.d.ts +44 -0
  26. package/dist/host/tool-server.js +47 -0
  27. package/dist/ids.d.ts +9 -0
  28. package/dist/ids.js +17 -0
  29. package/dist/inbox.d.ts +14 -0
  30. package/dist/inbox.js +36 -0
  31. package/dist/index.d.ts +11 -0
  32. package/dist/index.js +7 -0
  33. package/dist/serial.d.ts +3 -0
  34. package/dist/serial.js +10 -0
  35. package/dist/spawn.d.ts +51 -0
  36. package/dist/spawn.js +131 -0
  37. package/dist/store.d.ts +119 -0
  38. package/dist/store.js +202 -0
  39. package/dist/testing/fake-anthropic.d.ts +97 -0
  40. package/dist/testing/fake-anthropic.js +279 -0
  41. package/dist/testing/fake-sdk.d.ts +60 -0
  42. package/dist/testing/fake-sdk.js +402 -0
  43. package/dist/testing/index.d.ts +3 -0
  44. package/dist/testing/index.js +5 -0
  45. package/dist/transcript.d.ts +73 -0
  46. package/dist/transcript.js +116 -0
  47. package/dist/versions.d.ts +34 -0
  48. package/dist/versions.js +76 -0
  49. package/package.json +76 -4
  50. package/vendor/durable-harness/UPSTREAM.json +59 -0
package/dist/store.js ADDED
@@ -0,0 +1,202 @@
1
+ /** The journal stream of the main transcript. */
2
+ export const CLAUDE_STREAM = 'claude';
3
+ /** The journal stream of a subagent transcript (`subpath` like `subagents/agent-<id>`). */
4
+ export const subStream = (subpath) => `${CLAUDE_STREAM}/${subpath}`;
5
+ const streamOf = (key) => (key.subpath ? subStream(key.subpath) : CLAUDE_STREAM);
6
+ /** The `tool_use` ids an assistant entry carries. */
7
+ export function toolUseIds(entry) {
8
+ if (entry?.type !== 'assistant')
9
+ return [];
10
+ const content = entry.message?.content;
11
+ if (!Array.isArray(content))
12
+ return [];
13
+ return content.filter((c) => c?.type === 'tool_use' && typeof c.id === 'string').map((c) => c.id);
14
+ }
15
+ /** The `tool_use_id`s a user entry answers (its `tool_result` blocks). */
16
+ export function toolResultIds(entry) {
17
+ if (entry?.type !== 'user')
18
+ return [];
19
+ const content = entry.message?.content;
20
+ if (!Array.isArray(content))
21
+ return [];
22
+ return content.filter((c) => c?.type === 'tool_result' && typeof c.tool_use_id === 'string').map((c) => c.tool_use_id);
23
+ }
24
+ /**
25
+ * A `SessionStore` (the SDK's `@alpha` mirror interface) whose storage is the
26
+ * drive's journal.
27
+ *
28
+ * - `append` queues the entries on the journal and returns: the journal is
29
+ * the durable writer (one batch in flight, the rest in the next), so the
30
+ * SDK's own retries and timeouts never come into play. A journal that
31
+ * failed has already halted the drive.
32
+ * - `load` returns what the log holds, as of the drive's start. Every
33
+ * session's key is the run, so `projectKey` (the CLI's cwd, which differs
34
+ * from machine to machine) is ignored.
35
+ * - `barrier(toolUseId)` resolves once the assistant entry that made that
36
+ * call is committed: before a `replay: 'never'` tool runs, the call that
37
+ * asked for it is in the log.
38
+ */
39
+ export class JournalSessionStore {
40
+ journal;
41
+ loaded = new Map();
42
+ calls = new Set();
43
+ users = new Set();
44
+ waiters = new Map();
45
+ results = new Set();
46
+ resultWaiters = new Map();
47
+ held = [];
48
+ timer;
49
+ coalesceMs;
50
+ /** Entries this drive appended (for tests and diagnostics). */
51
+ appended = 0;
52
+ constructor(journal, options) {
53
+ this.journal = journal;
54
+ this.coalesceMs = options.coalesceMs ?? 0;
55
+ for (const r of options.records) {
56
+ if (r.stream !== CLAUDE_STREAM && !r.stream.startsWith(`${CLAUDE_STREAM}/`))
57
+ continue;
58
+ const entry = r.data;
59
+ // An offloaded entry read without its blob (`journalRecords`, not `journal.read()`): nothing to note.
60
+ if (!entry)
61
+ continue;
62
+ const list = this.loaded.get(r.stream) ?? [];
63
+ list.push(entry);
64
+ this.loaded.set(r.stream, list);
65
+ this.note(entry);
66
+ }
67
+ }
68
+ /**
69
+ * Whether the log holds a transcript to resume: one with a message in it.
70
+ * Lines committed before a crash may be only queue operations, and the CLI
71
+ * refuses to resume those ("No conversation found"), every time: such a
72
+ * session starts again as a new one, under the same id.
73
+ */
74
+ get hasSession() {
75
+ return (this.loaded.get(CLAUDE_STREAM) ?? []).some((e) => (e.type === 'user' || e.type === 'assistant') && !!e.uuid);
76
+ }
77
+ /**
78
+ * Whether the user message sent with this `uuid` is in the transcript (the
79
+ * log's, or appended since): as its own user entry, or as the
80
+ * `queued_command` attachment a mid-turn message becomes.
81
+ */
82
+ hasUser(uuid) {
83
+ return this.users.has(uuid);
84
+ }
85
+ /** Whether an assistant entry that made this tool call is in the transcript. */
86
+ hasCall(toolUseId) {
87
+ return this.calls.has(toolUseId);
88
+ }
89
+ async append(key, entries) {
90
+ const stream = streamOf(key);
91
+ for (const entry of entries) {
92
+ this.held.push({ stream, entry });
93
+ this.appended++;
94
+ this.note(entry);
95
+ }
96
+ if (this.coalesceMs <= 0)
97
+ this.release();
98
+ else
99
+ this.timer ??= setTimeout(() => this.release(), this.coalesceMs);
100
+ }
101
+ /** An entry of the normalized transcript, held and committed with the lines around it. */
102
+ message(entry) {
103
+ this.held.push({ message: entry });
104
+ if (this.coalesceMs <= 0)
105
+ this.release();
106
+ else
107
+ this.timer ??= setTimeout(() => this.release(), this.coalesceMs);
108
+ }
109
+ /** Everything appended so far is committed. */
110
+ async flush() {
111
+ this.release();
112
+ await this.journal.flush();
113
+ }
114
+ /** Hand the held entries to the journal (which group-commits them). */
115
+ release() {
116
+ clearTimeout(this.timer);
117
+ this.timer = undefined;
118
+ for (const item of this.held.splice(0)) {
119
+ if ('message' in item)
120
+ this.journal.message(item.message);
121
+ // Entries without a uuid (titles, mode markers, queue operations) are appended as they come.
122
+ else
123
+ this.journal.append(item.stream, item.entry, item.entry.uuid ? { id: item.entry.uuid } : {});
124
+ }
125
+ }
126
+ async load(key) {
127
+ const entries = this.loaded.get(streamOf(key));
128
+ return entries?.length ? entries : null;
129
+ }
130
+ async listSubkeys(_key) {
131
+ return [...this.loaded.keys()].filter((s) => s !== CLAUDE_STREAM).map((s) => s.slice(CLAUDE_STREAM.length + 1));
132
+ }
133
+ /**
134
+ * Resolve once the assistant entry that made `toolUseId` is committed. The
135
+ * SDK delivers an entry about 100 ms after the CLI wrote it, and the tool
136
+ * runs right after the CLI wrote it, so this usually waits for the mirror
137
+ * first. Rejects after `timeoutMs` (the caller does not run the tool).
138
+ */
139
+ async barrier(toolUseId, timeoutMs) {
140
+ if (!this.calls.has(toolUseId)) {
141
+ await new Promise((resolve, reject) => {
142
+ const timer = setTimeout(() => {
143
+ const list = this.waiters.get(toolUseId)?.filter((w) => w !== done) ?? [];
144
+ if (list.length)
145
+ this.waiters.set(toolUseId, list);
146
+ else
147
+ this.waiters.delete(toolUseId);
148
+ reject(new Error(`the transcript entry for tool call ${toolUseId} did not reach the log within ${timeoutMs} ms`));
149
+ }, timeoutMs);
150
+ const done = () => {
151
+ clearTimeout(timer);
152
+ resolve();
153
+ };
154
+ this.waiters.set(toolUseId, [...(this.waiters.get(toolUseId) ?? []), done]);
155
+ });
156
+ }
157
+ await this.flush();
158
+ }
159
+ note(entry) {
160
+ if (entry.type === 'user' && entry.uuid)
161
+ this.users.add(entry.uuid);
162
+ const attachment = entry.type === 'attachment' ? entry.attachment : undefined;
163
+ if (attachment?.type === 'queued_command' && typeof attachment.source_uuid === 'string')
164
+ this.users.add(attachment.source_uuid);
165
+ for (const id of toolUseIds(entry)) {
166
+ this.calls.add(id);
167
+ for (const w of this.waiters.get(id) ?? [])
168
+ w();
169
+ this.waiters.delete(id);
170
+ }
171
+ for (const id of toolResultIds(entry)) {
172
+ this.results.add(id);
173
+ for (const w of this.resultWaiters.get(id) ?? [])
174
+ w();
175
+ this.resultWaiters.delete(id);
176
+ }
177
+ }
178
+ /**
179
+ * Resolve once the user entry that answers `toolUseId` (its `tool_result`) is committed: a call the CLI answered
180
+ * itself (a refusal) is told to the host only once the log holds the answer. Rejects after `timeoutMs`.
181
+ */
182
+ async resultBarrier(toolUseId, timeoutMs) {
183
+ if (!this.results.has(toolUseId)) {
184
+ await new Promise((resolve, reject) => {
185
+ const timer = setTimeout(() => {
186
+ const list = this.resultWaiters.get(toolUseId)?.filter((w) => w !== done) ?? [];
187
+ if (list.length)
188
+ this.resultWaiters.set(toolUseId, list);
189
+ else
190
+ this.resultWaiters.delete(toolUseId);
191
+ reject(new Error(`the transcript entry answering tool call ${toolUseId} did not reach the log within ${timeoutMs} ms`));
192
+ }, timeoutMs);
193
+ const done = () => {
194
+ clearTimeout(timer);
195
+ resolve();
196
+ };
197
+ this.resultWaiters.set(toolUseId, [...(this.resultWaiters.get(toolUseId) ?? []), done]);
198
+ });
199
+ }
200
+ await this.flush();
201
+ }
202
+ }
@@ -0,0 +1,97 @@
1
+ /** One content block, as the Messages API carries it. */
2
+ export type Block = {
3
+ type: string;
4
+ [key: string]: unknown;
5
+ };
6
+ /** One message of a request. */
7
+ export interface Message {
8
+ role: 'user' | 'assistant';
9
+ content: string | Block[];
10
+ }
11
+ /** A request as the script sees it. */
12
+ export interface FakeRequest {
13
+ method: string;
14
+ path: string;
15
+ query: string;
16
+ /** Header names (lowercase) and values, without `authorization` and `x-api-key`. */
17
+ headers: Record<string, string>;
18
+ /** Whether it carried a bearer or an api key (never the value). */
19
+ authorized: boolean;
20
+ body: Record<string, any>;
21
+ model?: string;
22
+ messages: Message[];
23
+ /** The tool names the request offers. */
24
+ tools: string[];
25
+ /** Every text block (and string content) of the conversation, joined, for scripts that look for a word. */
26
+ text: string;
27
+ /** The last user message's tool results, by tool_use id. */
28
+ results: Record<string, string>;
29
+ }
30
+ /** A thinking model's blocks before its answer: its thinking (signed), and a redacted one. */
31
+ type Thought = {
32
+ thinking?: string;
33
+ redacted?: string;
34
+ };
35
+ /** What the model says for one request. */
36
+ export type FakeReply = ({
37
+ text: string;
38
+ } & Thought) | ({
39
+ tool: {
40
+ name: string;
41
+ input: unknown;
42
+ id?: string;
43
+ };
44
+ text?: string;
45
+ } & Thought)
46
+ /** The provider's own web search (the answer to a request with its web search tool): its call and results, then
47
+ * `text`, with `searches` (default 1) in `usage.server_tool_use.web_search_requests`. */
48
+ | {
49
+ search: {
50
+ query: string;
51
+ results: {
52
+ title: string;
53
+ url: string;
54
+ }[];
55
+ text: string;
56
+ searches?: number;
57
+ };
58
+ } | {
59
+ error: {
60
+ status: number;
61
+ type: string;
62
+ message: string;
63
+ };
64
+ }
65
+ /** Hold the response open (after `message_start`) until `release` resolves, then say `then`. */
66
+ | {
67
+ hold: Promise<void>;
68
+ then: FakeReply;
69
+ };
70
+ export interface FakeAnthropicOptions {
71
+ /** The script: what to answer a `POST /v1/messages`. */
72
+ reply: (request: FakeRequest) => FakeReply | Promise<FakeReply>;
73
+ /** The Gateway's cost per response (`gatewayCost`). Default `'0.0001'`. */
74
+ cost?: string;
75
+ }
76
+ /** What the fake logged of a request, and what it answered. */
77
+ export interface LoggedRequest extends Omit<FakeRequest, 'body'> {
78
+ body: Record<string, any>;
79
+ status: number;
80
+ /** Why it was refused (a 400), if it was. */
81
+ refused?: string;
82
+ }
83
+ export interface FakeAnthropic {
84
+ /** `http://127.0.0.1:<port>`. */
85
+ url: string;
86
+ readonly requests: LoggedRequest[];
87
+ /** The `POST /v1/messages` requests (the model calls), in order. */
88
+ messages(): LoggedRequest[];
89
+ close(): Promise<void>;
90
+ }
91
+ /** The last user message's text (its string content, or its text blocks), without tool results. */
92
+ export declare function lastUserText(r: Pick<FakeRequest, 'messages'>): string;
93
+ /** Why `messages` breaks the Messages API's structure, or undefined when it doesn't. */
94
+ export declare function structureProblem(all: unknown): string | undefined;
95
+ /** Start the fake on a free loopback port. */
96
+ export declare function fakeAnthropic(options: FakeAnthropicOptions): Promise<FakeAnthropic>;
97
+ export {};
@@ -0,0 +1,279 @@
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/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
4
+ /**
5
+ * A scripted Anthropic Messages API for the real Claude Code CLI (docs/workspaces.md
6
+ * §11.4, "the restart-on-a-new-sandbox tests"): what `query()` and the pinned
7
+ * `claude` binary talk to in CI, with no key and no network. Grown from
8
+ * `harness-sandbox/probes/claude-code/spawn-and-resume.mjs`'s server.
9
+ *
10
+ * It enforces the structure the real API enforces, and answers a request that
11
+ * breaks it with the real API's 400 (`invalid_request_error`), so a resume
12
+ * that rebuilt a conversation wrong fails here as it would in production:
13
+ *
14
+ * - `messages` is a non-empty array that starts with a `user` message, and
15
+ * the roles alternate strictly;
16
+ * - every message has content (a non-empty string or block list), except an
17
+ * optional final assistant message;
18
+ * - every `tool_use` in an assistant message is answered by a `tool_result`
19
+ * with its id in the very next user message, and every `tool_result`
20
+ * answers a `tool_use` of the message before it (no dangling calls, no
21
+ * orphan results);
22
+ * - no `tool_use` id appears twice in the conversation, and no block is
23
+ * repeated within a message.
24
+ *
25
+ * What it says is the test's `reply` script, per request. Every streamed
26
+ * reply ends with the Gateway's cost in `message_delta`
27
+ * (`provider_metadata.gateway`, P0.18), so the gateway handler's ledger is
28
+ * charged a real figure. Every request is logged (`requests`): method, path,
29
+ * query, header names, `anthropic-beta`, model, and the parsed body; never an
30
+ * authorization header's value.
31
+ */
32
+ import { createServer } from 'node:http';
33
+ let toolSeq = 0;
34
+ /** The last user message's text (its string content, or its text blocks), without tool results. */
35
+ export function lastUserText(r) {
36
+ const m = [...r.messages].reverse().find((x) => x.role === 'user');
37
+ if (!m)
38
+ return '';
39
+ if (typeof m.content === 'string')
40
+ return m.content;
41
+ return m.content.filter((b) => b.type === 'text').map((b) => String(b.text)).join('\n');
42
+ }
43
+ /** Why `messages` breaks the Messages API's structure, or undefined when it doesn't. */
44
+ export function structureProblem(all) {
45
+ if (!Array.isArray(all) || all.length === 0)
46
+ return 'messages: at least one message is required';
47
+ // A system message after the first (Claude Code 2.1.296's environment note, to a model that takes an effort) is the API's own: the rest must still alternate.
48
+ const messages = all.filter((m, i) => !(i > 0 && m?.role === 'system'));
49
+ const seenToolUse = new Set();
50
+ for (let i = 0; i < messages.length; i++) {
51
+ const m = messages[i];
52
+ if (!m || (m.role !== 'user' && m.role !== 'assistant'))
53
+ return `messages.${i}.role: must be user or assistant`;
54
+ if (i === 0 && m.role !== 'user')
55
+ return 'messages: the first message must use the "user" role';
56
+ if (i > 0 && messages[i - 1].role === m.role)
57
+ return `messages.${i}: roles must alternate between "user" and "assistant"`;
58
+ const last = i === messages.length - 1;
59
+ const blocks = typeof m.content === 'string' ? undefined : m.content;
60
+ const empty = typeof m.content === 'string' ? m.content.length === 0 : !Array.isArray(m.content) || m.content.length === 0;
61
+ if (empty && !(last && m.role === 'assistant'))
62
+ return `messages.${i}: all messages must have non-empty content except for the optional final assistant message`;
63
+ if (blocks) {
64
+ const keys = new Set();
65
+ for (const b of blocks) {
66
+ const key = JSON.stringify(b);
67
+ if (keys.has(key))
68
+ return `messages.${i}: a content block is repeated`;
69
+ keys.add(key);
70
+ if (b.type === 'tool_use') {
71
+ const id = String(b.id);
72
+ if (seenToolUse.has(id))
73
+ return `messages.${i}: \`tool_use\` ids must be unique (${id})`;
74
+ seenToolUse.add(id);
75
+ }
76
+ }
77
+ }
78
+ // Every tool_use is answered by the very next message; every tool_result answers the message before it.
79
+ if (m.role === 'assistant' && blocks) {
80
+ const uses = blocks.filter((b) => b.type === 'tool_use').map((b) => String(b.id));
81
+ if (uses.length) {
82
+ const next = messages[i + 1];
83
+ const answered = new Set(next && Array.isArray(next.content) ? next.content.filter((b) => b.type === 'tool_result').map((b) => String(b.tool_use_id)) : []);
84
+ const dangling = uses.filter((id) => !answered.has(id));
85
+ if (dangling.length)
86
+ return `messages.${i + 1}: \`tool_use\` ids were found without \`tool_result\` blocks immediately after: ${dangling.join(', ')}. Each \`tool_use\` block must have a corresponding \`tool_result\` block in the next message.`;
87
+ }
88
+ }
89
+ if (m.role === 'user' && blocks) {
90
+ const results = blocks.filter((b) => b.type === 'tool_result').map((b) => String(b.tool_use_id));
91
+ if (results.length) {
92
+ const prev = messages[i - 1];
93
+ const uses = new Set(prev && Array.isArray(prev.content) ? prev.content.filter((b) => b.type === 'tool_use').map((b) => String(b.id)) : []);
94
+ const orphan = results.filter((id) => !uses.has(id));
95
+ if (orphan.length)
96
+ return `messages.${i}.content: unexpected \`tool_use_id\` found in \`tool_result\` blocks: ${orphan.join(', ')}. Each \`tool_result\` block must have a corresponding \`tool_use\` block in the previous message.`;
97
+ }
98
+ }
99
+ }
100
+ return undefined;
101
+ }
102
+ function textOf(messages, system) {
103
+ const out = [];
104
+ const walk = (c) => {
105
+ if (typeof c === 'string')
106
+ out.push(c);
107
+ else if (Array.isArray(c))
108
+ for (const b of c) {
109
+ if (typeof b?.text === 'string')
110
+ out.push(b.text);
111
+ if (b?.type === 'tool_result')
112
+ walk(b.content);
113
+ }
114
+ };
115
+ for (const m of messages)
116
+ walk(m.content);
117
+ walk(system);
118
+ return out.join('\n');
119
+ }
120
+ function resultsOf(messages) {
121
+ const last = messages.at(-1);
122
+ const out = {};
123
+ if (last?.role !== 'user' || !Array.isArray(last.content))
124
+ return out;
125
+ for (const b of last.content) {
126
+ if (b.type !== 'tool_result')
127
+ continue;
128
+ const c = b.content;
129
+ out[String(b.tool_use_id)] = typeof c === 'string' ? c : Array.isArray(c) ? c.map((x) => (typeof x.text === 'string' ? x.text : '')).join('') : '';
130
+ }
131
+ return out;
132
+ }
133
+ async function body(req) {
134
+ const chunks = [];
135
+ for await (const c of req)
136
+ chunks.push(c);
137
+ return Buffer.concat(chunks).toString('utf8');
138
+ }
139
+ /** Start the fake on a free loopback port. */
140
+ export async function fakeAnthropic(options) {
141
+ const requests = [];
142
+ const cost = options.cost ?? '0.0001';
143
+ const sockets = new Set();
144
+ const server = createServer((req, res) => {
145
+ void handle(req, res).catch((err) => {
146
+ if (!res.headersSent)
147
+ res.writeHead(500, { 'content-type': 'application/json' });
148
+ res.end(JSON.stringify({ type: 'error', error: { type: 'api_error', message: String(err?.message ?? err) } }));
149
+ });
150
+ });
151
+ server.on('connection', (s) => {
152
+ sockets.add(s);
153
+ s.on('close', () => sockets.delete(s));
154
+ });
155
+ async function handle(req, res) {
156
+ const url = new URL(req.url ?? '/', 'http://fake');
157
+ const text = await body(req);
158
+ let parsed = {};
159
+ try {
160
+ parsed = text ? JSON.parse(text) : {};
161
+ }
162
+ catch { }
163
+ const headers = Object.fromEntries(Object.entries(req.headers).filter(([k]) => k !== 'authorization' && k !== 'x-api-key').map(([k, v]) => [k, Array.isArray(v) ? v.join(', ') : String(v ?? '')]));
164
+ const messages = (Array.isArray(parsed.messages) ? parsed.messages : []);
165
+ const request = {
166
+ method: req.method ?? 'GET',
167
+ path: url.pathname,
168
+ query: url.search.replace(/^\?/, ''),
169
+ headers,
170
+ authorized: !!(req.headers.authorization || req.headers['x-api-key']),
171
+ body: parsed,
172
+ ...(typeof parsed.model === 'string' ? { model: parsed.model } : {}),
173
+ messages,
174
+ tools: Array.isArray(parsed.tools) ? parsed.tools.map((t) => String(t?.name)) : [],
175
+ text: textOf(messages, parsed.system),
176
+ results: resultsOf(messages),
177
+ };
178
+ const logged = { ...request, status: 200 };
179
+ requests.push(logged);
180
+ const fail = (status, type, message) => {
181
+ logged.status = status;
182
+ if (status === 400)
183
+ logged.refused = message;
184
+ res.writeHead(status, { 'content-type': 'application/json', 'request-id': `req_fake_${requests.length}` });
185
+ res.end(JSON.stringify({ type: 'error', error: { type, message } }));
186
+ };
187
+ if (req.method === 'POST' && url.pathname === '/v1/messages/count_tokens') {
188
+ const problem = structureProblem(messages);
189
+ if (problem)
190
+ return fail(400, 'invalid_request_error', problem);
191
+ res.writeHead(200, { 'content-type': 'application/json' });
192
+ return void res.end(JSON.stringify({ input_tokens: Math.ceil(text.length / 4) }));
193
+ }
194
+ if (req.method !== 'POST' || url.pathname !== '/v1/messages')
195
+ return fail(404, 'not_found_error', `${req.method} ${url.pathname} is not a route here`);
196
+ if (typeof parsed.model !== 'string')
197
+ return fail(400, 'invalid_request_error', 'model: Field required');
198
+ if (typeof parsed.max_tokens !== 'number')
199
+ return fail(400, 'invalid_request_error', 'max_tokens: Field required');
200
+ const problem = structureProblem(messages);
201
+ if (problem)
202
+ return fail(400, 'invalid_request_error', problem);
203
+ let reply = await options.reply(request);
204
+ let held;
205
+ if ('hold' in reply) {
206
+ held = reply.hold;
207
+ reply = reply.then;
208
+ }
209
+ if ('error' in reply)
210
+ return fail(reply.error.status, reply.error.type, reply.error.message);
211
+ const blocks = [];
212
+ if ('thinking' in reply && reply.thinking)
213
+ blocks.push({ type: 'thinking', thinking: reply.thinking, signature: `sig_fake_${requests.length}` });
214
+ if ('redacted' in reply && reply.redacted)
215
+ blocks.push({ type: 'redacted_thinking', data: reply.redacted });
216
+ if ('text' in reply && reply.text)
217
+ blocks.push({ type: 'text', text: reply.text });
218
+ if ('tool' in reply)
219
+ blocks.push({ type: 'tool_use', id: reply.tool.id ?? `toolu_fake_${String(++toolSeq).padStart(4, '0')}_${Date.now().toString(36)}`, name: reply.tool.name, input: reply.tool.input });
220
+ if ('search' in reply) {
221
+ const id = `srvtoolu_fake_${String(++toolSeq).padStart(4, '0')}`;
222
+ blocks.push({ type: 'server_tool_use', id, name: 'web_search', input: { query: reply.search.query } });
223
+ blocks.push({ type: 'web_search_tool_result', tool_use_id: id, content: reply.search.results.map((r) => ({ type: 'web_search_result', title: r.title, url: r.url, encrypted_content: 'ZmFrZQ==', page_age: null })) });
224
+ blocks.push({ type: 'text', text: reply.search.text });
225
+ }
226
+ const stopReason = 'tool' in reply ? 'tool_use' : 'end_turn';
227
+ // The real API's shape, nested objects included (a recorded response is in test/fixtures/).
228
+ const searched = 'search' in reply ? { server_tool_use: { web_search_requests: reply.search.searches ?? 1 } } : {};
229
+ const usage = { input_tokens: Math.ceil(text.length / 4), cache_creation_input_tokens: 0, cache_read_input_tokens: 0, cache_creation: { ephemeral_5m_input_tokens: 0, ephemeral_1h_input_tokens: 0 }, output_tokens: 12, output_tokens_details: { thinking_tokens: 0 }, service_tier: 'standard', ...searched };
230
+ const id = `msg_fake_${requests.length}`;
231
+ const metadata = { gateway: { cost, gatewayCost: cost } };
232
+ if (parsed.stream !== true) {
233
+ res.writeHead(200, { 'content-type': 'application/json', 'request-id': `req_fake_${requests.length}` });
234
+ return void res.end(JSON.stringify({ id, type: 'message', role: 'assistant', model: parsed.model, content: blocks, stop_reason: stopReason, stop_sequence: null, usage, provider_metadata: metadata }));
235
+ }
236
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache', 'request-id': `req_fake_${requests.length}` });
237
+ const ev = (type, data) => res.write(`event: ${type}\ndata: ${JSON.stringify(data)}\n\n`);
238
+ ev('message_start', { type: 'message_start', message: { id, type: 'message', role: 'assistant', model: parsed.model, content: [], stop_reason: null, stop_sequence: null, usage: { ...usage, output_tokens: 1, output_tokens_details: undefined, ...('search' in reply ? { server_tool_use: { web_search_requests: 0 } } : {}) } } });
239
+ if (held)
240
+ await held;
241
+ blocks.forEach((b, index) => {
242
+ if (b.type === 'thinking') {
243
+ ev('content_block_start', { type: 'content_block_start', index, content_block: { type: 'thinking', thinking: '', signature: '' } });
244
+ ev('content_block_delta', { type: 'content_block_delta', index, delta: { type: 'thinking_delta', thinking: b.thinking } });
245
+ ev('content_block_delta', { type: 'content_block_delta', index, delta: { type: 'signature_delta', signature: b.signature } });
246
+ }
247
+ else if (b.type === 'redacted_thinking') {
248
+ ev('content_block_start', { type: 'content_block_start', index, content_block: { type: 'redacted_thinking', data: b.data } });
249
+ }
250
+ else if (b.type === 'text') {
251
+ ev('content_block_start', { type: 'content_block_start', index, content_block: { type: 'text', text: '' } });
252
+ ev('content_block_delta', { type: 'content_block_delta', index, delta: { type: 'text_delta', text: b.text } });
253
+ }
254
+ else if (b.type === 'web_search_tool_result') {
255
+ ev('content_block_start', { type: 'content_block_start', index, content_block: b });
256
+ }
257
+ else {
258
+ ev('content_block_start', { type: 'content_block_start', index, content_block: { type: b.type, id: b.id, name: b.name, input: {} } });
259
+ ev('content_block_delta', { type: 'content_block_delta', index, delta: { type: 'input_json_delta', partial_json: JSON.stringify(b.input) } });
260
+ }
261
+ ev('content_block_stop', { type: 'content_block_stop', index });
262
+ });
263
+ ev('message_delta', { type: 'message_delta', delta: { stop_reason: stopReason, stop_sequence: null }, usage: { input_tokens: usage.input_tokens, cache_creation_input_tokens: 0, cache_read_input_tokens: 0, output_tokens: 12, output_tokens_details: { thinking_tokens: 0 }, ...searched }, provider_metadata: metadata });
264
+ ev('message_stop', { type: 'message_stop' });
265
+ res.end();
266
+ }
267
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
268
+ const port = server.address().port;
269
+ return {
270
+ url: `http://127.0.0.1:${port}`,
271
+ requests,
272
+ messages: () => requests.filter((r) => r.method === 'POST' && r.path === '/v1/messages'),
273
+ close: () => new Promise((resolve) => {
274
+ for (const s of sockets)
275
+ s.destroy();
276
+ server.close(() => resolve());
277
+ }),
278
+ };
279
+ }
@@ -0,0 +1,60 @@
1
+ import type { ClaudeAgentSdk } from '../harness.js';
2
+ export interface FakeSdkOptions {
3
+ mirrorLagMs?: number;
4
+ /** A built-in started (`Bash`: the pid of its command's shell, the leader of its own group). */
5
+ onBuiltin?: (call: {
6
+ id: string;
7
+ name: string;
8
+ pid?: number;
9
+ }) => void;
10
+ /** How long a tool call's handler is given before the fake carries on (never: it waits). */
11
+ onQuery?: (options: Record<string, any>) => void;
12
+ /** Called with each user message the fake consumes. */
13
+ onMessage?: (message: {
14
+ uuid: string;
15
+ text: string;
16
+ priority?: string;
17
+ }) => void;
18
+ /**
19
+ * Called once per `query()` with the system prompt it sends, by the CLI's snapshot rule (`sentSystemPrompt`).
20
+ */
21
+ onSystem?: (system: {
22
+ sessionId: string;
23
+ resumed: boolean;
24
+ snapshot: boolean;
25
+ sent: string;
26
+ }) => void;
27
+ /** Stream what it says from the model behind `ANTHROPIC_BASE_URL` (see above). */
28
+ remoteModel?: boolean;
29
+ /**
30
+ * Commands, one per user message the fake consumes, in place of the message's text: a runner sends its own prompts
31
+ * (the node's, then a nudge), so a test scripts what the "model" does instead. Past the end, the message's text.
32
+ */
33
+ script?: readonly string[];
34
+ /** Each `PreToolUse` decision a built-in got (with the input the hook rewrote, if it did). */
35
+ onDecision?: (call: {
36
+ id: string;
37
+ name: string;
38
+ decision: string;
39
+ updatedInput?: Record<string, unknown>;
40
+ reason?: string;
41
+ }) => void;
42
+ }
43
+ export interface FakeSdk extends ClaudeAgentSdk {
44
+ queries: Record<string, any>[];
45
+ /** Each query's `tools/list` answer from the session's MCP server, as the CLI would read it. */
46
+ listed: {
47
+ name: string;
48
+ description?: string;
49
+ inputSchema: unknown;
50
+ }[][];
51
+ }
52
+ /**
53
+ * The system prompt a launch sends, by the CLI's snapshot rule (measured on the real CLI, Agent SDK 0.3.286, in five
54
+ * cases: a later launch's own append dropped under a record; sent fresh with `snapshot: false`; a first or resumed
55
+ * launch with snapshot on recording its prompt when the session has none; a `false` launch recording nothing): with
56
+ * snapshot on (or omitted), the session's record, made from this launch's prompt if there is none yet; with it off,
57
+ * this launch's own prompt, recorded nowhere.
58
+ */
59
+ export declare function sentSystemPrompt(records: Map<string, string>, session: string, text: string, snapshot: boolean): string;
60
+ export declare function fakeSdk(fake?: FakeSdkOptions): FakeSdk;