@kliebhan/pi-prompt-autocomplete 0.3.0 → 0.5.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 (5) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +43 -8
  3. package/core.ts +433 -5
  4. package/index.ts +753 -245
  5. package/package.json +2 -2
package/core.ts CHANGED
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { readFileSync } from "node:fs";
3
3
  import { stripVTControlCharacters } from "node:util";
4
4
  import type { Api, Model } from "@earendil-works/pi-ai";
5
+ import type { KeyId, KeybindingsConfig } from "@earendil-works/pi-tui";
5
6
 
6
7
  const TEMPLATE_VARIABLE_PATTERN = /(?<!\\)\{\{\s*([A-Z0-9_]+)\s*(?:\|\s*([\s\S]*?))?\s*\}\}/g;
7
8
  const ESCAPED_TEMPLATE_VARIABLE_PATTERN = /\\(\{\{\s*[A-Z0-9_]+\s*(?:\|\s*[\s\S]*?)?\s*\}\})/g;
@@ -176,6 +177,48 @@ export function buildPromptAutocompletePrefixContextKey(
176
177
  return `${identity.modelLabel}|prefix|${hashPromptAutocompleteIdentity(identity)}`;
177
178
  }
178
179
 
180
+ /** What an Escape dismissal is bound to besides the draft. */
181
+ export interface PromptAutocompleteDismissalContextIdentity {
182
+ conversationId: string;
183
+ /** `provider/id` of the requested model, whether or not it can serve a request right now. */
184
+ requestedModel: string;
185
+ maxAlternatives: number;
186
+ maxSuggestionChars: number;
187
+ }
188
+
189
+ /**
190
+ * Context identity of an Escape dismissal.
191
+ *
192
+ * Unlike the prefix context key it needs no resolved, authenticated model, so a
193
+ * refresh can compare it before any gate: switching to a model that cannot
194
+ * serve a request still ends the dismissal.
195
+ */
196
+ export function buildPromptAutocompleteDismissalContext(
197
+ identity: PromptAutocompleteDismissalContextIdentity,
198
+ ): string {
199
+ return JSON.stringify([
200
+ identity.conversationId,
201
+ identity.requestedModel,
202
+ identity.maxAlternatives,
203
+ identity.maxSuggestionChars,
204
+ ]);
205
+ }
206
+
207
+ /**
208
+ * Whether an Escape dismissal still covers this draft in this context.
209
+ *
210
+ * A non-empty dismissed draft covers every draft that extends it. An empty one
211
+ * covers only the empty draft, because every draft extends "".
212
+ */
213
+ export function promptAutocompleteDismissalCovers(
214
+ dismissal: { draft: string; context: string },
215
+ draft: string,
216
+ context: string,
217
+ ): boolean {
218
+ if (dismissal.context !== context) return false;
219
+ return dismissal.draft.length === 0 ? draft.length === 0 : draft.startsWith(dismissal.draft);
220
+ }
221
+
179
222
  export class ExpiringLruCache<T> {
180
223
  private readonly entries = new Map<string, { value: T; expiresAt: number }>();
181
224
  private readonly ttlMs: number;
@@ -692,6 +735,8 @@ export interface PromptAutocompletePersistedSettings {
692
735
  maxAlternatives?: number;
693
736
  /** Raw dedicated model, or `active` for the session model. Invalid values are dropped on load. */
694
737
  model?: string;
738
+ /** Keys per configurable action; invalid key names are dropped on load. */
739
+ keys?: PromptAutocompleteKeySettings;
695
740
  }
696
741
 
697
742
  /**
@@ -737,12 +782,98 @@ export function parsePromptAutocompletePersistedSettings(
737
782
  const model = parsePersistedModelRaw(record.model);
738
783
  if (model !== undefined) settings.model = persistableModelRaw(model);
739
784
  }
785
+ const keys = readPersistedKeys(record.keys);
786
+ if (keys) settings.keys = keys;
740
787
  return settings;
741
788
  }
742
789
 
790
+ /** Saved keys per configurable action, keeping only names in Pi's key grammar. */
791
+ function readPersistedKeys(value: unknown): PromptAutocompleteKeySettings | undefined {
792
+ if (!isRecord(value)) return undefined;
793
+ const keys: PromptAutocompleteKeySettings = {};
794
+ for (const action of PROMPT_AUTOCOMPLETE_CONFIGURABLE_KEY_ACTIONS) {
795
+ const entry = value[action];
796
+ if (!Array.isArray(entry)) continue;
797
+ keys[action] = entry.flatMap((raw) => {
798
+ const key = typeof raw === "string" ? parsePromptAutocompleteKeyId(raw) : undefined;
799
+ return key ? [key] : [];
800
+ });
801
+ }
802
+ return Object.keys(keys).length > 0 ? keys : undefined;
803
+ }
804
+
805
+ /**
806
+ * Apply a settings decision to the in-memory settings.
807
+ *
808
+ * `keys` merges per action, and an action set to `undefined` returns to its
809
+ * default keys.
810
+ */
811
+ export function applyPromptAutocompleteSettingsPatch(
812
+ settings: PromptAutocompletePersistedSettings,
813
+ patch: Partial<PromptAutocompletePersistedSettings>,
814
+ ): PromptAutocompletePersistedSettings {
815
+ const next = { ...settings, ...patch };
816
+ if (patch.keys) next.keys = mergeKeySettings(settings.keys ?? {}, patch.keys);
817
+ if (next.keys === undefined) delete next.keys;
818
+ return next;
819
+ }
820
+
821
+ function mergeKeySettings(
822
+ current: PromptAutocompleteKeySettings,
823
+ patch: PromptAutocompleteKeySettings,
824
+ ): PromptAutocompleteKeySettings | undefined {
825
+ const merged: PromptAutocompleteKeySettings = { ...current, ...patch };
826
+ for (const action of PROMPT_AUTOCOMPLETE_CONFIGURABLE_KEY_ACTIONS) {
827
+ if (merged[action] === undefined) delete merged[action];
828
+ }
829
+ return Object.keys(merged).length > 0 ? merged : undefined;
830
+ }
831
+
832
+ /**
833
+ * Write one settings decision into the current settings file text.
834
+ *
835
+ * The file is re-read right before every save, so a decision another Pi
836
+ * process saved in the meantime survives; only the decision itself changes.
837
+ * Fields this version does not know, such as a newer version's settings, stay
838
+ * as they are. Invalid values in the patch are not written.
839
+ */
840
+ export function mergePromptAutocompleteSettingsText(
841
+ currentText: string | undefined,
842
+ patch: Partial<PromptAutocompletePersistedSettings>,
843
+ ): string {
844
+ let current: Record<string, unknown> = {};
845
+ try {
846
+ const parsed: unknown = currentText ? JSON.parse(currentText) : {};
847
+ if (isRecord(parsed)) current = parsed;
848
+ } catch {
849
+ // An unreadable file is replaced by the decision, as on first save.
850
+ }
851
+ const { keys: patchKeys, ...scalars } = patch;
852
+ const next: Record<string, unknown> = { ...current, ...toPersistedPayload(scalars) };
853
+ if (patchKeys) {
854
+ // Other actions, including ones this version does not know, stay as written.
855
+ const keys: Record<string, unknown> = isRecord(current.keys) ? { ...current.keys } : {};
856
+ const valid = toPersistedPayload({ keys: patchKeys }).keys ?? {};
857
+ for (const action of PROMPT_AUTOCOMPLETE_CONFIGURABLE_KEY_ACTIONS) {
858
+ if (!(action in patchKeys)) continue;
859
+ const value = valid[action];
860
+ if (value === undefined) delete keys[action];
861
+ else keys[action] = value;
862
+ }
863
+ if (Object.keys(keys).length > 0) next.keys = keys;
864
+ else delete next.keys;
865
+ }
866
+ return `${JSON.stringify(next, null, 2)}\n`;
867
+ }
868
+
743
869
  export function serializePromptAutocompletePersistedSettings(
744
870
  settings: PromptAutocompletePersistedSettings,
745
871
  ): string {
872
+ return `${JSON.stringify(toPersistedPayload(settings), null, 2)}\n`;
873
+ }
874
+
875
+ /** The valid decisions in `settings`, as they are written to the file. */
876
+ function toPersistedPayload(settings: PromptAutocompletePersistedSettings): PromptAutocompletePersistedSettings {
746
877
  const payload: PromptAutocompletePersistedSettings = {};
747
878
  if (typeof settings.enabled === "boolean") payload.enabled = settings.enabled;
748
879
  if (
@@ -779,7 +910,15 @@ export function serializePromptAutocompletePersistedSettings(
779
910
  }
780
911
  const model = parsePersistedModelRaw(settings.model);
781
912
  if (model !== undefined) payload.model = persistableModelRaw(model);
782
- return `${JSON.stringify(payload, null, 2)}\n`;
913
+ if (settings.keys) {
914
+ const keys: PromptAutocompleteKeySettings = {};
915
+ for (const action of PROMPT_AUTOCOMPLETE_CONFIGURABLE_KEY_ACTIONS) {
916
+ const entry = settings.keys[action];
917
+ if (entry) keys[action] = entry.filter((key) => parsePromptAutocompleteKeyId(key) === key);
918
+ }
919
+ if (Object.keys(keys).length > 0) payload.keys = keys;
920
+ }
921
+ return payload;
783
922
  }
784
923
 
785
924
  function readPersistedBoundedInt(
@@ -2346,6 +2485,15 @@ export function reusePromptAutocompleteSuggestions(
2346
2485
  return suggestions.length > 0 ? { suggestions, origins } : undefined;
2347
2486
  }
2348
2487
 
2488
+ /**
2489
+ * The suggestion up to and including its first line break, or all of it when
2490
+ * it has one line; accepting it leaves the cursor at the start of the next line.
2491
+ */
2492
+ export function extractSuggestionLine(suggestion: string): string {
2493
+ const lineBreak = suggestion.indexOf("\n");
2494
+ return lineBreak < 0 ? suggestion : suggestion.slice(0, lineBreak + 1);
2495
+ }
2496
+
2349
2497
  export function extractNextSuggestionChunk(suggestion: string): string | undefined {
2350
2498
  if (!suggestion) return undefined;
2351
2499
 
@@ -2491,13 +2639,15 @@ export const PROMPT_AUTOCOMPLETE_SET_KEYS = [
2491
2639
  { key: "max-chars", min: MAX_SUGGESTION_CHARS_MIN, max: MAX_SUGGESTION_CHARS_MAX, description: "Maximum characters per suggestion" },
2492
2640
  { key: "max-alternatives", min: MAX_ALTERNATIVES_MIN, max: MAX_ALTERNATIVES_MAX, description: "Maximum alternatives per request" },
2493
2641
  { key: "model", description: "Model for autocomplete requests" },
2642
+ { key: "key", description: "Keys for a Prompt Autocomplete action" },
2494
2643
  ] as const;
2495
2644
 
2496
2645
  export type PromptAutocompleteSetKey = (typeof PROMPT_AUTOCOMPLETE_SET_KEYS)[number]["key"];
2497
2646
 
2498
2647
  /** Usage placeholder of one set key, e.g. `<0-5000>`. */
2499
2648
  export function formatSetKeyPlaceholder(spec: (typeof PROMPT_AUTOCOMPLETE_SET_KEYS)[number]): string {
2500
- return "min" in spec ? `<${spec.min}-${spec.max}>` : "<provider/model|active>";
2649
+ if ("min" in spec) return `<${spec.min}-${spec.max}>`;
2650
+ return spec.key === "key" ? "<action> <key...|default|none>" : "<provider/model|active>";
2501
2651
  }
2502
2652
 
2503
2653
  const SET_COMPLETIONS: readonly PromptAutocompleteCommandCompletion[] = PROMPT_AUTOCOMPLETE_SET_KEYS.flatMap((spec) => [
@@ -2508,17 +2658,292 @@ const SET_COMPLETIONS: readonly PromptAutocompleteCommandCompletion[] = PROMPT_A
2508
2658
  value: `set ${spec.key} `,
2509
2659
  // `active` has its own entry above, so the model label leaves it out and
2510
2660
  // fits Pi's 30-column label space.
2511
- label: `set ${spec.key} ${"min" in spec ? formatSetKeyPlaceholder(spec) : "<provider/model>"}`,
2661
+ label: `set ${spec.key} ${"min" in spec ? formatSetKeyPlaceholder(spec) : spec.key === "key" ? "<action> <keys>" : "<provider/model>"}`,
2512
2662
  description: spec.description,
2513
2663
  },
2514
2664
  ]);
2515
2665
 
2666
+
2516
2667
  const ON_OFF_TOGGLE = (subject: string) => [
2517
2668
  ["on", `Turn ${subject} on`],
2518
2669
  ["off", `Turn ${subject} off`],
2519
2670
  ["toggle", `Switch ${subject}`],
2520
2671
  ] as const;
2521
2672
 
2673
+ /**
2674
+ * Prompt Autocomplete's key actions: command name for `set key`, label for
2675
+ * hints, and default keys, the first of which hints show.
2676
+ *
2677
+ * `accept` and `dismiss` take `tab` and `escape` only while ghost text is
2678
+ * visible and are fixed. The configurable actions act only on input that Pi
2679
+ * leaves free, so a user's Pi keymap or a Pi default on the same key wins.
2680
+ */
2681
+ export const PROMPT_AUTOCOMPLETE_KEY_ACTIONS = {
2682
+ accept: { command: "accept", keys: ["tab"] },
2683
+ acceptWord: { command: "accept-word", keys: ["ctrl+space", "ctrl+tab"] },
2684
+ acceptLine: { command: "accept-line", keys: [] },
2685
+ /** Also the manual one-shot trigger when no suggestion is shown. */
2686
+ cycleNext: { command: "cycle-next", keys: ["ctrl+.", "alt+]"] },
2687
+ cyclePrev: { command: "cycle-prev", keys: ["ctrl+,", "alt+["] },
2688
+ dismiss: { command: "dismiss", keys: ["escape"] },
2689
+ } as const satisfies Record<string, { command: string; keys: readonly KeyId[] }>;
2690
+
2691
+ export type PromptAutocompleteKeyAction = keyof typeof PROMPT_AUTOCOMPLETE_KEY_ACTIONS;
2692
+
2693
+ /** Actions whose keys `set key` changes, in resolution order. */
2694
+ export const PROMPT_AUTOCOMPLETE_CONFIGURABLE_KEY_ACTIONS = [
2695
+ "acceptWord",
2696
+ "acceptLine",
2697
+ "cycleNext",
2698
+ "cyclePrev",
2699
+ ] as const satisfies readonly PromptAutocompleteKeyAction[];
2700
+
2701
+ export type PromptAutocompleteConfigurableKeyAction = (typeof PROMPT_AUTOCOMPLETE_CONFIGURABLE_KEY_ACTIONS)[number];
2702
+
2703
+ /** Saved keys per configurable action; an empty list unbinds the action. */
2704
+ export type PromptAutocompleteKeySettings = Partial<Record<PromptAutocompleteConfigurableKeyAction, KeyId[]>>;
2705
+
2706
+ export function findConfigurableKeyAction(command: string): PromptAutocompleteConfigurableKeyAction | undefined {
2707
+ return PROMPT_AUTOCOMPLETE_CONFIGURABLE_KEY_ACTIONS.find(
2708
+ (action) => PROMPT_AUTOCOMPLETE_KEY_ACTIONS[action].command === command,
2709
+ );
2710
+ }
2711
+
2712
+ const KEY_MODIFIER_ORDER = ["ctrl", "shift", "alt", "super"] as const;
2713
+ const KEY_NAME_ALIASES: Record<string, string> = { esc: "escape", return: "enter" };
2714
+ /** US-layout symbols that Shift produces; Pi matches both spellings of such a key. */
2715
+ const SHIFTED_SYMBOLS: Record<string, string> = {
2716
+ "`": "~", "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&", "8": "*", "9": "(", "0": ")",
2717
+ "-": "_", "=": "+", "[": "{", "]": "}", "\\": "|", ";": ":", ",": "<", ".": ">", "/": "?",
2718
+ };
2719
+ /** Key ids that legacy terminals encode as the same bytes as another key id. */
2720
+ const LEGACY_EQUIVALENT_KEYS: Record<string, string> = {
2721
+ "ctrl+i": "tab",
2722
+ "ctrl+[": "escape",
2723
+ "ctrl+m": "enter",
2724
+ "ctrl+h": "backspace",
2725
+ "ctrl+_": "ctrl+-",
2726
+ };
2727
+ /**
2728
+ * Pi's named keys, the values of pi-tui's `Key` (a test keeps them equal).
2729
+ * Listed here because importing pi-tui at runtime would stop this module from
2730
+ * loading where `Intl.Segmenter` is missing.
2731
+ */
2732
+ export const PI_KEY_NAMES: readonly string[] = [
2733
+ "escape", "esc", "enter", "return", "tab", "space", "backspace", "delete", "insert", "clear", "home", "end",
2734
+ "pageUp", "pageDown", "up", "down", "left", "right",
2735
+ "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "f10", "f11", "f12",
2736
+ "`", "-", "=", "[", "]", "\\", ";", "'", ",", ".", "/", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")",
2737
+ "_", "+", "|", "~", "{", "}", ":", "<", ">", "?",
2738
+ ];
2739
+ /** Pi's key names by lowercase spelling (`pageup` → `pageUp`). */
2740
+ const PI_KEY_NAMES_BY_LOWERCASE = new Map(PI_KEY_NAMES.map((name) => [name.toLowerCase(), name] as const));
2741
+
2742
+ /** Modifiers and base key of a key id; `ctrl++` keeps its `+` key. */
2743
+ function splitKeyId(key: string): { modifiers: Set<string>; base: string } {
2744
+ let rest = key.toLowerCase();
2745
+ const modifiers = new Set<string>();
2746
+ for (let matched = true; matched;) {
2747
+ matched = false;
2748
+ for (const modifier of KEY_MODIFIER_ORDER) {
2749
+ if (rest.startsWith(`${modifier}+`) && rest.length > modifier.length + 1) {
2750
+ modifiers.add(modifier);
2751
+ rest = rest.slice(modifier.length + 1);
2752
+ matched = true;
2753
+ }
2754
+ }
2755
+ }
2756
+ const base = KEY_NAME_ALIASES[rest] ?? rest;
2757
+ // `ctrl+shift+=` and `ctrl++` name the same keypress.
2758
+ const shifted = modifiers.has("shift") ? SHIFTED_SYMBOLS[base] : undefined;
2759
+ if (!shifted) return { modifiers, base };
2760
+ modifiers.delete("shift");
2761
+ return { modifiers, base: shifted };
2762
+ }
2763
+
2764
+ /**
2765
+ * Comparable form of a key id: lowercase, modifiers in a fixed order, Pi's key
2766
+ * name aliases resolved, Shift plus a symbol folded into the shifted symbol,
2767
+ * and legacy byte-equivalent keys folded together.
2768
+ */
2769
+ export function canonicalKeyId(key: string): string {
2770
+ const normalized = normalizeKeyId(key);
2771
+ return LEGACY_EQUIVALENT_KEYS[normalized] ?? normalized;
2772
+ }
2773
+
2774
+ /** `canonicalKeyId` without folding legacy byte equivalents. */
2775
+ function normalizeKeyId(key: string): string {
2776
+ const { modifiers, base } = splitKeyId(key);
2777
+ return [...KEY_MODIFIER_ORDER.filter((modifier) => modifiers.has(modifier)), base].join("+");
2778
+ }
2779
+
2780
+ /** Pi's spelling of a key id in its documented grammar, or undefined. */
2781
+ function spellKeyId(raw: string): string | undefined {
2782
+ let rest = raw.trim().toLowerCase();
2783
+ const modifiers: string[] = [];
2784
+ for (;;) {
2785
+ const modifier = KEY_MODIFIER_ORDER.find(
2786
+ (candidate) => rest.startsWith(`${candidate}+`) && rest.length > candidate.length + 1,
2787
+ );
2788
+ if (!modifier) break;
2789
+ if (modifiers.includes(modifier)) return undefined;
2790
+ modifiers.push(modifier);
2791
+ rest = rest.slice(modifier.length + 1);
2792
+ }
2793
+ const base = /^[a-z0-9]$/.test(rest) ? rest : PI_KEY_NAMES_BY_LOWERCASE.get(rest);
2794
+ return base === undefined ? undefined : [...modifiers, base].join("+");
2795
+ }
2796
+
2797
+ function isKeyId(value: string): value is KeyId {
2798
+ return spellKeyId(value) === value;
2799
+ }
2800
+
2801
+ /**
2802
+ * Parse a key in Pi's documented grammar (`ctrl+shift+x`, `alt+]`, `f5`):
2803
+ * modifiers `ctrl`, `shift`, `alt`, `super` at most once each, then a letter,
2804
+ * digit, or one of Pi's key names. Case-insensitive; returns Pi's spelling.
2805
+ */
2806
+ export function parsePromptAutocompleteKeyId(raw: string): KeyId | undefined {
2807
+ const spelled = spellKeyId(raw);
2808
+ return spelled !== undefined && isKeyId(spelled) ? spelled : undefined;
2809
+ }
2810
+
2811
+ const RESERVED_KEYS = new Set(["tab", "escape", "enter", "backspace"]);
2812
+ // `ctrl+j` arrives as a line feed in legacy terminals, which the editor inserts as a newline.
2813
+ const EDITOR_HARD_CODED_KEYS = new Set(["shift+space", "shift+backspace", "shift+delete", "shift+enter", "ctrl+j"]);
2814
+
2815
+ /**
2816
+ * Why a key cannot be a Prompt Autocomplete key, or undefined if it can.
2817
+ *
2818
+ * Tab, Escape, Enter, and Backspace (also as their legacy aliases such as
2819
+ * `ctrl+i`), the keys Pi's editor handles outside its keymap, keys that type
2820
+ * text, and keys Pi's matcher never recognizes (Escape or F1–F12 with a
2821
+ * modifier, Clear with anything but Shift or Ctrl alone) would never reach
2822
+ * the action, or would take text away.
2823
+ */
2824
+ export function describeUnusablePromptAutocompleteKey(key: string): string | undefined {
2825
+ const canonical = canonicalKeyId(key);
2826
+ if (RESERVED_KEYS.has(canonical)) {
2827
+ return LEGACY_EQUIVALENT_KEYS[normalizeKeyId(key)] ? `${key} is the same input as ${canonical}` : `${key} is reserved`;
2828
+ }
2829
+ if (EDITOR_HARD_CODED_KEYS.has(canonical)) return `Pi's editor handles ${key}`;
2830
+ const { modifiers, base } = splitKeyId(key);
2831
+ // Pi's matcher has no encoding for these modifier combinations.
2832
+ const onlyShiftOrCtrl = modifiers.size === 1 && (modifiers.has("shift") || modifiers.has("ctrl"));
2833
+ if (
2834
+ modifiers.size > 0
2835
+ && (base === "escape" || /^f([1-9]|1[0-2])$/.test(base) || (base === "clear" && !onlyShiftOrCtrl))
2836
+ ) {
2837
+ return `Pi does not recognize ${key}`;
2838
+ }
2839
+ const typesText = [...modifiers].every((modifier) => modifier === "shift")
2840
+ && (base.length === 1 || base === "space");
2841
+ return typesText ? `${key} types text` : undefined;
2842
+ }
2843
+
2844
+ /** Effective Prompt Autocomplete keys, where each came from, and what was dropped. */
2845
+ export interface PromptAutocompleteKeymap {
2846
+ keys: Record<PromptAutocompleteKeyAction, readonly KeyId[]>;
2847
+ sources: Record<PromptAutocompleteConfigurableKeyAction, "default" | "saved">;
2848
+ /** Saved keys that cannot be used, with the reason. */
2849
+ ignored: string[];
2850
+ }
2851
+
2852
+ /** Every action with its effective keys and their source, in hint order. */
2853
+ export function listPromptAutocompleteKeys(
2854
+ keymap: PromptAutocompleteKeymap,
2855
+ ): Array<{ command: string; keys: readonly KeyId[]; source: "default" | "saved" | "fixed" }> {
2856
+ const fixed = (action: "accept" | "dismiss") => ({
2857
+ command: PROMPT_AUTOCOMPLETE_KEY_ACTIONS[action].command,
2858
+ keys: keymap.keys[action],
2859
+ source: "fixed" as const,
2860
+ });
2861
+ return [
2862
+ fixed("accept"),
2863
+ ...PROMPT_AUTOCOMPLETE_CONFIGURABLE_KEY_ACTIONS.map((action) => ({
2864
+ command: PROMPT_AUTOCOMPLETE_KEY_ACTIONS[action].command,
2865
+ keys: keymap.keys[action],
2866
+ source: keymap.sources[action],
2867
+ })),
2868
+ fixed("dismiss"),
2869
+ ];
2870
+ }
2871
+
2872
+ /**
2873
+ * Resolve saved keys over the defaults.
2874
+ *
2875
+ * A key that cannot be used, or that an earlier action already has (fixed
2876
+ * actions first, then the configurable ones in table order), is dropped, so
2877
+ * one keypress always means one action.
2878
+ */
2879
+ export function resolvePromptAutocompleteKeymap(saved: PromptAutocompleteKeySettings = {}): PromptAutocompleteKeymap {
2880
+ const { accept, dismiss } = PROMPT_AUTOCOMPLETE_KEY_ACTIONS;
2881
+ const owners = new Map<string, PromptAutocompleteKeyAction>();
2882
+ for (const key of accept.keys) owners.set(canonicalKeyId(key), "accept");
2883
+ for (const key of dismiss.keys) owners.set(canonicalKeyId(key), "dismiss");
2884
+ const configurable: Record<PromptAutocompleteConfigurableKeyAction, KeyId[]> = {
2885
+ acceptWord: [],
2886
+ acceptLine: [],
2887
+ cycleNext: [],
2888
+ cyclePrev: [],
2889
+ };
2890
+ const sources: PromptAutocompleteKeymap["sources"] = {
2891
+ acceptWord: "default",
2892
+ acceptLine: "default",
2893
+ cycleNext: "default",
2894
+ cyclePrev: "default",
2895
+ };
2896
+ const ignored: string[] = [];
2897
+ for (const action of PROMPT_AUTOCOMPLETE_CONFIGURABLE_KEY_ACTIONS) {
2898
+ const configured = saved[action];
2899
+ if (configured) sources[action] = "saved";
2900
+ for (const key of configured ?? PROMPT_AUTOCOMPLETE_KEY_ACTIONS[action].keys) {
2901
+ const canonical = canonicalKeyId(key);
2902
+ const owner = owners.get(canonical);
2903
+ if (owner === action) continue;
2904
+ const reason = describeUnusablePromptAutocompleteKey(key)
2905
+ ?? (owner ? `${key} already ${PROMPT_AUTOCOMPLETE_KEY_ACTIONS[owner].command}` : undefined);
2906
+ if (reason) {
2907
+ ignored.push(reason);
2908
+ continue;
2909
+ }
2910
+ owners.set(canonical, action);
2911
+ configurable[action].push(key);
2912
+ }
2913
+ }
2914
+ return { keys: { ...configurable, accept: accept.keys, dismiss: dismiss.keys }, sources, ignored };
2915
+ }
2916
+
2917
+ /**
2918
+ * Pi actions whose resolved keys look like `key`.
2919
+ *
2920
+ * For diagnostics only. The editor decides at input time with Pi's own
2921
+ * matcher, so a miss here can hide a warning but never let a key act on input
2922
+ * that Pi uses.
2923
+ */
2924
+ export function findPiKeyConflicts(key: string, resolvedBindings: KeybindingsConfig): string[] {
2925
+ const wanted = canonicalKeyId(key);
2926
+ const conflicts: string[] = [];
2927
+ for (const [action, keys] of Object.entries(resolvedBindings)) {
2928
+ if (keys === undefined) continue;
2929
+ if ((Array.isArray(keys) ? keys : [keys]).some((bound) => canonicalKeyId(bound) === wanted)) {
2930
+ conflicts.push(action);
2931
+ }
2932
+ }
2933
+ return conflicts;
2934
+ }
2935
+
2936
+ /** `set key` forms, offered once `set key ` is typed so `set ` stays short. */
2937
+ const SET_KEY_COMPLETIONS: readonly PromptAutocompleteCommandCompletion[] = PROMPT_AUTOCOMPLETE_CONFIGURABLE_KEY_ACTIONS
2938
+ .flatMap((action) => {
2939
+ const { command } = PROMPT_AUTOCOMPLETE_KEY_ACTIONS[action];
2940
+ return [
2941
+ { value: `set key ${command} `, label: `set key ${command} <keys>`, description: "Space-separated keys" },
2942
+ { value: `set key ${command} default`, label: `set key ${command} default`, description: "Restore the default keys" },
2943
+ { value: `set key ${command} none`, label: `set key ${command} none`, description: "Unbind the action" },
2944
+ ];
2945
+ });
2946
+
2522
2947
  /**
2523
2948
  * The `/prompt-autocomplete` grammar: the single source for dispatch, usage
2524
2949
  * text, and argument completion. Order is the order of the usage text.
@@ -2545,6 +2970,7 @@ export const PROMPT_AUTOCOMPLETE_COMMANDS = [
2545
2970
  ...commandSpec("set", "Show runtime knobs", { usage: "<key> [value]", bareComplete: true }),
2546
2971
  completions: SET_COMPLETIONS,
2547
2972
  },
2973
+ commandSpec("keys", "Show the key for every action", { readOnly: true }),
2548
2974
  commandSpec("stream", "Toggle streamed response previews", {
2549
2975
  usage: "on|off|toggle",
2550
2976
  choices: ON_OFF_TOGGLE("streamed previews"),
@@ -2594,7 +3020,9 @@ const ALL_COMMAND_COMPLETIONS: readonly PromptAutocompleteCommandCompletion[] =
2594
3020
  const COMPLETE_ARGUMENTS: ReadonlySet<string> = new Set([
2595
3021
  ...PROMPT_AUTOCOMPLETE_COMMANDS.filter((spec) => spec.bareComplete).map((spec) => spec.name),
2596
3022
  ...PROMPT_AUTOCOMPLETE_SET_KEYS.filter((spec) => "bareReports" in spec).map((spec) => `set ${spec.key}`),
2597
- ...ALL_COMMAND_COMPLETIONS.map((completion) => completion.value).filter((value) => !value.endsWith(" ")),
3023
+ ...[...ALL_COMMAND_COMPLETIONS, ...SET_KEY_COMPLETIONS]
3024
+ .map((completion) => completion.value)
3025
+ .filter((value) => !value.endsWith(" ")),
2598
3026
  ]);
2599
3027
 
2600
3028
  /**
@@ -2610,7 +3038,7 @@ export function completePromptAutocompleteArguments(
2610
3038
  ): PromptAutocompleteCommandCompletion[] | null {
2611
3039
  const typed = argumentPrefix.trimStart().replace(/\s+/g, " ").toLowerCase();
2612
3040
  if (COMPLETE_ARGUMENTS.has(typed)) return null;
2613
- const matches = ALL_COMMAND_COMPLETIONS
3041
+ const matches = (typed.startsWith("set key ") ? SET_KEY_COMPLETIONS : ALL_COMMAND_COMPLETIONS)
2614
3042
  .filter((completion) => completion.value.length > typed.length && completion.value.startsWith(typed))
2615
3043
  .map((completion) => ({ ...completion }));
2616
3044
  return matches.length > 0 ? matches : null;