@timmyjl12/pi-subagents 0.0.0-stage → 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 (244) hide show
  1. package/CHANGELOG.md +862 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1125 -3
  5. package/SECURITY.md +97 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/active-agents-prompt.d.ts +40 -0
  9. package/dist/active-agents-prompt.js +98 -0
  10. package/dist/advisor-status.d.ts +16 -0
  11. package/dist/advisor-status.js +74 -0
  12. package/dist/agent-color.d.ts +35 -0
  13. package/dist/agent-color.js +131 -0
  14. package/dist/agent-file-toggle.d.ts +125 -0
  15. package/dist/agent-file-toggle.js +264 -0
  16. package/dist/agent-manager.d.ts +872 -0
  17. package/dist/agent-manager.js +2910 -0
  18. package/dist/agent-runner.d.ts +358 -0
  19. package/dist/agent-runner.js +1219 -0
  20. package/dist/agent-types.d.ts +142 -0
  21. package/dist/agent-types.js +315 -0
  22. package/dist/awaited-result.d.ts +37 -0
  23. package/dist/awaited-result.js +150 -0
  24. package/dist/child-context.d.ts +15 -0
  25. package/dist/child-context.js +181 -0
  26. package/dist/child-session-shutdown.d.ts +21 -0
  27. package/dist/child-session-shutdown.js +97 -0
  28. package/dist/cleanup-plans.d.ts +10 -0
  29. package/dist/cleanup-plans.js +112 -0
  30. package/dist/context.d.ts +12 -0
  31. package/dist/context.js +56 -0
  32. package/dist/cross-extension-rpc.d.ts +73 -0
  33. package/dist/cross-extension-rpc.js +192 -0
  34. package/dist/custom-agents.d.ts +79 -0
  35. package/dist/custom-agents.js +583 -0
  36. package/dist/default-agents.d.ts +7 -0
  37. package/dist/default-agents.js +125 -0
  38. package/dist/enabled-models.d.ts +49 -0
  39. package/dist/enabled-models.js +145 -0
  40. package/dist/env.d.ts +6 -0
  41. package/dist/env.js +28 -0
  42. package/dist/error-log.d.ts +64 -0
  43. package/dist/error-log.js +176 -0
  44. package/dist/force-main-model.d.ts +21 -0
  45. package/dist/force-main-model.js +28 -0
  46. package/dist/goal-bridge.d.ts +155 -0
  47. package/dist/goal-bridge.js +305 -0
  48. package/dist/group-join.d.ts +36 -0
  49. package/dist/group-join.js +161 -0
  50. package/dist/index.d.ts +52 -0
  51. package/dist/index.js +6390 -0
  52. package/dist/invocation-config.d.ts +164 -0
  53. package/dist/invocation-config.js +158 -0
  54. package/dist/memory.d.ts +53 -0
  55. package/dist/memory.js +165 -0
  56. package/dist/mention-clone.d.ts +87 -0
  57. package/dist/mention-clone.js +178 -0
  58. package/dist/mention.d.ts +81 -0
  59. package/dist/mention.js +131 -0
  60. package/dist/model-resolver.d.ts +36 -0
  61. package/dist/model-resolver.js +95 -0
  62. package/dist/model-scope.d.ts +49 -0
  63. package/dist/model-scope.js +48 -0
  64. package/dist/nested-tools.d.ts +76 -0
  65. package/dist/nested-tools.js +393 -0
  66. package/dist/output-diagnostics.d.ts +11 -0
  67. package/dist/output-diagnostics.js +64 -0
  68. package/dist/output-file.d.ts +64 -0
  69. package/dist/output-file.js +351 -0
  70. package/dist/prompts.d.ts +61 -0
  71. package/dist/prompts.js +94 -0
  72. package/dist/recovery.d.ts +56 -0
  73. package/dist/recovery.js +341 -0
  74. package/dist/report-cleanup.d.ts +204 -0
  75. package/dist/report-cleanup.js +1632 -0
  76. package/dist/report-store.d.ts +738 -0
  77. package/dist/report-store.js +3612 -0
  78. package/dist/schedule-store.d.ts +52 -0
  79. package/dist/schedule-store.js +240 -0
  80. package/dist/schedule.d.ts +121 -0
  81. package/dist/schedule.js +420 -0
  82. package/dist/settings.d.ts +388 -0
  83. package/dist/settings.js +268 -0
  84. package/dist/skill-loader.d.ts +24 -0
  85. package/dist/skill-loader.js +93 -0
  86. package/dist/standalone-fallback.d.ts +30 -0
  87. package/dist/standalone-fallback.js +239 -0
  88. package/dist/status-note.d.ts +61 -0
  89. package/dist/status-note.js +85 -0
  90. package/dist/structured-output.d.ts +61 -0
  91. package/dist/structured-output.js +112 -0
  92. package/dist/terminal-progress.d.ts +115 -0
  93. package/dist/terminal-progress.js +206 -0
  94. package/dist/types.d.ts +411 -0
  95. package/dist/types.js +5 -0
  96. package/dist/ui/agent-mention.d.ts +82 -0
  97. package/dist/ui/agent-mention.js +187 -0
  98. package/dist/ui/agent-widget.d.ts +304 -0
  99. package/dist/ui/agent-widget.js +770 -0
  100. package/dist/ui/cleanup-preview.d.ts +59 -0
  101. package/dist/ui/cleanup-preview.js +466 -0
  102. package/dist/ui/conversation-viewer.d.ts +105 -0
  103. package/dist/ui/conversation-viewer.js +544 -0
  104. package/dist/ui/fleet-list.d.ts +183 -0
  105. package/dist/ui/fleet-list.js +494 -0
  106. package/dist/ui/fleet-overlay.d.ts +203 -0
  107. package/dist/ui/fleet-overlay.js +887 -0
  108. package/dist/ui/hub-feed.d.ts +52 -0
  109. package/dist/ui/hub-feed.js +148 -0
  110. package/dist/ui/native-transcript.d.ts +33 -0
  111. package/dist/ui/native-transcript.js +234 -0
  112. package/dist/ui/schedule-menu.d.ts +16 -0
  113. package/dist/ui/schedule-menu.js +94 -0
  114. package/dist/ui/select-item.d.ts +27 -0
  115. package/dist/ui/select-item.js +34 -0
  116. package/dist/ui/tool-progress.d.ts +22 -0
  117. package/dist/ui/tool-progress.js +56 -0
  118. package/dist/ui/viewer-keys.d.ts +20 -0
  119. package/dist/ui/viewer-keys.js +17 -0
  120. package/dist/ui/workflow-card.d.ts +175 -0
  121. package/dist/ui/workflow-card.js +332 -0
  122. package/dist/ui/workflow-dialog.d.ts +305 -0
  123. package/dist/ui/workflow-dialog.js +848 -0
  124. package/dist/ui/workflow-menu.d.ts +60 -0
  125. package/dist/ui/workflow-menu.js +147 -0
  126. package/dist/usage.d.ts +147 -0
  127. package/dist/usage.js +147 -0
  128. package/dist/workflow/collisions.d.ts +95 -0
  129. package/dist/workflow/collisions.js +88 -0
  130. package/dist/workflow/entry.d.ts +32 -0
  131. package/dist/workflow/entry.js +29 -0
  132. package/dist/workflow/host.d.ts +65 -0
  133. package/dist/workflow/host.js +477 -0
  134. package/dist/workflow/journal.d.ts +113 -0
  135. package/dist/workflow/journal.js +177 -0
  136. package/dist/workflow/json-schema.d.ts +51 -0
  137. package/dist/workflow/json-schema.js +111 -0
  138. package/dist/workflow/meta.d.ts +67 -0
  139. package/dist/workflow/meta.js +317 -0
  140. package/dist/workflow/progress.d.ts +224 -0
  141. package/dist/workflow/progress.js +361 -0
  142. package/dist/workflow/runtime.d.ts +373 -0
  143. package/dist/workflow/runtime.js +919 -0
  144. package/dist/workflow/saved.d.ts +90 -0
  145. package/dist/workflow/saved.js +203 -0
  146. package/dist/workflow/task.d.ts +145 -0
  147. package/dist/workflow/task.js +213 -0
  148. package/dist/workflow/tool-description.d.ts +43 -0
  149. package/dist/workflow/tool-description.js +204 -0
  150. package/dist/workflow/worker-source.d.ts +47 -0
  151. package/dist/workflow/worker-source.js +778 -0
  152. package/dist/worktree.d.ts +52 -0
  153. package/dist/worktree.js +164 -0
  154. package/dist/xml.d.ts +10 -0
  155. package/dist/xml.js +12 -0
  156. package/docs/DEVELOPMENT.md +40 -0
  157. package/docs/artifacts.md +93 -0
  158. package/docs/recovery.md +62 -0
  159. package/docs/rpc.md +252 -0
  160. package/docs/runtime-performance.md +53 -0
  161. package/docs/workflows.md +467 -0
  162. package/examples/agent-tool-description.md +43 -0
  163. package/examples/workflows/compose.js +51 -0
  164. package/examples/workflows/fan-out-audit.js +47 -0
  165. package/examples/workflows/gated-fix.js +60 -0
  166. package/examples/workflows/lib/count-child.js +27 -0
  167. package/examples/workflows/review-panel.js +66 -0
  168. package/examples/workflows/structured-findings.js +78 -0
  169. package/package.json +75 -6
  170. package/src/abortable.ts +43 -0
  171. package/src/active-agents-prompt.ts +115 -0
  172. package/src/advisor-status.ts +74 -0
  173. package/src/agent-color.ts +169 -0
  174. package/src/agent-file-toggle.ts +273 -0
  175. package/src/agent-manager.ts +3312 -0
  176. package/src/agent-runner.ts +1500 -0
  177. package/src/agent-types.ts +390 -0
  178. package/src/awaited-result.ts +187 -0
  179. package/src/child-context.ts +173 -0
  180. package/src/child-session-shutdown.ts +114 -0
  181. package/src/cleanup-plans.ts +112 -0
  182. package/src/context.ts +58 -0
  183. package/src/cross-extension-rpc.ts +257 -0
  184. package/src/custom-agents.ts +689 -0
  185. package/src/default-agents.ts +129 -0
  186. package/src/enabled-models.ts +180 -0
  187. package/src/env.ts +33 -0
  188. package/src/error-log.ts +202 -0
  189. package/src/force-main-model.ts +29 -0
  190. package/src/goal-bridge.ts +468 -0
  191. package/src/group-join.ts +188 -0
  192. package/src/index.ts +6856 -0
  193. package/src/invocation-config.ts +276 -0
  194. package/src/memory.ts +179 -0
  195. package/src/mention-clone.ts +221 -0
  196. package/src/mention.ts +141 -0
  197. package/src/model-resolver.ts +118 -0
  198. package/src/model-scope.ts +70 -0
  199. package/src/nested-tools.ts +553 -0
  200. package/src/output-diagnostics.ts +68 -0
  201. package/src/output-file.ts +380 -0
  202. package/src/prompts.ts +151 -0
  203. package/src/recovery.ts +320 -0
  204. package/src/report-cleanup.ts +2044 -0
  205. package/src/report-store.ts +4130 -0
  206. package/src/schedule-store.ts +244 -0
  207. package/src/schedule.ts +450 -0
  208. package/src/settings.ts +632 -0
  209. package/src/skill-loader.ts +102 -0
  210. package/src/standalone-fallback.ts +195 -0
  211. package/src/status-note.ts +90 -0
  212. package/src/structured-output.ts +130 -0
  213. package/src/terminal-progress.ts +215 -0
  214. package/src/types.ts +424 -0
  215. package/src/ui/agent-mention.ts +216 -0
  216. package/src/ui/agent-widget.ts +866 -0
  217. package/src/ui/cleanup-preview.ts +518 -0
  218. package/src/ui/conversation-viewer.ts +527 -0
  219. package/src/ui/fleet-list.ts +563 -0
  220. package/src/ui/fleet-overlay.ts +1048 -0
  221. package/src/ui/hub-feed.ts +179 -0
  222. package/src/ui/native-transcript.ts +224 -0
  223. package/src/ui/schedule-menu.ts +105 -0
  224. package/src/ui/select-item.ts +45 -0
  225. package/src/ui/tool-progress.ts +67 -0
  226. package/src/ui/viewer-keys.ts +39 -0
  227. package/src/ui/workflow-card.ts +470 -0
  228. package/src/ui/workflow-dialog.ts +1119 -0
  229. package/src/ui/workflow-menu.ts +193 -0
  230. package/src/usage.ts +217 -0
  231. package/src/workflow/collisions.ts +123 -0
  232. package/src/workflow/entry.ts +47 -0
  233. package/src/workflow/host.ts +524 -0
  234. package/src/workflow/journal.ts +221 -0
  235. package/src/workflow/json-schema.ts +128 -0
  236. package/src/workflow/meta.ts +325 -0
  237. package/src/workflow/progress.ts +550 -0
  238. package/src/workflow/runtime.ts +1342 -0
  239. package/src/workflow/saved.ts +217 -0
  240. package/src/workflow/task.ts +313 -0
  241. package/src/workflow/tool-description.ts +205 -0
  242. package/src/workflow/worker-source.ts +781 -0
  243. package/src/worktree.ts +205 -0
  244. package/src/xml.ts +13 -0
@@ -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>;
@@ -0,0 +1,466 @@
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 { isKeyRelease, matchesKey, ScrollView, Text, truncateToWidth, visibleWidth, wrapTextWithAnsi, } from "@earendil-works/pi-tui";
36
+ import { cleanupReadStateLabel, isCleanupPlanEmpty, } from "../report-cleanup.js";
37
+ import { createViewerKeys } from "./viewer-keys.js";
38
+ /**
39
+ * Show control characters as `\xNN` instead of emitting them.
40
+ *
41
+ * A report path is drawn verbatim inside a terminal frame; a raw ESC or BEL
42
+ * in one would inject terminal control sequences into the preview itself.
43
+ * The escaping is per code point and reversible, so the display loses no
44
+ * data — it just cannot execute.
45
+ */
46
+ function escapeDisplay(value) {
47
+ let out = "";
48
+ for (const ch of value) {
49
+ const code = ch.codePointAt(0) ?? 0;
50
+ if (ch === "\\") {
51
+ out += "\\\\";
52
+ }
53
+ else if (code < 0x20 || (code >= 0x7f && code <= 0x9f)) {
54
+ out += `\\x${code.toString(16).toUpperCase().padStart(2, "0")}`;
55
+ }
56
+ else {
57
+ out += ch;
58
+ }
59
+ }
60
+ return out;
61
+ }
62
+ /** 1024-based, one decimal under 100 — `512 B`, `1.5 KB`, `340 MB`. */
63
+ function formatBytes(bytes) {
64
+ if (!Number.isFinite(bytes) || bytes <= 0)
65
+ return "0 B";
66
+ if (bytes < 1024)
67
+ return `${bytes} B`;
68
+ const units = ["KB", "MB", "GB", "TB"];
69
+ let value = bytes;
70
+ let unit = -1;
71
+ do {
72
+ value /= 1024;
73
+ unit++;
74
+ } while (value >= 1024 && unit < units.length - 1);
75
+ const rounded = value >= 100 ? String(Math.round(value)) : value.toFixed(1).replace(/\.0$/, "");
76
+ return `${rounded} ${units[unit]}`;
77
+ }
78
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
79
+ /** One line per file: size and kind as aligned columns, then state, flags, path. */
80
+ function fileLine(file, sizeWidth, kindWidth) {
81
+ const flags = [file.legacy ? "legacy" : "", file.shared ? "shared" : ""].filter(Boolean).join(" ");
82
+ const head = `${formatBytes(file.size).padEnd(sizeWidth)} ${file.kind.padEnd(kindWidth)} ${cleanupReadStateLabel(file.readState)}`;
83
+ return ` ${head}${flags ? ` ${flags}` : ""} ${escapeDisplay(file.path)}`;
84
+ }
85
+ /** One line per skip: the reason first — it is why the file survives — then identity, then path. */
86
+ function skipLine(skip) {
87
+ const tags = [];
88
+ if (skip.kind)
89
+ tags.push(skip.kind);
90
+ if (skip.agentId)
91
+ tags.push(`agent ${escapeDisplay(skip.agentId)}`);
92
+ if (skip.workflowId)
93
+ tags.push(`workflow ${escapeDisplay(skip.workflowId)}`);
94
+ if (skip.rootSessionId)
95
+ tags.push(`root ${escapeDisplay(skip.rootSessionId)}`);
96
+ if (skip.legacy)
97
+ tags.push("legacy");
98
+ const identity = tags.length > 0 ? ` (${tags.join(", ")})` : "";
99
+ const path = skip.path ? ` — ${escapeDisplay(skip.path)}` : "";
100
+ return ` ${escapeDisplay(skip.reason)}${identity}${path}`;
101
+ }
102
+ /**
103
+ * The whole plan as ordered lines. Nothing is capped, windowed, or sampled:
104
+ * `plan.files` and `plan.skipped` map one-to-one onto lines here, and the
105
+ * counts are the plan's own rather than a recomputation that could drift.
106
+ */
107
+ function buildCleanupPreviewLines(plan) {
108
+ const lines = [];
109
+ const counts = plan.counts;
110
+ lines.push({ text: `Cleanup preview — ${plan.scope} scope`, tone: "title", fixed: true });
111
+ lines.push({ text: "Preview only — no changes have been made.", tone: "dim", fixed: true });
112
+ lines.push({ text: "Your own session history is never a cleanup candidate.", tone: "dim", fixed: true });
113
+ lines.push({ text: "Paths escape backslashes as \\\\ and control characters as \\xNN.", tone: "dim" });
114
+ const created = new Date(plan.createdAt).toISOString();
115
+ lines.push({
116
+ text: `Plan ${escapeDisplay(plan.planId)} · created ${created} · ${plural(plan.roots.length, "root")}`,
117
+ tone: "dim",
118
+ });
119
+ if (plan.identityUncertainty) {
120
+ lines.push({
121
+ text: `Identity uncertainty: ${escapeDisplay(plan.identityUncertainty)} — child-history candidates were refused.`,
122
+ tone: "warning",
123
+ });
124
+ }
125
+ lines.push({ text: "", tone: "plain" });
126
+ lines.push({ text: `Summary — ${plural(counts.files, "file")} · ${formatBytes(counts.bytes)}`, tone: "heading" });
127
+ lines.push({
128
+ text: ` ${plural(counts.reports, "report")} · task outputs ${counts.taskOutputs} · workflow files ${counts.workflowFiles} · child sessions ${counts.childSessions}`,
129
+ tone: "plain",
130
+ });
131
+ lines.push({
132
+ text: ` legacy ${counts.legacy} · diagnostics ${counts.diagnostics} · root metadata ${counts.rootMetadata}`,
133
+ tone: "plain",
134
+ });
135
+ const unreadNote = counts.unread > 0 ? " (not marked as read)" : "";
136
+ lines.push({
137
+ text: ` read state: ${plural(counts.unread, "unread artifact")}${unreadNote} · ${counts.unknownReadState} ${cleanupReadStateLabel("unknown")}`,
138
+ tone: counts.unread > 0 || counts.unknownReadState > 0 ? "warning" : "plain",
139
+ });
140
+ lines.push({ text: "", tone: "plain" });
141
+ if (plan.files.length === 0) {
142
+ lines.push({ text: "Files: none — nothing is eligible for cleanup.", tone: "dim" });
143
+ }
144
+ else {
145
+ lines.push({ text: `Files (${plan.files.length}):`, tone: "heading" });
146
+ let sizeWidth = 0;
147
+ let kindWidth = 0;
148
+ for (const file of plan.files) {
149
+ sizeWidth = Math.max(sizeWidth, formatBytes(file.size).length);
150
+ kindWidth = Math.max(kindWidth, file.kind.length);
151
+ }
152
+ for (const file of plan.files) {
153
+ lines.push({ text: fileLine(file, sizeWidth, kindWidth), tone: "plain" });
154
+ }
155
+ }
156
+ lines.push({ text: "", tone: "plain" });
157
+ if (plan.skipped.length === 0) {
158
+ lines.push({ text: "Skipped: none.", tone: "dim" });
159
+ }
160
+ else {
161
+ lines.push({ text: `Skipped (${plan.skipped.length}):`, tone: "heading" });
162
+ for (const skip of plan.skipped) {
163
+ lines.push({ text: skipLine(skip), tone: "plain" });
164
+ }
165
+ }
166
+ return lines;
167
+ }
168
+ /**
169
+ * The complete cleanup preview as plain text: scope, preview-only header,
170
+ * counts and bytes, read flags, every candidate path, and every skip.
171
+ *
172
+ * Pure — same plan in, same string out, no filesystem, no clock beyond the
173
+ * plan's own `createdAt`. This is also the text a non-TUI caller can print,
174
+ * so nothing the overlay shows exists only in the overlay.
175
+ */
176
+ export function formatCleanupPreview(plan) {
177
+ return buildCleanupPreviewLines(plan).map(line => line.text).join("\n");
178
+ }
179
+ /** Apply a tone with the active theme. Neutral by default; `warning` only for warnings. */
180
+ function styleLine(theme, line) {
181
+ switch (line.tone) {
182
+ case "title":
183
+ return theme.bold(line.text);
184
+ case "heading":
185
+ return theme.bold(theme.fg("muted", line.text));
186
+ case "dim":
187
+ return theme.fg("dim", line.text);
188
+ case "warning":
189
+ return theme.fg("warning", line.text);
190
+ default:
191
+ return line.text;
192
+ }
193
+ }
194
+ /** Short display names for the keys a footer advertises. */
195
+ function keyLabel(id) {
196
+ switch (id) {
197
+ case "escape":
198
+ case "esc":
199
+ return "esc";
200
+ case "enter":
201
+ case "return":
202
+ return "enter";
203
+ case "up":
204
+ return "↑";
205
+ case "down":
206
+ return "↓";
207
+ case "pageUp":
208
+ return "PgUp";
209
+ case "pageDown":
210
+ return "PgDn";
211
+ case "home":
212
+ return "Home";
213
+ case "end":
214
+ return "End";
215
+ default:
216
+ return id;
217
+ }
218
+ }
219
+ /**
220
+ * The overlay component. One instance per `ctx.ui.custom` call; the
221
+ * interaction ends only through `done`, never through an overlay handle.
222
+ */
223
+ class CleanupPreview {
224
+ tui;
225
+ theme;
226
+ keybindings;
227
+ plan;
228
+ dryRun;
229
+ done;
230
+ closed = false;
231
+ reviewable = false;
232
+ text;
233
+ scroll;
234
+ keys;
235
+ fixedLines;
236
+ bodyLines;
237
+ styledBodyCache;
238
+ lastStyledBody;
239
+ contentTop = 0;
240
+ constructor(tui, theme, keybindings, plan, dryRun, done) {
241
+ this.tui = tui;
242
+ this.theme = theme;
243
+ this.keybindings = keybindings;
244
+ this.plan = plan;
245
+ this.dryRun = dryRun;
246
+ this.done = done;
247
+ const lines = buildCleanupPreviewLines(plan);
248
+ this.fixedLines = lines.filter(line => line.fixed);
249
+ this.bodyLines = lines.filter(line => !line.fixed);
250
+ this.text = new Text("", 0, 0);
251
+ this.scroll = new ScrollView(this.text, { follow: "none", scrollbar: "hidden", overscroll: "contain" });
252
+ this.keys = createViewerKeys(keybindings);
253
+ }
254
+ handleInput(data) {
255
+ if (this.closed || isKeyRelease(data))
256
+ return;
257
+ if (this.isCancel(data)) {
258
+ this.close(false);
259
+ return;
260
+ }
261
+ if (this.isConfirm(data)) {
262
+ // The ONLY path that resolves true: an explicit Continue in normal
263
+ // mode. A dry run closes — it never consents.
264
+ this.close(!this.dryRun && this.reviewable);
265
+ return;
266
+ }
267
+ if (this.keys.scrollUp(data))
268
+ this.scroll.scrollBy(-1);
269
+ else if (this.keys.scrollDown(data))
270
+ this.scroll.scrollBy(1);
271
+ else if (this.keys.pageUp(data))
272
+ this.scroll.scrollBy(-Math.max(1, this.scroll.viewportHeight));
273
+ else if (this.keys.pageDown(data))
274
+ this.scroll.scrollBy(Math.max(1, this.scroll.viewportHeight));
275
+ else if (this.isBoundary(data, "top"))
276
+ this.scroll.scrollToStart();
277
+ else if (this.isBoundary(data, "bottom"))
278
+ this.scroll.scrollToEnd();
279
+ else
280
+ return;
281
+ this.tui.requestRender();
282
+ }
283
+ render(width) {
284
+ this.reviewable = false;
285
+ const rows = Math.max(0, this.tui.terminal.rows);
286
+ if (width < 6 || rows === 0)
287
+ return [];
288
+ const th = this.theme;
289
+ const innerW = width - 4;
290
+ const lines = [];
291
+ const pad = (s, len) => {
292
+ const vis = visibleWidth(s);
293
+ return s + " ".repeat(Math.max(0, len - vis));
294
+ };
295
+ const row = (content) => th.fg("border", "│") + " " + truncateToWidth(pad(content, innerW), innerW, "...", true) + " " + th.fg("border", "│");
296
+ const hrTop = th.fg("border", `╭${"─".repeat(width - 2)}╮`);
297
+ const hrBot = th.fg("border", `╰${"─".repeat(width - 2)}╯`);
298
+ const hrMid = row(th.fg("dim", "─".repeat(Math.max(0, innerW))));
299
+ lines.push(hrTop);
300
+ // Fixed chrome: the preview-only header, then the mode line. Wrapped, not
301
+ // truncated — the warning's unread count must survive a narrow terminal.
302
+ for (const line of [...this.fixedLines, ...this.modeLines()]) {
303
+ for (const wrapped of wrapTextWithAnsi(styleLine(th, line), Math.max(1, innerW))) {
304
+ lines.push(row(wrapped));
305
+ }
306
+ }
307
+ lines.push(hrMid);
308
+ // Keep the frame inside the terminal; the scroll region gets what is left.
309
+ const footerRows = rows >= 4 ? 2 : 0;
310
+ const viewportHeight = Math.max(0, rows - lines.length - footerRows);
311
+ if (viewportHeight === 0) {
312
+ return [truncateToWidth("Resize terminal to inspect cleanup; Esc cancels.", width)];
313
+ }
314
+ const content = this.contentLines(innerW);
315
+ this.scroll.updateLayout(content.length, viewportHeight, () => {
316
+ if (!this.closed)
317
+ this.tui.requestRender();
318
+ });
319
+ this.contentTop = lines.length;
320
+ const visible = content.slice(this.scroll.scrollTop, this.scroll.scrollTop + viewportHeight);
321
+ for (let i = 0; i < viewportHeight; i++)
322
+ lines.push(row(visible[i] ?? ""));
323
+ if (footerRows) {
324
+ lines.push(row(th.fg("dim", this.footerText(content.length, viewportHeight))));
325
+ lines.push(hrBot);
326
+ }
327
+ this.reviewable = true;
328
+ return lines.slice(0, rows);
329
+ }
330
+ handleMouse(event) {
331
+ if (this.closed)
332
+ return undefined;
333
+ if (event.type === "wheel" && event.y >= this.contentTop && event.y < this.contentTop + this.scroll.viewportHeight) {
334
+ this.scroll.scrollBy(event.wheelDelta ?? 0);
335
+ this.tui.requestRender();
336
+ return { handled: true };
337
+ }
338
+ return undefined;
339
+ }
340
+ invalidate() {
341
+ // The styled body embeds theme colors; rebuild it rather than reusing them.
342
+ this.styledBodyCache = undefined;
343
+ this.text.invalidate();
344
+ }
345
+ dispose() {
346
+ this.closed = true;
347
+ }
348
+ // ---- Private ----
349
+ close(result) {
350
+ if (this.closed)
351
+ return;
352
+ this.closed = true;
353
+ this.done(result);
354
+ }
355
+ /**
356
+ * Cancel is escape/ctrl+c even when the user rebound `tui.select.cancel`:
357
+ * the reflex key must never strand someone inside a deletion review.
358
+ */
359
+ isCancel(data) {
360
+ return (matchesKey(data, "escape") ||
361
+ matchesKey(data, "ctrl+c") ||
362
+ (this.keybindings?.matches(data, "tui.select.cancel") ?? false));
363
+ }
364
+ /** Enter always works alongside the configured confirm binding. */
365
+ isConfirm(data) {
366
+ return matchesKey(data, "enter") || (this.keybindings?.matches(data, "tui.select.confirm") ?? false);
367
+ }
368
+ isBoundary(data, boundary) {
369
+ if (boundary === "top") {
370
+ return (matchesKey(data, "home") ||
371
+ matchesKey(data, "ctrl+home") ||
372
+ matchesKey(data, "ctrl+shift+home") ||
373
+ (this.keybindings?.matches(data, "tui.altScreen.top") ?? false));
374
+ }
375
+ return (matchesKey(data, "end") ||
376
+ matchesKey(data, "ctrl+end") ||
377
+ matchesKey(data, "ctrl+shift+end") ||
378
+ (this.keybindings?.matches(data, "tui.altScreen.bottom") ?? false));
379
+ }
380
+ /** The fixed line under the header: what THIS showing of the preview means. */
381
+ modeLines() {
382
+ if (this.dryRun) {
383
+ return [{ text: "Dry run — review only; nothing will be deleted.", tone: "dim" }];
384
+ }
385
+ if (isCleanupPlanEmpty(this.plan)) {
386
+ return [{ text: "Nothing is eligible for cleanup.", tone: "dim" }];
387
+ }
388
+ const counts = this.plan.counts;
389
+ const parts = [];
390
+ if (counts.unread > 0) {
391
+ parts.push(`${plural(counts.unread, "unread artifact")} (not marked as read)`);
392
+ }
393
+ if (counts.unknownReadState > 0) {
394
+ parts.push(`read state unknown for ${plural(counts.unknownReadState, "artifact")} (archived read state was not recorded)`);
395
+ }
396
+ const detail = parts.length > 0 ? ` — ${parts.join("; ")}` : "";
397
+ return [
398
+ { text: `Warning — a confirmed cleanup permanently discards every file below${detail}.`, tone: "warning" },
399
+ ];
400
+ }
401
+ footerText(contentLength, viewportHeight) {
402
+ const hints = [];
403
+ const confirmKey = this.firstKeyLabel("tui.select.confirm", "enter");
404
+ const cancelKey = this.firstKeyLabel("tui.select.cancel", "esc");
405
+ if (this.dryRun) {
406
+ hints.push(`${confirmKey}/${cancelKey} close`);
407
+ }
408
+ else {
409
+ hints.push(`${confirmKey} continue`, `${cancelKey} cancel`);
410
+ }
411
+ hints.push(`${this.firstKeyLabel("tui.select.up", "↑")}${this.firstKeyLabel("tui.select.down", "↓")} scroll`);
412
+ hints.push(`${this.firstKeyLabel("tui.select.pageUp", "PgUp")}/${this.firstKeyLabel("tui.select.pageDown", "PgDn")} page`);
413
+ hints.push("Home/End top/bottom");
414
+ // Position last: it is the first hint a narrow footer may drop.
415
+ if (contentLength > viewportHeight) {
416
+ const top = this.scroll.scrollTop + 1;
417
+ const bottom = Math.min(this.scroll.scrollTop + viewportHeight, contentLength);
418
+ hints.push(`${top}–${bottom}/${contentLength}`);
419
+ }
420
+ return hints.join(" · ");
421
+ }
422
+ /** The user's own key for an action where bound, else the default label. */
423
+ firstKeyLabel(keybinding, fallback) {
424
+ const keys = this.keybindings?.getKeys(keybinding);
425
+ return keys && keys.length > 0 ? keyLabel(keys[0]) : fallback;
426
+ }
427
+ contentLines(width) {
428
+ const styled = this.styledBody();
429
+ if (styled !== this.lastStyledBody) {
430
+ this.text.setText(styled);
431
+ this.lastStyledBody = styled;
432
+ }
433
+ return this.text.render(Math.max(1, width));
434
+ }
435
+ styledBody() {
436
+ if (this.styledBodyCache === undefined) {
437
+ this.styledBodyCache = this.bodyLines.map(line => styleLine(this.theme, line)).join("\n");
438
+ }
439
+ return this.styledBodyCache;
440
+ }
441
+ }
442
+ /**
443
+ * Show the cleanup preview overlay and report whether the review was
444
+ * completed with an explicit Continue.
445
+ *
446
+ * Returns `true` ONLY in normal (non-dry-run) mode when the user presses the
447
+ * confirm key — that is "review done", not deletion approval; the parent runs
448
+ * its own `ctx.ui.confirm` afterwards. Esc, cancel, a closed dry run, and any
449
+ * environment without a real terminal all return `false`.
450
+ *
451
+ * TUI only: RPC clients report `hasUI` but their `custom()` resolves
452
+ * `undefined`, and print/JSON modes have no UI at all — so anything that is
453
+ * not an interactive terminal is a refusal, never a consent.
454
+ */
455
+ export async function showCleanupPreview(ctx, plan, dryRun) {
456
+ if (ctx.mode !== "tui" || !ctx.hasUI)
457
+ return false;
458
+ let reviewed;
459
+ try {
460
+ reviewed = await ctx.ui.custom((tui, theme, keybindings, done) => new CleanupPreview(tui, theme, keybindings, plan, dryRun, done), { overlay: true, overlayOptions: { anchor: "center", width: "90%", maxHeight: "100%" } });
461
+ }
462
+ catch {
463
+ return false;
464
+ }
465
+ return reviewed === true;
466
+ }
@@ -0,0 +1,105 @@
1
+ /**
2
+ * conversation-viewer.ts — Live conversation overlay for viewing agent sessions.
3
+ *
4
+ * Displays a scrollable, live-updating view of an agent's conversation.
5
+ * Subscribes to session events for real-time streaming updates.
6
+ */
7
+ import { type AgentSession, type KeybindingsManager } from "@earendil-works/pi-coding-agent";
8
+ import { type Component, type Focusable, type TUI, type TuiMouseEvent } from "@earendil-works/pi-tui";
9
+ import type { AgentRecord, ViewerMarkdownMode } from "../types.ts";
10
+ import type { Theme } from "./agent-widget.ts";
11
+ import { type AgentActivity } from "./agent-widget.ts";
12
+ export { RESULT_MAX_CHARS } from "./tool-progress.ts";
13
+ export declare const VIEWPORT_HEIGHT_PCT = 100;
14
+ export declare class ConversationViewer implements Component, Focusable {
15
+ private tui;
16
+ private session;
17
+ private record;
18
+ private activity;
19
+ private theme;
20
+ private done;
21
+ /** Abort the agent shown here. Omitted → no stop affordance (e.g. read-only history). */
22
+ private onStop?;
23
+ /** Resolves only after steering/resume acceptance. False or rejection retains the draft. */
24
+ private onSubmitMessage?;
25
+ /**
26
+ * Whether the header shows an estimated cost after the token count. Read
27
+ * once, at construction: the overlay is opened from a menu, so the setting
28
+ * cannot change while it is on screen.
29
+ */
30
+ private showCost;
31
+ /**
32
+ * The current `viewerMarkdown` setting. Read live rather than captured,
33
+ * unlike `showCost`: Ctrl+R changes it while the overlay is on screen.
34
+ * Omitted → `assistant`.
35
+ */
36
+ private viewerMarkdown?;
37
+ /**
38
+ * Persist a mode chosen with Ctrl+R, so the shortcut and `/agents → Settings`
39
+ * mean the same thing. Omitted → Ctrl+R still cycles, viewer-locally.
40
+ */
41
+ private onMarkdownMode?;
42
+ private unsubscribe;
43
+ private closed;
44
+ private stopArmed;
45
+ private readonly editor;
46
+ private readonly transcript;
47
+ private readonly scroll;
48
+ private transcriptTop;
49
+ private editorTop;
50
+ private editorClip;
51
+ private submitting;
52
+ private submissionDraft;
53
+ private submitError;
54
+ private readonly markdownTheme;
55
+ private markdownModeOverride;
56
+ get focused(): boolean;
57
+ set focused(value: boolean);
58
+ /**
59
+ * One `Markdown` per message, so its own text/width cache does the work. A
60
+ * fresh instance per render would re-parse the whole transcript on every
61
+ * keystroke — the component caches, but only across calls to the same object.
62
+ * Weak so a compacted-away message doesn't pin its render.
63
+ */
64
+ private markdownCache;
65
+ constructor(tui: TUI, session: AgentSession, record: AgentRecord, activity: AgentActivity | undefined, theme: Theme, done: (result: undefined) => void,
66
+ /** Abort the agent shown here. Omitted → no stop affordance (e.g. read-only history). */
67
+ onStop?: (() => void) | undefined,
68
+ /** User keybindings from `ctx.ui.custom()`. Omitted → hardcoded defaults. */
69
+ keybindings?: KeybindingsManager,
70
+ /** Resolves only after steering/resume acceptance. False or rejection retains the draft. */
71
+ onSubmitMessage?: ((message: string) => Promise<boolean>) | undefined,
72
+ /**
73
+ * Whether the header shows an estimated cost after the token count. Read
74
+ * once, at construction: the overlay is opened from a menu, so the setting
75
+ * cannot change while it is on screen.
76
+ */
77
+ showCost?: boolean,
78
+ /**
79
+ * The current `viewerMarkdown` setting. Read live rather than captured,
80
+ * unlike `showCost`: Ctrl+R changes it while the overlay is on screen.
81
+ * Omitted → `assistant`.
82
+ */
83
+ viewerMarkdown?: (() => ViewerMarkdownMode) | undefined,
84
+ /**
85
+ * Persist a mode chosen with Ctrl+R, so the shortcut and `/agents → Settings`
86
+ * mean the same thing. Omitted → Ctrl+R still cycles, viewer-locally.
87
+ */
88
+ onMarkdownMode?: ((mode: ViewerMarkdownMode) => void) | undefined);
89
+ handleInput(data: string): void;
90
+ private submit;
91
+ render(width: number): string[];
92
+ handleMouse(event: TuiMouseEvent): import("@earendil-works/pi-tui").TuiMouseEventResult | undefined;
93
+ /** Stoppable only when a stop handler exists and the agent is still active. */
94
+ private isStoppable;
95
+ /** The mode in force: a Ctrl+R press, else the setting, else native cards. */
96
+ private markdownMode;
97
+ /** Wrap `text` literally — the pre-Markdown path, and the fallback from it. */
98
+ private rawLines;
99
+ /** Render `text` as Markdown, reusing this message's component instance. */
100
+ private markdownLines;
101
+ invalidate(): void;
102
+ dispose(): void;
103
+ private invocationLine;
104
+ private buildContentLines;
105
+ }