@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
@@ -0,0 +1,402 @@
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-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
4
+ import { randomUUID } from 'node:crypto';
5
+ import { join } from 'node:path';
6
+ /**
7
+ * The fake "CLI" child in built-ins or remote-model mode. Each
8
+ * `{ id, command, cwd }` line from stdin it runs as Claude Code runs a Bash
9
+ * command, a `bash -c` in a process group of its own (detached) with this
10
+ * process's environment, and reports `{ id, started }` and
11
+ * `{ id, code, stdout, stderr }`. Each `{ id, say: { url, model, text,
12
+ * authorization } }` it sends as the CLI sends a model request (a streamed
13
+ * Messages API POST from this process), reporting `{ id, delta }` per text
14
+ * delta and then `{ id, end: true }` or `{ id, error }`. Exits when its stdin
15
+ * closes (the SDK closing the CLI), leaving any command running.
16
+ */
17
+ const RUNNER = `
18
+ const { spawn } = require('node:child_process');
19
+ const rl = require('node:readline').createInterface({ input: process.stdin });
20
+ const out = (r) => process.stdout.write(JSON.stringify(r) + '\\n');
21
+ async function say(id, { url, model, text, authorization }) {
22
+ try {
23
+ const res = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', 'anthropic-version': '2023-06-01', authorization }, body: JSON.stringify({ model, max_tokens: 1024, stream: true, messages: [{ role: 'user', content: text }] }) });
24
+ if (!res.ok || !res.body) throw new Error('the model answered ' + res.status);
25
+ const decoder = new TextDecoder();
26
+ let buffer = '';
27
+ for await (const chunk of res.body) {
28
+ buffer += decoder.decode(chunk, { stream: true });
29
+ for (let at = buffer.indexOf('\\n\\n'); at >= 0; at = buffer.indexOf('\\n\\n')) {
30
+ const event = buffer.slice(0, at);
31
+ buffer = buffer.slice(at + 2);
32
+ const data = event.split('\\n').find((l) => l.startsWith('data: '));
33
+ if (!data) continue;
34
+ const ev = JSON.parse(data.slice(6));
35
+ if (ev.type === 'content_block_delta' && ev.delta && ev.delta.type === 'text_delta') out({ id, delta: ev.delta.text || '' });
36
+ if (ev.type === 'message_stop') return out({ id, end: true });
37
+ }
38
+ }
39
+ out({ id, end: true });
40
+ } catch (err) {
41
+ out({ id, error: String((err && err.message) || err) });
42
+ }
43
+ }
44
+ rl.on('line', (line) => {
45
+ const { id, command, cwd, say: request } = JSON.parse(line);
46
+ if (request) return void say(id, request);
47
+ const p = spawn('/bin/bash', ['-c', command], { cwd, detached: true, stdio: ['pipe', 'pipe', 'pipe'] });
48
+ let stdout = '', stderr = '';
49
+ p.stdout.on('data', (d) => (stdout += d));
50
+ p.stderr.on('data', (d) => (stderr += d));
51
+ process.stdout.write(JSON.stringify({ id, started: p.pid }) + '\\n');
52
+ p.on('exit', (code) => process.stdout.write(JSON.stringify({ id, code: code ?? 1, stdout, stderr }) + '\\n'));
53
+ });
54
+ rl.on('close', () => process.exit(0));
55
+ `;
56
+ /** The fake "CLI" with built-ins off: it lives until its stdin closes (the SDK closing the CLI). */
57
+ const IDLE = `process.stdin.on('data', () => {}).on('end', () => process.exit(0))`;
58
+ /** 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. */
59
+ async function sessionTools(instance, listed) {
60
+ if (!instance?.server)
61
+ return new Map((instance?.tools ?? []).map((t) => [t.name, t]));
62
+ const [{ Client }, { InMemoryTransport }] = await Promise.all([import('@modelcontextprotocol/sdk/client/index.js'), import('@modelcontextprotocol/sdk/inMemory.js')]);
63
+ const [client, server] = InMemoryTransport.createLinkedPair();
64
+ await instance.connect(server);
65
+ const mcp = new Client({ name: 'fake-cli', version: '1.0.0' });
66
+ await mcp.connect(client);
67
+ const { tools } = await mcp.listTools();
68
+ listed.push(tools);
69
+ return new Map(tools.map((t) => [t.name, { name: t.name, handler: async (args, extra) => (await mcp.callTool({ name: t.name, arguments: args, _meta: extra?._meta })) }]));
70
+ }
71
+ /**
72
+ * Each session's recorded system prompt. The CLI keeps it with the session, which it keys by project (its cwd) and
73
+ * session id, so it outlives one fake's process; keyed the same way here, two tests share a record only if they share
74
+ * a cwd and a session.
75
+ */
76
+ const recordedPrompts = new Map();
77
+ /**
78
+ * The system prompt a launch sends, by the CLI's snapshot rule (measured on the real CLI, Agent SDK 0.3.286, in five
79
+ * cases: a later launch's own append dropped under a record; sent fresh with `snapshot: false`; a first or resumed
80
+ * launch with snapshot on recording its prompt when the session has none; a `false` launch recording nothing): with
81
+ * snapshot on (or omitted), the session's record, made from this launch's prompt if there is none yet; with it off,
82
+ * this launch's own prompt, recorded nowhere.
83
+ */
84
+ export function sentSystemPrompt(records, session, text, snapshot) {
85
+ if (!snapshot)
86
+ return text;
87
+ if (!records.has(session))
88
+ records.set(session, text);
89
+ return records.get(session);
90
+ }
91
+ /** The text of a `systemPrompt` option: a preset's name, a custom prompt, then the append. */
92
+ function systemText(prompt) {
93
+ if (typeof prompt === 'string')
94
+ return prompt;
95
+ if (!prompt || typeof prompt !== 'object')
96
+ return '';
97
+ const p = prompt;
98
+ const custom = p.prompt === undefined ? [] : Array.isArray(p.prompt) ? p.prompt : [p.prompt];
99
+ return [p.type === 'preset' ? `<preset ${p.preset}>` : '', ...custom, p.append ?? ''].filter(Boolean).join('\n\n');
100
+ }
101
+ export function fakeSdk(fake = {}) {
102
+ const lag = fake.mirrorLagMs ?? 100;
103
+ let scripted = 0;
104
+ const queries = [];
105
+ const listed = [];
106
+ const sdk = {
107
+ queries,
108
+ listed,
109
+ query({ prompt, options }) {
110
+ queries.push(options);
111
+ fake.onQuery?.(options);
112
+ const store = options.sessionStore;
113
+ const sessionId = options.resume ?? options.sessionId;
114
+ {
115
+ const text = systemText(options.systemPrompt);
116
+ const snapshot = options.systemPrompt?.snapshot !== false;
117
+ const sent = sentSystemPrompt(recordedPrompts, `${options.cwd}\0${sessionId}`, text, snapshot);
118
+ fake.onSystem?.({ sessionId, resumed: !!options.resume, snapshot, sent });
119
+ }
120
+ const key = { projectKey: `-fake${options.cwd.replace(/[^A-Za-z0-9]/g, '-')}`, sessionId };
121
+ const tools = sessionTools(options.mcpServers?.hands?.instance, listed);
122
+ tools.catch(() => { });
123
+ const signal = options.abortController?.signal;
124
+ let calls = 0;
125
+ let parent;
126
+ const uuid = () => randomUUID();
127
+ const entry = (type, body) => {
128
+ const e = { type, uuid: uuid(), parentUuid: parent ?? null, sessionId, message: undefined, ...body };
129
+ parent = e.uuid;
130
+ return e;
131
+ };
132
+ const mirror = (entries, delay = 0) => {
133
+ const go = () => store.append(key, entries);
134
+ return delay ? new Promise((r) => setTimeout(() => void go().then(r), delay)) : go();
135
+ };
136
+ const hooksOn = !!options.hooks;
137
+ const runner = hooksOn || !!fake.remoteModel;
138
+ // The "CLI" is `pathToClaudeCodeExecutable` (the tests give node there): the runner, or a child that only waits for stdin to close.
139
+ const child = options.spawnClaudeCodeProcess?.({
140
+ command: options.pathToClaudeCodeExecutable ?? process.execPath,
141
+ args: runner ? ['-e', RUNNER] : ['-e', IDLE],
142
+ env: options.env,
143
+ signal: signal ?? new AbortController().signal,
144
+ });
145
+ // The runner's reports: a command's `{ id, started }`, then `{ id, code, stdout, stderr }`; a model request's `{ id, delta }`s, then `{ id, end }` or `{ id, error }`.
146
+ const reports = new Map();
147
+ const started = new Map();
148
+ const said = new Map();
149
+ if (runner && child) {
150
+ let buf = '';
151
+ child.stdout.on('data', (d) => {
152
+ buf += d.toString();
153
+ for (let i = buf.indexOf('\n'); i >= 0; i = buf.indexOf('\n')) {
154
+ const line = buf.slice(0, i);
155
+ buf = buf.slice(i + 1);
156
+ try {
157
+ const r = JSON.parse(line);
158
+ if (r.started)
159
+ started.get(r.id)?.(r.started);
160
+ else if (typeof r.delta === 'string')
161
+ said.get(r.id)?.delta(r.delta);
162
+ else if (r.end || r.error !== undefined)
163
+ said.get(r.id)?.end(r.error);
164
+ else
165
+ reports.get(r.id)?.(r);
166
+ }
167
+ catch { }
168
+ }
169
+ });
170
+ }
171
+ const runBash = (id, command) => {
172
+ const done = new Promise((r) => reports.set(id, r));
173
+ const pid = new Promise((r) => started.set(id, r));
174
+ child.stdin.write(`${JSON.stringify({ id, command, cwd: options.cwd })}\n`);
175
+ return { done, pid };
176
+ };
177
+ const hook = async (event, input) => {
178
+ for (const m of options.hooks?.[event] ?? [])
179
+ for (const h of m.hooks) {
180
+ const out = await h({ hook_event_name: event, session_id: sessionId, cwd: options.cwd, ...input }, input.tool_use_id, { signal: signal ?? new AbortController().signal });
181
+ if (out?.hookSpecificOutput?.permissionDecision)
182
+ return out.hookSpecificOutput;
183
+ }
184
+ return undefined;
185
+ };
186
+ /** Run a built-in through its hooks. */
187
+ const builtinCall = async (id, name, input, opts = {}) => {
188
+ const decision = await hook('PreToolUse', { tool_name: name, tool_input: input, tool_use_id: id });
189
+ fake.onDecision?.({ id, name, decision: decision?.permissionDecision ?? 'none', ...(decision?.updatedInput ? { updatedInput: decision.updatedInput } : {}), ...(decision?.permissionDecisionReason ? { reason: decision.permissionDecisionReason } : {}) });
190
+ if (decision?.updatedInput)
191
+ input = decision.updatedInput;
192
+ if (decision?.permissionDecision !== 'allow')
193
+ return { text: decision?.permissionDecisionReason ?? `${name} is not allowed`, isError: true };
194
+ let response;
195
+ let failure;
196
+ if (name === 'Bash') {
197
+ const run = runBash(id, String(input.command));
198
+ fake.onBuiltin?.({ id, name, pid: await run.pid });
199
+ if (opts.exitDuring)
200
+ return undefined;
201
+ const r = await run.done;
202
+ if (r.code === 0)
203
+ response = { stdout: r.stdout.trimEnd(), stderr: r.stderr.trimEnd(), interrupted: false, isImage: false };
204
+ else
205
+ failure = `Exit code ${r.code}\n${r.stdout}${r.stderr}`.trimEnd();
206
+ }
207
+ else if (name === 'Write') {
208
+ const { writeFile } = await import('node:fs/promises');
209
+ await writeFile(join(options.cwd, input.file_path), String(input.content));
210
+ response = { type: 'create', filePath: join(options.cwd, input.file_path), content: String(input.content) };
211
+ if (opts.exitDuring)
212
+ return undefined;
213
+ }
214
+ else if (name === 'Read') {
215
+ const { readFile } = await import('node:fs/promises');
216
+ try {
217
+ response = { type: 'text', file: { filePath: join(options.cwd, input.file_path), content: await readFile(join(options.cwd, input.file_path), 'utf8') } };
218
+ }
219
+ catch (err) {
220
+ failure = err.message;
221
+ }
222
+ }
223
+ else
224
+ failure = `No such tool available: ${name}`;
225
+ if (failure !== undefined) {
226
+ await hook('PostToolUseFailure', { tool_name: name, tool_input: input, tool_use_id: id, error: failure });
227
+ return { text: failure, isError: true };
228
+ }
229
+ await hook('PostToolUse', { tool_name: name, tool_input: input, tool_use_id: id, tool_response: response });
230
+ return { text: typeof response === 'object' && response && 'stdout' in response ? String(response.stdout) : JSON.stringify(response), isError: false };
231
+ };
232
+ const inbox = [];
233
+ let wake;
234
+ let ended = false;
235
+ void (async () => {
236
+ for await (const m of prompt) {
237
+ inbox.push(m);
238
+ wake?.();
239
+ }
240
+ ended = true;
241
+ wake?.();
242
+ })();
243
+ const nextMessage = async () => {
244
+ while (!inbox.length && !ended && !signal?.aborted)
245
+ await new Promise((r) => (wake = r));
246
+ return inbox.shift();
247
+ };
248
+ const delta = (text) => ({ type: 'stream_event', parent_tool_use_id: null, event: { type: 'content_block_delta', delta: { type: 'text_delta', text } } });
249
+ /** Say `text`: one delta, or (remote) a model request whose pieces stream in. */
250
+ async function* speak(text) {
251
+ if (!fake.remoteModel) {
252
+ yield delta(text);
253
+ return;
254
+ }
255
+ if (!child)
256
+ throw new Error('fake-sdk: remoteModel needs spawnClaudeCodeProcess: the "CLI" child makes the model request');
257
+ const pieces = [];
258
+ let over;
259
+ let wake;
260
+ const id = uuid();
261
+ said.set(id, {
262
+ delta: (d) => (pieces.push(d), wake?.()),
263
+ end: (error) => ((over = error === undefined ? {} : { error: new Error(error) }), said.delete(id), wake?.()),
264
+ });
265
+ const request = { url: `${options.env.ANTHROPIC_BASE_URL}/v1/messages?beta=true`, model: String(options.model ?? 'claude-sonnet-4-5'), text, authorization: `Bearer ${options.env.ANTHROPIC_AUTH_TOKEN}` };
266
+ child.stdin.write(`${JSON.stringify({ id, say: request })}\n`);
267
+ for (;;) {
268
+ while (pieces.length)
269
+ yield delta(pieces.shift());
270
+ if (over)
271
+ break;
272
+ await new Promise((r) => (wake = r));
273
+ }
274
+ if (over.error)
275
+ throw over.error;
276
+ }
277
+ async function* run() {
278
+ yield { type: 'system', subtype: 'init', tools: [...(await tools).keys()].map((t) => `mcp__hands__${t}`), session_id: sessionId };
279
+ if (options.resume) {
280
+ const loaded = (await store.load(key)) ?? [];
281
+ parent = loaded.at(-1)?.uuid;
282
+ // The CLI's own repair of a dangling call.
283
+ const last = loaded.findLast((e) => e.type === 'assistant');
284
+ 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)) {
286
+ await mirror([
287
+ entry('user', { message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: dangling.id, is_error: true, content: '[Tool call interrupted]' }] } }),
288
+ ]);
289
+ }
290
+ }
291
+ for (;;) {
292
+ const m = await nextMessage();
293
+ if (!m || signal?.aborted)
294
+ return;
295
+ const consumed = [m.uuid];
296
+ const text = typeof m.message.content === 'string' ? m.message.content : '';
297
+ fake.onMessage?.({ uuid: m.uuid, text, ...(m.priority ? { priority: m.priority } : {}) });
298
+ parent = undefined;
299
+ const u = { type: 'user', uuid: m.uuid, parentUuid: null, sessionId, message: { role: 'user', content: text } };
300
+ parent = u.uuid;
301
+ await mirror([{ type: 'queue-operation', operation: 'enqueue' }, u]);
302
+ // 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/, '');
304
+ const builtin = /^(builtin|exit-during-builtin) (\S+) (.*)$/s.exec(command);
305
+ if (builtin) {
306
+ const id = `toolu_${randomUUID().slice(0, 8)}_${++calls}`;
307
+ const name = builtin[2];
308
+ const args = JSON.parse(builtin[3]);
309
+ const a = entry('assistant', { message: { role: 'assistant', content: [{ type: 'tool_use', id, name, input: args }] } });
310
+ yield* speak(`Running ${name}.`);
311
+ yield { type: 'assistant', parent_tool_use_id: null, uuid: a.uuid, session_id: sessionId, message: { content: [{ type: 'text', text: `Running ${name}.` }] } };
312
+ yield { type: 'assistant', parent_tool_use_id: null, uuid: a.uuid, session_id: sessionId, message: a.message };
313
+ const mirrored = mirror([a], lag);
314
+ const result = await builtinCall(id, name, args, { exitDuring: builtin[1] === 'exit-during-builtin' });
315
+ await mirrored;
316
+ // The CLI died mid-call: no result, no reply.
317
+ if (!result || signal?.aborted)
318
+ return;
319
+ const r = entry('user', { message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: id, is_error: result.isError, content: result.text }] } });
320
+ await mirror([r]);
321
+ yield { type: 'user', parent_tool_use_id: null, message: r.message };
322
+ const reply = `${name} returned: ${result.text}`;
323
+ if (fake.remoteModel)
324
+ yield* speak(reply);
325
+ const b = entry('assistant', { message: { role: 'assistant', content: [{ type: 'text', text: reply }] } });
326
+ await mirror([b]);
327
+ yield { type: 'assistant', parent_tool_use_id: null, uuid: b.uuid, session_id: sessionId, message: b.message };
328
+ yield { type: 'result', subtype: 'success', is_error: false, result: 'ok', session_id: sessionId, user_message_uuids: consumed, queued_turn_count: 0 };
329
+ await mirror([{ type: 'last-prompt' }]);
330
+ continue;
331
+ }
332
+ // The SDK dropped a mirror batch (its session store refused it three times): it says so, and the CLI carries on.
333
+ if (command === 'mirror-error')
334
+ yield { type: 'system', subtype: 'mirror_error', error: 'the session store refused the batch', key: { projectKey: 'session', sessionId }, uuid: randomUUID(), session_id: sessionId };
335
+ const dying = /^exit-during (\S+) (.*)$/s.exec(command);
336
+ if (dying) {
337
+ const id = `toolu_${randomUUID().slice(0, 8)}_${++calls}`;
338
+ await mirror([entry('assistant', { message: { role: 'assistant', content: [{ type: 'tool_use', id, name: `mcp__hands__${dying[1]}`, input: JSON.parse(dying[2]) }] } })]);
339
+ yield { type: 'assistant', parent_tool_use_id: null, session_id: sessionId, message: { content: [{ type: 'tool_use', id, name: `mcp__hands__${dying[1]}` }] } };
340
+ void tools.then((t) => t.get(dying[1])?.handler(JSON.parse(dying[2]), { _meta: { 'claudecode/toolUseId': id } }));
341
+ return;
342
+ }
343
+ const call = /^call (\S+) (.*)$/s.exec(command);
344
+ if (call) {
345
+ const id = `toolu_${randomUUID().slice(0, 8)}_${++calls}`;
346
+ const name = call[1];
347
+ const args = JSON.parse(call[2]);
348
+ const a = entry('assistant', { message: { role: 'assistant', content: [{ type: 'tool_use', id, name: `mcp__hands__${name}`, input: args }] } });
349
+ yield* speak(`Calling ${name}.`);
350
+ yield { type: 'assistant', parent_tool_use_id: null, uuid: a.uuid, session_id: sessionId, message: { content: [{ type: 'text', text: `Calling ${name}.` }] } };
351
+ yield { type: 'assistant', parent_tool_use_id: null, uuid: a.uuid, session_id: sessionId, message: a.message };
352
+ const mirrored = mirror([a], lag);
353
+ const tool = (await tools).get(name);
354
+ const result = tool ? await tool.handler(args, { _meta: { 'claudecode/toolUseId': id } }) : { content: [{ type: 'text', text: `no tool ${name}` }], isError: true };
355
+ await mirrored;
356
+ if (signal?.aborted)
357
+ return;
358
+ const r = entry('user', { message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: id, is_error: !!result.isError, content: result.content[0]?.text }] } });
359
+ await mirror([r]);
360
+ yield { type: 'user', parent_tool_use_id: null, message: r.message };
361
+ // A steer sent while the call ran is folded into this turn.
362
+ for (let i = inbox.findIndex((x) => x.priority === 'next'); i >= 0; i = inbox.findIndex((x) => x.priority === 'next')) {
363
+ const s = inbox.splice(i, 1)[0];
364
+ consumed.push(s.uuid);
365
+ fake.onMessage?.({ uuid: s.uuid, text: s.message.content, priority: s.priority });
366
+ // As the CLI does: a message taken in mid-turn is a queued_command attachment naming it, not a user entry.
367
+ await mirror([
368
+ { type: 'queue-operation', operation: 'remove', content: s.message.content },
369
+ entry('attachment', { attachment: { type: 'queued_command', prompt: s.message.content, source_uuid: s.uuid } }),
370
+ ]);
371
+ }
372
+ const reply = `${name} returned: ${result.content[0]?.text}${consumed.length > 1 ? ' (and I read your steer)' : ''}`;
373
+ if (fake.remoteModel)
374
+ yield* speak(reply);
375
+ const b = entry('assistant', { message: { role: 'assistant', content: [{ type: 'text', text: reply }] } });
376
+ await mirror([b]);
377
+ yield { type: 'assistant', parent_tool_use_id: null, uuid: b.uuid, session_id: sessionId, message: b.message };
378
+ }
379
+ else {
380
+ const reply = text.startsWith('[Recovery]') ? 'Recovered from the log.' : `echo: ${text}`;
381
+ yield* speak(reply);
382
+ const b = entry('assistant', { message: { role: 'assistant', content: [{ type: 'text', text: reply }] } });
383
+ await mirror([b]);
384
+ yield { type: 'assistant', parent_tool_use_id: null, uuid: b.uuid, session_id: sessionId, message: b.message };
385
+ }
386
+ yield { type: 'result', subtype: 'success', is_error: false, result: 'ok', session_id: sessionId, user_message_uuids: consumed, queued_turn_count: 0 };
387
+ await mirror([{ type: 'last-prompt' }]);
388
+ }
389
+ }
390
+ const gen = (async function* () {
391
+ try {
392
+ yield* run();
393
+ }
394
+ finally {
395
+ child?.stdin.end();
396
+ }
397
+ })();
398
+ return Object.assign(gen, { close: () => void gen.return(undefined) });
399
+ },
400
+ };
401
+ return sdk;
402
+ }
@@ -0,0 +1,3 @@
1
+ export { fakeSdk, sentSystemPrompt } from "./fake-sdk.js";
2
+ export type { FakeSdk, FakeSdkOptions } from "./fake-sdk.js";
3
+ export * from "./fake-anthropic.js";
@@ -0,0 +1,5 @@
1
+ // Test kit for the Claude Agent adapter, copied from another project (each file's header says from where): a scripted
2
+ // Agent SDK that needs no CLI, key or network, and a scripted Anthropic Messages API for the real CLI behind the
3
+ // session's model proxy.
4
+ export { fakeSdk, sentSystemPrompt } from "./fake-sdk.js";
5
+ export * from "./fake-anthropic.js";
@@ -0,0 +1,73 @@
1
+ import type { TranscriptEntry } from './host/process.js';
2
+ /**
3
+ * The normalized transcript (harness-world-process's `transcript` stream) and
4
+ * the live events, from the Agent SDK's messages.
5
+ *
6
+ * `query()` yields one `assistant` message per completed content block
7
+ * (thinking, text, tool_use), `stream_event` deltas while a block streams
8
+ * (with `includePartialMessages`), and one `result` per turn. This keeps the
9
+ * text said since the last tool call, writes it with the call that follows it
10
+ * (`{ role: 'assistant', text, toolCalls }`), and writes the rest and a `turn`
11
+ * entry at the result. Text deltas go to the live stream. Subagent messages
12
+ * (`parent_tool_use_id` set) are left out.
13
+ *
14
+ * Pure: the drive hands it SDK messages and gets entries back through `sink`,
15
+ * so it is tested on recorded messages.
16
+ */
17
+ export interface TranscriptSink {
18
+ message(entry: TranscriptEntry): void;
19
+ live(event: unknown): void;
20
+ }
21
+ /** The MCP server name the workspace tools are served under: the model sees `mcp__hands__<tool>`. */
22
+ export declare const MCP_SERVER = "hands";
23
+ /** A tool's name without the MCP prefix. */
24
+ export declare const bareToolName: (name: string) => string;
25
+ /** How a turn ended, from its `result` message. */
26
+ export interface TurnEnd {
27
+ status: 'completed' | 'failed';
28
+ error?: string;
29
+ /** More turns follow without new input (`queued_turn_count`). */
30
+ queued: number;
31
+ /**
32
+ * The `uuid`s of the user messages this turn consumed (`user_message_uuids`),
33
+ * or `undefined` from a CLI that does not report them.
34
+ */
35
+ consumed?: string[];
36
+ sessionId?: string;
37
+ }
38
+ type SdkMessage = {
39
+ type: string;
40
+ subtype?: string;
41
+ parent_tool_use_id?: string | null;
42
+ [k: string]: unknown;
43
+ };
44
+ export declare class TranscriptBuilder {
45
+ private readonly sink;
46
+ private said;
47
+ private readonly written;
48
+ private readonly waiters;
49
+ /** Each call the model made, by its id: its name as the model gave it and its input. */
50
+ private readonly asked;
51
+ /** Calls that reached the session's tool server (`beforeCall`): their error, whatever its text, is theirs, not a refusal. */
52
+ private readonly bridged;
53
+ constructor(sink: TranscriptSink);
54
+ /** One message from `query()`. Returns how the turn ended for a `result`. */
55
+ observe(m: SdkMessage): TurnEnd | undefined;
56
+ /**
57
+ * Write the turn's last text and its end. Called at each `result`, or with
58
+ * `interrupted` when the drive stops a turn it cannot finish.
59
+ */
60
+ endTurn(end: Pick<TurnEnd, 'status' | 'error'> | {
61
+ status: 'interrupted';
62
+ error?: string;
63
+ }): void;
64
+ /**
65
+ * A tool call is about to run (its MCP handler was called). The message
66
+ * that made it is written first: by `observe`, which normally sees the
67
+ * `tool_use` block a moment before the handler runs (the CLI writes the
68
+ * block before it calls the tool); after `waitMs`, by this.
69
+ */
70
+ beforeCall(id: string, name: string, waitMs?: number): Promise<void>;
71
+ private call;
72
+ }
73
+ export {};
@@ -0,0 +1,116 @@
1
+ /** The MCP server name the workspace tools are served under: the model sees `mcp__hands__<tool>`. */
2
+ export const MCP_SERVER = 'hands';
3
+ const MCP_PREFIX = `mcp__${MCP_SERVER}__`;
4
+ /** A tool's name without the MCP prefix. */
5
+ export const bareToolName = (name) => (name.startsWith(MCP_PREFIX) ? name.slice(MCP_PREFIX.length) : name);
6
+ /** The CLI's own refusal of a call, before any hook or tool server sees it (a tool the session doesn't have, say). */
7
+ const CLI_REFUSAL = /<tool_use_error>([\s\S]*?)<\/tool_use_error>/;
8
+ export class TranscriptBuilder {
9
+ sink;
10
+ said = '';
11
+ written = new Set();
12
+ waiters = new Map();
13
+ /** Each call the model made, by its id: its name as the model gave it and its input. */
14
+ asked = new Map();
15
+ /** Calls that reached the session's tool server (`beforeCall`): their error, whatever its text, is theirs, not a refusal. */
16
+ bridged = new Set();
17
+ constructor(sink) {
18
+ this.sink = sink;
19
+ }
20
+ /** One message from `query()`. Returns how the turn ended for a `result`. */
21
+ observe(m) {
22
+ if (m.parent_tool_use_id)
23
+ return undefined;
24
+ if (m.type === 'stream_event') {
25
+ const ev = m.event;
26
+ if (ev?.type === 'content_block_delta' && ev.delta?.type === 'text_delta' && ev.delta.text)
27
+ this.sink.live({ type: 'text', delta: ev.delta.text });
28
+ return undefined;
29
+ }
30
+ if (m.type === 'assistant') {
31
+ const content = m.message?.content;
32
+ for (const block of Array.isArray(content) ? content : []) {
33
+ if (block.type === 'text' && block.text)
34
+ this.said = this.said ? `${this.said}\n\n${block.text}` : block.text;
35
+ else if (block.type === 'tool_use' && block.id) {
36
+ this.asked.set(block.id, { name: bareToolName(block.name ?? 'tool'), input: block.input });
37
+ this.call(block.id, bareToolName(block.name ?? 'tool'));
38
+ }
39
+ }
40
+ return undefined;
41
+ }
42
+ if (m.type === 'user') {
43
+ // A call the CLI refused itself is answered at once with its error: the call never ran, and the host is told.
44
+ const content = m.message?.content;
45
+ for (const block of Array.isArray(content) ? content : []) {
46
+ if (block.type !== 'tool_result' || block.is_error !== true || !block.tool_use_id || this.bridged.has(block.tool_use_id))
47
+ continue;
48
+ const text = typeof block.content === 'string' ? block.content : Array.isArray(block.content) ? block.content.map((c) => c?.text ?? '').join('') : '';
49
+ const refused = CLI_REFUSAL.exec(text);
50
+ if (!refused)
51
+ continue;
52
+ const asked = this.asked.get(block.tool_use_id);
53
+ this.sink.live({ type: 'tool_refused', callId: block.tool_use_id, name: asked?.name ?? 'tool', args: asked?.input ?? {}, reason: refused[1].replace(/^Error:\s*/, '').trim().slice(0, 300) });
54
+ }
55
+ return undefined;
56
+ }
57
+ if (m.type === 'result') {
58
+ const isError = m.is_error === true || m.subtype !== 'success';
59
+ const errors = Array.isArray(m.errors) ? m.errors.map(String) : [];
60
+ const error = isError ? (typeof m.result === 'string' && m.result) || errors.join('; ') || String(m.subtype) : undefined;
61
+ const consumed = Array.isArray(m.user_message_uuids)
62
+ ? m.user_message_uuids.map(String)
63
+ : typeof m.user_message_uuid === 'string'
64
+ ? [m.user_message_uuid]
65
+ : undefined;
66
+ return {
67
+ status: isError ? 'failed' : 'completed',
68
+ ...(error ? { error } : {}),
69
+ queued: typeof m.queued_turn_count === 'number' ? m.queued_turn_count : 0,
70
+ ...(consumed ? { consumed } : {}),
71
+ ...(typeof m.session_id === 'string' ? { sessionId: m.session_id } : {}),
72
+ };
73
+ }
74
+ return undefined;
75
+ }
76
+ /**
77
+ * Write the turn's last text and its end. Called at each `result`, or with
78
+ * `interrupted` when the drive stops a turn it cannot finish.
79
+ */
80
+ endTurn(end) {
81
+ if (this.said)
82
+ this.sink.message({ type: 'message', role: 'assistant', text: this.said });
83
+ this.said = '';
84
+ this.sink.message({ type: 'turn', status: end.status, ...(end.error ? { error: end.error } : {}) });
85
+ }
86
+ /**
87
+ * A tool call is about to run (its MCP handler was called). The message
88
+ * that made it is written first: by `observe`, which normally sees the
89
+ * `tool_use` block a moment before the handler runs (the CLI writes the
90
+ * block before it calls the tool); after `waitMs`, by this.
91
+ */
92
+ async beforeCall(id, name, waitMs = 1000) {
93
+ this.bridged.add(id);
94
+ if (this.written.has(id))
95
+ return;
96
+ await new Promise((resolve) => {
97
+ const timer = setTimeout(done, waitMs);
98
+ this.waiters.set(id, [...(this.waiters.get(id) ?? []), done]);
99
+ function done() {
100
+ clearTimeout(timer);
101
+ resolve();
102
+ }
103
+ });
104
+ this.call(id, name);
105
+ }
106
+ call(id, name) {
107
+ if (this.written.has(id))
108
+ return;
109
+ this.written.add(id);
110
+ this.sink.message({ type: 'message', role: 'assistant', text: this.said, toolCalls: [{ id, name }] });
111
+ this.said = '';
112
+ for (const w of this.waiters.get(id) ?? [])
113
+ w();
114
+ this.waiters.delete(id);
115
+ }
116
+ }
@@ -0,0 +1,34 @@
1
+ import { Unavailable } from './host/kernel.js';
2
+ /**
3
+ * The Agent SDK and Claude Code versions this harness is built and tested
4
+ * with (docs/workspaces.md §5.2). The harness drives CLI internals that move
5
+ * between releases: the transcript the mirror carries, the `system/init`
6
+ * tool set `builtins: true` is pinned against, the spawn arguments and env
7
+ * `sandboxSpawn` checks. So the installed SDK must be the pinned one (pnpm
8
+ * only warns on a peer mismatch), and the CLI in the VM image is the one
9
+ * that SDK release bundles (`claudeCodeVersion`). A test keeps these equal
10
+ * to package.json's, the installed SDK's and harness-world-sandbox's base.
11
+ */
12
+ export declare const CLAUDE_AGENT_SDK_VERSION = "0.3.286";
13
+ /** The Claude Code CLI the pinned SDK release bundles (its package.json's `claudeCodeVersion`), installed in the VM image. */
14
+ export declare const CLAUDE_CODE_VERSION = "2.1.286";
15
+ /** Where the pinned CLI is in a session VM booted from the base (harness-world-sandbox's `CLAUDE_CLI`). */
16
+ export declare const CLAUDE_VM_EXECUTABLE = "/opt/dh/claude/2.1.286/claude";
17
+ /** The install line for the pinned SDK. */
18
+ export declare const CLAUDE_AGENT_SDK_INSTALL = "npm install --save-exact @anthropic-ai/claude-agent-sdk@0.3.286";
19
+ /**
20
+ * The version of `name` an import from here finds: Node's lookup for a
21
+ * package's folder (`node_modules/<name>` in this module's directory or the
22
+ * nearest one above it). Undefined when it isn't there (the import says what
23
+ * is missing) or this module isn't a file.
24
+ */
25
+ export declare function installedVersion(name: string, from?: string): string | undefined;
26
+ /**
27
+ * The installed Agent SDK, when it isn't the pinned one, as an `Unavailable`
28
+ * naming both versions and the install line (the turn fails with it; the
29
+ * session stays, and a fixed install drives it again), or undefined when it
30
+ * matches or can't be found (the import then says what is missing).
31
+ */
32
+ export declare function checkAgentSdkVersion(versionOf?: (name: string) => string | undefined): Unavailable | undefined;
33
+ /** `checkAgentSdkVersion()`, once per process: throws its `Unavailable`. */
34
+ export declare function assertAgentSdkVersion(): void;