@ldelossa/pi-ide 0.2.4 → 0.2.6
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 +8 -84
- package/client.ts +6 -66
- package/index.ts +8 -314
- package/package.json +1 -2
package/README.md
CHANGED
|
@@ -3,9 +3,8 @@
|
|
|
3
3
|
Connects a Pi coding-agent session to a running editor over a local
|
|
4
4
|
WebSocket MCP server. Provides ambient editor context (current file,
|
|
5
5
|
cursor, selection), routes `write`/`edit` tool calls through the editor
|
|
6
|
-
as interactive diffs
|
|
7
|
-
|
|
8
|
-
with Claude Code's editor integration.
|
|
6
|
+
as interactive diffs. The wireformat is compatible with Claude Code's editor
|
|
7
|
+
integration.
|
|
9
8
|
|
|
10
9
|
## Install
|
|
11
10
|
|
|
@@ -208,88 +207,13 @@ enter, and text change. Debounce locally (~100ms recommended).
|
|
|
208
207
|
Lines and characters are zero-based. The extension renders line numbers as
|
|
209
208
|
1-based.
|
|
210
209
|
|
|
211
|
-
##
|
|
212
|
-
|
|
213
|
-
The editor may send JSON-RPC requests to the extension over the same
|
|
214
|
-
WebSocket. The extension processes them and returns responses.
|
|
215
|
-
|
|
216
|
-
### Request: `getSuggestions`
|
|
217
|
-
|
|
218
|
-
Returns inline code completions for the editor to render as ghost text or
|
|
219
|
-
equivalent. The extension calls the configured model (current session
|
|
220
|
-
model by default; see model precedence below), parses up to 3
|
|
221
|
-
`<SUGGESTION>...</SUGGESTION>` blocks from the response, and returns them.
|
|
222
|
-
|
|
223
|
-
Input:
|
|
224
|
-
|
|
225
|
-
| field | type | description |
|
|
226
|
-
| ----------------- | ------ | -------------------------------------------- |
|
|
227
|
-
| `filePath` | string | optional. absolute path of the cursor file |
|
|
228
|
-
| `language` | string | optional. filetype or language id |
|
|
229
|
-
| `outline` | string | optional. structural sketch of the file |
|
|
230
|
-
| `enclosingScope` | string | optional. surrounding function or class |
|
|
231
|
-
| `cursorBefore` | string | text before cursor (typically ~20 lines) |
|
|
232
|
-
| `cursorAfter` | string | text after cursor (typically ~10 lines) |
|
|
233
|
-
| `suggestionCount` | int | optional. cap on returned alternatives. Max 3. |
|
|
234
|
-
| `model` | string | optional. preferred model "provider/id". CLI flag wins if set. |
|
|
235
|
-
|
|
236
|
-
`outline` is whatever structural sketch the editor produces with its native
|
|
237
|
-
source-analysis tool — treesitter sexpr (Neovim), document symbols from
|
|
238
|
-
LSP (VS Code), PSI tree (JetBrains), or omitted entirely. The model accepts
|
|
239
|
-
any text. Completion quality scales with the amount of structural context
|
|
240
|
-
provided. The minimal viable payload is `cursorBefore` and `cursorAfter`.
|
|
241
|
-
|
|
242
|
-
Response:
|
|
243
|
-
|
|
244
|
-
```
|
|
245
|
-
{ "suggestions": ["<text>", ...] }
|
|
246
|
-
```
|
|
247
|
-
|
|
248
|
-
Empty `suggestions` is valid and means the model declined to complete.
|
|
249
|
-
|
|
250
|
-
Cancellation: editor sends `request_cancelled` notification with
|
|
251
|
-
`{ "id": <request id> }`. The extension aborts the in-flight model call.
|
|
252
|
-
|
|
253
|
-
Model precedence: the CLI flag (`--pi-ide-suggestion-model <provider>/<id>`)
|
|
254
|
-
wins. Otherwise the editor-provided `model` field is used. If neither is
|
|
255
|
-
set, the current session's model is used.
|
|
256
|
-
|
|
257
|
-
To find valid `provider/id` strings, run `pi --list-models` and join the
|
|
258
|
-
`provider` and `model` columns with a `/` (e.g., `openai/gpt-4o`).
|
|
259
|
-
|
|
260
|
-
For suggestions, prefer low-latency models. Large reasoning models often
|
|
261
|
-
feel too slow for inline completion; smaller coding-capable models such as
|
|
262
|
-
`openai-codex/gpt-5.4-mini` or `deepseek/deepseek-v4-flash` usually provide
|
|
263
|
-
a better interactive experience.
|
|
264
|
-
|
|
265
|
-
### Request: `listSuggestionModels`
|
|
266
|
-
|
|
267
|
-
Returns models available to the current pi session for runtime suggestion
|
|
268
|
-
model selection in editors. The extension is the source of truth for model
|
|
269
|
-
discovery; editors should not read pi config files directly.
|
|
210
|
+
## Reference editor implementation
|
|
270
211
|
|
|
271
|
-
|
|
212
|
+
Neovim: `pi-ide.nvim`. Implements the editor-side contract, including diffs,
|
|
213
|
+
diagnostics, and selection notifications.
|
|
272
214
|
|
|
273
|
-
|
|
215
|
+
## Development
|
|
274
216
|
|
|
217
|
+
```bash
|
|
218
|
+
npm run check
|
|
275
219
|
```
|
|
276
|
-
{
|
|
277
|
-
"cliOverride": "<provider/id>", // optional. --pi-ide-suggestion-model is active
|
|
278
|
-
"currentModel": "<provider/id>", // optional. current pi session model
|
|
279
|
-
"models": [
|
|
280
|
-
{ "provider": "openai", "id": "gpt-4o", "name": "GPT-4o", "model": "openai/gpt-4o" }
|
|
281
|
-
]
|
|
282
|
-
}
|
|
283
|
-
```
|
|
284
|
-
|
|
285
|
-
If `cliOverride` is present, editor-provided model selections are still
|
|
286
|
-
accepted by the editor but will not affect suggestions because the CLI flag
|
|
287
|
-
has higher precedence.
|
|
288
|
-
|
|
289
|
-
## Reference editor implementation
|
|
290
|
-
|
|
291
|
-
Neovim: `pi-ide.nvim`. Implements both the editor-side contract (diffs,
|
|
292
|
-
diagnostics, selection notifications) and the `getSuggestions` client.
|
|
293
|
-
Suggestions always work; treesitter and LSP enrich the context but are
|
|
294
|
-
not required — the feature degrades gracefully to cursor-window-only
|
|
295
|
-
context when either is unavailable.
|
package/client.ts
CHANGED
|
@@ -84,27 +84,15 @@ 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>;
|
|
88
87
|
|
|
89
88
|
export class IdeClient {
|
|
90
89
|
private ws: WebSocket | null = null;
|
|
91
90
|
private closed = false;
|
|
92
91
|
public readonly lockfile: Lockfile;
|
|
93
92
|
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;
|
|
101
93
|
public onNotification: NotificationHandler = () => {};
|
|
102
94
|
public onClose: () => void = () => {};
|
|
103
95
|
|
|
104
|
-
onRequest(method: string, handler: RequestHandler): void {
|
|
105
|
-
this.requestHandlers.set(method, handler);
|
|
106
|
-
}
|
|
107
|
-
|
|
108
96
|
constructor(lockfile: Lockfile) {
|
|
109
97
|
this.lockfile = lockfile;
|
|
110
98
|
}
|
|
@@ -191,64 +179,18 @@ export class IdeClient {
|
|
|
191
179
|
else pending.resolve(msg.result);
|
|
192
180
|
return;
|
|
193
181
|
}
|
|
194
|
-
// Inbound
|
|
182
|
+
// Inbound requests from the server. The editor no longer initiates any,
|
|
183
|
+
// so answer method-not-found rather than leaving the peer waiting.
|
|
195
184
|
if (msg.id !== undefined && typeof msg.method === "string") {
|
|
196
|
-
void this.handleInboundRequest(msg.id, msg.method, msg.params);
|
|
197
|
-
return;
|
|
198
|
-
}
|
|
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
|
-
}
|
|
218
|
-
this.onNotification(msg.method, msg.params);
|
|
219
|
-
}
|
|
220
|
-
}
|
|
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
185
|
this.sendRaw({
|
|
227
186
|
jsonrpc: "2.0",
|
|
228
|
-
id,
|
|
229
|
-
error: { code: -32601, message: `Method not found: ${method}` },
|
|
187
|
+
id: msg.id,
|
|
188
|
+
error: { code: -32601, message: `Method not found: ${msg.method}` },
|
|
230
189
|
});
|
|
231
190
|
return;
|
|
232
191
|
}
|
|
233
|
-
if (
|
|
234
|
-
this.
|
|
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);
|
|
192
|
+
if (typeof msg.method === "string") {
|
|
193
|
+
this.onNotification(msg.method, msg.params);
|
|
252
194
|
}
|
|
253
195
|
}
|
|
254
196
|
|
|
@@ -263,8 +205,6 @@ export class IdeClient {
|
|
|
263
205
|
const err = new Error("IDE connection closed");
|
|
264
206
|
for (const pending of this.pending.values()) pending.reject(err);
|
|
265
207
|
this.pending.clear();
|
|
266
|
-
for (const ac of this.inboundAborts.values()) ac.abort();
|
|
267
|
-
this.inboundAborts.clear();
|
|
268
208
|
this.ws = null;
|
|
269
209
|
this.onClose();
|
|
270
210
|
}
|
package/index.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
2
|
import { basename, resolve as resolvePath } from "node:path";
|
|
3
|
-
import { completeSimple } from "@earendil-works/pi-ai";
|
|
4
3
|
import {
|
|
5
4
|
isToolCallEventType,
|
|
6
5
|
SettingsManager,
|
|
@@ -10,27 +9,11 @@ import {
|
|
|
10
9
|
} from "@earendil-works/pi-coding-agent";
|
|
11
10
|
import { IdeClient, isPidAlive, isPortListening, listLockfiles, type Lockfile, matchesCwd } from "./client.ts";
|
|
12
11
|
|
|
13
|
-
const SUGGESTION_FLAG = "pi-ide-suggestion-model";
|
|
14
|
-
const SUGGESTION_DEBUG_LOG_FLAG = "pi-ide-suggestion-debug-log";
|
|
15
|
-
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.
|
|
16
|
-
|
|
17
|
-
Rules:
|
|
18
|
-
1. Output ONLY the code to insert. Do not repeat code before or after the cursor.
|
|
19
|
-
2. Match the file's existing indentation, naming, and style.
|
|
20
|
-
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.
|
|
21
|
-
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.
|
|
22
|
-
5. When the cursor follows existing code on the line, complete only the current statement. Do not add new statements, blocks, or functions.
|
|
23
|
-
6. If mid-token, complete that token first.
|
|
24
|
-
7. If you have only one strong completion, output one block.
|
|
25
|
-
8. If nothing reasonable, output zero blocks.`;
|
|
26
|
-
|
|
27
12
|
type Selection = { startLine: number; endLine: number; text: string };
|
|
28
13
|
type EditorState = { filePath: string | null; cursorLine: number | null; selection: Selection | null };
|
|
29
14
|
|
|
30
15
|
const MAX_SELECTION_LINES = 100;
|
|
31
16
|
const WIDGET_KEY = "pi-ide";
|
|
32
|
-
const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
|
|
33
|
-
const SPINNER_INTERVAL_MS = 80;
|
|
34
17
|
|
|
35
18
|
// --- Autoconnect config & state ---
|
|
36
19
|
const PI_IDE_SETTINGS_KEY = "pi-ide";
|
|
@@ -89,10 +72,6 @@ function sameLockfile(a: Lockfile, b: Lockfile): boolean {
|
|
|
89
72
|
let client: IdeClient | null = null;
|
|
90
73
|
let state: EditorState = { filePath: null, cursorLine: null, selection: null };
|
|
91
74
|
let ui: ExtensionUIContext | null = null;
|
|
92
|
-
let sessionCtx: ExtensionContext | null = null;
|
|
93
|
-
let inFlightSuggestions = 0;
|
|
94
|
-
let spinnerTimer: ReturnType<typeof setInterval> | null = null;
|
|
95
|
-
let spinnerFrame = 0;
|
|
96
75
|
|
|
97
76
|
function disconnectFromIde(): void {
|
|
98
77
|
if (!client) return;
|
|
@@ -101,8 +80,6 @@ function disconnectFromIde(): void {
|
|
|
101
80
|
client = null;
|
|
102
81
|
old.close();
|
|
103
82
|
resetState();
|
|
104
|
-
inFlightSuggestions = 0;
|
|
105
|
-
stopSpinner();
|
|
106
83
|
renderWidget();
|
|
107
84
|
}
|
|
108
85
|
|
|
@@ -110,22 +87,6 @@ function resetState(): void {
|
|
|
110
87
|
state = { filePath: null, cursorLine: null, selection: null };
|
|
111
88
|
}
|
|
112
89
|
|
|
113
|
-
function startSpinner(): void {
|
|
114
|
-
if (spinnerTimer) return;
|
|
115
|
-
spinnerTimer = setInterval(() => {
|
|
116
|
-
spinnerFrame = (spinnerFrame + 1) % SPINNER.length;
|
|
117
|
-
renderWidget();
|
|
118
|
-
}, SPINNER_INTERVAL_MS);
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
function stopSpinner(): void {
|
|
122
|
-
if (spinnerTimer) {
|
|
123
|
-
clearInterval(spinnerTimer);
|
|
124
|
-
spinnerTimer = null;
|
|
125
|
-
}
|
|
126
|
-
spinnerFrame = 0;
|
|
127
|
-
}
|
|
128
|
-
|
|
129
90
|
function renderWidget(): void {
|
|
130
91
|
if (!ui) return;
|
|
131
92
|
if (!client?.isConnected()) {
|
|
@@ -141,9 +102,6 @@ function renderWidget(): void {
|
|
|
141
102
|
} else {
|
|
142
103
|
body = ideName;
|
|
143
104
|
}
|
|
144
|
-
if (inFlightSuggestions > 0) {
|
|
145
|
-
body += ` · Suggesting ${SPINNER[spinnerFrame]}`;
|
|
146
|
-
}
|
|
147
105
|
ui.setWidget(WIDGET_KEY, [body]);
|
|
148
106
|
}
|
|
149
107
|
|
|
@@ -242,228 +200,6 @@ function applyEdits(original: string, edits: { oldText: string; newText: string
|
|
|
242
200
|
return result;
|
|
243
201
|
}
|
|
244
202
|
|
|
245
|
-
type SuggestionParams = {
|
|
246
|
-
filePath?: string;
|
|
247
|
-
language?: string;
|
|
248
|
-
outline?: string;
|
|
249
|
-
enclosingScope?: string;
|
|
250
|
-
cursorBefore?: string;
|
|
251
|
-
cursorAfter?: string;
|
|
252
|
-
suggestionCount?: number;
|
|
253
|
-
cursorInComment?: boolean;
|
|
254
|
-
// Editor-provided model preference, format "provider/id". The CLI flag
|
|
255
|
-
// (--pi-ide-suggestion-model) wins when both are set.
|
|
256
|
-
model?: string;
|
|
257
|
-
};
|
|
258
|
-
|
|
259
|
-
function lastLines(text: string, count: number): string {
|
|
260
|
-
const lines = text.split("\n");
|
|
261
|
-
return lines.slice(Math.max(0, lines.length - count)).join("\n");
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
function firstLines(text: string, count: number): string {
|
|
265
|
-
return text.split("\n").slice(0, count).join("\n");
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
function buildSuggestionPrompt(params: SuggestionParams): string {
|
|
269
|
-
const filePath = params.filePath ?? "<unknown>";
|
|
270
|
-
const language = params.language ?? "<unknown>";
|
|
271
|
-
const before = params.cursorBefore ?? "";
|
|
272
|
-
const after = params.cursorAfter ?? "";
|
|
273
|
-
const count = params.suggestionCount ?? 3;
|
|
274
|
-
if (params.cursorInComment) {
|
|
275
|
-
return `File: ${filePath}
|
|
276
|
-
Language: ${language}
|
|
277
|
-
|
|
278
|
-
The cursor is inside a comment. Continue only the current comment line from <CURSOR>.
|
|
279
|
-
Do not generate code. Do not start a new comment line. Do not repeat a comment marker or existing comment text.
|
|
280
|
-
|
|
281
|
-
<cursor_context>
|
|
282
|
-
${lastLines(before, 8)}<CURSOR>${firstLines(after, 4)}␃
|
|
283
|
-
</cursor_context>
|
|
284
|
-
|
|
285
|
-
Provide up to ${count} suggestions.`;
|
|
286
|
-
}
|
|
287
|
-
const outline = params.outline?.trim() ? params.outline : "(none)";
|
|
288
|
-
const enclosing = params.enclosingScope?.trim() ? params.enclosingScope : "(none)";
|
|
289
|
-
return `File: ${filePath}
|
|
290
|
-
Language: ${language}
|
|
291
|
-
|
|
292
|
-
<file_outline>
|
|
293
|
-
${outline}
|
|
294
|
-
</file_outline>
|
|
295
|
-
|
|
296
|
-
<enclosing_scope>
|
|
297
|
-
${enclosing}
|
|
298
|
-
</enclosing_scope>
|
|
299
|
-
|
|
300
|
-
<cursor_context>
|
|
301
|
-
${before}<CURSOR>${after}␃
|
|
302
|
-
</cursor_context>
|
|
303
|
-
|
|
304
|
-
Provide up to ${count} suggestions.`;
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
function parseSuggestionBlocks(text: string): string[] {
|
|
308
|
-
const out: string[] = [];
|
|
309
|
-
const re = /<SUGGESTION>([\s\S]*?)<\/SUGGESTION>/g;
|
|
310
|
-
let m: RegExpExecArray | null;
|
|
311
|
-
while ((m = re.exec(text)) !== null) {
|
|
312
|
-
out.push(m[1].replace(/^\n+/, "").replace(/\n+$/, ""));
|
|
313
|
-
}
|
|
314
|
-
if (out.length === 0) {
|
|
315
|
-
// Salvage an unclosed trailing <SUGGESTION> when the LLM hit maxTokens
|
|
316
|
-
// before emitting the closing tag.
|
|
317
|
-
const open = text.lastIndexOf("<SUGGESTION>");
|
|
318
|
-
if (open !== -1 && text.indexOf("</SUGGESTION>", open) === -1) {
|
|
319
|
-
const tail = text.slice(open + "<SUGGESTION>".length).replace(/^\n+/, "").trimEnd();
|
|
320
|
-
if (tail) out.push(tail);
|
|
321
|
-
}
|
|
322
|
-
}
|
|
323
|
-
return out;
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
async function logSuggestionDebug(
|
|
327
|
-
pi: ExtensionAPI,
|
|
328
|
-
entry: {
|
|
329
|
-
model: string;
|
|
330
|
-
params: SuggestionParams;
|
|
331
|
-
userText: string;
|
|
332
|
-
rawText: string;
|
|
333
|
-
parsedBlocks: string[];
|
|
334
|
-
returnedSuggestions: string[];
|
|
335
|
-
},
|
|
336
|
-
): Promise<void> {
|
|
337
|
-
const flagValue = pi.getFlag(SUGGESTION_DEBUG_LOG_FLAG);
|
|
338
|
-
if (typeof flagValue !== "string" || !flagValue.trim()) return;
|
|
339
|
-
try {
|
|
340
|
-
await appendFile(
|
|
341
|
-
flagValue.trim(),
|
|
342
|
-
`${JSON.stringify({ timestamp: new Date().toISOString(), ...entry }, null, 2)}\n---\n`,
|
|
343
|
-
"utf8",
|
|
344
|
-
);
|
|
345
|
-
} catch {
|
|
346
|
-
// Debug logging must never break suggestions.
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
function currentLinePrefix(params: SuggestionParams): string {
|
|
351
|
-
const before = params.cursorBefore ?? "";
|
|
352
|
-
return before.slice(before.lastIndexOf("\n") + 1);
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
function startsWithCommentMarker(text: string): boolean {
|
|
356
|
-
return /^\s*(?:\/\/[\s\/!]?|#\s?|--\s?|;\s?|\/\*+\s?|\*\s?)/.test(text);
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
function looksLikeCodeLine(text: string): boolean {
|
|
360
|
-
const trimmed = text.trimStart();
|
|
361
|
-
if (/[;{}]/.test(trimmed)) return true;
|
|
362
|
-
if (/^(?:pub\s+)?(?:const|var|return|try|if|for|while|switch|fn)\b/.test(trimmed)) return true;
|
|
363
|
-
if (/^@\w+\s*\(/.test(trimmed)) return true;
|
|
364
|
-
return /^\w+(?:\.\w+)*\s*=/.test(trimmed);
|
|
365
|
-
}
|
|
366
|
-
|
|
367
|
-
function normalizeCommentSuggestion(block: string, prefix: string): string | null {
|
|
368
|
-
let firstLine = block.replace(/\r\n/g, "\n").split("\n", 1)[0] ?? "";
|
|
369
|
-
if (firstLine.startsWith(prefix)) firstLine = firstLine.slice(prefix.length);
|
|
370
|
-
if (startsWithCommentMarker(firstLine)) return null;
|
|
371
|
-
if (looksLikeCodeLine(firstLine)) return null;
|
|
372
|
-
const suggestion = firstLine.trimStart().trimEnd();
|
|
373
|
-
return suggestion === "" ? null : suggestion;
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
function alignSuggestion(block: string, params: SuggestionParams): string | null {
|
|
377
|
-
const prefix = currentLinePrefix(params);
|
|
378
|
-
let suggestion = block.replace(/\r\n/g, "\n").replace(/^\n+/, "").replace(/\n+$/, "");
|
|
379
|
-
if (suggestion === "") return null;
|
|
380
|
-
// The editor inserts the returned text at the cursor. When the cursor is
|
|
381
|
-
// already after indentation on an otherwise-empty line, a full-line model
|
|
382
|
-
// response often repeats that indentation; strip only that first-line prefix
|
|
383
|
-
// so the editor's existing indent is not doubled.
|
|
384
|
-
if (prefix !== "" && suggestion.startsWith(prefix)) suggestion = suggestion.slice(prefix.length);
|
|
385
|
-
if (params.cursorInComment) return normalizeCommentSuggestion(suggestion, prefix);
|
|
386
|
-
if (prefix.trim() !== "") {
|
|
387
|
-
const firstLine = suggestion.split("\n", 1)[0] ?? "";
|
|
388
|
-
if (/^\s+\S/.test(firstLine)) return null;
|
|
389
|
-
return firstLine.trimEnd() || null;
|
|
390
|
-
}
|
|
391
|
-
return suggestion;
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
function resolveSuggestionModel(pi: ExtensionAPI, ctx: ExtensionContext, editorPref: string | undefined) {
|
|
395
|
-
// Precedence: CLI flag (operator override) > editor-provided preference >
|
|
396
|
-
// current session model.
|
|
397
|
-
const flagValue = pi.getFlag(SUGGESTION_FLAG);
|
|
398
|
-
const pick = (typeof flagValue === "string" && flagValue) ? flagValue : (editorPref || "");
|
|
399
|
-
if (pick) {
|
|
400
|
-
const slash = pick.indexOf("/");
|
|
401
|
-
if (slash === -1) {
|
|
402
|
-
throw new Error(`suggestion model expects provider/id, got "${pick}"`);
|
|
403
|
-
}
|
|
404
|
-
const provider = pick.slice(0, slash);
|
|
405
|
-
const id = pick.slice(slash + 1);
|
|
406
|
-
const m = ctx.modelRegistry.find(provider, id);
|
|
407
|
-
if (!m) throw new Error(`model not found: ${pick}`);
|
|
408
|
-
return m;
|
|
409
|
-
}
|
|
410
|
-
if (!ctx.model) throw new Error("no current model, no editor-provided model, and --pi-ide-suggestion-model not set");
|
|
411
|
-
return ctx.model;
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
async function generateSuggestions(pi: ExtensionAPI, params: SuggestionParams, signal: AbortSignal): Promise<string[]> {
|
|
415
|
-
if (!sessionCtx) throw new Error("session not yet started");
|
|
416
|
-
const ctx = sessionCtx;
|
|
417
|
-
const model = resolveSuggestionModel(pi, ctx, params.model);
|
|
418
|
-
const auth = await ctx.modelRegistry.getApiKeyAndHeaders(model);
|
|
419
|
-
if (!auth.ok) throw new Error(`auth failed: ${auth.error}`);
|
|
420
|
-
if (!auth.apiKey) throw new Error(`no API key for ${model.provider}`);
|
|
421
|
-
|
|
422
|
-
const userText = buildSuggestionPrompt(params);
|
|
423
|
-
const response = await completeSimple(
|
|
424
|
-
model,
|
|
425
|
-
{
|
|
426
|
-
systemPrompt: SUGGESTION_SYSTEM_PROMPT,
|
|
427
|
-
messages: [
|
|
428
|
-
{
|
|
429
|
-
role: "user",
|
|
430
|
-
content: [{ type: "text", text: userText }],
|
|
431
|
-
timestamp: Date.now(),
|
|
432
|
-
},
|
|
433
|
-
],
|
|
434
|
-
},
|
|
435
|
-
{
|
|
436
|
-
apiKey: auth.apiKey,
|
|
437
|
-
headers: auth.headers,
|
|
438
|
-
maxTokens: 1024,
|
|
439
|
-
signal,
|
|
440
|
-
cacheRetention: "short",
|
|
441
|
-
},
|
|
442
|
-
);
|
|
443
|
-
if (response.stopReason === "error" || response.stopReason === "aborted") {
|
|
444
|
-
throw new Error(response.errorMessage ?? `suggestion model stopped with ${response.stopReason}`);
|
|
445
|
-
}
|
|
446
|
-
const text = response.content
|
|
447
|
-
.filter((c): c is { type: "text"; text: string } => c.type === "text")
|
|
448
|
-
.map((c) => c.text)
|
|
449
|
-
.join("");
|
|
450
|
-
const blocks = parseSuggestionBlocks(text);
|
|
451
|
-
const suggestions = blocks
|
|
452
|
-
.map((block) => alignSuggestion(block, params))
|
|
453
|
-
.filter((block): block is string => block !== null);
|
|
454
|
-
const max = params.suggestionCount ?? 3;
|
|
455
|
-
const returnedSuggestions = suggestions.slice(0, max);
|
|
456
|
-
await logSuggestionDebug(pi, {
|
|
457
|
-
model: `${model.provider}/${model.id}`,
|
|
458
|
-
params,
|
|
459
|
-
userText,
|
|
460
|
-
rawText: text,
|
|
461
|
-
parsedBlocks: blocks,
|
|
462
|
-
returnedSuggestions,
|
|
463
|
-
});
|
|
464
|
-
return returnedSuggestions;
|
|
465
|
-
}
|
|
466
|
-
|
|
467
203
|
type PickResult =
|
|
468
204
|
| { kind: "selected"; lockfile: Lockfile }
|
|
469
205
|
| { kind: "none" }
|
|
@@ -506,44 +242,14 @@ async function findCandidateLockfiles(cwd: string): Promise<Lockfile[]> {
|
|
|
506
242
|
/**
|
|
507
243
|
* Create an IdeClient, wire up handlers, and connect.
|
|
508
244
|
*/
|
|
509
|
-
async function connectToLockfile(lockfile: Lockfile, ctx: ExtensionContext
|
|
245
|
+
async function connectToLockfile(lockfile: Lockfile, ctx: ExtensionContext): Promise<IdeClient | null> {
|
|
510
246
|
const next = new IdeClient(lockfile);
|
|
511
247
|
ui = ctx.ui;
|
|
512
248
|
next.onNotification = onNotification;
|
|
513
|
-
next.onRequest("getSuggestions", async (params, signal) => {
|
|
514
|
-
inFlightSuggestions++;
|
|
515
|
-
if (inFlightSuggestions === 1) startSpinner();
|
|
516
|
-
renderWidget();
|
|
517
|
-
try {
|
|
518
|
-
const suggestions = await generateSuggestions(pi, (params ?? {}) as SuggestionParams, signal);
|
|
519
|
-
return { suggestions };
|
|
520
|
-
} finally {
|
|
521
|
-
inFlightSuggestions--;
|
|
522
|
-
if (inFlightSuggestions === 0) stopSpinner();
|
|
523
|
-
renderWidget();
|
|
524
|
-
}
|
|
525
|
-
});
|
|
526
|
-
next.onRequest("listSuggestionModels", async () => {
|
|
527
|
-
if (!sessionCtx) throw new Error("session not yet started");
|
|
528
|
-
const flagValue = pi.getFlag(SUGGESTION_FLAG);
|
|
529
|
-
const cliOverride = (typeof flagValue === "string" && flagValue) ? flagValue : undefined;
|
|
530
|
-
return {
|
|
531
|
-
cliOverride,
|
|
532
|
-
currentModel: sessionCtx.model ? `${sessionCtx.model.provider}/${sessionCtx.model.id}` : undefined,
|
|
533
|
-
models: sessionCtx.modelRegistry.getAvailable().map((model) => ({
|
|
534
|
-
provider: model.provider,
|
|
535
|
-
id: model.id,
|
|
536
|
-
name: model.name,
|
|
537
|
-
model: `${model.provider}/${model.id}`,
|
|
538
|
-
})),
|
|
539
|
-
};
|
|
540
|
-
});
|
|
541
249
|
next.onClose = () => {
|
|
542
250
|
if (client === next) {
|
|
543
251
|
client = null;
|
|
544
252
|
resetState();
|
|
545
|
-
inFlightSuggestions = 0;
|
|
546
|
-
stopSpinner();
|
|
547
253
|
renderWidget();
|
|
548
254
|
ui?.notify("IDE disconnected", "warning");
|
|
549
255
|
}
|
|
@@ -570,7 +276,7 @@ async function connectToLockfile(lockfile: Lockfile, ctx: ExtensionContext, pi:
|
|
|
570
276
|
* When `preferSticky` is false (cold startup), connects only when exactly one
|
|
571
277
|
* valid IDE candidate exists for the cwd.
|
|
572
278
|
*/
|
|
573
|
-
async function autoConnect(ctx: ExtensionContext,
|
|
279
|
+
async function autoConnect(ctx: ExtensionContext, options: { preferSticky: boolean }): Promise<void> {
|
|
574
280
|
if (client?.isConnected()) return;
|
|
575
281
|
if (!isAutoconnectEnabled(ctx.cwd)) return;
|
|
576
282
|
|
|
@@ -581,7 +287,7 @@ async function autoConnect(ctx: ExtensionContext, pi: ExtensionAPI, options: { p
|
|
|
581
287
|
if (sticky) {
|
|
582
288
|
const candidate = candidates.find((c) => sameLockfile(c, sticky));
|
|
583
289
|
if (candidate) {
|
|
584
|
-
const connected = await connectToLockfile(candidate, ctx
|
|
290
|
+
const connected = await connectToLockfile(candidate, ctx);
|
|
585
291
|
if (connected) {
|
|
586
292
|
ctx.ui.notify(`Reconnected to ${candidate.ideName}`, "info");
|
|
587
293
|
return;
|
|
@@ -599,29 +305,19 @@ async function autoConnect(ctx: ExtensionContext, pi: ExtensionAPI, options: { p
|
|
|
599
305
|
|
|
600
306
|
if (candidates.length !== 1) return;
|
|
601
307
|
const lockfile = candidates[0];
|
|
602
|
-
const connected = await connectToLockfile(lockfile, ctx
|
|
308
|
+
const connected = await connectToLockfile(lockfile, ctx);
|
|
603
309
|
if (connected) {
|
|
604
310
|
ctx.ui.notify(`Auto-connected to ${lockfile.ideName}`, "info");
|
|
605
311
|
}
|
|
606
312
|
}
|
|
607
313
|
|
|
608
314
|
export default function (pi: ExtensionAPI) {
|
|
609
|
-
pi.registerFlag(SUGGESTION_FLAG, {
|
|
610
|
-
type: "string",
|
|
611
|
-
description: "Model to use for inline suggestions (format: provider/id). Falls back to current session model.",
|
|
612
|
-
});
|
|
613
|
-
pi.registerFlag(SUGGESTION_DEBUG_LOG_FLAG, {
|
|
614
|
-
type: "string",
|
|
615
|
-
description: "Path to append raw inline suggestion debug logs.",
|
|
616
|
-
});
|
|
617
|
-
|
|
618
315
|
pi.on("session_start", async (event, ctx) => {
|
|
619
|
-
sessionCtx = ctx;
|
|
620
316
|
if (event.reason === "startup") {
|
|
621
|
-
await autoConnect(ctx,
|
|
317
|
+
await autoConnect(ctx, { preferSticky: false });
|
|
622
318
|
}
|
|
623
319
|
if (event.reason === "new" || event.reason === "resume" || event.reason === "reload") {
|
|
624
|
-
await autoConnect(ctx,
|
|
320
|
+
await autoConnect(ctx, { preferSticky: true });
|
|
625
321
|
}
|
|
626
322
|
});
|
|
627
323
|
|
|
@@ -656,7 +352,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
656
352
|
return;
|
|
657
353
|
}
|
|
658
354
|
|
|
659
|
-
await connectToLockfile(pick.lockfile, ctx
|
|
355
|
+
await connectToLockfile(pick.lockfile, ctx);
|
|
660
356
|
},
|
|
661
357
|
});
|
|
662
358
|
|
|
@@ -747,8 +443,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
747
443
|
|
|
748
444
|
pi.on("session_shutdown", () => {
|
|
749
445
|
client?.close();
|
|
750
|
-
inFlightSuggestions = 0;
|
|
751
|
-
stopSpinner();
|
|
752
446
|
renderWidget();
|
|
753
447
|
client = null;
|
|
754
448
|
resetState();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ldelossa/pi-ide",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.6",
|
|
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
6
|
"files": [
|
|
@@ -28,7 +28,6 @@
|
|
|
28
28
|
"ws": "8.21.0"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|
|
31
|
-
"@earendil-works/pi-ai": "*",
|
|
32
31
|
"@earendil-works/pi-coding-agent": "*"
|
|
33
32
|
},
|
|
34
33
|
"devDependencies": {
|