Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(agent-runtime): define PI_BUNDLED_NODE so packaged sidecars load extensions
vastsa967f3c2c60bc
diff --git a/apps/desktop/test/agent-runtime-bundle-package.test.mjs b/apps/desktop/test/agent-runtime-bundle-package.test.mjsindex 980f4e147..9cb7af415 100644--- a/apps/desktop/test/agent-runtime-bundle-package.test.mjs+++ b/apps/desktop/test/agent-runtime-bundle-package.test.mjs@@ -106,3 +106,16 @@ test("the chained write step produces a package.json Node will treat as ESM", asawait rm(workDir, { recursive: true, force: true });}});++test("agent-runtime bundle declares the bundled-Node flag for the kernel extension loader", () => {+ // pi-coding-agent's extension loader embeds typebox and the kernel modules+ // only for compiled or bundled Node distributions. Without the define it+ // resolves them from the importing file, which a packaged install under+ // resources/agent-runtime cannot satisfy, so every native Pi extension fails+ // with "Cannot find module 'typebox'" (see bundle.test.ts for the behavior).+ assert.match(+ bundleScript,+ /--define:PI_BUNDLED_NODE=true\b/,+ "bundle must define PI_BUNDLED_NODE so the packaged sidecar can load native Pi extensions",+ );+});diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 05269f3a4..fdf0d00eb 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -12376,7 +12376,7 @@ plugin-form fixtures in an isolated temporary directory at runtime.- **Specs linked**: `07-plugins/16-trusted-extensions.md` §4.2, §13; ADR 0214- **Acceptance**: Quality, Release- **Milestone**: Post-MVP (R7 v1, delivered first as the bundling spike)-- **Status**: Unit-covered by `packages/agent-runtime/src/extensions/bundle.test.ts` (esbuild bundle run from a temp directory); the packaged-app jiti journey remains Draft and is not faked by the headless runner.+- **Status**: Unit-covered by `packages/agent-runtime/src/extensions/bundle.test.ts`: an esbuild bundle run from a temp directory, plus a kernel-loader case that loads a `typebox`-importing extension through `@earendil-works/pi-coding-agent`'s own loader from a bundle with no `node_modules` above it; the packaged-app jiti journey remains Draft and is not faked by the headless runner.#### E2E-PLUGIN-import-extension-installs-dependencies: Importing an extension with npm dependencies installs them before first load- **Preconditions**: A local pi extension package with `package.json`, `pi.extensions`,diff --git a/docs/spec/07-plugins/16-trusted-extensions.md b/docs/spec/07-plugins/16-trusted-extensions.mdindex afd437213..feba79e98 100644--- a/docs/spec/07-plugins/16-trusted-extensions.md+++ b/docs/spec/07-plugins/16-trusted-extensions.md@@ -212,12 +212,22 @@ never in Electron main, the renderer, or a plugin host process.### 4.2 Loader- The sidecar pins `@earendil-works/pi-coding-agent` at exactly the version- pinned for `pi-ai` and `pi-agent-core`, as a types-only dependency. The- three versions must match; CI fails when they drift.+ pinned for `pi-ai` and `pi-agent-core`. The three versions must match; CI+ fails when they drift. Native Pi sessions run its extension loader+ in process, so the pin is a bundled runtime dependency and not a+ types-only contract.- The loader mirrors the `pi-coding-agent` discovery rules and uses`jiti/static` with `virtualModules`, so the babel transform is bundledand no path resolution happens at runtime. The bundling step is verifiedby a contract test that runs the bundle outside the repository (E2E-245).+- The bundle is built with `--define:PI_BUNDLED_NODE=true`. The+ `pi-coding-agent` extension loader embeds the kernel modules and+ `typebox` for a compiled binary, for a bundled Node distribution, and+ for its own TypeScript-source runtime; every other Node build resolves+ them from the importing file, which a packaged install+ (`resources/agent-runtime/`) cannot satisfy. An entry point that+ bundles pi's session or extension loader in process needs the same+ define.- Import aliases: `pi-ai`, `pi-agent-core`, and `typebox` resolve to thesidecar's copies; `@earendil-works/pi-coding-agent` resolves to a runtimeshim that exports `defineTool` and the tool-result type guards. `@earendil-works/pi-tui`diff --git a/packages/agent-runtime/package.json b/packages/agent-runtime/package.jsonindex 2912b04fc..aa0fb51be 100644--- a/packages/agent-runtime/package.json+++ b/packages/agent-runtime/package.json@@ -17,7 +17,7 @@},"scripts": {"build": "tsc -p tsconfig.json",- "bundle": "esbuild src/sidecar.ts --bundle --platform=node --format=esm --outfile=dist-bundle/sidecar.js --banner:js=\"import { createRequire as __piCreateRequire } from 'node:module'; const require = __piCreateRequire(import.meta.url);\" && node -e \"fs.writeFileSync('dist-bundle/package.json', JSON.stringify({ type: 'module' }, null, 2) + '\\n')\"",+ "bundle": "esbuild src/sidecar.ts --bundle --platform=node --format=esm --define:PI_BUNDLED_NODE=true --outfile=dist-bundle/sidecar.js --banner:js=\"import { createRequire as __piCreateRequire } from 'node:module'; const require = __piCreateRequire(import.meta.url);\" && node -e \"fs.writeFileSync('dist-bundle/package.json', JSON.stringify({ type: 'module' }, null, 2) + '\\n')\"","typecheck": "tsc -p tsconfig.json --noEmit","test": "vitest run","clean": "node -e \"fs.rmSync('dist',{recursive:true,force:true});fs.rmSync('dist-bundle',{recursive:true,force:true})\""diff --git a/packages/agent-runtime/src/extensions/bundle.test.ts b/packages/agent-runtime/src/extensions/bundle.test.tsindex 284d5de81..1a7e11dc4 100644--- a/packages/agent-runtime/src/extensions/bundle.test.ts+++ b/packages/agent-runtime/src/extensions/bundle.test.ts@@ -5,7 +5,7 @@* virtual modules.*/import { execFileSync } from "node:child_process";-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";@@ -83,3 +83,113 @@ export default function (pi: any) {});}, 30_000);});++/**+ * Regression for the packaged install: pi-coding-agent's own extension loader+ * picks jiti `virtualModules` only for compiled or bundled Node distributions.+ * Every other Node build falls back to `require.resolve("typebox")` relative to+ * the importing file. A packaged sidecar lives in `resources/agent-runtime/`,+ * which has no `node_modules` above it, so without the bundled-Node define the+ * sidecar fails every native Pi extension with+ * `Cannot find module 'typebox'`.+ */+describe("packaged sidecar extension loader", () => {+ // pi-coding-agent ships an import-only export map, so locate its directory+ // through the workspace layout the sidecar bundle resolves from.+ const extensionLoader = resolve(+ here,+ "..",+ "..",+ "node_modules",+ "@earendil-works/pi-coding-agent",+ "dist",+ "core",+ "extensions",+ "loader.js",+ );++ /** The esbuild `--define:` flags the shipped bundle script carries. */+ function bundleDefines(): Record<string, string> {+ const manifest = JSON.parse(readFileSync(resolve(here, "..", "..", "package.json"), "utf8")) as {+ scripts: Record<string, string>;+ };+ const defines: Record<string, string> = {};+ for (const [, name, value] of manifest.scripts.bundle.matchAll(/--define:([A-Za-z0-9_]+)=(\S+)/g)) {+ defines[name] = value;+ }+ return defines;+ }++ it("loads a typebox-importing extension from a bundle outside the repo", async () => {+ expect(existsSync(extensionLoader)).toBe(true);+ const entry = join(work, "entry.mjs");+ writeFileSync(+ entry,+ `import { createRequire } from "node:module";+import { loadExtensions } from ${JSON.stringify(extensionLoader)};+const [extension] = process.argv.slice(2);+const eventBus = { emit: () => {}, on: () => () => {}, off: () => {} };+const resolvesTypebox = (() => {+ try {+ createRequire(import.meta.url).resolve("typebox");+ return true;+ } catch {+ return false;+ }+})();+const loaded = await loadExtensions([extension], process.cwd(), eventBus, undefined);+process.stdout.write(JSON.stringify({ resolvesTypebox, loaded: loaded.extensions.length, errors: loaded.errors.map((error) => error.error) }));+`,+ );+ // `--platform`, `--format` and the banner are duplicated from the bundle+ // script on purpose; only `--define:` flags are read back from it, so a+ // future non-define flag in the script has to be mirrored here.+ await build({+ entryPoints: [entry],+ bundle: true,+ platform: "node",+ format: "esm",+ outfile: join(work, "sidecar.js"),+ logLevel: "silent",+ define: bundleDefines(),+ banner: {+ js: "import { createRequire as __piCreateRequire } from 'node:module'; const require = __piCreateRequire(import.meta.url);",+ },+ });++ const extension = join(work, "typed.ts");+ writeFileSync(+ extension,+ `import { Type } from "typebox";+export default function (pi: any) {+ pi.registerTool({+ name: "fx_noop",+ description: "no-op",+ parameters: Type.Object({ a: Type.Number() }),+ async execute() {+ return { content: [{ type: "text", text: "ok" }], details: {} };+ },+ });+}+`,+ );++ // vitest exports NODE_PATH into its workers and the child would inherit+ // the repository's node_modules through it. A packaged install has no such+ // fallback, so scrub it before running the bundle under test.+ const childEnv = { ...process.env };+ delete childEnv.NODE_PATH;+ const out = execFileSync(process.execPath, [join(work, "sidecar.js"), extension], {+ cwd: work,+ encoding: "utf8",+ env: childEnv,+ });+ const report = JSON.parse(out) as { resolvesTypebox: boolean; loaded: number; errors: string[] };+ expect(report.errors).toEqual([]);+ expect(report.loaded).toBe(1);+ // The child resolves `typebox` as soon as something above the bundle+ // provides it, and a `TMPDIR` inside the repository does, which would let+ // this case pass without the bundle define.+ expect(report.resolvesTypebox, "TMPDIR must lie outside any node_modules tree").toBe(false);+ }, 60_000);+});