@kliebhan/pi-prompt-autocomplete 0.1.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/LICENSE +21 -0
- package/README.md +103 -0
- package/core.ts +1038 -0
- package/index.ts +1412 -0
- package/media/prompt-autocomplete-demo.mp4 +0 -0
- package/package.json +52 -0
- package/system-prompt.template.md +18 -0
package/index.ts
ADDED
|
@@ -0,0 +1,1412 @@
|
|
|
1
|
+
import { completeSimple, type Api, type Model, type UserMessage } from "@earendil-works/pi-ai/compat";
|
|
2
|
+
import { CustomEditor, type ExtensionAPI, type ExtensionContext, type KeybindingsManager } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import { matchesKey, truncateToWidth, type EditorTheme, type KeyId, type TUI, visibleWidth } from "@earendil-works/pi-tui";
|
|
4
|
+
import {
|
|
5
|
+
acquireCoalescedRequest,
|
|
6
|
+
buildLatestAssistantMessageContext,
|
|
7
|
+
buildLatestUserMessageContext,
|
|
8
|
+
buildPromptAutocompleteCacheKey,
|
|
9
|
+
buildRecentConversationContext,
|
|
10
|
+
cancelAllCoalescedRequests,
|
|
11
|
+
computeRequestMaxTokens,
|
|
12
|
+
createOwnerRefCounter,
|
|
13
|
+
DEFAULT_DEBOUNCE_MS,
|
|
14
|
+
DEFAULT_MAX_ALTERNATIVES,
|
|
15
|
+
DEFAULT_MAX_SUGGESTION_CHARS,
|
|
16
|
+
DEFAULT_MIN_PROMPT_CHARS,
|
|
17
|
+
DEFAULT_PREFERRED_MODEL,
|
|
18
|
+
DEFAULT_PROMPT_AUTOCOMPLETE_ENABLED,
|
|
19
|
+
ExpiringLruCache,
|
|
20
|
+
extractNextSuggestionChunk,
|
|
21
|
+
formatModelLabel,
|
|
22
|
+
MAX_DRAFT_CONTEXT_CHARS,
|
|
23
|
+
normalizePromptSuggestions,
|
|
24
|
+
parseBoundedIntFlag,
|
|
25
|
+
parseModelRef,
|
|
26
|
+
PROMPT_AUTOCOMPLETE_SYSTEM_PROMPT,
|
|
27
|
+
SequenceOwnedSlot,
|
|
28
|
+
shouldSkipPromptAutocomplete,
|
|
29
|
+
truncateDraftTail,
|
|
30
|
+
type CoalescedRequestEntry,
|
|
31
|
+
type CoalescedRequestSubscription,
|
|
32
|
+
type ModelRef,
|
|
33
|
+
} from "./core.ts";
|
|
34
|
+
|
|
35
|
+
const GHOST_TEXT_STYLE = "\x1b[2m";
|
|
36
|
+
const GHOST_INDICATOR_STYLE = "\x1b[90m";
|
|
37
|
+
const RESET = "\x1b[0m";
|
|
38
|
+
const CURSOR_TOKEN = "\x1b[7m \x1b[0m";
|
|
39
|
+
const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] as const;
|
|
40
|
+
const SPINNER_INTERVAL_MS = 80;
|
|
41
|
+
const SPINNER_LABEL = "Generating suggestion";
|
|
42
|
+
// Inline autocomplete should fail fast instead of inheriting long provider retry/timeout defaults.
|
|
43
|
+
const REQUEST_TIMEOUT_MS = 8_000;
|
|
44
|
+
const REQUEST_MAX_RETRIES = 0;
|
|
45
|
+
const REQUEST_MAX_RETRY_DELAY_MS = 2_000;
|
|
46
|
+
// Brief cooldown avoids hammering providers after transient auth/network failures while keeping the UI responsive.
|
|
47
|
+
const FAILURE_COOLDOWN_MS = 5_000;
|
|
48
|
+
const REQUEST_CACHE_TTL_MS = 60_000;
|
|
49
|
+
const REQUEST_CACHE_MAX_ENTRIES = 128;
|
|
50
|
+
// Keymap audit vs. pi defaults (packages/tui/src/keybindings.ts +
|
|
51
|
+
// packages/coding-agent/src/core/keybindings.ts): none of the keys below are bound
|
|
52
|
+
// by pi's default keymap, so the editor can safely own them — including the
|
|
53
|
+
// broadened `ctrl+.`/`alt+]` one-shot trigger, which shadows no base action. The
|
|
54
|
+
// only nearby defaults are `ctrl+]` (jumpForward) and `ctrl+alt+]` (jumpBackward),
|
|
55
|
+
// both distinct from our `alt+]`.
|
|
56
|
+
const WORD_ACCEPT_KEYS: readonly KeyId[] = ["ctrl+space", "ctrl+tab"];
|
|
57
|
+
const CYCLE_NEXT_KEYS: readonly KeyId[] = ["ctrl+.", "alt+]"];
|
|
58
|
+
const CYCLE_PREV_KEYS: readonly KeyId[] = ["ctrl+,", "alt+["];
|
|
59
|
+
const NAVIGATION_ACTIONS = [
|
|
60
|
+
"tui.editor.cursorUp",
|
|
61
|
+
"tui.editor.cursorDown",
|
|
62
|
+
"tui.editor.cursorLeft",
|
|
63
|
+
"tui.editor.cursorRight",
|
|
64
|
+
"tui.editor.cursorWordLeft",
|
|
65
|
+
"tui.editor.cursorWordRight",
|
|
66
|
+
"tui.editor.cursorLineStart",
|
|
67
|
+
"tui.editor.cursorLineEnd",
|
|
68
|
+
"tui.editor.jumpForward",
|
|
69
|
+
"tui.editor.jumpBackward",
|
|
70
|
+
"tui.editor.pageUp",
|
|
71
|
+
"tui.editor.pageDown",
|
|
72
|
+
] as const;
|
|
73
|
+
const EDIT_ACTIONS = [
|
|
74
|
+
"tui.editor.deleteCharBackward",
|
|
75
|
+
"tui.editor.deleteCharForward",
|
|
76
|
+
"tui.editor.deleteWordBackward",
|
|
77
|
+
"tui.editor.deleteWordForward",
|
|
78
|
+
"tui.editor.deleteToLineStart",
|
|
79
|
+
"tui.editor.deleteToLineEnd",
|
|
80
|
+
"tui.editor.yank",
|
|
81
|
+
"tui.editor.yankPop",
|
|
82
|
+
"tui.editor.undo",
|
|
83
|
+
"tui.input.newLine",
|
|
84
|
+
"app.clear",
|
|
85
|
+
] as const;
|
|
86
|
+
|
|
87
|
+
interface PromptAutocompleteConfig {
|
|
88
|
+
allowWhileStreaming: boolean;
|
|
89
|
+
debug: boolean;
|
|
90
|
+
debounceMs: number;
|
|
91
|
+
minPromptChars: number;
|
|
92
|
+
maxSuggestionChars: number;
|
|
93
|
+
maxAlternatives: number;
|
|
94
|
+
preferredModel?: ModelRef;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
interface PromptAutocompleteCacheEntry {
|
|
98
|
+
suggestions: string[];
|
|
99
|
+
rawResponse?: string;
|
|
100
|
+
error?: string;
|
|
101
|
+
debugState?: string;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
interface SuggestionRefreshOptions {
|
|
105
|
+
clearExisting?: boolean;
|
|
106
|
+
immediate?: boolean;
|
|
107
|
+
// Manual one-shot trigger: bypasses the streaming gate and error cooldown so the
|
|
108
|
+
// user can force a single suggestion while the main agent is still working.
|
|
109
|
+
manual?: boolean;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
type EditorFactory = Exclude<Parameters<ExtensionContext["ui"]["setEditorComponent"]>[0], undefined>;
|
|
113
|
+
|
|
114
|
+
interface EditorMountState {
|
|
115
|
+
previousFactory: EditorFactory | undefined;
|
|
116
|
+
installedFactory: EditorFactory;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
type CompleteSimpleFunction = typeof completeSimple;
|
|
120
|
+
|
|
121
|
+
export interface PromptAutocompleteDependencies {
|
|
122
|
+
completeSimple?: CompleteSimpleFunction;
|
|
123
|
+
now?: () => number;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
interface PromptAutocompleteSharedState {
|
|
127
|
+
enabled: boolean;
|
|
128
|
+
activationId: number;
|
|
129
|
+
streaming: boolean;
|
|
130
|
+
config: PromptAutocompleteConfig;
|
|
131
|
+
currentModel?: Model<Api>;
|
|
132
|
+
modelRegistry?: ExtensionContext["modelRegistry"];
|
|
133
|
+
sessionManager?: ExtensionContext["sessionManager"];
|
|
134
|
+
completeSimple: CompleteSimpleFunction;
|
|
135
|
+
now: () => number;
|
|
136
|
+
debugState: string;
|
|
137
|
+
editorMount?: EditorMountState;
|
|
138
|
+
editorBlockedReason?: string;
|
|
139
|
+
lastError?: string;
|
|
140
|
+
lastRawResponse?: string;
|
|
141
|
+
requestCache: ExpiringLruCache<PromptAutocompleteCacheEntry>;
|
|
142
|
+
inFlightRequests: Map<string, CoalescedRequestEntry<PromptAutocompleteCacheEntry>>;
|
|
143
|
+
ownsEditor?: () => boolean;
|
|
144
|
+
refreshEditor?: (options?: SuggestionRefreshOptions) => void;
|
|
145
|
+
cancelActiveRequest?: () => void;
|
|
146
|
+
setStatusText?: (text: string | undefined) => void;
|
|
147
|
+
setSpinnerActive?: (owner: string, active: boolean) => void;
|
|
148
|
+
clearSpinner?: () => void;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
interface SuggestionRequest {
|
|
152
|
+
activationId: number;
|
|
153
|
+
draft: string;
|
|
154
|
+
draftTail: string;
|
|
155
|
+
model: Model<Api>;
|
|
156
|
+
modelLabel: string;
|
|
157
|
+
cacheKey: string;
|
|
158
|
+
maxAlternatives: number;
|
|
159
|
+
latestAssistantContext: string;
|
|
160
|
+
latestUserContext: string;
|
|
161
|
+
recentContext: string;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
interface PendingSuggestionRequest {
|
|
165
|
+
key: string;
|
|
166
|
+
seq: number;
|
|
167
|
+
spinnerOwner: string;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function arraysEqual(a: string[], b: string[]): boolean {
|
|
171
|
+
return a.length === b.length && a.every((value, index) => value === b[index]);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function matchesAnyKey(data: string, keys: readonly KeyId[]): boolean {
|
|
175
|
+
return keys.some((key) => matchesKey(data, key));
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function formatPrimaryKey(keys: readonly KeyId[]): string {
|
|
179
|
+
return keys[0] ?? "";
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function resolveSuggestionModel(shared: PromptAutocompleteSharedState): Model<Api> | undefined {
|
|
183
|
+
const registry = shared.modelRegistry;
|
|
184
|
+
if (!registry) return undefined;
|
|
185
|
+
|
|
186
|
+
if (shared.config.preferredModel) {
|
|
187
|
+
const preferred = registry.find(shared.config.preferredModel.provider, shared.config.preferredModel.id);
|
|
188
|
+
if (preferred && registry.hasConfiguredAuth(preferred)) {
|
|
189
|
+
return preferred as Model<Api>;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
if (shared.currentModel && registry.hasConfiguredAuth(shared.currentModel)) {
|
|
194
|
+
return shared.currentModel as Model<Api>;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
return undefined;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function parseConfig(pi: ExtensionAPI): PromptAutocompleteConfig {
|
|
201
|
+
return {
|
|
202
|
+
allowWhileStreaming: pi.getFlag("prompt-autocomplete-while-streaming") === true,
|
|
203
|
+
debug: pi.getFlag("prompt-autocomplete-debug") === true,
|
|
204
|
+
debounceMs: parseBoundedIntFlag(pi.getFlag("prompt-autocomplete-debounce-ms"), DEFAULT_DEBOUNCE_MS, 0, 5_000),
|
|
205
|
+
minPromptChars: parseBoundedIntFlag(pi.getFlag("prompt-autocomplete-min-chars"), DEFAULT_MIN_PROMPT_CHARS, 0, 500),
|
|
206
|
+
maxSuggestionChars: parseBoundedIntFlag(
|
|
207
|
+
pi.getFlag("prompt-autocomplete-max-chars"),
|
|
208
|
+
DEFAULT_MAX_SUGGESTION_CHARS,
|
|
209
|
+
16,
|
|
210
|
+
1_000,
|
|
211
|
+
),
|
|
212
|
+
maxAlternatives: parseBoundedIntFlag(
|
|
213
|
+
pi.getFlag("prompt-autocomplete-max-alternatives"),
|
|
214
|
+
DEFAULT_MAX_ALTERNATIVES,
|
|
215
|
+
1,
|
|
216
|
+
5,
|
|
217
|
+
),
|
|
218
|
+
preferredModel: parseModelRef(pi.getFlag("prompt-autocomplete-model")),
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function truncateDebug(text: string, maxLength = 140): string {
|
|
223
|
+
const normalized = text.replace(/\s+/g, " ").trim();
|
|
224
|
+
if (normalized.length <= maxLength) return normalized;
|
|
225
|
+
return `${normalized.slice(0, maxLength - 1)}…`;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function updateDebugState(shared: PromptAutocompleteSharedState, state: string, details?: string): void {
|
|
229
|
+
const nextState = details ? `${state}: ${truncateDebug(details)}` : state;
|
|
230
|
+
shared.debugState = nextState;
|
|
231
|
+
shared.setStatusText?.(shared.config.debug ? nextState : undefined);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function clearDebugUi(shared: PromptAutocompleteSharedState): void {
|
|
235
|
+
shared.setStatusText?.(undefined);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function formatStatus(shared: PromptAutocompleteSharedState): string {
|
|
239
|
+
const resolvedModel = resolveSuggestionModel(shared);
|
|
240
|
+
const editorState = shared.editorMount
|
|
241
|
+
? shared.ownsEditor?.()
|
|
242
|
+
? "mounted"
|
|
243
|
+
: "ownership-lost"
|
|
244
|
+
: shared.editorBlockedReason
|
|
245
|
+
? "blocked"
|
|
246
|
+
: "unmounted";
|
|
247
|
+
const requestedModel = shared.config.preferredModel
|
|
248
|
+
? `${shared.config.preferredModel.provider}/${shared.config.preferredModel.id}`
|
|
249
|
+
: "current active model";
|
|
250
|
+
|
|
251
|
+
return [
|
|
252
|
+
`enabled=${shared.enabled ? "yes" : "no"}`,
|
|
253
|
+
`editor=${editorState}`,
|
|
254
|
+
shared.editorBlockedReason ? `editor-blocked=${truncateDebug(shared.editorBlockedReason, 90)}` : undefined,
|
|
255
|
+
`model=${formatModelLabel(resolvedModel)}`,
|
|
256
|
+
`requested-model=${requestedModel}`,
|
|
257
|
+
`while-streaming=${shared.config.allowWhileStreaming ? "yes" : "no"}`,
|
|
258
|
+
`debug=${shared.config.debug ? "yes" : "no"}`,
|
|
259
|
+
`debounce=${shared.config.debounceMs}ms`,
|
|
260
|
+
`min-chars=${shared.config.minPromptChars}`,
|
|
261
|
+
`max-suggestion-chars=${shared.config.maxSuggestionChars}`,
|
|
262
|
+
`max-alternatives=${shared.config.maxAlternatives}`,
|
|
263
|
+
`cache-size=${shared.requestCache.size}`,
|
|
264
|
+
`state=${shared.debugState || "idle"}`,
|
|
265
|
+
shared.lastError ? `error=${truncateDebug(shared.lastError, 90)}` : undefined,
|
|
266
|
+
shared.lastRawResponse ? `raw=${truncateDebug(shared.lastRawResponse, 90)}` : undefined,
|
|
267
|
+
`keys=tab accept | ${formatPrimaryKey(WORD_ACCEPT_KEYS)} word | ${formatPrimaryKey(CYCLE_PREV_KEYS)}/${formatPrimaryKey(CYCLE_NEXT_KEYS)} cycle | ${formatPrimaryKey(CYCLE_NEXT_KEYS)} force one-shot`,
|
|
268
|
+
]
|
|
269
|
+
.filter((value): value is string => !!value)
|
|
270
|
+
.join(" | ");
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function getCachedRequest(
|
|
274
|
+
shared: PromptAutocompleteSharedState,
|
|
275
|
+
cacheKey: string,
|
|
276
|
+
options: { bypass?: boolean } = {},
|
|
277
|
+
): PromptAutocompleteCacheEntry | undefined {
|
|
278
|
+
const entry = shared.requestCache.get(cacheKey, options);
|
|
279
|
+
return entry ? { ...entry, suggestions: [...entry.suggestions] } : undefined;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function storeCachedRequest(
|
|
283
|
+
shared: PromptAutocompleteSharedState,
|
|
284
|
+
cacheKey: string,
|
|
285
|
+
entry: PromptAutocompleteCacheEntry,
|
|
286
|
+
): PromptAutocompleteCacheEntry {
|
|
287
|
+
const cachedEntry = { ...entry, suggestions: [...entry.suggestions] };
|
|
288
|
+
shared.requestCache.set(cacheKey, cachedEntry);
|
|
289
|
+
return { ...cachedEntry, suggestions: [...cachedEntry.suggestions] };
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
class PromptAutocompleteEditor extends CustomEditor {
|
|
293
|
+
private readonly shared: PromptAutocompleteSharedState;
|
|
294
|
+
private readonly activationId: number;
|
|
295
|
+
private readonly appKeybindings: KeybindingsManager;
|
|
296
|
+
|
|
297
|
+
private suggestions: string[] = [];
|
|
298
|
+
private suggestionIndex: number = 0;
|
|
299
|
+
private debounceTimer?: ReturnType<typeof setTimeout>;
|
|
300
|
+
private requestSeq = 0;
|
|
301
|
+
private readonly pendingRequests = new SequenceOwnedSlot<PendingSuggestionRequest>();
|
|
302
|
+
private activeRequestSubscription?: CoalescedRequestSubscription<PromptAutocompleteCacheEntry>;
|
|
303
|
+
// One owner token per editor instance; the mount-level refcounter keeps the
|
|
304
|
+
// shared spinner alive until every active owner has released it.
|
|
305
|
+
private activeSpinnerOwner?: string;
|
|
306
|
+
private suspendedUntil = 0;
|
|
307
|
+
private dismissedKey?: string;
|
|
308
|
+
|
|
309
|
+
constructor(
|
|
310
|
+
tui: TUI,
|
|
311
|
+
theme: EditorTheme,
|
|
312
|
+
keybindings: KeybindingsManager,
|
|
313
|
+
shared: PromptAutocompleteSharedState,
|
|
314
|
+
activationId: number,
|
|
315
|
+
) {
|
|
316
|
+
super(tui, theme, keybindings);
|
|
317
|
+
this.shared = shared;
|
|
318
|
+
this.activationId = activationId;
|
|
319
|
+
this.appKeybindings = keybindings;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
override setText(text: string): void {
|
|
323
|
+
super.setText(text);
|
|
324
|
+
this.refreshSuggestion({ clearExisting: true });
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
override insertTextAtCursor(text: string): void {
|
|
328
|
+
super.insertTextAtCursor(text);
|
|
329
|
+
this.refreshSuggestion({ clearExisting: true });
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
override handleInput(data: string): void {
|
|
333
|
+
if (this.canDismissInlineSuggestion(data)) {
|
|
334
|
+
this.dismissedKey = this.buildRequest()?.cacheKey;
|
|
335
|
+
this.clearInlineSuggestion("dismissed", "Suggestion dismissed for current draft");
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
if (this.canCycleSuggestions(data)) {
|
|
340
|
+
this.cycleSuggestions(matchesAnyKey(data, CYCLE_NEXT_KEYS) ? 1 : -1);
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
if (this.canTriggerManualSuggestion(data)) {
|
|
345
|
+
this.triggerManualSuggestion();
|
|
346
|
+
return;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
if (this.canAcceptInlineSuggestionByWord(data)) {
|
|
350
|
+
this.acceptInlineSuggestionByWord();
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
if (this.canAcceptInlineSuggestion(data)) {
|
|
355
|
+
this.acceptInlineSuggestion();
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
this.clearInlineSuggestionForUserIntent(data);
|
|
360
|
+
|
|
361
|
+
const beforeText = this.getText();
|
|
362
|
+
const beforeCursor = this.getCursor();
|
|
363
|
+
const beforeAutocomplete = this.isShowingAutocomplete();
|
|
364
|
+
|
|
365
|
+
super.handleInput(data);
|
|
366
|
+
|
|
367
|
+
const afterText = this.getText();
|
|
368
|
+
const afterCursor = this.getCursor();
|
|
369
|
+
const afterAutocomplete = this.isShowingAutocomplete();
|
|
370
|
+
|
|
371
|
+
const textChanged = beforeText !== afterText;
|
|
372
|
+
const cursorChanged = beforeCursor.line !== afterCursor.line || beforeCursor.col !== afterCursor.col;
|
|
373
|
+
const autocompleteChanged = beforeAutocomplete !== afterAutocomplete;
|
|
374
|
+
|
|
375
|
+
if (textChanged || cursorChanged || autocompleteChanged) {
|
|
376
|
+
this.refreshSuggestion({ clearExisting: true });
|
|
377
|
+
return;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
if (this.getActiveSuggestion()) {
|
|
381
|
+
this.refreshSuggestion();
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
override render(width: number): string[] {
|
|
386
|
+
const lines = super.render(width);
|
|
387
|
+
const activeSuggestion = this.getActiveSuggestion();
|
|
388
|
+
if (!this.shouldRenderInlineSuggestion() || !activeSuggestion) {
|
|
389
|
+
return lines;
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
const cursorLineIndex = lines.findIndex((line) => line.includes(CURSOR_TOKEN));
|
|
393
|
+
if (cursorLineIndex === -1) return lines;
|
|
394
|
+
|
|
395
|
+
const cursorLine = lines[cursorLineIndex]!;
|
|
396
|
+
const cursorIndex = cursorLine.indexOf(CURSOR_TOKEN);
|
|
397
|
+
if (cursorIndex === -1) return lines;
|
|
398
|
+
|
|
399
|
+
const before = cursorLine.slice(0, cursorIndex);
|
|
400
|
+
const after = cursorLine.slice(cursorIndex + CURSOR_TOKEN.length);
|
|
401
|
+
const availableWidth = visibleWidth(after);
|
|
402
|
+
if (availableWidth <= 0) return lines;
|
|
403
|
+
|
|
404
|
+
const previewText = activeSuggestion.replace(/\n/g, " ⏎ ");
|
|
405
|
+
const previewChars = Array.from(previewText);
|
|
406
|
+
const firstPreviewChar = previewChars[0] ?? "";
|
|
407
|
+
const absorbLeadingWhitespaceIntoCursor = /^[ \t]$/.test(firstPreviewChar);
|
|
408
|
+
|
|
409
|
+
const cursorCell = absorbLeadingWhitespaceIntoCursor ? `\x1b[7m${firstPreviewChar}\x1b[0m` : CURSOR_TOKEN;
|
|
410
|
+
const renderedPreviewText = absorbLeadingWhitespaceIntoCursor ? previewChars.slice(1).join("") : previewText;
|
|
411
|
+
|
|
412
|
+
const indicator = this.suggestions.length > 1 ? ` ‹${this.suggestionIndex + 1}/${this.suggestions.length}›` : "";
|
|
413
|
+
const indicatorWidth = indicator ? visibleWidth(indicator) : 0;
|
|
414
|
+
const showIndicator = indicatorWidth > 0 && availableWidth >= indicatorWidth + 8;
|
|
415
|
+
const textWidth = Math.max(0, availableWidth - (showIndicator ? indicatorWidth : 0));
|
|
416
|
+
const truncatedText = textWidth > 0
|
|
417
|
+
? truncateToWidth(renderedPreviewText, textWidth, textWidth > 1 ? "…" : "")
|
|
418
|
+
: "";
|
|
419
|
+
const renderedIndicator = showIndicator ? indicator : "";
|
|
420
|
+
const renderedWidth = visibleWidth(truncatedText) + (showIndicator ? indicatorWidth : 0);
|
|
421
|
+
const padding = " ".repeat(Math.max(0, availableWidth - renderedWidth));
|
|
422
|
+
|
|
423
|
+
lines[cursorLineIndex] =
|
|
424
|
+
`${before}${cursorCell}` +
|
|
425
|
+
`${truncatedText ? `${GHOST_TEXT_STYLE}${truncatedText}${RESET}` : ""}` +
|
|
426
|
+
`${showIndicator ? `${GHOST_INDICATOR_STYLE}${renderedIndicator}${RESET}` : ""}${padding}`;
|
|
427
|
+
return lines;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
refreshFromExternalChange(options: SuggestionRefreshOptions = {}): void {
|
|
431
|
+
this.refreshSuggestion({
|
|
432
|
+
clearExisting: options.clearExisting ?? true,
|
|
433
|
+
immediate: options.immediate ?? true,
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
private makeRequestSubscriberId(seq: number): string {
|
|
438
|
+
return `${this.activationId}:${seq}`;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
private makeSpinnerOwner(request: SuggestionRequest, seq: number): string {
|
|
442
|
+
return `${this.activationId}:${seq}:${request.cacheKey}`;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
private activateSpinner(owner: string): void {
|
|
446
|
+
if (this.activeSpinnerOwner && this.activeSpinnerOwner !== owner) {
|
|
447
|
+
this.shared.setSpinnerActive?.(this.activeSpinnerOwner, false);
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
this.activeSpinnerOwner = owner;
|
|
451
|
+
this.shared.setSpinnerActive?.(owner, true);
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
private deactivateSpinner(owner = this.activeSpinnerOwner): void {
|
|
455
|
+
if (!owner) return;
|
|
456
|
+
this.shared.setSpinnerActive?.(owner, false);
|
|
457
|
+
if (this.activeSpinnerOwner === owner) {
|
|
458
|
+
this.activeSpinnerOwner = undefined;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
private getActiveSuggestion(): string | undefined {
|
|
463
|
+
return this.suggestions[this.suggestionIndex];
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
private setSuggestions(nextSuggestions: string[]): void {
|
|
467
|
+
const currentActive = this.getActiveSuggestion();
|
|
468
|
+
let nextIndex = 0;
|
|
469
|
+
|
|
470
|
+
if (currentActive) {
|
|
471
|
+
const preservedIndex = nextSuggestions.indexOf(currentActive);
|
|
472
|
+
if (preservedIndex !== -1) {
|
|
473
|
+
nextIndex = preservedIndex;
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
if (nextSuggestions.length === 0) {
|
|
478
|
+
nextIndex = 0;
|
|
479
|
+
} else if (nextIndex >= nextSuggestions.length) {
|
|
480
|
+
nextIndex = 0;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
if (arraysEqual(this.suggestions, nextSuggestions) && this.suggestionIndex === nextIndex) {
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
this.suggestions = [...nextSuggestions];
|
|
488
|
+
this.suggestionIndex = nextIndex;
|
|
489
|
+
|
|
490
|
+
if (nextSuggestions.length > 0) {
|
|
491
|
+
updateDebugState(
|
|
492
|
+
this.shared,
|
|
493
|
+
"showing",
|
|
494
|
+
`${nextSuggestions.length} suggestion(s), selected ${nextIndex + 1}/${nextSuggestions.length}`,
|
|
495
|
+
);
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
this.tui.requestRender();
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
private cycleSuggestions(delta: 1 | -1): void {
|
|
502
|
+
if (this.suggestions.length <= 1) return;
|
|
503
|
+
const nextIndex = (this.suggestionIndex + delta + this.suggestions.length) % this.suggestions.length;
|
|
504
|
+
if (nextIndex === this.suggestionIndex) return;
|
|
505
|
+
this.suggestionIndex = nextIndex;
|
|
506
|
+
this.dismissedKey = undefined;
|
|
507
|
+
updateDebugState(this.shared, "cycled", `Now showing ${nextIndex + 1}/${this.suggestions.length}`);
|
|
508
|
+
this.tui.requestRender();
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
// Fires only when CYCLE_NEXT (ctrl+.) is pressed and there is nothing to cycle
|
|
512
|
+
// through, so the same key both advances alternatives and forces a one-shot
|
|
513
|
+
// suggestion (e.g. while the agent is streaming and while-streaming is off).
|
|
514
|
+
private canTriggerManualSuggestion(data: string): boolean {
|
|
515
|
+
if (!this.shared.enabled || this.activationId !== this.shared.activationId) return false;
|
|
516
|
+
if (this.isShowingAutocomplete()) return false;
|
|
517
|
+
return matchesAnyKey(data, CYCLE_NEXT_KEYS);
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
private triggerManualSuggestion(): void {
|
|
521
|
+
// refreshSuggestion immediately sets its own debug state, so we only clear any
|
|
522
|
+
// standing dismissal here and let the refresh report the real outcome.
|
|
523
|
+
this.dismissedKey = undefined;
|
|
524
|
+
this.refreshSuggestion({ clearExisting: true, immediate: true, manual: true });
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
private canDismissInlineSuggestion(data: string): boolean {
|
|
528
|
+
return this.shouldRenderInlineSuggestion() && !!this.getActiveSuggestion() && matchesKey(data, "escape");
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
private canAcceptInlineSuggestion(data: string): boolean {
|
|
532
|
+
return this.shouldRenderInlineSuggestion() && !!this.getActiveSuggestion() && matchesKey(data, "tab");
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
private canAcceptInlineSuggestionByWord(data: string): boolean {
|
|
536
|
+
return this.shouldRenderInlineSuggestion() && !!this.getActiveSuggestion() && matchesAnyKey(data, WORD_ACCEPT_KEYS);
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
private canCycleSuggestions(data: string): boolean {
|
|
540
|
+
if (!this.shouldRenderInlineSuggestion()) return false;
|
|
541
|
+
if (this.suggestions.length <= 1) return false;
|
|
542
|
+
return matchesAnyKey(data, CYCLE_NEXT_KEYS) || matchesAnyKey(data, CYCLE_PREV_KEYS);
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
private clearInlineSuggestion(state: string, details: string): void {
|
|
546
|
+
this.cancelPendingRequest();
|
|
547
|
+
updateDebugState(this.shared, state, details);
|
|
548
|
+
this.setSuggestions([]);
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
private clearInlineSuggestionForUserIntent(data: string): boolean {
|
|
552
|
+
const clearReason = this.getInlineSuggestionClearReason(data);
|
|
553
|
+
if (!clearReason) return false;
|
|
554
|
+
this.clearInlineSuggestion(clearReason.state, clearReason.details);
|
|
555
|
+
return true;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
private getInlineSuggestionClearReason(data: string): { state: string; details: string } | undefined {
|
|
559
|
+
if (!this.getActiveSuggestion()) return undefined;
|
|
560
|
+
|
|
561
|
+
if (NAVIGATION_ACTIONS.some((action) => this.appKeybindings.matches(data, action))) {
|
|
562
|
+
return {
|
|
563
|
+
state: "navigated",
|
|
564
|
+
details: "Suggestion cleared during editor navigation",
|
|
565
|
+
};
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
if (EDIT_ACTIONS.some((action) => this.appKeybindings.matches(data, action))) {
|
|
569
|
+
return {
|
|
570
|
+
state: "editing",
|
|
571
|
+
details: "Suggestion cleared before editor edit command",
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
return undefined;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
private acceptInlineSuggestion(): void {
|
|
579
|
+
const suggestion = this.getActiveSuggestion();
|
|
580
|
+
if (!suggestion) return;
|
|
581
|
+
|
|
582
|
+
this.dismissedKey = undefined;
|
|
583
|
+
this.clearInlineSuggestion("accepted", "Accepted full suggestion");
|
|
584
|
+
super.insertTextAtCursor(suggestion);
|
|
585
|
+
this.refreshSuggestion();
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
private acceptInlineSuggestionByWord(): void {
|
|
589
|
+
const suggestion = this.getActiveSuggestion();
|
|
590
|
+
if (!suggestion) return;
|
|
591
|
+
|
|
592
|
+
const chunk = extractNextSuggestionChunk(suggestion) ?? suggestion;
|
|
593
|
+
if (!chunk) return;
|
|
594
|
+
|
|
595
|
+
this.dismissedKey = undefined;
|
|
596
|
+
this.clearInlineSuggestion("accepted-word", `Accepted chunk: ${chunk}`);
|
|
597
|
+
super.insertTextAtCursor(chunk);
|
|
598
|
+
this.refreshSuggestion();
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
private shouldRenderInlineSuggestion(): boolean {
|
|
602
|
+
return (
|
|
603
|
+
this.shared.enabled &&
|
|
604
|
+
this.activationId === this.shared.activationId &&
|
|
605
|
+
this.suggestions.length > 0 &&
|
|
606
|
+
!this.isShowingAutocomplete() &&
|
|
607
|
+
this.isCursorAtEndOfDraft()
|
|
608
|
+
);
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
private isCursorAtEndOfDraft(): boolean {
|
|
612
|
+
const lines = this.getLines();
|
|
613
|
+
const cursor = this.getCursor();
|
|
614
|
+
if (lines.length === 0) return false;
|
|
615
|
+
if (cursor.line !== lines.length - 1) return false;
|
|
616
|
+
return cursor.col === (lines[cursor.line]?.length ?? 0);
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
private getSuppressionReason(options: { manual?: boolean } = {}): string | undefined {
|
|
620
|
+
if (!this.isCursorAtEndOfDraft()) return "Cursor is not at the end of the draft";
|
|
621
|
+
// A manual one-shot trigger deliberately ignores the noise-reduction gates
|
|
622
|
+
// (streaming gate, post-error cooldown, min-chars). Model/auth and slash/path
|
|
623
|
+
// checks still apply because those can never produce a useful suggestion.
|
|
624
|
+
if (!options.manual) {
|
|
625
|
+
if (!this.shared.config.allowWhileStreaming && this.shared.streaming) {
|
|
626
|
+
return "Waiting for the current agent turn to finish";
|
|
627
|
+
}
|
|
628
|
+
if (this.shared.now() < this.suspendedUntil) return "In temporary cooldown after the last error";
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
const model = resolveSuggestionModel(this.shared);
|
|
632
|
+
if (!model) return "No usable autocomplete model with configured auth was found";
|
|
633
|
+
|
|
634
|
+
const draft = this.getText();
|
|
635
|
+
if (!options.manual && draft.trim().length < this.shared.config.minPromptChars) {
|
|
636
|
+
return `Draft is shorter than min chars (${this.shared.config.minPromptChars})`;
|
|
637
|
+
}
|
|
638
|
+
if (shouldSkipPromptAutocomplete(draft)) {
|
|
639
|
+
return "Draft looks like a slash command or path autocomplete context";
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
return undefined;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
private refreshSuggestion(options: SuggestionRefreshOptions = {}): void {
|
|
646
|
+
if (options.clearExisting) {
|
|
647
|
+
this.cancelPendingRequest();
|
|
648
|
+
this.setSuggestions([]);
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
if (!this.shared.enabled || this.activationId !== this.shared.activationId) {
|
|
652
|
+
this.cancelPendingRequest();
|
|
653
|
+
updateDebugState(this.shared, "inactive");
|
|
654
|
+
this.setSuggestions([]);
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
if (!this.shared.ownsEditor?.()) {
|
|
659
|
+
this.cancelPendingRequest();
|
|
660
|
+
this.shared.editorBlockedReason = "Another extension replaced the prompt-autocomplete editor";
|
|
661
|
+
updateDebugState(this.shared, "ownership-lost", this.shared.editorBlockedReason);
|
|
662
|
+
this.setSuggestions([]);
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
if (this.isShowingAutocomplete()) {
|
|
667
|
+
this.cancelPendingRequest();
|
|
668
|
+
updateDebugState(this.shared, "paused", "Built-in autocomplete is active");
|
|
669
|
+
this.setSuggestions([]);
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
const suppressionReason = this.getSuppressionReason({ manual: options.manual });
|
|
674
|
+
if (suppressionReason) {
|
|
675
|
+
this.cancelPendingRequest();
|
|
676
|
+
updateDebugState(this.shared, "waiting", suppressionReason);
|
|
677
|
+
this.setSuggestions([]);
|
|
678
|
+
return;
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
const request = this.buildRequest();
|
|
682
|
+
if (!request) {
|
|
683
|
+
this.cancelPendingRequest();
|
|
684
|
+
updateDebugState(this.shared, "waiting", "No request could be built");
|
|
685
|
+
this.setSuggestions([]);
|
|
686
|
+
return;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
if (!options.manual && request.cacheKey === this.dismissedKey) {
|
|
690
|
+
this.cancelPendingRequest();
|
|
691
|
+
updateDebugState(this.shared, "dismissed", "Suggestion dismissed for current draft");
|
|
692
|
+
this.setSuggestions([]);
|
|
693
|
+
return;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
const cachedEntry = getCachedRequest(this.shared, request.cacheKey, { bypass: options.manual });
|
|
697
|
+
if (cachedEntry) {
|
|
698
|
+
this.cancelPendingRequest();
|
|
699
|
+
this.shared.lastRawResponse = cachedEntry.rawResponse;
|
|
700
|
+
this.shared.lastError = cachedEntry.error;
|
|
701
|
+
if (cachedEntry.suggestions.length === 0) {
|
|
702
|
+
updateDebugState(this.shared, "cache-hit", cachedEntry.debugState || "Cached no-suggestion result");
|
|
703
|
+
}
|
|
704
|
+
this.setSuggestions(cachedEntry.suggestions);
|
|
705
|
+
return;
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
if (this.pendingRequests.current?.key === request.cacheKey) {
|
|
709
|
+
updateDebugState(this.shared, "requesting", `Awaiting pending request for ${request.modelLabel}`);
|
|
710
|
+
return;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
const shouldJoinInFlight = this.shared.inFlightRequests.has(request.cacheKey);
|
|
714
|
+
this.cancelPendingRequest();
|
|
715
|
+
|
|
716
|
+
const seq = ++this.requestSeq;
|
|
717
|
+
const spinnerOwner = this.makeSpinnerOwner(request, seq);
|
|
718
|
+
this.pendingRequests.set({ key: request.cacheKey, seq, spinnerOwner });
|
|
719
|
+
this.activateSpinner(spinnerOwner);
|
|
720
|
+
|
|
721
|
+
const debounceMs = shouldJoinInFlight || options.immediate ? 0 : this.shared.config.debounceMs;
|
|
722
|
+
if (debounceMs <= 0) {
|
|
723
|
+
updateDebugState(
|
|
724
|
+
this.shared,
|
|
725
|
+
"requesting",
|
|
726
|
+
shouldJoinInFlight
|
|
727
|
+
? `Joining in-flight request for ${request.modelLabel}`
|
|
728
|
+
: `Immediate request to ${request.modelLabel}`,
|
|
729
|
+
);
|
|
730
|
+
void this.fetchSuggestion(request, seq, spinnerOwner);
|
|
731
|
+
return;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
updateDebugState(this.shared, "debouncing", `${debounceMs}ms before request to ${request.modelLabel}`);
|
|
735
|
+
this.debounceTimer = setTimeout(() => {
|
|
736
|
+
this.debounceTimer = undefined;
|
|
737
|
+
void this.fetchSuggestion(request, seq, spinnerOwner);
|
|
738
|
+
}, debounceMs);
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
private buildRequest(): SuggestionRequest | undefined {
|
|
742
|
+
const model = resolveSuggestionModel(this.shared);
|
|
743
|
+
if (!model) return undefined;
|
|
744
|
+
|
|
745
|
+
const draft = this.getText();
|
|
746
|
+
const branch = this.shared.sessionManager?.getBranch?.() ?? [];
|
|
747
|
+
const latestAssistantContext = buildLatestAssistantMessageContext(branch);
|
|
748
|
+
const latestUserContext = buildLatestUserMessageContext(branch);
|
|
749
|
+
const recentContext = buildRecentConversationContext(branch);
|
|
750
|
+
const draftTail = truncateDraftTail(draft, MAX_DRAFT_CONTEXT_CHARS);
|
|
751
|
+
const modelLabel = formatModelLabel(model);
|
|
752
|
+
const leafId = this.shared.sessionManager?.getLeafId?.() ?? "";
|
|
753
|
+
|
|
754
|
+
return {
|
|
755
|
+
activationId: this.activationId,
|
|
756
|
+
draft,
|
|
757
|
+
draftTail,
|
|
758
|
+
model,
|
|
759
|
+
modelLabel,
|
|
760
|
+
cacheKey: buildPromptAutocompleteCacheKey({
|
|
761
|
+
leafId,
|
|
762
|
+
modelLabel,
|
|
763
|
+
maxAlternatives: this.shared.config.maxAlternatives,
|
|
764
|
+
maxSuggestionChars: this.shared.config.maxSuggestionChars,
|
|
765
|
+
draft,
|
|
766
|
+
latestAssistantContext,
|
|
767
|
+
latestUserContext,
|
|
768
|
+
recentContext,
|
|
769
|
+
}),
|
|
770
|
+
maxAlternatives: this.shared.config.maxAlternatives,
|
|
771
|
+
latestAssistantContext,
|
|
772
|
+
latestUserContext,
|
|
773
|
+
recentContext,
|
|
774
|
+
};
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
private async fetchSuggestion(request: SuggestionRequest, seq: number, spinnerOwner: string): Promise<void> {
|
|
778
|
+
if (!this.isRequestStillCurrent(request, seq)) {
|
|
779
|
+
this.clearPendingRequestIfOwned(seq);
|
|
780
|
+
this.deactivateSpinner(spinnerOwner);
|
|
781
|
+
return;
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
const subscriberId = this.makeRequestSubscriberId(seq);
|
|
785
|
+
const subscription = acquireCoalescedRequest(
|
|
786
|
+
this.shared.inFlightRequests,
|
|
787
|
+
request.cacheKey,
|
|
788
|
+
subscriberId,
|
|
789
|
+
(signal) => this.fetchSuggestionUncached(request, signal),
|
|
790
|
+
);
|
|
791
|
+
|
|
792
|
+
this.activeRequestSubscription = subscription;
|
|
793
|
+
updateDebugState(
|
|
794
|
+
this.shared,
|
|
795
|
+
"requesting",
|
|
796
|
+
subscription.created
|
|
797
|
+
? `Requesting suggestions from ${request.modelLabel}`
|
|
798
|
+
: `Awaiting shared in-flight request for ${request.modelLabel}`,
|
|
799
|
+
);
|
|
800
|
+
|
|
801
|
+
try {
|
|
802
|
+
const entry = await subscription.promise;
|
|
803
|
+
if (!this.isRequestStillCurrent(request, seq)) {
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
this.shared.lastRawResponse = entry.rawResponse;
|
|
808
|
+
this.shared.lastError = entry.error;
|
|
809
|
+
|
|
810
|
+
if (entry.suggestions.length === 0) {
|
|
811
|
+
updateDebugState(this.shared, "no-suggestion", entry.debugState || "No usable suggestions");
|
|
812
|
+
}
|
|
813
|
+
if (request.cacheKey !== this.dismissedKey) {
|
|
814
|
+
this.setSuggestions(entry.suggestions);
|
|
815
|
+
}
|
|
816
|
+
} catch (error) {
|
|
817
|
+
if (this.isRequestStillCurrent(request, seq)) {
|
|
818
|
+
this.suspendedUntil = this.shared.now() + FAILURE_COOLDOWN_MS;
|
|
819
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
820
|
+
this.shared.lastError = message;
|
|
821
|
+
updateDebugState(this.shared, "error", message);
|
|
822
|
+
this.setSuggestions([]);
|
|
823
|
+
}
|
|
824
|
+
} finally {
|
|
825
|
+
subscription.release();
|
|
826
|
+
if (this.activeRequestSubscription === subscription) {
|
|
827
|
+
this.activeRequestSubscription = undefined;
|
|
828
|
+
}
|
|
829
|
+
this.clearPendingRequestIfOwned(seq);
|
|
830
|
+
this.deactivateSpinner(spinnerOwner);
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
private async fetchSuggestionUncached(
|
|
835
|
+
request: SuggestionRequest,
|
|
836
|
+
signal: AbortSignal,
|
|
837
|
+
): Promise<PromptAutocompleteCacheEntry> {
|
|
838
|
+
if (!this.shared.modelRegistry) {
|
|
839
|
+
throw new Error("No model registry available");
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
const auth = await this.shared.modelRegistry.getApiKeyAndHeaders(request.model);
|
|
843
|
+
if (!auth.ok || !auth.apiKey) {
|
|
844
|
+
throw new Error(auth.ok ? `No API key for ${request.modelLabel}` : auth.error);
|
|
845
|
+
}
|
|
846
|
+
if (signal.aborted) {
|
|
847
|
+
throw new Error("Request was aborted");
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
const sections: string[] = [];
|
|
851
|
+
if (request.latestAssistantContext) {
|
|
852
|
+
sections.push(`Latest assistant message (primary context):\n${request.latestAssistantContext}`);
|
|
853
|
+
}
|
|
854
|
+
if (request.latestUserContext) {
|
|
855
|
+
sections.push(`Latest user message:\n${request.latestUserContext}`);
|
|
856
|
+
}
|
|
857
|
+
if (request.recentContext) {
|
|
858
|
+
sections.push(`Recent conversation summary:\n${request.recentContext}`);
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
if (request.draft.length === 0) {
|
|
862
|
+
sections.push("Current draft is empty.");
|
|
863
|
+
sections.push(
|
|
864
|
+
[
|
|
865
|
+
`Task: propose up to ${request.maxAlternatives} ranked full next prompts the user could send now.`,
|
|
866
|
+
"Each item must be a complete next prompt, not a continuation fragment.",
|
|
867
|
+
"Suggest the prompt most likely to move the overall project forward.",
|
|
868
|
+
"Prefer 3-10 words when possible.",
|
|
869
|
+
].join("\n"),
|
|
870
|
+
);
|
|
871
|
+
} else {
|
|
872
|
+
if (request.draftTail.length < request.draft.length) {
|
|
873
|
+
sections.push(
|
|
874
|
+
`Current draft tail (the real draft is longer; the cursor is at the end of the full draft):\n${request.draftTail}`,
|
|
875
|
+
);
|
|
876
|
+
} else {
|
|
877
|
+
sections.push(`Current draft (cursor at end):\n${request.draft}`);
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
sections.push(
|
|
881
|
+
[
|
|
882
|
+
`Task: propose up to ${request.maxAlternatives} ranked continuations to insert at the cursor.`,
|
|
883
|
+
"Each item must be only the text after the cursor; never restate text the user already typed.",
|
|
884
|
+
"If the draft ends inside a partially typed word, complete that word directly without a leading space.",
|
|
885
|
+
].join("\n"),
|
|
886
|
+
);
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
const userMessage: UserMessage = {
|
|
890
|
+
role: "user",
|
|
891
|
+
content: [{ type: "text", text: sections.join("\n\n") }],
|
|
892
|
+
timestamp: Date.now(),
|
|
893
|
+
};
|
|
894
|
+
|
|
895
|
+
const response = await this.shared.completeSimple(
|
|
896
|
+
request.model,
|
|
897
|
+
{
|
|
898
|
+
systemPrompt: PROMPT_AUTOCOMPLETE_SYSTEM_PROMPT,
|
|
899
|
+
messages: [userMessage],
|
|
900
|
+
},
|
|
901
|
+
{
|
|
902
|
+
apiKey: auth.apiKey,
|
|
903
|
+
headers: auth.headers,
|
|
904
|
+
signal,
|
|
905
|
+
maxTokens: computeRequestMaxTokens(request.maxAlternatives, this.shared.config.maxSuggestionChars),
|
|
906
|
+
timeoutMs: REQUEST_TIMEOUT_MS,
|
|
907
|
+
maxRetries: REQUEST_MAX_RETRIES,
|
|
908
|
+
maxRetryDelayMs: REQUEST_MAX_RETRY_DELAY_MS,
|
|
909
|
+
},
|
|
910
|
+
);
|
|
911
|
+
|
|
912
|
+
const contentTypes = response.content.map((block) => block.type).join(", ") || "(none)";
|
|
913
|
+
const text = response.content
|
|
914
|
+
.filter((block): block is { type: "text"; text: string } => block.type === "text")
|
|
915
|
+
.map((block) => block.text)
|
|
916
|
+
.join("");
|
|
917
|
+
|
|
918
|
+
const responseError = response.errorMessage?.trim();
|
|
919
|
+
const rawResponse = text || responseError || `[types=${contentTypes}; stopReason=${response.stopReason}]`;
|
|
920
|
+
|
|
921
|
+
if (response.stopReason === "error" || response.stopReason === "aborted") {
|
|
922
|
+
throw new Error(responseError || `Provider returned stopReason=${response.stopReason}`);
|
|
923
|
+
}
|
|
924
|
+
if (signal.aborted) {
|
|
925
|
+
throw new Error("Request was aborted");
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
const normalized = normalizePromptSuggestions(
|
|
929
|
+
request.draft,
|
|
930
|
+
text,
|
|
931
|
+
this.shared.config.maxSuggestionChars,
|
|
932
|
+
request.maxAlternatives,
|
|
933
|
+
);
|
|
934
|
+
|
|
935
|
+
const debugState =
|
|
936
|
+
normalized.length === 0
|
|
937
|
+
? text || `No text blocks returned (types: ${contentTypes}; stopReason: ${response.stopReason})`
|
|
938
|
+
: `${normalized.length} suggestion(s) ready`;
|
|
939
|
+
|
|
940
|
+
return storeCachedRequest(this.shared, request.cacheKey, {
|
|
941
|
+
suggestions: normalized,
|
|
942
|
+
rawResponse,
|
|
943
|
+
debugState,
|
|
944
|
+
});
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
private isRequestStillCurrent(request: SuggestionRequest, seq: number): boolean {
|
|
948
|
+
if (!this.shared.enabled) return false;
|
|
949
|
+
if (!this.shared.ownsEditor?.()) return false;
|
|
950
|
+
if (this.activationId !== this.shared.activationId) return false;
|
|
951
|
+
if (seq !== this.requestSeq) return false;
|
|
952
|
+
if (request.activationId !== this.activationId) return false;
|
|
953
|
+
if (!this.isCursorAtEndOfDraft()) return false;
|
|
954
|
+
if (this.getText() !== request.draft) return false;
|
|
955
|
+
if (this.isShowingAutocomplete()) return false;
|
|
956
|
+
|
|
957
|
+
const currentModel = resolveSuggestionModel(this.shared);
|
|
958
|
+
return formatModelLabel(currentModel) === request.modelLabel;
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
cancelActiveRequest(): void {
|
|
962
|
+
this.cancelPendingRequest();
|
|
963
|
+
this.setSuggestions([]);
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
private clearPendingRequestIfOwned(seq: number): void {
|
|
967
|
+
this.pendingRequests.clearIfOwned(seq);
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
private cancelPendingRequest(): void {
|
|
971
|
+
this.requestSeq += 1;
|
|
972
|
+
|
|
973
|
+
if (this.debounceTimer) {
|
|
974
|
+
clearTimeout(this.debounceTimer);
|
|
975
|
+
this.debounceTimer = undefined;
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
const pending = this.pendingRequests.take();
|
|
979
|
+
const subscription = this.activeRequestSubscription;
|
|
980
|
+
this.activeRequestSubscription = undefined;
|
|
981
|
+
subscription?.release();
|
|
982
|
+
this.deactivateSpinner(pending?.spinnerOwner);
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
function releaseEditorRuntime(shared: PromptAutocompleteSharedState): void {
|
|
987
|
+
shared.cancelActiveRequest?.();
|
|
988
|
+
shared.activationId += 1;
|
|
989
|
+
cancelAllCoalescedRequests(shared.inFlightRequests);
|
|
990
|
+
shared.clearSpinner?.();
|
|
991
|
+
clearDebugUi(shared);
|
|
992
|
+
shared.refreshEditor = undefined;
|
|
993
|
+
shared.cancelActiveRequest = undefined;
|
|
994
|
+
shared.setStatusText = undefined;
|
|
995
|
+
shared.setSpinnerActive = undefined;
|
|
996
|
+
shared.clearSpinner = undefined;
|
|
997
|
+
shared.ownsEditor = undefined;
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
function mountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): boolean {
|
|
1001
|
+
if (ctx.mode !== "tui") return false;
|
|
1002
|
+
|
|
1003
|
+
if (shared.editorMount) {
|
|
1004
|
+
if (shared.ownsEditor?.()) return true;
|
|
1005
|
+
releaseEditorRuntime(shared);
|
|
1006
|
+
shared.editorMount = undefined;
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
const previousFactory = ctx.ui.getEditorComponent();
|
|
1010
|
+
if (previousFactory) {
|
|
1011
|
+
const reason = "Another custom editor is already active; prompt autocomplete did not replace it";
|
|
1012
|
+
const shouldNotify = shared.editorBlockedReason !== reason;
|
|
1013
|
+
shared.editorBlockedReason = reason;
|
|
1014
|
+
updateDebugState(shared, "blocked-custom-editor", reason);
|
|
1015
|
+
if (shouldNotify) ctx.ui.notify(reason, "warning");
|
|
1016
|
+
return false;
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
shared.editorBlockedReason = undefined;
|
|
1020
|
+
shared.activationId += 1;
|
|
1021
|
+
const activationId = shared.activationId;
|
|
1022
|
+
shared.setStatusText = (text) => {
|
|
1023
|
+
ctx.ui.setWidget(
|
|
1024
|
+
"prompt-autocomplete-debug",
|
|
1025
|
+
shared.config.debug && text ? [`PA ${text}`] : undefined,
|
|
1026
|
+
{ placement: "belowEditor" },
|
|
1027
|
+
);
|
|
1028
|
+
};
|
|
1029
|
+
|
|
1030
|
+
let spinnerFrame = 0;
|
|
1031
|
+
let spinnerTimer: ReturnType<typeof setInterval> | undefined;
|
|
1032
|
+
// Mount-scoped owner refcount: multiple request subscribers can share one
|
|
1033
|
+
// spinner, while clearSpinner resets all ownership during unmount/remount.
|
|
1034
|
+
const spinnerOwners = createOwnerRefCounter();
|
|
1035
|
+
const renderSpinner = () => {
|
|
1036
|
+
const frame = SPINNER_FRAMES[spinnerFrame % SPINNER_FRAMES.length];
|
|
1037
|
+
ctx.ui.setWidget(
|
|
1038
|
+
"prompt-autocomplete-spinner",
|
|
1039
|
+
[`${GHOST_INDICATOR_STYLE}${frame} ${SPINNER_LABEL}…${RESET}`],
|
|
1040
|
+
{ placement: "belowEditor" },
|
|
1041
|
+
);
|
|
1042
|
+
};
|
|
1043
|
+
const clearSpinnerWidget = () => {
|
|
1044
|
+
ctx.ui.setWidget("prompt-autocomplete-spinner", undefined, { placement: "belowEditor" });
|
|
1045
|
+
};
|
|
1046
|
+
const stopSpinnerTimer = () => {
|
|
1047
|
+
if (spinnerTimer) {
|
|
1048
|
+
clearInterval(spinnerTimer);
|
|
1049
|
+
spinnerTimer = undefined;
|
|
1050
|
+
}
|
|
1051
|
+
clearSpinnerWidget();
|
|
1052
|
+
};
|
|
1053
|
+
shared.setSpinnerActive = (owner, active) => {
|
|
1054
|
+
if (active) {
|
|
1055
|
+
spinnerOwners.activate(owner);
|
|
1056
|
+
if (spinnerTimer) return;
|
|
1057
|
+
spinnerFrame = 0;
|
|
1058
|
+
renderSpinner();
|
|
1059
|
+
spinnerTimer = setInterval(() => {
|
|
1060
|
+
spinnerFrame = (spinnerFrame + 1) % SPINNER_FRAMES.length;
|
|
1061
|
+
renderSpinner();
|
|
1062
|
+
}, SPINNER_INTERVAL_MS);
|
|
1063
|
+
return;
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
if (!spinnerOwners.deactivate(owner)) return;
|
|
1067
|
+
stopSpinnerTimer();
|
|
1068
|
+
};
|
|
1069
|
+
shared.clearSpinner = () => {
|
|
1070
|
+
spinnerOwners.clear();
|
|
1071
|
+
stopSpinnerTimer();
|
|
1072
|
+
};
|
|
1073
|
+
|
|
1074
|
+
const installedFactory: EditorFactory = (tui, theme, keybindings) => {
|
|
1075
|
+
const editor = new PromptAutocompleteEditor(tui, theme, keybindings, shared, activationId);
|
|
1076
|
+
shared.refreshEditor = (options) => {
|
|
1077
|
+
if (activationId !== shared.activationId) return;
|
|
1078
|
+
editor.refreshFromExternalChange(options);
|
|
1079
|
+
};
|
|
1080
|
+
shared.cancelActiveRequest = () => {
|
|
1081
|
+
if (activationId !== shared.activationId) return;
|
|
1082
|
+
editor.cancelActiveRequest();
|
|
1083
|
+
};
|
|
1084
|
+
return editor;
|
|
1085
|
+
};
|
|
1086
|
+
|
|
1087
|
+
shared.editorMount = { previousFactory, installedFactory };
|
|
1088
|
+
shared.ownsEditor = () => ctx.ui.getEditorComponent() === installedFactory;
|
|
1089
|
+
|
|
1090
|
+
try {
|
|
1091
|
+
ctx.ui.setEditorComponent(installedFactory);
|
|
1092
|
+
} catch (error) {
|
|
1093
|
+
releaseEditorRuntime(shared);
|
|
1094
|
+
shared.editorMount = undefined;
|
|
1095
|
+
throw error;
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
updateDebugState(shared, "mounted", "Editor extension attached");
|
|
1099
|
+
return true;
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
function unmountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): void {
|
|
1103
|
+
const mount = shared.editorMount;
|
|
1104
|
+
const shouldRestore = ctx.mode === "tui" && !!mount && ctx.ui.getEditorComponent() === mount.installedFactory;
|
|
1105
|
+
|
|
1106
|
+
releaseEditorRuntime(shared);
|
|
1107
|
+
shared.editorMount = undefined;
|
|
1108
|
+
shared.editorBlockedReason = undefined;
|
|
1109
|
+
|
|
1110
|
+
if (shouldRestore && mount) {
|
|
1111
|
+
ctx.ui.setEditorComponent(mount.previousFactory);
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
function resetSharedForSession(pi: ExtensionAPI, shared: PromptAutocompleteSharedState): void {
|
|
1116
|
+
shared.cancelActiveRequest?.();
|
|
1117
|
+
shared.cancelActiveRequest = undefined;
|
|
1118
|
+
shared.enabled = pi.getFlag("prompt-autocomplete") === true;
|
|
1119
|
+
shared.config = parseConfig(pi);
|
|
1120
|
+
shared.editorMount = undefined;
|
|
1121
|
+
shared.editorBlockedReason = undefined;
|
|
1122
|
+
shared.ownsEditor = undefined;
|
|
1123
|
+
shared.lastError = undefined;
|
|
1124
|
+
shared.lastRawResponse = undefined;
|
|
1125
|
+
shared.requestCache.clear();
|
|
1126
|
+
cancelAllCoalescedRequests(shared.inFlightRequests);
|
|
1127
|
+
shared.debugState = shared.enabled ? "configured" : "disabled";
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
function bindRuntimeContext(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): void {
|
|
1131
|
+
shared.currentModel = ctx.model as Model<Api> | undefined;
|
|
1132
|
+
shared.modelRegistry = ctx.modelRegistry;
|
|
1133
|
+
shared.sessionManager = ctx.sessionManager;
|
|
1134
|
+
shared.streaming = false;
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
function refreshEditorImmediately(shared: PromptAutocompleteSharedState, state: string, details: string): void {
|
|
1138
|
+
updateDebugState(shared, state, details);
|
|
1139
|
+
shared.refreshEditor?.({ clearExisting: true, immediate: true });
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
function setDebugDisplay(shared: PromptAutocompleteSharedState, enabled: boolean): void {
|
|
1143
|
+
shared.config.debug = enabled;
|
|
1144
|
+
if (enabled) {
|
|
1145
|
+
updateDebugState(shared, shared.debugState || "ready");
|
|
1146
|
+
} else {
|
|
1147
|
+
clearDebugUi(shared);
|
|
1148
|
+
}
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
function setWhileStreaming(
|
|
1152
|
+
ctx: ExtensionContext,
|
|
1153
|
+
shared: PromptAutocompleteSharedState,
|
|
1154
|
+
arg: string | undefined,
|
|
1155
|
+
): void {
|
|
1156
|
+
let next: boolean;
|
|
1157
|
+
if (arg === "on") {
|
|
1158
|
+
next = true;
|
|
1159
|
+
} else if (arg === "off") {
|
|
1160
|
+
next = false;
|
|
1161
|
+
} else if (arg === undefined || arg === "toggle") {
|
|
1162
|
+
next = !shared.config.allowWhileStreaming;
|
|
1163
|
+
} else {
|
|
1164
|
+
ctx.ui.notify("Usage: /prompt-autocomplete while-streaming [on|off|toggle]", "warning");
|
|
1165
|
+
return;
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
shared.config.allowWhileStreaming = next;
|
|
1169
|
+
ctx.ui.notify(`Prompt autocomplete while-streaming ${next ? "enabled" : "disabled"}`, "info");
|
|
1170
|
+
|
|
1171
|
+
if (shared.enabled) {
|
|
1172
|
+
// Only label it "waiting" when disabling actually suppresses right now (agent
|
|
1173
|
+
// streaming); otherwise the refresh below requests suggestions immediately.
|
|
1174
|
+
const willSuppress = !next && shared.streaming;
|
|
1175
|
+
refreshEditorImmediately(shared, willSuppress ? "waiting" : "ready", `While-streaming ${next ? "enabled" : "disabled"}`);
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
function enablePromptAutocomplete(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): boolean {
|
|
1180
|
+
shared.enabled = true;
|
|
1181
|
+
return mountEditor(ctx, shared);
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
function disablePromptAutocomplete(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): void {
|
|
1185
|
+
shared.enabled = false;
|
|
1186
|
+
unmountEditor(ctx, shared);
|
|
1187
|
+
shared.requestCache.clear();
|
|
1188
|
+
shared.lastRawResponse = undefined;
|
|
1189
|
+
shared.lastError = undefined;
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
function notifyPromptAutocompleteEnabled(
|
|
1193
|
+
ctx: ExtensionContext,
|
|
1194
|
+
shared: PromptAutocompleteSharedState,
|
|
1195
|
+
options: { includeModel: boolean },
|
|
1196
|
+
): void {
|
|
1197
|
+
const keyHint =
|
|
1198
|
+
`Tab accepts all, ${formatPrimaryKey(WORD_ACCEPT_KEYS)} accepts one word, ` +
|
|
1199
|
+
`${formatPrimaryKey(CYCLE_PREV_KEYS)}/${formatPrimaryKey(CYCLE_NEXT_KEYS)} cycle alternatives, ` +
|
|
1200
|
+
`${formatPrimaryKey(CYCLE_NEXT_KEYS)} also forces a one-shot suggestion when none is shown (even while the agent works).`;
|
|
1201
|
+
const resolvedModel = resolveSuggestionModel(shared);
|
|
1202
|
+
const privacyNotice = "Requests send the current draft and recent conversation context to the selected model and may incur provider usage.";
|
|
1203
|
+
|
|
1204
|
+
if (options.includeModel) {
|
|
1205
|
+
if (resolvedModel) {
|
|
1206
|
+
ctx.ui.notify(
|
|
1207
|
+
`Prompt autocomplete enabled. ${keyHint} Model: ${formatModelLabel(resolvedModel)} ${privacyNotice}`,
|
|
1208
|
+
"info",
|
|
1209
|
+
);
|
|
1210
|
+
} else {
|
|
1211
|
+
ctx.ui.notify(
|
|
1212
|
+
"Prompt autocomplete enabled, but no usable model/auth is configured yet. Select a model or configure auth first.",
|
|
1213
|
+
"warning",
|
|
1214
|
+
);
|
|
1215
|
+
}
|
|
1216
|
+
return;
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
ctx.ui.notify(`Prompt autocomplete enabled. ${keyHint} ${privacyNotice}`, "info");
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
function createPromptAutocompleteCommandHandlers(
|
|
1223
|
+
ctx: ExtensionContext,
|
|
1224
|
+
shared: PromptAutocompleteSharedState,
|
|
1225
|
+
): Record<string, () => void> {
|
|
1226
|
+
return {
|
|
1227
|
+
status: () => {
|
|
1228
|
+
ctx.ui.notify(formatStatus(shared), "info");
|
|
1229
|
+
},
|
|
1230
|
+
"debug-on": () => {
|
|
1231
|
+
setDebugDisplay(shared, true);
|
|
1232
|
+
ctx.ui.notify("Prompt autocomplete debug display enabled", "info");
|
|
1233
|
+
},
|
|
1234
|
+
"debug-off": () => {
|
|
1235
|
+
setDebugDisplay(shared, false);
|
|
1236
|
+
ctx.ui.notify("Prompt autocomplete debug display disabled", "info");
|
|
1237
|
+
},
|
|
1238
|
+
"debug-toggle": () => {
|
|
1239
|
+
const nextDebugEnabled = !shared.config.debug;
|
|
1240
|
+
setDebugDisplay(shared, nextDebugEnabled);
|
|
1241
|
+
ctx.ui.notify(
|
|
1242
|
+
nextDebugEnabled
|
|
1243
|
+
? "Prompt autocomplete debug display enabled"
|
|
1244
|
+
: "Prompt autocomplete debug display disabled",
|
|
1245
|
+
"info",
|
|
1246
|
+
);
|
|
1247
|
+
},
|
|
1248
|
+
on: () => {
|
|
1249
|
+
if (shared.enabled && shared.ownsEditor?.()) {
|
|
1250
|
+
ctx.ui.notify(`Prompt autocomplete already enabled (${formatStatus(shared)})`, "info");
|
|
1251
|
+
return;
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
if (enablePromptAutocomplete(ctx, shared)) {
|
|
1255
|
+
notifyPromptAutocompleteEnabled(ctx, shared, { includeModel: true });
|
|
1256
|
+
}
|
|
1257
|
+
},
|
|
1258
|
+
off: () => {
|
|
1259
|
+
if (!shared.enabled) {
|
|
1260
|
+
ctx.ui.notify("Prompt autocomplete is already disabled", "info");
|
|
1261
|
+
return;
|
|
1262
|
+
}
|
|
1263
|
+
|
|
1264
|
+
disablePromptAutocomplete(ctx, shared);
|
|
1265
|
+
ctx.ui.notify("Prompt autocomplete disabled", "info");
|
|
1266
|
+
},
|
|
1267
|
+
toggle: () => {
|
|
1268
|
+
if (shared.enabled) {
|
|
1269
|
+
disablePromptAutocomplete(ctx, shared);
|
|
1270
|
+
ctx.ui.notify("Prompt autocomplete disabled", "info");
|
|
1271
|
+
return;
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
if (enablePromptAutocomplete(ctx, shared)) {
|
|
1275
|
+
notifyPromptAutocompleteEnabled(ctx, shared, { includeModel: false });
|
|
1276
|
+
}
|
|
1277
|
+
},
|
|
1278
|
+
};
|
|
1279
|
+
}
|
|
1280
|
+
|
|
1281
|
+
export function createPromptAutocompleteExtension(
|
|
1282
|
+
dependencies: PromptAutocompleteDependencies = {},
|
|
1283
|
+
): (pi: ExtensionAPI) => void {
|
|
1284
|
+
const completeSimpleImpl = dependencies.completeSimple ?? completeSimple;
|
|
1285
|
+
const now = dependencies.now ?? Date.now;
|
|
1286
|
+
|
|
1287
|
+
return function promptAutocompleteExtension(pi: ExtensionAPI): void {
|
|
1288
|
+
pi.registerFlag("prompt-autocomplete", {
|
|
1289
|
+
description: "Enable inline AI prompt autocomplete in the editor",
|
|
1290
|
+
type: "boolean",
|
|
1291
|
+
default: DEFAULT_PROMPT_AUTOCOMPLETE_ENABLED,
|
|
1292
|
+
});
|
|
1293
|
+
pi.registerFlag("prompt-autocomplete-model", {
|
|
1294
|
+
description: "Optional provider/model override for prompt autocomplete, e.g. openai/gpt-5.4-mini",
|
|
1295
|
+
type: "string",
|
|
1296
|
+
default: DEFAULT_PREFERRED_MODEL,
|
|
1297
|
+
});
|
|
1298
|
+
pi.registerFlag("prompt-autocomplete-while-streaming", {
|
|
1299
|
+
description: "Allow prompt autocomplete while the main agent is still working",
|
|
1300
|
+
type: "boolean",
|
|
1301
|
+
default: false,
|
|
1302
|
+
});
|
|
1303
|
+
pi.registerFlag("prompt-autocomplete-debug", {
|
|
1304
|
+
description: "Show prompt autocomplete debug state below the editor",
|
|
1305
|
+
type: "boolean",
|
|
1306
|
+
default: false,
|
|
1307
|
+
});
|
|
1308
|
+
pi.registerFlag("prompt-autocomplete-debounce-ms", {
|
|
1309
|
+
description: "Debounce in ms before requesting a prompt completion",
|
|
1310
|
+
type: "string",
|
|
1311
|
+
default: String(DEFAULT_DEBOUNCE_MS),
|
|
1312
|
+
});
|
|
1313
|
+
pi.registerFlag("prompt-autocomplete-min-chars", {
|
|
1314
|
+
description: "Minimum prompt length before autocomplete activates",
|
|
1315
|
+
type: "string",
|
|
1316
|
+
default: String(DEFAULT_MIN_PROMPT_CHARS),
|
|
1317
|
+
});
|
|
1318
|
+
pi.registerFlag("prompt-autocomplete-max-chars", {
|
|
1319
|
+
description: "Maximum characters to accept from one prompt completion",
|
|
1320
|
+
type: "string",
|
|
1321
|
+
default: String(DEFAULT_MAX_SUGGESTION_CHARS),
|
|
1322
|
+
});
|
|
1323
|
+
pi.registerFlag("prompt-autocomplete-max-alternatives", {
|
|
1324
|
+
description: "Maximum number of inline suggestion alternatives to keep (1-5)",
|
|
1325
|
+
type: "string",
|
|
1326
|
+
default: String(DEFAULT_MAX_ALTERNATIVES),
|
|
1327
|
+
});
|
|
1328
|
+
|
|
1329
|
+
const shared: PromptAutocompleteSharedState = {
|
|
1330
|
+
enabled: false,
|
|
1331
|
+
activationId: 0,
|
|
1332
|
+
streaming: false,
|
|
1333
|
+
config: parseConfig(pi),
|
|
1334
|
+
completeSimple: completeSimpleImpl,
|
|
1335
|
+
now,
|
|
1336
|
+
debugState: "idle",
|
|
1337
|
+
requestCache: new ExpiringLruCache(REQUEST_CACHE_TTL_MS, REQUEST_CACHE_MAX_ENTRIES, now),
|
|
1338
|
+
inFlightRequests: new Map(),
|
|
1339
|
+
};
|
|
1340
|
+
|
|
1341
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
1342
|
+
if (shared.editorMount) {
|
|
1343
|
+
unmountEditor(ctx, shared);
|
|
1344
|
+
}
|
|
1345
|
+
resetSharedForSession(pi, shared);
|
|
1346
|
+
bindRuntimeContext(ctx, shared);
|
|
1347
|
+
|
|
1348
|
+
if (ctx.mode !== "tui" || !shared.enabled) return;
|
|
1349
|
+
mountEditor(ctx, shared);
|
|
1350
|
+
});
|
|
1351
|
+
|
|
1352
|
+
pi.on("session_shutdown", async (_event, ctx) => {
|
|
1353
|
+
shared.enabled = false;
|
|
1354
|
+
shared.cancelActiveRequest?.();
|
|
1355
|
+
shared.requestCache.clear();
|
|
1356
|
+
cancelAllCoalescedRequests(shared.inFlightRequests);
|
|
1357
|
+
unmountEditor(ctx, shared);
|
|
1358
|
+
});
|
|
1359
|
+
|
|
1360
|
+
pi.on("model_select", async (event, ctx) => {
|
|
1361
|
+
shared.currentModel = event.model as Model<Api>;
|
|
1362
|
+
shared.modelRegistry = ctx.modelRegistry;
|
|
1363
|
+
if (!shared.enabled) return;
|
|
1364
|
+
refreshEditorImmediately(shared, "model-changed", formatModelLabel(event.model as Model<Api>));
|
|
1365
|
+
});
|
|
1366
|
+
|
|
1367
|
+
pi.on("agent_start", async () => {
|
|
1368
|
+
shared.streaming = true;
|
|
1369
|
+
if (!shared.enabled || shared.config.allowWhileStreaming) return;
|
|
1370
|
+
refreshEditorImmediately(shared, "waiting", "Main agent is still working");
|
|
1371
|
+
});
|
|
1372
|
+
|
|
1373
|
+
pi.on("agent_end", async () => {
|
|
1374
|
+
shared.streaming = false;
|
|
1375
|
+
if (!shared.enabled) return;
|
|
1376
|
+
refreshEditorImmediately(shared, "ready", "Agent finished; autocomplete can request suggestions again");
|
|
1377
|
+
});
|
|
1378
|
+
|
|
1379
|
+
pi.registerCommand("prompt-autocomplete", {
|
|
1380
|
+
description: "Enable, disable, or inspect inline prompt autocomplete",
|
|
1381
|
+
handler: async (args, ctx) => {
|
|
1382
|
+
if (ctx.mode !== "tui") {
|
|
1383
|
+
ctx.ui.notify("prompt-autocomplete requires interactive TUI mode", "warning");
|
|
1384
|
+
return;
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
const parts = args.trim().toLowerCase().split(/\s+/).filter(Boolean);
|
|
1388
|
+
const command = parts[0] || "status";
|
|
1389
|
+
|
|
1390
|
+
if (command === "while-streaming") {
|
|
1391
|
+
setWhileStreaming(ctx, shared, parts[1]);
|
|
1392
|
+
return;
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
const handlers = createPromptAutocompleteCommandHandlers(ctx, shared);
|
|
1396
|
+
const handler = handlers[command];
|
|
1397
|
+
|
|
1398
|
+
if (handler) {
|
|
1399
|
+
handler();
|
|
1400
|
+
return;
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
ctx.ui.notify(
|
|
1404
|
+
"Usage: /prompt-autocomplete [on|off|toggle|status|while-streaming on|off|toggle|debug-on|debug-off|debug-toggle]",
|
|
1405
|
+
"warning",
|
|
1406
|
+
);
|
|
1407
|
+
},
|
|
1408
|
+
});
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
export default createPromptAutocompleteExtension();
|