@operad-io/harness-claude 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/worker.ts ADDED
@@ -0,0 +1,960 @@
1
+ /**
2
+ * The claude child program (docs/backlog/operad-harness-claude.md decisions
3
+ * 2 to 8).
4
+ *
5
+ * Reads one JSON object from stdin, runs one prompt through the Agent SDK
6
+ * (which starts the user's own `claude`) and writes one JSON object per line
7
+ * to stdout, the last a Result. `README.md` holds the tables.
8
+ */
9
+
10
+ import {
11
+ query,
12
+ type CanUseTool,
13
+ type HookCallback,
14
+ type Options,
15
+ type SDKMessage,
16
+ } from "@anthropic-ai/claude-agent-sdk";
17
+ import {
18
+ firstErrorLine,
19
+ match,
20
+ messageSummary,
21
+ readProfile,
22
+ REFUSED_IN_LOG,
23
+ summarizeCall,
24
+ type AccessProfile,
25
+ } from "@operad-io/access-match";
26
+ import { decideAccess, hasRules, translate, type CallAnswer } from "./access.ts";
27
+ import {
28
+ maskSecrets,
29
+ messageText,
30
+ OPERAD_SERVER,
31
+ readImage,
32
+ serverCommand,
33
+ toolOutputLines,
34
+ } from "@operad-io/harness-process";
35
+ import { findClaude } from "./claude-install.ts";
36
+ import {
37
+ DEFAULT_BASH_TIMEOUT_SECS,
38
+ parseInput,
39
+ type CostQuality,
40
+ type FailureReason,
41
+ type WorkerInput,
42
+ type WorkerLine,
43
+ type WorkerModelError,
44
+ type WorkerResult,
45
+ type WorkerUsage,
46
+ } from "./protocol.ts";
47
+
48
+ export const EXIT_FAILED = 1;
49
+ export const EXIT_INVALID_INPUT = 2;
50
+ export const EXIT_CANCELLED = 143;
51
+
52
+ /** The shortest time between two increment lines of one stream, in milliseconds. */
53
+ export const STREAM_GROUP_MS = 100;
54
+
55
+ type StreamKind = "text" | "thinking";
56
+
57
+ function recordOf(value: unknown): Record<string, unknown> | undefined {
58
+ return typeof value === "object" && value !== null && !Array.isArray(value)
59
+ ? (value as Record<string, unknown>)
60
+ : undefined;
61
+ }
62
+
63
+ function stringOf(value: unknown): string | undefined {
64
+ return typeof value === "string" ? value : undefined;
65
+ }
66
+
67
+ function numberOf(value: unknown): number | undefined {
68
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
69
+ }
70
+
71
+ /**
72
+ * The length of the longest suffix of `text` that is a proper prefix of a
73
+ * secret. A delta line may not end in such a suffix: the next line would
74
+ * complete the secret, and masking each line alone would leave both parts
75
+ * readable when a live reader joins them.
76
+ */
77
+ function secretPrefixLength(text: string, secrets: readonly string[]): number {
78
+ let held = 0;
79
+ for (const secret of secrets) {
80
+ const longest = Math.min(secret.length - 1, text.length);
81
+ for (let length = longest; length > held; length -= 1) {
82
+ if (text.endsWith(secret.slice(0, length))) {
83
+ held = length;
84
+ break;
85
+ }
86
+ }
87
+ }
88
+ return held;
89
+ }
90
+
91
+ /**
92
+ * The text a tool printed, from the shapes claude's tools return: a string, a
93
+ * text block, Bash's stdout and stderr, a file's content, or a list of names.
94
+ * Undefined when the response holds no output; the program never invents one.
95
+ */
96
+ export function toolOutputText(value: unknown): string | undefined {
97
+ if (typeof value === "string") return value;
98
+ if (Array.isArray(value)) {
99
+ const parts = value
100
+ .map((part) => toolOutputText(part))
101
+ .filter((part): part is string => part !== undefined && part.length > 0);
102
+ return parts.length === 0 ? undefined : parts.join("\n");
103
+ }
104
+ const record = recordOf(value);
105
+ if (record === undefined) return undefined;
106
+ const stdout = stringOf(record["stdout"]);
107
+ const stderr = stringOf(record["stderr"]);
108
+ if (stdout !== undefined || stderr !== undefined) {
109
+ const parts = [stdout ?? "", stderr ?? ""].filter((part) => part.length > 0);
110
+ return parts.length === 0 ? undefined : parts.join("\n");
111
+ }
112
+ for (const key of ["content", "output", "text", "message"]) {
113
+ const text = toolOutputText(record[key]);
114
+ if (text !== undefined) return text;
115
+ }
116
+ const file = recordOf(record["file"]);
117
+ const content = file === undefined ? undefined : stringOf(file["content"]);
118
+ if (content !== undefined) return content;
119
+ const names = record["filenames"];
120
+ if (Array.isArray(names)) {
121
+ const text = names.filter((name): name is string => typeof name === "string").join("\n");
122
+ if (text.length > 0) return text;
123
+ }
124
+ return undefined;
125
+ }
126
+
127
+ /**
128
+ * What the program sets for the `claude` it starts, so that it does not
129
+ * remember, read project instruction files, report or phone home on its own.
130
+ * `docs/research/2026-11-07-claude-isolation-env.md` lists which names the
131
+ * installed Claude Code reads.
132
+ */
133
+ export const ISOLATION_ENV: Readonly<Record<string, string>> = {
134
+ CLAUDE_CODE_DISABLE_AUTO_MEMORY: "1",
135
+ CLAUDE_CODE_DISABLE_CLAUDE_MDS: "1",
136
+ DISABLE_TELEMETRY: "1",
137
+ DISABLE_ERROR_REPORTING: "1",
138
+ // A run is one foreground turn: nothing may move to the background, where
139
+ // the turn would end and claude would go on by itself later.
140
+ CLAUDE_CODE_DISABLE_BACKGROUND_TASKS: "1",
141
+ };
142
+
143
+ /**
144
+ * Tools that only schedule or wait for work outside the turn. They are off, so
145
+ * the model cannot end its turn waiting for something that would continue it.
146
+ * Names are those of `BUILTIN_TOOL_NAMES` in the SDK (0.3.319).
147
+ */
148
+ export const DISALLOWED_TOOLS: readonly string[] = [
149
+ "Monitor",
150
+ "ScheduleWakeup",
151
+ "CronCreate",
152
+ "CronDelete",
153
+ "CronList",
154
+ "TaskStop",
155
+ ];
156
+
157
+ /** Where the program writes. Lines are written whole, in order. */
158
+ export interface WorkerIo {
159
+ line(line: WorkerLine): void;
160
+ /** Free text for humans; never parsed. */
161
+ log(text: string): void;
162
+ /**
163
+ * Asks the host to use up a one-time permission. True when it did and the
164
+ * call may run. Absent when the host cannot answer; no grant then applies.
165
+ */
166
+ useGrant?(waitId: string): Promise<boolean>;
167
+ /**
168
+ * Asks the host to ask a person whether one call may run, and resolves with
169
+ * the answer. Absent when the host cannot answer; a call that must ask is then
170
+ * refused.
171
+ */
172
+ ask?(call: {
173
+ readonly kind: "command" | "path";
174
+ readonly value: string;
175
+ readonly tool?: string;
176
+ readonly shown: string;
177
+ readonly session: string | null;
178
+ }): Promise<CallAnswer>;
179
+ /**
180
+ * Hands each message the host sends mid-run to `handler`, those that came
181
+ * before the call first. Absent when the host cannot send any.
182
+ */
183
+ onMessage?(handler: (text: string) => void): void;
184
+ }
185
+
186
+ export interface WorkerHooks {
187
+ /** Replaces the process the SDK starts; the tests use it for a fake `claude`. */
188
+ spawnClaudeCodeProcess?: Options["spawnClaudeCodeProcess"];
189
+ /** The clock for tool call times, in epoch milliseconds; the tests inject one. */
190
+ now?: () => number;
191
+ /** The environment the started `claude` inherits; the process's own when absent. */
192
+ env?: Readonly<Record<string, string | undefined>>;
193
+ }
194
+
195
+ /** Where the program talks to the world; the process entry points them at stdout and stderr. */
196
+ export interface WorkerPorts {
197
+ write(text: string): void;
198
+ log(text: string): void;
199
+ }
200
+
201
+ function failure(reason: FailureReason, message: string): WorkerResult {
202
+ return {
203
+ type: "result",
204
+ result: "failed",
205
+ sessionId: null,
206
+ usage: {},
207
+ cost: null,
208
+ finalMessage: null,
209
+ model: null,
210
+ reason,
211
+ message,
212
+ };
213
+ }
214
+
215
+ function finite(value: unknown): number {
216
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
217
+ }
218
+
219
+ function usageOf(value: unknown): Required<WorkerUsage> {
220
+ const read = (key: string): number =>
221
+ typeof value === "object" && value !== null ? finite(Reflect.get(value, key)) : 0;
222
+ return {
223
+ input: read("input_tokens"),
224
+ output: read("output_tokens"),
225
+ cache_read: read("cache_read_input_tokens"),
226
+ cache_write: read("cache_creation_input_tokens"),
227
+ };
228
+ }
229
+
230
+ function isSessionMissing(text: string): boolean {
231
+ return /no conversation found/i.test(text);
232
+ }
233
+
234
+ /**
235
+ * Runs one prompt and returns the exit code. `cancel` is the SIGTERM signal;
236
+ * the Result is written before the code is returned.
237
+ */
238
+ export async function runWorker(
239
+ input: WorkerInput,
240
+ io: WorkerIo,
241
+ cancel: AbortSignal,
242
+ hooks: WorkerHooks = {},
243
+ ): Promise<number> {
244
+ let executable = "claude";
245
+ if (hooks.spawnClaudeCodeProcess === undefined) {
246
+ try {
247
+ executable = findClaude(input.command);
248
+ } catch (error) {
249
+ io.line(failure("model_error", error instanceof Error ? error.message : String(error)));
250
+ return EXIT_FAILED;
251
+ }
252
+ }
253
+
254
+ const controller = new AbortController();
255
+ let cancelled = cancel.aborted;
256
+ const onCancel = (): void => {
257
+ cancelled = true;
258
+ controller.abort();
259
+ };
260
+ if (cancelled) controller.abort();
261
+ cancel.addEventListener("abort", onCancel, { once: true });
262
+
263
+ // The profile was checked when the input was read; a bad one never gets here.
264
+ const read = readProfile(input.access ?? {});
265
+ const profile: AccessProfile = read.ok ? read.profile : {};
266
+ const now = hooks.now ?? Date.now;
267
+ const secrets = input.secretValues ?? [];
268
+
269
+ // Increments are grouped: one line per stream at most every 100 ms, with the
270
+ // part still open written before the next line of any kind.
271
+ let deltaKind: StreamKind | undefined;
272
+ let deltaText = "";
273
+ let deltaAt = 0;
274
+ // `complete` says this stream has ended: a held suffix cannot be completed
275
+ // by a later group, so it is the last increment (masked if it is a whole
276
+ // secret). Otherwise a suffix that is a proper secret prefix stays back, so
277
+ // joining two increment lines can never form a secret.
278
+ const flushDelta = (complete: boolean): void => {
279
+ if (deltaKind === undefined || deltaText.length === 0) {
280
+ deltaKind = undefined;
281
+ deltaText = "";
282
+ return;
283
+ }
284
+ const kind = deltaKind;
285
+ let text: string;
286
+ if (complete) {
287
+ text = deltaText;
288
+ deltaText = "";
289
+ deltaKind = undefined;
290
+ } else {
291
+ const held = secretPrefixLength(deltaText, secrets);
292
+ text = held === 0 ? deltaText : deltaText.slice(0, -held);
293
+ deltaText = held === 0 ? "" : deltaText.slice(-held);
294
+ deltaKind = deltaText.length === 0 ? undefined : kind;
295
+ }
296
+ if (text.length > 0) {
297
+ io.line({ type: kind === "text" ? "text_delta" : "thinking_delta", text: maskSecrets(text, secrets) });
298
+ }
299
+ };
300
+ const writeLine = (line: WorkerLine): void => {
301
+ flushDelta(false);
302
+ io.line(line);
303
+ };
304
+ const addDelta = (kind: StreamKind, text: string): void => {
305
+ if (text.length === 0) return;
306
+ const at = now();
307
+ if (deltaKind === kind && at - deltaAt < STREAM_GROUP_MS) {
308
+ deltaText += text;
309
+ return;
310
+ }
311
+ // A different kind ends the previous stream; the same kind just starts a
312
+ // new group after its open part has been written.
313
+ flushDelta(deltaKind !== kind);
314
+ deltaKind = kind;
315
+ deltaText += text;
316
+ deltaAt = at;
317
+ };
318
+
319
+ // The blocks of the response being streamed, by their index. A block's end
320
+ // line is written from the finished assistant message, which carries the
321
+ // whole text even when the stream gave only a summary.
322
+ const streamBlocks = new Map<number, { readonly kind: StreamKind; text: string }>();
323
+ const streamEvent = (value: unknown): void => {
324
+ const event = recordOf(value);
325
+ if (event === undefined) return;
326
+ const type = stringOf(event["type"]);
327
+ if (type === "content_block_start") {
328
+ const index = numberOf(event["index"]);
329
+ const block = recordOf(event["content_block"]);
330
+ if (index === undefined || block === undefined) return;
331
+ const blockType = stringOf(block["type"]);
332
+ if (blockType === "text") {
333
+ const text = stringOf(block["text"]) ?? "";
334
+ streamBlocks.set(index, { kind: "text", text });
335
+ addDelta("text", text);
336
+ } else if (blockType === "thinking") {
337
+ const text = stringOf(block["thinking"]) ?? "";
338
+ streamBlocks.set(index, { kind: "thinking", text });
339
+ addDelta("thinking", text);
340
+ }
341
+ } else if (type === "content_block_delta") {
342
+ const index = numberOf(event["index"]);
343
+ const block = index === undefined ? undefined : streamBlocks.get(index);
344
+ const delta = recordOf(event["delta"]);
345
+ if (block === undefined || delta === undefined) return;
346
+ const deltaType = stringOf(delta["type"]);
347
+ if (block.kind === "text" && deltaType === "text_delta") {
348
+ const text = stringOf(delta["text"]);
349
+ if (text !== undefined) {
350
+ block.text += text;
351
+ addDelta("text", text);
352
+ }
353
+ } else if (block.kind === "thinking" && deltaType === "thinking_delta") {
354
+ const text = stringOf(delta["thinking"]);
355
+ if (text !== undefined) {
356
+ block.text += text;
357
+ addDelta("thinking", text);
358
+ }
359
+ }
360
+ } else if (type === "content_block_stop") {
361
+ const index = numberOf(event["index"]);
362
+ if (index !== undefined && streamBlocks.delete(index)) flushDelta(true);
363
+ }
364
+ };
365
+ const writeEnd = (kind: StreamKind, text: string): void => {
366
+ if (text.length === 0) return;
367
+ io.line({ type: kind === "text" ? "text_end" : "thinking_end", text: maskSecrets(text, secrets) });
368
+ };
369
+
370
+ // Tool calls that have started and not ended; a refused call ends here too,
371
+ // so the host never sees a call stay open.
372
+ const open = new Map<string, { readonly name: string; readonly startedAt: number }>();
373
+ // The same translation `decideAccess` uses, so a tool the summary does not
374
+ // know by name (NotebookEdit, MultiEdit) is still judged as its access-match tool.
375
+ const deniedByProfile = (name: string, toolInput: unknown): { readonly rule?: string } | undefined => {
376
+ const record = typeof toolInput === "object" && toolInput !== null ? (toolInput as Record<string, unknown>) : {};
377
+ const translated = translate(name, record);
378
+ if (translated.kind === "inert") return undefined;
379
+ if (translated.kind === "mapped") {
380
+ const verdict = match(profile, { tool: translated.tool, input: translated.input, cwd: input.cwd });
381
+ // A call that asks is not refused: it is shown as itself.
382
+ if (verdict.allow || verdict.ask === true) return undefined;
383
+ return verdict.rule === undefined ? {} : { rule: verdict.rule };
384
+ }
385
+ return hasRules(profile) ? {} : undefined;
386
+ };
387
+ const startCall = (id: string, name: string, toolInput: unknown): void => {
388
+ if (open.has(id)) return;
389
+ const startedAt = now();
390
+ open.set(id, { name, startedAt });
391
+ const denied = deniedByProfile(name, toolInput);
392
+ const summary = denied !== undefined
393
+ ? `${name} denied by the access profile${denied.rule === undefined ? "" : ` (rule: ${denied.rule.replace(/\s+/g, " ").slice(0, 300)})`}`
394
+ : summarizeCall(profile, name, toolInput, input.cwd, { secrets: input.secretValues, keepLines: true });
395
+ writeLine({
396
+ type: "tool_execution_start",
397
+ toolCallId: id,
398
+ toolName: name,
399
+ at: startedAt,
400
+ ...(summary === undefined ? {} : { input: summary }),
401
+ });
402
+ };
403
+ const endCall = (id: string, name: string, isError: boolean, error?: unknown, output?: unknown): void => {
404
+ const call = open.get(id);
405
+ if (call === undefined) return;
406
+ open.delete(id);
407
+ const text = isError ? undefined : toolOutputText(output);
408
+ if (text !== undefined && text.length > 0) {
409
+ for (const part of toolOutputLines(text, secrets)) {
410
+ writeLine({ type: "tool_output", toolCallId: id, text: part.text });
411
+ }
412
+ }
413
+ const firstLine = isError ? firstErrorLine(error, { secrets: input.secretValues }) : undefined;
414
+ writeLine({
415
+ type: "tool_execution_end",
416
+ toolCallId: id,
417
+ toolName: name,
418
+ isError,
419
+ durationMs: Math.max(0, now() - call.startedAt),
420
+ ...(firstLine === undefined ? {} : { error: firstLine }),
421
+ });
422
+ };
423
+ const toolHook =
424
+ (kind: "start" | "end" | "failed"): HookCallback =>
425
+ async (event) => {
426
+ if (event.hook_event_name === "PreToolUse" && kind === "start") {
427
+ startCall(event.tool_use_id, event.tool_name, event.tool_input);
428
+ } else if (event.hook_event_name === "PostToolUse" && kind === "end") {
429
+ endCall(event.tool_use_id, event.tool_name, false, undefined, event.tool_response);
430
+ } else if (event.hook_event_name === "PostToolUseFailure" && kind === "failed") {
431
+ endCall(event.tool_use_id, event.tool_name, true, event.error);
432
+ }
433
+ return {};
434
+ };
435
+
436
+ // The only permission surface (`permissionMode: 'default'` sends every call
437
+ // that is not already allowed here). A refusal goes to the model as the
438
+ // tool's result and the run goes on; the call is closed for the host.
439
+ const canUseTool: CanUseTool = async (toolName, toolInput, options) => {
440
+ io.log(`canUseTool ${toolName}`);
441
+ const askHost = io.ask;
442
+ const verdict = await decideAccess(
443
+ profile,
444
+ toolName,
445
+ toolInput,
446
+ input.cwd,
447
+ io.useGrant,
448
+ askHost === undefined
449
+ ? undefined
450
+ : async (question) => {
451
+ // A value that holds a secret is never asked about: no fact may hold it.
452
+ if ((input.secretValues ?? []).some((secret) => secret.length > 0 && question.value.includes(secret))) {
453
+ return { decision: "deny", reason: "the call holds a secret value, so nobody is asked about it" };
454
+ }
455
+ const shown = summarizeCall(profile, toolName, toolInput, input.cwd, { secrets: input.secretValues });
456
+ return askHost({ ...question, shown: shown ?? question.value, session: sessionId });
457
+ },
458
+ );
459
+ if (verdict.allow) return { behavior: "allow", updatedInput: toolInput };
460
+ if (verdict.stop === true) {
461
+ // The wait ended: the host ends this program next. Hold the call until it does.
462
+ await new Promise<void>((resolve) => {
463
+ if (controller.signal.aborted) resolve();
464
+ controller.signal.addEventListener("abort", () => resolve(), { once: true });
465
+ });
466
+ endCall(options.toolUseID, toolName, true, REFUSED_IN_LOG);
467
+ return { behavior: "deny", message: verdict.reason, interrupt: true };
468
+ }
469
+ writeLine({ type: "blocked", toolName, reason: REFUSED_IN_LOG });
470
+ endCall(options.toolUseID, toolName, true, REFUSED_IN_LOG);
471
+ return { behavior: "deny", message: verdict.reason };
472
+ };
473
+
474
+ // Operad's tools: the program that serves them on stdio, started by claude.
475
+ const operadServer =
476
+ input.operadTools === undefined
477
+ ? undefined
478
+ : {
479
+ type: "stdio" as const,
480
+ command: serverCommand(input.operadTools).command,
481
+ args: [...serverCommand(input.operadTools).args],
482
+ env: { OPERAD_HOME: input.operadTools.home },
483
+ };
484
+ const stderrTail: string[] = [];
485
+ const options: Options = {
486
+ cwd: input.cwd,
487
+ pathToClaudeCodeExecutable: executable,
488
+ settingSources: [],
489
+ permissionMode: "default",
490
+ permissionPrompts: "host",
491
+ includePartialMessages: true,
492
+ systemPrompt: { type: "preset", preset: "claude_code" },
493
+ canUseTool,
494
+ abortController: controller,
495
+ disallowedTools: [...DISALLOWED_TOOLS],
496
+ env: {
497
+ ...(hooks.env ?? process.env),
498
+ ...ISOLATION_ENV,
499
+ // Both limits, so a gate runs in the foreground instead of being moved on.
500
+ BASH_DEFAULT_TIMEOUT_MS: String((input.bashTimeoutSecs ?? DEFAULT_BASH_TIMEOUT_SECS) * 1000),
501
+ BASH_MAX_TIMEOUT_MS: String((input.bashTimeoutSecs ?? DEFAULT_BASH_TIMEOUT_SECS) * 1000),
502
+ },
503
+ hooks: {
504
+ PreToolUse: [{ hooks: [toolHook("start")] }],
505
+ PostToolUse: [{ hooks: [toolHook("end")] }],
506
+ PostToolUseFailure: [{ hooks: [toolHook("failed")] }],
507
+ },
508
+ stderr: (data) => {
509
+ io.log(data.trimEnd());
510
+ for (const text of data.split("\n")) if (text.trim().length > 0) stderrTail.push(text.trim());
511
+ if (stderrTail.length > 5) stderrTail.splice(0, stderrTail.length - 5);
512
+ },
513
+ ...(operadServer === undefined && input.mcpServers === undefined
514
+ ? {}
515
+ : {
516
+ mcpServers: {
517
+ ...(operadServer === undefined ? {} : { [OPERAD_SERVER]: operadServer }),
518
+ // A bot's servers: each is started behind its guard, which holds the secrets.
519
+ ...Object.fromEntries(
520
+ Object.entries(input.mcpServers ?? {}).map(([name, server]) => [
521
+ name,
522
+ { type: "stdio" as const, command: server.command, args: [...server.args] },
523
+ ]),
524
+ ),
525
+ },
526
+ }),
527
+ ...(input.resumeSession !== undefined ? { resume: input.resumeSession } : {}),
528
+ ...(input.model !== undefined ? { model: input.model } : {}),
529
+ ...(input.effort !== undefined ? { effort: input.effort } : {}),
530
+ ...(input.maxTurns !== undefined ? { maxTurns: input.maxTurns } : {}),
531
+ ...(input.budgetUsd !== undefined ? { maxBudgetUsd: input.budgetUsd } : {}),
532
+ ...(hooks.spawnClaudeCodeProcess !== undefined ? { spawnClaudeCodeProcess: hooks.spawnClaudeCodeProcess } : {}),
533
+ };
534
+
535
+ let sessionId: string | null = null;
536
+ let modelError: WorkerModelError | undefined;
537
+ let final: Extract<SDKMessage, { type: "result" }> | undefined;
538
+ const seenMessages = new Set<string>();
539
+ let thrown: string | undefined;
540
+ let continued = false;
541
+
542
+ // Images go with the prompt as one user message of text and image blocks.
543
+ const images = input.images ?? [];
544
+ const first = (async function* () {
545
+ const blocks = await Promise.all(images.map((image) => readImage(image)));
546
+ yield {
547
+ type: "user" as const,
548
+ message: {
549
+ role: "user" as const,
550
+ content: [
551
+ { type: "text" as const, text: input.prompt },
552
+ ...blocks.map((block) => ({
553
+ type: "image" as const,
554
+ source: { type: "base64" as const, media_type: block.mediaType, data: block.data },
555
+ })),
556
+ ],
557
+ },
558
+ parent_tool_use_id: null,
559
+ };
560
+ })();
561
+ const session = query({ prompt: images.length === 0 ? input.prompt : first, options });
562
+ // A message the host sends mid-run goes to claude as one more user turn,
563
+ // queued behind the tool call that is running.
564
+ io.onMessage?.((text) => {
565
+ const turn = (async function* () {
566
+ yield {
567
+ type: "user" as const,
568
+ message: { role: "user" as const, content: text },
569
+ parent_tool_use_id: null,
570
+ priority: "next" as const,
571
+ };
572
+ })();
573
+ session.streamInput(turn).catch((error: unknown) => {
574
+ io.log(`a message to claude was not delivered: ${error instanceof Error ? error.message : String(error)}`);
575
+ });
576
+ });
577
+ const account = session.initializationResult().then(
578
+ (init) => init.account,
579
+ () => undefined,
580
+ );
581
+
582
+ try {
583
+ messages: for await (const message of session) {
584
+ if ("session_id" in message && typeof message.session_id === "string") sessionId = message.session_id;
585
+ switch (message.type) {
586
+ case "system":
587
+ if (message.subtype === "init" && final !== undefined) {
588
+ // claude went on by itself after the result (something it started
589
+ // finished). A run is one turn: stop here and say so.
590
+ io.log("a second session started after the result; stopping");
591
+ continued = true;
592
+ break messages;
593
+ }
594
+ if (message.subtype === "init") {
595
+ io.log(`claude ${message.claude_code_version}`);
596
+ writeLine({
597
+ type: "session",
598
+ claudeVersion: message.claude_code_version,
599
+ apiKeySource: message.apiKeySource,
600
+ model: message.model,
601
+ });
602
+ }
603
+ break;
604
+ case "stream_event": {
605
+ streamEvent(message.event);
606
+ break;
607
+ }
608
+ case "assistant": {
609
+ flushDelta(true);
610
+ const texts: string[] = [];
611
+ for (const block of message.message.content) {
612
+ if (block.type === "text") texts.push(block.text);
613
+ else if (block.type === "thinking") writeEnd("thinking", block.thinking);
614
+ }
615
+ if (texts.length > 0) writeEnd("text", texts.join(""));
616
+
617
+ const id = message.message.id;
618
+ if (seenMessages.has(id)) break;
619
+ seenMessages.add(id);
620
+ const said = messageSummary(
621
+ message.message.content
622
+ .map((block) => (block.type === "text" ? block.text : ""))
623
+ .join(" "),
624
+ );
625
+ io.line({
626
+ type: "message_end",
627
+ role: "assistant",
628
+ ...(said === undefined ? {} : { text: said }),
629
+ stopReason: message.message.stop_reason,
630
+ usage: usageOf(message.message.usage),
631
+ cost: null,
632
+ });
633
+ break;
634
+ }
635
+ case "rate_limit_event": {
636
+ const info = message.rate_limit_info;
637
+ const rateLimitType = info.rateLimitType ?? null;
638
+ const resetsAt = info.resetsAt ?? null;
639
+ writeLine({ type: "rate_limit", status: info.status, rateLimitType, resetsAt });
640
+ if (info.status === "rejected") {
641
+ modelError = {
642
+ kind: "usage_limit",
643
+ message: `usage limit reached${rateLimitType === null ? "" : ` (${rateLimitType})`}`,
644
+ rateLimitType,
645
+ resetsAt,
646
+ };
647
+ }
648
+ break;
649
+ }
650
+ case "result":
651
+ final = message;
652
+ break;
653
+ default:
654
+ break;
655
+ }
656
+ }
657
+ } catch (error) {
658
+ if (!cancelled) {
659
+ thrown = error instanceof Error ? error.message : String(error);
660
+ if (stderrTail.length > 0) thrown = `${thrown}\n${stderrTail.join("\n")}`;
661
+ }
662
+ } finally {
663
+ cancel.removeEventListener("abort", onCancel);
664
+ session.close();
665
+ }
666
+
667
+ // Every way this run ends writes its Result here: text still held back as a
668
+ // possible secret prefix is released first (masked if it is a whole secret),
669
+ // so a cancelled or failed partial reply does not lose its last characters.
670
+ const finish = (line: WorkerResult, code: number): number => {
671
+ flushDelta(true);
672
+ io.line(line);
673
+ return code;
674
+ };
675
+
676
+ if (cancelled) {
677
+ return finish(
678
+ {
679
+ type: "result",
680
+ result: "cancelled",
681
+ sessionId,
682
+ usage: {},
683
+ cost: null,
684
+ finalMessage: null,
685
+ model: null,
686
+ },
687
+ EXIT_CANCELLED,
688
+ );
689
+ }
690
+
691
+ if (final === undefined) {
692
+ const message = thrown ?? "claude ended without a result";
693
+ return finish(
694
+ { ...failure(isSessionMissing(message) ? "session_missing" : "model_error", message), sessionId },
695
+ EXIT_FAILED,
696
+ );
697
+ }
698
+
699
+ const info = await account;
700
+ const quality: CostQuality =
701
+ info?.subscriptionType !== undefined && info.subscriptionType.length > 0 ? "estimated" : "exact";
702
+ const counts = usageOf(final.usage);
703
+ const text = "result" in final && typeof final.result === "string" ? final.result : null;
704
+ const names = Object.keys(final.modelUsage ?? {});
705
+ const hasModel = names.length > 0;
706
+ const base = {
707
+ type: "result",
708
+ sessionId: final.session_id,
709
+ usage: counts,
710
+ // A run that used no model (a session that would not load) has no cost to
711
+ // call exact or estimated.
712
+ cost: hasModel ? { micros: Math.round(finite(final.total_cost_usd) * 1e6), quality } : null,
713
+ finalMessage: text,
714
+ model: names[0] ?? null,
715
+ } as const;
716
+
717
+ if (continued) {
718
+ return finish(
719
+ {
720
+ ...base,
721
+ result: "failed",
722
+ reason: "model_error",
723
+ message:
724
+ "claude went on after its result: a second session started by itself (something it ran in the background finished); a run is one turn",
725
+ },
726
+ EXIT_FAILED,
727
+ );
728
+ }
729
+ if (final.subtype === "success" && !final.is_error) {
730
+ return finish({ ...base, result: "done" }, 0);
731
+ }
732
+ // An error result carries its text in `errors` (an unknown session says
733
+ // "No conversation found with session ID: ..."); a success-shaped one in `result`.
734
+ const errors = "errors" in final && Array.isArray(final.errors) ? final.errors.filter((e) => typeof e === "string") : [];
735
+ const message =
736
+ modelError?.message ??
737
+ (errors.length > 0
738
+ ? errors.join("; ")
739
+ : text !== null && text.length > 0
740
+ ? text
741
+ : `claude stopped: ${final.subtype}`);
742
+ const reason: FailureReason = isSessionMissing(message) ? "session_missing" : "model_error";
743
+ return finish(
744
+ {
745
+ ...base,
746
+ result: "failed",
747
+ reason,
748
+ message,
749
+ ...(modelError !== undefined ? { modelError } : {}),
750
+ },
751
+ EXIT_FAILED,
752
+ );
753
+ }
754
+
755
+ /**
756
+ * Stdin as lines. The first line (or all of stdin when it has no newline) is the
757
+ * input; later lines are the host's answers.
758
+ */
759
+ class StdinLines {
760
+ readonly #reader: AsyncIterator<Uint8Array>;
761
+ readonly #decoder = new TextDecoder();
762
+ #buffer = "";
763
+ #done = false;
764
+
765
+ constructor(stream: AsyncIterable<Uint8Array>) {
766
+ this.#reader = stream[Symbol.asyncIterator]();
767
+ }
768
+
769
+ /** Stops reading; a read that waits ends as if stdin had ended. */
770
+ close(): void {
771
+ void this.#reader.return?.()?.catch(() => undefined);
772
+ }
773
+
774
+ async #more(): Promise<boolean> {
775
+ if (this.#done) return false;
776
+ const chunk = await this.#reader.next();
777
+ if (chunk.done) {
778
+ this.#done = true;
779
+ this.#buffer += this.#decoder.decode();
780
+ return false;
781
+ }
782
+ this.#buffer += this.#decoder.decode(chunk.value, { stream: true });
783
+ return true;
784
+ }
785
+
786
+ /** The next line, or what is left at the end of stdin; undefined when nothing is. */
787
+ async next(): Promise<string | undefined> {
788
+ for (;;) {
789
+ const newline = this.#buffer.indexOf("\n");
790
+ if (newline !== -1) {
791
+ const line = this.#buffer.slice(0, newline);
792
+ this.#buffer = this.#buffer.slice(newline + 1);
793
+ if (line.trim().length === 0) continue;
794
+ return line;
795
+ }
796
+ if (!(await this.#more())) {
797
+ const rest = this.#buffer;
798
+ this.#buffer = "";
799
+ return rest.trim().length === 0 ? undefined : rest;
800
+ }
801
+ }
802
+ }
803
+
804
+ async first(): Promise<string> {
805
+ return (await this.next()) ?? "";
806
+ }
807
+ }
808
+
809
+ /**
810
+ * The program without the process around it: reads the input and the host's
811
+ * answers from `stdin`, writes lines through `ports`, and returns the exit
812
+ * code. `cancel` is the SIGTERM signal.
813
+ */
814
+ export async function serveWorker(
815
+ stdinStream: AsyncIterable<Uint8Array>,
816
+ ports: WorkerPorts,
817
+ cancel: AbortSignal,
818
+ hooks: WorkerHooks = {},
819
+ ): Promise<number> {
820
+ const write = ports.write;
821
+ const stdin = new StdinLines(stdinStream);
822
+ const waiting = new Map<number, (used: boolean) => void>();
823
+ const questions = new Map<number, (answer: CallAnswer) => void>();
824
+ let nextAsk = 1;
825
+ const early: string[] = [];
826
+ let onMessage: ((text: string) => void) | undefined;
827
+ let nextGrant = 1;
828
+ let hostGone = false;
829
+ const io: WorkerIo = {
830
+ line: (line) => write(`${JSON.stringify(line)}\n`),
831
+ onMessage: (handler) => {
832
+ onMessage = handler;
833
+ for (const text of early.splice(0)) handler(text);
834
+ },
835
+ log: (text) => ports.log(text),
836
+ useGrant: (waitId) =>
837
+ new Promise<boolean>((resolve) => {
838
+ if (hostGone) {
839
+ resolve(false);
840
+ return;
841
+ }
842
+ const id = nextGrant;
843
+ nextGrant += 1;
844
+ waiting.set(id, resolve);
845
+ write(`${JSON.stringify({ type: "grant_use", id, waitId })}\n`);
846
+ }),
847
+ ask: (call) =>
848
+ new Promise<CallAnswer>((resolve) => {
849
+ if (hostGone) {
850
+ resolve({ decision: "deny", reason: "the host is gone" });
851
+ return;
852
+ }
853
+ const id = nextAsk;
854
+ nextAsk += 1;
855
+ questions.set(id, (answer) => {
856
+ // The line that closes the question, so the host's stall timer runs again.
857
+ write(`${JSON.stringify({ type: "ask_resolved", id })}\n`);
858
+ resolve(answer);
859
+ });
860
+ write(`${JSON.stringify({ type: "ask_call", id, ...call })}\n`);
861
+ }),
862
+ };
863
+ let code: number;
864
+ try {
865
+ const text = await stdin.first();
866
+ let decoded: unknown;
867
+ let parsedOk = true;
868
+ try {
869
+ decoded = JSON.parse(text);
870
+ } catch {
871
+ parsedOk = false;
872
+ }
873
+ const parsed = parsedOk ? parseInput(decoded) : ({ ok: false, message: "the input is not valid JSON" } as const);
874
+ if (!parsed.ok) {
875
+ io.line(failure("invalid_input", parsed.message));
876
+ code = EXIT_INVALID_INPUT;
877
+ } else {
878
+ // Later stdin lines answer `grant_use` lines.
879
+ void (async () => {
880
+ for (;;) {
881
+ const line = await stdin.next();
882
+ if (line === undefined) break;
883
+ const said = messageText(line);
884
+ if (said !== undefined) {
885
+ if (onMessage === undefined) early.push(said);
886
+ else onMessage(said);
887
+ continue;
888
+ }
889
+ try {
890
+ const ack: unknown = JSON.parse(line);
891
+ if (typeof ack === "object" && ack !== null && Reflect.get(ack, "type") === "ask_ack") {
892
+ const id: unknown = Reflect.get(ack, "id");
893
+ const decision: unknown = Reflect.get(ack, "decision");
894
+ const reason: unknown = Reflect.get(ack, "reason");
895
+ if (typeof id === "number") {
896
+ questions.get(id)?.({
897
+ decision: decision === "allow" || decision === "stop" ? decision : "deny",
898
+ ...(typeof reason === "string" ? { reason } : {}),
899
+ });
900
+ questions.delete(id);
901
+ }
902
+ }
903
+ if (typeof ack === "object" && ack !== null && Reflect.get(ack, "type") === "grant_ack") {
904
+ const id: unknown = Reflect.get(ack, "id");
905
+ const used: unknown = Reflect.get(ack, "used");
906
+ if (typeof id === "number") {
907
+ waiting.get(id)?.(used === true);
908
+ waiting.delete(id);
909
+ }
910
+ }
911
+ } catch {
912
+ // Not a line the program understands; it is ignored.
913
+ }
914
+ }
915
+ // The host is gone: nothing more will be granted.
916
+ hostGone = true;
917
+ for (const resolve of waiting.values()) resolve(false);
918
+ waiting.clear();
919
+ for (const resolve of questions.values()) resolve({ decision: "deny", reason: "the host is gone" });
920
+ questions.clear();
921
+ })();
922
+ code = await runWorker(parsed.input, io, cancel, hooks);
923
+ }
924
+ } catch (error) {
925
+ io.log(error instanceof Error ? (error.stack ?? error.message) : String(error));
926
+ io.line(failure("model_error", error instanceof Error ? error.message : String(error)));
927
+ code = EXIT_FAILED;
928
+ }
929
+ stdin.close();
930
+ return code;
931
+ }
932
+
933
+ /** The process entry: stdin in, stdout lines out, exit code out. */
934
+ export async function main(hooks: WorkerHooks = {}): Promise<never> {
935
+ const flush = (): Promise<void> =>
936
+ new Promise((resolve) => {
937
+ process.stdout.write("", () => resolve());
938
+ });
939
+ // Anything that prints to stdout by accident would corrupt the protocol.
940
+ console.log = (...args: unknown[]): void => {
941
+ process.stderr.write(`${args.map(String).join(" ")}\n`);
942
+ };
943
+ const controller = new AbortController();
944
+ process.on("SIGTERM", () => controller.abort());
945
+ const code = await serveWorker(
946
+ Bun.stdin.stream(),
947
+ {
948
+ write: (text) => {
949
+ process.stdout.write(text);
950
+ },
951
+ log: (text) => process.stderr.write(`${text}\n`),
952
+ },
953
+ controller.signal,
954
+ hooks,
955
+ );
956
+ await flush();
957
+ process.exit(code);
958
+ }
959
+
960
+ if (import.meta.main) await main();