A desktop coding agent with free access to frontier models.
TypeScript
fix: sandbox chats on the new engine run in the box
ogsamratf73d352b2d76
diff --git a/apps/server/package.json b/apps/server/package.jsonindex 5a19f19b..3e5f2786 100644--- a/apps/server/package.json+++ b/apps/server/package.json@@ -12,7 +12,7 @@"test:coverage": "bun --conditions=development test --coverage --coverage-reporter=text --coverage-reporter=lcov --coverage-dir=coverage","test:artifacts": "bun --conditions=development test src/artifact-files.e2e.test.ts src/workspace-init.test.ts src/server.normalizeWorkspaceRelativePath.test.ts","build:enterprise-mcp-client": "pnpm --filter @omnirush/enterprise-mcp-client build",- "build": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && tsc -p tsconfig.json && node scripts/copy-mcp-allow.mjs && node scripts/copy-shared-modules.mjs && bun build src/opencode-plugins/managed-policy-next.ts src/opencode-plugins/omnirush-session-next.ts src/opencode-plugins/managed-policy.ts src/opencode-plugins/omnirush-chrome-devtools.ts src/opencode-plugins/omnirush-extensions-preview.ts src/opencode-plugins/omnirush-capabilities-knowledge.ts src/opencode-plugins/omnirush-office-attachments.ts src/opencode-plugins/omnirush-spreadsheets.ts src/opencode-plugins/omnirush-pdf-attachments.ts src/opencode-plugins/omnirush-anthropic-adaptive-thinking.ts src/opencode-plugins/omnirush-anthropic-tool-schema.ts src/opencode-plugins/omnirush-title-recovery.ts src/opencode-plugins/omnirush-reasoning-effort.ts src/opencode-plugins/omnirush-swarm.ts src/opencode-plugins/omnirush-budget-wrap.ts src/opencode-plugins/omnirush-mcp-policy.ts src/opencode-plugins/omnirush-box.ts src/opencode-plugins/omnirush-buildathon.ts src/opencode-plugins/omnirush-agent-assist.ts --root src/opencode-plugins --outdir dist/opencode-plugins --target node --format esm && node scripts/copy-pdfium-wasm.mjs dist/opencode-plugins",+ "build": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && tsc -p tsconfig.json && node scripts/copy-mcp-allow.mjs && node scripts/copy-shared-modules.mjs && bun build src/opencode-plugins/managed-policy-next.ts src/opencode-plugins/omnirush-session-next.ts src/opencode-plugins/managed-policy.ts src/opencode-plugins/omnirush-chrome-devtools.ts src/opencode-plugins/omnirush-extensions-preview.ts src/opencode-plugins/omnirush-capabilities-knowledge.ts src/opencode-plugins/omnirush-office-attachments.ts src/opencode-plugins/omnirush-spreadsheets.ts src/opencode-plugins/omnirush-pdf-attachments.ts src/opencode-plugins/omnirush-anthropic-adaptive-thinking.ts src/opencode-plugins/omnirush-anthropic-tool-schema.ts src/opencode-plugins/omnirush-title-recovery.ts src/opencode-plugins/omnirush-reasoning-effort.ts src/opencode-plugins/omnirush-swarm.ts src/opencode-plugins/omnirush-budget-wrap.ts src/opencode-plugins/omnirush-mcp-policy.ts src/opencode-plugins/omnirush-box.ts src/opencode-plugins/omnirush-box-next.ts src/opencode-plugins/omnirush-buildathon.ts src/opencode-plugins/omnirush-agent-assist.ts --root src/opencode-plugins --outdir dist/opencode-plugins --target node --format esm && node scripts/copy-pdfium-wasm.mjs dist/opencode-plugins","build:bin": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && bun build --compile src/cli.ts --outfile dist/bin/omnirush-server","build:bin:all": "pnpm --filter @omnirush/types build && pnpm build:enterprise-mcp-client && bun ./script/build.ts --outdir dist/bin --target bun-darwin-arm64 --target bun-darwin-x64 --target bun-linux-x64 --target bun-linux-arm64 --target bun-windows-x64 --target bun-windows-arm64","prepare:npm": "pnpm build:bin && node scripts/publish-npm.mjs --prepare-only",diff --git a/apps/server/src/engine-v2-preview.ts b/apps/server/src/engine-v2-preview.tsindex f71dc126..1a76912f 100644--- a/apps/server/src/engine-v2-preview.ts+++ b/apps/server/src/engine-v2-preview.ts@@ -29,6 +29,8 @@ import { engineDataDir } from "./engine-data-home.js";import { computerUseEngineEnv } from "./computer-use/desktop.js";import { engineV2Root, readMigratedSessions, seedV2StoreFromV1 } from "./engine-v2-migration.js";import type { ServerConfig } from "./types.js";+import { boxServiceFor } from "./box/desktop.js";+import { omnirushBoxNextPluginPath } from "./omnirush-extensions-plugin-path.js";const PREVIEW_STATE_FILE = "engine-v2-preview.json";const UNSET_API_KEY = "omnirush-engine-v2-preview-unset";@@ -150,6 +152,14 @@ async function resolveBinary(config: ServerConfig): Promise<ResolvedBinary> {return { bin, source: "env" };}+/**+ * The box's engine bits for the 2.x engine: the box shell as is, and the box plugin as its 2.x+ * module (omnirush-box-next.ts; the 1.x hook object it wraps is not loaded by 2.x). Null: no box.+ */+export function v2BoxBits(bits: { shell: string; plugin: string } | null): { shell: string; plugin: string } | null {+ return bits ? { shell: bits.shell, plugin: omnirushBoxNextPluginPath() } : null;+}+export function mapRuntimeProvidersToV2Specs(providerMap: Record<string, unknown>,storedCredentials: ReadonlyMap<string, string> = new Map(),@@ -531,6 +541,8 @@ export function createEngineV2Preview(options: { config: ServerConfig; env?: Pic},permissions: async () => executionRules((await readGlobalRuntimeOpencodeConfig(config)).managedPolicy?.execution),webSearch: () => webSearchSetting({ env: process.env, stateDir: runtimeStorageDir(config) }).enabled,+ // The Linux sandbox (box/): the shell and box plugin follow BoxService.engineBits on every config write.+ box: async () => v2BoxBits(await boxServiceFor(config).engineBits()),mcpGate: v2McpGate(runtimeStorageDir(config), { ...process.env, ...computerUseEngineEnv(runtimeStorageDir(config)) }, Boolean(await cloudConnector())),});sidecar = managed;diff --git a/apps/server/src/managed-opencode-v2.env.test.ts b/apps/server/src/managed-opencode-v2.env.test.tsindex 670d2394..0b68831c 100644--- a/apps/server/src/managed-opencode-v2.env.test.ts+++ b/apps/server/src/managed-opencode-v2.env.test.ts@@ -2,6 +2,10 @@ import { expect, test } from "bun:test";import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";+import { pathToFileURL } from "node:url";++import { v2BoxBits } from "./engine-v2-preview.js";+import { omnirushBoxNextPluginPath } from "./omnirush-extensions-plugin-path.js";import { assertEngineGates, createManagedOpencodeV2Server, engineV2SpawnEnv } from "./managed-opencode-v2.js";@@ -64,3 +68,30 @@ posix("the stock websearch tool searches through Exa only while the server's swiawait rm(dir, { recursive: true, force: true });}});++posix("the 2.x engine runs the box shell and the 2.x box plugin while a workspace's box is on, and neither when it is off", async () => {+ const dir = await mkdtemp(join(tmpdir(), "v2-box-"));+ try {+ const bin = join(dir, "fake-v2");+ await writeFile(bin, "#!/bin/sh\nexit 3\n");+ await chmod(bin, 0o755);+ const shell = join(dir, "box", "shell-desktop", "bash");+ // BoxService.engineBits as the server hands it over (a 1.x plugin file), mapped for the 2.x engine.+ const engineBits = { shell, plugin: join(dir, "omnirush-box.ts") };+ expect(v2BoxBits(engineBits)).toEqual({ shell, plugin: omnirushBoxNextPluginPath() });+ expect(v2BoxBits(null)).toBeNull();+ for (const on of [true, false]) {+ const rootDir = join(dir, String(on));+ await createManagedOpencodeV2Server({ bin, rootDir, bootTimeoutMs: 5_000, box: async () => v2BoxBits(on ? engineBits : null) })+ .then((server) => server.close(), () => undefined);+ const config = JSON.parse(await readFile(join(rootDir, "config", "opencode.json"), "utf8"));+ expect(config.shell).toEqual(on ? shell : undefined);+ // 2.x loads plugins from directories: the box one re-exports omnirush-box-next.+ const boxDirs = (config.plugins as string[]).filter((entry) => entry.endsWith("omnirush-box-next"));+ expect(boxDirs.length).toBe(on ? 1 : 0);+ if (on) expect(await readFile(join(boxDirs[0]!, "server.js"), "utf8")).toContain(pathToFileURL(omnirushBoxNextPluginPath()).href);+ }+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});diff --git a/apps/server/src/managed-opencode-v2.ts b/apps/server/src/managed-opencode-v2.tsindex 3d66d308..75e47526 100644--- a/apps/server/src/managed-opencode-v2.ts+++ b/apps/server/src/managed-opencode-v2.ts@@ -45,6 +45,8 @@ export interface ManagedOpencodeV2ServerOptions {webSearch?: () => boolean;/** The MCP servers the engine's gate allows (engine-v2-mcp.ts); none when absent. */mcpGate?: string[];+ /** The Linux sandbox's engine bits (engine-v2-preview.ts v2BoxBits): the box shell and the 2.x box plugin; null: none. */+ box?: () => Promise<{ shell: string; plugin: string } | null>;}export interface OpencodeV2Health {@@ -139,7 +141,7 @@ export async function createManagedOpencodeV2Server(// cloud, database, or control-plane credentials. Unknown keys stay private.const inherited: Record<string, string> = {};for (const key of [- "OMNIRUSH_SERVER_URL", "OMNIRUSH_POLICY_TOKEN", "OMNIRUSH_ACCESS_TOKEN",+ "OMNIRUSH_SERVER_URL", "OMNIRUSH_POLICY_TOKEN", "OMNIRUSH_ACCESS_TOKEN", "OMNIRUSH_BOX_HOME","PATH", "HOME", "USER", "LOGNAME", "SHELL", "TMPDIR", "TMP", "TEMP","LANG", "LC_ALL", "LC_CTYPE", "TZ", "TERM", "CI","XDG_CACHE_HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_RUNTIME_DIR",@@ -288,6 +290,8 @@ export async function createManagedOpencodeV2Server(};}const target = join(configDir, "opencode.json");+ // The box shell runs each command in its project's box (boxsh; natively for a project without one).+ const box = await options.box?.().catch(() => null) ?? null;await writeFileAtomic(target, `${JSON.stringify({$schema: "https://opencode.ai/config.json",// No session sharing to an outside service; the bundled engine never replaces itself.@@ -305,7 +309,8 @@ export async function createManagedOpencodeV2Server(// Off: no provider is picked (never `false`, which would take the tool out of the stock list).// shortcut: Exa until the gateway serves a search integration of its own....(options.webSearch?.() ? { websearch: { provider: "exa" } } : {}),- plugins: await pluginDirectories(join(options.rootDir, "plugins"), [sessionNextPluginPath(), ...(options.env?.OMNIRUSH_SERVER_URL ? [managedPolicyPluginPath(true)] : [])]),+ ...(box ? { shell: box.shell } : {}),+ plugins: await pluginDirectories(join(options.rootDir, "plugins"), [sessionNextPluginPath(), ...(options.env?.OMNIRUSH_SERVER_URL ? [managedPolicyPluginPath(true)] : []), ...(box ? [box.plugin] : [])]),}, null, 2)}\n`, { mode: 0o600 });}diff --git a/apps/server/src/omnirush-extensions-plugin-path.ts b/apps/server/src/omnirush-extensions-plugin-path.tsindex e1c8d7d9..1f94f3ad 100644--- a/apps/server/src/omnirush-extensions-plugin-path.ts+++ b/apps/server/src/omnirush-extensions-plugin-path.ts@@ -32,6 +32,8 @@ export function omnirushPluginPath(name: string, here?: string): string {}export const omnirushExtensionsPreviewPluginPath = () => omnirushPluginPath("omnirush-extensions-preview");+/** The box plugin on the 2.x engine (opencode-plugins/omnirush-box-next.ts). */+export const omnirushBoxNextPluginPath = () => omnirushPluginPath("omnirush-box-next");export const omnirushChromeDevtoolsPluginPath = () => omnirushPluginPath("omnirush-chrome-devtools");export const omnirushCapabilitiesKnowledgePluginPath = () => omnirushPluginPath("omnirush-capabilities-knowledge");export const omnirushAnthropicAdaptiveThinkingPluginPath = () => omnirushPluginPath("omnirush-anthropic-adaptive-thinking");diff --git a/apps/server/src/opencode-plugins/omnirush-box-next.test.ts b/apps/server/src/opencode-plugins/omnirush-box-next.test.tsnew file mode 100644index 00000000..a96588f0--- /dev/null+++ b/apps/server/src/opencode-plugins/omnirush-box-next.test.ts@@ -0,0 +1,82 @@+import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";++import { BOX_HEADER } from "../model-modes/model-modes.mjs";+import { keyOf } from "../box/plugin-lib.js";+import plugin from "./omnirush-box-next.js";++type Hook = (event: any) => Promise<void>;+let dir = "";+let savedHome: string | undefined;++beforeEach(() => {+ dir = mkdtempSync(path.join(tmpdir(), "box-next-"));+ savedHome = process.env.OMNIRUSH_BOX_HOME;+ process.env.OMNIRUSH_BOX_HOME = path.join(dir, "box");+});+afterEach(() => {+ if (savedHome === undefined) delete process.env.OMNIRUSH_BOX_HOME;+ else process.env.OMNIRUSH_BOX_HOME = savedHome;+ rmSync(dir, { recursive: true, force: true });+});++/** A project folder whose box the desktop lists (on) or not, with its running record. */+function project(on: boolean): { root: string; key: string } {+ const root = path.join(dir, "proj");+ mkdirSync(root, { recursive: true });+ const key = keyOf(root);+ mkdirSync(path.join(dir, "box", "boxes"), { recursive: true });+ writeFileSync(path.join(dir, "box", "boxes", `${key}.json`), JSON.stringify({ state: "running", uid: 0 }));+ writeFileSync(path.join(dir, "box", "desktop-projects.json"), JSON.stringify({ keys: on ? [key] : [], pkglog_dir: path.join(dir, "pkglog") }));+ return { root, key };+}++/** The 2.x plugin set up the way the engine does it: one instance per project folder. */+async function engine(root: string) {+ const hooks = new Map<string, Hook>();+ const hook = async (name: string, callback: Hook) => { hooks.set(name, callback); };+ await plugin.setup({+ location: { directory: root },+ session: { get: async () => ({ data: {} }), hook } as any,+ shell: { hook: (name: string, callback: Hook) => hook(`shell:${name}`, callback) } as any,+ tool: { hook: (name: string, callback: Hook) => hook(`tool:${name}`, callback) } as any,+ });+ return hooks;+}++test("a box chat's shell calls carry its box key and chat, its requests say box, the prompt names the sandbox", async () => {+ const { root, key } = project(true);+ const hooks = await engine(root);+ await hooks.get("tool:execute.before")!({ tool: "shell", id: "call_1", sessionID: "ses_a", input: { command: "hostname" } });+ const shell = { command: "hostname", cwd: root, env: { PATH: "/usr/bin" } as Record<string, string | undefined> };+ await hooks.get("shell:create.before")!(shell);+ // boxsh (the engine's shell) runs the command in the box named by OMNIRUSH_BOX_KEY.+ expect(shell.env).toMatchObject({ OMNIRUSH_BOX_KEY: key, OMNIRUSH_CALL: "call_1", OMNIRUSH_SESSION: "ses_a", PATH: "/usr/bin" });+ const request = { sessionID: "ses_a", headers: {} as Record<string, string> };+ await hooks.get("model.request")!(request);+ expect(request.headers[BOX_HEADER]).toBe("1");+ const context = { sessionID: "ses_a", system: ["Platform: darwin", { type: "text", text: "rules" }] as unknown[] };+ await hooks.get("context")!(context);+ expect(context.system[0]).toBe("Platform: linux");+ expect(context.system[1]).toEqual({ type: "text", text: "rules" });+ expect(JSON.stringify(context.system.at(-1))).toContain("Sandbox: shell commands run in a Linux");+ // File tools stay in the project folder: the rest is the box's.+ await expect(hooks.get("tool:execute.before")!({ tool: "read", id: "call_2", sessionID: "ses_a", input: { filePath: "/etc/hostname" } })).rejects.toThrow(/outside the project folder/);+});++test("a project whose box is off is left alone: no box key, no box header, no note", async () => {+ const { root } = project(false);+ const hooks = await engine(root);+ await hooks.get("tool:execute.before")!({ tool: "shell", id: "call_1", sessionID: "ses_b", input: { command: "hostname" } });+ const shell = { command: "hostname", cwd: root, env: {} as Record<string, string | undefined> };+ await hooks.get("shell:create.before")!(shell);+ expect(shell.env.OMNIRUSH_BOX_KEY).toBeUndefined();+ const request = { sessionID: "ses_b", headers: {} as Record<string, string> };+ await hooks.get("model.request")!(request);+ expect(request.headers[BOX_HEADER]).toBeUndefined();+ const context = { sessionID: "ses_b", system: ["Platform: darwin"] as unknown[] };+ await hooks.get("context")!(context);+ expect(context.system).toEqual(["Platform: darwin"]);+});diff --git a/apps/server/src/opencode-plugins/omnirush-box-next.ts b/apps/server/src/opencode-plugins/omnirush-box-next.tsnew file mode 100644index 00000000..1bd00ea9--- /dev/null+++ b/apps/server/src/opencode-plugins/omnirush-box-next.ts@@ -0,0 +1,90 @@+// 2.x engine plugin ({id, setup(ctx)}): the box plugin (omnirush-box.ts, a 1.x+// hook object, kept in step with the CLI's) on the 2.x plugin API, as the+// CLI's bridge plugin (omnirush-cli assets/engine-v2-plugin) registers it:+// shell.env -> shell "create.before" (env)+// tool.execute.before -> tool "execute.before"+// chat.headers -> session "model.request" (headers)+// experimental.chat.system.transform -> session "context" (system parts)+// The engine's shell is the box shell (opencode.json `shell`); a project+// whose box is off is left alone by the box plugin itself.++import { OmniRushBox } from "./omnirush-box.js";++export const OMNIRUSH_BOX_PLUGIN_ID = "omnirush.box";++type ShellEvent = { command?: string; cwd?: string; env: Record<string, string | undefined> };+type ToolEvent = { tool: string; id?: string; sessionID?: string; input?: unknown };+type HeadersEvent = { sessionID: string; headers: Record<string, string> };+type ContextEvent = { sessionID: string; model?: unknown; system?: unknown };+type Ctx = {+ location?: { directory?: string };+ session: {+ get(input: { sessionID: string }): Promise<unknown>;+ hook(name: "model.request", callback: (event: HeadersEvent) => Promise<void>): Promise<unknown>;+ hook(name: "context", callback: (event: ContextEvent) => Promise<void>): Promise<unknown>;+ };+ shell: { hook(name: "create.before", callback: (event: ShellEvent) => Promise<void>): Promise<unknown> };+ tool: { hook(name: "execute.before", callback: (event: ToolEvent) => Promise<void>): Promise<unknown> };+};++/** A system part's text (a string or { type: "text", text }), else null. */+function systemText(part: unknown): string | null {+ if (typeof part === "string") return part;+ return part && typeof part === "object" && typeof (part as { text?: unknown }).text === "string" ? (part as { text: string }).text : null;+}++export default {+ id: OMNIRUSH_BOX_PLUGIN_ID,+ async setup(ctx: Ctx) {+ // The 1.x client call the box plugin makes: a chat's parent (sub-agents keep their top chat's box).+ const client = {+ session: {+ get: async ({ path: where }: { path: { id: string } }) => {+ const found = await ctx.session.get({ sessionID: where.id }) as { data?: unknown } | undefined;+ const info = (found && typeof found === "object" && "data" in found ? found.data : found) as { parentID?: string } | null | undefined;+ return { data: info ?? null };+ },+ },+ };+ const hooks = await OmniRushBox({ directory: ctx.location?.directory ?? process.cwd(), client });+ // The 2.x shell hook names no call: execute.before sees the shell call (and its chat) first.+ // shortcut: keyed by command text, two identical commands at once share one id; upgrade when 2.x passes the call id.+ const calls = new Map<string, { callID: string; sessionID: string }>();++ await ctx.tool.hook("execute.before", async (event) => {+ const args = (event.input && typeof event.input === "object" ? event.input : {}) as Record<string, unknown>;+ if (event.tool === "shell" && typeof args.command === "string") {+ calls.set(args.command, { callID: String(event.id ?? ""), sessionID: String(event.sessionID ?? "") });+ if (calls.size > 256) calls.delete(calls.keys().next().value as string);+ }+ await hooks["tool.execute.before"]({ tool: event.tool, sessionID: event.sessionID }, { args });+ event.input = args;+ });++ await ctx.shell.hook("create.before", async (event) => {+ const { callID, sessionID } = calls.get(event.command ?? "") ?? { callID: "", sessionID: "" };+ const output = { env: event.env as Record<string, string> };+ await hooks["shell.env"]({ callID, sessionID }, output);+ event.env = output.env;+ });++ await ctx.session.hook("model.request", async (event) => {+ await hooks["chat.headers"]({ sessionID: event.sessionID }, { headers: event.headers });+ });++ await ctx.session.hook("context", async (event) => {+ if (!Array.isArray(event.system)) return;+ const parts = event.system as unknown[];+ const output = { system: parts.map(systemText).filter((text): text is string => text !== null) };+ const before = output.system.length;+ await hooks["experimental.chat.system.transform"]({ sessionID: event.sessionID }, output);+ let i = 0;+ event.system = parts.map((part) => {+ if (systemText(part) === null) return part;+ const text = output.system[i++];+ return typeof part === "string" ? text : { ...(part as object), text };+ });+ for (const extra of output.system.slice(before)) (event.system as unknown[]).push({ type: "text", text: extra });+ });+ },+};diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex bb1e043e..a2606ca0 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -1567,6 +1567,7 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {if (config.workspaces.length > 0) cloudProviderSync.markReloadPending();};const engineV2Preview = createEngineV2Preview({ config, env, deferStart: true });+ engineV2Refreshers.set(config, () => engineV2Preview.refreshProviders());engineV2ByServer.set(config, engineV2Preview);/** A chat on the 2.x engine, read where it lives (its folder), or null. */const v2ChatTarget = async (sessionId: string): Promise<EngineTarget | null> => {@@ -3462,12 +3463,17 @@ async function applyServerBoxDefault(config: ServerConfig, boxes: ReturnType<typvoid boxes.prefetch().catch(() => false);}+/** Each server's 2.x engine config rewrite (engine-v2-preview.ts refreshProviders), for applyBoxEngineConfig. */+const engineV2Refreshers = new WeakMap<ServerConfig, () => Promise<void>>();+/*** The Linux sandbox's engine bits (box/service.ts engineBits) may have* changed: the engine config file is written again and, when it changed,* the managed engine rolls over to it (as for a best-practices change).*/async function applyBoxEngineConfig(config: ServerConfig, reason: string, options: { restart?: boolean } = {}): Promise<{ status: "unchanged" | "applied" | "deferred" | "failed" | "unmanaged" }> {+ // The 2.x engine (every chat) gets the same bits through its own config file, written again here.+ await engineV2Refreshers.get(config)?.().catch(() => undefined);try {const written = await writeOmniRushRuntimeConfigFile(config);// `restart`: the engine's environment changed too (the provider lock), so a new engine even when the file did not.