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