@timmyjl12/pi-subagents 0.20.0 → 0.21.1

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 (159) hide show
  1. package/CHANGELOG.md +862 -827
  2. package/README.md +1125 -1080
  3. package/dist/active-agents-prompt.d.ts +31 -9
  4. package/dist/active-agents-prompt.js +73 -9
  5. package/dist/agent-color.js +9 -1
  6. package/dist/agent-file-toggle.d.ts +1 -1
  7. package/dist/agent-manager.d.ts +405 -18
  8. package/dist/agent-manager.js +1661 -131
  9. package/dist/agent-runner.d.ts +45 -6
  10. package/dist/agent-runner.js +109 -18
  11. package/dist/agent-types.d.ts +30 -7
  12. package/dist/agent-types.js +38 -9
  13. package/dist/awaited-result.d.ts +37 -0
  14. package/dist/awaited-result.js +150 -0
  15. package/dist/child-session-shutdown.d.ts +19 -1
  16. package/dist/child-session-shutdown.js +60 -11
  17. package/dist/cleanup-plans.d.ts +10 -0
  18. package/dist/cleanup-plans.js +112 -0
  19. package/dist/cross-extension-rpc.d.ts +8 -1
  20. package/dist/cross-extension-rpc.js +59 -5
  21. package/dist/custom-agents.d.ts +34 -9
  22. package/dist/custom-agents.js +308 -111
  23. package/dist/default-agents.d.ts +1 -1
  24. package/dist/env.d.ts +1 -1
  25. package/dist/error-log.d.ts +6 -0
  26. package/dist/error-log.js +8 -0
  27. package/dist/force-main-model.d.ts +21 -0
  28. package/dist/force-main-model.js +28 -0
  29. package/dist/goal-bridge.d.ts +155 -0
  30. package/dist/goal-bridge.js +305 -0
  31. package/dist/group-join.d.ts +5 -1
  32. package/dist/group-join.js +52 -7
  33. package/dist/index.d.ts +5 -5
  34. package/dist/index.js +2827 -333
  35. package/dist/invocation-config.d.ts +30 -3
  36. package/dist/invocation-config.js +30 -1
  37. package/dist/memory.d.ts +1 -1
  38. package/dist/mention-clone.d.ts +1 -1
  39. package/dist/model-scope.d.ts +1 -1
  40. package/dist/nested-tools.d.ts +22 -1
  41. package/dist/nested-tools.js +120 -26
  42. package/dist/output-file.d.ts +15 -4
  43. package/dist/output-file.js +146 -43
  44. package/dist/prompts.d.ts +1 -1
  45. package/dist/recovery.d.ts +1 -1
  46. package/dist/report-cleanup.d.ts +204 -0
  47. package/dist/report-cleanup.js +1632 -0
  48. package/dist/report-store.d.ts +738 -0
  49. package/dist/report-store.js +3616 -0
  50. package/dist/schedule-store.d.ts +14 -6
  51. package/dist/schedule-store.js +88 -58
  52. package/dist/schedule.d.ts +20 -8
  53. package/dist/schedule.js +135 -74
  54. package/dist/settings.d.ts +39 -11
  55. package/dist/settings.js +22 -5
  56. package/dist/status-note.d.ts +1 -1
  57. package/dist/structured-output.d.ts +1 -1
  58. package/dist/types.d.ts +32 -3
  59. package/dist/ui/agent-mention.d.ts +2 -2
  60. package/dist/ui/agent-widget.d.ts +82 -13
  61. package/dist/ui/agent-widget.js +155 -37
  62. package/dist/ui/cleanup-preview.d.ts +59 -0
  63. package/dist/ui/cleanup-preview.js +466 -0
  64. package/dist/ui/conversation-viewer.d.ts +4 -4
  65. package/dist/ui/conversation-viewer.js +10 -6
  66. package/dist/ui/fleet-list.d.ts +3 -3
  67. package/dist/ui/fleet-list.js +3 -3
  68. package/dist/ui/fleet-overlay.d.ts +37 -6
  69. package/dist/ui/fleet-overlay.js +214 -18
  70. package/dist/ui/hub-feed.d.ts +52 -0
  71. package/dist/ui/hub-feed.js +148 -0
  72. package/dist/ui/native-transcript.js +5 -1
  73. package/dist/ui/schedule-menu.d.ts +1 -1
  74. package/dist/ui/schedule-menu.js +1 -1
  75. package/dist/ui/workflow-card.d.ts +4 -4
  76. package/dist/ui/workflow-dialog.d.ts +4 -4
  77. package/dist/ui/workflow-dialog.js +8 -3
  78. package/dist/ui/workflow-menu.d.ts +2 -2
  79. package/dist/usage.d.ts +12 -0
  80. package/dist/usage.js +28 -1
  81. package/dist/workflow/entry.d.ts +3 -3
  82. package/dist/workflow/host.d.ts +7 -4
  83. package/dist/workflow/host.js +162 -48
  84. package/dist/workflow/journal.d.ts +23 -7
  85. package/dist/workflow/journal.js +80 -23
  86. package/dist/workflow/progress.d.ts +1 -1
  87. package/dist/workflow/runtime.d.ts +45 -6
  88. package/dist/workflow/runtime.js +105 -16
  89. package/dist/workflow/task.d.ts +13 -4
  90. package/dist/workflow/task.js +7 -1
  91. package/dist/workflow/tool-description.d.ts +7 -2
  92. package/dist/workflow/tool-description.js +10 -5
  93. package/docs/{FORK.md → DEVELOPMENT.md} +4 -4
  94. package/docs/artifacts.md +93 -0
  95. package/docs/rpc.md +252 -189
  96. package/docs/runtime-performance.md +53 -0
  97. package/docs/workflows.md +48 -18
  98. package/examples/agent-tool-description.md +2 -2
  99. package/examples/workflows/review-panel.js +6 -3
  100. package/package.json +5 -5
  101. package/src/active-agents-prompt.ts +115 -39
  102. package/src/agent-color.ts +10 -2
  103. package/src/agent-file-toggle.ts +2 -2
  104. package/src/agent-manager.ts +3312 -1601
  105. package/src/agent-runner.ts +164 -36
  106. package/src/agent-types.ts +56 -11
  107. package/src/awaited-result.ts +187 -0
  108. package/src/child-session-shutdown.ts +114 -46
  109. package/src/cleanup-plans.ts +112 -0
  110. package/src/cross-extension-rpc.ts +68 -9
  111. package/src/custom-agents.ts +384 -112
  112. package/src/default-agents.ts +1 -1
  113. package/src/enabled-models.ts +1 -1
  114. package/src/env.ts +1 -1
  115. package/src/error-log.ts +10 -1
  116. package/src/force-main-model.ts +29 -0
  117. package/src/goal-bridge.ts +468 -0
  118. package/src/group-join.ts +56 -9
  119. package/src/index.ts +2987 -349
  120. package/src/invocation-config.ts +50 -4
  121. package/src/memory.ts +1 -1
  122. package/src/mention-clone.ts +3 -3
  123. package/src/model-scope.ts +1 -1
  124. package/src/nested-tools.ts +164 -33
  125. package/src/output-file.ts +168 -46
  126. package/src/prompts.ts +1 -1
  127. package/src/recovery.ts +2 -2
  128. package/src/report-cleanup.ts +2044 -0
  129. package/src/report-store.ts +4133 -0
  130. package/src/schedule-store.ts +244 -201
  131. package/src/schedule.ts +144 -80
  132. package/src/settings.ts +61 -16
  133. package/src/skill-loader.ts +1 -1
  134. package/src/standalone-fallback.ts +2 -2
  135. package/src/status-note.ts +1 -1
  136. package/src/structured-output.ts +1 -1
  137. package/src/types.ts +33 -3
  138. package/src/ui/agent-mention.ts +3 -3
  139. package/src/ui/agent-widget.ts +179 -45
  140. package/src/ui/cleanup-preview.ts +518 -0
  141. package/src/ui/conversation-viewer.ts +19 -15
  142. package/src/ui/fleet-list.ts +7 -7
  143. package/src/ui/fleet-overlay.ts +1048 -847
  144. package/src/ui/hub-feed.ts +179 -0
  145. package/src/ui/native-transcript.ts +7 -3
  146. package/src/ui/schedule-menu.ts +4 -4
  147. package/src/ui/workflow-card.ts +4 -4
  148. package/src/ui/workflow-dialog.ts +10 -6
  149. package/src/ui/workflow-menu.ts +4 -4
  150. package/src/usage.ts +53 -3
  151. package/src/workflow/collisions.ts +1 -1
  152. package/src/workflow/entry.ts +3 -3
  153. package/src/workflow/host.ts +174 -54
  154. package/src/workflow/journal.ts +80 -23
  155. package/src/workflow/progress.ts +1 -1
  156. package/src/workflow/runtime.ts +146 -23
  157. package/src/workflow/saved.ts +3 -3
  158. package/src/workflow/task.ts +18 -7
  159. package/src/workflow/tool-description.ts +10 -5
@@ -1,847 +1,1048 @@
1
- /**
2
- * fleet-overlay.ts — model-picker-style two-pane fleet overlay.
3
- *
4
- * The full-screen counterpart to the below-editor FleetView list
5
- * (`fleet-list.ts`, which stays the compact glanceable surface). Frame, top to
6
- * bottom:
7
- *
8
- * ```
9
- * ╭─ Subagents ─────────────────── 9 agents · 4 workflows ─╮
10
- * │ │
11
- * ├─ Fleet ────────────────┬───────────────────────────────┤
12
- * │ ▾ Running 2 │ ● general-purpose │
13
- * │ ❯ ● general-purpose … │ Sleep then report 2 │
14
- * │ ● Explore find thing│ ───────── │
15
- * │ ▾ Failed 1 │ Type general-purpose │
16
- * │ ▾ Completed 1 │ Status running │
17
- * │ │ Model provider/model │
18
- * ├────────────────────────┴───────────────────────────────┤
19
- * │ ↑↓ move · enter open · d dismiss · esc close │
20
- * ╰────────────────────────────────────────────────────────╯
21
- * ```
22
- *
23
- * Left pane: the complete session roster — running, paused, failed and
24
- * completed runs, grouped into sections (headers are display-only, the cursor
25
- * skips them). Unlike the widget, completed/failed agents do not drop out after
26
- * a few seconds; rows live until the manager sweeps settled records (~10
27
- * minutes after settle — see agent-manager.ts `cleanup()`), matching the
28
- * retention the workflow dialog already documents. The manager is untouched:
29
- * dismissal from this list (`d`) is an overlay-local view filter.
30
- *
31
- * Right pane: a detail card for the selected entry — type, description, status,
32
- * model, thinking, elapsed, tokens, cost (when the `showCost` setting is on),
33
- * and a short activity/result tail. Enter opens the existing full surface for
34
- * the entry — the conversation overlay for an agent, the workflow inspector for
35
- * a run — stacked over this one; Esc there returns here.
36
- *
37
- * Narrow terminals (below {@link TWO_PANE_MIN_WIDTH} columns) drop the left
38
- * pane entirely: the detail card renders full width and carries a position
39
- * marker (`3 of 9`), so the roster is still navigable by ↑/↓ without ever
40
- * seeing the list — the same trade the model picker makes for its facet pane.
41
- *
42
- * Frame geometry mirrors the model picker's discipline (pi-model-picker
43
- * src/picker.ts): a fixed chrome budget around one body, a target height of a
44
- * fraction of the terminal capped at `rows - 2`, and an internal render floor
45
- * of {@link MIN_RENDER_WIDTH} columns with narrower requests clipped back — so
46
- * the frame never exceeds terminal width or height. Rendering uses pi-tui
47
- * primitives and the structural widget `Theme` (fg/bold) only — no sibling
48
- * imports, no hardcoded colors.
49
- */
50
-
51
- import { type Component, type Focusable, isKeyRelease, type KeyId, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
52
- import { formatAdvisorLastReview, formatAdvisorState } from "../advisor-status.js";
53
- import { hasAgentBadge, renderAgentName } from "../agent-color.js";
54
- import { isTopLevelAgent } from "../agent-manager.js";
55
- import type { AgentRecord } from "../types.js";
56
- import { getLifetimeCost, getLifetimeTotal } from "../usage.js";
57
- import { type AgentActivity, buildInvocationTags, describeActivity, formatCost, type Theme } from "./agent-widget.js";
58
- import { type FleetWorkflow, formatFleetElapsed, formatFleetTokens } from "./fleet-list.js";
59
-
60
- // ─── geometry ────────────────────────────────────────────────────────────────
61
-
62
- /**
63
- * Rows outside the body pane: top rule, blank, split opener, split closer,
64
- * footer hints, bottom rule.
65
- */
66
- const CHROME_ROWS = 6;
67
- /** Fraction of the terminal the overlay targets, below the host's maxHeight cap. */
68
- const HEIGHT_FRACTION = 0.88;
69
- /** Smallest body the frame will render. */
70
- const MIN_BODY_ROWS = 1;
71
- /** Below this the left pane is dropped and the detail card runs full width. */
72
- export const TWO_PANE_MIN_WIDTH = 72;
73
- const MIN_LEFT_WIDTH = 24;
74
- const MAX_LEFT_WIDTH = 36;
75
- /**
76
- * Internal rendering floor. A narrower request is laid out at this width and
77
- * clipped back, so the layout arithmetic never degenerates.
78
- */
79
- export const MIN_RENDER_WIDTH = 40;
80
- /** Re-render cadence so elapsed/token stats tick while agents run. */
81
- const TICK_MS = 250;
82
- /** Activity/result lines shown at the bottom of the detail card. */
83
- const MAX_TAIL_LINES = 3;
84
-
85
- /**
86
- * Total frame height for a terminal of `terminalRows`, including chrome.
87
- * Mirrored from the model picker's guard: capped at `rows - 2` so the frame is
88
- * never clipped by the overlay host, floored at one body row so the layout math
89
- * always has somewhere to draw.
90
- */
91
- export function overlayHeightFor(terminalRows: number): number {
92
- const rows = Number.isFinite(terminalRows) && terminalRows > 0 ? Math.floor(terminalRows) : 40;
93
- const smallest = CHROME_ROWS + MIN_BODY_ROWS;
94
- return Math.max(smallest, Math.min(Math.floor(rows * HEIGHT_FRACTION), rows - 2));
95
- }
96
-
97
- interface Layout {
98
- readonly width: number;
99
- readonly height: number;
100
- readonly twoPane: boolean;
101
- readonly leftWidth: number;
102
- readonly bodyHeight: number;
103
- /** Content width inside the right pane. */
104
- readonly bodyWidth: number;
105
- }
106
-
107
- // ─── glyphs ──────────────────────────────────────────────────────────────────
108
-
109
- interface Glyphs {
110
- /** Marks the highlighted roster row. */
111
- readonly cursor: string;
112
- /** Status dot; the section color carries the meaning. */
113
- readonly bullet: string;
114
- /** Section header prefix. */
115
- readonly group: string;
116
- }
117
-
118
- const UNICODE_GLYPHS: Glyphs = { cursor: "❯", bullet: "●", group: "▾" };
119
- const ASCII_GLYPHS: Glyphs = { cursor: ">", bullet: "*", group: "v" };
120
-
121
- /**
122
- * Resolve the glyph set. Set `PI_SUBAGENTS_GLYPHS=ascii` for terminals where
123
- * ambiguous-width glyphs render two cells wide and shift the frame. Box-drawing
124
- * frame characters stay — they are single-width in virtually all terminals;
125
- * only the label glyphs shift.
126
- */
127
- function resolveGlyphs(): Glyphs {
128
- return process.env.PI_SUBAGENTS_GLYPHS?.trim().toLowerCase() === "ascii" ? ASCII_GLYPHS : UNICODE_GLYPHS;
129
- }
130
-
131
- // ─── frame drawing (pi's dialog chrome, reproduced locally) ─────────────────
132
-
133
- const BOX = {
134
- topLeft: "╭",
135
- topRight: "╮",
136
- bottomLeft: "╰",
137
- bottomRight: "╯",
138
- horizontal: "─",
139
- vertical: "│",
140
- teeDown: "┬",
141
- teeUp: "┴",
142
- teeRight: "├",
143
- teeLeft: "┤",
144
- } as const;
145
-
146
- /** Left/right inset between a vertical border and its content. */
147
- const INSET = 1;
148
-
149
- /** Force `text` to exactly `width` columns: truncate with ellipsis, else pad. ANSI-aware. */
150
- function fitText(text: string, width: number): string {
151
- if (width <= 0) return "";
152
- const measured = visibleWidth(text);
153
- if (measured > width) {
154
- const clipped = truncateToWidth(text, width);
155
- const clippedWidth = visibleWidth(clipped);
156
- return clippedWidth < width ? clipped + " ".repeat(width - clippedWidth) : clipped;
157
- }
158
- return measured === width ? text : text + " ".repeat(width - measured);
159
- }
160
-
161
- /** Trim `text` to at most `width` columns without padding. */
162
- function clip(text: string, width: number): string {
163
- return width <= 0 ? "" : truncateToWidth(text, width);
164
- }
165
-
166
- /** Place `right` flush to `width`, truncating `left` first so the stats survive. */
167
- function rightAlign(left: string, right: string, width: number): string {
168
- const rightWidth = visibleWidth(right);
169
- const maxLeft = Math.max(0, width - rightWidth - 1);
170
- const leftClamped = clip(left, maxLeft);
171
- const gap = Math.max(1, width - visibleWidth(leftClamped) - rightWidth);
172
- return fitText(leftClamped + " ".repeat(gap) + right, width);
173
- }
174
-
175
- /** A dim `key` + muted `description` pair for the footer hint row. */
176
- function keyHint(theme: Theme, key: string, description: string): string {
177
- return theme.fg("dim", key) + theme.fg("muted", ` ${description}`);
178
- }
179
-
180
- /** Titled top rule: `╭─ Subagents ─────── right ─╮`. Right label is budgeted first. */
181
- function topRule(theme: Theme, width: number, title: string, right: string): string {
182
- const bar = (s: string) => theme.fg("border", s);
183
- const inner = Math.max(0, width - 2);
184
- if (inner <= 1) return bar(BOX.topLeft + BOX.horizontal.repeat(inner) + BOX.topRight);
185
-
186
- const rule = inner - 1; // columns for title + filler + right label
187
- const rightShown = right ? clip(` ${right} `, Math.max(0, Math.floor(rule * 0.4))) : "";
188
- const rightWidth = visibleWidth(rightShown);
189
- const rightBlock = rightShown.length > 0 ? rightWidth + 1 : 0;
190
-
191
- const titleShown = title ? clip(` ${title} `, Math.max(0, rule - rightBlock)) : "";
192
- const titleWidth = visibleWidth(titleShown);
193
- const fill = Math.max(0, rule - titleWidth - rightBlock);
194
-
195
- let line = bar(BOX.topLeft + BOX.horizontal);
196
- if (titleWidth > 0) line += theme.bold(theme.fg("accent", titleShown));
197
- line += bar(BOX.horizontal.repeat(fill));
198
- if (rightShown.length > 0) line += bar(BOX.horizontal) + theme.fg("dim", rightShown);
199
- return line + bar(BOX.topRight);
200
- }
201
-
202
- /** Full-width interior rule: `├────┤`. */
203
- function divider(theme: Theme, width: number): string {
204
- return (
205
- theme.fg("border", BOX.teeRight) +
206
- theme.fg("border", BOX.horizontal.repeat(Math.max(0, width - 2))) +
207
- theme.fg("border", BOX.teeLeft)
208
- );
209
- }
210
-
211
- /** Closing rule: `╰────╯`. */
212
- function bottomRule(theme: Theme, width: number): string {
213
- return (
214
- theme.fg("border", BOX.bottomLeft) +
215
- theme.fg("border", BOX.horizontal.repeat(Math.max(0, width - 2))) +
216
- theme.fg("border", BOX.bottomRight)
217
- );
218
- }
219
-
220
- /** `│ content │` with one column of inset on each side; exact width. */
221
- function contentRow(theme: Theme, content: string, width: number): string {
222
- const budget = width - 2 * (INSET + 1);
223
- const bar = theme.fg("border", BOX.vertical);
224
- if (budget <= 0) return bar + bar;
225
- return `${bar} ${fitText(content, budget)} ${bar}`;
226
- }
227
-
228
- /** Left/right rule lengths for an interior split rule over the pane divider. */
229
- function splitArms(width: number, leftWidth: number): { left: number; right: number } {
230
- const dividerColumn = leftWidth + INSET + 1 + INSET;
231
- return { left: Math.max(0, dividerColumn - 1), right: Math.max(0, width - 2 - dividerColumn) };
232
- }
233
-
234
- /** Rule opening the two-pane region, splitting over the divider: `├─ Fleet ──┬───┤`. */
235
- function openSplit(theme: Theme, width: number, title: string, leftWidth: number): string {
236
- const { left, right } = splitArms(width, leftWidth);
237
- let head: string;
238
- if (!title || left <= 1) {
239
- head = theme.fg("border", BOX.teeRight + BOX.horizontal.repeat(left));
240
- } else {
241
- const shown = clip(` ${title} `, Math.max(0, left - 1));
242
- head =
243
- theme.fg("border", BOX.teeRight + BOX.horizontal) +
244
- theme.bold(theme.fg("accent", shown)) +
245
- theme.fg("border", BOX.horizontal.repeat(Math.max(0, left - 1 - visibleWidth(shown))));
246
- }
247
- return (
248
- head + theme.fg("border", BOX.teeDown + BOX.horizontal.repeat(right) + BOX.teeLeft)
249
- );
250
- }
251
-
252
- /** Closing rule of the two-pane region: `├─────┴────┤`. */
253
- function closeSplit(theme: Theme, width: number, leftWidth: number): string {
254
- const { left, right } = splitArms(width, leftWidth);
255
- return theme.fg(
256
- "border",
257
- BOX.teeRight + BOX.horizontal.repeat(left) + BOX.teeUp + BOX.horizontal.repeat(right) + BOX.teeLeft,
258
- );
259
- }
260
-
261
- /** Right-pane content budget for a two-pane layout of `width`. */
262
- function bodyWidthFor(width: number, leftWidth: number): number {
263
- // Fixed overhead: `│ ` + ` │ ` + ` │` = 4 * INSET + 3.
264
- return Math.max(0, width - leftWidth - (4 * INSET + 3));
265
- }
266
-
267
- /** `│ left │ body │`, each pane padded to its exact budget. */
268
- function splitRow(theme: Theme, left: string, body: string, width: number, leftWidth: number): string {
269
- const bodyBudget = bodyWidthFor(width, leftWidth);
270
- const bar = theme.fg("border", BOX.vertical);
271
- if (bodyBudget <= 0) return bar + bar;
272
- return `${bar} ${fitText(left, leftWidth)} ${bar} ${fitText(body, bodyBudget)} ${bar}`;
273
- }
274
-
275
- // ─── roster model ────────────────────────────────────────────────────────────
276
-
277
- type SectionId = "running" | "paused" | "failed" | "completed";
278
-
279
- interface Section {
280
- readonly id: SectionId;
281
- readonly label: string;
282
- /** Theme color for the section header and every status dot in it. */
283
- readonly color: string;
284
- }
285
-
286
- /** Fixed display order: actionable first, history at the bottom. */
287
- const SECTIONS: readonly Section[] = [
288
- { id: "running", label: "Running", color: "accent" },
289
- { id: "paused", label: "Paused", color: "warning" },
290
- { id: "failed", label: "Failed", color: "error" },
291
- { id: "completed", label: "Completed", color: "success" },
292
- ];
293
-
294
- function sectionOfAgent(record: AgentRecord): SectionId {
295
- if (record.status === "running" || record.status === "queued") return "running";
296
- // aborted (user/tool cut) and stopped (manual halt) read as failures next to
297
- // error; steered is a completed run that happened to be redirected along the
298
- // way, so it settles into the success group.
299
- if (record.status === "error" || record.status === "aborted" || record.status === "stopped") return "failed";
300
- return "completed";
301
- }
302
-
303
- function sectionOfWorkflow(run: FleetWorkflow): SectionId {
304
- if (run.status === "running") return "running";
305
- if (run.status === "paused") return "paused";
306
- if (run.status === "failed" || run.status === "killed") return "failed";
307
- return "completed";
308
- }
309
-
310
- export type RosterEntry =
311
- | { readonly kind: "workflow"; readonly workflow: FleetWorkflow }
312
- | { readonly kind: "agent"; readonly record: AgentRecord };
313
-
314
- function entryKey(entry: RosterEntry): string {
315
- return entry.kind === "agent" ? `agent:${entry.record.id}` : `workflow:${entry.workflow.id}`;
316
- }
317
-
318
- interface SectionRow {
319
- readonly kind: "section";
320
- readonly key: string;
321
- readonly section: Section;
322
- readonly count: number;
323
- }
324
-
325
- interface EntryRow {
326
- readonly kind: "entry";
327
- readonly key: string;
328
- readonly entry: RosterEntry;
329
- }
330
-
331
- type Row = SectionRow | EntryRow;
332
-
333
- /** What the overlay reads from the host; every source is pulled live per render. */
334
- export interface FleetOverlayDeps {
335
- /** Render pump; the real pi `TUI` satisfies this structurally. */
336
- readonly tui: { requestRender(): void; terminal: { rows: number; columns: number } };
337
- readonly theme: Theme;
338
- /**
339
- * Top-level agent records for the session; read on every render. Records
340
- * without a session are filtered here (nothing to open behind them) — they
341
- * are typically queued and row into view once they start.
342
- */
343
- readonly records: () => AgentRecord[];
344
- /** Workflow runs as the fleet list sees them. */
345
- readonly workflows: () => readonly FleetWorkflow[];
346
- /** Live activity per running agent id, for the detail card's tail. */
347
- readonly activity: ReadonlyMap<string, AgentActivity>;
348
- /** Whether the detail card shows an estimated cost. Read per render. */
349
- readonly showCost: () => boolean;
350
- /** Opens the full conversation overlay for an agent, stacked over this one. */
351
- readonly openAgent: (record: AgentRecord) => Promise<void> | void;
352
- /** Opens the workflow inspector for a run, stacked over this one. */
353
- readonly openWorkflow: (id: string) => Promise<void> | void;
354
- readonly done: (result: undefined) => void;
355
- readonly notify?: (message: string, type?: "info" | "warning" | "error") => void;
356
- }
357
-
358
- /**
359
- * The fleet overlay. See the file header for the frame layout and the
360
- * roster → detail navigation model.
361
- */
362
- export class FleetOverlay implements Component, Focusable {
363
- private readonly deps: FleetOverlayDeps;
364
- private readonly theme: Theme;
365
- private readonly glyphs: Glyphs;
366
-
367
- /** `agent:<id>` / `workflow:<id>` of the highlighted row — key, never index. */
368
- private selectedKey = "";
369
- /** Fallback position when the keyed row is gone; the nearest survivor keeps the cursor. */
370
- private selectedIndex = 0;
371
- private windowStart = 0;
372
- /** Settled rows the user dismissed from this view; overlay-local, manager untouched. */
373
- private readonly dismissed = new Set<string>();
374
-
375
- private closed = false;
376
- private layout: Layout | undefined;
377
- private readonly timer: ReturnType<typeof setInterval>;
378
-
379
- // Focusable: no embedded editor/IME, so the flag is a plain holder.
380
- private focusedFlag = false;
381
-
382
- constructor(deps: FleetOverlayDeps) {
383
- this.deps = deps;
384
- this.theme = deps.theme;
385
- this.glyphs = resolveGlyphs();
386
- // Tick keeps elapsed/token stats live while anything is running; the roster
387
- // itself is rebuilt on every render, so this only needs to re-render.
388
- this.timer = setInterval(() => {
389
- if (!this.closed) this.deps.tui.requestRender();
390
- }, TICK_MS);
391
- (this.timer as { unref?: () => void }).unref?.();
392
- }
393
-
394
- get focused(): boolean {
395
- return this.focusedFlag;
396
- }
397
-
398
- set focused(value: boolean) {
399
- this.focusedFlag = value;
400
- }
401
-
402
- // ── roster ───────────────────────────────────────────────────────────
403
-
404
- /**
405
- * The full session roster. No linger cutoff — that window is the widget's
406
- * glance behavior, not a property of the records; the manager keeps settled
407
- * records long enough (~10 min) for this list to read as history.
408
- */
409
- private agentRecords(): AgentRecord[] {
410
- return this.deps.records().filter(record => isTopLevelAgent(record) && record.session !== undefined);
411
- }
412
-
413
- /** Flat row list: section headers interleaved, entries newest-first within. */
414
- private buildRows(): Row[] {
415
- const agents = this.agentRecords();
416
- const runs = this.deps.workflows().filter(run => !this.dismissed.has(`workflow:${run.id}`));
417
- const rows: Row[] = [];
418
-
419
- for (const section of SECTIONS) {
420
- const sectionRuns = runs
421
- .filter(run => sectionOfWorkflow(run) === section.id)
422
- .sort((a, b) => b.startedAt - a.startedAt);
423
- const sectionAgents = agents
424
- .filter(record => sectionOfAgent(record) === section.id && !this.dismissed.has(`agent:${record.id}`))
425
- .sort((a, b) => b.startedAt - a.startedAt);
426
- const entries: RosterEntry[] = [
427
- // Runs sit above agents, as in the widget: a run owns most of the
428
- // agents that would otherwise crowd the same section.
429
- ...sectionRuns.map(workflow => ({ kind: "workflow" as const, workflow })),
430
- ...sectionAgents.map(record => ({ kind: "agent" as const, record })),
431
- ];
432
- if (entries.length === 0) continue;
433
- rows.push({ kind: "section", key: `section:${section.id}`, section, count: entries.length });
434
- for (const entry of entries) rows.push({ kind: "entry", key: entryKey(entry), entry });
435
- }
436
- return rows;
437
- }
438
-
439
- private entriesOf(rows: Row[]): EntryRow[] {
440
- return rows.filter((row): row is EntryRow => row.kind === "entry");
441
- }
442
-
443
- /** Re-seat the selection on the same key; a removed row falls to the nearest survivor. */
444
- private reconcile(rows: Row[]): EntryRow[] {
445
- const entries = this.entriesOf(rows);
446
- if (entries.length === 0) {
447
- this.selectedKey = "";
448
- this.selectedIndex = 0;
449
- return entries;
450
- }
451
- const found = entries.findIndex(row => row.key === this.selectedKey);
452
- this.selectedIndex = found >= 0 ? found : Math.max(0, Math.min(this.selectedIndex, entries.length - 1));
453
- this.selectedKey = entries[this.selectedIndex].key;
454
- return entries;
455
- }
456
-
457
- private selectedEntry(rows: Row[]): RosterEntry | undefined {
458
- return this.entriesOf(rows)[this.selectedIndex]?.entry;
459
- }
460
-
461
- private move(delta: number, wrap: boolean, entries: EntryRow[]): void {
462
- const total = entries.length;
463
- if (total === 0) return;
464
- const next = wrap
465
- ? ((this.selectedIndex + delta) % total + total) % total
466
- : Math.max(0, Math.min(this.selectedIndex + delta, total - 1));
467
- this.selectedIndex = next;
468
- this.selectedKey = entries[next].key;
469
- }
470
-
471
- /** Pan the roster window so the highlighted entry's row is inside it. */
472
- private ensureSelectionVisible(rows: Row[]): void {
473
- const visible = this.layout?.bodyHeight ?? 10;
474
- const maxStart = Math.max(0, rows.length - visible);
475
- this.windowStart = Math.max(0, Math.min(this.windowStart, maxStart));
476
- if (!this.selectedKey) return;
477
- const rowIndex = rows.findIndex(row => row.kind === "entry" && row.key === this.selectedKey);
478
- if (rowIndex < 0) return;
479
- if (rowIndex < this.windowStart) this.windowStart = rowIndex;
480
- else if (rowIndex >= this.windowStart + visible) this.windowStart = rowIndex - visible + 1;
481
- this.windowStart = Math.max(0, Math.min(this.windowStart, maxStart));
482
- }
483
-
484
- // ── actions ──────────────────────────────────────────────────────────────
485
-
486
- /**
487
- * Hand control back to the caller, which closes and disposes the overlay.
488
- * Same done semantics as the conversation viewer: resolve with `undefined`.
489
- */
490
- private finish(): void {
491
- this.dispose();
492
- this.deps.done(undefined);
493
- }
494
-
495
- /** After a stacked view closes: put the cursor back on the entry it came from. */
496
- private afterStackedClose(key: string): void {
497
- if (this.closed) return;
498
- this.selectedKey = key;
499
- this.deps.tui.requestRender();
500
- }
501
-
502
- private activate(rows: Row[]): void {
503
- const entry = this.selectedEntry(rows);
504
- if (!entry) return;
505
- if (entry.kind === "workflow") {
506
- const id = entry.workflow.id;
507
- void Promise.resolve(this.deps.openWorkflow(id)).then(
508
- () => this.afterStackedClose(`workflow:${id}`),
509
- error => this.deps.notify?.(`Could not open the run: ${errorMessage(error)}`, "error"),
510
- );
511
- return;
512
- }
513
- const record = entry.record;
514
- // The roster filters to records with sessions, so this is only reachable
515
- // when the session was detached between render and keypress.
516
- if (!record.session) {
517
- this.deps.notify?.(`Agent is ${record.status} — no session available.`, "info");
518
- return;
519
- }
520
- void Promise.resolve(this.deps.openAgent(record)).then(
521
- () => this.afterStackedClose(`agent:${record.id}`),
522
- error => this.deps.notify?.(`Could not open the conversation: ${errorMessage(error)}`, "error"),
523
- );
524
- }
525
-
526
- /** Remove the selected settled row from this view. Running work is not dismissible. */
527
- private dismissSelected(rows: Row[]): void {
528
- const entry = this.selectedEntry(rows);
529
- if (!entry) return;
530
- const section = entry.kind === "workflow" ? sectionOfWorkflow(entry.workflow) : sectionOfAgent(entry.record);
531
- if (section === "running" || section === "paused") return;
532
- this.dismissed.add(entryKey(entry));
533
- this.deps.tui.requestRender();
534
- }
535
-
536
- // ── input ──────────────────────────────────────────────────────────────
537
-
538
- handleInput(data: string): void {
539
- if (this.closed || isKeyRelease(data)) return;
540
-
541
- if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
542
- this.finish();
543
- return;
544
- }
545
-
546
- const rows = this.buildRows();
547
- const entries = this.reconcile(rows);
548
- const page = Math.max(1, (this.layout?.bodyHeight ?? 10) - 1);
549
-
550
- const movements: ReadonlyArray<{ keys: readonly KeyId[]; delta: number; wrap: boolean }> = [
551
- { keys: ["up"], delta: -1, wrap: true },
552
- { keys: ["down"], delta: 1, wrap: true },
553
- { keys: ["pageUp"], delta: -page, wrap: false },
554
- { keys: ["pageDown"], delta: page, wrap: false },
555
- { keys: ["home"], delta: -Number.MAX_SAFE_INTEGER, wrap: false },
556
- { keys: ["end"], delta: Number.MAX_SAFE_INTEGER, wrap: false },
557
- ];
558
- for (const movement of movements) {
559
- if (!movement.keys.some(key => matchesKey(data, key))) continue;
560
- this.move(movement.delta, movement.wrap, entries);
561
- this.deps.tui.requestRender();
562
- return;
563
- }
564
-
565
- if (matchesKey(data, "enter") || matchesKey(data, "return")) {
566
- this.activate(rows);
567
- this.deps.tui.requestRender();
568
- return;
569
- }
570
- if (matchesKey(data, "d")) {
571
- this.dismissSelected(rows);
572
- this.deps.tui.requestRender();
573
- return;
574
- }
575
- }
576
-
577
- // ── layout ────────────────────────────────────────────────────────────
578
-
579
- private terminalRows(): number {
580
- const rows = this.deps.tui.terminal?.rows ?? 40;
581
- return Number.isFinite(rows) && rows > 12 ? Math.floor(rows) : 40;
582
- }
583
-
584
- private layoutFor(width: number): Layout {
585
- const height = overlayHeightFor(this.terminalRows());
586
- const cached = this.layout;
587
- if (cached && cached.height === height && cached.width === width) return cached;
588
- const twoPane = width >= TWO_PANE_MIN_WIDTH;
589
- const leftWidth = twoPane
590
- ? Math.max(MIN_LEFT_WIDTH, Math.min(MAX_LEFT_WIDTH, Math.round(width * 0.28), width - 46))
591
- : 0;
592
- const layout: Layout = {
593
- width,
594
- height,
595
- twoPane,
596
- leftWidth,
597
- bodyHeight: Math.max(MIN_BODY_ROWS, height - CHROME_ROWS),
598
- bodyWidth: twoPane ? bodyWidthFor(width, leftWidth) : width - 2 * (INSET + 1),
599
- };
600
- this.layout = layout;
601
- return layout;
602
- }
603
-
604
- // ── row rendering ─────────────────────────────────────────────────────
605
-
606
- private renderSectionRow(row: SectionRow, width: number): string {
607
- const head =
608
- this.theme.fg(row.section.color, this.glyphs.group) + " " + this.theme.bold(this.theme.fg("muted", row.section.label));
609
- return fitText(`${head} ${this.theme.fg("dim", String(row.count))}`, width);
610
- }
611
-
612
- private renderEntryRow(row: EntryRow, width: number): string {
613
- const entry = row.entry;
614
- const selected = row.key === this.selectedKey;
615
- const section = entry.kind === "workflow" ? sectionOfWorkflow(entry.workflow) : sectionOfAgent(entry.record);
616
- const sectionColor = (SECTIONS.find(s => s.id === section) ?? SECTIONS[0]).color;
617
-
618
- const cursor = selected ? `${this.theme.fg("accent", this.glyphs.cursor)} ` : " ";
619
- const dot = this.theme.fg(sectionColor, this.glyphs.bullet);
620
-
621
- let head: string;
622
- let stats: string;
623
- if (entry.kind === "workflow") {
624
- const run = entry.workflow;
625
- const kind = this.theme.fg(selected ? "text" : "muted", "workflow");
626
- const name = selected ? this.theme.fg("text", run.name) : run.name;
627
- head = `${cursor}${dot} ${kind} ${name}`;
628
- const elapsed = (run.completedAt ?? Date.now()) - run.startedAt;
629
- const agents = `${run.doneCount}/${run.totalCount} agent${run.totalCount === 1 ? "" : "s"}`;
630
- stats = `${agents} · ${formatFleetElapsed(elapsed)} · ${formatFleetTokens(run.tokens)}`;
631
- } else {
632
- const record = entry.record;
633
- const name = renderAgentName(record.type, this.theme, selected
634
- ? { fallbackColor: "text", bold: hasAgentBadge(record.type) }
635
- : { fallbackColor: "muted" });
636
- const description = selected ? this.theme.fg("text", record.description) : record.description;
637
- head = `${cursor}${dot} ${name} ${description}`;
638
- const elapsed = formatFleetElapsed((record.completedAt ?? Date.now()) - record.startedAt);
639
- const tokens = formatFleetTokens(getLifetimeTotal(record.lifetimeUsage));
640
- const cost = this.deps.showCost() ? formatCost(getLifetimeCost(record.lifetimeUsage)) : "";
641
- stats = `${elapsed} · ${tokens}${cost ? ` · ${cost}` : ""}`;
642
- }
643
-
644
- // A pane too narrow for the stats column shows the identity only; the
645
- // detail card next to it carries the numbers.
646
- if (width - visibleWidth(head) >= visibleWidth(stats) + 2 && width >= 30) {
647
- return rightAlign(head, this.theme.fg(selected ? "text" : "dim", stats), width);
648
- }
649
- return fitText(head, width);
650
- }
651
-
652
- // ── detail card (right pane) ─────────────────────────────────────────────
653
-
654
- /** One ` Label value` row, already styled, never wider than `width`. */
655
- private field(label: string, value: string, width: number): string {
656
- return clip(` ${this.theme.fg("dim", label.padEnd(12))}${value}`, width);
657
- }
658
-
659
- /**
660
- * The tail of what an agent just did or said: the live activity line while it
661
- * works, the final answer once it settles, the message when it errored.
662
- * Workflows have no per-run prose feed — the progress counters above carry it.
663
- */
664
- private agentTail(record: AgentRecord, width: number): string[] {
665
- const take = (text: string, color: string): string[] =>
666
- text
667
- .split("\n")
668
- .map(line => line.trim())
669
- .filter(line => line.length > 0)
670
- .slice(-MAX_TAIL_LINES)
671
- .map(line => this.theme.fg(color, clip(` ${line}`, width)));
672
-
673
- if (record.status === "error" && record.error) return take(record.error, "error");
674
- if ((record.status === "completed" || record.status === "steered") && record.result?.trim()) {
675
- return take(record.result, "dim");
676
- }
677
- if (record.status === "running" || record.status === "queued") {
678
- const activity = this.deps.activity.get(record.id);
679
- if (activity?.responseText?.trim()) return take(activity.responseText, "dim");
680
- if (activity) return [this.theme.fg("dim", clip(` ${describeActivity(activity.activeTools, activity.responseText)}`, width))];
681
- }
682
- return [];
683
- }
684
-
685
- private detailLines(rows: Row[], width: number): string[] {
686
- const lines: string[] = [];
687
- const entries = this.entriesOf(rows);
688
- const entry = this.selectedEntry(rows);
689
- if (!entry) {
690
- lines.push(this.theme.fg("muted", " Nothing to show"));
691
- lines.push(this.theme.fg("dim", " Settled rows may have been dismissed, or the roster is empty."));
692
- return lines;
693
- }
694
- const positionRaw = `${this.selectedIndex + 1} of ${entries.length}`;
695
-
696
- if (entry.kind === "workflow") {
697
- const run = entry.workflow;
698
- const section = SECTIONS.find(s => s.id === sectionOfWorkflow(run)) ?? SECTIONS[0];
699
- const nameLine = `${this.theme.fg(section.color, this.glyphs.bullet)} ${this.theme.fg("muted", "workflow")} ${run.name}`;
700
- lines.push(rightAlign(nameLine, this.theme.fg("dim", positionRaw), width));
701
- lines.push(this.theme.fg("dim", ` ${BOX.horizontal.repeat(Math.max(0, width - 4))}`));
702
- const elapsed = formatFleetElapsed((run.completedAt ?? Date.now()) - run.startedAt);
703
- lines.push(this.field("Status", this.theme.fg(section.color, run.status), width));
704
- lines.push(
705
- this.field("Progress", this.theme.fg("text", `${run.doneCount}/${run.totalCount} agent${run.totalCount === 1 ? "" : "s"}`), width),
706
- );
707
- lines.push(this.field("Elapsed", this.theme.fg("text", elapsed), width));
708
- lines.push(this.field("Tokens", this.theme.fg("text", formatFleetTokens(run.tokens)), width));
709
- lines.push("");
710
- lines.push(this.theme.fg("dim", " Enter to open the run · Esc to close"));
711
- return lines.map(line => clip(line, width));
712
- }
713
-
714
- const record = entry.record;
715
- const section = SECTIONS.find(s => s.id === sectionOfAgent(record)) ?? SECTIONS[0];
716
- const nameLine =
717
- `${this.theme.fg(section.color, this.glyphs.bullet)} ` + renderAgentName(record.type, this.theme, { bold: true });
718
- lines.push(rightAlign(nameLine, this.theme.fg("dim", positionRaw), width));
719
- lines.push(this.theme.fg("dim", ` ${BOX.horizontal.repeat(Math.max(0, width - 4))}`));
720
- lines.push(this.field("Type", this.theme.fg("text", record.type), width));
721
- lines.push(this.field("Task", this.theme.fg("muted", record.description), width));
722
- lines.push(this.field("Status", this.theme.fg(section.color, record.status), width));
723
-
724
- const { modelName, modelId, tags } = buildInvocationTags(record.invocation);
725
- lines.push(this.field("Model", this.theme.fg("text", modelId ?? modelName ?? "session default"), width));
726
- const [thinking, ...flags] = splitThinkingTag(tags);
727
- if (thinking) lines.push(this.field("Thinking", this.theme.fg("text", thinking), width));
728
- if (flags.length > 0) lines.push(this.field("Flags", this.theme.fg("muted", flags.join(" · ")), width));
729
-
730
- lines.push(this.field("Elapsed", this.theme.fg("text", formatFleetElapsed((record.completedAt ?? Date.now()) - record.startedAt)), width));
731
- lines.push(this.field("Tokens", this.theme.fg("text", formatFleetTokens(getLifetimeTotal(record.lifetimeUsage))), width));
732
- if (this.deps.showCost()) {
733
- const cost = formatCost(getLifetimeCost(record.lifetimeUsage));
734
- if (cost) lines.push(this.field("Cost", this.theme.fg("text", cost), width));
735
- }
736
- lines.push(this.field("Tools", this.theme.fg("text", String(record.toolUses)), width));
737
- const advisor = record.advisorStatus;
738
- lines.push(this.field("Advisor", this.theme.fg("muted", formatAdvisorState(advisor)), width));
739
- if (advisor && (advisor.state !== "off" || advisor.reviews > 0 || advisor.lastReviewAt !== undefined)) {
740
- lines.push(this.field("Adv model", this.theme.fg("text", advisor.models.join(", ") || "—"), width));
741
- lines.push(this.field("Reviews", this.theme.fg("text", String(advisor.reviews)), width));
742
- lines.push(this.field("Last review", this.theme.fg("text", formatAdvisorLastReview(advisor)), width));
743
- }
744
-
745
- const tail = this.agentTail(record, width);
746
- if (tail.length > 0) {
747
- lines.push("");
748
- lines.push(this.theme.fg("dim", record.status === "error" ? " Error" : record.status === "running" || record.status === "queued" ? " Activity" : " Result"));
749
- lines.push(...tail);
750
- }
751
- lines.push("");
752
- lines.push(this.theme.fg("dim", " Enter to open full view · Esc to close"));
753
- return lines.map(line => clip(line, width));
754
- }
755
-
756
- // ── frame ─────────────────────────────────────────────────────────────
757
-
758
- private headerRight(entries: EntryRow[]): string {
759
- const agents = entries.filter(row => row.entry.kind === "agent").length;
760
- const workflows = entries.length - agents;
761
- const parts = [`${agents} agent${agents === 1 ? "" : "s"}`];
762
- if (workflows > 0) parts.push(`${workflows} workflow${workflows === 1 ? "" : "s"}`);
763
- return parts.join(" · ");
764
- }
765
-
766
- private footerLine(width: number): string {
767
- const separator = this.theme.fg("dim", " · ");
768
- const required = [
769
- keyHint(this.theme, "↑↓", "move"),
770
- keyHint(this.theme, "enter", "open"),
771
- keyHint(this.theme, "d", "dismiss"),
772
- ];
773
- const close = keyHint(this.theme, "esc", "close");
774
- return clip(` ${required.join(separator)}${separator}${close}`, width);
775
- }
776
-
777
- render(width: number): string[] {
778
- const requested = Math.max(1, Math.floor(width));
779
- const w = Math.max(MIN_RENDER_WIDTH, requested);
780
- const lines = this.renderFrame(w);
781
- // Narrower than the internal floor: lay out at the floor, clip back.
782
- const output = requested >= w ? lines : lines.map(line => clip(line, requested));
783
- // Belt and braces: the TUI rejects lines wider than the viewport.
784
- return output.map(line => (visibleWidth(line) > requested ? clip(line, requested) : line));
785
- }
786
-
787
- private renderFrame(w: number): string[] {
788
- const layout = this.layoutFor(w);
789
-
790
- const rows = this.buildRows();
791
- const entries = this.reconcile(rows);
792
- this.ensureSelectionVisible(rows);
793
-
794
- const detail = this.detailLines(rows, layout.bodyWidth).slice(0, layout.bodyHeight);
795
-
796
- const lines: string[] = [];
797
- lines.push(topRule(this.theme, w, "Subagents", this.headerRight(entries)));
798
- lines.push(contentRow(this.theme, "", w));
799
- lines.push(
800
- layout.twoPane ? openSplit(this.theme, w, "Fleet", layout.leftWidth) : divider(this.theme, w),
801
- );
802
-
803
- const windowed = rows.slice(this.windowStart, this.windowStart + layout.bodyHeight);
804
- for (let i = 0; i < layout.bodyHeight; i++) {
805
- const right = detail[i] ?? "";
806
- if (!layout.twoPane) {
807
- lines.push(contentRow(this.theme, right, w));
808
- continue;
809
- }
810
- const row = windowed[i];
811
- const left = row === undefined
812
- ? ""
813
- : row.kind === "section"
814
- ? this.renderSectionRow(row, layout.leftWidth)
815
- : this.renderEntryRow(row, layout.leftWidth);
816
- lines.push(splitRow(this.theme, left, right, w, layout.leftWidth));
817
- }
818
-
819
- lines.push(
820
- layout.twoPane ? closeSplit(this.theme, w, layout.leftWidth) : divider(this.theme, w),
821
- );
822
- lines.push(contentRow(this.theme, this.footerLine(w - 2 * (INSET + 1)), w));
823
- lines.push(bottomRule(this.theme, w));
824
- return lines.map(line => (visibleWidth(line) > w ? clip(line, w) : line));
825
- }
826
-
827
- invalidate(): void {
828
- this.layout = undefined;
829
- }
830
-
831
- dispose(): void {
832
- this.closed = true;
833
- clearInterval(this.timer);
834
- }
835
- }
836
-
837
- // ─── small helpers ───────────────────────────────────────────────────────────
838
-
839
- function errorMessage(error: unknown): string {
840
- return error instanceof Error ? error.message : String(error);
841
- }
842
-
843
- /** Pull `thinking: x` out of the invocation tags; the rest are plain flags. */
844
- function splitThinkingTag(tags: readonly string[]): [thinking: string | undefined, flags: string[]] {
845
- const thinking = tags.find(tag => tag.startsWith("thinking: "));
846
- return [thinking ? thinking.slice("thinking: ".length) : undefined, tags.filter(tag => !tag.startsWith("thinking: "))];
847
- }
1
+ /**
2
+ * fleet-overlay.ts — model-picker-style two-pane fleet overlay.
3
+ *
4
+ * The full-screen counterpart to the compact AgentWidget list
5
+ * (`agent-widget.ts`, placed above or below the editor). Frame, top to bottom:
6
+ *
7
+ * ```
8
+ * ╭─ Subagents ─────────────────── 9 agents · 4 workflows ─╮
9
+ * │ │
10
+ * ├─ Fleet ────────────────┬───────────────────────────────┤
11
+ * │ ▾ Running 2 │ ● general-purpose │
12
+ * │ ❯ ● general-purpose … │ Sleep then report 2 │
13
+ * │ ● Explore find thing│ ───────── │
14
+ * │ ▾ Failed 1 │ Type general-purpose │
15
+ * │ ▾ Completed 1 │ Status running │
16
+ * │ │ Model provider/model │
17
+ * ├────────────────────────┴───────────────────────────────┤
18
+ * │ ↑↓ move · enter open · d dismiss · esc close │
19
+ * ╰────────────────────────────────────────────────────────╯
20
+ * ```
21
+ *
22
+ * Left pane: the complete session roster — running, paused, failed and
23
+ * completed runs, grouped into sections (headers are display-only, the cursor
24
+ * skips them). Unlike the widget, completed/failed agents do not drop out after
25
+ * a few seconds; rows live until the manager sweeps settled records (~10
26
+ * minutes after settle — see agent-manager.ts `cleanup()`), matching the
27
+ * retention the workflow dialog already documents. The manager is untouched:
28
+ * dismissal from this list (`d`) is an overlay-local view filter.
29
+ *
30
+ * Right pane: a detail card for the selected entry — type, description, status,
31
+ * model, thinking, elapsed, tokens, cost (when the `showCost` setting is on),
32
+ * and a short activity/result tail. Enter opens the existing full surface for
33
+ * the entry — the conversation overlay for an agent, the workflow inspector for
34
+ * a run — stacked over this one; Esc there returns here.
35
+ *
36
+ * Agent Hub additions (oh-my-pi parity):
37
+ * - under the detail card, a live transcript tail of the selected agent
38
+ * (prompts, replies, tool calls, failures) plus its current tools and context use;
39
+ * - `2` switches the right pane to an Activity log across agents (`f` cycles
40
+ * All/Errors/Responses/Tools, `s` toggles all agents vs the selected one), `1` returns;
41
+ * - `t` shows nested agents as a parent → child tree, `/` filters by id/handle/name/task;
42
+ * - `x` twice stops a running agent, `r` resumes a finished one; Alt+A closes.
43
+ *
44
+ * Narrow terminals (below {@link TWO_PANE_MIN_WIDTH} columns) drop the left
45
+ * pane entirely: the detail card renders full width and carries a position
46
+ * marker (`3 of 9`), so the roster is still navigable by ↑/↓ without ever
47
+ * seeing the list — the same trade the model picker makes for its facet pane.
48
+ *
49
+ * Frame geometry mirrors the model picker's discipline (pi-model-picker
50
+ * src/picker.ts): a fixed chrome budget around one body, a target height of a
51
+ * fraction of the terminal capped at `rows - 2`, and an internal render floor
52
+ * of {@link MIN_RENDER_WIDTH} columns with narrower requests clipped back — so
53
+ * the frame never exceeds terminal width or height. Rendering uses pi-tui
54
+ * primitives and the structural widget `Theme` (fg/bold) only — no sibling
55
+ * imports, no hardcoded colors.
56
+ */
57
+
58
+ import { type Component, decodeKittyPrintable, type Focusable, isKeyRelease, type KeyId, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
59
+ import { formatAdvisorLastReview, formatAdvisorState } from "../advisor-status.ts";
60
+ import { hasAgentBadge, renderAgentName } from "../agent-color.ts";
61
+ import { isTopLevelAgent } from "../agent-manager.ts";
62
+ import type { AgentRecord } from "../types.ts";
63
+ import { getLifetimeCost, getLifetimeTotal } from "../usage.ts";
64
+ import { type AgentActivity, buildInvocationTags, describeActivity, formatCost, sanitizeRowText, type Theme } from "./agent-widget.ts";
65
+ import { type FleetWorkflow, formatFleetElapsed, formatFleetTokens } from "./fleet-list.ts";
66
+ import {
67
+ ACTIVITY_FILTERS,
68
+ type ActivityFilter,
69
+ activityFeed,
70
+ type FeedEvent,
71
+ type FeedKind,
72
+ transcriptTail,
73
+ treeOrder,
74
+ } from "./hub-feed.ts";
75
+
76
+ // ─── geometry ────────────────────────────────────────────────────────────────
77
+
78
+ /**
79
+ * Rows outside the body pane: top rule, blank, split opener, split closer,
80
+ * footer hints, bottom rule.
81
+ */
82
+ const CHROME_ROWS = 6;
83
+ /** Fraction of the terminal the overlay targets, below the host's maxHeight cap. */
84
+ const HEIGHT_FRACTION = 0.88;
85
+ /** Smallest body the frame will render. */
86
+ const MIN_BODY_ROWS = 1;
87
+ /** Below this the left pane is dropped and the detail card runs full width. */
88
+ export const TWO_PANE_MIN_WIDTH = 72;
89
+ const MIN_LEFT_WIDTH = 24;
90
+ const MAX_LEFT_WIDTH = 36;
91
+ /**
92
+ * Internal rendering floor. A narrower request is laid out at this width and
93
+ * clipped back, so the layout arithmetic never degenerates.
94
+ */
95
+ export const MIN_RENDER_WIDTH = 40;
96
+ /** Re-render cadence so elapsed/token stats tick while agents run. */
97
+ const TICK_MS = 250;
98
+ /** Activity/result lines shown at the bottom of the detail card. */
99
+ const MAX_TAIL_LINES = 3;
100
+
101
+ /**
102
+ * Total frame height for a terminal of `terminalRows`, including chrome.
103
+ * Mirrored from the model picker's guard: capped at `rows - 2` so the frame is
104
+ * never clipped by the overlay host, floored at one body row so the layout math
105
+ * always has somewhere to draw.
106
+ */
107
+ export function overlayHeightFor(terminalRows: number): number {
108
+ const rows = Number.isFinite(terminalRows) && terminalRows > 0 ? Math.floor(terminalRows) : 40;
109
+ const smallest = CHROME_ROWS + MIN_BODY_ROWS;
110
+ return Math.max(smallest, Math.min(Math.floor(rows * HEIGHT_FRACTION), rows - 2));
111
+ }
112
+
113
+ interface Layout {
114
+ readonly width: number;
115
+ readonly height: number;
116
+ readonly twoPane: boolean;
117
+ readonly leftWidth: number;
118
+ readonly bodyHeight: number;
119
+ /** Content width inside the right pane. */
120
+ readonly bodyWidth: number;
121
+ }
122
+
123
+ // ─── glyphs ──────────────────────────────────────────────────────────────────
124
+
125
+ interface Glyphs {
126
+ /** Marks the highlighted roster row. */
127
+ readonly cursor: string;
128
+ /** Status dot; the section color carries the meaning. */
129
+ readonly bullet: string;
130
+ /** Section header prefix. */
131
+ readonly group: string;
132
+ }
133
+
134
+ const UNICODE_GLYPHS: Glyphs = { cursor: "❯", bullet: "●", group: "▾" };
135
+ const ASCII_GLYPHS: Glyphs = { cursor: ">", bullet: "*", group: "v" };
136
+
137
+ /**
138
+ * Resolve the glyph set. Set `PI_SUBAGENTS_GLYPHS=ascii` for terminals where
139
+ * ambiguous-width glyphs render two cells wide and shift the frame. Box-drawing
140
+ * frame characters stay — they are single-width in virtually all terminals;
141
+ * only the label glyphs shift.
142
+ */
143
+ function resolveGlyphs(): Glyphs {
144
+ return process.env.PI_SUBAGENTS_GLYPHS?.trim().toLowerCase() === "ascii" ? ASCII_GLYPHS : UNICODE_GLYPHS;
145
+ }
146
+
147
+ // ─── frame drawing (pi's dialog chrome, reproduced locally) ─────────────────
148
+
149
+ const BOX = {
150
+ topLeft: "╭",
151
+ topRight: "╮",
152
+ bottomLeft: "╰",
153
+ bottomRight: "╯",
154
+ horizontal: "─",
155
+ vertical: "│",
156
+ teeDown: "┬",
157
+ teeUp: "┴",
158
+ teeRight: "├",
159
+ teeLeft: "┤",
160
+ } as const;
161
+
162
+ /** Left/right inset between a vertical border and its content. */
163
+ const INSET = 1;
164
+
165
+ /** Force `text` to exactly `width` columns: truncate with ellipsis, else pad. ANSI-aware. */
166
+ function fitText(text: string, width: number): string {
167
+ if (width <= 0) return "";
168
+ const measured = visibleWidth(text);
169
+ if (measured > width) {
170
+ const clipped = truncateToWidth(text, width);
171
+ const clippedWidth = visibleWidth(clipped);
172
+ return clippedWidth < width ? clipped + " ".repeat(width - clippedWidth) : clipped;
173
+ }
174
+ return measured === width ? text : text + " ".repeat(width - measured);
175
+ }
176
+
177
+ /** Trim `text` to at most `width` columns without padding. */
178
+ function clip(text: string, width: number): string {
179
+ return width <= 0 ? "" : truncateToWidth(text, width);
180
+ }
181
+
182
+ /** Place `right` flush to `width`, truncating `left` first so the stats survive. */
183
+ function rightAlign(left: string, right: string, width: number): string {
184
+ const rightWidth = visibleWidth(right);
185
+ const maxLeft = Math.max(0, width - rightWidth - 1);
186
+ const leftClamped = clip(left, maxLeft);
187
+ const gap = Math.max(1, width - visibleWidth(leftClamped) - rightWidth);
188
+ return fitText(leftClamped + " ".repeat(gap) + right, width);
189
+ }
190
+
191
+ /** A dim `key` + muted `description` pair for the footer hint row. */
192
+ function keyHint(theme: Theme, key: string, description: string): string {
193
+ return theme.fg("dim", key) + theme.fg("muted", ` ${description}`);
194
+ }
195
+
196
+ /** Titled top rule: `╭─ Subagents ─────── right ─╮`. Right label is budgeted first. */
197
+ function topRule(theme: Theme, width: number, title: string, right: string): string {
198
+ const bar = (s: string) => theme.fg("border", s);
199
+ const inner = Math.max(0, width - 2);
200
+ if (inner <= 1) return bar(BOX.topLeft + BOX.horizontal.repeat(inner) + BOX.topRight);
201
+
202
+ const rule = inner - 1; // columns for title + filler + right label
203
+ const rightShown = right ? clip(` ${right} `, Math.max(0, Math.floor(rule * 0.4))) : "";
204
+ const rightWidth = visibleWidth(rightShown);
205
+ const rightBlock = rightShown.length > 0 ? rightWidth + 1 : 0;
206
+
207
+ const titleShown = title ? clip(` ${title} `, Math.max(0, rule - rightBlock)) : "";
208
+ const titleWidth = visibleWidth(titleShown);
209
+ const fill = Math.max(0, rule - titleWidth - rightBlock);
210
+
211
+ let line = bar(BOX.topLeft + BOX.horizontal);
212
+ if (titleWidth > 0) line += theme.bold(theme.fg("accent", titleShown));
213
+ line += bar(BOX.horizontal.repeat(fill));
214
+ if (rightShown.length > 0) line += bar(BOX.horizontal) + theme.fg("dim", rightShown);
215
+ return line + bar(BOX.topRight);
216
+ }
217
+
218
+ /** Full-width interior rule: `├────┤`. */
219
+ function divider(theme: Theme, width: number): string {
220
+ return (
221
+ theme.fg("border", BOX.teeRight) +
222
+ theme.fg("border", BOX.horizontal.repeat(Math.max(0, width - 2))) +
223
+ theme.fg("border", BOX.teeLeft)
224
+ );
225
+ }
226
+
227
+ /** Closing rule: `╰────╯`. */
228
+ function bottomRule(theme: Theme, width: number): string {
229
+ return (
230
+ theme.fg("border", BOX.bottomLeft) +
231
+ theme.fg("border", BOX.horizontal.repeat(Math.max(0, width - 2))) +
232
+ theme.fg("border", BOX.bottomRight)
233
+ );
234
+ }
235
+
236
+ /** `│ content │` with one column of inset on each side; exact width. */
237
+ function contentRow(theme: Theme, content: string, width: number): string {
238
+ const budget = width - 2 * (INSET + 1);
239
+ const bar = theme.fg("border", BOX.vertical);
240
+ if (budget <= 0) return bar + bar;
241
+ return `${bar} ${fitText(content, budget)} ${bar}`;
242
+ }
243
+
244
+ /** Left/right rule lengths for an interior split rule over the pane divider. */
245
+ function splitArms(width: number, leftWidth: number): { left: number; right: number } {
246
+ const dividerColumn = leftWidth + INSET + 1 + INSET;
247
+ return { left: Math.max(0, dividerColumn - 1), right: Math.max(0, width - 2 - dividerColumn) };
248
+ }
249
+
250
+ /** Rule opening the two-pane region, splitting over the divider: `├─ Fleet ──┬───┤`. */
251
+ function openSplit(theme: Theme, width: number, title: string, leftWidth: number): string {
252
+ const { left, right } = splitArms(width, leftWidth);
253
+ let head: string;
254
+ if (!title || left <= 1) {
255
+ head = theme.fg("border", BOX.teeRight + BOX.horizontal.repeat(left));
256
+ } else {
257
+ const shown = clip(` ${title} `, Math.max(0, left - 1));
258
+ head =
259
+ theme.fg("border", BOX.teeRight + BOX.horizontal) +
260
+ theme.bold(theme.fg("accent", shown)) +
261
+ theme.fg("border", BOX.horizontal.repeat(Math.max(0, left - 1 - visibleWidth(shown))));
262
+ }
263
+ return (
264
+ head + theme.fg("border", BOX.teeDown + BOX.horizontal.repeat(right) + BOX.teeLeft)
265
+ );
266
+ }
267
+
268
+ /** Closing rule of the two-pane region: `├─────┴────┤`. */
269
+ function closeSplit(theme: Theme, width: number, leftWidth: number): string {
270
+ const { left, right } = splitArms(width, leftWidth);
271
+ return theme.fg(
272
+ "border",
273
+ BOX.teeRight + BOX.horizontal.repeat(left) + BOX.teeUp + BOX.horizontal.repeat(right) + BOX.teeLeft,
274
+ );
275
+ }
276
+
277
+ /** Right-pane content budget for a two-pane layout of `width`. */
278
+ function bodyWidthFor(width: number, leftWidth: number): number {
279
+ // Fixed overhead: `│ ` + ` │ ` + ` │` = 4 * INSET + 3.
280
+ return Math.max(0, width - leftWidth - (4 * INSET + 3));
281
+ }
282
+
283
+ /** `│ left │ body │`, each pane padded to its exact budget. */
284
+ function splitRow(theme: Theme, left: string, body: string, width: number, leftWidth: number): string {
285
+ const bodyBudget = bodyWidthFor(width, leftWidth);
286
+ const bar = theme.fg("border", BOX.vertical);
287
+ if (bodyBudget <= 0) return bar + bar;
288
+ return `${bar} ${fitText(left, leftWidth)} ${bar} ${fitText(body, bodyBudget)} ${bar}`;
289
+ }
290
+
291
+ // ─── roster model ────────────────────────────────────────────────────────────
292
+
293
+ type SectionId = "running" | "paused" | "failed" | "completed";
294
+
295
+ interface Section {
296
+ readonly id: SectionId;
297
+ readonly label: string;
298
+ /** Theme color for the section header and every status dot in it. */
299
+ readonly color: string;
300
+ }
301
+
302
+ /** Fixed display order: actionable first, history at the bottom. */
303
+ const SECTIONS: readonly Section[] = [
304
+ { id: "running", label: "Running", color: "accent" },
305
+ { id: "paused", label: "Paused", color: "warning" },
306
+ { id: "failed", label: "Failed", color: "error" },
307
+ { id: "completed", label: "Completed", color: "success" },
308
+ ];
309
+
310
+ function sectionOfAgent(record: AgentRecord): SectionId {
311
+ if (record.status === "running" || record.status === "queued") return "running";
312
+ // aborted (user/tool cut) and stopped (manual halt) read as failures next to
313
+ // error; steered is a completed run that happened to be redirected along the
314
+ // way, so it settles into the success group.
315
+ if (record.status === "error" || record.status === "aborted" || record.status === "stopped") return "failed";
316
+ return "completed";
317
+ }
318
+
319
+ function sectionOfWorkflow(run: FleetWorkflow): SectionId {
320
+ if (run.status === "running") return "running";
321
+ if (run.status === "paused") return "paused";
322
+ if (run.status === "failed" || run.status === "killed") return "failed";
323
+ return "completed";
324
+ }
325
+
326
+ export type RosterEntry =
327
+ | { readonly kind: "workflow"; readonly workflow: FleetWorkflow }
328
+ | { readonly kind: "agent"; readonly record: AgentRecord; readonly depth?: number };
329
+
330
+ function entryKey(entry: RosterEntry): string {
331
+ return entry.kind === "agent" ? `agent:${entry.record.id}` : `workflow:${entry.workflow.id}`;
332
+ }
333
+
334
+ interface SectionRow {
335
+ readonly kind: "section";
336
+ readonly key: string;
337
+ readonly section: Section;
338
+ readonly count: number;
339
+ }
340
+
341
+ interface EntryRow {
342
+ readonly kind: "entry";
343
+ readonly key: string;
344
+ readonly entry: RosterEntry;
345
+ }
346
+
347
+ type Row = SectionRow | EntryRow;
348
+
349
+ /** What the overlay reads from the host; every source is pulled live per render. */
350
+ export interface FleetOverlayDeps {
351
+ /** Render pump; the real pi `TUI` satisfies this structurally. */
352
+ readonly tui: { requestRender(): void; terminal: { rows: number; columns: number } };
353
+ readonly theme: Theme;
354
+ /**
355
+ * Top-level agent records for the session; read on every render. Records
356
+ * without a session are filtered here (nothing to open behind them) — they
357
+ * are typically queued and row into view once they start.
358
+ */
359
+ readonly records: () => AgentRecord[];
360
+ /** Workflow runs as the fleet list sees them. */
361
+ readonly workflows: () => readonly FleetWorkflow[];
362
+ /** Live activity per running agent id, for the detail card's tail. */
363
+ readonly activity: ReadonlyMap<string, AgentActivity>;
364
+ /** Whether the detail card shows an estimated cost. Read per render. */
365
+ readonly showCost: () => boolean;
366
+ /** Opens the full conversation overlay for an agent, stacked over this one. */
367
+ readonly openAgent: (record: AgentRecord) => Promise<void> | void;
368
+ /** Opens the workflow inspector for a run, stacked over this one. */
369
+ readonly openWorkflow: (id: string) => Promise<void> | void;
370
+ readonly done: (result: undefined) => void;
371
+ readonly notify?: (message: string, type?: "info" | "warning" | "error") => void;
372
+ /** Every record including nested children, for the tree view (`t`). Defaults to `records`. */
373
+ readonly allRecords?: () => AgentRecord[];
374
+ /** Stop a running agent (`x` twice). Returns whether it was stopped. */
375
+ readonly stopAgent?: (record: AgentRecord) => boolean;
376
+ /** Resume a finished agent with a follow-up (`r`); the host asks for the message. */
377
+ readonly resumeAgent?: (record: AgentRecord) => Promise<void> | void;
378
+ }
379
+
380
+ const FEED_COLOR: Record<FeedKind, string> = { prompt: "accent", response: "text", tool: "muted", error: "error" };
381
+ const FEED_MARK: Record<FeedKind, string> = { prompt: "›", response: "◆", tool: "⚙", error: "✗" };
382
+
383
+ function clockTime(at: number | undefined): string {
384
+ if (at === undefined) return "--:--:--";
385
+ const d = new Date(at);
386
+ return [d.getHours(), d.getMinutes(), d.getSeconds()].map(n => String(n).padStart(2, "0")).join(":");
387
+ }
388
+
389
+ /** Id, handle, alias, type, task — what `/` matches against. */
390
+ function agentHaystack(record: AgentRecord): string {
391
+ return [record.id, record.handle, record.alias, record.type, record.description].filter(Boolean).join(" ").toLowerCase();
392
+ }
393
+
394
+ /**
395
+ * The fleet overlay. See the file header for the frame layout and the
396
+ * roster → detail navigation model.
397
+ */
398
+ export class FleetOverlay implements Component, Focusable {
399
+ private readonly deps: FleetOverlayDeps;
400
+ private readonly theme: Theme;
401
+ private readonly glyphs: Glyphs;
402
+
403
+ /** `agent:<id>` / `workflow:<id>` of the highlighted row — key, never index. */
404
+ private selectedKey = "";
405
+ /** Fallback position when the keyed row is gone; the nearest survivor keeps the cursor. */
406
+ private selectedIndex = 0;
407
+ private windowStart = 0;
408
+ /** Settled rows the user dismissed from this view; overlay-local, manager untouched. */
409
+ private readonly dismissed = new Set<string>();
410
+
411
+ private closed = false;
412
+ private layout: Layout | undefined;
413
+ /** Right pane: the selected entry's card + live transcript, or the cross-agent activity log. */
414
+ private tab: "agents" | "activity" = "agents";
415
+ private tree = false;
416
+ private filter = "";
417
+ private filtering = false;
418
+ private activityFilter: ActivityFilter = "all";
419
+ private activityScope: "all" | "selected" = "all";
420
+ /** Key armed by a first `x`; a second `x` on the same row stops it. */
421
+ private stopArmed: string | undefined;
422
+ private readonly timer: ReturnType<typeof setInterval>;
423
+
424
+ // Focusable: no embedded editor/IME, so the flag is a plain holder.
425
+ private focusedFlag = false;
426
+
427
+ constructor(deps: FleetOverlayDeps) {
428
+ this.deps = deps;
429
+ this.theme = deps.theme;
430
+ this.glyphs = resolveGlyphs();
431
+ // Tick keeps elapsed/token stats live while anything is running; the roster
432
+ // itself is rebuilt on every render, so this only needs to re-render.
433
+ this.timer = setInterval(() => {
434
+ if (!this.closed) this.deps.tui.requestRender();
435
+ }, TICK_MS);
436
+ (this.timer as { unref?: () => void }).unref?.();
437
+ }
438
+
439
+ get focused(): boolean {
440
+ return this.focusedFlag;
441
+ }
442
+
443
+ set focused(value: boolean) {
444
+ this.focusedFlag = value;
445
+ }
446
+
447
+ // ── roster ───────────────────────────────────────────────────────────
448
+
449
+ /**
450
+ * The full session roster. No linger cutoff — that window is the widget's
451
+ * glance behavior, not a property of the records; the manager keeps settled
452
+ * records long enough (~10 min) for this list to read as history.
453
+ */
454
+ private agentRecords(): AgentRecord[] {
455
+ return this.deps.records().filter(record => isTopLevelAgent(record) && record.session !== undefined);
456
+ }
457
+
458
+ /** Flat row list: section headers interleaved, entries newest-first within. */
459
+ private buildRows(): Row[] {
460
+ const query = this.filter.trim().toLowerCase();
461
+ const agents = this.agentRecords();
462
+ const runs = this.deps.workflows().filter(run =>
463
+ !this.dismissed.has(`workflow:${run.id}`) && (!query || `${run.id} ${run.name}`.toLowerCase().includes(query)));
464
+ const all = this.tree ? (this.deps.allRecords?.() ?? this.deps.records()).filter(record => record.session !== undefined) : [];
465
+ const rows: Row[] = [];
466
+
467
+ for (const section of SECTIONS) {
468
+ const sectionRuns = runs
469
+ .filter(run => sectionOfWorkflow(run) === section.id)
470
+ .sort((a, b) => b.startedAt - a.startedAt);
471
+ const sectionAgents = agents
472
+ .filter(record => sectionOfAgent(record) === section.id && (this.tree || !this.dismissed.has(`agent:${record.id}`)))
473
+ .sort((a, b) => b.startedAt - a.startedAt);
474
+ // Tree view: each top-level agent is followed by its nested children (any status).
475
+ const agentRows = this.tree
476
+ ? treeOrder(sectionAgents, all, record => this.dismissed.has(`agent:${record.id}`))
477
+ .map(({ record, depth }) => ({ kind: "agent" as const, record, depth }))
478
+ : sectionAgents.map(record => ({ kind: "agent" as const, record }));
479
+ const entries: RosterEntry[] = [
480
+ // Runs sit above agents, as in the widget: a run owns most of the
481
+ // agents that would otherwise crowd the same section.
482
+ ...sectionRuns.map(workflow => ({ kind: "workflow" as const, workflow })),
483
+ ...agentRows.filter(row => !query || agentHaystack(row.record).includes(query)),
484
+ ];
485
+ if (entries.length === 0) continue;
486
+ rows.push({ kind: "section", key: `section:${section.id}`, section, count: entries.length });
487
+ for (const entry of entries) rows.push({ kind: "entry", key: entryKey(entry), entry });
488
+ }
489
+ return rows;
490
+ }
491
+
492
+ private entriesOf(rows: Row[]): EntryRow[] {
493
+ return rows.filter((row): row is EntryRow => row.kind === "entry");
494
+ }
495
+
496
+ /** Re-seat the selection on the same key; a removed row falls to the nearest survivor. */
497
+ private reconcile(rows: Row[]): EntryRow[] {
498
+ const entries = this.entriesOf(rows);
499
+ if (entries.length === 0) {
500
+ this.selectedKey = "";
501
+ this.selectedIndex = 0;
502
+ return entries;
503
+ }
504
+ const found = entries.findIndex(row => row.key === this.selectedKey);
505
+ this.selectedIndex = found >= 0 ? found : Math.max(0, Math.min(this.selectedIndex, entries.length - 1));
506
+ this.selectedKey = entries[this.selectedIndex].key;
507
+ return entries;
508
+ }
509
+
510
+ private selectedEntry(rows: Row[]): RosterEntry | undefined {
511
+ return this.entriesOf(rows)[this.selectedIndex]?.entry;
512
+ }
513
+
514
+ private move(delta: number, wrap: boolean, entries: EntryRow[]): void {
515
+ const total = entries.length;
516
+ if (total === 0) return;
517
+ const next = wrap
518
+ ? ((this.selectedIndex + delta) % total + total) % total
519
+ : Math.max(0, Math.min(this.selectedIndex + delta, total - 1));
520
+ this.selectedIndex = next;
521
+ this.selectedKey = entries[next].key;
522
+ }
523
+
524
+ /** Pan the roster window so the highlighted entry's row is inside it. */
525
+ private ensureSelectionVisible(rows: Row[]): void {
526
+ const visible = this.layout?.bodyHeight ?? 10;
527
+ const maxStart = Math.max(0, rows.length - visible);
528
+ this.windowStart = Math.max(0, Math.min(this.windowStart, maxStart));
529
+ if (!this.selectedKey) return;
530
+ const rowIndex = rows.findIndex(row => row.kind === "entry" && row.key === this.selectedKey);
531
+ if (rowIndex < 0) return;
532
+ if (rowIndex < this.windowStart) this.windowStart = rowIndex;
533
+ else if (rowIndex >= this.windowStart + visible) this.windowStart = rowIndex - visible + 1;
534
+ this.windowStart = Math.max(0, Math.min(this.windowStart, maxStart));
535
+ }
536
+
537
+ // ── actions ──────────────────────────────────────────────────────────────
538
+
539
+ /**
540
+ * Hand control back to the caller, which closes and disposes the overlay.
541
+ * Same done semantics as the conversation viewer: resolve with `undefined`.
542
+ */
543
+ private finish(): void {
544
+ this.dispose();
545
+ this.deps.done(undefined);
546
+ }
547
+
548
+ /** After a stacked view closes: put the cursor back on the entry it came from. */
549
+ private afterStackedClose(key: string): void {
550
+ if (this.closed) return;
551
+ this.selectedKey = key;
552
+ this.deps.tui.requestRender();
553
+ }
554
+
555
+ private activate(rows: Row[]): void {
556
+ const entry = this.selectedEntry(rows);
557
+ if (!entry) return;
558
+ if (entry.kind === "workflow") {
559
+ const id = entry.workflow.id;
560
+ void Promise.resolve(this.deps.openWorkflow(id)).then(
561
+ () => this.afterStackedClose(`workflow:${id}`),
562
+ error => this.deps.notify?.(`Could not open the run: ${errorMessage(error)}`, "error"),
563
+ );
564
+ return;
565
+ }
566
+ const record = entry.record;
567
+ // The roster filters to records with sessions, so this is only reachable
568
+ // when the session was detached between render and keypress.
569
+ if (!record.session) {
570
+ this.deps.notify?.(`Agent is ${record.status} — no session available.`, "info");
571
+ return;
572
+ }
573
+ void Promise.resolve(this.deps.openAgent(record)).then(
574
+ () => this.afterStackedClose(`agent:${record.id}`),
575
+ error => this.deps.notify?.(`Could not open the conversation: ${errorMessage(error)}`, "error"),
576
+ );
577
+ }
578
+
579
+ /** Remove the selected settled row from this view. Running work is not dismissible. */
580
+ private dismissSelected(rows: Row[]): void {
581
+ const entry = this.selectedEntry(rows);
582
+ if (!entry) return;
583
+ const section = entry.kind === "workflow" ? sectionOfWorkflow(entry.workflow) : sectionOfAgent(entry.record);
584
+ if (section === "running" || section === "paused") return;
585
+ this.dismissed.add(entryKey(entry));
586
+ this.deps.tui.requestRender();
587
+ }
588
+
589
+ // ── input ──────────────────────────────────────────────────────────────
590
+
591
+ handleInput(data: string): void {
592
+ if (this.closed || isKeyRelease(data)) return;
593
+
594
+ if (this.filtering) {
595
+ this.handleFilterInput(data);
596
+ return;
597
+ }
598
+
599
+ if (matchesKey(data, "ctrl+c") || matchesKey(data, "alt+a")) {
600
+ this.finish();
601
+ return;
602
+ }
603
+ if (matchesKey(data, "escape")) {
604
+ // Esc ladder: clear an active filter first, then close.
605
+ if (this.filter) {
606
+ this.filter = "";
607
+ this.deps.tui.requestRender();
608
+ return;
609
+ }
610
+ this.finish();
611
+ return;
612
+ }
613
+
614
+ const rows = this.buildRows();
615
+ const entries = this.reconcile(rows);
616
+ if (this.handleHubKey(data, rows)) {
617
+ this.deps.tui.requestRender();
618
+ return;
619
+ }
620
+ const page = Math.max(1, (this.layout?.bodyHeight ?? 10) - 1);
621
+
622
+ const movements: ReadonlyArray<{ keys: readonly KeyId[]; delta: number; wrap: boolean }> = [
623
+ { keys: ["up"], delta: -1, wrap: true },
624
+ { keys: ["down"], delta: 1, wrap: true },
625
+ { keys: ["pageUp"], delta: -page, wrap: false },
626
+ { keys: ["pageDown"], delta: page, wrap: false },
627
+ { keys: ["home"], delta: -Number.MAX_SAFE_INTEGER, wrap: false },
628
+ { keys: ["end"], delta: Number.MAX_SAFE_INTEGER, wrap: false },
629
+ ];
630
+ for (const movement of movements) {
631
+ if (!movement.keys.some(key => matchesKey(data, key))) continue;
632
+ this.move(movement.delta, movement.wrap, entries);
633
+ this.deps.tui.requestRender();
634
+ return;
635
+ }
636
+
637
+ if (matchesKey(data, "enter") || matchesKey(data, "return")) {
638
+ this.activate(rows);
639
+ this.deps.tui.requestRender();
640
+ return;
641
+ }
642
+ if (matchesKey(data, "d")) {
643
+ this.dismissSelected(rows);
644
+ this.deps.tui.requestRender();
645
+ return;
646
+ }
647
+ }
648
+
649
+ private handleFilterInput(data: string): void {
650
+ if (matchesKey(data, "escape")) {
651
+ this.filtering = false;
652
+ this.filter = "";
653
+ } else if (matchesKey(data, "enter") || matchesKey(data, "return")) {
654
+ this.filtering = false;
655
+ } else if (matchesKey(data, "backspace")) {
656
+ this.filter = this.filter.slice(0, -1);
657
+ } else {
658
+ // Text keys arrive as bare bytes, or as CSI-u presses when the terminal
659
+ // enables the Kitty protocol (flag 1 sends every printable key that way).
660
+ const text = decodeKittyPrintable(data) ?? (data.length === 1 && data >= " " && data !== "\x7f" ? data : undefined);
661
+ if (text) this.filter += text;
662
+ }
663
+ this.deps.tui.requestRender();
664
+ }
665
+
666
+ /** Hub keys; true when the key was consumed. */
667
+ private handleHubKey(data: string, rows: Row[]): boolean {
668
+ const entry = this.selectedEntry(rows);
669
+ const armed = this.stopArmed;
670
+ this.stopArmed = undefined;
671
+ if (matchesKey(data, "1")) this.tab = "agents";
672
+ else if (matchesKey(data, "2")) this.tab = "activity";
673
+ else if (matchesKey(data, "t")) this.tree = !this.tree;
674
+ else if (matchesKey(data, "/")) this.filtering = true;
675
+ else if (matchesKey(data, "f") && this.tab === "activity") {
676
+ this.activityFilter = ACTIVITY_FILTERS[(ACTIVITY_FILTERS.indexOf(this.activityFilter) + 1) % ACTIVITY_FILTERS.length] as ActivityFilter;
677
+ } else if (matchesKey(data, "s") && this.tab === "activity") {
678
+ this.activityScope = this.activityScope === "all" ? "selected" : "all";
679
+ } else if (matchesKey(data, "x")) {
680
+ if (entry?.kind !== "agent" || !this.deps.stopAgent) return true;
681
+ const record = entry.record;
682
+ if (record.status !== "running" && record.status !== "queued") {
683
+ this.deps.notify?.("Only a running agent can be stopped.", "info");
684
+ return true;
685
+ }
686
+ const key = entryKey(entry);
687
+ if (armed !== key) {
688
+ this.stopArmed = key;
689
+ this.deps.notify?.(`Press x again to stop "${record.description}".`, "warning");
690
+ return true;
691
+ }
692
+ if (this.deps.stopAgent(record)) this.deps.notify?.(`Stopped "${record.description}".`, "info");
693
+ } else if (matchesKey(data, "r")) {
694
+ if (entry?.kind !== "agent" || !this.deps.resumeAgent) return true;
695
+ const record = entry.record;
696
+ if (record.status === "running" || record.status === "queued") {
697
+ this.deps.notify?.("Agent is still running — Enter opens it to steer.", "info");
698
+ return true;
699
+ }
700
+ const key = entryKey(entry);
701
+ void Promise.resolve(this.deps.resumeAgent(record)).then(
702
+ () => this.afterStackedClose(key),
703
+ error => this.deps.notify?.(`Could not resume: ${errorMessage(error)}`, "error"),
704
+ );
705
+ } else return false;
706
+ return true;
707
+ }
708
+
709
+ // ── layout ────────────────────────────────────────────────────────────
710
+
711
+ private terminalRows(): number {
712
+ const rows = this.deps.tui.terminal?.rows ?? 40;
713
+ return Number.isFinite(rows) && rows > 12 ? Math.floor(rows) : 40;
714
+ }
715
+
716
+ private layoutFor(width: number): Layout {
717
+ const height = overlayHeightFor(this.terminalRows());
718
+ const cached = this.layout;
719
+ if (cached && cached.height === height && cached.width === width) return cached;
720
+ const twoPane = width >= TWO_PANE_MIN_WIDTH;
721
+ const leftWidth = twoPane
722
+ ? Math.max(MIN_LEFT_WIDTH, Math.min(MAX_LEFT_WIDTH, Math.round(width * 0.28), width - 46))
723
+ : 0;
724
+ const layout: Layout = {
725
+ width,
726
+ height,
727
+ twoPane,
728
+ leftWidth,
729
+ bodyHeight: Math.max(MIN_BODY_ROWS, height - CHROME_ROWS),
730
+ bodyWidth: twoPane ? bodyWidthFor(width, leftWidth) : width - 2 * (INSET + 1),
731
+ };
732
+ this.layout = layout;
733
+ return layout;
734
+ }
735
+
736
+ // ── row rendering ─────────────────────────────────────────────────────
737
+
738
+ private renderSectionRow(row: SectionRow, width: number): string {
739
+ const head =
740
+ this.theme.fg(row.section.color, this.glyphs.group) + " " + this.theme.bold(this.theme.fg("muted", row.section.label));
741
+ return fitText(`${head} ${this.theme.fg("dim", String(row.count))}`, width);
742
+ }
743
+
744
+ private renderEntryRow(row: EntryRow, width: number): string {
745
+ const entry = row.entry;
746
+ const selected = row.key === this.selectedKey;
747
+ const section = entry.kind === "workflow" ? sectionOfWorkflow(entry.workflow) : sectionOfAgent(entry.record);
748
+ const sectionColor = (SECTIONS.find(s => s.id === section) ?? SECTIONS[0]).color;
749
+
750
+ const cursor = selected ? `${this.theme.fg("accent", this.glyphs.cursor)} ` : " ";
751
+ const dot = this.theme.fg(sectionColor, this.glyphs.bullet);
752
+
753
+ let head: string;
754
+ let stats: string;
755
+ if (entry.kind === "workflow") {
756
+ const run = entry.workflow;
757
+ const kind = this.theme.fg(selected ? "text" : "muted", "workflow");
758
+ const name = selected ? this.theme.fg("text", sanitizeRowText(run.name)) : sanitizeRowText(run.name);
759
+ head = `${cursor}${dot} ${kind} ${name}`;
760
+ const elapsed = (run.completedAt ?? Date.now()) - run.startedAt;
761
+ const agents = `${run.doneCount}/${run.totalCount} agent${run.totalCount === 1 ? "" : "s"}`;
762
+ stats = `${agents} · ${formatFleetElapsed(elapsed)} · ${formatFleetTokens(run.tokens)}`;
763
+ } else {
764
+ const record = entry.record;
765
+ const name = renderAgentName(record.type, this.theme, selected
766
+ ? { fallbackColor: "text", bold: hasAgentBadge(record.type) }
767
+ : { fallbackColor: "muted" });
768
+ const description = selected ? this.theme.fg("text", sanitizeRowText(record.description)) : sanitizeRowText(record.description);
769
+ const depth = entry.depth ?? 0;
770
+ const indent = depth > 0 ? `${" ".repeat(depth - 1)}${this.theme.fg("dim", "└ ")}` : "";
771
+ head = `${cursor}${indent}${dot} ${name} ${description}`;
772
+ const elapsed = formatFleetElapsed((record.completedAt ?? Date.now()) - record.startedAt);
773
+ const tokens = formatFleetTokens(getLifetimeTotal(record.lifetimeUsage));
774
+ const cost = this.deps.showCost() ? formatCost(getLifetimeCost(record.lifetimeUsage)) : "";
775
+ stats = `${elapsed} · ${tokens}${cost ? ` · ${cost}` : ""}`;
776
+ }
777
+
778
+ // A pane too narrow for the stats column shows the identity only; the
779
+ // detail card next to it carries the numbers.
780
+ if (width - visibleWidth(head) >= visibleWidth(stats) + 2 && width >= 30) {
781
+ return rightAlign(head, this.theme.fg(selected ? "text" : "dim", stats), width);
782
+ }
783
+ return fitText(head, width);
784
+ }
785
+
786
+ // ── detail card (right pane) ─────────────────────────────────────────────
787
+
788
+ /** One ` Label value` row, already styled, never wider than `width`. */
789
+ private field(label: string, value: string, width: number): string {
790
+ return clip(` ${this.theme.fg("dim", label.padEnd(12))}${value}`, width);
791
+ }
792
+
793
+ /**
794
+ * The tail of what an agent just did or said: the live activity line while it
795
+ * works, the final answer once it settles, the message when it errored.
796
+ * Workflows have no per-run prose feed — the progress counters above carry it.
797
+ */
798
+ private agentTail(record: AgentRecord, width: number): string[] {
799
+ const take = (text: string, color: string): string[] =>
800
+ text
801
+ .split("\n")
802
+ .map(line => line.trim())
803
+ .filter(line => line.length > 0)
804
+ .slice(-MAX_TAIL_LINES)
805
+ .map(line => this.theme.fg(color, clip(` ${line}`, width)));
806
+
807
+ if (record.status === "error" && record.error) return take(record.error, "error");
808
+ if ((record.status === "completed" || record.status === "steered") && record.result?.trim()) {
809
+ return take(record.result, "dim");
810
+ }
811
+ if (record.status === "running" || record.status === "queued") {
812
+ const activity = this.deps.activity.get(record.id);
813
+ if (activity?.responseText?.trim()) return take(activity.responseText, "dim");
814
+ if (activity) return [this.theme.fg("dim", clip(` ${describeActivity(activity.activeTools, activity.responseText)}`, width))];
815
+ }
816
+ return [];
817
+ }
818
+
819
+ private detailLines(rows: Row[], width: number): string[] {
820
+ const lines: string[] = [];
821
+ const entries = this.entriesOf(rows);
822
+ const entry = this.selectedEntry(rows);
823
+ if (!entry) {
824
+ lines.push(this.theme.fg("muted", " Nothing to show"));
825
+ lines.push(this.theme.fg("dim", " Settled rows may have been dismissed, or the roster is empty."));
826
+ return lines;
827
+ }
828
+ const positionRaw = `${this.selectedIndex + 1} of ${entries.length}`;
829
+
830
+ if (entry.kind === "workflow") {
831
+ const run = entry.workflow;
832
+ const section = SECTIONS.find(s => s.id === sectionOfWorkflow(run)) ?? SECTIONS[0];
833
+ const nameLine = `${this.theme.fg(section.color, this.glyphs.bullet)} ${this.theme.fg("muted", "workflow")} ${sanitizeRowText(run.name)}`;
834
+ lines.push(rightAlign(nameLine, this.theme.fg("dim", positionRaw), width));
835
+ lines.push(this.theme.fg("dim", ` ${BOX.horizontal.repeat(Math.max(0, width - 4))}`));
836
+ const elapsed = formatFleetElapsed((run.completedAt ?? Date.now()) - run.startedAt);
837
+ lines.push(this.field("Status", this.theme.fg(section.color, run.status), width));
838
+ lines.push(
839
+ this.field("Progress", this.theme.fg("text", `${run.doneCount}/${run.totalCount} agent${run.totalCount === 1 ? "" : "s"}`), width),
840
+ );
841
+ lines.push(this.field("Elapsed", this.theme.fg("text", elapsed), width));
842
+ lines.push(this.field("Tokens", this.theme.fg("text", formatFleetTokens(run.tokens)), width));
843
+ lines.push("");
844
+ lines.push(this.theme.fg("dim", " Enter to open the run · Esc to close"));
845
+ return lines.map(line => clip(line, width));
846
+ }
847
+
848
+ const record = entry.record;
849
+ const section = SECTIONS.find(s => s.id === sectionOfAgent(record)) ?? SECTIONS[0];
850
+ const nameLine =
851
+ `${this.theme.fg(section.color, this.glyphs.bullet)} ` + renderAgentName(record.type, this.theme, { bold: true });
852
+ lines.push(rightAlign(nameLine, this.theme.fg("dim", positionRaw), width));
853
+ lines.push(this.theme.fg("dim", ` ${BOX.horizontal.repeat(Math.max(0, width - 4))}`));
854
+ lines.push(this.field("Type", this.theme.fg("text", record.type), width));
855
+ lines.push(this.field("Task", this.theme.fg("muted", sanitizeRowText(record.description)), width));
856
+ lines.push(this.field("Status", this.theme.fg(section.color, record.status), width));
857
+
858
+ const { modelName, modelId, tags } = buildInvocationTags(record.invocation);
859
+ lines.push(this.field("Model", this.theme.fg("text", sanitizeRowText(modelId ?? modelName ?? "session default")), width));
860
+ const [thinking, ...flags] = splitThinkingTag(tags);
861
+ if (thinking) lines.push(this.field("Thinking", this.theme.fg("text", sanitizeRowText(thinking)), width));
862
+ if (flags.length > 0) lines.push(this.field("Flags", this.theme.fg("muted", flags.join(" · ")), width));
863
+
864
+ lines.push(this.field("Elapsed", this.theme.fg("text", formatFleetElapsed((record.completedAt ?? Date.now()) - record.startedAt)), width));
865
+ lines.push(this.field("Tokens", this.theme.fg("text", formatFleetTokens(getLifetimeTotal(record.lifetimeUsage))), width));
866
+ if (this.deps.showCost()) {
867
+ const cost = formatCost(getLifetimeCost(record.lifetimeUsage));
868
+ if (cost) lines.push(this.field("Cost", this.theme.fg("text", cost), width));
869
+ }
870
+ lines.push(this.field("Tools", this.theme.fg("text", String(record.toolUses)), width));
871
+ const activity = this.deps.activity.get(record.id);
872
+ if ((record.status === "running" || record.status === "queued") && activity && activity.activeTools.size > 0) {
873
+ lines.push(this.field("Now", this.theme.fg("accent", [...activity.activeTools.values()].join(", ")), width));
874
+ }
875
+ const usage = (record.session as { getContextUsage?: () => { percent?: number | null } | undefined } | undefined)
876
+ ?.getContextUsage?.();
877
+ if (typeof usage?.percent === "number") {
878
+ lines.push(this.field("Context", this.theme.fg("text", `${Math.round(usage.percent)}%`), width));
879
+ }
880
+ if (record.parentAgentId) lines.push(this.field("Parent", this.theme.fg("muted", record.parentAgentId), width));
881
+ const advisor = record.advisorStatus;
882
+ lines.push(this.field("Advisor", this.theme.fg("muted", formatAdvisorState(advisor)), width));
883
+ if (advisor && (advisor.state !== "off" || advisor.reviews > 0 || advisor.lastReviewAt !== undefined)) {
884
+ lines.push(this.field("Adv model", this.theme.fg("text", advisor.models.join(", ") || "—"), width));
885
+ lines.push(this.field("Reviews", this.theme.fg("text", String(advisor.reviews)), width));
886
+ lines.push(this.field("Last review", this.theme.fg("text", formatAdvisorLastReview(advisor)), width));
887
+ }
888
+
889
+ const tail = this.agentTail(record, width);
890
+ if (tail.length > 0) {
891
+ lines.push("");
892
+ lines.push(this.theme.fg("dim", record.status === "error" ? " Error" : record.status === "running" || record.status === "queued" ? " Activity" : " Result"));
893
+ lines.push(...tail);
894
+ }
895
+ lines.push("");
896
+ lines.push(this.theme.fg("dim", " Enter to open full view · Esc to close"));
897
+ return lines.map(line => clip(line, width));
898
+ }
899
+
900
+ private feedLine(event: FeedEvent, width: number, prefix = ""): string {
901
+ const mark = this.theme.fg(FEED_COLOR[event.kind], FEED_MARK[event.kind]);
902
+ return clip(` ${prefix}${mark} ${this.theme.fg(FEED_COLOR[event.kind], event.text)}`, width);
903
+ }
904
+
905
+ /** Card, then the live transcript filling the rest of the pane (newest at the bottom). */
906
+ private agentPane(rows: Row[], width: number, height: number): string[] {
907
+ const card = this.detailLines(rows, width);
908
+ const entry = this.selectedEntry(rows);
909
+ const room = height - card.length - 2;
910
+ if (entry?.kind !== "agent" || room < 2) return card.slice(0, height);
911
+ const tail = transcriptTail(entry.record, room);
912
+ if (tail.length === 0) return card;
913
+ return [
914
+ ...card,
915
+ "",
916
+ this.theme.fg("dim", clip(` ${BOX.horizontal} Live transcript ${BOX.horizontal.repeat(Math.max(0, width - 22))}`, width)),
917
+ ...tail.map(event => this.feedLine(event, width)),
918
+ ].slice(0, height);
919
+ }
920
+
921
+ /** Activity tab: newest events across agents (or the selected one), filtered by kind. */
922
+ private activityPane(rows: Row[], width: number, height: number): string[] {
923
+ const entry = this.selectedEntry(rows);
924
+ const scoped = this.activityScope === "selected" && entry?.kind === "agent";
925
+ const records = scoped
926
+ ? [entry.record]
927
+ : this.entriesOf(rows).flatMap(row => (row.entry.kind === "agent" ? [row.entry.record] : []));
928
+ const header =
929
+ `${this.theme.bold(this.theme.fg("accent", "Activity"))} ` +
930
+ this.theme.fg("dim", `${this.activityFilter} · ${scoped ? "selected agent" : "all agents"} · f filter · s scope · 1 back`);
931
+ const feed = activityFeed(records, { filter: this.activityFilter, limit: Math.max(0, height - 2) });
932
+ const lines = [clip(` ${header}`, width), this.theme.fg("dim", ` ${BOX.horizontal.repeat(Math.max(0, width - 4))}`)];
933
+ if (feed.length === 0) lines.push(this.theme.fg("muted", " No activity matches."));
934
+ for (const item of feed) {
935
+ lines.push(this.feedLine(item, width, `${this.theme.fg("dim", clockTime(item.at))} ${this.theme.fg("muted", item.agent)} `));
936
+ }
937
+ return lines.slice(0, height);
938
+ }
939
+
940
+ // ── frame ─────────────────────────────────────────────────────────────
941
+
942
+ private headerRight(entries: EntryRow[]): string {
943
+ const agents = entries.filter(row => row.entry.kind === "agent").length;
944
+ const workflows = entries.length - agents;
945
+ const parts = [`${agents} agent${agents === 1 ? "" : "s"}`];
946
+ if (workflows > 0) parts.push(`${workflows} workflow${workflows === 1 ? "" : "s"}`);
947
+ if (this.tree) parts.push("tree");
948
+ if (this.filter || this.filtering) parts.push(`/${this.filter}${this.filtering ? "▏" : ""}`);
949
+ return parts.join(" · ");
950
+ }
951
+
952
+ private footerLine(width: number): string {
953
+ const separator = this.theme.fg("dim", " · ");
954
+ if (this.filtering) {
955
+ return clip(` ${keyHint(this.theme, "type", "filter")}${separator}${keyHint(this.theme, "enter", "keep")}${separator}${keyHint(this.theme, "esc", "clear")}`, width);
956
+ }
957
+ const required = [
958
+ keyHint(this.theme, "↑↓", "move"),
959
+ keyHint(this.theme, "enter", "open"),
960
+ keyHint(this.theme, "d", "dismiss"),
961
+ ];
962
+ const close = keyHint(this.theme, "esc", "close");
963
+ const hub = [
964
+ keyHint(this.theme, "1/2", this.tab === "agents" ? "activity" : "agents"),
965
+ keyHint(this.theme, "t", "tree"),
966
+ keyHint(this.theme, "/", "filter"),
967
+ keyHint(this.theme, "x", "stop"),
968
+ keyHint(this.theme, "r", "resume"),
969
+ ];
970
+ // Hub hints are extras: they drop out first on a narrow frame.
971
+ const base = ` ${required.join(separator)}${separator}${close}`;
972
+ const full = ` ${required.join(separator)}${separator}${hub.join(separator)}${separator}${close}`;
973
+ return clip(visibleWidth(full) <= width ? full : base, width);
974
+ }
975
+
976
+ render(width: number): string[] {
977
+ const requested = Math.max(1, Math.floor(width));
978
+ const w = Math.max(MIN_RENDER_WIDTH, requested);
979
+ const lines = this.renderFrame(w);
980
+ // Narrower than the internal floor: lay out at the floor, clip back.
981
+ const output = requested >= w ? lines : lines.map(line => clip(line, requested));
982
+ // Belt and braces: the TUI rejects lines wider than the viewport.
983
+ return output.map(line => (visibleWidth(line) > requested ? clip(line, requested) : line));
984
+ }
985
+
986
+ private renderFrame(w: number): string[] {
987
+ const layout = this.layoutFor(w);
988
+
989
+ const rows = this.buildRows();
990
+ const entries = this.reconcile(rows);
991
+ this.ensureSelectionVisible(rows);
992
+
993
+ const detail = this.tab === "activity"
994
+ ? this.activityPane(rows, layout.bodyWidth, layout.bodyHeight)
995
+ : this.agentPane(rows, layout.bodyWidth, layout.bodyHeight);
996
+
997
+ const lines: string[] = [];
998
+ lines.push(topRule(this.theme, w, "Subagents", this.headerRight(entries)));
999
+ lines.push(contentRow(this.theme, "", w));
1000
+ lines.push(
1001
+ layout.twoPane ? openSplit(this.theme, w, "Fleet", layout.leftWidth) : divider(this.theme, w),
1002
+ );
1003
+
1004
+ const windowed = rows.slice(this.windowStart, this.windowStart + layout.bodyHeight);
1005
+ for (let i = 0; i < layout.bodyHeight; i++) {
1006
+ const right = detail[i] ?? "";
1007
+ if (!layout.twoPane) {
1008
+ lines.push(contentRow(this.theme, right, w));
1009
+ continue;
1010
+ }
1011
+ const row = windowed[i];
1012
+ const left = row === undefined
1013
+ ? ""
1014
+ : row.kind === "section"
1015
+ ? this.renderSectionRow(row, layout.leftWidth)
1016
+ : this.renderEntryRow(row, layout.leftWidth);
1017
+ lines.push(splitRow(this.theme, left, right, w, layout.leftWidth));
1018
+ }
1019
+
1020
+ lines.push(
1021
+ layout.twoPane ? closeSplit(this.theme, w, layout.leftWidth) : divider(this.theme, w),
1022
+ );
1023
+ lines.push(contentRow(this.theme, this.footerLine(w - 2 * (INSET + 1)), w));
1024
+ lines.push(bottomRule(this.theme, w));
1025
+ return lines.map(line => (visibleWidth(line) > w ? clip(line, w) : line));
1026
+ }
1027
+
1028
+ invalidate(): void {
1029
+ this.layout = undefined;
1030
+ }
1031
+
1032
+ dispose(): void {
1033
+ this.closed = true;
1034
+ clearInterval(this.timer);
1035
+ }
1036
+ }
1037
+
1038
+ // ─── small helpers ───────────────────────────────────────────────────────────
1039
+
1040
+ function errorMessage(error: unknown): string {
1041
+ return error instanceof Error ? error.message : String(error);
1042
+ }
1043
+
1044
+ /** Pull `thinking: x` out of the invocation tags; the rest are plain flags. */
1045
+ function splitThinkingTag(tags: readonly string[]): [thinking: string | undefined, flags: string[]] {
1046
+ const thinking = tags.find(tag => tag.startsWith("thinking: "));
1047
+ return [thinking ? thinking.slice("thinking: ".length) : undefined, tags.filter(tag => !tag.startsWith("thinking: "))];
1048
+ }