@kliebhan/pi-prompt-autocomplete 0.2.5 → 0.4.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/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;
@@ -81,16 +82,31 @@ export const DEFAULT_PREFERRED_MODEL = "current active model";
81
82
  export const DEFAULT_PROMPT_AUTOCOMPLETE_ENABLED = false;
82
83
  export const DEFAULT_STREAM_RESPONSES = true;
83
84
  export const DEFAULT_DEBOUNCE_MS = 350;
85
+ export const DEBOUNCE_MS_MIN = 0;
86
+ export const DEBOUNCE_MS_MAX = 5_000;
84
87
  export const DEFAULT_MIN_PROMPT_CHARS = 1;
85
88
  export const MIN_PROMPT_CHARS_MIN = 0;
86
89
  export const MIN_PROMPT_CHARS_MAX = 500;
87
90
  export const DEFAULT_MAX_SUGGESTION_CHARS = 160;
91
+ export const MAX_SUGGESTION_CHARS_MIN = 16;
92
+ export const MAX_SUGGESTION_CHARS_MAX = 1_000;
88
93
  export const DEFAULT_MAX_ALTERNATIVES = 3;
94
+ export const MAX_ALTERNATIVES_MIN = 1;
95
+ export const MAX_ALTERNATIVES_MAX = 5;
96
+ /** Provider-request ceiling bounds; `off` (no ceiling) is the default. */
97
+ export const BUDGET_REQUESTS_MIN = 1;
98
+ export const BUDGET_REQUESTS_MAX = 100_000;
99
+ export const DEFAULT_BUDGET_REQUESTS_FLAG = "off";
100
+ /** Custom-entry customType carrying versioned budget snapshots. */
101
+ export const PROMPT_AUTOCOMPLETE_BUDGET_ENTRY_TYPE = "prompt-autocomplete-stats";
102
+ export const PROMPT_AUTOCOMPLETE_BUDGET_SCHEMA_VERSION = 1;
89
103
  export const MAX_DRAFT_CONTEXT_CHARS = 2_000;
90
104
  export const MAX_CONTEXT_MESSAGES = 6;
91
105
  export const MAX_CONTEXT_MESSAGE_CHARS = 600;
92
106
  export const MAX_LATEST_ASSISTANT_MESSAGE_CHARS = 3_000;
93
107
  export const MAX_LATEST_USER_MESSAGE_CHARS = 1_200;
108
+ /** Bound for the latest compaction summary; the middle is elided so goal and next steps survive. */
109
+ export const MAX_COMPACTION_SUMMARY_CHARS = 1_500;
94
110
  // Scale the completion budget with the requested alternatives so a JSON array of
95
111
  // several short suggestions cannot be truncated mid-string (which would break parsing).
96
112
  export const MIN_REQUEST_MAX_TOKENS = 192;
@@ -102,7 +118,7 @@ export interface ModelRef {
102
118
  }
103
119
 
104
120
  export interface PromptAutocompleteCacheIdentity {
105
- leafId: string;
121
+ conversationId: string;
106
122
  modelLabel: string;
107
123
  maxAlternatives: number;
108
124
  maxSuggestionChars: number;
@@ -110,6 +126,38 @@ export interface PromptAutocompleteCacheIdentity {
110
126
  latestAssistantContext: string;
111
127
  latestUserContext: string;
112
128
  recentContext: string;
129
+ compactionSummaryContext: string;
130
+ }
131
+
132
+ /** Session entries that advance the raw leaf without changing autocomplete context. */
133
+ const AUTOCOMPLETE_METADATA_ENTRY_TYPES = new Set(["custom", "label", "session_info"]);
134
+
135
+ export function isAutocompleteMetadataEntry(entry: unknown): boolean {
136
+ return isRecord(entry)
137
+ && typeof entry.type === "string"
138
+ && AUTOCOMPLETE_METADATA_ENTRY_TYPES.has(entry.type);
139
+ }
140
+
141
+ /**
142
+ * Newest branch entry that affects transmitted autocomplete context.
143
+ *
144
+ * Custom, label, and session-info entries are skipped because they are excluded
145
+ * from model context. Entries without an id are skipped so a host that omits
146
+ * ids can still fall back to the raw leaf. `custom_message` is kept: it is
147
+ * included in LLM context even though today's context builders only read
148
+ * `type === "message"`.
149
+ */
150
+ export function resolveAutocompleteConversationId(
151
+ branch: unknown[],
152
+ fallbackId = "",
153
+ ): string {
154
+ for (let index = branch.length - 1; index >= 0; index -= 1) {
155
+ const entry = branch[index];
156
+ if (isAutocompleteMetadataEntry(entry)) continue;
157
+ if (!isRecord(entry) || typeof entry.id !== "string" || entry.id.length === 0) continue;
158
+ return entry.id;
159
+ }
160
+ return fallbackId;
113
161
  }
114
162
 
115
163
  export type PromptAutocompletePrefixContextIdentity = Omit<PromptAutocompleteCacheIdentity, "draft">;
@@ -129,6 +177,48 @@ export function buildPromptAutocompletePrefixContextKey(
129
177
  return `${identity.modelLabel}|prefix|${hashPromptAutocompleteIdentity(identity)}`;
130
178
  }
131
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
+
132
222
  export class ExpiringLruCache<T> {
133
223
  private readonly entries = new Map<string, { value: T; expiresAt: number }>();
134
224
  private readonly ttlMs: number;
@@ -611,6 +701,12 @@ export interface PromptAutocompleteRuntimeOverrides {
611
701
  streamResponses?: boolean;
612
702
  debug?: boolean;
613
703
  minPromptChars?: number;
704
+ debounceMs?: number;
705
+ maxSuggestionChars?: number;
706
+ maxAlternatives?: number;
707
+ modelSelection?: PromptAutocompleteModelSelection;
708
+ /** Session request ceiling; `"off"` is an explicit decision, not unset. */
709
+ budgetLimit?: PromptAutocompleteBudgetSetting;
614
710
  }
615
711
 
616
712
  export type PromptAutocompleteSettingSource = "flag" | "saved" | "session";
@@ -626,13 +722,21 @@ export function describeSettingSource(override: unknown): PromptAutocompleteSett
626
722
  /**
627
723
  * Settings persisted across processes.
628
724
  *
629
- * Only explicit `/prompt-autocomplete on|off` decisions are stored. An absent
630
- * field defers to the CLI flag, so an empty or missing file behaves exactly
631
- * like no persisted decision.
725
+ * Explicit `/prompt-autocomplete on|off`, `min-chars`, and `set` decisions are
726
+ * stored. An absent field defers to the CLI flag, so an empty or missing file
727
+ * behaves exactly like no persisted decision. The file stores nothing but these
728
+ * decisions: no conversation, cache, or stats.
632
729
  */
633
730
  export interface PromptAutocompletePersistedSettings {
634
731
  enabled?: boolean;
635
732
  minPromptChars?: number;
733
+ debounceMs?: number;
734
+ maxSuggestionChars?: number;
735
+ maxAlternatives?: number;
736
+ /** Raw dedicated model, or `active` for the session model. Invalid values are dropped on load. */
737
+ model?: string;
738
+ /** Keys per configurable action; invalid key names are dropped on load. */
739
+ keys?: PromptAutocompleteKeySettings;
636
740
  }
637
741
 
638
742
  /**
@@ -656,20 +760,120 @@ export function parsePromptAutocompletePersistedSettings(
656
760
  const record = parsed as Record<string, unknown>;
657
761
  const settings: PromptAutocompletePersistedSettings = {};
658
762
  if (typeof record.enabled === "boolean") settings.enabled = record.enabled;
659
- if (
660
- typeof record.minPromptChars === "number"
661
- && Number.isInteger(record.minPromptChars)
662
- && record.minPromptChars >= MIN_PROMPT_CHARS_MIN
663
- && record.minPromptChars <= MIN_PROMPT_CHARS_MAX
664
- ) {
665
- settings.minPromptChars = record.minPromptChars;
763
+ const minPromptChars = readPersistedBoundedInt(record, "minPromptChars", MIN_PROMPT_CHARS_MIN, MIN_PROMPT_CHARS_MAX);
764
+ if (minPromptChars !== undefined) settings.minPromptChars = minPromptChars;
765
+ const debounceMs = readPersistedBoundedInt(record, "debounceMs", DEBOUNCE_MS_MIN, DEBOUNCE_MS_MAX);
766
+ if (debounceMs !== undefined) settings.debounceMs = debounceMs;
767
+ const maxSuggestionChars = readPersistedBoundedInt(
768
+ record,
769
+ "maxSuggestionChars",
770
+ MAX_SUGGESTION_CHARS_MIN,
771
+ MAX_SUGGESTION_CHARS_MAX,
772
+ );
773
+ if (maxSuggestionChars !== undefined) settings.maxSuggestionChars = maxSuggestionChars;
774
+ const maxAlternatives = readPersistedBoundedInt(
775
+ record,
776
+ "maxAlternatives",
777
+ MAX_ALTERNATIVES_MIN,
778
+ MAX_ALTERNATIVES_MAX,
779
+ );
780
+ if (maxAlternatives !== undefined) settings.maxAlternatives = maxAlternatives;
781
+ if (typeof record.model === "string") {
782
+ const model = parsePersistedModelRaw(record.model);
783
+ if (model !== undefined) settings.model = persistableModelRaw(model);
666
784
  }
785
+ const keys = readPersistedKeys(record.keys);
786
+ if (keys) settings.keys = keys;
667
787
  return settings;
668
788
  }
669
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
+
670
869
  export function serializePromptAutocompletePersistedSettings(
671
870
  settings: PromptAutocompletePersistedSettings,
672
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 {
673
877
  const payload: PromptAutocompletePersistedSettings = {};
674
878
  if (typeof settings.enabled === "boolean") payload.enabled = settings.enabled;
675
879
  if (
@@ -680,7 +884,52 @@ export function serializePromptAutocompletePersistedSettings(
680
884
  ) {
681
885
  payload.minPromptChars = settings.minPromptChars;
682
886
  }
683
- return `${JSON.stringify(payload, null, 2)}\n`;
887
+ if (
888
+ typeof settings.debounceMs === "number"
889
+ && Number.isInteger(settings.debounceMs)
890
+ && settings.debounceMs >= DEBOUNCE_MS_MIN
891
+ && settings.debounceMs <= DEBOUNCE_MS_MAX
892
+ ) {
893
+ payload.debounceMs = settings.debounceMs;
894
+ }
895
+ if (
896
+ typeof settings.maxSuggestionChars === "number"
897
+ && Number.isInteger(settings.maxSuggestionChars)
898
+ && settings.maxSuggestionChars >= MAX_SUGGESTION_CHARS_MIN
899
+ && settings.maxSuggestionChars <= MAX_SUGGESTION_CHARS_MAX
900
+ ) {
901
+ payload.maxSuggestionChars = settings.maxSuggestionChars;
902
+ }
903
+ if (
904
+ typeof settings.maxAlternatives === "number"
905
+ && Number.isInteger(settings.maxAlternatives)
906
+ && settings.maxAlternatives >= MAX_ALTERNATIVES_MIN
907
+ && settings.maxAlternatives <= MAX_ALTERNATIVES_MAX
908
+ ) {
909
+ payload.maxAlternatives = settings.maxAlternatives;
910
+ }
911
+ const model = parsePersistedModelRaw(settings.model);
912
+ if (model !== undefined) payload.model = persistableModelRaw(model);
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;
922
+ }
923
+
924
+ function readPersistedBoundedInt(
925
+ record: Record<string, unknown>,
926
+ key: string,
927
+ min: number,
928
+ max: number,
929
+ ): number | undefined {
930
+ const value = record[key];
931
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) return undefined;
932
+ return value;
684
933
  }
685
934
 
686
935
  /**
@@ -741,6 +990,222 @@ export function parseExplicitBoundedIntFlag(
741
990
  return bounded === defaultValue ? undefined : bounded;
742
991
  }
743
992
 
993
+ /**
994
+ * Parse a slash-command integer. Out-of-range and malformed values are rejected
995
+ * rather than clamped, so the user sees the valid range instead of a silent
996
+ * substitution.
997
+ */
998
+ export function parseStrictBoundedInt(
999
+ value: string | undefined,
1000
+ min: number,
1001
+ max: number,
1002
+ ): number | undefined {
1003
+ if (value === undefined) return undefined;
1004
+ const trimmed = value.trim();
1005
+ if (!trimmed) return undefined;
1006
+ const parsed = Number.parseInt(trimmed, 10);
1007
+ if (!Number.isFinite(parsed) || String(parsed) !== trimmed) return undefined;
1008
+ if (parsed < min || parsed > max) return undefined;
1009
+ return parsed;
1010
+ }
1011
+
1012
+ /**
1013
+ * An explicit `--prompt-autocomplete-model` value, or undefined when the flag
1014
+ * still holds its registered default. `active` is an explicit sentinel and is
1015
+ * not treated as unset.
1016
+ */
1017
+ export function parseExplicitModelFlag(
1018
+ value: boolean | string | undefined,
1019
+ ): PromptAutocompleteModelSelection | undefined {
1020
+ if (typeof value !== "string") return undefined;
1021
+ const trimmed = value.trim();
1022
+ if (!trimmed || trimmed.toLowerCase() === DEFAULT_PREFERRED_MODEL) return undefined;
1023
+ return parsePromptAutocompleteModelSelection(trimmed);
1024
+ }
1025
+
1026
+ export function persistableModelRaw(selection: PromptAutocompleteModelSelection): string | undefined {
1027
+ if (selection.kind === "active") return "active";
1028
+ if (selection.kind === "dedicated") return selection.raw;
1029
+ return undefined;
1030
+ }
1031
+
1032
+ export function parsePersistedModelRaw(value: string | undefined): PromptAutocompleteModelSelection | undefined {
1033
+ if (typeof value !== "string") return undefined;
1034
+ const trimmed = value.trim();
1035
+ // An empty field is "no decision", not an explicit request for the session model.
1036
+ if (!trimmed) return undefined;
1037
+ const selection = parsePromptAutocompleteModelSelection(trimmed);
1038
+ return selection.kind === "invalid" ? undefined : selection;
1039
+ }
1040
+
1041
+ export function resolvePersistedModelSelection(
1042
+ override: PromptAutocompleteModelSelection | undefined,
1043
+ explicitFlag: PromptAutocompleteModelSelection | undefined,
1044
+ saved: PromptAutocompleteModelSelection | undefined,
1045
+ ): { selection: PromptAutocompleteModelSelection; source: PromptAutocompleteSettingSource } {
1046
+ if (override !== undefined) return { selection: override, source: "session" };
1047
+ if (explicitFlag !== undefined) return { selection: explicitFlag, source: "flag" };
1048
+ if (saved !== undefined) return { selection: saved, source: "saved" };
1049
+ return { selection: { kind: "active" }, source: "flag" };
1050
+ }
1051
+
1052
+ /**
1053
+ * Session-scoped provider-request ceiling.
1054
+ *
1055
+ * The limit is the effective ceiling (`undefined` means off) and `used` counts
1056
+ * every provider invocation reserved in the current physical session,
1057
+ * including failed and aborted ones, and including invocations made while the
1058
+ * ceiling was off. Cache hits and in-flight joins never reserve.
1059
+ */
1060
+ export interface PromptAutocompleteBudgetState {
1061
+ limit?: number;
1062
+ used: number;
1063
+ }
1064
+
1065
+ export type PromptAutocompleteBudgetSetting = number | "off";
1066
+
1067
+ /** A restored snapshot always carries a real decision, including an explicit `off`. */
1068
+ export interface PromptAutocompleteBudgetSnapshotState {
1069
+ limit: PromptAutocompleteBudgetSetting;
1070
+ used: number;
1071
+ }
1072
+
1073
+ /**
1074
+ * Parse the `--prompt-autocomplete-max-requests` flag. Flags clamp: invalid
1075
+ * input and the registered default (`off`) fall back to "no explicit flag",
1076
+ * which defers to the session-restored value.
1077
+ */
1078
+ export function parsePromptAutocompleteBudgetFlag(
1079
+ value: boolean | string | undefined,
1080
+ ): number | undefined {
1081
+ if (typeof value !== "string") return undefined;
1082
+ const trimmed = value.trim();
1083
+ if (!trimmed || trimmed.toLowerCase() === DEFAULT_BUDGET_REQUESTS_FLAG) return undefined;
1084
+ const parsed = Number.parseInt(trimmed, 10);
1085
+ if (!Number.isFinite(parsed) || String(parsed) !== trimmed) return undefined;
1086
+ return Math.min(BUDGET_REQUESTS_MAX, Math.max(BUDGET_REQUESTS_MIN, parsed));
1087
+ }
1088
+
1089
+ /** Result of parsing an interactive `budget` argument. */
1090
+ export type ParsedPromptAutocompleteBudgetValue =
1091
+ | { kind: "limit"; value: number }
1092
+ | { kind: "off" }
1093
+ | { kind: "unset" }
1094
+ | { kind: "invalid" };
1095
+
1096
+ /**
1097
+ * Parse `/prompt-autocomplete budget <n|off>`. Interactive values are rejected
1098
+ * rather than clamped so the user sees the valid range.
1099
+ */
1100
+ export function parsePromptAutocompleteBudgetValue(value: string | undefined): ParsedPromptAutocompleteBudgetValue {
1101
+ if (value === undefined || !value.trim()) return { kind: "unset" };
1102
+ const trimmed = value.trim();
1103
+ if (trimmed.toLowerCase() === DEFAULT_BUDGET_REQUESTS_FLAG) return { kind: "off" };
1104
+ if (!/^\d+$/.test(trimmed)) return { kind: "invalid" };
1105
+ const parsed = Number.parseInt(trimmed, 10);
1106
+ if (parsed < BUDGET_REQUESTS_MIN || parsed > BUDGET_REQUESTS_MAX) return { kind: "invalid" };
1107
+ return { kind: "limit", value: parsed };
1108
+ }
1109
+
1110
+ /** Durable snapshot of the session budget, appended as a non-LLM custom entry. */
1111
+ export interface PromptAutocompleteBudgetSnapshot {
1112
+ schemaVersion: number;
1113
+ physicalSessionId: string;
1114
+ limit: PromptAutocompleteBudgetSetting;
1115
+ used: number;
1116
+ }
1117
+
1118
+ export function buildPromptAutocompleteBudgetSnapshot(
1119
+ limit: PromptAutocompleteBudgetSetting,
1120
+ used: number,
1121
+ physicalSessionId: string,
1122
+ ): PromptAutocompleteBudgetSnapshot {
1123
+ return {
1124
+ schemaVersion: PROMPT_AUTOCOMPLETE_BUDGET_SCHEMA_VERSION,
1125
+ physicalSessionId,
1126
+ limit,
1127
+ used,
1128
+ };
1129
+ }
1130
+
1131
+ /**
1132
+ * Parse a persisted snapshot. Unknown schema versions, foreign physical
1133
+ * sessions, and malformed fields degrade to `undefined` (fresh budget).
1134
+ */
1135
+ export function parsePromptAutocompleteBudgetSnapshot(
1136
+ data: unknown,
1137
+ physicalSessionId: string,
1138
+ ): PromptAutocompleteBudgetSnapshotState | undefined {
1139
+ if (!isRecord(data)) return undefined;
1140
+ if (data.schemaVersion !== PROMPT_AUTOCOMPLETE_BUDGET_SCHEMA_VERSION) return undefined;
1141
+ if (data.physicalSessionId !== physicalSessionId) return undefined;
1142
+ const limit: PromptAutocompleteBudgetSetting | undefined = data.limit === "off"
1143
+ ? "off"
1144
+ : typeof data.limit === "number" && Number.isInteger(data.limit)
1145
+ && data.limit >= BUDGET_REQUESTS_MIN && data.limit <= BUDGET_REQUESTS_MAX
1146
+ ? data.limit
1147
+ : undefined;
1148
+ if (limit === undefined) return undefined;
1149
+ if (typeof data.used !== "number" || !Number.isInteger(data.used) || data.used < 0) return undefined;
1150
+ return { limit, used: data.used };
1151
+ }
1152
+
1153
+ /**
1154
+ * Restore this physical session's budget from its own entries.
1155
+ *
1156
+ * Scans every entry of the session, not just the current leaf path: a request
1157
+ * paid for on a branch the user later left was still paid for, so switching
1158
+ * branches must not hand out a fresh allowance. Usage is therefore restored
1159
+ * monotonically (the highest observed count), while the ceiling is the last
1160
+ * recorded decision.
1161
+ */
1162
+ export function findPromptAutocompleteBudgetSnapshot(
1163
+ entries: unknown[],
1164
+ physicalSessionId: string,
1165
+ ): PromptAutocompleteBudgetSnapshotState | undefined {
1166
+ let restored: PromptAutocompleteBudgetSnapshotState | undefined;
1167
+ for (const entry of entries) {
1168
+ if (!isRecord(entry) || entry.type !== "custom") continue;
1169
+ if (entry.customType !== PROMPT_AUTOCOMPLETE_BUDGET_ENTRY_TYPE) continue;
1170
+ const snapshot = parsePromptAutocompleteBudgetSnapshot(entry.data, physicalSessionId);
1171
+ if (!snapshot) continue;
1172
+ restored = {
1173
+ limit: snapshot.limit,
1174
+ used: Math.max(restored?.used ?? 0, snapshot.used),
1175
+ };
1176
+ }
1177
+ return restored;
1178
+ }
1179
+
1180
+ /**
1181
+ * Thrown by a request producer that cannot reserve budget. This is not a
1182
+ * provider failure: it must not enter the failure cooldown or failure stats.
1183
+ */
1184
+ export class PromptAutocompleteBudgetExhaustedError extends Error {
1185
+ constructor(limit: number, used: number) {
1186
+ super(`Session request budget exhausted (${used}/${limit} provider requests used)`);
1187
+ this.name = "PromptAutocompleteBudgetExhaustedError";
1188
+ }
1189
+ }
1190
+
1191
+ /**
1192
+ * Resolve the effective request ceiling and its attribution. An explicit
1193
+ * `budget off` override outranks flag and saved values; the registered flag
1194
+ * default is indistinguishable from not passing the flag.
1195
+ */
1196
+ export function resolvePromptAutocompleteBudgetLimit(
1197
+ override: PromptAutocompleteBudgetSetting | undefined,
1198
+ explicitFlag: number | undefined,
1199
+ saved: PromptAutocompleteBudgetSetting | undefined,
1200
+ ): { limit?: number; source: PromptAutocompleteSettingSource } {
1201
+ if (override !== undefined) {
1202
+ return { limit: override === "off" ? undefined : override, source: "session" };
1203
+ }
1204
+ if (explicitFlag !== undefined) return { limit: explicitFlag, source: "flag" };
1205
+ if (saved !== undefined) return { limit: saved === "off" ? undefined : saved, source: "saved" };
1206
+ return { limit: undefined, source: "flag" };
1207
+ }
1208
+
744
1209
  interface SuggestionPayload {
745
1210
  completions?: unknown;
746
1211
  suggestions?: unknown;
@@ -1740,11 +2205,156 @@ export function buildLatestUserMessageContext(
1740
2205
  return buildLatestRoleMessageContext(branch, "user", maxChars);
1741
2206
  }
1742
2207
 
2208
+ /**
2209
+ * Model-visible conversation entries, in the shape the context builders read.
2210
+ *
2211
+ * Pi 1.x builds model context from a session projection that applies
2212
+ * `context_edit` entries and compaction: an edit can omit an earlier message or
2213
+ * replace its content, for example to redact it. Autocomplete must not send
2214
+ * what the model itself no longer sees, so its context comes from that
2215
+ * projection. Message entries contribute their messages, as with the raw
2216
+ * branch. A compaction contributes only its summary text, as a
2217
+ * `compaction_summary` entry, because the projection replaced the summarized
2218
+ * messages with it; the compaction's system checkpoint is never taken. A
2219
+ * malformed projection yields no conversation context rather than raw entries.
2220
+ */
2221
+ export function projectAutocompleteContextEntries(projection: unknown): unknown[] {
2222
+ if (!isRecord(projection) || !Array.isArray(projection.entries)) return [];
2223
+ const entries: unknown[] = [];
2224
+ for (const projected of projection.entries) {
2225
+ if (!isRecord(projected) || !isRecord(projected.sourceEntry) || !Array.isArray(projected.messages)) continue;
2226
+ const source = projected.sourceEntry;
2227
+ if (source.type === "compaction") {
2228
+ for (const message of projected.messages) {
2229
+ if (isRecord(message) && message.role === "compactionSummary" && typeof message.summary === "string") {
2230
+ entries.push({ type: "compaction_summary", id: source.id, summary: message.summary });
2231
+ }
2232
+ }
2233
+ continue;
2234
+ }
2235
+ if (source.type !== "message") continue;
2236
+ for (const message of projected.messages) {
2237
+ entries.push({ type: "message", id: source.id, message });
2238
+ }
2239
+ }
2240
+ return entries;
2241
+ }
2242
+
2243
+ /**
2244
+ * The newest compaction summary among projected context entries, bounded with
2245
+ * the middle elided. Raw branches never carry `compaction_summary` entries, so
2246
+ * hosts without a projection send no summary: they still see the summarized
2247
+ * messages themselves.
2248
+ */
2249
+ export function buildCompactionSummaryContext(
2250
+ entries: unknown[],
2251
+ maxChars = MAX_COMPACTION_SUMMARY_CHARS,
2252
+ ): string {
2253
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
2254
+ const entry = entries[index];
2255
+ if (!isRecord(entry) || entry.type !== "compaction_summary" || typeof entry.summary !== "string") continue;
2256
+ const summary = entry.summary.trim();
2257
+ if (summary) return truncateMiddle(summary, maxChars);
2258
+ }
2259
+ return "";
2260
+ }
2261
+
1743
2262
  export function truncateDraftTail(draft: string, maxChars = MAX_DRAFT_CONTEXT_CHARS): string {
1744
2263
  if (draft.length <= maxChars) return draft;
1745
2264
  return draft.slice(-maxChars);
1746
2265
  }
1747
2266
 
2267
+ /**
2268
+ * Everything one autocomplete request transmits, derived from the draft and
2269
+ * the conversation branch.
2270
+ *
2271
+ * The provider request and `/prompt-autocomplete inspect` consume the same
2272
+ * snapshot and render it with the same function, so the local preview cannot
2273
+ * drift from what is sent. Credentials and headers are never part of it.
2274
+ */
2275
+ export interface PromptAutocompleteRequestSnapshot {
2276
+ draft: string;
2277
+ /** The transmitted part of the draft: its last MAX_DRAFT_CONTEXT_CHARS characters. */
2278
+ draftTail: string;
2279
+ latestAssistantContext: string;
2280
+ latestUserContext: string;
2281
+ recentContext: string;
2282
+ /** Newest compaction summary the model sees; empty without one or without a host projection. */
2283
+ compactionSummaryContext: string;
2284
+ maxAlternatives: number;
2285
+ maxSuggestionChars: number;
2286
+ }
2287
+
2288
+ export function buildPromptAutocompleteRequestSnapshot(input: {
2289
+ draft: string;
2290
+ branch: unknown[];
2291
+ maxAlternatives: number;
2292
+ maxSuggestionChars: number;
2293
+ }): PromptAutocompleteRequestSnapshot {
2294
+ return {
2295
+ draft: input.draft,
2296
+ draftTail: truncateDraftTail(input.draft, MAX_DRAFT_CONTEXT_CHARS),
2297
+ latestAssistantContext: buildLatestAssistantMessageContext(input.branch),
2298
+ latestUserContext: buildLatestUserMessageContext(input.branch),
2299
+ recentContext: buildRecentConversationContext(input.branch),
2300
+ compactionSummaryContext: buildCompactionSummaryContext(input.branch),
2301
+ maxAlternatives: input.maxAlternatives,
2302
+ maxSuggestionChars: input.maxSuggestionChars,
2303
+ };
2304
+ }
2305
+
2306
+ /**
2307
+ * Render the single user message a request sends.
2308
+ *
2309
+ * Kept separate from the snapshot so the keystroke path only gathers context;
2310
+ * the message text is produced when a provider request is actually created,
2311
+ * or when inspection asks for it.
2312
+ */
2313
+ export function renderPromptAutocompleteUserText(snapshot: PromptAutocompleteRequestSnapshot): string {
2314
+ const sections: string[] = [];
2315
+ if (snapshot.latestAssistantContext) {
2316
+ sections.push(`Latest assistant message (primary context):\n${snapshot.latestAssistantContext}`);
2317
+ }
2318
+ if (snapshot.latestUserContext) {
2319
+ sections.push(`Latest user message:\n${snapshot.latestUserContext}`);
2320
+ }
2321
+ if (snapshot.recentContext) {
2322
+ sections.push(`Recent conversation summary:\n${snapshot.recentContext}`);
2323
+ }
2324
+ if (snapshot.compactionSummaryContext) {
2325
+ sections.push(`Earlier conversation summary (compacted background):\n${snapshot.compactionSummaryContext}`);
2326
+ }
2327
+
2328
+ if (snapshot.draft.length === 0) {
2329
+ sections.push("Current draft is empty.");
2330
+ sections.push(
2331
+ [
2332
+ `Task: propose up to ${snapshot.maxAlternatives} ranked full next prompts the user could send now.`,
2333
+ "Each item must be a complete next prompt, not a continuation fragment.",
2334
+ "Suggest the prompt most likely to move the overall project forward.",
2335
+ "Prefer 3-10 words when possible.",
2336
+ ].join("\n"),
2337
+ );
2338
+ } else {
2339
+ if (snapshot.draftTail.length < snapshot.draft.length) {
2340
+ sections.push(
2341
+ `Current draft tail (the real draft is longer; the cursor is at the end of the full draft):\n${snapshot.draftTail}`,
2342
+ );
2343
+ } else {
2344
+ sections.push(`Current draft (cursor at end):\n${snapshot.draft}`);
2345
+ }
2346
+
2347
+ sections.push(
2348
+ [
2349
+ `Task: propose up to ${snapshot.maxAlternatives} ranked continuations to insert at the cursor.`,
2350
+ "Each item must be only the text after the cursor; never restate text the user already typed.",
2351
+ "If the draft ends inside a partially typed word, complete that word directly without a leading space.",
2352
+ ].join("\n"),
2353
+ );
2354
+ }
2355
+ return sections.join("\n\n");
2356
+ }
2357
+
1748
2358
  export function shouldSkipPromptAutocomplete(text: string): boolean {
1749
2359
  const trimmedStart = text.trimStart();
1750
2360
  if (trimmedStart.startsWith("/") || trimmedStart.startsWith("!")) return true;
@@ -1875,6 +2485,15 @@ export function reusePromptAutocompleteSuggestions(
1875
2485
  return suggestions.length > 0 ? { suggestions, origins } : undefined;
1876
2486
  }
1877
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
+
1878
2497
  export function extractNextSuggestionChunk(suggestion: string): string | undefined {
1879
2498
  if (!suggestion) return undefined;
1880
2499
 
@@ -1953,3 +2572,474 @@ export function hostSupportsStreamedResponses(api: {
1953
2572
  if (typeof api.streamSimple === "function") return true;
1954
2573
  return typeof api.completeSimple !== "function";
1955
2574
  }
2575
+
2576
+ /** One argument completion, in the shape Pi's slash-command autocomplete expects. */
2577
+ export interface PromptAutocompleteCommandCompletion {
2578
+ /**
2579
+ * The full argument text after `/prompt-autocomplete `. Pi replaces the whole
2580
+ * argument span with it, so nested forms carry every token. A trailing space
2581
+ * leaves the cursor where the user types a value.
2582
+ */
2583
+ value: string;
2584
+ label: string;
2585
+ description: string;
2586
+ }
2587
+
2588
+ interface PromptAutocompleteCommandSpec<Name extends string> {
2589
+ name: Name;
2590
+ /** Placeholder after the name in the usage text, if the command takes an argument. */
2591
+ usage?: string;
2592
+ /** Reports state only, so it may run on hosts without an interactive editor. */
2593
+ readOnly: boolean;
2594
+ /** The name alone is a complete submission: it reports, toggles, or previews. */
2595
+ bareComplete: boolean;
2596
+ completions: readonly PromptAutocompleteCommandCompletion[];
2597
+ }
2598
+
2599
+ function commandSpec<Name extends string>(
2600
+ name: Name,
2601
+ description: string,
2602
+ options: {
2603
+ usage?: string;
2604
+ readOnly?: boolean;
2605
+ /** Fixed argument choices, each offered as a complete form. */
2606
+ choices?: readonly (readonly [choice: string, description: string])[];
2607
+ /** A free value: offered as the name and a space, labeled with this placeholder. */
2608
+ valuePlaceholder?: string;
2609
+ /** Arguments are optional; without choices or a value the name alone is the only form. */
2610
+ bareComplete?: boolean;
2611
+ } = {},
2612
+ ): PromptAutocompleteCommandSpec<Name> {
2613
+ const completions: PromptAutocompleteCommandCompletion[] = [];
2614
+ const takesArgument = !!options.choices || !!options.valuePlaceholder;
2615
+ if (!takesArgument) completions.push({ value: name, label: name, description });
2616
+ for (const [choice, choiceDescription] of options.choices ?? []) {
2617
+ completions.push({ value: `${name} ${choice}`, label: `${name} ${choice}`, description: choiceDescription });
2618
+ }
2619
+ if (options.valuePlaceholder) {
2620
+ completions.push({ value: `${name} `, label: `${name} ${options.valuePlaceholder}`, description });
2621
+ }
2622
+ return {
2623
+ name,
2624
+ usage: options.usage,
2625
+ readOnly: options.readOnly ?? false,
2626
+ bareComplete: !takesArgument || (options.bareComplete ?? false),
2627
+ completions,
2628
+ };
2629
+ }
2630
+
2631
+ /**
2632
+ * Keys accepted by `/prompt-autocomplete set`. Numeric keys carry their bounds,
2633
+ * which both validation and the usage text use. `bareReports` marks a key that
2634
+ * reports its value when submitted without one, so it is a complete command.
2635
+ */
2636
+ export const PROMPT_AUTOCOMPLETE_SET_KEYS = [
2637
+ { key: "debounce-ms", min: DEBOUNCE_MS_MIN, max: DEBOUNCE_MS_MAX, description: "Delay before an automatic request, in milliseconds" },
2638
+ { key: "min-chars", min: MIN_PROMPT_CHARS_MIN, max: MIN_PROMPT_CHARS_MAX, bareReports: true, description: "Minimum draft length for automatic suggestions" },
2639
+ { key: "max-chars", min: MAX_SUGGESTION_CHARS_MIN, max: MAX_SUGGESTION_CHARS_MAX, description: "Maximum characters per suggestion" },
2640
+ { key: "max-alternatives", min: MAX_ALTERNATIVES_MIN, max: MAX_ALTERNATIVES_MAX, description: "Maximum alternatives per request" },
2641
+ { key: "model", description: "Model for autocomplete requests" },
2642
+ { key: "key", description: "Keys for a Prompt Autocomplete action" },
2643
+ ] as const;
2644
+
2645
+ export type PromptAutocompleteSetKey = (typeof PROMPT_AUTOCOMPLETE_SET_KEYS)[number]["key"];
2646
+
2647
+ /** Usage placeholder of one set key, e.g. `<0-5000>`. */
2648
+ export function formatSetKeyPlaceholder(spec: (typeof PROMPT_AUTOCOMPLETE_SET_KEYS)[number]): string {
2649
+ if ("min" in spec) return `<${spec.min}-${spec.max}>`;
2650
+ return spec.key === "key" ? "<action> <key...|default|none>" : "<provider/model|active>";
2651
+ }
2652
+
2653
+ const SET_COMPLETIONS: readonly PromptAutocompleteCommandCompletion[] = PROMPT_AUTOCOMPLETE_SET_KEYS.flatMap((spec) => [
2654
+ ...(spec.key === "model"
2655
+ ? [{ value: "set model active", label: "set model active", description: "Follow the session model" }]
2656
+ : []),
2657
+ {
2658
+ value: `set ${spec.key} `,
2659
+ // `active` has its own entry above, so the model label leaves it out and
2660
+ // fits Pi's 30-column label space.
2661
+ label: `set ${spec.key} ${"min" in spec ? formatSetKeyPlaceholder(spec) : spec.key === "key" ? "<action> <keys>" : "<provider/model>"}`,
2662
+ description: spec.description,
2663
+ },
2664
+ ]);
2665
+
2666
+
2667
+ const ON_OFF_TOGGLE = (subject: string) => [
2668
+ ["on", `Turn ${subject} on`],
2669
+ ["off", `Turn ${subject} off`],
2670
+ ["toggle", `Switch ${subject}`],
2671
+ ] as const;
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
+
2947
+ /**
2948
+ * The `/prompt-autocomplete` grammar: the single source for dispatch, usage
2949
+ * text, and argument completion. Order is the order of the usage text.
2950
+ */
2951
+ export const PROMPT_AUTOCOMPLETE_COMMANDS = [
2952
+ commandSpec("on", "Enable inline suggestions and save the decision"),
2953
+ commandSpec("off", "Disable inline suggestions and save the decision"),
2954
+ commandSpec("toggle", "Switch inline suggestions on or off"),
2955
+ commandSpec("status", "Show configuration and request state", { readOnly: true }),
2956
+ commandSpec("stats", "Show session requests, cache hits, tokens, and cost", { readOnly: true }),
2957
+ commandSpec("inspect", "Preview locally what a request would send", { usage: "[draft]", readOnly: true }),
2958
+ commandSpec("min-chars", "Set and save the minimum draft length", {
2959
+ usage: "<n>",
2960
+ valuePlaceholder: `<${MIN_PROMPT_CHARS_MIN}-${MIN_PROMPT_CHARS_MAX}>`,
2961
+ bareComplete: true,
2962
+ }),
2963
+ commandSpec("budget", "Cap provider requests for this session", {
2964
+ usage: "<n|off>",
2965
+ choices: [["off", "Remove the session request ceiling"]],
2966
+ valuePlaceholder: `<${BUDGET_REQUESTS_MIN}-${BUDGET_REQUESTS_MAX}>`,
2967
+ bareComplete: true,
2968
+ }),
2969
+ {
2970
+ ...commandSpec("set", "Show runtime knobs", { usage: "<key> [value]", bareComplete: true }),
2971
+ completions: SET_COMPLETIONS,
2972
+ },
2973
+ commandSpec("keys", "Show the key for every action", { readOnly: true }),
2974
+ commandSpec("stream", "Toggle streamed response previews", {
2975
+ usage: "on|off|toggle",
2976
+ choices: ON_OFF_TOGGLE("streamed previews"),
2977
+ bareComplete: true,
2978
+ }),
2979
+ commandSpec("while-streaming", "Toggle suggestions while the agent works", {
2980
+ usage: "on|off|toggle",
2981
+ choices: ON_OFF_TOGGLE("suggestions while the agent works"),
2982
+ bareComplete: true,
2983
+ }),
2984
+ commandSpec("debug-on", "Show the debug status line"),
2985
+ commandSpec("debug-off", "Hide the debug status line"),
2986
+ commandSpec("debug-toggle", "Switch the debug status line"),
2987
+ ] as const;
2988
+
2989
+ export type PromptAutocompleteCommandName = (typeof PROMPT_AUTOCOMPLETE_COMMANDS)[number]["name"];
2990
+
2991
+ export function findPromptAutocompleteCommand(
2992
+ name: string,
2993
+ ): (typeof PROMPT_AUTOCOMPLETE_COMMANDS)[number] | undefined {
2994
+ return PROMPT_AUTOCOMPLETE_COMMANDS.find((spec) => spec.name === name);
2995
+ }
2996
+
2997
+ export function findPromptAutocompleteSetKey(
2998
+ key: string,
2999
+ ): (typeof PROMPT_AUTOCOMPLETE_SET_KEYS)[number] | undefined {
3000
+ return PROMPT_AUTOCOMPLETE_SET_KEYS.find((spec) => spec.key === key);
3001
+ }
3002
+
3003
+ export const PROMPT_AUTOCOMPLETE_USAGE = `Usage: /prompt-autocomplete [${PROMPT_AUTOCOMPLETE_COMMANDS.map((spec) =>
3004
+ spec.usage ? `${spec.name} ${spec.usage}` : spec.name
3005
+ ).join("|")}]`;
3006
+
3007
+ export const PROMPT_AUTOCOMPLETE_SET_USAGE = `Usage: /prompt-autocomplete set [${PROMPT_AUTOCOMPLETE_SET_KEYS.map((spec) =>
3008
+ `${spec.key} ${formatSetKeyPlaceholder(spec)}`
3009
+ ).join("|")}]`;
3010
+
3011
+ const ALL_COMMAND_COMPLETIONS: readonly PromptAutocompleteCommandCompletion[] = PROMPT_AUTOCOMPLETE_COMMANDS.flatMap(
3012
+ (spec) => spec.completions,
3013
+ );
3014
+
3015
+ /**
3016
+ * Argument texts that are complete submissions on their own. Typing one of
3017
+ * these exactly must not open the menu: while it is open, Enter applies a
3018
+ * completion instead of submitting, so `stats` would need Enter twice.
3019
+ */
3020
+ const COMPLETE_ARGUMENTS: ReadonlySet<string> = new Set([
3021
+ ...PROMPT_AUTOCOMPLETE_COMMANDS.filter((spec) => spec.bareComplete).map((spec) => spec.name),
3022
+ ...PROMPT_AUTOCOMPLETE_SET_KEYS.filter((spec) => "bareReports" in spec).map((spec) => `set ${spec.key}`),
3023
+ ...[...ALL_COMMAND_COMPLETIONS, ...SET_KEY_COMPLETIONS]
3024
+ .map((completion) => completion.value)
3025
+ .filter((value) => !value.endsWith(" ")),
3026
+ ]);
3027
+
3028
+ /**
3029
+ * Complete the argument span of `/prompt-autocomplete`.
3030
+ *
3031
+ * Purely local and synchronous: forms that strictly extend the typed text,
3032
+ * matched case-insensitively with whitespace collapsed, in grammar order.
3033
+ * Returns null when nothing matches or when the typed text is already a
3034
+ * complete submission, so Enter keeps submitting it.
3035
+ */
3036
+ export function completePromptAutocompleteArguments(
3037
+ argumentPrefix: string,
3038
+ ): PromptAutocompleteCommandCompletion[] | null {
3039
+ const typed = argumentPrefix.trimStart().replace(/\s+/g, " ").toLowerCase();
3040
+ if (COMPLETE_ARGUMENTS.has(typed)) return null;
3041
+ const matches = (typed.startsWith("set key ") ? SET_KEY_COMPLETIONS : ALL_COMMAND_COMPLETIONS)
3042
+ .filter((completion) => completion.value.length > typed.length && completion.value.startsWith(typed))
3043
+ .map((completion) => ({ ...completion }));
3044
+ return matches.length > 0 ? matches : null;
3045
+ }