@kliebhan/pi-prompt-autocomplete 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +43 -8
  3. package/core.ts +433 -5
  4. package/index.ts +753 -245
  5. package/package.json +2 -2
package/index.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
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 { matchesKey, truncateToWidth, type EditorTheme, type KeyId, type TUI, visibleWidth } from "@earendil-works/pi-tui";
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; `save` may throw and the caller reports the failure.
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
- save(settings: PromptAutocompletePersistedSettings): void;
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
- function createFileSettingsStore(path: string): PromptAutocompleteSettingsStore {
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
- text = readFileSync(path, "utf8");
443
+ return parsePromptAutocompletePersistedSettings(readText());
400
444
  } catch {
401
445
  return {};
402
446
  }
403
- return parsePromptAutocompletePersistedSettings(text);
404
447
  },
405
- save(settings: PromptAutocompletePersistedSettings): void {
406
- // Atomic replace so a crash mid-write cannot corrupt the settings file.
407
- const tempPath = `${path}.tmp`;
408
- mkdirSync(dirname(path), { recursive: true });
409
- writeFileSync(tempPath, serializePromptAutocompletePersistedSettings(settings), "utf8");
410
- renameSync(tempPath, path);
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,14 @@ 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;
586
+ draftCompletionAbort?: AbortController;
509
587
  setStatusText?: (text: string | undefined) => void;
510
588
  setSpinnerActive?: (owner: string, active: boolean) => void;
511
589
  clearSpinner?: () => void;
@@ -519,9 +597,20 @@ interface SuggestionRequest extends PromptAutocompleteRequestSnapshot {
519
597
  modelLabel: string;
520
598
  cacheKey: string;
521
599
  prefixContextKey: string;
600
+ /** Context an Escape dismissal of this request's suggestions is bound to. */
601
+ dismissalContext: string;
522
602
  useStreaming: boolean;
523
603
  }
524
604
 
605
+ /** Key actions that act only on input Pi leaves free. */
606
+ type YieldingKeyAction = "cycle" | "manual" | "acceptWord" | "acceptLine";
607
+
608
+ interface EditorInputState {
609
+ text: string;
610
+ cursor: { line: number; col: number };
611
+ autocomplete: boolean;
612
+ }
613
+
525
614
  interface PendingSuggestionRequest {
526
615
  key: string;
527
616
  seq: number;
@@ -607,8 +696,103 @@ function matchesAnyKey(data: string, keys: readonly KeyId[]): boolean {
607
696
  return keys.some((key) => matchesKey(data, key));
608
697
  }
609
698
 
610
- function formatPrimaryKey(keys: readonly KeyId[]): string {
611
- return keys[0] ?? "";
699
+ /**
700
+ * What in Pi uses this exact input, if anything; a yielding Prompt Autocomplete
701
+ * key must then leave it to Pi.
702
+ *
703
+ * Every action in Pi's current keymap counts, in any scope; Pi's own matcher
704
+ * decides, so its byte and shifted-symbol equivalences apply, and remaps loaded
705
+ * by `/reload` count at once. Inputs that Pi's editor handles outside its keymap
706
+ * count as well: Shift+Space/Backspace/Delete, newline encodings, and printable
707
+ * text. A host whose keymap cannot be listed keeps the keys, as before 0.4.0.
708
+ */
709
+ function findPiUseOfInput(keybindings: KeybindingsManager, data: string): string | undefined {
710
+ if (typeof keybindings.getResolvedBindings === "function") {
711
+ for (const [action, keys] of Object.entries(keybindings.getResolvedBindings())) {
712
+ if (keys === undefined) continue;
713
+ if ((Array.isArray(keys) ? keys : [keys]).some((key) => matchesKey(data, key))) return action;
714
+ }
715
+ }
716
+ if (matchesKey(data, "shift+space") || matchesKey(data, "shift+backspace") || matchesKey(data, "shift+delete")) {
717
+ return "the editor";
718
+ }
719
+ // Newline encodings the pi-tui editor accepts besides `tui.input.newLine`.
720
+ if (data === "\n" || data === "\x1b\r" || data === "\x1b[13;2~") return "the editor";
721
+ if (data.length > 1 && (data.charCodeAt(0) === 10 || (data.includes("\x1b") && data.includes("\r")))) {
722
+ return "the editor";
723
+ }
724
+ return data.charCodeAt(0) >= 32 || decodeKittyPrintable(data) !== undefined ? "text input" : undefined;
725
+ }
726
+
727
+ /**
728
+ * Those of `keys` that Pi's keymap also binds, as `ctrl+space (app.model.select)`;
729
+ * undefined while the editor has not received Pi's keymap.
730
+ */
731
+ function listKeysUsedByPi(keybindings: KeybindingsManager | undefined, keys: readonly KeyId[]): string[] | undefined {
732
+ if (typeof keybindings?.getResolvedBindings !== "function") return undefined;
733
+ const resolved = keybindings.getResolvedBindings();
734
+ return keys.flatMap((key) => {
735
+ const conflicts = findPiKeyConflicts(key, resolved);
736
+ return conflicts.length > 0 ? [`${key} (${conflicts.join(", ")})`] : [];
737
+ });
738
+ }
739
+
740
+ function configurableKeys(keymap: PromptAutocompleteKeymap): KeyId[] {
741
+ return PROMPT_AUTOCOMPLETE_CONFIGURABLE_KEY_ACTIONS.flatMap((action) => keymap.keys[action]);
742
+ }
743
+
744
+ function formatKeysUsedByPi(shared: PromptAutocompleteSharedState): string | undefined {
745
+ const usedByPi = listKeysUsedByPi(shared.keybindings, configurableKeys(shared.keymap));
746
+ return usedByPi && usedByPi.length > 0 ? `keys-used-by-pi=${usedByPi.join(", ")}` : undefined;
747
+ }
748
+
749
+ /** Key hints for `status` and the enable notice; each names an action's first key. */
750
+ function formatKeyHints(keymap: PromptAutocompleteKeymap): { status: string; notice: string } {
751
+ const [word, line, next, prev] = [
752
+ keymap.keys.acceptWord[0],
753
+ keymap.keys.acceptLine[0],
754
+ keymap.keys.cycleNext[0],
755
+ keymap.keys.cyclePrev[0],
756
+ ];
757
+ const cycle = [prev, next].filter((key) => key !== undefined).join("/");
758
+ const status = [
759
+ "tab accept",
760
+ word && `${word} word`,
761
+ line && `${line} line`,
762
+ cycle && `${cycle} cycle`,
763
+ next && `${next} force one-shot`,
764
+ ];
765
+ const notice = [
766
+ "Tab accepts all",
767
+ word && `${word} accepts one word`,
768
+ line && `${line} accepts one line`,
769
+ cycle && `${cycle} cycle alternatives`,
770
+ next && `${next} also forces a one-shot suggestion when none is shown (even while the agent works)`,
771
+ ];
772
+ return {
773
+ status: status.filter((part) => !!part).join(" | "),
774
+ notice: `${notice.filter((part) => !!part).join(", ")}.`,
775
+ };
776
+ }
777
+
778
+ /** `/prompt-autocomplete keys`: every action with its keys and where they come from. */
779
+ function formatKeymap(shared: PromptAutocompleteSharedState): string {
780
+ const { keymap } = shared;
781
+ const actions = listPromptAutocompleteKeys(keymap).map(
782
+ ({ command, keys, source }) => `${command} ${keys.join(" ") || "none"} (${source})`,
783
+ );
784
+ const usedByPi = listKeysUsedByPi(shared.keybindings, configurableKeys(keymap));
785
+ return [
786
+ `Prompt autocomplete keys: ${actions.join(" | ")}`,
787
+ keymap.ignored.length > 0 ? `ignored: ${keymap.ignored.join(", ")}` : undefined,
788
+ usedByPi === undefined
789
+ ? "Pi's keymap is checked once the editor is active"
790
+ : usedByPi.length > 0
791
+ ? `used by Pi, so Pi keeps them: ${usedByPi.join(", ")}`
792
+ : undefined,
793
+ ]
794
+ .filter((part) => part !== undefined)
795
+ .join(" | ");
612
796
  }
613
797
 
614
798
  interface SuggestionModelResolution {
@@ -728,6 +912,7 @@ function parseConfig(pi: ExtensionAPI): PromptAutocompleteConfig {
728
912
  ),
729
913
  modelSelection: parsePromptAutocompleteModelSelection(pi.getFlag("prompt-autocomplete-model")),
730
914
  budgetLimit: parsePromptAutocompleteBudgetFlag(pi.getFlag("prompt-autocomplete-max-requests")),
915
+ nextPrompt: pi.getFlag("prompt-autocomplete-next-prompt") === true,
731
916
  };
732
917
  }
733
918
 
@@ -926,9 +1111,8 @@ function formatStatus(shared: PromptAutocompleteSharedState, interactiveHost = t
926
1111
  `state=${shared.debugState || "idle"}`,
927
1112
  shared.lastError ? `error=${truncateDebug(shared.lastError, 90)}` : undefined,
928
1113
  shared.lastRawResponse ? `raw=${truncateDebug(shared.lastRawResponse, 90)}` : undefined,
929
- interactiveHost
930
- ? `keys=tab accept | ${formatPrimaryKey(WORD_ACCEPT_KEYS)} word | ${formatPrimaryKey(CYCLE_PREV_KEYS)}/${formatPrimaryKey(CYCLE_NEXT_KEYS)} cycle | ${formatPrimaryKey(CYCLE_NEXT_KEYS)} force one-shot`
931
- : undefined,
1114
+ interactiveHost ? `keys=${formatKeyHints(shared.keymap).status}` : undefined,
1115
+ interactiveHost ? formatKeysUsedByPi(shared) : undefined,
932
1116
  ]
933
1117
  .filter((value): value is string => !!value)
934
1118
  .join(" | ");
@@ -1140,7 +1324,10 @@ class PromptAutocompleteEditor extends CustomEditor {
1140
1324
  // shared spinner alive until every active owner has released it.
1141
1325
  private activeSpinnerOwner?: string;
1142
1326
  private suspendedUntil = 0;
1143
- private dismissedKey?: string;
1327
+ /** Escape dismissal: holds while the draft extends `draft` in `context`. */
1328
+ private dismissal?: { draft: string; context: string };
1329
+ /** Dismissal context under which the shown suggestions were produced. */
1330
+ private suggestionsContext?: string;
1144
1331
 
1145
1332
  constructor(
1146
1333
  tui: TUI,
@@ -1167,23 +1354,33 @@ class PromptAutocompleteEditor extends CustomEditor {
1167
1354
 
1168
1355
  override handleInput(data: string): void {
1169
1356
  if (this.canDismissInlineSuggestion(data)) {
1170
- this.dismissedKey = this.buildRequest()?.cacheKey;
1171
- this.clearInlineSuggestion("dismissed", "Suggestion dismissed for current draft");
1172
- return;
1173
- }
1174
-
1175
- if (this.canCycleSuggestions(data)) {
1176
- this.cycleSuggestions(matchesAnyKey(data, CYCLE_NEXT_KEYS) ? 1 : -1);
1177
- return;
1178
- }
1179
-
1180
- if (this.canTriggerManualSuggestion(data)) {
1181
- this.triggerManualSuggestion();
1357
+ // Bound to the context the visible suggestion came from, not a freshly
1358
+ // built request, which a model or auth failure could not provide.
1359
+ this.dismissal = {
1360
+ draft: this.getText(),
1361
+ context: this.suggestionsContext
1362
+ ?? buildDismissalContext(this.shared, resolveCurrentConversationId(this.shared)),
1363
+ };
1364
+ this.clearInlineSuggestion("dismissed", "Suggestion dismissed while this draft continues");
1182
1365
  return;
1183
1366
  }
1184
1367
 
1185
- if (this.canAcceptInlineSuggestionByWord(data)) {
1186
- this.acceptInlineSuggestionByWord();
1368
+ const action = this.matchYieldingKeyAction(data);
1369
+ const piUse = action ? findPiUseOfInput(this.appKeybindings, data) : undefined;
1370
+ if (piUse) {
1371
+ // Shown until the refresh after Pi's handling reports something newer.
1372
+ updateDebugState(this.shared, "yielded", `Key left to Pi: ${piUse}`);
1373
+ } else if (action) {
1374
+ // Pi's order: another extension's shortcut on the same key comes first.
1375
+ const before = this.captureInputState();
1376
+ if (this.onExtensionShortcut?.(data)) {
1377
+ this.refreshAfterInput(before);
1378
+ return;
1379
+ }
1380
+ // For input Pi leaves free, Pi's editor only cancels a pending character
1381
+ // jump, exactly as without this extension.
1382
+ super.handleInput(data);
1383
+ this.runYieldingKeyAction(action, data);
1187
1384
  return;
1188
1385
  }
1189
1386
 
@@ -1194,19 +1391,42 @@ class PromptAutocompleteEditor extends CustomEditor {
1194
1391
 
1195
1392
  this.clearInlineSuggestionForUserIntent(data);
1196
1393
 
1197
- const beforeText = this.getText();
1198
- const beforeCursor = this.getCursor();
1199
- const beforeAutocomplete = this.isShowingAutocomplete();
1200
-
1394
+ const before = this.captureInputState();
1201
1395
  super.handleInput(data);
1396
+ this.refreshAfterInput(before);
1397
+ }
1202
1398
 
1203
- const afterText = this.getText();
1204
- const afterCursor = this.getCursor();
1205
- const afterAutocomplete = this.isShowingAutocomplete();
1399
+ /** The yielding key action this input would trigger right now, if any. */
1400
+ private matchYieldingKeyAction(data: string): YieldingKeyAction | undefined {
1401
+ if (this.canCycleSuggestions(data)) return "cycle";
1402
+ if (this.canTriggerManualSuggestion(data)) return "manual";
1403
+ if (this.canAcceptInlineSuggestionPart(data, this.shared.keymap.keys.acceptWord)) return "acceptWord";
1404
+ if (this.canAcceptInlineSuggestionPart(data, this.shared.keymap.keys.acceptLine)) return "acceptLine";
1405
+ return undefined;
1406
+ }
1206
1407
 
1207
- const textChanged = beforeText !== afterText;
1208
- const cursorChanged = beforeCursor.line !== afterCursor.line || beforeCursor.col !== afterCursor.col;
1209
- const autocompleteChanged = beforeAutocomplete !== afterAutocomplete;
1408
+ private runYieldingKeyAction(action: YieldingKeyAction, data: string): void {
1409
+ if (action === "cycle") {
1410
+ this.cycleSuggestions(matchesAnyKey(data, this.shared.keymap.keys.cycleNext) ? 1 : -1);
1411
+ } else if (action === "manual") {
1412
+ this.triggerManualSuggestion();
1413
+ } else if (action === "acceptWord") {
1414
+ this.acceptInlineSuggestionByWord();
1415
+ } else {
1416
+ this.acceptInlineSuggestionByLine();
1417
+ }
1418
+ }
1419
+
1420
+ private captureInputState(): EditorInputState {
1421
+ return { text: this.getText(), cursor: this.getCursor(), autocomplete: this.isShowingAutocomplete() };
1422
+ }
1423
+
1424
+ /** Refresh suggestions after input that the editor or Pi handled. */
1425
+ private refreshAfterInput(before: EditorInputState): void {
1426
+ const after = this.captureInputState();
1427
+ const textChanged = before.text !== after.text;
1428
+ const cursorChanged = before.cursor.line !== after.cursor.line || before.cursor.col !== after.cursor.col;
1429
+ const autocompleteChanged = before.autocomplete !== after.autocomplete;
1210
1430
 
1211
1431
  if (textChanged || cursorChanged || autocompleteChanged) {
1212
1432
  this.refreshSuggestion({ clearExisting: true });
@@ -1323,8 +1543,15 @@ class PromptAutocompleteEditor extends CustomEditor {
1323
1543
 
1324
1544
  private setSuggestions(
1325
1545
  nextSuggestions: string[],
1326
- options: { provisional?: boolean; origins?: string[]; preferredOrigin?: string } = {},
1546
+ options: {
1547
+ provisional?: boolean;
1548
+ origins?: string[];
1549
+ preferredOrigin?: string;
1550
+ /** Dismissal context of the request that produced the suggestions. */
1551
+ context?: string;
1552
+ } = {},
1327
1553
  ): void {
1554
+ this.suggestionsContext = nextSuggestions.length > 0 ? options.context : undefined;
1328
1555
  const provisional = options.provisional ?? false;
1329
1556
  const nextOrigins = options.origins?.length === nextSuggestions.length
1330
1557
  ? [...options.origins]
@@ -1377,13 +1604,33 @@ class PromptAutocompleteEditor extends CustomEditor {
1377
1604
  this.tui.requestRender();
1378
1605
  }
1379
1606
 
1607
+ /**
1608
+ * End a dismissal for good once the draft or its context moved on.
1609
+ *
1610
+ * Returns whether the dismissal still holds. Returning to the dismissed draft
1611
+ * or context later does not restore a dismissal that ended.
1612
+ */
1613
+ private reconcileDismissal(): boolean {
1614
+ if (!this.dismissal) return false;
1615
+ const context = buildDismissalContext(this.shared, resolveCurrentConversationId(this.shared));
1616
+ if (promptAutocompleteDismissalCovers(this.dismissal, this.getText(), context)) return true;
1617
+ this.dismissal = undefined;
1618
+ return false;
1619
+ }
1620
+
1621
+ /** Whether a response for `request` arrives into a standing dismissal. */
1622
+ private dismissalCovers(request: SuggestionRequest): boolean {
1623
+ return !!this.dismissal
1624
+ && promptAutocompleteDismissalCovers(this.dismissal, request.draft, request.dismissalContext);
1625
+ }
1626
+
1380
1627
  private cycleSuggestions(delta: 1 | -1): void {
1381
1628
  if (this.suggestions.length <= 1) return;
1382
1629
  const nextIndex = (this.suggestionIndex + delta + this.suggestions.length) % this.suggestions.length;
1383
1630
  if (nextIndex === this.suggestionIndex) return;
1384
1631
  this.suggestionIndex = nextIndex;
1385
1632
  this.shared.usageStats.suggestionsOffered += 1;
1386
- this.dismissedKey = undefined;
1633
+ this.dismissal = undefined;
1387
1634
  updateDebugState(this.shared, "cycled", `Now showing ${nextIndex + 1}/${this.suggestions.length}`);
1388
1635
  this.tui.requestRender();
1389
1636
  }
@@ -1394,13 +1641,13 @@ class PromptAutocompleteEditor extends CustomEditor {
1394
1641
  private canTriggerManualSuggestion(data: string): boolean {
1395
1642
  if (!this.shared.enabled || this.activationId !== this.shared.activationId) return false;
1396
1643
  if (this.isShowingAutocomplete()) return false;
1397
- return matchesAnyKey(data, CYCLE_NEXT_KEYS);
1644
+ return matchesAnyKey(data, this.shared.keymap.keys.cycleNext);
1398
1645
  }
1399
1646
 
1400
1647
  private triggerManualSuggestion(): void {
1401
1648
  // refreshSuggestion immediately sets its own debug state, so we only clear any
1402
1649
  // standing dismissal here and let the refresh report the real outcome.
1403
- this.dismissedKey = undefined;
1650
+ this.dismissal = undefined;
1404
1651
  this.refreshSuggestion({ clearExisting: true, immediate: true, manual: true });
1405
1652
  }
1406
1653
 
@@ -1412,14 +1659,15 @@ class PromptAutocompleteEditor extends CustomEditor {
1412
1659
  return this.shouldRenderInlineSuggestion() && !!this.getActiveSuggestion() && matchesKey(data, "tab");
1413
1660
  }
1414
1661
 
1415
- private canAcceptInlineSuggestionByWord(data: string): boolean {
1416
- return this.shouldRenderInlineSuggestion() && !!this.getActiveSuggestion() && matchesAnyKey(data, WORD_ACCEPT_KEYS);
1662
+ private canAcceptInlineSuggestionPart(data: string, keys: readonly KeyId[]): boolean {
1663
+ return this.shouldRenderInlineSuggestion() && !!this.getActiveSuggestion() && matchesAnyKey(data, keys);
1417
1664
  }
1418
1665
 
1419
1666
  private canCycleSuggestions(data: string): boolean {
1420
1667
  if (!this.shouldRenderInlineSuggestion()) return false;
1421
1668
  if (this.suggestions.length <= 1) return false;
1422
- return matchesAnyKey(data, CYCLE_NEXT_KEYS) || matchesAnyKey(data, CYCLE_PREV_KEYS);
1669
+ const { cycleNext, cyclePrev } = this.shared.keymap.keys;
1670
+ return matchesAnyKey(data, cycleNext) || matchesAnyKey(data, cyclePrev);
1423
1671
  }
1424
1672
 
1425
1673
  private clearInlineSuggestion(state: string, details: string): void {
@@ -1461,7 +1709,7 @@ class PromptAutocompleteEditor extends CustomEditor {
1461
1709
 
1462
1710
  const wasProvisional = this.suggestionsProvisional;
1463
1711
  this.shared.usageStats.fullAccepts += 1;
1464
- this.dismissedKey = undefined;
1712
+ this.dismissal = undefined;
1465
1713
  this.clearInlineSuggestion("accepted", wasProvisional ? "Accepted streamed partial suggestion" : "Accepted full suggestion");
1466
1714
  super.insertTextAtCursor(suggestion);
1467
1715
  // A provisional accept is explicit cancellation of the request. Starting a
@@ -1472,15 +1720,30 @@ class PromptAutocompleteEditor extends CustomEditor {
1472
1720
  private acceptInlineSuggestionByWord(): void {
1473
1721
  const suggestion = this.getActiveSuggestion();
1474
1722
  if (!suggestion) return;
1723
+ this.acceptInlineSuggestionPart(extractNextSuggestionChunk(suggestion) ?? suggestion, "accepted-word");
1724
+ }
1475
1725
 
1476
- const origin = this.getActiveSuggestionOrigin();
1477
- const chunk = extractNextSuggestionChunk(suggestion) ?? suggestion;
1478
- if (!chunk) return;
1726
+ /** Accept up to the first line break; a completed one-line suggestion is a full accept. */
1727
+ private acceptInlineSuggestionByLine(): void {
1728
+ const suggestion = this.getActiveSuggestion();
1729
+ if (!suggestion) return;
1730
+ const line = extractSuggestionLine(suggestion);
1731
+ // A streamed partial is not the whole suggestion, even without a line break.
1732
+ if (line === suggestion && !this.suggestionsProvisional) {
1733
+ this.acceptInlineSuggestion();
1734
+ return;
1735
+ }
1736
+ this.acceptInlineSuggestionPart(line, "accepted-line");
1737
+ }
1479
1738
 
1739
+ /** Insert the start of the active suggestion and keep offering the rest. */
1740
+ private acceptInlineSuggestionPart(chunk: string, state: string): void {
1741
+ if (!chunk) return;
1742
+ const origin = this.getActiveSuggestionOrigin();
1480
1743
  const wasProvisional = this.suggestionsProvisional;
1481
1744
  this.shared.usageStats.chunkAccepts += 1;
1482
- this.dismissedKey = undefined;
1483
- this.clearInlineSuggestion("accepted-word", `Accepted chunk: ${chunk}`);
1745
+ this.dismissal = undefined;
1746
+ this.clearInlineSuggestion(state, `Accepted chunk: ${chunk}`);
1484
1747
  super.insertTextAtCursor(chunk);
1485
1748
  if (!wasProvisional) this.refreshSuggestion({ preferredOrigin: origin });
1486
1749
  }
@@ -1534,6 +1797,9 @@ class PromptAutocompleteEditor extends CustomEditor {
1534
1797
 
1535
1798
  private refreshSuggestion(options: SuggestionRefreshOptions = {}): void {
1536
1799
  const preferredOrigin = options.preferredOrigin ?? this.getActiveSuggestionOrigin();
1800
+ // Before every gate: a draft or context that moved on ends the dismissal
1801
+ // even when a gate or a model without auth stops this refresh.
1802
+ const dismissed = this.reconcileDismissal();
1537
1803
  if (options.clearExisting) {
1538
1804
  this.cancelPendingRequest();
1539
1805
  this.setSuggestions([]);
@@ -1551,6 +1817,15 @@ class PromptAutocompleteEditor extends CustomEditor {
1551
1817
  return;
1552
1818
  }
1553
1819
 
1820
+ // A standing dismissal settles the refresh before any gate, model lookup, or
1821
+ // request snapshot, so continued typing stays cheap.
1822
+ if (!options.manual && dismissed) {
1823
+ this.cancelPendingRequest();
1824
+ updateDebugState(this.shared, "dismissed", "Suggestion dismissed while this draft continues");
1825
+ this.setSuggestions([]);
1826
+ return;
1827
+ }
1828
+
1554
1829
  if (this.isShowingAutocomplete()) {
1555
1830
  this.cancelPendingRequest();
1556
1831
  updateDebugState(this.shared, "paused", "Built-in autocomplete is active");
@@ -1574,13 +1849,6 @@ class PromptAutocompleteEditor extends CustomEditor {
1574
1849
  return;
1575
1850
  }
1576
1851
 
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
1852
  const cachedEntry = getCachedRequest(this.shared, request.cacheKey, { bypass: options.manual });
1585
1853
  if (cachedEntry) {
1586
1854
  this.shared.usageStats.cacheHits += 1;
@@ -1594,6 +1862,7 @@ class PromptAutocompleteEditor extends CustomEditor {
1594
1862
  this.setSuggestions(cachedEntry.suggestions, {
1595
1863
  origins: cachedEntry.suggestions,
1596
1864
  preferredOrigin,
1865
+ context: request.dismissalContext,
1597
1866
  });
1598
1867
  return;
1599
1868
  }
@@ -1608,6 +1877,7 @@ class PromptAutocompleteEditor extends CustomEditor {
1608
1877
  this.setSuggestions(prefixReused.entry.suggestions, {
1609
1878
  origins: prefixReused.origins,
1610
1879
  preferredOrigin,
1880
+ context: request.dismissalContext,
1611
1881
  });
1612
1882
  updateDebugState(
1613
1883
  this.shared,
@@ -1667,35 +1937,7 @@ class PromptAutocompleteEditor extends CustomEditor {
1667
1937
  }
1668
1938
 
1669
1939
  private buildRequest(): SuggestionRequest | undefined {
1670
- const model = resolveSuggestionModel(this.shared);
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
- };
1940
+ return buildSuggestionRequest(this.shared, this.getText(), this.activationId);
1699
1941
  }
1700
1942
 
1701
1943
  private async fetchSuggestion(request: SuggestionRequest, seq: number, spinnerOwner: string): Promise<void> {
@@ -1710,7 +1952,7 @@ class PromptAutocompleteEditor extends CustomEditor {
1710
1952
  this.shared.inFlightRequests,
1711
1953
  request.cacheKey,
1712
1954
  subscriberId,
1713
- (signal, publish) => this.fetchSuggestionUncached(request, signal, publish),
1955
+ (signal, publish) => fetchSuggestionUncached(this.shared, request, signal, publish),
1714
1956
  (suggestion) => this.showStreamedSuggestion(request, seq, spinnerOwner, suggestion),
1715
1957
  );
1716
1958
 
@@ -1736,8 +1978,8 @@ class PromptAutocompleteEditor extends CustomEditor {
1736
1978
  if (entry.suggestions.length === 0) {
1737
1979
  updateDebugState(this.shared, "no-suggestion", entry.debugState || "No usable suggestions");
1738
1980
  }
1739
- if (request.cacheKey !== this.dismissedKey) {
1740
- this.setSuggestions(entry.suggestions);
1981
+ if (!this.dismissalCovers(request)) {
1982
+ this.setSuggestions(entry.suggestions, { context: request.dismissalContext });
1741
1983
  }
1742
1984
  } catch (error) {
1743
1985
  if (error instanceof PromptAutocompleteBudgetExhaustedError) {
@@ -1782,144 +2024,17 @@ class PromptAutocompleteEditor extends CustomEditor {
1782
2024
  return;
1783
2025
  }
1784
2026
  if (!this.isRequestStillCurrent(request, seq)) return;
1785
- if (request.cacheKey === this.dismissedKey) return;
2027
+ if (this.dismissalCovers(request)) return;
1786
2028
 
1787
2029
  const current = this.getActiveSuggestion();
1788
2030
  // Progress is strictly monotonic. If a provider revises earlier text, keep
1789
2031
  // the last honest preview and let the terminal response replace it.
1790
2032
  if (current && (!suggestion.startsWith(current) || suggestion.length <= current.length)) return;
1791
2033
 
1792
- this.setSuggestions([suggestion], { provisional: true });
2034
+ this.setSuggestions([suggestion], { provisional: true, context: request.dismissalContext });
1793
2035
  this.deactivateSpinner(spinnerOwner);
1794
2036
  }
1795
2037
 
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
2038
  private isRequestStillCurrent(request: SuggestionRequest, seq: number): boolean {
1924
2039
  if (!this.shared.enabled) return false;
1925
2040
  if (!this.shared.ownsEditor?.()) return false;
@@ -1994,6 +2109,138 @@ class PromptAutocompleteEditor extends CustomEditor {
1994
2109
  }
1995
2110
  }
1996
2111
 
2112
+ /**
2113
+ * One provider call for `request`, outside any editor: reserves budget, records
2114
+ * usage, and caches the normalized result. `publish` receives streamed partials.
2115
+ */
2116
+ async function fetchSuggestionUncached(
2117
+ shared: PromptAutocompleteSharedState,
2118
+ request: SuggestionRequest,
2119
+ signal: AbortSignal,
2120
+ publish: (suggestion: string) => void,
2121
+ ): Promise<PromptAutocompleteCacheEntry> {
2122
+ if (!shared.modelRegistry) {
2123
+ throw new Error("No model registry available");
2124
+ }
2125
+
2126
+ const auth = await shared.modelRegistry.getApiKeyAndHeaders(request.model);
2127
+ // Through the host registry Pi resolves the stored credential itself, which
2128
+ // may be header-only or ambient, so only the compat path needs a key here.
2129
+ const viaRegistry = shared.routesThroughHostRegistry();
2130
+ if (!auth.ok) throw new Error(auth.error);
2131
+ if (!viaRegistry && !auth.apiKey) throw new Error(`No API key for ${request.modelLabel}`);
2132
+ if (signal.aborted) {
2133
+ throw new Error("Request was aborted");
2134
+ }
2135
+ // Last await is done: reserving here and invoking below without another
2136
+ // await is what keeps two concurrent producers from overshooting a ceiling.
2137
+ if (!reserveBudgetRequest(shared)) {
2138
+ throw new PromptAutocompleteBudgetExhaustedError(
2139
+ shared.config.budgetLimit ?? shared.budgetUsed,
2140
+ shared.budgetUsed,
2141
+ );
2142
+ }
2143
+
2144
+ const userMessage: UserMessage = {
2145
+ role: "user",
2146
+ content: [{ type: "text", text: renderPromptAutocompleteUserText(request) }],
2147
+ timestamp: Date.now(),
2148
+ };
2149
+
2150
+ const stats = shared.usageStats;
2151
+ stats.providerRequests += 1;
2152
+
2153
+ const context = {
2154
+ systemPrompt: PROMPT_AUTOCOMPLETE_SYSTEM_PROMPT,
2155
+ messages: [userMessage],
2156
+ };
2157
+ const requestOptions = {
2158
+ // An explicit key makes Pi's registry skip the stored credential and with
2159
+ // it any OAuth-derived endpoint (for example GitHub Copilot Enterprise),
2160
+ // so credentials are only passed to the compat functions and to seams.
2161
+ ...(viaRegistry ? {} : { apiKey: auth.apiKey, headers: auth.headers }),
2162
+ signal,
2163
+ maxTokens: computeRequestMaxTokens(request.maxAlternatives, request.maxSuggestionChars),
2164
+ timeoutMs: REQUEST_TIMEOUT_MS,
2165
+ maxRetries: REQUEST_MAX_RETRIES,
2166
+ maxRetryDelayMs: REQUEST_MAX_RETRY_DELAY_MS,
2167
+ };
2168
+
2169
+ const providerStartedAt = shared.now();
2170
+ let response: AssistantMessage;
2171
+ try {
2172
+ if (request.useStreaming && shared.streamSimple) {
2173
+ const hardDeadlineController = new AbortController();
2174
+ const streamSignal = AbortSignal.any([signal, hardDeadlineController.signal]);
2175
+ const stream = shared.streamSimple(request.model, context, {
2176
+ ...requestOptions,
2177
+ signal: streamSignal,
2178
+ });
2179
+ let lastPublished = "";
2180
+
2181
+ // Exactly one consumer receives the terminal message. Partial text is
2182
+ // fanned out through coalescing; after UI cancellation the callback is
2183
+ // gone, but the bounded drain can still retain terminal usage.
2184
+ response = await consumeAssistantStream(stream, streamSignal, () => hardDeadlineController.abort(), (partial) => {
2185
+ // `partial` is cumulative. Appending delta plus text_end.content would
2186
+ // duplicate the completed block on providers that emit both.
2187
+ const partialText = extractAssistantText(partial);
2188
+ const suggestion = parsePartialPromptSuggestion(request.draft, partialText, request.maxSuggestionChars);
2189
+ if (!suggestion || suggestion === lastPublished) return;
2190
+ if (lastPublished && !suggestion.startsWith(lastPublished)) return;
2191
+ lastPublished = suggestion;
2192
+ publish(suggestion);
2193
+ });
2194
+ } else {
2195
+ response = await shared.completeSimple(request.model, context, requestOptions);
2196
+ }
2197
+ } catch (error) {
2198
+ stats.failedRequests += 1;
2199
+ throw error;
2200
+ } finally {
2201
+ recordProviderLatency(stats, shared.now() - providerStartedAt);
2202
+ }
2203
+
2204
+ // Tokens spent on a failed or aborted response are still spent, so usage is
2205
+ // recorded before the stop-reason check rejects the request.
2206
+ recordProviderUsage(stats, response.usage);
2207
+
2208
+ const contentTypes = response.content.map((block) => block.type).join(", ") || "(none)";
2209
+ const text = extractAssistantText(response);
2210
+
2211
+ const responseError = response.errorMessage?.trim();
2212
+ const rawResponse = text || responseError || `[types=${contentTypes}; stopReason=${response.stopReason}]`;
2213
+
2214
+ if (response.stopReason === "error" || response.stopReason === "aborted") {
2215
+ stats.failedRequests += 1;
2216
+ throw new Error(responseError || `Provider returned stopReason=${response.stopReason}`);
2217
+ }
2218
+ if (signal.aborted) {
2219
+ stats.failedRequests += 1;
2220
+ throw new Error("Request was aborted");
2221
+ }
2222
+
2223
+ const normalized = normalizePromptSuggestions(
2224
+ request.draft,
2225
+ text,
2226
+ request.maxSuggestionChars,
2227
+ request.maxAlternatives,
2228
+ );
2229
+
2230
+ const debugState =
2231
+ normalized.length === 0
2232
+ ? text || `No text blocks returned (types: ${contentTypes}; stopReason: ${response.stopReason})`
2233
+ : `${normalized.length} suggestion(s) ready`;
2234
+
2235
+ return storeCachedRequest(shared, request.cacheKey, {
2236
+ draft: request.draft,
2237
+ prefixContextKey: request.prefixContextKey,
2238
+ suggestions: normalized,
2239
+ rawResponse,
2240
+ debugState,
2241
+ });
2242
+ }
2243
+
1997
2244
  function releaseEditorRuntime(shared: PromptAutocompleteSharedState): void {
1998
2245
  shared.cancelActiveRequest?.();
1999
2246
  shared.activationId += 1;
@@ -2110,6 +2357,7 @@ function mountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedStat
2110
2357
 
2111
2358
  const installedFactory: EditorFactory = (tui, theme, keybindings) => {
2112
2359
  const editor = new PromptAutocompleteEditor(tui, theme, keybindings, shared, activationId);
2360
+ shared.keybindings = keybindings;
2113
2361
  shared.refreshEditor = (options) => {
2114
2362
  if (activationId !== shared.activationId) return;
2115
2363
  editor.refreshFromExternalChange(options);
@@ -2176,6 +2424,7 @@ function unmountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedSt
2176
2424
 
2177
2425
  function resetSharedForSession(pi: ExtensionAPI, shared: PromptAutocompleteSharedState): void {
2178
2426
  shared.cancelActiveRequest?.();
2427
+ cancelNextPrompt(shared);
2179
2428
  shared.cancelActiveRequest = undefined;
2180
2429
  shared.cancelScheduledRequest = undefined;
2181
2430
  // Budget accounting is physical-session scoped: a new session starts fresh.
@@ -2229,15 +2478,65 @@ function buildCurrentRequestSnapshot(
2229
2478
  shared: PromptAutocompleteSharedState,
2230
2479
  draft: string,
2231
2480
  conversationId: string,
2481
+ maxAlternatives = shared.config.maxAlternatives,
2232
2482
  ): PromptAutocompleteRequestSnapshot {
2233
2483
  return buildPromptAutocompleteRequestSnapshot({
2234
2484
  draft,
2235
2485
  branch: readAutocompleteContextEntries(shared, conversationId),
2236
- maxAlternatives: shared.config.maxAlternatives,
2486
+ maxAlternatives,
2237
2487
  maxSuggestionChars: shared.config.maxSuggestionChars,
2238
2488
  });
2239
2489
  }
2240
2490
 
2491
+ /**
2492
+ * A provider request for `draft` against the current conversation, or
2493
+ * undefined when no usable model resolves. Used by the editor and by the
2494
+ * next-prompt path, which asks for one alternative only.
2495
+ */
2496
+ function buildSuggestionRequest(
2497
+ shared: PromptAutocompleteSharedState,
2498
+ draft: string,
2499
+ activationId: number,
2500
+ maxAlternatives = shared.config.maxAlternatives,
2501
+ contextBranch?: unknown[],
2502
+ ): SuggestionRequest | undefined {
2503
+ const model = resolveSuggestionModel(shared);
2504
+ if (!model) return undefined;
2505
+
2506
+ const conversationId = resolveCurrentConversationId(shared);
2507
+ shared.lastConversationId = conversationId;
2508
+ const snapshot = contextBranch === undefined
2509
+ ? buildCurrentRequestSnapshot(shared, draft, conversationId, maxAlternatives)
2510
+ : buildPromptAutocompleteRequestSnapshot({
2511
+ draft, branch: contextBranch, maxAlternatives,
2512
+ maxSuggestionChars: shared.config.maxSuggestionChars,
2513
+ });
2514
+ const modelLabel = formatModelLabel(model);
2515
+
2516
+ const prefixContextIdentity = {
2517
+ conversationId,
2518
+ modelLabel,
2519
+ maxAlternatives: snapshot.maxAlternatives,
2520
+ maxSuggestionChars: snapshot.maxSuggestionChars,
2521
+ latestAssistantContext: snapshot.latestAssistantContext,
2522
+ latestUserContext: snapshot.latestUserContext,
2523
+ recentContext: snapshot.recentContext,
2524
+ compactionSummaryContext: snapshot.compactionSummaryContext,
2525
+ };
2526
+
2527
+ return {
2528
+ ...snapshot,
2529
+ activationId,
2530
+ conversationId,
2531
+ model,
2532
+ modelLabel,
2533
+ cacheKey: buildPromptAutocompleteCacheKey({ ...prefixContextIdentity, draft: snapshot.draft }),
2534
+ prefixContextKey: buildPromptAutocompletePrefixContextKey(prefixContextIdentity),
2535
+ dismissalContext: buildDismissalContext(shared, conversationId),
2536
+ useStreaming: shared.config.streamResponses && !!shared.streamSimple,
2537
+ };
2538
+ }
2539
+
2241
2540
  /**
2242
2541
  * Conversation entries autocomplete may draw context from.
2243
2542
  *
@@ -2275,6 +2574,28 @@ function resolveCurrentConversationId(shared: PromptAutocompleteSharedState): st
2275
2574
  return resolveAutocompleteConversationId(branch, leafId || shared.physicalSessionId);
2276
2575
  }
2277
2576
 
2577
+ /**
2578
+ * Dismissal context for the given conversation.
2579
+ *
2580
+ * The model part is what is requested, not what resolves: a dedicated model's
2581
+ * reference, or the active session model in `active` mode. It therefore changes
2582
+ * on a switch to a model without auth, which no request could be built for.
2583
+ */
2584
+ function buildDismissalContext(shared: PromptAutocompleteSharedState, conversationId: string): string {
2585
+ const selection = shared.config.modelSelection;
2586
+ const requestedModel = selection.kind === "dedicated"
2587
+ ? `${selection.ref.provider}/${selection.ref.id}`
2588
+ : selection.kind === "invalid"
2589
+ ? selection.raw
2590
+ : formatModelLabel(shared.currentModel);
2591
+ return buildPromptAutocompleteDismissalContext({
2592
+ conversationId,
2593
+ requestedModel,
2594
+ maxAlternatives: shared.config.maxAlternatives,
2595
+ maxSuggestionChars: shared.config.maxSuggestionChars,
2596
+ });
2597
+ }
2598
+
2278
2599
  function rememberAgentSettledSupport(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): void {
2279
2600
  if (shared.hostEmitsAgentSettled !== undefined) return;
2280
2601
  shared.hostEmitsAgentSettled = typeof ctx.isIdle === "function";
@@ -2286,6 +2607,112 @@ function settleAgentTurn(shared: PromptAutocompleteSharedState, details: string)
2286
2607
  refreshEditorImmediately(shared, "ready", details);
2287
2608
  }
2288
2609
 
2610
+ /**
2611
+ * RPC hosts started with `--prompt-autocomplete-next-prompt`: after a settled
2612
+ * turn, predict the user's next prompt and hand it over with `setEditorText`,
2613
+ * which T3 Code shows as its suggested next prompt. Budget, model selection,
2614
+ * and stats apply as in the editor. A new turn or session aborts the request,
2615
+ * and a result is dropped when the agent is busy again or the conversation
2616
+ * moved to another branch while it was pending.
2617
+ */
2618
+ async function suggestNextPrompt(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): Promise<void> {
2619
+ cancelNextPrompt(shared);
2620
+ if (!shared.config.nextPrompt || ctx.mode !== "rpc") return;
2621
+ const request = buildSuggestionRequest(shared, "", shared.activationId, 1);
2622
+ if (!request) return;
2623
+ const controller = new AbortController();
2624
+ shared.nextPromptAbort = controller;
2625
+ try {
2626
+ const entry = await fetchSuggestionUncached(
2627
+ shared,
2628
+ { ...request, useStreaming: false },
2629
+ controller.signal,
2630
+ () => undefined,
2631
+ );
2632
+ const suggestion = entry.suggestions[0];
2633
+ if (!suggestion || controller.signal.aborted) return;
2634
+ // Pi marks a new run busy before `agent_start` reaches this extension.
2635
+ if (typeof ctx.isIdle === "function" && !ctx.isIdle()) return;
2636
+ if (resolveCurrentConversationId(shared) !== request.conversationId) return;
2637
+ ctx.ui.setEditorText(suggestion);
2638
+ } catch (error) {
2639
+ if (!controller.signal.aborted) shared.lastError = error instanceof Error ? error.message : String(error);
2640
+ } finally {
2641
+ if (shared.nextPromptAbort === controller) shared.nextPromptAbort = undefined;
2642
+ }
2643
+ }
2644
+
2645
+ /** RPC-only request/reply adapter; provider errors never cross the host boundary. */
2646
+ async function completeRpcDraft(ctx: ExtensionContext, shared: PromptAutocompleteSharedState, payload: string): Promise<void> {
2647
+ if (ctx.mode !== "rpc") {
2648
+ ctx.ui.notify("prompt-autocomplete complete is for RPC hosts", "warning");
2649
+ return;
2650
+ }
2651
+ shared.draftCompletionAbort?.abort();
2652
+ let value: unknown;
2653
+ try { value = JSON.parse(payload); } catch { return; }
2654
+ if (!value || typeof value !== "object" || !("id" in value) || typeof value.id !== "string") return;
2655
+ const id = value.id;
2656
+ const controller = new AbortController();
2657
+ shared.draftCompletionAbort = controller;
2658
+ let replied = false;
2659
+ const reply = (completion: string | null, error?: string) => {
2660
+ if (replied) return;
2661
+ replied = true;
2662
+ ctx.ui.setWidget("prompt-autocomplete-completion", [JSON.stringify({ id, completion, ...(error ? { error } : {}) })]);
2663
+ };
2664
+ const onAbort = () => reply(null);
2665
+ controller.signal.addEventListener("abort", onAbort, { once: true });
2666
+ try {
2667
+ if (!("draft" in value) || typeof value.draft !== "string") {
2668
+ reply(null, "Invalid completion request");
2669
+ return;
2670
+ }
2671
+ const context = "context" in value ? value.context : undefined;
2672
+ const branch: unknown[] = [];
2673
+ if (context !== undefined) {
2674
+ if (!context || typeof context !== "object" || Array.isArray(context)) {
2675
+ reply(null, "Invalid completion context");
2676
+ return;
2677
+ }
2678
+ for (const [key, role] of [["lastUser", "user"], ["lastAssistant", "assistant"]] as const) {
2679
+ const text = key === "lastUser"
2680
+ ? ("lastUser" in context ? context.lastUser : undefined)
2681
+ : ("lastAssistant" in context ? context.lastAssistant : undefined);
2682
+ if (text !== undefined && typeof text !== "string") {
2683
+ reply(null, "Invalid completion context");
2684
+ return;
2685
+ }
2686
+ if (text) branch.push({ type: "message", message: { role, content: text } });
2687
+ }
2688
+ }
2689
+ if (value.draft.trim().length < shared.config.minPromptChars) {
2690
+ reply(null);
2691
+ return;
2692
+ }
2693
+ const request = buildSuggestionRequest(shared, value.draft, shared.activationId, 1, branch);
2694
+ if (!request) {
2695
+ reply(null, "Completion model unavailable");
2696
+ return;
2697
+ }
2698
+ let entry = getCachedRequest(shared, request.cacheKey);
2699
+ if (entry) shared.usageStats.cacheHits += 1;
2700
+ else entry = await fetchSuggestionUncached(shared, { ...request, useStreaming: false }, controller.signal, () => undefined);
2701
+ reply(controller.signal.aborted ? null : entry.suggestions[0] ?? null);
2702
+ } catch (error) {
2703
+ reply(null, controller.signal.aborted || error instanceof PromptAutocompleteBudgetExhaustedError
2704
+ ? undefined : "Completion request failed");
2705
+ } finally {
2706
+ controller.signal.removeEventListener("abort", onAbort);
2707
+ if (shared.draftCompletionAbort === controller) shared.draftCompletionAbort = undefined;
2708
+ }
2709
+ }
2710
+
2711
+ function cancelNextPrompt(shared: PromptAutocompleteSharedState): void {
2712
+ shared.nextPromptAbort?.abort();
2713
+ shared.nextPromptAbort = undefined;
2714
+ }
2715
+
2289
2716
  function refreshEditorImmediately(shared: PromptAutocompleteSharedState, state: string, details: string): void {
2290
2717
  updateDebugState(shared, state, details);
2291
2718
  shared.refreshEditor?.({ clearExisting: true, immediate: true });
@@ -2482,11 +2909,11 @@ function persistSettingsDecision(
2482
2909
  shared: PromptAutocompleteSharedState,
2483
2910
  patch: Partial<PromptAutocompletePersistedSettings>,
2484
2911
  ): boolean {
2485
- shared.persistedSettings = { ...shared.persistedSettings, ...patch };
2912
+ shared.persistedSettings = applyPromptAutocompleteSettingsPatch(shared.persistedSettings, patch);
2486
2913
  const store = shared.settingsStore;
2487
2914
  if (!store) return false;
2488
2915
  try {
2489
- store.save(shared.persistedSettings);
2916
+ store.update(patch);
2490
2917
  return true;
2491
2918
  } catch (error) {
2492
2919
  const reason = error instanceof Error ? error.message : String(error);
@@ -2766,8 +3193,74 @@ const SET_KEY_RUNNERS: {
2766
3193
  }
2767
3194
  setModelSetting(ctx, shared, value);
2768
3195
  },
3196
+ key: (ctx, shared, value) => setActionKeys(ctx, shared, value),
2769
3197
  };
2770
3198
 
3199
+ const SET_KEY_USAGE = `Usage: /prompt-autocomplete set key <${
3200
+ PROMPT_AUTOCOMPLETE_CONFIGURABLE_KEY_ACTIONS.map((action) => PROMPT_AUTOCOMPLETE_KEY_ACTIONS[action].command).join("|")
3201
+ }> <key...|default|none>`;
3202
+
3203
+ /**
3204
+ * `set key <action> <key...|default|none>`: change one action's keys, save
3205
+ * them, and apply them to the editor at once.
3206
+ *
3207
+ * Keys are whitespace-separated, because `,` is a key. A key that another
3208
+ * Prompt Autocomplete action has must be freed there first, so one keypress
3209
+ * never means two actions. A key Pi's keymap binds is accepted with a note:
3210
+ * the editor leaves it to Pi.
3211
+ */
3212
+ function setActionKeys(ctx: ExtensionContext, shared: PromptAutocompleteSharedState, value: string): void {
3213
+ const [command = "", ...tokens] = value.split(/\s+/).filter((token) => token.length > 0);
3214
+ const action = findConfigurableKeyAction(command.toLowerCase());
3215
+ if (!action || tokens.length === 0) {
3216
+ ctx.ui.notify(SET_KEY_USAGE, "warning");
3217
+ return;
3218
+ }
3219
+ const choice = tokens.length === 1 ? tokens[0]!.toLowerCase() : undefined;
3220
+ let keys: KeyId[] | undefined;
3221
+ if (choice === "none") {
3222
+ keys = [];
3223
+ } else if (choice !== "default") {
3224
+ keys = [];
3225
+ for (const token of tokens) {
3226
+ const key = parsePromptAutocompleteKeyId(token);
3227
+ if (!key) {
3228
+ ctx.ui.notify(`${truncateDebug(token, 40)} is not a key. ${SET_KEY_USAGE}`, "warning");
3229
+ return;
3230
+ }
3231
+ const unusable = describeUnusablePromptAutocompleteKey(key);
3232
+ if (unusable) {
3233
+ ctx.ui.notify(`Prompt autocomplete cannot use this key: ${unusable}.`, "warning");
3234
+ return;
3235
+ }
3236
+ if (!keys.some((existing) => canonicalKeyId(existing) === canonicalKeyId(key))) keys.push(key);
3237
+ }
3238
+ }
3239
+
3240
+ for (const key of keys ?? PROMPT_AUTOCOMPLETE_KEY_ACTIONS[action].keys) {
3241
+ const owner = listPromptAutocompleteKeys(shared.keymap).find(
3242
+ (entry) => entry.command !== command.toLowerCase()
3243
+ && entry.keys.some((owned) => canonicalKeyId(owned) === canonicalKeyId(key)),
3244
+ );
3245
+ if (owner) {
3246
+ ctx.ui.notify(`${key} is already ${owner.command}; change that action first.`, "warning");
3247
+ return;
3248
+ }
3249
+ }
3250
+
3251
+ const persisted = persistSettingsDecision(ctx, shared, { keys: { [action]: keys } });
3252
+ shared.keymap = resolvePromptAutocompleteKeymap(shared.persistedSettings.keys);
3253
+ const effective = shared.keymap.keys[action];
3254
+ const usedByPi = listKeysUsedByPi(shared.keybindings, effective) ?? [];
3255
+ ctx.ui.notify(
3256
+ `Prompt autocomplete ${command.toLowerCase()} keys set to ${effective.join(" ") || "none"}`
3257
+ + `${keys === undefined ? " (default)" : ""}`
3258
+ + `${persisted ? " (saved for future sessions)" : " (session only — could not save for future sessions)"}`
3259
+ + `${usedByPi.length > 0 ? `. Pi's keymap also binds ${usedByPi.join(", ")}, so Pi keeps those keys.` : ""}`,
3260
+ usedByPi.length > 0 ? "warning" : "info",
3261
+ );
3262
+ }
3263
+
2771
3264
  function setBoundedSetKey(
2772
3265
  ctx: ExtensionContext,
2773
3266
  shared: PromptAutocompleteSharedState,
@@ -2839,10 +3332,7 @@ function notifyPromptAutocompleteEnabled(
2839
3332
  shared: PromptAutocompleteSharedState,
2840
3333
  options: { includeModel: boolean },
2841
3334
  ): 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).`;
3335
+ const keyHint = formatKeyHints(shared.keymap).notice;
2846
3336
  const resolution = resolveSuggestionModelResolution(shared);
2847
3337
  const resolvedModel = resolution.model;
2848
3338
  const privacyNotice = PRIVACY_NOTICE;
@@ -2889,7 +3379,7 @@ function hasNotificationChannel(ctx: ExtensionContext): boolean {
2889
3379
  * cannot issue requests there, instead of staying silently inert.
2890
3380
  */
2891
3381
  function notifyEnabledWithoutEditorOnce(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): void {
2892
- if (!shared.enabled || shared.processState.nonInteractiveNoticeShown) return;
3382
+ if (!shared.enabled || shared.config.nextPrompt || shared.processState.nonInteractiveNoticeShown) return;
2893
3383
  if (hostOwnsInteractiveEditor(ctx, shared) || !hasNotificationChannel(ctx)) return;
2894
3384
  shared.processState.nonInteractiveNoticeShown = true;
2895
3385
  ctx.ui.notify(
@@ -2974,6 +3464,7 @@ const COMMAND_RUNNERS: { [Name in PromptAutocompleteCommandName]: CommandRunner
2974
3464
  "min-chars": (ctx, shared, { firstArgument }) => setMinPromptChars(ctx, shared, firstArgument),
2975
3465
  budget: (ctx, shared, { firstArgument }) => setBudgetLimit(ctx, shared, firstArgument),
2976
3466
  set: (ctx, shared, { rest }) => handleSetCommand(ctx, shared, rest),
3467
+ keys: (ctx, shared) => ctx.ui.notify(formatKeymap(shared), "info"),
2977
3468
  stream: (ctx, shared, { firstArgument }) => setStreamResponses(ctx, shared, firstArgument),
2978
3469
  "while-streaming": (ctx, shared, { firstArgument }) => setWhileStreaming(ctx, shared, firstArgument),
2979
3470
  "debug-on": (ctx, shared) => {
@@ -3027,7 +3518,8 @@ export function createPromptAutocompleteExtension(
3027
3518
  dependencies.streamSimple
3028
3519
  ?? (dependencies.completeSimple || !hostStreaming ? undefined : routedStreamSimple);
3029
3520
 
3030
- const settingsStore = dependencies.settingsStore ?? createFileSettingsStore(resolvePromptAutocompleteSettingsPath());
3521
+ const settingsStore = dependencies.settingsStore
3522
+ ?? createPromptAutocompleteFileSettingsStore(resolvePromptAutocompleteSettingsPath());
3031
3523
  let persistedSettings: PromptAutocompletePersistedSettings;
3032
3524
  try {
3033
3525
  persistedSettings = settingsStore.load();
@@ -3088,6 +3580,11 @@ export function createPromptAutocompleteExtension(
3088
3580
  type: "string",
3089
3581
  default: DEFAULT_BUDGET_REQUESTS_FLAG,
3090
3582
  });
3583
+ pi.registerFlag("prompt-autocomplete-next-prompt", {
3584
+ description: "RPC mode: suggest the next prompt after each turn through setEditorText (T3 Code)",
3585
+ type: "boolean",
3586
+ default: false,
3587
+ });
3091
3588
 
3092
3589
  const shared: PromptAutocompleteSharedState = {
3093
3590
  enabled: false,
@@ -3099,6 +3596,7 @@ export function createPromptAutocompleteExtension(
3099
3596
  runtimeOverrides: {},
3100
3597
  persistedSettings,
3101
3598
  settingsStore,
3599
+ keymap: resolvePromptAutocompleteKeymap(persistedSettings.keys),
3102
3600
  enabledFlagValue: false,
3103
3601
  budgetUsed: 0,
3104
3602
  budgetBlockNotices: new Set(),
@@ -3132,8 +3630,11 @@ export function createPromptAutocompleteExtension(
3132
3630
 
3133
3631
  pi.on("session_shutdown", async (_event, ctx) => {
3134
3632
  // Teardown, not a user decision: leave runtimeOverrides untouched.
3633
+ shared.draftCompletionAbort?.abort();
3634
+ shared.draftCompletionAbort = undefined;
3135
3635
  shared.enabled = false;
3136
3636
  shared.cancelActiveRequest?.();
3637
+ cancelNextPrompt(shared);
3137
3638
  shared.requestCache.clear();
3138
3639
  shared.prefixReuseCache.clear();
3139
3640
  cancelAllCoalescedRequests(shared.inFlightRequests);
@@ -3158,6 +3659,7 @@ export function createPromptAutocompleteExtension(
3158
3659
 
3159
3660
  pi.on("agent_start", async () => {
3160
3661
  shared.agentStreaming = true;
3662
+ cancelNextPrompt(shared);
3161
3663
  if (!shared.enabled || shared.config.allowWhileStreaming) return;
3162
3664
  refreshEditorImmediately(shared, "waiting", "Main agent is still working");
3163
3665
  });
@@ -3168,8 +3670,10 @@ export function createPromptAutocompleteExtension(
3168
3670
  settleAgentTurn(shared, "Agent finished; autocomplete can request suggestions again");
3169
3671
  });
3170
3672
 
3171
- pi.on("agent_settled", async () => {
3673
+ pi.on("agent_settled", async (_event, ctx) => {
3172
3674
  settleAgentTurn(shared, "Agent settled; autocomplete can request suggestions again");
3675
+ // Not awaited: Pi waits for handlers, and the turn is already over.
3676
+ void suggestNextPrompt(ctx, shared);
3173
3677
  });
3174
3678
 
3175
3679
  pi.registerCommand("prompt-autocomplete", {
@@ -3184,6 +3688,10 @@ export function createPromptAutocompleteExtension(
3184
3688
  // must keep its leading and trailing whitespace to match production.
3185
3689
  const payload = space < 0 ? "" : commandStart.slice(space + 1);
3186
3690
  const rest = payload.trim();
3691
+ if (name === "complete") {
3692
+ await completeRpcDraft(ctx, shared, payload);
3693
+ return;
3694
+ }
3187
3695
  const spec = findPromptAutocompleteCommand(name);
3188
3696
 
3189
3697
  // Reporting works wherever a notification can be shown; anything that