@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
@@ -35,7 +35,6 @@ export interface HerdrStatusRun {
35
35
  /** Explicit launch/workflow label only; raw prompts never enter pane metadata. */
36
36
  taskLabel?: string;
37
37
  needsAttention?: boolean;
38
- attentionLabel?: string;
39
38
  }
40
39
 
41
40
  export interface HerdrStatusBridgeOptions {
@@ -124,15 +123,10 @@ function completedRunId(data: unknown): string | undefined {
124
123
  return typeof id === "string" && id.length > 0 ? id : undefined;
125
124
  }
126
125
 
127
- function attentionNotice(data: unknown): { runId: string; label: string } | undefined {
126
+ function attentionRunId(data: unknown): string | undefined {
128
127
  if (!isRecord(data) || data.source !== "async" || !isRecord(data.event)) return undefined;
129
128
  if (data.event.type !== "needs_attention" || typeof data.event.runId !== "string" || !data.event.runId) return undefined;
130
- const label = typeof data.noticeText === "string" && data.noticeText
131
- ? data.noticeText
132
- : typeof data.event.message === "string" && data.event.message
133
- ? data.event.message
134
- : "subagent needs attention";
135
- return { runId: data.event.runId, label };
129
+ return data.event.runId;
136
130
  }
137
131
 
138
132
  export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): HerdrStatusBridge {
@@ -144,15 +138,15 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
144
138
  const refreshMs = options.refreshMs ?? DEFAULT_REFRESH_MS;
145
139
  const timers = options.timers ?? { setInterval, clearInterval };
146
140
  const runs = new Map<string, HerdrStatusRun>();
147
- const attentionLabels = new Map<string, string>();
141
+ // Child attention is addressed to the parent agent, so it only adds ⚠ to the
142
+ // metadata label and never raises Herdr's human-blocked state.
143
+ const attentionRuns = new Set<string>();
148
144
  const acknowledgedAttention = new Set<string>();
149
145
  const subscriptions: Array<() => void> = [];
150
146
  let rootSession = false;
151
147
  let published = false;
152
148
  let busyRaised = false;
153
149
  let busyLabel: string | undefined;
154
- let blockedRaised = false;
155
- let blockedLabel: string | undefined;
156
150
  let disposed = false;
157
151
  let pendingReport: readonly string[] | undefined;
158
152
  let draining = false;
@@ -176,7 +170,7 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
176
170
  const paneText = panes > 0 ? ` · ${panes} pane${panes === 1 ? "" : "s"}` : "";
177
171
  const task = activeTaskLabel();
178
172
  const taskText = task ? ` · ${task}` : "";
179
- const attention = includeAttention && attentionLabels.size > 0 ? " ⚠" : "";
173
+ const attention = includeAttention && attentionRuns.size > 0 ? " ⚠" : "";
180
174
  return `⏳ ${activeCount} subagent${activeCount === 1 ? "" : "s"}${who}${paneText}${taskText}${attention}`;
181
175
  };
182
176
 
@@ -186,7 +180,7 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
186
180
  const activeCount = activeSubagentCount();
187
181
  const task = boundedTaskLabel(activeTaskLabel(), MAX_TITLE_TASK_CHARS);
188
182
  const target = task ?? (activeCount === 1 && agentNames.length === 1 ? agentNames[0]! : String(activeCount));
189
- return `⏳${target}${attentionLabels.size > 0 ? "⚠" : ""}`;
183
+ return `⏳${target}${attentionRuns.size > 0 ? "⚠" : ""}`;
190
184
  };
191
185
 
192
186
  const enqueue = (args: readonly string[]): void => {
@@ -273,44 +267,22 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
273
267
  }
274
268
  };
275
269
 
276
- const syncBlocked = (): void => {
277
- if (!enabled || !rootSession || disposed) return;
278
- const nextLabel = [...attentionLabels.values()].at(-1);
279
- if (nextLabel !== undefined) {
280
- if (blockedRaised && blockedLabel === nextLabel) return;
281
- // Herdr's sibling overlay contract is counted. Lower before changing
282
- // the active label so this bridge continues to own exactly one count.
283
- if (blockedRaised) options.events.emit("herdr:blocked", { active: false });
284
- blockedRaised = true;
285
- blockedLabel = nextLabel;
286
- options.events.emit("herdr:blocked", { active: true, label: nextLabel });
287
- return;
288
- }
289
- if (blockedRaised) {
290
- blockedRaised = false;
291
- blockedLabel = undefined;
292
- options.events.emit("herdr:blocked", { active: false });
293
- }
294
- };
295
-
296
270
  const clearAttention = (): void => {
297
- attentionLabels.clear();
298
- syncBlocked();
271
+ attentionRuns.clear();
299
272
  publish();
300
273
  };
301
274
 
302
- const raiseAttention = (runId: string, labelText: string): void => {
303
- if (!rootSession || attentionLabels.has(runId)) return;
275
+ const raiseAttention = (runId: string): void => {
276
+ if (!rootSession || attentionRuns.has(runId)) return;
304
277
  acknowledgedAttention.delete(runId);
305
- attentionLabels.set(runId, labelText);
306
- syncBlocked();
278
+ attentionRuns.add(runId);
307
279
  publish();
308
280
  };
309
281
 
310
282
  const replaceRuns = (nextRuns: Iterable<HerdrStatusRun>): void => {
311
- const nextAttention = new Map<string, string>();
312
283
  const activeIds = new Set<string>();
313
284
  runs.clear();
285
+ attentionRuns.clear();
314
286
  for (const run of nextRuns) {
315
287
  if (!run || typeof run.id !== "string" || !run.id) continue;
316
288
  activeIds.add(run.id);
@@ -320,17 +292,14 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
320
292
  if (!run.needsAttention) {
321
293
  acknowledgedAttention.delete(run.id);
322
294
  } else if (!acknowledgedAttention.has(run.id)) {
323
- nextAttention.set(run.id, run.attentionLabel || attentionLabels.get(run.id) || "subagent needs attention");
295
+ attentionRuns.add(run.id);
324
296
  }
325
297
  }
326
298
  for (const id of acknowledgedAttention) {
327
299
  if (!activeIds.has(id)) acknowledgedAttention.delete(id);
328
300
  }
329
- attentionLabels.clear();
330
- for (const [id, labelText] of nextAttention) attentionLabels.set(id, labelText);
331
301
  syncBusy();
332
302
  syncRefreshTimer();
333
- syncBlocked();
334
303
  publish();
335
304
  };
336
305
 
@@ -371,22 +340,22 @@ export function registerHerdrStatusBridge(options: HerdrStatusBridgeOptions): He
371
340
  const id = completedRunId(data);
372
341
  if (!id || !runs.delete(id)) return;
373
342
  acknowledgedAttention.delete(id);
374
- if (attentionLabels.delete(id)) syncBlocked();
343
+ attentionRuns.delete(id);
375
344
  syncBusy();
376
345
  syncRefreshTimer();
377
346
  publish();
378
347
  });
379
348
  subscribe(SUBAGENT_CONTROL_EVENT, (data) => {
380
349
  if (!rootSession) return;
381
- const notice = attentionNotice(data);
382
- if (!notice || !runs.has(notice.runId)) return;
383
- raiseAttention(notice.runId, notice.label);
350
+ const runId = attentionRunId(data);
351
+ if (!runId || !runs.has(runId)) return;
352
+ raiseAttention(runId);
384
353
  });
385
354
  }
386
355
 
387
356
  return {
388
357
  agentStarted() {
389
- for (const id of attentionLabels.keys()) acknowledgedAttention.add(id);
358
+ for (const id of attentionRuns) acknowledgedAttention.add(id);
390
359
  clearAttention();
391
360
  },
392
361
  sessionStarted({ hasUI, runs: restoredRuns }) {
@@ -0,0 +1,215 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { AsyncJobState } from "../shared/types.ts";
3
+ import { sanitizeDisplayText } from "../shared/display-text.ts";
4
+
5
+ /**
6
+ * Reports each subagent run to the terminal with OSC 7501, the Program Status Protocol
7
+ * (https://www.superlogical.com/rex/docs/build/program-status). Pi owns the root record;
8
+ * runs live under `subagents/`.
9
+ */
10
+
11
+ type ProgramState = "working" | "blocked" | "done" | "error" | "idle";
12
+
13
+ const ID_ROOT = "subagents";
14
+ const MAX_RECORDS = 64;
15
+ const MAX_MSG_BYTES = 2048;
16
+ const MAX_TITLE_BYTES = 192;
17
+ const RUN_SEGMENT_CHARS = 12;
18
+ // 32-character segment limit, minus the run part and the `.` separator.
19
+ const MAX_KEY_CHARS = 32 - RUN_SEGMENT_CHARS - 1;
20
+
21
+ export interface ProgramStatusReporterOptions {
22
+ /** `programStatus` from the user config; only `false` turns it off. */
23
+ enabled: boolean;
24
+ getJobs: () => Iterable<AsyncJobState>;
25
+ /** Pending native supervisor requests that expect a reply. */
26
+ getPendingRequests: () => Iterable<{ id: string; runId: string }>;
27
+ write?: (data: string) => void;
28
+ isTTY?: boolean;
29
+ env?: Record<string, string | undefined>;
30
+ }
31
+
32
+ export interface ProgramStatusReporter {
33
+ /** Only the interactive TUI session on a real terminal reports. */
34
+ sessionStarted(input: { hasUI: boolean; mode?: string }): void;
35
+ sync(): void;
36
+ agentStarted(): void;
37
+ agentSettled(): void;
38
+ /**
39
+ * Stops reporting. Unless Pi is quitting, clears every record sent, since the runtime that replaces
40
+ * this one cannot clear them. On quit, finished records stay for the user, as the spec intends.
41
+ */
42
+ dispose(shutdownReason?: string): void;
43
+ }
44
+
45
+ // `.` is left out so it can only appear as the run/key separator.
46
+ function segment(value: string): string {
47
+ return value.replace(/[^A-Za-z0-9_+-]/g, "-");
48
+ }
49
+
50
+ function runSegment(runId: string): string {
51
+ return segment(runId.replace(/-/g, "").slice(0, RUN_SEGMENT_CHARS));
52
+ }
53
+
54
+ // A clear removes the record's descendants too, so workflow children are siblings of their run,
55
+ // never nested under another record of ours: `subagents/<run>.<key>`, one segment of at most 32 characters.
56
+ // A key that needs any change gets a hash of the original, so keys differing only in replaced characters stay distinct.
57
+ function keySegment(key: string): string {
58
+ if (key.length <= MAX_KEY_CHARS && /^[A-Za-z0-9_+-]+$/.test(key)) return key;
59
+ return `${segment(key).slice(0, 12)}-${createHash("sha1").update(key).digest("hex").slice(0, 6)}`;
60
+ }
61
+
62
+ function recordId(job: AsyncJobState): string | undefined {
63
+ if (job.parentWorkflowRunId && job.workflowKey) {
64
+ const parent = runSegment(job.parentWorkflowRunId);
65
+ return parent ? `${ID_ROOT}/${parent}.${keySegment(job.workflowKey)}` : undefined;
66
+ }
67
+ const run = runSegment(job.asyncId);
68
+ return run ? `${ID_ROOT}/${run}` : undefined;
69
+ }
70
+
71
+ function programState(job: AsyncJobState, blocked: boolean): ProgramState {
72
+ switch (job.status) {
73
+ case "queued":
74
+ case "running":
75
+ return blocked ? "blocked" : "working";
76
+ case "complete":
77
+ return "done";
78
+ case "failed":
79
+ case "partial":
80
+ case "rejected":
81
+ return "error";
82
+ case "stopped":
83
+ case "paused":
84
+ return "idle";
85
+ }
86
+ }
87
+
88
+ function jobLabel(job: AsyncJobState): string {
89
+ if (job.workflowKey) return job.workflowKey;
90
+ if (job.mode === "workflow") return "workflow";
91
+ const agents = [...new Set(job.agents ?? [])];
92
+ if (agents.length === 0) return "subagent";
93
+ return agents.length > 3 ? `${agents.slice(0, 3).join(", ")} +${agents.length - 3}` : agents.join(", ");
94
+ }
95
+
96
+ // Prompt text never goes into the record: it is shown outside the terminal grid.
97
+ function message(job: AsyncJobState, state: ProgramState): string {
98
+ switch (state) {
99
+ case "working":
100
+ return job.currentTool ? `Running ${job.currentTool}` : "Running";
101
+ case "blocked":
102
+ return "Waiting for a reply";
103
+ case "done":
104
+ return "Finished";
105
+ case "error":
106
+ return job.status === "partial" ? "Finished with failures" : job.status === "rejected" ? "Rejected" : "Failed";
107
+ case "idle":
108
+ return job.status === "paused" ? "Paused" : "Stopped";
109
+ }
110
+ }
111
+
112
+ function encodeText(text: string, maxBytes: number): string {
113
+ let bytes = Buffer.from(sanitizeDisplayText(text), "utf-8");
114
+ if (bytes.length > maxBytes) {
115
+ let end = maxBytes;
116
+ while (end > 0 && (bytes[end]! & 0xc0) === 0x80) end--;
117
+ bytes = bytes.subarray(0, end);
118
+ }
119
+ return bytes.toString("base64");
120
+ }
121
+
122
+ function programStatusReport(fields: { state: ProgramState | "clear"; id: string; kind?: "question"; title?: string; msg?: string }): string {
123
+ const pairs = [`state=${fields.state}`, `id=${fields.id}`];
124
+ if (fields.state !== "clear") pairs.push("app=pi-subagents");
125
+ if (fields.kind) pairs.push(`kind=${fields.kind}`);
126
+ if (fields.title !== undefined) pairs.push(`title=${encodeText(fields.title, MAX_TITLE_BYTES)}`);
127
+ if (fields.msg !== undefined) pairs.push(`msg=${encodeText(fields.msg, MAX_MSG_BYTES)}`);
128
+ return `\x1b]7501;${pairs.join(":")}\x1b\\`;
129
+ }
130
+
131
+ export function registerProgramStatusReporter(options: ProgramStatusReporterOptions): ProgramStatusReporter {
132
+ const write = options.write ?? ((data: string) => { process.stdout.write(data); });
133
+ const env = options.env ?? process.env;
134
+ const isTTY = options.isTTY ?? process.stdout.isTTY === true;
135
+ const sent = new Map<string, string>();
136
+ let active = false;
137
+ let parentIdle = true;
138
+ // A request counts as waiting on the user only after the parent settled without answering it.
139
+ let unansweredAtSettle = new Set<string>();
140
+ // Pi clears every OSC 7501 record when it suspends on Ctrl+Z and re-reports only its own root
141
+ // record on resume, so the records this extension shows are sent again.
142
+ const resend = (): void => {
143
+ if (!active) return;
144
+ for (const report of sent.values()) write(report);
145
+ };
146
+ let listeningForResume = false;
147
+
148
+ // The shown records are recomputed from the current jobs on every sync: active runs first, then
149
+ // finished ones, each most recently updated first, up to the cap. Only the difference is written.
150
+ const sync = (): void => {
151
+ if (!active) return;
152
+ const blockedRuns = new Set<string>();
153
+ if (parentIdle) {
154
+ for (const request of options.getPendingRequests()) {
155
+ if (unansweredAtSettle.has(request.id)) blockedRuns.add(request.runId);
156
+ }
157
+ }
158
+ const candidates: Array<{ id: string; report: string; active: boolean; updatedAt: number }> = [];
159
+ for (const job of options.getJobs()) {
160
+ const id = recordId(job);
161
+ if (!id) continue;
162
+ const state = programState(job, blockedRuns.has(job.asyncId));
163
+ const report = programStatusReport({ state, id, ...(state === "blocked" ? { kind: "question" as const } : {}), title: jobLabel(job), msg: message(job, state) });
164
+ candidates.push({ id, report, active: state === "working" || state === "blocked", updatedAt: job.updatedAt ?? job.startedAt ?? 0 });
165
+ }
166
+ candidates.sort((left, right) => Number(right.active) - Number(left.active) || right.updatedAt - left.updatedAt || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0));
167
+ const desired = new Map<string, string>();
168
+ for (const candidate of candidates) {
169
+ if (desired.size === MAX_RECORDS) break;
170
+ if (!desired.has(candidate.id)) desired.set(candidate.id, candidate.report);
171
+ }
172
+ for (const id of sent.keys()) {
173
+ if (desired.has(id)) continue;
174
+ sent.delete(id);
175
+ write(programStatusReport({ state: "clear", id }));
176
+ }
177
+ for (const [id, report] of desired) {
178
+ if (sent.get(id) === report) continue;
179
+ sent.set(id, report);
180
+ write(report);
181
+ }
182
+ };
183
+
184
+ return {
185
+ sessionStarted({ hasUI, mode }) {
186
+ active = options.enabled && hasUI && mode === "tui" && isTTY && env.TERM !== "dumb" && env.PI_PROGRAM_STATUS !== "0";
187
+ if (active && !listeningForResume && process.platform !== "win32") {
188
+ process.on("SIGCONT", resend);
189
+ listeningForResume = true;
190
+ }
191
+ sync();
192
+ },
193
+ sync,
194
+ agentStarted() {
195
+ parentIdle = false;
196
+ sync();
197
+ },
198
+ agentSettled() {
199
+ parentIdle = true;
200
+ unansweredAtSettle = new Set([...options.getPendingRequests()].map((request) => request.id));
201
+ sync();
202
+ },
203
+ dispose(shutdownReason) {
204
+ if (active && shutdownReason !== "quit") {
205
+ for (const id of sent.keys()) write(programStatusReport({ state: "clear", id }));
206
+ }
207
+ sent.clear();
208
+ active = false;
209
+ if (listeningForResume) {
210
+ process.off("SIGCONT", resend);
211
+ listeningForResume = false;
212
+ }
213
+ },
214
+ };
215
+ }
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
5
- import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
5
+ import type { AgentBeforeSettleEvent, AgentBeforeSettleEventResult, ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
6
6
  import { Type } from "typebox";
7
7
  import type { ChildSupervisorMetadata } from "../runs/shared/child-runtime-config.ts";
8
8
  import { INTERCOM_DETACH_REQUEST_EVENT, POLL_INTERVAL_MS, TEMP_ROOT_DIR, type ControlEvent, type IntercomEventBus, type SubagentState } from "../shared/types.ts";
@@ -88,6 +88,7 @@ interface NativeSupervisorChannelDeps {
88
88
  getChannelDirs?: () => { dirs: string[]; retire?: () => void };
89
89
  /** Retained scheduled states for the current runtime owner, never foreign owners. */
90
90
  getCurrentOwnerStates?: () => Iterable<SubagentState>;
91
+ parentWake?: Pick<ExtensionAPI, "sendMessage">;
91
92
  platform?: NodeJS.Platform;
92
93
  watch?: SupervisorWatch;
93
94
  timers?: Pick<typeof globalThis, "setInterval" | "clearInterval" | "setImmediate" | "clearImmediate">;
@@ -511,7 +512,7 @@ function requestVisibleText(request: PendingSupervisorRequest): string {
511
512
  if (request.interview !== undefined) lines.push(JSON.stringify(request.interview, null, "\t"));
512
513
  }
513
514
  if (request.expectsReply) lines.push("", `Reply with: ${supervisorReplyHint(request.id)}`);
514
- lines.push("", `Live guidance: subagent({ action: "steer", id: ${JSON.stringify(request.runId)}, index: ${request.childIndex}, message: "..." })${request.expectsReply ? " (Reply to the pending request first.)" : ""}`);
515
+ lines.push("", `Live guidance: subagent({ action: "steer", id: ${JSON.stringify(request.runId)}, message: "...", options: { index: ${request.childIndex} } })${request.expectsReply ? " (Reply to the pending request first.)" : ""}`);
515
516
  return lines.join("\n").trimEnd();
516
517
  }
517
518
 
@@ -607,8 +608,8 @@ function buildParentSupervisorTool(pi: ExtensionAPI, pending: Map<string, Pendin
607
608
  const request = resolvePendingRequest(pending, input);
608
609
  const reply = writeReply(request, input.message ?? "");
609
610
  appendSupervisorReplyEntry(pi, request, reply);
610
- onLifecycle(request, "resolved");
611
611
  pending.delete(request.id);
612
+ onLifecycle(request, "resolved");
612
613
  clearForegroundSupervisorAttention(request, pending, state);
613
614
  return { content: [{ type: "text", text: `Replied to supervisor request ${request.id}.` }], details: { replyTo: request.id, runId: request.runId, agent: request.agent } };
614
615
  }
@@ -636,6 +637,9 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
636
637
  return state;
637
638
  };
638
639
  const pending = new Map<string, PendingSupervisorRequest>();
640
+ // One continuation and one warning per request; never auto-answer or loop.
641
+ const settleNotices = new Map<string, "reminded" | "warned" | "handled">();
642
+ let unsubscribeSettle: (() => void) | undefined;
639
643
  const requestCorrelations = new Map<string, SupervisorRequestCorrelation>();
640
644
  const correlationKey = (request: { runId: string; agent: string; childIndex: number; toolCallId?: string }): string | undefined => {
641
645
  if (!request.toolCallId) return undefined;
@@ -664,7 +668,9 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
664
668
  pruneRequestCorrelations();
665
669
  };
666
670
  const observeRequestLifecycle: SupervisorRequestLifecycleObserver = (request, lifecycle) => {
671
+ settleNotices.delete(request.id);
667
672
  if (lifecycle !== "wrong-session") rememberResolvedRequest(request);
673
+ updateSettleSubscription();
668
674
  };
669
675
  const getSupervisorRequestState = (event: ControlEvent): SupervisorRequestState => {
670
676
  if (event.currentTool === "intercom" || event.index === undefined) return "unknown";
@@ -751,11 +757,12 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
751
757
  }
752
758
  rememberPendingRequest(request);
753
759
  pending.set(request.id, request);
760
+ updateSettleSubscription();
754
761
  markForegroundSupervisorAttention(request, state);
755
762
  // The ask is already queued above. A sendMessage failure (no UI, stale context) must not
756
763
  // lose it, and must not abort the loop before the remaining asks register.
757
764
  try {
758
- pi.sendMessage({
765
+ (deps.parentWake ?? pi).sendMessage({
759
766
  customType: SUPERVISOR_REQUEST_MESSAGE_TYPE,
760
767
  content: requestVisibleText(request),
761
768
  display: true,
@@ -785,6 +792,70 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
785
792
  if (pending.has(request.id)) markForegroundSupervisorAttention(request, state);
786
793
  }
787
794
  channels?.retire?.();
795
+ updateSettleSubscription();
796
+ };
797
+
798
+ const handleBeforeSettle = (event: AgentBeforeSettleEvent): AgentBeforeSettleEventResult | undefined => {
799
+ if (!started || event.outcome !== "completed")
800
+ return;
801
+ refreshPendingRequests(pending, state, observeRequestLifecycle, runState);
802
+ if (event.continue || event.context.pendingMessages.length)
803
+ return;
804
+ const messages = event.context.contextMessages;
805
+ const requests = [...pending.values()].filter(request => {
806
+ if (!request.expectsReply || settleNotices.get(request.id) === "warned" || settleNotices.get(request.id) === "handled") return false;
807
+ const index = messages.findLastIndex(message => message.role === "custom"
808
+ && message.customType === SUPERVISOR_REQUEST_MESSAGE_TYPE
809
+ && (message.details as { requestId?: string } | undefined)?.requestId === request.id);
810
+ const acted = index !== -1 && messages.slice(index + 1).some(message => message.role === "assistant"
811
+ && message.content.some(part => part.type === "toolCall" || (part.type === "text" && part.text.trim())));
812
+ if (index === -1 || acted) {
813
+ settleNotices.set(request.id, "handled");
814
+ return false;
815
+ }
816
+ return true;
817
+ });
818
+ updateSettleSubscription();
819
+ if (!requests.length) return;
820
+ const unanswered = requests.filter(request => !settleNotices.has(request.id));
821
+ if (unanswered.length) {
822
+ for (const request of unanswered)
823
+ settleNotices.set(request.id, "reminded");
824
+ return {
825
+ entries: [...event.entries, {
826
+ type: "custom_message",
827
+ customType: "subagent-supervisor-unanswered",
828
+ content: "Silent supervisor wake. Pending request IDs: " + requests.map(request => request.id).join(", ") + ". Check subagent_supervisor({ action: \"pending\" }) and reply within existing authority, or explicitly ask the user for approval. Do not auto-approve.",
829
+ display: true,
830
+ details: { requestIds: requests.map(request => request.id) },
831
+ }],
832
+ continue: true,
833
+ };
834
+ }
835
+ const unflagged = requests.filter(request => settleNotices.get(request.id) !== "warned");
836
+ if (!unflagged.length)
837
+ return;
838
+ for (const request of unflagged)
839
+ settleNotices.set(request.id, "warned");
840
+ updateSettleSubscription();
841
+ return {
842
+ entries: [...event.entries, {
843
+ type: "custom_message",
844
+ customType: "subagent-supervisor-blocked",
845
+ content: "BLOCKED: unanswered supervisor request IDs: " + unflagged.map(request => request.id).join(", ") + ". Reminder budget exhausted; no reply or approval sent. Inspect subagent_supervisor({ action: \"pending\" }).",
846
+ display: true,
847
+ details: { blocked: true, requestIds: unflagged.map(request => request.id) },
848
+ }],
849
+ };
850
+ };
851
+ const updateSettleSubscription = (): void => {
852
+ const needed = started && [...pending.values()].some(request => request.expectsReply
853
+ && settleNotices.get(request.id) !== "warned" && settleNotices.get(request.id) !== "handled");
854
+ if (needed && !unsubscribeSettle) unsubscribeSettle = pi.on?.("agent_before_settle", handleBeforeSettle);
855
+ if (!needed) {
856
+ unsubscribeSettle?.();
857
+ unsubscribeSettle = undefined;
858
+ }
788
859
  };
789
860
 
790
861
  const startPolling = (): void => {
@@ -901,6 +972,7 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
901
972
  },
902
973
  dispose: () => {
903
974
  started = false;
975
+ updateSettleSubscription();
904
976
  try {
905
977
  rootWatcher?.close();
906
978
  } catch {
@@ -918,6 +990,7 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
918
990
  if (deferredWatcherRefresh) timers.clearImmediate(deferredWatcherRefresh);
919
991
  deferredWatcherRefresh = undefined;
920
992
  pending.clear();
993
+ settleNotices.clear();
921
994
  requestCorrelations.clear();
922
995
  seenFiles.clear();
923
996
  },
@@ -231,7 +231,7 @@ function asyncResumeGuidance(input: {
231
231
  }
232
232
  if (resumable.length > 0) {
233
233
  const firstIndex = resumable[0]?.index ?? input.children.indexOf(resumable[0]!);
234
- return `Revive child: subagent({ action: "resume", id: "${input.asyncId}", index: ${firstIndex}, message: "..." })`;
234
+ return `Revive child: subagent({ action: "resume", id: "${input.asyncId}", message: "...", options: { index: ${firstIndex} } })`;
235
235
  }
236
236
  return "Resume: unavailable; no child session file was persisted.";
237
237
  }
@@ -279,7 +279,7 @@ function formatSubagentResultIntercomMessage(input: {
279
279
  for (let index = 0; index < input.children.length; index++) {
280
280
  const child = input.children[index]!;
281
281
  lines.push("");
282
- lines.push(`${index + 1}. ${child.agent} — process ${child.status} · output ${child.outputState ?? "unknown"}`);
282
+ lines.push(`${index + 1}. ${child.agent} — process ${child.status} · output ${child.outputState ?? "unknown"}${child.outputPartial ? " (partial)" : ""}`);
283
283
  if (child.intercomTarget) lines.push(`${input.source === "async" ? "Previous intercom target" : "Run intercom target"}: ${child.intercomTarget}`);
284
284
  if (child.artifactPath) lines.push(`Output artifact: ${child.artifactPath}`);
285
285
  if (child.sessionPath) lines.push(`Session: ${child.sessionPath}`);
@@ -295,6 +295,7 @@ export function buildSubagentResultIntercomPayload(input: GroupedResultIntercomM
295
295
  const children = input.children.map((child) => ({
296
296
  ...child,
297
297
  outputState: child.outputState ?? "unknown",
298
+ ...(child.outputPartial ? { outputPartial: true } : {}),
298
299
  summary: child.summary.trim() || "(no output)",
299
300
  children: compactNestedResultChildren(child.children),
300
301
  }));