@timmyjl12/pi-subagents 0.0.0-stage → 0.20.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 (218) hide show
  1. package/CHANGELOG.md +827 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1079 -2
  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 +18 -0
  9. package/dist/active-agents-prompt.js +34 -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 +123 -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 +485 -0
  17. package/dist/agent-manager.js +1380 -0
  18. package/dist/agent-runner.d.ts +319 -0
  19. package/dist/agent-runner.js +1128 -0
  20. package/dist/agent-types.d.ts +119 -0
  21. package/dist/agent-types.js +286 -0
  22. package/dist/child-context.d.ts +15 -0
  23. package/dist/child-context.js +181 -0
  24. package/dist/child-session-shutdown.d.ts +3 -0
  25. package/dist/child-session-shutdown.js +48 -0
  26. package/dist/context.d.ts +12 -0
  27. package/dist/context.js +56 -0
  28. package/dist/cross-extension-rpc.d.ts +66 -0
  29. package/dist/cross-extension-rpc.js +138 -0
  30. package/dist/custom-agents.d.ts +54 -0
  31. package/dist/custom-agents.js +386 -0
  32. package/dist/default-agents.d.ts +7 -0
  33. package/dist/default-agents.js +125 -0
  34. package/dist/enabled-models.d.ts +49 -0
  35. package/dist/enabled-models.js +145 -0
  36. package/dist/env.d.ts +6 -0
  37. package/dist/env.js +28 -0
  38. package/dist/error-log.d.ts +58 -0
  39. package/dist/error-log.js +168 -0
  40. package/dist/group-join.d.ts +32 -0
  41. package/dist/group-join.js +116 -0
  42. package/dist/index.d.ts +52 -0
  43. package/dist/index.js +3896 -0
  44. package/dist/invocation-config.d.ts +137 -0
  45. package/dist/invocation-config.js +129 -0
  46. package/dist/memory.d.ts +53 -0
  47. package/dist/memory.js +165 -0
  48. package/dist/mention-clone.d.ts +87 -0
  49. package/dist/mention-clone.js +178 -0
  50. package/dist/mention.d.ts +81 -0
  51. package/dist/mention.js +131 -0
  52. package/dist/model-resolver.d.ts +36 -0
  53. package/dist/model-resolver.js +95 -0
  54. package/dist/model-scope.d.ts +49 -0
  55. package/dist/model-scope.js +48 -0
  56. package/dist/nested-tools.d.ts +55 -0
  57. package/dist/nested-tools.js +299 -0
  58. package/dist/output-diagnostics.d.ts +11 -0
  59. package/dist/output-diagnostics.js +64 -0
  60. package/dist/output-file.d.ts +53 -0
  61. package/dist/output-file.js +248 -0
  62. package/dist/prompts.d.ts +61 -0
  63. package/dist/prompts.js +94 -0
  64. package/dist/recovery.d.ts +56 -0
  65. package/dist/recovery.js +341 -0
  66. package/dist/schedule-store.d.ts +44 -0
  67. package/dist/schedule-store.js +210 -0
  68. package/dist/schedule.d.ts +109 -0
  69. package/dist/schedule.js +359 -0
  70. package/dist/settings.d.ts +360 -0
  71. package/dist/settings.js +251 -0
  72. package/dist/skill-loader.d.ts +24 -0
  73. package/dist/skill-loader.js +93 -0
  74. package/dist/standalone-fallback.d.ts +30 -0
  75. package/dist/standalone-fallback.js +239 -0
  76. package/dist/status-note.d.ts +61 -0
  77. package/dist/status-note.js +85 -0
  78. package/dist/structured-output.d.ts +61 -0
  79. package/dist/structured-output.js +112 -0
  80. package/dist/terminal-progress.d.ts +115 -0
  81. package/dist/terminal-progress.js +206 -0
  82. package/dist/types.d.ts +382 -0
  83. package/dist/types.js +5 -0
  84. package/dist/ui/agent-mention.d.ts +82 -0
  85. package/dist/ui/agent-mention.js +187 -0
  86. package/dist/ui/agent-widget.d.ts +235 -0
  87. package/dist/ui/agent-widget.js +652 -0
  88. package/dist/ui/conversation-viewer.d.ts +105 -0
  89. package/dist/ui/conversation-viewer.js +540 -0
  90. package/dist/ui/fleet-list.d.ts +183 -0
  91. package/dist/ui/fleet-list.js +494 -0
  92. package/dist/ui/fleet-overlay.d.ts +172 -0
  93. package/dist/ui/fleet-overlay.js +691 -0
  94. package/dist/ui/native-transcript.d.ts +33 -0
  95. package/dist/ui/native-transcript.js +230 -0
  96. package/dist/ui/schedule-menu.d.ts +16 -0
  97. package/dist/ui/schedule-menu.js +94 -0
  98. package/dist/ui/select-item.d.ts +27 -0
  99. package/dist/ui/select-item.js +34 -0
  100. package/dist/ui/tool-progress.d.ts +22 -0
  101. package/dist/ui/tool-progress.js +56 -0
  102. package/dist/ui/viewer-keys.d.ts +20 -0
  103. package/dist/ui/viewer-keys.js +17 -0
  104. package/dist/ui/workflow-card.d.ts +175 -0
  105. package/dist/ui/workflow-card.js +332 -0
  106. package/dist/ui/workflow-dialog.d.ts +305 -0
  107. package/dist/ui/workflow-dialog.js +843 -0
  108. package/dist/ui/workflow-menu.d.ts +60 -0
  109. package/dist/ui/workflow-menu.js +147 -0
  110. package/dist/usage.d.ts +135 -0
  111. package/dist/usage.js +120 -0
  112. package/dist/workflow/collisions.d.ts +95 -0
  113. package/dist/workflow/collisions.js +88 -0
  114. package/dist/workflow/entry.d.ts +32 -0
  115. package/dist/workflow/entry.js +29 -0
  116. package/dist/workflow/host.d.ts +62 -0
  117. package/dist/workflow/host.js +363 -0
  118. package/dist/workflow/journal.d.ts +97 -0
  119. package/dist/workflow/journal.js +120 -0
  120. package/dist/workflow/json-schema.d.ts +51 -0
  121. package/dist/workflow/json-schema.js +111 -0
  122. package/dist/workflow/meta.d.ts +67 -0
  123. package/dist/workflow/meta.js +317 -0
  124. package/dist/workflow/progress.d.ts +224 -0
  125. package/dist/workflow/progress.js +361 -0
  126. package/dist/workflow/runtime.d.ts +334 -0
  127. package/dist/workflow/runtime.js +830 -0
  128. package/dist/workflow/saved.d.ts +90 -0
  129. package/dist/workflow/saved.js +203 -0
  130. package/dist/workflow/task.d.ts +136 -0
  131. package/dist/workflow/task.js +207 -0
  132. package/dist/workflow/tool-description.d.ts +38 -0
  133. package/dist/workflow/tool-description.js +199 -0
  134. package/dist/workflow/worker-source.d.ts +47 -0
  135. package/dist/workflow/worker-source.js +778 -0
  136. package/dist/worktree.d.ts +52 -0
  137. package/dist/worktree.js +164 -0
  138. package/dist/xml.d.ts +10 -0
  139. package/dist/xml.js +12 -0
  140. package/docs/FORK.md +40 -0
  141. package/docs/recovery.md +62 -0
  142. package/docs/rpc.md +189 -0
  143. package/docs/workflows.md +437 -0
  144. package/examples/agent-tool-description.md +43 -0
  145. package/examples/workflows/compose.js +51 -0
  146. package/examples/workflows/fan-out-audit.js +47 -0
  147. package/examples/workflows/gated-fix.js +60 -0
  148. package/examples/workflows/lib/count-child.js +27 -0
  149. package/examples/workflows/review-panel.js +63 -0
  150. package/examples/workflows/structured-findings.js +78 -0
  151. package/package.json +75 -6
  152. package/src/abortable.ts +43 -0
  153. package/src/active-agents-prompt.ts +39 -0
  154. package/src/advisor-status.ts +74 -0
  155. package/src/agent-color.ts +161 -0
  156. package/src/agent-file-toggle.ts +273 -0
  157. package/src/agent-manager.ts +1601 -0
  158. package/src/agent-runner.ts +1372 -0
  159. package/src/agent-types.ts +345 -0
  160. package/src/child-context.ts +173 -0
  161. package/src/child-session-shutdown.ts +46 -0
  162. package/src/context.ts +58 -0
  163. package/src/cross-extension-rpc.ts +198 -0
  164. package/src/custom-agents.ts +417 -0
  165. package/src/default-agents.ts +129 -0
  166. package/src/enabled-models.ts +180 -0
  167. package/src/env.ts +33 -0
  168. package/src/error-log.ts +193 -0
  169. package/src/group-join.ts +141 -0
  170. package/src/index.ts +4218 -0
  171. package/src/invocation-config.ts +230 -0
  172. package/src/memory.ts +179 -0
  173. package/src/mention-clone.ts +221 -0
  174. package/src/mention.ts +141 -0
  175. package/src/model-resolver.ts +118 -0
  176. package/src/model-scope.ts +70 -0
  177. package/src/nested-tools.ts +422 -0
  178. package/src/output-diagnostics.ts +68 -0
  179. package/src/output-file.ts +258 -0
  180. package/src/prompts.ts +151 -0
  181. package/src/recovery.ts +320 -0
  182. package/src/schedule-store.ts +201 -0
  183. package/src/schedule.ts +386 -0
  184. package/src/settings.ts +587 -0
  185. package/src/skill-loader.ts +102 -0
  186. package/src/standalone-fallback.ts +195 -0
  187. package/src/status-note.ts +90 -0
  188. package/src/structured-output.ts +130 -0
  189. package/src/terminal-progress.ts +215 -0
  190. package/src/types.ts +394 -0
  191. package/src/ui/agent-mention.ts +216 -0
  192. package/src/ui/agent-widget.ts +732 -0
  193. package/src/ui/conversation-viewer.ts +523 -0
  194. package/src/ui/fleet-list.ts +563 -0
  195. package/src/ui/fleet-overlay.ts +847 -0
  196. package/src/ui/native-transcript.ts +220 -0
  197. package/src/ui/schedule-menu.ts +105 -0
  198. package/src/ui/select-item.ts +45 -0
  199. package/src/ui/tool-progress.ts +67 -0
  200. package/src/ui/viewer-keys.ts +39 -0
  201. package/src/ui/workflow-card.ts +470 -0
  202. package/src/ui/workflow-dialog.ts +1115 -0
  203. package/src/ui/workflow-menu.ts +193 -0
  204. package/src/usage.ts +167 -0
  205. package/src/workflow/collisions.ts +123 -0
  206. package/src/workflow/entry.ts +47 -0
  207. package/src/workflow/host.ts +404 -0
  208. package/src/workflow/journal.ts +164 -0
  209. package/src/workflow/json-schema.ts +128 -0
  210. package/src/workflow/meta.ts +325 -0
  211. package/src/workflow/progress.ts +550 -0
  212. package/src/workflow/runtime.ts +1219 -0
  213. package/src/workflow/saved.ts +217 -0
  214. package/src/workflow/task.ts +302 -0
  215. package/src/workflow/tool-description.ts +200 -0
  216. package/src/workflow/worker-source.ts +781 -0
  217. package/src/worktree.ts +205 -0
  218. package/src/xml.ts +13 -0
@@ -0,0 +1,652 @@
1
+ /**
2
+ * agent-widget.ts — Persistent widget showing running/completed agents above 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
+ import { truncateToWidth } from "@earendil-works/pi-tui";
8
+ import { formatAdvisorStatus } from "../advisor-status.js";
9
+ import { renderAgentName } from "../agent-color.js";
10
+ import { isTopLevelAgent } from "../agent-manager.js";
11
+ import { getConfig } from "../agent-types.js";
12
+ import { getLifetimeCost, getLifetimeTotal, getSessionContextPercent } from "../usage.js";
13
+ // ---- Constants ----
14
+ /** Maximum number of rendered lines before overflow collapse kicks in. */
15
+ const MAX_WIDGET_LINES = 12;
16
+ /** Braille spinner frames for animated running indicator. */
17
+ export const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
18
+ /** Statuses that indicate an error/non-success outcome (used for linger behavior and icon rendering). */
19
+ export const ERROR_STATUSES = new Set(["error", "aborted", "steered", "stopped"]);
20
+ /** Tool name → human-readable action for activity descriptions. */
21
+ const TOOL_DISPLAY = {
22
+ read: "reading",
23
+ bash: "running command",
24
+ edit: "editing",
25
+ write: "writing",
26
+ grep: "searching",
27
+ find: "finding files",
28
+ ls: "listing",
29
+ };
30
+ // ---- Formatting helpers ----
31
+ /** Apply foreground styling while restoring it after nested foreground/full ANSI resets. */
32
+ export function fgPreservingNestedStyles(theme, color, text) {
33
+ const styledEmpty = theme.fg(color, "");
34
+ const styleStart = styledEmpty.replace(/\u001b\[(?:0|39)m/g, "");
35
+ return theme.fg(color, text.replace(/\u001b\[(?:0|39)m/g, reset => `${reset}${styleStart}`));
36
+ }
37
+ /** Format a token count compactly: "33.8k token", "1.2M token". */
38
+ export function formatTokens(count) {
39
+ if (count >= 1_000_000)
40
+ return `${(count / 1_000_000).toFixed(1)}M token`;
41
+ if (count >= 1_000)
42
+ return `${(count / 1_000).toFixed(1)}k token`;
43
+ return `${count} token`;
44
+ }
45
+ /**
46
+ * Format a cost as `~$0.0042`, or "" when there is nothing to show.
47
+ *
48
+ * The tilde is load-bearing: this is pi's own estimate from the model's listed
49
+ * rates, not a billed figure, and the surfaces that print it sit next to token
50
+ * counts that ARE exact.
51
+ *
52
+ * Nothing is printed for zero, which is also what a model with no pricing data
53
+ * reports: `$0.00` beside a local model's tokens would claim its cost was
54
+ * measured and found to be nothing, rather than never measured at all. For the
55
+ * same reason a real cost too small for four decimals reads `<$0.0001` — it was
56
+ * measured, and rounding it to `~$0.0000` would say the opposite.
57
+ */
58
+ export function formatCost(cost) {
59
+ if (!(cost > 0))
60
+ return ""; // also catches NaN
61
+ if (cost < 0.0001)
62
+ return "<$0.0001";
63
+ if (cost >= 1)
64
+ return `~$${cost.toFixed(2)}`;
65
+ // Under a dollar: cents at minimum, four decimals at most, nothing trailing.
66
+ // Most single runs land between a tenth of a cent and a dime, where rounding
67
+ // to cents would collapse a 4x difference in spend into the same figure.
68
+ const rounded = Number(cost.toFixed(4));
69
+ const decimals = (String(rounded).split(".")[1] ?? "").length;
70
+ return `~$${rounded.toFixed(Math.max(2, decimals))}`;
71
+ }
72
+ /**
73
+ * Token count with optional context-fill % and compaction-count annotations.
74
+ * Thresholds for percent: <70% dim, 70–85% warning, ≥85% error.
75
+ * Compaction count rendered as `⇊N` in dim.
76
+ *
77
+ * "12.3k token" — no annotations
78
+ * "12.3k token (45%)" — percent only
79
+ * "12.3k token (⇊2)" — compactions only (e.g. right after compact)
80
+ * "12.3k token (45% · ⇊2)" — both
81
+ */
82
+ export function formatSessionTokens(tokens, percent, theme, compactions = 0) {
83
+ const tokenStr = formatTokens(tokens);
84
+ const annot = [];
85
+ if (percent !== null) {
86
+ const color = percent >= 85 ? "error" : percent >= 70 ? "warning" : "dim";
87
+ annot.push(theme.fg(color, `${Math.round(percent)}%`));
88
+ }
89
+ if (compactions > 0) {
90
+ annot.push(theme.fg("dim", `⇊${compactions}`));
91
+ }
92
+ if (annot.length === 0)
93
+ return tokenStr;
94
+ return `${tokenStr} (${annot.join(" · ")})`;
95
+ }
96
+ /** Format turn count with optional max limit: "↻5≤30" or "↻5". */
97
+ export function formatTurns(turnCount, maxTurns) {
98
+ return maxTurns != null ? `↻${turnCount}≤${maxTurns}` : `↻${turnCount}`;
99
+ }
100
+ /** Format milliseconds as human-readable duration. */
101
+ export function formatMs(ms) {
102
+ return `${(ms / 1000).toFixed(1)}s`;
103
+ }
104
+ /** Format duration from start/completed timestamps. */
105
+ export function formatDuration(startedAt, completedAt) {
106
+ if (completedAt)
107
+ return formatMs(completedAt - startedAt);
108
+ return `${formatMs(Date.now() - startedAt)} (running)`;
109
+ }
110
+ /** Get display name for any agent type (built-in or custom). */
111
+ export function getDisplayName(type) {
112
+ return getConfig(type).displayName;
113
+ }
114
+ /** Short label for prompt mode: "twin" for append, nothing for replace (the default). */
115
+ export function getPromptModeLabel(type) {
116
+ const config = getConfig(type);
117
+ return config.promptMode === "append" ? "twin" : undefined;
118
+ }
119
+ /**
120
+ * Mode label is not included — callers add it where they want it.
121
+ *
122
+ * Both model forms come back so each surface can pick by width; the
123
+ * "(asked X)" annotation is applied here rather than by callers, so a value the
124
+ * spawn did not honor cannot be rendered as though it had been (#182).
125
+ */
126
+ export function buildInvocationTags(invocation) {
127
+ const tags = [];
128
+ if (!invocation)
129
+ return { tags };
130
+ const asked = (value, requested) => value && requested && requested !== value ? `${value} (asked ${requested})` : value;
131
+ const thinking = asked(invocation.thinking, invocation.requestedThinking);
132
+ if (thinking)
133
+ tags.push(`thinking: ${thinking}`);
134
+ if (invocation.isolated)
135
+ tags.push("isolated");
136
+ if (invocation.isolation === "worktree")
137
+ tags.push("worktree");
138
+ if (invocation.inheritContext)
139
+ tags.push("inherit context");
140
+ if (invocation.runInBackground)
141
+ tags.push("background");
142
+ if (invocation.maxTurns != null)
143
+ tags.push(`max turns: ${invocation.maxTurns}`);
144
+ return {
145
+ modelName: asked(invocation.modelName, invocation.requestedModel),
146
+ modelId: asked(invocation.modelId, invocation.requestedModel),
147
+ tags,
148
+ };
149
+ }
150
+ /** Truncate text to a single line, max `len` chars. */
151
+ function truncateLine(text, len = 60) {
152
+ const line = text.split("\n").find(l => l.trim())?.trim() ?? "";
153
+ if (line.length <= len)
154
+ return line;
155
+ return line.slice(0, len) + "…";
156
+ }
157
+ /** Build a human-readable activity string from currently-running tools or response text. */
158
+ export function describeActivity(activeTools, responseText) {
159
+ if (activeTools.size > 0) {
160
+ const groups = new Map();
161
+ for (const toolName of activeTools.values()) {
162
+ const action = TOOL_DISPLAY[toolName] ?? toolName;
163
+ groups.set(action, (groups.get(action) ?? 0) + 1);
164
+ }
165
+ const parts = [];
166
+ for (const [action, count] of groups) {
167
+ if (count > 1) {
168
+ parts.push(`${action} ${count} ${action === "searching" ? "patterns" : "files"}`);
169
+ }
170
+ else {
171
+ parts.push(action);
172
+ }
173
+ }
174
+ return parts.join(", ") + "…";
175
+ }
176
+ // No tools active — show truncated response text if available
177
+ if (responseText && responseText.trim().length > 0) {
178
+ return truncateLine(responseText);
179
+ }
180
+ return "thinking…";
181
+ }
182
+ // ---- Widget manager ----
183
+ export class AgentWidget {
184
+ manager;
185
+ agentActivity;
186
+ mode;
187
+ showCost;
188
+ showModel;
189
+ uiCtx;
190
+ widgetFrame = 0;
191
+ widgetInterval;
192
+ /** One-shot timer that re-runs update() when the earliest finished row expires. */
193
+ expiryTimer;
194
+ /** Wall-clock time each finished agent was first seen finished. */
195
+ finishedAt = new Map();
196
+ /** How long a completed row lingers without any turn activity. */
197
+ static FINISHED_LINGER_MS = 5000;
198
+ /** Errors/aborts linger longer so they are not missed. */
199
+ static ERROR_LINGER_MS = 10000;
200
+ /** Tracks how many turns each finished agent has survived. Key: agent ID, Value: turns since finished. */
201
+ finishedTurnAge = new Map();
202
+ /** How many extra turns errors/aborted agents linger (completed agents clear after 1 turn). */
203
+ static ERROR_LINGER_TURNS = 2;
204
+ /** Whether the widget callback is currently registered with the TUI. */
205
+ widgetRegistered = false;
206
+ /** Cached TUI reference from widget factory callback, used for requestRender(). */
207
+ tui;
208
+ /** Last status bar text, used to avoid redundant setStatus calls. */
209
+ lastStatusText;
210
+ constructor(manager, agentActivity,
211
+ /**
212
+ * Read live at render time. Selects which agents the widget shows — see
213
+ * `WidgetMode`. Defaults to `"all"` when a caller supplies no policy; the
214
+ * extension supplies one defaulting to `"background"`.
215
+ */
216
+ mode = () => "all",
217
+ /**
218
+ * Read live at render time, like `mode`. Whether running agents show an
219
+ * estimated cost beside their token count. Defaults to off — the extension
220
+ * supplies the user's `showCost` setting.
221
+ */
222
+ showCost = () => false,
223
+ /**
224
+ * Read live at render time, like `mode`. Whether running agents name the
225
+ * model driving them and the thinking level it is running at. Defaults to
226
+ * off — the extension supplies the user's `showModel` setting — because the
227
+ * row is already dense and the same pair is on the tool result and in the
228
+ * conversation viewer unconditionally.
229
+ */
230
+ showModel = () => false) {
231
+ this.manager = manager;
232
+ this.agentActivity = agentActivity;
233
+ this.mode = mode;
234
+ this.showCost = showCost;
235
+ this.showModel = showModel;
236
+ }
237
+ /**
238
+ * Agents eligible for the widget, per the current `WidgetMode`:
239
+ * - `off`: none (the widget's existing empty-state path hides it entirely).
240
+ * - `background`: drop only agents *known* to be foreground
241
+ * (`isBackground === false`); keep everything else — background, queued,
242
+ * scheduled, or RPC-spawned (`undefined`). Keying off the `isBackground`
243
+ * record flag rather than the UI-only `invocation` snapshot (which only the
244
+ * Agent-tool path sets), and excluding rather than allow-listing, means
245
+ * only proven-foreground runs drop out — nothing else silently vanishes.
246
+ * - `all`: every agent.
247
+ */
248
+ widgetAgents() {
249
+ const all = this.manager.listAgents().filter(isTopLevelAgent);
250
+ switch (this.mode()) {
251
+ case "off": return [];
252
+ case "background": return all.filter(a => a.isBackground !== false);
253
+ default: return all;
254
+ }
255
+ }
256
+ /** Set the UI context (grabbed from first tool execution). */
257
+ setUICtx(ctx) {
258
+ if (ctx !== this.uiCtx) {
259
+ // UICtx changed — the widget registered on the old context is gone.
260
+ // Force re-registration on next update().
261
+ this.uiCtx = ctx;
262
+ this.widgetRegistered = false;
263
+ this.tui = undefined;
264
+ this.lastStatusText = undefined;
265
+ }
266
+ }
267
+ /**
268
+ * Called on each new turn (tool_execution_start).
269
+ * Ages finished agents and clears those that have lingered long enough.
270
+ */
271
+ onTurnStart() {
272
+ // Age all finished agents
273
+ for (const [id, age] of this.finishedTurnAge) {
274
+ this.finishedTurnAge.set(id, age + 1);
275
+ }
276
+ // Trigger a widget refresh (will filter out expired agents)
277
+ this.update();
278
+ }
279
+ /** Ensure the widget update timer is running. */
280
+ ensureTimer() {
281
+ if (!this.widgetInterval) {
282
+ // The spinner only animates while something is running/queued; update()
283
+ // stops this interval as soon as nothing active remains.
284
+ this.widgetInterval = setInterval(() => this.update(), 80);
285
+ this.widgetInterval.unref?.();
286
+ }
287
+ }
288
+ /** Check if a finished agent should still be shown in the widget. */
289
+ shouldShowFinished(agentId, status) {
290
+ const age = this.finishedTurnAge.get(agentId) ?? 0;
291
+ const maxAge = ERROR_STATUSES.has(status) ? AgentWidget.ERROR_LINGER_TURNS : 1;
292
+ if (age >= maxAge)
293
+ return false;
294
+ return Date.now() < this.finishedExpiry(agentId, status);
295
+ }
296
+ /** Wall-clock expiry of a finished row (seeds the finish time on first sight). */
297
+ finishedExpiry(agentId, status) {
298
+ let at = this.finishedAt.get(agentId);
299
+ if (at === undefined) {
300
+ at = Date.now();
301
+ this.finishedAt.set(agentId, at);
302
+ }
303
+ return at + (ERROR_STATUSES.has(status) ? AgentWidget.ERROR_LINGER_MS : AgentWidget.FINISHED_LINGER_MS);
304
+ }
305
+ /** Record an agent as finished (call when agent completes). */
306
+ markFinished(agentId) {
307
+ if (!this.finishedTurnAge.has(agentId)) {
308
+ this.finishedTurnAge.set(agentId, 0);
309
+ }
310
+ if (!this.finishedAt.has(agentId))
311
+ this.finishedAt.set(agentId, Date.now());
312
+ }
313
+ stopInterval() {
314
+ if (this.widgetInterval) {
315
+ clearInterval(this.widgetInterval);
316
+ this.widgetInterval = undefined;
317
+ }
318
+ }
319
+ clearExpiryTimer() {
320
+ if (this.expiryTimer) {
321
+ clearTimeout(this.expiryTimer);
322
+ this.expiryTimer = undefined;
323
+ }
324
+ }
325
+ /** Schedule one unref'd update() at the given wall-clock time. */
326
+ scheduleExpiry(at) {
327
+ this.clearExpiryTimer();
328
+ this.expiryTimer = setTimeout(() => {
329
+ this.expiryTimer = undefined;
330
+ this.update();
331
+ }, Math.max(0, at - Date.now()) + 20);
332
+ this.expiryTimer.unref?.();
333
+ }
334
+ /** True while the widget holds a repaint timer (interval or expiry). */
335
+ hasPendingTimers() {
336
+ return this.widgetInterval !== undefined || this.expiryTimer !== undefined;
337
+ }
338
+ /**
339
+ * Drop an agent's finished-age (call when a settled agent starts running
340
+ * again, i.e. a background resume). markFinished only seeds an age it has not
341
+ * seen before, so a resumed agent would otherwise keep the age from its
342
+ * previous run — already past the linger limit, hiding the new run's
343
+ * completion line entirely.
344
+ */
345
+ markRunning(agentId) {
346
+ this.finishedTurnAge.delete(agentId);
347
+ this.finishedAt.delete(agentId);
348
+ }
349
+ /** Render a finished agent line. */
350
+ renderFinishedLine(a, theme) {
351
+ const modeLabel = getPromptModeLabel(a.type);
352
+ const duration = formatMs((a.completedAt ?? Date.now()) - a.startedAt);
353
+ let icon;
354
+ let statusText;
355
+ if (a.status === "completed") {
356
+ icon = theme.fg("success", "✓");
357
+ statusText = "";
358
+ }
359
+ else if (a.status === "steered") {
360
+ icon = theme.fg("warning", "✓");
361
+ statusText = theme.fg("warning", " (turn limit)");
362
+ }
363
+ else if (a.status === "stopped") {
364
+ icon = theme.fg("dim", "■");
365
+ statusText = theme.fg("dim", " stopped");
366
+ }
367
+ else if (a.status === "error") {
368
+ icon = theme.fg("error", "✗");
369
+ const errMsg = a.error ? `: ${a.error.slice(0, 60)}` : "";
370
+ statusText = theme.fg("error", ` error${errMsg}`);
371
+ }
372
+ else {
373
+ // aborted
374
+ icon = theme.fg("error", "✗");
375
+ statusText = theme.fg("warning", " aborted");
376
+ }
377
+ const parts = [];
378
+ const activity = this.agentActivity.get(a.id);
379
+ if (activity)
380
+ parts.push(formatTurns(activity.turnCount, activity.maxTurns));
381
+ if (a.toolUses > 0)
382
+ parts.push(`${a.toolUses} tool use${a.toolUses === 1 ? "" : "s"}`);
383
+ // From the record, not the activity tracker: that entry is deleted the
384
+ // moment an agent finishes, and "what did it cost" is a question asked
385
+ // about finished agents.
386
+ const costText = this.showCost() ? formatCost(getLifetimeCost(a.lifetimeUsage)) : "";
387
+ if (costText)
388
+ parts.push(costText);
389
+ parts.push(duration);
390
+ const modeTag = modeLabel ? ` ${theme.fg("dim", `(${modeLabel})`)}` : "";
391
+ return `${icon} ${renderAgentName(a.type, theme, { fallbackColor: "dim" })}${modeTag} ${theme.fg("dim", a.description)} ${theme.fg("dim", "·")} ${theme.fg("dim", parts.join(" · "))}${statusText}`;
392
+ }
393
+ /**
394
+ * Render the widget content. Called from the registered widget's render() callback,
395
+ * reading live state each time instead of capturing it in a closure.
396
+ */
397
+ renderWidget(tui, theme) {
398
+ const allAgents = this.widgetAgents();
399
+ const running = allAgents.filter(a => a.status === "running");
400
+ const queued = allAgents.filter(a => a.status === "queued");
401
+ const finished = allAgents.filter(a => a.status !== "running" && a.status !== "queued" && a.completedAt
402
+ && this.shouldShowFinished(a.id, a.status));
403
+ const hasActive = running.length > 0 || queued.length > 0;
404
+ const hasFinished = finished.length > 0;
405
+ // Nothing to show — return empty (widget will be unregistered by update())
406
+ if (!hasActive && !hasFinished)
407
+ return [];
408
+ const w = tui.terminal.columns;
409
+ const truncate = (line) => truncateToWidth(line, w);
410
+ const headingColor = hasActive ? "accent" : "dim";
411
+ const headingIcon = hasActive ? "●" : "○";
412
+ const frame = SPINNER[this.widgetFrame % SPINNER.length];
413
+ // Build sections separately for overflow-aware assembly.
414
+ // Running agents have header, activity and advisor rows; finished/queued stay compact.
415
+ const finishedLines = [];
416
+ for (const a of finished) {
417
+ finishedLines.push(truncate(theme.fg("dim", "├─") + " " + this.renderFinishedLine(a, theme)));
418
+ }
419
+ const runningLines = []; // each entry is [header, activity, advisor]
420
+ for (const a of running) {
421
+ const modeLabel = getPromptModeLabel(a.type);
422
+ const modeTag = modeLabel ? ` ${theme.fg("dim", `(${modeLabel})`)}` : "";
423
+ const elapsed = formatMs(Date.now() - a.startedAt);
424
+ const bg = this.agentActivity.get(a.id);
425
+ const toolUses = bg?.toolUses ?? a.toolUses;
426
+ // Spend comes from the record, never from the activity tracker: the record
427
+ // is the one that survives the agent finishing, and the one nested-tools
428
+ // folds a hidden child's spend into. Reading the tracker while an agent
429
+ // runs and the record once it stops made the figure jump at completion.
430
+ const tokens = getLifetimeTotal(a.lifetimeUsage);
431
+ const contextPercent = getSessionContextPercent(bg?.session);
432
+ const tokenText = tokens > 0 ? formatSessionTokens(tokens, contextPercent, theme, a.compactionCount) : "";
433
+ const costText = this.showCost() ? formatCost(getLifetimeCost(a.lifetimeUsage)) : "";
434
+ const parts = [];
435
+ if (this.showModel()) {
436
+ // Leading, and paired: a thinking level means nothing without the model
437
+ // it applies to. The tag is taken from buildInvocationTags rather than
438
+ // rebuilt so the "(asked X)" annotation survives.
439
+ const { modelName, tags } = buildInvocationTags(a.invocation);
440
+ if (modelName)
441
+ parts.push(modelName);
442
+ const thinkingTag = tags.find(tag => tag.startsWith("thinking: "));
443
+ if (thinkingTag)
444
+ parts.push(thinkingTag);
445
+ }
446
+ if (bg)
447
+ parts.push(formatTurns(bg.turnCount, bg.maxTurns));
448
+ if (toolUses > 0)
449
+ parts.push(`${toolUses} tool use${toolUses === 1 ? "" : "s"}`);
450
+ if (tokenText)
451
+ parts.push(tokenText);
452
+ if (costText)
453
+ parts.push(costText);
454
+ parts.push(elapsed);
455
+ const statsText = parts.join(" · ");
456
+ const activity = bg ? describeActivity(bg.activeTools, bg.responseText) : "thinking…";
457
+ runningLines.push([
458
+ truncate(theme.fg("dim", "├─") + ` ${theme.fg("accent", frame)} ${renderAgentName(a.type, theme, { bold: true })}${modeTag} ${theme.fg("muted", a.description)} ${theme.fg("dim", "·")} ${fgPreservingNestedStyles(theme, "dim", statsText)}`),
459
+ truncate(theme.fg("dim", "│ ") + theme.fg("dim", ` ⎿ ${activity}`)),
460
+ truncate(theme.fg("dim", "│ ") + theme.fg("dim", ` ⎿ ${formatAdvisorStatus(a.advisorStatus)}`)),
461
+ ]);
462
+ }
463
+ const queuedLine = queued.length > 0
464
+ ? truncate(theme.fg("dim", "├─") + ` ${theme.fg("muted", "◦")} ${theme.fg("dim", `${queued.length} queued`)}`)
465
+ : undefined;
466
+ // Assemble with overflow cap (heading + overflow indicator = 2 reserved lines).
467
+ const maxBody = MAX_WIDGET_LINES - 1; // heading takes 1 line
468
+ const totalBody = finishedLines.length + runningLines.reduce((sum, rows) => sum + rows.length, 0) + (queuedLine ? 1 : 0);
469
+ const lines = [truncate(theme.fg(headingColor, headingIcon) + " " + theme.fg(headingColor, "Agents"))];
470
+ if (totalBody <= maxBody) {
471
+ // Everything fits — add all lines and fix up connectors for the last item.
472
+ lines.push(...finishedLines);
473
+ for (const pair of runningLines)
474
+ lines.push(...pair);
475
+ if (queuedLine)
476
+ lines.push(queuedLine);
477
+ // Fix last connector: swap ├─ → └─ and │ → space for activity lines.
478
+ if (lines.length > 1) {
479
+ const last = lines.length - 1;
480
+ lines[last] = lines[last].replace("├─", "└─");
481
+ // If last item is a running agent activity line, fix indent of that line
482
+ // and fix the header line above it.
483
+ if (runningLines.length > 0 && !queuedLine) {
484
+ const lastRows = runningLines[runningLines.length - 1];
485
+ const header = lines.length - lastRows.length;
486
+ lines[header] = lines[header].replace("├─", "└─");
487
+ for (let row = header + 1; row < lines.length; row++) {
488
+ lines[row] = lines[row].replace("│ ", " ");
489
+ }
490
+ }
491
+ }
492
+ }
493
+ else {
494
+ // Overflow — prioritize: running > queued > finished.
495
+ // Reserve 1 line for overflow indicator.
496
+ let budget = maxBody - 1;
497
+ let hiddenRunning = 0;
498
+ let hiddenFinished = 0;
499
+ // Reserve the queued line's row up front. It is a single summary of N
500
+ // waiting agents, so it cannot be folded into the "+N more" count (which
501
+ // is denominated in agents) without either under-reporting it as 1 or
502
+ // inflating the total with agents that were never getting their own rows.
503
+ // Reserving costs at most one running agent — which IS counted below —
504
+ // and makes the drop unreachable. It matters most exactly when it used to
505
+ // vanish: the pool is saturated and the queue is what the user needs to see.
506
+ const queuedReserve = queuedLine ? 1 : 0;
507
+ budget -= queuedReserve;
508
+ // 1. Running agents (whole cards only)
509
+ for (const pair of runningLines) {
510
+ if (budget >= pair.length) {
511
+ lines.push(...pair);
512
+ budget -= pair.length;
513
+ }
514
+ else {
515
+ hiddenRunning++;
516
+ }
517
+ }
518
+ // 2. Queued line (always fits — its row was reserved above)
519
+ if (queuedLine) {
520
+ budget += queuedReserve;
521
+ lines.push(queuedLine);
522
+ budget--;
523
+ }
524
+ // 3. Finished agents
525
+ for (const fl of finishedLines) {
526
+ if (budget >= 1) {
527
+ lines.push(fl);
528
+ budget--;
529
+ }
530
+ else {
531
+ hiddenFinished++;
532
+ }
533
+ }
534
+ // Overflow summary
535
+ const overflowParts = [];
536
+ if (hiddenRunning > 0)
537
+ overflowParts.push(`${hiddenRunning} running`);
538
+ if (hiddenFinished > 0)
539
+ overflowParts.push(`${hiddenFinished} finished`);
540
+ const overflowText = overflowParts.join(", ");
541
+ lines.push(truncate(theme.fg("dim", "└─") + ` ${theme.fg("dim", `+${hiddenRunning + hiddenFinished} more (${overflowText})`)}`));
542
+ }
543
+ return lines;
544
+ }
545
+ /** Force an immediate widget update. */
546
+ update() {
547
+ if (!this.uiCtx)
548
+ return;
549
+ const allAgents = this.widgetAgents();
550
+ // Lightweight existence checks — full categorization happens in renderWidget()
551
+ let runningCount = 0;
552
+ let queuedCount = 0;
553
+ let hasFinished = false;
554
+ let earliestExpiry = Number.POSITIVE_INFINITY;
555
+ for (const a of allAgents) {
556
+ if (a.status === "running") {
557
+ runningCount++;
558
+ }
559
+ else if (a.status === "queued") {
560
+ queuedCount++;
561
+ }
562
+ else if (a.completedAt && this.shouldShowFinished(a.id, a.status)) {
563
+ hasFinished = true;
564
+ earliestExpiry = Math.min(earliestExpiry, this.finishedExpiry(a.id, a.status));
565
+ }
566
+ }
567
+ const hasActive = runningCount > 0 || queuedCount > 0;
568
+ // Repaint scheduling: animate only while something is active. With only
569
+ // finished rows left, render once and wake a single time when the
570
+ // earliest row expires — an idle session must not redraw at 12.5 Hz.
571
+ if (hasActive) {
572
+ this.clearExpiryTimer();
573
+ this.ensureTimer();
574
+ }
575
+ else {
576
+ this.stopInterval();
577
+ if (hasFinished)
578
+ this.scheduleExpiry(earliestExpiry);
579
+ else
580
+ this.clearExpiryTimer();
581
+ }
582
+ // Nothing to show — clear widget
583
+ if (!hasActive && !hasFinished) {
584
+ if (this.widgetRegistered) {
585
+ this.uiCtx.setWidget("agents", undefined);
586
+ this.widgetRegistered = false;
587
+ this.tui = undefined;
588
+ }
589
+ if (this.lastStatusText !== undefined) {
590
+ this.uiCtx.setStatus("subagents", undefined);
591
+ this.lastStatusText = undefined;
592
+ }
593
+ // Clean up stale entries
594
+ for (const [id] of this.finishedTurnAge) {
595
+ if (!allAgents.some(a => a.id === id))
596
+ this.finishedTurnAge.delete(id);
597
+ }
598
+ for (const [id] of this.finishedAt) {
599
+ if (!allAgents.some(a => a.id === id))
600
+ this.finishedAt.delete(id);
601
+ }
602
+ return;
603
+ }
604
+ // Status bar — only call setStatus when the text actually changes
605
+ let newStatusText;
606
+ if (hasActive) {
607
+ const statusParts = [];
608
+ if (runningCount > 0)
609
+ statusParts.push(`${runningCount} running`);
610
+ if (queuedCount > 0)
611
+ statusParts.push(`${queuedCount} queued`);
612
+ const total = runningCount + queuedCount;
613
+ newStatusText = `${statusParts.join(", ")} agent${total === 1 ? "" : "s"}`;
614
+ }
615
+ if (newStatusText !== this.lastStatusText) {
616
+ this.uiCtx.setStatus("subagents", newStatusText);
617
+ this.lastStatusText = newStatusText;
618
+ }
619
+ this.widgetFrame++;
620
+ // Register widget callback once; subsequent updates use requestRender()
621
+ // which re-invokes render() without replacing the component (avoids layout thrashing).
622
+ if (!this.widgetRegistered) {
623
+ this.uiCtx.setWidget("agents", (tui, theme) => {
624
+ this.tui = tui;
625
+ return {
626
+ render: () => this.renderWidget(tui, theme),
627
+ invalidate: () => {
628
+ // Theme changed — force re-registration so factory captures fresh theme.
629
+ this.widgetRegistered = false;
630
+ this.tui = undefined;
631
+ },
632
+ };
633
+ }, { placement: "aboveEditor" });
634
+ this.widgetRegistered = true;
635
+ }
636
+ else {
637
+ // Widget already registered — just request a re-render of existing components.
638
+ this.tui?.requestRender();
639
+ }
640
+ }
641
+ dispose() {
642
+ this.stopInterval();
643
+ this.clearExpiryTimer();
644
+ if (this.uiCtx) {
645
+ this.uiCtx.setWidget("agents", undefined);
646
+ this.uiCtx.setStatus("subagents", undefined);
647
+ }
648
+ this.widgetRegistered = false;
649
+ this.tui = undefined;
650
+ this.lastStatusText = undefined;
651
+ }
652
+ }