@kliebhan/pi-prompt-autocomplete 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,12 @@
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.5.0] - 2026-11-17
6
+
7
+ ### Added
8
+
9
+ - RPC-only `/prompt-autocomplete complete <json>` returns a normalized draft continuation through the `prompt-autocomplete-completion` widget. Host-supplied conversation context uses the existing bounds; requests reuse model selection, cache, budget, and stats. Superseded requests are aborted and receive one null reply. Neither ghost text nor next-prompt mode needs to be enabled.
10
+
5
11
  ## [0.4.0] - 2026-11-12
6
12
 
7
13
  ### 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.4.0/prompt-autocomplete-demo.mp4)
5
+ [Watch the demo](https://github.com/KLIEBHAN/pi-extensions/releases/download/pi-prompt-autocomplete-v0.5.0/prompt-autocomplete-demo.mp4)
6
6
 
7
7
  ## Install
8
8
 
@@ -147,6 +147,20 @@ Budget: 4/25 (session)
147
147
  - Without draft text the report covers the conversation sections only. The slash command replaced the editor text when you submitted it, so the draft a real request would carry cannot be recovered and is not invented; pass one explicitly to preview a complete request. Pi trims trailing whitespace from submitted commands.
148
148
  - `Shared policy` evaluates only the gates every editor shares — enabled state, editor ownership, the main-agent gate, model and auth, `min-chars` and slash/path detection for the given draft, and the session budget — separately for automatic requests and the manual `Ctrl+.` one-shot. Cursor position, the built-in autocomplete menu, Escape dismissal, the per-editor error cooldown, and cached responses belong to the live editor and are not evaluated.
149
149
 
150
+ ### Draft completion for RPC hosts
151
+
152
+ An RPC host can request a continuation even while the agent is busy, without enabling ghost text or next-prompt suggestions:
153
+
154
+ ```sh
155
+ pi --mode rpc --no-session --no-tools --prompt-autocomplete-model provider/model
156
+ ```
157
+
158
+ Send an RPC `prompt` with message `/prompt-autocomplete complete <json>`. The JSON is `{"id":"unique-request-id","draft":"Write","context":{"lastUser":"…","lastAssistant":"…"}}`; `context` and both of its fields are optional. Supply the host thread's latest messages when the sidecar has no session. They use the existing bounded conversation snapshot, not the sidecar's conversation.
159
+
160
+ Each request receives one fire-and-forget `ctx.ui.setWidget("prompt-autocomplete-completion", [JSON.stringify(result)])`, where `result` is `{"id":"unique-request-id","completion":" the tests"}`. The completion is text to **append**, normalized like ghost text, first alternative only and bounded by `max-chars`. It is `null` for short drafts, exhausted budgets, unusable output, superseded requests, or errors; errors also carry a short, sanitized `error` string. Malformed requests with a string `id` receive an error; invalid JSON or missing/non-string ids cannot be correlated and receive no widget.
161
+
162
+ Use a unique id per request. A new request aborts the previous one and immediately replies `null` for its id, even if the provider is slow to stop. Requests share model selection, result cache, request budget, and stats with the existing path. This command does not write editor text or cancel next-prompt requests. It is RPC-only and omitted from argument completions.
163
+
150
164
  ### Next prompt for RPC hosts (T3 Code)
151
165
 
152
166
  With `--prompt-autocomplete-next-prompt`, Pi in RPC mode predicts your next prompt after each settled turn and sends it to the host with `set_editor_text` (`ctx.ui.setEditorText`). The host decides what to do with it. Upstream T3 Code ignores the call; the T3 Code branch [`KLIEBHAN/t3code@pi-prompt-suggestions`](https://github.com/KLIEBHAN/t3code/tree/pi-prompt-suggestions) shows it as the suggested next prompt when **Suggest next prompt** is on in Settings > Labs.
@@ -180,8 +194,8 @@ The extension makes no autocomplete request while disabled. Automatic empty-draf
180
194
  - Supported baseline: Pi `0.80.6`, Node.js `22.19.0` or newer.
181
195
  - Every release is verified against Pi `0.80.6`, `0.83.0`, `1.2.0`, and `1.5.2`. Pi 1.x draws the editor cursor through fake-cursor markers instead of inverse video; ghost text supports both forms.
182
196
  - On hosts that expose Pi's model-visible session projection (Pi 1.x), autocomplete context follows it: a message that `context_edit` omitted or replaced, for example to redact it, is omitted or replaced in autocomplete requests too. If that projection fails, requests carry no conversation context rather than the raw history. Besides user and assistant message text, autocomplete sends only the newest compaction summary, so suggestions keep the summarized background after a compaction; custom messages, tool results, and the compaction's system checkpoint are not sent.
183
- - Interactive ghost text requires Pi's TUI mode. RPC, JSON, and print modes do not install a custom editor and never reach a provider, except RPC mode with [`--prompt-autocomplete-next-prompt`](#next-prompt-for-rpc-hosts-t3-code).
184
- - The read-only commands `status`, `stats`, and `inspect` also work on hosts that can show notifications, such as RPC; there `status` reports `host=non-interactive` and `editor=unavailable`. Every command that changes state or touches the editor stays TUI-only. If the extension is enabled on such a host, it says once per process that no autocomplete request will be issued.
197
+ - Interactive ghost text requires Pi's TUI mode. RPC, JSON, and print modes do not install a custom editor and never reach a provider, except RPC [draft completion](#draft-completion-for-rpc-hosts) and [`--prompt-autocomplete-next-prompt`](#next-prompt-for-rpc-hosts-t3-code).
198
+ - The read-only commands `status`, `stats`, and `inspect` also work on hosts that can show notifications, such as RPC; there `status` reports `host=non-interactive` and `editor=unavailable`. Except for RPC draft completion, every command that changes state or touches the editor stays TUI-only. If the extension is enabled on such a host, it says once per process that no autocomplete request will be issued.
185
199
  - 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.
186
200
  - On Pi 1.x, requests go through the session's model registry, which resolves each provider's stored credential itself. Models from providers that other extensions register therefore work as well, as do OAuth credentials that derive their own endpoint (such as GitHub Copilot Enterprise) and header-only or ambient credentials. Older hosts use the simple completion API below and need an API key.
187
201
  - 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.
package/index.ts CHANGED
@@ -583,6 +583,7 @@ interface PromptAutocompleteSharedState {
583
583
  cancelScheduledRequest?: () => void;
584
584
  /** The running next-prompt request; a new turn or session makes it stale. */
585
585
  nextPromptAbort?: AbortController;
586
+ draftCompletionAbort?: AbortController;
586
587
  setStatusText?: (text: string | undefined) => void;
587
588
  setSpinnerActive?: (owner: string, active: boolean) => void;
588
589
  clearSpinner?: () => void;
@@ -2497,13 +2498,19 @@ function buildSuggestionRequest(
2497
2498
  draft: string,
2498
2499
  activationId: number,
2499
2500
  maxAlternatives = shared.config.maxAlternatives,
2501
+ contextBranch?: unknown[],
2500
2502
  ): SuggestionRequest | undefined {
2501
2503
  const model = resolveSuggestionModel(shared);
2502
2504
  if (!model) return undefined;
2503
2505
 
2504
2506
  const conversationId = resolveCurrentConversationId(shared);
2505
2507
  shared.lastConversationId = conversationId;
2506
- const snapshot = buildCurrentRequestSnapshot(shared, draft, conversationId, maxAlternatives);
2508
+ const snapshot = contextBranch === undefined
2509
+ ? buildCurrentRequestSnapshot(shared, draft, conversationId, maxAlternatives)
2510
+ : buildPromptAutocompleteRequestSnapshot({
2511
+ draft, branch: contextBranch, maxAlternatives,
2512
+ maxSuggestionChars: shared.config.maxSuggestionChars,
2513
+ });
2507
2514
  const modelLabel = formatModelLabel(model);
2508
2515
 
2509
2516
  const prefixContextIdentity = {
@@ -2635,6 +2642,72 @@ async function suggestNextPrompt(ctx: ExtensionContext, shared: PromptAutocomple
2635
2642
  }
2636
2643
  }
2637
2644
 
2645
+ /** RPC-only request/reply adapter; provider errors never cross the host boundary. */
2646
+ async function completeRpcDraft(ctx: ExtensionContext, shared: PromptAutocompleteSharedState, payload: string): Promise<void> {
2647
+ if (ctx.mode !== "rpc") {
2648
+ ctx.ui.notify("prompt-autocomplete complete is for RPC hosts", "warning");
2649
+ return;
2650
+ }
2651
+ shared.draftCompletionAbort?.abort();
2652
+ let value: unknown;
2653
+ try { value = JSON.parse(payload); } catch { return; }
2654
+ if (!value || typeof value !== "object" || !("id" in value) || typeof value.id !== "string") return;
2655
+ const id = value.id;
2656
+ const controller = new AbortController();
2657
+ shared.draftCompletionAbort = controller;
2658
+ let replied = false;
2659
+ const reply = (completion: string | null, error?: string) => {
2660
+ if (replied) return;
2661
+ replied = true;
2662
+ ctx.ui.setWidget("prompt-autocomplete-completion", [JSON.stringify({ id, completion, ...(error ? { error } : {}) })]);
2663
+ };
2664
+ const onAbort = () => reply(null);
2665
+ controller.signal.addEventListener("abort", onAbort, { once: true });
2666
+ try {
2667
+ if (!("draft" in value) || typeof value.draft !== "string") {
2668
+ reply(null, "Invalid completion request");
2669
+ return;
2670
+ }
2671
+ const context = "context" in value ? value.context : undefined;
2672
+ const branch: unknown[] = [];
2673
+ if (context !== undefined) {
2674
+ if (!context || typeof context !== "object" || Array.isArray(context)) {
2675
+ reply(null, "Invalid completion context");
2676
+ return;
2677
+ }
2678
+ for (const [key, role] of [["lastUser", "user"], ["lastAssistant", "assistant"]] as const) {
2679
+ const text = key === "lastUser"
2680
+ ? ("lastUser" in context ? context.lastUser : undefined)
2681
+ : ("lastAssistant" in context ? context.lastAssistant : undefined);
2682
+ if (text !== undefined && typeof text !== "string") {
2683
+ reply(null, "Invalid completion context");
2684
+ return;
2685
+ }
2686
+ if (text) branch.push({ type: "message", message: { role, content: text } });
2687
+ }
2688
+ }
2689
+ if (value.draft.trim().length < shared.config.minPromptChars) {
2690
+ reply(null);
2691
+ return;
2692
+ }
2693
+ const request = buildSuggestionRequest(shared, value.draft, shared.activationId, 1, branch);
2694
+ if (!request) {
2695
+ reply(null, "Completion model unavailable");
2696
+ return;
2697
+ }
2698
+ let entry = getCachedRequest(shared, request.cacheKey);
2699
+ if (entry) shared.usageStats.cacheHits += 1;
2700
+ else entry = await fetchSuggestionUncached(shared, { ...request, useStreaming: false }, controller.signal, () => undefined);
2701
+ reply(controller.signal.aborted ? null : entry.suggestions[0] ?? null);
2702
+ } catch (error) {
2703
+ reply(null, controller.signal.aborted || error instanceof PromptAutocompleteBudgetExhaustedError
2704
+ ? undefined : "Completion request failed");
2705
+ } finally {
2706
+ controller.signal.removeEventListener("abort", onAbort);
2707
+ if (shared.draftCompletionAbort === controller) shared.draftCompletionAbort = undefined;
2708
+ }
2709
+ }
2710
+
2638
2711
  function cancelNextPrompt(shared: PromptAutocompleteSharedState): void {
2639
2712
  shared.nextPromptAbort?.abort();
2640
2713
  shared.nextPromptAbort = undefined;
@@ -3557,6 +3630,8 @@ export function createPromptAutocompleteExtension(
3557
3630
 
3558
3631
  pi.on("session_shutdown", async (_event, ctx) => {
3559
3632
  // Teardown, not a user decision: leave runtimeOverrides untouched.
3633
+ shared.draftCompletionAbort?.abort();
3634
+ shared.draftCompletionAbort = undefined;
3560
3635
  shared.enabled = false;
3561
3636
  shared.cancelActiveRequest?.();
3562
3637
  cancelNextPrompt(shared);
@@ -3613,6 +3688,10 @@ export function createPromptAutocompleteExtension(
3613
3688
  // must keep its leading and trailing whitespace to match production.
3614
3689
  const payload = space < 0 ? "" : commandStart.slice(space + 1);
3615
3690
  const rest = payload.trim();
3691
+ if (name === "complete") {
3692
+ await completeRpcDraft(ctx, shared, payload);
3693
+ return;
3694
+ }
3616
3695
  const spec = findPromptAutocompleteCommand(name);
3617
3696
 
3618
3697
  // Reporting works wherever a notification can be shown; anything that
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kliebhan/pi-prompt-autocomplete",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
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.4.0/prompt-autocomplete-demo.mp4"
29
+ "video": "https://github.com/KLIEBHAN/pi-extensions/releases/download/pi-prompt-autocomplete-v0.5.0/prompt-autocomplete-demo.mp4"
30
30
  },
31
31
  "engines": {
32
32
  "node": ">=22.19.0"