pi-autosuggestions 0.1.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.
@@ -0,0 +1,4 @@
1
+ # Code Foundry release profile (see 0xPlayerOne/code-foundry).
2
+ release_type: node
3
+ npm_publish: "true"
4
+ release_merge_strategy: rebase
@@ -0,0 +1,12 @@
1
+ name: Release
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+
7
+ permissions: {}
8
+
9
+ jobs:
10
+ release:
11
+ uses: 0xPlayerOne/code-foundry/.github/workflows/release.yml@v0.31.12
12
+ secrets: inherit
@@ -0,0 +1 @@
1
+ {".": "0.1.0"}
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Andrew Mahoney-Fernandes
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,68 @@
1
+ # pi-autosuggestions
2
+
3
+ [zsh](https://www.zsh.org/)-style **inline ghost completion** for bash mode (`!command`) in the
4
+ [pi coding agent](https://github.com/earendil-works/pi-mono).
5
+
6
+ Type `!cd De` and `ktop/` appears dimmed right after your cursor — no dropdown,
7
+ no Tab required. Press `→` or `Tab` to accept. Everything outside bash mode keeps
8
+ stock editor behavior.
9
+
10
+ ## Features
11
+
12
+ - **Inline ghost text** — completions render dimmed after the cursor, zsh-autosuggestions style
13
+ - **Accept with `→` or `Tab`** — accepting a directory immediately suggests its first entry (zsh-like dir chaining)
14
+ - **Smart mode switching**:
15
+ - exactly **1 match** → inline ghost
16
+ - **multiple matches** → the stock dropdown appears, fully interactive (arrow keys, Enter, mouse)
17
+ - **0 matches** → just the cursor
18
+ - **Command position aware** — typing `!cd` (no space yet) lists all entries; picking one inserts it as the first argument
19
+ - **Blinking beam cursor** — replaces the block cursor with a thin vertical bar that blinks at ~2 Hz and stays solid while you type
20
+ - **`!!` hidden shell commands** get completions too
21
+ - Zero dependencies — only peer-imports pi's own bundled modules
22
+
23
+ ## Install
24
+
25
+ ```bash
26
+ pi install git:github.com/0xPlayerOne/pi-autosuggestions@v0.1.0
27
+ ```
28
+
29
+ or from a local checkout:
30
+
31
+ ```bash
32
+ pi install /path/to/pi-autosuggestions
33
+ ```
34
+
35
+ ## Usage
36
+
37
+ | Input | Result |
38
+ |-------|--------|
39
+ | `!cd` | dropdown — all entries |
40
+ | `!cd D` | dropdown — filtered to `D*` |
41
+ | `!cd Dow` | inline ghost `nloads/` |
42
+ | `→` / `Tab` | accept the suggestion |
43
+ | `Esc` | dismiss / clear as usual |
44
+
45
+ Works for any bash-mode path argument, not just `cd`: `!cat Do<Tab>`, `!vim do<Tab>`, `!!ls -la De<Tab>`…
46
+
47
+ ## Compatibility
48
+
49
+ - Built and tested against **pi 0.85.0**.
50
+ - Hooks pi-tui editor internals that are private in the type declarations; a major
51
+ pi update may require a touch-up. The extension fails visibly (a startup error
52
+ message), never corrupts the session.
53
+
54
+ ## How it works
55
+
56
+ The extension replaces the editor component with a subclass of pi's `CustomEditor`:
57
+
58
+ - A bash-aware wrapper around the shared autocomplete provider acts as the single
59
+ decision point: 1 match diverts to the ghost (returning "no suggestions" closes the
60
+ stock popup by design), multiple matches flow through to the genuine stock dropdown.
61
+ - Ghost text is spliced into the rendered cursor row at render time, taking cells
62
+ from row padding so widths stay exact.
63
+ - The beam cursor swaps the base renderer's reverse-video block at render time; the
64
+ blink is a focused render loop that pauses (solid) briefly after each keystroke.
65
+
66
+ ## License
67
+
68
+ MIT
@@ -0,0 +1,350 @@
1
+ // Bash inline completion — zsh-style ghost text in the Pi editor.
2
+ //
3
+ // In bash mode (message starts with "!"), path completions render as dimmed
4
+ // inline text after the cursor instead of a dropdown:
5
+ // - type `!cd A` → "ppleStuff/" appears dimmed right after the cursor
6
+ // - → (right arrow) or Tab accepts it
7
+ // - accepting a directory immediately suggests its first entry (zsh-like)
8
+ // - Escape dismisses
9
+ // Everything outside bash mode keeps stock editor behavior (dropdown etc.).
10
+
11
+ import { CustomEditor, type ExtensionAPI, type KeybindingsManager } from "@earendil-works/pi-coding-agent";
12
+ import {
13
+ Editor,
14
+ matchesKey,
15
+ visibleWidth,
16
+ type AutocompleteProvider,
17
+ type AutocompleteSuggestions,
18
+ type EditorTheme,
19
+ type TUI,
20
+ } from "@earendil-works/pi-tui";
21
+
22
+ /** Runtime access to Editor internals that are private in the type declarations. */
23
+ interface EditorInternals {
24
+ state: { lines: string[]; cursorLine: number; cursorCol: number };
25
+ autocompleteProvider?: AutocompleteProvider | null;
26
+ setCursorCol(col: number): void;
27
+ pushUndoSnapshot(): void;
28
+ tui: { requestRender(): void };
29
+ requestAutocomplete(options: { force?: boolean; explicitTab?: boolean }): void;
30
+ }
31
+
32
+ const DIM = "\x1b[2m";
33
+ const RESET = "\x1b[0m";
34
+ /** Beam cursor: thin vertical bar, bold so it stands out. One cell wide. */
35
+ const BEAM = "\x1b[1m▏\x1b[0m";
36
+ /** Matches the reverse-video block the base renderer emits for the cursor. */
37
+ const REVERSE_CURSOR = /\x1b\[7m([\s\S]*?)\x1b\[0m/;
38
+
39
+ const BLINK_INTERVAL_MS = 500;
40
+ /** Cursor stays solid for this long after each keystroke, then resumes blinking. */
41
+ const SOLID_AFTER_INPUT_MS = 450;
42
+
43
+ type Ghost = { lineIndex: number; prefix: string; remainder: string };
44
+
45
+ class BashInlineEditor extends CustomEditor {
46
+ private realProvider: AutocompleteProvider | undefined;
47
+ private bashProvider: AutocompleteProvider | undefined;
48
+ private ghost: Ghost | null = null;
49
+ private ghostToken = 0;
50
+ private ghostAbort?: AbortController;
51
+ private cursorOn = true;
52
+ private lastInputAt = 0;
53
+ private blinkTimer?: ReturnType<typeof setInterval>;
54
+
55
+ constructor(tui: TUI, theme: EditorTheme, keybindings: KeybindingsManager) {
56
+ super(tui, theme, keybindings);
57
+ this.startBlink();
58
+ // Wrap onChange so programmatic text changes (paste, undo, history,
59
+ // setText) also refresh the inline suggestion.
60
+ let external: ((text: string) => void) | undefined;
61
+ const self = this;
62
+ Object.defineProperty(this, "onChange", {
63
+ configurable: true,
64
+ enumerable: true,
65
+ get() {
66
+ if (!external) return undefined;
67
+ return (text: string) => {
68
+ external!(text);
69
+ self.updateGhost();
70
+ };
71
+ },
72
+ set(fn) {
73
+ external = fn;
74
+ },
75
+ });
76
+ }
77
+
78
+ // Pi installs the shared autocomplete provider here. Wrap it once with
79
+ // bash-mode-aware behavior; the wrapper is what the stock popup machinery
80
+ // talks to, so dropdown open/close and ghost diversion stay consistent.
81
+ setAutocompleteProvider(provider: AutocompleteProvider | undefined): void {
82
+ super.setAutocompleteProvider(provider);
83
+ this.realProvider = provider;
84
+ const bashProvider = provider ? this.createBashProvider(provider) : undefined;
85
+ this.bashProvider = bashProvider;
86
+ (this as unknown as EditorInternals).autocompleteProvider = bashProvider;
87
+ }
88
+
89
+ handleInput(data: string): void {
90
+ // Solid cursor while typing; blinking resumes after the idle window.
91
+ this.lastInputAt = Date.now();
92
+ this.cursorOn = true;
93
+ // Right arrow accepts the ghost suggestion when the cursor sits at EOL.
94
+ if (matchesKey(data, "right") && this.activeGhost() && this.cursorAtLineEnd()) {
95
+ this.acceptGhost();
96
+ return;
97
+ }
98
+ super.handleInput(data);
99
+ if (matchesKey(data, "escape")) {
100
+ this.ghost = null;
101
+ }
102
+ if (this.inBashMode()) {
103
+ this.updateGhost();
104
+ } else if (this.ghost) {
105
+ this.ghost = null;
106
+ }
107
+ }
108
+
109
+ handleTabCompletion(): void {
110
+ if (this.activeGhost()) {
111
+ this.acceptGhost();
112
+ return;
113
+ }
114
+ super.handleTabCompletion();
115
+ }
116
+
117
+ // Runtime override of the base Editor's (private) setCursorCol — virtual
118
+ // dispatch makes this shadow work. Refresh after cursor moves (clicks, etc.).
119
+ // @ts-ignore — intentional runtime override of a private base method
120
+ setCursorCol(col: number): void {
121
+ Editor.prototype.setCursorCol.call(this, col);
122
+ if (this.inBashMode()) {
123
+ this.updateGhost();
124
+ }
125
+ }
126
+
127
+ render(width: number): string[] {
128
+ const out = super.render(width);
129
+ // Replace the base renderer's reverse-video block cursor with a blinking
130
+ // beam. On ghost rows there is no separate cursor cell: the suggestion
131
+ // starts flush after the typed text and the blink highlights its first
132
+ // character instead.
133
+ const rowIdx = out.findIndex((row) => REVERSE_CURSOR.test(row));
134
+ if (rowIdx === -1) {
135
+ return out;
136
+ }
137
+ const row = out[rowIdx]!;
138
+ const match = REVERSE_CURSOR.exec(row);
139
+ if (!match) {
140
+ return out;
141
+ }
142
+ const head = row.slice(0, match.index);
143
+ const ghost = this.activeGhost();
144
+ if (ghost) {
145
+ // Base row layout: text + cursor cell + padding. Drop the cursor
146
+ // cell (frees 1 col) and render ghost chars into the padding.
147
+ const pad = / *$/.exec(row.slice(match.index + match[0].length))?.[0].length ?? 0;
148
+ const avail = pad + 1;
149
+ let used = 0;
150
+ const cells: string[] = [];
151
+ for (const ch of [...ghost.remainder]) {
152
+ const w = visibleWidth(ch);
153
+ if (used + w > avail) {
154
+ break;
155
+ }
156
+ // Blink "on": first suggestion char is bright (acts as the cursor)
157
+ cells.push(used === 0 && this.cursorOn ? `\x1b[1m${ch}${RESET}` : `${DIM}${ch}${RESET}`);
158
+ used += w;
159
+ }
160
+ out[rowIdx] = head + cells.join("") + " ".repeat(Math.max(0, pad - used + 1));
161
+ return out;
162
+ }
163
+ const ch = match[1] || " ";
164
+ const cursorCell = this.cursorOn ? BEAM : ch;
165
+ out[rowIdx] = head + cursorCell + row.slice(match.index + match[0].length);
166
+ return out;
167
+ }
168
+
169
+ // --- internals ---
170
+
171
+ /** Toggle the beam cursor while focused; solid briefly after keystrokes. */
172
+ private startBlink(): void {
173
+ if (this.blinkTimer) {
174
+ return;
175
+ }
176
+ this.blinkTimer = setInterval(() => {
177
+ if (!this.focused) {
178
+ return;
179
+ }
180
+ const idle = Date.now() - this.lastInputAt > SOLID_AFTER_INPUT_MS;
181
+ this.cursorOn = idle ? !this.cursorOn : true;
182
+ this.tui.requestRender();
183
+ }, BLINK_INTERVAL_MS);
184
+ }
185
+
186
+ private inBashMode(): boolean {
187
+ return this.getText().trimStart().startsWith("!");
188
+ }
189
+
190
+ private cursorAtLineEnd(): boolean {
191
+ const st = (this as unknown as EditorInternals).state;
192
+ return st.cursorCol === (st.lines[st.cursorLine] ?? "").length;
193
+ }
194
+
195
+ /** Suppress the dropdown in bash mode unless the popup is already open. */
196
+
197
+ /**
198
+ * True while the command word after "!" is still being typed (no space
199
+ * yet), e.g. "!cd" or "!!ls" — completion targets the argument position.
200
+ */
201
+ private commandPosition(beforeCursor: string): boolean {
202
+ return /^[ \t]*![^\s]*$/.test(beforeCursor);
203
+ }
204
+
205
+ /**
206
+ * Wrap the stock provider with bash-mode behavior. This is the single
207
+ * decision point for both the ghost and the dropdown:
208
+ * - command position ("!cd", no space yet) → suggest all entries
209
+ * - multiple matches → normal suggestions (stock dropdown shows them)
210
+ * - exactly one match → divert to the inline ghost, close any popup
211
+ * - non-bash text → untouched stock behavior
212
+ */
213
+ private createBashProvider(current: AutocompleteProvider): AutocompleteProvider {
214
+ const self = this;
215
+ return {
216
+ async getSuggestions(lines, cursorLine, cursorCol, options) {
217
+ if (!self.inBashMode()) {
218
+ return current.getSuggestions(lines, cursorLine, cursorCol, options);
219
+ }
220
+ const before = (lines[cursorLine] ?? "").slice(0, cursorCol);
221
+ const commandPos = self.commandPosition(before);
222
+ let queryLines = lines;
223
+ if (commandPos) {
224
+ // Neutralize the command word so the provider completes the
225
+ // (empty) argument position: every entry matches.
226
+ queryLines = [...lines];
227
+ queryLines[cursorLine] = before.replace(/![^!\s]*$/, "! ");
228
+ }
229
+ const suggestions = await current.getSuggestions(queryLines, cursorLine, cursorCol, {
230
+ ...options,
231
+ force: true,
232
+ });
233
+ const items = suggestions?.items ?? [];
234
+ if (items.length === 1) {
235
+ // Exactly one option: inline ghost instead of a popup. Returning
236
+ // null makes the stock machinery close/skip the dropdown.
237
+ const prefix = suggestions?.prefix ?? "";
238
+ const value = items[0]?.value ?? "";
239
+ const remainder = value.toLowerCase().startsWith(prefix.toLowerCase())
240
+ ? value.slice(prefix.length)
241
+ : "";
242
+ self.ghost = remainder ? { lineIndex: cursorLine, prefix, remainder } : null;
243
+ return null;
244
+ }
245
+ if (items.length === 0) {
246
+ self.ghost = null;
247
+ return null;
248
+ }
249
+ return suggestions;
250
+ },
251
+
252
+ applyCompletion(lines, cursorLine, cursorCol, item, prefix) {
253
+ const before = (lines[cursorLine] ?? "").slice(0, cursorCol);
254
+ if (self.inBashMode() && self.commandPosition(before)) {
255
+ // Completing from the command position: insert the chosen path
256
+ // as the first argument ("!cd" + AppleStuff/ → "!cd AppleStuff/").
257
+ const value = item.value ?? "";
258
+ const line = lines[cursorLine] ?? "";
259
+ const newLines = [...lines];
260
+ newLines[cursorLine] = `${line.slice(0, cursorCol)} ${value}${line.slice(cursorCol)}`;
261
+ return { lines: newLines, cursorLine, cursorCol: cursorCol + 1 + value.length };
262
+ }
263
+ return current.applyCompletion(lines, cursorLine, cursorCol, item, prefix);
264
+ },
265
+
266
+ shouldTriggerFileCompletion(lines, cursorLine, cursorCol) {
267
+ return current.shouldTriggerFileCompletion?.(lines, cursorLine, cursorCol) ?? true;
268
+ },
269
+ };
270
+ }
271
+ private activeGhost(): Ghost | null {
272
+ const ghost = this.ghost;
273
+ if (!ghost || this.isShowingAutocomplete() || !this.inBashMode()) {
274
+ return null;
275
+ }
276
+ const st = (this as unknown as EditorInternals).state;
277
+ if (ghost.lineIndex !== st.cursorLine || !this.cursorAtLineEnd()) {
278
+ return null;
279
+ }
280
+ const line = st.lines[st.cursorLine] ?? "";
281
+ if (!line.toLowerCase().endsWith(ghost.prefix.toLowerCase())) {
282
+ return null;
283
+ }
284
+ return ghost;
285
+ }
286
+
287
+ private acceptGhost(): void {
288
+ const ghost = this.activeGhost();
289
+ if (!ghost) {
290
+ return;
291
+ }
292
+ const st = (this as unknown as EditorInternals).state;
293
+ const line = st.lines[ghost.lineIndex] ?? "";
294
+ const col = st.cursorCol;
295
+ const completed = ghost.prefix + ghost.remainder;
296
+ const before = line.slice(0, col);
297
+ // Completing from the command position: the path becomes the first
298
+ // argument, so a leading space is part of the insertion.
299
+ const separator = this.commandPosition(before) ? " " : "";
300
+ (this as unknown as EditorInternals).pushUndoSnapshot();
301
+ st.lines[ghost.lineIndex] = line.slice(0, col - ghost.prefix.length) + separator + completed + line.slice(col);
302
+ this.ghost = null;
303
+ (this as unknown as EditorInternals).setCursorCol(
304
+ col - ghost.prefix.length + separator.length + completed.length,
305
+ );
306
+ this.onChange?.(this.getText());
307
+ // Like zsh: after completing into a directory, suggest its first entry.
308
+ this.updateGhost();
309
+ }
310
+
311
+ private updateGhost(): void {
312
+ const token = ++this.ghostToken;
313
+ const provider = this.bashProvider;
314
+ if (!provider || !this.inBashMode() || !this.cursorAtLineEnd()) {
315
+ this.ghost = null;
316
+ return;
317
+ }
318
+ const state = (this as unknown as EditorInternals).state;
319
+ const lineIndex = state.cursorLine;
320
+ const controller = new AbortController();
321
+ this.ghostAbort?.abort();
322
+ this.ghostAbort = controller;
323
+ void provider
324
+ .getSuggestions(state.lines, lineIndex, state.cursorCol, {
325
+ signal: controller.signal,
326
+ force: true,
327
+ })
328
+ .then((suggestions: AutocompleteSuggestions | null) => {
329
+ if (token !== this.ghostToken) {
330
+ return;
331
+ }
332
+ // The wrapper owns ghost state (single matches are diverted to
333
+ // the ghost there); this only triggers the dropdown for >1.
334
+ const items = suggestions?.items ?? [];
335
+ const st = this as unknown as EditorInternals;
336
+ if (items.length > 1 && !this.isShowingAutocomplete()) {
337
+ this.ghost = null;
338
+ st.requestAutocomplete({ force: true, explicitTab: false });
339
+ }
340
+ st.tui.requestRender();
341
+ })
342
+ .catch(() => {});
343
+ }
344
+ }
345
+
346
+ export default function (pi: ExtensionAPI): void {
347
+ pi.on("session_start", (_event, ctx) => {
348
+ ctx.ui.setEditorComponent((tui, theme, keybindings) => new BashInlineEditor(tui, theme, keybindings));
349
+ });
350
+ }
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "pi-autosuggestions",
3
+ "version": "0.1.0",
4
+ "description": "zsh-autosuggestions-style ghost completions for the pi coding agent — history-based inline suggestions, path completion in bash mode, blinking beam cursor",
5
+ "keywords": [
6
+ "pi-package",
7
+ "pi",
8
+ "autocomplete",
9
+ "completions",
10
+ "autosuggestions",
11
+ "zsh"
12
+ ],
13
+ "license": "MIT",
14
+ "author": "Andrew Mahoney-Fernandes <0xPlayerOne>",
15
+ "type": "module",
16
+ "pi": {
17
+ "extensions": [
18
+ "./extensions/*.ts"
19
+ ]
20
+ },
21
+ "peerDependencies": {
22
+ "@earendil-works/pi-coding-agent": "*",
23
+ "@earendil-works/pi-tui": "*"
24
+ }
25
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json",
3
+ "bump-minor-pre-major": true,
4
+ "changelog-sections": [
5
+ { "type": "feat", "section": "Features" },
6
+ { "type": "fix", "section": "Bug Fixes" },
7
+ { "type": "perf", "section": "Performance" },
8
+ { "type": "revert", "section": "Reverts" },
9
+ { "type": "deps", "section": "Dependencies" },
10
+ { "type": "docs", "section": "Documentation" },
11
+ { "type": "test", "section": "Tests" },
12
+ { "type": "ci", "section": "CI" },
13
+ { "type": "refactor", "section": "Maintenance" },
14
+ { "type": "chore", "section": "Maintenance" }
15
+ ]
16
+ }