@narumitw/pi-subagents 3.0.1 → 3.0.2

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/process.ts CHANGED
@@ -4,11 +4,7 @@ import * as path from "node:path";
4
4
  import { StringDecoder } from "node:string_decoder";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { getPackageDir } from "@earendil-works/pi-coding-agent";
7
- import {
8
- BROKER_CREDENTIAL_FD,
9
- brokerCredentialEnvironment,
10
- serializeBrokerCredentials,
11
- } from "./broker-credentials.js";
7
+ import { BROKER_CREDENTIAL_FD, brokerCredentialEnvironment, serializeBrokerCredentials } from "./broker-credentials.js";
12
8
  import { CHILD_COMMUNICATION_TOOL_NAMES } from "./child-communication-tools.js";
13
9
  import type { ChildControl, ChildRequest, ChildResult } from "./types.js";
14
10
 
@@ -22,667 +18,650 @@ const RPC_RESPONSE_TIMEOUT_MS = 30_000;
22
18
  const KILL_GRACE_MS = 1_000;
23
19
 
24
20
  interface ProcessSettlement {
25
- code: number;
26
- cancelled: boolean;
27
- timedOut: boolean;
28
- completed: boolean;
29
- launchError?: string;
21
+ code: number;
22
+ cancelled: boolean;
23
+ timedOut: boolean;
24
+ completed: boolean;
25
+ launchError?: string;
30
26
  }
31
27
 
32
28
  interface AssistantEvent {
33
- type?: string;
34
- id?: string;
35
- success?: boolean;
36
- error?: string;
37
- message?: {
38
- role?: string;
39
- content?: Array<{ type?: string; text?: string }>;
40
- stopReason?: string;
41
- errorMessage?: string;
42
- };
29
+ type?: string;
30
+ id?: string;
31
+ success?: boolean;
32
+ error?: string;
33
+ message?: {
34
+ role?: string;
35
+ content?: Array<{ type?: string; text?: string }>;
36
+ stopReason?: string;
37
+ errorMessage?: string;
38
+ };
43
39
  }
44
40
 
45
41
  interface PendingRpcCommand {
46
- command: string;
47
- resolve: () => void;
48
- reject: (error: Error) => void;
49
- timer: NodeJS.Timeout;
50
- onAccepted?: () => void;
51
- signal?: AbortSignal;
52
- onAbort?: () => void;
42
+ command: string;
43
+ resolve: () => void;
44
+ reject: (error: Error) => void;
45
+ timer: NodeJS.Timeout;
46
+ onAccepted?: () => void;
47
+ signal?: AbortSignal;
48
+ onAbort?: () => void;
53
49
  }
54
50
 
55
51
  export function resolveTimeoutMs(timeout: number | undefined): number | undefined {
56
- if (timeout === undefined) return undefined;
57
- if (!Number.isFinite(timeout) || timeout <= 0) {
58
- throw new Error("Invalid timeout: must be a finite number of seconds");
59
- }
60
- const timeoutMs = timeout * 1000;
61
- if (timeoutMs > MAX_TIMEOUT_MS) {
62
- throw new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);
63
- }
64
- return timeoutMs;
52
+ if (timeout === undefined) return undefined;
53
+ if (!Number.isFinite(timeout) || timeout <= 0) {
54
+ throw new Error("Invalid timeout: must be a finite number of seconds");
55
+ }
56
+ const timeoutMs = timeout * 1000;
57
+ if (timeoutMs > MAX_TIMEOUT_MS) {
58
+ throw new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);
59
+ }
60
+ return timeoutMs;
65
61
  }
66
62
 
67
63
  export async function runChild(request: ChildRequest): Promise<ChildResult> {
68
- if (request.signal.aborted) return cancelledResult();
69
- try {
70
- const invocation = resolvePiInvocation(buildPiArgs(request));
71
- return await executeProcess(invocation, request);
72
- } catch (error) {
73
- if (request.signal.aborted) return cancelledResult();
74
- return {
75
- state: "failed",
76
- error: truncateText(error instanceof Error ? error.message : String(error), MAX_ERROR_BYTES)
77
- .text,
78
- limitations: [],
79
- truncated: false,
80
- };
81
- }
64
+ if (request.signal.aborted) return cancelledResult();
65
+ try {
66
+ const invocation = resolvePiInvocation(buildPiArgs(request));
67
+ return await executeProcess(invocation, request);
68
+ } catch (error) {
69
+ if (request.signal.aborted) return cancelledResult();
70
+ return {
71
+ state: "failed",
72
+ error: truncateText(error instanceof Error ? error.message : String(error), MAX_ERROR_BYTES).text,
73
+ limitations: [],
74
+ truncated: false,
75
+ };
76
+ }
82
77
  }
83
78
 
84
79
  export function buildPiArgs(request: ChildRequest): string[] {
85
- const args = [
86
- "--mode",
87
- "rpc",
88
- "--no-session",
89
- "--no-extensions",
90
- "--no-skills",
91
- "--no-prompt-templates",
92
- "-e",
93
- childCommunicationBridgePath(),
94
- "--model",
95
- request.model,
96
- "--thinking",
97
- request.thinkingLevel,
98
- request.projectTrusted ? "--approve" : "--no-approve",
99
- ];
100
- const tools = [...new Set([...request.tools, ...CHILD_COMMUNICATION_TOOL_NAMES])];
101
- args.push("--tools", tools.join(","));
102
- return args;
80
+ const args = [
81
+ "--mode",
82
+ "rpc",
83
+ "--no-session",
84
+ "--no-extensions",
85
+ "--no-skills",
86
+ "--no-prompt-templates",
87
+ "-e",
88
+ childCommunicationBridgePath(),
89
+ "--model",
90
+ request.model,
91
+ "--thinking",
92
+ request.thinkingLevel,
93
+ request.projectTrusted ? "--approve" : "--no-approve",
94
+ ];
95
+ const tools = [...new Set([...request.tools, ...CHILD_COMMUNICATION_TOOL_NAMES])];
96
+ args.push("--tools", tools.join(","));
97
+ return args;
103
98
  }
104
99
 
105
100
  export function childCommunicationBridgePath(): string {
106
- return fileURLToPath(new URL("./child-communication-bridge.ts", import.meta.url));
101
+ return fileURLToPath(new URL("./child-communication-bridge.ts", import.meta.url));
107
102
  }
108
103
 
109
104
  async function executeProcess(
110
- invocation: { command: string; args: string[] },
111
- request: ChildRequest,
105
+ invocation: { command: string; args: string[] },
106
+ request: ChildRequest,
112
107
  ): Promise<ChildResult> {
113
- const timeoutMs = resolveTimeoutMs(request.timeout);
114
- let latestOutput = "";
115
- let terminalOutput: string | undefined;
116
- let terminalStopReason: "stop" | "length" | undefined;
117
- let errorMessage = "";
118
- let assistantFailed = false;
119
- let stderr = "";
120
- let truncated = false;
121
- let malformedEvents = 0;
122
- let rpcCounter = 0;
123
- const pendingCommands = new Map<string, PendingRpcCommand>();
124
- let rpcInputError: Error | undefined;
125
- let sendCommand: (
126
- command: { type: "prompt" | "steer"; message: string },
127
- onAccepted?: () => void,
128
- signal?: AbortSignal,
129
- ) => Promise<void> = () => Promise.reject(new Error("Subagent RPC process is unavailable."));
130
- let onAgentSettled: () => void = () => undefined;
131
-
132
- const takePendingCommand = (id: string): PendingRpcCommand | undefined => {
133
- const pending = pendingCommands.get(id);
134
- if (!pending) return undefined;
135
- pendingCommands.delete(id);
136
- clearTimeout(pending.timer);
137
- if (pending.signal && pending.onAbort) {
138
- pending.signal.removeEventListener("abort", pending.onAbort);
139
- }
140
- return pending;
141
- };
142
- const rejectPendingCommand = (id: string, error: Error) => {
143
- takePendingCommand(id)?.reject(error);
144
- };
145
- const rejectPendingCommands = (error: Error) => {
146
- for (const id of [...pendingCommands.keys()]) rejectPendingCommand(id, error);
147
- };
148
- const resolvePendingCommand = (id: string) => {
149
- const pending = takePendingCommand(id);
150
- if (!pending) return;
151
- try {
152
- pending.onAccepted?.();
153
- pending.resolve();
154
- } catch (error) {
155
- pending.reject(error instanceof Error ? error : new Error(String(error)));
156
- }
157
- };
158
- const failRpcInput = (error: Error) => {
159
- rpcInputError ??= error;
160
- rejectPendingCommands(rpcInputError);
161
- };
162
-
163
- const decoder = new JsonLineDecoder(
164
- (value) => {
165
- const event = value as AssistantEvent;
166
- if (event.type === "response" && typeof event.id === "string") {
167
- const pending = pendingCommands.get(event.id);
168
- if (!pending) return;
169
- if (event.success === true) {
170
- resolvePendingCommand(event.id);
171
- } else {
172
- rejectPendingCommand(
173
- event.id,
174
- new Error(
175
- typeof event.error === "string"
176
- ? event.error
177
- : `Subagent RPC ${pending.command} command failed.`,
178
- ),
179
- );
180
- }
181
- return;
182
- }
183
- if (event.type === "agent_settled") {
184
- onAgentSettled();
185
- return;
186
- }
187
- if (event.type === "message_end" && event.message?.role === "assistant") {
188
- const text = (event.message.content ?? [])
189
- .filter((part) => part.type === "text" && typeof part.text === "string")
190
- .map((part) => part.text)
191
- .join("\n")
192
- .trim();
193
- if (text) {
194
- const limited = truncateText(text, MAX_OUTPUT_BYTES);
195
- latestOutput = limited.text;
196
- truncated ||= limited.truncated;
197
- if (event.message.stopReason === "stop" || event.message.stopReason === "length") {
198
- terminalOutput = limited.text;
199
- terminalStopReason = event.message.stopReason;
200
- }
201
- }
202
- if (event.message.stopReason === "error" || event.message.stopReason === "aborted") {
203
- assistantFailed = true;
204
- }
205
- if (event.message.errorMessage) {
206
- const limited = truncateText(event.message.errorMessage, MAX_ERROR_BYTES);
207
- errorMessage = limited.text;
208
- truncated ||= limited.truncated;
209
- }
210
- }
211
- },
212
- () => {
213
- malformedEvents++;
214
- },
215
- );
216
-
217
- const settlement = await new Promise<ProcessSettlement>((resolve) => {
218
- let process: ChildProcess;
219
- let settled = false;
220
- let finishRequested = false;
221
- let spawned = false;
222
- let terminating = false;
223
- let cancelled = false;
224
- let timedOut = false;
225
- let completed = false;
226
- let ready = false;
227
- let deadline: NodeJS.Timeout | undefined;
228
- let forceClose: NodeJS.Timeout | undefined;
229
- let escalation: NodeJS.Timeout | undefined;
230
- let termination: Promise<void> | undefined;
231
-
232
- const finish = (code: number, launchError?: string) => {
233
- if (settled || finishRequested) return;
234
- finishRequested = true;
235
- const complete = () => {
236
- if (settled) return;
237
- settled = true;
238
- if (deadline) clearTimeout(deadline);
239
- if (forceClose) clearTimeout(forceClose);
240
- if (escalation) clearTimeout(escalation);
241
- request.signal.removeEventListener("abort", onAbort);
242
- rejectPendingCommands(new Error("Subagent RPC process closed."));
243
- resolve({ code, cancelled, timedOut, completed, launchError });
244
- };
245
- if (termination) void termination.then(complete, complete);
246
- else complete();
247
- };
248
- const terminate = (code: number) => {
249
- if (settled || terminating) return;
250
- terminating = true;
251
- if (deadline) {
252
- clearTimeout(deadline);
253
- deadline = undefined;
254
- }
255
- if (globalThis.process.platform === "win32") {
256
- termination = terminateWindowsProcessTree(process);
257
- } else {
258
- signalPosixProcess(process, "SIGTERM");
259
- escalation = setTimeout(() => signalPosixProcess(process, "SIGKILL"), KILL_GRACE_MS);
260
- escalation.unref();
261
- }
262
- forceClose = setTimeout(() => {
263
- decoder.finish();
264
- process.stdin?.destroy();
265
- process.stdout?.destroy();
266
- process.stderr?.destroy();
267
- finish(code);
268
- }, KILL_GRACE_MS * 2);
269
- forceClose.unref();
270
- };
271
- const onAbort = () => {
272
- if (settled) return;
273
- cancelled = true;
274
- terminate(130);
275
- };
276
- const completeNormally = () => {
277
- if (settled || terminating || !ready) return;
278
- completed = true;
279
- terminate(0);
280
- };
281
- onAgentSettled = completeNormally;
282
-
283
- try {
284
- process = spawn(invocation.command, invocation.args, {
285
- cwd: request.cwd,
286
- detached: globalThis.process.platform !== "win32",
287
- shell: false,
288
- stdio: ["pipe", "pipe", "pipe", "pipe"],
289
- env: {
290
- ...globalThis.process.env,
291
- ...brokerCredentialEnvironment(),
292
- PI_SUBAGENT_DEPTH: String(
293
- (Number.parseInt(globalThis.process.env.PI_SUBAGENT_DEPTH ?? "0", 10) || 0) + 1,
294
- ),
295
- },
296
- });
297
- } catch (error) {
298
- finish(1, error instanceof Error ? error.message : String(error));
299
- return;
300
- }
301
-
302
- process.stdin?.on("error", failRpcInput);
303
- sendCommand = (command, onAccepted, signal) => {
304
- if (settled || terminating || process.exitCode !== null) {
305
- return Promise.reject(new Error("Subagent RPC process is no longer active."));
306
- }
307
- if (signal?.aborted) {
308
- return Promise.reject(abortError("Subagent RPC command was cancelled."));
309
- }
310
- if (rpcInputError) return Promise.reject(rpcInputError);
311
- const stdin = process.stdin;
312
- if (!stdin || stdin.destroyed || !stdin.writable) {
313
- return Promise.reject(new Error("Subagent RPC stdin is unavailable."));
314
- }
315
- const id = `rpc_${++rpcCounter}`;
316
- return new Promise<void>((resolveCommand, rejectCommand) => {
317
- const timer = setTimeout(
318
- () =>
319
- rejectPendingCommand(id, new Error(`Subagent RPC ${command.type} response timed out.`)),
320
- RPC_RESPONSE_TIMEOUT_MS,
321
- );
322
- timer.unref();
323
- const pending: PendingRpcCommand = {
324
- command: command.type,
325
- resolve: resolveCommand,
326
- reject: rejectCommand,
327
- timer,
328
- onAccepted,
329
- signal,
330
- };
331
- if (signal) {
332
- pending.onAbort = () =>
333
- rejectPendingCommand(id, abortError("Subagent RPC command was cancelled."));
334
- }
335
- pendingCommands.set(id, pending);
336
- if (signal && pending.onAbort) {
337
- signal.addEventListener("abort", pending.onAbort, { once: true });
338
- if (signal.aborted) {
339
- pending.onAbort();
340
- return;
341
- }
342
- }
343
- try {
344
- stdin.write(`${JSON.stringify({ id, ...command })}\n`, (error) => {
345
- if (error) failRpcInput(error);
346
- });
347
- } catch (error) {
348
- failRpcInput(error instanceof Error ? error : new Error(String(error)));
349
- }
350
- });
351
- };
352
-
353
- request.signal.addEventListener("abort", onAbort, { once: true });
354
- if (request.signal.aborted) onAbort();
355
- process.once("spawn", () => {
356
- spawned = true;
357
- if (settled || cancelled) return;
358
- void sendCommand(
359
- { type: "prompt", message: `Task: ${request.task}` },
360
- () => {
361
- if (settled || terminating || request.signal.aborted) {
362
- throw new Error("Subagent RPC prompt was superseded.");
363
- }
364
- ready = true;
365
- if (timeoutMs !== undefined) {
366
- deadline = setTimeout(() => {
367
- timedOut = true;
368
- terminate(124);
369
- }, timeoutMs);
370
- deadline.unref();
371
- }
372
- const control: ChildControl = {
373
- send: async (message, signal) => {
374
- if (!ready || completed || terminating) {
375
- throw new Error("Subagent job is no longer accepting messages.");
376
- }
377
- await sendCommand({ type: "steer", message }, undefined, signal);
378
- },
379
- };
380
- request.onControl?.(control);
381
- },
382
- request.signal,
383
- ).catch((error) => {
384
- if (settled || terminating) return;
385
- errorMessage = truncateText(
386
- error instanceof Error ? error.message : String(error),
387
- MAX_ERROR_BYTES,
388
- ).text;
389
- terminate(1);
390
- });
391
- });
392
- process.stdout?.on("data", (chunk) => decoder.push(chunk));
393
- process.stderr?.on("data", (chunk) => {
394
- const limited = truncateTail(`${stderr}${chunk.toString()}`, MAX_ERROR_BYTES);
395
- stderr = limited.text;
396
- truncated ||= limited.truncated;
397
- });
398
- process.once("close", (code) => {
399
- decoder.finish();
400
- finish(cancelled ? 130 : timedOut ? 124 : completed ? 0 : (code ?? 1));
401
- });
402
- process.once("error", (error) => {
403
- const limited = truncateText(error.message, MAX_ERROR_BYTES);
404
- errorMessage = limited.text;
405
- truncated ||= limited.truncated;
406
- if (spawned) terminate(1);
407
- else finish(1, error.message);
408
- });
409
- const credentialPipe = process.stdio[BROKER_CREDENTIAL_FD];
410
- if (!credentialPipe || !("end" in credentialPipe)) {
411
- errorMessage = "Subagent broker credential pipe is unavailable.";
412
- terminate(1);
413
- } else {
414
- const onCredentialError = () => {
415
- if (settled || finishRequested) return;
416
- errorMessage = "Subagent broker credential transfer failed.";
417
- terminate(1);
418
- };
419
- const removeCredentialListeners = () => {
420
- credentialPipe.removeListener("error", onCredentialError);
421
- credentialPipe.removeListener("close", removeCredentialListeners);
422
- };
423
- credentialPipe.on("error", onCredentialError);
424
- credentialPipe.once("close", removeCredentialListeners);
425
- try {
426
- credentialPipe.end(serializeBrokerCredentials(request.communication));
427
- } catch {
428
- onCredentialError();
429
- }
430
- }
431
- });
432
-
433
- const output = terminalOutput ?? latestOutput;
434
- const limitations =
435
- malformedEvents > 0
436
- ? [`Ignored ${malformedEvents} malformed or oversized child event(s).`]
437
- : [];
438
- if (truncated) limitations.push("Child output was truncated to runtime limits.");
439
- if (terminalStopReason === "length") {
440
- limitations.push("Child output ended at the model output limit and may be incomplete.");
441
- }
442
- if (settlement.cancelled) return cancelledResult(output, limitations, truncated);
443
- if (settlement.timedOut) {
444
- return {
445
- state: "timed_out",
446
- ...(output ? { result: output } : {}),
447
- error: "Subagent execution timed out.",
448
- limitations,
449
- truncated,
450
- };
451
- }
452
- const error = settlement.launchError || errorMessage || stderr.trim();
453
- if (settlement.completed && terminalStopReason === "stop" && !assistantFailed && !errorMessage) {
454
- return {
455
- state: "completed",
456
- result: terminalOutput,
457
- limitations,
458
- truncated,
459
- };
460
- }
461
- const failure =
462
- error ||
463
- (terminalStopReason === "length"
464
- ? "Subagent output reached the model limit."
465
- : assistantFailed
466
- ? "Subagent model turn failed."
467
- : settlement.completed
468
- ? "Subagent settled without a terminal assistant result."
469
- : settlement.code === 0
470
- ? "Subagent exited without settling."
471
- : `Subagent exited with code ${settlement.code}.`);
472
- if (output) {
473
- return {
474
- state: "partial",
475
- result: output,
476
- error: failure,
477
- limitations,
478
- truncated,
479
- };
480
- }
481
- return {
482
- state: "failed",
483
- error: failure,
484
- limitations,
485
- truncated,
486
- };
108
+ const timeoutMs = resolveTimeoutMs(request.timeout);
109
+ let latestOutput = "";
110
+ let terminalOutput: string | undefined;
111
+ let terminalStopReason: "stop" | "length" | undefined;
112
+ let errorMessage = "";
113
+ let assistantFailed = false;
114
+ let stderr = "";
115
+ let truncated = false;
116
+ let malformedEvents = 0;
117
+ let rpcCounter = 0;
118
+ const pendingCommands = new Map<string, PendingRpcCommand>();
119
+ let rpcInputError: Error | undefined;
120
+ let sendCommand: (
121
+ command: { type: "prompt" | "steer"; message: string },
122
+ onAccepted?: () => void,
123
+ signal?: AbortSignal,
124
+ ) => Promise<void> = () => Promise.reject(new Error("Subagent RPC process is unavailable."));
125
+ let onAgentSettled: () => void = () => undefined;
126
+
127
+ const takePendingCommand = (id: string): PendingRpcCommand | undefined => {
128
+ const pending = pendingCommands.get(id);
129
+ if (!pending) return undefined;
130
+ pendingCommands.delete(id);
131
+ clearTimeout(pending.timer);
132
+ if (pending.signal && pending.onAbort) {
133
+ pending.signal.removeEventListener("abort", pending.onAbort);
134
+ }
135
+ return pending;
136
+ };
137
+ const rejectPendingCommand = (id: string, error: Error) => {
138
+ takePendingCommand(id)?.reject(error);
139
+ };
140
+ const rejectPendingCommands = (error: Error) => {
141
+ for (const id of [...pendingCommands.keys()]) rejectPendingCommand(id, error);
142
+ };
143
+ const resolvePendingCommand = (id: string) => {
144
+ const pending = takePendingCommand(id);
145
+ if (!pending) return;
146
+ try {
147
+ pending.onAccepted?.();
148
+ pending.resolve();
149
+ } catch (error) {
150
+ pending.reject(error instanceof Error ? error : new Error(String(error)));
151
+ }
152
+ };
153
+ const failRpcInput = (error: Error) => {
154
+ rpcInputError ??= error;
155
+ rejectPendingCommands(rpcInputError);
156
+ };
157
+
158
+ const decoder = new JsonLineDecoder(
159
+ (value) => {
160
+ const event = value as AssistantEvent;
161
+ if (event.type === "response" && typeof event.id === "string") {
162
+ const pending = pendingCommands.get(event.id);
163
+ if (!pending) return;
164
+ if (event.success === true) {
165
+ resolvePendingCommand(event.id);
166
+ } else {
167
+ rejectPendingCommand(
168
+ event.id,
169
+ new Error(
170
+ typeof event.error === "string" ? event.error : `Subagent RPC ${pending.command} command failed.`,
171
+ ),
172
+ );
173
+ }
174
+ return;
175
+ }
176
+ if (event.type === "agent_settled") {
177
+ onAgentSettled();
178
+ return;
179
+ }
180
+ if (event.type === "message_end" && event.message?.role === "assistant") {
181
+ const text = (event.message.content ?? [])
182
+ .filter((part) => part.type === "text" && typeof part.text === "string")
183
+ .map((part) => part.text)
184
+ .join("\n")
185
+ .trim();
186
+ if (text) {
187
+ const limited = truncateText(text, MAX_OUTPUT_BYTES);
188
+ latestOutput = limited.text;
189
+ truncated ||= limited.truncated;
190
+ if (event.message.stopReason === "stop" || event.message.stopReason === "length") {
191
+ terminalOutput = limited.text;
192
+ terminalStopReason = event.message.stopReason;
193
+ }
194
+ }
195
+ if (event.message.stopReason === "error" || event.message.stopReason === "aborted") {
196
+ assistantFailed = true;
197
+ }
198
+ if (event.message.errorMessage) {
199
+ const limited = truncateText(event.message.errorMessage, MAX_ERROR_BYTES);
200
+ errorMessage = limited.text;
201
+ truncated ||= limited.truncated;
202
+ }
203
+ }
204
+ },
205
+ () => {
206
+ malformedEvents++;
207
+ },
208
+ );
209
+
210
+ const settlement = await new Promise<ProcessSettlement>((resolve) => {
211
+ let process: ChildProcess;
212
+ let settled = false;
213
+ let finishRequested = false;
214
+ let spawned = false;
215
+ let terminating = false;
216
+ let cancelled = false;
217
+ let timedOut = false;
218
+ let completed = false;
219
+ let ready = false;
220
+ let deadline: NodeJS.Timeout | undefined;
221
+ let forceClose: NodeJS.Timeout | undefined;
222
+ let escalation: NodeJS.Timeout | undefined;
223
+ let termination: Promise<void> | undefined;
224
+
225
+ const finish = (code: number, launchError?: string) => {
226
+ if (settled || finishRequested) return;
227
+ finishRequested = true;
228
+ const complete = () => {
229
+ if (settled) return;
230
+ settled = true;
231
+ if (deadline) clearTimeout(deadline);
232
+ if (forceClose) clearTimeout(forceClose);
233
+ if (escalation) clearTimeout(escalation);
234
+ request.signal.removeEventListener("abort", onAbort);
235
+ rejectPendingCommands(new Error("Subagent RPC process closed."));
236
+ resolve({ code, cancelled, timedOut, completed, launchError });
237
+ };
238
+ if (termination) void termination.then(complete, complete);
239
+ else complete();
240
+ };
241
+ const terminate = (code: number) => {
242
+ if (settled || terminating) return;
243
+ terminating = true;
244
+ if (deadline) {
245
+ clearTimeout(deadline);
246
+ deadline = undefined;
247
+ }
248
+ if (globalThis.process.platform === "win32") {
249
+ termination = terminateWindowsProcessTree(process);
250
+ } else {
251
+ signalPosixProcess(process, "SIGTERM");
252
+ escalation = setTimeout(() => signalPosixProcess(process, "SIGKILL"), KILL_GRACE_MS);
253
+ escalation.unref();
254
+ }
255
+ forceClose = setTimeout(() => {
256
+ decoder.finish();
257
+ process.stdin?.destroy();
258
+ process.stdout?.destroy();
259
+ process.stderr?.destroy();
260
+ finish(code);
261
+ }, KILL_GRACE_MS * 2);
262
+ forceClose.unref();
263
+ };
264
+ const onAbort = () => {
265
+ if (settled) return;
266
+ cancelled = true;
267
+ terminate(130);
268
+ };
269
+ const completeNormally = () => {
270
+ if (settled || terminating || !ready) return;
271
+ completed = true;
272
+ terminate(0);
273
+ };
274
+ onAgentSettled = completeNormally;
275
+
276
+ try {
277
+ process = spawn(invocation.command, invocation.args, {
278
+ cwd: request.cwd,
279
+ detached: globalThis.process.platform !== "win32",
280
+ shell: false,
281
+ stdio: ["pipe", "pipe", "pipe", "pipe"],
282
+ env: {
283
+ ...globalThis.process.env,
284
+ ...brokerCredentialEnvironment(),
285
+ PI_SUBAGENT_DEPTH: String((Number.parseInt(globalThis.process.env.PI_SUBAGENT_DEPTH ?? "0", 10) || 0) + 1),
286
+ },
287
+ });
288
+ } catch (error) {
289
+ finish(1, error instanceof Error ? error.message : String(error));
290
+ return;
291
+ }
292
+
293
+ process.stdin?.on("error", failRpcInput);
294
+ sendCommand = (command, onAccepted, signal) => {
295
+ if (settled || terminating || process.exitCode !== null) {
296
+ return Promise.reject(new Error("Subagent RPC process is no longer active."));
297
+ }
298
+ if (signal?.aborted) {
299
+ return Promise.reject(abortError("Subagent RPC command was cancelled."));
300
+ }
301
+ if (rpcInputError) return Promise.reject(rpcInputError);
302
+ const stdin = process.stdin;
303
+ if (!stdin || stdin.destroyed || !stdin.writable) {
304
+ return Promise.reject(new Error("Subagent RPC stdin is unavailable."));
305
+ }
306
+ const id = `rpc_${++rpcCounter}`;
307
+ return new Promise<void>((resolveCommand, rejectCommand) => {
308
+ const timer = setTimeout(
309
+ () => rejectPendingCommand(id, new Error(`Subagent RPC ${command.type} response timed out.`)),
310
+ RPC_RESPONSE_TIMEOUT_MS,
311
+ );
312
+ timer.unref();
313
+ const pending: PendingRpcCommand = {
314
+ command: command.type,
315
+ resolve: resolveCommand,
316
+ reject: rejectCommand,
317
+ timer,
318
+ onAccepted,
319
+ signal,
320
+ };
321
+ if (signal) {
322
+ pending.onAbort = () => rejectPendingCommand(id, abortError("Subagent RPC command was cancelled."));
323
+ }
324
+ pendingCommands.set(id, pending);
325
+ if (signal && pending.onAbort) {
326
+ signal.addEventListener("abort", pending.onAbort, { once: true });
327
+ if (signal.aborted) {
328
+ pending.onAbort();
329
+ return;
330
+ }
331
+ }
332
+ try {
333
+ stdin.write(`${JSON.stringify({ id, ...command })}\n`, (error) => {
334
+ if (error) failRpcInput(error);
335
+ });
336
+ } catch (error) {
337
+ failRpcInput(error instanceof Error ? error : new Error(String(error)));
338
+ }
339
+ });
340
+ };
341
+
342
+ request.signal.addEventListener("abort", onAbort, { once: true });
343
+ if (request.signal.aborted) onAbort();
344
+ process.once("spawn", () => {
345
+ spawned = true;
346
+ if (settled || cancelled) return;
347
+ void sendCommand(
348
+ { type: "prompt", message: `Task: ${request.task}` },
349
+ () => {
350
+ if (settled || terminating || request.signal.aborted) {
351
+ throw new Error("Subagent RPC prompt was superseded.");
352
+ }
353
+ ready = true;
354
+ if (timeoutMs !== undefined) {
355
+ deadline = setTimeout(() => {
356
+ timedOut = true;
357
+ terminate(124);
358
+ }, timeoutMs);
359
+ deadline.unref();
360
+ }
361
+ const control: ChildControl = {
362
+ send: async (message, signal) => {
363
+ if (!ready || completed || terminating) {
364
+ throw new Error("Subagent job is no longer accepting messages.");
365
+ }
366
+ await sendCommand({ type: "steer", message }, undefined, signal);
367
+ },
368
+ };
369
+ request.onControl?.(control);
370
+ },
371
+ request.signal,
372
+ ).catch((error) => {
373
+ if (settled || terminating) return;
374
+ errorMessage = truncateText(error instanceof Error ? error.message : String(error), MAX_ERROR_BYTES).text;
375
+ terminate(1);
376
+ });
377
+ });
378
+ process.stdout?.on("data", (chunk) => decoder.push(chunk));
379
+ process.stderr?.on("data", (chunk) => {
380
+ const limited = truncateTail(`${stderr}${chunk.toString()}`, MAX_ERROR_BYTES);
381
+ stderr = limited.text;
382
+ truncated ||= limited.truncated;
383
+ });
384
+ process.once("close", (code) => {
385
+ decoder.finish();
386
+ finish(cancelled ? 130 : timedOut ? 124 : completed ? 0 : (code ?? 1));
387
+ });
388
+ process.once("error", (error) => {
389
+ const limited = truncateText(error.message, MAX_ERROR_BYTES);
390
+ errorMessage = limited.text;
391
+ truncated ||= limited.truncated;
392
+ if (spawned) terminate(1);
393
+ else finish(1, error.message);
394
+ });
395
+ const credentialPipe = process.stdio[BROKER_CREDENTIAL_FD];
396
+ if (!credentialPipe || !("end" in credentialPipe)) {
397
+ errorMessage = "Subagent broker credential pipe is unavailable.";
398
+ terminate(1);
399
+ } else {
400
+ const onCredentialError = () => {
401
+ if (settled || finishRequested) return;
402
+ errorMessage = "Subagent broker credential transfer failed.";
403
+ terminate(1);
404
+ };
405
+ const removeCredentialListeners = () => {
406
+ credentialPipe.removeListener("error", onCredentialError);
407
+ credentialPipe.removeListener("close", removeCredentialListeners);
408
+ };
409
+ credentialPipe.on("error", onCredentialError);
410
+ credentialPipe.once("close", removeCredentialListeners);
411
+ try {
412
+ credentialPipe.end(serializeBrokerCredentials(request.communication));
413
+ } catch {
414
+ onCredentialError();
415
+ }
416
+ }
417
+ });
418
+
419
+ const output = terminalOutput ?? latestOutput;
420
+ const limitations = malformedEvents > 0 ? [`Ignored ${malformedEvents} malformed or oversized child event(s).`] : [];
421
+ if (truncated) limitations.push("Child output was truncated to runtime limits.");
422
+ if (terminalStopReason === "length") {
423
+ limitations.push("Child output ended at the model output limit and may be incomplete.");
424
+ }
425
+ if (settlement.cancelled) return cancelledResult(output, limitations, truncated);
426
+ if (settlement.timedOut) {
427
+ return {
428
+ state: "timed_out",
429
+ ...(output ? { result: output } : {}),
430
+ error: "Subagent execution timed out.",
431
+ limitations,
432
+ truncated,
433
+ };
434
+ }
435
+ const error = settlement.launchError || errorMessage || stderr.trim();
436
+ if (settlement.completed && terminalStopReason === "stop" && !assistantFailed && !errorMessage) {
437
+ return {
438
+ state: "completed",
439
+ result: terminalOutput,
440
+ limitations,
441
+ truncated,
442
+ };
443
+ }
444
+ const failure =
445
+ error ||
446
+ (terminalStopReason === "length"
447
+ ? "Subagent output reached the model limit."
448
+ : assistantFailed
449
+ ? "Subagent model turn failed."
450
+ : settlement.completed
451
+ ? "Subagent settled without a terminal assistant result."
452
+ : settlement.code === 0
453
+ ? "Subagent exited without settling."
454
+ : `Subagent exited with code ${settlement.code}.`);
455
+ if (output) {
456
+ return {
457
+ state: "partial",
458
+ result: output,
459
+ error: failure,
460
+ limitations,
461
+ truncated,
462
+ };
463
+ }
464
+ return {
465
+ state: "failed",
466
+ error: failure,
467
+ limitations,
468
+ truncated,
469
+ };
487
470
  }
488
471
 
489
472
  function resolvePiInvocation(args: string[]): { command: string; args: string[] } {
490
- const packageDirectory = fs.realpathSync(getPackageDir());
491
- const manifestPath = path.join(packageDirectory, "package.json");
492
- const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")) as {
493
- name?: string;
494
- bin?: { pi?: string };
495
- };
496
- if (manifest.name !== CORE_PACKAGE_NAME || typeof manifest.bin?.pi !== "string") {
497
- throw new Error("Loaded Pi core package does not declare a valid bin.pi entry.");
498
- }
499
- const declared = manifest.bin.pi;
500
- if (path.isAbsolute(declared)) throw new Error("Pi core bin.pi must be package-relative.");
501
- if (
502
- globalThis.process.versions.bun &&
503
- /^pi(?:\.exe)?$/iu.test(path.basename(globalThis.process.execPath)) &&
504
- path.dirname(fs.realpathSync(globalThis.process.execPath)) === packageDirectory
505
- ) {
506
- return { command: globalThis.process.execPath, args };
507
- }
508
- const cliPath = fs.realpathSync(path.resolve(packageDirectory, declared));
509
- const relative = path.relative(packageDirectory, cliPath);
510
- if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
511
- throw new Error("Pi core bin.pi escapes its package directory.");
512
- }
513
- if (!fs.statSync(cliPath).isFile()) throw new Error("Pi core bin.pi is not a file.");
514
- return { command: globalThis.process.execPath, args: [cliPath, ...args] };
473
+ const packageDirectory = fs.realpathSync(getPackageDir());
474
+ const manifestPath = path.join(packageDirectory, "package.json");
475
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")) as {
476
+ name?: string;
477
+ bin?: { pi?: string };
478
+ };
479
+ if (manifest.name !== CORE_PACKAGE_NAME || typeof manifest.bin?.pi !== "string") {
480
+ throw new Error("Loaded Pi core package does not declare a valid bin.pi entry.");
481
+ }
482
+ const declared = manifest.bin.pi;
483
+ if (path.isAbsolute(declared)) throw new Error("Pi core bin.pi must be package-relative.");
484
+ if (
485
+ globalThis.process.versions.bun &&
486
+ /^pi(?:\.exe)?$/iu.test(path.basename(globalThis.process.execPath)) &&
487
+ path.dirname(fs.realpathSync(globalThis.process.execPath)) === packageDirectory
488
+ ) {
489
+ return { command: globalThis.process.execPath, args };
490
+ }
491
+ const cliPath = fs.realpathSync(path.resolve(packageDirectory, declared));
492
+ const relative = path.relative(packageDirectory, cliPath);
493
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
494
+ throw new Error("Pi core bin.pi escapes its package directory.");
495
+ }
496
+ if (!fs.statSync(cliPath).isFile()) throw new Error("Pi core bin.pi is not a file.");
497
+ return { command: globalThis.process.execPath, args: [cliPath, ...args] };
515
498
  }
516
499
 
517
500
  function signalPosixProcess(process: ChildProcess, signal: NodeJS.Signals): void {
518
- if (process.pid) {
519
- try {
520
- globalThis.process.kill(-process.pid, signal);
521
- return;
522
- } catch {
523
- // Fall back to the immediate child.
524
- }
525
- }
526
- try {
527
- process.kill(signal);
528
- } catch {
529
- // The process may already be terminal.
530
- }
501
+ if (process.pid) {
502
+ try {
503
+ globalThis.process.kill(-process.pid, signal);
504
+ return;
505
+ } catch {
506
+ // Fall back to the immediate child.
507
+ }
508
+ }
509
+ try {
510
+ process.kill(signal);
511
+ } catch {
512
+ // The process may already be terminal.
513
+ }
531
514
  }
532
515
 
533
516
  export function terminateWindowsProcessTree(
534
- process: ChildProcess,
535
- spawnProcess: typeof spawn = spawn,
536
- taskkillPath = resolveTaskkillPath(),
537
- helperTimeoutMs = KILL_GRACE_MS,
517
+ process: ChildProcess,
518
+ spawnProcess: typeof spawn = spawn,
519
+ taskkillPath = resolveTaskkillPath(),
520
+ helperTimeoutMs = KILL_GRACE_MS,
538
521
  ): Promise<void> {
539
- if (!process.pid || !taskkillPath) {
540
- killImmediateChild(process);
541
- return Promise.resolve();
542
- }
543
- return new Promise((resolve) => {
544
- let settled = false;
545
- let treeKiller: ChildProcess;
546
- let deadline: NodeJS.Timeout | undefined;
547
- const onError = () => finish(true, false);
548
- const onClose = (code: number | null) => finish(code !== 0, false);
549
- const finish = (fallback: boolean, terminateHelper: boolean) => {
550
- if (settled) return;
551
- settled = true;
552
- if (deadline) clearTimeout(deadline);
553
- treeKiller.removeListener("error", onError);
554
- treeKiller.removeListener("close", onClose);
555
- if (terminateHelper) killImmediateChild(treeKiller);
556
- if (fallback) killImmediateChild(process);
557
- resolve();
558
- };
559
- try {
560
- treeKiller = spawnProcess(taskkillPath, ["/PID", String(process.pid), "/T", "/F"], {
561
- stdio: "ignore",
562
- windowsHide: true,
563
- });
564
- } catch {
565
- killImmediateChild(process);
566
- resolve();
567
- return;
568
- }
569
- treeKiller.once("error", onError);
570
- treeKiller.once("close", onClose);
571
- deadline = setTimeout(() => finish(true, true), helperTimeoutMs);
572
- deadline.unref();
573
- });
522
+ if (!process.pid || !taskkillPath) {
523
+ killImmediateChild(process);
524
+ return Promise.resolve();
525
+ }
526
+ return new Promise((resolve) => {
527
+ let settled = false;
528
+ let treeKiller: ChildProcess;
529
+ let deadline: NodeJS.Timeout | undefined;
530
+ const onError = () => finish(true, false);
531
+ const onClose = (code: number | null) => finish(code !== 0, false);
532
+ const finish = (fallback: boolean, terminateHelper: boolean) => {
533
+ if (settled) return;
534
+ settled = true;
535
+ if (deadline) clearTimeout(deadline);
536
+ treeKiller.removeListener("error", onError);
537
+ treeKiller.removeListener("close", onClose);
538
+ if (terminateHelper) killImmediateChild(treeKiller);
539
+ if (fallback) killImmediateChild(process);
540
+ resolve();
541
+ };
542
+ try {
543
+ treeKiller = spawnProcess(taskkillPath, ["/PID", String(process.pid), "/T", "/F"], {
544
+ stdio: "ignore",
545
+ windowsHide: true,
546
+ });
547
+ } catch {
548
+ killImmediateChild(process);
549
+ resolve();
550
+ return;
551
+ }
552
+ treeKiller.once("error", onError);
553
+ treeKiller.once("close", onClose);
554
+ deadline = setTimeout(() => finish(true, true), helperTimeoutMs);
555
+ deadline.unref();
556
+ });
574
557
  }
575
558
 
576
559
  function resolveTaskkillPath(): string | undefined {
577
- const systemRoot = globalThis.process.env.SystemRoot ?? globalThis.process.env.WINDIR;
578
- if (!systemRoot || !path.win32.isAbsolute(systemRoot)) return undefined;
579
- return path.win32.join(systemRoot, "System32", "taskkill.exe");
560
+ const systemRoot = globalThis.process.env.SystemRoot ?? globalThis.process.env.WINDIR;
561
+ if (!systemRoot || !path.win32.isAbsolute(systemRoot)) return undefined;
562
+ return path.win32.join(systemRoot, "System32", "taskkill.exe");
580
563
  }
581
564
 
582
565
  function killImmediateChild(process: ChildProcess): void {
583
- try {
584
- process.kill("SIGKILL");
585
- } catch {
586
- // The process may already be terminal.
587
- }
566
+ try {
567
+ process.kill("SIGKILL");
568
+ } catch {
569
+ // The process may already be terminal.
570
+ }
588
571
  }
589
572
 
590
573
  function abortError(message: string): Error {
591
- const error = new Error(message);
592
- error.name = "AbortError";
593
- return error;
574
+ const error = new Error(message);
575
+ error.name = "AbortError";
576
+ return error;
594
577
  }
595
578
 
596
- function cancelledResult(
597
- result?: string,
598
- limitations: string[] = [],
599
- truncated = false,
600
- ): ChildResult {
601
- return {
602
- state: "cancelled",
603
- ...(result ? { result } : {}),
604
- error: "Subagent execution was cancelled.",
605
- limitations,
606
- truncated,
607
- };
579
+ function cancelledResult(result?: string, limitations: string[] = [], truncated = false): ChildResult {
580
+ return {
581
+ state: "cancelled",
582
+ ...(result ? { result } : {}),
583
+ error: "Subagent execution was cancelled.",
584
+ limitations,
585
+ truncated,
586
+ };
608
587
  }
609
588
 
610
589
  function truncateText(text: string, maxBytes: number): { text: string; truncated: boolean } {
611
- const bytes = Buffer.from(text, "utf8");
612
- if (bytes.length <= maxBytes) return { text, truncated: false };
613
- return {
614
- text: `${bytes
615
- .subarray(0, Math.max(0, maxBytes - 18))
616
- .toString("utf8")
617
- .replace(/�+$/gu, "")}\n… [truncated]`,
618
- truncated: true,
619
- };
590
+ const bytes = Buffer.from(text, "utf8");
591
+ if (bytes.length <= maxBytes) return { text, truncated: false };
592
+ return {
593
+ text: `${bytes
594
+ .subarray(0, Math.max(0, maxBytes - 18))
595
+ .toString("utf8")
596
+ .replace(/�+$/gu, "")}\n… [truncated]`,
597
+ truncated: true,
598
+ };
620
599
  }
621
600
 
622
601
  function truncateTail(text: string, maxBytes: number): { text: string; truncated: boolean } {
623
- const bytes = Buffer.from(text, "utf8");
624
- if (bytes.length <= maxBytes) return { text, truncated: false };
625
- return {
626
- text: `… [truncated]\n${bytes
627
- .subarray(bytes.length - Math.max(0, maxBytes - 18))
628
- .toString("utf8")
629
- .replace(/^�+/gu, "")}`,
630
- truncated: true,
631
- };
602
+ const bytes = Buffer.from(text, "utf8");
603
+ if (bytes.length <= maxBytes) return { text, truncated: false };
604
+ return {
605
+ text: `… [truncated]\n${bytes
606
+ .subarray(bytes.length - Math.max(0, maxBytes - 18))
607
+ .toString("utf8")
608
+ .replace(/^�+/gu, "")}`,
609
+ truncated: true,
610
+ };
632
611
  }
633
612
 
634
613
  class JsonLineDecoder {
635
- private buffer = "";
636
- private dropping = false;
637
- private readonly decoder = new StringDecoder("utf8");
638
-
639
- constructor(
640
- private readonly onValue: (value: unknown) => void,
641
- private readonly onMalformed: () => void,
642
- ) {}
643
-
644
- push(chunk: Buffer | string): void {
645
- this.buffer += typeof chunk === "string" ? chunk : this.decoder.write(chunk);
646
- this.drain(false);
647
- }
648
-
649
- finish(): void {
650
- this.buffer += this.decoder.end();
651
- this.drain(true);
652
- this.buffer = "";
653
- this.dropping = false;
654
- }
655
-
656
- private drain(flush: boolean): void {
657
- while (true) {
658
- const newline = this.buffer.indexOf("\n");
659
- if (newline < 0) break;
660
- const line = this.buffer.slice(0, newline).replace(/\r$/u, "");
661
- this.buffer = this.buffer.slice(newline + 1);
662
- if (this.dropping) {
663
- this.dropping = false;
664
- continue;
665
- }
666
- this.parse(line);
667
- }
668
- if (!flush && Buffer.byteLength(this.buffer, "utf8") > MAX_EVENT_LINE_BYTES) {
669
- this.onMalformed();
670
- this.buffer = "";
671
- this.dropping = true;
672
- }
673
- if (flush && this.buffer && !this.dropping) this.parse(this.buffer.replace(/\r$/u, ""));
674
- }
675
-
676
- private parse(line: string): void {
677
- if (!line.trim()) return;
678
- if (Buffer.byteLength(line, "utf8") > MAX_EVENT_LINE_BYTES) {
679
- this.onMalformed();
680
- return;
681
- }
682
- try {
683
- this.onValue(JSON.parse(line));
684
- } catch {
685
- this.onMalformed();
686
- }
687
- }
614
+ private buffer = "";
615
+ private dropping = false;
616
+ private readonly decoder = new StringDecoder("utf8");
617
+
618
+ constructor(
619
+ private readonly onValue: (value: unknown) => void,
620
+ private readonly onMalformed: () => void,
621
+ ) {}
622
+
623
+ push(chunk: Buffer | string): void {
624
+ this.buffer += typeof chunk === "string" ? chunk : this.decoder.write(chunk);
625
+ this.drain(false);
626
+ }
627
+
628
+ finish(): void {
629
+ this.buffer += this.decoder.end();
630
+ this.drain(true);
631
+ this.buffer = "";
632
+ this.dropping = false;
633
+ }
634
+
635
+ private drain(flush: boolean): void {
636
+ while (true) {
637
+ const newline = this.buffer.indexOf("\n");
638
+ if (newline < 0) break;
639
+ const line = this.buffer.slice(0, newline).replace(/\r$/u, "");
640
+ this.buffer = this.buffer.slice(newline + 1);
641
+ if (this.dropping) {
642
+ this.dropping = false;
643
+ continue;
644
+ }
645
+ this.parse(line);
646
+ }
647
+ if (!flush && Buffer.byteLength(this.buffer, "utf8") > MAX_EVENT_LINE_BYTES) {
648
+ this.onMalformed();
649
+ this.buffer = "";
650
+ this.dropping = true;
651
+ }
652
+ if (flush && this.buffer && !this.dropping) this.parse(this.buffer.replace(/\r$/u, ""));
653
+ }
654
+
655
+ private parse(line: string): void {
656
+ if (!line.trim()) return;
657
+ if (Buffer.byteLength(line, "utf8") > MAX_EVENT_LINE_BYTES) {
658
+ this.onMalformed();
659
+ return;
660
+ }
661
+ try {
662
+ this.onValue(JSON.parse(line));
663
+ } catch {
664
+ this.onMalformed();
665
+ }
666
+ }
688
667
  }