@kliebhan/pi-prompt-autocomplete 0.2.0 → 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 CHANGED
@@ -2,6 +2,24 @@
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
+
16
+ ## [0.2.1] - 2026-08-06
17
+
18
+ ### Fixed
19
+
20
+ - Load the simple completion API from the `@earendil-works/pi-ai` root specifier, which Pi maps to its compat entrypoint and forked hosts export directly. Hosts that never mapped the `@earendil-works/pi-ai/compat` subpath, such as prime-agent, can now load the extension at all.
21
+ - Detect the interactive editor host without requiring `ExtensionContext.mode`. Hosts that report a mode keep the previous behaviour, so Pi's RPC, JSON, and print runs stay excluded unchanged. Hosts built on an older extension API are treated as candidates only when they report UI availability and expose a custom-editor slot, and the installation is then verified: a host that accepts an editor factory without installing it — such as a forked headless or daemon front-end — is detected on the first attempt, is never retried, is not left enabled, and can neither render ghost text nor issue a provider request. This restores `/prompt-autocomplete` commands and ghost text on prime-agent.
22
+
5
23
  ## [0.2.0] - 2026-07-31
6
24
 
7
25
  ### Added
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.0/prompt-autocomplete-demo.mp4)
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
 
@@ -118,6 +120,8 @@ The extension makes no autocomplete request while disabled. Automatic empty-draf
118
120
 
119
121
  - Supported baseline: Pi `0.80.6`, Node.js `22.19.0` or newer.
120
122
  - Interactive ghost text requires Pi's TUI mode. RPC, JSON, and print modes do not install a custom editor.
123
+ - Forks of Pi's extension API whose `ExtensionContext` predates `mode`, such as [prime-agent](https://www.npmjs.com/package/prime-agent), are supported. For those hosts the extension first requires UI availability and a custom-editor slot, and then verifies that the host actually installed the editor. A front-end that accepts an editor factory without installing it, as forked RPC and daemon modes do, is detected on the first attempt and stays inactive: it is not retried, not left enabled, and can neither render ghost text nor issue a provider request.
124
+ - The simple completion API is imported from the `@earendil-works/pi-ai` root specifier, which Pi maps to its compat entrypoint and such forks export directly. If a host exposes that module without `streamSimple`, the extension uses the completion path instead of failing requests.
121
125
  - Prompt Autocomplete requires exclusive ownership of Pi's custom-editor slot. It refuses to replace another custom editor and never removes a later replacement editor.
122
126
 
123
127
  ## Development
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();
@@ -1629,3 +1781,54 @@ export function formatModelLabel(model: Model<Api> | undefined): string {
1629
1781
  if (!model) return "none";
1630
1782
  return `${model.provider}/${model.id}`;
1631
1783
  }
1784
+
1785
+ /**
1786
+ * Host capabilities needed to decide whether an interactive editor slot exists.
1787
+ *
1788
+ * Pi exposes `ExtensionContext.mode`. Forks of the Pi extension API (for
1789
+ * example prime-agent, which is based on an older API revision) ship
1790
+ * `hasUI` without `mode`.
1791
+ */
1792
+ export interface EditorHostCapabilities {
1793
+ /** `ExtensionContext.mode` when the host provides it. */
1794
+ mode?: unknown;
1795
+ /** `ExtensionContext.hasUI` when the host provides it. */
1796
+ hasUI?: unknown;
1797
+ /** Whether the host exposes a usable custom-editor slot. */
1798
+ canInstallEditor?: unknown;
1799
+ }
1800
+
1801
+ /**
1802
+ * Decide whether the host runs an interactive terminal editor.
1803
+ *
1804
+ * A host that reports `mode` is authoritative: only `"tui"` may own the editor,
1805
+ * so `rpc`, `json`, and `print` stay excluded exactly as before. Only a host
1806
+ * that omits `mode` entirely is treated as a forked API revision, and then only
1807
+ * when it reports UI availability *and* exposes the custom-editor slot. Any
1808
+ * other reported value, including `null`, fails closed.
1809
+ *
1810
+ * Capabilities alone cannot prove that a host really installs custom editors:
1811
+ * some forks expose a no-op editor slot in headless front-ends. The caller must
1812
+ * still verify the installation after mounting.
1813
+ */
1814
+ export function isInteractiveEditorHost(host: EditorHostCapabilities): boolean {
1815
+ if (typeof host.mode === "string") return host.mode === "tui";
1816
+ if (host.mode !== undefined) return false;
1817
+ return host.hasUI === true && host.canInstallEditor === true;
1818
+ }
1819
+
1820
+ /**
1821
+ * Whether streamed responses can be requested from the host's pi-ai module.
1822
+ *
1823
+ * A host that exposes the simple completion API without `streamSimple` must use
1824
+ * the completion path instead of failing every request. When the module exposes
1825
+ * neither function the extension is not running inside a host that maps them,
1826
+ * so streaming support stays unknown and is reported only once a request runs.
1827
+ */
1828
+ export function hostSupportsStreamedResponses(api: {
1829
+ completeSimple?: unknown;
1830
+ streamSimple?: unknown;
1831
+ }): boolean {
1832
+ if (typeof api.streamSimple === "function") return true;
1833
+ return typeof api.completeSimple !== "function";
1834
+ }
package/index.ts CHANGED
@@ -1,12 +1,11 @@
1
- import {
2
- completeSimple,
3
- streamSimple,
4
- type Api,
5
- type AssistantMessage,
6
- type AssistantMessageEventStream,
7
- type Model,
8
- type UserMessage,
9
- } from "@earendil-works/pi-ai/compat";
1
+ import * as piAi from "@earendil-works/pi-ai";
2
+ import type {
3
+ Api,
4
+ AssistantMessage,
5
+ AssistantMessageEventStream,
6
+ Model,
7
+ UserMessage,
8
+ } from "@earendil-works/pi-ai";
10
9
  import { CustomEditor, type ExtensionAPI, type ExtensionContext, type KeybindingsManager } from "@earendil-works/pi-coding-agent";
11
10
  import { matchesKey, truncateToWidth, type EditorTheme, type KeyId, type TUI, visibleWidth } from "@earendil-works/pi-tui";
12
11
  import {
@@ -20,6 +19,7 @@ import {
20
19
  computeRequestMaxTokens,
21
20
  createOwnerRefCounter,
22
21
  createPromptAutocompleteUsageStats,
22
+ describePromptAutocompleteModelSelection,
23
23
  describeSettingSource,
24
24
  DEFAULT_DEBOUNCE_MS,
25
25
  DEFAULT_MAX_ALTERNATIVES,
@@ -33,22 +33,25 @@ import {
33
33
  formatModelLabel,
34
34
  formatPromptAutocompleteStats,
35
35
  formatUsageStats,
36
+ hostSupportsStreamedResponses,
37
+ isInteractiveEditorHost,
36
38
  MAX_DRAFT_CONTEXT_CHARS,
37
39
  normalizePromptSuggestions,
38
40
  parseBoundedIntFlag,
39
- parseModelRef,
40
41
  parsePartialPromptSuggestion,
42
+ parsePromptAutocompleteModelSelection,
41
43
  PROMPT_AUTOCOMPLETE_SYSTEM_PROMPT,
42
44
  recordProviderLatency,
43
45
  recordProviderUsage,
44
46
  resolveOverride,
45
47
  reusePromptAutocompleteSuggestions,
48
+ sanitizeTerminalText,
46
49
  SequenceOwnedSlot,
47
50
  shouldSkipPromptAutocomplete,
48
51
  truncateDraftTail,
49
52
  type CoalescedRequestEntry,
50
53
  type CoalescedRequestSubscription,
51
- type ModelRef,
54
+ type PromptAutocompleteModelSelection,
52
55
  type PromptAutocompleteRuntimeOverrides,
53
56
  type PromptAutocompleteUsageStats,
54
57
  } from "./core.ts";
@@ -60,6 +63,8 @@ const CURSOR_TOKEN = "\x1b[7m \x1b[0m";
60
63
  const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"] as const;
61
64
  const SPINNER_INTERVAL_MS = 80;
62
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;
63
68
  // Inline autocomplete should fail fast instead of inheriting long provider retry/timeout defaults.
64
69
  const REQUEST_TIMEOUT_MS = 8_000;
65
70
  // A compliant provider emits its terminal aborted message immediately, which
@@ -119,7 +124,7 @@ interface PromptAutocompleteConfig {
119
124
  minPromptChars: number;
120
125
  maxSuggestionChars: number;
121
126
  maxAlternatives: number;
122
- preferredModel?: ModelRef;
127
+ modelSelection: PromptAutocompleteModelSelection;
123
128
  }
124
129
 
125
130
  interface PromptAutocompleteCacheEntry {
@@ -148,8 +153,52 @@ interface EditorMountState {
148
153
  installedFactory: EditorFactory;
149
154
  }
150
155
 
151
- type CompleteSimpleFunction = typeof completeSimple;
152
- type StreamSimpleFunction = typeof streamSimple;
156
+ type CompleteSimpleFunction = typeof import("@earendil-works/pi-ai/compat").completeSimple;
157
+ type StreamSimpleFunction = typeof import("@earendil-works/pi-ai/compat").streamSimple;
158
+
159
+ /**
160
+ * Host-neutral access to the simple completion API.
161
+ *
162
+ * Pi aliases the pi-ai root specifier to its compat entrypoint for extensions,
163
+ * and forked hosts based on an older API revision (for example prime-agent)
164
+ * export the same functions from the pi-ai root module. Importing the root
165
+ * specifier therefore works on both, while importing `@earendil-works/pi-ai/compat`
166
+ * fails to resolve on hosts that never mapped that subpath.
167
+ */
168
+ const piAiSimpleApi = piAi as unknown as {
169
+ completeSimple?: CompleteSimpleFunction;
170
+ streamSimple?: StreamSimpleFunction;
171
+ };
172
+
173
+ type SimpleApiFunction = CompleteSimpleFunction | StreamSimpleFunction;
174
+
175
+ function requireSimpleApiFunction<F extends SimpleApiFunction>(
176
+ name: "completeSimple" | "streamSimple",
177
+ impl: F | undefined,
178
+ ): F {
179
+ if (typeof impl !== "function") {
180
+ throw new Error(
181
+ `prompt-autocomplete requires ${name}() from @earendil-works/pi-ai; this host does not provide it`,
182
+ );
183
+ }
184
+ return impl;
185
+ }
186
+
187
+ // Resolved on first use: plain Node test runs resolve the real pi-ai root,
188
+ // which only exposes these functions when the host maps them for extensions.
189
+ const hostCompleteSimple = ((model, context, options) =>
190
+ requireSimpleApiFunction("completeSimple", piAiSimpleApi.completeSimple)(
191
+ model,
192
+ context,
193
+ options,
194
+ )) as CompleteSimpleFunction;
195
+
196
+ const hostStreamSimple = ((model, context, options) =>
197
+ requireSimpleApiFunction("streamSimple", piAiSimpleApi.streamSimple)(
198
+ model,
199
+ context,
200
+ options,
201
+ )) as StreamSimpleFunction;
153
202
 
154
203
  export interface PromptAutocompleteDependencies {
155
204
  completeSimple?: CompleteSimpleFunction;
@@ -175,6 +224,18 @@ interface PromptAutocompleteSharedState {
175
224
  debugState: string;
176
225
  editorMount?: EditorMountState;
177
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>;
231
+ /**
232
+ * Set once a mount attempt proved whether this host installs custom editors.
233
+ *
234
+ * A process cannot change its front-end, so this is deliberately never reset:
235
+ * a host that dropped the editor factory once would drop it again. Restarting
236
+ * the host is the only way to re-probe.
237
+ */
238
+ hostInstallsEditors?: boolean;
178
239
  lastError?: string;
179
240
  lastRawResponse?: string;
180
241
  requestCache: ExpiringLruCache<PromptAutocompleteCacheEntry>;
@@ -294,22 +355,81 @@ function formatPrimaryKey(keys: readonly KeyId[]): string {
294
355
  return keys[0] ?? "";
295
356
  }
296
357
 
297
- function resolveSuggestionModel(shared: PromptAutocompleteSharedState): Model<Api> | undefined {
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 {
298
377
  const registry = shared.modelRegistry;
299
- if (!registry) return undefined;
378
+ if (!registry) return { reason: "No model registry is available yet" };
300
379
 
301
- if (shared.config.preferredModel) {
302
- const preferred = registry.find(shared.config.preferredModel.provider, shared.config.preferredModel.id);
303
- if (preferred && registry.hasConfiguredAuth(preferred)) {
304
- return preferred as Model<Api>;
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
+ }
390
+
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
+ };
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
+ };
305
406
  }
407
+ return { model: preferred as Model<Api> };
306
408
  }
307
409
 
308
410
  if (shared.currentModel && registry.hasConfiguredAuth(shared.currentModel)) {
309
- return shared.currentModel as Model<Api>;
411
+ return { model: shared.currentModel as Model<Api> };
310
412
  }
311
413
 
312
- return undefined;
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");
313
433
  }
314
434
 
315
435
  function parseOnOffFlag(value: boolean | string | undefined, fallback: boolean): boolean {
@@ -340,7 +460,7 @@ function parseConfig(pi: ExtensionAPI): PromptAutocompleteConfig {
340
460
  1,
341
461
  5,
342
462
  ),
343
- preferredModel: parseModelRef(pi.getFlag("prompt-autocomplete-model")),
463
+ modelSelection: parsePromptAutocompleteModelSelection(pi.getFlag("prompt-autocomplete-model")),
344
464
  };
345
465
  }
346
466
 
@@ -367,10 +487,24 @@ function applyEffectiveConfig(pi: ExtensionAPI, shared: PromptAutocompleteShared
367
487
  };
368
488
  }
369
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
+
370
496
  function truncateDebug(text: string, maxLength = 140): string {
371
- const normalized = text.replace(/\s+/g, " ").trim();
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();
372
505
  if (normalized.length <= maxLength) return normalized;
373
- return `${normalized.slice(0, maxLength - 1)}…`;
506
+ // Slicing can split a surrogate pair that sanitization had just repaired.
507
+ return `${truncateAtSafeBoundary(normalized.slice(0, maxLength - 1))}…`;
374
508
  }
375
509
 
376
510
  function updateDebugState(shared: PromptAutocompleteSharedState, state: string, details?: string): void {
@@ -392,15 +526,13 @@ function formatStatus(shared: PromptAutocompleteSharedState): string {
392
526
  : shared.editorBlockedReason
393
527
  ? "blocked"
394
528
  : "unmounted";
395
- const requestedModel = shared.config.preferredModel
396
- ? `${shared.config.preferredModel.provider}/${shared.config.preferredModel.id}`
397
- : "current active model";
529
+ const requestedModel = describePromptAutocompleteModelSelection(shared.config.modelSelection);
398
530
 
399
531
  return [
400
532
  `enabled=${shared.enabled ? "yes" : "no"}(${describeSettingSource(shared.runtimeOverrides.enabled)})`,
401
533
  `editor=${editorState}`,
402
534
  shared.editorBlockedReason ? `editor-blocked=${truncateDebug(shared.editorBlockedReason, 90)}` : undefined,
403
- `model=${formatModelLabel(resolvedModel)}`,
535
+ `model=${truncateDebug(formatModelLabel(resolvedModel), 90)}`,
404
536
  `requested-model=${requestedModel}`,
405
537
  `while-streaming=${shared.config.allowWhileStreaming ? "yes" : "no"}(${describeSettingSource(shared.runtimeOverrides.allowWhileStreaming)})`,
406
538
  `stream=${shared.config.streamResponses ? "yes" : "no"}(${describeSettingSource(shared.runtimeOverrides.streamResponses)})`,
@@ -858,8 +990,11 @@ class PromptAutocompleteEditor extends CustomEditor {
858
990
  if (this.shared.now() < this.suspendedUntil) return "In temporary cooldown after the last error";
859
991
  }
860
992
 
861
- const model = resolveSuggestionModel(this.shared);
862
- if (!model) return "No usable autocomplete model with configured auth was found";
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
+ }
863
998
 
864
999
  const draft = this.getText();
865
1000
  if (!options.manual && draft.trim().length < this.shared.config.minPromptChars) {
@@ -1319,11 +1454,32 @@ function releaseEditorRuntime(shared: PromptAutocompleteSharedState): void {
1319
1454
  shared.setStatusText = undefined;
1320
1455
  shared.setSpinnerActive = undefined;
1321
1456
  shared.clearSpinner = undefined;
1457
+ shared.notify = undefined;
1322
1458
  shared.ownsEditor = undefined;
1323
1459
  }
1324
1460
 
1461
+ /**
1462
+ * Whether this host can hand the prompt editor to the extension.
1463
+ *
1464
+ * Hosts that report `ctx.mode` stay authoritative (only `"tui"` owns the
1465
+ * editor). Hosts from older forks of the extension API omit `mode` entirely, so
1466
+ * UI availability plus a usable editor slot decides instead.
1467
+ */
1468
+ function hostOwnsInteractiveEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): boolean {
1469
+ // A host that already accepted an editor factory without installing it is not
1470
+ // interactive, no matter what its capabilities claim.
1471
+ if (shared.hostInstallsEditors === false) return false;
1472
+ const host = ctx as Partial<Pick<ExtensionContext, "mode" | "hasUI" | "ui">>;
1473
+ return isInteractiveEditorHost({
1474
+ mode: host.mode,
1475
+ hasUI: host.hasUI,
1476
+ canInstallEditor:
1477
+ typeof host.ui?.setEditorComponent === "function" && typeof host.ui?.getEditorComponent === "function",
1478
+ });
1479
+ }
1480
+
1325
1481
  function mountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): boolean {
1326
- if (ctx.mode !== "tui") return false;
1482
+ if (!hostOwnsInteractiveEditor(ctx, shared)) return false;
1327
1483
 
1328
1484
  if (shared.editorMount) {
1329
1485
  if (shared.ownsEditor?.()) return true;
@@ -1344,6 +1500,10 @@ function mountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedStat
1344
1500
  shared.editorBlockedReason = undefined;
1345
1501
  shared.activationId += 1;
1346
1502
  const activationId = shared.activationId;
1503
+ shared.notify = (message, type) => {
1504
+ if (activationId !== shared.activationId) return;
1505
+ ctx.ui.notify(message, type ?? "info");
1506
+ };
1347
1507
  shared.setStatusText = (text) => {
1348
1508
  ctx.ui.setWidget(
1349
1509
  "prompt-autocomplete-debug",
@@ -1420,13 +1580,34 @@ function mountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedStat
1420
1580
  throw error;
1421
1581
  }
1422
1582
 
1583
+ // Some hosts accept the call without installing anything: forked front-ends
1584
+ // (for example prime-agent's RPC mode) expose a no-op editor slot while still
1585
+ // reporting UI availability. Verify the installation instead of trusting it.
1586
+ if (ctx.ui.getEditorComponent() !== installedFactory) {
1587
+ releaseEditorRuntime(shared);
1588
+ shared.editorMount = undefined;
1589
+ shared.hostInstallsEditors = false;
1590
+ // Nothing can render or request here, so the extension must not stay marked
1591
+ // enabled, no matter which path attempted the mount.
1592
+ shared.enabled = false;
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.";
1595
+ const shouldNotify = shared.editorBlockedReason !== reason;
1596
+ shared.editorBlockedReason = reason;
1597
+ updateDebugState(shared, "blocked-no-editor-slot", reason);
1598
+ if (shouldNotify) ctx.ui.notify(reason, "warning");
1599
+ return false;
1600
+ }
1601
+
1602
+ shared.hostInstallsEditors = true;
1423
1603
  updateDebugState(shared, "mounted", "Editor extension attached");
1424
1604
  return true;
1425
1605
  }
1426
1606
 
1427
1607
  function unmountEditor(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): void {
1428
1608
  const mount = shared.editorMount;
1429
- const shouldRestore = ctx.mode === "tui" && !!mount && ctx.ui.getEditorComponent() === mount.installedFactory;
1609
+ const shouldRestore =
1610
+ hostOwnsInteractiveEditor(ctx, shared) && !!mount && ctx.ui.getEditorComponent() === mount.installedFactory;
1430
1611
 
1431
1612
  releaseEditorRuntime(shared);
1432
1613
  shared.editorMount = undefined;
@@ -1441,12 +1622,16 @@ function resetSharedForSession(pi: ExtensionAPI, shared: PromptAutocompleteShare
1441
1622
  shared.cancelActiveRequest?.();
1442
1623
  shared.cancelActiveRequest = undefined;
1443
1624
  applyEffectiveConfig(pi, shared);
1625
+ // A host that never installs custom editors stays inactive for the rest of
1626
+ // the process, so flags must not re-enable it in a later session either.
1627
+ if (shared.hostInstallsEditors === false) shared.enabled = false;
1444
1628
  shared.usageStats = createPromptAutocompleteUsageStats();
1445
1629
  shared.editorMount = undefined;
1446
1630
  shared.editorBlockedReason = undefined;
1447
1631
  shared.ownsEditor = undefined;
1448
1632
  shared.lastError = undefined;
1449
1633
  shared.lastRawResponse = undefined;
1634
+ shared.reportedModelRefusals.clear();
1450
1635
  shared.requestCache.clear();
1451
1636
  shared.prefixReuseCache.clear();
1452
1637
  cancelAllCoalescedRequests(shared.inFlightRequests);
@@ -1540,9 +1725,20 @@ function setStreamResponses(
1540
1725
  }
1541
1726
 
1542
1727
  function enablePromptAutocomplete(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): boolean {
1728
+ const previousOverride = shared.runtimeOverrides.enabled;
1543
1729
  shared.enabled = true;
1544
1730
  shared.runtimeOverrides.enabled = true;
1545
- return mountEditor(ctx, shared);
1731
+
1732
+ if (!mountEditor(ctx, shared) && shared.hostInstallsEditors === false) {
1733
+ // The host accepted the editor factory without installing it. mountEditor
1734
+ // already cleared `enabled`; keep it cleared and drop the session override
1735
+ // so the refused activation is not replayed as a user decision later.
1736
+ shared.enabled = false;
1737
+ shared.runtimeOverrides.enabled = previousOverride;
1738
+ return false;
1739
+ }
1740
+
1741
+ return shared.editorMount !== undefined;
1546
1742
  }
1547
1743
 
1548
1744
  function disablePromptAutocomplete(ctx: ExtensionContext, shared: PromptAutocompleteSharedState): void {
@@ -1553,6 +1749,8 @@ function disablePromptAutocomplete(ctx: ExtensionContext, shared: PromptAutocomp
1553
1749
  shared.prefixReuseCache.clear();
1554
1750
  shared.lastRawResponse = undefined;
1555
1751
  shared.lastError = undefined;
1752
+ // Re-enabling must be able to report a refused model again.
1753
+ shared.reportedModelRefusals.clear();
1556
1754
  }
1557
1755
 
1558
1756
  function notifyPromptAutocompleteEnabled(
@@ -1564,13 +1762,27 @@ function notifyPromptAutocompleteEnabled(
1564
1762
  `Tab accepts all, ${formatPrimaryKey(WORD_ACCEPT_KEYS)} accepts one word, ` +
1565
1763
  `${formatPrimaryKey(CYCLE_PREV_KEYS)}/${formatPrimaryKey(CYCLE_NEXT_KEYS)} cycle alternatives, ` +
1566
1764
  `${formatPrimaryKey(CYCLE_NEXT_KEYS)} also forces a one-shot suggestion when none is shown (even while the agent works).`;
1567
- const resolvedModel = resolveSuggestionModel(shared);
1765
+ const resolution = resolveSuggestionModelResolution(shared);
1766
+ const resolvedModel = resolution.model;
1568
1767
  const privacyNotice = "Requests send the current draft and recent conversation context to the selected model and may incur provider usage.";
1569
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
+
1570
1782
  if (options.includeModel) {
1571
1783
  if (resolvedModel) {
1572
1784
  ctx.ui.notify(
1573
- `Prompt autocomplete enabled. ${keyHint} Model: ${formatModelLabel(resolvedModel)} ${privacyNotice}`,
1785
+ `Prompt autocomplete enabled. ${keyHint} Model: ${truncateDebug(formatModelLabel(resolvedModel), 90)} ${privacyNotice}`,
1574
1786
  "info",
1575
1787
  );
1576
1788
  } else {
@@ -1654,10 +1866,13 @@ function createPromptAutocompleteCommandHandlers(
1654
1866
  export function createPromptAutocompleteExtension(
1655
1867
  dependencies: PromptAutocompleteDependencies = {},
1656
1868
  ): (pi: ExtensionAPI) => void {
1657
- const completeSimpleImpl = dependencies.completeSimple ?? completeSimple;
1869
+ const completeSimpleImpl = dependencies.completeSimple ?? hostCompleteSimple;
1870
+ const hostStreaming = hostSupportsStreamedResponses(piAiSimpleApi);
1658
1871
  // Existing deterministic harnesses inject only completeSimple. Never let such
1659
1872
  // a harness fall through to the real network-capable stream implementation.
1660
- const streamSimpleImpl = dependencies.streamSimple ?? (dependencies.completeSimple ? undefined : streamSimple);
1873
+ const streamSimpleImpl =
1874
+ dependencies.streamSimple
1875
+ ?? (dependencies.completeSimple || !hostStreaming ? undefined : hostStreamSimple);
1661
1876
  const now = dependencies.now ?? Date.now;
1662
1877
 
1663
1878
  return function promptAutocompleteExtension(pi: ExtensionAPI): void {
@@ -1723,6 +1938,7 @@ export function createPromptAutocompleteExtension(
1723
1938
  requestCache: new ExpiringLruCache(REQUEST_CACHE_TTL_MS, REQUEST_CACHE_MAX_ENTRIES, now),
1724
1939
  prefixReuseCache: new ExpiringLruCache(REQUEST_CACHE_TTL_MS, REQUEST_CACHE_MAX_ENTRIES, now),
1725
1940
  inFlightRequests: new Map(),
1941
+ reportedModelRefusals: new Set(),
1726
1942
  };
1727
1943
 
1728
1944
  pi.on("session_start", async (_event, ctx) => {
@@ -1732,7 +1948,7 @@ export function createPromptAutocompleteExtension(
1732
1948
  resetSharedForSession(pi, shared);
1733
1949
  bindRuntimeContext(ctx, shared);
1734
1950
 
1735
- if (ctx.mode !== "tui" || !shared.enabled) return;
1951
+ if (!hostOwnsInteractiveEditor(ctx, shared) || !shared.enabled) return;
1736
1952
  mountEditor(ctx, shared);
1737
1953
  });
1738
1954
 
@@ -1774,7 +1990,7 @@ export function createPromptAutocompleteExtension(
1774
1990
  pi.registerCommand("prompt-autocomplete", {
1775
1991
  description: "Enable, disable, or inspect inline prompt autocomplete and session stats",
1776
1992
  handler: async (args, ctx) => {
1777
- if (ctx.mode !== "tui") {
1993
+ if (!hostOwnsInteractiveEditor(ctx, shared)) {
1778
1994
  ctx.ui.notify("prompt-autocomplete requires interactive TUI mode", "warning");
1779
1995
  return;
1780
1996
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kliebhan/pi-prompt-autocomplete",
3
- "version": "0.2.0",
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.0/prompt-autocomplete-demo.mp4"
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"