@kliebhan/pi-prompt-autocomplete 0.2.5 → 0.3.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/CHANGELOG.md +22 -0
- package/README.md +51 -13
- package/core.ts +673 -11
- package/index.ts +1206 -236
- package/media/prompt-autocomplete-demo.mp4 +0 -0
- package/package.json +2 -2
package/core.ts
CHANGED
|
@@ -81,16 +81,31 @@ export const DEFAULT_PREFERRED_MODEL = "current active model";
|
|
|
81
81
|
export const DEFAULT_PROMPT_AUTOCOMPLETE_ENABLED = false;
|
|
82
82
|
export const DEFAULT_STREAM_RESPONSES = true;
|
|
83
83
|
export const DEFAULT_DEBOUNCE_MS = 350;
|
|
84
|
+
export const DEBOUNCE_MS_MIN = 0;
|
|
85
|
+
export const DEBOUNCE_MS_MAX = 5_000;
|
|
84
86
|
export const DEFAULT_MIN_PROMPT_CHARS = 1;
|
|
85
87
|
export const MIN_PROMPT_CHARS_MIN = 0;
|
|
86
88
|
export const MIN_PROMPT_CHARS_MAX = 500;
|
|
87
89
|
export const DEFAULT_MAX_SUGGESTION_CHARS = 160;
|
|
90
|
+
export const MAX_SUGGESTION_CHARS_MIN = 16;
|
|
91
|
+
export const MAX_SUGGESTION_CHARS_MAX = 1_000;
|
|
88
92
|
export const DEFAULT_MAX_ALTERNATIVES = 3;
|
|
93
|
+
export const MAX_ALTERNATIVES_MIN = 1;
|
|
94
|
+
export const MAX_ALTERNATIVES_MAX = 5;
|
|
95
|
+
/** Provider-request ceiling bounds; `off` (no ceiling) is the default. */
|
|
96
|
+
export const BUDGET_REQUESTS_MIN = 1;
|
|
97
|
+
export const BUDGET_REQUESTS_MAX = 100_000;
|
|
98
|
+
export const DEFAULT_BUDGET_REQUESTS_FLAG = "off";
|
|
99
|
+
/** Custom-entry customType carrying versioned budget snapshots. */
|
|
100
|
+
export const PROMPT_AUTOCOMPLETE_BUDGET_ENTRY_TYPE = "prompt-autocomplete-stats";
|
|
101
|
+
export const PROMPT_AUTOCOMPLETE_BUDGET_SCHEMA_VERSION = 1;
|
|
89
102
|
export const MAX_DRAFT_CONTEXT_CHARS = 2_000;
|
|
90
103
|
export const MAX_CONTEXT_MESSAGES = 6;
|
|
91
104
|
export const MAX_CONTEXT_MESSAGE_CHARS = 600;
|
|
92
105
|
export const MAX_LATEST_ASSISTANT_MESSAGE_CHARS = 3_000;
|
|
93
106
|
export const MAX_LATEST_USER_MESSAGE_CHARS = 1_200;
|
|
107
|
+
/** Bound for the latest compaction summary; the middle is elided so goal and next steps survive. */
|
|
108
|
+
export const MAX_COMPACTION_SUMMARY_CHARS = 1_500;
|
|
94
109
|
// Scale the completion budget with the requested alternatives so a JSON array of
|
|
95
110
|
// several short suggestions cannot be truncated mid-string (which would break parsing).
|
|
96
111
|
export const MIN_REQUEST_MAX_TOKENS = 192;
|
|
@@ -102,7 +117,7 @@ export interface ModelRef {
|
|
|
102
117
|
}
|
|
103
118
|
|
|
104
119
|
export interface PromptAutocompleteCacheIdentity {
|
|
105
|
-
|
|
120
|
+
conversationId: string;
|
|
106
121
|
modelLabel: string;
|
|
107
122
|
maxAlternatives: number;
|
|
108
123
|
maxSuggestionChars: number;
|
|
@@ -110,6 +125,38 @@ export interface PromptAutocompleteCacheIdentity {
|
|
|
110
125
|
latestAssistantContext: string;
|
|
111
126
|
latestUserContext: string;
|
|
112
127
|
recentContext: string;
|
|
128
|
+
compactionSummaryContext: string;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Session entries that advance the raw leaf without changing autocomplete context. */
|
|
132
|
+
const AUTOCOMPLETE_METADATA_ENTRY_TYPES = new Set(["custom", "label", "session_info"]);
|
|
133
|
+
|
|
134
|
+
export function isAutocompleteMetadataEntry(entry: unknown): boolean {
|
|
135
|
+
return isRecord(entry)
|
|
136
|
+
&& typeof entry.type === "string"
|
|
137
|
+
&& AUTOCOMPLETE_METADATA_ENTRY_TYPES.has(entry.type);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Newest branch entry that affects transmitted autocomplete context.
|
|
142
|
+
*
|
|
143
|
+
* Custom, label, and session-info entries are skipped because they are excluded
|
|
144
|
+
* from model context. Entries without an id are skipped so a host that omits
|
|
145
|
+
* ids can still fall back to the raw leaf. `custom_message` is kept: it is
|
|
146
|
+
* included in LLM context even though today's context builders only read
|
|
147
|
+
* `type === "message"`.
|
|
148
|
+
*/
|
|
149
|
+
export function resolveAutocompleteConversationId(
|
|
150
|
+
branch: unknown[],
|
|
151
|
+
fallbackId = "",
|
|
152
|
+
): string {
|
|
153
|
+
for (let index = branch.length - 1; index >= 0; index -= 1) {
|
|
154
|
+
const entry = branch[index];
|
|
155
|
+
if (isAutocompleteMetadataEntry(entry)) continue;
|
|
156
|
+
if (!isRecord(entry) || typeof entry.id !== "string" || entry.id.length === 0) continue;
|
|
157
|
+
return entry.id;
|
|
158
|
+
}
|
|
159
|
+
return fallbackId;
|
|
113
160
|
}
|
|
114
161
|
|
|
115
162
|
export type PromptAutocompletePrefixContextIdentity = Omit<PromptAutocompleteCacheIdentity, "draft">;
|
|
@@ -611,6 +658,12 @@ export interface PromptAutocompleteRuntimeOverrides {
|
|
|
611
658
|
streamResponses?: boolean;
|
|
612
659
|
debug?: boolean;
|
|
613
660
|
minPromptChars?: number;
|
|
661
|
+
debounceMs?: number;
|
|
662
|
+
maxSuggestionChars?: number;
|
|
663
|
+
maxAlternatives?: number;
|
|
664
|
+
modelSelection?: PromptAutocompleteModelSelection;
|
|
665
|
+
/** Session request ceiling; `"off"` is an explicit decision, not unset. */
|
|
666
|
+
budgetLimit?: PromptAutocompleteBudgetSetting;
|
|
614
667
|
}
|
|
615
668
|
|
|
616
669
|
export type PromptAutocompleteSettingSource = "flag" | "saved" | "session";
|
|
@@ -626,13 +679,19 @@ export function describeSettingSource(override: unknown): PromptAutocompleteSett
|
|
|
626
679
|
/**
|
|
627
680
|
* Settings persisted across processes.
|
|
628
681
|
*
|
|
629
|
-
*
|
|
630
|
-
* field defers to the CLI flag, so an empty or missing file
|
|
631
|
-
* like no persisted decision.
|
|
682
|
+
* Explicit `/prompt-autocomplete on|off`, `min-chars`, and `set` decisions are
|
|
683
|
+
* stored. An absent field defers to the CLI flag, so an empty or missing file
|
|
684
|
+
* behaves exactly like no persisted decision. The file stores nothing but these
|
|
685
|
+
* decisions: no conversation, cache, or stats.
|
|
632
686
|
*/
|
|
633
687
|
export interface PromptAutocompletePersistedSettings {
|
|
634
688
|
enabled?: boolean;
|
|
635
689
|
minPromptChars?: number;
|
|
690
|
+
debounceMs?: number;
|
|
691
|
+
maxSuggestionChars?: number;
|
|
692
|
+
maxAlternatives?: number;
|
|
693
|
+
/** Raw dedicated model, or `active` for the session model. Invalid values are dropped on load. */
|
|
694
|
+
model?: string;
|
|
636
695
|
}
|
|
637
696
|
|
|
638
697
|
/**
|
|
@@ -656,13 +715,27 @@ export function parsePromptAutocompletePersistedSettings(
|
|
|
656
715
|
const record = parsed as Record<string, unknown>;
|
|
657
716
|
const settings: PromptAutocompletePersistedSettings = {};
|
|
658
717
|
if (typeof record.enabled === "boolean") settings.enabled = record.enabled;
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
718
|
+
const minPromptChars = readPersistedBoundedInt(record, "minPromptChars", MIN_PROMPT_CHARS_MIN, MIN_PROMPT_CHARS_MAX);
|
|
719
|
+
if (minPromptChars !== undefined) settings.minPromptChars = minPromptChars;
|
|
720
|
+
const debounceMs = readPersistedBoundedInt(record, "debounceMs", DEBOUNCE_MS_MIN, DEBOUNCE_MS_MAX);
|
|
721
|
+
if (debounceMs !== undefined) settings.debounceMs = debounceMs;
|
|
722
|
+
const maxSuggestionChars = readPersistedBoundedInt(
|
|
723
|
+
record,
|
|
724
|
+
"maxSuggestionChars",
|
|
725
|
+
MAX_SUGGESTION_CHARS_MIN,
|
|
726
|
+
MAX_SUGGESTION_CHARS_MAX,
|
|
727
|
+
);
|
|
728
|
+
if (maxSuggestionChars !== undefined) settings.maxSuggestionChars = maxSuggestionChars;
|
|
729
|
+
const maxAlternatives = readPersistedBoundedInt(
|
|
730
|
+
record,
|
|
731
|
+
"maxAlternatives",
|
|
732
|
+
MAX_ALTERNATIVES_MIN,
|
|
733
|
+
MAX_ALTERNATIVES_MAX,
|
|
734
|
+
);
|
|
735
|
+
if (maxAlternatives !== undefined) settings.maxAlternatives = maxAlternatives;
|
|
736
|
+
if (typeof record.model === "string") {
|
|
737
|
+
const model = parsePersistedModelRaw(record.model);
|
|
738
|
+
if (model !== undefined) settings.model = persistableModelRaw(model);
|
|
666
739
|
}
|
|
667
740
|
return settings;
|
|
668
741
|
}
|
|
@@ -680,9 +753,46 @@ export function serializePromptAutocompletePersistedSettings(
|
|
|
680
753
|
) {
|
|
681
754
|
payload.minPromptChars = settings.minPromptChars;
|
|
682
755
|
}
|
|
756
|
+
if (
|
|
757
|
+
typeof settings.debounceMs === "number"
|
|
758
|
+
&& Number.isInteger(settings.debounceMs)
|
|
759
|
+
&& settings.debounceMs >= DEBOUNCE_MS_MIN
|
|
760
|
+
&& settings.debounceMs <= DEBOUNCE_MS_MAX
|
|
761
|
+
) {
|
|
762
|
+
payload.debounceMs = settings.debounceMs;
|
|
763
|
+
}
|
|
764
|
+
if (
|
|
765
|
+
typeof settings.maxSuggestionChars === "number"
|
|
766
|
+
&& Number.isInteger(settings.maxSuggestionChars)
|
|
767
|
+
&& settings.maxSuggestionChars >= MAX_SUGGESTION_CHARS_MIN
|
|
768
|
+
&& settings.maxSuggestionChars <= MAX_SUGGESTION_CHARS_MAX
|
|
769
|
+
) {
|
|
770
|
+
payload.maxSuggestionChars = settings.maxSuggestionChars;
|
|
771
|
+
}
|
|
772
|
+
if (
|
|
773
|
+
typeof settings.maxAlternatives === "number"
|
|
774
|
+
&& Number.isInteger(settings.maxAlternatives)
|
|
775
|
+
&& settings.maxAlternatives >= MAX_ALTERNATIVES_MIN
|
|
776
|
+
&& settings.maxAlternatives <= MAX_ALTERNATIVES_MAX
|
|
777
|
+
) {
|
|
778
|
+
payload.maxAlternatives = settings.maxAlternatives;
|
|
779
|
+
}
|
|
780
|
+
const model = parsePersistedModelRaw(settings.model);
|
|
781
|
+
if (model !== undefined) payload.model = persistableModelRaw(model);
|
|
683
782
|
return `${JSON.stringify(payload, null, 2)}\n`;
|
|
684
783
|
}
|
|
685
784
|
|
|
785
|
+
function readPersistedBoundedInt(
|
|
786
|
+
record: Record<string, unknown>,
|
|
787
|
+
key: string,
|
|
788
|
+
min: number,
|
|
789
|
+
max: number,
|
|
790
|
+
): number | undefined {
|
|
791
|
+
const value = record[key];
|
|
792
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) return undefined;
|
|
793
|
+
return value;
|
|
794
|
+
}
|
|
795
|
+
|
|
686
796
|
/**
|
|
687
797
|
* Resolve the effective enabled state and its attribution.
|
|
688
798
|
*
|
|
@@ -741,6 +851,222 @@ export function parseExplicitBoundedIntFlag(
|
|
|
741
851
|
return bounded === defaultValue ? undefined : bounded;
|
|
742
852
|
}
|
|
743
853
|
|
|
854
|
+
/**
|
|
855
|
+
* Parse a slash-command integer. Out-of-range and malformed values are rejected
|
|
856
|
+
* rather than clamped, so the user sees the valid range instead of a silent
|
|
857
|
+
* substitution.
|
|
858
|
+
*/
|
|
859
|
+
export function parseStrictBoundedInt(
|
|
860
|
+
value: string | undefined,
|
|
861
|
+
min: number,
|
|
862
|
+
max: number,
|
|
863
|
+
): number | undefined {
|
|
864
|
+
if (value === undefined) return undefined;
|
|
865
|
+
const trimmed = value.trim();
|
|
866
|
+
if (!trimmed) return undefined;
|
|
867
|
+
const parsed = Number.parseInt(trimmed, 10);
|
|
868
|
+
if (!Number.isFinite(parsed) || String(parsed) !== trimmed) return undefined;
|
|
869
|
+
if (parsed < min || parsed > max) return undefined;
|
|
870
|
+
return parsed;
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
/**
|
|
874
|
+
* An explicit `--prompt-autocomplete-model` value, or undefined when the flag
|
|
875
|
+
* still holds its registered default. `active` is an explicit sentinel and is
|
|
876
|
+
* not treated as unset.
|
|
877
|
+
*/
|
|
878
|
+
export function parseExplicitModelFlag(
|
|
879
|
+
value: boolean | string | undefined,
|
|
880
|
+
): PromptAutocompleteModelSelection | undefined {
|
|
881
|
+
if (typeof value !== "string") return undefined;
|
|
882
|
+
const trimmed = value.trim();
|
|
883
|
+
if (!trimmed || trimmed.toLowerCase() === DEFAULT_PREFERRED_MODEL) return undefined;
|
|
884
|
+
return parsePromptAutocompleteModelSelection(trimmed);
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
export function persistableModelRaw(selection: PromptAutocompleteModelSelection): string | undefined {
|
|
888
|
+
if (selection.kind === "active") return "active";
|
|
889
|
+
if (selection.kind === "dedicated") return selection.raw;
|
|
890
|
+
return undefined;
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
export function parsePersistedModelRaw(value: string | undefined): PromptAutocompleteModelSelection | undefined {
|
|
894
|
+
if (typeof value !== "string") return undefined;
|
|
895
|
+
const trimmed = value.trim();
|
|
896
|
+
// An empty field is "no decision", not an explicit request for the session model.
|
|
897
|
+
if (!trimmed) return undefined;
|
|
898
|
+
const selection = parsePromptAutocompleteModelSelection(trimmed);
|
|
899
|
+
return selection.kind === "invalid" ? undefined : selection;
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
export function resolvePersistedModelSelection(
|
|
903
|
+
override: PromptAutocompleteModelSelection | undefined,
|
|
904
|
+
explicitFlag: PromptAutocompleteModelSelection | undefined,
|
|
905
|
+
saved: PromptAutocompleteModelSelection | undefined,
|
|
906
|
+
): { selection: PromptAutocompleteModelSelection; source: PromptAutocompleteSettingSource } {
|
|
907
|
+
if (override !== undefined) return { selection: override, source: "session" };
|
|
908
|
+
if (explicitFlag !== undefined) return { selection: explicitFlag, source: "flag" };
|
|
909
|
+
if (saved !== undefined) return { selection: saved, source: "saved" };
|
|
910
|
+
return { selection: { kind: "active" }, source: "flag" };
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/**
|
|
914
|
+
* Session-scoped provider-request ceiling.
|
|
915
|
+
*
|
|
916
|
+
* The limit is the effective ceiling (`undefined` means off) and `used` counts
|
|
917
|
+
* every provider invocation reserved in the current physical session,
|
|
918
|
+
* including failed and aborted ones, and including invocations made while the
|
|
919
|
+
* ceiling was off. Cache hits and in-flight joins never reserve.
|
|
920
|
+
*/
|
|
921
|
+
export interface PromptAutocompleteBudgetState {
|
|
922
|
+
limit?: number;
|
|
923
|
+
used: number;
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
export type PromptAutocompleteBudgetSetting = number | "off";
|
|
927
|
+
|
|
928
|
+
/** A restored snapshot always carries a real decision, including an explicit `off`. */
|
|
929
|
+
export interface PromptAutocompleteBudgetSnapshotState {
|
|
930
|
+
limit: PromptAutocompleteBudgetSetting;
|
|
931
|
+
used: number;
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
/**
|
|
935
|
+
* Parse the `--prompt-autocomplete-max-requests` flag. Flags clamp: invalid
|
|
936
|
+
* input and the registered default (`off`) fall back to "no explicit flag",
|
|
937
|
+
* which defers to the session-restored value.
|
|
938
|
+
*/
|
|
939
|
+
export function parsePromptAutocompleteBudgetFlag(
|
|
940
|
+
value: boolean | string | undefined,
|
|
941
|
+
): number | undefined {
|
|
942
|
+
if (typeof value !== "string") return undefined;
|
|
943
|
+
const trimmed = value.trim();
|
|
944
|
+
if (!trimmed || trimmed.toLowerCase() === DEFAULT_BUDGET_REQUESTS_FLAG) return undefined;
|
|
945
|
+
const parsed = Number.parseInt(trimmed, 10);
|
|
946
|
+
if (!Number.isFinite(parsed) || String(parsed) !== trimmed) return undefined;
|
|
947
|
+
return Math.min(BUDGET_REQUESTS_MAX, Math.max(BUDGET_REQUESTS_MIN, parsed));
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
/** Result of parsing an interactive `budget` argument. */
|
|
951
|
+
export type ParsedPromptAutocompleteBudgetValue =
|
|
952
|
+
| { kind: "limit"; value: number }
|
|
953
|
+
| { kind: "off" }
|
|
954
|
+
| { kind: "unset" }
|
|
955
|
+
| { kind: "invalid" };
|
|
956
|
+
|
|
957
|
+
/**
|
|
958
|
+
* Parse `/prompt-autocomplete budget <n|off>`. Interactive values are rejected
|
|
959
|
+
* rather than clamped so the user sees the valid range.
|
|
960
|
+
*/
|
|
961
|
+
export function parsePromptAutocompleteBudgetValue(value: string | undefined): ParsedPromptAutocompleteBudgetValue {
|
|
962
|
+
if (value === undefined || !value.trim()) return { kind: "unset" };
|
|
963
|
+
const trimmed = value.trim();
|
|
964
|
+
if (trimmed.toLowerCase() === DEFAULT_BUDGET_REQUESTS_FLAG) return { kind: "off" };
|
|
965
|
+
if (!/^\d+$/.test(trimmed)) return { kind: "invalid" };
|
|
966
|
+
const parsed = Number.parseInt(trimmed, 10);
|
|
967
|
+
if (parsed < BUDGET_REQUESTS_MIN || parsed > BUDGET_REQUESTS_MAX) return { kind: "invalid" };
|
|
968
|
+
return { kind: "limit", value: parsed };
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
/** Durable snapshot of the session budget, appended as a non-LLM custom entry. */
|
|
972
|
+
export interface PromptAutocompleteBudgetSnapshot {
|
|
973
|
+
schemaVersion: number;
|
|
974
|
+
physicalSessionId: string;
|
|
975
|
+
limit: PromptAutocompleteBudgetSetting;
|
|
976
|
+
used: number;
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
export function buildPromptAutocompleteBudgetSnapshot(
|
|
980
|
+
limit: PromptAutocompleteBudgetSetting,
|
|
981
|
+
used: number,
|
|
982
|
+
physicalSessionId: string,
|
|
983
|
+
): PromptAutocompleteBudgetSnapshot {
|
|
984
|
+
return {
|
|
985
|
+
schemaVersion: PROMPT_AUTOCOMPLETE_BUDGET_SCHEMA_VERSION,
|
|
986
|
+
physicalSessionId,
|
|
987
|
+
limit,
|
|
988
|
+
used,
|
|
989
|
+
};
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
/**
|
|
993
|
+
* Parse a persisted snapshot. Unknown schema versions, foreign physical
|
|
994
|
+
* sessions, and malformed fields degrade to `undefined` (fresh budget).
|
|
995
|
+
*/
|
|
996
|
+
export function parsePromptAutocompleteBudgetSnapshot(
|
|
997
|
+
data: unknown,
|
|
998
|
+
physicalSessionId: string,
|
|
999
|
+
): PromptAutocompleteBudgetSnapshotState | undefined {
|
|
1000
|
+
if (!isRecord(data)) return undefined;
|
|
1001
|
+
if (data.schemaVersion !== PROMPT_AUTOCOMPLETE_BUDGET_SCHEMA_VERSION) return undefined;
|
|
1002
|
+
if (data.physicalSessionId !== physicalSessionId) return undefined;
|
|
1003
|
+
const limit: PromptAutocompleteBudgetSetting | undefined = data.limit === "off"
|
|
1004
|
+
? "off"
|
|
1005
|
+
: typeof data.limit === "number" && Number.isInteger(data.limit)
|
|
1006
|
+
&& data.limit >= BUDGET_REQUESTS_MIN && data.limit <= BUDGET_REQUESTS_MAX
|
|
1007
|
+
? data.limit
|
|
1008
|
+
: undefined;
|
|
1009
|
+
if (limit === undefined) return undefined;
|
|
1010
|
+
if (typeof data.used !== "number" || !Number.isInteger(data.used) || data.used < 0) return undefined;
|
|
1011
|
+
return { limit, used: data.used };
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
/**
|
|
1015
|
+
* Restore this physical session's budget from its own entries.
|
|
1016
|
+
*
|
|
1017
|
+
* Scans every entry of the session, not just the current leaf path: a request
|
|
1018
|
+
* paid for on a branch the user later left was still paid for, so switching
|
|
1019
|
+
* branches must not hand out a fresh allowance. Usage is therefore restored
|
|
1020
|
+
* monotonically (the highest observed count), while the ceiling is the last
|
|
1021
|
+
* recorded decision.
|
|
1022
|
+
*/
|
|
1023
|
+
export function findPromptAutocompleteBudgetSnapshot(
|
|
1024
|
+
entries: unknown[],
|
|
1025
|
+
physicalSessionId: string,
|
|
1026
|
+
): PromptAutocompleteBudgetSnapshotState | undefined {
|
|
1027
|
+
let restored: PromptAutocompleteBudgetSnapshotState | undefined;
|
|
1028
|
+
for (const entry of entries) {
|
|
1029
|
+
if (!isRecord(entry) || entry.type !== "custom") continue;
|
|
1030
|
+
if (entry.customType !== PROMPT_AUTOCOMPLETE_BUDGET_ENTRY_TYPE) continue;
|
|
1031
|
+
const snapshot = parsePromptAutocompleteBudgetSnapshot(entry.data, physicalSessionId);
|
|
1032
|
+
if (!snapshot) continue;
|
|
1033
|
+
restored = {
|
|
1034
|
+
limit: snapshot.limit,
|
|
1035
|
+
used: Math.max(restored?.used ?? 0, snapshot.used),
|
|
1036
|
+
};
|
|
1037
|
+
}
|
|
1038
|
+
return restored;
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
/**
|
|
1042
|
+
* Thrown by a request producer that cannot reserve budget. This is not a
|
|
1043
|
+
* provider failure: it must not enter the failure cooldown or failure stats.
|
|
1044
|
+
*/
|
|
1045
|
+
export class PromptAutocompleteBudgetExhaustedError extends Error {
|
|
1046
|
+
constructor(limit: number, used: number) {
|
|
1047
|
+
super(`Session request budget exhausted (${used}/${limit} provider requests used)`);
|
|
1048
|
+
this.name = "PromptAutocompleteBudgetExhaustedError";
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
/**
|
|
1053
|
+
* Resolve the effective request ceiling and its attribution. An explicit
|
|
1054
|
+
* `budget off` override outranks flag and saved values; the registered flag
|
|
1055
|
+
* default is indistinguishable from not passing the flag.
|
|
1056
|
+
*/
|
|
1057
|
+
export function resolvePromptAutocompleteBudgetLimit(
|
|
1058
|
+
override: PromptAutocompleteBudgetSetting | undefined,
|
|
1059
|
+
explicitFlag: number | undefined,
|
|
1060
|
+
saved: PromptAutocompleteBudgetSetting | undefined,
|
|
1061
|
+
): { limit?: number; source: PromptAutocompleteSettingSource } {
|
|
1062
|
+
if (override !== undefined) {
|
|
1063
|
+
return { limit: override === "off" ? undefined : override, source: "session" };
|
|
1064
|
+
}
|
|
1065
|
+
if (explicitFlag !== undefined) return { limit: explicitFlag, source: "flag" };
|
|
1066
|
+
if (saved !== undefined) return { limit: saved === "off" ? undefined : saved, source: "saved" };
|
|
1067
|
+
return { limit: undefined, source: "flag" };
|
|
1068
|
+
}
|
|
1069
|
+
|
|
744
1070
|
interface SuggestionPayload {
|
|
745
1071
|
completions?: unknown;
|
|
746
1072
|
suggestions?: unknown;
|
|
@@ -1740,11 +2066,156 @@ export function buildLatestUserMessageContext(
|
|
|
1740
2066
|
return buildLatestRoleMessageContext(branch, "user", maxChars);
|
|
1741
2067
|
}
|
|
1742
2068
|
|
|
2069
|
+
/**
|
|
2070
|
+
* Model-visible conversation entries, in the shape the context builders read.
|
|
2071
|
+
*
|
|
2072
|
+
* Pi 1.x builds model context from a session projection that applies
|
|
2073
|
+
* `context_edit` entries and compaction: an edit can omit an earlier message or
|
|
2074
|
+
* replace its content, for example to redact it. Autocomplete must not send
|
|
2075
|
+
* what the model itself no longer sees, so its context comes from that
|
|
2076
|
+
* projection. Message entries contribute their messages, as with the raw
|
|
2077
|
+
* branch. A compaction contributes only its summary text, as a
|
|
2078
|
+
* `compaction_summary` entry, because the projection replaced the summarized
|
|
2079
|
+
* messages with it; the compaction's system checkpoint is never taken. A
|
|
2080
|
+
* malformed projection yields no conversation context rather than raw entries.
|
|
2081
|
+
*/
|
|
2082
|
+
export function projectAutocompleteContextEntries(projection: unknown): unknown[] {
|
|
2083
|
+
if (!isRecord(projection) || !Array.isArray(projection.entries)) return [];
|
|
2084
|
+
const entries: unknown[] = [];
|
|
2085
|
+
for (const projected of projection.entries) {
|
|
2086
|
+
if (!isRecord(projected) || !isRecord(projected.sourceEntry) || !Array.isArray(projected.messages)) continue;
|
|
2087
|
+
const source = projected.sourceEntry;
|
|
2088
|
+
if (source.type === "compaction") {
|
|
2089
|
+
for (const message of projected.messages) {
|
|
2090
|
+
if (isRecord(message) && message.role === "compactionSummary" && typeof message.summary === "string") {
|
|
2091
|
+
entries.push({ type: "compaction_summary", id: source.id, summary: message.summary });
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
continue;
|
|
2095
|
+
}
|
|
2096
|
+
if (source.type !== "message") continue;
|
|
2097
|
+
for (const message of projected.messages) {
|
|
2098
|
+
entries.push({ type: "message", id: source.id, message });
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
return entries;
|
|
2102
|
+
}
|
|
2103
|
+
|
|
2104
|
+
/**
|
|
2105
|
+
* The newest compaction summary among projected context entries, bounded with
|
|
2106
|
+
* the middle elided. Raw branches never carry `compaction_summary` entries, so
|
|
2107
|
+
* hosts without a projection send no summary: they still see the summarized
|
|
2108
|
+
* messages themselves.
|
|
2109
|
+
*/
|
|
2110
|
+
export function buildCompactionSummaryContext(
|
|
2111
|
+
entries: unknown[],
|
|
2112
|
+
maxChars = MAX_COMPACTION_SUMMARY_CHARS,
|
|
2113
|
+
): string {
|
|
2114
|
+
for (let index = entries.length - 1; index >= 0; index -= 1) {
|
|
2115
|
+
const entry = entries[index];
|
|
2116
|
+
if (!isRecord(entry) || entry.type !== "compaction_summary" || typeof entry.summary !== "string") continue;
|
|
2117
|
+
const summary = entry.summary.trim();
|
|
2118
|
+
if (summary) return truncateMiddle(summary, maxChars);
|
|
2119
|
+
}
|
|
2120
|
+
return "";
|
|
2121
|
+
}
|
|
2122
|
+
|
|
1743
2123
|
export function truncateDraftTail(draft: string, maxChars = MAX_DRAFT_CONTEXT_CHARS): string {
|
|
1744
2124
|
if (draft.length <= maxChars) return draft;
|
|
1745
2125
|
return draft.slice(-maxChars);
|
|
1746
2126
|
}
|
|
1747
2127
|
|
|
2128
|
+
/**
|
|
2129
|
+
* Everything one autocomplete request transmits, derived from the draft and
|
|
2130
|
+
* the conversation branch.
|
|
2131
|
+
*
|
|
2132
|
+
* The provider request and `/prompt-autocomplete inspect` consume the same
|
|
2133
|
+
* snapshot and render it with the same function, so the local preview cannot
|
|
2134
|
+
* drift from what is sent. Credentials and headers are never part of it.
|
|
2135
|
+
*/
|
|
2136
|
+
export interface PromptAutocompleteRequestSnapshot {
|
|
2137
|
+
draft: string;
|
|
2138
|
+
/** The transmitted part of the draft: its last MAX_DRAFT_CONTEXT_CHARS characters. */
|
|
2139
|
+
draftTail: string;
|
|
2140
|
+
latestAssistantContext: string;
|
|
2141
|
+
latestUserContext: string;
|
|
2142
|
+
recentContext: string;
|
|
2143
|
+
/** Newest compaction summary the model sees; empty without one or without a host projection. */
|
|
2144
|
+
compactionSummaryContext: string;
|
|
2145
|
+
maxAlternatives: number;
|
|
2146
|
+
maxSuggestionChars: number;
|
|
2147
|
+
}
|
|
2148
|
+
|
|
2149
|
+
export function buildPromptAutocompleteRequestSnapshot(input: {
|
|
2150
|
+
draft: string;
|
|
2151
|
+
branch: unknown[];
|
|
2152
|
+
maxAlternatives: number;
|
|
2153
|
+
maxSuggestionChars: number;
|
|
2154
|
+
}): PromptAutocompleteRequestSnapshot {
|
|
2155
|
+
return {
|
|
2156
|
+
draft: input.draft,
|
|
2157
|
+
draftTail: truncateDraftTail(input.draft, MAX_DRAFT_CONTEXT_CHARS),
|
|
2158
|
+
latestAssistantContext: buildLatestAssistantMessageContext(input.branch),
|
|
2159
|
+
latestUserContext: buildLatestUserMessageContext(input.branch),
|
|
2160
|
+
recentContext: buildRecentConversationContext(input.branch),
|
|
2161
|
+
compactionSummaryContext: buildCompactionSummaryContext(input.branch),
|
|
2162
|
+
maxAlternatives: input.maxAlternatives,
|
|
2163
|
+
maxSuggestionChars: input.maxSuggestionChars,
|
|
2164
|
+
};
|
|
2165
|
+
}
|
|
2166
|
+
|
|
2167
|
+
/**
|
|
2168
|
+
* Render the single user message a request sends.
|
|
2169
|
+
*
|
|
2170
|
+
* Kept separate from the snapshot so the keystroke path only gathers context;
|
|
2171
|
+
* the message text is produced when a provider request is actually created,
|
|
2172
|
+
* or when inspection asks for it.
|
|
2173
|
+
*/
|
|
2174
|
+
export function renderPromptAutocompleteUserText(snapshot: PromptAutocompleteRequestSnapshot): string {
|
|
2175
|
+
const sections: string[] = [];
|
|
2176
|
+
if (snapshot.latestAssistantContext) {
|
|
2177
|
+
sections.push(`Latest assistant message (primary context):\n${snapshot.latestAssistantContext}`);
|
|
2178
|
+
}
|
|
2179
|
+
if (snapshot.latestUserContext) {
|
|
2180
|
+
sections.push(`Latest user message:\n${snapshot.latestUserContext}`);
|
|
2181
|
+
}
|
|
2182
|
+
if (snapshot.recentContext) {
|
|
2183
|
+
sections.push(`Recent conversation summary:\n${snapshot.recentContext}`);
|
|
2184
|
+
}
|
|
2185
|
+
if (snapshot.compactionSummaryContext) {
|
|
2186
|
+
sections.push(`Earlier conversation summary (compacted background):\n${snapshot.compactionSummaryContext}`);
|
|
2187
|
+
}
|
|
2188
|
+
|
|
2189
|
+
if (snapshot.draft.length === 0) {
|
|
2190
|
+
sections.push("Current draft is empty.");
|
|
2191
|
+
sections.push(
|
|
2192
|
+
[
|
|
2193
|
+
`Task: propose up to ${snapshot.maxAlternatives} ranked full next prompts the user could send now.`,
|
|
2194
|
+
"Each item must be a complete next prompt, not a continuation fragment.",
|
|
2195
|
+
"Suggest the prompt most likely to move the overall project forward.",
|
|
2196
|
+
"Prefer 3-10 words when possible.",
|
|
2197
|
+
].join("\n"),
|
|
2198
|
+
);
|
|
2199
|
+
} else {
|
|
2200
|
+
if (snapshot.draftTail.length < snapshot.draft.length) {
|
|
2201
|
+
sections.push(
|
|
2202
|
+
`Current draft tail (the real draft is longer; the cursor is at the end of the full draft):\n${snapshot.draftTail}`,
|
|
2203
|
+
);
|
|
2204
|
+
} else {
|
|
2205
|
+
sections.push(`Current draft (cursor at end):\n${snapshot.draft}`);
|
|
2206
|
+
}
|
|
2207
|
+
|
|
2208
|
+
sections.push(
|
|
2209
|
+
[
|
|
2210
|
+
`Task: propose up to ${snapshot.maxAlternatives} ranked continuations to insert at the cursor.`,
|
|
2211
|
+
"Each item must be only the text after the cursor; never restate text the user already typed.",
|
|
2212
|
+
"If the draft ends inside a partially typed word, complete that word directly without a leading space.",
|
|
2213
|
+
].join("\n"),
|
|
2214
|
+
);
|
|
2215
|
+
}
|
|
2216
|
+
return sections.join("\n\n");
|
|
2217
|
+
}
|
|
2218
|
+
|
|
1748
2219
|
export function shouldSkipPromptAutocomplete(text: string): boolean {
|
|
1749
2220
|
const trimmedStart = text.trimStart();
|
|
1750
2221
|
if (trimmedStart.startsWith("/") || trimmedStart.startsWith("!")) return true;
|
|
@@ -1953,3 +2424,194 @@ export function hostSupportsStreamedResponses(api: {
|
|
|
1953
2424
|
if (typeof api.streamSimple === "function") return true;
|
|
1954
2425
|
return typeof api.completeSimple !== "function";
|
|
1955
2426
|
}
|
|
2427
|
+
|
|
2428
|
+
/** One argument completion, in the shape Pi's slash-command autocomplete expects. */
|
|
2429
|
+
export interface PromptAutocompleteCommandCompletion {
|
|
2430
|
+
/**
|
|
2431
|
+
* The full argument text after `/prompt-autocomplete `. Pi replaces the whole
|
|
2432
|
+
* argument span with it, so nested forms carry every token. A trailing space
|
|
2433
|
+
* leaves the cursor where the user types a value.
|
|
2434
|
+
*/
|
|
2435
|
+
value: string;
|
|
2436
|
+
label: string;
|
|
2437
|
+
description: string;
|
|
2438
|
+
}
|
|
2439
|
+
|
|
2440
|
+
interface PromptAutocompleteCommandSpec<Name extends string> {
|
|
2441
|
+
name: Name;
|
|
2442
|
+
/** Placeholder after the name in the usage text, if the command takes an argument. */
|
|
2443
|
+
usage?: string;
|
|
2444
|
+
/** Reports state only, so it may run on hosts without an interactive editor. */
|
|
2445
|
+
readOnly: boolean;
|
|
2446
|
+
/** The name alone is a complete submission: it reports, toggles, or previews. */
|
|
2447
|
+
bareComplete: boolean;
|
|
2448
|
+
completions: readonly PromptAutocompleteCommandCompletion[];
|
|
2449
|
+
}
|
|
2450
|
+
|
|
2451
|
+
function commandSpec<Name extends string>(
|
|
2452
|
+
name: Name,
|
|
2453
|
+
description: string,
|
|
2454
|
+
options: {
|
|
2455
|
+
usage?: string;
|
|
2456
|
+
readOnly?: boolean;
|
|
2457
|
+
/** Fixed argument choices, each offered as a complete form. */
|
|
2458
|
+
choices?: readonly (readonly [choice: string, description: string])[];
|
|
2459
|
+
/** A free value: offered as the name and a space, labeled with this placeholder. */
|
|
2460
|
+
valuePlaceholder?: string;
|
|
2461
|
+
/** Arguments are optional; without choices or a value the name alone is the only form. */
|
|
2462
|
+
bareComplete?: boolean;
|
|
2463
|
+
} = {},
|
|
2464
|
+
): PromptAutocompleteCommandSpec<Name> {
|
|
2465
|
+
const completions: PromptAutocompleteCommandCompletion[] = [];
|
|
2466
|
+
const takesArgument = !!options.choices || !!options.valuePlaceholder;
|
|
2467
|
+
if (!takesArgument) completions.push({ value: name, label: name, description });
|
|
2468
|
+
for (const [choice, choiceDescription] of options.choices ?? []) {
|
|
2469
|
+
completions.push({ value: `${name} ${choice}`, label: `${name} ${choice}`, description: choiceDescription });
|
|
2470
|
+
}
|
|
2471
|
+
if (options.valuePlaceholder) {
|
|
2472
|
+
completions.push({ value: `${name} `, label: `${name} ${options.valuePlaceholder}`, description });
|
|
2473
|
+
}
|
|
2474
|
+
return {
|
|
2475
|
+
name,
|
|
2476
|
+
usage: options.usage,
|
|
2477
|
+
readOnly: options.readOnly ?? false,
|
|
2478
|
+
bareComplete: !takesArgument || (options.bareComplete ?? false),
|
|
2479
|
+
completions,
|
|
2480
|
+
};
|
|
2481
|
+
}
|
|
2482
|
+
|
|
2483
|
+
/**
|
|
2484
|
+
* Keys accepted by `/prompt-autocomplete set`. Numeric keys carry their bounds,
|
|
2485
|
+
* which both validation and the usage text use. `bareReports` marks a key that
|
|
2486
|
+
* reports its value when submitted without one, so it is a complete command.
|
|
2487
|
+
*/
|
|
2488
|
+
export const PROMPT_AUTOCOMPLETE_SET_KEYS = [
|
|
2489
|
+
{ key: "debounce-ms", min: DEBOUNCE_MS_MIN, max: DEBOUNCE_MS_MAX, description: "Delay before an automatic request, in milliseconds" },
|
|
2490
|
+
{ key: "min-chars", min: MIN_PROMPT_CHARS_MIN, max: MIN_PROMPT_CHARS_MAX, bareReports: true, description: "Minimum draft length for automatic suggestions" },
|
|
2491
|
+
{ key: "max-chars", min: MAX_SUGGESTION_CHARS_MIN, max: MAX_SUGGESTION_CHARS_MAX, description: "Maximum characters per suggestion" },
|
|
2492
|
+
{ key: "max-alternatives", min: MAX_ALTERNATIVES_MIN, max: MAX_ALTERNATIVES_MAX, description: "Maximum alternatives per request" },
|
|
2493
|
+
{ key: "model", description: "Model for autocomplete requests" },
|
|
2494
|
+
] as const;
|
|
2495
|
+
|
|
2496
|
+
export type PromptAutocompleteSetKey = (typeof PROMPT_AUTOCOMPLETE_SET_KEYS)[number]["key"];
|
|
2497
|
+
|
|
2498
|
+
/** Usage placeholder of one set key, e.g. `<0-5000>`. */
|
|
2499
|
+
export function formatSetKeyPlaceholder(spec: (typeof PROMPT_AUTOCOMPLETE_SET_KEYS)[number]): string {
|
|
2500
|
+
return "min" in spec ? `<${spec.min}-${spec.max}>` : "<provider/model|active>";
|
|
2501
|
+
}
|
|
2502
|
+
|
|
2503
|
+
const SET_COMPLETIONS: readonly PromptAutocompleteCommandCompletion[] = PROMPT_AUTOCOMPLETE_SET_KEYS.flatMap((spec) => [
|
|
2504
|
+
...(spec.key === "model"
|
|
2505
|
+
? [{ value: "set model active", label: "set model active", description: "Follow the session model" }]
|
|
2506
|
+
: []),
|
|
2507
|
+
{
|
|
2508
|
+
value: `set ${spec.key} `,
|
|
2509
|
+
// `active` has its own entry above, so the model label leaves it out and
|
|
2510
|
+
// fits Pi's 30-column label space.
|
|
2511
|
+
label: `set ${spec.key} ${"min" in spec ? formatSetKeyPlaceholder(spec) : "<provider/model>"}`,
|
|
2512
|
+
description: spec.description,
|
|
2513
|
+
},
|
|
2514
|
+
]);
|
|
2515
|
+
|
|
2516
|
+
const ON_OFF_TOGGLE = (subject: string) => [
|
|
2517
|
+
["on", `Turn ${subject} on`],
|
|
2518
|
+
["off", `Turn ${subject} off`],
|
|
2519
|
+
["toggle", `Switch ${subject}`],
|
|
2520
|
+
] as const;
|
|
2521
|
+
|
|
2522
|
+
/**
|
|
2523
|
+
* The `/prompt-autocomplete` grammar: the single source for dispatch, usage
|
|
2524
|
+
* text, and argument completion. Order is the order of the usage text.
|
|
2525
|
+
*/
|
|
2526
|
+
export const PROMPT_AUTOCOMPLETE_COMMANDS = [
|
|
2527
|
+
commandSpec("on", "Enable inline suggestions and save the decision"),
|
|
2528
|
+
commandSpec("off", "Disable inline suggestions and save the decision"),
|
|
2529
|
+
commandSpec("toggle", "Switch inline suggestions on or off"),
|
|
2530
|
+
commandSpec("status", "Show configuration and request state", { readOnly: true }),
|
|
2531
|
+
commandSpec("stats", "Show session requests, cache hits, tokens, and cost", { readOnly: true }),
|
|
2532
|
+
commandSpec("inspect", "Preview locally what a request would send", { usage: "[draft]", readOnly: true }),
|
|
2533
|
+
commandSpec("min-chars", "Set and save the minimum draft length", {
|
|
2534
|
+
usage: "<n>",
|
|
2535
|
+
valuePlaceholder: `<${MIN_PROMPT_CHARS_MIN}-${MIN_PROMPT_CHARS_MAX}>`,
|
|
2536
|
+
bareComplete: true,
|
|
2537
|
+
}),
|
|
2538
|
+
commandSpec("budget", "Cap provider requests for this session", {
|
|
2539
|
+
usage: "<n|off>",
|
|
2540
|
+
choices: [["off", "Remove the session request ceiling"]],
|
|
2541
|
+
valuePlaceholder: `<${BUDGET_REQUESTS_MIN}-${BUDGET_REQUESTS_MAX}>`,
|
|
2542
|
+
bareComplete: true,
|
|
2543
|
+
}),
|
|
2544
|
+
{
|
|
2545
|
+
...commandSpec("set", "Show runtime knobs", { usage: "<key> [value]", bareComplete: true }),
|
|
2546
|
+
completions: SET_COMPLETIONS,
|
|
2547
|
+
},
|
|
2548
|
+
commandSpec("stream", "Toggle streamed response previews", {
|
|
2549
|
+
usage: "on|off|toggle",
|
|
2550
|
+
choices: ON_OFF_TOGGLE("streamed previews"),
|
|
2551
|
+
bareComplete: true,
|
|
2552
|
+
}),
|
|
2553
|
+
commandSpec("while-streaming", "Toggle suggestions while the agent works", {
|
|
2554
|
+
usage: "on|off|toggle",
|
|
2555
|
+
choices: ON_OFF_TOGGLE("suggestions while the agent works"),
|
|
2556
|
+
bareComplete: true,
|
|
2557
|
+
}),
|
|
2558
|
+
commandSpec("debug-on", "Show the debug status line"),
|
|
2559
|
+
commandSpec("debug-off", "Hide the debug status line"),
|
|
2560
|
+
commandSpec("debug-toggle", "Switch the debug status line"),
|
|
2561
|
+
] as const;
|
|
2562
|
+
|
|
2563
|
+
export type PromptAutocompleteCommandName = (typeof PROMPT_AUTOCOMPLETE_COMMANDS)[number]["name"];
|
|
2564
|
+
|
|
2565
|
+
export function findPromptAutocompleteCommand(
|
|
2566
|
+
name: string,
|
|
2567
|
+
): (typeof PROMPT_AUTOCOMPLETE_COMMANDS)[number] | undefined {
|
|
2568
|
+
return PROMPT_AUTOCOMPLETE_COMMANDS.find((spec) => spec.name === name);
|
|
2569
|
+
}
|
|
2570
|
+
|
|
2571
|
+
export function findPromptAutocompleteSetKey(
|
|
2572
|
+
key: string,
|
|
2573
|
+
): (typeof PROMPT_AUTOCOMPLETE_SET_KEYS)[number] | undefined {
|
|
2574
|
+
return PROMPT_AUTOCOMPLETE_SET_KEYS.find((spec) => spec.key === key);
|
|
2575
|
+
}
|
|
2576
|
+
|
|
2577
|
+
export const PROMPT_AUTOCOMPLETE_USAGE = `Usage: /prompt-autocomplete [${PROMPT_AUTOCOMPLETE_COMMANDS.map((spec) =>
|
|
2578
|
+
spec.usage ? `${spec.name} ${spec.usage}` : spec.name
|
|
2579
|
+
).join("|")}]`;
|
|
2580
|
+
|
|
2581
|
+
export const PROMPT_AUTOCOMPLETE_SET_USAGE = `Usage: /prompt-autocomplete set [${PROMPT_AUTOCOMPLETE_SET_KEYS.map((spec) =>
|
|
2582
|
+
`${spec.key} ${formatSetKeyPlaceholder(spec)}`
|
|
2583
|
+
).join("|")}]`;
|
|
2584
|
+
|
|
2585
|
+
const ALL_COMMAND_COMPLETIONS: readonly PromptAutocompleteCommandCompletion[] = PROMPT_AUTOCOMPLETE_COMMANDS.flatMap(
|
|
2586
|
+
(spec) => spec.completions,
|
|
2587
|
+
);
|
|
2588
|
+
|
|
2589
|
+
/**
|
|
2590
|
+
* Argument texts that are complete submissions on their own. Typing one of
|
|
2591
|
+
* these exactly must not open the menu: while it is open, Enter applies a
|
|
2592
|
+
* completion instead of submitting, so `stats` would need Enter twice.
|
|
2593
|
+
*/
|
|
2594
|
+
const COMPLETE_ARGUMENTS: ReadonlySet<string> = new Set([
|
|
2595
|
+
...PROMPT_AUTOCOMPLETE_COMMANDS.filter((spec) => spec.bareComplete).map((spec) => spec.name),
|
|
2596
|
+
...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(" ")),
|
|
2598
|
+
]);
|
|
2599
|
+
|
|
2600
|
+
/**
|
|
2601
|
+
* Complete the argument span of `/prompt-autocomplete`.
|
|
2602
|
+
*
|
|
2603
|
+
* Purely local and synchronous: forms that strictly extend the typed text,
|
|
2604
|
+
* matched case-insensitively with whitespace collapsed, in grammar order.
|
|
2605
|
+
* Returns null when nothing matches or when the typed text is already a
|
|
2606
|
+
* complete submission, so Enter keeps submitting it.
|
|
2607
|
+
*/
|
|
2608
|
+
export function completePromptAutocompleteArguments(
|
|
2609
|
+
argumentPrefix: string,
|
|
2610
|
+
): PromptAutocompleteCommandCompletion[] | null {
|
|
2611
|
+
const typed = argumentPrefix.trimStart().replace(/\s+/g, " ").toLowerCase();
|
|
2612
|
+
if (COMPLETE_ARGUMENTS.has(typed)) return null;
|
|
2613
|
+
const matches = ALL_COMMAND_COMPLETIONS
|
|
2614
|
+
.filter((completion) => completion.value.length > typed.length && completion.value.startsWith(typed))
|
|
2615
|
+
.map((completion) => ({ ...completion }));
|
|
2616
|
+
return matches.length > 0 ? matches : null;
|
|
2617
|
+
}
|