@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
package/src/types.ts CHANGED
@@ -3,8 +3,8 @@
3
3
  */
4
4
 
5
5
  import type { AgentSession } from "@earendil-works/pi-coding-agent";
6
- import type { AdvisorStatus } from "./advisor-status.js";
7
- import type { LifetimeUsage } from "./usage.js";
6
+ import type { AdvisorStatus } from "./advisor-status.ts";
7
+ import type { LifetimeUsage } from "./usage.ts";
8
8
 
9
9
  /** Use the session's full control surface, including the explicit "off" level. */
10
10
  export type ThinkingLevel = AgentSession["thinkingLevel"];
@@ -105,7 +105,7 @@ export interface AgentConfig {
105
105
  export type JoinMode = 'async' | 'group' | 'smart';
106
106
 
107
107
  /**
108
- * Display mode for the persistent above-editor agent widget.
108
+ * Display mode for the persistent agent widget.
109
109
  * - `all`: show every agent (foreground + background).
110
110
  * - `background`: hide foreground agents (they already render inline as the
111
111
  * Agent tool result, #118); show background/queued/scheduled/RPC.
@@ -113,6 +113,9 @@ export type JoinMode = 'async' | 'group' | 'smart';
113
113
  */
114
114
  export type WidgetMode = 'all' | 'background' | 'off';
115
115
 
116
+ /** Placement of the compact agent widget relative to the prompt editor. */
117
+ export type WidgetPlacement = 'above' | 'below';
118
+
116
119
  /**
117
120
  * How much of the conversation viewer's transcript is rendered as Markdown.
118
121
  * - `off`: every line wraps as literal text, as it did before the mode existed.
@@ -210,6 +213,13 @@ export interface AgentRecord {
210
213
  startGate?: Promise<void>;
211
214
  groupId?: string;
212
215
  joinMode?: JoinMode;
216
+ /**
217
+ * Run identity within one record: incremented once when a resume starts a new
218
+ * run. Completions, group holds and held nudges captured under an older
219
+ * generation are superseded and must not deliver against this run.
220
+ * Undefined (0) is the initial run.
221
+ */
222
+ runGeneration?: number;
213
223
  /** Set when result was already consumed via get_subagent_result — suppresses completion notification. */
214
224
  resultConsumed?: boolean;
215
225
  /** Steering messages queued before the session was ready. */
@@ -228,6 +238,16 @@ export interface AgentRecord {
228
238
  toolCallId?: string;
229
239
  /** Path to the streaming output transcript file. */
230
240
  outputFile?: string;
241
+ /**
242
+ * Every ancestor agent that owns this record, nearest first, captured at
243
+ * spawn time from the live parent chain.
244
+ *
245
+ * This exists so ownership survives the eviction of an intermediate parent:
246
+ * a grandchild archived after Parent2 is gone still names Parent1, which is
247
+ * what an active cleanup uses to protect the descendant's files. A workflow
248
+ * owner stays on `workflowId`; this list is the agent lineage only.
249
+ */
250
+ ownerIds?: string[];
231
251
  /**
232
252
  * The agent's pi session file, when it was persisted (`persist_session`, or
233
253
  * the `rememberAgents` default). Captured so a mention can reopen the
@@ -290,8 +310,18 @@ export interface AgentRecord {
290
310
  * Session id of the root (main) session this branch descends from. Nested
291
311
  * spawns inherit it so their transcripts file under the same session
292
312
  * directory as their ancestors' instead of the child session's own id.
313
+ *
314
+ * Also pinned for spawns that enter outside the Agent tool (mentions,
315
+ * schedules, RPC) from the session context that started them, so child
316
+ * sessions and their archived provenance share one stable root.
293
317
  */
294
318
  rootSessionId?: string;
319
+ /** Stable root project directory; never a worktree copy's cwd. */
320
+ rootCwd?: string;
321
+ /** The root session's pi JSONL file, when it has one. */
322
+ rootSessionFile?: string;
323
+ /** The child session id, once a session exists. Plain string, never a session. */
324
+ sessionId?: string;
295
325
  }
296
326
 
297
327
  /** Actual session level after SDK model-capability clamping. */
@@ -43,9 +43,9 @@
43
43
  */
44
44
 
45
45
  import type { AutocompleteItem, AutocompleteProvider, AutocompleteSuggestions } from "@earendil-works/pi-tui";
46
- import type { AgentManager } from "../agent-manager.js";
47
- import { handleBase, MENTION_TRIGGER } from "../mention.js";
48
- import type { AgentRecord, AgentTombstone } from "../types.js";
46
+ import type { AgentManager } from "../agent-manager.ts";
47
+ import { handleBase, MENTION_TRIGGER } from "../mention.ts";
48
+ import type { AgentRecord, AgentTombstone } from "../types.ts";
49
49
 
50
50
  /**
51
51
  * One thing `@` can address, and what sending to it will do. `typeLabel` is the
@@ -1,22 +1,24 @@
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
7
 
8
- import { truncateToWidth } from "@earendil-works/pi-tui";
9
- import { type AdvisorStatus, formatAdvisorStatus } from "../advisor-status.js";
10
- import { renderAgentName } from "../agent-color.js";
11
- import { type AgentManager, isTopLevelAgent } from "../agent-manager.js";
12
- import { getConfig } from "../agent-types.js";
13
- import type { AgentInvocation, SubagentType, WidgetMode } from "../types.js";
14
- import { getLifetimeCost, getLifetimeTotal, getSessionContextPercent, type LifetimeUsage, type SessionLike } from "../usage.js";
8
+ import { Editor, isKeyRelease, isKeyRepeat, matchesKey, truncateToWidth } from "@earendil-works/pi-tui";
9
+ import { type AdvisorStatus, formatAdvisorStatus } from "../advisor-status.ts";
10
+ import { renderAgentName } from "../agent-color.ts";
11
+ import { type AgentManager, isTopLevelAgent } from "../agent-manager.ts";
12
+ import { getConfig } from "../agent-types.ts";
13
+ import type { AgentInvocation, SubagentType, WidgetMode, WidgetPlacement } from "../types.ts";
14
+ import { getLifetimeCost, getLifetimeTotal, getSessionContextPercent, type LifetimeUsage, type SessionLike } from "../usage.ts";
15
15
 
16
16
  // ---- Constants ----
17
17
 
18
18
  /** Maximum number of rendered lines before overflow collapse kicks in. */
19
19
  const MAX_WIDGET_LINES = 12;
20
+ /** Header, activity and advisor status form one indivisible running card. */
21
+ const RUNNING_CARD_LINES = 3;
20
22
 
21
23
  /** Braille spinner frames for animated running indicator. */
22
24
  export const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
@@ -42,15 +44,39 @@ export type Theme = {
42
44
  bold(text: string): string;
43
45
  };
44
46
 
47
+ type WidgetTUI = {
48
+ terminal: { columns: number };
49
+ requestRender(): void;
50
+ getFocusedComponent?(): unknown;
51
+ focusedComponent?: unknown;
52
+ };
53
+
45
54
  export type UICtx = {
46
55
  setStatus(key: string, text: string | undefined): void;
47
56
  setWidget(
48
57
  key: string,
49
- content: undefined | ((tui: any, theme: Theme) => { render(): string[]; invalidate(): void }),
58
+ content: undefined | ((tui: WidgetTUI, theme: Theme) => { render(width?: number): string[]; invalidate(): void }),
50
59
  options?: { placement?: "aboveEditor" | "belowEditor" },
51
60
  ): void;
61
+ onTerminalInput?(handler: (data: string) => { consume?: boolean } | undefined): () => void;
62
+ getEditorText?(): string;
52
63
  };
53
64
 
65
+ /** The host's side of the ← → Agent Hub shortcut; every field is read live. */
66
+ export interface AgentHubWiring {
67
+ /** Open the Hub overlay. */
68
+ open(): void;
69
+ /**
70
+ * Whether the Hub would have rows: the Hub's content, not the compact list's
71
+ * visibility — a foreground-only roster (filtered out by `widgetMode`) or
72
+ * settled history past the linger must still open. Defaults to the
73
+ * unfiltered top-level roster.
74
+ */
75
+ hasContent?(): boolean;
76
+ /** True while the Hub overlay is open; ← then belongs to it, not this handler. */
77
+ isOpen?(): boolean;
78
+ }
79
+
54
80
  /** Per-agent live activity state. */
55
81
  export interface AgentActivity {
56
82
  activeTools: Map<string, string>;
@@ -216,9 +242,47 @@ export function buildInvocationTags(
216
242
  };
217
243
  }
218
244
 
245
+ /**
246
+ * Make externally supplied text safe to place in ONE terminal row.
247
+ *
248
+ * Every entry an extension returns from `render()` is ONE terminal row: pi's
249
+ * TUI pushes each array element verbatim (`tui.js` `lines.push(line)`) and
250
+ * measures the block's height as `childLines.length`. A literal `\n` — or `\t`,
251
+ * or any other control byte — inside an entry makes the terminal advance a row
252
+ * the renderer never counted, permanently desynchronising its line diff. The
253
+ * visible symptom is a frozen duplicate row left on screen above and rows
254
+ * clipped below (the footer/statusline among them). Truncation cannot rescue
255
+ * it either: pi-tui's `visibleWidth` counts control characters as zero-width,
256
+ * so such a line passes the width check and still wraps in the terminal.
257
+ *
258
+ * Agent descriptions and error messages are the realistic carriers — both are
259
+ * free text (a model-supplied tool argument; a raw `Error.message`, which is
260
+ * frequently multi-line). ANSI styling is applied AFTER this runs, so stripping
261
+ * ESC here doubles as a terminal-injection guard for the plain fragments.
262
+ *
263
+ * Internal whitespace is preserved; see {@link sanitizeRowText} to collapse it.
264
+ */
265
+ export function flattenRow(text: string): string {
266
+ return text
267
+ // Whole escape sequences go, not just the ESC byte: a stripped-but-not-
268
+ // consumed CSI would leave its `[31m` payload as visible garbage.
269
+ .replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g, " ") // OSC (hyperlinks, titles)
270
+ .replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, " ") // CSI (cursor, erase, SGR)
271
+ .replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " ");
272
+ }
273
+
274
+ /**
275
+ * {@link flattenRow} plus whitespace collapsing, for short single-line labels
276
+ * (descriptions, names, error heads) where runs of spaces carry nothing.
277
+ * Use {@link flattenRow} instead where indentation is meaningful.
278
+ */
279
+ export function sanitizeRowText(text: string): string {
280
+ return flattenRow(text).replace(/\s+/g, " ").trim();
281
+ }
282
+
219
283
  /** Truncate text to a single line, max `len` chars. */
220
284
  function truncateLine(text: string, len = 60): string {
221
- const line = text.split("\n").find(l => l.trim())?.trim() ?? "";
285
+ const line = sanitizeRowText(text.split("\n").find(l => l.trim()) ?? "");
222
286
  if (line.length <= len) return line;
223
287
  return line.slice(0, len) + "…";
224
288
  }
@@ -272,8 +336,11 @@ export class AgentWidget {
272
336
 
273
337
  /** Whether the widget callback is currently registered with the TUI. */
274
338
  private widgetRegistered = false;
275
- /** Cached TUI reference from widget factory callback, used for requestRender(). */
276
- private tui: any | undefined;
339
+ private registeredPlacement: WidgetPlacement | undefined;
340
+ private inputUnsub: (() => void) | undefined;
341
+ private hub: AgentHubWiring | undefined;
342
+ /** Cached TUI reference from widget factory callback, used for repaint and focus checks. */
343
+ private tui: WidgetTUI | undefined;
277
344
  /** Last status bar text, used to avoid redundant setStatus calls. */
278
345
  private lastStatusText: string | undefined;
279
346
 
@@ -282,8 +349,7 @@ export class AgentWidget {
282
349
  private agentActivity: Map<string, AgentActivity>,
283
350
  /**
284
351
  * Read live at render time. Selects which agents the widget shows — see
285
- * `WidgetMode`. Defaults to `"all"` when a caller supplies no policy; the
286
- * extension supplies one defaulting to `"background"`.
352
+ * `WidgetMode`. Defaults to `"all"`, matching the extension's own default.
287
353
  */
288
354
  private mode: () => WidgetMode = () => "all",
289
355
  /**
@@ -300,8 +366,15 @@ export class AgentWidget {
300
366
  * conversation viewer unconditionally.
301
367
  */
302
368
  private showModel: () => boolean = () => false,
369
+ /** Read live; changing placement remounts the same widget key once. */
370
+ private placement: () => WidgetPlacement = () => "above",
303
371
  ) {}
304
372
 
373
+ /** Reuse the extension's canonical Agent Hub, without an inline navigation mode. */
374
+ setHubOpener(hub: AgentHubWiring): void {
375
+ this.hub = hub;
376
+ }
377
+
305
378
  /**
306
379
  * Agents eligible for the widget, per the current `WidgetMode`:
307
380
  * - `off`: none (the widget's existing empty-state path hides it entirely).
@@ -325,12 +398,34 @@ export class AgentWidget {
325
398
  /** Set the UI context (grabbed from first tool execution). */
326
399
  setUICtx(ctx: UICtx) {
327
400
  if (ctx !== this.uiCtx) {
328
- // UICtx changed — the widget registered on the old context is gone.
329
- // Force re-registration on next update().
401
+ // UICtx changed — force re-registration and detach the old input listener.
402
+ this.inputUnsub?.();
330
403
  this.uiCtx = ctx;
331
404
  this.widgetRegistered = false;
405
+ this.registeredPlacement = undefined;
332
406
  this.tui = undefined;
333
407
  this.lastStatusText = undefined;
408
+ this.inputUnsub = ctx.onTerminalInput?.(data => {
409
+ if (ctx !== this.uiCtx || !this.hub) return undefined;
410
+ if (isKeyRelease(data) || isKeyRepeat(data) || !matchesKey(data, "left") || ctx.getEditorText?.() !== "") return undefined;
411
+ // The Hub owns every key while it holds the keyboard — re-entering it
412
+ // here would stack a second overlay and swallow the first one's input.
413
+ if (this.hub.isOpen?.()) return undefined;
414
+ // "off" retires the key with the list, like the retired fleetView: false.
415
+ if (this.mode() === "off") return undefined;
416
+ // Focus distinguishes the real prompt from a detached empty editor
417
+ // underneath a dialog — but only with a TUI to read it from. The list
418
+ // may never have mounted (a foreground-only roster under "background"),
419
+ // so the reference is acquired on demand rather than awaited.
420
+ if (this.tui === undefined) this.probeTui();
421
+ if (this.tui === undefined) return undefined;
422
+ const focused = this.tui.getFocusedComponent?.() ?? this.tui.focusedComponent;
423
+ if (focused != null && !(focused instanceof Editor)) return undefined;
424
+ const hasContent = this.hub.hasContent?.() ?? this.manager.listAgents().some(isTopLevelAgent);
425
+ if (!hasContent) return undefined;
426
+ this.hub.open();
427
+ return { consume: true };
428
+ });
334
429
  }
335
430
  }
336
431
 
@@ -442,7 +537,9 @@ export class AgentWidget {
442
537
  statusText = theme.fg("dim", " stopped");
443
538
  } else if (a.status === "error") {
444
539
  icon = theme.fg("error", "✗");
445
- const errMsg = a.error ? `: ${a.error.slice(0, 60)}` : "";
540
+ // Error messages are routinely multi-line; they must be flattened before
541
+ // the slice, or a truncated tail keeps the newline that breaks the row.
542
+ const errMsg = a.error ? `: ${sanitizeRowText(a.error).slice(0, 60)}` : "";
446
543
  statusText = theme.fg("error", ` error${errMsg}`);
447
544
  } else {
448
545
  // aborted
@@ -462,14 +559,14 @@ export class AgentWidget {
462
559
  parts.push(duration);
463
560
 
464
561
  const modeTag = modeLabel ? ` ${theme.fg("dim", `(${modeLabel})`)}` : "";
465
- return `${icon} ${renderAgentName(a.type, theme, { fallbackColor: "dim" })}${modeTag} ${theme.fg("dim", a.description)} ${theme.fg("dim", "·")} ${theme.fg("dim", parts.join(" · "))}${statusText}`;
562
+ return `${icon} ${renderAgentName(a.type, theme, { fallbackColor: "dim" })}${modeTag} ${theme.fg("dim", sanitizeRowText(a.description))} ${theme.fg("dim", "·")} ${theme.fg("dim", parts.join(" · "))}${statusText}`;
466
563
  }
467
564
 
468
565
  /**
469
566
  * Render the widget content. Called from the registered widget's render() callback,
470
567
  * reading live state each time instead of capturing it in a closure.
471
568
  */
472
- private renderWidget(tui: any, theme: Theme): string[] {
569
+ private renderWidget(tui: WidgetTUI, theme: Theme, width?: number): string[] {
473
570
  const allAgents = this.widgetAgents();
474
571
  const running = allAgents.filter(a => a.status === "running");
475
572
  const queued = allAgents.filter(a => a.status === "queued");
@@ -484,22 +581,34 @@ export class AgentWidget {
484
581
  // Nothing to show — return empty (widget will be unregistered by update())
485
582
  if (!hasActive && !hasFinished) return [];
486
583
 
487
- const w = tui.terminal.columns;
584
+ // Render to the width the HOST allocated, not the terminal's: the dock can
585
+ // be narrower than `terminal.columns`, and a line wider than its slot wraps
586
+ // in the terminal while the renderer still counts one row — the same
587
+ // desync an embedded newline causes. Older hosts call render() with no
588
+ // argument; fall back to the terminal width for them.
589
+ const w = typeof width === "number" && Number.isFinite(width) && width >= 0 ? width : tui.terminal.columns;
488
590
  const truncate = (line: string) => truncateToWidth(line, w);
489
591
  const headingColor = hasActive ? "accent" : "dim";
490
592
  const headingIcon = hasActive ? "●" : "○";
491
593
  const frame = SPINNER[this.widgetFrame % SPINNER.length];
492
594
 
493
- // Build sections separately for overflow-aware assembly.
494
- // Running agents have header, activity and advisor rows; finished/queued stay compact.
595
+ // Apply the existing overflow priority before formatting. Hidden cards must
596
+ // not project session history or format text just to be discarded below.
597
+ const maxBody = MAX_WIDGET_LINES - 1;
598
+ const queueRows = queued.length > 0 ? 1 : 0;
599
+ const totalBody = finished.length + running.length * RUNNING_CARD_LINES + queueRows;
600
+ const overflow = totalBody > maxBody;
601
+ const cardBudget = overflow ? maxBody - 1 - queueRows : maxBody;
602
+ const runningLimit = overflow ? Math.min(running.length, Math.floor(cardBudget / RUNNING_CARD_LINES)) : running.length;
603
+ const finishedLimit = overflow ? Math.max(0, cardBudget - runningLimit * RUNNING_CARD_LINES) : finished.length;
495
604
 
496
605
  const finishedLines: string[] = [];
497
- for (const a of finished) {
606
+ for (const a of finished.slice(0, finishedLimit)) {
498
607
  finishedLines.push(truncate(theme.fg("dim", "├─") + " " + this.renderFinishedLine(a, theme)));
499
608
  }
500
609
 
501
610
  const runningLines: string[][] = []; // each entry is [header, activity, advisor]
502
- for (const a of running) {
611
+ for (const a of running.slice(0, runningLimit)) {
503
612
  const modeLabel = getPromptModeLabel(a.type);
504
613
  const modeTag = modeLabel ? ` ${theme.fg("dim", `(${modeLabel})`)}` : "";
505
614
  const elapsed = formatMs(Date.now() - a.startedAt);
@@ -519,11 +628,13 @@ export class AgentWidget {
519
628
  if (this.showModel()) {
520
629
  // Leading, and paired: a thinking level means nothing without the model
521
630
  // it applies to. The tag is taken from buildInvocationTags rather than
522
- // rebuilt so the "(asked X)" annotation survives.
631
+ // rebuilt so the "(asked X)" annotation survives. Both are plain text
632
+ // that ends up inside a styled run, so they are flattened first — a
633
+ // control byte here would still break the row.
523
634
  const { modelName, tags } = buildInvocationTags(a.invocation);
524
- if (modelName) parts.push(modelName);
635
+ if (modelName) parts.push(sanitizeRowText(modelName));
525
636
  const thinkingTag = tags.find(tag => tag.startsWith("thinking: "));
526
- if (thinkingTag) parts.push(thinkingTag);
637
+ if (thinkingTag) parts.push(sanitizeRowText(thinkingTag));
527
638
  }
528
639
  if (bg) parts.push(formatTurns(bg.turnCount, bg.maxTurns));
529
640
  if (toolUses > 0) parts.push(`${toolUses} tool use${toolUses === 1 ? "" : "s"}`);
@@ -532,12 +643,12 @@ export class AgentWidget {
532
643
  parts.push(elapsed);
533
644
  const statsText = parts.join(" · ");
534
645
 
535
- const activity = bg ? describeActivity(bg.activeTools, bg.responseText) : "thinking…";
646
+ const activity = sanitizeRowText(bg ? describeActivity(bg.activeTools, bg.responseText) : "thinking…");
536
647
 
537
648
  runningLines.push([
538
- 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)}`),
649
+ 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)}`),
539
650
  truncate(theme.fg("dim", "│ ") + theme.fg("dim", ` ⎿ ${activity}`)),
540
- truncate(theme.fg("dim", "│ ") + theme.fg("dim", ` ⎿ ${formatAdvisorStatus(a.advisorStatus)}`)),
651
+ truncate(theme.fg("dim", "│ ") + theme.fg("dim", ` ⎿ ${sanitizeRowText(formatAdvisorStatus(a.advisorStatus))}`)),
541
652
  ]);
542
653
  }
543
654
 
@@ -545,11 +656,8 @@ export class AgentWidget {
545
656
  ? truncate(theme.fg("dim", "├─") + ` ${theme.fg("muted", "◦")} ${theme.fg("dim", `${queued.length} queued`)}`)
546
657
  : undefined;
547
658
 
548
- // Assemble with overflow cap (heading + overflow indicator = 2 reserved lines).
549
- const maxBody = MAX_WIDGET_LINES - 1; // heading takes 1 line
550
- const totalBody = finishedLines.length + runningLines.reduce((sum, rows) => sum + rows.length, 0) + (queuedLine ? 1 : 0);
551
-
552
- const lines: string[] = [truncate(theme.fg(headingColor, headingIcon) + " " + theme.fg(headingColor, "Agents"))];
659
+ const hubHint = this.hub ? theme.fg("dim", " · ← Agent Hub") : "";
660
+ const lines: string[] = [truncate(theme.fg(headingColor, headingIcon) + " " + theme.fg(headingColor, "Agents") + hubHint)];
553
661
 
554
662
  if (totalBody <= maxBody) {
555
663
  // Everything fits — add all lines and fix up connectors for the last item.
@@ -576,8 +684,8 @@ export class AgentWidget {
576
684
  // Overflow — prioritize: running > queued > finished.
577
685
  // Reserve 1 line for overflow indicator.
578
686
  let budget = maxBody - 1;
579
- let hiddenRunning = 0;
580
- let hiddenFinished = 0;
687
+ let hiddenRunning = running.length - runningLines.length;
688
+ let hiddenFinished = finished.length - finishedLines.length;
581
689
 
582
690
  // Reserve the queued line's row up front. It is a single summary of N
583
691
  // waiting agents, so it cannot be folded into the "+N more" count (which
@@ -628,6 +736,22 @@ export class AgentWidget {
628
736
  return lines;
629
737
  }
630
738
 
739
+ /**
740
+ * Acquire the TUI reference without a visible list. Pi invokes the factory
741
+ * synchronously inside setWidget but paints on the next render tick, so a
742
+ * register immediately followed by an unregister captures the reference and
743
+ * never draws a frame. A separate key from the real widget, so the
744
+ * registration state machine never notices.
745
+ */
746
+ private probeTui(): void {
747
+ if (!this.uiCtx) return;
748
+ this.uiCtx.setWidget("agents-probe", tui => {
749
+ this.tui = tui;
750
+ return { render: () => [], invalidate: () => {} };
751
+ });
752
+ this.uiCtx.setWidget("agents-probe", undefined);
753
+ }
754
+
631
755
  /** Force an immediate widget update. */
632
756
  update() {
633
757
  if (!this.uiCtx) return;
@@ -665,7 +789,10 @@ export class AgentWidget {
665
789
  if (this.widgetRegistered) {
666
790
  this.uiCtx.setWidget("agents", undefined);
667
791
  this.widgetRegistered = false;
668
- this.tui = undefined;
792
+ this.registeredPlacement = undefined;
793
+ // `this.tui` deliberately survives the hide: the ← handler reads focus
794
+ // from it, and a reference from any past mount stays valid for the
795
+ // whole interactive session.
669
796
  }
670
797
  if (this.lastStatusText !== undefined) {
671
798
  this.uiCtx.setStatus("subagents", undefined);
@@ -697,21 +824,24 @@ export class AgentWidget {
697
824
 
698
825
  this.widgetFrame++;
699
826
 
700
- // Register widget callback once; subsequent updates use requestRender()
701
- // which re-invokes render() without replacing the component (avoids layout thrashing).
702
- if (!this.widgetRegistered) {
827
+ // Same-key registration moves between Pi's placement Maps. Otherwise keep
828
+ // the component and its insertion order stable across spinner updates.
829
+ const placement = this.placement();
830
+ if (!this.widgetRegistered || this.registeredPlacement !== placement) {
703
831
  this.uiCtx.setWidget("agents", (tui, theme) => {
704
832
  this.tui = tui;
705
833
  return {
706
- render: () => this.renderWidget(tui, theme),
834
+ render: (width?: number) => this.renderWidget(tui, theme, width),
707
835
  invalidate: () => {
708
- // Theme changed — force re-registration so factory captures fresh theme.
836
+ // Theme changed — force re-registration so the factory captures the
837
+ // fresh theme. The TUI reference stays: it does not change themes.
709
838
  this.widgetRegistered = false;
710
- this.tui = undefined;
839
+ this.registeredPlacement = undefined;
711
840
  },
712
841
  };
713
- }, { placement: "aboveEditor" });
842
+ }, { placement: placement === "above" ? "aboveEditor" : "belowEditor" });
714
843
  this.widgetRegistered = true;
844
+ this.registeredPlacement = placement;
715
845
  } else {
716
846
  // Widget already registered — just request a re-render of existing components.
717
847
  this.tui?.requestRender();
@@ -721,12 +851,16 @@ export class AgentWidget {
721
851
  dispose() {
722
852
  this.stopInterval();
723
853
  this.clearExpiryTimer();
854
+ this.inputUnsub?.();
855
+ this.inputUnsub = undefined;
724
856
  if (this.uiCtx) {
725
857
  this.uiCtx.setWidget("agents", undefined);
726
858
  this.uiCtx.setStatus("subagents", undefined);
727
859
  }
728
860
  this.widgetRegistered = false;
861
+ this.registeredPlacement = undefined;
729
862
  this.tui = undefined;
863
+ this.uiCtx = undefined;
730
864
  this.lastStatusText = undefined;
731
865
  }
732
866
  }