@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,887 @@
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/harness.ts at ea8aa4060c (UPSTREAM.json records its blob and sha256).
3
+ // Changed by Parcha, imports rewritten for AgentRun; patches: 001-gate-always-on, 002-names, 003-comments, 008-tool-description-max, 009-tool-result-barrier-and-refusals, 010-served-tools-with-images, 011-session-skills, 013-recovery-note-system-prompt, 015-web-search, 016-mcp-output-tokens, 017-key-refused, 019-recovery-covers
4
+ import { AsyncLocalStorage } from 'node:async_hooks';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { mkdtemp, rm } from 'node:fs/promises';
7
+ import { tmpdir } from 'node:os';
8
+ import { dirname, join, posix } from 'node:path';
9
+ import { Restart, Unavailable } from './host/kernel.js';
10
+ import { BuiltinCalls, CLAUDE_ROUTES, gatewayCredential, gatewayHandler, gatewayUrl, isBrandedMachine, journalLedger, ModelSteps, NativeJournal, openTurn, placeSubmissions, recoveryNote, restartEvent, replayBy, settleAbandonedModelSteps, toolBridge, waitForSubmissions, } from './host/process.js';
11
+ import { durableEnv, nativeModelId } from './env.js';
12
+ import { uuidFrom } from './ids.js';
13
+ import { MessageQueue } from './inbox.js';
14
+ import { sandboxSpawn } from './spawn.js';
15
+ import { MCP_OUTPUT_TOKENS, toolServer } from './host/tool-server.js';
16
+ import { JournalSessionStore } from './store.js';
17
+ import { MCP_SERVER, TranscriptBuilder } from './transcript.js';
18
+ import { CLAUDE_AGENT_CLI_SKILL_NAMES } from './cli-names.js';
19
+ import { assertAgentSdkVersion, CLAUDE_VM_EXECUTABLE } from './versions.js';
20
+ /** The default model. */
21
+ export const DEFAULT_MODEL = 'claude-sonnet-4-5';
22
+ /** What the harness appends to the system prompt about the tools, before `instructions`, with the built-ins off and the app's tools there. */
23
+ export const TOOLS_NOTE = `Your only tools are this app's, the mcp__${MCP_SERVER}__ tools; you have no shell, file, search or web tools of your own.`;
24
+ /** `TOOLS_NOTE` with WebSearch on (`providerTools: ['web_search']`) and the other built-ins off. */
25
+ export const WEB_SEARCH_NOTE = `Your only tools are this app's (the mcp__${MCP_SERVER}__ tools, if it has any) and WebSearch; you have no shell, file or fetch tools of your own.`;
26
+ /** `TOOLS_NOTE` for a session with no tools at all (built-ins off, no `tools`). */
27
+ export const NO_TOOLS_NOTE = 'You have no tools in this session: no shell, file, search or web tools. Answer from the conversation.';
28
+ /** With the built-ins on (docs/workspaces.md §5.6 "Workspace note"): what `/workspace` is. */
29
+ export const DRIVE_NOTE = 'Your working directory, /workspace, is this session\'s own disk: files there are durable (they stay for later turns, on any machine) but not transactional: a command that a crash interrupted may have half-run, so check before you repeat one. Commands end with this turn: nothing keeps running in the background.';
30
+ /**
31
+ * Built-ins that stay off whatever `builtins` says: their state lives in the
32
+ * CLI process or its local files, which the transcript the log carries does
33
+ * not hold (cron jobs, scheduled wakeups, worktrees, agent teams and their
34
+ * messages, background shells, workflows, the task list, P0.17: 2.1.296
35
+ * keeps it in the config dir), or they wait for a user who is not there
36
+ * (questions, plan mode).
37
+ */
38
+ export const CLAUDE_BUILTINS_OFF = [
39
+ 'CronCreate',
40
+ 'CronDelete',
41
+ 'CronList',
42
+ 'ScheduleWakeup',
43
+ 'EnterWorktree',
44
+ 'ExitWorktree',
45
+ 'ListAgents',
46
+ 'SendMessage',
47
+ 'TaskCreate',
48
+ 'TaskGet',
49
+ 'TaskList',
50
+ 'TaskUpdate',
51
+ 'TaskStop',
52
+ 'TodoWrite',
53
+ 'Workflow',
54
+ 'ReportFindings',
55
+ 'Monitor',
56
+ 'BashOutput',
57
+ 'KillShell',
58
+ 'AskUserQuestion',
59
+ 'EnterPlanMode',
60
+ 'ExitPlanMode',
61
+ // Subagents (the `claude_code` preset): their sidechains' resume across VMs is not proven yet (§11.4 R7).
62
+ 'Task',
63
+ 'Agent',
64
+ ];
65
+ /**
66
+ * `builtins: true`: the pinned allowlist, the tools Claude Code 2.1.296 has
67
+ * (its `system/init` list, checked by a test) that act on `/workspace` and
68
+ * whose state is in the transcript. The design's Glob, Grep and TodoWrite are
69
+ * not tools of this CLI (it searches through Bash, and its task list is off,
70
+ * P0.17); WebSearch is provider-hosted (`providerTools`).
71
+ */
72
+ export const CLAUDE_BUILTINS = ['Bash', 'Read', 'Edit', 'Write', 'NotebookEdit', 'WebFetch'];
73
+ /** Built-ins that only read: "safe to repeat" after a crash, and no flush before their outcome. Everything else: "may have taken effect". */
74
+ export const CLAUDE_SAFE_BUILTINS = ['Read', 'Glob', 'Grep', 'LS', 'NotebookRead', 'WebFetch', 'WebSearch', 'ToolSearch', 'Skill'];
75
+ /** The default `builtinReplay`. */
76
+ export const claudeBuiltinReplay = replayBy(CLAUDE_SAFE_BUILTINS);
77
+ /** What a Bash command keeps of the invocation for its outcome to be recorded and the drive to end (the kernel's end-of-drive margin is 15 s). */
78
+ const BASH_MARGIN_MS = 20_000;
79
+ /** The shortest clamped Bash timeout worth running: past it, the call is refused before it runs. */
80
+ const BASH_MIN_MS = 1_000;
81
+ /** The invocation assumed when the kernel gives no deadline (a hand-written context): a serverless function's default maximum duration, the shortest likely one. */
82
+ const ASSUMED_INVOCATION_MS = 300_000;
83
+ /** How often one delivery rebuilds a drive whose CLI exited mid-turn (the kernel fails the session at 8). */
84
+ const CLI_RESTARTS = 3;
85
+ /** What a rebuilt drive needs of the invocation to be worth starting: else the delivery fails, and the queue redelivers. */
86
+ const RESTART_MIN_LEFT_MS = 60_000;
87
+ /** Where the built-in file tools may not write (they run in the CLI, outside Claude's sandbox): the repo's and Claude's config on the Drive. */
88
+ const PROTECTED_DIRS = ['.git', '.claude'];
89
+ /** The file tools' path inputs. */
90
+ const FILE_TOOLS = { Write: 'file_path', Edit: 'file_path', MultiEdit: 'file_path', NotebookEdit: 'notebook_path' };
91
+ /** What the model hears beside a call whose writes the Drive didn't confirm. */
92
+ const NOT_FLUSHED_NOTE = "The session's disk didn't confirm this call's writes: they may not have reached it. Check the files before relying on them.";
93
+ /** The `builtins` option, resolved: the `tools` option for `query()` (undefined: the preset, all of them). */
94
+ export function builtinTools(builtins) {
95
+ if (builtins === undefined || builtins === false)
96
+ return [];
97
+ if (builtins === true)
98
+ return [...CLAUDE_BUILTINS];
99
+ if (Array.isArray(builtins)) {
100
+ if (!builtins.every((b) => typeof b === 'string' && /^[A-Za-z][A-Za-z0-9_]*$/.test(b)))
101
+ throw new TypeError('agentrun-harness-claude: builtins takes tool names (Bash, Read, ...)');
102
+ return [...builtins];
103
+ }
104
+ const preset = builtins;
105
+ if (preset.type === 'preset' && preset.preset === 'claude_code')
106
+ return undefined;
107
+ throw new TypeError("agentrun-harness-claude: builtins takes true, a list of tool names, or { type: 'preset', preset: 'claude_code' }");
108
+ }
109
+ /** The Claude Code sandbox settings for the VM (§5.5 "Claude Code runs under its own sandbox"; P0.10, P0.16). */
110
+ export function claudeSandboxSettings(machine, network) {
111
+ const { dirs } = machine;
112
+ const open = [dirs.tmp, dirs.home, dirs.cache];
113
+ return {
114
+ enabled: true,
115
+ failIfUnavailable: true,
116
+ allowUnsandboxedCommands: false,
117
+ filesystem: { allowWrite: [machine.root, ...open], denyRead: [dirname(dirs.config)], allowRead: open },
118
+ credentials: { envVars: [{ name: 'ANTHROPIC_AUTH_TOKEN', mode: 'deny' }] },
119
+ network: {
120
+ ...(network === 'allow-all' ? { allowedDomains: ['*'] } : network === 'deny-all' ? { allowedDomains: [], strictAllowlist: true } : { allowedDomains: [...network.allow], strictAllowlist: true }),
121
+ // The model port is the CLI's alone: never through the sandbox's proxy (the loopback names and literals it takes;
122
+ // a public name that resolves to loopback still gets past, and then meets the port's key).
123
+ deniedDomains: [...LOOPBACK_NAMES],
124
+ },
125
+ };
126
+ }
127
+ /** Loopback, as names and literals a command could hand the sandbox's proxy for the model port. */
128
+ export const LOOPBACK_NAMES = ['localhost', 'localhost.', '127.0.0.1', '127.1', '0.0.0.0', '0', '2130706433', '::1', '[::1]', '::ffff:127.0.0.1', '[::ffff:127.0.0.1]', '::', '[::]'];
129
+ /** The bwrap self-test (P0.10): what Claude Code's sandbox needs of the VM, as the unprivileged user. */
130
+ const BWRAP_SELF_TEST = ['--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc', '--unshare-pid', '--unshare-net', '--die-with-parent', 'true'];
131
+ /** Whether bubblewrap works in the VM as the agent (a fresh `/proc` in a pid namespace, no network): Claude Code's sandbox can start. */
132
+ async function bwrapWorks(machine, signal) {
133
+ try {
134
+ const proc = await machine.spawn({ command: 'bwrap', args: BWRAP_SELF_TEST, signal });
135
+ const timer = setTimeout(() => proc.kill('SIGKILL'), 10_000);
136
+ const exit = await proc.exited;
137
+ clearTimeout(timer);
138
+ return exit.code === 0;
139
+ }
140
+ catch {
141
+ return false;
142
+ }
143
+ }
144
+ export function claudeCodeHarness(options = {}) {
145
+ const tools = options.tools ?? [];
146
+ const allowed = builtinTools(options.builtins);
147
+ const builtinsOn = allowed === undefined || allowed.length > 0;
148
+ const skills = options.skills?.names.length ? options.skills : undefined;
149
+ const model = nativeModelId(options.model ?? DEFAULT_MODEL);
150
+ const smallModel = options.smallModel ? nativeModelId(options.smallModel) : undefined;
151
+ const barrierMs = options.barrierMs ?? 10_000;
152
+ const executable = options.executable ?? CLAUDE_VM_EXECUTABLE;
153
+ const replay = typeof options.builtinReplay === 'function' ? options.builtinReplay : options.builtinReplay ? (name) => options.builtinReplay[name] ?? claudeBuiltinReplay(name) : claudeBuiltinReplay;
154
+ const providerTools = options.providerTools ?? [];
155
+ const webSearch = providerTools.includes('web_search');
156
+ const log = options.log ?? (() => { });
157
+ let sdk;
158
+ const loadSdk = () => {
159
+ if (!sdk) {
160
+ // The installed SDK must be the pinned one (pnpm only warns on a peer mismatch); a failed load is tried again on the next drive.
161
+ const loading = options.sdk
162
+ ? Promise.resolve(options.sdk)
163
+ : Promise.resolve().then(() => {
164
+ assertAgentSdkVersion();
165
+ return import('@anthropic-ai/claude-agent-sdk');
166
+ });
167
+ sdk = loading;
168
+ loading.catch(() => (sdk = undefined));
169
+ }
170
+ return sdk;
171
+ };
172
+ return {
173
+ name: options.name ?? 'claude-agent',
174
+ // Each model request reaches the provider through the session's proxy (`ModelSteps.request`).
175
+ modelCalls: 'self',
176
+ async drive(ctx) {
177
+ // Nothing to do (an idle wake, a chaos arming): no VM. A model step a
178
+ // crash left open after its turn ended is closed (no request will retry it).
179
+ if (!recoveryNote(ctx.state()) && ctx.pending().length === 0) {
180
+ await settleAbandonedModelSteps(ctx);
181
+ return;
182
+ }
183
+ const sandbox = options.sandbox;
184
+ if (!sandbox)
185
+ throw sandboxRequired();
186
+ const { query } = await loadSdk();
187
+ const journal = new NativeJournal(ctx);
188
+ const records = await journal.read();
189
+ const store = new JournalSessionStore(journal, { records, coalesceMs: options.coalesceMs ?? 150 });
190
+ // The handler reads the credential per request, in the drive's async
191
+ // context: on a serverless function the OIDC token comes from the request
192
+ // that started the drive.
193
+ const inDrive = AsyncLocalStorage.snapshot();
194
+ const credential = options.credential ?? gatewayCredential;
195
+ // The handler also sees each model request start and end: the drive's
196
+ // model steps, written around a "Crash during: model" drill.
197
+ const steps = new ModelSteps(ctx, options.log ? { log: options.log } : {});
198
+ const ledger = journalLedger(journal, { records });
199
+ if (ctx.deadline === undefined)
200
+ log('claude-agent: the kernel gave no deadline; assuming a 300 s invocation', {});
201
+ const deadline = ctx.deadline ?? Date.now() + ASSUMED_INVOCATION_MS;
202
+ const handler = gatewayHandler({
203
+ routes: CLAUDE_ROUTES,
204
+ models: { model, ...(smallModel ? { smallModel } : {}) },
205
+ budget: sandbox.budget,
206
+ ledger,
207
+ providerTools,
208
+ network: sandbox.network === 'allow-all' || sandbox.network === 'deny-all' ? sandbox.network : 'custom',
209
+ credential: () => inDrive(credential),
210
+ target: options.gatewayUrl ?? gatewayUrl(),
211
+ track: steps.request,
212
+ onCap: (cap) => {
213
+ if (cap !== 'concurrency')
214
+ ctx.halt?.(spendCapped(cap));
215
+ },
216
+ // A refused key fails the turn at the provider's first 401, in the words the CLI would end on after its retries.
217
+ onKeyRefused: (detail) => ctx.halt?.(new Error(`Failed to authenticate. API Error: 401${detail ? ` ${detail}` : ''}`)),
218
+ // Without the app's own log, the handler's default: a refused model call is a warning in the Function's logs, not silence.
219
+ ...(options.log ? { log: (message, fields) => log(`claude-agent gateway: ${message}`, fields) } : {}),
220
+ });
221
+ const abort = new AbortController();
222
+ const stop = () => abort.abort(ctx.signal.reason);
223
+ ctx.signal.addEventListener('abort', stop, { once: true });
224
+ /** What the attach handed back (closed when the drive ends, branded or not), and the Function's side of the CLI's config dir. */
225
+ let held;
226
+ let configDir;
227
+ try {
228
+ const machine = (held = await sandbox.attach(ctx, { model: handler, deadline }));
229
+ if (!isBrandedMachine(machine))
230
+ throw sandboxRequired();
231
+ // The Function's side of the CLI's config dir: empty, 0700, this drive's.
232
+ // The SDK's resume copies nothing from it (no credentials, no settings),
233
+ // and the mirror's paths are mapped to it.
234
+ configDir = await mkdtemp(join(tmpdir(), 'dh-claude-'));
235
+ let proc;
236
+ // What the model must hear once (a lost Drive), in the drive's first message, and what it described (to acknowledge exactly that).
237
+ let notes = machine.notes.length ? machine.notes.join('\n\n') : undefined;
238
+ let noteSent = false;
239
+ // The Drive's manifest: what the Files panel shows, kept in the log so it reads with no VM.
240
+ const driveFiles = sandbox.files?.(ctx, machine);
241
+ // Claude Code's own sandbox (P0.10): bubblewrap must work in the VM. A failed self-test is tried once more (a slow relay, a timeout).
242
+ const ownSandbox = builtinsOn && ((await bwrapWorks(machine, ctx.signal)) || (await bwrapWorks(machine, ctx.signal)));
243
+ if (builtinsOn && !ownSandbox) {
244
+ if (ctx.signal.aborted)
245
+ throw ctx.signal.reason;
246
+ if (!options.unsandboxedCommands)
247
+ throw noCommandSandbox();
248
+ log("claude-agent: bubblewrap doesn't work in this VM: the CLI's commands run without its sandbox (unsandboxedCommands; the VM is the boundary, the model key only a correlation id)");
249
+ }
250
+ /**
251
+ * Tool calls the MCP server is running. The drive never returns with
252
+ * one in flight: if the CLI dies mid-call, the call still runs to its
253
+ * outcome in this process, and that outcome lands before the next
254
+ * delivery reads the log.
255
+ */
256
+ const calls = new Set();
257
+ const input = new MessageQueue();
258
+ /** User messages sent and not yet consumed by a turn (by `uuid`). */
259
+ const outstanding = new Set();
260
+ const transcript = new TranscriptBuilder({
261
+ message: (e) => store.message(e),
262
+ // A refusal is told once its answer is in the log, as a host tool's end is told once its outcome is.
263
+ live: (e) => {
264
+ const refused = e;
265
+ if (refused.type !== 'tool_refused' || typeof refused.callId !== 'string')
266
+ return ctx.live(e);
267
+ void store.resultBarrier(refused.callId, barrierMs).then(() => ctx.live(e), (error) => log('claude-agent: a refused call is not shown: its answer never reached the log', { callId: refused.callId, error: String(error?.message ?? error).slice(0, 200) }));
268
+ },
269
+ });
270
+ const bridge = toolBridge(ctx, tools, {
271
+ // A `never` tool runs only once the assistant entry that asked for it is in the log.
272
+ beforeNever: ({ callId }) => store.barrier(callId, barrierMs),
273
+ });
274
+ // The built-ins: each call an intent before it runs, its outcome after (the hooks below).
275
+ const builtins = new BuiltinCalls(ctx, { replay, beforeNever: ({ callId }) => store.barrier(callId, barrierMs), live: true });
276
+ /** Bash calls whose timeout the invocation clamped: their outcome, if it timed out, says so. */
277
+ const clamped = new Map();
278
+ const bridged = (name) => name.startsWith(`mcp__${MCP_SERVER}__`);
279
+ const byName = new Map(bridge.tools.map((t) => [t.name, t]));
280
+ const server = await toolServer(MCP_SERVER, bridge.tools, async (name, args, callId) => {
281
+ const t = byName.get(name);
282
+ if (typeof callId !== 'string')
283
+ return errorResult(`${t.name} was not run: the call carries no tool_use id`);
284
+ await transcript.beforeCall(callId, t.name);
285
+ const running = t.call(args, callId);
286
+ calls.add(running);
287
+ try {
288
+ const result = await running;
289
+ const images = (result.images ?? []).map((image) => ({ type: 'image', data: image.data, mimeType: image.mimeType }));
290
+ return { content: [{ type: 'text', text: result.text }, ...images], ...(result.isError ? { isError: true } : {}) };
291
+ }
292
+ catch (err) {
293
+ // The barrier timed out (nothing ran), or the drive stopped (the bridge halted it).
294
+ return errorResult(`${t.name} was not run: ${err?.message ?? String(err)}`);
295
+ }
296
+ finally {
297
+ calls.delete(running);
298
+ }
299
+ });
300
+ const allow = (updatedInput) => ({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow', ...(updatedInput ? { updatedInput } : {}) } });
301
+ const deny = (reason) => ({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: reason } });
302
+ /**
303
+ * A mutating call's writes reach the Drive before its outcome is
304
+ * recorded (a timed-out Bash may have written). Returns why the flush
305
+ * failed, if it did: that outcome is then committed as failed, saying
306
+ * its writes may not be on the Drive (never as a plain success).
307
+ */
308
+ /** A mutating built-in ended: the Drive's manifest hears of it (a live event, and the file it named). */
309
+ const changed = (name, callId, input) => {
310
+ if (replay(name) === 'safe' || !driveFiles)
311
+ return;
312
+ const field = FILE_TOOLS[name];
313
+ const path = field ? input?.[field] : undefined;
314
+ driveFiles.changed({ tool: name, callId, ...(typeof path === 'string' ? { paths: [path] } : {}) });
315
+ };
316
+ const flushed = async (name) => {
317
+ if (replay(name) === 'safe')
318
+ return undefined;
319
+ try {
320
+ await machine.fsync();
321
+ return undefined;
322
+ }
323
+ catch (err) {
324
+ const why = String(err?.message ?? err).slice(0, 200);
325
+ log('claude-agent: the Drive flush after a built-in failed', { name, error: why });
326
+ return why;
327
+ }
328
+ };
329
+ const hooks = {
330
+ // Every built-in call commits its intent before it runs. Fails
331
+ // closed: a hook that throws lets the tool run, so every error here
332
+ // is a deny.
333
+ PreToolUse: [
334
+ {
335
+ hooks: [
336
+ async (hook) => {
337
+ try {
338
+ if (hook.hook_event_name !== 'PreToolUse' || bridged(hook.tool_name))
339
+ return {};
340
+ // A skill only loads text into the conversation: one of the session's own, by its plugin-qualified
341
+ // name or by its bare one, which is rewritten to the qualified one so the record names what loaded.
342
+ // A bare name the CLI keeps for itself (a command or bundled skill) is never mapped to the session's.
343
+ if (skills && hook.tool_name === 'Skill') {
344
+ const input = (hook.tool_input ?? {});
345
+ const asked = input.skill;
346
+ const name = typeof asked === 'string' ? skills.names.find((n) => n === asked || (!CLAUDE_AGENT_CLI_SKILL_NAMES.has(asked) && n.slice(n.indexOf(':') + 1) === asked)) : undefined;
347
+ if (name === undefined)
348
+ return deny(`Not run: ${JSON.stringify(String(asked).slice(0, 80))} is not one of this session's skills.`);
349
+ return name === asked ? allow() : allow({ ...input, skill: name });
350
+ }
351
+ // WebSearch, when on, takes the built-ins' path below: its intent recorded before it runs.
352
+ if (!builtinsOn && !(webSearch && hook.tool_name === 'WebSearch'))
353
+ return deny("Not run: this session's only tools are its own.");
354
+ if (ctx.signal.aborted)
355
+ return deny('the session stopped');
356
+ let updated;
357
+ const field = FILE_TOOLS[hook.tool_name];
358
+ if (field) {
359
+ const target = hook.tool_input?.[field];
360
+ if (typeof target === 'string' && protectedPath(machine.root, target))
361
+ return deny(`Not run: ${PROTECTED_DIRS.join(' and ')} on /workspace are not written by the file tools in this session.`);
362
+ }
363
+ if (hook.tool_name === 'Bash') {
364
+ const bash = (hook.tool_input ?? {});
365
+ if (bash.run_in_background === true)
366
+ return deny('Not run: commands can\'t run in the background in this session (they end with the turn). Run it in the foreground.');
367
+ const left = deadline - Date.now() - BASH_MARGIN_MS;
368
+ if (left < BASH_MIN_MS)
369
+ return deny('Not run: this invocation of the session is out of time. Say so, and the next turn can run it.');
370
+ const asked = typeof bash.timeout === 'number' && bash.timeout > 0 ? bash.timeout : (sandbox.commandTimeoutMs ? Math.min(120_000, sandbox.commandTimeoutMs) : 120_000);
371
+ const timeout = Math.floor(Math.min(asked, left, sandbox.commandTimeoutMs ?? Infinity));
372
+ // Only a clamped call's input changes (what the log records is what ran).
373
+ if (timeout < asked) {
374
+ clamped.set(hook.tool_use_id, timeout);
375
+ updated = { ...bash, timeout };
376
+ }
377
+ }
378
+ await transcript.beforeCall(hook.tool_use_id, hook.tool_name);
379
+ const start = await builtins.begin({ callId: hook.tool_use_id, name: hook.tool_name, input: updated ?? hook.tool_input });
380
+ if (start.run)
381
+ return allow(updated);
382
+ // The log already has this call's outcome (it ran before a crash): never again.
383
+ return deny(`Not run again: this call already ran in this session. Its recorded result: ${start.result.text}`);
384
+ }
385
+ catch (err) {
386
+ return deny(`Not run: ${err?.message ?? String(err)}`);
387
+ }
388
+ },
389
+ ],
390
+ },
391
+ ],
392
+ PostToolUse: [
393
+ {
394
+ hooks: [
395
+ async (hook) => {
396
+ if (hook.hook_event_name !== 'PostToolUse' || bridged(hook.tool_name))
397
+ return {};
398
+ const unflushed = await flushed(hook.tool_name);
399
+ const limit = clamped.get(hook.tool_use_id);
400
+ const timedOut = limit !== undefined && hook.tool_response?.interrupted === true;
401
+ let text = toolResponseText(hook.tool_response);
402
+ if (timedOut)
403
+ text = outOfTime(limit, text);
404
+ if (unflushed !== undefined)
405
+ text = notFlushed(unflushed, text);
406
+ await builtins.end(hook.tool_use_id, { name: hook.tool_name, input: hook.tool_input, text, ...(timedOut || unflushed !== undefined ? { isError: true } : {}) }).catch(() => { });
407
+ changed(hook.tool_name, hook.tool_use_id, hook.tool_input);
408
+ return unflushed === undefined ? {} : { hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: NOT_FLUSHED_NOTE } };
409
+ },
410
+ ],
411
+ },
412
+ ],
413
+ PostToolUseFailure: [
414
+ {
415
+ hooks: [
416
+ async (hook) => {
417
+ if (hook.hook_event_name !== 'PostToolUseFailure' || bridged(hook.tool_name))
418
+ return {};
419
+ const unflushed = await flushed(hook.tool_name);
420
+ const limit = clamped.get(hook.tool_use_id);
421
+ const timedOut = limit !== undefined && /timed? ?out|timeout/i.test(hook.error);
422
+ let text = timedOut ? outOfTime(limit, hook.error) : hook.error;
423
+ if (unflushed !== undefined)
424
+ text = notFlushed(unflushed, text);
425
+ await builtins.end(hook.tool_use_id, { name: hook.tool_name, input: hook.tool_input, text, isError: true }).catch(() => { });
426
+ changed(hook.tool_name, hook.tool_use_id, hook.tool_input);
427
+ return unflushed === undefined ? {} : { hookSpecificOutput: { hookEventName: 'PostToolUseFailure', additionalContext: NOT_FLUSHED_NOTE } };
428
+ },
429
+ ],
430
+ },
431
+ ],
432
+ };
433
+ // The CLI's environment in the VM (the SDK gets it with the Function's config dir; `sandboxSpawn` swaps the VM's back in).
434
+ const vmEnv = durableEnv({
435
+ home: machine.dirs.home,
436
+ configDir: machine.dirs.config,
437
+ tmpDir: machine.dirs.tmp,
438
+ cacheDir: machine.dirs.cache,
439
+ baseUrl: machine.modelUrl,
440
+ token: machine.modelKey,
441
+ model,
442
+ ...(smallModel ? { smallModel } : {}),
443
+ ...(sandbox.commandTimeoutMs ? { bashTimeoutMs: sandbox.commandTimeoutMs } : {}),
444
+ ...(sandbox.env ? { extra: sandbox.env } : {}),
445
+ toolDescriptionMax: Math.max(0, ...bridge.tools.map((t) => t.description.length)),
446
+ // A host tool's result within the host's bound reaches the model whole (each tool is listed with it, too).
447
+ mcpOutputTokens: MCP_OUTPUT_TOKENS,
448
+ });
449
+ const sdkEnv = { ...vmEnv, CLAUDE_CONFIG_DIR: configDir };
450
+ const disallowed = [...CLAUDE_BUILTINS_OFF, ...(providerTools.includes('web_search') ? [] : ['WebSearch']), ...(options.disallowedTools ?? [])].filter((name) => !(skills && name === 'Skill'));
451
+ const sessionId = uuidFrom(ctx.runId);
452
+ // A turn a crash cut off: the harness's own account of it (which calls completed, which may have half-run) goes
453
+ // in this drive's system prompt, not in a user message the model might answer back to the user. A resumed
454
+ // session sends the system prompt recorded at its start (`snapshot`), whatever a later launch passes, so this
455
+ // drive alone renders its own (`snapshot: false`, which records nothing: the next drive's is the recorded one).
456
+ const recovered = recoverySystemNote(ctx.state());
457
+ const queryOptions = {
458
+ model,
459
+ cwd: machine.root,
460
+ env: sdkEnv,
461
+ // Built-ins on: the allowed ones (less those whose state the log does not carry), each let through by
462
+ // the PreToolUse hook once its intent is in the log. Off: the bridged tools are the only ones. Either
463
+ // way nothing is asked of a user, and nothing else is permitted.
464
+ ...(allowed !== undefined ? { tools: [...allowed, ...(skills ? ['Skill'] : []), ...(webSearch && !allowed.includes('WebSearch') ? ['WebSearch'] : [])] } : {}),
465
+ // The session's skills, from its own plugin: listed to the model and loadable, and no other.
466
+ ...(skills ? { plugins: [{ type: 'local', path: skills.plugin }], skills: [...skills.names] } : {}),
467
+ disallowedTools: disallowed,
468
+ hooks,
469
+ ...(ownSandbox ? { sandbox: claudeSandboxSettings(machine, sandbox.network) } : {}),
470
+ ...(bridge.tools.length ? { mcpServers: { [MCP_SERVER]: server } } : {}),
471
+ allowedTools: bridge.tools.map((t) => `mcp__${MCP_SERVER}__${t.name}`),
472
+ permissionMode: 'dontAsk',
473
+ strictMcpConfig: true,
474
+ // No user, project or local settings (and so no CLAUDE.md): a model-planted .claude/ on the Drive is ignored.
475
+ settingSources: [],
476
+ persistSession: true,
477
+ sessionStore: store,
478
+ sessionStoreFlush: 'eager',
479
+ includePartialMessages: true,
480
+ systemPrompt: {
481
+ type: 'preset',
482
+ preset: 'claude_code',
483
+ append: [builtinsOn ? DRIVE_NOTE : webSearch ? WEB_SEARCH_NOTE : bridge.tools.length ? TOOLS_NOTE : NO_TOOLS_NOTE, options.instructions, recovered].filter(Boolean).join('\n\n'),
484
+ snapshot: !recovered,
485
+ },
486
+ ...(store.hasSession ? { resume: sessionId } : { sessionId }),
487
+ ...(options.maxTurns ? { maxTurns: options.maxTurns } : {}),
488
+ pathToClaudeCodeExecutable: executable,
489
+ spawnClaudeCodeProcess: sandboxSpawn({
490
+ machine,
491
+ executable,
492
+ env: sdkEnv,
493
+ signal: ctx.signal,
494
+ onError: (err) => ctx.halt?.(err),
495
+ onSpawn: (p) => (proc = p),
496
+ onUnmapped: (why) => ctx.halt?.(mirrorUnmapped(why)),
497
+ // Its commands in their own pid namespace (its sandbox), or none at all: the model port then admits the CLI. Without its
498
+ // sandbox (`unsandboxedCommands`) it doesn't, on a real VM: a command could read the key from its environ.
499
+ isolatedCommands: ownSandbox || !builtinsOn,
500
+ }),
501
+ abortController: abort,
502
+ };
503
+ const q = query({ prompt: input, options: queryOptions });
504
+ const messages = q[Symbol.asyncIterator]();
505
+ const send = async (text, placed, how = {}) => {
506
+ // The drive's first message says, once, what the sandbox told it (a lost Drive).
507
+ if (notes) {
508
+ if (!how.synthetic)
509
+ store.message({ type: 'message', role: 'user', text: notes, synthetic: 'environment' });
510
+ text = `${notes}\n\n${text}`;
511
+ notes = undefined;
512
+ noteSent = true;
513
+ }
514
+ if (how.synthetic) {
515
+ // In the log before the submissions it carries are placed.
516
+ store.message({ type: 'message', role: 'user', text, synthetic: how.synthetic });
517
+ await store.flush();
518
+ }
519
+ // Place before send: a withdraw that wins never reaches the CLI.
520
+ await placeSubmissions(ctx, placed);
521
+ // The message's id is derived from the first submission it carries
522
+ // (the key of its placement), so a recovery can find it in the
523
+ // transcript (`lostPrompts`).
524
+ const first = placed[0]?.id;
525
+ // A new turn's spend is keyed by its first submission; a steer joins the turn it steers, and a recovery note keeps the key of the turn it resumes (set before).
526
+ if (first && how.priority !== 'next' && !how.synthetic)
527
+ ledger.turn(first);
528
+ const uuid = !first ? randomUUID() : how.synthetic ? uuidFrom(`note:${first}`) : uuidFrom(first);
529
+ // A recovery message carries placed prompts' words: which, under its uuid, before it goes (lostPrompts reads it).
530
+ if (how.covers?.length)
531
+ await ctx.effect(`covers:${uuid}`, { name: 'covers', replay: 'safe', input: { ids: how.covers } }, async () => true);
532
+ outstanding.add(uuid);
533
+ input.push({
534
+ type: 'user',
535
+ message: { role: 'user', content: text },
536
+ parent_tool_use_id: null,
537
+ uuid: uuid,
538
+ ...(how.priority ? { priority: how.priority } : {}),
539
+ });
540
+ };
541
+ /**
542
+ * The CLI exited mid-turn, not because the drive stopped: the link to
543
+ * the VM dropped (the relay killed it), or the VM killed it. Rebuild
544
+ * the drive from the log in this delivery (`Restart`: it re-attaches,
545
+ * and the turn resumes with the recovery note) while time is left;
546
+ * past that, the delivery fails and the queue redelivers.
547
+ */
548
+ const cliExited = (why) => {
549
+ const tail = proc ? proc.stderrTail().slice(-500) : '';
550
+ const message = `claude exited mid-turn: ${why}${machine.signal.aborted ? ' (the link to the VM was lost)' : ''}${tail ? ` (${tail})` : ''}`;
551
+ if (ctx.attempt < CLI_RESTARTS && deadline - Date.now() > RESTART_MIN_LEFT_MS) {
552
+ log('claude-agent: the CLI exited mid-turn; the drive is rebuilt from the log', { why: why.slice(0, 200), linkLost: machine.signal.aborted, attempt: ctx.attempt });
553
+ return new Restart(message);
554
+ }
555
+ return new Error(message);
556
+ };
557
+ /** Read messages until a turn ends. */
558
+ const nextTurnEnd = async () => {
559
+ for (;;) {
560
+ let r;
561
+ try {
562
+ r = await messages.next();
563
+ }
564
+ catch (err) {
565
+ if (ctx.signal.aborted)
566
+ throw ctx.signal.reason;
567
+ throw cliExited(String(err?.message ?? err));
568
+ }
569
+ if (ctx.signal.aborted)
570
+ throw ctx.signal.reason;
571
+ if (r.done)
572
+ throw cliExited('its output ended');
573
+ const m = r.value;
574
+ // The SDK dropped a mirror batch (the session store refused it three times): as an unmapped frame, the turn ends and the session is kept.
575
+ if (m.type === 'system' && m.subtype === 'mirror_error') {
576
+ log('claude-agent: the SDK dropped a mirror batch', { error: String(m.error ?? '').slice(0, 200) });
577
+ ctx.halt?.(mirrorUnmapped('a batch the Agent SDK could not keep in the log'));
578
+ throw ctx.signal.reason ?? mirrorUnmapped('a batch the Agent SDK could not keep in the log');
579
+ }
580
+ const end = transcript.observe(m);
581
+ if (end)
582
+ return end;
583
+ }
584
+ };
585
+ /** Steers that arrive while a turn runs go in at once, at priority `next`; the rest wait for the turn to end. */
586
+ const steering = () => {
587
+ const done = new AbortController();
588
+ const stopped = AbortSignal.any([done.signal, ctx.signal]);
589
+ const running = (async () => {
590
+ for (;;) {
591
+ for (const s of ctx.pending().filter((p) => p.kind === 'steer')) {
592
+ if (stopped.aborted)
593
+ return;
594
+ await send(s.text ?? '', [s], { priority: 'next' });
595
+ }
596
+ // A hint wakes it at once; without hints the inbox is polled.
597
+ await nap(ctx, ctx.onHint ? 5000 : 1000, stopped);
598
+ if (stopped.aborted)
599
+ return;
600
+ await ctx.refresh();
601
+ }
602
+ })().catch((err) => {
603
+ // A withdraw won a placement race (`Restart`), or a write failed: rebuild from the log.
604
+ if (!ctx.signal.aborted)
605
+ ctx.halt?.(err);
606
+ });
607
+ return async () => {
608
+ done.abort();
609
+ await running;
610
+ };
611
+ };
612
+ const runTurn = async () => {
613
+ const stopSteering = steering();
614
+ try {
615
+ for (;;) {
616
+ const end = await nextTurnEnd();
617
+ transcript.endTurn(end);
618
+ // A failed turn (a refused or failed model call) says so on the live stream too, not only in the log.
619
+ if (end.status === 'failed')
620
+ ctx.live({ type: 'error', message: end.error ?? 'the turn failed' });
621
+ if (end.consumed)
622
+ for (const u of end.consumed)
623
+ outstanding.delete(u);
624
+ else
625
+ outstanding.clear();
626
+ if (end.queued > 0 || outstanding.size > 0)
627
+ continue;
628
+ await stopSteering();
629
+ // A steer placed while the turn was ending starts another turn.
630
+ if (outstanding.size === 0)
631
+ break;
632
+ }
633
+ }
634
+ finally {
635
+ await stopSteering();
636
+ }
637
+ // The CLI writes its end-of-turn lines (last-prompt, mode, cost) right
638
+ // after the result: let them ride in the turn's last batch.
639
+ await new Promise((r) => setTimeout(r, 30));
640
+ await store.flush();
641
+ // The note reached the model in a turn that committed: a later attach doesn't show it again (unless the Drive was lost again since).
642
+ if (noteSent) {
643
+ noteSent = false;
644
+ await sandbox.acknowledge?.(ctx, machine.notesKey);
645
+ }
646
+ ctx.live({ type: 'idle' });
647
+ // The Drive as the turn left it, for the Files panel (best effort: bounded by the invocation's time left).
648
+ await driveFiles?.snapshot();
649
+ };
650
+ try {
651
+ // A turn a crash cut off: resume it with what the log knows. Quote
652
+ // its prompts if the transcript never got one of them. Its spend
653
+ // stays keyed as the turn it resumes, so the turn cap holds across
654
+ // redeliveries.
655
+ // An earlier invocation that ended before its snapshot: the manifest catches up first.
656
+ await driveFiles?.catchUp();
657
+ const open = openTurn(ctx.state());
658
+ const note = recovered && recoveryNote(ctx.state());
659
+ if (note) {
660
+ if (open)
661
+ ledger.turn(open.placed[0] ?? `open:${open.since}`);
662
+ // The CLI answers again from the interrupted step: what a reader saw of its reply is replaced by what the log kept.
663
+ ctx.live(restartEvent(note.turn));
664
+ const covers = [...(open ? lostPrompts(ctx.state(), open.placed, store) : []), ...note.pending.map((s) => s.id)];
665
+ await send(recoveryUserTurn(ctx.state(), store, note.pending), note.pending, { synthetic: 'recovery', covers });
666
+ await runTurn();
667
+ }
668
+ // The inbox, one submission per turn.
669
+ for (;;) {
670
+ await ctx.refresh();
671
+ let [s] = ctx.pending();
672
+ if (!s && options.idleMs)
673
+ [s] = await waitForSubmissions(ctx, { signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(options.idleMs)]) });
674
+ if (!s)
675
+ break;
676
+ await send(s.text ?? '', [s]);
677
+ await runTurn();
678
+ }
679
+ // A model step a crash left open that no request of this drive made again: closed.
680
+ await steps.settleAbandoned();
681
+ // Let the CLI exit (stdin closed) and the SDK deliver its last mirror frames.
682
+ input.end();
683
+ await drain(messages, 10_000);
684
+ await store.flush();
685
+ }
686
+ finally {
687
+ // A call still running (the CLI exited mid-call) finishes first; a
688
+ // stopped drive's calls stop with it (their signal), given a moment.
689
+ if (calls.size)
690
+ await settled([...calls], ctx.signal, 5000);
691
+ // A built-in the CLI never reported (it died mid-call): interrupted,
692
+ // "may or may not have taken effect". A stopped drive's are left to
693
+ // the kernel, which resolves them the same way.
694
+ if (builtins.size)
695
+ await builtins.interruptAll();
696
+ if (!input.closed)
697
+ input.end();
698
+ q.close();
699
+ const p = proc;
700
+ if (p?.alive())
701
+ await Promise.race([p.exited, new Promise((r) => setTimeout(r, 2000))]);
702
+ }
703
+ }
704
+ finally {
705
+ ctx.signal.removeEventListener('abort', stop);
706
+ // A drive that ends unstopped (the CLI exited mid-turn, a Restart): its spend records and the mirror lines still in the coalesce
707
+ // window reach the log before the rebuilt drive reads it (bounded: a failing journal has halted the drive anyway).
708
+ if (!ctx.signal.aborted)
709
+ await Promise.race([Promise.allSettled([store.flush(), journal.flush()]), new Promise((r) => setTimeout(r, 2000).unref())]);
710
+ // Nothing the model started outlives the drive: the session's processes in the VM are killed (the VM and the Drive stay).
711
+ if (held)
712
+ await held.close().catch(() => { });
713
+ // No model step outlives the drive.
714
+ await steps.close();
715
+ if (configDir)
716
+ await rm(configDir, { recursive: true, force: true }).catch(() => { });
717
+ }
718
+ },
719
+ };
720
+ }
721
+ /** The refusal by provenance (docs/workspaces.md §6 rule 1). */
722
+ function sandboxRequired() {
723
+ return new Unavailable('agentrun-harness-claude: the Claude Agent CLI runs only on the session machine its adapter makes', {
724
+ code: 'sandbox_required',
725
+ hint: "claudeAgentAdapter() makes it; a hand-built harness needs the adapter's machine.",
726
+ });
727
+ }
728
+ /** Claude Code's sandbox can't start in the VM (with the built-ins on, and no `unsandboxedCommands`). */
729
+ function noCommandSandbox() {
730
+ return new Unavailable("agentrun-harness-claude: the CLI's own command sandbox (bubblewrap) doesn't start on this machine, so its commands would run beside the CLI, where they can read its model key: this turn ends", {
731
+ hint: 'Boot from the base (prepareSandboxBase) or an image built by the same recipe (bubblewrap, socat, a mountable /proc); the next turn tries again.',
732
+ });
733
+ }
734
+ /** A built-in's outcome when the Drive didn't confirm its writes (§5.6 "FSYNC"): a failure, never a plain success. */
735
+ function notFlushed(why, output) {
736
+ return `${NOT_FLUSHED_NOTE} (the flush failed: ${why})\n${output}`;
737
+ }
738
+ /** Whether a file tool's path is under one of `PROTECTED_DIRS` of the workspace (relative paths are the workspace's). */
739
+ export function protectedPath(root, path) {
740
+ const abs = posix.resolve(root, path);
741
+ return PROTECTED_DIRS.some((d) => {
742
+ const base = posix.join(root, d);
743
+ return abs === base || abs.startsWith(`${base}/`);
744
+ });
745
+ }
746
+ /** A spend cap the model calls reached: the turn ends, saying which (§5.5 step 6). */
747
+ function spendCapped(cap) {
748
+ return new Unavailable(`The turn stopped: the ${cap === 'turnUsd' ? "turn's" : "session's"} model spend reached its cap (sandbox({ budget: { ${cap} } })).`, {
749
+ hint: `Raise sandbox({ budget: { ${cap} } }) to let the session spend more.`,
750
+ });
751
+ }
752
+ /** The mirror guard (§5.6 "Mirror"): the turn ends, the session is kept. */
753
+ function mirrorUnmapped(why) {
754
+ return new Unavailable(`agentrun-harness-claude: mirror_unmapped: the CLI's transcript mirror sent ${why}, so the transcript can't be kept in the log; this turn ends and the session is kept`, {
755
+ hint: 'This is a VM or CLI fault, not a model one: check the deployment pins the CLI the image carries; the next turn tries again.',
756
+ });
757
+ }
758
+ /** A Bash call the invocation's clamp ended (§5.6 "Deadlines"): a definite outcome, never an open intent. */
759
+ function outOfTime(limitMs, output) {
760
+ return `Ran out of time in this invocation of the session (its timeout was cut to ${Math.round(limitMs / 1000)} s); partial effects may exist. Output so far:\n${output}`;
761
+ }
762
+ /** The user's turn that resumes a cut-off turn when the user has said nothing new: no recovery text in it. */
763
+ export const RECOVERY_NUDGE = 'Continue.';
764
+ /**
765
+ * The user's turn that resumes a cut-off turn: only the user's words, the prompts of that turn the transcript never got
766
+ * (`lostPrompts`), then the messages sent since (`pending`), each whole, in that order. With none, the bare nudge: a
767
+ * resumed session moves only on a user message. The harness's own account of the turn goes in the system prompt.
768
+ */
769
+ export function recoveryUserTurn(state, store, pending) {
770
+ const open = openTurn(state);
771
+ const lost = open ? lostPrompts(state, open.placed, store) : [];
772
+ const words = [...lost.map((id) => state.submissions.find((x) => x.id === id)?.text), ...pending.map((x) => x.text)].filter((t) => !!t);
773
+ return words.length ? words.join('\n\n') : RECOVERY_NUDGE;
774
+ }
775
+ /**
776
+ * The harness's recovery note, as the resuming drive's system prompt carries it, or undefined with no turn to recover:
777
+ * only the harness's own words. Each tool call of the cut-off turn by its name, its id and its status, and never its
778
+ * input, output or error text: those can hold what a file or a web page said, and the system prompt would give that the
779
+ * harness's authority. Nor do they go in the user's turn, which would give it the user's.
780
+ */
781
+ export function recoverySystemNote(state) {
782
+ const note = recoveryNote(state, { pending: [] });
783
+ if (!note)
784
+ return undefined;
785
+ const lines = [
786
+ 'The harness, not the user, adds this about the turn before this one:',
787
+ '[Recovery] Your previous turn was interrupted: the process running it stopped, and this session was resumed from its durable log.',
788
+ '',
789
+ ];
790
+ if (note.calls.length === 0)
791
+ lines.push('No tool call had started in that turn.');
792
+ else {
793
+ lines.push('What the log records about the tool calls since that turn began (none was run again):');
794
+ for (const c of note.calls)
795
+ lines.push(`- ${c.name}, call ${c.callId}: ${RECOVERY_STATUS[c.status]}`);
796
+ lines.push('', 'The output of those calls is not shown here. Check the actual state before relying on it.');
797
+ }
798
+ lines.push('', 'Check the actual state before repeating anything that may have taken effect, then carry on with the task.');
799
+ return lines.join('\n');
800
+ }
801
+ /** What the note says of a call in each status the log can give it (the shared note's words, harness-process 010). */
802
+ const RECOVERY_STATUS = {
803
+ completed: 'completed.',
804
+ failed: 'failed.',
805
+ interrupted: 'interrupted before it reported a result. It is not safe to repeat, and it may have taken effect.',
806
+ retryable: 'interrupted before it reported a result. It is safe to repeat.',
807
+ running: 'interrupted, and it may still be running. It may have taken effect.',
808
+ };
809
+ /**
810
+ * The prompts among `placed` that never reached the transcript: neither the
811
+ * message sent for them (its `uuid` is derived from the first submission of
812
+ * their placement, `place:<id>`) nor a recovery note that carried them is in
813
+ * it. The crash came between the placement and the CLI's write.
814
+ */
815
+ export function lostPrompts(state, placed, store) {
816
+ const said = new Set(state.submissions.filter((s) => s.kind === 'prompt' || s.kind === 'steer' || s.kind === 'followUp').map((s) => s.id));
817
+ // A prompt a recovery message carried (its cover, by the message's uuid) is recorded once the transcript holds that message.
818
+ const covered = new Set(state.effectOrder.filter((e) => e.name === 'covers' && e.key.startsWith('covers:') && store.hasUser(e.key.slice('covers:'.length))).flatMap((e) => e.input?.ids ?? []));
819
+ return placed.filter((id) => {
820
+ if (!said.has(id) || covered.has(id))
821
+ return false;
822
+ const placement = state.effectOrder.find((e) => e.name === 'place' && e.key.startsWith('place:') && e.placed.includes(id));
823
+ const first = placement ? placement.key.slice('place:'.length) : id;
824
+ return !store.hasUser(uuidFrom(first)) && !store.hasUser(uuidFrom(`note:${first}`));
825
+ });
826
+ }
827
+ /** Wait `ms`, or until a hint says the log moved, or until `signal` aborts. */
828
+ function nap(ctx, ms, signal) {
829
+ return new Promise((resolve) => {
830
+ if (signal.aborted)
831
+ return resolve();
832
+ const timer = setTimeout(done, ms);
833
+ const off = ctx.onHint?.(() => done());
834
+ signal.addEventListener('abort', done, { once: true });
835
+ function done() {
836
+ clearTimeout(timer);
837
+ off?.();
838
+ signal.removeEventListener('abort', done);
839
+ resolve();
840
+ }
841
+ });
842
+ }
843
+ /** Every promise settled, or `graceMs` after `signal` aborted, whichever is first. */
844
+ function settled(promises, signal, graceMs) {
845
+ return new Promise((resolve) => {
846
+ let timer;
847
+ const onAbort = () => (timer = setTimeout(done, graceMs));
848
+ function done() {
849
+ clearTimeout(timer);
850
+ signal.removeEventListener('abort', onAbort);
851
+ resolve();
852
+ }
853
+ void Promise.allSettled(promises).then(done);
854
+ if (signal.aborted)
855
+ onAbort();
856
+ else
857
+ signal.addEventListener('abort', onAbort, { once: true });
858
+ });
859
+ }
860
+ /** A built-in's result as text: Bash's output, an edit's patch, a read file's content, else the JSON. */
861
+ export function toolResponseText(response) {
862
+ if (typeof response === 'string')
863
+ return response;
864
+ const r = response;
865
+ if (r && typeof r === 'object') {
866
+ if (typeof r.stdout === 'string' || typeof r.stderr === 'string')
867
+ return [r.stdout, r.stderr].filter(Boolean).join('\n') || '(no output)';
868
+ if (r.type === 'text' && typeof r.file?.content === 'string')
869
+ return r.file.content;
870
+ }
871
+ return JSON.stringify(response) ?? String(response);
872
+ }
873
+ function errorResult(text) {
874
+ return { content: [{ type: 'text', text }], isError: true };
875
+ }
876
+ /** Read the iterator to its end (or until `ms` passed). */
877
+ async function drain(it, ms) {
878
+ const deadline = Date.now() + ms;
879
+ for (;;) {
880
+ const left = deadline - Date.now();
881
+ if (left <= 0)
882
+ return;
883
+ const r = await Promise.race([it.next().catch(() => ({ done: true, value: undefined })), new Promise((ok) => setTimeout(() => ok('timeout'), left))]);
884
+ if (r === 'timeout' || r.done)
885
+ return;
886
+ }
887
+ }