From db58a5f1e8865440c1f8b35da138dba03eb37c5e Mon Sep 17 00:00:00 2001 From: ls02155419 Date: Mon, 9 Nov 2026 00:32:11 -0800 Subject: [PATCH] Run the Pi extension's server on Node under a Bun-compiled Pi In a Bun-compiled program process.execPath is that program, so the extension started another Pi instead of LayerMap's server and the session waited for an answer that never came. Under Bun the server now runs on the Node on PATH, by its full path, and a server that does not answer initialize within 30 seconds is stopped and reported. Fixes #7 Co-Authored-By: Claude Opus 5.5 --- plugins/pi/layermap.mjs | 43 +++++++--- scripts/pi-extension.mjs | 35 +++++--- test/pi.test.ts | 168 ++++++++++++++++++++++++++++++++++++++- 3 files changed, 226 insertions(+), 20 deletions(-) diff --git a/plugins/pi/layermap.mjs b/plugins/pi/layermap.mjs index 6f9854a..8d506f5 100644 --- a/plugins/pi/layermap.mjs +++ b/plugins/pi/layermap.mjs @@ -1,7 +1,7 @@ // Generated by scripts/plugins.ts from scripts/pi-extension.mjs. // scripts/pi-extension.mjs import { spawn } from "node:child_process"; -import path2 from "node:path"; +import path3 from "node:path"; import { createInterface } from "node:readline"; import { fileURLToPath } from "node:url"; import { Type } from "typebox"; @@ -174,18 +174,35 @@ function checkedRepository(result, depth = 0) { return void 0; } +// src/platform.ts +import { existsSync } from "node:fs"; +import path2 from "node:path"; +var executableName = (name, platform = process.platform) => platform === "win32" ? `${name}.exe` : name; +var searchPath = (env) => env.PATH ?? Object.entries(env).find(([name]) => name.toUpperCase() === "PATH")?.[1] ?? ""; +function findOnPath(files, env, platform) { + const join = platform === "win32" ? path2.win32.join : path2.posix.join; + for (const directory of searchPath(env).split(platform === "win32" ? ";" : ":")) + for (const file of files) + if (directory && existsSync(join(directory, file))) return join(directory, file); + return void 0; +} +var findExecutable = (name, env = process.env, platform = process.platform) => findOnPath([executableName(name, platform)], env, platform); + // scripts/pi-extension.mjs var CHECK_TOOL = "project_check_changes"; -var CLI = path2.join(path2.dirname(fileURLToPath(import.meta.url)), "..", "dist", "cli.mjs"); +var CLI = path3.join(path3.dirname(fileURLToPath(import.meta.url)), "..", "dist", "cli.mjs"); var READS = /* @__PURE__ */ new Set(["read", "grep", "find", "ls"]); var WRITES = /* @__PURE__ */ new Set(["edit", "write"]); var PATCH = "apply_patch"; var PATCH_FILES = /^\*\*\* (?:(?:Add|Update|Delete) File|Move to): (.+)$/gm; +var NODE = process.versions.bun ? findExecutable("node") : process.execPath; +var START_TIMEOUT_MS = 3e4; var MapServer = class { constructor(cwd) { + if (!NODE) throw new Error("The server runs on Node, and none is on PATH."); this.pending = /* @__PURE__ */ new Map(); this.next = 1; - this.child = spawn(process.execPath, [CLI, "mcp"], { + this.child = spawn(NODE, [CLI, "mcp"], { cwd, stdio: ["pipe", "pipe", "ignore"], windowsHide: true @@ -234,11 +251,19 @@ var MapServer = class { }); } async start(version) { - await this.request("initialize", { - protocolVersion: "2025-06-18", - capabilities: {}, - clientInfo: { name: "layermap-pi", version } - }); + const timer = setTimeout(() => { + this.fail(new Error(`The server did not answer within ${START_TIMEOUT_MS / 1e3} seconds.`)); + this.child.kill(); + }, START_TIMEOUT_MS); + try { + await this.request("initialize", { + protocolVersion: "2025-06-18", + capabilities: {}, + clientInfo: { name: "layermap-pi", version } + }); + } finally { + clearTimeout(timer); + } this.send({ method: "notifications/initialized" }); return (await this.request("tools/list", {})).tools; } @@ -322,7 +347,7 @@ function layermap(pi) { if (!cwd) return; const before = running.get(event.toolCallId); running.delete(event.toolCallId); - const files = before ? changedFiles(before, await fileStates(Object.keys(before))) : event.isError ? [] : namedFiles(event).map((file) => path2.resolve(cwd, file)); + const files = before ? changedFiles(before, await fileStates(Object.keys(before))) : event.isError ? [] : namedFiles(event).map((file) => path3.resolve(cwd, file)); changes.push(...await codeEdits(files)); }); pi.on("agent_before_settle", async (event) => { diff --git a/scripts/pi-extension.mjs b/scripts/pi-extension.mjs index cb03f2e..da1f10b 100644 --- a/scripts/pi-extension.mjs +++ b/scripts/pi-extension.mjs @@ -2,9 +2,9 @@ // plugin's hooks into plugins/pi/layermap.mjs, which the npm package ships as its Pi extension // (`pi install npm:layermap`). // -// The map runs in LayerMap's own MCP server, started with Pi's Node in the session's directory; its -// tools become Pi tools of the same names. Like the Claude Code plugin's stop hook, the extension -// asks the agent once, before it settles, to check the code its tool calls changed. +// The map runs in LayerMap's own MCP server, started on Node in the session's directory; its tools +// become Pi tools of the same names. Like the Claude Code plugin's stop hook, the extension asks +// the agent once, before it settles, to check the code its tool calls changed. import { spawn } from "node:child_process"; import path from "node:path"; import { createInterface } from "node:readline"; @@ -20,6 +20,7 @@ import { fileStates, repositoryAt, } from "../src/agent/session-changes"; +import { findExecutable } from "../src/platform"; const CHECK_TOOL = "project_check_changes"; const CLI = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "dist", "cli.mjs"); @@ -31,13 +32,21 @@ const WRITES = new Set(["edit", "write"]); // each file it adds, updates, deletes or moves one to, relative to the session's directory. const PATCH = "apply_patch"; const PATCH_FILES = /^\*\*\* (?:(?:Add|Update|Delete) File|Move to): (.+)$/gm; +// LayerMap runs on Node. Under Bun process.execPath is not Node, and in a Bun-compiled Pi (the +// release binary, Pi-Bolt) it is that Pi, so there the server runs on the Node on PATH, by its full +// path: the server starts in the session's repository, whose own programs must not run. +const NODE = process.versions.bun ? findExecutable("node") : process.execPath; +// The server answers initialize before it opens any map; a program that is not the server never +// does, and the session waits for that answer. +const START_TIMEOUT_MS = 30_000; // LayerMap's MCP server over stdio: one JSON-RPC message per line. class MapServer { constructor(cwd) { + if (!NODE) throw new Error("The server runs on Node, and none is on PATH."); this.pending = new Map(); this.next = 1; - this.child = spawn(process.execPath, [CLI, "mcp"], { + this.child = spawn(NODE, [CLI, "mcp"], { cwd, stdio: ["pipe", "pipe", "ignore"], windowsHide: true, @@ -85,11 +94,19 @@ class MapServer { }); } async start(version) { - await this.request("initialize", { - protocolVersion: "2025-06-18", - capabilities: {}, - clientInfo: { name: "layermap-pi", version }, - }); + const timer = setTimeout(() => { + this.fail(new Error(`The server did not answer within ${START_TIMEOUT_MS / 1000} seconds.`)); + this.child.kill(); + }, START_TIMEOUT_MS); + try { + await this.request("initialize", { + protocolVersion: "2025-06-18", + capabilities: {}, + clientInfo: { name: "layermap-pi", version }, + }); + } finally { + clearTimeout(timer); + } // The server starts building the map as soon as it is told the client is ready. this.send({ method: "notifications/initialized" }); return (await this.request("tools/list", {})).tools; diff --git a/test/pi.test.ts b/test/pi.test.ts index 5b9463a..7b99669 100644 --- a/test/pi.test.ts +++ b/test/pi.test.ts @@ -1,9 +1,10 @@ import assert from "node:assert/strict"; import { execFile } from "node:child_process"; import { existsSync } from "node:fs"; -import { mkdir, realpath, writeFile } from "node:fs/promises"; +import { mkdir, readFile, realpath, writeFile } from "node:fs/promises"; import path from "node:path"; -import { test } from "node:test"; +import { type TestContext, test } from "node:test"; +import { setTimeout as delay, setImmediate } from "node:timers/promises"; import { pathToFileURL } from "node:url"; import { promisify } from "node:util"; import { generatedFiles } from "../scripts/plugins"; @@ -140,6 +141,169 @@ test("the Pi extension serves LayerMap's tools from its server and asks once to assert.equal((await ask())?.continue, true); }); +// The extension as Pi loads it. It picks its runtime as it loads, so a test sets the host up first. +async function loaded(pkg: string, cwd: string) { + const handlers = new Map(); + const tools: Tool[] = []; + const notes: string[] = []; + const { default: extension } = await import( + pathToFileURL(path.join(pkg, "pi", "layermap.mjs")).href + ); + extension({ + on: (name: string, h: Handler) => handlers.set(name, h), + registerTool: (tool: Tool) => tools.push(tool), + }); + const ctx = { cwd, ui: { notify: (note: string) => notes.push(note) } }; + return { + tools, + notes, + start: () => handlers.get("session_start")?.({}, ctx), + stop: () => handlers.get("session_shutdown")?.({}, ctx), + }; +} + +// A host compiled with Bun: process.execPath is that program, which here starts nothing at all. +function compiledWithBun(t: TestContext, directory: string) { + const { execPath } = process; + const versions = Object.getOwnPropertyDescriptor(process, "versions") as PropertyDescriptor; + process.execPath = path.join(directory, "pi"); + Object.defineProperty(process, "versions", { + ...versions, + value: { ...process.versions, bun: "1.4.3" }, + }); + t.after(() => { + process.execPath = execPath; + Object.defineProperty(process, "versions", versions); + }); +} + +function withoutPath(t: TestContext) { + const { PATH } = process.env; + process.env.PATH = ""; + t.after(() => { + process.env.PATH = PATH; + }); +} + +test("a Pi compiled with Bun runs the server on the Node on PATH, not on itself", async (t) => { + const pkg = await installed(); + const repo = await sandbox(); + compiledWithBun(t, repo); + const { tools, start, stop } = await loaded(pkg, repo); + await start(); + t.after(stop); + + assert.deepEqual( + tools.map((tool) => tool.name), + ["project_check_changes"], + ); +}); + +test("a Pi compiled with Bun says so when no Node is on PATH", async (t) => { + const pkg = await installed(); + const repo = await sandbox(); + compiledWithBun(t, repo); + withoutPath(t); + const { tools, notes, start } = await loaded(pkg, repo); + await start(); + + assert.deepEqual(notes, [ + "LayerMap could not start: The server runs on Node, and none is on PATH.", + ]); + assert.deepEqual(tools, []); +}); + +test("a Pi on Node runs the server on that Node, whatever is on PATH", async (t) => { + const pkg = await installed(); + const repo = await sandbox(); + withoutPath(t); + const { tools, notes, start, stop } = await loaded(pkg, repo); + await start(); + t.after(stop); + + assert.deepEqual(notes, []); + assert.deepEqual( + tools.map((tool) => tool.name), + ["project_check_changes"], + ); +}); + +test("the Pi extension keeps a server that answered initialize, however long the rest takes", async (t) => { + const pkg = await installed(); + const repo = await sandbox(); + const ready = path.join(pkg, "ready"); + const release = path.join(pkg, "release"); + await writeFile( + path.join(pkg, "dist", "cli.mjs"), + `import { existsSync, writeFileSync } from "node:fs"; +import { createInterface } from "node:readline"; +const send = (m) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...m }) + "\\n"); +const tools = [{ name: "project_check_changes", title: "Check", description: "d", inputSchema: { type: "object" } }]; +createInterface({ input: process.stdin }).on("line", (line) => { + const { id, method } = JSON.parse(line); + if (method === "initialize") send({ id, result: {} }); + if (method === "notifications/initialized") writeFileSync(${JSON.stringify(ready)}, ""); + if (method === "tools/list") { + const answer = () => existsSync(${JSON.stringify(release)}) ? send({ id, result: { tools } }) : setTimeout(answer, 10); + answer(); + } + if (method === "tools/call") send({ id, result: { content: [{ type: "text", text: "called" }], isError: false } }); +}); +`, + ); + const { tools, notes, start, stop } = await loaded(pkg, repo); + + t.mock.timers.enable({ apis: ["setTimeout"] }); + const started = start(); + while (!existsSync(ready)) await setImmediate(); + t.mock.timers.tick(30_000); + await writeFile(release, ""); + await started; + t.mock.timers.reset(); + t.after(stop); + + assert.deepEqual(notes, []); + const result = await tools[0]?.execute("1", {}, undefined); + assert.equal(result?.content[0]?.text, "called"); +}); + +test("the Pi extension stops a server that never answers and lets the session start", async (t) => { + const pkg = await installed(); + const repo = await sandbox(); + const pidFile = path.join(pkg, "server.pid"); + await writeFile( + path.join(pkg, "dist", "cli.mjs"), + `import { writeFileSync } from "node:fs"; +writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); +process.stdin.resume(); +`, + ); + const { tools, notes, start } = await loaded(pkg, repo); + + t.mock.timers.enable({ apis: ["setTimeout"] }); + const started = start(); + while (!existsSync(pidFile) || !(await readFile(pidFile, "utf8"))) await setImmediate(); + const pid = Number(await readFile(pidFile, "utf8")); + t.mock.timers.tick(30_000); + await started; + t.mock.timers.reset(); + + assert.deepEqual(tools, []); + assert.deepEqual(notes, [ + "LayerMap could not start: The server did not answer within 30 seconds.", + ]); + const alive = () => { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } + }; + for (let waited = 0; alive() && waited < 100; waited++) await delay(50); + assert.equal(alive(), false, "the server was stopped"); +}); + test("the generated Pi extension carries the notes and this version", () => { const source = generatedFiles("1.2.3")["plugins/pi/layermap.mjs"] ?? ""; assert.ok(source.includes(JSON.stringify(AGENT_MAP_NOTE)));