@kliebhan/pi-prompt-autocomplete 0.2.1 → 0.2.2
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 +11 -0
- package/README.md +5 -3
- package/core.ts +152 -0
- package/index.ts +129 -23
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this package are documented here. This project follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
4
4
|
|
|
5
|
+
## [0.2.2] - 2026-08-06
|
|
6
|
+
|
|
7
|
+
### Security
|
|
8
|
+
|
|
9
|
+
- Sanitize every untrusted string before it reaches the terminal. Provider errors, raw responses, model identifiers, and host diagnostics are stripped of complete escape sequences, including the DCS, SOS, PM, and APC payloads that Node's own helper leaves behind, of any remaining C0/C1 control such as a bare ESC or a carriage return, and of every Unicode format or default-ignorable character that could make a diagnostic display something other than its content; line and paragraph separators become real line breaks, while the joiners used by Arabic, Persian, Indic, and emoji sequences are preserved. Tabs and newlines are preserved, sanitization runs in a single linear scan so an unbounded provider error cannot stall the terminal, and diagnostic input is capped before display.
|
|
10
|
+
- An explicitly requested `--prompt-autocomplete-model` is now honoured or refused, never substituted. An unknown, unauthenticated, or malformed value suppresses autocomplete requests and reports the reason once instead of silently sending the draft and recent conversation context to the active model, which may belong to a different provider.
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
|
|
14
|
+
- The notice for hosts that accept a custom editor without installing it now explains the cause: such hosts run extensions outside their terminal UI, so inline suggestions are unavailable.
|
|
15
|
+
|
|
5
16
|
## [0.2.1] - 2026-08-06
|
|
6
17
|
|
|
7
18
|
### Fixed
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Inline AI completions for the [Pi coding agent](https://github.com/earendil-works/pi-mono), rendered as unobtrusive ghost text in the prompt editor.
|
|
4
4
|
|
|
5
|
-
[Watch the demo](https://github.com/KLIEBHAN/pi-extensions/releases/download/pi-prompt-autocomplete-v0.2.
|
|
5
|
+
[Watch the demo](https://github.com/KLIEBHAN/pi-extensions/releases/download/pi-prompt-autocomplete-v0.2.2/prompt-autocomplete-demo.mp4)
|
|
6
6
|
|
|
7
7
|
## Install
|
|
8
8
|
|
|
@@ -60,7 +60,7 @@ pi \
|
|
|
60
60
|
--prompt-autocomplete-max-alternatives 3
|
|
61
61
|
```
|
|
62
62
|
|
|
63
|
-
- The active Pi model is used unless `--prompt-autocomplete-model provider/model` selects a dedicated authenticated model.
|
|
63
|
+
- The active Pi model is used unless `--prompt-autocomplete-model provider/model` selects a dedicated authenticated model; `active` selects the session model explicitly. An explicitly requested model is never substituted: if it is unknown, unauthenticated, or malformed, autocomplete stays inactive and reports why.
|
|
64
64
|
- Automatic suggestions require at least one non-whitespace draft character by default. Set `--prompt-autocomplete-min-chars 0` to opt into empty-draft suggestions.
|
|
65
65
|
- Provider responses stream into the first ghost-text suggestion by default. Use `--prompt-autocomplete-stream off` or `/prompt-autocomplete stream off` to wait for complete responses instead. This changes rendering only: each suggestion request still uses the same context and token budget.
|
|
66
66
|
- Changing `/prompt-autocomplete stream` cancels active autocomplete work but does **not** start a replacement request; the selected path applies to the next edit or manual one-shot.
|
|
@@ -108,7 +108,9 @@ Enabling Prompt Autocomplete permits additional model requests. Streaming change
|
|
|
108
108
|
|
|
109
109
|
The active conversation leaf identity is used only in the local in-memory cache key and is not sent to the provider.
|
|
110
110
|
|
|
111
|
-
By default, requests use the active model. A dedicated `--prompt-autocomplete-model` may send this context to a different provider. Requests can incur token charges and consume provider rate limits.
|
|
111
|
+
By default, requests use the active model. A dedicated `--prompt-autocomplete-model` may send this context to a different provider, so an explicitly requested model that cannot be used suppresses requests instead of falling back to the active one. Requests can incur token charges and consume provider rate limits.
|
|
112
|
+
|
|
113
|
+
Provider errors, raw responses, model identifiers, and host diagnostics are stripped of terminal control sequences and of bidirectional or invisible formatting characters before they are displayed, so untrusted text cannot repaint the terminal, hide output, drive OSC clipboard and hyperlink escapes, or misrepresent what it names.
|
|
112
114
|
|
|
113
115
|
Successful results are cached only in memory for up to 60 seconds; a terminal entry retains its base draft in process memory for the prefix comparison. If the draft then grows by an exact prefix of a cached suggestion, Prompt Autocomplete removes the text you typed and shows the remaining suffix locally instead of issuing another provider request. Prefix reuse is forward-only, stays scoped to the same conversation leaf, model, bounded context and output configuration, and never uses partial streamed text. Divergence, expiry or any context change falls through to a fresh request. The caches are bounded and are cleared on session reset or when the extension is disabled. Provider failures are not cached.
|
|
114
116
|
|
package/core.ts
CHANGED
|
@@ -1,10 +1,33 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { readFileSync } from "node:fs";
|
|
3
|
+
import { stripVTControlCharacters } from "node:util";
|
|
3
4
|
import type { Api, Model } from "@earendil-works/pi-ai";
|
|
4
5
|
|
|
5
6
|
const TEMPLATE_VARIABLE_PATTERN = /(?<!\\)\{\{\s*([A-Z0-9_]+)\s*(?:\|\s*([\s\S]*?))?\s*\}\}/g;
|
|
6
7
|
const ESCAPED_TEMPLATE_VARIABLE_PATTERN = /\\(\{\{\s*[A-Z0-9_]+\s*(?:\|\s*[\s\S]*?)?\s*\}\})/g;
|
|
7
8
|
const PROMPT_AUTOCOMPLETE_RESPONSE_KEY = "completions";
|
|
9
|
+
/** Model references are short; a longer flag value is never displayed in full. */
|
|
10
|
+
const MAX_RAW_MODEL_CHARS = 512;
|
|
11
|
+
/** DCS, SOS, OSC, PM, and APC introducers in their C1 form. */
|
|
12
|
+
const C1_STRING_SEQUENCE_OPENERS = new Set(["\u0090", "\u0098", "\u009D", "\u009E", "\u009F"]);
|
|
13
|
+
/** The same introducers in their ESC-prefixed form. */
|
|
14
|
+
const ESCAPED_STRING_SEQUENCE_OPENERS = new Set(["P", "X", "^", "_"]);
|
|
15
|
+
/**
|
|
16
|
+
* Format and default-ignorable characters.
|
|
17
|
+
*
|
|
18
|
+
* They cannot change terminal state, but they can make a diagnostic display
|
|
19
|
+
* text that differs from its actual content, which defeats the purpose of
|
|
20
|
+
* naming a rejected model or a failing provider. Both Unicode properties are
|
|
21
|
+
* matched instead of an explicit list, because an enumeration misses soft
|
|
22
|
+
* hyphens, Hangul fillers, annotation marks, and most of plane 14.
|
|
23
|
+
*
|
|
24
|
+
* Zero-width joiner and non-joiner are deliberately kept: they carry meaning in
|
|
25
|
+
* Arabic, Persian, and Indic scripts and in emoji sequences, and they cannot
|
|
26
|
+
* reorder text.
|
|
27
|
+
*/
|
|
28
|
+
const DECEPTIVE_FORMAT_CHARACTERS = /[^\P{Cf}\u200C\u200D]|[^\P{Default_Ignorable_Code_Point}\u200C\u200D]/gu;
|
|
29
|
+
/** Line and paragraph separators; a line break keeps the text readable. */
|
|
30
|
+
const UNICODE_LINE_SEPARATORS = /[\u2028\u2029]/g;
|
|
8
31
|
|
|
9
32
|
export function normalizeTemplateText(template: string): string {
|
|
10
33
|
return template.replace(/\r\n/g, "\n").trim();
|
|
@@ -1325,6 +1348,135 @@ function parseSuggestionResponse(rawResponse: string): string[] {
|
|
|
1325
1348
|
return rawResponse.trim() ? [rawResponse] : [];
|
|
1326
1349
|
}
|
|
1327
1350
|
|
|
1351
|
+
/**
|
|
1352
|
+
* Make untrusted text safe to render in a terminal.
|
|
1353
|
+
*
|
|
1354
|
+
* Provider errors, raw responses, model identifiers taken from CLI flags, and
|
|
1355
|
+
* host diagnostics all end up in notifications and widgets whose renderer keeps
|
|
1356
|
+
* ANSI escapes intact. Sanitizing happens in three steps because no single one
|
|
1357
|
+
* is sufficient: malformed UTF-16 is repaired first so later passes cannot split
|
|
1358
|
+
* a surrogate pair, complete VT sequences (CSI, OSC, DCS) are removed next so
|
|
1359
|
+
* their payload disappears with the introducer, and any remaining C0/C1 control
|
|
1360
|
+
* is dropped so a bare ESC or C1 introducer cannot start a new sequence.
|
|
1361
|
+
*
|
|
1362
|
+
* Tabs and newlines survive; callers that need a single line collapse whitespace
|
|
1363
|
+
* afterwards.
|
|
1364
|
+
*/
|
|
1365
|
+
export function sanitizeTerminalText(text: string): string {
|
|
1366
|
+
const wellFormed = typeof (text as { toWellFormed?: () => string }).toWellFormed === "function"
|
|
1367
|
+
? text.toWellFormed()
|
|
1368
|
+
: truncateAtFirstUnpairedSurrogate(text);
|
|
1369
|
+
return stripVTControlCharacters(removeStringControlSequences(wellFormed))
|
|
1370
|
+
// Everything except tab and newline goes, including carriage return, which a
|
|
1371
|
+
// terminal would otherwise use to overwrite the line that was already drawn.
|
|
1372
|
+
.replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g, "")
|
|
1373
|
+
// Separators become real line breaks instead of disappearing, so a
|
|
1374
|
+
// multi-line provider error does not end up with its words glued together.
|
|
1375
|
+
.replace(UNICODE_LINE_SEPARATORS, "\n")
|
|
1376
|
+
.replace(DECEPTIVE_FORMAT_CHARACTERS, "");
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
/**
|
|
1380
|
+
* Drop DCS, SOS, PM, and APC sequences including their payload.
|
|
1381
|
+
*
|
|
1382
|
+
* `stripVTControlCharacters` leaves these string sequences behind, and a
|
|
1383
|
+
* terminal consumes everything up to the string terminator, so an unterminated
|
|
1384
|
+
* introducer discards the remainder here as well. The discard stops at a line
|
|
1385
|
+
* break: a C1 introducer is also what a mis-decoded UTF-8 quote looks like, and
|
|
1386
|
+
* losing the rest of a provider message to mojibake would hide the diagnostic
|
|
1387
|
+
* this text exists for.
|
|
1388
|
+
*
|
|
1389
|
+
* This is a single forward scan rather than a regex: a pattern with a lazy body
|
|
1390
|
+
* backtracks quadratically when an input carries many unterminated introducers,
|
|
1391
|
+
* and provider error text is not length-bounded.
|
|
1392
|
+
*/
|
|
1393
|
+
function removeStringControlSequences(text: string): string {
|
|
1394
|
+
let result = "";
|
|
1395
|
+
let index = 0;
|
|
1396
|
+
|
|
1397
|
+
while (index < text.length) {
|
|
1398
|
+
const char = text[index] as string;
|
|
1399
|
+
const isC1Opener = C1_STRING_SEQUENCE_OPENERS.has(char);
|
|
1400
|
+
const isEscapedOpener = char === "\u001B" && ESCAPED_STRING_SEQUENCE_OPENERS.has(text[index + 1] ?? "");
|
|
1401
|
+
if (!isC1Opener && !isEscapedOpener) {
|
|
1402
|
+
result += char;
|
|
1403
|
+
index += 1;
|
|
1404
|
+
continue;
|
|
1405
|
+
}
|
|
1406
|
+
|
|
1407
|
+
index += isC1Opener ? 1 : 2;
|
|
1408
|
+
while (index < text.length) {
|
|
1409
|
+
const candidate = text[index] as string;
|
|
1410
|
+
if (candidate === "\u0007" || candidate === "\u009C") {
|
|
1411
|
+
index += 1;
|
|
1412
|
+
break;
|
|
1413
|
+
}
|
|
1414
|
+
if (candidate === "\u001B" && text[index + 1] === "\\") {
|
|
1415
|
+
index += 2;
|
|
1416
|
+
break;
|
|
1417
|
+
}
|
|
1418
|
+
if (candidate === "\n") break;
|
|
1419
|
+
index += 1;
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
return result;
|
|
1424
|
+
}
|
|
1425
|
+
|
|
1426
|
+
/** Which model an autocomplete request may use. */
|
|
1427
|
+
export type PromptAutocompleteModelSelection =
|
|
1428
|
+
| { kind: "active" }
|
|
1429
|
+
| { kind: "dedicated"; ref: ModelRef; raw: string }
|
|
1430
|
+
| { kind: "invalid"; raw: string };
|
|
1431
|
+
|
|
1432
|
+
/**
|
|
1433
|
+
* Classify the `--prompt-autocomplete-model` value.
|
|
1434
|
+
*
|
|
1435
|
+
* An explicit but unusable value must stay distinguishable from "no dedicated
|
|
1436
|
+
* model requested". Collapsing both into `undefined` is what allows a malformed
|
|
1437
|
+
* value to silently send the draft and conversation context to the active
|
|
1438
|
+
* model, which may belong to a different provider than the user asked for.
|
|
1439
|
+
*/
|
|
1440
|
+
export function parsePromptAutocompleteModelSelection(
|
|
1441
|
+
value: boolean | string | undefined,
|
|
1442
|
+
): PromptAutocompleteModelSelection {
|
|
1443
|
+
if (typeof value !== "string") return { kind: "active" };
|
|
1444
|
+
const trimmed = value.trim();
|
|
1445
|
+
if (!trimmed) return { kind: "active" };
|
|
1446
|
+
// The flag ships the sentinel default `DEFAULT_PREFERRED_MODEL`, and `active`
|
|
1447
|
+
// is the explicit way to ask for the session model.
|
|
1448
|
+
const normalized = trimmed.toLowerCase();
|
|
1449
|
+
if (normalized === DEFAULT_PREFERRED_MODEL || normalized === "active") return { kind: "active" };
|
|
1450
|
+
|
|
1451
|
+
const ref = parseModelRef(trimmed);
|
|
1452
|
+
// Preserve the raw value: model identifiers are case-sensitive and the user
|
|
1453
|
+
// needs to recognize what was rejected.
|
|
1454
|
+
return ref ? { kind: "dedicated", ref, raw: trimmed } : { kind: "invalid", raw: trimmed };
|
|
1455
|
+
}
|
|
1456
|
+
|
|
1457
|
+
/** Human-readable, terminal-safe description of the requested model. */
|
|
1458
|
+
export function describePromptAutocompleteModelSelection(
|
|
1459
|
+
selection: PromptAutocompleteModelSelection,
|
|
1460
|
+
maxRawChars = 78,
|
|
1461
|
+
): string {
|
|
1462
|
+
if (selection.kind === "active") return "current active model";
|
|
1463
|
+
// This runs on the request path, so the value is capped before sanitizing
|
|
1464
|
+
// rather than only afterwards.
|
|
1465
|
+
const capped = selection.raw.length > MAX_RAW_MODEL_CHARS
|
|
1466
|
+
? truncateAtFirstUnpairedSurrogate(selection.raw.slice(0, MAX_RAW_MODEL_CHARS))
|
|
1467
|
+
: selection.raw;
|
|
1468
|
+
const raw = trimAndCollapse(sanitizeTerminalText(capped));
|
|
1469
|
+
// A value made only of invisible characters would otherwise be reported as an
|
|
1470
|
+
// empty string, leaving nothing to recognize.
|
|
1471
|
+
if (!raw) return selection.kind === "dedicated" ? "<unprintable>" : "<unprintable> (invalid)";
|
|
1472
|
+
// Truncate the raw value only, so a long malformed value cannot push the
|
|
1473
|
+
// rejection marker out of the message and read as a plausible model name.
|
|
1474
|
+
const bounded = raw.length > maxRawChars
|
|
1475
|
+
? `${truncateAtFirstUnpairedSurrogate(raw.slice(0, maxRawChars - 1))}…`
|
|
1476
|
+
: raw;
|
|
1477
|
+
return selection.kind === "dedicated" ? bounded : `${bounded} (invalid)`;
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1328
1480
|
export function parseModelRef(value: boolean | string | undefined): ModelRef | undefined {
|
|
1329
1481
|
if (typeof value !== "string") return undefined;
|
|
1330
1482
|
const trimmed = value.trim();
|
package/index.ts
CHANGED
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
computeRequestMaxTokens,
|
|
20
20
|
createOwnerRefCounter,
|
|
21
21
|
createPromptAutocompleteUsageStats,
|
|
22
|
+
describePromptAutocompleteModelSelection,
|
|
22
23
|
describeSettingSource,
|
|
23
24
|
DEFAULT_DEBOUNCE_MS,
|
|
24
25
|
DEFAULT_MAX_ALTERNATIVES,
|
|
@@ -37,19 +38,20 @@ import {
|
|
|
37
38
|
MAX_DRAFT_CONTEXT_CHARS,
|
|
38
39
|
normalizePromptSuggestions,
|
|
39
40
|
parseBoundedIntFlag,
|
|
40
|
-
parseModelRef,
|
|
41
41
|
parsePartialPromptSuggestion,
|
|
42
|
+
parsePromptAutocompleteModelSelection,
|
|
42
43
|
PROMPT_AUTOCOMPLETE_SYSTEM_PROMPT,
|
|
43
44
|
recordProviderLatency,
|
|
44
45
|
recordProviderUsage,
|
|
45
46
|
resolveOverride,
|
|
46
47
|
reusePromptAutocompleteSuggestions,
|
|
48
|
+
sanitizeTerminalText,
|
|
47
49
|
SequenceOwnedSlot,
|
|
48
50
|
shouldSkipPromptAutocomplete,
|
|
49
51
|
truncateDraftTail,
|
|
50
52
|
type CoalescedRequestEntry,
|
|
51
53
|
type CoalescedRequestSubscription,
|
|
52
|
-
type
|
|
54
|
+
type PromptAutocompleteModelSelection,
|
|
53
55
|
type PromptAutocompleteRuntimeOverrides,
|
|
54
56
|
type PromptAutocompleteUsageStats,
|
|
55
57
|
} from "./core.ts";
|
|
@@ -61,6 +63,8 @@ const CURSOR_TOKEN = "\x1b[7m \x1b[0m";
|
|
|
61
63
|
const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] as const;
|
|
62
64
|
const SPINNER_INTERVAL_MS = 80;
|
|
63
65
|
const SPINNER_LABEL = "Generating suggestion";
|
|
66
|
+
/** Diagnostics are displayed as a short prefix; longer input is never needed. */
|
|
67
|
+
const MAX_DIAGNOSTIC_INPUT_CHARS = 8_192;
|
|
64
68
|
// Inline autocomplete should fail fast instead of inheriting long provider retry/timeout defaults.
|
|
65
69
|
const REQUEST_TIMEOUT_MS = 8_000;
|
|
66
70
|
// A compliant provider emits its terminal aborted message immediately, which
|
|
@@ -120,7 +124,7 @@ interface PromptAutocompleteConfig {
|
|
|
120
124
|
minPromptChars: number;
|
|
121
125
|
maxSuggestionChars: number;
|
|
122
126
|
maxAlternatives: number;
|
|
123
|
-
|
|
127
|
+
modelSelection: PromptAutocompleteModelSelection;
|
|
124
128
|
}
|
|
125
129
|
|
|
126
130
|
interface PromptAutocompleteCacheEntry {
|
|
@@ -220,6 +224,10 @@ interface PromptAutocompleteSharedState {
|
|
|
220
224
|
debugState: string;
|
|
221
225
|
editorMount?: EditorMountState;
|
|
222
226
|
editorBlockedReason?: string;
|
|
227
|
+
/** Mount-bound notification channel; cleared together with the editor runtime. */
|
|
228
|
+
notify?: (message: string, type?: "info" | "warning" | "error") => void;
|
|
229
|
+
/** Refused model requests already reported, to avoid repeating them. */
|
|
230
|
+
reportedModelRefusals: Set<string>;
|
|
223
231
|
/**
|
|
224
232
|
* Set once a mount attempt proved whether this host installs custom editors.
|
|
225
233
|
*
|
|
@@ -347,22 +355,81 @@ function formatPrimaryKey(keys: readonly KeyId[]): string {
|
|
|
347
355
|
return keys[0] ?? "";
|
|
348
356
|
}
|
|
349
357
|
|
|
350
|
-
|
|
358
|
+
interface SuggestionModelResolution {
|
|
359
|
+
model?: Model<Api>;
|
|
360
|
+
/** Why no model is usable; also used as the suppression reason. */
|
|
361
|
+
reason?: string;
|
|
362
|
+
/** Set when an explicitly requested model was refused, for a one-time notice. */
|
|
363
|
+
refusedRequest?: string;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Resolve the model an autocomplete request may use.
|
|
368
|
+
*
|
|
369
|
+
* An explicitly requested model is honoured or refused, never substituted: the
|
|
370
|
+
* request carries the draft and recent conversation context, so falling back to
|
|
371
|
+
* the active model would send that context to a provider the user did not
|
|
372
|
+
* choose and bill it there.
|
|
373
|
+
*/
|
|
374
|
+
function resolveSuggestionModelResolution(
|
|
375
|
+
shared: PromptAutocompleteSharedState,
|
|
376
|
+
): SuggestionModelResolution {
|
|
351
377
|
const registry = shared.modelRegistry;
|
|
352
|
-
if (!registry) return
|
|
378
|
+
if (!registry) return { reason: "No model registry is available yet" };
|
|
379
|
+
|
|
380
|
+
const selection = shared.config.modelSelection;
|
|
381
|
+
const requested = describePromptAutocompleteModelSelection(selection);
|
|
382
|
+
|
|
383
|
+
if (selection.kind === "invalid") {
|
|
384
|
+
return {
|
|
385
|
+
reason: `Requested autocomplete model ${requested} is not a provider/model reference`,
|
|
386
|
+
refusedRequest: "Prompt autocomplete is inactive and requests are not sent to the active model instead: "
|
|
387
|
+
+ `${requested} is not a provider/model reference.`,
|
|
388
|
+
};
|
|
389
|
+
}
|
|
353
390
|
|
|
354
|
-
if (
|
|
355
|
-
const preferred = registry.find(
|
|
356
|
-
if (preferred
|
|
357
|
-
return
|
|
391
|
+
if (selection.kind === "dedicated") {
|
|
392
|
+
const preferred = registry.find(selection.ref.provider, selection.ref.id);
|
|
393
|
+
if (!preferred) {
|
|
394
|
+
return {
|
|
395
|
+
reason: `Requested autocomplete model ${requested} is unknown`,
|
|
396
|
+
refusedRequest: "Prompt autocomplete is inactive and requests are not sent to the active model instead: "
|
|
397
|
+
+ `model ${requested} is unknown.`,
|
|
398
|
+
};
|
|
358
399
|
}
|
|
400
|
+
if (!registry.hasConfiguredAuth(preferred)) {
|
|
401
|
+
return {
|
|
402
|
+
reason: `Requested autocomplete model ${requested} has no configured auth`,
|
|
403
|
+
refusedRequest: "Prompt autocomplete is inactive and requests are not sent to the active model instead: "
|
|
404
|
+
+ `model ${requested} has no configured auth.`,
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
return { model: preferred as Model<Api> };
|
|
359
408
|
}
|
|
360
409
|
|
|
361
410
|
if (shared.currentModel && registry.hasConfiguredAuth(shared.currentModel)) {
|
|
362
|
-
return shared.currentModel as Model<Api
|
|
411
|
+
return { model: shared.currentModel as Model<Api> };
|
|
363
412
|
}
|
|
364
413
|
|
|
365
|
-
return
|
|
414
|
+
return { reason: "No usable autocomplete model with configured auth was found" };
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function resolveSuggestionModel(shared: PromptAutocompleteSharedState): Model<Api> | undefined {
|
|
418
|
+
return resolveSuggestionModelResolution(shared).model;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* Report a refused model request once per distinct reason.
|
|
423
|
+
*
|
|
424
|
+
* The refusal repeats on every keystroke, so without deduplication a single
|
|
425
|
+
* misconfigured flag would flood the terminal.
|
|
426
|
+
*/
|
|
427
|
+
function notifyRefusedModelRequest(shared: PromptAutocompleteSharedState, message: string): void {
|
|
428
|
+
// Remember every distinct reason: a registry that flips between "unknown" and
|
|
429
|
+
// "no configured auth" would otherwise re-notify on each alternation.
|
|
430
|
+
if (shared.reportedModelRefusals.has(message)) return;
|
|
431
|
+
shared.reportedModelRefusals.add(message);
|
|
432
|
+
shared.notify?.(truncateDebug(message, 240), "warning");
|
|
366
433
|
}
|
|
367
434
|
|
|
368
435
|
function parseOnOffFlag(value: boolean | string | undefined, fallback: boolean): boolean {
|
|
@@ -393,7 +460,7 @@ function parseConfig(pi: ExtensionAPI): PromptAutocompleteConfig {
|
|
|
393
460
|
1,
|
|
394
461
|
5,
|
|
395
462
|
),
|
|
396
|
-
|
|
463
|
+
modelSelection: parsePromptAutocompleteModelSelection(pi.getFlag("prompt-autocomplete-model")),
|
|
397
464
|
};
|
|
398
465
|
}
|
|
399
466
|
|
|
@@ -420,10 +487,24 @@ function applyEffectiveConfig(pi: ExtensionAPI, shared: PromptAutocompleteShared
|
|
|
420
487
|
};
|
|
421
488
|
}
|
|
422
489
|
|
|
490
|
+
/** Drop a trailing lone surrogate produced by slicing sanitized text. */
|
|
491
|
+
function truncateAtSafeBoundary(text: string): string {
|
|
492
|
+
const lastCode = text.charCodeAt(text.length - 1);
|
|
493
|
+
return lastCode >= 0xD800 && lastCode <= 0xDBFF ? text.slice(0, -1) : text;
|
|
494
|
+
}
|
|
495
|
+
|
|
423
496
|
function truncateDebug(text: string, maxLength = 140): string {
|
|
424
|
-
|
|
497
|
+
// Every diagnostic string can contain untrusted provider or host text, so the
|
|
498
|
+
// terminal-control scrub happens here, before whitespace collapsing keeps a
|
|
499
|
+
// sanitized fragment on one line. Provider error bodies are not length-bounded,
|
|
500
|
+
// and only a short prefix is ever displayed, so the input is capped first.
|
|
501
|
+
const bounded = text.length > MAX_DIAGNOSTIC_INPUT_CHARS
|
|
502
|
+
? truncateAtSafeBoundary(text.slice(0, MAX_DIAGNOSTIC_INPUT_CHARS))
|
|
503
|
+
: text;
|
|
504
|
+
const normalized = sanitizeTerminalText(bounded).replace(/\s+/g, " ").trim();
|
|
425
505
|
if (normalized.length <= maxLength) return normalized;
|
|
426
|
-
|
|
506
|
+
// Slicing can split a surrogate pair that sanitization had just repaired.
|
|
507
|
+
return `${truncateAtSafeBoundary(normalized.slice(0, maxLength - 1))}…`;
|
|
427
508
|
}
|
|
428
509
|
|
|
429
510
|
function updateDebugState(shared: PromptAutocompleteSharedState, state: string, details?: string): void {
|
|
@@ -445,15 +526,13 @@ function formatStatus(shared: PromptAutocompleteSharedState): string {
|
|
|
445
526
|
: shared.editorBlockedReason
|
|
446
527
|
? "blocked"
|
|
447
528
|
: "unmounted";
|
|
448
|
-
const requestedModel = shared.config.
|
|
449
|
-
? `${shared.config.preferredModel.provider}/${shared.config.preferredModel.id}`
|
|
450
|
-
: "current active model";
|
|
529
|
+
const requestedModel = describePromptAutocompleteModelSelection(shared.config.modelSelection);
|
|
451
530
|
|
|
452
531
|
return [
|
|
453
532
|
`enabled=${shared.enabled ? "yes" : "no"}(${describeSettingSource(shared.runtimeOverrides.enabled)})`,
|
|
454
533
|
`editor=${editorState}`,
|
|
455
534
|
shared.editorBlockedReason ? `editor-blocked=${truncateDebug(shared.editorBlockedReason, 90)}` : undefined,
|
|
456
|
-
`model=${formatModelLabel(resolvedModel)}`,
|
|
535
|
+
`model=${truncateDebug(formatModelLabel(resolvedModel), 90)}`,
|
|
457
536
|
`requested-model=${requestedModel}`,
|
|
458
537
|
`while-streaming=${shared.config.allowWhileStreaming ? "yes" : "no"}(${describeSettingSource(shared.runtimeOverrides.allowWhileStreaming)})`,
|
|
459
538
|
`stream=${shared.config.streamResponses ? "yes" : "no"}(${describeSettingSource(shared.runtimeOverrides.streamResponses)})`,
|
|
@@ -911,8 +990,11 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
911
990
|
if (this.shared.now() < this.suspendedUntil) return "In temporary cooldown after the last error";
|
|
912
991
|
}
|
|
913
992
|
|
|
914
|
-
const
|
|
915
|
-
if (!model)
|
|
993
|
+
const resolution = resolveSuggestionModelResolution(this.shared);
|
|
994
|
+
if (!resolution.model) {
|
|
995
|
+
if (resolution.refusedRequest) notifyRefusedModelRequest(this.shared, resolution.refusedRequest);
|
|
996
|
+
return resolution.reason ?? "No usable autocomplete model with configured auth was found";
|
|
997
|
+
}
|
|
916
998
|
|
|
917
999
|
const draft = this.getText();
|
|
918
1000
|
if (!options.manual && draft.trim().length < this.shared.config.minPromptChars) {
|
|
@@ -1372,6 +1454,7 @@ function releaseEditorRuntime(shared: PromptAutocompleteSharedState): void {
|
|
|
1372
1454
|
shared.setStatusText = undefined;
|
|
1373
1455
|
shared.setSpinnerActive = undefined;
|
|
1374
1456
|
shared.clearSpinner = undefined;
|
|
1457
|
+
shared.notify = undefined;
|
|
1375
1458
|
shared.ownsEditor = undefined;
|
|
1376
1459
|
}
|
|
1377
1460
|
|
|
@@ -1417,6 +1500,10 @@ function mountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedStat
|
|
|
1417
1500
|
shared.editorBlockedReason = undefined;
|
|
1418
1501
|
shared.activationId += 1;
|
|
1419
1502
|
const activationId = shared.activationId;
|
|
1503
|
+
shared.notify = (message, type) => {
|
|
1504
|
+
if (activationId !== shared.activationId) return;
|
|
1505
|
+
ctx.ui.notify(message, type ?? "info");
|
|
1506
|
+
};
|
|
1420
1507
|
shared.setStatusText = (text) => {
|
|
1421
1508
|
ctx.ui.setWidget(
|
|
1422
1509
|
"prompt-autocomplete-debug",
|
|
@@ -1503,7 +1590,8 @@ function mountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedStat
|
|
|
1503
1590
|
// Nothing can render or request here, so the extension must not stay marked
|
|
1504
1591
|
// enabled, no matter which path attempted the mount.
|
|
1505
1592
|
shared.enabled = false;
|
|
1506
|
-
const reason = "
|
|
1593
|
+
const reason = "Prompt autocomplete needs a host that installs custom editors in the terminal process. "
|
|
1594
|
+
+ "This host accepted the editor but runs extensions outside its terminal UI, so inline suggestions stay unavailable.";
|
|
1507
1595
|
const shouldNotify = shared.editorBlockedReason !== reason;
|
|
1508
1596
|
shared.editorBlockedReason = reason;
|
|
1509
1597
|
updateDebugState(shared, "blocked-no-editor-slot", reason);
|
|
@@ -1543,6 +1631,7 @@ function resetSharedForSession(pi: ExtensionAPI, shared: PromptAutocompleteShare
|
|
|
1543
1631
|
shared.ownsEditor = undefined;
|
|
1544
1632
|
shared.lastError = undefined;
|
|
1545
1633
|
shared.lastRawResponse = undefined;
|
|
1634
|
+
shared.reportedModelRefusals.clear();
|
|
1546
1635
|
shared.requestCache.clear();
|
|
1547
1636
|
shared.prefixReuseCache.clear();
|
|
1548
1637
|
cancelAllCoalescedRequests(shared.inFlightRequests);
|
|
@@ -1660,6 +1749,8 @@ function disablePromptAutocomplete(ctx: ExtensionContext, shared: PromptAutocomp
|
|
|
1660
1749
|
shared.prefixReuseCache.clear();
|
|
1661
1750
|
shared.lastRawResponse = undefined;
|
|
1662
1751
|
shared.lastError = undefined;
|
|
1752
|
+
// Re-enabling must be able to report a refused model again.
|
|
1753
|
+
shared.reportedModelRefusals.clear();
|
|
1663
1754
|
}
|
|
1664
1755
|
|
|
1665
1756
|
function notifyPromptAutocompleteEnabled(
|
|
@@ -1671,13 +1762,27 @@ function notifyPromptAutocompleteEnabled(
|
|
|
1671
1762
|
`Tab accepts all, ${formatPrimaryKey(WORD_ACCEPT_KEYS)} accepts one word, ` +
|
|
1672
1763
|
`${formatPrimaryKey(CYCLE_PREV_KEYS)}/${formatPrimaryKey(CYCLE_NEXT_KEYS)} cycle alternatives, ` +
|
|
1673
1764
|
`${formatPrimaryKey(CYCLE_NEXT_KEYS)} also forces a one-shot suggestion when none is shown (even while the agent works).`;
|
|
1674
|
-
const
|
|
1765
|
+
const resolution = resolveSuggestionModelResolution(shared);
|
|
1766
|
+
const resolvedModel = resolution.model;
|
|
1675
1767
|
const privacyNotice = "Requests send the current draft and recent conversation context to the selected model and may incur provider usage.";
|
|
1676
1768
|
|
|
1769
|
+
if (!resolvedModel && resolution.refusedRequest) {
|
|
1770
|
+
// A refused explicit request must be reported on every enable path,
|
|
1771
|
+
// including toggle: "configure auth" would point at the active model, which
|
|
1772
|
+
// is deliberately not used.
|
|
1773
|
+
// Recorded as reported so the first keystroke does not repeat it verbatim.
|
|
1774
|
+
shared.reportedModelRefusals.add(resolution.refusedRequest);
|
|
1775
|
+
ctx.ui.notify(
|
|
1776
|
+
`Prompt autocomplete enabled, but no request can be issued. ${truncateDebug(resolution.refusedRequest, 240)}`,
|
|
1777
|
+
"warning",
|
|
1778
|
+
);
|
|
1779
|
+
return;
|
|
1780
|
+
}
|
|
1781
|
+
|
|
1677
1782
|
if (options.includeModel) {
|
|
1678
1783
|
if (resolvedModel) {
|
|
1679
1784
|
ctx.ui.notify(
|
|
1680
|
-
`Prompt autocomplete enabled. ${keyHint} Model: ${formatModelLabel(resolvedModel)} ${privacyNotice}`,
|
|
1785
|
+
`Prompt autocomplete enabled. ${keyHint} Model: ${truncateDebug(formatModelLabel(resolvedModel), 90)} ${privacyNotice}`,
|
|
1681
1786
|
"info",
|
|
1682
1787
|
);
|
|
1683
1788
|
} else {
|
|
@@ -1833,6 +1938,7 @@ export function createPromptAutocompleteExtension(
|
|
|
1833
1938
|
requestCache: new ExpiringLruCache(REQUEST_CACHE_TTL_MS, REQUEST_CACHE_MAX_ENTRIES, now),
|
|
1834
1939
|
prefixReuseCache: new ExpiringLruCache(REQUEST_CACHE_TTL_MS, REQUEST_CACHE_MAX_ENTRIES, now),
|
|
1835
1940
|
inFlightRequests: new Map(),
|
|
1941
|
+
reportedModelRefusals: new Set(),
|
|
1836
1942
|
};
|
|
1837
1943
|
|
|
1838
1944
|
pi.on("session_start", async (_event, ctx) => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kliebhan/pi-prompt-autocomplete",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"description": "Privacy-conscious inline AI prompt completion for the Pi coding agent",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
"extensions": [
|
|
27
27
|
"./index.ts"
|
|
28
28
|
],
|
|
29
|
-
"video": "https://github.com/KLIEBHAN/pi-extensions/releases/download/pi-prompt-autocomplete-v0.2.
|
|
29
|
+
"video": "https://github.com/KLIEBHAN/pi-extensions/releases/download/pi-prompt-autocomplete-v0.2.2/prompt-autocomplete-demo.mp4"
|
|
30
30
|
},
|
|
31
31
|
"engines": {
|
|
32
32
|
"node": ">=22.19.0"
|