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

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