@kliebhan/pi-prompt-autocomplete 0.2.4 → 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 +28 -0
- package/README.md +54 -15
- package/core.ts +728 -6
- package/index.ts +1284 -235
- package/media/prompt-autocomplete-demo.mp4 +0 -0
- package/package.json +2 -2
package/index.ts
CHANGED
|
@@ -13,22 +13,40 @@ 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,
|
|
48
|
+
MIN_PROMPT_CHARS_MAX,
|
|
49
|
+
MIN_PROMPT_CHARS_MIN,
|
|
32
50
|
DEFAULT_PROMPT_AUTOCOMPLETE_ENABLED,
|
|
33
51
|
DEFAULT_STREAM_RESPONSES,
|
|
34
52
|
ExpiringLruCache,
|
|
@@ -38,23 +56,44 @@ import {
|
|
|
38
56
|
formatUsageStats,
|
|
39
57
|
hostSupportsStreamedResponses,
|
|
40
58
|
isInteractiveEditorHost,
|
|
41
|
-
MAX_DRAFT_CONTEXT_CHARS,
|
|
42
59
|
normalizePromptSuggestions,
|
|
43
60
|
parseBoundedIntFlag,
|
|
61
|
+
parseExplicitBoundedIntFlag,
|
|
62
|
+
parseExplicitModelFlag,
|
|
63
|
+
parsePersistedModelRaw,
|
|
64
|
+
parsePromptAutocompleteBudgetFlag,
|
|
65
|
+
parsePromptAutocompleteBudgetValue,
|
|
66
|
+
parseStrictBoundedInt,
|
|
67
|
+
persistableModelRaw,
|
|
44
68
|
parsePartialPromptSuggestion,
|
|
45
69
|
parsePromptAutocompleteModelSelection,
|
|
46
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,
|
|
47
82
|
resolvePersistedEnabled,
|
|
83
|
+
resolvePersistedNumber,
|
|
84
|
+
resolvePromptAutocompleteBudgetLimit,
|
|
48
85
|
serializePromptAutocompletePersistedSettings,
|
|
49
86
|
PROMPT_AUTOCOMPLETE_SYSTEM_PROMPT,
|
|
87
|
+
PROMPT_AUTOCOMPLETE_BUDGET_ENTRY_TYPE,
|
|
50
88
|
recordProviderLatency,
|
|
51
89
|
recordProviderUsage,
|
|
90
|
+
resolveAutocompleteConversationId,
|
|
52
91
|
resolveOverride,
|
|
92
|
+
resolvePersistedModelSelection,
|
|
53
93
|
reusePromptAutocompleteSuggestions,
|
|
54
94
|
sanitizeTerminalText,
|
|
55
95
|
SequenceOwnedSlot,
|
|
56
96
|
shouldSkipPromptAutocomplete,
|
|
57
|
-
truncateDraftTail,
|
|
58
97
|
type CoalescedRequestEntry,
|
|
59
98
|
type CoalescedRequestSubscription,
|
|
60
99
|
type PromptAutocompleteModelSelection,
|
|
@@ -66,13 +105,16 @@ import {
|
|
|
66
105
|
const GHOST_TEXT_STYLE = "\x1b[2m";
|
|
67
106
|
const GHOST_INDICATOR_STYLE = "\x1b[90m";
|
|
68
107
|
const RESET = "\x1b[0m";
|
|
69
|
-
// Hosts draw the end-of-line
|
|
70
|
-
//
|
|
71
|
-
// surface alive, such as prime-agent, close it with \x1b[27m so the
|
|
72
|
-
// survives the cursor cell
|
|
73
|
-
//
|
|
74
|
-
|
|
75
|
-
|
|
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/;
|
|
76
118
|
const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] as const;
|
|
77
119
|
const SPINNER_INTERVAL_MS = 80;
|
|
78
120
|
const SPINNER_LABEL = "Generating suggestion";
|
|
@@ -92,6 +134,8 @@ const REQUEST_MAX_RETRY_DELAY_MS = 2_000;
|
|
|
92
134
|
const FAILURE_COOLDOWN_MS = 5_000;
|
|
93
135
|
const REQUEST_CACHE_TTL_MS = 60_000;
|
|
94
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.";
|
|
95
139
|
// Keymap audit vs. pi defaults (packages/tui/src/keybindings.ts +
|
|
96
140
|
// packages/coding-agent/src/core/keybindings.ts): none of the keys below are bound
|
|
97
141
|
// by pi's default keymap, so the editor can safely own them — including the
|
|
@@ -138,6 +182,8 @@ interface PromptAutocompleteConfig {
|
|
|
138
182
|
maxSuggestionChars: number;
|
|
139
183
|
maxAlternatives: number;
|
|
140
184
|
modelSelection: PromptAutocompleteModelSelection;
|
|
185
|
+
/** Effective provider-request ceiling; undefined means off. */
|
|
186
|
+
budgetLimit?: number;
|
|
141
187
|
}
|
|
142
188
|
|
|
143
189
|
interface PromptAutocompleteCacheEntry {
|
|
@@ -213,12 +259,106 @@ const hostStreamSimple = ((model, context, options) =>
|
|
|
213
259
|
options,
|
|
214
260
|
)) as StreamSimpleFunction;
|
|
215
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
|
+
|
|
216
283
|
export interface PromptAutocompleteDependencies {
|
|
217
284
|
completeSimple?: CompleteSimpleFunction;
|
|
218
285
|
streamSimple?: StreamSimpleFunction;
|
|
219
286
|
now?: () => number;
|
|
220
287
|
/** Store for decisions that survive the process; defaults to a JSON settings file. */
|
|
221
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;
|
|
222
362
|
}
|
|
223
363
|
|
|
224
364
|
/**
|
|
@@ -276,6 +416,26 @@ interface PromptAutocompleteSharedState {
|
|
|
276
416
|
enabled: boolean;
|
|
277
417
|
activationId: number;
|
|
278
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;
|
|
279
439
|
config: PromptAutocompleteConfig;
|
|
280
440
|
/** Slash-command decisions that outrank flags for the lifetime of the process. */
|
|
281
441
|
runtimeOverrides: PromptAutocompleteRuntimeOverrides;
|
|
@@ -284,6 +444,30 @@ interface PromptAutocompleteSharedState {
|
|
|
284
444
|
settingsStore?: PromptAutocompleteSettingsStore;
|
|
285
445
|
/** Last enabled-flag value seen by applyEffectiveConfig, for status attribution. */
|
|
286
446
|
enabledFlagValue: boolean;
|
|
447
|
+
/** Explicit min-chars flag value seen by applyEffectiveConfig, undefined when defaulted. */
|
|
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;
|
|
287
471
|
/** Session-scoped request accounting; reset together with the cache. */
|
|
288
472
|
usageStats: PromptAutocompleteUsageStats;
|
|
289
473
|
currentModel?: Model<Api>;
|
|
@@ -295,18 +479,23 @@ interface PromptAutocompleteSharedState {
|
|
|
295
479
|
debugState: string;
|
|
296
480
|
editorMount?: EditorMountState;
|
|
297
481
|
editorBlockedReason?: string;
|
|
482
|
+
/** Whether requests go through the session's model registry rather than compat or injected seams. */
|
|
483
|
+
routesThroughHostRegistry: () => boolean;
|
|
298
484
|
/** Mount-bound notification channel; cleared together with the editor runtime. */
|
|
299
485
|
notify?: (message: string, type?: "info" | "warning" | "error") => void;
|
|
300
486
|
/** Refused model requests already reported, to avoid repeating them. */
|
|
301
487
|
reportedModelRefusals: Set<string>;
|
|
488
|
+
/** Process-lifetime state shared with later runtimes of this process. */
|
|
489
|
+
processState: PromptAutocompleteProcessState;
|
|
302
490
|
/**
|
|
303
|
-
*
|
|
491
|
+
* Projected context entries and the conversation id they belong to.
|
|
304
492
|
*
|
|
305
|
-
*
|
|
306
|
-
*
|
|
307
|
-
*
|
|
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.
|
|
308
497
|
*/
|
|
309
|
-
|
|
498
|
+
projectedContextMemo?: { conversationId: string; entries: unknown[] };
|
|
310
499
|
lastError?: string;
|
|
311
500
|
lastRawResponse?: string;
|
|
312
501
|
requestCache: ExpiringLruCache<PromptAutocompleteCacheEntry>;
|
|
@@ -315,26 +504,22 @@ interface PromptAutocompleteSharedState {
|
|
|
315
504
|
ownsEditor?: () => boolean;
|
|
316
505
|
refreshEditor?: (options?: SuggestionRefreshOptions) => void;
|
|
317
506
|
cancelActiveRequest?: () => void;
|
|
507
|
+
/** Cancel a pending debounce timer without aborting an in-flight provider call. */
|
|
508
|
+
cancelScheduledRequest?: () => void;
|
|
318
509
|
setStatusText?: (text: string | undefined) => void;
|
|
319
510
|
setSpinnerActive?: (owner: string, active: boolean) => void;
|
|
320
511
|
clearSpinner?: () => void;
|
|
321
512
|
}
|
|
322
513
|
|
|
323
|
-
|
|
514
|
+
/** A request snapshot plus the local routing and cache identity around it. */
|
|
515
|
+
interface SuggestionRequest extends PromptAutocompleteRequestSnapshot {
|
|
324
516
|
activationId: number;
|
|
325
|
-
|
|
326
|
-
draft: string;
|
|
327
|
-
draftTail: string;
|
|
517
|
+
conversationId: string;
|
|
328
518
|
model: Model<Api>;
|
|
329
519
|
modelLabel: string;
|
|
330
520
|
cacheKey: string;
|
|
331
521
|
prefixContextKey: string;
|
|
332
|
-
maxAlternatives: number;
|
|
333
|
-
maxSuggestionChars: number;
|
|
334
522
|
useStreaming: boolean;
|
|
335
|
-
latestAssistantContext: string;
|
|
336
|
-
latestUserContext: string;
|
|
337
|
-
recentContext: string;
|
|
338
523
|
}
|
|
339
524
|
|
|
340
525
|
interface PendingSuggestionRequest {
|
|
@@ -444,11 +629,11 @@ interface SuggestionModelResolution {
|
|
|
444
629
|
*/
|
|
445
630
|
function resolveSuggestionModelResolution(
|
|
446
631
|
shared: PromptAutocompleteSharedState,
|
|
632
|
+
selection: PromptAutocompleteModelSelection = shared.config.modelSelection,
|
|
447
633
|
): SuggestionModelResolution {
|
|
448
634
|
const registry = shared.modelRegistry;
|
|
449
635
|
if (!registry) return { reason: "No model registry is available yet" };
|
|
450
636
|
|
|
451
|
-
const selection = shared.config.modelSelection;
|
|
452
637
|
const requested = describePromptAutocompleteModelSelection(selection);
|
|
453
638
|
|
|
454
639
|
if (selection.kind === "invalid") {
|
|
@@ -517,21 +702,32 @@ function parseConfig(pi: ExtensionAPI): PromptAutocompleteConfig {
|
|
|
517
702
|
allowWhileStreaming: pi.getFlag("prompt-autocomplete-while-streaming") === true,
|
|
518
703
|
streamResponses: parseOnOffFlag(pi.getFlag("prompt-autocomplete-stream"), DEFAULT_STREAM_RESPONSES),
|
|
519
704
|
debug: pi.getFlag("prompt-autocomplete-debug") === true,
|
|
520
|
-
debounceMs: parseBoundedIntFlag(
|
|
521
|
-
|
|
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
|
+
),
|
|
522
717
|
maxSuggestionChars: parseBoundedIntFlag(
|
|
523
718
|
pi.getFlag("prompt-autocomplete-max-chars"),
|
|
524
719
|
DEFAULT_MAX_SUGGESTION_CHARS,
|
|
525
|
-
|
|
526
|
-
|
|
720
|
+
MAX_SUGGESTION_CHARS_MIN,
|
|
721
|
+
MAX_SUGGESTION_CHARS_MAX,
|
|
527
722
|
),
|
|
528
723
|
maxAlternatives: parseBoundedIntFlag(
|
|
529
724
|
pi.getFlag("prompt-autocomplete-max-alternatives"),
|
|
530
725
|
DEFAULT_MAX_ALTERNATIVES,
|
|
531
|
-
|
|
532
|
-
|
|
726
|
+
MAX_ALTERNATIVES_MIN,
|
|
727
|
+
MAX_ALTERNATIVES_MAX,
|
|
533
728
|
),
|
|
534
729
|
modelSelection: parsePromptAutocompleteModelSelection(pi.getFlag("prompt-autocomplete-model")),
|
|
730
|
+
budgetLimit: parsePromptAutocompleteBudgetFlag(pi.getFlag("prompt-autocomplete-max-requests")),
|
|
535
731
|
};
|
|
536
732
|
}
|
|
537
733
|
|
|
@@ -552,6 +748,32 @@ function applyEffectiveConfig(pi: ExtensionAPI, shared: PromptAutocompleteShared
|
|
|
552
748
|
flagEnabled,
|
|
553
749
|
shared.persistedSettings.enabled,
|
|
554
750
|
).enabled;
|
|
751
|
+
shared.minPromptCharsFlagExplicit = parseExplicitBoundedIntFlag(
|
|
752
|
+
pi.getFlag("prompt-autocomplete-min-chars"),
|
|
753
|
+
DEFAULT_MIN_PROMPT_CHARS,
|
|
754
|
+
MIN_PROMPT_CHARS_MIN,
|
|
755
|
+
MIN_PROMPT_CHARS_MAX,
|
|
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"));
|
|
555
777
|
shared.config = {
|
|
556
778
|
...flagConfig,
|
|
557
779
|
allowWhileStreaming: resolveOverride(
|
|
@@ -560,6 +782,40 @@ function applyEffectiveConfig(pi: ExtensionAPI, shared: PromptAutocompleteShared
|
|
|
560
782
|
),
|
|
561
783
|
streamResponses: resolveOverride(shared.runtimeOverrides.streamResponses, flagConfig.streamResponses),
|
|
562
784
|
debug: resolveOverride(shared.runtimeOverrides.debug, flagConfig.debug),
|
|
785
|
+
minPromptChars: resolvePersistedNumber(
|
|
786
|
+
shared.runtimeOverrides.minPromptChars,
|
|
787
|
+
shared.minPromptCharsFlagExplicit,
|
|
788
|
+
shared.persistedSettings.minPromptChars,
|
|
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,
|
|
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,
|
|
563
819
|
};
|
|
564
820
|
}
|
|
565
821
|
|
|
@@ -593,18 +849,24 @@ function clearDebugUi(shared: PromptAutocompleteSharedState): void {
|
|
|
593
849
|
shared.setStatusText?.(undefined);
|
|
594
850
|
}
|
|
595
851
|
|
|
596
|
-
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 {
|
|
597
864
|
const resolvedModel = resolveSuggestionModel(shared);
|
|
598
|
-
const editorState = shared
|
|
599
|
-
? shared.ownsEditor?.()
|
|
600
|
-
? "mounted"
|
|
601
|
-
: "ownership-lost"
|
|
602
|
-
: shared.editorBlockedReason
|
|
603
|
-
? "blocked"
|
|
604
|
-
: "unmounted";
|
|
865
|
+
const editorState = describeEditorState(shared, interactiveHost);
|
|
605
866
|
const requestedModel = describePromptAutocompleteModelSelection(shared.config.modelSelection);
|
|
606
867
|
|
|
607
868
|
return [
|
|
869
|
+
interactiveHost ? undefined : "host=non-interactive",
|
|
608
870
|
`enabled=${shared.enabled ? "yes" : "no"}(${
|
|
609
871
|
resolvePersistedEnabled(
|
|
610
872
|
shared.runtimeOverrides.enabled,
|
|
@@ -615,26 +877,189 @@ function formatStatus(shared: PromptAutocompleteSharedState): string {
|
|
|
615
877
|
`editor=${editorState}`,
|
|
616
878
|
shared.editorBlockedReason ? `editor-blocked=${truncateDebug(shared.editorBlockedReason, 90)}` : undefined,
|
|
617
879
|
`model=${truncateDebug(formatModelLabel(resolvedModel), 90)}`,
|
|
618
|
-
`requested-model=${requestedModel}
|
|
880
|
+
`requested-model=${requestedModel}(${
|
|
881
|
+
resolvePersistedModelSelection(
|
|
882
|
+
shared.runtimeOverrides.modelSelection,
|
|
883
|
+
shared.modelFlagExplicit,
|
|
884
|
+
parsePersistedModelRaw(shared.persistedSettings.model),
|
|
885
|
+
).source
|
|
886
|
+
})`,
|
|
619
887
|
`while-streaming=${shared.config.allowWhileStreaming ? "yes" : "no"}(${describeSettingSource(shared.runtimeOverrides.allowWhileStreaming)})`,
|
|
620
888
|
`stream=${shared.config.streamResponses ? "yes" : "no"}(${describeSettingSource(shared.runtimeOverrides.streamResponses)})`,
|
|
621
889
|
`request-path=${shared.config.streamResponses && shared.streamSimple ? "stream" : shared.config.streamResponses ? "complete-compat" : "complete"}`,
|
|
622
890
|
`debug=${shared.config.debug ? "yes" : "no"}(${describeSettingSource(shared.runtimeOverrides.debug)})`,
|
|
623
|
-
`debounce=${shared.config.debounceMs}ms
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
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
|
+
})`,
|
|
899
|
+
`min-chars=${shared.config.minPromptChars}(${
|
|
900
|
+
resolvePersistedNumber(
|
|
901
|
+
shared.runtimeOverrides.minPromptChars,
|
|
902
|
+
shared.minPromptCharsFlagExplicit,
|
|
903
|
+
shared.persistedSettings.minPromptChars,
|
|
904
|
+
DEFAULT_MIN_PROMPT_CHARS,
|
|
905
|
+
).source
|
|
906
|
+
})`,
|
|
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
|
+
})`,
|
|
627
923
|
`cache-size=${shared.requestCache.size}`,
|
|
924
|
+
`budget=${formatBudget(shared)}`,
|
|
628
925
|
`usage=${formatUsageStats(shared.usageStats)}`,
|
|
629
926
|
`state=${shared.debugState || "idle"}`,
|
|
630
927
|
shared.lastError ? `error=${truncateDebug(shared.lastError, 90)}` : undefined,
|
|
631
928
|
shared.lastRawResponse ? `raw=${truncateDebug(shared.lastRawResponse, 90)}` : undefined,
|
|
632
|
-
|
|
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,
|
|
633
932
|
]
|
|
634
933
|
.filter((value): value is string => !!value)
|
|
635
934
|
.join(" | ");
|
|
636
935
|
}
|
|
637
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
|
+
|
|
638
1063
|
function cloneCacheEntry(entry: PromptAutocompleteCacheEntry): PromptAutocompleteCacheEntry {
|
|
639
1064
|
return { ...entry, suggestions: [...entry.suggestions] };
|
|
640
1065
|
}
|
|
@@ -803,8 +1228,9 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
803
1228
|
let cursorLineIndex = -1;
|
|
804
1229
|
let cursorMatch: RegExpMatchArray | undefined;
|
|
805
1230
|
for (let index = 0; index < lines.length; index++) {
|
|
806
|
-
|
|
807
|
-
|
|
1231
|
+
const line = lines[index]!;
|
|
1232
|
+
if (!CURSOR_CELL_OPENERS.some((opener) => line.includes(opener))) continue;
|
|
1233
|
+
const match = line.match(CURSOR_CELL_PATTERN);
|
|
808
1234
|
if (match?.index !== undefined) {
|
|
809
1235
|
cursorLineIndex = index;
|
|
810
1236
|
cursorMatch = match;
|
|
@@ -816,7 +1242,11 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
816
1242
|
const cursorLine = lines[cursorLineIndex]!;
|
|
817
1243
|
const cursorIndex = cursorMatch.index;
|
|
818
1244
|
const cursorToken = cursorMatch[0];
|
|
819
|
-
|
|
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);
|
|
820
1250
|
|
|
821
1251
|
const before = cursorLine.slice(0, cursorIndex);
|
|
822
1252
|
const after = cursorLine.slice(cursorIndex + cursorToken.length);
|
|
@@ -828,7 +1258,9 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
828
1258
|
const firstPreviewChar = previewChars[0] ?? "";
|
|
829
1259
|
const absorbLeadingWhitespaceIntoCursor = /^[ \t]$/.test(firstPreviewChar);
|
|
830
1260
|
|
|
831
|
-
const cursorCell = absorbLeadingWhitespaceIntoCursor
|
|
1261
|
+
const cursorCell = absorbLeadingWhitespaceIntoCursor
|
|
1262
|
+
? `${cursorOpen}${firstPreviewChar}${cursorClose}`
|
|
1263
|
+
: cursorToken;
|
|
832
1264
|
const renderedPreviewText = absorbLeadingWhitespaceIntoCursor ? previewChars.slice(1).join("") : previewText;
|
|
833
1265
|
|
|
834
1266
|
const indicator = this.suggestions.length > 1 ? ` ‹${this.suggestionIndex + 1}/${this.suggestions.length}›` : "";
|
|
@@ -1115,10 +1547,7 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1115
1547
|
}
|
|
1116
1548
|
|
|
1117
1549
|
if (!this.shared.ownsEditor?.()) {
|
|
1118
|
-
this.
|
|
1119
|
-
this.shared.editorBlockedReason = "Another extension replaced the prompt-autocomplete editor";
|
|
1120
|
-
updateDebugState(this.shared, "ownership-lost", this.shared.editorBlockedReason);
|
|
1121
|
-
this.setSuggestions([]);
|
|
1550
|
+
this.releaseForOwnershipLoss();
|
|
1122
1551
|
return;
|
|
1123
1552
|
}
|
|
1124
1553
|
|
|
@@ -1194,6 +1623,22 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1194
1623
|
}
|
|
1195
1624
|
|
|
1196
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
|
+
|
|
1197
1642
|
this.cancelPendingRequest();
|
|
1198
1643
|
|
|
1199
1644
|
const seq = ++this.requestSeq;
|
|
@@ -1225,40 +1670,31 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1225
1670
|
const model = resolveSuggestionModel(this.shared);
|
|
1226
1671
|
if (!model) return undefined;
|
|
1227
1672
|
|
|
1228
|
-
const
|
|
1229
|
-
|
|
1230
|
-
const
|
|
1231
|
-
const latestUserContext = buildLatestUserMessageContext(branch);
|
|
1232
|
-
const recentContext = buildRecentConversationContext(branch);
|
|
1233
|
-
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);
|
|
1234
1676
|
const modelLabel = formatModelLabel(model);
|
|
1235
|
-
const leafId = this.shared.sessionManager?.getLeafId?.() ?? "";
|
|
1236
1677
|
|
|
1237
1678
|
const prefixContextIdentity = {
|
|
1238
|
-
|
|
1679
|
+
conversationId,
|
|
1239
1680
|
modelLabel,
|
|
1240
|
-
maxAlternatives:
|
|
1241
|
-
maxSuggestionChars:
|
|
1242
|
-
latestAssistantContext,
|
|
1243
|
-
latestUserContext,
|
|
1244
|
-
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,
|
|
1245
1687
|
};
|
|
1246
1688
|
|
|
1247
1689
|
return {
|
|
1690
|
+
...snapshot,
|
|
1248
1691
|
activationId: this.activationId,
|
|
1249
|
-
|
|
1250
|
-
draft,
|
|
1251
|
-
draftTail,
|
|
1692
|
+
conversationId,
|
|
1252
1693
|
model,
|
|
1253
1694
|
modelLabel,
|
|
1254
|
-
cacheKey: buildPromptAutocompleteCacheKey({ ...prefixContextIdentity, draft }),
|
|
1695
|
+
cacheKey: buildPromptAutocompleteCacheKey({ ...prefixContextIdentity, draft: snapshot.draft }),
|
|
1255
1696
|
prefixContextKey: buildPromptAutocompletePrefixContextKey(prefixContextIdentity),
|
|
1256
|
-
maxAlternatives: this.shared.config.maxAlternatives,
|
|
1257
|
-
maxSuggestionChars: this.shared.config.maxSuggestionChars,
|
|
1258
1697
|
useStreaming: this.shared.config.streamResponses && !!this.shared.streamSimple,
|
|
1259
|
-
latestAssistantContext,
|
|
1260
|
-
latestUserContext,
|
|
1261
|
-
recentContext,
|
|
1262
1698
|
};
|
|
1263
1699
|
}
|
|
1264
1700
|
|
|
@@ -1290,6 +1726,7 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1290
1726
|
try {
|
|
1291
1727
|
const entry = await subscription.promise;
|
|
1292
1728
|
if (!this.isRequestStillCurrent(request, seq)) {
|
|
1729
|
+
if (seq === this.requestSeq && !this.shared.ownsEditor?.()) this.releaseForOwnershipLoss();
|
|
1293
1730
|
return;
|
|
1294
1731
|
}
|
|
1295
1732
|
|
|
@@ -1303,7 +1740,18 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1303
1740
|
this.setSuggestions(entry.suggestions);
|
|
1304
1741
|
}
|
|
1305
1742
|
} catch (error) {
|
|
1306
|
-
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)) {
|
|
1307
1755
|
this.suspendedUntil = this.shared.now() + FAILURE_COOLDOWN_MS;
|
|
1308
1756
|
const message = error instanceof Error ? error.message : String(error);
|
|
1309
1757
|
this.shared.lastError = message;
|
|
@@ -1326,6 +1774,13 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1326
1774
|
spinnerOwner: string,
|
|
1327
1775
|
suggestion: string,
|
|
1328
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
|
+
}
|
|
1329
1784
|
if (!this.isRequestStillCurrent(request, seq)) return;
|
|
1330
1785
|
if (request.cacheKey === this.dismissedKey) return;
|
|
1331
1786
|
|
|
@@ -1348,55 +1803,26 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1348
1803
|
}
|
|
1349
1804
|
|
|
1350
1805
|
const auth = await this.shared.modelRegistry.getApiKeyAndHeaders(request.model);
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
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}`);
|
|
1354
1811
|
if (signal.aborted) {
|
|
1355
1812
|
throw new Error("Request was aborted");
|
|
1356
1813
|
}
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
if (
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
sections.push(`Latest user message:\n${request.latestUserContext}`);
|
|
1364
|
-
}
|
|
1365
|
-
if (request.recentContext) {
|
|
1366
|
-
sections.push(`Recent conversation summary:\n${request.recentContext}`);
|
|
1367
|
-
}
|
|
1368
|
-
|
|
1369
|
-
if (request.draft.length === 0) {
|
|
1370
|
-
sections.push("Current draft is empty.");
|
|
1371
|
-
sections.push(
|
|
1372
|
-
[
|
|
1373
|
-
`Task: propose up to ${request.maxAlternatives} ranked full next prompts the user could send now.`,
|
|
1374
|
-
"Each item must be a complete next prompt, not a continuation fragment.",
|
|
1375
|
-
"Suggest the prompt most likely to move the overall project forward.",
|
|
1376
|
-
"Prefer 3-10 words when possible.",
|
|
1377
|
-
].join("\n"),
|
|
1378
|
-
);
|
|
1379
|
-
} else {
|
|
1380
|
-
if (request.draftTail.length < request.draft.length) {
|
|
1381
|
-
sections.push(
|
|
1382
|
-
`Current draft tail (the real draft is longer; the cursor is at the end of the full draft):\n${request.draftTail}`,
|
|
1383
|
-
);
|
|
1384
|
-
} else {
|
|
1385
|
-
sections.push(`Current draft (cursor at end):\n${request.draft}`);
|
|
1386
|
-
}
|
|
1387
|
-
|
|
1388
|
-
sections.push(
|
|
1389
|
-
[
|
|
1390
|
-
`Task: propose up to ${request.maxAlternatives} ranked continuations to insert at the cursor.`,
|
|
1391
|
-
"Each item must be only the text after the cursor; never restate text the user already typed.",
|
|
1392
|
-
"If the draft ends inside a partially typed word, complete that word directly without a leading space.",
|
|
1393
|
-
].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,
|
|
1394
1820
|
);
|
|
1395
1821
|
}
|
|
1396
1822
|
|
|
1397
1823
|
const userMessage: UserMessage = {
|
|
1398
1824
|
role: "user",
|
|
1399
|
-
content: [{ type: "text", text:
|
|
1825
|
+
content: [{ type: "text", text: renderPromptAutocompleteUserText(request) }],
|
|
1400
1826
|
timestamp: Date.now(),
|
|
1401
1827
|
};
|
|
1402
1828
|
|
|
@@ -1408,8 +1834,10 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1408
1834
|
messages: [userMessage],
|
|
1409
1835
|
};
|
|
1410
1836
|
const requestOptions = {
|
|
1411
|
-
|
|
1412
|
-
|
|
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 }),
|
|
1413
1841
|
signal,
|
|
1414
1842
|
maxTokens: computeRequestMaxTokens(request.maxAlternatives, request.maxSuggestionChars),
|
|
1415
1843
|
timeoutMs: REQUEST_TIMEOUT_MS,
|
|
@@ -1505,10 +1933,11 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1505
1933
|
const currentModel = resolveSuggestionModel(this.shared);
|
|
1506
1934
|
if (formatModelLabel(currentModel) !== request.modelLabel) return false;
|
|
1507
1935
|
|
|
1508
|
-
// Session entries are immutable
|
|
1509
|
-
// from which all bounded context sections were
|
|
1510
|
-
//
|
|
1511
|
-
|
|
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;
|
|
1512
1941
|
}
|
|
1513
1942
|
|
|
1514
1943
|
cancelActiveRequest(): void {
|
|
@@ -1516,10 +1945,39 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
1516
1945
|
this.setSuggestions([]);
|
|
1517
1946
|
}
|
|
1518
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
|
+
|
|
1519
1962
|
private clearPendingRequestIfOwned(seq: number): void {
|
|
1520
1963
|
this.pendingRequests.clearIfOwned(seq);
|
|
1521
1964
|
}
|
|
1522
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
|
+
|
|
1523
1981
|
private cancelPendingRequest(): void {
|
|
1524
1982
|
this.requestSeq += 1;
|
|
1525
1983
|
|
|
@@ -1544,6 +2002,7 @@ function releaseEditorRuntime(shared: PromptAutocompleteSharedState): void {
|
|
|
1544
2002
|
clearDebugUi(shared);
|
|
1545
2003
|
shared.refreshEditor = undefined;
|
|
1546
2004
|
shared.cancelActiveRequest = undefined;
|
|
2005
|
+
shared.cancelScheduledRequest = undefined;
|
|
1547
2006
|
shared.setStatusText = undefined;
|
|
1548
2007
|
shared.setSpinnerActive = undefined;
|
|
1549
2008
|
shared.clearSpinner = undefined;
|
|
@@ -1561,7 +2020,7 @@ function releaseEditorRuntime(shared: PromptAutocompleteSharedState): void {
|
|
|
1561
2020
|
function hostOwnsInteractiveEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): boolean {
|
|
1562
2021
|
// A host that already accepted an editor factory without installing it is not
|
|
1563
2022
|
// interactive, no matter what its capabilities claim.
|
|
1564
|
-
if (shared.hostInstallsEditors === false) return false;
|
|
2023
|
+
if (shared.processState.hostInstallsEditors === false) return false;
|
|
1565
2024
|
const host = ctx as Partial<Pick<ExtensionContext, "mode" | "hasUI" | "ui">>;
|
|
1566
2025
|
return isInteractiveEditorHost({
|
|
1567
2026
|
mode: host.mode,
|
|
@@ -1659,6 +2118,10 @@ function mountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedStat
|
|
|
1659
2118
|
if (activationId !== shared.activationId) return;
|
|
1660
2119
|
editor.cancelActiveRequest();
|
|
1661
2120
|
};
|
|
2121
|
+
shared.cancelScheduledRequest = () => {
|
|
2122
|
+
if (activationId !== shared.activationId) return;
|
|
2123
|
+
editor.cancelScheduledRequest();
|
|
2124
|
+
};
|
|
1662
2125
|
return editor;
|
|
1663
2126
|
};
|
|
1664
2127
|
|
|
@@ -1679,7 +2142,7 @@ function mountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedStat
|
|
|
1679
2142
|
if (ctx.ui.getEditorComponent() !== installedFactory) {
|
|
1680
2143
|
releaseEditorRuntime(shared);
|
|
1681
2144
|
shared.editorMount = undefined;
|
|
1682
|
-
shared.hostInstallsEditors = false;
|
|
2145
|
+
shared.processState.hostInstallsEditors = false;
|
|
1683
2146
|
// Nothing can render or request here, so the extension must not stay marked
|
|
1684
2147
|
// enabled, no matter which path attempted the mount.
|
|
1685
2148
|
shared.enabled = false;
|
|
@@ -1692,7 +2155,7 @@ function mountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedStat
|
|
|
1692
2155
|
return false;
|
|
1693
2156
|
}
|
|
1694
2157
|
|
|
1695
|
-
shared.hostInstallsEditors = true;
|
|
2158
|
+
shared.processState.hostInstallsEditors = true;
|
|
1696
2159
|
updateDebugState(shared, "mounted", "Editor extension attached");
|
|
1697
2160
|
return true;
|
|
1698
2161
|
}
|
|
@@ -1714,10 +2177,20 @@ function unmountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedSt
|
|
|
1714
2177
|
function resetSharedForSession(pi: ExtensionAPI, shared: PromptAutocompleteSharedState): void {
|
|
1715
2178
|
shared.cancelActiveRequest?.();
|
|
1716
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();
|
|
1717
2190
|
applyEffectiveConfig(pi, shared);
|
|
1718
2191
|
// A host that never installs custom editors stays inactive for the rest of
|
|
1719
2192
|
// the process, so flags must not re-enable it in a later session either.
|
|
1720
|
-
if (shared.hostInstallsEditors === false) shared.enabled = false;
|
|
2193
|
+
if (shared.processState.hostInstallsEditors === false) shared.enabled = false;
|
|
1721
2194
|
shared.usageStats = createPromptAutocompleteUsageStats();
|
|
1722
2195
|
shared.editorMount = undefined;
|
|
1723
2196
|
shared.editorBlockedReason = undefined;
|
|
@@ -1725,6 +2198,7 @@ function resetSharedForSession(pi: ExtensionAPI, shared: PromptAutocompleteShare
|
|
|
1725
2198
|
shared.lastError = undefined;
|
|
1726
2199
|
shared.lastRawResponse = undefined;
|
|
1727
2200
|
shared.reportedModelRefusals.clear();
|
|
2201
|
+
shared.projectedContextMemo = undefined;
|
|
1728
2202
|
shared.requestCache.clear();
|
|
1729
2203
|
shared.prefixReuseCache.clear();
|
|
1730
2204
|
cancelAllCoalescedRequests(shared.inFlightRequests);
|
|
@@ -1735,7 +2209,81 @@ function bindRuntimeContext(ctx: ExtensionContext, shared: PromptAutocompleteSha
|
|
|
1735
2209
|
shared.currentModel = ctx.model as Model<Api> | undefined;
|
|
1736
2210
|
shared.modelRegistry = ctx.modelRegistry;
|
|
1737
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 {
|
|
1738
2284
|
shared.agentStreaming = false;
|
|
2285
|
+
if (!shared.enabled) return;
|
|
2286
|
+
refreshEditorImmediately(shared, "ready", details);
|
|
1739
2287
|
}
|
|
1740
2288
|
|
|
1741
2289
|
function refreshEditorImmediately(shared: PromptAutocompleteSharedState, state: string, details: string): void {
|
|
@@ -1817,29 +2365,444 @@ function setStreamResponses(
|
|
|
1817
2365
|
}
|
|
1818
2366
|
}
|
|
1819
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
|
+
|
|
2430
|
+
function setMinPromptChars(
|
|
2431
|
+
ctx: ExtensionContext,
|
|
2432
|
+
shared: PromptAutocompleteSharedState,
|
|
2433
|
+
arg: string | undefined,
|
|
2434
|
+
): void {
|
|
2435
|
+
if (arg === undefined) {
|
|
2436
|
+
const resolution = resolvePersistedNumber(
|
|
2437
|
+
shared.runtimeOverrides.minPromptChars,
|
|
2438
|
+
shared.minPromptCharsFlagExplicit,
|
|
2439
|
+
shared.persistedSettings.minPromptChars,
|
|
2440
|
+
DEFAULT_MIN_PROMPT_CHARS,
|
|
2441
|
+
);
|
|
2442
|
+
ctx.ui.notify(
|
|
2443
|
+
`Prompt autocomplete min-chars is ${shared.config.minPromptChars} (${resolution.source})`,
|
|
2444
|
+
"info",
|
|
2445
|
+
);
|
|
2446
|
+
return;
|
|
2447
|
+
}
|
|
2448
|
+
|
|
2449
|
+
const parsed = Number.parseInt(arg, 10);
|
|
2450
|
+
if (!Number.isInteger(parsed) || String(parsed) !== arg || parsed < MIN_PROMPT_CHARS_MIN || parsed > MIN_PROMPT_CHARS_MAX) {
|
|
2451
|
+
ctx.ui.notify(
|
|
2452
|
+
`Usage: /prompt-autocomplete min-chars [${MIN_PROMPT_CHARS_MIN}-${MIN_PROMPT_CHARS_MAX}]`,
|
|
2453
|
+
"warning",
|
|
2454
|
+
);
|
|
2455
|
+
return;
|
|
2456
|
+
}
|
|
2457
|
+
|
|
2458
|
+
const changed = shared.config.minPromptChars !== parsed;
|
|
2459
|
+
shared.config.minPromptChars = parsed;
|
|
2460
|
+
shared.runtimeOverrides.minPromptChars = parsed;
|
|
2461
|
+
const persisted = persistSettingsDecision(ctx, shared, { minPromptChars: parsed });
|
|
2462
|
+
ctx.ui.notify(
|
|
2463
|
+
`Prompt autocomplete min-chars set to ${parsed}${
|
|
2464
|
+
persisted ? " (saved for future sessions)" : " (session only — could not save for future sessions)"
|
|
2465
|
+
}`,
|
|
2466
|
+
"info",
|
|
2467
|
+
);
|
|
2468
|
+
|
|
2469
|
+
if (shared.enabled && changed) {
|
|
2470
|
+
refreshEditorImmediately(shared, "ready", `Minimum prompt length set to ${parsed}`);
|
|
2471
|
+
}
|
|
2472
|
+
}
|
|
2473
|
+
|
|
1820
2474
|
/**
|
|
1821
|
-
* Record an explicit
|
|
2475
|
+
* Record an explicit user decision so later processes honour it.
|
|
1822
2476
|
*
|
|
1823
2477
|
* The in-memory copy is updated even when the store write fails, so the
|
|
1824
2478
|
* current process stays consistent with what the user asked for.
|
|
1825
2479
|
*/
|
|
1826
|
-
function
|
|
2480
|
+
function persistSettingsDecision(
|
|
1827
2481
|
ctx: ExtensionContext,
|
|
1828
2482
|
shared: PromptAutocompleteSharedState,
|
|
1829
|
-
|
|
1830
|
-
):
|
|
1831
|
-
shared.persistedSettings = { ...shared.persistedSettings,
|
|
2483
|
+
patch: Partial<PromptAutocompletePersistedSettings>,
|
|
2484
|
+
): boolean {
|
|
2485
|
+
shared.persistedSettings = { ...shared.persistedSettings, ...patch };
|
|
1832
2486
|
const store = shared.settingsStore;
|
|
1833
|
-
if (!store) return;
|
|
2487
|
+
if (!store) return false;
|
|
1834
2488
|
try {
|
|
1835
2489
|
store.save(shared.persistedSettings);
|
|
2490
|
+
return true;
|
|
1836
2491
|
} catch (error) {
|
|
1837
2492
|
const reason = error instanceof Error ? error.message : String(error);
|
|
1838
2493
|
ctx.ui.notify(
|
|
1839
|
-
`Prompt autocomplete could not save the
|
|
2494
|
+
`Prompt autocomplete could not save the setting: ${truncateDebug(reason, 90)}`,
|
|
1840
2495
|
"warning",
|
|
1841
2496
|
);
|
|
2497
|
+
return false;
|
|
2498
|
+
}
|
|
2499
|
+
}
|
|
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;
|
|
1842
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
|
+
|
|
2800
|
+
function persistEnabledDecision(
|
|
2801
|
+
ctx: ExtensionContext,
|
|
2802
|
+
shared: PromptAutocompleteSharedState,
|
|
2803
|
+
enabled: boolean,
|
|
2804
|
+
): void {
|
|
2805
|
+
persistSettingsDecision(ctx, shared, { enabled });
|
|
1843
2806
|
}
|
|
1844
2807
|
|
|
1845
2808
|
function enablePromptAutocomplete(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): boolean {
|
|
@@ -1847,7 +2810,7 @@ function enablePromptAutocomplete(ctx: ExtensionContext, shared: PromptAutocompl
|
|
|
1847
2810
|
shared.enabled = true;
|
|
1848
2811
|
shared.runtimeOverrides.enabled = true;
|
|
1849
2812
|
|
|
1850
|
-
if (!mountEditor(ctx, shared) && shared.hostInstallsEditors === false) {
|
|
2813
|
+
if (!mountEditor(ctx, shared) && shared.processState.hostInstallsEditors === false) {
|
|
1851
2814
|
// The host accepted the editor factory without installing it. mountEditor
|
|
1852
2815
|
// already cleared `enabled`; keep it cleared and drop the session override
|
|
1853
2816
|
// so the refused activation is not replayed as a user decision later.
|
|
@@ -1882,7 +2845,7 @@ function notifyPromptAutocompleteEnabled(
|
|
|
1882
2845
|
`${formatPrimaryKey(CYCLE_NEXT_KEYS)} also forces a one-shot suggestion when none is shown (even while the agent works).`;
|
|
1883
2846
|
const resolution = resolveSuggestionModelResolution(shared);
|
|
1884
2847
|
const resolvedModel = resolution.model;
|
|
1885
|
-
const privacyNotice =
|
|
2848
|
+
const privacyNotice = PRIVACY_NOTICE;
|
|
1886
2849
|
|
|
1887
2850
|
if (!resolvedModel && resolution.refusedRequest) {
|
|
1888
2851
|
// A refused explicit request must be reported on every enable path,
|
|
@@ -1915,91 +2878,155 @@ function notifyPromptAutocompleteEnabled(
|
|
|
1915
2878
|
ctx.ui.notify(`Prompt autocomplete enabled. ${keyHint} ${privacyNotice}`, "info");
|
|
1916
2879
|
}
|
|
1917
2880
|
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
status: () => {
|
|
1924
|
-
ctx.ui.notify(formatStatus(shared), "info");
|
|
1925
|
-
},
|
|
1926
|
-
stats: () => {
|
|
1927
|
-
ctx.ui.notify(formatPromptAutocompleteStats(shared.usageStats), "info");
|
|
1928
|
-
},
|
|
1929
|
-
"debug-on": () => {
|
|
1930
|
-
setDebugDisplay(shared, true);
|
|
1931
|
-
ctx.ui.notify("Prompt autocomplete debug display enabled", "info");
|
|
1932
|
-
},
|
|
1933
|
-
"debug-off": () => {
|
|
1934
|
-
setDebugDisplay(shared, false);
|
|
1935
|
-
ctx.ui.notify("Prompt autocomplete debug display disabled", "info");
|
|
1936
|
-
},
|
|
1937
|
-
"debug-toggle": () => {
|
|
1938
|
-
const nextDebugEnabled = !shared.config.debug;
|
|
1939
|
-
setDebugDisplay(shared, nextDebugEnabled);
|
|
1940
|
-
ctx.ui.notify(
|
|
1941
|
-
nextDebugEnabled
|
|
1942
|
-
? "Prompt autocomplete debug display enabled"
|
|
1943
|
-
: "Prompt autocomplete debug display disabled",
|
|
1944
|
-
"info",
|
|
1945
|
-
);
|
|
1946
|
-
},
|
|
1947
|
-
on: () => {
|
|
1948
|
-
if (shared.enabled && shared.ownsEditor?.()) {
|
|
1949
|
-
// Already in the requested state, but the user still expressed intent:
|
|
1950
|
-
// record it so later sessions and processes do not fall back to the flag.
|
|
1951
|
-
shared.runtimeOverrides.enabled = true;
|
|
1952
|
-
persistEnabledDecision(ctx, shared, true);
|
|
1953
|
-
ctx.ui.notify(`Prompt autocomplete already enabled (${formatStatus(shared)})`, "info");
|
|
1954
|
-
return;
|
|
1955
|
-
}
|
|
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
|
+
}
|
|
1956
2886
|
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
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
|
+
}
|
|
1969
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
|
+
}
|
|
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) {
|
|
1970
2953
|
disablePromptAutocomplete(ctx, shared);
|
|
1971
2954
|
persistEnabledDecision(ctx, shared, false);
|
|
1972
2955
|
ctx.ui.notify("Prompt autocomplete disabled", "info");
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
if (shared.enabled) {
|
|
1976
|
-
disablePromptAutocomplete(ctx, shared);
|
|
1977
|
-
persistEnabledDecision(ctx, shared, false);
|
|
1978
|
-
ctx.ui.notify("Prompt autocomplete disabled", "info");
|
|
1979
|
-
return;
|
|
1980
|
-
}
|
|
2956
|
+
return;
|
|
2957
|
+
}
|
|
1981
2958
|
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
}
|
|
1988
|
-
|
|
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
|
+
};
|
|
1989
2998
|
|
|
1990
2999
|
export function createPromptAutocompleteExtension(
|
|
1991
3000
|
dependencies: PromptAutocompleteDependencies = {},
|
|
1992
3001
|
): (pi: ExtensionAPI) => void {
|
|
1993
|
-
const completeSimpleImpl = dependencies.completeSimple ?? hostCompleteSimple;
|
|
1994
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;
|
|
1995
3024
|
// Existing deterministic harnesses inject only completeSimple. Never let such
|
|
1996
3025
|
// a harness fall through to the real network-capable stream implementation.
|
|
1997
3026
|
const streamSimpleImpl =
|
|
1998
3027
|
dependencies.streamSimple
|
|
1999
|
-
?? (dependencies.completeSimple || !hostStreaming ? undefined :
|
|
2000
|
-
const now = dependencies.now ?? Date.now;
|
|
3028
|
+
?? (dependencies.completeSimple || !hostStreaming ? undefined : routedStreamSimple);
|
|
2001
3029
|
|
|
2002
|
-
return function promptAutocompleteExtension(pi: ExtensionAPI): void {
|
|
2003
3030
|
const settingsStore = dependencies.settingsStore ?? createFileSettingsStore(resolvePromptAutocompleteSettingsPath());
|
|
2004
3031
|
let persistedSettings: PromptAutocompletePersistedSettings;
|
|
2005
3032
|
try {
|
|
@@ -2056,25 +3083,36 @@ export function createPromptAutocompleteExtension(
|
|
|
2056
3083
|
type: "string",
|
|
2057
3084
|
default: String(DEFAULT_MAX_ALTERNATIVES),
|
|
2058
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
|
+
});
|
|
2059
3091
|
|
|
2060
3092
|
const shared: PromptAutocompleteSharedState = {
|
|
2061
3093
|
enabled: false,
|
|
2062
3094
|
activationId: 0,
|
|
2063
3095
|
agentStreaming: false,
|
|
3096
|
+
physicalSessionId: "",
|
|
3097
|
+
lastConversationId: "",
|
|
2064
3098
|
config: parseConfig(pi),
|
|
2065
3099
|
runtimeOverrides: {},
|
|
2066
3100
|
persistedSettings,
|
|
2067
3101
|
settingsStore,
|
|
2068
3102
|
enabledFlagValue: false,
|
|
3103
|
+
budgetUsed: 0,
|
|
3104
|
+
budgetBlockNotices: new Set(),
|
|
2069
3105
|
usageStats: createPromptAutocompleteUsageStats(),
|
|
2070
3106
|
completeSimple: completeSimpleImpl,
|
|
2071
3107
|
streamSimple: streamSimpleImpl,
|
|
3108
|
+
routesThroughHostRegistry: () => hostRegistryStream() !== undefined,
|
|
2072
3109
|
now,
|
|
2073
3110
|
debugState: "idle",
|
|
2074
3111
|
requestCache: new ExpiringLruCache(REQUEST_CACHE_TTL_MS, REQUEST_CACHE_MAX_ENTRIES, now),
|
|
2075
3112
|
prefixReuseCache: new ExpiringLruCache(REQUEST_CACHE_TTL_MS, REQUEST_CACHE_MAX_ENTRIES, now),
|
|
2076
3113
|
inFlightRequests: new Map(),
|
|
2077
3114
|
reportedModelRefusals: new Set(),
|
|
3115
|
+
processState: dependencies.processState ?? sharedProcessState(),
|
|
2078
3116
|
};
|
|
2079
3117
|
|
|
2080
3118
|
pi.on("session_start", async (_event, ctx) => {
|
|
@@ -2083,8 +3121,12 @@ export function createPromptAutocompleteExtension(
|
|
|
2083
3121
|
}
|
|
2084
3122
|
resetSharedForSession(pi, shared);
|
|
2085
3123
|
bindRuntimeContext(ctx, shared);
|
|
3124
|
+
restoreBudgetFromSession(pi, shared);
|
|
2086
3125
|
|
|
2087
|
-
if (!hostOwnsInteractiveEditor(ctx, shared) || !shared.enabled)
|
|
3126
|
+
if (!hostOwnsInteractiveEditor(ctx, shared) || !shared.enabled) {
|
|
3127
|
+
notifyEnabledWithoutEditorOnce(ctx, shared);
|
|
3128
|
+
return;
|
|
3129
|
+
}
|
|
2088
3130
|
mountEditor(ctx, shared);
|
|
2089
3131
|
});
|
|
2090
3132
|
|
|
@@ -2108,6 +3150,9 @@ export function createPromptAutocompleteExtension(
|
|
|
2108
3150
|
pi.on("session_tree", async (_event, ctx) => {
|
|
2109
3151
|
shared.sessionManager = ctx.sessionManager;
|
|
2110
3152
|
if (!shared.enabled) return;
|
|
3153
|
+
const nextConversationId = resolveCurrentConversationId(shared);
|
|
3154
|
+
if (nextConversationId === shared.lastConversationId) return;
|
|
3155
|
+
shared.lastConversationId = nextConversationId;
|
|
2111
3156
|
refreshEditorImmediately(shared, "context-changed", "Conversation branch changed");
|
|
2112
3157
|
});
|
|
2113
3158
|
|
|
@@ -2117,44 +3162,48 @@ export function createPromptAutocompleteExtension(
|
|
|
2117
3162
|
refreshEditorImmediately(shared, "waiting", "Main agent is still working");
|
|
2118
3163
|
});
|
|
2119
3164
|
|
|
2120
|
-
pi.on("agent_end", async () => {
|
|
2121
|
-
shared
|
|
2122
|
-
if (
|
|
2123
|
-
|
|
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");
|
|
2124
3173
|
});
|
|
2125
3174
|
|
|
2126
3175
|
pi.registerCommand("prompt-autocomplete", {
|
|
2127
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),
|
|
2128
3179
|
handler: async (args, ctx) => {
|
|
2129
|
-
|
|
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))) {
|
|
2130
3193
|
ctx.ui.notify("prompt-autocomplete requires interactive TUI mode", "warning");
|
|
2131
3194
|
return;
|
|
2132
3195
|
}
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
const command = parts[0] || "status";
|
|
2136
|
-
|
|
2137
|
-
if (command === "while-streaming") {
|
|
2138
|
-
setWhileStreaming(ctx, shared, parts[1]);
|
|
3196
|
+
if (!spec) {
|
|
3197
|
+
ctx.ui.notify(PROMPT_AUTOCOMPLETE_USAGE, "warning");
|
|
2139
3198
|
return;
|
|
2140
3199
|
}
|
|
2141
|
-
if (command === "stream") {
|
|
2142
|
-
setStreamResponses(ctx, shared, parts[1]);
|
|
2143
|
-
return;
|
|
2144
|
-
}
|
|
2145
|
-
|
|
2146
|
-
const handlers = createPromptAutocompleteCommandHandlers(ctx, shared);
|
|
2147
|
-
const handler = handlers[command];
|
|
2148
3200
|
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
"Usage: /prompt-autocomplete [on|off|toggle|status|stats|stream on|off|toggle|while-streaming on|off|toggle|debug-on|debug-off|debug-toggle]",
|
|
2156
|
-
"warning",
|
|
2157
|
-
);
|
|
3201
|
+
COMMAND_RUNNERS[spec.name](ctx, shared, {
|
|
3202
|
+
payload,
|
|
3203
|
+
rest,
|
|
3204
|
+
firstArgument: rest.split(/\s+/, 1)[0] || undefined,
|
|
3205
|
+
interactiveHost,
|
|
3206
|
+
});
|
|
2158
3207
|
},
|
|
2159
3208
|
});
|
|
2160
3209
|
};
|