@kliebhan/pi-prompt-autocomplete 0.2.5 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/README.md +51 -13
- package/core.ts +673 -11
- package/index.ts +1206 -236
- package/media/prompt-autocomplete-demo.mp4 +0 -0
- package/package.json +2 -2
package/index.ts
CHANGED
|
@@ -13,21 +13,37 @@ import { CustomEditor, type ExtensionAPI, type ExtensionContext, type Keybinding
|
|
|
13
13
|
import { matchesKey, truncateToWidth, type EditorTheme, type KeyId, type TUI, visibleWidth } from "@earendil-works/pi-tui";
|
|
14
14
|
import {
|
|
15
15
|
acquireCoalescedRequest,
|
|
16
|
-
buildLatestAssistantMessageContext,
|
|
17
|
-
buildLatestUserMessageContext,
|
|
18
16
|
buildPromptAutocompleteCacheKey,
|
|
19
17
|
buildPromptAutocompletePrefixContextKey,
|
|
20
|
-
|
|
18
|
+
buildPromptAutocompleteBudgetSnapshot,
|
|
19
|
+
buildPromptAutocompleteRequestSnapshot,
|
|
20
|
+
renderPromptAutocompleteUserText,
|
|
21
|
+
type PromptAutocompleteRequestSnapshot,
|
|
22
|
+
BUDGET_REQUESTS_MAX,
|
|
23
|
+
BUDGET_REQUESTS_MIN,
|
|
21
24
|
cancelAllCoalescedRequests,
|
|
22
25
|
computeRequestMaxTokens,
|
|
23
26
|
createOwnerRefCounter,
|
|
24
27
|
createPromptAutocompleteUsageStats,
|
|
28
|
+
DEFAULT_BUDGET_REQUESTS_FLAG,
|
|
25
29
|
describePromptAutocompleteModelSelection,
|
|
26
30
|
describeSettingSource,
|
|
27
31
|
DEFAULT_DEBOUNCE_MS,
|
|
32
|
+
DEBOUNCE_MS_MAX,
|
|
33
|
+
DEBOUNCE_MS_MIN,
|
|
28
34
|
DEFAULT_MAX_ALTERNATIVES,
|
|
29
35
|
DEFAULT_MAX_SUGGESTION_CHARS,
|
|
30
36
|
DEFAULT_MIN_PROMPT_CHARS,
|
|
37
|
+
MAX_ALTERNATIVES_MAX,
|
|
38
|
+
MAX_ALTERNATIVES_MIN,
|
|
39
|
+
MAX_COMPACTION_SUMMARY_CHARS,
|
|
40
|
+
MAX_CONTEXT_MESSAGE_CHARS,
|
|
41
|
+
MAX_CONTEXT_MESSAGES,
|
|
42
|
+
MAX_DRAFT_CONTEXT_CHARS,
|
|
43
|
+
MAX_LATEST_ASSISTANT_MESSAGE_CHARS,
|
|
44
|
+
MAX_LATEST_USER_MESSAGE_CHARS,
|
|
45
|
+
MAX_SUGGESTION_CHARS_MAX,
|
|
46
|
+
MAX_SUGGESTION_CHARS_MIN,
|
|
31
47
|
DEFAULT_PREFERRED_MODEL,
|
|
32
48
|
MIN_PROMPT_CHARS_MAX,
|
|
33
49
|
MIN_PROMPT_CHARS_MIN,
|
|
@@ -40,25 +56,44 @@ import {
|
|
|
40
56
|
formatUsageStats,
|
|
41
57
|
hostSupportsStreamedResponses,
|
|
42
58
|
isInteractiveEditorHost,
|
|
43
|
-
MAX_DRAFT_CONTEXT_CHARS,
|
|
44
59
|
normalizePromptSuggestions,
|
|
45
60
|
parseBoundedIntFlag,
|
|
46
61
|
parseExplicitBoundedIntFlag,
|
|
62
|
+
parseExplicitModelFlag,
|
|
63
|
+
parsePersistedModelRaw,
|
|
64
|
+
parsePromptAutocompleteBudgetFlag,
|
|
65
|
+
parsePromptAutocompleteBudgetValue,
|
|
66
|
+
parseStrictBoundedInt,
|
|
67
|
+
persistableModelRaw,
|
|
47
68
|
parsePartialPromptSuggestion,
|
|
48
69
|
parsePromptAutocompleteModelSelection,
|
|
49
70
|
parsePromptAutocompletePersistedSettings,
|
|
71
|
+
projectAutocompleteContextEntries,
|
|
72
|
+
findPromptAutocompleteBudgetSnapshot,
|
|
73
|
+
completePromptAutocompleteArguments,
|
|
74
|
+
findPromptAutocompleteCommand,
|
|
75
|
+
findPromptAutocompleteSetKey,
|
|
76
|
+
PROMPT_AUTOCOMPLETE_SET_USAGE,
|
|
77
|
+
PROMPT_AUTOCOMPLETE_USAGE,
|
|
78
|
+
type PromptAutocompleteCommandName,
|
|
79
|
+
type PromptAutocompleteSetKey,
|
|
80
|
+
PromptAutocompleteBudgetExhaustedError,
|
|
81
|
+
type PromptAutocompleteBudgetSetting,
|
|
50
82
|
resolvePersistedEnabled,
|
|
51
83
|
resolvePersistedNumber,
|
|
84
|
+
resolvePromptAutocompleteBudgetLimit,
|
|
52
85
|
serializePromptAutocompletePersistedSettings,
|
|
53
86
|
PROMPT_AUTOCOMPLETE_SYSTEM_PROMPT,
|
|
87
|
+
PROMPT_AUTOCOMPLETE_BUDGET_ENTRY_TYPE,
|
|
54
88
|
recordProviderLatency,
|
|
55
89
|
recordProviderUsage,
|
|
90
|
+
resolveAutocompleteConversationId,
|
|
56
91
|
resolveOverride,
|
|
92
|
+
resolvePersistedModelSelection,
|
|
57
93
|
reusePromptAutocompleteSuggestions,
|
|
58
94
|
sanitizeTerminalText,
|
|
59
95
|
SequenceOwnedSlot,
|
|
60
96
|
shouldSkipPromptAutocomplete,
|
|
61
|
-
truncateDraftTail,
|
|
62
97
|
type CoalescedRequestEntry,
|
|
63
98
|
type CoalescedRequestSubscription,
|
|
64
99
|
type PromptAutocompleteModelSelection,
|
|
@@ -70,13 +105,16 @@ import {
|
|
|
70
105
|
const GHOST_TEXT_STYLE = "\x1b[2m";
|
|
71
106
|
const GHOST_INDICATOR_STYLE = "\x1b[90m";
|
|
72
107
|
const RESET = "\x1b[0m";
|
|
73
|
-
// Hosts draw the end-of-line
|
|
74
|
-
//
|
|
75
|
-
// surface alive, such as prime-agent, close it with \x1b[27m so the
|
|
76
|
-
// survives the cursor cell
|
|
77
|
-
//
|
|
78
|
-
|
|
79
|
-
|
|
108
|
+
// Hosts draw the end-of-line cursor as a marked space cell. Pi 0.x draws inverse
|
|
109
|
+
// video closed by a full SGR reset (\x1b[0m); forks that keep an editor
|
|
110
|
+
// background surface alive, such as prime-agent, close it with \x1b[27m so the
|
|
111
|
+
// background survives the cursor cell; Pi 1.x wraps the cell in fake-cursor APC
|
|
112
|
+
// markers that its TUI later turns into inverse video or the hardware cursor.
|
|
113
|
+
// Accept all three, otherwise the suggestion lookup never finds the cursor and
|
|
114
|
+
// inline suggestions silently never render. Each form is matched as a whole so
|
|
115
|
+
// the cell is always rebuilt with its own opening and closing sequence.
|
|
116
|
+
const CURSOR_CELL_OPENERS = ["\x1b[7m ", "\x1b_pi:fc\x07 "] as const;
|
|
117
|
+
const CURSOR_CELL_PATTERN = /\x1b\[7m \x1b\[(?:0|27)m|\x1b_pi:fc\x07 \x1b_pi:\/fc\x07/;
|
|
80
118
|
const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] as const;
|
|
81
119
|
const SPINNER_INTERVAL_MS = 80;
|
|
82
120
|
const SPINNER_LABEL = "Generating suggestion";
|
|
@@ -96,6 +134,8 @@ const REQUEST_MAX_RETRY_DELAY_MS = 2_000;
|
|
|
96
134
|
const FAILURE_COOLDOWN_MS = 5_000;
|
|
97
135
|
const REQUEST_CACHE_TTL_MS = 60_000;
|
|
98
136
|
const REQUEST_CACHE_MAX_ENTRIES = 128;
|
|
137
|
+
const PRIVACY_NOTICE =
|
|
138
|
+
"Requests send the current draft and recent conversation context to the selected model and may incur provider usage.";
|
|
99
139
|
// Keymap audit vs. pi defaults (packages/tui/src/keybindings.ts +
|
|
100
140
|
// packages/coding-agent/src/core/keybindings.ts): none of the keys below are bound
|
|
101
141
|
// by pi's default keymap, so the editor can safely own them — including the
|
|
@@ -142,6 +182,8 @@ interface PromptAutocompleteConfig {
|
|
|
142
182
|
maxSuggestionChars: number;
|
|
143
183
|
maxAlternatives: number;
|
|
144
184
|
modelSelection: PromptAutocompleteModelSelection;
|
|
185
|
+
/** Effective provider-request ceiling; undefined means off. */
|
|
186
|
+
budgetLimit?: number;
|
|
145
187
|
}
|
|
146
188
|
|
|
147
189
|
interface PromptAutocompleteCacheEntry {
|
|
@@ -217,12 +259,106 @@ const hostStreamSimple = ((model, context, options) =>
|
|
|
217
259
|
options,
|
|
218
260
|
)) as StreamSimpleFunction;
|
|
219
261
|
|
|
262
|
+
/** The model registry's own request entry point, which Pi 1.x provides. */
|
|
263
|
+
type RegistryStreamSimple = (...args: Parameters<StreamSimpleFunction>) => ReturnType<StreamSimpleFunction>;
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Where a request goes when no seam was injected.
|
|
267
|
+
*
|
|
268
|
+
* Pi 1.x serves every chat model, including those that extensions register
|
|
269
|
+
* with their own streaming implementation, through the session's model
|
|
270
|
+
* registry; the global `pi-ai` compat functions only know Pi's built-in APIs
|
|
271
|
+
* there and fail for extension providers. The registry also applies the
|
|
272
|
+
* provider's request-time base URL and environment. Hosts without it (Pi 0.x
|
|
273
|
+
* and forks of that API) keep the compat functions, which serve every model
|
|
274
|
+
* there.
|
|
275
|
+
*/
|
|
276
|
+
function registryStreamSimple(registry: unknown): RegistryStreamSimple | undefined {
|
|
277
|
+
if (typeof registry !== "object" || registry === null) return undefined;
|
|
278
|
+
const streamSimple: unknown = Reflect.get(registry, "streamSimple");
|
|
279
|
+
if (typeof streamSimple !== "function") return undefined;
|
|
280
|
+
return (model, context, options) => Reflect.apply(streamSimple, registry, [model, context, options]);
|
|
281
|
+
}
|
|
282
|
+
|
|
220
283
|
export interface PromptAutocompleteDependencies {
|
|
221
284
|
completeSimple?: CompleteSimpleFunction;
|
|
222
285
|
streamSimple?: StreamSimpleFunction;
|
|
223
286
|
now?: () => number;
|
|
224
287
|
/** Store for decisions that survive the process; defaults to a JSON settings file. */
|
|
225
288
|
settingsStore?: PromptAutocompleteSettingsStore;
|
|
289
|
+
/** Process-lifetime state; defaults to one object shared by every runtime of this process. */
|
|
290
|
+
processState?: PromptAutocompleteProcessState;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* State that must outlive extension runtimes within one process.
|
|
295
|
+
*
|
|
296
|
+
* Pi re-imports the extension module for every runtime (`/new`, `/resume`,
|
|
297
|
+
* `/fork`, `/reload`), so neither runtime state nor module scope lasts for the
|
|
298
|
+
* process. Only what is genuinely process-wide belongs here.
|
|
299
|
+
*/
|
|
300
|
+
export interface PromptAutocompleteProcessState {
|
|
301
|
+
/** The enabled-but-non-interactive notice was already shown. */
|
|
302
|
+
nonInteractiveNoticeShown?: boolean;
|
|
303
|
+
/**
|
|
304
|
+
* Set once a mount attempt proved whether this host installs custom editors.
|
|
305
|
+
*
|
|
306
|
+
* A process cannot change its front-end, so this is deliberately never reset:
|
|
307
|
+
* a host that dropped the editor factory once would drop it again, also in a
|
|
308
|
+
* later runtime. Restarting the host is the only way to re-probe.
|
|
309
|
+
*/
|
|
310
|
+
hostInstallsEditors?: boolean;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const PROCESS_STATE_KEY = Symbol.for("@kliebhan/pi-prompt-autocomplete/process-state");
|
|
314
|
+
|
|
315
|
+
const PROCESS_STATE_FIELDS = ["nonInteractiveNoticeShown", "hostInstallsEditors"] as const;
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Accept only an occupant this extension could have written: an extensible
|
|
319
|
+
* plain object whose known fields are absent or own writable booleans. Anything
|
|
320
|
+
* else — a frozen object, a stringly typed flag, an inherited field, or a
|
|
321
|
+
* proxy whose traps throw — is replaced rather than trusted.
|
|
322
|
+
*/
|
|
323
|
+
function isProcessState(value: unknown): value is PromptAutocompleteProcessState {
|
|
324
|
+
try {
|
|
325
|
+
if (typeof value !== "object" || value === null) return false;
|
|
326
|
+
if (Object.getPrototypeOf(value) !== Object.prototype || !Object.isExtensible(value)) return false;
|
|
327
|
+
return PROCESS_STATE_FIELDS.every((field) => {
|
|
328
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, field);
|
|
329
|
+
return descriptor === undefined
|
|
330
|
+
|| (descriptor.writable === true && (descriptor.value === undefined || typeof descriptor.value === "boolean"));
|
|
331
|
+
});
|
|
332
|
+
} catch {
|
|
333
|
+
return false;
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/**
|
|
338
|
+
* The process-wide state object, created on first use and found again after a
|
|
339
|
+
* re-import.
|
|
340
|
+
*
|
|
341
|
+
* If another occupant holds the slot and cannot be replaced, there is no other
|
|
342
|
+
* process-wide store, so this runtime falls back to private state: a notice or
|
|
343
|
+
* the editor probe may then repeat after a runtime replacement, but nothing
|
|
344
|
+
* fails.
|
|
345
|
+
*/
|
|
346
|
+
function sharedProcessState(): PromptAutocompleteProcessState {
|
|
347
|
+
let existing: unknown;
|
|
348
|
+
try {
|
|
349
|
+
existing = Reflect.get(globalThis, PROCESS_STATE_KEY);
|
|
350
|
+
} catch {
|
|
351
|
+
existing = undefined;
|
|
352
|
+
}
|
|
353
|
+
if (isProcessState(existing)) return existing;
|
|
354
|
+
const created: PromptAutocompleteProcessState = {};
|
|
355
|
+
Reflect.defineProperty(globalThis, PROCESS_STATE_KEY, {
|
|
356
|
+
value: created,
|
|
357
|
+
writable: true,
|
|
358
|
+
configurable: true,
|
|
359
|
+
enumerable: false,
|
|
360
|
+
});
|
|
361
|
+
return created;
|
|
226
362
|
}
|
|
227
363
|
|
|
228
364
|
/**
|
|
@@ -280,6 +416,26 @@ interface PromptAutocompleteSharedState {
|
|
|
280
416
|
enabled: boolean;
|
|
281
417
|
activationId: number;
|
|
282
418
|
agentStreaming: boolean;
|
|
419
|
+
/**
|
|
420
|
+
* Immutable for the current extension runtime's session. Captured at
|
|
421
|
+
* `session_start` from `sessionManager.getSessionId()`. Fork/new replace the
|
|
422
|
+
* runtime, so a later session cannot inherit this id from an old closure.
|
|
423
|
+
*/
|
|
424
|
+
physicalSessionId: string;
|
|
425
|
+
/**
|
|
426
|
+
* Last context-relevant conversation id observed on this runtime. Used to
|
|
427
|
+
* ignore `session_tree` events that only moved the raw leaf.
|
|
428
|
+
*/
|
|
429
|
+
lastConversationId: string;
|
|
430
|
+
/**
|
|
431
|
+
* Set once we know whether this host emits `agent_settled`.
|
|
432
|
+
*
|
|
433
|
+
* `pi.on("agent_settled")` never throws — Pi stores any event name — so the
|
|
434
|
+
* probe is `typeof ctx.isIdle === "function"`. That method shipped together
|
|
435
|
+
* with `agent_settled` in Pi 0.80.5. A process cannot change its front-end,
|
|
436
|
+
* so this is never reset.
|
|
437
|
+
*/
|
|
438
|
+
hostEmitsAgentSettled?: boolean;
|
|
283
439
|
config: PromptAutocompleteConfig;
|
|
284
440
|
/** Slash-command decisions that outrank flags for the lifetime of the process. */
|
|
285
441
|
runtimeOverrides: PromptAutocompleteRuntimeOverrides;
|
|
@@ -290,6 +446,28 @@ interface PromptAutocompleteSharedState {
|
|
|
290
446
|
enabledFlagValue: boolean;
|
|
291
447
|
/** Explicit min-chars flag value seen by applyEffectiveConfig, undefined when defaulted. */
|
|
292
448
|
minPromptCharsFlagExplicit?: number;
|
|
449
|
+
debounceMsFlagExplicit?: number;
|
|
450
|
+
maxSuggestionCharsFlagExplicit?: number;
|
|
451
|
+
maxAlternativesFlagExplicit?: number;
|
|
452
|
+
modelFlagExplicit?: PromptAutocompleteModelSelection;
|
|
453
|
+
/** Explicit max-requests flag value seen by applyEffectiveConfig, undefined when defaulted. */
|
|
454
|
+
budgetFlagExplicit?: number;
|
|
455
|
+
/** Ceiling restored from this session's entries; `"off"` is a real restored decision. */
|
|
456
|
+
savedBudgetLimit?: PromptAutocompleteBudgetSetting;
|
|
457
|
+
/** Reserved provider invocations of the current physical session. */
|
|
458
|
+
budgetUsed: number;
|
|
459
|
+
/**
|
|
460
|
+
* Whether this physical session already carries durable budget state.
|
|
461
|
+
*
|
|
462
|
+
* Once a ceiling was set or restored, accounting stays durable even while the
|
|
463
|
+
* ceiling is off, so a later ceiling cannot ignore what the session spent in
|
|
464
|
+
* between. A session that never touched the budget writes no entries at all.
|
|
465
|
+
*/
|
|
466
|
+
budgetSnapshotsActive?: boolean;
|
|
467
|
+
/** Exhaustion notices already delivered, keyed by `used/limit`. */
|
|
468
|
+
budgetBlockNotices: Set<string>;
|
|
469
|
+
/** Session-bound snapshot writer; appends a non-LLM custom entry. */
|
|
470
|
+
persistBudgetSnapshot?: (limit: PromptAutocompleteBudgetSetting, used: number) => void;
|
|
293
471
|
/** Session-scoped request accounting; reset together with the cache. */
|
|
294
472
|
usageStats: PromptAutocompleteUsageStats;
|
|
295
473
|
currentModel?: Model<Api>;
|
|
@@ -301,18 +479,23 @@ interface PromptAutocompleteSharedState {
|
|
|
301
479
|
debugState: string;
|
|
302
480
|
editorMount?: EditorMountState;
|
|
303
481
|
editorBlockedReason?: string;
|
|
482
|
+
/** Whether requests go through the session's model registry rather than compat or injected seams. */
|
|
483
|
+
routesThroughHostRegistry: () => boolean;
|
|
304
484
|
/** Mount-bound notification channel; cleared together with the editor runtime. */
|
|
305
485
|
notify?: (message: string, type?: "info" | "warning" | "error") => void;
|
|
306
486
|
/** Refused model requests already reported, to avoid repeating them. */
|
|
307
487
|
reportedModelRefusals: Set<string>;
|
|
488
|
+
/** Process-lifetime state shared with later runtimes of this process. */
|
|
489
|
+
processState: PromptAutocompleteProcessState;
|
|
308
490
|
/**
|
|
309
|
-
*
|
|
491
|
+
* Projected context entries and the conversation id they belong to.
|
|
310
492
|
*
|
|
311
|
-
*
|
|
312
|
-
*
|
|
313
|
-
*
|
|
493
|
+
* The host projection scans the whole session, every branch included, so it
|
|
494
|
+
* is rebuilt only when a context-relevant entry changes the conversation id —
|
|
495
|
+
* a message, a context edit, a compaction, or a branch switch — and not on
|
|
496
|
+
* every keystroke. Metadata entries such as budget snapshots keep the id.
|
|
314
497
|
*/
|
|
315
|
-
|
|
498
|
+
projectedContextMemo?: { conversationId: string; entries: unknown[] };
|
|
316
499
|
lastError?: string;
|
|
317
500
|
lastRawResponse?: string;
|
|
318
501
|
requestCache: ExpiringLruCache<PromptAutocompleteCacheEntry>;
|
|
@@ -321,26 +504,22 @@ interface PromptAutocompleteSharedState {
|
|
|
321
504
|
ownsEditor?: () => boolean;
|
|
322
505
|
refreshEditor?: (options?: SuggestionRefreshOptions) => void;
|
|
323
506
|
cancelActiveRequest?: () => void;
|
|
507
|
+
/** Cancel a pending debounce timer without aborting an in-flight provider call. */
|
|
508
|
+
cancelScheduledRequest?: () => void;
|
|
324
509
|
setStatusText?: (text: string | undefined) => void;
|
|
325
510
|
setSpinnerActive?: (owner: string, active: boolean) => void;
|
|
326
511
|
clearSpinner?: () => void;
|
|
327
512
|
}
|
|
328
513
|
|
|
329
|
-
|
|
514
|
+
/** A request snapshot plus the local routing and cache identity around it. */
|
|
515
|
+
interface SuggestionRequest extends PromptAutocompleteRequestSnapshot {
|
|
330
516
|
activationId: number;
|
|
331
|
-
|
|
332
|
-
draft: string;
|
|
333
|
-
draftTail: string;
|
|
517
|
+
conversationId: string;
|
|
334
518
|
model: Model<Api>;
|
|
335
519
|
modelLabel: string;
|
|
336
520
|
cacheKey: string;
|
|
337
521
|
prefixContextKey: string;
|
|
338
|
-
maxAlternatives: number;
|
|
339
|
-
maxSuggestionChars: number;
|
|
340
522
|
useStreaming: boolean;
|
|
341
|
-
latestAssistantContext: string;
|
|
342
|
-
latestUserContext: string;
|
|
343
|
-
recentContext: string;
|
|
344
523
|
}
|
|
345
524
|
|
|
346
525
|
interface PendingSuggestionRequest {
|
|
@@ -450,11 +629,11 @@ interface SuggestionModelResolution {
|
|
|
450
629
|
*/
|
|
451
630
|
function resolveSuggestionModelResolution(
|
|
452
631
|
shared: PromptAutocompleteSharedState,
|
|
632
|
+
selection: PromptAutocompleteModelSelection = shared.config.modelSelection,
|
|
453
633
|
): SuggestionModelResolution {
|
|
454
634
|
const registry = shared.modelRegistry;
|
|
455
635
|
if (!registry) return { reason: "No model registry is available yet" };
|
|
456
636
|
|
|
457
|
-
const selection = shared.config.modelSelection;
|
|
458
637
|
const requested = describePromptAutocompleteModelSelection(selection);
|
|
459
638
|
|
|
460
639
|
if (selection.kind === "invalid") {
|
|
@@ -523,21 +702,32 @@ function parseConfig(pi: ExtensionAPI): PromptAutocompleteConfig {
|
|
|
523
702
|
allowWhileStreaming: pi.getFlag("prompt-autocomplete-while-streaming") === true,
|
|
524
703
|
streamResponses: parseOnOffFlag(pi.getFlag("prompt-autocomplete-stream"), DEFAULT_STREAM_RESPONSES),
|
|
525
704
|
debug: pi.getFlag("prompt-autocomplete-debug") === true,
|
|
526
|
-
debounceMs: parseBoundedIntFlag(
|
|
527
|
-
|
|
705
|
+
debounceMs: parseBoundedIntFlag(
|
|
706
|
+
pi.getFlag("prompt-autocomplete-debounce-ms"),
|
|
707
|
+
DEFAULT_DEBOUNCE_MS,
|
|
708
|
+
DEBOUNCE_MS_MIN,
|
|
709
|
+
DEBOUNCE_MS_MAX,
|
|
710
|
+
),
|
|
711
|
+
minPromptChars: parseBoundedIntFlag(
|
|
712
|
+
pi.getFlag("prompt-autocomplete-min-chars"),
|
|
713
|
+
DEFAULT_MIN_PROMPT_CHARS,
|
|
714
|
+
MIN_PROMPT_CHARS_MIN,
|
|
715
|
+
MIN_PROMPT_CHARS_MAX,
|
|
716
|
+
),
|
|
528
717
|
maxSuggestionChars: parseBoundedIntFlag(
|
|
529
718
|
pi.getFlag("prompt-autocomplete-max-chars"),
|
|
530
719
|
DEFAULT_MAX_SUGGESTION_CHARS,
|
|
531
|
-
|
|
532
|
-
|
|
720
|
+
MAX_SUGGESTION_CHARS_MIN,
|
|
721
|
+
MAX_SUGGESTION_CHARS_MAX,
|
|
533
722
|
),
|
|
534
723
|
maxAlternatives: parseBoundedIntFlag(
|
|
535
724
|
pi.getFlag("prompt-autocomplete-max-alternatives"),
|
|
536
725
|
DEFAULT_MAX_ALTERNATIVES,
|
|
537
|
-
|
|
538
|
-
|
|
726
|
+
MAX_ALTERNATIVES_MIN,
|
|
727
|
+
MAX_ALTERNATIVES_MAX,
|
|
539
728
|
),
|
|
540
729
|
modelSelection: parsePromptAutocompleteModelSelection(pi.getFlag("prompt-autocomplete-model")),
|
|
730
|
+
budgetLimit: parsePromptAutocompleteBudgetFlag(pi.getFlag("prompt-autocomplete-max-requests")),
|
|
541
731
|
};
|
|
542
732
|
}
|
|
543
733
|
|
|
@@ -564,6 +754,26 @@ function applyEffectiveConfig(pi: ExtensionAPI, shared: PromptAutocompleteShared
|
|
|
564
754
|
MIN_PROMPT_CHARS_MIN,
|
|
565
755
|
MIN_PROMPT_CHARS_MAX,
|
|
566
756
|
);
|
|
757
|
+
shared.debounceMsFlagExplicit = parseExplicitBoundedIntFlag(
|
|
758
|
+
pi.getFlag("prompt-autocomplete-debounce-ms"),
|
|
759
|
+
DEFAULT_DEBOUNCE_MS,
|
|
760
|
+
DEBOUNCE_MS_MIN,
|
|
761
|
+
DEBOUNCE_MS_MAX,
|
|
762
|
+
);
|
|
763
|
+
shared.maxSuggestionCharsFlagExplicit = parseExplicitBoundedIntFlag(
|
|
764
|
+
pi.getFlag("prompt-autocomplete-max-chars"),
|
|
765
|
+
DEFAULT_MAX_SUGGESTION_CHARS,
|
|
766
|
+
MAX_SUGGESTION_CHARS_MIN,
|
|
767
|
+
MAX_SUGGESTION_CHARS_MAX,
|
|
768
|
+
);
|
|
769
|
+
shared.maxAlternativesFlagExplicit = parseExplicitBoundedIntFlag(
|
|
770
|
+
pi.getFlag("prompt-autocomplete-max-alternatives"),
|
|
771
|
+
DEFAULT_MAX_ALTERNATIVES,
|
|
772
|
+
MAX_ALTERNATIVES_MIN,
|
|
773
|
+
MAX_ALTERNATIVES_MAX,
|
|
774
|
+
);
|
|
775
|
+
shared.modelFlagExplicit = parseExplicitModelFlag(pi.getFlag("prompt-autocomplete-model"));
|
|
776
|
+
shared.budgetFlagExplicit = parsePromptAutocompleteBudgetFlag(pi.getFlag("prompt-autocomplete-max-requests"));
|
|
567
777
|
shared.config = {
|
|
568
778
|
...flagConfig,
|
|
569
779
|
allowWhileStreaming: resolveOverride(
|
|
@@ -576,8 +786,36 @@ function applyEffectiveConfig(pi: ExtensionAPI, shared: PromptAutocompleteShared
|
|
|
576
786
|
shared.runtimeOverrides.minPromptChars,
|
|
577
787
|
shared.minPromptCharsFlagExplicit,
|
|
578
788
|
shared.persistedSettings.minPromptChars,
|
|
579
|
-
|
|
789
|
+
DEFAULT_MIN_PROMPT_CHARS,
|
|
790
|
+
).value,
|
|
791
|
+
debounceMs: resolvePersistedNumber(
|
|
792
|
+
shared.runtimeOverrides.debounceMs,
|
|
793
|
+
shared.debounceMsFlagExplicit,
|
|
794
|
+
shared.persistedSettings.debounceMs,
|
|
795
|
+
DEFAULT_DEBOUNCE_MS,
|
|
580
796
|
).value,
|
|
797
|
+
maxSuggestionChars: resolvePersistedNumber(
|
|
798
|
+
shared.runtimeOverrides.maxSuggestionChars,
|
|
799
|
+
shared.maxSuggestionCharsFlagExplicit,
|
|
800
|
+
shared.persistedSettings.maxSuggestionChars,
|
|
801
|
+
DEFAULT_MAX_SUGGESTION_CHARS,
|
|
802
|
+
).value,
|
|
803
|
+
maxAlternatives: resolvePersistedNumber(
|
|
804
|
+
shared.runtimeOverrides.maxAlternatives,
|
|
805
|
+
shared.maxAlternativesFlagExplicit,
|
|
806
|
+
shared.persistedSettings.maxAlternatives,
|
|
807
|
+
DEFAULT_MAX_ALTERNATIVES,
|
|
808
|
+
).value,
|
|
809
|
+
modelSelection: resolvePersistedModelSelection(
|
|
810
|
+
shared.runtimeOverrides.modelSelection,
|
|
811
|
+
shared.modelFlagExplicit,
|
|
812
|
+
parsePersistedModelRaw(shared.persistedSettings.model),
|
|
813
|
+
).selection,
|
|
814
|
+
budgetLimit: resolvePromptAutocompleteBudgetLimit(
|
|
815
|
+
shared.runtimeOverrides.budgetLimit,
|
|
816
|
+
shared.budgetFlagExplicit,
|
|
817
|
+
shared.savedBudgetLimit,
|
|
818
|
+
).limit,
|
|
581
819
|
};
|
|
582
820
|
}
|
|
583
821
|
|
|
@@ -611,18 +849,24 @@ function clearDebugUi(shared: PromptAutocompleteSharedState): void {
|
|
|
611
849
|
shared.setStatusText?.(undefined);
|
|
612
850
|
}
|
|
613
851
|
|
|
614
|
-
function
|
|
852
|
+
function describeEditorState(shared: PromptAutocompleteSharedState, interactiveHost: boolean): string {
|
|
853
|
+
if (!interactiveHost) return "unavailable";
|
|
854
|
+
if (shared.editorMount) return shared.ownsEditor?.() ? "mounted" : "ownership-lost";
|
|
855
|
+
return shared.editorBlockedReason ? "blocked" : "unmounted";
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
/**
|
|
859
|
+
* Compact one-line status. `interactiveHost` is false only for the read-only
|
|
860
|
+
* status a non-interactive host (for example RPC) may request; there the
|
|
861
|
+
* editor is reported as unavailable instead of merely unmounted.
|
|
862
|
+
*/
|
|
863
|
+
function formatStatus(shared: PromptAutocompleteSharedState, interactiveHost = true): string {
|
|
615
864
|
const resolvedModel = resolveSuggestionModel(shared);
|
|
616
|
-
const editorState = shared
|
|
617
|
-
? shared.ownsEditor?.()
|
|
618
|
-
? "mounted"
|
|
619
|
-
: "ownership-lost"
|
|
620
|
-
: shared.editorBlockedReason
|
|
621
|
-
? "blocked"
|
|
622
|
-
: "unmounted";
|
|
865
|
+
const editorState = describeEditorState(shared, interactiveHost);
|
|
623
866
|
const requestedModel = describePromptAutocompleteModelSelection(shared.config.modelSelection);
|
|
624
867
|
|
|
625
868
|
return [
|
|
869
|
+
interactiveHost ? undefined : "host=non-interactive",
|
|
626
870
|
`enabled=${shared.enabled ? "yes" : "no"}(${
|
|
627
871
|
resolvePersistedEnabled(
|
|
628
872
|
shared.runtimeOverrides.enabled,
|
|
@@ -633,12 +877,25 @@ function formatStatus(shared: PromptAutocompleteSharedState): string {
|
|
|
633
877
|
`editor=${editorState}`,
|
|
634
878
|
shared.editorBlockedReason ? `editor-blocked=${truncateDebug(shared.editorBlockedReason, 90)}` : undefined,
|
|
635
879
|
`model=${truncateDebug(formatModelLabel(resolvedModel), 90)}`,
|
|
636
|
-
`requested-model=${requestedModel}
|
|
880
|
+
`requested-model=${requestedModel}(${
|
|
881
|
+
resolvePersistedModelSelection(
|
|
882
|
+
shared.runtimeOverrides.modelSelection,
|
|
883
|
+
shared.modelFlagExplicit,
|
|
884
|
+
parsePersistedModelRaw(shared.persistedSettings.model),
|
|
885
|
+
).source
|
|
886
|
+
})`,
|
|
637
887
|
`while-streaming=${shared.config.allowWhileStreaming ? "yes" : "no"}(${describeSettingSource(shared.runtimeOverrides.allowWhileStreaming)})`,
|
|
638
888
|
`stream=${shared.config.streamResponses ? "yes" : "no"}(${describeSettingSource(shared.runtimeOverrides.streamResponses)})`,
|
|
639
889
|
`request-path=${shared.config.streamResponses && shared.streamSimple ? "stream" : shared.config.streamResponses ? "complete-compat" : "complete"}`,
|
|
640
890
|
`debug=${shared.config.debug ? "yes" : "no"}(${describeSettingSource(shared.runtimeOverrides.debug)})`,
|
|
641
|
-
`debounce=${shared.config.debounceMs}ms
|
|
891
|
+
`debounce=${shared.config.debounceMs}ms(${
|
|
892
|
+
resolvePersistedNumber(
|
|
893
|
+
shared.runtimeOverrides.debounceMs,
|
|
894
|
+
shared.debounceMsFlagExplicit,
|
|
895
|
+
shared.persistedSettings.debounceMs,
|
|
896
|
+
DEFAULT_DEBOUNCE_MS,
|
|
897
|
+
).source
|
|
898
|
+
})`,
|
|
642
899
|
`min-chars=${shared.config.minPromptChars}(${
|
|
643
900
|
resolvePersistedNumber(
|
|
644
901
|
shared.runtimeOverrides.minPromptChars,
|
|
@@ -647,19 +904,162 @@ function formatStatus(shared: PromptAutocompleteSharedState): string {
|
|
|
647
904
|
DEFAULT_MIN_PROMPT_CHARS,
|
|
648
905
|
).source
|
|
649
906
|
})`,
|
|
650
|
-
`max-suggestion-chars=${shared.config.maxSuggestionChars}
|
|
651
|
-
|
|
907
|
+
`max-suggestion-chars=${shared.config.maxSuggestionChars}(${
|
|
908
|
+
resolvePersistedNumber(
|
|
909
|
+
shared.runtimeOverrides.maxSuggestionChars,
|
|
910
|
+
shared.maxSuggestionCharsFlagExplicit,
|
|
911
|
+
shared.persistedSettings.maxSuggestionChars,
|
|
912
|
+
DEFAULT_MAX_SUGGESTION_CHARS,
|
|
913
|
+
).source
|
|
914
|
+
})`,
|
|
915
|
+
`max-alternatives=${shared.config.maxAlternatives}(${
|
|
916
|
+
resolvePersistedNumber(
|
|
917
|
+
shared.runtimeOverrides.maxAlternatives,
|
|
918
|
+
shared.maxAlternativesFlagExplicit,
|
|
919
|
+
shared.persistedSettings.maxAlternatives,
|
|
920
|
+
DEFAULT_MAX_ALTERNATIVES,
|
|
921
|
+
).source
|
|
922
|
+
})`,
|
|
652
923
|
`cache-size=${shared.requestCache.size}`,
|
|
924
|
+
`budget=${formatBudget(shared)}`,
|
|
653
925
|
`usage=${formatUsageStats(shared.usageStats)}`,
|
|
654
926
|
`state=${shared.debugState || "idle"}`,
|
|
655
927
|
shared.lastError ? `error=${truncateDebug(shared.lastError, 90)}` : undefined,
|
|
656
928
|
shared.lastRawResponse ? `raw=${truncateDebug(shared.lastRawResponse, 90)}` : undefined,
|
|
657
|
-
|
|
929
|
+
interactiveHost
|
|
930
|
+
? `keys=tab accept | ${formatPrimaryKey(WORD_ACCEPT_KEYS)} word | ${formatPrimaryKey(CYCLE_PREV_KEYS)}/${formatPrimaryKey(CYCLE_NEXT_KEYS)} cycle | ${formatPrimaryKey(CYCLE_NEXT_KEYS)} force one-shot`
|
|
931
|
+
: undefined,
|
|
658
932
|
]
|
|
659
933
|
.filter((value): value is string => !!value)
|
|
660
934
|
.join(" | ");
|
|
661
935
|
}
|
|
662
936
|
|
|
937
|
+
const INSPECT_EXCERPT_CHARS = 120;
|
|
938
|
+
|
|
939
|
+
function formatInspectionSection(label: string, text: string, cap: string): string {
|
|
940
|
+
if (!text) return `${label}: none`;
|
|
941
|
+
return `${label}: ${text.length} chars sent (${cap}): "${truncateDebug(text, INSPECT_EXCERPT_CHARS)}"`;
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
/**
|
|
945
|
+
* The shared gates a request must pass, in production order.
|
|
946
|
+
*
|
|
947
|
+
* Only state shared by every editor instance is evaluated. Cursor position,
|
|
948
|
+
* the built-in autocomplete menu, Escape dismissal, the per-editor error
|
|
949
|
+
* cooldown, and cached responses belong to the live editor and are not.
|
|
950
|
+
*/
|
|
951
|
+
function evaluateSharedRequestPolicy(
|
|
952
|
+
shared: PromptAutocompleteSharedState,
|
|
953
|
+
interactiveHost: boolean,
|
|
954
|
+
draft: string | undefined,
|
|
955
|
+
): { automatic?: string; manual?: string } {
|
|
956
|
+
const blocks: Array<{ reason: string; manualToo: boolean }> = [];
|
|
957
|
+
if (!shared.enabled) blocks.push({ reason: "autocomplete is disabled", manualToo: true });
|
|
958
|
+
if (!interactiveHost) {
|
|
959
|
+
blocks.push({ reason: "this host has no interactive editor", manualToo: true });
|
|
960
|
+
} else if (!shared.editorMount || !shared.ownsEditor?.()) {
|
|
961
|
+
blocks.push({ reason: "the autocomplete editor is not active", manualToo: true });
|
|
962
|
+
}
|
|
963
|
+
if (!shared.config.allowWhileStreaming && shared.agentStreaming) {
|
|
964
|
+
blocks.push({ reason: "the main agent is working", manualToo: false });
|
|
965
|
+
}
|
|
966
|
+
const resolution = resolveSuggestionModelResolution(shared);
|
|
967
|
+
if (!resolution.model) {
|
|
968
|
+
blocks.push({
|
|
969
|
+
reason: resolution.reason ?? "no usable autocomplete model with configured auth",
|
|
970
|
+
manualToo: true,
|
|
971
|
+
});
|
|
972
|
+
}
|
|
973
|
+
if (draft !== undefined) {
|
|
974
|
+
if (draft.trim().length < shared.config.minPromptChars) {
|
|
975
|
+
blocks.push({ reason: `the draft is shorter than min-chars (${shared.config.minPromptChars})`, manualToo: false });
|
|
976
|
+
}
|
|
977
|
+
if (shouldSkipPromptAutocomplete(draft)) {
|
|
978
|
+
blocks.push({ reason: "the draft looks like a slash command or path", manualToo: true });
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
if (isBudgetExhausted(shared)) {
|
|
982
|
+
blocks.push({
|
|
983
|
+
reason: `the session budget is exhausted (${shared.budgetUsed}/${shared.config.budgetLimit})`,
|
|
984
|
+
manualToo: true,
|
|
985
|
+
});
|
|
986
|
+
}
|
|
987
|
+
return {
|
|
988
|
+
automatic: blocks[0]?.reason,
|
|
989
|
+
manual: blocks.find((block) => block.manualToo)?.reason,
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
/**
|
|
994
|
+
* Local, bounded preview of what an autocomplete request would transmit.
|
|
995
|
+
*
|
|
996
|
+
* It renders the same snapshot the provider path uses and makes no provider
|
|
997
|
+
* request. Without explicit draft text it reports the conversation sections
|
|
998
|
+
* only: the submitted slash command replaced the editor text, so the draft a
|
|
999
|
+
* real request would carry cannot be recovered and is not invented.
|
|
1000
|
+
*/
|
|
1001
|
+
function formatPromptAutocompleteInspection(
|
|
1002
|
+
shared: PromptAutocompleteSharedState,
|
|
1003
|
+
interactiveHost: boolean,
|
|
1004
|
+
draft: string | undefined,
|
|
1005
|
+
): string {
|
|
1006
|
+
const snapshot = buildCurrentRequestSnapshot(shared, draft ?? "", resolveCurrentConversationId(shared));
|
|
1007
|
+
const resolution = resolveSuggestionModelResolution(shared);
|
|
1008
|
+
const requestedSource = resolvePersistedModelSelection(
|
|
1009
|
+
shared.runtimeOverrides.modelSelection,
|
|
1010
|
+
shared.modelFlagExplicit,
|
|
1011
|
+
parsePersistedModelRaw(shared.persistedSettings.model),
|
|
1012
|
+
).source;
|
|
1013
|
+
const policy = evaluateSharedRequestPolicy(shared, interactiveHost, draft);
|
|
1014
|
+
const mainAgent = shared.agentStreaming
|
|
1015
|
+
? shared.config.allowWhileStreaming ? "working (requests allowed)" : "working"
|
|
1016
|
+
: "idle";
|
|
1017
|
+
const verdict = (reason: string | undefined) =>
|
|
1018
|
+
reason ? `blocked (${truncateDebug(reason, 120)})` : "allowed";
|
|
1019
|
+
|
|
1020
|
+
const draftLine = draft === undefined
|
|
1021
|
+
? "Draft: not available — the slash command replaced the editor text. "
|
|
1022
|
+
+ "Run /prompt-autocomplete inspect <draft text> to preview one."
|
|
1023
|
+
: `Draft: ${snapshot.draft.length} chars, ${snapshot.draftTail.length} sent `
|
|
1024
|
+
+ `(only the last ${MAX_DRAFT_CONTEXT_CHARS} are sent): "${truncateDebug(snapshot.draftTail, INSPECT_EXCERPT_CHARS)}"`;
|
|
1025
|
+
const sizeLine = draft === undefined
|
|
1026
|
+
? `Request size: system prompt ${PROMPT_AUTOCOMPLETE_SYSTEM_PROMPT.length} chars + one user message whose size depends on the draft`
|
|
1027
|
+
: `Request size: system prompt ${PROMPT_AUTOCOMPLETE_SYSTEM_PROMPT.length} chars + user message `
|
|
1028
|
+
+ `${renderPromptAutocompleteUserText(snapshot).length} chars`;
|
|
1029
|
+
|
|
1030
|
+
return [
|
|
1031
|
+
"Prompt Autocomplete — request inspection (local only; no provider request was made)",
|
|
1032
|
+
`Model: ${truncateDebug(formatModelLabel(resolution.model), 90)} · requested `
|
|
1033
|
+
+ `${describePromptAutocompleteModelSelection(shared.config.modelSelection)}(${requestedSource})`,
|
|
1034
|
+
`Shared policy: automatic ${verdict(policy.automatic)} · manual ${verdict(policy.manual)}`,
|
|
1035
|
+
` enabled=${shared.enabled ? "yes" : "no"} editor=${describeEditorState(shared, interactiveHost)} `
|
|
1036
|
+
+ `main-agent=${mainAgent} auth=${resolution.model ? "configured" : "unavailable"} budget=${formatBudget(shared)}`,
|
|
1037
|
+
draftLine,
|
|
1038
|
+
formatInspectionSection(
|
|
1039
|
+
"Latest assistant message",
|
|
1040
|
+
snapshot.latestAssistantContext,
|
|
1041
|
+
`cap ${MAX_LATEST_ASSISTANT_MESSAGE_CHARS}`,
|
|
1042
|
+
),
|
|
1043
|
+
formatInspectionSection("Latest user message", snapshot.latestUserContext, `cap ${MAX_LATEST_USER_MESSAGE_CHARS}`),
|
|
1044
|
+
formatInspectionSection(
|
|
1045
|
+
"Recent conversation",
|
|
1046
|
+
snapshot.recentContext,
|
|
1047
|
+
`up to ${MAX_CONTEXT_MESSAGES} messages × ${MAX_CONTEXT_MESSAGE_CHARS} chars`,
|
|
1048
|
+
),
|
|
1049
|
+
formatInspectionSection(
|
|
1050
|
+
"Compaction summary",
|
|
1051
|
+
snapshot.compactionSummaryContext,
|
|
1052
|
+
`cap ${MAX_COMPACTION_SUMMARY_CHARS}, middle elided`,
|
|
1053
|
+
),
|
|
1054
|
+
sizeLine,
|
|
1055
|
+
`Output: up to ${snapshot.maxAlternatives} alternatives × ${snapshot.maxSuggestionChars} chars, `
|
|
1056
|
+
+ `at most ${computeRequestMaxTokens(snapshot.maxAlternatives, snapshot.maxSuggestionChars)} output tokens`,
|
|
1057
|
+
"Not evaluated here (live editor state): cursor position, built-in autocomplete menu, "
|
|
1058
|
+
+ "Escape dismissal, error cooldown, cached responses.",
|
|
1059
|
+
"The conversation id used for caching is local metadata and is never sent; credentials and headers are never shown.",
|
|
1060
|
+
].join("\n");
|
|
1061
|
+
}
|
|
1062
|
+
|
|
663
1063
|
function cloneCacheEntry(entry: PromptAutocompleteCacheEntry): PromptAutocompleteCacheEntry {
|
|
664
1064
|
return { ...entry, suggestions: [...entry.suggestions] };
|
|
665
1065
|
}
|
|
@@ -828,8 +1228,9 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
828
1228
|
let cursorLineIndex = -1;
|
|
829
1229
|
let cursorMatch: RegExpMatchArray | undefined;
|
|
830
1230
|
for (let index = 0; index < lines.length; index++) {
|
|
831
|
-
|
|
832
|
-
|
|
1231
|
+
const line = lines[index]!;
|
|
1232
|
+
if (!CURSOR_CELL_OPENERS.some((opener) => line.includes(opener))) continue;
|
|
1233
|
+
const match = line.match(CURSOR_CELL_PATTERN);
|
|
833
1234
|
if (match?.index !== undefined) {
|
|
834
1235
|
cursorLineIndex = index;
|
|
835
1236
|
cursorMatch = match;
|
|
@@ -841,7 +1242,11 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
841
1242
|
const cursorLine = lines[cursorLineIndex]!;
|
|
842
1243
|
const cursorIndex = cursorMatch.index;
|
|
843
1244
|
const cursorToken = cursorMatch[0];
|
|
844
|
-
|
|
1245
|
+
// The cell holds one space and no escape sequence contains a space, so the
|
|
1246
|
+
// space separates the opening sequence from the closing one.
|
|
1247
|
+
const cursorSpace = cursorToken.indexOf(" ");
|
|
1248
|
+
const cursorOpen = cursorToken.slice(0, cursorSpace);
|
|
1249
|
+
const cursorClose = cursorToken.slice(cursorSpace + 1);
|
|
845
1250
|
|
|
846
1251
|
const before = cursorLine.slice(0, cursorIndex);
|
|
847
1252
|
const after = cursorLine.slice(cursorIndex + cursorToken.length);
|
|
@@ -853,7 +1258,9 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
853
1258
|
const firstPreviewChar = previewChars[0] ?? "";
|
|
854
1259
|
const absorbLeadingWhitespaceIntoCursor = /^[ \t]$/.test(firstPreviewChar);
|
|
855
1260
|
|
|
856
|
-
const cursorCell = absorbLeadingWhitespaceIntoCursor
|
|
1261
|
+
const cursorCell = absorbLeadingWhitespaceIntoCursor
|
|
1262
|
+
? `${cursorOpen}${firstPreviewChar}${cursorClose}`
|
|
1263
|
+
: cursorToken;
|
|
857
1264
|
const renderedPreviewText = absorbLeadingWhitespaceIntoCursor ? previewChars.slice(1).join("") : previewText;
|
|
858
1265
|
|
|
859
1266
|
const indicator = this.suggestions.length > 1 ? ` ‹${this.suggestionIndex + 1}/${this.suggestions.length}›` : "";
|
|
@@ -1140,10 +1547,7 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1140
1547
|
}
|
|
1141
1548
|
|
|
1142
1549
|
if (!this.shared.ownsEditor?.()) {
|
|
1143
|
-
this.
|
|
1144
|
-
this.shared.editorBlockedReason = "Another extension replaced the prompt-autocomplete editor";
|
|
1145
|
-
updateDebugState(this.shared, "ownership-lost", this.shared.editorBlockedReason);
|
|
1146
|
-
this.setSuggestions([]);
|
|
1550
|
+
this.releaseForOwnershipLoss();
|
|
1147
1551
|
return;
|
|
1148
1552
|
}
|
|
1149
1553
|
|
|
@@ -1219,6 +1623,22 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1219
1623
|
}
|
|
1220
1624
|
|
|
1221
1625
|
const shouldJoinInFlight = this.shared.inFlightRequests.has(request.cacheKey);
|
|
1626
|
+
|
|
1627
|
+
// Cache hits and joins of existing work stay free above the ceiling; only a
|
|
1628
|
+
// request that would start new provider work is blocked here. The producer
|
|
1629
|
+
// still re-checks and reserves, which is what makes concurrency safe.
|
|
1630
|
+
if (!shouldJoinInFlight && isBudgetExhausted(this.shared)) {
|
|
1631
|
+
this.cancelPendingRequest();
|
|
1632
|
+
updateDebugState(
|
|
1633
|
+
this.shared,
|
|
1634
|
+
"budget-exhausted",
|
|
1635
|
+
`Session request budget exhausted (${this.shared.budgetUsed}/${this.shared.config.budgetLimit})`,
|
|
1636
|
+
);
|
|
1637
|
+
notifyBudgetExhaustedOnce(this.shared);
|
|
1638
|
+
this.setSuggestions([]);
|
|
1639
|
+
return;
|
|
1640
|
+
}
|
|
1641
|
+
|
|
1222
1642
|
this.cancelPendingRequest();
|
|
1223
1643
|
|
|
1224
1644
|
const seq = ++this.requestSeq;
|
|
@@ -1250,40 +1670,31 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1250
1670
|
const model = resolveSuggestionModel(this.shared);
|
|
1251
1671
|
if (!model) return undefined;
|
|
1252
1672
|
|
|
1253
|
-
const
|
|
1254
|
-
|
|
1255
|
-
const
|
|
1256
|
-
const latestUserContext = buildLatestUserMessageContext(branch);
|
|
1257
|
-
const recentContext = buildRecentConversationContext(branch);
|
|
1258
|
-
const draftTail = truncateDraftTail(draft, MAX_DRAFT_CONTEXT_CHARS);
|
|
1673
|
+
const conversationId = resolveCurrentConversationId(this.shared);
|
|
1674
|
+
this.shared.lastConversationId = conversationId;
|
|
1675
|
+
const snapshot = buildCurrentRequestSnapshot(this.shared, this.getText(), conversationId);
|
|
1259
1676
|
const modelLabel = formatModelLabel(model);
|
|
1260
|
-
const leafId = this.shared.sessionManager?.getLeafId?.() ?? "";
|
|
1261
1677
|
|
|
1262
1678
|
const prefixContextIdentity = {
|
|
1263
|
-
|
|
1679
|
+
conversationId,
|
|
1264
1680
|
modelLabel,
|
|
1265
|
-
maxAlternatives:
|
|
1266
|
-
maxSuggestionChars:
|
|
1267
|
-
latestAssistantContext,
|
|
1268
|
-
latestUserContext,
|
|
1269
|
-
recentContext,
|
|
1681
|
+
maxAlternatives: snapshot.maxAlternatives,
|
|
1682
|
+
maxSuggestionChars: snapshot.maxSuggestionChars,
|
|
1683
|
+
latestAssistantContext: snapshot.latestAssistantContext,
|
|
1684
|
+
latestUserContext: snapshot.latestUserContext,
|
|
1685
|
+
recentContext: snapshot.recentContext,
|
|
1686
|
+
compactionSummaryContext: snapshot.compactionSummaryContext,
|
|
1270
1687
|
};
|
|
1271
1688
|
|
|
1272
1689
|
return {
|
|
1690
|
+
...snapshot,
|
|
1273
1691
|
activationId: this.activationId,
|
|
1274
|
-
|
|
1275
|
-
draft,
|
|
1276
|
-
draftTail,
|
|
1692
|
+
conversationId,
|
|
1277
1693
|
model,
|
|
1278
1694
|
modelLabel,
|
|
1279
|
-
cacheKey: buildPromptAutocompleteCacheKey({ ...prefixContextIdentity, draft }),
|
|
1695
|
+
cacheKey: buildPromptAutocompleteCacheKey({ ...prefixContextIdentity, draft: snapshot.draft }),
|
|
1280
1696
|
prefixContextKey: buildPromptAutocompletePrefixContextKey(prefixContextIdentity),
|
|
1281
|
-
maxAlternatives: this.shared.config.maxAlternatives,
|
|
1282
|
-
maxSuggestionChars: this.shared.config.maxSuggestionChars,
|
|
1283
1697
|
useStreaming: this.shared.config.streamResponses && !!this.shared.streamSimple,
|
|
1284
|
-
latestAssistantContext,
|
|
1285
|
-
latestUserContext,
|
|
1286
|
-
recentContext,
|
|
1287
1698
|
};
|
|
1288
1699
|
}
|
|
1289
1700
|
|
|
@@ -1315,6 +1726,7 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1315
1726
|
try {
|
|
1316
1727
|
const entry = await subscription.promise;
|
|
1317
1728
|
if (!this.isRequestStillCurrent(request, seq)) {
|
|
1729
|
+
if (seq === this.requestSeq && !this.shared.ownsEditor?.()) this.releaseForOwnershipLoss();
|
|
1318
1730
|
return;
|
|
1319
1731
|
}
|
|
1320
1732
|
|
|
@@ -1328,7 +1740,18 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1328
1740
|
this.setSuggestions(entry.suggestions);
|
|
1329
1741
|
}
|
|
1330
1742
|
} catch (error) {
|
|
1331
|
-
if (
|
|
1743
|
+
if (error instanceof PromptAutocompleteBudgetExhaustedError) {
|
|
1744
|
+
// Not a provider failure: no cooldown, no failure stat, no provider call.
|
|
1745
|
+
if (this.isRequestStillCurrent(request, seq)) {
|
|
1746
|
+
updateDebugState(
|
|
1747
|
+
this.shared,
|
|
1748
|
+
"budget-exhausted",
|
|
1749
|
+
`Session request budget exhausted (${this.shared.budgetUsed}/${this.shared.config.budgetLimit})`,
|
|
1750
|
+
);
|
|
1751
|
+
notifyBudgetExhaustedOnce(this.shared);
|
|
1752
|
+
this.setSuggestions([]);
|
|
1753
|
+
}
|
|
1754
|
+
} else if (this.isRequestStillCurrent(request, seq)) {
|
|
1332
1755
|
this.suspendedUntil = this.shared.now() + FAILURE_COOLDOWN_MS;
|
|
1333
1756
|
const message = error instanceof Error ? error.message : String(error);
|
|
1334
1757
|
this.shared.lastError = message;
|
|
@@ -1351,6 +1774,13 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1351
1774
|
spinnerOwner: string,
|
|
1352
1775
|
suggestion: string,
|
|
1353
1776
|
): void {
|
|
1777
|
+
// A replaced editor receives no more input, so streamed progress is the
|
|
1778
|
+
// first boundary at which it can notice. Release the provider work here
|
|
1779
|
+
// instead of letting it run to completion for an editor nobody renders.
|
|
1780
|
+
if (seq === this.requestSeq && !this.shared.ownsEditor?.()) {
|
|
1781
|
+
this.releaseForOwnershipLoss();
|
|
1782
|
+
return;
|
|
1783
|
+
}
|
|
1354
1784
|
if (!this.isRequestStillCurrent(request, seq)) return;
|
|
1355
1785
|
if (request.cacheKey === this.dismissedKey) return;
|
|
1356
1786
|
|
|
@@ -1373,55 +1803,26 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1373
1803
|
}
|
|
1374
1804
|
|
|
1375
1805
|
const auth = await this.shared.modelRegistry.getApiKeyAndHeaders(request.model);
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1806
|
+
// Through the host registry Pi resolves the stored credential itself, which
|
|
1807
|
+
// may be header-only or ambient, so only the compat path needs a key here.
|
|
1808
|
+
const viaRegistry = this.shared.routesThroughHostRegistry();
|
|
1809
|
+
if (!auth.ok) throw new Error(auth.error);
|
|
1810
|
+
if (!viaRegistry && !auth.apiKey) throw new Error(`No API key for ${request.modelLabel}`);
|
|
1379
1811
|
if (signal.aborted) {
|
|
1380
1812
|
throw new Error("Request was aborted");
|
|
1381
1813
|
}
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
if (
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
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"),
|
|
1814
|
+
// Last await is done: reserving here and invoking below without another
|
|
1815
|
+
// await is what keeps two concurrent producers from overshooting a ceiling.
|
|
1816
|
+
if (!reserveBudgetRequest(this.shared)) {
|
|
1817
|
+
throw new PromptAutocompleteBudgetExhaustedError(
|
|
1818
|
+
this.shared.config.budgetLimit ?? this.shared.budgetUsed,
|
|
1819
|
+
this.shared.budgetUsed,
|
|
1419
1820
|
);
|
|
1420
1821
|
}
|
|
1421
1822
|
|
|
1422
1823
|
const userMessage: UserMessage = {
|
|
1423
1824
|
role: "user",
|
|
1424
|
-
content: [{ type: "text", text:
|
|
1825
|
+
content: [{ type: "text", text: renderPromptAutocompleteUserText(request) }],
|
|
1425
1826
|
timestamp: Date.now(),
|
|
1426
1827
|
};
|
|
1427
1828
|
|
|
@@ -1433,8 +1834,10 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1433
1834
|
messages: [userMessage],
|
|
1434
1835
|
};
|
|
1435
1836
|
const requestOptions = {
|
|
1436
|
-
|
|
1437
|
-
|
|
1837
|
+
// An explicit key makes Pi's registry skip the stored credential and with
|
|
1838
|
+
// it any OAuth-derived endpoint (for example GitHub Copilot Enterprise),
|
|
1839
|
+
// so credentials are only passed to the compat functions and to seams.
|
|
1840
|
+
...(viaRegistry ? {} : { apiKey: auth.apiKey, headers: auth.headers }),
|
|
1438
1841
|
signal,
|
|
1439
1842
|
maxTokens: computeRequestMaxTokens(request.maxAlternatives, request.maxSuggestionChars),
|
|
1440
1843
|
timeoutMs: REQUEST_TIMEOUT_MS,
|
|
@@ -1530,10 +1933,11 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1530
1933
|
const currentModel = resolveSuggestionModel(this.shared);
|
|
1531
1934
|
if (formatModelLabel(currentModel) !== request.modelLabel) return false;
|
|
1532
1935
|
|
|
1533
|
-
// Session entries are immutable
|
|
1534
|
-
// from which all bounded context sections were
|
|
1535
|
-
//
|
|
1536
|
-
|
|
1936
|
+
// Session entries are immutable. The context-relevant conversation id
|
|
1937
|
+
// identifies the branch from which all bounded context sections were
|
|
1938
|
+
// derived, without treating custom/label/session-info leaf movement as a
|
|
1939
|
+
// new conversation. Checking it avoids rebuilding that context per token.
|
|
1940
|
+
return resolveCurrentConversationId(this.shared) === request.conversationId;
|
|
1537
1941
|
}
|
|
1538
1942
|
|
|
1539
1943
|
cancelActiveRequest(): void {
|
|
@@ -1541,10 +1945,39 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1541
1945
|
this.setSuggestions([]);
|
|
1542
1946
|
}
|
|
1543
1947
|
|
|
1948
|
+
/**
|
|
1949
|
+
* Drop a waiting debounce without aborting an in-flight provider call.
|
|
1950
|
+
*
|
|
1951
|
+
* A debounce-only config change must not increment the request sequence or
|
|
1952
|
+
* release the active subscription: those belong to work that already started.
|
|
1953
|
+
*/
|
|
1954
|
+
cancelScheduledRequest(): void {
|
|
1955
|
+
if (!this.debounceTimer) return;
|
|
1956
|
+
clearTimeout(this.debounceTimer);
|
|
1957
|
+
this.debounceTimer = undefined;
|
|
1958
|
+
const pending = this.pendingRequests.take();
|
|
1959
|
+
this.deactivateSpinner(pending?.spinnerOwner);
|
|
1960
|
+
}
|
|
1961
|
+
|
|
1544
1962
|
private clearPendingRequestIfOwned(seq: number): void {
|
|
1545
1963
|
this.pendingRequests.clearIfOwned(seq);
|
|
1546
1964
|
}
|
|
1547
1965
|
|
|
1966
|
+
/**
|
|
1967
|
+
* Stop owned work after another extension replaced this editor.
|
|
1968
|
+
*
|
|
1969
|
+
* Pi exposes no editor-change event, so loss is only noticed at the next
|
|
1970
|
+
* boundary this instance observes: an edit, streamed progress, or a terminal
|
|
1971
|
+
* response. A provider that never yields cannot be interrupted earlier. The
|
|
1972
|
+
* foreign editor is never touched.
|
|
1973
|
+
*/
|
|
1974
|
+
private releaseForOwnershipLoss(): void {
|
|
1975
|
+
this.cancelPendingRequest();
|
|
1976
|
+
this.shared.editorBlockedReason = "Another extension replaced the prompt-autocomplete editor";
|
|
1977
|
+
updateDebugState(this.shared, "ownership-lost", this.shared.editorBlockedReason);
|
|
1978
|
+
this.setSuggestions([]);
|
|
1979
|
+
}
|
|
1980
|
+
|
|
1548
1981
|
private cancelPendingRequest(): void {
|
|
1549
1982
|
this.requestSeq += 1;
|
|
1550
1983
|
|
|
@@ -1569,6 +2002,7 @@ function releaseEditorRuntime(shared: PromptAutocompleteSharedState): void {
|
|
|
1569
2002
|
clearDebugUi(shared);
|
|
1570
2003
|
shared.refreshEditor = undefined;
|
|
1571
2004
|
shared.cancelActiveRequest = undefined;
|
|
2005
|
+
shared.cancelScheduledRequest = undefined;
|
|
1572
2006
|
shared.setStatusText = undefined;
|
|
1573
2007
|
shared.setSpinnerActive = undefined;
|
|
1574
2008
|
shared.clearSpinner = undefined;
|
|
@@ -1586,7 +2020,7 @@ function releaseEditorRuntime(shared: PromptAutocompleteSharedState): void {
|
|
|
1586
2020
|
function hostOwnsInteractiveEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): boolean {
|
|
1587
2021
|
// A host that already accepted an editor factory without installing it is not
|
|
1588
2022
|
// interactive, no matter what its capabilities claim.
|
|
1589
|
-
if (shared.hostInstallsEditors === false) return false;
|
|
2023
|
+
if (shared.processState.hostInstallsEditors === false) return false;
|
|
1590
2024
|
const host = ctx as Partial<Pick<ExtensionContext, "mode" | "hasUI" | "ui">>;
|
|
1591
2025
|
return isInteractiveEditorHost({
|
|
1592
2026
|
mode: host.mode,
|
|
@@ -1684,6 +2118,10 @@ function mountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedStat
|
|
|
1684
2118
|
if (activationId !== shared.activationId) return;
|
|
1685
2119
|
editor.cancelActiveRequest();
|
|
1686
2120
|
};
|
|
2121
|
+
shared.cancelScheduledRequest = () => {
|
|
2122
|
+
if (activationId !== shared.activationId) return;
|
|
2123
|
+
editor.cancelScheduledRequest();
|
|
2124
|
+
};
|
|
1687
2125
|
return editor;
|
|
1688
2126
|
};
|
|
1689
2127
|
|
|
@@ -1704,7 +2142,7 @@ function mountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedStat
|
|
|
1704
2142
|
if (ctx.ui.getEditorComponent() !== installedFactory) {
|
|
1705
2143
|
releaseEditorRuntime(shared);
|
|
1706
2144
|
shared.editorMount = undefined;
|
|
1707
|
-
shared.hostInstallsEditors = false;
|
|
2145
|
+
shared.processState.hostInstallsEditors = false;
|
|
1708
2146
|
// Nothing can render or request here, so the extension must not stay marked
|
|
1709
2147
|
// enabled, no matter which path attempted the mount.
|
|
1710
2148
|
shared.enabled = false;
|
|
@@ -1717,7 +2155,7 @@ function mountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedStat
|
|
|
1717
2155
|
return false;
|
|
1718
2156
|
}
|
|
1719
2157
|
|
|
1720
|
-
shared.hostInstallsEditors = true;
|
|
2158
|
+
shared.processState.hostInstallsEditors = true;
|
|
1721
2159
|
updateDebugState(shared, "mounted", "Editor extension attached");
|
|
1722
2160
|
return true;
|
|
1723
2161
|
}
|
|
@@ -1739,10 +2177,20 @@ function unmountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedSt
|
|
|
1739
2177
|
function resetSharedForSession(pi: ExtensionAPI, shared: PromptAutocompleteSharedState): void {
|
|
1740
2178
|
shared.cancelActiveRequest?.();
|
|
1741
2179
|
shared.cancelActiveRequest = undefined;
|
|
2180
|
+
shared.cancelScheduledRequest = undefined;
|
|
2181
|
+
// Budget accounting is physical-session scoped: a new session starts fresh.
|
|
2182
|
+
// Clearing before applyEffectiveConfig keeps the effective ceiling from
|
|
2183
|
+
// silently inheriting the previous session's restored value; session_start
|
|
2184
|
+
// restores this session's own snapshot right afterwards.
|
|
2185
|
+
shared.budgetUsed = 0;
|
|
2186
|
+
shared.savedBudgetLimit = undefined;
|
|
2187
|
+
shared.persistBudgetSnapshot = undefined;
|
|
2188
|
+
shared.budgetSnapshotsActive = false;
|
|
2189
|
+
shared.budgetBlockNotices.clear();
|
|
1742
2190
|
applyEffectiveConfig(pi, shared);
|
|
1743
2191
|
// A host that never installs custom editors stays inactive for the rest of
|
|
1744
2192
|
// the process, so flags must not re-enable it in a later session either.
|
|
1745
|
-
if (shared.hostInstallsEditors === false) shared.enabled = false;
|
|
2193
|
+
if (shared.processState.hostInstallsEditors === false) shared.enabled = false;
|
|
1746
2194
|
shared.usageStats = createPromptAutocompleteUsageStats();
|
|
1747
2195
|
shared.editorMount = undefined;
|
|
1748
2196
|
shared.editorBlockedReason = undefined;
|
|
@@ -1750,6 +2198,7 @@ function resetSharedForSession(pi: ExtensionAPI, shared: PromptAutocompleteShare
|
|
|
1750
2198
|
shared.lastError = undefined;
|
|
1751
2199
|
shared.lastRawResponse = undefined;
|
|
1752
2200
|
shared.reportedModelRefusals.clear();
|
|
2201
|
+
shared.projectedContextMemo = undefined;
|
|
1753
2202
|
shared.requestCache.clear();
|
|
1754
2203
|
shared.prefixReuseCache.clear();
|
|
1755
2204
|
cancelAllCoalescedRequests(shared.inFlightRequests);
|
|
@@ -1760,7 +2209,81 @@ function bindRuntimeContext(ctx: ExtensionContext, shared: PromptAutocompleteSha
|
|
|
1760
2209
|
shared.currentModel = ctx.model as Model<Api> | undefined;
|
|
1761
2210
|
shared.modelRegistry = ctx.modelRegistry;
|
|
1762
2211
|
shared.sessionManager = ctx.sessionManager;
|
|
2212
|
+
shared.physicalSessionId = readPhysicalSessionId(ctx);
|
|
2213
|
+
shared.lastConversationId = resolveCurrentConversationId(shared);
|
|
2214
|
+
rememberAgentSettledSupport(ctx, shared);
|
|
2215
|
+
shared.agentStreaming = false;
|
|
2216
|
+
}
|
|
2217
|
+
|
|
2218
|
+
function readPhysicalSessionId(ctx: ExtensionContext): string {
|
|
2219
|
+
const sessionId = ctx.sessionManager?.getSessionId?.();
|
|
2220
|
+
return typeof sessionId === "string" ? sessionId : "";
|
|
2221
|
+
}
|
|
2222
|
+
|
|
2223
|
+
/**
|
|
2224
|
+
* The request snapshot for `draft` against the model-visible conversation and
|
|
2225
|
+
* the output configuration. Shared by the editor's provider path and by
|
|
2226
|
+
* inspection, so both read the same context source.
|
|
2227
|
+
*/
|
|
2228
|
+
function buildCurrentRequestSnapshot(
|
|
2229
|
+
shared: PromptAutocompleteSharedState,
|
|
2230
|
+
draft: string,
|
|
2231
|
+
conversationId: string,
|
|
2232
|
+
): PromptAutocompleteRequestSnapshot {
|
|
2233
|
+
return buildPromptAutocompleteRequestSnapshot({
|
|
2234
|
+
draft,
|
|
2235
|
+
branch: readAutocompleteContextEntries(shared, conversationId),
|
|
2236
|
+
maxAlternatives: shared.config.maxAlternatives,
|
|
2237
|
+
maxSuggestionChars: shared.config.maxSuggestionChars,
|
|
2238
|
+
});
|
|
2239
|
+
}
|
|
2240
|
+
|
|
2241
|
+
/**
|
|
2242
|
+
* Conversation entries autocomplete may draw context from.
|
|
2243
|
+
*
|
|
2244
|
+
* Hosts with a session projection (Pi 1.x) supply the model-visible context,
|
|
2245
|
+
* so messages omitted or replaced by `context_edit` stay out of autocomplete
|
|
2246
|
+
* requests as well. A projection that throws yields no conversation context
|
|
2247
|
+
* instead of the raw branch. Older hosts have no context edits, so their raw
|
|
2248
|
+
* branch is used as before.
|
|
2249
|
+
*
|
|
2250
|
+
* Autocomplete context covers user and assistant message text plus, on hosts
|
|
2251
|
+
* with a projection, the newest compaction summary; the projection decides
|
|
2252
|
+
* which of those the model still sees and in which form. Compaction system
|
|
2253
|
+
* checkpoints, branch summaries, custom messages, and tool results are never
|
|
2254
|
+
* included.
|
|
2255
|
+
*/
|
|
2256
|
+
function readAutocompleteContextEntries(shared: PromptAutocompleteSharedState, conversationId: string): unknown[] {
|
|
2257
|
+
const manager = shared.sessionManager;
|
|
2258
|
+
if (typeof manager?.buildSessionProjection === "function") {
|
|
2259
|
+
const memo = shared.projectedContextMemo;
|
|
2260
|
+
if (memo?.conversationId === conversationId) return memo.entries;
|
|
2261
|
+
try {
|
|
2262
|
+
const entries = projectAutocompleteContextEntries(manager.buildSessionProjection());
|
|
2263
|
+
shared.projectedContextMemo = { conversationId, entries };
|
|
2264
|
+
return entries;
|
|
2265
|
+
} catch {
|
|
2266
|
+
return [];
|
|
2267
|
+
}
|
|
2268
|
+
}
|
|
2269
|
+
return manager?.getBranch?.() ?? [];
|
|
2270
|
+
}
|
|
2271
|
+
|
|
2272
|
+
function resolveCurrentConversationId(shared: PromptAutocompleteSharedState): string {
|
|
2273
|
+
const branch = shared.sessionManager?.getBranch?.() ?? [];
|
|
2274
|
+
const leafId = shared.sessionManager?.getLeafId?.() ?? "";
|
|
2275
|
+
return resolveAutocompleteConversationId(branch, leafId || shared.physicalSessionId);
|
|
2276
|
+
}
|
|
2277
|
+
|
|
2278
|
+
function rememberAgentSettledSupport(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): void {
|
|
2279
|
+
if (shared.hostEmitsAgentSettled !== undefined) return;
|
|
2280
|
+
shared.hostEmitsAgentSettled = typeof ctx.isIdle === "function";
|
|
2281
|
+
}
|
|
2282
|
+
|
|
2283
|
+
function settleAgentTurn(shared: PromptAutocompleteSharedState, details: string): void {
|
|
1763
2284
|
shared.agentStreaming = false;
|
|
2285
|
+
if (!shared.enabled) return;
|
|
2286
|
+
refreshEditorImmediately(shared, "ready", details);
|
|
1764
2287
|
}
|
|
1765
2288
|
|
|
1766
2289
|
function refreshEditorImmediately(shared: PromptAutocompleteSharedState, state: string, details: string): void {
|
|
@@ -1842,6 +2365,68 @@ function setStreamResponses(
|
|
|
1842
2365
|
}
|
|
1843
2366
|
}
|
|
1844
2367
|
|
|
2368
|
+
function describeBudget(shared: PromptAutocompleteSharedState): { value: string; source: string } {
|
|
2369
|
+
const resolution = resolvePromptAutocompleteBudgetLimit(
|
|
2370
|
+
shared.runtimeOverrides.budgetLimit,
|
|
2371
|
+
shared.budgetFlagExplicit,
|
|
2372
|
+
shared.savedBudgetLimit,
|
|
2373
|
+
);
|
|
2374
|
+
return {
|
|
2375
|
+
value: resolution.limit === undefined ? "off" : `${shared.budgetUsed}/${resolution.limit}`,
|
|
2376
|
+
source: resolution.source,
|
|
2377
|
+
};
|
|
2378
|
+
}
|
|
2379
|
+
|
|
2380
|
+
function formatBudget(shared: PromptAutocompleteSharedState): string {
|
|
2381
|
+
const { value, source } = describeBudget(shared);
|
|
2382
|
+
return `${value}(${source})`;
|
|
2383
|
+
}
|
|
2384
|
+
|
|
2385
|
+
/**
|
|
2386
|
+
* Set the session request ceiling.
|
|
2387
|
+
*
|
|
2388
|
+
* The decision is session-scoped by design: it is snapshotted into the current
|
|
2389
|
+
* session's entries, never into the process-wide settings file.
|
|
2390
|
+
*/
|
|
2391
|
+
function setBudgetLimit(
|
|
2392
|
+
ctx: ExtensionContext,
|
|
2393
|
+
shared: PromptAutocompleteSharedState,
|
|
2394
|
+
arg: string | undefined,
|
|
2395
|
+
): void {
|
|
2396
|
+
const parsed = parsePromptAutocompleteBudgetValue(arg);
|
|
2397
|
+
if (parsed.kind === "unset") {
|
|
2398
|
+
const { value, source } = describeBudget(shared);
|
|
2399
|
+
ctx.ui.notify(
|
|
2400
|
+
`Prompt autocomplete budget is ${value} (${source}); ${shared.budgetUsed} provider request${
|
|
2401
|
+
shared.budgetUsed === 1 ? "" : "s"
|
|
2402
|
+
} used this session`,
|
|
2403
|
+
"info",
|
|
2404
|
+
);
|
|
2405
|
+
return;
|
|
2406
|
+
}
|
|
2407
|
+
if (parsed.kind === "invalid") {
|
|
2408
|
+
ctx.ui.notify(
|
|
2409
|
+
`Usage: /prompt-autocomplete budget <${BUDGET_REQUESTS_MIN}-${BUDGET_REQUESTS_MAX}|off>`,
|
|
2410
|
+
"warning",
|
|
2411
|
+
);
|
|
2412
|
+
return;
|
|
2413
|
+
}
|
|
2414
|
+
|
|
2415
|
+
shared.runtimeOverrides.budgetLimit = parsed.kind === "off" ? "off" : parsed.value;
|
|
2416
|
+
const nextLimit = parsed.kind === "off" ? undefined : parsed.value;
|
|
2417
|
+
// Only a real transition is a new exhaustion state worth reporting again.
|
|
2418
|
+
if (nextLimit !== shared.config.budgetLimit) shared.budgetBlockNotices.clear();
|
|
2419
|
+
shared.config.budgetLimit = nextLimit;
|
|
2420
|
+
persistBudgetSnapshot(shared);
|
|
2421
|
+
updateDebugState(shared, "configured", `Budget ${formatBudget(shared)}`);
|
|
2422
|
+
ctx.ui.notify(
|
|
2423
|
+
parsed.kind === "off"
|
|
2424
|
+
? `Prompt autocomplete budget off (${shared.budgetUsed} request${shared.budgetUsed === 1 ? "" : "s"} used this session)`
|
|
2425
|
+
: `Prompt autocomplete budget set to ${parsed.value} provider request${parsed.value === 1 ? "" : "s"} per session (${shared.budgetUsed} used)`,
|
|
2426
|
+
"info",
|
|
2427
|
+
);
|
|
2428
|
+
}
|
|
2429
|
+
|
|
1845
2430
|
function setMinPromptChars(
|
|
1846
2431
|
ctx: ExtensionContext,
|
|
1847
2432
|
shared: PromptAutocompleteSharedState,
|
|
@@ -1873,9 +2458,11 @@ function setMinPromptChars(
|
|
|
1873
2458
|
const changed = shared.config.minPromptChars !== parsed;
|
|
1874
2459
|
shared.config.minPromptChars = parsed;
|
|
1875
2460
|
shared.runtimeOverrides.minPromptChars = parsed;
|
|
1876
|
-
persistSettingsDecision(ctx, shared, { minPromptChars: parsed });
|
|
2461
|
+
const persisted = persistSettingsDecision(ctx, shared, { minPromptChars: parsed });
|
|
1877
2462
|
ctx.ui.notify(
|
|
1878
|
-
`Prompt autocomplete min-chars set to ${parsed}
|
|
2463
|
+
`Prompt autocomplete min-chars set to ${parsed}${
|
|
2464
|
+
persisted ? " (saved for future sessions)" : " (session only — could not save for future sessions)"
|
|
2465
|
+
}`,
|
|
1879
2466
|
"info",
|
|
1880
2467
|
);
|
|
1881
2468
|
|
|
@@ -1894,21 +2481,322 @@ function persistSettingsDecision(
|
|
|
1894
2481
|
ctx: ExtensionContext,
|
|
1895
2482
|
shared: PromptAutocompleteSharedState,
|
|
1896
2483
|
patch: Partial<PromptAutocompletePersistedSettings>,
|
|
1897
|
-
):
|
|
2484
|
+
): boolean {
|
|
1898
2485
|
shared.persistedSettings = { ...shared.persistedSettings, ...patch };
|
|
1899
2486
|
const store = shared.settingsStore;
|
|
1900
|
-
if (!store) return;
|
|
2487
|
+
if (!store) return false;
|
|
1901
2488
|
try {
|
|
1902
2489
|
store.save(shared.persistedSettings);
|
|
2490
|
+
return true;
|
|
1903
2491
|
} catch (error) {
|
|
1904
2492
|
const reason = error instanceof Error ? error.message : String(error);
|
|
1905
2493
|
ctx.ui.notify(
|
|
1906
2494
|
`Prompt autocomplete could not save the setting: ${truncateDebug(reason, 90)}`,
|
|
1907
2495
|
"warning",
|
|
1908
2496
|
);
|
|
2497
|
+
return false;
|
|
1909
2498
|
}
|
|
1910
2499
|
}
|
|
1911
2500
|
|
|
2501
|
+
function isBudgetExhausted(shared: PromptAutocompleteSharedState): boolean {
|
|
2502
|
+
return shared.config.budgetLimit !== undefined && shared.budgetUsed >= shared.config.budgetLimit;
|
|
2503
|
+
}
|
|
2504
|
+
|
|
2505
|
+
function notifyBudgetExhaustedOnce(shared: PromptAutocompleteSharedState): void {
|
|
2506
|
+
const limit = shared.config.budgetLimit;
|
|
2507
|
+
if (limit === undefined) return;
|
|
2508
|
+
const key = `${shared.budgetUsed}/${limit}`;
|
|
2509
|
+
if (shared.budgetBlockNotices.has(key)) return;
|
|
2510
|
+
shared.budgetBlockNotices.add(key);
|
|
2511
|
+
shared.notify?.(
|
|
2512
|
+
`Prompt autocomplete session budget exhausted (${shared.budgetUsed}/${limit} provider requests). `
|
|
2513
|
+
+ "Raise it with /prompt-autocomplete budget <n> or disable it with /prompt-autocomplete budget off.",
|
|
2514
|
+
"warning",
|
|
2515
|
+
);
|
|
2516
|
+
}
|
|
2517
|
+
|
|
2518
|
+
/**
|
|
2519
|
+
* Authoritative budget admission inside a request producer.
|
|
2520
|
+
*
|
|
2521
|
+
* Called synchronously after the last await (successful auth) and before the
|
|
2522
|
+
* provider invocation, so two concurrent producers can never both pass a
|
|
2523
|
+
* limit of one. Failed and aborted calls keep their reservation; auth
|
|
2524
|
+
* failures never reach this point and consume nothing.
|
|
2525
|
+
*
|
|
2526
|
+
* Every real invocation advances the physical-session count, including while
|
|
2527
|
+
* the ceiling is off: enabling a ceiling later must not hand out an allowance
|
|
2528
|
+
* that ignores what this session already spent. Snapshots are written while a
|
|
2529
|
+
* ceiling exists and, once this session carries durable budget state, also for
|
|
2530
|
+
* uncapped invocations — so a session that never touched the budget still adds
|
|
2531
|
+
* no session entries.
|
|
2532
|
+
*/
|
|
2533
|
+
function reserveBudgetRequest(shared: PromptAutocompleteSharedState): boolean {
|
|
2534
|
+
const limit = shared.config.budgetLimit;
|
|
2535
|
+
if (limit !== undefined && shared.budgetUsed >= limit) return false;
|
|
2536
|
+
shared.budgetUsed += 1;
|
|
2537
|
+
if (limit !== undefined || shared.budgetSnapshotsActive) persistBudgetSnapshot(shared);
|
|
2538
|
+
return true;
|
|
2539
|
+
}
|
|
2540
|
+
|
|
2541
|
+
function persistBudgetSnapshot(shared: PromptAutocompleteSharedState): void {
|
|
2542
|
+
if (!shared.physicalSessionId || !shared.persistBudgetSnapshot) return;
|
|
2543
|
+
shared.budgetSnapshotsActive = true;
|
|
2544
|
+
shared.persistBudgetSnapshot(
|
|
2545
|
+
shared.config.budgetLimit === undefined ? "off" : shared.config.budgetLimit,
|
|
2546
|
+
shared.budgetUsed,
|
|
2547
|
+
);
|
|
2548
|
+
}
|
|
2549
|
+
|
|
2550
|
+
/**
|
|
2551
|
+
* Restore this physical session's budget from its own entries and bind the
|
|
2552
|
+
* snapshot writer for the session.
|
|
2553
|
+
*
|
|
2554
|
+
* `/reload` and `/resume` re-run `session_start` on the same session file, so
|
|
2555
|
+
* the session's own snapshots re-establish usage and the ceiling; `/new` and
|
|
2556
|
+
* `/fork` start a session whose entries hold no (or foreign) snapshots and
|
|
2557
|
+
* begin with a fresh budget. Hosts without `appendEntry` keep the in-process
|
|
2558
|
+
* ceiling without durable snapshots.
|
|
2559
|
+
*/
|
|
2560
|
+
function restoreBudgetFromSession(pi: ExtensionAPI, shared: PromptAutocompleteSharedState): void {
|
|
2561
|
+
const snapshot = findPromptAutocompleteBudgetSnapshot(
|
|
2562
|
+
readSessionEntries(shared),
|
|
2563
|
+
shared.physicalSessionId,
|
|
2564
|
+
);
|
|
2565
|
+
if (snapshot) {
|
|
2566
|
+
shared.budgetUsed = snapshot.used;
|
|
2567
|
+
shared.savedBudgetLimit = snapshot.limit;
|
|
2568
|
+
// This session already accounts durably: keep it that way even if the
|
|
2569
|
+
// restored decision is an explicit off.
|
|
2570
|
+
shared.budgetSnapshotsActive = true;
|
|
2571
|
+
}
|
|
2572
|
+
// Always recompute: resetSharedForSession cleared the previous session's
|
|
2573
|
+
// restored ceiling, so the effective config must follow even when this
|
|
2574
|
+
// session has no snapshot of its own.
|
|
2575
|
+
applyEffectiveConfig(pi, shared);
|
|
2576
|
+
if (typeof pi.appendEntry !== "function") return;
|
|
2577
|
+
shared.persistBudgetSnapshot = (limit, used) => {
|
|
2578
|
+
try {
|
|
2579
|
+
pi.appendEntry(
|
|
2580
|
+
PROMPT_AUTOCOMPLETE_BUDGET_ENTRY_TYPE,
|
|
2581
|
+
buildPromptAutocompleteBudgetSnapshot(limit, used, shared.physicalSessionId),
|
|
2582
|
+
);
|
|
2583
|
+
} catch {
|
|
2584
|
+
// Durability is best-effort: the in-process ceiling still applies.
|
|
2585
|
+
}
|
|
2586
|
+
};
|
|
2587
|
+
}
|
|
2588
|
+
|
|
2589
|
+
/**
|
|
2590
|
+
* Every entry of the current session, falling back to the current branch.
|
|
2591
|
+
*
|
|
2592
|
+
* The ceiling is a physical-session fact, so restoring it must not depend on
|
|
2593
|
+
* the current leaf path: a request paid for on a branch the user later left
|
|
2594
|
+
* was still paid for.
|
|
2595
|
+
*/
|
|
2596
|
+
function readSessionEntries(shared: PromptAutocompleteSharedState): unknown[] {
|
|
2597
|
+
const manager = shared.sessionManager as
|
|
2598
|
+
| { getEntries?: () => unknown[]; getBranch?: () => unknown[] }
|
|
2599
|
+
| undefined;
|
|
2600
|
+
const entries = manager?.getEntries?.();
|
|
2601
|
+
if (Array.isArray(entries)) return entries;
|
|
2602
|
+
return manager?.getBranch?.() ?? [];
|
|
2603
|
+
}
|
|
2604
|
+
|
|
2605
|
+
function requestIdentityFingerprint(shared: PromptAutocompleteSharedState): string {
|
|
2606
|
+
return JSON.stringify({
|
|
2607
|
+
model: formatModelLabel(resolveSuggestionModel(shared)),
|
|
2608
|
+
maxAlternatives: shared.config.maxAlternatives,
|
|
2609
|
+
maxSuggestionChars: shared.config.maxSuggestionChars,
|
|
2610
|
+
});
|
|
2611
|
+
}
|
|
2612
|
+
|
|
2613
|
+
function invalidateRequestCaches(shared: PromptAutocompleteSharedState): void {
|
|
2614
|
+
shared.requestCache.clear();
|
|
2615
|
+
shared.prefixReuseCache.clear();
|
|
2616
|
+
cancelAllCoalescedRequests(shared.inFlightRequests);
|
|
2617
|
+
}
|
|
2618
|
+
|
|
2619
|
+
interface ConfigTransaction {
|
|
2620
|
+
apply(): void;
|
|
2621
|
+
persist?: Partial<PromptAutocompletePersistedSettings>;
|
|
2622
|
+
/** When true, abort in-flight work and drop caches. Debounce-only changes stay false. */
|
|
2623
|
+
affectsRequestIdentity: boolean;
|
|
2624
|
+
notify: string;
|
|
2625
|
+
}
|
|
2626
|
+
|
|
2627
|
+
function applyConfigTransaction(
|
|
2628
|
+
ctx: ExtensionContext,
|
|
2629
|
+
shared: PromptAutocompleteSharedState,
|
|
2630
|
+
transaction: ConfigTransaction,
|
|
2631
|
+
): void {
|
|
2632
|
+
const previousIdentity = requestIdentityFingerprint(shared);
|
|
2633
|
+
transaction.apply();
|
|
2634
|
+
const persisted = transaction.persist
|
|
2635
|
+
? persistSettingsDecision(ctx, shared, transaction.persist)
|
|
2636
|
+
: false;
|
|
2637
|
+
const identityChanged = transaction.affectsRequestIdentity
|
|
2638
|
+
&& requestIdentityFingerprint(shared) !== previousIdentity;
|
|
2639
|
+
if (identityChanged) {
|
|
2640
|
+
shared.cancelActiveRequest?.();
|
|
2641
|
+
invalidateRequestCaches(shared);
|
|
2642
|
+
updateDebugState(shared, "configured", transaction.notify);
|
|
2643
|
+
} else if (!transaction.affectsRequestIdentity) {
|
|
2644
|
+
shared.cancelScheduledRequest?.();
|
|
2645
|
+
updateDebugState(shared, "configured", transaction.notify);
|
|
2646
|
+
}
|
|
2647
|
+
// A failed store write already warned above; the success notice must not
|
|
2648
|
+
// contradict it by claiming the decision is durable.
|
|
2649
|
+
ctx.ui.notify(
|
|
2650
|
+
transaction.persist
|
|
2651
|
+
? `${transaction.notify}${persisted ? " (saved for future sessions)" : " (session only — could not save for future sessions)"}`
|
|
2652
|
+
: transaction.notify,
|
|
2653
|
+
"info",
|
|
2654
|
+
);
|
|
2655
|
+
}
|
|
2656
|
+
|
|
2657
|
+
function setBoundedConfigField(
|
|
2658
|
+
ctx: ExtensionContext,
|
|
2659
|
+
shared: PromptAutocompleteSharedState,
|
|
2660
|
+
options: {
|
|
2661
|
+
key: string;
|
|
2662
|
+
field: "debounceMs" | "maxSuggestionChars" | "maxAlternatives";
|
|
2663
|
+
min: number;
|
|
2664
|
+
max: number;
|
|
2665
|
+
value: string;
|
|
2666
|
+
affectsRequestIdentity: boolean;
|
|
2667
|
+
},
|
|
2668
|
+
): void {
|
|
2669
|
+
const parsed = parseStrictBoundedInt(options.value, options.min, options.max);
|
|
2670
|
+
if (parsed === undefined) {
|
|
2671
|
+
ctx.ui.notify(
|
|
2672
|
+
`Usage: /prompt-autocomplete set ${options.key} <${options.min}-${options.max}>`,
|
|
2673
|
+
"warning",
|
|
2674
|
+
);
|
|
2675
|
+
return;
|
|
2676
|
+
}
|
|
2677
|
+
applyConfigTransaction(ctx, shared, {
|
|
2678
|
+
apply: () => {
|
|
2679
|
+
shared.config[options.field] = parsed;
|
|
2680
|
+
shared.runtimeOverrides[options.field] = parsed;
|
|
2681
|
+
},
|
|
2682
|
+
persist: { [options.field]: parsed },
|
|
2683
|
+
affectsRequestIdentity: options.affectsRequestIdentity,
|
|
2684
|
+
notify: `Prompt autocomplete ${options.key} set to ${parsed}`,
|
|
2685
|
+
});
|
|
2686
|
+
}
|
|
2687
|
+
|
|
2688
|
+
function setModelSetting(ctx: ExtensionContext, shared: PromptAutocompleteSharedState, raw: string): void {
|
|
2689
|
+
const selection = parsePromptAutocompleteModelSelection(raw);
|
|
2690
|
+
if (selection.kind === "invalid") {
|
|
2691
|
+
ctx.ui.notify(
|
|
2692
|
+
`Prompt autocomplete model ${describePromptAutocompleteModelSelection(selection)} is not a provider/model reference.`,
|
|
2693
|
+
"warning",
|
|
2694
|
+
);
|
|
2695
|
+
return;
|
|
2696
|
+
}
|
|
2697
|
+
|
|
2698
|
+
if (selection.kind === "dedicated") {
|
|
2699
|
+
const resolution = resolveSuggestionModelResolution(shared, selection);
|
|
2700
|
+
if (!resolution.model) {
|
|
2701
|
+
ctx.ui.notify(
|
|
2702
|
+
resolution.refusedRequest ?? resolution.reason ?? PROMPT_AUTOCOMPLETE_SET_USAGE,
|
|
2703
|
+
"warning",
|
|
2704
|
+
);
|
|
2705
|
+
return;
|
|
2706
|
+
}
|
|
2707
|
+
} else if (shared.currentModel) {
|
|
2708
|
+
// `active` is a selector that follows the session model, so it stays
|
|
2709
|
+
// committable while no model is known yet. Once the target is known it
|
|
2710
|
+
// must be usable: silently switching a working dedicated model to an
|
|
2711
|
+
// unusable active model would cancel live work and deaden autocomplete.
|
|
2712
|
+
const resolution = resolveSuggestionModelResolution(shared, selection);
|
|
2713
|
+
if (!resolution.model) {
|
|
2714
|
+
ctx.ui.notify(
|
|
2715
|
+
`Prompt autocomplete could not set the model to active: ${
|
|
2716
|
+
resolution.reason ?? "the current active model is not usable"
|
|
2717
|
+
}.`,
|
|
2718
|
+
"warning",
|
|
2719
|
+
);
|
|
2720
|
+
return;
|
|
2721
|
+
}
|
|
2722
|
+
}
|
|
2723
|
+
|
|
2724
|
+
// Compare the configured destinations, not the currently usable models: an
|
|
2725
|
+
// unusable old model still defines where requests were meant to go, and the
|
|
2726
|
+
// provider change must restate the privacy notice either way.
|
|
2727
|
+
const configured = shared.config.modelSelection;
|
|
2728
|
+
const currentProvider = configured.kind === "dedicated" ? configured.ref.provider : shared.currentModel?.provider;
|
|
2729
|
+
const nextProvider = selection.kind === "dedicated"
|
|
2730
|
+
? selection.ref.provider
|
|
2731
|
+
: shared.currentModel?.provider;
|
|
2732
|
+
if (nextProvider && currentProvider && nextProvider !== currentProvider) {
|
|
2733
|
+
ctx.ui.notify(PRIVACY_NOTICE, "info");
|
|
2734
|
+
}
|
|
2735
|
+
|
|
2736
|
+
const persisted = persistableModelRaw(selection);
|
|
2737
|
+
applyConfigTransaction(ctx, shared, {
|
|
2738
|
+
apply: () => {
|
|
2739
|
+
shared.config.modelSelection = selection;
|
|
2740
|
+
shared.runtimeOverrides.modelSelection = selection;
|
|
2741
|
+
shared.reportedModelRefusals.clear();
|
|
2742
|
+
},
|
|
2743
|
+
persist: persisted === undefined ? undefined : { model: persisted },
|
|
2744
|
+
affectsRequestIdentity: true,
|
|
2745
|
+
notify: selection.kind === "active"
|
|
2746
|
+
? "Prompt autocomplete model set to current active model"
|
|
2747
|
+
: `Prompt autocomplete model set to ${describePromptAutocompleteModelSelection(selection)}`,
|
|
2748
|
+
});
|
|
2749
|
+
}
|
|
2750
|
+
|
|
2751
|
+
/** What each `set` key changes; validation bounds come from the grammar. */
|
|
2752
|
+
const SET_KEY_RUNNERS: {
|
|
2753
|
+
[Key in PromptAutocompleteSetKey]: (ctx: ExtensionContext, shared: PromptAutocompleteSharedState, value: string) => void;
|
|
2754
|
+
} = {
|
|
2755
|
+
"debounce-ms": (ctx, shared, value) =>
|
|
2756
|
+
setBoundedSetKey(ctx, shared, "debounce-ms", "debounceMs", value, false),
|
|
2757
|
+
"min-chars": (ctx, shared, value) => setMinPromptChars(ctx, shared, value || undefined),
|
|
2758
|
+
"max-chars": (ctx, shared, value) =>
|
|
2759
|
+
setBoundedSetKey(ctx, shared, "max-chars", "maxSuggestionChars", value, true),
|
|
2760
|
+
"max-alternatives": (ctx, shared, value) =>
|
|
2761
|
+
setBoundedSetKey(ctx, shared, "max-alternatives", "maxAlternatives", value, true),
|
|
2762
|
+
model: (ctx, shared, value) => {
|
|
2763
|
+
if (!value) {
|
|
2764
|
+
ctx.ui.notify("Usage: /prompt-autocomplete set model <provider/model|active>", "warning");
|
|
2765
|
+
return;
|
|
2766
|
+
}
|
|
2767
|
+
setModelSetting(ctx, shared, value);
|
|
2768
|
+
},
|
|
2769
|
+
};
|
|
2770
|
+
|
|
2771
|
+
function setBoundedSetKey(
|
|
2772
|
+
ctx: ExtensionContext,
|
|
2773
|
+
shared: PromptAutocompleteSharedState,
|
|
2774
|
+
key: "debounce-ms" | "max-chars" | "max-alternatives",
|
|
2775
|
+
field: "debounceMs" | "maxSuggestionChars" | "maxAlternatives",
|
|
2776
|
+
value: string,
|
|
2777
|
+
affectsRequestIdentity: boolean,
|
|
2778
|
+
): void {
|
|
2779
|
+
const spec = findPromptAutocompleteSetKey(key);
|
|
2780
|
+
if (!spec || !("min" in spec)) return;
|
|
2781
|
+
setBoundedConfigField(ctx, shared, { key, field, min: spec.min, max: spec.max, value, affectsRequestIdentity });
|
|
2782
|
+
}
|
|
2783
|
+
|
|
2784
|
+
function handleSetCommand(ctx: ExtensionContext, shared: PromptAutocompleteSharedState, rest: string): void {
|
|
2785
|
+
if (!rest) {
|
|
2786
|
+
ctx.ui.notify(formatStatus(shared), "info");
|
|
2787
|
+
return;
|
|
2788
|
+
}
|
|
2789
|
+
const space = rest.search(/\s/);
|
|
2790
|
+
const key = (space < 0 ? rest : rest.slice(0, space)).toLowerCase();
|
|
2791
|
+
const value = space < 0 ? "" : rest.slice(space + 1).trim();
|
|
2792
|
+
const spec = findPromptAutocompleteSetKey(key);
|
|
2793
|
+
if (!spec) {
|
|
2794
|
+
ctx.ui.notify(PROMPT_AUTOCOMPLETE_SET_USAGE, "warning");
|
|
2795
|
+
return;
|
|
2796
|
+
}
|
|
2797
|
+
SET_KEY_RUNNERS[spec.key](ctx, shared, value);
|
|
2798
|
+
}
|
|
2799
|
+
|
|
1912
2800
|
function persistEnabledDecision(
|
|
1913
2801
|
ctx: ExtensionContext,
|
|
1914
2802
|
shared: PromptAutocompleteSharedState,
|
|
@@ -1922,7 +2810,7 @@ function enablePromptAutocomplete(ctx: ExtensionContext, shared: PromptAutocompl
|
|
|
1922
2810
|
shared.enabled = true;
|
|
1923
2811
|
shared.runtimeOverrides.enabled = true;
|
|
1924
2812
|
|
|
1925
|
-
if (!mountEditor(ctx, shared) && shared.hostInstallsEditors === false) {
|
|
2813
|
+
if (!mountEditor(ctx, shared) && shared.processState.hostInstallsEditors === false) {
|
|
1926
2814
|
// The host accepted the editor factory without installing it. mountEditor
|
|
1927
2815
|
// already cleared `enabled`; keep it cleared and drop the session override
|
|
1928
2816
|
// so the refused activation is not replayed as a user decision later.
|
|
@@ -1957,7 +2845,7 @@ function notifyPromptAutocompleteEnabled(
|
|
|
1957
2845
|
`${formatPrimaryKey(CYCLE_NEXT_KEYS)} also forces a one-shot suggestion when none is shown (even while the agent works).`;
|
|
1958
2846
|
const resolution = resolveSuggestionModelResolution(shared);
|
|
1959
2847
|
const resolvedModel = resolution.model;
|
|
1960
|
-
const privacyNotice =
|
|
2848
|
+
const privacyNotice = PRIVACY_NOTICE;
|
|
1961
2849
|
|
|
1962
2850
|
if (!resolvedModel && resolution.refusedRequest) {
|
|
1963
2851
|
// A refused explicit request must be reported on every enable path,
|
|
@@ -1990,91 +2878,155 @@ function notifyPromptAutocompleteEnabled(
|
|
|
1990
2878
|
ctx.ui.notify(`Prompt autocomplete enabled. ${keyHint} ${privacyNotice}`, "info");
|
|
1991
2879
|
}
|
|
1992
2880
|
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
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
|
-
}
|
|
2881
|
+
/** Whether the host can show a notification, which read-only commands need. */
|
|
2882
|
+
function hasNotificationChannel(ctx: ExtensionContext): boolean {
|
|
2883
|
+
const host = ctx as Partial<Pick<ExtensionContext, "hasUI" | "ui">>;
|
|
2884
|
+
return host.hasUI === true && typeof host.ui?.notify === "function";
|
|
2885
|
+
}
|
|
2031
2886
|
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2887
|
+
/**
|
|
2888
|
+
* Tell a non-interactive host once per process that an enabled extension
|
|
2889
|
+
* cannot issue requests there, instead of staying silently inert.
|
|
2890
|
+
*/
|
|
2891
|
+
function notifyEnabledWithoutEditorOnce(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): void {
|
|
2892
|
+
if (!shared.enabled || shared.processState.nonInteractiveNoticeShown) return;
|
|
2893
|
+
if (hostOwnsInteractiveEditor(ctx, shared) || !hasNotificationChannel(ctx)) return;
|
|
2894
|
+
shared.processState.nonInteractiveNoticeShown = true;
|
|
2895
|
+
ctx.ui.notify(
|
|
2896
|
+
"Prompt autocomplete is enabled, but this host has no interactive editor: no autocomplete requests will be issued.",
|
|
2897
|
+
"info",
|
|
2898
|
+
);
|
|
2899
|
+
}
|
|
2900
|
+
|
|
2901
|
+
/** Parsed command arguments, in the forms the individual commands consume. */
|
|
2902
|
+
interface CommandInput {
|
|
2903
|
+
/** Everything after exactly one separator, verbatim (inspection keeps whitespace). */
|
|
2904
|
+
payload: string;
|
|
2905
|
+
/** The payload trimmed. */
|
|
2906
|
+
rest: string;
|
|
2907
|
+
/** The first whitespace-separated argument, if any. */
|
|
2908
|
+
firstArgument: string | undefined;
|
|
2909
|
+
interactiveHost: boolean;
|
|
2910
|
+
}
|
|
2911
|
+
|
|
2912
|
+
type CommandRunner = (ctx: ExtensionContext, shared: PromptAutocompleteSharedState, input: CommandInput) => void;
|
|
2913
|
+
|
|
2914
|
+
/**
|
|
2915
|
+
* One runner per grammar command. The mapped type makes a command without a
|
|
2916
|
+
* runner, or a runner without a grammar entry, a type error.
|
|
2917
|
+
*
|
|
2918
|
+
* Read-only runners (the grammar marks them) change no settings, overrides,
|
|
2919
|
+
* budget, or stats, mount no editor, and reach no provider seam, which is what
|
|
2920
|
+
* lets them run outside the TUI. Inspection may warm the in-memory projection
|
|
2921
|
+
* memo, a deterministic cache the next request in the same conversation reuses.
|
|
2922
|
+
*/
|
|
2923
|
+
const COMMAND_RUNNERS: { [Name in PromptAutocompleteCommandName]: CommandRunner } = {
|
|
2924
|
+
on: (ctx, shared) => {
|
|
2925
|
+
if (shared.enabled && shared.ownsEditor?.()) {
|
|
2926
|
+
// Already in the requested state, but the user still expressed intent:
|
|
2927
|
+
// record it so later sessions and processes do not fall back to the flag.
|
|
2928
|
+
shared.runtimeOverrides.enabled = true;
|
|
2929
|
+
persistEnabledDecision(ctx, shared, true);
|
|
2930
|
+
ctx.ui.notify(`Prompt autocomplete already enabled (${formatStatus(shared)})`, "info");
|
|
2931
|
+
return;
|
|
2932
|
+
}
|
|
2044
2933
|
|
|
2934
|
+
if (enablePromptAutocomplete(ctx, shared)) {
|
|
2935
|
+
persistEnabledDecision(ctx, shared, true);
|
|
2936
|
+
notifyPromptAutocompleteEnabled(ctx, shared, { includeModel: true });
|
|
2937
|
+
}
|
|
2938
|
+
},
|
|
2939
|
+
off: (ctx, shared) => {
|
|
2940
|
+
if (!shared.enabled) {
|
|
2941
|
+
shared.runtimeOverrides.enabled = false;
|
|
2942
|
+
persistEnabledDecision(ctx, shared, false);
|
|
2943
|
+
ctx.ui.notify("Prompt autocomplete is already disabled", "info");
|
|
2944
|
+
return;
|
|
2945
|
+
}
|
|
2946
|
+
|
|
2947
|
+
disablePromptAutocomplete(ctx, shared);
|
|
2948
|
+
persistEnabledDecision(ctx, shared, false);
|
|
2949
|
+
ctx.ui.notify("Prompt autocomplete disabled", "info");
|
|
2950
|
+
},
|
|
2951
|
+
toggle: (ctx, shared) => {
|
|
2952
|
+
if (shared.enabled) {
|
|
2045
2953
|
disablePromptAutocomplete(ctx, shared);
|
|
2046
2954
|
persistEnabledDecision(ctx, shared, false);
|
|
2047
2955
|
ctx.ui.notify("Prompt autocomplete disabled", "info");
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
if (shared.enabled) {
|
|
2051
|
-
disablePromptAutocomplete(ctx, shared);
|
|
2052
|
-
persistEnabledDecision(ctx, shared, false);
|
|
2053
|
-
ctx.ui.notify("Prompt autocomplete disabled", "info");
|
|
2054
|
-
return;
|
|
2055
|
-
}
|
|
2956
|
+
return;
|
|
2957
|
+
}
|
|
2056
2958
|
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
}
|
|
2063
|
-
|
|
2959
|
+
if (enablePromptAutocomplete(ctx, shared)) {
|
|
2960
|
+
persistEnabledDecision(ctx, shared, true);
|
|
2961
|
+
notifyPromptAutocompleteEnabled(ctx, shared, { includeModel: false });
|
|
2962
|
+
}
|
|
2963
|
+
},
|
|
2964
|
+
status: (ctx, shared, { interactiveHost }) => {
|
|
2965
|
+
ctx.ui.notify(formatStatus(shared, interactiveHost), "info");
|
|
2966
|
+
},
|
|
2967
|
+
stats: (ctx, shared) => {
|
|
2968
|
+
const { value, source } = describeBudget(shared);
|
|
2969
|
+
ctx.ui.notify(`${formatPromptAutocompleteStats(shared.usageStats)}\nBudget: ${value} (${source})`, "info");
|
|
2970
|
+
},
|
|
2971
|
+
inspect: (ctx, shared, { payload, interactiveHost }) => {
|
|
2972
|
+
ctx.ui.notify(formatPromptAutocompleteInspection(shared, interactiveHost, payload || undefined), "info");
|
|
2973
|
+
},
|
|
2974
|
+
"min-chars": (ctx, shared, { firstArgument }) => setMinPromptChars(ctx, shared, firstArgument),
|
|
2975
|
+
budget: (ctx, shared, { firstArgument }) => setBudgetLimit(ctx, shared, firstArgument),
|
|
2976
|
+
set: (ctx, shared, { rest }) => handleSetCommand(ctx, shared, rest),
|
|
2977
|
+
stream: (ctx, shared, { firstArgument }) => setStreamResponses(ctx, shared, firstArgument),
|
|
2978
|
+
"while-streaming": (ctx, shared, { firstArgument }) => setWhileStreaming(ctx, shared, firstArgument),
|
|
2979
|
+
"debug-on": (ctx, shared) => {
|
|
2980
|
+
setDebugDisplay(shared, true);
|
|
2981
|
+
ctx.ui.notify("Prompt autocomplete debug display enabled", "info");
|
|
2982
|
+
},
|
|
2983
|
+
"debug-off": (ctx, shared) => {
|
|
2984
|
+
setDebugDisplay(shared, false);
|
|
2985
|
+
ctx.ui.notify("Prompt autocomplete debug display disabled", "info");
|
|
2986
|
+
},
|
|
2987
|
+
"debug-toggle": (ctx, shared) => {
|
|
2988
|
+
const nextDebugEnabled = !shared.config.debug;
|
|
2989
|
+
setDebugDisplay(shared, nextDebugEnabled);
|
|
2990
|
+
ctx.ui.notify(
|
|
2991
|
+
nextDebugEnabled
|
|
2992
|
+
? "Prompt autocomplete debug display enabled"
|
|
2993
|
+
: "Prompt autocomplete debug display disabled",
|
|
2994
|
+
"info",
|
|
2995
|
+
);
|
|
2996
|
+
},
|
|
2997
|
+
};
|
|
2064
2998
|
|
|
2065
2999
|
export function createPromptAutocompleteExtension(
|
|
2066
3000
|
dependencies: PromptAutocompleteDependencies = {},
|
|
2067
3001
|
): (pi: ExtensionAPI) => void {
|
|
2068
|
-
const completeSimpleImpl = dependencies.completeSimple ?? hostCompleteSimple;
|
|
2069
3002
|
const hostStreaming = hostSupportsStreamedResponses(piAiSimpleApi);
|
|
3003
|
+
const now = dependencies.now ?? Date.now;
|
|
3004
|
+
|
|
3005
|
+
return function promptAutocompleteExtension(pi: ExtensionAPI): void {
|
|
3006
|
+
// Injected seams win; otherwise each request routes through the session's
|
|
3007
|
+
// model registry when it has one, and through the compat functions if not.
|
|
3008
|
+
// The registry is read per request because a new session may bring another.
|
|
3009
|
+
// This one function decides routing for both paths and for the credential
|
|
3010
|
+
// handling in the producer, so they cannot disagree. Any injected seam keeps
|
|
3011
|
+
// the registry out entirely, including for the path that was not injected.
|
|
3012
|
+
const injectedSeams = !!(dependencies.completeSimple || dependencies.streamSimple);
|
|
3013
|
+
const hostRegistryStream = (): RegistryStreamSimple | undefined =>
|
|
3014
|
+
injectedSeams ? undefined : registryStreamSimple(shared.modelRegistry);
|
|
3015
|
+
const routedCompleteSimple: CompleteSimpleFunction = (model, context, options) => {
|
|
3016
|
+
const viaRegistry = hostRegistryStream();
|
|
3017
|
+
return viaRegistry ? viaRegistry(model, context, options).result() : hostCompleteSimple(model, context, options);
|
|
3018
|
+
};
|
|
3019
|
+
const routedStreamSimple: StreamSimpleFunction = (model, context, options) => {
|
|
3020
|
+
const viaRegistry = hostRegistryStream();
|
|
3021
|
+
return viaRegistry ? viaRegistry(model, context, options) : hostStreamSimple(model, context, options);
|
|
3022
|
+
};
|
|
3023
|
+
const completeSimpleImpl = dependencies.completeSimple ?? routedCompleteSimple;
|
|
2070
3024
|
// Existing deterministic harnesses inject only completeSimple. Never let such
|
|
2071
3025
|
// a harness fall through to the real network-capable stream implementation.
|
|
2072
3026
|
const streamSimpleImpl =
|
|
2073
3027
|
dependencies.streamSimple
|
|
2074
|
-
?? (dependencies.completeSimple || !hostStreaming ? undefined :
|
|
2075
|
-
const now = dependencies.now ?? Date.now;
|
|
3028
|
+
?? (dependencies.completeSimple || !hostStreaming ? undefined : routedStreamSimple);
|
|
2076
3029
|
|
|
2077
|
-
return function promptAutocompleteExtension(pi: ExtensionAPI): void {
|
|
2078
3030
|
const settingsStore = dependencies.settingsStore ?? createFileSettingsStore(resolvePromptAutocompleteSettingsPath());
|
|
2079
3031
|
let persistedSettings: PromptAutocompletePersistedSettings;
|
|
2080
3032
|
try {
|
|
@@ -2131,25 +3083,36 @@ export function createPromptAutocompleteExtension(
|
|
|
2131
3083
|
type: "string",
|
|
2132
3084
|
default: String(DEFAULT_MAX_ALTERNATIVES),
|
|
2133
3085
|
});
|
|
3086
|
+
pi.registerFlag("prompt-autocomplete-max-requests", {
|
|
3087
|
+
description: `Maximum provider requests per session before autocomplete stops requesting (${BUDGET_REQUESTS_MIN}-${BUDGET_REQUESTS_MAX} or off)`,
|
|
3088
|
+
type: "string",
|
|
3089
|
+
default: DEFAULT_BUDGET_REQUESTS_FLAG,
|
|
3090
|
+
});
|
|
2134
3091
|
|
|
2135
3092
|
const shared: PromptAutocompleteSharedState = {
|
|
2136
3093
|
enabled: false,
|
|
2137
3094
|
activationId: 0,
|
|
2138
3095
|
agentStreaming: false,
|
|
3096
|
+
physicalSessionId: "",
|
|
3097
|
+
lastConversationId: "",
|
|
2139
3098
|
config: parseConfig(pi),
|
|
2140
3099
|
runtimeOverrides: {},
|
|
2141
3100
|
persistedSettings,
|
|
2142
3101
|
settingsStore,
|
|
2143
3102
|
enabledFlagValue: false,
|
|
3103
|
+
budgetUsed: 0,
|
|
3104
|
+
budgetBlockNotices: new Set(),
|
|
2144
3105
|
usageStats: createPromptAutocompleteUsageStats(),
|
|
2145
3106
|
completeSimple: completeSimpleImpl,
|
|
2146
3107
|
streamSimple: streamSimpleImpl,
|
|
3108
|
+
routesThroughHostRegistry: () => hostRegistryStream() !== undefined,
|
|
2147
3109
|
now,
|
|
2148
3110
|
debugState: "idle",
|
|
2149
3111
|
requestCache: new ExpiringLruCache(REQUEST_CACHE_TTL_MS, REQUEST_CACHE_MAX_ENTRIES, now),
|
|
2150
3112
|
prefixReuseCache: new ExpiringLruCache(REQUEST_CACHE_TTL_MS, REQUEST_CACHE_MAX_ENTRIES, now),
|
|
2151
3113
|
inFlightRequests: new Map(),
|
|
2152
3114
|
reportedModelRefusals: new Set(),
|
|
3115
|
+
processState: dependencies.processState ?? sharedProcessState(),
|
|
2153
3116
|
};
|
|
2154
3117
|
|
|
2155
3118
|
pi.on("session_start", async (_event, ctx) => {
|
|
@@ -2158,8 +3121,12 @@ export function createPromptAutocompleteExtension(
|
|
|
2158
3121
|
}
|
|
2159
3122
|
resetSharedForSession(pi, shared);
|
|
2160
3123
|
bindRuntimeContext(ctx, shared);
|
|
3124
|
+
restoreBudgetFromSession(pi, shared);
|
|
2161
3125
|
|
|
2162
|
-
if (!hostOwnsInteractiveEditor(ctx, shared) || !shared.enabled)
|
|
3126
|
+
if (!hostOwnsInteractiveEditor(ctx, shared) || !shared.enabled) {
|
|
3127
|
+
notifyEnabledWithoutEditorOnce(ctx, shared);
|
|
3128
|
+
return;
|
|
3129
|
+
}
|
|
2163
3130
|
mountEditor(ctx, shared);
|
|
2164
3131
|
});
|
|
2165
3132
|
|
|
@@ -2183,6 +3150,9 @@ export function createPromptAutocompleteExtension(
|
|
|
2183
3150
|
pi.on("session_tree", async (_event, ctx) => {
|
|
2184
3151
|
shared.sessionManager = ctx.sessionManager;
|
|
2185
3152
|
if (!shared.enabled) return;
|
|
3153
|
+
const nextConversationId = resolveCurrentConversationId(shared);
|
|
3154
|
+
if (nextConversationId === shared.lastConversationId) return;
|
|
3155
|
+
shared.lastConversationId = nextConversationId;
|
|
2186
3156
|
refreshEditorImmediately(shared, "context-changed", "Conversation branch changed");
|
|
2187
3157
|
});
|
|
2188
3158
|
|
|
@@ -2192,48 +3162,48 @@ export function createPromptAutocompleteExtension(
|
|
|
2192
3162
|
refreshEditorImmediately(shared, "waiting", "Main agent is still working");
|
|
2193
3163
|
});
|
|
2194
3164
|
|
|
2195
|
-
pi.on("agent_end", async () => {
|
|
2196
|
-
shared
|
|
2197
|
-
if (
|
|
2198
|
-
|
|
3165
|
+
pi.on("agent_end", async (_event, ctx) => {
|
|
3166
|
+
rememberAgentSettledSupport(ctx, shared);
|
|
3167
|
+
if (shared.hostEmitsAgentSettled) return;
|
|
3168
|
+
settleAgentTurn(shared, "Agent finished; autocomplete can request suggestions again");
|
|
3169
|
+
});
|
|
3170
|
+
|
|
3171
|
+
pi.on("agent_settled", async () => {
|
|
3172
|
+
settleAgentTurn(shared, "Agent settled; autocomplete can request suggestions again");
|
|
2199
3173
|
});
|
|
2200
3174
|
|
|
2201
3175
|
pi.registerCommand("prompt-autocomplete", {
|
|
2202
3176
|
description: "Enable, disable, or inspect inline prompt autocomplete and session stats",
|
|
3177
|
+
// Local and synchronous: Pi replaces the whole argument span with the value.
|
|
3178
|
+
getArgumentCompletions: (argumentPrefix) => completePromptAutocompleteArguments(argumentPrefix),
|
|
2203
3179
|
handler: async (args, ctx) => {
|
|
2204
|
-
|
|
3180
|
+
const commandStart = args.trimStart();
|
|
3181
|
+
const space = commandStart.search(/\s/);
|
|
3182
|
+
const name = (space < 0 ? commandStart : commandStart.slice(0, space)).toLowerCase() || "status";
|
|
3183
|
+
// Everything after exactly one separator, verbatim: an inspected draft
|
|
3184
|
+
// must keep its leading and trailing whitespace to match production.
|
|
3185
|
+
const payload = space < 0 ? "" : commandStart.slice(space + 1);
|
|
3186
|
+
const rest = payload.trim();
|
|
3187
|
+
const spec = findPromptAutocompleteCommand(name);
|
|
3188
|
+
|
|
3189
|
+
// Reporting works wherever a notification can be shown; anything that
|
|
3190
|
+
// changes state or touches the editor stays TUI-only.
|
|
3191
|
+
const interactiveHost = hostOwnsInteractiveEditor(ctx, shared);
|
|
3192
|
+
if (!interactiveHost && !(spec?.readOnly && hasNotificationChannel(ctx))) {
|
|
2205
3193
|
ctx.ui.notify("prompt-autocomplete requires interactive TUI mode", "warning");
|
|
2206
3194
|
return;
|
|
2207
3195
|
}
|
|
2208
|
-
|
|
2209
|
-
|
|
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();
|
|
3196
|
+
if (!spec) {
|
|
3197
|
+
ctx.ui.notify(PROMPT_AUTOCOMPLETE_USAGE, "warning");
|
|
2230
3198
|
return;
|
|
2231
3199
|
}
|
|
2232
3200
|
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
3201
|
+
COMMAND_RUNNERS[spec.name](ctx, shared, {
|
|
3202
|
+
payload,
|
|
3203
|
+
rest,
|
|
3204
|
+
firstArgument: rest.split(/\s+/, 1)[0] || undefined,
|
|
3205
|
+
interactiveHost,
|
|
3206
|
+
});
|
|
2237
3207
|
},
|
|
2238
3208
|
});
|
|
2239
3209
|
};
|