pi-suite 0.0.0-stage → 0.3.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 (220) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +100 -2
  3. package/README.zh-CN.md +101 -0
  4. package/package.json +63 -4
  5. package/skills/pi-suite-jobs/SKILL.md +76 -0
  6. package/skills/pi-suite-workflow/SKILL.md +114 -0
  7. package/src/agents/catalog.ts +80 -0
  8. package/src/agents/child.ts +79 -0
  9. package/src/agents/commands.ts +17 -0
  10. package/src/agents/defaults.ts +78 -0
  11. package/src/agents/history.ts +112 -0
  12. package/src/agents/index.ts +211 -0
  13. package/src/agents/manager.ts +438 -0
  14. package/src/agents/mentions/clone.ts +51 -0
  15. package/src/agents/mentions/grammar.ts +64 -0
  16. package/src/agents/mentions/index.ts +76 -0
  17. package/src/agents/mentions/provider.ts +79 -0
  18. package/src/agents/model-editor.ts +95 -0
  19. package/src/agents/models.ts +43 -0
  20. package/src/agents/output/schema.ts +101 -0
  21. package/src/agents/output/tool.ts +98 -0
  22. package/src/agents/parent.ts +13 -0
  23. package/src/agents/questions.ts +63 -0
  24. package/src/agents/records.ts +90 -0
  25. package/src/agents/registry.ts +20 -0
  26. package/src/agents/render.ts +85 -0
  27. package/src/agents/resources/context.ts +48 -0
  28. package/src/agents/resources/loader.ts +86 -0
  29. package/src/agents/resources/memory.ts +67 -0
  30. package/src/agents/resources/packages.ts +96 -0
  31. package/src/agents/resources/paths.ts +8 -0
  32. package/src/agents/resources/prompts.ts +11 -0
  33. package/src/agents/resources/scope.ts +147 -0
  34. package/src/agents/resources/selectors.ts +186 -0
  35. package/src/agents/retry.ts +20 -0
  36. package/src/agents/rpc/handlers.ts +62 -0
  37. package/src/agents/rpc/index.ts +73 -0
  38. package/src/agents/rpc/options.ts +44 -0
  39. package/src/agents/run-groups.ts +16 -0
  40. package/src/agents/runner.ts +131 -0
  41. package/src/agents/runtime.ts +40 -0
  42. package/src/agents/schedules/index.ts +136 -0
  43. package/src/agents/schedules/menu.ts +38 -0
  44. package/src/agents/schedules/parse.ts +42 -0
  45. package/src/agents/schedules/store.ts +78 -0
  46. package/src/agents/schema.ts +5 -0
  47. package/src/agents/session.ts +29 -0
  48. package/src/agents/tools.ts +177 -0
  49. package/src/agents/types.ts +87 -0
  50. package/src/agents/ui/index.ts +42 -0
  51. package/src/agents/ui/runs.ts +122 -0
  52. package/src/agents/ui/types.ts +91 -0
  53. package/src/agents/viewer-info.ts +36 -0
  54. package/src/agents/viewer.ts +160 -0
  55. package/src/agents/workflow/collisions.ts +124 -0
  56. package/src/agents/workflow/entry.ts +93 -0
  57. package/src/agents/workflow/host.ts +119 -0
  58. package/src/agents/workflow/index.ts +100 -0
  59. package/src/agents/workflow/journal.ts +147 -0
  60. package/src/agents/workflow/literal.ts +57 -0
  61. package/src/agents/workflow/manager.ts +169 -0
  62. package/src/agents/workflow/meta.ts +323 -0
  63. package/src/agents/workflow/progress/format.ts +184 -0
  64. package/src/agents/workflow/progress/index.ts +3 -0
  65. package/src/agents/workflow/progress/model.ts +224 -0
  66. package/src/agents/workflow/progress/types.ts +144 -0
  67. package/src/agents/workflow/render.ts +46 -0
  68. package/src/agents/workflow/runtime/helpers.ts +236 -0
  69. package/src/agents/workflow/runtime/index.ts +3 -0
  70. package/src/agents/workflow/runtime/run.ts +646 -0
  71. package/src/agents/workflow/runtime/types.ts +273 -0
  72. package/src/agents/workflow/saved.ts +74 -0
  73. package/src/agents/workflow/store.ts +23 -0
  74. package/src/agents/workflow/task.ts +277 -0
  75. package/src/agents/workflow/tool-description.ts +32 -0
  76. package/src/agents/workflow/tools.ts +66 -0
  77. package/src/agents/workflow/ui/menu.ts +144 -0
  78. package/src/agents/workflow/ui/progress.ts +91 -0
  79. package/src/agents/workflow/worker/bootstrap.ts +316 -0
  80. package/src/agents/workflow/worker/flow.ts +218 -0
  81. package/src/agents/workflow/worker/index.ts +7 -0
  82. package/src/agents/workflow/worker/scope.ts +215 -0
  83. package/src/ask/.gitkeep +0 -0
  84. package/src/ask/form.ts +67 -0
  85. package/src/ask/index.ts +73 -0
  86. package/src/ask/keys.ts +32 -0
  87. package/src/ask/layout.ts +78 -0
  88. package/src/ask/queue.ts +40 -0
  89. package/src/ask/render.ts +62 -0
  90. package/src/ask/result.ts +56 -0
  91. package/src/ask/schema.ts +67 -0
  92. package/src/ask/tool-render.ts +49 -0
  93. package/src/ask/view.ts +406 -0
  94. package/src/goal/.gitkeep +0 -0
  95. package/src/goal/activity.ts +50 -0
  96. package/src/goal/commands.ts +75 -0
  97. package/src/goal/context.ts +36 -0
  98. package/src/goal/index.ts +38 -0
  99. package/src/goal/manager.ts +386 -0
  100. package/src/goal/presentation.ts +15 -0
  101. package/src/goal/render.ts +36 -0
  102. package/src/goal/snapshot.ts +78 -0
  103. package/src/goal/state.ts +39 -0
  104. package/src/goal/store.ts +59 -0
  105. package/src/goal/tools.ts +59 -0
  106. package/src/goal/wait.ts +39 -0
  107. package/src/index.ts +20 -0
  108. package/src/jobs/backends/linux-tree.ts +87 -0
  109. package/src/jobs/backends/pipe.ts +74 -0
  110. package/src/jobs/backends/process.ts +79 -0
  111. package/src/jobs/backends/pty-job.ts +45 -0
  112. package/src/jobs/backends/pty.ts +502 -0
  113. package/src/jobs/backends/windows-tree.ts +289 -0
  114. package/src/jobs/commands.ts +7 -0
  115. package/src/jobs/control.ts +13 -0
  116. package/src/jobs/index.ts +331 -0
  117. package/src/jobs/launch/config.ts +26 -0
  118. package/src/jobs/launch/name.ts +16 -0
  119. package/src/jobs/launch/presets.ts +61 -0
  120. package/src/jobs/log-viewer.ts +147 -0
  121. package/src/jobs/manager.ts +507 -0
  122. package/src/jobs/monitors/compile.ts +101 -0
  123. package/src/jobs/monitors/hands-free.ts +108 -0
  124. package/src/jobs/monitors/runtime.ts +165 -0
  125. package/src/jobs/output.ts +54 -0
  126. package/src/jobs/query.ts +62 -0
  127. package/src/jobs/render.ts +103 -0
  128. package/src/jobs/runtime.ts +89 -0
  129. package/src/jobs/state.ts +25 -0
  130. package/src/jobs/store.ts +168 -0
  131. package/src/jobs/terminal/keys.ts +292 -0
  132. package/src/jobs/terminal/protocol.ts +37 -0
  133. package/src/jobs/terminal/read.ts +131 -0
  134. package/src/jobs/terminal/render.ts +70 -0
  135. package/src/jobs/terminal/screen.ts +92 -0
  136. package/src/jobs/terminal/session.ts +100 -0
  137. package/src/jobs/terminal/shell.ts +22 -0
  138. package/src/jobs/terminal/snapshot.ts +8 -0
  139. package/src/jobs/terminal/visible-text.ts +53 -0
  140. package/src/jobs/tools.ts +203 -0
  141. package/src/jobs/types.ts +60 -0
  142. package/src/jobs/viewer/component.ts +209 -0
  143. package/src/jobs/viewer/metadata.ts +9 -0
  144. package/src/jobs/viewer.ts +149 -0
  145. package/src/jobs/workspace.ts +31 -0
  146. package/src/runtime/.gitkeep +0 -0
  147. package/src/runtime/binding.ts +26 -0
  148. package/src/runtime/cli-prompt.ts +24 -0
  149. package/src/runtime/clipboard.ts +16 -0
  150. package/src/runtime/config-edit.ts +31 -0
  151. package/src/runtime/config-fields.ts +65 -0
  152. package/src/runtime/config.ts +111 -0
  153. package/src/runtime/errors.ts +11 -0
  154. package/src/runtime/json-store.ts +156 -0
  155. package/src/runtime/notification-render.ts +35 -0
  156. package/src/runtime/notifications.ts +98 -0
  157. package/src/runtime/owner.ts +54 -0
  158. package/src/runtime/read.ts +200 -0
  159. package/src/runtime/renderers.ts +50 -0
  160. package/src/runtime/responses/index.ts +108 -0
  161. package/src/runtime/responses/payload.ts +78 -0
  162. package/src/runtime/settings/index.ts +24 -0
  163. package/src/runtime/settings/view.ts +84 -0
  164. package/src/runtime/suite.ts +192 -0
  165. package/src/runtime/text.ts +6 -0
  166. package/src/runtime/tools.ts +131 -0
  167. package/src/runtime/wait-render.ts +33 -0
  168. package/src/runtime/wait.ts +134 -0
  169. package/src/tasks/commands.ts +41 -0
  170. package/src/tasks/index.ts +305 -0
  171. package/src/tasks/model.ts +152 -0
  172. package/src/tasks/presentation.ts +40 -0
  173. package/src/tasks/query.ts +38 -0
  174. package/src/tasks/render.ts +54 -0
  175. package/src/tasks/schema.ts +25 -0
  176. package/src/tasks/store.ts +164 -0
  177. package/src/tasks/tools.ts +69 -0
  178. package/src/tasks/types.ts +61 -0
  179. package/src/tasks/viewer.ts +68 -0
  180. package/src/ui/.gitkeep +0 -0
  181. package/src/ui/actions.ts +50 -0
  182. package/src/ui/browser-chrome.ts +175 -0
  183. package/src/ui/browser.ts +292 -0
  184. package/src/ui/details.ts +111 -0
  185. package/src/ui/dock/line.ts +14 -0
  186. package/src/ui/dock/rows.ts +78 -0
  187. package/src/ui/dock.ts +224 -0
  188. package/src/ui/format.ts +25 -0
  189. package/src/ui/frame.ts +8 -0
  190. package/src/ui/inline-input.ts +98 -0
  191. package/src/ui/reading.ts +105 -0
  192. package/src/ui/rendering/builtin-command.ts +34 -0
  193. package/src/ui/rendering/command.ts +60 -0
  194. package/src/ui/rendering/read-page.ts +15 -0
  195. package/src/ui/rendering/shell/bash.ts +281 -0
  196. package/src/ui/rendering/shell/index.ts +24 -0
  197. package/src/ui/rendering/shell/powershell.ts +155 -0
  198. package/src/ui/rendering/shell/spans.ts +28 -0
  199. package/src/ui/scroll.ts +111 -0
  200. package/src/ui/select.ts +67 -0
  201. package/src/ui/status.ts +67 -0
  202. package/src/ui/structured-details.ts +41 -0
  203. package/src/ui/terminal.ts +137 -0
  204. package/src/ui/ticker.ts +18 -0
  205. package/src/ui/tool-render.ts +152 -0
  206. package/src/ui/transcript.ts +140 -0
  207. package/src/ui/viewer/agent-information.ts +34 -0
  208. package/src/ui/viewer/editor.ts +18 -0
  209. package/src/ui/viewer/navigation.ts +25 -0
  210. package/themes/oh-my-pi.json +95 -0
  211. package/third-party/UPSTREAM.md +88 -0
  212. package/third-party/licenses/.gitkeep +0 -0
  213. package/third-party/licenses/oh-my-pi.txt +23 -0
  214. package/third-party/licenses/pi-ask-user.txt +21 -0
  215. package/third-party/licenses/pi-background-jobs.txt +21 -0
  216. package/third-party/licenses/pi-goal.txt +21 -0
  217. package/third-party/licenses/pi-interactive-shell.txt +25 -0
  218. package/third-party/licenses/pi-subagents.txt +21 -0
  219. package/third-party/licenses/pi-tasks.txt +21 -0
  220. package/third-party/sources.json +111 -0
@@ -0,0 +1,67 @@
1
+ import { getSelectListTheme, type ExtensionContext } from '@earendil-works/pi-coding-agent';
2
+ import { Input, SelectList, fuzzyFilter, getSelectPageIndex, truncateToWidth, type SelectItem } from '@earendil-works/pi-tui';
3
+ import { DoubleLeft, type ViewerNavigation } from './viewer/navigation.ts';
4
+ import { commandFrame } from './frame.ts';
5
+ import { isReadingSession, openReading, readingRows, type ReadingFactory } from './reading.ts';
6
+
7
+ /** Native input, paging and display-only truncation keep complete resource identities selectable. */
8
+ export function selectValue(ctx: ExtensionContext, title: string, items: SelectItem[], initial?: string, options: { filter?: boolean; navigation?: ViewerNavigation } = {}): Promise<string | undefined> {
9
+ const inReading = isReadingSession(ctx);
10
+ const factory: ReadingFactory<string | undefined> = (tui, theme, keys, done) => {
11
+ const input = options.filter ? new Input({ prompt: 'Filter: ' }) : undefined;
12
+ const doubleLeft = new DoubleLeft();
13
+ let filtered = items;
14
+ const listHeight = () => Math.max(1, (inReading ? readingRows(tui) : tui.terminal.rows) - 6 - Number(Boolean(input)));
15
+ let maxVisible = listHeight();
16
+ const createList = (index: number) => {
17
+ const next = new SelectList(filtered, maxVisible, getSelectListTheme());
18
+ next.setSelectedIndex(index);
19
+ return next;
20
+ };
21
+ let list = createList(items.findIndex(item => item.value === initial));
22
+ const key = (action: Parameters<typeof keys.getKeys>[0]) => keys.getKeys(action).join('/');
23
+ const hint = `${options.navigation && !input ? '←← close · ' : ''}${key('tui.select.confirm')} select · ${key('tui.select.cancel')} cancel · ${key('tui.select.up')}/${key('tui.select.down')} move · ${key('tui.select.pageUp')}/${key('tui.select.pageDown')} page`;
24
+ return {
25
+ capturesViewportInput: true,
26
+ get focused() { return input?.focused ?? false; },
27
+ set focused(value: boolean) { if (input) input.focused = value; },
28
+ render(width: number) {
29
+ const height = listHeight();
30
+ if (height !== maxVisible) {
31
+ const index = filtered.indexOf(list.getSelectedItem()!);
32
+ maxVisible = height; list = createList(index);
33
+ }
34
+ return commandFrame(width, [truncateToWidth(title, width), ...input ? input.render(width) : [],
35
+ ...filtered.length ? list.render(width) : [theme.fg('warning', 'No matching items')], truncateToWidth(hint, width)], theme)
36
+ .map(line => truncateToWidth(line, width));
37
+ },
38
+ dispose: () => doubleLeft.reset(),
39
+ invalidate: () => { list.invalidate(); input?.invalidate(); },
40
+ getSelectedItem: () => list.getSelectedItem(),
41
+ handleInput(data: string) {
42
+ if (!input && options.navigation && doubleLeft.handle(data)) { options.navigation.close(); done(undefined); return; }
43
+ const selected = list.getSelectedItem(), index = filtered.indexOf(selected!);
44
+ const page = getSelectPageIndex(keys, data, index, filtered.length, maxVisible);
45
+ // SelectList reads a package-global key manager. Route named actions through the
46
+ // injected host manager instead, while retaining its native selection/layout state.
47
+ if (keys.matches(data, 'tui.select.cancel')) { done(undefined); return; }
48
+ if (keys.matches(data, 'tui.select.confirm')) { if (selected) done(selected.value); return; }
49
+ if (keys.matches(data, 'tui.select.up')) { if (filtered.length) list.setSelectedIndex((index - 1 + filtered.length) % filtered.length); }
50
+ else if (keys.matches(data, 'tui.select.down')) { if (filtered.length) list.setSelectedIndex((index + 1) % filtered.length); }
51
+ else if (page !== undefined) list.setSelectedIndex(page);
52
+ else if (input) {
53
+ const previous = input.getValue();
54
+ input.handleInput(data);
55
+ if (input.getValue() !== previous) {
56
+ filtered = fuzzyFilter(items, input.getValue(), item => `${item.value} ${item.label ?? ''} ${item.description ?? ''}`);
57
+ list = createList(0);
58
+ }
59
+ }
60
+ tui.requestRender();
61
+ },
62
+ };
63
+ };
64
+ // An inline dialog would sit behind the retained browser frame. Mount through
65
+ // the same reading session so the new overlay takes focus and replaces that frame.
66
+ return inReading ? openReading(ctx, factory) : ctx.ui.custom(factory);
67
+ }
@@ -0,0 +1,67 @@
1
+ import type { ExtensionUIContext } from "@earendil-works/pi-coding-agent";
2
+ import type { DisplayMode } from "../runtime/config.ts";
3
+ import type { Dock, DockRow } from "./dock.ts";
4
+ import type { DisplayText } from './browser-chrome.ts';
5
+
6
+ export class StatusPublisher {
7
+ private ui?: ExtensionUIContext;
8
+ private previous = new Map<string, string | undefined>();
9
+ private goal?: string;
10
+ private agents = new Set<string>();
11
+ private jobs = new Set<string>();
12
+ private details: Record<'agents' | 'jobs', DockRow[]> = { agents: [], jobs: [] };
13
+ private asides: Record<'agents' | 'jobs', DisplayText> = { agents: '', jobs: '' };
14
+ private ownsGoal = true;
15
+ private modes: Record<"goal" | "agents" | "jobs", DisplayMode> = { goal: "status", agents: "status", jobs: "status" };
16
+
17
+ constructor(private dock: Dock) {
18
+ dock.register("goal", { title: "Goal", rows: () => this.modes.goal === "dock" && this.goal
19
+ ? [{ id: "goal", text: this.goal, priority: 90 }] : [] });
20
+ for (const key of ["agents", "jobs"] as const) dock.register(key, { title: key === 'agents' ? 'Agents' : 'Jobs', rows: () => [
21
+ // Counts are summaries, not object identities that a viewer can open.
22
+ ...(this.modes[key] === "dock" && this[key].size && !this.asides[key].length ? [{ id: key, text: `${this[key].size} active`, priority: 70, selectable: false }] : []),
23
+ ...(this.modes[key] === 'hidden' ? [] : this.details[key]),
24
+ ], aside: () => this.asides[key] });
25
+ }
26
+
27
+ bind(ui: ExtensionUIContext, modes: typeof this.modes, ownsGoal = true): void {
28
+ this.detach(); this.ui = ui; this.modes = modes; this.ownsGoal = ownsGoal; this.previous.clear(); this.flush();
29
+ }
30
+ detach(): void {
31
+ if (this.ownsGoal) this.ui?.setStatus("goal", undefined);
32
+ this.ui?.setStatus("pi-suite:runtime", undefined);
33
+ this.ui = undefined;
34
+ this.goal = undefined; this.agents.clear(); this.jobs.clear();
35
+ this.details = { agents: [], jobs: [] }; this.asides = { agents: '', jobs: '' };
36
+ this.dock.setStatusRow(false);
37
+ }
38
+ setGoal(text?: string): void {
39
+ if (text === this.goal) return;
40
+ this.goal = text; this.flush();
41
+ }
42
+ get goalVisible(): boolean { return Boolean(this.ui && this.modes.goal !== 'hidden'); }
43
+ detailsVisible(kind: 'agents' | 'jobs'): boolean { return Boolean(this.ui && this.modes[kind] !== 'hidden'); }
44
+ setActivities(kind: "agents" | "jobs", ids: Iterable<string>, details: DockRow[] = [], aside: DisplayText = ''): void {
45
+ const next = new Set(ids), previousSize = this[kind].size;
46
+ this[kind] = next;
47
+ const changed = JSON.stringify(details) !== JSON.stringify(this.details[kind]) || JSON.stringify(aside) !== JSON.stringify(this.asides[kind]);
48
+ this.details[kind] = details; this.asides[kind] = aside;
49
+ // Footer counts do not tick; live row metrics and state counts only redraw Dock.
50
+ if (next.size !== previousSize) this.flush();
51
+ else if (changed && this.modes[kind] !== 'hidden') this.dock.invalidate();
52
+ }
53
+
54
+ private flush(): void {
55
+ const goal = this.modes.goal === "status" ? this.goal : undefined;
56
+ const runtime = (["agents", "jobs"] as const).filter(key => this.modes[key] === "status" && this[key].size)
57
+ .map(key => `${key === "agents" ? "🤖" : "⚙"}${this[key].size}`).join(" · ") || undefined;
58
+ for (const [key, text] of [["goal", goal], ["pi-suite:runtime", runtime]] as const) {
59
+ // The goal key is shared with pi-goal; a disabled suite module does not own it.
60
+ if (key === 'goal' && !this.ownsGoal) continue;
61
+ if (!this.previous.has(key) || this.previous.get(key) !== text) {
62
+ this.ui?.setStatus(key, text); this.previous.set(key, text);
63
+ }
64
+ }
65
+ this.dock.setStatusRow(Boolean(goal || runtime));
66
+ }
67
+ }
@@ -0,0 +1,41 @@
1
+ import type { Theme } from '@earendil-works/pi-coding-agent';
2
+ import { Text } from '@earendil-works/pi-tui';
3
+ import { detailPartText, divider, heading, type DetailPart } from './browser-chrome.ts';
4
+ import { sanitizeText } from '../runtime/text.ts';
5
+
6
+ /** A section names the block below it (metadata, input, output) so long free text is never
7
+ * mistaken for a field value. It always starts a new group. */
8
+ export interface DetailSection { section: string }
9
+ export type DetailRow = string | readonly DetailPart[] | DetailSection;
10
+ /** null marks a UI group break; undefined omits an optional row. */
11
+ export interface StructuredDetails { rows: readonly (DetailRow | null | undefined)[] }
12
+
13
+ export const part = (text: string | number | boolean, role?: DetailPart['role']): DetailPart => ({ text: String(text), role });
14
+ export const statePart = (text: string | boolean, state = String(text)): DetailPart => ({ text: String(text), state });
15
+ export const field = (label: string, value: DetailPart | string | number | boolean, ...suffix: DetailPart[]): DetailRow =>
16
+ [part(`${label} `, 'label'), typeof value === 'object' ? value : part(value), ...suffix];
17
+ export const section = (title: string): DetailSection => ({ section: title });
18
+ const isSection = (row: DetailRow): row is DetailSection => typeof row === 'object' && 'section' in row;
19
+ const sectionText = (title: string, theme?: Theme) => `${divider('──', theme)} ${heading(sanitizeText(title), theme)} ${divider('──', theme)}`;
20
+
21
+ /** Tool receipts use the original, unsanitized text without UI-only spacing. */
22
+ export function plainDetailLines({ rows }: StructuredDetails): string[] {
23
+ return rows.flatMap(row => row == null ? [] : [typeof row === 'string' ? row : isSection(row) ? `── ${row.section} ──` : row.map(({text}) => text).join('')]);
24
+ }
25
+
26
+ export function detailsText({ rows }: StructuredDetails, theme?: Theme): string {
27
+ const lines: string[] = [];
28
+ let gap = false;
29
+ for (const row of rows) {
30
+ if (row === undefined) continue;
31
+ if (row === null) { gap = true; continue; }
32
+ const line = isSection(row) ? sectionText(row.section, theme)
33
+ : (typeof row === 'string' ? [part(row)] : row).map(value => detailPartText(value, theme)).join('');
34
+ if ((gap || isSection(row)) && lines.length) lines.push('');
35
+ lines.push(line);
36
+ gap = false;
37
+ }
38
+ return lines.join('\n');
39
+ }
40
+
41
+ export const detailsContent = (details: StructuredDetails, theme?: Theme): Text => new Text(detailsText(details, theme), 0, 0);
@@ -0,0 +1,137 @@
1
+ import type { Theme } from '@earendil-works/pi-coding-agent';
2
+ import { Key, matchesKey, truncateToWidth, type Component, type KeyId, type TUI, type TuiMouseEvent } from '@earendil-works/pi-tui';
3
+ import { commandFrame } from './frame.ts';
4
+ import { ActionBar, keyHelp, type DetailAction } from './actions.ts';
5
+ import { keyHint, separator } from './browser-chrome.ts';
6
+ import { readingRows } from './reading.ts';
7
+ import { DoubleLeft, type ViewerNavigation } from './viewer/navigation.ts';
8
+
9
+ /** Both the live PTY and a restored xterm screen implement the same visual boundary. */
10
+ export interface TerminalSource {
11
+ readonly cols: number; readonly rows: number; readonly closed: boolean;
12
+ readonly following?: boolean;
13
+ readonly viewport?: {start: number; total: number; alternate: boolean; cursor: {x: number; y: number; visible: boolean}};
14
+ getViewportLines(options?: {ansi?: boolean; cursor?: boolean; hardwareCursor?: boolean; height?: number}): string[];
15
+ resize(cols: number, rows: number): void;
16
+ scroll(lines: number): void;
17
+ follow?(): void;
18
+ onVisualChange(listener: () => void): () => void;
19
+ }
20
+ export interface TerminalKeys { detachKey: KeyId; returnKey: KeyId; transferKey: KeyId }
21
+ export type TerminalExit = { action: 'detach' | 'transfer'; screen: string[] };
22
+ export interface TerminalViewOptions {
23
+ title: () => string;
24
+ write(data: string): void;
25
+ takeControl?(): void;
26
+ returnControl(): void;
27
+ userControl: () => boolean;
28
+ canInput?: () => boolean;
29
+ readonly?: boolean;
30
+ initialInput?: boolean;
31
+ navigation?: ViewerNavigation;
32
+ actions?: DetailAction[];
33
+ bottom?: (width: number) => string[];
34
+ hideTitle?: boolean;
35
+ }
36
+
37
+ /** A visual subscriber, not an owner. Browse mode never forwards keys or acquires control. */
38
+ export class TerminalView implements Component {
39
+ focused = true;
40
+ readonly capturesViewportInput = true;
41
+ private unsubscribe: () => void;
42
+ private error?: string;
43
+ private height = 1;
44
+ private bodyStart = 1;
45
+ private finished = false;
46
+ private input = false;
47
+ private doubleLeft = new DoubleLeft();
48
+ private bar: ActionBar;
49
+ constructor(private tui: TUI, private theme: Theme, private source: TerminalSource, private keys: TerminalKeys,
50
+ private options: TerminalViewOptions, private done: (result: TerminalExit) => void) {
51
+ this.unsubscribe = source.onVisualChange(() => {
52
+ if (source.closed && this.input) this.releaseInput();
53
+ tui.requestRender();
54
+ });
55
+ this.bar = new ActionBar(() => [
56
+ ...options.actions ?? [],
57
+ {key: 'f', label: 'Follow latest', run: () => this.follow()},
58
+ {key: 'i', label: 'Input', available: () => this.canInput(), run: () => this.enterInput()},
59
+ ], () => { throw new Error('Terminal actions do not accept inline text'); });
60
+ if (options.initialInput) this.enterInput();
61
+ }
62
+ private canInput(): boolean { return !this.options.readonly && !this.source.closed && this.options.canInput?.() !== false; }
63
+ get inputMode(): boolean { return this.input; }
64
+ enterInput(): void {
65
+ if (!this.canInput()) return;
66
+ this.doubleLeft.reset(); this.bar.disarm();
67
+ try { this.options.takeControl?.(); this.input = true; this.follow(); }
68
+ catch (error) { this.error = error instanceof Error ? error.message : String(error); }
69
+ this.tui.requestRender();
70
+ }
71
+ private releaseInput(): void { if (this.input) { this.input = false; this.options.returnControl(); } }
72
+ private follow(): void { if (this.source.follow) this.source.follow(); else this.source.scroll(-Number.MAX_SAFE_INTEGER); }
73
+ render(width: number): string[] {
74
+ if (!this.canInput() && this.input) this.releaseInput();
75
+ const leave = keyHint(this.keys.detachKey, 'leave', this.theme);
76
+ const help = this.input
77
+ ? [leave, keyHint(this.keys.returnKey, 'return input', this.theme), keyHint(this.keys.transferKey, 'send screen', this.theme), keyHint('Shift+↑↓', 'history', this.theme)].join(' · ')
78
+ : [leave, keyHint('Esc', 'back', this.theme), ...this.canInput() && this.focused ? [keyHint('i', 'input', this.theme)] : [],
79
+ keyHint('↑↓ PgUp/PgDn Home/End', 'history', this.theme), ...this.options.navigation ? [keyHint('←←', 'close', this.theme)] : [],
80
+ this.bar.render(this.theme, ['i'])].join(' · ');
81
+ const total = readingRows(this.tui), titleRows = Number(!this.options.hideTitle);
82
+ const bottom = this.options.bottom?.(width) ?? [];
83
+ const metadata = bottom.length ? [separator(width, this.theme), ...bottom] : [];
84
+ // Errors and confirmations must not erase the user's escape route. The promoted
85
+ // input action is omitted from the secondary bar, without changing dispatch.
86
+ const feedback = this.error ? this.theme.fg('warning', this.error) : !this.input ? this.bar.hint(this.theme) : undefined;
87
+ const notice = feedback ? [truncateToWidth(feedback, width)] : [];
88
+ const hints = keyHelp(help, width, Math.min(2, Math.max(1, total - titleRows - metadata.length - notice.length - 4)));
89
+ this.height = Math.max(1, total - 3 - titleRows - metadata.length - notice.length - hints.length);
90
+ this.bodyStart = 1 + titleRows;
91
+ // Only process screen rows reach xterm/PTY. An unchanged size never causes resize/redraw.
92
+ if (!this.source.closed && (this.source.cols !== width || this.source.rows !== this.height)) this.source.resize(Math.max(1, width), this.height);
93
+ const screen = this.source.getViewportLines({ansi: true, cursor: this.focused, hardwareCursor: this.input && this.focused, height: this.height});
94
+ const control = this.source.closed ? 'exited' : this.input ? 'you control input' : 'read-only view';
95
+ return commandFrame(width, [...titleRows ? [truncateToWidth(this.theme.fg('accent', `${this.options.title()} · ${control}`), width)] : [],
96
+ ...Array.from({length: this.height}, (_, index) => screen[index] ?? ''), ...metadata, ...notice, separator(width, this.theme), ...hints], this.theme)
97
+ .map(line => truncateToWidth(line, width));
98
+ }
99
+ handleInput(data: string): void {
100
+ this.error = undefined;
101
+ if (this.input) {
102
+ this.doubleLeft.reset();
103
+ if (matchesKey(data, this.keys.detachKey)) return this.finish('detach');
104
+ if (matchesKey(data, this.keys.transferKey)) return this.finish('transfer');
105
+ if (matchesKey(data, this.keys.returnKey)) { this.releaseInput(); this.tui.requestRender(); return; }
106
+ if (matchesKey(data, Key.shift('up'))) { this.source.scroll(Math.max(1, this.height - 1)); return; }
107
+ if (matchesKey(data, Key.shift('down'))) { this.source.scroll(-Math.max(1, this.height - 1)); return; }
108
+ if (!this.canInput()) { this.releaseInput(); this.tui.requestRender(); return; }
109
+ try { this.options.write(data); }
110
+ catch (error) { this.error = error instanceof Error ? error.message : String(error); this.tui.requestRender(); }
111
+ return;
112
+ }
113
+ if (this.options.navigation && this.doubleLeft.handle(data)) { this.options.navigation.close(); return this.finish('detach'); }
114
+ if (matchesKey(data, Key.escape) || matchesKey(data, this.keys.detachKey)) return this.finish('detach');
115
+ if (this.bar.handleInput(data)) { this.tui.requestRender(); return; }
116
+ if (matchesKey(data, Key.end)) this.follow();
117
+ else if (matchesKey(data, Key.home)) this.source.scroll(Number.MAX_SAFE_INTEGER);
118
+ else if (matchesKey(data, Key.up) || matchesKey(data, Key.shift('up'))) this.source.scroll(1);
119
+ else if (matchesKey(data, Key.down) || matchesKey(data, Key.shift('down'))) this.source.scroll(-1);
120
+ else if (matchesKey(data, Key.pageUp)) this.source.scroll(this.height);
121
+ else if (matchesKey(data, Key.pageDown)) this.source.scroll(-this.height);
122
+ }
123
+ handleMouse(event: TuiMouseEvent) {
124
+ this.doubleLeft.reset();
125
+ if (event.type !== 'wheel' || event.y < this.bodyStart || event.y >= this.bodyStart + this.height) return;
126
+ this.source.scroll(-(event.wheelDelta ?? 0) * 3); return {handled: true};
127
+ }
128
+ invalidate(): void {}
129
+ finish(action: TerminalExit['action']): void {
130
+ if (this.finished) return;
131
+ this.finished = true;
132
+ // Transfer is the actual current screen, not a manually scrolled history viewport.
133
+ this.follow(); const screen = this.source.getViewportLines();
134
+ this.dispose(); this.done({ action, screen });
135
+ }
136
+ dispose(): void { this.doubleLeft.reset(); this.releaseInput(); this.unsubscribe(); }
137
+ }
@@ -0,0 +1,18 @@
1
+ /** Refresh presentation without turning clock ticks into execution changes. */
2
+ export class PresentationTicker {
3
+ private timer?: NodeJS.Timeout;
4
+
5
+ constructor(private visible: () => boolean, private publish: () => void) {}
6
+
7
+ update(active: boolean): void {
8
+ if (!active || !this.visible()) { this.stop(); return; }
9
+ this.timer ??= setInterval(() => {
10
+ if (this.visible()) this.publish();
11
+ else this.stop();
12
+ }, 1000).unref();
13
+ }
14
+
15
+ stop(): void {
16
+ clearInterval(this.timer); this.timer = undefined;
17
+ }
18
+ }
@@ -0,0 +1,152 @@
1
+ import { performance } from 'node:perf_hooks';
2
+ import { getLanguageFromPath, type Theme, type ThemeColor, type ToolRenderers } from '@earendil-works/pi-coding-agent';
3
+ import { Container, Text, truncateToWidth, type Component } from '@earendil-works/pi-tui';
4
+ import { sanitizeText } from '../runtime/text.ts';
5
+ import { stateTone } from './browser-chrome.ts';
6
+ import { CodeComponent, commandComponent, type CodeSource, type CommandShell } from './rendering/command.ts';
7
+
8
+ export type Tone = ThemeColor;
9
+ export interface ToolLine {
10
+ icon: string; tone?: Tone; title: string; titleTone?: Tone; summary?: string;
11
+ meta?: (string | { text: string; tone: Tone })[]; strike?: boolean; indent?: number;
12
+ }
13
+ /** Labels are chrome; values remain literal, multiline text unless explicitly typed as code. */
14
+ export interface ToolField { label: string; value: string; tone?: Tone }
15
+ export type ToolCode = { code: string; label?: string } & ({ language: string; path?: never } | { path: string; language?: never });
16
+ export interface ToolCommand { command: string; shell: CommandShell; label?: string }
17
+ export type ToolExpandedRow = string | ToolLine | ToolField | ToolCode | ToolCommand | Component;
18
+ export type ToolExpansion = ToolExpandedRow[] | Component;
19
+ export interface ToolView<A, D> {
20
+ call(args: A): ToolLine;
21
+ collapsed(details: D, args: A, text: string): ToolLine;
22
+ /** Sensitive fields can be echoed by diagnostics; transform text before expansion/error display. */
23
+ redact?(args: A, text: string, isError: boolean): string;
24
+ /** A tool can label a rejection and supply its diagnostic separately from model guidance. */
25
+ error?(details: D | undefined): { summary: string; diagnostic?: string };
26
+ /** Components are trusted presentation; their producer sanitizes input before generating ANSI. */
27
+ expanded?(details: D, args: A, text: string, theme: Theme): ToolExpansion;
28
+ }
29
+ const literal = (text: string) => sanitizeText(text).replace(/\s+/g, ' ').trim();
30
+ function lineText(theme: Theme, line: ToolLine): string {
31
+ let title = literal(line.title);
32
+ if (line.strike) title = `\x1b[9m${title}\x1b[29m`;
33
+ const heading = [line.icon && theme.fg(line.tone ?? 'accent', literal(line.icon)),
34
+ title && theme.fg(line.titleTone ?? 'toolTitle', title)].filter(Boolean).join(' ');
35
+ return ' '.repeat(line.indent ?? 0) + [
36
+ heading,
37
+ line.summary && theme.fg('toolOutput', literal(line.summary)),
38
+ ...(line.meta ?? []).filter(Boolean).map(item => theme.fg(typeof item === 'string' ? 'dim' : item.tone,
39
+ literal(typeof item === 'string' ? item : item.text))),
40
+ ].filter(Boolean).join(' · ');
41
+ }
42
+ export function toolLine(theme: Theme, line: ToolLine, width: number): string {
43
+ return truncateToWidth(lineText(theme, line), width);
44
+ }
45
+ const bodyLine = (theme: Theme, line: ToolLine): Component => new Text(lineText(theme, line), 0, 0);
46
+ export function stateLine(state: string): Pick<ToolLine, 'icon' | 'tone'> {
47
+ const icon = ['completed', 'answered'].includes(state) ? '✔' : state === 'failed' ? '✘'
48
+ : ['stopped', 'skipped', 'cancelled'].includes(state) ? '⊘' : ['timed_out', 'limited'].includes(state) ? '⏱'
49
+ : state === 'queued' ? '⧗' : state.startsWith('waiting') ? '?' : '⟳';
50
+ return { icon, tone: stateTone(state) ?? (state === 'answered' ? 'success' : ['skipped', 'cancelled'].includes(state) ? 'dim' : 'accent') };
51
+ }
52
+ const plainText = (theme: Theme, text: string, tone: Tone = 'toolOutput') =>
53
+ new Text(sanitizeText(text).split('\n').map(line => theme.fg(tone, line)).join('\n'), 0, 0);
54
+
55
+ /** Body only: the host owns background, padding, expansion, mouse regions and images. */
56
+ class ToolBody implements Component {
57
+ private content?: Container;
58
+ private codes = new Map<number, CodeComponent>();
59
+ private caption!: ToolLine;
60
+ private rows?: () => ToolExpansion;
61
+ private theme!: Theme;
62
+ private visible?: () => boolean;
63
+ update(caption: ToolLine, rows: (() => ToolExpansion) | undefined, theme: Theme, visible?: () => boolean): void {
64
+ this.caption = caption; this.rows = rows; this.theme = theme; this.visible = visible;
65
+ this.content = undefined;
66
+ }
67
+ invalidate(): void { this.content?.invalidate(); this.content = undefined; for (const code of this.codes.values()) code.invalidate(); }
68
+ private body(): Container {
69
+ if (this.content) return this.content;
70
+ const content = new Container(), expanded = this.rows?.();
71
+ const rows = expanded === undefined ? [] : Array.isArray(expanded) ? expanded : [expanded];
72
+ rows.forEach((row, index) => {
73
+ if (typeof row === 'string') content.addChild(plainText(this.theme, row));
74
+ else if ('render' in row) content.addChild(row);
75
+ else if ('command' in row || 'code' in row) {
76
+ const language = 'command' in row ? row.shell : row.language ?? getLanguageFromPath(row.path);
77
+ if (row.label) content.addChild(plainText(this.theme, `${row.label}:`, 'muted'));
78
+ const source = 'command' in row ? row.command : row.code;
79
+ if (language) {
80
+ const spec: CodeSource = 'command' in row ? { code: source, language: row.shell, mode: 'command', theme: this.theme }
81
+ : { code: source, language, theme: this.theme };
82
+ const code = this.codes.get(index) ?? ('command' in row
83
+ ? commandComponent(source, row.shell, this.theme) as CodeComponent : new CodeComponent(spec));
84
+ code.setSource(spec); this.codes.set(index, code); content.addChild(code);
85
+ } else content.addChild(plainText(this.theme, source)); // A real path with no grammar is literal, not auto-detected.
86
+ } else if ('label' in row) {
87
+ const label = this.theme.fg('muted', `${literal(row.label)}: `);
88
+ const value = sanitizeText(row.value).split('\n').map(line => this.theme.fg(row.tone ?? 'toolOutput', line));
89
+ content.addChild(new Text(label + value.join('\n'), 0, 0));
90
+ } else content.addChild(bodyLine(this.theme, row));
91
+ });
92
+ for (const index of this.codes.keys()) if (index >= rows.length) this.codes.delete(index);
93
+ this.content = content; return content;
94
+ }
95
+ render(width: number): string[] {
96
+ if (this.visible && !this.visible()) return [];
97
+ return [...this.rows ? bodyLine(this.theme, this.caption).render(width)
98
+ : [toolLine(this.theme, this.caption, width)], ...this.body().render(width)];
99
+ }
100
+ }
101
+ // A session switch can discard a row without delivering a result. The renderer state
102
+ // owns the callback; the interval must not keep the discarded host row alive.
103
+ function redrawTimer(invalidate: WeakRef<() => void>): NodeJS.Timeout {
104
+ const timer = setInterval(() => {
105
+ const redraw = invalidate.deref();
106
+ if (redraw) redraw(); else clearInterval(timer);
107
+ }, 1000).unref();
108
+ return timer;
109
+ }
110
+
111
+ /** Shared state hides the call body once any result arrives, leaving one summary in the native Box. */
112
+ export function toolRenderers<A, D>(view: ToolView<A, D>, { timing }: { timing?: (ms: number) => string } = {}): ToolRenderers {
113
+ // Duration is the last meta item so it stays next to the summary instead of drifting to the far edge.
114
+ const timed = (caption: ToolLine, ms?: number): ToolLine => timing && ms !== undefined
115
+ ? { ...caption, meta: [...caption.meta ?? [], { text: timing(ms), tone: 'dim' }] } : caption;
116
+ const live = (state: { startedAt?: number }) => state.startedAt === undefined ? undefined : performance.now() - state.startedAt;
117
+ return {
118
+ renderCall(args, theme, ctx) {
119
+ const body = ctx.lastComponent instanceof ToolBody ? ctx.lastComponent : new ToolBody();
120
+ // The host builds the call slot before the result slot; defer visibility until render.
121
+ if (timing && ctx.executionStarted && !ctx.state.finished && ctx.state.startedAt === undefined) {
122
+ ctx.state.startedAt = performance.now();
123
+ ctx.state.invalidate = ctx.invalidate;
124
+ ctx.state.timer = redrawTimer(new WeakRef(ctx.invalidate));
125
+ }
126
+ body.update(timed(view.call(args as A), live(ctx.state)), undefined, theme, () => !ctx.state.finished);
127
+ return body;
128
+ },
129
+ renderResult(result, options, theme, ctx) {
130
+ // Partial output takes over immediately, not only after execution finishes.
131
+ ctx.state.finished = true;
132
+ if (timing && !options.isPartial) {
133
+ clearInterval(ctx.state.timer);
134
+ ctx.state.timer = ctx.state.invalidate = undefined;
135
+ }
136
+ const details = result.details as D, args = ctx.args as A;
137
+ const error = ctx.isError ? view.error?.(details) : undefined;
138
+ const raw = sanitizeText(error?.diagnostic ?? result.content.filter(item => item.type === 'text').map(item => item.text).join('\n'));
139
+ const text = view.redact?.(args, raw, ctx.isError) ?? raw;
140
+ const body = ctx.lastComponent instanceof ToolBody ? ctx.lastComponent : new ToolBody();
141
+ // Expanded errors show the full diagnostic below, so the caption repeats only a tool-supplied label.
142
+ const errorSummary = error?.summary ?? (options.expanded ? undefined : text.split('\n', 1)[0]);
143
+ const caption = ctx.isError ? { icon: '✘', tone: 'error' as const, title: view.call(args).title,
144
+ meta: errorSummary ? [{ text: errorSummary, tone: 'error' as const }] : [] }
145
+ : view.collapsed(details, args, text);
146
+ body.update(timed(caption, options.isPartial ? live(ctx.state) : ctx.durationMs), !options.expanded ? undefined
147
+ : ctx.isError ? () => [plainText(theme, text, 'error')]
148
+ : () => view.expanded?.(details, args, text, theme) ?? [text], theme);
149
+ return body;
150
+ },
151
+ };
152
+ }
@@ -0,0 +1,140 @@
1
+ import {
2
+ AssistantMessageComponent, UserMessageComponent, ToolExecutionComponent, CustomMessageComponent,
3
+ CompactionSummaryMessageComponent, BranchSummaryMessageComponent, BashExecutionComponent,
4
+ createReadToolDefinition, createWriteToolDefinition, createEditToolDefinition, createBashToolDefinition,
5
+ createPowerShellToolDefinition, createGrepToolDefinition, createFindToolDefinition, createLsToolDefinition,
6
+ getMarkdownTheme, keyHint, keyText, type CustomEntry, type EntryRenderer, type ExtensionRunner,
7
+ type SessionEntry, type Theme, type ToolRenderers, truncateTail,
8
+ } from "@earendil-works/pi-coding-agent";
9
+ import { Container, Spacer, type Component, type TUI } from "@earendil-works/pi-tui";
10
+
11
+ export type TranscriptRenderers = Pick<ExtensionRunner, 'getMessageRenderer' | 'getEntryRenderer'> & { theme: Theme };
12
+
13
+ // Pi does not export CustomEntryComponent. Keep entry chrome minimal and leave the
14
+ // actual content to the registered renderer, including entries that only show when expanded.
15
+ class RenderedEntry extends Container {
16
+ constructor(private entry: CustomEntry, private renderer: EntryRenderer, private theme: Theme) { super(); }
17
+ setExpanded(expanded: boolean): void {
18
+ const content = this.renderer(this.entry, { expanded, keyText, keyHint }, this.theme);
19
+ this.clear();
20
+ if (content) { this.addChild(new Spacer(1)); this.addChild(content); }
21
+ }
22
+ }
23
+
24
+ /** Uses public Pi components, including paired calls/results, rather than extracting plain text. */
25
+ export class Transcript extends Container {
26
+ private expanded = false;
27
+ private thinking = false;
28
+ private entries: SessionEntry[] = [];
29
+ private builtins: Map<string, ToolRenderers>;
30
+ private cache = new Map<string, { entry: SessionEntry; components: Component[]; calls: Map<string, ToolExecutionComponent> }>();
31
+ private results = new WeakMap<ToolExecutionComponent, SessionEntry>();
32
+ private arguments = new WeakMap<ToolExecutionComponent, unknown>();
33
+
34
+ constructor(private tui: TUI, private cwd: string, private renderer?: (name: string) => ToolRenderers | undefined,
35
+ private custom?: TranscriptRenderers) {
36
+ super();
37
+ this.builtins = new Map([
38
+ createReadToolDefinition(cwd), createWriteToolDefinition(cwd), createEditToolDefinition(cwd),
39
+ createBashToolDefinition(cwd), createPowerShellToolDefinition(cwd), createGrepToolDefinition(cwd),
40
+ createFindToolDefinition(cwd), createLsToolDefinition(cwd),
41
+ // Pi's heterogeneous renderer API erases individual tool parameter types.
42
+ ].map(tool => [tool.name, tool as unknown as ToolRenderers]));
43
+ }
44
+ setEntries(entries: SessionEntry[]): void { this.entries = entries; this.rebuild(); }
45
+ toggleTools(): void {
46
+ this.expanded = !this.expanded;
47
+ for (const component of this.children) {
48
+ if ('setExpanded' in component && typeof component.setExpanded === 'function') component.setExpanded(this.expanded);
49
+ }
50
+ }
51
+ toggleThinking(): void {
52
+ this.thinking = !this.thinking;
53
+ for (const component of this.children) if (component instanceof AssistantMessageComponent) component.setHideThinkingBlock(!this.thinking);
54
+ }
55
+
56
+ private customMessage(message: ConstructorParameters<typeof CustomMessageComponent>[0], theme: ReturnType<typeof getMarkdownTheme>): Component {
57
+ const component = new CustomMessageComponent(message, this.custom?.getMessageRenderer(message.customType), theme, 0);
58
+ component.setExpanded(this.expanded);
59
+ return component;
60
+ }
61
+
62
+ private rebuild(): void {
63
+ const theme = getMarkdownTheme();
64
+ const components: Component[] = [];
65
+ const calls = new Map<string, ToolExecutionComponent>();
66
+ const previousCalls = new Map([...this.cache.values()].flatMap(cached => [...cached.calls]));
67
+ const retained = new Set<string>();
68
+ for (const entry of this.entries) {
69
+ retained.add(entry.id);
70
+ const cached = this.cache.get(entry.id);
71
+ const result = entry.type === 'message' && entry.message.role === 'toolResult';
72
+ // Canonical Pi entries are immutable after append. Streaming tails are fresh synthetic
73
+ // entries, so their components update while stable Markdown/tools retain width caches.
74
+ if (cached?.entry === entry && !result) {
75
+ components.push(...cached.components); for (const [id, tool] of cached.calls) calls.set(id, tool);
76
+ continue;
77
+ }
78
+ const start = components.length, ownCalls = new Map<string, ToolExecutionComponent>();
79
+ const timestamp = Date.parse(entry.timestamp);
80
+ if (entry.type === "compaction") {
81
+ const component = new CompactionSummaryMessageComponent({ role: "compactionSummary", summary: entry.summary, tokensBefore: entry.tokensBefore, timestamp }, theme, 0);
82
+ component.setExpanded(this.expanded); components.push(component);
83
+ } else if (entry.type === "branch_summary") {
84
+ const component = new BranchSummaryMessageComponent({ role: "branchSummary", summary: entry.summary, fromId: entry.fromId, timestamp }, theme, 0);
85
+ component.setExpanded(this.expanded); components.push(component);
86
+ } else if (entry.type === "custom" && this.custom) {
87
+ const renderer = this.custom.getEntryRenderer(entry.customType);
88
+ if (renderer) {
89
+ const component = new RenderedEntry(entry, renderer, this.custom.theme);
90
+ component.setExpanded(this.expanded); components.push(component);
91
+ }
92
+ } else if (entry.type === "custom_message" && entry.display) {
93
+ components.push(this.customMessage({ ...entry, role: "custom", timestamp }, theme));
94
+ } else if (entry.type === "message") {
95
+ const message = entry.message;
96
+ if (message.role === "user") {
97
+ const text = typeof message.content === "string" ? message.content : message.content
98
+ .map(block => block.type === "text" ? block.text : "[image]").join("\n");
99
+ components.push(new UserMessageComponent(text, theme, 0));
100
+ } else if (message.role === "assistant") {
101
+ // Streaming entry replacements update native messages/tools rather than dropping
102
+ // renderer state and per-tool expansion on every provider event.
103
+ const previous = cached?.components[0];
104
+ const assistant = previous instanceof AssistantMessageComponent ? previous : new AssistantMessageComponent(message, !this.thinking, theme, undefined, 0);
105
+ if (assistant === previous) assistant.updateContent(message, entry.id.startsWith('stream:'));
106
+ components.push(assistant);
107
+ for (const block of message.content) {
108
+ if (block.type !== "toolCall") continue;
109
+ const retainedTool = previousCalls.get(block.id);
110
+ const tool = retainedTool ?? new ToolExecutionComponent(block.name, block.id, block.arguments, { showImages: false, outputPad: 0 }, this.renderer?.(block.name) ?? this.builtins.get(block.name), this.tui, this.cwd);
111
+ if (retainedTool && this.arguments.get(tool) !== block.arguments) tool.updateArgs(block.arguments);
112
+ if (!retainedTool) tool.setExpanded(this.expanded);
113
+ this.arguments.set(tool, block.arguments);
114
+ if (!entry.id.startsWith('stream:')) { tool.setArgsComplete(); tool.markExecutionStarted(); }
115
+ ownCalls.set(block.id, tool);
116
+ calls.set(block.id, tool); components.push(tool);
117
+ }
118
+ } else if (message.role === "toolResult") {
119
+ let tool = calls.get(message.toolCallId);
120
+ if (!tool) {
121
+ // A branch can retain a result after its call was compacted away.
122
+ tool = cached?.components[0] as ToolExecutionComponent | undefined ?? new ToolExecutionComponent(message.toolName, message.toolCallId, {}, { showImages: false, outputPad: 0 }, this.renderer?.(message.toolName) ?? this.builtins.get(message.toolName), this.tui, this.cwd);
123
+ tool.setExpanded(this.expanded); components.push(tool);
124
+ }
125
+ if (this.results.get(tool) !== entry) { tool.updateResult(message, entry.id.startsWith('stream:')); this.results.set(tool, entry); }
126
+ } else if (message.role === "custom" && message.display) {
127
+ components.push(this.customMessage(message, theme));
128
+ } else if (message.role === "bashExecution") {
129
+ const component = new BashExecutionComponent(message.command, this.tui, message.excludeFromContext, 0);
130
+ component.appendOutput(message.output);
131
+ component.setComplete(message.exitCode, message.cancelled, message.truncated ? { ...truncateTail(message.output), truncated: true } : undefined, message.fullOutputPath);
132
+ component.setExpanded(this.expanded); components.push(component);
133
+ }
134
+ }
135
+ this.cache.set(entry.id, { entry, components: components.slice(start), calls: ownCalls });
136
+ }
137
+ for (const id of this.cache.keys()) if (!retained.has(id)) this.cache.delete(id);
138
+ this.children = components;
139
+ }
140
+ }