Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

perf(agent-runtime): split sidecar bundle (#1284)

Lana339630b450d
diff --git a/apps/desktop/test/agent-runtime-bundle-package.test.mjs b/apps/desktop/test/agent-runtime-bundle-package.test.mjs
index 9cb7af415..a0346f808 100644
--- a/apps/desktop/test/agent-runtime-bundle-package.test.mjs
+++ b/apps/desktop/test/agent-runtime-bundle-package.test.mjs
@@ -1,22 +1,16 @@
import assert from "node:assert/strict";
-import { execFileSync } from "node:child_process";
-import { mkdtemp, mkdir, readFile, rm } from "node:fs/promises";
+import { spawn } from "node:child_process";
+import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
+import {
+ bundleAgentRuntime,
+ writeBundlePackageManifest,
+} from "../../../packages/agent-runtime/scripts/bundle.mjs";
-// 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.
-
+// The split ESM output uses relative chunk imports. Electron packaging copies
+// the complete dist-bundle directory, including its module-type marker.
const desktopPackageJson = JSON.parse(
await readFile(new URL("../package.json", import.meta.url), "utf8"),
);
@@ -26,8 +20,11 @@ const agentRuntimePackageJson = JSON.parse(
"utf8",
),
);
-
const bundleScript = agentRuntimePackageJson.scripts.bundle ?? "";
+const bundleSource = await readFile(
+ new URL("../../../packages/agent-runtime/scripts/bundle.mjs", import.meta.url),
+ "utf8",
+);
test("desktop packaging ships the whole agent-runtime dist-bundle directory", () => {
const entry = desktopPackageJson.build.extraResources.find(
@@ -40,82 +37,153 @@ test("desktop packaging ships the whole agent-runtime dist-bundle directory", ()
from: "../../packages/agent-runtime/dist-bundle",
to: "agent-runtime",
},
- "extraResources must copy dist-bundle (including its package.json) to resources/agent-runtime",
+ "extraResources must copy the entry, package marker, and chunks 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 uses hashed ESM chunks and a stable sidecar entry", () => {
+ assert.equal(bundleScript, "node scripts/bundle.mjs");
+ assert.match(bundleSource, /splitting:\s*true/);
+ assert.match(bundleSource, /outdir:\s*stagingDir/);
+ assert.match(bundleSource, /entryNames:\s*"sidecar"/);
+ assert.match(bundleSource, /chunkNames:\s*"chunks\/\[name\]-\[hash\]"/);
+ assert.match(bundleSource, /format:\s*"esm"/);
+ assert.match(bundleSource, /createRequire as __piCreateRequire/);
+ assert.match(bundleSource, /rename\(stagingDir, outputDir\)/);
});
-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",
- );
+test("agent-runtime bundle declares the bundled-Node flag for the extension loader", () => {
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"',
+ bundleSource,
+ /define:\s*\{\s*PI_BUNDLED_NODE:\s*"true"\s*\}/,
+ "bundle must define PI_BUNDLED_NODE for packaged native Pi extensions",
);
});
-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",
- );
-
+test("the bundle manifest helper produces a package.json Node treats as ESM", async () => {
const workDir = await mkdtemp(join(tmpdir(), "pi-agent-runtime-bundle-"));
try {
- await mkdir(join(workDir, "dist-bundle"), { recursive: true });
+ const bundleDir = join(workDir, "dist-bundle");
+ await mkdir(bundleDir, { recursive: true });
+ await writeBundlePackageManifest(bundleDir);
- // 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"),
- );
+ const written = JSON.parse(await readFile(join(bundleDir, "package.json"), "utf8"));
assert.equal(
written.type,
"module",
- 'dist-bundle/package.json must declare {"type":"module"} so sidecar.js loads as ESM',
+ 'dist-bundle/package.json must declare {"type":"module"} for the entry and chunks',
);
} finally {
await 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",
- );
-});
+test(
+ "split sidecar starts outside node_modules and loads native session chunks on demand",
+ { timeout: 60_000 },
+ async () => {
+ const workDir = await mkdtemp(join(tmpdir(), "pi-agent-runtime-sidecar-"));
+ const bundleDir = join(workDir, "resources", "agent-runtime");
+ let child;
+ try {
+ await mkdir(join(bundleDir, "chunks"), { recursive: true });
+ await writeFile(join(bundleDir, "chunks", "stale.js"), "stale build output");
+ await bundleAgentRuntime(bundleDir);
+ assert.equal(
+ (await readdir(join(bundleDir, "chunks"))).includes("stale.js"),
+ false,
+ "replacing a bundle must not ship stale chunks from an earlier build",
+ );
+ const sidecarSource = await readFile(join(bundleDir, "sidecar.js"), "utf8");
+ assert.ok(
+ Buffer.byteLength(sidecarSource) < 500 * 1024,
+ `sidecar entry must stay below esbuild's 500 KiB size-warning threshold; got ${Buffer.byteLength(sidecarSource)} bytes`,
+ );
+ assert.match(sidecarSource, /import\(["']\.\/chunks\/native-pi-session-/);
+ assert.match(sidecarSource, /import\(["']\.\/chunks\/runner-/);
+
+ const childEnv = {
+ ...process.env,
+ HOME: workDir,
+ USERPROFILE: workDir,
+ TMPDIR: workDir,
+ };
+ delete childEnv.NODE_PATH;
+ delete childEnv.PI_DESKTOP_PROXY_JSON;
+ child = spawn(process.execPath, [join(bundleDir, "sidecar.js")], {
+ cwd: workDir,
+ env: childEnv,
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+
+ const received = new Map();
+ const result = await new Promise((resolve, reject) => {
+ let stdout = "";
+ let stderr = "";
+ let closed = false;
+ let exitCode;
+ let settled = false;
+ const fail = (error) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ reject(error);
+ };
+ const timer = setTimeout(() => {
+ child.kill();
+ fail(new Error(`sidecar bundle smoke timed out: ${stderr}`));
+ }, 30_000);
+ const finish = () => {
+ if (settled || !closed || received.size !== 2) return;
+ settled = true;
+ clearTimeout(timer);
+ resolve({ exitCode, stderr });
+ };
+
+ child.stdout.setEncoding("utf8");
+ child.stderr.setEncoding("utf8");
+ child.stdout.on("data", (chunk) => {
+ stdout += chunk;
+ const lines = stdout.split("\n");
+ stdout = lines.pop() ?? "";
+ for (const line of lines) {
+ if (!line) continue;
+ const message = JSON.parse(line);
+ received.set(message.id, message);
+ }
+ finish();
+ });
+ child.stderr.on("data", (chunk) => {
+ stderr += chunk;
+ });
+ child.on("error", (error) => {
+ fail(error);
+ });
+ child.on("close", (code) => {
+ exitCode = code;
+ closed = true;
+ if (received.size !== 2) {
+ fail(new Error(`sidecar closed before both responses arrived: ${stderr}`));
+ return;
+ }
+ finish();
+ });
+ child.stdin.end(
+ `${JSON.stringify({ jsonrpc: "2.0", id: 1, method: "sidecar.health", params: {} })}\n` +
+ `${JSON.stringify({ jsonrpc: "2.0", id: 2, method: "native.session.list", params: {} })}\n`,
+ );
+ });
+
+ assert.equal(result.exitCode, 0, result.stderr);
+ assert.deepEqual(received.get(1)?.result, { ok: true, runtimes: 0 });
+ assert.deepEqual(received.get(2)?.result?.sessions, []);
+ } finally {
+ if (child && child.exitCode === null && child.signalCode === null) {
+ const closed = new Promise((resolve) => child.once("close", resolve));
+ child.kill();
+ await closed;
+ }
+ await rm(workDir, { recursive: true, force: true });
+ }
+ },
+);
diff --git a/packages/agent-runtime/package.json b/packages/agent-runtime/package.json
index 0ac608eba..99d908b42 100644
--- a/packages/agent-runtime/package.json
+++ b/packages/agent-runtime/package.json
@@ -21,7 +21,7 @@
},
"scripts": {
"build": "tsc -p tsconfig.json",
- "bundle": "esbuild src/sidecar.ts --bundle --platform=node --format=esm --minify --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')\"",
+ "bundle": "node scripts/bundle.mjs",
"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/scripts/bundle.mjs b/packages/agent-runtime/scripts/bundle.mjs
new file mode 100644
index 000000000..d00b526cd
--- /dev/null
+++ b/packages/agent-runtime/scripts/bundle.mjs
@@ -0,0 +1,80 @@
+import { build } from "esbuild";
+import { randomUUID } from "node:crypto";
+import { mkdir, mkdtemp, rename, rm, writeFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+
+const packageRoot = fileURLToPath(new URL("../", import.meta.url));
+const outputDir = join(packageRoot, "dist-bundle");
+const banner = "import { createRequire as __piCreateRequire } from 'node:module'; const require = __piCreateRequire(import.meta.url);";
+
+export async function writeBundlePackageManifest(directory) {
+ await writeFile(
+ join(directory, "package.json"),
+ `${JSON.stringify({ type: "module" }, null, 2)}\n`,
+ );
+}
+
+export async function bundleAgentRuntime(outputDir = join(packageRoot, "dist-bundle")) {
+ await mkdir(dirname(outputDir), { recursive: true });
+ const stagingDir = await mkdtemp(join(dirname(outputDir), ".dist-bundle-stage-"));
+ const backupDir = join(dirname(outputDir), `.dist-bundle-backup-${randomUUID()}`);
+ let previousOutputMoved = false;
+
+ try {
+ await build({
+ entryPoints: [join(packageRoot, "src/sidecar.ts")],
+ bundle: true,
+ platform: "node",
+ format: "esm",
+ minify: true,
+ splitting: true,
+ outdir: stagingDir,
+ entryNames: "sidecar",
+ chunkNames: "chunks/[name]-[hash]",
+ define: { PI_BUNDLED_NODE: "true" },
+ banner: { js: banner },
+ });
+ await writeBundlePackageManifest(stagingDir);
+
+ try {
+ await rename(outputDir, backupDir);
+ previousOutputMoved = true;
+ } catch (error) {
+ if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") {
+ // A first build has no previous output to preserve.
+ } else {
+ throw error;
+ }
+ }
+
+ try {
+ await rename(stagingDir, outputDir);
+ } catch (error) {
+ if (previousOutputMoved) {
+ try {
+ await rename(backupDir, outputDir);
+ previousOutputMoved = false;
+ } catch (restoreError) {
+ throw new AggregateError(
+ [error, restoreError],
+ "Could not install the new sidecar bundle or restore the previous bundle",
+ );
+ }
+ }
+ throw error;
+ }
+
+ if (previousOutputMoved) {
+ await rm(backupDir, { recursive: true });
+ previousOutputMoved = false;
+ }
+ } finally {
+ await rm(stagingDir, { recursive: true, force: true });
+ if (!previousOutputMoved) await rm(backupDir, { recursive: true, force: true });
+ }
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ await bundleAgentRuntime();
+}
diff --git a/packages/agent-runtime/src/extensions/bundle.test.ts b/packages/agent-runtime/src/extensions/bundle.test.ts
index c51574287..247fb5e2c 100644
--- a/packages/agent-runtime/src/extensions/bundle.test.ts
+++ b/packages/agent-runtime/src/extensions/bundle.test.ts
@@ -1,8 +1,7 @@
/**
- * E2E-245 contract: the single-file sidecar bundle (esbuild, same flags as
- * `pnpm bundle`) must load a TypeScript extension through jiti from a
- * directory with no node_modules, with the kernel packages reachable through
- * virtual modules.
+ * E2E-245 contract: the packaged sidecar output must load a TypeScript
+ * extension through jiti from a directory with no node_modules, with the
+ * kernel packages reachable through virtual modules.
*/
import { execFileSync } from "node:child_process";
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
@@ -24,7 +23,7 @@ afterEach(() => {
});
describe("bundled loader (E2E-245)", () => {
- it("loads a TypeScript extension from a bundle outside the repo", async () => {
+ it("loads a TypeScript extension through split ESM chunks outside the repo", async () => {
const entry = join(work, "entry.ts");
writeFileSync(
entry,
@@ -46,18 +45,23 @@ const result = tool ? await tool.execute("1", { a: 20, b: 22 }) : undefined;
process.stdout.write(JSON.stringify({ state: report.state, diagnostics: runner.getDiagnostics(), text: result?.content[0] }));
`,
);
+ const bundleDir = join(work, "bundle");
await build({
entryPoints: [entry],
bundle: true,
platform: "node",
format: "esm",
minify: true,
- outfile: join(work, "bundle.mjs"),
+ splitting: true,
+ outdir: bundleDir,
+ entryNames: "sidecar",
+ chunkNames: "chunks/[name]-[hash]",
logLevel: "silent",
banner: {
js: "import { createRequire as __piCreateRequire } from 'node:module'; const require = __piCreateRequire(import.meta.url);",
},
});
+ writeFileSync(join(bundleDir, "package.json"), '{"type":"module"}\n');
const extension = join(work, "typed.ts");
writeFileSync(
extension,
@@ -73,7 +77,7 @@ export default function (pi: any) {
}
`,
);
- const out = execFileSync(process.execPath, [join(work, "bundle.mjs"), extension], {
+ const out = execFileSync(process.execPath, [join(bundleDir, "sidecar.js"), extension], {
cwd: work,
encoding: "utf8",
});
@@ -109,20 +113,16 @@ describe("packaged sidecar extension loader", () => {
"loader.js",
);
- /** The esbuild `--define:` flags the shipped bundle script carries. */
+ /** Read the esbuild defines from the production bundle configuration. */
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;
+ const source = readFileSync(resolve(here, "..", "..", "scripts", "bundle.mjs"), "utf8");
+ const value = source.match(/PI_BUNDLED_NODE:\s*"([^"]+)"/)?.[1];
+ return value ? { PI_BUNDLED_NODE: value } : {};
}
it("loads a typebox-importing extension from a bundle outside the repo", async () => {
expect(existsSync(extensionLoader)).toBe(true);
+ expect(bundleDefines()).toEqual({ PI_BUNDLED_NODE: "true" });
const entry = join(work, "entry.mjs");
writeFileSync(
entry,
diff --git a/packages/agent-runtime/src/extensions/loader.ts b/packages/agent-runtime/src/extensions/loader.ts
index e5a893002..a8096b3ed 100644
--- a/packages/agent-runtime/src/extensions/loader.ts
+++ b/packages/agent-runtime/src/extensions/loader.ts
@@ -1,8 +1,8 @@
/**
* Loader for trusted extension modules (spec 07-plugins/16 §4.2).
*
- * Uses `jiti/static` so the babel transform is bundled into the sidecar's
- * single-file build and no path resolution happens at runtime. Kernel
+ * Uses `jiti/static` so the babel transform ships in the sidecar bundle and
+ * no path resolution happens at runtime. Kernel
* packages reach extensions through jiti `virtualModules`: the same module
* objects the sidecar already holds, plus a shim for
* `@earendil-works/pi-coding-agent` and an inert stub for
@@ -150,7 +150,7 @@ export async function loadExtensionFactory(
virtualModules: Record<string, unknown>,
): Promise<ExtensionFactory | undefined> {
// Lazy so Electron main, which bundles this package for discovery, never
- // pulls jiti into its own bundle; the sidecar bundle inlines it.
+ // pulls jiti into its own bundle; the sidecar loads its split chunk on demand.
const { createJiti } = await import("jiti/static");
const jiti = createJiti(import.meta.url, {
moduleCache: false,
diff --git a/packages/agent-runtime/src/extensions/runtime-lifecycle.test.ts b/packages/agent-runtime/src/extensions/runtime-lifecycle.test.ts
index 4c214a899..1aa06fa22 100644
--- a/packages/agent-runtime/src/extensions/runtime-lifecycle.test.ts
+++ b/packages/agent-runtime/src/extensions/runtime-lifecycle.test.ts
@@ -16,6 +16,45 @@ function deferred<T>() {
}
describe("Desktop extension lifecycle", () => {
+ it("loads trusted extensions once when the first calls race the lazy import", async () => {
+ const root = mkdtempSync(join(tmpdir(), "pi-hooks-load-race-"));
+ const entry = join(root, "extension.ts");
+ writeFileSync(entry, `export default function (pi) { pi.registerCommand("hello", { handler: () => {} }); }`);
+ let commandPublications = 0;
+ const runtime = new DesktopAgentRuntime({
+ host: {
+ call: async (method: string) => {
+ if (method === "extensions.commands.publish") commandPublications += 1;
+ return {};
+ },
+ onNotification: () => () => {},
+ } as never,
+ sessionId: "hooks-load-race",
+ projectPath: root,
+ mode: "agent",
+ thinkingLevel: "off",
+ provider: {
+ id: "fixture", name: "Fixture", apiKey: "", authKind: "none",
+ baseUrl: "http://127.0.0.1:1/v1", modelId: "fixture",
+ supportsReasoning: false, supportedThinkingLevels: ["off"],
+ },
+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
+ trustedExtensions: [{ id: entry, entry, label: "Lifecycle", root, source: "plugin" }],
+ onEvent: () => {},
+ });
+
+ try {
+ await Promise.all([runtime.loadTrustedExtensions(), runtime.loadTrustedExtensions()]);
+ expect(commandPublications).toBe(1);
+ expect(runtime.getTrustedExtensionReports()).toMatchObject([
+ { extensionId: entry, state: "loaded", commandNames: ["hello"] },
+ ]);
+ } finally {
+ await runtime.dispose();
+ rmSync(root, { recursive: true, force: true });
+ }
+ });
+
it("does not apply a session rename locally after its invocation is cancelled", async () => {
const rename = deferred<Record<string, never>>();
const runtime = new DesktopAgentRuntime({
diff --git a/packages/agent-runtime/src/native-pi-session-id.ts b/packages/agent-runtime/src/native-pi-session-id.ts
new file mode 100644
index 000000000..5fd89e0bd
--- /dev/null
+++ b/packages/agent-runtime/src/native-pi-session-id.ts
@@ -0,0 +1 @@
+export const NATIVE_PI_SESSION_PREFIX = "native-pi:";
diff --git a/packages/agent-runtime/src/native-pi-session.ts b/packages/agent-runtime/src/native-pi-session.ts
index 98c041f54..b57a5cd44 100644
--- a/packages/agent-runtime/src/native-pi-session.ts
+++ b/packages/agent-runtime/src/native-pi-session.ts
@@ -45,8 +45,9 @@ import {
nativePiSnapshot,
type NativePiSnapshot,
} from "./native-pi-session-lease.js";
+import { NATIVE_PI_SESSION_PREFIX } from "./native-pi-session-id.js";
-export const NATIVE_PI_SESSION_PREFIX = "native-pi:";
+export { NATIVE_PI_SESSION_PREFIX };
export type NativePiReadOnlyReason =
| "busy"
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 64a28cc64..309b4e7ee 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -59,10 +59,10 @@ import {
type TrustedExtensionSpec,
type TrustedExtensionUiResponse,
} from "@pi-desktop/shared";
-import {
+import type {
TrustedExtensionRunner,
- type RegisteredTrustedExtensionAgent,
- type TrustedExtensionBridge,
+ RegisteredTrustedExtensionAgent,
+ TrustedExtensionBridge,
} from "./extensions/runner.js";
import type {
AgentActivity,
@@ -1617,6 +1617,7 @@ export class DesktopAgentRuntime {
private pluginSkills: PluginSkillDef[];
private trustedExtensionSpecs: TrustedExtensionSpec[];
private extensionRunner?: TrustedExtensionRunner;
+ private trustedExtensionLoad?: Promise<void>;
private extensionSessionName?: string;
private extensionTurnIndex = 0;
/** Headers an extension edited in `before_provider_headers` for the current turn. */
@@ -2473,6 +2474,19 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
* never fails the session.
*/
async loadTrustedExtensions(): Promise<void> {
+ if (this.disposed || this.extensionRunner || this.trustedExtensionSpecs.length === 0) return;
+ if (this.trustedExtensionLoad) return this.trustedExtensionLoad;
+ const loading = this.loadTrustedExtensionsForSession();
+ this.trustedExtensionLoad = loading;
+ try {
+ await loading;
+ } finally {
+ if (this.trustedExtensionLoad === loading) this.trustedExtensionLoad = undefined;
+ }
+ }
+
+ private async loadTrustedExtensionsForSession(): Promise<void> {
+ const { TrustedExtensionRunner } = await import("./extensions/runner.js");
if (this.disposed || this.extensionRunner || this.trustedExtensionSpecs.length === 0) return;
const runner = new TrustedExtensionRunner({
specs: this.trustedExtensionSpecs,
diff --git a/packages/agent-runtime/src/sidecar.ts b/packages/agent-runtime/src/sidecar.ts
index 84344b2fc..ce7db0b7b 100644
--- a/packages/agent-runtime/src/sidecar.ts
+++ b/packages/agent-runtime/src/sidecar.ts
@@ -28,7 +28,7 @@ import {
import { matchesExpectedTurnId } from "./turn-target.js";
import { applyNodeNetworkProxy } from "./node-proxy.js";
import { applyAdditiveDefaultCaCertificates } from "./system-ca.js";
-import { NATIVE_PI_SESSION_PREFIX, nativePiService } from "./native-pi-session.js";
+import { NATIVE_PI_SESSION_PREFIX } from "./native-pi-session-id.js";
import {
isCommandShellOption,
normalizeMode,
@@ -51,6 +51,16 @@ import type {
type RuntimeMap = Map<string, DesktopAgentRuntime>;
+type NativePiServiceFactory = typeof import("./native-pi-session.js")["nativePiService"];
+let nativePiServiceFactory: NativePiServiceFactory | undefined;
+
+async function getNativePiService() {
+ if (!nativePiServiceFactory) {
+ nativePiServiceFactory = (await import("./native-pi-session.js")).nativePiService;
+ }
+ return nativePiServiceFactory();
+}
+
const runtimes: RuntimeMap = new Map();
const hostProxy = new ParentHostProxy();
const testRuntimeIds = new WeakMap<DesktopAgentRuntime, string>();
@@ -366,28 +376,36 @@ async function handle(method: string, params: any): Promise<unknown> {
}
case "sidecar.health":
return { ok: true, runtimes: runtimes.size };
- case "native.session.list":
- return { sessions: await nativePiService().list() };
- case "native.session.search":
- return nativePiService().search(String(params.query ?? ""));
- case "native.session.get":
+ case "native.session.list": {
+ const service = await getNativePiService();
+ return { sessions: await service.list() };
+ }
+ case "native.session.search": {
+ const service = await getNativePiService();
+ return service.search(String(params.query ?? ""));
+ }
+ case "native.session.get": {
+ const service = await getNativePiService();
return {
- session: nativePiService().detail(String(params.id ?? ""), {
+ session: service.detail(String(params.id ?? ""), {
messageBefore: params.messageBefore,
messageLimit: params.messageLimit,
messageAround: params.messageAround,
contentLimit: params.contentLimit,
}),
};
- case "native.session.fork":
+ }
+ case "native.session.fork": {
+ const service = await getNativePiService();
return {
- session: nativePiService().fork({
+ session: service.fork({
id: String(params.id ?? ""),
title: typeof params.title === "string" ? params.title : undefined,
throughMessageId:
typeof params.throughMessageId === "string" ? params.throughMessageId : undefined,
}),
};
+ }
case "agent.testRuntimeIdentity": {
return testRuntimeIdentity(String(params.sessionId ?? ""));
}
@@ -395,7 +413,8 @@ async function handle(method: string, params: any): Promise<unknown> {
const sessionId = String(params.sessionId);
const content = String(params.content ?? "");
if (sessionId.startsWith(NATIVE_PI_SESSION_PREFIX)) {
- return nativePiService().prompt(sessionId, content, (envelope) =>
+ const service = await getNativePiService();
+ return service.prompt(sessionId, content, (envelope) =>
notify("native.agent.event", envelope),
typeof params.userMessageId === "string" ? params.userMessageId : undefined,
);
@@ -495,7 +514,7 @@ async function handle(method: string, params: any): Promise<unknown> {
const sessionId = String(params.sessionId);
const turnId = typeof params.turnId === "string" ? params.turnId : undefined;
if (sessionId.startsWith(NATIVE_PI_SESSION_PREFIX)) {
- return nativePiService().abort(sessionId, turnId);
+ return (await getNativePiService()).abort(sessionId, turnId);
}
const runtime = runtimes.get(sessionId);
if (!matchesExpectedTurnId(runtime?.getStatus().currentTurnId, turnId)) return { ok: false, aborted: false };
@@ -509,7 +528,7 @@ async function handle(method: string, params: any): Promise<unknown> {
const sessionId = String(params.sessionId);
const turnId = typeof params.turnId === "string" ? params.turnId : undefined;
if (sessionId.startsWith(NATIVE_PI_SESSION_PREFIX)) {
- return nativePiService().abort(sessionId, turnId);
+ return (await getNativePiService()).abort(sessionId, turnId);
}
const runtime = runtimes.get(sessionId);
if (!matchesExpectedTurnId(runtime?.getStatus().currentTurnId, turnId)) {
@@ -544,7 +563,7 @@ async function handle(method: string, params: any): Promise<unknown> {
case "agent.getStatus": {
const sessionId = String(params.sessionId);
if (sessionId.startsWith(NATIVE_PI_SESSION_PREFIX)) {
- return nativePiService().status(sessionId);
+ return (await getNativePiService()).status(sessionId);
}
const runtime = runtimes.get(sessionId);
return {
@@ -558,7 +577,7 @@ async function handle(method: string, params: any): Promise<unknown> {
case "agent.disposeSession": {
const sessionId = String(params.sessionId);
if (sessionId.startsWith(NATIVE_PI_SESSION_PREFIX)) {
- nativePiService().dispose(sessionId);
+ (await getNativePiService()).dispose(sessionId);
return { ok: true };
}
const runtime = runtimes.get(sessionId);
@@ -611,7 +630,9 @@ readNdjsonLines(process.stdin, async (line) => {
// host call) must not take every session's runtime down with it: Node's
// default for `unhandledRejection` is to exit the process. Log and carry on;
// the affected session surfaces its own error through the normal event path.
-process.on("exit", () => nativePiService().disposeAll());
+process.on("exit", () => {
+ nativePiServiceFactory?.().disposeAll();
+});
process.on("unhandledRejection", (reason) => {
const detail =