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): ship type module package.json with the sidecar bundle (#507) (#519)
Zihao Peng06ac93370d68
diff --git a/apps/desktop/test/agent-runtime-bundle-package.test.mjs b/apps/desktop/test/agent-runtime-bundle-package.test.mjsnew file mode 100644index 000000000..980f4e147--- /dev/null+++ b/apps/desktop/test/agent-runtime-bundle-package.test.mjs@@ -0,0 +1,108 @@+import assert from "node:assert/strict";+import { execFileSync } from "node:child_process";+import { mkdtemp, mkdir, readFile, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";++// Issue #507: packaged installs copy packages/agent-runtime/dist-bundle to+// resources/agent-runtime via electron-builder extraResources. The esbuild+// output is ESM (.js entry + import banner), but Node resolves module type+// from the nearest package.json. Without dist-bundle/package.json declaring+// "type":"module", sidecar.js loads as CommonJS and dies at startup.+//+// Tradeoff: the unit suite asserts the bundle-script contract (source + a+// real execution of the chained write step in a temp dir) instead of running+// full esbuild. A full bundle depends on a freshly built packages/shared/dist+// and takes multi-second CPU time, which is too heavy/flaky for this runner;+// packaging CI already rebuilds workspace deps before bundling.++const desktopPackageJson = JSON.parse(+ await readFile(new URL("../package.json", import.meta.url), "utf8"),+);+const agentRuntimePackageJson = JSON.parse(+ await readFile(+ new URL("../../../packages/agent-runtime/package.json", import.meta.url),+ "utf8",+ ),+);++const bundleScript = agentRuntimePackageJson.scripts.bundle ?? "";++test("desktop packaging ships the whole agent-runtime dist-bundle directory", () => {+ const entry = desktopPackageJson.build.extraResources.find(+ (resource) => resource.to === "agent-runtime",+ );++ assert.deepEqual(+ entry,+ {+ from: "../../packages/agent-runtime/dist-bundle",+ to: "agent-runtime",+ },+ "extraResources must copy dist-bundle (including its package.json) to resources/agent-runtime",+ );+});++test("agent-runtime bundle emits an ESM sidecar entry", () => {+ assert.match(bundleScript, /esbuild\b/);+ assert.match(bundleScript, /--format=esm\b/);+ assert.match(bundleScript, /--outfile=dist-bundle\/sidecar\.js\b/);+});++test("agent-runtime bundle writes dist-bundle/package.json with type module", () => {+ // The write must be chained after esbuild so a successful bundle always+ // produces the ESM marker that electron-builder will ship beside sidecar.js.+ assert.match(+ bundleScript,+ /&&/,+ "bundle must chain the package.json write after esbuild so it cannot be skipped on success",+ );+ assert.match(+ bundleScript,+ /dist-bundle\/package\.json/,+ "bundle must write dist-bundle/package.json",+ );+ // Accept either JSON ("type":"module") or a JS object literal+ // ({ type: 'module' }) inside the chained node -e write.+ assert.match(+ bundleScript,+ /(?:["']type["']|type)\s*:\s*["']module["']/,+ 'dist-bundle/package.json must set "type":"module"',+ );+});++test("the chained write step produces a package.json Node will treat as ESM", async () => {+ const writeStep = bundleScript+ .split("&&")+ .map((part) => part.trim())+ .find((part) => part.includes("dist-bundle/package.json"));++ assert.ok(+ writeStep,+ "bundle script must contain a chained write step for dist-bundle/package.json",+ );++ const workDir = await mkdtemp(join(tmpdir(), "pi-agent-runtime-bundle-"));+ try {+ await mkdir(join(workDir, "dist-bundle"), { recursive: true });++ // Execute the real write command from package.json against a scratch+ // dist-bundle so the payload (not just the source string) is validated.+ execFileSync("bash", ["-c", writeStep], {+ cwd: workDir,+ stdio: ["ignore", "pipe", "pipe"],+ });++ const written = JSON.parse(+ await readFile(join(workDir, "dist-bundle/package.json"), "utf8"),+ );+ assert.equal(+ written.type,+ "module",+ 'dist-bundle/package.json must declare {"type":"module"} so sidecar.js loads as ESM',+ );+ } finally {+ await rm(workDir, { recursive: true, force: true });+ }+});diff --git a/apps/desktop/test/packaging-footprint.test.mjs b/apps/desktop/test/packaging-footprint.test.mjsindex a1350aa48..bcf873163 100644--- a/apps/desktop/test/packaging-footprint.test.mjs+++ b/apps/desktop/test/packaging-footprint.test.mjs@@ -189,6 +189,10 @@ test("packaging keeps only shipped locales and excludes non-runtime artifacts",),"third-party license and notice files must remain packageable",);+ // The agent-runtime dist-bundle mapping must remain a directory copy: the+ // bundle emits dist-bundle/package.json with "type":"module" so the ESM+ // sidecar.js loads in packaged installs (issue #507). Contract tests live+ // in agent-runtime-bundle-package.test.mjs.assert.deepEqual(packageJson.build.extraResources, [{from: "build/icon.png",diff --git a/docs/compose/spec/sidecar-bundle-esm-package.md b/docs/compose/spec/sidecar-bundle-esm-package.mdnew file mode 100644index 000000000..1e11a037d--- /dev/null+++ b/docs/compose/spec/sidecar-bundle-esm-package.md@@ -0,0 +1,70 @@+---+feature: sidecar-bundle-esm-package+status: delivered+updated: 2026-09-17+branch: fix/sidecar-bundle-esm-package+commits: 8d826433868f6bcc992c29bae2f799cc6de1e069..7d6890ebc7816675c31f707460efcf0601310e40+---++# Sidecar Bundle ESM package.json++## Report++**What was built** — Packaged installs copy `packages/agent-runtime/dist-bundle` to `resources/agent-runtime` via electron-builder `extraResources`. The directory previously contained only the esbuild ESM `sidecar.js`, so Node treated the entry as CommonJS and agent runtime died at startup with `SyntaxError: Cannot use import statement outside a module` (issue #507). The `bundle` script now chains a write of `dist-bundle/package.json` (`{"type":"module"}`) after esbuild. Desktop packaging and the sidecar spawn path are unchanged. Regression tests lock the extraResources directory-copy mapping and the bundle write-step contract (including a real execution of the write command in a temp dir).++**Verification** —+- `pnpm -C packages/shared build` — PASS+- `pnpm -C packages/agent-runtime bundle` — PASS; `dist-bundle/{sidecar.js,package.json}` with `"type":"module"`+- `node --test test/agent-runtime-bundle-package.test.mjs test/packaging-footprint.test.mjs` from `apps/desktop` — PASS 13/13+- Independent review of `8d826433..7d6890eb` — no critical findings++**Journey log** —+- Issue #507’s “VPN” framing is not supported by logs: model discovery returned HTTP 401 (auth), while the agent path failed on sidecar ESM packaging. Scope kept to the packaging defect.+- Fresh worktrees need `pnpm -C packages/shared build` before `agent-runtime` bundle; cold esbuild fails on missing shared `dist/` exports before the write step runs.+- Unit tests intentionally skip full esbuild (shared rebuild + multi-second CPU); contract + write-step execution covers the packaging invariant, with full bundle verified out of band.+- Desktop unit-test runner is `node --test test/*.test.mjs` — `pnpm --filter @pi-desktop/desktop test -- <file>` does not isolate a single file.++## [S1] Problem++Issue #507 (v0.14.8 Windows packaged install) shows the agent sidecar dying at startup:++```text+SyntaxError: Cannot use import statement outside a module+ at .../resources/agent-runtime/sidecar.js:1+```++`resources/agent-runtime/sidecar.js` is the esbuild ESM bundle copied from+`packages/agent-runtime/dist-bundle` via electron-builder `extraResources`.+`dist-bundle` contains only `sidecar.js`. Node's nearest-`package.json` lookup+finds no `"type": "module"`, so the `.js` entry is loaded as CommonJS and the+ESM `import` banner fails. Development is unaffected because the repo package+itself declares `"type": "module"`.++This is independent of VPN and of the separate `model list request failed (401)`+auth error in the same report.++## [S2] Design++1. The `bundle` script in `packages/agent-runtime/package.json` must, after+ esbuild, write `dist-bundle/package.json` containing at least+ `{"type":"module"}` so electron-builder ships it beside `sidecar.js`.+2. No change to `apps/desktop` `extraResources` mapping: the whole+ `dist-bundle` directory is already copied to `agent-runtime`.+3. No change to `agent-sidecar.ts` spawn path or entry filename.+4. Regression coverage must assert the packaging contract:+ - after a successful bundle, `dist-bundle/package.json` exists and sets+ `"type": "module"`;+ - desktop `extraResources` still sources `agent-runtime` from+ `../../packages/agent-runtime/dist-bundle` (so the new file is shipped).++## [S3] Out of Scope++- HTTP 401 / API-key UX for model discovery (user config; not this bug).+- Issue #506 plugin ESM/CJS main generation.+- Renaming the entry to `sidecar.mjs` or switching the bundle to CJS.+- Proxy/VPN transport behavior.++## Tasks++- [x] T1: Emit `dist-bundle/package.json` with `"type":"module"` from the agent-runtime bundle script — acceptance: `pnpm -C packages/agent-runtime bundle` produces `dist-bundle/sidecar.js` and `dist-bundle/package.json` with `"type":"module"` (covers: S2)+- [x] T2: Add packaging regression tests for the ESM package.json contract — acceptance: tests fail without T1 and pass with it; they cover both the bundle output and the desktop extraResources source path (covers: S2; depends: T1)diff --git a/packages/agent-runtime/package.json b/packages/agent-runtime/package.jsonindex fe7eb08c0..0790c3f7b 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);\"",+ "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')\"","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})\""