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