@kliebhan/pi-prompt-autocomplete 0.2.5 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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,24 +11,49 @@ 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
- buildLatestAssistantMessageContext,
17
- buildLatestUserMessageContext,
18
25
  buildPromptAutocompleteCacheKey,
26
+ buildPromptAutocompleteDismissalContext,
19
27
  buildPromptAutocompletePrefixContextKey,
20
- buildRecentConversationContext,
28
+ buildPromptAutocompleteBudgetSnapshot,
29
+ buildPromptAutocompleteRequestSnapshot,
30
+ renderPromptAutocompleteUserText,
31
+ type PromptAutocompleteRequestSnapshot,
32
+ BUDGET_REQUESTS_MAX,
33
+ BUDGET_REQUESTS_MIN,
21
34
  cancelAllCoalescedRequests,
22
35
  computeRequestMaxTokens,
23
36
  createOwnerRefCounter,
24
37
  createPromptAutocompleteUsageStats,
38
+ DEFAULT_BUDGET_REQUESTS_FLAG,
25
39
  describePromptAutocompleteModelSelection,
26
40
  describeSettingSource,
27
41
  DEFAULT_DEBOUNCE_MS,
42
+ DEBOUNCE_MS_MAX,
43
+ DEBOUNCE_MS_MIN,
28
44
  DEFAULT_MAX_ALTERNATIVES,
29
45
  DEFAULT_MAX_SUGGESTION_CHARS,
30
46
  DEFAULT_MIN_PROMPT_CHARS,
47
+ MAX_ALTERNATIVES_MAX,
48
+ MAX_ALTERNATIVES_MIN,
49
+ MAX_COMPACTION_SUMMARY_CHARS,
50
+ MAX_CONTEXT_MESSAGE_CHARS,
51
+ MAX_CONTEXT_MESSAGES,
52
+ MAX_DRAFT_CONTEXT_CHARS,
53
+ MAX_LATEST_ASSISTANT_MESSAGE_CHARS,
54
+ MAX_LATEST_USER_MESSAGE_CHARS,
55
+ MAX_SUGGESTION_CHARS_MAX,
56
+ MAX_SUGGESTION_CHARS_MIN,
31
57
  DEFAULT_PREFERRED_MODEL,
32
58
  MIN_PROMPT_CHARS_MAX,
33
59
  MIN_PROMPT_CHARS_MIN,
@@ -40,25 +66,57 @@ import {
40
66
  formatUsageStats,
41
67
  hostSupportsStreamedResponses,
42
68
  isInteractiveEditorHost,
43
- MAX_DRAFT_CONTEXT_CHARS,
44
69
  normalizePromptSuggestions,
45
70
  parseBoundedIntFlag,
46
71
  parseExplicitBoundedIntFlag,
72
+ parseExplicitModelFlag,
73
+ parsePersistedModelRaw,
74
+ parsePromptAutocompleteBudgetFlag,
75
+ parsePromptAutocompleteBudgetValue,
76
+ parseStrictBoundedInt,
77
+ persistableModelRaw,
47
78
  parsePartialPromptSuggestion,
48
79
  parsePromptAutocompleteModelSelection,
49
80
  parsePromptAutocompletePersistedSettings,
81
+ projectAutocompleteContextEntries,
82
+ findPromptAutocompleteBudgetSnapshot,
83
+ completePromptAutocompleteArguments,
84
+ findPromptAutocompleteCommand,
85
+ findPromptAutocompleteSetKey,
86
+ PROMPT_AUTOCOMPLETE_SET_USAGE,
87
+ PROMPT_AUTOCOMPLETE_USAGE,
88
+ type PromptAutocompleteCommandName,
89
+ type PromptAutocompleteSetKey,
90
+ PromptAutocompleteBudgetExhaustedError,
91
+ type PromptAutocompleteBudgetSetting,
50
92
  resolvePersistedEnabled,
51
93
  resolvePersistedNumber,
52
- serializePromptAutocompletePersistedSettings,
94
+ resolvePromptAutocompleteBudgetLimit,
53
95
  PROMPT_AUTOCOMPLETE_SYSTEM_PROMPT,
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,
54
111
  recordProviderLatency,
55
112
  recordProviderUsage,
113
+ resolveAutocompleteConversationId,
56
114
  resolveOverride,
115
+ resolvePersistedModelSelection,
57
116
  reusePromptAutocompleteSuggestions,
58
117
  sanitizeTerminalText,
59
118
  SequenceOwnedSlot,
60
119
  shouldSkipPromptAutocomplete,
61
- truncateDraftTail,
62
120
  type CoalescedRequestEntry,
63
121
  type CoalescedRequestSubscription,
64
122
  type PromptAutocompleteModelSelection,
@@ -70,13 +128,16 @@ import {
70
128
  const GHOST_TEXT_STYLE = "\x1b[2m";
71
129
  const GHOST_INDICATOR_STYLE = "\x1b[90m";
72
130
  const RESET = "\x1b[0m";
73
- // Hosts draw the end-of-line fake cursor as an inverse-video space. Pi closes
74
- // it with a full SGR reset (\x1b[0m); forks that keep an editor background
75
- // surface alive, such as prime-agent, close it with \x1b[27m so the background
76
- // survives the cursor cell. Accept both, otherwise the suggestion lookup never
77
- // finds the cursor and inline suggestions silently never render.
78
- const CURSOR_INVERSE_SPACE = "\x1b[7m ";
79
- const CURSOR_TOKEN_PATTERN = /\x1b\[7m \x1b\[(0|27)m/;
131
+ // Hosts draw the end-of-line cursor as a marked space cell. Pi 0.x draws inverse
132
+ // video closed by a full SGR reset (\x1b[0m); forks that keep an editor
133
+ // background surface alive, such as prime-agent, close it with \x1b[27m so the
134
+ // background survives the cursor cell; Pi 1.x wraps the cell in fake-cursor APC
135
+ // markers that its TUI later turns into inverse video or the hardware cursor.
136
+ // Accept all three, otherwise the suggestion lookup never finds the cursor and
137
+ // inline suggestions silently never render. Each form is matched as a whole so
138
+ // the cell is always rebuilt with its own opening and closing sequence.
139
+ const CURSOR_CELL_OPENERS = ["\x1b[7m ", "\x1b_pi:fc\x07 "] as const;
140
+ const CURSOR_CELL_PATTERN = /\x1b\[7m \x1b\[(?:0|27)m|\x1b_pi:fc\x07 \x1b_pi:\/fc\x07/;
80
141
  const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] as const;
81
142
  const SPINNER_INTERVAL_MS = 80;
82
143
  const SPINNER_LABEL = "Generating suggestion";
@@ -96,15 +157,8 @@ const REQUEST_MAX_RETRY_DELAY_MS = 2_000;
96
157
  const FAILURE_COOLDOWN_MS = 5_000;
97
158
  const REQUEST_CACHE_TTL_MS = 60_000;
98
159
  const REQUEST_CACHE_MAX_ENTRIES = 128;
99
- // Keymap audit vs. pi defaults (packages/tui/src/keybindings.ts +
100
- // packages/coding-agent/src/core/keybindings.ts): none of the keys below are bound
101
- // by pi's default keymap, so the editor can safely own them — including the
102
- // broadened `ctrl+.`/`alt+]` one-shot trigger, which shadows no base action. The
103
- // only nearby defaults are `ctrl+]` (jumpForward) and `ctrl+alt+]` (jumpBackward),
104
- // both distinct from our `alt+]`.
105
- const WORD_ACCEPT_KEYS: readonly KeyId[] = ["ctrl+space", "ctrl+tab"];
106
- const CYCLE_NEXT_KEYS: readonly KeyId[] = ["ctrl+.", "alt+]"];
107
- const CYCLE_PREV_KEYS: readonly KeyId[] = ["ctrl+,", "alt+["];
160
+ const PRIVACY_NOTICE =
161
+ "Requests send the current draft and recent conversation context to the selected model and may incur provider usage.";
108
162
  const NAVIGATION_ACTIONS = [
109
163
  "tui.editor.cursorUp",
110
164
  "tui.editor.cursorDown",
@@ -142,6 +196,10 @@ interface PromptAutocompleteConfig {
142
196
  maxSuggestionChars: number;
143
197
  maxAlternatives: number;
144
198
  modelSelection: PromptAutocompleteModelSelection;
199
+ /** Effective provider-request ceiling; undefined means off. */
200
+ budgetLimit?: number;
201
+ /** RPC hosts only: send a predicted next prompt through `setEditorText` after each settled turn. */
202
+ nextPrompt: boolean;
145
203
  }
146
204
 
147
205
  interface PromptAutocompleteCacheEntry {
@@ -217,23 +275,119 @@ const hostStreamSimple = ((model, context, options) =>
217
275
  options,
218
276
  )) as StreamSimpleFunction;
219
277
 
278
+ /** The model registry's own request entry point, which Pi 1.x provides. */
279
+ type RegistryStreamSimple = (...args: Parameters<StreamSimpleFunction>) => ReturnType<StreamSimpleFunction>;
280
+
281
+ /**
282
+ * Where a request goes when no seam was injected.
283
+ *
284
+ * Pi 1.x serves every chat model, including those that extensions register
285
+ * with their own streaming implementation, through the session's model
286
+ * registry; the global `pi-ai` compat functions only know Pi's built-in APIs
287
+ * there and fail for extension providers. The registry also applies the
288
+ * provider's request-time base URL and environment. Hosts without it (Pi 0.x
289
+ * and forks of that API) keep the compat functions, which serve every model
290
+ * there.
291
+ */
292
+ function registryStreamSimple(registry: unknown): RegistryStreamSimple | undefined {
293
+ if (typeof registry !== "object" || registry === null) return undefined;
294
+ const streamSimple: unknown = Reflect.get(registry, "streamSimple");
295
+ if (typeof streamSimple !== "function") return undefined;
296
+ return (model, context, options) => Reflect.apply(streamSimple, registry, [model, context, options]);
297
+ }
298
+
220
299
  export interface PromptAutocompleteDependencies {
221
300
  completeSimple?: CompleteSimpleFunction;
222
301
  streamSimple?: StreamSimpleFunction;
223
302
  now?: () => number;
224
303
  /** Store for decisions that survive the process; defaults to a JSON settings file. */
225
304
  settingsStore?: PromptAutocompleteSettingsStore;
305
+ /** Process-lifetime state; defaults to one object shared by every runtime of this process. */
306
+ processState?: PromptAutocompleteProcessState;
307
+ }
308
+
309
+ /**
310
+ * State that must outlive extension runtimes within one process.
311
+ *
312
+ * Pi re-imports the extension module for every runtime (`/new`, `/resume`,
313
+ * `/fork`, `/reload`), so neither runtime state nor module scope lasts for the
314
+ * process. Only what is genuinely process-wide belongs here.
315
+ */
316
+ export interface PromptAutocompleteProcessState {
317
+ /** The enabled-but-non-interactive notice was already shown. */
318
+ nonInteractiveNoticeShown?: boolean;
319
+ /**
320
+ * Set once a mount attempt proved whether this host installs custom editors.
321
+ *
322
+ * A process cannot change its front-end, so this is deliberately never reset:
323
+ * a host that dropped the editor factory once would drop it again, also in a
324
+ * later runtime. Restarting the host is the only way to re-probe.
325
+ */
326
+ hostInstallsEditors?: boolean;
327
+ }
328
+
329
+ const PROCESS_STATE_KEY = Symbol.for("@kliebhan/pi-prompt-autocomplete/process-state");
330
+
331
+ const PROCESS_STATE_FIELDS = ["nonInteractiveNoticeShown", "hostInstallsEditors"] as const;
332
+
333
+ /**
334
+ * Accept only an occupant this extension could have written: an extensible
335
+ * plain object whose known fields are absent or own writable booleans. Anything
336
+ * else — a frozen object, a stringly typed flag, an inherited field, or a
337
+ * proxy whose traps throw — is replaced rather than trusted.
338
+ */
339
+ function isProcessState(value: unknown): value is PromptAutocompleteProcessState {
340
+ try {
341
+ if (typeof value !== "object" || value === null) return false;
342
+ if (Object.getPrototypeOf(value) !== Object.prototype || !Object.isExtensible(value)) return false;
343
+ return PROCESS_STATE_FIELDS.every((field) => {
344
+ const descriptor = Object.getOwnPropertyDescriptor(value, field);
345
+ return descriptor === undefined
346
+ || (descriptor.writable === true && (descriptor.value === undefined || typeof descriptor.value === "boolean"));
347
+ });
348
+ } catch {
349
+ return false;
350
+ }
351
+ }
352
+
353
+ /**
354
+ * The process-wide state object, created on first use and found again after a
355
+ * re-import.
356
+ *
357
+ * If another occupant holds the slot and cannot be replaced, there is no other
358
+ * process-wide store, so this runtime falls back to private state: a notice or
359
+ * the editor probe may then repeat after a runtime replacement, but nothing
360
+ * fails.
361
+ */
362
+ function sharedProcessState(): PromptAutocompleteProcessState {
363
+ let existing: unknown;
364
+ try {
365
+ existing = Reflect.get(globalThis, PROCESS_STATE_KEY);
366
+ } catch {
367
+ existing = undefined;
368
+ }
369
+ if (isProcessState(existing)) return existing;
370
+ const created: PromptAutocompleteProcessState = {};
371
+ Reflect.defineProperty(globalThis, PROCESS_STATE_KEY, {
372
+ value: created,
373
+ writable: true,
374
+ configurable: true,
375
+ enumerable: false,
376
+ });
377
+ return created;
226
378
  }
227
379
 
228
380
  /**
229
381
  * Persistence boundary for cross-process decisions.
230
382
  *
231
383
  * `load` runs once per activation and must not throw for a missing or
232
- * 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.
233
387
  */
234
388
  export interface PromptAutocompleteSettingsStore {
235
389
  load(): PromptAutocompletePersistedSettings;
236
- save(settings: PromptAutocompletePersistedSettings): void;
390
+ update(patch: Partial<PromptAutocompletePersistedSettings>): void;
237
391
  }
238
392
 
239
393
  /**
@@ -255,41 +409,138 @@ export function resolvePromptAutocompleteSettingsPath(
255
409
  return join(configHome, "pi-prompt-autocomplete", "settings.json");
256
410
  }
257
411
 
258
- 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
+ };
259
440
  return {
260
441
  load(): PromptAutocompletePersistedSettings {
261
- let text: string;
262
442
  try {
263
- text = readFileSync(path, "utf8");
443
+ return parsePromptAutocompletePersistedSettings(readText());
264
444
  } catch {
265
445
  return {};
266
446
  }
267
- return parsePromptAutocompletePersistedSettings(text);
268
447
  },
269
- save(settings: PromptAutocompletePersistedSettings): void {
270
- // Atomic replace so a crash mid-write cannot corrupt the settings file.
271
- const tempPath = `${path}.tmp`;
272
- mkdirSync(dirname(path), { recursive: true });
273
- writeFileSync(tempPath, serializePromptAutocompletePersistedSettings(settings), "utf8");
274
- 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
+ }
275
467
  },
276
468
  };
277
469
  }
278
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
+
279
486
  interface PromptAutocompleteSharedState {
280
487
  enabled: boolean;
281
488
  activationId: number;
282
489
  agentStreaming: boolean;
490
+ /**
491
+ * Immutable for the current extension runtime's session. Captured at
492
+ * `session_start` from `sessionManager.getSessionId()`. Fork/new replace the
493
+ * runtime, so a later session cannot inherit this id from an old closure.
494
+ */
495
+ physicalSessionId: string;
496
+ /**
497
+ * Last context-relevant conversation id observed on this runtime. Used to
498
+ * ignore `session_tree` events that only moved the raw leaf.
499
+ */
500
+ lastConversationId: string;
501
+ /**
502
+ * Set once we know whether this host emits `agent_settled`.
503
+ *
504
+ * `pi.on("agent_settled")` never throws — Pi stores any event name — so the
505
+ * probe is `typeof ctx.isIdle === "function"`. That method shipped together
506
+ * with `agent_settled` in Pi 0.80.5. A process cannot change its front-end,
507
+ * so this is never reset.
508
+ */
509
+ hostEmitsAgentSettled?: boolean;
283
510
  config: PromptAutocompleteConfig;
284
511
  /** Slash-command decisions that outrank flags for the lifetime of the process. */
285
512
  runtimeOverrides: PromptAutocompleteRuntimeOverrides;
286
513
  /** Decisions persisted across processes; loaded once per activation. */
287
514
  persistedSettings: PromptAutocompletePersistedSettings;
288
515
  settingsStore?: PromptAutocompleteSettingsStore;
516
+ /** Effective keys from the saved keys; replaced by `set key`, read at every keypress. */
517
+ keymap: PromptAutocompleteKeymap;
289
518
  /** Last enabled-flag value seen by applyEffectiveConfig, for status attribution. */
290
519
  enabledFlagValue: boolean;
291
520
  /** Explicit min-chars flag value seen by applyEffectiveConfig, undefined when defaulted. */
292
521
  minPromptCharsFlagExplicit?: number;
522
+ debounceMsFlagExplicit?: number;
523
+ maxSuggestionCharsFlagExplicit?: number;
524
+ maxAlternativesFlagExplicit?: number;
525
+ modelFlagExplicit?: PromptAutocompleteModelSelection;
526
+ /** Explicit max-requests flag value seen by applyEffectiveConfig, undefined when defaulted. */
527
+ budgetFlagExplicit?: number;
528
+ /** Ceiling restored from this session's entries; `"off"` is a real restored decision. */
529
+ savedBudgetLimit?: PromptAutocompleteBudgetSetting;
530
+ /** Reserved provider invocations of the current physical session. */
531
+ budgetUsed: number;
532
+ /**
533
+ * Whether this physical session already carries durable budget state.
534
+ *
535
+ * Once a ceiling was set or restored, accounting stays durable even while the
536
+ * ceiling is off, so a later ceiling cannot ignore what the session spent in
537
+ * between. A session that never touched the budget writes no entries at all.
538
+ */
539
+ budgetSnapshotsActive?: boolean;
540
+ /** Exhaustion notices already delivered, keyed by `used/limit`. */
541
+ budgetBlockNotices: Set<string>;
542
+ /** Session-bound snapshot writer; appends a non-LLM custom entry. */
543
+ persistBudgetSnapshot?: (limit: PromptAutocompleteBudgetSetting, used: number) => void;
293
544
  /** Session-scoped request accounting; reset together with the cache. */
294
545
  usageStats: PromptAutocompleteUsageStats;
295
546
  currentModel?: Model<Api>;
@@ -301,18 +552,23 @@ interface PromptAutocompleteSharedState {
301
552
  debugState: string;
302
553
  editorMount?: EditorMountState;
303
554
  editorBlockedReason?: string;
555
+ /** Whether requests go through the session's model registry rather than compat or injected seams. */
556
+ routesThroughHostRegistry: () => boolean;
304
557
  /** Mount-bound notification channel; cleared together with the editor runtime. */
305
558
  notify?: (message: string, type?: "info" | "warning" | "error") => void;
306
559
  /** Refused model requests already reported, to avoid repeating them. */
307
560
  reportedModelRefusals: Set<string>;
561
+ /** Process-lifetime state shared with later runtimes of this process. */
562
+ processState: PromptAutocompleteProcessState;
308
563
  /**
309
- * Set once a mount attempt proved whether this host installs custom editors.
564
+ * Projected context entries and the conversation id they belong to.
310
565
  *
311
- * A process cannot change its front-end, so this is deliberately never reset:
312
- * a host that dropped the editor factory once would drop it again. Restarting
313
- * the host is the only way to re-probe.
566
+ * The host projection scans the whole session, every branch included, so it
567
+ * is rebuilt only when a context-relevant entry changes the conversation id —
568
+ * a message, a context edit, a compaction, or a branch switch — and not on
569
+ * every keystroke. Metadata entries such as budget snapshots keep the id.
314
570
  */
315
- hostInstallsEditors?: boolean;
571
+ projectedContextMemo?: { conversationId: string; entries: unknown[] };
316
572
  lastError?: string;
317
573
  lastRawResponse?: string;
318
574
  requestCache: ExpiringLruCache<PromptAutocompleteCacheEntry>;
@@ -320,27 +576,38 @@ interface PromptAutocompleteSharedState {
320
576
  inFlightRequests: Map<string, CoalescedRequestEntry<PromptAutocompleteCacheEntry, string>>;
321
577
  ownsEditor?: () => boolean;
322
578
  refreshEditor?: (options?: SuggestionRefreshOptions) => void;
579
+ /** Pi's keymap as last handed to the editor factory; read by `status`. */
580
+ keybindings?: KeybindingsManager;
323
581
  cancelActiveRequest?: () => void;
582
+ /** Cancel a pending debounce timer without aborting an in-flight provider call. */
583
+ cancelScheduledRequest?: () => void;
584
+ /** The running next-prompt request; a new turn or session makes it stale. */
585
+ nextPromptAbort?: AbortController;
324
586
  setStatusText?: (text: string | undefined) => void;
325
587
  setSpinnerActive?: (owner: string, active: boolean) => void;
326
588
  clearSpinner?: () => void;
327
589
  }
328
590
 
329
- interface SuggestionRequest {
591
+ /** A request snapshot plus the local routing and cache identity around it. */
592
+ interface SuggestionRequest extends PromptAutocompleteRequestSnapshot {
330
593
  activationId: number;
331
- leafId: string;
332
- draft: string;
333
- draftTail: string;
594
+ conversationId: string;
334
595
  model: Model<Api>;
335
596
  modelLabel: string;
336
597
  cacheKey: string;
337
598
  prefixContextKey: string;
338
- maxAlternatives: number;
339
- maxSuggestionChars: number;
599
+ /** Context an Escape dismissal of this request's suggestions is bound to. */
600
+ dismissalContext: string;
340
601
  useStreaming: boolean;
341
- latestAssistantContext: string;
342
- latestUserContext: string;
343
- recentContext: string;
602
+ }
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;
344
611
  }
345
612
 
346
613
  interface PendingSuggestionRequest {
@@ -428,8 +695,103 @@ function matchesAnyKey(data: string, keys: readonly KeyId[]): boolean {
428
695
  return keys.some((key) => matchesKey(data, key));
429
696
  }
430
697
 
431
- function formatPrimaryKey(keys: readonly KeyId[]): string {
432
- return keys[0] ?? "";
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(" | ");
433
795
  }
434
796
 
435
797
  interface SuggestionModelResolution {
@@ -450,11 +812,11 @@ interface SuggestionModelResolution {
450
812
  */
451
813
  function resolveSuggestionModelResolution(
452
814
  shared: PromptAutocompleteSharedState,
815
+ selection: PromptAutocompleteModelSelection = shared.config.modelSelection,
453
816
  ): SuggestionModelResolution {
454
817
  const registry = shared.modelRegistry;
455
818
  if (!registry) return { reason: "No model registry is available yet" };
456
819
 
457
- const selection = shared.config.modelSelection;
458
820
  const requested = describePromptAutocompleteModelSelection(selection);
459
821
 
460
822
  if (selection.kind === "invalid") {
@@ -523,21 +885,33 @@ function parseConfig(pi: ExtensionAPI): PromptAutocompleteConfig {
523
885
  allowWhileStreaming: pi.getFlag("prompt-autocomplete-while-streaming") === true,
524
886
  streamResponses: parseOnOffFlag(pi.getFlag("prompt-autocomplete-stream"), DEFAULT_STREAM_RESPONSES),
525
887
  debug: pi.getFlag("prompt-autocomplete-debug") === true,
526
- debounceMs: parseBoundedIntFlag(pi.getFlag("prompt-autocomplete-debounce-ms"), DEFAULT_DEBOUNCE_MS, 0, 5_000),
527
- minPromptChars: parseBoundedIntFlag(pi.getFlag("prompt-autocomplete-min-chars"), DEFAULT_MIN_PROMPT_CHARS, 0, 500),
888
+ debounceMs: parseBoundedIntFlag(
889
+ pi.getFlag("prompt-autocomplete-debounce-ms"),
890
+ DEFAULT_DEBOUNCE_MS,
891
+ DEBOUNCE_MS_MIN,
892
+ DEBOUNCE_MS_MAX,
893
+ ),
894
+ minPromptChars: parseBoundedIntFlag(
895
+ pi.getFlag("prompt-autocomplete-min-chars"),
896
+ DEFAULT_MIN_PROMPT_CHARS,
897
+ MIN_PROMPT_CHARS_MIN,
898
+ MIN_PROMPT_CHARS_MAX,
899
+ ),
528
900
  maxSuggestionChars: parseBoundedIntFlag(
529
901
  pi.getFlag("prompt-autocomplete-max-chars"),
530
902
  DEFAULT_MAX_SUGGESTION_CHARS,
531
- 16,
532
- 1_000,
903
+ MAX_SUGGESTION_CHARS_MIN,
904
+ MAX_SUGGESTION_CHARS_MAX,
533
905
  ),
534
906
  maxAlternatives: parseBoundedIntFlag(
535
907
  pi.getFlag("prompt-autocomplete-max-alternatives"),
536
908
  DEFAULT_MAX_ALTERNATIVES,
537
- 1,
538
- 5,
909
+ MAX_ALTERNATIVES_MIN,
910
+ MAX_ALTERNATIVES_MAX,
539
911
  ),
540
912
  modelSelection: parsePromptAutocompleteModelSelection(pi.getFlag("prompt-autocomplete-model")),
913
+ budgetLimit: parsePromptAutocompleteBudgetFlag(pi.getFlag("prompt-autocomplete-max-requests")),
914
+ nextPrompt: pi.getFlag("prompt-autocomplete-next-prompt") === true,
541
915
  };
542
916
  }
543
917
 
@@ -564,6 +938,26 @@ function applyEffectiveConfig(pi: ExtensionAPI, shared: PromptAutocompleteShared
564
938
  MIN_PROMPT_CHARS_MIN,
565
939
  MIN_PROMPT_CHARS_MAX,
566
940
  );
941
+ shared.debounceMsFlagExplicit = parseExplicitBoundedIntFlag(
942
+ pi.getFlag("prompt-autocomplete-debounce-ms"),
943
+ DEFAULT_DEBOUNCE_MS,
944
+ DEBOUNCE_MS_MIN,
945
+ DEBOUNCE_MS_MAX,
946
+ );
947
+ shared.maxSuggestionCharsFlagExplicit = parseExplicitBoundedIntFlag(
948
+ pi.getFlag("prompt-autocomplete-max-chars"),
949
+ DEFAULT_MAX_SUGGESTION_CHARS,
950
+ MAX_SUGGESTION_CHARS_MIN,
951
+ MAX_SUGGESTION_CHARS_MAX,
952
+ );
953
+ shared.maxAlternativesFlagExplicit = parseExplicitBoundedIntFlag(
954
+ pi.getFlag("prompt-autocomplete-max-alternatives"),
955
+ DEFAULT_MAX_ALTERNATIVES,
956
+ MAX_ALTERNATIVES_MIN,
957
+ MAX_ALTERNATIVES_MAX,
958
+ );
959
+ shared.modelFlagExplicit = parseExplicitModelFlag(pi.getFlag("prompt-autocomplete-model"));
960
+ shared.budgetFlagExplicit = parsePromptAutocompleteBudgetFlag(pi.getFlag("prompt-autocomplete-max-requests"));
567
961
  shared.config = {
568
962
  ...flagConfig,
569
963
  allowWhileStreaming: resolveOverride(
@@ -576,8 +970,36 @@ function applyEffectiveConfig(pi: ExtensionAPI, shared: PromptAutocompleteShared
576
970
  shared.runtimeOverrides.minPromptChars,
577
971
  shared.minPromptCharsFlagExplicit,
578
972
  shared.persistedSettings.minPromptChars,
579
- flagConfig.minPromptChars,
973
+ DEFAULT_MIN_PROMPT_CHARS,
974
+ ).value,
975
+ debounceMs: resolvePersistedNumber(
976
+ shared.runtimeOverrides.debounceMs,
977
+ shared.debounceMsFlagExplicit,
978
+ shared.persistedSettings.debounceMs,
979
+ DEFAULT_DEBOUNCE_MS,
980
+ ).value,
981
+ maxSuggestionChars: resolvePersistedNumber(
982
+ shared.runtimeOverrides.maxSuggestionChars,
983
+ shared.maxSuggestionCharsFlagExplicit,
984
+ shared.persistedSettings.maxSuggestionChars,
985
+ DEFAULT_MAX_SUGGESTION_CHARS,
580
986
  ).value,
987
+ maxAlternatives: resolvePersistedNumber(
988
+ shared.runtimeOverrides.maxAlternatives,
989
+ shared.maxAlternativesFlagExplicit,
990
+ shared.persistedSettings.maxAlternatives,
991
+ DEFAULT_MAX_ALTERNATIVES,
992
+ ).value,
993
+ modelSelection: resolvePersistedModelSelection(
994
+ shared.runtimeOverrides.modelSelection,
995
+ shared.modelFlagExplicit,
996
+ parsePersistedModelRaw(shared.persistedSettings.model),
997
+ ).selection,
998
+ budgetLimit: resolvePromptAutocompleteBudgetLimit(
999
+ shared.runtimeOverrides.budgetLimit,
1000
+ shared.budgetFlagExplicit,
1001
+ shared.savedBudgetLimit,
1002
+ ).limit,
581
1003
  };
582
1004
  }
583
1005
 
@@ -611,18 +1033,24 @@ function clearDebugUi(shared: PromptAutocompleteSharedState): void {
611
1033
  shared.setStatusText?.(undefined);
612
1034
  }
613
1035
 
614
- function formatStatus(shared: PromptAutocompleteSharedState): string {
1036
+ function describeEditorState(shared: PromptAutocompleteSharedState, interactiveHost: boolean): string {
1037
+ if (!interactiveHost) return "unavailable";
1038
+ if (shared.editorMount) return shared.ownsEditor?.() ? "mounted" : "ownership-lost";
1039
+ return shared.editorBlockedReason ? "blocked" : "unmounted";
1040
+ }
1041
+
1042
+ /**
1043
+ * Compact one-line status. `interactiveHost` is false only for the read-only
1044
+ * status a non-interactive host (for example RPC) may request; there the
1045
+ * editor is reported as unavailable instead of merely unmounted.
1046
+ */
1047
+ function formatStatus(shared: PromptAutocompleteSharedState, interactiveHost = true): string {
615
1048
  const resolvedModel = resolveSuggestionModel(shared);
616
- const editorState = shared.editorMount
617
- ? shared.ownsEditor?.()
618
- ? "mounted"
619
- : "ownership-lost"
620
- : shared.editorBlockedReason
621
- ? "blocked"
622
- : "unmounted";
1049
+ const editorState = describeEditorState(shared, interactiveHost);
623
1050
  const requestedModel = describePromptAutocompleteModelSelection(shared.config.modelSelection);
624
1051
 
625
1052
  return [
1053
+ interactiveHost ? undefined : "host=non-interactive",
626
1054
  `enabled=${shared.enabled ? "yes" : "no"}(${
627
1055
  resolvePersistedEnabled(
628
1056
  shared.runtimeOverrides.enabled,
@@ -633,12 +1061,25 @@ function formatStatus(shared: PromptAutocompleteSharedState): string {
633
1061
  `editor=${editorState}`,
634
1062
  shared.editorBlockedReason ? `editor-blocked=${truncateDebug(shared.editorBlockedReason, 90)}` : undefined,
635
1063
  `model=${truncateDebug(formatModelLabel(resolvedModel), 90)}`,
636
- `requested-model=${requestedModel}`,
1064
+ `requested-model=${requestedModel}(${
1065
+ resolvePersistedModelSelection(
1066
+ shared.runtimeOverrides.modelSelection,
1067
+ shared.modelFlagExplicit,
1068
+ parsePersistedModelRaw(shared.persistedSettings.model),
1069
+ ).source
1070
+ })`,
637
1071
  `while-streaming=${shared.config.allowWhileStreaming ? "yes" : "no"}(${describeSettingSource(shared.runtimeOverrides.allowWhileStreaming)})`,
638
1072
  `stream=${shared.config.streamResponses ? "yes" : "no"}(${describeSettingSource(shared.runtimeOverrides.streamResponses)})`,
639
1073
  `request-path=${shared.config.streamResponses && shared.streamSimple ? "stream" : shared.config.streamResponses ? "complete-compat" : "complete"}`,
640
1074
  `debug=${shared.config.debug ? "yes" : "no"}(${describeSettingSource(shared.runtimeOverrides.debug)})`,
641
- `debounce=${shared.config.debounceMs}ms`,
1075
+ `debounce=${shared.config.debounceMs}ms(${
1076
+ resolvePersistedNumber(
1077
+ shared.runtimeOverrides.debounceMs,
1078
+ shared.debounceMsFlagExplicit,
1079
+ shared.persistedSettings.debounceMs,
1080
+ DEFAULT_DEBOUNCE_MS,
1081
+ ).source
1082
+ })`,
642
1083
  `min-chars=${shared.config.minPromptChars}(${
643
1084
  resolvePersistedNumber(
644
1085
  shared.runtimeOverrides.minPromptChars,
@@ -647,19 +1088,161 @@ function formatStatus(shared: PromptAutocompleteSharedState): string {
647
1088
  DEFAULT_MIN_PROMPT_CHARS,
648
1089
  ).source
649
1090
  })`,
650
- `max-suggestion-chars=${shared.config.maxSuggestionChars}`,
651
- `max-alternatives=${shared.config.maxAlternatives}`,
1091
+ `max-suggestion-chars=${shared.config.maxSuggestionChars}(${
1092
+ resolvePersistedNumber(
1093
+ shared.runtimeOverrides.maxSuggestionChars,
1094
+ shared.maxSuggestionCharsFlagExplicit,
1095
+ shared.persistedSettings.maxSuggestionChars,
1096
+ DEFAULT_MAX_SUGGESTION_CHARS,
1097
+ ).source
1098
+ })`,
1099
+ `max-alternatives=${shared.config.maxAlternatives}(${
1100
+ resolvePersistedNumber(
1101
+ shared.runtimeOverrides.maxAlternatives,
1102
+ shared.maxAlternativesFlagExplicit,
1103
+ shared.persistedSettings.maxAlternatives,
1104
+ DEFAULT_MAX_ALTERNATIVES,
1105
+ ).source
1106
+ })`,
652
1107
  `cache-size=${shared.requestCache.size}`,
1108
+ `budget=${formatBudget(shared)}`,
653
1109
  `usage=${formatUsageStats(shared.usageStats)}`,
654
1110
  `state=${shared.debugState || "idle"}`,
655
1111
  shared.lastError ? `error=${truncateDebug(shared.lastError, 90)}` : undefined,
656
1112
  shared.lastRawResponse ? `raw=${truncateDebug(shared.lastRawResponse, 90)}` : undefined,
657
- `keys=tab accept | ${formatPrimaryKey(WORD_ACCEPT_KEYS)} word | ${formatPrimaryKey(CYCLE_PREV_KEYS)}/${formatPrimaryKey(CYCLE_NEXT_KEYS)} cycle | ${formatPrimaryKey(CYCLE_NEXT_KEYS)} force one-shot`,
1113
+ interactiveHost ? `keys=${formatKeyHints(shared.keymap).status}` : undefined,
1114
+ interactiveHost ? formatKeysUsedByPi(shared) : undefined,
658
1115
  ]
659
1116
  .filter((value): value is string => !!value)
660
1117
  .join(" | ");
661
1118
  }
662
1119
 
1120
+ const INSPECT_EXCERPT_CHARS = 120;
1121
+
1122
+ function formatInspectionSection(label: string, text: string, cap: string): string {
1123
+ if (!text) return `${label}: none`;
1124
+ return `${label}: ${text.length} chars sent (${cap}): "${truncateDebug(text, INSPECT_EXCERPT_CHARS)}"`;
1125
+ }
1126
+
1127
+ /**
1128
+ * The shared gates a request must pass, in production order.
1129
+ *
1130
+ * Only state shared by every editor instance is evaluated. Cursor position,
1131
+ * the built-in autocomplete menu, Escape dismissal, the per-editor error
1132
+ * cooldown, and cached responses belong to the live editor and are not.
1133
+ */
1134
+ function evaluateSharedRequestPolicy(
1135
+ shared: PromptAutocompleteSharedState,
1136
+ interactiveHost: boolean,
1137
+ draft: string | undefined,
1138
+ ): { automatic?: string; manual?: string } {
1139
+ const blocks: Array<{ reason: string; manualToo: boolean }> = [];
1140
+ if (!shared.enabled) blocks.push({ reason: "autocomplete is disabled", manualToo: true });
1141
+ if (!interactiveHost) {
1142
+ blocks.push({ reason: "this host has no interactive editor", manualToo: true });
1143
+ } else if (!shared.editorMount || !shared.ownsEditor?.()) {
1144
+ blocks.push({ reason: "the autocomplete editor is not active", manualToo: true });
1145
+ }
1146
+ if (!shared.config.allowWhileStreaming && shared.agentStreaming) {
1147
+ blocks.push({ reason: "the main agent is working", manualToo: false });
1148
+ }
1149
+ const resolution = resolveSuggestionModelResolution(shared);
1150
+ if (!resolution.model) {
1151
+ blocks.push({
1152
+ reason: resolution.reason ?? "no usable autocomplete model with configured auth",
1153
+ manualToo: true,
1154
+ });
1155
+ }
1156
+ if (draft !== undefined) {
1157
+ if (draft.trim().length < shared.config.minPromptChars) {
1158
+ blocks.push({ reason: `the draft is shorter than min-chars (${shared.config.minPromptChars})`, manualToo: false });
1159
+ }
1160
+ if (shouldSkipPromptAutocomplete(draft)) {
1161
+ blocks.push({ reason: "the draft looks like a slash command or path", manualToo: true });
1162
+ }
1163
+ }
1164
+ if (isBudgetExhausted(shared)) {
1165
+ blocks.push({
1166
+ reason: `the session budget is exhausted (${shared.budgetUsed}/${shared.config.budgetLimit})`,
1167
+ manualToo: true,
1168
+ });
1169
+ }
1170
+ return {
1171
+ automatic: blocks[0]?.reason,
1172
+ manual: blocks.find((block) => block.manualToo)?.reason,
1173
+ };
1174
+ }
1175
+
1176
+ /**
1177
+ * Local, bounded preview of what an autocomplete request would transmit.
1178
+ *
1179
+ * It renders the same snapshot the provider path uses and makes no provider
1180
+ * request. Without explicit draft text it reports the conversation sections
1181
+ * only: the submitted slash command replaced the editor text, so the draft a
1182
+ * real request would carry cannot be recovered and is not invented.
1183
+ */
1184
+ function formatPromptAutocompleteInspection(
1185
+ shared: PromptAutocompleteSharedState,
1186
+ interactiveHost: boolean,
1187
+ draft: string | undefined,
1188
+ ): string {
1189
+ const snapshot = buildCurrentRequestSnapshot(shared, draft ?? "", resolveCurrentConversationId(shared));
1190
+ const resolution = resolveSuggestionModelResolution(shared);
1191
+ const requestedSource = resolvePersistedModelSelection(
1192
+ shared.runtimeOverrides.modelSelection,
1193
+ shared.modelFlagExplicit,
1194
+ parsePersistedModelRaw(shared.persistedSettings.model),
1195
+ ).source;
1196
+ const policy = evaluateSharedRequestPolicy(shared, interactiveHost, draft);
1197
+ const mainAgent = shared.agentStreaming
1198
+ ? shared.config.allowWhileStreaming ? "working (requests allowed)" : "working"
1199
+ : "idle";
1200
+ const verdict = (reason: string | undefined) =>
1201
+ reason ? `blocked (${truncateDebug(reason, 120)})` : "allowed";
1202
+
1203
+ const draftLine = draft === undefined
1204
+ ? "Draft: not available — the slash command replaced the editor text. "
1205
+ + "Run /prompt-autocomplete inspect <draft text> to preview one."
1206
+ : `Draft: ${snapshot.draft.length} chars, ${snapshot.draftTail.length} sent `
1207
+ + `(only the last ${MAX_DRAFT_CONTEXT_CHARS} are sent): "${truncateDebug(snapshot.draftTail, INSPECT_EXCERPT_CHARS)}"`;
1208
+ const sizeLine = draft === undefined
1209
+ ? `Request size: system prompt ${PROMPT_AUTOCOMPLETE_SYSTEM_PROMPT.length} chars + one user message whose size depends on the draft`
1210
+ : `Request size: system prompt ${PROMPT_AUTOCOMPLETE_SYSTEM_PROMPT.length} chars + user message `
1211
+ + `${renderPromptAutocompleteUserText(snapshot).length} chars`;
1212
+
1213
+ return [
1214
+ "Prompt Autocomplete — request inspection (local only; no provider request was made)",
1215
+ `Model: ${truncateDebug(formatModelLabel(resolution.model), 90)} · requested `
1216
+ + `${describePromptAutocompleteModelSelection(shared.config.modelSelection)}(${requestedSource})`,
1217
+ `Shared policy: automatic ${verdict(policy.automatic)} · manual ${verdict(policy.manual)}`,
1218
+ ` enabled=${shared.enabled ? "yes" : "no"} editor=${describeEditorState(shared, interactiveHost)} `
1219
+ + `main-agent=${mainAgent} auth=${resolution.model ? "configured" : "unavailable"} budget=${formatBudget(shared)}`,
1220
+ draftLine,
1221
+ formatInspectionSection(
1222
+ "Latest assistant message",
1223
+ snapshot.latestAssistantContext,
1224
+ `cap ${MAX_LATEST_ASSISTANT_MESSAGE_CHARS}`,
1225
+ ),
1226
+ formatInspectionSection("Latest user message", snapshot.latestUserContext, `cap ${MAX_LATEST_USER_MESSAGE_CHARS}`),
1227
+ formatInspectionSection(
1228
+ "Recent conversation",
1229
+ snapshot.recentContext,
1230
+ `up to ${MAX_CONTEXT_MESSAGES} messages × ${MAX_CONTEXT_MESSAGE_CHARS} chars`,
1231
+ ),
1232
+ formatInspectionSection(
1233
+ "Compaction summary",
1234
+ snapshot.compactionSummaryContext,
1235
+ `cap ${MAX_COMPACTION_SUMMARY_CHARS}, middle elided`,
1236
+ ),
1237
+ sizeLine,
1238
+ `Output: up to ${snapshot.maxAlternatives} alternatives × ${snapshot.maxSuggestionChars} chars, `
1239
+ + `at most ${computeRequestMaxTokens(snapshot.maxAlternatives, snapshot.maxSuggestionChars)} output tokens`,
1240
+ "Not evaluated here (live editor state): cursor position, built-in autocomplete menu, "
1241
+ + "Escape dismissal, error cooldown, cached responses.",
1242
+ "The conversation id used for caching is local metadata and is never sent; credentials and headers are never shown.",
1243
+ ].join("\n");
1244
+ }
1245
+
663
1246
  function cloneCacheEntry(entry: PromptAutocompleteCacheEntry): PromptAutocompleteCacheEntry {
664
1247
  return { ...entry, suggestions: [...entry.suggestions] };
665
1248
  }
@@ -740,7 +1323,10 @@ class PromptAutocompleteEditor extends CustomEditor {
740
1323
  // shared spinner alive until every active owner has released it.
741
1324
  private activeSpinnerOwner?: string;
742
1325
  private suspendedUntil = 0;
743
- private dismissedKey?: string;
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;
744
1330
 
745
1331
  constructor(
746
1332
  tui: TUI,
@@ -767,23 +1353,33 @@ class PromptAutocompleteEditor extends CustomEditor {
767
1353
 
768
1354
  override handleInput(data: string): void {
769
1355
  if (this.canDismissInlineSuggestion(data)) {
770
- this.dismissedKey = this.buildRequest()?.cacheKey;
771
- this.clearInlineSuggestion("dismissed", "Suggestion dismissed for current draft");
772
- return;
773
- }
774
-
775
- if (this.canCycleSuggestions(data)) {
776
- this.cycleSuggestions(matchesAnyKey(data, CYCLE_NEXT_KEYS) ? 1 : -1);
777
- return;
778
- }
779
-
780
- if (this.canTriggerManualSuggestion(data)) {
781
- 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");
782
1364
  return;
783
1365
  }
784
1366
 
785
- if (this.canAcceptInlineSuggestionByWord(data)) {
786
- this.acceptInlineSuggestionByWord();
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);
787
1383
  return;
788
1384
  }
789
1385
 
@@ -794,19 +1390,42 @@ class PromptAutocompleteEditor extends CustomEditor {
794
1390
 
795
1391
  this.clearInlineSuggestionForUserIntent(data);
796
1392
 
797
- const beforeText = this.getText();
798
- const beforeCursor = this.getCursor();
799
- const beforeAutocomplete = this.isShowingAutocomplete();
800
-
1393
+ const before = this.captureInputState();
801
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
+ }
802
1406
 
803
- const afterText = this.getText();
804
- const afterCursor = this.getCursor();
805
- const afterAutocomplete = this.isShowingAutocomplete();
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
+ }
1418
+
1419
+ private captureInputState(): EditorInputState {
1420
+ return { text: this.getText(), cursor: this.getCursor(), autocomplete: this.isShowingAutocomplete() };
1421
+ }
806
1422
 
807
- const textChanged = beforeText !== afterText;
808
- const cursorChanged = beforeCursor.line !== afterCursor.line || beforeCursor.col !== afterCursor.col;
809
- const autocompleteChanged = beforeAutocomplete !== afterAutocomplete;
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;
810
1429
 
811
1430
  if (textChanged || cursorChanged || autocompleteChanged) {
812
1431
  this.refreshSuggestion({ clearExisting: true });
@@ -828,8 +1447,9 @@ class PromptAutocompleteEditor extends CustomEditor {
828
1447
  let cursorLineIndex = -1;
829
1448
  let cursorMatch: RegExpMatchArray | undefined;
830
1449
  for (let index = 0; index < lines.length; index++) {
831
- if (!lines[index]!.includes(CURSOR_INVERSE_SPACE)) continue;
832
- const match = lines[index]!.match(CURSOR_TOKEN_PATTERN);
1450
+ const line = lines[index]!;
1451
+ if (!CURSOR_CELL_OPENERS.some((opener) => line.includes(opener))) continue;
1452
+ const match = line.match(CURSOR_CELL_PATTERN);
833
1453
  if (match?.index !== undefined) {
834
1454
  cursorLineIndex = index;
835
1455
  cursorMatch = match;
@@ -841,7 +1461,11 @@ class PromptAutocompleteEditor extends CustomEditor {
841
1461
  const cursorLine = lines[cursorLineIndex]!;
842
1462
  const cursorIndex = cursorMatch.index;
843
1463
  const cursorToken = cursorMatch[0];
844
- const cursorReset = cursorMatch[1] === "27" ? "\x1b[27m" : "\x1b[0m";
1464
+ // The cell holds one space and no escape sequence contains a space, so the
1465
+ // space separates the opening sequence from the closing one.
1466
+ const cursorSpace = cursorToken.indexOf(" ");
1467
+ const cursorOpen = cursorToken.slice(0, cursorSpace);
1468
+ const cursorClose = cursorToken.slice(cursorSpace + 1);
845
1469
 
846
1470
  const before = cursorLine.slice(0, cursorIndex);
847
1471
  const after = cursorLine.slice(cursorIndex + cursorToken.length);
@@ -853,7 +1477,9 @@ class PromptAutocompleteEditor extends CustomEditor {
853
1477
  const firstPreviewChar = previewChars[0] ?? "";
854
1478
  const absorbLeadingWhitespaceIntoCursor = /^[ \t]$/.test(firstPreviewChar);
855
1479
 
856
- const cursorCell = absorbLeadingWhitespaceIntoCursor ? `\x1b[7m${firstPreviewChar}${cursorReset}` : cursorToken;
1480
+ const cursorCell = absorbLeadingWhitespaceIntoCursor
1481
+ ? `${cursorOpen}${firstPreviewChar}${cursorClose}`
1482
+ : cursorToken;
857
1483
  const renderedPreviewText = absorbLeadingWhitespaceIntoCursor ? previewChars.slice(1).join("") : previewText;
858
1484
 
859
1485
  const indicator = this.suggestions.length > 1 ? ` ‹${this.suggestionIndex + 1}/${this.suggestions.length}›` : "";
@@ -916,8 +1542,15 @@ class PromptAutocompleteEditor extends CustomEditor {
916
1542
 
917
1543
  private setSuggestions(
918
1544
  nextSuggestions: string[],
919
- options: { provisional?: boolean; origins?: string[]; preferredOrigin?: string } = {},
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
+ } = {},
920
1552
  ): void {
1553
+ this.suggestionsContext = nextSuggestions.length > 0 ? options.context : undefined;
921
1554
  const provisional = options.provisional ?? false;
922
1555
  const nextOrigins = options.origins?.length === nextSuggestions.length
923
1556
  ? [...options.origins]
@@ -970,13 +1603,33 @@ class PromptAutocompleteEditor extends CustomEditor {
970
1603
  this.tui.requestRender();
971
1604
  }
972
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
+
973
1626
  private cycleSuggestions(delta: 1 | -1): void {
974
1627
  if (this.suggestions.length <= 1) return;
975
1628
  const nextIndex = (this.suggestionIndex + delta + this.suggestions.length) % this.suggestions.length;
976
1629
  if (nextIndex === this.suggestionIndex) return;
977
1630
  this.suggestionIndex = nextIndex;
978
1631
  this.shared.usageStats.suggestionsOffered += 1;
979
- this.dismissedKey = undefined;
1632
+ this.dismissal = undefined;
980
1633
  updateDebugState(this.shared, "cycled", `Now showing ${nextIndex + 1}/${this.suggestions.length}`);
981
1634
  this.tui.requestRender();
982
1635
  }
@@ -987,13 +1640,13 @@ class PromptAutocompleteEditor extends CustomEditor {
987
1640
  private canTriggerManualSuggestion(data: string): boolean {
988
1641
  if (!this.shared.enabled || this.activationId !== this.shared.activationId) return false;
989
1642
  if (this.isShowingAutocomplete()) return false;
990
- return matchesAnyKey(data, CYCLE_NEXT_KEYS);
1643
+ return matchesAnyKey(data, this.shared.keymap.keys.cycleNext);
991
1644
  }
992
1645
 
993
1646
  private triggerManualSuggestion(): void {
994
1647
  // refreshSuggestion immediately sets its own debug state, so we only clear any
995
1648
  // standing dismissal here and let the refresh report the real outcome.
996
- this.dismissedKey = undefined;
1649
+ this.dismissal = undefined;
997
1650
  this.refreshSuggestion({ clearExisting: true, immediate: true, manual: true });
998
1651
  }
999
1652
 
@@ -1005,14 +1658,15 @@ class PromptAutocompleteEditor extends CustomEditor {
1005
1658
  return this.shouldRenderInlineSuggestion() && !!this.getActiveSuggestion() && matchesKey(data, "tab");
1006
1659
  }
1007
1660
 
1008
- private canAcceptInlineSuggestionByWord(data: string): boolean {
1009
- return this.shouldRenderInlineSuggestion() && !!this.getActiveSuggestion() && matchesAnyKey(data, WORD_ACCEPT_KEYS);
1661
+ private canAcceptInlineSuggestionPart(data: string, keys: readonly KeyId[]): boolean {
1662
+ return this.shouldRenderInlineSuggestion() && !!this.getActiveSuggestion() && matchesAnyKey(data, keys);
1010
1663
  }
1011
1664
 
1012
1665
  private canCycleSuggestions(data: string): boolean {
1013
1666
  if (!this.shouldRenderInlineSuggestion()) return false;
1014
1667
  if (this.suggestions.length <= 1) return false;
1015
- return matchesAnyKey(data, CYCLE_NEXT_KEYS) || matchesAnyKey(data, CYCLE_PREV_KEYS);
1668
+ const { cycleNext, cyclePrev } = this.shared.keymap.keys;
1669
+ return matchesAnyKey(data, cycleNext) || matchesAnyKey(data, cyclePrev);
1016
1670
  }
1017
1671
 
1018
1672
  private clearInlineSuggestion(state: string, details: string): void {
@@ -1054,7 +1708,7 @@ class PromptAutocompleteEditor extends CustomEditor {
1054
1708
 
1055
1709
  const wasProvisional = this.suggestionsProvisional;
1056
1710
  this.shared.usageStats.fullAccepts += 1;
1057
- this.dismissedKey = undefined;
1711
+ this.dismissal = undefined;
1058
1712
  this.clearInlineSuggestion("accepted", wasProvisional ? "Accepted streamed partial suggestion" : "Accepted full suggestion");
1059
1713
  super.insertTextAtCursor(suggestion);
1060
1714
  // A provisional accept is explicit cancellation of the request. Starting a
@@ -1065,15 +1719,30 @@ class PromptAutocompleteEditor extends CustomEditor {
1065
1719
  private acceptInlineSuggestionByWord(): void {
1066
1720
  const suggestion = this.getActiveSuggestion();
1067
1721
  if (!suggestion) return;
1722
+ this.acceptInlineSuggestionPart(extractNextSuggestionChunk(suggestion) ?? suggestion, "accepted-word");
1723
+ }
1068
1724
 
1069
- const origin = this.getActiveSuggestionOrigin();
1070
- const chunk = extractNextSuggestionChunk(suggestion) ?? suggestion;
1071
- if (!chunk) return;
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
+ }
1072
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();
1073
1742
  const wasProvisional = this.suggestionsProvisional;
1074
1743
  this.shared.usageStats.chunkAccepts += 1;
1075
- this.dismissedKey = undefined;
1076
- this.clearInlineSuggestion("accepted-word", `Accepted chunk: ${chunk}`);
1744
+ this.dismissal = undefined;
1745
+ this.clearInlineSuggestion(state, `Accepted chunk: ${chunk}`);
1077
1746
  super.insertTextAtCursor(chunk);
1078
1747
  if (!wasProvisional) this.refreshSuggestion({ preferredOrigin: origin });
1079
1748
  }
@@ -1127,6 +1796,9 @@ class PromptAutocompleteEditor extends CustomEditor {
1127
1796
 
1128
1797
  private refreshSuggestion(options: SuggestionRefreshOptions = {}): void {
1129
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();
1130
1802
  if (options.clearExisting) {
1131
1803
  this.cancelPendingRequest();
1132
1804
  this.setSuggestions([]);
@@ -1140,9 +1812,15 @@ class PromptAutocompleteEditor extends CustomEditor {
1140
1812
  }
1141
1813
 
1142
1814
  if (!this.shared.ownsEditor?.()) {
1815
+ this.releaseForOwnershipLoss();
1816
+ return;
1817
+ }
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) {
1143
1822
  this.cancelPendingRequest();
1144
- this.shared.editorBlockedReason = "Another extension replaced the prompt-autocomplete editor";
1145
- updateDebugState(this.shared, "ownership-lost", this.shared.editorBlockedReason);
1823
+ updateDebugState(this.shared, "dismissed", "Suggestion dismissed while this draft continues");
1146
1824
  this.setSuggestions([]);
1147
1825
  return;
1148
1826
  }
@@ -1170,13 +1848,6 @@ class PromptAutocompleteEditor extends CustomEditor {
1170
1848
  return;
1171
1849
  }
1172
1850
 
1173
- if (!options.manual && request.cacheKey === this.dismissedKey) {
1174
- this.cancelPendingRequest();
1175
- updateDebugState(this.shared, "dismissed", "Suggestion dismissed for current draft");
1176
- this.setSuggestions([]);
1177
- return;
1178
- }
1179
-
1180
1851
  const cachedEntry = getCachedRequest(this.shared, request.cacheKey, { bypass: options.manual });
1181
1852
  if (cachedEntry) {
1182
1853
  this.shared.usageStats.cacheHits += 1;
@@ -1190,6 +1861,7 @@ class PromptAutocompleteEditor extends CustomEditor {
1190
1861
  this.setSuggestions(cachedEntry.suggestions, {
1191
1862
  origins: cachedEntry.suggestions,
1192
1863
  preferredOrigin,
1864
+ context: request.dismissalContext,
1193
1865
  });
1194
1866
  return;
1195
1867
  }
@@ -1204,6 +1876,7 @@ class PromptAutocompleteEditor extends CustomEditor {
1204
1876
  this.setSuggestions(prefixReused.entry.suggestions, {
1205
1877
  origins: prefixReused.origins,
1206
1878
  preferredOrigin,
1879
+ context: request.dismissalContext,
1207
1880
  });
1208
1881
  updateDebugState(
1209
1882
  this.shared,
@@ -1219,6 +1892,22 @@ class PromptAutocompleteEditor extends CustomEditor {
1219
1892
  }
1220
1893
 
1221
1894
  const shouldJoinInFlight = this.shared.inFlightRequests.has(request.cacheKey);
1895
+
1896
+ // Cache hits and joins of existing work stay free above the ceiling; only a
1897
+ // request that would start new provider work is blocked here. The producer
1898
+ // still re-checks and reserves, which is what makes concurrency safe.
1899
+ if (!shouldJoinInFlight && isBudgetExhausted(this.shared)) {
1900
+ this.cancelPendingRequest();
1901
+ updateDebugState(
1902
+ this.shared,
1903
+ "budget-exhausted",
1904
+ `Session request budget exhausted (${this.shared.budgetUsed}/${this.shared.config.budgetLimit})`,
1905
+ );
1906
+ notifyBudgetExhaustedOnce(this.shared);
1907
+ this.setSuggestions([]);
1908
+ return;
1909
+ }
1910
+
1222
1911
  this.cancelPendingRequest();
1223
1912
 
1224
1913
  const seq = ++this.requestSeq;
@@ -1247,44 +1936,7 @@ class PromptAutocompleteEditor extends CustomEditor {
1247
1936
  }
1248
1937
 
1249
1938
  private buildRequest(): SuggestionRequest | undefined {
1250
- const model = resolveSuggestionModel(this.shared);
1251
- if (!model) return undefined;
1252
-
1253
- const draft = this.getText();
1254
- const branch = this.shared.sessionManager?.getBranch?.() ?? [];
1255
- const latestAssistantContext = buildLatestAssistantMessageContext(branch);
1256
- const latestUserContext = buildLatestUserMessageContext(branch);
1257
- const recentContext = buildRecentConversationContext(branch);
1258
- const draftTail = truncateDraftTail(draft, MAX_DRAFT_CONTEXT_CHARS);
1259
- const modelLabel = formatModelLabel(model);
1260
- const leafId = this.shared.sessionManager?.getLeafId?.() ?? "";
1261
-
1262
- const prefixContextIdentity = {
1263
- leafId,
1264
- modelLabel,
1265
- maxAlternatives: this.shared.config.maxAlternatives,
1266
- maxSuggestionChars: this.shared.config.maxSuggestionChars,
1267
- latestAssistantContext,
1268
- latestUserContext,
1269
- recentContext,
1270
- };
1271
-
1272
- return {
1273
- activationId: this.activationId,
1274
- leafId,
1275
- draft,
1276
- draftTail,
1277
- model,
1278
- modelLabel,
1279
- cacheKey: buildPromptAutocompleteCacheKey({ ...prefixContextIdentity, draft }),
1280
- prefixContextKey: buildPromptAutocompletePrefixContextKey(prefixContextIdentity),
1281
- maxAlternatives: this.shared.config.maxAlternatives,
1282
- maxSuggestionChars: this.shared.config.maxSuggestionChars,
1283
- useStreaming: this.shared.config.streamResponses && !!this.shared.streamSimple,
1284
- latestAssistantContext,
1285
- latestUserContext,
1286
- recentContext,
1287
- };
1939
+ return buildSuggestionRequest(this.shared, this.getText(), this.activationId);
1288
1940
  }
1289
1941
 
1290
1942
  private async fetchSuggestion(request: SuggestionRequest, seq: number, spinnerOwner: string): Promise<void> {
@@ -1299,7 +1951,7 @@ class PromptAutocompleteEditor extends CustomEditor {
1299
1951
  this.shared.inFlightRequests,
1300
1952
  request.cacheKey,
1301
1953
  subscriberId,
1302
- (signal, publish) => this.fetchSuggestionUncached(request, signal, publish),
1954
+ (signal, publish) => fetchSuggestionUncached(this.shared, request, signal, publish),
1303
1955
  (suggestion) => this.showStreamedSuggestion(request, seq, spinnerOwner, suggestion),
1304
1956
  );
1305
1957
 
@@ -1315,6 +1967,7 @@ class PromptAutocompleteEditor extends CustomEditor {
1315
1967
  try {
1316
1968
  const entry = await subscription.promise;
1317
1969
  if (!this.isRequestStillCurrent(request, seq)) {
1970
+ if (seq === this.requestSeq && !this.shared.ownsEditor?.()) this.releaseForOwnershipLoss();
1318
1971
  return;
1319
1972
  }
1320
1973
 
@@ -1324,11 +1977,22 @@ class PromptAutocompleteEditor extends CustomEditor {
1324
1977
  if (entry.suggestions.length === 0) {
1325
1978
  updateDebugState(this.shared, "no-suggestion", entry.debugState || "No usable suggestions");
1326
1979
  }
1327
- if (request.cacheKey !== this.dismissedKey) {
1328
- this.setSuggestions(entry.suggestions);
1980
+ if (!this.dismissalCovers(request)) {
1981
+ this.setSuggestions(entry.suggestions, { context: request.dismissalContext });
1329
1982
  }
1330
1983
  } catch (error) {
1331
- if (this.isRequestStillCurrent(request, seq)) {
1984
+ if (error instanceof PromptAutocompleteBudgetExhaustedError) {
1985
+ // Not a provider failure: no cooldown, no failure stat, no provider call.
1986
+ if (this.isRequestStillCurrent(request, seq)) {
1987
+ updateDebugState(
1988
+ this.shared,
1989
+ "budget-exhausted",
1990
+ `Session request budget exhausted (${this.shared.budgetUsed}/${this.shared.config.budgetLimit})`,
1991
+ );
1992
+ notifyBudgetExhaustedOnce(this.shared);
1993
+ this.setSuggestions([]);
1994
+ }
1995
+ } else if (this.isRequestStillCurrent(request, seq)) {
1332
1996
  this.suspendedUntil = this.shared.now() + FAILURE_COOLDOWN_MS;
1333
1997
  const message = error instanceof Error ? error.message : String(error);
1334
1998
  this.shared.lastError = message;
@@ -1351,200 +2015,83 @@ class PromptAutocompleteEditor extends CustomEditor {
1351
2015
  spinnerOwner: string,
1352
2016
  suggestion: string,
1353
2017
  ): void {
2018
+ // A replaced editor receives no more input, so streamed progress is the
2019
+ // first boundary at which it can notice. Release the provider work here
2020
+ // instead of letting it run to completion for an editor nobody renders.
2021
+ if (seq === this.requestSeq && !this.shared.ownsEditor?.()) {
2022
+ this.releaseForOwnershipLoss();
2023
+ return;
2024
+ }
1354
2025
  if (!this.isRequestStillCurrent(request, seq)) return;
1355
- if (request.cacheKey === this.dismissedKey) return;
2026
+ if (this.dismissalCovers(request)) return;
1356
2027
 
1357
2028
  const current = this.getActiveSuggestion();
1358
2029
  // Progress is strictly monotonic. If a provider revises earlier text, keep
1359
2030
  // the last honest preview and let the terminal response replace it.
1360
2031
  if (current && (!suggestion.startsWith(current) || suggestion.length <= current.length)) return;
1361
2032
 
1362
- this.setSuggestions([suggestion], { provisional: true });
2033
+ this.setSuggestions([suggestion], { provisional: true, context: request.dismissalContext });
1363
2034
  this.deactivateSpinner(spinnerOwner);
1364
2035
  }
1365
2036
 
1366
- private async fetchSuggestionUncached(
1367
- request: SuggestionRequest,
1368
- signal: AbortSignal,
1369
- publish: (suggestion: string) => void,
1370
- ): Promise<PromptAutocompleteCacheEntry> {
1371
- if (!this.shared.modelRegistry) {
1372
- throw new Error("No model registry available");
1373
- }
2037
+ private isRequestStillCurrent(request: SuggestionRequest, seq: number): boolean {
2038
+ if (!this.shared.enabled) return false;
2039
+ if (!this.shared.ownsEditor?.()) return false;
2040
+ if (this.activationId !== this.shared.activationId) return false;
2041
+ if (seq !== this.requestSeq) return false;
2042
+ if (request.activationId !== this.activationId) return false;
2043
+ if (!this.isCursorAtEndOfDraft()) return false;
2044
+ if (this.getText() !== request.draft) return false;
2045
+ if (this.isShowingAutocomplete()) return false;
1374
2046
 
1375
- const auth = await this.shared.modelRegistry.getApiKeyAndHeaders(request.model);
1376
- if (!auth.ok || !auth.apiKey) {
1377
- throw new Error(auth.ok ? `No API key for ${request.modelLabel}` : auth.error);
1378
- }
1379
- if (signal.aborted) {
1380
- throw new Error("Request was aborted");
1381
- }
2047
+ const currentModel = resolveSuggestionModel(this.shared);
2048
+ if (formatModelLabel(currentModel) !== request.modelLabel) return false;
1382
2049
 
1383
- const sections: string[] = [];
1384
- if (request.latestAssistantContext) {
1385
- sections.push(`Latest assistant message (primary context):\n${request.latestAssistantContext}`);
1386
- }
1387
- if (request.latestUserContext) {
1388
- sections.push(`Latest user message:\n${request.latestUserContext}`);
1389
- }
1390
- if (request.recentContext) {
1391
- sections.push(`Recent conversation summary:\n${request.recentContext}`);
1392
- }
1393
-
1394
- if (request.draft.length === 0) {
1395
- sections.push("Current draft is empty.");
1396
- sections.push(
1397
- [
1398
- `Task: propose up to ${request.maxAlternatives} ranked full next prompts the user could send now.`,
1399
- "Each item must be a complete next prompt, not a continuation fragment.",
1400
- "Suggest the prompt most likely to move the overall project forward.",
1401
- "Prefer 3-10 words when possible.",
1402
- ].join("\n"),
1403
- );
1404
- } else {
1405
- if (request.draftTail.length < request.draft.length) {
1406
- sections.push(
1407
- `Current draft tail (the real draft is longer; the cursor is at the end of the full draft):\n${request.draftTail}`,
1408
- );
1409
- } else {
1410
- sections.push(`Current draft (cursor at end):\n${request.draft}`);
1411
- }
1412
-
1413
- sections.push(
1414
- [
1415
- `Task: propose up to ${request.maxAlternatives} ranked continuations to insert at the cursor.`,
1416
- "Each item must be only the text after the cursor; never restate text the user already typed.",
1417
- "If the draft ends inside a partially typed word, complete that word directly without a leading space.",
1418
- ].join("\n"),
1419
- );
1420
- }
1421
-
1422
- const userMessage: UserMessage = {
1423
- role: "user",
1424
- content: [{ type: "text", text: sections.join("\n\n") }],
1425
- timestamp: Date.now(),
1426
- };
1427
-
1428
- const stats = this.shared.usageStats;
1429
- stats.providerRequests += 1;
1430
-
1431
- const context = {
1432
- systemPrompt: PROMPT_AUTOCOMPLETE_SYSTEM_PROMPT,
1433
- messages: [userMessage],
1434
- };
1435
- const requestOptions = {
1436
- apiKey: auth.apiKey,
1437
- headers: auth.headers,
1438
- signal,
1439
- maxTokens: computeRequestMaxTokens(request.maxAlternatives, request.maxSuggestionChars),
1440
- timeoutMs: REQUEST_TIMEOUT_MS,
1441
- maxRetries: REQUEST_MAX_RETRIES,
1442
- maxRetryDelayMs: REQUEST_MAX_RETRY_DELAY_MS,
1443
- };
1444
-
1445
- const providerStartedAt = this.shared.now();
1446
- let response: AssistantMessage;
1447
- try {
1448
- if (request.useStreaming && this.shared.streamSimple) {
1449
- const hardDeadlineController = new AbortController();
1450
- const streamSignal = AbortSignal.any([signal, hardDeadlineController.signal]);
1451
- const stream = this.shared.streamSimple(request.model, context, {
1452
- ...requestOptions,
1453
- signal: streamSignal,
1454
- });
1455
- let lastPublished = "";
1456
-
1457
- // Exactly one consumer receives the terminal message. Partial text is
1458
- // fanned out through coalescing; after UI cancellation the callback is
1459
- // gone, but the bounded drain can still retain terminal usage.
1460
- response = await consumeAssistantStream(stream, streamSignal, () => hardDeadlineController.abort(), (partial) => {
1461
- // `partial` is cumulative. Appending delta plus text_end.content would
1462
- // duplicate the completed block on providers that emit both.
1463
- const partialText = extractAssistantText(partial);
1464
- const suggestion = parsePartialPromptSuggestion(request.draft, partialText, request.maxSuggestionChars);
1465
- if (!suggestion || suggestion === lastPublished) return;
1466
- if (lastPublished && !suggestion.startsWith(lastPublished)) return;
1467
- lastPublished = suggestion;
1468
- publish(suggestion);
1469
- });
1470
- } else {
1471
- response = await this.shared.completeSimple(request.model, context, requestOptions);
1472
- }
1473
- } catch (error) {
1474
- stats.failedRequests += 1;
1475
- throw error;
1476
- } finally {
1477
- recordProviderLatency(stats, this.shared.now() - providerStartedAt);
1478
- }
1479
-
1480
- // Tokens spent on a failed or aborted response are still spent, so usage is
1481
- // recorded before the stop-reason check rejects the request.
1482
- recordProviderUsage(stats, response.usage);
1483
-
1484
- const contentTypes = response.content.map((block) => block.type).join(", ") || "(none)";
1485
- const text = extractAssistantText(response);
1486
-
1487
- const responseError = response.errorMessage?.trim();
1488
- const rawResponse = text || responseError || `[types=${contentTypes}; stopReason=${response.stopReason}]`;
1489
-
1490
- if (response.stopReason === "error" || response.stopReason === "aborted") {
1491
- stats.failedRequests += 1;
1492
- throw new Error(responseError || `Provider returned stopReason=${response.stopReason}`);
1493
- }
1494
- if (signal.aborted) {
1495
- stats.failedRequests += 1;
1496
- throw new Error("Request was aborted");
1497
- }
1498
-
1499
- const normalized = normalizePromptSuggestions(
1500
- request.draft,
1501
- text,
1502
- request.maxSuggestionChars,
1503
- request.maxAlternatives,
1504
- );
1505
-
1506
- const debugState =
1507
- normalized.length === 0
1508
- ? text || `No text blocks returned (types: ${contentTypes}; stopReason: ${response.stopReason})`
1509
- : `${normalized.length} suggestion(s) ready`;
1510
-
1511
- return storeCachedRequest(this.shared, request.cacheKey, {
1512
- draft: request.draft,
1513
- prefixContextKey: request.prefixContextKey,
1514
- suggestions: normalized,
1515
- rawResponse,
1516
- debugState,
1517
- });
1518
- }
1519
-
1520
- private isRequestStillCurrent(request: SuggestionRequest, seq: number): boolean {
1521
- if (!this.shared.enabled) return false;
1522
- if (!this.shared.ownsEditor?.()) return false;
1523
- if (this.activationId !== this.shared.activationId) return false;
1524
- if (seq !== this.requestSeq) return false;
1525
- if (request.activationId !== this.activationId) return false;
1526
- if (!this.isCursorAtEndOfDraft()) return false;
1527
- if (this.getText() !== request.draft) return false;
1528
- if (this.isShowingAutocomplete()) return false;
1529
-
1530
- const currentModel = resolveSuggestionModel(this.shared);
1531
- if (formatModelLabel(currentModel) !== request.modelLabel) return false;
1532
-
1533
- // Session entries are immutable and the leaf identifies the exact branch
1534
- // from which all bounded context sections were derived. Checking it avoids
1535
- // rebuilding/scanning and hashing that context for every streamed token.
1536
- return (this.shared.sessionManager?.getLeafId?.() ?? "") === request.leafId;
1537
- }
2050
+ // Session entries are immutable. The context-relevant conversation id
2051
+ // identifies the branch from which all bounded context sections were
2052
+ // derived, without treating custom/label/session-info leaf movement as a
2053
+ // new conversation. Checking it avoids rebuilding that context per token.
2054
+ return resolveCurrentConversationId(this.shared) === request.conversationId;
2055
+ }
1538
2056
 
1539
2057
  cancelActiveRequest(): void {
1540
2058
  this.cancelPendingRequest();
1541
2059
  this.setSuggestions([]);
1542
2060
  }
1543
2061
 
2062
+ /**
2063
+ * Drop a waiting debounce without aborting an in-flight provider call.
2064
+ *
2065
+ * A debounce-only config change must not increment the request sequence or
2066
+ * release the active subscription: those belong to work that already started.
2067
+ */
2068
+ cancelScheduledRequest(): void {
2069
+ if (!this.debounceTimer) return;
2070
+ clearTimeout(this.debounceTimer);
2071
+ this.debounceTimer = undefined;
2072
+ const pending = this.pendingRequests.take();
2073
+ this.deactivateSpinner(pending?.spinnerOwner);
2074
+ }
2075
+
1544
2076
  private clearPendingRequestIfOwned(seq: number): void {
1545
2077
  this.pendingRequests.clearIfOwned(seq);
1546
2078
  }
1547
2079
 
2080
+ /**
2081
+ * Stop owned work after another extension replaced this editor.
2082
+ *
2083
+ * Pi exposes no editor-change event, so loss is only noticed at the next
2084
+ * boundary this instance observes: an edit, streamed progress, or a terminal
2085
+ * response. A provider that never yields cannot be interrupted earlier. The
2086
+ * foreign editor is never touched.
2087
+ */
2088
+ private releaseForOwnershipLoss(): void {
2089
+ this.cancelPendingRequest();
2090
+ this.shared.editorBlockedReason = "Another extension replaced the prompt-autocomplete editor";
2091
+ updateDebugState(this.shared, "ownership-lost", this.shared.editorBlockedReason);
2092
+ this.setSuggestions([]);
2093
+ }
2094
+
1548
2095
  private cancelPendingRequest(): void {
1549
2096
  this.requestSeq += 1;
1550
2097
 
@@ -1561,6 +2108,138 @@ class PromptAutocompleteEditor extends CustomEditor {
1561
2108
  }
1562
2109
  }
1563
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
+
1564
2243
  function releaseEditorRuntime(shared: PromptAutocompleteSharedState): void {
1565
2244
  shared.cancelActiveRequest?.();
1566
2245
  shared.activationId += 1;
@@ -1569,6 +2248,7 @@ function releaseEditorRuntime(shared: PromptAutocompleteSharedState): void {
1569
2248
  clearDebugUi(shared);
1570
2249
  shared.refreshEditor = undefined;
1571
2250
  shared.cancelActiveRequest = undefined;
2251
+ shared.cancelScheduledRequest = undefined;
1572
2252
  shared.setStatusText = undefined;
1573
2253
  shared.setSpinnerActive = undefined;
1574
2254
  shared.clearSpinner = undefined;
@@ -1586,7 +2266,7 @@ function releaseEditorRuntime(shared: PromptAutocompleteSharedState): void {
1586
2266
  function hostOwnsInteractiveEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): boolean {
1587
2267
  // A host that already accepted an editor factory without installing it is not
1588
2268
  // interactive, no matter what its capabilities claim.
1589
- if (shared.hostInstallsEditors === false) return false;
2269
+ if (shared.processState.hostInstallsEditors === false) return false;
1590
2270
  const host = ctx as Partial<Pick<ExtensionContext, "mode" | "hasUI" | "ui">>;
1591
2271
  return isInteractiveEditorHost({
1592
2272
  mode: host.mode,
@@ -1676,6 +2356,7 @@ function mountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedStat
1676
2356
 
1677
2357
  const installedFactory: EditorFactory = (tui, theme, keybindings) => {
1678
2358
  const editor = new PromptAutocompleteEditor(tui, theme, keybindings, shared, activationId);
2359
+ shared.keybindings = keybindings;
1679
2360
  shared.refreshEditor = (options) => {
1680
2361
  if (activationId !== shared.activationId) return;
1681
2362
  editor.refreshFromExternalChange(options);
@@ -1684,6 +2365,10 @@ function mountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedStat
1684
2365
  if (activationId !== shared.activationId) return;
1685
2366
  editor.cancelActiveRequest();
1686
2367
  };
2368
+ shared.cancelScheduledRequest = () => {
2369
+ if (activationId !== shared.activationId) return;
2370
+ editor.cancelScheduledRequest();
2371
+ };
1687
2372
  return editor;
1688
2373
  };
1689
2374
 
@@ -1704,7 +2389,7 @@ function mountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedStat
1704
2389
  if (ctx.ui.getEditorComponent() !== installedFactory) {
1705
2390
  releaseEditorRuntime(shared);
1706
2391
  shared.editorMount = undefined;
1707
- shared.hostInstallsEditors = false;
2392
+ shared.processState.hostInstallsEditors = false;
1708
2393
  // Nothing can render or request here, so the extension must not stay marked
1709
2394
  // enabled, no matter which path attempted the mount.
1710
2395
  shared.enabled = false;
@@ -1717,7 +2402,7 @@ function mountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedStat
1717
2402
  return false;
1718
2403
  }
1719
2404
 
1720
- shared.hostInstallsEditors = true;
2405
+ shared.processState.hostInstallsEditors = true;
1721
2406
  updateDebugState(shared, "mounted", "Editor extension attached");
1722
2407
  return true;
1723
2408
  }
@@ -1738,11 +2423,22 @@ function unmountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedSt
1738
2423
 
1739
2424
  function resetSharedForSession(pi: ExtensionAPI, shared: PromptAutocompleteSharedState): void {
1740
2425
  shared.cancelActiveRequest?.();
2426
+ cancelNextPrompt(shared);
1741
2427
  shared.cancelActiveRequest = undefined;
2428
+ shared.cancelScheduledRequest = undefined;
2429
+ // Budget accounting is physical-session scoped: a new session starts fresh.
2430
+ // Clearing before applyEffectiveConfig keeps the effective ceiling from
2431
+ // silently inheriting the previous session's restored value; session_start
2432
+ // restores this session's own snapshot right afterwards.
2433
+ shared.budgetUsed = 0;
2434
+ shared.savedBudgetLimit = undefined;
2435
+ shared.persistBudgetSnapshot = undefined;
2436
+ shared.budgetSnapshotsActive = false;
2437
+ shared.budgetBlockNotices.clear();
1742
2438
  applyEffectiveConfig(pi, shared);
1743
2439
  // A host that never installs custom editors stays inactive for the rest of
1744
2440
  // the process, so flags must not re-enable it in a later session either.
1745
- if (shared.hostInstallsEditors === false) shared.enabled = false;
2441
+ if (shared.processState.hostInstallsEditors === false) shared.enabled = false;
1746
2442
  shared.usageStats = createPromptAutocompleteUsageStats();
1747
2443
  shared.editorMount = undefined;
1748
2444
  shared.editorBlockedReason = undefined;
@@ -1750,6 +2446,7 @@ function resetSharedForSession(pi: ExtensionAPI, shared: PromptAutocompleteShare
1750
2446
  shared.lastError = undefined;
1751
2447
  shared.lastRawResponse = undefined;
1752
2448
  shared.reportedModelRefusals.clear();
2449
+ shared.projectedContextMemo = undefined;
1753
2450
  shared.requestCache.clear();
1754
2451
  shared.prefixReuseCache.clear();
1755
2452
  cancelAllCoalescedRequests(shared.inFlightRequests);
@@ -1760,7 +2457,187 @@ function bindRuntimeContext(ctx: ExtensionContext, shared: PromptAutocompleteSha
1760
2457
  shared.currentModel = ctx.model as Model<Api> | undefined;
1761
2458
  shared.modelRegistry = ctx.modelRegistry;
1762
2459
  shared.sessionManager = ctx.sessionManager;
2460
+ shared.physicalSessionId = readPhysicalSessionId(ctx);
2461
+ shared.lastConversationId = resolveCurrentConversationId(shared);
2462
+ rememberAgentSettledSupport(ctx, shared);
2463
+ shared.agentStreaming = false;
2464
+ }
2465
+
2466
+ function readPhysicalSessionId(ctx: ExtensionContext): string {
2467
+ const sessionId = ctx.sessionManager?.getSessionId?.();
2468
+ return typeof sessionId === "string" ? sessionId : "";
2469
+ }
2470
+
2471
+ /**
2472
+ * The request snapshot for `draft` against the model-visible conversation and
2473
+ * the output configuration. Shared by the editor's provider path and by
2474
+ * inspection, so both read the same context source.
2475
+ */
2476
+ function buildCurrentRequestSnapshot(
2477
+ shared: PromptAutocompleteSharedState,
2478
+ draft: string,
2479
+ conversationId: string,
2480
+ maxAlternatives = shared.config.maxAlternatives,
2481
+ ): PromptAutocompleteRequestSnapshot {
2482
+ return buildPromptAutocompleteRequestSnapshot({
2483
+ draft,
2484
+ branch: readAutocompleteContextEntries(shared, conversationId),
2485
+ maxAlternatives,
2486
+ maxSuggestionChars: shared.config.maxSuggestionChars,
2487
+ });
2488
+ }
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
+
2533
+ /**
2534
+ * Conversation entries autocomplete may draw context from.
2535
+ *
2536
+ * Hosts with a session projection (Pi 1.x) supply the model-visible context,
2537
+ * so messages omitted or replaced by `context_edit` stay out of autocomplete
2538
+ * requests as well. A projection that throws yields no conversation context
2539
+ * instead of the raw branch. Older hosts have no context edits, so their raw
2540
+ * branch is used as before.
2541
+ *
2542
+ * Autocomplete context covers user and assistant message text plus, on hosts
2543
+ * with a projection, the newest compaction summary; the projection decides
2544
+ * which of those the model still sees and in which form. Compaction system
2545
+ * checkpoints, branch summaries, custom messages, and tool results are never
2546
+ * included.
2547
+ */
2548
+ function readAutocompleteContextEntries(shared: PromptAutocompleteSharedState, conversationId: string): unknown[] {
2549
+ const manager = shared.sessionManager;
2550
+ if (typeof manager?.buildSessionProjection === "function") {
2551
+ const memo = shared.projectedContextMemo;
2552
+ if (memo?.conversationId === conversationId) return memo.entries;
2553
+ try {
2554
+ const entries = projectAutocompleteContextEntries(manager.buildSessionProjection());
2555
+ shared.projectedContextMemo = { conversationId, entries };
2556
+ return entries;
2557
+ } catch {
2558
+ return [];
2559
+ }
2560
+ }
2561
+ return manager?.getBranch?.() ?? [];
2562
+ }
2563
+
2564
+ function resolveCurrentConversationId(shared: PromptAutocompleteSharedState): string {
2565
+ const branch = shared.sessionManager?.getBranch?.() ?? [];
2566
+ const leafId = shared.sessionManager?.getLeafId?.() ?? "";
2567
+ return resolveAutocompleteConversationId(branch, leafId || shared.physicalSessionId);
2568
+ }
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
+
2592
+ function rememberAgentSettledSupport(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): void {
2593
+ if (shared.hostEmitsAgentSettled !== undefined) return;
2594
+ shared.hostEmitsAgentSettled = typeof ctx.isIdle === "function";
2595
+ }
2596
+
2597
+ function settleAgentTurn(shared: PromptAutocompleteSharedState, details: string): void {
1763
2598
  shared.agentStreaming = false;
2599
+ if (!shared.enabled) return;
2600
+ refreshEditorImmediately(shared, "ready", details);
2601
+ }
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;
1764
2641
  }
1765
2642
 
1766
2643
  function refreshEditorImmediately(shared: PromptAutocompleteSharedState, state: string, details: string): void {
@@ -1842,6 +2719,68 @@ function setStreamResponses(
1842
2719
  }
1843
2720
  }
1844
2721
 
2722
+ function describeBudget(shared: PromptAutocompleteSharedState): { value: string; source: string } {
2723
+ const resolution = resolvePromptAutocompleteBudgetLimit(
2724
+ shared.runtimeOverrides.budgetLimit,
2725
+ shared.budgetFlagExplicit,
2726
+ shared.savedBudgetLimit,
2727
+ );
2728
+ return {
2729
+ value: resolution.limit === undefined ? "off" : `${shared.budgetUsed}/${resolution.limit}`,
2730
+ source: resolution.source,
2731
+ };
2732
+ }
2733
+
2734
+ function formatBudget(shared: PromptAutocompleteSharedState): string {
2735
+ const { value, source } = describeBudget(shared);
2736
+ return `${value}(${source})`;
2737
+ }
2738
+
2739
+ /**
2740
+ * Set the session request ceiling.
2741
+ *
2742
+ * The decision is session-scoped by design: it is snapshotted into the current
2743
+ * session's entries, never into the process-wide settings file.
2744
+ */
2745
+ function setBudgetLimit(
2746
+ ctx: ExtensionContext,
2747
+ shared: PromptAutocompleteSharedState,
2748
+ arg: string | undefined,
2749
+ ): void {
2750
+ const parsed = parsePromptAutocompleteBudgetValue(arg);
2751
+ if (parsed.kind === "unset") {
2752
+ const { value, source } = describeBudget(shared);
2753
+ ctx.ui.notify(
2754
+ `Prompt autocomplete budget is ${value} (${source}); ${shared.budgetUsed} provider request${
2755
+ shared.budgetUsed === 1 ? "" : "s"
2756
+ } used this session`,
2757
+ "info",
2758
+ );
2759
+ return;
2760
+ }
2761
+ if (parsed.kind === "invalid") {
2762
+ ctx.ui.notify(
2763
+ `Usage: /prompt-autocomplete budget <${BUDGET_REQUESTS_MIN}-${BUDGET_REQUESTS_MAX}|off>`,
2764
+ "warning",
2765
+ );
2766
+ return;
2767
+ }
2768
+
2769
+ shared.runtimeOverrides.budgetLimit = parsed.kind === "off" ? "off" : parsed.value;
2770
+ const nextLimit = parsed.kind === "off" ? undefined : parsed.value;
2771
+ // Only a real transition is a new exhaustion state worth reporting again.
2772
+ if (nextLimit !== shared.config.budgetLimit) shared.budgetBlockNotices.clear();
2773
+ shared.config.budgetLimit = nextLimit;
2774
+ persistBudgetSnapshot(shared);
2775
+ updateDebugState(shared, "configured", `Budget ${formatBudget(shared)}`);
2776
+ ctx.ui.notify(
2777
+ parsed.kind === "off"
2778
+ ? `Prompt autocomplete budget off (${shared.budgetUsed} request${shared.budgetUsed === 1 ? "" : "s"} used this session)`
2779
+ : `Prompt autocomplete budget set to ${parsed.value} provider request${parsed.value === 1 ? "" : "s"} per session (${shared.budgetUsed} used)`,
2780
+ "info",
2781
+ );
2782
+ }
2783
+
1845
2784
  function setMinPromptChars(
1846
2785
  ctx: ExtensionContext,
1847
2786
  shared: PromptAutocompleteSharedState,
@@ -1873,9 +2812,11 @@ function setMinPromptChars(
1873
2812
  const changed = shared.config.minPromptChars !== parsed;
1874
2813
  shared.config.minPromptChars = parsed;
1875
2814
  shared.runtimeOverrides.minPromptChars = parsed;
1876
- persistSettingsDecision(ctx, shared, { minPromptChars: parsed });
2815
+ const persisted = persistSettingsDecision(ctx, shared, { minPromptChars: parsed });
1877
2816
  ctx.ui.notify(
1878
- `Prompt autocomplete min-chars set to ${parsed} (saved for future sessions)`,
2817
+ `Prompt autocomplete min-chars set to ${parsed}${
2818
+ persisted ? " (saved for future sessions)" : " (session only — could not save for future sessions)"
2819
+ }`,
1879
2820
  "info",
1880
2821
  );
1881
2822
 
@@ -1894,19 +2835,386 @@ function persistSettingsDecision(
1894
2835
  ctx: ExtensionContext,
1895
2836
  shared: PromptAutocompleteSharedState,
1896
2837
  patch: Partial<PromptAutocompletePersistedSettings>,
1897
- ): void {
1898
- shared.persistedSettings = { ...shared.persistedSettings, ...patch };
2838
+ ): boolean {
2839
+ shared.persistedSettings = applyPromptAutocompleteSettingsPatch(shared.persistedSettings, patch);
1899
2840
  const store = shared.settingsStore;
1900
- if (!store) return;
2841
+ if (!store) return false;
1901
2842
  try {
1902
- store.save(shared.persistedSettings);
2843
+ store.update(patch);
2844
+ return true;
1903
2845
  } catch (error) {
1904
2846
  const reason = error instanceof Error ? error.message : String(error);
1905
2847
  ctx.ui.notify(
1906
2848
  `Prompt autocomplete could not save the setting: ${truncateDebug(reason, 90)}`,
1907
2849
  "warning",
1908
2850
  );
2851
+ return false;
2852
+ }
2853
+ }
2854
+
2855
+ function isBudgetExhausted(shared: PromptAutocompleteSharedState): boolean {
2856
+ return shared.config.budgetLimit !== undefined && shared.budgetUsed >= shared.config.budgetLimit;
2857
+ }
2858
+
2859
+ function notifyBudgetExhaustedOnce(shared: PromptAutocompleteSharedState): void {
2860
+ const limit = shared.config.budgetLimit;
2861
+ if (limit === undefined) return;
2862
+ const key = `${shared.budgetUsed}/${limit}`;
2863
+ if (shared.budgetBlockNotices.has(key)) return;
2864
+ shared.budgetBlockNotices.add(key);
2865
+ shared.notify?.(
2866
+ `Prompt autocomplete session budget exhausted (${shared.budgetUsed}/${limit} provider requests). `
2867
+ + "Raise it with /prompt-autocomplete budget <n> or disable it with /prompt-autocomplete budget off.",
2868
+ "warning",
2869
+ );
2870
+ }
2871
+
2872
+ /**
2873
+ * Authoritative budget admission inside a request producer.
2874
+ *
2875
+ * Called synchronously after the last await (successful auth) and before the
2876
+ * provider invocation, so two concurrent producers can never both pass a
2877
+ * limit of one. Failed and aborted calls keep their reservation; auth
2878
+ * failures never reach this point and consume nothing.
2879
+ *
2880
+ * Every real invocation advances the physical-session count, including while
2881
+ * the ceiling is off: enabling a ceiling later must not hand out an allowance
2882
+ * that ignores what this session already spent. Snapshots are written while a
2883
+ * ceiling exists and, once this session carries durable budget state, also for
2884
+ * uncapped invocations — so a session that never touched the budget still adds
2885
+ * no session entries.
2886
+ */
2887
+ function reserveBudgetRequest(shared: PromptAutocompleteSharedState): boolean {
2888
+ const limit = shared.config.budgetLimit;
2889
+ if (limit !== undefined && shared.budgetUsed >= limit) return false;
2890
+ shared.budgetUsed += 1;
2891
+ if (limit !== undefined || shared.budgetSnapshotsActive) persistBudgetSnapshot(shared);
2892
+ return true;
2893
+ }
2894
+
2895
+ function persistBudgetSnapshot(shared: PromptAutocompleteSharedState): void {
2896
+ if (!shared.physicalSessionId || !shared.persistBudgetSnapshot) return;
2897
+ shared.budgetSnapshotsActive = true;
2898
+ shared.persistBudgetSnapshot(
2899
+ shared.config.budgetLimit === undefined ? "off" : shared.config.budgetLimit,
2900
+ shared.budgetUsed,
2901
+ );
2902
+ }
2903
+
2904
+ /**
2905
+ * Restore this physical session's budget from its own entries and bind the
2906
+ * snapshot writer for the session.
2907
+ *
2908
+ * `/reload` and `/resume` re-run `session_start` on the same session file, so
2909
+ * the session's own snapshots re-establish usage and the ceiling; `/new` and
2910
+ * `/fork` start a session whose entries hold no (or foreign) snapshots and
2911
+ * begin with a fresh budget. Hosts without `appendEntry` keep the in-process
2912
+ * ceiling without durable snapshots.
2913
+ */
2914
+ function restoreBudgetFromSession(pi: ExtensionAPI, shared: PromptAutocompleteSharedState): void {
2915
+ const snapshot = findPromptAutocompleteBudgetSnapshot(
2916
+ readSessionEntries(shared),
2917
+ shared.physicalSessionId,
2918
+ );
2919
+ if (snapshot) {
2920
+ shared.budgetUsed = snapshot.used;
2921
+ shared.savedBudgetLimit = snapshot.limit;
2922
+ // This session already accounts durably: keep it that way even if the
2923
+ // restored decision is an explicit off.
2924
+ shared.budgetSnapshotsActive = true;
2925
+ }
2926
+ // Always recompute: resetSharedForSession cleared the previous session's
2927
+ // restored ceiling, so the effective config must follow even when this
2928
+ // session has no snapshot of its own.
2929
+ applyEffectiveConfig(pi, shared);
2930
+ if (typeof pi.appendEntry !== "function") return;
2931
+ shared.persistBudgetSnapshot = (limit, used) => {
2932
+ try {
2933
+ pi.appendEntry(
2934
+ PROMPT_AUTOCOMPLETE_BUDGET_ENTRY_TYPE,
2935
+ buildPromptAutocompleteBudgetSnapshot(limit, used, shared.physicalSessionId),
2936
+ );
2937
+ } catch {
2938
+ // Durability is best-effort: the in-process ceiling still applies.
2939
+ }
2940
+ };
2941
+ }
2942
+
2943
+ /**
2944
+ * Every entry of the current session, falling back to the current branch.
2945
+ *
2946
+ * The ceiling is a physical-session fact, so restoring it must not depend on
2947
+ * the current leaf path: a request paid for on a branch the user later left
2948
+ * was still paid for.
2949
+ */
2950
+ function readSessionEntries(shared: PromptAutocompleteSharedState): unknown[] {
2951
+ const manager = shared.sessionManager as
2952
+ | { getEntries?: () => unknown[]; getBranch?: () => unknown[] }
2953
+ | undefined;
2954
+ const entries = manager?.getEntries?.();
2955
+ if (Array.isArray(entries)) return entries;
2956
+ return manager?.getBranch?.() ?? [];
2957
+ }
2958
+
2959
+ function requestIdentityFingerprint(shared: PromptAutocompleteSharedState): string {
2960
+ return JSON.stringify({
2961
+ model: formatModelLabel(resolveSuggestionModel(shared)),
2962
+ maxAlternatives: shared.config.maxAlternatives,
2963
+ maxSuggestionChars: shared.config.maxSuggestionChars,
2964
+ });
2965
+ }
2966
+
2967
+ function invalidateRequestCaches(shared: PromptAutocompleteSharedState): void {
2968
+ shared.requestCache.clear();
2969
+ shared.prefixReuseCache.clear();
2970
+ cancelAllCoalescedRequests(shared.inFlightRequests);
2971
+ }
2972
+
2973
+ interface ConfigTransaction {
2974
+ apply(): void;
2975
+ persist?: Partial<PromptAutocompletePersistedSettings>;
2976
+ /** When true, abort in-flight work and drop caches. Debounce-only changes stay false. */
2977
+ affectsRequestIdentity: boolean;
2978
+ notify: string;
2979
+ }
2980
+
2981
+ function applyConfigTransaction(
2982
+ ctx: ExtensionContext,
2983
+ shared: PromptAutocompleteSharedState,
2984
+ transaction: ConfigTransaction,
2985
+ ): void {
2986
+ const previousIdentity = requestIdentityFingerprint(shared);
2987
+ transaction.apply();
2988
+ const persisted = transaction.persist
2989
+ ? persistSettingsDecision(ctx, shared, transaction.persist)
2990
+ : false;
2991
+ const identityChanged = transaction.affectsRequestIdentity
2992
+ && requestIdentityFingerprint(shared) !== previousIdentity;
2993
+ if (identityChanged) {
2994
+ shared.cancelActiveRequest?.();
2995
+ invalidateRequestCaches(shared);
2996
+ updateDebugState(shared, "configured", transaction.notify);
2997
+ } else if (!transaction.affectsRequestIdentity) {
2998
+ shared.cancelScheduledRequest?.();
2999
+ updateDebugState(shared, "configured", transaction.notify);
3000
+ }
3001
+ // A failed store write already warned above; the success notice must not
3002
+ // contradict it by claiming the decision is durable.
3003
+ ctx.ui.notify(
3004
+ transaction.persist
3005
+ ? `${transaction.notify}${persisted ? " (saved for future sessions)" : " (session only — could not save for future sessions)"}`
3006
+ : transaction.notify,
3007
+ "info",
3008
+ );
3009
+ }
3010
+
3011
+ function setBoundedConfigField(
3012
+ ctx: ExtensionContext,
3013
+ shared: PromptAutocompleteSharedState,
3014
+ options: {
3015
+ key: string;
3016
+ field: "debounceMs" | "maxSuggestionChars" | "maxAlternatives";
3017
+ min: number;
3018
+ max: number;
3019
+ value: string;
3020
+ affectsRequestIdentity: boolean;
3021
+ },
3022
+ ): void {
3023
+ const parsed = parseStrictBoundedInt(options.value, options.min, options.max);
3024
+ if (parsed === undefined) {
3025
+ ctx.ui.notify(
3026
+ `Usage: /prompt-autocomplete set ${options.key} <${options.min}-${options.max}>`,
3027
+ "warning",
3028
+ );
3029
+ return;
3030
+ }
3031
+ applyConfigTransaction(ctx, shared, {
3032
+ apply: () => {
3033
+ shared.config[options.field] = parsed;
3034
+ shared.runtimeOverrides[options.field] = parsed;
3035
+ },
3036
+ persist: { [options.field]: parsed },
3037
+ affectsRequestIdentity: options.affectsRequestIdentity,
3038
+ notify: `Prompt autocomplete ${options.key} set to ${parsed}`,
3039
+ });
3040
+ }
3041
+
3042
+ function setModelSetting(ctx: ExtensionContext, shared: PromptAutocompleteSharedState, raw: string): void {
3043
+ const selection = parsePromptAutocompleteModelSelection(raw);
3044
+ if (selection.kind === "invalid") {
3045
+ ctx.ui.notify(
3046
+ `Prompt autocomplete model ${describePromptAutocompleteModelSelection(selection)} is not a provider/model reference.`,
3047
+ "warning",
3048
+ );
3049
+ return;
3050
+ }
3051
+
3052
+ if (selection.kind === "dedicated") {
3053
+ const resolution = resolveSuggestionModelResolution(shared, selection);
3054
+ if (!resolution.model) {
3055
+ ctx.ui.notify(
3056
+ resolution.refusedRequest ?? resolution.reason ?? PROMPT_AUTOCOMPLETE_SET_USAGE,
3057
+ "warning",
3058
+ );
3059
+ return;
3060
+ }
3061
+ } else if (shared.currentModel) {
3062
+ // `active` is a selector that follows the session model, so it stays
3063
+ // committable while no model is known yet. Once the target is known it
3064
+ // must be usable: silently switching a working dedicated model to an
3065
+ // unusable active model would cancel live work and deaden autocomplete.
3066
+ const resolution = resolveSuggestionModelResolution(shared, selection);
3067
+ if (!resolution.model) {
3068
+ ctx.ui.notify(
3069
+ `Prompt autocomplete could not set the model to active: ${
3070
+ resolution.reason ?? "the current active model is not usable"
3071
+ }.`,
3072
+ "warning",
3073
+ );
3074
+ return;
3075
+ }
3076
+ }
3077
+
3078
+ // Compare the configured destinations, not the currently usable models: an
3079
+ // unusable old model still defines where requests were meant to go, and the
3080
+ // provider change must restate the privacy notice either way.
3081
+ const configured = shared.config.modelSelection;
3082
+ const currentProvider = configured.kind === "dedicated" ? configured.ref.provider : shared.currentModel?.provider;
3083
+ const nextProvider = selection.kind === "dedicated"
3084
+ ? selection.ref.provider
3085
+ : shared.currentModel?.provider;
3086
+ if (nextProvider && currentProvider && nextProvider !== currentProvider) {
3087
+ ctx.ui.notify(PRIVACY_NOTICE, "info");
1909
3088
  }
3089
+
3090
+ const persisted = persistableModelRaw(selection);
3091
+ applyConfigTransaction(ctx, shared, {
3092
+ apply: () => {
3093
+ shared.config.modelSelection = selection;
3094
+ shared.runtimeOverrides.modelSelection = selection;
3095
+ shared.reportedModelRefusals.clear();
3096
+ },
3097
+ persist: persisted === undefined ? undefined : { model: persisted },
3098
+ affectsRequestIdentity: true,
3099
+ notify: selection.kind === "active"
3100
+ ? "Prompt autocomplete model set to current active model"
3101
+ : `Prompt autocomplete model set to ${describePromptAutocompleteModelSelection(selection)}`,
3102
+ });
3103
+ }
3104
+
3105
+ /** What each `set` key changes; validation bounds come from the grammar. */
3106
+ const SET_KEY_RUNNERS: {
3107
+ [Key in PromptAutocompleteSetKey]: (ctx: ExtensionContext, shared: PromptAutocompleteSharedState, value: string) => void;
3108
+ } = {
3109
+ "debounce-ms": (ctx, shared, value) =>
3110
+ setBoundedSetKey(ctx, shared, "debounce-ms", "debounceMs", value, false),
3111
+ "min-chars": (ctx, shared, value) => setMinPromptChars(ctx, shared, value || undefined),
3112
+ "max-chars": (ctx, shared, value) =>
3113
+ setBoundedSetKey(ctx, shared, "max-chars", "maxSuggestionChars", value, true),
3114
+ "max-alternatives": (ctx, shared, value) =>
3115
+ setBoundedSetKey(ctx, shared, "max-alternatives", "maxAlternatives", value, true),
3116
+ model: (ctx, shared, value) => {
3117
+ if (!value) {
3118
+ ctx.ui.notify("Usage: /prompt-autocomplete set model <provider/model|active>", "warning");
3119
+ return;
3120
+ }
3121
+ setModelSetting(ctx, shared, value);
3122
+ },
3123
+ key: (ctx, shared, value) => setActionKeys(ctx, shared, value),
3124
+ };
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
+
3191
+ function setBoundedSetKey(
3192
+ ctx: ExtensionContext,
3193
+ shared: PromptAutocompleteSharedState,
3194
+ key: "debounce-ms" | "max-chars" | "max-alternatives",
3195
+ field: "debounceMs" | "maxSuggestionChars" | "maxAlternatives",
3196
+ value: string,
3197
+ affectsRequestIdentity: boolean,
3198
+ ): void {
3199
+ const spec = findPromptAutocompleteSetKey(key);
3200
+ if (!spec || !("min" in spec)) return;
3201
+ setBoundedConfigField(ctx, shared, { key, field, min: spec.min, max: spec.max, value, affectsRequestIdentity });
3202
+ }
3203
+
3204
+ function handleSetCommand(ctx: ExtensionContext, shared: PromptAutocompleteSharedState, rest: string): void {
3205
+ if (!rest) {
3206
+ ctx.ui.notify(formatStatus(shared), "info");
3207
+ return;
3208
+ }
3209
+ const space = rest.search(/\s/);
3210
+ const key = (space < 0 ? rest : rest.slice(0, space)).toLowerCase();
3211
+ const value = space < 0 ? "" : rest.slice(space + 1).trim();
3212
+ const spec = findPromptAutocompleteSetKey(key);
3213
+ if (!spec) {
3214
+ ctx.ui.notify(PROMPT_AUTOCOMPLETE_SET_USAGE, "warning");
3215
+ return;
3216
+ }
3217
+ SET_KEY_RUNNERS[spec.key](ctx, shared, value);
1910
3218
  }
1911
3219
 
1912
3220
  function persistEnabledDecision(
@@ -1922,7 +3230,7 @@ function enablePromptAutocomplete(ctx: ExtensionContext, shared: PromptAutocompl
1922
3230
  shared.enabled = true;
1923
3231
  shared.runtimeOverrides.enabled = true;
1924
3232
 
1925
- if (!mountEditor(ctx, shared) && shared.hostInstallsEditors === false) {
3233
+ if (!mountEditor(ctx, shared) && shared.processState.hostInstallsEditors === false) {
1926
3234
  // The host accepted the editor factory without installing it. mountEditor
1927
3235
  // already cleared `enabled`; keep it cleared and drop the session override
1928
3236
  // so the refused activation is not replayed as a user decision later.
@@ -1951,13 +3259,10 @@ function notifyPromptAutocompleteEnabled(
1951
3259
  shared: PromptAutocompleteSharedState,
1952
3260
  options: { includeModel: boolean },
1953
3261
  ): void {
1954
- const keyHint =
1955
- `Tab accepts all, ${formatPrimaryKey(WORD_ACCEPT_KEYS)} accepts one word, ` +
1956
- `${formatPrimaryKey(CYCLE_PREV_KEYS)}/${formatPrimaryKey(CYCLE_NEXT_KEYS)} cycle alternatives, ` +
1957
- `${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;
1958
3263
  const resolution = resolveSuggestionModelResolution(shared);
1959
3264
  const resolvedModel = resolution.model;
1960
- const privacyNotice = "Requests send the current draft and recent conversation context to the selected model and may incur provider usage.";
3265
+ const privacyNotice = PRIVACY_NOTICE;
1961
3266
 
1962
3267
  if (!resolvedModel && resolution.refusedRequest) {
1963
3268
  // A refused explicit request must be reported on every enable path,
@@ -1990,92 +3295,158 @@ function notifyPromptAutocompleteEnabled(
1990
3295
  ctx.ui.notify(`Prompt autocomplete enabled. ${keyHint} ${privacyNotice}`, "info");
1991
3296
  }
1992
3297
 
1993
- function createPromptAutocompleteCommandHandlers(
1994
- ctx: ExtensionContext,
1995
- shared: PromptAutocompleteSharedState,
1996
- ): Record<string, () => void> {
1997
- return {
1998
- status: () => {
1999
- ctx.ui.notify(formatStatus(shared), "info");
2000
- },
2001
- stats: () => {
2002
- ctx.ui.notify(formatPromptAutocompleteStats(shared.usageStats), "info");
2003
- },
2004
- "debug-on": () => {
2005
- setDebugDisplay(shared, true);
2006
- ctx.ui.notify("Prompt autocomplete debug display enabled", "info");
2007
- },
2008
- "debug-off": () => {
2009
- setDebugDisplay(shared, false);
2010
- ctx.ui.notify("Prompt autocomplete debug display disabled", "info");
2011
- },
2012
- "debug-toggle": () => {
2013
- const nextDebugEnabled = !shared.config.debug;
2014
- setDebugDisplay(shared, nextDebugEnabled);
2015
- ctx.ui.notify(
2016
- nextDebugEnabled
2017
- ? "Prompt autocomplete debug display enabled"
2018
- : "Prompt autocomplete debug display disabled",
2019
- "info",
2020
- );
2021
- },
2022
- on: () => {
2023
- if (shared.enabled && shared.ownsEditor?.()) {
2024
- // Already in the requested state, but the user still expressed intent:
2025
- // record it so later sessions and processes do not fall back to the flag.
2026
- shared.runtimeOverrides.enabled = true;
2027
- persistEnabledDecision(ctx, shared, true);
2028
- ctx.ui.notify(`Prompt autocomplete already enabled (${formatStatus(shared)})`, "info");
2029
- return;
2030
- }
3298
+ /** Whether the host can show a notification, which read-only commands need. */
3299
+ function hasNotificationChannel(ctx: ExtensionContext): boolean {
3300
+ const host = ctx as Partial<Pick<ExtensionContext, "hasUI" | "ui">>;
3301
+ return host.hasUI === true && typeof host.ui?.notify === "function";
3302
+ }
2031
3303
 
2032
- if (enablePromptAutocomplete(ctx, shared)) {
2033
- persistEnabledDecision(ctx, shared, true);
2034
- notifyPromptAutocompleteEnabled(ctx, shared, { includeModel: true });
2035
- }
2036
- },
2037
- off: () => {
2038
- if (!shared.enabled) {
2039
- shared.runtimeOverrides.enabled = false;
2040
- persistEnabledDecision(ctx, shared, false);
2041
- ctx.ui.notify("Prompt autocomplete is already disabled", "info");
2042
- return;
2043
- }
3304
+ /**
3305
+ * Tell a non-interactive host once per process that an enabled extension
3306
+ * cannot issue requests there, instead of staying silently inert.
3307
+ */
3308
+ function notifyEnabledWithoutEditorOnce(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): void {
3309
+ if (!shared.enabled || shared.config.nextPrompt || shared.processState.nonInteractiveNoticeShown) return;
3310
+ if (hostOwnsInteractiveEditor(ctx, shared) || !hasNotificationChannel(ctx)) return;
3311
+ shared.processState.nonInteractiveNoticeShown = true;
3312
+ ctx.ui.notify(
3313
+ "Prompt autocomplete is enabled, but this host has no interactive editor: no autocomplete requests will be issued.",
3314
+ "info",
3315
+ );
3316
+ }
3317
+
3318
+ /** Parsed command arguments, in the forms the individual commands consume. */
3319
+ interface CommandInput {
3320
+ /** Everything after exactly one separator, verbatim (inspection keeps whitespace). */
3321
+ payload: string;
3322
+ /** The payload trimmed. */
3323
+ rest: string;
3324
+ /** The first whitespace-separated argument, if any. */
3325
+ firstArgument: string | undefined;
3326
+ interactiveHost: boolean;
3327
+ }
3328
+
3329
+ type CommandRunner = (ctx: ExtensionContext, shared: PromptAutocompleteSharedState, input: CommandInput) => void;
3330
+
3331
+ /**
3332
+ * One runner per grammar command. The mapped type makes a command without a
3333
+ * runner, or a runner without a grammar entry, a type error.
3334
+ *
3335
+ * Read-only runners (the grammar marks them) change no settings, overrides,
3336
+ * budget, or stats, mount no editor, and reach no provider seam, which is what
3337
+ * lets them run outside the TUI. Inspection may warm the in-memory projection
3338
+ * memo, a deterministic cache the next request in the same conversation reuses.
3339
+ */
3340
+ const COMMAND_RUNNERS: { [Name in PromptAutocompleteCommandName]: CommandRunner } = {
3341
+ on: (ctx, shared) => {
3342
+ if (shared.enabled && shared.ownsEditor?.()) {
3343
+ // Already in the requested state, but the user still expressed intent:
3344
+ // record it so later sessions and processes do not fall back to the flag.
3345
+ shared.runtimeOverrides.enabled = true;
3346
+ persistEnabledDecision(ctx, shared, true);
3347
+ ctx.ui.notify(`Prompt autocomplete already enabled (${formatStatus(shared)})`, "info");
3348
+ return;
3349
+ }
2044
3350
 
3351
+ if (enablePromptAutocomplete(ctx, shared)) {
3352
+ persistEnabledDecision(ctx, shared, true);
3353
+ notifyPromptAutocompleteEnabled(ctx, shared, { includeModel: true });
3354
+ }
3355
+ },
3356
+ off: (ctx, shared) => {
3357
+ if (!shared.enabled) {
3358
+ shared.runtimeOverrides.enabled = false;
3359
+ persistEnabledDecision(ctx, shared, false);
3360
+ ctx.ui.notify("Prompt autocomplete is already disabled", "info");
3361
+ return;
3362
+ }
3363
+
3364
+ disablePromptAutocomplete(ctx, shared);
3365
+ persistEnabledDecision(ctx, shared, false);
3366
+ ctx.ui.notify("Prompt autocomplete disabled", "info");
3367
+ },
3368
+ toggle: (ctx, shared) => {
3369
+ if (shared.enabled) {
2045
3370
  disablePromptAutocomplete(ctx, shared);
2046
3371
  persistEnabledDecision(ctx, shared, false);
2047
3372
  ctx.ui.notify("Prompt autocomplete disabled", "info");
2048
- },
2049
- toggle: () => {
2050
- if (shared.enabled) {
2051
- disablePromptAutocomplete(ctx, shared);
2052
- persistEnabledDecision(ctx, shared, false);
2053
- ctx.ui.notify("Prompt autocomplete disabled", "info");
2054
- return;
2055
- }
3373
+ return;
3374
+ }
2056
3375
 
2057
- if (enablePromptAutocomplete(ctx, shared)) {
2058
- persistEnabledDecision(ctx, shared, true);
2059
- notifyPromptAutocompleteEnabled(ctx, shared, { includeModel: false });
2060
- }
2061
- },
2062
- };
2063
- }
3376
+ if (enablePromptAutocomplete(ctx, shared)) {
3377
+ persistEnabledDecision(ctx, shared, true);
3378
+ notifyPromptAutocompleteEnabled(ctx, shared, { includeModel: false });
3379
+ }
3380
+ },
3381
+ status: (ctx, shared, { interactiveHost }) => {
3382
+ ctx.ui.notify(formatStatus(shared, interactiveHost), "info");
3383
+ },
3384
+ stats: (ctx, shared) => {
3385
+ const { value, source } = describeBudget(shared);
3386
+ ctx.ui.notify(`${formatPromptAutocompleteStats(shared.usageStats)}\nBudget: ${value} (${source})`, "info");
3387
+ },
3388
+ inspect: (ctx, shared, { payload, interactiveHost }) => {
3389
+ ctx.ui.notify(formatPromptAutocompleteInspection(shared, interactiveHost, payload || undefined), "info");
3390
+ },
3391
+ "min-chars": (ctx, shared, { firstArgument }) => setMinPromptChars(ctx, shared, firstArgument),
3392
+ budget: (ctx, shared, { firstArgument }) => setBudgetLimit(ctx, shared, firstArgument),
3393
+ set: (ctx, shared, { rest }) => handleSetCommand(ctx, shared, rest),
3394
+ keys: (ctx, shared) => ctx.ui.notify(formatKeymap(shared), "info"),
3395
+ stream: (ctx, shared, { firstArgument }) => setStreamResponses(ctx, shared, firstArgument),
3396
+ "while-streaming": (ctx, shared, { firstArgument }) => setWhileStreaming(ctx, shared, firstArgument),
3397
+ "debug-on": (ctx, shared) => {
3398
+ setDebugDisplay(shared, true);
3399
+ ctx.ui.notify("Prompt autocomplete debug display enabled", "info");
3400
+ },
3401
+ "debug-off": (ctx, shared) => {
3402
+ setDebugDisplay(shared, false);
3403
+ ctx.ui.notify("Prompt autocomplete debug display disabled", "info");
3404
+ },
3405
+ "debug-toggle": (ctx, shared) => {
3406
+ const nextDebugEnabled = !shared.config.debug;
3407
+ setDebugDisplay(shared, nextDebugEnabled);
3408
+ ctx.ui.notify(
3409
+ nextDebugEnabled
3410
+ ? "Prompt autocomplete debug display enabled"
3411
+ : "Prompt autocomplete debug display disabled",
3412
+ "info",
3413
+ );
3414
+ },
3415
+ };
2064
3416
 
2065
3417
  export function createPromptAutocompleteExtension(
2066
3418
  dependencies: PromptAutocompleteDependencies = {},
2067
3419
  ): (pi: ExtensionAPI) => void {
2068
- const completeSimpleImpl = dependencies.completeSimple ?? hostCompleteSimple;
2069
3420
  const hostStreaming = hostSupportsStreamedResponses(piAiSimpleApi);
3421
+ const now = dependencies.now ?? Date.now;
3422
+
3423
+ return function promptAutocompleteExtension(pi: ExtensionAPI): void {
3424
+ // Injected seams win; otherwise each request routes through the session's
3425
+ // model registry when it has one, and through the compat functions if not.
3426
+ // The registry is read per request because a new session may bring another.
3427
+ // This one function decides routing for both paths and for the credential
3428
+ // handling in the producer, so they cannot disagree. Any injected seam keeps
3429
+ // the registry out entirely, including for the path that was not injected.
3430
+ const injectedSeams = !!(dependencies.completeSimple || dependencies.streamSimple);
3431
+ const hostRegistryStream = (): RegistryStreamSimple | undefined =>
3432
+ injectedSeams ? undefined : registryStreamSimple(shared.modelRegistry);
3433
+ const routedCompleteSimple: CompleteSimpleFunction = (model, context, options) => {
3434
+ const viaRegistry = hostRegistryStream();
3435
+ return viaRegistry ? viaRegistry(model, context, options).result() : hostCompleteSimple(model, context, options);
3436
+ };
3437
+ const routedStreamSimple: StreamSimpleFunction = (model, context, options) => {
3438
+ const viaRegistry = hostRegistryStream();
3439
+ return viaRegistry ? viaRegistry(model, context, options) : hostStreamSimple(model, context, options);
3440
+ };
3441
+ const completeSimpleImpl = dependencies.completeSimple ?? routedCompleteSimple;
2070
3442
  // Existing deterministic harnesses inject only completeSimple. Never let such
2071
3443
  // a harness fall through to the real network-capable stream implementation.
2072
3444
  const streamSimpleImpl =
2073
3445
  dependencies.streamSimple
2074
- ?? (dependencies.completeSimple || !hostStreaming ? undefined : hostStreamSimple);
2075
- const now = dependencies.now ?? Date.now;
3446
+ ?? (dependencies.completeSimple || !hostStreaming ? undefined : routedStreamSimple);
2076
3447
 
2077
- return function promptAutocompleteExtension(pi: ExtensionAPI): void {
2078
- const settingsStore = dependencies.settingsStore ?? createFileSettingsStore(resolvePromptAutocompleteSettingsPath());
3448
+ const settingsStore = dependencies.settingsStore
3449
+ ?? createPromptAutocompleteFileSettingsStore(resolvePromptAutocompleteSettingsPath());
2079
3450
  let persistedSettings: PromptAutocompletePersistedSettings;
2080
3451
  try {
2081
3452
  persistedSettings = settingsStore.load();
@@ -2131,25 +3502,42 @@ export function createPromptAutocompleteExtension(
2131
3502
  type: "string",
2132
3503
  default: String(DEFAULT_MAX_ALTERNATIVES),
2133
3504
  });
3505
+ pi.registerFlag("prompt-autocomplete-max-requests", {
3506
+ description: `Maximum provider requests per session before autocomplete stops requesting (${BUDGET_REQUESTS_MIN}-${BUDGET_REQUESTS_MAX} or off)`,
3507
+ type: "string",
3508
+ default: DEFAULT_BUDGET_REQUESTS_FLAG,
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
+ });
2134
3515
 
2135
3516
  const shared: PromptAutocompleteSharedState = {
2136
3517
  enabled: false,
2137
3518
  activationId: 0,
2138
3519
  agentStreaming: false,
3520
+ physicalSessionId: "",
3521
+ lastConversationId: "",
2139
3522
  config: parseConfig(pi),
2140
3523
  runtimeOverrides: {},
2141
3524
  persistedSettings,
2142
3525
  settingsStore,
3526
+ keymap: resolvePromptAutocompleteKeymap(persistedSettings.keys),
2143
3527
  enabledFlagValue: false,
3528
+ budgetUsed: 0,
3529
+ budgetBlockNotices: new Set(),
2144
3530
  usageStats: createPromptAutocompleteUsageStats(),
2145
3531
  completeSimple: completeSimpleImpl,
2146
3532
  streamSimple: streamSimpleImpl,
3533
+ routesThroughHostRegistry: () => hostRegistryStream() !== undefined,
2147
3534
  now,
2148
3535
  debugState: "idle",
2149
3536
  requestCache: new ExpiringLruCache(REQUEST_CACHE_TTL_MS, REQUEST_CACHE_MAX_ENTRIES, now),
2150
3537
  prefixReuseCache: new ExpiringLruCache(REQUEST_CACHE_TTL_MS, REQUEST_CACHE_MAX_ENTRIES, now),
2151
3538
  inFlightRequests: new Map(),
2152
3539
  reportedModelRefusals: new Set(),
3540
+ processState: dependencies.processState ?? sharedProcessState(),
2153
3541
  };
2154
3542
 
2155
3543
  pi.on("session_start", async (_event, ctx) => {
@@ -2158,8 +3546,12 @@ export function createPromptAutocompleteExtension(
2158
3546
  }
2159
3547
  resetSharedForSession(pi, shared);
2160
3548
  bindRuntimeContext(ctx, shared);
3549
+ restoreBudgetFromSession(pi, shared);
2161
3550
 
2162
- if (!hostOwnsInteractiveEditor(ctx, shared) || !shared.enabled) return;
3551
+ if (!hostOwnsInteractiveEditor(ctx, shared) || !shared.enabled) {
3552
+ notifyEnabledWithoutEditorOnce(ctx, shared);
3553
+ return;
3554
+ }
2163
3555
  mountEditor(ctx, shared);
2164
3556
  });
2165
3557
 
@@ -2167,6 +3559,7 @@ export function createPromptAutocompleteExtension(
2167
3559
  // Teardown, not a user decision: leave runtimeOverrides untouched.
2168
3560
  shared.enabled = false;
2169
3561
  shared.cancelActiveRequest?.();
3562
+ cancelNextPrompt(shared);
2170
3563
  shared.requestCache.clear();
2171
3564
  shared.prefixReuseCache.clear();
2172
3565
  cancelAllCoalescedRequests(shared.inFlightRequests);
@@ -2183,57 +3576,63 @@ export function createPromptAutocompleteExtension(
2183
3576
  pi.on("session_tree", async (_event, ctx) => {
2184
3577
  shared.sessionManager = ctx.sessionManager;
2185
3578
  if (!shared.enabled) return;
3579
+ const nextConversationId = resolveCurrentConversationId(shared);
3580
+ if (nextConversationId === shared.lastConversationId) return;
3581
+ shared.lastConversationId = nextConversationId;
2186
3582
  refreshEditorImmediately(shared, "context-changed", "Conversation branch changed");
2187
3583
  });
2188
3584
 
2189
3585
  pi.on("agent_start", async () => {
2190
3586
  shared.agentStreaming = true;
3587
+ cancelNextPrompt(shared);
2191
3588
  if (!shared.enabled || shared.config.allowWhileStreaming) return;
2192
3589
  refreshEditorImmediately(shared, "waiting", "Main agent is still working");
2193
3590
  });
2194
3591
 
2195
- pi.on("agent_end", async () => {
2196
- shared.agentStreaming = false;
2197
- if (!shared.enabled) return;
2198
- refreshEditorImmediately(shared, "ready", "Agent finished; autocomplete can request suggestions again");
3592
+ pi.on("agent_end", async (_event, ctx) => {
3593
+ rememberAgentSettledSupport(ctx, shared);
3594
+ if (shared.hostEmitsAgentSettled) return;
3595
+ settleAgentTurn(shared, "Agent finished; autocomplete can request suggestions again");
3596
+ });
3597
+
3598
+ pi.on("agent_settled", async (_event, ctx) => {
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);
2199
3602
  });
2200
3603
 
2201
3604
  pi.registerCommand("prompt-autocomplete", {
2202
3605
  description: "Enable, disable, or inspect inline prompt autocomplete and session stats",
3606
+ // Local and synchronous: Pi replaces the whole argument span with the value.
3607
+ getArgumentCompletions: (argumentPrefix) => completePromptAutocompleteArguments(argumentPrefix),
2203
3608
  handler: async (args, ctx) => {
2204
- if (!hostOwnsInteractiveEditor(ctx, shared)) {
3609
+ const commandStart = args.trimStart();
3610
+ const space = commandStart.search(/\s/);
3611
+ const name = (space < 0 ? commandStart : commandStart.slice(0, space)).toLowerCase() || "status";
3612
+ // Everything after exactly one separator, verbatim: an inspected draft
3613
+ // must keep its leading and trailing whitespace to match production.
3614
+ const payload = space < 0 ? "" : commandStart.slice(space + 1);
3615
+ const rest = payload.trim();
3616
+ const spec = findPromptAutocompleteCommand(name);
3617
+
3618
+ // Reporting works wherever a notification can be shown; anything that
3619
+ // changes state or touches the editor stays TUI-only.
3620
+ const interactiveHost = hostOwnsInteractiveEditor(ctx, shared);
3621
+ if (!interactiveHost && !(spec?.readOnly && hasNotificationChannel(ctx))) {
2205
3622
  ctx.ui.notify("prompt-autocomplete requires interactive TUI mode", "warning");
2206
3623
  return;
2207
3624
  }
2208
-
2209
- const parts = args.trim().toLowerCase().split(/\s+/).filter(Boolean);
2210
- const command = parts[0] || "status";
2211
-
2212
- if (command === "while-streaming") {
2213
- setWhileStreaming(ctx, shared, parts[1]);
2214
- return;
2215
- }
2216
- if (command === "stream") {
2217
- setStreamResponses(ctx, shared, parts[1]);
2218
- return;
2219
- }
2220
- if (command === "min-chars") {
2221
- setMinPromptChars(ctx, shared, parts[1]);
2222
- return;
2223
- }
2224
-
2225
- const handlers = createPromptAutocompleteCommandHandlers(ctx, shared);
2226
- const handler = handlers[command];
2227
-
2228
- if (handler) {
2229
- handler();
3625
+ if (!spec) {
3626
+ ctx.ui.notify(PROMPT_AUTOCOMPLETE_USAGE, "warning");
2230
3627
  return;
2231
3628
  }
2232
3629
 
2233
- ctx.ui.notify(
2234
- "Usage: /prompt-autocomplete [on|off|toggle|status|stats|min-chars <n>|stream on|off|toggle|while-streaming on|off|toggle|debug-on|debug-off|debug-toggle]",
2235
- "warning",
2236
- );
3630
+ COMMAND_RUNNERS[spec.name](ctx, shared, {
3631
+ payload,
3632
+ rest,
3633
+ firstArgument: rest.split(/\s+/, 1)[0] || undefined,
3634
+ interactiveHost,
3635
+ });
2237
3636
  },
2238
3637
  });
2239
3638
  };