@0xkahi/pi-qol 0.1.0 → 1.0.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 (32) hide show
  1. package/README.md +13 -0
  2. package/assets/config.schema.json +23 -0
  3. package/package.json +4 -4
  4. package/src/codemap.md +3 -2
  5. package/src/config-loader.ts +4 -0
  6. package/src/constants.ts +1 -0
  7. package/src/extensions/auto-session-name/title-generator.ts +1 -1
  8. package/src/extensions/codemap.md +9 -2
  9. package/src/extensions/context-view/capture.ts +394 -0
  10. package/src/extensions/context-view/codemap.md +28 -0
  11. package/src/extensions/context-view/constants.ts +4 -0
  12. package/src/extensions/context-view/context-view-controller.ts +67 -0
  13. package/src/extensions/context-view/index.ts +120 -0
  14. package/src/extensions/context-view/measure.ts +307 -0
  15. package/src/extensions/context-view/model.ts +207 -0
  16. package/src/extensions/context-view/ui/context-view-dialog.ts +81 -0
  17. package/src/extensions/context-view/ui/injections-model.ts +257 -0
  18. package/src/extensions/context-view/ui/injections-view.ts +396 -0
  19. package/src/extensions/context-view/ui/layout.ts +88 -0
  20. package/src/extensions/context-view/ui/navigation.ts +37 -0
  21. package/src/extensions/context-view/ui/skill-preview.ts +82 -0
  22. package/src/extensions/context-view/ui/usage-map.ts +133 -0
  23. package/src/extensions/context-view/ui/usage-view.ts +734 -0
  24. package/src/extensions/context-view/usage.ts +432 -0
  25. package/src/extensions/model-select/index.ts +12 -6
  26. package/src/extensions/model-select/model-select-dialog.ts +2 -1
  27. package/src/extensions/model-select/types.ts +2 -0
  28. package/src/index.ts +2 -0
  29. package/src/schemas/codemap.md +2 -2
  30. package/src/schemas/config.schema.ts +3 -0
  31. package/src/schemas/context-view.config.schema.ts +13 -0
  32. package/src/schemas/model-select.config.schema.ts +3 -1
@@ -0,0 +1,396 @@
1
+ /** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
2
+ /**
3
+ * Focused `/context injections` view: hierarchical Initial snapshot rows. The
4
+ * Runtime label stays hidden until the runtime-inspection roadmap step.
5
+ */
6
+ import type { Theme } from '@earendil-works/pi-coding-agent';
7
+ import { Key, matchesKey, visibleWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
8
+
9
+ import type { InitialSnapshot, InjectionItem } from '../model';
10
+ import {
11
+ buildInjectionRows,
12
+ collectItemsById,
13
+ type InjectionRow,
14
+ ListNavigator,
15
+ normalizeInlineText,
16
+ normalizePreviewText,
17
+ PreviewScroller,
18
+ } from './injections-model';
19
+ import {
20
+ BODY_INDENT,
21
+ calculateViewport,
22
+ DEFAULT_TERMINAL_ROWS,
23
+ fitLine,
24
+ fitToTerminalHeight,
25
+ hintRow,
26
+ normalizeTerminalRows,
27
+ STEP_KEY_HINT,
28
+ spreadLine,
29
+ wrapDescriptionLines,
30
+ } from './layout';
31
+ import type { NavigationAction } from './navigation';
32
+
33
+ const LIST_FIXED_LINE_COUNT = 10;
34
+ const PREVIEW_FIXED_LINE_COUNT = 8;
35
+ const LIST_DESCRIPTION = 'Injections into the model context for the first turn, with token estimates.';
36
+ const CURSOR_COLUMN_WIDTH = 2;
37
+ const MAX_TOKEN_VALUE_COLUMN = 54;
38
+ const TOKEN_LEADER_GAP = 4;
39
+
40
+ /** Everything the Injections view renders. */
41
+ export interface InjectionsViewInput {
42
+ readonly snapshot: InitialSnapshot;
43
+ readonly degradedReason?: string;
44
+ }
45
+
46
+ /** Shared token-value column measured after the fixed cursor column. */
47
+ interface InjectionColumns {
48
+ readonly value: number;
49
+ }
50
+
51
+ /** Stateful Injections tab retained by ContextViewDialog. */
52
+ export class InjectionsView {
53
+ private readonly theme: Theme;
54
+ private readonly input: InjectionsViewInput;
55
+ private readonly done: (result: undefined) => void;
56
+ private readonly getTerminalRows: () => number;
57
+ private readonly rows: InjectionRow[];
58
+ private readonly navigator: ListNavigator;
59
+ private readonly itemsById: Map<string, InjectionItem>;
60
+ private readonly previewScroller = new PreviewScroller();
61
+ private previewItem: InjectionItem | undefined;
62
+ private previewLines: string[] | undefined;
63
+ private previewWrapWidth: number | undefined;
64
+ private cachedWidth: number | undefined;
65
+ private cachedTerminalRows: number | undefined;
66
+ private cachedLines: string[] | undefined;
67
+
68
+ public constructor(
69
+ theme: Theme,
70
+ input: InjectionsViewInput,
71
+ done: (result: undefined) => void,
72
+ getTerminalRows: () => number = () => process.stdout.rows ?? DEFAULT_TERMINAL_ROWS,
73
+ ) {
74
+ this.theme = theme;
75
+ this.input = input;
76
+ this.done = done;
77
+ this.getTerminalRows = getTerminalRows;
78
+ this.rows = buildInjectionRows(input.snapshot);
79
+ this.navigator = new ListNavigator(this.rows.length, 1, this.rows.length - 2);
80
+ this.itemsById = collectItemsById(input.snapshot);
81
+ }
82
+
83
+ public handleInput(data: string): void {
84
+ if (this.previewItem !== undefined) {
85
+ this.handlePreviewInput(data);
86
+ return;
87
+ }
88
+ if (matchesKey(data, Key.escape) || data === 'q') {
89
+ this.done(undefined);
90
+ return;
91
+ }
92
+ if (matchesKey(data, Key.enter)) {
93
+ this.openPreview();
94
+ }
95
+ }
96
+
97
+ /** Apply semantic movement in either the hierarchy or its preview. */
98
+ public handleNavigation(action: NavigationAction): void {
99
+ if (this.previewItem !== undefined) {
100
+ const changed =
101
+ action === 'step-back'
102
+ ? this.previewScroller.scrollBy(-1)
103
+ : action === 'step-forward'
104
+ ? this.previewScroller.scrollBy(1)
105
+ : action === 'page-back'
106
+ ? this.previewScroller.page(-1)
107
+ : action === 'page-forward'
108
+ ? this.previewScroller.page(1)
109
+ : action === 'first'
110
+ ? this.previewScroller.scrollTo(0)
111
+ : this.previewScroller.scrollTo(this.previewScroller.maxOffset);
112
+ if (changed) this.clearCache();
113
+ return;
114
+ }
115
+
116
+ const changed =
117
+ action === 'step-back'
118
+ ? this.navigator.moveBy(-1)
119
+ : action === 'step-forward'
120
+ ? this.navigator.moveBy(1)
121
+ : action === 'page-back'
122
+ ? this.navigator.page(-1)
123
+ : action === 'page-forward'
124
+ ? this.navigator.page(1)
125
+ : action === 'first'
126
+ ? this.navigator.moveTo(0)
127
+ : this.navigator.moveTo(this.rows.length - 1);
128
+ if (changed) this.clearCache();
129
+ }
130
+
131
+ public render(width: number): string[] {
132
+ const terminalRows = normalizeTerminalRows(this.getTerminalRows());
133
+ if (this.cachedLines !== undefined && this.cachedWidth === width && this.cachedTerminalRows === terminalRows) {
134
+ return this.cachedLines;
135
+ }
136
+ if (this.previewItem !== undefined) {
137
+ const lines = this.renderPreview(width, terminalRows, this.previewItem);
138
+ this.cachedWidth = width;
139
+ this.cachedTerminalRows = terminalRows;
140
+ this.cachedLines = lines;
141
+ return lines;
142
+ }
143
+ const theme = this.theme;
144
+ const border = theme.fg('border', '─'.repeat(Math.max(1, width)));
145
+ const headerLines = this.headerLines(width);
146
+ const warningLines = this.degradedWarningLines(width);
147
+ const descriptionLines = this.descriptionLines(width);
148
+ const extraLineCount = headerLines.length - 1 + warningLines.length + descriptionLines.length - 1;
149
+ const viewport = calculateViewport(this.rows.length, terminalRows, LIST_FIXED_LINE_COUNT, extraLineCount);
150
+ this.navigator.setVisibleCount(viewport.visibleCount);
151
+ const lines: string[] = [border, '', ...headerLines, '', ...warningLines];
152
+ const listLines = this.listLines(width);
153
+ lines.push(...listLines);
154
+ if (viewport.showScroll) lines.push(this.scrollLine(width));
155
+ const paddingCount = viewport.visibleCount - listLines.length;
156
+ for (let pad = 0; pad < paddingCount; pad++) lines.push('');
157
+ lines.push('');
158
+ lines.push(...descriptionLines);
159
+ lines.push('');
160
+ lines.push(
161
+ this.fit(
162
+ hintRow(this.theme, [
163
+ [STEP_KEY_HINT, 'Navigate'],
164
+ ['Ctrl+u/d', 'Page'],
165
+ ['gg/G', 'Bounds'],
166
+ ['Enter', 'Preview'],
167
+ ['Esc', 'Close'],
168
+ ]),
169
+ width,
170
+ ),
171
+ );
172
+ lines.push('', border);
173
+
174
+ const fittedLines = fitToTerminalHeight(lines, terminalRows, border);
175
+ this.cachedWidth = width;
176
+ this.cachedTerminalRows = terminalRows;
177
+ this.cachedLines = fittedLines;
178
+ return fittedLines;
179
+ }
180
+
181
+ public invalidate(): void {
182
+ this.clearCache();
183
+ }
184
+
185
+ // === Preview mode ===
186
+
187
+ private handlePreviewInput(data: string): void {
188
+ if (matchesKey(data, Key.escape) || data === 'q') {
189
+ this.closePreview();
190
+ return;
191
+ }
192
+ }
193
+
194
+ private openPreview(): void {
195
+ const row = this.rows[this.navigator.selected];
196
+ if (row?.kind !== 'item') return;
197
+ const item = this.itemsById.get(row.itemId);
198
+ if (item === undefined) return;
199
+ this.previewItem = item;
200
+ this.previewLines = undefined;
201
+ this.previewWrapWidth = undefined;
202
+ this.previewScroller.reset();
203
+ this.clearCache();
204
+ }
205
+
206
+ private closePreview(): void {
207
+ this.previewItem = undefined;
208
+ this.previewLines = undefined;
209
+ this.previewWrapWidth = undefined;
210
+ this.clearCache();
211
+ }
212
+
213
+ private renderPreview(width: number, terminalRows: number, item: InjectionItem): string[] {
214
+ const theme = this.theme;
215
+ const border = theme.fg('border', '─'.repeat(Math.max(1, width)));
216
+ const wrapped = this.getPreviewLines(width, item);
217
+ const viewport = calculateViewport(wrapped.length, terminalRows, PREVIEW_FIXED_LINE_COUNT);
218
+ this.previewScroller.setExtent(wrapped.length, viewport.visibleCount);
219
+
220
+ const lines: string[] = [border, ''];
221
+ const title = theme.fg('accent', theme.bold(normalizeInlineText(item.label)));
222
+ const source = normalizeInlineText(item.source.label);
223
+ const meta = theme.fg('muted', `${source} · ${item.tokens.toLocaleString('en-US')} tokens `);
224
+ lines.push(this.spread(title, meta, width));
225
+ lines.push('');
226
+
227
+ const start = this.previewScroller.offset;
228
+ for (let index = start; index < start + viewport.visibleCount; index++) {
229
+ lines.push(wrapped[index] ?? '');
230
+ }
231
+
232
+ if (viewport.showScroll) lines.push(this.previewScrollLine(width, wrapped.length));
233
+ lines.push('');
234
+ lines.push(
235
+ this.fit(
236
+ hintRow(this.theme, [
237
+ [STEP_KEY_HINT, 'Scroll'],
238
+ ['Ctrl+u/d', 'Page'],
239
+ ['gg/G', 'Bounds'],
240
+ ['Esc', 'Back'],
241
+ ]),
242
+ width,
243
+ ),
244
+ );
245
+ lines.push('', border);
246
+ return fitToTerminalHeight(lines, terminalRows, border);
247
+ }
248
+
249
+ private getPreviewLines(width: number, item: InjectionItem): string[] {
250
+ const wrapWidth = Math.max(10, width - BODY_INDENT.length - 1);
251
+ if (this.previewLines !== undefined && this.previewWrapWidth === wrapWidth) return this.previewLines;
252
+ const text = normalizePreviewText(item.text);
253
+ const lines: string[] = [];
254
+ for (const paragraph of text.split('\n')) {
255
+ const wrapped = wrapTextWithAnsi(paragraph, wrapWidth);
256
+ if (wrapped.length === 0) {
257
+ lines.push('');
258
+ continue;
259
+ }
260
+ for (const line of wrapped) lines.push(`${BODY_INDENT}${line}`);
261
+ }
262
+ this.previewLines = lines;
263
+ this.previewWrapWidth = wrapWidth;
264
+ return lines;
265
+ }
266
+
267
+ private previewScrollLine(width: number, totalLines: number): string {
268
+ if (!this.previewScroller.hasOverflow) return this.fit('', width);
269
+ return this.fit(this.theme.fg('dim', `${BODY_INDENT}(${this.previewScroller.visibleEnd}/${totalLines})`), width);
270
+ }
271
+
272
+ /** Keep title/label together when possible; give the narrow label its own breathing room. */
273
+ private headerLines(width: number): string[] {
274
+ const theme = this.theme;
275
+ const title = theme.fg('accent', theme.bold('Context Injections'));
276
+ const separator = theme.fg('dim', ' · ');
277
+ // Runtime remains unimplemented, so only the Initial label is shown.
278
+ const tabs = theme.fg('mdHeading', theme.bold('[INITIAL]'));
279
+ const combined = `${title}${separator}${tabs}`;
280
+ if (visibleWidth(combined) <= width) return [this.fit(combined, width)];
281
+ return [this.fit(title, width), '', this.fit(tabs, width)];
282
+ }
283
+
284
+ /** Render the current hierarchy viewport against one stable, nearby value column. */
285
+ private listLines(width: number): string[] {
286
+ const theme = this.theme;
287
+ const lines: string[] = [];
288
+ const contentWidth = Math.max(1, width - CURSOR_COLUMN_WIDTH);
289
+ const columns = this.injectionColumns(contentWidth);
290
+ const start = this.navigator.offset;
291
+ const end = start + this.navigator.windowSize;
292
+ for (let index = start; index < end; index++) {
293
+ const row = this.rows[index];
294
+ if (row === undefined) break;
295
+ if (row.kind === 'separator') {
296
+ lines.push('');
297
+ continue;
298
+ }
299
+ const selected = row.kind !== 'total' && index === this.navigator.selected;
300
+ const cursor = selected ? theme.fg('accent', '→ ') : BODY_INDENT;
301
+ const content = this.injectionLine(row, columns, contentWidth, selected);
302
+ lines.push(this.fit(`${cursor}${content}`, width));
303
+ }
304
+ return lines;
305
+ }
306
+
307
+ /** Choose the earliest useful shared value column, capped on wide terminals. */
308
+ private injectionColumns(width: number): InjectionColumns {
309
+ const contentRows = this.rows.filter(row => row.kind !== 'separator');
310
+ const labelWidth = Math.max(1, ...contentRows.map(row => visibleWidth(this.plainRowLabel(row))));
311
+ const tokenWidth = Math.max(1, ...contentRows.map(row => row.tokens.toLocaleString('en-US').length));
312
+ const idealValue = Math.min(MAX_TOKEN_VALUE_COLUMN, labelWidth + TOKEN_LEADER_GAP);
313
+ return { value: Math.max(1, Math.min(idealValue, width - tokenWidth)) };
314
+ }
315
+
316
+ /** One hierarchy row with dim leaders and a full token estimate when width permits. */
317
+ private injectionLine(
318
+ row: Exclude<InjectionRow, { readonly kind: 'separator' }>,
319
+ columns: InjectionColumns,
320
+ width: number,
321
+ selected: boolean,
322
+ ): string {
323
+ const labelWidth = Math.max(1, columns.value - 1);
324
+ const left = fitLine(this.styledRowLabel(row, selected), labelWidth);
325
+ const leader = this.tokenLeader(columns.value - visibleWidth(left));
326
+ const value = row.tokens.toLocaleString('en-US');
327
+ const tokens = row.kind === 'total' ? this.theme.bold(this.theme.fg('text', value)) : this.theme.fg(selected ? 'accent' : 'muted', value);
328
+ return fitLine(`${left}${leader}${tokens}`, width);
329
+ }
330
+
331
+ /** Fill a label/value gap with dim dots, retaining spaces at both ends. */
332
+ private tokenLeader(width: number): string {
333
+ if (width < 3) return ' '.repeat(Math.max(0, width));
334
+ return ` ${this.theme.fg('dim', '.'.repeat(width - 2))} `;
335
+ }
336
+
337
+ /** Unstyled hierarchy label used to keep the value column stable while scrolling. */
338
+ private plainRowLabel(row: Exclude<InjectionRow, { readonly kind: 'separator' }>): string {
339
+ const label = normalizeInlineText(row.label);
340
+ return row.kind === 'item' ? `${this.treePrefix(row)}${label}` : label;
341
+ }
342
+
343
+ /** Themed hierarchy label with connectors intentionally dim even on selection. */
344
+ private styledRowLabel(row: Exclude<InjectionRow, { readonly kind: 'separator' }>, selected: boolean): string {
345
+ const theme = this.theme;
346
+ const label = normalizeInlineText(row.label);
347
+ if (row.kind === 'group' || row.kind === 'total') {
348
+ return theme.bold(theme.fg(selected ? 'accent' : 'text', label));
349
+ }
350
+ const prefix = theme.fg('dim', this.treePrefix(row));
351
+ const color = selected ? 'accent' : row.depth === 1 ? 'muted' : 'dim';
352
+ return `${prefix}${theme.fg(color, label)}`;
353
+ }
354
+
355
+ /** Tree branch and ancestor continuation prefix for one item row. */
356
+ private treePrefix(row: Extract<InjectionRow, { readonly kind: 'item' }>): string {
357
+ const branch = row.isLast ? '└─ ' : '├─ ';
358
+ if (row.depth === 1) return branch;
359
+ return `${row.parentContinues === true ? '│ ' : ' '}${branch}`;
360
+ }
361
+
362
+ private scrollLine(width: number): string {
363
+ if (!this.navigator.hasOverflow) return this.fit('', width);
364
+ return this.fit(this.theme.fg('dim', `${BODY_INDENT}(${this.navigator.selectedOrdinal + 1}/${this.navigator.selectableCount})`), width);
365
+ }
366
+
367
+ /** Wrapped degraded-capture reason placed below the dialog header. */
368
+ private degradedWarningLines(width: number): string[] {
369
+ if (this.input.degradedReason === undefined) return [];
370
+ const reason = this.theme.fg('warning', `${BODY_INDENT}${normalizeInlineText(this.input.degradedReason)}`);
371
+ return wrapTextWithAnsi(reason, width);
372
+ }
373
+
374
+ /** Wrapped dialog description, including the degraded-capture indicator when needed. */
375
+ private descriptionLines(width: number): string[] {
376
+ const lines = wrapDescriptionLines(this.theme, LIST_DESCRIPTION, 'dim', width);
377
+ if (this.input.degradedReason !== undefined) {
378
+ lines.push(...wrapDescriptionLines(this.theme, '[Degraded: pi-native fallback used]', 'warning', width));
379
+ }
380
+ return lines;
381
+ }
382
+
383
+ private spread(left: string, right: string, width: number): string {
384
+ return spreadLine(left, right, width);
385
+ }
386
+
387
+ private fit(line: string, width: number): string {
388
+ return fitLine(line, width);
389
+ }
390
+
391
+ private clearCache(): void {
392
+ this.cachedWidth = undefined;
393
+ this.cachedTerminalRows = undefined;
394
+ this.cachedLines = undefined;
395
+ }
396
+ }
@@ -0,0 +1,88 @@
1
+ /** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
2
+ /**
3
+ * Shared pi-native fullscreen-view helpers: indentation constants,
4
+ * terminal-height viewport math, width fitting, hint-row formatting, and
5
+ * step-navigation key matching used by the Usage and Injections views. Pure
6
+ * string/number logic — no pi access.
7
+ */
8
+ import type { Theme, ThemeColor } from '@earendil-works/pi-coding-agent';
9
+ import { Key, matchesKey, truncateToWidth, visibleWidth, wrapTextWithAnsi } from '@earendil-works/pi-tui';
10
+
11
+ /** Hint-row key label for the single-step navigation keys both views accept. */
12
+ export const STEP_KEY_HINT = '↑↓/jk';
13
+
14
+ /** Two-space indent for descriptions, counters, hints, and body content. */
15
+ export const BODY_INDENT = ' ';
16
+ export const DEFAULT_TERMINAL_ROWS = 24;
17
+
18
+ /** How many content rows fit and whether an overflow indicator is needed. */
19
+ export interface Viewport {
20
+ visibleCount: number;
21
+ showScroll: boolean;
22
+ }
23
+
24
+ /** Divide terminal rows between content and an overflow indicator. */
25
+ export function calculateViewport(itemCount: number, terminalRows: number, fixedLineCount: number, extraLineCount = 0): Viewport {
26
+ const available = Math.max(1, terminalRows - fixedLineCount - extraLineCount);
27
+ const showScroll = itemCount > available && available > 1;
28
+ return {
29
+ visibleCount: Math.max(1, available - (showScroll ? 1 : 0)),
30
+ showScroll,
31
+ };
32
+ }
33
+
34
+ /** Keep emergency short-terminal output bounded while preserving both borders. */
35
+ export function fitToTerminalHeight(lines: string[], terminalRows: number, border: string): string[] {
36
+ if (lines.length <= terminalRows) return lines;
37
+ if (terminalRows === 1) return [border];
38
+ return [...lines.slice(0, terminalRows - 1), border];
39
+ }
40
+
41
+ /** Normalize an injected terminal-height reading to a usable positive integer. */
42
+ export function normalizeTerminalRows(rows: number): number {
43
+ return Number.isFinite(rows) ? Math.max(1, Math.floor(rows)) : DEFAULT_TERMINAL_ROWS;
44
+ }
45
+
46
+ /** Whether input requests one step backwards: Up or vim-style `k`. */
47
+ export function isStepBackKey(data: string): boolean {
48
+ return matchesKey(data, Key.up) || data === 'k';
49
+ }
50
+
51
+ /** Whether input requests one step forwards: Down or vim-style `j`. */
52
+ export function isStepForwardKey(data: string): boolean {
53
+ return matchesKey(data, Key.down) || data === 'j';
54
+ }
55
+
56
+ /** Truncate one rendered line to the supplied width. */
57
+ export function fitLine(line: string, width: number): string {
58
+ return truncateToWidth(line, width, '…');
59
+ }
60
+
61
+ /** Wrap plain dialog-description text with semantic color and an indented continuation column. */
62
+ export function wrapDescriptionLines(theme: Theme, text: string, color: ThemeColor, width: number): string[] {
63
+ const indentWidth = Math.min(BODY_INDENT.length, Math.max(0, width - 1));
64
+ const indent = BODY_INDENT.slice(0, indentWidth);
65
+ const contentWidth = Math.max(1, width - indentWidth);
66
+ const wrapped = wrapTextWithAnsi(text, contentWidth);
67
+ return (wrapped.length === 0 ? [''] : wrapped).map(line => truncateToWidth(theme.fg(color, `${indent}${line}`), width, ''));
68
+ }
69
+
70
+ /** Spread left and right content across the width, truncating the left side on overlap. */
71
+ export function spreadLine(left: string, right: string, width: number): string {
72
+ const gap = width - visibleWidth(left) - visibleWidth(right);
73
+ if (gap < 1) {
74
+ return fitLine(`${truncateToWidth(left, Math.max(1, width - visibleWidth(right) - 2), '…')} ${right}`, width);
75
+ }
76
+ return `${left}${' '.repeat(gap)}${right}`;
77
+ }
78
+
79
+ /** Pi-style hint row: two-space indent, `key description` pairs joined by ` · `. */
80
+ export function hintRow(theme: Theme, hints: ReadonlyArray<readonly [string, string]>): string {
81
+ const separator = theme.fg('dim', ' · ');
82
+ return `${BODY_INDENT}${hints.map(([key, description]) => hint(theme, key, description)).join(separator)}`;
83
+ }
84
+
85
+ /** Pi-style hint: dim key, slightly brighter (muted) description. */
86
+ function hint(theme: Theme, key: string, description: string): string {
87
+ return theme.fg('dim', key) + theme.fg('muted', ` ${description}`);
88
+ }
@@ -0,0 +1,37 @@
1
+ import { Key, matchesKey } from '@earendil-works/pi-tui';
2
+
3
+ export type NavigationAction = 'step-back' | 'step-forward' | 'page-back' | 'page-forward' | 'first' | 'last';
4
+ export type NavigationResult = { handled: boolean; action?: NavigationAction };
5
+
6
+ /** Stateful Vim navigation parser shared by both tabs and their previews. */
7
+ export class VimNavigation {
8
+ private pendingG = false;
9
+
10
+ reset(): void {
11
+ this.pendingG = false;
12
+ }
13
+
14
+ consume(data: string): NavigationResult {
15
+ if (data === 'g') {
16
+ if (this.pendingG) {
17
+ this.pendingG = false;
18
+ return { handled: true, action: 'first' };
19
+ }
20
+ this.pendingG = true;
21
+ return { handled: true };
22
+ }
23
+
24
+ this.pendingG = false;
25
+ if (data === 'G') return { handled: true, action: 'last' };
26
+ if (matchesKey(data, Key.ctrl('u'))) return { handled: true, action: 'page-back' };
27
+ if (matchesKey(data, Key.ctrl('d'))) return { handled: true, action: 'page-forward' };
28
+ if (matchesKey(data, Key.up) || data === 'k') return { handled: true, action: 'step-back' };
29
+ if (matchesKey(data, Key.down) || data === 'j') return { handled: true, action: 'step-forward' };
30
+
31
+ // These keys were intentionally replaced by Vim bindings.
32
+ if (matchesKey(data, Key.pageUp) || matchesKey(data, Key.pageDown) || matchesKey(data, Key.home) || matchesKey(data, Key.end)) {
33
+ return { handled: true };
34
+ }
35
+ return { handled: false };
36
+ }
37
+ }
@@ -0,0 +1,82 @@
1
+ /** Forked from dimk90/pi-context-view at f6f007b867212bcf81a61519c8e40ce209cdd608 (MIT). */
2
+ /**
3
+ * Preview-only recognition of complete pi skill-expansion wrappers. The
4
+ * returned segments retain ordinary and malformed text verbatim; callers are
5
+ * responsible for terminal sanitization before parsing or rendering.
6
+ */
7
+
8
+ const SKILL_OPEN_TAG = /^<skill name="([^"\r\n]+)"(?: location="[^"\r\n]*")?>\r?$/gm;
9
+ const ANY_SKILL_OPEN_TAG = /^<skill(?:\s|>)[^\r\n]*\r?$/gm;
10
+ const SKILL_CLOSE_TAG = /^<\/skill>\r?$/gm;
11
+
12
+ /** One display segment from a user message containing attached skills. */
13
+ export type SkillPreviewSegment = { readonly type: 'text'; readonly text: string } | { readonly type: 'skill'; readonly name: string };
14
+
15
+ interface TagSpan {
16
+ readonly start: number;
17
+ readonly end: number;
18
+ }
19
+
20
+ interface SkillOpenTag extends TagSpan {
21
+ readonly name: string;
22
+ }
23
+
24
+ /**
25
+ * Replace no content directly: split complete skill wrappers into named
26
+ * segments so the UI can render compact badges while retaining unmatched
27
+ * wrappers as text. A later complete wrapper is still recognized when an
28
+ * earlier opening tag is malformed or unclosed.
29
+ */
30
+ export function splitSkillPreview(text: string): SkillPreviewSegment[] {
31
+ const openings = collectOpenTags(text);
32
+ const openingBoundaries = collectTagSpans(text, ANY_SKILL_OPEN_TAG);
33
+ const closings = collectTagSpans(text, SKILL_CLOSE_TAG);
34
+ const segments: SkillPreviewSegment[] = [];
35
+ let textStart = 0;
36
+ let openingBoundaryIndex = 0;
37
+ let closingIndex = 0;
38
+
39
+ for (let openingIndex = 0; openingIndex < openings.length; openingIndex++) {
40
+ const opening = openings[openingIndex];
41
+ if (opening === undefined || opening.start < textStart) continue;
42
+ while ((closings[closingIndex]?.start ?? text.length) < opening.end) closingIndex++;
43
+ const closing = closings[closingIndex];
44
+ if (closing === undefined) continue;
45
+
46
+ while ((openingBoundaries[openingBoundaryIndex]?.start ?? text.length) <= opening.start) {
47
+ openingBoundaryIndex++;
48
+ }
49
+ const nextOpening = openingBoundaries[openingBoundaryIndex];
50
+ if (nextOpening !== undefined && nextOpening.start < closing.start) continue;
51
+
52
+ pushTextSegment(segments, text.slice(textStart, opening.start));
53
+ segments.push({ type: 'skill', name: opening.name });
54
+ textStart = closing.end;
55
+ closingIndex++;
56
+ }
57
+
58
+ pushTextSegment(segments, text.slice(textStart));
59
+ return segments;
60
+ }
61
+
62
+ /** Collect structurally valid opening tags and their skill names. */
63
+ function collectOpenTags(text: string): SkillOpenTag[] {
64
+ return [...text.matchAll(SKILL_OPEN_TAG)].map(match => ({
65
+ start: match.index,
66
+ end: match.index + match[0].length,
67
+ name: match[1] ?? '',
68
+ }));
69
+ }
70
+
71
+ /** Collect complete line-delimited tag spans for one global expression. */
72
+ function collectTagSpans(text: string, expression: RegExp): TagSpan[] {
73
+ return [...text.matchAll(expression)].map(match => ({
74
+ start: match.index,
75
+ end: match.index + match[0].length,
76
+ }));
77
+ }
78
+
79
+ /** Append non-empty ordinary text without merging it into skill segments. */
80
+ function pushTextSegment(segments: SkillPreviewSegment[], text: string): void {
81
+ if (text.length > 0) segments.push({ type: 'text', text });
82
+ }