@xzzpig/pi-subagents 0.8.0 → 0.9.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 (218) hide show
  1. package/CHANGELOG.md +443 -0
  2. package/README.md +2 -2
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +1 -1
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +151 -39
  12. package/docs/configuration.md +81 -22
  13. package/docs/extension-api.md +69 -14
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +32 -9
  16. package/docs/observability.md +22 -20
  17. package/docs/tool-reference.md +123 -14
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +142 -4
  20. package/install.mjs +1 -1
  21. package/package.json +5 -4
  22. package/prompts/review-loop.md +2 -2
  23. package/skills/council-mode/SKILL.md +48 -243
  24. package/skills/council-mode/references/pass-contracts.md +150 -0
  25. package/skills/pi-subagents/SKILL.md +89 -35
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
  27. package/skills/pi-subagents/references/execution-controls.md +91 -15
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
  31. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  32. package/src/agents/agent-management.ts +370 -114
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +12 -2
  35. package/src/agents/agents.ts +919 -372
  36. package/src/agents/builtin-names.ts +6 -0
  37. package/src/agents/runtime-agent-events.ts +70 -0
  38. package/src/agents/runtime-agent-registry.ts +31 -20
  39. package/src/api/agents.ts +10 -5
  40. package/src/api/background-work.ts +12 -3
  41. package/src/api/capability-ceiling.ts +0 -1
  42. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  43. package/src/api/delegation.ts +0 -7
  44. package/src/api/external-runs.ts +67 -4
  45. package/src/api/preflight.ts +48 -18
  46. package/src/api/shared-types.ts +6 -0
  47. package/src/extension/config.ts +90 -0
  48. package/src/extension/doctor.ts +5 -13
  49. package/src/extension/fanout-child.ts +14 -14
  50. package/src/extension/index.ts +115 -37
  51. package/src/extension/public-execution.ts +103 -15
  52. package/src/extension/rpc.ts +120 -25
  53. package/src/extension/schemas.ts +57 -21
  54. package/src/extension/tool-description.ts +48 -26
  55. package/src/inspectors/herdr/actions.ts +2 -1
  56. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  57. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  58. package/src/integrations/herdr-status.ts +51 -3
  59. package/src/intercom/native-supervisor-channel.ts +138 -60
  60. package/src/intercom/result-intercom.ts +2 -0
  61. package/src/intercom/supervisor-ui.ts +243 -0
  62. package/src/profiles/profiles.ts +5 -6
  63. package/src/runs/background/active-async-capacity.ts +103 -18
  64. package/src/runs/background/async-execution.ts +366 -128
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +45 -28
  67. package/src/runs/background/async-retention.ts +20 -3
  68. package/src/runs/background/async-status-snapshot.ts +23 -261
  69. package/src/runs/background/async-status.ts +189 -14
  70. package/src/runs/background/auto-drain.ts +1 -1
  71. package/src/runs/background/chain-append.ts +8 -3
  72. package/src/runs/background/chain-root-attachment.ts +74 -8
  73. package/src/runs/background/control-channel.ts +4 -205
  74. package/src/runs/background/fleet-view.ts +38 -22
  75. package/src/runs/background/inspect-rpc.ts +8 -8
  76. package/src/runs/background/notify.ts +238 -12
  77. package/src/runs/background/process-terminal.ts +16 -0
  78. package/src/runs/background/result-delivery-ownership.ts +45 -0
  79. package/src/runs/background/result-files.ts +28 -14
  80. package/src/runs/background/result-watcher.ts +39 -16
  81. package/src/runs/background/resume-guidance.ts +2 -2
  82. package/src/runs/background/retained-children.ts +1 -1
  83. package/src/runs/background/run-child-session.ts +613 -0
  84. package/src/runs/background/run-status.ts +84 -17
  85. package/src/runs/background/runner-aliases.ts +125 -0
  86. package/src/runs/background/runner-child-sessions.ts +31 -0
  87. package/src/runs/background/scheduled-runs.ts +174 -18
  88. package/src/runs/background/stale-run-reconciler.ts +10 -4
  89. package/src/runs/background/steering.ts +8 -15
  90. package/src/runs/background/subagent-runner.ts +676 -1161
  91. package/src/runs/background/subagent-wait.ts +86 -31
  92. package/src/runs/background/terminal-run-index.ts +1 -1
  93. package/src/runs/background/wait-completions.ts +43 -2
  94. package/src/runs/background/wait-config.ts +23 -9
  95. package/src/runs/background/wait-tool.ts +26 -19
  96. package/src/runs/foreground/async-steering-action.ts +3 -19
  97. package/src/runs/foreground/execution.ts +468 -499
  98. package/src/runs/foreground/foreground-control.ts +13 -0
  99. package/src/runs/foreground/foreground-history.ts +23 -1
  100. package/src/runs/foreground/subagent-executor.ts +1172 -400
  101. package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
  102. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  103. package/src/runs/shared/abort-recovery.ts +119 -0
  104. package/src/runs/shared/acceptance.ts +138 -36
  105. package/src/runs/shared/async-status-projection.ts +565 -0
  106. package/src/runs/shared/background-process-options.ts +9 -0
  107. package/src/runs/shared/capability-ceiling.ts +2 -2
  108. package/src/runs/shared/child-hooks.ts +25 -0
  109. package/src/runs/shared/child-identity.ts +32 -6
  110. package/src/runs/shared/child-launch-plan.ts +151 -0
  111. package/src/runs/shared/child-launch.ts +314 -0
  112. package/src/runs/shared/child-lifecycle.ts +25 -0
  113. package/src/runs/shared/child-runtime-config.ts +126 -0
  114. package/src/runs/shared/child-session.ts +342 -0
  115. package/src/runs/shared/child-tool-plan.ts +540 -0
  116. package/src/runs/shared/claude-code-adapter.ts +133 -0
  117. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  118. package/src/runs/shared/completion-evidence.ts +89 -0
  119. package/src/runs/shared/completion-guard.ts +6 -5
  120. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  121. package/src/runs/shared/dynamic-fanout.ts +3 -3
  122. package/src/runs/shared/external-cli-contract.ts +167 -0
  123. package/src/runs/shared/external-cli-preflight.ts +138 -0
  124. package/src/runs/shared/external-cli-runner.ts +348 -55
  125. package/src/runs/shared/fast-mode-extension.ts +5 -5
  126. package/src/runs/shared/host-step-status.ts +231 -0
  127. package/src/runs/shared/lane-metadata.ts +126 -0
  128. package/src/runs/shared/launch-cwd.ts +16 -0
  129. package/src/runs/shared/long-running-guard.ts +2 -1
  130. package/src/runs/shared/mcp-config-sources.ts +422 -0
  131. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  132. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  133. package/src/runs/shared/model-exclusions.ts +139 -9
  134. package/src/runs/shared/model-fallback.ts +142 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +38 -48
  137. package/src/runs/shared/nested-path.ts +0 -14
  138. package/src/runs/shared/nested-render.ts +9 -5
  139. package/src/runs/shared/orca-progress-tabs.ts +12 -7
  140. package/src/runs/shared/parallel-handoff.ts +423 -7
  141. package/src/runs/shared/parallel-utils.ts +15 -7
  142. package/src/runs/shared/permissions.ts +1 -14
  143. package/src/runs/shared/pi-spawn.ts +69 -35
  144. package/src/runs/shared/process-signal.ts +16 -0
  145. package/src/runs/shared/run-fanout-budget.ts +0 -13
  146. package/src/runs/shared/run-history.ts +21 -1
  147. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  148. package/src/runs/shared/single-output.ts +89 -22
  149. package/src/runs/shared/structured-output.ts +49 -9
  150. package/src/runs/shared/subagent-control.ts +6 -2
  151. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  152. package/src/runs/shared/task-intent.ts +21 -7
  153. package/src/runs/shared/tool-availability.ts +18 -62
  154. package/src/runs/shared/tool-budget.ts +0 -14
  155. package/src/runs/shared/tool-timeout.ts +1 -1
  156. package/src/runs/shared/workflow-graph.ts +16 -0
  157. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  158. package/src/runs/shared/worktree.ts +571 -62
  159. package/src/shared/atomic-json.ts +3 -1
  160. package/src/shared/child-session-name.ts +46 -0
  161. package/src/shared/extension-context.ts +24 -0
  162. package/src/shared/fork-context.ts +21 -12
  163. package/src/shared/fork-session-cwd.ts +27 -0
  164. package/src/shared/formatters.ts +18 -3
  165. package/src/shared/jsonl-writer.ts +11 -0
  166. package/src/shared/launch-contract.ts +8 -1
  167. package/src/shared/pruned-fork.ts +450 -0
  168. package/src/shared/session-file-trust.ts +19 -0
  169. package/src/shared/session-tokens.ts +14 -3
  170. package/src/shared/settings.ts +19 -105
  171. package/src/shared/shortcuts.ts +17 -0
  172. package/src/shared/thinking-ceiling.ts +0 -6
  173. package/src/shared/types.ts +524 -70
  174. package/src/shared/utils.ts +60 -93
  175. package/src/shared/workflow-child-permit.ts +207 -0
  176. package/src/slash/delegation-adapters.ts +1 -9
  177. package/src/slash/delegation-request.ts +0 -4
  178. package/src/slash/prompt-template-bridge.ts +37 -1
  179. package/src/slash/slash-bridge.ts +1 -2
  180. package/src/slash/slash-commands.ts +383 -116
  181. package/src/slash/slash-live-state.ts +22 -11
  182. package/src/slash/subagents-admin.ts +29 -12
  183. package/src/tui/fleet-native-transcript.ts +4 -0
  184. package/src/tui/fleet-status.ts +217 -82
  185. package/src/tui/fleet-transcript.ts +11 -5
  186. package/src/tui/fleet.ts +54 -28
  187. package/src/tui/render-helpers.ts +31 -0
  188. package/src/tui/render.ts +1429 -163
  189. package/src/watchdog/change-signature.ts +40 -1
  190. package/src/watchdog/child-status.ts +54 -34
  191. package/src/watchdog/diff-tool.ts +77 -0
  192. package/src/watchdog/emission-guard.ts +5 -3
  193. package/src/watchdog/guidance.ts +20 -0
  194. package/src/watchdog/register-child.ts +28 -25
  195. package/src/watchdog/register-main.ts +10 -9
  196. package/src/watchdog/render.ts +4 -5
  197. package/src/watchdog/review.ts +15 -4
  198. package/src/watchdog/rules.ts +70 -0
  199. package/src/watchdog/runtime.ts +75 -92
  200. package/src/watchdog/scope.ts +0 -11
  201. package/src/watchdog/settings.ts +48 -104
  202. package/src/watchdog/turn-delta.ts +1 -1
  203. package/src/watchdog/types.ts +18 -32
  204. package/src/watchdog/warning-format.ts +0 -1
  205. package/src/workflows/chat-progress.ts +7 -3
  206. package/src/workflows/host-command.ts +235 -0
  207. package/src/workflows/scripted-workflow.ts +988 -59
  208. package/src/workflows/workflow-checklist.ts +439 -0
  209. package/src/workflows/workflow-child-summary.ts +121 -0
  210. package/src/workflows/workflow-preflight.ts +297 -0
  211. package/src/workflows/workflow-receipt.ts +232 -6
  212. package/src/workflows/workflow-resources.ts +150 -0
  213. package/src/workflows/workflow-settlement.ts +246 -0
  214. package/src/runs/shared/child-protocol.ts +0 -401
  215. package/src/runs/shared/pi-args.ts +0 -935
  216. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  217. package/src/runs/shared/turn-budget.ts +0 -98
  218. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -18,6 +18,7 @@ import { readStatus } from "../../shared/utils.ts";
18
18
  import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
19
19
  import { contextModeLabel, summarizeContextModes } from "../shared/context-mode.ts";
20
20
  import { formatAsyncRunOutputPath, formatAsyncRunProgressLabel, listAsyncRuns, type AsyncRunSummary } from "./async-status.ts";
21
+ import { isTrustedRecordedSessionFile } from "../../shared/session-file-trust.ts";
21
22
 
22
23
  const DEFAULT_TRANSCRIPT_LINES = 80;
23
24
  const MAX_TRANSCRIPT_LINES = 500;
@@ -43,6 +44,8 @@ interface TranscriptOptions {
43
44
  index?: number;
44
45
  lines?: number;
45
46
  sessionRoots?: string[];
47
+ trustedSessionFiles?: string[];
48
+ trustedSessionFileRoot?: string;
46
49
  }
47
50
 
48
51
  interface TextTailResult {
@@ -69,6 +72,14 @@ function uniqueStrings(values: Array<string | undefined>): string[] {
69
72
  return result;
70
73
  }
71
74
 
75
+ function fleetChildDisplayName(child: { agent?: string; sessionName?: string }, fallback = "subagent"): string {
76
+ return child.sessionName?.trim() || child.agent || fallback;
77
+ }
78
+
79
+ function fleetStepDisplayName(step: Pick<AsyncJobStep, "agent" | "sessionName" | "label">): string {
80
+ return step.sessionName?.trim() || (step.label ? `${step.label} (${step.agent})` : step.agent);
81
+ }
82
+
72
83
  function resolveMaybeRelative(asyncDir: string, filePath: string | undefined): string | undefined {
73
84
  if (!filePath) return undefined;
74
85
  return path.resolve(asyncDir, filePath);
@@ -120,10 +131,13 @@ function readTextTail(filePath: string, maxLines: number): TextTailResult {
120
131
  }
121
132
  }
122
133
 
123
- function readContainedTextTail(filePath: string, maxLines: number, trustedRoots: string[], label: string): TextTailResult {
124
- if (trustedRoots.length === 0) return { path: filePath, lines: [], truncated: false, error: `Refusing to read ${label} transcript path without a trusted root: ${filePath}` };
134
+ function readContainedTextTail(filePath: string, maxLines: number, trustedRoots: string[], label: string, trustedFiles: string[] = [], trustedFileRoot?: string): TextTailResult {
135
+ if (trustedRoots.length === 0 && (!trustedFileRoot || trustedFiles.length === 0)) return { path: filePath, lines: [], truncated: false, error: `Refusing to read ${label} transcript path without a trusted root: ${filePath}` };
125
136
  const resolvedPath = path.resolve(filePath);
126
- if (!trustedRoots.some((root) => pathWithin(root, resolvedPath))) {
137
+ const recordedCandidate = trustedFileRoot
138
+ && pathWithin(trustedFileRoot, resolvedPath)
139
+ && trustedFiles.some((file) => path.resolve(file) === resolvedPath);
140
+ if (!trustedRoots.some((root) => pathWithin(root, resolvedPath)) && !recordedCandidate) {
127
141
  return { path: filePath, lines: [], truncated: false, error: `Refusing to read ${label} transcript path outside trusted roots: ${filePath}` };
128
142
  }
129
143
  let lstat: fs.Stats;
@@ -143,7 +157,7 @@ function readContainedTextTail(filePath: string, maxLines: number, trustedRoots:
143
157
  } catch (error) {
144
158
  return { path: filePath, lines: [], truncated: false, error: getErrorMessage(error) };
145
159
  }
146
- if (!realRoots.some((root) => pathWithin(root, realPath))) {
160
+ if (!realRoots.some((root) => pathWithin(root, realPath)) && !isTrustedRecordedSessionFile(realPath, trustedFiles, trustedFileRoot)) {
147
161
  return { path: filePath, lines: [], truncated: false, error: `Refusing to read ${label} transcript path outside trusted roots: ${filePath}` };
148
162
  }
149
163
  return readTextTail(resolvedPath, maxLines);
@@ -213,8 +227,8 @@ function sessionMessageLine(record: unknown): string | undefined {
213
227
 
214
228
  /** Structured session tail: parsed content parts, newest last, bounded by
215
229
  * maxMessages. Same trusted-root containment as the prose transcript tail. */
216
- export function readSessionMessagesTail(sessionFile: string, maxMessages: number, trustedRoots: string[]): { messages: SessionTranscriptMessage[]; warnings: string[]; truncated: boolean } {
217
- const tail = readContainedTextTail(sessionFile, Math.max(maxMessages * 4, maxMessages), trustedRoots, "session");
230
+ export function readSessionMessagesTail(sessionFile: string, maxMessages: number, trustedRoots: string[], trustedFiles: string[] = [], trustedFileRoot?: string): { messages: SessionTranscriptMessage[]; warnings: string[]; truncated: boolean } {
231
+ const tail = readContainedTextTail(sessionFile, Math.max(maxMessages * 4, maxMessages), trustedRoots, "session", trustedFiles, trustedFileRoot);
218
232
  const warnings: string[] = [];
219
233
  if (tail.error) warnings.push(`Session read failed for ${sessionFile}: ${tail.error}`);
220
234
  const parsedMessages: SessionTranscriptMessage[] = [];
@@ -235,8 +249,8 @@ export function readSessionMessagesTail(sessionFile: string, maxMessages: number
235
249
  return { messages, warnings, truncated: tail.truncated || parsedMessages.length > messages.length };
236
250
  }
237
251
 
238
- function readSessionTranscriptTail(sessionFile: string, maxLines: number, trustedRoots: string[]): { lines: string[]; warnings: string[] } {
239
- const tail = readContainedTextTail(sessionFile, Math.max(maxLines * 4, maxLines), trustedRoots, "session");
252
+ function readSessionTranscriptTail(sessionFile: string, maxLines: number, trustedRoots: string[], trustedFiles: string[] = [], trustedFileRoot?: string): { lines: string[]; warnings: string[] } {
253
+ const tail = readContainedTextTail(sessionFile, Math.max(maxLines * 4, maxLines), trustedRoots, "session", trustedFiles, trustedFileRoot);
240
254
  const warnings: string[] = [];
241
255
  if (tail.error) warnings.push(`Session read failed for ${sessionFile}: ${tail.error}`);
242
256
  const lines: string[] = [];
@@ -277,7 +291,8 @@ function formatActivityFacts(input: {
277
291
  }
278
292
 
279
293
  function foregroundModeName(control: ForegroundControl): string {
280
- if (control.mode === "single" && control.currentAgent) return control.currentAgent;
294
+ const currentDisplayName = control.sessionName?.trim() || control.currentAgent;
295
+ if (control.mode === "single" && currentDisplayName) return currentDisplayName;
281
296
  return control.mode;
282
297
  }
283
298
 
@@ -296,7 +311,8 @@ function formatForegroundFleetLines(controls: ForegroundControl[]): string[] {
296
311
  toolCount: control.toolCount,
297
312
  ...(control.tokens !== undefined ? { tokens: { total: control.tokens } } : {}),
298
313
  });
299
- const current = control.currentAgent ? ` | ${control.currentAgent}${control.currentIndex !== undefined ? ` #${control.currentIndex}` : ""}` : "";
314
+ const currentDisplayName = control.sessionName?.trim() || control.currentAgent;
315
+ const current = currentDisplayName ? ` | ${currentDisplayName}${control.currentIndex !== undefined ? ` #${control.currentIndex}` : ""}` : "";
300
316
  lines.push(`- ${control.runId} | running | ${foregroundModeName(control)}${current}${activity ? ` | ${activity}` : ""}`);
301
317
  lines.push(` status: subagent({ action: "status", id: "${control.runId}" })`);
302
318
  lines.push(" transcript: live in the expanded foreground result; persisted session transcript appears after completion when sessions are enabled.");
@@ -311,10 +327,10 @@ function formatDetachedForegroundFleetLines(runs: ForegroundRun[]): string[] {
311
327
  const ordered = [...runs].sort((left, right) => right.updatedAt - left.updatedAt);
312
328
  for (const run of ordered) {
313
329
  const detachedChildren = run.children.filter((child) => child.status === "detached");
314
- const childSummary = detachedChildren.map((child) => `${child.agent} #${child.index}`).join(", ");
330
+ const childSummary = detachedChildren.map((child) => `${fleetChildDisplayName(child)} #${child.index}`).join(", ");
315
331
  lines.push(`- ${run.runId} | detached | ${run.mode}${childSummary ? ` | ${childSummary}` : ""}`);
316
332
  lines.push(` status: subagent({ action: "status", id: "${run.runId}" })`);
317
- lines.push(` recovery: reply to the supervisor request first, then wait with subagent_wait({ id: "${run.runId}" }); do not resume or launch a replacement while any child remains detached.`);
333
+ lines.push(` recovery: reply to the supervisor request first, then wait with bg_wait({ id: "${run.runId}" }); do not resume or launch a replacement while any child remains detached.`);
318
334
  }
319
335
  return lines;
320
336
  }
@@ -332,7 +348,7 @@ function formatAsyncFleetLines(runs: AsyncRunSummary[]): string[] {
332
348
  lines.push(` status: subagent({ action: "status", id: "${run.id}" })`);
333
349
  lines.push(` transcript: subagent({ action: "status", id: "${run.id}", view: "transcript" })`);
334
350
  for (const step of run.steps) {
335
- const display = step.label ? `${step.label} (${step.agent})` : step.agent;
351
+ const display = fleetStepDisplayName(step);
336
352
  const stepContext = contextModeLabel(step.context);
337
353
  const phase = step.phase ? `[${step.phase}] ` : "";
338
354
  const stepActivity = formatActivityFacts(step);
@@ -429,7 +445,7 @@ function selectTranscriptStep(status: AsyncStatus, options: TranscriptOptions):
429
445
  }
430
446
  const step = selectedIndex !== undefined ? steps[selectedIndex] : undefined;
431
447
  const hint = options.index === undefined && steps.length > 1
432
- ? `Tip: pass index to inspect a specific child transcript (${steps.map((candidate, index) => `${index}=${candidate.agent}`).join(", ")}).`
448
+ ? `Tip: pass index to inspect a specific child transcript (${steps.map((candidate, index) => `${index}=${fleetChildDisplayName(candidate)}`).join(", ")}).`
433
449
  : undefined;
434
450
  return { index: selectedIndex, step, hint };
435
451
  }
@@ -439,7 +455,7 @@ function stepStateLine(mode: SubagentRunMode, index: number | undefined, step: A
439
455
  const modelThinking = formatModelThinking(step.model, step.thinking);
440
456
  const context = contextModeLabel(step.context);
441
457
  const parts = [
442
- `${mode === "parallel" ? "Agent" : "Step"}: ${index} (${step.agent})${context ? ` ${context}` : ""}`,
458
+ `${mode === "parallel" ? "Agent" : "Step"}: ${index} (${fleetChildDisplayName(step)})${context ? ` ${context}` : ""}`,
443
459
  step.status,
444
460
  formatActivityFacts(step),
445
461
  modelThinking,
@@ -523,7 +539,7 @@ export function formatAsyncRunTranscript(status: AsyncStatus, asyncDir: string,
523
539
  transcriptSource = "Recent output from status.json";
524
540
  }
525
541
  if (transcriptLines.length === 0 && sessionFile) {
526
- const sessionTail = readSessionTranscriptTail(sessionFile, lineLimit, options.sessionRoots ?? []);
542
+ const sessionTail = readSessionTranscriptTail(sessionFile, lineLimit, options.sessionRoots ?? [], options.trustedSessionFiles, options.trustedSessionFileRoot);
527
543
  transcriptLines = sessionTail.lines;
528
544
  warnings.push(...sessionTail.warnings);
529
545
  if (transcriptLines.length > 0) transcriptSource = `Session transcript tail from ${sessionFile}`;
@@ -547,14 +563,14 @@ export function formatNestedRunTranscript(run: NestedRunSummary, options: Transc
547
563
  `Nested run: ${run.id}`,
548
564
  `State: ${run.state}`,
549
565
  run.mode ? `Mode: ${run.mode}` : undefined,
550
- run.agent ? `Agent: ${run.agent}` : run.agents?.length ? `Agents: ${run.agents.join(", ")}` : undefined,
566
+ run.sessionName?.trim() ? `Agent: ${run.sessionName.trim()}` : run.agent ? `Agent: ${run.agent}` : run.agents?.length ? `Agents: ${run.agents.join(", ")}` : undefined,
551
567
  ].filter((line): line is string => Boolean(line));
552
568
  appendKnownArtifacts(lines, { outputPaths: [], sessionFile: run.sessionFile });
553
569
  if (!run.sessionFile) {
554
570
  appendTranscriptBody(lines, "Transcript tail", [], false);
555
571
  return safeTranscriptLines(lines);
556
572
  }
557
- const sessionTail = readSessionTranscriptTail(run.sessionFile, lineLimit, options.sessionRoots ?? []);
573
+ const sessionTail = readSessionTranscriptTail(run.sessionFile, lineLimit, options.sessionRoots ?? [], options.trustedSessionFiles, options.trustedSessionFileRoot);
558
574
  if (sessionTail.warnings.length) {
559
575
  lines.push("Warnings:");
560
576
  for (const warning of sessionTail.warnings) lines.push(` ${warning}`);
@@ -573,14 +589,14 @@ export function formatAsyncResultTranscript(data: {
573
589
  sessionFile?: string;
574
590
  agent?: string;
575
591
  exitCode?: number | null;
576
- results?: Array<{ agent?: string; output?: string; summary?: string; sessionFile?: string; state?: string; success?: boolean; exitCode?: number | null }>;
592
+ results?: Array<{ agent?: string; sessionName?: string; output?: string; summary?: string; sessionFile?: string; state?: string; success?: boolean; exitCode?: number | null }>;
577
593
  }, resultPath: string, options: TranscriptOptions = {}): string {
578
594
  const lineLimit = transcriptLineLimit(options.lines);
579
595
  const runId = data.runId ?? data.id ?? path.basename(resultPath, ".json");
580
596
  const children = Array.isArray(data.results)
581
597
  ? data.results
582
598
  : data.agent
583
- ? [{ agent: data.agent, output: data.output, summary: data.summary, sessionFile: data.sessionFile, state: data.state, success: data.success, exitCode: data.exitCode }]
599
+ ? [{ agent: data.agent, sessionName: undefined, output: data.output, summary: data.summary, sessionFile: data.sessionFile, state: data.state, success: data.success, exitCode: data.exitCode }]
584
600
  : [];
585
601
  let index = options.index;
586
602
  if (index !== undefined && !Number.isInteger(index)) throw new Error("Transcript index must be an integer.");
@@ -595,8 +611,8 @@ export function formatAsyncResultTranscript(data: {
595
611
  const lines = [
596
612
  `Run: ${runId}`,
597
613
  `State: ${data.state ?? (data.success ? "complete" : "failed")}`,
598
- index !== undefined && child ? `Child: ${index} (${child.agent ?? "subagent"})` : undefined,
599
- index === undefined && children.length > 1 ? `Tip: pass index to inspect a specific child transcript (${children.map((candidate, childIndex) => `${childIndex}=${candidate.agent ?? "subagent"}`).join(", ")}).` : undefined,
614
+ index !== undefined && child ? `Child: ${index} (${fleetChildDisplayName(child)})` : undefined,
615
+ index === undefined && children.length > 1 ? `Tip: pass index to inspect a specific child transcript (${children.map((candidate, childIndex) => `${childIndex}=${fleetChildDisplayName(candidate)}`).join(", ")}).` : undefined,
600
616
  ].filter((line): line is string => Boolean(line));
601
617
  appendKnownArtifacts(lines, { outputPaths: [], sessionFile, resultPath });
602
618
  appendTranscriptBody(lines, "Result transcript tail", transcriptLines.filter((line) => line.trim()), output.split(/\r?\n/).length > lineLimit);
@@ -218,19 +218,19 @@ function readOutputArtifact(outputPath: string): { output?: string; errorText?:
218
218
  }
219
219
  }
220
220
 
221
- function readSessionBackedOutput(sessionPath: string, trustedRoots: string[]): { output?: string } {
222
- if (trustedRoots.length === 0) return {};
221
+ function readSessionBackedOutput(sessionPath: string, trustedRoots: string[], trustedSessionFileRoot?: string): { output?: string } {
222
+ if (trustedRoots.length === 0 && !trustedSessionFileRoot) return {};
223
223
  // The archive retains the child's session file as its output record. The
224
224
  // final answer is the terminal assistant message's text — all text parts
225
225
  // of that one session record, not just the last part.
226
- const tail = readSessionMessagesTail(sessionPath, MAX_MESSAGE_LINES, trustedRoots);
226
+ const tail = readSessionMessagesTail(sessionPath, MAX_MESSAGE_LINES, trustedRoots, [sessionPath], trustedSessionFileRoot);
227
227
  const last = tail.messages.findLast((message) => message.role === "assistant" && message.kind === "text");
228
228
  if (!last) return {};
229
229
  const parts = tail.messages.filter((message) => message.recordIndex === last.recordIndex && message.kind === "text");
230
230
  return { output: parts.map((part) => part.text).join("\n") };
231
231
  }
232
232
 
233
- function readResultOutput(resultsDir: string, sessionId: string, runId: string, stepIndex: number | undefined, trustedRoots: string[], stepAgent: string | undefined, now: () => number): { output?: string; errorText?: string } {
233
+ function readResultOutput(resultsDir: string, sessionId: string, runId: string, stepIndex: number | undefined, trustedRoots: string[], stepAgent: string | undefined, now: () => number, trustedSessionFileRoot?: string): { output?: string; errorText?: string } {
234
234
  const resultPath = resultPayloadPathForSessionRun(resultsDir, sessionId, runId);
235
235
  if (resultPath) return resultOutput(JSON.parse(fs.readFileSync(resultPath, "utf-8")) as unknown, stepIndex);
236
236
  // Read the raw record first: readCompletionReplay best-effort deletes
@@ -284,7 +284,7 @@ function readResultOutput(resultsDir: string, sessionId: string, runId: string,
284
284
  if (artifactPath) return readOutputArtifact(artifactPath);
285
285
  const sessionEntry = archive?.entries.find((entry) => entry.source === "session" && matches(entry));
286
286
  const sessionPath = sessionEntry?.source === "session" ? sessionEntry.path : undefined;
287
- if (sessionPath) return readSessionBackedOutput(sessionPath, trustedRoots);
287
+ if (sessionPath) return readSessionBackedOutput(sessionPath, trustedRoots, trustedSessionFileRoot);
288
288
  const output = archive?.entries.find((entry) => entry.source === "result-tail" && matches(entry))?.text;
289
289
  return output ? { output } : {};
290
290
  }
@@ -377,8 +377,8 @@ export function buildInspectReply(request: InspectRequest, deps: InspectDeps = {
377
377
 
378
378
  let messages: InspectReplyMessage[] | undefined;
379
379
  let task: string | undefined;
380
- if (sessionFile && trustedRoots.length > 0) {
381
- const tail = readSessionMessagesTail(sessionFile, lineLimit, trustedRoots);
380
+ if (sessionFile && (trustedRoots.length > 0 || deps.state?.trustedSessionFileRoot)) {
381
+ const tail = readSessionMessagesTail(sessionFile, lineLimit, trustedRoots, [sessionFile], deps.state?.trustedSessionFileRoot);
382
382
  if (tail.messages.length > 0) {
383
383
  messages = tail.messages.map(toReplyMessage);
384
384
  // The delegated task is the child session's first user message, but
@@ -393,7 +393,7 @@ export function buildInspectReply(request: InspectRequest, deps: InspectDeps = {
393
393
  }
394
394
  }
395
395
 
396
- const result = readResultOutput(resultsDir, currentSessionId, node.status.runId, node.stepIndex, trustedRoots, step?.agent, deps.now ?? Date.now);
396
+ const result = readResultOutput(resultsDir, currentSessionId, node.status.runId, node.stepIndex, trustedRoots, step?.agent, deps.now ?? Date.now, deps.state?.trustedSessionFileRoot);
397
397
  const failedText = step?.error ?? node.status.error;
398
398
  if (result.output === undefined && result.errorText === undefined && failedText !== undefined) {
399
399
  return errorReply(request, "internal", "Inspection could not read the async run artifacts.");
@@ -14,8 +14,24 @@ import {
14
14
  createCompletionBatcher,
15
15
  resolveCompletionBatchConfig,
16
16
  } from "./completion-batcher.ts";
17
- import { SUBAGENT_ASYNC_COMPLETE_EVENT, SUBAGENT_FOREGROUND_COMPLETE_EVENT, type ParallelHandoffReference, type ScheduleOrigin, type SubagentState } from "../../shared/types.ts";
17
+ import { SUBAGENT_ASYNC_COMPLETE_EVENT, SUBAGENT_FOREGROUND_COMPLETE_EVENT, type ChildWatchdogProgress, type ChildWatchdogWarningSummary, type ParallelHandoffReference, type ScheduleOrigin, type SubagentState } from "../../shared/types.ts";
18
+ import { safeTerminalText } from "../../shared/display-text.ts";
19
+ import { resolveSubagentResultStatus } from "../../intercom/result-intercom.ts";
18
20
  import { isUnexplainedProcessSignal } from "../shared/process-signal.ts";
21
+ import type { ResultDeliveryOwnership } from "./result-delivery-ownership.ts";
22
+
23
+ export interface SubagentNotifyChildOutput {
24
+ workflowKey?: string;
25
+ runId?: string;
26
+ agent?: string;
27
+ status: string;
28
+ savedOutputPath?: string;
29
+ preview: string;
30
+ previewTruncated?: boolean;
31
+ previewUnavailableReason?: string;
32
+ }
33
+
34
+ export type SubagentNotifyWatchdogBlocker = Pick<ChildWatchdogWarningSummary, "summary" | "addressed" | "stalemate"> & { agent: string };
19
35
 
20
36
  export interface SubagentNotifyDetails {
21
37
  agent: string;
@@ -26,12 +42,14 @@ export interface SubagentNotifyDetails {
26
42
  durationMs?: number;
27
43
  workflowRunId?: string;
28
44
  childRuns?: Array<{ runId: string; workflowKey?: string; agent?: string; status?: string }>;
45
+ childOutputs?: SubagentNotifyChildOutput[];
29
46
  reconciledFromDetachedChild?: string;
30
47
  sessionLabel?: string;
31
48
  sessionValue?: string;
32
49
  handoffPath?: string;
33
50
  /** Present when a durable schedule launched the run. */
34
51
  scheduleOrigin?: ScheduleOrigin;
52
+ watchdogBlockers?: SubagentNotifyWatchdogBlocker[];
35
53
  }
36
54
 
37
55
  export interface CompletionNotification {
@@ -56,14 +74,23 @@ export interface CompletionNotification {
56
74
  workflowKey?: string;
57
75
  agent?: string;
58
76
  status?: string;
77
+ state?: string;
59
78
  success?: boolean;
79
+ output?: string;
80
+ structuredOutput?: unknown;
81
+ outputState?: "present" | "absent" | "unknown";
82
+ outputReference?: string | { path?: string };
83
+ artifactPaths?: { outputPath?: string };
84
+ detached?: boolean;
60
85
  exitCode?: number | null;
61
86
  processSignal?: string | null;
62
87
  interrupted?: boolean;
63
88
  timedOut?: boolean;
64
89
  stopped?: boolean;
65
90
  turnBudgetExceeded?: boolean;
91
+ watchdog?: ChildWatchdogProgress;
66
92
  }>;
93
+ watchdog?: ChildWatchdogProgress;
67
94
  timestamp?: number;
68
95
  durationMs?: number;
69
96
  cwd?: string;
@@ -91,6 +118,7 @@ export interface RegisterSubagentNotifyOptions {
91
118
  batchConfig?: CompletionBatchConfig;
92
119
  timers?: NotifyTimerApi;
93
120
  now?: () => number;
121
+ ownership?: Pick<ResultDeliveryOwnership, "owns">;
94
122
  }
95
123
 
96
124
  export interface CompletionNotifier {
@@ -98,6 +126,115 @@ export interface CompletionNotifier {
98
126
  dispose(): void;
99
127
  }
100
128
 
129
+ const CHILD_OUTPUT_PREVIEW_MAX_BYTES = 4 * 1024;
130
+ const CHILD_OUTPUT_PREVIEW_COUNT = 8;
131
+ const PREVIEW_TRUNCATION_MARKER = "...[preview truncated]";
132
+ type CompletionChild = NonNullable<CompletionNotification["results"]>[number];
133
+
134
+ function truncateUtf8Head(value: string, maxBytes: number): { text: string; truncated: boolean } {
135
+ const bytes = Buffer.from(value, "utf8");
136
+ if (bytes.length <= maxBytes) return { text: value, truncated: false };
137
+ const markerBytes = Buffer.byteLength(PREVIEW_TRUNCATION_MARKER, "utf8");
138
+ const contentBytes = Math.max(0, maxBytes - markerBytes);
139
+ let end = contentBytes;
140
+ while (end > 0 && (bytes[end]! & 0xc0) === 0x80) end -= 1;
141
+ return {
142
+ text: `${bytes.subarray(0, end).toString("utf8")}${PREVIEW_TRUNCATION_MARKER}`,
143
+ truncated: true,
144
+ };
145
+ }
146
+
147
+ function boundedSafeText(value: string, maxBytes = 1_024): string {
148
+ return truncateUtf8Head(safeTerminalText(value).replace(/\n/g, "\\n"), maxBytes).text;
149
+ }
150
+
151
+ function outputPathFromReference(value: CompletionChild["outputReference"]): string | undefined {
152
+ if (typeof value === "string" && value.trim()) return value.trim();
153
+ if (value && typeof value === "object" && typeof value.path === "string" && value.path.trim()) return value.path.trim();
154
+ return undefined;
155
+ }
156
+
157
+ function childSavedOutputPath(child: CompletionChild): string | undefined {
158
+ return outputPathFromReference(child.outputReference);
159
+ }
160
+
161
+ function childStatus(child: CompletionChild, workflowState?: string): string {
162
+ const knownStatus = child.status === "complete"
163
+ ? "completed"
164
+ : child.status === "completed" || child.status === "failed" || child.status === "paused" || child.status === "stopped" || child.status === "detached"
165
+ ? child.status
166
+ : undefined;
167
+ if (knownStatus) return knownStatus;
168
+ return resolveSubagentResultStatus({
169
+ success: child.success,
170
+ state: child.state ?? (child.success === undefined ? workflowState : undefined),
171
+ interrupted: child.interrupted,
172
+ detached: child.detached,
173
+ processSignal: child.processSignal,
174
+ timedOut: child.timedOut,
175
+ stopped: child.stopped,
176
+ turnBudgetExceeded: child.turnBudgetExceeded,
177
+ exitCode: typeof child.exitCode === "number" ? child.exitCode : undefined,
178
+ });
179
+ }
180
+
181
+ function structuredOutputText(value: unknown): string | undefined {
182
+ if (value === undefined) return undefined;
183
+ try {
184
+ const serialized = JSON.stringify(value, null, 2);
185
+ return typeof serialized === "string" ? serialized : undefined;
186
+ } catch {
187
+ return undefined;
188
+ }
189
+ }
190
+
191
+ function childInlinePreview(child: CompletionChild): { preview?: string; truncated?: boolean; unavailableReason?: string } {
192
+ const output = typeof child.output === "string" ? child.output : "";
193
+ const outputReference = childSavedOutputPath(child);
194
+ const referenceOnly = Boolean(outputReference && output.trim().startsWith("Output saved to:"));
195
+ const raw = child.outputState === "absent" || referenceOnly ? structuredOutputText(child.structuredOutput) : output || structuredOutputText(child.structuredOutput);
196
+ if (!raw?.trim()) {
197
+ return { unavailableReason: referenceOnly ? "saved output is file-only" : "no safe inline output" };
198
+ }
199
+ const safe = safeTerminalText(raw);
200
+ if (!safe.trim()) return { unavailableReason: "no safe inline output" };
201
+ const bounded = truncateUtf8Head(safe, CHILD_OUTPUT_PREVIEW_MAX_BYTES);
202
+ return { preview: bounded.text, ...(bounded.truncated ? { truncated: true } : {}) };
203
+ }
204
+
205
+ function formatChildOutputBlock(children: SubagentNotifyChildOutput[] | undefined): string | undefined {
206
+ if (!children?.length) return undefined;
207
+ const lines = ["Child outputs:"];
208
+ for (let index = 0; index < children.length; index++) {
209
+ const child = children[index]!;
210
+ const key = child.workflowKey ? boundedSafeText(child.workflowKey) : "unavailable";
211
+ const runId = child.runId ? boundedSafeText(child.runId) : "unavailable";
212
+ const status = boundedSafeText(child.status) || "unavailable";
213
+ lines.push(`- key=${key} run=${runId} status=${status}`);
214
+ lines.push(` Saved output: ${child.savedOutputPath ? boundedSafeText(child.savedOutputPath) : "unavailable"}`);
215
+ if (index >= CHILD_OUTPUT_PREVIEW_COUNT) {
216
+ lines.push(" Preview: unavailable (notice preview budget exceeded)");
217
+ continue;
218
+ }
219
+ if (!child.preview) {
220
+ lines.push(` Preview: unavailable (${child.previewUnavailableReason ?? "no safe inline output"})`);
221
+ continue;
222
+ }
223
+ lines.push(" Preview:");
224
+ for (const line of child.preview.split("\n")) lines.push(` | ${line}`);
225
+ }
226
+ if (children.length > CHILD_OUTPUT_PREVIEW_COUNT) {
227
+ lines.push(`- ${children.length - CHILD_OUTPUT_PREVIEW_COUNT} additional child preview(s) omitted by notice budget; child run metadata is retained below.`);
228
+ }
229
+ return lines.join("\n");
230
+ }
231
+
232
+ function formatResultPreview(details: SubagentNotifyDetails): string {
233
+ const summary = details.resultPreview.trim() ? details.resultPreview : "(no output)";
234
+ const childOutputs = formatChildOutputBlock(details.childOutputs);
235
+ return childOutputs ? `${summary}\n\n${childOutputs}` : summary;
236
+ }
237
+
101
238
  function formatSessionLine(details: SubagentNotifyDetails): string | undefined {
102
239
  if (!details.sessionValue) return undefined;
103
240
  return details.sessionLabel ? `${details.sessionLabel}: ${details.sessionValue}` : details.sessionValue;
@@ -117,9 +254,28 @@ function formatCorrelationLines(details: SubagentNotifyDetails): string[] {
117
254
  ].filter((line): line is string => line !== undefined);
118
255
  }
119
256
 
257
+ const WATCHDOG_BLOCKERS_HEADING = "Watchdog blockers:";
258
+
259
+ function formatWatchdogBlockerLines(details: SubagentNotifyDetails): string[] {
260
+ if (!details.watchdogBlockers?.length) return [];
261
+ return [WATCHDOG_BLOCKERS_HEADING, ...details.watchdogBlockers.map((blocker) => `- ${blocker.agent}: ${blocker.summary} (${blocker.stalemate ? "stalemate" : blocker.addressed ? "addressed" : "unaddressed"})`)];
262
+ }
263
+
264
+ // A stalemate blocker parses back as unaddressed; acceptance treats both as unresolved.
265
+ function parseWatchdogBlockerLines(lines: string[]): SubagentNotifyWatchdogBlocker[] {
266
+ const blockers: SubagentNotifyWatchdogBlocker[] = [];
267
+ for (const line of lines) {
268
+ const match = line.match(/^- (.+?): (.+) \((addressed|unaddressed|stalemate)\)$/);
269
+ if (!match) break;
270
+ blockers.push({ agent: match[1]!, summary: match[2]!, addressed: match[3] === "addressed", stalemate: match[3] === "stalemate" });
271
+ }
272
+ return blockers;
273
+ }
274
+
120
275
  export function formatSingleCompletion(details: SubagentNotifyDetails): string {
121
276
  const sessionLine = formatSessionLine(details);
122
277
  const correlationLines = formatCorrelationLines(details);
278
+ const watchdogLines = formatWatchdogBlockerLines(details);
123
279
  const taskKind = details.source === "foreground" ? "Detached foreground task" : "Background task";
124
280
  const scheduleLine = details.scheduleOrigin
125
281
  ? `Scheduled run from **${details.scheduleOrigin.name ?? details.scheduleOrigin.id}** (schedule ${details.scheduleOrigin.id}).`
@@ -129,7 +285,8 @@ export function formatSingleCompletion(details: SubagentNotifyDetails): string {
129
285
  "",
130
286
  scheduleLine,
131
287
  scheduleLine ? "" : undefined,
132
- details.resultPreview.trim() ? details.resultPreview : "(no output)",
288
+ formatResultPreview(details),
289
+ ...(watchdogLines.length ? ["", ...watchdogLines] : []),
133
290
  details.handoffPath ? "" : undefined,
134
291
  details.handoffPath ? `Parallel handoff: ${details.handoffPath}` : undefined,
135
292
  correlationLines.length && !details.handoffPath ? "" : undefined,
@@ -168,7 +325,9 @@ export function parseSubagentNotifyContent(content: string): SubagentNotifyDetai
168
325
  const workflowRunIndex = body.findIndex((line) => line.startsWith("Workflow run: "));
169
326
  const childRunsIndex = body.findIndex((line) => line.startsWith("Child runs: "));
170
327
  const reconciledIndex = body.findIndex((line) => line.startsWith("Reconciled detached child: "));
171
- const metadataIndexes = [sessionIndex, handoffIndex, workflowRunIndex, childRunsIndex, reconciledIndex].filter((index) => index >= 0);
328
+ const watchdogIndex = body.findIndex((line) => line === WATCHDOG_BLOCKERS_HEADING);
329
+ const watchdogBlockers = watchdogIndex >= 0 ? parseWatchdogBlockerLines(body.slice(watchdogIndex + 1)) : [];
330
+ const metadataIndexes = [sessionIndex, handoffIndex, workflowRunIndex, childRunsIndex, reconciledIndex, watchdogIndex].filter((index) => index >= 0);
172
331
  const firstMetadataIndex = metadataIndexes.length ? Math.min(...metadataIndexes) : body.length;
173
332
  const resultEnd = firstMetadataIndex > 0 && body[firstMetadataIndex - 1]?.trim() === "" ? firstMetadataIndex - 1 : firstMetadataIndex;
174
333
  const resultPreview = body.slice(0, resultEnd).join("\n").trim() || "(no output)";
@@ -204,6 +363,7 @@ export function parseSubagentNotifyContent(content: string): SubagentNotifyDetai
204
363
  ...(workflowRunId ? { workflowRunId } : {}),
205
364
  ...(childRuns?.length ? { childRuns } : {}),
206
365
  ...(reconciledFromDetachedChild ? { reconciledFromDetachedChild } : {}),
366
+ ...(watchdogBlockers.length ? { watchdogBlockers } : {}),
207
367
  ...(sessionLabel && sessionValue ? { sessionLabel, sessionValue } : {}),
208
368
  };
209
369
  }
@@ -216,7 +376,8 @@ export function formatGroupedCompletion(details: SubagentNotifyDetails[]): strin
216
376
  if (!detail) continue;
217
377
  const sessionLine = formatSessionLine(detail);
218
378
  blocks.push(`${index + 1}. ${detail.agent}${detail.taskInfo ?? ""}${detail.scheduleOrigin ? ` — scheduled run from ${detail.scheduleOrigin.name ?? detail.scheduleOrigin.id} (schedule ${detail.scheduleOrigin.id})` : ""}`);
219
- blocks.push(detail.resultPreview.trim() ? detail.resultPreview : "(no output)");
379
+ blocks.push(formatResultPreview(detail));
380
+ blocks.push(...formatWatchdogBlockerLines(detail));
220
381
  if (detail.handoffPath) blocks.push(`Parallel handoff: ${detail.handoffPath}`);
221
382
  blocks.push(...formatCorrelationLines(detail));
222
383
  if (sessionLine) blocks.push(sessionLine);
@@ -228,6 +389,8 @@ export function formatGroupedCompletion(details: SubagentNotifyDetails[]): strin
228
389
  interface PendingCompletion {
229
390
  key: string;
230
391
  details: SubagentNotifyDetails;
392
+ sessionId: string;
393
+ completionOwnerId: unknown;
231
394
  triggerTurn: boolean;
232
395
  resolve(accepted: boolean): void;
233
396
  }
@@ -271,6 +434,7 @@ export function buildCompletionDetails(result: CompletionNotification): Subagent
271
434
  const paused = !stopped && !result.success && (
272
435
  result.exitCode === 0
273
436
  || result.state === "paused"
437
+ || result.interrupted === true
274
438
  || summary.startsWith("Paused after interrupt.")
275
439
  );
276
440
  const status = stopped ? "stopped" : paused ? "paused" : result.success ? "completed" : "failed";
@@ -285,16 +449,57 @@ export function buildCompletionDetails(result: CompletionNotification): Subagent
285
449
  const handoffPath = typeof parallelHandoff?.path === "string" ? parallelHandoff.path : undefined;
286
450
  const rawRunId = typeof result.runId === "string" ? result.runId : typeof result.id === "string" ? result.id : undefined;
287
451
  const workflowRunId = (result.mode === "workflow" || agent === "workflow") && rawRunId ? rawRunId : undefined;
452
+ const directChild = !workflowRunId && result.results?.length === 1 ? result.results[0]! : undefined;
453
+ const directStructuredPreview = directChild
454
+ ? childInlinePreview(directChild).preview
455
+ : undefined;
456
+ const directSummary = summary.trim();
457
+ const directAgent = typeof directChild?.agent === "string" ? directChild.agent : agent;
458
+ const directNoOutputSummary = directChild && (!directSummary
459
+ || directSummary === "(no output)"
460
+ || (directAgent && directSummary === `${directAgent}:\n(no output)`));
461
+ const resultPreview = directStructuredPreview && directNoOutputSummary
462
+ ? `Structured output:\n${directStructuredPreview}`
463
+ : summary;
288
464
  const childRuns = result.results?.flatMap((child) => {
289
- if (typeof child.runId !== "string" || !child.runId.trim()) return [];
465
+ const runId = typeof child.runId === "string" && child.runId.trim() ? child.runId.trim() : undefined;
466
+ const workflowKey = typeof child.workflowKey === "string" && child.workflowKey.trim() ? child.workflowKey.trim() : undefined;
467
+ if (!runId && (!workflowRunId || !workflowKey)) return [];
290
468
  return [{
291
- runId: child.runId,
292
- ...(typeof child.workflowKey === "string" ? { workflowKey: child.workflowKey } : {}),
469
+ runId: runId ?? "unavailable",
470
+ ...(workflowKey ? { workflowKey } : {}),
293
471
  ...(typeof child.agent === "string" ? { agent: child.agent } : {}),
294
- ...(typeof child.status === "string" ? { status: child.status } : {}),
472
+ status: childStatus(child, workflowRunId ? result.state : undefined),
295
473
  }];
296
474
  }) ?? [];
475
+ const childOutputs = workflowRunId && result.results?.length
476
+ ? result.results.map((child) => {
477
+ const inline = childInlinePreview(child);
478
+ const workflowKey = typeof child.workflowKey === "string" && child.workflowKey.trim() ? child.workflowKey.trim() : undefined;
479
+ const runId = typeof child.runId === "string" && child.runId.trim() ? child.runId.trim() : undefined;
480
+ const savedOutputPath = childSavedOutputPath(child);
481
+ return {
482
+ ...(workflowKey ? { workflowKey } : {}),
483
+ ...(runId ? { runId } : {}),
484
+ ...(typeof child.agent === "string" ? { agent: child.agent } : {}),
485
+ status: childStatus(child, result.state),
486
+ ...(savedOutputPath ? { savedOutputPath } : {}),
487
+ ...(inline.preview ? { preview: inline.preview } : { preview: "" }),
488
+ ...(inline.truncated ? { previewTruncated: true } : {}),
489
+ ...(inline.unavailableReason ? { previewUnavailableReason: inline.unavailableReason } : {}),
490
+ };
491
+ })
492
+ : undefined;
297
493
  const reconciledFromDetachedChild = typeof result.reconciledFromDetachedChild === "string" ? result.reconciledFromDetachedChild : undefined;
494
+ const watchdogBlockers: SubagentNotifyWatchdogBlocker[] = [];
495
+ const collectWatchdogBlockers = (owner: string, progress: ChildWatchdogProgress | undefined) => {
496
+ for (const warning of progress?.warnings ?? []) {
497
+ if (warning.severity !== "blocker") continue;
498
+ watchdogBlockers.push({ agent: owner, summary: warning.summary, addressed: warning.addressed, stalemate: warning.stalemate });
499
+ }
500
+ };
501
+ collectWatchdogBlockers(agent, result.watchdog);
502
+ for (const child of result.results ?? []) collectWatchdogBlockers(typeof child.agent === "string" ? child.agent : agent, child.watchdog);
298
503
  const session =
299
504
  result.shareUrl
300
505
  ? { label: "Session", value: result.shareUrl }
@@ -313,12 +518,14 @@ export function buildCompletionDetails(result: CompletionNotification): Subagent
313
518
  ...(scheduleOrigin ? { scheduleOrigin } : {}),
314
519
  ...(result.source ? { source: result.source } : {}),
315
520
  ...(taskInfo ? { taskInfo } : {}),
316
- resultPreview: summary,
521
+ resultPreview,
317
522
  ...(typeof result.durationMs === "number" ? { durationMs: result.durationMs } : {}),
318
523
  ...(handoffPath ? { handoffPath } : {}),
319
524
  ...(workflowRunId ? { workflowRunId } : {}),
320
525
  ...(childRuns.length ? { childRuns } : {}),
526
+ ...(childOutputs?.length ? { childOutputs } : {}),
321
527
  ...(reconciledFromDetachedChild ? { reconciledFromDetachedChild } : {}),
528
+ ...(watchdogBlockers.length ? { watchdogBlockers } : {}),
322
529
  ...(session ? { sessionLabel: session.label, sessionValue: session.value } : {}),
323
530
  };
324
531
  }
@@ -335,6 +542,10 @@ export default function registerSubagentNotify(
335
542
  const batchConfig = resolveCompletionBatchConfig(options.batchConfig);
336
543
  const batchers = new Map<string, CompletionBatcher<PendingCompletion>>();
337
544
  let disposed = false;
545
+ const ownsResult = options.ownership?.owns
546
+ ?? ((sessionId: string, completionOwnerId: unknown) => sessionId === state.currentSessionId
547
+ && typeof completionOwnerId === "string"
548
+ && completionOwnerId === state.completionOwnerId);
338
549
 
339
550
  const settle = (items: PendingCompletion[], accepted: boolean) => {
340
551
  for (const item of items) {
@@ -343,7 +554,18 @@ export default function registerSubagentNotify(
343
554
  item.resolve(accepted);
344
555
  }
345
556
  };
346
- const emit = (items: PendingCompletion[]) => settle(items, sendCompletion(pi, items));
557
+ const emit = (items: PendingCompletion[]) => {
558
+ const accepted: PendingCompletion[] = [];
559
+ const rejected: PendingCompletion[] = [];
560
+ for (const item of items) {
561
+ const owned = item.details.source === "foreground"
562
+ ? item.sessionId === state.currentSessionId
563
+ : ownsResult(item.sessionId, item.completionOwnerId);
564
+ (owned ? accepted : rejected).push(item);
565
+ }
566
+ settle(rejected, false);
567
+ settle(accepted, sendCompletion(pi, accepted));
568
+ };
347
569
  const getBatcher = (result: CompletionNotification) => {
348
570
  const key = completionBatchKey(result);
349
571
  let batcher = batchers.get(key);
@@ -360,8 +582,10 @@ export default function registerSubagentNotify(
360
582
  };
361
583
 
362
584
  const deliver = (result: CompletionNotification): Promise<boolean> => {
363
- if (disposed || typeof result.sessionId !== "string" || result.sessionId !== state.currentSessionId) return Promise.resolve(false);
364
- if (result.source !== "foreground" && (!state.completionOwnerId || result.completionOwnerId !== state.completionOwnerId)) return Promise.resolve(false);
585
+ if (disposed || typeof result.sessionId !== "string") return Promise.resolve(false);
586
+ if (result.source === "foreground") {
587
+ if (result.sessionId !== state.currentSessionId) return Promise.resolve(false);
588
+ } else if (!ownsResult(result.sessionId, result.completionOwnerId)) return Promise.resolve(false);
365
589
  if (result.intercomDelivered === true) return Promise.resolve(true);
366
590
  const key = buildCompletionKey(result, "notify");
367
591
  const seenAt = seen.get(key);
@@ -376,6 +600,8 @@ export default function registerSubagentNotify(
376
600
  const item: PendingCompletion = {
377
601
  key,
378
602
  details,
603
+ sessionId: result.sessionId,
604
+ completionOwnerId: result.completionOwnerId,
379
605
  triggerTurn: result.triggerTurn !== false,
380
606
  resolve,
381
607
  };