pi-autosuggestions 0.5.0 → 0.6.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.
@@ -1 +1 @@
1
- {".":"0.5.0"}
1
+ {".":"0.6.0"}
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.6.0](https://github.com/0xPlayerOne/pi-autosuggestions/compare/pi-autosuggestions-v0.5.0...pi-autosuggestions-v0.6.0) (2026-09-05)
4
+
5
+
6
+ ### Features
7
+
8
+ * cross-session history, candidate cycling, theme-aware cursor, new dynamic sources ([71fe236](https://github.com/0xPlayerOne/pi-autosuggestions/commit/71fe236ac272d54432da96aa35e53a919102f657))
9
+
3
10
  ## [0.5.0](https://github.com/0xPlayerOne/pi-autosuggestions/compare/pi-autosuggestions-v0.4.0...pi-autosuggestions-v0.5.0) (2026-09-04)
4
11
 
5
12
 
package/README.md CHANGED
@@ -23,6 +23,12 @@ pi install git:github.com/0xPlayerOne/pi-autosuggestions@pi-autosuggestions-v0.2
23
23
  pi install npm:pi-autosuggestions
24
24
  ```
25
25
 
26
+ ## Configuration
27
+
28
+ `/autosuggest` — toggle cross-session history for ghost suggestions (stored
29
+ in `~/.pi/agent/pi-autosuggestions.json`; applies from the next session).
30
+ Default: off (history is session-scoped).
31
+
26
32
  ## Scope
27
33
 
28
34
  | Layer | Where it works |
@@ -32,11 +38,19 @@ pi install npm:pi-autosuggestions
32
38
  | Command-name completion | **Bash mode only**, first word after `!` |
33
39
  | Beam cursor | **Everywhere** |
34
40
 
35
- History is **session-scoped**: the ghost can only suggest prompts you already
36
- submitted *in the current session* (pi has no persistent shell-history file
37
- across sessions yet). If you mostly run `!` commands, the ghost will mostly
38
- appear in bash mode — it isn't restricted there, it just has nothing to
39
- suggest elsewhere.
41
+ History is **session-scoped by default**: the ghost suggests prompts you
42
+ submitted in the current session. Opt into **cross-session history** with
43
+ `/autosuggest` — the extension then seeds suggestions from your previous
44
+ pi sessions in the same working directory (read from pi's own session files;
45
+ nothing leaves your machine). If you mostly run `!` commands, the ghost will
46
+ mostly appear in bash mode — it isn't restricted there, it just has nothing
47
+ to suggest elsewhere.
48
+
49
+ **Candidate cycling**: with multiple history matches, `Alt+Down` / `Alt+Up`
50
+ rotate the ghost through the alternatives (most recent first).
51
+
52
+ The cursor colors follow the **pi theme** (accent while "on", dim while
53
+ "off"), so they stay visible on light and dark themes.
40
54
 
41
55
  ## Features
42
56
 
@@ -80,6 +94,9 @@ static table (results cached for 10s):
80
94
  | `!npm run d` / `!pnpm run` / `!bun d` (implicit for yarn/pnpm/bun) | `scripts` from the nearest `package.json` |
81
95
  | `!make d` | targets parsed from the nearest `Makefile` |
82
96
  | `!docker compose u` | compose subcommands |
97
+ | `!docker start n` / `logs` / `exec` … | running container names |
98
+ | `!kubectl get p` | resource types |
99
+ | `!ssh ` / `!scp ` | hosts from `~/.ssh/config` |
83
100
 
84
101
  ### Command completion (bash mode)
85
102
 
@@ -20,8 +20,9 @@ import {
20
20
  } from "@earendil-works/pi-tui";
21
21
 
22
22
  /** Runtime access to Editor internals that are private in the type declarations. */
23
- import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
23
+ import { existsSync, readFileSync, realpathSync, readdirSync, statSync, writeFileSync } from "node:fs";
24
24
  import { dirname } from "node:path";
25
+ import { homedir } from "node:os";
25
26
  import type { AutocompleteItem } from "@earendil-works/pi-tui";
26
27
 
27
28
  interface EditorInternals {
@@ -37,6 +38,30 @@ const DIM = "\x1b[2m";
37
38
  const RESET = "\x1b[0m";
38
39
  /** Set at extension load; used for dynamic completion exec calls. */
39
40
  let execApi: ExtensionAPI | undefined;
41
+ /** Active pi theme (set at session start) for theme-aware cursor colors. */
42
+ let themeRef: { fg(name: string, text: string): string } | undefined;
43
+ /** Persisted extension settings (~/.pi/agent/pi-autosuggestions.json). */
44
+ interface AutosuggestConfig {
45
+ crossSessionHistory?: boolean;
46
+ }
47
+ let config: AutosuggestConfig = {};
48
+ const configPath = `${homedir()}/.pi/agent/pi-autosuggestions.json`;
49
+
50
+ function loadConfig(): void {
51
+ try {
52
+ config = JSON.parse(readFileSync(configPath, "utf8"));
53
+ } catch {
54
+ config = {};
55
+ }
56
+ }
57
+
58
+ function saveConfig(): void {
59
+ try {
60
+ writeFileSync(configPath, JSON.stringify(config, null, 2));
61
+ } catch {
62
+ // read-only home — settings stay in-memory
63
+ }
64
+ }
40
65
  /** Beam cursor: thin vertical bar, bold so it stands out. One cell wide. */
41
66
  const BEAM = "\x1b[1m▏\x1b[0m";
42
67
  /** Matches the reverse-video block the base renderer emits for the cursor. */
@@ -177,6 +202,18 @@ const COMPOSE_SUBCOMMANDS = [
177
202
 
178
203
  // (SUBCOMMANDS gains more tables below — see SUBCOMMANDS_EXTRA merge point.)
179
204
 
205
+ const DOCKER_CONTAINER_VERBS = [
206
+ "start", "stop", "restart", "kill", "rm", "logs", "exec", "inspect", "stats",
207
+ "top", "pause", "unpause", "commit",
208
+ ];
209
+
210
+ const KUBECTL_RESOURCES = [
211
+ "pods", "po", "deployments", "deploy", "services", "svc", "ingresses", "ing",
212
+ "nodes", "no", "namespaces", "ns", "configmaps", "cm", "secrets", "persistentvolumes",
213
+ "pv", "persistentvolumeclaims", "pvc", "events", "ev", "replicasets", "rs",
214
+ "statefulsets", "sts", "daemonsets", "ds", "jobs", "cronjobs", "hpa", "endpoints", "ep",
215
+ ];
216
+
180
217
  const BLINK_INTERVAL_MS = 500;
181
218
  /** Cursor stays solid for this long after each keystroke, then resumes blinking. */
182
219
  const SOLID_AFTER_INPUT_MS = 450;
@@ -192,6 +229,10 @@ class BashInlineEditor extends CustomEditor {
192
229
  private ghostAbort?: AbortController;
193
230
  /** Submitted prompts, oldest first — the zsh-autosuggestions history strategy. */
194
231
  private promptHistory: string[] = [];
232
+ private historyLoaded = false;
233
+ /** History candidates for the current ghost (most recent first). */
234
+ private ghostCandidates: string[] = [];
235
+ private ghostCandidateIndex = 0;
195
236
  /** Set by Escape; keeps the ghost dismissed until the next text edit. */
196
237
  private ghostSuppressed = false;
197
238
 
@@ -279,6 +320,14 @@ class BashInlineEditor extends CustomEditor {
279
320
  this.acceptGhostWord();
280
321
  return;
281
322
  }
323
+ if (matchesKey(data, "alt+down")) {
324
+ this.cycleGhostCandidate(1);
325
+ return;
326
+ }
327
+ if (matchesKey(data, "alt+up")) {
328
+ this.cycleGhostCandidate(-1);
329
+ return;
330
+ }
282
331
  }
283
332
  super.handleInput(data);
284
333
  if (matchesKey(data, "escape")) {
@@ -386,6 +435,15 @@ class BashInlineEditor extends CustomEditor {
386
435
  return st.cursorCol === (st.lines[st.cursorLine] ?? "").length;
387
436
  }
388
437
 
438
+ /** Theme-aware styles; fall back to white/dim when no theme is set. */
439
+ private bright(text: string): string {
440
+ return themeRef ? themeRef.fg("accent", text) : `${CURSOR_COLOR}${text}${RESET}`;
441
+ }
442
+
443
+ private dimmed(text: string): string {
444
+ return themeRef ? themeRef.fg("dim", text) : `${DIM}${text}${RESET}`;
445
+ }
446
+
389
447
  /** Suppress the dropdown in bash mode unless the popup is already open. */
390
448
 
391
449
  /**
@@ -528,6 +586,32 @@ class BashInlineEditor extends CustomEditor {
528
586
  }
529
587
 
530
588
  /** Live sources: git branches, package scripts, make targets, compose. */
589
+ private sshHosts(): Promise<string[]> {
590
+ return this.cached("ssh:hosts", 60_000, async () => {
591
+ const cfg = `${homedir()}/.ssh/config`;
592
+ if (!existsSync(cfg)) {
593
+ return [];
594
+ }
595
+ const hosts: string[] = [];
596
+ for (const lineText of readFileSync(cfg, "utf8").split("\n")) {
597
+ const m = /^\s*[Hh]ost\s+(.+)$/.exec(lineText);
598
+ if (m) {
599
+ for (const host of m[1]!.trim().split(/\s+/)) {
600
+ if (!host.includes("*") && !hosts.includes(host)) {
601
+ hosts.push(host);
602
+ }
603
+ }
604
+ }
605
+ }
606
+ return hosts;
607
+ });
608
+ }
609
+
610
+ private dockerContainers(): Promise<string[]> {
611
+ return this.cached("docker:containers", 10_000, async () =>
612
+ await this.runCommand("docker", ["ps", "--format", "{{.Names}}"]));
613
+ }
614
+
531
615
  private async dynamicCompletions(
532
616
  cmd: string,
533
617
  args: string[],
@@ -553,6 +637,15 @@ class BashInlineEditor extends CustomEditor {
553
637
  } else if (cmd === "docker" && args[0] === "compose" && args.length === 1) {
554
638
  items = COMPOSE_SUBCOMMANDS.filter((sc) => sc.startsWith(token));
555
639
  description = "compose subcommand";
640
+ } else if (cmd === "docker" && args.length === 1 && DOCKER_CONTAINER_VERBS.includes(args[0]!)) {
641
+ items = (await this.dockerContainers()).filter((c) => c.startsWith(token));
642
+ description = "container";
643
+ } else if (cmd === "kubectl" && args[0] === "get" && args.length === 1) {
644
+ items = KUBECTL_RESOURCES.filter((r) => r.startsWith(token));
645
+ description = "resource";
646
+ } else if (["ssh", "scp"].includes(cmd) && args.length === 0) {
647
+ items = (await this.sshHosts()).filter((h) => h.startsWith(token));
648
+ description = "host";
556
649
  }
557
650
  if (!items || items.length === 0) {
558
651
  return null;
@@ -683,22 +776,103 @@ class BashInlineEditor extends CustomEditor {
683
776
 
684
777
  /** Most recent history entry extending the current line (history strategy). */
685
778
  private historyGhost(): Ghost | null {
779
+ this.loadCrossSessionHistory();
686
780
  const st = (this as unknown as EditorInternals).state;
687
781
  const line = st.lines[st.cursorLine] ?? "";
688
782
  const typed = line.slice(0, st.cursorCol);
689
783
  if (!typed.trim()) {
690
784
  return null;
691
785
  }
786
+ const matches: string[] = [];
692
787
  for (let i = this.promptHistory.length - 1; i >= 0; i--) {
693
788
  const entry = this.promptHistory[i] ?? "";
694
789
  // Suggest only the entry's first line: ghost text renders on a
695
790
  // single editor row (full multi-line entries are inserted on accept).
696
791
  const firstLine = entry.split("\n", 1)[0] ?? "";
697
- if (firstLine.length > typed.length && firstLine.startsWith(typed)) {
698
- return { lineIndex: st.cursorLine, typed, suggestion: firstLine, source: "history" };
792
+ if (firstLine.length > typed.length && firstLine.startsWith(typed) && !matches.includes(firstLine)) {
793
+ matches.push(firstLine);
794
+ }
795
+ }
796
+ this.ghostCandidates = matches;
797
+ this.ghostCandidateIndex = 0;
798
+ const first = matches[0];
799
+ return first ? { lineIndex: st.cursorLine, typed, suggestion: first, source: "history" } : null;
800
+ }
801
+
802
+ /**
803
+ * Seed the history strategy with prompts from previous sessions in this
804
+ * working directory. Opt-in via /autosuggest; runs once per editor.
805
+ */
806
+ private loadCrossSessionHistory(): void {
807
+ if (this.historyLoaded) {
808
+ return;
809
+ }
810
+ this.historyLoaded = true;
811
+ if (!config.crossSessionHistory) {
812
+ return;
813
+ }
814
+ try {
815
+ const sessionsDir = `${homedir()}/.pi/agent/sessions`;
816
+ const encoded = (p: string) => `--${p.split("/").filter(Boolean).join("-")}--`;
817
+ let dir: string | undefined;
818
+ for (const candidate of [process.cwd(), realpathSync(process.cwd())]) {
819
+ const path13 = `${sessionsDir}/${encoded(candidate)}`;
820
+ if (existsSync(path13)) {
821
+ dir = path13;
822
+ break;
823
+ }
824
+ }
825
+ if (!dir) {
826
+ return;
827
+ }
828
+ const files = readdirSync(dir)
829
+ .filter((f) => f.endsWith(".jsonl"))
830
+ .sort()
831
+ .slice(-5);
832
+ const prompts: string[] = [];
833
+ for (const file of files) {
834
+ for (const lineText of readFileSync(`${dir}/${file}`, "utf8").split("\n")) {
835
+ try {
836
+ const entry = JSON.parse(lineText) as {
837
+ type?: string;
838
+ message?: { role?: string; content?: string | { type?: string; text?: string }[] };
839
+ };
840
+ if (entry.type !== "message" || entry.message?.role !== "user") {
841
+ continue;
842
+ }
843
+ const content = entry.message.content;
844
+ const text =
845
+ typeof content === "string"
846
+ ? content
847
+ : (content ?? [])
848
+ .filter((b) => b.type === "text")
849
+ .map((b) => b.text ?? "")
850
+ .join("");
851
+ const firstLine = text.split("\n", 1)[0] ?? "";
852
+ if (firstLine.trim()) {
853
+ prompts.push(firstLine);
854
+ }
855
+ } catch {
856
+ // partial line or unsupported entry
857
+ }
858
+ }
699
859
  }
860
+ // Cross-session entries come before anything typed this session.
861
+ this.promptHistory = [...prompts.reverse(), ...this.promptHistory];
862
+ } catch (e) {
700
863
  }
701
- return null;
864
+ }
865
+
866
+ /** Rotate to the previous/next history candidate (Alt+Up / Alt+Down). */
867
+ private cycleGhostCandidate(dir: 1 | -1): void {
868
+ const ghost = this.activeGhost();
869
+ if (!ghost || ghost.source !== "history" || this.ghostCandidates.length < 2) {
870
+ return;
871
+ }
872
+ this.ghostCandidateIndex =
873
+ (this.ghostCandidateIndex + dir + this.ghostCandidates.length) % this.ghostCandidates.length;
874
+ this.ghost = { ...ghost, suggestion: this.ghostCandidates[this.ghostCandidateIndex]! };
875
+ (this as unknown as EditorInternals).tui.requestRender();
702
876
  }
703
877
 
704
878
  /** Path ghost from provider suggestions (completion strategy, bash mode). */
@@ -821,9 +995,28 @@ class BashInlineEditor extends CustomEditor {
821
995
 
822
996
  export default function (pi: ExtensionAPI): void {
823
997
  execApi = pi;
998
+ loadConfig();
824
999
  pi.on("session_start", (_event, ctx) => {
1000
+ themeRef = ctx.ui.theme;
825
1001
  ctx.ui.setEditorComponent((tui, theme, keybindings) => new BashInlineEditor(tui, theme, keybindings));
826
1002
  });
1003
+ pi.registerCommand("autosuggest", {
1004
+ description: "Toggle cross-session history for ghost suggestions",
1005
+ handler: async (args, ctx) => {
1006
+ const arg = (args ?? "").trim().toLowerCase();
1007
+ if (arg === "on" || arg === "off") {
1008
+ config.crossSessionHistory = arg === "on";
1009
+ } else {
1010
+ config.crossSessionHistory = !config.crossSessionHistory;
1011
+ }
1012
+ saveConfig();
1013
+ const state = config.crossSessionHistory ? "ON" : "OFF";
1014
+ ctx.ui.notify(
1015
+ `pi-autosuggestions: cross-session history ${state}${config.crossSessionHistory ? " (applies next session)" : ""}`,
1016
+ "info",
1017
+ );
1018
+ },
1019
+ });
827
1020
  // Restore the terminal's own cursor color and shape when pi exits so the
828
1021
  // shell afterwards isn't left with our forced white bar.
829
1022
  process.on("exit", () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-autosuggestions",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
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
5
  "keywords": [
6
6
  "pi-package",