@operad-io/harness-pi 0.1.1 → 0.2.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
@@ -5,29 +5,44 @@
5
5
  * object per line to stdout, the last a Result. `README.md` holds the tables.
6
6
  */
7
7
 
8
+ import { messageOf } from "@operad-io/engine";
8
9
  import { existsSync, mkdirSync } from "node:fs";
9
10
  import {
10
11
  findGrant,
11
12
  firstErrorLine,
12
13
  REFUSED_IN_LOG,
14
+ liveAccess,
13
15
  match,
14
16
  messageSummary,
15
17
  readProfile,
16
18
  summarizeCall,
17
19
  type AccessProfile,
20
+ type Verdict,
18
21
  } from "@operad-io/access-match";
19
22
  import type {
20
23
  AgentSessionEvent,
24
+ DefaultResourceLoader as PiResourceLoader,
21
25
  ExtensionFactory,
22
26
  ModelRuntime,
23
27
  } from "@earendil-works/pi-coding-agent";
24
28
  import { openMcpTools, type McpTools } from "@operad-io/mcp";
25
29
  import {
30
+ EXIT_CANCELLED,
31
+ EXIT_FAILED,
32
+ EXIT_INVALID_INPUT,
33
+ Increments,
26
34
  maskSecrets,
27
- messageText,
35
+ readGivenSkills,
28
36
  readImage,
37
+ decodeWorkerInput,
38
+ runWorkerMain,
39
+ serveKeptWorker,
40
+ serveOne,
29
41
  toolOutputLines,
30
42
  type CallAnswer,
43
+ type WorkerAdapter,
44
+ type WorkerIo as SharedWorkerIo,
45
+ type WorkerPorts,
31
46
  } from "@operad-io/harness-process";
32
47
  import { findPi, loadPi } from "./pi-install.ts";
33
48
  import {
@@ -51,37 +66,29 @@ export function boundedTimeout(requested: unknown, limitSecs: number): number |
51
66
  return undefined;
52
67
  }
53
68
 
54
- export const EXIT_FAILED = 1;
55
- export const EXIT_INVALID_INPUT = 2;
56
- export const EXIT_CANCELLED = 143;
69
+ export { EXIT_CANCELLED, EXIT_FAILED, EXIT_INVALID_INPUT };
57
70
 
58
71
  /** Where the program writes. Lines are written whole, in order. */
59
- export interface WorkerIo {
60
- line(line: WorkerLine): void;
61
- /** Free text for humans; never parsed. */
62
- log(text: string): void;
63
- /**
64
- * Asks the host to use up a one-time permission. True when it did and the
65
- * call may run. Absent when the host cannot answer; no grant then applies.
66
- */
67
- useGrant?(waitId: string): Promise<boolean>;
68
- /**
69
- * Asks the host to ask a person whether one call may run, and resolves with
70
- * the answer. Absent when the host cannot answer; a call that must ask is then
71
- * refused.
72
- */
73
- ask?(call: {
74
- readonly kind: "command" | "path";
75
- readonly value: string;
76
- readonly tool?: string;
77
- readonly shown: string;
78
- readonly session: string | null;
79
- }): Promise<CallAnswer>;
80
- /**
81
- * Hands each message the host sends mid-run to `handler`, those that came
82
- * before the call first. Absent when the host cannot send any.
83
- */
84
- onMessage?(handler: (text: string) => void): void;
72
+ export type WorkerIo = SharedWorkerIo<WorkerLine>;
73
+
74
+ /** What a run gives pi's settings and resource loader; the tests inspect it. */
75
+ export interface SeenResources {
76
+ readonly settings: {
77
+ readonly compaction: boolean;
78
+ readonly retry: boolean;
79
+ };
80
+ readonly loader: {
81
+ readonly cwd: string;
82
+ readonly agentDir: string;
83
+ readonly noExtensions: boolean | undefined;
84
+ readonly noSkills: boolean | undefined;
85
+ readonly noPromptTemplates: boolean | undefined;
86
+ readonly noThemes: boolean | undefined;
87
+ readonly noContextFiles: boolean | undefined;
88
+ readonly additionalSkillPaths: readonly string[] | undefined;
89
+ readonly hasSkillsOverride: boolean;
90
+ readonly extensions: readonly string[];
91
+ };
85
92
  }
86
93
 
87
94
  export interface WorkerHooks {
@@ -89,12 +96,8 @@ export interface WorkerHooks {
89
96
  registerProviders?(runtime: ModelRuntime): void;
90
97
  /** The clock for tool call times, in epoch milliseconds; the tests inject one. */
91
98
  now?: () => number;
92
- }
93
-
94
- /** Where the program talks to the world; the process entry points them at stdout and stderr. */
95
- export interface WorkerPorts {
96
- write(text: string): void;
97
- log(text: string): void;
99
+ /** Sees the settings and loader options of one run; the tests use it. */
100
+ observeResources?(seen: SeenResources): void;
98
101
  }
99
102
 
100
103
  /** The text of an assistant message, thinking and tool calls left out. */
@@ -129,6 +132,7 @@ class Tally {
129
132
  #unpriced = 0;
130
133
  lastStop: string | undefined;
131
134
  lastError: string | undefined;
135
+ lastUsage: Required<WorkerUsage> | undefined;
132
136
 
133
137
  add(message: Extract<AgentSessionEvent, { type: "message_end" }>["message"]): WorkerLine | undefined {
134
138
  if (message.role !== "assistant") return undefined;
@@ -142,6 +146,7 @@ class Tally {
142
146
  for (const key of ["input", "output", "cache_read", "cache_write"] as const) {
143
147
  this.usage[key] = (this.usage[key] ?? 0) + counts[key];
144
148
  }
149
+ this.lastUsage = counts;
145
150
  const price = priceOf(usage);
146
151
  if (price === null) this.#unpriced += 1;
147
152
  else {
@@ -149,6 +154,7 @@ class Tally {
149
154
  this.#total += price;
150
155
  }
151
156
  this.lastStop = message.stopReason;
157
+ // A later success clears the earlier failed attempt: only the last message decides the run.
152
158
  this.lastError = message.stopReason === "error" ? (message.errorMessage ?? "the model failed") : undefined;
153
159
  const said = messageSummary(textOf(message.content));
154
160
  return {
@@ -172,133 +178,6 @@ class Tally {
172
178
  }
173
179
  }
174
180
 
175
- /** How often one stream writes an increment line at most, in milliseconds. */
176
- const FLUSH_MS = 100;
177
-
178
- /** The spellings `maskSecrets` masks for one value: the value and, if it differs, its JSON text. */
179
- function spellingsOf(secret: string): readonly string[] {
180
- if (secret.length === 0) return [];
181
- const escaped = JSON.stringify(secret).slice(1, -1);
182
- return escaped === secret ? [secret] : [secret, escaped];
183
- }
184
-
185
- /**
186
- * Splits an increment so that no line ends inside a secret: the longest suffix
187
- * of `text` that is a proper prefix of a secret value is held back and joined
188
- * to the next increment, where the completed secret is masked. A secret that
189
- * is wholly in the emitted part is masked there. Both the value as written and
190
- * its JSON-escaped spelling count, as `maskSecrets` masks both.
191
- */
192
- function splitSecretPrefix(
193
- text: string,
194
- secrets: readonly string[],
195
- ): { readonly emit: string; readonly held: string } {
196
- let held = 0;
197
- for (const secret of secrets.flatMap(spellingsOf)) {
198
- const longest = Math.min(secret.length - 1, text.length);
199
- for (let length = longest; length > held; length -= 1) {
200
- if (text.endsWith(secret.slice(0, length))) {
201
- held = length;
202
- break;
203
- }
204
- }
205
- }
206
- if (held === 0) return { emit: text, held: "" };
207
- return { emit: text.slice(0, text.length - held), held: text.slice(text.length - held) };
208
- }
209
-
210
- /**
211
- * Assistant text and thinking as they stream. A line carries the new text
212
- * only, and each stream writes at most one per `FLUSH_MS`: a message that
213
- * arrives faster is grouped. The tail that is still buffered when a block or a
214
- * message ends is left to the full line that follows (`text_end`,
215
- * `thinking_end`), so no increment goes out closer than `FLUSH_MS` to the one
216
- * before it. Secret values are masked in every line.
217
- */
218
- class Increments {
219
- #text = "";
220
- #thinking = "";
221
- #textAt: number | undefined;
222
- #thinkingAt: number | undefined;
223
-
224
- constructor(
225
- private readonly io: WorkerIo,
226
- private readonly now: () => number,
227
- private readonly secrets: readonly string[],
228
- ) {}
229
-
230
- text(delta: string): void {
231
- if (delta.length === 0) return;
232
- this.#text += delta;
233
- const at = this.now();
234
- if (this.#textAt === undefined || at - this.#textAt >= FLUSH_MS) this.#writeText(at);
235
- }
236
-
237
- thinking(delta: string): void {
238
- if (delta.length === 0) return;
239
- this.#thinking += delta;
240
- const at = this.now();
241
- if (this.#thinkingAt === undefined || at - this.#thinkingAt >= FLUSH_MS) this.#writeThinking(at);
242
- }
243
-
244
- #writeText(at: number): void {
245
- const { emit, held } = splitSecretPrefix(this.#text, this.secrets);
246
- if (emit.length > 0) {
247
- this.io.line({ type: "text_delta", text: maskSecrets(emit, this.secrets) });
248
- }
249
- this.#text = held;
250
- this.#textAt = at;
251
- }
252
-
253
- #writeThinking(at: number): void {
254
- const { emit, held } = splitSecretPrefix(this.#thinking, this.secrets);
255
- if (emit.length > 0) {
256
- this.io.line({ type: "thinking_delta", text: maskSecrets(emit, this.secrets) });
257
- }
258
- this.#thinking = held;
259
- this.#thinkingAt = at;
260
- }
261
-
262
- /** A thinking block finished: its full text follows the increments. */
263
- endThinking(text: string): void {
264
- this.#thinking = "";
265
- this.#thinkingAt = undefined;
266
- if (text.length > 0) this.io.line({ type: "thinking_end", text: maskSecrets(text, this.secrets) });
267
- }
268
-
269
- /** An assistant message finished: its full text follows the increments. */
270
- endMessage(text: string): void {
271
- if (text.length > 0) {
272
- this.#text = "";
273
- this.#textAt = undefined;
274
- this.io.line({ type: "text_end", text: maskSecrets(text, this.secrets) });
275
- } else if (this.#text.length > 0) {
276
- this.#writeText(this.now());
277
- }
278
- // A thinking block that ended wrote its own full text; anything left is
279
- // a block the run stopped in, and the increments are all it has.
280
- if (this.#thinking.length > 0) this.#writeThinking(this.now());
281
- }
282
-
283
- /**
284
- * The stream is ending and no later text can complete a held prefix: write
285
- * it now, masked when it holds a whole secret. Every end path calls this
286
- * before its Result, so a stopped reply keeps what it had reached.
287
- */
288
- release(): void {
289
- if (this.#text.length > 0) {
290
- this.io.line({ type: "text_delta", text: maskSecrets(this.#text, this.secrets) });
291
- this.#text = "";
292
- this.#textAt = undefined;
293
- }
294
- if (this.#thinking.length > 0) {
295
- this.io.line({ type: "thinking_delta", text: maskSecrets(this.#thinking, this.secrets) });
296
- this.#thinking = "";
297
- this.#thinkingAt = undefined;
298
- }
299
- }
300
- }
301
-
302
181
  function failure(reason: FailureReason, message: string): WorkerResult {
303
182
  return { type: "result", result: "failed", sessionId: null, usage: {}, cost: null, finalMessage: null, reason, message };
304
183
  }
@@ -318,18 +197,38 @@ export async function runWorker(
318
197
  return EXIT_FAILED;
319
198
  }
320
199
 
321
- // pi is the user's own install: found at start, never bundled.
200
+ // A line for the step log and for the free-text stderr: a skill that cannot
201
+ // be used is skipped, never a failed run.
202
+ const note = (text: string): void => {
203
+ io.log(text);
204
+ io.line({ type: "log", text });
205
+ };
206
+ const given = readGivenSkills(input.skills ?? []);
207
+ for (const skip of given.skipped) note(`skill ${skip.path}: ${skip.reason}`);
208
+
209
+ // pi is the user's own install, or the one operad put in the home: found at
210
+ // start, never imported into the hub.
322
211
  let pi: Awaited<ReturnType<typeof loadPi>>;
323
212
  try {
324
- const install = findPi(input.piCommand);
213
+ const install = findPi(input.piCommand, {
214
+ ...(input.piHome === undefined ? {} : { home: input.piHome }),
215
+ });
325
216
  io.log(`pi ${install.version} loaded from ${install.dir}`);
326
217
  pi = await loadPi(install);
327
218
  } catch (error) {
328
- const message = error instanceof Error ? error.message : String(error);
219
+ const message = messageOf(error);
329
220
  io.line(failure("model_error", message));
330
221
  return EXIT_FAILED;
331
222
  }
332
- const { createAgentSession, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager } = pi;
223
+ const {
224
+ createAgentSession,
225
+ DefaultResourceLoader,
226
+ ModelRuntime,
227
+ SessionManager,
228
+ SettingsManager,
229
+ getAgentDir,
230
+ loadSkills,
231
+ } = pi;
333
232
 
334
233
  mkdirSync(input.agentDir, { recursive: true });
335
234
  mkdirSync(input.sessionDir, { recursive: true });
@@ -360,8 +259,54 @@ export async function runWorker(
360
259
  // matcher; a refusal blocks the call and the agent goes on.
361
260
  const bashTimeoutSecs = input.bashTimeoutSecs ?? DEFAULT_BASH_TIMEOUT_SECS;
362
261
  const access = readProfile(input.access ?? {});
363
- const profile: AccessProfile = access.ok ? access.profile : {};
262
+ const startProfile: AccessProfile = access.ok ? access.profile : {};
263
+ // A chat writes its live level beside the profile; reading it per call lets a
264
+ // change reach a reply that is already running, including a lowering.
265
+ const currentProfile = (): AccessProfile => liveAccess(startProfile);
364
266
  const blockedCalls = new Set<string>();
267
+ const ownSettings = input.useOwnSettings === true;
268
+ // Operad's own tools, by the names they take in pi; they are not the owner's
269
+ // to override and the profile leaves them to the MCP allow lists.
270
+ const operadToolNames = new Set<string>();
271
+ // The fields the access matcher reads for pi's own tools. A tool it cannot
272
+ // place is refused while a rule is set: an extension's tool would otherwise
273
+ // run a command or touch a path the profile never saw.
274
+ const TOOL_FIELDS: Readonly<Record<string, { readonly field: "command" | "path"; readonly required: boolean }>> = {
275
+ bash: { field: "command", required: true },
276
+ read: { field: "path", required: true },
277
+ write: { field: "path", required: true },
278
+ edit: { field: "path", required: true },
279
+ grep: { field: "path", required: false },
280
+ find: { field: "path", required: false },
281
+ ls: { field: "path", required: false },
282
+ };
283
+ const hasProfileRules = (candidate: AccessProfile): boolean =>
284
+ (candidate.denyPaths ?? []).length > 0 ||
285
+ (candidate.denyCommands ?? []).length > 0 ||
286
+ (candidate.askCommands ?? []).length > 0 ||
287
+ (candidate.askPaths ?? []).length > 0 ||
288
+ candidate.readOnly === true ||
289
+ (candidate.level !== undefined && candidate.level !== "full");
290
+ const judge = (profile: AccessProfile, name: string, toolInput: Readonly<Record<string, unknown>>): Verdict => {
291
+ if (operadToolNames.has(name)) return { allow: true };
292
+ const row = TOOL_FIELDS[name];
293
+ if (row === undefined) {
294
+ return ownSettings && hasProfileRules(profile)
295
+ ? {
296
+ allow: false,
297
+ reason: `tool "${name}" is not one the access profile can check; it is refused while the profile has rules`,
298
+ }
299
+ : { allow: true };
300
+ }
301
+ const value = row.field === "command" ? toolInput["command"] : toolInput["path"] ?? toolInput["file_path"];
302
+ if (ownSettings && row.required && (typeof value !== "string" || value.length === 0) && hasProfileRules(profile)) {
303
+ return {
304
+ allow: false,
305
+ reason: `tool "${name}" has no ${row.field}; it is refused while the profile has rules`,
306
+ };
307
+ }
308
+ return match(profile, { tool: name, input: toolInput, cwd: input.cwd });
309
+ };
365
310
  // What a late answer continues; known once the session exists.
366
311
  let sessionFile: string | null = null;
367
312
  const operadExtension: ExtensionFactory = (pi) => {
@@ -372,7 +317,8 @@ export async function runWorker(
372
317
  const bounded = boundedTimeout(Reflect.get(event.input, "timeout"), bashTimeoutSecs);
373
318
  if (bounded !== undefined) Reflect.set(event.input, "timeout", bounded);
374
319
  }
375
- const verdict = match(profile, { tool: event.toolName, input: event.input, cwd: input.cwd });
320
+ const profile = currentProfile();
321
+ const verdict = judge(profile, event.toolName, event.input);
376
322
  if (verdict.allow) return undefined;
377
323
  // A one-time permission covers one exact call that would be refused. The
378
324
  // host writes the fact before it answers, so a crash after it cannot
@@ -397,9 +343,12 @@ export async function runWorker(
397
343
  // A value that holds a secret is never asked about: no fact may hold it.
398
344
  answer = { decision: "deny", reason: "the call holds a secret value, so nobody is asked about it" };
399
345
  } else {
400
- const shown = summarizeCall(profile, event.toolName, event.input, input.cwd, { secrets: input.secretValues });
346
+ const shown = summarizeCall(profile, event.toolName, event.input, input.cwd, {
347
+ secrets: input.secretValues,
348
+ forQuestion: true,
349
+ });
401
350
  try {
402
- answer = await io.ask({ kind: verdict.kind, value: verdict.value, ...(verdict.tool === undefined ? {} : { tool: verdict.tool }), shown: shown ?? verdict.value, session: sessionFile });
351
+ answer = await io.ask({ kind: verdict.kind, value: verdict.value, ...(verdict.tool === undefined ? {} : { tool: verdict.tool }), ...(verdict.outward === undefined ? {} : { outward: verdict.outward }), shown: shown ?? verdict.value, session: sessionFile });
403
352
  } catch {
404
353
  answer = { decision: "deny", reason: "the question could not be asked" };
405
354
  }
@@ -422,22 +371,93 @@ export async function runWorker(
422
371
  });
423
372
  };
424
373
 
425
- const settingsManager = SettingsManager.inMemory({
426
- compaction: { enabled: false },
427
- retry: { enabled: false },
428
- });
429
- const resourceLoader = new DefaultResourceLoader({
430
- cwd: input.cwd,
431
- agentDir: input.agentDir,
432
- settingsManager,
433
- noExtensions: true,
434
- noSkills: true,
435
- noPromptTemplates: true,
436
- noThemes: true,
437
- noContextFiles: true,
438
- extensionFactories: [{ name: "operad", factory: operadExtension, hidden: true }],
439
- });
374
+ // With the switch off the child is exactly the one it always was. With it
375
+ // on, pi's own settings and resources load from the owner's pi directory;
376
+ // the project is not trusted here, so only the owner's user layer and the
377
+ // context files pi finds from the working directory load.
378
+ const ownerAgentDir = ownSettings ? getAgentDir() : undefined;
379
+ const retry = input.retry === true;
380
+ const settingsManager =
381
+ ownerAgentDir === undefined
382
+ ? SettingsManager.inMemory({
383
+ compaction: { enabled: false },
384
+ retry: { enabled: retry },
385
+ })
386
+ : SettingsManager.create(input.cwd, ownerAgentDir, { projectTrusted: false });
387
+ const givenSkills =
388
+ ownerAgentDir === undefined || given.skills.length === 0
389
+ ? undefined
390
+ : loadSkills({
391
+ cwd: input.cwd,
392
+ agentDir: ownerAgentDir,
393
+ skillPaths: given.skills.map((skill) => skill.path),
394
+ includeDefaults: false,
395
+ });
396
+ const extensionFactories = [{ name: "operad", factory: operadExtension, hidden: true }];
397
+ type LoaderOptions = ConstructorParameters<typeof PiResourceLoader>[0];
398
+ const loaderOptions: LoaderOptions =
399
+ ownerAgentDir === undefined
400
+ ? {
401
+ cwd: input.cwd,
402
+ agentDir: input.agentDir,
403
+ settingsManager,
404
+ noExtensions: true,
405
+ // No discovery: the only skills are the directories this step gave.
406
+ noSkills: true,
407
+ ...(given.skills.length === 0 ? {} : { additionalSkillPaths: given.skills.map((skill) => skill.path) }),
408
+ noPromptTemplates: true,
409
+ noThemes: true,
410
+ noContextFiles: true,
411
+ extensionFactories,
412
+ }
413
+ : {
414
+ cwd: input.cwd,
415
+ agentDir: ownerAgentDir,
416
+ settingsManager,
417
+ extensionFactories,
418
+ // A skill the bot lists wins a name clash with the owner's.
419
+ ...(givenSkills === undefined
420
+ ? {}
421
+ : {
422
+ skillsOverride: (base) => {
423
+ const names = new Set(givenSkills.skills.map((skill) => skill.name));
424
+ return {
425
+ skills: [...givenSkills.skills, ...base.skills.filter((skill) => !names.has(skill.name))],
426
+ diagnostics: [...givenSkills.diagnostics, ...base.diagnostics],
427
+ };
428
+ },
429
+ }),
430
+ };
431
+ const resourceLoader = new DefaultResourceLoader(loaderOptions);
440
432
  await resourceLoader.reload();
433
+ // A chat's compaction and retry are operad's, not the owner's settings'. A
434
+ // chat turns retry on; a task keeps it off, and the owner's other retry
435
+ // values (attempts and delays) still apply when the switch is on.
436
+ settingsManager.applyOverrides({ compaction: { enabled: false }, retry: { enabled: retry } });
437
+ const isolation = ownerAgentDir === undefined;
438
+ hooks.observeResources?.({
439
+ settings: {
440
+ compaction: settingsManager.getCompactionEnabled(),
441
+ retry: settingsManager.getRetryEnabled(),
442
+ },
443
+ loader: {
444
+ cwd: loaderOptions.cwd,
445
+ agentDir: loaderOptions.agentDir,
446
+ noExtensions: isolation ? true : undefined,
447
+ noSkills: isolation ? true : undefined,
448
+ noPromptTemplates: isolation ? true : undefined,
449
+ noThemes: isolation ? true : undefined,
450
+ noContextFiles: isolation ? true : undefined,
451
+ additionalSkillPaths:
452
+ isolation && given.skills.length > 0 ? given.skills.map((skill) => skill.path) : undefined,
453
+ hasSkillsOverride: !isolation && givenSkills !== undefined,
454
+ extensions: extensionFactories.map((entry) => entry.name),
455
+ },
456
+ });
457
+ if ((input.skills ?? []).length > 0) {
458
+ const names = resourceLoader.getSkills().skills.map((skill) => skill.name);
459
+ note(`skills: ${names.length === 0 ? "none" : names.join(", ")}`);
460
+ }
441
461
 
442
462
  // Operad's tools, as pi's own custom tools; each call runs against the home.
443
463
  let operad: McpTools | undefined;
@@ -452,19 +472,23 @@ export async function runWorker(
452
472
  const customTools =
453
473
  mcp === undefined
454
474
  ? undefined
455
- : mcp.tools.map((tool) => ({
456
- name: `operad_${tool.name}`,
457
- label: `operad ${tool.name}`,
458
- description: tool.description,
459
- // The same JSON Schema the MCP server states; pi checks arguments against it.
460
- parameters: { ...tool.inputSchema },
461
- async execute(_id: string, params: Record<string, unknown>) {
462
- const outcome = await mcp.call(tool.name, params);
463
- const text = outcome.content.map((block) => block.text).join("\n");
464
- if (outcome.isError === true) throw new Error(text);
465
- return { content: [{ type: "text" as const, text }], details: outcome.structuredContent ?? {} };
466
- },
467
- }));
475
+ : mcp.tools.map((tool) => {
476
+ const name = `operad_${tool.name}`;
477
+ operadToolNames.add(name);
478
+ return {
479
+ name,
480
+ label: `operad ${tool.name}`,
481
+ description: tool.description,
482
+ // The same JSON Schema the MCP server states; pi checks arguments against it.
483
+ parameters: { ...tool.inputSchema },
484
+ async execute(_id: string, params: Record<string, unknown>) {
485
+ const outcome = await mcp.call(tool.name, params);
486
+ const text = outcome.content.map((block) => block.text).join("\n");
487
+ if (outcome.isError === true) throw new Error(text);
488
+ return { content: [{ type: "text" as const, text }], details: outcome.structuredContent ?? {} };
489
+ },
490
+ };
491
+ });
468
492
 
469
493
  const { session } = await createAgentSession({
470
494
  ...(customTools === undefined ? {} : { customTools }),
@@ -512,10 +536,23 @@ export async function runWorker(
512
536
  if (line !== undefined) io.line(line);
513
537
  break;
514
538
  }
539
+ case "auto_retry_start": {
540
+ io.line({
541
+ type: "retry_start",
542
+ attempt: event.attempt,
543
+ maxAttempts: event.maxAttempts,
544
+ delayMs: event.delayMs,
545
+ reason: maskSecrets(event.errorMessage || "the model request failed", input.secretValues ?? []),
546
+ });
547
+ break;
548
+ }
549
+ case "auto_retry_end":
550
+ io.line({ type: "retry_end", success: event.success });
551
+ break;
515
552
  case "tool_execution_start": {
516
553
  const startedAt = now();
517
554
  started.set(event.toolCallId, startedAt);
518
- const summary = summarizeCall(profile, event.toolName, event.args, input.cwd, { secrets: input.secretValues, keepLines: true });
555
+ const summary = summarizeCall(currentProfile(), event.toolName, event.args, input.cwd, { secrets: input.secretValues, keepLines: true });
519
556
  io.line({
520
557
  type: "tool_execution_start",
521
558
  toolCallId: event.toolCallId,
@@ -574,6 +611,19 @@ export async function runWorker(
574
611
  usage: tally.usage,
575
612
  cost: tally.cost,
576
613
  finalMessage: session.getLastAssistantText() ?? null,
614
+ ...(tally.lastUsage === undefined
615
+ ? {}
616
+ : {
617
+ context: {
618
+ used:
619
+ tally.lastUsage.input +
620
+ tally.lastUsage.cache_read +
621
+ tally.lastUsage.cache_write,
622
+ ...(model?.contextWindow !== undefined && model.contextWindow > 0
623
+ ? { window: model.contextWindow }
624
+ : {}),
625
+ },
626
+ }),
577
627
  });
578
628
 
579
629
  // Every way this run ends writes its Result here: text still held back as a
@@ -588,8 +638,8 @@ export async function runWorker(
588
638
  // the tool call that is running.
589
639
  io.onMessage?.((text) => {
590
640
  io.log("a message from the host is given to pi");
591
- session.prompt(text, { streamingBehavior: "steer" }).catch((error: unknown) => {
592
- io.log(`a message to pi was not delivered: ${error instanceof Error ? error.message : String(error)}`);
641
+ session.prompt(text, { streamingBehavior: "steer", expandPromptTemplates: false }).catch((error: unknown) => {
642
+ io.log(`a message to pi was not delivered: ${messageOf(error)}`);
593
643
  });
594
644
  });
595
645
 
@@ -600,21 +650,30 @@ export async function runWorker(
600
650
  };
601
651
  cancel.addEventListener("abort", onCancel, { once: true });
602
652
 
653
+ // The session is ready and the prompt is about to go to the model.
654
+ io.line({
655
+ type: "session",
656
+ sessionId: session.sessionFile ?? null,
657
+ ...(input.model === undefined ? {} : { model: input.model }),
658
+ });
659
+
603
660
  try {
604
661
  if (!cancelled) {
605
662
  try {
606
663
  const images = await Promise.all((input.images ?? []).map((image) => readImage(image)));
607
- await session.prompt(
608
- input.prompt,
609
- images.length === 0
610
- ? undefined
611
- : { images: images.map((image) => ({ type: "image" as const, data: image.data, mimeType: image.mediaType })) },
612
- );
664
+ // The prompt is operad's text, not a line at pi's terminal: a leading
665
+ // `/` is never one of pi's commands or a prompt template.
666
+ await session.prompt(input.prompt, {
667
+ expandPromptTemplates: false,
668
+ ...(images.length === 0
669
+ ? {}
670
+ : { images: images.map((image) => ({ type: "image" as const, data: image.data, mimeType: image.mediaType })) }),
671
+ });
613
672
  } catch (error) {
614
673
  if (!cancelled) {
615
674
  return finish(
616
675
  {
617
- ...failure("model_error", error instanceof Error ? error.message : String(error)),
676
+ ...failure("model_error", messageOf(error)),
618
677
  sessionId: session.sessionFile ?? null,
619
678
  usage: tally.usage,
620
679
  cost: tally.cost,
@@ -648,58 +707,20 @@ export async function runWorker(
648
707
  }
649
708
  }
650
709
 
651
- /**
652
- * Stdin as lines. The first line (or all of stdin when it has no newline) is the
653
- * input; later lines are the host's answers.
654
- */
655
- class StdinLines {
656
- readonly #reader: AsyncIterator<Uint8Array>;
657
- readonly #decoder = new TextDecoder();
658
- #buffer = "";
659
- #done = false;
660
-
661
- constructor(stream: AsyncIterable<Uint8Array>) {
662
- this.#reader = stream[Symbol.asyncIterator]();
663
- }
664
-
665
- /** Stops reading; a read that waits ends as if stdin had ended. */
666
- close(): void {
667
- void this.#reader.return?.()?.catch(() => undefined);
668
- }
669
-
670
- async #more(): Promise<boolean> {
671
- if (this.#done) return false;
672
- const chunk = await this.#reader.next();
673
- if (chunk.done) {
674
- this.#done = true;
675
- this.#buffer += this.#decoder.decode();
676
- return false;
677
- }
678
- this.#buffer += this.#decoder.decode(chunk.value, { stream: true });
679
- return true;
680
- }
681
-
682
- /** The next line, or what is left at the end of stdin; undefined when nothing is. */
683
- async next(): Promise<string | undefined> {
684
- for (;;) {
685
- const newline = this.#buffer.indexOf("\n");
686
- if (newline !== -1) {
687
- const line = this.#buffer.slice(0, newline);
688
- this.#buffer = this.#buffer.slice(newline + 1);
689
- if (line.trim().length === 0) continue;
690
- return line;
691
- }
692
- if (!(await this.#more())) {
693
- const rest = this.#buffer;
694
- this.#buffer = "";
695
- return rest.trim().length === 0 ? undefined : rest;
696
- }
697
- }
698
- }
699
-
700
- async first(): Promise<string> {
701
- return (await this.next()) ?? "";
702
- }
710
+ /** The adapter the shared worker process calls for pi's program. */
711
+ function piAdapter(hooks: WorkerHooks): WorkerAdapter<WorkerInput> {
712
+ let session: string | null = null;
713
+ return {
714
+ parse: (text) => decodeWorkerInput(text, parseInput),
715
+ invalidInput: (message) => failure("invalid_input", message),
716
+ error: (message) => failure("model_error", message),
717
+ keep: (input) => input.keep,
718
+ session: () => session,
719
+ setSession: (next) => {
720
+ session = next;
721
+ },
722
+ run: (input, io, cancel) => runWorker(input, io as WorkerIo, cancel, hooks),
723
+ };
703
724
  }
704
725
 
705
726
  /**
@@ -713,151 +734,32 @@ export async function serveWorker(
713
734
  cancel: AbortSignal,
714
735
  hooks: WorkerHooks = {},
715
736
  ): Promise<number> {
716
- const write = ports.write;
717
- const stdin = new StdinLines(stdinStream);
718
- const waiting = new Map<number, (used: boolean) => void>();
719
- const questions = new Map<number, (answer: CallAnswer) => void>();
720
- let nextAsk = 1;
721
- const early: string[] = [];
722
- let onMessage: ((text: string) => void) | undefined;
723
- let nextGrant = 1;
724
- let hostGone = false;
725
- const io: WorkerIo = {
726
- line: (line) => write(`${JSON.stringify(line)}\n`),
727
- onMessage: (handler) => {
728
- onMessage = handler;
729
- for (const text of early.splice(0)) handler(text);
730
- },
731
- log: (text) => ports.log(text),
732
- useGrant: (waitId) =>
733
- new Promise<boolean>((resolve) => {
734
- if (hostGone) {
735
- resolve(false);
736
- return;
737
- }
738
- const id = nextGrant;
739
- nextGrant += 1;
740
- waiting.set(id, resolve);
741
- write(`${JSON.stringify({ type: "grant_use", id, waitId })}\n`);
742
- }),
743
- ask: (call) =>
744
- new Promise<CallAnswer>((resolve) => {
745
- if (hostGone) {
746
- resolve({ decision: "deny", reason: "the host is gone" });
747
- return;
748
- }
749
- const id = nextAsk;
750
- nextAsk += 1;
751
- questions.set(id, (answer) => {
752
- // The line that closes the question, so the host's stall timer runs again.
753
- write(`${JSON.stringify({ type: "ask_resolved", id })}\n`);
754
- resolve(answer);
755
- });
756
- write(`${JSON.stringify({ type: "ask_call", id, ...call })}\n`);
757
- }),
758
- };
759
- let code: number;
760
- try {
761
- const text = await stdin.first();
762
- let decoded: unknown;
763
- let parsedOk = true;
764
- try {
765
- decoded = JSON.parse(text);
766
- } catch {
767
- parsedOk = false;
768
- }
769
- const parsed = parsedOk ? parseInput(decoded) : ({ ok: false, message: "the input is not valid JSON" } as const);
770
- if (!parsed.ok) {
771
- io.line(failure("invalid_input", parsed.message));
772
- code = EXIT_INVALID_INPUT;
773
- } else {
774
- // Later stdin lines answer `grant_use` lines.
775
- void (async () => {
776
- for (;;) {
777
- const line = await stdin.next();
778
- if (line === undefined) break;
779
- const said = messageText(line);
780
- if (said !== undefined) {
781
- if (onMessage === undefined) early.push(said);
782
- else onMessage(said);
783
- continue;
784
- }
785
- try {
786
- const ack: unknown = JSON.parse(line);
787
- if (typeof ack === "object" && ack !== null && Reflect.get(ack, "type") === "ask_ack") {
788
- const id: unknown = Reflect.get(ack, "id");
789
- const decision: unknown = Reflect.get(ack, "decision");
790
- const reason: unknown = Reflect.get(ack, "reason");
791
- if (typeof id === "number") {
792
- questions.get(id)?.({
793
- decision: decision === "allow" || decision === "stop" ? decision : "deny",
794
- ...(typeof reason === "string" ? { reason } : {}),
795
- });
796
- questions.delete(id);
797
- }
798
- }
799
- if (typeof ack === "object" && ack !== null && Reflect.get(ack, "type") === "grant_ack") {
800
- const id: unknown = Reflect.get(ack, "id");
801
- const used: unknown = Reflect.get(ack, "used");
802
- if (typeof id === "number") {
803
- waiting.get(id)?.(used === true);
804
- waiting.delete(id);
805
- }
806
- }
807
- } catch {
808
- // Not a line the program understands; it is ignored.
809
- }
810
- }
811
- // The host is gone: nothing more will be granted.
812
- hostGone = true;
813
- for (const resolve of waiting.values()) resolve(false);
814
- waiting.clear();
815
- for (const resolve of questions.values()) resolve({ decision: "deny", reason: "the host is gone" });
816
- questions.clear();
817
- })();
818
- code = await runWorker(parsed.input, io, cancel, hooks);
819
- }
820
- } catch (error) {
821
- io.log(error instanceof Error ? (error.stack ?? error.message) : String(error));
822
- io.line(failure("model_error", error instanceof Error ? error.message : String(error)));
823
- code = EXIT_FAILED;
824
- }
825
- stdin.close();
826
- return code;
737
+ return serveOne(stdinStream, ports, cancel, piAdapter(hooks));
738
+ }
739
+
740
+ /**
741
+ * Runs the first reply from stdin and, when the reply was done and asked for
742
+ * keeping, serves later replies from a socket in the operad home. The worker's
743
+ * own timer ends it after the kept time; a failed, stopped or interrupted reply
744
+ * leaves no kept worker.
745
+ */
746
+ export async function serveWorkerProcess(
747
+ stdinStream: AsyncIterable<Uint8Array>,
748
+ ports: WorkerPorts,
749
+ cancel: AbortSignal,
750
+ hooks: WorkerHooks = {},
751
+ ): Promise<number> {
752
+ return serveKeptWorker(stdinStream, ports, cancel, piAdapter(hooks));
827
753
  }
828
754
 
829
755
  /** The process entry: stdin in, stdout lines out, exit code out. */
830
756
  export async function main(hooks: WorkerHooks = {}): Promise<never> {
831
- const flush = (): Promise<void> =>
832
- new Promise((resolve) => {
833
- process.stdout.write("", () => resolve());
834
- });
835
- // Anything that prints to stdout by accident would corrupt the protocol.
836
- console.log = (...args: unknown[]): void => {
837
- process.stderr.write(`${args.map(String).join(" ")}\n`);
838
- };
839
-
840
757
  // pi runs bash non-interactively (`bash -c`): no aliases or functions from the
841
758
  // user's rc files. BASH_ENV and ENV are the two ways a non-interactive shell
842
759
  // is made to read a file, so the agent's shell does not get them.
843
- delete process.env["BASH_ENV"];
844
- delete process.env["ENV"];
845
-
846
- const controller = new AbortController();
847
- process.on("SIGTERM", () => controller.abort());
848
- const code = await serveWorker(
849
- Bun.stdin.stream(),
850
- {
851
- write: (text) => {
852
- process.stdout.write(text);
853
- },
854
- log: (text) => process.stderr.write(`${text}\n`),
855
- },
856
- controller.signal,
857
- hooks,
858
- );
859
- await flush();
860
- process.exit(code);
760
+ return runWorkerMain(piAdapter(hooks), {
761
+ envToDelete: ["BASH_ENV", "ENV"],
762
+ });
861
763
  }
862
764
 
863
765
  if (import.meta.main) await main();