@timmyjl12/pi-subagents 0.20.0 → 0.21.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 (159) hide show
  1. package/CHANGELOG.md +862 -827
  2. package/README.md +1125 -1080
  3. package/dist/active-agents-prompt.d.ts +31 -9
  4. package/dist/active-agents-prompt.js +73 -9
  5. package/dist/agent-color.js +9 -1
  6. package/dist/agent-file-toggle.d.ts +1 -1
  7. package/dist/agent-manager.d.ts +405 -18
  8. package/dist/agent-manager.js +1661 -131
  9. package/dist/agent-runner.d.ts +45 -6
  10. package/dist/agent-runner.js +109 -18
  11. package/dist/agent-types.d.ts +30 -7
  12. package/dist/agent-types.js +38 -9
  13. package/dist/awaited-result.d.ts +37 -0
  14. package/dist/awaited-result.js +150 -0
  15. package/dist/child-session-shutdown.d.ts +19 -1
  16. package/dist/child-session-shutdown.js +60 -11
  17. package/dist/cleanup-plans.d.ts +10 -0
  18. package/dist/cleanup-plans.js +112 -0
  19. package/dist/cross-extension-rpc.d.ts +8 -1
  20. package/dist/cross-extension-rpc.js +59 -5
  21. package/dist/custom-agents.d.ts +34 -9
  22. package/dist/custom-agents.js +308 -111
  23. package/dist/default-agents.d.ts +1 -1
  24. package/dist/env.d.ts +1 -1
  25. package/dist/error-log.d.ts +6 -0
  26. package/dist/error-log.js +8 -0
  27. package/dist/force-main-model.d.ts +21 -0
  28. package/dist/force-main-model.js +28 -0
  29. package/dist/goal-bridge.d.ts +155 -0
  30. package/dist/goal-bridge.js +305 -0
  31. package/dist/group-join.d.ts +5 -1
  32. package/dist/group-join.js +52 -7
  33. package/dist/index.d.ts +5 -5
  34. package/dist/index.js +2827 -333
  35. package/dist/invocation-config.d.ts +30 -3
  36. package/dist/invocation-config.js +30 -1
  37. package/dist/memory.d.ts +1 -1
  38. package/dist/mention-clone.d.ts +1 -1
  39. package/dist/model-scope.d.ts +1 -1
  40. package/dist/nested-tools.d.ts +22 -1
  41. package/dist/nested-tools.js +120 -26
  42. package/dist/output-file.d.ts +15 -4
  43. package/dist/output-file.js +146 -43
  44. package/dist/prompts.d.ts +1 -1
  45. package/dist/recovery.d.ts +1 -1
  46. package/dist/report-cleanup.d.ts +204 -0
  47. package/dist/report-cleanup.js +1632 -0
  48. package/dist/report-store.d.ts +738 -0
  49. package/dist/report-store.js +3612 -0
  50. package/dist/schedule-store.d.ts +14 -6
  51. package/dist/schedule-store.js +88 -58
  52. package/dist/schedule.d.ts +20 -8
  53. package/dist/schedule.js +135 -74
  54. package/dist/settings.d.ts +39 -11
  55. package/dist/settings.js +22 -5
  56. package/dist/status-note.d.ts +1 -1
  57. package/dist/structured-output.d.ts +1 -1
  58. package/dist/types.d.ts +32 -3
  59. package/dist/ui/agent-mention.d.ts +2 -2
  60. package/dist/ui/agent-widget.d.ts +82 -13
  61. package/dist/ui/agent-widget.js +155 -37
  62. package/dist/ui/cleanup-preview.d.ts +59 -0
  63. package/dist/ui/cleanup-preview.js +466 -0
  64. package/dist/ui/conversation-viewer.d.ts +4 -4
  65. package/dist/ui/conversation-viewer.js +10 -6
  66. package/dist/ui/fleet-list.d.ts +3 -3
  67. package/dist/ui/fleet-list.js +3 -3
  68. package/dist/ui/fleet-overlay.d.ts +37 -6
  69. package/dist/ui/fleet-overlay.js +214 -18
  70. package/dist/ui/hub-feed.d.ts +52 -0
  71. package/dist/ui/hub-feed.js +148 -0
  72. package/dist/ui/native-transcript.js +5 -1
  73. package/dist/ui/schedule-menu.d.ts +1 -1
  74. package/dist/ui/schedule-menu.js +1 -1
  75. package/dist/ui/workflow-card.d.ts +4 -4
  76. package/dist/ui/workflow-dialog.d.ts +4 -4
  77. package/dist/ui/workflow-dialog.js +8 -3
  78. package/dist/ui/workflow-menu.d.ts +2 -2
  79. package/dist/usage.d.ts +12 -0
  80. package/dist/usage.js +28 -1
  81. package/dist/workflow/entry.d.ts +3 -3
  82. package/dist/workflow/host.d.ts +7 -4
  83. package/dist/workflow/host.js +162 -48
  84. package/dist/workflow/journal.d.ts +23 -7
  85. package/dist/workflow/journal.js +80 -23
  86. package/dist/workflow/progress.d.ts +1 -1
  87. package/dist/workflow/runtime.d.ts +45 -6
  88. package/dist/workflow/runtime.js +105 -16
  89. package/dist/workflow/task.d.ts +13 -4
  90. package/dist/workflow/task.js +7 -1
  91. package/dist/workflow/tool-description.d.ts +7 -2
  92. package/dist/workflow/tool-description.js +10 -5
  93. package/docs/{FORK.md → DEVELOPMENT.md} +4 -4
  94. package/docs/artifacts.md +93 -0
  95. package/docs/rpc.md +252 -189
  96. package/docs/runtime-performance.md +53 -0
  97. package/docs/workflows.md +48 -18
  98. package/examples/agent-tool-description.md +2 -2
  99. package/examples/workflows/review-panel.js +6 -3
  100. package/package.json +5 -5
  101. package/src/active-agents-prompt.ts +115 -39
  102. package/src/agent-color.ts +10 -2
  103. package/src/agent-file-toggle.ts +2 -2
  104. package/src/agent-manager.ts +3312 -1601
  105. package/src/agent-runner.ts +164 -36
  106. package/src/agent-types.ts +56 -11
  107. package/src/awaited-result.ts +187 -0
  108. package/src/child-session-shutdown.ts +114 -46
  109. package/src/cleanup-plans.ts +112 -0
  110. package/src/cross-extension-rpc.ts +68 -9
  111. package/src/custom-agents.ts +384 -112
  112. package/src/default-agents.ts +1 -1
  113. package/src/enabled-models.ts +1 -1
  114. package/src/env.ts +1 -1
  115. package/src/error-log.ts +10 -1
  116. package/src/force-main-model.ts +29 -0
  117. package/src/goal-bridge.ts +468 -0
  118. package/src/group-join.ts +56 -9
  119. package/src/index.ts +2987 -349
  120. package/src/invocation-config.ts +50 -4
  121. package/src/memory.ts +1 -1
  122. package/src/mention-clone.ts +3 -3
  123. package/src/model-scope.ts +1 -1
  124. package/src/nested-tools.ts +164 -33
  125. package/src/output-file.ts +168 -46
  126. package/src/prompts.ts +1 -1
  127. package/src/recovery.ts +2 -2
  128. package/src/report-cleanup.ts +2044 -0
  129. package/src/report-store.ts +4130 -0
  130. package/src/schedule-store.ts +244 -201
  131. package/src/schedule.ts +144 -80
  132. package/src/settings.ts +61 -16
  133. package/src/skill-loader.ts +1 -1
  134. package/src/standalone-fallback.ts +2 -2
  135. package/src/status-note.ts +1 -1
  136. package/src/structured-output.ts +1 -1
  137. package/src/types.ts +33 -3
  138. package/src/ui/agent-mention.ts +3 -3
  139. package/src/ui/agent-widget.ts +179 -45
  140. package/src/ui/cleanup-preview.ts +518 -0
  141. package/src/ui/conversation-viewer.ts +19 -15
  142. package/src/ui/fleet-list.ts +7 -7
  143. package/src/ui/fleet-overlay.ts +1048 -847
  144. package/src/ui/hub-feed.ts +179 -0
  145. package/src/ui/native-transcript.ts +7 -3
  146. package/src/ui/schedule-menu.ts +4 -4
  147. package/src/ui/workflow-card.ts +4 -4
  148. package/src/ui/workflow-dialog.ts +10 -6
  149. package/src/ui/workflow-menu.ts +4 -4
  150. package/src/usage.ts +53 -3
  151. package/src/workflow/collisions.ts +1 -1
  152. package/src/workflow/entry.ts +3 -3
  153. package/src/workflow/host.ts +174 -54
  154. package/src/workflow/journal.ts +80 -23
  155. package/src/workflow/progress.ts +1 -1
  156. package/src/workflow/runtime.ts +146 -23
  157. package/src/workflow/saved.ts +3 -3
  158. package/src/workflow/task.ts +18 -7
  159. package/src/workflow/tool-description.ts +10 -5
@@ -1,13 +1,13 @@
1
1
  /**
2
- * agent-widget.ts — Persistent widget showing running/completed agents above the editor.
2
+ * agent-widget.ts — Compact running/completed agent list above or below the editor.
3
3
  *
4
4
  * Displays a tree of agents with animated spinners, live stats, and activity descriptions.
5
5
  * Uses the callback form of setWidget for themed rendering.
6
6
  */
7
- import { type AdvisorStatus } from "../advisor-status.js";
8
- import { type AgentManager } from "../agent-manager.js";
9
- import type { AgentInvocation, SubagentType, WidgetMode } from "../types.js";
10
- import { type SessionLike } from "../usage.js";
7
+ import { type AdvisorStatus } from "../advisor-status.ts";
8
+ import { type AgentManager } from "../agent-manager.ts";
9
+ import type { AgentInvocation, SubagentType, WidgetMode, WidgetPlacement } from "../types.ts";
10
+ import { type SessionLike } from "../usage.ts";
11
11
  /** Braille spinner frames for animated running indicator. */
12
12
  export declare const SPINNER: string[];
13
13
  /** Statuses that indicate an error/non-success outcome (used for linger behavior and icon rendering). */
@@ -16,15 +16,41 @@ export type Theme = {
16
16
  fg(color: string, text: string): string;
17
17
  bold(text: string): string;
18
18
  };
19
+ type WidgetTUI = {
20
+ terminal: {
21
+ columns: number;
22
+ };
23
+ requestRender(): void;
24
+ getFocusedComponent?(): unknown;
25
+ focusedComponent?: unknown;
26
+ };
19
27
  export type UICtx = {
20
28
  setStatus(key: string, text: string | undefined): void;
21
- setWidget(key: string, content: undefined | ((tui: any, theme: Theme) => {
22
- render(): string[];
29
+ setWidget(key: string, content: undefined | ((tui: WidgetTUI, theme: Theme) => {
30
+ render(width?: number): string[];
23
31
  invalidate(): void;
24
32
  }), options?: {
25
33
  placement?: "aboveEditor" | "belowEditor";
26
34
  }): void;
35
+ onTerminalInput?(handler: (data: string) => {
36
+ consume?: boolean;
37
+ } | undefined): () => void;
38
+ getEditorText?(): string;
27
39
  };
40
+ /** The host's side of the ← → Agent Hub shortcut; every field is read live. */
41
+ export interface AgentHubWiring {
42
+ /** Open the Hub overlay. */
43
+ open(): void;
44
+ /**
45
+ * Whether the Hub would have rows: the Hub's content, not the compact list's
46
+ * visibility — a foreground-only roster (filtered out by `widgetMode`) or
47
+ * settled history past the linger must still open. Defaults to the
48
+ * unfiltered top-level roster.
49
+ */
50
+ hasContent?(): boolean;
51
+ /** True while the Hub overlay is open; ← then belongs to it, not this handler. */
52
+ isOpen?(): boolean;
53
+ }
28
54
  /** Per-agent live activity state. */
29
55
  export interface AgentActivity {
30
56
  activeTools: Map<string, string>;
@@ -114,6 +140,33 @@ export declare function buildInvocationTags(invocation: AgentInvocation | undefi
114
140
  modelId?: string;
115
141
  tags: string[];
116
142
  };
143
+ /**
144
+ * Make externally supplied text safe to place in ONE terminal row.
145
+ *
146
+ * Every entry an extension returns from `render()` is ONE terminal row: pi's
147
+ * TUI pushes each array element verbatim (`tui.js` `lines.push(line)`) and
148
+ * measures the block's height as `childLines.length`. A literal `\n` — or `\t`,
149
+ * or any other control byte — inside an entry makes the terminal advance a row
150
+ * the renderer never counted, permanently desynchronising its line diff. The
151
+ * visible symptom is a frozen duplicate row left on screen above and rows
152
+ * clipped below (the footer/statusline among them). Truncation cannot rescue
153
+ * it either: pi-tui's `visibleWidth` counts control characters as zero-width,
154
+ * so such a line passes the width check and still wraps in the terminal.
155
+ *
156
+ * Agent descriptions and error messages are the realistic carriers — both are
157
+ * free text (a model-supplied tool argument; a raw `Error.message`, which is
158
+ * frequently multi-line). ANSI styling is applied AFTER this runs, so stripping
159
+ * ESC here doubles as a terminal-injection guard for the plain fragments.
160
+ *
161
+ * Internal whitespace is preserved; see {@link sanitizeRowText} to collapse it.
162
+ */
163
+ export declare function flattenRow(text: string): string;
164
+ /**
165
+ * {@link flattenRow} plus whitespace collapsing, for short single-line labels
166
+ * (descriptions, names, error heads) where runs of spaces carry nothing.
167
+ * Use {@link flattenRow} instead where indentation is meaningful.
168
+ */
169
+ export declare function sanitizeRowText(text: string): string;
117
170
  /** Build a human-readable activity string from currently-running tools or response text. */
118
171
  export declare function describeActivity(activeTools: Map<string, string>, responseText?: string): string;
119
172
  export declare class AgentWidget {
@@ -121,8 +174,7 @@ export declare class AgentWidget {
121
174
  private agentActivity;
122
175
  /**
123
176
  * Read live at render time. Selects which agents the widget shows — see
124
- * `WidgetMode`. Defaults to `"all"` when a caller supplies no policy; the
125
- * extension supplies one defaulting to `"background"`.
177
+ * `WidgetMode`. Defaults to `"all"`, matching the extension's own default.
126
178
  */
127
179
  private mode;
128
180
  /**
@@ -139,6 +191,8 @@ export declare class AgentWidget {
139
191
  * conversation viewer unconditionally.
140
192
  */
141
193
  private showModel;
194
+ /** Read live; changing placement remounts the same widget key once. */
195
+ private placement;
142
196
  private uiCtx;
143
197
  private widgetFrame;
144
198
  private widgetInterval;
@@ -156,15 +210,17 @@ export declare class AgentWidget {
156
210
  private static readonly ERROR_LINGER_TURNS;
157
211
  /** Whether the widget callback is currently registered with the TUI. */
158
212
  private widgetRegistered;
159
- /** Cached TUI reference from widget factory callback, used for requestRender(). */
213
+ private registeredPlacement;
214
+ private inputUnsub;
215
+ private hub;
216
+ /** Cached TUI reference from widget factory callback, used for repaint and focus checks. */
160
217
  private tui;
161
218
  /** Last status bar text, used to avoid redundant setStatus calls. */
162
219
  private lastStatusText;
163
220
  constructor(manager: AgentManager, agentActivity: Map<string, AgentActivity>,
164
221
  /**
165
222
  * Read live at render time. Selects which agents the widget shows — see
166
- * `WidgetMode`. Defaults to `"all"` when a caller supplies no policy; the
167
- * extension supplies one defaulting to `"background"`.
223
+ * `WidgetMode`. Defaults to `"all"`, matching the extension's own default.
168
224
  */
169
225
  mode?: () => WidgetMode,
170
226
  /**
@@ -180,7 +236,11 @@ export declare class AgentWidget {
180
236
  * row is already dense and the same pair is on the tool result and in the
181
237
  * conversation viewer unconditionally.
182
238
  */
183
- showModel?: () => boolean);
239
+ showModel?: () => boolean,
240
+ /** Read live; changing placement remounts the same widget key once. */
241
+ placement?: () => WidgetPlacement);
242
+ /** Reuse the extension's canonical Agent Hub, without an inline navigation mode. */
243
+ setHubOpener(hub: AgentHubWiring): void;
184
244
  /**
185
245
  * Agents eligible for the widget, per the current `WidgetMode`:
186
246
  * - `off`: none (the widget's existing empty-state path hides it entirely).
@@ -229,7 +289,16 @@ export declare class AgentWidget {
229
289
  * reading live state each time instead of capturing it in a closure.
230
290
  */
231
291
  private renderWidget;
292
+ /**
293
+ * Acquire the TUI reference without a visible list. Pi invokes the factory
294
+ * synchronously inside setWidget but paints on the next render tick, so a
295
+ * register immediately followed by an unregister captures the reference and
296
+ * never draws a frame. A separate key from the real widget, so the
297
+ * registration state machine never notices.
298
+ */
299
+ private probeTui;
232
300
  /** Force an immediate widget update. */
233
301
  update(): void;
234
302
  dispose(): void;
235
303
  }
304
+ export {};
@@ -1,10 +1,10 @@
1
1
  /**
2
- * agent-widget.ts — Persistent widget showing running/completed agents above the editor.
2
+ * agent-widget.ts — Compact running/completed agent list above or below the editor.
3
3
  *
4
4
  * Displays a tree of agents with animated spinners, live stats, and activity descriptions.
5
5
  * Uses the callback form of setWidget for themed rendering.
6
6
  */
7
- import { truncateToWidth } from "@earendil-works/pi-tui";
7
+ import { Editor, isKeyRelease, isKeyRepeat, matchesKey, truncateToWidth } from "@earendil-works/pi-tui";
8
8
  import { formatAdvisorStatus } from "../advisor-status.js";
9
9
  import { renderAgentName } from "../agent-color.js";
10
10
  import { isTopLevelAgent } from "../agent-manager.js";
@@ -13,6 +13,8 @@ import { getLifetimeCost, getLifetimeTotal, getSessionContextPercent } from "../
13
13
  // ---- Constants ----
14
14
  /** Maximum number of rendered lines before overflow collapse kicks in. */
15
15
  const MAX_WIDGET_LINES = 12;
16
+ /** Header, activity and advisor status form one indivisible running card. */
17
+ const RUNNING_CARD_LINES = 3;
16
18
  /** Braille spinner frames for animated running indicator. */
17
19
  export const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
18
20
  /** Statuses that indicate an error/non-success outcome (used for linger behavior and icon rendering). */
@@ -147,9 +149,45 @@ export function buildInvocationTags(invocation) {
147
149
  tags,
148
150
  };
149
151
  }
152
+ /**
153
+ * Make externally supplied text safe to place in ONE terminal row.
154
+ *
155
+ * Every entry an extension returns from `render()` is ONE terminal row: pi's
156
+ * TUI pushes each array element verbatim (`tui.js` `lines.push(line)`) and
157
+ * measures the block's height as `childLines.length`. A literal `\n` — or `\t`,
158
+ * or any other control byte — inside an entry makes the terminal advance a row
159
+ * the renderer never counted, permanently desynchronising its line diff. The
160
+ * visible symptom is a frozen duplicate row left on screen above and rows
161
+ * clipped below (the footer/statusline among them). Truncation cannot rescue
162
+ * it either: pi-tui's `visibleWidth` counts control characters as zero-width,
163
+ * so such a line passes the width check and still wraps in the terminal.
164
+ *
165
+ * Agent descriptions and error messages are the realistic carriers — both are
166
+ * free text (a model-supplied tool argument; a raw `Error.message`, which is
167
+ * frequently multi-line). ANSI styling is applied AFTER this runs, so stripping
168
+ * ESC here doubles as a terminal-injection guard for the plain fragments.
169
+ *
170
+ * Internal whitespace is preserved; see {@link sanitizeRowText} to collapse it.
171
+ */
172
+ export function flattenRow(text) {
173
+ return text
174
+ // Whole escape sequences go, not just the ESC byte: a stripped-but-not-
175
+ // consumed CSI would leave its `[31m` payload as visible garbage.
176
+ .replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g, " ") // OSC (hyperlinks, titles)
177
+ .replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, " ") // CSI (cursor, erase, SGR)
178
+ .replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ");
179
+ }
180
+ /**
181
+ * {@link flattenRow} plus whitespace collapsing, for short single-line labels
182
+ * (descriptions, names, error heads) where runs of spaces carry nothing.
183
+ * Use {@link flattenRow} instead where indentation is meaningful.
184
+ */
185
+ export function sanitizeRowText(text) {
186
+ return flattenRow(text).replace(/\s+/g, " ").trim();
187
+ }
150
188
  /** Truncate text to a single line, max `len` chars. */
151
189
  function truncateLine(text, len = 60) {
152
- const line = text.split("\n").find(l => l.trim())?.trim() ?? "";
190
+ const line = sanitizeRowText(text.split("\n").find(l => l.trim()) ?? "");
153
191
  if (line.length <= len)
154
192
  return line;
155
193
  return line.slice(0, len) + "…";
@@ -186,6 +224,7 @@ export class AgentWidget {
186
224
  mode;
187
225
  showCost;
188
226
  showModel;
227
+ placement;
189
228
  uiCtx;
190
229
  widgetFrame = 0;
191
230
  widgetInterval;
@@ -203,15 +242,17 @@ export class AgentWidget {
203
242
  static ERROR_LINGER_TURNS = 2;
204
243
  /** Whether the widget callback is currently registered with the TUI. */
205
244
  widgetRegistered = false;
206
- /** Cached TUI reference from widget factory callback, used for requestRender(). */
245
+ registeredPlacement;
246
+ inputUnsub;
247
+ hub;
248
+ /** Cached TUI reference from widget factory callback, used for repaint and focus checks. */
207
249
  tui;
208
250
  /** Last status bar text, used to avoid redundant setStatus calls. */
209
251
  lastStatusText;
210
252
  constructor(manager, agentActivity,
211
253
  /**
212
254
  * Read live at render time. Selects which agents the widget shows — see
213
- * `WidgetMode`. Defaults to `"all"` when a caller supplies no policy; the
214
- * extension supplies one defaulting to `"background"`.
255
+ * `WidgetMode`. Defaults to `"all"`, matching the extension's own default.
215
256
  */
216
257
  mode = () => "all",
217
258
  /**
@@ -227,12 +268,19 @@ export class AgentWidget {
227
268
  * row is already dense and the same pair is on the tool result and in the
228
269
  * conversation viewer unconditionally.
229
270
  */
230
- showModel = () => false) {
271
+ showModel = () => false,
272
+ /** Read live; changing placement remounts the same widget key once. */
273
+ placement = () => "above") {
231
274
  this.manager = manager;
232
275
  this.agentActivity = agentActivity;
233
276
  this.mode = mode;
234
277
  this.showCost = showCost;
235
278
  this.showModel = showModel;
279
+ this.placement = placement;
280
+ }
281
+ /** Reuse the extension's canonical Agent Hub, without an inline navigation mode. */
282
+ setHubOpener(hub) {
283
+ this.hub = hub;
236
284
  }
237
285
  /**
238
286
  * Agents eligible for the widget, per the current `WidgetMode`:
@@ -256,12 +304,42 @@ export class AgentWidget {
256
304
  /** Set the UI context (grabbed from first tool execution). */
257
305
  setUICtx(ctx) {
258
306
  if (ctx !== this.uiCtx) {
259
- // UICtx changed — the widget registered on the old context is gone.
260
- // Force re-registration on next update().
307
+ // UICtx changed — force re-registration and detach the old input listener.
308
+ this.inputUnsub?.();
261
309
  this.uiCtx = ctx;
262
310
  this.widgetRegistered = false;
311
+ this.registeredPlacement = undefined;
263
312
  this.tui = undefined;
264
313
  this.lastStatusText = undefined;
314
+ this.inputUnsub = ctx.onTerminalInput?.(data => {
315
+ if (ctx !== this.uiCtx || !this.hub)
316
+ return undefined;
317
+ if (isKeyRelease(data) || isKeyRepeat(data) || !matchesKey(data, "left") || ctx.getEditorText?.() !== "")
318
+ return undefined;
319
+ // The Hub owns every key while it holds the keyboard — re-entering it
320
+ // here would stack a second overlay and swallow the first one's input.
321
+ if (this.hub.isOpen?.())
322
+ return undefined;
323
+ // "off" retires the key with the list, like the retired fleetView: false.
324
+ if (this.mode() === "off")
325
+ return undefined;
326
+ // Focus distinguishes the real prompt from a detached empty editor
327
+ // underneath a dialog — but only with a TUI to read it from. The list
328
+ // may never have mounted (a foreground-only roster under "background"),
329
+ // so the reference is acquired on demand rather than awaited.
330
+ if (this.tui === undefined)
331
+ this.probeTui();
332
+ if (this.tui === undefined)
333
+ return undefined;
334
+ const focused = this.tui.getFocusedComponent?.() ?? this.tui.focusedComponent;
335
+ if (focused != null && !(focused instanceof Editor))
336
+ return undefined;
337
+ const hasContent = this.hub.hasContent?.() ?? this.manager.listAgents().some(isTopLevelAgent);
338
+ if (!hasContent)
339
+ return undefined;
340
+ this.hub.open();
341
+ return { consume: true };
342
+ });
265
343
  }
266
344
  }
267
345
  /**
@@ -366,7 +444,9 @@ export class AgentWidget {
366
444
  }
367
445
  else if (a.status === "error") {
368
446
  icon = theme.fg("error", "✗");
369
- const errMsg = a.error ? `: ${a.error.slice(0, 60)}` : "";
447
+ // Error messages are routinely multi-line; they must be flattened before
448
+ // the slice, or a truncated tail keeps the newline that breaks the row.
449
+ const errMsg = a.error ? `: ${sanitizeRowText(a.error).slice(0, 60)}` : "";
370
450
  statusText = theme.fg("error", ` error${errMsg}`);
371
451
  }
372
452
  else {
@@ -388,13 +468,13 @@ export class AgentWidget {
388
468
  parts.push(costText);
389
469
  parts.push(duration);
390
470
  const modeTag = modeLabel ? ` ${theme.fg("dim", `(${modeLabel})`)}` : "";
391
- return `${icon} ${renderAgentName(a.type, theme, { fallbackColor: "dim" })}${modeTag} ${theme.fg("dim", a.description)} ${theme.fg("dim", "·")} ${theme.fg("dim", parts.join(" · "))}${statusText}`;
471
+ return `${icon} ${renderAgentName(a.type, theme, { fallbackColor: "dim" })}${modeTag} ${theme.fg("dim", sanitizeRowText(a.description))} ${theme.fg("dim", "·")} ${theme.fg("dim", parts.join(" · "))}${statusText}`;
392
472
  }
393
473
  /**
394
474
  * Render the widget content. Called from the registered widget's render() callback,
395
475
  * reading live state each time instead of capturing it in a closure.
396
476
  */
397
- renderWidget(tui, theme) {
477
+ renderWidget(tui, theme, width) {
398
478
  const allAgents = this.widgetAgents();
399
479
  const running = allAgents.filter(a => a.status === "running");
400
480
  const queued = allAgents.filter(a => a.status === "queued");
@@ -405,19 +485,31 @@ export class AgentWidget {
405
485
  // Nothing to show — return empty (widget will be unregistered by update())
406
486
  if (!hasActive && !hasFinished)
407
487
  return [];
408
- const w = tui.terminal.columns;
488
+ // Render to the width the HOST allocated, not the terminal's: the dock can
489
+ // be narrower than `terminal.columns`, and a line wider than its slot wraps
490
+ // in the terminal while the renderer still counts one row — the same
491
+ // desync an embedded newline causes. Older hosts call render() with no
492
+ // argument; fall back to the terminal width for them.
493
+ const w = typeof width === "number" && Number.isFinite(width) && width >= 0 ? width : tui.terminal.columns;
409
494
  const truncate = (line) => truncateToWidth(line, w);
410
495
  const headingColor = hasActive ? "accent" : "dim";
411
496
  const headingIcon = hasActive ? "●" : "○";
412
497
  const frame = SPINNER[this.widgetFrame % SPINNER.length];
413
- // Build sections separately for overflow-aware assembly.
414
- // Running agents have header, activity and advisor rows; finished/queued stay compact.
498
+ // Apply the existing overflow priority before formatting. Hidden cards must
499
+ // not project session history or format text just to be discarded below.
500
+ const maxBody = MAX_WIDGET_LINES - 1;
501
+ const queueRows = queued.length > 0 ? 1 : 0;
502
+ const totalBody = finished.length + running.length * RUNNING_CARD_LINES + queueRows;
503
+ const overflow = totalBody > maxBody;
504
+ const cardBudget = overflow ? maxBody - 1 - queueRows : maxBody;
505
+ const runningLimit = overflow ? Math.min(running.length, Math.floor(cardBudget / RUNNING_CARD_LINES)) : running.length;
506
+ const finishedLimit = overflow ? Math.max(0, cardBudget - runningLimit * RUNNING_CARD_LINES) : finished.length;
415
507
  const finishedLines = [];
416
- for (const a of finished) {
508
+ for (const a of finished.slice(0, finishedLimit)) {
417
509
  finishedLines.push(truncate(theme.fg("dim", "├─") + " " + this.renderFinishedLine(a, theme)));
418
510
  }
419
511
  const runningLines = []; // each entry is [header, activity, advisor]
420
- for (const a of running) {
512
+ for (const a of running.slice(0, runningLimit)) {
421
513
  const modeLabel = getPromptModeLabel(a.type);
422
514
  const modeTag = modeLabel ? ` ${theme.fg("dim", `(${modeLabel})`)}` : "";
423
515
  const elapsed = formatMs(Date.now() - a.startedAt);
@@ -435,13 +527,15 @@ export class AgentWidget {
435
527
  if (this.showModel()) {
436
528
  // Leading, and paired: a thinking level means nothing without the model
437
529
  // it applies to. The tag is taken from buildInvocationTags rather than
438
- // rebuilt so the "(asked X)" annotation survives.
530
+ // rebuilt so the "(asked X)" annotation survives. Both are plain text
531
+ // that ends up inside a styled run, so they are flattened first — a
532
+ // control byte here would still break the row.
439
533
  const { modelName, tags } = buildInvocationTags(a.invocation);
440
534
  if (modelName)
441
- parts.push(modelName);
535
+ parts.push(sanitizeRowText(modelName));
442
536
  const thinkingTag = tags.find(tag => tag.startsWith("thinking: "));
443
537
  if (thinkingTag)
444
- parts.push(thinkingTag);
538
+ parts.push(sanitizeRowText(thinkingTag));
445
539
  }
446
540
  if (bg)
447
541
  parts.push(formatTurns(bg.turnCount, bg.maxTurns));
@@ -453,20 +547,18 @@ export class AgentWidget {
453
547
  parts.push(costText);
454
548
  parts.push(elapsed);
455
549
  const statsText = parts.join(" · ");
456
- const activity = bg ? describeActivity(bg.activeTools, bg.responseText) : "thinking…";
550
+ const activity = sanitizeRowText(bg ? describeActivity(bg.activeTools, bg.responseText) : "thinking…");
457
551
  runningLines.push([
458
- truncate(theme.fg("dim", "├─") + ` ${theme.fg("accent", frame)} ${renderAgentName(a.type, theme, { bold: true })}${modeTag} ${theme.fg("muted", a.description)} ${theme.fg("dim", "·")} ${fgPreservingNestedStyles(theme, "dim", statsText)}`),
552
+ truncate(theme.fg("dim", "├─") + ` ${theme.fg("accent", frame)} ${renderAgentName(a.type, theme, { bold: true })}${modeTag} ${theme.fg("muted", sanitizeRowText(a.description))} ${theme.fg("dim", "·")} ${fgPreservingNestedStyles(theme, "dim", statsText)}`),
459
553
  truncate(theme.fg("dim", "│ ") + theme.fg("dim", ` ⎿ ${activity}`)),
460
- truncate(theme.fg("dim", "│ ") + theme.fg("dim", ` ⎿ ${formatAdvisorStatus(a.advisorStatus)}`)),
554
+ truncate(theme.fg("dim", "│ ") + theme.fg("dim", ` ⎿ ${sanitizeRowText(formatAdvisorStatus(a.advisorStatus))}`)),
461
555
  ]);
462
556
  }
463
557
  const queuedLine = queued.length > 0
464
558
  ? truncate(theme.fg("dim", "├─") + ` ${theme.fg("muted", "◦")} ${theme.fg("dim", `${queued.length} queued`)}`)
465
559
  : undefined;
466
- // Assemble with overflow cap (heading + overflow indicator = 2 reserved lines).
467
- const maxBody = MAX_WIDGET_LINES - 1; // heading takes 1 line
468
- const totalBody = finishedLines.length + runningLines.reduce((sum, rows) => sum + rows.length, 0) + (queuedLine ? 1 : 0);
469
- const lines = [truncate(theme.fg(headingColor, headingIcon) + " " + theme.fg(headingColor, "Agents"))];
560
+ const hubHint = this.hub ? theme.fg("dim", " · ← Agent Hub") : "";
561
+ const lines = [truncate(theme.fg(headingColor, headingIcon) + " " + theme.fg(headingColor, "Agents") + hubHint)];
470
562
  if (totalBody <= maxBody) {
471
563
  // Everything fits — add all lines and fix up connectors for the last item.
472
564
  lines.push(...finishedLines);
@@ -494,8 +586,8 @@ export class AgentWidget {
494
586
  // Overflow — prioritize: running > queued > finished.
495
587
  // Reserve 1 line for overflow indicator.
496
588
  let budget = maxBody - 1;
497
- let hiddenRunning = 0;
498
- let hiddenFinished = 0;
589
+ let hiddenRunning = running.length - runningLines.length;
590
+ let hiddenFinished = finished.length - finishedLines.length;
499
591
  // Reserve the queued line's row up front. It is a single summary of N
500
592
  // waiting agents, so it cannot be folded into the "+N more" count (which
501
593
  // is denominated in agents) without either under-reporting it as 1 or
@@ -542,6 +634,22 @@ export class AgentWidget {
542
634
  }
543
635
  return lines;
544
636
  }
637
+ /**
638
+ * Acquire the TUI reference without a visible list. Pi invokes the factory
639
+ * synchronously inside setWidget but paints on the next render tick, so a
640
+ * register immediately followed by an unregister captures the reference and
641
+ * never draws a frame. A separate key from the real widget, so the
642
+ * registration state machine never notices.
643
+ */
644
+ probeTui() {
645
+ if (!this.uiCtx)
646
+ return;
647
+ this.uiCtx.setWidget("agents-probe", tui => {
648
+ this.tui = tui;
649
+ return { render: () => [], invalidate: () => { } };
650
+ });
651
+ this.uiCtx.setWidget("agents-probe", undefined);
652
+ }
545
653
  /** Force an immediate widget update. */
546
654
  update() {
547
655
  if (!this.uiCtx)
@@ -584,7 +692,10 @@ export class AgentWidget {
584
692
  if (this.widgetRegistered) {
585
693
  this.uiCtx.setWidget("agents", undefined);
586
694
  this.widgetRegistered = false;
587
- this.tui = undefined;
695
+ this.registeredPlacement = undefined;
696
+ // `this.tui` deliberately survives the hide: the ← handler reads focus
697
+ // from it, and a reference from any past mount stays valid for the
698
+ // whole interactive session.
588
699
  }
589
700
  if (this.lastStatusText !== undefined) {
590
701
  this.uiCtx.setStatus("subagents", undefined);
@@ -617,21 +728,24 @@ export class AgentWidget {
617
728
  this.lastStatusText = newStatusText;
618
729
  }
619
730
  this.widgetFrame++;
620
- // Register widget callback once; subsequent updates use requestRender()
621
- // which re-invokes render() without replacing the component (avoids layout thrashing).
622
- if (!this.widgetRegistered) {
731
+ // Same-key registration moves between Pi's placement Maps. Otherwise keep
732
+ // the component and its insertion order stable across spinner updates.
733
+ const placement = this.placement();
734
+ if (!this.widgetRegistered || this.registeredPlacement !== placement) {
623
735
  this.uiCtx.setWidget("agents", (tui, theme) => {
624
736
  this.tui = tui;
625
737
  return {
626
- render: () => this.renderWidget(tui, theme),
738
+ render: (width) => this.renderWidget(tui, theme, width),
627
739
  invalidate: () => {
628
- // Theme changed — force re-registration so factory captures fresh theme.
740
+ // Theme changed — force re-registration so the factory captures the
741
+ // fresh theme. The TUI reference stays: it does not change themes.
629
742
  this.widgetRegistered = false;
630
- this.tui = undefined;
743
+ this.registeredPlacement = undefined;
631
744
  },
632
745
  };
633
- }, { placement: "aboveEditor" });
746
+ }, { placement: placement === "above" ? "aboveEditor" : "belowEditor" });
634
747
  this.widgetRegistered = true;
748
+ this.registeredPlacement = placement;
635
749
  }
636
750
  else {
637
751
  // Widget already registered — just request a re-render of existing components.
@@ -641,12 +755,16 @@ export class AgentWidget {
641
755
  dispose() {
642
756
  this.stopInterval();
643
757
  this.clearExpiryTimer();
758
+ this.inputUnsub?.();
759
+ this.inputUnsub = undefined;
644
760
  if (this.uiCtx) {
645
761
  this.uiCtx.setWidget("agents", undefined);
646
762
  this.uiCtx.setStatus("subagents", undefined);
647
763
  }
648
764
  this.widgetRegistered = false;
765
+ this.registeredPlacement = undefined;
649
766
  this.tui = undefined;
767
+ this.uiCtx = undefined;
650
768
  this.lastStatusText = undefined;
651
769
  }
652
770
  }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * cleanup-preview.ts — the `/subagents cleanup` review surface.
3
+ *
4
+ * Two exports, one job: let the user INSPECT a `CleanupPlan` before anything
5
+ * irreversible happens. `formatCleanupPreview` is the plan as plain text —
6
+ * every candidate path, every count, every read flag, every skip, no cap and
7
+ * no subset — and is what a headless caller can print. `showCleanupPreview`
8
+ * puts that same text behind a native-TUI overlay and reports whether the
9
+ * review finished with an explicit Continue.
10
+ *
11
+ * The module is deliberately inert: it never unlinks, prepares, consumes, or
12
+ * even READS the filesystem, and it never asks the deletion question. `true`
13
+ * means only "the user reviewed the plan and chose Continue"; the parent owns
14
+ * the separate `ctx.ui.confirm` gate (and the legacy extra confirmation) and
15
+ * everything that follows it. Esc, cancel, a closed dry run, or any UI that
16
+ * cannot show the preview all resolve `false` — no terminal, no consent.
17
+ *
18
+ * Rendering follows the conversation viewer rather than inventing a layer:
19
+ * the full text lives in a `Text` child, a `ScrollView` holds the scroll
20
+ * state (`updateLayout` + `scrollTop`), and `render` slices the visible
21
+ * window itself — the local `ScrollView` has no height option, and bounded
22
+ * composition through `LAYOUT_NODE` is the fullscreen layout's job, not an
23
+ * overlay's. The whole list stays reachable: page/line/home/end keys scroll
24
+ * to either end, so the tail of `plan.files`/`plan.skipped` is always
25
+ * inspectable. Scroll/confirm/cancel keys come from the injected
26
+ * `KeybindingsManager` where one is available (same `tui.select.*` resolution
27
+ * as the viewer), with enter/escape kept as reflex fallbacks so the gate is
28
+ * never inoperable.
29
+ *
30
+ * Paths are user data drawn on a terminal: backslashes are doubled and
31
+ * C0/C1/DEL characters use `\xNN` escapes, so paths cannot inject controls and
32
+ * no character goes missing. Unicode width, wrapping, and resizing are left
33
+ * to pi-tui's width utilities and the `Text` wrapper.
34
+ */
35
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
36
+ import { type CleanupPlan } from "../report-cleanup.ts";
37
+ /**
38
+ * The complete cleanup preview as plain text: scope, preview-only header,
39
+ * counts and bytes, read flags, every candidate path, and every skip.
40
+ *
41
+ * Pure — same plan in, same string out, no filesystem, no clock beyond the
42
+ * plan's own `createdAt`. This is also the text a non-TUI caller can print,
43
+ * so nothing the overlay shows exists only in the overlay.
44
+ */
45
+ export declare function formatCleanupPreview(plan: CleanupPlan): string;
46
+ /**
47
+ * Show the cleanup preview overlay and report whether the review was
48
+ * completed with an explicit Continue.
49
+ *
50
+ * Returns `true` ONLY in normal (non-dry-run) mode when the user presses the
51
+ * confirm key — that is "review done", not deletion approval; the parent runs
52
+ * its own `ctx.ui.confirm` afterwards. Esc, cancel, a closed dry run, and any
53
+ * environment without a real terminal all return `false`.
54
+ *
55
+ * TUI only: RPC clients report `hasUI` but their `custom()` resolves
56
+ * `undefined`, and print/JSON modes have no UI at all — so anything that is
57
+ * not an interactive terminal is a refusal, never a consent.
58
+ */
59
+ export declare function showCleanupPreview(ctx: ExtensionCommandContext, plan: CleanupPlan, dryRun: boolean): Promise<boolean>;