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