@kliebhan/pi-prompt-autocomplete 0.3.0 → 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/CHANGELOG.md +27 -0
- package/README.md +28 -7
- package/core.ts +433 -5
- package/index.ts +674 -245
- package/package.json +2 -2
package/index.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
2
3
|
import { homedir } from "node:os";
|
|
3
4
|
import { dirname, isAbsolute, join } from "node:path";
|
|
4
5
|
import * as piAi from "@earendil-works/pi-ai";
|
|
@@ -10,10 +11,19 @@ import type {
|
|
|
10
11
|
UserMessage,
|
|
11
12
|
} from "@earendil-works/pi-ai";
|
|
12
13
|
import { CustomEditor, type ExtensionAPI, type ExtensionContext, type KeybindingsManager } from "@earendil-works/pi-coding-agent";
|
|
13
|
-
import {
|
|
14
|
+
import {
|
|
15
|
+
decodeKittyPrintable,
|
|
16
|
+
matchesKey,
|
|
17
|
+
truncateToWidth,
|
|
18
|
+
type EditorTheme,
|
|
19
|
+
type KeyId,
|
|
20
|
+
type TUI,
|
|
21
|
+
visibleWidth,
|
|
22
|
+
} from "@earendil-works/pi-tui";
|
|
14
23
|
import {
|
|
15
24
|
acquireCoalescedRequest,
|
|
16
25
|
buildPromptAutocompleteCacheKey,
|
|
26
|
+
buildPromptAutocompleteDismissalContext,
|
|
17
27
|
buildPromptAutocompletePrefixContextKey,
|
|
18
28
|
buildPromptAutocompleteBudgetSnapshot,
|
|
19
29
|
buildPromptAutocompleteRequestSnapshot,
|
|
@@ -82,9 +92,22 @@ import {
|
|
|
82
92
|
resolvePersistedEnabled,
|
|
83
93
|
resolvePersistedNumber,
|
|
84
94
|
resolvePromptAutocompleteBudgetLimit,
|
|
85
|
-
serializePromptAutocompletePersistedSettings,
|
|
86
95
|
PROMPT_AUTOCOMPLETE_SYSTEM_PROMPT,
|
|
87
96
|
PROMPT_AUTOCOMPLETE_BUDGET_ENTRY_TYPE,
|
|
97
|
+
PROMPT_AUTOCOMPLETE_KEY_ACTIONS,
|
|
98
|
+
PROMPT_AUTOCOMPLETE_CONFIGURABLE_KEY_ACTIONS,
|
|
99
|
+
applyPromptAutocompleteSettingsPatch,
|
|
100
|
+
describeUnusablePromptAutocompleteKey,
|
|
101
|
+
canonicalKeyId,
|
|
102
|
+
extractSuggestionLine,
|
|
103
|
+
findConfigurableKeyAction,
|
|
104
|
+
findPiKeyConflicts,
|
|
105
|
+
mergePromptAutocompleteSettingsText,
|
|
106
|
+
parsePromptAutocompleteKeyId,
|
|
107
|
+
listPromptAutocompleteKeys,
|
|
108
|
+
resolvePromptAutocompleteKeymap,
|
|
109
|
+
type PromptAutocompleteKeymap,
|
|
110
|
+
promptAutocompleteDismissalCovers,
|
|
88
111
|
recordProviderLatency,
|
|
89
112
|
recordProviderUsage,
|
|
90
113
|
resolveAutocompleteConversationId,
|
|
@@ -136,15 +159,6 @@ const REQUEST_CACHE_TTL_MS = 60_000;
|
|
|
136
159
|
const REQUEST_CACHE_MAX_ENTRIES = 128;
|
|
137
160
|
const PRIVACY_NOTICE =
|
|
138
161
|
"Requests send the current draft and recent conversation context to the selected model and may incur provider usage.";
|
|
139
|
-
// Keymap audit vs. pi defaults (packages/tui/src/keybindings.ts +
|
|
140
|
-
// packages/coding-agent/src/core/keybindings.ts): none of the keys below are bound
|
|
141
|
-
// by pi's default keymap, so the editor can safely own them — including the
|
|
142
|
-
// broadened `ctrl+.`/`alt+]` one-shot trigger, which shadows no base action. The
|
|
143
|
-
// only nearby defaults are `ctrl+]` (jumpForward) and `ctrl+alt+]` (jumpBackward),
|
|
144
|
-
// both distinct from our `alt+]`.
|
|
145
|
-
const WORD_ACCEPT_KEYS: readonly KeyId[] = ["ctrl+space", "ctrl+tab"];
|
|
146
|
-
const CYCLE_NEXT_KEYS: readonly KeyId[] = ["ctrl+.", "alt+]"];
|
|
147
|
-
const CYCLE_PREV_KEYS: readonly KeyId[] = ["ctrl+,", "alt+["];
|
|
148
162
|
const NAVIGATION_ACTIONS = [
|
|
149
163
|
"tui.editor.cursorUp",
|
|
150
164
|
"tui.editor.cursorDown",
|
|
@@ -184,6 +198,8 @@ interface PromptAutocompleteConfig {
|
|
|
184
198
|
modelSelection: PromptAutocompleteModelSelection;
|
|
185
199
|
/** Effective provider-request ceiling; undefined means off. */
|
|
186
200
|
budgetLimit?: number;
|
|
201
|
+
/** RPC hosts only: send a predicted next prompt through `setEditorText` after each settled turn. */
|
|
202
|
+
nextPrompt: boolean;
|
|
187
203
|
}
|
|
188
204
|
|
|
189
205
|
interface PromptAutocompleteCacheEntry {
|
|
@@ -365,11 +381,13 @@ function sharedProcessState(): PromptAutocompleteProcessState {
|
|
|
365
381
|
* Persistence boundary for cross-process decisions.
|
|
366
382
|
*
|
|
367
383
|
* `load` runs once per activation and must not throw for a missing or
|
|
368
|
-
* malformed store
|
|
384
|
+
* malformed store. `update` writes one decision on top of what the store holds
|
|
385
|
+
* at that moment, so decisions other processes saved meanwhile survive; it may
|
|
386
|
+
* throw and the caller reports the failure.
|
|
369
387
|
*/
|
|
370
388
|
export interface PromptAutocompleteSettingsStore {
|
|
371
389
|
load(): PromptAutocompletePersistedSettings;
|
|
372
|
-
|
|
390
|
+
update(patch: Partial<PromptAutocompletePersistedSettings>): void;
|
|
373
391
|
}
|
|
374
392
|
|
|
375
393
|
/**
|
|
@@ -391,27 +409,80 @@ export function resolvePromptAutocompleteSettingsPath(
|
|
|
391
409
|
return join(configHome, "pi-prompt-autocomplete", "settings.json");
|
|
392
410
|
}
|
|
393
411
|
|
|
394
|
-
|
|
412
|
+
/**
|
|
413
|
+
* The settings file as a store.
|
|
414
|
+
*
|
|
415
|
+
* Every update re-reads the file and replaces it atomically through a new,
|
|
416
|
+
* owner-only temporary file with an unpredictable name. Only a missing file
|
|
417
|
+
* counts as empty: any other read error aborts the update, so the saved
|
|
418
|
+
* decisions are never replaced by the new one alone. Two processes saving in
|
|
419
|
+
* the same instant can still lose one decision; there is no lock.
|
|
420
|
+
*/
|
|
421
|
+
export function createPromptAutocompleteFileSettingsStore(
|
|
422
|
+
path: string,
|
|
423
|
+
fileSystem: SettingsFileSystem = NODE_SETTINGS_FILE_SYSTEM,
|
|
424
|
+
): PromptAutocompleteSettingsStore {
|
|
425
|
+
const readText = (): string | undefined => {
|
|
426
|
+
try {
|
|
427
|
+
return fileSystem.readFileSync(path, "utf8");
|
|
428
|
+
} catch (error) {
|
|
429
|
+
if (hasErrorCode(error, "ENOENT")) return undefined;
|
|
430
|
+
throw error;
|
|
431
|
+
}
|
|
432
|
+
};
|
|
433
|
+
const removeTemporaryFile = (tempPath: string): void => {
|
|
434
|
+
try {
|
|
435
|
+
fileSystem.rmSync(tempPath, { force: true });
|
|
436
|
+
} catch {
|
|
437
|
+
// The write failure is the error worth reporting.
|
|
438
|
+
}
|
|
439
|
+
};
|
|
395
440
|
return {
|
|
396
441
|
load(): PromptAutocompletePersistedSettings {
|
|
397
|
-
let text: string;
|
|
398
442
|
try {
|
|
399
|
-
|
|
443
|
+
return parsePromptAutocompletePersistedSettings(readText());
|
|
400
444
|
} catch {
|
|
401
445
|
return {};
|
|
402
446
|
}
|
|
403
|
-
return parsePromptAutocompletePersistedSettings(text);
|
|
404
447
|
},
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
const tempPath = `${path}.tmp`;
|
|
408
|
-
mkdirSync(dirname(path), { recursive: true });
|
|
409
|
-
|
|
410
|
-
|
|
448
|
+
update(patch: Partial<PromptAutocompletePersistedSettings>): void {
|
|
449
|
+
const merged = mergePromptAutocompleteSettingsText(readText(), patch);
|
|
450
|
+
const tempPath = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
|
|
451
|
+
fileSystem.mkdirSync(dirname(path), { recursive: true });
|
|
452
|
+
try {
|
|
453
|
+
// `wx` creates the file or fails; it never writes through an entry
|
|
454
|
+
// that already exists under that name, such as a planted link.
|
|
455
|
+
fileSystem.writeFileSync(tempPath, merged, { encoding: "utf8", flag: "wx", mode: 0o600 });
|
|
456
|
+
} catch (error) {
|
|
457
|
+
// An entry that already existed is not ours to remove.
|
|
458
|
+
if (!hasErrorCode(error, "EEXIST")) removeTemporaryFile(tempPath);
|
|
459
|
+
throw error;
|
|
460
|
+
}
|
|
461
|
+
try {
|
|
462
|
+
fileSystem.renameSync(tempPath, path);
|
|
463
|
+
} catch (error) {
|
|
464
|
+
removeTemporaryFile(tempPath);
|
|
465
|
+
throw error;
|
|
466
|
+
}
|
|
411
467
|
},
|
|
412
468
|
};
|
|
413
469
|
}
|
|
414
470
|
|
|
471
|
+
/** The file operations the settings store uses; tests replace them to inject failures. */
|
|
472
|
+
export interface SettingsFileSystem {
|
|
473
|
+
readFileSync(path: string, encoding: "utf8"): string;
|
|
474
|
+
writeFileSync(path: string, data: string, options: { encoding: "utf8"; flag: string; mode: number }): void;
|
|
475
|
+
renameSync(oldPath: string, newPath: string): void;
|
|
476
|
+
rmSync(path: string, options: { force: boolean }): void;
|
|
477
|
+
mkdirSync(path: string, options: { recursive: true }): unknown;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
const NODE_SETTINGS_FILE_SYSTEM: SettingsFileSystem = { readFileSync, writeFileSync, renameSync, rmSync, mkdirSync };
|
|
481
|
+
|
|
482
|
+
function hasErrorCode(error: unknown, code: string): boolean {
|
|
483
|
+
return typeof error === "object" && error !== null && "code" in error && error.code === code;
|
|
484
|
+
}
|
|
485
|
+
|
|
415
486
|
interface PromptAutocompleteSharedState {
|
|
416
487
|
enabled: boolean;
|
|
417
488
|
activationId: number;
|
|
@@ -442,6 +513,8 @@ interface PromptAutocompleteSharedState {
|
|
|
442
513
|
/** Decisions persisted across processes; loaded once per activation. */
|
|
443
514
|
persistedSettings: PromptAutocompletePersistedSettings;
|
|
444
515
|
settingsStore?: PromptAutocompleteSettingsStore;
|
|
516
|
+
/** Effective keys from the saved keys; replaced by `set key`, read at every keypress. */
|
|
517
|
+
keymap: PromptAutocompleteKeymap;
|
|
445
518
|
/** Last enabled-flag value seen by applyEffectiveConfig, for status attribution. */
|
|
446
519
|
enabledFlagValue: boolean;
|
|
447
520
|
/** Explicit min-chars flag value seen by applyEffectiveConfig, undefined when defaulted. */
|
|
@@ -503,9 +576,13 @@ interface PromptAutocompleteSharedState {
|
|
|
503
576
|
inFlightRequests: Map<string, CoalescedRequestEntry<PromptAutocompleteCacheEntry, string>>;
|
|
504
577
|
ownsEditor?: () => boolean;
|
|
505
578
|
refreshEditor?: (options?: SuggestionRefreshOptions) => void;
|
|
579
|
+
/** Pi's keymap as last handed to the editor factory; read by `status`. */
|
|
580
|
+
keybindings?: KeybindingsManager;
|
|
506
581
|
cancelActiveRequest?: () => void;
|
|
507
582
|
/** Cancel a pending debounce timer without aborting an in-flight provider call. */
|
|
508
583
|
cancelScheduledRequest?: () => void;
|
|
584
|
+
/** The running next-prompt request; a new turn or session makes it stale. */
|
|
585
|
+
nextPromptAbort?: AbortController;
|
|
509
586
|
setStatusText?: (text: string | undefined) => void;
|
|
510
587
|
setSpinnerActive?: (owner: string, active: boolean) => void;
|
|
511
588
|
clearSpinner?: () => void;
|
|
@@ -519,9 +596,20 @@ interface SuggestionRequest extends PromptAutocompleteRequestSnapshot {
|
|
|
519
596
|
modelLabel: string;
|
|
520
597
|
cacheKey: string;
|
|
521
598
|
prefixContextKey: string;
|
|
599
|
+
/** Context an Escape dismissal of this request's suggestions is bound to. */
|
|
600
|
+
dismissalContext: string;
|
|
522
601
|
useStreaming: boolean;
|
|
523
602
|
}
|
|
524
603
|
|
|
604
|
+
/** Key actions that act only on input Pi leaves free. */
|
|
605
|
+
type YieldingKeyAction = "cycle" | "manual" | "acceptWord" | "acceptLine";
|
|
606
|
+
|
|
607
|
+
interface EditorInputState {
|
|
608
|
+
text: string;
|
|
609
|
+
cursor: { line: number; col: number };
|
|
610
|
+
autocomplete: boolean;
|
|
611
|
+
}
|
|
612
|
+
|
|
525
613
|
interface PendingSuggestionRequest {
|
|
526
614
|
key: string;
|
|
527
615
|
seq: number;
|
|
@@ -607,8 +695,103 @@ function matchesAnyKey(data: string, keys: readonly KeyId[]): boolean {
|
|
|
607
695
|
return keys.some((key) => matchesKey(data, key));
|
|
608
696
|
}
|
|
609
697
|
|
|
610
|
-
|
|
611
|
-
|
|
698
|
+
/**
|
|
699
|
+
* What in Pi uses this exact input, if anything; a yielding Prompt Autocomplete
|
|
700
|
+
* key must then leave it to Pi.
|
|
701
|
+
*
|
|
702
|
+
* Every action in Pi's current keymap counts, in any scope; Pi's own matcher
|
|
703
|
+
* decides, so its byte and shifted-symbol equivalences apply, and remaps loaded
|
|
704
|
+
* by `/reload` count at once. Inputs that Pi's editor handles outside its keymap
|
|
705
|
+
* count as well: Shift+Space/Backspace/Delete, newline encodings, and printable
|
|
706
|
+
* text. A host whose keymap cannot be listed keeps the keys, as before 0.4.0.
|
|
707
|
+
*/
|
|
708
|
+
function findPiUseOfInput(keybindings: KeybindingsManager, data: string): string | undefined {
|
|
709
|
+
if (typeof keybindings.getResolvedBindings === "function") {
|
|
710
|
+
for (const [action, keys] of Object.entries(keybindings.getResolvedBindings())) {
|
|
711
|
+
if (keys === undefined) continue;
|
|
712
|
+
if ((Array.isArray(keys) ? keys : [keys]).some((key) => matchesKey(data, key))) return action;
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
if (matchesKey(data, "shift+space") || matchesKey(data, "shift+backspace") || matchesKey(data, "shift+delete")) {
|
|
716
|
+
return "the editor";
|
|
717
|
+
}
|
|
718
|
+
// Newline encodings the pi-tui editor accepts besides `tui.input.newLine`.
|
|
719
|
+
if (data === "\n" || data === "\x1b\r" || data === "\x1b[13;2~") return "the editor";
|
|
720
|
+
if (data.length > 1 && (data.charCodeAt(0) === 10 || (data.includes("\x1b") && data.includes("\r")))) {
|
|
721
|
+
return "the editor";
|
|
722
|
+
}
|
|
723
|
+
return data.charCodeAt(0) >= 32 || decodeKittyPrintable(data) !== undefined ? "text input" : undefined;
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/**
|
|
727
|
+
* Those of `keys` that Pi's keymap also binds, as `ctrl+space (app.model.select)`;
|
|
728
|
+
* undefined while the editor has not received Pi's keymap.
|
|
729
|
+
*/
|
|
730
|
+
function listKeysUsedByPi(keybindings: KeybindingsManager | undefined, keys: readonly KeyId[]): string[] | undefined {
|
|
731
|
+
if (typeof keybindings?.getResolvedBindings !== "function") return undefined;
|
|
732
|
+
const resolved = keybindings.getResolvedBindings();
|
|
733
|
+
return keys.flatMap((key) => {
|
|
734
|
+
const conflicts = findPiKeyConflicts(key, resolved);
|
|
735
|
+
return conflicts.length > 0 ? [`${key} (${conflicts.join(", ")})`] : [];
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
function configurableKeys(keymap: PromptAutocompleteKeymap): KeyId[] {
|
|
740
|
+
return PROMPT_AUTOCOMPLETE_CONFIGURABLE_KEY_ACTIONS.flatMap((action) => keymap.keys[action]);
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
function formatKeysUsedByPi(shared: PromptAutocompleteSharedState): string | undefined {
|
|
744
|
+
const usedByPi = listKeysUsedByPi(shared.keybindings, configurableKeys(shared.keymap));
|
|
745
|
+
return usedByPi && usedByPi.length > 0 ? `keys-used-by-pi=${usedByPi.join(", ")}` : undefined;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
/** Key hints for `status` and the enable notice; each names an action's first key. */
|
|
749
|
+
function formatKeyHints(keymap: PromptAutocompleteKeymap): { status: string; notice: string } {
|
|
750
|
+
const [word, line, next, prev] = [
|
|
751
|
+
keymap.keys.acceptWord[0],
|
|
752
|
+
keymap.keys.acceptLine[0],
|
|
753
|
+
keymap.keys.cycleNext[0],
|
|
754
|
+
keymap.keys.cyclePrev[0],
|
|
755
|
+
];
|
|
756
|
+
const cycle = [prev, next].filter((key) => key !== undefined).join("/");
|
|
757
|
+
const status = [
|
|
758
|
+
"tab accept",
|
|
759
|
+
word && `${word} word`,
|
|
760
|
+
line && `${line} line`,
|
|
761
|
+
cycle && `${cycle} cycle`,
|
|
762
|
+
next && `${next} force one-shot`,
|
|
763
|
+
];
|
|
764
|
+
const notice = [
|
|
765
|
+
"Tab accepts all",
|
|
766
|
+
word && `${word} accepts one word`,
|
|
767
|
+
line && `${line} accepts one line`,
|
|
768
|
+
cycle && `${cycle} cycle alternatives`,
|
|
769
|
+
next && `${next} also forces a one-shot suggestion when none is shown (even while the agent works)`,
|
|
770
|
+
];
|
|
771
|
+
return {
|
|
772
|
+
status: status.filter((part) => !!part).join(" | "),
|
|
773
|
+
notice: `${notice.filter((part) => !!part).join(", ")}.`,
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/** `/prompt-autocomplete keys`: every action with its keys and where they come from. */
|
|
778
|
+
function formatKeymap(shared: PromptAutocompleteSharedState): string {
|
|
779
|
+
const { keymap } = shared;
|
|
780
|
+
const actions = listPromptAutocompleteKeys(keymap).map(
|
|
781
|
+
({ command, keys, source }) => `${command} ${keys.join(" ") || "none"} (${source})`,
|
|
782
|
+
);
|
|
783
|
+
const usedByPi = listKeysUsedByPi(shared.keybindings, configurableKeys(keymap));
|
|
784
|
+
return [
|
|
785
|
+
`Prompt autocomplete keys: ${actions.join(" | ")}`,
|
|
786
|
+
keymap.ignored.length > 0 ? `ignored: ${keymap.ignored.join(", ")}` : undefined,
|
|
787
|
+
usedByPi === undefined
|
|
788
|
+
? "Pi's keymap is checked once the editor is active"
|
|
789
|
+
: usedByPi.length > 0
|
|
790
|
+
? `used by Pi, so Pi keeps them: ${usedByPi.join(", ")}`
|
|
791
|
+
: undefined,
|
|
792
|
+
]
|
|
793
|
+
.filter((part) => part !== undefined)
|
|
794
|
+
.join(" | ");
|
|
612
795
|
}
|
|
613
796
|
|
|
614
797
|
interface SuggestionModelResolution {
|
|
@@ -728,6 +911,7 @@ function parseConfig(pi: ExtensionAPI): PromptAutocompleteConfig {
|
|
|
728
911
|
),
|
|
729
912
|
modelSelection: parsePromptAutocompleteModelSelection(pi.getFlag("prompt-autocomplete-model")),
|
|
730
913
|
budgetLimit: parsePromptAutocompleteBudgetFlag(pi.getFlag("prompt-autocomplete-max-requests")),
|
|
914
|
+
nextPrompt: pi.getFlag("prompt-autocomplete-next-prompt") === true,
|
|
731
915
|
};
|
|
732
916
|
}
|
|
733
917
|
|
|
@@ -926,9 +1110,8 @@ function formatStatus(shared: PromptAutocompleteSharedState, interactiveHost = t
|
|
|
926
1110
|
`state=${shared.debugState || "idle"}`,
|
|
927
1111
|
shared.lastError ? `error=${truncateDebug(shared.lastError, 90)}` : undefined,
|
|
928
1112
|
shared.lastRawResponse ? `raw=${truncateDebug(shared.lastRawResponse, 90)}` : undefined,
|
|
929
|
-
interactiveHost
|
|
930
|
-
|
|
931
|
-
: undefined,
|
|
1113
|
+
interactiveHost ? `keys=${formatKeyHints(shared.keymap).status}` : undefined,
|
|
1114
|
+
interactiveHost ? formatKeysUsedByPi(shared) : undefined,
|
|
932
1115
|
]
|
|
933
1116
|
.filter((value): value is string => !!value)
|
|
934
1117
|
.join(" | ");
|
|
@@ -1140,7 +1323,10 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1140
1323
|
// shared spinner alive until every active owner has released it.
|
|
1141
1324
|
private activeSpinnerOwner?: string;
|
|
1142
1325
|
private suspendedUntil = 0;
|
|
1143
|
-
|
|
1326
|
+
/** Escape dismissal: holds while the draft extends `draft` in `context`. */
|
|
1327
|
+
private dismissal?: { draft: string; context: string };
|
|
1328
|
+
/** Dismissal context under which the shown suggestions were produced. */
|
|
1329
|
+
private suggestionsContext?: string;
|
|
1144
1330
|
|
|
1145
1331
|
constructor(
|
|
1146
1332
|
tui: TUI,
|
|
@@ -1167,23 +1353,33 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1167
1353
|
|
|
1168
1354
|
override handleInput(data: string): void {
|
|
1169
1355
|
if (this.canDismissInlineSuggestion(data)) {
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
}
|
|
1179
|
-
|
|
1180
|
-
if (this.canTriggerManualSuggestion(data)) {
|
|
1181
|
-
this.triggerManualSuggestion();
|
|
1356
|
+
// Bound to the context the visible suggestion came from, not a freshly
|
|
1357
|
+
// built request, which a model or auth failure could not provide.
|
|
1358
|
+
this.dismissal = {
|
|
1359
|
+
draft: this.getText(),
|
|
1360
|
+
context: this.suggestionsContext
|
|
1361
|
+
?? buildDismissalContext(this.shared, resolveCurrentConversationId(this.shared)),
|
|
1362
|
+
};
|
|
1363
|
+
this.clearInlineSuggestion("dismissed", "Suggestion dismissed while this draft continues");
|
|
1182
1364
|
return;
|
|
1183
1365
|
}
|
|
1184
1366
|
|
|
1185
|
-
|
|
1186
|
-
|
|
1367
|
+
const action = this.matchYieldingKeyAction(data);
|
|
1368
|
+
const piUse = action ? findPiUseOfInput(this.appKeybindings, data) : undefined;
|
|
1369
|
+
if (piUse) {
|
|
1370
|
+
// Shown until the refresh after Pi's handling reports something newer.
|
|
1371
|
+
updateDebugState(this.shared, "yielded", `Key left to Pi: ${piUse}`);
|
|
1372
|
+
} else if (action) {
|
|
1373
|
+
// Pi's order: another extension's shortcut on the same key comes first.
|
|
1374
|
+
const before = this.captureInputState();
|
|
1375
|
+
if (this.onExtensionShortcut?.(data)) {
|
|
1376
|
+
this.refreshAfterInput(before);
|
|
1377
|
+
return;
|
|
1378
|
+
}
|
|
1379
|
+
// For input Pi leaves free, Pi's editor only cancels a pending character
|
|
1380
|
+
// jump, exactly as without this extension.
|
|
1381
|
+
super.handleInput(data);
|
|
1382
|
+
this.runYieldingKeyAction(action, data);
|
|
1187
1383
|
return;
|
|
1188
1384
|
}
|
|
1189
1385
|
|
|
@@ -1194,19 +1390,42 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1194
1390
|
|
|
1195
1391
|
this.clearInlineSuggestionForUserIntent(data);
|
|
1196
1392
|
|
|
1197
|
-
const
|
|
1198
|
-
const beforeCursor = this.getCursor();
|
|
1199
|
-
const beforeAutocomplete = this.isShowingAutocomplete();
|
|
1200
|
-
|
|
1393
|
+
const before = this.captureInputState();
|
|
1201
1394
|
super.handleInput(data);
|
|
1395
|
+
this.refreshAfterInput(before);
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
/** The yielding key action this input would trigger right now, if any. */
|
|
1399
|
+
private matchYieldingKeyAction(data: string): YieldingKeyAction | undefined {
|
|
1400
|
+
if (this.canCycleSuggestions(data)) return "cycle";
|
|
1401
|
+
if (this.canTriggerManualSuggestion(data)) return "manual";
|
|
1402
|
+
if (this.canAcceptInlineSuggestionPart(data, this.shared.keymap.keys.acceptWord)) return "acceptWord";
|
|
1403
|
+
if (this.canAcceptInlineSuggestionPart(data, this.shared.keymap.keys.acceptLine)) return "acceptLine";
|
|
1404
|
+
return undefined;
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
private runYieldingKeyAction(action: YieldingKeyAction, data: string): void {
|
|
1408
|
+
if (action === "cycle") {
|
|
1409
|
+
this.cycleSuggestions(matchesAnyKey(data, this.shared.keymap.keys.cycleNext) ? 1 : -1);
|
|
1410
|
+
} else if (action === "manual") {
|
|
1411
|
+
this.triggerManualSuggestion();
|
|
1412
|
+
} else if (action === "acceptWord") {
|
|
1413
|
+
this.acceptInlineSuggestionByWord();
|
|
1414
|
+
} else {
|
|
1415
|
+
this.acceptInlineSuggestionByLine();
|
|
1416
|
+
}
|
|
1417
|
+
}
|
|
1202
1418
|
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1419
|
+
private captureInputState(): EditorInputState {
|
|
1420
|
+
return { text: this.getText(), cursor: this.getCursor(), autocomplete: this.isShowingAutocomplete() };
|
|
1421
|
+
}
|
|
1206
1422
|
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
const
|
|
1423
|
+
/** Refresh suggestions after input that the editor or Pi handled. */
|
|
1424
|
+
private refreshAfterInput(before: EditorInputState): void {
|
|
1425
|
+
const after = this.captureInputState();
|
|
1426
|
+
const textChanged = before.text !== after.text;
|
|
1427
|
+
const cursorChanged = before.cursor.line !== after.cursor.line || before.cursor.col !== after.cursor.col;
|
|
1428
|
+
const autocompleteChanged = before.autocomplete !== after.autocomplete;
|
|
1210
1429
|
|
|
1211
1430
|
if (textChanged || cursorChanged || autocompleteChanged) {
|
|
1212
1431
|
this.refreshSuggestion({ clearExisting: true });
|
|
@@ -1323,8 +1542,15 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1323
1542
|
|
|
1324
1543
|
private setSuggestions(
|
|
1325
1544
|
nextSuggestions: string[],
|
|
1326
|
-
options: {
|
|
1545
|
+
options: {
|
|
1546
|
+
provisional?: boolean;
|
|
1547
|
+
origins?: string[];
|
|
1548
|
+
preferredOrigin?: string;
|
|
1549
|
+
/** Dismissal context of the request that produced the suggestions. */
|
|
1550
|
+
context?: string;
|
|
1551
|
+
} = {},
|
|
1327
1552
|
): void {
|
|
1553
|
+
this.suggestionsContext = nextSuggestions.length > 0 ? options.context : undefined;
|
|
1328
1554
|
const provisional = options.provisional ?? false;
|
|
1329
1555
|
const nextOrigins = options.origins?.length === nextSuggestions.length
|
|
1330
1556
|
? [...options.origins]
|
|
@@ -1377,13 +1603,33 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1377
1603
|
this.tui.requestRender();
|
|
1378
1604
|
}
|
|
1379
1605
|
|
|
1606
|
+
/**
|
|
1607
|
+
* End a dismissal for good once the draft or its context moved on.
|
|
1608
|
+
*
|
|
1609
|
+
* Returns whether the dismissal still holds. Returning to the dismissed draft
|
|
1610
|
+
* or context later does not restore a dismissal that ended.
|
|
1611
|
+
*/
|
|
1612
|
+
private reconcileDismissal(): boolean {
|
|
1613
|
+
if (!this.dismissal) return false;
|
|
1614
|
+
const context = buildDismissalContext(this.shared, resolveCurrentConversationId(this.shared));
|
|
1615
|
+
if (promptAutocompleteDismissalCovers(this.dismissal, this.getText(), context)) return true;
|
|
1616
|
+
this.dismissal = undefined;
|
|
1617
|
+
return false;
|
|
1618
|
+
}
|
|
1619
|
+
|
|
1620
|
+
/** Whether a response for `request` arrives into a standing dismissal. */
|
|
1621
|
+
private dismissalCovers(request: SuggestionRequest): boolean {
|
|
1622
|
+
return !!this.dismissal
|
|
1623
|
+
&& promptAutocompleteDismissalCovers(this.dismissal, request.draft, request.dismissalContext);
|
|
1624
|
+
}
|
|
1625
|
+
|
|
1380
1626
|
private cycleSuggestions(delta: 1 | -1): void {
|
|
1381
1627
|
if (this.suggestions.length <= 1) return;
|
|
1382
1628
|
const nextIndex = (this.suggestionIndex + delta + this.suggestions.length) % this.suggestions.length;
|
|
1383
1629
|
if (nextIndex === this.suggestionIndex) return;
|
|
1384
1630
|
this.suggestionIndex = nextIndex;
|
|
1385
1631
|
this.shared.usageStats.suggestionsOffered += 1;
|
|
1386
|
-
this.
|
|
1632
|
+
this.dismissal = undefined;
|
|
1387
1633
|
updateDebugState(this.shared, "cycled", `Now showing ${nextIndex + 1}/${this.suggestions.length}`);
|
|
1388
1634
|
this.tui.requestRender();
|
|
1389
1635
|
}
|
|
@@ -1394,13 +1640,13 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1394
1640
|
private canTriggerManualSuggestion(data: string): boolean {
|
|
1395
1641
|
if (!this.shared.enabled || this.activationId !== this.shared.activationId) return false;
|
|
1396
1642
|
if (this.isShowingAutocomplete()) return false;
|
|
1397
|
-
return matchesAnyKey(data,
|
|
1643
|
+
return matchesAnyKey(data, this.shared.keymap.keys.cycleNext);
|
|
1398
1644
|
}
|
|
1399
1645
|
|
|
1400
1646
|
private triggerManualSuggestion(): void {
|
|
1401
1647
|
// refreshSuggestion immediately sets its own debug state, so we only clear any
|
|
1402
1648
|
// standing dismissal here and let the refresh report the real outcome.
|
|
1403
|
-
this.
|
|
1649
|
+
this.dismissal = undefined;
|
|
1404
1650
|
this.refreshSuggestion({ clearExisting: true, immediate: true, manual: true });
|
|
1405
1651
|
}
|
|
1406
1652
|
|
|
@@ -1412,14 +1658,15 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1412
1658
|
return this.shouldRenderInlineSuggestion() && !!this.getActiveSuggestion() && matchesKey(data, "tab");
|
|
1413
1659
|
}
|
|
1414
1660
|
|
|
1415
|
-
private
|
|
1416
|
-
return this.shouldRenderInlineSuggestion() && !!this.getActiveSuggestion() && matchesAnyKey(data,
|
|
1661
|
+
private canAcceptInlineSuggestionPart(data: string, keys: readonly KeyId[]): boolean {
|
|
1662
|
+
return this.shouldRenderInlineSuggestion() && !!this.getActiveSuggestion() && matchesAnyKey(data, keys);
|
|
1417
1663
|
}
|
|
1418
1664
|
|
|
1419
1665
|
private canCycleSuggestions(data: string): boolean {
|
|
1420
1666
|
if (!this.shouldRenderInlineSuggestion()) return false;
|
|
1421
1667
|
if (this.suggestions.length <= 1) return false;
|
|
1422
|
-
|
|
1668
|
+
const { cycleNext, cyclePrev } = this.shared.keymap.keys;
|
|
1669
|
+
return matchesAnyKey(data, cycleNext) || matchesAnyKey(data, cyclePrev);
|
|
1423
1670
|
}
|
|
1424
1671
|
|
|
1425
1672
|
private clearInlineSuggestion(state: string, details: string): void {
|
|
@@ -1461,7 +1708,7 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1461
1708
|
|
|
1462
1709
|
const wasProvisional = this.suggestionsProvisional;
|
|
1463
1710
|
this.shared.usageStats.fullAccepts += 1;
|
|
1464
|
-
this.
|
|
1711
|
+
this.dismissal = undefined;
|
|
1465
1712
|
this.clearInlineSuggestion("accepted", wasProvisional ? "Accepted streamed partial suggestion" : "Accepted full suggestion");
|
|
1466
1713
|
super.insertTextAtCursor(suggestion);
|
|
1467
1714
|
// A provisional accept is explicit cancellation of the request. Starting a
|
|
@@ -1472,15 +1719,30 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1472
1719
|
private acceptInlineSuggestionByWord(): void {
|
|
1473
1720
|
const suggestion = this.getActiveSuggestion();
|
|
1474
1721
|
if (!suggestion) return;
|
|
1722
|
+
this.acceptInlineSuggestionPart(extractNextSuggestionChunk(suggestion) ?? suggestion, "accepted-word");
|
|
1723
|
+
}
|
|
1475
1724
|
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1725
|
+
/** Accept up to the first line break; a completed one-line suggestion is a full accept. */
|
|
1726
|
+
private acceptInlineSuggestionByLine(): void {
|
|
1727
|
+
const suggestion = this.getActiveSuggestion();
|
|
1728
|
+
if (!suggestion) return;
|
|
1729
|
+
const line = extractSuggestionLine(suggestion);
|
|
1730
|
+
// A streamed partial is not the whole suggestion, even without a line break.
|
|
1731
|
+
if (line === suggestion && !this.suggestionsProvisional) {
|
|
1732
|
+
this.acceptInlineSuggestion();
|
|
1733
|
+
return;
|
|
1734
|
+
}
|
|
1735
|
+
this.acceptInlineSuggestionPart(line, "accepted-line");
|
|
1736
|
+
}
|
|
1479
1737
|
|
|
1738
|
+
/** Insert the start of the active suggestion and keep offering the rest. */
|
|
1739
|
+
private acceptInlineSuggestionPart(chunk: string, state: string): void {
|
|
1740
|
+
if (!chunk) return;
|
|
1741
|
+
const origin = this.getActiveSuggestionOrigin();
|
|
1480
1742
|
const wasProvisional = this.suggestionsProvisional;
|
|
1481
1743
|
this.shared.usageStats.chunkAccepts += 1;
|
|
1482
|
-
this.
|
|
1483
|
-
this.clearInlineSuggestion(
|
|
1744
|
+
this.dismissal = undefined;
|
|
1745
|
+
this.clearInlineSuggestion(state, `Accepted chunk: ${chunk}`);
|
|
1484
1746
|
super.insertTextAtCursor(chunk);
|
|
1485
1747
|
if (!wasProvisional) this.refreshSuggestion({ preferredOrigin: origin });
|
|
1486
1748
|
}
|
|
@@ -1534,6 +1796,9 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1534
1796
|
|
|
1535
1797
|
private refreshSuggestion(options: SuggestionRefreshOptions = {}): void {
|
|
1536
1798
|
const preferredOrigin = options.preferredOrigin ?? this.getActiveSuggestionOrigin();
|
|
1799
|
+
// Before every gate: a draft or context that moved on ends the dismissal
|
|
1800
|
+
// even when a gate or a model without auth stops this refresh.
|
|
1801
|
+
const dismissed = this.reconcileDismissal();
|
|
1537
1802
|
if (options.clearExisting) {
|
|
1538
1803
|
this.cancelPendingRequest();
|
|
1539
1804
|
this.setSuggestions([]);
|
|
@@ -1551,6 +1816,15 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1551
1816
|
return;
|
|
1552
1817
|
}
|
|
1553
1818
|
|
|
1819
|
+
// A standing dismissal settles the refresh before any gate, model lookup, or
|
|
1820
|
+
// request snapshot, so continued typing stays cheap.
|
|
1821
|
+
if (!options.manual && dismissed) {
|
|
1822
|
+
this.cancelPendingRequest();
|
|
1823
|
+
updateDebugState(this.shared, "dismissed", "Suggestion dismissed while this draft continues");
|
|
1824
|
+
this.setSuggestions([]);
|
|
1825
|
+
return;
|
|
1826
|
+
}
|
|
1827
|
+
|
|
1554
1828
|
if (this.isShowingAutocomplete()) {
|
|
1555
1829
|
this.cancelPendingRequest();
|
|
1556
1830
|
updateDebugState(this.shared, "paused", "Built-in autocomplete is active");
|
|
@@ -1574,13 +1848,6 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1574
1848
|
return;
|
|
1575
1849
|
}
|
|
1576
1850
|
|
|
1577
|
-
if (!options.manual && request.cacheKey === this.dismissedKey) {
|
|
1578
|
-
this.cancelPendingRequest();
|
|
1579
|
-
updateDebugState(this.shared, "dismissed", "Suggestion dismissed for current draft");
|
|
1580
|
-
this.setSuggestions([]);
|
|
1581
|
-
return;
|
|
1582
|
-
}
|
|
1583
|
-
|
|
1584
1851
|
const cachedEntry = getCachedRequest(this.shared, request.cacheKey, { bypass: options.manual });
|
|
1585
1852
|
if (cachedEntry) {
|
|
1586
1853
|
this.shared.usageStats.cacheHits += 1;
|
|
@@ -1594,6 +1861,7 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1594
1861
|
this.setSuggestions(cachedEntry.suggestions, {
|
|
1595
1862
|
origins: cachedEntry.suggestions,
|
|
1596
1863
|
preferredOrigin,
|
|
1864
|
+
context: request.dismissalContext,
|
|
1597
1865
|
});
|
|
1598
1866
|
return;
|
|
1599
1867
|
}
|
|
@@ -1608,6 +1876,7 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1608
1876
|
this.setSuggestions(prefixReused.entry.suggestions, {
|
|
1609
1877
|
origins: prefixReused.origins,
|
|
1610
1878
|
preferredOrigin,
|
|
1879
|
+
context: request.dismissalContext,
|
|
1611
1880
|
});
|
|
1612
1881
|
updateDebugState(
|
|
1613
1882
|
this.shared,
|
|
@@ -1667,35 +1936,7 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1667
1936
|
}
|
|
1668
1937
|
|
|
1669
1938
|
private buildRequest(): SuggestionRequest | undefined {
|
|
1670
|
-
|
|
1671
|
-
if (!model) return undefined;
|
|
1672
|
-
|
|
1673
|
-
const conversationId = resolveCurrentConversationId(this.shared);
|
|
1674
|
-
this.shared.lastConversationId = conversationId;
|
|
1675
|
-
const snapshot = buildCurrentRequestSnapshot(this.shared, this.getText(), conversationId);
|
|
1676
|
-
const modelLabel = formatModelLabel(model);
|
|
1677
|
-
|
|
1678
|
-
const prefixContextIdentity = {
|
|
1679
|
-
conversationId,
|
|
1680
|
-
modelLabel,
|
|
1681
|
-
maxAlternatives: snapshot.maxAlternatives,
|
|
1682
|
-
maxSuggestionChars: snapshot.maxSuggestionChars,
|
|
1683
|
-
latestAssistantContext: snapshot.latestAssistantContext,
|
|
1684
|
-
latestUserContext: snapshot.latestUserContext,
|
|
1685
|
-
recentContext: snapshot.recentContext,
|
|
1686
|
-
compactionSummaryContext: snapshot.compactionSummaryContext,
|
|
1687
|
-
};
|
|
1688
|
-
|
|
1689
|
-
return {
|
|
1690
|
-
...snapshot,
|
|
1691
|
-
activationId: this.activationId,
|
|
1692
|
-
conversationId,
|
|
1693
|
-
model,
|
|
1694
|
-
modelLabel,
|
|
1695
|
-
cacheKey: buildPromptAutocompleteCacheKey({ ...prefixContextIdentity, draft: snapshot.draft }),
|
|
1696
|
-
prefixContextKey: buildPromptAutocompletePrefixContextKey(prefixContextIdentity),
|
|
1697
|
-
useStreaming: this.shared.config.streamResponses && !!this.shared.streamSimple,
|
|
1698
|
-
};
|
|
1939
|
+
return buildSuggestionRequest(this.shared, this.getText(), this.activationId);
|
|
1699
1940
|
}
|
|
1700
1941
|
|
|
1701
1942
|
private async fetchSuggestion(request: SuggestionRequest, seq: number, spinnerOwner: string): Promise<void> {
|
|
@@ -1710,7 +1951,7 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1710
1951
|
this.shared.inFlightRequests,
|
|
1711
1952
|
request.cacheKey,
|
|
1712
1953
|
subscriberId,
|
|
1713
|
-
(signal, publish) => this.
|
|
1954
|
+
(signal, publish) => fetchSuggestionUncached(this.shared, request, signal, publish),
|
|
1714
1955
|
(suggestion) => this.showStreamedSuggestion(request, seq, spinnerOwner, suggestion),
|
|
1715
1956
|
);
|
|
1716
1957
|
|
|
@@ -1736,8 +1977,8 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1736
1977
|
if (entry.suggestions.length === 0) {
|
|
1737
1978
|
updateDebugState(this.shared, "no-suggestion", entry.debugState || "No usable suggestions");
|
|
1738
1979
|
}
|
|
1739
|
-
if (
|
|
1740
|
-
this.setSuggestions(entry.suggestions);
|
|
1980
|
+
if (!this.dismissalCovers(request)) {
|
|
1981
|
+
this.setSuggestions(entry.suggestions, { context: request.dismissalContext });
|
|
1741
1982
|
}
|
|
1742
1983
|
} catch (error) {
|
|
1743
1984
|
if (error instanceof PromptAutocompleteBudgetExhaustedError) {
|
|
@@ -1782,144 +2023,17 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1782
2023
|
return;
|
|
1783
2024
|
}
|
|
1784
2025
|
if (!this.isRequestStillCurrent(request, seq)) return;
|
|
1785
|
-
if (
|
|
2026
|
+
if (this.dismissalCovers(request)) return;
|
|
1786
2027
|
|
|
1787
2028
|
const current = this.getActiveSuggestion();
|
|
1788
2029
|
// Progress is strictly monotonic. If a provider revises earlier text, keep
|
|
1789
2030
|
// the last honest preview and let the terminal response replace it.
|
|
1790
2031
|
if (current && (!suggestion.startsWith(current) || suggestion.length <= current.length)) return;
|
|
1791
2032
|
|
|
1792
|
-
this.setSuggestions([suggestion], { provisional: true });
|
|
2033
|
+
this.setSuggestions([suggestion], { provisional: true, context: request.dismissalContext });
|
|
1793
2034
|
this.deactivateSpinner(spinnerOwner);
|
|
1794
2035
|
}
|
|
1795
2036
|
|
|
1796
|
-
private async fetchSuggestionUncached(
|
|
1797
|
-
request: SuggestionRequest,
|
|
1798
|
-
signal: AbortSignal,
|
|
1799
|
-
publish: (suggestion: string) => void,
|
|
1800
|
-
): Promise<PromptAutocompleteCacheEntry> {
|
|
1801
|
-
if (!this.shared.modelRegistry) {
|
|
1802
|
-
throw new Error("No model registry available");
|
|
1803
|
-
}
|
|
1804
|
-
|
|
1805
|
-
const auth = await this.shared.modelRegistry.getApiKeyAndHeaders(request.model);
|
|
1806
|
-
// Through the host registry Pi resolves the stored credential itself, which
|
|
1807
|
-
// may be header-only or ambient, so only the compat path needs a key here.
|
|
1808
|
-
const viaRegistry = this.shared.routesThroughHostRegistry();
|
|
1809
|
-
if (!auth.ok) throw new Error(auth.error);
|
|
1810
|
-
if (!viaRegistry && !auth.apiKey) throw new Error(`No API key for ${request.modelLabel}`);
|
|
1811
|
-
if (signal.aborted) {
|
|
1812
|
-
throw new Error("Request was aborted");
|
|
1813
|
-
}
|
|
1814
|
-
// Last await is done: reserving here and invoking below without another
|
|
1815
|
-
// await is what keeps two concurrent producers from overshooting a ceiling.
|
|
1816
|
-
if (!reserveBudgetRequest(this.shared)) {
|
|
1817
|
-
throw new PromptAutocompleteBudgetExhaustedError(
|
|
1818
|
-
this.shared.config.budgetLimit ?? this.shared.budgetUsed,
|
|
1819
|
-
this.shared.budgetUsed,
|
|
1820
|
-
);
|
|
1821
|
-
}
|
|
1822
|
-
|
|
1823
|
-
const userMessage: UserMessage = {
|
|
1824
|
-
role: "user",
|
|
1825
|
-
content: [{ type: "text", text: renderPromptAutocompleteUserText(request) }],
|
|
1826
|
-
timestamp: Date.now(),
|
|
1827
|
-
};
|
|
1828
|
-
|
|
1829
|
-
const stats = this.shared.usageStats;
|
|
1830
|
-
stats.providerRequests += 1;
|
|
1831
|
-
|
|
1832
|
-
const context = {
|
|
1833
|
-
systemPrompt: PROMPT_AUTOCOMPLETE_SYSTEM_PROMPT,
|
|
1834
|
-
messages: [userMessage],
|
|
1835
|
-
};
|
|
1836
|
-
const requestOptions = {
|
|
1837
|
-
// An explicit key makes Pi's registry skip the stored credential and with
|
|
1838
|
-
// it any OAuth-derived endpoint (for example GitHub Copilot Enterprise),
|
|
1839
|
-
// so credentials are only passed to the compat functions and to seams.
|
|
1840
|
-
...(viaRegistry ? {} : { apiKey: auth.apiKey, headers: auth.headers }),
|
|
1841
|
-
signal,
|
|
1842
|
-
maxTokens: computeRequestMaxTokens(request.maxAlternatives, request.maxSuggestionChars),
|
|
1843
|
-
timeoutMs: REQUEST_TIMEOUT_MS,
|
|
1844
|
-
maxRetries: REQUEST_MAX_RETRIES,
|
|
1845
|
-
maxRetryDelayMs: REQUEST_MAX_RETRY_DELAY_MS,
|
|
1846
|
-
};
|
|
1847
|
-
|
|
1848
|
-
const providerStartedAt = this.shared.now();
|
|
1849
|
-
let response: AssistantMessage;
|
|
1850
|
-
try {
|
|
1851
|
-
if (request.useStreaming && this.shared.streamSimple) {
|
|
1852
|
-
const hardDeadlineController = new AbortController();
|
|
1853
|
-
const streamSignal = AbortSignal.any([signal, hardDeadlineController.signal]);
|
|
1854
|
-
const stream = this.shared.streamSimple(request.model, context, {
|
|
1855
|
-
...requestOptions,
|
|
1856
|
-
signal: streamSignal,
|
|
1857
|
-
});
|
|
1858
|
-
let lastPublished = "";
|
|
1859
|
-
|
|
1860
|
-
// Exactly one consumer receives the terminal message. Partial text is
|
|
1861
|
-
// fanned out through coalescing; after UI cancellation the callback is
|
|
1862
|
-
// gone, but the bounded drain can still retain terminal usage.
|
|
1863
|
-
response = await consumeAssistantStream(stream, streamSignal, () => hardDeadlineController.abort(), (partial) => {
|
|
1864
|
-
// `partial` is cumulative. Appending delta plus text_end.content would
|
|
1865
|
-
// duplicate the completed block on providers that emit both.
|
|
1866
|
-
const partialText = extractAssistantText(partial);
|
|
1867
|
-
const suggestion = parsePartialPromptSuggestion(request.draft, partialText, request.maxSuggestionChars);
|
|
1868
|
-
if (!suggestion || suggestion === lastPublished) return;
|
|
1869
|
-
if (lastPublished && !suggestion.startsWith(lastPublished)) return;
|
|
1870
|
-
lastPublished = suggestion;
|
|
1871
|
-
publish(suggestion);
|
|
1872
|
-
});
|
|
1873
|
-
} else {
|
|
1874
|
-
response = await this.shared.completeSimple(request.model, context, requestOptions);
|
|
1875
|
-
}
|
|
1876
|
-
} catch (error) {
|
|
1877
|
-
stats.failedRequests += 1;
|
|
1878
|
-
throw error;
|
|
1879
|
-
} finally {
|
|
1880
|
-
recordProviderLatency(stats, this.shared.now() - providerStartedAt);
|
|
1881
|
-
}
|
|
1882
|
-
|
|
1883
|
-
// Tokens spent on a failed or aborted response are still spent, so usage is
|
|
1884
|
-
// recorded before the stop-reason check rejects the request.
|
|
1885
|
-
recordProviderUsage(stats, response.usage);
|
|
1886
|
-
|
|
1887
|
-
const contentTypes = response.content.map((block) => block.type).join(", ") || "(none)";
|
|
1888
|
-
const text = extractAssistantText(response);
|
|
1889
|
-
|
|
1890
|
-
const responseError = response.errorMessage?.trim();
|
|
1891
|
-
const rawResponse = text || responseError || `[types=${contentTypes}; stopReason=${response.stopReason}]`;
|
|
1892
|
-
|
|
1893
|
-
if (response.stopReason === "error" || response.stopReason === "aborted") {
|
|
1894
|
-
stats.failedRequests += 1;
|
|
1895
|
-
throw new Error(responseError || `Provider returned stopReason=${response.stopReason}`);
|
|
1896
|
-
}
|
|
1897
|
-
if (signal.aborted) {
|
|
1898
|
-
stats.failedRequests += 1;
|
|
1899
|
-
throw new Error("Request was aborted");
|
|
1900
|
-
}
|
|
1901
|
-
|
|
1902
|
-
const normalized = normalizePromptSuggestions(
|
|
1903
|
-
request.draft,
|
|
1904
|
-
text,
|
|
1905
|
-
request.maxSuggestionChars,
|
|
1906
|
-
request.maxAlternatives,
|
|
1907
|
-
);
|
|
1908
|
-
|
|
1909
|
-
const debugState =
|
|
1910
|
-
normalized.length === 0
|
|
1911
|
-
? text || `No text blocks returned (types: ${contentTypes}; stopReason: ${response.stopReason})`
|
|
1912
|
-
: `${normalized.length} suggestion(s) ready`;
|
|
1913
|
-
|
|
1914
|
-
return storeCachedRequest(this.shared, request.cacheKey, {
|
|
1915
|
-
draft: request.draft,
|
|
1916
|
-
prefixContextKey: request.prefixContextKey,
|
|
1917
|
-
suggestions: normalized,
|
|
1918
|
-
rawResponse,
|
|
1919
|
-
debugState,
|
|
1920
|
-
});
|
|
1921
|
-
}
|
|
1922
|
-
|
|
1923
2037
|
private isRequestStillCurrent(request: SuggestionRequest, seq: number): boolean {
|
|
1924
2038
|
if (!this.shared.enabled) return false;
|
|
1925
2039
|
if (!this.shared.ownsEditor?.()) return false;
|
|
@@ -1994,6 +2108,138 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1994
2108
|
}
|
|
1995
2109
|
}
|
|
1996
2110
|
|
|
2111
|
+
/**
|
|
2112
|
+
* One provider call for `request`, outside any editor: reserves budget, records
|
|
2113
|
+
* usage, and caches the normalized result. `publish` receives streamed partials.
|
|
2114
|
+
*/
|
|
2115
|
+
async function fetchSuggestionUncached(
|
|
2116
|
+
shared: PromptAutocompleteSharedState,
|
|
2117
|
+
request: SuggestionRequest,
|
|
2118
|
+
signal: AbortSignal,
|
|
2119
|
+
publish: (suggestion: string) => void,
|
|
2120
|
+
): Promise<PromptAutocompleteCacheEntry> {
|
|
2121
|
+
if (!shared.modelRegistry) {
|
|
2122
|
+
throw new Error("No model registry available");
|
|
2123
|
+
}
|
|
2124
|
+
|
|
2125
|
+
const auth = await shared.modelRegistry.getApiKeyAndHeaders(request.model);
|
|
2126
|
+
// Through the host registry Pi resolves the stored credential itself, which
|
|
2127
|
+
// may be header-only or ambient, so only the compat path needs a key here.
|
|
2128
|
+
const viaRegistry = shared.routesThroughHostRegistry();
|
|
2129
|
+
if (!auth.ok) throw new Error(auth.error);
|
|
2130
|
+
if (!viaRegistry && !auth.apiKey) throw new Error(`No API key for ${request.modelLabel}`);
|
|
2131
|
+
if (signal.aborted) {
|
|
2132
|
+
throw new Error("Request was aborted");
|
|
2133
|
+
}
|
|
2134
|
+
// Last await is done: reserving here and invoking below without another
|
|
2135
|
+
// await is what keeps two concurrent producers from overshooting a ceiling.
|
|
2136
|
+
if (!reserveBudgetRequest(shared)) {
|
|
2137
|
+
throw new PromptAutocompleteBudgetExhaustedError(
|
|
2138
|
+
shared.config.budgetLimit ?? shared.budgetUsed,
|
|
2139
|
+
shared.budgetUsed,
|
|
2140
|
+
);
|
|
2141
|
+
}
|
|
2142
|
+
|
|
2143
|
+
const userMessage: UserMessage = {
|
|
2144
|
+
role: "user",
|
|
2145
|
+
content: [{ type: "text", text: renderPromptAutocompleteUserText(request) }],
|
|
2146
|
+
timestamp: Date.now(),
|
|
2147
|
+
};
|
|
2148
|
+
|
|
2149
|
+
const stats = shared.usageStats;
|
|
2150
|
+
stats.providerRequests += 1;
|
|
2151
|
+
|
|
2152
|
+
const context = {
|
|
2153
|
+
systemPrompt: PROMPT_AUTOCOMPLETE_SYSTEM_PROMPT,
|
|
2154
|
+
messages: [userMessage],
|
|
2155
|
+
};
|
|
2156
|
+
const requestOptions = {
|
|
2157
|
+
// An explicit key makes Pi's registry skip the stored credential and with
|
|
2158
|
+
// it any OAuth-derived endpoint (for example GitHub Copilot Enterprise),
|
|
2159
|
+
// so credentials are only passed to the compat functions and to seams.
|
|
2160
|
+
...(viaRegistry ? {} : { apiKey: auth.apiKey, headers: auth.headers }),
|
|
2161
|
+
signal,
|
|
2162
|
+
maxTokens: computeRequestMaxTokens(request.maxAlternatives, request.maxSuggestionChars),
|
|
2163
|
+
timeoutMs: REQUEST_TIMEOUT_MS,
|
|
2164
|
+
maxRetries: REQUEST_MAX_RETRIES,
|
|
2165
|
+
maxRetryDelayMs: REQUEST_MAX_RETRY_DELAY_MS,
|
|
2166
|
+
};
|
|
2167
|
+
|
|
2168
|
+
const providerStartedAt = shared.now();
|
|
2169
|
+
let response: AssistantMessage;
|
|
2170
|
+
try {
|
|
2171
|
+
if (request.useStreaming && shared.streamSimple) {
|
|
2172
|
+
const hardDeadlineController = new AbortController();
|
|
2173
|
+
const streamSignal = AbortSignal.any([signal, hardDeadlineController.signal]);
|
|
2174
|
+
const stream = shared.streamSimple(request.model, context, {
|
|
2175
|
+
...requestOptions,
|
|
2176
|
+
signal: streamSignal,
|
|
2177
|
+
});
|
|
2178
|
+
let lastPublished = "";
|
|
2179
|
+
|
|
2180
|
+
// Exactly one consumer receives the terminal message. Partial text is
|
|
2181
|
+
// fanned out through coalescing; after UI cancellation the callback is
|
|
2182
|
+
// gone, but the bounded drain can still retain terminal usage.
|
|
2183
|
+
response = await consumeAssistantStream(stream, streamSignal, () => hardDeadlineController.abort(), (partial) => {
|
|
2184
|
+
// `partial` is cumulative. Appending delta plus text_end.content would
|
|
2185
|
+
// duplicate the completed block on providers that emit both.
|
|
2186
|
+
const partialText = extractAssistantText(partial);
|
|
2187
|
+
const suggestion = parsePartialPromptSuggestion(request.draft, partialText, request.maxSuggestionChars);
|
|
2188
|
+
if (!suggestion || suggestion === lastPublished) return;
|
|
2189
|
+
if (lastPublished && !suggestion.startsWith(lastPublished)) return;
|
|
2190
|
+
lastPublished = suggestion;
|
|
2191
|
+
publish(suggestion);
|
|
2192
|
+
});
|
|
2193
|
+
} else {
|
|
2194
|
+
response = await shared.completeSimple(request.model, context, requestOptions);
|
|
2195
|
+
}
|
|
2196
|
+
} catch (error) {
|
|
2197
|
+
stats.failedRequests += 1;
|
|
2198
|
+
throw error;
|
|
2199
|
+
} finally {
|
|
2200
|
+
recordProviderLatency(stats, shared.now() - providerStartedAt);
|
|
2201
|
+
}
|
|
2202
|
+
|
|
2203
|
+
// Tokens spent on a failed or aborted response are still spent, so usage is
|
|
2204
|
+
// recorded before the stop-reason check rejects the request.
|
|
2205
|
+
recordProviderUsage(stats, response.usage);
|
|
2206
|
+
|
|
2207
|
+
const contentTypes = response.content.map((block) => block.type).join(", ") || "(none)";
|
|
2208
|
+
const text = extractAssistantText(response);
|
|
2209
|
+
|
|
2210
|
+
const responseError = response.errorMessage?.trim();
|
|
2211
|
+
const rawResponse = text || responseError || `[types=${contentTypes}; stopReason=${response.stopReason}]`;
|
|
2212
|
+
|
|
2213
|
+
if (response.stopReason === "error" || response.stopReason === "aborted") {
|
|
2214
|
+
stats.failedRequests += 1;
|
|
2215
|
+
throw new Error(responseError || `Provider returned stopReason=${response.stopReason}`);
|
|
2216
|
+
}
|
|
2217
|
+
if (signal.aborted) {
|
|
2218
|
+
stats.failedRequests += 1;
|
|
2219
|
+
throw new Error("Request was aborted");
|
|
2220
|
+
}
|
|
2221
|
+
|
|
2222
|
+
const normalized = normalizePromptSuggestions(
|
|
2223
|
+
request.draft,
|
|
2224
|
+
text,
|
|
2225
|
+
request.maxSuggestionChars,
|
|
2226
|
+
request.maxAlternatives,
|
|
2227
|
+
);
|
|
2228
|
+
|
|
2229
|
+
const debugState =
|
|
2230
|
+
normalized.length === 0
|
|
2231
|
+
? text || `No text blocks returned (types: ${contentTypes}; stopReason: ${response.stopReason})`
|
|
2232
|
+
: `${normalized.length} suggestion(s) ready`;
|
|
2233
|
+
|
|
2234
|
+
return storeCachedRequest(shared, request.cacheKey, {
|
|
2235
|
+
draft: request.draft,
|
|
2236
|
+
prefixContextKey: request.prefixContextKey,
|
|
2237
|
+
suggestions: normalized,
|
|
2238
|
+
rawResponse,
|
|
2239
|
+
debugState,
|
|
2240
|
+
});
|
|
2241
|
+
}
|
|
2242
|
+
|
|
1997
2243
|
function releaseEditorRuntime(shared: PromptAutocompleteSharedState): void {
|
|
1998
2244
|
shared.cancelActiveRequest?.();
|
|
1999
2245
|
shared.activationId += 1;
|
|
@@ -2110,6 +2356,7 @@ function mountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedStat
|
|
|
2110
2356
|
|
|
2111
2357
|
const installedFactory: EditorFactory = (tui, theme, keybindings) => {
|
|
2112
2358
|
const editor = new PromptAutocompleteEditor(tui, theme, keybindings, shared, activationId);
|
|
2359
|
+
shared.keybindings = keybindings;
|
|
2113
2360
|
shared.refreshEditor = (options) => {
|
|
2114
2361
|
if (activationId !== shared.activationId) return;
|
|
2115
2362
|
editor.refreshFromExternalChange(options);
|
|
@@ -2176,6 +2423,7 @@ function unmountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedSt
|
|
|
2176
2423
|
|
|
2177
2424
|
function resetSharedForSession(pi: ExtensionAPI, shared: PromptAutocompleteSharedState): void {
|
|
2178
2425
|
shared.cancelActiveRequest?.();
|
|
2426
|
+
cancelNextPrompt(shared);
|
|
2179
2427
|
shared.cancelActiveRequest = undefined;
|
|
2180
2428
|
shared.cancelScheduledRequest = undefined;
|
|
2181
2429
|
// Budget accounting is physical-session scoped: a new session starts fresh.
|
|
@@ -2229,15 +2477,59 @@ function buildCurrentRequestSnapshot(
|
|
|
2229
2477
|
shared: PromptAutocompleteSharedState,
|
|
2230
2478
|
draft: string,
|
|
2231
2479
|
conversationId: string,
|
|
2480
|
+
maxAlternatives = shared.config.maxAlternatives,
|
|
2232
2481
|
): PromptAutocompleteRequestSnapshot {
|
|
2233
2482
|
return buildPromptAutocompleteRequestSnapshot({
|
|
2234
2483
|
draft,
|
|
2235
2484
|
branch: readAutocompleteContextEntries(shared, conversationId),
|
|
2236
|
-
maxAlternatives
|
|
2485
|
+
maxAlternatives,
|
|
2237
2486
|
maxSuggestionChars: shared.config.maxSuggestionChars,
|
|
2238
2487
|
});
|
|
2239
2488
|
}
|
|
2240
2489
|
|
|
2490
|
+
/**
|
|
2491
|
+
* A provider request for `draft` against the current conversation, or
|
|
2492
|
+
* undefined when no usable model resolves. Used by the editor and by the
|
|
2493
|
+
* next-prompt path, which asks for one alternative only.
|
|
2494
|
+
*/
|
|
2495
|
+
function buildSuggestionRequest(
|
|
2496
|
+
shared: PromptAutocompleteSharedState,
|
|
2497
|
+
draft: string,
|
|
2498
|
+
activationId: number,
|
|
2499
|
+
maxAlternatives = shared.config.maxAlternatives,
|
|
2500
|
+
): SuggestionRequest | undefined {
|
|
2501
|
+
const model = resolveSuggestionModel(shared);
|
|
2502
|
+
if (!model) return undefined;
|
|
2503
|
+
|
|
2504
|
+
const conversationId = resolveCurrentConversationId(shared);
|
|
2505
|
+
shared.lastConversationId = conversationId;
|
|
2506
|
+
const snapshot = buildCurrentRequestSnapshot(shared, draft, conversationId, maxAlternatives);
|
|
2507
|
+
const modelLabel = formatModelLabel(model);
|
|
2508
|
+
|
|
2509
|
+
const prefixContextIdentity = {
|
|
2510
|
+
conversationId,
|
|
2511
|
+
modelLabel,
|
|
2512
|
+
maxAlternatives: snapshot.maxAlternatives,
|
|
2513
|
+
maxSuggestionChars: snapshot.maxSuggestionChars,
|
|
2514
|
+
latestAssistantContext: snapshot.latestAssistantContext,
|
|
2515
|
+
latestUserContext: snapshot.latestUserContext,
|
|
2516
|
+
recentContext: snapshot.recentContext,
|
|
2517
|
+
compactionSummaryContext: snapshot.compactionSummaryContext,
|
|
2518
|
+
};
|
|
2519
|
+
|
|
2520
|
+
return {
|
|
2521
|
+
...snapshot,
|
|
2522
|
+
activationId,
|
|
2523
|
+
conversationId,
|
|
2524
|
+
model,
|
|
2525
|
+
modelLabel,
|
|
2526
|
+
cacheKey: buildPromptAutocompleteCacheKey({ ...prefixContextIdentity, draft: snapshot.draft }),
|
|
2527
|
+
prefixContextKey: buildPromptAutocompletePrefixContextKey(prefixContextIdentity),
|
|
2528
|
+
dismissalContext: buildDismissalContext(shared, conversationId),
|
|
2529
|
+
useStreaming: shared.config.streamResponses && !!shared.streamSimple,
|
|
2530
|
+
};
|
|
2531
|
+
}
|
|
2532
|
+
|
|
2241
2533
|
/**
|
|
2242
2534
|
* Conversation entries autocomplete may draw context from.
|
|
2243
2535
|
*
|
|
@@ -2275,6 +2567,28 @@ function resolveCurrentConversationId(shared: PromptAutocompleteSharedState): st
|
|
|
2275
2567
|
return resolveAutocompleteConversationId(branch, leafId || shared.physicalSessionId);
|
|
2276
2568
|
}
|
|
2277
2569
|
|
|
2570
|
+
/**
|
|
2571
|
+
* Dismissal context for the given conversation.
|
|
2572
|
+
*
|
|
2573
|
+
* The model part is what is requested, not what resolves: a dedicated model's
|
|
2574
|
+
* reference, or the active session model in `active` mode. It therefore changes
|
|
2575
|
+
* on a switch to a model without auth, which no request could be built for.
|
|
2576
|
+
*/
|
|
2577
|
+
function buildDismissalContext(shared: PromptAutocompleteSharedState, conversationId: string): string {
|
|
2578
|
+
const selection = shared.config.modelSelection;
|
|
2579
|
+
const requestedModel = selection.kind === "dedicated"
|
|
2580
|
+
? `${selection.ref.provider}/${selection.ref.id}`
|
|
2581
|
+
: selection.kind === "invalid"
|
|
2582
|
+
? selection.raw
|
|
2583
|
+
: formatModelLabel(shared.currentModel);
|
|
2584
|
+
return buildPromptAutocompleteDismissalContext({
|
|
2585
|
+
conversationId,
|
|
2586
|
+
requestedModel,
|
|
2587
|
+
maxAlternatives: shared.config.maxAlternatives,
|
|
2588
|
+
maxSuggestionChars: shared.config.maxSuggestionChars,
|
|
2589
|
+
});
|
|
2590
|
+
}
|
|
2591
|
+
|
|
2278
2592
|
function rememberAgentSettledSupport(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): void {
|
|
2279
2593
|
if (shared.hostEmitsAgentSettled !== undefined) return;
|
|
2280
2594
|
shared.hostEmitsAgentSettled = typeof ctx.isIdle === "function";
|
|
@@ -2286,6 +2600,46 @@ function settleAgentTurn(shared: PromptAutocompleteSharedState, details: string)
|
|
|
2286
2600
|
refreshEditorImmediately(shared, "ready", details);
|
|
2287
2601
|
}
|
|
2288
2602
|
|
|
2603
|
+
/**
|
|
2604
|
+
* RPC hosts started with `--prompt-autocomplete-next-prompt`: after a settled
|
|
2605
|
+
* turn, predict the user's next prompt and hand it over with `setEditorText`,
|
|
2606
|
+
* which T3 Code shows as its suggested next prompt. Budget, model selection,
|
|
2607
|
+
* and stats apply as in the editor. A new turn or session aborts the request,
|
|
2608
|
+
* and a result is dropped when the agent is busy again or the conversation
|
|
2609
|
+
* moved to another branch while it was pending.
|
|
2610
|
+
*/
|
|
2611
|
+
async function suggestNextPrompt(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): Promise<void> {
|
|
2612
|
+
cancelNextPrompt(shared);
|
|
2613
|
+
if (!shared.config.nextPrompt || ctx.mode !== "rpc") return;
|
|
2614
|
+
const request = buildSuggestionRequest(shared, "", shared.activationId, 1);
|
|
2615
|
+
if (!request) return;
|
|
2616
|
+
const controller = new AbortController();
|
|
2617
|
+
shared.nextPromptAbort = controller;
|
|
2618
|
+
try {
|
|
2619
|
+
const entry = await fetchSuggestionUncached(
|
|
2620
|
+
shared,
|
|
2621
|
+
{ ...request, useStreaming: false },
|
|
2622
|
+
controller.signal,
|
|
2623
|
+
() => undefined,
|
|
2624
|
+
);
|
|
2625
|
+
const suggestion = entry.suggestions[0];
|
|
2626
|
+
if (!suggestion || controller.signal.aborted) return;
|
|
2627
|
+
// Pi marks a new run busy before `agent_start` reaches this extension.
|
|
2628
|
+
if (typeof ctx.isIdle === "function" && !ctx.isIdle()) return;
|
|
2629
|
+
if (resolveCurrentConversationId(shared) !== request.conversationId) return;
|
|
2630
|
+
ctx.ui.setEditorText(suggestion);
|
|
2631
|
+
} catch (error) {
|
|
2632
|
+
if (!controller.signal.aborted) shared.lastError = error instanceof Error ? error.message : String(error);
|
|
2633
|
+
} finally {
|
|
2634
|
+
if (shared.nextPromptAbort === controller) shared.nextPromptAbort = undefined;
|
|
2635
|
+
}
|
|
2636
|
+
}
|
|
2637
|
+
|
|
2638
|
+
function cancelNextPrompt(shared: PromptAutocompleteSharedState): void {
|
|
2639
|
+
shared.nextPromptAbort?.abort();
|
|
2640
|
+
shared.nextPromptAbort = undefined;
|
|
2641
|
+
}
|
|
2642
|
+
|
|
2289
2643
|
function refreshEditorImmediately(shared: PromptAutocompleteSharedState, state: string, details: string): void {
|
|
2290
2644
|
updateDebugState(shared, state, details);
|
|
2291
2645
|
shared.refreshEditor?.({ clearExisting: true, immediate: true });
|
|
@@ -2482,11 +2836,11 @@ function persistSettingsDecision(
|
|
|
2482
2836
|
shared: PromptAutocompleteSharedState,
|
|
2483
2837
|
patch: Partial<PromptAutocompletePersistedSettings>,
|
|
2484
2838
|
): boolean {
|
|
2485
|
-
shared.persistedSettings =
|
|
2839
|
+
shared.persistedSettings = applyPromptAutocompleteSettingsPatch(shared.persistedSettings, patch);
|
|
2486
2840
|
const store = shared.settingsStore;
|
|
2487
2841
|
if (!store) return false;
|
|
2488
2842
|
try {
|
|
2489
|
-
store.
|
|
2843
|
+
store.update(patch);
|
|
2490
2844
|
return true;
|
|
2491
2845
|
} catch (error) {
|
|
2492
2846
|
const reason = error instanceof Error ? error.message : String(error);
|
|
@@ -2766,8 +3120,74 @@ const SET_KEY_RUNNERS: {
|
|
|
2766
3120
|
}
|
|
2767
3121
|
setModelSetting(ctx, shared, value);
|
|
2768
3122
|
},
|
|
3123
|
+
key: (ctx, shared, value) => setActionKeys(ctx, shared, value),
|
|
2769
3124
|
};
|
|
2770
3125
|
|
|
3126
|
+
const SET_KEY_USAGE = `Usage: /prompt-autocomplete set key <${
|
|
3127
|
+
PROMPT_AUTOCOMPLETE_CONFIGURABLE_KEY_ACTIONS.map((action) => PROMPT_AUTOCOMPLETE_KEY_ACTIONS[action].command).join("|")
|
|
3128
|
+
}> <key...|default|none>`;
|
|
3129
|
+
|
|
3130
|
+
/**
|
|
3131
|
+
* `set key <action> <key...|default|none>`: change one action's keys, save
|
|
3132
|
+
* them, and apply them to the editor at once.
|
|
3133
|
+
*
|
|
3134
|
+
* Keys are whitespace-separated, because `,` is a key. A key that another
|
|
3135
|
+
* Prompt Autocomplete action has must be freed there first, so one keypress
|
|
3136
|
+
* never means two actions. A key Pi's keymap binds is accepted with a note:
|
|
3137
|
+
* the editor leaves it to Pi.
|
|
3138
|
+
*/
|
|
3139
|
+
function setActionKeys(ctx: ExtensionContext, shared: PromptAutocompleteSharedState, value: string): void {
|
|
3140
|
+
const [command = "", ...tokens] = value.split(/\s+/).filter((token) => token.length > 0);
|
|
3141
|
+
const action = findConfigurableKeyAction(command.toLowerCase());
|
|
3142
|
+
if (!action || tokens.length === 0) {
|
|
3143
|
+
ctx.ui.notify(SET_KEY_USAGE, "warning");
|
|
3144
|
+
return;
|
|
3145
|
+
}
|
|
3146
|
+
const choice = tokens.length === 1 ? tokens[0]!.toLowerCase() : undefined;
|
|
3147
|
+
let keys: KeyId[] | undefined;
|
|
3148
|
+
if (choice === "none") {
|
|
3149
|
+
keys = [];
|
|
3150
|
+
} else if (choice !== "default") {
|
|
3151
|
+
keys = [];
|
|
3152
|
+
for (const token of tokens) {
|
|
3153
|
+
const key = parsePromptAutocompleteKeyId(token);
|
|
3154
|
+
if (!key) {
|
|
3155
|
+
ctx.ui.notify(`${truncateDebug(token, 40)} is not a key. ${SET_KEY_USAGE}`, "warning");
|
|
3156
|
+
return;
|
|
3157
|
+
}
|
|
3158
|
+
const unusable = describeUnusablePromptAutocompleteKey(key);
|
|
3159
|
+
if (unusable) {
|
|
3160
|
+
ctx.ui.notify(`Prompt autocomplete cannot use this key: ${unusable}.`, "warning");
|
|
3161
|
+
return;
|
|
3162
|
+
}
|
|
3163
|
+
if (!keys.some((existing) => canonicalKeyId(existing) === canonicalKeyId(key))) keys.push(key);
|
|
3164
|
+
}
|
|
3165
|
+
}
|
|
3166
|
+
|
|
3167
|
+
for (const key of keys ?? PROMPT_AUTOCOMPLETE_KEY_ACTIONS[action].keys) {
|
|
3168
|
+
const owner = listPromptAutocompleteKeys(shared.keymap).find(
|
|
3169
|
+
(entry) => entry.command !== command.toLowerCase()
|
|
3170
|
+
&& entry.keys.some((owned) => canonicalKeyId(owned) === canonicalKeyId(key)),
|
|
3171
|
+
);
|
|
3172
|
+
if (owner) {
|
|
3173
|
+
ctx.ui.notify(`${key} is already ${owner.command}; change that action first.`, "warning");
|
|
3174
|
+
return;
|
|
3175
|
+
}
|
|
3176
|
+
}
|
|
3177
|
+
|
|
3178
|
+
const persisted = persistSettingsDecision(ctx, shared, { keys: { [action]: keys } });
|
|
3179
|
+
shared.keymap = resolvePromptAutocompleteKeymap(shared.persistedSettings.keys);
|
|
3180
|
+
const effective = shared.keymap.keys[action];
|
|
3181
|
+
const usedByPi = listKeysUsedByPi(shared.keybindings, effective) ?? [];
|
|
3182
|
+
ctx.ui.notify(
|
|
3183
|
+
`Prompt autocomplete ${command.toLowerCase()} keys set to ${effective.join(" ") || "none"}`
|
|
3184
|
+
+ `${keys === undefined ? " (default)" : ""}`
|
|
3185
|
+
+ `${persisted ? " (saved for future sessions)" : " (session only — could not save for future sessions)"}`
|
|
3186
|
+
+ `${usedByPi.length > 0 ? `. Pi's keymap also binds ${usedByPi.join(", ")}, so Pi keeps those keys.` : ""}`,
|
|
3187
|
+
usedByPi.length > 0 ? "warning" : "info",
|
|
3188
|
+
);
|
|
3189
|
+
}
|
|
3190
|
+
|
|
2771
3191
|
function setBoundedSetKey(
|
|
2772
3192
|
ctx: ExtensionContext,
|
|
2773
3193
|
shared: PromptAutocompleteSharedState,
|
|
@@ -2839,10 +3259,7 @@ function notifyPromptAutocompleteEnabled(
|
|
|
2839
3259
|
shared: PromptAutocompleteSharedState,
|
|
2840
3260
|
options: { includeModel: boolean },
|
|
2841
3261
|
): void {
|
|
2842
|
-
const keyHint =
|
|
2843
|
-
`Tab accepts all, ${formatPrimaryKey(WORD_ACCEPT_KEYS)} accepts one word, ` +
|
|
2844
|
-
`${formatPrimaryKey(CYCLE_PREV_KEYS)}/${formatPrimaryKey(CYCLE_NEXT_KEYS)} cycle alternatives, ` +
|
|
2845
|
-
`${formatPrimaryKey(CYCLE_NEXT_KEYS)} also forces a one-shot suggestion when none is shown (even while the agent works).`;
|
|
3262
|
+
const keyHint = formatKeyHints(shared.keymap).notice;
|
|
2846
3263
|
const resolution = resolveSuggestionModelResolution(shared);
|
|
2847
3264
|
const resolvedModel = resolution.model;
|
|
2848
3265
|
const privacyNotice = PRIVACY_NOTICE;
|
|
@@ -2889,7 +3306,7 @@ function hasNotificationChannel(ctx: ExtensionContext): boolean {
|
|
|
2889
3306
|
* cannot issue requests there, instead of staying silently inert.
|
|
2890
3307
|
*/
|
|
2891
3308
|
function notifyEnabledWithoutEditorOnce(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): void {
|
|
2892
|
-
if (!shared.enabled || shared.processState.nonInteractiveNoticeShown) return;
|
|
3309
|
+
if (!shared.enabled || shared.config.nextPrompt || shared.processState.nonInteractiveNoticeShown) return;
|
|
2893
3310
|
if (hostOwnsInteractiveEditor(ctx, shared) || !hasNotificationChannel(ctx)) return;
|
|
2894
3311
|
shared.processState.nonInteractiveNoticeShown = true;
|
|
2895
3312
|
ctx.ui.notify(
|
|
@@ -2974,6 +3391,7 @@ const COMMAND_RUNNERS: { [Name in PromptAutocompleteCommandName]: CommandRunner
|
|
|
2974
3391
|
"min-chars": (ctx, shared, { firstArgument }) => setMinPromptChars(ctx, shared, firstArgument),
|
|
2975
3392
|
budget: (ctx, shared, { firstArgument }) => setBudgetLimit(ctx, shared, firstArgument),
|
|
2976
3393
|
set: (ctx, shared, { rest }) => handleSetCommand(ctx, shared, rest),
|
|
3394
|
+
keys: (ctx, shared) => ctx.ui.notify(formatKeymap(shared), "info"),
|
|
2977
3395
|
stream: (ctx, shared, { firstArgument }) => setStreamResponses(ctx, shared, firstArgument),
|
|
2978
3396
|
"while-streaming": (ctx, shared, { firstArgument }) => setWhileStreaming(ctx, shared, firstArgument),
|
|
2979
3397
|
"debug-on": (ctx, shared) => {
|
|
@@ -3027,7 +3445,8 @@ export function createPromptAutocompleteExtension(
|
|
|
3027
3445
|
dependencies.streamSimple
|
|
3028
3446
|
?? (dependencies.completeSimple || !hostStreaming ? undefined : routedStreamSimple);
|
|
3029
3447
|
|
|
3030
|
-
const settingsStore = dependencies.settingsStore
|
|
3448
|
+
const settingsStore = dependencies.settingsStore
|
|
3449
|
+
?? createPromptAutocompleteFileSettingsStore(resolvePromptAutocompleteSettingsPath());
|
|
3031
3450
|
let persistedSettings: PromptAutocompletePersistedSettings;
|
|
3032
3451
|
try {
|
|
3033
3452
|
persistedSettings = settingsStore.load();
|
|
@@ -3088,6 +3507,11 @@ export function createPromptAutocompleteExtension(
|
|
|
3088
3507
|
type: "string",
|
|
3089
3508
|
default: DEFAULT_BUDGET_REQUESTS_FLAG,
|
|
3090
3509
|
});
|
|
3510
|
+
pi.registerFlag("prompt-autocomplete-next-prompt", {
|
|
3511
|
+
description: "RPC mode: suggest the next prompt after each turn through setEditorText (T3 Code)",
|
|
3512
|
+
type: "boolean",
|
|
3513
|
+
default: false,
|
|
3514
|
+
});
|
|
3091
3515
|
|
|
3092
3516
|
const shared: PromptAutocompleteSharedState = {
|
|
3093
3517
|
enabled: false,
|
|
@@ -3099,6 +3523,7 @@ export function createPromptAutocompleteExtension(
|
|
|
3099
3523
|
runtimeOverrides: {},
|
|
3100
3524
|
persistedSettings,
|
|
3101
3525
|
settingsStore,
|
|
3526
|
+
keymap: resolvePromptAutocompleteKeymap(persistedSettings.keys),
|
|
3102
3527
|
enabledFlagValue: false,
|
|
3103
3528
|
budgetUsed: 0,
|
|
3104
3529
|
budgetBlockNotices: new Set(),
|
|
@@ -3134,6 +3559,7 @@ export function createPromptAutocompleteExtension(
|
|
|
3134
3559
|
// Teardown, not a user decision: leave runtimeOverrides untouched.
|
|
3135
3560
|
shared.enabled = false;
|
|
3136
3561
|
shared.cancelActiveRequest?.();
|
|
3562
|
+
cancelNextPrompt(shared);
|
|
3137
3563
|
shared.requestCache.clear();
|
|
3138
3564
|
shared.prefixReuseCache.clear();
|
|
3139
3565
|
cancelAllCoalescedRequests(shared.inFlightRequests);
|
|
@@ -3158,6 +3584,7 @@ export function createPromptAutocompleteExtension(
|
|
|
3158
3584
|
|
|
3159
3585
|
pi.on("agent_start", async () => {
|
|
3160
3586
|
shared.agentStreaming = true;
|
|
3587
|
+
cancelNextPrompt(shared);
|
|
3161
3588
|
if (!shared.enabled || shared.config.allowWhileStreaming) return;
|
|
3162
3589
|
refreshEditorImmediately(shared, "waiting", "Main agent is still working");
|
|
3163
3590
|
});
|
|
@@ -3168,8 +3595,10 @@ export function createPromptAutocompleteExtension(
|
|
|
3168
3595
|
settleAgentTurn(shared, "Agent finished; autocomplete can request suggestions again");
|
|
3169
3596
|
});
|
|
3170
3597
|
|
|
3171
|
-
pi.on("agent_settled", async () => {
|
|
3598
|
+
pi.on("agent_settled", async (_event, ctx) => {
|
|
3172
3599
|
settleAgentTurn(shared, "Agent settled; autocomplete can request suggestions again");
|
|
3600
|
+
// Not awaited: Pi waits for handlers, and the turn is already over.
|
|
3601
|
+
void suggestNextPrompt(ctx, shared);
|
|
3173
3602
|
});
|
|
3174
3603
|
|
|
3175
3604
|
pi.registerCommand("prompt-autocomplete", {
|