proper-base 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "proper-base",
3
+ "version": "0.2.0",
4
+ "description": "Baseline Pi behavior for session naming, history, prompt editing, fullscreen navigation, and footer styling",
5
+ "keywords": [
6
+ "pi-package",
7
+ "pi",
8
+ "pi-extension",
9
+ "pi-coding-agent",
10
+ "base",
11
+ "customization",
12
+ "history",
13
+ "prompt-history",
14
+ "session-title",
15
+ "autocomplete",
16
+ "fullscreen",
17
+ "scrolling",
18
+ "footer",
19
+ "theme"
20
+ ],
21
+ "license": "MIT",
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/sharaf-nassar/proper-pi-extensions.git",
25
+ "directory": "proper-base"
26
+ },
27
+ "homepage": "https://github.com/sharaf-nassar/proper-pi-extensions/tree/main/proper-base#readme",
28
+ "bugs": {
29
+ "url": "https://github.com/sharaf-nassar/proper-pi-extensions/issues"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public",
33
+ "registry": "https://registry.npmjs.org/"
34
+ },
35
+ "type": "module",
36
+ "files": [
37
+ "index.ts",
38
+ "install.mjs",
39
+ "src",
40
+ "README.md",
41
+ "LICENSE"
42
+ ],
43
+ "scripts": {
44
+ "postinstall": "node install.mjs",
45
+ "prepack": "npm test && npm run typecheck",
46
+ "test": "node --test test/*.test.ts",
47
+ "test:coverage": "node --experimental-test-coverage --test --test-coverage-lines=93 --test-coverage-branches=78 --test-coverage-functions=90 test/*.test.ts",
48
+ "typecheck": "tsc"
49
+ },
50
+ "engines": {
51
+ "node": ">=22.19.0"
52
+ },
53
+ "peerDependencies": {
54
+ "@earendil-works/pi-coding-agent": "*",
55
+ "@earendil-works/pi-tui": "*"
56
+ },
57
+ "devDependencies": {
58
+ "@earendil-works/pi-coding-agent": "0.84.2",
59
+ "@earendil-works/pi-tui": "0.84.2",
60
+ "@types/node": "25.9.5",
61
+ "typescript": "6.0.2"
62
+ },
63
+ "pi": {
64
+ "extensions": [
65
+ "./index.ts"
66
+ ]
67
+ }
68
+ }
@@ -0,0 +1,406 @@
1
+ import {
2
+ type AutocompleteProvider,
3
+ type Component,
4
+ type OverlayHandle,
5
+ type OverlayMargin,
6
+ type OverlayOptions,
7
+ type TUI,
8
+ truncateToWidth,
9
+ visibleWidth,
10
+ wrapTextWithAnsi,
11
+ } from "@earendil-works/pi-tui";
12
+
13
+ const INSTALLED = Symbol.for("pi-proper-base.autocomplete-details");
14
+ const MODEL_SUBMIT_INSTALLED = Symbol.for(
15
+ "pi-proper-base.model-autocomplete-submit",
16
+ );
17
+ const ACTIVE_OVERLAY = Symbol.for("pi-proper-base.autocomplete-overlay");
18
+ const INLINE_SLASH_INSTALLED = Symbol.for(
19
+ "pi-proper-base.inline-slash-autocomplete",
20
+ );
21
+
22
+ type AutocompleteEditor = Component & {
23
+ autocompleteList?: {
24
+ getSelectedItem(): { description?: string } | null;
25
+ };
26
+ [INSTALLED]?: boolean;
27
+ };
28
+
29
+ type InlineSlashEditor = Component & {
30
+ state?: {
31
+ lines: string[];
32
+ cursorLine: number;
33
+ cursorCol: number;
34
+ };
35
+ handleInput?(data: string): void;
36
+ isShowingAutocomplete?(): boolean;
37
+ tryTriggerAutocomplete?(): void;
38
+ [INLINE_SLASH_INSTALLED]?: boolean;
39
+ };
40
+
41
+ type ModelAutocompleteEditor = Component & {
42
+ autocompleteList?: {
43
+ getSelectedItem(): { value?: string } | null;
44
+ };
45
+ getText?(): string;
46
+ handleInput?(data: string): void;
47
+ submitValue?(): void;
48
+ [MODEL_SUBMIT_INSTALLED]?: boolean;
49
+ };
50
+
51
+ type EditorKeybindings = {
52
+ matches(data: string, action: string): boolean;
53
+ };
54
+
55
+ type DetailTheme = {
56
+ borderColor(text: string): string;
57
+ selectList: {
58
+ selectedText?(text: string): string;
59
+ description(text: string): string;
60
+ };
61
+ };
62
+
63
+ type OverlayTui = TUI & { [ACTIVE_OVERLAY]?: OverlayHandle };
64
+ type ComponentWithChildren = Component & { children?: Component[] };
65
+
66
+ type InlineSlashContext = {
67
+ prefix: string;
68
+ start: number;
69
+ };
70
+
71
+ function inlineSlashContext(
72
+ lines: string[],
73
+ cursorLine: number,
74
+ cursorCol: number,
75
+ ): InlineSlashContext | undefined {
76
+ const beforeCursor = (lines[cursorLine] ?? "").slice(0, cursorCol);
77
+ const match = [...beforeCursor.matchAll(/(?:^|\s)\//g)].at(-1);
78
+ if (!match) return undefined;
79
+ const start = (match.index ?? 0) + match[0].length - 1;
80
+ if (start === 0 && cursorLine === 0) return undefined;
81
+ return { prefix: beforeCursor.slice(start), start };
82
+ }
83
+
84
+ export function installInlineSlashAutocomplete(editor: Component): void {
85
+ const target = editor as InlineSlashEditor;
86
+ if (
87
+ target[INLINE_SLASH_INSTALLED] ||
88
+ !target.handleInput ||
89
+ !target.state ||
90
+ !target.tryTriggerAutocomplete
91
+ ) {
92
+ return;
93
+ }
94
+
95
+ const handleInput = target.handleInput.bind(target);
96
+ target.handleInput = (data: string) => {
97
+ handleInput(data);
98
+ if (target.isShowingAutocomplete?.() || !/^[/a-zA-Z0-9._:-]$/.test(data)) {
99
+ return;
100
+ }
101
+ const state = target.state;
102
+ if (!state) return;
103
+ if (inlineSlashContext(state.lines, state.cursorLine, state.cursorCol)) {
104
+ target.tryTriggerAutocomplete?.();
105
+ }
106
+ };
107
+ target[INLINE_SLASH_INSTALLED] = true;
108
+ }
109
+
110
+ function createAutocompleteDetailBox(theme: DetailTheme) {
111
+ let description: string | undefined;
112
+ let maxRows = 0;
113
+ const isVisible = () => description !== undefined && maxRows >= 3;
114
+
115
+ return {
116
+ isVisible,
117
+ setDescription(next: string | undefined, availableRows: number): void {
118
+ description = next?.replace(/[\r\n]+/g, " ").trim() || undefined;
119
+ maxRows = availableRows;
120
+ },
121
+ component: {
122
+ render(width: number): string[] {
123
+ if (!description || !isVisible() || width < 6) return [];
124
+
125
+ const textWidth = width - 4;
126
+ const contentRows = maxRows - 2;
127
+ let lines = wrapTextWithAnsi(description, textWidth);
128
+ if (lines.length > contentRows) {
129
+ lines = lines.slice(0, contentRows);
130
+ const last = lines.at(-1);
131
+ if (last !== undefined) {
132
+ const lastIndex = lines.length - 1;
133
+ lines[lastIndex] = `${truncateToWidth(last, textWidth - 1, "")}…`;
134
+ }
135
+ }
136
+
137
+ const border = (text: string) => theme.borderColor(text);
138
+ return [
139
+ border(`┌${"─".repeat(width - 2)}┐`),
140
+ ...lines.map(
141
+ (line) =>
142
+ `${border("│")} ${(theme.selectList.selectedText ?? theme.selectList.description)(line)}${" ".repeat(
143
+ Math.max(0, textWidth - visibleWidth(line)),
144
+ )} ${border("│")}`,
145
+ ),
146
+ border(`└${"─".repeat(width - 2)}┘`),
147
+ ];
148
+ },
149
+ invalidate(): void {},
150
+ } satisfies Component,
151
+ };
152
+ }
153
+
154
+ export function sortModelAutocompleteDescending(
155
+ current: AutocompleteProvider,
156
+ ): AutocompleteProvider {
157
+ return {
158
+ ...(current.triggerCharacters
159
+ ? { triggerCharacters: current.triggerCharacters }
160
+ : {}),
161
+ async getSuggestions(lines, cursorLine, cursorCol, options) {
162
+ const inline = inlineSlashContext(lines, cursorLine, cursorCol);
163
+ const requestLines = inline ? [...lines] : lines;
164
+ if (inline) requestLines[cursorLine] = inline.prefix;
165
+ const suggestions = await current.getSuggestions(
166
+ requestLines,
167
+ cursorLine,
168
+ inline ? inline.prefix.length : cursorCol,
169
+ inline ? { ...options, force: false } : options,
170
+ );
171
+ const line = lines[cursorLine] ?? "";
172
+ const activeLine = inline?.prefix ?? line.slice(0, cursorCol);
173
+ if (!suggestions || !activeLine.startsWith("/model ")) {
174
+ return suggestions;
175
+ }
176
+
177
+ const terms = suggestions.prefix
178
+ .toLowerCase()
179
+ .split(/\s+/)
180
+ .filter(Boolean);
181
+ const strictMatches = suggestions.items.filter((item) => {
182
+ const searchable =
183
+ `${item.label} ${item.value} ${item.description ?? ""}`.toLowerCase();
184
+ return terms.every((term) => searchable.includes(term));
185
+ });
186
+ const items =
187
+ terms.length > 0 && strictMatches.length > 0
188
+ ? strictMatches
189
+ : suggestions.items;
190
+
191
+ return {
192
+ ...suggestions,
193
+ items: [...items].sort(
194
+ (a, b) =>
195
+ b.label.localeCompare(a.label, "en", {
196
+ numeric: true,
197
+ sensitivity: "base",
198
+ }) || b.value.localeCompare(a.value),
199
+ ),
200
+ };
201
+ },
202
+ applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
203
+ const inline = inlineSlashContext(lines, cursorLine, cursorCol);
204
+ if (!inline) {
205
+ return current.applyCompletion(
206
+ lines,
207
+ cursorLine,
208
+ cursorCol,
209
+ item,
210
+ prefix,
211
+ );
212
+ }
213
+ const completed = current.applyCompletion(
214
+ [inline.prefix],
215
+ 0,
216
+ inline.prefix.length,
217
+ item,
218
+ prefix,
219
+ );
220
+ const replacement = completed.lines[0] ?? inline.prefix;
221
+ const next = [...lines];
222
+ const currentLine = lines[cursorLine] ?? "";
223
+ next[cursorLine] =
224
+ currentLine.slice(0, inline.start) +
225
+ replacement +
226
+ currentLine.slice(cursorCol);
227
+ return {
228
+ lines: next,
229
+ cursorLine,
230
+ cursorCol: inline.start + completed.cursorCol,
231
+ };
232
+ },
233
+ shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
234
+ return (
235
+ current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ??
236
+ true
237
+ );
238
+ },
239
+ };
240
+ }
241
+
242
+ export function installModelAutocompleteSubmit(
243
+ editor: Component,
244
+ keybindings: EditorKeybindings,
245
+ ): void {
246
+ const target = editor as ModelAutocompleteEditor;
247
+ if (
248
+ target[MODEL_SUBMIT_INSTALLED] ||
249
+ !target.handleInput ||
250
+ !target.getText
251
+ ) {
252
+ return;
253
+ }
254
+
255
+ const handleInput = target.handleInput.bind(target);
256
+ target.handleInput = (data: string) => {
257
+ const selected = target.autocompleteList?.getSelectedItem();
258
+ const selectedValue = selected?.value;
259
+ const confirm = keybindings.matches(data, "tui.select.confirm");
260
+ const tab = keybindings.matches(data, "tui.input.tab");
261
+ const shouldSubmit =
262
+ (confirm || tab) &&
263
+ typeof selectedValue === "string" &&
264
+ /^\/model [^\n]*$/.test(target.getText?.() ?? "");
265
+
266
+ handleInput(data);
267
+ if (
268
+ shouldSubmit &&
269
+ target.autocompleteList === undefined &&
270
+ target.getText?.() === `/model ${selectedValue}`
271
+ ) {
272
+ if (tab) {
273
+ if (target.submitValue) target.submitValue();
274
+ else handleInput("\r");
275
+ } else {
276
+ handleInput(data);
277
+ }
278
+ }
279
+ };
280
+ target[MODEL_SUBMIT_INSTALLED] = true;
281
+ }
282
+
283
+ export function installAutocompleteDetails(
284
+ editor: Component,
285
+ tui: TUI,
286
+ theme: DetailTheme,
287
+ ): void {
288
+ const target = editor as AutocompleteEditor;
289
+ if (target[INSTALLED]) return;
290
+
291
+ const host = tui as OverlayTui;
292
+ host[ACTIVE_OVERLAY]?.hide();
293
+
294
+ const detail = createAutocompleteDetailBox(theme);
295
+ const margin: OverlayMargin = { bottom: 0 };
296
+ let overlay: OverlayHandle | undefined;
297
+ const releaseOverlay = () => {
298
+ const active = overlay;
299
+ if (!active) return;
300
+ active.hide();
301
+ overlay = undefined;
302
+ if (host[ACTIVE_OVERLAY] === active) delete host[ACTIVE_OVERLAY];
303
+ };
304
+ const scheduleReleaseOverlay = () => {
305
+ const inactive = overlay;
306
+ if (!inactive) return;
307
+ queueMicrotask(() => {
308
+ if (
309
+ overlay === inactive &&
310
+ (!detail.isVisible() || !isMounted(tui, target))
311
+ ) {
312
+ releaseOverlay();
313
+ }
314
+ });
315
+ };
316
+ const options: OverlayOptions = {
317
+ anchor: "bottom-left",
318
+ margin,
319
+ nonCapturing: true,
320
+ width: "100%",
321
+ visible: () => {
322
+ const visible = detail.isVisible() && isMounted(tui, target);
323
+ if (!visible) scheduleReleaseOverlay();
324
+ return visible;
325
+ },
326
+ };
327
+ const ensureOverlay = () => {
328
+ const active = host[ACTIVE_OVERLAY];
329
+ if (overlay !== undefined && active === overlay) return;
330
+ active?.hide();
331
+ overlay = tui.showOverlay(detail.component, options);
332
+ host[ACTIVE_OVERLAY] = overlay;
333
+ };
334
+
335
+ const render = target.render.bind(target);
336
+ target.render = (width: number) => {
337
+ const lines = render(width);
338
+ margin.bottom = lines.length + rowsBelow(tui, target, width);
339
+ detail.setDescription(
340
+ target.autocompleteList?.getSelectedItem()?.description,
341
+ Math.max(0, tui.terminal.rows - margin.bottom),
342
+ );
343
+ if (detail.isVisible() && isMounted(tui, target)) ensureOverlay();
344
+ else releaseOverlay();
345
+ return lines;
346
+ };
347
+ target[INSTALLED] = true;
348
+ }
349
+
350
+ export function isMounted(tui: TUI, target: Component): boolean {
351
+ return roots(tui).some((root) => contains(root, target));
352
+ }
353
+
354
+ function contains(root: Component, target: Component): boolean {
355
+ if (root === target) return true;
356
+ return childrenOf(root).some((child) => contains(child, target));
357
+ }
358
+
359
+ export function rowsBelow(tui: TUI, target: Component, width: number): number {
360
+ const mountedRoots = roots(tui);
361
+ for (let index = 0; index < mountedRoots.length; index++) {
362
+ const root = mountedRoots[index];
363
+ if (!root) continue;
364
+ const rows = rowsAfter(root, target, width);
365
+ if (rows === undefined) continue;
366
+ return (
367
+ rows +
368
+ mountedRoots
369
+ .slice(index + 1)
370
+ .reduce((total, root) => total + root.render(width).length, 0)
371
+ );
372
+ }
373
+ return 0;
374
+ }
375
+
376
+ function rowsAfter(
377
+ root: Component,
378
+ target: Component,
379
+ width: number,
380
+ ): number | undefined {
381
+ if (root === target) return 0;
382
+
383
+ const children = childrenOf(root);
384
+ for (let index = 0; index < children.length; index++) {
385
+ const child = children[index];
386
+ if (!child) continue;
387
+ const rows = rowsAfter(child, target, width);
388
+ if (rows === undefined) continue;
389
+ return (
390
+ rows +
391
+ children
392
+ .slice(index + 1)
393
+ .reduce((total, child) => total + child.render(width).length, 0)
394
+ );
395
+ }
396
+ return undefined;
397
+ }
398
+
399
+ function roots(tui: TUI): Component[] {
400
+ const layoutRoot = (tui as TUI & { layoutRoot?: Component }).layoutRoot;
401
+ return layoutRoot ? [layoutRoot] : tui.children;
402
+ }
403
+
404
+ function childrenOf(component: Component): Component[] {
405
+ return (component as ComponentWithChildren).children ?? [];
406
+ }