@ldelossa/pi-ide 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +165 -0
- package/client.ts +189 -0
- package/index.ts +274 -0
- package/package.json +39 -0
- package/tsconfig.json +17 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Louis DeLosSantos
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
6
|
+
this software and associated documentation files (the "Software"), to deal in
|
|
7
|
+
the Software without restriction, including without limitation the rights to
|
|
8
|
+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
|
9
|
+
of the Software, and to permit persons to whom the Software is furnished to do
|
|
10
|
+
so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
# pi-ide
|
|
2
|
+
|
|
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.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
pi install git:github.com/ldelossa/pi-ide@v0.1.0
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
That writes to `~/.pi/agent/settings.json` and loads pi-ide on every pi
|
|
16
|
+
session. To scope it to one project instead of globally, add `-l`:
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pi install -l git:github.com/ldelossa/pi-ide@v0.1.0
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Project installs land in `./.pi/settings.json` and can be checked in so
|
|
23
|
+
teammates pick the extension up automatically.
|
|
24
|
+
|
|
25
|
+
To try it without installing permanently:
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pi -e git:github.com/ldelossa/pi-ide@v0.1.0
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
To remove:
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pi remove git:github.com/ldelossa/pi-ide
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
You also need an editor that speaks the protocol. The reference Neovim
|
|
38
|
+
implementation is at <https://github.com/ldelossa/pi-ide.nvim>.
|
|
39
|
+
|
|
40
|
+
Once both are running, use `/ide` inside pi to connect to the editor.
|
|
41
|
+
|
|
42
|
+
## Architecture
|
|
43
|
+
|
|
44
|
+
1. Editor starts a loopback MCP server on a free TCP port. Writes a lockfile to
|
|
45
|
+
`$PI_IDE_LOCK_DIR` (default `~/.pi/ide/<port>.lock`). Removes it on exit.
|
|
46
|
+
2. User runs `/ide` in pi. Extension enumerates lockfiles, filters to entries
|
|
47
|
+
whose `workspaceFolders` cover `cwd`, whose `pid` is alive, and whose port
|
|
48
|
+
accepts connections. Prompts on multiple matches.
|
|
49
|
+
3. Extension opens `ws://127.0.0.1:<port>/` with header
|
|
50
|
+
`x-pi-ide-authorization: <authToken>` and runs MCP `initialize`.
|
|
51
|
+
4. While connected:
|
|
52
|
+
- Editor pushes `selection_changed` notifications. Extension caches
|
|
53
|
+
`filePath`, cursor, selection. Renders a status widget.
|
|
54
|
+
- Before each agent run, cached state is injected into the system prompt as
|
|
55
|
+
an `<editor>` block.
|
|
56
|
+
- On every `write` or `edit` tool call, extension calls `openDiff`. The call
|
|
57
|
+
blocks until the editor returns `FILE_SAVED` (accept) or `DIFF_REJECTED`
|
|
58
|
+
(reject). On reject, the tool call is blocked and the rejection is
|
|
59
|
+
surfaced to the agent.
|
|
60
|
+
5. Session shutdown closes the socket.
|
|
61
|
+
|
|
62
|
+
## Lockfile
|
|
63
|
+
|
|
64
|
+
Path: `$PI_IDE_LOCK_DIR/<port>.lock` (default `~/.pi/ide/<port>.lock`).
|
|
65
|
+
|
|
66
|
+
```
|
|
67
|
+
{
|
|
68
|
+
"pid": <int>,
|
|
69
|
+
"workspaceFolders": ["<abs path>", ...],
|
|
70
|
+
"ideName": "<display name>",
|
|
71
|
+
"transport": "ws",
|
|
72
|
+
"authToken": "<uuid>"
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Transport
|
|
77
|
+
|
|
78
|
+
- WebSocket on `127.0.0.1:<port>`, path `/`.
|
|
79
|
+
- Required header: `x-pi-ide-authorization: <authToken>`. Mismatches
|
|
80
|
+
must be rejected before upgrade.
|
|
81
|
+
- Framing: JSON-RPC 2.0 in text frames. One message per frame.
|
|
82
|
+
- Protocol: MCP `2024-11-05`. Subset only. `resources/*`, `prompts/*`,
|
|
83
|
+
`logging/*`, and sampling are not used. Server-reported capabilities are
|
|
84
|
+
ignored by the client. Four methods carry the protocol: `initialize`,
|
|
85
|
+
`notifications/initialized`, `tools/list`, `tools/call`.
|
|
86
|
+
|
|
87
|
+
## Editor-side contract
|
|
88
|
+
|
|
89
|
+
The editor must:
|
|
90
|
+
|
|
91
|
+
1. Serve MCP on loopback. Write the lockfile on start, remove on shutdown.
|
|
92
|
+
2. Authenticate the upgrade header against the lockfile's `authToken`.
|
|
93
|
+
3. Implement `initialize`, `tools/list`, `tools/call`.
|
|
94
|
+
4. Implement the tools below.
|
|
95
|
+
5. Emit the notifications below.
|
|
96
|
+
|
|
97
|
+
### Tool: `openDiff`
|
|
98
|
+
|
|
99
|
+
Input:
|
|
100
|
+
|
|
101
|
+
| field | type | description |
|
|
102
|
+
| ------------------- | ------ | ------------------------------------------ |
|
|
103
|
+
| `old_file_path` | string | absolute path of the existing file |
|
|
104
|
+
| `new_file_path` | string | destination path (typically same as old) |
|
|
105
|
+
| `new_file_contents` | string | proposed contents |
|
|
106
|
+
| `tab_name` | string | stable id for this diff invocation |
|
|
107
|
+
|
|
108
|
+
Behavior: open a two-pane diff between on-disk content and proposed content.
|
|
109
|
+
Block (suspend the JSON-RPC response) until the user accepts or rejects.
|
|
110
|
+
|
|
111
|
+
Response on accept:
|
|
112
|
+
|
|
113
|
+
```
|
|
114
|
+
{ "content": [
|
|
115
|
+
{ "type": "text", "text": "FILE_SAVED" },
|
|
116
|
+
{ "type": "text", "text": "<final contents>" }
|
|
117
|
+
]}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
Final contents may differ from `new_file_contents` if the user edited the diff
|
|
121
|
+
before saving.
|
|
122
|
+
|
|
123
|
+
Response on reject:
|
|
124
|
+
|
|
125
|
+
```
|
|
126
|
+
{ "content": [
|
|
127
|
+
{ "type": "text", "text": "DIFF_REJECTED" },
|
|
128
|
+
{ "type": "text", "text": "<tab_name>" }
|
|
129
|
+
]}
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
### Tool: `close_tab`
|
|
133
|
+
|
|
134
|
+
Input: `tab_name` (string). Close the named diff if open. No-op otherwise.
|
|
135
|
+
|
|
136
|
+
Response:
|
|
137
|
+
|
|
138
|
+
```
|
|
139
|
+
{ "content": [ { "type": "text", "text": "TAB_CLOSED" } ] }
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
### Notification: `selection_changed`
|
|
143
|
+
|
|
144
|
+
JSON-RPC notification (no `id`). Sent on cursor move, mode change, buffer
|
|
145
|
+
enter, and text change. Debounce locally (~100ms recommended).
|
|
146
|
+
|
|
147
|
+
```
|
|
148
|
+
{
|
|
149
|
+
"text": "<selected text, empty when no selection>",
|
|
150
|
+
"filePath": "<abs path>",
|
|
151
|
+
"fileUrl": "file://<abs path>",
|
|
152
|
+
"selection": {
|
|
153
|
+
"start": { "line": <0-based>, "character": <0-based> },
|
|
154
|
+
"end": { "line": <0-based>, "character": <0-based> },
|
|
155
|
+
"isEmpty": <bool>
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Lines and characters are zero-based. The extension renders line numbers as
|
|
161
|
+
1-based.
|
|
162
|
+
|
|
163
|
+
## Reference editor implementation
|
|
164
|
+
|
|
165
|
+
Neovim: `pi-ide.nvim`.
|
package/client.ts
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { readdir, readFile } from "node:fs/promises";
|
|
3
|
+
import * as net from "node:net";
|
|
4
|
+
import { homedir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import WebSocket from "ws";
|
|
7
|
+
|
|
8
|
+
export type Lockfile = {
|
|
9
|
+
port: number;
|
|
10
|
+
pid: number;
|
|
11
|
+
workspaceFolders: string[];
|
|
12
|
+
ideName: string;
|
|
13
|
+
authToken: string;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export type McpContent = { type: "text"; text: string }[];
|
|
17
|
+
export type McpResult = { content: McpContent };
|
|
18
|
+
|
|
19
|
+
type Pending = { resolve: (v: unknown) => void; reject: (e: Error) => void };
|
|
20
|
+
|
|
21
|
+
const AUTH_HEADER = "x-pi-ide-authorization";
|
|
22
|
+
const PROTOCOL_VERSION = "2024-11-05";
|
|
23
|
+
|
|
24
|
+
export function getLockDir(): string {
|
|
25
|
+
return process.env.PI_IDE_LOCK_DIR ?? join(homedir(), ".pi", "ide");
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function listLockfiles(): Promise<Lockfile[]> {
|
|
29
|
+
const dir = getLockDir();
|
|
30
|
+
let entries: string[];
|
|
31
|
+
try {
|
|
32
|
+
entries = await readdir(dir);
|
|
33
|
+
} catch (err) {
|
|
34
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") return [];
|
|
35
|
+
throw err;
|
|
36
|
+
}
|
|
37
|
+
const out: Lockfile[] = [];
|
|
38
|
+
for (const entry of entries) {
|
|
39
|
+
if (!entry.endsWith(".lock")) continue;
|
|
40
|
+
const port = Number.parseInt(entry.slice(0, -5), 10);
|
|
41
|
+
if (!Number.isFinite(port)) continue;
|
|
42
|
+
try {
|
|
43
|
+
const data = JSON.parse(await readFile(join(dir, entry), "utf-8"));
|
|
44
|
+
if (typeof data.pid !== "number" || typeof data.authToken !== "string") continue;
|
|
45
|
+
out.push({
|
|
46
|
+
port,
|
|
47
|
+
pid: data.pid,
|
|
48
|
+
workspaceFolders: Array.isArray(data.workspaceFolders) ? data.workspaceFolders : [],
|
|
49
|
+
ideName: typeof data.ideName === "string" ? data.ideName : "unknown",
|
|
50
|
+
authToken: data.authToken,
|
|
51
|
+
});
|
|
52
|
+
} catch {}
|
|
53
|
+
}
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function isPidAlive(pid: number): boolean {
|
|
58
|
+
try {
|
|
59
|
+
process.kill(pid, 0);
|
|
60
|
+
return true;
|
|
61
|
+
} catch (err) {
|
|
62
|
+
return (err as NodeJS.ErrnoException).code === "EPERM";
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function isPortListening(port: number): Promise<boolean> {
|
|
67
|
+
return new Promise((resolve) => {
|
|
68
|
+
const socket = net.connect({ port, host: "127.0.0.1" });
|
|
69
|
+
socket.once("connect", () => {
|
|
70
|
+
socket.destroy();
|
|
71
|
+
resolve(true);
|
|
72
|
+
});
|
|
73
|
+
socket.once("error", () => resolve(false));
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function matchesCwd(lockfile: Lockfile, cwd: string): boolean {
|
|
78
|
+
const norm = (p: string) => (p.endsWith("/") ? p : `${p}/`);
|
|
79
|
+
const target = norm(cwd);
|
|
80
|
+
return lockfile.workspaceFolders.some((f) => {
|
|
81
|
+
const folder = norm(f);
|
|
82
|
+
return target === folder || target.startsWith(folder);
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export type NotificationHandler = (method: string, params: unknown) => void;
|
|
87
|
+
|
|
88
|
+
export class IdeClient {
|
|
89
|
+
private ws: WebSocket | null = null;
|
|
90
|
+
private closed = false;
|
|
91
|
+
public readonly lockfile: Lockfile;
|
|
92
|
+
private pending = new Map<string, Pending>();
|
|
93
|
+
public onNotification: NotificationHandler = () => {};
|
|
94
|
+
public onClose: () => void = () => {};
|
|
95
|
+
|
|
96
|
+
constructor(lockfile: Lockfile) {
|
|
97
|
+
this.lockfile = lockfile;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async connect(): Promise<void> {
|
|
101
|
+
const ws = new WebSocket(`ws://127.0.0.1:${this.lockfile.port}/`, {
|
|
102
|
+
headers: { [AUTH_HEADER]: this.lockfile.authToken },
|
|
103
|
+
});
|
|
104
|
+
await new Promise<void>((resolve, reject) => {
|
|
105
|
+
ws.once("open", () => resolve());
|
|
106
|
+
ws.once("error", (err) => reject(err));
|
|
107
|
+
});
|
|
108
|
+
this.ws = ws;
|
|
109
|
+
ws.on("message", (data) => this.handleMessage(data.toString()));
|
|
110
|
+
ws.on("close", () => this.handleClose());
|
|
111
|
+
ws.on("error", () => {});
|
|
112
|
+
try {
|
|
113
|
+
await this.request("initialize", {
|
|
114
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
115
|
+
capabilities: {},
|
|
116
|
+
clientInfo: { name: "pi-ide", version: "0.1.0" },
|
|
117
|
+
});
|
|
118
|
+
} catch (err) {
|
|
119
|
+
this.ws = null;
|
|
120
|
+
try {
|
|
121
|
+
ws.close();
|
|
122
|
+
} catch {}
|
|
123
|
+
throw err;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
isConnected(): boolean {
|
|
128
|
+
return this.ws?.readyState === WebSocket.OPEN;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
close(): void {
|
|
132
|
+
if (this.ws) {
|
|
133
|
+
this.ws.close(1000);
|
|
134
|
+
this.ws = null;
|
|
135
|
+
}
|
|
136
|
+
this.handleClose();
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
request(method: string, params?: unknown): Promise<unknown> {
|
|
140
|
+
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
|
|
141
|
+
return Promise.reject(new Error("IDE not connected"));
|
|
142
|
+
}
|
|
143
|
+
const id = randomUUID();
|
|
144
|
+
const payload = JSON.stringify({ jsonrpc: "2.0", id, method, params });
|
|
145
|
+
return new Promise((resolve, reject) => {
|
|
146
|
+
this.pending.set(id, { resolve, reject });
|
|
147
|
+
this.ws!.send(payload, (err) => {
|
|
148
|
+
if (err) {
|
|
149
|
+
this.pending.delete(id);
|
|
150
|
+
reject(err);
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
callTool(name: string, args: Record<string, unknown>): Promise<McpResult> {
|
|
157
|
+
return this.request("tools/call", { name, arguments: args }) as Promise<McpResult>;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
private handleMessage(text: string): void {
|
|
161
|
+
let msg: { id?: string; method?: string; params?: unknown; result?: unknown; error?: { code: number; message: string } };
|
|
162
|
+
try {
|
|
163
|
+
msg = JSON.parse(text);
|
|
164
|
+
} catch {
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
if (msg.id !== undefined) {
|
|
168
|
+
const pending = this.pending.get(msg.id);
|
|
169
|
+
if (!pending) return;
|
|
170
|
+
this.pending.delete(msg.id);
|
|
171
|
+
if (msg.error) pending.reject(new Error(`${msg.error.code}: ${msg.error.message}`));
|
|
172
|
+
else pending.resolve(msg.result);
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
if (typeof msg.method === "string") {
|
|
176
|
+
this.onNotification(msg.method, msg.params);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
private handleClose(): void {
|
|
181
|
+
if (this.closed) return;
|
|
182
|
+
this.closed = true;
|
|
183
|
+
const err = new Error("IDE connection closed");
|
|
184
|
+
for (const pending of this.pending.values()) pending.reject(err);
|
|
185
|
+
this.pending.clear();
|
|
186
|
+
this.ws = null;
|
|
187
|
+
this.onClose();
|
|
188
|
+
}
|
|
189
|
+
}
|
package/index.ts
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { basename, resolve as resolvePath } from "node:path";
|
|
3
|
+
import { isToolCallEventType, type ExtensionAPI, type ExtensionUIContext } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import { IdeClient, isPidAlive, isPortListening, listLockfiles, type Lockfile, matchesCwd } from "./client.ts";
|
|
5
|
+
|
|
6
|
+
type Selection = { startLine: number; endLine: number; text: string };
|
|
7
|
+
type EditorState = { filePath: string | null; cursorLine: number | null; selection: Selection | null };
|
|
8
|
+
|
|
9
|
+
const MAX_SELECTION_LINES = 100;
|
|
10
|
+
const WIDGET_KEY = "pi-ide";
|
|
11
|
+
|
|
12
|
+
let client: IdeClient | null = null;
|
|
13
|
+
let state: EditorState = { filePath: null, cursorLine: null, selection: null };
|
|
14
|
+
let ui: ExtensionUIContext | null = null;
|
|
15
|
+
|
|
16
|
+
function resetState(): void {
|
|
17
|
+
state = { filePath: null, cursorLine: null, selection: null };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function renderWidget(): void {
|
|
21
|
+
if (!ui) return;
|
|
22
|
+
if (!client?.isConnected()) {
|
|
23
|
+
ui.setWidget(WIDGET_KEY, undefined);
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
const ideName = client.lockfile.ideName;
|
|
27
|
+
let body: string;
|
|
28
|
+
if (state.selection && state.filePath) {
|
|
29
|
+
body = `${ideName} · Lines ${state.selection.startLine + 1}-${state.selection.endLine + 1} selected in ${basename(state.filePath)}`;
|
|
30
|
+
} else if (state.filePath) {
|
|
31
|
+
body = `${ideName} · In ${basename(state.filePath)}`;
|
|
32
|
+
} else {
|
|
33
|
+
body = ideName;
|
|
34
|
+
}
|
|
35
|
+
ui.setWidget(WIDGET_KEY, [body]);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function onNotification(method: string, params: unknown): void {
|
|
39
|
+
if (method !== "selection_changed" || !params || typeof params !== "object") return;
|
|
40
|
+
const p = params as {
|
|
41
|
+
text?: string;
|
|
42
|
+
filePath?: string;
|
|
43
|
+
selection?: { start: { line: number }; end: { line: number }; isEmpty: boolean };
|
|
44
|
+
};
|
|
45
|
+
if (!p.filePath || !p.selection) return;
|
|
46
|
+
state.filePath = p.filePath;
|
|
47
|
+
state.cursorLine = p.selection.start.line;
|
|
48
|
+
state.selection = p.selection.isEmpty
|
|
49
|
+
? null
|
|
50
|
+
: { startLine: p.selection.start.line, endLine: p.selection.end.line, text: p.text ?? "" };
|
|
51
|
+
renderWidget();
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function renderEditorBlock(): string | null {
|
|
55
|
+
if (!state.filePath) return null;
|
|
56
|
+
const out = ["<editor>", ` <file>${state.filePath}</file>`];
|
|
57
|
+
if (state.cursorLine !== null) out.push(` <cursor>line ${state.cursorLine + 1}</cursor>`);
|
|
58
|
+
if (state.selection) {
|
|
59
|
+
const lines = state.selection.text.split("\n");
|
|
60
|
+
const text =
|
|
61
|
+
lines.length <= MAX_SELECTION_LINES
|
|
62
|
+
? state.selection.text
|
|
63
|
+
: `${lines.slice(0, MAX_SELECTION_LINES).join("\n")}\n... <truncated ${lines.length - MAX_SELECTION_LINES} more lines>`;
|
|
64
|
+
out.push(` <selection lines="${state.selection.startLine + 1}-${state.selection.endLine + 1}">`);
|
|
65
|
+
out.push(text);
|
|
66
|
+
out.push(" </selection>");
|
|
67
|
+
}
|
|
68
|
+
out.push("</editor>");
|
|
69
|
+
return out.join("\n");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function parseDiffResult(result: { content?: { text?: string }[] }): { saved: boolean; text: string } {
|
|
73
|
+
const items = result?.content ?? [];
|
|
74
|
+
const marker = items[0]?.text;
|
|
75
|
+
if (marker === "FILE_SAVED") return { saved: true, text: items[1]?.text ?? "" };
|
|
76
|
+
return { saved: false, text: "" };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const MAX_DIAGNOSTICS = 50;
|
|
80
|
+
|
|
81
|
+
type Diagnostic = {
|
|
82
|
+
severity: string;
|
|
83
|
+
message: string;
|
|
84
|
+
source?: string;
|
|
85
|
+
range: { start: { line: number; character: number }; end: { line: number; character: number } };
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
async function fetchDiagnosticsBlock(): Promise<string | null> {
|
|
89
|
+
if (!client?.isConnected()) return null;
|
|
90
|
+
let result: { content?: { text?: string }[] };
|
|
91
|
+
try {
|
|
92
|
+
result = await client.callTool("getDiagnostics", {});
|
|
93
|
+
} catch {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
const text = result?.content?.[0]?.text;
|
|
97
|
+
if (!text) return null;
|
|
98
|
+
let parsed: Record<string, Diagnostic[]>;
|
|
99
|
+
try {
|
|
100
|
+
parsed = JSON.parse(text);
|
|
101
|
+
} catch {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
const lines: string[] = [];
|
|
105
|
+
for (const [uri, items] of Object.entries(parsed)) {
|
|
106
|
+
for (const d of items) {
|
|
107
|
+
if (d.severity !== "Error" && d.severity !== "Warning") continue;
|
|
108
|
+
lines.push(
|
|
109
|
+
`${uri}:${d.range.start.line + 1}:${d.range.start.character + 1} [${d.severity}] ${d.message}`,
|
|
110
|
+
);
|
|
111
|
+
if (lines.length >= MAX_DIAGNOSTICS) break;
|
|
112
|
+
}
|
|
113
|
+
if (lines.length >= MAX_DIAGNOSTICS) break;
|
|
114
|
+
}
|
|
115
|
+
if (lines.length === 0) return null;
|
|
116
|
+
return `<lsp_diagnostics>\n${lines.join("\n")}\n</lsp_diagnostics>`;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function applyEdits(original: string, edits: { oldText: string; newText: string }[]): string {
|
|
120
|
+
let result = original;
|
|
121
|
+
for (const edit of edits) {
|
|
122
|
+
const idx = result.indexOf(edit.oldText);
|
|
123
|
+
if (idx === -1) throw new Error("edit oldText not found in file");
|
|
124
|
+
if (result.indexOf(edit.oldText, idx + 1) !== -1) {
|
|
125
|
+
throw new Error("edit oldText not unique in file");
|
|
126
|
+
}
|
|
127
|
+
// slice+concat avoids String.replace's $N pattern interpretation.
|
|
128
|
+
result = result.slice(0, idx) + edit.newText + result.slice(idx + edit.oldText.length);
|
|
129
|
+
}
|
|
130
|
+
return result;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
type PickResult =
|
|
134
|
+
| { kind: "selected"; lockfile: Lockfile }
|
|
135
|
+
| { kind: "none" }
|
|
136
|
+
| { kind: "cancelled" };
|
|
137
|
+
|
|
138
|
+
async function pickLockfile(cwd: string, ui: { select: (t: string, o: string[]) => Promise<string | undefined> }): Promise<PickResult> {
|
|
139
|
+
const all = await listLockfiles();
|
|
140
|
+
const candidates: Lockfile[] = [];
|
|
141
|
+
for (const lf of all) {
|
|
142
|
+
if (!matchesCwd(lf, cwd)) continue;
|
|
143
|
+
if (!isPidAlive(lf.pid)) continue;
|
|
144
|
+
if (!(await isPortListening(lf.port))) continue;
|
|
145
|
+
candidates.push(lf);
|
|
146
|
+
}
|
|
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}`;
|
|
151
|
+
});
|
|
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" };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export default function (pi: ExtensionAPI) {
|
|
159
|
+
pi.registerCommand("ide", {
|
|
160
|
+
description: "Connect to a running IDE for ambient context and IDE-routed diffs.",
|
|
161
|
+
async handler(_args, ctx) {
|
|
162
|
+
if (client?.isConnected()) {
|
|
163
|
+
ctx.ui.notify(`Already connected to ${client.lockfile.ideName} (port ${client.lockfile.port})`);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
const pick = await pickLockfile(ctx.cwd, ctx.ui);
|
|
167
|
+
if (pick.kind === "none") {
|
|
168
|
+
ctx.ui.notify("No running IDE found for this project", "warning");
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
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();
|
|
191
|
+
},
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
pi.on("before_agent_start", async (event) => {
|
|
195
|
+
const blocks: string[] = [];
|
|
196
|
+
const editor = renderEditorBlock();
|
|
197
|
+
if (editor) blocks.push(editor);
|
|
198
|
+
const diagnostics = await fetchDiagnosticsBlock();
|
|
199
|
+
if (diagnostics) blocks.push(diagnostics);
|
|
200
|
+
if (blocks.length === 0) return;
|
|
201
|
+
return { systemPrompt: `${event.systemPrompt}\n\n${blocks.join("\n\n")}` };
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
pi.on("tool_call", async (event, ctx) => {
|
|
205
|
+
if (!client?.isConnected()) return;
|
|
206
|
+
|
|
207
|
+
let path: string;
|
|
208
|
+
let originalContent: string;
|
|
209
|
+
let proposedContent: string;
|
|
210
|
+
let applyResult: (text: string) => void;
|
|
211
|
+
|
|
212
|
+
if (isToolCallEventType("write", event)) {
|
|
213
|
+
const writeEvent = event;
|
|
214
|
+
path = resolvePath(ctx.cwd, writeEvent.input.path);
|
|
215
|
+
try {
|
|
216
|
+
originalContent = await readFile(path, "utf-8");
|
|
217
|
+
} catch {
|
|
218
|
+
originalContent = "";
|
|
219
|
+
}
|
|
220
|
+
proposedContent = writeEvent.input.content;
|
|
221
|
+
applyResult = (text) => {
|
|
222
|
+
writeEvent.input.content = text;
|
|
223
|
+
};
|
|
224
|
+
} else if (isToolCallEventType("edit", event)) {
|
|
225
|
+
const editEvent = event;
|
|
226
|
+
path = resolvePath(ctx.cwd, editEvent.input.path);
|
|
227
|
+
try {
|
|
228
|
+
originalContent = await readFile(path, "utf-8");
|
|
229
|
+
} catch {
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
try {
|
|
233
|
+
proposedContent = applyEdits(originalContent, editEvent.input.edits);
|
|
234
|
+
} catch (err) {
|
|
235
|
+
ctx.ui.notify(
|
|
236
|
+
`pi-ide: edit preview failed (${err instanceof Error ? err.message : String(err)})`,
|
|
237
|
+
"warning",
|
|
238
|
+
);
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
applyResult = (text) => {
|
|
242
|
+
editEvent.input.edits = [{ oldText: originalContent, newText: text }];
|
|
243
|
+
};
|
|
244
|
+
} else {
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const tabName = `pi-${event.toolName}:${event.toolCallId}`;
|
|
249
|
+
let result: { content?: { text?: string }[] };
|
|
250
|
+
try {
|
|
251
|
+
result = await client.callTool("openDiff", {
|
|
252
|
+
old_file_path: path,
|
|
253
|
+
new_file_path: path,
|
|
254
|
+
new_file_contents: proposedContent,
|
|
255
|
+
tab_name: tabName,
|
|
256
|
+
});
|
|
257
|
+
} catch (err) {
|
|
258
|
+
ctx.ui.notify(`IDE diff failed: ${err instanceof Error ? err.message : String(err)}`, "warning");
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
void client.callTool("close_tab", { tab_name: tabName }).catch(() => {});
|
|
262
|
+
const parsed = parseDiffResult(result);
|
|
263
|
+
if (!parsed.saved) return { block: true, reason: `user rejected the ${event.toolName} in IDE` };
|
|
264
|
+
applyResult(parsed.text);
|
|
265
|
+
return undefined;
|
|
266
|
+
});
|
|
267
|
+
|
|
268
|
+
pi.on("session_shutdown", () => {
|
|
269
|
+
client?.close();
|
|
270
|
+
renderWidget();
|
|
271
|
+
client = null;
|
|
272
|
+
resetState();
|
|
273
|
+
});
|
|
274
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@ldelossa/pi-ide",
|
|
3
|
+
"version": "0.1.0",
|
|
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
|
+
"keywords": ["pi-package", "pi", "ide", "neovim"],
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "Louis DeLosSantos <louis.delos@gmail.com>",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/ldelossa/pi-ide.git"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/ldelossa/pi-ide#readme",
|
|
13
|
+
"bugs": "https://github.com/ldelossa/pi-ide/issues",
|
|
14
|
+
"type": "module",
|
|
15
|
+
"pi": {
|
|
16
|
+
"extensions": ["./index.ts"]
|
|
17
|
+
},
|
|
18
|
+
"scripts": {
|
|
19
|
+
"check": "tsc --noEmit"
|
|
20
|
+
},
|
|
21
|
+
"dependencies": {
|
|
22
|
+
"ws": "8.21.0"
|
|
23
|
+
},
|
|
24
|
+
"peerDependencies": {
|
|
25
|
+
"@earendil-works/pi-agent-core": "*",
|
|
26
|
+
"@earendil-works/pi-ai": "*",
|
|
27
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
28
|
+
"@earendil-works/pi-tui": "*",
|
|
29
|
+
"typebox": "*"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@types/node": "22.19.19",
|
|
33
|
+
"@types/ws": "8.18.1",
|
|
34
|
+
"typescript": "5.9.3"
|
|
35
|
+
},
|
|
36
|
+
"engines": {
|
|
37
|
+
"node": ">=22.19.0"
|
|
38
|
+
}
|
|
39
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
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
|
+
}
|