@diousk/pi-subagents-fast 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 (183) hide show
  1. package/CHANGELOG.md +808 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1034 -0
  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 +125 -0
  11. package/dist/agent-file-toggle.js +260 -0
  12. package/dist/agent-manager.d.ts +472 -0
  13. package/dist/agent-manager.js +1338 -0
  14. package/dist/agent-runner.d.ts +312 -0
  15. package/dist/agent-runner.js +1034 -0
  16. package/dist/agent-types.d.ts +119 -0
  17. package/dist/agent-types.js +286 -0
  18. package/dist/child-context.d.ts +2 -0
  19. package/dist/child-context.js +12 -0
  20. package/dist/context.d.ts +12 -0
  21. package/dist/context.js +56 -0
  22. package/dist/cross-extension-rpc.d.ts +66 -0
  23. package/dist/cross-extension-rpc.js +138 -0
  24. package/dist/custom-agents.d.ts +54 -0
  25. package/dist/custom-agents.js +316 -0
  26. package/dist/default-agents.d.ts +7 -0
  27. package/dist/default-agents.js +122 -0
  28. package/dist/enabled-models.d.ts +49 -0
  29. package/dist/enabled-models.js +145 -0
  30. package/dist/env.d.ts +6 -0
  31. package/dist/env.js +28 -0
  32. package/dist/group-join.d.ts +32 -0
  33. package/dist/group-join.js +116 -0
  34. package/dist/index.d.ts +50 -0
  35. package/dist/index.js +3682 -0
  36. package/dist/invocation-config.d.ts +107 -0
  37. package/dist/invocation-config.js +83 -0
  38. package/dist/memory.d.ts +53 -0
  39. package/dist/memory.js +165 -0
  40. package/dist/mention-clone.d.ts +87 -0
  41. package/dist/mention-clone.js +153 -0
  42. package/dist/mention.d.ts +81 -0
  43. package/dist/mention.js +131 -0
  44. package/dist/model-resolver.d.ts +36 -0
  45. package/dist/model-resolver.js +95 -0
  46. package/dist/model-scope.d.ts +49 -0
  47. package/dist/model-scope.js +48 -0
  48. package/dist/nested-tools.d.ts +55 -0
  49. package/dist/nested-tools.js +299 -0
  50. package/dist/output-file.d.ts +43 -0
  51. package/dist/output-file.js +142 -0
  52. package/dist/prompts.d.ts +55 -0
  53. package/dist/prompts.js +91 -0
  54. package/dist/schedule-store.d.ts +38 -0
  55. package/dist/schedule-store.js +155 -0
  56. package/dist/schedule.d.ts +109 -0
  57. package/dist/schedule.js +359 -0
  58. package/dist/settings.d.ts +360 -0
  59. package/dist/settings.js +251 -0
  60. package/dist/skill-loader.d.ts +24 -0
  61. package/dist/skill-loader.js +93 -0
  62. package/dist/status-note.d.ts +61 -0
  63. package/dist/status-note.js +85 -0
  64. package/dist/structured-output.d.ts +61 -0
  65. package/dist/structured-output.js +112 -0
  66. package/dist/types.d.ts +371 -0
  67. package/dist/types.js +5 -0
  68. package/dist/ui/agent-mention.d.ts +82 -0
  69. package/dist/ui/agent-mention.js +187 -0
  70. package/dist/ui/agent-widget.d.ts +219 -0
  71. package/dist/ui/agent-widget.js +592 -0
  72. package/dist/ui/conversation-viewer.d.ts +120 -0
  73. package/dist/ui/conversation-viewer.js +578 -0
  74. package/dist/ui/fleet-list.d.ts +195 -0
  75. package/dist/ui/fleet-list.js +471 -0
  76. package/dist/ui/schedule-menu.d.ts +16 -0
  77. package/dist/ui/schedule-menu.js +94 -0
  78. package/dist/ui/select-item.d.ts +27 -0
  79. package/dist/ui/select-item.js +34 -0
  80. package/dist/ui/viewer-keys.d.ts +20 -0
  81. package/dist/ui/viewer-keys.js +17 -0
  82. package/dist/ui/workflow-card.d.ts +175 -0
  83. package/dist/ui/workflow-card.js +332 -0
  84. package/dist/ui/workflow-dialog.d.ts +305 -0
  85. package/dist/ui/workflow-dialog.js +843 -0
  86. package/dist/ui/workflow-menu.d.ts +60 -0
  87. package/dist/ui/workflow-menu.js +147 -0
  88. package/dist/usage.d.ts +135 -0
  89. package/dist/usage.js +120 -0
  90. package/dist/workflow/collisions.d.ts +95 -0
  91. package/dist/workflow/collisions.js +88 -0
  92. package/dist/workflow/entry.d.ts +32 -0
  93. package/dist/workflow/entry.js +29 -0
  94. package/dist/workflow/host.d.ts +62 -0
  95. package/dist/workflow/host.js +362 -0
  96. package/dist/workflow/journal.d.ts +97 -0
  97. package/dist/workflow/journal.js +120 -0
  98. package/dist/workflow/json-schema.d.ts +51 -0
  99. package/dist/workflow/json-schema.js +111 -0
  100. package/dist/workflow/meta.d.ts +67 -0
  101. package/dist/workflow/meta.js +317 -0
  102. package/dist/workflow/progress.d.ts +224 -0
  103. package/dist/workflow/progress.js +361 -0
  104. package/dist/workflow/runtime.d.ts +334 -0
  105. package/dist/workflow/runtime.js +830 -0
  106. package/dist/workflow/saved.d.ts +90 -0
  107. package/dist/workflow/saved.js +203 -0
  108. package/dist/workflow/task.d.ts +136 -0
  109. package/dist/workflow/task.js +207 -0
  110. package/dist/workflow/tool-description.d.ts +38 -0
  111. package/dist/workflow/tool-description.js +199 -0
  112. package/dist/workflow/worker-source.d.ts +47 -0
  113. package/dist/workflow/worker-source.js +778 -0
  114. package/dist/worktree.d.ts +52 -0
  115. package/dist/worktree.js +164 -0
  116. package/dist/xml.d.ts +10 -0
  117. package/dist/xml.js +12 -0
  118. package/docs/rpc.md +183 -0
  119. package/docs/workflows.md +437 -0
  120. package/examples/agent-tool-description.md +42 -0
  121. package/examples/workflows/compose.js +51 -0
  122. package/examples/workflows/fan-out-audit.js +47 -0
  123. package/examples/workflows/gated-fix.js +60 -0
  124. package/examples/workflows/lib/count-child.js +27 -0
  125. package/examples/workflows/review-panel.js +63 -0
  126. package/examples/workflows/structured-findings.js +78 -0
  127. package/package.json +68 -0
  128. package/src/abortable.ts +43 -0
  129. package/src/agent-color.ts +161 -0
  130. package/src/agent-file-toggle.ts +270 -0
  131. package/src/agent-manager.ts +1581 -0
  132. package/src/agent-runner.ts +1286 -0
  133. package/src/agent-types.ts +346 -0
  134. package/src/child-context.ts +15 -0
  135. package/src/context.ts +58 -0
  136. package/src/cross-extension-rpc.ts +198 -0
  137. package/src/custom-agents.ts +333 -0
  138. package/src/default-agents.ts +126 -0
  139. package/src/enabled-models.ts +180 -0
  140. package/src/env.ts +33 -0
  141. package/src/group-join.ts +141 -0
  142. package/src/index.ts +3991 -0
  143. package/src/invocation-config.ts +155 -0
  144. package/src/memory.ts +179 -0
  145. package/src/mention-clone.ts +196 -0
  146. package/src/mention.ts +141 -0
  147. package/src/model-resolver.ts +118 -0
  148. package/src/model-scope.ts +70 -0
  149. package/src/nested-tools.ts +422 -0
  150. package/src/output-file.ts +155 -0
  151. package/src/prompts.ts +142 -0
  152. package/src/schedule-store.ts +153 -0
  153. package/src/schedule.ts +386 -0
  154. package/src/settings.ts +587 -0
  155. package/src/skill-loader.ts +102 -0
  156. package/src/status-note.ts +90 -0
  157. package/src/structured-output.ts +130 -0
  158. package/src/types.ts +384 -0
  159. package/src/ui/agent-mention.ts +216 -0
  160. package/src/ui/agent-widget.ts +664 -0
  161. package/src/ui/conversation-viewer.ts +589 -0
  162. package/src/ui/fleet-list.ts +543 -0
  163. package/src/ui/schedule-menu.ts +105 -0
  164. package/src/ui/select-item.ts +45 -0
  165. package/src/ui/viewer-keys.ts +39 -0
  166. package/src/ui/workflow-card.ts +470 -0
  167. package/src/ui/workflow-dialog.ts +1115 -0
  168. package/src/ui/workflow-menu.ts +193 -0
  169. package/src/usage.ts +167 -0
  170. package/src/workflow/collisions.ts +123 -0
  171. package/src/workflow/entry.ts +47 -0
  172. package/src/workflow/host.ts +403 -0
  173. package/src/workflow/journal.ts +164 -0
  174. package/src/workflow/json-schema.ts +128 -0
  175. package/src/workflow/meta.ts +325 -0
  176. package/src/workflow/progress.ts +550 -0
  177. package/src/workflow/runtime.ts +1219 -0
  178. package/src/workflow/saved.ts +217 -0
  179. package/src/workflow/task.ts +302 -0
  180. package/src/workflow/tool-description.ts +200 -0
  181. package/src/workflow/worker-source.ts +781 -0
  182. package/src/worktree.ts +205 -0
  183. package/src/xml.ts +13 -0
@@ -0,0 +1,195 @@
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 { type AgentManager } from "../agent-manager.js";
14
+ import type { ViewerMarkdownMode } from "../types.js";
15
+ import { type AgentActivity, type Theme } from "./agent-widget.js";
16
+ /** Minimal UI surface the FleetView needs from `ctx.ui` (structural subset). */
17
+ export type FleetUICtx = {
18
+ setWidget(key: string, content: undefined | ((tui: any, theme: Theme) => {
19
+ render(width: number): string[];
20
+ invalidate(): void;
21
+ dispose?(): void;
22
+ }), options?: {
23
+ placement?: "aboveEditor" | "belowEditor";
24
+ }): void;
25
+ onTerminalInput(handler: (data: string) => {
26
+ consume?: boolean;
27
+ data?: string;
28
+ } | undefined): () => void;
29
+ getEditorText(): string;
30
+ notify(message: string, type?: "info" | "warning" | "error"): void;
31
+ custom<T>(factory: (tui: any, theme: Theme, keybindings: any, done: (result: T) => void) => {
32
+ render(width: number): string[];
33
+ invalidate(): void;
34
+ dispose?(): void;
35
+ }, options?: {
36
+ overlay?: boolean;
37
+ overlayOptions?: unknown;
38
+ onHandle?: (handle: unknown) => void;
39
+ }): Promise<T>;
40
+ };
41
+ /**
42
+ * A workflow run, as the fleet list needs to see it.
43
+ *
44
+ * Narrow on purpose: the list knows nothing about `WorkflowTask`, the runtime
45
+ * or the dialog, so it stays as testable as it was when it only held agents.
46
+ * The extension maps its tasks into this shape and injects an opener.
47
+ */
48
+ export interface FleetWorkflow {
49
+ id: string;
50
+ /** The `meta.name` of the run, or its id when the script named nothing. */
51
+ name: string;
52
+ status: "running" | "completed" | "failed" | "killed" | "paused";
53
+ doneCount: number;
54
+ totalCount: number;
55
+ startedAt: number;
56
+ /** Set once the run settles, which is what freezes its clock. */
57
+ completedAt?: number;
58
+ tokens: number;
59
+ }
60
+ /** `11s` — integer seconds, no decimal/suffix (matches Claude Code, unlike formatMs). */
61
+ export declare function formatFleetElapsed(ms: number): string;
62
+ /** `↓ 13.1k tokens` — down-arrow prefix, compact magnitude, plural "tokens". */
63
+ export declare function formatFleetTokens(count: number): string;
64
+ export declare class FleetList {
65
+ private manager;
66
+ private agentActivity;
67
+ /**
68
+ * Read live at render time. Whether each row shows an estimated cost after
69
+ * its token count. Defaults to off — the extension supplies the user's
70
+ * `showCost` setting.
71
+ */
72
+ private showCost;
73
+ /**
74
+ * The user's `viewerMarkdown` setting, for a conversation overlay opened
75
+ * from here. Read live rather than captured, because the viewer's `m` key
76
+ * changes it while the overlay is up. Omitted → the viewer's own default.
77
+ */
78
+ private viewerMarkdown?;
79
+ /**
80
+ * Persist a mode chosen with `m` in that overlay, so the key means the same
81
+ * thing here as it does from `/agents` — one setting, not one per entry
82
+ * point. Omitted → `m` still cycles, viewer-locally.
83
+ */
84
+ private onViewerMarkdown?;
85
+ private ui;
86
+ private tui;
87
+ private inputUnsub;
88
+ private widgetRegistered;
89
+ private timer;
90
+ private enabled;
91
+ /** Whether arrow keys currently navigate the list (vs. flow to the editor). */
92
+ private active;
93
+ /** 0 = `main`, 1..N = subagents. */
94
+ private selectedIndex;
95
+ /** Set while a conversation overlay is open; calling it closes the overlay. */
96
+ private viewerClose;
97
+ private viewingAgentId;
98
+ /** Injected by the extension; absent until workflows are wired (or at all). */
99
+ private workflowSource;
100
+ private openWorkflow;
101
+ /**
102
+ * Set while the workflow inspector is up.
103
+ *
104
+ * It does the two jobs `viewerClose` does for an agent's overlay — keep the
105
+ * list out of the dialog's keys, and remember which row to come back to —
106
+ * minus the close handle, because that overlay belongs to the extension.
107
+ */
108
+ private viewingWorkflowId;
109
+ constructor(manager: AgentManager, agentActivity: Map<string, AgentActivity>,
110
+ /**
111
+ * Read live at render time. Whether each row shows an estimated cost after
112
+ * its token count. Defaults to off — the extension supplies the user's
113
+ * `showCost` setting.
114
+ */
115
+ showCost?: () => boolean,
116
+ /**
117
+ * The user's `viewerMarkdown` setting, for a conversation overlay opened
118
+ * from here. Read live rather than captured, because the viewer's `m` key
119
+ * changes it while the overlay is up. Omitted → the viewer's own default.
120
+ */
121
+ viewerMarkdown?: (() => ViewerMarkdownMode) | undefined,
122
+ /**
123
+ * Persist a mode chosen with `m` in that overlay, so the key means the same
124
+ * thing here as it does from `/agents` — one setting, not one per entry
125
+ * point. Omitted → `m` still cycles, viewer-locally.
126
+ */
127
+ onViewerMarkdown?: ((mode: ViewerMarkdownMode) => void) | undefined);
128
+ setEnabled(enabled: boolean): void;
129
+ /** Capture the UI context and (re)register the global input handler. */
130
+ setUICtx(ui: FleetUICtx): void;
131
+ /** Ensure the re-render timer is running (called when an agent spawns). */
132
+ ensureTimer(): void;
133
+ /**
134
+ * Called when an agent finishes. The viewer (if open on it) stays open so the
135
+ * final output remains readable, and the row lingers in the list — just refresh.
136
+ */
137
+ onAgentFinished(_id: string): void;
138
+ dispose(): void;
139
+ /** Re-register/refresh the below-editor widget; clears it when nothing remains. */
140
+ update(): void;
141
+ /**
142
+ * Agents shown in the list, ordered earliest-launched first so the ones you
143
+ * started sooner sit at the top. Every row is openable (has a session), so Enter
144
+ * never dead-ends. Included: running/queued, plus the agent currently being
145
+ * viewed, plus recently-finished ones (they linger briefly before dropping out).
146
+ * Pending agents with no session yet are hidden until they start.
147
+ * (`listAgents()` is newest-first, so we re-sort.)
148
+ */
149
+ private agentRecords;
150
+ /**
151
+ * Wire workflow runs into the list.
152
+ *
153
+ * Injected rather than constructed here because the fleet list predates
154
+ * workflows and must keep working without them — a session with the feature
155
+ * switched off never calls this, and the roster is agents-only exactly as
156
+ * before.
157
+ */
158
+ setWorkflowSource(source: () => readonly FleetWorkflow[], open: (id: string) => Promise<void> | void): void;
159
+ /** Live runs, plus recently settled ones — the same linger the agents get. */
160
+ private workflows;
161
+ /**
162
+ * Runs sit above the agents rather than interleaved by start time: a run owns
163
+ * most of the agents under it, so listing the container first is what makes
164
+ * the list read as a hierarchy rather than a shuffle.
165
+ */
166
+ private roster;
167
+ private clampSelection;
168
+ /** Returns `{consume:true}` to swallow a key, or undefined to let it through. */
169
+ handleKey(data: string): {
170
+ consume?: boolean;
171
+ data?: string;
172
+ } | undefined;
173
+ /**
174
+ * True when pi's prompt editor owns the keyboard. pi's editor is an `Editor`
175
+ * subclass (CustomEditor) while every dialog/selector is not, and the loader
176
+ * aliases pi-tui to pi's own copy, so `instanceof` is a reliable identity
177
+ * check. `focusedComponent` is TUI-private (no public accessor), hence the
178
+ * best-effort peek: unknowable focus (no tui seen yet, nothing focused)
179
+ * counts as the editor so activation keeps working.
180
+ */
181
+ private editorHasFocus;
182
+ private deactivate;
183
+ private openSelected;
184
+ /** Reset overlay state and return to the list (on close, auto-close, or error). */
185
+ private clearViewer;
186
+ private renderBar;
187
+ private bullet;
188
+ /**
189
+ * A run's row. Shaped like an agent's — bullet, kind, name, stats flush right
190
+ * — so the two read as one list, with the agent count where an agent has its
191
+ * description and the same elapsed/token tail.
192
+ */
193
+ private renderWorkflowRow;
194
+ private renderAgentRow;
195
+ }
@@ -0,0 +1,471 @@
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 { Editor, 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, VIEWPORT_HEIGHT_PCT } 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
+ ui;
61
+ tui;
62
+ inputUnsub;
63
+ widgetRegistered = false;
64
+ timer;
65
+ enabled = true;
66
+ /** Whether arrow keys currently navigate the list (vs. flow to the editor). */
67
+ active = false;
68
+ /** 0 = `main`, 1..N = subagents. */
69
+ selectedIndex = 0;
70
+ /** Set while a conversation overlay is open; calling it closes the overlay. */
71
+ viewerClose;
72
+ viewingAgentId;
73
+ /** Injected by the extension; absent until workflows are wired (or at all). */
74
+ workflowSource;
75
+ openWorkflow;
76
+ /**
77
+ * Set while the workflow inspector is up.
78
+ *
79
+ * It does the two jobs `viewerClose` does for an agent's overlay — keep the
80
+ * list out of the dialog's keys, and remember which row to come back to —
81
+ * minus the close handle, because that overlay belongs to the extension.
82
+ */
83
+ viewingWorkflowId;
84
+ constructor(manager, agentActivity,
85
+ /**
86
+ * Read live at render time. Whether each row shows an estimated cost after
87
+ * its token count. Defaults to off — the extension supplies the user's
88
+ * `showCost` setting.
89
+ */
90
+ showCost = () => false,
91
+ /**
92
+ * The user's `viewerMarkdown` setting, for a conversation overlay opened
93
+ * from here. Read live rather than captured, because the viewer's `m` key
94
+ * changes it while the overlay is up. Omitted → the viewer's own default.
95
+ */
96
+ viewerMarkdown,
97
+ /**
98
+ * Persist a mode chosen with `m` in that overlay, so the key means the same
99
+ * thing here as it does from `/agents` — one setting, not one per entry
100
+ * point. Omitted → `m` still cycles, viewer-locally.
101
+ */
102
+ onViewerMarkdown) {
103
+ this.manager = manager;
104
+ this.agentActivity = agentActivity;
105
+ this.showCost = showCost;
106
+ this.viewerMarkdown = viewerMarkdown;
107
+ this.onViewerMarkdown = onViewerMarkdown;
108
+ }
109
+ // ---- Lifecycle ----
110
+ setEnabled(enabled) {
111
+ if (enabled === this.enabled)
112
+ return;
113
+ this.enabled = enabled;
114
+ if (!enabled)
115
+ this.active = false;
116
+ this.update();
117
+ }
118
+ /** Capture the UI context and (re)register the global input handler. */
119
+ setUICtx(ui) {
120
+ if (ui === this.ui)
121
+ return;
122
+ this.inputUnsub?.();
123
+ this.ui = ui;
124
+ this.widgetRegistered = false;
125
+ this.tui = undefined;
126
+ this.inputUnsub = ui.onTerminalInput(data => this.handleKey(data));
127
+ }
128
+ /** Ensure the re-render timer is running (called when an agent spawns). */
129
+ ensureTimer() {
130
+ if (!this.timer)
131
+ this.timer = setInterval(() => this.update(), TICK_MS);
132
+ }
133
+ /**
134
+ * Called when an agent finishes. The viewer (if open on it) stays open so the
135
+ * final output remains readable, and the row lingers in the list — just refresh.
136
+ */
137
+ onAgentFinished(_id) {
138
+ this.update();
139
+ }
140
+ dispose() {
141
+ if (this.timer) {
142
+ clearInterval(this.timer);
143
+ this.timer = undefined;
144
+ }
145
+ this.inputUnsub?.();
146
+ this.inputUnsub = undefined;
147
+ if (this.viewerClose) {
148
+ this.viewerClose();
149
+ this.viewerClose = undefined;
150
+ }
151
+ this.viewingAgentId = undefined;
152
+ // No handle to close the workflow inspector with, but the list is going
153
+ // away — leaving the id set would keep it swallowing input forever.
154
+ this.viewingWorkflowId = undefined;
155
+ if (this.ui && this.widgetRegistered)
156
+ this.ui.setWidget(FLEET_KEY, undefined);
157
+ this.widgetRegistered = false;
158
+ this.tui = undefined;
159
+ this.active = false;
160
+ // Null last so a `viewerClose()` microtask above can't re-register the widget.
161
+ this.ui = undefined;
162
+ }
163
+ /** Re-register/refresh the below-editor widget; clears it when nothing remains. */
164
+ update() {
165
+ if (!this.ui)
166
+ return;
167
+ // A run with no agents of its own left in the list is still worth a row —
168
+ // it is the thing the user opens to see what its children did. Read off the
169
+ // roster for the same reason activation does: two counts of "is there
170
+ // anything here" drifted apart once before.
171
+ const hasRows = this.enabled && this.roster().length > 1;
172
+ if (!hasRows) {
173
+ if (this.widgetRegistered) {
174
+ this.ui.setWidget(FLEET_KEY, undefined);
175
+ this.widgetRegistered = false;
176
+ this.tui = undefined;
177
+ }
178
+ if (this.timer) {
179
+ clearInterval(this.timer);
180
+ this.timer = undefined;
181
+ }
182
+ this.active = false;
183
+ this.selectedIndex = 0;
184
+ return;
185
+ }
186
+ this.clampSelection();
187
+ this.ensureTimer(); // keep stats ticking whenever the list is shown (e.g. after a re-enable)
188
+ if (!this.widgetRegistered) {
189
+ this.ui.setWidget(FLEET_KEY, (tui, theme) => {
190
+ this.tui = tui;
191
+ return {
192
+ render: (w) => this.renderBar(w, theme),
193
+ invalidate: () => { this.widgetRegistered = false; this.tui = undefined; },
194
+ };
195
+ }, { placement: "belowEditor" });
196
+ this.widgetRegistered = true;
197
+ }
198
+ else {
199
+ this.tui?.requestRender();
200
+ }
201
+ }
202
+ // ---- Roster ----
203
+ /**
204
+ * Agents shown in the list, ordered earliest-launched first so the ones you
205
+ * started sooner sit at the top. Every row is openable (has a session), so Enter
206
+ * never dead-ends. Included: running/queued, plus the agent currently being
207
+ * viewed, plus recently-finished ones (they linger briefly before dropping out).
208
+ * Pending agents with no session yet are hidden until they start.
209
+ * (`listAgents()` is newest-first, so we re-sort.)
210
+ */
211
+ agentRecords() {
212
+ const now = Date.now();
213
+ return this.manager.listAgents()
214
+ .filter(a => isTopLevelAgent(a) && a.session && (a.status === "running" || a.status === "queued"
215
+ || a.id === this.viewingAgentId
216
+ || (a.completedAt != null && now - a.completedAt < FINISHED_LINGER_MS)))
217
+ .sort((a, b) => a.startedAt - b.startedAt);
218
+ }
219
+ /**
220
+ * Wire workflow runs into the list.
221
+ *
222
+ * Injected rather than constructed here because the fleet list predates
223
+ * workflows and must keep working without them — a session with the feature
224
+ * switched off never calls this, and the roster is agents-only exactly as
225
+ * before.
226
+ */
227
+ setWorkflowSource(source, open) {
228
+ this.workflowSource = source;
229
+ this.openWorkflow = open;
230
+ }
231
+ /** Live runs, plus recently settled ones — the same linger the agents get. */
232
+ workflows() {
233
+ if (!this.workflowSource)
234
+ return [];
235
+ const now = Date.now();
236
+ return [...this.workflowSource()]
237
+ .filter(run => run.status === "running"
238
+ || run.status === "paused"
239
+ || (run.completedAt != null && now - run.completedAt < FINISHED_LINGER_MS))
240
+ .sort((a, b) => a.startedAt - b.startedAt);
241
+ }
242
+ /**
243
+ * Runs sit above the agents rather than interleaved by start time: a run owns
244
+ * most of the agents under it, so listing the container first is what makes
245
+ * the list read as a hierarchy rather than a shuffle.
246
+ */
247
+ roster() {
248
+ return [
249
+ { kind: "main" },
250
+ ...this.workflows().map(workflow => ({ kind: "workflow", workflow })),
251
+ ...this.agentRecords().map(record => ({ kind: "agent", record })),
252
+ ];
253
+ }
254
+ clampSelection() {
255
+ const max = this.roster().length - 1;
256
+ if (this.selectedIndex > max)
257
+ this.selectedIndex = Math.max(0, max);
258
+ if (this.selectedIndex < 0)
259
+ this.selectedIndex = 0;
260
+ }
261
+ // ---- Key handling ----
262
+ /** Returns `{consume:true}` to swallow a key, or undefined to let it through. */
263
+ handleKey(data) {
264
+ if (!this.enabled || !this.ui)
265
+ return undefined;
266
+ // Input listeners receive BOTH key-press and key-release (the kitty protocol
267
+ // emits both, and matchesKey matches either) — act on press only, or every
268
+ // tap would move/fire twice. Repeats still pass through for held-key nav.
269
+ if (isKeyRelease(data))
270
+ return undefined;
271
+ // While an overlay is open, let it own all input. Checked before the focus
272
+ // test below, which would otherwise read the dialog holding the keyboard as
273
+ // "the user left the list" and reset the selection out from under it.
274
+ if (this.viewerClose || this.viewingWorkflowId)
275
+ return undefined;
276
+ // Input listeners fire BEFORE the focused component, and dialogs
277
+ // (ctx.ui.select/confirm/input, pi's own menus) swap the prompt editor out
278
+ // while getEditorText() still reads the detached — empty — editor. So when
279
+ // anything but the editor owns the keyboard, stay out of its keys (#123).
280
+ if (!this.editorHasFocus()) {
281
+ if (this.active)
282
+ this.deactivate();
283
+ return undefined;
284
+ }
285
+ if (!this.active) {
286
+ // Activate: ↓ or ← at an empty prompt moves focus into the list.
287
+ const isActivator = matchesKey(data, "down") || matchesKey(data, "left");
288
+ // Gated on the roster, not the agents: a session whose only row is a
289
+ // workflow run still has somewhere to go, and requiring an agent would
290
+ // render the row but refuse to move into it.
291
+ if (isActivator && this.roster().length > 1 && this.ui.getEditorText() === "") {
292
+ this.active = true;
293
+ this.selectedIndex = 0;
294
+ this.update();
295
+ return { consume: true };
296
+ }
297
+ return undefined;
298
+ }
299
+ // Active — arrows navigate, Enter opens, Esc / Up-past-top exits.
300
+ if (matchesKey(data, "down")) {
301
+ const max = this.roster().length - 1;
302
+ this.selectedIndex = Math.min(max, this.selectedIndex + 1);
303
+ this.update();
304
+ return { consume: true };
305
+ }
306
+ if (matchesKey(data, "up")) {
307
+ if (this.selectedIndex === 0) {
308
+ this.deactivate();
309
+ return { consume: true };
310
+ }
311
+ this.selectedIndex -= 1;
312
+ this.update();
313
+ return { consume: true };
314
+ }
315
+ if (matchesKey(data, "escape")) {
316
+ this.deactivate();
317
+ return { consume: true };
318
+ }
319
+ if (matchesKey(data, Key.enter)) {
320
+ this.openSelected();
321
+ return { consume: true };
322
+ }
323
+ // Any other key cancels navigation and flows to the editor.
324
+ this.deactivate();
325
+ return undefined;
326
+ }
327
+ /**
328
+ * True when pi's prompt editor owns the keyboard. pi's editor is an `Editor`
329
+ * subclass (CustomEditor) while every dialog/selector is not, and the loader
330
+ * aliases pi-tui to pi's own copy, so `instanceof` is a reliable identity
331
+ * check. `focusedComponent` is TUI-private (no public accessor), hence the
332
+ * best-effort peek: unknowable focus (no tui seen yet, nothing focused)
333
+ * counts as the editor so activation keeps working.
334
+ */
335
+ editorHasFocus() {
336
+ const focused = this.tui?.focusedComponent;
337
+ return focused == null || focused instanceof Editor;
338
+ }
339
+ deactivate() {
340
+ this.active = false;
341
+ this.selectedIndex = 0;
342
+ this.update();
343
+ }
344
+ openSelected() {
345
+ const entry = this.roster()[this.selectedIndex];
346
+ if (!entry || entry.kind === "main") {
347
+ // `main` = return to the prompt; the native transcript is already shown.
348
+ this.deactivate();
349
+ return;
350
+ }
351
+ if (entry.kind === "workflow") {
352
+ // The extension owns this overlay and closes it, so there is no
353
+ // `viewerClose` to hold — but the list still has to know one is up, and
354
+ // still has to put the cursor back on the run when it comes down.
355
+ this.viewingWorkflowId = entry.workflow.id;
356
+ void Promise.resolve(this.openWorkflow?.(entry.workflow.id)).then(() => this.clearViewer(), () => this.clearViewer());
357
+ return;
358
+ }
359
+ const record = entry.record;
360
+ if (!this.ui)
361
+ return;
362
+ if (!record.session) {
363
+ this.ui.notify(`Agent is ${record.status} — no session available.`, "info");
364
+ return;
365
+ }
366
+ const session = record.session;
367
+ const activity = this.agentActivity.get(record.id);
368
+ this.viewingAgentId = record.id;
369
+ void this.ui.custom((tui, theme, keybindings, done) => {
370
+ this.viewerClose = () => done(undefined);
371
+ return new ConversationViewer(tui, session, record, activity, theme, done, () => {
372
+ if (this.manager.abort(record.id))
373
+ this.ui?.notify(`Stopped "${record.description}".`, "info");
374
+ }, keybindings, (message) => this.manager.steer(record.id, message), this.showCost(), this.viewerMarkdown, this.onViewerMarkdown);
375
+ }, {
376
+ overlay: true,
377
+ overlayOptions: { anchor: "center", width: "90%", maxHeight: `${VIEWPORT_HEIGHT_PCT}%` },
378
+ }).then(() => this.clearViewer(), () => this.clearViewer());
379
+ }
380
+ /** Reset overlay state and return to the list (on close, auto-close, or error). */
381
+ clearViewer() {
382
+ // Keep the cursor on the agent we were viewing — re-resolve by id so it
383
+ // still feels natural if the list reordered (an earlier agent finished)
384
+ // while the overlay was open. If that agent is gone, leave the index for
385
+ // update()'s clamp to settle.
386
+ const viewed = this.viewingAgentId ?? this.viewingWorkflowId;
387
+ if (viewed !== undefined) {
388
+ const idx = this.roster().findIndex(e => e.kind === "agent" ? e.record.id === viewed
389
+ : e.kind === "workflow" ? e.workflow.id === viewed
390
+ : false);
391
+ if (idx >= 0)
392
+ this.selectedIndex = idx;
393
+ }
394
+ this.viewerClose = undefined;
395
+ this.viewingAgentId = undefined;
396
+ this.viewingWorkflowId = undefined;
397
+ this.update();
398
+ }
399
+ // ---- Rendering ----
400
+ renderBar(width, theme) {
401
+ const rows = this.roster().slice(1);
402
+ if (rows.length === 0)
403
+ return [];
404
+ // Clamp locally so a render between a roster shrink and the next update()
405
+ // (e.g. on terminal resize) never loses the selection marker.
406
+ const sel = Math.min(this.selectedIndex, rows.length);
407
+ const hint = this.active
408
+ ? "↑↓ select · enter view · esc back"
409
+ : "esc to interrupt · ← for agents · ↓ to manage";
410
+ const lines = [];
411
+ lines.push(truncateToWidth(" " + theme.fg("dim", hint), width));
412
+ lines.push("");
413
+ lines.push(truncateToWidth(` ${this.bullet(0, sel, theme)} main`, width));
414
+ // Window the rows so the selected one stays visible.
415
+ const visible = Math.min(MAX_AGENT_ROWS, rows.length);
416
+ const selRow = Math.max(0, sel - 1);
417
+ const start = selRow < visible ? 0 : selRow - visible + 1;
418
+ const hiddenBelow = rows.length - (start + visible);
419
+ if (start > 0)
420
+ lines.push(rightAlign("", theme.fg("dim", `↑ ${start} more`), width));
421
+ for (let a = start; a < start + visible; a++) {
422
+ const row = rows[a];
423
+ lines.push(row.kind === "workflow" ?
424
+ this.renderWorkflowRow(a + 1, sel, row.workflow, width, theme)
425
+ : this.renderAgentRow(a + 1, sel, row.record, width, theme));
426
+ }
427
+ if (hiddenBelow > 0)
428
+ lines.push(rightAlign("", theme.fg("dim", `↓ ${hiddenBelow} more`), width));
429
+ return lines;
430
+ }
431
+ bullet(rosterIndex, sel, theme) {
432
+ return rosterIndex === sel ? theme.fg("accent", "●") : theme.fg("dim", "○");
433
+ }
434
+ /**
435
+ * A run's row. Shaped like an agent's — bullet, kind, name, stats flush right
436
+ * — so the two read as one list, with the agent count where an agent has its
437
+ * description and the same elapsed/token tail.
438
+ */
439
+ renderWorkflowRow(rosterIndex, sel, workflow, width, theme) {
440
+ const selected = rosterIndex === sel;
441
+ const kind = theme.fg(selected ? "text" : "muted", "workflow");
442
+ const name = selected ? theme.fg("text", workflow.name) : workflow.name;
443
+ const left = ` ${this.bullet(rosterIndex, sel, theme)} ${kind} ${name}`;
444
+ // Frozen once the run settles, exactly as an agent's clock is.
445
+ const elapsed = (workflow.completedAt ?? Date.now()) - workflow.startedAt;
446
+ const agents = `${workflow.doneCount}/${workflow.totalCount} agent${workflow.totalCount === 1 ? "" : "s"}`;
447
+ const stats = `${agents} · ${formatFleetElapsed(elapsed)} · ${formatFleetTokens(workflow.tokens)}`;
448
+ return rightAlign(left, selected ? theme.fg("text", stats) : theme.fg("dim", stats), width);
449
+ }
450
+ renderAgentRow(rosterIndex, sel, record, width, theme) {
451
+ // The selected row renders in the theme's primary text color so it reads as
452
+ // one selection (#230). A configured badge survives — Claude Code's FleetView
453
+ // keeps the agent color on the selected row too and only bolds it — which also
454
+ // keeps the row's width fixed as the selection moves.
455
+ const selected = rosterIndex === sel;
456
+ const name = renderAgentName(record.type, theme, selected
457
+ ? { fallbackColor: "text", bold: hasAgentBadge(record.type) }
458
+ : { fallbackColor: "muted" });
459
+ const description = selected ? theme.fg("text", record.description) : record.description;
460
+ const left = ` ${this.bullet(rosterIndex, sel, theme)} ${name} ${description}`;
461
+ // The record, not the activity tracker — see the note in AgentWidget's
462
+ // running line: only the record carries a nested child's spend, and only it
463
+ // outlives the agent.
464
+ const tokens = getLifetimeTotal(record.lifetimeUsage);
465
+ const elapsedMs = (record.completedAt ?? Date.now()) - record.startedAt; // freezes once finished
466
+ const cost = this.showCost() ? formatCost(getLifetimeCost(record.lifetimeUsage)) : "";
467
+ const stats = `${formatFleetElapsed(elapsedMs)} · ${formatFleetTokens(tokens)}${cost ? ` · ${cost}` : ""}`;
468
+ const right = selected ? theme.fg("text", stats) : theme.fg("dim", stats);
469
+ return rightAlign(left, right, width);
470
+ }
471
+ }
@@ -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>;