@timmyjl12/pi-subagents 0.0.0-stage → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/CHANGELOG.md +827 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1079 -2
  5. package/SECURITY.md +97 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/active-agents-prompt.d.ts +18 -0
  9. package/dist/active-agents-prompt.js +34 -0
  10. package/dist/advisor-status.d.ts +16 -0
  11. package/dist/advisor-status.js +74 -0
  12. package/dist/agent-color.d.ts +35 -0
  13. package/dist/agent-color.js +123 -0
  14. package/dist/agent-file-toggle.d.ts +125 -0
  15. package/dist/agent-file-toggle.js +264 -0
  16. package/dist/agent-manager.d.ts +485 -0
  17. package/dist/agent-manager.js +1380 -0
  18. package/dist/agent-runner.d.ts +319 -0
  19. package/dist/agent-runner.js +1128 -0
  20. package/dist/agent-types.d.ts +119 -0
  21. package/dist/agent-types.js +286 -0
  22. package/dist/child-context.d.ts +15 -0
  23. package/dist/child-context.js +181 -0
  24. package/dist/child-session-shutdown.d.ts +3 -0
  25. package/dist/child-session-shutdown.js +48 -0
  26. package/dist/context.d.ts +12 -0
  27. package/dist/context.js +56 -0
  28. package/dist/cross-extension-rpc.d.ts +66 -0
  29. package/dist/cross-extension-rpc.js +138 -0
  30. package/dist/custom-agents.d.ts +54 -0
  31. package/dist/custom-agents.js +386 -0
  32. package/dist/default-agents.d.ts +7 -0
  33. package/dist/default-agents.js +125 -0
  34. package/dist/enabled-models.d.ts +49 -0
  35. package/dist/enabled-models.js +145 -0
  36. package/dist/env.d.ts +6 -0
  37. package/dist/env.js +28 -0
  38. package/dist/error-log.d.ts +58 -0
  39. package/dist/error-log.js +168 -0
  40. package/dist/group-join.d.ts +32 -0
  41. package/dist/group-join.js +116 -0
  42. package/dist/index.d.ts +52 -0
  43. package/dist/index.js +3896 -0
  44. package/dist/invocation-config.d.ts +137 -0
  45. package/dist/invocation-config.js +129 -0
  46. package/dist/memory.d.ts +53 -0
  47. package/dist/memory.js +165 -0
  48. package/dist/mention-clone.d.ts +87 -0
  49. package/dist/mention-clone.js +178 -0
  50. package/dist/mention.d.ts +81 -0
  51. package/dist/mention.js +131 -0
  52. package/dist/model-resolver.d.ts +36 -0
  53. package/dist/model-resolver.js +95 -0
  54. package/dist/model-scope.d.ts +49 -0
  55. package/dist/model-scope.js +48 -0
  56. package/dist/nested-tools.d.ts +55 -0
  57. package/dist/nested-tools.js +299 -0
  58. package/dist/output-diagnostics.d.ts +11 -0
  59. package/dist/output-diagnostics.js +64 -0
  60. package/dist/output-file.d.ts +53 -0
  61. package/dist/output-file.js +248 -0
  62. package/dist/prompts.d.ts +61 -0
  63. package/dist/prompts.js +94 -0
  64. package/dist/recovery.d.ts +56 -0
  65. package/dist/recovery.js +341 -0
  66. package/dist/schedule-store.d.ts +44 -0
  67. package/dist/schedule-store.js +210 -0
  68. package/dist/schedule.d.ts +109 -0
  69. package/dist/schedule.js +359 -0
  70. package/dist/settings.d.ts +360 -0
  71. package/dist/settings.js +251 -0
  72. package/dist/skill-loader.d.ts +24 -0
  73. package/dist/skill-loader.js +93 -0
  74. package/dist/standalone-fallback.d.ts +30 -0
  75. package/dist/standalone-fallback.js +239 -0
  76. package/dist/status-note.d.ts +61 -0
  77. package/dist/status-note.js +85 -0
  78. package/dist/structured-output.d.ts +61 -0
  79. package/dist/structured-output.js +112 -0
  80. package/dist/terminal-progress.d.ts +115 -0
  81. package/dist/terminal-progress.js +206 -0
  82. package/dist/types.d.ts +382 -0
  83. package/dist/types.js +5 -0
  84. package/dist/ui/agent-mention.d.ts +82 -0
  85. package/dist/ui/agent-mention.js +187 -0
  86. package/dist/ui/agent-widget.d.ts +235 -0
  87. package/dist/ui/agent-widget.js +652 -0
  88. package/dist/ui/conversation-viewer.d.ts +105 -0
  89. package/dist/ui/conversation-viewer.js +540 -0
  90. package/dist/ui/fleet-list.d.ts +183 -0
  91. package/dist/ui/fleet-list.js +494 -0
  92. package/dist/ui/fleet-overlay.d.ts +172 -0
  93. package/dist/ui/fleet-overlay.js +691 -0
  94. package/dist/ui/native-transcript.d.ts +33 -0
  95. package/dist/ui/native-transcript.js +230 -0
  96. package/dist/ui/schedule-menu.d.ts +16 -0
  97. package/dist/ui/schedule-menu.js +94 -0
  98. package/dist/ui/select-item.d.ts +27 -0
  99. package/dist/ui/select-item.js +34 -0
  100. package/dist/ui/tool-progress.d.ts +22 -0
  101. package/dist/ui/tool-progress.js +56 -0
  102. package/dist/ui/viewer-keys.d.ts +20 -0
  103. package/dist/ui/viewer-keys.js +17 -0
  104. package/dist/ui/workflow-card.d.ts +175 -0
  105. package/dist/ui/workflow-card.js +332 -0
  106. package/dist/ui/workflow-dialog.d.ts +305 -0
  107. package/dist/ui/workflow-dialog.js +843 -0
  108. package/dist/ui/workflow-menu.d.ts +60 -0
  109. package/dist/ui/workflow-menu.js +147 -0
  110. package/dist/usage.d.ts +135 -0
  111. package/dist/usage.js +120 -0
  112. package/dist/workflow/collisions.d.ts +95 -0
  113. package/dist/workflow/collisions.js +88 -0
  114. package/dist/workflow/entry.d.ts +32 -0
  115. package/dist/workflow/entry.js +29 -0
  116. package/dist/workflow/host.d.ts +62 -0
  117. package/dist/workflow/host.js +363 -0
  118. package/dist/workflow/journal.d.ts +97 -0
  119. package/dist/workflow/journal.js +120 -0
  120. package/dist/workflow/json-schema.d.ts +51 -0
  121. package/dist/workflow/json-schema.js +111 -0
  122. package/dist/workflow/meta.d.ts +67 -0
  123. package/dist/workflow/meta.js +317 -0
  124. package/dist/workflow/progress.d.ts +224 -0
  125. package/dist/workflow/progress.js +361 -0
  126. package/dist/workflow/runtime.d.ts +334 -0
  127. package/dist/workflow/runtime.js +830 -0
  128. package/dist/workflow/saved.d.ts +90 -0
  129. package/dist/workflow/saved.js +203 -0
  130. package/dist/workflow/task.d.ts +136 -0
  131. package/dist/workflow/task.js +207 -0
  132. package/dist/workflow/tool-description.d.ts +38 -0
  133. package/dist/workflow/tool-description.js +199 -0
  134. package/dist/workflow/worker-source.d.ts +47 -0
  135. package/dist/workflow/worker-source.js +778 -0
  136. package/dist/worktree.d.ts +52 -0
  137. package/dist/worktree.js +164 -0
  138. package/dist/xml.d.ts +10 -0
  139. package/dist/xml.js +12 -0
  140. package/docs/FORK.md +40 -0
  141. package/docs/recovery.md +62 -0
  142. package/docs/rpc.md +189 -0
  143. package/docs/workflows.md +437 -0
  144. package/examples/agent-tool-description.md +43 -0
  145. package/examples/workflows/compose.js +51 -0
  146. package/examples/workflows/fan-out-audit.js +47 -0
  147. package/examples/workflows/gated-fix.js +60 -0
  148. package/examples/workflows/lib/count-child.js +27 -0
  149. package/examples/workflows/review-panel.js +63 -0
  150. package/examples/workflows/structured-findings.js +78 -0
  151. package/package.json +75 -6
  152. package/src/abortable.ts +43 -0
  153. package/src/active-agents-prompt.ts +39 -0
  154. package/src/advisor-status.ts +74 -0
  155. package/src/agent-color.ts +161 -0
  156. package/src/agent-file-toggle.ts +273 -0
  157. package/src/agent-manager.ts +1601 -0
  158. package/src/agent-runner.ts +1372 -0
  159. package/src/agent-types.ts +345 -0
  160. package/src/child-context.ts +173 -0
  161. package/src/child-session-shutdown.ts +46 -0
  162. package/src/context.ts +58 -0
  163. package/src/cross-extension-rpc.ts +198 -0
  164. package/src/custom-agents.ts +417 -0
  165. package/src/default-agents.ts +129 -0
  166. package/src/enabled-models.ts +180 -0
  167. package/src/env.ts +33 -0
  168. package/src/error-log.ts +193 -0
  169. package/src/group-join.ts +141 -0
  170. package/src/index.ts +4218 -0
  171. package/src/invocation-config.ts +230 -0
  172. package/src/memory.ts +179 -0
  173. package/src/mention-clone.ts +221 -0
  174. package/src/mention.ts +141 -0
  175. package/src/model-resolver.ts +118 -0
  176. package/src/model-scope.ts +70 -0
  177. package/src/nested-tools.ts +422 -0
  178. package/src/output-diagnostics.ts +68 -0
  179. package/src/output-file.ts +258 -0
  180. package/src/prompts.ts +151 -0
  181. package/src/recovery.ts +320 -0
  182. package/src/schedule-store.ts +201 -0
  183. package/src/schedule.ts +386 -0
  184. package/src/settings.ts +587 -0
  185. package/src/skill-loader.ts +102 -0
  186. package/src/standalone-fallback.ts +195 -0
  187. package/src/status-note.ts +90 -0
  188. package/src/structured-output.ts +130 -0
  189. package/src/terminal-progress.ts +215 -0
  190. package/src/types.ts +394 -0
  191. package/src/ui/agent-mention.ts +216 -0
  192. package/src/ui/agent-widget.ts +732 -0
  193. package/src/ui/conversation-viewer.ts +523 -0
  194. package/src/ui/fleet-list.ts +563 -0
  195. package/src/ui/fleet-overlay.ts +847 -0
  196. package/src/ui/native-transcript.ts +220 -0
  197. package/src/ui/schedule-menu.ts +105 -0
  198. package/src/ui/select-item.ts +45 -0
  199. package/src/ui/tool-progress.ts +67 -0
  200. package/src/ui/viewer-keys.ts +39 -0
  201. package/src/ui/workflow-card.ts +470 -0
  202. package/src/ui/workflow-dialog.ts +1115 -0
  203. package/src/ui/workflow-menu.ts +193 -0
  204. package/src/usage.ts +167 -0
  205. package/src/workflow/collisions.ts +123 -0
  206. package/src/workflow/entry.ts +47 -0
  207. package/src/workflow/host.ts +404 -0
  208. package/src/workflow/journal.ts +164 -0
  209. package/src/workflow/json-schema.ts +128 -0
  210. package/src/workflow/meta.ts +325 -0
  211. package/src/workflow/progress.ts +550 -0
  212. package/src/workflow/runtime.ts +1219 -0
  213. package/src/workflow/saved.ts +217 -0
  214. package/src/workflow/task.ts +302 -0
  215. package/src/workflow/tool-description.ts +200 -0
  216. package/src/workflow/worker-source.ts +781 -0
  217. package/src/worktree.ts +205 -0
  218. package/src/xml.ts +13 -0
@@ -0,0 +1,563 @@
1
+ /**
2
+ * fleet-list.ts — Claude Code-style "FleetView" list rendered below the editor.
3
+ *
4
+ * Shows `main` + each running/queued subagent as a navigable list. Pressing ↓ (or
5
+ * ←) at an empty prompt activates the list; ↑/↓ move the selection (filled ● marker),
6
+ * Enter opens the selected agent's live conversation overlay, Esc returns to the prompt.
7
+ * A viewer stays open when its agent finishes; finished agents linger briefly in the list.
8
+ *
9
+ * Mechanics (see plan): the list is a `belowEditor` widget (render-only), and ALL key
10
+ * handling goes through `onTerminalInput` — which fires before the focused editor and
11
+ * can `consume` keys — gated on `getEditorText() === ""` so normal typing is untouched.
12
+ */
13
+
14
+ import { Editor, isKeyRelease, Key, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
15
+ import { hasAgentBadge, renderAgentName } from "../agent-color.js";
16
+ import { type AgentManager, isTopLevelAgent } from "../agent-manager.js";
17
+ import type { AgentRecord } from "../types.js";
18
+ import { getLifetimeCost, getLifetimeTotal } from "../usage.js";
19
+ import { type AgentActivity, formatCost, type Theme } from "./agent-widget.js";
20
+
21
+ /** Widget key for the below-editor fleet list. */
22
+ const FLEET_KEY = "fleet";
23
+ /** Max agent rows shown at once; extras collapse into a "↓ N more" indicator. */
24
+ const MAX_AGENT_ROWS = 5;
25
+ /** Re-render cadence so elapsed/token stats tick while agents run. */
26
+ const TICK_MS = 200;
27
+ /** How long a finished agent lingers in the list before it drops out. */
28
+ const FINISHED_LINGER_MS = 4000;
29
+
30
+ /** Minimal UI surface the FleetView needs from `ctx.ui` (structural subset). */
31
+ export type FleetUICtx = {
32
+ setWidget(
33
+ key: string,
34
+ content: undefined | ((tui: any, theme: Theme) => { render(width: number): string[]; invalidate(): void; dispose?(): void }),
35
+ options?: { placement?: "aboveEditor" | "belowEditor" },
36
+ ): void;
37
+ onTerminalInput(handler: (data: string) => { consume?: boolean; data?: string } | undefined): () => void;
38
+ getEditorText(): string;
39
+ notify(message: string, type?: "info" | "warning" | "error"): void;
40
+ custom<T>(
41
+ factory: (tui: any, theme: Theme, keybindings: any, done: (result: T) => void) => { render(width: number): string[]; invalidate(): void; dispose?(): void },
42
+ options?: { overlay?: boolean; overlayOptions?: unknown; onHandle?: (handle: unknown) => void },
43
+ ): Promise<T>;
44
+ };
45
+
46
+ /**
47
+ * A workflow run, as the fleet list needs to see it.
48
+ *
49
+ * Narrow on purpose: the list knows nothing about `WorkflowTask`, the runtime
50
+ * or the dialog, so it stays as testable as it was when it only held agents.
51
+ * The extension maps its tasks into this shape and injects an opener.
52
+ */
53
+ export interface FleetWorkflow {
54
+ id: string;
55
+ /** The `meta.name` of the run, or its id when the script named nothing. */
56
+ name: string;
57
+ status: "running" | "completed" | "failed" | "killed" | "paused";
58
+ doneCount: number;
59
+ totalCount: number;
60
+ startedAt: number;
61
+ /** Set once the run settles, which is what freezes its clock. */
62
+ completedAt?: number;
63
+ tokens: number;
64
+ }
65
+
66
+ type MainEntry = { kind: "main" };
67
+ type AgentEntry = { kind: "agent"; record: AgentRecord };
68
+ type WorkflowEntry = { kind: "workflow"; workflow: FleetWorkflow };
69
+ type FleetEntry = MainEntry | WorkflowEntry | AgentEntry;
70
+
71
+ function entryKey(entry: FleetEntry): string {
72
+ return entry.kind === "agent" ? `agent:${entry.record.id}`
73
+ : entry.kind === "workflow" ? `workflow:${entry.workflow.id}` : "main";
74
+ }
75
+
76
+ /** `11s` — integer seconds, no decimal/suffix (matches Claude Code, unlike formatMs). */
77
+ export function formatFleetElapsed(ms: number): string {
78
+ return `${Math.max(0, Math.round(ms / 1000))}s`;
79
+ }
80
+
81
+ /** `↓ 13.1k tokens` — down-arrow prefix, compact magnitude, plural "tokens". */
82
+ export function formatFleetTokens(count: number): string {
83
+ let compact: string;
84
+ if (count >= 1_000_000) compact = `${(count / 1_000_000).toFixed(1)}M`;
85
+ else if (count >= 1_000) compact = `${(count / 1_000).toFixed(1)}k`;
86
+ else compact = `${count}`;
87
+ return `↓ ${compact} tokens`;
88
+ }
89
+
90
+ /**
91
+ * Place `right` flush to `width`, truncating `left` first so the stats survive.
92
+ * The final clamp guarantees the line never exceeds `width` (which would wrap and
93
+ * desync pi's line-diff → flicker) even on a terminal too narrow for the stats.
94
+ */
95
+ function rightAlign(left: string, right: string, width: number): string {
96
+ const rightW = visibleWidth(right);
97
+ const maxLeft = Math.max(0, width - rightW - 1);
98
+ const leftClamped = truncateToWidth(left, maxLeft);
99
+ const gap = Math.max(1, width - visibleWidth(leftClamped) - rightW);
100
+ return truncateToWidth(leftClamped + " ".repeat(gap) + right, width);
101
+ }
102
+
103
+ export class FleetList {
104
+ private ui: FleetUICtx | undefined;
105
+ private tui: any | undefined;
106
+ private inputUnsub: (() => void) | undefined;
107
+ private widgetRegistered = false;
108
+ private timer: ReturnType<typeof setInterval> | undefined;
109
+
110
+ private enabled = true;
111
+ /** Whether arrow keys currently navigate the list (vs. flow to the editor). */
112
+ private active = false;
113
+ /** 0 = `main`, 1..N = workflows/agents; also the fallback if the row disappears. */
114
+ private selectedIndex = 0;
115
+ private selectedKey = "main";
116
+ /** Set while a conversation overlay is open; calling it closes the overlay. */
117
+ private viewerClose: (() => void) | undefined;
118
+ private viewingAgentId: string | undefined;
119
+ private openAgent: ((record: AgentRecord, onCloseReady: (close: () => void) => void) => Promise<void>) | undefined;
120
+ /**
121
+ * Injected by the extension; opens the full two-pane fleet overlay. When set,
122
+ * ← at an empty prompt opens that overlay instead of engaging inline
123
+ * navigation (↓ still does). Without it ← keeps its legacy activator role, so
124
+ * a host that only wires the list sees no behavior change.
125
+ */
126
+ private overlayOpener: (() => void) | undefined;
127
+ /** Injected by the extension; absent until workflows are wired (or at all). */
128
+ private workflowSource: (() => readonly FleetWorkflow[]) | undefined;
129
+ private openWorkflow: ((id: string) => Promise<void> | void) | undefined;
130
+ /**
131
+ * Set while the workflow inspector is up.
132
+ *
133
+ * It does the two jobs `viewerClose` does for an agent's overlay — keep the
134
+ * list out of the dialog's keys, and remember which row to come back to —
135
+ * minus the close handle, because that overlay belongs to the extension.
136
+ */
137
+ private viewingWorkflowId: string | undefined;
138
+
139
+ constructor(
140
+ private manager: AgentManager,
141
+ _agentActivity: Map<string, AgentActivity>,
142
+ /**
143
+ * Read live at render time. Whether each row shows an estimated cost after
144
+ * its token count. Defaults to off — the extension supplies the user's
145
+ * `showCost` setting.
146
+ */
147
+ private showCost: () => boolean = () => false,
148
+ ) {}
149
+
150
+ /** One extension-owned opener for fleet, menu, and workflow entry points. */
151
+ setAgentOpener(open: (record: AgentRecord, onCloseReady: (close: () => void) => void) => Promise<void>): void {
152
+ this.openAgent = open;
153
+ }
154
+
155
+ /** Wire the two-pane overlay as what ← opens (see the field's note). */
156
+ setOverlayOpener(open: () => void): void {
157
+ this.overlayOpener = open;
158
+ }
159
+
160
+ // ---- Lifecycle ----
161
+
162
+ setEnabled(enabled: boolean): void {
163
+ if (enabled === this.enabled) return;
164
+ this.enabled = enabled;
165
+ if (!enabled) this.active = false;
166
+ this.update();
167
+ }
168
+
169
+ /** Capture the UI context and (re)register the global input handler. */
170
+ setUICtx(ui: FleetUICtx): void {
171
+ if (ui === this.ui) return;
172
+ this.inputUnsub?.();
173
+ this.ui = ui;
174
+ this.widgetRegistered = false;
175
+ this.tui = undefined;
176
+ this.inputUnsub = ui.onTerminalInput(data => this.handleKey(data));
177
+ }
178
+
179
+ /** Ensure the re-render timer is running (called when an agent spawns). */
180
+ ensureTimer(): void {
181
+ if (!this.timer) this.timer = setInterval(() => this.update(), TICK_MS);
182
+ }
183
+
184
+ /**
185
+ * Called when an agent finishes. The viewer (if open on it) stays open so the
186
+ * final output remains readable, and the row lingers in the list — just refresh.
187
+ */
188
+ onAgentFinished(_id: string): void {
189
+ this.update();
190
+ }
191
+
192
+ dispose(): void {
193
+ if (this.timer) { clearInterval(this.timer); this.timer = undefined; }
194
+ this.inputUnsub?.();
195
+ this.inputUnsub = undefined;
196
+ if (this.viewerClose) { this.viewerClose(); this.viewerClose = undefined; }
197
+ this.viewingAgentId = undefined;
198
+ // No handle to close the workflow inspector with, but the list is going
199
+ // away — leaving the id set would keep it swallowing input forever.
200
+ this.viewingWorkflowId = undefined;
201
+ if (this.ui && this.widgetRegistered) this.ui.setWidget(FLEET_KEY, undefined);
202
+ this.widgetRegistered = false;
203
+ this.tui = undefined;
204
+ this.active = false;
205
+ // Null last so a `viewerClose()` microtask above can't re-register the widget.
206
+ this.ui = undefined;
207
+ }
208
+
209
+ /** Re-register/refresh the below-editor widget; clears it when nothing remains. */
210
+ update(): void {
211
+ if (!this.ui) return;
212
+ // A run with no agents of its own left in the list is still worth a row —
213
+ // it is the thing the user opens to see what its children did. Read off the
214
+ // roster for the same reason activation does: two counts of "is there
215
+ // anything here" drifted apart once before.
216
+ const roster = this.enabled ? this.roster() : [{ kind: "main" as const }];
217
+ const hasRows = roster.length > 1;
218
+
219
+ if (!hasRows) {
220
+ if (this.widgetRegistered) {
221
+ this.ui.setWidget(FLEET_KEY, undefined);
222
+ this.widgetRegistered = false;
223
+ this.tui = undefined;
224
+ }
225
+ if (this.timer) { clearInterval(this.timer); this.timer = undefined; }
226
+ this.active = false;
227
+ this.select(0, roster);
228
+ return;
229
+ }
230
+
231
+ this.clampSelection(roster);
232
+ this.ensureTimer(); // keep stats ticking whenever the list is shown (e.g. after a re-enable)
233
+
234
+ if (!this.widgetRegistered) {
235
+ this.ui.setWidget(FLEET_KEY, (tui, theme) => {
236
+ this.tui = tui;
237
+ return {
238
+ render: (w: number) => this.renderBar(w, theme),
239
+ invalidate: () => { this.widgetRegistered = false; this.tui = undefined; },
240
+ };
241
+ }, { placement: "belowEditor" });
242
+ this.widgetRegistered = true;
243
+ } else {
244
+ this.tui?.requestRender();
245
+ }
246
+ }
247
+
248
+ // ---- Roster ----
249
+
250
+ /**
251
+ * Agents shown in the list, ordered earliest-launched first so the ones you
252
+ * started sooner sit at the top. Every row is openable (has a session), so Enter
253
+ * never dead-ends. Included: running/queued, plus the agent currently being
254
+ * viewed, plus recently-finished ones (they linger briefly before dropping out).
255
+ * Pending agents with no session yet are hidden until they start.
256
+ * (`listAgents()` is newest-first, so we re-sort.)
257
+ */
258
+ private agentRecords(): AgentRecord[] {
259
+ const now = Date.now();
260
+ return this.manager.listAgents()
261
+ .filter(a => isTopLevelAgent(a) && a.session && (
262
+ a.status === "running" || a.status === "queued"
263
+ || a.id === this.viewingAgentId
264
+ || (a.completedAt != null && now - a.completedAt < FINISHED_LINGER_MS)
265
+ ))
266
+ .sort((a, b) => a.startedAt - b.startedAt);
267
+ }
268
+
269
+ /**
270
+ * Wire workflow runs into the list.
271
+ *
272
+ * Injected rather than constructed here because the fleet list predates
273
+ * workflows and must keep working without them — a session with the feature
274
+ * switched off never calls this, and the roster is agents-only exactly as
275
+ * before.
276
+ */
277
+ setWorkflowSource(
278
+ source: () => readonly FleetWorkflow[],
279
+ open: (id: string) => Promise<void> | void,
280
+ ): void {
281
+ this.workflowSource = source;
282
+ this.openWorkflow = open;
283
+ }
284
+
285
+ /** Live runs, plus recently settled ones — the same linger the agents get. */
286
+ private workflows(): FleetWorkflow[] {
287
+ if (!this.workflowSource) return [];
288
+ const now = Date.now();
289
+ return [...this.workflowSource()]
290
+ .filter(run =>
291
+ run.status === "running"
292
+ || run.status === "paused"
293
+ || (run.completedAt != null && now - run.completedAt < FINISHED_LINGER_MS)
294
+ )
295
+ .sort((a, b) => a.startedAt - b.startedAt);
296
+ }
297
+
298
+ /**
299
+ * Runs sit above the agents rather than interleaved by start time: a run owns
300
+ * most of the agents under it, so listing the container first is what makes
301
+ * the list read as a hierarchy rather than a shuffle.
302
+ */
303
+ private roster(): FleetEntry[] {
304
+ return [
305
+ { kind: "main" },
306
+ ...this.workflows().map(workflow => ({ kind: "workflow" as const, workflow })),
307
+ ...this.agentRecords().map(record => ({ kind: "agent" as const, record })),
308
+ ];
309
+ }
310
+
311
+ private select(index: number, roster = this.roster()): void {
312
+ this.selectedIndex = Math.max(0, Math.min(index, roster.length - 1));
313
+ this.selectedKey = entryKey(roster[this.selectedIndex]);
314
+ }
315
+
316
+ private clampSelection(roster: FleetEntry[]): void {
317
+ const index = roster.findIndex(entry => entryKey(entry) === this.selectedKey);
318
+ // Keep identity across inserts/reorders; a removed row falls to the same
319
+ // position (its successor), or the preceding row when it was last.
320
+ this.select(index >= 0 ? index : this.selectedIndex, roster);
321
+ }
322
+
323
+ // ---- Key handling ----
324
+
325
+ /** Returns `{consume:true}` to swallow a key, or undefined to let it through. */
326
+ handleKey(data: string): { consume?: boolean; data?: string } | undefined {
327
+ if (!this.enabled || !this.ui) return undefined;
328
+ // Input listeners receive BOTH key-press and key-release (the kitty protocol
329
+ // emits both, and matchesKey matches either) — act on press only, or every
330
+ // tap would move/fire twice. Repeats still pass through for held-key nav.
331
+ if (isKeyRelease(data)) return undefined;
332
+ // While an overlay is open, let it own all input. Checked before the focus
333
+ // test below, which would otherwise read the dialog holding the keyboard as
334
+ // "the user left the list" and reset the selection out from under it.
335
+ if (this.viewingAgentId || this.viewingWorkflowId) return undefined;
336
+ // Input listeners fire BEFORE the focused component, and dialogs
337
+ // (ctx.ui.select/confirm/input, pi's own menus) swap the prompt editor out
338
+ // while getEditorText() still reads the detached — empty — editor. So when
339
+ // anything but the editor owns the keyboard, stay out of its keys (#123).
340
+ if (!this.editorHasFocus()) {
341
+ if (this.active) this.deactivate();
342
+ return undefined;
343
+ }
344
+
345
+ if (!this.active) {
346
+ // ← opens the two-pane overlay when the host wired it; the overlay is the
347
+ // fuller surface (detail card, settled history), so inline activation
348
+ // falls to ↓ alone. Without an opener ← stays an activator, exactly as ↓.
349
+ if (matchesKey(data, "left") && this.overlayOpener) {
350
+ if (this.roster().length > 1 && this.ui.getEditorText() === "") {
351
+ this.overlayOpener();
352
+ return { consume: true };
353
+ }
354
+ return undefined;
355
+ }
356
+ // Activate: ↓ at an empty prompt moves focus into the list.
357
+ const isActivator = matchesKey(data, "down") || (matchesKey(data, "left") && !this.overlayOpener);
358
+ // Gated on the roster, not the agents: a session whose only row is a
359
+ // workflow run still has somewhere to go, and requiring an agent would
360
+ // render the row but refuse to move into it.
361
+ if (isActivator && this.roster().length > 1 && this.ui.getEditorText() === "") {
362
+ this.active = true;
363
+ this.select(0);
364
+ this.update();
365
+ return { consume: true };
366
+ }
367
+ return undefined;
368
+ }
369
+
370
+ // Reconcile even before the next timer tick/render, including on Enter.
371
+ const roster = this.roster();
372
+ this.clampSelection(roster);
373
+ // Active — arrows navigate, Enter opens, Esc / Up-past-top exits.
374
+ if (matchesKey(data, "down")) {
375
+ this.select(this.selectedIndex + 1, roster);
376
+ this.update();
377
+ return { consume: true };
378
+ }
379
+ if (matchesKey(data, "up")) {
380
+ if (this.selectedIndex === 0) { this.deactivate(); return { consume: true }; }
381
+ this.select(this.selectedIndex - 1, roster);
382
+ this.update();
383
+ return { consume: true };
384
+ }
385
+ if (matchesKey(data, "escape")) { this.deactivate(); return { consume: true }; }
386
+ if (matchesKey(data, Key.enter)) { this.openSelected(); return { consume: true }; }
387
+ // While navigating, ← reaches for the fuller surface too: leave the inline
388
+ // list and open the overlay. The editor holds no text here (activation
389
+ // requires an empty prompt), so nothing typed is disturbed either way.
390
+ if (matchesKey(data, "left") && this.overlayOpener) {
391
+ this.deactivate();
392
+ this.overlayOpener();
393
+ return { consume: true };
394
+ }
395
+
396
+ // Any other key cancels navigation and flows to the editor.
397
+ this.deactivate();
398
+ return undefined;
399
+ }
400
+
401
+ /**
402
+ * True when pi's prompt editor owns the keyboard. pi's editor is an `Editor`
403
+ * subclass (CustomEditor) while every dialog/selector is not, and the loader
404
+ * aliases pi-tui to pi's own copy, so `instanceof` is a reliable identity
405
+ * check. Prefer Pi's public accessor; the fallback supports older UI test
406
+ * hosts. Unknowable focus counts as the editor so activation keeps working.
407
+ */
408
+ private editorHasFocus(): boolean {
409
+ const focused = this.tui?.getFocusedComponent?.() ?? this.tui?.focusedComponent;
410
+ return focused == null || focused instanceof Editor;
411
+ }
412
+
413
+ private deactivate(): void {
414
+ this.active = false;
415
+ this.select(0);
416
+ this.update();
417
+ }
418
+
419
+ private openSelected(): void {
420
+ const roster = this.roster();
421
+ this.clampSelection(roster);
422
+ const entry = roster[this.selectedIndex];
423
+ if (!entry || entry.kind === "main") {
424
+ // `main` = return to the prompt; the native transcript is already shown.
425
+ this.deactivate();
426
+ return;
427
+ }
428
+ if (entry.kind === "workflow") {
429
+ // The extension owns this overlay and closes it, so there is no
430
+ // `viewerClose` to hold — but the list still has to know one is up, and
431
+ // still has to put the cursor back on the run when it comes down.
432
+ this.viewingWorkflowId = entry.workflow.id;
433
+ void Promise.resolve(this.openWorkflow?.(entry.workflow.id)).then(
434
+ () => this.clearViewer(),
435
+ () => this.clearViewer(),
436
+ );
437
+ return;
438
+ }
439
+ const record = entry.record;
440
+ if (!this.ui) return;
441
+ if (!record.session) {
442
+ this.ui.notify(`Agent is ${record.status} — no session available.`, "info");
443
+ return;
444
+ }
445
+ if (!this.openAgent) {
446
+ this.ui.notify("Child conversation opener is unavailable.", "warning");
447
+ return;
448
+ }
449
+ this.viewingAgentId = record.id;
450
+ void this.openAgent(record, close => { this.viewerClose = close; }).then(
451
+ () => this.clearViewer(),
452
+ error => {
453
+ this.ui?.notify(`Could not open child: ${error instanceof Error ? error.message : String(error)}`, "error");
454
+ this.clearViewer();
455
+ },
456
+ );
457
+ }
458
+
459
+ /** Reset overlay state and return to the list (on close, auto-close, or error). */
460
+ private clearViewer(): void {
461
+ // Keep the cursor on the agent we were viewing — re-resolve by id so it
462
+ // still feels natural if the list reordered (an earlier agent finished)
463
+ // while the overlay was open. If that agent is gone, leave the index for
464
+ // update()'s clamp to settle.
465
+ const viewed = this.viewingAgentId !== undefined ? `agent:${this.viewingAgentId}`
466
+ : this.viewingWorkflowId !== undefined ? `workflow:${this.viewingWorkflowId}` : undefined;
467
+ if (viewed !== undefined) {
468
+ const roster = this.roster();
469
+ const idx = roster.findIndex(entry => entryKey(entry) === viewed);
470
+ if (idx >= 0) this.select(idx, roster);
471
+ }
472
+ this.viewerClose = undefined;
473
+ this.viewingAgentId = undefined;
474
+ this.viewingWorkflowId = undefined;
475
+ this.update();
476
+ }
477
+
478
+ // ---- Rendering ----
479
+
480
+ private renderBar(width: number, theme: Theme): string[] {
481
+ const roster = this.roster();
482
+ this.clampSelection(roster);
483
+ const rows = roster.slice(1) as (WorkflowEntry | AgentEntry)[];
484
+ if (rows.length === 0) return [];
485
+ const sel = this.selectedIndex;
486
+
487
+ const hint = this.active
488
+ ? "↑↓ select · enter view · esc back"
489
+ : "esc to interrupt · ← for agents · ↓ to manage";
490
+ const lines: string[] = [];
491
+ lines.push(truncateToWidth(" " + theme.fg("dim", hint), width));
492
+ lines.push("");
493
+ lines.push(truncateToWidth(` ${this.bullet(0, sel, theme)} main`, width));
494
+
495
+ // Window the rows so the selected one stays visible.
496
+ const visible = Math.min(MAX_AGENT_ROWS, rows.length);
497
+ const selRow = Math.max(0, sel - 1);
498
+ const start = selRow < visible ? 0 : selRow - visible + 1;
499
+ const hiddenBelow = rows.length - (start + visible);
500
+
501
+ if (start > 0) lines.push(rightAlign("", theme.fg("dim", `↑ ${start} more`), width));
502
+ for (let a = start; a < start + visible; a++) {
503
+ const row = rows[a];
504
+ lines.push(
505
+ row.kind === "workflow" ?
506
+ this.renderWorkflowRow(a + 1, sel, row.workflow, width, theme)
507
+ : this.renderAgentRow(a + 1, sel, row.record, width, theme),
508
+ );
509
+ }
510
+ if (hiddenBelow > 0) lines.push(rightAlign("", theme.fg("dim", `↓ ${hiddenBelow} more`), width));
511
+
512
+ return lines;
513
+ }
514
+
515
+ private bullet(rosterIndex: number, sel: number, theme: Theme): string {
516
+ return rosterIndex === sel ? theme.fg("accent", "●") : theme.fg("dim", "○");
517
+ }
518
+
519
+ /**
520
+ * A run's row. Shaped like an agent's — bullet, kind, name, stats flush right
521
+ * — so the two read as one list, with the agent count where an agent has its
522
+ * description and the same elapsed/token tail.
523
+ */
524
+ private renderWorkflowRow(
525
+ rosterIndex: number,
526
+ sel: number,
527
+ workflow: FleetWorkflow,
528
+ width: number,
529
+ theme: Theme,
530
+ ): string {
531
+ const selected = rosterIndex === sel;
532
+ const kind = theme.fg(selected ? "text" : "muted", "workflow");
533
+ const name = selected ? theme.fg("text", workflow.name) : workflow.name;
534
+ const left = ` ${this.bullet(rosterIndex, sel, theme)} ${kind} ${name}`;
535
+ // Frozen once the run settles, exactly as an agent's clock is.
536
+ const elapsed = (workflow.completedAt ?? Date.now()) - workflow.startedAt;
537
+ const agents = `${workflow.doneCount}/${workflow.totalCount} agent${workflow.totalCount === 1 ? "" : "s"}`;
538
+ const stats = `${agents} · ${formatFleetElapsed(elapsed)} · ${formatFleetTokens(workflow.tokens)}`;
539
+ return rightAlign(left, selected ? theme.fg("text", stats) : theme.fg("dim", stats), width);
540
+ }
541
+
542
+ private renderAgentRow(rosterIndex: number, sel: number, record: AgentRecord, width: number, theme: Theme): string {
543
+ // The selected row renders in the theme's primary text color so it reads as
544
+ // one selection (#230). A configured badge survives — Claude Code's FleetView
545
+ // keeps the agent color on the selected row too and only bolds it — which also
546
+ // keeps the row's width fixed as the selection moves.
547
+ const selected = rosterIndex === sel;
548
+ const name = renderAgentName(record.type, theme, selected
549
+ ? { fallbackColor: "text", bold: hasAgentBadge(record.type) }
550
+ : { fallbackColor: "muted" });
551
+ const description = selected ? theme.fg("text", record.description) : record.description;
552
+ const left = ` ${this.bullet(rosterIndex, sel, theme)} ${name} ${description}`;
553
+ // The record, not the activity tracker — see the note in AgentWidget's
554
+ // running line: only the record carries a nested child's spend, and only it
555
+ // outlives the agent.
556
+ const tokens = getLifetimeTotal(record.lifetimeUsage);
557
+ const elapsedMs = (record.completedAt ?? Date.now()) - record.startedAt; // freezes once finished
558
+ const cost = this.showCost() ? formatCost(getLifetimeCost(record.lifetimeUsage)) : "";
559
+ const stats = `${formatFleetElapsed(elapsedMs)} · ${formatFleetTokens(tokens)}${cost ? ` · ${cost}` : ""}`;
560
+ const right = selected ? theme.fg("text", stats) : theme.fg("dim", stats);
561
+ return rightAlign(left, right, width);
562
+ }
563
+ }