@operad-io/harness-claude 0.1.1 → 0.3.0

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 CHANGED
@@ -6,33 +6,60 @@
6
6
  * to stdout, the last a Result. `README.md` holds the tables.
7
7
  */
8
8
 
9
+ import { messageOf } from "@operad-io/engine";
9
10
  import {
10
11
  query,
11
12
  type CanUseTool,
12
13
  type HookCallback,
13
14
  type Options,
14
15
  type SDKMessage,
16
+ type SDKUserMessage,
17
+ type SpawnOptions,
18
+ type SpawnedProcess,
15
19
  } from "@anthropic-ai/claude-agent-sdk";
16
20
  import {
17
21
  firstErrorLine,
18
- match,
22
+ liveAccess,
19
23
  messageSummary,
20
24
  readProfile,
21
25
  REFUSED_IN_LOG,
22
26
  summarizeCall,
23
27
  type AccessProfile,
24
28
  } from "@operad-io/access-match";
25
- import { decideAccess, hasRules, translate, type CallAnswer } from "./access.ts";
29
+ import { checkProfile, decideAccess, type CallAnswer } from "./access.ts";
26
30
  import {
31
+ EXIT_CANCELLED,
32
+ EXIT_FAILED,
33
+ EXIT_INVALID_INPUT,
34
+ Increments,
27
35
  maskSecrets,
28
- messageText,
29
36
  OPERAD_SERVER,
37
+ readGivenSkills,
30
38
  readImage,
39
+ decodeWorkerInput,
40
+ runWorkerMain,
41
+ serveKeptWorker,
42
+ serveOne,
31
43
  serverCommand,
44
+ STREAM_GROUP_MS,
32
45
  toolOutputLines,
46
+ askQuestions,
47
+ answerFor,
48
+ answerText,
49
+ isSkipped,
50
+ type GivenSkill,
51
+ type HarnessQuestion,
52
+ type WorkerAdapter,
53
+ type WorkerIo as SharedWorkerIo,
54
+ type WorkerPorts,
33
55
  } from "@operad-io/harness-process";
56
+ import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
57
+ import { spawn as spawnProcess } from "node:child_process";
58
+ import { tmpdir } from "node:os";
59
+ import { join } from "node:path";
34
60
  import { findClaude } from "./claude-install.ts";
35
61
  import {
62
+ claudeContextWindow,
36
63
  DEFAULT_BASH_TIMEOUT_SECS,
37
64
  parseInput,
38
65
  type CostQuality,
@@ -44,15 +71,112 @@ import {
44
71
  type WorkerUsage,
45
72
  } from "./protocol.ts";
46
73
 
47
- export const EXIT_FAILED = 1;
48
- export const EXIT_INVALID_INPUT = 2;
49
- export const EXIT_CANCELLED = 143;
50
-
51
- /** The shortest time between two increment lines of one stream, in milliseconds. */
52
- export const STREAM_GROUP_MS = 100;
74
+ export { EXIT_CANCELLED, EXIT_FAILED, EXIT_INVALID_INPUT, STREAM_GROUP_MS };
53
75
 
54
76
  type StreamKind = "text" | "thinking";
55
77
 
78
+ /** The tool claude asks its own questions with. */
79
+ export const ASK_QUESTION_TOOL = "AskUserQuestion";
80
+
81
+ /** The tool claude leaves plan mode with. */
82
+ export const EXIT_PLAN_MODE_TOOL = "ExitPlanMode";
83
+
84
+ /** The id of the one question a plan review is. */
85
+ export const PLAN_QUESTION_ID = "plan";
86
+
87
+ /** The two answers a plan review offers. */
88
+ export const PLAN_APPROVE = "Approve";
89
+ export const PLAN_REQUEST_CHANGES = "Request changes";
90
+
91
+ /** The word a plan without a heading is titled with. */
92
+ export const PLAN_TITLE = "Plan";
93
+
94
+ /** The capability that lets an answer say a question was skipped. */
95
+ export const UNANSWERED_CAPABILITY = "ask_user_question_unanswered_v1";
96
+
97
+ /**
98
+ * The questions claude's `AskUserQuestion` asked, in the shape the shared form
99
+ * takes (ADR 0026 D6). Claude always offers the person their own words, so
100
+ * every question allows free text. Undefined when the call is not that shape,
101
+ * and then the access profile judges it as before.
102
+ */
103
+ export function claudeQuestions(toolInput: unknown): HarnessQuestion[] | undefined {
104
+ const record = recordOf(toolInput);
105
+ const raw = record?.["questions"];
106
+ if (!Array.isArray(raw) || raw.length === 0) return undefined;
107
+ const questions: HarnessQuestion[] = [];
108
+ for (const item of raw) {
109
+ const question = recordOf(item);
110
+ const text = question === undefined ? undefined : stringOf(question["question"]);
111
+ if (question === undefined || text === undefined || text.trim().length === 0) return undefined;
112
+ const choices: { label: string; description?: string }[] = [];
113
+ if (Array.isArray(question["options"])) {
114
+ for (const option of question["options"]) {
115
+ const row = recordOf(option);
116
+ const label = row === undefined ? undefined : stringOf(row["label"]);
117
+ if (row === undefined || label === undefined) continue;
118
+ const description = stringOf(row["description"]);
119
+ choices.push({ label, ...(description === undefined ? {} : { description }) });
120
+ }
121
+ }
122
+ const header = stringOf(question["header"]);
123
+ questions.push({
124
+ // Claude keys its answers by the question's own text.
125
+ id: text,
126
+ text,
127
+ ...(header === undefined ? {} : { header }),
128
+ ...(choices.length === 0 ? {} : { choices }),
129
+ ...(question["multiSelect"] === true ? { multiple: true } : {}),
130
+ freeText: true,
131
+ });
132
+ }
133
+ return questions;
134
+ }
135
+
136
+ /** A plan a person reviews before claude leaves plan mode. */
137
+ export interface PlanReview {
138
+ readonly title: string;
139
+ readonly text: string;
140
+ }
141
+
142
+ const PLAN_TITLE_LIMIT = 120;
143
+
144
+ /** The plan's title: its first Markdown heading, else its first line, else "Plan". */
145
+ function planTitle(text: string): string {
146
+ for (const raw of text.split(/\r\n|[\r\n\u2028\u2029]/)) {
147
+ const line = raw.trim();
148
+ if (line.length === 0) continue;
149
+ const heading = /^#{1,6}\s+(.+?)\s*#*$/.exec(line);
150
+ const title = (heading?.[1] ?? line).replace(/[*_`]/g, "").trim();
151
+ if (title.length === 0) continue;
152
+ return title.length <= PLAN_TITLE_LIMIT ? title : `${title.slice(0, PLAN_TITLE_LIMIT - 1)}…`;
153
+ }
154
+ return PLAN_TITLE;
155
+ }
156
+
157
+ /** The plan claude's `ExitPlanMode` call carries, when it carries one. */
158
+ export function planReview(toolInput: unknown): PlanReview | undefined {
159
+ const record = recordOf(toolInput);
160
+ const text = record === undefined ? undefined : stringOf(record["plan"]);
161
+ if (text === undefined || text.trim().length === 0) return undefined;
162
+ return { title: planTitle(text), text };
163
+ }
164
+
165
+ /** The one-question form a plan review puts to the person (ADR 0026 D6). */
166
+ export function planQuestions(review: PlanReview) {
167
+ return askQuestions([
168
+ {
169
+ id: PLAN_QUESTION_ID,
170
+ text: review.title,
171
+ body: review.text,
172
+ choices: [
173
+ { label: PLAN_APPROVE, description: "Leave plan mode and carry out the plan." },
174
+ { label: PLAN_REQUEST_CHANGES, description: "Refuse this plan and end the reply so you can say what to change." },
175
+ ],
176
+ },
177
+ ]);
178
+ }
179
+
56
180
  function recordOf(value: unknown): Record<string, unknown> | undefined {
57
181
  return typeof value === "object" && value !== null && !Array.isArray(value)
58
182
  ? (value as Record<string, unknown>)
@@ -67,26 +191,6 @@ function numberOf(value: unknown): number | undefined {
67
191
  return typeof value === "number" && Number.isFinite(value) ? value : undefined;
68
192
  }
69
193
 
70
- /**
71
- * The length of the longest suffix of `text` that is a proper prefix of a
72
- * secret. A delta line may not end in such a suffix: the next line would
73
- * complete the secret, and masking each line alone would leave both parts
74
- * readable when a live reader joins them.
75
- */
76
- function secretPrefixLength(text: string, secrets: readonly string[]): number {
77
- let held = 0;
78
- for (const secret of secrets) {
79
- const longest = Math.min(secret.length - 1, text.length);
80
- for (let length = longest; length > held; length -= 1) {
81
- if (text.endsWith(secret.slice(0, length))) {
82
- held = length;
83
- break;
84
- }
85
- }
86
- }
87
- return held;
88
- }
89
-
90
194
  /**
91
195
  * The text a tool printed, from the shapes claude's tools return: a string, a
92
196
  * text block, Bash's stdout and stderr, a file's content, or a list of names.
@@ -139,6 +243,19 @@ export const ISOLATION_ENV: Readonly<Record<string, string>> = {
139
243
  CLAUDE_CODE_DISABLE_BACKGROUND_TASKS: "1",
140
244
  };
141
245
 
246
+ /**
247
+ * The isolation variables that keep instruction files and auto memory off.
248
+ * A bot that uses the owner's own agent settings leaves these out; telemetry,
249
+ * error reporting and background tasks stay off.
250
+ */
251
+ export const INSTRUCTION_ISOLATION_ENV: readonly string[] = [
252
+ "CLAUDE_CODE_DISABLE_AUTO_MEMORY",
253
+ "CLAUDE_CODE_DISABLE_CLAUDE_MDS",
254
+ ];
255
+
256
+ /** The setting sources a bot that uses the owner's own agent settings loads. */
257
+ export const OWN_SETTING_SOURCES = ["user", "project", "local"] as const;
258
+
142
259
  /**
143
260
  * Tools that only schedule or wait for work outside the turn. They are off, so
144
261
  * the model cannot end its turn waiting for something that would continue it.
@@ -153,35 +270,43 @@ export const DISALLOWED_TOOLS: readonly string[] = [
153
270
  "TaskStop",
154
271
  ];
155
272
 
156
- /** Where the program writes. Lines are written whole, in order. */
157
- export interface WorkerIo {
158
- line(line: WorkerLine): void;
159
- /** Free text for humans; never parsed. */
160
- log(text: string): void;
161
- /**
162
- * Asks the host to use up a one-time permission. True when it did and the
163
- * call may run. Absent when the host cannot answer; no grant then applies.
164
- */
165
- useGrant?(waitId: string): Promise<boolean>;
166
- /**
167
- * Asks the host to ask a person whether one call may run, and resolves with
168
- * the answer. Absent when the host cannot answer; a call that must ask is then
169
- * refused.
170
- */
171
- ask?(call: {
172
- readonly kind: "command" | "path";
173
- readonly value: string;
174
- readonly tool?: string;
175
- readonly shown: string;
176
- readonly session: string | null;
177
- }): Promise<CallAnswer>;
178
- /**
179
- * Hands each message the host sends mid-run to `handler`, those that came
180
- * before the call first. Absent when the host cannot send any.
181
- */
182
- onMessage?(handler: (text: string) => void): void;
273
+ /** The name the temporary plugin mounts operad's skills under. */
274
+ export const SKILLS_PLUGIN = "operad-skills";
275
+
276
+ interface SkillPlugin {
277
+ readonly dir: string;
278
+ readonly names: readonly string[];
279
+ }
280
+
281
+ /**
282
+ * The SDK's `skills` option filters skills it discovered; it cannot add a
283
+ * directory. A local plugin can, so the given skill directories are mounted
284
+ * as links in a plugin under the worker's own temporary directory. Nothing is
285
+ * written into a skill directory or the repository, and the whole temporary
286
+ * plugin is removed when the run ends.
287
+ */
288
+ function buildSkillPlugin(skills: readonly GivenSkill[]): SkillPlugin {
289
+ const dir = mkdtempSync(join(tmpdir(), "operad-claude-skills-"));
290
+ try {
291
+ mkdirSync(join(dir, ".claude-plugin"), { recursive: true });
292
+ mkdirSync(join(dir, "skills"), { recursive: true });
293
+ writeFileSync(
294
+ join(dir, ".claude-plugin", "plugin.json"),
295
+ `${JSON.stringify({ name: SKILLS_PLUGIN, version: "0.1.0", skills: ["./skills"] }, null, 2)}\n`,
296
+ );
297
+ for (const skill of skills) {
298
+ symlinkSync(skill.path, join(dir, "skills", skill.name), "dir");
299
+ }
300
+ return { dir, names: skills.map((skill) => skill.name) };
301
+ } catch (error) {
302
+ rmSync(dir, { recursive: true, force: true });
303
+ throw error;
304
+ }
183
305
  }
184
306
 
307
+ /** Where the program writes. Lines are written whole, in order. */
308
+ export type WorkerIo = SharedWorkerIo<WorkerLine>;
309
+
185
310
  export interface WorkerHooks {
186
311
  /** Replaces the process the SDK starts; the tests use it for a fake `claude`. */
187
312
  spawnClaudeCodeProcess?: Options["spawnClaudeCodeProcess"];
@@ -191,12 +316,6 @@ export interface WorkerHooks {
191
316
  env?: Readonly<Record<string, string | undefined>>;
192
317
  }
193
318
 
194
- /** Where the program talks to the world; the process entry points them at stdout and stderr. */
195
- export interface WorkerPorts {
196
- write(text: string): void;
197
- log(text: string): void;
198
- }
199
-
200
319
  function failure(reason: FailureReason, message: string): WorkerResult {
201
320
  return {
202
321
  type: "result",
@@ -230,96 +349,659 @@ function isSessionMissing(text: string): boolean {
230
349
  return /no conversation found/i.test(text);
231
350
  }
232
351
 
352
+ /** What claude itself says about a turn that ended without text and without a model call. */
353
+ function noAnswerReason(
354
+ final: { readonly subtype: string; readonly local_command?: string },
355
+ errors: readonly string[],
356
+ ): string {
357
+ const parts = [`the agent reported ${final.subtype}`];
358
+ if (errors.length > 0) parts.push(`errors: ${errors.join("; ")}`);
359
+ const command = typeof final.local_command === "string" ? final.local_command.trim() : "";
360
+ if (command.length > 0) parts.push(`it ran the local command ${command}`);
361
+ return parts.join("; ");
362
+ }
363
+
233
364
  /**
234
365
  * Runs one prompt and returns the exit code. `cancel` is the SIGTERM signal;
235
366
  * the Result is written before the code is returned.
236
367
  */
237
- export async function runWorker(
238
- input: WorkerInput,
239
- io: WorkerIo,
240
- cancel: AbortSignal,
241
- hooks: WorkerHooks = {},
242
- ): Promise<number> {
243
- let executable = "claude";
244
- if (hooks.spawnClaudeCodeProcess === undefined) {
368
+ /** One reply's state while the session's message loop writes its lines. */
369
+ interface Turn {
370
+ readonly input: WorkerInput;
371
+ readonly io: WorkerIo;
372
+ readonly cancel: AbortSignal;
373
+ cancelled: boolean;
374
+ readonly increments: Increments;
375
+ readonly streamBlocks: Map<number, { readonly kind: StreamKind; text: string }>;
376
+ readonly open: Map<string, { readonly name: string; readonly startedAt: number }>;
377
+ readonly profile: AccessProfile;
378
+ final: Extract<SDKMessage, { type: "result" }> | undefined;
379
+ lastUsage: Required<WorkerUsage> | undefined;
380
+ modelError: WorkerModelError | undefined;
381
+ thrown: string | undefined;
382
+ continued: boolean;
383
+ settled: boolean;
384
+ readonly done: Promise<void>;
385
+ readonly resolveDone: () => void;
386
+ }
387
+
388
+ function newTurn(input: WorkerInput, io: WorkerIo, cancel: AbortSignal, increments: Increments): Turn {
389
+ let resolveDone: () => void = () => {};
390
+ const done = new Promise<void>((resolve) => {
391
+ resolveDone = resolve;
392
+ });
393
+ return {
394
+ input,
395
+ io,
396
+ cancel,
397
+ cancelled: cancel.aborted,
398
+ increments,
399
+ streamBlocks: new Map(),
400
+ open: new Map(),
401
+ profile: (() => {
402
+ const read = readProfile(input.access ?? {});
403
+ return read.ok ? read.profile : {};
404
+ })(),
405
+ final: undefined,
406
+ lastUsage: undefined,
407
+ modelError: undefined,
408
+ thrown: undefined,
409
+ continued: false,
410
+ settled: false,
411
+ done,
412
+ resolveDone,
413
+ };
414
+ }
415
+
416
+ /** The prompts after the first, held until the SDK asks for them. */
417
+ class PromptQueue implements AsyncIterable<SDKUserMessage> {
418
+ private readonly items: SDKUserMessage[] = [];
419
+ private readonly waiters: Array<(value: IteratorResult<SDKUserMessage>) => void> = [];
420
+ private closed = false;
421
+
422
+ push(message: SDKUserMessage): void {
423
+ if (this.closed) return;
424
+ const waiter = this.waiters.shift();
425
+ if (waiter === undefined) this.items.push(message);
426
+ else waiter({ value: message, done: false });
427
+ }
428
+
429
+ close(): void {
430
+ if (this.closed) return;
431
+ this.closed = true;
432
+ for (const waiter of this.waiters.splice(0)) waiter({ value: undefined, done: true });
433
+ }
434
+
435
+ [Symbol.asyncIterator](): AsyncIterator<SDKUserMessage> {
436
+ return {
437
+ next: (): Promise<IteratorResult<SDKUserMessage>> => {
438
+ const item = this.items.shift();
439
+ if (item !== undefined) return Promise.resolve({ value: item, done: false });
440
+ if (this.closed) return Promise.resolve({ value: undefined, done: true });
441
+ return new Promise((resolve) => this.waiters.push(resolve));
442
+ },
443
+ return: (): Promise<IteratorResult<SDKUserMessage>> => {
444
+ this.close();
445
+ return Promise.resolve({ value: undefined, done: true });
446
+ },
447
+ };
448
+ }
449
+ }
450
+
451
+ /** Whether claude must take the text as written instead of dispatching it as its own command. */
452
+ function leadingSlash(text: string): boolean {
453
+ return text.trimStart().startsWith("/");
454
+ }
455
+
456
+ function clientComposed(text: string): { readonly client_composed?: true } {
457
+ return leadingSlash(text) ? { client_composed: true } : {};
458
+ }
459
+
460
+ function userMessage(text: string): SDKUserMessage {
461
+ return {
462
+ type: "user" as const,
463
+ message: { role: "user" as const, content: text },
464
+ parent_tool_use_id: null,
465
+ ...clientComposed(text),
466
+ };
467
+ }
468
+
469
+ async function userMessageWithImages(input: WorkerInput): Promise<SDKUserMessage> {
470
+ const blocks = await Promise.all((input.images ?? []).map((image) => readImage(image)));
471
+ return {
472
+ type: "user" as const,
473
+ message: {
474
+ role: "user" as const,
475
+ content: [
476
+ { type: "text" as const, text: input.prompt },
477
+ ...blocks.map((block) => ({
478
+ type: "image" as const,
479
+ source: { type: "base64" as const, media_type: block.mediaType, data: block.data },
480
+ })),
481
+ ],
482
+ },
483
+ parent_tool_use_id: null,
484
+ ...clientComposed(input.prompt),
485
+ };
486
+ }
487
+
488
+ /**
489
+ * Starts claude in a process group of its own with a helper that watches this
490
+ * worker. A worker killed with no chance to clean up (SIGKILL) still leaves no
491
+ * `claude` behind: the helper sees its parent gone and kills the group. Without
492
+ * this, only a graceful close would end claude.
493
+ */
494
+ function spawnWatched(options: SpawnOptions): SpawnedProcess {
495
+ const script = [
496
+ "parent=$1",
497
+ "shift",
498
+ '( while kill -0 "$parent" 2>/dev/null; do sleep 1; done; kill -KILL -$$ ) >/dev/null 2>&1 &',
499
+ 'exec "$@"',
500
+ ].join("\n");
501
+ return spawnProcess(
502
+ "sh",
503
+ ["-c", script, "operad-claude", String(process.pid), options.command, ...options.args],
504
+ {
505
+ cwd: options.cwd,
506
+ env: options.env as NodeJS.ProcessEnv,
507
+ detached: true,
508
+ stdio: ["pipe", "pipe", "pipe"],
509
+ },
510
+ );
511
+ }
512
+
513
+ /**
514
+ * One claude session behind the worker. A plain worker opens it for one reply
515
+ * and closes it; a kept worker opens it for the first reply and leaves it open,
516
+ * so later replies send another prompt through the same query stream and the
517
+ * `claude` process is not started again.
518
+ */
519
+ class ClaudeSession {
520
+ private readonly controller = new AbortController();
521
+ private readonly now: () => number;
522
+ private readonly hooks: WorkerHooks;
523
+ private readonly persistent: boolean;
524
+ private readonly secrets: readonly string[];
525
+ private readonly given: ReturnType<typeof readGivenSkills>;
526
+ private readonly skillPlugin: SkillPlugin | undefined;
527
+ private readonly sessionSkillNote: string | undefined;
528
+ private readonly stderrTail: string[] = [];
529
+ private readonly seenMessages = new Set<string>();
530
+ private readonly queue: PromptQueue | undefined;
531
+ private readonly options: Options;
532
+ private session: ReturnType<typeof query> | undefined;
533
+ private account: Promise<{ subscriptionType?: string } | undefined> | undefined;
534
+ private reading: Promise<void> | undefined;
535
+ private turn: Turn | undefined;
536
+ private sessionId: string | null = null;
537
+ private initLine:
538
+ | { readonly claudeVersion: string; readonly apiKeySource: string; readonly model: string }
539
+ | undefined;
540
+ /** What this claude said it supports, from the init line's capabilities. */
541
+ private capabilities = new Set<string>();
542
+ private started = false;
543
+ private queryEnded = false;
544
+ private closed = false;
545
+ private broken: string | undefined;
546
+ private readonly endedHandlers: Array<(code: number) => void> = [];
547
+
548
+ constructor(
549
+ private readonly initial: WorkerInput,
550
+ private readonly firstIo: WorkerIo,
551
+ private readonly firstCancel: AbortSignal,
552
+ hooks: WorkerHooks,
553
+ persistent: boolean,
554
+ ) {
555
+ this.hooks = hooks;
556
+ this.persistent = persistent;
557
+ this.now = hooks.now ?? Date.now;
558
+ this.secrets = initial.secretValues ?? [];
559
+ this.given = readGivenSkills(initial.skills ?? []);
560
+ this.skillPlugin = this.given.skills.length === 0 ? undefined : buildSkillPlugin(this.given.skills);
561
+ this.sessionSkillNote =
562
+ this.skillPlugin === undefined ? undefined : `skills: ${this.skillPlugin.names.join(", ")}`;
563
+ this.queue = persistent ? new PromptQueue() : undefined;
564
+
565
+ for (const skip of this.given.skipped) {
566
+ const text = `skill ${skip.path}: ${skip.reason}`;
567
+ firstIo.log(text);
568
+ firstIo.line({ type: "log", text });
569
+ }
570
+
571
+ const operadServer =
572
+ initial.operadTools === undefined
573
+ ? undefined
574
+ : {
575
+ type: "stdio" as const,
576
+ command: serverCommand(initial.operadTools).command,
577
+ args: [...serverCommand(initial.operadTools).args],
578
+ env: { OPERAD_HOME: initial.operadTools.home },
579
+ };
580
+
581
+ const childEnv: Record<string, string | undefined> = {
582
+ ...(hooks.env ?? process.env),
583
+ ...ISOLATION_ENV,
584
+ BASH_DEFAULT_TIMEOUT_MS: String((initial.bashTimeoutSecs ?? DEFAULT_BASH_TIMEOUT_SECS) * 1000),
585
+ BASH_MAX_TIMEOUT_MS: String((initial.bashTimeoutSecs ?? DEFAULT_BASH_TIMEOUT_SECS) * 1000),
586
+ };
587
+ if (initial.useOwnSettings === true) {
588
+ // Instruction files and auto memory are the owner's own; telemetry, error
589
+ // reporting and background tasks stay off.
590
+ for (const name of INSTRUCTION_ISOLATION_ENV) delete childEnv[name];
591
+ }
592
+ this.options = {
593
+ cwd: initial.cwd,
594
+ pathToClaudeCodeExecutable: this.executable(initial),
595
+ settingSources: initial.useOwnSettings === true ? [...OWN_SETTING_SOURCES] : [],
596
+ permissionMode: "default",
597
+ permissionPrompts: "host",
598
+ includePartialMessages: true,
599
+ systemPrompt: { type: "preset", preset: "claude_code" },
600
+ canUseTool: this.canUseTool,
601
+ abortController: this.controller,
602
+ disallowedTools: [...DISALLOWED_TOOLS],
603
+ ...(this.skillPlugin === undefined
604
+ ? {}
605
+ : {
606
+ plugins: [{ type: "local" as const, path: this.skillPlugin.dir }],
607
+ // The switch keeps operad's skills and adds the owner's own; a name
608
+ // both sides define is operad's because its plugin is the one mounted
609
+ // here. With the switch off, only the skills mounted above load.
610
+ skills:
611
+ initial.useOwnSettings === true
612
+ ? "all"
613
+ : this.skillPlugin.names.map((name) => `${SKILLS_PLUGIN}:${name}`),
614
+ }),
615
+ env: childEnv,
616
+ hooks: {
617
+ PreToolUse: [{ hooks: [this.toolHook("start")] }],
618
+ PostToolUse: [{ hooks: [this.toolHook("end")] }],
619
+ PostToolUseFailure: [{ hooks: [this.toolHook("failed")] }],
620
+ },
621
+ stderr: (data) => {
622
+ const io = this.turn?.io ?? this.firstIo;
623
+ io.log(data.trimEnd());
624
+ for (const text of data.split("\n")) if (text.trim().length > 0) this.stderrTail.push(text.trim());
625
+ if (this.stderrTail.length > 5) this.stderrTail.splice(0, this.stderrTail.length - 5);
626
+ },
627
+ ...(operadServer === undefined && initial.mcpServers === undefined
628
+ ? {}
629
+ : {
630
+ mcpServers: {
631
+ ...(operadServer === undefined ? {} : { [OPERAD_SERVER]: operadServer }),
632
+ ...Object.fromEntries(
633
+ Object.entries(initial.mcpServers ?? {}).map(([name, server]) => [
634
+ name,
635
+ { type: "stdio" as const, command: server.command, args: [...server.args] },
636
+ ]),
637
+ ),
638
+ },
639
+ }),
640
+ ...(initial.resumeSession !== undefined ? { resume: initial.resumeSession } : {}),
641
+ ...(initial.model !== undefined ? { model: initial.model } : {}),
642
+ ...(initial.effort !== undefined ? { effort: initial.effort } : {}),
643
+ ...(initial.maxTurns !== undefined ? { maxTurns: initial.maxTurns } : {}),
644
+ ...(initial.budgetUsd !== undefined ? { maxBudgetUsd: initial.budgetUsd } : {}),
645
+ spawnClaudeCodeProcess: hooks.spawnClaudeCodeProcess ?? spawnWatched,
646
+ };
647
+ }
648
+
649
+ /** The user's own claude, found at start unless a test supplies the spawn. */
650
+ private executable(input: WorkerInput): string {
651
+ if (this.hooks.spawnClaudeCodeProcess !== undefined) return "claude";
652
+ return findClaude(input.command);
653
+ }
654
+
655
+ /** Tells a kept worker when the session ends by itself. */
656
+ onEnded(handler: (code: number) => void): void {
657
+ this.endedHandlers.push(handler);
658
+ }
659
+
660
+ /** The session the last reply used, as the kept record reports it. */
661
+ currentSession(): string | null {
662
+ return this.sessionId;
663
+ }
664
+
665
+ /** The first reply; the query starts here. */
666
+ async first(): Promise<number> {
667
+ return this.runTurn(this.initial, this.firstIo, this.firstCancel, true);
668
+ }
669
+
670
+ /** A later reply through the session this worker kept. */
671
+ async next(input: WorkerInput, io: WorkerIo, cancel: AbortSignal): Promise<number> {
672
+ return this.runTurn(input, io, cancel, false);
673
+ }
674
+
675
+ private async runTurn(input: WorkerInput, io: WorkerIo, cancel: AbortSignal, first: boolean): Promise<number> {
676
+ if (this.closed || this.broken !== undefined) {
677
+ const message = this.broken ?? "the kept session is closed";
678
+ io.line(failure("model_error", message));
679
+ return EXIT_FAILED;
680
+ }
681
+ const turn = newTurn(
682
+ input,
683
+ io,
684
+ cancel,
685
+ new Increments(io, this.now, this.secrets, { firstImmediately: false }),
686
+ );
687
+ this.turn = turn;
688
+ const onCancel = (): void => {
689
+ turn.cancelled = true;
690
+ this.controller.abort();
691
+ };
692
+ cancel.addEventListener("abort", onCancel, { once: true });
693
+ if (cancel.aborted) onCancel();
694
+
695
+ io.onMessage?.((text) => {
696
+ if (this.queue !== undefined) {
697
+ this.queue.push({ ...userMessage(text), priority: "next" as const });
698
+ return;
699
+ }
700
+ const next = (async function* () {
701
+ yield { ...userMessage(text), priority: "next" as const };
702
+ })();
703
+ this.session?.streamInput(next).catch((error: unknown) => {
704
+ io.log(`a message to claude was not delivered: ${messageOf(error)}`);
705
+ });
706
+ });
707
+
708
+ if (first) {
709
+ this.started = true;
710
+ try {
711
+ this.session = query({
712
+ prompt:
713
+ this.queue ??
714
+ ((input.images ?? []).length === 0 && !leadingSlash(input.prompt)
715
+ ? input.prompt
716
+ : (async function* () {
717
+ yield await userMessageWithImages(input);
718
+ })()),
719
+ options: this.options,
720
+ });
721
+ } catch (error) {
722
+ turn.cancel.removeEventListener("abort", onCancel);
723
+ this.removeSkillPlugin();
724
+ io.line(failure("model_error", messageOf(error)));
725
+ return EXIT_FAILED;
726
+ }
727
+ this.account = this.session.initializationResult().then(
728
+ (init) => init.account,
729
+ () => undefined,
730
+ );
731
+ this.reading = this.readLoop();
732
+ } else if (this.initLine !== undefined) {
733
+ // The session line and the skill note belong to this reply's own log too.
734
+ io.line({ type: "session", ...this.initLine });
735
+ if (this.sessionSkillNote !== undefined) {
736
+ io.log(this.sessionSkillNote);
737
+ io.line({ type: "log", text: this.sessionSkillNote });
738
+ }
739
+ }
740
+
741
+ if (this.queue !== undefined) {
742
+ this.queue.push(await userMessageWithImages(input));
743
+ await turn.done;
744
+ } else {
745
+ await this.reading;
746
+ }
747
+ turn.cancel.removeEventListener("abort", onCancel);
748
+
749
+ const outcome = await this.resultOf(turn);
750
+ turn.io.line(outcome.line);
751
+ if (!this.persistent) this.close();
752
+ return outcome.code;
753
+ }
754
+
755
+ private resolve(turn: Turn): void {
756
+ if (turn.settled) return;
757
+ turn.settled = true;
758
+ turn.resolveDone();
759
+ }
760
+
761
+ private handleMessage(message: SDKMessage): "stop" | undefined {
762
+ const turn = this.turn;
763
+ if (turn === undefined) {
764
+ if (message.type === "system" && message.subtype === "init") {
765
+ this.broken = "claude started a second session while no reply was running";
766
+ this.firstIo.log(`${this.broken}; stopping`);
767
+ }
768
+ return undefined;
769
+ }
770
+ if ("session_id" in message && typeof message.session_id === "string") this.sessionId = message.session_id;
771
+ switch (message.type) {
772
+ case "system":
773
+ if (message.subtype === "api_retry") {
774
+ turn.io.line({
775
+ type: "retry_start",
776
+ attempt: message.attempt,
777
+ maxAttempts: message.max_retries,
778
+ delayMs: message.retry_delay_ms,
779
+ reason: `the model request failed: ${message.error}${message.error_status === null ? "" : ` (HTTP ${message.error_status})`}`,
780
+ });
781
+ break;
782
+ }
783
+ if (message.subtype === "init" && turn.final !== undefined) {
784
+ turn.io.log("a second session started after the result; stopping");
785
+ turn.continued = true;
786
+ if (this.persistent) this.broken = "claude went on after its result";
787
+ return this.persistent ? undefined : "stop";
788
+ }
789
+ if (message.subtype === "init") {
790
+ turn.io.log(`claude ${message.claude_code_version}`);
791
+ this.capabilities = new Set(message.capabilities ?? []);
792
+ if (this.sessionSkillNote !== undefined) {
793
+ turn.io.log(this.sessionSkillNote);
794
+ turn.io.line({ type: "log", text: this.sessionSkillNote });
795
+ }
796
+ const line = {
797
+ claudeVersion: message.claude_code_version,
798
+ apiKeySource: message.apiKeySource,
799
+ model: message.model,
800
+ };
801
+ this.initLine = line;
802
+ turn.io.line({ type: "session", ...line });
803
+ }
804
+ break;
805
+ case "stream_event":
806
+ this.streamEvent(turn, message.event);
807
+ break;
808
+ case "assistant": {
809
+ turn.increments.flush("text", true);
810
+ turn.increments.flush("thinking", true);
811
+ const texts: string[] = [];
812
+ for (const block of message.message.content) {
813
+ if (block.type === "text") texts.push(block.text);
814
+ else if (block.type === "thinking") this.writeEnd(turn, "thinking", block.thinking);
815
+ }
816
+ if (texts.length > 0) this.writeEnd(turn, "text", texts.join(""));
817
+
818
+ const id = message.message.id;
819
+ if (this.seenMessages.has(id)) break;
820
+ this.seenMessages.add(id);
821
+ const counts = usageOf(message.message.usage);
822
+ turn.lastUsage = counts;
823
+ const said = messageSummary(
824
+ message.message.content.map((block) => (block.type === "text" ? block.text : "")).join(" "),
825
+ );
826
+ turn.io.line({
827
+ type: "message_end",
828
+ role: "assistant",
829
+ ...(said === undefined ? {} : { text: said }),
830
+ stopReason: message.message.stop_reason,
831
+ usage: counts,
832
+ cost: null,
833
+ });
834
+ break;
835
+ }
836
+ case "rate_limit_event": {
837
+ const info = message.rate_limit_info;
838
+ const rateLimitType = info.rateLimitType ?? null;
839
+ const resetsAt = info.resetsAt ?? null;
840
+ this.writeLine(turn, { type: "rate_limit", status: info.status, rateLimitType, resetsAt });
841
+ if (info.status === "rejected") {
842
+ turn.modelError = {
843
+ kind: "usage_limit",
844
+ message: `usage limit reached${rateLimitType === null ? "" : ` (${rateLimitType})`}`,
845
+ rateLimitType,
846
+ resetsAt,
847
+ retry_after_secs:
848
+ resetsAt === null
849
+ ? null
850
+ : Math.max(0, Math.ceil(resetsAt - Date.now() / 1000)),
851
+ reported_at: resetsAt === null ? null : Date.now(),
852
+ };
853
+ }
854
+ break;
855
+ }
856
+ case "result":
857
+ turn.final = message;
858
+ if (this.persistent) this.resolve(turn);
859
+ break;
860
+ default:
861
+ break;
862
+ }
863
+ return undefined;
864
+ }
865
+
866
+ private async readLoop(): Promise<void> {
245
867
  try {
246
- executable = findClaude(input.command);
868
+ reading: for (;;) {
869
+ const session = this.session;
870
+ if (session === undefined) break;
871
+ for await (const message of session) {
872
+ if (this.handleMessage(message) === "stop") break reading;
873
+ }
874
+ break;
875
+ }
247
876
  } catch (error) {
248
- io.line(failure("model_error", error instanceof Error ? error.message : String(error)));
249
- return EXIT_FAILED;
877
+ const turn = this.turn;
878
+ if (turn !== undefined && !turn.cancelled) {
879
+ turn.thrown = messageOf(error);
880
+ if (this.stderrTail.length > 0) turn.thrown = `${turn.thrown}\n${this.stderrTail.join("\n")}`;
881
+ }
882
+ } finally {
883
+ this.queryEnded = true;
884
+ if (this.turn !== undefined) this.resolve(this.turn);
885
+ if (this.persistent && !this.closed) {
886
+ for (const handler of this.endedHandlers.splice(0)) handler(EXIT_FAILED);
887
+ }
250
888
  }
251
889
  }
252
890
 
253
- const controller = new AbortController();
254
- let cancelled = cancel.aborted;
255
- const onCancel = (): void => {
256
- cancelled = true;
257
- controller.abort();
258
- };
259
- if (cancelled) controller.abort();
260
- cancel.addEventListener("abort", onCancel, { once: true });
261
-
262
- // The profile was checked when the input was read; a bad one never gets here.
263
- const read = readProfile(input.access ?? {});
264
- const profile: AccessProfile = read.ok ? read.profile : {};
265
- const now = hooks.now ?? Date.now;
266
- const secrets = input.secretValues ?? [];
267
-
268
- // Increments are grouped: one line per stream at most every 100 ms, with the
269
- // part still open written before the next line of any kind.
270
- let deltaKind: StreamKind | undefined;
271
- let deltaText = "";
272
- let deltaAt = 0;
273
- // `complete` says this stream has ended: a held suffix cannot be completed
274
- // by a later group, so it is the last increment (masked if it is a whole
275
- // secret). Otherwise a suffix that is a proper secret prefix stays back, so
276
- // joining two increment lines can never form a secret.
277
- const flushDelta = (complete: boolean): void => {
278
- if (deltaKind === undefined || deltaText.length === 0) {
279
- deltaKind = undefined;
280
- deltaText = "";
281
- return;
282
- }
283
- const kind = deltaKind;
284
- let text: string;
285
- if (complete) {
286
- text = deltaText;
287
- deltaText = "";
288
- deltaKind = undefined;
289
- } else {
290
- const held = secretPrefixLength(deltaText, secrets);
291
- text = held === 0 ? deltaText : deltaText.slice(0, -held);
292
- deltaText = held === 0 ? "" : deltaText.slice(-held);
293
- deltaKind = deltaText.length === 0 ? undefined : kind;
891
+ private async resultOf(turn: Turn): Promise<{ readonly line: WorkerResult; readonly code: number }> {
892
+ turn.increments.release();
893
+ if (turn.cancelled) {
894
+ return {
895
+ line: {
896
+ type: "result",
897
+ result: "cancelled",
898
+ sessionId: this.sessionId,
899
+ usage: {},
900
+ cost: null,
901
+ finalMessage: null,
902
+ model: null,
903
+ },
904
+ code: EXIT_CANCELLED,
905
+ };
294
906
  }
295
- if (text.length > 0) {
296
- io.line({ type: kind === "text" ? "text_delta" : "thinking_delta", text: maskSecrets(text, secrets) });
907
+ if (turn.final === undefined) {
908
+ const message = turn.thrown ?? "claude ended without a result";
909
+ return {
910
+ line: {
911
+ ...failure(isSessionMissing(message) ? "session_missing" : "model_error", message),
912
+ sessionId: this.sessionId,
913
+ },
914
+ code: EXIT_FAILED,
915
+ };
297
916
  }
298
- };
299
- const writeLine = (line: WorkerLine): void => {
300
- flushDelta(false);
301
- io.line(line);
302
- };
303
- const addDelta = (kind: StreamKind, text: string): void => {
304
- if (text.length === 0) return;
305
- const at = now();
306
- if (deltaKind === kind && at - deltaAt < STREAM_GROUP_MS) {
307
- deltaText += text;
308
- return;
309
- }
310
- // A different kind ends the previous stream; the same kind just starts a
311
- // new group after its open part has been written.
312
- flushDelta(deltaKind !== kind);
313
- deltaKind = kind;
314
- deltaText += text;
315
- deltaAt = at;
316
- };
917
+ const info = await this.account;
918
+ const quality: CostQuality =
919
+ info?.subscriptionType !== undefined && info.subscriptionType.length > 0 ? "estimated" : "exact";
920
+ const final = turn.final;
921
+ const counts = usageOf(final.usage);
922
+ const text = "result" in final && typeof final.result === "string" ? final.result : null;
923
+ const names = Object.keys(final.modelUsage ?? {});
924
+ const hasModel = names.length > 0;
925
+ const window = claudeContextWindow(turn.input.model ?? names[0]);
926
+ const context =
927
+ turn.lastUsage === undefined
928
+ ? undefined
929
+ : {
930
+ used:
931
+ turn.lastUsage.input +
932
+ turn.lastUsage.cache_read +
933
+ turn.lastUsage.cache_write,
934
+ ...(window === undefined ? {} : { window }),
935
+ };
936
+ const base = {
937
+ type: "result" as const,
938
+ sessionId: final.session_id,
939
+ usage: counts,
940
+ cost: hasModel ? { micros: Math.round(finite(final.total_cost_usd) * 1e6), quality } : null,
941
+ finalMessage: text,
942
+ model: names[0] ?? null,
943
+ ...(context === undefined ? {} : { context }),
944
+ };
945
+ if (turn.continued) {
946
+ return {
947
+ line: {
948
+ ...base,
949
+ result: "failed",
950
+ reason: "model_error",
951
+ message:
952
+ "claude went on after its result: a second session started by itself (something it ran in the background finished); a run is one turn",
953
+ },
954
+ code: EXIT_FAILED,
955
+ };
956
+ }
957
+ const errors =
958
+ "errors" in final && Array.isArray(final.errors)
959
+ ? final.errors.filter((e): e is string => typeof e === "string")
960
+ : [];
961
+ if (final.subtype === "success" && !final.is_error) {
962
+ // A reply with no text and no usage never reached the model, as a local
963
+ // command does. The reason is kept for the chat's failure line.
964
+ const emptyText = text === null || text.trim().length === 0;
965
+ const noUsage =
966
+ !hasModel &&
967
+ counts.input === 0 &&
968
+ counts.output === 0 &&
969
+ counts.cache_read === 0 &&
970
+ counts.cache_write === 0 &&
971
+ finite(final.total_cost_usd) === 0;
972
+ const reason = emptyText && noUsage ? noAnswerReason(final, errors) : undefined;
973
+ return {
974
+ line: { ...base, result: "done", ...(reason === undefined ? {} : { message: reason }) },
975
+ code: 0,
976
+ };
977
+ }
978
+ const message =
979
+ turn.modelError?.message ??
980
+ (errors.length > 0
981
+ ? errors.join("; ")
982
+ : text !== null && text.length > 0
983
+ ? text
984
+ : `claude stopped: ${final.subtype}`);
985
+ const reason: FailureReason = isSessionMissing(message) ? "session_missing" : "model_error";
986
+ return {
987
+ line: {
988
+ ...base,
989
+ result: "failed",
990
+ reason,
991
+ message,
992
+ ...(turn.modelError !== undefined ? { modelError: turn.modelError } : {}),
993
+ },
994
+ code: EXIT_FAILED,
995
+ };
996
+ }
317
997
 
318
- // The blocks of the response being streamed, by their index. A block's end
319
- // line is written from the finished assistant message, which carries the
320
- // whole text even when the stream gave only a summary.
321
- const streamBlocks = new Map<number, { readonly kind: StreamKind; text: string }>();
322
- const streamEvent = (value: unknown): void => {
998
+ private writeLine(turn: Turn, line: WorkerLine): void {
999
+ turn.increments.flush("text", false);
1000
+ turn.increments.flush("thinking", false);
1001
+ turn.io.line(line);
1002
+ }
1003
+
1004
+ private streamEvent(turn: Turn, value: unknown): void {
323
1005
  const event = recordOf(value);
324
1006
  if (event === undefined) return;
325
1007
  const type = stringOf(event["type"]);
@@ -330,16 +1012,16 @@ export async function runWorker(
330
1012
  const blockType = stringOf(block["type"]);
331
1013
  if (blockType === "text") {
332
1014
  const text = stringOf(block["text"]) ?? "";
333
- streamBlocks.set(index, { kind: "text", text });
334
- addDelta("text", text);
1015
+ turn.streamBlocks.set(index, { kind: "text", text });
1016
+ turn.increments.text(text);
335
1017
  } else if (blockType === "thinking") {
336
1018
  const text = stringOf(block["thinking"]) ?? "";
337
- streamBlocks.set(index, { kind: "thinking", text });
338
- addDelta("thinking", text);
1019
+ turn.streamBlocks.set(index, { kind: "thinking", text });
1020
+ turn.increments.thinking(text);
339
1021
  }
340
1022
  } else if (type === "content_block_delta") {
341
1023
  const index = numberOf(event["index"]);
342
- const block = index === undefined ? undefined : streamBlocks.get(index);
1024
+ const block = index === undefined ? undefined : turn.streamBlocks.get(index);
343
1025
  const delta = recordOf(event["delta"]);
344
1026
  if (block === undefined || delta === undefined) return;
345
1027
  const deltaType = stringOf(delta["type"]);
@@ -347,96 +1029,39 @@ export async function runWorker(
347
1029
  const text = stringOf(delta["text"]);
348
1030
  if (text !== undefined) {
349
1031
  block.text += text;
350
- addDelta("text", text);
1032
+ turn.increments.text(text);
351
1033
  }
352
1034
  } else if (block.kind === "thinking" && deltaType === "thinking_delta") {
353
1035
  const text = stringOf(delta["thinking"]);
354
1036
  if (text !== undefined) {
355
1037
  block.text += text;
356
- addDelta("thinking", text);
1038
+ turn.increments.thinking(text);
357
1039
  }
358
1040
  }
359
1041
  } else if (type === "content_block_stop") {
360
1042
  const index = numberOf(event["index"]);
361
- if (index !== undefined && streamBlocks.delete(index)) flushDelta(true);
362
- }
363
- };
364
- const writeEnd = (kind: StreamKind, text: string): void => {
365
- if (text.length === 0) return;
366
- io.line({ type: kind === "text" ? "text_end" : "thinking_end", text: maskSecrets(text, secrets) });
367
- };
368
-
369
- // Tool calls that have started and not ended; a refused call ends here too,
370
- // so the host never sees a call stay open.
371
- const open = new Map<string, { readonly name: string; readonly startedAt: number }>();
372
- // The same translation `decideAccess` uses, so a tool the summary does not
373
- // know by name (NotebookEdit, MultiEdit) is still judged as its access-match tool.
374
- const deniedByProfile = (name: string, toolInput: unknown): { readonly rule?: string } | undefined => {
375
- const record = typeof toolInput === "object" && toolInput !== null ? (toolInput as Record<string, unknown>) : {};
376
- const translated = translate(name, record);
377
- if (translated.kind === "inert") return undefined;
378
- if (translated.kind === "mapped") {
379
- const verdict = match(profile, { tool: translated.tool, input: translated.input, cwd: input.cwd });
380
- // A call that asks is not refused: it is shown as itself.
381
- if (verdict.allow || verdict.ask === true) return undefined;
382
- return verdict.rule === undefined ? {} : { rule: verdict.rule };
383
- }
384
- return hasRules(profile) ? {} : undefined;
385
- };
386
- const startCall = (id: string, name: string, toolInput: unknown): void => {
387
- if (open.has(id)) return;
388
- const startedAt = now();
389
- open.set(id, { name, startedAt });
390
- const denied = deniedByProfile(name, toolInput);
391
- const summary = denied !== undefined
392
- ? `${name} denied by the access profile${denied.rule === undefined ? "" : ` (rule: ${denied.rule.replace(/\s+/g, " ").slice(0, 300)})`}`
393
- : summarizeCall(profile, name, toolInput, input.cwd, { secrets: input.secretValues, keepLines: true });
394
- writeLine({
395
- type: "tool_execution_start",
396
- toolCallId: id,
397
- toolName: name,
398
- at: startedAt,
399
- ...(summary === undefined ? {} : { input: summary }),
400
- });
401
- };
402
- const endCall = (id: string, name: string, isError: boolean, error?: unknown, output?: unknown): void => {
403
- const call = open.get(id);
404
- if (call === undefined) return;
405
- open.delete(id);
406
- const text = isError ? undefined : toolOutputText(output);
407
- if (text !== undefined && text.length > 0) {
408
- for (const part of toolOutputLines(text, secrets)) {
409
- writeLine({ type: "tool_output", toolCallId: id, text: part.text });
1043
+ const block = index === undefined ? undefined : turn.streamBlocks.get(index);
1044
+ if (index !== undefined && block !== undefined) {
1045
+ turn.streamBlocks.delete(index);
1046
+ turn.increments.flush(block.kind, true);
410
1047
  }
411
1048
  }
412
- const firstLine = isError ? firstErrorLine(error, { secrets: input.secretValues }) : undefined;
413
- writeLine({
414
- type: "tool_execution_end",
415
- toolCallId: id,
416
- toolName: name,
417
- isError,
418
- durationMs: Math.max(0, now() - call.startedAt),
419
- ...(firstLine === undefined ? {} : { error: firstLine }),
420
- });
421
- };
422
- const toolHook =
423
- (kind: "start" | "end" | "failed"): HookCallback =>
424
- async (event) => {
425
- if (event.hook_event_name === "PreToolUse" && kind === "start") {
426
- startCall(event.tool_use_id, event.tool_name, event.tool_input);
427
- } else if (event.hook_event_name === "PostToolUse" && kind === "end") {
428
- endCall(event.tool_use_id, event.tool_name, false, undefined, event.tool_response);
429
- } else if (event.hook_event_name === "PostToolUseFailure" && kind === "failed") {
430
- endCall(event.tool_use_id, event.tool_name, true, event.error);
431
- }
432
- return {};
433
- };
1049
+ }
434
1050
 
435
- // The only permission surface (`permissionMode: 'default'` sends every call
436
- // that is not already allowed here). A refusal goes to the model as the
437
- // tool's result and the run goes on; the call is closed for the host.
438
- const canUseTool: CanUseTool = async (toolName, toolInput, options) => {
1051
+ private writeEnd(turn: Turn, kind: StreamKind, text: string): void {
1052
+ if (text.length === 0) return;
1053
+ turn.io.line({ type: kind === "text" ? "text_end" : "thinking_end", text: maskSecrets(text, this.secrets) });
1054
+ }
1055
+
1056
+ private readonly canUseTool: CanUseTool = async (toolName, toolInput, options) => {
1057
+ const turn = this.turn;
1058
+ if (turn === undefined) return { behavior: "deny", message: "no reply is running" };
1059
+ const input = turn.input;
1060
+ const io = turn.io;
1061
+ const profile = liveAccess(turn.profile);
439
1062
  io.log(`canUseTool ${toolName}`);
1063
+ if (toolName === ASK_QUESTION_TOOL) return this.askQuestion(turn, toolInput, options);
1064
+ if (toolName === EXIT_PLAN_MODE_TOOL) return this.reviewPlan(turn, toolInput, options);
440
1065
  const askHost = io.ask;
441
1066
  const verdict = await decideAccess(
442
1067
  profile,
@@ -447,362 +1072,337 @@ export async function runWorker(
447
1072
  askHost === undefined
448
1073
  ? undefined
449
1074
  : async (question) => {
450
- // A value that holds a secret is never asked about: no fact may hold it.
451
1075
  if ((input.secretValues ?? []).some((secret) => secret.length > 0 && question.value.includes(secret))) {
452
1076
  return { decision: "deny", reason: "the call holds a secret value, so nobody is asked about it" };
453
1077
  }
454
- const shown = summarizeCall(profile, toolName, toolInput, input.cwd, { secrets: input.secretValues });
455
- return askHost({ ...question, shown: shown ?? question.value, session: sessionId });
1078
+ const shown = summarizeCall(profile, toolName, toolInput, input.cwd, {
1079
+ secrets: input.secretValues,
1080
+ forQuestion: true,
1081
+ });
1082
+ return askHost({ ...question, shown: shown ?? question.value, session: this.sessionId });
456
1083
  },
457
1084
  );
458
1085
  if (verdict.allow) return { behavior: "allow", updatedInput: toolInput };
459
1086
  if (verdict.stop === true) {
460
- // The wait ended: the host ends this program next. Hold the call until it does.
461
1087
  await new Promise<void>((resolve) => {
462
- if (controller.signal.aborted) resolve();
463
- controller.signal.addEventListener("abort", () => resolve(), { once: true });
1088
+ if (this.controller.signal.aborted) resolve();
1089
+ this.controller.signal.addEventListener("abort", () => resolve(), { once: true });
464
1090
  });
465
- endCall(options.toolUseID, toolName, true, REFUSED_IN_LOG);
1091
+ this.endCall(turn, options.toolUseID, toolName, true, REFUSED_IN_LOG);
466
1092
  return { behavior: "deny", message: verdict.reason, interrupt: true };
467
1093
  }
468
- writeLine({ type: "blocked", toolName, reason: REFUSED_IN_LOG });
469
- endCall(options.toolUseID, toolName, true, REFUSED_IN_LOG);
1094
+ this.writeLine(turn, { type: "blocked", toolName, reason: REFUSED_IN_LOG });
1095
+ this.endCall(turn, options.toolUseID, toolName, true, REFUSED_IN_LOG);
470
1096
  return { behavior: "deny", message: verdict.reason };
471
1097
  };
472
1098
 
473
- // Operad's tools: the program that serves them on stdio, started by claude.
474
- const operadServer =
475
- input.operadTools === undefined
476
- ? undefined
477
- : {
478
- type: "stdio" as const,
479
- command: serverCommand(input.operadTools).command,
480
- args: [...serverCommand(input.operadTools).args],
481
- env: { OPERAD_HOME: input.operadTools.home },
482
- };
483
- const stderrTail: string[] = [];
484
- const options: Options = {
485
- cwd: input.cwd,
486
- pathToClaudeCodeExecutable: executable,
487
- settingSources: [],
488
- permissionMode: "default",
489
- permissionPrompts: "host",
490
- includePartialMessages: true,
491
- systemPrompt: { type: "preset", preset: "claude_code" },
492
- canUseTool,
493
- abortController: controller,
494
- disallowedTools: [...DISALLOWED_TOOLS],
495
- env: {
496
- ...(hooks.env ?? process.env),
497
- ...ISOLATION_ENV,
498
- // Both limits, so a gate runs in the foreground instead of being moved on.
499
- BASH_DEFAULT_TIMEOUT_MS: String((input.bashTimeoutSecs ?? DEFAULT_BASH_TIMEOUT_SECS) * 1000),
500
- BASH_MAX_TIMEOUT_MS: String((input.bashTimeoutSecs ?? DEFAULT_BASH_TIMEOUT_SECS) * 1000),
501
- },
502
- hooks: {
503
- PreToolUse: [{ hooks: [toolHook("start")] }],
504
- PostToolUse: [{ hooks: [toolHook("end")] }],
505
- PostToolUseFailure: [{ hooks: [toolHook("failed")] }],
506
- },
507
- stderr: (data) => {
508
- io.log(data.trimEnd());
509
- for (const text of data.split("\n")) if (text.trim().length > 0) stderrTail.push(text.trim());
510
- if (stderrTail.length > 5) stderrTail.splice(0, stderrTail.length - 5);
511
- },
512
- ...(operadServer === undefined && input.mcpServers === undefined
513
- ? {}
514
- : {
515
- mcpServers: {
516
- ...(operadServer === undefined ? {} : { [OPERAD_SERVER]: operadServer }),
517
- // A bot's servers: each is started behind its guard, which holds the secrets.
518
- ...Object.fromEntries(
519
- Object.entries(input.mcpServers ?? {}).map(([name, server]) => [
520
- name,
521
- { type: "stdio" as const, command: server.command, args: [...server.args] },
522
- ]),
523
- ),
524
- },
525
- }),
526
- ...(input.resumeSession !== undefined ? { resume: input.resumeSession } : {}),
527
- ...(input.model !== undefined ? { model: input.model } : {}),
528
- ...(input.effort !== undefined ? { effort: input.effort } : {}),
529
- ...(input.maxTurns !== undefined ? { maxTurns: input.maxTurns } : {}),
530
- ...(input.budgetUsd !== undefined ? { maxBudgetUsd: input.budgetUsd } : {}),
531
- ...(hooks.spawnClaudeCodeProcess !== undefined ? { spawnClaudeCodeProcess: hooks.spawnClaudeCodeProcess } : {}),
532
- };
533
-
534
- let sessionId: string | null = null;
535
- let modelError: WorkerModelError | undefined;
536
- let final: Extract<SDKMessage, { type: "result" }> | undefined;
537
- const seenMessages = new Set<string>();
538
- let thrown: string | undefined;
539
- let continued = false;
540
-
541
- // Images go with the prompt as one user message of text and image blocks.
542
- const images = input.images ?? [];
543
- const first = (async function* () {
544
- const blocks = await Promise.all(images.map((image) => readImage(image)));
545
- yield {
546
- type: "user" as const,
547
- message: {
548
- role: "user" as const,
549
- content: [
550
- { type: "text" as const, text: input.prompt },
551
- ...blocks.map((block) => ({
552
- type: "image" as const,
553
- source: { type: "base64" as const, media_type: block.mediaType, data: block.data },
554
- })),
555
- ],
556
- },
557
- parent_tool_use_id: null,
558
- };
559
- })();
560
- const session = query({ prompt: images.length === 0 ? input.prompt : first, options });
561
- // A message the host sends mid-run goes to claude as one more user turn,
562
- // queued behind the tool call that is running.
563
- io.onMessage?.((text) => {
564
- const turn = (async function* () {
565
- yield {
566
- type: "user" as const,
567
- message: { role: "user" as const, content: text },
568
- parent_tool_use_id: null,
569
- priority: "next" as const,
570
- };
571
- })();
572
- session.streamInput(turn).catch((error: unknown) => {
573
- io.log(`a message to claude was not delivered: ${error instanceof Error ? error.message : String(error)}`);
574
- });
575
- });
576
- const account = session.initializationResult().then(
577
- (init) => init.account,
578
- () => undefined,
579
- );
580
-
581
- try {
582
- messages: for await (const message of session) {
583
- if ("session_id" in message && typeof message.session_id === "string") sessionId = message.session_id;
584
- switch (message.type) {
585
- case "system":
586
- if (message.subtype === "init" && final !== undefined) {
587
- // claude went on by itself after the result (something it started
588
- // finished). A run is one turn: stop here and say so.
589
- io.log("a second session started after the result; stopping");
590
- continued = true;
591
- break messages;
592
- }
593
- if (message.subtype === "init") {
594
- io.log(`claude ${message.claude_code_version}`);
595
- writeLine({
596
- type: "session",
597
- claudeVersion: message.claude_code_version,
598
- apiKeySource: message.apiKeySource,
599
- model: message.model,
600
- });
601
- }
602
- break;
603
- case "stream_event": {
604
- streamEvent(message.event);
605
- break;
606
- }
607
- case "assistant": {
608
- flushDelta(true);
609
- const texts: string[] = [];
610
- for (const block of message.message.content) {
611
- if (block.type === "text") texts.push(block.text);
612
- else if (block.type === "thinking") writeEnd("thinking", block.thinking);
613
- }
614
- if (texts.length > 0) writeEnd("text", texts.join(""));
615
-
616
- const id = message.message.id;
617
- if (seenMessages.has(id)) break;
618
- seenMessages.add(id);
619
- const said = messageSummary(
620
- message.message.content
621
- .map((block) => (block.type === "text" ? block.text : ""))
622
- .join(" "),
623
- );
624
- io.line({
625
- type: "message_end",
626
- role: "assistant",
627
- ...(said === undefined ? {} : { text: said }),
628
- stopReason: message.message.stop_reason,
629
- usage: usageOf(message.message.usage),
630
- cost: null,
631
- });
632
- break;
633
- }
634
- case "rate_limit_event": {
635
- const info = message.rate_limit_info;
636
- const rateLimitType = info.rateLimitType ?? null;
637
- const resetsAt = info.resetsAt ?? null;
638
- writeLine({ type: "rate_limit", status: info.status, rateLimitType, resetsAt });
639
- if (info.status === "rejected") {
640
- modelError = {
641
- kind: "usage_limit",
642
- message: `usage limit reached${rateLimitType === null ? "" : ` (${rateLimitType})`}`,
643
- rateLimitType,
644
- resetsAt,
645
- };
646
- }
647
- break;
1099
+ /**
1100
+ * The agent's own question, as a form the person fills in (ADR 0026 D6). The
1101
+ * answers go back as the `answers` claude's tool reads, keyed by question
1102
+ * text; a skipped question is reported as such only when this claude takes
1103
+ * that field.
1104
+ */
1105
+ private async askQuestion(
1106
+ turn: Turn,
1107
+ toolInput: unknown,
1108
+ options: { readonly toolUseID: string; readonly signal: AbortSignal },
1109
+ ): Promise<Awaited<ReturnType<CanUseTool>>> {
1110
+ const io = turn.io;
1111
+ const raw = claudeQuestions(toolInput);
1112
+ const questions = raw === undefined ? [] : askQuestions(raw);
1113
+ if (questions.length === 0) {
1114
+ return { behavior: "deny", message: `the ${ASK_QUESTION_TOOL} call named no question a person can answer` };
1115
+ }
1116
+ if (io.askForm === undefined) {
1117
+ return { behavior: "deny", message: "this host cannot put a question to a person" };
1118
+ }
1119
+ const shown = JSON.stringify(questions);
1120
+ if (this.secrets.some((secret) => secret.length > 0 && shown.includes(secret))) {
1121
+ return { behavior: "deny", message: "the question holds a secret value, so nobody is asked about it" };
1122
+ }
1123
+ let got;
1124
+ try {
1125
+ got = await io.askForm({ questions, session: this.sessionId });
1126
+ } catch {
1127
+ return { behavior: "deny", message: "the question could not be asked" };
1128
+ }
1129
+ if (got.decision === "stop") {
1130
+ // The grace passed: the host ends this program, and the answer comes
1131
+ // back to a resumed session as text.
1132
+ await new Promise<void>((resolve) => {
1133
+ if (this.controller.signal.aborted) resolve();
1134
+ this.controller.signal.addEventListener("abort", () => resolve(), { once: true });
1135
+ });
1136
+ this.endCall(turn, options.toolUseID, ASK_QUESTION_TOOL, true, REFUSED_IN_LOG);
1137
+ return { behavior: "deny", message: "waiting for an answer", interrupt: true };
1138
+ }
1139
+ if (got.decision === "rejected") {
1140
+ this.writeLine(turn, { type: "blocked", toolName: ASK_QUESTION_TOOL, reason: REFUSED_IN_LOG });
1141
+ this.endCall(turn, options.toolUseID, ASK_QUESTION_TOOL, true, REFUSED_IN_LOG);
1142
+ return { behavior: "deny", message: "nobody answered the questions in time" };
1143
+ }
1144
+ const answers: Record<string, string> = {};
1145
+ const annotations: Record<string, { readonly unanswered: "skipped" }> = {};
1146
+ // claude keys its answers by the question's own text, and the share form
1147
+ // trims an id or suffixes a duplicate one; the raw text is still the key.
1148
+ const keys = raw?.map((question) => question.id) ?? [];
1149
+ for (const [index, question] of questions.entries()) {
1150
+ const key = keys[index] ?? question.id;
1151
+ const answer = answerFor(got.answers, question.id);
1152
+ if (isSkipped(answer)) {
1153
+ answers[key] = "";
1154
+ if (this.capabilities.has(UNANSWERED_CAPABILITY)) {
1155
+ annotations[key] = { unanswered: "skipped" };
648
1156
  }
649
- case "result":
650
- final = message;
651
- break;
652
- default:
653
- break;
1157
+ continue;
654
1158
  }
1159
+ answers[key] = answerText(answer);
655
1160
  }
656
- } catch (error) {
657
- if (!cancelled) {
658
- thrown = error instanceof Error ? error.message : String(error);
659
- if (stderrTail.length > 0) thrown = `${thrown}\n${stderrTail.join("\n")}`;
660
- }
661
- } finally {
662
- cancel.removeEventListener("abort", onCancel);
663
- session.close();
664
- }
665
-
666
- // Every way this run ends writes its Result here: text still held back as a
667
- // possible secret prefix is released first (masked if it is a whole secret),
668
- // so a cancelled or failed partial reply does not lose its last characters.
669
- const finish = (line: WorkerResult, code: number): number => {
670
- flushDelta(true);
671
- io.line(line);
672
- return code;
673
- };
674
-
675
- if (cancelled) {
676
- return finish(
677
- {
678
- type: "result",
679
- result: "cancelled",
680
- sessionId,
681
- usage: {},
682
- cost: null,
683
- finalMessage: null,
684
- model: null,
1161
+ return {
1162
+ behavior: "allow",
1163
+ updatedInput: {
1164
+ ...(recordOf(toolInput) ?? {}),
1165
+ answers,
1166
+ ...(Object.keys(annotations).length === 0 ? {} : { annotations }),
685
1167
  },
686
- EXIT_CANCELLED,
687
- );
1168
+ };
688
1169
  }
689
1170
 
690
- if (final === undefined) {
691
- const message = thrown ?? "claude ended without a result";
692
- return finish(
693
- { ...failure(isSessionMissing(message) ? "session_missing" : "model_error", message), sessionId },
694
- EXIT_FAILED,
695
- );
1171
+ /**
1172
+ * The plan claude is ready to carry out, put to the person before plan mode
1173
+ * ends. Approving lets the tool run as it did before, so claude itself leaves
1174
+ * plan mode; asking for changes refuses the call with the person's note and
1175
+ * ends the reply, so the next message can say what to change.
1176
+ */
1177
+ private async reviewPlan(
1178
+ turn: Turn,
1179
+ toolInput: Record<string, unknown>,
1180
+ options: { readonly toolUseID: string; readonly signal: AbortSignal },
1181
+ ): Promise<Awaited<ReturnType<CanUseTool>>> {
1182
+ const io = turn.io;
1183
+ const review = planReview(toolInput);
1184
+ if (review === undefined) {
1185
+ return {
1186
+ behavior: "deny",
1187
+ message: "the plan was empty; write the plan and call ExitPlanMode with it in the plan argument",
1188
+ };
1189
+ }
1190
+ const questions = planQuestions(review);
1191
+ if (io.askForm === undefined) {
1192
+ return { behavior: "deny", message: "this host cannot put a plan to a person" };
1193
+ }
1194
+ const shown = JSON.stringify(review);
1195
+ if (this.secrets.some((secret) => secret.length > 0 && shown.includes(secret))) {
1196
+ return { behavior: "deny", message: "the plan holds a secret value, so nobody is asked about it" };
1197
+ }
1198
+ let got;
1199
+ try {
1200
+ got = await io.askForm({ questions, session: this.sessionId });
1201
+ } catch {
1202
+ return { behavior: "deny", message: "the plan could not be put to a person" };
1203
+ }
1204
+ if (got.decision === "stop") {
1205
+ // The grace passed: the host ends this program, and the answer comes
1206
+ // back to a resumed session as text.
1207
+ await new Promise<void>((resolve) => {
1208
+ if (this.controller.signal.aborted) resolve();
1209
+ this.controller.signal.addEventListener("abort", () => resolve(), { once: true });
1210
+ });
1211
+ this.endCall(turn, options.toolUseID, EXIT_PLAN_MODE_TOOL, true, REFUSED_IN_LOG);
1212
+ return { behavior: "deny", message: "waiting for a plan review", interrupt: true };
1213
+ }
1214
+ if (got.decision === "rejected") {
1215
+ this.writeLine(turn, { type: "blocked", toolName: EXIT_PLAN_MODE_TOOL, reason: REFUSED_IN_LOG });
1216
+ this.endCall(turn, options.toolUseID, EXIT_PLAN_MODE_TOOL, true, REFUSED_IN_LOG);
1217
+ return { behavior: "deny", message: "nobody reviewed the plan in time" };
1218
+ }
1219
+ const answer = answerFor(got.answers, PLAN_QUESTION_ID);
1220
+ const choice = answer?.choices?.[0];
1221
+ if (choice === PLAN_APPROVE && answer?.skipped !== true) {
1222
+ return { behavior: "allow", updatedInput: toolInput };
1223
+ }
1224
+ const note = got.note === undefined || got.note.trim().length === 0 ? undefined : got.note.trim();
1225
+ this.writeLine(turn, { type: "blocked", toolName: EXIT_PLAN_MODE_TOOL, reason: REFUSED_IN_LOG });
1226
+ this.endCall(turn, options.toolUseID, EXIT_PLAN_MODE_TOOL, true, REFUSED_IN_LOG);
1227
+ return {
1228
+ behavior: "deny",
1229
+ message: note ?? "The person asked for changes to the plan.",
1230
+ interrupt: true,
1231
+ };
696
1232
  }
697
1233
 
698
- const info = await account;
699
- const quality: CostQuality =
700
- info?.subscriptionType !== undefined && info.subscriptionType.length > 0 ? "estimated" : "exact";
701
- const counts = usageOf(final.usage);
702
- const text = "result" in final && typeof final.result === "string" ? final.result : null;
703
- const names = Object.keys(final.modelUsage ?? {});
704
- const hasModel = names.length > 0;
705
- const base = {
706
- type: "result",
707
- sessionId: final.session_id,
708
- usage: counts,
709
- // A run that used no model (a session that would not load) has no cost to
710
- // call exact or estimated.
711
- cost: hasModel ? { micros: Math.round(finite(final.total_cost_usd) * 1e6), quality } : null,
712
- finalMessage: text,
713
- model: names[0] ?? null,
714
- } as const;
715
-
716
- if (continued) {
717
- return finish(
718
- {
719
- ...base,
720
- result: "failed",
721
- reason: "model_error",
722
- message:
723
- "claude went on after its result: a second session started by itself (something it ran in the background finished); a run is one turn",
724
- },
725
- EXIT_FAILED,
726
- );
1234
+ private deniedByProfile(turn: Turn, name: string, toolInput: unknown): { readonly rule?: string } | undefined {
1235
+ const record = typeof toolInput === "object" && toolInput !== null ? (toolInput as Record<string, unknown>) : {};
1236
+ const check = checkProfile(liveAccess(turn.profile), name, record, turn.input.cwd);
1237
+ if (check.kind !== "refuse") return undefined;
1238
+ return check.rule === undefined ? {} : { rule: check.rule };
727
1239
  }
728
- if (final.subtype === "success" && !final.is_error) {
729
- return finish({ ...base, result: "done" }, 0);
730
- }
731
- // An error result carries its text in `errors` (an unknown session says
732
- // "No conversation found with session ID: ..."); a success-shaped one in `result`.
733
- const errors = "errors" in final && Array.isArray(final.errors) ? final.errors.filter((e) => typeof e === "string") : [];
734
- const message =
735
- modelError?.message ??
736
- (errors.length > 0
737
- ? errors.join("; ")
738
- : text !== null && text.length > 0
739
- ? text
740
- : `claude stopped: ${final.subtype}`);
741
- const reason: FailureReason = isSessionMissing(message) ? "session_missing" : "model_error";
742
- return finish(
743
- {
744
- ...base,
745
- result: "failed",
746
- reason,
747
- message,
748
- ...(modelError !== undefined ? { modelError } : {}),
749
- },
750
- EXIT_FAILED,
751
- );
752
- }
753
1240
 
754
- /**
755
- * Stdin as lines. The first line (or all of stdin when it has no newline) is the
756
- * input; later lines are the host's answers.
757
- */
758
- class StdinLines {
759
- readonly #reader: AsyncIterator<Uint8Array>;
760
- readonly #decoder = new TextDecoder();
761
- #buffer = "";
762
- #done = false;
1241
+ // The profile's refusals for the `PreToolUse` hook. A read-only profile asks
1242
+ // in `canUseTool` so a person can answer, but with the owner's settings on it
1243
+ // is also a refusal that no user allow rule may pass: `{ readOnly: true }`
1244
+ // through the same matcher says whether read-only is what stops the call.
1245
+ private hookRefusal(turn: Turn, name: string, toolInput: unknown): { readonly reason: string } | undefined {
1246
+ const record = typeof toolInput === "object" && toolInput !== null ? (toolInput as Record<string, unknown>) : {};
1247
+ const profile = liveAccess(turn.profile);
1248
+ const check = checkProfile(profile, name, record, turn.input.cwd);
1249
+ if (check.kind === "refuse") return { reason: check.reason };
1250
+ if (profile.readOnly === true) {
1251
+ const alone = checkProfile({ readOnly: true }, name, record, turn.input.cwd);
1252
+ if (alone.kind !== "allow") return { reason: alone.reason };
1253
+ }
1254
+ return undefined;
1255
+ }
763
1256
 
764
- constructor(stream: AsyncIterable<Uint8Array>) {
765
- this.#reader = stream[Symbol.asyncIterator]();
1257
+ private startCall(turn: Turn, id: string, name: string, toolInput: unknown): void {
1258
+ if (turn.open.has(id)) return;
1259
+ const startedAt = this.now();
1260
+ turn.open.set(id, { name, startedAt });
1261
+ const denied = this.deniedByProfile(turn, name, toolInput);
1262
+ const summary = denied !== undefined
1263
+ ? `${name} denied by the access profile${denied.rule === undefined ? "" : ` (rule: ${denied.rule.replace(/\s+/g, " ").slice(0, 300)})`}`
1264
+ : summarizeCall(liveAccess(turn.profile), name, toolInput, turn.input.cwd, {
1265
+ secrets: turn.input.secretValues,
1266
+ keepLines: true,
1267
+ });
1268
+ this.writeLine(turn, {
1269
+ type: "tool_execution_start",
1270
+ toolCallId: id,
1271
+ toolName: name,
1272
+ at: startedAt,
1273
+ ...(summary === undefined ? {} : { input: summary }),
1274
+ });
766
1275
  }
767
1276
 
768
- /** Stops reading; a read that waits ends as if stdin had ended. */
769
- close(): void {
770
- void this.#reader.return?.()?.catch(() => undefined);
771
- }
772
-
773
- async #more(): Promise<boolean> {
774
- if (this.#done) return false;
775
- const chunk = await this.#reader.next();
776
- if (chunk.done) {
777
- this.#done = true;
778
- this.#buffer += this.#decoder.decode();
779
- return false;
780
- }
781
- this.#buffer += this.#decoder.decode(chunk.value, { stream: true });
782
- return true;
783
- }
784
-
785
- /** The next line, or what is left at the end of stdin; undefined when nothing is. */
786
- async next(): Promise<string | undefined> {
787
- for (;;) {
788
- const newline = this.#buffer.indexOf("\n");
789
- if (newline !== -1) {
790
- const line = this.#buffer.slice(0, newline);
791
- this.#buffer = this.#buffer.slice(newline + 1);
792
- if (line.trim().length === 0) continue;
793
- return line;
1277
+ private endCall(turn: Turn, id: string, name: string, isError: boolean, error?: unknown, output?: unknown): void {
1278
+ const call = turn.open.get(id);
1279
+ if (call === undefined) return;
1280
+ turn.open.delete(id);
1281
+ const text = isError ? undefined : toolOutputText(output);
1282
+ if (text !== undefined && text.length > 0) {
1283
+ for (const part of toolOutputLines(text, this.secrets)) {
1284
+ this.writeLine(turn, { type: "tool_output", toolCallId: id, text: part.text });
794
1285
  }
795
- if (!(await this.#more())) {
796
- const rest = this.#buffer;
797
- this.#buffer = "";
798
- return rest.trim().length === 0 ? undefined : rest;
1286
+ }
1287
+ const firstLine = isError ? firstErrorLine(error, { secrets: turn.input.secretValues }) : undefined;
1288
+ this.writeLine(turn, {
1289
+ type: "tool_execution_end",
1290
+ toolCallId: id,
1291
+ toolName: name,
1292
+ isError,
1293
+ durationMs: Math.max(0, this.now() - call.startedAt),
1294
+ ...(firstLine === undefined ? {} : { error: firstLine }),
1295
+ });
1296
+ }
1297
+
1298
+ private toolHook(kind: "start" | "end" | "failed"): HookCallback {
1299
+ return async (event) => {
1300
+ const turn = this.turn;
1301
+ if (turn === undefined) return {};
1302
+ if (event.hook_event_name === "PreToolUse" && kind === "start") {
1303
+ this.startCall(turn, event.tool_use_id, event.tool_name, event.tool_input);
1304
+ // A bot that loads the owner's settings may have an allow rule there.
1305
+ // The profile is judged first, in this hook, so no such rule can let a
1306
+ // call through that it refuses. A grant or an ask is not a refusal and
1307
+ // stays with `canUseTool`.
1308
+ if (turn.input.useOwnSettings === true) {
1309
+ const refusal = this.hookRefusal(turn, event.tool_name, event.tool_input);
1310
+ if (refusal !== undefined) {
1311
+ this.writeLine(turn, { type: "blocked", toolName: event.tool_name, reason: REFUSED_IN_LOG });
1312
+ this.endCall(turn, event.tool_use_id, event.tool_name, true, REFUSED_IN_LOG);
1313
+ return {
1314
+ hookSpecificOutput: {
1315
+ hookEventName: "PreToolUse",
1316
+ permissionDecision: "deny",
1317
+ permissionDecisionReason: refusal.reason,
1318
+ },
1319
+ };
1320
+ }
1321
+ }
1322
+ } else if (event.hook_event_name === "PostToolUse" && kind === "end") {
1323
+ this.endCall(turn, event.tool_use_id, event.tool_name, false, undefined, event.tool_response);
1324
+ } else if (event.hook_event_name === "PostToolUseFailure" && kind === "failed") {
1325
+ this.endCall(turn, event.tool_use_id, event.tool_name, true, event.error);
799
1326
  }
1327
+ return {};
1328
+ };
1329
+ }
1330
+
1331
+ private removeSkillPlugin(): void {
1332
+ if (this.skillPlugin !== undefined) rmSync(this.skillPlugin.dir, { recursive: true, force: true });
1333
+ }
1334
+
1335
+ /** Ends the session and removes what the kept worker mounted. */
1336
+ close(): void {
1337
+ if (this.closed) return;
1338
+ this.closed = true;
1339
+ try {
1340
+ this.session?.close();
1341
+ } catch {
1342
+ // A session that already ended has nothing left to close.
800
1343
  }
1344
+ this.queue?.close();
1345
+ this.removeSkillPlugin();
801
1346
  }
1347
+ }
802
1348
 
803
- async first(): Promise<string> {
804
- return (await this.next()) ?? "";
1349
+ /** Runs one prompt through a session that ends after it, the plain worker path. */
1350
+ export async function runWorker(
1351
+ input: WorkerInput,
1352
+ io: WorkerIo,
1353
+ cancel: AbortSignal,
1354
+ hooks: WorkerHooks = {},
1355
+ ): Promise<number> {
1356
+ let executable = "claude";
1357
+ if (hooks.spawnClaudeCodeProcess === undefined) {
1358
+ try {
1359
+ executable = findClaude(input.command);
1360
+ } catch (error) {
1361
+ io.line(failure("model_error", messageOf(error)));
1362
+ return EXIT_FAILED;
1363
+ }
805
1364
  }
1365
+ const session = new ClaudeSession(
1366
+ { ...input, command: input.command ?? executable },
1367
+ io,
1368
+ cancel,
1369
+ hooks,
1370
+ false,
1371
+ );
1372
+ return session.first();
1373
+ }
1374
+
1375
+ /** The adapter the shared worker process calls for claude's program. */
1376
+ function claudeAdapter(hooks: WorkerHooks): WorkerAdapter<WorkerInput> {
1377
+ let current: ClaudeSession | undefined;
1378
+ let session: string | null = null;
1379
+ return {
1380
+ parse: (text) => decodeWorkerInput(text, parseInput),
1381
+ invalidInput: (message) => failure("invalid_input", message),
1382
+ error: (message) => failure("model_error", message),
1383
+ keep: (input) => input.keep,
1384
+ session: () => session,
1385
+ setSession: (next) => {
1386
+ session = next;
1387
+ },
1388
+ onEnded: (handler) => current?.onEnded(handler),
1389
+ async run(input, io, cancel) {
1390
+ if (current !== undefined) {
1391
+ const code = await current.next(input, io as WorkerIo, cancel);
1392
+ session = current.currentSession();
1393
+ return code;
1394
+ }
1395
+ const started = new ClaudeSession(input, io as WorkerIo, cancel, hooks, input.keep !== undefined);
1396
+ current = started;
1397
+ const code = await started.first();
1398
+ session = started.currentSession();
1399
+ return code;
1400
+ },
1401
+ close: () => {
1402
+ current?.close();
1403
+ current = undefined;
1404
+ },
1405
+ };
806
1406
  }
807
1407
 
808
1408
  /**
@@ -816,144 +1416,26 @@ export async function serveWorker(
816
1416
  cancel: AbortSignal,
817
1417
  hooks: WorkerHooks = {},
818
1418
  ): Promise<number> {
819
- const write = ports.write;
820
- const stdin = new StdinLines(stdinStream);
821
- const waiting = new Map<number, (used: boolean) => void>();
822
- const questions = new Map<number, (answer: CallAnswer) => void>();
823
- let nextAsk = 1;
824
- const early: string[] = [];
825
- let onMessage: ((text: string) => void) | undefined;
826
- let nextGrant = 1;
827
- let hostGone = false;
828
- const io: WorkerIo = {
829
- line: (line) => write(`${JSON.stringify(line)}\n`),
830
- onMessage: (handler) => {
831
- onMessage = handler;
832
- for (const text of early.splice(0)) handler(text);
833
- },
834
- log: (text) => ports.log(text),
835
- useGrant: (waitId) =>
836
- new Promise<boolean>((resolve) => {
837
- if (hostGone) {
838
- resolve(false);
839
- return;
840
- }
841
- const id = nextGrant;
842
- nextGrant += 1;
843
- waiting.set(id, resolve);
844
- write(`${JSON.stringify({ type: "grant_use", id, waitId })}\n`);
845
- }),
846
- ask: (call) =>
847
- new Promise<CallAnswer>((resolve) => {
848
- if (hostGone) {
849
- resolve({ decision: "deny", reason: "the host is gone" });
850
- return;
851
- }
852
- const id = nextAsk;
853
- nextAsk += 1;
854
- questions.set(id, (answer) => {
855
- // The line that closes the question, so the host's stall timer runs again.
856
- write(`${JSON.stringify({ type: "ask_resolved", id })}\n`);
857
- resolve(answer);
858
- });
859
- write(`${JSON.stringify({ type: "ask_call", id, ...call })}\n`);
860
- }),
861
- };
862
- let code: number;
863
- try {
864
- const text = await stdin.first();
865
- let decoded: unknown;
866
- let parsedOk = true;
867
- try {
868
- decoded = JSON.parse(text);
869
- } catch {
870
- parsedOk = false;
871
- }
872
- const parsed = parsedOk ? parseInput(decoded) : ({ ok: false, message: "the input is not valid JSON" } as const);
873
- if (!parsed.ok) {
874
- io.line(failure("invalid_input", parsed.message));
875
- code = EXIT_INVALID_INPUT;
876
- } else {
877
- // Later stdin lines answer `grant_use` lines.
878
- void (async () => {
879
- for (;;) {
880
- const line = await stdin.next();
881
- if (line === undefined) break;
882
- const said = messageText(line);
883
- if (said !== undefined) {
884
- if (onMessage === undefined) early.push(said);
885
- else onMessage(said);
886
- continue;
887
- }
888
- try {
889
- const ack: unknown = JSON.parse(line);
890
- if (typeof ack === "object" && ack !== null && Reflect.get(ack, "type") === "ask_ack") {
891
- const id: unknown = Reflect.get(ack, "id");
892
- const decision: unknown = Reflect.get(ack, "decision");
893
- const reason: unknown = Reflect.get(ack, "reason");
894
- if (typeof id === "number") {
895
- questions.get(id)?.({
896
- decision: decision === "allow" || decision === "stop" ? decision : "deny",
897
- ...(typeof reason === "string" ? { reason } : {}),
898
- });
899
- questions.delete(id);
900
- }
901
- }
902
- if (typeof ack === "object" && ack !== null && Reflect.get(ack, "type") === "grant_ack") {
903
- const id: unknown = Reflect.get(ack, "id");
904
- const used: unknown = Reflect.get(ack, "used");
905
- if (typeof id === "number") {
906
- waiting.get(id)?.(used === true);
907
- waiting.delete(id);
908
- }
909
- }
910
- } catch {
911
- // Not a line the program understands; it is ignored.
912
- }
913
- }
914
- // The host is gone: nothing more will be granted.
915
- hostGone = true;
916
- for (const resolve of waiting.values()) resolve(false);
917
- waiting.clear();
918
- for (const resolve of questions.values()) resolve({ decision: "deny", reason: "the host is gone" });
919
- questions.clear();
920
- })();
921
- code = await runWorker(parsed.input, io, cancel, hooks);
922
- }
923
- } catch (error) {
924
- io.log(error instanceof Error ? (error.stack ?? error.message) : String(error));
925
- io.line(failure("model_error", error instanceof Error ? error.message : String(error)));
926
- code = EXIT_FAILED;
927
- }
928
- stdin.close();
929
- return code;
1419
+ return serveOne(stdinStream, ports, cancel, claudeAdapter(hooks));
1420
+ }
1421
+
1422
+ /**
1423
+ * Runs the first reply from stdin and, when the reply was done and asked for
1424
+ * keeping, serves later replies from a socket in the operad home. The same
1425
+ * `claude` session serves them too, so neither process starts again.
1426
+ */
1427
+ export async function serveWorkerProcess(
1428
+ stdinStream: AsyncIterable<Uint8Array>,
1429
+ ports: WorkerPorts,
1430
+ cancel: AbortSignal,
1431
+ hooks: WorkerHooks = {},
1432
+ ): Promise<number> {
1433
+ return serveKeptWorker(stdinStream, ports, cancel, claudeAdapter(hooks));
930
1434
  }
931
1435
 
932
1436
  /** The process entry: stdin in, stdout lines out, exit code out. */
933
1437
  export async function main(hooks: WorkerHooks = {}): Promise<never> {
934
- const flush = (): Promise<void> =>
935
- new Promise((resolve) => {
936
- process.stdout.write("", () => resolve());
937
- });
938
- // Anything that prints to stdout by accident would corrupt the protocol.
939
- console.log = (...args: unknown[]): void => {
940
- process.stderr.write(`${args.map(String).join(" ")}\n`);
941
- };
942
- const controller = new AbortController();
943
- process.on("SIGTERM", () => controller.abort());
944
- const code = await serveWorker(
945
- Bun.stdin.stream(),
946
- {
947
- write: (text) => {
948
- process.stdout.write(text);
949
- },
950
- log: (text) => process.stderr.write(`${text}\n`),
951
- },
952
- controller.signal,
953
- hooks,
954
- );
955
- await flush();
956
- process.exit(code);
1438
+ return runWorkerMain(claudeAdapter(hooks));
957
1439
  }
958
1440
 
959
1441
  if (import.meta.main) await main();