@xzzpig/pi-subagents 0.20.0 → 0.22.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 (144) hide show
  1. package/CHANGELOG.md +164 -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/fork-supervisor-routing.md +77 -0
  13. package/docs/missions.md +34 -17
  14. package/docs/models.md +1 -1
  15. package/docs/observability.md +10 -5
  16. package/docs/tool-reference.md +117 -84
  17. package/docs/watchdog.md +8 -6
  18. package/docs/workflows.md +16 -7
  19. package/index.ts +5 -0
  20. package/package.json +6 -3
  21. package/prompts/council.md +1 -1
  22. package/skills/pi-subagents/SKILL.md +1 -1
  23. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  24. package/skills/pi-subagents/references/execution-controls.md +16 -16
  25. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  26. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  27. package/src/agents/advertised-agent-prompt.ts +9 -1
  28. package/src/agents/agent-management.ts +4 -0
  29. package/src/agents/agent-memory.ts +3 -3
  30. package/src/agents/agent-scope.ts +4 -0
  31. package/src/agents/agent-serializer.ts +8 -1
  32. package/src/agents/agents.ts +191 -145
  33. package/src/api/preflight.ts +8 -4
  34. package/src/api/supervisor-routing.ts +196 -0
  35. package/src/extension/config.ts +21 -2
  36. package/src/extension/context-injection.ts +6 -1
  37. package/src/extension/control-notices.ts +1 -9
  38. package/src/extension/declaration-pinning.ts +164 -0
  39. package/src/extension/doctor.ts +7 -10
  40. package/src/extension/fanout-child.ts +7 -8
  41. package/src/extension/index.ts +143 -134
  42. package/src/extension/reply-workflow-script.ts +20 -11
  43. package/src/extension/rpc.ts +11 -6
  44. package/src/extension/schemas.ts +34 -30
  45. package/src/extension/subagent-guide.ts +86 -6
  46. package/src/extension/subagent-options.ts +47 -0
  47. package/src/extension/tool-activation.ts +3 -2
  48. package/src/extension/tool-description.ts +51 -68
  49. package/src/inspectors/actions.ts +37 -11
  50. package/src/inspectors/plugins.ts +3 -2
  51. package/src/inspectors/tmux/actions.ts +204 -0
  52. package/src/inspectors/tmux/client.ts +85 -0
  53. package/src/inspectors/tmux/plugin.ts +21 -0
  54. package/src/integrations/herdr-status.ts +18 -49
  55. package/src/integrations/program-status.ts +215 -0
  56. package/src/intercom/fork-supervisor-routing.ts +533 -0
  57. package/src/intercom/native-supervisor-channel.ts +152 -13
  58. package/src/intercom/result-intercom.ts +3 -2
  59. package/src/intercom/supervisor-ui.ts +2 -174
  60. package/src/missions/store.ts +25 -5
  61. package/src/profiles/profiles.ts +24 -21
  62. package/src/runs/background/active-async-capacity.ts +58 -8
  63. package/src/runs/background/async-execution.ts +143 -38
  64. package/src/runs/background/async-job-tracker.ts +11 -4
  65. package/src/runs/background/async-resume.ts +5 -2
  66. package/src/runs/background/await-async-run.ts +14 -9
  67. package/src/runs/background/binary-bootstrap.ts +2 -1
  68. package/src/runs/background/calendar-schedule.ts +90 -0
  69. package/src/runs/background/chain-root-attachment.ts +9 -5
  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 +16 -2
  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-child-launch.ts +1 -0
  79. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  80. package/src/runs/background/scheduled-runs.ts +256 -61
  81. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  82. package/src/runs/background/subagent-runner.ts +32 -12
  83. package/src/runs/background/subagent-wait.ts +38 -19
  84. package/src/runs/background/terminal-run-index.ts +46 -1
  85. package/src/runs/background/wait-completions.ts +1 -0
  86. package/src/runs/background/wait-tool.ts +33 -23
  87. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  88. package/src/runs/foreground/async-stop-action.ts +48 -22
  89. package/src/runs/foreground/execution.ts +94 -52
  90. package/src/runs/foreground/foreground-history.ts +1 -0
  91. package/src/runs/foreground/subagent-executor.ts +232 -77
  92. package/src/runs/shared/child-commands.ts +2 -1
  93. package/src/runs/shared/child-hooks.ts +4 -3
  94. package/src/runs/shared/child-launch.ts +3 -0
  95. package/src/runs/shared/child-session.ts +41 -24
  96. package/src/runs/shared/child-tool-plan.ts +13 -26
  97. package/src/runs/shared/dynamic-fanout.ts +1 -1
  98. package/src/runs/shared/fork-command-result.ts +10 -0
  99. package/src/runs/shared/herdr-placed-run.ts +5 -4
  100. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
  101. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  102. package/src/runs/shared/model-resolution.ts +30 -1
  103. package/src/runs/shared/nested-events.ts +5 -0
  104. package/src/runs/shared/parallel-handoff.ts +56 -8
  105. package/src/runs/shared/parallel-utils.ts +2 -0
  106. package/src/runs/shared/partial-output.ts +48 -0
  107. package/src/runs/shared/runner-launcher.ts +25 -0
  108. package/src/runs/shared/single-output.ts +53 -0
  109. package/src/runs/shared/structured-output.ts +14 -7
  110. package/src/runs/shared/subagent-control.ts +3 -3
  111. package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
  112. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  113. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  114. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  115. package/src/runs/shared/worktree-lock.ts +29 -0
  116. package/src/runs/shared/worktree.ts +12 -1
  117. package/src/shared/atomic-json.ts +4 -2
  118. package/src/shared/edit-distance.ts +33 -0
  119. package/src/shared/file-lease.ts +74 -0
  120. package/src/shared/formatters.ts +1 -5
  121. package/src/shared/model-info.ts +22 -0
  122. package/src/shared/package-version.ts +17 -0
  123. package/src/shared/parent-wake.ts +79 -0
  124. package/src/shared/pruned-fork.ts +7 -1
  125. package/src/shared/runtime-module-path.ts +19 -0
  126. package/src/shared/settings-file-lease.ts +36 -0
  127. package/src/shared/types.ts +36 -2
  128. package/src/shared/utils.ts +8 -6
  129. package/src/slash/prompt-template-bridge.ts +21 -20
  130. package/src/slash/slash-commands.ts +3 -3
  131. package/src/slash/subagents-admin.ts +2 -1
  132. package/src/tui/fleet-native-transcript.ts +2 -0
  133. package/src/tui/fleet-transcript.ts +12 -3
  134. package/src/tui/fleet.ts +11 -8
  135. package/src/tui/render.ts +27 -19
  136. package/src/tui/subagent-messages.ts +305 -0
  137. package/src/watchdog/diff-tool.ts +2 -2
  138. package/src/watchdog/register-main.ts +2 -22
  139. package/src/watchdog/render.ts +2 -24
  140. package/src/watchdog/runtime.ts +6 -4
  141. package/src/watchdog/settings.ts +18 -13
  142. package/src/watchdog/tool-actions.ts +2 -2
  143. package/src/workflows/scripted-workflow.ts +20 -6
  144. package/src/workflows/workflow-resources.ts +11 -0
@@ -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
+ }