@timmyjl12/pi-subagents 0.20.0 → 0.21.1

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 +3616 -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 +4133 -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
@@ -0,0 +1,518 @@
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
+
36
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
37
+ import {
38
+ type Component,
39
+ isKeyRelease,
40
+ type Keybinding,
41
+ type KeybindingsManager,
42
+ type KeyId,
43
+ matchesKey,
44
+ ScrollView,
45
+ Text,
46
+ type TUI,
47
+ type TuiMouseEvent,
48
+ type TuiMouseEventResult,
49
+ truncateToWidth,
50
+ visibleWidth,
51
+ wrapTextWithAnsi,
52
+ } from "@earendil-works/pi-tui";
53
+ import {
54
+ type CleanupFileInventory,
55
+ type CleanupPlan,
56
+ type CleanupSkip,
57
+ cleanupReadStateLabel,
58
+ isCleanupPlanEmpty,
59
+ } from "../report-cleanup.ts";
60
+ import type { Theme } from "./agent-widget.ts";
61
+ import { createViewerKeys, type ViewerKeys } from "./viewer-keys.ts";
62
+
63
+ /** Semantic tones the overlay applies; the pure text carries them untyped. */
64
+ type PreviewTone = "title" | "heading" | "dim" | "warning" | "plain";
65
+
66
+ interface PreviewLine {
67
+ text: string;
68
+ tone: PreviewTone;
69
+ /** Fixed above the scroll region in the overlay; still part of the text. */
70
+ fixed?: boolean;
71
+ }
72
+
73
+ /**
74
+ * Show control characters as `\xNN` instead of emitting them.
75
+ *
76
+ * A report path is drawn verbatim inside a terminal frame; a raw ESC or BEL
77
+ * in one would inject terminal control sequences into the preview itself.
78
+ * The escaping is per code point and reversible, so the display loses no
79
+ * data — it just cannot execute.
80
+ */
81
+ function escapeDisplay(value: string): string {
82
+ let out = "";
83
+ for (const ch of value) {
84
+ const code = ch.codePointAt(0) ?? 0;
85
+ if (ch === "\\") {
86
+ out += "\\\\";
87
+ } else if (code < 0x20 || (code >= 0x7f && code <= 0x9f)) {
88
+ out += `\\x${code.toString(16).toUpperCase().padStart(2, "0")}`;
89
+ } else {
90
+ out += ch;
91
+ }
92
+ }
93
+ return out;
94
+ }
95
+
96
+ /** 1024-based, one decimal under 100 — `512 B`, `1.5 KB`, `340 MB`. */
97
+ function formatBytes(bytes: number): string {
98
+ if (!Number.isFinite(bytes) || bytes <= 0) return "0 B";
99
+ if (bytes < 1024) return `${bytes} B`;
100
+ const units = ["KB", "MB", "GB", "TB"] as const;
101
+ let value = bytes;
102
+ let unit = -1;
103
+ do {
104
+ value /= 1024;
105
+ unit++;
106
+ } while (value >= 1024 && unit < units.length - 1);
107
+ const rounded = value >= 100 ? String(Math.round(value)) : value.toFixed(1).replace(/\.0$/, "");
108
+ return `${rounded} ${units[unit]}`;
109
+ }
110
+
111
+ const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? "" : "s"}`;
112
+
113
+ /** One line per file: size and kind as aligned columns, then state, flags, path. */
114
+ function fileLine(file: CleanupFileInventory, sizeWidth: number, kindWidth: number): string {
115
+ const flags = [file.legacy ? "legacy" : "", file.shared ? "shared" : ""].filter(Boolean).join(" ");
116
+ const head = `${formatBytes(file.size).padEnd(sizeWidth)} ${file.kind.padEnd(kindWidth)} ${cleanupReadStateLabel(file.readState)}`;
117
+ return ` ${head}${flags ? ` ${flags}` : ""} ${escapeDisplay(file.path)}`;
118
+ }
119
+
120
+ /** One line per skip: the reason first — it is why the file survives — then identity, then path. */
121
+ function skipLine(skip: CleanupSkip): string {
122
+ const tags: string[] = [];
123
+ if (skip.kind) tags.push(skip.kind);
124
+ if (skip.agentId) tags.push(`agent ${escapeDisplay(skip.agentId)}`);
125
+ if (skip.workflowId) tags.push(`workflow ${escapeDisplay(skip.workflowId)}`);
126
+ if (skip.rootSessionId) tags.push(`root ${escapeDisplay(skip.rootSessionId)}`);
127
+ if (skip.legacy) tags.push("legacy");
128
+ const identity = tags.length > 0 ? ` (${tags.join(", ")})` : "";
129
+ const path = skip.path ? ` — ${escapeDisplay(skip.path)}` : "";
130
+ return ` ${escapeDisplay(skip.reason)}${identity}${path}`;
131
+ }
132
+
133
+ /**
134
+ * The whole plan as ordered lines. Nothing is capped, windowed, or sampled:
135
+ * `plan.files` and `plan.skipped` map one-to-one onto lines here, and the
136
+ * counts are the plan's own rather than a recomputation that could drift.
137
+ */
138
+ function buildCleanupPreviewLines(plan: CleanupPlan): PreviewLine[] {
139
+ const lines: PreviewLine[] = [];
140
+ const counts = plan.counts;
141
+
142
+ lines.push({ text: `Cleanup preview — ${plan.scope} scope`, tone: "title", fixed: true });
143
+ lines.push({ text: "Preview only — no changes have been made.", tone: "dim", fixed: true });
144
+ lines.push({ text: "Your own session history is never a cleanup candidate.", tone: "dim", fixed: true });
145
+ lines.push({ text: "Paths escape backslashes as \\\\ and control characters as \\xNN.", tone: "dim" });
146
+
147
+ const created = new Date(plan.createdAt).toISOString();
148
+ lines.push({
149
+ text: `Plan ${escapeDisplay(plan.planId)} · created ${created} · ${plural(plan.roots.length, "root")}`,
150
+ tone: "dim",
151
+ });
152
+ if (plan.identityUncertainty) {
153
+ lines.push({
154
+ text: `Identity uncertainty: ${escapeDisplay(plan.identityUncertainty)} — child-history candidates were refused.`,
155
+ tone: "warning",
156
+ });
157
+ }
158
+
159
+ lines.push({ text: "", tone: "plain" });
160
+ lines.push({ text: `Summary — ${plural(counts.files, "file")} · ${formatBytes(counts.bytes)}`, tone: "heading" });
161
+ lines.push({
162
+ text: ` ${plural(counts.reports, "report")} · task outputs ${counts.taskOutputs} · workflow files ${counts.workflowFiles} · child sessions ${counts.childSessions}`,
163
+ tone: "plain",
164
+ });
165
+ lines.push({
166
+ text: ` legacy ${counts.legacy} · diagnostics ${counts.diagnostics} · root metadata ${counts.rootMetadata}`,
167
+ tone: "plain",
168
+ });
169
+ const unreadNote = counts.unread > 0 ? " (not marked as read)" : "";
170
+ lines.push({
171
+ text: ` read state: ${plural(counts.unread, "unread artifact")}${unreadNote} · ${counts.unknownReadState} ${cleanupReadStateLabel("unknown")}`,
172
+ tone: counts.unread > 0 || counts.unknownReadState > 0 ? "warning" : "plain",
173
+ });
174
+
175
+ lines.push({ text: "", tone: "plain" });
176
+ if (plan.files.length === 0) {
177
+ lines.push({ text: "Files: none — nothing is eligible for cleanup.", tone: "dim" });
178
+ } else {
179
+ lines.push({ text: `Files (${plan.files.length}):`, tone: "heading" });
180
+ let sizeWidth = 0;
181
+ let kindWidth = 0;
182
+ for (const file of plan.files) {
183
+ sizeWidth = Math.max(sizeWidth, formatBytes(file.size).length);
184
+ kindWidth = Math.max(kindWidth, file.kind.length);
185
+ }
186
+ for (const file of plan.files) {
187
+ lines.push({ text: fileLine(file, sizeWidth, kindWidth), tone: "plain" });
188
+ }
189
+ }
190
+
191
+ lines.push({ text: "", tone: "plain" });
192
+ if (plan.skipped.length === 0) {
193
+ lines.push({ text: "Skipped: none.", tone: "dim" });
194
+ } else {
195
+ lines.push({ text: `Skipped (${plan.skipped.length}):`, tone: "heading" });
196
+ for (const skip of plan.skipped) {
197
+ lines.push({ text: skipLine(skip), tone: "plain" });
198
+ }
199
+ }
200
+
201
+ return lines;
202
+ }
203
+
204
+ /**
205
+ * The complete cleanup preview as plain text: scope, preview-only header,
206
+ * counts and bytes, read flags, every candidate path, and every skip.
207
+ *
208
+ * Pure — same plan in, same string out, no filesystem, no clock beyond the
209
+ * plan's own `createdAt`. This is also the text a non-TUI caller can print,
210
+ * so nothing the overlay shows exists only in the overlay.
211
+ */
212
+ export function formatCleanupPreview(plan: CleanupPlan): string {
213
+ return buildCleanupPreviewLines(plan).map(line => line.text).join("\n");
214
+ }
215
+
216
+ /** Apply a tone with the active theme. Neutral by default; `warning` only for warnings. */
217
+ function styleLine(theme: Theme, line: PreviewLine): string {
218
+ switch (line.tone) {
219
+ case "title":
220
+ return theme.bold(line.text);
221
+ case "heading":
222
+ return theme.bold(theme.fg("muted", line.text));
223
+ case "dim":
224
+ return theme.fg("dim", line.text);
225
+ case "warning":
226
+ return theme.fg("warning", line.text);
227
+ default:
228
+ return line.text;
229
+ }
230
+ }
231
+
232
+ /** Short display names for the keys a footer advertises. */
233
+ function keyLabel(id: KeyId): string {
234
+ switch (id) {
235
+ case "escape":
236
+ case "esc":
237
+ return "esc";
238
+ case "enter":
239
+ case "return":
240
+ return "enter";
241
+ case "up":
242
+ return "↑";
243
+ case "down":
244
+ return "↓";
245
+ case "pageUp":
246
+ return "PgUp";
247
+ case "pageDown":
248
+ return "PgDn";
249
+ case "home":
250
+ return "Home";
251
+ case "end":
252
+ return "End";
253
+ default:
254
+ return id;
255
+ }
256
+ }
257
+
258
+ /**
259
+ * The overlay component. One instance per `ctx.ui.custom` call; the
260
+ * interaction ends only through `done`, never through an overlay handle.
261
+ */
262
+ class CleanupPreview implements Component {
263
+ private closed = false;
264
+ private reviewable = false;
265
+ private readonly text: Text;
266
+ private readonly scroll: ScrollView;
267
+ private readonly keys: ViewerKeys;
268
+ private readonly fixedLines: PreviewLine[];
269
+ private readonly bodyLines: PreviewLine[];
270
+ private styledBodyCache: string | undefined;
271
+ private lastStyledBody: string | undefined;
272
+ private contentTop = 0;
273
+
274
+ constructor(
275
+ private readonly tui: TUI,
276
+ private readonly theme: Theme,
277
+ private readonly keybindings: KeybindingsManager | undefined,
278
+ private readonly plan: CleanupPlan,
279
+ private readonly dryRun: boolean,
280
+ private readonly done: (result: boolean) => void,
281
+ ) {
282
+ const lines = buildCleanupPreviewLines(plan);
283
+ this.fixedLines = lines.filter(line => line.fixed);
284
+ this.bodyLines = lines.filter(line => !line.fixed);
285
+ this.text = new Text("", 0, 0);
286
+ this.scroll = new ScrollView(this.text, { follow: "none", scrollbar: "hidden", overscroll: "contain" });
287
+ this.keys = createViewerKeys(keybindings);
288
+ }
289
+
290
+ handleInput(data: string): void {
291
+ if (this.closed || isKeyRelease(data)) return;
292
+ if (this.isCancel(data)) {
293
+ this.close(false);
294
+ return;
295
+ }
296
+ if (this.isConfirm(data)) {
297
+ // The ONLY path that resolves true: an explicit Continue in normal
298
+ // mode. A dry run closes — it never consents.
299
+ this.close(!this.dryRun && this.reviewable);
300
+ return;
301
+ }
302
+ if (this.keys.scrollUp(data)) this.scroll.scrollBy(-1);
303
+ else if (this.keys.scrollDown(data)) this.scroll.scrollBy(1);
304
+ else if (this.keys.pageUp(data)) this.scroll.scrollBy(-Math.max(1, this.scroll.viewportHeight));
305
+ else if (this.keys.pageDown(data)) this.scroll.scrollBy(Math.max(1, this.scroll.viewportHeight));
306
+ else if (this.isBoundary(data, "top")) this.scroll.scrollToStart();
307
+ else if (this.isBoundary(data, "bottom")) this.scroll.scrollToEnd();
308
+ else return;
309
+ this.tui.requestRender();
310
+ }
311
+
312
+ render(width: number): string[] {
313
+ this.reviewable = false;
314
+ const rows = Math.max(0, this.tui.terminal.rows);
315
+ if (width < 6 || rows === 0) return [];
316
+ const th = this.theme;
317
+ const innerW = width - 4;
318
+ const lines: string[] = [];
319
+
320
+ const pad = (s: string, len: number) => {
321
+ const vis = visibleWidth(s);
322
+ return s + " ".repeat(Math.max(0, len - vis));
323
+ };
324
+ const row = (content: string) =>
325
+ th.fg("border", "│") + " " + truncateToWidth(pad(content, innerW), innerW, "...", true) + " " + th.fg("border", "│");
326
+ const hrTop = th.fg("border", `╭${"─".repeat(width - 2)}╮`);
327
+ const hrBot = th.fg("border", `╰${"─".repeat(width - 2)}╯`);
328
+ const hrMid = row(th.fg("dim", "─".repeat(Math.max(0, innerW))));
329
+
330
+ lines.push(hrTop);
331
+ // Fixed chrome: the preview-only header, then the mode line. Wrapped, not
332
+ // truncated — the warning's unread count must survive a narrow terminal.
333
+ for (const line of [...this.fixedLines, ...this.modeLines()]) {
334
+ for (const wrapped of wrapTextWithAnsi(styleLine(th, line), Math.max(1, innerW))) {
335
+ lines.push(row(wrapped));
336
+ }
337
+ }
338
+ lines.push(hrMid);
339
+
340
+ // Keep the frame inside the terminal; the scroll region gets what is left.
341
+ const footerRows = rows >= 4 ? 2 : 0;
342
+ const viewportHeight = Math.max(0, rows - lines.length - footerRows);
343
+ if (viewportHeight === 0) {
344
+ return [truncateToWidth("Resize terminal to inspect cleanup; Esc cancels.", width)];
345
+ }
346
+ const content = this.contentLines(innerW);
347
+ this.scroll.updateLayout(content.length, viewportHeight, () => {
348
+ if (!this.closed) this.tui.requestRender();
349
+ });
350
+ this.contentTop = lines.length;
351
+ const visible = content.slice(this.scroll.scrollTop, this.scroll.scrollTop + viewportHeight);
352
+ for (let i = 0; i < viewportHeight; i++) lines.push(row(visible[i] ?? ""));
353
+ if (footerRows) {
354
+ lines.push(row(th.fg("dim", this.footerText(content.length, viewportHeight))));
355
+ lines.push(hrBot);
356
+ }
357
+ this.reviewable = true;
358
+ return lines.slice(0, rows);
359
+ }
360
+
361
+ handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined {
362
+ if (this.closed) return undefined;
363
+ if (event.type === "wheel" && event.y >= this.contentTop && event.y < this.contentTop + this.scroll.viewportHeight) {
364
+ this.scroll.scrollBy(event.wheelDelta ?? 0);
365
+ this.tui.requestRender();
366
+ return { handled: true };
367
+ }
368
+ return undefined;
369
+ }
370
+
371
+ invalidate(): void {
372
+ // The styled body embeds theme colors; rebuild it rather than reusing them.
373
+ this.styledBodyCache = undefined;
374
+ this.text.invalidate();
375
+ }
376
+
377
+ dispose(): void {
378
+ this.closed = true;
379
+ }
380
+
381
+ // ---- Private ----
382
+
383
+ private close(result: boolean): void {
384
+ if (this.closed) return;
385
+ this.closed = true;
386
+ this.done(result);
387
+ }
388
+
389
+ /**
390
+ * Cancel is escape/ctrl+c even when the user rebound `tui.select.cancel`:
391
+ * the reflex key must never strand someone inside a deletion review.
392
+ */
393
+ private isCancel(data: string): boolean {
394
+ return (
395
+ matchesKey(data, "escape") ||
396
+ matchesKey(data, "ctrl+c") ||
397
+ (this.keybindings?.matches(data, "tui.select.cancel") ?? false)
398
+ );
399
+ }
400
+
401
+ /** Enter always works alongside the configured confirm binding. */
402
+ private isConfirm(data: string): boolean {
403
+ return matchesKey(data, "enter") || (this.keybindings?.matches(data, "tui.select.confirm") ?? false);
404
+ }
405
+
406
+ private isBoundary(data: string, boundary: "top" | "bottom"): boolean {
407
+ if (boundary === "top") {
408
+ return (
409
+ matchesKey(data, "home") ||
410
+ matchesKey(data, "ctrl+home") ||
411
+ matchesKey(data, "ctrl+shift+home") ||
412
+ (this.keybindings?.matches(data, "tui.altScreen.top") ?? false)
413
+ );
414
+ }
415
+ return (
416
+ matchesKey(data, "end") ||
417
+ matchesKey(data, "ctrl+end") ||
418
+ matchesKey(data, "ctrl+shift+end") ||
419
+ (this.keybindings?.matches(data, "tui.altScreen.bottom") ?? false)
420
+ );
421
+ }
422
+
423
+ /** The fixed line under the header: what THIS showing of the preview means. */
424
+ private modeLines(): PreviewLine[] {
425
+ if (this.dryRun) {
426
+ return [{ text: "Dry run — review only; nothing will be deleted.", tone: "dim" }];
427
+ }
428
+ if (isCleanupPlanEmpty(this.plan)) {
429
+ return [{ text: "Nothing is eligible for cleanup.", tone: "dim" }];
430
+ }
431
+ const counts = this.plan.counts;
432
+ const parts: string[] = [];
433
+ if (counts.unread > 0) {
434
+ parts.push(`${plural(counts.unread, "unread artifact")} (not marked as read)`);
435
+ }
436
+ if (counts.unknownReadState > 0) {
437
+ parts.push(`read state unknown for ${plural(counts.unknownReadState, "artifact")} (archived read state was not recorded)`);
438
+ }
439
+ const detail = parts.length > 0 ? ` — ${parts.join("; ")}` : "";
440
+ return [
441
+ { text: `Warning — a confirmed cleanup permanently discards every file below${detail}.`, tone: "warning" },
442
+ ];
443
+ }
444
+
445
+ private footerText(contentLength: number, viewportHeight: number): string {
446
+ const hints: string[] = [];
447
+ const confirmKey = this.firstKeyLabel("tui.select.confirm", "enter");
448
+ const cancelKey = this.firstKeyLabel("tui.select.cancel", "esc");
449
+ if (this.dryRun) {
450
+ hints.push(`${confirmKey}/${cancelKey} close`);
451
+ } else {
452
+ hints.push(`${confirmKey} continue`, `${cancelKey} cancel`);
453
+ }
454
+ hints.push(`${this.firstKeyLabel("tui.select.up", "↑")}${this.firstKeyLabel("tui.select.down", "↓")} scroll`);
455
+ hints.push(`${this.firstKeyLabel("tui.select.pageUp", "PgUp")}/${this.firstKeyLabel("tui.select.pageDown", "PgDn")} page`);
456
+ hints.push("Home/End top/bottom");
457
+ // Position last: it is the first hint a narrow footer may drop.
458
+ if (contentLength > viewportHeight) {
459
+ const top = this.scroll.scrollTop + 1;
460
+ const bottom = Math.min(this.scroll.scrollTop + viewportHeight, contentLength);
461
+ hints.push(`${top}–${bottom}/${contentLength}`);
462
+ }
463
+ return hints.join(" · ");
464
+ }
465
+
466
+ /** The user's own key for an action where bound, else the default label. */
467
+ private firstKeyLabel(keybinding: Keybinding, fallback: string): string {
468
+ const keys = this.keybindings?.getKeys(keybinding);
469
+ return keys && keys.length > 0 ? keyLabel(keys[0]) : fallback;
470
+ }
471
+
472
+ private contentLines(width: number): string[] {
473
+ const styled = this.styledBody();
474
+ if (styled !== this.lastStyledBody) {
475
+ this.text.setText(styled);
476
+ this.lastStyledBody = styled;
477
+ }
478
+ return this.text.render(Math.max(1, width));
479
+ }
480
+
481
+ private styledBody(): string {
482
+ if (this.styledBodyCache === undefined) {
483
+ this.styledBodyCache = this.bodyLines.map(line => styleLine(this.theme, line)).join("\n");
484
+ }
485
+ return this.styledBodyCache;
486
+ }
487
+ }
488
+
489
+ /**
490
+ * Show the cleanup preview overlay and report whether the review was
491
+ * completed with an explicit Continue.
492
+ *
493
+ * Returns `true` ONLY in normal (non-dry-run) mode when the user presses the
494
+ * confirm key — that is "review done", not deletion approval; the parent runs
495
+ * its own `ctx.ui.confirm` afterwards. Esc, cancel, a closed dry run, and any
496
+ * environment without a real terminal all return `false`.
497
+ *
498
+ * TUI only: RPC clients report `hasUI` but their `custom()` resolves
499
+ * `undefined`, and print/JSON modes have no UI at all — so anything that is
500
+ * not an interactive terminal is a refusal, never a consent.
501
+ */
502
+ export async function showCleanupPreview(
503
+ ctx: ExtensionCommandContext,
504
+ plan: CleanupPlan,
505
+ dryRun: boolean,
506
+ ): Promise<boolean> {
507
+ if (ctx.mode !== "tui" || !ctx.hasUI) return false;
508
+ let reviewed: boolean | undefined;
509
+ try {
510
+ reviewed = await ctx.ui.custom<boolean>(
511
+ (tui, theme, keybindings, done) => new CleanupPreview(tui, theme, keybindings, plan, dryRun, done),
512
+ { overlay: true, overlayOptions: { anchor: "center", width: "90%", maxHeight: "100%" } },
513
+ );
514
+ } catch {
515
+ return false;
516
+ }
517
+ return reviewed === true;
518
+ }
@@ -7,16 +7,16 @@
7
7
 
8
8
  import { type AgentSession, CustomEditor, getMarkdownTheme, type KeybindingsManager } from "@earendil-works/pi-coding-agent";
9
9
  import { type Component, CURSOR_MARKER, type Focusable, getKeybindings, isKeyRelease, Markdown, type MarkdownOptions, type MarkdownTheme, matchesKey, ScrollView, type TUI, type TuiMouseEvent, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
10
- import { renderAgentName } from "../agent-color.js";
11
- import { extractText } from "../context.js";
12
- import type { AgentRecord, ViewerMarkdownMode } from "../types.js";
13
- import { getLifetimeCost, getLifetimeTotal, getSessionContextPercent } from "../usage.js";
14
- import type { Theme } from "./agent-widget.js";
15
- import { type AgentActivity, buildInvocationTags, describeActivity, fgPreservingNestedStyles, formatCost, formatDuration, formatSessionTokens, getPromptModeLabel } from "./agent-widget.js";
16
- import { NativeTranscript } from "./native-transcript.js";
17
- import { RESULT_MAX_CHARS, truncationNote } from "./tool-progress.js";
18
-
19
- export { RESULT_MAX_CHARS } from "./tool-progress.js";
10
+ import { renderAgentName } from "../agent-color.ts";
11
+ import { extractText } from "../context.ts";
12
+ import type { AgentRecord, ViewerMarkdownMode } from "../types.ts";
13
+ import { getLifetimeCost, getLifetimeTotal, getSessionContextPercent } from "../usage.ts";
14
+ import type { Theme } from "./agent-widget.ts";
15
+ import { type AgentActivity, buildInvocationTags, describeActivity, fgPreservingNestedStyles, formatCost, formatDuration, formatSessionTokens, getPromptModeLabel, sanitizeRowText } from "./agent-widget.ts";
16
+ import { NativeTranscript } from "./native-transcript.ts";
17
+ import { RESULT_MAX_CHARS, truncationNote } from "./tool-progress.ts";
18
+
19
+ export { RESULT_MAX_CHARS } from "./tool-progress.ts";
20
20
  export const VIEWPORT_HEIGHT_PCT = 100;
21
21
  const drafts = new WeakMap<AgentSession, string>();
22
22
 
@@ -291,7 +291,7 @@ export class ConversationViewer implements Component, Focusable {
291
291
  if (cost) headerParts.push(cost);
292
292
 
293
293
  lines.push(row(
294
- `${statusIcon} ${renderAgentName(this.record.type, th, { bold: true })}${modeTag} ${th.fg("muted", this.record.description)} ${th.fg("dim", "·")} ${fgPreservingNestedStyles(th, "dim", headerParts.join(" · "))}`,
294
+ `${statusIcon} ${renderAgentName(this.record.type, th, { bold: true })}${modeTag} ${th.fg("muted", sanitizeRowText(this.record.description))} ${th.fg("dim", "·")} ${fgPreservingNestedStyles(th, "dim", headerParts.join(" · "))}`,
295
295
  ));
296
296
  const invocationLine = this.invocationLine();
297
297
  if (invocationLine) lines.push(row(invocationLine));
@@ -316,7 +316,9 @@ export class ConversationViewer implements Component, Focusable {
316
316
  const queued = (this.session.getSteeringMessages?.().length ?? 0) + (this.session.getFollowUpMessages?.().length ?? 0);
317
317
  const action = !this.onSubmitMessage ? "Read only" : this.record.status === "running" || this.record.status === "queued" ? "Enter steer" : "Enter continue";
318
318
  const stop = this.isStoppable() ? this.stopArmed ? " · Ctrl+X again to STOP" : " · Ctrl+X stop" : "";
319
- lines.push(row(th.fg(this.submitError ? "error" : "dim", this.submitError || `${this.submitting ? "Sending…" : action}${queued ? ` · ${queued} queued` : ""}${stop}`)));
319
+ // `submitError` is an error message and may be multi-line; one overlay
320
+ // row is one terminal row, so it is flattened like every other fragment.
321
+ lines.push(row(th.fg(this.submitError ? "error" : "dim", sanitizeRowText(this.submitError || `${this.submitting ? "Sending…" : action}${queued ? ` · ${queued} queued` : ""}${stop}`))));
320
322
  }
321
323
  this.editorTop = lines.length;
322
324
  lines.push(...editorLines.slice(this.editorClip, this.editorClip + editorHeight).map(row));
@@ -436,7 +438,9 @@ export class ConversationViewer implements Component, Focusable {
436
438
  const model = modelId ?? modelName;
437
439
  const parts = model ? [model, ...tags] : tags;
438
440
  if (parts.length === 0) return undefined;
439
- return this.theme.fg("dim", ` ↳ ${parts.join(" · ")}`);
441
+ // Model names/ids come from the registry and tags are derived from them;
442
+ // flattened here because the line is a single overlay row.
443
+ return this.theme.fg("dim", ` ↳ ${sanitizeRowText(parts.join(" · "))}`);
440
444
  }
441
445
 
442
446
  private buildContentLines(width: number): string[] {
@@ -497,7 +501,7 @@ export class ConversationViewer implements Component, Focusable {
497
501
  } else if ((msg as any).role === "bashExecution") {
498
502
  const bash = msg as any;
499
503
  if (needsSeparator) lines.push(th.fg("dim", "───"));
500
- lines.push(truncateToWidth(th.fg("muted", ` $ ${bash.command}`), width));
504
+ lines.push(truncateToWidth(th.fg("muted", ` $ ${sanitizeRowText(bash.command)}`), width));
501
505
  if (bash.output?.trim()) {
502
506
  // Same cap as a tool result, never Markdown: command output is the one
503
507
  // thing here that is definitionally not authored as Markdown.
@@ -513,7 +517,7 @@ export class ConversationViewer implements Component, Focusable {
513
517
 
514
518
  // Streaming indicator for running agents
515
519
  if (this.record.status === "running" && this.activity) {
516
- const act = describeActivity(this.activity.activeTools, this.activity.responseText);
520
+ const act = sanitizeRowText(describeActivity(this.activity.activeTools, this.activity.responseText));
517
521
  lines.push("");
518
522
  lines.push(truncateToWidth(th.fg("accent", "▍ ") + th.fg("dim", act), width));
519
523
  }
@@ -12,11 +12,11 @@
12
12
  */
13
13
 
14
14
  import { Editor, isKeyRelease, Key, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
15
- import { hasAgentBadge, renderAgentName } from "../agent-color.js";
16
- import { type AgentManager, isTopLevelAgent } from "../agent-manager.js";
17
- import type { AgentRecord } from "../types.js";
18
- import { getLifetimeCost, getLifetimeTotal } from "../usage.js";
19
- import { type AgentActivity, formatCost, type Theme } from "./agent-widget.js";
15
+ import { hasAgentBadge, renderAgentName } from "../agent-color.ts";
16
+ import { type AgentManager, isTopLevelAgent } from "../agent-manager.ts";
17
+ import type { AgentRecord } from "../types.ts";
18
+ import { getLifetimeCost, getLifetimeTotal } from "../usage.ts";
19
+ import { type AgentActivity, formatCost, sanitizeRowText, type Theme } from "./agent-widget.ts";
20
20
 
21
21
  /** Widget key for the below-editor fleet list. */
22
22
  const FLEET_KEY = "fleet";
@@ -530,7 +530,7 @@ export class FleetList {
530
530
  ): string {
531
531
  const selected = rosterIndex === sel;
532
532
  const kind = theme.fg(selected ? "text" : "muted", "workflow");
533
- const name = selected ? theme.fg("text", workflow.name) : workflow.name;
533
+ const name = selected ? theme.fg("text", sanitizeRowText(workflow.name)) : sanitizeRowText(workflow.name);
534
534
  const left = ` ${this.bullet(rosterIndex, sel, theme)} ${kind} ${name}`;
535
535
  // Frozen once the run settles, exactly as an agent's clock is.
536
536
  const elapsed = (workflow.completedAt ?? Date.now()) - workflow.startedAt;
@@ -548,7 +548,7 @@ export class FleetList {
548
548
  const name = renderAgentName(record.type, theme, selected
549
549
  ? { fallbackColor: "text", bold: hasAgentBadge(record.type) }
550
550
  : { fallbackColor: "muted" });
551
- const description = selected ? theme.fg("text", record.description) : record.description;
551
+ const description = selected ? theme.fg("text", sanitizeRowText(record.description)) : sanitizeRowText(record.description);
552
552
  const left = ` ${this.bullet(rosterIndex, sel, theme)} ${name} ${description}`;
553
553
  // The record, not the activity tracker — see the note in AgentWidget's
554
554
  // running line: only the record carries a nested child's spend, and only it