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
Modified29 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
Addednew file mode 100644 1 +import { cpus }
from "node:os";
4 + schemaWithoutInjectedProjectPath,
6 +}
from "../implementation.ts";
8 +const TOOL_COUNT
= 512;
9 +const ITERATIONS
= 30;
12 + type:
"object" as const,
14 + projectPath: { type:
"string" },
15 + query: { type:
"string", minLength:
1 },
24 + name: { type:
"string" },
25 + enabled: { type:
"boolean" },
29 + maximum: { type:
"integer" },
30 + ratio: { type:
"number" },
40 + required: [
"projectPath",
"query"],
42 +const tools
= Array.
from({ length: TOOL_COUNT }, (_, index)
=> ({
43 + name:
`tool_${index}`,
44 + inputSchema: schema,
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),
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;
70 + `Benchmark${name}-${cpus().length}\t${ITERATIONS}\t${nanoseconds.toFixed(0)} ns/op`,
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 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
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)",
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([
109 +const SCHEMA_MAP_KEYWORDS
= [
111 + "patternProperties",
115 +const SCHEMA_CHILD_KEYWORDS
= [
116 + "additionalProperties",
117 + "unevaluatedProperties",
126 +const SCHEMA_ARRAY_KEYWORDS
= [
132 +const SCHEMA_COMPOSITION_KEYWORDS
= [
"allOf",
"anyOf",
"oneOf"]
as const;
100 133 const PROJECT_PROBE
= "get_project_modules";
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(
193 + return SCHEMA_COMPOSITION_KEYWORDS.
some((keyword)
=> {
194 + const value
= schema[keyword];
162 196 Array.
isArray(value)
&& 163 - value.
some((entry)
=> acceptsProjectPathIn(entry,
root, visitedRefs)),
197 + value.
some((entry)
=> acceptsProjectPathIn(entry,
root, visitedRefs))
167 202 function schemaAcceptsString(
183 - return [schema.allOf, schema.anyOf, schema.oneOf].
some(
218 + return SCHEMA_COMPOSITION_KEYWORDS.
some((keyword)
=> {
219 + const value
= schema[keyword];
185 221 Array.
isArray(value)
&& 186 - value.
some((entry)
=> schemaAcceptsString(entry,
root, visitedRefs)),
222 + value.
some((entry)
=> schemaAcceptsString(entry,
root, visitedRefs))
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"]) {
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);
259 + findProjectSchemas(schema);
260 + if (nodesToStrip.
size === 0)
return schema;
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;
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;
291 + Array.
isArray(current.required)
&& 292 + current.required.
includes(
"projectPath")
294 + copy
??= {
...value };
295 + copy.required
= current.required.
filter(
296 + (field)
=> field
!== "projectPath",
300 + return copy
?? value;
302 + return copyChangedPaths(schema)
as JsonObject & { type
: "object" };
222 305 export function validateRemoteTool(value
: unknown)
: RemoteTool {
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([
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 [
303 - "patternProperties",
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",
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;
602 - const timeout
= AbortSignal.
timeout(CONNECT_TIMEOUT_MS);
604 - signal: parent
? AbortSignal.
any([parent, timeout])
: timeout,
657 +type ConnectionResult = {
658 + connection
: McpConnection;
659 + tools
: RemoteTool[];
609 662 async function connectOnce(
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(()
=> {});
704 +async function connectWithLaunch(
706 + projectPath
: string,
707 + signal
: AbortSignal,
708 + allowLaunch
: boolean,
709 +)
: Promise<
ConnectionResult> {
711 + return await connectOnce(url, projectPath, signal);
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;
722 + return await connectOnce(url, projectPath, signal);
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",
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} ✗`],
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) {
1089 1172 command: IntellijCommand,
1153 1236 let attemptedConnection
: McpConnection | undefined;
1155 - let connected
: { connection
: McpConnection; tools
: RemoteTool[] };
1157 - connected
= await connectOnce(url, ctx.cwd, signal);
1158 - }
catch (firstError) {
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;
1171 - connected
= await connectOnce(url, ctx.cwd, signal);
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(
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();
1500 + settingsReadFailed
= true;
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)) 1515 + settingsReadFailed ? "warning" :
"info",
extensions/intellij/mise.toml
Addednew file mode 100644 2 +description =
"Verify IntelliJ formatting and lint" 3 +depends = [
"//:install"]
5 + "npm exec -- biome ci .",
7 + "taplo format --check",
11 +description =
"Run IntelliJ tests" 12 +depends = [
"//:install"]
16 +description =
"Typecheck and statically check IntelliJ" 17 +depends = [
"//:install"]
19 + "npm exec -- tsc --noEmit --project tsconfig.json",
20 + "node ../../scripts/extensions.mjs check intellij",
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
Addednew file mode 100644 2 + "extends":
"../../tsconfig.json",
4 + "exclude": [
"__bench__",
"__tests__"]