pi-crew 0.1.45 → 0.1.49

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.
Files changed (178) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/README.md +5 -5
  3. package/agents/analyst.md +11 -11
  4. package/agents/critic.md +11 -11
  5. package/agents/executor.md +11 -11
  6. package/agents/explorer.md +11 -11
  7. package/agents/planner.md +11 -11
  8. package/agents/reviewer.md +11 -11
  9. package/agents/security-reviewer.md +11 -11
  10. package/agents/test-engineer.md +11 -11
  11. package/agents/verifier.md +11 -11
  12. package/agents/writer.md +11 -11
  13. package/docs/next-upgrade-roadmap.md +808 -0
  14. package/docs/research/AGENT-EXECUTION-ARCHITECTURE.md +261 -0
  15. package/docs/research/AGENT-LIFECYCLE-COMPARISON.md +111 -0
  16. package/docs/research/AUDIT_OH_MY_PI.md +261 -0
  17. package/docs/research/AUDIT_PI_CREW.md +457 -0
  18. package/docs/research/CAVEMAN-DEEP-RESEARCH.md +281 -0
  19. package/docs/research/COMPARISON_OH_MY_PI_VS_PI_CREW.md +264 -0
  20. package/docs/research/DEEP-RESEARCH-PI-POWERBAR.md +343 -0
  21. package/docs/research/DEEP_RESEARCH_SUBAGENT_ARCHITECTURE.md +480 -0
  22. package/docs/research/GAP_CLOSURE_IMPLEMENTATION_PLAN.md +354 -0
  23. package/docs/research/IMPLEMENTATION_PLAN.md +385 -0
  24. package/docs/research/LIVE-SESSION-PRODUCTION-READY-PLAN.md +502 -0
  25. package/docs/research/OH-MY-PI-DEEP-RESEARCH-v14.7.6.md +266 -0
  26. package/docs/research/REMAINING-GAPS-PLAN.md +363 -0
  27. package/docs/research/SESSION-SUMMARY-2026-05-08.md +146 -0
  28. package/docs/research/UI-RESPONSIVENESS-AUDIT.md +173 -0
  29. package/docs/research-awesome-agent-skills-distillation.md +100 -0
  30. package/docs/research-oh-my-pi-distillation.md +369 -0
  31. package/docs/source-runtime-refactor-map.md +24 -0
  32. package/docs/usage.md +3 -3
  33. package/install.mjs +52 -8
  34. package/package.json +99 -98
  35. package/schema.json +10 -1
  36. package/skills/async-worker-recovery/SKILL.md +42 -0
  37. package/skills/context-artifact-hygiene/SKILL.md +52 -0
  38. package/skills/delegation-patterns/SKILL.md +54 -0
  39. package/skills/mailbox-interactive/SKILL.md +40 -0
  40. package/skills/model-routing-context/SKILL.md +39 -0
  41. package/skills/multi-perspective-review/SKILL.md +58 -0
  42. package/skills/observability-reliability/SKILL.md +41 -0
  43. package/skills/orchestration/SKILL.md +157 -0
  44. package/skills/ownership-session-security/SKILL.md +41 -0
  45. package/skills/pi-extension-lifecycle/SKILL.md +39 -0
  46. package/skills/requirements-to-task-packet/SKILL.md +63 -0
  47. package/skills/resource-discovery-config/SKILL.md +41 -0
  48. package/skills/runtime-state-reader/SKILL.md +44 -0
  49. package/skills/secure-agent-orchestration-review/SKILL.md +45 -0
  50. package/skills/state-mutation-locking/SKILL.md +42 -0
  51. package/skills/systematic-debugging/SKILL.md +67 -0
  52. package/skills/ui-render-performance/SKILL.md +39 -0
  53. package/skills/verification-before-done/SKILL.md +57 -0
  54. package/skills/worktree-isolation/SKILL.md +39 -0
  55. package/src/agents/agent-config.ts +6 -0
  56. package/src/agents/agent-search.ts +98 -0
  57. package/src/agents/agent-serializer.ts +38 -34
  58. package/src/agents/discover-agents.ts +29 -15
  59. package/src/config/config.ts +72 -24
  60. package/src/config/defaults.ts +25 -0
  61. package/src/extension/autonomous-policy.ts +26 -33
  62. package/src/extension/help.ts +1 -0
  63. package/src/extension/management.ts +5 -0
  64. package/src/extension/project-init.ts +62 -2
  65. package/src/extension/register.ts +69 -22
  66. package/src/extension/registration/commands.ts +64 -25
  67. package/src/extension/registration/compaction-guard.ts +1 -1
  68. package/src/extension/registration/subagent-helpers.ts +8 -0
  69. package/src/extension/registration/subagent-tools.ts +149 -148
  70. package/src/extension/registration/team-tool.ts +14 -10
  71. package/src/extension/run-index.ts +35 -21
  72. package/src/extension/run-maintenance.ts +30 -5
  73. package/src/extension/team-tool/api.ts +47 -9
  74. package/src/extension/team-tool/cancel.ts +109 -5
  75. package/src/extension/team-tool/context.ts +8 -0
  76. package/src/extension/team-tool/intent-policy.ts +42 -0
  77. package/src/extension/team-tool/lifecycle-actions.ts +120 -79
  78. package/src/extension/team-tool/parallel-dispatch.ts +156 -0
  79. package/src/extension/team-tool/respond.ts +46 -18
  80. package/src/extension/team-tool/run.ts +55 -12
  81. package/src/extension/team-tool/status.ts +13 -2
  82. package/src/extension/team-tool-types.ts +3 -0
  83. package/src/extension/team-tool.ts +45 -14
  84. package/src/hooks/registry.ts +61 -0
  85. package/src/hooks/types.ts +41 -0
  86. package/src/observability/event-to-metric.ts +8 -1
  87. package/src/runtime/agent-control.ts +169 -63
  88. package/src/runtime/async-runner.ts +3 -1
  89. package/src/runtime/background-runner.ts +78 -53
  90. package/src/runtime/cancellation-token.ts +89 -0
  91. package/src/runtime/cancellation.ts +61 -0
  92. package/src/runtime/capability-inventory.ts +116 -0
  93. package/src/runtime/child-pi.ts +458 -444
  94. package/src/runtime/code-summary.ts +247 -0
  95. package/src/runtime/crash-recovery.ts +182 -0
  96. package/src/runtime/crew-agent-records.ts +70 -10
  97. package/src/runtime/crew-agent-runtime.ts +1 -0
  98. package/src/runtime/custom-tools/irc-tool.ts +201 -0
  99. package/src/runtime/custom-tools/submit-result-tool.ts +90 -0
  100. package/src/runtime/deadletter.ts +1 -0
  101. package/src/runtime/delivery-coordinator.ts +48 -25
  102. package/src/runtime/effectiveness.ts +81 -0
  103. package/src/runtime/event-stream-bridge.ts +90 -0
  104. package/src/runtime/live-agent-control.ts +2 -1
  105. package/src/runtime/live-agent-manager.ts +179 -85
  106. package/src/runtime/live-control-realtime.ts +1 -1
  107. package/src/runtime/live-extension-bridge.ts +150 -0
  108. package/src/runtime/live-irc.ts +92 -0
  109. package/src/runtime/live-session-health.ts +100 -0
  110. package/src/runtime/live-session-runtime.ts +599 -305
  111. package/src/runtime/manifest-cache.ts +17 -2
  112. package/src/runtime/mcp-proxy.ts +113 -0
  113. package/src/runtime/model-fallback.ts +6 -4
  114. package/src/runtime/notebook-helpers.ts +90 -0
  115. package/src/runtime/orphan-sentinel.ts +7 -0
  116. package/src/runtime/output-validator.ts +187 -0
  117. package/src/runtime/parallel-utils.ts +57 -0
  118. package/src/runtime/parent-guard.ts +80 -0
  119. package/src/runtime/pi-args.ts +18 -3
  120. package/src/runtime/process-status.ts +5 -1
  121. package/src/runtime/prose-compressor.ts +164 -0
  122. package/src/runtime/result-extractor.ts +121 -0
  123. package/src/runtime/retry-executor.ts +81 -64
  124. package/src/runtime/runtime-resolver.ts +23 -10
  125. package/src/runtime/semaphore.ts +131 -0
  126. package/src/runtime/sensitive-paths.ts +92 -0
  127. package/src/runtime/skill-instructions.ts +222 -0
  128. package/src/runtime/stale-reconciler.ts +4 -14
  129. package/src/runtime/stream-preview.ts +177 -0
  130. package/src/runtime/subagent-manager.ts +6 -2
  131. package/src/runtime/subprocess-tool-registry.ts +67 -0
  132. package/src/runtime/task-output-context.ts +177 -127
  133. package/src/runtime/task-runner/capabilities.ts +78 -0
  134. package/src/runtime/task-runner/live-executor.ts +107 -101
  135. package/src/runtime/task-runner/prompt-builder.ts +72 -8
  136. package/src/runtime/task-runner/prompt-pipeline.ts +64 -0
  137. package/src/runtime/task-runner/run-projection.ts +104 -0
  138. package/src/runtime/task-runner.ts +115 -5
  139. package/src/runtime/team-runner.ts +134 -19
  140. package/src/runtime/workspace-tree.ts +298 -0
  141. package/src/runtime/yield-handler.ts +189 -0
  142. package/src/schema/config-schema.ts +7 -0
  143. package/src/schema/team-tool-schema.ts +14 -4
  144. package/src/skills/discover-skills.ts +67 -0
  145. package/src/state/active-run-registry.ts +167 -0
  146. package/src/state/artifact-store.ts +4 -1
  147. package/src/state/atomic-write.ts +50 -1
  148. package/src/state/blob-store.ts +117 -0
  149. package/src/state/contracts.ts +2 -1
  150. package/src/state/event-log-rotation.ts +158 -0
  151. package/src/state/event-log.ts +52 -2
  152. package/src/state/mailbox.ts +129 -9
  153. package/src/state/state-store.ts +32 -5
  154. package/src/state/types.ts +64 -2
  155. package/src/teams/team-config.ts +1 -0
  156. package/src/ui/agent-management-overlay.ts +144 -0
  157. package/src/ui/crew-widget.ts +15 -5
  158. package/src/ui/dashboard-panes/cancellation-pane.ts +43 -0
  159. package/src/ui/dashboard-panes/capability-pane.ts +60 -0
  160. package/src/ui/dashboard-panes/mailbox-pane.ts +35 -11
  161. package/src/ui/dashboard-panes/progress-pane.ts +2 -0
  162. package/src/ui/live-run-sidebar.ts +4 -0
  163. package/src/ui/powerbar-publisher.ts +77 -15
  164. package/src/ui/render-coalescer.ts +51 -0
  165. package/src/ui/run-dashboard.ts +4 -0
  166. package/src/ui/run-event-bus.ts +209 -0
  167. package/src/ui/run-snapshot-cache.ts +78 -18
  168. package/src/ui/snapshot-types.ts +10 -0
  169. package/src/ui/transcript-entries.ts +258 -0
  170. package/src/utils/ids.ts +5 -0
  171. package/src/utils/incremental-reader.ts +104 -0
  172. package/src/utils/paths.ts +4 -2
  173. package/src/utils/scan-cache.ts +137 -0
  174. package/src/utils/sse-parser.ts +134 -0
  175. package/src/utils/task-name-generator.ts +337 -0
  176. package/src/utils/visual.ts +33 -2
  177. package/src/workflows/workflow-config.ts +1 -0
  178. package/src/worktree/cleanup.ts +2 -1
@@ -1,444 +1,458 @@
1
- import { spawn, type ChildProcess, type SpawnOptions } from "node:child_process";
2
- import * as fs from "node:fs";
3
- import * as path from "node:path";
4
- import type { AgentConfig } from "../agents/agent-config.ts";
5
- import { buildPiWorkerArgs, checkCrewDepth, cleanupTempDir } from "./pi-args.ts";
6
- import { getPiSpawnCommand } from "./pi-spawn.ts";
7
- import { DEFAULT_CHILD_PI } from "../config/defaults.ts";
8
- import { logInternalError } from "../utils/internal-error.ts";
9
- import { attachPostExitStdioGuard, trySignalChild } from "./post-exit-stdio-guard.ts";
10
- import { redactJsonLine } from "../utils/redaction.ts";
11
-
12
- const POST_EXIT_STDIO_GUARD_MS = DEFAULT_CHILD_PI.postExitStdioGuardMs;
13
- const FINAL_DRAIN_MS = DEFAULT_CHILD_PI.finalDrainMs;
14
- const HARD_KILL_MS = DEFAULT_CHILD_PI.hardKillMs;
15
- const RESPONSE_TIMEOUT_MS = DEFAULT_CHILD_PI.responseTimeoutMs;
16
- const MAX_CAPTURE_BYTES = DEFAULT_CHILD_PI.maxCaptureBytes;
17
- const MAX_ASSISTANT_TEXT_CHARS = DEFAULT_CHILD_PI.maxAssistantTextChars;
18
- const MAX_TOOL_RESULT_CHARS = DEFAULT_CHILD_PI.maxToolResultChars;
19
- const MAX_TOOL_INPUT_CHARS = DEFAULT_CHILD_PI.maxToolInputChars;
20
- const MAX_COMPACT_CONTENT_CHARS = DEFAULT_CHILD_PI.maxCompactContentChars;
21
- const activeChildProcesses = new Map<number, ChildProcess>();
22
- const childHardKillTimers = new Map<number, NodeJS.Timeout>();
23
-
24
- function appendBoundedTail(current: string, chunk: string, maxBytes = MAX_CAPTURE_BYTES): string {
25
- const combined = current + chunk;
26
- if (Buffer.byteLength(combined, "utf-8") <= maxBytes) return combined;
27
- let tail = combined.slice(Math.max(0, combined.length - maxBytes));
28
- while (Buffer.byteLength(tail, "utf-8") > maxBytes) tail = tail.slice(1024);
29
- return `[pi-crew captured output truncated to last ${Math.round(maxBytes / 1024)} KiB]\n${tail}`;
30
- }
31
-
32
- function clearHardKillTimer(pid: number | undefined): void {
33
- if (!pid) return;
34
- const timer = childHardKillTimers.get(pid);
35
- if (!timer) return;
36
- clearTimeout(timer);
37
- childHardKillTimers.delete(pid);
38
- }
39
-
40
- function killProcessTree(pid: number | undefined, child?: ChildProcess): void {
41
- if (!pid || !Number.isInteger(pid) || pid <= 0) return;
42
- if (child && child.exitCode !== null) return;
43
- try {
44
- if (process.platform === "win32") {
45
- spawn("taskkill", ["/pid", String(pid), "/t", "/f"], { stdio: "ignore", windowsHide: true });
46
- return;
47
- }
48
- try {
49
- process.kill(-pid, "SIGTERM");
50
- } catch (error) {
51
- logInternalError("child-pi.sigterm", error, `pid=${pid}`);
52
- try {
53
- process.kill(pid, "SIGTERM");
54
- } catch (fallbackError) {
55
- logInternalError("child-pi.sigterm-absolute", fallbackError, `pid=${pid}`);
56
- }
57
- }
58
- clearHardKillTimer(pid);
59
- const hardKillTimer = setTimeout(() => {
60
- try {
61
- process.kill(-pid, "SIGKILL");
62
- } catch (error) {
63
- logInternalError("child-pi.sigkill", error, `pid=${pid}`);
64
- try {
65
- process.kill(pid, "SIGKILL");
66
- } catch (fallbackError) {
67
- logInternalError("child-pi.sigkill-absolute", fallbackError, `pid=${pid}`);
68
- }
69
- }
70
- childHardKillTimers.delete(pid);
71
- }, HARD_KILL_MS);
72
- hardKillTimer.unref();
73
- child?.once("exit", () => clearHardKillTimer(pid));
74
- childHardKillTimers.set(pid, hardKillTimer);
75
- } catch (error) {
76
- logInternalError("child-pi.kill-process-tree", error, `pid=${pid}`);
77
- }
78
- }
79
-
80
- export function terminateActiveChildPiProcesses(): number {
81
- const entries = [...activeChildProcesses.entries()];
82
- for (const [pid, child] of entries) killProcessTree(pid, child);
83
- return entries.length;
84
- }
85
-
86
- export interface ChildPiRunInput {
87
- cwd: string;
88
- task: string;
89
- agent: AgentConfig;
90
- model?: string;
91
- signal?: AbortSignal;
92
- transcriptPath?: string;
93
- onStdoutLine?: (line: string) => void;
94
- onJsonEvent?: (event: unknown) => void;
95
- onSpawn?: (pid: number) => void;
96
- maxDepth?: number;
97
- finalDrainMs?: number;
98
- hardKillMs?: number;
99
- responseTimeoutMs?: number;
100
- }
101
-
102
- export interface ChildPiRunResult {
103
- exitCode: number | null;
104
- stdout: string;
105
- stderr: string;
106
- error?: string;
107
- }
108
-
109
- export function buildChildPiSpawnOptions(cwd: string, env: NodeJS.ProcessEnv): SpawnOptions {
110
- return {
111
- cwd,
112
- env,
113
- stdio: ["ignore", "pipe", "pipe"],
114
- detached: process.platform !== "win32",
115
- windowsHide: true,
116
- };
117
- }
118
-
119
- function appendTranscript(input: ChildPiRunInput, line: string): void {
120
- if (!input.transcriptPath) return;
121
- fs.mkdirSync(path.dirname(input.transcriptPath), { recursive: true });
122
- fs.appendFileSync(input.transcriptPath, `${redactJsonLine(line)}\n`, "utf-8");
123
- }
124
-
125
- function compactString(value: string, maxChars = MAX_COMPACT_CONTENT_CHARS): string {
126
- if (value.length <= maxChars) return value;
127
- return `${value.slice(0, maxChars)}\n[pi-crew compacted ${value.length - maxChars} chars]`;
128
- }
129
-
130
- function compactValue(value: unknown): unknown {
131
- if (typeof value === "string") return compactString(value);
132
- if (Array.isArray(value)) return value.slice(0, 20).map(compactValue);
133
- const record = asRecord(value);
134
- if (!record) return value;
135
- const compacted: Record<string, unknown> = {};
136
- for (const [key, entry] of Object.entries(record).slice(0, 20)) compacted[key] = compactValue(entry);
137
- return compacted;
138
- }
139
-
140
- function compactContentPart(part: unknown): unknown | undefined {
141
- const record = asRecord(part);
142
- if (!record) return undefined;
143
- if (record.type === "text") return { type: "text", text: typeof record.text === "string" ? compactString(record.text, MAX_ASSISTANT_TEXT_CHARS) : "" };
144
- if (record.type === "toolCall") return { type: "toolCall", name: record.name, input: compactValue(typeof record.input === "string" ? compactString(record.input, MAX_TOOL_INPUT_CHARS) : record.input) };
145
- if (record.type === "toolResult") return { type: "toolResult", name: record.name, content: compactValue(typeof record.content === "string" ? compactString(record.content, MAX_TOOL_RESULT_CHARS) : record.content) };
146
- return undefined;
147
- }
148
-
149
- function compactChildPiEvent(event: unknown): unknown | undefined {
150
- const record = asRecord(event);
151
- if (!record) return undefined;
152
- if (record.type === "message_update") return undefined;
153
- if (record.type === "tool_execution_start" || record.type === "tool_execution_end") {
154
- return { type: record.type, toolName: record.toolName, args: record.args };
155
- }
156
- if (record.type === "tool_result_end" || record.type === "message_end" || record.type === "message") {
157
- const message = asRecord(record.message);
158
- if (message?.role === "user" || message?.role === "system") return undefined;
159
- const content = Array.isArray(message?.content) ? message.content.map(compactContentPart).filter((part) => part !== undefined) : undefined;
160
- return {
161
- type: record.type,
162
- ...(typeof record.text === "string" ? { text: record.text } : {}),
163
- ...(message ? { message: { role: message.role, ...(content ? { content } : {}), usage: message.usage, model: message.model, errorMessage: message.errorMessage, stopReason: message.stopReason } } : {}),
164
- usage: record.usage,
165
- model: record.model,
166
- provider: record.provider,
167
- stopReason: record.stopReason,
168
- };
169
- }
170
- return record.type ? { type: record.type } : undefined;
171
- }
172
-
173
- function displayTextFromCompactEvent(event: unknown): string | undefined {
174
- const record = asRecord(event);
175
- if (!record) return undefined;
176
- if (record.type === "tool_execution_start") {
177
- return typeof record.toolName === "string" ? `tool: ${record.toolName}` : "tool started";
178
- }
179
- if (record.type !== "message" && record.type !== "message_end") return undefined;
180
- const message = asRecord(record.message);
181
- if (message?.role !== undefined && message.role !== "assistant") return undefined;
182
- const content = Array.isArray(message?.content) ? message.content : [];
183
- const text = content.flatMap((part) => {
184
- const item = asRecord(part);
185
- return item?.type === "text" && typeof item.text === "string" ? [item.text] : [];
186
- }).join("\n").trim();
187
- return text || (typeof record.text === "string" ? record.text : undefined);
188
- }
189
-
190
- function compactChildPiLine(line: string): { persistedLine: string; event?: unknown; displayLine?: string; json: boolean } {
191
- try {
192
- const parsed = JSON.parse(line);
193
- const compact = compactChildPiEvent(parsed);
194
- return { json: true, event: compact, persistedLine: compact ? JSON.stringify(compact) : "", displayLine: displayTextFromCompactEvent(compact) };
195
- } catch {
196
- return { json: false, persistedLine: line, displayLine: line };
197
- }
198
- }
199
-
200
- export class ChildPiLineObserver {
201
- private buffer = "";
202
- private readonly input: ChildPiRunInput;
203
-
204
- constructor(input: ChildPiRunInput) {
205
- this.input = input;
206
- }
207
-
208
- observe(text: string): void {
209
- this.buffer += text;
210
- const lines = this.buffer.split(/\r?\n/);
211
- this.buffer = lines.pop() ?? "";
212
- for (const line of lines) this.emitLine(line);
213
- }
214
-
215
- flush(): void {
216
- if (!this.buffer) return;
217
- const line = this.buffer;
218
- this.buffer = "";
219
- this.emitLine(line);
220
- }
221
-
222
- private emitLine(line: string): void {
223
- if (!line.trim()) return;
224
- const compact = compactChildPiLine(line);
225
- if (compact.event !== undefined) {
226
- try {
227
- this.input.onJsonEvent?.(compact.event);
228
- } catch (error) {
229
- logInternalError("child-pi.on-json-event", error, `line=${compact.persistedLine ?? compact.displayLine ?? ""}`);
230
- }
231
- }
232
- if (compact.persistedLine) appendTranscript(this.input, compact.persistedLine);
233
- if (compact.displayLine?.trim()) {
234
- try {
235
- this.input.onStdoutLine?.(compact.displayLine);
236
- } catch (error) {
237
- logInternalError("child-pi.on-stdout-line", error, `line=${compact.displayLine}`);
238
- }
239
- }
240
- }
241
- }
242
-
243
- function observeStdoutChunk(input: ChildPiRunInput, text: string): void {
244
- const observer = new ChildPiLineObserver(input);
245
- observer.observe(text);
246
- observer.flush();
247
- }
248
-
249
- function asRecord(value: unknown): Record<string, unknown> | undefined {
250
- return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
251
- }
252
-
253
- function isFinalAssistantEvent(event: unknown): boolean {
254
- const obj = asRecord(event);
255
- if (!obj || obj.type !== "message_end") return false;
256
- const message = asRecord(obj.message);
257
- const role = message?.role;
258
- if (role !== undefined && role !== "assistant") return false;
259
- const stopReason = typeof message?.stopReason === "string" ? message.stopReason : typeof obj.stopReason === "string" ? obj.stopReason : undefined;
260
- if (stopReason !== undefined && stopReason !== "stop") return false;
261
- const content = Array.isArray(message?.content) ? message.content : [];
262
- return !content.some((part) => asRecord(part)?.type === "toolCall");
263
- }
264
-
265
- export async function runChildPi(input: ChildPiRunInput): Promise<ChildPiRunResult> {
266
- const depth = checkCrewDepth(input.maxDepth);
267
- if (depth.blocked) return { exitCode: 1, stdout: "", stderr: `pi-crew depth guard blocked child worker: depth ${depth.depth} >= max ${depth.maxDepth}` };
268
- const mock = process.env.PI_TEAMS_MOCK_CHILD_PI;
269
- if (mock) {
270
- if (mock === "success") {
271
- const stdout = `Mock child Pi success for ${input.agent.name}\n`;
272
- observeStdoutChunk(input, stdout);
273
- return { exitCode: 0, stdout, stderr: "" };
274
- }
275
- if (mock === "json-success" || mock === "adaptive-plan") {
276
- const text = mock === "adaptive-plan" && input.task.includes("ADAPTIVE_PLAN_JSON_START")
277
- ? `Adaptive mock plan\nADAPTIVE_PLAN_JSON_START\n${JSON.stringify({ phases: [{ name: "research", tasks: [{ role: "explorer", task: "Explore adaptive target" }, { role: "analyst", task: "Analyze adaptive target" }, { role: "planner", task: "Plan adaptive target" }] }, { name: "build", tasks: [{ role: "executor", task: "Implement adaptive target" }] }, { name: "check", tasks: [{ role: "reviewer", task: "Review adaptive target" }, { role: "test-engineer", task: "Test adaptive target" }, { role: "writer", task: "Summarize adaptive target" }] }] })}\nADAPTIVE_PLAN_JSON_END`
278
- : `Mock JSON success for ${input.agent.name}`;
279
- const stdout = `${JSON.stringify({ type: "message", message: { role: "assistant", content: [{ type: "text", text }] } })}\n${JSON.stringify({ type: "message_end", usage: { input: 10, output: 5, cost: 0.001, turns: 1 } })}\n`;
280
- observeStdoutChunk(input, stdout);
281
- return { exitCode: 0, stdout, stderr: "" };
282
- }
283
- if (mock === "retryable-failure") return { exitCode: 1, stdout: "", stderr: "rate limit: mock failure" };
284
- return { exitCode: 1, stdout: "", stderr: `mock failure: ${mock}` };
285
- }
286
- const built = buildPiWorkerArgs({ task: input.task, agent: input.agent, model: input.model, sessionEnabled: false, maxDepth: input.maxDepth });
287
- const spawnSpec = getPiSpawnCommand(built.args);
288
- try {
289
- return await new Promise<ChildPiRunResult>((resolve) => {
290
- const child = spawn(spawnSpec.command, spawnSpec.args, buildChildPiSpawnOptions(input.cwd, { ...process.env, ...built.env }));
291
- if (child.pid) {
292
- activeChildProcesses.set(child.pid, child);
293
- input.onSpawn?.(child.pid);
294
- }
295
- let stdout = "";
296
- let stderr = "";
297
- let settled = false;
298
- let childExited = false;
299
- let postExitGuardCleanup: (() => void) | undefined;
300
- let finalDrainTimer: NodeJS.Timeout | undefined;
301
- let hardKillTimer: NodeJS.Timeout | undefined;
302
- let noResponseTimer: NodeJS.Timeout | undefined;
303
- const finalDrainMs = input.finalDrainMs ?? FINAL_DRAIN_MS;
304
- const hardKillMs = input.hardKillMs ?? HARD_KILL_MS;
305
- const responseTimeoutEnv = Number.parseInt(process.env.PI_TEAMS_CHILD_RESPONSE_TIMEOUT_MS ?? "", 10);
306
- const responseTimeoutMs = Number.isFinite(responseTimeoutEnv) && responseTimeoutEnv >= 0 ? responseTimeoutEnv : input.responseTimeoutMs ?? RESPONSE_TIMEOUT_MS;
307
- let responseTimeoutHit = false;
308
- let forcedFinalDrain = false;
309
- const restartNoResponseTimer = (): void => {
310
- if (responseTimeoutMs <= 0) return;
311
- if (noResponseTimer) clearTimeout(noResponseTimer);
312
- noResponseTimer = setTimeout(() => {
313
- responseTimeoutHit = true;
314
- killProcessTree(child.pid, child);
315
- try {
316
- child.kill(process.platform === "win32" ? undefined : "SIGTERM");
317
- } catch (error) {
318
- logInternalError("child-pi.response-timeout-term", error, `pid=${child.pid}`);
319
- }
320
- }, responseTimeoutMs);
321
- noResponseTimer.unref();
322
- };
323
- const clearNoResponseTimer = (): void => {
324
- if (noResponseTimer) clearTimeout(noResponseTimer);
325
- noResponseTimer = undefined;
326
- };
327
- restartNoResponseTimer();
328
- const lineObserver = new ChildPiLineObserver({
329
- ...input,
330
- onStdoutLine: (line) => {
331
- restartNoResponseTimer();
332
- stdout = appendBoundedTail(stdout, `${line}\n`);
333
- input.onStdoutLine?.(line);
334
- },
335
- onJsonEvent: (event) => {
336
- restartNoResponseTimer();
337
- input.onJsonEvent?.(event);
338
- if (!isFinalAssistantEvent(event) || childExited || settled || finalDrainTimer) return;
339
- finalDrainTimer = setTimeout(() => {
340
- if (settled || childExited) return;
341
- forcedFinalDrain = true;
342
- try {
343
- child.kill(process.platform === "win32" ? undefined : "SIGTERM");
344
- } catch (error) {
345
- logInternalError("child-pi.final-drain-term", error, `pid=${child.pid}`);
346
- }
347
- hardKillTimer = setTimeout(() => {
348
- if (settled || childExited) return;
349
- try {
350
- child.kill(process.platform === "win32" ? undefined : "SIGKILL");
351
- } catch (error) {
352
- logInternalError("child-pi.final-drain-kill", error, `pid=${child.pid}`);
353
- }
354
- }, hardKillMs);
355
- hardKillTimer.unref();
356
- }, finalDrainMs);
357
- finalDrainTimer.unref();
358
- },
359
- });
360
-
361
- const clearFinalDrainTimers = (): void => {
362
- if (finalDrainTimer) clearTimeout(finalDrainTimer);
363
- if (hardKillTimer) clearTimeout(hardKillTimer);
364
- finalDrainTimer = undefined;
365
- hardKillTimer = undefined;
366
- };
367
- const clearPostExitGuard = (): void => {
368
- if (postExitGuardCleanup) {
369
- postExitGuardCleanup();
370
- postExitGuardCleanup = undefined;
371
- }
372
- };
373
- const clearChildPiTimeouts = (): void => {
374
- clearNoResponseTimer();
375
- clearFinalDrainTimers();
376
- clearPostExitGuard();
377
- };
378
-
379
- const settle = (result: ChildPiRunResult): void => {
380
- if (settled) return;
381
- settled = true;
382
- clearChildPiTimeouts();
383
- lineObserver.flush();
384
- input.signal?.removeEventListener("abort", abort);
385
- cleanupTempDir(built.tempDir);
386
- resolve(result);
387
- };
388
-
389
- const abort = (): void => {
390
- killProcessTree(child.pid, child);
391
- if (process.platform !== "win32") {
392
- trySignalChild(child, "SIGTERM");
393
- }
394
- try {
395
- child.kill(process.platform === "win32" ? undefined : "SIGTERM");
396
- } catch {
397
- // Ignore kill races.
398
- }
399
- };
400
-
401
- input.signal?.addEventListener("abort", abort, { once: true });
402
- child.stdout?.on("data", (chunk: Buffer) => {
403
- restartNoResponseTimer();
404
- lineObserver.observe(chunk.toString("utf-8"));
405
- });
406
- child.stderr?.on("data", (chunk: Buffer) => {
407
- restartNoResponseTimer();
408
- stderr = appendBoundedTail(stderr, chunk.toString("utf-8"));
409
- });
410
- child.on("error", (error) => {
411
- settle({ exitCode: null, stdout, stderr, error: error.message });
412
- });
413
- child.on("exit", () => {
414
- if (child.pid) {
415
- activeChildProcesses.delete(child.pid);
416
- clearHardKillTimer(child.pid);
417
- }
418
- childExited = true;
419
- clearNoResponseTimer();
420
- clearFinalDrainTimers();
421
- if (!postExitGuardCleanup) {
422
- postExitGuardCleanup = attachPostExitStdioGuard(child, {
423
- idleMs: POST_EXIT_STDIO_GUARD_MS,
424
- hardMs: HARD_KILL_MS,
425
- });
426
- }
427
- });
428
- child.on("close", (exitCode) => {
429
- if (child.pid) {
430
- activeChildProcesses.delete(child.pid);
431
- clearHardKillTimer(child.pid);
432
- }
433
- const timeoutError = responseTimeoutHit && !stderr.trim() ? { error: `Child Pi produced no new output for ${responseTimeoutMs}ms; process was terminated as unresponsive.` } : undefined;
434
- // A final assistant event is the child Pi contract for "the worker produced its answer".
435
- // Some Pi processes can linger during post-final cleanup/stdio shutdown; finalDrain terminates
436
- // that lingering process so the parent can continue, but it must not turn a completed
437
- // subagent answer into a failed task. Real pre-final response timeouts still report errors.
438
- settle({ exitCode: forcedFinalDrain && !timeoutError ? 0 : exitCode, stdout, stderr, ...(timeoutError ? { error: timeoutError.error } : {}) });
439
- });
440
- });
441
- } finally {
442
- cleanupTempDir(built.tempDir);
443
- }
444
- }
1
+ import { spawn, type ChildProcess, type SpawnOptions } from "node:child_process";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import type { AgentConfig } from "../agents/agent-config.ts";
5
+ import type { WorkerExitStatus } from "../state/types.ts";
6
+ import { buildPiWorkerArgs, checkCrewDepth, cleanupTempDir } from "./pi-args.ts";
7
+ import { getPiSpawnCommand } from "./pi-spawn.ts";
8
+ import { DEFAULT_CHILD_PI } from "../config/defaults.ts";
9
+ import { logInternalError } from "../utils/internal-error.ts";
10
+ import { attachPostExitStdioGuard, trySignalChild } from "./post-exit-stdio-guard.ts";
11
+ import { redactJsonLine } from "../utils/redaction.ts";
12
+
13
+ const POST_EXIT_STDIO_GUARD_MS = DEFAULT_CHILD_PI.postExitStdioGuardMs;
14
+ const FINAL_DRAIN_MS = DEFAULT_CHILD_PI.finalDrainMs;
15
+ const HARD_KILL_MS = DEFAULT_CHILD_PI.hardKillMs;
16
+ const RESPONSE_TIMEOUT_MS = DEFAULT_CHILD_PI.responseTimeoutMs;
17
+ const MAX_CAPTURE_BYTES = DEFAULT_CHILD_PI.maxCaptureBytes;
18
+ const MAX_ASSISTANT_TEXT_CHARS = DEFAULT_CHILD_PI.maxAssistantTextChars;
19
+ const MAX_TOOL_RESULT_CHARS = DEFAULT_CHILD_PI.maxToolResultChars;
20
+ const MAX_TOOL_INPUT_CHARS = DEFAULT_CHILD_PI.maxToolInputChars;
21
+ const MAX_COMPACT_CONTENT_CHARS = DEFAULT_CHILD_PI.maxCompactContentChars;
22
+ const activeChildProcesses = new Map<number, ChildProcess>();
23
+ const childHardKillTimers = new Map<number, NodeJS.Timeout>();
24
+
25
+ function appendBoundedTail(current: string, chunk: string, maxBytes = MAX_CAPTURE_BYTES): string {
26
+ const combined = current + chunk;
27
+ if (Buffer.byteLength(combined, "utf-8") <= maxBytes) return combined;
28
+ let tail = combined.slice(Math.max(0, combined.length - maxBytes));
29
+ while (Buffer.byteLength(tail, "utf-8") > maxBytes) tail = tail.slice(1024);
30
+ return `[pi-crew captured output truncated to last ${Math.round(maxBytes / 1024)} KiB]\n${tail}`;
31
+ }
32
+
33
+ function clearHardKillTimer(pid: number | undefined): void {
34
+ if (!pid) return;
35
+ const timer = childHardKillTimers.get(pid);
36
+ if (!timer) return;
37
+ clearTimeout(timer);
38
+ childHardKillTimers.delete(pid);
39
+ }
40
+
41
+ function killProcessTree(pid: number | undefined, child?: ChildProcess): void {
42
+ if (!pid || !Number.isInteger(pid) || pid <= 0) return;
43
+ if (child && child.exitCode !== null) return;
44
+ try {
45
+ if (process.platform === "win32") {
46
+ spawn("taskkill", ["/pid", String(pid), "/t", "/f"], { stdio: "ignore", windowsHide: true });
47
+ return;
48
+ }
49
+ try {
50
+ process.kill(-pid, "SIGTERM");
51
+ } catch (error) {
52
+ logInternalError("child-pi.sigterm", error, `pid=${pid}`);
53
+ try {
54
+ process.kill(pid, "SIGTERM");
55
+ } catch (fallbackError) {
56
+ logInternalError("child-pi.sigterm-absolute", fallbackError, `pid=${pid}`);
57
+ }
58
+ }
59
+ clearHardKillTimer(pid);
60
+ const hardKillTimer = setTimeout(() => {
61
+ try {
62
+ process.kill(-pid, "SIGKILL");
63
+ } catch (error) {
64
+ logInternalError("child-pi.sigkill", error, `pid=${pid}`);
65
+ try {
66
+ process.kill(pid, "SIGKILL");
67
+ } catch (fallbackError) {
68
+ logInternalError("child-pi.sigkill-absolute", fallbackError, `pid=${pid}`);
69
+ }
70
+ }
71
+ childHardKillTimers.delete(pid);
72
+ }, HARD_KILL_MS);
73
+ hardKillTimer.unref();
74
+ child?.once("exit", () => clearHardKillTimer(pid));
75
+ childHardKillTimers.set(pid, hardKillTimer);
76
+ } catch (error) {
77
+ logInternalError("child-pi.kill-process-tree", error, `pid=${pid}`);
78
+ }
79
+ }
80
+
81
+ export function terminateActiveChildPiProcesses(): number {
82
+ const entries = [...activeChildProcesses.entries()];
83
+ for (const [pid, child] of entries) killProcessTree(pid, child);
84
+ return entries.length;
85
+ }
86
+
87
+ export interface ChildPiRunInput {
88
+ cwd: string;
89
+ task: string;
90
+ agent: AgentConfig;
91
+ model?: string;
92
+ skillPaths?: string[];
93
+ signal?: AbortSignal;
94
+ transcriptPath?: string;
95
+ onStdoutLine?: (line: string) => void;
96
+ onJsonEvent?: (event: unknown) => void;
97
+ onSpawn?: (pid: number) => void;
98
+ maxDepth?: number;
99
+ finalDrainMs?: number;
100
+ hardKillMs?: number;
101
+ responseTimeoutMs?: number;
102
+ }
103
+
104
+ export interface ChildPiRunResult {
105
+ exitCode: number | null;
106
+ stdout: string;
107
+ stderr: string;
108
+ error?: string;
109
+ exitStatus?: WorkerExitStatus;
110
+ }
111
+
112
+ export function buildChildPiSpawnOptions(cwd: string, env: NodeJS.ProcessEnv): SpawnOptions {
113
+ return {
114
+ cwd,
115
+ env: { ...env, PI_CREW_PARENT_PID: String(process.pid) },
116
+ stdio: ["ignore", "pipe", "pipe"],
117
+ detached: process.platform !== "win32",
118
+ windowsHide: true,
119
+ };
120
+ }
121
+
122
+ function appendTranscript(input: ChildPiRunInput, line: string): void {
123
+ if (!input.transcriptPath) return;
124
+ fs.mkdirSync(path.dirname(input.transcriptPath), { recursive: true });
125
+ fs.appendFileSync(input.transcriptPath, `${redactJsonLine(line)}\n`, "utf-8");
126
+ }
127
+
128
+ function compactString(value: string, maxChars = MAX_COMPACT_CONTENT_CHARS): string {
129
+ if (value.length <= maxChars) return value;
130
+ return `${value.slice(0, maxChars)}\n[pi-crew compacted ${value.length - maxChars} chars]`;
131
+ }
132
+
133
+ function compactValue(value: unknown): unknown {
134
+ if (typeof value === "string") return compactString(value);
135
+ if (Array.isArray(value)) return value.slice(0, 20).map(compactValue);
136
+ const record = asRecord(value);
137
+ if (!record) return value;
138
+ const compacted: Record<string, unknown> = {};
139
+ for (const [key, entry] of Object.entries(record).slice(0, 20)) compacted[key] = compactValue(entry);
140
+ return compacted;
141
+ }
142
+
143
+ function compactContentPart(part: unknown): unknown | undefined {
144
+ const record = asRecord(part);
145
+ if (!record) return undefined;
146
+ if (record.type === "text") return { type: "text", text: typeof record.text === "string" ? compactString(record.text, MAX_ASSISTANT_TEXT_CHARS) : "" };
147
+ if (record.type === "toolCall") return { type: "toolCall", name: record.name, input: compactValue(typeof record.input === "string" ? compactString(record.input, MAX_TOOL_INPUT_CHARS) : record.input) };
148
+ if (record.type === "toolResult") return { type: "toolResult", name: record.name, content: compactValue(typeof record.content === "string" ? compactString(record.content, MAX_TOOL_RESULT_CHARS) : record.content) };
149
+ return undefined;
150
+ }
151
+
152
+ function compactChildPiEvent(event: unknown): unknown | undefined {
153
+ const record = asRecord(event);
154
+ if (!record) return undefined;
155
+ if (record.type === "message_update") return undefined;
156
+ if (record.type === "tool_execution_start" || record.type === "tool_execution_end") {
157
+ return { type: record.type, toolName: record.toolName, args: record.args };
158
+ }
159
+ if (record.type === "tool_result_end" || record.type === "message_end" || record.type === "message") {
160
+ const message = asRecord(record.message);
161
+ if (message?.role === "user" || message?.role === "system") return undefined;
162
+ const content = Array.isArray(message?.content) ? message.content.map(compactContentPart).filter((part) => part !== undefined) : undefined;
163
+ return {
164
+ type: record.type,
165
+ ...(typeof record.text === "string" ? { text: record.text } : {}),
166
+ ...(message ? { message: { role: message.role, ...(content ? { content } : {}), usage: message.usage, model: message.model, errorMessage: message.errorMessage, stopReason: message.stopReason } } : {}),
167
+ usage: record.usage,
168
+ model: record.model,
169
+ provider: record.provider,
170
+ stopReason: record.stopReason,
171
+ };
172
+ }
173
+ return record.type ? { type: record.type } : undefined;
174
+ }
175
+
176
+ function displayTextFromCompactEvent(event: unknown): string | undefined {
177
+ const record = asRecord(event);
178
+ if (!record) return undefined;
179
+ if (record.type === "tool_execution_start") {
180
+ return typeof record.toolName === "string" ? `tool: ${record.toolName}` : "tool started";
181
+ }
182
+ if (record.type !== "message" && record.type !== "message_end") return undefined;
183
+ const message = asRecord(record.message);
184
+ if (message?.role !== undefined && message.role !== "assistant") return undefined;
185
+ const content = Array.isArray(message?.content) ? message.content : [];
186
+ const text = content.flatMap((part) => {
187
+ const item = asRecord(part);
188
+ return item?.type === "text" && typeof item.text === "string" ? [item.text] : [];
189
+ }).join("\n").trim();
190
+ return text || (typeof record.text === "string" ? record.text : undefined);
191
+ }
192
+
193
+ function compactChildPiLine(line: string): { persistedLine: string; event?: unknown; displayLine?: string; json: boolean } {
194
+ try {
195
+ const parsed = JSON.parse(line);
196
+ const compact = compactChildPiEvent(parsed);
197
+ return { json: true, event: compact, persistedLine: compact ? JSON.stringify(compact) : "", displayLine: displayTextFromCompactEvent(compact) };
198
+ } catch {
199
+ return { json: false, persistedLine: line, displayLine: line };
200
+ }
201
+ }
202
+
203
+ export class ChildPiLineObserver {
204
+ private buffer = "";
205
+ private readonly input: ChildPiRunInput;
206
+
207
+ constructor(input: ChildPiRunInput) {
208
+ this.input = input;
209
+ }
210
+
211
+ observe(text: string): void {
212
+ this.buffer += text;
213
+ const lines = this.buffer.split(/\r?\n/);
214
+ this.buffer = lines.pop() ?? "";
215
+ for (const line of lines) this.emitLine(line);
216
+ }
217
+
218
+ flush(): void {
219
+ if (!this.buffer) return;
220
+ const line = this.buffer;
221
+ this.buffer = "";
222
+ this.emitLine(line);
223
+ }
224
+
225
+ private emitLine(line: string): void {
226
+ if (!line.trim()) return;
227
+ const compact = compactChildPiLine(line);
228
+ if (compact.event !== undefined) {
229
+ try {
230
+ this.input.onJsonEvent?.(compact.event);
231
+ } catch (error) {
232
+ logInternalError("child-pi.on-json-event", error, `line=${compact.persistedLine ?? compact.displayLine ?? ""}`);
233
+ }
234
+ }
235
+ if (compact.persistedLine) appendTranscript(this.input, compact.persistedLine);
236
+ if (compact.displayLine?.trim()) {
237
+ try {
238
+ this.input.onStdoutLine?.(compact.displayLine);
239
+ } catch (error) {
240
+ logInternalError("child-pi.on-stdout-line", error, `line=${compact.displayLine}`);
241
+ }
242
+ }
243
+ }
244
+ }
245
+
246
+ /** Mock-only path — real code path reuses a single observer. */
247
+ function observeStdoutChunk(input: ChildPiRunInput, text: string): void {
248
+ const observer = new ChildPiLineObserver(input);
249
+ observer.observe(text);
250
+ observer.flush();
251
+ }
252
+
253
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
254
+ return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
255
+ }
256
+
257
+ function isFinalAssistantEvent(event: unknown): boolean {
258
+ const obj = asRecord(event);
259
+ if (!obj || obj.type !== "message_end") return false;
260
+ const message = asRecord(obj.message);
261
+ const role = message?.role;
262
+ if (role !== undefined && role !== "assistant") return false;
263
+ const stopReason = typeof message?.stopReason === "string" ? message.stopReason : typeof obj.stopReason === "string" ? obj.stopReason : undefined;
264
+ if (stopReason !== undefined && stopReason !== "stop") return false;
265
+ const content = Array.isArray(message?.content) ? message.content : [];
266
+ return !content.some((part) => asRecord(part)?.type === "toolCall");
267
+ }
268
+
269
+ export async function runChildPi(input: ChildPiRunInput): Promise<ChildPiRunResult> {
270
+ const depth = checkCrewDepth(input.maxDepth);
271
+ if (depth.blocked) return { exitCode: 1, stdout: "", stderr: `pi-crew depth guard blocked child worker: depth ${depth.depth} >= max ${depth.maxDepth}` };
272
+ const mock = process.env.PI_TEAMS_MOCK_CHILD_PI;
273
+ if (mock) {
274
+ if (mock === "success") {
275
+ const stdout = `Mock child Pi success for ${input.agent.name}\n`;
276
+ observeStdoutChunk(input, stdout);
277
+ return { exitCode: 0, stdout, stderr: "" };
278
+ }
279
+ if (mock === "json-success" || mock === "adaptive-plan") {
280
+ const text = mock === "adaptive-plan" && input.task.includes("ADAPTIVE_PLAN_JSON_START")
281
+ ? `Adaptive mock plan\nADAPTIVE_PLAN_JSON_START\n${JSON.stringify({ phases: [{ name: "research", tasks: [{ role: "explorer", task: "Explore adaptive target" }, { role: "analyst", task: "Analyze adaptive target" }, { role: "planner", task: "Plan adaptive target" }] }, { name: "build", tasks: [{ role: "executor", task: "Implement adaptive target" }] }, { name: "check", tasks: [{ role: "reviewer", task: "Review adaptive target" }, { role: "test-engineer", task: "Test adaptive target" }, { role: "writer", task: "Summarize adaptive target" }] }] })}\nADAPTIVE_PLAN_JSON_END`
282
+ : `Mock JSON success for ${input.agent.name}`;
283
+ const stdout = `${JSON.stringify({ type: "message", message: { role: "assistant", content: [{ type: "text", text }] } })}\n${JSON.stringify({ type: "message_end", usage: { input: 10, output: 5, cost: 0.001, turns: 1 } })}\n`;
284
+ observeStdoutChunk(input, stdout);
285
+ return { exitCode: 0, stdout, stderr: "" };
286
+ }
287
+ if (mock === "retryable-failure") return { exitCode: 1, stdout: "", stderr: "rate limit: mock failure" };
288
+ return { exitCode: 1, stdout: "", stderr: `mock failure: ${mock}` };
289
+ }
290
+ const built = buildPiWorkerArgs({ task: input.task, agent: input.agent, model: input.model, sessionEnabled: false, maxDepth: input.maxDepth, skillPaths: input.skillPaths });
291
+ const spawnSpec = getPiSpawnCommand(built.args);
292
+ try {
293
+ return await new Promise<ChildPiRunResult>((resolve) => {
294
+ const child = spawn(spawnSpec.command, spawnSpec.args, buildChildPiSpawnOptions(input.cwd, { ...process.env, ...built.env }));
295
+ if (child.pid) {
296
+ activeChildProcesses.set(child.pid, child);
297
+ input.onSpawn?.(child.pid);
298
+ }
299
+ let stdout = "";
300
+ let stderr = "";
301
+ let settled = false;
302
+ let childExited = false;
303
+ let postExitGuardCleanup: (() => void) | undefined;
304
+ let finalDrainTimer: NodeJS.Timeout | undefined;
305
+ let hardKillTimer: NodeJS.Timeout | undefined;
306
+ let noResponseTimer: NodeJS.Timeout | undefined;
307
+ const finalDrainMs = input.finalDrainMs ?? FINAL_DRAIN_MS;
308
+ const hardKillMs = input.hardKillMs ?? HARD_KILL_MS;
309
+ const responseTimeoutEnv = Number.parseInt(process.env.PI_TEAMS_CHILD_RESPONSE_TIMEOUT_MS ?? "", 10);
310
+ const responseTimeoutMs = Number.isFinite(responseTimeoutEnv) && responseTimeoutEnv >= 0 ? responseTimeoutEnv : input.responseTimeoutMs ?? RESPONSE_TIMEOUT_MS;
311
+ let responseTimeoutHit = false;
312
+ let forcedFinalDrain = false;
313
+ let abortRequested = input.signal?.aborted === true;
314
+ let hardKilled = false;
315
+ const cleanupErrors: string[] = [];
316
+ const restartNoResponseTimer = (): void => {
317
+ if (responseTimeoutMs <= 0) return;
318
+ if (noResponseTimer) clearTimeout(noResponseTimer);
319
+ noResponseTimer = setTimeout(() => {
320
+ responseTimeoutHit = true;
321
+ killProcessTree(child.pid, child);
322
+ try {
323
+ child.kill(process.platform === "win32" ? undefined : "SIGTERM");
324
+ } catch (error) {
325
+ logInternalError("child-pi.response-timeout-term", error, `pid=${child.pid}`);
326
+ }
327
+ }, responseTimeoutMs);
328
+ noResponseTimer.unref();
329
+ };
330
+ const clearNoResponseTimer = (): void => {
331
+ if (noResponseTimer) clearTimeout(noResponseTimer);
332
+ noResponseTimer = undefined;
333
+ };
334
+ restartNoResponseTimer();
335
+ const lineObserver = new ChildPiLineObserver({
336
+ ...input,
337
+ onStdoutLine: (line) => {
338
+ restartNoResponseTimer();
339
+ stdout = appendBoundedTail(stdout, `${line}\n`);
340
+ input.onStdoutLine?.(line);
341
+ },
342
+ onJsonEvent: (event) => {
343
+ restartNoResponseTimer();
344
+ input.onJsonEvent?.(event);
345
+ if (!isFinalAssistantEvent(event) || childExited || settled || finalDrainTimer) return;
346
+ finalDrainTimer = setTimeout(() => {
347
+ if (settled || childExited) return;
348
+ forcedFinalDrain = true;
349
+ try {
350
+ child.kill(process.platform === "win32" ? undefined : "SIGTERM");
351
+ } catch (error) {
352
+ logInternalError("child-pi.final-drain-term", error, `pid=${child.pid}`);
353
+ }
354
+ hardKillTimer = setTimeout(() => {
355
+ if (settled || childExited) return;
356
+ try {
357
+ hardKilled = true;
358
+ child.kill(process.platform === "win32" ? undefined : "SIGKILL");
359
+ } catch (error) {
360
+ logInternalError("child-pi.final-drain-kill", error, `pid=${child.pid}`);
361
+ }
362
+ }, hardKillMs);
363
+ hardKillTimer.unref();
364
+ }, finalDrainMs);
365
+ finalDrainTimer.unref();
366
+ },
367
+ });
368
+
369
+ const clearFinalDrainTimers = (): void => {
370
+ if (finalDrainTimer) clearTimeout(finalDrainTimer);
371
+ if (hardKillTimer) clearTimeout(hardKillTimer);
372
+ finalDrainTimer = undefined;
373
+ hardKillTimer = undefined;
374
+ };
375
+ const clearPostExitGuard = (): void => {
376
+ if (postExitGuardCleanup) {
377
+ postExitGuardCleanup();
378
+ postExitGuardCleanup = undefined;
379
+ }
380
+ };
381
+ const clearChildPiTimeouts = (): void => {
382
+ clearNoResponseTimer();
383
+ clearFinalDrainTimers();
384
+ clearPostExitGuard();
385
+ };
386
+
387
+ const settle = (result: ChildPiRunResult): void => {
388
+ if (settled) return;
389
+ settled = true;
390
+ clearChildPiTimeouts();
391
+ lineObserver.flush();
392
+ input.signal?.removeEventListener("abort", abort);
393
+ try {
394
+ cleanupTempDir(built.tempDir);
395
+ } catch (error) {
396
+ cleanupErrors.push(error instanceof Error ? error.message : String(error));
397
+ }
398
+ resolve({ ...result, exitStatus: result.exitStatus ?? { exitCode: result.exitCode, cancelled: abortRequested, timedOut: responseTimeoutHit, killed: hardKilled, cleanupErrors, finalDrainMs } });
399
+ };
400
+
401
+ const abort = (): void => {
402
+ abortRequested = true;
403
+ killProcessTree(child.pid, child);
404
+ if (process.platform !== "win32") {
405
+ trySignalChild(child, "SIGTERM");
406
+ }
407
+ try {
408
+ child.kill(process.platform === "win32" ? undefined : "SIGTERM");
409
+ } catch {
410
+ // Ignore kill races.
411
+ }
412
+ };
413
+
414
+ input.signal?.addEventListener("abort", abort, { once: true });
415
+ child.stdout?.on("data", (chunk: Buffer) => {
416
+ restartNoResponseTimer();
417
+ lineObserver.observe(chunk.toString("utf-8"));
418
+ });
419
+ child.stderr?.on("data", (chunk: Buffer) => {
420
+ restartNoResponseTimer();
421
+ stderr = appendBoundedTail(stderr, chunk.toString("utf-8"));
422
+ });
423
+ child.on("error", (error) => {
424
+ settle({ exitCode: null, stdout, stderr, error: error.message });
425
+ });
426
+ child.on("exit", () => {
427
+ if (child.pid) {
428
+ activeChildProcesses.delete(child.pid);
429
+ clearHardKillTimer(child.pid);
430
+ }
431
+ childExited = true;
432
+ clearNoResponseTimer();
433
+ clearFinalDrainTimers();
434
+ if (!postExitGuardCleanup) {
435
+ postExitGuardCleanup = attachPostExitStdioGuard(child, {
436
+ idleMs: POST_EXIT_STDIO_GUARD_MS,
437
+ hardMs: HARD_KILL_MS,
438
+ });
439
+ }
440
+ });
441
+ child.on("close", (exitCode) => {
442
+ if (child.pid) {
443
+ activeChildProcesses.delete(child.pid);
444
+ clearHardKillTimer(child.pid);
445
+ }
446
+ const timeoutError = responseTimeoutHit && !stderr.trim() ? { error: `Child Pi produced no new output for ${responseTimeoutMs}ms; process was terminated as unresponsive.` } : undefined;
447
+ const finalExitCode = forcedFinalDrain && !timeoutError ? 0 : exitCode;
448
+ // A final assistant event is the child Pi contract for "the worker produced its answer".
449
+ // Some Pi processes can linger during post-final cleanup/stdio shutdown; finalDrain terminates
450
+ // that lingering process so the parent can continue, but it must not turn a completed
451
+ // subagent answer into a failed task. Real pre-final response timeouts still report errors.
452
+ settle({ exitCode: finalExitCode, stdout, stderr, ...(timeoutError ? { error: timeoutError.error } : {}), exitStatus: { exitCode: finalExitCode, cancelled: abortRequested, timedOut: responseTimeoutHit, killed: hardKilled, cleanupErrors, finalDrainMs } });
453
+ });
454
+ });
455
+ } finally {
456
+ cleanupTempDir(built.tempDir);
457
+ }
458
+ }