Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: the app ships the new engine and runs chats on it

ogsamrat628a94b19635
diff --git a/apps/desktop/electron/runtime.mjs b/apps/desktop/electron/runtime.mjs
index 3fe330c7..be38416f 100644
--- a/apps/desktop/electron/runtime.mjs
+++ b/apps/desktop/electron/runtime.mjs
@@ -2151,6 +2151,13 @@ export function createRuntimeManager({
const host = options.remoteAccessEnabled ? "0.0.0.0" : "127.0.0.1";
const managedOpencode = options.manageOpencode ? resolveOpencodeBinary(options.opencodeBinPath) : null;
+ // The 2.x engine every new chat runs on (engine-v2-preview.ts reads it): a release
+ // runs only its bundled, hash-checked copy; a dev build may name another one.
+ if (isReleaseBuild()) process.env.OMNIRUSH_OPENCODE2_BIN = releaseEngineBinary({ fileNames: binaryFileNames("opencode2") }).path;
+ else if (!process.env.OMNIRUSH_OPENCODE2_BIN?.trim()) {
+ const bundledV2 = resolveBinaryInfo("opencode2");
+ if (bundledV2) process.env.OMNIRUSH_OPENCODE2_BIN = bundledV2.path;
+ }
omnirushServerState.managedOpencodeBinPath = managedOpencode?.path ?? null;
omnirushServerState.managedOpencodeBinSource = managedOpencode?.source ?? null;
if (options.manageOpencode) {
diff --git a/apps/desktop/scripts/check-packaged-engine.mjs b/apps/desktop/scripts/check-packaged-engine.mjs
index 6a57663a..ce0c7694 100644
--- a/apps/desktop/scripts/check-packaged-engine.mjs
+++ b/apps/desktop/scripts/check-packaged-engine.mjs
@@ -18,7 +18,7 @@ if (build.variant !== "release") fail(`expected a release build, found "${build.
if (!build.engineSha256) fail("the build records no engine sha256");
const sidecars = path.join(resources, "sidecars");
-const engines = readdirSync(sidecars).filter((name) => /^opencode(?:-[a-z0-9_-]+)?(?:\.exe)?$/.test(name) && !/^opencode-v\d|^opencode2/.test(name));
+const engines = readdirSync(sidecars).filter((name) => /^opencode2?(?:-[a-z0-9_-]+)?(?:\.exe)?$/.test(name));
if (!engines.length) fail(`no bundled engine in ${sidecars}`);
const guard = await import(pathToFileURL(path.join(asar, "server", "dist", "release-guard.js")).href);
diff --git a/apps/desktop/scripts/electron-after-pack.cjs b/apps/desktop/scripts/electron-after-pack.cjs
index bd252dc5..2e947775 100644
--- a/apps/desktop/scripts/electron-after-pack.cjs
+++ b/apps/desktop/scripts/electron-after-pack.cjs
@@ -9,6 +9,7 @@ const computerUseHelperAppName = "OmniRush.ai Computer Use.app";
const sidecarBases = [
"opencode",
+ "opencode2",
];
function targetTriple(platformName, arch) {
diff --git a/apps/desktop/scripts/electron-build.mjs b/apps/desktop/scripts/electron-build.mjs
index 01eeeafa..c35742b0 100644
--- a/apps/desktop/scripts/electron-build.mjs
+++ b/apps/desktop/scripts/electron-build.mjs
@@ -49,6 +49,7 @@ function writeSentryBuildConfig() {
}
run(nodeCmd, [resolve(__dirname, "prepare-sidecar.mjs"), "--force", "--outdir", electronSidecarDir], desktopRoot);
+run(nodeCmd, [resolve(__dirname, "prepare-sidecar.mjs"), "--force", "--engine", "v2", "--outdir", electronSidecarDir], desktopRoot);
run(nodeCmd, [resolve(__dirname, "prepare-computer-use-helper.mjs"), "--force", "--outdir", electronHelperDir], desktopRoot);
run(nodeCmd, [resolve(__dirname, "prepare-runtime-node-modules.mjs"), "--outdir", packagedRuntimeRoot], desktopRoot);
// The built-in UI-control MCP ships inside the app as one bundled module and
diff --git a/apps/desktop/scripts/electron-dev.mjs b/apps/desktop/scripts/electron-dev.mjs
index a80cea60..12f2ad78 100644
--- a/apps/desktop/scripts/electron-dev.mjs
+++ b/apps/desktop/scripts/electron-dev.mjs
@@ -231,6 +231,7 @@ process.once("SIGTERM", () => void stopAll(143));
if (process.env.OMNIRUSH_ELECTRON_SKIP_SHARED_PREPARE !== "1") {
runSync(nodeCmd, [resolve(__dirname, "prepare-sidecar.mjs"), "--force", "--outdir", electronSidecarDir], { cwd: desktopRoot });
+ runSync(nodeCmd, [resolve(__dirname, "prepare-sidecar.mjs"), "--force", "--engine", "v2", "--outdir", electronSidecarDir], { cwd: desktopRoot });
runSync(nodeCmd, [resolve(__dirname, "prepare-computer-use-helper.mjs"), "--force", "--outdir", electronHelperDir], { cwd: desktopRoot });
}
diff --git a/apps/desktop/scripts/engine-v2-release.json b/apps/desktop/scripts/engine-v2-release.json
new file mode 100644
index 00000000..3ddc3b62
--- /dev/null
+++ b/apps/desktop/scripts/engine-v2-release.json
@@ -0,0 +1,36 @@
+{
+ "repo": "omnirush-ai/omnirush-gui",
+ "tag": "engine-2.0.32-r2",
+ "version": "2.0.32",
+ "origin": "OmniRush.ai's build of OpenCode 2.0.32 (engine-2.0.32-r2, the archives the CLI pins), copied to a public pre-release of this repo that is never marked latest. Until it is uploaded, set OMNIRUSH_ENGINE_ARCHIVE_DIR to a folder holding these archives.",
+ "license": {
+ "name": "LICENSE-opencode-MIT",
+ "sha256": "625f0f619133f89bbbb2abe37369613dfa1885eba1e50d02170deb62bb42cb6b"
+ },
+ "assets": {
+ "aarch64-apple-darwin": {
+ "name": "omnirush-engine-darwin-arm64-2.0.32.tar.gz",
+ "sha256": "f4a968d5c07703a49c64427bd0632707b0c0151a9c78a8f7382626bc2aec0d49"
+ },
+ "x86_64-apple-darwin": {
+ "name": "omnirush-engine-darwin-x64-2.0.32.tar.gz",
+ "sha256": "f7a008de7c170e2917918a8647b027ed9f6a4eaadee289b05ce9b82385122e24"
+ },
+ "x86_64-unknown-linux-gnu": {
+ "name": "omnirush-engine-linux-x64-2.0.32.tar.gz",
+ "sha256": "b1cfaf8d6f260671d92d45082b73f0b6a675824a5cce9fab533c56038d2b5b58"
+ },
+ "aarch64-unknown-linux-gnu": {
+ "name": "omnirush-engine-linux-arm64-2.0.32.tar.gz",
+ "sha256": "2a3279dc0610009042aa262577caf9876041a7c30ea456073f67adf4091bc1e6"
+ },
+ "x86_64-pc-windows-msvc": {
+ "name": "omnirush-engine-win32-x64-2.0.32.tar.gz",
+ "sha256": "918699dd8e9faaf965fa9463f4ff656bce03abbe40ef27805bb0134df1705c14"
+ },
+ "aarch64-pc-windows-msvc": {
+ "name": "omnirush-engine-win32-arm64-2.0.32.tar.gz",
+ "sha256": "26a2a867481d603bd7be781471362ae9ed3cc9fbed68629848c5dd260d248066"
+ }
+ }
+}
diff --git a/apps/desktop/scripts/packaged-smoke.mjs b/apps/desktop/scripts/packaged-smoke.mjs
index 6ec06a4f..82073a28 100644
--- a/apps/desktop/scripts/packaged-smoke.mjs
+++ b/apps/desktop/scripts/packaged-smoke.mjs
@@ -47,6 +47,9 @@ try {
throw new Error("Packaged sidecar unexpectedly contains the generic opencode alias");
}
run("sidecar", sidecar, ["--version"], 10_000, {}, output);
+ const sidecarV2 = join(resources, `sidecars/opencode2-${targetTriple}`);
+ accessSync(sidecarV2, constants.X_OK);
+ run("sidecar-v2", sidecarV2, ["--version"], 10_000, {}, output);
const embedded = pathToFileURL(join(archive, "server/dist/embedded.js")).href;
run("server-import", binary, ["--input-type=module", "-e",
`const server = await import(${JSON.stringify(embedded)}); if (typeof server.startEmbeddedServer !== "function") throw new Error("Missing embedded server export");`],
diff --git a/apps/desktop/scripts/prepare-sidecar.mjs b/apps/desktop/scripts/prepare-sidecar.mjs
index ff2cfbb3..1d6f2f95 100644
--- a/apps/desktop/scripts/prepare-sidecar.mjs
+++ b/apps/desktop/scripts/prepare-sidecar.mjs
@@ -29,6 +29,8 @@ const readArg = (name) => {
};
const sidecarOverride = process.env.OMNIRUSH_SIDECAR_DIR?.trim() || readArg("--outdir");
+// `--engine v2`: the OpenCode 2.x engine (engine-v2-release.json) beside the 1.x one, as `opencode2-<triple>`.
+const engineV2 = readArg("--engine") === "v2";
const sidecarDir = sidecarOverride ? resolve(sidecarOverride) : join(__dirname, "..", "resources", "sidecars");
const constantsPath = resolve(__dirname, "..", "..", "..", "constants.json");
@@ -36,7 +38,8 @@ const opencodeVersion = (() => {
try {
const raw = readFileSync(constantsPath, "utf8");
const parsed = JSON.parse(raw);
- return typeof parsed.opencodeVersion === "string" ? parsed.opencodeVersion.trim() || null : null;
+ const pinned = engineV2 ? parsed.opencodeV2Version : parsed.opencodeVersion;
+ return typeof pinned === "string" ? pinned.trim() || null : null;
} catch {
return null;
}
@@ -53,7 +56,7 @@ const normalizeVersion = (value) => {
// bundles): per-platform tarballs on a public pre-release of this repo (never
// marked latest), sha256-pinned in engine-release.json. No token is needed.
// Each tarball holds one executable, `opencode[.exe]`, at its root.
-const engineReleasePath = resolve(__dirname, "engine-release.json");
+const engineReleasePath = resolve(__dirname, engineV2 ? "engine-v2-release.json" : "engine-release.json");
const engineRelease = JSON.parse(readFileSync(engineReleasePath, "utf8"));
// Target triple for native platform binaries
@@ -76,10 +79,11 @@ const resolvedTargetTriple = (() => {
})();
const isWindowsTarget = process.platform === "win32" || resolvedTargetTriple?.includes("windows") === true;
-const opencodeBaseName = isWindowsTarget ? "opencode.exe" : "opencode";
+const engineBase = engineV2 ? "opencode2" : "opencode";
+const opencodeBaseName = isWindowsTarget ? `${engineBase}.exe` : engineBase;
const opencodePath = join(sidecarDir, opencodeBaseName);
const opencodeTargetName = resolvedTargetTriple
- ? `opencode-${resolvedTargetTriple}${isWindowsTarget ? ".exe" : ""}`
+ ? `${engineBase}-${resolvedTargetTriple}${isWindowsTarget ? ".exe" : ""}`
: null;
const opencodeTargetPath = opencodeTargetName ? join(sidecarDir, opencodeTargetName) : null;
@@ -230,7 +234,7 @@ const readRecordedEngine = () => {
for (const name of names.filter(Boolean)) {
try {
const parsed = JSON.parse(readFileSync(join(sidecarDir, name), "utf8"));
- if (parsed?.opencode) return parsed.opencode;
+ if (parsed?.[engineBase]) return parsed[engineBase];
} catch {
// not recorded
}
@@ -279,8 +283,14 @@ const readEngineArchive = async () => {
}
return bytes;
};
- const local = process.env.OMNIRUSH_ENGINE_ARCHIVE?.trim();
+ const local = engineV2 ? null : process.env.OMNIRUSH_ENGINE_ARCHIVE?.trim();
if (local) return verify(readFileSync(resolve(local)), local);
+ // A folder of release archives not uploaded yet (either engine; only its own asset name is read).
+ const localDir = process.env.OMNIRUSH_ENGINE_ARCHIVE_DIR?.trim();
+ if (localDir && existsSync(join(resolve(localDir), engineAsset.name))) {
+ const file = join(resolve(localDir), engineAsset.name);
+ return verify(readFileSync(file), file);
+ }
const cacheDir = process.env.OMNIRUSH_ENGINE_CACHE?.trim()
? resolve(process.env.OMNIRUSH_ENGINE_CACHE.trim())
: join(homedir(), ".cache", "omnirush-desktop", "engine");
@@ -381,8 +391,17 @@ const omnirushServerVersion = (() => {
}
})();
+// One versions.json for both engines: each run updates its own entry.
+const previousVersions = (() => {
+ try {
+ return JSON.parse(readFileSync(join(sidecarDir, "versions.json"), "utf8"));
+ } catch {
+ return {};
+ }
+})();
const versions = {
- opencode: {
+ ...(engineV2 ? previousVersions : previousVersions.opencode2 ? { opencode2: previousVersions.opencode2 } : {}),
+ [engineBase]: {
version: normalizedOpencodeVersion,
sha256: opencodeCandidatePath && existsSync(opencodeCandidatePath) ? sha256File(opencodeCandidatePath) : null,
release: engineRelease.tag,
@@ -420,7 +439,7 @@ try {
// The Linux sandbox's helpers (boxsh, boxd) beside the engine: optional, never fatal.
try {
- await import("./prepare-box-helpers.mjs");
+ if (!engineV2) await import("./prepare-box-helpers.mjs");
} catch (error) {
console.warn(`Sandbox helpers not prepared: ${error instanceof Error ? error.message : String(error)}`);
}
diff --git a/apps/desktop/scripts/stamp-build-variant.mjs b/apps/desktop/scripts/stamp-build-variant.mjs
index 022d2b95..757359b3 100644
--- a/apps/desktop/scripts/stamp-build-variant.mjs
+++ b/apps/desktop/scripts/stamp-build-variant.mjs
@@ -15,12 +15,13 @@ export function desktopVariant(env = process.env) {
/**
* The sha256 of each bundled engine binary, comma-separated in sorted order.
* A macOS build bundles one engine per architecture (arm64 and x64): each is
- * recorded, and a release runs only a binary with one of these hashes.
+ * recorded, as is the 2.x engine (opencode2) beside the 1.x one, and a
+ * release runs only a binary with one of these hashes.
*/
export function bundledEngineSha256(sidecarDir) {
- const names = existsSync(sidecarDir) ? readdirSync(sidecarDir).filter((name) => /^opencode(?:-[a-z0-9_-]+)?(?:\.exe)?$/.test(name)) : [];
+ const names = existsSync(sidecarDir) ? readdirSync(sidecarDir).filter((name) => /^opencode2?(?:-[a-z0-9_-]+)?(?:\.exe)?$/.test(name)) : [];
const hashes = [...new Set(names.map((name) => createHash("sha256").update(readFileSync(join(sidecarDir, name))).digest("hex")))].sort();
- if (hashes.length < 1 || hashes.length > 4) throw new Error(`Expected one engine per architecture in ${sidecarDir}, found ${names.length} file(s) with ${hashes.length} different content(s)`);
+ if (hashes.length < 1 || hashes.length > 8) throw new Error(`Expected one engine per architecture in ${sidecarDir}, found ${names.length} file(s) with ${hashes.length} different content(s)`);
return hashes.join(",");
}
diff --git a/apps/server/package.json b/apps/server/package.json
index 6c00b5eb..5a19f19b 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/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-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-gates/PARITY.sha256 b/apps/server/src/engine-gates/PARITY.sha256
new file mode 100644
index 00000000..5ba8b5e5
--- /dev/null
+++ b/apps/server/src/engine-gates/PARITY.sha256
@@ -0,0 +1 @@
+c45407012c8a3776f5ad36937233cc7170e0c3016c81c7781fc3dc416df6f63c engine-gates.mjs
diff --git a/apps/server/src/engine-gates/engine-gates.d.mts b/apps/server/src/engine-gates/engine-gates.d.mts
new file mode 100644
index 00000000..bcf74674
--- /dev/null
+++ b/apps/server/src/engine-gates/engine-gates.d.mts
@@ -0,0 +1,2 @@
+// Types of engine-gates.mjs (shared with omnirush-cli byte for byte; PARITY.sha256 covers the .mjs).
+export function gateEnv(options?: { provider?: string; mcp?: readonly string[] }): Record<string, string>;
diff --git a/apps/server/src/engine-gates/engine-gates.mjs b/apps/server/src/engine-gates/engine-gates.mjs
new file mode 100644
index 00000000..c4af4215
--- /dev/null
+++ b/apps/server/src/engine-gates/engine-gates.mjs
@@ -0,0 +1,39 @@
+// Shared by omnirush-cli and omnirush-gui, byte for byte (PARITY.sha256). Engine: omnirush fork of opencode 2.0.32.
+//
+// Env for the engine process that turns on the engine's gates (fork patches 0003, 0004, 0005):
+// - Provider lock and MCP fail-closed: OMNIRUSH_GATE_PROVIDERS / OMNIRUSH_GATE_MCP. The engine core turns
+// them into policies evaluated after every config layer (system, global, OPENCODE_CONFIG, project,
+// OPENCODE_CONFIG_CONTENT), so no config file can outrank them, and a missing or invalid config file
+// cannot drop them. With the gate on, an empty or malformed list denies everything.
+// - Project code: the engine drops plugins, shell, formatter, lsp, mcp, providers, update, share, websearch,
+// agent request overlays and .opencode/plugin(s) from project config unless OMNIRUSH_PROJECT_CODE=1
+// (a user opt-in; this module never sets it).
+// - Isolation from a stock opencode setup: OMNIRUSH_NO_SYSTEM_CONFIG skips /etc/opencode,
+// /Library/Application Support/opencode, %ProgramData%\opencode, the ai.opencode.managed.plist MDM file and
+// the home-level ~/.claude and ~/.agents skill dirs (project .claude/.agents still load).
+// - Models fetch off (OPENCODE_DISABLE_MODELS_FETCH).
+//
+// Merge the result over the user's env (spread it last). Define the gateway provider and the allowed MCP
+// servers in the app's own config (OPENCODE_CONFIG_DIR or OPENCODE_CONFIG), never through
+// OPENCODE_CONFIG_CONTENT: that layer ranks below project files.
+
+const NAME = /^[A-Za-z0-9_.-]+$/
+
+/**
+ * @param {{ provider?: string, mcp?: readonly string[] }} [options]
+ * @returns {Record<string, string>}
+ */
+export function gateEnv(options = {}) {
+ const provider = options.provider ?? "omnirush"
+ const mcp = options.mcp ?? []
+ // A wildcard or separator in a name would widen or split a rule; refuse instead of guessing.
+ for (const item of [provider, ...mcp]) {
+ if (typeof item !== "string" || !NAME.test(item)) throw new Error(`engine gate: invalid name ${JSON.stringify(item)}`)
+ }
+ return {
+ OMNIRUSH_GATE_PROVIDERS: provider,
+ OMNIRUSH_GATE_MCP: mcp.join(","),
+ OMNIRUSH_NO_SYSTEM_CONFIG: "1",
+ OPENCODE_DISABLE_MODELS_FETCH: "1",
+ }
+}
diff --git a/apps/server/src/engine-gates/engine-gates.test.mjs b/apps/server/src/engine-gates/engine-gates.test.mjs
new file mode 100644
index 00000000..fe9fd881
--- /dev/null
+++ b/apps/server/src/engine-gates/engine-gates.test.mjs
@@ -0,0 +1,26 @@
+import { test } from "node:test"
+import assert from "node:assert/strict"
+import { gateEnv } from "./engine-gates.mjs"
+
+test("gateway provider and listed MCP servers only, models fetch off", () => {
+ assert.deepEqual(gateEnv({ mcp: ["figma", "computer-use"] }), {
+ OMNIRUSH_GATE_PROVIDERS: "omnirush",
+ OMNIRUSH_GATE_MCP: "figma,computer-use",
+ OMNIRUSH_NO_SYSTEM_CONFIG: "1",
+ OPENCODE_DISABLE_MODELS_FETCH: "1",
+ })
+})
+
+test("no MCP list means no MCP server, and the gate is still on", () => {
+ assert.equal(gateEnv().OMNIRUSH_GATE_MCP, "")
+ assert.equal(gateEnv().OMNIRUSH_GATE_PROVIDERS, "omnirush")
+})
+
+test("refuses names that would widen or split a rule", () => {
+ for (const bad of ["*", "a*", "", "a b", "a,b", "mcp:x"]) assert.throws(() => gateEnv({ mcp: [bad] }))
+ assert.throws(() => gateEnv({ provider: "*" }))
+})
+
+test("never turns on project code", () => {
+ assert.equal("OMNIRUSH_PROJECT_CODE" in gateEnv(), false)
+})
diff --git a/apps/server/src/engine-identity.test.ts b/apps/server/src/engine-identity.test.ts
index 65b27787..49048632 100644
--- a/apps/server/src/engine-identity.test.ts
+++ b/apps/server/src/engine-identity.test.ts
@@ -30,7 +30,7 @@ afterEach(async () => {
});
async function engineRelease(): Promise<{ tag: string; version: string }> {
- const path = resolve(import.meta.dir, "../../desktop/scripts/engine-release.json");
+ const path = resolve(import.meta.dir, "../../desktop/scripts/engine-v2-release.json");
return JSON.parse(await readFile(path, "utf8")) as { tag: string; version: string };
}
@@ -52,8 +52,8 @@ describe("engine identity", () => {
test("names the engine release the build bundles", async () => {
const release = await engineRelease();
// constants.json and engine-release.json name the same engine build.
- expect((constants as { engineReleaseTag?: string }).engineReleaseTag).toBe(release.tag);
- expect(constants.opencodeVersion.replace(/^v/, "")).toBe(release.version);
+ expect((constants as { engineV2ReleaseTag?: string }).engineV2ReleaseTag).toBe(release.tag);
+ expect(constants.opencodeV2Version).toBe(release.version);
expect(BUNDLED_HARNESS.build_tag).toBe(release.tag);
expect(BUNDLED_HARNESS.version.startsWith(release.version)).toBe(true);
expect(BUNDLED_HARNESS.version).toBe(release.tag.replace(/^engine-/, ""));
diff --git a/apps/server/src/engine-identity.ts b/apps/server/src/engine-identity.ts
index 9f647571..cfe50d6b 100644
--- a/apps/server/src/engine-identity.ts
+++ b/apps/server/src/engine-identity.ts
@@ -27,7 +27,7 @@ export function engineBuildVersion(buildTag: string, fallbackVersion: string): s
return fallbackVersion.trim().replace(/^v/, "");
}
-/** The desktop's engine: OmniRush.ai's opencode build (apps/desktop/scripts/engine-release.json). */
+/** The desktop's engine: OmniRush.ai's opencode build (apps/desktop/scripts/engine-v2-release.json). */
export function opencodeHarness(buildTag: string, fallbackVersion: string): Harness {
const version = engineBuildVersion(buildTag, fallbackVersion) || "unknown";
return {
@@ -43,11 +43,11 @@ export function engineVersionOf(harness: Harness): string {
return `${harness.name}/${harness.version}`;
}
-const bundled = constants as { opencodeVersion?: string; engineReleaseTag?: string };
+const bundled = constants as { opencodeV2Version?: string; engineV2ReleaseTag?: string };
-/** The engine this build bundles. */
+/** The engine every chat runs on: the bundled 2.x engine (apps/desktop/scripts/engine-v2-release.json). */
export const BUNDLED_HARNESS: Harness = Object.freeze(
- opencodeHarness(bundled.engineReleaseTag ?? "", bundled.opencodeVersion ?? ""),
+ opencodeHarness(bundled.engineV2ReleaseTag ?? "", bundled.opencodeV2Version ?? ""),
) as Harness;
/** `engine_version` of the bundled engine ("opencode/1.18.32-r2"). */
diff --git a/apps/server/src/engine-v2-migration.ts b/apps/server/src/engine-v2-migration.ts
new file mode 100644
index 00000000..b195b864
--- /dev/null
+++ b/apps/server/src/engine-v2-migration.ts
@@ -0,0 +1,69 @@
+/**
+ * First start of the 2.x engine with an existing 1.x store.
+ *
+ * The 2.x engine migrates a 1.x `opencode.db` in place on its first start (and drops
+ * what it cannot read). It never gets the 1.x store itself: a consistent copy
+ * (VACUUM INTO, safe while the 1.x engine still has it open) is kept as a backup, and
+ * another copy seeds the 2.x store. The 1.x store stays untouched, so reinstalling a
+ * 1.x app is the rollback. The chats that came from 1.x are recorded: their later
+ * turns are marked in uploads (engine.migrated_from) and left out of deliveries.
+ */
+import { existsSync, readFileSync } from "node:fs";
+import { copyFile, mkdir, rename, writeFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+
+import { importNodeSqlite } from "./runtime-db.js";
+
+export const MIGRATED_SESSIONS_FILE = "v1-migrated-sessions.json";
+export const MIGRATED_FROM = "opencode/1.18.32";
+
+type Sqlite = { exec(sql: string): void; all(sql: string): unknown[]; close(): void };
+
+async function openReadOnly(path: string): Promise<Sqlite> {
+ if (typeof process.versions.bun === "string") {
+ const { Database } = await import("bun:sqlite");
+ const db = new Database(path, { readonly: true, create: false });
+ return { exec: (sql) => db.run(sql), all: (sql) => db.query(sql).all(), close: () => db.close() };
+ }
+ const { DatabaseSync } = await importNodeSqlite();
+ const db = new DatabaseSync(path, { readOnly: true });
+ return { exec: (sql) => db.exec(sql), all: (sql) => db.prepare(sql).all(), close: () => db.close() };
+}
+
+/**
+ * Seeds `<v2Root>/opencode.db` from the 1.x store once (only while the 2.x store does not exist yet).
+ * Returns what it did, or null when there was nothing to do.
+ */
+export async function seedV2StoreFromV1(v2Root: string, v1Db: string, now = new Date()): Promise<{ backup: string; sessions: string[] } | null> {
+ const target = join(v2Root, "opencode.db");
+ if (existsSync(target) || !existsSync(v1Db)) return null;
+ const backupDir = join(dirname(v2Root), `v1-store-backup-${now.toISOString().replace(/[:.]/g, "-")}`);
+ await mkdir(backupDir, { recursive: true, mode: 0o700 });
+ const backup = join(backupDir, "opencode.db");
+ const source = await openReadOnly(v1Db);
+ let sessions: string[];
+ try {
+ source.exec(`VACUUM INTO '${backup.replace(/'/g, "''")}'`);
+ sessions = source.all("SELECT id FROM session").flatMap((row) =>
+ row && typeof (row as { id?: unknown }).id === "string" ? [(row as { id: string }).id] : []);
+ } finally {
+ source.close();
+ }
+ await mkdir(v2Root, { recursive: true, mode: 0o700 });
+ const staging = `${target}.seed`;
+ await copyFile(backup, staging);
+ await writeFile(join(v2Root, MIGRATED_SESSIONS_FILE), `${JSON.stringify({ from: MIGRATED_FROM, at: now.toISOString(), backup, sessions })}\n`, { mode: 0o600 });
+ await rename(staging, target);
+ return { backup, sessions };
+}
+
+/** The chats that came from the 1.x store (empty when none did). */
+export function readMigratedSessions(v2Root: string): Set<string> {
+ try {
+ const parsed: unknown = JSON.parse(readFileSync(join(v2Root, MIGRATED_SESSIONS_FILE), "utf8"));
+ const sessions = parsed && typeof parsed === "object" ? (parsed as { sessions?: unknown }).sessions : undefined;
+ return new Set(Array.isArray(sessions) ? sessions.filter((id): id is string => typeof id === "string") : []);
+ } catch {
+ return new Set();
+ }
+}
diff --git a/apps/server/src/engine-v2-next.test.ts b/apps/server/src/engine-v2-next.test.ts
new file mode 100644
index 00000000..9be196f3
--- /dev/null
+++ b/apps/server/src/engine-v2-next.test.ts
@@ -0,0 +1,94 @@
+import { Database } from "bun:sqlite";
+import { expect, test } from "bun:test";
+import { existsSync } from "node:fs";
+import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { assertSessionPluginActive } from "./engine-v2-preview.js";
+import { readMigratedSessions, seedV2StoreFromV1 } from "./engine-v2-migration.js";
+import { pluginDirectories } from "./managed-opencode-v2.js";
+import sessionPlugin from "./opencode-plugins/omnirush-session-next.js";
+import { startsV1Chat } from "./server.js";
+
+async function withDir(run: (dir: string) => Promise<void>): Promise<void> {
+ const dir = await mkdtemp(join(tmpdir(), "v2-next-"));
+ try { await run(dir); } finally { await rm(dir, { recursive: true, force: true }); }
+}
+
+test("a 1.x store seeds the 2.x store once, keeps a backup and stays untouched", () => withDir(async (dir) => {
+ const v1 = join(dir, "v1", "opencode.db");
+ await Bun.write(join(dir, "v1", ".keep"), "");
+ const db = new Database(v1, { create: true });
+ db.run("PRAGMA journal_mode=WAL");
+ db.run("CREATE TABLE session (id TEXT PRIMARY KEY)");
+ db.run("INSERT INTO session VALUES ('ses_a'), ('ses_b')");
+ const root = join(dir, "v2", "state");
+ const seeded = await seedV2StoreFromV1(root, v1, new Date("2026-10-25T00:00:00Z"));
+ db.close();
+ expect(seeded?.sessions.sort()).toEqual(["ses_a", "ses_b"]);
+ expect(existsSync(seeded!.backup)).toBe(true);
+ // The copy holds the rows still in the WAL.
+ const copy = new Database(join(root, "opencode.db"), { readonly: true });
+ expect(copy.query("SELECT count(*) AS n FROM session").get()).toEqual({ n: 2 });
+ copy.close();
+ expect(readMigratedSessions(root)).toEqual(new Set(["ses_a", "ses_b"]));
+ // Nothing was written beside the 1.x store.
+ expect((await readdir(join(dir, "v1"))).filter((name) => !/^(\.keep|opencode\.db(-wal|-shm)?)$/.test(name))).toEqual([]);
+ // Never again once the 2.x store exists.
+ expect(await seedV2StoreFromV1(root, v1)).toBeNull();
+ expect(await seedV2StoreFromV1(join(dir, "other"), join(dir, "missing.db"))).toBeNull();
+ expect(readMigratedSessions(join(dir, "other"))).toEqual(new Set());
+}));
+
+test("the session plugin names the chat on gateway requests and blanks secrets in shells", async () => {
+ const hooks: Record<string, (event: never) => Promise<void> | void> = {};
+ process.env.OMNIRUSH_USER_XDG_DATA_HOME = "/home/me/.data";
+ process.env.OMNIRUSH_USER_XDG_STATE_HOME = "";
+ try {
+ await sessionPlugin.setup({
+ session: {
+ get: async ({ sessionID }) => ({ id: sessionID, parentID: sessionID === "ses_child" ? "ses_parent" : undefined, model: { id: "gpt-6-astra" } }),
+ hook: async (name, callback) => { hooks[name] = callback as never; },
+ },
+ shell: { hook: async (name, callback) => { hooks[name] = callback as never; } },
+ });
+ } finally {
+ delete process.env.OMNIRUSH_USER_XDG_DATA_HOME;
+ delete process.env.OMNIRUSH_USER_XDG_STATE_HOME;
+ }
+ const request = (sessionID: string, kind: string, providerID = "omnirush") => {
+ const event = { sessionID, kind, model: { id: "cheap", providerID }, headers: {} as Record<string, string> };
+ return (hooks["model.request"] as (e: typeof event) => Promise<void>)(event).then(() => event.headers);
+ };
+ expect(await request("ses_main", "primary")).toEqual({ "x-omnirush-session-id": "ses_main" });
+ expect(await request("ses_child", "primary")).toEqual({ "x-omnirush-session-id": "ses_child", "x-parent-session-id": "ses_parent" });
+ expect(await request("ses_main", "title")).toEqual({ "x-omnirush-session-id": "ses_main", "x-omnirush-title": "1", "x-omnirush-chat-model": "gpt-6-astra" });
+ expect(await request("ses_main", "primary", "openai")).toEqual({});
+ const env: Record<string, string | undefined> = { OPENCODE_PASSWORD: "pw", OMNIRUSH_POLICY_TOKEN: "t", XDG_DATA_HOME: "/engine/data", XDG_STATE_HOME: "/engine/state", PATH: "/bin" };
+ await (hooks["create.before"] as (e: { env: typeof env }) => void)({ env });
+ expect(env).toMatchObject({ OPENCODE_PASSWORD: "", OMNIRUSH_POLICY_TOKEN: "", XDG_DATA_HOME: "/home/me/.data", XDG_STATE_HOME: undefined, PATH: "/bin" });
+});
+
+test("chats do not start unless the session plugin is active", async () => {
+ const engine = (data: unknown, status = 200) => ({ fetchJson: async () => ({ status, json: { data } }) });
+ await assertSessionPluginActive(engine([{ id: "omnirush.session", state: { status: "active" } }]), "/p");
+ await expect(assertSessionPluginActive(engine([{ id: "opencode.agent", state: { status: "active" } }]), "/p")).rejects.toThrow(/not active/);
+ await expect(assertSessionPluginActive(engine([{ id: "omnirush.session", state: { status: "failed" } }]), "/p")).rejects.toThrow(/not active/);
+ await expect(assertSessionPluginActive(engine([], 500), "/p")).rejects.toThrow(/not active/);
+});
+
+test("each plugin module gets a directory the 2.x engine loads", () => withDir(async (dir) => {
+ const [plugin] = await pluginDirectories(dir, ["/app/opencode-plugins/omnirush-session-next.js"]);
+ expect(plugin).toBe(join(dir, "omnirush-session-next"));
+ expect(await readFile(join(plugin!, "server.js"), "utf8")).toBe('export { default } from "file:///app/opencode-plugins/omnirush-session-next.js";\n');
+}));
+
+test("the 1.x engine starts no chat and no turn", () => {
+ for (const path of ["/session", "/opencode/session", "/session/ses_1/prompt_async", "/session/ses_1/message", "/session/ses_1/command", "/session/ses_1/shell", "/session/ses_1/summarize", "/session/ses_1/fork"]) {
+ expect(startsV1Chat("POST", path)).toBe(true);
+ }
+ for (const [method, path] of [["GET", "/session"], ["GET", "/session/ses_1/message"], ["POST", "/session/ses_1/abort"], ["DELETE", "/session/ses_1"], ["POST", "/session/ses_1/permissions/p1"]]) {
+ expect(startsV1Chat(method!, path!)).toBe(false);
+ }
+});
diff --git a/apps/server/src/engine-v2-preview.test.ts b/apps/server/src/engine-v2-preview.test.ts
index 26cc01bb..28421d94 100644
--- a/apps/server/src/engine-v2-preview.test.ts
+++ b/apps/server/src/engine-v2-preview.test.ts
@@ -77,24 +77,10 @@ function testConfig(root: string): ServerConfig {
};
}
-test("keeps persisted engine v2 preview state when the override is unset", () => {
- const persisted = { enabled: true, chatRouting: false };
- expect(resolveInitialEngineV2PreviewState({}, persisted)).toEqual(persisted);
-});
-
-test("enables engine v2 preview and chat routing when the override is 1", () => {
- expect(resolveInitialEngineV2PreviewState(
- { OMNIRUSH_ENGINE_V2_PREVIEW: "1" },
- { enabled: false, chatRouting: false },
- )).toEqual({ enabled: true, chatRouting: true });
-});
-
-test("keeps persisted engine v2 preview state for an invalid override", () => {
- const persisted = { enabled: false, chatRouting: true };
- expect(resolveInitialEngineV2PreviewState(
- { OMNIRUSH_ENGINE_V2_PREVIEW: "invalid" },
- persisted,
- )).toEqual(persisted);
+test("the 2.x engine runs every chat, whatever an earlier preview setting said", () => {
+ expect(resolveInitialEngineV2PreviewState({}, { enabled: false, chatRouting: false })).toEqual({ enabled: true, chatRouting: true });
+ expect(resolveInitialEngineV2PreviewState({ OMNIRUSH_ENGINE_V2_PREVIEW: "0" })).toEqual({ enabled: true, chatRouting: true });
+ expect(resolveInitialEngineV2PreviewState({ OMNIRUSH_ENGINE_V2_PREVIEW: "sidecar" })).toEqual({ enabled: true, chatRouting: false });
});
test("round trips enabled and chat routing state and defaults corrupt state", async () => {
@@ -111,18 +97,13 @@ test("round trips enabled and chat routing state and defaults corrupt state", as
}
});
-test("persists chat routing and includes it in preview status without starting the engine", async () => {
+test("the 2.x engine cannot be turned off", async () => {
const root = await mkdtemp(join(tmpdir(), "omnirush-engine-v2-preview-"));
- const config = testConfig(root);
- const preview = createEngineV2Preview({ config });
+ const preview = createEngineV2Preview({ config: testConfig(root), deferStart: true });
try {
- expect(preview.status().chatRouting).toBe(false);
- const status = await preview.setChatRouting(true);
- expect(status.chatRouting).toBe(true);
- expect(status.enabled).toBe(false);
- expect(status.running).toBe(false);
- expect(preview.connection()).toBeUndefined();
- expect(readEngineV2PreviewState(config)).toEqual({ enabled: false, chatRouting: true });
+ expect(preview.status()).toMatchObject({ enabled: true, chatRouting: true });
+ await expect(preview.setEnabled(false)).rejects.toThrow(/cannot be turned off/);
+ await expect(preview.setChatRouting(false)).rejects.toThrow(/cannot be turned off/);
} finally {
await preview.stop();
await rm(root, { recursive: true, force: true });
diff --git a/apps/server/src/engine-v2-preview.ts b/apps/server/src/engine-v2-preview.ts
index 8c54f492..d78330dc 100644
--- a/apps/server/src/engine-v2-preview.ts
+++ b/apps/server/src/engine-v2-preview.ts
@@ -1,14 +1,11 @@
import { executionRules } from "./managed-policy-rules.js";
import { managedDesktopPolicy } from "./managed-desktop-policy.js";
-import { execFile } from "node:child_process";
import { readFileSync } from "node:fs";
-import { mkdir, writeFile } from "node:fs/promises";
+import { mkdir, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
-import constants from "../../../constants.json" with { type: "json" };
import {
createManagedOpencodeV2Server,
- installOpencodeV2Binary,
type ManagedOpencodeV2Server,
type OpencodeV2ProviderSpec,
} from "./managed-opencode-v2.js";
@@ -22,9 +19,11 @@ import {
} from "./runtime-opencode-config-store.js";
import type { EnvService } from "./env-file.js";
import { selectPrimaryCredentialEnvName } from "./managed-provider-auth.js";
+import { OMNIRUSH_SESSION_PLUGIN_ID } from "./opencode-plugins/omnirush-session-next.js";
+import { engineDataDir } from "./engine-data-home.js";
+import { readMigratedSessions, seedV2StoreFromV1 } from "./engine-v2-migration.js";
import type { ServerConfig } from "./types.js";
-const OPENCODE_V2_VERSION = constants.opencodeV2Version;
const PREVIEW_STATE_FILE = "engine-v2-preview.json";
const UNSET_API_KEY = "omnirush-engine-v2-preview-unset";
// A cold sidecar can return HTTP 503 while its model catalog initializes for 17–20 seconds.
@@ -36,7 +35,7 @@ export interface EngineV2PreviewStatus {
running: boolean;
version?: string;
pid?: number;
- binSource?: "env" | "path" | "cache";
+ binSource?: "env";
mirroredProviderIds: string[];
skippedProviderIds: string[];
catalogModelIds: string[];
@@ -62,6 +61,8 @@ export interface EngineV2Preview {
connection(): { url: string; username: string; password: string } | undefined;
ensureWorkspaceReady(directory: string): Promise<void>;
syncWorkspaceMcp(workspaceId: string, directory: string): Promise<void>;
+ /** Whether a chat came from the 1.x store (engine-v2-migration.ts). */
+ migratedFromV1(sessionId: string): boolean;
stop(): Promise<void>;
}
@@ -70,19 +71,20 @@ export interface EngineV2PreviewState {
chatRouting?: boolean;
}
+/**
+ * The 2.x engine runs every new chat: on, with chats routed to it, whatever an
+ * earlier preview setting or switch said. `sidecar` (tests only) leaves chats off it.
+ */
export function resolveInitialEngineV2PreviewState(
env: NodeJS.ProcessEnv,
- persisted: EngineV2PreviewState,
+ _persisted?: EngineV2PreviewState,
): EngineV2PreviewState {
- const override = env.OMNIRUSH_ENGINE_V2_PREVIEW;
- if (override === "1" || override === "chat") return { enabled: true, chatRouting: true };
- if (override === "sidecar") return { enabled: true, chatRouting: false };
- return persisted;
+ return { enabled: true, chatRouting: env.OMNIRUSH_ENGINE_V2_PREVIEW !== "sidecar" };
}
interface ResolvedBinary {
bin: string;
- source: "env" | "path" | "cache";
+ source: "env";
}
function isRecord(value: unknown): value is Record<string, unknown> {
@@ -121,35 +123,13 @@ export async function writeEngineV2PreviewState(
await writeFile(statePath(config), `${JSON.stringify(state, null, 2)}\n`, "utf8");
}
-function exec(file: string, args: string[], options: { cwd?: string; timeout?: number } = {}): Promise<void> {
- return new Promise((resolve, reject) => {
- execFile(file, args, options, (error) => {
- if (error) reject(error);
- else resolve();
- });
- });
-}
-
async function resolveBinary(config: ServerConfig): Promise<ResolvedBinary> {
- const override = process.env.OMNIRUSH_OPENCODE2_BIN?.trim();
- if (override) return { bin: override, source: "env" };
-
- let pathError = "not found";
- try {
- await exec("opencode2", ["--version"]);
- return { bin: "opencode2", source: "path" };
- } catch (error) {
- pathError = errorMessage(error);
- }
-
- try {
- const binary = await installOpencodeV2Binary(join(runtimeStorageDir(config), "opencode-v2-verified"), OPENCODE_V2_VERSION);
- return { bin: binary, source: "cache" };
- } catch (error) {
- throw new Error(
- `Unable to resolve OmniRush v2 (${pathError}; verified download: ${errorMessage(error)}). Configure a working runtime binary override in advanced settings.`,
- );
- }
+ // Engines the preview downloaded before the 2.x engine shipped inside the app.
+ await rm(join(runtimeStorageDir(config), "opencode-v2-verified"), { recursive: true, force: true }).catch(() => undefined);
+ // The app's bundled engine (Electron main sets it; a release build checks its hash there and at launch).
+ const bin = process.env.OMNIRUSH_OPENCODE2_BIN?.trim();
+ if (!bin) throw new Error("The OmniRush engine was not found. Reinstall OmniRush.ai.");
+ return { bin, source: "env" };
}
export function mapRuntimeProvidersToV2Specs(
@@ -294,6 +274,23 @@ export function mapRuntimeMcpToV2(value: unknown): Record<string, unknown> | und
...(oauth === undefined ? {} : { oauth }), ...shared };
}
+/**
+ * Chats bind to the gateway only through the session plugin's headers, and a 2.x plugin that
+ * fails to load only warns: no chat starts in a location where it is not active.
+ */
+export async function assertSessionPluginActive(
+ engine: Pick<ManagedOpencodeV2Server, "fetchJson">,
+ directory: string,
+): Promise<void> {
+ const response = await engine.fetchJson("/api/plugin", { directory, timeoutMs: 5_000 });
+ const plugins = isRecord(response.json) && Array.isArray(response.json.data) ? response.json.data : [];
+ const ours = plugins.find((plugin) => isRecord(plugin) && plugin.id === OMNIRUSH_SESSION_PLUGIN_ID);
+ const state = isRecord(ours) ? (isRecord(ours.state) ? ours.state.status ?? ours.state.type : ours.state) : undefined;
+ if (response.status !== 200 || !ours || (state !== undefined && !["active", "loaded", "ready"].includes(String(state)))) {
+ throw new Error("The OmniRush engine's session plugin is not active; chats cannot start.");
+ }
+}
+
export function createEngineV2Preview(options: { config: ServerConfig; env?: Pick<EnvService, "list" | "onChange">; deferStart?: boolean }): EngineV2Preview {
const { config } = options;
const rootDir = join(runtimeStorageDir(config), "opencode-v2", "state");
@@ -317,6 +314,7 @@ export function createEngineV2Preview(options: { config: ServerConfig; env?: Pic
let mirrorInFlight: Promise<void> | undefined;
let mirrorDirty = false;
const workspaceReadiness = new Map<string, Promise<void>>();
+ let migrated = readMigratedSessions(rootDir);
let mirroredSpecs: OpencodeV2ProviderSpec[] = [];
const mcpCleaned = new Set<string>();
const mcpInFlight = new Map<string, Promise<void>>();
@@ -347,7 +345,7 @@ export function createEngineV2Preview(options: { config: ServerConfig; env?: Pic
: []
));
await Promise.all(names.map(async (name) => {
- const result = await active.fetchJson(`/api/mcp/${encodeURIComponent(name)}`, {
+ const result = await active.fetchJson(`/api/experimental/mcp/${encodeURIComponent(name)}`, {
method: "DELETE", directory, timeoutMs: 15_000,
});
if (result.status !== 204 && result.status !== 404) throw new Error(`OmniRush v2 MCP removal failed (${result.status})`);
@@ -454,6 +452,13 @@ export function createEngineV2Preview(options: { config: ServerConfig; env?: Pic
binSource = resolved.source;
if (!enabled || !allowRunning) return;
await mkdir(workspaceDir, { recursive: true });
+ // First start next to a 1.x store: back it up and seed the 2.x store from a copy (the 1.x store is kept).
+ try {
+ await seedV2StoreFromV1(rootDir, join(engineDataDir(process.env), "opencode.db"));
+ } catch (error) {
+ lastError = `1.x chats were not brought over: ${errorMessage(error)}`;
+ }
+ migrated = readMigratedSessions(rootDir);
const opencodeModelsEnv = await resolveOpencodeModelsEnv();
const managed = await createManagedOpencodeV2Server({
bin: resolved.bin,
@@ -515,7 +520,7 @@ export function createEngineV2Preview(options: { config: ServerConfig; env?: Pic
function recordStartError(error: unknown): void {
running = false;
- lastError = `${errorMessage(error)} Configure a working runtime binary override in advanced settings.`;
+ lastError = errorMessage(error);
}
async function stopRuntime(): Promise<void> {
@@ -529,6 +534,7 @@ export function createEngineV2Preview(options: { config: ServerConfig; env?: Pic
}
async function setEnabled(nextEnabled: boolean): Promise<EngineV2PreviewStatus> {
+ if (!nextEnabled) throw new Error("The 2.x engine runs every chat and cannot be turned off.");
if (nextEnabled && enabled && running) return status();
await writeEngineV2PreviewState(config, { enabled: nextEnabled, chatRouting });
enabled = nextEnabled;
@@ -546,6 +552,7 @@ export function createEngineV2Preview(options: { config: ServerConfig; env?: Pic
}
async function setChatRouting(nextChatRouting: boolean): Promise<EngineV2PreviewStatus> {
+ if (!nextChatRouting) throw new Error("The 2.x engine runs every chat and cannot be turned off.");
await writeEngineV2PreviewState(config, { enabled, chatRouting: nextChatRouting });
chatRouting = nextChatRouting;
return status();
@@ -576,7 +583,7 @@ export function createEngineV2Preview(options: { config: ServerConfig; env?: Pic
await new Promise((resolve) => setTimeout(resolve, 100));
} while (Date.now() < deadline);
throw new Error("OmniRush v2 workspace provider configuration did not become ready");
- })();
+ })().then(() => assertSessionPluginActive(active, directory));
workspaceReadiness.set(directory, pending);
try { await pending; } catch (error) {
if (workspaceReadiness.get(directory) === pending) workspaceReadiness.delete(directory);
@@ -592,5 +599,5 @@ export function createEngineV2Preview(options: { config: ServerConfig; env?: Pic
if (enabled) void start().catch(recordStartError);
}
if (!options.deferStart) startWhenReady();
- return { start: startWhenReady, status, setEnabled, setChatRouting, connection, ensureWorkspaceReady, syncWorkspaceMcp, stop };
+ return { start: startWhenReady, status, setEnabled, setChatRouting, connection, ensureWorkspaceReady, syncWorkspaceMcp, migratedFromV1: (id) => migrated.has(id), stop };
}
diff --git a/apps/server/src/managed-opencode-v2.env.test.ts b/apps/server/src/managed-opencode-v2.env.test.ts
index ab55881f..acdcf404 100644
--- a/apps/server/src/managed-opencode-v2.env.test.ts
+++ b/apps/server/src/managed-opencode-v2.env.test.ts
@@ -3,7 +3,7 @@ import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { createManagedOpencodeV2Server } from "./managed-opencode-v2.js";
+import { assertEngineGates, createManagedOpencodeV2Server, engineV2SpawnEnv } from "./managed-opencode-v2.js";
const posix = process.platform === "win32" ? test.skip : test;
@@ -20,9 +20,23 @@ posix("the v2 engine gets its own empty config home, not the user's global openc
const env = await readFile(record, "utf8");
const configHome = /^XDG_CONFIG_HOME=(.*)$/m.exec(env)?.[1];
expect(configHome).toBe(join(dir, "state", "xdg-config"));
- expect(env).not.toContain(userConfig);
- expect(env).toMatch(/^OPENCODE_DISABLE_PROJECT_CONFIG=1$/m);
+ // Only agent shells get the user's config home back (omnirush-session-next.ts).
+ expect(env.replace(/^OMNIRUSH_USER_XDG_CONFIG_HOME=.*$/m, "")).not.toContain(userConfig);
+ expect(env).toMatch(/^OMNIRUSH_USER_XDG_CONFIG_HOME=.*user-config$/m);
+ // Project config stays on (engine patch 0003 keeps only its descriptive keys); the gates are on.
+ expect(env).not.toMatch(/^OPENCODE_DISABLE_PROJECT_CONFIG=/m);
+ expect(env).toMatch(/^OMNIRUSH_GATE_PROVIDERS=omnirush$/m);
+ expect(env).toMatch(/^OMNIRUSH_GATE_MCP=$/m);
+ expect(env).toMatch(/^OMNIRUSH_NO_SYSTEM_CONFIG=1$/m);
+ expect(/^XDG_DATA_HOME=(.*)$/m.exec(env)?.[1]).toBe(join(dir, "state", "data"));
} finally {
await rm(dir, { recursive: true, force: true });
}
});
+
+test("the engine's gates are applied last and a spawn without them is refused", () => {
+ const env = engineV2SpawnEnv({ OMNIRUSH_GATE_PROVIDERS: "*", OMNIRUSH_GATE_MCP: "anything", OMNIRUSH_NO_SYSTEM_CONFIG: "0", PATH: "/bin" });
+ expect(env).toMatchObject({ OMNIRUSH_GATE_PROVIDERS: "omnirush", OMNIRUSH_GATE_MCP: "", OMNIRUSH_NO_SYSTEM_CONFIG: "1", PATH: "/bin" });
+ expect(() => assertEngineGates({ PATH: "/bin" })).toThrow(/gates are missing/);
+ expect(() => assertEngineGates({ OMNIRUSH_GATE_PROVIDERS: "omnirush", OMNIRUSH_NO_SYSTEM_CONFIG: "1" })).toThrow(/gates are missing/);
+});
diff --git a/apps/server/src/managed-opencode-v2.ts b/apps/server/src/managed-opencode-v2.ts
index 145e40da..d9b8496a 100644
--- a/apps/server/src/managed-opencode-v2.ts
+++ b/apps/server/src/managed-opencode-v2.ts
@@ -1,19 +1,20 @@
-import { managedPolicyPluginPath } from "./managed-policy-plugin.js";
+import { managedPolicyPluginPath, sessionNextPluginPath } from "./managed-policy-plugin.js";
import type { EnginePermissionRule } from "./managed-policy-rules.js";
// Parallel v2 lane prototype: provider injection is a watched-config write. This module
// deliberately has no reload/dispose call, unlike managed-opencode.ts and server.ts reloadOpencodeEngine.
import { spawn } from "node:child_process";
import { randomBytes } from "node:crypto";
-import { chmod, mkdir } from "node:fs/promises";
-import { join } from "node:path";
+import { chmod, mkdir, writeFile } from "node:fs/promises";
+import { basename, extname, join } from "node:path";
+import { pathToFileURL } from "node:url";
-export { installOpencodeV2Binary } from "./opencode-v2-binary.js";
import { loopbackFetch } from "./server-fetch.js";
import { writeFileAtomic } from "./atomic-write.js";
import { currentProviderLockPolicy, noteEngineStarted, providerAllowed } from "./provider-lock.js";
import { providerLockEnv } from "./provider-lock/provider-lock.mjs";
-import { isReleaseBuild, RELEASE_ENGINE_ERROR } from "./release-guard.js";
+import { gateEnv } from "./engine-gates/engine-gates.mjs";
+import { releaseEngineBinary } from "./release-guard.js";
export interface OpencodeV2ModelSpec {
id: string;
@@ -78,11 +79,40 @@ function diagnostics(exitCode: number | null, stdout: string, stderr: string): E
);
}
+/**
+ * The 2.x engine loads a configured plugin only from a directory (a file path is skipped with a
+ * warning): each plugin module gets one, whose server.js re-exports it.
+ */
+export async function pluginDirectories(root: string, modules: string[]): Promise<string[]> {
+ return Promise.all(modules.map(async (module) => {
+ const directory = join(root, basename(module, extname(module)));
+ await mkdir(directory, { recursive: true, mode: 0o700 });
+ await writeFile(join(directory, "server.js"), `export { default } from ${JSON.stringify(pathToFileURL(module).href)};\n`, { mode: 0o600 });
+ return directory;
+ }));
+}
+
+/**
+ * The engine's environment with its gates last (engine-gates.mjs): only the gateway provider and no MCP
+ * server (MCP stays off on this engine until its allowlist is wired). The engine fails open without the
+ * gate variables, so the spawn is refused when they are missing.
+ */
+export function engineV2SpawnEnv(env: Record<string, string>): Record<string, string> {
+ return assertEngineGates({ ...env, ...gateEnv({ provider: "omnirush", mcp: [] }) });
+}
+
+export function assertEngineGates(env: Record<string, string | undefined>): Record<string, string> {
+ if (!env.OMNIRUSH_GATE_PROVIDERS || env.OMNIRUSH_NO_SYSTEM_CONFIG !== "1" || typeof env.OMNIRUSH_GATE_MCP !== "string") {
+ throw new Error("The OmniRush engine's gates are missing; it was not started.");
+ }
+ return env as Record<string, string>;
+}
+
export async function createManagedOpencodeV2Server(
options: ManagedOpencodeV2ServerOptions,
): Promise<ManagedOpencodeV2Server> {
- // A release build runs only the engine it bundles (release-guard.ts); this preview downloads another.
- if (isReleaseBuild()) throw new Error(RELEASE_ENGINE_ERROR);
+ // A release build runs only the engine it bundles, checked by its sha256 (release-guard.ts).
+ const bin = await releaseEngineBinary(options.bin) ?? options.bin;
const hostname = options.hostname ?? "127.0.0.1";
const port = options.port ?? 0;
const bootTimeoutMs = options.bootTimeoutMs ?? 60_000;
@@ -124,24 +154,29 @@ export async function createManagedOpencodeV2Server(
await chmod(configHome, 0o700);
// Load enforcement on the first boot, before any session can run.
await writeProviders();
- const child = spawn(options.bin, ["serve", "--hostname", hostname, "--port", String(port)], {
- env: {
- ...inherited,
- OPENCODE_PASSWORD: password,
- OPENCODE_DB: join(options.rootDir, "opencode.db"),
- OPENCODE_CONFIG_DIR: configDir,
- XDG_CONFIG_HOME: configHome,
- // No session sharing to an outside share service.
- OPENCODE_DISABLE_SHARE: "1",
- // A project's own config files are not read: this engine has no MCP filter, and it starts a project's
- // MCP servers (with this environment, the password included) as soon as it opens the folder.
- OPENCODE_DISABLE_PROJECT_CONFIG: "1",
- OPENCODE_CONFIG_PROJECT_DISABLE: "1",
- OPENCODE_AUTO_SHARE: "false",
- ...(opencodeModelsUrl === undefined ? {} : { OPENCODE_MODELS_URL: opencodeModelsUrl }),
- ...(disableModelsFetch === undefined ? {} : { OPENCODE_DISABLE_MODELS_FETCH: disableModelsFetch }),
- ...providerLockEnv(providerLock).set,
- },
+ const env = engineV2SpawnEnv({
+ ...inherited,
+ OPENCODE_PASSWORD: password,
+ OPENCODE_DB: join(options.rootDir, "opencode.db"),
+ OPENCODE_CONFIG_DIR: configDir,
+ XDG_CONFIG_HOME: configHome,
+ // Its data and state (snapshots, logs, sign-ins) stay in its own folder, never the CLI's
+ // <XDG data>/omnirush; agent shells get the user's back (omnirush-session-next.ts).
+ XDG_DATA_HOME: join(options.rootDir, "data"),
+ XDG_STATE_HOME: join(options.rootDir, "state"),
+ OMNIRUSH_USER_XDG_DATA_HOME: inherited.XDG_DATA_HOME ?? "",
+ OMNIRUSH_USER_XDG_STATE_HOME: inherited.XDG_STATE_HOME ?? "",
+ OMNIRUSH_USER_XDG_CONFIG_HOME: inherited.XDG_CONFIG_HOME ?? "",
+ // Claude Code's global files (~/.claude) are not read either.
+ OPENCODE_DISABLE_CLAUDE_CODE: "1",
+ // A project's own config stays on (its AGENTS.md is stock behaviour); the engine keeps only its
+ // descriptive keys there and loads none of its plugins, MCP servers or providers.
+ ...(opencodeModelsUrl === undefined ? {} : { OPENCODE_MODELS_URL: opencodeModelsUrl }),
+ ...(disableModelsFetch === undefined ? {} : { OPENCODE_DISABLE_MODELS_FETCH: disableModelsFetch }),
+ ...providerLockEnv(providerLock).set,
+ });
+ const child = spawn(bin, ["serve", "--hostname", hostname, "--port", String(port)], {
+ env,
stdio: ["ignore", "pipe", "pipe"],
});
@@ -189,16 +224,17 @@ export async function createManagedOpencodeV2Server(
}
async function health(): Promise<OpencodeV2Health> {
- const response = await fetchJson("/api/health", { timeoutMs: 5_000 });
+ // 2.0.x has no health route: its info answers 200 once the server serves.
+ const response = await fetchJson("/api/info", { timeoutMs: 5_000 });
if (response.status !== 200 || !isRecord(response.json)) {
throw new Error(`OmniRush v2 health returned HTTP ${response.status}`);
}
- const { healthy, version, pid } = response.json;
- if (typeof healthy !== "boolean" || typeof version !== "string" || typeof pid !== "number") {
+ const { version, pid } = response.json;
+ if (typeof version !== "string" || typeof pid !== "number") {
throw new Error("OmniRush v2 health returned an invalid payload");
}
if (pid !== child.pid) throw new Error("OmniRush v2 health did not match the spawned child");
- return { healthy, version, pid };
+ return { healthy: true, version, pid };
}
async function writeProviders(): Promise<void> {
@@ -241,9 +277,12 @@ export async function createManagedOpencodeV2Server(
const target = join(configDir, "opencode.json");
await writeFileAtomic(target, `${JSON.stringify({
$schema: "https://opencode.ai/config.json",
+ // No session sharing to an outside service; the bundled engine never replaces itself.
+ share: "disabled",
+ update: "disable",
providers: providerConfig,
...(options.permissions ? { permissions: await options.permissions() } : {}),
- ...(options.env?.OMNIRUSH_SERVER_URL ? { plugins: [managedPolicyPluginPath(true)] } : {}),
+ plugins: await pluginDirectories(join(options.rootDir, "plugins"), [sessionNextPluginPath(), ...(options.env?.OMNIRUSH_SERVER_URL ? [managedPolicyPluginPath(true)] : [])]),
}, null, 2)}\n`, { mode: 0o600 });
}
diff --git a/apps/server/src/managed-policy-plugin.ts b/apps/server/src/managed-policy-plugin.ts
index ef756bd9..19ba74a6 100644
--- a/apps/server/src/managed-policy-plugin.ts
+++ b/apps/server/src/managed-policy-plugin.ts
@@ -1,4 +1,6 @@
import { omnirushPluginPath } from "./omnirush-extensions-plugin-path.js";
+/** The 2.x engine's session plugin (gateway chat headers, shell secrets). */
+export const sessionNextPluginPath = (): string => omnirushPluginPath("omnirush-session-next");
export function managedPolicyPluginPath(next = false): string {
return omnirushPluginPath(next ? "managed-policy-next" : "managed-policy");
}
diff --git a/apps/server/src/opencode-plugins/omnirush-session-next.ts b/apps/server/src/opencode-plugins/omnirush-session-next.ts
new file mode 100644
index 00000000..951f0e7d
--- /dev/null
+++ b/apps/server/src/opencode-plugins/omnirush-session-next.ts
@@ -0,0 +1,58 @@
+import { SHELL_SECRET_ENV } from "./shell-secret-env.js";
+
+/**
+ * 2.x engine plugin: what the 1.x plugins' `chat.headers` and `shell.env` did.
+ * - Every model request to the app's gateway names its chat (x-omnirush-session-id) and,
+ * for a sub-agent, its parent chat, so the broker binds the chat (strict sessions) and
+ * keeps one model per chat. A title request is marked and names the chat's model.
+ * - Agent shells never see the app's secrets (the engine password included).
+ * The server refuses v2 chats while this plugin is not active (engine-v2-preview.ts).
+ */
+export const OMNIRUSH_SESSION_PLUGIN_ID = "omnirush.session";
+const PROVIDER_ID = "omnirush";
+
+type SessionInfo = { parentID?: unknown; model?: { id?: unknown } | null };
+
+export default {
+ id: OMNIRUSH_SESSION_PLUGIN_ID,
+ async setup(ctx: {
+ session: {
+ get(input: { sessionID: string }): Promise<unknown>;
+ hook(name: "model.request", callback: (event: { sessionID: string; kind: string; model: { id: string; providerID: string }; headers: Record<string, string> }) => Promise<void>, options?: { providerID?: string }): Promise<unknown>;
+ };
+ shell: { hook(name: "create.before", callback: (event: { env: Record<string, string | undefined> }) => Promise<void> | void): Promise<unknown> };
+ }) {
+ const sessions = new Map<string, SessionInfo>();
+ const info = async (sessionID: string): Promise<SessionInfo> => {
+ const known = sessions.get(sessionID);
+ if (known) return known;
+ const result: unknown = await ctx.session.get({ sessionID }).catch(() => undefined);
+ const raw = result && typeof result === "object" && "data" in result ? (result as { data: unknown }).data : result;
+ const found = (raw && typeof raw === "object" ? raw : {}) as SessionInfo;
+ if (sessions.size >= 512) sessions.clear();
+ sessions.set(sessionID, found);
+ return found;
+ };
+ await ctx.session.hook("model.request", async (event) => {
+ if (event.model.providerID !== PROVIDER_ID || !event.sessionID) return;
+ event.headers["x-omnirush-session-id"] = event.sessionID;
+ const session = await info(event.sessionID);
+ if (typeof session.parentID === "string" && session.parentID) event.headers["x-parent-session-id"] = session.parentID;
+ if (event.kind === "title") {
+ event.headers["x-omnirush-title"] = "1";
+ const chatModel = typeof session.model?.id === "string" ? session.model.id : event.model.id;
+ if (chatModel) event.headers["x-omnirush-chat-model"] = chatModel;
+ }
+ }, { providerID: PROVIDER_ID });
+ // Captured before any shell runs: the engine's own XDG folders are not the user's.
+ const userXdg = Object.fromEntries(["DATA", "STATE", "CONFIG"].map((kind) =>
+ [`XDG_${kind}_HOME`, process.env[`OMNIRUSH_USER_XDG_${kind}_HOME`]]));
+ await ctx.shell.hook("create.before", (event) => {
+ for (const name of SHELL_SECRET_ENV) event.env[name] = "";
+ for (const [name, value] of Object.entries(userXdg)) {
+ if (value === undefined) continue;
+ event.env[name] = value || undefined;
+ }
+ });
+ },
+};
diff --git a/apps/server/src/opencode-v2-artifacts.json b/apps/server/src/opencode-v2-artifacts.json
deleted file mode 100644
index 79b1f4d4..00000000
--- a/apps/server/src/opencode-v2-artifacts.json
+++ /dev/null
@@ -1,37 +0,0 @@
-{
- "version": "0.0.0-beta-19086",
- "platforms": {
- "linux-x64-baseline": {
- "url": "https://registry.npmjs.org/@opencode-ai/cli-linux-x64-baseline/-/cli-linux-x64-baseline-0.0.0-beta-19086.tgz",
- "integrity": "sha512-UZ0BQb+0LuqPj02jmX35JOSCIrwx/qt8m+aoFOEnwydCpn/zETLQcF+6Z1qkeC4Dgsj55hnc2oc/O1kkoTuzUg=="
- },
- "linux-arm64": {
- "url": "https://registry.npmjs.org/@opencode-ai/cli-linux-arm64/-/cli-linux-arm64-0.0.0-beta-19086.tgz",
- "integrity": "sha512-bGVr6JkW5EfQf/KvsUEupV5HQoqBMXb0B5YahHclNk+lI0cjeIWdPMFD5L8qAtwwGaIsHS/0XduwR1CK+76OQw=="
- },
- "linux-x64-baseline-musl": {
- "url": "https://registry.npmjs.org/@opencode-ai/cli-linux-x64-baseline-musl/-/cli-linux-x64-baseline-musl-0.0.0-beta-19086.tgz",
- "integrity": "sha512-m9lpDXWdhk9LDSgLHtBV8Vsvm+dwwgQozjdzvbw5exNgqdwulj/SEYA2TIGmdzxWJMbHg25/ql4E0SbPl58BQQ=="
- },
- "linux-arm64-musl": {
- "url": "https://registry.npmjs.org/@opencode-ai/cli-linux-arm64-musl/-/cli-linux-arm64-musl-0.0.0-beta-19086.tgz",
- "integrity": "sha512-RF7yvA6L/i3JJC6cOKrUnLy313Jb5FIFTuU3+zAR1RkR+MbRj+p+eFy11y4ofi4FSTxZs8jZpi8lFXF57UNi0Q=="
- },
- "darwin-x64-baseline": {
- "url": "https://registry.npmjs.org/@opencode-ai/cli-darwin-x64-baseline/-/cli-darwin-x64-baseline-0.0.0-beta-19086.tgz",
- "integrity": "sha512-erllsGf+M+5wf4KoN+r4DRGRxfFXC7f4Ob8o2W2VW0uRm+N+s+Hg0Sott++ZsKmYLtEI3YoNNWhkHd64yrKH8A=="
- },
- "darwin-arm64": {
- "url": "https://registry.npmjs.org/@opencode-ai/cli-darwin-arm64/-/cli-darwin-arm64-0.0.0-beta-19086.tgz",
- "integrity": "sha512-Pdhlr9KFpdTYw9YKsD2ztM6dMG5oi/cR1YiiDxikaUaqdXJnOKSRpHjRulilIYsnqaoOe0SKdORvwKRYik/SvA=="
- },
- "windows-x64-baseline": {
- "url": "https://registry.npmjs.org/@opencode-ai/cli-windows-x64-baseline/-/cli-windows-x64-baseline-0.0.0-beta-19086.tgz",
- "integrity": "sha512-ywVxQeIyT+Uzg0suZjiUJGZ0xQ03s9PcR+kFtUaoFO17rPr4Fh8V3RHC+zrAos01Mi9zjLM64aFKuhhxyetftQ=="
- },
- "windows-arm64": {
- "url": "https://registry.npmjs.org/@opencode-ai/cli-windows-arm64/-/cli-windows-arm64-0.0.0-beta-19086.tgz",
- "integrity": "sha512-rO+CgxDwIdSCWKkCbgkJqupr1L1TsPjfMjJi/SJ8eEe5HrXdKD7ly+hFlheS9OsBYcdfavv/XIw5H2XktXFbfQ=="
- }
- }
-}
diff --git a/apps/server/src/opencode-v2-binary.ts b/apps/server/src/opencode-v2-binary.ts
deleted file mode 100644
index 3554734b..00000000
--- a/apps/server/src/opencode-v2-binary.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import { externalFetch } from "./server-fetch.js";
-import { execFile } from "node:child_process";
-import { createHash } from "node:crypto";
-import { access, chmod, mkdir, mkdtemp, readdir, rename, rm, writeFile } from "node:fs/promises";
-import { join } from "node:path";
-import { promisify } from "node:util";
-import artifacts from "./opencode-v2-artifacts.json" with { type: "json" };
-
-const exec = promisify(execFile);
-
-/** Install only the pinned native executable; never run registry lifecycle scripts. */
-export async function installOpencodeV2Binary(cacheRoot: string, version: string): Promise<string> {
- if (version !== artifacts.version) throw new Error(`No verified OmniRush v2 artifacts for ${version}`);
- const platform = process.platform === "win32" ? "windows" : process.platform;
- const report = process.platform === "linux" ? process.report?.getReport() : undefined;
- const glibc = typeof report === "object" && report !== null && "header" in report
- && typeof report.header === "object" && report.header !== null && "glibcVersionRuntime" in report.header;
- const key = `${platform}-${process.arch}${process.arch === "x64" ? "-baseline" : ""}${platform === "linux" && !glibc ? "-musl" : ""}`;
- const artifact = Object.entries(artifacts.platforms).find(([name]) => name === key)?.[1];
- if (!artifact) throw new Error(`OmniRush v2 does not support ${key}`);
- const directory = join(cacheRoot, version, key);
- const name = platform === "windows" ? "opencode2.exe" : "opencode2";
- const binary = join(directory, name);
- try { await access(binary); void pruneOpencodeV2Versions(cacheRoot, version); return binary; } catch { /* First installation. */ }
- await mkdir(cacheRoot, { recursive: true, mode: 0o700 });
- await chmod(cacheRoot, 0o700);
- await mkdir(directory, { recursive: true, mode: 0o700 });
- await chmod(directory, 0o700);
- const staging = await mkdtemp(join(directory, ".install-"));
- try {
- const response = await externalFetch(artifact.url, { redirect: "error", signal: AbortSignal.timeout(180_000) });
- if (!response.ok) throw new Error(`OmniRush v2 download returned HTTP ${response.status}`);
- const bytes = Buffer.from(await response.arrayBuffer());
- const integrity = `sha512-${createHash("sha512").update(bytes).digest("base64")}`;
- if (integrity !== artifact.integrity) throw new Error("OmniRush v2 archive integrity mismatch");
- const archive = join(staging, "binary.tgz");
- await writeFile(archive, bytes, { mode: 0o600 });
- await exec("tar", ["-xzf", archive, "-C", staging, `package/bin/${name}`], { timeout: 60_000 });
- const extracted = join(staging, "package", "bin", name);
- await chmod(extracted, 0o755);
- await rename(extracted, binary);
- void pruneOpencodeV2Versions(cacheRoot, version);
- return binary;
- } finally {
- await rm(staging, { recursive: true, force: true });
- }
-}
-
-function versionParts(value: string): number[] | null {
- const m = /^(\d+)\.(\d+)\.(\d+)/.exec(value);
- return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
-}
-
-function olderThan(a: number[], b: number[]): boolean {
- for (let i = 0; i < 3; i += 1) if (a[i] !== b[i]) return a[i] < b[i];
- return false;
-}
-
-/**
- * Downloaded engine versions other than the current one and the newest older
- * one (what the previous app version runs) go; newer ones (an app version
- * ahead of this one) and names that are not versions stay. Never throws.
- */
-export async function pruneOpencodeV2Versions(cacheRoot: string, current: string): Promise<string[]> {
- const now = versionParts(current);
- if (!now) return [];
- let names: string[] = [];
- try { names = await readdir(cacheRoot); } catch { return []; }
- const older = names
- .map((name) => ({ name, parts: versionParts(name) }))
- .filter((entry): entry is { name: string; parts: number[] } => Boolean(entry.parts) && entry.name !== current && /^\d+\.\d+\.\d+[0-9A-Za-z.+-]*$/.test(entry.name))
- .filter((entry) => olderThan(entry.parts, now))
- .sort((a, b) => (olderThan(a.parts, b.parts) ? -1 : olderThan(b.parts, a.parts) ? 1 : 0));
- const removed: string[] = [];
- for (const entry of older.slice(0, -1)) {
- try { await rm(join(cacheRoot, entry.name), { recursive: true, force: true, maxRetries: 2 }); removed.push(entry.name); } catch { /* in use (Windows): next start */ }
- }
- return removed;
-}
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 054b6375..b3751592 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -231,7 +231,8 @@ import { modelsNamedIn } from "./omnirush-swarm.js";
import { findManagedEngineWorkspace } from "./workspaces.js";
import { startThreadApprovalReplayer, type ThreadApprovalReplayer } from "./thread-approvals.js";
import { CloudProviderSync, parseCloudProviderDenSession } from "./cloud-provider-sync.js";
-import { createEngineV2Preview, type EngineV2Preview } from "./engine-v2-preview.js";
+import { createEngineV2Preview, resolveInitialEngineV2PreviewState, type EngineV2Preview } from "./engine-v2-preview.js";
+import { MIGRATED_FROM } from "./engine-v2-migration.js";
import { APP_SECRET_HEADER, appRequestRefusal } from "./app-request-gate.js";
import { isUploadFileDenied, sessionUploaderEnabled } from "./session-uploader.js";
import { editorUserEditEvent, editorUserReviewEvent } from "./editor-events.js";
@@ -991,6 +992,11 @@ function isPromptAsyncProxyRequest(method: string, proxyPath: string) {
// A prompt dispatch (v1 prompt_async, the v1 engine's synchronous prompt
// `POST /session/:id/message`, v2 prompt, or a slash command) is the session
// uploader's "prompt" milestone: the workspace is captured as the turn begins.
+/** A new chat or a turn on the 1.x engine (retired for chats: the 2.x engine runs them). */
+export function startsV1Chat(method: string, proxyPath: string): boolean {
+ return method === "POST" && /^\/session(?:\/[^/]+\/(?:prompt_async|prompt|message|command|shell|summarize|init|fork))?\/?$/.test(normalizeOpencodeProxyPath(proxyPath));
+}
+
function isUploadPromptDispatch(method: string, proxyPath: string): boolean {
return method === "POST" && /^\/session\/[^/]+\/(?:prompt_async|prompt|message|command)$/.test(normalizeOpencodeProxyPath(proxyPath));
}
@@ -1671,6 +1677,7 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
proxyPath: mount.restPath,
connection,
recoverySignal: taskRecovery?.owns(request) ? request.signal : undefined,
+ migratedFromV1: engineV2Preview.migratedFromV1,
});
const response = taskRecovery ? await taskRecovery.forward(workspace, "v2", decodeEngineRoutePath(mount.restPath), request, send) : await send();
return finalize(response);
@@ -2015,6 +2022,8 @@ export async function proxyOpencodeV2Request(input: {
proxyPath: string;
connection: { url: string; username: string; password: string };
recoverySignal?: AbortSignal;
+ /** Whether a chat came from the 1.x store: its turns are marked and kept out of deliveries. */
+ migratedFromV1?: (sessionId: string) => boolean;
}): Promise<Response> {
const method = input.request.method.toUpperCase();
if (method !== "GET" && method !== "HEAD") ensureWritable(input.config);
@@ -2134,7 +2143,7 @@ export async function proxyOpencodeV2Request(input: {
});
const value = buildOmniRushV2Instructions(false);
const instructionUrl = new URL(target);
- instructionUrl.pathname = `/api/session/${encodeURIComponent(sessionId)}/instructions/entries/${OMNIRUSH_V2_INSTRUCTION_KEY}`;
+ instructionUrl.pathname = `/api/experimental/session/${encodeURIComponent(sessionId)}/instructions/entries/${OMNIRUSH_V2_INSTRUCTION_KEY}`;
const synced = await loopbackFetch(instructionUrl.toString(), {
method: "PUT", headers: internalHeaders, body: JSON.stringify({ value }), signal: AbortSignal.timeout(15_000),
});
@@ -2187,6 +2196,7 @@ export async function proxyOpencodeV2Request(input: {
capture.boxSession(uploadedSessionId, boxInfo);
capture.permissionMode(await capturePermissionMode(input.config));
capture.startSession(uploadedSessionId, input.workspace.id, input.workspace.path, turnsBefore);
+ if (input.migratedFromV1?.(uploadedSessionId)) capture.recordTrace(uploadedSessionId, "engine.migrated_from", { from: MIGRATED_FROM, exclude_from_delivery: true });
const boxPlan = await boxServiceFor(input.config).planOutcome(uploadedSessionId, input.workspace).catch(() => null);
if (boxPlan) capture.recordTrace(uploadedSessionId, "box.plan", boxPlan);
capture.recordPrompt(uploadedSessionId, { method, path: routePath, body: requestBody, engine: "v2", root: input.workspace.path, attachments: true, dispatchedAt: Date.now() });
@@ -2492,6 +2502,12 @@ export async function proxyOpencodeRequest(input: {
ensureWritable(input.config);
}
assertEngineMcpRouteAllowed(input.config, method, normalizeOpencodeProxyPath(proxyPath));
+ // Chats run on the 2.x engine (/opencode2): the 1.x engine starts no chat and no turn.
+ if (workspace && workspace.workspaceType !== "remote" && startsV1Chat(method, proxyPath)
+ && resolveInitialEngineV2PreviewState(process.env).chatRouting) {
+ await input.request.arrayBuffer().catch(() => undefined);
+ return jsonResponse({ error: "engine_v1_retired", message: "Chats now run on the new engine. Update OmniRush.ai or reopen the chat." }, 409);
+ }
if (workspace && workspace.workspaceType !== "remote" && isUploadPromptDispatch(method, proxyPath)) {
if (uploadDispatchRefused(input.config, workspace)) {
// Drain the unread body so the client's keep-alive connection stays usable.
@@ -4781,6 +4797,9 @@ function createRoutes(
if (body.chatRouting !== undefined && typeof body.chatRouting !== "boolean") {
throw new ApiError(400, "invalid_payload", "chatRouting must be a boolean");
}
+ if (body.enabled === false || body.chatRouting === false) {
+ throw new ApiError(409, "engine_v2_required", "The 2.x engine runs every chat and cannot be turned off.");
+ }
let status = engineV2Preview.status();
if (typeof body.enabled === "boolean") status = await engineV2Preview.setEnabled(body.enabled);
if (typeof body.chatRouting === "boolean") status = await engineV2Preview.setChatRouting(body.chatRouting);
diff --git a/constants.json b/constants.json
index b5fb9c11..4c5613f0 100644
--- a/constants.json
+++ b/constants.json
@@ -1,5 +1,6 @@
{
"opencodeVersion": "v1.18.32",
- "opencodeV2Version": "0.0.0-beta-19086",
- "engineReleaseTag": "engine-1.18.32-ux4-ed3-pl4"
+ "opencodeV2Version": "2.0.32",
+ "engineReleaseTag": "engine-1.18.32-ux4-ed3-pl4",
+ "engineV2ReleaseTag": "engine-2.0.32-r2"
}