@ldelossa/pi-ide 0.1.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,10 +1,11 @@
1
1
  # pi-ide
2
2
 
3
3
  Connects a Pi coding-agent session to a running editor over a local
4
- WebSocket MCP server. Provides ambient editor context (current file, cursor,
5
- selection) and routes `write`/`edit` tool calls through the editor as
6
- interactive diffs. The wireformat is compatible with Claude Code's editor
7
- integration.
4
+ WebSocket MCP server. Provides ambient editor context (current file,
5
+ cursor, selection), routes `write`/`edit` tool calls through the editor
6
+ as interactive diffs, and serves inline code completions (often called
7
+ "suggestions") to editors that request them. The wireformat is compatible
8
+ with Claude Code's editor integration.
8
9
 
9
10
  ## Install
10
11
 
@@ -166,6 +167,88 @@ enter, and text change. Debounce locally (~100ms recommended).
166
167
  Lines and characters are zero-based. The extension renders line numbers as
167
168
  1-based.
168
169
 
170
+ ## Editor-initiated requests
171
+
172
+ The editor may send JSON-RPC requests to the extension over the same
173
+ WebSocket. The extension processes them and returns responses.
174
+
175
+ ### Request: `getSuggestions`
176
+
177
+ Returns inline code completions for the editor to render as ghost text or
178
+ equivalent. The extension calls the configured model (current session
179
+ model by default; see model precedence below), parses up to 3
180
+ `<SUGGESTION>...</SUGGESTION>` blocks from the response, and returns them.
181
+
182
+ Input:
183
+
184
+ | field | type | description |
185
+ | ----------------- | ------ | -------------------------------------------- |
186
+ | `filePath` | string | optional. absolute path of the cursor file |
187
+ | `language` | string | optional. filetype or language id |
188
+ | `outline` | string | optional. structural sketch of the file |
189
+ | `enclosingScope` | string | optional. surrounding function or class |
190
+ | `cursorBefore` | string | text before cursor (typically ~20 lines) |
191
+ | `cursorAfter` | string | text after cursor (typically ~10 lines) |
192
+ | `suggestionCount` | int | optional. cap on returned alternatives. Max 3. |
193
+ | `model` | string | optional. preferred model "provider/id". CLI flag wins if set. |
194
+
195
+ `outline` is whatever structural sketch the editor produces with its native
196
+ source-analysis tool — treesitter sexpr (Neovim), document symbols from
197
+ LSP (VS Code), PSI tree (JetBrains), or omitted entirely. The model accepts
198
+ any text. Completion quality scales with the amount of structural context
199
+ provided. The minimal viable payload is `cursorBefore` and `cursorAfter`.
200
+
201
+ Response:
202
+
203
+ ```
204
+ { "suggestions": ["<text>", ...] }
205
+ ```
206
+
207
+ Empty `suggestions` is valid and means the model declined to complete.
208
+
209
+ Cancellation: editor sends `request_cancelled` notification with
210
+ `{ "id": <request id> }`. The extension aborts the in-flight model call.
211
+
212
+ Model precedence: the CLI flag (`--pi-ide-suggestion-model <provider>/<id>`)
213
+ wins. Otherwise the editor-provided `model` field is used. If neither is
214
+ set, the current session's model is used.
215
+
216
+ To find valid `provider/id` strings, run `pi --list-models` and join the
217
+ `provider` and `model` columns with a `/` (e.g., `openai/gpt-4o`).
218
+
219
+ For suggestions, prefer low-latency models. Large reasoning models often
220
+ feel too slow for inline completion; smaller coding-capable models such as
221
+ `openai-codex/gpt-5.4-mini` or `deepseek/deepseek-v4-flash` usually provide
222
+ a better interactive experience.
223
+
224
+ ### Request: `listSuggestionModels`
225
+
226
+ Returns models available to the current pi session for runtime suggestion
227
+ model selection in editors. The extension is the source of truth for model
228
+ discovery; editors should not read pi config files directly.
229
+
230
+ Input: none.
231
+
232
+ Response:
233
+
234
+ ```
235
+ {
236
+ "cliOverride": "<provider/id>", // optional. --pi-ide-suggestion-model is active
237
+ "currentModel": "<provider/id>", // optional. current pi session model
238
+ "models": [
239
+ { "provider": "openai", "id": "gpt-4o", "name": "GPT-4o", "model": "openai/gpt-4o" }
240
+ ]
241
+ }
242
+ ```
243
+
244
+ If `cliOverride` is present, editor-provided model selections are still
245
+ accepted by the editor but will not affect suggestions because the CLI flag
246
+ has higher precedence.
247
+
169
248
  ## Reference editor implementation
170
249
 
171
- Neovim: `pi-ide.nvim`.
250
+ Neovim: `pi-ide.nvim`. Implements both the editor-side contract (diffs,
251
+ diagnostics, selection notifications) and the `getSuggestions` client.
252
+ Suggestions always work; treesitter and LSP enrich the context but are
253
+ not required — the feature degrades gracefully to cursor-window-only
254
+ context when either is unavailable.
package/client.ts CHANGED
@@ -84,15 +84,27 @@ export function matchesCwd(lockfile: Lockfile, cwd: string): boolean {
84
84
  }
85
85
 
86
86
  export type NotificationHandler = (method: string, params: unknown) => void;
87
+ export type RequestHandler = (params: unknown, signal: AbortSignal) => Promise<unknown>;
87
88
 
88
89
  export class IdeClient {
89
90
  private ws: WebSocket | null = null;
90
91
  private closed = false;
91
92
  public readonly lockfile: Lockfile;
92
93
  private pending = new Map<string, Pending>();
94
+ private requestHandlers = new Map<string, RequestHandler>();
95
+ private inboundAborts = new Map<string, AbortController>();
96
+ // Ids that were cancelled before their handler started. Pruned on dispatch.
97
+ // Capped so a server that emits stray cancels can't grow this without bound;
98
+ // oldest entries are evicted first.
99
+ private earlyCancels = new Set<string>();
100
+ private static EARLY_CANCEL_CAP = 50;
93
101
  public onNotification: NotificationHandler = () => {};
94
102
  public onClose: () => void = () => {};
95
103
 
104
+ onRequest(method: string, handler: RequestHandler): void {
105
+ this.requestHandlers.set(method, handler);
106
+ }
107
+
96
108
  constructor(lockfile: Lockfile) {
97
109
  this.lockfile = lockfile;
98
110
  }
@@ -158,31 +170,101 @@ export class IdeClient {
158
170
  }
159
171
 
160
172
  private handleMessage(text: string): void {
161
- let msg: { id?: string; method?: string; params?: unknown; result?: unknown; error?: { code: number; message: string } };
173
+ let msg: {
174
+ id?: string | number;
175
+ method?: string;
176
+ params?: unknown;
177
+ result?: unknown;
178
+ error?: { code: number; message: string };
179
+ };
162
180
  try {
163
181
  msg = JSON.parse(text);
164
182
  } catch {
165
183
  return;
166
184
  }
167
- if (msg.id !== undefined) {
168
- const pending = this.pending.get(msg.id);
185
+ // Response to a request we sent: has id and no method.
186
+ if (msg.id !== undefined && typeof msg.method !== "string") {
187
+ const pending = this.pending.get(String(msg.id));
169
188
  if (!pending) return;
170
- this.pending.delete(msg.id);
189
+ this.pending.delete(String(msg.id));
171
190
  if (msg.error) pending.reject(new Error(`${msg.error.code}: ${msg.error.message}`));
172
191
  else pending.resolve(msg.result);
173
192
  return;
174
193
  }
194
+ // Inbound request from server: has both id and method.
195
+ if (msg.id !== undefined && typeof msg.method === "string") {
196
+ void this.handleInboundRequest(msg.id, msg.method, msg.params);
197
+ return;
198
+ }
175
199
  if (typeof msg.method === "string") {
200
+ if (msg.method === "request_cancelled") {
201
+ const params = msg.params as { id?: string | number } | undefined;
202
+ const id = params?.id;
203
+ if (id !== undefined) {
204
+ const key = String(id);
205
+ const ac = this.inboundAborts.get(key);
206
+ if (ac) {
207
+ ac.abort();
208
+ } else {
209
+ if (this.earlyCancels.size >= IdeClient.EARLY_CANCEL_CAP) {
210
+ const oldest = this.earlyCancels.values().next().value;
211
+ if (oldest !== undefined) this.earlyCancels.delete(oldest);
212
+ }
213
+ this.earlyCancels.add(key);
214
+ }
215
+ }
216
+ return;
217
+ }
176
218
  this.onNotification(msg.method, msg.params);
177
219
  }
178
220
  }
179
221
 
222
+ private async handleInboundRequest(id: string | number, method: string, params: unknown): Promise<void> {
223
+ const key = String(id);
224
+ const handler = this.requestHandlers.get(method);
225
+ if (!handler) {
226
+ this.sendRaw({
227
+ jsonrpc: "2.0",
228
+ id,
229
+ error: { code: -32601, message: `Method not found: ${method}` },
230
+ });
231
+ return;
232
+ }
233
+ if (this.earlyCancels.delete(key)) {
234
+ this.sendRaw({
235
+ jsonrpc: "2.0",
236
+ id,
237
+ error: { code: -32800, message: "Request cancelled" },
238
+ });
239
+ return;
240
+ }
241
+ const ac = new AbortController();
242
+ this.inboundAborts.set(key, ac);
243
+ try {
244
+ const result = await handler(params, ac.signal);
245
+ this.sendRaw({ jsonrpc: "2.0", id, result });
246
+ } catch (err) {
247
+ const message = err instanceof Error ? err.message : String(err);
248
+ const code = ac.signal.aborted ? -32800 : -32603;
249
+ this.sendRaw({ jsonrpc: "2.0", id, error: { code, message } });
250
+ } finally {
251
+ this.inboundAborts.delete(key);
252
+ }
253
+ }
254
+
255
+ private sendRaw(message: unknown): void {
256
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;
257
+ this.ws.send(JSON.stringify(message));
258
+ }
259
+
180
260
  private handleClose(): void {
181
261
  if (this.closed) return;
182
262
  this.closed = true;
183
263
  const err = new Error("IDE connection closed");
184
264
  for (const pending of this.pending.values()) pending.reject(err);
185
265
  this.pending.clear();
266
+ for (const ac of this.inboundAborts.values()) ac.abort();
267
+ this.inboundAborts.clear();
186
268
  this.ws = null;
187
269
  this.onClose();
188
270
  }
package/index.ts CHANGED
@@ -1,22 +1,75 @@
1
- import { readFile } from "node:fs/promises";
1
+ import { appendFile, readFile } from "node:fs/promises";
2
2
  import { basename, resolve as resolvePath } from "node:path";
3
- import { isToolCallEventType, type ExtensionAPI, type ExtensionUIContext } from "@earendil-works/pi-coding-agent";
3
+ import { completeSimple } from "@earendil-works/pi-ai";
4
+ import {
5
+ isToolCallEventType,
6
+ type ExtensionAPI,
7
+ type ExtensionContext,
8
+ type ExtensionUIContext,
9
+ } from "@earendil-works/pi-coding-agent";
4
10
  import { IdeClient, isPidAlive, isPortListening, listLockfiles, type Lockfile, matchesCwd } from "./client.ts";
5
11
 
12
+ const SUGGESTION_FLAG = "pi-ide-suggestion-model";
13
+ const SUGGESTION_DEBUG_LOG_FLAG = "pi-ide-suggestion-debug-log";
14
+ const SUGGESTION_SYSTEM_PROMPT = `You are an inline code completion engine. Output up to N alternative completions for what should appear at the cursor position. Each must be wrapped in <SUGGESTION>...</SUGGESTION> tags. Order most-likely first.
15
+
16
+ Rules:
17
+ 1. Output ONLY the code to insert. Do not repeat code before or after the cursor.
18
+ 2. Match the file's existing indentation, naming, and style.
19
+ 3. When the cursor is inside a comment, continue the current comment line from <CURSOR>. Do not start a new comment line or repeat the comment marker.
20
+ 4. When the cursor is on an empty line immediately following a descriptive comment, provide a multi-line implementation that fulfills the comment's intent.
21
+ 5. When the cursor follows existing code on the line, complete only the current statement. Do not add new statements, blocks, or functions.
22
+ 6. If mid-token, complete that token first.
23
+ 7. If you have only one strong completion, output one block.
24
+ 8. If nothing reasonable, output zero blocks.`;
25
+
6
26
  type Selection = { startLine: number; endLine: number; text: string };
7
27
  type EditorState = { filePath: string | null; cursorLine: number | null; selection: Selection | null };
8
28
 
9
29
  const MAX_SELECTION_LINES = 100;
10
30
  const WIDGET_KEY = "pi-ide";
31
+ const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
32
+ const SPINNER_INTERVAL_MS = 80;
11
33
 
12
34
  let client: IdeClient | null = null;
13
35
  let state: EditorState = { filePath: null, cursorLine: null, selection: null };
14
36
  let ui: ExtensionUIContext | null = null;
37
+ let sessionCtx: ExtensionContext | null = null;
38
+ let inFlightSuggestions = 0;
39
+ let spinnerTimer: ReturnType<typeof setInterval> | null = null;
40
+ let spinnerFrame = 0;
41
+
42
+ function disconnectFromIde(): void {
43
+ if (!client) return;
44
+ const old = client;
45
+ client = null;
46
+ old.close();
47
+ resetState();
48
+ inFlightSuggestions = 0;
49
+ stopSpinner();
50
+ renderWidget();
51
+ }
15
52
 
16
53
  function resetState(): void {
17
54
  state = { filePath: null, cursorLine: null, selection: null };
18
55
  }
19
56
 
57
+ function startSpinner(): void {
58
+ if (spinnerTimer) return;
59
+ spinnerTimer = setInterval(() => {
60
+ spinnerFrame = (spinnerFrame + 1) % SPINNER.length;
61
+ renderWidget();
62
+ }, SPINNER_INTERVAL_MS);
63
+ }
64
+
65
+ function stopSpinner(): void {
66
+ if (spinnerTimer) {
67
+ clearInterval(spinnerTimer);
68
+ spinnerTimer = null;
69
+ }
70
+ spinnerFrame = 0;
71
+ }
72
+
20
73
  function renderWidget(): void {
21
74
  if (!ui) return;
22
75
  if (!client?.isConnected()) {
@@ -32,6 +85,9 @@ function renderWidget(): void {
32
85
  } else {
33
86
  body = ideName;
34
87
  }
88
+ if (inFlightSuggestions > 0) {
89
+ body += ` · Suggesting ${SPINNER[spinnerFrame]}`;
90
+ }
35
91
  ui.setWidget(WIDGET_KEY, [body]);
36
92
  }
37
93
 
@@ -130,12 +186,252 @@ function applyEdits(original: string, edits: { oldText: string; newText: string
130
186
  return result;
131
187
  }
132
188
 
189
+ type SuggestionParams = {
190
+ filePath?: string;
191
+ language?: string;
192
+ outline?: string;
193
+ enclosingScope?: string;
194
+ cursorBefore?: string;
195
+ cursorAfter?: string;
196
+ suggestionCount?: number;
197
+ cursorInComment?: boolean;
198
+ // Editor-provided model preference, format "provider/id". The CLI flag
199
+ // (--pi-ide-suggestion-model) wins when both are set.
200
+ model?: string;
201
+ };
202
+
203
+ function lastLines(text: string, count: number): string {
204
+ const lines = text.split("\n");
205
+ return lines.slice(Math.max(0, lines.length - count)).join("\n");
206
+ }
207
+
208
+ function firstLines(text: string, count: number): string {
209
+ return text.split("\n").slice(0, count).join("\n");
210
+ }
211
+
212
+ function buildSuggestionPrompt(params: SuggestionParams): string {
213
+ const filePath = params.filePath ?? "<unknown>";
214
+ const language = params.language ?? "<unknown>";
215
+ const before = params.cursorBefore ?? "";
216
+ const after = params.cursorAfter ?? "";
217
+ const count = params.suggestionCount ?? 3;
218
+ if (params.cursorInComment) {
219
+ return `File: ${filePath}
220
+ Language: ${language}
221
+
222
+ The cursor is inside a comment. Continue only the current comment line from <CURSOR>.
223
+ Do not generate code. Do not start a new comment line. Do not repeat a comment marker or existing comment text.
224
+
225
+ <cursor_context>
226
+ ${lastLines(before, 8)}<CURSOR>${firstLines(after, 4)}␃
227
+ </cursor_context>
228
+
229
+ Provide up to ${count} suggestions.`;
230
+ }
231
+ const outline = params.outline?.trim() ? params.outline : "(none)";
232
+ const enclosing = params.enclosingScope?.trim() ? params.enclosingScope : "(none)";
233
+ return `File: ${filePath}
234
+ Language: ${language}
235
+
236
+ <file_outline>
237
+ ${outline}
238
+ </file_outline>
239
+
240
+ <enclosing_scope>
241
+ ${enclosing}
242
+ </enclosing_scope>
243
+
244
+ <cursor_context>
245
+ ${before}<CURSOR>${after}␃
246
+ </cursor_context>
247
+
248
+ Provide up to ${count} suggestions.`;
249
+ }
250
+
251
+ function parseSuggestionBlocks(text: string): string[] {
252
+ const out: string[] = [];
253
+ const re = /<SUGGESTION>([\s\S]*?)<\/SUGGESTION>/g;
254
+ let m: RegExpExecArray | null;
255
+ while ((m = re.exec(text)) !== null) {
256
+ out.push(m[1].replace(/^\n+/, "").replace(/\n+$/, ""));
257
+ }
258
+ if (out.length === 0) {
259
+ // Salvage an unclosed trailing <SUGGESTION> when the LLM hit maxTokens
260
+ // before emitting the closing tag.
261
+ const open = text.lastIndexOf("<SUGGESTION>");
262
+ if (open !== -1 && text.indexOf("</SUGGESTION>", open) === -1) {
263
+ const tail = text.slice(open + "<SUGGESTION>".length).replace(/^\n+/, "").trimEnd();
264
+ if (tail) out.push(tail);
265
+ }
266
+ }
267
+ return out;
268
+ }
269
+
270
+ async function logSuggestionDebug(
271
+ pi: ExtensionAPI,
272
+ entry: {
273
+ model: string;
274
+ params: SuggestionParams;
275
+ userText: string;
276
+ rawText: string;
277
+ parsedBlocks: string[];
278
+ returnedSuggestions: string[];
279
+ },
280
+ ): Promise<void> {
281
+ const flagValue = pi.getFlag(SUGGESTION_DEBUG_LOG_FLAG);
282
+ if (typeof flagValue !== "string" || !flagValue.trim()) return;
283
+ try {
284
+ await appendFile(
285
+ flagValue.trim(),
286
+ `${JSON.stringify({ timestamp: new Date().toISOString(), ...entry }, null, 2)}\n---\n`,
287
+ "utf8",
288
+ );
289
+ } catch {
290
+ // Debug logging must never break suggestions.
291
+ }
292
+ }
293
+
294
+ function currentLinePrefix(params: SuggestionParams): string {
295
+ const before = params.cursorBefore ?? "";
296
+ return before.slice(before.lastIndexOf("\n") + 1);
297
+ }
298
+
299
+ function startsWithCommentMarker(text: string): boolean {
300
+ return /^\s*(?:\/\/[\s\/!]?|#\s?|--\s?|;\s?|\/\*+\s?|\*\s?)/.test(text);
301
+ }
302
+
303
+ function looksLikeCodeLine(text: string): boolean {
304
+ const trimmed = text.trimStart();
305
+ if (/[;{}]/.test(trimmed)) return true;
306
+ if (/^(?:pub\s+)?(?:const|var|return|try|if|for|while|switch|fn)\b/.test(trimmed)) return true;
307
+ if (/^@\w+\s*\(/.test(trimmed)) return true;
308
+ return /^\w+(?:\.\w+)*\s*=/.test(trimmed);
309
+ }
310
+
311
+ function normalizeCommentSuggestion(block: string, prefix: string): string | null {
312
+ let firstLine = block.replace(/\r\n/g, "\n").split("\n", 1)[0] ?? "";
313
+ if (firstLine.startsWith(prefix)) firstLine = firstLine.slice(prefix.length);
314
+ if (startsWithCommentMarker(firstLine)) return null;
315
+ if (looksLikeCodeLine(firstLine)) return null;
316
+ const suggestion = firstLine.trimStart().trimEnd();
317
+ return suggestion === "" ? null : suggestion;
318
+ }
319
+
320
+ function alignSuggestion(block: string, params: SuggestionParams): string | null {
321
+ const prefix = currentLinePrefix(params);
322
+ let suggestion = block.replace(/\r\n/g, "\n").replace(/^\n+/, "").replace(/\n+$/, "");
323
+ if (suggestion === "") return null;
324
+ if (prefix.trim() !== "" && suggestion.startsWith(prefix)) suggestion = suggestion.slice(prefix.length);
325
+ if (params.cursorInComment) return normalizeCommentSuggestion(suggestion, prefix);
326
+ if (prefix.trim() !== "") {
327
+ const firstLine = suggestion.split("\n", 1)[0] ?? "";
328
+ if (/^\s+\S/.test(firstLine)) return null;
329
+ return firstLine.trimEnd() || null;
330
+ }
331
+ return suggestion;
332
+ }
333
+
334
+ function resolveSuggestionModel(pi: ExtensionAPI, ctx: ExtensionContext, editorPref: string | undefined) {
335
+ // Precedence: CLI flag (operator override) > editor-provided preference >
336
+ // current session model.
337
+ const flagValue = pi.getFlag(SUGGESTION_FLAG);
338
+ const pick = (typeof flagValue === "string" && flagValue) ? flagValue : (editorPref || "");
339
+ if (pick) {
340
+ const slash = pick.indexOf("/");
341
+ if (slash === -1) {
342
+ throw new Error(`suggestion model expects provider/id, got "${pick}"`);
343
+ }
344
+ const provider = pick.slice(0, slash);
345
+ const id = pick.slice(slash + 1);
346
+ const m = ctx.modelRegistry.find(provider, id);
347
+ if (!m) throw new Error(`model not found: ${pick}`);
348
+ return m;
349
+ }
350
+ if (!ctx.model) throw new Error("no current model, no editor-provided model, and --pi-ide-suggestion-model not set");
351
+ return ctx.model;
352
+ }
353
+
354
+ async function generateSuggestions(pi: ExtensionAPI, params: SuggestionParams, signal: AbortSignal): Promise<string[]> {
355
+ if (!sessionCtx) throw new Error("session not yet started");
356
+ const ctx = sessionCtx;
357
+ const model = resolveSuggestionModel(pi, ctx, params.model);
358
+ const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
359
+ if (!auth.ok) throw new Error(`auth failed: ${auth.error}`);
360
+ if (!auth.apiKey) throw new Error(`no API key for ${model.provider}`);
361
+
362
+ const userText = buildSuggestionPrompt(params);
363
+ const response = await completeSimple(
364
+ model,
365
+ {
366
+ systemPrompt: SUGGESTION_SYSTEM_PROMPT,
367
+ messages: [
368
+ {
369
+ role: "user",
370
+ content: [{ type: "text", text: userText }],
371
+ timestamp: Date.now(),
372
+ },
373
+ ],
374
+ },
375
+ {
376
+ apiKey: auth.apiKey,
377
+ headers: auth.headers,
378
+ maxTokens: 1024,
379
+ signal,
380
+ cacheRetention: "short",
381
+ },
382
+ );
383
+ if (response.stopReason === "error" || response.stopReason === "aborted") {
384
+ throw new Error(response.errorMessage ?? `suggestion model stopped with ${response.stopReason}`);
385
+ }
386
+ const text = response.content
387
+ .filter((c): c is { type: "text"; text: string } => c.type === "text")
388
+ .map((c) => c.text)
389
+ .join("");
390
+ const blocks = parseSuggestionBlocks(text);
391
+ const suggestions = blocks
392
+ .map((block) => alignSuggestion(block, params))
393
+ .filter((block): block is string => block !== null);
394
+ const max = params.suggestionCount ?? 3;
395
+ const returnedSuggestions = suggestions.slice(0, max);
396
+ await logSuggestionDebug(pi, {
397
+ model: `${model.provider}/${model.id}`,
398
+ params,
399
+ userText,
400
+ rawText: text,
401
+ parsedBlocks: blocks,
402
+ returnedSuggestions,
403
+ });
404
+ return returnedSuggestions;
405
+ }
406
+
133
407
  type PickResult =
134
408
  | { kind: "selected"; lockfile: Lockfile }
135
409
  | { kind: "none" }
136
410
  | { kind: "cancelled" };
137
411
 
138
- async function pickLockfile(cwd: string, ui: { select: (t: string, o: string[]) => Promise<string | undefined> }): Promise<PickResult> {
412
+ async function pickLockfile(
413
+ cwd: string,
414
+ ui: { select: (t: string, o: string[]) => Promise<string | undefined> },
415
+ current?: Lockfile,
416
+ ): Promise<PickResult> {
417
+ const candidates = await findCandidateLockfiles(cwd);
418
+ if (candidates.length === 0) return { kind: "none" };
419
+ const labels = candidates.map((c) => {
420
+ const folder = c.workspaceFolders[0] ?? "?";
421
+ const marker = current && c.port === current.port && c.pid === current.pid ? " · (connected)" : "";
422
+ return `${c.ideName} · ${folder} · pid=${c.pid} port=${c.port}${marker}`;
423
+ });
424
+ const title = current ? "Select IDE (toggle to disconnect)" : "Connect to IDE";
425
+ const choice = await ui.select(title, labels);
426
+ if (!choice) return { kind: "cancelled" };
427
+ const lockfile = candidates[labels.indexOf(choice)];
428
+ return lockfile ? { kind: "selected", lockfile } : { kind: "cancelled" };
429
+ }
430
+
431
+ /**
432
+ * Find lockfiles that match the given cwd, have a live PID, and are listening.
433
+ */
434
+ async function findCandidateLockfiles(cwd: string): Promise<Lockfile[]> {
139
435
  const all = await listLockfiles();
140
436
  const candidates: Lockfile[] = [];
141
437
  for (const lf of all) {
@@ -144,61 +440,151 @@ async function pickLockfile(cwd: string, ui: { select: (t: string, o: string[])
144
440
  if (!(await isPortListening(lf.port))) continue;
145
441
  candidates.push(lf);
146
442
  }
147
- if (candidates.length === 0) return { kind: "none" };
148
- const labels = candidates.map((c) => {
149
- const folder = c.workspaceFolders[0] ?? "?";
150
- return `${c.ideName} · ${folder} · pid=${c.pid} port=${c.port}`;
443
+ return candidates;
444
+ }
445
+
446
+ /**
447
+ * Create an IdeClient, wire up handlers, and connect.
448
+ */
449
+ async function connectToLockfile(lockfile: Lockfile, ctx: ExtensionContext, pi: ExtensionAPI): Promise<IdeClient | null> {
450
+ const next = new IdeClient(lockfile);
451
+ next.onNotification = onNotification;
452
+ next.onRequest("getSuggestions", async (params, signal) => {
453
+ inFlightSuggestions++;
454
+ if (inFlightSuggestions === 1) startSpinner();
455
+ renderWidget();
456
+ try {
457
+ const suggestions = await generateSuggestions(pi, (params ?? {}) as SuggestionParams, signal);
458
+ return { suggestions };
459
+ } finally {
460
+ inFlightSuggestions--;
461
+ if (inFlightSuggestions === 0) stopSpinner();
462
+ renderWidget();
463
+ }
151
464
  });
152
- const choice = await ui.select("Connect to IDE", labels);
153
- if (!choice) return { kind: "cancelled" };
154
- const lockfile = candidates[labels.indexOf(choice)];
155
- return lockfile ? { kind: "selected", lockfile } : { kind: "cancelled" };
465
+ next.onRequest("listSuggestionModels", async () => {
466
+ if (!sessionCtx) throw new Error("session not yet started");
467
+ const flagValue = pi.getFlag(SUGGESTION_FLAG);
468
+ const cliOverride = (typeof flagValue === "string" && flagValue) ? flagValue : undefined;
469
+ return {
470
+ cliOverride,
471
+ currentModel: sessionCtx.model ? `${sessionCtx.model.provider}/${sessionCtx.model.id}` : undefined,
472
+ models: sessionCtx.modelRegistry.getAvailable().map((model) => ({
473
+ provider: model.provider,
474
+ id: model.id,
475
+ name: model.name,
476
+ model: `${model.provider}/${model.id}`,
477
+ })),
478
+ };
479
+ });
480
+ next.onClose = () => {
481
+ if (client === next) {
482
+ client = null;
483
+ resetState();
484
+ inFlightSuggestions = 0;
485
+ stopSpinner();
486
+ renderWidget();
487
+ ui?.notify("IDE disconnected", "warning");
488
+ }
489
+ };
490
+ try {
491
+ await next.connect();
492
+ } catch (err) {
493
+ ui?.notify(`Failed to connect: ${err instanceof Error ? err.message : String(err)}`, "error");
494
+ return null;
495
+ }
496
+ client = next;
497
+ ui = ctx.ui;
498
+ renderWidget();
499
+ return next;
500
+ }
501
+
502
+ /**
503
+ * Auto-connect to the single matching IDE for this cwd, if exactly one valid
504
+ * lockfile exists. Does nothing when zero or multiple candidates are found.
505
+ */
506
+ async function autoConnect(ctx: ExtensionContext, pi: ExtensionAPI): Promise<void> {
507
+ if (client?.isConnected()) return;
508
+ const candidates = await findCandidateLockfiles(ctx.cwd);
509
+ if (candidates.length !== 1) return;
510
+ const lockfile = candidates[0];
511
+ const connected = await connectToLockfile(lockfile, ctx, pi);
512
+ if (connected) {
513
+ ui?.notify(`Auto-connected to ${lockfile.ideName}`, "info");
514
+ }
156
515
  }
157
516
 
158
517
  export default function (pi: ExtensionAPI) {
518
+ pi.registerFlag(SUGGESTION_FLAG, {
519
+ type: "string",
520
+ description: "Model to use for inline suggestions (format: provider/id). Falls back to current session model.",
521
+ });
522
+ pi.registerFlag(SUGGESTION_DEBUG_LOG_FLAG, {
523
+ type: "string",
524
+ description: "Path to append raw inline suggestion debug logs.",
525
+ });
526
+
527
+ pi.on("session_start", async (event, ctx) => {
528
+ sessionCtx = ctx;
529
+ if (event.reason === "new" || event.reason === "resume" || event.reason === "reload") {
530
+ await autoConnect(ctx, pi);
531
+ }
532
+ });
533
+
159
534
  pi.registerCommand("ide", {
160
- description: "Connect to a running IDE for ambient context and IDE-routed diffs.",
535
+ description: "Connect to a running IDE for ambient context and IDE-routed diffs. Select the current IDE to disconnect.",
161
536
  async handler(_args, ctx) {
162
- if (client?.isConnected()) {
163
- ctx.ui.notify(`Already connected to ${client.lockfile.ideName} (port ${client.lockfile.port})`);
164
- return;
537
+ const wasConnected = client?.isConnected() ?? false;
538
+ const currentLockfile = wasConnected ? client!.lockfile : undefined;
539
+ const pick = await pickLockfile(ctx.cwd, ctx.ui, currentLockfile);
540
+ if (pick.kind === "cancelled") return;
541
+
542
+ if (wasConnected) {
543
+ if (pick.kind === "none") {
544
+ disconnectFromIde();
545
+ ctx.ui.notify(`Disconnected from ${currentLockfile!.ideName}`, "warning");
546
+ return;
547
+ }
548
+ const same =
549
+ pick.lockfile.port === currentLockfile!.port &&
550
+ pick.lockfile.pid === currentLockfile!.pid;
551
+ if (same) {
552
+ disconnectFromIde();
553
+ ctx.ui.notify(`Disconnected from ${currentLockfile!.ideName}`, "warning");
554
+ return;
555
+ }
556
+ // Switch to a different IDE
557
+ disconnectFromIde();
165
558
  }
166
- const pick = await pickLockfile(ctx.cwd, ctx.ui);
559
+
167
560
  if (pick.kind === "none") {
168
561
  ctx.ui.notify("No running IDE found for this project", "warning");
169
562
  return;
170
563
  }
171
- if (pick.kind === "cancelled") return;
172
- const next = new IdeClient(pick.lockfile);
173
- next.onNotification = onNotification;
174
- next.onClose = () => {
175
- if (client === next) {
176
- client = null;
177
- resetState();
178
- renderWidget();
179
- ctx.ui.notify("IDE disconnected", "warning");
180
- }
181
- };
182
- try {
183
- await next.connect();
184
- } catch (err) {
185
- ctx.ui.notify(`Failed to connect: ${err instanceof Error ? err.message : String(err)}`, "error");
186
- return;
187
- }
188
- client = next;
189
- ui = ctx.ui;
190
- renderWidget();
564
+
565
+ await connectToLockfile(pick.lockfile, ctx, pi);
191
566
  },
192
567
  });
193
568
 
194
- pi.on("before_agent_start", async (event) => {
569
+ pi.on("context", async (event) => {
195
570
  const blocks: string[] = [];
196
571
  const editor = renderEditorBlock();
197
572
  if (editor) blocks.push(editor);
198
573
  const diagnostics = await fetchDiagnosticsBlock();
199
574
  if (diagnostics) blocks.push(diagnostics);
200
575
  if (blocks.length === 0) return;
201
- return { systemPrompt: `${event.systemPrompt}\n\n${blocks.join("\n\n")}` };
576
+ return {
577
+ messages: [
578
+ ...event.messages,
579
+ {
580
+ role: "custom",
581
+ customType: "pi-ide.editor-context",
582
+ content: blocks.join("\n\n"),
583
+ display: false,
584
+ timestamp: Date.now(),
585
+ },
586
+ ],
587
+ };
202
588
  });
203
589
 
204
590
  pi.on("tool_call", async (event, ctx) => {
@@ -267,6 +653,8 @@ export default function (pi: ExtensionAPI) {
267
653
 
268
654
  pi.on("session_shutdown", () => {
269
655
  client?.close();
656
+ inFlightSuggestions = 0;
657
+ stopSpinner();
270
658
  renderWidget();
271
659
  client = null;
272
660
  resetState();
package/package.json CHANGED
@@ -1,8 +1,14 @@
1
1
  {
2
2
  "name": "@ldelossa/pi-ide",
3
- "version": "0.1.1",
3
+ "version": "0.2.2",
4
4
  "description": "Pi extension that connects to a running editor (Neovim today, more later) over a local WebSocket. Adds ambient editor context to the agent and routes write/edit tool calls through interactive diffs in the editor.",
5
5
  "keywords": ["pi-package", "pi", "ide", "neovim"],
6
+ "files": [
7
+ "client.ts",
8
+ "index.ts",
9
+ "LICENSE",
10
+ "README.md"
11
+ ],
6
12
  "license": "MIT",
7
13
  "author": "Louis DeLosSantos <louis.delos@gmail.com>",
8
14
  "repository": {
@@ -22,11 +28,8 @@
22
28
  "ws": "8.21.0"
23
29
  },
24
30
  "peerDependencies": {
25
- "@earendil-works/pi-agent-core": "*",
26
31
  "@earendil-works/pi-ai": "*",
27
- "@earendil-works/pi-coding-agent": "*",
28
- "@earendil-works/pi-tui": "*",
29
- "typebox": "*"
32
+ "@earendil-works/pi-coding-agent": "*"
30
33
  },
31
34
  "devDependencies": {
32
35
  "@types/node": "22.19.19",
package/tsconfig.json DELETED
@@ -1,17 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- "target": "ES2023",
4
- "module": "NodeNext",
5
- "moduleResolution": "NodeNext",
6
- "lib": ["ES2023"],
7
- "strict": true,
8
- "noEmit": true,
9
- "esModuleInterop": true,
10
- "skipLibCheck": true,
11
- "resolveJsonModule": true,
12
- "allowImportingTsExtensions": true,
13
- "verbatimModuleSyntax": true,
14
- "types": ["node"]
15
- },
16
- "include": ["*.ts"]
17
- }