@xzzpig/pi-subagents 0.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.
Files changed (196) hide show
  1. package/CHANGELOG.md +1621 -0
  2. package/LICENSE +21 -0
  3. package/README.md +118 -0
  4. package/agents/delegate.md +14 -0
  5. package/agents/oracle.md +74 -0
  6. package/agents/researcher.md +52 -0
  7. package/agents/reviewer.md +79 -0
  8. package/agents/scout.md +50 -0
  9. package/agents/worker.md +58 -0
  10. package/index.ts +1 -0
  11. package/inspector-runner.mjs +11 -0
  12. package/install.mjs +93 -0
  13. package/package.json +105 -0
  14. package/prompts/gather-context-and-clarify.md +13 -0
  15. package/prompts/parallel-cleanup.md +59 -0
  16. package/prompts/parallel-research.md +50 -0
  17. package/prompts/parallel-review.md +54 -0
  18. package/prompts/review-loop.md +43 -0
  19. package/skills/pi-subagents/SKILL.md +41 -0
  20. package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
  21. package/skills/pi-subagents/references/execution-controls.md +428 -0
  22. package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
  23. package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
  24. package/src/agents/agent-management.ts +1256 -0
  25. package/src/agents/agent-memory.ts +254 -0
  26. package/src/agents/agent-refinements.ts +624 -0
  27. package/src/agents/agent-scope.ts +6 -0
  28. package/src/agents/agent-selection.ts +25 -0
  29. package/src/agents/agent-serializer.ts +163 -0
  30. package/src/agents/agents.ts +1889 -0
  31. package/src/agents/chain-serializer.ts +280 -0
  32. package/src/agents/frontmatter.ts +149 -0
  33. package/src/agents/identity.ts +30 -0
  34. package/src/agents/proactive-skills.ts +194 -0
  35. package/src/agents/skills.ts +761 -0
  36. package/src/api/background-work.ts +197 -0
  37. package/src/api/capability-ceiling.ts +17 -0
  38. package/src/api/control-channel.ts +4 -0
  39. package/src/api/delegation.ts +119 -0
  40. package/src/api/external-runs.ts +129 -0
  41. package/src/api/intercom-bridge.ts +3 -0
  42. package/src/api/pi-args.ts +5 -0
  43. package/src/api/preflight.ts +403 -0
  44. package/src/api/shared-types.ts +19 -0
  45. package/src/extension/config.ts +76 -0
  46. package/src/extension/control-notices.ts +58 -0
  47. package/src/extension/doctor.ts +230 -0
  48. package/src/extension/fanout-child.ts +201 -0
  49. package/src/extension/index.ts +805 -0
  50. package/src/extension/public-execution.ts +71 -0
  51. package/src/extension/rpc.ts +653 -0
  52. package/src/extension/schemas.ts +375 -0
  53. package/src/extension/steering-notices.ts +35 -0
  54. package/src/extension/tool-description.ts +164 -0
  55. package/src/inspectors/herdr/actions.ts +229 -0
  56. package/src/inspectors/herdr/client.ts +130 -0
  57. package/src/inspectors/herdr/inspector-runner.ts +141 -0
  58. package/src/inspectors/herdr/project-panes.ts +154 -0
  59. package/src/integrations/herdr-status.ts +330 -0
  60. package/src/intercom/intercom-bridge.ts +187 -0
  61. package/src/intercom/native-supervisor-channel.ts +715 -0
  62. package/src/intercom/result-intercom.ts +421 -0
  63. package/src/missions/actions.ts +410 -0
  64. package/src/missions/goal-driver.ts +162 -0
  65. package/src/missions/lifecycle.ts +346 -0
  66. package/src/missions/store.ts +507 -0
  67. package/src/missions/types.ts +157 -0
  68. package/src/missions/workflow-state.ts +250 -0
  69. package/src/policy/authority.ts +46 -0
  70. package/src/profiles/profiles.ts +661 -0
  71. package/src/runs/background/async-execution.ts +1574 -0
  72. package/src/runs/background/async-job-tracker.ts +511 -0
  73. package/src/runs/background/async-resume.ts +539 -0
  74. package/src/runs/background/async-status.ts +542 -0
  75. package/src/runs/background/auto-drain.ts +67 -0
  76. package/src/runs/background/chain-append.ts +328 -0
  77. package/src/runs/background/chain-root-attachment.ts +199 -0
  78. package/src/runs/background/completion-batcher.ts +168 -0
  79. package/src/runs/background/completion-dedupe.ts +54 -0
  80. package/src/runs/background/control-channel.ts +692 -0
  81. package/src/runs/background/fleet-view.ts +540 -0
  82. package/src/runs/background/notify.ts +332 -0
  83. package/src/runs/background/parallel-groups.ts +45 -0
  84. package/src/runs/background/process-terminal.ts +280 -0
  85. package/src/runs/background/result-watcher.ts +414 -0
  86. package/src/runs/background/retained-children.ts +68 -0
  87. package/src/runs/background/run-id-resolver.ts +167 -0
  88. package/src/runs/background/run-status.ts +504 -0
  89. package/src/runs/background/scheduled-runs.ts +753 -0
  90. package/src/runs/background/stale-run-reconciler.ts +396 -0
  91. package/src/runs/background/steering.ts +239 -0
  92. package/src/runs/background/subagent-runner.ts +4718 -0
  93. package/src/runs/background/subagent-wait.ts +661 -0
  94. package/src/runs/background/top-level-async.ts +14 -0
  95. package/src/runs/background/wait-completions.ts +112 -0
  96. package/src/runs/background/wait-config.ts +36 -0
  97. package/src/runs/background/wait-subscriptions.ts +253 -0
  98. package/src/runs/background/wait-tool.ts +34 -0
  99. package/src/runs/foreground/async-steering-action.ts +256 -0
  100. package/src/runs/foreground/async-stop-action.ts +65 -0
  101. package/src/runs/foreground/chain-clarify.ts +1354 -0
  102. package/src/runs/foreground/chain-execution.ts +1527 -0
  103. package/src/runs/foreground/execution.ts +1868 -0
  104. package/src/runs/foreground/foreground-control.ts +132 -0
  105. package/src/runs/foreground/subagent-executor.ts +5532 -0
  106. package/src/runs/shared/acceptance.ts +1365 -0
  107. package/src/runs/shared/agent-contract.ts +38 -0
  108. package/src/runs/shared/capability-ceiling.ts +209 -0
  109. package/src/runs/shared/chain-outputs.ts +118 -0
  110. package/src/runs/shared/child-protocol.ts +401 -0
  111. package/src/runs/shared/completion-guard.ts +95 -0
  112. package/src/runs/shared/context-mode.ts +44 -0
  113. package/src/runs/shared/dynamic-fanout.ts +297 -0
  114. package/src/runs/shared/external-cli-runner.ts +130 -0
  115. package/src/runs/shared/long-running-guard.ts +220 -0
  116. package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
  117. package/src/runs/shared/model-fallback.ts +336 -0
  118. package/src/runs/shared/model-scope.ts +128 -0
  119. package/src/runs/shared/nested-events.ts +1076 -0
  120. package/src/runs/shared/nested-path.ts +52 -0
  121. package/src/runs/shared/nested-render.ts +123 -0
  122. package/src/runs/shared/parallel-handoff.ts +238 -0
  123. package/src/runs/shared/parallel-utils.ts +256 -0
  124. package/src/runs/shared/permissions.ts +95 -0
  125. package/src/runs/shared/pi-args.ts +808 -0
  126. package/src/runs/shared/pi-spawn.ts +163 -0
  127. package/src/runs/shared/process-signal.ts +19 -0
  128. package/src/runs/shared/run-history.ts +181 -0
  129. package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
  130. package/src/runs/shared/session-lease.ts +299 -0
  131. package/src/runs/shared/single-output.ts +235 -0
  132. package/src/runs/shared/spawn-budget.ts +128 -0
  133. package/src/runs/shared/structured-output.ts +182 -0
  134. package/src/runs/shared/subagent-control.ts +231 -0
  135. package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
  136. package/src/runs/shared/subagent-startup-retry.ts +104 -0
  137. package/src/runs/shared/task-intent.ts +181 -0
  138. package/src/runs/shared/tool-availability.ts +83 -0
  139. package/src/runs/shared/tool-budget.ts +80 -0
  140. package/src/runs/shared/turn-budget.ts +98 -0
  141. package/src/runs/shared/usage-budget.ts +65 -0
  142. package/src/runs/shared/workflow-graph.ts +231 -0
  143. package/src/runs/shared/worktree.ts +759 -0
  144. package/src/shared/accessible-dir.ts +47 -0
  145. package/src/shared/artifacts.ts +285 -0
  146. package/src/shared/atomic-json.ts +61 -0
  147. package/src/shared/child-transcript.ts +264 -0
  148. package/src/shared/file-coalescer.ts +40 -0
  149. package/src/shared/file-system-retry.ts +47 -0
  150. package/src/shared/fork-context.ts +213 -0
  151. package/src/shared/formatters.ts +133 -0
  152. package/src/shared/jsonl-writer.ts +81 -0
  153. package/src/shared/launch-contract.ts +124 -0
  154. package/src/shared/model-info.ts +81 -0
  155. package/src/shared/post-exit-stdio-guard.ts +85 -0
  156. package/src/shared/session-identity.ts +10 -0
  157. package/src/shared/session-tokens.ts +44 -0
  158. package/src/shared/settings.ts +501 -0
  159. package/src/shared/status-format.ts +55 -0
  160. package/src/shared/types.ts +2069 -0
  161. package/src/shared/utils.ts +613 -0
  162. package/src/slash/delegation-adapters.ts +434 -0
  163. package/src/slash/delegation-json.ts +108 -0
  164. package/src/slash/delegation-request.ts +166 -0
  165. package/src/slash/prompt-template-bridge.ts +383 -0
  166. package/src/slash/prompt-workflows.ts +300 -0
  167. package/src/slash/selector.ts +147 -0
  168. package/src/slash/slash-bridge.ts +192 -0
  169. package/src/slash/slash-commands.ts +994 -0
  170. package/src/slash/slash-live-state.ts +296 -0
  171. package/src/slash/subagents-admin.ts +432 -0
  172. package/src/tui/fleet-status.ts +564 -0
  173. package/src/tui/fleet-transcript.ts +577 -0
  174. package/src/tui/fleet.ts +879 -0
  175. package/src/tui/render-helpers.ts +80 -0
  176. package/src/tui/render.ts +2029 -0
  177. package/src/types/pi-runtime-compat.d.ts +8 -0
  178. package/src/watchdog/change-signature.ts +220 -0
  179. package/src/watchdog/child-status.ts +205 -0
  180. package/src/watchdog/emission-guard.ts +123 -0
  181. package/src/watchdog/lsp-diagnostics.ts +537 -0
  182. package/src/watchdog/model-selection.ts +167 -0
  183. package/src/watchdog/permission-arbiter.ts +145 -0
  184. package/src/watchdog/register-child.ts +117 -0
  185. package/src/watchdog/register-main.ts +440 -0
  186. package/src/watchdog/render.ts +54 -0
  187. package/src/watchdog/review.ts +302 -0
  188. package/src/watchdog/runtime.ts +868 -0
  189. package/src/watchdog/scope.ts +62 -0
  190. package/src/watchdog/settings.ts +568 -0
  191. package/src/watchdog/tool-actions.ts +155 -0
  192. package/src/watchdog/turn-delta.ts +161 -0
  193. package/src/watchdog/types.ts +198 -0
  194. package/src/watchdog/warning-format.ts +73 -0
  195. package/src/workflows/chat-progress.ts +140 -0
  196. package/src/workflows/scripted-workflow.ts +506 -0
@@ -0,0 +1,613 @@
1
+ /**
2
+ * General utility functions for the subagent extension
3
+ */
4
+
5
+ import * as fs from "node:fs";
6
+ import * as os from "node:os";
7
+ import * as path from "node:path";
8
+ import type { Message } from "@earendil-works/pi-ai";
9
+ import { formatToolCall } from "./formatters.ts";
10
+ import type { AgentProgress, AsyncStatus, Details, DisplayItem, ErrorInfo, NestedRunSummary, SingleResult, ToolCallSummary, Usage } from "./types.ts";
11
+
12
+ // ============================================================================
13
+ // File System Utilities
14
+ // ============================================================================
15
+
16
+ const DEFAULT_CONFIG_DIR_NAME = ".pi";
17
+ const PI_CODING_AGENT_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
18
+ export const PI_CODING_AGENT_PACKAGE_ROOT_ENV = "PI_SUBAGENTS_PI_CODING_AGENT_PACKAGE_ROOT";
19
+
20
+ export function resolveWatchPath(
21
+ watchPath: string,
22
+ nativeRealpath: (filePath: string) => string = fs.realpathSync.native,
23
+ ): string {
24
+ // libuv's Windows watcher cannot mix 8.3 registration paths with long event paths.
25
+ try {
26
+ return nativeRealpath(watchPath);
27
+ } catch {
28
+ return watchPath;
29
+ }
30
+ }
31
+
32
+ function validConfigDirName(value: unknown): string | undefined {
33
+ return typeof value === "string" && value.trim() ? value : undefined;
34
+ }
35
+
36
+ function readConfigDirNameFromPackageRoot(packageRoot: string | undefined): string | undefined {
37
+ if (!packageRoot) return undefined;
38
+ try {
39
+ const pkg = JSON.parse(fs.readFileSync(path.join(packageRoot, "package.json"), "utf-8")) as {
40
+ name?: unknown;
41
+ piConfig?: { configDir?: unknown };
42
+ };
43
+ if (pkg.name !== PI_CODING_AGENT_PACKAGE_NAME) return undefined;
44
+ return validConfigDirName(pkg.piConfig?.configDir);
45
+ } catch {
46
+ return undefined;
47
+ }
48
+ }
49
+
50
+ function resolveConfigDirNameFromPackageJson(entryPoint = process.argv[1], packageRoot = process.env[PI_CODING_AGENT_PACKAGE_ROOT_ENV]): string | undefined {
51
+ const packageRootValue = readConfigDirNameFromPackageRoot(packageRoot);
52
+ if (packageRootValue) return packageRootValue;
53
+ if (!entryPoint) return undefined;
54
+ try {
55
+ let dir = path.dirname(fs.realpathSync(entryPoint));
56
+ while (dir !== path.dirname(dir)) {
57
+ const value = readConfigDirNameFromPackageRoot(dir);
58
+ if (value) return value;
59
+ dir = path.dirname(dir);
60
+ }
61
+ } catch {
62
+ // Package metadata lookup is best-effort; detached runners must not fail here.
63
+ }
64
+ return undefined;
65
+ }
66
+
67
+ export function resolveConfigDirName(codingAgentModule?: unknown, entryPoint?: string, packageRoot?: string): string {
68
+ const moduleValue = codingAgentModule && typeof codingAgentModule === "object"
69
+ ? validConfigDirName((codingAgentModule as { CONFIG_DIR_NAME?: unknown }).CONFIG_DIR_NAME)
70
+ : undefined;
71
+ return moduleValue
72
+ ?? resolveConfigDirNameFromPackageJson(entryPoint, packageRoot)
73
+ ?? DEFAULT_CONFIG_DIR_NAME;
74
+ }
75
+
76
+ let cachedConfigDirName: { entryPoint: string | undefined; packageRoot: string | undefined; value: string } | undefined;
77
+
78
+ export function getConfigDirName(): string {
79
+ const entryPoint = process.argv[1];
80
+ const packageRoot = process.env[PI_CODING_AGENT_PACKAGE_ROOT_ENV];
81
+ if (cachedConfigDirName
82
+ && cachedConfigDirName.entryPoint === entryPoint
83
+ && cachedConfigDirName.packageRoot === packageRoot) {
84
+ return cachedConfigDirName.value;
85
+ }
86
+ const value = resolveConfigDirName(undefined, entryPoint, packageRoot);
87
+ cachedConfigDirName = { entryPoint, packageRoot, value };
88
+ return value;
89
+ }
90
+
91
+ export function getProjectConfigDir(projectRoot: string): string {
92
+ return path.join(projectRoot, getConfigDirName());
93
+ }
94
+
95
+ export function getAgentDir(): string {
96
+ const configured = process.env.PI_CODING_AGENT_DIR;
97
+ if (configured === "~") return os.homedir();
98
+ if (configured?.startsWith("~/")) return path.join(os.homedir(), configured.slice(2));
99
+ return configured || path.join(os.homedir(), getConfigDirName(), "agent");
100
+ }
101
+
102
+ const statusCache = new Map<string, { mtime: number; ctime: number; size: number; ino: number; status: AsyncStatus }>();
103
+
104
+ function getErrorMessage(error: unknown): string {
105
+ return error instanceof Error ? error.message : String(error);
106
+ }
107
+
108
+ export function resolveChildCwd(baseCwd: string, childCwd: string | undefined): string {
109
+ if (!childCwd) return baseCwd;
110
+ return path.isAbsolute(childCwd) ? childCwd : path.resolve(baseCwd, childCwd);
111
+ }
112
+
113
+ function isNotFoundError(error: unknown): boolean {
114
+ return typeof error === "object"
115
+ && error !== null
116
+ && "code" in error
117
+ && (error as NodeJS.ErrnoException).code === "ENOENT";
118
+ }
119
+
120
+ /**
121
+ * Read async job status from disk (with mtime-based caching)
122
+ */
123
+ export function readStatus(asyncDir: string): AsyncStatus | null {
124
+ const statusPath = path.join(asyncDir, "status.json");
125
+
126
+ let stat: fs.Stats;
127
+ try {
128
+ stat = fs.statSync(statusPath);
129
+ } catch (error) {
130
+ if (isNotFoundError(error)) return null;
131
+ throw new Error(`Failed to inspect async status file '${statusPath}': ${getErrorMessage(error)}`, {
132
+ cause: error instanceof Error ? error : undefined,
133
+ });
134
+ }
135
+
136
+ const cached = statusCache.get(statusPath);
137
+ if (
138
+ cached
139
+ && cached.mtime === stat.mtimeMs
140
+ && cached.ctime === stat.ctimeMs
141
+ && cached.size === stat.size
142
+ && cached.ino === stat.ino
143
+ ) {
144
+ return cached.status;
145
+ }
146
+
147
+ let content: string;
148
+ try {
149
+ content = fs.readFileSync(statusPath, "utf-8");
150
+ } catch (error) {
151
+ if (isNotFoundError(error)) return null;
152
+ throw new Error(`Failed to read async status file '${statusPath}': ${getErrorMessage(error)}`, {
153
+ cause: error instanceof Error ? error : undefined,
154
+ });
155
+ }
156
+
157
+ let status: AsyncStatus;
158
+ try {
159
+ status = JSON.parse(content) as AsyncStatus;
160
+ } catch (error) {
161
+ throw new Error(`Failed to parse async status file '${statusPath}': ${getErrorMessage(error)}`, {
162
+ cause: error instanceof Error ? error : undefined,
163
+ });
164
+ }
165
+
166
+ statusCache.set(statusPath, {
167
+ mtime: stat.mtimeMs,
168
+ ctime: stat.ctimeMs,
169
+ size: stat.size,
170
+ ino: stat.ino,
171
+ status,
172
+ });
173
+ if (statusCache.size > 50) {
174
+ const firstKey = statusCache.keys().next().value;
175
+ if (firstKey) statusCache.delete(firstKey);
176
+ }
177
+ return status;
178
+ }
179
+
180
+ const outputTailCache = new Map<string, { mtime: number; size: number; lines: string[] }>();
181
+
182
+ /**
183
+ * Get the last N lines from an output file (with mtime/size-based caching)
184
+ */
185
+ function getOutputTail(outputFile: string | undefined, maxLines: number = 3): string[] {
186
+ if (!outputFile) return [];
187
+ let fd: number | null = null;
188
+ try {
189
+ const stat = fs.statSync(outputFile);
190
+ if (stat.size === 0) return [];
191
+
192
+ const cached = outputTailCache.get(outputFile);
193
+ if (cached && cached.mtime === stat.mtimeMs && cached.size === stat.size) {
194
+ return cached.lines;
195
+ }
196
+
197
+ const tailBytes = 4096;
198
+ const start = Math.max(0, stat.size - tailBytes);
199
+ fd = fs.openSync(outputFile, "r");
200
+ const buffer = Buffer.alloc(Math.min(tailBytes, stat.size));
201
+ fs.readSync(fd, buffer, 0, buffer.length, start);
202
+ const content = buffer.toString("utf-8");
203
+ const allLines = content.split("\n").filter((l) => l.trim());
204
+ const lines = allLines.slice(-maxLines).map((l) => l.slice(0, 120) + (l.length > 120 ? "..." : ""));
205
+
206
+ outputTailCache.set(outputFile, { mtime: stat.mtimeMs, size: stat.size, lines });
207
+ if (outputTailCache.size > 20) {
208
+ const firstKey = outputTailCache.keys().next().value;
209
+ if (firstKey) outputTailCache.delete(firstKey);
210
+ }
211
+
212
+ return lines;
213
+ } catch {
214
+ // Output tails are UI-only hints; unreadable or missing files should render as no tail.
215
+ return [];
216
+ } finally {
217
+ if (fd !== null) {
218
+ try {
219
+ fs.closeSync(fd);
220
+ } catch {
221
+ // Closing the best-effort tail file handle should not surface over the main status view.
222
+ }
223
+ }
224
+ }
225
+ }
226
+
227
+ /**
228
+ * Get human-readable last activity time for a file
229
+ */
230
+ export function getLastActivity(outputFile: string | undefined): string {
231
+ if (!outputFile) return "";
232
+ try {
233
+ const stat = fs.statSync(outputFile);
234
+ const ago = Date.now() - stat.mtimeMs;
235
+ if (ago < 1000) return "active now";
236
+ if (ago < 60000) return `active ${Math.floor(ago / 1000)}s ago`;
237
+ return `active ${Math.floor(ago / 60000)}m ago`;
238
+ } catch {
239
+ // Last-activity text is best effort; missing files should simply omit the hint.
240
+ return "";
241
+ }
242
+ }
243
+
244
+ /**
245
+ * Find the latest session file in a directory
246
+ */
247
+ export function findLatestSessionFile(sessionDir: string): string | null {
248
+ if (!fs.existsSync(sessionDir)) return null;
249
+ const files = fs.readdirSync(sessionDir)
250
+ .filter((f) => f.endsWith(".jsonl"))
251
+ .map((f) => {
252
+ const filePath = path.join(sessionDir, f);
253
+ return {
254
+ path: filePath,
255
+ mtime: fs.statSync(filePath).mtimeMs,
256
+ };
257
+ })
258
+ .sort((a, b) => b.mtime - a.mtime);
259
+ const latest = files[0];
260
+ return latest ? latest.path : null;
261
+ }
262
+
263
+ /**
264
+ * Write a prompt to a temporary file
265
+ */
266
+ function writePrompt(agent: string, prompt: string): { dir: string; path: string } {
267
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagent-"));
268
+ const p = path.join(dir, `${agent.replace(/[^\w.-]/g, "_")}.md`);
269
+ fs.writeFileSync(p, prompt, { mode: 0o600 });
270
+ return { dir, path: p };
271
+ }
272
+
273
+ // ============================================================================
274
+ // Message Parsing Utilities
275
+ // ============================================================================
276
+
277
+ /**
278
+ * Get the final text output from a list of messages
279
+ */
280
+ export function getFinalOutput(messages: Message[]): string {
281
+ const validTextParts: string[] = [];
282
+ for (let i = messages.length - 1; i >= 0; i--) {
283
+ const msg = messages[i];
284
+ if (!msg || msg.role !== "assistant") continue;
285
+ const hasAssistantError = ("errorMessage" in msg && typeof msg.errorMessage === "string" && msg.errorMessage.length > 0)
286
+ || ("stopReason" in msg && msg.stopReason === "error");
287
+ if (hasAssistantError) continue;
288
+ const messageText = msg.content
289
+ .filter((part) => part.type === "text" && part.text.trim().length > 0)
290
+ .map((part) => part.type === "text" ? part.text : "")
291
+ .join("\n");
292
+ for (let j = msg.content.length - 1; j >= 0; j--) {
293
+ const part = msg.content[j];
294
+ if (!part || part.type !== "text" || part.text.trim().length === 0) continue;
295
+ validTextParts.push(part.text);
296
+ if (/```acceptance[-_]report\s*\n[\s\S]*?```/i.test(part.text)) return messageText;
297
+ for (const match of part.text.matchAll(/```(?:json|jsonc|json5)\s*\n([\s\S]*?)```/gi)) {
298
+ const body = match[1] ?? "";
299
+ if (/"(?:criteriaSatisfied|criteria_satisfied)"/.test(body) && /"(?:changedFiles|changed_files|testsAddedOrUpdated|tests_added_or_updated|commandsRun|commands_run|validationOutput|validation_output|residualRisks|residual_risks|noStagedFiles|no_staged_files|diffSummary|diff_summary|reviewFindings|review_findings|manualNotes|manual_notes)"/.test(body)) {
300
+ return messageText;
301
+ }
302
+ }
303
+ if (/ACCEPTANCE_REPORT\s*:/i.test(part.text)) return messageText;
304
+ }
305
+ }
306
+ return validTextParts[0] ?? "";
307
+ }
308
+
309
+ export function getSingleResultOutput(result: Pick<SingleResult, "finalOutput" | "messages">): string {
310
+ return result.finalOutput ?? getFinalOutput(result.messages ?? []);
311
+ }
312
+
313
+ /**
314
+ * Extract display items (text and tool calls) from messages
315
+ */
316
+ export function getDisplayItems(messages: Message[] | undefined): DisplayItem[] {
317
+ if (!messages || messages.length === 0) return [];
318
+ const items: DisplayItem[] = [];
319
+ for (const msg of messages) {
320
+ if (msg.role === "assistant") {
321
+ for (const part of msg.content) {
322
+ if (part.type === "text") items.push({ type: "text", text: part.text });
323
+ else if (part.type === "toolCall") items.push({ type: "tool", name: part.name, args: part.arguments });
324
+ }
325
+ }
326
+ }
327
+ return items;
328
+ }
329
+
330
+ function compactCompletedProgress(progress: AgentProgress): AgentProgress {
331
+ if (progress.status === "running") return progress;
332
+ return {
333
+ index: progress.index,
334
+ agent: progress.agent,
335
+ status: progress.status,
336
+ activityState: progress.activityState,
337
+ task: progress.task,
338
+ skills: progress.skills,
339
+ toolCount: progress.toolCount,
340
+ tokens: progress.tokens,
341
+ durationMs: progress.durationMs,
342
+ error: progress.error,
343
+ failedTool: progress.failedTool,
344
+ recentTools: [],
345
+ recentOutput: [],
346
+ };
347
+ }
348
+
349
+ function extractToolCallSummaries(messages: Message[] | undefined): ToolCallSummary[] {
350
+ if (!messages?.length) return [];
351
+ const summaries: ToolCallSummary[] = [];
352
+ for (const msg of messages) {
353
+ if (msg.role !== "assistant") continue;
354
+ for (const part of msg.content) {
355
+ if (part.type !== "toolCall") continue;
356
+ const args = typeof part.arguments === "object" && part.arguments !== null && !Array.isArray(part.arguments)
357
+ ? part.arguments
358
+ : {};
359
+ summaries.push({
360
+ text: formatToolCall(part.name, args),
361
+ expandedText: formatToolCall(part.name, args, true),
362
+ });
363
+ }
364
+ }
365
+ return summaries;
366
+ }
367
+
368
+ export function sumResultsUsage(results: SingleResult[]): Usage {
369
+ const usage: Usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
370
+ for (const result of results) {
371
+ usage.input += result.usage.input;
372
+ usage.output += result.usage.output;
373
+ usage.cacheRead += result.usage.cacheRead;
374
+ usage.cacheWrite += result.usage.cacheWrite;
375
+ usage.cost += result.usage.cost;
376
+ usage.turns += result.usage.turns;
377
+ }
378
+ return usage;
379
+ }
380
+
381
+ function addNestedCost(total: NonNullable<Details["totalCost"]>, children: NestedRunSummary[] | undefined): void {
382
+ for (const child of children ?? []) {
383
+ if (child.totalCost) {
384
+ total.inputTokens += child.totalCost.inputTokens;
385
+ total.outputTokens += child.totalCost.outputTokens;
386
+ total.costUsd += child.totalCost.costUsd;
387
+ continue;
388
+ }
389
+ addNestedCost(total, child.children);
390
+ for (const step of child.steps ?? []) addNestedCost(total, step.children);
391
+ }
392
+ }
393
+
394
+ /** Sum input tokens, output tokens, and cost across a set of SingleResults. */
395
+ export function sumResultsCost(results: SingleResult[]): NonNullable<Details["totalCost"]> {
396
+ const total = { inputTokens: 0, outputTokens: 0, costUsd: 0 };
397
+ for (const result of results) {
398
+ total.inputTokens += result.usage.input;
399
+ total.outputTokens += result.usage.output;
400
+ total.costUsd += result.usage.cost;
401
+ addNestedCost(total, result.children);
402
+ }
403
+ return total;
404
+ }
405
+
406
+ export function compactForegroundResult(result: SingleResult): SingleResult {
407
+ if (result.progress?.status === "running") return result;
408
+ const toolCalls = result.toolCalls?.length ? result.toolCalls : extractToolCallSummaries(result.messages);
409
+ return {
410
+ ...result,
411
+ messages: undefined,
412
+ progress: undefined,
413
+ toolCalls: toolCalls.length ? toolCalls : undefined,
414
+ };
415
+ }
416
+
417
+ export function compactForegroundDetails(details: Details): Details {
418
+ return {
419
+ ...details,
420
+ results: details.results.map(compactForegroundResult),
421
+ progress: details.progress
422
+ ? details.progress.map(compactCompletedProgress)
423
+ : undefined,
424
+ };
425
+ }
426
+
427
+ /**
428
+ * Streaming counterparts to compactForegroundResult / compactCompletedProgress.
429
+ *
430
+ * The completed-compaction helpers above bail out while a child is still
431
+ * `running`, so a long or deeply nested fan-out streams full, unbounded progress on
432
+ * every tick. Pi serializes each streamed `tool_execution_update` as a single
433
+ * child-stdout line, which the parent reads under `MAX_CHILD_PENDING_LINE_BYTES`;
434
+ * an unbounded running snapshot can cross that cap and kill the child with
435
+ * `protocol_output_limit`.
436
+ *
437
+ * These bound the STREAMED snapshot only. The final returned result keeps the full
438
+ * live progress and message transcript, and every live-display consumer already
439
+ * reads just the last few entries (`recentTools.slice(-3)`, `recentOutput.slice(-5)`).
440
+ */
441
+ export const MAX_STREAMED_RECENT_TOOLS = 32;
442
+ export const MAX_STREAMED_TOOL_CALLS = 64;
443
+ export const MAX_STREAMED_OUTPUT_LINE_CHARS = 2000;
444
+
445
+ /** Keep only the most recent tool-history entries in a streamed snapshot. */
446
+ export function boundStreamedRecentTools(recentTools: AgentProgress["recentTools"]): AgentProgress["recentTools"] {
447
+ return recentTools.slice(-MAX_STREAMED_RECENT_TOOLS).map((tool) => ({ ...tool }));
448
+ }
449
+
450
+ /** Cap per-line length of recent output so one long line can't inflate a snapshot. */
451
+ export function boundStreamedRecentOutput(recentOutput: string[]): string[] {
452
+ return recentOutput.map((line) =>
453
+ line.length > MAX_STREAMED_OUTPUT_LINE_CHARS
454
+ ? `${line.slice(0, MAX_STREAMED_OUTPUT_LINE_CHARS)}… [truncated]`
455
+ : line,
456
+ );
457
+ }
458
+
459
+ /**
460
+ * Compact tool-call summaries for a streamed snapshot, standing in for the
461
+ * unbounded `messages` transcript. Prefers an existing `toolCalls` summary, else
462
+ * derives one from `messages`; bounded to the most recent calls.
463
+ */
464
+ export function boundStreamedToolCalls(result: Pick<SingleResult, "toolCalls" | "messages">): ToolCallSummary[] | undefined {
465
+ const summaries = result.toolCalls?.length ? result.toolCalls : extractToolCallSummaries(result.messages);
466
+ if (!summaries.length) return undefined;
467
+ return summaries.slice(-MAX_STREAMED_TOOL_CALLS).map((summary) => ({ ...summary }));
468
+ }
469
+
470
+ export function hasEmptyTerminalAssistantResponse(messages: Message[]): boolean {
471
+ const lastAssistant = messages.findLast((message) => message.role === "assistant");
472
+ return lastAssistant?.role === "assistant"
473
+ && Array.isArray(lastAssistant.content)
474
+ && lastAssistant.content.length === 0
475
+ && lastAssistant.usage.output === 0;
476
+ }
477
+
478
+ /**
479
+ * Detect errors in subagent execution from messages (only errors with no subsequent success)
480
+ */
481
+ export function detectSubagentError(messages: Message[]): ErrorInfo {
482
+ let lastAssistantTextIndex = -1;
483
+ for (let i = messages.length - 1; i >= 0; i--) {
484
+ const msg = messages[i];
485
+ if (msg?.role === "assistant") {
486
+ const hasText = Array.isArray(msg.content) && msg.content.some(
487
+ (c) => c.type === "text" && "text" in c && typeof c.text === "string" && c.text.trim().length > 0,
488
+ );
489
+ if (hasText) {
490
+ lastAssistantTextIndex = i;
491
+ break;
492
+ }
493
+ }
494
+ }
495
+
496
+ const scanStart = lastAssistantTextIndex >= 0 ? lastAssistantTextIndex + 1 : 0;
497
+
498
+ for (let i = messages.length - 1; i >= scanStart; i--) {
499
+ const msg = messages[i];
500
+ if (!msg || msg.role !== "toolResult") continue;
501
+ const toolName = "toolName" in msg && typeof msg.toolName === "string" ? msg.toolName : undefined;
502
+ const isError = "isError" in msg && msg.isError === true;
503
+
504
+ if (!isError) continue;
505
+
506
+ const text = msg.content.find((c) => c.type === "text");
507
+ const details = text && "text" in text ? text.text : undefined;
508
+ const exitMatch = details?.match(/exit(?:ed)?\s*(?:with\s*)?(?:code|status)?\s*[:\s]?\s*(\d+)/i);
509
+ const exitCodeText = exitMatch?.[1];
510
+ return {
511
+ hasError: true,
512
+ exitCode: exitCodeText ? parseInt(exitCodeText, 10) : 1,
513
+ errorType: toolName || "tool",
514
+ details: details?.slice(0, 200),
515
+ };
516
+ }
517
+
518
+ return { hasError: false };
519
+ }
520
+
521
+ /**
522
+ * Extract a preview of tool arguments for display
523
+ */
524
+ export function extractToolArgsPreview(args: Record<string, unknown>): string {
525
+ const truncatePreview = (value: string, maxLength: number): string =>
526
+ value.length > maxLength ? `${value.slice(0, maxLength - 3)}...` : value;
527
+
528
+ const stringifyPreviewValue = (value: unknown): string | undefined => {
529
+ if (typeof value === "string" && value.trim().length > 0) return value;
530
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
531
+ return undefined;
532
+ };
533
+
534
+ const previewArray = (value: unknown): string | undefined => {
535
+ if (!Array.isArray(value) || value.length === 0) return undefined;
536
+ const first = stringifyPreviewValue(value[0]);
537
+ if (!first) return undefined;
538
+ const suffix = value.length > 1 ? ` (+${value.length - 1} more)` : "";
539
+ return `${first}${suffix}`;
540
+ };
541
+
542
+ // Handle MCP tool calls - show server/tool info
543
+ if (args.tool && typeof args.tool === "string") {
544
+ const server = args.server && typeof args.server === "string" ? `${args.server}/` : "";
545
+ const toolArgs = args.args && typeof args.args === "string" ? ` ${args.args.slice(0, 40)}` : "";
546
+ return `${server}${args.tool}${toolArgs}`;
547
+ }
548
+
549
+ const queriesPreview = previewArray(args.queries);
550
+ if (queriesPreview) return truncatePreview(queriesPreview, 60);
551
+ if (typeof args.query === "string" && args.query.trim().length > 0) return truncatePreview(args.query, 60);
552
+ if (typeof args.workflow === "string" && args.workflow.trim().length > 0) return `workflow=${truncatePreview(args.workflow, 48)}`;
553
+
554
+ if (typeof args.url === "string" && args.url.trim().length > 0) return truncatePreview(args.url, 60);
555
+ const urlsPreview = previewArray(args.urls);
556
+ if (urlsPreview) return truncatePreview(urlsPreview, 60);
557
+ if (typeof args.prompt === "string" && args.prompt.trim().length > 0) return truncatePreview(args.prompt, 60);
558
+
559
+ const previewKeys = ["command", "path", "file_path", "pattern", "query", "url", "task", "describe", "search"];
560
+ for (const key of previewKeys) {
561
+ if (args[key] && typeof args[key] === "string") {
562
+ const value = args[key] as string;
563
+ return truncatePreview(value, 60);
564
+ }
565
+ }
566
+
567
+ // Fallback: show first string value found
568
+ for (const [key, value] of Object.entries(args)) {
569
+ const arrayPreview = previewArray(value);
570
+ if (arrayPreview) return `${key}=${truncatePreview(arrayPreview, 50)}`;
571
+ if (typeof value === "string" && value.length > 0) {
572
+ const preview = truncatePreview(value, 50);
573
+ return `${key}=${preview}`;
574
+ }
575
+ }
576
+ return "";
577
+ }
578
+
579
+ /**
580
+ * Extract text content from various message content formats
581
+ */
582
+ export function extractTextFromContent(content: unknown): string {
583
+ if (!content) return "";
584
+ // Handle string content directly
585
+ if (typeof content === "string") return content;
586
+ // Handle array content
587
+ if (!Array.isArray(content)) return "";
588
+ const texts: string[] = [];
589
+ for (const part of content) {
590
+ if (part && typeof part === "object") {
591
+ // Handle { type: "text", text: "..." }
592
+ if ("type" in part && part.type === "text" && "text" in part) {
593
+ texts.push(String(part.text));
594
+ }
595
+ // Handle { type: "tool_result", content: "..." }
596
+ else if ("type" in part && part.type === "tool_result" && "content" in part) {
597
+ const inner = extractTextFromContent(part.content);
598
+ if (inner) texts.push(inner);
599
+ }
600
+ // Handle { text: "..." } without type
601
+ else if ("text" in part) {
602
+ texts.push(String(part.text));
603
+ }
604
+ }
605
+ }
606
+ return texts.join("\n");
607
+ }
608
+
609
+ // ============================================================================
610
+ // Concurrency Utilities
611
+ // ============================================================================
612
+
613
+ export { mapConcurrent } from "../runs/shared/parallel-utils.ts";