@ldelossa/pi-ide 0.1.0 → 0.2.1
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 +98 -9
- package/client.ts +86 -4
- package/index.ts +367 -13
- package/package.json +8 -5
- package/tsconfig.json +0 -17
package/README.md
CHANGED
|
@@ -1,22 +1,23 @@
|
|
|
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,
|
|
5
|
-
selection)
|
|
6
|
-
interactive diffs
|
|
7
|
-
|
|
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
|
|
|
11
12
|
```bash
|
|
12
|
-
pi install
|
|
13
|
+
pi install npm:@ldelossa/pi-ide
|
|
13
14
|
```
|
|
14
15
|
|
|
15
16
|
That writes to `~/.pi/agent/settings.json` and loads pi-ide on every pi
|
|
16
17
|
session. To scope it to one project instead of globally, add `-l`:
|
|
17
18
|
|
|
18
19
|
```bash
|
|
19
|
-
pi install -l
|
|
20
|
+
pi install -l npm:@ldelossa/pi-ide
|
|
20
21
|
```
|
|
21
22
|
|
|
22
23
|
Project installs land in `./.pi/settings.json` and can be checked in so
|
|
@@ -25,13 +26,19 @@ teammates pick the extension up automatically.
|
|
|
25
26
|
To try it without installing permanently:
|
|
26
27
|
|
|
27
28
|
```bash
|
|
28
|
-
pi -e
|
|
29
|
+
pi -e npm:@ldelossa/pi-ide
|
|
29
30
|
```
|
|
30
31
|
|
|
31
32
|
To remove:
|
|
32
33
|
|
|
33
34
|
```bash
|
|
34
|
-
pi remove
|
|
35
|
+
pi remove npm:@ldelossa/pi-ide
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Git installs also work if you prefer pinning to a tag:
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pi install git:github.com/ldelossa/pi-ide@v0.1.0
|
|
35
42
|
```
|
|
36
43
|
|
|
37
44
|
You also need an editor that speaks the protocol. The reference Neovim
|
|
@@ -160,6 +167,88 @@ enter, and text change. Debounce locally (~100ms recommended).
|
|
|
160
167
|
Lines and characters are zero-based. The extension renders line numbers as
|
|
161
168
|
1-based.
|
|
162
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
|
+
|
|
163
248
|
## Reference editor implementation
|
|
164
249
|
|
|
165
|
-
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: {
|
|
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
|
-
|
|
168
|
-
|
|
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 {
|
|
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,234 @@ 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(
|
|
412
|
+
async function pickLockfile(
|
|
413
|
+
cwd: string,
|
|
414
|
+
ui: { select: (t: string, o: string[]) => Promise<string | undefined> },
|
|
415
|
+
current?: Lockfile,
|
|
416
|
+
): Promise<PickResult> {
|
|
139
417
|
const all = await listLockfiles();
|
|
140
418
|
const candidates: Lockfile[] = [];
|
|
141
419
|
for (const lf of all) {
|
|
@@ -147,34 +425,97 @@ async function pickLockfile(cwd: string, ui: { select: (t: string, o: string[])
|
|
|
147
425
|
if (candidates.length === 0) return { kind: "none" };
|
|
148
426
|
const labels = candidates.map((c) => {
|
|
149
427
|
const folder = c.workspaceFolders[0] ?? "?";
|
|
150
|
-
|
|
428
|
+
const marker = current && c.port === current.port && c.pid === current.pid ? " · (connected)" : "";
|
|
429
|
+
return `${c.ideName} · ${folder} · pid=${c.pid} port=${c.port}${marker}`;
|
|
151
430
|
});
|
|
152
|
-
const
|
|
431
|
+
const title = current ? "Select IDE (toggle to disconnect)" : "Connect to IDE";
|
|
432
|
+
const choice = await ui.select(title, labels);
|
|
153
433
|
if (!choice) return { kind: "cancelled" };
|
|
154
434
|
const lockfile = candidates[labels.indexOf(choice)];
|
|
155
435
|
return lockfile ? { kind: "selected", lockfile } : { kind: "cancelled" };
|
|
156
436
|
}
|
|
157
437
|
|
|
158
438
|
export default function (pi: ExtensionAPI) {
|
|
439
|
+
pi.registerFlag(SUGGESTION_FLAG, {
|
|
440
|
+
type: "string",
|
|
441
|
+
description: "Model to use for inline suggestions (format: provider/id). Falls back to current session model.",
|
|
442
|
+
});
|
|
443
|
+
pi.registerFlag(SUGGESTION_DEBUG_LOG_FLAG, {
|
|
444
|
+
type: "string",
|
|
445
|
+
description: "Path to append raw inline suggestion debug logs.",
|
|
446
|
+
});
|
|
447
|
+
|
|
448
|
+
pi.on("session_start", (_event, ctx) => {
|
|
449
|
+
sessionCtx = ctx;
|
|
450
|
+
});
|
|
451
|
+
|
|
159
452
|
pi.registerCommand("ide", {
|
|
160
|
-
description: "Connect to a running IDE for ambient context and IDE-routed diffs.",
|
|
453
|
+
description: "Connect to a running IDE for ambient context and IDE-routed diffs. Select the current IDE to disconnect.",
|
|
161
454
|
async handler(_args, ctx) {
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
455
|
+
const wasConnected = client?.isConnected() ?? false;
|
|
456
|
+
const currentLockfile = wasConnected ? client!.lockfile : undefined;
|
|
457
|
+
const pick = await pickLockfile(ctx.cwd, ctx.ui, currentLockfile);
|
|
458
|
+
if (pick.kind === "cancelled") return;
|
|
459
|
+
|
|
460
|
+
if (wasConnected) {
|
|
461
|
+
if (pick.kind === "none") {
|
|
462
|
+
disconnectFromIde();
|
|
463
|
+
ctx.ui.notify(`Disconnected from ${currentLockfile!.ideName}`, "warning");
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
const same =
|
|
467
|
+
pick.lockfile.port === currentLockfile!.port &&
|
|
468
|
+
pick.lockfile.pid === currentLockfile!.pid;
|
|
469
|
+
if (same) {
|
|
470
|
+
disconnectFromIde();
|
|
471
|
+
ctx.ui.notify(`Disconnected from ${currentLockfile!.ideName}`, "warning");
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
// Switch to a different IDE
|
|
475
|
+
disconnectFromIde();
|
|
165
476
|
}
|
|
166
|
-
|
|
477
|
+
|
|
167
478
|
if (pick.kind === "none") {
|
|
168
479
|
ctx.ui.notify("No running IDE found for this project", "warning");
|
|
169
480
|
return;
|
|
170
481
|
}
|
|
171
|
-
|
|
482
|
+
|
|
172
483
|
const next = new IdeClient(pick.lockfile);
|
|
173
484
|
next.onNotification = onNotification;
|
|
485
|
+
next.onRequest("getSuggestions", async (params, signal) => {
|
|
486
|
+
inFlightSuggestions++;
|
|
487
|
+
if (inFlightSuggestions === 1) startSpinner();
|
|
488
|
+
renderWidget();
|
|
489
|
+
try {
|
|
490
|
+
const suggestions = await generateSuggestions(pi, (params ?? {}) as SuggestionParams, signal);
|
|
491
|
+
return { suggestions };
|
|
492
|
+
} finally {
|
|
493
|
+
inFlightSuggestions--;
|
|
494
|
+
if (inFlightSuggestions === 0) stopSpinner();
|
|
495
|
+
renderWidget();
|
|
496
|
+
}
|
|
497
|
+
});
|
|
498
|
+
next.onRequest("listSuggestionModels", async () => {
|
|
499
|
+
if (!sessionCtx) throw new Error("session not yet started");
|
|
500
|
+
const flagValue = pi.getFlag(SUGGESTION_FLAG);
|
|
501
|
+
const cliOverride = (typeof flagValue === "string" && flagValue) ? flagValue : undefined;
|
|
502
|
+
return {
|
|
503
|
+
cliOverride,
|
|
504
|
+
currentModel: sessionCtx.model ? `${sessionCtx.model.provider}/${sessionCtx.model.id}` : undefined,
|
|
505
|
+
models: sessionCtx.modelRegistry.getAvailable().map((model) => ({
|
|
506
|
+
provider: model.provider,
|
|
507
|
+
id: model.id,
|
|
508
|
+
name: model.name,
|
|
509
|
+
model: `${model.provider}/${model.id}`,
|
|
510
|
+
})),
|
|
511
|
+
};
|
|
512
|
+
});
|
|
174
513
|
next.onClose = () => {
|
|
175
514
|
if (client === next) {
|
|
176
515
|
client = null;
|
|
177
516
|
resetState();
|
|
517
|
+
inFlightSuggestions = 0;
|
|
518
|
+
stopSpinner();
|
|
178
519
|
renderWidget();
|
|
179
520
|
ctx.ui.notify("IDE disconnected", "warning");
|
|
180
521
|
}
|
|
@@ -191,14 +532,25 @@ export default function (pi: ExtensionAPI) {
|
|
|
191
532
|
},
|
|
192
533
|
});
|
|
193
534
|
|
|
194
|
-
pi.on("
|
|
535
|
+
pi.on("context", async (event) => {
|
|
195
536
|
const blocks: string[] = [];
|
|
196
537
|
const editor = renderEditorBlock();
|
|
197
538
|
if (editor) blocks.push(editor);
|
|
198
539
|
const diagnostics = await fetchDiagnosticsBlock();
|
|
199
540
|
if (diagnostics) blocks.push(diagnostics);
|
|
200
541
|
if (blocks.length === 0) return;
|
|
201
|
-
return {
|
|
542
|
+
return {
|
|
543
|
+
messages: [
|
|
544
|
+
...event.messages,
|
|
545
|
+
{
|
|
546
|
+
role: "custom",
|
|
547
|
+
customType: "pi-ide.editor-context",
|
|
548
|
+
content: blocks.join("\n\n"),
|
|
549
|
+
display: false,
|
|
550
|
+
timestamp: Date.now(),
|
|
551
|
+
},
|
|
552
|
+
],
|
|
553
|
+
};
|
|
202
554
|
});
|
|
203
555
|
|
|
204
556
|
pi.on("tool_call", async (event, ctx) => {
|
|
@@ -267,6 +619,8 @@ export default function (pi: ExtensionAPI) {
|
|
|
267
619
|
|
|
268
620
|
pi.on("session_shutdown", () => {
|
|
269
621
|
client?.close();
|
|
622
|
+
inFlightSuggestions = 0;
|
|
623
|
+
stopSpinner();
|
|
270
624
|
renderWidget();
|
|
271
625
|
client = null;
|
|
272
626
|
resetState();
|
package/package.json
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ldelossa/pi-ide",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
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
|
-
}
|