@nredd/pi-subagents 0.0.0-stage → 0.22.0-nredd.10

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