@timmyjl12/pi-subagents 0.0.0-stage → 0.20.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 (218) hide show
  1. package/CHANGELOG.md +827 -0
  2. package/CONTRIBUTING.md +72 -0
  3. package/LICENSE +21 -0
  4. package/README.md +1079 -2
  5. package/SECURITY.md +97 -0
  6. package/dist/abortable.d.ts +12 -0
  7. package/dist/abortable.js +42 -0
  8. package/dist/active-agents-prompt.d.ts +18 -0
  9. package/dist/active-agents-prompt.js +34 -0
  10. package/dist/advisor-status.d.ts +16 -0
  11. package/dist/advisor-status.js +74 -0
  12. package/dist/agent-color.d.ts +35 -0
  13. package/dist/agent-color.js +123 -0
  14. package/dist/agent-file-toggle.d.ts +125 -0
  15. package/dist/agent-file-toggle.js +264 -0
  16. package/dist/agent-manager.d.ts +485 -0
  17. package/dist/agent-manager.js +1380 -0
  18. package/dist/agent-runner.d.ts +319 -0
  19. package/dist/agent-runner.js +1128 -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 +15 -0
  23. package/dist/child-context.js +181 -0
  24. package/dist/child-session-shutdown.d.ts +3 -0
  25. package/dist/child-session-shutdown.js +48 -0
  26. package/dist/context.d.ts +12 -0
  27. package/dist/context.js +56 -0
  28. package/dist/cross-extension-rpc.d.ts +66 -0
  29. package/dist/cross-extension-rpc.js +138 -0
  30. package/dist/custom-agents.d.ts +54 -0
  31. package/dist/custom-agents.js +386 -0
  32. package/dist/default-agents.d.ts +7 -0
  33. package/dist/default-agents.js +125 -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/error-log.d.ts +58 -0
  39. package/dist/error-log.js +168 -0
  40. package/dist/group-join.d.ts +32 -0
  41. package/dist/group-join.js +116 -0
  42. package/dist/index.d.ts +52 -0
  43. package/dist/index.js +3896 -0
  44. package/dist/invocation-config.d.ts +137 -0
  45. package/dist/invocation-config.js +129 -0
  46. package/dist/memory.d.ts +53 -0
  47. package/dist/memory.js +165 -0
  48. package/dist/mention-clone.d.ts +87 -0
  49. package/dist/mention-clone.js +178 -0
  50. package/dist/mention.d.ts +81 -0
  51. package/dist/mention.js +131 -0
  52. package/dist/model-resolver.d.ts +36 -0
  53. package/dist/model-resolver.js +95 -0
  54. package/dist/model-scope.d.ts +49 -0
  55. package/dist/model-scope.js +48 -0
  56. package/dist/nested-tools.d.ts +55 -0
  57. package/dist/nested-tools.js +299 -0
  58. package/dist/output-diagnostics.d.ts +11 -0
  59. package/dist/output-diagnostics.js +64 -0
  60. package/dist/output-file.d.ts +53 -0
  61. package/dist/output-file.js +248 -0
  62. package/dist/prompts.d.ts +61 -0
  63. package/dist/prompts.js +94 -0
  64. package/dist/recovery.d.ts +56 -0
  65. package/dist/recovery.js +341 -0
  66. package/dist/schedule-store.d.ts +44 -0
  67. package/dist/schedule-store.js +210 -0
  68. package/dist/schedule.d.ts +109 -0
  69. package/dist/schedule.js +359 -0
  70. package/dist/settings.d.ts +360 -0
  71. package/dist/settings.js +251 -0
  72. package/dist/skill-loader.d.ts +24 -0
  73. package/dist/skill-loader.js +93 -0
  74. package/dist/standalone-fallback.d.ts +30 -0
  75. package/dist/standalone-fallback.js +239 -0
  76. package/dist/status-note.d.ts +61 -0
  77. package/dist/status-note.js +85 -0
  78. package/dist/structured-output.d.ts +61 -0
  79. package/dist/structured-output.js +112 -0
  80. package/dist/terminal-progress.d.ts +115 -0
  81. package/dist/terminal-progress.js +206 -0
  82. package/dist/types.d.ts +382 -0
  83. package/dist/types.js +5 -0
  84. package/dist/ui/agent-mention.d.ts +82 -0
  85. package/dist/ui/agent-mention.js +187 -0
  86. package/dist/ui/agent-widget.d.ts +235 -0
  87. package/dist/ui/agent-widget.js +652 -0
  88. package/dist/ui/conversation-viewer.d.ts +105 -0
  89. package/dist/ui/conversation-viewer.js +540 -0
  90. package/dist/ui/fleet-list.d.ts +183 -0
  91. package/dist/ui/fleet-list.js +494 -0
  92. package/dist/ui/fleet-overlay.d.ts +172 -0
  93. package/dist/ui/fleet-overlay.js +691 -0
  94. package/dist/ui/native-transcript.d.ts +33 -0
  95. package/dist/ui/native-transcript.js +230 -0
  96. package/dist/ui/schedule-menu.d.ts +16 -0
  97. package/dist/ui/schedule-menu.js +94 -0
  98. package/dist/ui/select-item.d.ts +27 -0
  99. package/dist/ui/select-item.js +34 -0
  100. package/dist/ui/tool-progress.d.ts +22 -0
  101. package/dist/ui/tool-progress.js +56 -0
  102. package/dist/ui/viewer-keys.d.ts +20 -0
  103. package/dist/ui/viewer-keys.js +17 -0
  104. package/dist/ui/workflow-card.d.ts +175 -0
  105. package/dist/ui/workflow-card.js +332 -0
  106. package/dist/ui/workflow-dialog.d.ts +305 -0
  107. package/dist/ui/workflow-dialog.js +843 -0
  108. package/dist/ui/workflow-menu.d.ts +60 -0
  109. package/dist/ui/workflow-menu.js +147 -0
  110. package/dist/usage.d.ts +135 -0
  111. package/dist/usage.js +120 -0
  112. package/dist/workflow/collisions.d.ts +95 -0
  113. package/dist/workflow/collisions.js +88 -0
  114. package/dist/workflow/entry.d.ts +32 -0
  115. package/dist/workflow/entry.js +29 -0
  116. package/dist/workflow/host.d.ts +62 -0
  117. package/dist/workflow/host.js +363 -0
  118. package/dist/workflow/journal.d.ts +97 -0
  119. package/dist/workflow/journal.js +120 -0
  120. package/dist/workflow/json-schema.d.ts +51 -0
  121. package/dist/workflow/json-schema.js +111 -0
  122. package/dist/workflow/meta.d.ts +67 -0
  123. package/dist/workflow/meta.js +317 -0
  124. package/dist/workflow/progress.d.ts +224 -0
  125. package/dist/workflow/progress.js +361 -0
  126. package/dist/workflow/runtime.d.ts +334 -0
  127. package/dist/workflow/runtime.js +830 -0
  128. package/dist/workflow/saved.d.ts +90 -0
  129. package/dist/workflow/saved.js +203 -0
  130. package/dist/workflow/task.d.ts +136 -0
  131. package/dist/workflow/task.js +207 -0
  132. package/dist/workflow/tool-description.d.ts +38 -0
  133. package/dist/workflow/tool-description.js +199 -0
  134. package/dist/workflow/worker-source.d.ts +47 -0
  135. package/dist/workflow/worker-source.js +778 -0
  136. package/dist/worktree.d.ts +52 -0
  137. package/dist/worktree.js +164 -0
  138. package/dist/xml.d.ts +10 -0
  139. package/dist/xml.js +12 -0
  140. package/docs/FORK.md +40 -0
  141. package/docs/recovery.md +62 -0
  142. package/docs/rpc.md +189 -0
  143. package/docs/workflows.md +437 -0
  144. package/examples/agent-tool-description.md +43 -0
  145. package/examples/workflows/compose.js +51 -0
  146. package/examples/workflows/fan-out-audit.js +47 -0
  147. package/examples/workflows/gated-fix.js +60 -0
  148. package/examples/workflows/lib/count-child.js +27 -0
  149. package/examples/workflows/review-panel.js +63 -0
  150. package/examples/workflows/structured-findings.js +78 -0
  151. package/package.json +75 -6
  152. package/src/abortable.ts +43 -0
  153. package/src/active-agents-prompt.ts +39 -0
  154. package/src/advisor-status.ts +74 -0
  155. package/src/agent-color.ts +161 -0
  156. package/src/agent-file-toggle.ts +273 -0
  157. package/src/agent-manager.ts +1601 -0
  158. package/src/agent-runner.ts +1372 -0
  159. package/src/agent-types.ts +345 -0
  160. package/src/child-context.ts +173 -0
  161. package/src/child-session-shutdown.ts +46 -0
  162. package/src/context.ts +58 -0
  163. package/src/cross-extension-rpc.ts +198 -0
  164. package/src/custom-agents.ts +417 -0
  165. package/src/default-agents.ts +129 -0
  166. package/src/enabled-models.ts +180 -0
  167. package/src/env.ts +33 -0
  168. package/src/error-log.ts +193 -0
  169. package/src/group-join.ts +141 -0
  170. package/src/index.ts +4218 -0
  171. package/src/invocation-config.ts +230 -0
  172. package/src/memory.ts +179 -0
  173. package/src/mention-clone.ts +221 -0
  174. package/src/mention.ts +141 -0
  175. package/src/model-resolver.ts +118 -0
  176. package/src/model-scope.ts +70 -0
  177. package/src/nested-tools.ts +422 -0
  178. package/src/output-diagnostics.ts +68 -0
  179. package/src/output-file.ts +258 -0
  180. package/src/prompts.ts +151 -0
  181. package/src/recovery.ts +320 -0
  182. package/src/schedule-store.ts +201 -0
  183. package/src/schedule.ts +386 -0
  184. package/src/settings.ts +587 -0
  185. package/src/skill-loader.ts +102 -0
  186. package/src/standalone-fallback.ts +195 -0
  187. package/src/status-note.ts +90 -0
  188. package/src/structured-output.ts +130 -0
  189. package/src/terminal-progress.ts +215 -0
  190. package/src/types.ts +394 -0
  191. package/src/ui/agent-mention.ts +216 -0
  192. package/src/ui/agent-widget.ts +732 -0
  193. package/src/ui/conversation-viewer.ts +523 -0
  194. package/src/ui/fleet-list.ts +563 -0
  195. package/src/ui/fleet-overlay.ts +847 -0
  196. package/src/ui/native-transcript.ts +220 -0
  197. package/src/ui/schedule-menu.ts +105 -0
  198. package/src/ui/select-item.ts +45 -0
  199. package/src/ui/tool-progress.ts +67 -0
  200. package/src/ui/viewer-keys.ts +39 -0
  201. package/src/ui/workflow-card.ts +470 -0
  202. package/src/ui/workflow-dialog.ts +1115 -0
  203. package/src/ui/workflow-menu.ts +193 -0
  204. package/src/usage.ts +167 -0
  205. package/src/workflow/collisions.ts +123 -0
  206. package/src/workflow/entry.ts +47 -0
  207. package/src/workflow/host.ts +404 -0
  208. package/src/workflow/journal.ts +164 -0
  209. package/src/workflow/json-schema.ts +128 -0
  210. package/src/workflow/meta.ts +325 -0
  211. package/src/workflow/progress.ts +550 -0
  212. package/src/workflow/runtime.ts +1219 -0
  213. package/src/workflow/saved.ts +217 -0
  214. package/src/workflow/task.ts +302 -0
  215. package/src/workflow/tool-description.ts +200 -0
  216. package/src/workflow/worker-source.ts +781 -0
  217. package/src/worktree.ts +205 -0
  218. package/src/xml.ts +13 -0
@@ -0,0 +1,523 @@
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, CustomEditor, getMarkdownTheme, type KeybindingsManager } from "@earendil-works/pi-coding-agent";
9
+ import { type Component, CURSOR_MARKER, type Focusable, getKeybindings, isKeyRelease, Markdown, type MarkdownOptions, type MarkdownTheme, matchesKey, ScrollView, type TUI, type TuiMouseEvent, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
10
+ import { renderAgentName } from "../agent-color.js";
11
+ import { extractText } from "../context.js";
12
+ import type { AgentRecord, ViewerMarkdownMode } from "../types.js";
13
+ import { getLifetimeCost, getLifetimeTotal, getSessionContextPercent } from "../usage.js";
14
+ import type { Theme } from "./agent-widget.js";
15
+ import { type AgentActivity, buildInvocationTags, describeActivity, fgPreservingNestedStyles, formatCost, formatDuration, formatSessionTokens, getPromptModeLabel } from "./agent-widget.js";
16
+ import { NativeTranscript } from "./native-transcript.js";
17
+ import { RESULT_MAX_CHARS, truncationNote } from "./tool-progress.js";
18
+
19
+ export { RESULT_MAX_CHARS } from "./tool-progress.js";
20
+ export const VIEWPORT_HEIGHT_PCT = 100;
21
+ const drafts = new WeakMap<AgentSession, string>();
22
+
23
+ /** Ctrl+R cycles native cards → Markdown inspection → raw inspection. Ordinary text stays typable. */
24
+ const MARKDOWN_MODES: readonly ViewerMarkdownMode[] = ["off", "assistant", "all"];
25
+
26
+ /** Footer labels — short, because the idle footer is already full at 80 columns. */
27
+ const MARKDOWN_MODE_LABELS: Record<ViewerMarkdownMode, string> = {
28
+ off: "raw",
29
+ assistant: "md",
30
+ all: "md+",
31
+ };
32
+
33
+ /**
34
+ * Both options keep the renderer from *rewriting* source that only looks like
35
+ * Markdown: without them `3) a / 7) b / 9) c` comes back renumbered `3. 4. 5.`
36
+ * and backslash escapes are normalized away. Neither is a safe edit to make to
37
+ * a tool's output, and both are cheap to switch off.
38
+ */
39
+ const MARKDOWN_OPTIONS: MarkdownOptions = {
40
+ preserveOrderedListMarkers: true,
41
+ preserveBackslashEscapes: true,
42
+ };
43
+
44
+ /**
45
+ * Pi's own Markdown theme when this process has one, else a theme built from the
46
+ * viewer's `Theme`.
47
+ *
48
+ * Preferring pi's is what buys syntax-highlighted code fences (it carries a
49
+ * `highlightCode`), and it keeps this surface consistent with the notification
50
+ * renderer, which uses the same source. It has to be *probed* rather than
51
+ * try/caught around the call: `getMarkdownTheme()` returns arrow functions that
52
+ * read pi's global theme lazily, so an uninitialized theme throws inside
53
+ * `render()` — long after this returns — and takes the overlay with it. That is
54
+ * the case in tests and any embedded session that never called `initTheme()`.
55
+ */
56
+ function resolveMarkdownTheme(th: Theme): MarkdownTheme {
57
+ try {
58
+ const piTheme = getMarkdownTheme();
59
+ piTheme.heading("probe");
60
+ return piTheme;
61
+ } catch {
62
+ return fallbackMarkdownTheme(th);
63
+ }
64
+ }
65
+
66
+ /**
67
+ * `Theme` carries only `fg` and `bold`, so the three remaining styles are
68
+ * written as raw SGR. Rendering them as plain text instead would silently drop
69
+ * `*emphasis*`'s markers with nothing in their place, turning a formatting
70
+ * change into a content change.
71
+ */
72
+ function fallbackMarkdownTheme(th: Theme): MarkdownTheme {
73
+ const sgr = (on: number, off: number) => (text: string) => `\x1b[${on}m${text}\x1b[${off}m`;
74
+ return {
75
+ heading: text => th.bold(th.fg("accent", text)),
76
+ link: text => th.fg("accent", text),
77
+ linkUrl: text => th.fg("muted", text),
78
+ code: text => th.fg("muted", text),
79
+ codeBlock: text => th.fg("muted", text),
80
+ codeBlockBorder: text => th.fg("dim", text),
81
+ quote: text => th.fg("muted", text),
82
+ quoteBorder: text => th.fg("dim", text),
83
+ hr: text => th.fg("dim", text),
84
+ listBullet: text => th.fg("accent", text),
85
+ bold: text => th.bold(text),
86
+ italic: sgr(3, 23),
87
+ underline: sgr(4, 24),
88
+ strikethrough: sgr(9, 29),
89
+ };
90
+ }
91
+
92
+ /**
93
+ * Cap `text` at `RESULT_MAX_CHARS`, reporting the elision separately rather than
94
+ * appending it.
95
+ *
96
+ * Separately because the notice is the viewer's chrome, not the tool's output.
97
+ * Appended into the string it becomes content: a cut landing inside a fenced
98
+ * code block — likely, on exactly the large `ctx_execute` results this is for —
99
+ * renders the notice as a line of source inside the fence.
100
+ */
101
+ function capResult(text: string): { text: string; elided: number } {
102
+ if (text.length <= RESULT_MAX_CHARS) return { text, elided: 0 };
103
+ return {
104
+ text: text.slice(0, RESULT_MAX_CHARS),
105
+ elided: text.length - RESULT_MAX_CHARS,
106
+ };
107
+ }
108
+
109
+ export class ConversationViewer implements Component, Focusable {
110
+ private unsubscribe: (() => void) | undefined;
111
+ private closed = false;
112
+ private stopArmed = false;
113
+ private readonly editor: CustomEditor;
114
+ private readonly transcript: NativeTranscript;
115
+ private readonly scroll: ScrollView;
116
+ private transcriptTop = 0;
117
+ private editorTop = 0;
118
+ private editorClip = 0;
119
+ private submitting = false;
120
+ private submissionDraft = "";
121
+ private submitError = "";
122
+ private readonly markdownTheme: MarkdownTheme;
123
+ private markdownModeOverride: ViewerMarkdownMode | undefined;
124
+
125
+ get focused(): boolean { return this.editor.focused; }
126
+ set focused(value: boolean) { this.editor.focused = value; }
127
+ /**
128
+ * One `Markdown` per message, so its own text/width cache does the work. A
129
+ * fresh instance per render would re-parse the whole transcript on every
130
+ * keystroke — the component caches, but only across calls to the same object.
131
+ * Weak so a compacted-away message doesn't pin its render.
132
+ */
133
+ private markdownCache = new WeakMap<object, { md: Markdown; text: string; failed?: boolean }>();
134
+
135
+ constructor(
136
+ private tui: TUI,
137
+ private session: AgentSession,
138
+ private record: AgentRecord,
139
+ private activity: AgentActivity | undefined,
140
+ private theme: Theme,
141
+ private done: (result: undefined) => void,
142
+ /** Abort the agent shown here. Omitted → no stop affordance (e.g. read-only history). */
143
+ private onStop?: () => void,
144
+ /** User keybindings from `ctx.ui.custom()`. Omitted → hardcoded defaults. */
145
+ keybindings: KeybindingsManager = getKeybindings() as KeybindingsManager,
146
+ /** Resolves only after steering/resume acceptance. False or rejection retains the draft. */
147
+ private onSubmitMessage?: (message: string) => Promise<boolean>,
148
+ /**
149
+ * Whether the header shows an estimated cost after the token count. Read
150
+ * once, at construction: the overlay is opened from a menu, so the setting
151
+ * cannot change while it is on screen.
152
+ */
153
+ private showCost = false,
154
+ /**
155
+ * The current `viewerMarkdown` setting. Read live rather than captured,
156
+ * unlike `showCost`: Ctrl+R changes it while the overlay is on screen.
157
+ * Omitted → `assistant`.
158
+ */
159
+ private viewerMarkdown?: () => ViewerMarkdownMode,
160
+ /**
161
+ * Persist a mode chosen with Ctrl+R, so the shortcut and `/agents → Settings`
162
+ * mean the same thing. Omitted → Ctrl+R still cycles, viewer-locally.
163
+ */
164
+ private onMarkdownMode?: (mode: ViewerMarkdownMode) => void,
165
+ ) {
166
+ this.markdownTheme = resolveMarkdownTheme(theme);
167
+ this.transcript = new NativeTranscript(session, tui, this.markdownTheme);
168
+ this.scroll = new ScrollView(this.transcript, { follow: "end", scrollbar: "hidden", overscroll: "contain" });
169
+ this.editor = new CustomEditor(tui, {
170
+ borderColor: text => theme.fg("border", text),
171
+ selectList: {
172
+ selectedPrefix: text => theme.fg("accent", text), selectedText: text => theme.fg("accent", text),
173
+ description: text => theme.fg("muted", text), scrollInfo: text => theme.fg("dim", text), noMatch: text => theme.fg("dim", text),
174
+ },
175
+ }, keybindings);
176
+ this.editor.setText(drafts.get(session) ?? "");
177
+ this.editor.onChange = () => { drafts.set(session, this.editor.getExpandedText()); };
178
+ this.editor.onSubmit = () => { void this.submit(); };
179
+ this.editor.disableSubmit = !onSubmitMessage;
180
+ this.editor.onAction("app.tools.expand", () => { this.transcript.toggleExpanded(); });
181
+ // Deliberately no parent app actions, slash-command provider, or session replacement.
182
+ this.unsubscribe = session.subscribe(event => {
183
+ if (this.closed) return;
184
+ this.transcript.handleEvent(event);
185
+ this.tui.requestRender();
186
+ });
187
+ this.transcript.hydrate();
188
+ }
189
+
190
+ handleInput(data: string): void {
191
+ if (this.closed || isKeyRelease(data)) return;
192
+ if (matchesKey(data, "escape") || matchesKey(data, "ctrl+c")) {
193
+ this.dispose();
194
+ this.done(undefined);
195
+ return;
196
+ }
197
+ if (matchesKey(data, "ctrl+x")) {
198
+ if (this.isStoppable()) {
199
+ if (this.stopArmed) { this.stopArmed = false; this.onStop?.(); }
200
+ else this.stopArmed = true;
201
+ }
202
+ } else {
203
+ this.stopArmed = false;
204
+ if (matchesKey(data, "ctrl+r")) {
205
+ const next = MARKDOWN_MODES[(MARKDOWN_MODES.indexOf(this.markdownMode()) + 1) % MARKDOWN_MODES.length];
206
+ this.markdownModeOverride = next;
207
+ this.onMarkdownMode?.(next);
208
+ } else if (matchesKey(data, "pageUp") || matchesKey(data, "shift+up")) {
209
+ this.scroll.scrollBy(-Math.max(1, this.scroll.viewportHeight));
210
+ } else if (matchesKey(data, "pageDown") || matchesKey(data, "shift+down")) {
211
+ this.scroll.scrollBy(Math.max(1, this.scroll.viewportHeight));
212
+ } else if (matchesKey(data, "ctrl+shift+home")) {
213
+ this.scroll.scrollToStart();
214
+ } else if (matchesKey(data, "ctrl+shift+end")) {
215
+ this.scroll.scrollToEnd();
216
+ } else {
217
+ this.submissionDraft = this.editor.getExpandedText();
218
+ this.editor.handleInput(data);
219
+ }
220
+ }
221
+ this.tui.requestRender();
222
+ }
223
+
224
+ private async submit(): Promise<void> {
225
+ const draft = this.submissionDraft;
226
+ // Editor clears itself before onSubmit; restore until the lifecycle accepts it.
227
+ this.editor.setText(draft);
228
+ const message = draft.trim();
229
+ if (!message || !this.onSubmitMessage || this.submitting) return;
230
+ this.submitting = true;
231
+ this.editor.disableSubmit = true;
232
+ this.submitError = "";
233
+ try {
234
+ if (await this.onSubmitMessage(message) !== true) throw new Error("Child could not accept the message.");
235
+ if (drafts.get(this.session) === draft) drafts.delete(this.session);
236
+ if (!this.closed) {
237
+ this.editor.addToHistory(message);
238
+ if (this.editor.getExpandedText() === draft) this.editor.setText("");
239
+ }
240
+ } catch (error) {
241
+ this.submitError = `Not sent: ${error instanceof Error ? error.message : String(error)}`;
242
+ } finally {
243
+ this.submitting = false;
244
+ this.editor.disableSubmit = !this.onSubmitMessage;
245
+ if (!this.closed) this.tui.requestRender();
246
+ }
247
+ }
248
+
249
+ render(width: number): string[] {
250
+ const rows = Math.max(0, this.tui.terminal.rows);
251
+ if (width < 6 || rows === 0) return [];
252
+ const th = this.theme;
253
+ const innerW = width - 4;
254
+ const lines: string[] = [];
255
+
256
+ const pad = (s: string, len: number) => {
257
+ const vis = visibleWidth(s);
258
+ return s + " ".repeat(Math.max(0, len - vis));
259
+ };
260
+ const row = (content: string) =>
261
+ th.fg("border", "│") + " " + truncateToWidth(pad(content, innerW), innerW, "...", true) + " " + th.fg("border", "│");
262
+ const hrTop = th.fg("border", `╭${"─".repeat(width - 2)}╮`);
263
+ const hrBot = th.fg("border", `╰${"─".repeat(width - 2)}╯`);
264
+ const hrMid = row(th.fg("dim", "─".repeat(innerW)));
265
+
266
+ // Header
267
+ lines.push(hrTop);
268
+ const modeLabel = getPromptModeLabel(this.record.type);
269
+ const modeTag = modeLabel ? ` ${th.fg("dim", `(${modeLabel})`)}` : "";
270
+ const statusIcon = this.record.status === "running"
271
+ ? th.fg("accent", "●")
272
+ : this.record.status === "completed"
273
+ ? th.fg("success", "✓")
274
+ : this.record.status === "error"
275
+ ? th.fg("error", "✗")
276
+ : th.fg("dim", "○");
277
+ const duration = formatDuration(this.record.startedAt, this.record.completedAt);
278
+
279
+ const headerParts: string[] = [duration];
280
+ const toolUses = this.activity?.toolUses ?? this.record.toolUses;
281
+ if (toolUses > 0) headerParts.unshift(`${toolUses} tool${toolUses === 1 ? "" : "s"}`);
282
+ // Spend from the record, context from the live session: the record is the
283
+ // only total that survives the agent finishing and the only one carrying a
284
+ // nested child's spend.
285
+ const tokens = getLifetimeTotal(this.record.lifetimeUsage);
286
+ if (tokens > 0) {
287
+ const percent = getSessionContextPercent(this.activity?.session);
288
+ headerParts.push(formatSessionTokens(tokens, percent, th, this.record.compactionCount));
289
+ }
290
+ const cost = this.showCost ? formatCost(getLifetimeCost(this.record.lifetimeUsage)) : "";
291
+ if (cost) headerParts.push(cost);
292
+
293
+ lines.push(row(
294
+ `${statusIcon} ${renderAgentName(this.record.type, th, { bold: true })}${modeTag} ${th.fg("muted", this.record.description)} ${th.fg("dim", "·")} ${fgPreservingNestedStyles(th, "dim", headerParts.join(" · "))}`,
295
+ ));
296
+ const invocationLine = this.invocationLine();
297
+ if (invocationLine) lines.push(row(invocationLine));
298
+ lines.push(hrMid);
299
+
300
+ // Measure editor/chrome first; ScrollView supplies state, not clipping in an overlay.
301
+ lines.splice(Math.max(0, rows - 4));
302
+ const footerRows = rows >= 4 ? 2 : 0;
303
+ const available = rows - lines.length - footerRows;
304
+ const statusRows = available > 3 ? 1 : 0;
305
+ const editorLines = this.editor.render(innerW);
306
+ const editorHeight = Math.min(editorLines.length, Math.max(3, Math.floor(rows * 0.35)), available - statusRows);
307
+ const cursorLine = Math.max(0, editorLines.findIndex(line => line.includes(CURSOR_MARKER)));
308
+ this.editorClip = Math.max(0, Math.min(cursorLine, editorLines.length - editorHeight));
309
+ const viewportHeight = Math.max(0, available - statusRows - editorHeight);
310
+ const contentLines = this.markdownMode() === "assistant" ? this.transcript.render(innerW) : this.buildContentLines(innerW);
311
+ this.scroll.updateLayout(contentLines.length, viewportHeight, () => { if (!this.closed) this.tui.requestRender(); });
312
+ this.transcriptTop = lines.length;
313
+ const visible = contentLines.slice(this.scroll.scrollTop, this.scroll.scrollTop + viewportHeight);
314
+ for (let i = 0; i < viewportHeight; i++) lines.push(row(visible[i] ?? ""));
315
+ if (statusRows) {
316
+ const queued = (this.session.getSteeringMessages?.().length ?? 0) + (this.session.getFollowUpMessages?.().length ?? 0);
317
+ const action = !this.onSubmitMessage ? "Read only" : this.record.status === "running" || this.record.status === "queued" ? "Enter steer" : "Enter continue";
318
+ const stop = this.isStoppable() ? this.stopArmed ? " · Ctrl+X again to STOP" : " · Ctrl+X stop" : "";
319
+ lines.push(row(th.fg(this.submitError ? "error" : "dim", this.submitError || `${this.submitting ? "Sending…" : action}${queued ? ` · ${queued} queued` : ""}${stop}`)));
320
+ }
321
+ this.editorTop = lines.length;
322
+ lines.push(...editorLines.slice(this.editorClip, this.editorClip + editorHeight).map(row));
323
+ if (footerRows) {
324
+ lines.push(row(th.fg("dim", `Esc parent · Ctrl+R ${MARKDOWN_MODE_LABELS[this.markdownMode()]} · PgUp/Dn scroll · Ctrl+Shift+End tail`)));
325
+ lines.push(hrBot);
326
+ }
327
+ return lines.slice(0, rows);
328
+ }
329
+
330
+ handleMouse(event: TuiMouseEvent) {
331
+ if (this.closed) return undefined;
332
+ if (event.y >= this.transcriptTop && event.y < this.transcriptTop + this.scroll.viewportHeight) {
333
+ if (event.type === "wheel") {
334
+ this.scroll.scrollBy(event.wheelDelta ?? 0);
335
+ this.tui.requestRender();
336
+ return { handled: true };
337
+ }
338
+ if (this.markdownMode() === "assistant") {
339
+ return this.transcript.handleMouse({ ...event, y: event.y - this.transcriptTop + this.scroll.scrollTop, x: event.x - 2, width: event.width - 4 });
340
+ }
341
+ } else if (event.y >= this.editorTop && event.y < this.tui.terminal.rows - 2) {
342
+ return this.editor.handleMouse({ ...event, y: event.y - this.editorTop + this.editorClip, x: event.x - 2, width: event.width - 4 });
343
+ }
344
+ return undefined;
345
+ }
346
+
347
+ /** Stoppable only when a stop handler exists and the agent is still active. */
348
+ private isStoppable(): boolean {
349
+ return !!this.onStop && (this.record.status === "running" || this.record.status === "queued");
350
+ }
351
+
352
+ /** The mode in force: a Ctrl+R press, else the setting, else native cards. */
353
+ private markdownMode(): ViewerMarkdownMode {
354
+ return this.markdownModeOverride ?? this.viewerMarkdown?.() ?? "assistant";
355
+ }
356
+
357
+ /** Wrap `text` literally — the pre-Markdown path, and the fallback from it. */
358
+ private rawLines(text: string, width: number, dim: boolean): string[] {
359
+ const lines = wrapTextWithAnsi(text, width);
360
+ return dim ? lines.map(l => this.theme.fg("dim", l)) : lines;
361
+ }
362
+
363
+ /** Render `text` as Markdown, reusing this message's component instance. */
364
+ private markdownLines(msg: AgentSession["messages"][number], text: string, width: number, dim: boolean): string[] {
365
+ let entry = this.markdownCache.get(msg);
366
+ if (!entry) {
367
+ entry = {
368
+ md: new Markdown(
369
+ text,
370
+ 0,
371
+ 0,
372
+ this.markdownTheme,
373
+ // Keeps result prose visually receded, the way the raw path's
374
+ // per-line `fg("dim", …)` did. Fenced code is the exception and is
375
+ // left alone deliberately: pi's theme highlights it with its own
376
+ // colors, which this would otherwise flatten.
377
+ dim ? { color: (t: string) => this.theme.fg("dim", t) } : undefined,
378
+ MARKDOWN_OPTIONS,
379
+ ),
380
+ text,
381
+ };
382
+ this.markdownCache.set(msg, entry);
383
+ } else if (entry.text !== text) {
384
+ // Streaming: the message object is stable, its text grows. A failed
385
+ // prefix remains unsafe after append-only deltas, so retry only when the
386
+ // content was replaced or truncated.
387
+ const shouldRetry = !text.startsWith(entry.text);
388
+ entry.md.setText(text);
389
+ entry.text = text;
390
+ if (shouldRetry) entry.failed = false;
391
+ }
392
+ if (entry.failed) return this.rawLines(text, width, dim);
393
+
394
+ try {
395
+ return entry.md.render(width);
396
+ } catch {
397
+ // The parser is recursive and this is arbitrary tool output: ~54 nested
398
+ // blockquotes overflow the stack, and no amount of fuzzing proves that is
399
+ // the only such input. `render()` is on the TUI's critical path, so a
400
+ // throw here takes the overlay down for content the literal path shows
401
+ // fine — degrade to that instead, and remember, since the throw would
402
+ // otherwise repeat on every render and every scroll key.
403
+ entry.failed = true;
404
+ return this.rawLines(text, width, dim);
405
+ }
406
+ }
407
+
408
+ invalidate(): void {
409
+ this.transcript.invalidate();
410
+ this.editor.invalidate();
411
+ this.markdownCache = new WeakMap();
412
+ }
413
+
414
+ dispose(): void {
415
+ this.closed = true;
416
+ if (this.unsubscribe) {
417
+ this.unsubscribe();
418
+ this.unsubscribe = undefined;
419
+ }
420
+ }
421
+
422
+ // ---- Private ----
423
+
424
+ private invocationLine(): string | undefined {
425
+ // Canonical id here, short label everywhere else: this overlay is opened to
426
+ // inspect one agent and has the width for it, and two providers can serve
427
+ // models whose short names read alike.
428
+ const effective = this.session.model;
429
+ const invocation = effective ? {
430
+ ...this.record.invocation,
431
+ modelName: effective.name,
432
+ modelId: `${effective.provider}/${effective.id}`,
433
+ thinking: this.session.thinkingLevel ?? this.record.invocation?.thinking,
434
+ } : this.record.invocation;
435
+ const { modelName, modelId, tags } = buildInvocationTags(invocation);
436
+ const model = modelId ?? modelName;
437
+ const parts = model ? [model, ...tags] : tags;
438
+ if (parts.length === 0) return undefined;
439
+ return this.theme.fg("dim", ` ↳ ${parts.join(" · ")}`);
440
+ }
441
+
442
+ private buildContentLines(width: number): string[] {
443
+ if (width <= 0) return [];
444
+
445
+ const th = this.theme;
446
+ const messages = this.transcript.inspectionMessages();
447
+ const lines: string[] = [];
448
+
449
+ if (messages.length === 0) {
450
+ lines.push(th.fg("dim", "(waiting for first message...)"));
451
+ return lines;
452
+ }
453
+
454
+ const mode = this.markdownMode();
455
+ let needsSeparator = false;
456
+ for (const msg of messages) {
457
+ if (msg.role === "user") {
458
+ const text = typeof msg.content === "string"
459
+ ? msg.content
460
+ : extractText(msg.content);
461
+ if (!text.trim()) continue;
462
+ if (needsSeparator) lines.push(th.fg("dim", "───"));
463
+ lines.push(th.fg("accent", "[User]"));
464
+ for (const line of wrapTextWithAnsi(text.trim(), width)) {
465
+ lines.push(line);
466
+ }
467
+ } else if (msg.role === "assistant") {
468
+ const textParts: string[] = [];
469
+ const toolCalls: string[] = [];
470
+ for (const c of msg.content) {
471
+ if (c.type === "text" && c.text) textParts.push(c.text);
472
+ else if (c.type === "toolCall") {
473
+ toolCalls.push((c as any).name ?? (c as any).toolName ?? "unknown");
474
+ }
475
+ }
476
+ if (needsSeparator) lines.push(th.fg("dim", "───"));
477
+ lines.push(th.bold("[Assistant]"));
478
+ if (textParts.length > 0) {
479
+ const text = textParts.join("\n").trim();
480
+ lines.push(...(mode === "off"
481
+ ? this.rawLines(text, width, false)
482
+ : this.markdownLines(msg, text, width, false)));
483
+ }
484
+ for (const name of toolCalls) {
485
+ lines.push(truncateToWidth(th.fg("muted", ` [Tool: ${name}]`), width));
486
+ }
487
+ } else if (msg.role === "toolResult") {
488
+ const { text, elided } = capResult(extractText(msg.content).trim());
489
+ if (!text) continue;
490
+ if (needsSeparator) lines.push(th.fg("dim", "───"));
491
+ lines.push(th.fg("dim", "[Result]"));
492
+ lines.push(...(mode === "all"
493
+ ? this.markdownLines(msg, text, width, true)
494
+ : this.rawLines(text, width, true)));
495
+ const omitted = elided + (msg.viewerElided ?? 0);
496
+ if (omitted) lines.push(truncateToWidth(th.fg("dim", truncationNote(omitted)), width));
497
+ } else if ((msg as any).role === "bashExecution") {
498
+ const bash = msg as any;
499
+ if (needsSeparator) lines.push(th.fg("dim", "───"));
500
+ lines.push(truncateToWidth(th.fg("muted", ` $ ${bash.command}`), width));
501
+ if (bash.output?.trim()) {
502
+ // Same cap as a tool result, never Markdown: command output is the one
503
+ // thing here that is definitionally not authored as Markdown.
504
+ const { text, elided } = capResult(bash.output.trim());
505
+ lines.push(...this.rawLines(text, width, true));
506
+ if (elided) lines.push(truncateToWidth(th.fg("dim", truncationNote(elided)), width));
507
+ }
508
+ } else {
509
+ continue;
510
+ }
511
+ needsSeparator = true;
512
+ }
513
+
514
+ // Streaming indicator for running agents
515
+ if (this.record.status === "running" && this.activity) {
516
+ const act = describeActivity(this.activity.activeTools, this.activity.responseText);
517
+ lines.push("");
518
+ lines.push(truncateToWidth(th.fg("accent", "▍ ") + th.fg("dim", act), width));
519
+ }
520
+
521
+ return lines.map(l => truncateToWidth(l, width));
522
+ }
523
+ }