@ymy88/pi-subagents 0.0.0-stage → 0.24.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 (196) hide show
  1. package/CHANGELOG.md +904 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1170 -2
  5. package/SECURITY.md +95 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/agent-color.d.ts +35 -0
  9. package/dist/agent-color.js +123 -0
  10. package/dist/agent-file-toggle.d.ts +133 -0
  11. package/dist/agent-file-toggle.js +287 -0
  12. package/dist/agent-manager.d.ts +552 -0
  13. package/dist/agent-manager.js +1466 -0
  14. package/dist/agent-record-entry.d.ts +96 -0
  15. package/dist/agent-record-entry.js +121 -0
  16. package/dist/agent-runner.d.ts +310 -0
  17. package/dist/agent-runner.js +1195 -0
  18. package/dist/agent-source-badge.d.ts +50 -0
  19. package/dist/agent-source-badge.js +74 -0
  20. package/dist/agent-types.d.ts +119 -0
  21. package/dist/agent-types.js +286 -0
  22. package/dist/child-context.d.ts +2 -0
  23. package/dist/child-context.js +12 -0
  24. package/dist/completion-outbox.d.ts +63 -0
  25. package/dist/completion-outbox.js +104 -0
  26. package/dist/context.d.ts +12 -0
  27. package/dist/context.js +56 -0
  28. package/dist/cross-extension-rpc.d.ts +72 -0
  29. package/dist/cross-extension-rpc.js +153 -0
  30. package/dist/custom-agents.d.ts +77 -0
  31. package/dist/custom-agents.js +396 -0
  32. package/dist/default-agents.d.ts +7 -0
  33. package/dist/default-agents.js +121 -0
  34. package/dist/enabled-models.d.ts +49 -0
  35. package/dist/enabled-models.js +145 -0
  36. package/dist/env.d.ts +6 -0
  37. package/dist/env.js +28 -0
  38. package/dist/group-join.d.ts +32 -0
  39. package/dist/group-join.js +116 -0
  40. package/dist/index.d.ts +50 -0
  41. package/dist/index.js +4111 -0
  42. package/dist/invocation-config.d.ts +108 -0
  43. package/dist/invocation-config.js +83 -0
  44. package/dist/memory.d.ts +53 -0
  45. package/dist/memory.js +165 -0
  46. package/dist/mention-clone.d.ts +79 -0
  47. package/dist/mention-clone.js +155 -0
  48. package/dist/mention.d.ts +81 -0
  49. package/dist/mention.js +131 -0
  50. package/dist/model-resolver.d.ts +36 -0
  51. package/dist/model-resolver.js +95 -0
  52. package/dist/model-scope.d.ts +49 -0
  53. package/dist/model-scope.js +48 -0
  54. package/dist/nested-tools.d.ts +57 -0
  55. package/dist/nested-tools.js +303 -0
  56. package/dist/output-file.d.ts +43 -0
  57. package/dist/output-file.js +153 -0
  58. package/dist/package-resources.d.ts +240 -0
  59. package/dist/package-resources.js +519 -0
  60. package/dist/prompts.d.ts +76 -0
  61. package/dist/prompts.js +121 -0
  62. package/dist/schedule-store.d.ts +38 -0
  63. package/dist/schedule-store.js +155 -0
  64. package/dist/schedule.d.ts +109 -0
  65. package/dist/schedule.js +359 -0
  66. package/dist/settings.d.ts +398 -0
  67. package/dist/settings.js +282 -0
  68. package/dist/skill-loader.d.ts +24 -0
  69. package/dist/skill-loader.js +93 -0
  70. package/dist/status-note.d.ts +61 -0
  71. package/dist/status-note.js +85 -0
  72. package/dist/structured-output.d.ts +61 -0
  73. package/dist/structured-output.js +112 -0
  74. package/dist/types.d.ts +391 -0
  75. package/dist/types.js +5 -0
  76. package/dist/ui/agent-mention.d.ts +82 -0
  77. package/dist/ui/agent-mention.js +187 -0
  78. package/dist/ui/agent-widget.d.ts +219 -0
  79. package/dist/ui/agent-widget.js +585 -0
  80. package/dist/ui/conversation-viewer.d.ts +177 -0
  81. package/dist/ui/conversation-viewer.js +905 -0
  82. package/dist/ui/fleet-list.d.ts +211 -0
  83. package/dist/ui/fleet-list.js +489 -0
  84. package/dist/ui/schedule-menu.d.ts +16 -0
  85. package/dist/ui/schedule-menu.js +94 -0
  86. package/dist/ui/select-item.d.ts +27 -0
  87. package/dist/ui/select-item.js +34 -0
  88. package/dist/ui/viewer-keys.d.ts +22 -0
  89. package/dist/ui/viewer-keys.js +18 -0
  90. package/dist/ui/workflow-card.d.ts +175 -0
  91. package/dist/ui/workflow-card.js +332 -0
  92. package/dist/ui/workflow-dialog.d.ts +305 -0
  93. package/dist/ui/workflow-dialog.js +843 -0
  94. package/dist/ui/workflow-menu.d.ts +60 -0
  95. package/dist/ui/workflow-menu.js +147 -0
  96. package/dist/usage.d.ts +135 -0
  97. package/dist/usage.js +120 -0
  98. package/dist/workflow/collisions.d.ts +95 -0
  99. package/dist/workflow/collisions.js +88 -0
  100. package/dist/workflow/entry.d.ts +32 -0
  101. package/dist/workflow/entry.js +29 -0
  102. package/dist/workflow/host.d.ts +62 -0
  103. package/dist/workflow/host.js +419 -0
  104. package/dist/workflow/journal.d.ts +97 -0
  105. package/dist/workflow/journal.js +120 -0
  106. package/dist/workflow/json-schema.d.ts +52 -0
  107. package/dist/workflow/json-schema.js +112 -0
  108. package/dist/workflow/meta.d.ts +67 -0
  109. package/dist/workflow/meta.js +317 -0
  110. package/dist/workflow/progress.d.ts +224 -0
  111. package/dist/workflow/progress.js +361 -0
  112. package/dist/workflow/runtime.d.ts +334 -0
  113. package/dist/workflow/runtime.js +830 -0
  114. package/dist/workflow/saved.d.ts +102 -0
  115. package/dist/workflow/saved.js +247 -0
  116. package/dist/workflow/task.d.ts +136 -0
  117. package/dist/workflow/task.js +207 -0
  118. package/dist/workflow/tool-description.d.ts +38 -0
  119. package/dist/workflow/tool-description.js +199 -0
  120. package/dist/workflow/worker-source.d.ts +47 -0
  121. package/dist/workflow/worker-source.js +778 -0
  122. package/dist/worktree.d.ts +52 -0
  123. package/dist/worktree.js +164 -0
  124. package/dist/xml.d.ts +10 -0
  125. package/dist/xml.js +12 -0
  126. package/docs/packages.md +211 -0
  127. package/docs/rpc.md +192 -0
  128. package/docs/workflows.md +447 -0
  129. package/examples/agent-tool-description.md +42 -0
  130. package/examples/workflows/compose.js +51 -0
  131. package/examples/workflows/fan-out-audit.js +47 -0
  132. package/examples/workflows/gated-fix.js +60 -0
  133. package/examples/workflows/lib/count-child.js +27 -0
  134. package/examples/workflows/review-panel.js +63 -0
  135. package/examples/workflows/structured-findings.js +78 -0
  136. package/package.json +74 -4
  137. package/src/abortable.ts +43 -0
  138. package/src/agent-color.ts +161 -0
  139. package/src/agent-file-toggle.ts +297 -0
  140. package/src/agent-manager.ts +1735 -0
  141. package/src/agent-record-entry.ts +153 -0
  142. package/src/agent-runner.ts +1468 -0
  143. package/src/agent-source-badge.ts +75 -0
  144. package/src/agent-types.ts +346 -0
  145. package/src/child-context.ts +15 -0
  146. package/src/completion-outbox.ts +116 -0
  147. package/src/context.ts +58 -0
  148. package/src/cross-extension-rpc.ts +221 -0
  149. package/src/custom-agents.ts +452 -0
  150. package/src/default-agents.ts +125 -0
  151. package/src/enabled-models.ts +180 -0
  152. package/src/env.ts +33 -0
  153. package/src/group-join.ts +141 -0
  154. package/src/index.ts +4433 -0
  155. package/src/invocation-config.ts +155 -0
  156. package/src/memory.ts +179 -0
  157. package/src/mention-clone.ts +195 -0
  158. package/src/mention.ts +141 -0
  159. package/src/model-resolver.ts +118 -0
  160. package/src/model-scope.ts +70 -0
  161. package/src/nested-tools.ts +426 -0
  162. package/src/output-file.ts +164 -0
  163. package/src/package-resources.ts +652 -0
  164. package/src/prompts.ts +171 -0
  165. package/src/schedule-store.ts +153 -0
  166. package/src/schedule.ts +386 -0
  167. package/src/settings.ts +650 -0
  168. package/src/skill-loader.ts +102 -0
  169. package/src/status-note.ts +90 -0
  170. package/src/structured-output.ts +130 -0
  171. package/src/types.ts +404 -0
  172. package/src/ui/agent-mention.ts +216 -0
  173. package/src/ui/agent-widget.ts +661 -0
  174. package/src/ui/conversation-viewer.ts +928 -0
  175. package/src/ui/fleet-list.ts +559 -0
  176. package/src/ui/schedule-menu.ts +105 -0
  177. package/src/ui/select-item.ts +45 -0
  178. package/src/ui/viewer-keys.ts +43 -0
  179. package/src/ui/workflow-card.ts +470 -0
  180. package/src/ui/workflow-dialog.ts +1115 -0
  181. package/src/ui/workflow-menu.ts +193 -0
  182. package/src/usage.ts +167 -0
  183. package/src/workflow/collisions.ts +123 -0
  184. package/src/workflow/entry.ts +47 -0
  185. package/src/workflow/host.ts +467 -0
  186. package/src/workflow/journal.ts +164 -0
  187. package/src/workflow/json-schema.ts +129 -0
  188. package/src/workflow/meta.ts +325 -0
  189. package/src/workflow/progress.ts +551 -0
  190. package/src/workflow/runtime.ts +1219 -0
  191. package/src/workflow/saved.ts +259 -0
  192. package/src/workflow/task.ts +302 -0
  193. package/src/workflow/tool-description.ts +200 -0
  194. package/src/workflow/worker-source.ts +781 -0
  195. package/src/worktree.ts +205 -0
  196. package/src/xml.ts +13 -0
@@ -0,0 +1,928 @@
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
+
8
+ import { type AgentSession, getMarkdownTheme, ToolExecutionComponent } from "@earendil-works/pi-coding-agent";
9
+ import { type Component, type Focusable, Input, Markdown, type MarkdownOptions, type MarkdownTheme, matchesKey, type OverlayOptions, ScrollView, type ScrollViewScrollbar, stripTerminalSequences, type TUI, type TuiMouseEvent, type TuiMouseEventResult, 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 { createViewerKeys, type ViewerKeybindings, type ViewerKeys } from "./viewer-keys.js";
17
+
18
+ /** An assistant message's tool call, and the message that answers it. */
19
+ type AgentMessage = AgentSession["messages"][number];
20
+ type ToolCallPart = Extract<Extract<AgentMessage, { role: "assistant" }>["content"][number], { type: "toolCall" }>;
21
+ type ToolResultPart = Extract<AgentMessage, { role: "toolResult" }>;
22
+
23
+ /** A rendered tool call, reused across renders so its component's caches survive. */
24
+ interface ToolBlock {
25
+ component: ToolExecutionComponent;
26
+ /** The result already handed to the component, if any. */
27
+ result?: ToolResultPart;
28
+ /**
29
+ * The block's rendered rows and the width they were produced at.
30
+ *
31
+ * `ToolExecutionComponent` re-wraps and re-paints its whole subtree on every
32
+ * `render()`, which costs ~0.4 ms per settled call — enough that a 500-message
33
+ * transcript re-wrapped every block on every keystroke. The rows only change
34
+ * when the inputs above do, so they are kept and reused until one does.
35
+ */
36
+ rows?: string[];
37
+ width?: number;
38
+ }
39
+
40
+ /**
41
+ * Whether pi's global theme is initialized.
42
+ *
43
+ * `ToolExecutionComponent` draws with pi's theme rather than the instance this
44
+ * viewer is handed, and pi throws on the first color lookup when nothing called
45
+ * `initTheme()`. This viewer is constructed outside pi too — its own unit tests,
46
+ * an embedded session — so the tool path is gated on a probe, the same way
47
+ * `resolveMarkdownTheme` already treats pi's Markdown theme.
48
+ */
49
+ function piThemeAvailable(): boolean {
50
+ try {
51
+ getMarkdownTheme().heading("probe");
52
+ return true;
53
+ } catch {
54
+ return false;
55
+ }
56
+ }
57
+
58
+ /** Base lines consumed by chrome: top border + header + header sep + footer sep + footer + bottom border. */
59
+ const CHROME_LINES_BASE = 6;
60
+ const MIN_VIEWPORT = 3;
61
+ /** Height ceiling shared by the overlay's `maxHeight` and the viewer's internal viewport cap. */
62
+ export const VIEWPORT_HEIGHT_PCT = 70;
63
+ const SCROLLBAR_WIDTH = 1;
64
+
65
+ /** Follow the active renderer, not a setting that may require a restart. */
66
+ export function getConversationOverlayOptions(tui: Pick<TUI, "mode">): OverlayOptions {
67
+ return tui.mode === "fullscreen"
68
+ ? { anchor: "top-left", width: "100%", maxHeight: "100%", margin: 0 }
69
+ : { anchor: "center", width: "90%", maxHeight: `${VIEWPORT_HEIGHT_PCT}%` };
70
+ }
71
+
72
+ /**
73
+ * Cap on a single tool result or bash output before the viewer elides the rest.
74
+ *
75
+ * The cap is not cosmetic — it bounds render cost. `buildContentLines()` runs on
76
+ * every render *and* on every scroll key (`handleInput` calls it to compute
77
+ * `maxScroll`), so an uncapped 200 KB result costs ~6 ms per keystroke to parse
78
+ * as Markdown, against ~0.5 ms once capped and effectively nothing on a cache
79
+ * hit (best of 5, width 76). 16 KB is roughly a screenful at every terminal size
80
+ * and still ~30x the 500 characters this replaces, which was small enough to cut
81
+ * most real results mid-sentence.
82
+ */
83
+ export const RESULT_MAX_CHARS = 16_000;
84
+
85
+ /** The `b` affordance: whether this run can be handed to the background now, and the handoff. */
86
+ export interface ViewerBackgroundAction {
87
+ available(): boolean;
88
+ send(): void;
89
+ }
90
+
91
+ /** Cycle order for the viewer's `m` key. */
92
+ const MARKDOWN_MODES: readonly ViewerMarkdownMode[] = ["off", "assistant", "all"];
93
+
94
+ /** Footer labels — short, because the idle footer is already full at 80 columns. */
95
+ const MARKDOWN_MODE_LABELS: Record<ViewerMarkdownMode, string> = {
96
+ off: "raw",
97
+ assistant: "md",
98
+ all: "md+",
99
+ };
100
+
101
+ /**
102
+ * Both options keep the renderer from *rewriting* source that only looks like
103
+ * Markdown: without them `3) a / 7) b / 9) c` comes back renumbered `3. 4. 5.`
104
+ * and backslash escapes are normalized away. Neither is a safe edit to make to
105
+ * a tool's output, and both are cheap to switch off.
106
+ */
107
+ const MARKDOWN_OPTIONS: MarkdownOptions = {
108
+ preserveOrderedListMarkers: true,
109
+ preserveBackslashEscapes: true,
110
+ };
111
+
112
+ /**
113
+ * Pi's own Markdown theme when this process has one, else a theme built from the
114
+ * viewer's `Theme`.
115
+ *
116
+ * Preferring pi's is what buys syntax-highlighted code fences (it carries a
117
+ * `highlightCode`), and it keeps this surface consistent with the notification
118
+ * renderer, which uses the same source. It has to be *probed* rather than
119
+ * try/caught around the call: `getMarkdownTheme()` returns arrow functions that
120
+ * read pi's global theme lazily, so an uninitialized theme throws inside
121
+ * `render()` — long after this returns — and takes the overlay with it. That is
122
+ * the case in tests and any embedded session that never called `initTheme()`.
123
+ */
124
+ function resolveMarkdownTheme(th: Theme): MarkdownTheme {
125
+ try {
126
+ const piTheme = getMarkdownTheme();
127
+ piTheme.heading("probe");
128
+ return piTheme;
129
+ } catch {
130
+ return fallbackMarkdownTheme(th);
131
+ }
132
+ }
133
+
134
+ /**
135
+ * `Theme` carries only `fg` and `bold`, so the three remaining styles are
136
+ * written as raw SGR. Rendering them as plain text instead would silently drop
137
+ * `*emphasis*`'s markers with nothing in their place, turning a formatting
138
+ * change into a content change.
139
+ */
140
+ function fallbackMarkdownTheme(th: Theme): MarkdownTheme {
141
+ const sgr = (on: number, off: number) => (text: string) => `\x1b[${on}m${text}\x1b[${off}m`;
142
+ return {
143
+ heading: text => th.bold(th.fg("accent", text)),
144
+ link: text => th.fg("accent", text),
145
+ linkUrl: text => th.fg("muted", text),
146
+ code: text => th.fg("muted", text),
147
+ codeBlock: text => th.fg("muted", text),
148
+ codeBlockBorder: text => th.fg("dim", text),
149
+ quote: text => th.fg("muted", text),
150
+ quoteBorder: text => th.fg("dim", text),
151
+ hr: text => th.fg("dim", text),
152
+ listBullet: text => th.fg("accent", text),
153
+ bold: text => th.bold(text),
154
+ italic: sgr(3, 23),
155
+ underline: sgr(4, 24),
156
+ strikethrough: sgr(9, 29),
157
+ };
158
+ }
159
+
160
+ /**
161
+ * Cap `text` at `RESULT_MAX_CHARS`, reporting the elision separately rather than
162
+ * appending it.
163
+ *
164
+ * Separately because the notice is the viewer's chrome, not the tool's output.
165
+ * Appended into the string it becomes content: a cut landing inside a fenced
166
+ * code block — likely, on exactly the large `ctx_execute` results this is for —
167
+ * renders the notice as a line of source inside the fence.
168
+ */
169
+ function capResult(text: string): { text: string; elided: number } {
170
+ if (text.length <= RESULT_MAX_CHARS) return { text, elided: 0 };
171
+ return {
172
+ text: text.slice(0, RESULT_MAX_CHARS),
173
+ elided: text.length - RESULT_MAX_CHARS,
174
+ };
175
+ }
176
+
177
+ /**
178
+ * `999` · `1.5k` · `8.4M` — a magnitude cue, not an exact count, past 1000.
179
+ *
180
+ * The bracket is chosen against the *rounded* value, so 999,999 reads `1M`
181
+ * rather than the `1000.0k` a naive `< 1e6` test produces.
182
+ */
183
+ function humanCount(n: number): string {
184
+ if (n < 1_000) return `${n}`;
185
+ const thousands = n < 999_950;
186
+ const value = thousands ? n / 1_000 : n / 1_000_000;
187
+ return `${value.toFixed(1).replace(/\.0$/, "")}${thousands ? "k" : "M"}`;
188
+ }
189
+
190
+ function truncationNote(elided: number): string {
191
+ return `... (truncated, ${humanCount(elided)} more character${elided === 1 ? "" : "s"})`;
192
+ }
193
+
194
+ export class ConversationViewer implements Component, Focusable {
195
+ private scrollOffset = 0;
196
+ private autoScroll = true;
197
+ focused = false;
198
+ private readonly fullscreen: boolean;
199
+ private viewport: { width: number; top: number; height: number; maxScroll: number; thumbTop: number; thumbHeight: number } | undefined;
200
+ private scrollbarGrabOffset: number | undefined;
201
+ private footerTargets: { start: number; end: number; key: string }[] = [];
202
+ private latestTarget: { row: number; start: number; end: number } | undefined;
203
+ private newMessages = 0;
204
+ private readonly scrollView: ScrollView;
205
+ private unsubscribe: (() => void) | undefined;
206
+ private lastInnerW = 0;
207
+ private closed = false;
208
+ /** Two-press confirm guard for the stop key, so a stray key can't kill the agent. */
209
+ private stopArmed = false;
210
+ private keys: ViewerKeys;
211
+ /** Steering composer — present while the user is typing a message to the agent. */
212
+ private composer: Input | undefined;
213
+ /** Resolved once: pi's Markdown theme is fixed for the life of the process. */
214
+ private readonly markdownTheme: MarkdownTheme;
215
+ /** Set by the `m` key. Wins over the setting so `m` works without a persist hook. */
216
+ private markdownModeOverride: ViewerMarkdownMode | undefined;
217
+ /**
218
+ * One `Markdown` per message, so its own text/width cache does the work. A
219
+ * fresh instance per render would re-parse the whole transcript on every
220
+ * keystroke — the component caches, but only across calls to the same object.
221
+ * Weak so a compacted-away message doesn't pin its render.
222
+ */
223
+ private readonly markdownCache = new WeakMap<object, { md: Markdown; text: string; failed?: boolean }>();
224
+ /** One block per tool call id, so a redraw reuses the component's own caches. */
225
+ private readonly toolBlocks = new Map<string, ToolBlock>();
226
+ /**
227
+ * Whether calls render through pi's components. Probe-gated: without pi's
228
+ * theme the viewer keeps its own plain rendering rather than throwing.
229
+ */
230
+ private readonly toolRendering = piThemeAvailable();
231
+ /** Whether tool blocks show their full output; toggled with pi's expand key. */
232
+ private toolsExpanded = false;
233
+
234
+ constructor(
235
+ private tui: TUI,
236
+ private session: AgentSession,
237
+ private record: AgentRecord,
238
+ private activity: AgentActivity | undefined,
239
+ private theme: Theme,
240
+ private done: (result: undefined) => void,
241
+ /** Abort the agent shown here. Omitted → no stop affordance (e.g. read-only history). */
242
+ private onStop?: () => void,
243
+ /** User keybindings from `ctx.ui.custom()`. Omitted → hardcoded defaults. */
244
+ keybindings?: ViewerKeybindings,
245
+ /** Send a steering message to the agent. Omitted → no compose affordance. */
246
+ private onSteer?: (message: string) => void,
247
+ /**
248
+ * Whether the header shows an estimated cost after the token count. Read
249
+ * once, at construction: the overlay is opened from a menu, so the setting
250
+ * cannot change while it is on screen.
251
+ */
252
+ private showCost = false,
253
+ /**
254
+ * The current `viewerMarkdown` setting. Read live rather than captured,
255
+ * unlike `showCost`: `m` changes it while the overlay is on screen.
256
+ * Omitted → `assistant`.
257
+ */
258
+ private viewerMarkdown?: () => ViewerMarkdownMode,
259
+ /**
260
+ * Persist a mode chosen with `m`, so the key and `/agents → Settings` mean
261
+ * the same thing. Omitted → `m` still cycles, viewer-locally.
262
+ */
263
+ private onMarkdownMode?: (mode: ViewerMarkdownMode) => void,
264
+ /** Pi's fullscreen scrollbar preference, captured when the observer opens. */
265
+ scrollbarMode: ScrollViewScrollbar = "auto",
266
+ /**
267
+ * Hand this run to the background. `available` is read live — it turns
268
+ * false the instant the handoff lands or the run ends. Omitted → no `b`
269
+ * affordance (history views).
270
+ */
271
+ private onBackground?: ViewerBackgroundAction,
272
+ ) {
273
+ this.fullscreen = tui.mode === "fullscreen";
274
+ this.markdownTheme = resolveMarkdownTheme(theme);
275
+ this.keys = createViewerKeys(keybindings);
276
+ this.scrollView = new ScrollView({
277
+ render: width => this.buildContentLines(width),
278
+ invalidate: () => {},
279
+ }, { follow: "end", scrollbar: this.fullscreen ? scrollbarMode : "hidden" });
280
+ this.unsubscribe = session.subscribe(event => {
281
+ if (this.closed) return;
282
+ if (this.fullscreen && !this.scrollView.isFollowingEnd && event.type === "message_start" && ["user", "assistant", "toolResult", "bashExecution"].includes(event.message.role)) {
283
+ this.newMessages++;
284
+ }
285
+ this.tui.requestRender();
286
+ });
287
+ }
288
+
289
+ handleInput(data: string): void {
290
+ if (this.closed) return;
291
+ if (this.fullscreen && (matchesKey(data, "ctrl+end") || (!this.composer && matchesKey(data, "end")))) {
292
+ this.jumpToLatest();
293
+ return;
294
+ }
295
+ // While composing a steer message, the input owns all keys (Enter sends,
296
+ // Esc cancels — both wired in openComposer()). Editing keys flow through.
297
+ if (this.composer) {
298
+ this.composer.handleInput(data);
299
+ this.tui.requestRender();
300
+ return;
301
+ }
302
+
303
+ if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c") || matchesKey(data, "q")) {
304
+ this.closed = true;
305
+ this.done(undefined);
306
+ return;
307
+ }
308
+
309
+ // Enter opens the steering composer (only while the agent can still be
310
+ // steered) — then type + Enter sends, Esc or an empty submit returns. When
311
+ // not steerable, fall through so the key still disarms a pending stop.
312
+ if (matchesKey(data, "enter") && this.canSteer()) {
313
+ this.stopArmed = false;
314
+ this.openComposer();
315
+ return;
316
+ }
317
+
318
+ // Hand a live foreground run to the background. Single press, unlike stop:
319
+ // the transition is one-way but keeps the agent working, so a stray key
320
+ // costs a notification rather than the run.
321
+ if (matchesKey(data, "b") && this.canSendToBackground()) {
322
+ this.stopArmed = false;
323
+ this.onBackground?.send();
324
+ this.tui.requestRender();
325
+ return;
326
+ }
327
+
328
+ // Stop/abort the agent (only while it can still be stopped). Two-press:
329
+ // first "x" arms, second confirms — any other key disarms.
330
+ if (matchesKey(data, "x")) {
331
+ if (this.isStoppable()) {
332
+ if (this.stopArmed) {
333
+ this.stopArmed = false;
334
+ this.onStop?.();
335
+ } else {
336
+ this.stopArmed = true;
337
+ }
338
+ this.tui.requestRender();
339
+ }
340
+ return;
341
+ }
342
+
343
+ // Cycle raw → assistant-only → everything. The escape hatch that makes
344
+ // Markdown rendering safe to default on: a result the renderer reshapes
345
+ // (a diff, an indented log, a `#`-commented script) is one key from verbatim.
346
+ if (matchesKey(data, "m")) {
347
+ this.stopArmed = false;
348
+ const next = MARKDOWN_MODES[(MARKDOWN_MODES.indexOf(this.markdownMode()) + 1) % MARKDOWN_MODES.length];
349
+ this.markdownModeOverride = next;
350
+ this.onMarkdownMode?.(next);
351
+ this.tui.requestRender();
352
+ return;
353
+ }
354
+ if (this.stopArmed) this.stopArmed = false;
355
+
356
+ // Unfold tool output — the same key, and the same meaning, as in the main
357
+ // transcript. It is what the renderers' own elision notices refer to.
358
+ if (this.keys.expand(data)) {
359
+ this.toolsExpanded = !this.toolsExpanded;
360
+ for (const block of this.toolBlocks.values()) {
361
+ block.component.setExpanded(this.toolsExpanded);
362
+ block.rows = undefined;
363
+ }
364
+ this.tui.requestRender();
365
+ return;
366
+ }
367
+
368
+ const totalLines = this.buildContentLines(this.lastInnerW).length;
369
+ const viewportHeight = this.viewportHeight();
370
+ if (this.fullscreen) {
371
+ this.scrollView.updateLayout(totalLines, viewportHeight, () => {
372
+ if (!this.closed) this.tui.requestRender();
373
+ });
374
+ if (this.keys.scrollUp(data)) this.scrollView.scrollBy(-1);
375
+ else if (this.keys.scrollDown(data)) this.scrollView.scrollBy(1);
376
+ else if (this.keys.pageUp(data)) this.scrollView.scrollBy(-viewportHeight);
377
+ else if (this.keys.pageDown(data)) this.scrollView.scrollBy(viewportHeight);
378
+ else if (matchesKey(data, "home")) this.scrollView.scrollToStart();
379
+ return;
380
+ }
381
+ const maxScroll = Math.max(0, totalLines - viewportHeight);
382
+
383
+ if (this.keys.scrollUp(data)) {
384
+ this.scrollOffset = Math.max(0, this.scrollOffset - 1);
385
+ this.autoScroll = this.scrollOffset >= maxScroll;
386
+ } else if (this.keys.scrollDown(data)) {
387
+ this.scrollOffset = Math.min(maxScroll, this.scrollOffset + 1);
388
+ this.autoScroll = this.scrollOffset >= maxScroll;
389
+ } else if (this.keys.pageUp(data)) {
390
+ this.scrollOffset = Math.max(0, this.scrollOffset - viewportHeight);
391
+ this.autoScroll = false;
392
+ } else if (this.keys.pageDown(data)) {
393
+ this.scrollOffset = Math.min(maxScroll, this.scrollOffset + viewportHeight);
394
+ this.autoScroll = this.scrollOffset >= maxScroll;
395
+ } else if (matchesKey(data, "home")) {
396
+ this.scrollOffset = 0;
397
+ this.autoScroll = false;
398
+ } else if (matchesKey(data, "end")) {
399
+ this.scrollOffset = maxScroll;
400
+ this.autoScroll = true;
401
+ }
402
+ }
403
+
404
+ private jumpToLatest(): void {
405
+ this.scrollView.scrollToEnd();
406
+ this.newMessages = 0;
407
+ this.stopArmed = false;
408
+ this.tui.requestRender();
409
+ }
410
+
411
+ handleMouse(event: TuiMouseEvent): TuiMouseEventResult {
412
+ if (!this.fullscreen) return { handled: false };
413
+ // Every cell belongs to this observer. Even unused clicks/drags must not
414
+ // fall through to Pi's transcript selection, scrolling, or editor.
415
+ if (this.closed || !this.viewport) return { handled: true, render: false };
416
+ const view = this.viewport;
417
+ const onScrollbar = this.scrollView.scrollbar !== "hidden" && event.x >= view.width - SCROLLBAR_WIDTH && event.x < view.width && event.y >= view.top && event.y < view.top + view.height;
418
+ if (event.type === "move") {
419
+ this.scrollView.setScrollbarActive(onScrollbar);
420
+ return { handled: true, render: false };
421
+ }
422
+ if (event.type === "wheel") {
423
+ this.stopArmed = false;
424
+ this.scrollView.scrollBy(event.wheelDelta ?? 0);
425
+ return { handled: true, render: true };
426
+ }
427
+ if (event.type === "release") {
428
+ const wasDragging = this.scrollbarGrabOffset !== undefined;
429
+ this.scrollbarGrabOffset = undefined;
430
+ this.scrollView.setScrollbarActive(onScrollbar);
431
+ return { handled: true, render: wasDragging };
432
+ }
433
+ if (event.type === "drag" && this.scrollbarGrabOffset !== undefined) {
434
+ const travel = view.height - view.thumbHeight;
435
+ const position = Math.max(0, Math.min(travel, event.y - view.top - this.scrollbarGrabOffset));
436
+ this.scrollView.scrollTo(travel > 0 ? Math.round(position / travel * view.maxScroll) : 0);
437
+ return { handled: true, render: true };
438
+ }
439
+ if (event.type === "press" && event.button === "left") {
440
+ this.scrollbarGrabOffset = undefined;
441
+ this.scrollView.setScrollbarActive(onScrollbar);
442
+ if (this.latestTarget && event.y === this.latestTarget.row && event.x >= this.latestTarget.start && event.x < this.latestTarget.end) {
443
+ this.jumpToLatest();
444
+ return { handled: true, render: true };
445
+ }
446
+ if (event.y === this.tui.terminal.rows - 1) {
447
+ const target = this.footerTargets.find(t => event.x >= t.start && event.x < t.end);
448
+ if (target) {
449
+ this.handleInput(target.key);
450
+ return { handled: true, render: true };
451
+ }
452
+ }
453
+ this.stopArmed = false;
454
+ if (this.composer && event.y === this.tui.terminal.rows - 2) {
455
+ this.composer.handleMouse({ ...event, x: event.x - 1, y: 0, width: this.lastInnerW, height: 1 });
456
+ return { handled: true, render: true };
457
+ }
458
+ if (onScrollbar && view.maxScroll > 0) {
459
+ const y = event.y - view.top;
460
+ if (y >= view.thumbTop && y < view.thumbTop + view.thumbHeight) {
461
+ this.scrollbarGrabOffset = y - view.thumbTop;
462
+ return { handled: true, capture: true, render: true };
463
+ }
464
+ this.scrollView.scrollBy(y < view.thumbTop ? -view.height : view.height);
465
+ // A track click still pages, but holding it can grab the thumb too.
466
+ this.scrollbarGrabOffset = Math.floor(view.thumbHeight / 2);
467
+ return { handled: true, capture: true, render: true };
468
+ }
469
+ return { handled: true, render: true };
470
+ }
471
+ return { handled: true, render: false };
472
+ }
473
+
474
+ render(width: number): string[] {
475
+ this.footerTargets = [];
476
+ this.latestTarget = undefined;
477
+ this.viewport = undefined;
478
+ const rows = Math.max(0, this.tui.terminal.rows);
479
+ if (!this.fullscreen && width < 6) return []; // too narrow for any meaningful rendering
480
+ if (width <= SCROLLBAR_WIDTH + 1) return Array.from({ length: rows }, () => " ".repeat(Math.max(0, width)));
481
+ const th = this.theme;
482
+ const innerW = this.fullscreen ? this.scrollView.getContentWidth(width - 1) : width - 4;
483
+ this.lastInnerW = innerW;
484
+ const lines: string[] = [];
485
+ const footerActions: { label: string; key: string }[] = [];
486
+ const pad = (s: string, len: number) => {
487
+ const vis = visibleWidth(s);
488
+ return s + " ".repeat(Math.max(0, len - vis));
489
+ };
490
+ const row = (content: string, scrollbar?: string): string => {
491
+ if (this.fullscreen) {
492
+ const contentWidth = width - 1 - (scrollbar ? SCROLLBAR_WIDTH : 0);
493
+ return " " + truncateToWidth(content, contentWidth, scrollbar ? "" : "...", true) + (scrollbar ?? "");
494
+ }
495
+ return th.fg("border", "│") + " " + truncateToWidth(pad(content, innerW), innerW, "...", true) + " " + th.fg("border", "│");
496
+ };
497
+ const hrTop = th.fg("border", `╭${"─".repeat(width - 2)}╮`);
498
+ const hrBot = th.fg("border", `╰${"─".repeat(width - 2)}╯`);
499
+ const hrMid = row(th.fg("dim", "─".repeat(innerW)));
500
+
501
+ // Header
502
+ if (!this.fullscreen) lines.push(hrTop);
503
+ const modeLabel = getPromptModeLabel(this.record.type);
504
+ const modeTag = modeLabel ? ` ${th.fg("dim", `(${modeLabel})`)}` : "";
505
+ const statusIcon = this.record.status === "running"
506
+ ? th.fg("accent", "●")
507
+ : this.record.status === "completed"
508
+ ? th.fg("success", "✓")
509
+ : this.record.status === "error"
510
+ ? th.fg("error", "✗")
511
+ : th.fg("dim", "○");
512
+ const duration = formatDuration(this.record.startedAt, this.record.completedAt);
513
+
514
+ const headerParts: string[] = [duration];
515
+ const toolUses = this.activity?.toolUses ?? this.record.toolUses;
516
+ if (toolUses > 0) headerParts.unshift(`${toolUses} tool${toolUses === 1 ? "" : "s"}`);
517
+ // Spend from the record, context from the live session: the record is the
518
+ // only total that survives the agent finishing and the only one carrying a
519
+ // nested child's spend.
520
+ const tokens = getLifetimeTotal(this.record.lifetimeUsage);
521
+ if (tokens > 0) {
522
+ const percent = getSessionContextPercent(this.activity?.session);
523
+ headerParts.push(formatSessionTokens(tokens, percent, th, this.record.compactionCount));
524
+ }
525
+ const cost = this.showCost ? formatCost(getLifetimeCost(this.record.lifetimeUsage)) : "";
526
+ if (cost) headerParts.push(cost);
527
+
528
+ lines.push(row(
529
+ `${statusIcon} ${renderAgentName(this.record.type, th, { bold: true })}${modeTag} ${th.fg("muted", this.record.description)} ${th.fg("dim", "·")} ${fgPreservingNestedStyles(th, "dim", headerParts.join(" · "))}`,
530
+ ));
531
+ const invocationLine = this.invocationLine();
532
+ if (invocationLine) lines.push(row(invocationLine));
533
+ lines.push(hrMid);
534
+
535
+ // Content area — rebuild every render (live data, no cache needed)
536
+ const contentLines = this.fullscreen ? this.scrollView.render(width - 1) : this.buildContentLines(innerW);
537
+ const viewportHeight = this.viewportHeight();
538
+ const maxScroll = Math.max(0, contentLines.length - viewportHeight);
539
+ if (this.fullscreen) {
540
+ this.scrollView.updateLayout(contentLines.length, viewportHeight, () => {
541
+ if (!this.closed) this.tui.requestRender();
542
+ });
543
+ if (this.scrollView.isFollowingEnd) this.newMessages = 0;
544
+ } else if (this.autoScroll) {
545
+ this.scrollOffset = maxScroll;
546
+ }
547
+
548
+ const visibleStart = this.fullscreen ? this.scrollView.scrollTop : Math.min(this.scrollOffset, maxScroll);
549
+ const visible = contentLines.slice(visibleStart, visibleStart + viewportHeight);
550
+ // Match Pi's scrollbar geometry: rounded size, at least two rows when available.
551
+ const thumbHeight = Math.min(viewportHeight, Math.max(2, Math.round(viewportHeight * viewportHeight / Math.max(1, contentLines.length))));
552
+ const thumbTop = maxScroll > 0 ? Math.round(visibleStart / maxScroll * (viewportHeight - thumbHeight)) : 0;
553
+ this.viewport = { width, top: lines.length, height: viewportHeight, maxScroll, thumbTop, thumbHeight };
554
+
555
+ for (let i = 0; i < viewportHeight; i++) {
556
+ let scrollbar: string | undefined;
557
+ if (this.scrollView.isScrollbarVisible) {
558
+ const onThumb = i >= thumbTop && i < thumbTop + thumbHeight;
559
+ if (onThumb) {
560
+ scrollbar = th.fg("scrollbarThumb", this.scrollView.isScrollbarActive ? "█" : "┃");
561
+ } else {
562
+ scrollbar = th.fg("scrollbarTrack", "│");
563
+ }
564
+ }
565
+ lines.push(row(visible[i] ?? "", scrollbar));
566
+ }
567
+
568
+ // Keep the divider pinned above the footer, with the jump control centered
569
+ // inside it. Neither scrolling nor new messages change its position.
570
+ if (this.fullscreen && !this.scrollView.isFollowingEnd && maxScroll > 0 && rows >= this.chromeLines()) {
571
+ const text = this.newMessages > 0
572
+ ? `${this.newMessages} new message${this.newMessages === 1 ? "" : "s"}`
573
+ : "Jump to latest message";
574
+ const label = truncateToWidth(`[ ↓ ${text} · Ctrl+End ]`, innerW, "…");
575
+ const labelWidth = visibleWidth(label);
576
+ const padding = Math.floor((innerW - labelWidth) / 2);
577
+ this.latestTarget = { row: lines.length, start: padding + 1, end: padding + 1 + labelWidth };
578
+ lines.push(row(th.fg("dim", "─".repeat(padding)) + th.fg("accent", label) + th.fg("dim", "─".repeat(innerW - padding - labelWidth))));
579
+ } else {
580
+ lines.push(hrMid);
581
+ }
582
+ if (this.composer) {
583
+ // Composer row: the Input renders its own `> ` prompt and cursor.
584
+ this.composer.focused = this.focused;
585
+ lines.push(row(this.composer.render(innerW)[0] ?? ""));
586
+ footerActions.push({ label: "Enter send", key: "\r" }, { label: "Esc cancel", key: "\x1b" });
587
+ const composeHint = th.fg("dim", "Enter send · Esc cancel");
588
+ const composeLeft = th.fg("accent", "✎ steer");
589
+ const composeGap = Math.max(1, innerW - visibleWidth(composeLeft) - visibleWidth(composeHint));
590
+ lines.push(row(composeLeft + " ".repeat(composeGap) + composeHint));
591
+ } else {
592
+ // Actions on the left, navigation on the right. The scroll hint keeps its
593
+ // full key list so the less-obvious bindings stay discoverable; it leads
594
+ // the right group so "Esc close" is the only part that truncates first.
595
+ const sep = th.fg("dim", " · ");
596
+ if (this.canSteer()) footerActions.push({ label: "Enter steer", key: "\r" });
597
+ // Abbreviated for the same reason as the Markdown group below.
598
+ if (this.canSendToBackground()) footerActions.push({ label: "b bg", key: "b" });
599
+ if (this.isStoppable()) {
600
+ footerActions.push({ label: this.stopArmed ? "x again to STOP" : "x stop", key: "x" });
601
+ }
602
+ // Abbreviated (`raw`/`md`/`md+`) because the idle footer is already full
603
+ // at 80 columns with steer + stop present, and this group has no
604
+ // degradation step below "drop the line-count readout".
605
+ footerActions.push({ label: `m ${MARKDOWN_MODE_LABELS[this.markdownMode()]}`, key: "m" });
606
+ const actions = footerActions.map(a => th.fg(a.key === "x" && this.stopArmed ? "error" : "dim", a.label));
607
+ footerActions.push({ label: "Esc close", key: "\x1b" });
608
+ const footerRight = th.fg("dim", "↑↓ scroll · PgUp/PgDn or Shift+↑↓ · Esc close");
609
+
610
+ // Prepend the line-count/scroll-% readout only when there's spare width —
611
+ // it's the first thing dropped so it never crowds out the hints.
612
+ const scrollPct = contentLines.length <= viewportHeight
613
+ ? "100%"
614
+ : `${Math.round(((visibleStart + viewportHeight) / contentLines.length) * 100)}%`;
615
+ const count = th.fg("dim", `${contentLines.length} lines · ${scrollPct}`);
616
+ const withCount = [count, ...actions].join(sep);
617
+ const footerLeft = visibleWidth(withCount) + visibleWidth(footerRight) + 1 <= innerW
618
+ ? withCount
619
+ : actions.join(sep);
620
+
621
+ const footerGap = Math.max(1, innerW - visibleWidth(footerLeft) - visibleWidth(footerRight));
622
+ lines.push(row(footerLeft + " ".repeat(footerGap) + footerRight));
623
+ }
624
+ if (!this.fullscreen) {
625
+ lines.push(hrBot);
626
+ return lines;
627
+ }
628
+ // Keep the footer on screen even in a terminal shorter than the chrome.
629
+ const footer = lines.pop() ?? row("");
630
+ const output = rows > 0 ? [...lines.slice(0, rows - 1), footer] : [];
631
+ const footerText = stripTerminalSequences(footer);
632
+ for (const action of footerActions) {
633
+ const index = footerText.indexOf(action.label);
634
+ if (index < 0) continue; // a clipped label is not a clickable control
635
+ const start = visibleWidth(footerText.slice(0, index));
636
+ this.footerTargets.push({ start, end: start + visibleWidth(action.label), key: action.key });
637
+ }
638
+ return output;
639
+ }
640
+
641
+ /** Stoppable only when a stop handler exists and the agent is still active. */
642
+ private isStoppable(): boolean {
643
+ return !!this.onStop && (this.record.status === "running" || this.record.status === "queued");
644
+ }
645
+
646
+ /** The mode in force: an `m` press, else the setting, else the default. */
647
+ private markdownMode(): ViewerMarkdownMode {
648
+ return this.markdownModeOverride ?? this.viewerMarkdown?.() ?? "assistant";
649
+ }
650
+
651
+ /** Wrap `text` literally — the pre-Markdown path, and the fallback from it. */
652
+ private rawLines(text: string, width: number, dim: boolean): string[] {
653
+ const lines = wrapTextWithAnsi(text, width);
654
+ return dim ? lines.map(l => this.theme.fg("dim", l)) : lines;
655
+ }
656
+
657
+ /** Render `text` as Markdown, reusing this message's component instance. */
658
+ private markdownLines(msg: AgentSession["messages"][number], text: string, width: number, dim: boolean): string[] {
659
+ let entry = this.markdownCache.get(msg);
660
+ if (!entry) {
661
+ entry = {
662
+ md: new Markdown(
663
+ text,
664
+ 0,
665
+ 0,
666
+ this.markdownTheme,
667
+ // Keeps result prose visually receded, the way the raw path's
668
+ // per-line `fg("dim", …)` did. Fenced code is the exception and is
669
+ // left alone deliberately: pi's theme highlights it with its own
670
+ // colors, which this would otherwise flatten.
671
+ dim ? { color: (t: string) => this.theme.fg("dim", t) } : undefined,
672
+ MARKDOWN_OPTIONS,
673
+ ),
674
+ text,
675
+ };
676
+ this.markdownCache.set(msg, entry);
677
+ } else if (entry.text !== text) {
678
+ // Streaming: the message object is stable, its text grows. A failed
679
+ // prefix remains unsafe after append-only deltas, so retry only when the
680
+ // content was replaced or truncated.
681
+ const shouldRetry = !text.startsWith(entry.text);
682
+ entry.md.setText(text);
683
+ entry.text = text;
684
+ if (shouldRetry) entry.failed = false;
685
+ }
686
+ if (entry.failed) return this.rawLines(text, width, dim);
687
+
688
+ try {
689
+ return entry.md.render(width);
690
+ } catch {
691
+ // The parser is recursive and this is arbitrary tool output: ~54 nested
692
+ // blockquotes overflow the stack, and no amount of fuzzing proves that is
693
+ // the only such input. `render()` is on the TUI's critical path, so a
694
+ // throw here takes the overlay down for content the literal path shows
695
+ // fine — degrade to that instead, and remember, since the throw would
696
+ // otherwise repeat on every render and every scroll key.
697
+ entry.failed = true;
698
+ return this.rawLines(text, width, dim);
699
+ }
700
+ }
701
+
702
+ /** Steerable only when a steer handler exists and the agent is still active. */
703
+ private canSteer(): boolean {
704
+ return !!this.onSteer && (this.record.status === "running" || this.record.status === "queued");
705
+ }
706
+
707
+ /**
708
+ * Asked of the owner rather than derived from the record: only the caller
709
+ * blocked on this run knows it can let go of it, and `blocking` alone also
710
+ * matches spawns nobody can hand off (the agent generator).
711
+ */
712
+ private canSendToBackground(): boolean {
713
+ return this.onBackground?.available() === true;
714
+ }
715
+
716
+ /** Open the inline steering composer and route subsequent input to it. */
717
+ private openComposer(): void {
718
+ const input = new Input();
719
+ input.focused = true;
720
+ input.onSubmit = (value: string) => {
721
+ const message = value.trim();
722
+ this.composer = undefined;
723
+ if (message) this.onSteer?.(message);
724
+ this.tui.requestRender();
725
+ };
726
+ input.onEscape = () => {
727
+ this.composer = undefined;
728
+ this.tui.requestRender();
729
+ };
730
+ this.composer = input;
731
+ this.tui.requestRender();
732
+ }
733
+
734
+ invalidate(): void { /* no cached state to clear */ }
735
+
736
+ dispose(): void {
737
+ this.closed = true;
738
+ this.scrollView.setScrollbar("hidden"); // clears Pi's auto-hide timer
739
+ if (this.unsubscribe) {
740
+ this.unsubscribe();
741
+ this.unsubscribe = undefined;
742
+ }
743
+ }
744
+
745
+ // ---- Private ----
746
+
747
+ private viewportHeight(): number {
748
+ if (this.fullscreen) return Math.max(0, this.tui.terminal.rows - this.chromeLines());
749
+ // Cap mirrors the overlay's maxHeight — otherwise the viewer would render
750
+ // more lines than the overlay shows and clip the footer.
751
+ const maxRows = Math.floor((this.tui.terminal.rows * VIEWPORT_HEIGHT_PCT) / 100);
752
+ return Math.max(MIN_VIEWPORT, maxRows - this.chromeLines());
753
+ }
754
+
755
+ private chromeLines(): number {
756
+ // The composer adds one row above the footer hint while it's open.
757
+ return CHROME_LINES_BASE - (this.fullscreen ? 2 : 0) + (this.invocationLine() ? 1 : 0) + (this.composer ? 1 : 0);
758
+ }
759
+
760
+ private invocationLine(): string | undefined {
761
+ // Canonical id here, short label everywhere else: this overlay is opened to
762
+ // inspect one agent and has the width for it, and two providers can serve
763
+ // models whose short names read alike.
764
+ const { modelName, modelId, tags } = buildInvocationTags(this.record.invocation);
765
+ const model = modelId ?? modelName;
766
+ const parts = model ? [model, ...tags] : tags;
767
+ if (parts.length === 0) return undefined;
768
+ return this.theme.fg("dim", ` ↳ ${parts.join(" · ")}`);
769
+ }
770
+
771
+ private buildContentLines(width: number): string[] {
772
+ if (width <= 0) return [];
773
+
774
+ const th = this.theme;
775
+ const messages = this.session.messages;
776
+ const lines: string[] = [];
777
+
778
+ if (messages.length === 0) {
779
+ lines.push(th.fg("dim", "(waiting for first message...)"));
780
+ return lines;
781
+ }
782
+
783
+ // A result is folded into the block of the call it answers, so every call
784
+ // has to find its result before the loop reaches it.
785
+ const results = new Map<string, ToolResultPart>();
786
+ for (const msg of messages) {
787
+ if (msg.role === "toolResult") results.set(msg.toolCallId, msg);
788
+ }
789
+ const foldedCalls = new Set<string>();
790
+
791
+ const mode = this.markdownMode();
792
+ let needsSeparator = false;
793
+ for (const msg of messages) {
794
+ if (msg.role === "user") {
795
+ const text = typeof msg.content === "string"
796
+ ? msg.content
797
+ : extractText(msg.content);
798
+ if (!text.trim()) continue;
799
+ if (needsSeparator) lines.push(th.fg("dim", "───"));
800
+ lines.push(th.fg("accent", "[User]"));
801
+ for (const line of wrapTextWithAnsi(text.trim(), width)) {
802
+ lines.push(line);
803
+ }
804
+ } else if (msg.role === "assistant") {
805
+ const textParts: string[] = [];
806
+ const toolCalls: ToolCallPart[] = [];
807
+ for (const c of msg.content) {
808
+ if (c.type === "text" && c.text) textParts.push(c.text);
809
+ else if (c.type === "toolCall") toolCalls.push(c);
810
+ }
811
+ if (needsSeparator) lines.push(th.fg("dim", "───"));
812
+ lines.push(th.bold("[Assistant]"));
813
+ if (textParts.length > 0) {
814
+ const text = textParts.join("\n").trim();
815
+ lines.push(...(mode === "off"
816
+ ? this.rawLines(text, width, false)
817
+ : this.markdownLines(msg, text, width, false)));
818
+ }
819
+ for (const call of toolCalls) {
820
+ if (!this.toolRendering) {
821
+ lines.push(truncateToWidth(th.fg("muted", ` [Tool: ${call.name}]`), width));
822
+ continue;
823
+ }
824
+ foldedCalls.add(call.id);
825
+ // An aborted or failed response never runs its calls, so no result
826
+ // will arrive: say so, as pi's session replay does.
827
+ const notRun = msg.stopReason === "aborted" ? "Operation aborted"
828
+ : msg.stopReason === "error" ? msg.errorMessage || "Error"
829
+ : undefined;
830
+ lines.push(...this.toolBlockLines(call, results.get(call.id), notRun, width));
831
+ }
832
+ } else if (msg.role === "toolResult") {
833
+ // Rendered under its call above. A result whose call is not in the
834
+ // transcript — a compacted prefix, a reopened session — keeps the plain
835
+ // block, because there is no call row to fold it into.
836
+ if (foldedCalls.has(msg.toolCallId)) continue;
837
+ const { text, elided } = capResult(extractText(msg.content).trim());
838
+ if (!text) continue;
839
+ if (needsSeparator) lines.push(th.fg("dim", "───"));
840
+ lines.push(th.fg("dim", "[Result]"));
841
+ lines.push(...(mode === "all"
842
+ ? this.markdownLines(msg, text, width, true)
843
+ : this.rawLines(text, width, true)));
844
+ if (elided) lines.push(truncateToWidth(th.fg("dim", truncationNote(elided)), width));
845
+ } else if ((msg as any).role === "bashExecution") {
846
+ const bash = msg as any;
847
+ if (needsSeparator) lines.push(th.fg("dim", "───"));
848
+ lines.push(truncateToWidth(th.fg("muted", ` $ ${bash.command}`), width));
849
+ if (bash.output?.trim()) {
850
+ // Same cap as a tool result, never Markdown: command output is the one
851
+ // thing here that is definitionally not authored as Markdown.
852
+ const { text, elided } = capResult(bash.output.trim());
853
+ lines.push(...this.rawLines(text, width, true));
854
+ if (elided) lines.push(truncateToWidth(th.fg("dim", truncationNote(elided)), width));
855
+ }
856
+ } else {
857
+ continue;
858
+ }
859
+ needsSeparator = true;
860
+ }
861
+
862
+ // Streaming indicator for running agents
863
+ if (this.record.status === "running" && this.activity) {
864
+ const act = describeActivity(this.activity.activeTools, this.activity.responseText);
865
+ lines.push("");
866
+ lines.push(truncateToWidth(th.fg("accent", "▍ ") + th.fg("dim", act), width));
867
+ }
868
+
869
+ // Only clamp what actually overflows: `truncateToWidth` takes a slow,
870
+ // character-by-character path for any line carrying an escape sequence, and
871
+ // a tool block's rows are already rendered at this width by its component.
872
+ return lines.map(l => (visibleWidth(l) > width ? truncateToWidth(l, width) : l));
873
+ }
874
+
875
+ /**
876
+ * One tool call as pi draws it in the main transcript: the arguments on the
877
+ * call, then the result in that tool's own format — a bash box, read line
878
+ * numbers, an edit diff. Blocks are cached per call id because
879
+ * `ToolExecutionComponent` rebuilds its renderer tree on every update.
880
+ *
881
+ * A tool without a renderer still renders: the component falls back to a
882
+ * generic `name key=value` header plus a bounded preview that the expand key
883
+ * unfolds.
884
+ */
885
+ private toolBlockLines(call: ToolCallPart, result: ToolResultPart | undefined, notRun: string | undefined, width: number): string[] {
886
+ let block = this.toolBlocks.get(call.id);
887
+ let changed = false;
888
+ if (!block) {
889
+ // Built the way pi replays a saved session: `session.messages` only holds
890
+ // finished messages, so the arguments are final. No setArgsComplete() or
891
+ // markExecutionStarted() — both request a render, and this runs inside
892
+ // one; the former also makes the edit renderer re-read the file.
893
+ const component = new ToolExecutionComponent(
894
+ call.name,
895
+ call.id,
896
+ call.arguments,
897
+ // Text only: an image needs rows this line-based renderer cannot reserve.
898
+ { showImages: false },
899
+ // pi's resolution for the agent's own session: builtin and extension
900
+ // renderers, and extension overrides. `{}` for a tool no registry knows,
901
+ // so it gets the bounded, expandable fallback rather than a raw dump.
902
+ this.session.extensionRunner.resolveToolRenderers(call.name, () => this.session.getToolDefinition(call.name)) ?? {},
903
+ this.tui,
904
+ this.session.sessionManager.getCwd(),
905
+ );
906
+ component.setExpanded(this.toolsExpanded);
907
+ // The message is final, so this is decided once, when the block is built.
908
+ if (notRun && !result) component.updateResult({ content: [{ type: "text", text: notRun }], isError: true });
909
+ block = { component };
910
+ this.toolBlocks.set(call.id, block);
911
+ changed = true;
912
+ }
913
+ if (result && block.result !== result) {
914
+ block.result = result;
915
+ block.component.updateResult({
916
+ content: result.content,
917
+ details: result.details,
918
+ isError: result.isError,
919
+ durationMs: result.durationMs,
920
+ });
921
+ changed = true;
922
+ }
923
+ if (!changed && block.rows && block.width === width) return block.rows;
924
+ block.rows = block.component.render(width);
925
+ block.width = width;
926
+ return block.rows;
927
+ }
928
+ }