@timmyjl12/pi-subagents 0.0.0-stage → 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 (244) hide show
  1. package/CHANGELOG.md +862 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1125 -3
  5. package/SECURITY.md +97 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/active-agents-prompt.d.ts +40 -0
  9. package/dist/active-agents-prompt.js +98 -0
  10. package/dist/advisor-status.d.ts +16 -0
  11. package/dist/advisor-status.js +74 -0
  12. package/dist/agent-color.d.ts +35 -0
  13. package/dist/agent-color.js +131 -0
  14. package/dist/agent-file-toggle.d.ts +125 -0
  15. package/dist/agent-file-toggle.js +264 -0
  16. package/dist/agent-manager.d.ts +872 -0
  17. package/dist/agent-manager.js +2910 -0
  18. package/dist/agent-runner.d.ts +358 -0
  19. package/dist/agent-runner.js +1219 -0
  20. package/dist/agent-types.d.ts +142 -0
  21. package/dist/agent-types.js +315 -0
  22. package/dist/awaited-result.d.ts +37 -0
  23. package/dist/awaited-result.js +150 -0
  24. package/dist/child-context.d.ts +15 -0
  25. package/dist/child-context.js +181 -0
  26. package/dist/child-session-shutdown.d.ts +21 -0
  27. package/dist/child-session-shutdown.js +97 -0
  28. package/dist/cleanup-plans.d.ts +10 -0
  29. package/dist/cleanup-plans.js +112 -0
  30. package/dist/context.d.ts +12 -0
  31. package/dist/context.js +56 -0
  32. package/dist/cross-extension-rpc.d.ts +73 -0
  33. package/dist/cross-extension-rpc.js +192 -0
  34. package/dist/custom-agents.d.ts +79 -0
  35. package/dist/custom-agents.js +583 -0
  36. package/dist/default-agents.d.ts +7 -0
  37. package/dist/default-agents.js +125 -0
  38. package/dist/enabled-models.d.ts +49 -0
  39. package/dist/enabled-models.js +145 -0
  40. package/dist/env.d.ts +6 -0
  41. package/dist/env.js +28 -0
  42. package/dist/error-log.d.ts +64 -0
  43. package/dist/error-log.js +176 -0
  44. package/dist/force-main-model.d.ts +21 -0
  45. package/dist/force-main-model.js +28 -0
  46. package/dist/goal-bridge.d.ts +155 -0
  47. package/dist/goal-bridge.js +305 -0
  48. package/dist/group-join.d.ts +36 -0
  49. package/dist/group-join.js +161 -0
  50. package/dist/index.d.ts +52 -0
  51. package/dist/index.js +6390 -0
  52. package/dist/invocation-config.d.ts +164 -0
  53. package/dist/invocation-config.js +158 -0
  54. package/dist/memory.d.ts +53 -0
  55. package/dist/memory.js +165 -0
  56. package/dist/mention-clone.d.ts +87 -0
  57. package/dist/mention-clone.js +178 -0
  58. package/dist/mention.d.ts +81 -0
  59. package/dist/mention.js +131 -0
  60. package/dist/model-resolver.d.ts +36 -0
  61. package/dist/model-resolver.js +95 -0
  62. package/dist/model-scope.d.ts +49 -0
  63. package/dist/model-scope.js +48 -0
  64. package/dist/nested-tools.d.ts +76 -0
  65. package/dist/nested-tools.js +393 -0
  66. package/dist/output-diagnostics.d.ts +11 -0
  67. package/dist/output-diagnostics.js +64 -0
  68. package/dist/output-file.d.ts +64 -0
  69. package/dist/output-file.js +351 -0
  70. package/dist/prompts.d.ts +61 -0
  71. package/dist/prompts.js +94 -0
  72. package/dist/recovery.d.ts +56 -0
  73. package/dist/recovery.js +341 -0
  74. package/dist/report-cleanup.d.ts +204 -0
  75. package/dist/report-cleanup.js +1632 -0
  76. package/dist/report-store.d.ts +738 -0
  77. package/dist/report-store.js +3612 -0
  78. package/dist/schedule-store.d.ts +52 -0
  79. package/dist/schedule-store.js +240 -0
  80. package/dist/schedule.d.ts +121 -0
  81. package/dist/schedule.js +420 -0
  82. package/dist/settings.d.ts +388 -0
  83. package/dist/settings.js +268 -0
  84. package/dist/skill-loader.d.ts +24 -0
  85. package/dist/skill-loader.js +93 -0
  86. package/dist/standalone-fallback.d.ts +30 -0
  87. package/dist/standalone-fallback.js +239 -0
  88. package/dist/status-note.d.ts +61 -0
  89. package/dist/status-note.js +85 -0
  90. package/dist/structured-output.d.ts +61 -0
  91. package/dist/structured-output.js +112 -0
  92. package/dist/terminal-progress.d.ts +115 -0
  93. package/dist/terminal-progress.js +206 -0
  94. package/dist/types.d.ts +411 -0
  95. package/dist/types.js +5 -0
  96. package/dist/ui/agent-mention.d.ts +82 -0
  97. package/dist/ui/agent-mention.js +187 -0
  98. package/dist/ui/agent-widget.d.ts +304 -0
  99. package/dist/ui/agent-widget.js +770 -0
  100. package/dist/ui/cleanup-preview.d.ts +59 -0
  101. package/dist/ui/cleanup-preview.js +466 -0
  102. package/dist/ui/conversation-viewer.d.ts +105 -0
  103. package/dist/ui/conversation-viewer.js +544 -0
  104. package/dist/ui/fleet-list.d.ts +183 -0
  105. package/dist/ui/fleet-list.js +494 -0
  106. package/dist/ui/fleet-overlay.d.ts +203 -0
  107. package/dist/ui/fleet-overlay.js +887 -0
  108. package/dist/ui/hub-feed.d.ts +52 -0
  109. package/dist/ui/hub-feed.js +148 -0
  110. package/dist/ui/native-transcript.d.ts +33 -0
  111. package/dist/ui/native-transcript.js +234 -0
  112. package/dist/ui/schedule-menu.d.ts +16 -0
  113. package/dist/ui/schedule-menu.js +94 -0
  114. package/dist/ui/select-item.d.ts +27 -0
  115. package/dist/ui/select-item.js +34 -0
  116. package/dist/ui/tool-progress.d.ts +22 -0
  117. package/dist/ui/tool-progress.js +56 -0
  118. package/dist/ui/viewer-keys.d.ts +20 -0
  119. package/dist/ui/viewer-keys.js +17 -0
  120. package/dist/ui/workflow-card.d.ts +175 -0
  121. package/dist/ui/workflow-card.js +332 -0
  122. package/dist/ui/workflow-dialog.d.ts +305 -0
  123. package/dist/ui/workflow-dialog.js +848 -0
  124. package/dist/ui/workflow-menu.d.ts +60 -0
  125. package/dist/ui/workflow-menu.js +147 -0
  126. package/dist/usage.d.ts +147 -0
  127. package/dist/usage.js +147 -0
  128. package/dist/workflow/collisions.d.ts +95 -0
  129. package/dist/workflow/collisions.js +88 -0
  130. package/dist/workflow/entry.d.ts +32 -0
  131. package/dist/workflow/entry.js +29 -0
  132. package/dist/workflow/host.d.ts +65 -0
  133. package/dist/workflow/host.js +477 -0
  134. package/dist/workflow/journal.d.ts +113 -0
  135. package/dist/workflow/journal.js +177 -0
  136. package/dist/workflow/json-schema.d.ts +51 -0
  137. package/dist/workflow/json-schema.js +111 -0
  138. package/dist/workflow/meta.d.ts +67 -0
  139. package/dist/workflow/meta.js +317 -0
  140. package/dist/workflow/progress.d.ts +224 -0
  141. package/dist/workflow/progress.js +361 -0
  142. package/dist/workflow/runtime.d.ts +373 -0
  143. package/dist/workflow/runtime.js +919 -0
  144. package/dist/workflow/saved.d.ts +90 -0
  145. package/dist/workflow/saved.js +203 -0
  146. package/dist/workflow/task.d.ts +145 -0
  147. package/dist/workflow/task.js +213 -0
  148. package/dist/workflow/tool-description.d.ts +43 -0
  149. package/dist/workflow/tool-description.js +204 -0
  150. package/dist/workflow/worker-source.d.ts +47 -0
  151. package/dist/workflow/worker-source.js +778 -0
  152. package/dist/worktree.d.ts +52 -0
  153. package/dist/worktree.js +164 -0
  154. package/dist/xml.d.ts +10 -0
  155. package/dist/xml.js +12 -0
  156. package/docs/DEVELOPMENT.md +40 -0
  157. package/docs/artifacts.md +93 -0
  158. package/docs/recovery.md +62 -0
  159. package/docs/rpc.md +252 -0
  160. package/docs/runtime-performance.md +53 -0
  161. package/docs/workflows.md +467 -0
  162. package/examples/agent-tool-description.md +43 -0
  163. package/examples/workflows/compose.js +51 -0
  164. package/examples/workflows/fan-out-audit.js +47 -0
  165. package/examples/workflows/gated-fix.js +60 -0
  166. package/examples/workflows/lib/count-child.js +27 -0
  167. package/examples/workflows/review-panel.js +66 -0
  168. package/examples/workflows/structured-findings.js +78 -0
  169. package/package.json +75 -6
  170. package/src/abortable.ts +43 -0
  171. package/src/active-agents-prompt.ts +115 -0
  172. package/src/advisor-status.ts +74 -0
  173. package/src/agent-color.ts +169 -0
  174. package/src/agent-file-toggle.ts +273 -0
  175. package/src/agent-manager.ts +3312 -0
  176. package/src/agent-runner.ts +1500 -0
  177. package/src/agent-types.ts +390 -0
  178. package/src/awaited-result.ts +187 -0
  179. package/src/child-context.ts +173 -0
  180. package/src/child-session-shutdown.ts +114 -0
  181. package/src/cleanup-plans.ts +112 -0
  182. package/src/context.ts +58 -0
  183. package/src/cross-extension-rpc.ts +257 -0
  184. package/src/custom-agents.ts +689 -0
  185. package/src/default-agents.ts +129 -0
  186. package/src/enabled-models.ts +180 -0
  187. package/src/env.ts +33 -0
  188. package/src/error-log.ts +202 -0
  189. package/src/force-main-model.ts +29 -0
  190. package/src/goal-bridge.ts +468 -0
  191. package/src/group-join.ts +188 -0
  192. package/src/index.ts +6856 -0
  193. package/src/invocation-config.ts +276 -0
  194. package/src/memory.ts +179 -0
  195. package/src/mention-clone.ts +221 -0
  196. package/src/mention.ts +141 -0
  197. package/src/model-resolver.ts +118 -0
  198. package/src/model-scope.ts +70 -0
  199. package/src/nested-tools.ts +553 -0
  200. package/src/output-diagnostics.ts +68 -0
  201. package/src/output-file.ts +380 -0
  202. package/src/prompts.ts +151 -0
  203. package/src/recovery.ts +320 -0
  204. package/src/report-cleanup.ts +2044 -0
  205. package/src/report-store.ts +4130 -0
  206. package/src/schedule-store.ts +244 -0
  207. package/src/schedule.ts +450 -0
  208. package/src/settings.ts +632 -0
  209. package/src/skill-loader.ts +102 -0
  210. package/src/standalone-fallback.ts +195 -0
  211. package/src/status-note.ts +90 -0
  212. package/src/structured-output.ts +130 -0
  213. package/src/terminal-progress.ts +215 -0
  214. package/src/types.ts +424 -0
  215. package/src/ui/agent-mention.ts +216 -0
  216. package/src/ui/agent-widget.ts +866 -0
  217. package/src/ui/cleanup-preview.ts +518 -0
  218. package/src/ui/conversation-viewer.ts +527 -0
  219. package/src/ui/fleet-list.ts +563 -0
  220. package/src/ui/fleet-overlay.ts +1048 -0
  221. package/src/ui/hub-feed.ts +179 -0
  222. package/src/ui/native-transcript.ts +224 -0
  223. package/src/ui/schedule-menu.ts +105 -0
  224. package/src/ui/select-item.ts +45 -0
  225. package/src/ui/tool-progress.ts +67 -0
  226. package/src/ui/viewer-keys.ts +39 -0
  227. package/src/ui/workflow-card.ts +470 -0
  228. package/src/ui/workflow-dialog.ts +1119 -0
  229. package/src/ui/workflow-menu.ts +193 -0
  230. package/src/usage.ts +217 -0
  231. package/src/workflow/collisions.ts +123 -0
  232. package/src/workflow/entry.ts +47 -0
  233. package/src/workflow/host.ts +524 -0
  234. package/src/workflow/journal.ts +221 -0
  235. package/src/workflow/json-schema.ts +128 -0
  236. package/src/workflow/meta.ts +325 -0
  237. package/src/workflow/progress.ts +550 -0
  238. package/src/workflow/runtime.ts +1342 -0
  239. package/src/workflow/saved.ts +217 -0
  240. package/src/workflow/task.ts +313 -0
  241. package/src/workflow/tool-description.ts +205 -0
  242. package/src/workflow/worker-source.ts +781 -0
  243. package/src/worktree.ts +205 -0
  244. package/src/xml.ts +13 -0
@@ -0,0 +1,866 @@
1
+ /**
2
+ * agent-widget.ts — Compact running/completed agent list above or below the editor.
3
+ *
4
+ * Displays a tree of agents with animated spinners, live stats, and activity descriptions.
5
+ * Uses the callback form of setWidget for themed rendering.
6
+ */
7
+
8
+ import { Editor, isKeyRelease, isKeyRepeat, matchesKey, truncateToWidth } from "@earendil-works/pi-tui";
9
+ import { type AdvisorStatus, formatAdvisorStatus } from "../advisor-status.ts";
10
+ import { renderAgentName } from "../agent-color.ts";
11
+ import { type AgentManager, isTopLevelAgent } from "../agent-manager.ts";
12
+ import { getConfig } from "../agent-types.ts";
13
+ import type { AgentInvocation, SubagentType, WidgetMode, WidgetPlacement } from "../types.ts";
14
+ import { getLifetimeCost, getLifetimeTotal, getSessionContextPercent, type LifetimeUsage, type SessionLike } from "../usage.ts";
15
+
16
+ // ---- Constants ----
17
+
18
+ /** Maximum number of rendered lines before overflow collapse kicks in. */
19
+ const MAX_WIDGET_LINES = 12;
20
+ /** Header, activity and advisor status form one indivisible running card. */
21
+ const RUNNING_CARD_LINES = 3;
22
+
23
+ /** Braille spinner frames for animated running indicator. */
24
+ export const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
25
+
26
+ /** Statuses that indicate an error/non-success outcome (used for linger behavior and icon rendering). */
27
+ export const ERROR_STATUSES = new Set(["error", "aborted", "steered", "stopped"]);
28
+
29
+ /** Tool name → human-readable action for activity descriptions. */
30
+ const TOOL_DISPLAY: Record<string, string> = {
31
+ read: "reading",
32
+ bash: "running command",
33
+ edit: "editing",
34
+ write: "writing",
35
+ grep: "searching",
36
+ find: "finding files",
37
+ ls: "listing",
38
+ };
39
+
40
+ // ---- Types ----
41
+
42
+ export type Theme = {
43
+ fg(color: string, text: string): string;
44
+ bold(text: string): string;
45
+ };
46
+
47
+ type WidgetTUI = {
48
+ terminal: { columns: number };
49
+ requestRender(): void;
50
+ getFocusedComponent?(): unknown;
51
+ focusedComponent?: unknown;
52
+ };
53
+
54
+ export type UICtx = {
55
+ setStatus(key: string, text: string | undefined): void;
56
+ setWidget(
57
+ key: string,
58
+ content: undefined | ((tui: WidgetTUI, theme: Theme) => { render(width?: number): string[]; invalidate(): void }),
59
+ options?: { placement?: "aboveEditor" | "belowEditor" },
60
+ ): void;
61
+ onTerminalInput?(handler: (data: string) => { consume?: boolean } | undefined): () => void;
62
+ getEditorText?(): string;
63
+ };
64
+
65
+ /** The host's side of the ← → Agent Hub shortcut; every field is read live. */
66
+ export interface AgentHubWiring {
67
+ /** Open the Hub overlay. */
68
+ open(): void;
69
+ /**
70
+ * Whether the Hub would have rows: the Hub's content, not the compact list's
71
+ * visibility — a foreground-only roster (filtered out by `widgetMode`) or
72
+ * settled history past the linger must still open. Defaults to the
73
+ * unfiltered top-level roster.
74
+ */
75
+ hasContent?(): boolean;
76
+ /** True while the Hub overlay is open; ← then belongs to it, not this handler. */
77
+ isOpen?(): boolean;
78
+ }
79
+
80
+ /** Per-agent live activity state. */
81
+ export interface AgentActivity {
82
+ activeTools: Map<string, string>;
83
+ toolUses: number;
84
+ responseText: string;
85
+ session?: SessionLike;
86
+ /** Current turn count. */
87
+ turnCount: number;
88
+ /** Effective max turns for this agent (undefined = unlimited). */
89
+ maxTurns?: number;
90
+ }
91
+
92
+ /** Metadata attached to Agent tool results for custom rendering. */
93
+ export interface AgentDetails {
94
+ displayName: string;
95
+ description: string;
96
+ subagentType: string;
97
+ toolUses: number;
98
+ tokens: string;
99
+ durationMs: number;
100
+ status: "queued" | "running" | "completed" | "steered" | "aborted" | "stopped" | "error" | "background";
101
+ /** Human-readable description of what the agent is currently doing. */
102
+ activity?: string;
103
+ /** Current spinner frame index (for animated running indicator). */
104
+ spinnerFrame?: number;
105
+ /** Short label for the model the run used, e.g. "haiku 4.5". */
106
+ modelName?: string;
107
+ /** Notable config tags (e.g. ["thinking: high", "isolated"]). */
108
+ tags?: string[];
109
+ /** Current turn count. */
110
+ turnCount?: number;
111
+ /** Effective max turns (undefined = unlimited). */
112
+ maxTurns?: number;
113
+ /** Estimated cost in USD; 0 when the model has no pricing data. */
114
+ cost?: number;
115
+ agentId?: string;
116
+ advisorStatus?: AdvisorStatus;
117
+ error?: string;
118
+ }
119
+
120
+ // ---- Formatting helpers ----
121
+
122
+ /** Apply foreground styling while restoring it after nested foreground/full ANSI resets. */
123
+ export function fgPreservingNestedStyles(theme: Theme, color: string, text: string): string {
124
+ const styledEmpty = theme.fg(color, "");
125
+ const styleStart = styledEmpty.replace(/\u001b\[(?:0|39)m/g, "");
126
+ return theme.fg(color, text.replace(/\u001b\[(?:0|39)m/g, reset => `${reset}${styleStart}`));
127
+ }
128
+
129
+ /** Format a token count compactly: "33.8k token", "1.2M token". */
130
+ export function formatTokens(count: number): string {
131
+ if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M token`;
132
+ if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k token`;
133
+ return `${count} token`;
134
+ }
135
+
136
+ /**
137
+ * Format a cost as `~$0.0042`, or "" when there is nothing to show.
138
+ *
139
+ * The tilde is load-bearing: this is pi's own estimate from the model's listed
140
+ * rates, not a billed figure, and the surfaces that print it sit next to token
141
+ * counts that ARE exact.
142
+ *
143
+ * Nothing is printed for zero, which is also what a model with no pricing data
144
+ * reports: `$0.00` beside a local model's tokens would claim its cost was
145
+ * measured and found to be nothing, rather than never measured at all. For the
146
+ * same reason a real cost too small for four decimals reads `<$0.0001` — it was
147
+ * measured, and rounding it to `~$0.0000` would say the opposite.
148
+ */
149
+ export function formatCost(cost: number): string {
150
+ if (!(cost > 0)) return ""; // also catches NaN
151
+ if (cost < 0.0001) return "<$0.0001";
152
+ if (cost >= 1) return `~$${cost.toFixed(2)}`;
153
+ // Under a dollar: cents at minimum, four decimals at most, nothing trailing.
154
+ // Most single runs land between a tenth of a cent and a dime, where rounding
155
+ // to cents would collapse a 4x difference in spend into the same figure.
156
+ const rounded = Number(cost.toFixed(4));
157
+ const decimals = (String(rounded).split(".")[1] ?? "").length;
158
+ return `~$${rounded.toFixed(Math.max(2, decimals))}`;
159
+ }
160
+
161
+ /**
162
+ * Token count with optional context-fill % and compaction-count annotations.
163
+ * Thresholds for percent: <70% dim, 70–85% warning, ≥85% error.
164
+ * Compaction count rendered as `⇊N` in dim.
165
+ *
166
+ * "12.3k token" — no annotations
167
+ * "12.3k token (45%)" — percent only
168
+ * "12.3k token (⇊2)" — compactions only (e.g. right after compact)
169
+ * "12.3k token (45% · ⇊2)" — both
170
+ */
171
+ export function formatSessionTokens(
172
+ tokens: number,
173
+ percent: number | null,
174
+ theme: Theme,
175
+ compactions = 0,
176
+ ): string {
177
+ const tokenStr = formatTokens(tokens);
178
+ const annot: string[] = [];
179
+ if (percent !== null) {
180
+ const color = percent >= 85 ? "error" : percent >= 70 ? "warning" : "dim";
181
+ annot.push(theme.fg(color, `${Math.round(percent)}%`));
182
+ }
183
+ if (compactions > 0) {
184
+ annot.push(theme.fg("dim", `⇊${compactions}`));
185
+ }
186
+ if (annot.length === 0) return tokenStr;
187
+ return `${tokenStr} (${annot.join(" · ")})`;
188
+ }
189
+
190
+ /** Format turn count with optional max limit: "↻5≤30" or "↻5". */
191
+ export function formatTurns(turnCount: number, maxTurns?: number | null): string {
192
+ return maxTurns != null ? `↻${turnCount}≤${maxTurns}` : `↻${turnCount}`;
193
+ }
194
+
195
+ /** Format milliseconds as human-readable duration. */
196
+ export function formatMs(ms: number): string {
197
+ return `${(ms / 1000).toFixed(1)}s`;
198
+ }
199
+
200
+ /** Format duration from start/completed timestamps. */
201
+ export function formatDuration(startedAt: number, completedAt?: number): string {
202
+ if (completedAt) return formatMs(completedAt - startedAt);
203
+ return `${formatMs(Date.now() - startedAt)} (running)`;
204
+ }
205
+
206
+ /** Get display name for any agent type (built-in or custom). */
207
+ export function getDisplayName(type: SubagentType): string {
208
+ return getConfig(type).displayName;
209
+ }
210
+
211
+ /** Short label for prompt mode: "twin" for append, nothing for replace (the default). */
212
+ export function getPromptModeLabel(type: SubagentType): string | undefined {
213
+ const config = getConfig(type);
214
+ return config.promptMode === "append" ? "twin" : undefined;
215
+ }
216
+
217
+ /**
218
+ * Mode label is not included — callers add it where they want it.
219
+ *
220
+ * Both model forms come back so each surface can pick by width; the
221
+ * "(asked X)" annotation is applied here rather than by callers, so a value the
222
+ * spawn did not honor cannot be rendered as though it had been (#182).
223
+ */
224
+ export function buildInvocationTags(
225
+ invocation: AgentInvocation | undefined,
226
+ ): { modelName?: string; modelId?: string; tags: string[] } {
227
+ const tags: string[] = [];
228
+ if (!invocation) return { tags };
229
+ const asked = (value: string | undefined, requested: string | undefined): string | undefined =>
230
+ value && requested && requested !== value ? `${value} (asked ${requested})` : value;
231
+ const thinking = asked(invocation.thinking, invocation.requestedThinking);
232
+ if (thinking) tags.push(`thinking: ${thinking}`);
233
+ if (invocation.isolated) tags.push("isolated");
234
+ if (invocation.isolation === "worktree") tags.push("worktree");
235
+ if (invocation.inheritContext) tags.push("inherit context");
236
+ if (invocation.runInBackground) tags.push("background");
237
+ if (invocation.maxTurns != null) tags.push(`max turns: ${invocation.maxTurns}`);
238
+ return {
239
+ modelName: asked(invocation.modelName, invocation.requestedModel),
240
+ modelId: asked(invocation.modelId, invocation.requestedModel),
241
+ tags,
242
+ };
243
+ }
244
+
245
+ /**
246
+ * Make externally supplied text safe to place in ONE terminal row.
247
+ *
248
+ * Every entry an extension returns from `render()` is ONE terminal row: pi's
249
+ * TUI pushes each array element verbatim (`tui.js` `lines.push(line)`) and
250
+ * measures the block's height as `childLines.length`. A literal `\n` — or `\t`,
251
+ * or any other control byte — inside an entry makes the terminal advance a row
252
+ * the renderer never counted, permanently desynchronising its line diff. The
253
+ * visible symptom is a frozen duplicate row left on screen above and rows
254
+ * clipped below (the footer/statusline among them). Truncation cannot rescue
255
+ * it either: pi-tui's `visibleWidth` counts control characters as zero-width,
256
+ * so such a line passes the width check and still wraps in the terminal.
257
+ *
258
+ * Agent descriptions and error messages are the realistic carriers — both are
259
+ * free text (a model-supplied tool argument; a raw `Error.message`, which is
260
+ * frequently multi-line). ANSI styling is applied AFTER this runs, so stripping
261
+ * ESC here doubles as a terminal-injection guard for the plain fragments.
262
+ *
263
+ * Internal whitespace is preserved; see {@link sanitizeRowText} to collapse it.
264
+ */
265
+ export function flattenRow(text: string): string {
266
+ return text
267
+ // Whole escape sequences go, not just the ESC byte: a stripped-but-not-
268
+ // consumed CSI would leave its `[31m` payload as visible garbage.
269
+ .replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g, " ") // OSC (hyperlinks, titles)
270
+ .replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, " ") // CSI (cursor, erase, SGR)
271
+ .replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ");
272
+ }
273
+
274
+ /**
275
+ * {@link flattenRow} plus whitespace collapsing, for short single-line labels
276
+ * (descriptions, names, error heads) where runs of spaces carry nothing.
277
+ * Use {@link flattenRow} instead where indentation is meaningful.
278
+ */
279
+ export function sanitizeRowText(text: string): string {
280
+ return flattenRow(text).replace(/\s+/g, " ").trim();
281
+ }
282
+
283
+ /** Truncate text to a single line, max `len` chars. */
284
+ function truncateLine(text: string, len = 60): string {
285
+ const line = sanitizeRowText(text.split("\n").find(l => l.trim()) ?? "");
286
+ if (line.length <= len) return line;
287
+ return line.slice(0, len) + "…";
288
+ }
289
+
290
+ /** Build a human-readable activity string from currently-running tools or response text. */
291
+ export function describeActivity(activeTools: Map<string, string>, responseText?: string): string {
292
+ if (activeTools.size > 0) {
293
+ const groups = new Map<string, number>();
294
+ for (const toolName of activeTools.values()) {
295
+ const action = TOOL_DISPLAY[toolName] ?? toolName;
296
+ groups.set(action, (groups.get(action) ?? 0) + 1);
297
+ }
298
+
299
+ const parts: string[] = [];
300
+ for (const [action, count] of groups) {
301
+ if (count > 1) {
302
+ parts.push(`${action} ${count} ${action === "searching" ? "patterns" : "files"}`);
303
+ } else {
304
+ parts.push(action);
305
+ }
306
+ }
307
+ return parts.join(", ") + "…";
308
+ }
309
+
310
+ // No tools active — show truncated response text if available
311
+ if (responseText && responseText.trim().length > 0) {
312
+ return truncateLine(responseText);
313
+ }
314
+
315
+ return "thinking…";
316
+ }
317
+
318
+ // ---- Widget manager ----
319
+
320
+ export class AgentWidget {
321
+ private uiCtx: UICtx | undefined;
322
+ private widgetFrame = 0;
323
+ private widgetInterval: ReturnType<typeof setInterval> | undefined;
324
+ /** One-shot timer that re-runs update() when the earliest finished row expires. */
325
+ private expiryTimer: ReturnType<typeof setTimeout> | undefined;
326
+ /** Wall-clock time each finished agent was first seen finished. */
327
+ private finishedAt = new Map<string, number>();
328
+ /** How long a completed row lingers without any turn activity. */
329
+ static readonly FINISHED_LINGER_MS = 5000;
330
+ /** Errors/aborts linger longer so they are not missed. */
331
+ static readonly ERROR_LINGER_MS = 10000;
332
+ /** Tracks how many turns each finished agent has survived. Key: agent ID, Value: turns since finished. */
333
+ private finishedTurnAge = new Map<string, number>();
334
+ /** How many extra turns errors/aborted agents linger (completed agents clear after 1 turn). */
335
+ private static readonly ERROR_LINGER_TURNS = 2;
336
+
337
+ /** Whether the widget callback is currently registered with the TUI. */
338
+ private widgetRegistered = false;
339
+ private registeredPlacement: WidgetPlacement | undefined;
340
+ private inputUnsub: (() => void) | undefined;
341
+ private hub: AgentHubWiring | undefined;
342
+ /** Cached TUI reference from widget factory callback, used for repaint and focus checks. */
343
+ private tui: WidgetTUI | undefined;
344
+ /** Last status bar text, used to avoid redundant setStatus calls. */
345
+ private lastStatusText: string | undefined;
346
+
347
+ constructor(
348
+ private manager: AgentManager,
349
+ private agentActivity: Map<string, AgentActivity>,
350
+ /**
351
+ * Read live at render time. Selects which agents the widget shows — see
352
+ * `WidgetMode`. Defaults to `"all"`, matching the extension's own default.
353
+ */
354
+ private mode: () => WidgetMode = () => "all",
355
+ /**
356
+ * Read live at render time, like `mode`. Whether running agents show an
357
+ * estimated cost beside their token count. Defaults to off — the extension
358
+ * supplies the user's `showCost` setting.
359
+ */
360
+ private showCost: () => boolean = () => false,
361
+ /**
362
+ * Read live at render time, like `mode`. Whether running agents name the
363
+ * model driving them and the thinking level it is running at. Defaults to
364
+ * off — the extension supplies the user's `showModel` setting — because the
365
+ * row is already dense and the same pair is on the tool result and in the
366
+ * conversation viewer unconditionally.
367
+ */
368
+ private showModel: () => boolean = () => false,
369
+ /** Read live; changing placement remounts the same widget key once. */
370
+ private placement: () => WidgetPlacement = () => "above",
371
+ ) {}
372
+
373
+ /** Reuse the extension's canonical Agent Hub, without an inline navigation mode. */
374
+ setHubOpener(hub: AgentHubWiring): void {
375
+ this.hub = hub;
376
+ }
377
+
378
+ /**
379
+ * Agents eligible for the widget, per the current `WidgetMode`:
380
+ * - `off`: none (the widget's existing empty-state path hides it entirely).
381
+ * - `background`: drop only agents *known* to be foreground
382
+ * (`isBackground === false`); keep everything else — background, queued,
383
+ * scheduled, or RPC-spawned (`undefined`). Keying off the `isBackground`
384
+ * record flag rather than the UI-only `invocation` snapshot (which only the
385
+ * Agent-tool path sets), and excluding rather than allow-listing, means
386
+ * only proven-foreground runs drop out — nothing else silently vanishes.
387
+ * - `all`: every agent.
388
+ */
389
+ private widgetAgents() {
390
+ const all = this.manager.listAgents().filter(isTopLevelAgent);
391
+ switch (this.mode()) {
392
+ case "off": return [];
393
+ case "background": return all.filter(a => a.isBackground !== false);
394
+ default: return all;
395
+ }
396
+ }
397
+
398
+ /** Set the UI context (grabbed from first tool execution). */
399
+ setUICtx(ctx: UICtx) {
400
+ if (ctx !== this.uiCtx) {
401
+ // UICtx changed — force re-registration and detach the old input listener.
402
+ this.inputUnsub?.();
403
+ this.uiCtx = ctx;
404
+ this.widgetRegistered = false;
405
+ this.registeredPlacement = undefined;
406
+ this.tui = undefined;
407
+ this.lastStatusText = undefined;
408
+ this.inputUnsub = ctx.onTerminalInput?.(data => {
409
+ if (ctx !== this.uiCtx || !this.hub) return undefined;
410
+ if (isKeyRelease(data) || isKeyRepeat(data) || !matchesKey(data, "left") || ctx.getEditorText?.() !== "") return undefined;
411
+ // The Hub owns every key while it holds the keyboard — re-entering it
412
+ // here would stack a second overlay and swallow the first one's input.
413
+ if (this.hub.isOpen?.()) return undefined;
414
+ // "off" retires the key with the list, like the retired fleetView: false.
415
+ if (this.mode() === "off") return undefined;
416
+ // Focus distinguishes the real prompt from a detached empty editor
417
+ // underneath a dialog — but only with a TUI to read it from. The list
418
+ // may never have mounted (a foreground-only roster under "background"),
419
+ // so the reference is acquired on demand rather than awaited.
420
+ if (this.tui === undefined) this.probeTui();
421
+ if (this.tui === undefined) return undefined;
422
+ const focused = this.tui.getFocusedComponent?.() ?? this.tui.focusedComponent;
423
+ if (focused != null && !(focused instanceof Editor)) return undefined;
424
+ const hasContent = this.hub.hasContent?.() ?? this.manager.listAgents().some(isTopLevelAgent);
425
+ if (!hasContent) return undefined;
426
+ this.hub.open();
427
+ return { consume: true };
428
+ });
429
+ }
430
+ }
431
+
432
+ /**
433
+ * Called on each new turn (tool_execution_start).
434
+ * Ages finished agents and clears those that have lingered long enough.
435
+ */
436
+ onTurnStart() {
437
+ // Age all finished agents
438
+ for (const [id, age] of this.finishedTurnAge) {
439
+ this.finishedTurnAge.set(id, age + 1);
440
+ }
441
+ // Trigger a widget refresh (will filter out expired agents)
442
+ this.update();
443
+ }
444
+
445
+ /** Ensure the widget update timer is running. */
446
+ ensureTimer() {
447
+ if (!this.widgetInterval) {
448
+ // The spinner only animates while something is running/queued; update()
449
+ // stops this interval as soon as nothing active remains.
450
+ this.widgetInterval = setInterval(() => this.update(), 80);
451
+ this.widgetInterval.unref?.();
452
+ }
453
+ }
454
+
455
+ /** Check if a finished agent should still be shown in the widget. */
456
+ private shouldShowFinished(agentId: string, status: string): boolean {
457
+ const age = this.finishedTurnAge.get(agentId) ?? 0;
458
+ const maxAge = ERROR_STATUSES.has(status) ? AgentWidget.ERROR_LINGER_TURNS : 1;
459
+ if (age >= maxAge) return false;
460
+ return Date.now() < this.finishedExpiry(agentId, status);
461
+ }
462
+
463
+ /** Wall-clock expiry of a finished row (seeds the finish time on first sight). */
464
+ private finishedExpiry(agentId: string, status: string): number {
465
+ let at = this.finishedAt.get(agentId);
466
+ if (at === undefined) {
467
+ at = Date.now();
468
+ this.finishedAt.set(agentId, at);
469
+ }
470
+ return at + (ERROR_STATUSES.has(status) ? AgentWidget.ERROR_LINGER_MS : AgentWidget.FINISHED_LINGER_MS);
471
+ }
472
+
473
+ /** Record an agent as finished (call when agent completes). */
474
+ markFinished(agentId: string) {
475
+ if (!this.finishedTurnAge.has(agentId)) {
476
+ this.finishedTurnAge.set(agentId, 0);
477
+ }
478
+ if (!this.finishedAt.has(agentId)) this.finishedAt.set(agentId, Date.now());
479
+ }
480
+
481
+ private stopInterval() {
482
+ if (this.widgetInterval) {
483
+ clearInterval(this.widgetInterval);
484
+ this.widgetInterval = undefined;
485
+ }
486
+ }
487
+
488
+ private clearExpiryTimer() {
489
+ if (this.expiryTimer) {
490
+ clearTimeout(this.expiryTimer);
491
+ this.expiryTimer = undefined;
492
+ }
493
+ }
494
+
495
+ /** Schedule one unref'd update() at the given wall-clock time. */
496
+ private scheduleExpiry(at: number) {
497
+ this.clearExpiryTimer();
498
+ this.expiryTimer = setTimeout(() => {
499
+ this.expiryTimer = undefined;
500
+ this.update();
501
+ }, Math.max(0, at - Date.now()) + 20);
502
+ this.expiryTimer.unref?.();
503
+ }
504
+
505
+ /** True while the widget holds a repaint timer (interval or expiry). */
506
+ hasPendingTimers(): boolean {
507
+ return this.widgetInterval !== undefined || this.expiryTimer !== undefined;
508
+ }
509
+
510
+ /**
511
+ * Drop an agent's finished-age (call when a settled agent starts running
512
+ * again, i.e. a background resume). markFinished only seeds an age it has not
513
+ * seen before, so a resumed agent would otherwise keep the age from its
514
+ * previous run — already past the linger limit, hiding the new run's
515
+ * completion line entirely.
516
+ */
517
+ markRunning(agentId: string) {
518
+ this.finishedTurnAge.delete(agentId);
519
+ this.finishedAt.delete(agentId);
520
+ }
521
+
522
+ /** Render a finished agent line. */
523
+ private renderFinishedLine(a: { id: string; type: SubagentType; status: string; description: string; toolUses: number; startedAt: number; completedAt?: number; error?: string; lifetimeUsage?: LifetimeUsage }, theme: Theme): string {
524
+ const modeLabel = getPromptModeLabel(a.type);
525
+ const duration = formatMs((a.completedAt ?? Date.now()) - a.startedAt);
526
+
527
+ let icon: string;
528
+ let statusText: string;
529
+ if (a.status === "completed") {
530
+ icon = theme.fg("success", "✓");
531
+ statusText = "";
532
+ } else if (a.status === "steered") {
533
+ icon = theme.fg("warning", "✓");
534
+ statusText = theme.fg("warning", " (turn limit)");
535
+ } else if (a.status === "stopped") {
536
+ icon = theme.fg("dim", "■");
537
+ statusText = theme.fg("dim", " stopped");
538
+ } else if (a.status === "error") {
539
+ icon = theme.fg("error", "✗");
540
+ // Error messages are routinely multi-line; they must be flattened before
541
+ // the slice, or a truncated tail keeps the newline that breaks the row.
542
+ const errMsg = a.error ? `: ${sanitizeRowText(a.error).slice(0, 60)}` : "";
543
+ statusText = theme.fg("error", ` error${errMsg}`);
544
+ } else {
545
+ // aborted
546
+ icon = theme.fg("error", "✗");
547
+ statusText = theme.fg("warning", " aborted");
548
+ }
549
+
550
+ const parts: string[] = [];
551
+ const activity = this.agentActivity.get(a.id);
552
+ if (activity) parts.push(formatTurns(activity.turnCount, activity.maxTurns));
553
+ if (a.toolUses > 0) parts.push(`${a.toolUses} tool use${a.toolUses === 1 ? "" : "s"}`);
554
+ // From the record, not the activity tracker: that entry is deleted the
555
+ // moment an agent finishes, and "what did it cost" is a question asked
556
+ // about finished agents.
557
+ const costText = this.showCost() ? formatCost(getLifetimeCost(a.lifetimeUsage)) : "";
558
+ if (costText) parts.push(costText);
559
+ parts.push(duration);
560
+
561
+ const modeTag = modeLabel ? ` ${theme.fg("dim", `(${modeLabel})`)}` : "";
562
+ return `${icon} ${renderAgentName(a.type, theme, { fallbackColor: "dim" })}${modeTag} ${theme.fg("dim", sanitizeRowText(a.description))} ${theme.fg("dim", "·")} ${theme.fg("dim", parts.join(" · "))}${statusText}`;
563
+ }
564
+
565
+ /**
566
+ * Render the widget content. Called from the registered widget's render() callback,
567
+ * reading live state each time instead of capturing it in a closure.
568
+ */
569
+ private renderWidget(tui: WidgetTUI, theme: Theme, width?: number): string[] {
570
+ const allAgents = this.widgetAgents();
571
+ const running = allAgents.filter(a => a.status === "running");
572
+ const queued = allAgents.filter(a => a.status === "queued");
573
+ const finished = allAgents.filter(a =>
574
+ a.status !== "running" && a.status !== "queued" && a.completedAt
575
+ && this.shouldShowFinished(a.id, a.status),
576
+ );
577
+
578
+ const hasActive = running.length > 0 || queued.length > 0;
579
+ const hasFinished = finished.length > 0;
580
+
581
+ // Nothing to show — return empty (widget will be unregistered by update())
582
+ if (!hasActive && !hasFinished) return [];
583
+
584
+ // Render to the width the HOST allocated, not the terminal's: the dock can
585
+ // be narrower than `terminal.columns`, and a line wider than its slot wraps
586
+ // in the terminal while the renderer still counts one row — the same
587
+ // desync an embedded newline causes. Older hosts call render() with no
588
+ // argument; fall back to the terminal width for them.
589
+ const w = typeof width === "number" && Number.isFinite(width) && width >= 0 ? width : tui.terminal.columns;
590
+ const truncate = (line: string) => truncateToWidth(line, w);
591
+ const headingColor = hasActive ? "accent" : "dim";
592
+ const headingIcon = hasActive ? "●" : "○";
593
+ const frame = SPINNER[this.widgetFrame % SPINNER.length];
594
+
595
+ // Apply the existing overflow priority before formatting. Hidden cards must
596
+ // not project session history or format text just to be discarded below.
597
+ const maxBody = MAX_WIDGET_LINES - 1;
598
+ const queueRows = queued.length > 0 ? 1 : 0;
599
+ const totalBody = finished.length + running.length * RUNNING_CARD_LINES + queueRows;
600
+ const overflow = totalBody > maxBody;
601
+ const cardBudget = overflow ? maxBody - 1 - queueRows : maxBody;
602
+ const runningLimit = overflow ? Math.min(running.length, Math.floor(cardBudget / RUNNING_CARD_LINES)) : running.length;
603
+ const finishedLimit = overflow ? Math.max(0, cardBudget - runningLimit * RUNNING_CARD_LINES) : finished.length;
604
+
605
+ const finishedLines: string[] = [];
606
+ for (const a of finished.slice(0, finishedLimit)) {
607
+ finishedLines.push(truncate(theme.fg("dim", "├─") + " " + this.renderFinishedLine(a, theme)));
608
+ }
609
+
610
+ const runningLines: string[][] = []; // each entry is [header, activity, advisor]
611
+ for (const a of running.slice(0, runningLimit)) {
612
+ const modeLabel = getPromptModeLabel(a.type);
613
+ const modeTag = modeLabel ? ` ${theme.fg("dim", `(${modeLabel})`)}` : "";
614
+ const elapsed = formatMs(Date.now() - a.startedAt);
615
+
616
+ const bg = this.agentActivity.get(a.id);
617
+ const toolUses = bg?.toolUses ?? a.toolUses;
618
+ // Spend comes from the record, never from the activity tracker: the record
619
+ // is the one that survives the agent finishing, and the one nested-tools
620
+ // folds a hidden child's spend into. Reading the tracker while an agent
621
+ // runs and the record once it stops made the figure jump at completion.
622
+ const tokens = getLifetimeTotal(a.lifetimeUsage);
623
+ const contextPercent = getSessionContextPercent(bg?.session);
624
+ const tokenText = tokens > 0 ? formatSessionTokens(tokens, contextPercent, theme, a.compactionCount) : "";
625
+ const costText = this.showCost() ? formatCost(getLifetimeCost(a.lifetimeUsage)) : "";
626
+
627
+ const parts: string[] = [];
628
+ if (this.showModel()) {
629
+ // Leading, and paired: a thinking level means nothing without the model
630
+ // it applies to. The tag is taken from buildInvocationTags rather than
631
+ // rebuilt so the "(asked X)" annotation survives. Both are plain text
632
+ // that ends up inside a styled run, so they are flattened first — a
633
+ // control byte here would still break the row.
634
+ const { modelName, tags } = buildInvocationTags(a.invocation);
635
+ if (modelName) parts.push(sanitizeRowText(modelName));
636
+ const thinkingTag = tags.find(tag => tag.startsWith("thinking: "));
637
+ if (thinkingTag) parts.push(sanitizeRowText(thinkingTag));
638
+ }
639
+ if (bg) parts.push(formatTurns(bg.turnCount, bg.maxTurns));
640
+ if (toolUses > 0) parts.push(`${toolUses} tool use${toolUses === 1 ? "" : "s"}`);
641
+ if (tokenText) parts.push(tokenText);
642
+ if (costText) parts.push(costText);
643
+ parts.push(elapsed);
644
+ const statsText = parts.join(" · ");
645
+
646
+ const activity = sanitizeRowText(bg ? describeActivity(bg.activeTools, bg.responseText) : "thinking…");
647
+
648
+ runningLines.push([
649
+ truncate(theme.fg("dim", "├─") + ` ${theme.fg("accent", frame)} ${renderAgentName(a.type, theme, { bold: true })}${modeTag} ${theme.fg("muted", sanitizeRowText(a.description))} ${theme.fg("dim", "·")} ${fgPreservingNestedStyles(theme, "dim", statsText)}`),
650
+ truncate(theme.fg("dim", "│ ") + theme.fg("dim", ` ⎿ ${activity}`)),
651
+ truncate(theme.fg("dim", "│ ") + theme.fg("dim", ` ⎿ ${sanitizeRowText(formatAdvisorStatus(a.advisorStatus))}`)),
652
+ ]);
653
+ }
654
+
655
+ const queuedLine = queued.length > 0
656
+ ? truncate(theme.fg("dim", "├─") + ` ${theme.fg("muted", "◦")} ${theme.fg("dim", `${queued.length} queued`)}`)
657
+ : undefined;
658
+
659
+ const hubHint = this.hub ? theme.fg("dim", " · ← Agent Hub") : "";
660
+ const lines: string[] = [truncate(theme.fg(headingColor, headingIcon) + " " + theme.fg(headingColor, "Agents") + hubHint)];
661
+
662
+ if (totalBody <= maxBody) {
663
+ // Everything fits — add all lines and fix up connectors for the last item.
664
+ lines.push(...finishedLines);
665
+ for (const pair of runningLines) lines.push(...pair);
666
+ if (queuedLine) lines.push(queuedLine);
667
+
668
+ // Fix last connector: swap ├─ → └─ and │ → space for activity lines.
669
+ if (lines.length > 1) {
670
+ const last = lines.length - 1;
671
+ lines[last] = lines[last].replace("├─", "└─");
672
+ // If last item is a running agent activity line, fix indent of that line
673
+ // and fix the header line above it.
674
+ if (runningLines.length > 0 && !queuedLine) {
675
+ const lastRows = runningLines[runningLines.length - 1];
676
+ const header = lines.length - lastRows.length;
677
+ lines[header] = lines[header].replace("├─", "└─");
678
+ for (let row = header + 1; row < lines.length; row++) {
679
+ lines[row] = lines[row].replace("│ ", " ");
680
+ }
681
+ }
682
+ }
683
+ } else {
684
+ // Overflow — prioritize: running > queued > finished.
685
+ // Reserve 1 line for overflow indicator.
686
+ let budget = maxBody - 1;
687
+ let hiddenRunning = running.length - runningLines.length;
688
+ let hiddenFinished = finished.length - finishedLines.length;
689
+
690
+ // Reserve the queued line's row up front. It is a single summary of N
691
+ // waiting agents, so it cannot be folded into the "+N more" count (which
692
+ // is denominated in agents) without either under-reporting it as 1 or
693
+ // inflating the total with agents that were never getting their own rows.
694
+ // Reserving costs at most one running agent — which IS counted below —
695
+ // and makes the drop unreachable. It matters most exactly when it used to
696
+ // vanish: the pool is saturated and the queue is what the user needs to see.
697
+ const queuedReserve = queuedLine ? 1 : 0;
698
+ budget -= queuedReserve;
699
+
700
+ // 1. Running agents (whole cards only)
701
+ for (const pair of runningLines) {
702
+ if (budget >= pair.length) {
703
+ lines.push(...pair);
704
+ budget -= pair.length;
705
+ } else {
706
+ hiddenRunning++;
707
+ }
708
+ }
709
+
710
+ // 2. Queued line (always fits — its row was reserved above)
711
+ if (queuedLine) {
712
+ budget += queuedReserve;
713
+ lines.push(queuedLine);
714
+ budget--;
715
+ }
716
+
717
+ // 3. Finished agents
718
+ for (const fl of finishedLines) {
719
+ if (budget >= 1) {
720
+ lines.push(fl);
721
+ budget--;
722
+ } else {
723
+ hiddenFinished++;
724
+ }
725
+ }
726
+
727
+ // Overflow summary
728
+ const overflowParts: string[] = [];
729
+ if (hiddenRunning > 0) overflowParts.push(`${hiddenRunning} running`);
730
+ if (hiddenFinished > 0) overflowParts.push(`${hiddenFinished} finished`);
731
+ const overflowText = overflowParts.join(", ");
732
+ lines.push(truncate(theme.fg("dim", "└─") + ` ${theme.fg("dim", `+${hiddenRunning + hiddenFinished} more (${overflowText})`)}`)
733
+ );
734
+ }
735
+
736
+ return lines;
737
+ }
738
+
739
+ /**
740
+ * Acquire the TUI reference without a visible list. Pi invokes the factory
741
+ * synchronously inside setWidget but paints on the next render tick, so a
742
+ * register immediately followed by an unregister captures the reference and
743
+ * never draws a frame. A separate key from the real widget, so the
744
+ * registration state machine never notices.
745
+ */
746
+ private probeTui(): void {
747
+ if (!this.uiCtx) return;
748
+ this.uiCtx.setWidget("agents-probe", tui => {
749
+ this.tui = tui;
750
+ return { render: () => [], invalidate: () => {} };
751
+ });
752
+ this.uiCtx.setWidget("agents-probe", undefined);
753
+ }
754
+
755
+ /** Force an immediate widget update. */
756
+ update() {
757
+ if (!this.uiCtx) return;
758
+ const allAgents = this.widgetAgents();
759
+
760
+ // Lightweight existence checks — full categorization happens in renderWidget()
761
+ let runningCount = 0;
762
+ let queuedCount = 0;
763
+ let hasFinished = false;
764
+ let earliestExpiry = Number.POSITIVE_INFINITY;
765
+ for (const a of allAgents) {
766
+ if (a.status === "running") { runningCount++; }
767
+ else if (a.status === "queued") { queuedCount++; }
768
+ else if (a.completedAt && this.shouldShowFinished(a.id, a.status)) {
769
+ hasFinished = true;
770
+ earliestExpiry = Math.min(earliestExpiry, this.finishedExpiry(a.id, a.status));
771
+ }
772
+ }
773
+ const hasActive = runningCount > 0 || queuedCount > 0;
774
+
775
+ // Repaint scheduling: animate only while something is active. With only
776
+ // finished rows left, render once and wake a single time when the
777
+ // earliest row expires — an idle session must not redraw at 12.5 Hz.
778
+ if (hasActive) {
779
+ this.clearExpiryTimer();
780
+ this.ensureTimer();
781
+ } else {
782
+ this.stopInterval();
783
+ if (hasFinished) this.scheduleExpiry(earliestExpiry);
784
+ else this.clearExpiryTimer();
785
+ }
786
+
787
+ // Nothing to show — clear widget
788
+ if (!hasActive && !hasFinished) {
789
+ if (this.widgetRegistered) {
790
+ this.uiCtx.setWidget("agents", undefined);
791
+ this.widgetRegistered = false;
792
+ this.registeredPlacement = undefined;
793
+ // `this.tui` deliberately survives the hide: the ← handler reads focus
794
+ // from it, and a reference from any past mount stays valid for the
795
+ // whole interactive session.
796
+ }
797
+ if (this.lastStatusText !== undefined) {
798
+ this.uiCtx.setStatus("subagents", undefined);
799
+ this.lastStatusText = undefined;
800
+ }
801
+ // Clean up stale entries
802
+ for (const [id] of this.finishedTurnAge) {
803
+ if (!allAgents.some(a => a.id === id)) this.finishedTurnAge.delete(id);
804
+ }
805
+ for (const [id] of this.finishedAt) {
806
+ if (!allAgents.some(a => a.id === id)) this.finishedAt.delete(id);
807
+ }
808
+ return;
809
+ }
810
+
811
+ // Status bar — only call setStatus when the text actually changes
812
+ let newStatusText: string | undefined;
813
+ if (hasActive) {
814
+ const statusParts: string[] = [];
815
+ if (runningCount > 0) statusParts.push(`${runningCount} running`);
816
+ if (queuedCount > 0) statusParts.push(`${queuedCount} queued`);
817
+ const total = runningCount + queuedCount;
818
+ newStatusText = `${statusParts.join(", ")} agent${total === 1 ? "" : "s"}`;
819
+ }
820
+ if (newStatusText !== this.lastStatusText) {
821
+ this.uiCtx.setStatus("subagents", newStatusText);
822
+ this.lastStatusText = newStatusText;
823
+ }
824
+
825
+ this.widgetFrame++;
826
+
827
+ // Same-key registration moves between Pi's placement Maps. Otherwise keep
828
+ // the component and its insertion order stable across spinner updates.
829
+ const placement = this.placement();
830
+ if (!this.widgetRegistered || this.registeredPlacement !== placement) {
831
+ this.uiCtx.setWidget("agents", (tui, theme) => {
832
+ this.tui = tui;
833
+ return {
834
+ render: (width?: number) => this.renderWidget(tui, theme, width),
835
+ invalidate: () => {
836
+ // Theme changed — force re-registration so the factory captures the
837
+ // fresh theme. The TUI reference stays: it does not change themes.
838
+ this.widgetRegistered = false;
839
+ this.registeredPlacement = undefined;
840
+ },
841
+ };
842
+ }, { placement: placement === "above" ? "aboveEditor" : "belowEditor" });
843
+ this.widgetRegistered = true;
844
+ this.registeredPlacement = placement;
845
+ } else {
846
+ // Widget already registered — just request a re-render of existing components.
847
+ this.tui?.requestRender();
848
+ }
849
+ }
850
+
851
+ dispose() {
852
+ this.stopInterval();
853
+ this.clearExpiryTimer();
854
+ this.inputUnsub?.();
855
+ this.inputUnsub = undefined;
856
+ if (this.uiCtx) {
857
+ this.uiCtx.setWidget("agents", undefined);
858
+ this.uiCtx.setStatus("subagents", undefined);
859
+ }
860
+ this.widgetRegistered = false;
861
+ this.registeredPlacement = undefined;
862
+ this.tui = undefined;
863
+ this.uiCtx = undefined;
864
+ this.lastStatusText = undefined;
865
+ }
866
+ }