pi-suite 0.0.0-stage → 0.3.1

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 +126 -0
  161. package/src/runtime/responses/payload.ts +101 -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,292 @@
1
+ import { getSelectListTheme, type ExtensionContext, type KeybindingsManager, type Theme } from '@earendil-works/pi-coding-agent';
2
+ import { Container, Input, Key, SelectList, Text, VStack, HStack, fuzzyFilter, matchesKey, truncateToWidth, visibleWidth,
3
+ type SelectItem, type KeyId, type SelectListLayoutOptions, type TUI, type Component } from '@earendil-works/pi-tui';
4
+ import { sanitizeText } from '../runtime/text.ts';
5
+ import { ScrollView } from './scroll.ts';
6
+ import type { Dock } from './dock.ts';
7
+ import { InlineInput } from './inline-input.ts';
8
+ import { ActionBar, type DetailAction } from './actions.ts';
9
+ import { commandFrame } from './frame.ts';
10
+ import { openReading, readingRows, readingText, readingWindow } from './reading.ts';
11
+ import { DoubleLeft, type ViewerNavigation } from './viewer/navigation.ts';
12
+ import { controlRows, cycle, divider, displayText, emptyRow, focusLabel, keyHint, paneHeading, readerHeading, recordStyle, selectedRow, separator, statusLabels, statusRow, titleRow, type BrowseChoice, type BrowseControl, type BrowseSelection, type DisplayText } from './browser-chrome.ts';
13
+ export type { BrowseChoice, BrowseControl, BrowseSelection } from './browser-chrome.ts';
14
+ import { detailsContent, type StructuredDetails } from './structured-details.ts';
15
+
16
+ export interface BrowseItem extends SelectItem { search?: string; status?: string; display?: DisplayText; details?: () => string | StructuredDetails | Component }
17
+ export type BrowseLayout = Omit<SelectListLayoutOptions, 'truncatePrimary'> & {
18
+ truncatePrimary?: (context: Parameters<NonNullable<SelectListLayoutOptions['truncatePrimary']>>[0] & {theme?: Theme}) => string;
19
+ };
20
+ /** Browsing is not tool pagination: active execution stays above even newly finished history. */
21
+ export function compareActivity<T extends { createdAt: string; startedAt?: string; lastUpdateAt?: string; endedAt?: string }>(a: T, b: T, active: (item: T) => boolean): number {
22
+ const time = (item: T) => (!active(item) && item.endedAt) || item.lastUpdateAt || item.startedAt || item.createdAt;
23
+ return Number(active(b)) - Number(active(a)) || time(b).localeCompare(time(a));
24
+ }
25
+ /** The list owns every command key; details is a reading mode and filter a text mode, both left with Esc. */
26
+ type BrowseFocus = 'list' | 'details' | 'filter';
27
+ export interface BrowseState { query: string; selected?: string; readers: Map<string, ScrollView>; focus?: BrowseFocus }
28
+ export const browseState = (): BrowseState => ({ query: '', readers: new Map() });
29
+ /** One page of a multi-page command: its own list state plus the shared page switcher. */
30
+ export interface BrowsePage { state: BrowseState; pages: BrowseChoice; navigation?: ViewerNavigation }
31
+ export interface BrowseOptions {
32
+ title: string; items: () => BrowseItem[]; state: BrowseState;
33
+ /** Page tabs live in the title row and switch with 1–9 or [ ]; they are not a focus stop. */
34
+ pages?: BrowseChoice;
35
+ page?: string;
36
+ /** Fixed scope for views such as the selected run's Jobs subtree. */
37
+ scope?: string;
38
+ /** Total before domain filters, when the page exposes a larger scope than items(). */
39
+ total?: () => number;
40
+ controls?: BrowseControl[];
41
+ subscribe?: (refresh: () => void) => () => void;
42
+ ticking?: () => boolean;
43
+ actions?: (item: BrowseItem, done: (value?: string) => void) => DetailAction[];
44
+ /** Enter always resolves the selected value; pages only name what that opens. */
45
+ open?: string;
46
+ selection?: (item: BrowseItem) => BrowseSelection;
47
+ navigation?: ViewerNavigation;
48
+ layout?: BrowseLayout;
49
+ }
50
+
51
+ /** A shared native list owns selection identities; details never become another data source. */
52
+ export class BrowserView extends Container {
53
+ focused = true;
54
+ readonly capturesViewportInput = true;
55
+ private input = new Input({ prompt: '' });
56
+ private list!: SelectList;
57
+ private items: BrowseItem[] = [];
58
+ private total = 0;
59
+ private fingerprint = '';
60
+ private visibleRows = 8;
61
+ private focus: BrowseFocus;
62
+ private bar: ActionBar;
63
+ private composer: InlineInput;
64
+ private doubleLeft = new DoubleLeft();
65
+ private actionOwner?: string;
66
+ private reader?: ScrollView;
67
+ private leftWidth = 0;
68
+ private refreshTimer?: ReturnType<typeof setTimeout>;
69
+ private clock?: ReturnType<typeof setInterval>;
70
+ private unsubscribe?: () => void;
71
+
72
+ constructor(private tui: TUI, private options: BrowseOptions, private done: (value?: string) => void, private theme?: Theme, keys?: KeybindingsManager) {
73
+ super();
74
+ this.focus = options.state.focus ?? 'list';
75
+ this.composer = new InlineInput(() => tui.requestRender(), theme, tui, keys);
76
+ this.bar = new ActionBar(() => this.actions(), request => this.composer.open(request));
77
+ this.input.setValue(options.state.query);
78
+ this.update();
79
+ // Streaming events share one render request; elapsed-time ticks only read live snapshots.
80
+ this.unsubscribe = options.subscribe?.(() => {
81
+ this.refreshTimer ??= setTimeout(() => { this.refreshTimer = undefined; tui.requestRender(); }, 40);
82
+ });
83
+ if (options.ticking) {
84
+ this.clock = setInterval(() => { if (options.ticking!()) tui.requestRender(); }, 1000);
85
+ this.clock.unref();
86
+ }
87
+ }
88
+ dispose(): void {
89
+ this.doubleLeft.reset(); this.composer.dispose(); this.unsubscribe?.(); clearTimeout(this.refreshTimer); clearInterval(this.clock);
90
+ for (const reader of this.options.state.readers.values()) reader.dispose();
91
+ }
92
+ override invalidate(): void { this.list.invalidate(); this.reader?.invalidate(); }
93
+ getSelectedItem(): SelectItem | null { return this.list.getSelectedItem(); }
94
+ private selectedItem(): BrowseItem | undefined { return this.items.find(item => item.value === this.list?.getSelectedItem()?.value); }
95
+ private actions(): DetailAction[] {
96
+ const item = this.selectedItem();
97
+ return item ? this.options.actions?.(item, this.done) ?? [] : [];
98
+ }
99
+ private update(reset = false): void {
100
+ const oldIndex = this.items.findIndex(item => item.value === this.list?.getSelectedItem()?.value);
101
+ const all = this.options.items().map(item => ({ ...item, label: item.display ? displayText(item.display, this.theme) : sanitizeText(item.label).replace(/[\r\n\t]/g, ' '),
102
+ description: item.description === undefined ? undefined : sanitizeText(item.description).replace(/[\r\n\t]/g, ' ') }));
103
+ this.total = this.options.total?.() ?? all.length;
104
+ this.items = fuzzyFilter(all, this.options.state.query, item => item.search ?? `${item.label} ${item.description ?? ''}`);
105
+ const fingerprint = JSON.stringify([this.visibleRows, this.items.map(item => [item.value, item.label, item.description, item.status])]);
106
+ if (reset || fingerprint !== this.fingerprint || !this.list) {
107
+ const previous = reset ? undefined : this.list?.getSelectedItem()?.value ?? this.options.state.selected;
108
+ const index = this.items.findIndex(item => item.value === previous);
109
+ // Native SelectList still owns selection and scrolling. Its selectedText callback receives
110
+ // the complete visible row, so background and marker do not require a parallel renderer.
111
+ this.list = new SelectList(this.items, this.visibleRows, { ...getSelectListTheme(),
112
+ selectedText: text => selectedRow(text, this.leftWidth, this.theme, this.active('list')) }, {
113
+ ...this.options.layout, truncatePrimary: context => {
114
+ const text = this.options.layout?.truncatePrimary?.({...context, theme: this.theme}) ?? truncateToWidth(context.text, context.maxWidth, '');
115
+ return (context.item as BrowseItem).display ? text : recordStyle(text, (context.item as BrowseItem).status, this.theme);
116
+ },
117
+ });
118
+ this.list.setSelectedIndex(index >= 0 ? index : reset ? 0 : Math.max(0, Math.min(oldIndex, this.items.length - 1)));
119
+ this.list.onSelectionChange = () => this.changed();
120
+ this.list.onSelect = () => this.select();
121
+ this.list.onCancel = () => this.done();
122
+ this.fingerprint = fingerprint;
123
+ }
124
+ this.changed();
125
+ this.setFocus(this.focus);
126
+ }
127
+ private setFocus(focus: BrowseFocus): void {
128
+ this.focus = this.options.state.focus = focus === 'details' && !this.reader ? 'list' : focus;
129
+ if (this.focus !== 'list') this.bar.disarm();
130
+ }
131
+ private active(focus: BrowseFocus): boolean {
132
+ return this.focused && !this.composer.active && this.focus === focus && !(focus === 'details' && this.reader?.searching);
133
+ }
134
+ /** Native inputs own their cursor; the prefix consumes columns, never another layout row. */
135
+ private inputRow(label: string, width: number, active: boolean, render: (width: number) => string): string {
136
+ const prefix = `${focusLabel(label, active, this.theme)} `;
137
+ return truncateToWidth(prefix + render(Math.max(1, width - visibleWidth(prefix))), width);
138
+ }
139
+ private changed(): void {
140
+ const value = this.list.getSelectedItem()?.value;
141
+ this.options.state.selected = value;
142
+ // A confirmation belongs to one record. Moving selection cannot stop the next one.
143
+ if (value !== this.actionOwner) { this.bar.disarm(); this.actionOwner = value; }
144
+ const item = this.items.find(item => item.value === value);
145
+ if (!item?.details) { this.reader = undefined; return; }
146
+ // Each identity retains its own search and scroll when another row or action is opened.
147
+ const details = item.details();
148
+ const content = typeof details === 'string' ? new Text(sanitizeText(details), 0, 0)
149
+ : 'rows' in details ? detailsContent(details, this.theme) : details;
150
+ this.reader = this.options.state.readers.get(item.value);
151
+ if (this.reader) this.reader.setContent(content);
152
+ else { this.reader = new ScrollView(content); this.options.state.readers.set(item.value, this.reader); }
153
+ }
154
+ private select(): void { const value = this.list.getSelectedItem()?.value; if (value !== undefined) this.done(value); }
155
+ private setQuery(query: string): void { this.input.setValue(query); this.options.state.query = query; this.update(true); }
156
+ private status(width: number): string {
157
+ const { pages, controls = [], state, selection } = this.options, item = this.selectedItem();
158
+ const page = pages ? pages.items().find(page => page.value === pages.selected())?.label ?? pages.selected() : this.options.page ?? 'List';
159
+ // The new-output hint belongs to the Details heading; the status row keeps its width for page and selection.
160
+ return statusRow(width, page, [...this.options.scope ? [this.options.scope] : [], ...statusLabels(controls), ...state.query ? [`/${state.query}`] : [], `${this.items.length}/${this.total}`],
161
+ item && (selection?.(item) ?? { name: item.label }), this.theme);
162
+ }
163
+ private page(): string {
164
+ return this.options.pages ? this.options.pages.items().find(page => page.value === this.options.pages!.selected())?.label ?? this.options.pages.selected()
165
+ : this.options.page ?? this.options.title;
166
+ }
167
+ private empty(): string { return emptyRow(this.page(), this.options.controls ?? [], this.options.state.query, this.options.pages, this.theme); }
168
+ private firstPage(): boolean {
169
+ const { pages } = this.options;
170
+ return !pages || pages.items()[0]?.value === pages.selected();
171
+ }
172
+ private navigation(): string {
173
+ const hint = (key: string, action: string) => keyHint(key, action, this.theme);
174
+ if (this.focus === 'filter') return `Type to filter · ${hint('↑↓', 'select')} · ${hint('Enter', 'keep')} · ${hint('Esc', 'clear')}`;
175
+ const { pages, controls = [] } = this.options;
176
+ const firstPage = this.firstPage();
177
+ const close = this.options.navigation && firstPage ? [hint('←←', 'close')] : [];
178
+ if (this.focus === 'details') return [...close,
179
+ hint('Tab/Esc', 'list'), hint('↑↓ PgUp PgDn', 'scroll'), hint('/', 'search'), hint('n/N', 'next')].join(' · ');
180
+ return [...close, hint('Esc', this.options.state.query ? 'clear filter' : this.options.navigation ? 'back' : 'close'),
181
+ ...pages ? [hint(`1-${Math.min(9, pages.items().length)} / ${firstPage ? '→' : '← →'} / [ ]`, 'page')] : [],
182
+ ...controls.map(control => hint(control.key, control.label.toLowerCase())), hint('/', 'filter'), hint('Tab', 'details')].join(' · ');
183
+ }
184
+ private help(): string {
185
+ const confirmation = this.bar.hint(this.theme);
186
+ if (confirmation) return confirmation;
187
+ if (!this.items.length) return this.empty();
188
+ // Reading and text modes do not own record shortcuts; advertise only keys they can execute.
189
+ if (this.focus === 'filter') return [keyHint('Enter', 'keep filter', this.theme), keyHint('Esc', 'clear filter', this.theme)].join(' · ');
190
+ return [keyHint('Enter', (this.options.open ?? 'open').toLowerCase(), this.theme),
191
+ ...this.focus === 'list' ? [this.bar.render(this.theme)] : []].filter(Boolean).join(' · ');
192
+ }
193
+ override render(width: number): string[] {
194
+ const total = readingRows(this.tui);
195
+ this.update();
196
+ this.composer.focused = this.focused;
197
+ this.input.focused = this.active('filter');
198
+ if (this.reader) this.reader.search.focused = this.focused && !this.composer.active && this.focus === 'details' && this.reader.searching;
199
+ const header = [titleRow(this.options.title, this.options.pages, width, this.theme, this.options.page), ...controlRows(this.options.controls ?? [], width, this.theme)];
200
+ const filter = this.focus === 'filter' || this.options.state.query;
201
+ const headerRows = 2 + header.length + Number(Boolean(filter));
202
+ const composerRows = this.composer.active && this.composer.multiline
203
+ ? this.composer.renderRows(width, Math.max(1, total - headerRows - 5)) : [];
204
+ const footerRows = composerRows.length || 1;
205
+ const height = Math.max(0, total - headerRows - footerRows - 3);
206
+ const wide = width >= 80;
207
+ this.leftWidth = wide ? Math.min(52, Math.floor(width * 0.45)) : width;
208
+ const listHeight = wide ? height : this.reader ? Math.min(height, this.focus === 'details' ? 2 : Math.max(2, Math.floor(height / 2))) : height;
209
+ this.visibleRows = Math.max(1, listHeight - 1);
210
+ this.update();
211
+ const listLines = readingWindow([paneHeading('List', this.leftWidth, this.active('list'), this.theme),
212
+ ...this.items.length ? this.list.render(this.leftWidth) : [this.empty()]], listHeight);
213
+ const detailsHeight = wide ? height : height - listHeight;
214
+ const detailsWidth = wide ? width - this.leftWidth - 3 : width;
215
+ const detailBody = this.reader?.viewport(detailsWidth, Math.max(0, detailsHeight - 1), () => this.tui.requestRender()) ?? [];
216
+ const detailLines = readingWindow([this.reader ? readerHeading('Details', this.reader.position, this.reader.hasNewOutput, detailsWidth, this.theme, this.active('details'))
217
+ : paneHeading('Details', detailsWidth, false, this.theme), ...detailBody], detailsHeight);
218
+ // HStack combines already-bounded native list/reader output. It does not measure
219
+ // a live ScrollView twice at different widths or maintain another scroll offset.
220
+ const body = wide ? new HStack([
221
+ {component: readingText(() => listLines), basis: this.leftWidth, shrink: 0},
222
+ {component: readingText(() => readingWindow([], height).map(() => divider(' │ ', this.theme))), basis: 3, shrink: 0},
223
+ {component: readingText(() => detailLines), basis: detailsWidth, shrink: 0},
224
+ ]).render(width) : [...listLines, ...this.reader ? detailLines : []];
225
+ const navigation = this.composer.active ? composerRows.length ? composerRows : [this.inputRow('Input', width, this.focused, space => this.composer.render(space) ?? '')]
226
+ : this.reader?.searching && this.focus === 'details' ? this.textInput('Search', this.reader.search, width) : [this.navigation()];
227
+ const border = commandFrame(width, [], this.theme)[0];
228
+ const frame = new VStack([
229
+ readingText(() => [border, ...header, ...filter ? this.textInput('Filter:', this.input, width) : [], this.status(width)]),
230
+ readingText(() => body), readingText(() => [separator(width, this.theme), ...navigation,
231
+ this.composer.active ? this.composer.help() : this.composer.render(width) ?? this.help(), border]),
232
+ ]);
233
+ this.options.state.focus = this.focus;
234
+ return readingWindow(frame.render(width), total);
235
+ }
236
+ /** Native inputs still own keyboard editing and their cursor; labels consume only columns. */
237
+ private textInput(label: string, input: Input, room: number): string[] {
238
+ return [this.inputRow(label, room, Boolean(input.focused), width => input.focused ? input.render(width)[0] ?? '' : truncateToWidth(input.getValue(), width))];
239
+ }
240
+ handleInput(data: string): void {
241
+ const { navigation } = this.options;
242
+ const canClose = this.firstPage() && !this.composer.active && this.focus !== 'filter' && !this.reader?.searching;
243
+ if (!canClose) this.doubleLeft.reset();
244
+ if (this.composer.handleInput(data)) { this.bar.disarm(); return; }
245
+ if (navigation && canClose && this.doubleLeft.handle(data)) {
246
+ navigation.close(); this.bar.disarm(); this.done(); return;
247
+ }
248
+ this.update();
249
+ const nav = [Key.up, Key.down, Key.pageUp, Key.pageDown].some(key => matchesKey(data, key));
250
+ if (this.focus !== 'list') this.bar.disarm();
251
+ if (this.focus === 'details') {
252
+ if (this.reader?.searching) this.reader.handleInput(data);
253
+ else if (matchesKey(data, Key.escape) || matchesKey(data, Key.tab)) this.focus = 'list';
254
+ else if (matchesKey(data, Key.enter)) this.select();
255
+ else this.reader?.handleInput(data);
256
+ } else if (this.focus === 'filter') {
257
+ // Enter keeps the query and returns command keys to the list; Esc discards it.
258
+ if (matchesKey(data, Key.escape)) { this.setQuery(''); this.focus = 'list'; }
259
+ else if (matchesKey(data, Key.enter) || matchesKey(data, Key.tab)) this.focus = 'list';
260
+ else if (nav) this.list.handleInput(data);
261
+ else { this.input.handleInput(data); this.options.state.query = this.input.getValue(); this.update(true); }
262
+ } else this.listInput(data, nav);
263
+ this.setFocus(this.focus);
264
+ this.tui.requestRender();
265
+ }
266
+ /** Enter is owned by the frame, never by a record action. */
267
+ private listInput(data: string, nav: boolean): void {
268
+ const { pages, controls = [] } = this.options;
269
+ if (matchesKey(data, Key.enter)) { this.bar.disarm(); this.select(); return; }
270
+ // ActionBar clears a pending confirmation on any key it does not own.
271
+ if (this.bar.handleInput(data)) return;
272
+ if (matchesKey(data, Key.escape)) { if (this.options.state.query) this.setQuery(''); else this.done(); }
273
+ else if (matchesKey(data, Key.tab)) { if (this.reader) this.focus = 'details'; }
274
+ else if (matchesKey(data, '/')) this.focus = 'filter';
275
+ else if (nav) this.list.handleInput(data);
276
+ else if (pages && (matchesKey(data, ']') || matchesKey(data, Key.right))) cycle(pages, this.done);
277
+ // '[' still wraps; Left is reserved for the close gesture on the first page.
278
+ else if (pages && (matchesKey(data, '[') || (!this.firstPage() && matchesKey(data, Key.left)))) cycle(pages, this.done, -1);
279
+ else {
280
+ const page = pages?.items().find((_page, index) => index < 9 && matchesKey(data, String(index + 1) as KeyId));
281
+ const control = controls.find(control => matchesKey(data, control.key));
282
+ if (page && page.value !== pages!.selected()) pages!.select(page.value, this.done);
283
+ else if (control) cycle(control, this.done);
284
+ }
285
+ }
286
+ }
287
+
288
+ export async function browse(ctx: ExtensionContext, dock: Dock, options: BrowseOptions): Promise<string | undefined> {
289
+ dock.setDetail(true);
290
+ try { return await openReading<string | undefined>(ctx, (tui, theme, keys, done) => new BrowserView(tui, options, done, theme, keys)); }
291
+ finally { dock.setDetail(false); }
292
+ }
@@ -0,0 +1,111 @@
1
+ import { getMarkdownTheme, type ExtensionContext, type KeybindingsManager, type Theme } from '@earendil-works/pi-coding-agent';
2
+ import { Container, Key, Markdown, Text, VStack, matchesKey, type Component, type TUI } from '@earendil-works/pi-tui';
3
+ import type { Dock } from './dock.ts';
4
+ import { ScrollView } from './scroll.ts';
5
+ import { ActionBar, keyHelp, type DetailAction } from './actions.ts';
6
+ export type { DetailAction } from './actions.ts';
7
+ import { readerHeading, keyHint, separator } from './browser-chrome.ts';
8
+ import { InlineInput } from './inline-input.ts';
9
+ import { commandFrame } from './frame.ts';
10
+ import { openReading, readingRows, readingText, readingWindow } from './reading.ts';
11
+ import { sanitizeText } from '../runtime/text.ts';
12
+ import { DoubleLeft, type ViewerNavigation } from './viewer/navigation.ts';
13
+ import { detailsContent, plainDetailLines, type StructuredDetails } from './structured-details.ts';
14
+
15
+ export interface DetailOptions {
16
+ title?: boolean;
17
+ /** One/two information rows; the shared frame supplies the separator and settles position. */
18
+ bottom?: (width: number) => string[];
19
+ navigation?: ViewerNavigation;
20
+ keys?: KeybindingsManager;
21
+ }
22
+
23
+ /** A shared reading frame budgets native input, metadata and actions before laying out its body. */
24
+ export class DetailsView extends Container {
25
+ focused = true;
26
+ readonly capturesViewportInput = true;
27
+ readonly reader: ScrollView;
28
+ private bar: ActionBar;
29
+ private composer: InlineInput;
30
+ private doubleLeft = new DoubleLeft();
31
+ private readonly scrollChanged = () => this.readingChanged();
32
+ readonly actions: DetailAction[];
33
+ constructor(private tui: TUI, private title: () => string, content: Component, private done: () => void, actions: DetailAction[] = [], reader?: ScrollView, private theme?: Theme, private options: DetailOptions = {}) {
34
+ super();
35
+ this.reader = reader ?? new ScrollView(content);
36
+ this.reader.onScroll = this.scrollChanged;
37
+ this.actions = actions;
38
+ this.composer = new InlineInput(() => tui.requestRender(), theme, tui, options.keys);
39
+ this.bar = new ActionBar(() => this.actions, request => this.composer.open(request));
40
+ }
41
+ override render(width: number): string[] {
42
+ const total = readingRows(this.tui);
43
+ this.composer.focused = this.focused;
44
+ this.reader.search.focused = this.focused && !this.composer.active && this.reader.searching;
45
+ const shortcuts = this.bar.render(this.theme);
46
+ const help = this.bar.hint(this.theme) ?? [...this.options.navigation ? [keyHint('←←', 'close', this.theme)] : [],
47
+ keyHint('Esc', 'back', this.theme), shortcuts, keyHint('↑↓ PgUp PgDn Home/End', 'scroll', this.theme),
48
+ keyHint('/', 'search', this.theme), keyHint('n/N', 'next', this.theme)].filter(Boolean).join(' · ');
49
+ const topRows = Number(this.options.title !== false);
50
+ // Measure the native document once. Metadata includes position, so it must be
51
+ // re-read after updateLayout has applied follow-end/clamp to this same document.
52
+ const lines = this.reader.render(width);
53
+ let information = this.options.bottom?.(width).slice(0, 2) ?? [];
54
+ let footer: string[] = [], bodyRows = 0;
55
+ const inline = this.composer.render(width);
56
+ for (let pass = 0; pass < 2; pass++) {
57
+ const informationRows = this.options.bottom ? 1 + information.length : 0;
58
+ const footerLimit = Math.max(1, total - 2 - topRows - informationRows - 2);
59
+ footer = this.composer.active
60
+ ? [...this.composer.renderRows(width, Math.max(1, footerLimit - 1)), this.composer.help()]
61
+ : this.reader.searching ? this.reader.search.render(width) : keyHelp(inline ?? help, width).slice(0, footerLimit);
62
+ bodyRows = Math.max(0, total - 3 - topRows - informationRows - footer.length);
63
+ this.reader.updateLayout(lines.length, bodyRows, () => this.tui.requestRender());
64
+ const settled = this.options.bottom?.(width).slice(0, 2) ?? [];
65
+ const sameRows = settled.length === information.length;
66
+ information = settled;
67
+ // One/two-line position metadata needs at most one correction: reclaiming a
68
+ // row can only shorten its clamped/following position, reserving one lengthens it.
69
+ if (sameRows) break;
70
+ }
71
+ const border = () => commandFrame(width, [], this.theme)[0];
72
+ const body = readingWindow(lines.slice(this.reader.offset, this.reader.offset + bodyRows), bodyRows);
73
+ const top = [border(), ...topRows ? [readerHeading(this.title(), this.reader.position, this.reader.hasNewOutput, width, this.theme)] : []];
74
+ const metadata = this.options.bottom ? [separator(width, this.theme), ...information] : [];
75
+ const frame = new VStack([readingText(() => top), readingText(() => body), readingText(() => metadata),
76
+ readingText(() => [separator(width, this.theme), ...footer, border()])]);
77
+ return readingWindow(frame.render(width), total);
78
+ }
79
+ get textInputActive(): boolean { return this.composer.active || this.reader.searching; }
80
+ protected readingChanged(): void {}
81
+ dispose(): void {
82
+ this.doubleLeft.reset(); this.composer.dispose();
83
+ // A replacement view can already own the retained reader when an old factory
84
+ // completes. Only its current owner may detach scroll/layout callbacks.
85
+ if (this.reader.onScroll === this.scrollChanged) this.reader.dispose();
86
+ }
87
+ override invalidate(): void { this.reader.invalidate(); }
88
+ handleInput(data: string): void {
89
+ // Text and search own all direction keys, including both Left presses.
90
+ if (this.composer.active) this.doubleLeft.reset();
91
+ if (this.composer.handleInput(data)) { this.bar.disarm(); return; }
92
+ if (this.reader.searching) { this.doubleLeft.reset(); this.bar.disarm(); this.reader.handleInput(data); }
93
+ else if (this.options.navigation && this.doubleLeft.handle(data)) {
94
+ this.options.navigation.close(); this.bar.disarm(); this.done();
95
+ } else if (matchesKey(data, Key.escape)) { this.bar.disarm(); this.done(); }
96
+ else if (!this.bar.handleInput(data)) this.reader.handleInput(data);
97
+ this.tui.requestRender();
98
+ }
99
+ }
100
+
101
+ export async function showDetails(ctx: ExtensionContext, dock: Dock, title: string, content: string | StructuredDetails, format: 'markdown' | 'text' = 'markdown', navigation?: ViewerNavigation): Promise<void> {
102
+ if (ctx.mode !== 'tui') {
103
+ ctx.ui.notify(`${title}\n${typeof content === 'string' ? content : plainDetailLines(content).join('\n')}`); return;
104
+ }
105
+ dock.setDetail(true);
106
+ try {
107
+ await openReading<void>(ctx, (tui, theme, keys, done) => new DetailsView(tui, () => title,
108
+ typeof content !== 'string' ? detailsContent(content, theme) : format === 'text' ? new Text(sanitizeText(content), 0, 0) : new Markdown(content, 0, 0, getMarkdownTheme()),
109
+ done, [], undefined, theme, {navigation, keys}));
110
+ } finally { dock.setDetail(false); }
111
+ }
@@ -0,0 +1,14 @@
1
+ import { truncateToWidth, visibleWidth } from '@earendil-works/pi-tui';
2
+ import type { Theme } from '@earendil-works/pi-coding-agent';
3
+ import { displayText, type DisplayText } from '../browser-chrome.ts';
4
+
5
+ /** The domain orders metric omissions; the shared UI decides which suffix fits a real cell. */
6
+ export function executionRow(name: string, suffix: DisplayText, compactSuffixes: readonly DisplayText[] | undefined, width: number, theme?: Theme): string {
7
+ const suffixes = [suffix, ...compactSuffixes ?? []].map(value => displayText(value, theme));
8
+ const nameSpace = compactSuffixes ? Math.min(8, visibleWidth(name)) + 1 : 0;
9
+ const tail = truncateToWidth(suffixes.find(text => visibleWidth(text) <= width - nameSpace) ?? suffixes.at(-1)!, width);
10
+ if (!tail) return truncateToWidth(name, width);
11
+ const titleWidth = Math.max(0, width - visibleWidth(tail) - 1);
12
+ const text = truncateToWidth(name, titleWidth, '…');
13
+ return (titleWidth ? text + ' '.repeat(titleWidth - visibleWidth(text) + 1) : '') + tail;
14
+ }
@@ -0,0 +1,78 @@
1
+ import type { DockRow } from '../dock.ts';
2
+
3
+ /** Gaps stay at their actual sibling positions, including gaps before a selected tail. */
4
+ function withGaps(rows: DockRow[], ids: Set<string>, rootUnit: string): DockRow[] {
5
+ const children = new Map<string, DockRow[]>();
6
+ for (const row of rows) if (row.parentId) {
7
+ const siblings = children.get(row.parentId) ?? [];
8
+ siblings.push(row); children.set(row.parentId, siblings);
9
+ }
10
+ const result: DockRow[] = [];
11
+ const append = (siblings: DockRow[], parentId?: string): void => {
12
+ if (!siblings.some(row => ids.has(row.id))) return;
13
+ let gap: DockRow[] = [], start = 0;
14
+ const flush = (end: number): void => {
15
+ if (gap.length === 1) result.push(gap[0]); // Showing one object costs the same row as an overflow hint.
16
+ else if (gap.length) result.push({id: `overflow:${parentId ?? ''}:${start}`, parentId, priority: 0, selectable: false,
17
+ text: `${start === 0 ? '↑' : end === siblings.length ? '↓' : '↕'} … ${gap.length} more ${parentId ? 'items' : rootUnit}`});
18
+ gap = [];
19
+ };
20
+ siblings.forEach((row, index) => {
21
+ if (!ids.has(row.id)) { if (!gap.length) start = index; gap.push(row); return; }
22
+ flush(index); result.push(row);
23
+ append(children.get(row.id) ?? [], row.id);
24
+ });
25
+ flush(siblings.length);
26
+ };
27
+ append(rows.filter(row => !row.parentId));
28
+ return result;
29
+ }
30
+
31
+ export interface DockWindow { rows: DockRow[]; compactHint?: string }
32
+ /** Priority selects idle membership; active navigation retains neighbours around the stable selected ID. */
33
+ export function dockWindow(input: DockRow[], capacity: number, selectedId?: string, rootUnit = 'items', gapHints = true): DockWindow {
34
+ // The root tail row joins selection at its own priority and, once reached, holds its row
35
+ // while lower rows compete for the rest. Its count is derived from the final membership, so
36
+ // roots trimmed after the reservation are counted instead of vanishing with a trimmed hint.
37
+ const tail = input.find(row => row.omitted !== undefined);
38
+ const rows = tail ? input.filter(row => row !== tail) : input;
39
+ const roots = rows.filter(row => !row.parentId).length;
40
+ const byId = new Map(rows.map(row => [row.id, row]));
41
+ const focusIndex = rows.findIndex(row => row.id === selectedId), focus = rows[focusIndex];
42
+ const ids = new Set<string>();
43
+ let reserved = false;
44
+ // While selecting, a reserved tail occupies its row even at zero; the final window drops it then.
45
+ const visible = (final = false): DockRow[] => {
46
+ const shown = gapHints ? withGaps(rows, ids, rootUnit) : rows.filter(row => ids.has(row.id));
47
+ if (!reserved) return shown;
48
+ const omitted = tail!.omitted! + roots - [...ids].filter(id => !byId.get(id)!.parentId).length;
49
+ return omitted || !final ? [...shown, {...tail!, text: `… ${omitted} more ${rootUnit}`}] : shown;
50
+ };
51
+ const add = (row: DockRow): string[] => {
52
+ const parent = row.parentId ? byId.get(row.parentId) : undefined;
53
+ if (row.parentId && !parent) return [];
54
+ const added = [parent, row].filter((item): item is DockRow => !!item && !ids.has(item.id)).map(item => item.id);
55
+ added.forEach(id => ids.add(id)); return added;
56
+ };
57
+ if (focus) {
58
+ add(focus);
59
+ if (visible().length > capacity) {
60
+ // Tiny viewports cannot fit ancestry plus both gaps. Keep the real selected object,
61
+ // and put exact omitted-row counts in the header rather than hiding it or lying about direction.
62
+ const hint = [focusIndex ? `↑${focusIndex}` : '', rows.length - focusIndex - 1 ? `↓${rows.length - focusIndex - 1}` : ''].filter(Boolean).join(' ');
63
+ return {rows: [focus], compactHint: hint};
64
+ }
65
+ }
66
+ const order = focus ? input.indexOf(focus) : -1;
67
+ const ranked = input.map((row, index) => ({row, index})).sort((a, b) => focus
68
+ ? Math.abs(a.index - order) - Math.abs(b.index - order) || a.index - b.index
69
+ : b.row.priority - a.row.priority);
70
+ for (const {row} of ranked) {
71
+ const added = row === tail ? [] : add(row);
72
+ if (row === tail) reserved = true;
73
+ const count = visible().length;
74
+ if (count > capacity) { if (row === tail) reserved = false; added.forEach(id => ids.delete(id)); }
75
+ else if (count === capacity) break;
76
+ }
77
+ return {rows: visible(true)};
78
+ }