Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat: run the 1.x engine and import earlier history

ogsamrat8e7edcc0a804
diff --git a/apps/server/package.json b/apps/server/package.json
index 2c184ca5..003f648d 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 && 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-engine2.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 && 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 --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/cli.ts b/apps/server/src/cli.ts
index 42181a83..f0d25f5b 100644
--- a/apps/server/src/cli.ts
+++ b/apps/server/src/cli.ts
@@ -29,7 +29,7 @@ import { migrateWorkspaceRuntimeConfigToEngineGlobal } from "./runtime-opencode-
import { migrateLegacyOmniRushUiMcpCommand } from "./omnirush-ui-mcp-migration.js";
import { resolveOpencodeModelsEnv } from "./opencode-models-url.js";
import { assertOpencodeConfigCompat } from "./opencode-config-compat.js";
-import { resolveEngineIdentity } from "./engine2/launch.js";
+import { adoptOpencodeCredentials, startEngine2SessionImport } from "./engine2/import.js";
import { startWorkerActivityHeartbeat } from "./worker-activity-heartbeat.js";
import pkg from "../package.json" with { type: "json" };
@@ -106,21 +106,26 @@ if (!config.opencodeBaseUrl && process.env.OMNIRUSH_MANAGE_OPENCODE === "1") {
};
// See embedded.ts: a V2 `permissions` key in a user-owned config file is
// fatal to the bundled engine; report the file before spawning.
- if ((await resolveEngineIdentity(process.env.OMNIRUSH_OPENCODE_BIN?.trim() || "opencode", { ...process.env, ...engineEnv })).dialect === "v1") {
- await assertOpencodeConfigCompat({
- workspaceRoots: config.workspaces
- .filter((entry) => entry.workspaceType !== "remote")
- .map((entry) => entry.path),
- env: { ...process.env, ...engineEnv },
- logger,
- });
- }
+ await assertOpencodeConfigCompat({
+ workspaceRoots: config.workspaces
+ .filter((entry) => entry.workspaceType !== "remote")
+ .map((entry) => entry.path),
+ env: { ...process.env, ...engineEnv },
+ logger,
+ });
+ adoptOpencodeCredentials({ ...process.env, ...engineEnv }, (level, message, attributes) => logger.log(level, message, attributes));
managedOpencode = await createManagedOpencodeServer({
bin: process.env.OMNIRUSH_OPENCODE_BIN,
cwd: managedOpencodeCwd,
excludedPorts: [config.port],
env: engineEnv,
});
+ // Sessions the 2.x engine of OmniRush.ai 2.2.0 – 3.x stored: copied once into this engine's store.
+ void startEngine2SessionImport({
+ bin: process.env.OMNIRUSH_OPENCODE_BIN?.trim() || "opencode",
+ env: { ...process.env, ...engineEnv },
+ log: (level, message, attributes) => logger.log(level, message, attributes),
+ });
config.opencodeBaseUrl = managedOpencode.url;
config.opencodeUsername = managedOpencode.username;
config.opencodePassword = managedOpencode.password;
diff --git a/apps/server/src/embedded.ts b/apps/server/src/embedded.ts
index 44ffab86..3b0a08ad 100644
--- a/apps/server/src/embedded.ts
+++ b/apps/server/src/embedded.ts
@@ -41,7 +41,7 @@ import { migrateWorkspaceRuntimeConfigToEngineGlobal } from "./runtime-opencode-
import { migrateLegacyOmniRushUiMcpCommand, type OmniRushUiMcpLaunch } from "./omnirush-ui-mcp-migration.js";
import { resolveOpencodeModelsEnv } from "./opencode-models-url.js";
import { assertOpencodeConfigCompat } from "./opencode-config-compat.js";
-import { resolveEngineIdentity } from "./engine2/launch.js";
+import { adoptOpencodeCredentials, startEngine2SessionImport } from "./engine2/import.js";
import type { ServeResult } from "./serve-node.js";
import type { CaptureFileUpload, LocalManagedMcpVaultKeyProvider, OmniRushGatewayCredentials, ServerConfig } from "./types.js";
@@ -274,26 +274,30 @@ export async function startEmbeddedServer(options: EmbeddedServerOptions): Promi
return [...new Set([config.port, ...poolPorts, startupPort].filter((port) => port > 0))];
},
};
- // A 1.x engine (1.18.32+) refuses user-owned config files that carry a
- // V2 `permissions` key: a global file exits the engine at boot, a
- // workspace file breaks that workspace's instance. Name the file and
+ // The bundled engine (1.18.32+) refuses user-owned config files that
+ // carry a V2 `permissions` key: a global file exits the engine at boot,
+ // a workspace file breaks that workspace's instance. Name the file and
// the keys here, before the spawn, instead of surfacing an opaque exit.
- // The bundled 2.x engine reads both spellings, so it needs no check.
- if ((await resolveEngineIdentity(opencodeBin?.trim() || "opencode", { ...process.env, ...engineEnv })).dialect === "v1") {
- await duringStartup(() => assertOpencodeConfigCompat({
- workspaceRoots: config.workspaces
- .filter((entry) => entry.workspaceType !== "remote")
- .map((entry) => entry.path),
- env: { ...process.env, ...engineEnv },
- logger,
- }));
- }
+ await duringStartup(() => assertOpencodeConfigCompat({
+ workspaceRoots: config.workspaces
+ .filter((entry) => entry.workspaceType !== "remote")
+ .map((entry) => entry.path),
+ env: { ...process.env, ...engineEnv },
+ logger,
+ }));
+ adoptOpencodeCredentials({ ...process.env, ...engineEnv }, (level, message, attributes) => logger.log(level, message, attributes));
managedOpencode = await duringStartup(() => createManagedOpencodeServer({
bin: opencodeBin,
cwd,
excludedPorts: [config.port],
env: engineEnv,
}));
+ // Sessions the 2.x engine of OmniRush.ai 2.2.0 – 3.x stored: copied once into this engine's store.
+ void startEngine2SessionImport({
+ bin: opencodeBin?.trim() || "opencode",
+ env: { ...process.env, ...engineEnv },
+ log: (level, message, attributes) => logger.log(level, message, attributes),
+ });
config.opencodeBaseUrl = managedOpencode.url;
config.opencodeUsername = managedOpencode.username;
diff --git a/apps/server/src/engine-plugin-bridge.e2e.test.ts b/apps/server/src/engine-plugin-bridge.e2e.test.ts
index 072247f6..c88823cb 100644
--- a/apps/server/src/engine-plugin-bridge.e2e.test.ts
+++ b/apps/server/src/engine-plugin-bridge.e2e.test.ts
@@ -3,23 +3,25 @@ import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
-import { createManagedOpencodeServer, type ManagedOpencodeServer } from "../managed-opencode.js";
+import { createManagedOpencodeServer, type ManagedOpencodeServer } from "./managed-opencode.js";
+import { omnirushAnthropicToolSchemaPluginPath, omnirushTitleRecoveryPluginPath } from "./omnirush-extensions-plugin-path.js";
/**
- * OmniRush plugins that used to patch the global fetch, on the real 2.x
- * engine (the bundled sidecar, started as the app starts it, with the plugin
- * bridge) against a mock provider:
+ * OmniRush plugins that patch the global fetch the engine sends model
+ * requests through, on the real engine (the bundled sidecar, started as the
+ * app starts it, the plugins listed in its config) against a mock provider:
*
* - title recovery: the private x-omnirush-title-attempt header never
* reaches the provider, and a rejected optional title parameter
- * (`reasoning_effort`) is retried without it, so the session still gets its title;
+ * (`reasoning_effort`, `temperature`, `top_p`) is retried without it, so the session
+ * still gets its title;
* - Anthropic tool schemas: an MCP tool whose input schema has a top-level
* `anyOf` reaches the Anthropic Messages API flattened.
*
* Skipped when the sidecar binary is not present (prepare:sidecar not run).
*/
-const repoRoot = resolve(import.meta.dir, "../../../..");
+const repoRoot = resolve(import.meta.dir, "../../..");
const sidecarDir = join(repoRoot, "apps/desktop/resources/sidecars");
function findSidecar(): string | null {
const arch = process.arch === "arm64" ? "aarch64" : "x86_64";
@@ -31,6 +33,8 @@ const enginePath = findSidecar();
const describeMaybe = enginePath ? describe : describe.skip;
const HEADER = "x-omnirush-title-attempt";
+/** Optional title-request parameters the mock refuses (title recovery retries without them). */
+const OPTIONAL_TITLE_PARAMETERS = ["reasoning_effort", "temperature", "top_p"];
const TITLE = "Recovered title from the mock";
type Seen = { path: string; headers: Record<string, string>; body: Record<string, any> };
@@ -46,7 +50,7 @@ function chatJson(content: string): Response {
return Response.json({ id: "c", object: "chat.completion", created: 1, model: "m", choices: [{ index: 0, message: { role: "assistant", content }, finish_reason: "stop" }], usage: { prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 } });
}
-describeMaybe("OmniRush plugins on the 2.x engine's own hooks (mock provider)", () => {
+describeMaybe("OmniRush fetch plugins on the bundled engine (mock provider)", () => {
let engine: ManagedOpencodeServer;
let provider: ReturnType<typeof Bun.serve>;
let work = "";
@@ -95,8 +99,9 @@ describeMaybe("OmniRush plugins on the 2.x engine's own hooks (mock provider)",
return Response.json({ type: "error", error: { type: "invalid_request_error", message: "stop here" } }, { status: 400 });
}
const titleRequest = !Array.isArray(body.tools) || body.tools.length === 0;
- if (titleRequest && "reasoning_effort" in body) {
- return Response.json({ error: { code: "unsupported_parameter", param: "reasoning_effort", message: "Unsupported parameter: reasoning_effort" } }, { status: 400 });
+ const rejected = titleRequest ? OPTIONAL_TITLE_PARAMETERS.find((key) => key in body) : undefined;
+ if (rejected) {
+ return Response.json({ error: { code: "unsupported_parameter", param: rejected, message: `Unsupported parameter: ${rejected}` } }, { status: 400 });
}
if (titleRequest) return body.stream ? chatStream(TITLE) : chatJson(TITLE);
return body.stream ? chatStream("Done.") : chatJson("Done.");
@@ -125,6 +130,7 @@ rl.on("line", (line) => {
anth: { name: "Anth", npm: "@ai-sdk/anthropic", options: { baseURL: `${base}/v1`, apiKey: "mock-key" }, models: { "claude-mock": { name: "Claude mock", tool_call: true, limit: { context: 100_000, output: 4_000 } } } },
},
mcp: { anyof: { type: "local", command: ["node", mcpScript], enabled: true } },
+ plugin: [omnirushTitleRecoveryPluginPath(), omnirushAnthropicToolSchemaPluginPath()],
}));
engine = await createManagedOpencodeServer({
bin: enginePath!,
@@ -132,7 +138,6 @@ rl.on("line", (line) => {
env: {
OPENCODE_CONFIG: configPath,
OPENCODE_DISABLE_MODELS_FETCH: "1",
- OMNIRUSH_ENGINE2_CONFIG_DIR: join(data, "engine2"),
OMNIRUSH_SERVER_URL: base,
OMNIRUSH_POLICY_TOKEN: "policy",
OMNIRUSH_SERVER_TOKEN: "server",
@@ -154,7 +159,7 @@ rl.on("line", (line) => {
rmSync(data, { recursive: true, force: true });
}, 30_000);
- test("the title marker never reaches the provider, and a rejected reasoning effort is retried without it", async () => {
+ test("the title marker never reaches the provider, and a rejected optional parameter is retried without it", async () => {
seen.length = 0;
const sessionID = await prompt({ providerID: "mock", modelID: "mock-model" }, "Say done.", "high");
const titled = await waitFor(async () => {
@@ -167,8 +172,13 @@ rl.on("line", (line) => {
const chat = seen.filter((request) => request.path === "/v1/chat/completions");
for (const request of chat) expect(request.headers[HEADER]).toBeUndefined();
const titles = chat.filter((request) => !Array.isArray(request.body.tools) || request.body.tools.length === 0);
- // The session's variant gives the title request a reasoning effort the mock rejects.
- expect(titles.map((request) => "reasoning_effort" in request.body)).toEqual([true, false]);
+ // An optional parameter the mock refused is dropped on the one retry; the title request that
+ // went through carries none of them.
+ const refused = titles.map((request) => OPTIONAL_TITLE_PARAMETERS.filter((key) => key in request.body));
+ expect(refused.at(-1)).toEqual([]);
+ expect(refused.length).toBeLessThanOrEqual(2);
+ if (refused.length === 2) expect(refused[0]!.length).toBeGreaterThan(0);
+ console.log("title requests: optional parameters", JSON.stringify(refused));
}, 90_000);
test("an MCP tool with a top-level anyOf reaches the Anthropic API flattened", async () => {
diff --git a/apps/server/src/engine-pool.test.ts b/apps/server/src/engine-pool.test.ts
index 494b7025..ec5532a1 100644
--- a/apps/server/src/engine-pool.test.ts
+++ b/apps/server/src/engine-pool.test.ts
@@ -1237,72 +1237,3 @@ describe("engine event stream bounds", () => {
});
});
-/** A pool whose primary re-reads its config while running, as the 2.x engine does. */
-async function createLivePool(fixture: Fixture): Promise<{ pool: EnginePool; refreshes: () => number }> {
- const primary = await fixture.spawnPrimary();
- let refreshes = 0;
- const pool = new EnginePool({ config: fixture.config, template: fixture.template, hooks: fixture.hooks });
- setEnginePoolForConfig(fixture.config, pool);
- cleanups.push(async () => {
- clearEnginePoolForConfig(fixture.config);
- await pool.disposeAll().catch(() => undefined);
- });
- pool.adoptPrimary({
- handle: { ...primary, refreshConfig: async () => { refreshes += 1; } },
- fingerprint: await computeEngineConfigFingerprint(fixture.template),
- registryId: null,
- trustedIdentity: null,
- });
- fixture.config.opencodeBaseUrl = primary.url;
- fixture.config.workspaces[0]!.baseUrl = primary.url;
- return { pool, refreshes: () => refreshes };
-}
-
-describe("engine pool: config applied live", () => {
- test("an engine that re-reads its config gets the change with no restart while a turn runs, and a later reload does not redo it", async () => {
- const fixture = await createFixture();
- const { pool, refreshes } = await createLivePool(fixture);
- const primaryUrl = pool.primaryUrl();
- await fixture.setBusy(portOf(primaryUrl ?? "http://127.0.0.1:0"), ["ses_live"]);
-
- const applied = await pool.applyConfigLive(() => fixture.setRuntimeConfig(JSON.stringify({ catalog: 2 })));
-
- expect(applied).toBe(true);
- expect(refreshes()).toBe(1);
- expect(fixture.hookCalls.reloadInPlace).toBe(0);
- expect(pool.snapshot().generations).toHaveLength(1);
- expect(pool.primaryUrl()).toBe(primaryUrl);
- // The engine already runs the new config: even a forced standby request has nothing to do.
- expect(await pool.requestRollover({ reason: "omnirush_model_catalog", workspace: fixture.workspace, forceStandby: true }))
- .toEqual({ action: "skipped", reason: "unchanged" });
- expect(pool.snapshot().generations).toHaveLength(1);
- });
-
- test("a change that was already pending is not marked applied by a live apply", async () => {
- const fixture = await createFixture();
- const { pool } = await createLivePool(fixture);
- // Something the engine has not been brought onto yet.
- await fixture.setRuntimeConfig(JSON.stringify({ plugin: ["other"] }));
-
- expect(await pool.applyConfigLive(() => fixture.setRuntimeConfig(JSON.stringify({ plugin: ["other"], catalog: 2 })))).toBe(true);
-
- expect(await pool.requestRollover({ reason: "config_changed", workspace: fixture.workspace }))
- .toEqual({ action: "reloaded_in_place" });
- });
-
- test("an engine that only reads its config at build time (1.x) still gets the write, and the caller reloads", async () => {
- const fixture = await createFixture();
- const { pool } = await createPool(fixture);
- let writes = 0;
-
- const applied = await pool.applyConfigLive(async () => {
- writes += 1;
- await fixture.setRuntimeConfig(JSON.stringify({ catalog: 2 }));
- });
-
- expect(applied).toBe(false);
- expect(writes).toBe(1);
- expect(await pool.requestRollover({ reason: "omnirush_model_catalog", workspace: fixture.workspace }))
- .toEqual({ action: "reloaded_in_place" });
- });
-});
diff --git a/apps/server/src/engine-pool.ts b/apps/server/src/engine-pool.ts
index 7a06f000..2b0bfc9e 100644
--- a/apps/server/src/engine-pool.ts
+++ b/apps/server/src/engine-pool.ts
@@ -735,37 +735,6 @@ export class EnginePool {
return this.generations.some((entry) => entry.status === "draining");
}
- /**
- * Apply a runtime config change without restarting or reloading the engine,
- * when the serving engine re-reads its config while running (the 2.x engine
- * watches its config file and applies provider and model changes live; a
- * run in flight keeps going). `write` rewrites the runtime config file and
- * always runs exactly once. Returns false, after the write, when the change
- * cannot be applied live: a 1.x engine, or a rollover in flight (the
- * standby reads the new file at spawn). The caller then reloads as before.
- *
- * When the primary was on the config from just before `write`, it is
- * recorded as on the new one, so a later reload request with nothing else
- * changed does not spawn a replacement for a change the engine already has.
- */
- async applyConfigLive(write: () => Promise<void>): Promise<boolean> {
- const primary = this.generations.find((entry) => entry.status === "primary") ?? null;
- const refresh = primary?.handle.refreshConfig;
- if (this.disposed || this.inFlight || !primary || !refresh || !primary.handle.isAlive()) {
- await write();
- return false;
- }
- const before = await this.currentFingerprint();
- await write();
- const after = await this.currentFingerprint();
- await refresh();
- if (primary.fingerprint === before) primary.fingerprint = after;
- this.hooks.logger?.log("info", "Engine config applied live (no restart).", {
- "engine.config.changed": before !== after,
- });
- return true;
- }
-
/**
* Bring the engine onto current config. Idle engines reload in place; busy
* ones roll over to a standby. Serialized: concurrent requests collapse into
diff --git a/apps/server/src/engine-restraint-notes.e2e.test.ts b/apps/server/src/engine-restraint-notes.e2e.test.ts
index 54f0f6a5..87d05d8e 100644
--- a/apps/server/src/engine-restraint-notes.e2e.test.ts
+++ b/apps/server/src/engine-restraint-notes.e2e.test.ts
@@ -3,23 +3,24 @@ import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
-import { createManagedOpencodeServer, type ManagedOpencodeServer } from "../managed-opencode.js";
-import { OMNIRUSH_AGENT_PROMPT } from "../omnirush-agent-prompt.js";
-import { OMNIRUSH_TASK_TOOL_NOTE, omnirushSubagentNote } from "../omnirush-swarm.js";
+import { createManagedOpencodeServer, type ManagedOpencodeServer } from "./managed-opencode.js";
+import { omnirushSwarmPluginPath } from "./omnirush-extensions-plugin-path.js";
+import { OMNIRUSH_AGENT_PROMPT } from "./omnirush-agent-prompt.js";
+import { OMNIRUSH_TASK_TOOL_NOTE, omnirushSubagentNote } from "./omnirush-swarm.js";
/**
- * omnirush.ai's delegation rules reach the model on the real 2.x engine (the
- * bundled sidecar with the plugin bridge) against a mock provider:
+ * omnirush.ai's delegation rules reach the model on the real engine (the
+ * bundled sidecar with the swarm plugin) against a mock provider:
*
* - the main session's request carries the restraint wording of the agent
- * prompt and the subagent tool's description ends with omnirush.ai's note,
+ * prompt and the task tool's description carries omnirush.ai's note once,
* and it gets no sub-agent note;
* - a sub-agent session's request carries the sub-agent note (system).
*
* Skipped when the sidecar binary is not present (prepare:sidecar not run).
*/
-const repoRoot = resolve(import.meta.dir, "../../../..");
+const repoRoot = resolve(import.meta.dir, "../../..");
const sidecarDir = join(repoRoot, "apps/desktop/resources/sidecars");
function findSidecar(): string | null {
const arch = process.arch === "arm64" ? "aarch64" : "x86_64";
@@ -56,11 +57,11 @@ function sse(chunks: object[]): Response {
const say = (content: string) => sse([{ index: 0, delta: { role: "assistant", content } }, { index: 0, delta: {}, finish_reason: "stop" }]);
const callSubagent = () => sse([
{ index: 0, delta: { role: "assistant", content: "" } },
- { index: 0, delta: { tool_calls: [{ index: 0, id: "call_sub_1", type: "function", function: { name: "subagent", arguments: JSON.stringify({ agent: "general", description: "Child part", prompt: `${CHILD_MARK}: reply with one word.` }) } }] } },
+ { index: 0, delta: { tool_calls: [{ index: 0, id: "call_sub_1", type: "function", function: { name: "task", arguments: JSON.stringify({ subagent_type: "general", description: "Child part", prompt: `${CHILD_MARK}: reply with one word.` }) } }] } },
{ index: 0, delta: {}, finish_reason: "tool_calls" },
]);
-describeMaybe("delegation rules on the 2.x engine (mock provider)", () => {
+describeMaybe("delegation rules on the bundled engine (mock provider)", () => {
let engine: ManagedOpencodeServer;
let provider: ReturnType<typeof Bun.serve>;
let work = "";
@@ -111,6 +112,7 @@ describeMaybe("delegation rules on the 2.x engine (mock provider)", () => {
provider: {
mock: { name: "Mock", npm: "@ai-sdk/openai-compatible", options: { baseURL: `${base}/v1`, apiKey: "mock-key" }, models: { "mock-model": { name: "Mock", tool_call: true, limit: { context: 100_000, output: 4_000 } } } },
},
+ plugin: [omnirushSwarmPluginPath()],
}));
engine = await createManagedOpencodeServer({
bin: enginePath!,
@@ -118,7 +120,6 @@ describeMaybe("delegation rules on the 2.x engine (mock provider)", () => {
env: {
OPENCODE_CONFIG: configPath,
OPENCODE_DISABLE_MODELS_FETCH: "1",
- OMNIRUSH_ENGINE2_CONFIG_DIR: join(data, "engine2"),
OMNIRUSH_SERVER_URL: base,
OMNIRUSH_POLICY_TOKEN: "policy",
OMNIRUSH_SERVER_TOKEN: "server",
@@ -141,7 +142,7 @@ describeMaybe("delegation rules on the 2.x engine (mock provider)", () => {
rmSync(data, { recursive: true, force: true });
}, 30_000);
- test("the main request carries the prompt rules and the subagent tool note; the sub-agent's carries the sub-agent note", async () => {
+ test("the main request carries the prompt rules and the task tool note; the sub-agent's carries the sub-agent note", async () => {
const session = (await (await engineFetch("/session", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" })).json()) as { id: string };
const sent = await engineFetch(`/session/${session.id}/prompt_async`, {
method: "POST",
@@ -153,17 +154,17 @@ describeMaybe("delegation rules on the 2.x engine (mock provider)", () => {
const main = await waitFor(() => seen.find((body) => !isChild(body)), "the main session's request");
const mainSystem = systemOf(main);
expect(mainSystem).toContain("Split real work: for a task of more than a few tool calls, start one sub-agent per independent part in one message");
- expect(mainSystem).toContain("make exactly that many subagent calls, no more and no fewer, and start them all in one message");
+ expect(mainSystem).toContain("make exactly that many task-tool calls, no more and no fewer, and start them all in one message");
expect(mainSystem).toContain("Tell a sub-agent to start its own sub-agents only when the user explicitly asked for nested sub-agents.");
expect(mainSystem).not.toContain(SUB_NOTE_MARK);
- const mainTool = main.tools!.find((tool) => tool.function.name === "subagent");
+ const mainTool = main.tools!.find((tool) => tool.function.name === "task");
expect(mainTool).toBeDefined();
- expect(mainTool!.function.description!.endsWith(OMNIRUSH_TASK_TOOL_NOTE)).toBe(true);
+ // Once, after the engine's own text (the engine lists the sub-agents after it).
expect(mainTool!.function.description!.split(OMNIRUSH_TASK_TOOL_NOTE)).toHaveLength(2);
const child = await waitFor(() => seen.find(isChild), "the sub-agent's request");
expect(systemOf(child)).toContain(omnirushSubagentNote(1));
- const childTool = child.tools!.find((tool) => tool.function.name === "subagent");
- if (childTool) expect(childTool.function.description!.endsWith(OMNIRUSH_TASK_TOOL_NOTE)).toBe(true);
+ const childTool = child.tools!.find((tool) => tool.function.name === "task");
+ if (childTool) expect(childTool.function.description!.split(OMNIRUSH_TASK_TOOL_NOTE)).toHaveLength(2);
}, 150_000);
});
diff --git a/apps/server/src/engine-revert.e2e.test.ts b/apps/server/src/engine-revert.e2e.test.ts
index d81eccb1..060c3da8 100644
--- a/apps/server/src/engine-revert.e2e.test.ts
+++ b/apps/server/src/engine-revert.e2e.test.ts
@@ -4,12 +4,12 @@ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "no
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
-import { createManagedOpencodeServer, type ManagedOpencodeServer } from "../managed-opencode.js";
+import { createManagedOpencodeServer, type ManagedOpencodeServer } from "./managed-opencode.js";
/**
- * Revert, undo revert and a prompt after a revert on the real 2.x engine
- * (the bundled sidecar behind the 1.x adapter) against a mock provider whose
- * turns edit a file in a git project:
+ * Revert, undo revert and a prompt after a revert on the real engine (the
+ * bundled sidecar, started as the app starts it) against a mock provider
+ * whose turns edit a file in a git project:
*
* - revert restores the files to the chosen point and reports the revert
* point on the session, keeping the later messages until it is final;
@@ -21,7 +21,7 @@ import { createManagedOpencodeServer, type ManagedOpencodeServer } from "../mana
* Skipped when the sidecar binary is not present (prepare:sidecar not run).
*/
-const repoRoot = resolve(import.meta.dir, "../../../..");
+const repoRoot = resolve(import.meta.dir, "../../..");
const sidecarDir = join(repoRoot, "apps/desktop/resources/sidecars");
function findSidecar(): string | null {
const arch = process.arch === "arm64" ? "aarch64" : "x86_64";
@@ -55,7 +55,7 @@ const callTool = (id: string, name: string, args: object) => sse([
{ index: 0, delta: {}, finish_reason: "tool_calls" },
]);
-describeMaybe("revert on the 2.x engine (mock provider, real files)", () => {
+describeMaybe("revert on the bundled engine (mock provider, real files)", () => {
let engine: ManagedOpencodeServer;
let provider: ReturnType<typeof Bun.serve>;
let work = "";
@@ -132,7 +132,7 @@ describeMaybe("revert on the 2.x engine (mock provider, real files)", () => {
const n = Number(/EDIT (\d+)/.exec(text(lastUser?.content))?.[1] ?? "0");
if (list.at(-1)?.role === "tool") return say(`ok ${n}`);
const write = body.tools.find((tool) => tool.function.name === "write") ? "write" : body.tools[0]!.function.name;
- return callTool(`call_${n}_${seen.length}`, write, { path: join(work, "a.txt"), content: `v${n}\n` });
+ return callTool(`call_${n}_${seen.length}`, write, { filePath: join(work, "a.txt"), content: `v${n}\n` });
},
});
const base = `http://127.0.0.1:${provider.port}`;
@@ -150,7 +150,6 @@ describeMaybe("revert on the 2.x engine (mock provider, real files)", () => {
env: {
OPENCODE_CONFIG: configPath,
OPENCODE_DISABLE_MODELS_FETCH: "1",
- OMNIRUSH_ENGINE2_CONFIG_DIR: join(data, "engine2"),
OMNIRUSH_SERVER_URL: base,
OMNIRUSH_POLICY_TOKEN: "policy",
OMNIRUSH_SERVER_TOKEN: "server",
diff --git a/apps/server/src/engine2/import.test.ts b/apps/server/src/engine2/import.test.ts
new file mode 100644
index 00000000..41c96236
--- /dev/null
+++ b/apps/server/src/engine2/import.test.ts
@@ -0,0 +1,312 @@
+import { Database } from "bun:sqlite";
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import { spawn } from "node:child_process";
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+
+import { adoptOpencodeCredentials, ENGINE2_IMPORT_MANIFEST, engine2ImportDisabled, engine2StorePath, importEngine2Sessions, v1ImportDocument } from "./import.js";
+import { readEngine2Session } from "./store.js";
+
+/**
+ * The one-time import of the 2.x engine's sessions into the 1.x engine's
+ * store. A 2.x store is built from the recorded 2.x conversations
+ * (fixtures/v2-*.json: what the 2.x engine's API answered, the same rows its
+ * `opencode.db` holds) and imported:
+ *
+ * - with a stand-in engine that records each `opencode import` it is asked for;
+ * - with the bundled engine (when prepare:sidecar ran), whose 1.x API then
+ * serves the imported sessions.
+ */
+
+type Tree = { session: Record<string, any>; messages: Array<Record<string, any>>; children: Tree[] };
+const fixture = (name: string): Tree => JSON.parse(readFileSync(join(import.meta.dir, "fixtures", `${name}.json`), "utf8"));
+const flatten = (tree: Tree, out: Tree[] = []): Tree[] => {
+ out.push(tree);
+ for (const child of tree.children) flatten(child, out);
+ return out;
+};
+
+const roots: string[] = [];
+afterAll(() => {
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
+});
+
+/** A 2.x `opencode.db` holding `trees` (sessions placed in `directory`), as the 2.x engine's tables keep them. */
+function write2xStore(path: string, trees: Tree[], directory: string): void {
+ mkdirSync(resolve(path, ".."), { recursive: true });
+ const db = new Database(path, { create: true });
+ db.run(`CREATE TABLE project (id text PRIMARY KEY, worktree text NOT NULL)`);
+ db.run(`CREATE TABLE session_v2 (id text PRIMARY KEY, project_id text NOT NULL, workspace_id text, parent_id text, slug text NOT NULL,
+ directory text NOT NULL, path text, title text, version text, metadata text, cost real, tokens_input integer, tokens_output integer,
+ tokens_reasoning integer, tokens_cache_read integer, tokens_cache_write integer, revert text, permission text, agent text, model text,
+ time_created integer NOT NULL, time_updated integer NOT NULL, time_archived integer)`);
+ db.run(`CREATE TABLE session_message (id text PRIMARY KEY, session_id text NOT NULL, type text NOT NULL, seq integer NOT NULL,
+ time_created integer NOT NULL, time_updated integer NOT NULL, data text NOT NULL)`);
+ for (const tree of trees) {
+ for (const node of flatten(tree)) {
+ const s = node.session;
+ db.run(`INSERT OR IGNORE INTO project (id, worktree) VALUES (?, ?)`, [s.projectID ?? "global", "/"]);
+ db.run(
+ `INSERT INTO session_v2 (id, project_id, parent_id, slug, directory, path, title, version, cost, tokens_input, tokens_output, tokens_reasoning,
+ tokens_cache_read, tokens_cache_write, agent, model, time_created, time_updated) VALUES (?, ?, ?, ?, ?, '', ?, '2.0.18', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ [s.id, s.projectID ?? "global", s.parentID ?? null, s.id.slice(-8).toLowerCase(), directory, s.title ?? null, s.cost ?? 0,
+ s.tokens?.input ?? 0, s.tokens?.output ?? 0, s.tokens?.reasoning ?? 0, s.tokens?.cache?.read ?? 0, s.tokens?.cache?.write ?? 0,
+ s.agent ?? null, s.model ? JSON.stringify(s.model) : null, s.time.created, s.time.updated],
+ );
+ node.messages.forEach((message, seq) => {
+ const { id, type, ...data } = message;
+ db.run(`INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?, ?, ?)`,
+ [id, s.id, type, seq, message.time?.created ?? 0, message.time?.created ?? 0, JSON.stringify(data)]);
+ });
+ }
+ }
+ db.close();
+}
+
+/** HOME with a 2.x store at <data>/opencode/opencode.db and a project folder. */
+function makeHome(trees: Tree[]): { home: string; env: NodeJS.ProcessEnv; project: string; store: string } {
+ const home = mkdtempSync(join(tmpdir(), "engine2-import-"));
+ roots.push(home);
+ const project = join(home, "proj");
+ mkdirSync(project, { recursive: true });
+ const env = {
+ PATH: process.env.PATH,
+ HOME: home,
+ XDG_DATA_HOME: join(home, ".local", "share"),
+ XDG_CONFIG_HOME: join(home, ".config"),
+ XDG_STATE_HOME: join(home, ".local", "state"),
+ XDG_CACHE_HOME: join(home, ".cache"),
+ OPENCODE_SERVER_PASSWORD: "engine-secret",
+ };
+ const store = engine2StorePath(env)!;
+ write2xStore(store, trees, project);
+ return { home, env, project, store };
+}
+
+/** An engine stand-in: records each `import <file>` (document, folder, environment) and reports it imported. */
+function fakeEngine(home: string, failFor: string[] = []): { bin: string; calls: () => Array<{ id: string; cwd: string; env: string; doc: any }> } {
+ const dir = join(home, "fake-engine");
+ mkdirSync(join(dir, "calls"), { recursive: true });
+ const bin = join(dir, "opencode");
+ writeFileSync(bin, `#!/bin/sh
+[ "$1" = import ] || exit 2
+id=$(basename "$2" .json)
+for bad in ${failFor.join(" ")}; do [ "$id" = "$bad" ] && { echo "Error: decode failed" >&2; exit 1; }; done
+cp "$2" "${dir}/calls/$id.json"
+pwd > "${dir}/calls/$id.cwd"
+env > "${dir}/calls/$id.env"
+echo "Imported session: $id"
+`);
+ chmodSync(bin, 0o755);
+ return {
+ bin,
+ calls: () => readdirSync(join(dir, "calls")).filter((name) => name.endsWith(".json")).map((name) => {
+ const id = name.slice(0, -5);
+ return {
+ id,
+ cwd: readFileSync(join(dir, "calls", `${id}.cwd`), "utf8").trim(),
+ env: readFileSync(join(dir, "calls", `${id}.env`), "utf8"),
+ doc: JSON.parse(readFileSync(join(dir, "calls", name), "utf8")),
+ };
+ }),
+ };
+}
+
+describe("2.x session import (stand-in engine)", () => {
+ test("every 2.x session is imported once, in its folder, as the 1.x export document", async () => {
+ const trees = [fixture("v2-p1"), fixture("v2-sub")];
+ const { home, env, project, store } = makeHome(trees);
+ const engine = fakeEngine(home);
+ const ids = trees.flatMap((tree) => flatten(tree).map((node) => node.session.id as string));
+
+ const first = await importEngine2Sessions({ bin: engine.bin, env });
+ expect(first.source).toBe(store);
+ expect(first.imported.sort()).toEqual([...ids].sort());
+ expect(first.failed).toEqual([]);
+ const calls = engine.calls();
+ expect(calls.map((call) => call.id).sort()).toEqual([...ids].sort());
+ for (const call of calls) {
+ expect(call.cwd).toBe(project);
+ // No plugins, no project or user config, no engine password: only the stores are shared.
+ expect(call.env).toContain("OPENCODE_PURE=1");
+ expect(call.env).toContain("OPENCODE_DISABLE_PROJECT_CONFIG=1");
+ expect(call.env).toContain(`XDG_DATA_HOME=${env.XDG_DATA_HOME}`);
+ expect(call.env).not.toContain("engine-secret");
+ expect(call.doc.info.id).toBe(call.id);
+ expect(call.doc.info.directory).toBe(project);
+ for (const message of call.doc.messages) {
+ expect(message.info.sessionID).toBe(call.id);
+ // The 1.x engine lists parts by id: they are numbered in their order.
+ const partIds = message.parts.map((part: { id: string }) => part.id);
+ expect(partIds).toEqual([...partIds].sort());
+ for (const part of message.parts) expect(part.messageID).toBe(message.info.id);
+ }
+ // And messages by creation time, then id.
+ const keys = call.doc.messages.map((message: any) => [message.info.time.created, message.info.id]);
+ expect(keys).toEqual([...keys].sort((a: any, b: any) => a[0] - b[0] || (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0)));
+ }
+ const child = calls.find((call) => call.doc.info.parentID)!;
+ expect(child.doc.info.title).toMatch(/\(@general subagent\)$/);
+
+ const manifest = JSON.parse(readFileSync(join(env.XDG_DATA_HOME!, "omnirush", ENGINE2_IMPORT_MANIFEST), "utf8"));
+ expect(Object.keys(manifest.imported).sort()).toEqual([...ids].sort());
+
+ // The next launch finds nothing to do, and the 2.x store is untouched.
+ const second = await importEngine2Sessions({ bin: engine.bin, env });
+ expect(second.imported).toEqual([]);
+ expect(second.done).toBe(ids.length);
+ expect(engine.calls()).toHaveLength(ids.length);
+ expect((await readEngine2Session(store, ids[0]!))?.messages.length).toBe(trees[0]!.messages.length);
+ });
+
+ test("a failed session is tried again on the next launches, at most three times; a missing folder waits for it", async () => {
+ const trees = [fixture("v2-p1"), fixture("v2-tools")];
+ const { home, env, project } = makeHome(trees);
+ const bad = trees[0]!.session.id as string;
+ const engine = fakeEngine(home, [bad]);
+ for (let launch = 0; launch < 4; launch++) await importEngine2Sessions({ bin: engine.bin, env });
+ const manifest = JSON.parse(readFileSync(join(env.XDG_DATA_HOME!, "omnirush", ENGINE2_IMPORT_MANIFEST), "utf8"));
+ expect(manifest.failed[bad].attempts).toBe(3);
+ expect(manifest.failed[bad].error).toContain("decode failed");
+ expect(Object.keys(manifest.imported)).toEqual([trees[1]!.session.id]);
+
+ rmSync(project, { recursive: true, force: true });
+ const gone = makeHome([fixture("v2-patch")]);
+ rmSync(gone.project, { recursive: true, force: true });
+ const ghost = fakeEngine(gone.home);
+ const skipped = await importEngine2Sessions({ bin: ghost.bin, env: gone.env });
+ expect(skipped.skipped).toEqual([fixture("v2-patch").session.id]);
+ mkdirSync(gone.project, { recursive: true });
+ const back = await importEngine2Sessions({ bin: ghost.bin, env: gone.env });
+ expect(back.imported).toEqual([fixture("v2-patch").session.id]);
+ });
+
+ test("off under test runs, with OMNIRUSH_ENGINE2_IMPORT=0 and with an explicit OPENCODE_DB", async () => {
+ expect(engine2ImportDisabled({ NODE_ENV: "test" })).toBe(true);
+ expect(engine2ImportDisabled({ NODE_ENV: "test", OMNIRUSH_ENGINE2_IMPORT: "1" })).toBe(false);
+ expect(engine2ImportDisabled({ OMNIRUSH_ENGINE2_IMPORT: "0" })).toBe(true);
+ expect(engine2ImportDisabled({ OPENCODE_DB: "/x/db" })).toBe(true);
+ expect(engine2ImportDisabled({})).toBe(false);
+ const { home, env } = makeHome([fixture("v2-p1")]);
+ const engine = fakeEngine(home);
+ expect((await importEngine2Sessions({ bin: engine.bin, env: { ...env, OMNIRUSH_ENGINE2_IMPORT: "0" } })).imported).toEqual([]);
+ expect(engine.calls()).toEqual([]);
+ });
+
+ test("a store without the 2.x tables (a 1.x store) is left alone", async () => {
+ const home = mkdtempSync(join(tmpdir(), "engine2-import-v1-"));
+ roots.push(home);
+ const env = { HOME: home, XDG_DATA_HOME: join(home, "data") };
+ mkdirSync(join(home, "data", "opencode"), { recursive: true });
+ const db = new Database(join(home, "data", "opencode", "opencode.db"), { create: true });
+ db.run("CREATE TABLE session (id text PRIMARY KEY)");
+ db.close();
+ const engine = fakeEngine(home);
+ expect(await importEngine2Sessions({ bin: engine.bin, env })).toMatchObject({ imported: [], failed: [], skipped: [] });
+ expect(existsSync(join(home, "data", "omnirush", ENGINE2_IMPORT_MANIFEST))).toBe(false);
+ });
+
+ test("sign-in files move over once and never replace the engine's own", () => {
+ const home = mkdtempSync(join(tmpdir(), "engine2-import-auth-"));
+ roots.push(home);
+ const env = { HOME: home, XDG_DATA_HOME: join(home, "data") };
+ mkdirSync(join(home, "data", "opencode"), { recursive: true });
+ mkdirSync(join(home, "data", "omnirush"), { recursive: true });
+ writeFileSync(join(home, "data", "opencode", "auth.json"), '{"openai":{"type":"api","key":"k"}}');
+ writeFileSync(join(home, "data", "opencode", "mcp-auth.json"), '{"old":true}');
+ writeFileSync(join(home, "data", "omnirush", "mcp-auth.json"), '{"new":true}');
+ expect(adoptOpencodeCredentials(env)).toEqual(["auth.json"]);
+ expect(readFileSync(join(home, "data", "omnirush", "auth.json"), "utf8")).toContain('"openai"');
+ expect(readFileSync(join(home, "data", "omnirush", "mcp-auth.json"), "utf8")).toBe('{"new":true}');
+ expect(adoptOpencodeCredentials(env)).toEqual([]);
+ });
+
+ test("a step that never finished is closed, its running tool an aborted error", () => {
+ const tree = fixture("v2-p1");
+ const step = structuredClone(tree.messages.find((message) => message.type === "assistant" && (message.content ?? []).some((entry: any) => entry.type === "tool")))!;
+ delete step.time.completed;
+ for (const entry of step.content) if (entry.type === "tool") entry.state = { status: "running", input: entry.state.input };
+ const document = v1ImportDocument({ session: tree.session, messages: [tree.messages[0]!, step] })!;
+ const reply = document.messages[1]!;
+ expect(reply.info.role).toBe("assistant");
+ expect((reply.info.time as { completed?: number }).completed).toBeNumber();
+ const tool = reply.parts.find((part) => part.type === "tool") as { state: { status: string; error: string } };
+ expect(tool.state).toMatchObject({ status: "error", error: "Tool execution aborted" });
+ });
+});
+
+// ---- the bundled engine -------------------------------------------------------------------
+
+const repoRoot = resolve(import.meta.dir, "../../../..");
+function findSidecar(): string | null {
+ const arch = process.arch === "arm64" ? "aarch64" : "x86_64";
+ const name = process.platform === "darwin" ? `opencode-${arch}-apple-darwin` : process.platform === "linux" ? `opencode-${arch}-unknown-linux-gnu` : "";
+ const candidate = join(repoRoot, "apps/desktop/resources/sidecars", name);
+ return name && existsSync(candidate) ? candidate : null;
+}
+const enginePath = findSidecar();
+const describeEngine = enginePath ? describe : describe.skip;
+
+describeEngine("2.x session import into the bundled engine", () => {
+ let serve: ReturnType<typeof spawn> | null = null;
+ let url = "";
+ let setup: ReturnType<typeof makeHome>;
+ const trees = [fixture("v2-p1"), fixture("v2-sub"), fixture("v2-patch"), fixture("v2-tools"), fixture("v2-nest")];
+
+ beforeAll(async () => {
+ setup = makeHome(trees);
+ const result = await importEngine2Sessions({ bin: enginePath!, env: { ...process.env, ...setup.env, OMNIRUSH_ENGINE2_IMPORT: "1" } });
+ expect(result.failed).toEqual([]);
+ serve = spawn(enginePath!, ["serve", "--hostname", "127.0.0.1", "--port", "0"], {
+ cwd: setup.project,
+ env: { ...process.env, ...setup.env, OPENCODE_SERVER_PASSWORD: "pw", OPENCODE_DISABLE_AUTOUPDATE: "1", OPENCODE_DISABLE_MODELS_FETCH: "1" },
+ stdio: ["ignore", "pipe", "pipe"],
+ });
+ url = await new Promise<string>((done, fail) => {
+ let output = "";
+ const timer = setTimeout(() => fail(new Error(`engine did not start: ${output}`)), 60_000);
+ serve!.stdout!.on("data", (chunk) => {
+ output += String(chunk);
+ const match = output.match(/listening on (http:\/\/\S+)/);
+ if (match) {
+ clearTimeout(timer);
+ done(match[1]!);
+ }
+ });
+ });
+ }, 180_000);
+
+ afterAll(() => {
+ serve?.kill("SIGKILL");
+ });
+
+ const get = async (path: string) => {
+ const target = new URL(path, url);
+ target.searchParams.set("directory", setup.project);
+ const response = await fetch(target, { headers: { authorization: `Basic ${Buffer.from("opencode:pw").toString("base64")}` } });
+ expect(response.status).toBe(200);
+ return response.json() as Promise<any>;
+ };
+
+ test("the 1.x engine lists every imported session and serves its messages in order", async () => {
+ const sessions = await get("/session");
+ const ids = trees.flatMap((tree) => flatten(tree).map((node) => node.session.id));
+ expect(sessions.map((session: { id: string }) => session.id).sort()).toEqual([...ids].sort());
+ for (const tree of trees) {
+ for (const node of flatten(tree)) {
+ const stored = (await readEngine2Session(setup.store, node.session.id))!;
+ const expected = v1ImportDocument(stored)!;
+ const served = await get(`/session/${node.session.id}/message`);
+ expect(served.map((message: any) => message.info.id)).toEqual(expected.messages.map((message) => message.info.id));
+ expect(served.map((message: any) => message.parts.map((part: any) => part.type)))
+ .toEqual(expected.messages.map((message) => message.parts.map((part) => part.type)));
+ const tools = (list: any[]) => list.flatMap((message) => message.parts).filter((part) => part.type === "tool")
+ .map((part) => [part.tool, part.state.status, part.state.output ?? part.state.error]);
+ expect(tools(served)).toEqual(tools(expected.messages));
+ }
+ }
+ const child = sessions.find((session: { parentID?: string }) => session.parentID);
+ expect(child.title).toMatch(/subagent\)$/);
+ }, 60_000);
+});
diff --git a/apps/server/src/engine2/import.ts b/apps/server/src/engine2/import.ts
new file mode 100644
index 00000000..2bce8f25
--- /dev/null
+++ b/apps/server/src/engine2/import.ts
@@ -0,0 +1,418 @@
+/**
+ * One-time import of the sessions the opencode 2.x engine stored into the
+ * 1.x engine's store.
+ *
+ * OmniRush.ai desktop 2.2.0 – 3.x ran the opencode 2.x engine, which kept its
+ * sessions in `<data>/opencode/opencode.db` (2.x tables: `session_v2`,
+ * `session_message`; on its first start it had moved the 1.x sessions of
+ * earlier releases in there too). The app now runs OmniRush.ai's build of the
+ * 1.x engine (1.18.32), whose store is `<data>/omnirush/opencode.db` and which
+ * cannot read the 2.x tables. So that no session is lost, each 2.x session is
+ * copied once into the 1.x store:
+ *
+ * - the 2.x store is opened read-only and never changed (engine2/store.ts),
+ * so an older OmniRush.ai still opens it;
+ * - each session becomes the 1.x export document `{info, messages:[{info, parts}]}`
+ * (engine2/shapes.ts) and is written by the engine itself, `opencode import <file>`,
+ * run in the session's folder (the 1.x engine keys sessions by project), with
+ * no plugins, no project config and no network;
+ * - the import keeps every id, so a session imported twice is written once;
+ * - what was imported, skipped (its folder is gone) or failed is recorded in
+ * `<data>/omnirush/desktop-engine2-import.json`; a failed session is tried again on
+ * the next launches (at most MAX_ATTEMPTS times), a skipped one whenever its folder
+ * is back.
+ *
+ * Runs in the background after the engine started; sessions appear in the
+ * app's lists as they are imported.
+ */
+import { spawn } from "node:child_process";
+import { chmodSync, closeSync, constants as fsConstants, copyFileSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
+import { homedir, tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { v1Messages, v1Session, type V1Message } from "./shapes.js";
+import { isEngine2Store, listEngine2Sessions, readEngine2Session, type Engine2StoredSession } from "./store.js";
+import { isRecord, num, record, str, type JsonRecord } from "./util.js";
+
+export const ENGINE2_IMPORT_MANIFEST = "desktop-engine2-import.json";
+const MAX_ATTEMPTS = 3;
+const IMPORT_TIMEOUT_MS = 120_000;
+const LOCK_STALE_MS = 30 * 60_000;
+
+/** The part types the 1.x engine stores (SessionV1.Part); anything else is left out. */
+const V1_PART_TYPES = new Set(["text", "reasoning", "file", "tool", "step-start", "step-finish", "snapshot", "patch", "agent", "retry", "compaction", "subtask"]);
+
+export type Engine2ImportLog = (level: "info" | "warn", message: string, attributes?: Record<string, unknown>) => void;
+
+type ManifestEntry = { at: number; messages?: number; attempts?: number; error?: string; reason?: string };
+type Manifest = {
+ version: 1;
+ source: string;
+ imported: Record<string, ManifestEntry>;
+ failed: Record<string, ManifestEntry>;
+ skipped: Record<string, ManifestEntry>;
+};
+
+export type Engine2ImportResult = {
+ source: string | null;
+ imported: string[];
+ skipped: string[];
+ failed: string[];
+ /** Already imported on an earlier launch. */
+ done: number;
+};
+
+export type Engine2ImportOptions = {
+ /** The 1.x engine binary. */
+ bin: string;
+ /** The engine's environment (HOME / XDG_DATA_HOME decide both stores). */
+ env: NodeJS.ProcessEnv;
+ log?: Engine2ImportLog;
+ /** Tests: where the 2.x store and the manifest are. */
+ sourcePath?: string;
+ targetDataDir?: string;
+ timeoutMs?: number;
+};
+
+function dataHome(env: NodeJS.ProcessEnv): string {
+ const xdg = env.XDG_DATA_HOME?.trim();
+ if (xdg) return xdg;
+ return join(env.HOME?.trim() || homedir(), ".local", "share");
+}
+
+/** The 2.x engine's store, as the 2.x engine resolved it; null when an explicit store is in use. */
+export function engine2StorePath(env: NodeJS.ProcessEnv): string | null {
+ if (env.OPENCODE_DB?.trim()) return null;
+ return join(dataHome(env), "opencode", "opencode.db");
+}
+
+/** The 1.x engine's data directory (OmniRush.ai's build keeps its store in `<data>/omnirush`). */
+export function engine1DataDir(env: NodeJS.ProcessEnv): string {
+ return join(dataHome(env), "omnirush");
+}
+
+/**
+ * Whether the import is switched off (OMNIRUSH_ENGINE2_IMPORT=0, or a test
+ * run without OMNIRUSH_ENGINE2_IMPORT=1: tests never touch the real stores) or
+ * cannot apply (an explicit OPENCODE_DB).
+ */
+export function engine2ImportDisabled(env: NodeJS.ProcessEnv): boolean {
+ const flag = env.OMNIRUSH_ENGINE2_IMPORT?.trim();
+ if (flag === "0" || env.OPENCODE_DB?.trim()) return true;
+ return env.NODE_ENV === "test" && flag !== "1";
+}
+
+/** The tool states 1.x keeps for a call that never finished: an aborted call is an error. */
+function settleTool(part: JsonRecord, end: number): JsonRecord {
+ const state = record(part, "state");
+ const status = str(state, "status");
+ if (!state || (status !== "pending" && status !== "running")) return part;
+ const start = num(record(state, "time"), "start") ?? end;
+ return {
+ ...part,
+ state: {
+ status: "error",
+ input: isRecord(state.input) ? state.input : {},
+ error: "Tool execution aborted",
+ ...(isRecord(state.metadata) ? { metadata: state.metadata } : {}),
+ time: { start, end: Math.max(start, end) },
+ },
+ };
+}
+
+/** One message as the 1.x engine stores it: only 1.x part types, finished steps closed. */
+function storedMessage(message: V1Message): V1Message {
+ const info = { ...message.info };
+ const time = isRecord(info.time) ? { ...info.time } : {};
+ const created = num(time, "created") ?? 0;
+ let end = created;
+ for (const part of message.parts) {
+ const partTime = record(part, "time") ?? record(record(part, "state"), "time");
+ end = Math.max(end, num(partTime, "end") ?? 0, num(partTime, "start") ?? 0);
+ }
+ if (info.role === "assistant" && num(time, "completed") === undefined) {
+ time.completed = end;
+ info.time = time;
+ }
+ const parts = message.parts
+ .filter((part) => V1_PART_TYPES.has(String(part.type)))
+ .map((part) => (part.type === "tool" ? settleTool(part, num(time, "completed") ?? end) : part));
+ return { info, parts };
+}
+
+/**
+ * The 1.x engine lists a message's parts by part id, and a session's messages
+ * by creation time, then id. Part ids are renumbered in their order
+ * (`prt_<message>_<ordinal>`), and a message that would sort before the one it
+ * follows (a user-run shell command's prompt and reply share a creation time)
+ * is created a millisecond after it.
+ */
+function inStoredOrder(messages: V1Message[]): V1Message[] {
+ let previous: { created: number; id: string } | null = null;
+ return messages.map((message) => {
+ const id = String(message.info.id ?? "");
+ const time = isRecord(message.info.time) ? { ...message.info.time } : {};
+ let created = num(time, "created") ?? 0;
+ if (previous && (created < previous.created || (created === previous.created && id <= previous.id))) {
+ created = previous.created + 1;
+ time.created = created;
+ if (num(time, "completed") !== undefined && num(time, "completed")! < created) time.completed = created;
+ }
+ previous = { created, id };
+ const core = id.startsWith("msg_") ? id.slice(4) : id;
+ const parts = message.parts.map((part, index) => ({ ...part, id: `prt_${core}_${String(index).padStart(4, "0")}` }));
+ return { info: { ...message.info, time }, parts };
+ });
+}
+
+/** A stored 2.x session as the 1.x export document `opencode import` reads. */
+export function v1ImportDocument(stored: Engine2StoredSession): { info: JsonRecord; messages: V1Message[] } | null {
+ const info = v1Session(stored.session, { version: str(stored.session, "version") ?? "2" });
+ if (!info) return null;
+ const directory = str(info, "directory") || undefined;
+ const model = record(stored.session, "model");
+ const variant = str(model, "variant");
+ const messages = v1Messages(stored.messages, {
+ sessionID: String(info.id),
+ directory,
+ root: stored.worktree ?? "/",
+ agent: str(stored.session, "agent"),
+ model: model && str(model, "id") && str(model, "providerID")
+ ? { providerID: str(model, "providerID")!, modelID: str(model, "id")!, ...(variant && variant !== "default" ? { variant } : {}) }
+ : undefined,
+ child: Boolean(str(stored.session, "parentID")),
+ }).map(storedMessage);
+ return { info, messages: inStoredOrder(messages) };
+}
+
+function readManifest(path: string, source: string): Manifest {
+ try {
+ const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
+ if (isRecord(parsed) && parsed.version === 1) {
+ return {
+ version: 1,
+ source,
+ imported: isRecord(parsed.imported) ? (parsed.imported as Manifest["imported"]) : {},
+ failed: isRecord(parsed.failed) ? (parsed.failed as Manifest["failed"]) : {},
+ skipped: isRecord(parsed.skipped) ? (parsed.skipped as Manifest["skipped"]) : {},
+ };
+ }
+ } catch {
+ // none yet
+ }
+ return { version: 1, source, imported: {}, failed: {}, skipped: {} };
+}
+
+function writeManifest(path: string, manifest: Manifest): void {
+ mkdirSync(dirname(path), { recursive: true });
+ const temporary = `${path}.${process.pid}.tmp`;
+ writeFileSync(temporary, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
+ renameSync(temporary, path);
+}
+
+/** An exclusive lock beside the manifest, so two app processes never import at once. */
+function takeLock(path: string): (() => void) | null {
+ const lock = `${path}.lock`;
+ try {
+ if (existsSync(lock) && Date.now() - statSync(lock).mtimeMs > LOCK_STALE_MS) unlinkSync(lock);
+ } catch {
+ // raced: the open below decides
+ }
+ try {
+ mkdirSync(dirname(lock), { recursive: true });
+ closeSync(openSync(lock, "wx"));
+ } catch {
+ return null;
+ }
+ return () => {
+ try {
+ unlinkSync(lock);
+ } catch {
+ // already gone
+ }
+ };
+}
+
+const SECRET_ENV = /^(OPENCODE_SERVER_(USERNAME|PASSWORD)|OPENCODE_PASSWORD|OMNIRUSH_ENCRYPTION_KEY|OMNIRUSH_(ACCESS|REFRESH)_TOKEN)$/;
+
+/** The engine environment for `opencode import`: same stores, no plugins, project or user config, no network. */
+function importEnv(env: NodeJS.ProcessEnv, configDir: string): NodeJS.ProcessEnv {
+ const out: NodeJS.ProcessEnv = {};
+ for (const [name, value] of Object.entries(env)) if (typeof value === "string" && !SECRET_ENV.test(name)) out[name] = value;
+ delete out.OPENCODE_CONFIG_CONTENT;
+ out.OPENCODE_CONFIG = join(configDir, "opencode.json");
+ out.OPENCODE_CONFIG_DIR = configDir;
+ out.OPENCODE_DISABLE_PROJECT_CONFIG = "1";
+ out.OPENCODE_PURE = "1";
+ out.OPENCODE_DISABLE_AUTOUPDATE = "1";
+ out.OPENCODE_DISABLE_MODELS_FETCH = "1";
+ out.OPENCODE_DISABLE_LSP_DOWNLOAD = "1";
+ out.OPENCODE_DISABLE_DEFAULT_PLUGINS = "1";
+ out.npm_config_audit = "false";
+ return out;
+}
+
+function runImport(bin: string, file: string, cwd: string, env: NodeJS.ProcessEnv, timeoutMs: number): Promise<{ ok: boolean; output: string }> {
+ return new Promise((resolve) => {
+ let output = "";
+ let settled = false;
+ const done = (ok: boolean) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolve({ ok, output: output.slice(-2_000) });
+ };
+ let child: ReturnType<typeof spawn>;
+ try {
+ child = spawn(bin, ["import", file], { cwd, env, stdio: ["ignore", "pipe", "pipe"] });
+ } catch (error) {
+ output = error instanceof Error ? error.message : String(error);
+ resolve({ ok: false, output });
+ return;
+ }
+ const timer = setTimeout(() => {
+ output += `\nimport timed out after ${timeoutMs}ms`;
+ try {
+ child.kill("SIGKILL");
+ } catch {
+ // gone
+ }
+ done(false);
+ }, timeoutMs);
+ child.stdout?.on("data", (chunk) => {
+ output += chunk.toString();
+ });
+ child.stderr?.on("data", (chunk) => {
+ output += chunk.toString();
+ });
+ child.once("error", (error) => {
+ output += error.message;
+ done(false);
+ });
+ child.once("close", (code) => done(code === 0));
+ });
+}
+
+/** Imports every 2.x session not imported yet. Never throws; a run already in progress elsewhere is skipped. */
+export async function importEngine2Sessions(options: Engine2ImportOptions): Promise<Engine2ImportResult> {
+ const log = options.log ?? (() => undefined);
+ const source = options.sourcePath ?? engine2StorePath(options.env);
+ const result: Engine2ImportResult = { source, imported: [], skipped: [], failed: [], done: 0 };
+ if (!source || (!options.sourcePath && engine2ImportDisabled(options.env))) return result;
+ if (!(await isEngine2Store(source))) return result;
+ const manifestPath = join(options.targetDataDir ?? engine1DataDir(options.env), ENGINE2_IMPORT_MANIFEST);
+ const release = takeLock(manifestPath);
+ if (!release) {
+ log("info", "engine2 session import already running elsewhere");
+ return result;
+ }
+ const work = mkdtempSync(join(tmpdir(), "omnirush-engine2-import-"));
+ try {
+ const configDir = join(work, "config");
+ mkdirSync(configDir, { recursive: true });
+ writeFileSync(join(configDir, "opencode.json"), "{}\n", "utf8");
+ const env = importEnv(options.env, configDir);
+ const manifest = readManifest(manifestPath, source);
+ let ids: string[];
+ try {
+ ids = await listEngine2Sessions(source);
+ } catch (error) {
+ log("warn", "engine2 session store could not be read", { error: error instanceof Error ? error.message : String(error) });
+ return result;
+ }
+ for (const id of ids) {
+ if (manifest.imported[id]) {
+ result.done += 1;
+ continue;
+ }
+ const attempts = manifest.failed[id]?.attempts ?? 0;
+ if (attempts >= MAX_ATTEMPTS) {
+ result.failed.push(id);
+ continue;
+ }
+ let document: ReturnType<typeof v1ImportDocument> = null;
+ try {
+ const stored = await readEngine2Session(source, id);
+ document = stored ? v1ImportDocument(stored) : null;
+ } catch (error) {
+ manifest.failed[id] = { at: Date.now(), attempts: attempts + 1, error: error instanceof Error ? error.message : String(error) };
+ result.failed.push(id);
+ writeManifest(manifestPath, manifest);
+ continue;
+ }
+ if (!document) continue;
+ const directory = String(document.info.directory ?? "");
+ if (!directory || !existsSync(directory) || !statSync(directory).isDirectory()) {
+ manifest.skipped[id] = { at: Date.now(), reason: "directory_missing" };
+ result.skipped.push(id);
+ writeManifest(manifestPath, manifest);
+ continue;
+ }
+ const file = join(work, `${id}.json`);
+ writeFileSync(file, JSON.stringify(document), "utf8");
+ const run = await runImport(options.bin, file, directory, env, options.timeoutMs ?? IMPORT_TIMEOUT_MS);
+ rmSync(file, { force: true });
+ if (run.ok && run.output.includes(`Imported session: ${id}`)) {
+ manifest.imported[id] = { at: Date.now(), messages: document.messages.length };
+ delete manifest.failed[id];
+ delete manifest.skipped[id];
+ result.imported.push(id);
+ } else {
+ manifest.failed[id] = { at: Date.now(), attempts: attempts + 1, error: run.output.trim().split("\n").slice(-3).join(" ").slice(0, 500) };
+ result.failed.push(id);
+ log("warn", "engine2 session import failed", { session: id, attempts: attempts + 1 });
+ }
+ writeManifest(manifestPath, manifest);
+ }
+ if (result.imported.length || result.failed.length || result.skipped.length) {
+ log("info", "engine2 session import finished", {
+ imported: result.imported.length,
+ skipped: result.skipped.length,
+ failed: result.failed.length,
+ done: result.done,
+ });
+ }
+ return result;
+ } catch (error) {
+ log("warn", "engine2 session import stopped", { error: error instanceof Error ? error.message : String(error) });
+ return result;
+ } finally {
+ rmSync(work, { recursive: true, force: true });
+ release();
+ }
+}
+
+/**
+ * Provider and MCP sign-ins the opencode engine kept in its data directory
+ * (`auth.json`, `mcp-auth.json` in `<data>/opencode`, shared with the earlier
+ * 1.x and 2.x engines): copied once into OmniRush.ai's engine data directory,
+ * where it now reads them. A file already there is never replaced.
+ */
+export function adoptOpencodeCredentials(env: NodeJS.ProcessEnv, log?: Engine2ImportLog): string[] {
+ if (engine2ImportDisabled(env)) return [];
+ const from = join(dataHome(env), "opencode");
+ const to = engine1DataDir(env);
+ const copied: string[] = [];
+ for (const name of ["auth.json", "mcp-auth.json"]) {
+ const source = join(from, name);
+ const target = join(to, name);
+ try {
+ if (!existsSync(source) || existsSync(target)) continue;
+ mkdirSync(to, { recursive: true });
+ copyFileSync(source, target, fsConstants.COPYFILE_EXCL);
+ chmodSync(target, 0o600);
+ copied.push(name);
+ } catch (error) {
+ log?.("warn", "engine sign-in file could not be copied", { file: name, error: error instanceof Error ? error.message : String(error) });
+ }
+ }
+ if (copied.length) log?.("info", "engine sign-ins copied from the opencode data directory", { files: copied.join(",") });
+ return copied;
+}
+
+let running: Promise<Engine2ImportResult> | null = null;
+
+/** Starts the import once per process (later calls get the same run). */
+export function startEngine2SessionImport(options: Engine2ImportOptions): Promise<Engine2ImportResult> {
+ running ??= importEngine2Sessions(options);
+ return running;
+}
diff --git a/apps/server/src/engine2/shapes.test.ts b/apps/server/src/engine2/shapes.test.ts
index 9f958ed9..618174a7 100644
--- a/apps/server/src/engine2/shapes.test.ts
+++ b/apps/server/src/engine2/shapes.test.ts
@@ -2,8 +2,7 @@ import { describe, expect, test } from "bun:test";
import { readFileSync } from "node:fs";
import { join } from "node:path";
-import { EventTranslator } from "./events.js";
-import { partId, v1Messages, v1PermissionRequest, v1QuestionRequest, v1Session, v1ToolInput, v1ToolName, v2FormAnswer, v2ToolInput, type V1Message } from "./shapes.js";
+import { partId, v1Messages, v1Session, v1ToolInput, v1ToolName, type V1Message } from "./shapes.js";
/**
* Fixtures: the same scripted conversations run on the 1.x engine (1.18.32)
@@ -22,14 +21,14 @@ function typeOf(value: unknown): string {
return typeof value;
}
-/** Part types only the 2.x engine records (context records carried as parts, engine2/native.ts). */
+/** Part types only the 2.x engine records; the import never writes them. */
const NATIVE_PART_TYPES = new Set(["agent-switched", "model-switched", "location-switched", "system", "idle"]);
/**
- * Every 1.x key path the adapter's record lacks or writes with another value
- * type ("only in 1.x" / type mismatches), and the key paths it adds (the 2.x
- * engine's own fields, "only in adapter"). Parts are paired after leaving out
- * the 2.x-only part types.
+ * Every 1.x key path the converted record lacks or writes with another value
+ * type ("only in 1.x" / type mismatches), and the key paths it adds ("only in
+ * adapter"). Parts are paired after leaving out the 2.x-only part types (and
+ * a 2.x-only part type in the converted record is reported).
*/
function shapeDiff(a: unknown, b: unknown, path = "$", out: string[] = []): string[] {
if (typeOf(a) !== typeOf(b)) {
@@ -102,12 +101,14 @@ describe("2.x messages in the 1.x shape (uploaded trace parity)", () => {
const out: string[] = [];
compareTrees(fixture(`v1-${scenario}`), mapTree(fixture(`v2-${scenario}`)), "root", out);
expect(regressions(out)).toEqual([]);
+ // No record of a type the 1.x engine never wrote.
+ expect(out.filter((line) => line.includes("[type="))).toEqual([]);
});
}
test("p1: the uploaded messages, field for field", () => {
const [user, first, second, third, answer] = mapTree(fixture("v2-p1")).messages;
- // 1.x fields, exactly; the 2.x engine's own fields sit next to them (next test).
+ // 1.x fields, exactly.
expect(pick(user!.info, ["id", "sessionID", "role", "time", "summary", "agent", "model"])).toEqual({
id: "msg_0e0eb02300010Ie6K3lQAqUici",
sessionID: "ses_f1f14fdf6ffe32y5eLxrDN6MFs",
@@ -128,7 +129,7 @@ describe("2.x messages in the 1.x shape (uploaded trace parity)", () => {
id: "msg_0e0eb029c001Gb432955hHZq2J",
sessionID: "ses_f1f14fdf6ffe32y5eLxrDN6MFs",
role: "assistant",
- time: { created: 1790479893170, completed: 1790479893443, streamed: 1790479893305 },
+ time: { created: 1790479893170, completed: 1790479893443 },
parentID: "msg_0e0eb02300010Ie6K3lQAqUici",
modelID: "mock-model",
providerID: "mock",
@@ -152,9 +153,8 @@ describe("2.x messages in the 1.x shape (uploaded trace parity)", () => {
input: { command: "ls -a", description: "List files" },
output: ".\n..\n",
title: "List files",
- metadata: { output: ".\n..\n", truncated: false, exit: 0, status: "completed" },
+ metadata: { output: ".\n..\n", truncated: false, exit: 0 },
time: { start: 1790479893299, end: 1790479893435 },
- content: [{ type: "text", text: ".\n..\n" }],
},
});
expect(first!.parts[3]).toEqual({
@@ -174,10 +174,10 @@ describe("2.x messages in the 1.x shape (uploaded trace parity)", () => {
const edit = third!.parts.find((part) => part.type === "tool") as { tool: string; state: { input: unknown; metadata: Record<string, unknown> } };
expect(edit.tool).toBe("edit");
expect(edit.state.input).toEqual({ filePath: "/work/proj/notes.md", oldString: "line one", newString: "line one\nline two" });
- expect(Object.keys(edit.state.metadata)).toEqual(["diagnostics", "diff", "filediff", "truncated", "files"]);
+ expect(Object.keys(edit.state.metadata)).toEqual(["diagnostics", "diff", "filediff", "truncated"]);
expect(edit.state.metadata.filediff).toMatchObject({ file: "/work/proj/notes.md", additions: 1, deletions: 0 });
- // The turn's 2.x idle marker (its outcome) closes the last reply as a part of its own type.
- expect(answer!.parts.map((part) => part.type)).toEqual(["step-start", "reasoning", "text", "step-finish", "idle"]);
+ // Only 1.x part types: the turn's 2.x idle marker is not written.
+ expect(answer!.parts.map((part) => part.type)).toEqual(["step-start", "reasoning", "text", "step-finish"]);
expect(answer!.info.finish).toBe("stop");
});
@@ -209,101 +209,6 @@ describe("2.x messages in the 1.x shape (uploaded trace parity)", () => {
});
});
-describe("the 2.x engine's own fields ride along (additive)", () => {
- test("p1: step, tool and turn records keep what 2.x recorded", () => {
- const [user, first, , third, answer] = mapTree(fixture("v2-p1")).messages;
- expect(user!.info).toMatchObject({ type: "user", text: "PARITY-1 create the notes file" });
- expect(first!.info).toMatchObject({
- type: "assistant",
- model: { id: "mock-model", providerID: "mock" },
- rawFinish: "tool_calls",
- time: { created: 1790479893170, streamed: 1790479893305, completed: 1790479893443 },
- });
- const shell = first!.parts[2] as Record<string, any>;
- expect(shell).toMatchObject({
- tool: "bash",
- name: "shell",
- executed: false,
- time: { created: 1790479893236, ran: 1790479893299, completed: 1790479893435 },
- state: { content: [{ type: "text", text: ".\n..\n" }], metadata: { status: "completed" } },
- });
- const reasoning = first!.parts[1] as Record<string, any>;
- expect(reasoning).toMatchObject({ state: { reasoningField: "reasoning_content" }, time: { created: 1790479893188, completed: 1790479893285 } });
- const edit = third!.parts.find((part) => part.type === "tool") as Record<string, any>;
- // Native input keys the 1.x input names differently, and the native file list.
- expect(edit.state.v2).toEqual({ input: { path: "/work/proj/notes.md" } });
- expect(edit.state.metadata.files[0]).toMatchObject({ file: "notes.md", status: "modified", additions: 1, deletions: 0 });
- // The turn's idle marker, with its outcome.
- expect(answer!.parts.at(-1)).toEqual({
- id: "msg_0e0eb0600001Z6P4VHgDiDmR03",
- time: { created: 1790479894016 },
- type: "idle",
- outcome: "succeeded",
- sessionID: "ses_f1f14fdf6ffe32y5eLxrDN6MFs",
- messageID: answer!.info.id,
- });
- });
-
- test("patch: the model switch before the prompt and the native patch file list", () => {
- const [user, reply] = mapTree(fixture("v2-patch")).messages;
- expect(user!.parts[0]).toMatchObject({ type: "model-switched", model: { id: "gpt-5.1-mock", providerID: "mock" }, messageID: user!.info.id });
- const patch = reply!.parts.find((part) => part.type === "tool") as Record<string, any>;
- expect(patch.name).toBe("patch");
- expect(patch.state.metadata.files.map((file: Record<string, unknown>) => file.relativePath)).toEqual(["work/proj/notes.md", "work/proj/extra.md"]);
- expect(patch.state.metadata.v2.files.map((file: Record<string, unknown>) => [file.file, file.status])).toEqual([["notes.md", "modified"], ["extra.md", "added"]]);
- expect(reply!.info).toMatchObject({ model: { id: "gpt-5.1-mock", providerID: "mock", variant: "default" } });
- expect(reply!.info.variant).toBeUndefined();
- });
-
- test("provider state, snapshots and errors: 1.x values in place, 2.x values next to them", () => {
- const [message] = v1Messages([{
- id: "msg_x",
- type: "assistant",
- agent: "build",
- model: { id: "gpt-6-astra", providerID: "omnirush", variant: "default" },
- snapshot: { start: "aaa", end: "bbb", files: ["math.js"] },
- providerState: { responseId: "resp_1", serviceTier: "default" },
- error: { type: "provider.rate-limit", message: "slow down", status: 429 },
- retry: { attempt: 1, at: 5, error: { type: "provider.rate-limit", message: "slow down" } },
- content: [
- { type: "text", text: "hi", state: { itemId: "msg_item", phase: "final_answer" } },
- {
- type: "tool", id: "call_1", name: "browser_observe", executed: true, providerState: { itemId: "fc_1" }, providerResultState: { ok: 1 },
- state: { status: "completed", input: {}, content: [{ type: "text", text: "seen" }, { type: "file", uri: "data:image/png;base64,QUJD", mime: "image/png" }], metadata: {} },
- time: { created: 1, ran: 2, completed: 3 },
- },
- ],
- finish: "stop",
- time: { created: 1, completed: 4 },
- }], { sessionID: "ses_1", directory: "/work", root: "/work" });
- expect(message!.info).toMatchObject({
- error: { name: "APIError", data: { message: "slow down", statusCode: 429, isRetryable: true }, type: "provider.rate-limit", message: "slow down", status: 429 },
- snapshot: { start: "aaa", end: "bbb", files: ["math.js"] },
- providerState: { responseId: "resp_1", serviceTier: "default" },
- retry: { attempt: 1 },
- });
- const text = message!.parts.find((part) => part.type === "text")!;
- expect(text).toMatchObject({ metadata: { openai: { itemId: "msg_item", phase: "final_answer" } }, state: { itemId: "msg_item", phase: "final_answer" } });
- const tool = message!.parts.find((part) => part.type === "tool") as Record<string, any>;
- expect(tool).toMatchObject({ metadata: { openai: { itemId: "fc_1" } }, providerState: { itemId: "fc_1" }, providerResultState: { ok: 1 }, executed: true });
- // The screenshot's bytes are in state.attachments once; the native content points at them.
- expect(tool.state.attachments[0].url).toBe("data:image/png;base64,QUJD");
- expect(tool.state.content[1]).toEqual({ type: "file", uri: "sameAs:state.attachments[0].url", mime: "image/png" });
- expect(message!.parts.map((part) => part.type)).toEqual(["step-start", "text", "tool", "step-finish", "patch"]);
- });
-
- test("a prompt's image is written once; the native file entry keeps its other fields", () => {
- const [message] = v1Messages([{
- id: "msg_u", type: "user", text: "look", time: { created: 1 },
- files: [{ uri: "data:image/png;base64,QUJD", name: "a.png", mention: { start: 0, end: 4 } }],
- }], { sessionID: "ses_1" });
- const file = message!.parts.find((part) => part.type === "file")!;
- expect(file).toMatchObject({ url: "data:image/png;base64,QUJD", filename: "a.png", name: "a.png", mention: { start: 0, end: 4 } });
- expect(file.uri).toBeUndefined();
- expect(message!.info).toMatchObject({ type: "user", text: "look", files: [{ uri: "sameAs:parts[1].url", name: "a.png" }] });
- });
-});
-
describe("prompts with synthetic notes", () => {
const note = "Attached files were copied into this worker workspace for tool access:\n- image.png: .opencode/omnirush/inbox/chat-attachments/s/1-image.png (file:///home/u/p/.opencode/omnirush/inbox/chat-attachments/s/1-image.png)";
const metadata = { omnirushAttachments: [] };
@@ -326,13 +231,6 @@ describe("prompts with synthetic notes", () => {
expect(message!.parts).toHaveLength(3);
});
- test("live: the enqueued prompt shows the same parts", async () => {
- const translator = new EventTranslator({ version: "2.0.18" });
- const out = await translator.translate({ type: "session.inbox.enqueued", data: { sessionID: "ses_n", inboxID: "msg_note", item: { type: "user", payload } } });
- const parts = out.filter((item) => item.event.type === "message.part.updated").map((item) => item.event.properties.part);
- expect(parts).toMatchObject(expected);
- });
-
test("an image the engine keeps inline reads back as its data: URL, bytes not repeated", () => {
const inline = { data: "AAAA", mime: "image/png", source: { type: "inline" }, name: "image.png" };
const tree = { type: "user", time: { created: 1 }, ...payload, files: [inline] };
@@ -351,150 +249,15 @@ describe("prompts with synthetic notes", () => {
});
});
-describe("live events and read-back agree", () => {
- test("parts built from the 2.x stream carry the ids and fields of the same parts read back", async () => {
- const tree = fixture("v2-sub");
- const translator = new EventTranslator({ version: "2.0.18" });
- const events = JSON.parse(readFileSync(join(import.meta.dir, "fixtures", "v2-sub-events.json"), "utf8")) as unknown[];
- const live = new Map<string, Record<string, unknown>>();
- const types = new Set<string>();
- for (const event of events) {
- for (const item of await translator.translate(event)) {
- types.add(item.event.type);
- if (item.event.type === "message.part.updated") {
- const part = item.event.properties.part as Record<string, unknown>;
- live.set(String(part.id), part);
- }
- }
- }
- for (const type of ["session.created", "message.updated", "message.part.updated", "message.part.delta", "session.status", "session.idle"]) {
- expect(types.has(type)).toBe(true);
- }
- const read = mapTree(tree, { providerID: "mock", modelID: "mock-model" });
- const all = [read, ...read.children].flatMap((node) => node.messages.flatMap((message) => message.parts));
- const assistantParts = all.filter((part) => String(part.id).startsWith("prt_") && (part.type !== "text" || !String(part.id).endsWith("_u0")));
- expect(assistantParts.length).toBeGreaterThan(10);
- for (const part of assistantParts) {
- const seen = live.get(String(part.id));
- expect(seen).toBeDefined();
- expect(seen!.type).toBe(part.type);
- if (part.type === "tool") {
- expect((seen!.state as { status: string }).status).toBe("completed");
- expect(seen!.tool).toBe(part.tool);
- }
- }
- });
-
- test("a read of running sub-agent calls names their child sessions, as their progress did", async () => {
- // The 2.x engine's read of a running subagent call leaves out the child session; only the
- // call's progress events name it. A re-read (the app reloads the session's messages) used to
- // drop the child from the task card until the call ended.
- const tree = fixture("v2-sub");
- const parent = (tree.session as { id: string }).id;
- const running = JSON.parse(JSON.stringify(tree.messages)) as Array<Record<string, unknown>>;
- for (const message of running) {
- for (const entry of (Array.isArray(message.content) ? message.content : []) as Array<Record<string, any>>) {
- if (entry.type === "tool" && entry.name === "subagent") entry.state = { status: "running", input: entry.state.input, metadata: {} };
- }
- }
- const translator = new EventTranslator({ version: "2.0.18" });
- const events = JSON.parse(readFileSync(join(import.meta.dir, "fixtures", "v2-sub-events.json"), "utf8")) as Array<{ type: string; data: Record<string, any> }>;
- const progressed = new Map<string, string>();
- for (const event of events) {
- await translator.translate(event);
- if (event.type === "session.tool.progress" && event.data.sessionID === parent && typeof event.data.metadata?.sessionID === "string") {
- progressed.set(String(event.data.id), event.data.metadata.sessionID);
- }
- if (event.type === "session.tool.success") break;
- }
- expect(progressed.size).toBe(2);
- const read = (childSessionOf?: (callID: string) => string | undefined) =>
- (v1Messages(running, { sessionID: parent, directory: "/work/proj", root: "/", model: { providerID: "mock", modelID: "mock-model" }, childSessionOf })
- .flatMap((message) => message.parts)
- .filter((part) => part.type === "tool") as Array<{ callID: string; tool: string; state: { status: string; metadata: Record<string, unknown> } }>);
-
- const tasks = read((callID) => translator.childSessionOf(parent, callID));
- expect(tasks.map((task) => [task.tool, task.state.status])).toEqual([["task", "running"], ["task", "running"]]);
- for (const task of tasks) expect(task.state.metadata.sessionId).toBe(progressed.get(task.callID));
- // Without the progress it was read with no child (the bug), and a stored child is never replaced.
- expect(read().map((task) => task.state.metadata.sessionId)).toEqual([undefined, undefined]);
- const stored = JSON.parse(JSON.stringify(running)) as Array<Record<string, any>>;
- for (const message of stored) for (const entry of message.content ?? []) if (entry.type === "tool") entry.state.metadata = { sessionID: "ses_stored" };
- const kept = v1Messages(stored, { sessionID: parent, childSessionOf: () => "ses_from_progress" }).flatMap((message) => message.parts).filter((part) => part.type === "tool") as Array<{ state: { metadata: Record<string, unknown> } }>;
- expect(kept.map((task) => task.state.metadata.sessionId)).toEqual(["ses_stored", "ses_stored"]);
- // Only this session's calls: another session's call of the same id names no child.
- expect(translator.childSessionOf("ses_other", tasks[0]!.callID)).toBeUndefined();
- });
-
- test("a sub-agent call's child is remembered only until the engine's own record names it", async () => {
- const translator = new EventTranslator({ version: "2.0.18" });
- const progress = (sessionID: string, id: string, child: string) =>
- translator.translate({ type: "session.tool.progress", data: { sessionID, id, metadata: { sessionID: child, status: "running" } } });
- await progress("ses_p", "call_ok", "ses_c1");
- await progress("ses_p", "call_bad", "ses_c2");
- await progress("ses_p", "call_bad_named", "ses_c3");
- await progress("ses_q", "call_other", "ses_c4");
-
- // Success names the child (the engine stores it from then on): forgotten.
- await translator.translate({ type: "session.tool.success", data: { sessionID: "ses_p", id: "call_ok", metadata: { sessionID: "ses_c1", status: "completed" } } });
- expect(translator.childSessionOf("ses_p", "call_ok")).toBeUndefined();
- // A failure that does not name the child keeps it, so its card stays linked.
- await translator.translate({ type: "session.tool.failed", data: { sessionID: "ses_p", id: "call_bad", error: "aborted" } });
- expect(translator.childSessionOf("ses_p", "call_bad")).toBe("ses_c2");
- // A failure that names it is forgotten like a success.
- await translator.translate({ type: "session.tool.failed", data: { sessionID: "ses_p", id: "call_bad_named", error: "boom", metadata: { sessionID: "ses_c3" } } });
- expect(translator.childSessionOf("ses_p", "call_bad_named")).toBeUndefined();
-
- // Deleting the parent session forgets its calls, and only its calls.
- await translator.translate({ type: "session.deleted", data: { sessionID: "ses_p" } });
- expect(translator.childSessionOf("ses_p", "call_bad")).toBeUndefined();
- expect(translator.childSessionOf("ses_q", "call_other")).toBe("ses_c4");
- });
-
- test("busy and idle come from the execution lifecycle", async () => {
- const translator = new EventTranslator({ version: "2.0.18" });
- const started = await translator.translate({ type: "session.execution.started", data: { sessionID: "ses_a" } });
- expect(started.map((item) => item.event)).toEqual([{ type: "session.status", properties: { sessionID: "ses_a", status: { type: "busy" } } }]);
- expect(translator.statuses()).toEqual({ ses_a: { type: "busy" } });
- const done = await translator.translate({ type: "session.execution.succeeded", data: { sessionID: "ses_a" } });
- expect(done.map((item) => item.event.type)).toEqual(["session.status", "session.idle"]);
- expect(translator.statuses()).toEqual({});
- });
-});
-
-describe("tool names, inputs, permissions and questions", () => {
- test("names and inputs map both ways", () => {
+describe("tool names and inputs", () => {
+ test("2.x names and inputs take their 1.x spelling", () => {
expect(v1ToolName("shell")).toBe("bash");
expect(v1ToolName("subagent")).toBe("task");
expect(v1ToolName("patch")).toBe("apply_patch");
expect(v1ToolName("webfetch")).toBe("webfetch");
expect(v1ToolInput("read", { path: "/a", offset: 2 })).toEqual({ filePath: "/a", offset: 2 });
- expect(v1ToolInput("subagent", { agent: "general", prompt: "x", description: "d" })).toEqual({ subagent_type: "general", prompt: "x", description: "d" });
+ expect(v1ToolInput("subagent", { agent: "general", prompt: "x", description: "d", background: true })).toEqual({ subagent_type: "general", prompt: "x", description: "d" });
expect(v1ToolInput("edit", '{"path":"/a","oldString":"x","newString":"y"}')).toEqual({ filePath: "/a", oldString: "x", newString: "y" });
- expect(v2ToolInput("task", { subagent_type: "general", prompt: "x" })).toEqual({ agent: "general", prompt: "x" });
- expect(v2ToolInput("write", { filePath: "/a", content: "c" })).toEqual({ path: "/a", content: "c" });
- });
-
- test("a 2.x permission request becomes the 1.x request", () => {
- expect(v1PermissionRequest({
- id: "per_1", sessionID: "ses_1", action: "shell", resources: ["git push"], save: ["git push *"],
- metadata: { command: "git push" }, source: { type: "tool", messageID: "msg_1", id: "call_1" },
- })).toEqual({
- id: "per_1", sessionID: "ses_1", permission: "bash", patterns: ["git push"], metadata: { command: "git push" },
- always: ["git push *"], tool: { messageID: "msg_1", callID: "call_1" },
- });
- });
-
- test("question forms map to 1.x questions and answers map back", () => {
- const mapping = v1QuestionRequest({
- id: "frm_1", sessionID: "ses_1",
- fields: [{ key: "color", type: "multiselect", title: "Color", description: "Pick colors", options: [{ value: "r", label: "Red", description: "" }, { value: "g", label: "Green", description: "" }] }],
- })!;
- expect(mapping.request).toEqual({
- id: "frm_1", sessionID: "ses_1",
- questions: [{ question: "Pick colors", header: "Color", options: [{ label: "Red", description: "" }, { label: "Green", description: "" }], multiple: true }],
- });
- expect(v2FormAnswer(mapping.fields, [["Green"]])).toEqual({ color: ["g"] });
});
test("part ids are stable per message slot", () => {
diff --git a/apps/server/src/engine2/shapes.ts b/apps/server/src/engine2/shapes.ts
index b90658c3..a65f2528 100644
--- a/apps/server/src/engine2/shapes.ts
+++ b/apps/server/src/engine2/shapes.ts
@@ -1,14 +1,11 @@
/**
- * The 2.x engine's records in the 1.x shapes the app, the session uploader and the
- * uploaded traces are written against.
+ * Sessions the opencode 2.x engine stored, in the 1.x shapes.
*
- * OmniRush.ai bundles the opencode 2.x engine but keeps talking the 1.x
- * dialect everywhere above the engine: the renderer's SDK client, the
- * server's own engine reads, the turn observer and the trace upload
- * ("omnirush.trace.v1", shared with the CLI and read by the admin
- * converter). This module is the single place where a 2.x session,
- * message, tool call, permission, question, agent, command or catalog entry
- * becomes its 1.x counterpart, field for field:
+ * OmniRush.ai desktop 2.2.0 – 3.x bundled the opencode 2.x engine; the app
+ * now bundles the 1.x engine again (OmniRush.ai's build of 1.18.32), which
+ * cannot read the 2.x session store. engine2/import.ts copies each 2.x
+ * session into the 1.x engine's store once, through `opencode import`; this
+ * module turns the 2.x records into the 1.x records it takes, field for field:
*
* - a 2.x `user` message becomes `{info:{role:"user", agent, model}, parts:[text, file…]}`;
* - a 2.x `assistant` message (one model step) becomes `{info:{role:"assistant", parentID,
@@ -17,14 +14,13 @@
* - 2.x tool names and inputs take their 1.x names (`shell`→`bash`, `subagent`→`task`,
* `path`→`filePath`, `agent`→`subagent_type`, `patch`→`apply_patch`), results become
* `output`/`title`/`metadata` with the 1.x metadata keys (`sessionId`, `filediff`, …);
+ * a tool's result text is kept exactly as the 2.x engine wrote it;
* - context-only records (system, instruction, agent/model switches, idle markers) are left out,
* as the 1.x engine never listed them.
*
* Part ids are derived from the message id and the part's place (`prt_<msg>_r0`, `_t1`,
- * `_c<callID>`, …) so a part read from a message list and the same part built from live events
- * (engine2/events.ts) agree.
+ * `_c<callID>`, …), so importing a session twice writes the same records.
*/
-import { withNativeFields } from "./native.js";
import { arr, isRecord, num, omitUndefined, promptFileUrl, record, str, unwrap, type JsonRecord } from "./util.js";
export type V1Message = { info: JsonRecord; parts: JsonRecord[] };
@@ -43,14 +39,6 @@ export function v1ToolName(name: string): string {
return TOOL_NAMES_V1[name] ?? name;
}
-/** A 1.x tool name in its 2.x spelling (permission actions, plugin tool filters). */
-export function v2ToolName(name: string): string {
- if (name === "bash") return "shell";
- if (name === "task") return "subagent";
- if (name === "apply_patch") return "patch";
- return name;
-}
-
function parseInput(value: unknown): JsonRecord {
if (isRecord(value)) return value;
if (typeof value !== "string" || value === "") return {};
@@ -86,26 +74,6 @@ export function v1ToolInput(name: string, raw: unknown): JsonRecord {
}
}
-/** A 1.x tool input with the 2.x key names (used where a plugin or the swarm rewrites a call). */
-export function v2ToolInput(name: string, input: JsonRecord): JsonRecord {
- switch (name) {
- case "read":
- case "write":
- case "edit": {
- if (typeof input.filePath !== "string" || "path" in input) return input;
- const { filePath, ...rest } = input;
- return { path: filePath, ...rest };
- }
- case "task": {
- if (typeof input.subagent_type !== "string" || "agent" in input) return input;
- const { subagent_type, ...rest } = input;
- return { agent: subagent_type, ...rest };
- }
- default:
- return input;
- }
-}
-
function contentText(content: unknown): string {
if (typeof content === "string") return content;
if (!Array.isArray(content)) return "";
@@ -140,8 +108,6 @@ type ToolContext = {
directory?: string;
root?: string;
parentModel?: { providerID: string; modelID: string };
- /** The child session a sub-agent call's progress named (MessageContext.childSessionOf). */
- childSessionOf?: (callID: string) => string | undefined;
};
function v1ToolTitle(name: string, input: JsonRecord, ctx: ToolContext): string {
@@ -349,10 +315,7 @@ export function v1ToolPart(
return { ...base, state: { status: "pending", input, raw: typeof state.input === "string" ? state.input : JSON.stringify(state.input ?? {}) } };
}
const { __title: pluginTitle, ...stored } = record(state, "metadata") ?? {};
- // The engine's read of a running sub-agent call leaves out its child session (only the
- // call's progress events name it): the child the progress named, so the card can open it.
- const child = name === "subagent" && typeof stored.sessionID !== "string" ? ctx.childSessionOf?.(callID) : undefined;
- const metadata: JsonRecord = child ? { ...stored, sessionID: child } : stored;
+ const metadata: JsonRecord = stored;
const title = (fallback: string) => (typeof pluginTitle === "string" && pluginTitle ? pluginTitle : fallback);
if (status === "running") {
const runningTitle = title(v1ToolTitle(name, rawInput, ctx));
@@ -471,11 +434,6 @@ export type MessageContext = {
model?: { providerID: string; modelID: string; variant?: string };
/** Whether the session is a sub-agent's (its first user message then has the 2.x task preamble). */
child?: boolean;
- /**
- * The child session of one of this session's sub-agent calls, as its progress events named it
- * (EventTranslator.childSessionOf): a read of a running call does not carry it.
- */
- childSessionOf?: (callID: string) => string | undefined;
};
type ModelRef = { providerID: string; modelID: string; variant?: string };
@@ -499,7 +457,7 @@ export function v1AssistantMessage(message: JsonRecord, ctx: MessageContext, par
const model = modelRef(message.model) ?? ctx.model;
const agent = str(message, "agent") ?? ctx.agent ?? "build";
const ids = { messageID: id, sessionID: ctx.sessionID };
- const toolCtx: ToolContext = { sessionID: ctx.sessionID, directory: ctx.directory, root: ctx.root, parentModel: model, childSessionOf: ctx.childSessionOf };
+ const toolCtx: ToolContext = { sessionID: ctx.sessionID, directory: ctx.directory, root: ctx.root, parentModel: model };
const tokens = v1Tokens(message.tokens);
const cost = num(message, "cost") ?? 0;
const finish = str(message, "finish");
@@ -758,9 +716,7 @@ function v1CompactionMessages(message: JsonRecord, ctx: MessageContext, model: M
export function v1Messages(messages: unknown[], ctx: MessageContext): V1Message[] {
const list = messages.filter(isRecord);
const out: V1Message[] = [];
- const mappedFrom = new Map<JsonRecord, V1Message[]>();
- const emit = (message: JsonRecord, mapped: V1Message[]) => {
- mappedFrom.set(message, mapped);
+ const emit = (_message: JsonRecord, mapped: V1Message[]) => {
out.push(...mapped);
};
let agent = ctx.agent ?? "build";
@@ -833,7 +789,7 @@ export function v1Messages(messages: unknown[], ctx: MessageContext): V1Message[
return;
}
});
- return withNativeFields(out, list, mappedFrom, ctx.sessionID);
+ return out;
}
export type SessionShapeOptions = {
@@ -891,238 +847,3 @@ export function v1Session(value: unknown, options: SessionShapeOptions): JsonRec
revert: revert && str(revert, "messageID") ? omitUndefined({ messageID: str(revert, "messageID"), partID: str(revert, "partID"), snapshot: str(revert, "snapshot") }) : undefined,
});
}
-
-/** A 2.x permission request as a 1.x one (`permission` = the 1.x tool/permission name). */
-export function v1PermissionRequest(value: unknown): JsonRecord | null {
- if (!isRecord(value)) return null;
- const id = str(value, "id");
- const sessionID = str(value, "sessionID");
- const action = str(value, "action");
- if (!id || !sessionID || !action) return null;
- const resources = arr(value, "resources").filter((item): item is string => typeof item === "string");
- const save = arr(value, "save").filter((item): item is string => typeof item === "string");
- const source = record(value, "source");
- const messageID = str(source, "messageID");
- const callID = str(source, "id");
- return omitUndefined({
- id,
- sessionID,
- permission: v1ToolName(action),
- patterns: resources,
- metadata: record(value, "metadata") ?? {},
- always: save.length > 0 ? save : resources,
- tool: messageID && callID ? { messageID, callID } : undefined,
- });
-}
-
-/** A 2.x permission request in the 1.x engine's own `/api` (PermissionV2Request) shape. */
-export function v1PermissionV2Request(value: unknown): JsonRecord | null {
- if (!isRecord(value)) return null;
- const id = str(value, "id");
- const sessionID = str(value, "sessionID");
- const action = str(value, "action");
- if (!id || !sessionID || !action) return null;
- return omitUndefined({
- id,
- sessionID,
- action: v1ToolName(action),
- resources: arr(value, "resources"),
- save: isRecord(value) && Array.isArray(value.save) ? value.save : undefined,
- metadata: record(value, "metadata"),
- source: record(value, "source") ? omitUndefined({ type: "tool", messageID: str(record(value, "source"), "messageID"), callID: str(record(value, "source"), "id") }) : undefined,
- });
-}
-
-export type QuestionMapping = { request: JsonRecord; fields: Array<{ key: string; multiple: boolean; options: Array<{ value: string; label: string }> }> };
-
-/** A 2.x form that asks questions (the question tool's form) as a 1.x question request. */
-export function v1QuestionRequest(value: unknown): QuestionMapping | null {
- if (!isRecord(value)) return null;
- const id = str(value, "id");
- const sessionID = str(value, "sessionID");
- if (!id || !sessionID) return null;
- const fields = arr(value, "fields").filter(isRecord);
- if (fields.length === 0) return null;
- const mapped: QuestionMapping["fields"] = [];
- const questions: JsonRecord[] = [];
- for (const field of fields) {
- const key = str(field, "key") ?? str(field, "id") ?? String(mapped.length);
- const type = str(field, "type");
- const options = arr(field, "options").filter(isRecord).map((option) => ({
- value: str(option, "value") ?? str(option, "label") ?? "",
- label: str(option, "label") ?? str(option, "value") ?? "",
- description: str(option, "description") ?? "",
- }));
- mapped.push({ key, multiple: type === "multiselect", options });
- questions.push(omitUndefined({
- question: str(field, "description") ?? str(field, "title") ?? "",
- header: str(field, "title") ?? "",
- options: options.map(({ label, description }) => ({ label, description })),
- multiple: type === "multiselect" || undefined,
- custom: field.custom === true || type === "string" || undefined,
- }));
- }
- const source = record(value, "source") ?? record(record(value, "metadata"), "source");
- const messageID = str(source, "messageID");
- const callID = str(source, "id") ?? str(source, "callID");
- return {
- request: omitUndefined({ id, sessionID, questions, tool: messageID && callID ? { messageID, callID } : undefined }),
- fields: mapped,
- };
-}
-
-/** 1.x question answers (labels per question) as a 2.x form answer keyed by field. */
-export function v2FormAnswer(mapping: QuestionMapping["fields"], answers: unknown[]): JsonRecord {
- const answer: JsonRecord = {};
- mapping.forEach((field, index) => {
- const raw = answers[index];
- const labels = Array.isArray(raw) ? raw.filter((item): item is string => typeof item === "string") : typeof raw === "string" ? [raw] : [];
- const values = labels.map((label) => field.options.find((option) => option.label === label)?.value ?? label);
- answer[field.key] = field.multiple ? values : values[0] ?? "";
- });
- return answer;
-}
-
-/** A 2.x agent as a 1.x agent record. */
-export function v1Agent(value: unknown): JsonRecord | null {
- if (!isRecord(value)) return null;
- const name = str(value, "id") ?? str(value, "name");
- if (!name) return null;
- const model = record(value, "model");
- const request = record(value, "request");
- const body = record(request, "body") ?? {};
- const permissions = arr(value, "permissions").filter(isRecord);
- return omitUndefined({
- name,
- description: str(value, "description"),
- mode: str(value, "mode") ?? "all",
- native: value.native === true || undefined,
- hidden: value.hidden === true || undefined,
- color: str(value, "color"),
- temperature: typeof body.temperature === "number" ? body.temperature : undefined,
- topP: typeof body.top_p === "number" ? body.top_p : undefined,
- permission: permissions.map((rule) => ({ permission: v1ToolName(str(rule, "action") ?? "*"), pattern: str(rule, "resource") ?? "*", action: str(rule, "effect") ?? "ask" })),
- model: model && str(model, "providerID") ? { providerID: str(model, "providerID"), modelID: str(model, "id") ?? str(model, "model") ?? "" } : undefined,
- variant: str(model, "variant"),
- prompt: typeof value.system === "string" ? value.system : undefined,
- options: {},
- steps: num(value, "steps"),
- });
-}
-
-/** A 2.x command as a 1.x command record. */
-export function v1Command(value: unknown): JsonRecord | null {
- if (!isRecord(value)) return null;
- const name = str(value, "id") ?? str(value, "name");
- if (!name) return null;
- const model = record(value, "model");
- return omitUndefined({
- name,
- description: str(value, "description"),
- agent: str(value, "agent"),
- model: model && str(model, "providerID") ? `${str(model, "providerID")}/${str(model, "id") ?? str(model, "model") ?? ""}` : str(value, "model"),
- source: str(value, "source") === "mcp" ? "mcp" : str(value, "source") === "skill" ? "skill" : "command",
- template: str(value, "template") ?? "",
- subtask: value.subagent === true || undefined,
- hints: Array.isArray(value.hints) ? value.hints : [],
- });
-}
-
-function modelStatus(value: unknown): string {
- return value === "alpha" || value === "beta" || value === "deprecated" ? value : "active";
-}
-
-/** A 2.x catalog model as a 1.x provider model. */
-export function v1Model(value: unknown): JsonRecord | null {
- if (!isRecord(value)) return null;
- const id = str(value, "id");
- const providerID = str(value, "providerID");
- if (!id || !providerID) return null;
- const capabilities = record(value, "capabilities") ?? {};
- const input = arr(capabilities, "input").filter((item): item is string => typeof item === "string");
- const output = arr(capabilities, "output").filter((item): item is string => typeof item === "string");
- const cost = arr(value, "cost").filter(isRecord);
- const base = cost.find((tier) => !isRecord(tier.tier)) ?? cost[0];
- const limit = record(value, "limit") ?? {};
- const settings = record(value, "settings") ?? {};
- const variants = arr(value, "variants").filter(isRecord);
- const compatibility = record(value, "compatibility");
- const reasoningField = str(compatibility, "reasoningField");
- return omitUndefined({
- id,
- providerID,
- api: { id: str(value, "modelID") ?? id, url: str(settings, "baseURL") ?? "", npm: str(value, "package") ?? "" },
- name: str(value, "name") ?? id,
- family: str(value, "family"),
- capabilities: {
- temperature: true,
- reasoning: variants.length > 0 || Boolean(reasoningField),
- attachment: input.some((kind) => kind !== "text"),
- toolcall: capabilities.tools !== false,
- input: { text: true, audio: input.includes("audio"), image: input.includes("image"), video: input.includes("video"), pdf: input.includes("pdf") },
- output: { text: true, audio: output.includes("audio"), image: output.includes("image"), video: output.includes("video"), pdf: output.includes("pdf") },
- interleaved: reasoningField ? { field: reasoningField } : false,
- },
- cost: {
- input: num(base, "input") ?? 0,
- output: num(base, "output") ?? 0,
- cache: { read: num(record(base, "cache"), "read") ?? 0, write: num(record(base, "cache"), "write") ?? 0 },
- },
- limit: omitUndefined({ context: num(limit, "context") ?? 0, input: num(limit, "input"), output: num(limit, "output") ?? 0 }),
- status: modelStatus(value.status),
- options: {},
- headers: {},
- release_date: num(record(value, "time"), "released") ? new Date(num(record(value, "time"), "released")!).toISOString().slice(0, 10) : "",
- variants: Object.fromEntries(variants.map((variant) => [str(variant, "id") ?? "", record(variant, "settings") ?? {}]).filter(([key]) => key)),
- });
-}
-
-/** The 2.x provider and model catalog as the 1.x `/provider` answer `{all, default, connected}`. */
-export function v1ProviderList(providers: unknown[], models: unknown[], defaults: Record<string, string>): JsonRecord {
- const byProvider = new Map<string, JsonRecord>();
- for (const provider of providers) {
- if (!isRecord(provider)) continue;
- const id = str(provider, "id");
- if (!id) continue;
- byProvider.set(id, {
- id,
- name: str(provider, "name") ?? id,
- source: "config",
- env: arr(provider, "env").filter((item) => typeof item === "string"),
- options: {},
- models: {},
- });
- }
- for (const model of models) {
- const mapped = v1Model(model);
- if (!mapped) continue;
- if (isRecord(model) && model.enabled === false) continue;
- const providerID = String(mapped.providerID);
- const provider = byProvider.get(providerID) ?? { id: providerID, name: providerID, source: "config", env: [], options: {}, models: {} };
- (provider.models as JsonRecord)[String(mapped.id)] = mapped;
- byProvider.set(providerID, provider);
- }
- const all = [...byProvider.values()].filter((provider) => Object.keys(provider.models as JsonRecord).length > 0);
- return { all, default: defaults, connected: all.map((provider) => provider.id) };
-}
-
-/** A 2.x MCP server entry (`GET /api/mcp`: `{name, status: {status, error?}}`) as the 1.x status map value. */
-export function v1McpStatus(value: unknown): JsonRecord {
- const nested = record(value, "status");
- const status = str(nested, "status") ?? str(value, "status") ?? "failed";
- const error = str(nested, "error") ?? str(value, "error");
- switch (status) {
- case "connected":
- return { status: "connected" };
- case "disabled":
- return { status: "disabled" };
- case "needs_auth":
- return { status: "needs_auth" };
- case "needs_client_registration":
- return { status: "needs_client_registration", error: error ?? "" };
- case "pending":
- return { status: "failed", error: "The MCP server is still connecting." };
- default:
- return { status: "failed", error: error ?? status };
- }
-}
diff --git a/apps/server/src/engine2/store.ts b/apps/server/src/engine2/store.ts
new file mode 100644
index 00000000..50fcdb95
--- /dev/null
+++ b/apps/server/src/engine2/store.ts
@@ -0,0 +1,158 @@
+/**
+ * A read-only view of the opencode 2.x engine's session store (its
+ * `opencode.db`, as OmniRush.ai desktop 2.2.0 – 3.x left it), in the shapes
+ * the 2.x engine's own API answered with:
+ *
+ * - a session (`session_v2` row) as `GET /api/session/:id` gave it:
+ * `{id, projectID, parentID, title, agent, model, cost, tokens, time, location, revert, …}`;
+ * - its messages (`session_message` rows, in `seq` order) as
+ * `GET /api/session/:id/message` gave them: `{id, type, ...data}`.
+ *
+ * The file is opened read-only and never written: the 2.x store stays as it
+ * was, so an older OmniRush.ai still opens it.
+ */
+import { existsSync } from "node:fs";
+import { isRecord, type JsonRecord } from "./util.js";
+
+export type Engine2StoredSession = {
+ session: JsonRecord;
+ messages: JsonRecord[];
+ /** The 2.x project's worktree (its git root, or "/" without one). */
+ worktree?: string;
+};
+
+type Row = Record<string, unknown>;
+type Reader = { all: (sql: string, ...params: unknown[]) => Row[]; close: () => void };
+
+async function openReadOnly(path: string): Promise<Reader> {
+ if (typeof (globalThis as { Bun?: unknown }).Bun !== "undefined") {
+ const { Database } = await import("bun:sqlite");
+ const db = new Database(path, { readonly: true });
+ return {
+ all: (sql, ...params) => db.query(sql).all(...(params as never[])) as Row[],
+ close: () => db.close(),
+ };
+ }
+ // A literal specifier would make Bun's bundler try to resolve node:sqlite.
+ const specifier = "node:sqlite";
+ const { DatabaseSync } = (await import(specifier)) as typeof import("node:sqlite");
+ const db = new DatabaseSync(path, { readOnly: true });
+ return {
+ all: (sql, ...params) => db.prepare(sql).all(...(params as never[])) as Row[],
+ close: () => db.close(),
+ };
+}
+
+function json(value: unknown): unknown {
+ if (typeof value !== "string" || value === "") return undefined;
+ try {
+ return JSON.parse(value);
+ } catch {
+ return undefined;
+ }
+}
+
+function text(value: unknown): string | undefined {
+ return typeof value === "string" && value !== "" ? value : undefined;
+}
+
+function number(value: unknown): number | undefined {
+ if (typeof value === "bigint") return Number(value);
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
+}
+
+function compact<T extends JsonRecord>(value: T): T {
+ for (const key of Object.keys(value)) if (value[key] === undefined) delete value[key];
+ return value;
+}
+
+/** A `session_v2` row as the 2.x API's session record. */
+export function engine2SessionRecord(row: Row): JsonRecord {
+ const model = json(row.model);
+ const revert = json(row.revert);
+ const permissions = json(row.permission);
+ const metadata = json(row.metadata);
+ return compact({
+ id: String(row.id),
+ slug: text(row.slug),
+ projectID: text(row.project_id),
+ parentID: text(row.parent_id),
+ title: text(row.title),
+ agent: text(row.agent),
+ model: isRecord(model) ? model : undefined,
+ cost: number(row.cost),
+ tokens: {
+ input: number(row.tokens_input) ?? 0,
+ output: number(row.tokens_output) ?? 0,
+ reasoning: number(row.tokens_reasoning) ?? 0,
+ cache: { read: number(row.tokens_cache_read) ?? 0, write: number(row.tokens_cache_write) ?? 0 },
+ },
+ time: compact({
+ created: number(row.time_created) ?? 0,
+ updated: number(row.time_updated) ?? number(row.time_created) ?? 0,
+ archived: number(row.time_archived),
+ }),
+ location: { directory: text(row.directory) ?? "" },
+ subpath: text(row.path),
+ revert: isRecord(revert) ? revert : undefined,
+ permissions: Array.isArray(permissions) ? permissions : undefined,
+ metadata: isRecord(metadata) ? metadata : undefined,
+ version: text(row.version),
+ });
+}
+
+/** A `session_message` row as the 2.x API's message record. */
+export function engine2MessageRecord(row: Row): JsonRecord | null {
+ const data = json(row.data);
+ if (!isRecord(data)) return null;
+ return { id: String(row.id), ...data, type: String(row.type) };
+}
+
+/** Whether `path` is a 2.x engine store (it has the 2.x session tables). */
+export async function isEngine2Store(path: string): Promise<boolean> {
+ if (!existsSync(path)) return false;
+ let reader: Reader | null = null;
+ try {
+ reader = await openReadOnly(path);
+ const tables = new Set(reader.all("SELECT name FROM sqlite_master WHERE type = 'table'").map((row) => String(row.name)));
+ return tables.has("session_v2") && tables.has("session_message");
+ } catch {
+ return false;
+ } finally {
+ reader?.close();
+ }
+}
+
+/** The ids of the stored sessions, oldest first. */
+export async function listEngine2Sessions(path: string): Promise<string[]> {
+ const reader = await openReadOnly(path);
+ try {
+ return reader.all("SELECT id FROM session_v2 ORDER BY time_created, id").map((row) => String(row.id));
+ } finally {
+ reader.close();
+ }
+}
+
+/** One stored session with its messages, or null when it is gone. */
+export async function readEngine2Session(path: string, sessionID: string): Promise<Engine2StoredSession | null> {
+ const reader = await openReadOnly(path);
+ try {
+ const row = reader.all("SELECT * FROM session_v2 WHERE id = ?", sessionID)[0];
+ if (!row) return null;
+ const messages = reader
+ .all("SELECT id, type, seq, data FROM session_message WHERE session_id = ? ORDER BY seq, id", sessionID)
+ .map(engine2MessageRecord)
+ .filter((message): message is JsonRecord => message !== null);
+ let worktree: string | undefined;
+ if (typeof row.project_id === "string") {
+ try {
+ worktree = text(reader.all("SELECT worktree FROM project WHERE id = ?", row.project_id)[0]?.worktree);
+ } catch {
+ worktree = undefined;
+ }
+ }
+ return { session: engine2SessionRecord(row), messages, ...(worktree ? { worktree } : {}) };
+ } finally {
+ reader.close();
+ }
+}
diff --git a/apps/server/src/managed-opencode.ts b/apps/server/src/managed-opencode.ts
index e38e4269..1cbbef7d 100644
--- a/apps/server/src/managed-opencode.ts
+++ b/apps/server/src/managed-opencode.ts
@@ -1,8 +1,7 @@
import { spawn, type ChildProcess } from "node:child_process";
import net from "node:net";
import { randomUUID } from "node:crypto";
-import { startEngineFacade } from "./engine2/facade.js";
-import { prepareEngine2Launch, resolveEngineIdentity, type EngineDialect } from "./engine2/launch.js";
+import { globalOpencodeConfigDir } from "@omnirush/paths";
export type ManagedChildProcess = {
exitCode: number | null;
@@ -25,13 +24,6 @@ export type ManagedOpencodeServer = {
execution: OpencodeExecutionSnapshot;
isAlive: () => boolean;
close: () => Promise<void>;
- /**
- * Engines that re-read their config while running (the 2.x engine watches
- * its config file): re-renders that config from the runtime config file, so
- * a change reaches the engine without a restart. Absent on 1.x engines,
- * which only read their config when an instance is (re)built.
- */
- refreshConfig?: () => Promise<void>;
};
export type OpencodeExecutionEnvEntry = {
@@ -130,12 +122,6 @@ async function findFreePort(hostname: string, excludedPorts: number[] = []): Pro
type ManagedOpencodeServerOptions = {
bin?: string;
- /**
- * The engine API the binary speaks. Unset: resolved from the binary
- * (engine2/launch.ts). A 2.x engine is started behind the 1.x engine
- * adapter (engine2/facade.ts), whose URL and credentials are returned.
- */
- dialect?: EngineDialect;
cwd: string;
hostname?: string;
port?: number;
@@ -159,136 +145,11 @@ function isRetryableAddressInUseExit(error: unknown): boolean {
/\bEADDRINUSE\b/.test(error.message);
}
-function redactedEnv(entries: Record<string, string | undefined>): OpencodeExecutionEnvEntry[] {
- return Object.entries(entries)
- .filter((entry): entry is [string, string] => typeof entry[1] === "string")
- .map(([name, value]) => ({
- name,
- value: SECRET_ENV_PATTERN.test(name) ? "<redacted>" : value,
- redacted: SECRET_ENV_PATTERN.test(name),
- }))
- .sort((left, right) => left.name.localeCompare(right.name));
-}
-
-/**
- * Starts a 2.x engine on an ephemeral loopback port and the 1.x engine
- * adapter on `port`: callers get the adapter's URL and Basic credentials,
- * exactly as they got the 1.x engine's.
- */
-async function startManagedEngine2Server(
- options: ManagedOpencodeServerOptions,
- hostname: string,
- port: number,
- version: string | null,
-): Promise<ManagedOpencodeServer> {
- const username = randomSecret();
- const password = randomSecret();
- const enginePassword = randomSecret();
- const command = options.bin?.trim() || "opencode";
- const args = ["serve", "--hostname", "127.0.0.1", "--port", "0"];
- const adapterUrl = `http://${hostname.includes(":") ? `[${hostname}]` : hostname}:${port}`;
- const adapterAuthorization = `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`;
- const engineEnvDefaults = { npm_config_audit: "false" };
- const launch = await prepareEngine2Launch({
- env: { ...process.env, ...engineEnvDefaults, ...options.env },
- cwd: options.cwd,
- password: enginePassword,
- adapterUrl,
- adapterAuthorization,
- });
- const env: NodeJS.ProcessEnv = { ...launch.env };
- delete env.OMNIRUSH_ENCRYPTION_KEY;
- delete env.OPENCODE_SERVER_USERNAME;
- delete env.OPENCODE_SERVER_PASSWORD;
- const injectedEnv = redactedEnv({
- ...engineEnvDefaults,
- ...(options.env ?? {}),
- OPENCODE_CONFIG: launch.configFile,
- OPENCODE_PASSWORD: enginePassword,
- OMNIRUSH_ENGINE_ADAPTER_URL: adapterUrl,
- OMNIRUSH_ENGINE_ADAPTER_AUTHORIZATION: adapterAuthorization,
- });
- const child: ChildProcess = spawn(command, args, { cwd: options.cwd, env, stdio: ["ignore", "pipe", "pipe"] });
- const processLifecycle = createManagedProcessClose(child);
- const timeoutMs = Math.max(options.timeoutMs ?? 15_000, 90_000);
- let engineUrl: string;
- try {
- engineUrl = await new Promise<string>((resolve, reject) => {
- const timeout = setTimeout(() => reject(new Error(`Timeout waiting for OmniRush server after ${timeoutMs}ms`)), timeoutMs);
- let output = "";
- const done = (value: string) => {
- clearTimeout(timeout);
- resolve(value);
- };
- const fail = (error: Error) => {
- clearTimeout(timeout);
- reject(error);
- };
- child.stdout?.on("data", (chunk) => {
- output += chunk.toString();
- for (const line of output.split("\n")) {
- const match = line.match(/server listening on\s+(https?:\/\/[^\s]+)/);
- if (match?.[1]) return done(match[1]);
- }
- });
- child.stderr?.on("data", (chunk) => {
- output += chunk.toString();
- });
- child.once("error", fail);
- child.once("close", (code) => fail(new ManagedOpencodeExitError(code, output)));
- });
- } catch (error) {
- await processLifecycle.close();
- throw error;
- }
- let facade: Awaited<ReturnType<typeof startEngineFacade>>;
- try {
- facade = await startEngineFacade({
- upstreamUrl: engineUrl,
- upstreamPassword: enginePassword,
- username,
- password,
- hostname,
- port,
- version: version ?? "2",
- defaultDirectory: options.cwd,
- v1ConfigPath: launch.v1ConfigPath,
- writeEngineConfig: launch.writeEngineConfig,
- plugins: launch.plugins,
- log: (message, attributes) => console.warn(`[engine-adapter] ${message}`, attributes ? JSON.stringify(attributes) : ""),
- });
- } catch (error) {
- await processLifecycle.close();
- const message = error instanceof Error ? error.message : String(error);
- throw new ManagedOpencodeExitError(1, `engine adapter could not listen: ${message}`);
- }
- child.once("exit", () => {
- void facade.close().catch(() => undefined);
- });
- return {
- url: facade.url,
- username,
- password,
- pid: child.pid ?? null,
- execution: { command, args, cwd: options.cwd, env: injectedEnv },
- isAlive: processLifecycle.isAlive,
- close: async () => {
- await facade.close().catch(() => undefined);
- await processLifecycle.close();
- },
- refreshConfig: facade.refreshConfig,
- };
-}
-
async function startManagedOpencodeServer(
options: ManagedOpencodeServerOptions,
hostname: string,
port: number,
): Promise<ManagedOpencodeServer> {
- const identity = options.dialect
- ? { dialect: options.dialect, version: null }
- : await resolveEngineIdentity(options.bin?.trim() || "opencode", { ...process.env, ...options.env });
- if (identity.dialect === "v2") return startManagedEngine2Server(options, hostname, port, identity.version);
const username = randomSecret();
const password = randomSecret();
const args = ["serve", "--hostname", hostname, "--port", String(port), "--cors", "*"];
@@ -297,7 +158,13 @@ async function startManagedOpencodeServer(
// That audit POST depends on npm's advisories endpoint, which has been observed
// to hang for the full five-minute registry timeout, so first-run must not wait.
// @npmcli/config reads npm_config_* settings from the environment.
- const engineEnvDefaults = { npm_config_audit: "false" };
+ // The question tool is the engine's way to ask the user; the app answers it.
+ const engineEnvDefaults: Record<string, string> = { npm_config_audit: "false", OPENCODE_ENABLE_QUESTION_TOOL: "1" };
+ // OmniRush.ai's engine build keeps its own global config in
+ // ~/.config/omnirush; the app's global skills, agents and config live in
+ // the opencode global config directory, so the engine reads that one too.
+ const baseEnv = { ...process.env, ...options.env };
+ if (!baseEnv.OPENCODE_CONFIG_DIR?.trim()) engineEnvDefaults.OPENCODE_CONFIG_DIR = globalOpencodeConfigDir({ env: baseEnv });
const env: NodeJS.ProcessEnv = {
...process.env,
...engineEnvDefaults,
diff --git a/apps/server/src/mcp.authorization-link.e2e.test.ts b/apps/server/src/mcp.authorization-link.e2e.test.ts
index 3fe006fa..a8e8324d 100644
--- a/apps/server/src/mcp.authorization-link.e2e.test.ts
+++ b/apps/server/src/mcp.authorization-link.e2e.test.ts
@@ -102,7 +102,7 @@ describeMaybe("authorization-required MCP tool error pass-through", () => {
let modelRequests: Array<{ hasToolError: boolean; toolNames: Array<string | undefined> }> = [];
let engineLogs = "";
- // The engine as the app runs it: the bundled 2.x engine behind the 1.x engine adapter.
+ // The engine as the app runs it (managed-opencode.ts).
const engineFetch = (path: string, init?: RequestInit) => {
const url = new URL(`${engine.url}${path}`);
url.searchParams.set("directory", workspace);
@@ -226,8 +226,6 @@ describeMaybe("authorization-required MCP tool error pass-through", () => {
OPENCODE_CONFIG: configPath,
OPENCODE_DISABLE_AUTOUPDATE: "1",
OPENCODE_DISABLE_MODELS_FETCH: "1",
- OMNIRUSH_ENGINE_PLUGINS: "0",
- OMNIRUSH_ENGINE2_CONFIG_DIR: join(dataDir, "engine2"),
XDG_DATA_HOME: join(dataDir, "data"),
XDG_CONFIG_HOME: join(dataDir, "config"),
XDG_STATE_HOME: join(dataDir, "state"),
diff --git a/apps/server/src/mcp.oauth-flow.e2e.test.ts b/apps/server/src/mcp.oauth-flow.e2e.test.ts
index 8b048f40..5f787222 100644
--- a/apps/server/src/mcp.oauth-flow.e2e.test.ts
+++ b/apps/server/src/mcp.oauth-flow.e2e.test.ts
@@ -1,14 +1,14 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { spawn, type ChildProcess } from "node:child_process";
-import { mkdtempSync, rmSync, writeFileSync, existsSync } from "node:fs";
+import { mkdtempSync, rmSync, writeFileSync, existsSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
/**
* Full MCP OAuth flow e2e:
*
- * real opencode engine (sidecar binary, started as the app starts it: the
- * 2.x engine behind the 1.x engine adapter, managed-opencode.ts)
+ * real opencode engine (sidecar binary, started as the app starts it,
+ * managed-opencode.ts)
* -> mock OAuth MCP server (scripts/mock-oauth-mcp-server.mjs)
* -> discovery + dynamic client registration + PKCE (S256)
* -> authorization redirect ("the browser")
@@ -89,14 +89,9 @@ describeMaybe("mcp oauth flow against mock provider", () => {
return fetch(url, { ...init, headers });
}
- /** The OAuth credential the engine stored for the server (2.x keeps it with the server's integration). */
- async function storedCredentials(): Promise<Array<{ id: string }>> {
- const servers = (await (await engineFetch("/api/mcp")).json()) as { data: Array<{ name: string; integrationID?: string }> };
- const integrationID = servers.data.find((server) => server.name === MCP_NAME)?.integrationID;
- if (!integrationID) return [];
- const integration = (await (await engineFetch(`/api/integration/${encodeURIComponent(integrationID)}`)).json()) as { data?: { connections?: Array<{ type: string; id: string }> } };
- return (integration.data?.connections ?? []).filter((connection) => connection.type === "credential");
- }
+ /** Where the engine keeps MCP OAuth tokens (OmniRush.ai's engine build keeps its data in `<data>/omnirush`). */
+ const authFile = () => join(dataDir, "xdg-data", "omnirush", "mcp-auth.json");
+ type SavedAuth = Record<string, { tokens?: { accessToken?: string; refreshToken?: string } }>;
beforeAll(async () => {
mockPort = await getFreePort();
@@ -136,8 +131,6 @@ describeMaybe("mcp oauth flow against mock provider", () => {
XDG_CACHE_HOME: join(dataDir, "xdg-cache"),
OPENCODE_DISABLE_AUTOUPDATE: "1",
OPENCODE_DISABLE_MODELS_FETCH: "1",
- OMNIRUSH_ENGINE_PLUGINS: "0",
- OMNIRUSH_ENGINE2_CONFIG_DIR: join(dataDir, "engine2"),
},
});
await waitFor(
@@ -220,8 +213,10 @@ describeMaybe("mcp oauth flow against mock provider", () => {
);
expect(connected[MCP_NAME].status).toBe("connected");
- // Tokens are persisted for reuse across restarts (a credential of the server's integration).
- expect((await storedCredentials()).length).toBeGreaterThan(0);
+ // Tokens are persisted for reuse across restarts.
+ expect(existsSync(authFile())).toBe(true);
+ const saved = JSON.parse(readFileSync(authFile(), "utf8")) as SavedAuth;
+ expect(saved[MCP_NAME]?.tokens?.accessToken).toStartWith("mock-access-");
// The mock saw the full, authenticated MCP handshake.
const log = (await (await fetch(`${mockUrl()}/requests`)).json()) as {
@@ -239,8 +234,10 @@ describeMaybe("mcp oauth flow against mock provider", () => {
test(
"engine silently refreshes an expired access token without re-authorization",
async () => {
- const before = await storedCredentials();
- expect(before.length).toBeGreaterThan(0);
+ const before = JSON.parse(readFileSync(authFile(), "utf8")) as SavedAuth;
+ const beforeAccess = before[MCP_NAME]?.tokens?.accessToken;
+ expect(beforeAccess).toStartWith("mock-access-");
+ expect(before[MCP_NAME]?.tokens?.refreshToken).toStartWith("mock-refresh-");
// Only assert on traffic that happens after this point.
const markLog = (await (await fetch(`${mockUrl()}/requests`)).json()) as { requests: Array<unknown> };
@@ -289,7 +286,10 @@ describeMaybe("mcp oauth flow against mock provider", () => {
expect(afterMark.some((r) => r.method === "POST" && r.path === "/register")).toBe(false);
// The rotated tokens were persisted for the next restart.
- expect((await storedCredentials()).length).toBeGreaterThan(0);
+ const after = JSON.parse(readFileSync(authFile(), "utf8")) as SavedAuth;
+ expect(after[MCP_NAME]?.tokens?.accessToken).toStartWith("mock-access-");
+ expect(after[MCP_NAME]?.tokens?.accessToken).not.toBe(beforeAccess);
+ expect(after[MCP_NAME]?.tokens?.refreshToken).not.toBe(before[MCP_NAME]?.tokens?.refreshToken);
},
60_000,
);
@@ -297,6 +297,8 @@ describeMaybe("mcp oauth flow against mock provider", () => {
test("logout removes stored tokens and drops the connection", async () => {
const remove = await engineFetch(`/mcp/${MCP_NAME}/auth`, { method: "DELETE" });
expect(remove.ok).toBe(true);
- expect(await storedCredentials()).toEqual([]);
+
+ const saved = JSON.parse(readFileSync(authFile(), "utf8")) as Record<string, unknown>;
+ expect(saved[MCP_NAME]).toBeUndefined();
}, 30_000);
});
diff --git a/apps/server/src/omnirush-agent-prompt.ts b/apps/server/src/omnirush-agent-prompt.ts
index effe7459..b9042a7f 100644
--- a/apps/server/src/omnirush-agent-prompt.ts
+++ b/apps/server/src/omnirush-agent-prompt.ts
@@ -37,9 +37,9 @@ Hard rule: never copy private memory into repo files. Store only redacted summar
- If required setup or credentials are missing, ask one targeted question and continue once provided.
- If you change code, run the smallest meaningful test.
-- Write long files in chunks: create a file with its first section, then append the rest in a few smaller edit (or patch) calls instead of one very large write. A single multi-thousand-token patch is the write most likely to be cut off in transit; if a write is interrupted, re-issue only the missing part.
+- Write long files in chunks: create a file with its first section, then append the rest in a few smaller apply_patch (or edit) calls instead of one very large patch. A single multi-thousand-token patch is the write most likely to be cut off in transit; if a write is interrupted, re-issue only the missing part.
- Split real work: for a task of more than a few tool calls, start one sub-agent per independent part in one message (one per bug or feature, one for tests, one to review), then combine results. Do quick questions yourself.
-- When the user asks for a specific number of agents, make exactly that many subagent calls, no more and no fewer, and start them all in one message so they run in parallel. Use the general subagent unless a more specialized subagent is clearly better. Never replace an explicit delegation request with a simulated multi-role answer, and never claim subagents are unavailable while the subagent tool is present.
+- When the user asks for a specific number of agents, make exactly that many task-tool calls, no more and no fewer, and start them all in one message so they run in parallel. Use the general subagent unless a more specialized subagent is clearly better. Never replace an explicit delegation request with a simulated multi-role answer, and never claim subagents are unavailable while the task tool is present.
- Write each sub-agent's prompt yourself: self-contained, limited to that sub-agent's part, saying what to return. Never paste the user's whole message, or the user's instructions about sub-agents, into a sub-agent's prompt: the sub-agent would follow them again. Tell a sub-agent to start its own sub-agents only when the user explicitly asked for nested sub-agents.
- Wait for every delegated task, then synthesize their actual results before answering; keep delegated activity visible in the session.
- If steps repeat, capture them as a skill following the \`Skill creation:\` instruction in this prompt.
@@ -49,7 +49,7 @@ ${OMNIRUSH_SWARM_PROMPT}
## Editing files
-- When patch or edit reports that expected lines were not found, the file changed since you read it (a formatter ran, or an earlier edit was rejected or aborted). Read the file again before retrying; never resend the same patch. Prefer smaller hunks with unambiguous context. On Windows, keep the file's existing line endings.
+- When apply_patch or edit reports that expected lines were not found, the file changed since you read it (a formatter ran, or an earlier edit was rejected or aborted). Read the file again before retrying; never resend the same patch. Prefer smaller hunks with unambiguous context. On Windows, keep the file's existing line endings.
## OmniRush.ai Artifacts
@@ -63,7 +63,7 @@ OmniRush.ai can preview, edit, and download standard artifacts when you create o
## Git workflows
-- Use git and gh from the shell tool; run them from the repository (the tool's workdir) rather than with \`git -C\`, so approvals match the command family.
+- Use git and gh from the bash tool; run them from the repository (the tool's workdir) rather than with \`git -C\`, so approvals match the command family.
- Read-only commands (status, log, diff, branch --list, fetch origin, gh pr list/view/status) run without approval. Write commands (add, commit, checkout -b, switch, worktree add, push, gh pr create) ask once per session per command family. Destructive commands (push --force, reset --hard, clean -fd, branch -D, rebase -i, filter-branch, rm -rf) always ask; omnirush.ai marks them with OMNIRUSH_DESTRUCTIVE=1 in the approval prompt. Never add or remove that marker yourself.
- Prefer worktrees for parallel branches: \`git worktree add ../<repo>-<branch> -b <branch>\`, and remove them when the work is merged.
- Write conventional commit messages (feat:, fix:, docs:, refactor:, test:, chore:), one logical change per commit.
diff --git a/apps/server/src/omnirush-extensions-plugin-path.ts b/apps/server/src/omnirush-extensions-plugin-path.ts
index f1d052ec..aa043725 100644
--- a/apps/server/src/omnirush-extensions-plugin-path.ts
+++ b/apps/server/src/omnirush-extensions-plugin-path.ts
@@ -42,3 +42,4 @@ export const omnirushPdfAttachmentsPluginPath = () => omnirushPluginPath("omniru
export const omnirushTitleRecoveryPluginPath = () => omnirushPluginPath("omnirush-title-recovery");
export const omnirushReasoningEffortPluginPath = () => omnirushPluginPath("omnirush-reasoning-effort");
export const omnirushSwarmPluginPath = () => omnirushPluginPath("omnirush-swarm");
+export const omnirushBudgetWrapPluginPath = () => omnirushPluginPath("omnirush-budget-wrap");
diff --git a/apps/server/src/omnirush-model-catalog-sync.test.ts b/apps/server/src/omnirush-model-catalog-sync.test.ts
index 7a85c2a9..7544e8c9 100644
--- a/apps/server/src/omnirush-model-catalog-sync.test.ts
+++ b/apps/server/src/omnirush-model-catalog-sync.test.ts
@@ -264,95 +264,6 @@ describe("omnirush model catalog sync", () => {
});
});
-describe("omnirush model catalog sync on an engine that re-reads its config (2.x)", () => {
- test("the catalog is applied live: no reload, no wait for idle, even while a turn runs", async () => {
- const config = await setup();
- await writeOmniRushRuntimeConfigFile(config);
- const live: string[][] = [];
- let busyChecks = 0;
- let reloads = 0;
- const sync = new OmniRushModelCatalogSync({
- config,
- fetchCatalog: async () => Response.json(backendCatalogBody()),
- applyLive: async (write) => {
- await write();
- // The engine re-reads the file it was handed: it sees the new models.
- live.push(await engineModelIds(config));
- return true;
- },
- reloadEngine: async () => { reloads += 1; },
- engineBusy: async () => {
- busyChecks += 1;
- return true;
- },
- reloadRetryMs: 10,
- });
- cleanups.push(() => sync.stop());
-
- expect(await sync.run()).toBe("applied");
- expect(live).toEqual([MUSE_ENGINE_IDS]);
- await new Promise((resolve) => setTimeout(resolve, 50));
- expect(reloads).toBe(0);
- expect(busyChecks).toBe(0);
- expect(await sync.run()).toBe("unchanged");
- expect(live).toHaveLength(1);
- });
-
- test("an engine that cannot take it live (1.x) still waits for idle and reloads once", async () => {
- const config = await setup();
- let busy = true;
- let writes = 0;
- const reloads: string[][] = [];
- const sync = new OmniRushModelCatalogSync({
- config,
- fetchCatalog: async () => Response.json(backendCatalogBody()),
- applyLive: async (write) => {
- writes += 1;
- await write();
- return false;
- },
- reloadEngine: async () => { reloads.push(await engineModelIds(config)); },
- engineBusy: async () => busy,
- reloadRetryMs: 10,
- });
- cleanups.push(() => sync.stop());
-
- expect(await sync.run()).toBe("applied");
- await waitFor(() => writes >= 3);
- expect(reloads).toEqual([]);
- busy = false;
- await waitFor(() => reloads.length > 0);
- await new Promise((resolve) => setTimeout(resolve, 50));
- expect(reloads).toEqual([MUSE_ENGINE_IDS]);
- });
-
- test("a failed live apply is retried and never falls back to a restart", async () => {
- const config = await setup();
- let failures = 2;
- let applied = 0;
- let reloads = 0;
- const sync = new OmniRushModelCatalogSync({
- config,
- fetchCatalog: async () => Response.json(backendCatalogBody()),
- applyLive: async (write) => {
- await write();
- if (failures-- > 0) throw new Error("engine config write failed");
- applied += 1;
- return true;
- },
- reloadEngine: async () => { reloads += 1; },
- reloadRetryMs: 10,
- });
- cleanups.push(() => sync.stop());
-
- expect(await sync.run()).toBe("applied");
- await waitFor(() => applied > 0);
- await new Promise((resolve) => setTimeout(resolve, 50));
- expect(applied).toBe(1);
- expect(reloads).toBe(0);
- });
-});
-
describe("a prompt before the first catalog sync", () => {
test("starts the first pass at once instead of after the initial delay, and waits for it to land", async () => {
const config = await setup();
@@ -363,12 +274,9 @@ describe("a prompt before the first catalog sync", () => {
await new Promise((resolve) => setTimeout(resolve, 30));
return Response.json(backendCatalogBody());
},
- applyLive: async (write) => {
- await write();
+ reloadEngine: async () => {
live.push(await engineModelIds(config));
- return true;
},
- reloadEngine: async () => undefined,
initialDelayMs: 60_000,
intervalMs: 60_000,
});
@@ -406,7 +314,6 @@ describe("a prompt before the first catalog sync", () => {
const handle = startOmniRushModelCatalogSync({
config,
broker: { enabled: true, modelCatalog: async () => { fetches += 1; return Response.json(backendCatalogBody()); } },
- applyLive: async (write) => { await write(); return true; },
reloadEngine: async () => undefined,
initialDelayMs: 60_000,
});
diff --git a/apps/server/src/omnirush-model-catalog-sync.ts b/apps/server/src/omnirush-model-catalog-sync.ts
index 524950e6..d8184947 100644
--- a/apps/server/src/omnirush-model-catalog-sync.ts
+++ b/apps/server/src/omnirush-model-catalog-sync.ts
@@ -10,11 +10,9 @@
* rewrites it from the new cache (keepOmniRushRuntimeConfigFileFresh), so its
* `changed` flag may already be spent by the time the sync writes.
*
- * An engine that re-reads its config while running (the 2.x engine) gets the
- * change live: no restart, no reload, so a turn in flight is never cut off.
- * Only an engine that cannot (1.x) is reloaded, and only once no session
- * runs. The engine pool rewrites the file before a rollover and skips an
- * unchanged fingerprint, so an extra reload costs nothing.
+ * The engine is reloaded only once no session runs, so a turn in flight is
+ * never cut off. The engine pool rewrites the file before a rollover and
+ * skips an unchanged fingerprint, so an extra reload costs nothing.
*
* A prompt sent before the first sync has settled waits for it (briefly, see
* awaitOmniRushModelCatalogSettled): on a fresh profile the engine starts on
@@ -41,12 +39,6 @@ export type OmniRushModelCatalogSyncOptions = {
config: ServerConfig;
fetchCatalog: () => Promise<Response>;
reloadEngine: () => Promise<void>;
- /**
- * Applies the change without an engine reload when the engine supports it.
- * Must run `write` (rewrites the runtime config file) exactly once, and
- * resolve true only when the engine took the change live.
- */
- applyLive?: (write: () => Promise<void>) => Promise<boolean>;
/** A busy engine defers the reload; unknown activity never blocks it. */
engineBusy?: () => Promise<boolean>;
log?: SyncLog;
@@ -173,26 +165,6 @@ export class OmniRushModelCatalogSync {
private async reload(): Promise<void> {
if (!this.reloadPending || this.stopped) return;
- const write = async () => {
- await writeOmniRushRuntimeConfigFile(this.options.config);
- };
- if (this.options.applyLive) {
- try {
- // Live first: nothing restarts, so it never waits for idle and never
- // cuts off a run in flight.
- if (await this.options.applyLive(write)) {
- this.reloadPending = false;
- this.options.log?.("info", "omnirush.ai model catalog applied to the running engine");
- return;
- }
- } catch (error) {
- this.options.log?.("warn", "omnirush.ai model catalog live apply failed; retrying", {
- error: error instanceof Error ? error.message : "unknown",
- });
- this.scheduleReload();
- return;
- }
- }
if (await this.engineBusy()) {
this.scheduleReload();
return;
@@ -200,7 +172,7 @@ export class OmniRushModelCatalogSync {
try {
// An engine without a rollover pool reloads in place and reads the file
// as it stands; the pool rewrites it itself before comparing.
- if (!this.options.applyLive) await write();
+ await writeOmniRushRuntimeConfigFile(this.options.config);
await this.options.reloadEngine();
this.reloadPending = false;
} catch (error) {
@@ -239,7 +211,6 @@ export function startOmniRushModelCatalogSync(input: {
config: ServerConfig;
broker: Pick<OmniRushGatewayBroker, "enabled" | "modelCatalog">;
reloadEngine: () => Promise<void>;
- applyLive?: (write: () => Promise<void>) => Promise<boolean>;
engineBusy?: () => Promise<boolean>;
log?: SyncLog;
initialDelayMs?: number;
@@ -252,7 +223,6 @@ export function startOmniRushModelCatalogSync(input: {
config: input.config,
fetchCatalog: () => input.broker.modelCatalog(),
reloadEngine: input.reloadEngine,
- applyLive: input.applyLive,
engineBusy: input.engineBusy,
log: input.log,
initialDelayMs: input.initialDelayMs,
diff --git a/apps/server/src/omnirush-runtime-config.test.ts b/apps/server/src/omnirush-runtime-config.test.ts
index be79f49c..9be08c0e 100644
--- a/apps/server/src/omnirush-runtime-config.test.ts
+++ b/apps/server/src/omnirush-runtime-config.test.ts
@@ -36,7 +36,6 @@ import {
import { gitWorkflowPermissionRules } from "./git-command-policy.js";
import { OMNIRUSH_AGENT_PROMPT } from "./omnirush-agent-prompt.js";
import { BestPracticesEngineReloads, OMNIRUSH_BEST_PRACTICES, omnirushBestPracticesSkillsDir, waitForBestPracticesReady } from "./best-practices.js";
-import { buildEngine2Config } from "./engine2/config.js";
import type { ServerConfig } from "./types.js";
const roots: string[] = [];
@@ -328,7 +327,7 @@ describe("omnirush runtime config file", () => {
expect(prompt).toContain("## OmniRush.ai Artifacts");
expect(prompt).toContain("## Connected work");
expect(prompt).toContain("Split real work: for a task of more than a few tool calls, start one sub-agent per independent part in one message");
- expect(prompt).toContain("make exactly that many subagent calls, no more and no fewer, and start them all in one message");
+ expect(prompt).toContain("make exactly that many task-tool calls, no more and no fewer, and start them all in one message");
expect(prompt).toContain("Never paste the user's whole message, or the user's instructions about sub-agents, into a sub-agent's prompt");
expect(prompt).toContain("Never replace an explicit delegation request with a simulated multi-role answer");
expect(prompt).toContain("Wait for every delegated task");
@@ -438,14 +437,12 @@ describe("omnirush runtime config file", () => {
for (const skill of OMNIRUSH_BEST_PRACTICES.skills) {
expect(await readFile(join(bestDir, skill.name, "SKILL.md"), "utf8")).toBe(skill.content);
}
- expect(buildEngine2Config({ v1: on })).toMatchObject({ skills: [swarmDir, bestDir], agents: { omnirush: { system: prompt } } });
await writeGlobalRuntimeOpencodeConfig(config, (current) => ({ ...current, bestPractices: false }));
await writeOmniRushRuntimeConfigFile(config);
const off = await readConfigFile(config);
expect(off).toMatchObject({ skills: { paths: [swarmDir] }, agent: { omnirush: { prompt: OMNIRUSH_AGENT_PROMPT } } });
expect(off.bestPractices).toBeUndefined();
- expect(buildEngine2Config({ v1: off })).toMatchObject({ skills: [swarmDir], agents: { omnirush: { system: OMNIRUSH_AGENT_PROMPT } } });
// A fresh config object, as on startup, still reads the local persisted choice.
expect(JSON.parse(await buildOmniRushRuntimeConfig({ ...config }))).toEqual(off);
expect(await readFile(join(swarmDir, OMNIRUSH_SWARM_SKILL_NAME, "SKILL.md"), "utf8")).toBe(omnirushSwarmSkillMarkdown());
diff --git a/apps/server/src/omnirush-runtime-config.ts b/apps/server/src/omnirush-runtime-config.ts
index b07baa39..ac059085 100644
--- a/apps/server/src/omnirush-runtime-config.ts
+++ b/apps/server/src/omnirush-runtime-config.ts
@@ -25,6 +25,7 @@ import {
omnirushTitleRecoveryPluginPath,
omnirushReasoningEffortPluginPath,
omnirushSwarmPluginPath,
+ omnirushBudgetWrapPluginPath,
omnirushOfficeAttachmentsPluginPath,
omnirushSpreadsheetsPluginPath,
omnirushChromeDevtoolsPluginPath,
@@ -231,6 +232,10 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(
// writes and reads the board itself, and never pays for the tool
// definition on its requests.
[OMNIRUSH_SWARM_TOOL_NAME]: "deny",
+ // The engine denies its question tool to every agent but its own
+ // build and plan agents; the app answers questions, so the main
+ // agent may ask (sub-agents still cannot).
+ question: "allow",
},
},
// The engine hides the task tool from a sub-agent unless the sub-agent's
@@ -252,6 +257,7 @@ export function buildOmniRushRuntimeConfigObjectFromSnapshot(
// catalogs, so rules precede state and state precedes data.
omnirushCapabilitiesKnowledgePluginPath(),
omnirushExtensionsPreviewPluginPath(),
+ omnirushBudgetWrapPluginPath(),
omnirushOfficeAttachmentsPluginPath(),
omnirushSpreadsheetsPluginPath(),
omnirushPdfAttachmentsPluginPath(),
diff --git a/apps/server/src/omnirush-swarm.ts b/apps/server/src/omnirush-swarm.ts
index 9ad7a2f6..eca6af0e 100644
--- a/apps/server/src/omnirush-swarm.ts
+++ b/apps/server/src/omnirush-swarm.ts
@@ -8,10 +8,9 @@
* coordinating through one `.omnirush/swarm.md` board. Only a swarm gets a
* board: the procedure is the on-demand omnirush-swarm skill, and the
* always-on prompt only says when to load it. The bundled engine (opencode
- * 2.x) counts sub-agent layers from the main session through `parentID` and
- * refuses the subagent tool (the 1.x task tool) at
- * `experimental.subagent_depth`; it has no fan-out limit of its own, so the
- * plugin adds one.
+ * 1.18.32) counts sub-agent layers from the main session through `parentID`
+ * and refuses the task tool at `subagent_depth`; it has no fan-out limit of
+ * its own, so the plugin adds one.
*
* Kept dependency-free: the engine plugin bundle imports it.
*/
@@ -151,14 +150,14 @@ Before you start ${OMNIRUSH_SWARM_MIN_AGENTS} or more sub-agents for implementat
/** The body of the omnirush-swarm skill (without frontmatter). */
export const OMNIRUSH_SWARM_SKILL = `# Sub-agent swarm
-Use this only for a real implementation swarm: ${OMNIRUSH_SWARM_MIN_AGENTS} or more sub-agents working in parallel, or the user asked for a swarm or for ${OMNIRUSH_SWARM_MIN_AGENTS}+ agents. For 1-2 sub-agents, stop here: call the subagent tool directly and do not create or touch a board.
+Use this only for a real implementation swarm: ${OMNIRUSH_SWARM_MIN_AGENTS} or more sub-agents working in parallel, or the user asked for a swarm or for ${OMNIRUSH_SWARM_MIN_AGENTS}+ agents. For 1-2 sub-agents, stop here: call the task tool directly and do not create or touch a board.
The board is \`${OMNIRUSH_SWARM_FILE}\` in the workspace, never a file in the project root. It is a short status board, not a report: every agent re-reads it, so keep it small. omnirush.ai keeps it out of git and clears it when your turn ends. Ignore any \`swarm.md\` in the project root: it is not this swarm's board.
1. Before delegating, create \`${OMNIRUSH_SWARM_FILE}\` (replace it if one exists) with: \`# Goal\` (at most 3 sentences), \`## Tasks\` (a table: id, task, owner, status, result; ids like T1, T2, and T1.1 for a sub-task of T1; status is todo, running, done or blocked; every cell one short line), \`## Findings\` (empty) and \`## Decisions\` (choices every agent must follow, one line each).
-2. Give each sub-agent one task id. Its subagent-tool prompt names the id and only its own part of the work (never the user's whole message or instructions about sub-agents), and says: use the \`${OMNIRUSH_SWARM_TOOL_NAME}\` tool with your task id (it shows your row and the Decisions, and sets your status, one-line result and at most ${OMNIRUSH_SWARM_FINDINGS_PER_TASK} one-line findings); do not read or edit the board file; report back briefly.
+2. Give each sub-agent one task id. Its task-tool prompt names the id and only its own part of the work (never the user's whole message or instructions about sub-agents), and says: use the \`${OMNIRUSH_SWARM_TOOL_NAME}\` tool with your task id (it shows your row and the Decisions, and sets your status, one-line result and at most ${OMNIRUSH_SWARM_FINDINGS_PER_TASK} one-line findings); do not read or edit the board file; report back briefly.
3. Sub-agents do their own task themselves, even long ones. Split a task further only when the user explicitly asked for nested sub-agents: then its prompt tells that sub-agent to add sub-task rows (T1.1, T1.2) with \`${OMNIRUSH_SWARM_TOOL_NAME}\` and gives the same instructions to its own sub-agents. Sub-agents nest at most ${OMNIRUSH_SUBAGENT_DEPTH} layers deep. Start as many sub-agents as the work needs, and no more.
-4. Launch independent tasks in parallel (several subagent calls in one message); give tasks that edit the same files to one agent.
+4. Launch independent tasks in parallel (several task calls in one message); give tasks that edit the same files to one agent.
5. When every task is done, read \`${OMNIRUSH_SWARM_FILE}\` once, check the results against the task reports, and answer the user. Do not move, copy or archive the board: omnirush.ai does that when the turn ends. Board cells over ${OMNIRUSH_SWARM_CELL_MAX_CHARS} characters, lines over ${OMNIRUSH_SWARM_LINE_MAX_CHARS} and findings past ${OMNIRUSH_SWARM_FINDINGS_PER_TASK} per task are cut.`;
/** The omnirush-swarm skill's SKILL.md. */
@@ -185,7 +184,7 @@ export function omnirushSubagentNote(depth: number): string {
`You are a sub-agent (layer ${depth} of at most ${OMNIRUSH_SUBAGENT_DEPTH}). Do your task yourself.`,
"Instructions about sub-agents that the user wrote (how many agents to use, what to delegate) were meant for the main session, which already carried them out: do not repeat them.",
depth < OMNIRUSH_SUBAGENT_DEPTH
- ? "Start sub-agents with the subagent tool only if your task explicitly tells you to implement a part; otherwise do the whole task yourself, even when it is long. Never re-delegate your whole task."
+ ? "Start sub-agents with the task tool only if your task explicitly tells you to implement a part; otherwise do the whole task yourself, even when it is long. Never re-delegate your whole task."
: "You cannot delegate further: do the work yourself.",
].join("\n");
}
@@ -209,7 +208,7 @@ export function omnirushSwarmSubagentNote(depth: number): string {
}
/**
- * Appended to the engine's subagent tool (the 1.x task tool) description
+ * Appended to the engine's task tool description
* (every agent that has the tool, main or sub-agent). The engine's own text
* asks for detailed prompts and parallel launches; this bounds both.
*/
diff --git a/apps/server/src/opencode-config-compat.ts b/apps/server/src/opencode-config-compat.ts
index 550aff0b..40e8edc2 100644
--- a/apps/server/src/opencode-config-compat.ts
+++ b/apps/server/src/opencode-config-compat.ts
@@ -1,7 +1,6 @@
/**
- * Pre-flight compatibility check for user-owned OpenCode config files, for a
- * 1.x engine (OMNIRUSH_OPENCODE_BIN). The bundled 2.x engine reads both
- * `permission` and `permissions`, so the server skips this check for it.
+ * Pre-flight compatibility check for user-owned OpenCode config files, for
+ * the bundled 1.x engine (or OMNIRUSH_OPENCODE_BIN).
*
* A 1.x engine (OpenCode V1) lowers V2-style
* config on load (packages/opencode/src/config/v2-compat.ts). Most V2 keys
diff --git a/apps/server/src/opencode-plugins/omnirush-budget-wrap.test.ts b/apps/server/src/opencode-plugins/omnirush-budget-wrap.test.ts
index 61a675d5..ff6bc362 100644
--- a/apps/server/src/opencode-plugins/omnirush-budget-wrap.test.ts
+++ b/apps/server/src/opencode-plugins/omnirush-budget-wrap.test.ts
@@ -1,102 +1,115 @@
-import { afterEach, describe, expect, test } from "bun:test";
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { OmniRushBudgetWrap } from "./omnirush-budget-wrap.js";
-const previousAdapter = process.env.OMNIRUSH_ENGINE_ADAPTER_URL;
-const previousAuthorization = process.env.OMNIRUSH_ENGINE_ADAPTER_AUTHORIZATION;
-
-afterEach(() => {
- if (previousAdapter === undefined) delete process.env.OMNIRUSH_ENGINE_ADAPTER_URL;
- else process.env.OMNIRUSH_ENGINE_ADAPTER_URL = previousAdapter;
- if (previousAuthorization === undefined) delete process.env.OMNIRUSH_ENGINE_ADAPTER_AUTHORIZATION;
- else process.env.OMNIRUSH_ENGINE_ADAPTER_AUTHORIZATION = previousAuthorization;
+/**
+ * The engine sends model requests through the global fetch: the plugin wraps
+ * it and reads the backend's wrap headers on the requests it marked in
+ * `chat.headers`. The model responses here come from a stand-in global fetch.
+ */
+const gatewayHeaders = new Map<string, Record<string, string>>();
+const originalFetch = globalThis.fetch;
+beforeAll(() => {
+ globalThis.fetch = Object.assign(async (input: Parameters<typeof fetch>[0], init?: RequestInit) => {
+ const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
+ return new Response("{}", { status: 200, headers: gatewayHeaders.get(headers.get("x-omnirush-session-id") ?? "") ?? {} });
+ }, originalFetch);
+});
+afterAll(() => {
+ globalThis.fetch = originalFetch;
});
+type Hooks = Awaited<ReturnType<typeof OmniRushBudgetWrap>>;
+
+/** One model request of `sessionID` as the engine sends it: headers from chat.headers, then the global fetch. */
+async function modelRequest(hooks: Hooks, sessionID: string, answer: Record<string, string>): Promise<void> {
+ const headers: Record<string, string> = { "content-type": "application/json" };
+ await hooks["chat.headers"]!({ sessionID, model: { providerID: "omnirush", id: "gpt-6-astra" } }, { headers });
+ gatewayHeaders.set(sessionID, answer);
+ await (await fetch("http://gateway.test/v1/responses", { method: "POST", headers, body: "{}" })).text();
+}
+
describe("account budget wrap plugin", () => {
- test("waits for session idle, then compacts without inserting a trace message", async () => {
- process.env.OMNIRUSH_ENGINE_ADAPTER_URL = "http://adapter.test";
- process.env.OMNIRUSH_ENGINE_ADAPTER_AUTHORIZATION = "Bearer adapter";
+ test("waits for session idle, then compacts on the session's model without inserting a trace message", async () => {
const calls: Array<{ url: string; init?: RequestInit }> = [];
const hooks = await OmniRushBudgetWrap({
directory: "/workspace/project",
+ serverUrl: new URL("http://127.0.0.1:4096"),
fetch: async (input, init) => {
calls.push({ url: String(input), init });
- return new Response(null, { status: 204 });
+ return new Response("true", { status: 200 });
},
});
const modelHeaders: Record<string, string> = {};
- await hooks["chat.headers"]!({ sessionID: "ses_1", model: { providerID: "omnirush" } }, { headers: modelHeaders });
+ await hooks["chat.headers"]!({ sessionID: "ses_1", model: { providerID: "omnirush", id: "gpt-6-astra" } }, { headers: modelHeaders });
expect(modelHeaders["x-omnirush-session-id"]).toBe("ses_1");
+ const otherHeaders: Record<string, string> = {};
+ await hooks["chat.headers"]!({ sessionID: "ses_1", model: { providerID: "openai", id: "gpt-x" } }, { headers: otherHeaders });
+ expect(otherHeaders["x-omnirush-session-id"]).toBeUndefined();
- await hooks["omnirush.http.response"]!({
- request: new Request("http://gateway.test/v1/responses", {
- headers: { "x-omnirush-session-id": "ses_1" },
- }),
- response: new Response(null, {
- status: 200,
- headers: { "x-omnirush-wrap-required": "1" },
- }),
- });
+ await modelRequest(hooks, "ses_1", { "x-omnirush-wrap-required": "1" });
await hooks.event!({ event: { type: "session.updated", properties: { sessionID: "ses_1" } } });
expect(calls).toHaveLength(0);
await hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_1" } } });
expect(calls).toHaveLength(1);
- expect(calls[0]!.url).toBe("http://adapter.test/session/ses_1/summarize");
+ expect(calls[0]!.url).toBe("http://127.0.0.1:4096/session/ses_1/summarize");
expect(calls[0]!.init?.method).toBe("POST");
- expect(calls[0]!.init?.body).toBe("{}");
- expect(new Headers(calls[0]!.init?.headers).get("authorization")).toBe("Bearer adapter");
+ expect(JSON.parse(String(calls[0]!.init?.body))).toEqual({ providerID: "omnirush", modelID: "gpt-6-astra" });
expect(new Headers(calls[0]!.init?.headers).get("x-opencode-directory")).toBe(encodeURIComponent("/workspace/project"));
+
+ // Done: the next idle does nothing.
+ await hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_1" } } });
+ expect(calls).toHaveLength(1);
});
test("the backend wrap-up response clears the pending marker", async () => {
- process.env.OMNIRUSH_ENGINE_ADAPTER_URL = "http://adapter.test";
const calls: string[] = [];
const hooks = await OmniRushBudgetWrap({
+ serverUrl: "http://127.0.0.1:4096",
fetch: async (input) => {
calls.push(String(input));
- return new Response(null, { status: 204 });
+ return new Response("true", { status: 200 });
},
});
- const request = new Request("http://gateway.test/v1/responses", {
- headers: { "x-omnirush-session-id": "ses_2" },
- });
- await hooks["omnirush.http.response"]!({
- request,
- response: new Response(null, { status: 200, headers: { "x-omnirush-wrap-required": "1" } }),
- });
- await hooks["omnirush.http.response"]!({
- request,
- response: new Response(null, { status: 200, headers: { "x-omnirush-wrap-up": "1" } }),
- });
+ await modelRequest(hooks, "ses_2", { "x-omnirush-wrap-required": "1" });
+ await modelRequest(hooks, "ses_2", { "x-omnirush-wrap-up": "1" });
await hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_2" } } });
expect(calls).toHaveLength(0);
});
+ test("a request without the marker never starts a wrap", async () => {
+ const calls: string[] = [];
+ const hooks = await OmniRushBudgetWrap({
+ serverUrl: "http://127.0.0.1:4096",
+ fetch: async (input) => {
+ calls.push(String(input));
+ return new Response("true", { status: 200 });
+ },
+ });
+ gatewayHeaders.set("", { "x-omnirush-wrap-required": "1" });
+ await (await fetch("http://gateway.test/v1/responses", { method: "POST", body: "{}" })).text();
+ await hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_4" } } });
+ expect(calls).toHaveLength(0);
+ });
+
test("a failed wrap retries on the next idle without showing the toast again", async () => {
- process.env.OMNIRUSH_ENGINE_ADAPTER_URL = "http://adapter.test";
const toasts: string[] = [];
let attempts = 0;
const hooks = await OmniRushBudgetWrap({
+ serverUrl: "http://127.0.0.1:4096",
client: { tui: { showToast: async ({ body }) => { toasts.push(body.title); } } },
fetch: async () => {
attempts += 1;
- return new Response(null, { status: attempts < 3 ? 500 : 204 });
+ return new Response(null, { status: attempts < 3 ? 500 : 200 });
},
});
- const request = new Request("http://gateway.test/v1/responses", {
- headers: { "x-omnirush-session-id": "ses_3" },
- });
- const required = () => hooks["omnirush.http.response"]!({
- request,
- response: new Response(null, { status: 200, headers: { "x-omnirush-wrap-required": "1" } }),
- });
- await required();
+ await modelRequest(hooks, "ses_3", { "x-omnirush-wrap-required": "1" });
for (let idle = 0; idle < 3; idle += 1) {
// Every answer of the retried turns still asks for the wrap.
- await required();
+ await modelRequest(hooks, "ses_3", { "x-omnirush-wrap-required": "1" });
await hooks.event!({ event: { type: "session.idle", properties: { sessionID: "ses_3" } } });
}
expect(attempts).toBe(3);
diff --git a/apps/server/src/opencode-plugins/omnirush-budget-wrap.ts b/apps/server/src/opencode-plugins/omnirush-budget-wrap.ts
index cbe95c4f..703d8374 100644
--- a/apps/server/src/opencode-plugins/omnirush-budget-wrap.ts
+++ b/apps/server/src/opencode-plugins/omnirush-budget-wrap.ts
@@ -1,14 +1,21 @@
/** Automatically finish an account-level quota wrap in the desktop GUI.
*
* The backend decides when a grant needs wrapping and publishes a private
- * response header. This plugin waits until the engine reports the session
- * idle, then asks the local engine to compact. The compaction record itself
- * contains the generated handoff summary; no warning or synthetic prompt is
- * written to the session trace.
+ * response header on the model response. The engine sends model requests
+ * through the global fetch, which this plugin wraps to read that header on
+ * requests it marked (`chat.headers`). Once the engine reports the session
+ * idle it asks the engine to compact the session on the model it last ran on.
+ * The compaction record itself contains the generated handoff summary; no
+ * warning or synthetic prompt is written to the session trace.
*/
const REQUIRED_HEADER = "x-omnirush-wrap-required";
const WRAP_UP_HEADER = "x-omnirush-wrap-up";
+const SESSION_HEADER = "x-omnirush-session-id";
+type ModelRef = { providerID: string; modelID: string };
const pending = new Map<string, { inFlight: boolean; announced?: boolean }>();
+/** The model each session last sent a request on (the compaction runs on it). */
+const models = new Map<string, ModelRef>();
+const MAX_TRACKED_SESSIONS = 256;
type BudgetFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
type BudgetClient = {
tui?: { showToast?: (input: { query?: { directory?: string }; body: { title: string; message: string; variant: string; duration: number } }) => Promise<unknown> };
@@ -26,13 +33,56 @@ function sessionIDFromEvent(event: unknown): string {
return typeof properties.sessionID === "string" ? properties.sessionID : "";
}
+function remember<T>(map: Map<string, T>, key: string, value: T): void {
+ map.delete(key);
+ map.set(key, value);
+ while (map.size > MAX_TRACKED_SESSIONS) map.delete(map.keys().next().value as string);
+}
+
+/** Records what a model response says about the session's wrap. */
+function noteBudgetResponse(sessionID: string, headers: Headers): void {
+ if (!sessionID) return;
+ if (headers.get(WRAP_UP_HEADER) === "1") {
+ pending.delete(sessionID);
+ return;
+ }
+ if (headers.get(REQUIRED_HEADER) === "1" && !pending.has(sessionID)) remember(pending, sessionID, { inFlight: false });
+}
+
+let installed = false;
+
+/** Wraps the global fetch once: a marked model request's response headers are read, nothing else changes. */
+function install(): void {
+ if (installed) return;
+ installed = true;
+ const base = globalThis.fetch;
+ const patched = async (input: Parameters<typeof fetch>[0], init?: RequestInit): Promise<Response> => {
+ const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : undefined));
+ const sessionID = headers.get(SESSION_HEADER)?.trim() ?? "";
+ const response = await base(input, init);
+ if (sessionID) noteBudgetResponse(sessionID, response.headers);
+ return response;
+ };
+ globalThis.fetch = Object.assign(patched, base);
+}
+
+function basicAuthorization(): string {
+ const password = process.env.OPENCODE_SERVER_PASSWORD?.trim() ?? "";
+ if (!password) return "";
+ const username = process.env.OPENCODE_SERVER_USERNAME?.trim() || "opencode";
+ return `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`;
+}
+
export const OmniRushBudgetWrap = async (input: {
directory?: string;
+ /** The engine's own server (the plugin input's `serverUrl`). */
+ serverUrl?: URL | string;
fetch?: BudgetFetch;
client?: BudgetClient;
}) => {
- const baseUrl = (process.env.OMNIRUSH_ENGINE_ADAPTER_URL?.trim() ?? "").replace(/\/+$/, "");
- const authorization = process.env.OMNIRUSH_ENGINE_ADAPTER_AUTHORIZATION?.trim() ?? "";
+ install();
+ const baseUrl = String(input.serverUrl ?? "").replace(/\/+$/, "");
+ const authorization = basicAuthorization();
const fetcher = input.fetch ?? globalThis.fetch;
async function notify(title: string, message: string, variant: "info" | "warning"): Promise<void> {
@@ -63,7 +113,8 @@ export const OmniRushBudgetWrap = async (input: {
async function compact(sessionID: string): Promise<void> {
const entry = pending.get(sessionID);
- if (!entry || entry.inFlight || !baseUrl) return;
+ const model = models.get(sessionID);
+ if (!entry || entry.inFlight || !baseUrl || !model) return;
entry.inFlight = true;
// Once per wrap: a failed summarize retries on the next idle without
// showing the toast again.
@@ -81,7 +132,7 @@ export const OmniRushBudgetWrap = async (input: {
...(authorization ? { authorization } : {}),
...(input.directory ? { "x-opencode-directory": encodeURIComponent(input.directory) } : {}),
},
- body: "{}",
+ body: JSON.stringify({ providerID: model.providerID, modelID: model.modelID }),
},
);
if (!response.ok) throw new Error("automatic budget wrap returned " + response.status);
@@ -99,22 +150,12 @@ export const OmniRushBudgetWrap = async (input: {
}
return {
- "chat.headers": async (input: { sessionID?: string; model?: { providerID?: string } }, output: { headers: Record<string, string> }) => {
+ "chat.headers": async (input: { sessionID?: string; model?: { providerID?: string; id?: string; modelID?: string } }, output: { headers: Record<string, string> }) => {
const sessionID = input?.sessionID?.trim() ?? "";
- if (sessionID && input.model?.providerID === "omnirush") output.headers["x-omnirush-session-id"] = sessionID;
- },
- "omnirush.http.response": async (event: { request?: Request; response?: Response }) => {
- const request = event?.request;
- const response = event?.response;
- const sessionID = request?.headers.get("x-omnirush-session-id")?.trim() ?? "";
- if (!sessionID || !response) return;
- if (response.headers.get(WRAP_UP_HEADER) === "1") {
- pending.delete(sessionID);
- return;
- }
- if (response.headers.get(REQUIRED_HEADER) === "1" && !pending.has(sessionID)) {
- pending.set(sessionID, { inFlight: false });
- }
+ if (!sessionID || input.model?.providerID !== "omnirush") return;
+ output.headers[SESSION_HEADER] = sessionID;
+ const modelID = input.model.id ?? input.model.modelID;
+ if (modelID) remember(models, sessionID, { providerID: input.model.providerID, modelID });
},
event: async ({ event }: { event: unknown }) => {
if (!record(event) || event.type !== "session.idle") return;
@@ -123,6 +164,7 @@ export const OmniRushBudgetWrap = async (input: {
},
dispose: async () => {
pending.clear();
+ models.clear();
},
};
};
diff --git a/apps/server/src/opencode-plugins/omnirush-pdf-attachments.test.ts b/apps/server/src/opencode-plugins/omnirush-pdf-attachments.test.ts
index a3cac1b0..2836ca31 100644
--- a/apps/server/src/opencode-plugins/omnirush-pdf-attachments.test.ts
+++ b/apps/server/src/opencode-plugins/omnirush-pdf-attachments.test.ts
@@ -491,9 +491,8 @@ describe("OmniRush.ai PDF attachments plugin", () => {
});
}, 30_000);
- test("on the 2.x engine the step's model comes from the hook input, since the bridge's messages carry no model", async () => {
- // omnirush-engine2.ts messagesForV1 gives each message only {id, role} and
- // passes {sessionID, model} as the hook input.
+ test("the step's model comes from the hook input when the messages carry no model", async () => {
+ // Messages whose info is only {id, role}, with {sessionID, model} as the hook input.
await withWorkspace(async (root) => {
await mkdir(join(root, "docs"), { recursive: true });
await writeFile(join(root, "docs", "spec.pdf"), buildTestPdf(["Spec page one", "Spec page two"]));
diff --git a/apps/server/src/opencode-plugins/omnirush-pdf-attachments.ts b/apps/server/src/opencode-plugins/omnirush-pdf-attachments.ts
index 9cc037f3..dbec508d 100644
--- a/apps/server/src/opencode-plugins/omnirush-pdf-attachments.ts
+++ b/apps/server/src/opencode-plugins/omnirush-pdf-attachments.ts
@@ -604,10 +604,9 @@ function stepModel(messages: unknown[]): StepModel | null {
}
/**
- * The step's model from the hook input. The 2.x engine bridge
- * (omnirush-engine2.ts) passes `{sessionID, model}` there and hands the hook
- * messages whose `info` is only `{id, role}`, so `stepModel` finds nothing in
- * them; the 1.x engine passes an empty input and full message infos.
+ * The step's model from the hook input, when the engine passes
+ * `{sessionID, model}` there; the 1.x engine passes an empty input and full
+ * message infos, which `stepModel` reads.
*/
function hookModel(input: unknown): StepModel | null {
if (!isRecord(input) || !isRecord(input.model)) return null;
diff --git a/apps/server/src/opencode-plugins/omnirush-swarm.test.ts b/apps/server/src/opencode-plugins/omnirush-swarm.test.ts
index f1bfb9c6..2c119e31 100644
--- a/apps/server/src/opencode-plugins/omnirush-swarm.test.ts
+++ b/apps/server/src/opencode-plugins/omnirush-swarm.test.ts
@@ -144,7 +144,7 @@ describe("omnirush swarm plugin", () => {
expect(await system("ses_grand")).toContain("layer 2 of at most 3");
const great = await system("ses_great");
expect(great).toContain("You cannot delegate further");
- expect(great).not.toContain("Start sub-agents with the subagent tool");
+ expect(great).not.toContain("Start sub-agents with the task tool");
// Same text on every step (prompt cache).
expect(await system("ses_child")).toBe(child);
});
diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts
index 8ca378cf..a615b96e 100644
--- a/apps/server/src/server.ts
+++ b/apps/server/src/server.ts
@@ -202,7 +202,7 @@ import type { ArchiveApiRequestInit } from "./session-archive/upload.js";
import { runtimeStorageDir } from "./runtime-db.js";
import pkg from "../package.json" with { type: "json" };
import constants from "../../../constants.json" with { type: "json" };
-import { BestPracticesEngineReloads, waitForBestPracticesReady } from "./best-practices.js";
+import { BestPracticesEngineReloads } from "./best-practices.js";
export {
isSupportedWorkspaceTextFilePath,
@@ -1462,19 +1462,10 @@ export async function startServer(config: ServerConfig): Promise<ServeResult> {
engineInstanceReaper.start();
// The account's model catalog (omnirush-model-catalog-sync.ts): a change
- // reaches an engine that re-reads its config (2.x) live, with no restart;
- // any other engine reloads like a cloud provider sync, without stopping a run.
+ // reloads the engine like a cloud provider sync, without stopping a run.
const modelCatalogSync = startOmniRushModelCatalogSync({
config,
broker: gatewayBroker,
- applyLive: async (write) => {
- const pool = enginePoolForConfig(config);
- if (!pool) {
- await write();
- return false;
- }
- return pool.applyConfigLive(write);
- },
reloadEngine: async () => {
if (config.workspaces.length === 0) return;
await reloadOpencodeEngine(config, resolveEngineRuntimeWorkspace(config), engineMcpServerState, {
@@ -3616,32 +3607,7 @@ function createRoutes(
// Return a separate application status so the UI never calls it applied early.
try {
const pool = enginePoolForConfig(config);
- const write = async () => { await writeOmniRushRuntimeConfigFile(config); };
- if (pool && await pool.applyConfigLive(write)) {
- const primary = primaryManagedEngineConnection(config);
- if (!primary) throw new Error("Managed engine is unavailable");
- const authorization = buildEngineAuthProbeHeader(primary.username, primary.password);
- const baseUrl = primary.baseUrl.replace(/\/+$/, "");
- const directories = [...new Set(config.workspaces
- .filter((workspace) => resolveWorkspaceOpencodeConnection(config, workspace).baseUrl?.trim().replace(/\/+$/, "") === baseUrl)
- .map(resolveOpencodeDirectory).filter((directory): directory is string => directory !== null))];
- await waitForBestPracticesReady({
- config, enabled,
- read: async (signal) => await Promise.all(directories.map(async (directory) => {
- const read = async (path: string): Promise<unknown> => {
- const url = new URL(path, primary.baseUrl);
- url.searchParams.set("directory", directory);
- const response = await loopbackFetch(url, { headers: authorization ? { Authorization: authorization } : {}, signal });
- if (!response.ok) throw new Error("Managed engine metadata is unavailable");
- return await response.json();
- };
- const [agents, skills] = await Promise.all([read("/agent"), read("/skill")]);
- return { agents, skills };
- })),
- });
- return jsonResponse({ ok: true, enabled, changed: result.changed, engine: { status: "applied" } });
- }
- if (!pool) await write();
+ await writeOmniRushRuntimeConfigFile(config);
const workspaces = config.workspaces.filter((workspace) => resolveWorkspaceOpencodeConnection(config, workspace).baseUrl?.trim());
const workspace = findManagedEngineWorkspace(workspaces) ?? workspaces[0];
if (!workspace) {
diff --git a/docs/skills-and-mcp.md b/docs/skills-and-mcp.md
index 0cc4a97c..0c277d5e 100644
--- a/docs/skills-and-mcp.md
+++ b/docs/skills-and-mcp.md
@@ -151,12 +151,25 @@ The engine caches its skill catalog per project instance and needs an instance r
**Removing an MCP server left tools behind in a running session.**
The engine drops the registration immediately, but a session that already started a turn keeps its captured tool set until the turn ends.
-**Which engine does the app run, and what happened to `permissions` in my `opencode.json`?**
-The bundled engine is opencode 2.x (pinned in `constants.json`, published on npm as `@opencode/cli`). OmniRush.ai's server starts it on a private loopback port and serves the 1.x engine API the app is written against in front of it (the engine adapter, `apps/server/src/engine2/`), so sessions, sub-agents, permissions, MCP and the uploaded traces keep their 1.x shape. The engine reads both the 1.x `permission` rules and the 2.x `permissions` list, so a `permissions` key in a user-owned `opencode.json(c)` no longer stops startup. The runtime config OmniRush.ai renders for the engine is written to `engine2/opencode.json` next to `runtime-opencode-config.json`; OmniRush.ai's engine plugins load through `engine2/omnirush-plugin/`. MCP servers defined in a project's own config offer their tools directly (`<server>_<tool>`), not through the engine's code mode. The first start after the upgrade migrates the 1.x engine's sessions in `~/.local/share/opencode/opencode.db` in place. With `OMNIRUSH_OPENCODE_BIN` pointing at a 1.x binary the server talks to it directly, as before, and keeps the 1.x `permissions` pre-flight check.
+**The app reports "Configuration is invalid at … V2 permissions are not supported by OmniRush V1", or a workspace answers `opencode_config_invalid`.**
+The bundled engine is OpenCode V1 (pinned in `constants.json`). Since engine 1.18.32 a `permissions` key in a user-owned `opencode.json(c)` — top level, or under `agent`, `agents` or `mode.<name>` — is rejected instead of ignored. The server checks those files before spawning the engine: a `permissions` key in the global file (`~/.config/opencode/opencode.json(c)`, `config.json`, or the `OPENCODE_CONFIG_DIR` directory) stops startup with the message above naming the file; a `permissions` key in `<workspace>/.opencode/opencode.json(c)` or `<workspace>/opencode.json(c)` is logged as a warning, the engine still starts, server routes that read the engine for that workspace return `422 opencode_config_invalid` with the engine's message and the file path in `details`, and the native engine proxy passes the engine's own `400 ConfigInvalidError` body through unchanged. Other V2-only keys (`plugins`, `providers`, `websearch`, `warming`, …) are dropped with a "configuration compatibility diagnostic" warning in the engine log and do not block anything. Fix: rename `permissions` to `permission` (V1 rules) or remove it, then restart OmniRush.ai.
+
+**Which engine does the app run?**
+OmniRush.ai's own build of opencode 1.18.32, the engine the OmniRush CLI ships (release `engine-1.18.32-r2` of omnirush-ai/omnirush-cli, sha256-pinned per platform in `apps/desktop/scripts/engine-release.json`; `prepare-sidecar.mjs` fetches it with a token that can read that release, `OMNIRUSH_ENGINE_TOKEN`, or takes a local copy from `OMNIRUSH_ENGINE_ARCHIVE`). The server starts it directly (`managed-opencode.ts`) and OmniRush.ai's engine plugins load from the `plugin` list of the runtime config. Desktop 2.2.0 – 3.x ran the opencode 2.x engine behind an adapter; that adapter is gone.
+
+**My sessions from desktop 2.2.0 – 3.x: are they still there?**
+Yes. The 2.x engine kept them (and the 1.x sessions of earlier releases, which it moved in on its first start) in `~/.local/share/opencode/opencode.db`, in tables the 1.x engine cannot read. The first start of this release copies every session from there into the engine's own store, once (`apps/server/src/engine2/import.ts`):
+- the 2.x store is opened read-only and never changed, so an older OmniRush.ai still opens it;
+- each session becomes the 1.x export document (`apps/server/src/engine2/shapes.ts`: messages, tool calls and their results exactly as the 2.x engine recorded them, sub-agent sessions with their parents) and the engine writes it itself with `opencode import`, run in the session's folder with no plugins, no project or user config and no network; ids are kept, so a session is never written twice;
+- the import runs in the background after the engine started; sessions appear in the session lists as they are written;
+- progress is recorded in `~/.local/share/omnirush/desktop-engine2-import.json`: a session whose folder no longer exists is skipped and imported once the folder is back, a session the engine refuses is tried again on the next starts (three times at most) and the reason is kept there;
+- `OMNIRUSH_ENGINE2_IMPORT=0` turns the import off; a run with an explicit `OPENCODE_DB` skips it.
+Provider and MCP sign-ins the engine kept as files in `~/.local/share/opencode/` (`auth.json`, `mcp-auth.json`) are copied into `~/.local/share/omnirush/` once, never over a file already there. The 2.x engine kept newer sign-ins inside its database; those are not copied and have to be signed in again.
**Where are the files?**
-- Server state directory: `~/.config/omnirush/` (or the directory of `OMNIRUSH_SERVER_CONFIG`), containing `runtime.sqlite` (runtime DB), `runtime-opencode-config.json` (the engine config in 1.x keys), `engine2/opencode.json` (the same config as the 2.x engine reads it) and the managed MCP vault.
-- Engine data: `~/.local/share/opencode/` (the `opencode.db` session database, logs under `log/`).
+- Server state directory: `~/.config/omnirush/` (or the directory of `OMNIRUSH_SERVER_CONFIG`), containing `runtime.sqlite` (runtime DB), `runtime-opencode-config.json` (engine-visible config) and the managed MCP vault.
+- Engine data: `~/.local/share/omnirush/` (the `opencode.db` session database, shared with the OmniRush CLI, logs under `log/`). The engine also reads the global opencode config directory (`~/.config/opencode/`, or `OPENCODE_CONFIG_DIR`) for the app's global skills and config.
+- The 2.x engine's store of desktop 2.2.0 – 3.x: `~/.local/share/opencode/opencode.db` (read once by the import above, never written).
- Audit log: `<workspace>/.opencode/` audit entries record every skill and MCP change with the actor.
## API summary