@kliebhan/pi-prompt-autocomplete 0.2.1 → 0.2.3
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 +17 -0
- package/README.md +5 -3
- package/core.ts +152 -0
- package/index.ts +153 -30
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,23 @@
|
|
|
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.3] - 2026-08-06
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
|
|
9
|
+
- Inline suggestions now render on hosts that keep an editor background surface alive. The renderer located the fake cursor by Pi's exact `\x1b[7m \x1b[0m` byte sequence, but forks such as prime-agent close the inverse-video cursor with `\x1b[27m` so the background survives the cursor cell. The lookup missed, so suggestions were generated and counted as showing yet never drawn. The cursor lookup now accepts both reset variants and rebuilds the line with the host's own reset.
|
|
10
|
+
|
|
11
|
+
## [0.2.2] - 2026-08-06
|
|
12
|
+
|
|
13
|
+
### Security
|
|
14
|
+
|
|
15
|
+
- 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.
|
|
16
|
+
- 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.
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
|
|
20
|
+
- 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.
|
|
21
|
+
|
|
5
22
|
## [0.2.1] - 2026-08-06
|
|
6
23
|
|
|
7
24
|
### 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.3/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";
|
|
@@ -57,10 +59,18 @@ import {
|
|
|
57
59
|
const GHOST_TEXT_STYLE = "\x1b[2m";
|
|
58
60
|
const GHOST_INDICATOR_STYLE = "\x1b[90m";
|
|
59
61
|
const RESET = "\x1b[0m";
|
|
60
|
-
|
|
62
|
+
// Hosts draw the end-of-line fake cursor as an inverse-video space. Pi closes
|
|
63
|
+
// it with a full SGR reset (\x1b[0m); forks that keep an editor background
|
|
64
|
+
// surface alive, such as prime-agent, close it with \x1b[27m so the background
|
|
65
|
+
// survives the cursor cell. Accept both, otherwise the suggestion lookup never
|
|
66
|
+
// finds the cursor and inline suggestions silently never render.
|
|
67
|
+
const CURSOR_INVERSE_SPACE = "\x1b[7m ";
|
|
68
|
+
const CURSOR_TOKEN_PATTERN = /\x1b\[7m \x1b\[(0|27)m/;
|
|
61
69
|
const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] as const;
|
|
62
70
|
const SPINNER_INTERVAL_MS = 80;
|
|
63
71
|
const SPINNER_LABEL = "Generating suggestion";
|
|
72
|
+
/** Diagnostics are displayed as a short prefix; longer input is never needed. */
|
|
73
|
+
const MAX_DIAGNOSTIC_INPUT_CHARS = 8_192;
|
|
64
74
|
// Inline autocomplete should fail fast instead of inheriting long provider retry/timeout defaults.
|
|
65
75
|
const REQUEST_TIMEOUT_MS = 8_000;
|
|
66
76
|
// A compliant provider emits its terminal aborted message immediately, which
|
|
@@ -120,7 +130,7 @@ interface PromptAutocompleteConfig {
|
|
|
120
130
|
minPromptChars: number;
|
|
121
131
|
maxSuggestionChars: number;
|
|
122
132
|
maxAlternatives: number;
|
|
123
|
-
|
|
133
|
+
modelSelection: PromptAutocompleteModelSelection;
|
|
124
134
|
}
|
|
125
135
|
|
|
126
136
|
interface PromptAutocompleteCacheEntry {
|
|
@@ -220,6 +230,10 @@ interface PromptAutocompleteSharedState {
|
|
|
220
230
|
debugState: string;
|
|
221
231
|
editorMount?: EditorMountState;
|
|
222
232
|
editorBlockedReason?: string;
|
|
233
|
+
/** Mount-bound notification channel; cleared together with the editor runtime. */
|
|
234
|
+
notify?: (message: string, type?: "info" | "warning" | "error") => void;
|
|
235
|
+
/** Refused model requests already reported, to avoid repeating them. */
|
|
236
|
+
reportedModelRefusals: Set<string>;
|
|
223
237
|
/**
|
|
224
238
|
* Set once a mount attempt proved whether this host installs custom editors.
|
|
225
239
|
*
|
|
@@ -347,22 +361,81 @@ function formatPrimaryKey(keys: readonly KeyId[]): string {
|
|
|
347
361
|
return keys[0] ?? "";
|
|
348
362
|
}
|
|
349
363
|
|
|
350
|
-
|
|
364
|
+
interface SuggestionModelResolution {
|
|
365
|
+
model?: Model<Api>;
|
|
366
|
+
/** Why no model is usable; also used as the suppression reason. */
|
|
367
|
+
reason?: string;
|
|
368
|
+
/** Set when an explicitly requested model was refused, for a one-time notice. */
|
|
369
|
+
refusedRequest?: string;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Resolve the model an autocomplete request may use.
|
|
374
|
+
*
|
|
375
|
+
* An explicitly requested model is honoured or refused, never substituted: the
|
|
376
|
+
* request carries the draft and recent conversation context, so falling back to
|
|
377
|
+
* the active model would send that context to a provider the user did not
|
|
378
|
+
* choose and bill it there.
|
|
379
|
+
*/
|
|
380
|
+
function resolveSuggestionModelResolution(
|
|
381
|
+
shared: PromptAutocompleteSharedState,
|
|
382
|
+
): SuggestionModelResolution {
|
|
351
383
|
const registry = shared.modelRegistry;
|
|
352
|
-
if (!registry) return
|
|
384
|
+
if (!registry) return { reason: "No model registry is available yet" };
|
|
385
|
+
|
|
386
|
+
const selection = shared.config.modelSelection;
|
|
387
|
+
const requested = describePromptAutocompleteModelSelection(selection);
|
|
353
388
|
|
|
354
|
-
if (
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
389
|
+
if (selection.kind === "invalid") {
|
|
390
|
+
return {
|
|
391
|
+
reason: `Requested autocomplete model ${requested} is not a provider/model reference`,
|
|
392
|
+
refusedRequest: "Prompt autocomplete is inactive and requests are not sent to the active model instead: "
|
|
393
|
+
+ `${requested} is not a provider/model reference.`,
|
|
394
|
+
};
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
if (selection.kind === "dedicated") {
|
|
398
|
+
const preferred = registry.find(selection.ref.provider, selection.ref.id);
|
|
399
|
+
if (!preferred) {
|
|
400
|
+
return {
|
|
401
|
+
reason: `Requested autocomplete model ${requested} is unknown`,
|
|
402
|
+
refusedRequest: "Prompt autocomplete is inactive and requests are not sent to the active model instead: "
|
|
403
|
+
+ `model ${requested} is unknown.`,
|
|
404
|
+
};
|
|
358
405
|
}
|
|
406
|
+
if (!registry.hasConfiguredAuth(preferred)) {
|
|
407
|
+
return {
|
|
408
|
+
reason: `Requested autocomplete model ${requested} has no configured auth`,
|
|
409
|
+
refusedRequest: "Prompt autocomplete is inactive and requests are not sent to the active model instead: "
|
|
410
|
+
+ `model ${requested} has no configured auth.`,
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
return { model: preferred as Model<Api> };
|
|
359
414
|
}
|
|
360
415
|
|
|
361
416
|
if (shared.currentModel && registry.hasConfiguredAuth(shared.currentModel)) {
|
|
362
|
-
return shared.currentModel as Model<Api
|
|
417
|
+
return { model: shared.currentModel as Model<Api> };
|
|
363
418
|
}
|
|
364
419
|
|
|
365
|
-
return
|
|
420
|
+
return { reason: "No usable autocomplete model with configured auth was found" };
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
function resolveSuggestionModel(shared: PromptAutocompleteSharedState): Model<Api> | undefined {
|
|
424
|
+
return resolveSuggestionModelResolution(shared).model;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/**
|
|
428
|
+
* Report a refused model request once per distinct reason.
|
|
429
|
+
*
|
|
430
|
+
* The refusal repeats on every keystroke, so without deduplication a single
|
|
431
|
+
* misconfigured flag would flood the terminal.
|
|
432
|
+
*/
|
|
433
|
+
function notifyRefusedModelRequest(shared: PromptAutocompleteSharedState, message: string): void {
|
|
434
|
+
// Remember every distinct reason: a registry that flips between "unknown" and
|
|
435
|
+
// "no configured auth" would otherwise re-notify on each alternation.
|
|
436
|
+
if (shared.reportedModelRefusals.has(message)) return;
|
|
437
|
+
shared.reportedModelRefusals.add(message);
|
|
438
|
+
shared.notify?.(truncateDebug(message, 240), "warning");
|
|
366
439
|
}
|
|
367
440
|
|
|
368
441
|
function parseOnOffFlag(value: boolean | string | undefined, fallback: boolean): boolean {
|
|
@@ -393,7 +466,7 @@ function parseConfig(pi: ExtensionAPI): PromptAutocompleteConfig {
|
|
|
393
466
|
1,
|
|
394
467
|
5,
|
|
395
468
|
),
|
|
396
|
-
|
|
469
|
+
modelSelection: parsePromptAutocompleteModelSelection(pi.getFlag("prompt-autocomplete-model")),
|
|
397
470
|
};
|
|
398
471
|
}
|
|
399
472
|
|
|
@@ -420,10 +493,24 @@ function applyEffectiveConfig(pi: ExtensionAPI, shared: PromptAutocompleteShared
|
|
|
420
493
|
};
|
|
421
494
|
}
|
|
422
495
|
|
|
496
|
+
/** Drop a trailing lone surrogate produced by slicing sanitized text. */
|
|
497
|
+
function truncateAtSafeBoundary(text: string): string {
|
|
498
|
+
const lastCode = text.charCodeAt(text.length - 1);
|
|
499
|
+
return lastCode >= 0xD800 && lastCode <= 0xDBFF ? text.slice(0, -1) : text;
|
|
500
|
+
}
|
|
501
|
+
|
|
423
502
|
function truncateDebug(text: string, maxLength = 140): string {
|
|
424
|
-
|
|
503
|
+
// Every diagnostic string can contain untrusted provider or host text, so the
|
|
504
|
+
// terminal-control scrub happens here, before whitespace collapsing keeps a
|
|
505
|
+
// sanitized fragment on one line. Provider error bodies are not length-bounded,
|
|
506
|
+
// and only a short prefix is ever displayed, so the input is capped first.
|
|
507
|
+
const bounded = text.length > MAX_DIAGNOSTIC_INPUT_CHARS
|
|
508
|
+
? truncateAtSafeBoundary(text.slice(0, MAX_DIAGNOSTIC_INPUT_CHARS))
|
|
509
|
+
: text;
|
|
510
|
+
const normalized = sanitizeTerminalText(bounded).replace(/\s+/g, " ").trim();
|
|
425
511
|
if (normalized.length <= maxLength) return normalized;
|
|
426
|
-
|
|
512
|
+
// Slicing can split a surrogate pair that sanitization had just repaired.
|
|
513
|
+
return `${truncateAtSafeBoundary(normalized.slice(0, maxLength - 1))}…`;
|
|
427
514
|
}
|
|
428
515
|
|
|
429
516
|
function updateDebugState(shared: PromptAutocompleteSharedState, state: string, details?: string): void {
|
|
@@ -445,15 +532,13 @@ function formatStatus(shared: PromptAutocompleteSharedState): string {
|
|
|
445
532
|
: shared.editorBlockedReason
|
|
446
533
|
? "blocked"
|
|
447
534
|
: "unmounted";
|
|
448
|
-
const requestedModel = shared.config.
|
|
449
|
-
? `${shared.config.preferredModel.provider}/${shared.config.preferredModel.id}`
|
|
450
|
-
: "current active model";
|
|
535
|
+
const requestedModel = describePromptAutocompleteModelSelection(shared.config.modelSelection);
|
|
451
536
|
|
|
452
537
|
return [
|
|
453
538
|
`enabled=${shared.enabled ? "yes" : "no"}(${describeSettingSource(shared.runtimeOverrides.enabled)})`,
|
|
454
539
|
`editor=${editorState}`,
|
|
455
540
|
shared.editorBlockedReason ? `editor-blocked=${truncateDebug(shared.editorBlockedReason, 90)}` : undefined,
|
|
456
|
-
`model=${formatModelLabel(resolvedModel)}`,
|
|
541
|
+
`model=${truncateDebug(formatModelLabel(resolvedModel), 90)}`,
|
|
457
542
|
`requested-model=${requestedModel}`,
|
|
458
543
|
`while-streaming=${shared.config.allowWhileStreaming ? "yes" : "no"}(${describeSettingSource(shared.runtimeOverrides.allowWhileStreaming)})`,
|
|
459
544
|
`stream=${shared.config.streamResponses ? "yes" : "no"}(${describeSettingSource(shared.runtimeOverrides.streamResponses)})`,
|
|
@@ -639,15 +724,26 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
639
724
|
return lines;
|
|
640
725
|
}
|
|
641
726
|
|
|
642
|
-
|
|
643
|
-
|
|
727
|
+
let cursorLineIndex = -1;
|
|
728
|
+
let cursorMatch: RegExpMatchArray | undefined;
|
|
729
|
+
for (let index = 0; index < lines.length; index++) {
|
|
730
|
+
if (!lines[index]!.includes(CURSOR_INVERSE_SPACE)) continue;
|
|
731
|
+
const match = lines[index]!.match(CURSOR_TOKEN_PATTERN);
|
|
732
|
+
if (match?.index !== undefined) {
|
|
733
|
+
cursorLineIndex = index;
|
|
734
|
+
cursorMatch = match;
|
|
735
|
+
break;
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
if (cursorLineIndex === -1 || !cursorMatch || cursorMatch.index === undefined) return lines;
|
|
644
739
|
|
|
645
740
|
const cursorLine = lines[cursorLineIndex]!;
|
|
646
|
-
const cursorIndex =
|
|
647
|
-
|
|
741
|
+
const cursorIndex = cursorMatch.index;
|
|
742
|
+
const cursorToken = cursorMatch[0];
|
|
743
|
+
const cursorReset = cursorMatch[1] === "27" ? "\x1b[27m" : "\x1b[0m";
|
|
648
744
|
|
|
649
745
|
const before = cursorLine.slice(0, cursorIndex);
|
|
650
|
-
const after = cursorLine.slice(cursorIndex +
|
|
746
|
+
const after = cursorLine.slice(cursorIndex + cursorToken.length);
|
|
651
747
|
const availableWidth = visibleWidth(after);
|
|
652
748
|
if (availableWidth <= 0) return lines;
|
|
653
749
|
|
|
@@ -656,7 +752,7 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
656
752
|
const firstPreviewChar = previewChars[0] ?? "";
|
|
657
753
|
const absorbLeadingWhitespaceIntoCursor = /^[ \t]$/.test(firstPreviewChar);
|
|
658
754
|
|
|
659
|
-
const cursorCell = absorbLeadingWhitespaceIntoCursor ? `\x1b[7m${firstPreviewChar}
|
|
755
|
+
const cursorCell = absorbLeadingWhitespaceIntoCursor ? `\x1b[7m${firstPreviewChar}${cursorReset}` : cursorToken;
|
|
660
756
|
const renderedPreviewText = absorbLeadingWhitespaceIntoCursor ? previewChars.slice(1).join("") : previewText;
|
|
661
757
|
|
|
662
758
|
const indicator = this.suggestions.length > 1 ? ` ‹${this.suggestionIndex + 1}/${this.suggestions.length}›` : "";
|
|
@@ -911,8 +1007,11 @@ class PromptAutocompleteEditor extends CustomEditor {
|
|
|
911
1007
|
if (this.shared.now() < this.suspendedUntil) return "In temporary cooldown after the last error";
|
|
912
1008
|
}
|
|
913
1009
|
|
|
914
|
-
const
|
|
915
|
-
if (!model)
|
|
1010
|
+
const resolution = resolveSuggestionModelResolution(this.shared);
|
|
1011
|
+
if (!resolution.model) {
|
|
1012
|
+
if (resolution.refusedRequest) notifyRefusedModelRequest(this.shared, resolution.refusedRequest);
|
|
1013
|
+
return resolution.reason ?? "No usable autocomplete model with configured auth was found";
|
|
1014
|
+
}
|
|
916
1015
|
|
|
917
1016
|
const draft = this.getText();
|
|
918
1017
|
if (!options.manual && draft.trim().length < this.shared.config.minPromptChars) {
|
|
@@ -1372,6 +1471,7 @@ function releaseEditorRuntime(shared: PromptAutocompleteSharedState): void {
|
|
|
1372
1471
|
shared.setStatusText = undefined;
|
|
1373
1472
|
shared.setSpinnerActive = undefined;
|
|
1374
1473
|
shared.clearSpinner = undefined;
|
|
1474
|
+
shared.notify = undefined;
|
|
1375
1475
|
shared.ownsEditor = undefined;
|
|
1376
1476
|
}
|
|
1377
1477
|
|
|
@@ -1417,6 +1517,10 @@ function mountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedStat
|
|
|
1417
1517
|
shared.editorBlockedReason = undefined;
|
|
1418
1518
|
shared.activationId += 1;
|
|
1419
1519
|
const activationId = shared.activationId;
|
|
1520
|
+
shared.notify = (message, type) => {
|
|
1521
|
+
if (activationId !== shared.activationId) return;
|
|
1522
|
+
ctx.ui.notify(message, type ?? "info");
|
|
1523
|
+
};
|
|
1420
1524
|
shared.setStatusText = (text) => {
|
|
1421
1525
|
ctx.ui.setWidget(
|
|
1422
1526
|
"prompt-autocomplete-debug",
|
|
@@ -1503,7 +1607,8 @@ function mountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedStat
|
|
|
1503
1607
|
// Nothing can render or request here, so the extension must not stay marked
|
|
1504
1608
|
// enabled, no matter which path attempted the mount.
|
|
1505
1609
|
shared.enabled = false;
|
|
1506
|
-
const reason = "
|
|
1610
|
+
const reason = "Prompt autocomplete needs a host that installs custom editors in the terminal process. "
|
|
1611
|
+
+ "This host accepted the editor but runs extensions outside its terminal UI, so inline suggestions stay unavailable.";
|
|
1507
1612
|
const shouldNotify = shared.editorBlockedReason !== reason;
|
|
1508
1613
|
shared.editorBlockedReason = reason;
|
|
1509
1614
|
updateDebugState(shared, "blocked-no-editor-slot", reason);
|
|
@@ -1543,6 +1648,7 @@ function resetSharedForSession(pi: ExtensionAPI, shared: PromptAutocompleteShare
|
|
|
1543
1648
|
shared.ownsEditor = undefined;
|
|
1544
1649
|
shared.lastError = undefined;
|
|
1545
1650
|
shared.lastRawResponse = undefined;
|
|
1651
|
+
shared.reportedModelRefusals.clear();
|
|
1546
1652
|
shared.requestCache.clear();
|
|
1547
1653
|
shared.prefixReuseCache.clear();
|
|
1548
1654
|
cancelAllCoalescedRequests(shared.inFlightRequests);
|
|
@@ -1660,6 +1766,8 @@ function disablePromptAutocomplete(ctx: ExtensionContext, shared: PromptAutocomp
|
|
|
1660
1766
|
shared.prefixReuseCache.clear();
|
|
1661
1767
|
shared.lastRawResponse = undefined;
|
|
1662
1768
|
shared.lastError = undefined;
|
|
1769
|
+
// Re-enabling must be able to report a refused model again.
|
|
1770
|
+
shared.reportedModelRefusals.clear();
|
|
1663
1771
|
}
|
|
1664
1772
|
|
|
1665
1773
|
function notifyPromptAutocompleteEnabled(
|
|
@@ -1671,13 +1779,27 @@ function notifyPromptAutocompleteEnabled(
|
|
|
1671
1779
|
`Tab accepts all, ${formatPrimaryKey(WORD_ACCEPT_KEYS)} accepts one word, ` +
|
|
1672
1780
|
`${formatPrimaryKey(CYCLE_PREV_KEYS)}/${formatPrimaryKey(CYCLE_NEXT_KEYS)} cycle alternatives, ` +
|
|
1673
1781
|
`${formatPrimaryKey(CYCLE_NEXT_KEYS)} also forces a one-shot suggestion when none is shown (even while the agent works).`;
|
|
1674
|
-
const
|
|
1782
|
+
const resolution = resolveSuggestionModelResolution(shared);
|
|
1783
|
+
const resolvedModel = resolution.model;
|
|
1675
1784
|
const privacyNotice = "Requests send the current draft and recent conversation context to the selected model and may incur provider usage.";
|
|
1676
1785
|
|
|
1786
|
+
if (!resolvedModel && resolution.refusedRequest) {
|
|
1787
|
+
// A refused explicit request must be reported on every enable path,
|
|
1788
|
+
// including toggle: "configure auth" would point at the active model, which
|
|
1789
|
+
// is deliberately not used.
|
|
1790
|
+
// Recorded as reported so the first keystroke does not repeat it verbatim.
|
|
1791
|
+
shared.reportedModelRefusals.add(resolution.refusedRequest);
|
|
1792
|
+
ctx.ui.notify(
|
|
1793
|
+
`Prompt autocomplete enabled, but no request can be issued. ${truncateDebug(resolution.refusedRequest, 240)}`,
|
|
1794
|
+
"warning",
|
|
1795
|
+
);
|
|
1796
|
+
return;
|
|
1797
|
+
}
|
|
1798
|
+
|
|
1677
1799
|
if (options.includeModel) {
|
|
1678
1800
|
if (resolvedModel) {
|
|
1679
1801
|
ctx.ui.notify(
|
|
1680
|
-
`Prompt autocomplete enabled. ${keyHint} Model: ${formatModelLabel(resolvedModel)} ${privacyNotice}`,
|
|
1802
|
+
`Prompt autocomplete enabled. ${keyHint} Model: ${truncateDebug(formatModelLabel(resolvedModel), 90)} ${privacyNotice}`,
|
|
1681
1803
|
"info",
|
|
1682
1804
|
);
|
|
1683
1805
|
} else {
|
|
@@ -1833,6 +1955,7 @@ export function createPromptAutocompleteExtension(
|
|
|
1833
1955
|
requestCache: new ExpiringLruCache(REQUEST_CACHE_TTL_MS, REQUEST_CACHE_MAX_ENTRIES, now),
|
|
1834
1956
|
prefixReuseCache: new ExpiringLruCache(REQUEST_CACHE_TTL_MS, REQUEST_CACHE_MAX_ENTRIES, now),
|
|
1835
1957
|
inFlightRequests: new Map(),
|
|
1958
|
+
reportedModelRefusals: new Set(),
|
|
1836
1959
|
};
|
|
1837
1960
|
|
|
1838
1961
|
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.3",
|
|
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.3/prompt-autocomplete-demo.mp4"
|
|
30
30
|
},
|
|
31
31
|
"engines": {
|
|
32
32
|
"node": ">=22.19.0"
|