repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

refactor(intellij): streamline bridge runtime

ef72e9f932563baa9646d082b4f2faa8375a1370

Oliver Krylow <o.krylow@isp-insoft.de> ·

SSH signature · not checked

Browse filesCompare with HEAD

Changed files (6)

extensions/intellij/README.md

Modified
29 29 Remote tools are registered with an `intellij_` prefix.
30 30 The bridge hides `projectPath` from agent-facing schemas and injects the Pi session's exact `ctx.cwd`.
31 -The footer shows IntelliJ connection health as `…`, `✓`, or `✗`.
31 +The footer shows IntelliJ connection health as ` …`, ` ✓`, or ` ✗`.
32 32 Collapsed tool rows show operation, target, and outcome; expand them for diagnostics, matches, patches, and full returned context.
33 33 IntelliJ's **Exposed Tools** setting is the only allowlist.

extensions/intellij/__bench__/catalog.bench.ts

Added
new file mode 100644
1 +import { cpus } from "node:os";
2 +import {
3 + acceptsProjectPath,
4 + schemaWithoutInjectedProjectPath,
5 + validateRemoteTool,
6 +} from "../implementation.ts";
8 +const TOOL_COUNT = 512;
9 +const ITERATIONS = 30;
10 +const ROUNDS = 12;
11 +const schema = {
12 + type: "object" as const,
13 + properties: {
14 + projectPath: { type: "string" },
15 + query: { type: "string", minLength: 1 },
16 + options: {
17 + type: "object",
18 + properties: {
19 + scopes: {
20 + type: "array",
21 + items: {
22 + type: "object",
23 + properties: {
24 + name: { type: "string" },
25 + enabled: { type: "boolean" },
26 + limits: {
27 + type: "object",
28 + properties: {
29 + maximum: { type: "integer" },
30 + ratio: { type: "number" },
31 + },
32 + },
33 + },
34 + required: ["name"],
35 + },
36 + },
37 + },
38 + },
39 + },
40 + required: ["projectPath", "query"],
41 +};
42 +const tools = Array.from({ length: TOOL_COUNT }, (_, index) => ({
43 + name: `tool_${index}`,
44 + inputSchema: schema,
45 +}));
46 +let sink = 0;
48 +function validateCatalog(): void {
49 + for (const candidate of tools)
50 + sink += validateRemoteTool(candidate).name.length;
53 +function projectCatalog(): void {
54 + for (const candidate of tools) {
55 + const tool = validateRemoteTool(candidate);
56 + sink += acceptsProjectPath(tool.inputSchema) ? 1 : 0;
57 + sink += JSON.stringify(
58 + schemaWithoutInjectedProjectPath(tool.inputSchema),
59 + ).length;
60 + }
63 +function bench(name: string, operation: () => void): void {
64 + for (let index = 0; index < 10; index++) operation();
65 + for (let round = 0; round < ROUNDS; round++) {
66 + const start = performance.now();
67 + for (let index = 0; index < ITERATIONS; index++) operation();
68 + const nanoseconds = ((performance.now() - start) * 1_000_000) / ITERATIONS;
69 + console.log(
70 + `Benchmark${name}-${cpus().length}\t${ITERATIONS}\t${nanoseconds.toFixed(0)} ns/op`,
71 + );
72 + }
75 +bench("ValidateCatalog512", validateCatalog);
76 +bench("PrepareCatalog512", projectCatalog);
77 +if (sink === 0) throw new Error("benchmark result was not consumed");

extensions/intellij/__tests__/harness.test.ts

Modified
244 244 ).toBe(false);
247 + it("reports unreadable saved settings without hiding runtime status", async () => {
248 + t = await createTestSession({ extensionFactories: [intellijExtension] });
249 + const settingsDir = join(t.env.HOME as string, ".pi", "agent");
250 + await mkdir(settingsDir, { recursive: true });
251 + await writeFile(join(settingsDir, "settings.json"), "{");
252 + const [extension] = t.session.extensionRunner.extensions;
254 + await extension.commands
255 + .get("intellij")
256 + .handler("status", t.session.extensionRunner.createCommandContext());
258 + expect(t.events.uiCallsFor("notify").at(-1)?.args).toEqual([
259 + expect.stringContaining(
260 + "IntelliJ MCP: disconnected\nendpoint: unavailable (settings read failed)",
261 + ),
262 + "warning",
263 + ]);
264 + });
247 266 it("cancels an in-flight connection without launching IntelliJ", async () => {
248 267 const root = await mkdtemp(join(tmpdir(), "intellij-cancel-"));
249 268 roots.push(root);
475 494 await command.handler(`connect ${fake.url}`, ctx);
476 495 const status = String(t.events.uiCallsFor("setStatus").at(-1)?.args[1]);
477 - expect(status).toContain("✓");
496 + expect(status).toContain(" ✓");
478 497 expect(status).not.toContain("tools");
480 499 const probe = extension.tools.get(

extensions/intellij/implementation.ts

Modified
97 97 const RETRY_DELAY_MS = 400;
98 98 const MAX_CATALOG_TOOLS = 512;
99 99 const MAX_SCHEMA_BYTES = 256 * 1024;
100 +const VALID_SCHEMA_TYPES = new Set([
101 + "null",
102 + "boolean",
103 + "object",
104 + "array",
105 + "number",
106 + "integer",
107 + "string",
108 +]);
109 +const SCHEMA_MAP_KEYWORDS = [
110 + "properties",
111 + "patternProperties",
112 + "$defs",
113 + "definitions",
114 +] as const;
115 +const SCHEMA_CHILD_KEYWORDS = [
116 + "additionalProperties",
117 + "unevaluatedProperties",
118 + "items",
119 + "contains",
120 + "propertyNames",
121 + "not",
122 + "if",
123 + "then",
124 + "else",
125 +] as const;
126 +const SCHEMA_ARRAY_KEYWORDS = [
127 + "allOf",
128 + "anyOf",
129 + "oneOf",
130 + "prefixItems",
131 +] as const;
132 +const SCHEMA_COMPOSITION_KEYWORDS = ["allOf", "anyOf", "oneOf"] as const;
100 133 const PROJECT_PROBE = "get_project_modules";
101 134 // nf-dev-intellij, U+E7B5.
102 135 const INTELLIJ_ICON = "";
157 190 const target = resolveLocalRef(root, schema.$ref);
158 191 if (acceptsProjectPathIn(target, root, visitedRefs)) return true;
160 - return [schema.allOf, schema.anyOf, schema.oneOf].some(
161 - (value) =>
193 + return SCHEMA_COMPOSITION_KEYWORDS.some((keyword) => {
194 + const value = schema[keyword];
195 + return (
162 196 Array.isArray(value) &&
163 - value.some((entry) => acceptsProjectPathIn(entry, root, visitedRefs)),
164 - );
197 + value.some((entry) => acceptsProjectPathIn(entry, root, visitedRefs))
198 + );
199 + });
167 202 function schemaAcceptsString(
181 216 return true;
183 - return [schema.allOf, schema.anyOf, schema.oneOf].some(
184 - (value) =>
218 + return SCHEMA_COMPOSITION_KEYWORDS.some((keyword) => {
219 + const value = schema[keyword];
220 + return (
185 221 Array.isArray(value) &&
186 - value.some((entry) => schemaAcceptsString(entry, root, visitedRefs)),
187 - );
222 + value.some((entry) => schemaAcceptsString(entry, root, visitedRefs))
223 + );
224 + });
190 227 function resolveLocalRef(root: JsonObject, reference: string): unknown {
201 238 export function schemaWithoutInjectedProjectPath(
202 239 schema: JsonObject & { type: "object" },
203 240 ): JsonObject & { type: "object" } {
204 - const clone = structuredClone(schema);
241 + const nodesToStrip = new Set<JsonObject>();
205 242 const visited = new Set<JsonObject>();
206 - const strip = (node: unknown): void => {
243 + const findProjectSchemas = (node: unknown): void => {
207 244 if (!isRecord(node) || visited.has(node)) return;
208 245 visited.add(node);
209 - if (isRecord(node.properties)) delete node.properties.projectPath;
210 - if (Array.isArray(node.required))
211 - node.required = node.required.filter((field) => field !== "projectPath");
212 - if (typeof node.$ref === "string") strip(resolveLocalRef(clone, node.$ref));
213 - for (const keyword of ["allOf", "anyOf", "oneOf"]) {
246 + if (
247 + (isRecord(node.properties) && "projectPath" in node.properties) ||
248 + (Array.isArray(node.required) && node.required.includes("projectPath"))
250 + nodesToStrip.add(node);
251 + if (typeof node.$ref === "string")
252 + findProjectSchemas(resolveLocalRef(schema, node.$ref));
253 + for (const keyword of SCHEMA_COMPOSITION_KEYWORDS) {
214 254 const children = node[keyword];
215 - if (Array.isArray(children)) for (const child of children) strip(child);
255 + if (Array.isArray(children))
256 + for (const child of children) findProjectSchemas(child);
218 - strip(clone);
219 - return clone;
259 + findProjectSchemas(schema);
260 + if (nodesToStrip.size === 0) return schema;
262 + // MCP schemas are validated immutable JSON. Copy only paths leading to the
263 + // bridge-owned field; cloning every untouched schema node dominated connect CPU.
264 + const copyChangedPaths = (value: unknown): unknown => {
265 + if (Array.isArray(value)) {
266 + let changed = false;
267 + const children = value.map((child) => {
268 + const copy = copyChangedPaths(child);
269 + if (copy !== child) changed = true;
270 + return copy;
271 + });
272 + return changed ? children : value;
274 + if (!isRecord(value)) return value;
275 + let copy: JsonObject | undefined;
276 + for (const [key, child] of Object.entries(value)) {
277 + const childCopy = copyChangedPaths(child);
278 + if (childCopy !== child) {
279 + copy ??= { ...value };
280 + copy[key] = childCopy;
283 + if (nodesToStrip.has(value)) {
284 + const current = copy ?? value;
285 + if (isRecord(current.properties) && "projectPath" in current.properties) {
286 + copy ??= { ...value };
287 + copy.properties = { ...current.properties };
288 + delete (copy.properties as JsonObject).projectPath;
290 + if (
291 + Array.isArray(current.required) &&
292 + current.required.includes("projectPath")
293 + ) {
294 + copy ??= { ...value };
295 + copy.required = current.required.filter(
296 + (field) => field !== "projectPath",
297 + );
300 + return copy ?? value;
301 + };
302 + return copyChangedPaths(schema) as JsonObject & { type: "object" };
222 305 export function validateRemoteTool(value: unknown): RemoteTool {
255 338 ): void {
256 339 if (!isRecord(value) || depth > 64 || ++budget.count > 10_000)
257 340 throw new Error("MCP tool schema contains an invalid nested schema.");
258 - const validTypes = new Set([
259 - "null",
260 - "boolean",
261 - "object",
262 - "array",
263 - "number",
264 - "integer",
265 - "string",
266 - ]);
268 342 value.type !== undefined &&
270 - (typeof value.type === "string" && validTypes.has(value.type)) ||
344 + (typeof value.type === "string" && VALID_SCHEMA_TYPES.has(value.type)) ||
271 345 (Array.isArray(value.type) &&
272 346 value.type.length > 0 &&
273 347 value.type.every(
274 - (type) => typeof type === "string" && validTypes.has(type),
348 + (type) => typeof type === "string" && VALID_SCHEMA_TYPES.has(type),
299 373 throw new Error("MCP tool schema requires an unknown field.");
301 - for (const keyword of [
302 - "properties",
303 - "patternProperties",
304 - "$defs",
305 - "definitions",
306 - ]) {
375 + for (const keyword of SCHEMA_MAP_KEYWORDS) {
307 376 const entries = value[keyword];
308 377 if (entries === undefined) continue;
309 378 if (!isRecord(entries))
311 380 for (const child of Object.values(entries))
312 381 validateSchemaNode(child, root, depth + 1, budget);
314 - for (const keyword of [
315 - "additionalProperties",
316 - "unevaluatedProperties",
317 - "items",
318 - "contains",
319 - "propertyNames",
320 - "not",
321 - "if",
322 - "then",
323 - "else",
324 - ]) {
383 + for (const keyword of SCHEMA_CHILD_KEYWORDS) {
325 384 const child = value[keyword];
326 385 if (child === undefined || typeof child === "boolean") continue;
327 386 validateSchemaNode(child, root, depth + 1, budget);
329 - for (const keyword of ["allOf", "anyOf", "oneOf", "prefixItems"]) {
388 + for (const keyword of SCHEMA_ARRAY_KEYWORDS) {
330 389 const children = value[keyword];
331 390 if (children === undefined) continue;
332 391 if (!Array.isArray(children) || children.length === 0)
598 -function commandSignal(parent?: AbortSignal): {
599 - signal: AbortSignal;
600 - dispose: () => void;
601 -} {
602 - const timeout = AbortSignal.timeout(CONNECT_TIMEOUT_MS);
603 - return {
604 - signal: parent ? AbortSignal.any([parent, timeout]) : timeout,
605 - dispose: () => {},
606 - };
657 +type ConnectionResult = {
658 + connection: McpConnection;
659 + tools: RemoteTool[];
609 662 async function connectOnce(
610 663 url: string,
611 664 projectPath: string,
612 665 signal?: AbortSignal,
613 -): Promise<{ connection: McpConnection; tools: RemoteTool[] }> {
614 - const bounded = commandSignal(signal);
666 +): Promise<ConnectionResult> {
667 + const timeout = AbortSignal.timeout(CONNECT_TIMEOUT_MS);
668 + const boundedSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
615 669 let connection: McpConnection | undefined;
617 - connection = await openMcpConnection(url, bounded.signal);
671 + connection = await openMcpConnection(url, boundedSignal);
618 672 verifyJetBrains(connection);
619 673 let tools: RemoteTool[];
621 - tools = await connection.listTools(bounded.signal);
675 + tools = await connection.listTools(boundedSignal);
622 676 } catch (error) {
623 677 throw new EndpointValidationError(
624 678 error instanceof Error ? error.message : String(error),
627 - await verifyProject(connection, tools, projectPath, bounded.signal);
681 + await verifyProject(connection, tools, projectPath, boundedSignal);
628 682 return { connection, tools };
629 683 } catch (error) {
630 684 await connection?.close().catch(() => {});
631 685 throw error;
632 - } finally {
633 - bounded.dispose();
704 +async function connectWithLaunch(
705 + url: string,
706 + projectPath: string,
707 + signal: AbortSignal,
708 + allowLaunch: boolean,
709 +): Promise<ConnectionResult> {
710 + try {
711 + return await connectOnce(url, projectPath, signal);
712 + } catch (error) {
713 + if (signal.aborted) throw signal.reason;
714 + if (!allowLaunch || error instanceof EndpointValidationError) throw error;
717 + await launchIdea(projectPath);
718 + signal.throwIfAborted();
719 + const deadline = Date.now() + RETRY_WINDOW_MS;
720 + for (;;) {
721 + try {
722 + return await connectOnce(url, projectPath, signal);
723 + } catch (error) {
724 + if (signal.aborted) throw signal.reason;
725 + if (Date.now() >= deadline) throw error;
726 + await sleep(RETRY_DELAY_MS, signal);
652 731 function samePath(left: string, right: string): boolean {
653 732 const normalize = (value: string) => {
654 733 const absolute = resolve(value).replace(/[\\/]+$/, "");
794 873 state: "connecting" | "connected" | "failed",
795 874 ): void {
796 875 const presentation = {
797 - connecting: ["warning", `${INTELLIJ_ICON}…`],
798 - connected: ["success", `${INTELLIJ_ICON}✓`],
799 - failed: ["error", `${INTELLIJ_ICON}✗`],
876 + connecting: ["warning", `${INTELLIJ_ICON} …`],
877 + connected: ["success", `${INTELLIJ_ICON} ✓`],
878 + failed: ["error", `${INTELLIJ_ICON} ✗`],
800 879 } as const;
801 880 const [color, text] = presentation[state];
802 881 ctx.ui.setStatus("intellij", ctx.ui.theme.fg(color, text));
1083 1162 private generation = 0;
1084 1163 private pendingAbort: AbortController | undefined;
1086 - constructor(private readonly pi: ExtensionAPI) {}
1165 + private readonly pi: ExtensionAPI;
1167 + constructor(pi: ExtensionAPI) {
1168 + this.pi = pi;
1088 1171 async run(
1089 1172 command: IntellijCommand,
1153 1236 let attemptedConnection: McpConnection | undefined;
1155 - let connected: { connection: McpConnection; tools: RemoteTool[] };
1156 - try {
1157 - connected = await connectOnce(url, ctx.cwd, signal);
1158 - } catch (firstError) {
1159 - if (
1160 - signal.aborted ||
1161 - !allowLaunch ||
1162 - firstError instanceof EndpointValidationError
1164 - throw signal.aborted ? signal.reason : firstError;
1165 - await launchIdea(ctx.cwd);
1166 - signal.throwIfAborted();
1167 - const deadline = Date.now() + RETRY_WINDOW_MS;
1168 - let lastError: unknown = firstError;
1169 - for (;;) {
1170 - try {
1171 - connected = await connectOnce(url, ctx.cwd, signal);
1172 - break;
1173 - } catch (error) {
1174 - lastError = error;
1175 - if (signal.aborted) throw signal.reason;
1176 - if (Date.now() >= deadline) throw lastError;
1177 - await sleep(RETRY_DELAY_MS, signal);
1238 + const connected = await connectWithLaunch(
1239 + url,
1240 + ctx.cwd,
1241 + signal,
1242 + allowLaunch,
1243 + );
1181 1244 attemptedConnection = connected.connection;
1182 1245 if (generation !== this.generation) {
1183 1246 await attemptedConnection.close().catch(() => {});
1430 1493 private async showStatus(ctx: ExtensionContext): Promise<void> {
1431 1494 let endpoint = this.endpoint;
1495 + let settingsReadFailed = false;
1432 1496 if (!endpoint) {
1434 1498 endpoint = await readSavedUrl();
1435 1499 } catch {
1436 - // State remains useful when settings cannot be read.
1500 + settingsReadFailed = true;
1439 1503 ctx.ui.notify(
1441 1505 `IntelliJ MCP: ${this.state}`,
1442 - `endpoint: ${endpoint ?? "none"}`,
1506 + settingsReadFailed
1507 + ? "endpoint: unavailable (settings read failed)"
1508 + : `endpoint: ${endpoint ?? "none"}`,
1443 1509 `project: ${this.projectPath ?? ctx.cwd}`,
1444 1510 `active tools: ${
1445 1511 this.pi.getActiveTools().filter((name) => this.ownedNames.has(name))
1446 1512 .length
1448 1514 ].join("\n"),
1449 - "info",
1515 + settingsReadFailed ? "warning" : "info",

extensions/intellij/mise.toml

Added
new file mode 100644
1 +[tasks.lint]
2 +description = "Verify IntelliJ formatting and lint"
3 +depends = ["//:install"]
4 +run = [
5 + "npm exec -- biome ci .",
6 + "rumdl check .",
7 + "taplo format --check",
8 +]
10 +[tasks.test]
11 +description = "Run IntelliJ tests"
12 +depends = ["//:install"]
13 +run = "npm test"
15 +[tasks.check]
16 +description = "Typecheck and statically check IntelliJ"
17 +depends = ["//:install"]
18 +run = [
19 + "npm exec -- tsc --noEmit --project tsconfig.json",
20 + "node ../../scripts/extensions.mjs check intellij",
23 +[tasks.bench]
24 +description = "Benchmark IntelliJ catalog preparation"
25 +depends = ["//:install"]
26 +run = "node --no-warnings --experimental-strip-types --experimental-loader ../../scripts/ts-js-loader.mjs __bench__/catalog.bench.ts"

extensions/intellij/tsconfig.json

Added
new file mode 100644
1 +{
2 + "extends": "../../tsconfig.json",
3 + "include": ["*.ts"],
4 + "exclude": ["__bench__", "__tests__"]
5 +}