@narumitw/pi-subagents 3.0.1 → 3.1.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/process.ts CHANGED
@@ -4,685 +4,1008 @@ 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 { isWithin } from "./attachment-utils.js";
7
8
  import {
8
- BROKER_CREDENTIAL_FD,
9
- brokerCredentialEnvironment,
10
- serializeBrokerCredentials,
9
+ assertChildBootstrapCapacity,
10
+ BROKER_CREDENTIAL_FD,
11
+ CHILD_READINESS_FD,
12
+ CHILD_READINESS_FD_ENV,
13
+ childBootstrapEnvironment,
14
+ MAX_READINESS_FRAME_BYTES,
15
+ serializeChildBootstrap,
11
16
  } from "./broker-credentials.js";
12
17
  import { CHILD_COMMUNICATION_TOOL_NAMES } from "./child-communication-tools.js";
18
+ import { sanitizeTerminalText } from "./message-broker.js";
19
+ import { resolveTimeoutMs } from "./timeout.js";
13
20
  import type { ChildControl, ChildRequest, ChildResult } from "./types.js";
14
21
 
22
+ export { resolveTimeoutMs };
23
+
15
24
  const CORE_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
16
- const MAX_TIMEOUT_MS = 2_147_483_647;
17
- const MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;
18
25
  const MAX_OUTPUT_BYTES = 32 * 1024;
19
26
  const MAX_ERROR_BYTES = 8 * 1024;
20
27
  const MAX_EVENT_LINE_BYTES = 256 * 1024;
21
28
  const RPC_RESPONSE_TIMEOUT_MS = 30_000;
22
29
  const KILL_GRACE_MS = 1_000;
30
+ const MAX_WINDOWS_COMMAND_LINE_CODE_UNITS = 32_767;
23
31
 
24
32
  interface ProcessSettlement {
25
- code: number;
26
- cancelled: boolean;
27
- timedOut: boolean;
28
- completed: boolean;
29
- launchError?: string;
33
+ code: number;
34
+ cancelled: boolean;
35
+ timedOut: boolean;
36
+ completed: boolean;
37
+ launchError?: string;
30
38
  }
31
39
 
32
40
  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
- };
41
+ type?: string;
42
+ id?: string;
43
+ success?: boolean;
44
+ error?: string;
45
+ event?: string;
46
+ data?: unknown;
47
+ message?: {
48
+ role?: string;
49
+ content?: Array<{ type?: string; text?: string }>;
50
+ stopReason?: string;
51
+ errorMessage?: string;
52
+ };
43
53
  }
44
54
 
45
55
  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;
56
+ command: string;
57
+ resolve: () => void;
58
+ reject: (error: Error) => void;
59
+ timer: NodeJS.Timeout;
60
+ onAccepted?: (response: AssistantEvent) => void;
61
+ signal?: AbortSignal;
62
+ onAbort?: () => void;
53
63
  }
54
64
 
55
- 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;
65
- }
65
+ type ChildRpcCommand = { type: "get_state" | "get_commands" } | { type: "prompt" | "steer"; message: string };
66
66
 
67
67
  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
- }
68
+ if (request.signal.aborted) return cancelledResult();
69
+ try {
70
+ assertChildCommandCapacity(request);
71
+ const invocation = resolvePiInvocation(buildPiArgs(request));
72
+ return await executeProcess(invocation, request);
73
+ } catch (error) {
74
+ if (request.signal.aborted) return cancelledResult();
75
+ return {
76
+ state: "failed",
77
+ error: truncateText(
78
+ redactAttachmentPaths(error instanceof Error ? error.message : String(error), request),
79
+ MAX_ERROR_BYTES,
80
+ ).text,
81
+ limitations: [],
82
+ truncated: false,
83
+ };
84
+ }
85
+ }
86
+
87
+ type ChildCommandRequest = Pick<
88
+ ChildRequest,
89
+ "tools" | "skills" | "extensions" | "model" | "thinkingLevel" | "projectTrusted"
90
+ >;
91
+
92
+ export function buildPiArgs(request: ChildCommandRequest): string[] {
93
+ const args = [
94
+ "--mode",
95
+ "rpc",
96
+ "--no-session",
97
+ "--no-extensions",
98
+ "--no-skills",
99
+ "--no-prompt-templates",
100
+ "-e",
101
+ childCommunicationBridgePath(),
102
+ ];
103
+ for (const extension of request.extensions) args.push("-e", extension.path);
104
+ if (requiresReadinessAttestation(request)) args.push("-e", childReadinessProbePath());
105
+ for (const skill of request.skills) args.push("--skill", skill);
106
+ args.push(
107
+ "--model",
108
+ request.model,
109
+ "--thinking",
110
+ request.thinkingLevel,
111
+ request.projectTrusted ? "--approve" : "--no-approve",
112
+ );
113
+ args.push("--tools", selectedChildTools(request).join(","));
114
+ return args;
82
115
  }
83
116
 
84
- 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;
117
+ export function assertChildCommandCapacity(
118
+ request: ChildCommandRequest,
119
+ platform: NodeJS.Platform = process.platform,
120
+ ): void {
121
+ if (platform !== "win32") return;
122
+ const invocation = resolvePiInvocation(buildPiArgs(request));
123
+ const commandLineLength = [invocation.command, ...invocation.args].map(quoteWindowsArgument).join(" ").length;
124
+ if (commandLineLength + 1 > MAX_WINDOWS_COMMAND_LINE_CODE_UNITS) {
125
+ throw new Error("Subagent child command line exceeds the Windows process limit.");
126
+ }
127
+ }
128
+
129
+ function quoteWindowsArgument(value: string): string {
130
+ if (value.length > 0 && !/[\s"]/u.test(value)) return value;
131
+ let quoted = '"';
132
+ let backslashes = 0;
133
+ for (const character of value) {
134
+ if (character === "\\") {
135
+ backslashes++;
136
+ continue;
137
+ }
138
+ if (character === '"') {
139
+ quoted += `${"\\".repeat(backslashes * 2 + 1)}"`;
140
+ } else {
141
+ quoted += `${"\\".repeat(backslashes)}${character}`;
142
+ }
143
+ backslashes = 0;
144
+ }
145
+ return `${quoted}${"\\".repeat(backslashes * 2)}"`;
103
146
  }
104
147
 
105
148
  export function childCommunicationBridgePath(): string {
106
- return fileURLToPath(new URL("./child-communication-bridge.ts", import.meta.url));
149
+ return fileURLToPath(new URL("./child-communication-bridge.ts", import.meta.url));
150
+ }
151
+
152
+ export function childReadinessProbePath(): string {
153
+ return fileURLToPath(new URL("./child-readiness-probe.ts", import.meta.url));
154
+ }
155
+
156
+ function requiresReadinessAttestation(request: Pick<ChildRequest, "extensions">): boolean {
157
+ return request.extensions.length > 0;
158
+ }
159
+
160
+ function selectedChildTools(request: Pick<ChildRequest, "tools" | "extensions">): string[] {
161
+ return [
162
+ ...new Set([
163
+ ...request.tools,
164
+ ...CHILD_COMMUNICATION_TOOL_NAMES,
165
+ ...request.extensions.flatMap((extension) => extension.tools),
166
+ ]),
167
+ ];
107
168
  }
108
169
 
109
170
  async function executeProcess(
110
- invocation: { command: string; args: string[] },
111
- request: ChildRequest,
171
+ invocation: { command: string; args: string[] },
172
+ request: ChildRequest,
112
173
  ): 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
- };
174
+ const timeoutMs = resolveTimeoutMs(request.timeout);
175
+ const expectedTools = selectedChildTools(request);
176
+ const expectReadiness = requiresReadinessAttestation(request);
177
+ if (expectReadiness) assertChildBootstrapCapacity(expectedTools);
178
+ let latestOutput = "";
179
+ let terminalOutput: string | undefined;
180
+ let terminalStopReason: "stop" | "length" | undefined;
181
+ let errorMessage = "";
182
+ let assistantFailed = false;
183
+ let stderr = "";
184
+ let stderrRedactionCarry = "";
185
+ const stderrDecoder = new StringDecoder("utf8");
186
+ const diagnosticAttachmentPaths = attachmentPathVariants(request);
187
+ let truncated = false;
188
+ const appendStderr = (value: string) => {
189
+ if (!value) return;
190
+ const limited = truncateTail(`${stderr}${value}`, MAX_ERROR_BYTES);
191
+ stderr = limited.text;
192
+ truncated ||= limited.truncated;
193
+ };
194
+ const pushStderr = (chunk: Buffer | string) => {
195
+ const combined = `${stderrRedactionCarry}${typeof chunk === "string" ? chunk : stderrDecoder.write(chunk)}`;
196
+ const carryLength = attachmentPathCarryLength(combined, diagnosticAttachmentPaths);
197
+ const boundary = combined.length - carryLength;
198
+ appendStderr(redactAttachmentPathVariants(combined.slice(0, boundary), diagnosticAttachmentPaths));
199
+ stderrRedactionCarry = combined.slice(boundary);
200
+ };
201
+ const flushStderr = () => {
202
+ const combined = `${stderrRedactionCarry}${stderrDecoder.end()}`;
203
+ const carryLength = attachmentPathCarryLength(combined, diagnosticAttachmentPaths);
204
+ const boundary = combined.length - carryLength;
205
+ appendStderr(
206
+ `${redactAttachmentPathVariants(combined.slice(0, boundary), diagnosticAttachmentPaths)}${
207
+ carryLength > 0 ? "[attachment path]" : ""
208
+ }`,
209
+ );
210
+ stderrRedactionCarry = "";
211
+ };
212
+ let malformedEvents = 0;
213
+ let rpcCounter = 0;
214
+ let attachmentStartupPending = expectReadiness;
215
+ let attachmentStartupError: string | undefined;
216
+ const pendingCommands = new Map<string, PendingRpcCommand>();
217
+ let rpcInputError: Error | undefined;
218
+ let sendCommand: (
219
+ command: ChildRpcCommand,
220
+ onAccepted?: (response: AssistantEvent) => void,
221
+ signal?: AbortSignal,
222
+ ) => Promise<void> = () => Promise.reject(new Error("Subagent RPC process is unavailable."));
223
+ let onAgentSettled: () => void = () => undefined;
224
+
225
+ const takePendingCommand = (id: string): PendingRpcCommand | undefined => {
226
+ const pending = pendingCommands.get(id);
227
+ if (!pending) return undefined;
228
+ pendingCommands.delete(id);
229
+ clearTimeout(pending.timer);
230
+ if (pending.signal && pending.onAbort) {
231
+ pending.signal.removeEventListener("abort", pending.onAbort);
232
+ }
233
+ return pending;
234
+ };
235
+ const rejectPendingCommand = (id: string, error: Error) => {
236
+ takePendingCommand(id)?.reject(error);
237
+ };
238
+ const rejectPendingCommands = (error: Error) => {
239
+ for (const id of [...pendingCommands.keys()]) rejectPendingCommand(id, error);
240
+ };
241
+ const resolvePendingCommand = (id: string, response: AssistantEvent) => {
242
+ const pending = takePendingCommand(id);
243
+ if (!pending) return;
244
+ try {
245
+ pending.onAccepted?.(response);
246
+ pending.resolve();
247
+ } catch (error) {
248
+ pending.reject(error instanceof Error ? error : new Error(String(error)));
249
+ }
250
+ };
251
+ const failRpcInput = (error: Error) => {
252
+ rpcInputError ??= error;
253
+ rejectPendingCommands(rpcInputError);
254
+ };
255
+
256
+ const decoder = new JsonLineDecoder(
257
+ (value) => {
258
+ const event = value as AssistantEvent;
259
+ if (
260
+ expectReadiness &&
261
+ event.type === "extension_error" &&
262
+ (event.event === "session_start" || event.event === "resources_discover") &&
263
+ !attachmentStartupError
264
+ ) {
265
+ const detail =
266
+ typeof event.error === "string" && event.error
267
+ ? redactAttachmentPaths(sanitizeTerminalText(event.error), request)
268
+ : "Unknown error.";
269
+ attachmentStartupError = `Subagent attachment startup failed during ${event.event}: ${detail}`;
270
+ return;
271
+ }
272
+ if (event.type === "response" && typeof event.id === "string") {
273
+ const pending = pendingCommands.get(event.id);
274
+ if (!pending) return;
275
+ if (event.success === true) {
276
+ resolvePendingCommand(event.id, event);
277
+ } else {
278
+ rejectPendingCommand(
279
+ event.id,
280
+ new Error(
281
+ pending.command === "get_commands"
282
+ ? "Subagent child resource attestation failed."
283
+ : typeof event.error === "string"
284
+ ? event.error
285
+ : `Subagent RPC ${pending.command} command failed.`,
286
+ ),
287
+ );
288
+ }
289
+ return;
290
+ }
291
+ if (event.type === "agent_settled") {
292
+ onAgentSettled();
293
+ return;
294
+ }
295
+ if (event.type === "message_end" && event.message?.role === "assistant") {
296
+ const text = (event.message.content ?? [])
297
+ .filter((part) => part.type === "text" && typeof part.text === "string")
298
+ .map((part) => part.text)
299
+ .join("\n")
300
+ .trim();
301
+ if (text) {
302
+ const limited = truncateText(text, MAX_OUTPUT_BYTES);
303
+ latestOutput = limited.text;
304
+ truncated ||= limited.truncated;
305
+ if (event.message.stopReason === "stop" || event.message.stopReason === "length") {
306
+ terminalOutput = limited.text;
307
+ terminalStopReason = event.message.stopReason;
308
+ }
309
+ }
310
+ if (event.message.stopReason === "error" || event.message.stopReason === "aborted") {
311
+ assistantFailed = true;
312
+ }
313
+ if (event.message.errorMessage) {
314
+ const limited = truncateText(redactAttachmentPaths(event.message.errorMessage, request), MAX_ERROR_BYTES);
315
+ errorMessage = limited.text;
316
+ truncated ||= limited.truncated;
317
+ }
318
+ }
319
+ },
320
+ () => {
321
+ malformedEvents++;
322
+ if (attachmentStartupPending && !attachmentStartupError) {
323
+ attachmentStartupError = "Subagent attachment startup emitted malformed or oversized RPC output.";
324
+ }
325
+ },
326
+ );
327
+
328
+ const settlement = await new Promise<ProcessSettlement>((resolve) => {
329
+ let process: ChildProcess;
330
+ let settled = false;
331
+ let finishRequested = false;
332
+ let spawned = false;
333
+ let terminating = false;
334
+ let cancelled = false;
335
+ let timedOut = false;
336
+ let completed = false;
337
+ let ready = false;
338
+ let attachmentReady = !expectReadiness;
339
+ let promptStarted = false;
340
+ let readinessPipe: import("node:stream").Readable | undefined;
341
+ let deadline: NodeJS.Timeout | undefined;
342
+ let forceClose: NodeJS.Timeout | undefined;
343
+ let escalation: NodeJS.Timeout | undefined;
344
+ let termination: Promise<void> | undefined;
345
+
346
+ const finish = (code: number, launchError?: string) => {
347
+ if (settled || finishRequested) return;
348
+ finishRequested = true;
349
+ const complete = () => {
350
+ if (settled) return;
351
+ settled = true;
352
+ if (deadline) clearTimeout(deadline);
353
+ if (forceClose) clearTimeout(forceClose);
354
+ if (escalation) clearTimeout(escalation);
355
+ request.signal.removeEventListener("abort", onAbort);
356
+ readinessPipe?.removeAllListeners();
357
+ readinessPipe?.destroy();
358
+ rejectPendingCommands(new Error("Subagent RPC process closed."));
359
+ resolve({ code, cancelled, timedOut, completed, launchError });
360
+ };
361
+ if (termination) void termination.then(complete, complete);
362
+ else complete();
363
+ };
364
+ const terminate = (code: number) => {
365
+ if (settled || terminating) return;
366
+ terminating = true;
367
+ if (deadline) {
368
+ clearTimeout(deadline);
369
+ deadline = undefined;
370
+ }
371
+ if (globalThis.process.platform === "win32") {
372
+ termination = terminateWindowsProcessTree(process);
373
+ } else {
374
+ signalPosixProcess(process, "SIGTERM");
375
+ escalation = setTimeout(() => signalPosixProcess(process, "SIGKILL"), KILL_GRACE_MS);
376
+ escalation.unref();
377
+ }
378
+ forceClose = setTimeout(() => {
379
+ decoder.finish();
380
+ process.stdin?.destroy();
381
+ process.stdout?.destroy();
382
+ process.stderr?.destroy();
383
+ readinessPipe?.destroy();
384
+ finish(code);
385
+ }, KILL_GRACE_MS * 2);
386
+ forceClose.unref();
387
+ };
388
+ const onAbort = () => {
389
+ if (settled) return;
390
+ cancelled = true;
391
+ terminate(130);
392
+ };
393
+ const completeNormally = () => {
394
+ if (settled || terminating || !ready) return;
395
+ completed = true;
396
+ terminate(0);
397
+ };
398
+ onAgentSettled = completeNormally;
399
+
400
+ try {
401
+ const environment: NodeJS.ProcessEnv = {
402
+ ...globalThis.process.env,
403
+ ...childBootstrapEnvironment(expectReadiness),
404
+ PI_SUBAGENT_DEPTH: String((Number.parseInt(globalThis.process.env.PI_SUBAGENT_DEPTH ?? "0", 10) || 0) + 1),
405
+ };
406
+ if (!expectReadiness) delete environment[CHILD_READINESS_FD_ENV];
407
+ process = spawn(invocation.command, invocation.args, {
408
+ cwd: request.cwd,
409
+ detached: globalThis.process.platform !== "win32",
410
+ shell: false,
411
+ stdio: expectReadiness ? ["pipe", "pipe", "pipe", "pipe", "pipe"] : ["pipe", "pipe", "pipe", "pipe"],
412
+ env: environment,
413
+ });
414
+ } catch (error) {
415
+ finish(1, error instanceof Error ? error.message : String(error));
416
+ return;
417
+ }
418
+
419
+ process.stdin?.on("error", failRpcInput);
420
+ sendCommand = (command, onAccepted, signal) => {
421
+ if (settled || terminating || process.exitCode !== null) {
422
+ return Promise.reject(new Error("Subagent RPC process is no longer active."));
423
+ }
424
+ if (signal?.aborted) {
425
+ return Promise.reject(abortError("Subagent RPC command was cancelled."));
426
+ }
427
+ if (rpcInputError) return Promise.reject(rpcInputError);
428
+ const stdin = process.stdin;
429
+ if (!stdin || stdin.destroyed || !stdin.writable) {
430
+ return Promise.reject(new Error("Subagent RPC stdin is unavailable."));
431
+ }
432
+ const id = `rpc_${++rpcCounter}`;
433
+ return new Promise<void>((resolveCommand, rejectCommand) => {
434
+ const timer = setTimeout(
435
+ () => rejectPendingCommand(id, new Error(`Subagent RPC ${command.type} response timed out.`)),
436
+ RPC_RESPONSE_TIMEOUT_MS,
437
+ );
438
+ timer.unref();
439
+ const pending: PendingRpcCommand = {
440
+ command: command.type,
441
+ resolve: resolveCommand,
442
+ reject: rejectCommand,
443
+ timer,
444
+ onAccepted,
445
+ signal,
446
+ };
447
+ if (signal) {
448
+ pending.onAbort = () => rejectPendingCommand(id, abortError("Subagent RPC command was cancelled."));
449
+ }
450
+ pendingCommands.set(id, pending);
451
+ if (signal && pending.onAbort) {
452
+ signal.addEventListener("abort", pending.onAbort, { once: true });
453
+ if (signal.aborted) {
454
+ pending.onAbort();
455
+ return;
456
+ }
457
+ }
458
+ try {
459
+ stdin.write(`${JSON.stringify({ id, ...command })}\n`, (error) => {
460
+ if (error) failRpcInput(error);
461
+ });
462
+ } catch (error) {
463
+ failRpcInput(error instanceof Error ? error : new Error(String(error)));
464
+ }
465
+ });
466
+ };
467
+
468
+ const startPrompt = () => {
469
+ if (!spawned || !attachmentReady || promptStarted || settled || cancelled || terminating) return;
470
+ promptStarted = true;
471
+ void sendCommand(
472
+ { type: "prompt", message: `Task: ${request.task}` },
473
+ () => {
474
+ if (settled || terminating || request.signal.aborted) {
475
+ throw new Error("Subagent RPC prompt was superseded.");
476
+ }
477
+ ready = true;
478
+ if (timeoutMs !== undefined) {
479
+ deadline = setTimeout(() => {
480
+ timedOut = true;
481
+ terminate(124);
482
+ }, timeoutMs);
483
+ deadline.unref();
484
+ }
485
+ const control: ChildControl = {
486
+ send: async (message, signal) => {
487
+ if (!ready || completed || terminating) {
488
+ throw new Error("Subagent job is no longer accepting messages.");
489
+ }
490
+ await sendCommand({ type: "steer", message }, undefined, signal);
491
+ },
492
+ };
493
+ request.onControl?.(control);
494
+ },
495
+ request.signal,
496
+ ).catch((error) => {
497
+ if (settled || terminating) return;
498
+ errorMessage = truncateText(
499
+ redactAttachmentPaths(error instanceof Error ? error.message : String(error), request),
500
+ MAX_ERROR_BYTES,
501
+ ).text;
502
+ terminate(1);
503
+ });
504
+ };
505
+ const failReadiness = (message: string) => {
506
+ if (settled || terminating || attachmentReady) return;
507
+ errorMessage = truncateText(redactAttachmentPaths(message, request), MAX_ERROR_BYTES).text;
508
+ terminate(1);
509
+ };
510
+ const confirmAttachmentStartup = () => {
511
+ void sendCommand({ type: "get_state" }, undefined, request.signal)
512
+ .then(async () => {
513
+ if (attachmentStartupError) throw new Error(attachmentStartupError);
514
+ if (!request.projectTrusted) {
515
+ // Pi's RPC get_commands includes effective skills and prompts after resources_discover.
516
+ // RPC themes have no UI or model-visible representation.
517
+ await sendCommand(
518
+ { type: "get_commands" },
519
+ (response) => assertTrustedChildResources(response.data, request.cwd),
520
+ request.signal,
521
+ );
522
+ }
523
+ if (attachmentStartupError) throw new Error(attachmentStartupError);
524
+ attachmentStartupPending = false;
525
+ attachmentReady = true;
526
+ startPrompt();
527
+ })
528
+ .catch((error) => {
529
+ failReadiness(error instanceof Error ? error.message : String(error));
530
+ });
531
+ };
532
+
533
+ request.signal.addEventListener("abort", onAbort, { once: true });
534
+ if (request.signal.aborted) onAbort();
535
+ process.once("spawn", () => {
536
+ spawned = true;
537
+ startPrompt();
538
+ });
539
+ if (expectReadiness) {
540
+ const candidate = process.stdio[CHILD_READINESS_FD];
541
+ if (!candidate || !("on" in candidate)) {
542
+ errorMessage = "Subagent readiness pipe is unavailable.";
543
+ terminate(1);
544
+ } else {
545
+ readinessPipe = candidate as import("node:stream").Readable;
546
+ let buffer = Buffer.alloc(0);
547
+ let readinessSettled = false;
548
+ readinessPipe.on("data", (chunk: Buffer | string) => {
549
+ if (readinessSettled || terminating) return;
550
+ buffer = Buffer.concat([buffer, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)]);
551
+ if (buffer.byteLength > MAX_READINESS_FRAME_BYTES) {
552
+ readinessSettled = true;
553
+ failReadiness("Subagent readiness frame exceeded its size limit.");
554
+ }
555
+ });
556
+ readinessPipe.once("end", () => {
557
+ if (readinessSettled || terminating) return;
558
+ readinessSettled = true;
559
+ let frame: { ok: true; sources: string[] } | { ok: false; error: string };
560
+ try {
561
+ frame = parseReadinessFrame(buffer, expectedTools.length);
562
+ } catch (error) {
563
+ failReadiness(error instanceof Error ? error.message : String(error));
564
+ return;
565
+ }
566
+ if (!frame.ok) {
567
+ failReadiness(frame.error);
568
+ return;
569
+ }
570
+ for (const extension of request.extensions) {
571
+ for (const tool of extension.tools) {
572
+ const source = frame.sources[expectedTools.indexOf(tool)];
573
+ if (
574
+ !source ||
575
+ !Object.hasOwn(request.toolSources, tool) ||
576
+ !request.toolSources[tool]?.includes(source)
577
+ ) {
578
+ failReadiness(`Subagent extension tool ${tool} was not provided by its requested attachment.`);
579
+ return;
580
+ }
581
+ }
582
+ }
583
+ confirmAttachmentStartup();
584
+ });
585
+ readinessPipe.once("error", () => {
586
+ if (readinessSettled || terminating) return;
587
+ readinessSettled = true;
588
+ failReadiness("Subagent readiness transfer failed.");
589
+ });
590
+ readinessPipe.once("close", () => {
591
+ if (readinessSettled || terminating) return;
592
+ readinessSettled = true;
593
+ failReadiness("Subagent readiness pipe closed without a result.");
594
+ });
595
+ }
596
+ }
597
+ process.stdout?.on("data", (chunk) => decoder.push(chunk));
598
+ process.stderr?.on("data", (chunk: Buffer | string) => pushStderr(chunk));
599
+ process.once("close", (code) => {
600
+ flushStderr();
601
+ decoder.finish();
602
+ finish(cancelled ? 130 : timedOut ? 124 : completed ? 0 : (code ?? 1));
603
+ });
604
+ process.once("error", (error) => {
605
+ const limited = truncateText(redactAttachmentPaths(error.message, request), MAX_ERROR_BYTES);
606
+ errorMessage = limited.text;
607
+ truncated ||= limited.truncated;
608
+ if (spawned) terminate(1);
609
+ else finish(1, error.message);
610
+ });
611
+ const credentialPipe = process.stdio[BROKER_CREDENTIAL_FD];
612
+ if (!credentialPipe || !("end" in credentialPipe)) {
613
+ errorMessage = "Subagent broker credential pipe is unavailable.";
614
+ terminate(1);
615
+ } else {
616
+ const onCredentialError = () => {
617
+ if (settled || finishRequested) return;
618
+ errorMessage = "Subagent broker credential transfer failed.";
619
+ terminate(1);
620
+ };
621
+ const removeCredentialListeners = () => {
622
+ credentialPipe.removeListener("error", onCredentialError);
623
+ credentialPipe.removeListener("close", removeCredentialListeners);
624
+ };
625
+ credentialPipe.on("error", onCredentialError);
626
+ credentialPipe.once("close", removeCredentialListeners);
627
+ try {
628
+ credentialPipe.end(
629
+ serializeChildBootstrap({
630
+ communication: request.communication,
631
+ expectedTools: expectReadiness ? expectedTools : [],
632
+ }),
633
+ );
634
+ } catch {
635
+ onCredentialError();
636
+ }
637
+ }
638
+ });
639
+
640
+ const output = terminalOutput ?? latestOutput;
641
+ const limitations = malformedEvents > 0 ? [`Ignored ${malformedEvents} malformed or oversized child event(s).`] : [];
642
+ if (truncated) limitations.push("Child output was truncated to runtime limits.");
643
+ if (terminalStopReason === "length") {
644
+ limitations.push("Child output ended at the model output limit and may be incomplete.");
645
+ }
646
+ if (settlement.cancelled) return cancelledResult(output, limitations, truncated);
647
+ if (settlement.timedOut) {
648
+ return {
649
+ state: "timed_out",
650
+ ...(output ? { result: output } : {}),
651
+ error: "Subagent execution timed out.",
652
+ limitations,
653
+ truncated,
654
+ };
655
+ }
656
+ const redactedStderr = truncateTail(redactAttachmentPaths(stderr.trim(), request), MAX_ERROR_BYTES);
657
+ const combinedError = combineErrors(
658
+ redactAttachmentPaths(settlement.launchError ?? "", request),
659
+ redactAttachmentPaths(errorMessage, request),
660
+ redactedStderr.text,
661
+ );
662
+ const error = combinedError.text;
663
+ if ((combinedError.truncated || redactedStderr.truncated) && !truncated) {
664
+ limitations.push("Child output was truncated to runtime limits.");
665
+ }
666
+ truncated ||= combinedError.truncated || redactedStderr.truncated;
667
+ if (settlement.completed && terminalStopReason === "stop" && !assistantFailed && !errorMessage) {
668
+ return {
669
+ state: "completed",
670
+ result: terminalOutput,
671
+ limitations,
672
+ truncated,
673
+ };
674
+ }
675
+ const failure =
676
+ error ||
677
+ (terminalStopReason === "length"
678
+ ? "Subagent output reached the model limit."
679
+ : assistantFailed
680
+ ? "Subagent model turn failed."
681
+ : settlement.completed
682
+ ? "Subagent settled without a terminal assistant result."
683
+ : settlement.code === 0
684
+ ? "Subagent exited without settling."
685
+ : `Subagent exited with code ${settlement.code}.`);
686
+ if (output) {
687
+ return {
688
+ state: "partial",
689
+ result: output,
690
+ error: failure,
691
+ limitations,
692
+ truncated,
693
+ };
694
+ }
695
+ return {
696
+ state: "failed",
697
+ error: failure,
698
+ limitations,
699
+ truncated,
700
+ };
487
701
  }
488
702
 
489
703
  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] };
704
+ const packageDirectory = fs.realpathSync(getPackageDir());
705
+ const manifestPath = path.join(packageDirectory, "package.json");
706
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")) as {
707
+ name?: string;
708
+ bin?: { pi?: string };
709
+ };
710
+ if (manifest.name !== CORE_PACKAGE_NAME || typeof manifest.bin?.pi !== "string") {
711
+ throw new Error("Loaded Pi core package does not declare a valid bin.pi entry.");
712
+ }
713
+ const declared = manifest.bin.pi;
714
+ if (path.isAbsolute(declared)) throw new Error("Pi core bin.pi must be package-relative.");
715
+ if (
716
+ globalThis.process.versions.bun &&
717
+ /^pi(?:\.exe)?$/iu.test(path.basename(globalThis.process.execPath)) &&
718
+ path.dirname(fs.realpathSync(globalThis.process.execPath)) === packageDirectory
719
+ ) {
720
+ return { command: globalThis.process.execPath, args };
721
+ }
722
+ const cliPath = fs.realpathSync(path.resolve(packageDirectory, declared));
723
+ const relative = path.relative(packageDirectory, cliPath);
724
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
725
+ throw new Error("Pi core bin.pi escapes its package directory.");
726
+ }
727
+ if (!fs.statSync(cliPath).isFile()) throw new Error("Pi core bin.pi is not a file.");
728
+ return { command: globalThis.process.execPath, args: [cliPath, ...args] };
515
729
  }
516
730
 
517
731
  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
- }
732
+ if (process.pid) {
733
+ try {
734
+ globalThis.process.kill(-process.pid, signal);
735
+ return;
736
+ } catch {
737
+ // Fall back to the immediate child.
738
+ }
739
+ }
740
+ try {
741
+ process.kill(signal);
742
+ } catch {
743
+ // The process may already be terminal.
744
+ }
531
745
  }
532
746
 
533
747
  export function terminateWindowsProcessTree(
534
- process: ChildProcess,
535
- spawnProcess: typeof spawn = spawn,
536
- taskkillPath = resolveTaskkillPath(),
537
- helperTimeoutMs = KILL_GRACE_MS,
748
+ process: ChildProcess,
749
+ spawnProcess: typeof spawn = spawn,
750
+ taskkillPath = resolveTaskkillPath(),
751
+ helperTimeoutMs = KILL_GRACE_MS,
538
752
  ): 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
- });
753
+ if (!process.pid || !taskkillPath) {
754
+ killImmediateChild(process);
755
+ return Promise.resolve();
756
+ }
757
+ return new Promise((resolve) => {
758
+ let settled = false;
759
+ let treeKiller: ChildProcess;
760
+ let deadline: NodeJS.Timeout | undefined;
761
+ const onError = () => finish(true, false);
762
+ const onClose = (code: number | null) => finish(code !== 0, false);
763
+ const finish = (fallback: boolean, terminateHelper: boolean) => {
764
+ if (settled) return;
765
+ settled = true;
766
+ if (deadline) clearTimeout(deadline);
767
+ treeKiller.removeListener("error", onError);
768
+ treeKiller.removeListener("close", onClose);
769
+ if (terminateHelper) killImmediateChild(treeKiller);
770
+ if (fallback) killImmediateChild(process);
771
+ resolve();
772
+ };
773
+ try {
774
+ treeKiller = spawnProcess(taskkillPath, ["/PID", String(process.pid), "/T", "/F"], {
775
+ stdio: "ignore",
776
+ windowsHide: true,
777
+ });
778
+ } catch {
779
+ killImmediateChild(process);
780
+ resolve();
781
+ return;
782
+ }
783
+ treeKiller.once("error", onError);
784
+ treeKiller.once("close", onClose);
785
+ deadline = setTimeout(() => finish(true, true), helperTimeoutMs);
786
+ deadline.unref();
787
+ });
574
788
  }
575
789
 
576
790
  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");
791
+ const systemRoot = globalThis.process.env.SystemRoot ?? globalThis.process.env.WINDIR;
792
+ if (!systemRoot || !path.win32.isAbsolute(systemRoot)) return undefined;
793
+ return path.win32.join(systemRoot, "System32", "taskkill.exe");
580
794
  }
581
795
 
582
796
  function killImmediateChild(process: ChildProcess): void {
583
- try {
584
- process.kill("SIGKILL");
585
- } catch {
586
- // The process may already be terminal.
587
- }
797
+ try {
798
+ process.kill("SIGKILL");
799
+ } catch {
800
+ // The process may already be terminal.
801
+ }
802
+ }
803
+
804
+ function assertTrustedChildResources(value: unknown, cwd: string): void {
805
+ const invalid = () => new Error("Subagent child resource attestation returned invalid commands.");
806
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw invalid();
807
+ const commands = (value as { commands?: unknown }).commands;
808
+ if (!Array.isArray(commands)) throw invalid();
809
+ let canonicalCwd: string;
810
+ try {
811
+ canonicalCwd = fs.realpathSync(cwd);
812
+ } catch {
813
+ throw invalid();
814
+ }
815
+ for (const command of commands) {
816
+ if (!command || typeof command !== "object" || Array.isArray(command)) throw invalid();
817
+ const entry = command as { source?: unknown; sourceInfo?: { path?: unknown } };
818
+ if (entry.source !== "skill" && entry.source !== "prompt") continue;
819
+ const resourcePath = entry.sourceInfo?.path;
820
+ if (typeof resourcePath !== "string" || !resourcePath) throw invalid();
821
+ const lexicalPath = path.resolve(cwd, resourcePath);
822
+ let canonicalPath: string;
823
+ try {
824
+ canonicalPath = fs.realpathSync(lexicalPath);
825
+ } catch {
826
+ throw invalid();
827
+ }
828
+ if (isWithin(cwd, lexicalPath) || isWithin(canonicalCwd, canonicalPath)) {
829
+ throw new Error("Subagent child cannot load project resources because the project is not trusted.");
830
+ }
831
+ }
832
+ }
833
+
834
+ function parseReadinessFrame(
835
+ buffer: Buffer,
836
+ expectedToolCount: number,
837
+ ): { ok: true; sources: string[] } | { ok: false; error: string } {
838
+ if (buffer.byteLength === 0) {
839
+ throw new Error("Subagent readiness pipe closed without a result.");
840
+ }
841
+ const text = buffer.toString("utf8");
842
+ const newline = text.indexOf("\n");
843
+ if (newline < 0 || newline !== text.length - 1) {
844
+ throw new Error("Subagent readiness pipe returned an invalid frame.");
845
+ }
846
+ let value: unknown;
847
+ try {
848
+ value = JSON.parse(text.slice(0, newline));
849
+ } catch {
850
+ throw new Error("Subagent readiness pipe returned malformed JSON.");
851
+ }
852
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
853
+ throw new Error("Subagent readiness pipe returned an invalid result.");
854
+ }
855
+ const record = value as Record<string, unknown>;
856
+ if (
857
+ record.ok === true &&
858
+ Object.keys(record).length === 2 &&
859
+ Array.isArray(record.sources) &&
860
+ record.sources.length === expectedToolCount &&
861
+ record.sources.every((source) => typeof source === "string" && /^[a-f0-9]{64}$/u.test(source))
862
+ ) {
863
+ return { ok: true, sources: record.sources };
864
+ }
865
+ if (
866
+ record.ok === false &&
867
+ Object.keys(record).length === 2 &&
868
+ typeof record.error === "string" &&
869
+ record.error.length > 0 &&
870
+ Buffer.byteLength(record.error, "utf8") <= MAX_ERROR_BYTES
871
+ ) {
872
+ return { ok: false, error: sanitizeTerminalText(record.error) };
873
+ }
874
+ throw new Error("Subagent readiness pipe returned an invalid result.");
875
+ }
876
+
877
+ function redactAttachmentPaths(value: string, request: Pick<ChildRequest, "skills" | "extensions">): string {
878
+ return redactAttachmentPathVariants(value, attachmentPathVariants(request));
879
+ }
880
+
881
+ function redactAttachmentPathVariants(value: string, candidates: readonly string[]): string {
882
+ let redacted = value;
883
+ for (const candidate of candidates) redacted = redacted.replaceAll(candidate, "[attachment path]");
884
+ return redacted;
885
+ }
886
+
887
+ function attachmentPathCarryLength(value: string, candidates: readonly string[]): number {
888
+ const maximum = Math.min(
889
+ value.length,
890
+ candidates.reduce((length, candidate) => Math.max(length, candidate.length - 1), 0),
891
+ );
892
+ for (let length = maximum; length > 0; length--) {
893
+ const suffix = value.slice(-length);
894
+ if (candidates.some((candidate) => candidate.length > length && candidate.startsWith(suffix))) return length;
895
+ }
896
+ return 0;
897
+ }
898
+
899
+ function attachmentPathVariants(request: Pick<ChildRequest, "skills" | "extensions">): string[] {
900
+ const variants = new Set<string>();
901
+ const paths = [...request.skills, ...request.extensions.map((extension) => extension.path)];
902
+ for (const resourcePath of paths) {
903
+ for (const spelling of [resourcePath, resourcePath.replaceAll("\\", "/"), resourcePath.replaceAll("/", "\\")]) {
904
+ if (!spelling) continue;
905
+ variants.add(spelling);
906
+ variants.add(JSON.stringify(spelling).slice(1, -1));
907
+ }
908
+ }
909
+ return [...variants].sort((left, right) => right.length - left.length);
910
+ }
911
+
912
+ function combineErrors(...messages: Array<string | undefined>): { text: string; truncated: boolean } {
913
+ const unique = [...new Set(messages.filter((message): message is string => Boolean(message)))];
914
+ return truncateText(unique.join("\n"), MAX_ERROR_BYTES);
588
915
  }
589
916
 
590
917
  function abortError(message: string): Error {
591
- const error = new Error(message);
592
- error.name = "AbortError";
593
- return error;
918
+ const error = new Error(message);
919
+ error.name = "AbortError";
920
+ return error;
594
921
  }
595
922
 
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
- };
923
+ function cancelledResult(result?: string, limitations: string[] = [], truncated = false): ChildResult {
924
+ return {
925
+ state: "cancelled",
926
+ ...(result ? { result } : {}),
927
+ error: "Subagent execution was cancelled.",
928
+ limitations,
929
+ truncated,
930
+ };
608
931
  }
609
932
 
610
933
  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
- };
934
+ const bytes = Buffer.from(text, "utf8");
935
+ if (bytes.length <= maxBytes) return { text, truncated: false };
936
+ return {
937
+ text: `${bytes
938
+ .subarray(0, Math.max(0, maxBytes - 18))
939
+ .toString("utf8")
940
+ .replace(/�+$/gu, "")}\n… [truncated]`,
941
+ truncated: true,
942
+ };
620
943
  }
621
944
 
622
945
  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
- };
946
+ const bytes = Buffer.from(text, "utf8");
947
+ if (bytes.length <= maxBytes) return { text, truncated: false };
948
+ return {
949
+ text: `… [truncated]\n${bytes
950
+ .subarray(bytes.length - Math.max(0, maxBytes - 18))
951
+ .toString("utf8")
952
+ .replace(/^�+/gu, "")}`,
953
+ truncated: true,
954
+ };
632
955
  }
633
956
 
634
957
  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
- }
958
+ private buffer = "";
959
+ private dropping = false;
960
+ private readonly decoder = new StringDecoder("utf8");
961
+
962
+ constructor(
963
+ private readonly onValue: (value: unknown) => void,
964
+ private readonly onMalformed: () => void,
965
+ ) {}
966
+
967
+ push(chunk: Buffer | string): void {
968
+ this.buffer += typeof chunk === "string" ? chunk : this.decoder.write(chunk);
969
+ this.drain(false);
970
+ }
971
+
972
+ finish(): void {
973
+ this.buffer += this.decoder.end();
974
+ this.drain(true);
975
+ this.buffer = "";
976
+ this.dropping = false;
977
+ }
978
+
979
+ private drain(flush: boolean): void {
980
+ while (true) {
981
+ const newline = this.buffer.indexOf("\n");
982
+ if (newline < 0) break;
983
+ const line = this.buffer.slice(0, newline).replace(/\r$/u, "");
984
+ this.buffer = this.buffer.slice(newline + 1);
985
+ if (this.dropping) {
986
+ this.dropping = false;
987
+ continue;
988
+ }
989
+ this.parse(line);
990
+ }
991
+ if (!flush && Buffer.byteLength(this.buffer, "utf8") > MAX_EVENT_LINE_BYTES) {
992
+ this.onMalformed();
993
+ this.buffer = "";
994
+ this.dropping = true;
995
+ }
996
+ if (flush && this.buffer && !this.dropping) this.parse(this.buffer.replace(/\r$/u, ""));
997
+ }
998
+
999
+ private parse(line: string): void {
1000
+ if (!line.trim()) return;
1001
+ if (Buffer.byteLength(line, "utf8") > MAX_EVENT_LINE_BYTES) {
1002
+ this.onMalformed();
1003
+ return;
1004
+ }
1005
+ try {
1006
+ this.onValue(JSON.parse(line));
1007
+ } catch {
1008
+ this.onMalformed();
1009
+ }
1010
+ }
688
1011
  }