@asterxsk/kiln 0.1.0 → 0.2.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 (203) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +170 -170
  3. package/agent/AGENTS.md +67 -67
  4. package/agent/README.md +5 -5
  5. package/agent/extensions/AGENTS.md +68 -68
  6. package/agent/extensions/ask-user/index.ts +418 -418
  7. package/agent/extensions/ask-user/package-lock.json +769 -769
  8. package/agent/extensions/ask-user/package.json +19 -19
  9. package/agent/extensions/ask-user/prompt.ts +45 -45
  10. package/agent/extensions/ask-user/tsconfig.json +7 -7
  11. package/agent/extensions/background-terminals/docs/implementation-guide.md +942 -942
  12. package/agent/extensions/background-terminals/index.ts +627 -627
  13. package/agent/extensions/background-terminals/manager.test.ts +735 -735
  14. package/agent/extensions/background-terminals/output.test.ts +109 -109
  15. package/agent/extensions/background-terminals/package-lock.json +769 -769
  16. package/agent/extensions/background-terminals/package.json +17 -17
  17. package/agent/extensions/background-terminals/prompt.test.ts +125 -125
  18. package/agent/extensions/background-terminals/ps.test.ts +82 -82
  19. package/agent/extensions/background-terminals/result-delivery.test.ts +44 -44
  20. package/agent/extensions/background-terminals/src/domain.ts +87 -87
  21. package/agent/extensions/background-terminals/src/manager.ts +907 -907
  22. package/agent/extensions/background-terminals/src/output.ts +84 -84
  23. package/agent/extensions/background-terminals/src/prompt.ts +142 -142
  24. package/agent/extensions/background-terminals/src/result-delivery.ts +27 -27
  25. package/agent/extensions/background-terminals/src/runtime.ts +36 -36
  26. package/agent/extensions/background-terminals/src/ui/output-view.ts +79 -79
  27. package/agent/extensions/background-terminals/src/ui/ps.ts +621 -621
  28. package/agent/extensions/background-terminals/tsconfig.json +7 -7
  29. package/agent/extensions/file-search/index.spec.ts +443 -443
  30. package/agent/extensions/file-search/index.ts +459 -459
  31. package/agent/extensions/file-search/package-lock.json +2253 -2253
  32. package/agent/extensions/file-search/package.json +23 -23
  33. package/agent/extensions/file-search/src/args.ts +122 -122
  34. package/agent/extensions/file-search/src/binaries.ts +422 -422
  35. package/agent/extensions/file-search/src/output.ts +126 -126
  36. package/agent/extensions/file-search/src/process.ts +146 -146
  37. package/agent/extensions/file-search/src/prompt.ts +52 -52
  38. package/agent/extensions/file-search/tsconfig.json +7 -7
  39. package/agent/extensions/modelconf/PLAN.md +915 -915
  40. package/agent/extensions/modelconf/index.ts +296 -296
  41. package/agent/extensions/modelconf/src/ui/ModelConfView.ts +1101 -1101
  42. package/agent/extensions/pi-web-access/CHANGELOG.md +690 -690
  43. package/agent/extensions/pi-web-access/LICENSE +21 -21
  44. package/agent/extensions/pi-web-access/README.md +470 -470
  45. package/agent/extensions/pi-web-access/SECURITY.md +5 -5
  46. package/agent/extensions/pi-web-access/activity.ts +101 -101
  47. package/agent/extensions/pi-web-access/auth-fetch.ts +148 -148
  48. package/agent/extensions/pi-web-access/brightdata-unlocker.ts +272 -272
  49. package/agent/extensions/pi-web-access/chrome-cookies.ts +669 -669
  50. package/agent/extensions/pi-web-access/content-find.ts +139 -139
  51. package/agent/extensions/pi-web-access/credential-source.ts +191 -191
  52. package/agent/extensions/pi-web-access/data-uri-sanitize.ts +406 -406
  53. package/agent/extensions/pi-web-access/datalab-pdf-extract.ts +568 -568
  54. package/agent/extensions/pi-web-access/declared-web-links.ts +173 -173
  55. package/agent/extensions/pi-web-access/evidence/CONTRACT-EVIDENCE.md +496 -496
  56. package/agent/extensions/pi-web-access/evidence/contract-probe.mjs +140 -140
  57. package/agent/extensions/pi-web-access/exa.ts +526 -526
  58. package/agent/extensions/pi-web-access/extract.ts +1196 -1196
  59. package/agent/extensions/pi-web-access/feature-config.ts +29 -29
  60. package/agent/extensions/pi-web-access/fetch-params.ts +111 -111
  61. package/agent/extensions/pi-web-access/gemini-adc.ts +298 -298
  62. package/agent/extensions/pi-web-access/gemini-api.ts +353 -353
  63. package/agent/extensions/pi-web-access/gemini-pdf-extract.ts +108 -108
  64. package/agent/extensions/pi-web-access/gemini-url-context.ts +128 -128
  65. package/agent/extensions/pi-web-access/gemini-web-config.ts +101 -101
  66. package/agent/extensions/pi-web-access/gemini-web.ts +487 -487
  67. package/agent/extensions/pi-web-access/github-api.ts +197 -197
  68. package/agent/extensions/pi-web-access/github-extract.ts +746 -746
  69. package/agent/extensions/pi-web-access/github-issue-pr.ts +700 -700
  70. package/agent/extensions/pi-web-access/index.ts +1737 -1737
  71. package/agent/extensions/pi-web-access/package-lock.json +5808 -5808
  72. package/agent/extensions/pi-web-access/package.json +64 -64
  73. package/agent/extensions/pi-web-access/page-query.ts +96 -96
  74. package/agent/extensions/pi-web-access/pdf-extract.ts +409 -409
  75. package/agent/extensions/pi-web-access/promise-try.d.ts +7 -7
  76. package/agent/extensions/pi-web-access/query-rewrite.ts +51 -51
  77. package/agent/extensions/pi-web-access/render-search-error.ts +170 -170
  78. package/agent/extensions/pi-web-access/rsc-extract.ts +338 -338
  79. package/agent/extensions/pi-web-access/source-check.ts +282 -282
  80. package/agent/extensions/pi-web-access/ssrf-protection.ts +526 -526
  81. package/agent/extensions/pi-web-access/storage.ts +521 -521
  82. package/agent/extensions/pi-web-access/summary-model-scope.ts +125 -125
  83. package/agent/extensions/pi-web-access/test/auth-fetch.test.mjs +208 -208
  84. package/agent/extensions/pi-web-access/test/brightdata-unlocker.test.mjs +840 -840
  85. package/agent/extensions/pi-web-access/test/chrome-cookie-extraction.test.mjs +441 -441
  86. package/agent/extensions/pi-web-access/test/config-path.test.mjs +283 -283
  87. package/agent/extensions/pi-web-access/test/content-find.test.mjs +25 -25
  88. package/agent/extensions/pi-web-access/test/credential-source.test.mjs +118 -118
  89. package/agent/extensions/pi-web-access/test/data-uri-sanitize.test.mjs +210 -210
  90. package/agent/extensions/pi-web-access/test/datalab-pdf-extract.test.mjs +552 -552
  91. package/agent/extensions/pi-web-access/test/declared-web-links.test.mjs +212 -212
  92. package/agent/extensions/pi-web-access/test/fetch-answer-storage.test.mjs +40 -40
  93. package/agent/extensions/pi-web-access/test/fetch-cache-storage.test.mjs +334 -334
  94. package/agent/extensions/pi-web-access/test/fetch-content-domain-policy.test.mjs +95 -95
  95. package/agent/extensions/pi-web-access/test/fetch-modes.test.mjs +53 -53
  96. package/agent/extensions/pi-web-access/test/fetch-not-found-guidance.test.mjs +92 -92
  97. package/agent/extensions/pi-web-access/test/fetch-params.test.mjs +86 -86
  98. package/agent/extensions/pi-web-access/test/fetch-render-call.test.mjs +34 -34
  99. package/agent/extensions/pi-web-access/test/fetch-routing.test.mjs +173 -173
  100. package/agent/extensions/pi-web-access/test/gemini-adc-auth.test.mjs +257 -257
  101. package/agent/extensions/pi-web-access/test/gemini-api-transport.test.mjs +170 -170
  102. package/agent/extensions/pi-web-access/test/gemini-pdf-extract.test.mjs +133 -133
  103. package/agent/extensions/pi-web-access/test/gemini-web-cookie-opt-in.test.mjs +178 -178
  104. package/agent/extensions/pi-web-access/test/gemini-web-header-overflow.test.mjs +148 -148
  105. package/agent/extensions/pi-web-access/test/get-search-content.test.mjs +223 -223
  106. package/agent/extensions/pi-web-access/test/github-extract.test.mjs +378 -378
  107. package/agent/extensions/pi-web-access/test/github-issue-pr.test.mjs +565 -565
  108. package/agent/extensions/pi-web-access/test/inline-content-config.test.mjs +99 -99
  109. package/agent/extensions/pi-web-access/test/lazy-extract-load.test.mjs +118 -118
  110. package/agent/extensions/pi-web-access/test/local-video-oversize.test.mjs +52 -52
  111. package/agent/extensions/pi-web-access/test/package-typebox-dependency.test.mjs +50 -50
  112. package/agent/extensions/pi-web-access/test/page-query.test.mjs +51 -51
  113. package/agent/extensions/pi-web-access/test/pdf-config.test.mjs +140 -140
  114. package/agent/extensions/pi-web-access/test/pdf-extract.test.mjs +500 -500
  115. package/agent/extensions/pi-web-access/test/proxy-transport.test.mjs +286 -286
  116. package/agent/extensions/pi-web-access/test/query-rewrite.test.mjs +52 -52
  117. package/agent/extensions/pi-web-access/test/rsc-fallback.test.mjs +102 -102
  118. package/agent/extensions/pi-web-access/test/search-error-render.test.mjs +152 -152
  119. package/agent/extensions/pi-web-access/test/search-providers.test.mjs +274 -274
  120. package/agent/extensions/pi-web-access/test/source-check.test.mjs +179 -179
  121. package/agent/extensions/pi-web-access/test/ssrf-allow-ranges-config.test.mjs +205 -205
  122. package/agent/extensions/pi-web-access/test/ssrf-protection.test.mjs +456 -456
  123. package/agent/extensions/pi-web-access/test/tool-registration-config.test.mjs +182 -182
  124. package/agent/extensions/pi-web-access/test/youtube-extract-errors.test.mjs +64 -64
  125. package/agent/extensions/pi-web-access/tsconfig.json +11 -11
  126. package/agent/extensions/pi-web-access/utils.ts +451 -451
  127. package/agent/extensions/pi-web-access/video-extract.ts +392 -392
  128. package/agent/extensions/pi-web-access/youtube-extract.ts +328 -328
  129. package/agent/extensions/shared/activity-status.ts +31 -31
  130. package/agent/extensions/shared/child-session.test.ts +270 -270
  131. package/agent/extensions/shared/child-session.ts +148 -148
  132. package/agent/extensions/shared/context-utilization.test.ts +48 -48
  133. package/agent/extensions/shared/context-utilization.ts +47 -47
  134. package/agent/extensions/shared/dashboard-state.ts +99 -99
  135. package/agent/extensions/shared/tool-call-timeout.test.ts +117 -117
  136. package/agent/extensions/shared/tool-call-timeout.ts +104 -104
  137. package/agent/extensions/subagents/by-the-way.test.ts +29 -29
  138. package/agent/extensions/subagents/claude.test.ts +119 -119
  139. package/agent/extensions/subagents/codex.test.ts +102 -102
  140. package/agent/extensions/subagents/context-usage.test.ts +107 -107
  141. package/agent/extensions/subagents/docs/design-plan.md +568 -568
  142. package/agent/extensions/subagents/docs/effect-v4-extension-guide.md +354 -354
  143. package/agent/extensions/subagents/docs/effect-v4-notes.md +571 -571
  144. package/agent/extensions/subagents/index.ts +779 -779
  145. package/agent/extensions/subagents/manager.test.ts +276 -276
  146. package/agent/extensions/subagents/package-lock.json +2244 -2244
  147. package/agent/extensions/subagents/package.json +19 -19
  148. package/agent/extensions/subagents/result-delivery.test.ts +27 -27
  149. package/agent/extensions/subagents/src/backend.ts +73 -73
  150. package/agent/extensions/subagents/src/backends/claude.ts +701 -701
  151. package/agent/extensions/subagents/src/backends/codex.ts +1060 -1060
  152. package/agent/extensions/subagents/src/backends/pi.ts +575 -575
  153. package/agent/extensions/subagents/src/backends/stub.ts +300 -300
  154. package/agent/extensions/subagents/src/by-the-way.ts +21 -21
  155. package/agent/extensions/subagents/src/domain.ts +253 -253
  156. package/agent/extensions/subagents/src/format.ts +74 -74
  157. package/agent/extensions/subagents/src/manager.ts +736 -736
  158. package/agent/extensions/subagents/src/prompt.ts +92 -92
  159. package/agent/extensions/subagents/src/result-delivery.ts +20 -20
  160. package/agent/extensions/subagents/src/runtime.ts +53 -53
  161. package/agent/extensions/subagents/src/ui/takeover.ts +583 -583
  162. package/agent/extensions/subagents/src/ui/transcript.ts +201 -201
  163. package/agent/extensions/subagents/takeover.test.ts +29 -29
  164. package/agent/extensions/subagents/tsconfig.json +7 -7
  165. package/agent/extensions/todo/AGENTS.md +38 -38
  166. package/agent/extensions/todo/LICENSE +21 -21
  167. package/agent/extensions/todo/config.ts +55 -55
  168. package/agent/extensions/todo/index.ts +151 -151
  169. package/agent/extensions/todo/locales/de.json +17 -17
  170. package/agent/extensions/todo/locales/en.json +15 -15
  171. package/agent/extensions/todo/locales/es.json +17 -17
  172. package/agent/extensions/todo/locales/fr.json +17 -17
  173. package/agent/extensions/todo/locales/pt-BR.json +17 -17
  174. package/agent/extensions/todo/locales/pt.json +17 -17
  175. package/agent/extensions/todo/locales/ru.json +17 -17
  176. package/agent/extensions/todo/locales/uk.json +17 -17
  177. package/agent/extensions/todo/locales/zh.json +17 -17
  178. package/agent/extensions/todo/package-lock.json +3358 -3358
  179. package/agent/extensions/todo/package.json +67 -67
  180. package/agent/extensions/todo/state/i18n-bridge.ts +64 -64
  181. package/agent/extensions/todo/state/invariants.ts +20 -20
  182. package/agent/extensions/todo/state/replay.ts +38 -38
  183. package/agent/extensions/todo/state/selectors.ts +107 -107
  184. package/agent/extensions/todo/state/state-reducer.ts +326 -326
  185. package/agent/extensions/todo/state/state.ts +18 -18
  186. package/agent/extensions/todo/state/store.ts +82 -82
  187. package/agent/extensions/todo/state/task-graph.ts +57 -57
  188. package/agent/extensions/todo/todo-overlay.ts +200 -200
  189. package/agent/extensions/todo/todo.ts +155 -155
  190. package/agent/extensions/todo/tool/response-envelope.ts +109 -109
  191. package/agent/extensions/todo/tool/types.ts +206 -206
  192. package/agent/extensions/todo/view/format.ts +177 -177
  193. package/agent/install.ps1 +637 -527
  194. package/agent/install.sh +620 -511
  195. package/agent/keybindings.json +7 -7
  196. package/bin/kiln.js +124 -11
  197. package/package.json +8 -2
  198. package/agent/extensions/taste/index.ts +0 -443
  199. package/agent/extensions/taste/install.ps1 +0 -23
  200. package/agent/extensions/taste/install.sh +0 -21
  201. /package/agent/extensions/{status line → statusline}/index.ts +0 -0
  202. /package/agent/extensions/{status line → statusline}/install.ps1 +0 -0
  203. /package/agent/extensions/{status line → statusline}/install.sh +0 -0
@@ -1,583 +1,583 @@
1
- /**
2
- * Takeover UI for subagents (ported from v1, rendering from the synchronous
3
- * SubagentReadModel instead of live pi sessions):
4
- * - SubagentDashboard: full popup (overlay) listing all subagents.
5
- * - TakeoverView: full interactive view of one subagent with an input line
6
- * to steer/continue it.
7
- */
8
-
9
- import type {
10
- ExtensionCommandContext,
11
- KeybindingsManager,
12
- Theme,
13
- } from "@earendil-works/pi-coding-agent";
14
- import type { Component, Focusable, TUI } from "@earendil-works/pi-tui";
15
- import { Input, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
16
- import { formatElapsed, type SubagentSnapshot } from "../domain.ts";
17
- import { formatContextUtilization } from "../format.ts";
18
- import type { SubagentReadModel } from "../manager.ts";
19
- import { buildTranscriptLines } from "./transcript.ts";
20
-
21
- function configuredKeys(
22
- keybindings: KeybindingsManager,
23
- binding: Parameters<KeybindingsManager["getKeys"]>[0],
24
- ) {
25
- return keybindings.getKeys(binding).join("/") || "unbound";
26
- }
27
-
28
- function statusGlyph(snap: SubagentSnapshot, theme: Theme): string {
29
- switch (snap.status) {
30
- case "running":
31
- return theme.fg("warning", "■");
32
- case "done":
33
- return theme.fg("success", "■");
34
- case "error":
35
- return theme.fg("error", "■");
36
- }
37
- }
38
-
39
- function statusWord(snap: SubagentSnapshot, theme: Theme): string {
40
- switch (snap.status) {
41
- case "running":
42
- return theme.fg("warning", "running");
43
- case "done":
44
- return theme.fg("success", "done");
45
- case "error":
46
- return theme.fg("error", "failed");
47
- }
48
- }
49
-
50
- // --- Entry points --------------------------------------------------------------
51
-
52
- export interface TakeoverOptions {
53
- readonly badge?: string;
54
- }
55
-
56
- export async function openSubagentTakeover(
57
- ctx: ExtensionCommandContext,
58
- view: SubagentReadModel,
59
- id: string,
60
- options?: TakeoverOptions,
61
- ) {
62
- if (!view.get(id)) return;
63
- await ctx.ui.custom<null>(
64
- (tui, theme, keybindings, done) =>
65
- new TakeoverView(tui, theme, keybindings, id, view, done, options),
66
- {
67
- overlay: true,
68
- overlayOptions: { anchor: "center", width: "100%", maxHeight: "100%" },
69
- },
70
- );
71
- }
72
-
73
- export async function openSubagentPicker(
74
- ctx: ExtensionCommandContext,
75
- view: SubagentReadModel,
76
- ) {
77
- const selection: DashboardSelection = { index: 0 };
78
-
79
- while (true) {
80
- if (view.size() === 0) {
81
- ctx.ui.notify("No subagents", "info");
82
- return;
83
- }
84
-
85
- const picked = await ctx.ui.custom<string | null>(
86
- (tui, theme, keybindings, done) =>
87
- new SubagentDashboard(tui, theme, keybindings, view, selection, done),
88
- {
89
- overlay: true,
90
- overlayOptions: { anchor: "center", width: "100%", maxHeight: "100%" },
91
- },
92
- );
93
-
94
- if (!picked) return;
95
- if (!view.get(picked)) continue;
96
-
97
- await openSubagentTakeover(ctx, view, picked);
98
- // After leaving the takeover view, fall back to the dashboard.
99
- }
100
- }
101
-
102
- // --- Dashboard (fullscreen overlay) ----------------------------------------------
103
-
104
- export interface DashboardSelection {
105
- id?: string;
106
- index: number;
107
- }
108
-
109
- export function reconcileDashboardSelection(
110
- selection: DashboardSelection,
111
- subs: ReadonlyArray<Pick<SubagentSnapshot, "id">>,
112
- ) {
113
- const stableIndex = selection.id
114
- ? subs.findIndex((snap) => snap.id === selection.id)
115
- : -1;
116
- selection.index =
117
- stableIndex >= 0
118
- ? stableIndex
119
- : Math.min(Math.max(0, selection.index), Math.max(0, subs.length - 1));
120
- selection.id = subs[selection.index]?.id;
121
- }
122
-
123
- class SubagentDashboard implements Component {
124
- private tui: TUI;
125
- private theme: Theme;
126
- private keybindings: KeybindingsManager;
127
- private view: SubagentReadModel;
128
- private selection: DashboardSelection;
129
- private done: (value: string | null) => void;
130
-
131
- private closed = false;
132
- private ticker: ReturnType<typeof setInterval>;
133
- private unsubChange: () => void;
134
-
135
- constructor(
136
- tui: TUI,
137
- theme: Theme,
138
- keybindings: KeybindingsManager,
139
- view: SubagentReadModel,
140
- selection: DashboardSelection,
141
- done: (value: string | null) => void,
142
- ) {
143
- this.tui = tui;
144
- this.theme = theme;
145
- this.keybindings = keybindings;
146
- this.view = view;
147
- this.selection = selection;
148
- this.done = done;
149
- // Elapsed times, token counts, and statuses tick along at 1Hz.
150
- this.ticker = setInterval(() => this.tui.requestRender(), 1000);
151
- this.unsubChange = view.subscribe(() => this.tui.requestRender());
152
- }
153
-
154
- private subs(): ReadonlyArray<SubagentSnapshot> {
155
- return this.view.list();
156
- }
157
-
158
- private cleanup() {
159
- if (this.closed) return false;
160
- this.closed = true;
161
- clearInterval(this.ticker);
162
- this.unsubChange();
163
- return true;
164
- }
165
-
166
- private close(result: string | null) {
167
- if (this.cleanup()) this.done(result);
168
- }
169
-
170
- dispose(): void {
171
- this.cleanup();
172
- }
173
-
174
- handleInput(data: string): void {
175
- const subs = this.subs();
176
- reconcileDashboardSelection(this.selection, subs);
177
-
178
- if (this.keybindings.matches(data, "tui.select.cancel")) {
179
- this.close(null);
180
- return;
181
- }
182
- if (this.keybindings.matches(data, "tui.select.confirm")) {
183
- const snap = subs[this.selection.index];
184
- if (snap) this.close(snap.id);
185
- return;
186
- }
187
- if (this.keybindings.matches(data, "tui.select.up") || data === "k") {
188
- if (subs.length > 0) {
189
- this.selection.index =
190
- (this.selection.index - 1 + subs.length) % subs.length;
191
- this.selection.id = subs[this.selection.index]?.id;
192
- this.tui.requestRender();
193
- }
194
- return;
195
- }
196
- if (this.keybindings.matches(data, "tui.select.down") || data === "j") {
197
- if (subs.length > 0) {
198
- this.selection.index = (this.selection.index + 1) % subs.length;
199
- this.selection.id = subs[this.selection.index]?.id;
200
- this.tui.requestRender();
201
- }
202
- return;
203
- }
204
- if (data === "x") {
205
- const snap = subs[this.selection.index];
206
- if (snap && snap.status === "running") this.view.requestAbort(snap.id);
207
- return;
208
- }
209
- }
210
-
211
- private pad(text: string, width: number): string {
212
- const truncated = truncateToWidth(text, width);
213
- return truncated + " ".repeat(Math.max(0, width - visibleWidth(truncated)));
214
- }
215
-
216
- private borderSegment(width: number, title: string): string {
217
- const theme = this.theme;
218
- const label = title
219
- ? ` ${truncateToWidth(title, Math.max(0, width - 3))} `
220
- : "";
221
- const labelWidth = visibleWidth(label);
222
- return (
223
- theme.fg("border", "─") +
224
- (label ? theme.fg("text", label) : "") +
225
- theme.fg("border", "─".repeat(Math.max(0, width - 1 - labelWidth)))
226
- );
227
- }
228
-
229
- render(width: number): string[] {
230
- const theme = this.theme;
231
- const subs = this.subs();
232
- reconcileDashboardSelection(this.selection, subs);
233
-
234
- const rows = this.tui.terminal.rows || 30;
235
- // Render exactly terminal rows - 1 so the overlay covers the header,
236
- // chat, editor, and extra footer lines while leaving pi's final footer
237
- // row visible.
238
- const bodyHeight = Math.max(6, rows - 5);
239
- const innerWidth = width - 2;
240
-
241
- const lines: string[] = [];
242
-
243
- // Header: title left, count right
244
- const headerLeft = theme.fg("accent", theme.bold("Subagents"));
245
- const headerRight = theme.fg(
246
- "muted",
247
- `${subs.length} agent${subs.length === 1 ? "" : "s"}`,
248
- );
249
- const headerPad = Math.max(
250
- 1,
251
- width - visibleWidth(headerLeft) - visibleWidth(headerRight) - 4,
252
- );
253
- lines.push(
254
- truncateToWidth(
255
- ` ${headerLeft}${" ".repeat(headerPad)}${headerRight} `,
256
- width,
257
- ),
258
- );
259
-
260
- // Top border with panel title
261
- const settled = subs.filter((s) => s.status !== "running").length;
262
- lines.push(
263
- theme.fg("border", "╭") +
264
- this.borderSegment(innerWidth, `agents · ${settled}/${subs.length}`) +
265
- theme.fg("border", "╮"),
266
- );
267
-
268
- // Rows
269
- const divider = theme.fg("border", "│");
270
- const rowLines = this.renderRows(subs, innerWidth, bodyHeight);
271
- for (let i = 0; i < bodyHeight; i++) {
272
- lines.push(divider + this.pad(rowLines[i] ?? "", innerWidth) + divider);
273
- }
274
-
275
- // Bottom border
276
- lines.push(
277
- theme.fg("border", "╰") +
278
- theme.fg("border", "─".repeat(innerWidth)) +
279
- theme.fg("border", "╯"),
280
- );
281
-
282
- // Hints
283
- lines.push(
284
- truncateToWidth(
285
- theme.fg(
286
- "dim",
287
- ` ${configuredKeys(this.keybindings, "tui.select.up")}/${configuredKeys(this.keybindings, "tui.select.down")}/jk select · ${configuredKeys(this.keybindings, "tui.select.confirm")} take over · x abort · ${configuredKeys(this.keybindings, "tui.select.cancel")} close`,
288
- ),
289
- width,
290
- ),
291
- );
292
-
293
- return lines;
294
- }
295
-
296
- private renderRows(
297
- subs: ReadonlyArray<SubagentSnapshot>,
298
- width: number,
299
- height: number,
300
- ): string[] {
301
- const theme = this.theme;
302
- const out: string[] = [];
303
-
304
- // Scroll window around selection
305
- let start = 0;
306
- if (subs.length > height) {
307
- start = Math.min(
308
- Math.max(0, this.selection.index - Math.floor(height / 2)),
309
- subs.length - height,
310
- );
311
- }
312
- const visible = subs.slice(start, start + height);
313
-
314
- for (let i = 0; i < visible.length; i++) {
315
- const snap = visible[i];
316
- const index = start + i;
317
- const isSelected = index === this.selection.index;
318
-
319
- // Left: marker, status square, title, dim id
320
- const marker = isSelected ? theme.fg("accent", "❯") : " ";
321
- const title = isSelected
322
- ? theme.fg("accent", snap.title)
323
- : theme.fg("text", snap.title);
324
- const left = ` ${marker} ${statusGlyph(snap, theme)} ${title} ${theme.fg("dim", snap.id)}`;
325
-
326
- // Right: backend · model · context utilization · elapsed · status
327
- const utilization = formatContextUtilization(snap.usage);
328
- const dot = theme.fg("dim", " · ");
329
- const rightParts = [
330
- theme.fg("muted", snap.backend),
331
- theme.fg("muted", snap.meta.modelLabel ?? "?"),
332
- ...(utilization ? [theme.fg("muted", utilization)] : []),
333
- theme.fg("muted", formatElapsed(snap)),
334
- statusWord(snap, theme),
335
- ];
336
- const right = `${rightParts.join(dot)} `;
337
-
338
- const rightWidth = visibleWidth(right);
339
- const leftMax = Math.max(0, width - rightWidth - 2);
340
- const leftTruncated = truncateToWidth(left, leftMax);
341
- const gap = Math.max(2, width - visibleWidth(leftTruncated) - rightWidth);
342
- out.push(truncateToWidth(leftTruncated + " ".repeat(gap) + right, width));
343
- }
344
-
345
- if (start > 0) {
346
- out[0] = truncateToWidth(theme.fg("dim", ` ... ${start} more`), width);
347
- }
348
- if (start + height < subs.length) {
349
- out[out.length - 1] = truncateToWidth(
350
- theme.fg("dim", ` ... ${subs.length - start - height} more`),
351
- width,
352
- );
353
- }
354
- return out;
355
- }
356
-
357
- invalidate(): void {}
358
- }
359
-
360
- // --- Takeover view ------------------------------------------------------------
361
-
362
- const TRANSCRIPT_SCROLL_STEP = 6;
363
-
364
- class TakeoverView implements Component, Focusable {
365
- private tui: TUI;
366
- private theme: Theme;
367
- private keybindings: KeybindingsManager;
368
- private id: string;
369
- private view: SubagentReadModel;
370
- private done: (value: null) => void;
371
- private options?: TakeoverOptions;
372
-
373
- private input = new Input();
374
- /** Scroll offset in lines from the bottom of the transcript. 0 = pinned to bottom. */
375
- private scrollOffset = 0;
376
- private unsubscribe: () => void;
377
- private renderTimer?: ReturnType<typeof setTimeout>;
378
- private ticker: ReturnType<typeof setInterval>;
379
- private closed = false;
380
-
381
- private _focused = false;
382
- get focused(): boolean {
383
- return this._focused;
384
- }
385
- set focused(value: boolean) {
386
- this._focused = value;
387
- this.input.focused = value;
388
- }
389
-
390
- constructor(
391
- tui: TUI,
392
- theme: Theme,
393
- keybindings: KeybindingsManager,
394
- id: string,
395
- view: SubagentReadModel,
396
- done: (value: null) => void,
397
- options?: TakeoverOptions,
398
- ) {
399
- this.tui = tui;
400
- this.theme = theme;
401
- this.keybindings = keybindings;
402
- this.id = id;
403
- this.view = view;
404
- this.done = done;
405
- this.options = options;
406
- this.unsubscribe = view.subscribeTo(id, () => this.scheduleRender());
407
- // Elapsed time in the header ticks along at 1Hz.
408
- this.ticker = setInterval(() => this.tui.requestRender(), 1000);
409
- this.input.onSubmit = (value: string) => {
410
- const text = value.trim();
411
- if (!text) return;
412
- this.input.setValue("");
413
- this.view.requestSend(this.id, text);
414
- this.scrollOffset = 0;
415
- this.tui.requestRender();
416
- };
417
- }
418
-
419
- private snap(): SubagentSnapshot | undefined {
420
- return this.view.get(this.id);
421
- }
422
-
423
- private scheduleRender() {
424
- if (this.renderTimer) return;
425
- // Streaming can emit an event per token. Limit terminal repaints so this
426
- // view cannot starve input handling or make the child look frozen.
427
- this.renderTimer = setTimeout(() => {
428
- this.renderTimer = undefined;
429
- if (!this.closed) this.tui.requestRender();
430
- }, 50);
431
- }
432
-
433
- private cleanup() {
434
- if (this.closed) return false;
435
- this.closed = true;
436
- this.unsubscribe();
437
- clearInterval(this.ticker);
438
- if (this.renderTimer) clearTimeout(this.renderTimer);
439
- this.renderTimer = undefined;
440
- return true;
441
- }
442
-
443
- private close() {
444
- if (this.cleanup()) this.done(null);
445
- }
446
-
447
- dispose(): void {
448
- this.cleanup();
449
- }
450
-
451
- handleInput(data: string): void {
452
- if (this.keybindings.matches(data, "app.clear")) {
453
- const snap = this.snap();
454
- if (snap?.status === "running") this.view.requestAbort(this.id);
455
- return;
456
- }
457
- if (
458
- this.keybindings.matches(data, "app.interrupt") ||
459
- this.keybindings.matches(data, "tui.select.cancel")
460
- ) {
461
- this.close();
462
- return;
463
- }
464
- if (this.keybindings.matches(data, "tui.editor.cursorUp")) {
465
- this.scrollOffset += TRANSCRIPT_SCROLL_STEP;
466
- this.tui.requestRender();
467
- return;
468
- }
469
- if (this.keybindings.matches(data, "tui.editor.cursorDown")) {
470
- this.scrollOffset = Math.max(
471
- 0,
472
- this.scrollOffset - TRANSCRIPT_SCROLL_STEP,
473
- );
474
- this.tui.requestRender();
475
- return;
476
- }
477
- if (this.keybindings.matches(data, "tui.editor.pageUp")) {
478
- this.scrollOffset += this.viewportHeight();
479
- this.tui.requestRender();
480
- return;
481
- }
482
- if (this.keybindings.matches(data, "tui.editor.pageDown")) {
483
- this.scrollOffset = Math.max(
484
- 0,
485
- this.scrollOffset - this.viewportHeight(),
486
- );
487
- this.tui.requestRender();
488
- return;
489
- }
490
- this.input.handleInput(data);
491
- this.tui.requestRender();
492
- }
493
-
494
- private viewportHeight(): number {
495
- const rows = this.tui.terminal.rows || 30;
496
- // The complete view renders viewport + 7 chrome rows. Using rows - 8
497
- // makes the overlay exactly terminal rows - 1.
498
- return Math.max(6, rows - 8);
499
- }
500
-
501
- render(width: number): string[] {
502
- const theme = this.theme;
503
- const border = theme.fg("borderAccent", "─".repeat(Math.max(1, width)));
504
- const lines: string[] = [];
505
- const snap = this.snap();
506
-
507
- if (!snap) {
508
- lines.push(border);
509
- lines.push(theme.fg("dim", `${this.id} is no longer tracked`));
510
- lines.push(border);
511
- return lines;
512
- }
513
-
514
- lines.push(border);
515
- const utilization = formatContextUtilization(snap.usage);
516
- const header =
517
- `${statusGlyph(snap, theme)} ` +
518
- theme.fg("accent", theme.bold(`${snap.id} · ${snap.title}`)) +
519
- theme.fg("muted", ` · ${snap.status} · ${formatElapsed(snap)}`) +
520
- (this.options?.badge
521
- ? theme.fg("muted", ` · ${this.options.badge}`)
522
- : "") +
523
- theme.fg("dim", ` · ${snap.backend}: ${snap.meta.modelLabel ?? "?"}`) +
524
- (utilization ? theme.fg("dim", ` · ${utilization}`) : "");
525
- lines.push(truncateToWidth(header, width));
526
- lines.push(border);
527
-
528
- // Fixed-height transcript viewport. Error and scroll status consume rows
529
- // inside the viewport so streaming/scrolling never changes overlay height.
530
- const transcript = buildTranscriptLines(snap, width, theme);
531
- const viewport = this.viewportHeight();
532
- const errorRows = snap.errorText ? 1 : 0;
533
- const scrollRows = this.scrollOffset > 0 ? 1 : 0;
534
- const transcriptCapacity = Math.max(1, viewport - errorRows - scrollRows);
535
- const maxOffset = Math.max(0, transcript.length - transcriptCapacity);
536
- if (this.scrollOffset > maxOffset) this.scrollOffset = maxOffset;
537
-
538
- const body: string[] = [];
539
- if (snap.errorText) {
540
- body.push(
541
- truncateToWidth(theme.fg("error", `error: ${snap.errorText}`), width),
542
- );
543
- }
544
-
545
- const capacity = Math.max(
546
- 1,
547
- viewport - body.length - (this.scrollOffset > 0 ? 1 : 0),
548
- );
549
- const end = transcript.length - this.scrollOffset;
550
- const visible = transcript.slice(Math.max(0, end - capacity), end);
551
- if (visible.length === 0) body.push(theme.fg("dim", "(no output yet)"));
552
- else body.push(...visible);
553
-
554
- if (this.scrollOffset > 0) {
555
- body.push(
556
- truncateToWidth(
557
- theme.fg("dim", `... ${this.scrollOffset} lines below · ↓/pgdn`),
558
- width,
559
- ),
560
- );
561
- }
562
- while (body.length < viewport) body.push("");
563
- lines.push(...body.slice(0, viewport));
564
-
565
- lines.push(border);
566
- lines.push(...this.input.render(width));
567
- lines.push(
568
- truncateToWidth(
569
- theme.fg(
570
- "dim",
571
- `${configuredKeys(this.keybindings, "tui.input.submit")} send · ${configuredKeys(this.keybindings, "app.interrupt")} back · ${configuredKeys(this.keybindings, "app.clear")} abort run · ${configuredKeys(this.keybindings, "tui.editor.cursorUp")}/${configuredKeys(this.keybindings, "tui.editor.cursorDown")} scroll · ${configuredKeys(this.keybindings, "tui.editor.pageUp")}/${configuredKeys(this.keybindings, "tui.editor.pageDown")} page`,
572
- ),
573
- width,
574
- ),
575
- );
576
- lines.push(border);
577
- return lines;
578
- }
579
-
580
- invalidate(): void {
581
- this.input.invalidate();
582
- }
583
- }
1
+ /**
2
+ * Takeover UI for subagents (ported from v1, rendering from the synchronous
3
+ * SubagentReadModel instead of live pi sessions):
4
+ * - SubagentDashboard: full popup (overlay) listing all subagents.
5
+ * - TakeoverView: full interactive view of one subagent with an input line
6
+ * to steer/continue it.
7
+ */
8
+
9
+ import type {
10
+ ExtensionCommandContext,
11
+ KeybindingsManager,
12
+ Theme,
13
+ } from "@earendil-works/pi-coding-agent";
14
+ import type { Component, Focusable, TUI } from "@earendil-works/pi-tui";
15
+ import { Input, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
16
+ import { formatElapsed, type SubagentSnapshot } from "../domain.ts";
17
+ import { formatContextUtilization } from "../format.ts";
18
+ import type { SubagentReadModel } from "../manager.ts";
19
+ import { buildTranscriptLines } from "./transcript.ts";
20
+
21
+ function configuredKeys(
22
+ keybindings: KeybindingsManager,
23
+ binding: Parameters<KeybindingsManager["getKeys"]>[0],
24
+ ) {
25
+ return keybindings.getKeys(binding).join("/") || "unbound";
26
+ }
27
+
28
+ function statusGlyph(snap: SubagentSnapshot, theme: Theme): string {
29
+ switch (snap.status) {
30
+ case "running":
31
+ return theme.fg("warning", "■");
32
+ case "done":
33
+ return theme.fg("success", "■");
34
+ case "error":
35
+ return theme.fg("error", "■");
36
+ }
37
+ }
38
+
39
+ function statusWord(snap: SubagentSnapshot, theme: Theme): string {
40
+ switch (snap.status) {
41
+ case "running":
42
+ return theme.fg("warning", "running");
43
+ case "done":
44
+ return theme.fg("success", "done");
45
+ case "error":
46
+ return theme.fg("error", "failed");
47
+ }
48
+ }
49
+
50
+ // --- Entry points --------------------------------------------------------------
51
+
52
+ export interface TakeoverOptions {
53
+ readonly badge?: string;
54
+ }
55
+
56
+ export async function openSubagentTakeover(
57
+ ctx: ExtensionCommandContext,
58
+ view: SubagentReadModel,
59
+ id: string,
60
+ options?: TakeoverOptions,
61
+ ) {
62
+ if (!view.get(id)) return;
63
+ await ctx.ui.custom<null>(
64
+ (tui, theme, keybindings, done) =>
65
+ new TakeoverView(tui, theme, keybindings, id, view, done, options),
66
+ {
67
+ overlay: true,
68
+ overlayOptions: { anchor: "center", width: "100%", maxHeight: "100%" },
69
+ },
70
+ );
71
+ }
72
+
73
+ export async function openSubagentPicker(
74
+ ctx: ExtensionCommandContext,
75
+ view: SubagentReadModel,
76
+ ) {
77
+ const selection: DashboardSelection = { index: 0 };
78
+
79
+ while (true) {
80
+ if (view.size() === 0) {
81
+ ctx.ui.notify("No subagents", "info");
82
+ return;
83
+ }
84
+
85
+ const picked = await ctx.ui.custom<string | null>(
86
+ (tui, theme, keybindings, done) =>
87
+ new SubagentDashboard(tui, theme, keybindings, view, selection, done),
88
+ {
89
+ overlay: true,
90
+ overlayOptions: { anchor: "center", width: "100%", maxHeight: "100%" },
91
+ },
92
+ );
93
+
94
+ if (!picked) return;
95
+ if (!view.get(picked)) continue;
96
+
97
+ await openSubagentTakeover(ctx, view, picked);
98
+ // After leaving the takeover view, fall back to the dashboard.
99
+ }
100
+ }
101
+
102
+ // --- Dashboard (fullscreen overlay) ----------------------------------------------
103
+
104
+ export interface DashboardSelection {
105
+ id?: string;
106
+ index: number;
107
+ }
108
+
109
+ export function reconcileDashboardSelection(
110
+ selection: DashboardSelection,
111
+ subs: ReadonlyArray<Pick<SubagentSnapshot, "id">>,
112
+ ) {
113
+ const stableIndex = selection.id
114
+ ? subs.findIndex((snap) => snap.id === selection.id)
115
+ : -1;
116
+ selection.index =
117
+ stableIndex >= 0
118
+ ? stableIndex
119
+ : Math.min(Math.max(0, selection.index), Math.max(0, subs.length - 1));
120
+ selection.id = subs[selection.index]?.id;
121
+ }
122
+
123
+ class SubagentDashboard implements Component {
124
+ private tui: TUI;
125
+ private theme: Theme;
126
+ private keybindings: KeybindingsManager;
127
+ private view: SubagentReadModel;
128
+ private selection: DashboardSelection;
129
+ private done: (value: string | null) => void;
130
+
131
+ private closed = false;
132
+ private ticker: ReturnType<typeof setInterval>;
133
+ private unsubChange: () => void;
134
+
135
+ constructor(
136
+ tui: TUI,
137
+ theme: Theme,
138
+ keybindings: KeybindingsManager,
139
+ view: SubagentReadModel,
140
+ selection: DashboardSelection,
141
+ done: (value: string | null) => void,
142
+ ) {
143
+ this.tui = tui;
144
+ this.theme = theme;
145
+ this.keybindings = keybindings;
146
+ this.view = view;
147
+ this.selection = selection;
148
+ this.done = done;
149
+ // Elapsed times, token counts, and statuses tick along at 1Hz.
150
+ this.ticker = setInterval(() => this.tui.requestRender(), 1000);
151
+ this.unsubChange = view.subscribe(() => this.tui.requestRender());
152
+ }
153
+
154
+ private subs(): ReadonlyArray<SubagentSnapshot> {
155
+ return this.view.list();
156
+ }
157
+
158
+ private cleanup() {
159
+ if (this.closed) return false;
160
+ this.closed = true;
161
+ clearInterval(this.ticker);
162
+ this.unsubChange();
163
+ return true;
164
+ }
165
+
166
+ private close(result: string | null) {
167
+ if (this.cleanup()) this.done(result);
168
+ }
169
+
170
+ dispose(): void {
171
+ this.cleanup();
172
+ }
173
+
174
+ handleInput(data: string): void {
175
+ const subs = this.subs();
176
+ reconcileDashboardSelection(this.selection, subs);
177
+
178
+ if (this.keybindings.matches(data, "tui.select.cancel")) {
179
+ this.close(null);
180
+ return;
181
+ }
182
+ if (this.keybindings.matches(data, "tui.select.confirm")) {
183
+ const snap = subs[this.selection.index];
184
+ if (snap) this.close(snap.id);
185
+ return;
186
+ }
187
+ if (this.keybindings.matches(data, "tui.select.up") || data === "k") {
188
+ if (subs.length > 0) {
189
+ this.selection.index =
190
+ (this.selection.index - 1 + subs.length) % subs.length;
191
+ this.selection.id = subs[this.selection.index]?.id;
192
+ this.tui.requestRender();
193
+ }
194
+ return;
195
+ }
196
+ if (this.keybindings.matches(data, "tui.select.down") || data === "j") {
197
+ if (subs.length > 0) {
198
+ this.selection.index = (this.selection.index + 1) % subs.length;
199
+ this.selection.id = subs[this.selection.index]?.id;
200
+ this.tui.requestRender();
201
+ }
202
+ return;
203
+ }
204
+ if (data === "x") {
205
+ const snap = subs[this.selection.index];
206
+ if (snap && snap.status === "running") this.view.requestAbort(snap.id);
207
+ return;
208
+ }
209
+ }
210
+
211
+ private pad(text: string, width: number): string {
212
+ const truncated = truncateToWidth(text, width);
213
+ return truncated + " ".repeat(Math.max(0, width - visibleWidth(truncated)));
214
+ }
215
+
216
+ private borderSegment(width: number, title: string): string {
217
+ const theme = this.theme;
218
+ const label = title
219
+ ? ` ${truncateToWidth(title, Math.max(0, width - 3))} `
220
+ : "";
221
+ const labelWidth = visibleWidth(label);
222
+ return (
223
+ theme.fg("border", "─") +
224
+ (label ? theme.fg("text", label) : "") +
225
+ theme.fg("border", "─".repeat(Math.max(0, width - 1 - labelWidth)))
226
+ );
227
+ }
228
+
229
+ render(width: number): string[] {
230
+ const theme = this.theme;
231
+ const subs = this.subs();
232
+ reconcileDashboardSelection(this.selection, subs);
233
+
234
+ const rows = this.tui.terminal.rows || 30;
235
+ // Render exactly terminal rows - 1 so the overlay covers the header,
236
+ // chat, editor, and extra footer lines while leaving pi's final footer
237
+ // row visible.
238
+ const bodyHeight = Math.max(6, rows - 5);
239
+ const innerWidth = width - 2;
240
+
241
+ const lines: string[] = [];
242
+
243
+ // Header: title left, count right
244
+ const headerLeft = theme.fg("accent", theme.bold("Subagents"));
245
+ const headerRight = theme.fg(
246
+ "muted",
247
+ `${subs.length} agent${subs.length === 1 ? "" : "s"}`,
248
+ );
249
+ const headerPad = Math.max(
250
+ 1,
251
+ width - visibleWidth(headerLeft) - visibleWidth(headerRight) - 4,
252
+ );
253
+ lines.push(
254
+ truncateToWidth(
255
+ ` ${headerLeft}${" ".repeat(headerPad)}${headerRight} `,
256
+ width,
257
+ ),
258
+ );
259
+
260
+ // Top border with panel title
261
+ const settled = subs.filter((s) => s.status !== "running").length;
262
+ lines.push(
263
+ theme.fg("border", "╭") +
264
+ this.borderSegment(innerWidth, `agents · ${settled}/${subs.length}`) +
265
+ theme.fg("border", "╮"),
266
+ );
267
+
268
+ // Rows
269
+ const divider = theme.fg("border", "│");
270
+ const rowLines = this.renderRows(subs, innerWidth, bodyHeight);
271
+ for (let i = 0; i < bodyHeight; i++) {
272
+ lines.push(divider + this.pad(rowLines[i] ?? "", innerWidth) + divider);
273
+ }
274
+
275
+ // Bottom border
276
+ lines.push(
277
+ theme.fg("border", "╰") +
278
+ theme.fg("border", "─".repeat(innerWidth)) +
279
+ theme.fg("border", "╯"),
280
+ );
281
+
282
+ // Hints
283
+ lines.push(
284
+ truncateToWidth(
285
+ theme.fg(
286
+ "dim",
287
+ ` ${configuredKeys(this.keybindings, "tui.select.up")}/${configuredKeys(this.keybindings, "tui.select.down")}/jk select · ${configuredKeys(this.keybindings, "tui.select.confirm")} take over · x abort · ${configuredKeys(this.keybindings, "tui.select.cancel")} close`,
288
+ ),
289
+ width,
290
+ ),
291
+ );
292
+
293
+ return lines;
294
+ }
295
+
296
+ private renderRows(
297
+ subs: ReadonlyArray<SubagentSnapshot>,
298
+ width: number,
299
+ height: number,
300
+ ): string[] {
301
+ const theme = this.theme;
302
+ const out: string[] = [];
303
+
304
+ // Scroll window around selection
305
+ let start = 0;
306
+ if (subs.length > height) {
307
+ start = Math.min(
308
+ Math.max(0, this.selection.index - Math.floor(height / 2)),
309
+ subs.length - height,
310
+ );
311
+ }
312
+ const visible = subs.slice(start, start + height);
313
+
314
+ for (let i = 0; i < visible.length; i++) {
315
+ const snap = visible[i];
316
+ const index = start + i;
317
+ const isSelected = index === this.selection.index;
318
+
319
+ // Left: marker, status square, title, dim id
320
+ const marker = isSelected ? theme.fg("accent", "❯") : " ";
321
+ const title = isSelected
322
+ ? theme.fg("accent", snap.title)
323
+ : theme.fg("text", snap.title);
324
+ const left = ` ${marker} ${statusGlyph(snap, theme)} ${title} ${theme.fg("dim", snap.id)}`;
325
+
326
+ // Right: backend · model · context utilization · elapsed · status
327
+ const utilization = formatContextUtilization(snap.usage);
328
+ const dot = theme.fg("dim", " · ");
329
+ const rightParts = [
330
+ theme.fg("muted", snap.backend),
331
+ theme.fg("muted", snap.meta.modelLabel ?? "?"),
332
+ ...(utilization ? [theme.fg("muted", utilization)] : []),
333
+ theme.fg("muted", formatElapsed(snap)),
334
+ statusWord(snap, theme),
335
+ ];
336
+ const right = `${rightParts.join(dot)} `;
337
+
338
+ const rightWidth = visibleWidth(right);
339
+ const leftMax = Math.max(0, width - rightWidth - 2);
340
+ const leftTruncated = truncateToWidth(left, leftMax);
341
+ const gap = Math.max(2, width - visibleWidth(leftTruncated) - rightWidth);
342
+ out.push(truncateToWidth(leftTruncated + " ".repeat(gap) + right, width));
343
+ }
344
+
345
+ if (start > 0) {
346
+ out[0] = truncateToWidth(theme.fg("dim", ` ... ${start} more`), width);
347
+ }
348
+ if (start + height < subs.length) {
349
+ out[out.length - 1] = truncateToWidth(
350
+ theme.fg("dim", ` ... ${subs.length - start - height} more`),
351
+ width,
352
+ );
353
+ }
354
+ return out;
355
+ }
356
+
357
+ invalidate(): void {}
358
+ }
359
+
360
+ // --- Takeover view ------------------------------------------------------------
361
+
362
+ const TRANSCRIPT_SCROLL_STEP = 6;
363
+
364
+ class TakeoverView implements Component, Focusable {
365
+ private tui: TUI;
366
+ private theme: Theme;
367
+ private keybindings: KeybindingsManager;
368
+ private id: string;
369
+ private view: SubagentReadModel;
370
+ private done: (value: null) => void;
371
+ private options?: TakeoverOptions;
372
+
373
+ private input = new Input();
374
+ /** Scroll offset in lines from the bottom of the transcript. 0 = pinned to bottom. */
375
+ private scrollOffset = 0;
376
+ private unsubscribe: () => void;
377
+ private renderTimer?: ReturnType<typeof setTimeout>;
378
+ private ticker: ReturnType<typeof setInterval>;
379
+ private closed = false;
380
+
381
+ private _focused = false;
382
+ get focused(): boolean {
383
+ return this._focused;
384
+ }
385
+ set focused(value: boolean) {
386
+ this._focused = value;
387
+ this.input.focused = value;
388
+ }
389
+
390
+ constructor(
391
+ tui: TUI,
392
+ theme: Theme,
393
+ keybindings: KeybindingsManager,
394
+ id: string,
395
+ view: SubagentReadModel,
396
+ done: (value: null) => void,
397
+ options?: TakeoverOptions,
398
+ ) {
399
+ this.tui = tui;
400
+ this.theme = theme;
401
+ this.keybindings = keybindings;
402
+ this.id = id;
403
+ this.view = view;
404
+ this.done = done;
405
+ this.options = options;
406
+ this.unsubscribe = view.subscribeTo(id, () => this.scheduleRender());
407
+ // Elapsed time in the header ticks along at 1Hz.
408
+ this.ticker = setInterval(() => this.tui.requestRender(), 1000);
409
+ this.input.onSubmit = (value: string) => {
410
+ const text = value.trim();
411
+ if (!text) return;
412
+ this.input.setValue("");
413
+ this.view.requestSend(this.id, text);
414
+ this.scrollOffset = 0;
415
+ this.tui.requestRender();
416
+ };
417
+ }
418
+
419
+ private snap(): SubagentSnapshot | undefined {
420
+ return this.view.get(this.id);
421
+ }
422
+
423
+ private scheduleRender() {
424
+ if (this.renderTimer) return;
425
+ // Streaming can emit an event per token. Limit terminal repaints so this
426
+ // view cannot starve input handling or make the child look frozen.
427
+ this.renderTimer = setTimeout(() => {
428
+ this.renderTimer = undefined;
429
+ if (!this.closed) this.tui.requestRender();
430
+ }, 50);
431
+ }
432
+
433
+ private cleanup() {
434
+ if (this.closed) return false;
435
+ this.closed = true;
436
+ this.unsubscribe();
437
+ clearInterval(this.ticker);
438
+ if (this.renderTimer) clearTimeout(this.renderTimer);
439
+ this.renderTimer = undefined;
440
+ return true;
441
+ }
442
+
443
+ private close() {
444
+ if (this.cleanup()) this.done(null);
445
+ }
446
+
447
+ dispose(): void {
448
+ this.cleanup();
449
+ }
450
+
451
+ handleInput(data: string): void {
452
+ if (this.keybindings.matches(data, "app.clear")) {
453
+ const snap = this.snap();
454
+ if (snap?.status === "running") this.view.requestAbort(this.id);
455
+ return;
456
+ }
457
+ if (
458
+ this.keybindings.matches(data, "app.interrupt") ||
459
+ this.keybindings.matches(data, "tui.select.cancel")
460
+ ) {
461
+ this.close();
462
+ return;
463
+ }
464
+ if (this.keybindings.matches(data, "tui.editor.cursorUp")) {
465
+ this.scrollOffset += TRANSCRIPT_SCROLL_STEP;
466
+ this.tui.requestRender();
467
+ return;
468
+ }
469
+ if (this.keybindings.matches(data, "tui.editor.cursorDown")) {
470
+ this.scrollOffset = Math.max(
471
+ 0,
472
+ this.scrollOffset - TRANSCRIPT_SCROLL_STEP,
473
+ );
474
+ this.tui.requestRender();
475
+ return;
476
+ }
477
+ if (this.keybindings.matches(data, "tui.editor.pageUp")) {
478
+ this.scrollOffset += this.viewportHeight();
479
+ this.tui.requestRender();
480
+ return;
481
+ }
482
+ if (this.keybindings.matches(data, "tui.editor.pageDown")) {
483
+ this.scrollOffset = Math.max(
484
+ 0,
485
+ this.scrollOffset - this.viewportHeight(),
486
+ );
487
+ this.tui.requestRender();
488
+ return;
489
+ }
490
+ this.input.handleInput(data);
491
+ this.tui.requestRender();
492
+ }
493
+
494
+ private viewportHeight(): number {
495
+ const rows = this.tui.terminal.rows || 30;
496
+ // The complete view renders viewport + 7 chrome rows. Using rows - 8
497
+ // makes the overlay exactly terminal rows - 1.
498
+ return Math.max(6, rows - 8);
499
+ }
500
+
501
+ render(width: number): string[] {
502
+ const theme = this.theme;
503
+ const border = theme.fg("borderAccent", "─".repeat(Math.max(1, width)));
504
+ const lines: string[] = [];
505
+ const snap = this.snap();
506
+
507
+ if (!snap) {
508
+ lines.push(border);
509
+ lines.push(theme.fg("dim", `${this.id} is no longer tracked`));
510
+ lines.push(border);
511
+ return lines;
512
+ }
513
+
514
+ lines.push(border);
515
+ const utilization = formatContextUtilization(snap.usage);
516
+ const header =
517
+ `${statusGlyph(snap, theme)} ` +
518
+ theme.fg("accent", theme.bold(`${snap.id} · ${snap.title}`)) +
519
+ theme.fg("muted", ` · ${snap.status} · ${formatElapsed(snap)}`) +
520
+ (this.options?.badge
521
+ ? theme.fg("muted", ` · ${this.options.badge}`)
522
+ : "") +
523
+ theme.fg("dim", ` · ${snap.backend}: ${snap.meta.modelLabel ?? "?"}`) +
524
+ (utilization ? theme.fg("dim", ` · ${utilization}`) : "");
525
+ lines.push(truncateToWidth(header, width));
526
+ lines.push(border);
527
+
528
+ // Fixed-height transcript viewport. Error and scroll status consume rows
529
+ // inside the viewport so streaming/scrolling never changes overlay height.
530
+ const transcript = buildTranscriptLines(snap, width, theme);
531
+ const viewport = this.viewportHeight();
532
+ const errorRows = snap.errorText ? 1 : 0;
533
+ const scrollRows = this.scrollOffset > 0 ? 1 : 0;
534
+ const transcriptCapacity = Math.max(1, viewport - errorRows - scrollRows);
535
+ const maxOffset = Math.max(0, transcript.length - transcriptCapacity);
536
+ if (this.scrollOffset > maxOffset) this.scrollOffset = maxOffset;
537
+
538
+ const body: string[] = [];
539
+ if (snap.errorText) {
540
+ body.push(
541
+ truncateToWidth(theme.fg("error", `error: ${snap.errorText}`), width),
542
+ );
543
+ }
544
+
545
+ const capacity = Math.max(
546
+ 1,
547
+ viewport - body.length - (this.scrollOffset > 0 ? 1 : 0),
548
+ );
549
+ const end = transcript.length - this.scrollOffset;
550
+ const visible = transcript.slice(Math.max(0, end - capacity), end);
551
+ if (visible.length === 0) body.push(theme.fg("dim", "(no output yet)"));
552
+ else body.push(...visible);
553
+
554
+ if (this.scrollOffset > 0) {
555
+ body.push(
556
+ truncateToWidth(
557
+ theme.fg("dim", `... ${this.scrollOffset} lines below · ↓/pgdn`),
558
+ width,
559
+ ),
560
+ );
561
+ }
562
+ while (body.length < viewport) body.push("");
563
+ lines.push(...body.slice(0, viewport));
564
+
565
+ lines.push(border);
566
+ lines.push(...this.input.render(width));
567
+ lines.push(
568
+ truncateToWidth(
569
+ theme.fg(
570
+ "dim",
571
+ `${configuredKeys(this.keybindings, "tui.input.submit")} send · ${configuredKeys(this.keybindings, "app.interrupt")} back · ${configuredKeys(this.keybindings, "app.clear")} abort run · ${configuredKeys(this.keybindings, "tui.editor.cursorUp")}/${configuredKeys(this.keybindings, "tui.editor.cursorDown")} scroll · ${configuredKeys(this.keybindings, "tui.editor.pageUp")}/${configuredKeys(this.keybindings, "tui.editor.pageDown")} page`,
572
+ ),
573
+ width,
574
+ ),
575
+ );
576
+ lines.push(border);
577
+ return lines;
578
+ }
579
+
580
+ invalidate(): void {
581
+ this.input.invalidate();
582
+ }
583
+ }