@xzzpig/pi-subagents 0.19.0 → 0.21.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 (153) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +86 -11
  9. package/docs/configuration.md +68 -7
  10. package/docs/extension-api.md +37 -12
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +48 -17
  13. package/docs/models.md +7 -3
  14. package/docs/observability.md +18 -8
  15. package/docs/tool-reference.md +138 -80
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +18 -9
  18. package/index.ts +5 -0
  19. package/package.json +5 -3
  20. package/prompts/council.md +1 -1
  21. package/skills/pi-subagents/SKILL.md +1 -1
  22. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  23. package/skills/pi-subagents/references/execution-controls.md +16 -16
  24. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  25. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  26. package/src/agents/advertised-agent-prompt.ts +9 -1
  27. package/src/agents/agent-management.ts +4 -0
  28. package/src/agents/agent-memory.ts +3 -3
  29. package/src/agents/agent-scope.ts +4 -0
  30. package/src/agents/agent-serializer.ts +8 -1
  31. package/src/agents/agents.ts +224 -122
  32. package/src/api/preflight.ts +50 -5
  33. package/src/extension/config.ts +24 -2
  34. package/src/extension/context-injection.ts +6 -1
  35. package/src/extension/control-notices.ts +1 -9
  36. package/src/extension/declaration-pinning.ts +164 -0
  37. package/src/extension/doctor.ts +7 -10
  38. package/src/extension/fanout-child.ts +7 -8
  39. package/src/extension/index.ts +134 -145
  40. package/src/extension/public-execution.ts +3 -0
  41. package/src/extension/reply-workflow-script.ts +21 -12
  42. package/src/extension/rpc.ts +12 -7
  43. package/src/extension/schemas.ts +39 -33
  44. package/src/extension/subagent-guide.ts +86 -6
  45. package/src/extension/subagent-options.ts +47 -0
  46. package/src/extension/tool-activation.ts +3 -2
  47. package/src/extension/tool-description.ts +51 -68
  48. package/src/inspectors/actions.ts +37 -11
  49. package/src/inspectors/plugins.ts +3 -2
  50. package/src/inspectors/tmux/actions.ts +204 -0
  51. package/src/inspectors/tmux/client.ts +85 -0
  52. package/src/inspectors/tmux/plugin.ts +21 -0
  53. package/src/integrations/herdr-status.ts +18 -49
  54. package/src/integrations/program-status.ts +215 -0
  55. package/src/intercom/native-supervisor-channel.ts +77 -4
  56. package/src/intercom/result-intercom.ts +3 -2
  57. package/src/intercom/supervisor-ui.ts +2 -174
  58. package/src/missions/goal-driver.ts +44 -31
  59. package/src/missions/store.ts +35 -6
  60. package/src/profiles/profiles.ts +29 -23
  61. package/src/runs/background/active-async-capacity.ts +58 -8
  62. package/src/runs/background/async-execution.ts +231 -44
  63. package/src/runs/background/async-job-tracker.ts +12 -4
  64. package/src/runs/background/async-resume.ts +5 -2
  65. package/src/runs/background/await-async-run.ts +18 -11
  66. package/src/runs/background/binary-bootstrap.ts +2 -1
  67. package/src/runs/background/calendar-schedule.ts +90 -0
  68. package/src/runs/background/chain-root-attachment.ts +9 -5
  69. package/src/runs/background/control-channel.ts +43 -0
  70. package/src/runs/background/fleet-view.ts +5 -5
  71. package/src/runs/background/notify.ts +185 -12
  72. package/src/runs/background/result-files.ts +116 -5
  73. package/src/runs/background/result-watcher.ts +99 -66
  74. package/src/runs/background/resume-guidance.ts +2 -2
  75. package/src/runs/background/run-child-session.ts +29 -8
  76. package/src/runs/background/run-id-resolver.ts +8 -5
  77. package/src/runs/background/run-status.ts +21 -16
  78. package/src/runs/background/runner-aliases.ts +7 -4
  79. package/src/runs/background/runner-child-launch.ts +1 -0
  80. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  81. package/src/runs/background/scheduled-runs.ts +282 -72
  82. package/src/runs/background/stale-run-reconciler.ts +13 -2
  83. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  84. package/src/runs/background/subagent-runner.ts +75 -16
  85. package/src/runs/background/subagent-wait.ts +38 -19
  86. package/src/runs/background/terminal-run-index.ts +46 -1
  87. package/src/runs/background/wait-completions.ts +1 -0
  88. package/src/runs/background/wait-tool.ts +33 -23
  89. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  90. package/src/runs/foreground/async-stop-action.ts +48 -22
  91. package/src/runs/foreground/command-action.ts +41 -0
  92. package/src/runs/foreground/execution.ts +109 -58
  93. package/src/runs/foreground/foreground-history.ts +1 -0
  94. package/src/runs/foreground/subagent-executor.ts +270 -89
  95. package/src/runs/shared/child-commands.ts +229 -0
  96. package/src/runs/shared/child-hooks.ts +4 -3
  97. package/src/runs/shared/child-launch.ts +3 -0
  98. package/src/runs/shared/child-session.ts +131 -40
  99. package/src/runs/shared/child-tool-plan.ts +14 -27
  100. package/src/runs/shared/claude-code-adapter.ts +157 -2
  101. package/src/runs/shared/dynamic-fanout.ts +2 -2
  102. package/src/runs/shared/external-cli-preflight.ts +54 -6
  103. package/src/runs/shared/external-cli-runner.ts +5 -1
  104. package/src/runs/shared/fork-command-result.ts +10 -0
  105. package/src/runs/shared/herdr-placed-run.ts +5 -4
  106. package/src/runs/shared/mcp-direct-tool-allowlist.ts +8 -5
  107. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  108. package/src/runs/shared/model-resolution.ts +39 -2
  109. package/src/runs/shared/nested-events.ts +5 -0
  110. package/src/runs/shared/parallel-handoff.ts +56 -8
  111. package/src/runs/shared/parallel-utils.ts +4 -0
  112. package/src/runs/shared/partial-output.ts +48 -0
  113. package/src/runs/shared/run-history.ts +87 -0
  114. package/src/runs/shared/runner-launcher.ts +25 -0
  115. package/src/runs/shared/single-output.ts +53 -0
  116. package/src/runs/shared/structured-output.ts +14 -7
  117. package/src/runs/shared/subagent-control.ts +33 -18
  118. package/src/runs/shared/subagent-prompt-runtime.ts +59 -30
  119. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  120. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  121. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  122. package/src/runs/shared/worktree-lock.ts +29 -0
  123. package/src/runs/shared/worktree.ts +12 -1
  124. package/src/shared/atomic-json.ts +4 -2
  125. package/src/shared/edit-distance.ts +33 -0
  126. package/src/shared/file-lease.ts +74 -0
  127. package/src/shared/formatters.ts +1 -5
  128. package/src/shared/model-info.ts +22 -0
  129. package/src/shared/package-version.ts +17 -0
  130. package/src/shared/parent-wake.ts +79 -0
  131. package/src/shared/pruned-fork.ts +7 -1
  132. package/src/shared/required-child-extensions.ts +39 -5
  133. package/src/shared/runtime-module-path.ts +19 -0
  134. package/src/shared/settings-file-lease.ts +36 -0
  135. package/src/shared/types.ts +42 -3
  136. package/src/shared/utils.ts +8 -6
  137. package/src/slash/slash-commands.ts +3 -3
  138. package/src/slash/subagent-cost.ts +9 -5
  139. package/src/slash/subagents-admin.ts +2 -1
  140. package/src/tui/fleet-native-transcript.ts +2 -0
  141. package/src/tui/fleet-transcript.ts +12 -3
  142. package/src/tui/fleet.ts +11 -8
  143. package/src/tui/render.ts +28 -20
  144. package/src/tui/subagent-messages.ts +305 -0
  145. package/src/watchdog/diff-tool.ts +2 -2
  146. package/src/watchdog/register-main.ts +2 -22
  147. package/src/watchdog/render.ts +2 -24
  148. package/src/watchdog/runtime.ts +6 -4
  149. package/src/watchdog/settings.ts +18 -13
  150. package/src/watchdog/tool-actions.ts +2 -2
  151. package/src/workflows/scripted-workflow.ts +20 -6
  152. package/src/workflows/workflow-receipt.ts +2 -2
  153. package/src/workflows/workflow-resources.ts +18 -4
@@ -8,7 +8,8 @@
8
8
 
9
9
  import { statSync } from "node:fs";
10
10
  import { debuglog } from "node:util";
11
- import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
11
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
12
+ import type { AgentBeforeSettleEvent, AgentBeforeSettleEventResult, ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
12
13
  import { buildCompletionKey, markSeenWithTtl } from "./completion-dedupe.ts";
13
14
  import {
14
15
  type CompletionBatchConfig,
@@ -18,8 +19,10 @@ import {
18
19
  } from "./completion-batcher.ts";
19
20
  import { SUBAGENT_ASYNC_COMPLETE_EVENT, SUBAGENT_FOREGROUND_COMPLETE_EVENT, type ChildWatchdogProgress, type ChildWatchdogWarningSummary, type ParallelHandoffReference, type ScheduleOrigin, type SubagentState } from "../../shared/types.ts";
20
21
  import { safeTerminalText } from "../../shared/display-text.ts";
22
+ import type { ParentWake } from "../../shared/parent-wake.ts";
21
23
  import { resolveSubagentResultStatus } from "../../intercom/result-intercom.ts";
22
24
  import { isUnexplainedProcessSignal } from "../shared/process-signal.ts";
25
+ import { capSummaryOutputs } from "../shared/single-output.ts";
23
26
  import type { ResultDeliveryOwnership } from "./result-delivery-ownership.ts";
24
27
 
25
28
  export interface SubagentNotifyChildOutput {
@@ -34,6 +37,7 @@ export interface SubagentNotifyChildOutput {
34
37
  structuredOutputPath?: string;
35
38
  outputArtifactError?: RetainedPathError;
36
39
  structuredOutputError?: RetainedPathError;
40
+ error?: string;
37
41
  preview: string;
38
42
  previewTruncated?: boolean;
39
43
  previewUnavailableReason?: string;
@@ -50,6 +54,8 @@ export interface SubagentNotifyDetails {
50
54
  taskInfo?: string;
51
55
  resultPreview: string;
52
56
  durationMs?: number;
57
+ /** The finished run's id; for a workflow it equals workflowRunId. */
58
+ runId?: string;
53
59
  workflowRunId?: string;
54
60
  childRuns?: Array<{ runId: string; workflowKey?: string; agent?: string; status?: string }>;
55
61
  childOutputs?: SubagentNotifyChildOutput[];
@@ -98,10 +104,12 @@ export interface CompletionNotification {
98
104
  revival?: string;
99
105
  success?: boolean;
100
106
  output?: string;
107
+ error?: string;
101
108
  structuredOutput?: unknown;
102
109
  structuredOutputPath?: string;
103
110
  outputState?: "present" | "absent" | "unknown";
104
111
  outputReference?: string | { path?: string };
112
+ savedOutputPath?: string;
105
113
  artifactPaths?: { outputPath?: string };
106
114
  outputSaveError?: string;
107
115
  artifactOutputSaveFailed?: true;
@@ -149,11 +157,21 @@ export interface RegisterSubagentNotifyOptions {
149
157
 
150
158
  export interface CompletionNotifier {
151
159
  deliver(result: CompletionNotification): Promise<boolean>;
160
+ /** True while a completion is batched, being sent, or accepted as a wake that Pi has not started yet. */
152
161
  hasPendingDelivery(): boolean;
162
+ /** Releases a completion wake once Pi starts it (native message_start). */
163
+ messageStarted(message: AgentMessage): void;
164
+ /** Adopts wakes a reloaded notifier left queued for the same session manager and session UUID. */
165
+ bindSession(sessionManager: Pick<ExtensionContext["sessionManager"], "getSessionId">): void;
166
+ /** Drops queued wakes unless the session is only reloading extensions. */
167
+ sessionShutdown(reason: string | undefined): void;
168
+ /** Send every batched completion now instead of waiting for its batch timer. */
169
+ flush(): void;
153
170
  dispose(): void;
154
171
  }
155
172
 
156
- const CHILD_OUTPUT_PREVIEW_MAX_BYTES = 4 * 1024;
173
+ const CHILD_OUTPUT_PREVIEW_MAX_BYTES = 2_000;
174
+ const ERROR_LINE_MAX_BYTES = 300;
157
175
  const CHILD_OUTPUT_PREVIEW_COUNT = 8;
158
176
  const PREVIEW_TRUNCATION_MARKER = "...[preview truncated]";
159
177
  const COMPLETION_SEND_TTL_MS = 10 * 60 * 1000;
@@ -247,6 +265,12 @@ function isDegenerateOutput(text: string): boolean {
247
265
  return !text.trim() || text.trim() === "</think>";
248
266
  }
249
267
 
268
+ function firstErrorLine(error: unknown): string | undefined {
269
+ if (typeof error !== "string") return undefined;
270
+ const line = error.split("\n").find((part) => part.trim())?.trim();
271
+ return line ? boundedSafeText(line, ERROR_LINE_MAX_BYTES) : undefined;
272
+ }
273
+
250
274
  function childInlinePreview(child: CompletionChild): { preview?: string; truncated?: boolean; unavailableReason?: string } {
251
275
  const output = typeof child.output === "string" ? child.output : "";
252
276
  const outputReference = childSavedOutputPath(child);
@@ -278,6 +302,7 @@ function formatChildOutputBlock(children: SubagentNotifyChildOutput[] | undefine
278
302
  if (child.structuredOutputPath) lines.push(` Structured output (retention-managed): ${boundedSafeText(child.structuredOutputPath)}`);
279
303
  if (child.outputArtifactError) lines.push(formatRetainedPathError("Output artifact", child.outputArtifactError));
280
304
  if (child.structuredOutputError) lines.push(formatRetainedPathError("Structured output", child.structuredOutputError));
305
+ if (child.error) lines.push(` Error: ${child.error}`);
281
306
  if (child.previewTruncated && !child.savedOutputPath && !child.outputArtifactPath) lines.push(" Full output unavailable");
282
307
  if (index >= CHILD_OUTPUT_PREVIEW_COUNT) {
283
308
  lines.push(" Preview: unavailable (notice preview budget exceeded)");
@@ -594,22 +619,59 @@ const processGlobal = globalThis as typeof globalThis & { [completionSendRegistr
594
619
  const processCompletionSendRegistry = processGlobal[completionSendRegistrySymbol]
595
620
  ?? (processGlobal[completionSendRegistrySymbol] = createCompletionSendRegistry());
596
621
 
597
- function sendCompletion(pi: Pick<ExtensionAPI, "sendMessage">, items: PendingCompletion[]): boolean {
622
+ // Reload replaces extension instances, not Pi's session manager or queued wakes.
623
+ // A manager can change sessions; retain wakes only while its UUID is unchanged.
624
+ type QueuedWakes = { sessionId: string; wakes: string[]; unansweredCompletions: Map<string, { reminded: boolean }> };
625
+ const queuedWakesSymbol = Symbol.for("pi-subagents.queued-completion-wakes.v2");
626
+ const wakeGlobal = globalThis as typeof globalThis & { [queuedWakesSymbol]?: WeakMap<object, QueuedWakes> };
627
+ const queuedWakes = wakeGlobal[queuedWakesSymbol] ?? (wakeGlobal[queuedWakesSymbol] = new WeakMap<object, QueuedWakes>());
628
+
629
+ type NotifyRunDetails = Omit<SubagentNotifyDetails, "resultPreview" | "childOutputs"> & {
630
+ childOutputs?: Array<Omit<SubagentNotifyChildOutput, "preview" | "previewTruncated" | "previewUnavailableReason">>;
631
+ };
632
+
633
+ function notifyRunDetails({ resultPreview: _preview, childOutputs, ...run }: SubagentNotifyDetails): NotifyRunDetails {
634
+ return {
635
+ ...run,
636
+ ...(childOutputs ? { childOutputs: childOutputs.map(({ preview: _childPreview, previewTruncated: _truncated, previewUnavailableReason: _reason, ...child }) => child) } : {}),
637
+ };
638
+ }
639
+
640
+ const COMPLETION_ACTION = "Read the saved results above and resume the already-authorized parent task, or report completion. If approval is required, explicitly ask the user. Do not silently yield, rerun completed work, or infer new authorization.";
641
+ function sendCompletion(pi: Pick<ParentWake, "sendMessage">, items: PendingCompletion[], unstartedWakes: string[], unansweredCompletions: Map<string, { reminded: boolean }>, updateSettleSubscription: () => void): boolean {
598
642
  if (items.length === 0) return true;
599
643
  const details = items.map((item) => item.details);
600
- const content = details.length === 1 ? formatSingleCompletion(details[0]!) : formatGroupedCompletion(details);
644
+ const triggerTurn = items.some((item) => item.triggerTurn);
645
+ const formatted = details.length === 1 ? formatSingleCompletion(details[0]!) : formatGroupedCompletion(details);
646
+ const content = triggerTurn ? `${formatted}\n\nParent action: ${COMPLETION_ACTION}` : formatted;
601
647
  const display = details.some((detail) => detail.source === "foreground" || detail.status !== "completed" || detail.scheduleOrigin !== undefined);
648
+ // Pi can queue an accepted wake behind the current turn or past agent_settled.
649
+ // Recorded before sending in case Pi starts the message synchronously.
650
+ if (triggerTurn) {
651
+ unstartedWakes.push(content);
652
+ unansweredCompletions.set(content, { reminded: false });
653
+ updateSettleSubscription();
654
+ }
602
655
  try {
603
- pi.sendMessage(
656
+ const appended = pi.sendMessage(
604
657
  {
605
658
  customType: "subagent-notify",
606
659
  content,
607
660
  display,
661
+ // Pi does not send details to the model. Hosts match runs by id; the text previews stay in content only.
662
+ details: { runs: details.map(notifyRunDetails) },
608
663
  },
609
- { triggerTurn: items.some((item) => item.triggerTurn) },
664
+ { triggerTurn },
610
665
  );
666
+ // An idle parent's appended notice gets no message_start; its wake prompt holds liveness instead.
667
+ if (appended) unstartedWakes.splice(unstartedWakes.lastIndexOf(content), 1);
611
668
  return true;
612
669
  } catch {
670
+ if (triggerTurn) {
671
+ unstartedWakes.splice(unstartedWakes.lastIndexOf(content), 1);
672
+ unansweredCompletions.delete(content);
673
+ updateSettleSubscription();
674
+ }
613
675
  return false;
614
676
  }
615
677
  }
@@ -671,9 +733,19 @@ export function buildCompletionDetails(result: CompletionNotification): Subagent
671
733
  const directNoOutputSummary = directChild && (!directSummary
672
734
  || directSummary === "(no output)"
673
735
  || (directAgent && directSummary === `${directAgent}:\n(no output)`));
674
- const resultPreview = directStructuredPreview && (directNoOutputSummary || directDegenerateSummary)
736
+ const outputPreview = directStructuredPreview && (directNoOutputSummary || directDegenerateSummary)
675
737
  ? `Structured output:\n${directStructuredPreview}`
676
- : summary;
738
+ : capSummaryOutputs(summary, result.results);
739
+ // A failed child that produced output reports that output as its summary, so its error needs its own line.
740
+ const errorSources = status === "completed" ? [] : [
741
+ { agent: undefined, error: result.error },
742
+ ...(workflowRunId ? [] : result.results ?? []).filter((child) => child.success !== true).map((child) => ({ agent: child.agent, error: child.error })),
743
+ ];
744
+ const errorLines = [...new Set(errorSources.flatMap(({ agent: errorAgent, error }) => {
745
+ const line = firstErrorLine(error);
746
+ return line && !outputPreview.includes(line) ? [`Error${errorAgent && (result.results?.length ?? 0) > 1 ? ` (${errorAgent})` : ""}: ${line}`] : [];
747
+ }))];
748
+ const resultPreview = errorLines.length ? `${errorLines.join("\n")}\n\n${outputPreview}` : outputPreview;
677
749
  const childRuns = result.results?.flatMap((child) => {
678
750
  const runId = typeof child.runId === "string" && child.runId.trim() ? child.runId.trim() : undefined;
679
751
  const workflowKey = typeof child.workflowKey === "string" && child.workflowKey.trim() ? child.workflowKey.trim() : undefined;
@@ -695,17 +767,20 @@ export function buildCompletionDetails(result: CompletionNotification): Subagent
695
767
  const structuredOutput = child.stopped === true || child.timedOut === true
696
768
  ? { status: "unavailable" as const }
697
769
  : retainedChildPath(child.structuredOutputPath, child.structuredOutput !== undefined);
770
+ const status = childStatus(child, result.state);
771
+ const error = status === "completed" || status === "running" ? undefined : firstErrorLine(child.error);
698
772
  return {
699
773
  ...(workflowKey ? { workflowKey } : {}),
700
774
  ...(runId ? { runId } : {}),
701
775
  ...(typeof child.agent === "string" ? { agent: child.agent } : {}),
702
- status: childStatus(child, result.state),
776
+ status,
703
777
  ...(typeof child.revival === "string" && child.revival ? { revival: child.revival } : {}),
704
778
  ...(savedOutputPath ? { savedOutputPath } : {}),
705
779
  ...(outputArtifact.status === "verified" ? { outputArtifactPath: outputArtifact.path } : {}),
706
780
  ...(structuredOutput.status === "verified" ? { structuredOutputPath: structuredOutput.path } : {}),
707
781
  ...(outputArtifact.status === "error" ? { outputArtifactError: outputArtifact.error } : {}),
708
782
  ...(structuredOutput.status === "error" ? { structuredOutputError: structuredOutput.error } : {}),
783
+ ...(error ? { error } : {}),
709
784
  ...(inline.preview ? { preview: inline.preview } : { preview: "" }),
710
785
  ...(inline.truncated ? { previewTruncated: true } : {}),
711
786
  ...(inline.unavailableReason ? { previewUnavailableReason: inline.unavailableReason } : {}),
@@ -748,6 +823,7 @@ export function buildCompletionDetails(result: CompletionNotification): Subagent
748
823
  resultPreview: watchdogConcerns.length ? `${resultPreview}\n\nHigh-importance watchdog concerns:\n${watchdogConcerns.map((warning) => `- ${warning}`).join("\n")}` : resultPreview,
749
824
  ...(typeof result.durationMs === "number" ? { durationMs: result.durationMs } : {}),
750
825
  ...(handoffPath ? { handoffPath } : {}),
826
+ ...(rawRunId ? { runId: rawRunId } : {}),
751
827
  ...(workflowRunId ? { workflowRunId } : {}),
752
828
  ...(childRuns.length ? { childRuns } : {}),
753
829
  ...(childOutputs?.length ? { childOutputs } : {}),
@@ -758,7 +834,7 @@ export function buildCompletionDetails(result: CompletionNotification): Subagent
758
834
  }
759
835
 
760
836
  export default function registerSubagentNotify(
761
- pi: ExtensionAPI,
837
+ pi: Pick<ExtensionAPI, "events"> & Partial<Pick<ExtensionAPI, "on">> & Pick<ParentWake, "sendMessage">,
762
838
  state: Pick<SubagentState, "currentSessionId" | "completionOwnerId">,
763
839
  options: RegisterSubagentNotifyOptions = {},
764
840
  ): CompletionNotifier {
@@ -769,7 +845,11 @@ export default function registerSubagentNotify(
769
845
  const sendRegistry = options.sendRegistry ?? processCompletionSendRegistry;
770
846
  const batchConfig = resolveCompletionBatchConfig(options.batchConfig);
771
847
  const batchers = new Map<string, CompletionBatcher<PendingCompletion>>();
848
+ let unstartedWakes: string[] = [];
849
+ let unansweredCompletions = new Map<string, { reminded: boolean }>();
850
+ let bound = false;
772
851
  let disposed = false;
852
+ let unsubscribeSettle: (() => void) | undefined;
773
853
  const ownsResult = options.ownership?.owns
774
854
  ?? ((sessionId: string, completionOwnerId: unknown) => sessionId === state.currentSessionId
775
855
  && typeof completionOwnerId === "string"
@@ -805,7 +885,7 @@ export default function registerSubagentNotify(
805
885
  void claim.outcome.then((outcome) => settle([item], outcome, outcome ? undefined : "send_failed"));
806
886
  }
807
887
  const claimedItems = claimed.map(({ item }) => item);
808
- const sent = sendCompletion(pi, claimedItems);
888
+ const sent = sendCompletion(pi, claimedItems, unstartedWakes, unansweredCompletions, updateSettleSubscription);
809
889
  for (const { claim } of claimed) claim.settle?.(sent);
810
890
  settle(claimedItems, sent, sent ? "send_accepted" : "send_failed");
811
891
  };
@@ -882,6 +962,61 @@ export default function registerSubagentNotify(
882
962
  return completion;
883
963
  };
884
964
 
965
+ const handleBeforeSettle = (event: AgentBeforeSettleEvent): AgentBeforeSettleEventResult | undefined => {
966
+ if (disposed || event.outcome !== "completed" || event.continue || event.context.pendingMessages.length)
967
+ return;
968
+ const messages = event.context.contextMessages;
969
+ const ignored: Array<[string, { reminded: boolean }]> = [];
970
+ for (const [content, notice] of unansweredCompletions) {
971
+ const index = messages.findLastIndex(message => message.role === "custom"
972
+ && message.customType === "subagent-notify" && message.content === content);
973
+ if (index === -1) {
974
+ // Removed by compaction or branch switch; never revive a stale notice.
975
+ unansweredCompletions.delete(content);
976
+ continue;
977
+ }
978
+ const acted = messages.slice(index + 1).some(message => message.role === "assistant"
979
+ && message.content.some(part => part.type === "toolCall"
980
+ || (part.type === "text" && part.text.trim())));
981
+ if (acted) {
982
+ unansweredCompletions.delete(content);
983
+ continue;
984
+ }
985
+ ignored.push([content, notice]);
986
+ }
987
+ updateSettleSubscription();
988
+ if (!ignored.length)
989
+ return;
990
+ const fresh = ignored.filter(([, notice]) => !notice.reminded);
991
+ if (fresh.length) {
992
+ for (const [, notice] of fresh)
993
+ notice.reminded = true;
994
+ return {
995
+ entries: [...event.entries, {
996
+ type: "custom_message", customType: "subagent-completion-unanswered", display: true,
997
+ content: "Completion wake ended silently. See the subagent completion notices above. " + COMPLETION_ACTION,
998
+ }],
999
+ continue: true,
1000
+ };
1001
+ }
1002
+ for (const [content] of ignored)
1003
+ unansweredCompletions.delete(content);
1004
+ updateSettleSubscription();
1005
+ return {
1006
+ entries: [...event.entries, {
1007
+ type: "custom_message", customType: "subagent-completion-unhandled", display: true,
1008
+ content: "UNHANDLED: no response to the subagent completion notices above. Reminder budget exhausted; results remain saved. No work was rerun or approval inferred.",
1009
+ }],
1010
+ };
1011
+ };
1012
+ const updateSettleSubscription = (): void => {
1013
+ if (!disposed && unansweredCompletions.size && !unsubscribeSettle)
1014
+ unsubscribeSettle = pi.on?.("agent_before_settle", handleBeforeSettle);
1015
+ if (disposed || !unansweredCompletions.size) {
1016
+ unsubscribeSettle?.();
1017
+ unsubscribeSettle = undefined;
1018
+ }
1019
+ };
885
1020
  const unsubscribeAsync = pi.events.on(SUBAGENT_ASYNC_COMPLETE_EVENT, (data) => {
886
1021
  if ((data as CompletionNotification).awaitedByWorkflow === true) return;
887
1022
  void deliver(data as CompletionNotification);
@@ -892,12 +1027,50 @@ export default function registerSubagentNotify(
892
1027
 
893
1028
  return {
894
1029
  deliver,
895
- hasPendingDelivery: () => pending.size > 0,
1030
+ hasPendingDelivery: () => pending.size > 0 || unstartedWakes.length > 0,
1031
+ messageStarted(message) {
1032
+ if (message.role !== "custom" || message.customType !== "subagent-notify") return;
1033
+ const index = unstartedWakes.indexOf(message.content as string);
1034
+ if (index !== -1) unstartedWakes.splice(index, 1);
1035
+ },
1036
+ bindSession(sessionManager) {
1037
+ if (disposed) return;
1038
+ const sessionId = sessionManager.getSessionId(); // UUID, not state.currentSessionId's possible file path.
1039
+ const retained = queuedWakes.get(sessionManager);
1040
+ const wakes = retained?.sessionId === sessionId ? retained.wakes : [];
1041
+ const unanswered = retained?.sessionId === sessionId && retained.unansweredCompletions instanceof Map
1042
+ ? retained.unansweredCompletions
1043
+ : new Map<string, { reminded: boolean }>(wakes.map(content => [content, { reminded: false }]));
1044
+ // Before the first bind, local wakes belong to this session; after it, to the previous one.
1045
+ if (!bound) {
1046
+ wakes.push(...unstartedWakes);
1047
+ for (const [content, notice] of unansweredCompletions) unanswered.set(content, notice);
1048
+ }
1049
+ bound = true;
1050
+ unstartedWakes = wakes;
1051
+ unansweredCompletions = unanswered;
1052
+ queuedWakes.set(sessionManager, { sessionId, wakes, unansweredCompletions });
1053
+ updateSettleSubscription();
1054
+ },
1055
+ sessionShutdown(reason) {
1056
+ if (reason !== "reload") {
1057
+ unstartedWakes.length = 0;
1058
+ unansweredCompletions.clear();
1059
+ }
1060
+ unsubscribeSettle?.();
1061
+ unsubscribeSettle = undefined;
1062
+ },
1063
+ flush() {
1064
+ for (const batcher of batchers.values()) batcher.flush();
1065
+ },
896
1066
  dispose() {
897
1067
  if (disposed) return;
898
1068
  disposed = true;
1069
+ updateSettleSubscription();
899
1070
  for (const batcher of batchers.values()) settle(batcher.dispose(), false, "dispose_pending");
900
1071
  batchers.clear();
1072
+ // Retained state belongs to the session manager; disposal must not erase it on reload.
1073
+ unansweredCompletions = new Map();
901
1074
  for (const unsubscribe of [unsubscribeAsync, unsubscribeForeground]) {
902
1075
  try {
903
1076
  unsubscribe?.();
@@ -1,6 +1,8 @@
1
+ import { createHash } from "node:crypto";
1
2
  import * as fs from "node:fs";
2
3
  import * as path from "node:path";
3
4
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
5
+ import { withFileLease } from "../../shared/file-lease.ts";
4
6
  import { MISSION_BINDING_FILE } from "../../missions/lifecycle.ts";
5
7
  import { encodeIndexSegment, indexSegmentAliases, MAX_INDEX_SEGMENT_BYTES } from "./index-segment.ts";
6
8
 
@@ -11,6 +13,7 @@ const RUN_INDEX_DIR = "runs";
11
13
  const OBSERVER_INDEX_DIR = "observers";
12
14
  const TOOL_CALL_INDEX_DIR = "tool-calls";
13
15
  const RESULT_PENDING_DIR = "result-pending";
16
+ const RESULT_LEASE_DIR = "result-leases";
14
17
  const MISSION_OBSERVER = "mission";
15
18
  const JSON_EXTENSION = ".json";
16
19
  const MAX_JSON_FILE_STEM_BYTES = MAX_INDEX_SEGMENT_BYTES - Buffer.byteLength(JSON_EXTENSION, "utf-8");
@@ -166,8 +169,18 @@ function writeIndexedPendingResultFile(resultPath: string, data: Record<string,
166
169
  const sessionId = nonEmptyString(data.sessionId);
167
170
  if (!sessionId) throw new Error(`Cannot write async result '${resultPath}' without a sessionId.`);
168
171
  const resultsDir = path.dirname(resultPath);
169
- writeAtomicJson(resultPendingPath(resultsDir, sessionId, runId), data);
170
- writeResultIndexForData(resultPath, data);
172
+ // A consumer can take the payload and remove its indexes as soon as the payload appears,
173
+ // so every index must exist before then. A failed index write still publishes the
174
+ // payload, unindexed but recoverable, before the error is rethrown.
175
+ let indexFailure: { error: unknown } | undefined;
176
+ writeAtomicJson(resultPendingPath(resultsDir, sessionId, runId), data, () => {
177
+ try {
178
+ writeResultIndexForData(resultPath, data);
179
+ } catch (error) {
180
+ indexFailure = { error };
181
+ }
182
+ });
183
+ if (indexFailure) throw indexFailure.error;
171
184
  return { runId, sessionId, resultsDir };
172
185
  }
173
186
 
@@ -228,6 +241,99 @@ export function removeMissionObserverIndex(resultsDir: string, runId: string | u
228
241
  }
229
242
  }
230
243
 
244
+ /** Serializes one run's result publication and retirement across processes. Lookups never take it. */
245
+ export function withResultRunLease<T>(resultsDir: string, runId: string, action: () => T): T {
246
+ const leaseDir = path.join(resultsDir, RESULT_LEASE_DIR);
247
+ fs.mkdirSync(leaseDir, { recursive: true });
248
+ return withFileLease(path.join(leaseDir, createHash("sha256").update(runId).digest("hex")), action);
249
+ }
250
+
251
+ /**
252
+ * The exact payload text a consumer read, with the identity its indexes are keyed by.
253
+ * `stalePublic` is what the public path held, read just before `snapshot`, when it differed:
254
+ * every writer goes through the pending path and promotion empties it, so a pending payload is
255
+ * always newer than the public one beside it, and `stalePublic` is older than `snapshot`.
256
+ */
257
+ export interface ResultSnapshot {
258
+ runId: string;
259
+ sessionId?: string;
260
+ toolCallId?: string;
261
+ snapshot: string;
262
+ stalePublic?: string;
263
+ }
264
+
265
+ export function readResultPayload(filePath: string): string | undefined {
266
+ try {
267
+ return fs.readFileSync(filePath, "utf-8");
268
+ } catch (error) {
269
+ const code = (error as NodeJS.ErrnoException).code;
270
+ // A directory at the public path blocks promotion; it holds no payload.
271
+ if (code === "ENOENT" || code === "ENOTDIR" || code === "EISDIR" || isUnaddressableResultCandidate(error)) return undefined;
272
+ throw error;
273
+ }
274
+ }
275
+
276
+ // Pending paths come first so a reader promoting pending to public between two reads is still seen.
277
+ function resultPayloadCandidates(publicPath: string, read: ResultSnapshot): string[] {
278
+ return [...(read.sessionId ? resultPendingPaths(path.dirname(publicPath), read.sessionId, read.runId) : []), publicPath];
279
+ }
280
+
281
+ /** A payload is one the consumer already read (or an older one it saw beside it), so not newer. */
282
+ function readByConsumer(publicPath: string, read: ResultSnapshot, candidate: string, current: string): boolean {
283
+ return current === read.snapshot || (candidate === publicPath && current === read.stalePublic);
284
+ }
285
+
286
+ /** Call under the run's lease: whether a payload written after the consumer read now exists for the run. */
287
+ export function resultSnapshotReplaced(publicPath: string, read: ResultSnapshot): boolean {
288
+ return resultPayloadCandidates(publicPath, read).some((candidate) => {
289
+ const current = readResultPayload(candidate);
290
+ return current !== undefined && !readByConsumer(publicPath, read, candidate, current);
291
+ });
292
+ }
293
+
294
+ /**
295
+ * Removes the payload a consumer read, the older public payload it saw beside it, and the run's
296
+ * indexes. When a newer payload replaced it, the shared payload paths and indexes stay and only
297
+ * the consumer's own claimed copy goes. A payload that cannot be removed is reported after the
298
+ * indexes are gone.
299
+ */
300
+ export function retireResultSnapshot(publicPath: string, read: ResultSnapshot, payloadPath = publicPath): "retired" | "replaced" {
301
+ const resultsDir = path.dirname(publicPath);
302
+ return withResultRunLease(resultsDir, read.runId, () => {
303
+ // Check every shared path before deleting any: unleased reader promotion can move a newer
304
+ // pending payload onto the public path between two deletions.
305
+ if (resultSnapshotReplaced(publicPath, read)) {
306
+ if (payloadPath !== publicPath && readResultPayload(payloadPath) === read.snapshot) fs.rmSync(payloadPath, { force: true });
307
+ return "replaced";
308
+ }
309
+ let removalFailure: { error: unknown } | undefined;
310
+ for (const candidate of new Set([...resultPayloadCandidates(publicPath, read), payloadPath])) {
311
+ const current = readResultPayload(candidate);
312
+ if (current === undefined || !readByConsumer(publicPath, read, candidate, current)) continue;
313
+ try {
314
+ fs.rmSync(candidate, { force: true });
315
+ } catch (error) {
316
+ removalFailure ??= { error };
317
+ }
318
+ }
319
+ removeResultIndex(resultsDir, read.sessionId, read.runId, read.toolCallId);
320
+ if (removalFailure) throw removalFailure.error;
321
+ return "retired";
322
+ });
323
+ }
324
+
325
+ /** Removes the mission observer index for the payload an observer handled, unless a newer payload replaced it. */
326
+ export function acknowledgeMissionObserverSnapshot(publicPath: string, read: ResultSnapshot): "acknowledged" | "replaced" {
327
+ const resultsDir = path.dirname(publicPath);
328
+ // With no index there is nothing to remove; skipping keeps the lease off runs without a mission.
329
+ if (!fs.existsSync(observerIndexPath(resultsDir, MISSION_OBSERVER, read.runId))) return "acknowledged";
330
+ return withResultRunLease(resultsDir, read.runId, () => {
331
+ if (resultSnapshotReplaced(publicPath, read)) return "replaced";
332
+ removeMissionObserverIndex(resultsDir, read.runId);
333
+ return "acknowledged";
334
+ });
335
+ }
336
+
231
337
  function existingResultFile(resultPath: string): boolean {
232
338
  try {
233
339
  return fs.statSync(resultPath).isFile();
@@ -307,6 +413,11 @@ export function fallbackResultPayloadPathForSessionRun(resultsDir: string, sessi
307
413
  return pendingPath;
308
414
  }
309
415
 
416
+ /** Any pending or public result file for the run, without validating its contents. */
417
+ export function resultPayloadFileForSessionRun(resultsDir: string, sessionId: string, runId: string): string | undefined {
418
+ return firstExistingResultFile([...resultPendingPaths(resultsDir, sessionId, runId), resultFilePath(resultsDir, runId)]);
419
+ }
420
+
310
421
  function resultPayloadLocationFromIndex(resultsDir: string, entry: ResultIndexEntry): ResultPayloadLocation | undefined {
311
422
  if (entry.file !== path.basename(entry.file) || !entry.file.endsWith(".json")) return undefined;
312
423
  const pendingState = promotePendingResultFile(resultsDir, entry.sessionId, entry.runId, entry.file);
@@ -361,9 +472,9 @@ export function resultPayloadPathForIndexedRun(resultsDir: string, runId: string
361
472
  fs.rmSync(entryPath, { force: true });
362
473
  return undefined;
363
474
  }
364
- const location = resultPayloadLocationFromIndex(resultsDir, entry);
365
- if (location) return location.path;
366
- fs.rmSync(entryPath, { force: true });
475
+ // A valid index can precede its payload while the writer is publishing it, so a lookup
476
+ // must not delete it. Payload-less indexes are swept by age in cleanupResultIndexes.
477
+ return resultPayloadLocationFromIndex(resultsDir, entry)?.path;
367
478
  } catch (error) {
368
479
  const code = (error as NodeJS.ErrnoException).code;
369
480
  if (isUnaddressableResultCandidate(error)) return undefined;