Skip to content

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

feat(agent-runtime): add opt-in sandboxed codemode tool

vastsa458f5c9eabdc
diff --git a/apps/desktop/electron/main/runtime/provider-catalog.ts b/apps/desktop/electron/main/runtime/provider-catalog.ts
index fbcd869f6..8dec50a02 100644
--- a/apps/desktop/electron/main/runtime/provider-catalog.ts
+++ b/apps/desktop/electron/main/runtime/provider-catalog.ts
@@ -181,6 +181,7 @@ export function createProviderCatalogRuntime({
scheduledTasksEnabled: (value as T & { scheduledTasksEnabled?: unknown })
.scheduledTasksEnabled !== false,
jevEnabled: (value as T & { jevEnabled?: unknown }).jevEnabled === true,
+ codemodeEnabled: (value as T & { codemodeEnabled?: unknown }).codemodeEnabled === true,
transcriptDisplayMode:
(value as T & { transcriptDisplayMode?: unknown }).transcriptDisplayMode === "flat" ||
(value as T & { transcriptDisplayMode?: unknown }).transcriptDisplayMode === "command-first" ||
@@ -216,6 +217,7 @@ export function createProviderCatalogRuntime({
keepAwakeWhileRunning?: unknown;
scheduledTasksEnabled?: unknown;
jevEnabled?: unknown;
+ codemodeEnabled?: unknown;
updatePreference?: unknown;
lastNotifiedUpdateVersion?: unknown;
networkProxy?: unknown;
@@ -269,6 +271,14 @@ export function createProviderCatalogRuntime({
errorCode: ErrorCodes.INVALID_PARAMS,
});
}
+ if (
+ Object.prototype.hasOwnProperty.call(value, "codemodeEnabled") &&
+ typeof value.codemodeEnabled !== "boolean"
+ ) {
+ throw Object.assign(new Error("codemodeEnabled is invalid"), {
+ errorCode: ErrorCodes.INVALID_PARAMS,
+ });
+ }
if (
Object.prototype.hasOwnProperty.call(value, "transcriptDisplayMode") &&
value.transcriptDisplayMode !== "flat" &&
diff --git a/apps/desktop/electron/main/runtime/session-launch.ts b/apps/desktop/electron/main/runtime/session-launch.ts
index e62b1cec9..87bced0a5 100644
--- a/apps/desktop/electron/main/runtime/session-launch.ts
+++ b/apps/desktop/electron/main/runtime/session-launch.ts
@@ -769,6 +769,10 @@ export function createSessionLaunchRuntime({
...(mode === "agent" && settings.computerUse?.enabled === true
? { computerUseEnabled: true }
: {}),
+ // Codemode is opt-in and Agent-only (ADR codemode-sandbox-boundary).
+ ...(mode === "agent" && settings.codemodeEnabled === true
+ ? { codemodeEnabled: true }
+ : {}),
commandShell,
scratchDir: join(dataDir, "scratch", sessionId),
// Remote-host tools write on that host; Main can only serve local files.
diff --git a/apps/desktop/src/features/settings/pages/AgentBehaviorSettings.tsx b/apps/desktop/src/features/settings/pages/AgentBehaviorSettings.tsx
index bf0aca70e..2b48858b7 100644
--- a/apps/desktop/src/features/settings/pages/AgentBehaviorSettings.tsx
+++ b/apps/desktop/src/features/settings/pages/AgentBehaviorSettings.tsx
@@ -75,6 +75,13 @@ export function AgentBehaviorSettings({
onChange={() => void saveSettings({ backgroundJobContinuationEnabled: settings.backgroundJobContinuationEnabled !== true })}
/>
</SettingsRow>
+ <SettingsRow title={t("settings.codemode")} description={t("settings.codemodeDesc")}>
+ <SettingsToggle
+ checked={settings.codemodeEnabled === true}
+ label={t("settings.codemode")}
+ onChange={() => void saveSettings({ codemodeEnabled: settings.codemodeEnabled !== true })}
+ />
+ </SettingsRow>
<SettingsRow
title={t("settings.infiniteProviderRetry")}
description={t("settings.infiniteProviderRetryDesc")}
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index cb3d48494..79ac5abc8 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -468,6 +468,7 @@ export function normalizeSettings(settings: AppSettings): AppSettings {
infiniteProviderRetry:
(settings as { infiniteProviderRetry?: unknown }).infiniteProviderRetry === true,
jevEnabled: (settings as { jevEnabled?: unknown }).jevEnabled === true,
+ codemodeEnabled: (settings as { codemodeEnabled?: unknown }).codemodeEnabled === true,
defaultCommandShell: isCommandShellId(
(settings as { defaultCommandShell?: unknown }).defaultCommandShell,
)
@@ -550,6 +551,7 @@ export function validateSettingsWrite(settings: AppSettings): AppSettings {
chatContentMaxWidth?: unknown;
infiniteProviderRetry?: unknown;
jevEnabled?: unknown;
+ codemodeEnabled?: unknown;
smoothStreaming?: unknown;
sidebarRunningIndicators?: unknown;
sidebarRunningBadge?: unknown;
@@ -617,6 +619,14 @@ export function validateSettingsWrite(settings: AppSettings): AppSettings {
errorCode: "INVALID_PARAMS",
});
}
+ if (
+ Object.prototype.hasOwnProperty.call(value, "codemodeEnabled") &&
+ typeof value.codemodeEnabled !== "boolean"
+ ) {
+ throw Object.assign(new Error("codemodeEnabled is invalid"), {
+ errorCode: "INVALID_PARAMS",
+ });
+ }
if (
Object.prototype.hasOwnProperty.call(value, "smoothStreaming") &&
typeof value.smoothStreaming !== "boolean"
diff --git a/apps/desktop/test/codemode-settings-user-path.test.mjs b/apps/desktop/test/codemode-settings-user-path.test.mjs
new file mode 100644
index 000000000..534626478
--- /dev/null
+++ b/apps/desktop/test/codemode-settings-user-path.test.mjs
@@ -0,0 +1,164 @@
+/**
+ * Isolated Electron user path for the Codemode switch (ADR
+ * codemode-sandbox-boundary). The switch lives in Agent behavior → Execution,
+ * is off by default, and toggling it writes exactly `codemodeEnabled`.
+ */
+import assert from "node:assert/strict";
+import { spawn } from "node:child_process";
+import { createRequire } from "node:module";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import test from "node:test";
+import { repositoryRoot, resolveElectronBinary } from "../../../scripts/e2e/boot.mjs";
+
+const root = repositoryRoot();
+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");
+
+const fixtureSource = String.raw`
+import React from "react";
+import { createRoot } from "react-dom/client";
+import { flushSync } from "react-dom";
+import i18n from "i18next";
+import { initReactI18next } from "react-i18next";
+import { catalogs, flattenCatalog } from "@pi-desktop/i18n";
+import { AgentBehaviorSettings } from "../../apps/desktop/src/features/settings/pages/AgentBehaviorSettings";
+
+const writes = [];
+window.piDesktop = {
+ platform: "darwin",
+ on() { return () => {}; },
+ // Neighbouring cards may ask for their own state; none is needed here.
+ async invoke() { return { ok: true, data: null }; },
+};
+
+await i18n.use(initReactI18next).init({
+ lng: "en",
+ fallbackLng: "en",
+ keySeparator: false,
+ resources: { en: { translation: flattenCatalog(catalogs.en) } },
+ interpolation: { escapeValue: false },
+});
+
+function Harness() {
+ const [settings, setSettings] = React.useState({ defaultMode: "agent", theme: "light", language: "en", developerMode: false });
+ const saveSettings = async (patch) => {
+ writes.push(patch);
+ setSettings((current) => ({ ...current, ...patch }));
+ };
+ return React.createElement(AgentBehaviorSettings, { settings, saveSettings });
+}
+const rootNode = createRoot(document.getElementById("root"));
+flushSync(() => rootNode.render(React.createElement(Harness)));
+
+const frame = () => new Promise(requestAnimationFrame);
+async function settle() { await frame(); await frame(); }
+
+window.codemodeSettingsProbe = async () => {
+ await settle();
+ const toggle = () => document.querySelector('[role="switch"][aria-label="Codemode scripts"]');
+ if (!toggle()) throw new Error("the Codemode switch is missing");
+ const offByDefault = toggle().getAttribute("aria-checked") === "false";
+ // Row descriptions are offered through the help control's accessible label.
+ const describesApprovals = [...document.querySelectorAll("[aria-label]")].some(
+ (node) => node.getAttribute("aria-label").includes("Each nested call still uses your permission mode and approvals."),
+ );
+ flushSync(() => toggle().click());
+ await settle();
+ const onAfterClick = toggle().getAttribute("aria-checked") === "true";
+ flushSync(() => toggle().click());
+ await settle();
+ const offAfterSecondClick = toggle().getAttribute("aria-checked") === "false";
+ return { offByDefault, describesApprovals, onAfterClick, offAfterSecondClick, writes };
+};
+`;
+
+test("the Codemode switch is off by default and persists codemodeEnabled", {
+ timeout: 60_000,
+ skip:
+ process.platform === "linux" && !process.env.DISPLAY
+ ? "Isolated Electron UI test requires a display"
+ : false,
+}, async () => {
+ const temp = await mkdtemp(join(root, "apps/desktop/.codemode-settings-ui-"));
+ try {
+ await build({
+ stdin: {
+ contents: fixtureSource,
+ resolveDir: join(root, "scripts", "e2e"),
+ sourcefile: join(root, "scripts", "e2e", "codemode-settings.jsx"),
+ loader: "tsx",
+ },
+ outfile: join(temp, "renderer.js"),
+ bundle: true,
+ platform: "browser",
+ format: "esm",
+ jsx: "automatic",
+ define: { "process.env.NODE_ENV": '"production"' },
+ alias: {
+ "@pi-desktop/i18n": join(root, "packages/i18n/src"),
+ react: join(root, "apps/desktop/node_modules/react"),
+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),
+ i18next: join(root, "apps/desktop/node_modules/i18next"),
+ "react-i18next": join(root, "apps/desktop/node_modules/react-i18next"),
+ },
+ nodePaths: [join(root, "apps/desktop/node_modules")],
+ });
+ await writeFile(
+ join(temp, "index.html"),
+ '<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; style-src \'self\' \'unsafe-inline\'"><body><div id="root"></div><script type="module" src="renderer.js"></script>',
+ );
+ await writeFile(
+ join(temp, "main.cjs"),
+ `
+const { app, BrowserWindow } = require("electron");
+const path = require("node:path");
+app.setPath("userData", path.join(__dirname, "profile"));
+app.whenReady().then(async () => {
+ const win = new BrowserWindow({ show: false, width: 900, height: 700,
+ webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });
+ win.webContents.on("console-message", (event) => console.error(event.message));
+ try {
+ await win.loadFile(path.join(__dirname, "index.html"));
+ const result = await win.webContents.executeJavaScript("window.codemodeSettingsProbe()");
+ console.log("CODEMODE_SETTINGS_PROBE " + JSON.stringify(result));
+ app.exit(0);
+ } catch (error) { console.error(error?.stack ?? error); app.exit(1); }
+});
+`,
+ );
+
+ const env = { ...process.env };
+ delete env.ELECTRON_RUN_AS_NODE;
+ const child = spawn(resolveElectronBinary(root).electronBinary, [join(temp, "main.cjs")], {
+ env,
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ let output = "";
+ for (const stream of [child.stdout, child.stderr]) {
+ stream.setEncoding("utf8");
+ stream.on("data", (chunk) => { output += chunk; });
+ }
+ const timer = setTimeout(() => child.kill("SIGKILL"), 45_000);
+ let code;
+ try {
+ code = await new Promise((resolve, reject) => {
+ child.once("error", reject);
+ child.once("close", resolve);
+ });
+ } finally {
+ clearTimeout(timer);
+ }
+ assert.equal(code, 0, output.slice(-6000));
+ const line = output.split(/\r?\n/).find((item) => item.startsWith("CODEMODE_SETTINGS_PROBE "));
+ assert(line, output.slice(-6000));
+ assert.deepEqual(JSON.parse(line.slice("CODEMODE_SETTINGS_PROBE ".length)), {
+ offByDefault: true,
+ describesApprovals: true,
+ onAfterClick: true,
+ offAfterSecondClick: true,
+ writes: [{ codemodeEnabled: true }, { codemodeEnabled: false }],
+ });
+ } finally {
+ await rm(temp, { recursive: true, force: true });
+ }
+});
diff --git a/apps/desktop/test/jev-session-launch.test.mjs b/apps/desktop/test/jev-session-launch.test.mjs
index 941ff9794..06d89db36 100644
--- a/apps/desktop/test/jev-session-launch.test.mjs
+++ b/apps/desktop/test/jev-session-launch.test.mjs
@@ -146,6 +146,13 @@ test("session launch resolves Jev credentials only for opted-in Agent mode", asy
assert.equal("jevApiKey" in plan.sidecarParams, false);
assert.deepEqual(keyReads, []);
+ // Codemode is opt-in and Agent-only (ADR codemode-sandbox-boundary).
+ assert.equal("codemodeEnabled" in disabledAgent.sidecarParams, false);
+ const codemodeAgent = await launch("agent", false, { codemodeEnabled: true });
+ assert.equal(codemodeAgent.sidecarParams.codemodeEnabled, true);
+ const codemodePlan = await launch("plan", false, { codemodeEnabled: true });
+ assert.equal("codemodeEnabled" in codemodePlan.sidecarParams, false);
+
failJevSecretRead = true;
const unavailable = await launch("agent", true);
assert.equal("jevApiKey" in unavailable.sidecarParams, false);
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 34109a912..b570288c6 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -26,6 +26,7 @@ git history.
| ID | Title | Status |
|---|---|---|
+| codemode-sandbox-boundary | [Codemode sandbox execution boundary](codemode-sandbox-boundary.md) | Accepted |
| mode-definitions | [User-definable modes as staged workflows](mode-definitions.md) | Proposed |
| sidebar-layout-recovery | [Recover sidebar layout independently of Chromium storage](sidebar-layout-recovery.md) | Accepted |
| steering-local-tool-interruption | [Steering waits for confirmed tool settlement](steering-local-tool-interruption.md) | Accepted |
diff --git a/docs/adr/codemode-sandbox-boundary.md b/docs/adr/codemode-sandbox-boundary.md
new file mode 100644
index 000000000..c8ca39190
--- /dev/null
+++ b/docs/adr/codemode-sandbox-boundary.md
@@ -0,0 +1,80 @@
+# ADR: Codemode sandbox execution boundary
+
+- Status: accepted
+- Date: 2026-11-21
+- Related: issue #2498, [pi-coding-agent design review](../project/pi-coding-agent-design-review.md#codemode), [tool abort](tool-abort-abandons-host-call.md)
+
+## Context
+
+Multi-step investigations, large-log filtering, and chains of MCP calls cost
+one model round trip per tool call, and every intermediate result enters the
+context. Pi 1.x ships a QuickJS-WASI sandbox (`@earendil-works/pi-codemode`)
+that lets a model write a short script which calls tools locally and returns
+only its own output. The coding-agent extension that uses it is bound to
+`AgentSession`, which would add a second session, permission, and usage
+authority beside Desktop's runtime and Host.
+
+## Decision
+
+1. Desktop adds an opt-in `codemode` tool in `packages/agent-runtime` on a
+ narrow adapter over `pi-codemode` (`src/codemode/`). It does not use
+ `AgentSession` or the coding-agent extension runtime. The setting is
+ `AppSettings.codemodeEnabled`, off when absent, and Electron main forwards it
+ only for Agent sessions. When on, the tool is declared up front.
+2. Scripts run in a QuickJS-WASI worker thread with a 256 MiB heap cap, a
+ default 120 s and maximum 600 s deadline, a 64 KiB source cap, at most 256
+ nested calls, a bounded call record (8 KiB arguments per call, 32 KiB in
+ total) and a bounded output budget. At most two sandbox workers run per
+ sidecar; a worker slot is held until the worker actually exits. The module,
+ worker and WASM load on the first script.
+3. The sandbox holds no host function, credential, binding, or header. A
+ nested `tools.<name>()` call is dispatched through pi-agent-core
+ `runToolCall` with the session's own `beforeToolCall`/`afterToolCall`, so
+ argument validation, ToolSearch activation, mode policy, trusted-extension
+ hooks, path instructions, Host permission/approval, file admission, audit,
+ and mutation recovery are exactly those of a direct call. Only the session's
+ currently active tools (core plus ToolSearch-activated, allowed in the mode)
+ are present in the sandbox. Discovery, `asktool`, mode and stage control,
+ `new_context`, delegation lifecycle, and `codemode` itself are never callable.
+ QuickJS isolation does not grant permission to anything.
+4. Tools that are not parallel-safe run one at a time in call order across all
+ scripts of a session; Read, Glob and Grep may overlap and still pass Host
+ admission. Each nested call is its own one-call batch and releases its Host
+ batch state when it settles.
+5. The script's `AbortSignal` reaches every nested call. Stop therefore sends
+ the existing `tools.abort` for an in-flight nested Host call. A failed script
+ states which nested calls already ran; side effects are never described as
+ rolled back.
+6. Nested calls emit ordinary `tool_start`/`tool_update`/`tool_end` events with
+ id `<codemodeCallId>/<n>` and `nestedParentToolCallId` set to the script's
+ call. `parentToolCallId` remains reserved for `Task` ownership, so the two
+ lineages never mix. Nested rows are transcript and review data only: they
+ are excluded when the model context is rebuilt, because the model saw only
+ the script's result. Delegates never inherit `codemode`.
+7. `models.*` globals expose allowlisted metadata only (id, account id, name,
+ limits, modalities): `models.list()`, `models.complete()` on the session's
+ own binding, `models.classify()` through TypeSafe Jev when it is enabled, and
+ `models.generateImages()` as a nested `GenerateImages` call when that tool is
+ callable. Model calls share a limit of four in flight per script. Every
+ physical request emits its own identified usage (operation id, physical
+ account and model), so the Host ledger records and deduplicates it.
+8. The sidecar bundle ships `chunks/codemode-worker.js` and
+ `chunks/quickjs.wasm`; a bundled runtime resolves only these and fails the
+ script rather than falling back to node_modules.
+
+## Consequences
+
+Scripts can batch and filter tool output locally while every effect still
+crosses the same Host boundary. The feature is invisible until enabled.
+`agent-runtime` takes a direct dependency on `@earendil-works/pi-codemode`
+(already in the lockfile through coding-agent). Script state (`store`/`load`)
+is not persisted across scripts in this version. Codemode is not offered in
+contract modes or to delegates; extending it there needs a lineage-aware binding
+for each owner.
+
+## Alternatives
+
+- Adopt coding-agent's `AgentSession` codemode extension: rejected, it creates a
+ second session, permission and ledger authority.
+- External plugins (`context-mode`, `rtk`): can shrink one output, but cannot
+ combine built-in tools, MCP and auxiliary models in one execution.
diff --git a/docs/project/pi-coding-agent-design-review.md b/docs/project/pi-coding-agent-design-review.md
index 2419be64a..3cc0cad56 100644
--- a/docs/project/pi-coding-agent-design-review.md
+++ b/docs/project/pi-coding-agent-design-review.md
@@ -50,7 +50,9 @@ Prefer a future narrow sandbox adapter to adopting the coding-agent extension
runtime. Adoption requires an ADR for the execution boundary, tests proving Host
permission enforcement and cancellation, and a standalone production bundle test
covering worker/WASM assets from outside node_modules. QuickJS isolation does not
-itself grant permission to tools. No Codemode execution is enabled by this review.
+itself grant permission to tools. No Codemode execution is enabled by this review; the
+opt-in adapter that followed is recorded in
+[ADR codemode-sandbox-boundary](../adr/codemode-sandbox-boundary.md).
## Virtual routing
diff --git a/docs/spec/02-architecture/06-pi-runtime-dependency-boundary.md b/docs/spec/02-architecture/06-pi-runtime-dependency-boundary.md
index 026ed395c..f37178319 100644
--- a/docs/spec/02-architecture/06-pi-runtime-dependency-boundary.md
+++ b/docs/spec/02-architecture/06-pi-runtime-dependency-boundary.md
@@ -26,6 +26,11 @@ in `docs/project/pi-150-adoption.md` and updated for 1.5.2 in
detailed versioned `User-Agent`, while `attribution: null` suppresses
pi-agent-core's default Pi attribution headers for OpenRouter, NVIDIA, and
OpenCode requests.
+- `@earendil-works/pi-codemode` (same release) supplies only the QuickJS-WASI
+ sandbox behind the opt-in `codemode` tool. Agent Runtime's own adapter
+ dispatches every nested call through the session's tool pipeline; the
+ coding-agent codemode extension and `AgentSession` are not used (ADR
+ codemode-sandbox-boundary).
- Rust `host-core` remains the sole owner of SQLite and authoritative durable
session state. The Node sidecar asks it to persist checkpoints and tool
outcomes through the existing RPC contract.
diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.md
index df1cf7a3a..70bfde7cd 100644
--- a/docs/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/spec/03-runtime/03-tools-and-permissions.md
@@ -103,7 +103,7 @@ See [ordered preparation](../../adr/parallel-read-batches.md) and
| Topic | Decision |
|---|---|
| Default mode | Agent |
-| Agent tools | Read / Glob / Grep / Write / Edit / Bash + Computer under an active scope grant + registered plugin tools + optional Jev classifier |
+| Agent tools | Read / Glob / Grep / Write / Edit / Bash + Computer under an active scope grant + registered plugin tools + optional Jev classifier + optional `codemode` |
| Plan tools | Read / Glob / Grep / BrowserPreview / Bash / SubmitPlan + plugin tools that declare plan-safe actions |
| Goal tools | Read / Glob / Grep / BrowserPreview / Bash / SubmitGoal + plugin tools that declare plan-safe actions |
| Plan and Goal hard deny | Write / Edit / Computer / plugin tools without `planSafeActions` / unknown tools / the other kind's submit tool |
@@ -197,6 +197,39 @@ on-demand discovery. Main rejects a selected MCP command without task text or
an attachment before opening or persisting a turn. See
`docs/adr/composer-mcp-invocations.md`.
+### 2.2 Codemode (ADR codemode-sandbox-boundary)
+
+`codemode` is offered only in Agent mode and only when Settings → Agent
+behavior → Execution enables it (`AppSettings.codemodeEnabled`, off when
+absent). When enabled it is declared with the first request. Its `code` runs
+as the body of an async function in a QuickJS-WASI worker with no Node,
+filesystem, network, timer, or module access.
+
+- `tools.<name>(args)` reaches only the session's currently active tools: core
+ tools plus tools activated through `ToolSearch`, allowed in the current mode.
+ `ToolSearch`, `asktool`, mode/stage control, `new_context`, `Task`,
+ `TaskWait`, `TaskList`, `TaskStop`, and `codemode` are never callable.
+- Every nested call runs through the same preparation, hooks and Host
+ `tools.execute` path as a direct call. Permission modes, approval cards,
+ denials, path rules, file admission, audit and mutation recovery are
+ unchanged. Read, Glob and Grep may overlap; other tools, including Write and
+ Edit, run one at a time. A script that follows a writable `Task` in the same
+ assistant message waits for that delegate before any nested call, as a direct
+ read does. A failed nested call always rejects inside the script.
+- Stop aborts the script and sends `tools.abort` for an in-flight nested Host
+ call. A failed script lists the nested calls that already ran; their side
+ effects are not undone.
+- Limits: 256 MiB VM heap, 64 KiB source, 120 s default and 600 s maximum
+ deadline, 256 nested calls, 10 000 output tokens by default and 50 000 at
+ most (`// @options:` first line), two sandbox workers per sidecar.
+- `models.list()` returns allowlisted metadata only. `models.complete()` uses
+ the session's own model binding, `models.classify()` uses Jev when enabled,
+ and `models.generateImages()` is a nested `GenerateImages` call when that tool
+ is callable. Each physical model request records its own identified usage.
+- Nested calls are recorded as `<callId>/<n>` with `nestedParentToolCallId`;
+ they never set `parentToolCallId` and never re-enter the model context.
+ Delegates never inherit `codemode`.
+
## 3. Common Tool Constraints
Every non-interactive workspace execution tool must have:
diff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.md
index 90f905998..67b05fe85 100644
--- a/docs/spec/04-ux/06-settings-ia.md
+++ b/docs/spec/04-ux/06-settings-ia.md
@@ -449,8 +449,12 @@ Card order is **Session defaults → Execution → Computer use**.
anchored-menu surface rather than a platform-drawn `<select>` popup, so every
Settings picker opens the same way. The closed trigger sizes to the current
label, capped by the settings control column.
-- **Execution** card: the infinite provider retry switch and the app-wide
- **Scheduled tasks** switch. The retry switch is off by default and explains
+- **Execution** card: the background-job continuation switch, the
+ **Codemode scripts** switch, the infinite provider retry switch and the
+ app-wide **Scheduled tasks** switch. The Codemode switch persists as optional
+ `AppSettings.codemodeEnabled`, off when absent; it offers the Agent-mode
+ `codemode` tool and states that every nested call still uses the permission
+ mode and approvals (ADR codemode-sandbox-boundary). The retry switch is off by default and explains
that network/transient provider failures keep retrying until success; Stop
still cancels the turn and the setting may continue API usage while enabled.
The scheduled-tasks switch persists as optional
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 8a3a5a559..d8fbb21d7 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -357,6 +357,7 @@ identify the platform validation still needed.
| G — Plugin host lifecycle (crash report) | E2E-PLUGIN-crash-report-names-the-exit-code |
| Quality (crash report) | E2E-PLUGIN-crash-report-names-the-exit-code |
| C / E / F / Quality — Background Bash tasks outlive their turn | E2E-265 |
+| C / E / Security / Quality — Codemode sandboxed nested calls | E2E-CODEMODE-sandboxed-nested-calls |
The `US-UI-*` visual scenarios (§UI shell visual scenarios) trace to the
Codex parity decisions in [decisions-log §D](../08-meta/decisions-log.md)
diff --git a/docs/spec/06-delivery/e2e/tools-and-workspace.md b/docs/spec/06-delivery/e2e/tools-and-workspace.md
index 9e83ac17f..ef09521f0 100644
--- a/docs/spec/06-delivery/e2e/tools-and-workspace.md
+++ b/docs/spec/06-delivery/e2e/tools-and-workspace.md
@@ -2829,3 +2829,28 @@ file, then reject a missing native session. The test asserts no native session
or scratch RPC reaches Desktop storage. `native-workspace-files.test.mjs`
additionally rejects replaced sidecars. No provider execution or native user
session data is used.
+
+## E2E-CODEMODE-sandboxed-nested-calls
+
+- Entry: `pnpm --filter @pi-desktop/agent-runtime test -- src/codemode scripts/codemode-bundle.test.mjs`
+ and `node --test apps/desktop/test/codemode-settings-user-path.test.mjs
+ apps/desktop/test/jev-session-launch.test.mjs`.
+- Preconditions: deterministic localhost Responses fixture and a fake Host; no
+ external model account. The packaged probe runs from a temporary directory
+ with no reachable node_modules.
+- Steps: with the setting off, confirm `codemode` is not declared. Turn it on;
+ run a script that reads a file, calls a never-activated on-demand tool, lists
+ models and requests a sub-model completion. Activate a plugin tool with
+ ToolSearch and call it from a script while Host denies Bash. Stop a script
+ whose nested Bash call is held by Host. Replay a transcript that contains a
+ nested row. Toggle the Settings switch.
+- Expected: nested Host calls carry `<callId>/<n>` and `nestedParentToolCallId`
+ only; the inactive tool is absent from the sandbox; Host denial rejects inside
+ the script; Stop sends `tools.abort` for the nested call; only the script
+ result reaches the next request; model metadata carries no credential or
+ header; each physical request emits distinct identified usage; nested rows
+ are not replayed; the packaged worker and WASM run outside node_modules and a
+ missing asset fails the script; the switch is off by default and persists
+ `codemodeEnabled`, and Electron main forwards it only in Agent mode.
+- Specs: `03-runtime/03-tools-and-permissions.md` §2.2, `04-ux/06-settings-ia.md`.
+- Acceptance: C / E / Security / Quality. Milestone: M6+. Status: automated.
diff --git a/packages/agent-runtime/package.json b/packages/agent-runtime/package.json
index 129b2e279..4396af2d4 100644
--- a/packages/agent-runtime/package.json
+++ b/packages/agent-runtime/package.json
@@ -33,6 +33,7 @@
"dependencies": {
"@earendil-works/pi-agent-core": "1.5.2",
"@earendil-works/pi-ai": "1.5.2",
+ "@earendil-works/pi-codemode": "1.5.2",
"@earendil-works/pi-coding-agent": "1.5.2",
"@pi-desktop/shared": "workspace:*",
"jiti": "2.7.0",
diff --git a/packages/agent-runtime/scripts/bundle.mjs b/packages/agent-runtime/scripts/bundle.mjs
index 8de9dad94..1889af4f9 100644
--- a/packages/agent-runtime/scripts/bundle.mjs
+++ b/packages/agent-runtime/scripts/bundle.mjs
@@ -40,6 +40,32 @@ async function bundleImageResizeAssets(directory) {
);
}
+/**
+ * The codemode sandbox starts a worker thread and compiles QuickJS-WASI. A
+ * packaged app has no node_modules, so both ship in `chunks/`, where the
+ * runtime looks for them (ADR codemode-sandbox-boundary).
+ */
+export async function bundleCodemodeAssets(directory) {
+ const chunksDirectory = join(directory, "chunks");
+ await mkdir(chunksDirectory, { recursive: true });
+ await build({
+ entryPoints: [join(packageRoot, "src/codemode/worker.ts")],
+ bundle: true,
+ platform: "node",
+ format: "esm",
+ minify: true,
+ outfile: join(chunksDirectory, "codemode-worker.js"),
+ banner: { js: banner },
+ });
+ const codemodeRequire = createRequire(
+ fileURLToPath(import.meta.resolve("@earendil-works/pi-codemode")),
+ );
+ await copyFile(
+ codemodeRequire.resolve("quickjs-wasi/quickjs.wasm"),
+ join(chunksDirectory, "quickjs.wasm"),
+ );
+}
+
export async function writeBundlePackageManifest(directory) {
await writeFile(
join(directory, "package.json"),
@@ -69,6 +95,7 @@ export async function bundleAgentRuntime(outputDir = join(packageRoot, "dist-bun
});
await bundleImageResizeAssets(stagingDir);
+ await bundleCodemodeAssets(stagingDir);
await writeBundlePackageManifest(stagingDir);
try {
diff --git a/packages/agent-runtime/scripts/codemode-bundle.test.mjs b/packages/agent-runtime/scripts/codemode-bundle.test.mjs
new file mode 100644
index 000000000..e7c2ddae1
--- /dev/null
+++ b/packages/agent-runtime/scripts/codemode-bundle.test.mjs
@@ -0,0 +1,98 @@
+import { spawn } from "node:child_process";
+import { existsSync } from "node:fs";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { build } from "esbuild";
+import { expect, it } from "vitest";
+import { bundleAgentRuntime } from "./bundle.mjs";
+
+const source = join(fileURLToPath(new URL("../", import.meta.url)), "src", "codemode");
+
+// Same layout-defining options as the sidecar build in bundle.mjs: split
+// chunks under chunks/, and the bundled-node define that selects packaged
+// asset resolution.
+const probeOptions = (outdir, entry) => ({
+ entryPoints: [entry],
+ bundle: true,
+ platform: "node",
+ format: "esm",
+ minify: true,
+ splitting: true,
+ outdir,
+ entryNames: "codemode-probe",
+ chunkNames: "chunks/[name]-[hash]",
+ define: { PI_BUNDLED_NODE: "true" },
+ banner: { js: "import { createRequire as __piCreateRequire } from 'node:module'; const require = __piCreateRequire(import.meta.url);" },
+});
+
+const probe = `
+const { NestedToolRunner } = await import(${JSON.stringify(join(source, "nested-calls.ts"))});
+const { createCodemodeTool } = await import(${JSON.stringify(join(source, "tool.ts"))});
+const events = [];
+const read = {
+ name: "Read", label: "Read", description: "Read a file", executionMode: "parallel",
+ parameters: { type: "object", properties: {} },
+ execute: async () => ({ content: [{ type: "text", text: "bundled" }], details: {} }),
+};
+const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } };
+const host = {
+ tools: () => [read],
+ hooks: () => ({}),
+ issuingMessage: (toolCall) => ({ role: "assistant", content: [toolCall], api: "x", provider: "x", model: "x", usage, stopReason: "toolUse", timestamp: 0 }),
+ emit: (event) => events.push(event.type),
+ track() {}, untrack() {}, settleBatch() {},
+};
+const tool = createCodemodeTool({ runner: new NestedToolRunner(host), callableTools: () => [read] });
+const result = await tool.execute("probe", { code: 'return (await tools.Read({})) + ":" + (6 * 7);' });
+console.log("CODEMODE_PROBE " + JSON.stringify({
+ text: result.content.map((block) => block.text ?? "").join("\\n"),
+ isError: result.isError === true,
+ events,
+}));
+`;
+
+function run(command, args, options) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(command, args, { ...options, stdio: ["ignore", "pipe", "pipe"] });
+ let output = "";
+ child.stdout.on("data", (chunk) => { output += chunk; });
+ child.stderr.on("data", (chunk) => { output += chunk; });
+ child.once("error", reject);
+ child.once("close", (code) => resolve({ code, output }));
+ });
+}
+
+it("runs a codemode script from the packaged bundle outside node_modules", async () => {
+ const root = await mkdtemp(join(tmpdir(), "pi-runtime-codemode-"));
+ const bundle = join(root, "resources", "agent-runtime");
+ try {
+ await bundleAgentRuntime(bundle);
+ expect(existsSync(join(bundle, "chunks", "codemode-worker.js"))).toBe(true);
+ expect(existsSync(join(bundle, "chunks", "quickjs.wasm"))).toBe(true);
+ // No node_modules may be reachable from the packaged layout.
+ for (let directory = bundle; directory !== dirname(directory); directory = dirname(directory)) {
+ expect(existsSync(join(directory, "node_modules"))).toBe(false);
+ }
+
+ const entry = join(root, "probe-entry.mjs");
+ await writeFile(entry, probe);
+ await build(probeOptions(bundle, entry));
+ await rm(entry);
+
+ const env = { ...process.env };
+ delete env.NODE_PATH;
+ const { code, output } = await run(process.execPath, [join(bundle, "codemode-probe.js")], { cwd: bundle, env });
+ expect(code, output).toBe(0);
+ const line = output.split(/\r?\n/).find((item) => item.startsWith("CODEMODE_PROBE "));
+ expect(line, output).toBeTruthy();
+ const result = JSON.parse(line.slice("CODEMODE_PROBE ".length));
+ expect(result.isError).toBe(false);
+ expect(result.text).toContain("Script completed");
+ expect(result.text).toContain("bundled:42");
+ expect(result.events).toEqual(["tool_start", "tool_end"]);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+}, 180_000);
diff --git a/packages/agent-runtime/src/codemode/limits.ts b/packages/agent-runtime/src/codemode/limits.ts
new file mode 100644
index 000000000..d50158408
--- /dev/null
+++ b/packages/agent-runtime/src/codemode/limits.ts
@@ -0,0 +1,38 @@
+/**
+ * Bounds of one codemode execution (ADR codemode-sandbox-boundary). They cap
+ * what a model-written script can cost: VM memory, wall time, the number and
+ * size of nested calls it records, model fan-out, and the text it returns.
+ */
+export const CODEMODE_TOOL_NAME = "codemode";
+
+export const CODEMODE_LIMITS = {
+ /** QuickJS heap cap; overruns fail inside the script as `InternalError: out of memory`. */
+ memoryLimitBytes: 256 * 1024 * 1024,
+ /** Source size accepted from the model. */
+ maxCodeChars: 64 * 1024,
+ /** Default and hard deadline per script, including nested tool time. */
+ defaultTimeoutMs: 120_000,
+ maxTimeoutMs: 600_000,
+ /** Nested tool and model calls one script may start; later calls reject. */
+ maxCalls: 256,
+ /** Arguments retained in the call record, per call and in total. */
+ maxArgumentBytesPerCall: 8 * 1024,
+ maxArgumentBytesTotal: 32 * 1024,
+ /** Error text retained per recorded call. */
+ maxErrorChars: 500,
+ /** Model calls one script may have in flight; the rest queue in call order. */
+ maxConcurrentModelCalls: 4,
+ /** Sub-model completion bounds. */
+ maxCompletionPromptChars: 200_000,
+ defaultCompletionOutputTokens: 4_096,
+ maxCompletionOutputTokens: 16_384,
+ /** Output returned to the model, in estimated tokens (4 chars each). */
+ defaultMaxOutputTokens: 10_000,
+ maxOutputTokens: 50_000,
+ /** Workers shared by every session in this sidecar process. */
+ maxWorkers: 2,
+ /** How long a script waits for a free worker before failing. */
+ workerWaitMs: 60_000,
+} as const;
+
+export const CODEMODE_CHARS_PER_TOKEN = 4;
diff --git a/packages/agent-runtime/src/codemode/model-globals.ts b/packages/agent-runtime/src/codemode/model-globals.ts
new file mode 100644
index 000000000..3f15809fc
--- /dev/null
+++ b/packages/agent-runtime/src/codemode/model-globals.ts
@@ -0,0 +1,165 @@
+/**
+ * `models.*` globals for codemode scripts. Scripts never receive a model
+ * object, base URL, header, or credential: they name a capability and the
+ * session runtime dispatches it with its own bindings. Every call is a row in
+ * the script's call record and goes through one concurrency limiter.
+ */
+import type { CodemodeTool } from "@earendil-works/pi-codemode";
+import type { JevClassification } from "../jev-classifier-tool.js";
+import { CODEMODE_LIMITS } from "./limits.js";
+import type { NestedCallRecorder } from "./nested-calls.js";
+
+/** Allowlisted public metadata. Never spread a model or provider object into this. */
+export type CodemodeModelInfo = {
+ kind: "chat" | "classifier" | "image";
+ providerId: string;
+ id: string;
+ name?: string;
+ contextWindow?: number;
+ maxTokens?: number;
+ reasoning?: boolean;
+ input?: string[];
+};
+
+export type CodemodeCompletionRequest = {
+ prompt: string;
+ system?: string;
+ maxOutputTokens: number;
+};
+
+/** What the session runtime provides. Absent capabilities are not exposed. */
+export interface CodemodeModelHost {
+ list(): CodemodeModelInfo[];
+ /** Text completion on the session's own model binding; usage is recorded by the host. */
+ complete?(request: CodemodeCompletionRequest, signal: AbortSignal): Promise<{ text: string }>;
+ /** TypeSafe Jev classification; usage is recorded by the host. */
+ classify?(params: unknown, signal: AbortSignal): Promise<JevClassification>;
+}
+
+type Limiter = <T>(run: () => Promise<T>) => Promise<T>;
+
+function createLimiter(limit: number): Limiter {
+ let active = 0;
+ const waiting: Array<() => void> = [];
+ return async <T>(run: () => Promise<T>): Promise<T> => {
+ if (active >= limit) await new Promise<void>((resolve) => waiting.push(resolve));
+ active += 1;
+ try {
+ return await run();
+ } finally {
+ active -= 1;
+ waiting.shift()?.();
+ }
+ };
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function errorText(error: unknown): string {
+ return error instanceof Error ? error.message : String(error);
+}
+
+/** Validate a script's completion request against the documented bounds. */
+export function parseCompletionRequest(value: unknown): CodemodeCompletionRequest {
+ const shape = 'Expected { prompt: string, system?: string, maxOutputTokens?: number }.';
+ if (!isRecord(value)) throw new Error(`models.complete() expects a request object. ${shape}`);
+ const { prompt, system, maxOutputTokens } = value;
+ if (typeof prompt !== "string" || !prompt.trim()) {
+ throw new Error(`models.complete() requires a non-empty prompt string. ${shape}`);
+ }
+ if (system !== undefined && typeof system !== "string") {
+ throw new Error(`models.complete() system must be a string. ${shape}`);
+ }
+ const chars = prompt.length + (system?.length ?? 0);
+ if (chars > CODEMODE_LIMITS.maxCompletionPromptChars) {
+ throw new Error(`models.complete() input is ${chars} characters; the limit is ${CODEMODE_LIMITS.maxCompletionPromptChars}. Filter it in the script first.`);
+ }
+ let tokens: number = CODEMODE_LIMITS.defaultCompletionOutputTokens;
+ if (maxOutputTokens !== undefined) {
+ if (typeof maxOutputTokens !== "number" || !Number.isInteger(maxOutputTokens) || maxOutputTokens <= 0) {
+ throw new Error("models.complete() maxOutputTokens must be a positive integer.");
+ }
+ tokens = Math.min(maxOutputTokens, CODEMODE_LIMITS.maxCompletionOutputTokens);
+ }
+ return { prompt, ...(system ? { system } : {}), maxOutputTokens: tokens };
+}
+
+export type ModelGlobalsOptions = {
+ callerId: string;
+ host: CodemodeModelHost | undefined;
+ recorder: NestedCallRecorder;
+ /** Runs the session's GenerateImages tool through the nested pipeline, when callable. */
+ generateImages?: (args: unknown, signal: AbortSignal) => Promise<unknown>;
+};
+
+export function createModelGlobals(options: ModelGlobalsOptions): CodemodeTool[] {
+ const { host, recorder, callerId } = options;
+ const limit = createLimiter(CODEMODE_LIMITS.maxConcurrentModelCalls);
+ let count = 0;
+ const models = host?.list() ?? [];
+ const chat = models.find((model) => model.kind === "chat");
+ const classifier = models.find((model) => model.kind === "classifier");
+
+ const recordedCall = async <T>(name: string, model: CodemodeModelInfo | undefined, run: () => Promise<T>): Promise<T> => {
+ const record = recorder.start(
+ `${callerId}/${name}/${++count}`,
+ name,
+ "model",
+ model ? { model: `${model.providerId}/${model.id}` } : {},
+ );
+ try {
+ const value = await limit(run);
+ recorder.finish(record, "ok");
+ return value;
+ } catch (error) {
+ recorder.finish(record, "error", errorText(error));
+ throw error;
+ }
+ };
+
+ const globals: CodemodeTool[] = [
+ {
+ name: "models.list",
+ description: "Public metadata of the models this script can use.",
+ execute: () => models.map((model) => ({ ...model })),
+ },
+ ];
+ if (host?.complete && chat) {
+ const complete = host.complete.bind(host);
+ globals.push({
+ name: "models.complete",
+ description: "Text completion on this session's model: { prompt, system?, maxOutputTokens? } -> { text }.",
+ execute: (args, { signal }) => {
+ const request = parseCompletionRequest(args);
+ return recordedCall("models.complete", chat, async () => {
+ const { text } = await complete(request, signal);
+ return { text, model: { providerId: chat.providerId, id: chat.id } };
+ });
+ },
+ });
+ }
+ if (host?.classify && classifier) {
+ const classify = host.classify.bind(host);
+ globals.push({
+ name: "models.classify",
+ description: "TypeSafe Jev structured classification: { state, questions } -> { answers }.",
+ execute: (args, { signal }) => recordedCall("models.classify", classifier, async () => {
+ const result = await classify(args, signal);
+ if (!result.ok) throw new Error(result.message);
+ return { answers: result.answers };
+ }),
+ });
+ }
+ if (options.generateImages) {
+ const generate = options.generateImages;
+ globals.push({
+ name: "models.generateImages",
+ description: "Generate or edit images through this session's GenerateImages tool; takes that tool's arguments.",
+ // GenerateImages is a nested tool call: it records its own row and usage.
+ execute: (args, { signal }) => limit(() => generate(args, signal)),
+ });
+ }
+ return globals;
+}
diff --git a/packages/agent-runtime/src/codemode/nested-calls.ts b/packages/agent-runtime/src/codemode/nested-calls.ts
new file mode 100644
index 000000000..385846632
--- /dev/null
+++ b/packages/agent-runtime/src/codemode/nested-calls.ts
@@ -0,0 +1,264 @@
+/**
+ * Tool calls a codemode script makes while it runs. Each one goes through the
+ * same pi-agent-core preparation as a model-issued call (`runToolCall`):
+ * argument preparation, schema validation, the session's `beforeToolCall`
+ * (ToolSearch activation, mode policy, extension hooks, path instructions),
+ * execution against the Host (permission, approval, audit), and
+ * `afterToolCall`. Nothing here grants a capability the session lacks.
+ */
+import {
+ runToolCall,
+ type AgentToolCall,
+ type AgentTool,
+ type AgentToolResult,
+ type ToolCallHooks,
+} from "@earendil-works/pi-agent-core";
+import type { AssistantMessage, JsonObject } from "@earendil-works/pi-ai";
+import type { AgentEvent } from "@pi-desktop/shared";
+import { CODEMODE_LIMITS } from "./limits.js";
+
+export type NestedCallStatus = "running" | "ok" | "error" | "cancelled";
+
+/** One row of the call record a codemode result carries in `details.calls`. */
+export type NestedCallRecord = {
+ id: string;
+ name: string;
+ kind: "tool" | "model";
+ status: NestedCallStatus;
+ durationMs?: number;
+ /** Retained arguments, or their size when they exceed the record budget. */
+ arguments?: unknown;
+ argumentsBytes?: number;
+ error?: string;
+};
+
+const encoder = new TextEncoder();
+
+/**
+ * Tools whose nested calls may overlap. They are read-only and still pass Host
+ * file admission. Everything else, including Write/Edit even where the Host
+ * could batch them, runs one call at a time.
+ */
+export const CODEMODE_PARALLEL_TOOL_NAMES: ReadonlySet<string> = new Set(["Read", "Glob", "Grep"]);
+
+function textOf(result: AgentToolResult<unknown>): string {
+ return (result.content ?? [])
+ .filter((block): block is { type: "text"; text: string } => block.type === "text")
+ .map((block) => block.text)
+ .join("\n");
+}
+
+/**
+ * Bounded record of the calls one script made. The call cap is enforced, not
+ * only recorded: a script cannot start more than `maxCalls` nested calls.
+ */
+export class NestedCallRecorder {
+ readonly calls: NestedCallRecord[] = [];
+ private argumentBytes = 0;
+ private complete = true;
+ private startedAt = new Map<NestedCallRecord, number>();
+
+ constructor(private readonly onChange: () => void = () => undefined) {}
+
+ /** Admit and record one call. Throws when the script used up its call budget. */
+ start(id: string, name: string, kind: NestedCallRecord["kind"], args: unknown): NestedCallRecord {
+ if (this.calls.length >= CODEMODE_LIMITS.maxCalls) {
+ throw new Error(`codemode scripts may start at most ${CODEMODE_LIMITS.maxCalls} nested calls.`);
+ }
+ const record: NestedCallRecord = { id, name, kind, status: "running" };
+ let json: string | undefined;
+ try {
+ json = JSON.stringify(args ?? {});
+ } catch {
+ json = undefined;
+ }
+ const bytes = json === undefined ? 0 : encoder.encode(json).length;
+ if (json === undefined
+ || bytes > CODEMODE_LIMITS.maxArgumentBytesPerCall
+ || this.argumentBytes + bytes > CODEMODE_LIMITS.maxArgumentBytesTotal) {
+ record.argumentsBytes = bytes;
+ this.complete = false;
+ } else {
+ record.arguments = JSON.parse(json) as unknown;
+ this.argumentBytes += bytes;
+ }
+ this.calls.push(record);
+ this.startedAt.set(record, performance.now());
+ this.onChange();
+ return record;
+ }
+
+ finish(record: NestedCallRecord, status: Exclude<NestedCallStatus, "running">, errorText?: string): void {
+ record.status = status;
+ record.durationMs = Math.round(performance.now() - (this.startedAt.get(record) ?? performance.now()));
+ this.startedAt.delete(record);
+ if (status !== "ok" && errorText) record.error = errorText.slice(0, CODEMODE_LIMITS.maxErrorChars);
+ this.onChange();
+ }
+
+ /** Calls the script did not await before it ended were cancelled with it. */
+ cancelRunning(): void {
+ for (const record of this.calls) {
+ if (record.status === "running") this.finish(record, "cancelled");
+ }
+ }
+
+ snapshot(): { calls: NestedCallRecord[]; complete: boolean } {
+ return {
+ calls: this.calls.map((call) => ({ ...call })),
+ complete: this.complete && this.calls.every((call) => call.status !== "running"),
+ };
+ }
+}
+
+export type NestedToolEvent = Extract<AgentEvent, { type: "tool_start" | "tool_update" | "tool_end" }>;
+
+/** What the session runtime provides to run nested calls. */
+export interface NestedToolHost {
+ /** Tools a nested call resolves against: the session catalog itself. */
+ tools(): readonly AgentTool[];
+ /** The session's own hooks, so nested calls pass the same gates. */
+ hooks(): ToolCallHooks;
+ /** A synthetic one-call assistant message that "issued" this nested call. */
+ issuingMessage(toolCall: AgentToolCall): AssistantMessage;
+ /**
+ * Emit a lifecycle event for the nested call. `nestedParentToolCallId` is
+ * the script's call; it never identifies `Task` ownership.
+ */
+ emit(event: NestedToolEvent, nestedParentToolCallId: string, ts?: number): void;
+ /** Track/untrack a running nested call (steering guard, activity). */
+ track(toolCallId: string, info: { toolName: string; args: unknown; startedAt: number }): void;
+ untrack(toolCallId: string): void;
+ /** Release Host batch state that a one-call nested batch may have registered. */
+ settleBatch(message: AssistantMessage): void;
+}
+
+export type NestedToolOutcome = {
+ toolCallId: string;
+ result: AgentToolResult<unknown>;
+ isError: boolean;
+ terminate: boolean;
+};
+
+/**
+ * Runs nested calls for every script of one session. Tools that are not
+ * parallel-safe run one at a time across all scripts, in call order; the
+ * read-only file tools may overlap and still pass Host admission.
+ */
+export class NestedToolRunner {
+ private queueTail: Promise<void> = Promise.resolve();
+ private nextIds = new Map<string, number>();
+
+ constructor(private readonly host: NestedToolHost) {}
+
+ /** Forget id counters of a finished script. */
+ finishScript(callerId: string): void {
+ this.nextIds.delete(callerId);
+ }
+
+ /** Never rejects for tool failures: those come back as `isError`. */
+ async run(
+ callerId: string,
+ name: string,
+ args: unknown,
+ recorder: NestedCallRecorder,
+ signal: AbortSignal | undefined,
+ ): Promise<NestedToolOutcome> {
+ const next = (this.nextIds.get(callerId) ?? 0) + 1;
+ this.nextIds.set(callerId, next);
+ const toolCall: AgentToolCall = {
+ type: "toolCall",
+ id: `${callerId}/${next}`,
+ name,
+ // Script arguments arrive after a JSON round trip, so they are JSON values.
+ arguments: (args && typeof args === "object" && !Array.isArray(args) ? args : {}) as JsonObject,
+ };
+ const record = recorder.start(toolCall.id, name, "tool", toolCall.arguments);
+ const tools = this.host.tools();
+ const tool = tools.find((candidate) => candidate.name === name);
+ const exclusive = !CODEMODE_PARALLEL_TOOL_NAMES.has(name) || tool?.executionMode !== "parallel";
+ let release: (() => void) | undefined;
+ if (exclusive) {
+ const previous = this.queueTail;
+ this.queueTail = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ await previous;
+ }
+ const startedAt = Date.now();
+ let outcome: NestedToolOutcome;
+ try {
+ if (signal?.aborted) {
+ outcome = {
+ toolCallId: toolCall.id,
+ result: { content: [{ type: "text", text: "Operation aborted" }], details: {} },
+ isError: true,
+ terminate: false,
+ };
+ } else {
+ let message: AssistantMessage | undefined;
+ let started = false;
+ try {
+ message = this.host.issuingMessage(toolCall);
+ this.host.track(toolCall.id, { toolName: name, args: toolCall.arguments, startedAt });
+ this.host.emit({ type: "tool_start", toolCallId: toolCall.id, toolName: name, args: toolCall.arguments }, callerId, startedAt);
+ started = true;
+ const finalized = await runToolCall(toolCall, {
+ ...this.host.hooks(),
+ tools,
+ assistantMessage: message,
+ context: { messages: [], tools: [...tools] },
+ ...(signal ? { signal } : {}),
+ onUpdate: (partialResult) => {
+ this.host.emit({ type: "tool_update", toolCallId: toolCall.id, partialResult }, callerId);
+ },
+ });
+ outcome = {
+ toolCallId: toolCall.id,
+ result: finalized.result,
+ isError: finalized.isError,
+ terminate: finalized.result.terminate === true,
+ };
+ } catch (error) {
+ // runToolCall reports tool failures as results; anything thrown here
+ // is unexpected. Settle the row instead of leaving it running.
+ outcome = {
+ toolCallId: toolCall.id,
+ result: { content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }], details: {} },
+ isError: true,
+ terminate: false,
+ };
+ } finally {
+ this.host.untrack(toolCall.id);
+ if (message) this.host.settleBatch(message);
+ }
+ if (started) {
+ this.host.emit({ type: "tool_end", toolCallId: toolCall.id, result: outcome.result, isError: outcome.isError }, callerId);
+ }
+ }
+ } finally {
+ release?.();
+ }
+ recorder.finish(
+ record,
+ outcome.isError ? (signal?.aborted ? "cancelled" : "error") : "ok",
+ outcome.isError ? textOf(outcome.result) : undefined,
+ );
+ return outcome;
+ }
+}
+
+/**
+ * The value a script receives: `structuredContent` for tools that declare an
+ * output schema, else the text content. Every failure rejects with the tool's
+ * text, also when it carries structured content.
+ */
+export function scriptValueOf(tool: AgentTool | undefined, outcome: NestedToolOutcome): unknown {
+ if (outcome.isError) {
+ throw new Error(textOf(outcome.result) || `Tool "${tool?.name ?? "unknown"}" failed`);
+ }
+ if (tool?.outputSchema && outcome.result.structuredContent !== undefined) {
+ return outcome.result.structuredContent;
+ }
+ return textOf(outcome.result);
+}
diff --git a/packages/agent-runtime/src/codemode/output.ts b/packages/agent-runtime/src/codemode/output.ts
new file mode 100644
index 000000000..638b87487
--- /dev/null
+++ b/packages/agent-runtime/src/codemode/output.ts
@@ -0,0 +1,125 @@
+/**
+ * Model-facing result of one codemode script: a status header, the script's
+ * own output in production order, and on failure a summary of which nested
+ * calls already completed. Side effects are never described as rolled back.
+ */
+import type { ImageContent, TextContent } from "@earendil-works/pi-ai";
+import type { CodemodeOutputItem, CodemodeResult } from "@earendil-works/pi-codemode";
+import { CODEMODE_CHARS_PER_TOKEN } from "./limits.js";
+import type { NestedCallRecord } from "./nested-calls.js";
+
+type Item = TextContent | ImageContent;
+
+function valueText(value: unknown): string {
+ if (typeof value === "string") return value;
+ try {
+ return JSON.stringify(value) ?? String(value);
+ } catch {
+ return String(value);
+ }
+}
+
+/**
+ * With more than one text item each starts with a `==> text N/M <==` line,
+ * because providers join adjacent text blocks without a separator. Console
+ * lines follow the rest in one `<console_output>` block.
+ */
+function layout(output: readonly CodemodeOutputItem[]): Item[] {
+ const total = output.filter((item) => item.type === "text" && !item.console).length;
+ const items: Item[] = [];
+ const consoleLines: string[] = [];
+ let index = 0;
+ for (const item of output) {
+ if (item.type === "image") {
+ items.push({ type: "image", data: item.data, mimeType: item.mimeType });
+ } else if (item.console) {
+ consoleLines.push(item.text);
+ } else {
+ index += 1;
+ items.push({ type: "text", text: total > 1 ? `==> text ${index}/${total} <==\n${item.text}` : item.text });
+ }
+ }
+ if (consoleLines.length > 0) {
+ items.push({ type: "text", text: `<console_output>\n${consoleLines.join("\n")}\n</console_output>` });
+ }
+ return items;
+}
+
+function joinText(items: readonly Item[]): Item[] {
+ const joined: Item[] = [];
+ let parts: string[] = [];
+ const flush = () => {
+ if (parts.length) joined.push({ type: "text", text: parts.join("\n") });
+ parts = [];
+ };
+ for (const item of items) {
+ if (item.type === "text") {
+ parts.push(item.text);
+ } else {
+ flush();
+ joined.push(item);
+ }
+ }
+ flush();
+ return joined;
+}
+
+/** Keep the start and end of over-budget text; images follow it unchanged. */
+function truncate(items: readonly Item[], maxTokens: number): { items: Item[]; truncated: boolean } {
+ const texts = items.filter((item): item is TextContent => item.type === "text").map((item) => item.text);
+ const combined = texts.join("\n");
+ const budget = maxTokens * CODEMODE_CHARS_PER_TOKEN;
+ if (texts.length === 0 || combined.length <= budget) return { items: [...items], truncated: false };
+ const head = Math.floor(budget / 2);
+ const tail = budget - head;
+ const removed = combined.length - head - tail;
+ const text = `Warning: output truncated (about ${Math.ceil(combined.length / CODEMODE_CHARS_PER_TOKEN)} tokens; budget ${maxTokens}). Filter or summarize inside the script, or raise max_output_tokens.\n\n${combined.slice(0, head)}\n…${Math.ceil(removed / CODEMODE_CHARS_PER_TOKEN)} tokens truncated…\n${combined.slice(combined.length - tail)}`;
+ return {
+ items: [{ type: "text", text }, ...items.filter((item) => item.type === "image")],
+ truncated: true,
+ };
+}
+
+function callSummary(calls: readonly NestedCallRecord[]): string {
+ if (calls.length === 0) return "No nested calls were made.";
+ return `Nested calls made before the failure (completed side effects are not undone): ${calls
+ .map((call) => `${call.name} (${call.status})`)
+ .join(", ")}`;
+}
+
+function errorHead(result: Extract<CodemodeResult, { ok: false }>): string {
+ const { error } = result;
+ switch (error.kind) {
+ case "script":
+ return error.stack ?? `${error.name ?? "Error"}: ${error.message}`;
+ case "timeout":
+ return `Script timed out: ${error.message}`;
+ case "aborted":
+ return `Script aborted: ${error.message}`;
+ default:
+ return `Script sandbox failed: ${error.message}`;
+ }
+}
+
+export function formatScriptResult(
+ result: CodemodeResult,
+ calls: readonly NestedCallRecord[],
+ maxOutputTokens: number,
+ wallMs: number,
+): { content: Item[]; truncated: boolean } {
+ const output = [...result.output];
+ if (result.ok && result.value !== undefined) output.push({ type: "text", text: valueText(result.value) });
+ const items = layout(output);
+ if (!result.ok) items.push({ type: "text", text: `Script error:\n${errorHead(result)}\n\n${callSummary(calls)}` });
+ const bounded = truncate(joinText(items), maxOutputTokens);
+ const header = `${result.ok ? "Script completed" : "Script failed"}\nWall time ${(wallMs / 1000).toFixed(1)} seconds\nOutput:\n`;
+ return { content: joinText([{ type: "text", text: header }, ...bounded.items]), truncated: bounded.truncated };
+}
+
+/** A script that never started: no nested call ran, so nothing needs undoing. */
+export function formatNotStarted(reason: string, wallMs: number): Item[] {
+ return [{
+ type: "text",
+ text: `Script failed\nWall time ${(wallMs / 1000).toFixed(1)} seconds\nOutput:\nScript error:\n${reason}\n\nThe script did not start.`,
+ }];
+}
diff --git a/packages/agent-runtime/src/codemode/runtime-codemode.test.ts b/packages/agent-runtime/src/codemode/runtime-codemode.test.ts
new file mode 100644
index 000000000..c4cae90ba
--- /dev/null
+++ b/packages/agent-runtime/src/codemode/runtime-codemode.test.ts
@@ -0,0 +1,230 @@
+import { createServer, type ServerResponse } from "node:http";
+import { afterEach, describe, expect, it } from "vitest";
+import type { AgentEventEnvelope, UiMessage } from "@pi-desktop/shared";
+import { DesktopAgentRuntime, type PluginToolDef } from "../runtime.js";
+import type { RuntimeProviderConfig } from "../provider-binding.js";
+
+const cleanups: Array<() => Promise<void>> = [];
+afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); });
+
+type Item = { type?: string; role?: string; name?: string; call_id?: string; content?: unknown; output?: unknown };
+type Request = { tools?: Array<{ name?: string }>; input: Item[] };
+type Reply = { call: { id: string; name: string; args: Record<string, unknown> } } | { text: string };
+
+function respond(res: ServerResponse, reply: Reply) {
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ const send = (data: { type: string; [key: string]: unknown }) => res.write(`event: ${data.type}\ndata: ${JSON.stringify(data)}\n\n`);
+ send({ type: "response.created", response: { id: "resp_fixture" } });
+ const item = "call" in reply
+ ? { id: `fc_${reply.call.id}`, type: "function_call", call_id: reply.call.id, name: reply.call.name, arguments: JSON.stringify(reply.call.args), status: "completed" }
+ : { id: "msg_fixture", type: "message", role: "assistant", status: "completed", content: [{ type: "output_text", text: reply.text, annotations: [] }] };
+ send({ type: "response.output_item.added", output_index: 0, item: "call" in reply ? { ...item, arguments: "", status: "in_progress" } : { ...item, content: [], status: "in_progress" } });
+ send("call" in reply
+ ? { type: "response.function_call_arguments.delta", output_index: 0, delta: JSON.stringify(reply.call.args) }
+ : { type: "response.output_text.delta", output_index: 0, content_index: 0, delta: reply.text });
+ send({ type: "response.output_item.done", output_index: 0, item });
+ send({ type: "response.completed", response: { id: "resp_fixture", status: "completed", output: [item],
+ usage: { input_tokens: 10, output_tokens: 5, total_tokens: 15, input_tokens_details: { cached_tokens: 0 }, output_tokens_details: { reasoning_tokens: 0 } } } });
+ res.end();
+}
+
+async function fixtureModel(replies: Reply[]) {
+ const requests: Request[] = [];
+ const server = createServer(async (req, res) => {
+ let raw = "";
+ for await (const part of req) raw += part;
+ requests.push(JSON.parse(raw) as Request);
+ respond(res, replies.shift() ?? { text: "Done." });
+ });
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ cleanups.push(async () => { server.closeAllConnections(); await new Promise<void>((resolve) => server.close(() => resolve())); });
+ const address = server.address();
+ if (!address || typeof address === "string") throw new Error("fixture address missing");
+ const baseUrl = `http://127.0.0.1:${address.port}/v1`;
+ const provider: RuntimeProviderConfig = {
+ id: "account-fixture", name: "Fixture", baseUrl, modelId: "fixture-model", apiKey: "fixture-not-real", apiStyle: "responses",
+ headers: { "x-fixture-secret": "must-not-reach-script" },
+ supportsReasoning: false, supportedThinkingLevels: ["off"],
+ modelConfig: { source: "generic", name: "Fixture", baseUrl, reasoning: false, input: ["text"],
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 200000, maxTokens: 2000 },
+ };
+ return { requests, provider };
+}
+
+const pluginTools: PluginToolDef[] = [{
+ name: "plugin_alpha", description: "Synthetic deferred plugin probe", parameters: { type: "object", properties: {}, required: [] }, risk: "low",
+}];
+
+function runtimeFixture(
+ provider: RuntimeProviderConfig,
+ options: {
+ codemodeEnabled: boolean;
+ history?: UiMessage[];
+ deny?: (toolName: string) => boolean;
+ /** Hold this tool's Host execution until Host receives `tools.abort` for it. */
+ holdUntilAbort?: string;
+ },
+) {
+ const aborts: string[] = [];
+ const held = new Map<string, () => void>();
+ let heldStarted!: () => void;
+ const heldStartedPromise = new Promise<void>((resolve) => { heldStarted = resolve; });
+ const events: AgentEventEnvelope[] = [];
+ const executed: Array<{ toolName: string; toolCallId: string }> = [];
+ const runtime = new DesktopAgentRuntime({
+ sessionId: "codemode-fixture", mode: "agent", provider, thinkingLevel: "off", history: options.history ?? [],
+ pluginTools, codemodeEnabled: options.codemodeEnabled,
+ compactionSettings: { enabled: false, reserveTokens: 0, keepRecentTokens: 0 },
+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
+ host: { call: async <T>(method: string, params?: unknown): Promise<T> => {
+ if (method === "tools.fileBatchCapabilities") return { version: 1, supported: false } as T;
+ if (method === "session.appendMessage") return undefined as T;
+ if (method === "project.instructions.resolve") return undefined as T;
+ if (method === "tools.abort") {
+ const call = params as { toolCallId: string };
+ aborts.push(call.toolCallId);
+ held.get(call.toolCallId)?.();
+ return undefined as T;
+ }
+ if (method === "tools.execute") {
+ const call = params as { toolName: string; toolCallId: string };
+ executed.push({ toolName: call.toolName, toolCallId: call.toolCallId });
+ if (options.deny?.(call.toolName)) return { ok: false, denied: true, content: "Permission denied by the user" } as T;
+ if (options.holdUntilAbort === call.toolName) {
+ heldStarted();
+ await new Promise<void>((resolve) => held.set(call.toolCallId, resolve));
+ return { ok: false, content: "Command aborted", errorCode: "TOOL_ABORTED" } as T;
+ }
+ return { ok: true, content: "alpha\nbeta\ngamma" } as T;
+ }
+ throw new Error(`Unexpected host method: ${method}`);
+ }, onNotification: () => () => {} },
+ onEvent: (event) => { events.push(event); },
+ });
+ cleanups.push(() => runtime.dispose());
+ return { runtime, events, executed, aborts, heldStarted: heldStartedPromise };
+}
+
+const SCRIPT = `
+const text = await tools.Read({ path: "notes.txt" });
+let blocked = "";
+try { await tools.plugin_alpha({}); } catch (error) { blocked = error.message; }
+const listed = await models.list();
+const summary = await models.complete({ prompt: "Summarize: " + text });
+return { lines: text.split("\\n").length, blocked, listed, summary: summary.text };
+`;
+
+describe("codemode through the session runtime", () => {
+ it("is not offered unless enabled", async () => {
+ const model = await fixtureModel([{ text: "Hello." }]);
+ const f = runtimeFixture(model.provider, { codemodeEnabled: false });
+ await f.runtime.prompt("hi", "user-1", "turn-1");
+ expect(model.requests[0].tools?.some((tool) => tool.name === "codemode")).toBe(false);
+ });
+
+ it("runs nested calls through the Host pipeline, gates on ToolSearch, records lineage and usage", async () => {
+ const model = await fixtureModel([
+ { call: { id: "call_code", name: "codemode", args: { code: SCRIPT } } },
+ { text: "Three short lines." },
+ { text: "All done." },
+ ]);
+ const f = runtimeFixture(model.provider, { codemodeEnabled: true });
+ await f.runtime.prompt("Summarize notes.txt", "user-1", "turn-1");
+
+ expect(model.requests[0].tools?.some((tool) => tool.name === "codemode")).toBe(true);
+ const start = f.events.find((envelope) => envelope.event.type === "tool_start" && envelope.event.toolName === "codemode");
+ const callerId = start?.event.type === "tool_start" ? start.event.toolCallId : "";
+ expect(callerId).toMatch(/^call_code/);
+ // The nested Read went to Host under a child id; the inactive plugin never did.
+ expect(f.executed).toEqual([{ toolName: "Read", toolCallId: `${callerId}/1` }]);
+
+ const nested = f.events.filter((envelope) => envelope.nestedParentToolCallId === callerId);
+ expect(nested.map((envelope) => envelope.event.type)).toEqual(
+ expect.arrayContaining(["tool_start", "tool_end"]),
+ );
+ expect(nested.every((envelope) => envelope.parentToolCallId === undefined)).toBe(true);
+ const codemodeEnd = f.events.find((envelope) => envelope.event.type === "tool_end" && envelope.event.toolCallId === callerId);
+ expect(codemodeEnd?.nestedParentToolCallId).toBeUndefined();
+
+ // Only the script result reaches the model; nested results do not.
+ const followUp = model.requests.at(-1)!;
+ const outputs = followUp.input.filter((item) => item.type === "function_call_output");
+ expect(outputs.map((item) => item.call_id)).toEqual(["call_code"]);
+ const output = JSON.stringify(outputs[0].output);
+ expect(output).toContain("Script completed");
+ expect(output).toContain('\\"lines\\":3');
+ // An on-demand tool that was never activated is not even present in the sandbox.
+ expect(output).toContain("tools.plugin_alpha does not exist");
+ expect(output).toContain("Three short lines.");
+ expect(output).not.toContain("must-not-reach-script");
+ expect(output).not.toContain("fixture-not-real");
+ expect(output).toContain('\\"providerId\\":\\"account-fixture\\"');
+
+ // The sub-model completion is a separate physical operation on the session account.
+ const usage = f.events.filter((envelope) => envelope.event.type === "usage")
+ .map((envelope) => (envelope.event as { usage: { operationId?: string; providerId?: string; modelId?: string } }).usage);
+ expect(usage.filter((entry) => entry.providerId === "account-fixture" && entry.modelId === "fixture-model").length)
+ .toBeGreaterThanOrEqual(3);
+ expect(new Set(usage.map((entry) => entry.operationId)).size).toBe(usage.length);
+ });
+
+ it("calls a tool once ToolSearch activated it, and surfaces Host denials to the script", async () => {
+ const model = await fixtureModel([
+ { call: { id: "call_search", name: "ToolSearch", args: { query: "plugin_alpha" } } },
+ { call: { id: "call_code", name: "codemode", args: { code: `
+ const alpha = await tools.plugin_alpha({});
+ let denied = "";
+ try { await tools.Bash({ command: "echo hi" }); } catch (error) { denied = error.message; }
+ return { alpha, denied };
+ ` } } },
+ { text: "Done." },
+ ]);
+ const f = runtimeFixture(model.provider, { codemodeEnabled: true, deny: (name) => name === "Bash" });
+ await f.runtime.prompt("Use the plugin", "user-1", "turn-1");
+ expect(f.executed.map((call) => call.toolName)).toEqual(["plugin_alpha", "Bash"]);
+ const output = JSON.stringify(model.requests.at(-1)!.input.filter((item) => item.type === "function_call_output").at(-1)?.output);
+ expect(output).toContain("alpha");
+ expect(output).toContain("Permission denied by the user");
+ const bashStart = f.events.find((envelope) => envelope.event.type === "tool_start" && envelope.event.toolName === "Bash");
+ const bashId = bashStart?.event.type === "tool_start" ? bashStart.event.toolCallId : undefined;
+ expect(bashStart?.nestedParentToolCallId).toBeTruthy();
+ const bashEnd = f.events.find((envelope) => envelope.event.type === "tool_end" && envelope.event.toolCallId === bashId);
+ expect(bashEnd?.event).toMatchObject({ isError: true });
+ });
+
+ it("Stop aborts the script's in-flight Host call", async () => {
+ const model = await fixtureModel([
+ { call: { id: "call_code", name: "codemode", args: { code: `await tools.Bash({ command: "sleep 100" }); return "unreachable";` } } },
+ { text: "Stopped." },
+ ]);
+ const f = runtimeFixture(model.provider, { codemodeEnabled: true, holdUntilAbort: "Bash" });
+ const pending = f.runtime.prompt("Run it", "user-1", "turn-1");
+ await f.heldStarted;
+ await f.runtime.abort();
+ await pending.catch(() => undefined);
+ const bash = f.executed.find((call) => call.toolName === "Bash");
+ expect(bash?.toolCallId).toMatch(/\/1$/);
+ expect(f.aborts).toContain(bash?.toolCallId);
+ const codemodeEnd = f.events.find((envelope) => envelope.event.type === "tool_end" && !envelope.nestedParentToolCallId);
+ expect(codemodeEnd?.event).toMatchObject({ isError: true });
+ });
+
+ it("keeps persisted nested rows out of the replayed model context", async () => {
+ const createdAt = "2026-11-20T00:00:00Z";
+ const history: UiMessage[] = [
+ { id: "u0", role: "user", content: "Earlier", createdAt, status: "complete" },
+ { id: "a0", role: "assistant", content: "", createdAt, status: "complete" },
+ { id: "call_old/1", role: "tool", toolName: "Read", toolCallId: "call_old/1", toolArgs: { path: "x" },
+ toolResult: "nested result", content: "nested result", toolStatus: "success", createdAt, status: "complete",
+ nestedParentToolCallId: "call_old" },
+ { id: "call_old", role: "tool", toolName: "codemode", toolCallId: "call_old", toolArgs: { code: "return 1" },
+ toolResult: "Script completed", content: "Script completed", toolStatus: "success", createdAt, status: "complete" },
+ ];
+ const model = await fixtureModel([{ text: "Ok." }]);
+ const f = runtimeFixture(model.provider, { codemodeEnabled: true, history });
+ await f.runtime.prompt("Continue", "user-2", "turn-2");
+ const input = model.requests[0].input;
+ expect(input.some((item) => item.call_id === "call_old")).toBe(true);
+ expect(input.some((item) => item.call_id === "call_old/1")).toBe(false);
+ });
+});
diff --git a/packages/agent-runtime/src/codemode/runtime-models.test.ts b/packages/agent-runtime/src/codemode/runtime-models.test.ts
new file mode 100644
index 000000000..0c2a38ae7
--- /dev/null
+++ b/packages/agent-runtime/src/codemode/runtime-models.test.ts
@@ -0,0 +1,117 @@
+import { describe, expect, it } from "vitest";
+import type { MessageUsage } from "@pi-desktop/shared";
+import type { RuntimeProviderConfig } from "../provider-binding.js";
+import { createRuntimeModelHost } from "./runtime-models.js";
+
+const provider: RuntimeProviderConfig = {
+ id: "account-7", name: "Relay", baseUrl: "https://relay.invalid/v1", modelId: "relay-model", apiKey: "sk-secret-value",
+ apiStyle: "responses", headers: { "x-team-token": "header-secret" }, supportsReasoning: false, supportedThinkingLevels: ["off"],
+ modelConfig: { source: "generic", name: "Relay model", baseUrl: "https://relay.invalid/v1", reasoning: false, input: ["text"],
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, contextWindow: 64000, maxTokens: 4000 },
+};
+
+describe("codemode runtime model host", () => {
+ it("lists only allowlisted metadata", () => {
+ const host = createRuntimeModelHost({ provider: () => provider, sessionId: "s", jevApiKey: "jev-key", emitUsage: () => undefined });
+ const listed = host.list();
+ expect(listed).toEqual([
+ { kind: "chat", providerId: "account-7", id: "relay-model", name: "Relay model", contextWindow: 64000, maxTokens: 4000, reasoning: false, input: ["text"] },
+ expect.objectContaining({ kind: "classifier", providerId: "typesafe", id: "jev-latest" }),
+ ]);
+ const serialized = JSON.stringify(listed);
+ for (const secret of ["sk-secret-value", "header-secret", "jev-key", "relay.invalid"]) expect(serialized).not.toContain(secret);
+ });
+
+ it("omits classify without a Jev credential", () => {
+ const host = createRuntimeModelHost({ provider: () => provider, sessionId: "s", emitUsage: () => undefined });
+ expect(host.classify).toBeUndefined();
+ expect(host.list().map((model) => model.kind)).toEqual(["chat"]);
+ });
+
+ it("dispatches completions on the session binding and forwards per-attempt usage", async () => {
+ const usage: MessageUsage[] = [];
+ const calls: unknown[] = [];
+ const host = createRuntimeModelHost({
+ provider: () => provider, sessionId: "session-9", emitUsage: (entry) => { usage.push(entry); },
+ complete: async (bound, context, thinking, options) => {
+ calls.push({ id: bound.id, context, thinking, max: options?.maxOutputTokens, session: options?.sessionId });
+ options?.onUsage?.({ operationId: "op-1", providerId: bound.id, modelId: bound.modelId, inputTokens: 3, outputTokens: 2, totalTokens: 5 });
+ return { text: "done" };
+ },
+ });
+ await expect(host.complete!({ prompt: "hi", system: "be brief", maxOutputTokens: 50 }, new AbortController().signal))
+ .resolves.toEqual({ text: "done" });
+ expect(calls).toEqual([{ id: "account-7", thinking: "off", max: 50, session: "session-9",
+ context: { systemPrompt: "be brief", messages: [expect.objectContaining({ role: "user", content: "hi" })] } }]);
+ expect(usage).toEqual([expect.objectContaining({ operationId: "op-1", providerId: "account-7", modelId: "relay-model" })]);
+ });
+
+ it("attributes late usage to the turn that started the call", async () => {
+ let turn = "turn-1";
+ const recorded: Array<string | undefined> = [];
+ let finish!: () => void;
+ const host = createRuntimeModelHost({
+ provider: () => provider, sessionId: "s", turnId: () => turn,
+ emitUsage: (_usage, turnId) => recorded.push(turnId),
+ complete: async (_bound, _context, _thinking, options) => {
+ await new Promise<void>((resolve) => { finish = resolve; });
+ options?.onUsage?.({ operationId: "late", inputTokens: 1, outputTokens: 1, totalTokens: 2 });
+ return { text: "late" };
+ },
+ });
+ const pending = host.complete!({ prompt: "hi", maxOutputTokens: 1 }, new AbortController().signal);
+ turn = "turn-2";
+ finish();
+ await pending;
+ expect(recorded).toEqual(["turn-1"]);
+ });
+
+ it("offers no completion while a trusted extension agent owns the session", async () => {
+ let called = false;
+ const extension = { ...provider, extensionAgentKey: "ext:agent" };
+ const host = createRuntimeModelHost({
+ provider: () => extension, sessionId: "s", emitUsage: () => undefined,
+ complete: async () => { called = true; return { text: "" }; },
+ });
+ expect(host.list()).toEqual([]);
+ await expect(host.complete!({ prompt: "hi", maxOutputTokens: 1 }, new AbortController().signal))
+ .rejects.toThrow("trusted extension agent");
+ expect(called).toBe(false);
+ });
+
+ it("redacts the session credential from completion errors", async () => {
+ const host = createRuntimeModelHost({
+ provider: () => provider, sessionId: "s", emitUsage: () => undefined,
+ complete: async () => { throw new Error("401 for key sk-secret-value"); },
+ });
+ await expect(host.complete!({ prompt: "hi", maxOutputTokens: 1 }, new AbortController().signal))
+ .rejects.toThrow("401 for key [redacted]");
+ });
+
+ it("records each classification as its own identified operation", async () => {
+ const usage: MessageUsage[] = [];
+ const retries: Array<number | undefined> = [];
+ let attempt = 0;
+ const host = createRuntimeModelHost({
+ provider: () => provider, sessionId: "s", jevApiKey: "jev-key", emitUsage: (entry) => { usage.push(entry); },
+ classify: async (_key, _params, _signal, options) => {
+ retries.push(options?.maxRetries);
+ attempt += 1;
+ const reported = { input: 7, output: 1, cacheRead: 0, cacheWrite: 0, totalTokens: 8,
+ cost: { input: 0.1, output: 0.1, cacheRead: 0, cacheWrite: 0, total: 0.2 } };
+ return attempt === 1
+ ? { ok: true, answers: {}, usage: reported }
+ : { ok: false, errorCode: "JEV_REQUEST_FAILED", message: "Jev classification failed: busy", usage: reported };
+ },
+ });
+ const signal = new AbortController().signal;
+ await host.classify!({}, signal);
+ await host.classify!({}, signal);
+ // One attempt per call; a failed request that reported usage is still recorded.
+ expect(retries).toEqual([0, 0]);
+ expect(usage).toHaveLength(2);
+ expect(usage[0]).toMatchObject({ providerId: "typesafe", modelId: "jev-latest", inputTokens: 7, outputTokens: 1, costStatus: "estimated" });
+ expect(usage[0].operationId).toBeTruthy();
+ expect(usage[0].operationId).not.toBe(usage[1].operationId);
+ });
+});
diff --git a/packages/agent-runtime/src/codemode/runtime-models.ts b/packages/agent-runtime/src/codemode/runtime-models.ts
new file mode 100644
index 000000000..6da47d8c3
--- /dev/null
+++ b/packages/agent-runtime/src/codemode/runtime-models.ts
@@ -0,0 +1,108 @@
+/**
+ * Session-side implementation of the codemode `models.*` capabilities. The
+ * sandbox only ever sees {@link CodemodeModelInfo}; bindings, headers, and
+ * credentials stay here. Each physical request reports its own identified
+ * usage, which the runtime emits as a `usage` event so the Host ledger
+ * records it against the real account and model.
+ */
+import type { Context } from "@earendil-works/pi-ai";
+import type { MessageUsage } from "@pi-desktop/shared";
+import { usageFromPi } from "../agent-messages.js";
+import { classifyWithJev, JEV_MODEL_REF } from "../jev-classifier-tool.js";
+import { completeOneShot } from "../one-shot-complete.js";
+import { buildProviderModel, type RuntimeProviderConfig } from "../provider-binding.js";
+import { requestUsageIdentity } from "../request-usage.js";
+import type { CodemodeModelHost, CodemodeModelInfo } from "./model-globals.js";
+
+export type RuntimeModelHostOptions = {
+ provider: () => RuntimeProviderConfig;
+ sessionId: string;
+ jevApiKey?: string;
+ /** The turn current when a model call starts; late usage stays with it. */
+ turnId?: () => string | undefined;
+ emitUsage: (usage: MessageUsage, turnId: string | undefined) => void;
+ /** Test seam. */
+ complete?: typeof completeOneShot;
+ classify?: typeof classifyWithJev;
+};
+
+function redact(message: string, secrets: Array<string | undefined>): string {
+ let text = message;
+ for (const secret of secrets) {
+ if (secret && secret.length >= 4) text = text.replaceAll(secret, "[redacted]");
+ }
+ return text;
+}
+
+/** Allowlisted metadata of the session's chat model. */
+export function chatModelInfo(provider: RuntimeProviderConfig): CodemodeModelInfo {
+ const model = buildProviderModel(provider);
+ return {
+ kind: "chat",
+ providerId: provider.id,
+ id: model.id,
+ ...(model.name ? { name: model.name } : {}),
+ contextWindow: model.contextWindow,
+ maxTokens: model.maxTokens,
+ reasoning: model.reasoning,
+ input: [...model.input],
+ };
+}
+
+export function createRuntimeModelHost(options: RuntimeModelHostOptions): CodemodeModelHost {
+ const complete = options.complete ?? completeOneShot;
+ const classify = options.classify ?? classifyWithJev;
+ const jevApiKey = options.jevApiKey;
+ return {
+ list() {
+ const provider = options.provider();
+ // A trusted-extension agent streams in process; there is no physical
+ // binding a one-shot completion could dispatch to.
+ const models: CodemodeModelInfo[] = provider.extensionAgentKey ? [] : [chatModelInfo(provider)];
+ if (jevApiKey) {
+ models.push({ kind: "classifier", providerId: JEV_MODEL_REF.provider, id: JEV_MODEL_REF.id, name: JEV_MODEL_REF.name });
+ }
+ return models;
+ },
+ async complete(request, signal) {
+ const provider = options.provider();
+ const turnId = options.turnId?.();
+ if (provider.extensionAgentKey) {
+ throw new Error("models.complete() is unavailable while a trusted extension agent answers this session.");
+ }
+ const context: Context = {
+ ...(request.system ? { systemPrompt: request.system } : {}),
+ messages: [{ role: "user", content: request.prompt, timestamp: Date.now() }],
+ };
+ try {
+ const result = await complete(provider, context, "off", {
+ signal,
+ maxOutputTokens: request.maxOutputTokens,
+ sessionId: options.sessionId,
+ onUsage: (usage) => options.emitUsage(usage, turnId),
+ });
+ return { text: result.text };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ throw new Error(redact(message, [provider.apiKey]));
+ }
+ },
+ ...(jevApiKey
+ ? {
+ async classify(params: unknown, signal: AbortSignal) {
+ const turnId = options.turnId?.();
+ // One attempt per call, so one physical request maps to one record.
+ const result = await classify(jevApiKey, params, signal, { maxRetries: 0 });
+ if (result.usage) {
+ const usage = usageFromPi(result.usage, {
+ ...requestUsageIdentity(JEV_MODEL_REF, JEV_MODEL_REF.provider),
+ ...(Number.isFinite(result.usage.cost?.total) ? { costStatus: "estimated" as const } : {}),
+ });
+ if (usage) options.emitUsage(usage, turnId);
+ }
+ return result;
+ },
+ }
+ : {}),
+ };
+}
diff --git a/packages/agent-runtime/src/codemode/sandbox.ts b/packages/agent-runtime/src/codemode/sandbox.ts
new file mode 100644
index 000000000..103577e10
--- /dev/null
+++ b/packages/agent-runtime/src/codemode/sandbox.ts
@@ -0,0 +1,144 @@
+/**
+ * QuickJS-WASI sandbox loading for codemode. Nothing here runs until a script
+ * executes: the pi-codemode module, its worker, and the WASM binary load on
+ * the first call and are cached for the life of the sidecar.
+ */
+import { existsSync } from "node:fs";
+import { basename, dirname, join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import type {
+ CodemodeResult,
+ CodemodeSandboxOptions,
+ CodemodeTool,
+} from "@earendil-works/pi-codemode";
+import { CODEMODE_LIMITS } from "./limits.js";
+
+declare const PI_BUNDLED_NODE: string | boolean | undefined;
+
+/** File names of the assets the sidecar bundle ships next to its chunks. */
+export const CODEMODE_WORKER_FILE = "codemode-worker.js";
+export const CODEMODE_WASM_FILE = "quickjs.wasm";
+
+export type CodemodeAssets = { wasmPath: string; workerUrl: URL };
+
+function bundled(): boolean {
+ return typeof PI_BUNDLED_NODE !== "undefined" && String(PI_BUNDLED_NODE) === "true";
+}
+
+/**
+ * Locate the bundled worker and WASM. esbuild may emit this module into the
+ * bundle root or into `chunks/`; the assets always live in `chunks/`. A
+ * missing asset fails the script instead of silently using node_modules,
+ * which does not exist in a packaged app.
+ */
+export function resolveBundledCodemodeAssets(moduleUrl: string): CodemodeAssets {
+ const directory = dirname(fileURLToPath(moduleUrl));
+ const chunks = basename(directory) === "chunks" ? directory : join(directory, "chunks");
+ const workerPath = join(chunks, CODEMODE_WORKER_FILE);
+ const wasmPath = join(chunks, CODEMODE_WASM_FILE);
+ if (!existsSync(workerPath) || !existsSync(wasmPath)) {
+ throw new Error(`The codemode sandbox assets are missing from this build (${chunks}).`);
+ }
+ return { wasmPath, workerUrl: pathToFileURL(workerPath) };
+}
+
+type CodemodeModule = typeof import("@earendil-works/pi-codemode");
+let modulePromise: Promise<CodemodeModule> | undefined;
+
+function loadCodemodeModule(): Promise<CodemodeModule> {
+ modulePromise ??= import("@earendil-works/pi-codemode").catch((error: unknown) => {
+ modulePromise = undefined;
+ throw error;
+ });
+ return modulePromise;
+}
+
+// Shared by every session in this process. Admission waits in arrival order.
+let activeWorkers = 0;
+const waiters: Array<() => void> = [];
+
+function admit(): void {
+ while (waiters.length > 0 && activeWorkers < CODEMODE_LIMITS.maxWorkers) {
+ activeWorkers += 1;
+ waiters.shift()?.();
+ }
+}
+
+function release(): void {
+ activeWorkers -= 1;
+ admit();
+}
+
+/** Reserve one worker slot. Resolves with why none was reserved, if so. */
+function reserveWorker(signal: AbortSignal | undefined, timeoutMs: number): Promise<"reserved" | "aborted" | "timeout"> {
+ if (signal?.aborted) return Promise.resolve("aborted");
+ return new Promise((resolve) => {
+ const settle = (outcome: "reserved" | "aborted" | "timeout") => {
+ clearTimeout(timer);
+ signal?.removeEventListener("abort", onAbort);
+ const index = waiters.indexOf(grant);
+ if (index >= 0) waiters.splice(index, 1);
+ resolve(outcome);
+ };
+ const grant = () => settle("reserved");
+ const onAbort = () => settle("aborted");
+ const timer = setTimeout(() => settle("timeout"), timeoutMs);
+ waiters.push(grant);
+ signal?.addEventListener("abort", onAbort, { once: true });
+ admit();
+ });
+}
+
+export type SandboxRunRequest = {
+ code: string;
+ tools: CodemodeTool[];
+ globals: CodemodeTool[];
+ timeoutMs: number;
+ signal?: AbortSignal;
+ /** Test seam; production resolves assets from the build layout. */
+ assets?: CodemodeAssets;
+};
+
+export type SandboxRunOutcome =
+ | { started: true; result: CodemodeResult }
+ | { started: false; reason: "aborted" | "timeout" };
+
+/**
+ * Run one script in a fresh worker. The worker slot is held until the worker
+ * actually exits, not merely until the result settles.
+ */
+export async function runInSandbox(request: SandboxRunRequest): Promise<SandboxRunOutcome> {
+ const startedAt = performance.now();
+ const admission = await reserveWorker(request.signal, Math.min(request.timeoutMs, CODEMODE_LIMITS.workerWaitMs));
+ if (admission !== "reserved") return { started: false, reason: admission };
+ let reserved = true;
+ const releaseReservation = () => {
+ if (!reserved) return;
+ reserved = false;
+ release();
+ };
+ let sandbox: InstanceType<CodemodeModule["CodemodeSandbox"]> | undefined;
+ try {
+ const codemode = await loadCodemodeModule();
+ const assets = request.assets ?? (bundled() ? resolveBundledCodemodeAssets(import.meta.url) : undefined);
+ const options: CodemodeSandboxOptions = {
+ tools: request.tools,
+ globals: request.globals,
+ timeoutMs: Math.max(1, Math.round(request.timeoutMs - (performance.now() - startedAt))),
+ memoryLimitBytes: CODEMODE_LIMITS.memoryLimitBytes,
+ ...(assets ? { wasm: codemode.loadQuickJSWasm(assets.wasmPath), workerUrl: assets.workerUrl } : {}),
+ acquireWorker: () => {
+ if (!reserved) throw new Error("The script already settled");
+ // From here the sandbox releases the slot when the worker exits.
+ reserved = false;
+ return release;
+ },
+ };
+ sandbox = new codemode.CodemodeSandbox(options);
+ const result = await sandbox.execute(request.code, request.signal ? { signal: request.signal } : {});
+ return { started: true, result };
+ } finally {
+ await sandbox?.close();
+ releaseReservation();
+ }
+}
diff --git a/packages/agent-runtime/src/codemode/session.ts b/packages/agent-runtime/src/codemode/session.ts
new file mode 100644
index 000000000..8c92e6708
--- /dev/null
+++ b/packages/agent-runtime/src/codemode/session.ts
@@ -0,0 +1,92 @@
+/**
+ * Binds the codemode tool to one session runtime. The runtime supplies only
+ * narrow closures; the sandbox reaches nothing else. Nested calls resolve
+ * against the session catalog and pass the session's own hooks, so ToolSearch
+ * activation, mode policy, extension hooks, Host permission/approval, audit,
+ * cancellation and file admission are the same as for a direct call.
+ */
+import type { AgentTool, ToolCallHooks } from "@earendil-works/pi-agent-core";
+import type { Api, AssistantMessage, Model } from "@earendil-works/pi-ai";
+import type { AgentEventEnvelope, MessageUsage } from "@pi-desktop/shared";
+import type { RuntimeProviderConfig } from "../provider-binding.js";
+import { CODEMODE_TOOL_NAME } from "./limits.js";
+import { NestedToolRunner, type NestedToolHost } from "./nested-calls.js";
+import { createRuntimeModelHost } from "./runtime-models.js";
+import { createCodemodeTool } from "./tool.js";
+
+export type SessionCodemodeBindings = {
+ sessionId: string;
+ /** Every tool of the session catalog; nested calls resolve against it. */
+ catalog(): readonly AgentTool[];
+ /** Tools callable right now: core plus ToolSearch-activated, allowed in this mode. */
+ active(): readonly AgentTool[];
+ /** Control and interactive tools a script must never call. */
+ excluded: ReadonlySet<string>;
+ hooks: ToolCallHooks;
+ model(): Model<Api>;
+ turnId(): string | undefined;
+ emit(envelope: AgentEventEnvelope): void;
+ emitUsage(usage: MessageUsage, turnId: string | undefined): void;
+ activeToolCalls: Map<string, { toolName: string; args: unknown; startedAt: number }>;
+ settleBatch(message: AssistantMessage): void;
+ provider(): RuntimeProviderConfig;
+ jevApiKey?: string;
+};
+
+const ZERO_USAGE = {
+ input: 0,
+ output: 0,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 0,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+};
+
+export function createSessionCodemodeTool(bindings: SessionCodemodeBindings): AgentTool {
+ const host: NestedToolHost = {
+ tools: () => bindings.catalog(),
+ hooks: () => bindings.hooks,
+ issuingMessage: (toolCall) => {
+ const model = bindings.model();
+ return {
+ role: "assistant",
+ content: [toolCall],
+ api: model.api,
+ provider: model.provider,
+ model: model.id,
+ usage: { ...ZERO_USAGE, cost: { ...ZERO_USAGE.cost } },
+ stopReason: "toolUse",
+ timestamp: Date.now(),
+ };
+ },
+ emit: (event, nestedParentToolCallId, ts = Date.now()) => {
+ const turnId = bindings.turnId();
+ bindings.emit({
+ sessionId: bindings.sessionId,
+ ...(turnId ? { turnId } : {}),
+ ts,
+ event,
+ nestedParentToolCallId,
+ });
+ },
+ track: (toolCallId, info) => {
+ bindings.activeToolCalls.set(toolCallId, info);
+ },
+ untrack: (toolCallId) => {
+ bindings.activeToolCalls.delete(toolCallId);
+ },
+ settleBatch: (message) => bindings.settleBatch(message),
+ };
+ return createCodemodeTool({
+ runner: new NestedToolRunner(host),
+ callableTools: () =>
+ bindings.active().filter((tool) => tool.name !== CODEMODE_TOOL_NAME && !bindings.excluded.has(tool.name)),
+ models: createRuntimeModelHost({
+ provider: bindings.provider,
+ sessionId: bindings.sessionId,
+ ...(bindings.jevApiKey ? { jevApiKey: bindings.jevApiKey } : {}),
+ turnId: bindings.turnId,
+ emitUsage: bindings.emitUsage,
+ }),
+ });
+}
diff --git a/packages/agent-runtime/src/codemode/tool.test.ts b/packages/agent-runtime/src/codemode/tool.test.ts
new file mode 100644
index 000000000..4d2c63ce7
--- /dev/null
+++ b/packages/agent-runtime/src/codemode/tool.test.ts
@@ -0,0 +1,337 @@
+import type { AgentTool, AgentToolResult, ToolCallHooks } from "@earendil-works/pi-agent-core";
+import type { AssistantMessage } from "@earendil-works/pi-ai";
+import { Type } from "typebox";
+import { describe, expect, it } from "vitest";
+import type { CodemodeModelHost } from "./model-globals.js";
+import { NestedToolRunner, type NestedToolEvent, type NestedToolHost } from "./nested-calls.js";
+import { createCodemodeTool, type CodemodeDetails } from "./tool.js";
+
+type Emitted = { event: NestedToolEvent; parent: string };
+
+function textTool(
+ name: string,
+ executionMode: "parallel" | "sequential",
+ run: (args: Record<string, unknown>, signal?: AbortSignal) => Promise<string>,
+): AgentTool {
+ return {
+ name,
+ label: name,
+ description: `${name} test tool`,
+ parameters: Type.Object({ value: Type.Optional(Type.String()) }),
+ executionMode,
+ execute: async (_id, args, signal) => ({
+ content: [{ type: "text", text: await run(args as Record<string, unknown>, signal) }],
+ details: {},
+ }),
+ };
+}
+
+function harness(tools: AgentTool[], hooks: ToolCallHooks = {}, models?: CodemodeModelHost) {
+ const emitted: Emitted[] = [];
+ const tracked = new Set<string>();
+ const settled: AssistantMessage[] = [];
+ const host: NestedToolHost = {
+ tools: () => tools,
+ hooks: () => hooks,
+ issuingMessage: (toolCall) => ({
+ role: "assistant",
+ content: [toolCall],
+ api: "openai-completions",
+ provider: "test",
+ model: "test",
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
+ stopReason: "toolUse",
+ timestamp: Date.now(),
+ }),
+ emit: (event, parent) => emitted.push({ event, parent }),
+ track: (id) => tracked.add(id),
+ untrack: (id) => tracked.delete(id),
+ settleBatch: (message) => settled.push(message),
+ };
+ const runner = new NestedToolRunner(host);
+ const terminated: string[] = [];
+ const tool = createCodemodeTool({
+ runner,
+ callableTools: () => tools,
+ ...(models ? { models } : {}),
+ onTerminate: (id) => terminated.push(id),
+ });
+ const run = (code: string, signal?: AbortSignal) =>
+ tool.execute("code-1", { code }, signal) as Promise<AgentToolResult<CodemodeDetails>>;
+ return { run, emitted, tracked, settled, terminated };
+}
+
+function text(result: AgentToolResult<unknown>): string {
+ return result.content.map((block) => (block.type === "text" ? block.text : `[${block.type}]`)).join("\n");
+}
+
+describe("codemode tool", () => {
+ it("runs nested calls through the session pipeline and returns only script output", async () => {
+ const read = textTool("Read", "parallel", async (args) => `contents of ${String(args.value)}`);
+ const { run, emitted, tracked, settled } = harness([read]);
+ const result = await run(`
+ const [a, b] = await Promise.all([tools.Read({ value: "a" }), tools.Read({ value: "b" })]);
+ return [a, b].map((s) => s.length);
+ `);
+ expect(result.isError).toBeUndefined();
+ expect(text(result)).toContain("Script completed");
+ expect(text(result)).toContain("[13,13]");
+ expect(text(result)).not.toContain("contents of a");
+ expect(result.details.calls.map((call) => [call.id, call.name, call.status])).toEqual([
+ ["code-1/1", "Read", "ok"],
+ ["code-1/2", "Read", "ok"],
+ ]);
+ // Lineage: every nested event names the script call as its immediate parent.
+ expect(emitted.map(({ event, parent }) => [event.type, event.toolCallId, parent])).toEqual(
+ expect.arrayContaining([
+ ["tool_start", "code-1/1", "code-1"],
+ ["tool_end", "code-1/1", "code-1"],
+ ["tool_start", "code-1/2", "code-1"],
+ ["tool_end", "code-1/2", "code-1"],
+ ]),
+ );
+ expect(tracked.size).toBe(0);
+ expect(settled).toHaveLength(2);
+ });
+
+ it("applies the session's beforeToolCall gate to nested calls", async () => {
+ const bash = textTool("Bash", "sequential", async () => "ran");
+ const { run } = harness([bash], {
+ beforeToolCall: async ({ toolCall }) =>
+ toolCall.name === "Bash" ? { block: true, reason: "Call ToolSearch to activate Bash before using it." } : undefined,
+ });
+ const result = await run(`
+ try { await tools.Bash({}); return "not blocked"; }
+ catch (error) { return "blocked: " + error.message; }
+ `);
+ expect(text(result)).toContain("blocked: Call ToolSearch to activate Bash");
+ expect(result.details.calls[0]).toMatchObject({ name: "Bash", status: "error" });
+ });
+
+ it("serializes exclusive tools while parallel-safe reads overlap", async () => {
+ let active = 0;
+ let maxSequential = 0;
+ let readActive = 0;
+ let maxRead = 0;
+ const gate = () => new Promise<void>((resolve) => setImmediate(resolve));
+ const bash = textTool("Bash", "sequential", async () => {
+ active += 1;
+ maxSequential = Math.max(maxSequential, active);
+ await gate();
+ active -= 1;
+ return "ok";
+ });
+ const read = textTool("Read", "parallel", async () => {
+ readActive += 1;
+ maxRead = Math.max(maxRead, readActive);
+ await gate();
+ await gate();
+ readActive -= 1;
+ return "ok";
+ });
+ const { run } = harness([bash, read]);
+ await run(`
+ await Promise.all([tools.Bash({}), tools.Bash({}), tools.Bash({})]);
+ await Promise.all([tools.Read({}), tools.Read({}), tools.Read({})]);
+ `);
+ expect(maxSequential).toBe(1);
+ expect(maxRead).toBeGreaterThan(1);
+ });
+
+ it("serializes Write and Edit even when the Host could batch them", async () => {
+ let active = 0;
+ let max = 0;
+ const gate = () => new Promise<void>((resolve) => setImmediate(resolve));
+ const writer = (name: string) => textTool(name, "parallel", async () => {
+ active += 1;
+ max = Math.max(max, active);
+ await gate();
+ active -= 1;
+ return "ok";
+ });
+ const { run } = harness([writer("Write"), writer("Edit")]);
+ await run(`await Promise.all([tools.Write({}), tools.Edit({}), tools.Write({})]);`);
+ expect(max).toBe(1);
+ });
+
+ it("rejects a failed call even when it carries structured content", async () => {
+ const structured: AgentTool = {
+ ...textTool("mcp_probe", "sequential", async () => "unused"),
+ outputSchema: { type: "object" },
+ execute: async () => ({ content: [{ type: "text", text: "remote failure" }], details: {}, structuredContent: { ok: false }, isError: true }),
+ };
+ const { run } = harness([structured]);
+ const result = await run(`try { await tools.mcp_probe({}); return "resolved"; } catch (error) { return "rejected: " + error.message; }`);
+ expect(text(result)).toContain("rejected: remote failure");
+ });
+
+ it("does not wedge the exclusive queue when building a call fails", async () => {
+ const bash = textTool("Bash", "sequential", async () => "ran");
+ const emitted: NestedToolEvent[] = [];
+ const tracked = new Set<string>();
+ let issued = 0;
+ const runner = new NestedToolRunner({
+ tools: () => [bash],
+ hooks: () => ({}),
+ issuingMessage: (toolCall) => {
+ issued += 1;
+ if (issued === 1) throw new Error("synthetic issue failure");
+ return {
+ role: "assistant", content: [toolCall], api: "openai-completions", provider: "test", model: "test",
+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0, cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },
+ stopReason: "toolUse", timestamp: Date.now(),
+ };
+ },
+ emit: (event) => emitted.push(event),
+ track: (id) => tracked.add(id),
+ untrack: (id) => tracked.delete(id),
+ settleBatch: () => undefined,
+ });
+ const tool = createCodemodeTool({ runner, callableTools: () => [bash] });
+ const result = await tool.execute("code-1", { code: `
+ const first = await tools.Bash({}).then(() => "ok", (error) => "error: " + error.message);
+ const second = await tools.Bash({});
+ return first + " | " + second;
+ ` }) as AgentToolResult<CodemodeDetails>;
+ expect(text(result)).toContain("error: synthetic issue failure | ran");
+ expect(tracked.size).toBe(0);
+ // The failed call never started, so it has neither start nor end events.
+ expect(emitted.map((event) => [event.type, event.toolCallId])).toEqual([
+ ["tool_start", "code-1/2"],
+ ["tool_end", "code-1/2"],
+ ]);
+ });
+
+ it("reports completed side effects when the script fails later", async () => {
+ const write = textTool("Write", "sequential", async () => "written");
+ const { run } = harness([write]);
+ const result = await run(`
+ await tools.Write({ value: "x" });
+ throw new Error("boom");
+ `);
+ expect(result.isError).toBe(true);
+ expect(text(result)).toContain("Error: boom");
+ expect(text(result)).toContain("completed side effects are not undone");
+ expect(text(result)).toContain("Write (ok)");
+ });
+
+ it("propagates cancellation to an in-flight nested call", async () => {
+ let observed: AbortSignal | undefined;
+ let started!: () => void;
+ const startedPromise = new Promise<void>((resolve) => { started = resolve; });
+ const slow = textTool("Bash", "sequential", (_args, signal) => {
+ observed = signal;
+ started();
+ return new Promise((_resolve, reject) => {
+ signal?.addEventListener("abort", () => reject(new Error("aborted by host")), { once: true });
+ });
+ });
+ const { run } = harness([slow]);
+ const controller = new AbortController();
+ const pending = run(`await tools.Bash({});`, controller.signal);
+ await startedPromise;
+ controller.abort();
+ const result = await pending;
+ expect(observed?.aborted).toBe(true);
+ expect(result.isError).toBe(true);
+ expect(result.details.errorKind).toBe("aborted");
+ });
+
+ it("enforces the nested call cap", async () => {
+ const read = textTool("Read", "parallel", async () => "x");
+ const { run } = harness([read]);
+ const result = await run(`
+ let count = 0;
+ try { for (let i = 0; i < 300; i++) { await tools.Read({}); count++; } }
+ catch (error) { return count + " " + error.message; }
+ `);
+ expect(text(result)).toContain("256 codemode scripts may start at most 256 nested calls.");
+ });
+
+ it("bounds output to the requested token budget", async () => {
+ const { run } = harness([]);
+ const result = await run(`// @options: {"max_output_tokens": 100}\ntext("a".repeat(5000));`);
+ expect(text(result)).toContain("Warning: output truncated");
+ expect(text(result).length).toBeLessThan(1_000);
+ expect(result.details.truncated).toBe(true);
+ });
+
+ it("caps the VM heap", async () => {
+ const { run } = harness([]);
+ const result = await run(`const parts = []; while (true) parts.push("x".repeat(1 << 20) + parts.length);`);
+ expect(result.isError).toBe(true);
+ expect(text(result)).toMatch(/out of memory/i);
+ }, 60_000);
+
+ it("exposes model capabilities without bindings and records model calls", async () => {
+ const requests: unknown[] = [];
+ const models: CodemodeModelHost = {
+ list: () => [{ kind: "chat", providerId: "acct-1", id: "model-a", contextWindow: 1000, maxTokens: 100, reasoning: false, input: ["text"] }],
+ complete: async (request) => {
+ requests.push(request);
+ return { text: "summary" };
+ },
+ };
+ const { run } = harness([], {}, models);
+ const result = await run(`
+ const listed = await models.list();
+ const done = await models.complete({ prompt: "summarize", maxOutputTokens: 99999 });
+ return { listed, done, classify: "classify" in models };
+ `);
+ const value = JSON.parse(text(result).split("Output:\n")[1] ?? "{}") as Record<string, unknown>;
+ expect(value).toEqual({
+ listed: [{ kind: "chat", providerId: "acct-1", id: "model-a", contextWindow: 1000, maxTokens: 100, reasoning: false, input: ["text"] }],
+ done: { text: "summary", model: { providerId: "acct-1", id: "model-a" } },
+ classify: false,
+ });
+ expect(requests).toEqual([{ prompt: "summarize", maxOutputTokens: 16_384 }]);
+ expect(result.details.calls).toEqual([
+ expect.objectContaining({ name: "models.complete", kind: "model", status: "ok", arguments: { model: "acct-1/model-a" } }),
+ ]);
+ });
+
+ it("routes models.generateImages through the nested GenerateImages call only when callable", async () => {
+ const images = textTool("GenerateImages", "sequential", async () => "saved 1 image");
+ const withImages = harness([images], {}, { list: () => [] });
+ const ok = await withImages.run(`return await models.generateImages({ value: "cat" });`);
+ expect(text(ok)).toContain("saved 1 image");
+ expect(withImages.emitted.some(({ event }) => event.type === "tool_start" && event.toolName === "GenerateImages")).toBe(true);
+
+ const without = harness([], {}, { list: () => [] });
+ const missing = await without.run(`return "generateImages" in models;`);
+ expect(text(missing)).toContain("false");
+ });
+
+ it("searches and describes only callable tools", async () => {
+ const read = textTool("Read", "parallel", async () => "x");
+ const { run } = harness([read]);
+ const result = await run(`return { found: await searchTools("read test"), none: await searchTools("bash"), sample: await describeTool("Read") };`);
+ const value = JSON.parse(text(result).split("Output:\n")[1] ?? "{}") as { found: unknown; none: unknown; sample: string };
+ expect(value.found).toEqual([{ name: "Read", description: "Read test tool" }]);
+ expect(value.none).toEqual([]);
+ expect(value.sample).toContain("Read");
+ });
+
+ it("reports missing sandbox assets as a sandbox failure with no nested calls", async () => {
+ const tool = createCodemodeTool({
+ runner: new NestedToolRunner({
+ tools: () => [], hooks: () => ({}), issuingMessage: () => { throw new Error("unused"); },
+ emit: () => undefined, track: () => undefined, untrack: () => undefined, settleBatch: () => undefined,
+ }),
+ callableTools: () => [],
+ assets: { wasmPath: "/nonexistent/quickjs.wasm", workerUrl: new URL("file:///nonexistent/codemode-worker.js") },
+ });
+ const result = await tool.execute("code-1", { code: "return 1" }) as AgentToolResult<CodemodeDetails>;
+ expect(result.isError).toBe(true);
+ expect(text(result)).toContain("Script sandbox failed");
+ expect(text(result)).toContain("No nested calls were made.");
+ expect(result.details.errorKind).toBe("sandbox");
+ });
+
+ it("rejects malformed options before starting a worker", async () => {
+ const { run } = harness([]);
+ const result = await run(`// @options: {"unknown": 1}\nreturn 1;`);
+ expect(result.isError).toBe(true);
+ expect(text(result)).toContain("The script did not start.");
+ });
+});
diff --git a/packages/agent-runtime/src/codemode/tool.ts b/packages/agent-runtime/src/codemode/tool.ts
new file mode 100644
index 000000000..687512dd2
--- /dev/null
+++ b/packages/agent-runtime/src/codemode/tool.ts
@@ -0,0 +1,211 @@
+/**
+ * The opt-in `codemode` tool (ADR codemode-sandbox-boundary): the model writes
+ * JavaScript that runs in a QuickJS-WASI worker and calls this session's tools
+ * and auxiliary models. Only the script's output reaches the model; nested
+ * results stay in the transcript as child rows of the codemode call.
+ *
+ * The sandbox holds no host function or credential. Every nested tool call is
+ * dispatched by {@link NestedToolRunner} through the session's normal tool
+ * pipeline, and every model call through the session's own bindings.
+ */
+import type { AgentTool, AgentToolResult } from "@earendil-works/pi-agent-core";
+import type { CodemodeTool } from "@earendil-works/pi-codemode";
+import { renderToolSample, toCodemodeIdentifier } from "@earendil-works/pi-codemode/declarations";
+import { CodemodeSourceError, parseCodemodeSource } from "@earendil-works/pi-codemode/source";
+import { Type } from "typebox";
+import { CODEMODE_LIMITS, CODEMODE_TOOL_NAME } from "./limits.js";
+import { createModelGlobals, type CodemodeModelHost } from "./model-globals.js";
+import { NestedCallRecorder, scriptValueOf, type NestedCallRecord, type NestedToolRunner } from "./nested-calls.js";
+import { formatNotStarted, formatScriptResult } from "./output.js";
+import { runInSandbox, type CodemodeAssets } from "./sandbox.js";
+
+export { CODEMODE_TOOL_NAME } from "./limits.js";
+
+/** Image generation is reachable as `models.generateImages()` when this tool is callable. */
+export const CODEMODE_IMAGE_TOOL_NAME = "GenerateImages";
+
+export type CodemodeDetails = {
+ calls: NestedCallRecord[];
+ complete: boolean;
+ status: "running" | "completed" | "failed";
+ errorKind?: string;
+ truncated?: boolean;
+};
+
+export type CodemodeToolOptions = {
+ runner: NestedToolRunner;
+ /** Tools a script may call right now: the session's active set minus control tools. */
+ callableTools(): readonly AgentTool[];
+ models?: CodemodeModelHost;
+ /** A nested call asked the turn to stop after this tool (mutation recovery). */
+ onTerminate?(callerId: string): void;
+ /** Test seam for asset locations. */
+ assets?: CodemodeAssets;
+};
+
+function description(models: boolean): string {
+ return [
+ "Run JavaScript in an isolated QuickJS sandbox to batch, chain, or filter tool calls locally, so only the final result enters the conversation. `code` is the body of an async function: top-level `await` and `return` work. There is no Node API, filesystem, network, timer, or module access.",
+ "- `await tools.<Name>(args)` runs one of the tools currently available to you through the normal permission and approval flow. It resolves to the tool's text result and rejects with an Error on failure. On-demand tools must be activated with ToolSearch before a script can call them. `ALL_TOOLS` lists callable tools; `await searchTools(query)` finds them and `await describeTool(name)` shows a tool's arguments.",
+ "- Read, Glob, and Grep calls may overlap (for example with `Promise.all`); every other tool runs one call at a time.",
+ "- `text(value)`, `console.log(...)`, `image(dataUrl)`, and `return value` produce output; `exit()` ends the script early. Calls still running when the script ends are cancelled.",
+ ...(models ? ["- `await models.list()`, `await models.complete({ prompt, system?, maxOutputTokens? })`, `await models.classify({ state, questions })` and `await models.generateImages(args)` reach this session's auxiliary models when they are configured."] : []),
+ `- Optional first line: \`// @options: {"max_output_tokens": ${CODEMODE_LIMITS.defaultMaxOutputTokens}, "timeout_ms": ${CODEMODE_LIMITS.defaultTimeoutMs}}\` (at most ${CODEMODE_LIMITS.maxOutputTokens} tokens and ${CODEMODE_LIMITS.maxTimeoutMs} ms). A script may start at most ${CODEMODE_LIMITS.maxCalls} nested calls.`,
+ "- A failed script reports which nested calls already ran. Their side effects are not undone.",
+ ].join("\n");
+}
+
+function sample(tool: AgentTool): string {
+ return renderToolSample({
+ name: tool.name,
+ description: tool.description,
+ inputSchema: tool.parameters as Record<string, unknown>,
+ outputSchema: (tool.outputSchema as Record<string, unknown> | undefined) ?? { type: "string" },
+ });
+}
+
+function clamp(value: number | undefined, fallback: number, max: number): number {
+ if (value === undefined || !Number.isFinite(value) || value <= 0) return fallback;
+ return Math.min(Math.round(value), max);
+}
+
+export function createCodemodeTool(options: CodemodeToolOptions): AgentTool<ReturnType<typeof codemodeSchema>, CodemodeDetails> {
+ return {
+ name: CODEMODE_TOOL_NAME,
+ label: "Codemode",
+ description: description(options.models !== undefined),
+ parameters: codemodeSchema(),
+ executionMode: "sequential",
+ execute: async (toolCallId, params, signal, onUpdate) => {
+ const startedAt = performance.now();
+ const elapsed = () => performance.now() - startedAt;
+ const fail = (reason: string): AgentToolResult<CodemodeDetails> => ({
+ content: formatNotStarted(reason, elapsed()),
+ details: { calls: [], complete: true, status: "failed" },
+ isError: true,
+ });
+ const raw = (params as { code?: unknown }).code;
+ if (typeof raw !== "string") return fail("`code` must be a JavaScript string.");
+ if (raw.length > CODEMODE_LIMITS.maxCodeChars) {
+ return fail(`The script is ${raw.length} characters; the limit is ${CODEMODE_LIMITS.maxCodeChars}.`);
+ }
+ let parsed: ReturnType<typeof parseCodemodeSource>;
+ try {
+ parsed = parseCodemodeSource(raw);
+ } catch (error) {
+ if (error instanceof CodemodeSourceError) return fail(error.message);
+ throw error;
+ }
+ const timeoutMs = clamp(parsed.options.timeoutMs, CODEMODE_LIMITS.defaultTimeoutMs, CODEMODE_LIMITS.maxTimeoutMs);
+ const maxOutputTokens = clamp(parsed.options.maxOutputTokens, CODEMODE_LIMITS.defaultMaxOutputTokens, CODEMODE_LIMITS.maxOutputTokens);
+
+ const publish = () => {
+ const snapshot = recorder.snapshot();
+ onUpdate?.({ content: [], details: { ...snapshot, status: "running" } });
+ };
+ const recorder = new NestedCallRecorder(publish);
+ let terminate = false;
+ const callable = options.callableTools().filter((tool) => tool.name !== CODEMODE_TOOL_NAME);
+ const byName = new Map(callable.map((tool) => [tool.name, tool]));
+ const runNested = async (name: string, args: unknown, callSignal: AbortSignal): Promise<unknown> => {
+ const tool = byName.get(name);
+ if (terminate) throw new Error("A previous call ended this turn; no further calls run.");
+ const outcome = await options.runner.run(toolCallId, name, args, recorder, callSignal);
+ if (outcome.terminate) {
+ terminate = true;
+ options.onTerminate?.(toolCallId);
+ }
+ return scriptValueOf(tool, outcome);
+ };
+ const tools: CodemodeTool[] = callable.map((tool) => ({
+ name: tool.name,
+ description: sample(tool),
+ execute: (args, context) => runNested(tool.name, args, context.signal),
+ }));
+ const describe: CodemodeTool = {
+ name: "describeTool",
+ description: "Arguments and result type of a callable tool.",
+ execute: (name) => {
+ if (typeof name !== "string") throw new Error("describeTool() expects a tool name.");
+ const tool = callable.find((candidate) => candidate.name === name || toCodemodeIdentifier(candidate.name) === name);
+ return tool ? sample(tool) : undefined;
+ },
+ };
+ const search: CodemodeTool = {
+ name: "searchTools",
+ description: "Callable tools whose name or description contains every query word.",
+ execute: (query) => {
+ if (typeof query !== "string") throw new Error("searchTools() expects a query string.");
+ const words = query.toLowerCase().split(/\s+/).filter(Boolean);
+ return callable
+ .filter((tool) => {
+ const haystack = `${tool.name}\n${tool.description}`.toLowerCase();
+ return words.every((word) => haystack.includes(word));
+ })
+ .slice(0, 24)
+ .map((tool) => ({ name: toCodemodeIdentifier(tool.name), description: tool.description.split("\n")[0] }));
+ },
+ };
+ const globals = [
+ describe,
+ search,
+ ...createModelGlobals({
+ callerId: toolCallId,
+ host: options.models,
+ recorder,
+ ...(byName.has(CODEMODE_IMAGE_TOOL_NAME)
+ ? { generateImages: (args: unknown, callSignal: AbortSignal) => runNested(CODEMODE_IMAGE_TOOL_NAME, args, callSignal) }
+ : {}),
+ }),
+ ];
+ publish();
+ try {
+ let run: Awaited<ReturnType<typeof runInSandbox>>;
+ try {
+ run = await runInSandbox({
+ code: parsed.code,
+ tools,
+ globals,
+ timeoutMs,
+ ...(signal ? { signal } : {}),
+ ...(options.assets ? { assets: options.assets } : {}),
+ });
+ } catch (error) {
+ // Loading the module, worker or WASM failed: no script code ran.
+ return fail(`The codemode sandbox could not start: ${error instanceof Error ? error.message : String(error)}`);
+ }
+ if (!run.started) {
+ return fail(run.reason === "aborted"
+ ? "Script aborted before a sandbox worker was free."
+ : `No codemode worker became free within ${Math.round(Math.min(timeoutMs, CODEMODE_LIMITS.workerWaitMs) / 1000)} seconds. Retry after other scripts finish.`);
+ }
+ recorder.cancelRunning();
+ const { result } = run;
+ const formatted = formatScriptResult(result, recorder.calls, maxOutputTokens, elapsed());
+ const snapshot = recorder.snapshot();
+ return {
+ content: formatted.content,
+ details: {
+ ...snapshot,
+ status: result.ok ? "completed" : "failed",
+ ...(result.ok ? {} : { errorKind: result.error.kind }),
+ ...(formatted.truncated ? { truncated: true } : {}),
+ },
+ ...(result.ok ? {} : { isError: true }),
+ ...(terminate ? { terminate: true } : {}),
+ };
+ } finally {
+ options.runner.finishScript(toolCallId);
+ }
+ },
+ };
+}
+
+export function codemodeSchema() {
+ return Type.Object(
+ {
+ code: Type.String({ description: "Raw JavaScript source: the body of an async function." }),
+ },
+ { additionalProperties: false },
+ );
+}
diff --git a/packages/agent-runtime/src/codemode/worker.ts b/packages/agent-runtime/src/codemode/worker.ts
new file mode 100644
index 000000000..79495d51f
--- /dev/null
+++ b/packages/agent-runtime/src/codemode/worker.ts
@@ -0,0 +1,6 @@
+/**
+ * Worker entry for the codemode sandbox. The sidecar bundle builds this file
+ * into `chunks/codemode-worker.js` next to `quickjs.wasm`, because a packaged
+ * app has no node_modules to resolve the package's own worker from.
+ */
+import "@earendil-works/pi-codemode/worker";
diff --git a/packages/agent-runtime/src/jev-classifier-tool.ts b/packages/agent-runtime/src/jev-classifier-tool.ts
index 19bda4672..97c4a3d6c 100644
--- a/packages/agent-runtime/src/jev-classifier-tool.ts
+++ b/packages/agent-runtime/src/jev-classifier-tool.ts
@@ -4,8 +4,10 @@ import { typesafeProvider } from "@earendil-works/pi-ai/providers/typesafe";
import type {
ClassifierContext,
ClassifierQuestion,
+ ClassifierResult,
JsonObject,
JsonValue,
+ Usage,
} from "@earendil-works/pi-ai";
import type { AgentTool } from "@earendil-works/pi-agent-core";
import { Type } from "typebox";
@@ -160,6 +162,61 @@ function parseContext(value: unknown): ClassifierContext | undefined {
return context;
}
+export type JevClassification =
+ | { ok: true; answers: ClassifierResult["answers"]; usage?: Usage }
+ | {
+ ok: false;
+ errorCode: "JEV_INVALID_ARGUMENT" | "JEV_ABORTED" | "JEV_REQUEST_FAILED";
+ message: string;
+ /** Reported by a request that reached the service but did not complete. */
+ usage?: Usage;
+ };
+
+/** The physical classifier model, for usage attribution by callers. */
+export const JEV_MODEL_REF = { provider: jevModel.provider, id: jevModel.id, name: jevModel.name } as const;
+
+const JEV_INVALID_ARGUMENT_MESSAGE =
+ "JevClassify requires a JSON object state and 1–16 valid structured questions; the total input must be at most 24 KiB.";
+
+/**
+ * Validate and run one TypeSafe Jev classification. Shared by the
+ * `JevClassify` tool and the codemode `models.classify()` global so both apply
+ * the same bounds, timeout, and credential redaction.
+ */
+export async function classifyWithJev(
+ apiKey: string,
+ rawParams: unknown,
+ signal?: AbortSignal,
+ options: { maxRetries?: number } = {},
+): Promise<JevClassification> {
+ const context = parseContext(rawParams);
+ if (!context) {
+ return { ok: false, errorCode: "JEV_INVALID_ARGUMENT", message: JEV_INVALID_ARGUMENT_MESSAGE };
+ }
+ const timeoutSignal = AbortSignal.timeout(45_000);
+ const requestSignal = signal
+ ? AbortSignal.any([signal, timeoutSignal])
+ : timeoutSignal;
+ const result = await models.classify(jevModel, context, {
+ apiKey,
+ signal: requestSignal,
+ timeoutMs: 45_000,
+ maxRetries: options.maxRetries ?? 1,
+ });
+ if (result.stopReason !== "stop") {
+ const errorMessage = (result.errorMessage ?? "Request did not complete")
+ .replaceAll(apiKey, "[redacted]")
+ .slice(0, 1_000);
+ return {
+ ok: false,
+ errorCode: result.stopReason === "aborted" ? "JEV_ABORTED" : "JEV_REQUEST_FAILED",
+ message: `Jev classification failed: ${errorMessage}`,
+ ...(result.usage ? { usage: result.usage } : {}),
+ };
+ }
+ return { ok: true, answers: result.answers, ...(result.usage ? { usage: result.usage } : {}) };
+}
+
/** Agent-only, deferred call to pi-ai's TypeSafe System One classifier. */
export function createJevClassifierTool(apiKey: string): AgentTool {
return {
@@ -183,41 +240,11 @@ export function createJevClassifierTool(apiKey: string): AgentTool {
),
executionMode: "sequential",
execute: async (_toolCallId, rawParams, signal) => {
- const context = parseContext(rawParams);
- if (!context) {
- return {
- content: [
- {
- type: "text",
- text: "JevClassify requires a JSON object state and 1–16 valid structured questions; the total input must be at most 24 KiB.",
- },
- ],
- details: { errorCode: "JEV_INVALID_ARGUMENT" },
- isError: true,
- };
- }
- const timeoutSignal = AbortSignal.timeout(45_000);
- const requestSignal = signal
- ? AbortSignal.any([signal, timeoutSignal])
- : timeoutSignal;
- const result = await models.classify(jevModel, context, {
- apiKey,
- signal: requestSignal,
- timeoutMs: 45_000,
- maxRetries: 1,
- });
- if (result.stopReason !== "stop") {
- const errorMessage = (result.errorMessage ?? "Request did not complete")
- .replaceAll(apiKey, "[redacted]")
- .slice(0, 1_000);
+ const result = await classifyWithJev(apiKey, rawParams, signal);
+ if (!result.ok) {
return {
- content: [{ type: "text", text: `Jev classification failed: ${errorMessage}` }],
- details: {
- errorCode:
- result.stopReason === "aborted"
- ? "JEV_ABORTED"
- : "JEV_REQUEST_FAILED",
- },
+ content: [{ type: "text", text: result.message }],
+ details: { errorCode: result.errorCode },
isError: true,
};
}
diff --git a/packages/agent-runtime/src/one-shot-complete.ts b/packages/agent-runtime/src/one-shot-complete.ts
index 2778bb74f..2886a5c29 100644
--- a/packages/agent-runtime/src/one-shot-complete.ts
+++ b/packages/agent-runtime/src/one-shot-complete.ts
@@ -57,6 +57,11 @@ export type OneShotCompleteOptions = {
emptyErrorMessage?: string;
/** Conversation id forwarded to OpenCode as `x-opencode-session`. */
sessionId?: string;
+ /**
+ * Observe each physical attempt's identified usage as it is reported, so a
+ * caller can write the ledger even when a later attempt fails.
+ */
+ onUsage?: (usage: MessageUsage) => void;
};
export type OneShotCompleteResult = {
@@ -148,7 +153,10 @@ export async function completeOneShot(
sessionOptions,
(retryOptions) => accountModelStream(model, () => streamSimple(model, context, retryOptions), {
providerId: provider.id, nativeCost: provider.modelConfig?.nativeCost,
- onUsage: attemptUsage => { usage = addUsage(usage, attemptUsage); },
+ onUsage: attemptUsage => {
+ usage = addUsage(usage, attemptUsage);
+ options.onUsage?.(attemptUsage);
+ },
}),
{
claim: (error, phase) => {
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index 60597e840..6b5a94437 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -196,6 +196,7 @@ function createRuntime(
pluginSkills: import("./plugin-skills-prompt.js").PluginSkillDef[];
commandShell: CommandShellOption;
jevApiKey: string;
+ codemodeEnabled: boolean;
turnId: string;
host: { call: ReturnType<typeof vi.fn>; onNotification?: ReturnType<typeof vi.fn> };
onEvent: (envelope: unknown) => void;
@@ -206,6 +207,7 @@ function createRuntime(
sessionId: "session-1",
mode: overrides.mode === "chat" ? "plan" : overrides.mode ?? "agent",
jevApiKey: overrides.jevApiKey,
+ codemodeEnabled: overrides.codemodeEnabled,
turnId: overrides.turnId,
provider: overrides.provider ?? provider,
commandShell: overrides.commandShell ?? commandShell,
@@ -988,6 +990,7 @@ describe("Task/read mixed-batch safety", () => {
*/
function setupMixedBatch(
calls: unknown[] = [taskCall("task"), readCall("read")],
+ options: { codemodeEnabled?: boolean } = {},
) {
const entered: string[] = [];
const events: any[] = [];
@@ -1002,6 +1005,7 @@ describe("Task/read mixed-batch safety", () => {
};
const runtime = createRuntime({
host,
+ ...options,
onEvent: (envelope) => { events.push((envelope as any).event); },
subagents: [{
name: "explorer",
@@ -1138,6 +1142,29 @@ describe("Task/read mixed-batch safety", () => {
},
);
+ it("holds a same-batch codemode script behind a writable delegate", async () => {
+ const batch = setupMixedBatch([
+ taskCall("task"),
+ { type: "toolCall", id: "code", name: "codemode", arguments: { code: 'return await tools.Read({ path: "target.txt" });' } },
+ ], { codemodeEnabled: true });
+ try {
+ const pending = batch.runtime.prompt("Delegate, then script.");
+ await vi.waitFor(() => expect(subagentRuns.instances).toHaveLength(1));
+ await vi.waitFor(() =>
+ expect(batch.events.some((event) => event.type === "tool_start" && event.toolCallId === "code")).toBe(true));
+ // While the writable delegate runs, the script's nested Read never reaches Host.
+ await expect(vi.waitFor(() => expect(batch.entered).not.toEqual([]), { timeout: 300 })).rejects.toThrow();
+ subagentRuns.resolveRun!(settled());
+ await vi.waitFor(() => expect(batch.entered).toEqual(["code/1"]));
+ batch.release("code/1")!({ ok: true, content: "updated" });
+ await pending;
+ const end = batch.events.find((event) => event.type === "tool_end" && event.toolCallId === "code");
+ expect(JSON.stringify(end?.result)).toContain("updated");
+ } finally {
+ await teardown(batch.runtime);
+ }
+ });
+
it("serializes a parent Read against an in-flight shared-workspace delegate Edit on the same path", async () => {
const batch = setupMixedBatch([taskCall("task")]);
subagentRuns.calls.length = 0;
@@ -1561,6 +1588,8 @@ describe("DesktopAgentRuntime configuration matching", () => {
runtimeFirstMismatch(runtime, { projectMemory: "Use the production database." }),
).toBe("projectMemory");
expect(runtimeFirstMismatch(runtime, { mode: "plan" })).toBe("mode");
+ // Turning codemode on changes the tool list, so the runtime is retired.
+ expect(runtimeFirstMismatch(runtime, { codemodeEnabled: true })).toBe("codemodeEnabled");
await runtime.dispose();
});
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index ff48fed14..e6fbd2a06 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -25,6 +25,8 @@ import { computerUseDescription, computerUseParameters } from "./computer-use/to
import { imageGenerationDescription, imageGenerationParameters } from "./image-generation/tool.js";
import { todoWriteDescription, todoWriteParameters } from "./todo-tool.js";
import { createJevClassifierTool } from "./jev-classifier-tool.js";
+import { CODEMODE_TOOL_NAME } from "./codemode/limits.js";
+import { createSessionCodemodeTool } from "./codemode/session.js";
import { scheduledToolParameters, scheduledToolDescriptions } from "./scheduled-tools.js";
import { withPiFileOpToolNames } from "./pi-file-ops.js";
import { remoteMutationIdentity } from "./remote-workspace.js";
@@ -978,6 +980,23 @@ function turnAbortedError(message: string): Error {
}
const CONTEXT_COMPACTION_TOOL_NAME = "new_context";
+/**
+ * Tools a codemode script never calls: tool discovery, user interaction, mode
+ * and stage control, context control, and delegation lifecycle all belong to
+ * the model's own turn, not to a script.
+ */
+const CODEMODE_EXCLUDED_TOOL_NAMES: ReadonlySet<string> = new Set([
+ CODEMODE_TOOL_NAME,
+ TOOL_SEARCH_NAME,
+ ASK_TOOL_NAME,
+ ...MODE_TRANSITION_TOOL_NAMES,
+ COMPLETE_STAGE_TOOL_NAME,
+ CONTEXT_COMPACTION_TOOL_NAME,
+ SUBAGENT_TOOL_NAME,
+ SUBAGENT_WAIT_TOOL_NAME,
+ SUBAGENT_LIST_TOOL_NAME,
+ SUBAGENT_STOP_TOOL_NAME,
+]);
/** Tools the read-only contract level may execute, besides plan-safe plugins. */
const CONTRACT_ALLOWED_TOOL_NAMES = new Set([...CONTRACT_CORE_TOOL_NAMES, CONTEXT_COMPACTION_TOOL_NAME]);
const CONTEXT_COMPACTION_TOOL_DESCRIPTION =
@@ -1070,6 +1089,11 @@ export type AgentRuntimeOptions = {
* prompt rather than advertised and refused on every call.
*/
computerUseEnabled?: boolean;
+ /**
+ * Whether the opt-in `codemode` tool is offered (ADR
+ * codemode-sandbox-boundary). Resolved by Electron main from settings.
+ */
+ codemodeEnabled?: boolean;
systemPrompt?: string;
/** pi-compatible SYSTEM.md / APPEND_SYSTEM.md resolved for the session (issue #542). */
customSystemPrompt?: CustomSystemPrompt;
@@ -1147,6 +1171,7 @@ export type RuntimeMatchConfig = {
thinkingLevel: SessionThinkingLevel;
jevApiKey?: string;
computerUseEnabled?: boolean;
+ codemodeEnabled?: boolean;
pluginTools?: PluginToolDef[];
pluginSkills?: PluginSkillDef[];
trustedExtensions?: TrustedExtensionSpec[];
@@ -2009,6 +2034,7 @@ export class DesktopAgentRuntime {
private fastMode = false;
private jevApiKey?: string;
private computerUseEnabled = false;
+ private codemodeEnabled = false;
private activeProviderRetryAttempt = 0;
private providerRetryInProgress = false;
private suppressProviderRetryRunEnd = false;
@@ -2127,6 +2153,7 @@ export class DesktopAgentRuntime {
this.fastMode = opts.fastMode === true;
this.jevApiKey = opts.jevApiKey;
this.computerUseEnabled = opts.computerUseEnabled === true;
+ this.codemodeEnabled = opts.codemodeEnabled === true;
this.host = opts.host;
this.batchPlanner = new BatchPlanner(this.host, this.sessionId);
this.onDiagnostic = opts.onDiagnostic ?? (() => undefined);
@@ -2867,6 +2894,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
// Turning computer use on or off changes the tool list, so the runtime
// is retired rather than left advertising a stale set.
["computerUseEnabled", this.computerUseEnabled === (config.computerUseEnabled === true)],
+ // Codemode changes the tool list as well.
+ ["codemodeEnabled", this.codemodeEnabled === (config.codemodeEnabled === true)],
["thinkingLevel", this.thinkingLevel === clampThinkingLevel(config.provider, config.thinkingLevel)],
["pluginTools", current === next],
["commandShell", safeJson(this.commandShell) === safeJson(config.commandShell)],
@@ -3232,6 +3261,10 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
// report, and replaying a delegate's messages would both contradict that
// and reintroduce the context cost delegation exists to avoid.
if (m.parentToolCallId) continue;
+ // Calls a codemode script made are transcript children of the script's
+ // call. The model only ever saw the script's own result, and these rows
+ // have no issuing assistant call to attach to (ADR codemode-sandbox-boundary).
+ if (m.nestedParentToolCallId) continue;
const timestamp = Date.parse(m.createdAt) || Date.now();
if (m.role === "system" && m.modelSystem) {
// An update recorded while a tool ran sits between the call and its
@@ -4215,6 +4248,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
agentLevel && this.jevApiKey
? [createJevClassifierTool(this.jevApiKey)]
: [];
+ const codemodeTools: AgentTool[] =
+ agentLevel && this.codemodeEnabled ? [this.buildCodemodeTool()] : [];
// Plugins contribute Agent tools by default. Plan/Goal modes only
// expose plugins that declare plan-safe actions (ADR 0211); the
@@ -4321,6 +4356,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
return [
...builtins,
...jevTools,
+ ...codemodeTools,
askTool,
...pluginTools,
...skillTools,
@@ -4336,6 +4372,41 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
* declarations. Execution activation and Host permissions remain separate
* from the provider-visible schemas.
*/
+ /**
+ * The opt-in `codemode` tool. Scripts call the session's active tools
+ * through the same hooks and Host path as direct calls; control,
+ * interactive and delegation tools stay out of reach.
+ */
+ private buildCodemodeTool(): AgentTool {
+ const tool = createSessionCodemodeTool({
+ sessionId: this.sessionId,
+ catalog: () => [...this.toolCatalog.values()],
+ active: () => this.activeTools().filter((tool) => this.isToolAllowedInMode(tool.name)),
+ excluded: CODEMODE_EXCLUDED_TOOL_NAMES,
+ hooks: {
+ beforeToolCall: (context) => this.beforeToolCall(context),
+ afterToolCall: (context) => this.afterToolCall(context),
+ },
+ model: () => this.model,
+ turnId: () => this.turnId,
+ emit: (envelope) => this.onEvent(envelope),
+ emitUsage: (usage, turnId) => this.emit({ type: "usage", usage }, turnId),
+ activeToolCalls: this.activeToolCalls,
+ settleBatch: (message) => this.batchPlanner.settleBatch(message),
+ provider: () => this.provider,
+ ...(this.jevApiKey ? { jevApiKey: this.jevApiKey } : {}),
+ });
+ return {
+ ...tool,
+ // Like a direct Read after a writable `Task` in the same message, a
+ // script waits for that delegate before any nested call runs.
+ execute: async (toolCallId, params, signal, onUpdate) => {
+ await this.waitForBatchWritableDelegations(toolCallId, signal);
+ return tool.execute(toolCallId, params, signal, onUpdate);
+ },
+ };
+ }
+
private guardSteeredTool(tool: AgentTool): AgentTool {
return { ...tool, execute: async (id, args, signal, update) => {
if (tool.name !== SUBAGENT_WAIT_TOOL_NAME && this.pendingSteering.size &&
@@ -4453,6 +4524,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
name === SUBAGENT_STOP_TOOL_NAME ||
// A stage's completion must never hide behind ToolSearch.
name === COMPLETE_STAGE_TOOL_NAME ||
+ // Codemode is opt-in; once enabled it is declared up front.
+ name === CODEMODE_TOOL_NAME ||
(this.modeState.isAgentLevel()
? AGENT_CORE_TOOL_NAMES.has(name)
: CONTRACT_CORE_TOOL_NAMES.has(name) || this.isPlanSafePluginTool(name))
diff --git a/packages/agent-runtime/src/sidecar.ts b/packages/agent-runtime/src/sidecar.ts
index 34e9a74f0..160de5df2 100644
--- a/packages/agent-runtime/src/sidecar.ts
+++ b/packages/agent-runtime/src/sidecar.ts
@@ -127,6 +127,8 @@ type RuntimeParams = {
jevApiKey?: string;
/** Set by main only for Agent sessions with computer use switched on. */
computerUseEnabled?: boolean;
+ /** Set by main only for Agent sessions with codemode switched on. */
+ codemodeEnabled?: boolean;
provider: RuntimeProviderConfig;
commandShell: CommandShellOption;
pluginTools?: PluginToolDef[];
@@ -258,6 +260,7 @@ async function runtimeFor(
subagentModelKeys,
jevApiKey: params.jevApiKey,
computerUseEnabled: params.computerUseEnabled === true,
+ codemodeEnabled: params.codemodeEnabled === true,
projectInstructions: params.projectInstructions,
customSystemPrompt: params.customSystemPrompt,
projectMemory: params.projectMemory,
@@ -344,6 +347,7 @@ async function runtimeFor(
fastMode: params.fastMode === true,
jevApiKey: params.jevApiKey,
computerUseEnabled: config.computerUseEnabled,
+ codemodeEnabled: config.codemodeEnabled,
history,
compaction,
compactionSettings: params.compactionSettings,
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index ffa76ebaf..744a9c084 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -1742,6 +1742,8 @@ sklm: {
"enterToSendDesc": "Aus: Zum Senden ⌘/Strg+Eingabe drücken.",
backgroundJobContinuation: "Nach Hintergrundaufgaben fortfahren",
backgroundJobContinuationDesc: "Lokale Gespräche nach angeforderten Tests oder Builds mit den bestehenden Berechtigungen fortsetzen. Standardmäßig aus. Ausschalten verwirft wartende Fortsetzungen, beendet aber keine Prozesse.",
+ codemode: "Codemode-Skripte",
+ codemodeDesc: "Erlaubt dem Assistenten, kurzes JavaScript in einer isolierten Sandbox auszuführen, um Werkzeug- und Modellaufrufe zu bündeln, zu verketten oder zu filtern, sodass nur das Endergebnis ins Gespräch gelangt. Jeder verschachtelte Aufruf nutzt weiterhin Ihren Berechtigungsmodus und Ihre Freigaben. Standardmäßig aus.",
"infiniteProviderRetry": "Bis zum Erfolg wiederholen",
"infiniteProviderRetryDesc": "Netzwerk- und vorübergehende Anbieterfehler werden bis zum Erfolg wiederholt. Du kannst den Lauf weiterhin stoppen; der API-Verbrauch kann fortlaufen.",
"smoothStreaming": "Sanftes Streaming",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index c7f36555f..2bf52cc4c 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -1754,6 +1754,8 @@ sklm: {
enterToSendDesc: "Off: press ⌘/Ctrl+Enter to send.",
backgroundJobContinuation: "Continue after background jobs",
backgroundJobContinuationDesc: "Allow the assistant to resume a local conversation after requested tests or builds finish, using the existing permission mode. Off by default. Turning this off cancels pending continuations, not their processes.",
+ codemode: "Codemode scripts",
+ codemodeDesc: "Let the assistant run short JavaScript in an isolated sandbox to batch, chain, or filter tool and model calls, so only the final result enters the conversation. Each nested call still uses your permission mode and approvals. Off by default.",
infiniteProviderRetry: "Retry until success",
infiniteProviderRetryDesc: "Keep retrying network and transient provider failures until the request succeeds. You can still stop the turn; API usage may continue while enabled.",
smoothStreaming: "Smooth streaming",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 6f7a7b994..79a302096 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -1742,6 +1742,8 @@ sklm: {
"enterToSendDesc": "Desactivado: presione ⌘/Ctrl+Entrar para enviar.",
backgroundJobContinuation: "Continuar tras tareas en segundo plano",
backgroundJobContinuationDesc: "Permitir reanudar la conversación local al terminar las pruebas o compilaciones solicitadas, con los permisos actuales. Desactivado por defecto. Desactivarlo cancela las continuaciones pendientes, no los procesos.",
+ codemode: "Scripts de Codemode",
+ codemodeDesc: "Permite que el asistente ejecute JavaScript breve en un entorno aislado para agrupar, encadenar o filtrar llamadas a herramientas y modelos, de modo que solo el resultado final entre en la conversación. Cada llamada anidada sigue usando tu modo de permisos y tus aprobaciones. Desactivado de forma predeterminada.",
"infiniteProviderRetry": "Reintentar hasta tener éxito",
"infiniteProviderRetryDesc": "Reintenta los errores de red y temporales hasta que la solicitud tenga éxito. Puedes detener el turno; el uso de la API puede continuar.",
"smoothStreaming": "Transmisión suave",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 7d0264e18..0b1908792 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -1742,6 +1742,8 @@ sklm: {
"enterToSendDesc": "Désactivé : appuyez sur ⌘/Ctrl+Entrée pour envoyer.",
backgroundJobContinuation: "Reprendre après les tâches en arrière-plan",
backgroundJobContinuationDesc: "Autoriser la reprise d’une conversation locale après les tests ou compilations demandés, avec les permissions actuelles. Désactivé par défaut. La désactivation annule les reprises en attente, sans arrêter les processus.",
+ codemode: "Scripts Codemode",
+ codemodeDesc: "Permet à l’assistant d’exécuter un court JavaScript dans un bac à sable isolé pour regrouper, enchaîner ou filtrer les appels d’outils et de modèles, afin que seul le résultat final entre dans la conversation. Chaque appel imbriqué respecte toujours votre mode d’autorisation et vos approbations. Désactivé par défaut.",
"infiniteProviderRetry": "Réessayer jusqu’à réussite",
"infiniteProviderRetryDesc": "Réessaie les erreurs réseau et temporaires jusqu’à la réussite. Vous pouvez toujours arrêter le tour ; la consommation d’API peut continuer.",
"smoothStreaming": "Streaming fluide",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 9176ee356..e6e82967e 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -1750,6 +1750,8 @@ sklm: {
enterToSendDesc: "끔: ⌘/Ctrl+Enter를 눌러 보내세요.",
backgroundJobContinuation: "백그라운드 작업 완료 후 계속",
backgroundJobContinuationDesc: "요청한 로컬 테스트나 빌드가 끝나면 기존 권한 모드로 대화를 재개합니다. 기본값은 꺼짐입니다. 끄면 대기 중인 재개만 취소되며 프로세스는 계속 실행됩니다.",
+ codemode: "Codemode 스크립트",
+ codemodeDesc: "어시스턴트가 격리된 샌드박스에서 짧은 JavaScript를 실행해 도구와 모델 호출을 묶거나 연결하거나 걸러내고, 최종 결과만 대화에 넣도록 허용합니다. 중첩된 각 호출은 여전히 현재 권한 모드와 승인을 따릅니다. 기본값은 꺼짐입니다.",
infiniteProviderRetry: "성공할 때까지 재시도",
infiniteProviderRetryDesc: "네트워크 및 일시적인 제공자 오류가 성공할 때까지 계속 재시도됩니다. 언제든 중지할 수 있지만 API 사용량이 계속 발생할 수 있습니다.",
smoothStreaming: "부드러운 스트리밍",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 2098402b7..e802014b0 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -1713,6 +1713,8 @@ export const ptBR = {
enterToSendDesc: "Desativado: pressione ⌘/Ctrl+Enter para enviar.",
backgroundJobContinuation: "Continuar após tarefas em segundo plano",
backgroundJobContinuationDesc: "Permitir retomar a conversa local após os testes ou compilações solicitados, com as permissões atuais. Desativado por padrão. Desativar cancela as continuações pendentes, sem encerrar os processos.",
+ codemode: "Scripts do Codemode",
+ codemodeDesc: "Permite que o assistente execute JavaScript curto em uma sandbox isolada para agrupar, encadear ou filtrar chamadas de ferramentas e modelos, de modo que só o resultado final entre na conversa. Cada chamada aninhada continua usando seu modo de permissão e suas aprovações. Desativado por padrão.",
infiniteProviderRetry: "Tentar novamente até obter sucesso",
infiniteProviderRetryDesc: "Continua tentando indefinidamente em caso de falhas temporárias de rede ou do provedor. Ainda é possível interromper a rodada; enquanto esta opção estiver ativada, o consumo e os custos da API podem continuar.",
smoothStreaming: "Exibição gradual",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index decb2adea..1011e44bd 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -1744,6 +1744,8 @@ sklm: {
enterToSendDesc: "Kapalı: göndermek için ⌘/Ctrl+Enter.",
backgroundJobContinuation: "Arka plan görevlerinden sonra devam et",
backgroundJobContinuationDesc: "İstenen yerel test veya derlemeler bitince mevcut izinlerle konuşmaya devam et. Varsayılan olarak kapalıdır. Kapatmak bekleyen devamları iptal eder, işlemleri durdurmaz.",
+ codemode: "Codemode betikleri",
+ codemodeDesc: "Asistanın araç ve model çağrılarını toplu yürütmek, zincirlemek veya süzmek için yalıtılmış bir sanal alanda kısa JavaScript çalıştırmasına izin verir; konuşmaya yalnızca nihai sonuç girer. Her iç içe çağrı yine izin modunuzu ve onaylarınızı kullanır. Varsayılan olarak kapalı.",
infiniteProviderRetry: "Başarılı olana kadar yeniden dene",
infiniteProviderRetryDesc: "Ağ ve geçici sağlayıcı hataları istek başarılı olana kadar yeniden denenir. Çalışmayı yine durdurabilirsiniz; açıkken API kullanımı sürebilir.",
smoothStreaming: "Düzgün akış",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index fed226404..30311bd73 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -1734,6 +1734,8 @@ sklm: {
enterToSendDesc: "关闭后按 ⌘/Ctrl+Enter 发送。",
backgroundJobContinuation: "后台任务完成后续跑",
backgroundJobContinuationDesc: "允许助手在安排的本地测试或构建结束后接回原会话,仍遵循现有权限模式。默认关闭;关闭时撤销待续跑任务,不停止后台进程。",
+ codemode: "Codemode 脚本",
+ codemodeDesc: "允许助手在隔离沙盒中运行简短的 JavaScript,批量、串联或筛选工具与模型调用,只把最终结果放回对话。每次嵌套调用仍遵循当前权限模式与审批。默认关闭。",
infiniteProviderRetry: "无尽重试",
infiniteProviderRetryDesc: "网络或临时服务故障会一直重试直到成功。仍可随时停止,但开启后可能持续消耗 API 用量。",
smoothStreaming: "平滑流式显示",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index b85cd5ea7..4e62b29bb 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -1734,6 +1734,8 @@ sklm: {
enterToSendDesc: "關閉後按 ⌘/Ctrl+Enter 傳送。",
backgroundJobContinuation: "背景工作完成後續跑",
backgroundJobContinuationDesc: "允許助理在安排的本機測試或建置結束後接回原對話,仍遵循現有權限模式。預設關閉;關閉時撤銷待續跑工作,不停止背景程序。",
+ codemode: "Codemode 腳本",
+ codemodeDesc: "允許助理在隔離沙盒中執行簡短的 JavaScript,批次、串接或篩選工具與模型呼叫,只把最終結果放回對話。每次巢狀呼叫仍遵循目前的權限模式與審核。預設關閉。",
infiniteProviderRetry: "無盡重試",
infiniteProviderRetryDesc: "網路或暫時性服務故障會持續重試直到成功。仍可隨時停止,但開啟後可能持續消耗 API 用量。",
smoothStreaming: "平滑串流顯示",
diff --git a/packages/shared/src/subagent-definition.ts b/packages/shared/src/subagent-definition.ts
index 54bbb4e4f..795eb2207 100644
--- a/packages/shared/src/subagent-definition.ts
+++ b/packages/shared/src/subagent-definition.ts
@@ -105,6 +105,8 @@ export const SUBAGENT_INHERIT_TOKEN = "inherit";
* reach because a delegate has no user. `ToolSearch` and `new_context` mutate
* the parent runtime's deferred-tool set and compaction flag, so they stay
* denied even though the child receives the full catalog without searching.
+ * `codemode` is bound to the parent session's tool pipeline and lineage, so a
+ * delegate never inherits it (ADR codemode-sandbox-boundary).
*/
export const SUBAGENT_INHERIT_DENY_TOOLS: readonly string[] = [
"Task",
@@ -117,6 +119,7 @@ export const SUBAGENT_INHERIT_DENY_TOOLS: readonly string[] = [
"asktool",
"new_context",
"ToolSearch",
+ "codemode",
];
/**
diff --git a/packages/shared/src/types/settings.ts b/packages/shared/src/types/settings.ts
index 7e91ec867..c03c2bc01 100644
--- a/packages/shared/src/types/settings.ts
+++ b/packages/shared/src/types/settings.ts
@@ -84,6 +84,11 @@ export type AppSettings = {
backgroundJobContinuationEnabled?: boolean;
/** Allow Agent mode to call TypeSafe Jev for explicit structured classifications. */
jevEnabled?: boolean;
+ /**
+ * Offer the sandboxed `codemode` tool in Agent mode (ADR
+ * codemode-sandbox-boundary). Off when absent.
+ */
+ codemodeEnabled?: boolean;
/** Prevent idle system sleep while this desktop app runs; off when absent. */
keepAwakeWhileRunning?: boolean;
/** Enable scheduled task UI, tools and new runs. Absent means enabled. */
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 4a90769d1..226c1fee6 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -439,6 +439,9 @@ importers:
'@earendil-works/pi-ai':
specifier: 1.5.2
version: 1.5.2(patch_hash=13ebb9c355267cf5341b0d1f4b089de6b73f0165be2c1492c10fa97a15d5e6bc)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])([email protected])
+ '@earendil-works/pi-codemode':
+ specifier: 1.5.2
+ version: 1.5.2
'@earendil-works/pi-coding-agent':
specifier: 1.5.2
version: 1.5.2(patch_hash=b1ad25365da34b5862e5263254f499e8c28a8344d66609110df5d2061c519bf9)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])