@xzzpig/pi-subagents 0.20.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 (140) hide show
  1. package/CHANGELOG.md +154 -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 +72 -7
  9. package/docs/configuration.md +58 -7
  10. package/docs/extension-api.md +36 -11
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +34 -17
  13. package/docs/models.md +1 -1
  14. package/docs/observability.md +10 -5
  15. package/docs/tool-reference.md +117 -84
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +16 -7
  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 +191 -145
  32. package/src/api/preflight.ts +8 -4
  33. package/src/extension/config.ts +21 -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 +114 -132
  40. package/src/extension/reply-workflow-script.ts +20 -11
  41. package/src/extension/rpc.ts +11 -6
  42. package/src/extension/schemas.ts +34 -30
  43. package/src/extension/subagent-guide.ts +86 -6
  44. package/src/extension/subagent-options.ts +47 -0
  45. package/src/extension/tool-activation.ts +3 -2
  46. package/src/extension/tool-description.ts +51 -68
  47. package/src/inspectors/actions.ts +37 -11
  48. package/src/inspectors/plugins.ts +3 -2
  49. package/src/inspectors/tmux/actions.ts +204 -0
  50. package/src/inspectors/tmux/client.ts +85 -0
  51. package/src/inspectors/tmux/plugin.ts +21 -0
  52. package/src/integrations/herdr-status.ts +18 -49
  53. package/src/integrations/program-status.ts +215 -0
  54. package/src/intercom/native-supervisor-channel.ts +77 -4
  55. package/src/intercom/result-intercom.ts +3 -2
  56. package/src/intercom/supervisor-ui.ts +2 -174
  57. package/src/missions/store.ts +25 -5
  58. package/src/profiles/profiles.ts +24 -21
  59. package/src/runs/background/active-async-capacity.ts +58 -8
  60. package/src/runs/background/async-execution.ts +143 -38
  61. package/src/runs/background/async-job-tracker.ts +11 -4
  62. package/src/runs/background/async-resume.ts +5 -2
  63. package/src/runs/background/await-async-run.ts +14 -9
  64. package/src/runs/background/binary-bootstrap.ts +2 -1
  65. package/src/runs/background/calendar-schedule.ts +90 -0
  66. package/src/runs/background/chain-root-attachment.ts +9 -5
  67. package/src/runs/background/fleet-view.ts +5 -5
  68. package/src/runs/background/notify.ts +185 -12
  69. package/src/runs/background/result-files.ts +116 -5
  70. package/src/runs/background/result-watcher.ts +99 -66
  71. package/src/runs/background/resume-guidance.ts +2 -2
  72. package/src/runs/background/run-child-session.ts +16 -2
  73. package/src/runs/background/run-id-resolver.ts +8 -5
  74. package/src/runs/background/run-status.ts +21 -16
  75. package/src/runs/background/runner-child-launch.ts +1 -0
  76. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  77. package/src/runs/background/scheduled-runs.ts +256 -61
  78. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  79. package/src/runs/background/subagent-runner.ts +32 -12
  80. package/src/runs/background/subagent-wait.ts +38 -19
  81. package/src/runs/background/terminal-run-index.ts +46 -1
  82. package/src/runs/background/wait-completions.ts +1 -0
  83. package/src/runs/background/wait-tool.ts +33 -23
  84. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  85. package/src/runs/foreground/async-stop-action.ts +48 -22
  86. package/src/runs/foreground/execution.ts +94 -52
  87. package/src/runs/foreground/foreground-history.ts +1 -0
  88. package/src/runs/foreground/subagent-executor.ts +207 -77
  89. package/src/runs/shared/child-commands.ts +2 -1
  90. package/src/runs/shared/child-hooks.ts +4 -3
  91. package/src/runs/shared/child-launch.ts +3 -0
  92. package/src/runs/shared/child-session.ts +41 -24
  93. package/src/runs/shared/child-tool-plan.ts +13 -26
  94. package/src/runs/shared/dynamic-fanout.ts +1 -1
  95. package/src/runs/shared/fork-command-result.ts +10 -0
  96. package/src/runs/shared/herdr-placed-run.ts +5 -4
  97. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
  98. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  99. package/src/runs/shared/model-resolution.ts +30 -1
  100. package/src/runs/shared/nested-events.ts +5 -0
  101. package/src/runs/shared/parallel-handoff.ts +56 -8
  102. package/src/runs/shared/parallel-utils.ts +2 -0
  103. package/src/runs/shared/partial-output.ts +48 -0
  104. package/src/runs/shared/runner-launcher.ts +25 -0
  105. package/src/runs/shared/single-output.ts +53 -0
  106. package/src/runs/shared/structured-output.ts +14 -7
  107. package/src/runs/shared/subagent-control.ts +3 -3
  108. package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
  109. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  110. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  111. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  112. package/src/runs/shared/worktree-lock.ts +29 -0
  113. package/src/runs/shared/worktree.ts +12 -1
  114. package/src/shared/atomic-json.ts +4 -2
  115. package/src/shared/edit-distance.ts +33 -0
  116. package/src/shared/file-lease.ts +74 -0
  117. package/src/shared/formatters.ts +1 -5
  118. package/src/shared/model-info.ts +22 -0
  119. package/src/shared/package-version.ts +17 -0
  120. package/src/shared/parent-wake.ts +79 -0
  121. package/src/shared/pruned-fork.ts +7 -1
  122. package/src/shared/runtime-module-path.ts +19 -0
  123. package/src/shared/settings-file-lease.ts +36 -0
  124. package/src/shared/types.ts +36 -2
  125. package/src/shared/utils.ts +8 -6
  126. package/src/slash/slash-commands.ts +3 -3
  127. package/src/slash/subagents-admin.ts +2 -1
  128. package/src/tui/fleet-native-transcript.ts +2 -0
  129. package/src/tui/fleet-transcript.ts +12 -3
  130. package/src/tui/fleet.ts +11 -8
  131. package/src/tui/render.ts +27 -19
  132. package/src/tui/subagent-messages.ts +305 -0
  133. package/src/watchdog/diff-tool.ts +2 -2
  134. package/src/watchdog/register-main.ts +2 -22
  135. package/src/watchdog/render.ts +2 -24
  136. package/src/watchdog/runtime.ts +6 -4
  137. package/src/watchdog/settings.ts +18 -13
  138. package/src/watchdog/tool-actions.ts +2 -2
  139. package/src/workflows/scripted-workflow.ts +20 -6
  140. package/src/workflows/workflow-resources.ts +11 -0
@@ -3,11 +3,11 @@ import { readStatus } from "../../shared/utils.ts";
3
3
  import { workflowAwaitedAsyncResultPath } from "./async-execution.ts";
4
4
  import { waitForImportedAsyncRoot, type ImportedAsyncRootResult } from "./chain-root-attachment.ts";
5
5
  import { currentPidNamespaceScope } from "./pid-namespace.ts";
6
- import { resultPayloadPathForSessionRun } from "./result-files.ts";
6
+ import { resultPayloadPathForSessionRun, resultSnapshotReplaced, withResultRunLease, type ResultSnapshot } from "./result-files.ts";
7
7
  import { checkPidLiveness } from "./stale-run-reconciler.ts";
8
8
 
9
9
  type ExistingAsyncRunOutcome =
10
- | { status: "settled"; result: ImportedAsyncRootResult }
10
+ | { status: "settled"; result: ImportedAsyncRootResult & { importedPublication: NonNullable<ImportedAsyncRootResult["importedPublication"]> } }
11
11
  | { status: "unavailable"; reason: string };
12
12
 
13
13
  function errorMessage(error: unknown): string {
@@ -60,18 +60,23 @@ export async function awaitExistingAsyncRun(asyncDir: string, runId: string, sig
60
60
  if (runnerExited) return { status: "unavailable", reason: `Async runner for run '${runId}' exited without publishing a result.` };
61
61
  // Only a parsed result file carries importedPublication; status-derived fallbacks do not.
62
62
  if (!completed.importedPublication) return { status: "unavailable", reason: `Async run '${runId}' ended without a result file at ${resultPath}.` };
63
- return { status: "settled", result: completed };
63
+ return { status: "settled", result: { ...completed, importedPublication: completed.importedPublication } };
64
64
  }
65
65
 
66
66
  /**
67
- * Renames the published result to a file owned by `claimant`. Only one of several
68
- * concurrent importers can win the rename; the others get undefined and launch fresh.
67
+ * Renames the published result to a file owned by `claimant`, if it is still the payload the
68
+ * claimant read. Only one of several concurrent importers can win the rename; the others, and a
69
+ * claimant whose payload a newer one replaced, get undefined and launch fresh.
69
70
  */
70
- export function claimWorkflowAwaitedResult(asyncDir: string, claimant: string): string | undefined {
71
- const claimedPath = `${workflowAwaitedAsyncResultPath(asyncDir)}.${claimant}.claimed`;
71
+ export function claimWorkflowAwaitedResult(asyncDir: string, claimant: string, read: ResultSnapshot): string | undefined {
72
+ const resultPath = workflowAwaitedAsyncResultPath(asyncDir);
73
+ const claimedPath = `${resultPath}.${claimant}.claimed`;
72
74
  try {
73
- fs.renameSync(workflowAwaitedAsyncResultPath(asyncDir), claimedPath);
74
- return claimedPath;
75
+ return withResultRunLease(asyncDir, read.runId, () => {
76
+ if (resultSnapshotReplaced(resultPath, read)) return undefined;
77
+ fs.renameSync(resultPath, claimedPath);
78
+ return claimedPath;
79
+ });
75
80
  } catch {
76
81
  return undefined;
77
82
  }
@@ -10,6 +10,7 @@ import * as typebox from "typebox";
10
10
  import * as typeboxCompile from "typebox/compile";
11
11
  import * as typeboxValue from "typebox/value";
12
12
  import { installRunnerHttpDispatcher } from "./runner-http-dispatcher.ts";
13
+ import { resolveRuntimeModuleExtension } from "../../shared/runtime-module-path.ts";
13
14
  import { runConfiguredSubagent, validateSubagentRunConfig } from "./subagent-runner-bootstrap.ts";
14
15
  import { getAgentDir } from "../../shared/utils.ts";
15
16
 
@@ -54,7 +55,7 @@ export default async function runBinaryBootstrap(): Promise<never> {
54
55
  "typebox/value": typeboxValue,
55
56
  },
56
57
  });
57
- const runner = `./subagent-runner${path.extname(fileURLToPath(import.meta.url))}`;
58
+ const runner = `./subagent-runner${resolveRuntimeModuleExtension(path.dirname(fileURLToPath(import.meta.url)), "subagent-runner")}`;
58
59
  return jiti.import<typeof import("./subagent-runner.ts")>(runner);
59
60
  },
60
61
  });
@@ -0,0 +1,90 @@
1
+ import { createRequire } from "node:module";
2
+ import type { Temporal } from "@js-temporal/polyfill";
3
+
4
+ const require = createRequire(import.meta.url);
5
+ let cachedTemporal: typeof Temporal | undefined;
6
+
7
+ function getTemporal(): typeof Temporal {
8
+ return cachedTemporal ??= (require("@js-temporal/polyfill") as typeof import("@js-temporal/polyfill")).Temporal;
9
+ }
10
+
11
+ export const CALENDAR_WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] as const;
12
+ export type CalendarWeekday = typeof CALENDAR_WEEKDAYS[number];
13
+ export type CalendarRule = { every: "day" | "week"; at: string; timezone: string; on?: CalendarWeekday[] };
14
+ export type CalendarOccurrence = { nextLocalDate: string; nextRunAt: string };
15
+ export type CalendarTrigger = CalendarRule & CalendarOccurrence & { kind: "calendar" };
16
+ const SEARCH_DAYS = 32;
17
+
18
+ export function normalizeCalendarRule(input: { every?: unknown; at?: unknown; timezone?: unknown; on?: unknown }): CalendarRule {
19
+ if (input.every !== "day" && input.every !== "week") throw new Error("Calendar every must be 'day' or 'week'.");
20
+ if (typeof input.at !== "string" || !/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(input.at)) throw new Error("Calendar at must use HH:mm (00:00-23:59).");
21
+ if (typeof input.timezone !== "string" || !input.timezone.trim() || /^[+-]/.test(input.timezone.trim())) throw new Error("Calendar timezone requires an IANA name, such as 'Asia/Taipei', or 'UTC'.");
22
+ let timezone: string;
23
+ try { timezone = new Intl.DateTimeFormat("en", { timeZone: input.timezone.trim() }).resolvedOptions().timeZone; }
24
+ catch { throw new Error(`Invalid calendar timezone '${input.timezone}'. Use an IANA name or 'UTC'.`); }
25
+ if (input.every === "day") {
26
+ if (input.on !== undefined) throw new Error("Daily schedules do not accept on; use every:'week' with a weekday array.");
27
+ return { every: "day", at: input.at, timezone };
28
+ }
29
+ if (!Array.isArray(input.on) || input.on.length === 0 || input.on.some((day) => !CALENDAR_WEEKDAYS.includes(day))) throw new Error("Weekly on must be a non-empty array of mon/tue/wed/thu/fri/sat/sun.");
30
+ const selected = input.on;
31
+ return { every: "week", at: input.at, timezone, on: CALENDAR_WEEKDAYS.filter((day) => selected.includes(day)) };
32
+ }
33
+
34
+ function localDate(value: string): Temporal.PlainDate {
35
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) throw new Error("Calendar nextLocalDate must use YYYY-MM-DD.");
36
+ return getTemporal().PlainDate.from(value, { overflow: "reject" });
37
+ }
38
+
39
+ function referenceDate(rule: CalendarRule, reference: number): Temporal.PlainDate {
40
+ return getTemporal().Instant.fromEpochMilliseconds(reference).toZonedDateTimeISO(rule.timezone).toPlainDate();
41
+ }
42
+
43
+ function occurrence(rule: CalendarRule, date: Temporal.PlainDate): CalendarOccurrence | undefined {
44
+ if (rule.every === "week" && !rule.on!.includes(CALENDAR_WEEKDAYS[date.dayOfWeek - 1]!)) return undefined;
45
+ const requested = date.toPlainDateTime(rule.at);
46
+ const zoned = requested.toZonedDateTime(rule.timezone, { disambiguation: "earlier" });
47
+ // Skip nonexistent times/dates. A repeated time uses its first instant only.
48
+ if (!zoned.toPlainDateTime().equals(requested)) return undefined;
49
+ return { nextLocalDate: date.toString(), nextRunAt: new Date(zoned.epochMilliseconds).toISOString() };
50
+ }
51
+
52
+ export function nextCalendarOccurrence(rule: CalendarRule, after: number, minimumDate?: string): CalendarOccurrence {
53
+ let date = referenceDate(rule, after);
54
+ if (minimumDate && getTemporal().PlainDate.compare(date, localDate(minimumDate)) < 0) date = localDate(minimumDate);
55
+ for (let i = 0; i < SEARCH_DAYS; i++, date = date.add({ days: 1 })) {
56
+ const candidate = occurrence(rule, date);
57
+ if (candidate && Date.parse(candidate.nextRunAt) > after) return candidate;
58
+ }
59
+ throw new Error("No valid calendar occurrence within 32 local dates; check the timezone and rule.");
60
+ }
61
+
62
+ export function latestCalendarOccurrence(rule: CalendarRule, now: number, minimumDate: string): CalendarOccurrence | undefined {
63
+ const floor = localDate(minimumDate);
64
+ let date = referenceDate(rule, now);
65
+ for (let i = 0; i < SEARCH_DAYS; i++, date = date.subtract({ days: 1 })) {
66
+ if (getTemporal().PlainDate.compare(date, floor) < 0) return undefined;
67
+ const candidate = occurrence(rule, date);
68
+ if (candidate && Date.parse(candidate.nextRunAt) <= now) return candidate;
69
+ }
70
+ throw new Error("No valid calendar occurrence within 32 local dates; check the timezone and rule.");
71
+ }
72
+
73
+ export function calendarDateAfter(rule: CalendarRule, consumedAt: number, pendingDate: string): string {
74
+ const consumed = referenceDate(rule, consumedAt);
75
+ const pending = localDate(pendingDate);
76
+ return (getTemporal().PlainDate.compare(consumed, pending) > 0 ? consumed : pending).add({ days: 1 }).toString();
77
+ }
78
+
79
+ /** Re-resolve the pending date using current timezone data, without consulting its UTC cache. */
80
+ export function restoreCalendarTrigger(input: CalendarTrigger): CalendarTrigger {
81
+ const rule = normalizeCalendarRule(input);
82
+ let date = localDate(input.nextLocalDate);
83
+ if (rule.every === "week" && !rule.on!.includes(CALENDAR_WEEKDAYS[date.dayOfWeek - 1]!)) throw new Error("Calendar nextLocalDate is outside the selected weekdays.");
84
+ if (typeof input.nextRunAt !== "string" || !Number.isFinite(Date.parse(input.nextRunAt))) throw new Error("Calendar nextRunAt must be a valid timestamp.");
85
+ for (let i = 0; i < SEARCH_DAYS; i++, date = date.add({ days: 1 })) {
86
+ const candidate = occurrence(rule, date);
87
+ if (candidate) return { kind: "calendar", ...rule, ...candidate };
88
+ }
89
+ throw new Error("No valid pending calendar occurrence within 32 local dates.");
90
+ }
@@ -13,7 +13,8 @@ export interface ImportedAsyncRoot {
13
13
 
14
14
  export interface ImportedAsyncRootResult {
15
15
  agent: string;
16
- importedPublication?: { sessionId?: string; toolCallId?: string };
16
+ /** `snapshot` is the payload text this result was built from, so cleanup can tell it from a newer one. */
17
+ importedPublication?: { sessionId?: string; toolCallId?: string; snapshot: string };
17
18
  /** Human-readable display name for the child session, when derived at launch. */
18
19
  sessionName?: string;
19
20
  output: string;
@@ -83,18 +84,20 @@ interface AsyncResultFile {
83
84
  const TERMINAL_STATES = new Set(["complete", "failed", "partial", "paused", "stopped"]);
84
85
  const TERMINAL_STEP_STATUSES = new Set(["complete", "completed", "failed", "partial", "paused", "stopped"]);
85
86
 
86
- function readResultFile(resultPath: string): AsyncResultFile | undefined {
87
+ function readResultFile(resultPath: string): { data: AsyncResultFile; raw: string } | undefined {
88
+ let raw: string;
87
89
  try {
88
- return JSON.parse(fs.readFileSync(resultPath, "utf-8")) as AsyncResultFile;
90
+ raw = fs.readFileSync(resultPath, "utf-8");
89
91
  } catch (error) {
90
92
  if (typeof error === "object" && error !== null && "code" in error && (error as NodeJS.ErrnoException).code === "ENOENT") {
91
93
  return undefined;
92
94
  }
93
95
  throw error;
94
96
  }
97
+ return { data: JSON.parse(raw) as AsyncResultFile, raw };
95
98
  }
96
99
 
97
- function readImportedResultFile(root: ImportedAsyncRoot, status: AsyncStatus | null): AsyncResultFile | undefined {
100
+ function readImportedResultFile(root: ImportedAsyncRoot, status: AsyncStatus | null): { data: AsyncResultFile; raw: string } | undefined {
98
101
  const direct = readResultFile(root.resultPath);
99
102
  if (direct || !status?.sessionId) return direct;
100
103
  const indexedPath = resultPayloadPathForSessionRun(path.dirname(root.resultPath), status.sessionId, root.runId);
@@ -180,7 +183,7 @@ function outputFromTimeout(root: ImportedAsyncRoot, status: AsyncStatus | null,
180
183
  };
181
184
  }
182
185
 
183
- function buildImportedResult(root: ImportedAsyncRoot, status: AsyncStatus | null, result: AsyncResultFile): ImportedAsyncRootResult {
186
+ function buildImportedResult(root: ImportedAsyncRoot, status: AsyncStatus | null, { data: result, raw }: { data: AsyncResultFile; raw: string }): ImportedAsyncRootResult {
184
187
  const child = result.results?.[root.index];
185
188
  const step = selectedStatusStep(status, root.index);
186
189
  const state = resultState(result, child);
@@ -197,6 +200,7 @@ function buildImportedResult(root: ImportedAsyncRoot, status: AsyncStatus | null
197
200
  importedPublication: {
198
201
  ...(typeof result.sessionId === "string" ? { sessionId: result.sessionId } : {}),
199
202
  ...(typeof result.toolCallId === "string" ? { toolCallId: result.toolCallId } : {}),
203
+ snapshot: raw,
200
204
  },
201
205
  output: success ? output : (output || error || ""),
202
206
  success,
@@ -359,7 +359,7 @@ function formatAsyncFleetLines(runs: AsyncRunSummary[], now = Date.now()): strin
359
359
  const runContext = contextModeLabel(run.context);
360
360
  lines.push(`- ${run.id} | ${run.state}${activity ? ` | ${activity}` : ""} | ${run.mode}${runContext ? ` ${runContext}` : ""} | ${progress}${pending} | ${cwd}`);
361
361
  lines.push(` status: subagent({ action: "status", id: "${run.id}" })`);
362
- lines.push(` transcript: subagent({ action: "status", id: "${run.id}", view: "transcript" })`);
362
+ lines.push(` transcript: subagent({ action: "status", id: "${run.id}", options: { view: "transcript" } })`);
363
363
  for (const step of run.steps) {
364
364
  const display = fleetStepDisplayName(step);
365
365
  const stepContext = contextModeLabel(step.context);
@@ -372,7 +372,7 @@ function formatAsyncFleetLines(runs: AsyncRunSummary[], now = Date.now()): strin
372
372
  if (fs.existsSync(output)) lines.push(` output: ${shortenPath(output)}`);
373
373
  if (step.sessionFile) lines.push(` session: ${shortenPath(step.sessionFile)}`);
374
374
  if (step.status === "running" || step.recentOutput?.length || fs.existsSync(output)) {
375
- lines.push(` transcript: subagent({ action: "status", id: "${run.id}", index: ${step.index}, view: "transcript" })`);
375
+ lines.push(` transcript: subagent({ action: "status", id: "${run.id}", options: { index: ${step.index}, view: "transcript" } })`);
376
376
  }
377
377
  lines.push(...formatNestedRunStatusLines(step.children, { indent: " ", commandHints: true, maxLines: 12 }));
378
378
  }
@@ -432,9 +432,9 @@ export function inspectSubagentFleet(_params: FleetViewParams, deps: FleetViewDe
432
432
  const asyncLines = formatAsyncFleetLines(asyncRuns, deps.now?.() ?? Date.now());
433
433
  if (asyncLines.length) lines.push(...asyncLines, "");
434
434
  lines.push("Commands:");
435
- lines.push(" Refresh fleet: subagent({ action: \"status\", view: \"fleet\" })");
436
- lines.push(" Tail run transcript: subagent({ action: \"status\", id: \"<run-id>\", view: \"transcript\" })");
437
- lines.push(" Tail child transcript: subagent({ action: \"status\", id: \"<run-id>\", index: 0, view: \"transcript\" })");
435
+ lines.push(" Refresh fleet: subagent({ action: \"status\", options: { view: \"fleet\" } })");
436
+ lines.push(" Tail run transcript: subagent({ action: \"status\", id: \"<run-id>\", options: { view: \"transcript\" } })");
437
+ lines.push(" Tail child transcript: subagent({ action: \"status\", id: \"<run-id>\", options: { index: 0, view: \"transcript\" } })");
438
438
 
439
439
  return { content: [{ type: "text", text: lines.join("\n").trimEnd() }], details: { mode: "management", results: [] } };
440
440
  }
@@ -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?.();