Skip to content

A desktop coding agent with free access to frontier models.

TypeScript

feat(engine): bundle opencode 2.0.18 behind a 1.x engine adapter

Samrat Talukdaracb88e76664c
diff --git a/.github/actions/setup-tests/action.yml b/.github/actions/setup-tests/action.yml
index 8b383216..30cca990 100644
--- a/.github/actions/setup-tests/action.yml
+++ b/.github/actions/setup-tests/action.yml
@@ -15,12 +15,9 @@ runs:
- name: Install OpenCode CLI
shell: bash
- env:
- GITHUB_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
- repo="${OPENCODE_GITHUB_REPO:-anomalyco/opencode}"
version="$(node -e "const fs=require('fs'); const parsed=JSON.parse(fs.readFileSync('constants.json','utf8')); process.stdout.write(String(parsed.opencodeVersion||'').trim().replace(/^v/,''));")"
version="$(echo "$version" | tr -d '\r\n' | sed 's/^v//')"
@@ -29,20 +26,22 @@ runs:
exit 1
fi
+ # The 2.x engine is published per platform on npm (@opencode/cli-<platform>),
+ # not as GitHub release assets.
arch="$(uname -m)"
case "${RUNNER_OS}" in
Linux)
if [ "$arch" = "aarch64" ] || [ "$arch" = "arm64" ]; then
- opencode_asset="opencode-linux-arm64.tar.gz"
+ opencode_pkg="cli-linux-arm64"
else
- opencode_asset="opencode-linux-x64-baseline.tar.gz"
+ opencode_pkg="cli-linux-x64-baseline"
fi
;;
macOS)
if [ "$arch" = "arm64" ]; then
- opencode_asset="opencode-darwin-arm64.zip"
+ opencode_pkg="cli-darwin-arm64"
else
- opencode_asset="opencode-darwin-x64-baseline.zip"
+ opencode_pkg="cli-darwin-x64-baseline"
fi
;;
*)
@@ -51,32 +50,27 @@ runs:
;;
esac
- url="https://github.com/${repo}/releases/download/v${version}/${opencode_asset}"
+ registry="${OPENCODE_NPM_REGISTRY:-https://registry.npmjs.org}"
+ url="${registry}/@opencode/${opencode_pkg}/-/${opencode_pkg}-${version}.tgz"
tmp_dir="$RUNNER_TEMP/opencode"
extract_dir="$tmp_dir/extracted"
rm -rf "$tmp_dir"
mkdir -p "$extract_dir"
- curl_headers=()
- if [ -n "${GITHUB_TOKEN:-}" ]; then
- curl_headers+=( -H "Authorization: Bearer ${GITHUB_TOKEN}" )
- fi
-
- curl -fsSL --retry 5 --retry-all-errors --retry-delay 2 "${curl_headers[@]}" -o "$tmp_dir/$opencode_asset" "$url"
-
- if [[ "$opencode_asset" == *.tar.gz ]]; then
- tar -xzf "$tmp_dir/$opencode_asset" -C "$extract_dir"
- else
- unzip -q "$tmp_dir/$opencode_asset" -d "$extract_dir"
+ integrity="$(curl -fsSL --retry 5 --retry-all-errors --retry-delay 2 "${registry}/@opencode/${opencode_pkg}/${version}" | node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>process.stdout.write(JSON.parse(s).dist.integrity))")"
+ curl -fsSL --retry 5 --retry-all-errors --retry-delay 2 -o "$tmp_dir/opencode.tgz" "$url"
+ actual="sha512-$(openssl dgst -sha512 -binary "$tmp_dir/opencode.tgz" | base64 | tr -d '\n')"
+ if [ "$actual" != "$integrity" ]; then
+ echo "OpenCode package integrity mismatch: expected $integrity, got $actual" >&2
+ exit 1
fi
+ tar -xzf "$tmp_dir/opencode.tgz" -C "$extract_dir"
- if [ -f "$extract_dir/opencode" ]; then
- bin_path="$extract_dir/opencode"
- elif [ -f "$extract_dir/opencode.exe" ]; then
- bin_path="$extract_dir/opencode.exe"
+ if [ -f "$extract_dir/package/bin/opencode" ]; then
+ bin_path="$extract_dir/package/bin/opencode"
else
- echo "OpenCode binary not found in archive" >&2
- ls -la "$extract_dir"
+ echo "OpenCode binary not found in package" >&2
+ ls -laR "$extract_dir"
exit 1
fi
diff --git a/apps/desktop/electron/runtime.mjs b/apps/desktop/electron/runtime.mjs
index cda314ef..abca646e 100644
--- a/apps/desktop/electron/runtime.mjs
+++ b/apps/desktop/electron/runtime.mjs
@@ -1798,7 +1798,8 @@ export function createRuntimeManager({
if (!version) {
throw new Error("constants.json is missing opencodeVersion");
}
- return `curl -fsSL https://opencode.ai/install | bash -s -- --version ${version} --no-modify-path`;
+ // The 2.x engine ships on npm as @opencode/cli (binaries `opencode` / `opencode2`).
+ return `npm install -g @opencode/cli@${version}`;
}
function processMatchesSidecar(command) {
diff --git a/apps/desktop/electron/runtime.test.mjs b/apps/desktop/electron/runtime.test.mjs
index 44a4c30a..12572d96 100644
--- a/apps/desktop/electron/runtime.test.mjs
+++ b/apps/desktop/electron/runtime.test.mjs
@@ -90,16 +90,14 @@ describe("workspace root preparation", () => {
});
describe("bundled OpenCode runtime", () => {
- it("pins the engine release containing the timestamp-based session loop repair", async () => {
+ it("pins the 2.x engine release the desktop bundles", async () => {
const constantsPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../constants.json");
const constants = JSON.parse(await readFile(constantsPath, "utf8"));
- // OpenCode #40990 stops old assistant messages with lexicographically
- // later IDs from short-circuiting a newly appended user turn. It shipped
- // in 1.18.18; the pin has since moved to 1.18.32 (2026-09-21) for the
- // patch-release fixes on top of it (apply_patch move-path metadata,
- // config snapshot comparison, provider SDK bumps, session header fixes).
- assert.equal(constants.opencodeVersion, "v1.18.32");
+ // The bundled engine moved from the 1.x line (last pin 1.18.32) to the
+ // 2.x rewrite: 2.0.18 (2026-09-25), published on npm as @opencode/cli.
+ // The server speaks to it through the 1.x engine adapter (engine2/).
+ assert.equal(constants.opencodeVersion, "v2.0.18");
});
});
diff --git a/apps/desktop/scripts/prepare-sidecar.mjs b/apps/desktop/scripts/prepare-sidecar.mjs
index 3be5aeb4..83861b5f 100644
--- a/apps/desktop/scripts/prepare-sidecar.mjs
+++ b/apps/desktop/scripts/prepare-sidecar.mjs
@@ -156,7 +156,11 @@ const findOpencodeBinary = (dir) => {
const readBinaryVersion = (filePath) => {
try {
const result = spawnSync(filePath, ["--version"], { encoding: "utf8" });
- if (result.status === 0 && result.stdout) return result.stdout.trim();
+ if (result.status === 0 && result.stdout) {
+ // 2.x prints "opencode v2.0.18"; 1.x printed the bare version.
+ const match = result.stdout.trim().match(/(\d+\.\d+\.\d+(?:[-+][\w.-]+)?)\s*$/);
+ return match ? match[1] : result.stdout.trim();
+ }
} catch {
// ignore
}
@@ -220,20 +224,24 @@ if (!normalizedOpencodeVersion) {
process.exit(1);
}
-const opencodeAssetByTarget = {
- "aarch64-apple-darwin": "opencode-darwin-arm64.zip",
- "x86_64-apple-darwin": "opencode-darwin-x64-baseline.zip",
- "x86_64-unknown-linux-gnu": "opencode-linux-x64-baseline.tar.gz",
- "aarch64-unknown-linux-gnu": "opencode-linux-arm64.tar.gz",
- "x86_64-pc-windows-msvc": "opencode-windows-x64-baseline.zip",
- "aarch64-pc-windows-msvc": "opencode-windows-arm64.zip",
+// The 2.x engine ships no GitHub release assets: each platform binary is an
+// npm package (@opencode/cli-<platform>), a tarball holding package/bin/opencode.
+// Its sha512 is checked against the registry's dist.integrity before use.
+const opencodePackageByTarget = {
+ "aarch64-apple-darwin": "cli-darwin-arm64",
+ "x86_64-apple-darwin": "cli-darwin-x64-baseline",
+ "x86_64-unknown-linux-gnu": "cli-linux-x64-baseline",
+ "aarch64-unknown-linux-gnu": "cli-linux-arm64",
+ "x86_64-pc-windows-msvc": "cli-windows-x64-baseline",
+ "aarch64-pc-windows-msvc": "cli-windows-arm64",
};
-const opencodeAsset =
- opencodeAssetOverride ?? (resolvedTargetTriple ? opencodeAssetByTarget[resolvedTargetTriple] : null);
-
-const opencodeUrl = opencodeAsset
- ? `https://github.com/${opencodeGithubRepo}/releases/download/v${normalizedOpencodeVersion}/${opencodeAsset}`
+const opencodeRegistry = (process.env.OPENCODE_NPM_REGISTRY?.trim() || "https://registry.npmjs.org").replace(/\/+$/, "");
+const opencodePackage =
+ opencodeAssetOverride ?? (resolvedTargetTriple ? opencodePackageByTarget[resolvedTargetTriple] : null);
+const opencodeAsset = opencodePackage ? `${opencodePackage}-${normalizedOpencodeVersion}.tgz` : null;
+const opencodeUrl = opencodePackage
+ ? `${opencodeRegistry}/@opencode/${opencodePackage}/-/${opencodeAsset}`
: null;
const shouldDownloadOpencode =
@@ -247,10 +255,20 @@ if (!shouldDownloadOpencode) {
console.log(`OpenCode sidecar already present (${existingOpencodeVersion}).`);
}
+/** The registry's dist.integrity of the platform package (sha512-<base64>). */
+const readOpencodeIntegrity = async () => {
+ const response = await fetch(`${opencodeRegistry}/@opencode/${opencodePackage}/${normalizedOpencodeVersion}`);
+ if (!response.ok) throw new Error(`npm registry answered ${response.status} for @opencode/${opencodePackage}@${normalizedOpencodeVersion}`);
+ const meta = await response.json();
+ const integrity = String(meta?.dist?.integrity ?? "");
+ if (!integrity.startsWith("sha512-")) throw new Error(`No sha512 integrity for @opencode/${opencodePackage}@${normalizedOpencodeVersion}`);
+ return integrity;
+};
+
if (shouldDownloadOpencode) {
- if (!opencodeAsset || !opencodeUrl) {
+ if (!opencodePackage || !opencodeUrl) {
console.error(
- `No OpenCode asset configured for target ${resolvedTargetTriple ?? "unknown"}. Set OPENCODE_ASSET to override.`
+ `No OpenCode package configured for target ${resolvedTargetTriple ?? "unknown"}. Set OPENCODE_ASSET to override.`
);
process.exit(1);
}
@@ -260,52 +278,25 @@ if (shouldDownloadOpencode) {
const stamp = Date.now();
const archivePath = join(tmpdir(), `opencode-${stamp}-${opencodeAsset}`);
const extractDir = join(tmpdir(), `opencode-${stamp}`);
-
mkdirSync(extractDir, { recursive: true });
- if (process.platform === "win32") {
- const psQuote = (value) => `'${value.replace(/'/g, "''")}'`;
- const psScript = [
- "$ErrorActionPreference = 'Stop'",
- `Invoke-WebRequest -Uri ${psQuote(opencodeUrl)} -OutFile ${psQuote(archivePath)}`,
- `Expand-Archive -Path ${psQuote(archivePath)} -DestinationPath ${psQuote(extractDir)} -Force`,
- ].join("; ");
-
- const result = spawnSync("powershell", ["-NoProfile", "-Command", psScript], {
- stdio: "inherit",
- });
-
- if (result.status !== 0) {
- process.exit(result.status ?? 1);
- }
- } else {
- const downloadResult = spawnSync("curl", ["-fsSL", "-o", archivePath, opencodeUrl], {
- stdio: "inherit",
- });
- if (downloadResult.status !== 0) {
- process.exit(downloadResult.status ?? 1);
- }
-
- mkdirSync(extractDir, { recursive: true });
+ try {
+ const integrity = await readOpencodeIntegrity();
+ const response = await fetch(opencodeUrl);
+ if (!response.ok) throw new Error(`Download of ${opencodeUrl} failed: ${response.status}`);
+ const archive = Buffer.from(await response.arrayBuffer());
+ const actual = `sha512-${createHash("sha512").update(archive).digest("base64")}`;
+ if (actual !== integrity) throw new Error(`Integrity mismatch for ${opencodeUrl}: expected ${integrity}, got ${actual}`);
+ writeFileSync(archivePath, archive);
+ } catch (error) {
+ console.error(error instanceof Error ? error.message : String(error));
+ process.exit(1);
+ }
- if (opencodeAsset.endsWith(".zip")) {
- const unzipResult = spawnSync("unzip", ["-q", archivePath, "-d", extractDir], {
- stdio: "inherit",
- });
- if (unzipResult.status !== 0) {
- process.exit(unzipResult.status ?? 1);
- }
- } else if (opencodeAsset.endsWith(".tar.gz")) {
- const tarResult = spawnSync("tar", ["-xzf", archivePath, "-C", extractDir], {
- stdio: "inherit",
- });
- if (tarResult.status !== 0) {
- process.exit(tarResult.status ?? 1);
- }
- } else {
- console.error(`Unknown OpenCode archive type: ${opencodeAsset}`);
- process.exit(1);
- }
+ // bsdtar (Windows 10+ tar.exe) and GNU tar both read gzip tarballs.
+ const tarResult = spawnSync("tar", ["-xzf", archivePath, "-C", extractDir], { stdio: "inherit" });
+ if (tarResult.status !== 0) {
+ process.exit(tarResult.status ?? 1);
}
const extractedBinary = findOpencodeBinary(extractDir);
diff --git a/apps/server/package.json b/apps/server/package.json
index 54f76c69..2c184ca5 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 --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-engine2.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 4be595da..1a72e6dc 100644
--- a/apps/server/src/cli.ts
+++ b/apps/server/src/cli.ts
@@ -29,6 +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 { startWorkerActivityHeartbeat } from "./worker-activity-heartbeat.js";
import pkg from "../package.json" with { type: "json" };
@@ -105,13 +106,15 @@ 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.
- await assertOpencodeConfigCompat({
- workspaceRoots: config.workspaces
- .filter((entry) => entry.workspaceType !== "remote")
- .map((entry) => entry.path),
- env: { ...process.env, ...engineEnv },
- logger,
- });
+ 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,
+ });
+ }
managedOpencode = await createManagedOpencodeServer({
bin: process.env.OMNIRUSH_OPENCODE_BIN,
cwd: managedOpencodeCwd,
diff --git a/apps/server/src/embedded.ts b/apps/server/src/embedded.ts
index fa17abd0..8feba773 100644
--- a/apps/server/src/embedded.ts
+++ b/apps/server/src/embedded.ts
@@ -41,6 +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 type { ServeResult } from "./serve-node.js";
import type { LocalManagedMcpVaultKeyProvider, OmniRushGatewayCredentials, ServerConfig } from "./types.js";
@@ -270,17 +271,20 @@ export async function startEmbeddedServer(options: EmbeddedServerOptions): Promi
return [...new Set([config.port, ...poolPorts, startupPort].filter((port) => port > 0))];
},
};
- // 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
+ // 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 keys here, before the spawn, instead of surfacing an opaque exit.
- await duringStartup(() => assertOpencodeConfigCompat({
- workspaceRoots: config.workspaces
- .filter((entry) => entry.workspaceType !== "remote")
- .map((entry) => entry.path),
- env: { ...process.env, ...engineEnv },
- logger,
- }));
+ // 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,
+ }));
+ }
managedOpencode = await duringStartup(() => createManagedOpencodeServer({
bin: opencodeBin,
cwd,
diff --git a/apps/server/src/engine2/config.test.ts b/apps/server/src/engine2/config.test.ts
new file mode 100644
index 00000000..2be2dcca
--- /dev/null
+++ b/apps/server/src/engine2/config.test.ts
@@ -0,0 +1,138 @@
+import { describe, expect, test } from "bun:test";
+
+import { buildEngine2Config, v2Mcp, v2Package, v2Permissions } from "./config.js";
+
+/** Shaped like buildOmniRushRuntimeConfigObjectFromSnapshot's output (omnirush-runtime-config.ts). */
+const runtime = {
+ model: "omnirush/gpt-6-astra",
+ enabled_providers: ["lpr_1", "omnirush"],
+ permission: { bash: { "*": "ask", "git status*": "allow" }, edit: "allow", external_directory: { "/tmp/*": "allow" } },
+ skills: { paths: ["/rt/skills"] },
+ default_agent: "omnirush",
+ subagent_depth: 3,
+ agent: {
+ omnirush: {
+ description: "omnirush.ai default agent",
+ mode: "primary",
+ temperature: 0.2,
+ prompt: "You are omnirush.",
+ permission: { bash: { "*": "ask" }, skill: { "get-started": "deny" }, swarm_board: "deny" },
+ },
+ general: { permission: { task: "allow", skill: { "omnirush-swarm": "deny" } } },
+ },
+ plugin: ["/app/opencode-plugins/managed-policy.js"],
+ mcp: {
+ "omnirush-cloud": { type: "remote", url: "https://mcp.example/mcp", headers: { authorization: "Bearer x" }, enabled: true },
+ local: { type: "local", command: ["node", "server.js"], environment: { A: "1" }, enabled: false, timeout: 5000 },
+ },
+ provider: {
+ omnirush: {
+ npm: "@ai-sdk/openai",
+ name: "omnirush.ai",
+ env: ["OMNIRUSH_ACCESS_TOKEN"],
+ options: { baseURL: "http://127.0.0.1:9/omnirush-gateway/v1" },
+ models: {
+ "gpt-6-astra": {
+ name: "GPT-6 Astra",
+ tool_call: true,
+ modalities: { input: ["text", "image"], output: ["text"] },
+ limit: { context: 400000, output: 128000 },
+ variants: { high: { reasoning_effort: "high" }, low: { reasoning_effort: "low", disabled: true } },
+ },
+ },
+ },
+ lpr_1: { npm: "@ai-sdk/openai-compatible", name: "Mine", options: { baseURL: "https://llm.example/v1", headers: { "x-a": "1" } }, models: { m: {} } },
+ },
+};
+
+describe("the 1.x runtime config as the 2.x engine config", () => {
+ const config = buildEngine2Config({ v1: runtime, apiKeys: { lpr_1: "sk-live" }, plugins: ["/rt/engine2/omnirush-plugin"] });
+
+ test("providers use the engine's native packages; delivered keys become settings", () => {
+ expect(config.providers).toEqual({
+ omnirush: {
+ name: "omnirush.ai",
+ env: ["OMNIRUSH_ACCESS_TOKEN"],
+ package: "@opencode/ai/providers/openai",
+ settings: { baseURL: "http://127.0.0.1:9/omnirush-gateway/v1" },
+ models: {
+ "gpt-6-astra": {
+ name: "GPT-6 Astra",
+ capabilities: { tools: true, input: ["text", "image"], output: ["text"] },
+ variants: [{ id: "high", settings: { reasoning_effort: "high" } }],
+ limit: { context: 400000, output: 128000 },
+ },
+ },
+ },
+ lpr_1: {
+ name: "Mine",
+ package: "@opencode/ai/providers/openai-compatible",
+ settings: { baseURL: "https://llm.example/v1", apiKey: "sk-live" },
+ headers: { "x-a": "1" },
+ models: { m: {} },
+ },
+ });
+ });
+
+ test("agents, permissions, depth, skills and plugins keep their meaning", () => {
+ expect(config.model).toBe("omnirush/gpt-6-astra");
+ expect(config.default_agent).toBe("omnirush");
+ expect(config.experimental).toEqual({
+ subagent_depth: 3,
+ policies: [
+ { action: "provider.use", resource: "*", effect: "deny" },
+ { action: "provider.use", resource: "lpr_1", effect: "allow" },
+ { action: "provider.use", resource: "omnirush", effect: "allow" },
+ ],
+ });
+ expect(config.skills).toEqual(["/rt/skills"]);
+ expect(config.plugins).toEqual(["/rt/engine2/omnirush-plugin"]);
+ expect(config.permissions).toEqual([
+ { action: "shell", resource: "*", effect: "ask" },
+ { action: "shell", resource: "git status*", effect: "allow" },
+ { action: "edit", resource: "*", effect: "allow" },
+ { action: "external_directory", resource: "/tmp/*", effect: "allow" },
+ { action: "execute", resource: "*", effect: "deny" },
+ ]);
+ expect(config.agents).toEqual({
+ omnirush: {
+ request: { body: { temperature: 0.2 } },
+ system: "You are omnirush.",
+ description: "omnirush.ai default agent",
+ mode: "primary",
+ permissions: [
+ { action: "shell", resource: "*", effect: "ask" },
+ { action: "skill", resource: "get-started", effect: "deny" },
+ { action: "swarm_board", resource: "*", effect: "deny" },
+ ],
+ },
+ general: {
+ permissions: [
+ { action: "subagent", resource: "*", effect: "allow" },
+ { action: "skill", resource: "omnirush-swarm", effect: "deny" },
+ ],
+ },
+ });
+ });
+
+ test("MCP servers keep direct tools (no code mode)", () => {
+ expect(config.mcp).toEqual({
+ servers: {
+ "omnirush-cloud": { type: "remote", url: "https://mcp.example/mcp", headers: { authorization: "Bearer x" }, disabled: false, codemode: false },
+ local: { type: "local", command: ["node", "server.js"], environment: { A: "1" }, disabled: true, timeout: { catalog: 5000, execution: 5000 }, codemode: false },
+ },
+ });
+ expect(v2Mcp({ type: "remote", url: "https://x", oauth: { clientId: "c" } })).toEqual({ type: "remote", url: "https://x", oauth: { client_id: "c" }, codemode: false });
+ });
+
+ test("packages and permission names", () => {
+ expect(v2Package("@ai-sdk/anthropic")).toBe("@opencode/ai/providers/anthropic");
+ expect(v2Package("@opencode-ai/ai/providers/openai")).toBe("@opencode/ai/providers/openai");
+ expect(v2Package("some-provider")).toBe("aisdk:some-provider");
+ expect(v2Permissions({ task: "deny", write: "ask" }, { webfetch: false })).toEqual([
+ { action: "webfetch", resource: "*", effect: "deny" },
+ { action: "subagent", resource: "*", effect: "deny" },
+ { action: "edit", resource: "*", effect: "ask" },
+ ]);
+ });
+});
diff --git a/apps/server/src/engine2/config.ts b/apps/server/src/engine2/config.ts
new file mode 100644
index 00000000..5e06229c
--- /dev/null
+++ b/apps/server/src/engine2/config.ts
@@ -0,0 +1,321 @@
+/**
+ * The runtime engine config OmniRush.ai renders in the 1.x dialect
+ * (omnirush-runtime-config.ts) as the 2.x engine's `opencode.json`.
+ *
+ * The 2.x engine can read most 1.x keys itself, but a few of them are lost in
+ * its own migration and matter here: plugin file paths are dropped (2.x loads
+ * plugins from `<config dir>/plugins/`), the top-level `subagent_depth` is
+ * unsupported (it lives under `experimental`), MCP servers default to
+ * "code mode" (tools reachable only through a JavaScript `execute` tool
+ * instead of as `<server>_<tool>` tools), and provider keys delivered at
+ * runtime (`PUT /auth/:id` in 1.x) have no config home. The whole file is
+ * therefore written in 2.x keys here, following the engine's own 1.x
+ * migration (core/src/v1/config/migrate.ts) for everything else.
+ */
+import { isRecord, omitUndefined, type JsonRecord } from "./util.js";
+
+export type EngineConfigInput = {
+ /** The 1.x runtime config object (the file handed to the engine as OPENCODE_CONFIG). */
+ v1: JsonRecord;
+ /** API keys delivered for providers at runtime (1.x `PUT /auth/:providerID` with `{type:"api", key}`). */
+ apiKeys?: Record<string, string>;
+ /** Plugin directories the engine loads (OmniRush.ai's plugin bridge). */
+ plugins?: string[];
+};
+
+/** 1.x tool / permission names in 2.x (core/src/v1/config/migrate.ts normalizeAction). */
+export function v2Action(action: string): string {
+ if (action === "write" || action === "patch") return "edit";
+ if (action === "task") return "subagent";
+ if (action === "bash") return "shell";
+ return action;
+}
+
+type Rule = { action: string; resource: string; effect: string };
+
+function isEffect(value: unknown): value is "allow" | "deny" | "ask" {
+ return value === "allow" || value === "deny" || value === "ask";
+}
+
+/** A 1.x permission map (`{bash: {"git *": "allow"}, edit: "ask", …}`) and `tools` flags as 2.x rules, in order. */
+export function v2Permissions(permission: unknown, tools?: unknown): Rule[] | undefined {
+ const rules: Rule[] = [];
+ if (isRecord(tools)) {
+ for (const [action, enabled] of Object.entries(tools)) {
+ if (typeof enabled === "boolean") rules.push({ action: v2Action(action), resource: "*", effect: enabled ? "allow" : "deny" });
+ }
+ }
+ if (isRecord(permission)) {
+ for (const [key, rule] of Object.entries(permission)) {
+ const action = v2Action(key);
+ if (isEffect(rule)) {
+ rules.push({ action, resource: "*", effect: rule });
+ continue;
+ }
+ if (!isRecord(rule)) continue;
+ for (const [resource, effect] of Object.entries(rule)) if (isEffect(effect)) rules.push({ action, resource, effect });
+ }
+ }
+ return rules.length ? rules : undefined;
+}
+
+function modelSelection(input: unknown, variant?: unknown): JsonRecord | undefined {
+ if (typeof input !== "string" || !/^[^/#]+\/[^#]+$/.test(input)) return undefined;
+ const separator = input.indexOf("/");
+ return omitUndefined({
+ providerID: input.slice(0, separator),
+ model: input.slice(separator + 1),
+ variant: typeof variant === "string" && variant && !variant.includes("#") ? variant : undefined,
+ });
+}
+
+function v2Agent(info: JsonRecord): JsonRecord {
+ const options = isRecord(info.options) ? info.options : {};
+ const body = omitUndefined({
+ ...options,
+ temperature: typeof info.temperature === "number" ? info.temperature : undefined,
+ top_p: typeof info.top_p === "number" ? info.top_p : undefined,
+ });
+ return omitUndefined({
+ model: modelSelection(info.model, info.variant),
+ request: Object.keys(body).length ? { body } : undefined,
+ system: typeof info.prompt === "string" ? info.prompt : undefined,
+ description: typeof info.description === "string" ? info.description : undefined,
+ mode: info.mode === "primary" || info.mode === "subagent" || info.mode === "all" ? info.mode : undefined,
+ hidden: typeof info.hidden === "boolean" ? info.hidden : undefined,
+ color: typeof info.color === "string" ? (info.color.startsWith("#") ? info.color : "#aaaaaa") : undefined,
+ steps: typeof info.steps === "number" ? info.steps : typeof info.maxSteps === "number" ? info.maxSteps : undefined,
+ disabled: info.disable === true ? true : undefined,
+ permissions: v2Permissions(info.permission, info.tools),
+ });
+}
+
+/** A 1.x MCP server entry as a 2.x one; tools stay direct (`<server>_<tool>`), not behind code mode. */
+export function v2Mcp(info: unknown): JsonRecord | undefined {
+ if (!isRecord(info)) return undefined;
+ const disabled = typeof info.enabled === "boolean" ? !info.enabled : typeof info.disabled === "boolean" ? info.disabled : undefined;
+ const timeout = typeof info.timeout === "number" ? { catalog: info.timeout, execution: info.timeout } : isRecord(info.timeout) ? info.timeout : undefined;
+ if (info.type === "local") {
+ return omitUndefined({
+ type: "local",
+ command: Array.isArray(info.command) ? info.command : undefined,
+ cwd: typeof info.cwd === "string" ? info.cwd : undefined,
+ environment: isRecord(info.environment) ? info.environment : undefined,
+ disabled,
+ timeout,
+ codemode: false,
+ });
+ }
+ if (info.type === "remote") {
+ const oauth = isRecord(info.oauth)
+ ? omitUndefined({
+ client_id: info.oauth.clientId ?? info.oauth.client_id,
+ client_secret: info.oauth.clientSecret ?? info.oauth.client_secret,
+ scope: info.oauth.scope,
+ callback_port: info.oauth.callbackPort ?? info.oauth.callback_port,
+ redirect_uri: info.oauth.redirectUri ?? info.oauth.redirect_uri,
+ })
+ : info.oauth === false ? false : undefined;
+ return omitUndefined({
+ type: "remote",
+ url: typeof info.url === "string" ? info.url : undefined,
+ headers: isRecord(info.headers) ? info.headers : undefined,
+ oauth,
+ disabled,
+ timeout,
+ codemode: false,
+ });
+ }
+ return undefined;
+}
+
+/** 1.x AI SDK package names the 2.x engine ships natively (core/src/aisdk-native.ts). */
+const NATIVE_PACKAGES: Record<string, string> = {
+ "@ai-sdk/amazon-bedrock": "@opencode/ai/providers/amazon-bedrock",
+ "@ai-sdk/anthropic": "@opencode/ai/providers/anthropic",
+ "@ai-sdk/azure": "@opencode/ai/providers/azure/responses",
+ "@ai-sdk/cerebras": "@opencode/ai/providers/cerebras",
+ "@ai-sdk/deepinfra": "@opencode/ai/providers/deepinfra",
+ "@ai-sdk/google": "@opencode/ai/providers/google",
+ "@ai-sdk/google-vertex": "@opencode/ai/providers/google-vertex",
+ "@ai-sdk/groq": "@opencode/ai/providers/groq",
+ "@ai-sdk/mistral": "@opencode/ai/providers/mistral",
+ "@ai-sdk/openai": "@opencode/ai/providers/openai",
+ "@ai-sdk/openai-compatible": "@opencode/ai/providers/openai-compatible",
+ "@ai-sdk/togetherai": "@opencode/ai/providers/togetherai",
+ "@ai-sdk/xai": "@opencode/ai/providers/xai",
+ "@openrouter/ai-sdk-provider": "@opencode/ai/providers/openrouter",
+};
+
+export function v2Package(npm: unknown): string | undefined {
+ if (typeof npm !== "string" || !npm.trim()) return undefined;
+ if (npm.startsWith("@opencode/") || npm.startsWith("aisdk:")) return npm;
+ if (npm.startsWith("@opencode-ai/ai/")) return npm.replace("@opencode-ai/", "@opencode/");
+ return NATIVE_PACKAGES[npm] ?? `aisdk:${npm}`;
+}
+
+function splitOptions(options: unknown): { settings: JsonRecord; headers?: Record<string, string>; body?: JsonRecord } {
+ if (!isRecord(options)) return { settings: {} };
+ const { headers, body, ...settings } = options;
+ return {
+ settings,
+ headers: isRecord(headers)
+ ? Object.fromEntries(Object.entries(headers).filter((entry): entry is [string, string] => typeof entry[1] === "string"))
+ : undefined,
+ body: isRecord(body) ? { ...body } : undefined,
+ };
+}
+
+function v2Model(info: JsonRecord): JsonRecord {
+ const cost = isRecord(info.cost) ? info.cost : undefined;
+ const modalities = isRecord(info.modalities) ? info.modalities : undefined;
+ const capabilities = info.tool_call !== undefined || modalities?.input !== undefined || modalities?.output !== undefined
+ ? {
+ tools: info.tool_call !== false,
+ input: Array.isArray(modalities?.input) ? modalities.input : ["text"],
+ output: Array.isArray(modalities?.output) ? modalities.output : ["text"],
+ }
+ : undefined;
+ const limit = isRecord(info.limit) ? info.limit : undefined;
+ const provider = isRecord(info.provider) ? info.provider : undefined;
+ const options = isRecord(info.options) ? { ...info.options } : undefined;
+ const interleaved = info.interleaved;
+ return omitUndefined({
+ modelID: typeof info.id === "string" ? info.id : undefined,
+ family: typeof info.family === "string" ? info.family : undefined,
+ name: typeof info.name === "string" ? info.name : undefined,
+ compatibility: isRecord(interleaved) && typeof interleaved.field === "string" ? { reasoningField: interleaved.field } : undefined,
+ package: provider ? v2Package(provider.npm) : undefined,
+ settings: provider && typeof provider.api === "string" ? { ...(options ?? {}), baseURL: provider.api } : options,
+ capabilities,
+ headers: isRecord(info.headers) ? info.headers : undefined,
+ variants: isRecord(info.variants)
+ ? Object.entries(info.variants).filter(([, value]) => isRecord(value) && value.disabled !== true).map(([id, value]) => ({ id, settings: { ...(value as JsonRecord) } }))
+ : undefined,
+ cost: cost
+ ? [
+ omitUndefined({
+ input: typeof cost.input === "number" ? cost.input : 0,
+ output: typeof cost.output === "number" ? cost.output : 0,
+ cache: { read: typeof cost.cache_read === "number" ? cost.cache_read : 0, write: typeof cost.cache_write === "number" ? cost.cache_write : 0 },
+ }),
+ ]
+ : undefined,
+ disabled: info.status === "deprecated" ? true : undefined,
+ limit: limit
+ ? omitUndefined({
+ context: typeof limit.context === "number" ? Math.trunc(limit.context) : undefined,
+ input: typeof limit.input === "number" ? Math.trunc(limit.input) : undefined,
+ output: typeof limit.output === "number" ? Math.trunc(limit.output) : undefined,
+ })
+ : undefined,
+ });
+}
+
+function v2Provider(info: JsonRecord, apiKey?: string): JsonRecord {
+ const { settings, headers, body } = splitOptions(info.options);
+ const merged = omitUndefined({
+ ...settings,
+ ...(typeof info.api === "string" ? { baseURL: info.api } : {}),
+ ...(apiKey ? { apiKey } : {}),
+ });
+ return omitUndefined({
+ name: typeof info.name === "string" ? info.name : undefined,
+ env: Array.isArray(info.env) ? info.env.filter((item) => typeof item === "string") : undefined,
+ package: v2Package(info.npm),
+ settings: Object.keys(merged).length ? merged : undefined,
+ headers: headers && Object.keys(headers).length ? headers : undefined,
+ body,
+ models: isRecord(info.models)
+ ? Object.fromEntries(Object.entries(info.models).filter(([, model]) => isRecord(model)).map(([id, model]) => [id, v2Model(model as JsonRecord)]))
+ : undefined,
+ });
+}
+
+/** The 2.x config for a 1.x runtime config. */
+export function buildEngine2Config(input: EngineConfigInput): JsonRecord {
+ const v1 = input.v1;
+ const apiKeys = input.apiKeys ?? {};
+ const providers: JsonRecord = {};
+ if (isRecord(v1.provider)) {
+ for (const [id, provider] of Object.entries(v1.provider)) {
+ if (isRecord(provider)) providers[id] = v2Provider(provider, apiKeys[id]);
+ }
+ }
+ // Keys delivered for catalog providers the config does not describe still need a home.
+ for (const [id, key] of Object.entries(apiKeys)) {
+ if (!providers[id]) providers[id] = { settings: { apiKey: key } };
+ }
+ const agents: JsonRecord = {};
+ for (const source of [v1.agent, v1.mode]) {
+ if (!isRecord(source)) continue;
+ for (const [name, agent] of Object.entries(source)) {
+ if (!isRecord(agent)) continue;
+ agents[name] = v2Agent(source === v1.mode ? { ...agent, mode: "primary" } : agent);
+ }
+ }
+ const small = modelSelection(v1.small_model);
+ if (small) agents.title = { model: small, ...(isRecord(agents.title) ? agents.title : {}) };
+ const servers: JsonRecord = {};
+ if (isRecord(v1.mcp)) {
+ for (const [name, server] of Object.entries(v1.mcp)) {
+ const mapped = v2Mcp(server);
+ if (mapped) servers[name] = mapped;
+ }
+ }
+ const policies = [
+ ...(Array.isArray(v1.enabled_providers)
+ ? [
+ { action: "provider.use", resource: "*", effect: "deny" },
+ ...v1.enabled_providers.filter((id): id is string => typeof id === "string").map((resource) => ({ action: "provider.use", resource, effect: "allow" })),
+ ]
+ : []),
+ ...(Array.isArray(v1.disabled_providers)
+ ? v1.disabled_providers.filter((id): id is string => typeof id === "string").map((resource) => ({ action: "provider.use", resource, effect: "deny" }))
+ : []),
+ ];
+ const depth = typeof v1.subagent_depth === "number"
+ ? v1.subagent_depth
+ : isRecord(v1.experimental) && typeof v1.experimental.subagent_depth === "number" ? v1.experimental.subagent_depth : undefined;
+ const skills = isRecord(v1.skills)
+ ? [...(Array.isArray(v1.skills.paths) ? v1.skills.paths : []), ...(Array.isArray(v1.skills.urls) ? v1.skills.urls : [])].filter((item) => typeof item === "string")
+ : Array.isArray(v1.skills) ? v1.skills : undefined;
+ const commands = isRecord(v1.command)
+ ? Object.fromEntries(Object.entries(v1.command).filter(([, value]) => isRecord(value)).map(([id, value]) => {
+ const command = value as JsonRecord;
+ return [id, omitUndefined({
+ template: command.template,
+ description: command.description,
+ agent: command.agent,
+ model: modelSelection(command.model, command.variant),
+ subagent: command.subtask,
+ })];
+ }))
+ : undefined;
+ const permissions = v2Permissions(v1.permission, v1.tools) ?? [];
+ return omitUndefined({
+ $schema: "https://opencode.ai/config.json",
+ model: typeof v1.model === "string" ? v1.model : undefined,
+ default_agent: typeof v1.default_agent === "string" ? v1.default_agent : undefined,
+ username: typeof v1.username === "string" ? v1.username : undefined,
+ shell: typeof v1.shell === "string" ? v1.shell : undefined,
+ share: v1.share === "manual" || v1.share === "auto" || v1.share === "disabled" ? v1.share : undefined,
+ update: "disable",
+ // The code-mode `execute` tool is not offered: the agent calls tools directly, as with 1.x.
+ permissions: [...permissions, { action: "execute", resource: "*", effect: "deny" }],
+ agents: Object.keys(agents).length ? agents : undefined,
+ mcp: Object.keys(servers).length ? { servers } : undefined,
+ skills: skills && skills.length ? skills : undefined,
+ commands,
+ instructions: Array.isArray(v1.instructions) ? v1.instructions : undefined,
+ formatter: v1.formatter === false || isRecord(v1.formatter) ? v1.formatter : undefined,
+ lsp: v1.lsp === false || isRecord(v1.lsp) ? v1.lsp : undefined,
+ watcher: isRecord(v1.watcher) ? v1.watcher : undefined,
+ snapshots: typeof v1.snapshot === "boolean" ? v1.snapshot : undefined,
+ plugins: input.plugins && input.plugins.length ? input.plugins : undefined,
+ experimental: depth !== undefined || policies.length
+ ? omitUndefined({ subagent_depth: depth, policies: policies.length ? policies : undefined })
+ : undefined,
+ providers: Object.keys(providers).length ? providers : undefined,
+ });
+}
diff --git a/apps/server/src/engine2/events.ts b/apps/server/src/engine2/events.ts
new file mode 100644
index 00000000..3e8bd95d
--- /dev/null
+++ b/apps/server/src/engine2/events.ts
@@ -0,0 +1,532 @@
+/**
+ * The 2.x engine's event stream (`GET /api/event`) as the 1.x bus events the
+ * app and the server consume (`message.updated`, `message.part.updated`,
+ * `message.part.delta`, `session.status`, `session.idle`, `permission.asked`,
+ * `question.asked`, …).
+ *
+ * 2.x streams a step as fine-grained events (step started, text/reasoning
+ * deltas, tool input/call/progress/result, step ended). The translator keeps
+ * each in-flight assistant message in its 2.x shape, applies every event to it
+ * and re-derives the 1.x parts with engine2/shapes.ts, so a part seen live and
+ * the same part read back from the message list carry the same id and fields.
+ * 2.x has no busy/idle status events: they are synthesized from the
+ * execution lifecycle (`session.execution.started` → busy, `.succeeded` /
+ * `.failed` / `.interrupted` → idle + `session.idle`).
+ */
+import { randomUUID } from "node:crypto";
+import {
+ partId,
+ v1AssistantMessage,
+ v1Error,
+ v1PermissionRequest,
+ v1QuestionRequest,
+ v1Session,
+ type QuestionMapping,
+} from "./shapes.js";
+import { arr, isRecord, num, omitUndefined, record, str, type JsonRecord } from "./util.js";
+
+export type V1Event = { type: string; properties: JsonRecord };
+/** A translated event and the directory it belongs to (null: every directory). */
+export type ScopedV1Event = { directory: string | null; event: V1Event };
+
+type ModelRef = { providerID: string; modelID: string; variant?: string };
+
+type LiveAssistant = {
+ sessionID: string;
+ message: JsonRecord;
+ parentID: string;
+ /** Tool input text streamed so far, per call id. */
+ raw: Map<string, string>;
+};
+
+type SessionState = {
+ directory: string | null;
+ parentID?: string;
+ agent?: string;
+ model?: ModelRef;
+ lastUserID: string;
+ status: JsonRecord;
+ info?: JsonRecord;
+};
+
+export type EventTranslatorOptions = {
+ version: string;
+ /** The worktree root reported in `path.root` for a directory (defaults to "/"). */
+ rootFor?: (directory: string) => string | undefined;
+ /** Looks up a session the stream has not described yet (its directory and parent). */
+ lookupSession?: (sessionID: string) => Promise<unknown>;
+ now?: () => number;
+};
+
+function eventId(): string {
+ return `evt_${randomUUID().replace(/-/g, "").slice(0, 26)}`;
+}
+
+function modelRef(value: unknown): ModelRef | undefined {
+ if (!isRecord(value)) return undefined;
+ const providerID = str(value, "providerID");
+ const modelID = str(value, "id") ?? str(value, "modelID");
+ if (!providerID || !modelID) return undefined;
+ const variant = str(value, "variant");
+ return variant ? { providerID, modelID, variant } : { providerID, modelID };
+}
+
+export class EventTranslator {
+ private readonly sessions = new Map<string, SessionState>();
+ private readonly live = new Map<string, LiveAssistant>();
+ private readonly questions = new Map<string, QuestionMapping>();
+ private readonly options: EventTranslatorOptions;
+
+ constructor(options: EventTranslatorOptions) {
+ this.options = options;
+ }
+
+ /** The 1.x status of every session the stream saw busy or retrying. */
+ statuses(): Record<string, JsonRecord> {
+ const out: Record<string, JsonRecord> = {};
+ for (const [id, state] of this.sessions) if (state.status.type !== "idle") out[id] = state.status;
+ return out;
+ }
+
+ statusOf(sessionID: string): JsonRecord | undefined {
+ return this.sessions.get(sessionID)?.status;
+ }
+
+ questionMapping(requestID: string): QuestionMapping | undefined {
+ return this.questions.get(requestID);
+ }
+
+ rememberQuestion(requestID: string, mapping: QuestionMapping): void {
+ this.questions.set(requestID, mapping);
+ }
+
+ /** Records what a read learned about a session (directory, parent, agent, model). */
+ noteSession(sessionID: string, patch: { directory?: string | null; parentID?: string; agent?: string; model?: ModelRef; info?: JsonRecord }): void {
+ const state = this.session(sessionID);
+ if (patch.directory !== undefined && patch.directory !== null) state.directory = patch.directory;
+ if (patch.parentID) state.parentID = patch.parentID;
+ if (patch.agent) state.agent = patch.agent;
+ if (patch.model) state.model = patch.model;
+ if (patch.info) state.info = patch.info;
+ }
+
+ directoryOf(sessionID: string): string | null {
+ return this.sessions.get(sessionID)?.directory ?? null;
+ }
+
+ isChild(sessionID: string): boolean {
+ return Boolean(this.sessions.get(sessionID)?.parentID);
+ }
+
+ private session(sessionID: string): SessionState {
+ let state = this.sessions.get(sessionID);
+ if (!state) {
+ state = { directory: null, lastUserID: "", status: { type: "idle" } };
+ this.sessions.set(sessionID, state);
+ }
+ return state;
+ }
+
+ private ctx(sessionID: string) {
+ const state = this.session(sessionID);
+ const directory = state.directory ?? undefined;
+ return {
+ sessionID,
+ directory,
+ root: directory ? this.options.rootFor?.(directory) : undefined,
+ agent: state.agent,
+ model: state.model,
+ child: Boolean(state.parentID),
+ };
+ }
+
+ private scoped(sessionID: string | undefined, type: string, properties: JsonRecord, directory?: string | null): ScopedV1Event {
+ const dir = directory !== undefined ? directory : sessionID ? this.directoryOf(sessionID) : null;
+ return { directory: dir, event: { type, properties } };
+ }
+
+ private assistantEvents(live: LiveAssistant, changedPart: string | null, includeInfo: boolean): ScopedV1Event[] {
+ const mapped = v1AssistantMessage(live.message, this.ctx(live.sessionID), live.parentID);
+ const out: ScopedV1Event[] = [];
+ if (includeInfo) out.push(this.scoped(live.sessionID, "message.updated", { sessionID: live.sessionID, info: mapped.info }));
+ for (const part of mapped.parts) {
+ if (changedPart !== null && part.id !== changedPart) continue;
+ out.push(this.scoped(live.sessionID, "message.part.updated", { sessionID: live.sessionID, part, time: this.now() }));
+ }
+ return out;
+ }
+
+ private now(): number {
+ return this.options.now?.() ?? Date.now();
+ }
+
+ private liveFor(data: JsonRecord): LiveAssistant | undefined {
+ const id = str(data, "assistantMessageID") ?? str(data, "messageID");
+ return id ? this.live.get(id) : undefined;
+ }
+
+ private contentEntry(live: LiveAssistant, kind: "text" | "reasoning", ordinal: number): JsonRecord {
+ const content = live.message.content as JsonRecord[];
+ let seen = 0;
+ for (const entry of content) {
+ if (entry.type !== kind) continue;
+ if (seen === ordinal) return entry;
+ seen++;
+ }
+ const entry: JsonRecord = { type: kind, text: "" };
+ content.push(entry);
+ return entry;
+ }
+
+ private toolEntry(live: LiveAssistant, callID: string, name?: string): JsonRecord {
+ const content = live.message.content as JsonRecord[];
+ const found = content.find((entry) => entry.type === "tool" && entry.id === callID);
+ if (found) return found;
+ const entry: JsonRecord = { type: "tool", id: callID, name: name ?? "tool", state: { status: "streaming", input: "" }, time: { created: this.now() } };
+ content.push(entry);
+ return entry;
+ }
+
+ /** Translates one 2.x event; the result may be empty. Session lookups for unknown sessions are awaited. */
+ async translate(raw: unknown): Promise<ScopedV1Event[]> {
+ if (!isRecord(raw)) return [];
+ const type = str(raw, "type") ?? "";
+ const data = record(raw, "data") ?? record(raw, "properties") ?? {};
+ const location = str(record(raw, "location"), "directory");
+ const sessionID = str(data, "sessionID");
+ if (sessionID && location) this.session(sessionID).directory = location;
+ if (sessionID && this.directoryOf(sessionID) === null && this.options.lookupSession) {
+ try {
+ const found = await this.options.lookupSession(sessionID);
+ const info = v1Session(found, { version: this.options.version });
+ if (info) this.noteSession(sessionID, { directory: String(info.directory || "") || null, parentID: str(info, "parentID") });
+ } catch {
+ // An unknown session stays unscoped; its events reach every subscriber.
+ }
+ }
+ switch (type) {
+ case "server.connected":
+ return [{ directory: null, event: { type: "server.connected", properties: {} } }];
+ case "session.created": {
+ if (!sessionID) return [];
+ const info = v1Session({ ...data, id: sessionID, time: { created: num(raw, "created") ?? this.now(), updated: num(raw, "created") ?? this.now() } }, { version: this.options.version });
+ if (!info) return [];
+ this.noteSession(sessionID, { directory: String(info.directory || "") || null, parentID: str(info, "parentID"), agent: str(data, "agent"), model: modelRef(data.model), info });
+ return [this.scoped(sessionID, "session.created", { sessionID, info })];
+ }
+ case "session.renamed":
+ case "session.metadata.updated":
+ case "session.moved": {
+ if (!sessionID) return [];
+ let info: JsonRecord | null = null;
+ if (this.options.lookupSession) {
+ try {
+ info = v1Session(await this.options.lookupSession(sessionID), { version: this.options.version });
+ } catch {
+ info = null;
+ }
+ }
+ if (!info) {
+ const known = this.session(sessionID).info;
+ if (!known) return [];
+ info = { ...known, ...(typeof data.title === "string" ? { title: data.title } : {}), time: { ...(record(known, "time") ?? {}), updated: this.now() } };
+ }
+ this.noteSession(sessionID, { info, directory: String(info.directory || "") || null });
+ return [this.scoped(sessionID, "session.updated", { sessionID, info })];
+ }
+ case "session.deleted": {
+ if (!sessionID) return [];
+ const info = this.session(sessionID).info ?? { id: sessionID };
+ const out = [this.scoped(sessionID, "session.deleted", { sessionID, info })];
+ this.sessions.delete(sessionID);
+ return out;
+ }
+ case "session.agent.selected": {
+ if (sessionID && typeof data.agent === "string") this.session(sessionID).agent = data.agent;
+ return [];
+ }
+ case "session.model.selected": {
+ if (sessionID) this.session(sessionID).model = modelRef(data.model) ?? this.session(sessionID).model;
+ return [];
+ }
+ case "session.inbox.enqueued": {
+ if (!sessionID) return [];
+ const item = record(data, "item");
+ if (str(item, "type") !== "user") return [];
+ const payload = record(item, "payload") ?? {};
+ const id = str(data, "inboxID") ?? str(payload, "id");
+ if (!id) return [];
+ const state = this.session(sessionID);
+ state.lastUserID = id;
+ const created = num(raw, "created") ?? this.now();
+ const info = omitUndefined({
+ id,
+ sessionID,
+ role: "user",
+ time: { created },
+ agent: state.agent ?? "build",
+ model: state.model ? omitUndefined({ providerID: state.model.providerID, modelID: state.model.modelID, variant: state.model.variant }) : { providerID: "", modelID: "" },
+ });
+ const out: ScopedV1Event[] = [this.scoped(sessionID, "message.updated", { sessionID, info })];
+ const text = str(payload, "text") ?? "";
+ const files = arr(payload, "files");
+ if (text || files.length === 0) {
+ out.push(this.scoped(sessionID, "message.part.updated", { sessionID, part: { id: partId(id, "u0"), sessionID, messageID: id, type: "text", text }, time: created }));
+ }
+ files.forEach((file, index) => {
+ if (!isRecord(file) || typeof file.uri !== "string") return;
+ out.push(this.scoped(sessionID, "message.part.updated", {
+ sessionID,
+ part: omitUndefined({ id: partId(id, `f${index}`), sessionID, messageID: id, type: "file", mime: str(file, "mime") ?? "application/octet-stream", filename: str(file, "name"), url: file.uri }),
+ time: created,
+ }));
+ });
+ return out;
+ }
+ case "session.inbox.cancelled": {
+ const id = str(data, "inboxID");
+ if (!sessionID || !id) return [];
+ return [this.scoped(sessionID, "message.removed", { sessionID, messageID: id })];
+ }
+ case "session.execution.started": {
+ if (!sessionID) return [];
+ const state = this.session(sessionID);
+ state.status = { type: "busy" };
+ return [this.scoped(sessionID, "session.status", { sessionID, status: { type: "busy" } })];
+ }
+ case "session.retry.scheduled": {
+ if (!sessionID) return [];
+ const state = this.session(sessionID);
+ const error = record(data, "error");
+ state.status = omitUndefined({
+ type: "retry",
+ attempt: num(data, "attempt") ?? 1,
+ message: str(error, "message") ?? str(data, "message") ?? "Retrying",
+ next: num(data, "at") ?? num(data, "next") ?? this.now(),
+ });
+ return [this.scoped(sessionID, "session.status", { sessionID, status: state.status })];
+ }
+ case "session.execution.succeeded":
+ case "session.execution.failed":
+ case "session.execution.interrupted": {
+ if (!sessionID) return [];
+ const out: ScopedV1Event[] = [];
+ for (const [id, live] of this.live) {
+ if (live.sessionID !== sessionID) continue;
+ const time = record(live.message, "time") ?? {};
+ if (num(time, "completed") === undefined) {
+ live.message.time = { ...time, completed: this.now() };
+ if (type === "session.execution.interrupted" && !live.message.error) live.message.error = { type: "aborted", message: "The operation was aborted." };
+ out.push(...this.assistantEvents(live, null, true));
+ }
+ this.live.delete(id);
+ }
+ if (type === "session.execution.failed") {
+ const error = v1Error(record(data, "error"), this.session(sessionID).model?.providerID);
+ if (error) out.push(this.scoped(sessionID, "session.error", { sessionID, error }));
+ }
+ this.session(sessionID).status = { type: "idle" };
+ out.push(this.scoped(sessionID, "session.status", { sessionID, status: { type: "idle" } }));
+ out.push(this.scoped(sessionID, "session.idle", { sessionID }));
+ return out;
+ }
+ case "session.step.started": {
+ if (!sessionID) return [];
+ const id = str(data, "assistantMessageID");
+ if (!id) return [];
+ const state = this.session(sessionID);
+ const agent = str(data, "agent") ?? state.agent;
+ const model = modelRef(data.model) ?? state.model;
+ if (agent) state.agent = agent;
+ if (model) state.model = { ...model, ...(state.model?.variant && !model.variant ? { variant: state.model.variant } : {}) };
+ const live: LiveAssistant = {
+ sessionID,
+ parentID: state.lastUserID,
+ raw: new Map(),
+ message: omitUndefined({
+ id,
+ type: "assistant",
+ agent,
+ model: model ? { id: model.modelID, providerID: model.providerID, variant: state.model?.variant } : undefined,
+ content: [],
+ time: { created: num(data, "started") ?? num(raw, "created") ?? this.now() },
+ }),
+ };
+ this.live.set(id, live);
+ if (state.status.type !== "busy") state.status = { type: "busy" };
+ return this.assistantEvents(live, null, true);
+ }
+ case "session.step.ended": {
+ const live = this.liveFor(data);
+ if (!live) return [];
+ live.message.finish = str(data, "finish") ?? "stop";
+ live.message.cost = num(data, "cost") ?? 0;
+ live.message.tokens = record(data, "tokens") ?? live.message.tokens;
+ const snapshot = str(data, "snapshot");
+ if (snapshot) live.message.snapshot = snapshot;
+ live.message.time = { ...(record(live.message, "time") ?? {}), completed: num(raw, "created") ?? this.now() };
+ this.live.delete(str(live.message, "id") ?? "");
+ const out = this.assistantEvents(live, partId(String(live.message.id), "f0"), false);
+ out.push(...this.assistantEvents(live, "", true).filter((item) => item.event.type === "message.updated"));
+ return out;
+ }
+ case "session.step.failed": {
+ const live = this.liveFor(data);
+ if (!live) return [];
+ live.message.error = record(data, "error") ?? { type: "unknown", message: "Step failed" };
+ live.message.time = { ...(record(live.message, "time") ?? {}), completed: num(raw, "created") ?? this.now() };
+ this.live.delete(str(live.message, "id") ?? "");
+ return this.assistantEvents(live, "", true).filter((item) => item.event.type === "message.updated");
+ }
+ case "session.text.started":
+ case "session.reasoning.started":
+ case "session.next.text.started":
+ case "session.next.reasoning.started": {
+ const live = this.liveFor(data);
+ if (!live) return [];
+ const kind = type.includes("reasoning") ? "reasoning" : "text";
+ const ordinal = num(data, "ordinal") ?? 0;
+ const entry = this.contentEntry(live, kind, ordinal);
+ entry.time = { created: num(raw, "created") ?? this.now() };
+ return this.assistantEvents(live, partId(String(live.message.id), `${kind === "text" ? "t" : "r"}${ordinal}`), false);
+ }
+ case "session.text.delta":
+ case "session.reasoning.delta":
+ case "session.next.text.delta":
+ case "session.next.reasoning.delta": {
+ const live = this.liveFor(data);
+ if (!live) return [];
+ const kind = type.includes("reasoning") ? "reasoning" : "text";
+ const ordinal = num(data, "ordinal") ?? 0;
+ const delta = str(data, "delta") ?? "";
+ const entry = this.contentEntry(live, kind, ordinal);
+ entry.text = `${typeof entry.text === "string" ? entry.text : ""}${delta}`;
+ const messageID = String(live.message.id);
+ return [this.scoped(live.sessionID, "message.part.delta", {
+ sessionID: live.sessionID,
+ messageID,
+ partID: partId(messageID, `${kind === "text" ? "t" : "r"}${ordinal}`),
+ field: "text",
+ delta,
+ })];
+ }
+ case "session.text.ended":
+ case "session.reasoning.ended":
+ case "session.next.text.ended":
+ case "session.next.reasoning.ended": {
+ const live = this.liveFor(data);
+ if (!live) return [];
+ const kind = type.includes("reasoning") ? "reasoning" : "text";
+ const ordinal = num(data, "ordinal") ?? 0;
+ const entry = this.contentEntry(live, kind, ordinal);
+ if (typeof data.text === "string") entry.text = data.text;
+ entry.time = { ...(record(entry, "time") ?? {}), completed: num(raw, "created") ?? this.now() };
+ return this.assistantEvents(live, partId(String(live.message.id), `${kind === "text" ? "t" : "r"}${ordinal}`), false);
+ }
+ case "session.tool.input.started": {
+ const live = this.liveFor(data);
+ const callID = str(data, "id");
+ if (!live || !callID) return [];
+ this.toolEntry(live, callID, str(data, "name"));
+ return this.assistantEvents(live, partId(String(live.message.id), "c", callID), false);
+ }
+ case "session.tool.input.delta": {
+ const live = this.liveFor(data);
+ const callID = str(data, "id");
+ if (!live || !callID) return [];
+ const raw = `${live.raw.get(callID) ?? ""}${str(data, "delta") ?? ""}`;
+ live.raw.set(callID, raw);
+ const entry = this.toolEntry(live, callID);
+ entry.state = { status: "streaming", input: raw };
+ return this.assistantEvents(live, partId(String(live.message.id), "c", callID), false);
+ }
+ case "session.tool.input.ended": {
+ const live = this.liveFor(data);
+ const callID = str(data, "id");
+ if (!live || !callID) return [];
+ const entry = this.toolEntry(live, callID);
+ entry.state = { status: "streaming", input: str(data, "text") ?? live.raw.get(callID) ?? "" };
+ return this.assistantEvents(live, partId(String(live.message.id), "c", callID), false);
+ }
+ case "session.tool.called": {
+ const live = this.liveFor(data);
+ const callID = str(data, "id");
+ if (!live || !callID) return [];
+ const entry = this.toolEntry(live, callID, str(data, "name"));
+ entry.state = { status: "running", input: data.input ?? {}, metadata: {} };
+ entry.time = { ...(record(entry, "time") ?? {}), ran: num(raw, "created") ?? this.now() };
+ return this.assistantEvents(live, partId(String(live.message.id), "c", callID), false);
+ }
+ case "session.tool.progress": {
+ const live = this.liveFor(data);
+ const callID = str(data, "id");
+ if (!live || !callID) return [];
+ const entry = this.toolEntry(live, callID);
+ const state = record(entry, "state") ?? {};
+ entry.state = { ...state, status: "running", metadata: { ...(record(state, "metadata") ?? {}), ...(record(data, "metadata") ?? {}) } };
+ return this.assistantEvents(live, partId(String(live.message.id), "c", callID), false);
+ }
+ case "session.tool.success":
+ case "session.tool.failed": {
+ const live = this.liveFor(data);
+ const callID = str(data, "id");
+ if (!live || !callID) return [];
+ const entry = this.toolEntry(live, callID);
+ const state = record(entry, "state") ?? {};
+ entry.time = { ...(record(entry, "time") ?? {}), completed: num(raw, "created") ?? this.now() };
+ entry.state = type === "session.tool.success"
+ ? omitUndefined({ status: "completed", input: state.input ?? {}, content: data.content ?? [], metadata: record(data, "metadata") ?? record(state, "metadata") })
+ : omitUndefined({ status: "error", input: state.input ?? {}, error: data.error ?? "Tool failed", content: data.content, metadata: record(data, "metadata") ?? record(state, "metadata") });
+ return this.assistantEvents(live, partId(String(live.message.id), "c", callID), false);
+ }
+ case "session.compaction.ended":
+ return sessionID ? [this.scoped(sessionID, "session.compacted", { sessionID })] : [];
+ case "permission.asked": {
+ const request = v1PermissionRequest(data);
+ if (!request) return [];
+ return [this.scoped(String(request.sessionID), "permission.asked", request)];
+ }
+ case "permission.replied": {
+ const requestID = str(data, "requestID") ?? str(data, "id");
+ if (!sessionID || !requestID) return [];
+ return [this.scoped(sessionID, "permission.replied", { sessionID, requestID, reply: str(data, "reply") ?? str(data, "decision") ?? "once" })];
+ }
+ case "form.created": {
+ const form = record(data, "form") ?? data;
+ const mapping = v1QuestionRequest(form);
+ if (!mapping) return [];
+ this.questions.set(String(mapping.request.id), mapping);
+ return [this.scoped(String(mapping.request.sessionID), "question.asked", mapping.request)];
+ }
+ case "form.replied": {
+ const requestID = str(data, "id") ?? str(data, "formID");
+ if (!sessionID || !requestID) return [];
+ const mapping = this.questions.get(requestID);
+ const answer = record(data, "answer") ?? {};
+ const answers = mapping
+ ? mapping.fields.map((field) => {
+ const value = answer[field.key];
+ const values = Array.isArray(value) ? value : value === undefined ? [] : [value];
+ return values.map((item) => field.options.find((option) => option.value === item)?.label ?? String(item));
+ })
+ : [];
+ this.questions.delete(requestID);
+ return [this.scoped(sessionID, "question.replied", { sessionID, requestID, answers })];
+ }
+ case "form.cancelled": {
+ const requestID = str(data, "id") ?? str(data, "formID");
+ if (!sessionID || !requestID) return [];
+ this.questions.delete(requestID);
+ return [this.scoped(sessionID, "question.rejected", { sessionID, requestID })];
+ }
+ case "mcp.status.changed":
+ return [{ directory: location ?? null, event: { type: "mcp.tools.changed", properties: { server: str(data, "server") ?? str(data, "name") ?? "" } } }];
+ default:
+ return [];
+ }
+ }
+}
+
+export function v1EventEnvelope(event: V1Event): JsonRecord {
+ return { id: eventId(), type: event.type, properties: event.properties };
+}
diff --git a/apps/server/src/engine2/facade.test.ts b/apps/server/src/engine2/facade.test.ts
new file mode 100644
index 00000000..fd72e9ee
--- /dev/null
+++ b/apps/server/src/engine2/facade.test.ts
@@ -0,0 +1,201 @@
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { startEngineFacade, type EngineFacade } from "./facade.js";
+
+type Tree = { session: Record<string, unknown>; messages: Array<Record<string, unknown>>; children: Tree[] };
+const tree: Tree = JSON.parse(readFileSync(join(import.meta.dir, "fixtures", "v2-p1.json"), "utf8"));
+const SESSION = String(tree.session.id);
+const DIRECTORY = "/work/proj";
+
+type Recorded = { method: string; path: string; query: Record<string, string>; body: unknown };
+const recorded: Recorded[] = [];
+let eventSink: ((event: unknown) => void) | null = null;
+let upstream: ReturnType<typeof Bun.serve>;
+let facade: EngineFacade;
+let configDir = "";
+const written: unknown[] = [];
+
+const auth = { authorization: `Basic ${Buffer.from("user:secret").toString("base64")}`, "x-opencode-directory": encodeURIComponent(DIRECTORY) };
+const get = (path: string) => fetch(`${facade.url}${path}`, { headers: auth });
+const post = (path: string, body: unknown) => fetch(`${facade.url}${path}`, { method: "POST", headers: { ...auth, "content-type": "application/json" }, body: JSON.stringify(body) });
+
+beforeAll(async () => {
+ configDir = mkdtempSync(join(tmpdir(), "facade-test-"));
+ const v1Config = join(configDir, "runtime.json");
+ writeFileSync(v1Config, JSON.stringify({ model: "mock/mock-model", provider: { mock: { npm: "@ai-sdk/openai-compatible", options: { baseURL: "http://x/v1" }, models: { "mock-model": {} } } } }));
+ upstream = Bun.serve({
+ port: 0,
+ async fetch(request) {
+ const url = new URL(request.url);
+ if (request.headers.get("authorization") !== `Basic ${Buffer.from("opencode:engine-pw").toString("base64")}`) return new Response("", { status: 401 });
+ const query = Object.fromEntries(url.searchParams);
+ const body = request.method === "GET" ? undefined : await request.json().catch(() => undefined);
+ recorded.push({ method: request.method, path: url.pathname, query, body });
+ const json = (value: unknown, status = 200) => Response.json(value, { status });
+ if (url.pathname === "/api/event") {
+ const stream = new ReadableStream({
+ start(controller) {
+ const encoder = new TextEncoder();
+ eventSink = (event) => controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`));
+ eventSink({ id: "evt_0", type: "server.connected", data: {} });
+ },
+ });
+ return new Response(stream, { headers: { "content-type": "text/event-stream" } });
+ }
+ if (url.pathname === `/api/session/${SESSION}` && request.method === "GET") return json({ data: tree.session });
+ if (url.pathname === `/api/session/${SESSION}/message`) {
+ const messages = query.order === "desc" ? [...tree.messages].reverse() : tree.messages;
+ return json({ data: messages.slice(0, Number(query.limit ?? 50)), cursor: {} });
+ }
+ if (url.pathname === "/api/session/active") return json({ data: {} });
+ if (url.pathname === "/api/session" && request.method === "POST") return json({ data: { ...tree.session, id: "ses_new", title: undefined } });
+ if (url.pathname === "/api/permission/request") {
+ return json({ location: { directory: DIRECTORY }, data: [{ id: "per_1", sessionID: SESSION, action: "shell", resources: ["rm -rf build"], metadata: {} }] });
+ }
+ if (url.pathname === "/api/mcp") return json({ location: { directory: DIRECTORY }, data: [{ name: "cloud", status: { status: "connected" } }, { name: "broken", status: { status: "failed", error: "boom" } }] });
+ if (url.pathname === "/api/agent") return json({ location: { directory: DIRECTORY }, data: [{ id: "general", description: "General", mode: "subagent", permissions: [{ action: "subagent", resource: "*", effect: "allow" }] }] });
+ if (request.method === "POST" || request.method === "PUT" || request.method === "DELETE") return new Response(null, { status: 204 });
+ return json({ data: null }, 404);
+ },
+ });
+ facade = await startEngineFacade({
+ upstreamUrl: `http://127.0.0.1:${upstream.port}`,
+ upstreamPassword: "engine-pw",
+ username: "user",
+ password: "secret",
+ version: "2.0.18",
+ defaultDirectory: DIRECTORY,
+ v1ConfigPath: v1Config,
+ writeEngineConfig: async (config) => {
+ written.push(config);
+ },
+ });
+});
+
+afterAll(async () => {
+ await facade?.close();
+ upstream?.stop(true);
+ rmSync(configDir, { recursive: true, force: true });
+});
+
+describe("1.x engine adapter over the 2.x engine", () => {
+ test("requires the per-boot Basic credentials", async () => {
+ const response = await fetch(`${facade.url}/global/health`);
+ expect(response.status).toBe(401);
+ expect(await (await get("/global/health")).json()).toEqual({ healthy: true, version: "2.0.18" });
+ });
+
+ test("renders the engine config from the 1.x runtime file at start", () => {
+ const config = written.at(-1) as Record<string, unknown>;
+ expect(config.model).toBe("mock/mock-model");
+ expect((config.providers as Record<string, { package: string }>).mock.package).toBe("@opencode/ai/providers/openai-compatible");
+ });
+
+ test("message pages read newest first with the 1.x cursor", async () => {
+ const all = (await (await get(`/session/${SESSION}/message`)).json()) as Array<{ info: { id: string; role: string } }>;
+ expect(all.map((message) => message.info.role)).toEqual(["user", "assistant", "assistant", "assistant", "assistant"]);
+ const page = await get(`/session/${SESSION}/message?limit=2`);
+ const newest = (await page.json()) as Array<{ info: { id: string } }>;
+ expect(newest.map((message) => message.info.id)).toEqual(all.slice(3).map((message) => message.info.id));
+ const cursor = page.headers.get("x-next-cursor");
+ expect(cursor).toBeTruthy();
+ const older = (await (await get(`/session/${SESSION}/message?limit=2&before=${cursor}`)).json()) as Array<{ info: { id: string } }>;
+ expect(older.map((message) => message.info.id)).toEqual(all.slice(1, 3).map((message) => message.info.id));
+ const one = (await (await get(`/session/${SESSION}/message/${all[0]!.info.id}`)).json()) as { info: { role: string } };
+ expect(one.info.role).toBe("user");
+ });
+
+ test("a session reads with the agent and model of its latest step", async () => {
+ const info = (await (await get(`/session/${SESSION}`)).json()) as Record<string, unknown>;
+ expect(info).toMatchObject({ id: SESSION, directory: DIRECTORY, agent: "build", model: { id: "mock-model", providerID: "mock", variant: "default" }, version: "2.0.18" });
+ });
+
+ test("prompt_async applies model, variant, agent and system, then sends text and files", async () => {
+ recorded.length = 0;
+ const response = await post(`/session/${SESSION}/prompt_async`, {
+ messageID: "msg_client_1",
+ model: { providerID: "omnirush", modelID: "gpt-6-astra" },
+ variant: "high",
+ agent: "omnirush",
+ system: "Extra system",
+ parts: [
+ { type: "text", text: "hello" },
+ { type: "file", mime: "image/png", filename: "a.png", url: "data:image/png;base64,AAAA" },
+ ],
+ });
+ expect(response.status).toBe(204);
+ const calls = recorded.map((call) => `${call.method} ${call.path}`);
+ expect(calls).toEqual([
+ `POST /api/session/${SESSION}/model`,
+ `POST /api/session/${SESSION}/agent`,
+ `PUT /api/experimental/session/${SESSION}/instructions/entries/omnirush.system`,
+ `POST /api/session/${SESSION}/prompt`,
+ ]);
+ expect(recorded[0]!.body).toEqual({ model: { providerID: "omnirush", id: "gpt-6-astra", variant: "high" } });
+ expect(recorded[1]!.body).toEqual({ agent: "omnirush" });
+ expect(recorded[2]!.body).toEqual({ value: "Extra system" });
+ expect(recorded[3]!.body).toEqual({ id: "msg_client_1", text: "hello", files: [{ uri: "data:image/png;base64,AAAA", name: "a.png" }] });
+ // The same selection is not sent again.
+ recorded.length = 0;
+ await post(`/session/${SESSION}/prompt_async`, { model: { providerID: "omnirush", modelID: "gpt-6-astra" }, variant: "high", agent: "omnirush", system: "Extra system", parts: [{ type: "text", text: "again" }] });
+ expect(recorded.map((call) => call.path)).toEqual([`/api/session/${SESSION}/prompt`]);
+ });
+
+ test("permissions list and reply in 1.x form", async () => {
+ const list = (await (await get("/permission")).json()) as Array<Record<string, unknown>>;
+ expect(list).toEqual([{ id: "per_1", sessionID: SESSION, permission: "bash", patterns: ["rm -rf build"], metadata: {}, always: ["rm -rf build"] }]);
+ recorded.length = 0;
+ expect((await post("/permission/per_1/reply", { reply: "always" })).status).toBe(200);
+ expect(recorded.at(-1)).toMatchObject({ method: "POST", path: `/api/session/${SESSION}/permission/per_1/reply`, body: { decision: "always" } });
+ });
+
+ test("MCP status and agents in 1.x form", async () => {
+ expect(await (await get("/mcp")).json()).toEqual({ cloud: { status: "connected" }, broken: { status: "failed", error: "boom" } });
+ const agents = (await (await get("/agent")).json()) as Array<Record<string, unknown>>;
+ expect(agents).toEqual([{ name: "general", description: "General", mode: "subagent", permission: [{ permission: "task", pattern: "*", action: "allow" }], options: {} }]);
+ });
+
+ test("provider keys delivered at runtime reach the engine config", async () => {
+ expect((await fetch(`${facade.url}/auth/mock`, { method: "PUT", headers: { ...auth, "content-type": "application/json" }, body: JSON.stringify({ type: "api", key: "sk-1" }) })).status).toBe(200);
+ const config = written.at(-1) as { providers: Record<string, { settings: Record<string, unknown> }> };
+ expect(config.providers.mock.settings.apiKey).toBe("sk-1");
+ });
+
+ test("the event stream speaks 1.x and keeps to the request's directory", async () => {
+ const controller = new AbortController();
+ const response = await fetch(`${facade.url}/event`, { headers: auth, signal: controller.signal });
+ const reader = response.body!.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+ const events: Array<{ type: string; properties: Record<string, unknown> }> = [];
+ const pump = (async () => {
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) return;
+ buffer += decoder.decode(value, { stream: true });
+ let index: number;
+ while ((index = buffer.indexOf("\n\n")) >= 0) {
+ const frame = buffer.slice(0, index);
+ buffer = buffer.slice(index + 2);
+ if (frame.startsWith("data: ")) events.push(JSON.parse(frame.slice(6)));
+ }
+ }
+ })().catch(() => undefined);
+ await Bun.sleep(100);
+ eventSink!({ type: "session.execution.started", location: { directory: "/elsewhere" }, data: { sessionID: "ses_other" } });
+ eventSink!({ type: "session.execution.started", location: { directory: DIRECTORY }, data: { sessionID: SESSION } });
+ eventSink!({ type: "session.execution.succeeded", location: { directory: DIRECTORY }, data: { sessionID: SESSION } });
+ await Bun.sleep(200);
+ controller.abort();
+ await pump;
+ const mine = events.filter((event) => event.type !== "server.connected" && event.type !== "server.heartbeat");
+ expect(mine.map((event) => `${event.type}:${String(event.properties.sessionID)}`)).toEqual([
+ `session.status:${SESSION}`,
+ `session.status:${SESSION}`,
+ `session.idle:${SESSION}`,
+ ]);
+ });
+});
diff --git a/apps/server/src/engine2/facade.ts b/apps/server/src/engine2/facade.ts
new file mode 100644
index 00000000..d73aa346
--- /dev/null
+++ b/apps/server/src/engine2/facade.ts
@@ -0,0 +1,1152 @@
+/**
+ * The 1.x engine HTTP API served in front of the 2.x engine.
+ *
+ * OmniRush.ai's server, renderer and turn observer speak the opencode 1.x
+ * API (`/session`, `/session/:id/prompt_async`, `/event`, `/permission`, …).
+ * The bundled 2.x engine only serves its own contract under `/api/*`. The
+ * facade is a loopback HTTP server that answers the 1.x routes the app uses by
+ * calling the 2.x engine and reshaping the result with engine2/shapes.ts and
+ * engine2/events.ts, so everything above the engine (and the uploaded
+ * traces) keeps the 1.x shapes. Requests to `/api/*` are passed through with
+ * the few 1.x-era `/api` routes the renderer uses (session permissions) mapped.
+ *
+ * Auth mirrors the 1.x engine: HTTP Basic with the per-boot username and
+ * password managed-opencode.ts generates; the facade authenticates to the
+ * engine with the engine's own password. The directory a request is for comes
+ * from `x-opencode-directory` / `?directory=` as with 1.x and is sent to the
+ * engine as `location[directory]`.
+ */
+import http from "node:http";
+import { spawn } from "node:child_process";
+import { readFile } from "node:fs/promises";
+import { homedir } from "node:os";
+import { buildEngine2Config, v2Mcp } from "./config.js";
+import { EventTranslator, v1EventEnvelope, type ScopedV1Event, type V1Event } from "./events.js";
+import {
+ v1Agent,
+ v1Command,
+ v1McpStatus,
+ v1Messages,
+ v1PermissionRequest,
+ v1PermissionV2Request,
+ v1ProviderList,
+ v1QuestionRequest,
+ v1Session,
+ v2FormAnswer,
+ type V1Message,
+} from "./shapes.js";
+import { arr, isRecord, num, omitUndefined, record, str, unwrap, type JsonRecord } from "./util.js";
+
+export type EngineFacadeOptions = {
+ /** The 2.x engine's base URL and password (user `opencode`). */
+ upstreamUrl: string;
+ upstreamPassword: string;
+ /** Credentials the facade itself requires (the 1.x engine's per-boot Basic auth). */
+ username: string;
+ password: string;
+ hostname?: string;
+ port?: number;
+ /** The engine's version (reported as `version` in 1.x session records and health). */
+ version: string;
+ /** The directory used when a request names none (the engine process cwd). */
+ defaultDirectory: string;
+ /** The 1.x runtime config file (OPENCODE_CONFIG) the engine config is rendered from. */
+ v1ConfigPath?: string;
+ /** Writes the rendered 2.x config (the engine watches it and reloads). */
+ writeEngineConfig?: (config: JsonRecord) => Promise<void>;
+ /** Plugin directories the rendered config names (OmniRush.ai's plugin bridge). */
+ plugins?: string[];
+ /** Engine state paths reported by `/path`. */
+ paths?: { state?: string; config?: string };
+ log?: (message: string, attributes?: Record<string, unknown>) => void;
+ fetch?: typeof globalThis.fetch;
+};
+
+export type EngineFacade = {
+ url: string;
+ close: () => Promise<void>;
+ /** Re-renders the engine config from the 1.x runtime file (as `/instance/dispose` does). */
+ refreshConfig: () => Promise<void>;
+};
+
+/** The tools a 2.x engine offers before the plugin bridge has reported its list (1.x names). */
+const BUILTIN_TOOL_IDS = ["question", "bash", "read", "glob", "grep", "edit", "write", "task", "webfetch", "websearch", "skill", "apply_patch"];
+
+/** Opens a URL in the user's browser, as the 1.x engine did for MCP OAuth. */
+function openInBrowser(url: string): void {
+ if (!/^https?:\/\//i.test(url)) return;
+ const [command, args] = process.platform === "darwin"
+ ? ["open", [url]]
+ : process.platform === "win32"
+ ? ["rundll32", ["url.dll,FileProtocolHandler", url]]
+ : ["xdg-open", [url]];
+ try {
+ const child = spawn(command, args as string[], { stdio: "ignore", detached: true });
+ child.on("error", () => undefined);
+ child.unref();
+ } catch {
+ // No browser launcher: the app shows the URL for manual completion.
+ }
+}
+
+class UpstreamError extends Error {
+ constructor(readonly status: number, readonly body: unknown) {
+ super(`engine answered ${status}`);
+ }
+}
+
+type Json = unknown;
+
+function json(res: http.ServerResponse, status: number, body: Json, headers: Record<string, string> = {}): void {
+ const text = JSON.stringify(body);
+ res.writeHead(status, { "content-type": "application/json", "content-length": String(Buffer.byteLength(text)), ...headers });
+ res.end(text);
+}
+
+function noContent(res: http.ServerResponse): void {
+ res.writeHead(204);
+ res.end();
+}
+
+function namedError(res: http.ServerResponse, status: number, name: string, message: string): void {
+ json(res, status, { name, data: { message } });
+}
+
+async function readBody(req: http.IncomingMessage): Promise<unknown> {
+ const chunks: Buffer[] = [];
+ for await (const chunk of req) chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
+ if (chunks.length === 0) return undefined;
+ const text = Buffer.concat(chunks).toString("utf8");
+ if (!text.trim()) return undefined;
+ try {
+ return JSON.parse(text);
+ } catch {
+ return undefined;
+ }
+}
+
+function encodeCursor(id: string): string {
+ return Buffer.from(JSON.stringify({ id })).toString("base64url");
+}
+
+function decodeCursor(value: string | null): string | null {
+ if (!value) return null;
+ try {
+ const parsed: unknown = JSON.parse(Buffer.from(value, "base64url").toString("utf8"));
+ return isRecord(parsed) && typeof parsed.id === "string" ? parsed.id : null;
+ } catch {
+ return value.startsWith("msg_") ? value : null;
+ }
+}
+
+function decodeDirectory(value: string | undefined | null): string | undefined {
+ if (!value) return undefined;
+ try {
+ return decodeURIComponent(value);
+ } catch {
+ return value;
+ }
+}
+
+type ModelRef = { providerID: string; modelID: string; variant?: string };
+
+export async function startEngineFacade(options: EngineFacadeOptions): Promise<EngineFacade> {
+ const fetchImpl = options.fetch ?? globalThis.fetch;
+ const upstream = options.upstreamUrl.replace(/\/+$/, "");
+ const upstreamAuth = `Basic ${Buffer.from(`opencode:${options.upstreamPassword}`).toString("base64")}`;
+ const expectedAuth = `Basic ${Buffer.from(`${options.username}:${options.password}`).toString("base64")}`;
+ const log = options.log ?? (() => undefined);
+ const apiKeys: Record<string, string> = {};
+ /** Session model/agent last sent to the engine, to skip redundant switch records. */
+ const selected = new Map<string, { model?: string; agent?: string; system?: string }>();
+ const archived = new Map<string, number>();
+
+ const call = async (
+ method: string,
+ path: string,
+ init: { directory?: string; query?: Record<string, string | undefined>; body?: unknown; signal?: AbortSignal } = {},
+ ): Promise<unknown> => {
+ const url = new URL(`${upstream}${path}`);
+ if (init.directory) url.searchParams.set("location[directory]", init.directory);
+ for (const [key, value] of Object.entries(init.query ?? {})) if (value !== undefined) url.searchParams.set(key, value);
+ const response = await fetchImpl(url, {
+ method,
+ headers: { authorization: upstreamAuth, ...(init.body !== undefined ? { "content-type": "application/json" } : {}) },
+ body: init.body !== undefined ? JSON.stringify(init.body) : undefined,
+ signal: init.signal,
+ });
+ const text = await response.text();
+ let payload: unknown = undefined;
+ if (text) {
+ try {
+ payload = JSON.parse(text);
+ } catch {
+ payload = text;
+ }
+ }
+ if (!response.ok) throw new UpstreamError(response.status, payload);
+ return payload;
+ };
+
+ const translator = new EventTranslator({
+ version: options.version,
+ lookupSession: (sessionID) => call("GET", `/api/session/${encodeURIComponent(sessionID)}`),
+ });
+
+ // ---- config rendering ---------------------------------------------------
+ const readV1Config = async (): Promise<JsonRecord> => {
+ if (!options.v1ConfigPath) return {};
+ try {
+ const parsed: unknown = JSON.parse(await readFile(options.v1ConfigPath, "utf8"));
+ return isRecord(parsed) ? parsed : {};
+ } catch {
+ return {};
+ }
+ };
+ let v1ConfigCache: JsonRecord = await readV1Config();
+ const refreshConfig = async (): Promise<void> => {
+ v1ConfigCache = await readV1Config();
+ if (options.writeEngineConfig) await options.writeEngineConfig(buildEngine2Config({ v1: v1ConfigCache, apiKeys, plugins: options.plugins }));
+ };
+
+ // ---- sessions & messages -----------------------------------------------
+ const sessionInfo = async (sessionID: string, directory?: string): Promise<JsonRecord | null> => {
+ const info = v1Session(await call("GET", `/api/session/${encodeURIComponent(sessionID)}`), { version: options.version, directory });
+ if (!info) return null;
+ const archivedAt = archived.get(sessionID) ?? num(record(info, "metadata"), "omnirushArchivedAt");
+ if (archivedAt) info.time = { ...(record(info, "time") ?? {}), archived: archivedAt };
+ if (!info.agent || !info.model) {
+ // 2.x records the agent and model on each step, not on the session: take the latest step's.
+ const recent = await call("GET", `/api/session/${encodeURIComponent(sessionID)}/message`, { query: { order: "desc", limit: "20" } }).catch(() => undefined);
+ const step = arr(recent, "data").find((message) => str(message, "type") === "assistant");
+ const variant = selected.get(sessionID)?.model?.split("#")[1];
+ if (step) {
+ info.agent ??= str(step, "agent");
+ const model = record(step, "model");
+ if (!info.model && model && str(model, "id") && str(model, "providerID")) {
+ info.model = { id: str(model, "id"), providerID: str(model, "providerID"), variant: str(model, "variant") ?? (variant || "default") };
+ }
+ }
+ if (!info.parentID) info.agent ??= "build";
+ }
+ translator.noteSession(sessionID, {
+ directory: String(info.directory || "") || null,
+ parentID: str(info, "parentID"),
+ agent: str(info, "agent"),
+ model: isRecord(info.model) && str(info.model, "id") ? { providerID: String(str(info.model, "providerID")), modelID: String(str(info.model, "id")), variant: str(info.model, "variant") } : undefined,
+ info,
+ });
+ return info;
+ };
+
+ const rawMessages = async (sessionID: string): Promise<unknown[]> => {
+ const all: unknown[] = [];
+ let cursor: string | undefined;
+ for (let page = 0; page < 500; page++) {
+ const payload = await call("GET", `/api/session/${encodeURIComponent(sessionID)}/message`, {
+ query: { order: "asc", limit: "200", cursor },
+ });
+ const items = arr(payload, "data");
+ all.push(...items);
+ const next = str(record(payload, "cursor"), "next");
+ if (items.length < 200 || !next || next === cursor) break;
+ cursor = next;
+ }
+ return all;
+ };
+
+ const sessionMessages = async (sessionID: string): Promise<V1Message[]> => {
+ const info = await sessionInfo(sessionID).catch(() => null);
+ const directory = info ? String(info.directory || "") || undefined : undefined;
+ const model = isRecord(info?.model) && str(info!.model, "id")
+ ? { providerID: String(str(info!.model, "providerID")), modelID: String(str(info!.model, "id")), variant: str(info!.model, "variant") }
+ : undefined;
+ return v1Messages(await rawMessages(sessionID), {
+ sessionID,
+ directory,
+ root: "/",
+ agent: info ? str(info, "agent") : undefined,
+ model,
+ child: Boolean(info && str(info, "parentID")),
+ });
+ };
+
+ const listSessions = async (directory: string | undefined, query: URLSearchParams, rootsOnly: boolean): Promise<JsonRecord[]> => {
+ const limit = Math.max(1, Math.min(Number(query.get("limit") ?? "") || 10_000, 10_000));
+ const out: JsonRecord[] = [];
+ let cursor: string | undefined;
+ const includeArchived = query.get("archived") === "true";
+ for (let page = 0; page < 200 && out.length < limit; page++) {
+ const payload = await call("GET", "/api/session", {
+ query: {
+ limit: String(Math.min(200, limit - out.length + 10)),
+ directory: directory,
+ parentID: rootsOnly ? "null" : undefined,
+ search: query.get("search") ?? undefined,
+ cursor,
+ },
+ });
+ const items = arr(payload, "data");
+ for (const item of items) {
+ const info = v1Session(item, { version: options.version, directory });
+ if (!info) continue;
+ const archivedAt = archived.get(String(info.id)) ?? num(record(info, "metadata"), "omnirushArchivedAt");
+ if (archivedAt) info.time = { ...(record(info, "time") ?? {}), archived: archivedAt };
+ if (archivedAt && !includeArchived && query.has("archived")) continue;
+ const start = Number(query.get("start") ?? "");
+ if (Number.isFinite(start) && start > 0 && Number(record(info, "time")?.updated ?? 0) < start) continue;
+ translator.noteSession(String(info.id), { directory: String(info.directory || "") || null, parentID: str(info, "parentID") });
+ out.push(info);
+ if (out.length >= limit) break;
+ }
+ const next = str(record(payload, "cursor"), "next");
+ if (items.length === 0 || !next || next === cursor) break;
+ cursor = next;
+ }
+ return out;
+ };
+
+ const modelRefFromBody = (body: JsonRecord): ModelRef | undefined => {
+ const model = record(body, "model");
+ const providerID = str(model, "providerID");
+ const modelID = str(model, "modelID") ?? str(model, "id");
+ if (!providerID || !modelID) return undefined;
+ const variant = str(body, "variant") ?? str(model, "variant") ?? str(body, "reasoning_effort");
+ return variant ? { providerID, modelID, variant } : { providerID, modelID };
+ };
+
+ /** Applies a 1.x prompt's model, agent and system prompt to the session before it is sent. */
+ const prepareSession = async (sessionID: string, body: JsonRecord): Promise<void> => {
+ const current = selected.get(sessionID) ?? {};
+ const model = modelRefFromBody(body);
+ if (model) {
+ const key = `${model.providerID}/${model.modelID}#${model.variant ?? ""}`;
+ if (current.model !== key) {
+ await call("POST", `/api/session/${encodeURIComponent(sessionID)}/model`, {
+ body: { model: omitUndefined({ providerID: model.providerID, id: model.modelID, variant: model.variant && model.variant !== "default" ? model.variant : undefined }) },
+ });
+ current.model = key;
+ translator.noteSession(sessionID, { model });
+ }
+ }
+ const agent = str(body, "agent");
+ if (agent && current.agent !== agent) {
+ await call("POST", `/api/session/${encodeURIComponent(sessionID)}/agent`, { body: { agent } });
+ current.agent = agent;
+ translator.noteSession(sessionID, { agent });
+ }
+ const system = str(body, "system") ?? "";
+ if ((current.system ?? "") !== system) {
+ const path = `/api/experimental/session/${encodeURIComponent(sessionID)}/instructions/entries/omnirush.system`;
+ if (system) await call("PUT", path, { body: { value: system } });
+ else await call("DELETE", path).catch(() => undefined);
+ current.system = system;
+ }
+ selected.set(sessionID, current);
+ };
+
+ /** A 1.x prompt's parts as the 2.x prompt (text, files, agent mentions). */
+ const v2Prompt = (body: JsonRecord): JsonRecord => {
+ const texts: string[] = [];
+ const files: JsonRecord[] = [];
+ const agents: JsonRecord[] = [];
+ for (const part of arr(body, "parts")) {
+ if (!isRecord(part)) continue;
+ const type = str(part, "type");
+ if (type === "text" && typeof part.text === "string") texts.push(part.text);
+ else if (type === "file" && typeof part.url === "string") files.push(omitUndefined({ uri: part.url, name: str(part, "filename") }));
+ else if (type === "agent" && typeof part.name === "string") agents.push({ id: part.name });
+ else if (type === "subtask" && typeof part.prompt === "string") texts.push(part.prompt);
+ }
+ return omitUndefined({
+ id: str(body, "messageID"),
+ text: texts.join("\n\n"),
+ files: files.length ? files : undefined,
+ agents: agents.length ? agents : undefined,
+ resume: body.noReply === true ? false : undefined,
+ });
+ };
+
+ const waitIdle = async (sessionID: string, timeoutMs = 30 * 60_000): Promise<void> => {
+ const started = Date.now();
+ await new Promise((resolve) => setTimeout(resolve, 250));
+ while (Date.now() - started < timeoutMs) {
+ const active = unwrap(await call("GET", "/api/session/active").catch(() => ({})));
+ if (!isRecord(active) || !(sessionID in active)) return;
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ }
+ };
+
+ const permissionSessions = new Map<string, string>();
+ const pendingPermissions = async (directory?: string): Promise<JsonRecord[]> => {
+ const payload = await call("GET", "/api/permission/request", { directory });
+ const out: JsonRecord[] = [];
+ for (const item of arr(payload, "data").length ? arr(payload, "data") : Array.isArray(unwrap(payload)) ? (unwrap(payload) as unknown[]) : []) {
+ const mapped = v1PermissionRequest(item);
+ if (!mapped) continue;
+ permissionSessions.set(String(mapped.id), String(mapped.sessionID));
+ out.push(mapped);
+ }
+ return out;
+ };
+
+ const pendingQuestions = async (directory?: string): Promise<JsonRecord[]> => {
+ const payload = await call("GET", "/api/form", { directory });
+ const list = unwrap(payload);
+ const out: JsonRecord[] = [];
+ for (const item of Array.isArray(list) ? list : []) {
+ const state = str(item, "state") ?? str(record(item, "state"), "status");
+ if (state && state !== "pending" && state !== "open") continue;
+ const mapping = v1QuestionRequest(item);
+ if (!mapping) continue;
+ translator.rememberQuestion(String(mapping.request.id), mapping);
+ out.push(mapping.request);
+ }
+ return out;
+ };
+
+ const replyPermission = async (requestID: string, reply: string, message: string | undefined, sessionID?: string, directory?: string) => {
+ let session = sessionID ?? permissionSessions.get(requestID);
+ if (!session) {
+ await pendingPermissions(directory).catch(() => []);
+ session = permissionSessions.get(requestID);
+ }
+ if (!session) throw new UpstreamError(404, { name: "NotFoundError", data: { message: `Permission request ${requestID} not found` } });
+ await call("POST", `/api/session/${encodeURIComponent(session)}/permission/${encodeURIComponent(requestID)}/reply`, {
+ body: omitUndefined({ decision: reply === "always" || reply === "reject" ? reply : "once", message }),
+ });
+ permissionSessions.delete(requestID);
+ };
+
+ const findQuestion = async (requestID: string, directory?: string) => {
+ let mapping = translator.questionMapping(requestID);
+ if (!mapping) {
+ await pendingQuestions(directory).catch(() => []);
+ mapping = translator.questionMapping(requestID);
+ }
+ return mapping;
+ };
+
+ // ---- MCP ----------------------------------------------------------------
+ const mcpAttempts = new Map<string, { integrationID: string; attemptID: string }>();
+ const engineTools = new Map<string, Array<{ id: string; description: string; parameters: JsonRecord }>>();
+ const mcpServers = async (directory: string): Promise<JsonRecord[]> => {
+ const list = unwrap(await call("GET", "/api/mcp", { directory }));
+ return (Array.isArray(list) ? list : []).filter(isRecord);
+ };
+ const settledMcpDirectories = new Set<string>();
+ const mcpStatuses = async (directory: string): Promise<Record<string, JsonRecord>> => {
+ let servers = await mcpServers(directory);
+ const deadline = Date.now() + 5_000;
+ if (!settledMcpDirectories.has(directory)) {
+ // A location's config (and its MCP servers) loads on first use: wait for the list to settle.
+ let previous = JSON.stringify(servers.map((server) => server.name));
+ const started = Date.now();
+ while (Date.now() < deadline) {
+ await new Promise((resolve) => setTimeout(resolve, 400));
+ servers = await mcpServers(directory);
+ const current = JSON.stringify(servers.map((server) => server.name));
+ if (current === previous && (servers.length > 0 || Date.now() - started > 1_200)) break;
+ previous = current;
+ }
+ settledMcpDirectories.add(directory);
+ }
+ // 2.x reports servers still connecting as pending; 1.x answered once they settled.
+ while (servers.some((server) => str(record(server, "status"), "status") === "pending") && Date.now() < deadline) {
+ await new Promise((resolve) => setTimeout(resolve, 250));
+ servers = await mcpServers(directory);
+ }
+ const out: Record<string, JsonRecord> = {};
+ for (const server of servers) {
+ const name = str(server, "name");
+ if (name) out[name] = v1McpStatus(server);
+ }
+ return out;
+ };
+ const mcpIntegration = async (name: string, directory: string): Promise<JsonRecord | undefined> => {
+ const server = (await mcpServers(directory)).find((entry) => str(entry, "name") === name);
+ const integrationID = str(server, "integrationID");
+ if (!integrationID) return undefined;
+ const integration = unwrap(await call("GET", `/api/integration/${encodeURIComponent(integrationID)}`, { directory }).catch(() => undefined));
+ return isRecord(integration) ? integration : undefined;
+ };
+ const waitMcpAttempt = async (attempt: { integrationID: string; attemptID: string }, directory: string, timeoutMs: number): Promise<string> => {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ const status = unwrap(await call("GET", `/api/integration/${attempt.integrationID}/connect/oauth/${encodeURIComponent(attempt.attemptID)}`, { directory }).catch(() => undefined));
+ const state = str(status, "status");
+ if (state && state !== "pending") return state;
+ await new Promise((resolve) => setTimeout(resolve, 500));
+ }
+ return "pending";
+ };
+
+ // ---- events -------------------------------------------------------------
+ type Subscriber = { directory: string | null; global: boolean; write: (event: V1Event, directory: string | null) => void };
+ const subscribers = new Set<Subscriber>();
+ const streamController = new AbortController();
+ let streamStarted = false;
+ const dispatch = (items: ScopedV1Event[]) => {
+ for (const item of items) {
+ for (const subscriber of subscribers) {
+ if (!subscriber.global && subscriber.directory && item.directory && item.directory !== subscriber.directory) continue;
+ subscriber.write(item.event, item.directory);
+ }
+ }
+ };
+ const runStream = async () => {
+ let backoff = 250;
+ while (!streamController.signal.aborted) {
+ try {
+ const response = await fetchImpl(`${upstream}/api/event`, { headers: { authorization: upstreamAuth, accept: "text/event-stream" }, signal: streamController.signal });
+ if (!response.ok || !response.body) throw new Error(`event stream answered ${response.status}`);
+ backoff = 250;
+ const decoder = new TextDecoder();
+ let buffer = "";
+ const reader = response.body.getReader();
+ // Events are translated in order: a translation may await a session lookup.
+ let chain: Promise<void> = Promise.resolve();
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+ let index: number;
+ while ((index = buffer.indexOf("\n\n")) >= 0) {
+ const frame = buffer.slice(0, index);
+ buffer = buffer.slice(index + 2);
+ const data = frame.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
+ if (!data) continue;
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(data);
+ } catch {
+ continue;
+ }
+ chain = chain.then(async () => {
+ try {
+ dispatch(await translator.translate(parsed));
+ } catch (error) {
+ log("engine event translation failed", { error: error instanceof Error ? error.message : String(error) });
+ }
+ });
+ }
+ }
+ } catch (error) {
+ if (streamController.signal.aborted) return;
+ log("engine event stream interrupted", { error: error instanceof Error ? error.message : String(error) });
+ }
+ await new Promise((resolve) => setTimeout(resolve, backoff));
+ backoff = Math.min(backoff * 2, 5_000);
+ }
+ };
+ const ensureStream = () => {
+ if (streamStarted) return;
+ streamStarted = true;
+ void runStream();
+ };
+
+ const serveEvents = (req: http.IncomingMessage, res: http.ServerResponse, directory: string | null, global: boolean) => {
+ ensureStream();
+ res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache", connection: "keep-alive" });
+ const write = (event: V1Event, eventDirectory: string | null) => {
+ const envelope = v1EventEnvelope(event);
+ const payload = global ? { directory: eventDirectory ?? "global", payload: envelope } : envelope;
+ res.write(`data: ${JSON.stringify(payload)}\n\n`);
+ };
+ write({ type: "server.connected", properties: {} }, null);
+ const subscriber: Subscriber = { directory, global, write };
+ subscribers.add(subscriber);
+ const heartbeat = setInterval(() => {
+ const beat = { type: "server.heartbeat", properties: {} };
+ write(beat, null);
+ }, 10_000);
+ const close = () => {
+ clearInterval(heartbeat);
+ subscribers.delete(subscriber);
+ };
+ req.on("close", close);
+ res.on("close", close);
+ };
+
+ // ---- routing ------------------------------------------------------------
+ const handle = async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
+ const url = new URL(req.url ?? "/", "http://engine.local");
+ const method = (req.method ?? "GET").toUpperCase();
+ const path = url.pathname.replace(/\/+$/, "") || "/";
+ const directory = decodeDirectory(req.headers["x-opencode-directory"] as string | undefined) ?? url.searchParams.get("directory") ?? undefined;
+ const dir = directory ?? options.defaultDirectory;
+ const segments = path.split("/").filter(Boolean).map((segment) => decodeURIComponent(segment));
+
+ if (path === "/global/health" || path === "/api/health") {
+ json(res, 200, { healthy: true, version: options.version });
+ return;
+ }
+ if (method === "GET" && path === "/event") return serveEvents(req, res, dir, false);
+ if (method === "GET" && path === "/global/event") return serveEvents(req, res, null, true);
+
+ // /session ...
+ if (segments[0] === "session") {
+ if (segments.length === 1) {
+ if (method === "GET") {
+ json(res, 200, await listSessions(directory, url.searchParams, url.searchParams.get("roots") === "true"));
+ return;
+ }
+ if (method === "POST") {
+ const body = (await readBody(req)) as JsonRecord | undefined;
+ const created = await call("POST", "/api/session", {
+ body: omitUndefined({ title: str(body, "title"), location: { directory: dir } }),
+ });
+ const info = v1Session(created, { version: options.version, directory: dir });
+ if (!info) throw new UpstreamError(502, { message: "engine created no session" });
+ translator.noteSession(String(info.id), { directory: dir, info });
+ json(res, 200, info);
+ return;
+ }
+ }
+ if (segments[1] === "status" && segments.length === 2 && method === "GET") {
+ const active = unwrap(await call("GET", "/api/session/active", { directory }));
+ const out: Record<string, JsonRecord> = {};
+ if (isRecord(active)) for (const id of Object.keys(active)) out[id] = translator.statusOf(id)?.type === "retry" ? translator.statusOf(id)! : { type: "busy" };
+ if (directory) {
+ for (const id of Object.keys(out)) {
+ const known = translator.directoryOf(id);
+ if (known && known !== directory) delete out[id];
+ }
+ }
+ json(res, 200, out);
+ return;
+ }
+ const sessionID = segments[1]!;
+ const encoded = encodeURIComponent(sessionID);
+ const action = segments[2];
+ if (!action) {
+ if (method === "GET") {
+ const info = await sessionInfo(sessionID, directory);
+ if (!info) return namedError(res, 404, "NotFoundError", `Session not found: ${sessionID}`);
+ json(res, 200, info);
+ return;
+ }
+ if (method === "DELETE") {
+ await call("POST", `/api/session/${encoded}/interrupt`, { query: { resume: "false" } }).catch(() => undefined);
+ await call("DELETE", `/api/session/${encoded}`);
+ json(res, 200, true);
+ return;
+ }
+ if (method === "PATCH") {
+ const body = ((await readBody(req)) ?? {}) as JsonRecord;
+ const patch: JsonRecord = {};
+ if (typeof body.title === "string") patch.title = body.title;
+ const time = record(body, "time");
+ if (time && "archived" in time) {
+ const at = typeof time.archived === "number" ? time.archived : undefined;
+ if (at) archived.set(sessionID, at);
+ else archived.delete(sessionID);
+ patch.metadata = { omnirushArchivedAt: at ?? null };
+ }
+ if (Object.keys(patch).length) await call("PATCH", `/api/session/${encoded}`, { body: patch });
+ const info = await sessionInfo(sessionID, directory);
+ json(res, 200, info);
+ return;
+ }
+ }
+ switch (action) {
+ case "children": {
+ const payload = await call("GET", "/api/session", { query: { parentID: sessionID, limit: "200" } });
+ json(res, 200, arr(payload, "data").map((item) => v1Session(item, { version: options.version, directory })).filter(Boolean));
+ return;
+ }
+ case "message": {
+ if (method === "GET" && segments.length === 3) {
+ const messages = await sessionMessages(sessionID);
+ const limit = Number(url.searchParams.get("limit") ?? "");
+ const before = decodeCursor(url.searchParams.get("before"));
+ let end = messages.length;
+ if (before) {
+ const index = messages.findIndex((message) => message.info.id === before);
+ if (index >= 0) end = index;
+ }
+ if (!Number.isFinite(limit) || limit <= 0) {
+ json(res, 200, messages.slice(0, end));
+ return;
+ }
+ const start = Math.max(0, end - limit);
+ const page = messages.slice(start, end);
+ const headers: Record<string, string> = { "access-control-expose-headers": "Link, X-Next-Cursor" };
+ if (start > 0 && page[0]) headers["x-next-cursor"] = encodeCursor(String(page[0].info.id));
+ json(res, 200, page, headers);
+ return;
+ }
+ if (method === "GET" && segments.length === 4) {
+ const messages = await sessionMessages(sessionID);
+ const found = messages.find((message) => message.info.id === segments[3]);
+ if (!found) return namedError(res, 404, "NotFoundError", `Message not found: ${segments[3]}`);
+ json(res, 200, found);
+ return;
+ }
+ if (method === "POST" && segments.length === 3) {
+ // Synchronous prompt: send, wait for the run to settle, answer with the last reply.
+ const body = ((await readBody(req)) ?? {}) as JsonRecord;
+ await prepareSession(sessionID, body);
+ await call("POST", `/api/session/${encoded}/prompt`, { body: v2Prompt(body) });
+ await waitIdle(sessionID);
+ const messages = await sessionMessages(sessionID);
+ const last = [...messages].reverse().find((message) => message.info.role === "assistant");
+ json(res, 200, last ?? null);
+ return;
+ }
+ break;
+ }
+ case "prompt_async": {
+ if (method !== "POST") break;
+ const body = ((await readBody(req)) ?? {}) as JsonRecord;
+ await prepareSession(sessionID, body);
+ await call("POST", `/api/session/${encoded}/prompt`, { body: v2Prompt(body) });
+ noContent(res);
+ return;
+ }
+ case "prompt": {
+ if (method !== "POST") break;
+ const body = ((await readBody(req)) ?? {}) as JsonRecord;
+ await prepareSession(sessionID, body);
+ await call("POST", `/api/session/${encoded}/prompt`, { body: v2Prompt(body) });
+ await waitIdle(sessionID);
+ const messages = await sessionMessages(sessionID);
+ const last = [...messages].reverse().find((message) => message.info.role === "assistant");
+ json(res, 200, last ?? null);
+ return;
+ }
+ case "command": {
+ if (method !== "POST") break;
+ const body = ((await readBody(req)) ?? {}) as JsonRecord;
+ await prepareSession(sessionID, body);
+ const name = String(body.command ?? "").replace(/^\//, "");
+ if (name === "compact" || name === "summarize") {
+ await call("POST", `/api/session/${encoded}/compact`, { body: {} });
+ } else {
+ await call("POST", `/api/session/${encoded}/command`, { body: { name, text: typeof body.arguments === "string" ? body.arguments : "" } });
+ }
+ noContent(res);
+ return;
+ }
+ case "shell": {
+ if (method !== "POST") break;
+ const body = ((await readBody(req)) ?? {}) as JsonRecord;
+ await call("POST", `/api/session/${encoded}/shell`, { body: { command: String(body.command ?? "") } });
+ json(res, 200, { id: "", sessionID, role: "assistant" });
+ return;
+ }
+ case "abort": {
+ const result = await call("POST", `/api/session/${encoded}/interrupt`, { query: { resume: "false" } }).catch((error) => {
+ if (error instanceof UpstreamError && error.status === 404) return { interrupted: false };
+ throw error;
+ });
+ json(res, 200, isRecord(result) ? result.interrupted !== false : true);
+ return;
+ }
+ case "summarize": {
+ const body = ((await readBody(req)) ?? {}) as JsonRecord;
+ await prepareSession(sessionID, body);
+ await call("POST", `/api/session/${encoded}/compact`, { body: {} });
+ json(res, 200, true);
+ return;
+ }
+ case "revert": {
+ const body = ((await readBody(req)) ?? {}) as JsonRecord;
+ const messageID = str(body, "messageID");
+ if (messageID) {
+ await call("POST", `/api/session/${encoded}/revert/stage`, { body: { messageID } });
+ await call("POST", `/api/session/${encoded}/revert/commit`, { body: {} }).catch(() => undefined);
+ }
+ json(res, 200, await sessionInfo(sessionID, directory));
+ return;
+ }
+ case "unrevert": {
+ await call("DELETE", `/api/session/${encoded}/revert`).catch(() => undefined);
+ json(res, 200, await sessionInfo(sessionID, directory));
+ return;
+ }
+ case "fork": {
+ const body = ((await readBody(req)) ?? {}) as JsonRecord;
+ const created = await call("POST", `/api/session/${encoded}/fork`, { body: omitUndefined({ before: str(body, "messageID") }) });
+ json(res, 200, v1Session(created, { version: options.version, directory }));
+ return;
+ }
+ case "todo":
+ json(res, 200, []);
+ return;
+ case "diff":
+ json(res, 200, []);
+ return;
+ case "init":
+ json(res, 200, true);
+ return;
+ case "share":
+ case "unshare":
+ json(res, 200, await sessionInfo(sessionID, directory));
+ return;
+ case "permissions": {
+ // 1.x legacy reply: POST /session/:id/permissions/:permissionID {response}
+ const body = ((await readBody(req)) ?? {}) as JsonRecord;
+ await replyPermission(String(segments[3] ?? ""), String(body.response ?? "once"), undefined, sessionID, directory);
+ json(res, 200, true);
+ return;
+ }
+ default:
+ break;
+ }
+ }
+
+ if (segments[0] === "experimental" && segments[1] === "session" && segments.length === 2 && method === "GET") {
+ json(res, 200, await listSessions(directory, url.searchParams, url.searchParams.get("roots") === "true"));
+ return;
+ }
+
+ if (segments[0] === "permission") {
+ if (segments.length === 1 && method === "GET") {
+ json(res, 200, await pendingPermissions(directory));
+ return;
+ }
+ if (segments[2] === "reply" && method === "POST") {
+ const body = ((await readBody(req)) ?? {}) as JsonRecord;
+ await replyPermission(String(segments[1]), String(body.reply ?? "once"), str(body, "message"), undefined, directory);
+ json(res, 200, true);
+ return;
+ }
+ }
+
+ if (segments[0] === "question") {
+ if (segments.length === 1 && method === "GET") {
+ json(res, 200, await pendingQuestions(directory));
+ return;
+ }
+ const requestID = String(segments[1] ?? "");
+ if ((segments[2] === "reply" || segments[2] === "reject") && method === "POST") {
+ const body = ((await readBody(req)) ?? {}) as JsonRecord;
+ const mapping = await findQuestion(requestID, directory);
+ if (!mapping) return namedError(res, 404, "NotFoundError", `Question ${requestID} not found`);
+ const session = encodeURIComponent(String(mapping.request.sessionID));
+ if (segments[2] === "reject") {
+ await call("DELETE", `/api/session/${session}/form/${encodeURIComponent(requestID)}`);
+ } else {
+ await call("POST", `/api/session/${session}/form/${encodeURIComponent(requestID)}/reply`, {
+ body: { answer: v2FormAnswer(mapping.fields, arr(body, "answers")) },
+ });
+ }
+ json(res, 200, true);
+ return;
+ }
+ }
+
+ // 1.x-era /api routes the renderer and engine pool use.
+ if (segments[0] === "api") {
+ if (segments[1] === "session" && segments[3] === "permission") {
+ const sessionID = String(segments[2]);
+ if (segments.length === 4 && method === "GET") {
+ const payload = await call("GET", `/api/session/${encodeURIComponent(sessionID)}/permission`);
+ const list = unwrap(payload);
+ json(res, 200, (Array.isArray(list) ? list : []).map(v1PermissionV2Request).filter(Boolean));
+ return;
+ }
+ if (segments[5] === "reply" && method === "POST") {
+ const body = ((await readBody(req)) ?? {}) as JsonRecord;
+ await replyPermission(String(segments[4]), String(body.reply ?? body.decision ?? "once"), str(body, "message"), sessionID, directory);
+ json(res, 200, true);
+ return;
+ }
+ }
+ if (segments[1] === "permission" && segments[2] === "request" && method === "GET") {
+ const payload = await call("GET", "/api/permission/request", { directory });
+ const list = unwrap(payload);
+ json(res, 200, (Array.isArray(list) ? list : []).map(v1PermissionV2Request).filter(Boolean));
+ return;
+ }
+ if (segments[1] === "question" && segments[2] === "request" && method === "GET") {
+ json(res, 200, await pendingQuestions(directory));
+ return;
+ }
+ // Anything else under /api is the 2.x contract itself.
+ const body = method === "GET" || method === "HEAD" ? undefined : await readBody(req);
+ try {
+ const query: Record<string, string> = {};
+ url.searchParams.forEach((value, key) => {
+ query[key] = value;
+ });
+ const payload = await call(method, path, { directory: query["location[directory]"] ? undefined : directory, query, body });
+ if (payload === undefined) noContent(res);
+ else json(res, 200, payload);
+ } catch (error) {
+ if (error instanceof UpstreamError) json(res, error.status, error.body ?? null);
+ else throw error;
+ }
+ return;
+ }
+
+ if (method === "GET" && path === "/agent") {
+ const payload = await call("GET", "/api/agent", { directory: dir });
+ const list = unwrap(payload);
+ json(res, 200, (Array.isArray(list) ? list : []).map(v1Agent).filter(Boolean));
+ return;
+ }
+ if (method === "GET" && path === "/command") {
+ const payload = await call("GET", "/api/command", { directory: dir });
+ const list = unwrap(payload);
+ json(res, 200, (Array.isArray(list) ? list : []).map(v1Command).filter(Boolean));
+ return;
+ }
+ if (method === "GET" && path === "/skill") {
+ const payload = await call("GET", "/api/skill", { directory: dir });
+ const list = unwrap(payload);
+ json(res, 200, (Array.isArray(list) ? list : []).filter(isRecord).map((skill) => omitUndefined({
+ name: str(skill, "name") ?? str(skill, "id") ?? "",
+ description: str(skill, "description") ?? "",
+ location: str(skill, "location") ?? str(skill, "path") ?? str(skill, "directory") ?? "",
+ content: str(skill, "content"),
+ })));
+ return;
+ }
+ if (method === "GET" && (path === "/provider" || path === "/config/providers")) {
+ const [providers, models, defaults] = await Promise.all([
+ call("GET", "/api/provider", { directory: dir }),
+ call("GET", "/api/model", { directory: dir }),
+ call("GET", "/api/model/default", { directory: dir }).catch(() => undefined),
+ ]);
+ const def = unwrap(defaults);
+ const defaultMap: Record<string, string> = {};
+ if (isRecord(def) && typeof def.providerID === "string" && typeof def.id === "string") defaultMap[def.providerID] = def.id;
+ const list = v1ProviderList(Array.isArray(unwrap(providers)) ? (unwrap(providers) as unknown[]) : [], Array.isArray(unwrap(models)) ? (unwrap(models) as unknown[]) : [], defaultMap);
+ for (const provider of list.all as JsonRecord[]) {
+ const models = record(provider, "models") ?? {};
+ if (!defaultMap[String(provider.id)]) {
+ const first = Object.keys(models)[0];
+ if (first) defaultMap[String(provider.id)] = first;
+ }
+ }
+ if (path === "/config/providers") json(res, 200, { providers: list.all, default: defaultMap });
+ else json(res, 200, { ...list, default: defaultMap });
+ return;
+ }
+ if (method === "GET" && path === "/provider/auth") {
+ json(res, 200, {});
+ return;
+ }
+ if (segments[0] === "auth" && segments.length === 2) {
+ const providerID = String(segments[1]);
+ if (method === "PUT" || method === "POST") {
+ const body = ((await readBody(req)) ?? {}) as JsonRecord;
+ const key = str(body, "key") ?? str(body, "access");
+ if (key) apiKeys[providerID] = key;
+ await refreshConfig();
+ json(res, 200, true);
+ return;
+ }
+ if (method === "DELETE") {
+ delete apiKeys[providerID];
+ await refreshConfig();
+ json(res, 200, true);
+ return;
+ }
+ }
+ if (method === "GET" && path === "/config") {
+ json(res, 200, v1ConfigCache);
+ return;
+ }
+ if (method === "PATCH" && path === "/config") {
+ namedError(res, 400, "UnsupportedError", "Engine config is managed by OmniRush.ai");
+ return;
+ }
+ if (method === "GET" && path === "/mcp") {
+ json(res, 200, await mcpStatuses(dir));
+ return;
+ }
+ if (segments[0] === "mcp") {
+ if (segments.length === 1 && method === "POST") {
+ const body = ((await readBody(req)) ?? {}) as JsonRecord;
+ const name = str(body, "name");
+ const config = v2Mcp(body.config);
+ if (!name || !config) return namedError(res, 400, "BadRequestError", "name and config are required");
+ await call("PUT", `/api/experimental/mcp/${encodeURIComponent(name)}`, { directory: dir, body: { config } });
+ json(res, 200, await mcpStatuses(dir));
+ return;
+ }
+ const name = String(segments[1] ?? "");
+ const encodedName = encodeURIComponent(name);
+ if ((segments[2] === "connect" || segments[2] === "disconnect") && method === "POST") {
+ await call("POST", `/api/experimental/mcp/${encodedName}/${segments[2]}`, { directory: dir, body: {} });
+ json(res, 200, true);
+ return;
+ }
+ if (segments[2] === "auth") {
+ const integration = await mcpIntegration(name, dir);
+ if (method === "DELETE" && segments.length === 3) {
+ for (const connection of arr(integration, "connections")) {
+ if (str(connection, "type") === "credential" && str(connection, "id")) {
+ await call("DELETE", `/api/credential/${encodeURIComponent(String(str(connection, "id")))}`).catch(() => undefined);
+ }
+ }
+ json(res, 200, { success: true });
+ return;
+ }
+ if (!integration) return namedError(res, 400, "UnsupportedOAuthError", `MCP server ${name} does not support OAuth`);
+ const integrationID = encodeURIComponent(String(str(integration, "id")));
+ const method0 = arr(integration, "methods").find((candidate) => str(candidate, "type") === "oauth");
+ const start = async (): Promise<JsonRecord> => {
+ const attempt = unwrap(await call("POST", `/api/integration/${integrationID}/connect/oauth`, {
+ directory: dir,
+ body: { methodID: str(method0, "id") ?? "oauth" },
+ }));
+ const record0 = isRecord(attempt) ? attempt : {};
+ mcpAttempts.set(`${dir}\u0000${name}`, { integrationID, attemptID: String(str(record0, "attemptID") ?? str(record0, "id") ?? "") });
+ return record0;
+ };
+ if (segments.length === 3 && method === "POST") {
+ const attempt = await start();
+ json(res, 200, { authorizationUrl: str(attempt, "url") ?? "" });
+ return;
+ }
+ if (segments[3] === "callback" && method === "POST") {
+ const body = ((await readBody(req)) ?? {}) as JsonRecord;
+ const pending = mcpAttempts.get(`${dir}\u0000${name}`);
+ if (!pending) return namedError(res, 400, "BadRequestError", "No OAuth attempt is pending for this server");
+ await call("POST", `/api/integration/${pending.integrationID}/connect/oauth/${encodeURIComponent(pending.attemptID)}/complete`, {
+ directory: dir,
+ body: omitUndefined({ code: str(body, "code") }),
+ }).catch(() => undefined);
+ await waitMcpAttempt(pending, dir, 30_000);
+ await call("POST", `/api/experimental/mcp/${encodedName}/connect`, { directory: dir, body: {} }).catch(() => undefined);
+ json(res, 200, (await mcpStatuses(dir))[name] ?? { status: "failed", error: "unknown server" });
+ return;
+ }
+ if (segments[3] === "authenticate" && method === "POST") {
+ const attempt = await start();
+ const url0 = str(attempt, "url");
+ if (url0) openInBrowser(url0);
+ const pending = mcpAttempts.get(`${dir}\u0000${name}`)!;
+ await waitMcpAttempt(pending, dir, 5 * 60_000);
+ await call("POST", `/api/experimental/mcp/${encodedName}/connect`, { directory: dir, body: {} }).catch(() => undefined);
+ json(res, 200, (await mcpStatuses(dir))[name] ?? { status: "failed", error: "unknown server" });
+ return;
+ }
+ }
+ }
+ if (method === "POST" && path === "/omnirush/engine-tools") {
+ // The plugin bridge reports the tools the engine offers (1.x names) for the tool listing routes.
+ const body = ((await readBody(req)) ?? {}) as JsonRecord;
+ const tools = arr(body, "tools").filter(isRecord).map((tool) => ({ id: String(tool.id ?? ""), description: String(tool.description ?? ""), parameters: isRecord(tool.parameters) ? tool.parameters : {} })).filter((tool) => tool.id);
+ engineTools.set(str(body, "directory") ?? dir, tools);
+ json(res, 200, true);
+ return;
+ }
+ if (method === "GET" && path === "/path") {
+ json(res, 200, { home: homedir(), state: options.paths?.state ?? "", config: options.paths?.config ?? "", worktree: dir, directory: dir });
+ return;
+ }
+ if (method === "GET" && (path === "/project/current" || path === "/project")) {
+ const location = unwrap(await call("GET", "/api/location", { directory: dir }).catch(() => undefined));
+ const project = record(location, "project");
+ const info = omitUndefined({
+ id: str(project, "id") ?? "global",
+ worktree: str(project, "canonical") ?? str(project, "worktree") ?? dir,
+ vcs: str(project, "vcs") === "git" ? "git" : undefined,
+ time: { created: num(record(project, "time"), "created") ?? Date.now(), updated: num(record(project, "time"), "updated") ?? Date.now() },
+ sandboxes: [],
+ });
+ json(res, 200, path === "/project" ? [info] : info);
+ return;
+ }
+ if (method === "GET" && path === "/vcs") {
+ const branch = unwrap(await call("GET", "/api/vcs/branch", { directory: dir }).catch(() => undefined));
+ json(res, 200, { branch: typeof branch === "string" ? branch : str(branch, "branch") ?? str(branch, "name") ?? null, default_branch: null });
+ return;
+ }
+ if (method === "GET" && (path === "/lsp" || path === "/formatter" || path === "/file/status")) {
+ json(res, 200, []);
+ return;
+ }
+ if (method === "GET" && path === "/find/file") {
+ const payload = await call("GET", "/api/fs/find", { directory: dir, query: { query: url.searchParams.get("query") ?? "", limit: url.searchParams.get("limit") ?? "50" } });
+ const list = unwrap(payload);
+ json(res, 200, (Array.isArray(list) ? list : []).map((item) => (typeof item === "string" ? item : str(item, "path") ?? str(item, "file") ?? "")).filter(Boolean));
+ return;
+ }
+ if (method === "GET" && path === "/file") {
+ const payload = await call("GET", "/api/fs/list", { directory: dir, query: { path: url.searchParams.get("path") ?? "." } });
+ const list = unwrap(payload);
+ json(res, 200, (Array.isArray(list) ? list : arr(list, "entries")).filter(isRecord).map((entry) => ({
+ name: str(entry, "name") ?? "",
+ path: str(entry, "path") ?? str(entry, "name") ?? "",
+ absolute: str(entry, "absolute") ?? "",
+ type: str(entry, "type") === "directory" ? "directory" : "file",
+ ignored: entry.ignored === true,
+ })));
+ return;
+ }
+ if (method === "GET" && path === "/experimental/tool/ids") {
+ const tools = engineTools.get(dir);
+ json(res, 200, tools ? tools.map((tool) => tool.id) : [...BUILTIN_TOOL_IDS]);
+ return;
+ }
+ if (method === "GET" && path === "/experimental/tool") {
+ json(res, 200, engineTools.get(dir) ?? []);
+ return;
+ }
+ if (method === "POST" && (path === "/instance/dispose" || path === "/global/dispose")) {
+ await refreshConfig();
+ await call("POST", "/api/location/reload", { directory: dir, body: {} }).catch(() => undefined);
+ json(res, 200, true);
+ return;
+ }
+ if (method === "POST" && (path === "/log" || path.startsWith("/tui/"))) {
+ await readBody(req);
+ json(res, 200, true);
+ return;
+ }
+ namedError(res, 404, "NotFoundError", `${method} ${path} is not served by the OmniRush.ai engine adapter`);
+ };
+
+ const server = http.createServer((req, res) => {
+ if ((req.headers.authorization ?? "") !== expectedAuth) {
+ res.writeHead(401, { "www-authenticate": 'Basic realm="opencode"' });
+ res.end();
+ return;
+ }
+ handle(req, res).catch((error: unknown) => {
+ if (res.headersSent) {
+ res.end();
+ return;
+ }
+ if (error instanceof UpstreamError) {
+ const body = error.body;
+ const message = isRecord(body) ? str(body, "message") ?? str(record(body, "data"), "message") ?? JSON.stringify(body) : String(body ?? error.message);
+ const name = isRecord(body) ? str(body, "name") ?? str(body, "_tag") ?? str(body, "code") ?? "EngineError" : "EngineError";
+ json(res, error.status, { name, data: { message } });
+ return;
+ }
+ log("engine adapter request failed", { url: req.url, error: error instanceof Error ? error.message : String(error) });
+ json(res, 500, { name: "UnknownError", data: { message: error instanceof Error ? error.message : String(error) } });
+ });
+ });
+ server.keepAliveTimeout = 65_000;
+
+ await new Promise<void>((resolve, reject) => {
+ server.once("error", reject);
+ server.listen(options.port ?? 0, options.hostname ?? "127.0.0.1", () => resolve());
+ });
+ const address = server.address();
+ if (!address || typeof address !== "object") throw new Error("engine adapter did not bind");
+ const host = options.hostname ?? "127.0.0.1";
+ const url = `http://${host.includes(":") ? `[${host}]` : host}:${address.port}`;
+ await refreshConfig().catch((error) => log("engine config render failed", { error: error instanceof Error ? error.message : String(error) }));
+ ensureStream();
+
+ return {
+ url,
+ refreshConfig,
+ close: async () => {
+ streamController.abort();
+ for (const subscriber of subscribers) subscribers.delete(subscriber);
+ const closed = new Promise<void>((resolve) => server.close(() => resolve()));
+ server.closeAllConnections?.();
+ await closed;
+ },
+ };
+}
diff --git a/apps/server/src/engine2/fixtures/v1-nest.json b/apps/server/src/engine2/fixtures/v1-nest.json
new file mode 100644
index 00000000..142988f0
--- /dev/null
+++ b/apps/server/src/engine2/fixtures/v1-nest.json
@@ -0,0 +1,692 @@
+{
+ "session": {
+ "id": "ses_f1f13cbbdffe1XNHL5h8tqoTRe",
+ "slug": "sunny-wizard",
+ "projectID": "global",
+ "directory": "/work/proj",
+ "path": "work/proj",
+ "summary": {
+ "additions": 0,
+ "deletions": 0,
+ "files": 0
+ },
+ "cost": 0,
+ "tokens": {
+ "input": 447,
+ "output": 80,
+ "reasoning": 0,
+ "cache": {
+ "read": 2000,
+ "write": 0
+ }
+ },
+ "title": "Parity session title",
+ "agent": "build",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock",
+ "variant": "default"
+ },
+ "version": "1.18.32",
+ "time": {
+ "created": 1790479971394,
+ "updated": 1790479973398
+ }
+ },
+ "messages": [
+ {
+ "info": {
+ "id": "msg_0e0ec3462001HRzYTUY6Ug2hJL",
+ "sessionID": "ses_f1f13cbbdffe1XNHL5h8tqoTRe",
+ "role": "user",
+ "time": {
+ "created": 1790479971426
+ },
+ "summary": {
+ "diffs": []
+ },
+ "agent": "build",
+ "model": {
+ "providerID": "mock",
+ "modelID": "mock-model"
+ }
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ec346b00155NRtrVvRDoEzB",
+ "sessionID": "ses_f1f13cbbdffe1XNHL5h8tqoTRe",
+ "messageID": "msg_0e0ec3462001HRzYTUY6Ug2hJL",
+ "type": "text",
+ "text": "PARITY-NEST go deep"
+ }
+ ]
+ },
+ {
+ "info": {
+ "id": "msg_0e0ec348c001IqeTNkU4s5lqZJ",
+ "sessionID": "ses_f1f13cbbdffe1XNHL5h8tqoTRe",
+ "role": "assistant",
+ "time": {
+ "created": 1790479971468,
+ "completed": 1790479973207
+ },
+ "parentID": "msg_0e0ec3462001HRzYTUY6Ug2hJL",
+ "modelID": "mock-model",
+ "providerID": "mock",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/work/proj",
+ "root": "/"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 1261,
+ "input": 221,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ },
+ "finish": "tool-calls"
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ec361b0016er6leUCL1QdgW",
+ "sessionID": "ses_f1f13cbbdffe1XNHL5h8tqoTRe",
+ "messageID": "msg_0e0ec348c001IqeTNkU4s5lqZJ",
+ "type": "step-start"
+ },
+ {
+ "id": "prt_0e0ec3626001u8uyyFG52DMl0v",
+ "sessionID": "ses_f1f13cbbdffe1XNHL5h8tqoTRe",
+ "messageID": "msg_0e0ec348c001IqeTNkU4s5lqZJ",
+ "type": "tool",
+ "callID": "call_21_0",
+ "tool": "task",
+ "state": {
+ "status": "completed",
+ "input": {
+ "subagent_type": "general",
+ "description": "Nested level one",
+ "prompt": "CHILD-N1: delegate once more"
+ },
+ "output": "<task id=\"ses_f1f13c9c7ffeErSXxQ26Uvsr6O\" state=\"completed\">\n<task_result>\nLevel one done.\n</task_result>\n</task>",
+ "title": "Nested level one",
+ "metadata": {
+ "parentSessionId": "ses_f1f13cbbdffe1XNHL5h8tqoTRe",
+ "sessionId": "ses_f1f13c9c7ffeErSXxQ26Uvsr6O",
+ "model": {
+ "modelID": "mock-model",
+ "providerID": "mock"
+ },
+ "truncated": false
+ },
+ "time": {
+ "start": 1790479971907,
+ "end": 1790479973189
+ }
+ }
+ },
+ {
+ "id": "prt_0e0ec3b4a001uplnLmFO7BG4zf",
+ "sessionID": "ses_f1f13cbbdffe1XNHL5h8tqoTRe",
+ "messageID": "msg_0e0ec348c001IqeTNkU4s5lqZJ",
+ "type": "step-finish",
+ "reason": "tool-calls",
+ "cost": 0,
+ "tokens": {
+ "total": 1261,
+ "input": 221,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ }
+ ]
+ },
+ {
+ "info": {
+ "id": "msg_0e0ec3b5d00101DqRqkRe3SpHh",
+ "sessionID": "ses_f1f13cbbdffe1XNHL5h8tqoTRe",
+ "role": "assistant",
+ "time": {
+ "created": 1790479973213,
+ "completed": 1790479973390
+ },
+ "parentID": "msg_0e0ec3462001HRzYTUY6Ug2hJL",
+ "modelID": "mock-model",
+ "providerID": "mock",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/work/proj",
+ "root": "/"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 1266,
+ "input": 226,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ },
+ "finish": "stop"
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ec3b8a001y9B38jRbMkN8ae",
+ "sessionID": "ses_f1f13cbbdffe1XNHL5h8tqoTRe",
+ "messageID": "msg_0e0ec3b5d00101DqRqkRe3SpHh",
+ "type": "step-start"
+ },
+ {
+ "id": "prt_0e0ec3b8e001GpcJ90wfA3ynlh",
+ "sessionID": "ses_f1f13cbbdffe1XNHL5h8tqoTRe",
+ "messageID": "msg_0e0ec3b5d00101DqRqkRe3SpHh",
+ "type": "text",
+ "text": "Nested run finished.",
+ "time": {
+ "start": 1790479973262,
+ "end": 1790479973376
+ }
+ },
+ {
+ "id": "prt_0e0ec3c06001j6DGqnl4FzZ948",
+ "sessionID": "ses_f1f13cbbdffe1XNHL5h8tqoTRe",
+ "messageID": "msg_0e0ec3b5d00101DqRqkRe3SpHh",
+ "type": "step-finish",
+ "reason": "stop",
+ "cost": 0,
+ "tokens": {
+ "total": 1266,
+ "input": 226,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ }
+ ]
+ }
+ ],
+ "children": [
+ {
+ "session": {
+ "id": "ses_f1f13c9c7ffeErSXxQ26Uvsr6O",
+ "slug": "tidy-wolf",
+ "projectID": "global",
+ "directory": "/work/proj",
+ "path": "work/proj",
+ "parentID": "ses_f1f13cbbdffe1XNHL5h8tqoTRe",
+ "summary": {
+ "additions": 0,
+ "deletions": 0,
+ "files": 0
+ },
+ "cost": 0,
+ "tokens": {
+ "input": 447,
+ "output": 80,
+ "reasoning": 0,
+ "cache": {
+ "read": 2000,
+ "write": 0
+ }
+ },
+ "title": "Nested level one (@general subagent)",
+ "agent": "general",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock",
+ "variant": "default"
+ },
+ "version": "1.18.32",
+ "time": {
+ "created": 1790479971896,
+ "updated": 1790479973223
+ },
+ "permission": []
+ },
+ "messages": [
+ {
+ "info": {
+ "id": "msg_0e0ec364e001Qy2gQweXYBXKi0",
+ "sessionID": "ses_f1f13c9c7ffeErSXxQ26Uvsr6O",
+ "role": "user",
+ "time": {
+ "created": 1790479971921
+ },
+ "summary": {
+ "diffs": []
+ },
+ "agent": "general",
+ "model": {
+ "providerID": "mock",
+ "modelID": "mock-model"
+ }
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ec365c001USjXeDrZg4z7b9",
+ "sessionID": "ses_f1f13c9c7ffeErSXxQ26Uvsr6O",
+ "messageID": "msg_0e0ec364e001Qy2gQweXYBXKi0",
+ "type": "text",
+ "text": "CHILD-N1: delegate once more"
+ }
+ ]
+ },
+ {
+ "info": {
+ "id": "msg_0e0ec3684001dL34qllcV1WR30",
+ "sessionID": "ses_f1f13c9c7ffeErSXxQ26Uvsr6O",
+ "role": "assistant",
+ "time": {
+ "created": 1790479971972,
+ "completed": 1790479972898
+ },
+ "parentID": "msg_0e0ec364e001Qy2gQweXYBXKi0",
+ "modelID": "mock-model",
+ "providerID": "mock",
+ "mode": "general",
+ "agent": "general",
+ "path": {
+ "cwd": "/work/proj",
+ "root": "/"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 1262,
+ "input": 222,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ },
+ "finish": "tool-calls"
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ec3735001mncaPAtcjMJzTo",
+ "sessionID": "ses_f1f13c9c7ffeErSXxQ26Uvsr6O",
+ "messageID": "msg_0e0ec3684001dL34qllcV1WR30",
+ "type": "step-start"
+ },
+ {
+ "id": "prt_0e0ec373f001DnLpSqR0XslJ50",
+ "sessionID": "ses_f1f13c9c7ffeErSXxQ26Uvsr6O",
+ "messageID": "msg_0e0ec3684001dL34qllcV1WR30",
+ "type": "tool",
+ "callID": "call_22_0",
+ "tool": "task",
+ "state": {
+ "status": "completed",
+ "input": {
+ "subagent_type": "general",
+ "description": "Nested level two",
+ "prompt": "CHILD-A: read notes.md and summarise it"
+ },
+ "output": "<task id=\"ses_f1f13c8adffe0RmAt7VUPtZZjk\" state=\"completed\">\n<task_result>\nnotes.md has a heading and two lines.\n</task_result>\n</task>",
+ "title": "Nested level two",
+ "metadata": {
+ "parentSessionId": "ses_f1f13c9c7ffeErSXxQ26Uvsr6O",
+ "sessionId": "ses_f1f13c8adffe0RmAt7VUPtZZjk",
+ "model": {
+ "modelID": "mock-model",
+ "providerID": "mock"
+ },
+ "truncated": false
+ },
+ "time": {
+ "start": 1790479972187,
+ "end": 1790479972886
+ }
+ }
+ },
+ {
+ "id": "prt_0e0ec3a1b001RosCgLC7c662zf",
+ "sessionID": "ses_f1f13c9c7ffeErSXxQ26Uvsr6O",
+ "messageID": "msg_0e0ec3684001dL34qllcV1WR30",
+ "type": "step-finish",
+ "reason": "tool-calls",
+ "cost": 0,
+ "tokens": {
+ "total": 1262,
+ "input": 222,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ }
+ ]
+ },
+ {
+ "info": {
+ "id": "msg_0e0ec3a27001WwtZkrp4HKcuyu",
+ "sessionID": "ses_f1f13c9c7ffeErSXxQ26Uvsr6O",
+ "role": "assistant",
+ "time": {
+ "created": 1790479972903,
+ "completed": 1790479973178
+ },
+ "parentID": "msg_0e0ec364e001Qy2gQweXYBXKi0",
+ "modelID": "mock-model",
+ "providerID": "mock",
+ "mode": "general",
+ "agent": "general",
+ "path": {
+ "cwd": "/work/proj",
+ "root": "/"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 1265,
+ "input": 225,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ },
+ "finish": "stop"
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ec3adb001pnNL6KMNqiSA0S",
+ "sessionID": "ses_f1f13c9c7ffeErSXxQ26Uvsr6O",
+ "messageID": "msg_0e0ec3a27001WwtZkrp4HKcuyu",
+ "type": "step-start"
+ },
+ {
+ "id": "prt_0e0ec3ae0001pVv8h803QqMswS",
+ "sessionID": "ses_f1f13c9c7ffeErSXxQ26Uvsr6O",
+ "messageID": "msg_0e0ec3a27001WwtZkrp4HKcuyu",
+ "type": "text",
+ "text": "Level one done.",
+ "time": {
+ "start": 1790479973088,
+ "end": 1790479973167
+ }
+ },
+ {
+ "id": "prt_0e0ec3b330017GrJ2q4tybJrSC",
+ "sessionID": "ses_f1f13c9c7ffeErSXxQ26Uvsr6O",
+ "messageID": "msg_0e0ec3a27001WwtZkrp4HKcuyu",
+ "type": "step-finish",
+ "reason": "stop",
+ "cost": 0,
+ "tokens": {
+ "total": 1265,
+ "input": 225,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ }
+ ]
+ }
+ ],
+ "children": [
+ {
+ "session": {
+ "id": "ses_f1f13c8adffe0RmAt7VUPtZZjk",
+ "slug": "jolly-pixel",
+ "projectID": "global",
+ "directory": "/work/proj",
+ "path": "work/proj",
+ "parentID": "ses_f1f13c9c7ffeErSXxQ26Uvsr6O",
+ "summary": {
+ "additions": 0,
+ "deletions": 0,
+ "files": 0
+ },
+ "cost": 0,
+ "tokens": {
+ "input": 447,
+ "output": 68,
+ "reasoning": 12,
+ "cache": {
+ "read": 2000,
+ "write": 0
+ }
+ },
+ "title": "Nested level two (@general subagent)",
+ "agent": "general",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock",
+ "variant": "default"
+ },
+ "version": "1.18.32",
+ "time": {
+ "created": 1790479972178,
+ "updated": 1790479972911
+ },
+ "permission": []
+ },
+ "messages": [
+ {
+ "info": {
+ "id": "msg_0e0ec3764001fbCj63CXyrAmw3",
+ "sessionID": "ses_f1f13c8adffe0RmAt7VUPtZZjk",
+ "role": "user",
+ "time": {
+ "created": 1790479972197
+ },
+ "summary": {
+ "diffs": []
+ },
+ "agent": "general",
+ "model": {
+ "providerID": "mock",
+ "modelID": "mock-model"
+ }
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ec3770001gzRxgoBpC9WLDg",
+ "sessionID": "ses_f1f13c8adffe0RmAt7VUPtZZjk",
+ "messageID": "msg_0e0ec3764001fbCj63CXyrAmw3",
+ "type": "text",
+ "text": "CHILD-A: read notes.md and summarise it"
+ }
+ ]
+ },
+ {
+ "info": {
+ "id": "msg_0e0ec3793001IQrOngidHiUc2l",
+ "sessionID": "ses_f1f13c8adffe0RmAt7VUPtZZjk",
+ "role": "assistant",
+ "time": {
+ "created": 1790479972243,
+ "completed": 1790479972683
+ },
+ "parentID": "msg_0e0ec3764001fbCj63CXyrAmw3",
+ "modelID": "mock-model",
+ "providerID": "mock",
+ "mode": "general",
+ "agent": "general",
+ "path": {
+ "cwd": "/work/proj",
+ "root": "/"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 1263,
+ "input": 223,
+ "output": 28,
+ "reasoning": 12,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ },
+ "finish": "tool-calls"
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ec3862001i2IRhssBnMmQb7",
+ "sessionID": "ses_f1f13c8adffe0RmAt7VUPtZZjk",
+ "messageID": "msg_0e0ec3793001IQrOngidHiUc2l",
+ "type": "step-start"
+ },
+ {
+ "id": "prt_0e0ec3869001z1C4Oyj9tl2qlr",
+ "sessionID": "ses_f1f13c8adffe0RmAt7VUPtZZjk",
+ "messageID": "msg_0e0ec3793001IQrOngidHiUc2l",
+ "type": "reasoning",
+ "text": "Read the file.",
+ "time": {
+ "start": 1790479972457,
+ "end": 1790479972483
+ }
+ },
+ {
+ "id": "prt_0e0ec389f001LRMG2jPQnI16nu",
+ "sessionID": "ses_f1f13c8adffe0RmAt7VUPtZZjk",
+ "messageID": "msg_0e0ec3793001IQrOngidHiUc2l",
+ "type": "tool",
+ "callID": "call_23_0",
+ "tool": "read",
+ "state": {
+ "status": "completed",
+ "input": {
+ "filePath": "/work/proj/notes.md"
+ },
+ "output": "<path>/work/proj/notes.md</path>\n<type>file</type>\n<content>\n1: # Notes\n2: line one\n3: line two\n\n(End of file - total 3 lines)\n</content>",
+ "title": "work/proj/notes.md",
+ "metadata": {
+ "preview": "# Notes\nline one\nline two",
+ "truncated": false,
+ "loaded": [],
+ "display": {
+ "type": "file",
+ "path": "/work/proj/notes.md",
+ "text": "# Notes\nline one\nline two",
+ "lineStart": 1,
+ "lineEnd": 3,
+ "totalLines": 3,
+ "truncated": false
+ }
+ },
+ "time": {
+ "start": 1790479972518,
+ "end": 1790479972670
+ }
+ }
+ },
+ {
+ "id": "prt_0e0ec3943001fGw9oK0i6wgcbo",
+ "sessionID": "ses_f1f13c8adffe0RmAt7VUPtZZjk",
+ "messageID": "msg_0e0ec3793001IQrOngidHiUc2l",
+ "type": "step-finish",
+ "reason": "tool-calls",
+ "cost": 0,
+ "tokens": {
+ "total": 1263,
+ "input": 223,
+ "output": 28,
+ "reasoning": 12,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ }
+ ]
+ },
+ {
+ "info": {
+ "id": "msg_0e0ec3950001Ozf0Q2sHHIc7IE",
+ "sessionID": "ses_f1f13c8adffe0RmAt7VUPtZZjk",
+ "role": "assistant",
+ "time": {
+ "created": 1790479972688,
+ "completed": 1790479972877
+ },
+ "parentID": "msg_0e0ec3764001fbCj63CXyrAmw3",
+ "modelID": "mock-model",
+ "providerID": "mock",
+ "mode": "general",
+ "agent": "general",
+ "path": {
+ "cwd": "/work/proj",
+ "root": "/"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 1264,
+ "input": 224,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ },
+ "finish": "stop"
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ec3975001ZN4dbRvNN9Y9lq",
+ "sessionID": "ses_f1f13c8adffe0RmAt7VUPtZZjk",
+ "messageID": "msg_0e0ec3950001Ozf0Q2sHHIc7IE",
+ "type": "step-start"
+ },
+ {
+ "id": "prt_0e0ec3982001G0r03p0qPKRgUJ",
+ "sessionID": "ses_f1f13c8adffe0RmAt7VUPtZZjk",
+ "messageID": "msg_0e0ec3950001Ozf0Q2sHHIc7IE",
+ "type": "text",
+ "text": "notes.md has a heading and two lines.",
+ "time": {
+ "start": 1790479972738,
+ "end": 1790479972862
+ }
+ },
+ {
+ "id": "prt_0e0ec3a04001A4ipciCfI98sON",
+ "sessionID": "ses_f1f13c8adffe0RmAt7VUPtZZjk",
+ "messageID": "msg_0e0ec3950001Ozf0Q2sHHIc7IE",
+ "type": "step-finish",
+ "reason": "stop",
+ "cost": 0,
+ "tokens": {
+ "total": 1264,
+ "input": 224,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ }
+ ]
+ }
+ ],
+ "children": []
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/apps/server/src/engine2/fixtures/v1-p1.json b/apps/server/src/engine2/fixtures/v1-p1.json
new file mode 100644
index 00000000..0c064807
--- /dev/null
+++ b/apps/server/src/engine2/fixtures/v1-p1.json
@@ -0,0 +1,439 @@
+{
+ "session": {
+ "id": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "slug": "quiet-knight",
+ "projectID": "global",
+ "directory": "/work/proj",
+ "path": "work/proj",
+ "summary": {
+ "additions": 0,
+ "deletions": 0,
+ "files": 0
+ },
+ "cost": 0,
+ "tokens": {
+ "input": 814,
+ "output": 112,
+ "reasoning": 48,
+ "cache": {
+ "read": 4000,
+ "write": 0
+ }
+ },
+ "title": "Parity session title",
+ "agent": "build",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock",
+ "variant": "default"
+ },
+ "version": "1.18.32",
+ "time": {
+ "created": 1790479938644,
+ "updated": 1790479944244
+ }
+ },
+ "messages": [
+ {
+ "info": {
+ "id": "msg_0e0ebb53a001LoATfrQaSVl3rn",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "role": "user",
+ "time": {
+ "created": 1790479938874
+ },
+ "summary": {
+ "diffs": []
+ },
+ "agent": "build",
+ "model": {
+ "providerID": "mock",
+ "modelID": "mock-model"
+ }
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ebb54a001YpFYJvFJxapVjE",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "messageID": "msg_0e0ebb53a001LoATfrQaSVl3rn",
+ "type": "text",
+ "text": "PARITY-1 create the notes file"
+ }
+ ]
+ },
+ {
+ "info": {
+ "id": "msg_0e0ebbc0f001yC2Cl6WtUyOEal",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "role": "assistant",
+ "time": {
+ "created": 1790479940623,
+ "completed": 1790479942962
+ },
+ "parentID": "msg_0e0ebb53a001LoATfrQaSVl3rn",
+ "modelID": "mock-model",
+ "providerID": "mock",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/work/proj",
+ "root": "/"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 1242,
+ "input": 202,
+ "output": 28,
+ "reasoning": 12,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ },
+ "finish": "tool-calls"
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ebc372001cUbwSg2P48RX2B",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "messageID": "msg_0e0ebbc0f001yC2Cl6WtUyOEal",
+ "type": "step-start"
+ },
+ {
+ "id": "prt_0e0ebc37a0013XPk6oXnw6dPhl",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "messageID": "msg_0e0ebbc0f001yC2Cl6WtUyOEal",
+ "type": "reasoning",
+ "text": "Look at the folder first.",
+ "time": {
+ "start": 1790479942522,
+ "end": 1790479942537
+ }
+ },
+ {
+ "id": "prt_0e0ebc390001VTrtoKihCp9gMg",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "messageID": "msg_0e0ebbc0f001yC2Cl6WtUyOEal",
+ "type": "tool",
+ "callID": "call_2_0",
+ "tool": "bash",
+ "state": {
+ "status": "completed",
+ "input": {
+ "command": "ls -a",
+ "description": "List files"
+ },
+ "output": ".\n..\n",
+ "title": "ls -a",
+ "metadata": {
+ "output": ".\n..\n",
+ "exit": 0,
+ "truncated": false
+ },
+ "time": {
+ "start": 1790479942569,
+ "end": 1790479942934
+ }
+ }
+ },
+ {
+ "id": "prt_0e0ebc522001Ie1TeJjnjM6SdI",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "messageID": "msg_0e0ebbc0f001yC2Cl6WtUyOEal",
+ "type": "step-finish",
+ "reason": "tool-calls",
+ "cost": 0,
+ "tokens": {
+ "total": 1242,
+ "input": 202,
+ "output": 28,
+ "reasoning": 12,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ }
+ ]
+ },
+ {
+ "info": {
+ "id": "msg_0e0ebc53b001so6QqwTJSJk52P",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "role": "assistant",
+ "time": {
+ "created": 1790479942971,
+ "completed": 1790479943374
+ },
+ "parentID": "msg_0e0ebb53a001LoATfrQaSVl3rn",
+ "modelID": "mock-model",
+ "providerID": "mock",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/work/proj",
+ "root": "/"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 1243,
+ "input": 203,
+ "output": 28,
+ "reasoning": 12,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ },
+ "finish": "tool-calls"
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ebc66b001i5XM3if1bJWXes",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "messageID": "msg_0e0ebc53b001so6QqwTJSJk52P",
+ "type": "step-start"
+ },
+ {
+ "id": "prt_0e0ebc671001yMDPuvdK3gMUm1",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "messageID": "msg_0e0ebc53b001so6QqwTJSJk52P",
+ "type": "reasoning",
+ "text": "Write the notes file.",
+ "time": {
+ "start": 1790479943281,
+ "end": 1790479943293
+ }
+ },
+ {
+ "id": "prt_0e0ebc684001egWT6EpNh7i7fI",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "messageID": "msg_0e0ebc53b001so6QqwTJSJk52P",
+ "type": "tool",
+ "callID": "call_3_0",
+ "tool": "write",
+ "state": {
+ "status": "completed",
+ "input": {
+ "filePath": "/work/proj/notes.md",
+ "content": "# Notes\nline one\n"
+ },
+ "output": "Wrote file successfully.",
+ "title": "work/proj/notes.md",
+ "metadata": {
+ "diagnostics": {},
+ "filepath": "/work/proj/notes.md",
+ "exists": false,
+ "truncated": false
+ },
+ "time": {
+ "start": 1790479943315,
+ "end": 1790479943357
+ }
+ }
+ },
+ {
+ "id": "prt_0e0ebc6c4001KViDcNvyw2W9j6",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "messageID": "msg_0e0ebc53b001so6QqwTJSJk52P",
+ "type": "step-finish",
+ "reason": "tool-calls",
+ "cost": 0,
+ "tokens": {
+ "total": 1243,
+ "input": 203,
+ "output": 28,
+ "reasoning": 12,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ }
+ ]
+ },
+ {
+ "info": {
+ "id": "msg_0e0ebc6d4001q6pEbUo9XsHtNg",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "role": "assistant",
+ "time": {
+ "created": 1790479943380,
+ "completed": 1790479943747
+ },
+ "parentID": "msg_0e0ebb53a001LoATfrQaSVl3rn",
+ "modelID": "mock-model",
+ "providerID": "mock",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/work/proj",
+ "root": "/"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 1244,
+ "input": 204,
+ "output": 28,
+ "reasoning": 12,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ },
+ "finish": "tool-calls"
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ebc7da001p5M0sJ3CWq2KYW",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "messageID": "msg_0e0ebc6d4001q6pEbUo9XsHtNg",
+ "type": "step-start"
+ },
+ {
+ "id": "prt_0e0ebc7df001l3wohHsFLAaEtI",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "messageID": "msg_0e0ebc6d4001q6pEbUo9XsHtNg",
+ "type": "reasoning",
+ "text": "Append a line.",
+ "time": {
+ "start": 1790479943647,
+ "end": 1790479943656
+ }
+ },
+ {
+ "id": "prt_0e0ebc7ee001WbTtgW9x5vtggc",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "messageID": "msg_0e0ebc6d4001q6pEbUo9XsHtNg",
+ "type": "tool",
+ "callID": "call_4_0",
+ "tool": "edit",
+ "state": {
+ "status": "completed",
+ "input": {
+ "filePath": "/work/proj/notes.md",
+ "oldString": "line one",
+ "newString": "line one\nline two"
+ },
+ "output": "Edit applied successfully.",
+ "title": "work/proj/notes.md",
+ "metadata": {
+ "diagnostics": {},
+ "diff": "Index: /work/proj/notes.md\n===================================================================\n--- /work/proj/notes.md\n+++ /work/proj/notes.md\n@@ -1,2 +1,3 @@\n # Notes\n line one\n+line two\n",
+ "filediff": {
+ "file": "/work/proj/notes.md",
+ "patch": "Index: /work/proj/notes.md\n===================================================================\n--- /work/proj/notes.md\n+++ /work/proj/notes.md\n@@ -1,2 +1,3 @@\n # Notes\n line one\n+line two\n",
+ "additions": 1,
+ "deletions": 0
+ },
+ "truncated": false
+ },
+ "time": {
+ "start": 1790479943680,
+ "end": 1790479943734
+ }
+ }
+ },
+ {
+ "id": "prt_0e0ebc83a001Luo8MZH10dXtHz",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "messageID": "msg_0e0ebc6d4001q6pEbUo9XsHtNg",
+ "type": "step-finish",
+ "reason": "tool-calls",
+ "cost": 0,
+ "tokens": {
+ "total": 1244,
+ "input": 204,
+ "output": 28,
+ "reasoning": 12,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ }
+ ]
+ },
+ {
+ "info": {
+ "id": "msg_0e0ebc849001Ic7k9PE7iv4sH4",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "role": "assistant",
+ "time": {
+ "created": 1790479943753,
+ "completed": 1790479944232
+ },
+ "parentID": "msg_0e0ebb53a001LoATfrQaSVl3rn",
+ "modelID": "mock-model",
+ "providerID": "mock",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/work/proj",
+ "root": "/"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 1245,
+ "input": 205,
+ "output": 28,
+ "reasoning": 12,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ },
+ "finish": "stop"
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ebc998001nFnQcTfgvmHHbw",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "messageID": "msg_0e0ebc849001Ic7k9PE7iv4sH4",
+ "type": "step-start"
+ },
+ {
+ "id": "prt_0e0ebc99c0014AL3AVpvMVmT1N",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "messageID": "msg_0e0ebc849001Ic7k9PE7iv4sH4",
+ "type": "reasoning",
+ "text": "Done; report.",
+ "time": {
+ "start": 1790479944092,
+ "end": 1790479944131
+ }
+ },
+ {
+ "id": "prt_0e0ebc9c9001l8BOUbvIBWMPQC",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "messageID": "msg_0e0ebc849001Ic7k9PE7iv4sH4",
+ "type": "text",
+ "text": "Created notes.md with two lines.",
+ "time": {
+ "start": 1790479944137,
+ "end": 1790479944218
+ }
+ },
+ {
+ "id": "prt_0e0ebca20001b0bGK8kJj8MrJN",
+ "sessionID": "ses_f1f144bacffeKNpHh3A6rwkwyw",
+ "messageID": "msg_0e0ebc849001Ic7k9PE7iv4sH4",
+ "type": "step-finish",
+ "reason": "stop",
+ "cost": 0,
+ "tokens": {
+ "total": 1245,
+ "input": 205,
+ "output": 28,
+ "reasoning": 12,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ }
+ ]
+ }
+ ],
+ "children": []
+}
\ No newline at end of file
diff --git a/apps/server/src/engine2/fixtures/v1-sub-events.json b/apps/server/src/engine2/fixtures/v1-sub-events.json
new file mode 100644
index 00000000..fde7acae
--- /dev/null
+++ b/apps/server/src/engine2/fixtures/v1-sub-events.json
@@ -0,0 +1,3132 @@
+[
+{
+"id": "evt_0e0ec076c001aNQpJc3f8r6D6H",
+"type": "server.connected",
+"properties": {}
+},
+{
+"id": "evt_0e0ec0970001UApGwFSdNf4hhs",
+"type": "session.created",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"info": {
+"id": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"slug": "silent-tiger",
+"version": "1.18.32",
+"projectID": "global",
+"directory": "/work/proj",
+"path": "work/proj",
+"title": "New session - 2026-09-27T03:32:40.431Z",
+"cost": 0,
+"tokens": {
+"input": 0,
+"output": 0,
+"reasoning": 0,
+"cache": {
+"read": 0,
+"write": 0
+}
+},
+"time": {
+"created": 1790479960432,
+"updated": 1790479960432
+}
+}
+}
+},
+{
+"id": "evt_0e0ec09a3001BjUZGngCG5Oecc",
+"type": "session.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"info": {
+"id": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"slug": "silent-tiger",
+"projectID": "global",
+"directory": "/work/proj",
+"path": "work/proj",
+"title": "New session - 2026-09-27T03:32:40.431Z",
+"agent": "build",
+"model": {
+"id": "mock-model",
+"providerID": "mock",
+"variant": "default"
+},
+"version": "1.18.32",
+"cost": 0,
+"tokens": {
+"input": 0,
+"output": 0,
+"reasoning": 0,
+"cache": {
+"read": 0,
+"write": 0
+}
+},
+"time": {
+"created": 1790479960432,
+"updated": 1790479960481
+}
+}
+}
+},
+{
+"id": "evt_0e0ec09a8001LX7AOC6ORkMuXL",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"info": {
+"id": "msg_0e0ec09a1001iv9xZgwHwbEu1b",
+"role": "user",
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"time": {
+"created": 1790479960481
+},
+"agent": "build",
+"model": {
+"providerID": "mock",
+"modelID": "mock-model"
+}
+}
+}
+},
+{
+"id": "evt_0e0ec09ac001sfWyrh0oR7UcKN",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"part": {
+"type": "text",
+"text": "PARITY-SUB use two helpers",
+"messageID": "msg_0e0ec09a1001iv9xZgwHwbEu1b",
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"id": "prt_0e0ec09a7001tLLL8l7H5kzeFl"
+},
+"time": 1790479960492
+}
+},
+{
+"id": "evt_0e0ec09b0001EoLO0lqaVH7DFX",
+"type": "session.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"info": {
+"id": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"slug": "silent-tiger",
+"projectID": "global",
+"directory": "/work/proj",
+"path": "work/proj",
+"title": "New session - 2026-09-27T03:32:40.431Z",
+"agent": "build",
+"model": {
+"id": "mock-model",
+"providerID": "mock",
+"variant": "default"
+},
+"version": "1.18.32",
+"cost": 0,
+"tokens": {
+"input": 0,
+"output": 0,
+"reasoning": 0,
+"cache": {
+"read": 0,
+"write": 0
+}
+},
+"time": {
+"created": 1790479960432,
+"updated": 1790479960495
+}
+}
+}
+},
+{
+"id": "evt_0e0ec09b9001gzVVrieXLP8bEk",
+"type": "session.status",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"status": {
+"type": "busy"
+}
+}
+},
+{
+"id": "evt_0e0ec09bd001aTc9yeLtLRkE3w",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"info": {
+"id": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq",
+"parentID": "msg_0e0ec09a1001iv9xZgwHwbEu1b",
+"role": "assistant",
+"mode": "build",
+"agent": "build",
+"path": {
+"cwd": "/work/proj",
+"root": "/"
+},
+"cost": 0,
+"tokens": {
+"input": 0,
+"output": 0,
+"reasoning": 0,
+"cache": {
+"read": 0,
+"write": 0
+}
+},
+"modelID": "mock-model",
+"providerID": "mock",
+"time": {
+"created": 1790479960508
+},
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7"
+}
+}
+},
+{
+"id": "evt_0e0ec09e1001DTT2IC3iV5IMUP",
+"type": "session.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"info": {
+"id": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"slug": "silent-tiger",
+"projectID": "global",
+"directory": "/work/proj",
+"path": "work/proj",
+"title": "New session - 2026-09-27T03:32:40.431Z",
+"agent": "build",
+"model": {
+"id": "mock-model",
+"providerID": "mock",
+"variant": "default"
+},
+"version": "1.18.32",
+"summary": {
+"additions": 0,
+"deletions": 0,
+"files": 0
+},
+"cost": 0,
+"tokens": {
+"input": 0,
+"output": 0,
+"reasoning": 0,
+"cache": {
+"read": 0,
+"write": 0
+}
+},
+"time": {
+"created": 1790479960432,
+"updated": 1790479960544
+}
+}
+}
+},
+{
+"id": "evt_0e0ec09e900154euDDHN0G44HD",
+"type": "session.diff",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"diff": []
+}
+},
+{
+"id": "evt_0e0ec09ec00142yGgHTHxIw8aJ",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"info": {
+"role": "user",
+"time": {
+"created": 1790479960481
+},
+"agent": "build",
+"model": {
+"providerID": "mock",
+"modelID": "mock-model"
+},
+"id": "msg_0e0ec09a1001iv9xZgwHwbEu1b",
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"summary": {
+"diffs": []
+}
+}
+}
+},
+{
+"id": "evt_0e0ec0a8c001nz0hDaXkmr5mbj",
+"type": "session.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"info": {
+"id": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"slug": "silent-tiger",
+"projectID": "global",
+"directory": "/work/proj",
+"path": "work/proj",
+"title": "Parity session title",
+"agent": "build",
+"model": {
+"id": "mock-model",
+"providerID": "mock",
+"variant": "default"
+},
+"version": "1.18.32",
+"summary": {
+"additions": 0,
+"deletions": 0,
+"files": 0
+},
+"cost": 0,
+"tokens": {
+"input": 0,
+"output": 0,
+"reasoning": 0,
+"cache": {
+"read": 0,
+"write": 0
+}
+},
+"time": {
+"created": 1790479960432,
+"updated": 1790479960544
+}
+}
+}
+},
+{
+"id": "evt_0e0ec0ad0001kAlZ76sb9Q7ntr",
+"type": "session.status",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"status": {
+"type": "busy"
+}
+}
+},
+{
+"id": "evt_0e0ec0b0b001SIluxdyfhfogKD",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"part": {
+"id": "prt_0e0ec0b0a001YWUbJz6re4JIvr",
+"messageID": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq",
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"type": "step-start"
+},
+"time": 1790479960843
+}
+},
+{
+"id": "evt_0e0ec0b0f00123BOGSWQ344cM6",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"part": {
+"id": "prt_0e0ec0b0f001Tz5Gj0FzNlJbn3",
+"messageID": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq",
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"type": "reasoning",
+"text": "",
+"time": {
+"start": 1790479960847
+}
+},
+"time": 1790479960847
+}
+},
+{
+"id": "evt_0e0ec0b120013GKsKSMyJsRz59",
+"type": "message.part.delta",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"messageID": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq",
+"partID": "prt_0e0ec0b0f001Tz5Gj0FzNlJbn3",
+"field": "text",
+"delta": "Delegate "
+}
+},
+{
+"id": "evt_0e0ec0b140019cjqPy3YOooFMR",
+"type": "message.part.delta",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"messageID": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq",
+"partID": "prt_0e0ec0b0f001Tz5Gj0FzNlJbn3",
+"field": "text",
+"delta": "to "
+}
+},
+{
+"id": "evt_0e0ec0b14002yUwwqqXjAJy4VG",
+"type": "message.part.delta",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"messageID": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq",
+"partID": "prt_0e0ec0b0f001Tz5Gj0FzNlJbn3",
+"field": "text",
+"delta": "two "
+}
+},
+{
+"id": "evt_0e0ec0b36001ck8Dc7njH0P8cU",
+"type": "message.part.delta",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"messageID": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq",
+"partID": "prt_0e0ec0b0f001Tz5Gj0FzNlJbn3",
+"field": "text",
+"delta": "helpers."
+}
+},
+{
+"id": "evt_0e0ec0b38001oC0KjXeoPORp3f",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"part": {
+"id": "prt_0e0ec0b0f001Tz5Gj0FzNlJbn3",
+"messageID": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq",
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"type": "reasoning",
+"text": "Delegate to two helpers.",
+"time": {
+"start": 1790479960847,
+"end": 1790479960888
+}
+},
+"time": 1790479960888
+}
+},
+{
+"id": "evt_0e0ec0b3e001IgjA56aHJKYRbB",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"part": {
+"id": "prt_0e0ec0b3d001bZUJ5SQD93yBsZ",
+"messageID": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq",
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"type": "tool",
+"tool": "task",
+"callID": "call_7_0",
+"state": {
+"status": "pending",
+"input": {},
+"raw": ""
+}
+},
+"time": 1790479960894
+}
+},
+{
+"id": "evt_0e0ec0b49002uJu21JH0J7XqQU",
+"type": "session.created",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"info": {
+"id": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"slug": "quick-meadow",
+"version": "1.18.32",
+"projectID": "global",
+"directory": "/work/proj",
+"path": "work/proj",
+"parentID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"title": "Read notes (@general subagent)",
+"agent": "general",
+"permission": [],
+"cost": 0,
+"tokens": {
+"input": 0,
+"output": 0,
+"reasoning": 0,
+"cache": {
+"read": 0,
+"write": 0
+}
+},
+"time": {
+"created": 1790479960905,
+"updated": 1790479960905
+}
+}
+}
+},
+{
+"id": "evt_0e0ec0b500018TgG6au0J1OP2W",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"part": {
+"type": "tool",
+"tool": "task",
+"callID": "call_7_0",
+"state": {
+"title": "Read notes",
+"metadata": {
+"parentSessionId": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"sessionId": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"model": {
+"modelID": "mock-model",
+"providerID": "mock"
+}
+},
+"status": "running",
+"input": {
+"subagent_type": "general",
+"description": "Read notes",
+"prompt": "CHILD-A: read notes.md and summarise it"
+},
+"time": {
+"start": 1790479960912
+}
+},
+"id": "prt_0e0ec0b3d001bZUJ5SQD93yBsZ",
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"messageID": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq"
+},
+"time": 1790479960912
+}
+},
+{
+"id": "evt_0e0ec0b5b001BS6u5dYdgyGBo3",
+"type": "session.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"info": {
+"id": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"slug": "quick-meadow",
+"projectID": "global",
+"directory": "/work/proj",
+"path": "work/proj",
+"parentID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"title": "Read notes (@general subagent)",
+"agent": "general",
+"model": {
+"id": "mock-model",
+"providerID": "mock",
+"variant": "default"
+},
+"version": "1.18.32",
+"cost": 0,
+"tokens": {
+"input": 0,
+"output": 0,
+"reasoning": 0,
+"cache": {
+"read": 0,
+"write": 0
+}
+},
+"permission": [],
+"time": {
+"created": 1790479960905,
+"updated": 1790479960921
+}
+}
+}
+},
+{
+"id": "evt_0e0ec0b61001rhXOQjG7f922dm",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"info": {
+"id": "msg_0e0ec0b58001JRNYR2QFjvJVq9",
+"role": "user",
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"time": {
+"created": 1790479960921
+},
+"agent": "general",
+"model": {
+"providerID": "mock",
+"modelID": "mock-model"
+}
+}
+}
+},
+{
+"id": "evt_0e0ec0b63001R7TsVIToNspmJg",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"part": {
+"type": "text",
+"text": "CHILD-A: read notes.md and summarise it",
+"messageID": "msg_0e0ec0b58001JRNYR2QFjvJVq9",
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"id": "prt_0e0ec0b600017brs5q9rM69OkU"
+},
+"time": 1790479960931
+}
+},
+{
+"id": "evt_0e0ec0b680016hEI1hza1sxGUn",
+"type": "session.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"info": {
+"id": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"slug": "quick-meadow",
+"projectID": "global",
+"directory": "/work/proj",
+"path": "work/proj",
+"parentID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"title": "Read notes (@general subagent)",
+"agent": "general",
+"model": {
+"id": "mock-model",
+"providerID": "mock",
+"variant": "default"
+},
+"version": "1.18.32",
+"cost": 0,
+"tokens": {
+"input": 0,
+"output": 0,
+"reasoning": 0,
+"cache": {
+"read": 0,
+"write": 0
+}
+},
+"permission": [],
+"time": {
+"created": 1790479960905,
+"updated": 1790479960935
+}
+}
+}
+},
+{
+"id": "evt_0e0ec0b73001vnmrixAkuP36lh",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"part": {
+"type": "tool",
+"tool": "task",
+"callID": "call_7_0",
+"state": {
+"title": "Read notes",
+"metadata": {
+"parentSessionId": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"sessionId": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"model": {
+"modelID": "mock-model",
+"providerID": "mock"
+}
+},
+"status": "running",
+"input": {
+"subagent_type": "general",
+"description": "Read notes",
+"prompt": "CHILD-A: read notes.md and summarise it"
+},
+"time": {
+"start": 1790479960912
+}
+},
+"id": "prt_0e0ec0b3d001bZUJ5SQD93yBsZ",
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"messageID": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq"
+},
+"time": 1790479960946
+}
+},
+{
+"id": "evt_0e0ec0b79001acX6fnohQyfCy0",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"part": {
+"id": "prt_0e0ec0b780012cfKkovTlLxCQO",
+"messageID": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq",
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"type": "tool",
+"tool": "task",
+"callID": "call_7_1",
+"state": {
+"status": "pending",
+"input": {},
+"raw": ""
+}
+},
+"time": 1790479960953
+}
+},
+{
+"id": "evt_0e0ec0b82002N6X4rzcq9SwpRW",
+"type": "session.created",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"info": {
+"id": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"slug": "kind-wizard",
+"version": "1.18.32",
+"projectID": "global",
+"directory": "/work/proj",
+"path": "work/proj",
+"parentID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"title": "List folder (@general subagent)",
+"agent": "general",
+"permission": [],
+"cost": 0,
+"tokens": {
+"input": 0,
+"output": 0,
+"reasoning": 0,
+"cache": {
+"read": 0,
+"write": 0
+}
+},
+"time": {
+"created": 1790479960962,
+"updated": 1790479960962
+}
+}
+}
+},
+{
+"id": "evt_0e0ec0b89001IF7F2O9LQh9uTG",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"part": {
+"type": "tool",
+"tool": "task",
+"callID": "call_7_1",
+"state": {
+"title": "List folder",
+"metadata": {
+"parentSessionId": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"sessionId": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"model": {
+"modelID": "mock-model",
+"providerID": "mock"
+}
+},
+"status": "running",
+"input": {
+"subagent_type": "general",
+"description": "List folder",
+"prompt": "CHILD-B: list the folder"
+},
+"time": {
+"start": 1790479960969
+}
+},
+"id": "prt_0e0ec0b780012cfKkovTlLxCQO",
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"messageID": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq"
+},
+"time": 1790479960969
+}
+},
+{
+"id": "evt_0e0ec0b91001gB2bNKz0ixYnw5",
+"type": "session.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"info": {
+"id": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"slug": "kind-wizard",
+"projectID": "global",
+"directory": "/work/proj",
+"path": "work/proj",
+"parentID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"title": "List folder (@general subagent)",
+"agent": "general",
+"model": {
+"id": "mock-model",
+"providerID": "mock",
+"variant": "default"
+},
+"version": "1.18.32",
+"cost": 0,
+"tokens": {
+"input": 0,
+"output": 0,
+"reasoning": 0,
+"cache": {
+"read": 0,
+"write": 0
+}
+},
+"permission": [],
+"time": {
+"created": 1790479960962,
+"updated": 1790479960975
+}
+}
+}
+},
+{
+"id": "evt_0e0ec0b95001pG0toBbYmBU1mb",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"info": {
+"id": "msg_0e0ec0b8d001qKf4KHIngQ5esm",
+"role": "user",
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"time": {
+"created": 1790479960975
+},
+"agent": "general",
+"model": {
+"providerID": "mock",
+"modelID": "mock-model"
+}
+}
+}
+},
+{
+"id": "evt_0e0ec0b98001AOxTXI3364GsnQ",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"part": {
+"type": "text",
+"text": "CHILD-B: list the folder",
+"messageID": "msg_0e0ec0b8d001qKf4KHIngQ5esm",
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"id": "prt_0e0ec0b940010KuE6dzbLSTPhf"
+},
+"time": 1790479960984
+}
+},
+{
+"id": "evt_0e0ec0b9c001ugeTlPsBAPDkiC",
+"type": "session.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"info": {
+"id": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"slug": "kind-wizard",
+"projectID": "global",
+"directory": "/work/proj",
+"path": "work/proj",
+"parentID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"title": "List folder (@general subagent)",
+"agent": "general",
+"model": {
+"id": "mock-model",
+"providerID": "mock",
+"variant": "default"
+},
+"version": "1.18.32",
+"cost": 0,
+"tokens": {
+"input": 0,
+"output": 0,
+"reasoning": 0,
+"cache": {
+"read": 0,
+"write": 0
+}
+},
+"permission": [],
+"time": {
+"created": 1790479960962,
+"updated": 1790479960987
+}
+}
+}
+},
+{
+"id": "evt_0e0ec0ba50017RPZ6dOHGal0xl",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"part": {
+"type": "tool",
+"tool": "task",
+"callID": "call_7_1",
+"state": {
+"title": "List folder",
+"metadata": {
+"parentSessionId": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"sessionId": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"model": {
+"modelID": "mock-model",
+"providerID": "mock"
+}
+},
+"status": "running",
+"input": {
+"subagent_type": "general",
+"description": "List folder",
+"prompt": "CHILD-B: list the folder"
+},
+"time": {
+"start": 1790479960969
+}
+},
+"id": "prt_0e0ec0b780012cfKkovTlLxCQO",
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"messageID": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq"
+},
+"time": 1790479960997
+}
+},
+{
+"id": "evt_0e0ec0bb7001NYFu5dJt4rQBu4",
+"type": "session.status",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"status": {
+"type": "busy"
+}
+}
+},
+{
+"id": "evt_0e0ec0bbb001qXqS3Mn57dfPSf",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"info": {
+"id": "msg_0e0ec0bba001nhq65tMsAnDxh0",
+"parentID": "msg_0e0ec0b58001JRNYR2QFjvJVq9",
+"role": "assistant",
+"mode": "general",
+"agent": "general",
+"path": {
+"cwd": "/work/proj",
+"root": "/"
+},
+"cost": 0,
+"tokens": {
+"input": 0,
+"output": 0,
+"reasoning": 0,
+"cache": {
+"read": 0,
+"write": 0
+}
+},
+"modelID": "mock-model",
+"providerID": "mock",
+"time": {
+"created": 1790479961018
+},
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd"
+}
+}
+},
+{
+"id": "evt_0e0ec0bc50013dIx1u6XXUlJjc",
+"type": "session.status",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"status": {
+"type": "busy"
+}
+}
+},
+{
+"id": "evt_0e0ec0bc8001TAonPqsgLwvGPl",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"info": {
+"id": "msg_0e0ec0bc8001WD9A3zmrls3IQN",
+"parentID": "msg_0e0ec0b8d001qKf4KHIngQ5esm",
+"role": "assistant",
+"mode": "general",
+"agent": "general",
+"path": {
+"cwd": "/work/proj",
+"root": "/"
+},
+"cost": 0,
+"tokens": {
+"input": 0,
+"output": 0,
+"reasoning": 0,
+"cache": {
+"read": 0,
+"write": 0
+}
+},
+"modelID": "mock-model",
+"providerID": "mock",
+"time": {
+"created": 1790479961032
+},
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3"
+}
+}
+},
+{
+"id": "evt_0e0ec0bf2001OMSIz1EiMI0Hq1",
+"type": "session.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"info": {
+"id": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"slug": "quick-meadow",
+"projectID": "global",
+"directory": "/work/proj",
+"path": "work/proj",
+"parentID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"title": "Read notes (@general subagent)",
+"agent": "general",
+"model": {
+"id": "mock-model",
+"providerID": "mock",
+"variant": "default"
+},
+"version": "1.18.32",
+"summary": {
+"additions": 0,
+"deletions": 0,
+"files": 0
+},
+"cost": 0,
+"tokens": {
+"input": 0,
+"output": 0,
+"reasoning": 0,
+"cache": {
+"read": 0,
+"write": 0
+}
+},
+"permission": [],
+"time": {
+"created": 1790479960905,
+"updated": 1790479961046
+}
+}
+}
+},
+{
+"id": "evt_0e0ec0bfc001MyRCGw3Z1ZnPsq",
+"type": "session.diff",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"diff": []
+}
+},
+{
+"id": "evt_0e0ec0bfe001ktLxhaSKGchXg4",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"info": {
+"role": "user",
+"time": {
+"created": 1790479960921
+},
+"agent": "general",
+"model": {
+"providerID": "mock",
+"modelID": "mock-model"
+},
+"id": "msg_0e0ec0b58001JRNYR2QFjvJVq9",
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"summary": {
+"diffs": []
+}
+}
+}
+},
+{
+"id": "evt_0e0ec0c02001E6pJHBl2166wBy",
+"type": "session.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"info": {
+"id": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"slug": "kind-wizard",
+"projectID": "global",
+"directory": "/work/proj",
+"path": "work/proj",
+"parentID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"title": "List folder (@general subagent)",
+"agent": "general",
+"model": {
+"id": "mock-model",
+"providerID": "mock",
+"variant": "default"
+},
+"version": "1.18.32",
+"summary": {
+"additions": 0,
+"deletions": 0,
+"files": 0
+},
+"cost": 0,
+"tokens": {
+"input": 0,
+"output": 0,
+"reasoning": 0,
+"cache": {
+"read": 0,
+"write": 0
+}
+},
+"permission": [],
+"time": {
+"created": 1790479960962,
+"updated": 1790479961089
+}
+}
+}
+},
+{
+"id": "evt_0e0ec0c06001W4PSobn2eQaj73",
+"type": "session.diff",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"diff": []
+}
+},
+{
+"id": "evt_0e0ec0c07001RN1CgryU4ll98Q",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"info": {
+"role": "user",
+"time": {
+"created": 1790479960975
+},
+"agent": "general",
+"model": {
+"providerID": "mock",
+"modelID": "mock-model"
+},
+"id": "msg_0e0ec0b8d001qKf4KHIngQ5esm",
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"summary": {
+"diffs": []
+}
+}
+}
+},
+{
+"id": "evt_0e0ec0c51001APt25y9jgV4yAi",
+"type": "session.status",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"status": {
+"type": "busy"
+}
+}
+},
+{
+"id": "evt_0e0ec0c5f001OE4YaWbiVzeEjx",
+"type": "session.status",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"status": {
+"type": "busy"
+}
+}
+},
+{
+"id": "evt_0e0ec0c67001FndkVeLNI1egOb",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"part": {
+"id": "prt_0e0ec0c66001E7txmGBCJaZ1qB",
+"messageID": "msg_0e0ec0bc8001WD9A3zmrls3IQN",
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"type": "step-start"
+},
+"time": 1790479961191
+}
+},
+{
+"id": "evt_0e0ec0c6d001Y2SwbnFR9hbSb6",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"part": {
+"id": "prt_0e0ec0c6c001OTYMsuy2fRX6Fg",
+"messageID": "msg_0e0ec0bc8001WD9A3zmrls3IQN",
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"type": "tool",
+"tool": "bash",
+"callID": "call_8_0",
+"state": {
+"status": "pending",
+"input": {},
+"raw": ""
+}
+},
+"time": 1790479961197
+}
+},
+{
+"id": "evt_0e0ec0c81001pr8lxGxlxcz6Yt",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"part": {
+"type": "tool",
+"tool": "bash",
+"callID": "call_8_0",
+"state": {
+"metadata": {
+"output": ""
+},
+"status": "running",
+"input": {
+"command": "ls",
+"description": "List folder"
+},
+"time": {
+"start": 1790479961216
+}
+},
+"id": "prt_0e0ec0c6c001OTYMsuy2fRX6Fg",
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"messageID": "msg_0e0ec0bc8001WD9A3zmrls3IQN"
+},
+"time": 1790479961216
+}
+},
+{
+"id": "evt_0e0ec0c87001Ax8la16tfjvPUu",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"part": {
+"type": "tool",
+"tool": "bash",
+"callID": "call_8_0",
+"state": {
+"metadata": {
+"output": ""
+},
+"status": "running",
+"input": {
+"command": "ls",
+"description": "List folder"
+},
+"time": {
+"start": 1790479961216
+}
+},
+"id": "prt_0e0ec0c6c001OTYMsuy2fRX6Fg",
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"messageID": "msg_0e0ec0bc8001WD9A3zmrls3IQN"
+},
+"time": 1790479961223
+}
+},
+{
+"id": "evt_0e0ec0c96001JcRA6lCS5YwXdM",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"part": {
+"id": "prt_0e0ec0c96001qT7ImpIdkPIPDS",
+"messageID": "msg_0e0ec0bba001nhq65tMsAnDxh0",
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"type": "step-start"
+},
+"time": 1790479961238
+}
+},
+{
+"id": "evt_0e0ec0c9a001klike09H95Gz9C",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"part": {
+"id": "prt_0e0ec0c9a001l2UiXCVrxV2Cw6",
+"messageID": "msg_0e0ec0bba001nhq65tMsAnDxh0",
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"type": "reasoning",
+"text": "",
+"time": {
+"start": 1790479961242
+}
+},
+"time": 1790479961242
+}
+},
+{
+"id": "evt_0e0ec0c9e001GwayA1USlg45U0",
+"type": "message.part.delta",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"messageID": "msg_0e0ec0bba001nhq65tMsAnDxh0",
+"partID": "prt_0e0ec0c9a001l2UiXCVrxV2Cw6",
+"field": "text",
+"delta": "Read "
+}
+},
+{
+"id": "evt_0e0ec0ca00012GBORxA7LwCEse",
+"type": "message.part.delta",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"messageID": "msg_0e0ec0bba001nhq65tMsAnDxh0",
+"partID": "prt_0e0ec0c9a001l2UiXCVrxV2Cw6",
+"field": "text",
+"delta": "the "
+}
+},
+{
+"id": "evt_0e0ec0ccb0019IFK9fj1kTI2qy",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"part": {
+"type": "tool",
+"tool": "bash",
+"callID": "call_8_0",
+"state": {
+"metadata": {
+"output": "notes.md\n"
+},
+"status": "running",
+"input": {
+"command": "ls",
+"description": "List folder"
+},
+"time": {
+"start": 1790479961216
+}
+},
+"id": "prt_0e0ec0c6c001OTYMsuy2fRX6Fg",
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"messageID": "msg_0e0ec0bc8001WD9A3zmrls3IQN"
+},
+"time": 1790479961291
+}
+},
+{
+"id": "evt_0e0ec0cd50017W2CJiSCMw71w6",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"part": {
+"type": "tool",
+"tool": "bash",
+"callID": "call_8_0",
+"state": {
+"status": "completed",
+"input": {
+"command": "ls",
+"description": "List folder"
+},
+"output": "notes.md\n",
+"metadata": {
+"output": "notes.md\n",
+"exit": 0,
+"truncated": false
+},
+"title": "ls",
+"time": {
+"start": 1790479961216,
+"end": 1790479961300
+}
+},
+"id": "prt_0e0ec0c6c001OTYMsuy2fRX6Fg",
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"messageID": "msg_0e0ec0bc8001WD9A3zmrls3IQN"
+},
+"time": 1790479961301
+}
+},
+{
+"id": "evt_0e0ec0cda001uIP7N2c1ByMuMn",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"part": {
+"id": "prt_0e0ec0cda001JfWXEZMXyU7rXD",
+"reason": "tool-calls",
+"messageID": "msg_0e0ec0bc8001WD9A3zmrls3IQN",
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"type": "step-finish",
+"tokens": {
+"total": 1248,
+"input": 208,
+"output": 40,
+"reasoning": 0,
+"cache": {
+"write": 0,
+"read": 1000
+}
+},
+"cost": 0
+},
+"time": 1790479961306
+}
+},
+{
+"id": "evt_0e0ec0cde001r1eLQ8Klch9tYw",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"info": {
+"id": "msg_0e0ec0bc8001WD9A3zmrls3IQN",
+"parentID": "msg_0e0ec0b8d001qKf4KHIngQ5esm",
+"role": "assistant",
+"mode": "general",
+"agent": "general",
+"path": {
+"cwd": "/work/proj",
+"root": "/"
+},
+"cost": 0,
+"tokens": {
+"total": 1248,
+"input": 208,
+"output": 40,
+"reasoning": 0,
+"cache": {
+"write": 0,
+"read": 1000
+}
+},
+"modelID": "mock-model",
+"providerID": "mock",
+"time": {
+"created": 1790479961032,
+"completed": 1790479961314
+},
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"finish": "tool-calls"
+}
+}
+},
+{
+"id": "evt_0e0ec0ce2001RtPB4mVucp16pw",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"info": {
+"id": "msg_0e0ec0bc8001WD9A3zmrls3IQN",
+"parentID": "msg_0e0ec0b8d001qKf4KHIngQ5esm",
+"role": "assistant",
+"mode": "general",
+"agent": "general",
+"path": {
+"cwd": "/work/proj",
+"root": "/"
+},
+"cost": 0,
+"tokens": {
+"total": 1248,
+"input": 208,
+"output": 40,
+"reasoning": 0,
+"cache": {
+"write": 0,
+"read": 1000
+}
+},
+"modelID": "mock-model",
+"providerID": "mock",
+"time": {
+"created": 1790479961032,
+"completed": 1790479961314
+},
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"finish": "tool-calls"
+}
+}
+},
+{
+"id": "evt_0e0ec0ce4001KSPMyDMLCvDkAR",
+"type": "session.status",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"status": {
+"type": "busy"
+}
+}
+},
+{
+"id": "evt_0e0ec0ce6001tMBW4dR0CM0yVs",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"info": {
+"id": "msg_0e0ec0ce6001Cy4WbgIDNaGKHq",
+"parentID": "msg_0e0ec0b8d001qKf4KHIngQ5esm",
+"role": "assistant",
+"mode": "general",
+"agent": "general",
+"path": {
+"cwd": "/work/proj",
+"root": "/"
+},
+"cost": 0,
+"tokens": {
+"input": 0,
+"output": 0,
+"reasoning": 0,
+"cache": {
+"read": 0,
+"write": 0
+}
+},
+"modelID": "mock-model",
+"providerID": "mock",
+"time": {
+"created": 1790479961318
+},
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3"
+}
+}
+},
+{
+"id": "evt_0e0ec0d0900179ChG1ZyRvDvD4",
+"type": "message.part.delta",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"messageID": "msg_0e0ec0bba001nhq65tMsAnDxh0",
+"partID": "prt_0e0ec0c9a001l2UiXCVrxV2Cw6",
+"field": "text",
+"delta": "file."
+}
+},
+{
+"id": "evt_0e0ec0d0a001go8ij0cJECFjNC",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"part": {
+"id": "prt_0e0ec0c9a001l2UiXCVrxV2Cw6",
+"messageID": "msg_0e0ec0bba001nhq65tMsAnDxh0",
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"type": "reasoning",
+"text": "Read the file.",
+"time": {
+"start": 1790479961242,
+"end": 1790479961354
+}
+},
+"time": 1790479961354
+}
+},
+{
+"id": "evt_0e0ec0d0e001Q5toiAsoE0zyXf",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"part": {
+"id": "prt_0e0ec0d0e001U2B014Ig4bFOTw",
+"messageID": "msg_0e0ec0bba001nhq65tMsAnDxh0",
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"type": "tool",
+"tool": "read",
+"callID": "call_9_0",
+"state": {
+"status": "pending",
+"input": {},
+"raw": ""
+}
+},
+"time": 1790479961358
+}
+},
+{
+"id": "evt_0e0ec0d17001tMpUxUOw08up7F",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"part": {
+"type": "tool",
+"tool": "read",
+"callID": "call_9_0",
+"state": {
+"status": "running",
+"input": {
+"filePath": "/work/proj/notes.md"
+},
+"time": {
+"start": 1790479961367
+}
+},
+"id": "prt_0e0ec0d0e001U2B014Ig4bFOTw",
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"messageID": "msg_0e0ec0bba001nhq65tMsAnDxh0"
+},
+"time": 1790479961367
+}
+},
+{
+"id": "evt_0e0ec0d1f001EWelhyC4Lozmeq",
+"type": "session.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"info": {
+"id": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"slug": "kind-wizard",
+"projectID": "global",
+"directory": "/work/proj",
+"path": "work/proj",
+"parentID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"title": "List folder (@general subagent)",
+"agent": "general",
+"model": {
+"id": "mock-model",
+"providerID": "mock",
+"variant": "default"
+},
+"version": "1.18.32",
+"summary": {
+"additions": 0,
+"deletions": 0,
+"files": 0
+},
+"cost": 0,
+"tokens": {
+"input": 208,
+"output": 40,
+"reasoning": 0,
+"cache": {
+"read": 1000,
+"write": 0
+}
+},
+"permission": [],
+"time": {
+"created": 1790479960962,
+"updated": 1790479961374
+}
+}
+}
+},
+{
+"id": "evt_0e0ec0d22001MoyA2k6xSbG1EC",
+"type": "session.diff",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"diff": []
+}
+},
+{
+"id": "evt_0e0ec0d24001INvw14TzybL5E9",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"info": {
+"role": "user",
+"time": {
+"created": 1790479960975
+},
+"agent": "general",
+"model": {
+"providerID": "mock",
+"modelID": "mock-model"
+},
+"summary": {
+"diffs": []
+},
+"id": "msg_0e0ec0b8d001qKf4KHIngQ5esm",
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3"
+}
+}
+},
+{
+"id": "evt_0e0ec0d51001xVzCGcQPFxmiEt",
+"type": "session.status",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"status": {
+"type": "busy"
+}
+}
+},
+{
+"id": "evt_0e0ec0d7d001Q7zMXGVncvD5zj",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"part": {
+"id": "prt_0e0ec0d7d001rdcpHnrV0Ve6uF",
+"messageID": "msg_0e0ec0ce6001Cy4WbgIDNaGKHq",
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"type": "step-start"
+},
+"time": 1790479961469
+}
+},
+{
+"id": "evt_0e0ec0d81001XsPUbGsZK4Jz4V",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"part": {
+"id": "prt_0e0ec0d81001pXh3X3V8e2t6mb",
+"messageID": "msg_0e0ec0ce6001Cy4WbgIDNaGKHq",
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"type": "text",
+"text": "",
+"time": {
+"start": 1790479961473
+}
+},
+"time": 1790479961473
+}
+},
+{
+"id": "evt_0e0ec0d84001R8d6x8fHBormy1",
+"type": "message.part.delta",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"messageID": "msg_0e0ec0ce6001Cy4WbgIDNaGKHq",
+"partID": "prt_0e0ec0d81001pXh3X3V8e2t6mb",
+"field": "text",
+"delta": "The "
+}
+},
+{
+"id": "evt_0e0ec0d86001gSBnXkdTKbVJHq",
+"type": "message.part.delta",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"messageID": "msg_0e0ec0ce6001Cy4WbgIDNaGKHq",
+"partID": "prt_0e0ec0d81001pXh3X3V8e2t6mb",
+"field": "text",
+"delta": "folder "
+}
+},
+{
+"id": "evt_0e0ec0d8700108yDZXvlS0lPNr",
+"type": "message.part.delta",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"messageID": "msg_0e0ec0ce6001Cy4WbgIDNaGKHq",
+"partID": "prt_0e0ec0d81001pXh3X3V8e2t6mb",
+"field": "text",
+"delta": "holds "
+}
+},
+{
+"id": "evt_0e0ec0d870026VrcjJMqX6tgy9",
+"type": "message.part.delta",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"messageID": "msg_0e0ec0ce6001Cy4WbgIDNaGKHq",
+"partID": "prt_0e0ec0d81001pXh3X3V8e2t6mb",
+"field": "text",
+"delta": "notes.md."
+}
+},
+{
+"id": "evt_0e0ec0dce001Ewc3TuyR4CdE2X",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"part": {
+"id": "prt_0e0ec0d81001pXh3X3V8e2t6mb",
+"messageID": "msg_0e0ec0ce6001Cy4WbgIDNaGKHq",
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"type": "text",
+"text": "The folder holds notes.md.",
+"time": {
+"start": 1790479961473,
+"end": 1790479961549
+}
+},
+"time": 1790479961550
+}
+},
+{
+"id": "evt_0e0ec0dd4001POefhH266KU3UV",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"part": {
+"id": "prt_0e0ec0dd3001KevS0vGYY3i4XP",
+"reason": "stop",
+"messageID": "msg_0e0ec0ce6001Cy4WbgIDNaGKHq",
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"type": "step-finish",
+"tokens": {
+"total": 1250,
+"input": 210,
+"output": 40,
+"reasoning": 0,
+"cache": {
+"write": 0,
+"read": 1000
+}
+},
+"cost": 0
+},
+"time": 1790479961556
+}
+},
+{
+"id": "evt_0e0ec0dd8001MvtiMtKWmvil5B",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"info": {
+"id": "msg_0e0ec0ce6001Cy4WbgIDNaGKHq",
+"parentID": "msg_0e0ec0b8d001qKf4KHIngQ5esm",
+"role": "assistant",
+"mode": "general",
+"agent": "general",
+"path": {
+"cwd": "/work/proj",
+"root": "/"
+},
+"cost": 0,
+"tokens": {
+"total": 1250,
+"input": 210,
+"output": 40,
+"reasoning": 0,
+"cache": {
+"write": 0,
+"read": 1000
+}
+},
+"modelID": "mock-model",
+"providerID": "mock",
+"time": {
+"created": 1790479961318,
+"completed": 1790479961564
+},
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"finish": "stop"
+}
+}
+},
+{
+"id": "evt_0e0ec0ddd001XSK648IndzR2G1",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"info": {
+"id": "msg_0e0ec0ce6001Cy4WbgIDNaGKHq",
+"parentID": "msg_0e0ec0b8d001qKf4KHIngQ5esm",
+"role": "assistant",
+"mode": "general",
+"agent": "general",
+"path": {
+"cwd": "/work/proj",
+"root": "/"
+},
+"cost": 0,
+"tokens": {
+"total": 1250,
+"input": 210,
+"output": 40,
+"reasoning": 0,
+"cache": {
+"write": 0,
+"read": 1000
+}
+},
+"modelID": "mock-model",
+"providerID": "mock",
+"time": {
+"created": 1790479961318,
+"completed": 1790479961564
+},
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"finish": "stop"
+}
+}
+},
+{
+"id": "evt_0e0ec0ddf001wNvNO3oTJzcwTl",
+"type": "session.status",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"status": {
+"type": "busy"
+}
+}
+},
+{
+"id": "evt_0e0ec0de30019Lj3hvdVxfAhPs",
+"type": "session.status",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"status": {
+"type": "idle"
+}
+}
+},
+{
+"id": "evt_0e0ec0de3002s6nFv56D8O7yY0",
+"type": "session.idle",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3"
+}
+},
+{
+"id": "evt_0e0ec0de9001v4wvVE5LzzDexU",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"part": {
+"type": "tool",
+"tool": "task",
+"callID": "call_7_1",
+"state": {
+"status": "completed",
+"input": {
+"subagent_type": "general",
+"description": "List folder",
+"prompt": "CHILD-B: list the folder"
+},
+"output": "<task id=\"ses_f1f13f47dffe0UEEbHXZERyxC3\" state=\"completed\">\n<task_result>\nThe folder holds notes.md.\n</task_result>\n</task>",
+"metadata": {
+"parentSessionId": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"sessionId": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"model": {
+"modelID": "mock-model",
+"providerID": "mock"
+},
+"truncated": false
+},
+"title": "List folder",
+"time": {
+"start": 1790479960969,
+"end": 1790479961576
+}
+},
+"id": "prt_0e0ec0b780012cfKkovTlLxCQO",
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"messageID": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq"
+},
+"time": 1790479961577
+}
+},
+{
+"id": "evt_0e0ec0def001nJd194V4phuo5J",
+"type": "session.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"info": {
+"id": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"slug": "kind-wizard",
+"projectID": "global",
+"directory": "/work/proj",
+"path": "work/proj",
+"parentID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"title": "List folder (@general subagent)",
+"agent": "general",
+"model": {
+"id": "mock-model",
+"providerID": "mock",
+"variant": "default"
+},
+"version": "1.18.32",
+"summary": {
+"additions": 0,
+"deletions": 0,
+"files": 0
+},
+"cost": 0,
+"tokens": {
+"input": 418,
+"output": 80,
+"reasoning": 0,
+"cache": {
+"read": 2000,
+"write": 0
+}
+},
+"permission": [],
+"time": {
+"created": 1790479960962,
+"updated": 1790479961582
+}
+}
+}
+},
+{
+"id": "evt_0e0ec0df3001YAr847xllC9B9l",
+"type": "session.diff",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"diff": []
+}
+},
+{
+"id": "evt_0e0ec0df6001CEfaMuGdEhXqgC",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+"info": {
+"role": "user",
+"time": {
+"created": 1790479960975
+},
+"agent": "general",
+"model": {
+"providerID": "mock",
+"modelID": "mock-model"
+},
+"summary": {
+"diffs": []
+},
+"id": "msg_0e0ec0b8d001qKf4KHIngQ5esm",
+"sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3"
+}
+}
+},
+{
+"id": "evt_0e0ec0e1e001HUrC3ZGzkwzyv1",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"part": {
+"type": "tool",
+"tool": "read",
+"callID": "call_9_0",
+"state": {
+"status": "completed",
+"input": {
+"filePath": "/work/proj/notes.md"
+},
+"output": "<path>/work/proj/notes.md</path>\n<type>file</type>\n<content>\n1: # Notes\n2: line one\n3: line two\n\n(End of file - total 3 lines)\n</content>",
+"metadata": {
+"preview": "# Notes\nline one\nline two",
+"truncated": false,
+"loaded": [],
+"display": {
+"type": "file",
+"path": "/work/proj/notes.md",
+"text": "# Notes\nline one\nline two",
+"lineStart": 1,
+"lineEnd": 3,
+"totalLines": 3,
+"truncated": false
+}
+},
+"title": "work/proj/notes.md",
+"time": {
+"start": 1790479961367,
+"end": 1790479961630
+}
+},
+"id": "prt_0e0ec0d0e001U2B014Ig4bFOTw",
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"messageID": "msg_0e0ec0bba001nhq65tMsAnDxh0"
+},
+"time": 1790479961630
+}
+},
+{
+"id": "evt_0e0ec0e230015Hs69EwH272MxJ",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"part": {
+"id": "prt_0e0ec0e23001MK1t2p8W4YKD1T",
+"reason": "tool-calls",
+"messageID": "msg_0e0ec0bba001nhq65tMsAnDxh0",
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"type": "step-finish",
+"tokens": {
+"total": 1249,
+"input": 209,
+"output": 28,
+"reasoning": 12,
+"cache": {
+"write": 0,
+"read": 1000
+}
+},
+"cost": 0
+},
+"time": 1790479961635
+}
+},
+{
+"id": "evt_0e0ec0e26001pw4W1purSCYy4c",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"info": {
+"id": "msg_0e0ec0bba001nhq65tMsAnDxh0",
+"parentID": "msg_0e0ec0b58001JRNYR2QFjvJVq9",
+"role": "assistant",
+"mode": "general",
+"agent": "general",
+"path": {
+"cwd": "/work/proj",
+"root": "/"
+},
+"cost": 0,
+"tokens": {
+"total": 1249,
+"input": 209,
+"output": 28,
+"reasoning": 12,
+"cache": {
+"write": 0,
+"read": 1000
+}
+},
+"modelID": "mock-model",
+"providerID": "mock",
+"time": {
+"created": 1790479961018,
+"completed": 1790479961651
+},
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"finish": "tool-calls"
+}
+}
+},
+{
+"id": "evt_0e0ec0e33001t7ktx2OekaztvM",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"info": {
+"id": "msg_0e0ec0bba001nhq65tMsAnDxh0",
+"parentID": "msg_0e0ec0b58001JRNYR2QFjvJVq9",
+"role": "assistant",
+"mode": "general",
+"agent": "general",
+"path": {
+"cwd": "/work/proj",
+"root": "/"
+},
+"cost": 0,
+"tokens": {
+"total": 1249,
+"input": 209,
+"output": 28,
+"reasoning": 12,
+"cache": {
+"write": 0,
+"read": 1000
+}
+},
+"modelID": "mock-model",
+"providerID": "mock",
+"time": {
+"created": 1790479961018,
+"completed": 1790479961651
+},
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"finish": "tool-calls"
+}
+}
+},
+{
+"id": "evt_0e0ec0e38001llxFdVrr93y6gR",
+"type": "session.status",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"status": {
+"type": "busy"
+}
+}
+},
+{
+"id": "evt_0e0ec0e3b001etO1qJhkPlzq93",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"info": {
+"id": "msg_0e0ec0e3a001mPOUEVl1sCmZTg",
+"parentID": "msg_0e0ec0b58001JRNYR2QFjvJVq9",
+"role": "assistant",
+"mode": "general",
+"agent": "general",
+"path": {
+"cwd": "/work/proj",
+"root": "/"
+},
+"cost": 0,
+"tokens": {
+"input": 0,
+"output": 0,
+"reasoning": 0,
+"cache": {
+"read": 0,
+"write": 0
+}
+},
+"modelID": "mock-model",
+"providerID": "mock",
+"time": {
+"created": 1790479961658
+},
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd"
+}
+}
+},
+{
+"id": "evt_0e0ec0e44001hvrj2VbtHLF5S6",
+"type": "session.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"info": {
+"id": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"slug": "quick-meadow",
+"projectID": "global",
+"directory": "/work/proj",
+"path": "work/proj",
+"parentID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"title": "Read notes (@general subagent)",
+"agent": "general",
+"model": {
+"id": "mock-model",
+"providerID": "mock",
+"variant": "default"
+},
+"version": "1.18.32",
+"summary": {
+"additions": 0,
+"deletions": 0,
+"files": 0
+},
+"cost": 0,
+"tokens": {
+"input": 209,
+"output": 28,
+"reasoning": 12,
+"cache": {
+"read": 1000,
+"write": 0
+}
+},
+"permission": [],
+"time": {
+"created": 1790479960905,
+"updated": 1790479961667
+}
+}
+}
+},
+{
+"id": "evt_0e0ec0e49001jpiXXk6OsK5uY4",
+"type": "session.diff",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"diff": []
+}
+},
+{
+"id": "evt_0e0ec0e4c001C3Y1xojnlXKa57",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"info": {
+"role": "user",
+"time": {
+"created": 1790479960921
+},
+"agent": "general",
+"model": {
+"providerID": "mock",
+"modelID": "mock-model"
+},
+"summary": {
+"diffs": []
+},
+"id": "msg_0e0ec0b58001JRNYR2QFjvJVq9",
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd"
+}
+}
+},
+{
+"id": "evt_0e0ec0ee10013Qgh6JvFtaSiPd",
+"type": "session.status",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"status": {
+"type": "busy"
+}
+}
+},
+{
+"id": "evt_0e0ec0f0a001pTpd28OMWCvv8T",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"part": {
+"id": "prt_0e0ec0f09001Uxl1XYcRwdxfZv",
+"messageID": "msg_0e0ec0e3a001mPOUEVl1sCmZTg",
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"type": "step-start"
+},
+"time": 1790479961866
+}
+},
+{
+"id": "evt_0e0ec0f11001F2EF4Nejyq28zi",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"part": {
+"id": "prt_0e0ec0f11001xM5V0LIMc4ekh3",
+"messageID": "msg_0e0ec0e3a001mPOUEVl1sCmZTg",
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"type": "text",
+"text": "",
+"time": {
+"start": 1790479961873
+}
+},
+"time": 1790479961873
+}
+},
+{
+"id": "evt_0e0ec0f18001NYNzZqS2kRaGEr",
+"type": "message.part.delta",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"messageID": "msg_0e0ec0e3a001mPOUEVl1sCmZTg",
+"partID": "prt_0e0ec0f11001xM5V0LIMc4ekh3",
+"field": "text",
+"delta": "notes.md "
+}
+},
+{
+"id": "evt_0e0ec0f1a001BV8pEwRH5GxkCx",
+"type": "message.part.delta",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"messageID": "msg_0e0ec0e3a001mPOUEVl1sCmZTg",
+"partID": "prt_0e0ec0f11001xM5V0LIMc4ekh3",
+"field": "text",
+"delta": "has "
+}
+},
+{
+"id": "evt_0e0ec0f1b0016rwxgidxGKbliu",
+"type": "message.part.delta",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"messageID": "msg_0e0ec0e3a001mPOUEVl1sCmZTg",
+"partID": "prt_0e0ec0f11001xM5V0LIMc4ekh3",
+"field": "text",
+"delta": "a "
+}
+},
+{
+"id": "evt_0e0ec0f1b002GwOFIAPhOhD4H4",
+"type": "message.part.delta",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"messageID": "msg_0e0ec0e3a001mPOUEVl1sCmZTg",
+"partID": "prt_0e0ec0f11001xM5V0LIMc4ekh3",
+"field": "text",
+"delta": "heading "
+}
+},
+{
+"id": "evt_0e0ec0f1c0011p2Xyt1we60N1j",
+"type": "message.part.delta",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"messageID": "msg_0e0ec0e3a001mPOUEVl1sCmZTg",
+"partID": "prt_0e0ec0f11001xM5V0LIMc4ekh3",
+"field": "text",
+"delta": "and "
+}
+},
+{
+"id": "evt_0e0ec0f34001g3syFrHdKzh6aL",
+"type": "message.part.delta",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"messageID": "msg_0e0ec0e3a001mPOUEVl1sCmZTg",
+"partID": "prt_0e0ec0f11001xM5V0LIMc4ekh3",
+"field": "text",
+"delta": "two "
+}
+},
+{
+"id": "evt_0e0ec0f35001HzsVO9vodQlUje",
+"type": "message.part.delta",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"messageID": "msg_0e0ec0e3a001mPOUEVl1sCmZTg",
+"partID": "prt_0e0ec0f11001xM5V0LIMc4ekh3",
+"field": "text",
+"delta": "lines."
+}
+},
+{
+"id": "evt_0e0ec0f7c001H0GeoK3tMEchZ2",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"part": {
+"id": "prt_0e0ec0f11001xM5V0LIMc4ekh3",
+"messageID": "msg_0e0ec0e3a001mPOUEVl1sCmZTg",
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"type": "text",
+"text": "notes.md has a heading and two lines.",
+"time": {
+"start": 1790479961873,
+"end": 1790479961980
+}
+},
+"time": 1790479961980
+}
+},
+{
+"id": "evt_0e0ec0f83001fCVBoRbFrPMucM",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"part": {
+"id": "prt_0e0ec0f8300122BMcV39F4W0mJ",
+"reason": "stop",
+"messageID": "msg_0e0ec0e3a001mPOUEVl1sCmZTg",
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"type": "step-finish",
+"tokens": {
+"total": 1251,
+"input": 211,
+"output": 40,
+"reasoning": 0,
+"cache": {
+"write": 0,
+"read": 1000
+}
+},
+"cost": 0
+},
+"time": 1790479961987
+}
+},
+{
+"id": "evt_0e0ec0f89001ELSSrw4xmK6h7b",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"info": {
+"id": "msg_0e0ec0e3a001mPOUEVl1sCmZTg",
+"parentID": "msg_0e0ec0b58001JRNYR2QFjvJVq9",
+"role": "assistant",
+"mode": "general",
+"agent": "general",
+"path": {
+"cwd": "/work/proj",
+"root": "/"
+},
+"cost": 0,
+"tokens": {
+"total": 1251,
+"input": 211,
+"output": 40,
+"reasoning": 0,
+"cache": {
+"write": 0,
+"read": 1000
+}
+},
+"modelID": "mock-model",
+"providerID": "mock",
+"time": {
+"created": 1790479961658,
+"completed": 1790479962000
+},
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"finish": "stop"
+}
+}
+},
+{
+"id": "evt_0e0ec0f90001dChUVlLY6wUc6l",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"info": {
+"id": "msg_0e0ec0e3a001mPOUEVl1sCmZTg",
+"parentID": "msg_0e0ec0b58001JRNYR2QFjvJVq9",
+"role": "assistant",
+"mode": "general",
+"agent": "general",
+"path": {
+"cwd": "/work/proj",
+"root": "/"
+},
+"cost": 0,
+"tokens": {
+"total": 1251,
+"input": 211,
+"output": 40,
+"reasoning": 0,
+"cache": {
+"write": 0,
+"read": 1000
+}
+},
+"modelID": "mock-model",
+"providerID": "mock",
+"time": {
+"created": 1790479961658,
+"completed": 1790479962000
+},
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"finish": "stop"
+}
+}
+},
+{
+"id": "evt_0e0ec0f96001Ws1LepLsh7XC5H",
+"type": "session.status",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"status": {
+"type": "busy"
+}
+}
+},
+{
+"id": "evt_0e0ec0fa40015jFcXSR1TAmukc",
+"type": "session.status",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"status": {
+"type": "idle"
+}
+}
+},
+{
+"id": "evt_0e0ec0fa4002UNeGSNryUK33oj",
+"type": "session.idle",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd"
+}
+},
+{
+"id": "evt_0e0ec0fab001o6Q194DVZidg7k",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"part": {
+"type": "tool",
+"tool": "task",
+"callID": "call_7_0",
+"state": {
+"status": "completed",
+"input": {
+"subagent_type": "general",
+"description": "Read notes",
+"prompt": "CHILD-A: read notes.md and summarise it"
+},
+"output": "<task id=\"ses_f1f13f4b6ffehFDFUBI5qx3Zsd\" state=\"completed\">\n<task_result>\nnotes.md has a heading and two lines.\n</task_result>\n</task>",
+"metadata": {
+"parentSessionId": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"sessionId": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"model": {
+"modelID": "mock-model",
+"providerID": "mock"
+},
+"truncated": false
+},
+"title": "Read notes",
+"time": {
+"start": 1790479960912,
+"end": 1790479962026
+}
+},
+"id": "prt_0e0ec0b3d001bZUJ5SQD93yBsZ",
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"messageID": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq"
+},
+"time": 1790479962026
+}
+},
+{
+"id": "evt_0e0ec0fb3001KbHBLpxliPcp7q",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"part": {
+"id": "prt_0e0ec0fb3001m6tfHe1ByWvbZP",
+"reason": "tool-calls",
+"messageID": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq",
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"type": "step-finish",
+"tokens": {
+"total": 1247,
+"input": 207,
+"output": 28,
+"reasoning": 12,
+"cache": {
+"write": 0,
+"read": 1000
+}
+},
+"cost": 0
+},
+"time": 1790479962035
+}
+},
+{
+"id": "evt_0e0ec0fbb0018ZvhMu0CrtqsHX",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"info": {
+"id": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq",
+"parentID": "msg_0e0ec09a1001iv9xZgwHwbEu1b",
+"role": "assistant",
+"mode": "build",
+"agent": "build",
+"path": {
+"cwd": "/work/proj",
+"root": "/"
+},
+"cost": 0,
+"tokens": {
+"total": 1247,
+"input": 207,
+"output": 28,
+"reasoning": 12,
+"cache": {
+"write": 0,
+"read": 1000
+}
+},
+"modelID": "mock-model",
+"providerID": "mock",
+"time": {
+"created": 1790479960508,
+"completed": 1790479962052
+},
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"finish": "tool-calls"
+}
+}
+},
+{
+"id": "evt_0e0ec0fc5001h2Gd0Du7NZEGrh",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"info": {
+"id": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq",
+"parentID": "msg_0e0ec09a1001iv9xZgwHwbEu1b",
+"role": "assistant",
+"mode": "build",
+"agent": "build",
+"path": {
+"cwd": "/work/proj",
+"root": "/"
+},
+"cost": 0,
+"tokens": {
+"total": 1247,
+"input": 207,
+"output": 28,
+"reasoning": 12,
+"cache": {
+"write": 0,
+"read": 1000
+}
+},
+"modelID": "mock-model",
+"providerID": "mock",
+"time": {
+"created": 1790479960508,
+"completed": 1790479962052
+},
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"finish": "tool-calls"
+}
+}
+},
+{
+"id": "evt_0e0ec0fcc001wkHTXRg66Ep1ty",
+"type": "session.status",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"status": {
+"type": "busy"
+}
+}
+},
+{
+"id": "evt_0e0ec0fd0001lXFvfcJimiqFqN",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"info": {
+"id": "msg_0e0ec0fcf001aPjWuo4NJ3UlL7",
+"parentID": "msg_0e0ec09a1001iv9xZgwHwbEu1b",
+"role": "assistant",
+"mode": "build",
+"agent": "build",
+"path": {
+"cwd": "/work/proj",
+"root": "/"
+},
+"cost": 0,
+"tokens": {
+"input": 0,
+"output": 0,
+"reasoning": 0,
+"cache": {
+"read": 0,
+"write": 0
+}
+},
+"modelID": "mock-model",
+"providerID": "mock",
+"time": {
+"created": 1790479962064
+},
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7"
+}
+}
+},
+{
+"id": "evt_0e0ec0fdc001QZT5LHz6VquB0N",
+"type": "session.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"info": {
+"id": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"slug": "quick-meadow",
+"projectID": "global",
+"directory": "/work/proj",
+"path": "work/proj",
+"parentID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"title": "Read notes (@general subagent)",
+"agent": "general",
+"model": {
+"id": "mock-model",
+"providerID": "mock",
+"variant": "default"
+},
+"version": "1.18.32",
+"summary": {
+"additions": 0,
+"deletions": 0,
+"files": 0
+},
+"cost": 0,
+"tokens": {
+"input": 420,
+"output": 68,
+"reasoning": 12,
+"cache": {
+"read": 2000,
+"write": 0
+}
+},
+"permission": [],
+"time": {
+"created": 1790479960905,
+"updated": 1790479962075
+}
+}
+}
+},
+{
+"id": "evt_0e0ec0fe2001Sy7TopQtgOnJ8m",
+"type": "session.diff",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"diff": []
+}
+},
+{
+"id": "evt_0e0ec0fe4001fEYrUx0zT3wGYe",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+"info": {
+"role": "user",
+"time": {
+"created": 1790479960921
+},
+"agent": "general",
+"model": {
+"providerID": "mock",
+"modelID": "mock-model"
+},
+"summary": {
+"diffs": []
+},
+"id": "msg_0e0ec0b58001JRNYR2QFjvJVq9",
+"sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd"
+}
+}
+},
+{
+"id": "evt_0e0ec0fea001WiM1d6IvSt9FP3",
+"type": "session.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"info": {
+"id": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"slug": "silent-tiger",
+"projectID": "global",
+"directory": "/work/proj",
+"path": "work/proj",
+"title": "Parity session title",
+"agent": "build",
+"model": {
+"id": "mock-model",
+"providerID": "mock",
+"variant": "default"
+},
+"version": "1.18.32",
+"summary": {
+"additions": 0,
+"deletions": 0,
+"files": 0
+},
+"cost": 0,
+"tokens": {
+"input": 207,
+"output": 28,
+"reasoning": 12,
+"cache": {
+"read": 1000,
+"write": 0
+}
+},
+"time": {
+"created": 1790479960432,
+"updated": 1790479962089
+}
+}
+}
+},
+{
+"id": "evt_0e0ec0ff1001RrTKc3qYXA9I6K",
+"type": "session.diff",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"diff": []
+}
+},
+{
+"id": "evt_0e0ec0ff4001X2sI0f5D312hBU",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"info": {
+"role": "user",
+"time": {
+"created": 1790479960481
+},
+"agent": "build",
+"model": {
+"providerID": "mock",
+"modelID": "mock-model"
+},
+"summary": {
+"diffs": []
+},
+"id": "msg_0e0ec09a1001iv9xZgwHwbEu1b",
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7"
+}
+}
+},
+{
+"id": "evt_0e0ec100a001OP1H09yR2rzh4w",
+"type": "session.status",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"status": {
+"type": "busy"
+}
+}
+},
+{
+"id": "evt_0e0ec105a001MTtAJMWQvl1ILi",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"part": {
+"id": "prt_0e0ec105a001HrSOo9rHt4DnG7",
+"messageID": "msg_0e0ec0fcf001aPjWuo4NJ3UlL7",
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"type": "step-start"
+},
+"time": 1790479962202
+}
+},
+{
+"id": "evt_0e0ec1063001SzgNNqTzC2upY2",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"part": {
+"id": "prt_0e0ec1063001GDlAQ3J7AQ9gqy",
+"messageID": "msg_0e0ec0fcf001aPjWuo4NJ3UlL7",
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"type": "text",
+"text": "",
+"time": {
+"start": 1790479962211
+}
+},
+"time": 1790479962211
+}
+},
+{
+"id": "evt_0e0ec1068001yna65mDCiJ3mID",
+"type": "message.part.delta",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"messageID": "msg_0e0ec0fcf001aPjWuo4NJ3UlL7",
+"partID": "prt_0e0ec1063001GDlAQ3J7AQ9gqy",
+"field": "text",
+"delta": "Both "
+}
+},
+{
+"id": "evt_0e0ec10690019nHCbOczMJlRVJ",
+"type": "message.part.delta",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"messageID": "msg_0e0ec0fcf001aPjWuo4NJ3UlL7",
+"partID": "prt_0e0ec1063001GDlAQ3J7AQ9gqy",
+"field": "text",
+"delta": "helpers "
+}
+},
+{
+"id": "evt_0e0ec106a001mDjBOZWBk2vwhy",
+"type": "message.part.delta",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"messageID": "msg_0e0ec0fcf001aPjWuo4NJ3UlL7",
+"partID": "prt_0e0ec1063001GDlAQ3J7AQ9gqy",
+"field": "text",
+"delta": "finished."
+}
+},
+{
+"id": "evt_0e0ec10b2001dz7pNYV2oKlhJ7",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"part": {
+"id": "prt_0e0ec1063001GDlAQ3J7AQ9gqy",
+"messageID": "msg_0e0ec0fcf001aPjWuo4NJ3UlL7",
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"type": "text",
+"text": "Both helpers finished.",
+"time": {
+"start": 1790479962211,
+"end": 1790479962290
+}
+},
+"time": 1790479962290
+}
+},
+{
+"id": "evt_0e0ec10ba001hphMkdWxw2JiBR",
+"type": "message.part.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"part": {
+"id": "prt_0e0ec10ba001CGRkC7BcQwA0eG",
+"reason": "stop",
+"messageID": "msg_0e0ec0fcf001aPjWuo4NJ3UlL7",
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"type": "step-finish",
+"tokens": {
+"total": 1252,
+"input": 212,
+"output": 40,
+"reasoning": 0,
+"cache": {
+"write": 0,
+"read": 1000
+}
+},
+"cost": 0
+},
+"time": 1790479962298
+}
+},
+{
+"id": "evt_0e0ec10c1001asmZBqk1Rh1vrZ",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"info": {
+"id": "msg_0e0ec0fcf001aPjWuo4NJ3UlL7",
+"parentID": "msg_0e0ec09a1001iv9xZgwHwbEu1b",
+"role": "assistant",
+"mode": "build",
+"agent": "build",
+"path": {
+"cwd": "/work/proj",
+"root": "/"
+},
+"cost": 0,
+"tokens": {
+"total": 1252,
+"input": 212,
+"output": 40,
+"reasoning": 0,
+"cache": {
+"write": 0,
+"read": 1000
+}
+},
+"modelID": "mock-model",
+"providerID": "mock",
+"time": {
+"created": 1790479962064,
+"completed": 1790479962309
+},
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"finish": "stop"
+}
+}
+},
+{
+"id": "evt_0e0ec10c5001y74d8VtrHeDiL0",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"info": {
+"id": "msg_0e0ec0fcf001aPjWuo4NJ3UlL7",
+"parentID": "msg_0e0ec09a1001iv9xZgwHwbEu1b",
+"role": "assistant",
+"mode": "build",
+"agent": "build",
+"path": {
+"cwd": "/work/proj",
+"root": "/"
+},
+"cost": 0,
+"tokens": {
+"total": 1252,
+"input": 212,
+"output": 40,
+"reasoning": 0,
+"cache": {
+"write": 0,
+"read": 1000
+}
+},
+"modelID": "mock-model",
+"providerID": "mock",
+"time": {
+"created": 1790479962064,
+"completed": 1790479962309
+},
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"finish": "stop"
+}
+}
+},
+{
+"id": "evt_0e0ec10c8001jD7Ic5EoPbTdcv",
+"type": "session.status",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"status": {
+"type": "busy"
+}
+}
+},
+{
+"id": "evt_0e0ec10cc001vVg13br001JEy3",
+"type": "session.status",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"status": {
+"type": "idle"
+}
+}
+},
+{
+"id": "evt_0e0ec10cc002k3oE1DKuqRfw7V",
+"type": "session.idle",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7"
+}
+},
+{
+"id": "evt_0e0ec10ce001G6olxrsOi0Gzfh",
+"type": "session.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"info": {
+"id": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"slug": "silent-tiger",
+"projectID": "global",
+"directory": "/work/proj",
+"path": "work/proj",
+"title": "Parity session title",
+"agent": "build",
+"model": {
+"id": "mock-model",
+"providerID": "mock",
+"variant": "default"
+},
+"version": "1.18.32",
+"summary": {
+"additions": 0,
+"deletions": 0,
+"files": 0
+},
+"cost": 0,
+"tokens": {
+"input": 419,
+"output": 68,
+"reasoning": 12,
+"cache": {
+"read": 2000,
+"write": 0
+}
+},
+"time": {
+"created": 1790479960432,
+"updated": 1790479962317
+}
+}
+}
+},
+{
+"id": "evt_0e0ec10d1001Ag0NesFemEui2e",
+"type": "session.diff",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"diff": []
+}
+},
+{
+"id": "evt_0e0ec10d3001c82BTFA35AEizp",
+"type": "message.updated",
+"properties": {
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+"info": {
+"role": "user",
+"time": {
+"created": 1790479960481
+},
+"agent": "build",
+"model": {
+"providerID": "mock",
+"modelID": "mock-model"
+},
+"summary": {
+"diffs": []
+},
+"id": "msg_0e0ec09a1001iv9xZgwHwbEu1b",
+"sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7"
+}
+}
+}
+]
\ No newline at end of file
diff --git a/apps/server/src/engine2/fixtures/v1-sub.json b/apps/server/src/engine2/fixtures/v1-sub.json
new file mode 100644
index 00000000..31e9ba71
--- /dev/null
+++ b/apps/server/src/engine2/fixtures/v1-sub.json
@@ -0,0 +1,728 @@
+{
+ "session": {
+ "id": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+ "slug": "silent-tiger",
+ "projectID": "global",
+ "directory": "/work/proj",
+ "path": "work/proj",
+ "summary": {
+ "additions": 0,
+ "deletions": 0,
+ "files": 0
+ },
+ "cost": 0,
+ "tokens": {
+ "input": 419,
+ "output": 68,
+ "reasoning": 12,
+ "cache": {
+ "read": 2000,
+ "write": 0
+ }
+ },
+ "title": "Parity session title",
+ "agent": "build",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock",
+ "variant": "default"
+ },
+ "version": "1.18.32",
+ "time": {
+ "created": 1790479960432,
+ "updated": 1790479962317
+ }
+ },
+ "messages": [
+ {
+ "info": {
+ "id": "msg_0e0ec09a1001iv9xZgwHwbEu1b",
+ "sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+ "role": "user",
+ "time": {
+ "created": 1790479960481
+ },
+ "summary": {
+ "diffs": []
+ },
+ "agent": "build",
+ "model": {
+ "providerID": "mock",
+ "modelID": "mock-model"
+ }
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ec09a7001tLLL8l7H5kzeFl",
+ "sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+ "messageID": "msg_0e0ec09a1001iv9xZgwHwbEu1b",
+ "type": "text",
+ "text": "PARITY-SUB use two helpers"
+ }
+ ]
+ },
+ {
+ "info": {
+ "id": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq",
+ "sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+ "role": "assistant",
+ "time": {
+ "created": 1790479960508,
+ "completed": 1790479962052
+ },
+ "parentID": "msg_0e0ec09a1001iv9xZgwHwbEu1b",
+ "modelID": "mock-model",
+ "providerID": "mock",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/work/proj",
+ "root": "/"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 1247,
+ "input": 207,
+ "output": 28,
+ "reasoning": 12,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ },
+ "finish": "tool-calls"
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ec0b0a001YWUbJz6re4JIvr",
+ "sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+ "messageID": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq",
+ "type": "step-start"
+ },
+ {
+ "id": "prt_0e0ec0b0f001Tz5Gj0FzNlJbn3",
+ "sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+ "messageID": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq",
+ "type": "reasoning",
+ "text": "Delegate to two helpers.",
+ "time": {
+ "start": 1790479960847,
+ "end": 1790479960888
+ }
+ },
+ {
+ "id": "prt_0e0ec0b3d001bZUJ5SQD93yBsZ",
+ "sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+ "messageID": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq",
+ "type": "tool",
+ "callID": "call_7_0",
+ "tool": "task",
+ "state": {
+ "status": "completed",
+ "input": {
+ "subagent_type": "general",
+ "description": "Read notes",
+ "prompt": "CHILD-A: read notes.md and summarise it"
+ },
+ "output": "<task id=\"ses_f1f13f4b6ffehFDFUBI5qx3Zsd\" state=\"completed\">\n<task_result>\nnotes.md has a heading and two lines.\n</task_result>\n</task>",
+ "title": "Read notes",
+ "metadata": {
+ "parentSessionId": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+ "sessionId": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+ "model": {
+ "modelID": "mock-model",
+ "providerID": "mock"
+ },
+ "truncated": false
+ },
+ "time": {
+ "start": 1790479960912,
+ "end": 1790479962026
+ }
+ }
+ },
+ {
+ "id": "prt_0e0ec0b780012cfKkovTlLxCQO",
+ "sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+ "messageID": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq",
+ "type": "tool",
+ "callID": "call_7_1",
+ "tool": "task",
+ "state": {
+ "status": "completed",
+ "input": {
+ "subagent_type": "general",
+ "description": "List folder",
+ "prompt": "CHILD-B: list the folder"
+ },
+ "output": "<task id=\"ses_f1f13f47dffe0UEEbHXZERyxC3\" state=\"completed\">\n<task_result>\nThe folder holds notes.md.\n</task_result>\n</task>",
+ "title": "List folder",
+ "metadata": {
+ "parentSessionId": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+ "sessionId": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+ "model": {
+ "modelID": "mock-model",
+ "providerID": "mock"
+ },
+ "truncated": false
+ },
+ "time": {
+ "start": 1790479960969,
+ "end": 1790479961576
+ }
+ }
+ },
+ {
+ "id": "prt_0e0ec0fb3001m6tfHe1ByWvbZP",
+ "sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+ "messageID": "msg_0e0ec09bc001tdekd1Ii9Rp8Qq",
+ "type": "step-finish",
+ "reason": "tool-calls",
+ "cost": 0,
+ "tokens": {
+ "total": 1247,
+ "input": 207,
+ "output": 28,
+ "reasoning": 12,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ }
+ ]
+ },
+ {
+ "info": {
+ "id": "msg_0e0ec0fcf001aPjWuo4NJ3UlL7",
+ "sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+ "role": "assistant",
+ "time": {
+ "created": 1790479962064,
+ "completed": 1790479962309
+ },
+ "parentID": "msg_0e0ec09a1001iv9xZgwHwbEu1b",
+ "modelID": "mock-model",
+ "providerID": "mock",
+ "mode": "build",
+ "agent": "build",
+ "path": {
+ "cwd": "/work/proj",
+ "root": "/"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 1252,
+ "input": 212,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ },
+ "finish": "stop"
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ec105a001HrSOo9rHt4DnG7",
+ "sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+ "messageID": "msg_0e0ec0fcf001aPjWuo4NJ3UlL7",
+ "type": "step-start"
+ },
+ {
+ "id": "prt_0e0ec1063001GDlAQ3J7AQ9gqy",
+ "sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+ "messageID": "msg_0e0ec0fcf001aPjWuo4NJ3UlL7",
+ "type": "text",
+ "text": "Both helpers finished.",
+ "time": {
+ "start": 1790479962211,
+ "end": 1790479962290
+ }
+ },
+ {
+ "id": "prt_0e0ec10ba001CGRkC7BcQwA0eG",
+ "sessionID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+ "messageID": "msg_0e0ec0fcf001aPjWuo4NJ3UlL7",
+ "type": "step-finish",
+ "reason": "stop",
+ "cost": 0,
+ "tokens": {
+ "total": 1252,
+ "input": 212,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ }
+ ]
+ }
+ ],
+ "children": [
+ {
+ "session": {
+ "id": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+ "slug": "quick-meadow",
+ "projectID": "global",
+ "directory": "/work/proj",
+ "path": "work/proj",
+ "parentID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+ "summary": {
+ "additions": 0,
+ "deletions": 0,
+ "files": 0
+ },
+ "cost": 0,
+ "tokens": {
+ "input": 420,
+ "output": 68,
+ "reasoning": 12,
+ "cache": {
+ "read": 2000,
+ "write": 0
+ }
+ },
+ "title": "Read notes (@general subagent)",
+ "agent": "general",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock",
+ "variant": "default"
+ },
+ "version": "1.18.32",
+ "time": {
+ "created": 1790479960905,
+ "updated": 1790479962075
+ },
+ "permission": []
+ },
+ "messages": [
+ {
+ "info": {
+ "id": "msg_0e0ec0b58001JRNYR2QFjvJVq9",
+ "sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+ "role": "user",
+ "time": {
+ "created": 1790479960921
+ },
+ "summary": {
+ "diffs": []
+ },
+ "agent": "general",
+ "model": {
+ "providerID": "mock",
+ "modelID": "mock-model"
+ }
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ec0b600017brs5q9rM69OkU",
+ "sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+ "messageID": "msg_0e0ec0b58001JRNYR2QFjvJVq9",
+ "type": "text",
+ "text": "CHILD-A: read notes.md and summarise it"
+ }
+ ]
+ },
+ {
+ "info": {
+ "id": "msg_0e0ec0bba001nhq65tMsAnDxh0",
+ "sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+ "role": "assistant",
+ "time": {
+ "created": 1790479961018,
+ "completed": 1790479961651
+ },
+ "parentID": "msg_0e0ec0b58001JRNYR2QFjvJVq9",
+ "modelID": "mock-model",
+ "providerID": "mock",
+ "mode": "general",
+ "agent": "general",
+ "path": {
+ "cwd": "/work/proj",
+ "root": "/"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 1249,
+ "input": 209,
+ "output": 28,
+ "reasoning": 12,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ },
+ "finish": "tool-calls"
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ec0c96001qT7ImpIdkPIPDS",
+ "sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+ "messageID": "msg_0e0ec0bba001nhq65tMsAnDxh0",
+ "type": "step-start"
+ },
+ {
+ "id": "prt_0e0ec0c9a001l2UiXCVrxV2Cw6",
+ "sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+ "messageID": "msg_0e0ec0bba001nhq65tMsAnDxh0",
+ "type": "reasoning",
+ "text": "Read the file.",
+ "time": {
+ "start": 1790479961242,
+ "end": 1790479961354
+ }
+ },
+ {
+ "id": "prt_0e0ec0d0e001U2B014Ig4bFOTw",
+ "sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+ "messageID": "msg_0e0ec0bba001nhq65tMsAnDxh0",
+ "type": "tool",
+ "callID": "call_9_0",
+ "tool": "read",
+ "state": {
+ "status": "completed",
+ "input": {
+ "filePath": "/work/proj/notes.md"
+ },
+ "output": "<path>/work/proj/notes.md</path>\n<type>file</type>\n<content>\n1: # Notes\n2: line one\n3: line two\n\n(End of file - total 3 lines)\n</content>",
+ "title": "work/proj/notes.md",
+ "metadata": {
+ "preview": "# Notes\nline one\nline two",
+ "truncated": false,
+ "loaded": [],
+ "display": {
+ "type": "file",
+ "path": "/work/proj/notes.md",
+ "text": "# Notes\nline one\nline two",
+ "lineStart": 1,
+ "lineEnd": 3,
+ "totalLines": 3,
+ "truncated": false
+ }
+ },
+ "time": {
+ "start": 1790479961367,
+ "end": 1790479961630
+ }
+ }
+ },
+ {
+ "id": "prt_0e0ec0e23001MK1t2p8W4YKD1T",
+ "sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+ "messageID": "msg_0e0ec0bba001nhq65tMsAnDxh0",
+ "type": "step-finish",
+ "reason": "tool-calls",
+ "cost": 0,
+ "tokens": {
+ "total": 1249,
+ "input": 209,
+ "output": 28,
+ "reasoning": 12,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ }
+ ]
+ },
+ {
+ "info": {
+ "id": "msg_0e0ec0e3a001mPOUEVl1sCmZTg",
+ "sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+ "role": "assistant",
+ "time": {
+ "created": 1790479961658,
+ "completed": 1790479962000
+ },
+ "parentID": "msg_0e0ec0b58001JRNYR2QFjvJVq9",
+ "modelID": "mock-model",
+ "providerID": "mock",
+ "mode": "general",
+ "agent": "general",
+ "path": {
+ "cwd": "/work/proj",
+ "root": "/"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 1251,
+ "input": 211,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ },
+ "finish": "stop"
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ec0f09001Uxl1XYcRwdxfZv",
+ "sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+ "messageID": "msg_0e0ec0e3a001mPOUEVl1sCmZTg",
+ "type": "step-start"
+ },
+ {
+ "id": "prt_0e0ec0f11001xM5V0LIMc4ekh3",
+ "sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+ "messageID": "msg_0e0ec0e3a001mPOUEVl1sCmZTg",
+ "type": "text",
+ "text": "notes.md has a heading and two lines.",
+ "time": {
+ "start": 1790479961873,
+ "end": 1790479961980
+ }
+ },
+ {
+ "id": "prt_0e0ec0f8300122BMcV39F4W0mJ",
+ "sessionID": "ses_f1f13f4b6ffehFDFUBI5qx3Zsd",
+ "messageID": "msg_0e0ec0e3a001mPOUEVl1sCmZTg",
+ "type": "step-finish",
+ "reason": "stop",
+ "cost": 0,
+ "tokens": {
+ "total": 1251,
+ "input": 211,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ }
+ ]
+ }
+ ],
+ "children": []
+ },
+ {
+ "session": {
+ "id": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+ "slug": "kind-wizard",
+ "projectID": "global",
+ "directory": "/work/proj",
+ "path": "work/proj",
+ "parentID": "ses_f1f13f690ffe0YPBQS9qpNaxs7",
+ "summary": {
+ "additions": 0,
+ "deletions": 0,
+ "files": 0
+ },
+ "cost": 0,
+ "tokens": {
+ "input": 418,
+ "output": 80,
+ "reasoning": 0,
+ "cache": {
+ "read": 2000,
+ "write": 0
+ }
+ },
+ "title": "List folder (@general subagent)",
+ "agent": "general",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock",
+ "variant": "default"
+ },
+ "version": "1.18.32",
+ "time": {
+ "created": 1790479960962,
+ "updated": 1790479961582
+ },
+ "permission": []
+ },
+ "messages": [
+ {
+ "info": {
+ "id": "msg_0e0ec0b8d001qKf4KHIngQ5esm",
+ "sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+ "role": "user",
+ "time": {
+ "created": 1790479960975
+ },
+ "summary": {
+ "diffs": []
+ },
+ "agent": "general",
+ "model": {
+ "providerID": "mock",
+ "modelID": "mock-model"
+ }
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ec0b940010KuE6dzbLSTPhf",
+ "sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+ "messageID": "msg_0e0ec0b8d001qKf4KHIngQ5esm",
+ "type": "text",
+ "text": "CHILD-B: list the folder"
+ }
+ ]
+ },
+ {
+ "info": {
+ "id": "msg_0e0ec0bc8001WD9A3zmrls3IQN",
+ "sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+ "role": "assistant",
+ "time": {
+ "created": 1790479961032,
+ "completed": 1790479961314
+ },
+ "parentID": "msg_0e0ec0b8d001qKf4KHIngQ5esm",
+ "modelID": "mock-model",
+ "providerID": "mock",
+ "mode": "general",
+ "agent": "general",
+ "path": {
+ "cwd": "/work/proj",
+ "root": "/"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 1248,
+ "input": 208,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ },
+ "finish": "tool-calls"
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ec0c66001E7txmGBCJaZ1qB",
+ "sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+ "messageID": "msg_0e0ec0bc8001WD9A3zmrls3IQN",
+ "type": "step-start"
+ },
+ {
+ "id": "prt_0e0ec0c6c001OTYMsuy2fRX6Fg",
+ "sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+ "messageID": "msg_0e0ec0bc8001WD9A3zmrls3IQN",
+ "type": "tool",
+ "callID": "call_8_0",
+ "tool": "bash",
+ "state": {
+ "status": "completed",
+ "input": {
+ "command": "ls",
+ "description": "List folder"
+ },
+ "output": "notes.md\n",
+ "title": "ls",
+ "metadata": {
+ "output": "notes.md\n",
+ "exit": 0,
+ "truncated": false
+ },
+ "time": {
+ "start": 1790479961216,
+ "end": 1790479961300
+ }
+ }
+ },
+ {
+ "id": "prt_0e0ec0cda001JfWXEZMXyU7rXD",
+ "sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+ "messageID": "msg_0e0ec0bc8001WD9A3zmrls3IQN",
+ "type": "step-finish",
+ "reason": "tool-calls",
+ "cost": 0,
+ "tokens": {
+ "total": 1248,
+ "input": 208,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ }
+ ]
+ },
+ {
+ "info": {
+ "id": "msg_0e0ec0ce6001Cy4WbgIDNaGKHq",
+ "sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+ "role": "assistant",
+ "time": {
+ "created": 1790479961318,
+ "completed": 1790479961564
+ },
+ "parentID": "msg_0e0ec0b8d001qKf4KHIngQ5esm",
+ "modelID": "mock-model",
+ "providerID": "mock",
+ "mode": "general",
+ "agent": "general",
+ "path": {
+ "cwd": "/work/proj",
+ "root": "/"
+ },
+ "cost": 0,
+ "tokens": {
+ "total": 1250,
+ "input": 210,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ },
+ "finish": "stop"
+ },
+ "parts": [
+ {
+ "id": "prt_0e0ec0d7d001rdcpHnrV0Ve6uF",
+ "sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+ "messageID": "msg_0e0ec0ce6001Cy4WbgIDNaGKHq",
+ "type": "step-start"
+ },
+ {
+ "id": "prt_0e0ec0d81001pXh3X3V8e2t6mb",
+ "sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+ "messageID": "msg_0e0ec0ce6001Cy4WbgIDNaGKHq",
+ "type": "text",
+ "text": "The folder holds notes.md.",
+ "time": {
+ "start": 1790479961473,
+ "end": 1790479961549
+ }
+ },
+ {
+ "id": "prt_0e0ec0dd3001KevS0vGYY3i4XP",
+ "sessionID": "ses_f1f13f47dffe0UEEbHXZERyxC3",
+ "messageID": "msg_0e0ec0ce6001Cy4WbgIDNaGKHq",
+ "type": "step-finish",
+ "reason": "stop",
+ "cost": 0,
+ "tokens": {
+ "total": 1250,
+ "input": 210,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ }
+ ]
+ }
+ ],
+ "children": []
+ }
+ ]
+}
\ No newline at end of file
diff --git a/apps/server/src/engine2/fixtures/v2-nest.json b/apps/server/src/engine2/fixtures/v2-nest.json
new file mode 100644
index 00000000..f5e5fff4
--- /dev/null
+++ b/apps/server/src/engine2/fixtures/v2-nest.json
@@ -0,0 +1,418 @@
+{
+ "session": {
+ "id": "ses_f1f13b606ffel12K7Au2wc8hY8",
+ "projectID": "a34c8d566d1fcce901d1be6ac3f41a8f903e9c7d",
+ "cost": 0,
+ "tokens": {
+ "input": 688,
+ "output": 120,
+ "reasoning": 0,
+ "cache": {
+ "read": 3000,
+ "write": 0
+ }
+ },
+ "outcome": "succeeded",
+ "time": {
+ "created": 1790479976963,
+ "updated": 1790479977131,
+ "idle": 1790479978022
+ },
+ "title": "Parity session title",
+ "location": {
+ "directory": "/work/proj"
+ }
+ },
+ "messages": [
+ {
+ "id": "msg_0e0ec4a1a001wYsqsBh3umsAkX",
+ "time": {
+ "created": 1790479977013
+ },
+ "text": "PARITY-NEST go deep",
+ "type": "user"
+ },
+ {
+ "id": "msg_0e0ec4a500010pgCV3ZprOOvKl",
+ "time": {
+ "created": 1790479977072,
+ "streamed": 1790479977142,
+ "completed": 1790479977862
+ },
+ "type": "assistant",
+ "agent": "build",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock"
+ },
+ "content": [
+ {
+ "type": "tool",
+ "id": "call_28_0",
+ "name": "subagent",
+ "executed": false,
+ "state": {
+ "status": "completed",
+ "input": {
+ "agent": "general",
+ "description": "Nested level one",
+ "prompt": "CHILD-N1: delegate once more"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "<subagent sessionID=\"ses_f1f13b544ffe3zzZq9HY7Rui06\" state=\"completed\">\nLevel one done.\n</subagent>"
+ }
+ ],
+ "metadata": {
+ "sessionID": "ses_f1f13b544ffe3zzZq9HY7Rui06",
+ "status": "completed",
+ "truncated": false
+ }
+ },
+ "time": {
+ "created": 1790479977084,
+ "ran": 1790479977138,
+ "completed": 1790479977859
+ }
+ }
+ ],
+ "finish": "tool-calls",
+ "rawFinish": "tool_calls",
+ "cost": 0,
+ "tokens": {
+ "input": 228,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ },
+ {
+ "id": "msg_0e0ec4d94001yh6LSEUWLKVi83",
+ "time": {
+ "created": 1790479977894,
+ "streamed": 1790479977992,
+ "completed": 1790479977998
+ },
+ "type": "assistant",
+ "agent": "build",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "Nested run finished."
+ }
+ ],
+ "finish": "stop",
+ "rawFinish": "stop",
+ "cost": 0,
+ "tokens": {
+ "input": 233,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ },
+ {
+ "id": "msg_0e0ec4e26001t1NjuIOXyJMOnO",
+ "time": {
+ "created": 1790479978022
+ },
+ "type": "idle",
+ "outcome": "succeeded"
+ }
+ ],
+ "children": [
+ {
+ "session": {
+ "id": "ses_f1f13b544ffe3zzZq9HY7Rui06",
+ "parentID": "ses_f1f13b606ffel12K7Au2wc8hY8",
+ "projectID": "a34c8d566d1fcce901d1be6ac3f41a8f903e9c7d",
+ "agent": "general",
+ "cost": 0,
+ "tokens": {
+ "input": 461,
+ "output": 80,
+ "reasoning": 0,
+ "cache": {
+ "read": 2000,
+ "write": 0
+ }
+ },
+ "outcome": "succeeded",
+ "time": {
+ "created": 1790479977152,
+ "updated": 1790479977159,
+ "idle": 1790479977855
+ },
+ "title": "Nested level one",
+ "location": {
+ "directory": "/work/proj"
+ }
+ },
+ "messages": [
+ {
+ "id": "msg_0e0ec4ac40014Mzgyh1vGj4wrC",
+ "time": {
+ "created": 1790479977180
+ },
+ "text": "You are a subagent spawned by another session.\nCHILD-N1: delegate once more",
+ "type": "user"
+ },
+ {
+ "id": "msg_0e0ec4ae500109IjVh7FzVJFEd",
+ "time": {
+ "created": 1790479977220,
+ "streamed": 1790479977286,
+ "completed": 1790479977704
+ },
+ "type": "assistant",
+ "agent": "general",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock"
+ },
+ "content": [
+ {
+ "type": "tool",
+ "id": "call_29_0",
+ "name": "subagent",
+ "executed": false,
+ "state": {
+ "status": "completed",
+ "input": {
+ "agent": "general",
+ "description": "Nested level two",
+ "prompt": "CHILD-A: read notes.md and summarise it"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "<subagent sessionID=\"ses_f1f13b4b2ffeTbh2YYIxytmdXX\" state=\"completed\">\nnotes.md has a heading and two lines.\n</subagent>"
+ }
+ ],
+ "metadata": {
+ "sessionID": "ses_f1f13b4b2ffeTbh2YYIxytmdXX",
+ "status": "completed",
+ "truncated": false
+ }
+ },
+ "time": {
+ "created": 1790479977234,
+ "ran": 1790479977282,
+ "completed": 1790479977701
+ }
+ }
+ ],
+ "finish": "tool-calls",
+ "rawFinish": "tool_calls",
+ "cost": 0,
+ "tokens": {
+ "input": 229,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ },
+ {
+ "id": "msg_0e0ec4cfd001HXI0W8KDwcYXnm",
+ "time": {
+ "created": 1790479977752,
+ "streamed": 1790479977848,
+ "completed": 1790479977851
+ },
+ "type": "assistant",
+ "agent": "general",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "Level one done."
+ }
+ ],
+ "finish": "stop",
+ "rawFinish": "stop",
+ "cost": 0,
+ "tokens": {
+ "input": 232,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ },
+ {
+ "id": "msg_0e0ec4d7f0018XJpAShUg4Npa9",
+ "time": {
+ "created": 1790479977855
+ },
+ "type": "idle",
+ "outcome": "succeeded"
+ }
+ ],
+ "children": [
+ {
+ "session": {
+ "id": "ses_f1f13b4b2ffeTbh2YYIxytmdXX",
+ "parentID": "ses_f1f13b544ffe3zzZq9HY7Rui06",
+ "projectID": "a34c8d566d1fcce901d1be6ac3f41a8f903e9c7d",
+ "agent": "general",
+ "cost": 0,
+ "tokens": {
+ "input": 461,
+ "output": 68,
+ "reasoning": 12,
+ "cache": {
+ "read": 2000,
+ "write": 0
+ }
+ },
+ "outcome": "succeeded",
+ "time": {
+ "created": 1790479977300,
+ "updated": 1790479977309,
+ "idle": 1790479977696
+ },
+ "title": "Nested level two",
+ "location": {
+ "directory": "/work/proj"
+ }
+ },
+ "messages": [
+ {
+ "id": "msg_0e0ec4b5a001BvMsDXZ8wWbEd5",
+ "time": {
+ "created": 1790479977330
+ },
+ "text": "You are a subagent spawned by another session.\nCHILD-A: read notes.md and summarise it",
+ "type": "user"
+ },
+ {
+ "id": "msg_0e0ec4b79001dn7C7jEwWaIOGQ",
+ "time": {
+ "created": 1790479977359,
+ "streamed": 1790479977457,
+ "completed": 1790479977497
+ },
+ "type": "assistant",
+ "agent": "general",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock"
+ },
+ "content": [
+ {
+ "type": "reasoning",
+ "text": "Read the file.",
+ "state": {
+ "reasoningField": "reasoning_content"
+ },
+ "time": {
+ "created": 1790479977374,
+ "completed": 1790479977447
+ }
+ },
+ {
+ "type": "tool",
+ "id": "call_30_0",
+ "name": "read",
+ "executed": false,
+ "state": {
+ "status": "completed",
+ "input": {
+ "path": "/work/proj/notes.md"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "Read file /work/proj/notes.md, lines 1-3\n1: # Notes\n2: line one\n3: line two"
+ }
+ ],
+ "metadata": {
+ "truncated": false
+ }
+ },
+ "time": {
+ "created": 1790479977397,
+ "ran": 1790479977453,
+ "completed": 1790479977493
+ }
+ }
+ ],
+ "finish": "tool-calls",
+ "rawFinish": "tool_calls",
+ "cost": 0,
+ "tokens": {
+ "input": 230,
+ "output": 28,
+ "reasoning": 12,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ },
+ {
+ "id": "msg_0e0ec4c3100132TIGSw44f8ukv",
+ "time": {
+ "created": 1790479977551,
+ "streamed": 1790479977688,
+ "completed": 1790479977691
+ },
+ "type": "assistant",
+ "agent": "general",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "notes.md has a heading and two lines."
+ }
+ ],
+ "finish": "stop",
+ "rawFinish": "stop",
+ "cost": 0,
+ "tokens": {
+ "input": 231,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ },
+ {
+ "id": "msg_0e0ec4ce0001cS1VrODNLo0omO",
+ "time": {
+ "created": 1790479977696
+ },
+ "type": "idle",
+ "outcome": "succeeded"
+ }
+ ],
+ "children": []
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/apps/server/src/engine2/fixtures/v2-p1.json b/apps/server/src/engine2/fixtures/v2-p1.json
new file mode 100644
index 00000000..8ad46d97
--- /dev/null
+++ b/apps/server/src/engine2/fixtures/v2-p1.json
@@ -0,0 +1,298 @@
+{
+ "session": {
+ "id": "ses_f1f14fdf6ffe32y5eLxrDN6MFs",
+ "projectID": "a34c8d566d1fcce901d1be6ac3f41a8f903e9c7d",
+ "cost": 0,
+ "tokens": {
+ "input": 1015,
+ "output": 152,
+ "reasoning": 48,
+ "cache": {
+ "read": 5000,
+ "write": 0
+ }
+ },
+ "outcome": "succeeded",
+ "time": {
+ "created": 1790479893010,
+ "updated": 1790479893261,
+ "idle": 1790479894016
+ },
+ "title": "Parity session title",
+ "location": {
+ "directory": "/work/proj"
+ }
+ },
+ "messages": [
+ {
+ "id": "msg_0e0eb02300010Ie6K3lQAqUici",
+ "time": {
+ "created": 1790479893113
+ },
+ "text": "PARITY-1 create the notes file",
+ "type": "user"
+ },
+ {
+ "id": "msg_0e0eb029c001Gb432955hHZq2J",
+ "time": {
+ "created": 1790479893170,
+ "streamed": 1790479893305,
+ "completed": 1790479893443
+ },
+ "type": "assistant",
+ "agent": "build",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock"
+ },
+ "content": [
+ {
+ "type": "reasoning",
+ "text": "Look at the folder first.",
+ "state": {
+ "reasoningField": "reasoning_content"
+ },
+ "time": {
+ "created": 1790479893188,
+ "completed": 1790479893285
+ }
+ },
+ {
+ "type": "tool",
+ "id": "call_2_0",
+ "name": "shell",
+ "executed": false,
+ "state": {
+ "status": "completed",
+ "input": {
+ "command": "ls -a",
+ "description": "List files"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": ".\n..\n"
+ }
+ ],
+ "metadata": {
+ "status": "completed",
+ "truncated": false,
+ "exit": 0
+ }
+ },
+ "time": {
+ "created": 1790479893236,
+ "ran": 1790479893299,
+ "completed": 1790479893435
+ }
+ }
+ ],
+ "finish": "tool-calls",
+ "rawFinish": "tool_calls",
+ "cost": 0,
+ "tokens": {
+ "input": 202,
+ "output": 28,
+ "reasoning": 12,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ },
+ {
+ "id": "msg_0e0eb03ef001V2TaGkKtwcn9ie",
+ "time": {
+ "created": 1790479893512,
+ "streamed": 1790479893638,
+ "completed": 1790479893655
+ },
+ "type": "assistant",
+ "agent": "build",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock"
+ },
+ "content": [
+ {
+ "type": "reasoning",
+ "text": "Write the notes file.",
+ "state": {
+ "reasoningField": "reasoning_content"
+ },
+ "time": {
+ "created": 1790479893528,
+ "completed": 1790479893619
+ }
+ },
+ {
+ "type": "tool",
+ "id": "call_3_0",
+ "name": "write",
+ "executed": false,
+ "state": {
+ "status": "completed",
+ "input": {
+ "path": "/work/proj/notes.md",
+ "content": "# Notes\nline one\n"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "Created file successfully: notes.md"
+ }
+ ],
+ "metadata": {
+ "truncated": false
+ }
+ },
+ "time": {
+ "created": 1790479893566,
+ "ran": 1790479893633,
+ "completed": 1790479893648
+ }
+ }
+ ],
+ "finish": "tool-calls",
+ "rawFinish": "tool_calls",
+ "cost": 0,
+ "tokens": {
+ "input": 203,
+ "output": 28,
+ "reasoning": 12,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ },
+ {
+ "id": "msg_0e0eb04b0001KSgr6P55Kg6N8y",
+ "time": {
+ "created": 1790479893699,
+ "streamed": 1790479893807,
+ "completed": 1790479893821
+ },
+ "type": "assistant",
+ "agent": "build",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock"
+ },
+ "content": [
+ {
+ "type": "reasoning",
+ "text": "Append a line.",
+ "state": {
+ "reasoningField": "reasoning_content"
+ },
+ "time": {
+ "created": 1790479893709,
+ "completed": 1790479893791
+ }
+ },
+ {
+ "type": "tool",
+ "id": "call_4_0",
+ "name": "edit",
+ "executed": false,
+ "state": {
+ "status": "completed",
+ "input": {
+ "path": "/work/proj/notes.md",
+ "oldString": "line one",
+ "newString": "line one\nline two"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "Edited notes.md (1 replacement)"
+ }
+ ],
+ "metadata": {
+ "files": [
+ {
+ "file": "notes.md",
+ "patch": "Index: notes.md\n===================================================================\n--- notes.md\n+++ notes.md\n@@ -1,2 +1,3 @@\n # Notes\n line one\n+line two\n",
+ "status": "modified",
+ "additions": 1,
+ "deletions": 0
+ }
+ ],
+ "truncated": false
+ }
+ },
+ "time": {
+ "created": 1790479893739,
+ "ran": 1790479893802,
+ "completed": 1790479893817
+ }
+ }
+ ],
+ "finish": "tool-calls",
+ "rawFinish": "tool_calls",
+ "cost": 0,
+ "tokens": {
+ "input": 204,
+ "output": 28,
+ "reasoning": 12,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ },
+ {
+ "id": "msg_0e0eb054d001DInzE54o6PPbWT",
+ "time": {
+ "created": 1790479893856,
+ "streamed": 1790479894005,
+ "completed": 1790479894009
+ },
+ "type": "assistant",
+ "agent": "build",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock"
+ },
+ "content": [
+ {
+ "type": "reasoning",
+ "text": "Done; report.",
+ "state": {
+ "reasoningField": "reasoning_content"
+ },
+ "time": {
+ "created": 1790479893872,
+ "completed": 1790479893991
+ }
+ },
+ {
+ "type": "text",
+ "text": "Created notes.md with two lines."
+ }
+ ],
+ "finish": "stop",
+ "rawFinish": "stop",
+ "cost": 0,
+ "tokens": {
+ "input": 205,
+ "output": 28,
+ "reasoning": 12,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ },
+ {
+ "id": "msg_0e0eb0600001Z6P4VHgDiDmR03",
+ "time": {
+ "created": 1790479894016
+ },
+ "type": "idle",
+ "outcome": "succeeded"
+ }
+ ],
+ "children": []
+}
\ No newline at end of file
diff --git a/apps/server/src/engine2/fixtures/v2-sub-events.json b/apps/server/src/engine2/fixtures/v2-sub-events.json
new file mode 100644
index 00000000..56817944
--- /dev/null
+++ b/apps/server/src/engine2/fixtures/v2-sub-events.json
@@ -0,0 +1,1653 @@
+[
+{
+"id": "evt_0e0ec1d41001O66ek8oy2A9EuA",
+"type": "server.connected",
+"data": {}
+},
+{
+"id": "evt_0e0ec1f3f001ON02J5GX7d07c3",
+"created": 1790479966015,
+"type": "session.created",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"slug": "mighty-lagoon",
+"version": "2.0.18",
+"projectID": "a34c8d566d1fcce901d1be6ac3f41a8f903e9c7d",
+"location": {
+"directory": "/work/proj"
+},
+"subpath": ""
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 0,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec1f59001XPwuINOKU8PWhQ",
+"created": 1790479966041,
+"type": "project.updated",
+"data": {
+"id": "a34c8d566d1fcce901d1be6ac3f41a8f903e9c7d",
+"canonical": "/work/proj",
+"time": {
+"created": 1790479865433,
+"updated": 1790479865433,
+"active": 1790479966040
+},
+"sandboxes": []
+}
+},
+{
+"id": "evt_0e0ec1f69001UlIUQg4W460v8G",
+"created": 1790479966057,
+"type": "session.inbox.enqueued",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"inboxID": "msg_0e0ec1f660019qW5hlMuhfxia5",
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"item": {
+"type": "user",
+"payload": {
+"text": "PARITY-SUB use two helpers"
+},
+"delivery": "steer"
+}
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 1,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec1f6e001funPfpy7SOnigW",
+"created": 1790479966062,
+"type": "session.execution.started",
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM"
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 2,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec1f830012k5Oooc10LOEjA",
+"created": 1790479966084,
+"metadata": {
+"instructions": {
+"initial": true
+}
+},
+"type": "session.instructions.updated",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"delta": {
+"core/environment": "d06cc2cf8afd979b0c8ea0e1e49c466c37d37f805359c2493ab1d3ae6ee6677a",
+"core/date": "31838d1728bba7c14ba6819d8964efd7aeb4f8166e852d256bb379f02c02ae4c",
+"core/codemode": "616a7ad8b8e40e8a71eab238dfbbe9eaf0f4a9e6fdad853226d075bfe602e1e6",
+"core/skill-guidance": "8394362d28c82fa4d13c7a9f5568c05680f6687e07db8f426a0e3c92f3027dc9"
+}
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 3,
+"version": 2
+}
+},
+{
+"id": "evt_0e0ec1f8800185lo5ZHoKQMY9f",
+"created": 1790479966088,
+"type": "session.inbox.delivered",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"inboxID": "msg_0e0ec1f660019qW5hlMuhfxia5"
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 4,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec1fcc001ZFpw7JfmDrCP77",
+"created": 1790479966156,
+"type": "session.step.started",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"agent": "build",
+"model": {
+"id": "mock-model",
+"providerID": "mock"
+},
+"assistantMessageID": "msg_0e0ec1fa6001GZ9bRlOF6m6y1c",
+"started": 1790479966146
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 5,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec1fcf001y290LR6NR0S6ty",
+"created": 1790479966159,
+"type": "session.reasoning.started",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"assistantMessageID": "msg_0e0ec1fa6001GZ9bRlOF6m6y1c",
+"ordinal": 0,
+"state": {
+"reasoningField": "reasoning_content"
+}
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 6,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec1ff800107LNyEy1NRgAjN",
+"created": 1790479966200,
+"type": "session.reasoning.delta",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"assistantMessageID": "msg_0e0ec1fa6001GZ9bRlOF6m6y1c",
+"ordinal": 0,
+"delta": "Delegate to two helpers."
+}
+},
+{
+"id": "evt_0e0ec1ff9001qMHlENwLRUZgDU",
+"created": 1790479966201,
+"type": "session.tool.input.started",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"assistantMessageID": "msg_0e0ec1fa6001GZ9bRlOF6m6y1c",
+"id": "call_14_0",
+"name": "subagent"
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 7,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec1fff00149QDu3TRe6RvhN",
+"created": 1790479966207,
+"type": "session.tool.input.started",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"assistantMessageID": "msg_0e0ec1fa6001GZ9bRlOF6m6y1c",
+"id": "call_14_1",
+"name": "subagent"
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 8,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec2008001gdAgvR0YBAEyiy",
+"created": 1790479966216,
+"type": "session.usage.updated",
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"cost": 0,
+"tokens": {
+"input": 213,
+"output": 40,
+"reasoning": 0,
+"cache": {
+"read": 1000,
+"write": 0
+}
+}
+}
+},
+{
+"id": "evt_0e0ec2009001bn7FL7skcT24mo",
+"created": 1790479966217,
+"type": "session.renamed",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"title": "Parity session title"
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 10,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec202a001JWJSDY2ZtcWVNe",
+"created": 1790479966250,
+"type": "session.reasoning.ended",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"assistantMessageID": "msg_0e0ec1fa6001GZ9bRlOF6m6y1c",
+"ordinal": 0,
+"text": "Delegate to two helpers.",
+"state": {
+"reasoningField": "reasoning_content"
+}
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 11,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec202f001vXfORt093YhMaa",
+"created": 1790479966255,
+"type": "session.tool.input.ended",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"assistantMessageID": "msg_0e0ec1fa6001GZ9bRlOF6m6y1c",
+"id": "call_14_0",
+"text": "{\"agent\":\"general\",\"description\":\"Read notes\",\"prompt\":\"CHILD-A: read notes.md and summarise it\"}"
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 12,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec2033001fpiW9qpOpDCInz",
+"created": 1790479966259,
+"type": "session.tool.called",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"assistantMessageID": "msg_0e0ec1fa6001GZ9bRlOF6m6y1c",
+"id": "call_14_0",
+"input": {
+"agent": "general",
+"description": "Read notes",
+"prompt": "CHILD-A: read notes.md and summarise it"
+},
+"executed": false
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 13,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec2037001yKplIzTcgkFBGm",
+"created": 1790479966263,
+"type": "session.tool.input.ended",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"assistantMessageID": "msg_0e0ec1fa6001GZ9bRlOF6m6y1c",
+"id": "call_14_1",
+"text": "{\"agent\":\"general\",\"description\":\"List folder\",\"prompt\":\"CHILD-B: list the folder\"}"
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 14,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec203b001zZGyovto06j9sg",
+"created": 1790479966267,
+"type": "session.tool.called",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"assistantMessageID": "msg_0e0ec1fa6001GZ9bRlOF6m6y1c",
+"id": "call_14_1",
+"input": {
+"agent": "general",
+"description": "List folder",
+"prompt": "CHILD-B: list the folder"
+},
+"executed": false
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 15,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec2041001eBYPPJpkv8RQJy",
+"created": 1790479966273,
+"type": "session.step.streamed",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"assistantMessageID": "msg_0e0ec1fa6001GZ9bRlOF6m6y1c"
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 16,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec20630013I6lNYzO7lyTBp",
+"created": 1790479966307,
+"type": "session.created",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"slug": "sunny-river",
+"version": "2.0.18",
+"projectID": "a34c8d566d1fcce901d1be6ac3f41a8f903e9c7d",
+"parentID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"location": {
+"directory": "/work/proj"
+},
+"subpath": "",
+"title": "List folder",
+"agent": "general"
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"seq": 0,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec2068001h4cOuLpzjdCndk",
+"created": 1790479966312,
+"type": "session.tool.progress",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"assistantMessageID": "msg_0e0ec1fa6001GZ9bRlOF6m6y1c",
+"id": "call_14_1",
+"metadata": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"status": "running"
+}
+}
+},
+{
+"id": "evt_0e0ec206c0013A3QUqxNiGTmnl",
+"created": 1790479966316,
+"type": "session.inbox.enqueued",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"inboxID": "msg_0e0ec206a001GLZFj5hw1kDiBK",
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"item": {
+"type": "user",
+"payload": {
+"text": "You are a subagent spawned by another session.\nCHILD-B: list the folder"
+},
+"delivery": "steer"
+}
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"seq": 1,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec2071001wgajk6Wj2332u6",
+"created": 1790479966321,
+"type": "session.created",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"slug": "lucky-island",
+"version": "2.0.18",
+"projectID": "a34c8d566d1fcce901d1be6ac3f41a8f903e9c7d",
+"parentID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"location": {
+"directory": "/work/proj"
+},
+"subpath": "",
+"title": "Read notes",
+"agent": "general"
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"seq": 0,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec207300141wtE1jwPNq2ua",
+"created": 1790479966323,
+"type": "session.tool.progress",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"assistantMessageID": "msg_0e0ec1fa6001GZ9bRlOF6m6y1c",
+"id": "call_14_0",
+"metadata": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"status": "running"
+}
+}
+},
+{
+"id": "evt_0e0ec2076001yc2tLY1kE6EtGU",
+"created": 1790479966326,
+"type": "session.inbox.enqueued",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"inboxID": "msg_0e0ec2074001V4UxN3Im17hT5V",
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"item": {
+"type": "user",
+"payload": {
+"text": "You are a subagent spawned by another session.\nCHILD-A: read notes.md and summarise it"
+},
+"delivery": "steer"
+}
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"seq": 1,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec2079001evZANr104nNDyS",
+"created": 1790479966329,
+"type": "session.execution.started",
+"data": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx"
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"seq": 2,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec20840010IBTwtA5las2sS",
+"created": 1790479966340,
+"metadata": {
+"instructions": {
+"initial": true
+}
+},
+"type": "session.instructions.updated",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"delta": {
+"core/environment": "0938fca5d7e08ca0c829193cfda9e7acfa82ad6c5753ce10372adf02c88c215f",
+"core/date": "31838d1728bba7c14ba6819d8964efd7aeb4f8166e852d256bb379f02c02ae4c",
+"core/codemode": "616a7ad8b8e40e8a71eab238dfbbe9eaf0f4a9e6fdad853226d075bfe602e1e6",
+"core/skill-guidance": "8394362d28c82fa4d13c7a9f5568c05680f6687e07db8f426a0e3c92f3027dc9"
+}
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"seq": 3,
+"version": 2
+}
+},
+{
+"id": "evt_0e0ec2088001QW4lNvb2E8exZT",
+"created": 1790479966344,
+"type": "session.inbox.delivered",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"inboxID": "msg_0e0ec206a001GLZFj5hw1kDiBK"
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"seq": 4,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec20a9001vRP0DQLigyUe8X",
+"created": 1790479966377,
+"type": "session.execution.started",
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE"
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"seq": 2,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec20b50015CNjQsP2SdOInv",
+"created": 1790479966389,
+"metadata": {
+"instructions": {
+"initial": true
+}
+},
+"type": "session.instructions.updated",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"delta": {
+"core/environment": "2a0e57c4917b8edc3562e04592329bea0c327e6beeffc9f7c2d3e214f9c706ea",
+"core/date": "31838d1728bba7c14ba6819d8964efd7aeb4f8166e852d256bb379f02c02ae4c",
+"core/codemode": "616a7ad8b8e40e8a71eab238dfbbe9eaf0f4a9e6fdad853226d075bfe602e1e6",
+"core/skill-guidance": "8394362d28c82fa4d13c7a9f5568c05680f6687e07db8f426a0e3c92f3027dc9"
+}
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"seq": 3,
+"version": 2
+}
+},
+{
+"id": "evt_0e0ec20b9001Fg17wD70tL9IoS",
+"created": 1790479966393,
+"type": "session.inbox.delivered",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"inboxID": "msg_0e0ec2074001V4UxN3Im17hT5V"
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"seq": 4,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec20de0015SdIbI7Vv0cEkJ",
+"created": 1790479966430,
+"type": "session.step.started",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"agent": "general",
+"model": {
+"id": "mock-model",
+"providerID": "mock"
+},
+"assistantMessageID": "msg_0e0ec2090001werAciyouOYr7H",
+"started": 1790479966374
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"seq": 5,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec20e1001RAnT3qnUQX8HTw",
+"created": 1790479966433,
+"type": "session.tool.input.started",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"assistantMessageID": "msg_0e0ec2090001werAciyouOYr7H",
+"id": "call_15_0",
+"name": "shell"
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"seq": 6,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec20e6001WZcVUUdB1UGzFL",
+"created": 1790479966438,
+"type": "session.tool.input.ended",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"assistantMessageID": "msg_0e0ec2090001werAciyouOYr7H",
+"id": "call_15_0",
+"text": "{\"command\":\"ls\",\"description\":\"List folder\"}"
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"seq": 7,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec20e90014Ia1rHrP1y5e8U",
+"created": 1790479966441,
+"type": "session.tool.called",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"assistantMessageID": "msg_0e0ec2090001werAciyouOYr7H",
+"id": "call_15_0",
+"input": {
+"command": "ls",
+"description": "List folder"
+},
+"executed": false
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"seq": 8,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec20ec001e1qYMcHnTOxF36",
+"created": 1790479966444,
+"type": "session.step.streamed",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"assistantMessageID": "msg_0e0ec2090001werAciyouOYr7H"
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"seq": 9,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec20ef0012YeEPVJ6lfG00A",
+"created": 1790479966447,
+"type": "session.step.started",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"agent": "general",
+"model": {
+"id": "mock-model",
+"providerID": "mock"
+},
+"assistantMessageID": "msg_0e0ec20c4001118N4AF962vqVE",
+"started": 1790479966425
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"seq": 5,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec20f2001LHyCrT7m6p1YXc",
+"created": 1790479966450,
+"type": "session.reasoning.started",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"assistantMessageID": "msg_0e0ec20c4001118N4AF962vqVE",
+"ordinal": 0,
+"state": {
+"reasoningField": "reasoning_content"
+}
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"seq": 6,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec21000014fMaCoZfZprQK8",
+"created": 1790479966464,
+"type": "shell.created",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"info": {
+"id": "sh_0e0ec20fc0018K22cqEoMKoJN3",
+"status": "running",
+"command": "ls",
+"cwd": "/work/proj",
+"shell": "/bin/bash",
+"file": "/data/opencode/shell/a34c8d566d1fcce901d1be6ac3f41a8f903e9c7d/sh_0e0ec20fc0018K22cqEoMKoJN3.out",
+"metadata": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx"
+},
+"time": {
+"started": 1790479966460
+}
+}
+}
+},
+{
+"id": "evt_0e0ec2118001Pv2AtZ5hO569VF",
+"created": 1790479966488,
+"type": "session.tool.progress",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"assistantMessageID": "msg_0e0ec2090001werAciyouOYr7H",
+"id": "call_15_0",
+"metadata": {
+"shellID": "sh_0e0ec20fc0018K22cqEoMKoJN3"
+}
+}
+},
+{
+"id": "evt_0e0ec211b001UQoX3SvOSYerVG",
+"created": 1790479966491,
+"type": "session.reasoning.delta",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"assistantMessageID": "msg_0e0ec20c4001118N4AF962vqVE",
+"ordinal": 0,
+"delta": "Read the file."
+}
+},
+{
+"id": "evt_0e0ec211c001f5vztJOsYAlbqw",
+"created": 1790479966492,
+"type": "session.tool.input.started",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"assistantMessageID": "msg_0e0ec20c4001118N4AF962vqVE",
+"id": "call_16_0",
+"name": "read"
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"seq": 7,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec212700110r8IpUEk2NPXS",
+"created": 1790479966503,
+"type": "shell.exited",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"id": "sh_0e0ec20fc0018K22cqEoMKoJN3",
+"exit": 0,
+"status": "exited"
+}
+},
+{
+"id": "evt_0e0ec212a001z5fvADNZ1zG1xx",
+"created": 1790479966506,
+"type": "session.tool.success",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"assistantMessageID": "msg_0e0ec2090001werAciyouOYr7H",
+"id": "call_15_0",
+"content": [
+{
+"type": "text",
+"text": "notes.md\n"
+}
+],
+"metadata": {
+"status": "completed",
+"truncated": false,
+"exit": 0
+},
+"executed": false
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"seq": 10,
+"version": 2
+}
+},
+{
+"id": "evt_0e0ec212e001fLzTu6w06KSQKJ",
+"created": 1790479966510,
+"type": "session.step.ended",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"assistantMessageID": "msg_0e0ec2090001werAciyouOYr7H",
+"finish": "tool-calls",
+"rawFinish": "tool_calls",
+"cost": 0,
+"tokens": {
+"input": 215,
+"output": 40,
+"reasoning": 0,
+"cache": {
+"read": 1000,
+"write": 0
+}
+}
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"seq": 11,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec2133001rWUvatL90g93sk",
+"created": 1790479966515,
+"type": "session.usage.updated",
+"data": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"cost": 0,
+"tokens": {
+"input": 215,
+"output": 40,
+"reasoning": 0,
+"cache": {
+"read": 1000,
+"write": 0
+}
+}
+}
+},
+{
+"id": "evt_0e0ec216b0010H95ewZEz8jS8m",
+"created": 1790479966571,
+"type": "session.reasoning.ended",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"assistantMessageID": "msg_0e0ec20c4001118N4AF962vqVE",
+"ordinal": 0,
+"text": "Read the file.",
+"state": {
+"reasoningField": "reasoning_content"
+}
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"seq": 8,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec216e001EFXV3sWV4CKBHD",
+"created": 1790479966574,
+"type": "session.tool.input.ended",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"assistantMessageID": "msg_0e0ec20c4001118N4AF962vqVE",
+"id": "call_16_0",
+"text": "{\"path\":\"/work/proj/notes.md\"}"
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"seq": 9,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec2172001nHapNveGtK4kw0",
+"created": 1790479966578,
+"type": "session.tool.called",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"assistantMessageID": "msg_0e0ec20c4001118N4AF962vqVE",
+"id": "call_16_0",
+"input": {
+"path": "/work/proj/notes.md"
+},
+"executed": false
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"seq": 10,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec2175001WZnzeMGkQC5TWT",
+"created": 1790479966581,
+"type": "session.step.streamed",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"assistantMessageID": "msg_0e0ec20c4001118N4AF962vqVE"
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"seq": 11,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec217a0014znPpGIcVO2wC6",
+"created": 1790479966586,
+"type": "session.step.started",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"agent": "general",
+"model": {
+"id": "mock-model",
+"providerID": "mock"
+},
+"assistantMessageID": "msg_0e0ec21480014ACPlK4Y92Rd3E",
+"started": 1790479966565
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"seq": 12,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec217e001iSzAYsfkdlFq0T",
+"created": 1790479966590,
+"type": "session.text.started",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"assistantMessageID": "msg_0e0ec21480014ACPlK4Y92Rd3E",
+"ordinal": 0
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"seq": 13,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec2198001uOy0Lq2uiiYKbh",
+"created": 1790479966616,
+"type": "session.tool.success",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"assistantMessageID": "msg_0e0ec20c4001118N4AF962vqVE",
+"id": "call_16_0",
+"content": [
+{
+"type": "text",
+"text": "Read file /work/proj/notes.md, lines 1-3\n1: # Notes\n2: line one\n3: line two"
+}
+],
+"metadata": {
+"truncated": false
+},
+"executed": false
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"seq": 12,
+"version": 2
+}
+},
+{
+"id": "evt_0e0ec21a0001cG3CtcUN9rpu4L",
+"created": 1790479966624,
+"type": "session.step.ended",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"assistantMessageID": "msg_0e0ec20c4001118N4AF962vqVE",
+"finish": "tool-calls",
+"rawFinish": "tool_calls",
+"cost": 0,
+"tokens": {
+"input": 216,
+"output": 28,
+"reasoning": 12,
+"cache": {
+"read": 1000,
+"write": 0
+}
+}
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"seq": 13,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec21a5001061KMkh6yx6Ps8",
+"created": 1790479966629,
+"type": "session.usage.updated",
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"cost": 0,
+"tokens": {
+"input": 216,
+"output": 28,
+"reasoning": 12,
+"cache": {
+"read": 1000,
+"write": 0
+}
+}
+}
+},
+{
+"id": "evt_0e0ec21c8001eetNQUV7O0kNmz",
+"created": 1790479966664,
+"type": "session.step.started",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"agent": "general",
+"model": {
+"id": "mock-model",
+"providerID": "mock"
+},
+"assistantMessageID": "msg_0e0ec21b2001LWN1MnhyphTfOO",
+"started": 1790479966658
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"seq": 14,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec21cb001jPxTlhFD2oH2Ox",
+"created": 1790479966667,
+"type": "session.text.started",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"assistantMessageID": "msg_0e0ec21b2001LWN1MnhyphTfOO",
+"ordinal": 0
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"seq": 15,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec21cf001jV2jEOiJYB7xuK",
+"created": 1790479966671,
+"type": "session.text.delta",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"assistantMessageID": "msg_0e0ec21480014ACPlK4Y92Rd3E",
+"ordinal": 0,
+"delta": "The folder holds notes.md."
+}
+},
+{
+"id": "evt_0e0ec21cf0020CP4mdI22JtX3X",
+"created": 1790479966671,
+"type": "session.text.ended",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"assistantMessageID": "msg_0e0ec21480014ACPlK4Y92Rd3E",
+"ordinal": 0,
+"text": "The folder holds notes.md."
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"seq": 14,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec21d3001YadvLKQsWnO1uN",
+"created": 1790479966675,
+"type": "session.step.streamed",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"assistantMessageID": "msg_0e0ec21480014ACPlK4Y92Rd3E"
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"seq": 15,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec21d6001GDEeGNefC1Ak5N",
+"created": 1790479966678,
+"type": "session.step.ended",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"assistantMessageID": "msg_0e0ec21480014ACPlK4Y92Rd3E",
+"finish": "stop",
+"rawFinish": "stop",
+"cost": 0,
+"tokens": {
+"input": 217,
+"output": 40,
+"reasoning": 0,
+"cache": {
+"read": 1000,
+"write": 0
+}
+}
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"seq": 16,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec21da001i2kK8SopEKPLVH",
+"created": 1790479966682,
+"type": "session.usage.updated",
+"data": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"cost": 0,
+"tokens": {
+"input": 432,
+"output": 80,
+"reasoning": 0,
+"cache": {
+"read": 2000,
+"write": 0
+}
+}
+}
+},
+{
+"id": "evt_0e0ec21db001wtPbUF18uj5Kio",
+"created": 1790479966683,
+"type": "session.execution.succeeded",
+"data": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx"
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"seq": 17,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec21e0001w7d1p1lR1DPPHk",
+"created": 1790479966688,
+"type": "session.tool.success",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"assistantMessageID": "msg_0e0ec1fa6001GZ9bRlOF6m6y1c",
+"id": "call_14_1",
+"content": [
+{
+"type": "text",
+"text": "<subagent sessionID=\"ses_f1f13dfb3ffeIzHsslPAtC1LRx\" state=\"completed\">\nThe folder holds notes.md.\n</subagent>"
+}
+],
+"metadata": {
+"sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+"status": "completed",
+"truncated": false
+},
+"executed": false
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 17,
+"version": 2
+}
+},
+{
+"id": "evt_0e0ec2232001hxZrG7fOA1457p",
+"created": 1790479966770,
+"type": "session.text.delta",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"assistantMessageID": "msg_0e0ec21b2001LWN1MnhyphTfOO",
+"ordinal": 0,
+"delta": "notes.md has a heading and two lines."
+}
+},
+{
+"id": "evt_0e0ec22460019HPiuvBs4LNIfE",
+"created": 1790479966790,
+"type": "session.text.ended",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"assistantMessageID": "msg_0e0ec21b2001LWN1MnhyphTfOO",
+"ordinal": 0,
+"text": "notes.md has a heading and two lines."
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"seq": 16,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec224c001v326E2OhEbfkPl",
+"created": 1790479966796,
+"type": "session.step.streamed",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"assistantMessageID": "msg_0e0ec21b2001LWN1MnhyphTfOO"
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"seq": 17,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec224f0011R1eUazQZGHNKN",
+"created": 1790479966799,
+"type": "session.step.ended",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"assistantMessageID": "msg_0e0ec21b2001LWN1MnhyphTfOO",
+"finish": "stop",
+"rawFinish": "stop",
+"cost": 0,
+"tokens": {
+"input": 218,
+"output": 40,
+"reasoning": 0,
+"cache": {
+"read": 1000,
+"write": 0
+}
+}
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"seq": 18,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec2253001ZDoLUGW2NceKl8",
+"created": 1790479966803,
+"type": "session.usage.updated",
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"cost": 0,
+"tokens": {
+"input": 434,
+"output": 68,
+"reasoning": 12,
+"cache": {
+"read": 2000,
+"write": 0
+}
+}
+}
+},
+{
+"id": "evt_0e0ec2255001BM5U9NSDgZzMSy",
+"created": 1790479966805,
+"type": "session.execution.succeeded",
+"data": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE"
+},
+"durable": {
+"aggregateID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"seq": 19,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec2259001gYP11LhFUEfv3J",
+"created": 1790479966809,
+"type": "session.tool.success",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"assistantMessageID": "msg_0e0ec1fa6001GZ9bRlOF6m6y1c",
+"id": "call_14_0",
+"content": [
+{
+"type": "text",
+"text": "<subagent sessionID=\"ses_f1f13dfb6ffeZS9tCB4p35mmoE\" state=\"completed\">\nnotes.md has a heading and two lines.\n</subagent>"
+}
+],
+"metadata": {
+"sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+"status": "completed",
+"truncated": false
+},
+"executed": false
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 18,
+"version": 2
+}
+},
+{
+"id": "evt_0e0ec225d001k8wZhpznUeJXET",
+"created": 1790479966813,
+"type": "session.step.ended",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"assistantMessageID": "msg_0e0ec1fa6001GZ9bRlOF6m6y1c",
+"finish": "tool-calls",
+"rawFinish": "tool_calls",
+"cost": 0,
+"tokens": {
+"input": 214,
+"output": 28,
+"reasoning": 12,
+"cache": {
+"read": 1000,
+"write": 0
+}
+}
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 19,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec2260001eXFeZwvjY4WHsy",
+"created": 1790479966816,
+"type": "session.usage.updated",
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"cost": 0,
+"tokens": {
+"input": 427,
+"output": 68,
+"reasoning": 12,
+"cache": {
+"read": 2000,
+"write": 0
+}
+}
+}
+},
+{
+"id": "evt_0e0ec228b001uWC01fAgt9CmKP",
+"created": 1790479966859,
+"type": "session.step.started",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"agent": "build",
+"model": {
+"id": "mock-model",
+"providerID": "mock"
+},
+"assistantMessageID": "msg_0e0ec226f0010OfGce9PlSXV63",
+"started": 1790479966850
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 20,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec22920015R252P7VfaIwV5",
+"created": 1790479966866,
+"type": "session.text.started",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"assistantMessageID": "msg_0e0ec226f0010OfGce9PlSXV63",
+"ordinal": 0
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 21,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec22db001MUv6a39QgvG1gJ",
+"created": 1790479966939,
+"type": "session.text.delta",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"assistantMessageID": "msg_0e0ec226f0010OfGce9PlSXV63",
+"ordinal": 0,
+"delta": "Both helpers finished."
+}
+},
+{
+"id": "evt_0e0ec22dc001d95TcuN0qTQtk5",
+"created": 1790479966940,
+"type": "session.text.ended",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"assistantMessageID": "msg_0e0ec226f0010OfGce9PlSXV63",
+"ordinal": 0,
+"text": "Both helpers finished."
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 22,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec22e7001h7m40zMeoPBOWh",
+"created": 1790479966951,
+"type": "session.step.streamed",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"assistantMessageID": "msg_0e0ec226f0010OfGce9PlSXV63"
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 23,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec22eb001UGiRf8oYRvXusw",
+"created": 1790479966955,
+"type": "session.step.ended",
+"location": {
+"directory": "/work/proj"
+},
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"assistantMessageID": "msg_0e0ec226f0010OfGce9PlSXV63",
+"finish": "stop",
+"rawFinish": "stop",
+"cost": 0,
+"tokens": {
+"input": 219,
+"output": 40,
+"reasoning": 0,
+"cache": {
+"read": 1000,
+"write": 0
+}
+}
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 24,
+"version": 1
+}
+},
+{
+"id": "evt_0e0ec22ef001O3fM0obBZmnqfj",
+"created": 1790479966959,
+"type": "session.usage.updated",
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"cost": 0,
+"tokens": {
+"input": 646,
+"output": 108,
+"reasoning": 12,
+"cache": {
+"read": 3000,
+"write": 0
+}
+}
+}
+},
+{
+"id": "evt_0e0ec22f1001cNkC0EpAcH0ynC",
+"created": 1790479966961,
+"type": "session.execution.succeeded",
+"data": {
+"sessionID": "ses_f1f13e0ccffe5XtNqflQuhSMLM"
+},
+"durable": {
+"aggregateID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+"seq": 25,
+"version": 1
+}
+}
+]
\ No newline at end of file
diff --git a/apps/server/src/engine2/fixtures/v2-sub.json b/apps/server/src/engine2/fixtures/v2-sub.json
new file mode 100644
index 00000000..fae97c3b
--- /dev/null
+++ b/apps/server/src/engine2/fixtures/v2-sub.json
@@ -0,0 +1,457 @@
+{
+ "session": {
+ "id": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+ "projectID": "a34c8d566d1fcce901d1be6ac3f41a8f903e9c7d",
+ "cost": 0,
+ "tokens": {
+ "input": 646,
+ "output": 108,
+ "reasoning": 12,
+ "cache": {
+ "read": 3000,
+ "write": 0
+ }
+ },
+ "outcome": "succeeded",
+ "time": {
+ "created": 1790479966015,
+ "updated": 1790479966217,
+ "idle": 1790479966961
+ },
+ "title": "Parity session title",
+ "location": {
+ "directory": "/work/proj"
+ }
+ },
+ "messages": [
+ {
+ "id": "msg_0e0ec1f660019qW5hlMuhfxia5",
+ "time": {
+ "created": 1790479966088
+ },
+ "text": "PARITY-SUB use two helpers",
+ "type": "user"
+ },
+ {
+ "id": "msg_0e0ec1fa6001GZ9bRlOF6m6y1c",
+ "time": {
+ "created": 1790479966146,
+ "streamed": 1790479966273,
+ "completed": 1790479966813
+ },
+ "type": "assistant",
+ "agent": "build",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock"
+ },
+ "content": [
+ {
+ "type": "reasoning",
+ "text": "Delegate to two helpers.",
+ "state": {
+ "reasoningField": "reasoning_content"
+ },
+ "time": {
+ "created": 1790479966159,
+ "completed": 1790479966250
+ }
+ },
+ {
+ "type": "tool",
+ "id": "call_14_0",
+ "name": "subagent",
+ "executed": false,
+ "state": {
+ "status": "completed",
+ "input": {
+ "agent": "general",
+ "description": "Read notes",
+ "prompt": "CHILD-A: read notes.md and summarise it"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "<subagent sessionID=\"ses_f1f13dfb6ffeZS9tCB4p35mmoE\" state=\"completed\">\nnotes.md has a heading and two lines.\n</subagent>"
+ }
+ ],
+ "metadata": {
+ "sessionID": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+ "status": "completed",
+ "truncated": false
+ }
+ },
+ "time": {
+ "created": 1790479966201,
+ "ran": 1790479966259,
+ "completed": 1790479966809
+ }
+ },
+ {
+ "type": "tool",
+ "id": "call_14_1",
+ "name": "subagent",
+ "executed": false,
+ "state": {
+ "status": "completed",
+ "input": {
+ "agent": "general",
+ "description": "List folder",
+ "prompt": "CHILD-B: list the folder"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "<subagent sessionID=\"ses_f1f13dfb3ffeIzHsslPAtC1LRx\" state=\"completed\">\nThe folder holds notes.md.\n</subagent>"
+ }
+ ],
+ "metadata": {
+ "sessionID": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+ "status": "completed",
+ "truncated": false
+ }
+ },
+ "time": {
+ "created": 1790479966207,
+ "ran": 1790479966267,
+ "completed": 1790479966688
+ }
+ }
+ ],
+ "finish": "tool-calls",
+ "rawFinish": "tool_calls",
+ "cost": 0,
+ "tokens": {
+ "input": 214,
+ "output": 28,
+ "reasoning": 12,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ },
+ {
+ "id": "msg_0e0ec226f0010OfGce9PlSXV63",
+ "time": {
+ "created": 1790479966850,
+ "streamed": 1790479966951,
+ "completed": 1790479966955
+ },
+ "type": "assistant",
+ "agent": "build",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "Both helpers finished."
+ }
+ ],
+ "finish": "stop",
+ "rawFinish": "stop",
+ "cost": 0,
+ "tokens": {
+ "input": 219,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ },
+ {
+ "id": "msg_0e0ec22f1001cNkC0EpAcH0ynC",
+ "time": {
+ "created": 1790479966961
+ },
+ "type": "idle",
+ "outcome": "succeeded"
+ }
+ ],
+ "children": [
+ {
+ "session": {
+ "id": "ses_f1f13dfb3ffeIzHsslPAtC1LRx",
+ "parentID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+ "projectID": "a34c8d566d1fcce901d1be6ac3f41a8f903e9c7d",
+ "agent": "general",
+ "cost": 0,
+ "tokens": {
+ "input": 432,
+ "output": 80,
+ "reasoning": 0,
+ "cache": {
+ "read": 2000,
+ "write": 0
+ }
+ },
+ "outcome": "succeeded",
+ "time": {
+ "created": 1790479966307,
+ "updated": 1790479966316,
+ "idle": 1790479966683
+ },
+ "title": "List folder",
+ "location": {
+ "directory": "/work/proj"
+ }
+ },
+ "messages": [
+ {
+ "id": "msg_0e0ec206a001GLZFj5hw1kDiBK",
+ "time": {
+ "created": 1790479966344
+ },
+ "text": "You are a subagent spawned by another session.\nCHILD-B: list the folder",
+ "type": "user"
+ },
+ {
+ "id": "msg_0e0ec2090001werAciyouOYr7H",
+ "time": {
+ "created": 1790479966374,
+ "streamed": 1790479966444,
+ "completed": 1790479966510
+ },
+ "type": "assistant",
+ "agent": "general",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock"
+ },
+ "content": [
+ {
+ "type": "tool",
+ "id": "call_15_0",
+ "name": "shell",
+ "executed": false,
+ "state": {
+ "status": "completed",
+ "input": {
+ "command": "ls",
+ "description": "List folder"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "notes.md\n"
+ }
+ ],
+ "metadata": {
+ "status": "completed",
+ "truncated": false,
+ "exit": 0
+ }
+ },
+ "time": {
+ "created": 1790479966433,
+ "ran": 1790479966441,
+ "completed": 1790479966506
+ }
+ }
+ ],
+ "finish": "tool-calls",
+ "rawFinish": "tool_calls",
+ "cost": 0,
+ "tokens": {
+ "input": 215,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ },
+ {
+ "id": "msg_0e0ec21480014ACPlK4Y92Rd3E",
+ "time": {
+ "created": 1790479966565,
+ "streamed": 1790479966675,
+ "completed": 1790479966678
+ },
+ "type": "assistant",
+ "agent": "general",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "The folder holds notes.md."
+ }
+ ],
+ "finish": "stop",
+ "rawFinish": "stop",
+ "cost": 0,
+ "tokens": {
+ "input": 217,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ },
+ {
+ "id": "msg_0e0ec21db001wtPbUF18uj5Kio",
+ "time": {
+ "created": 1790479966683
+ },
+ "type": "idle",
+ "outcome": "succeeded"
+ }
+ ],
+ "children": []
+ },
+ {
+ "session": {
+ "id": "ses_f1f13dfb6ffeZS9tCB4p35mmoE",
+ "parentID": "ses_f1f13e0ccffe5XtNqflQuhSMLM",
+ "projectID": "a34c8d566d1fcce901d1be6ac3f41a8f903e9c7d",
+ "agent": "general",
+ "cost": 0,
+ "tokens": {
+ "input": 434,
+ "output": 68,
+ "reasoning": 12,
+ "cache": {
+ "read": 2000,
+ "write": 0
+ }
+ },
+ "outcome": "succeeded",
+ "time": {
+ "created": 1790479966321,
+ "updated": 1790479966326,
+ "idle": 1790479966805
+ },
+ "title": "Read notes",
+ "location": {
+ "directory": "/work/proj"
+ }
+ },
+ "messages": [
+ {
+ "id": "msg_0e0ec2074001V4UxN3Im17hT5V",
+ "time": {
+ "created": 1790479966393
+ },
+ "text": "You are a subagent spawned by another session.\nCHILD-A: read notes.md and summarise it",
+ "type": "user"
+ },
+ {
+ "id": "msg_0e0ec20c4001118N4AF962vqVE",
+ "time": {
+ "created": 1790479966425,
+ "streamed": 1790479966581,
+ "completed": 1790479966624
+ },
+ "type": "assistant",
+ "agent": "general",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock"
+ },
+ "content": [
+ {
+ "type": "reasoning",
+ "text": "Read the file.",
+ "state": {
+ "reasoningField": "reasoning_content"
+ },
+ "time": {
+ "created": 1790479966450,
+ "completed": 1790479966571
+ }
+ },
+ {
+ "type": "tool",
+ "id": "call_16_0",
+ "name": "read",
+ "executed": false,
+ "state": {
+ "status": "completed",
+ "input": {
+ "path": "/work/proj/notes.md"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "Read file /work/proj/notes.md, lines 1-3\n1: # Notes\n2: line one\n3: line two"
+ }
+ ],
+ "metadata": {
+ "truncated": false
+ }
+ },
+ "time": {
+ "created": 1790479966492,
+ "ran": 1790479966578,
+ "completed": 1790479966616
+ }
+ }
+ ],
+ "finish": "tool-calls",
+ "rawFinish": "tool_calls",
+ "cost": 0,
+ "tokens": {
+ "input": 216,
+ "output": 28,
+ "reasoning": 12,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ },
+ {
+ "id": "msg_0e0ec21b2001LWN1MnhyphTfOO",
+ "time": {
+ "created": 1790479966658,
+ "streamed": 1790479966796,
+ "completed": 1790479966799
+ },
+ "type": "assistant",
+ "agent": "general",
+ "model": {
+ "id": "mock-model",
+ "providerID": "mock"
+ },
+ "content": [
+ {
+ "type": "text",
+ "text": "notes.md has a heading and two lines."
+ }
+ ],
+ "finish": "stop",
+ "rawFinish": "stop",
+ "cost": 0,
+ "tokens": {
+ "input": 218,
+ "output": 40,
+ "reasoning": 0,
+ "cache": {
+ "read": 1000,
+ "write": 0
+ }
+ }
+ },
+ {
+ "id": "msg_0e0ec2255001BM5U9NSDgZzMSy",
+ "time": {
+ "created": 1790479966805
+ },
+ "type": "idle",
+ "outcome": "succeeded"
+ }
+ ],
+ "children": []
+ }
+ ]
+}
\ No newline at end of file
diff --git a/apps/server/src/engine2/launch.ts b/apps/server/src/engine2/launch.ts
new file mode 100644
index 00000000..e4b8b27f
--- /dev/null
+++ b/apps/server/src/engine2/launch.ts
@@ -0,0 +1,179 @@
+/**
+ * Launch-time glue for the 2.x engine: which dialect a binary speaks, and the
+ * config directory, plugin shim and environment a 2.x engine is started with.
+ */
+import { spawn } from "node:child_process";
+import { closeSync, existsSync, openSync, readFileSync, readSync, statSync } from "node:fs";
+import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { pathToFileURL } from "node:url";
+import { omnirushPluginPath } from "../omnirush-extensions-plugin-path.js";
+import { buildEngine2Config } from "./config.js";
+import { isRecord, type JsonRecord } from "./util.js";
+
+export type EngineDialect = "v1" | "v2";
+export type EngineIdentity = { dialect: EngineDialect; version: string | null };
+
+const identityCache = new Map<string, EngineIdentity>();
+
+function readHead(path: string, length: number): string {
+ let fd: number | null = null;
+ try {
+ fd = openSync(path, "r");
+ const buffer = Buffer.alloc(length);
+ const read = readSync(fd, buffer, 0, length, 0);
+ return buffer.subarray(0, read).toString("utf8");
+ } catch {
+ return "";
+ } finally {
+ if (fd !== null) closeSync(fd);
+ }
+}
+
+export function dialectOfVersion(version: string | null | undefined): EngineDialect {
+ const major = Number(String(version ?? "").trim().replace(/^opencode\s+/i, "").replace(/^v/, "").split(".")[0]);
+ return Number.isFinite(major) && major >= 2 ? "v2" : "v1";
+}
+
+function parseVersion(output: string): string | null {
+ const match = output.trim().match(/(\d+\.\d+\.\d+(?:[-+][\w.-]+)?)\s*$/);
+ return match ? match[1]! : null;
+}
+
+async function probeVersion(bin: string, timeoutMs: number): Promise<string | null> {
+ return new Promise((resolve) => {
+ let output = "";
+ let settled = false;
+ const done = (value: string | null) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ resolve(value);
+ };
+ let child: ReturnType<typeof spawn>;
+ try {
+ child = spawn(bin, ["--version"], { stdio: ["ignore", "pipe", "ignore"] });
+ } catch {
+ resolve(null);
+ return;
+ }
+ const timer = setTimeout(() => {
+ try {
+ child.kill("SIGKILL");
+ } catch {
+ // already gone
+ }
+ done(null);
+ }, timeoutMs);
+ child.stdout?.on("data", (chunk) => {
+ output += chunk.toString();
+ });
+ child.once("error", () => done(null));
+ child.once("close", (code) => done(code === 0 ? parseVersion(output) : null));
+ });
+}
+
+/**
+ * The engine API a binary speaks. OMNIRUSH_ENGINE_DIALECT overrides; a script
+ * (a test stand-in) is 1.x; otherwise the sidecar's versions.json or the
+ * binary's `--version` decides (major 2 and up is the 2.x API).
+ */
+export async function resolveEngineIdentity(bin: string, env: NodeJS.ProcessEnv = process.env): Promise<EngineIdentity> {
+ const forced = env.OMNIRUSH_ENGINE_DIALECT?.trim();
+ if (forced === "v1" || forced === "v2") return { dialect: forced, version: null };
+ const path = bin.trim() || "opencode";
+ let key = path;
+ try {
+ const stat = statSync(path);
+ key = `${path}:${stat.size}:${stat.mtimeMs}`;
+ if (readHead(path, 2) === "#!") return { dialect: "v1", version: null };
+ } catch {
+ // A bare command name resolved through PATH: probe it.
+ }
+ const cached = identityCache.get(key);
+ if (cached) return cached;
+ let version: string | null = null;
+ const versionsFile = join(dirname(path), "versions.json");
+ if (existsSync(versionsFile)) {
+ try {
+ const parsed: unknown = JSON.parse(readFileSync(versionsFile, "utf8"));
+ const recorded = isRecord(parsed) && isRecord(parsed.opencode) && typeof parsed.opencode.version === "string" ? parsed.opencode.version : null;
+ if (recorded) version = recorded.replace(/^v/, "");
+ } catch {
+ version = null;
+ }
+ }
+ version ??= await probeVersion(path, 15_000);
+ const identity: EngineIdentity = { dialect: dialectOfVersion(version), version };
+ identityCache.set(key, identity);
+ return identity;
+}
+
+async function writeAtomic(path: string, content: string): Promise<void> {
+ await mkdir(dirname(path), { recursive: true });
+ const current = await readFile(path, "utf8").catch(() => undefined);
+ if (current === content) return;
+ const temporary = `${path}.${process.pid}.${Date.now()}.tmp`;
+ await writeFile(temporary, content, "utf8");
+ await rename(temporary, path);
+}
+
+export type Engine2Launch = {
+ configFile: string;
+ v1ConfigPath: string | undefined;
+ /** Plugin directories named in the rendered config. */
+ plugins: string[];
+ /** Environment for the engine process (OPENCODE_CONFIG names the rendered 2.x config). */
+ env: NodeJS.ProcessEnv;
+ writeEngineConfig: (config: JsonRecord) => Promise<void>;
+};
+
+/**
+ * Prepares a 2.x engine start: renders the 1.x runtime config (OPENCODE_CONFIG)
+ * into a 2.x config file beside it, places the plugin directory that loads
+ * OmniRush.ai's plugin bridge, and returns the engine environment. The user's
+ * global opencode config directory stays in effect, as with 1.x.
+ */
+export async function prepareEngine2Launch(input: {
+ env: NodeJS.ProcessEnv;
+ cwd: string;
+ password: string;
+ adapterUrl: string;
+ adapterAuthorization: string;
+ pluginPath?: string;
+}): Promise<Engine2Launch> {
+ const v1ConfigPath = input.env.OPENCODE_CONFIG?.trim() || undefined;
+ const root = input.env.OMNIRUSH_ENGINE2_CONFIG_DIR?.trim()
+ || (v1ConfigPath ? join(dirname(v1ConfigPath), "engine2") : join(tmpdir(), `omnirush-engine2-${process.pid}`));
+ const configFile = join(root, "opencode.json");
+ const plugins: string[] = [];
+ const pluginPath = input.pluginPath ?? omnirushPluginPath("omnirush-engine2");
+ // OMNIRUSH_ENGINE_PLUGINS=0 starts the engine without OmniRush.ai's plugins (engine-level tests).
+ if (input.env.OMNIRUSH_ENGINE_PLUGINS !== "0" && existsSync(pluginPath)) {
+ const pluginDir = join(root, "omnirush-plugin");
+ await writeAtomic(
+ join(pluginDir, "index.js"),
+ `// Generated by OmniRush.ai: loads the plugin bridge for the bundled engine.\nexport { default } from ${JSON.stringify(pathToFileURL(pluginPath).href)};\n`,
+ );
+ plugins.push(pluginDir);
+ }
+ const writeEngineConfig = (config: JsonRecord) => writeAtomic(configFile, `${JSON.stringify(config, null, 2)}\n`);
+ let v1: JsonRecord = {};
+ if (v1ConfigPath) {
+ try {
+ const parsed: unknown = JSON.parse(await readFile(v1ConfigPath, "utf8"));
+ if (isRecord(parsed)) v1 = parsed;
+ } catch {
+ v1 = {};
+ }
+ }
+ await writeEngineConfig(buildEngine2Config({ v1, plugins }));
+ const env: NodeJS.ProcessEnv = { ...input.env };
+ delete env.OPENCODE_CONFIG_CONTENT;
+ env.OPENCODE_CONFIG = configFile;
+ env.OPENCODE_PASSWORD = input.password;
+ env.OMNIRUSH_ENGINE_ADAPTER_URL = input.adapterUrl;
+ env.OMNIRUSH_ENGINE_ADAPTER_AUTHORIZATION = input.adapterAuthorization;
+ return { configFile, v1ConfigPath, plugins, env, writeEngineConfig };
+}
diff --git a/apps/server/src/engine2/shapes.test.ts b/apps/server/src/engine2/shapes.test.ts
new file mode 100644
index 00000000..c2c75f70
--- /dev/null
+++ b/apps/server/src/engine2/shapes.test.ts
@@ -0,0 +1,273 @@
+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";
+
+/**
+ * Fixtures: the same scripted conversations run on the 1.x engine (1.18.32)
+ * and on the 2.x engine (2.0.18), read back with each engine's own API
+ * (`v1-*.json`: `/session/:id/message`, `v2-*.json`: `/api/session/:id/message`),
+ * machine paths replaced by /work. p1: shell, write, edit and a text answer;
+ * sub: two parallel sub-agents; nest: sub-agents three layers deep.
+ */
+type Tree = { session: Record<string, unknown>; messages: unknown[]; children: Tree[] };
+const fixture = (name: string): Tree => JSON.parse(readFileSync(join(import.meta.dir, "fixtures", `${name}.json`), "utf8"));
+
+function typeOf(value: unknown): string {
+ if (Array.isArray(value)) return "array";
+ if (value === null) return "null";
+ return typeof value;
+}
+
+/** Every key path whose presence or value type differs between two JSON values. */
+function shapeDiff(a: unknown, b: unknown, path = "$", out: string[] = []): string[] {
+ if (typeOf(a) !== typeOf(b)) {
+ out.push(`${path}: ${typeOf(a)} != ${typeOf(b)}`);
+ return out;
+ }
+ if (Array.isArray(a) && Array.isArray(b)) {
+ if (path.endsWith(".parts")) {
+ const ta = a.map((part) => (part as { type?: string }).type).join(",");
+ const tb = b.map((part) => (part as { type?: string }).type).join(",");
+ if (ta !== tb) out.push(`${path}: part types [${ta}] != [${tb}]`);
+ }
+ if (a.length !== b.length) out.push(`${path}: length ${a.length} != ${b.length}`);
+ for (let index = 0; index < Math.min(a.length, b.length); index++) shapeDiff(a[index], b[index], `${path}[${index}]`, out);
+ return out;
+ }
+ if (a && b && typeof a === "object") {
+ const ka = Object.keys(a as object);
+ const kb = Object.keys(b as object);
+ for (const key of ka) if (!kb.includes(key)) out.push(`${path}.${key}: only in 1.x`);
+ for (const key of kb) if (!ka.includes(key)) out.push(`${path}.${key}: only in adapter`);
+ for (const key of ka) if (kb.includes(key)) shapeDiff((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key], `${path}.${key}`, out);
+ }
+ return out;
+}
+
+function mapTree(tree: Tree, parentModel?: { providerID: string; modelID: string }): { messages: V1Message[]; children: Array<ReturnType<typeof mapTree>> } {
+ const session = tree.session as { id: string; parentID?: string; location?: { directory?: string } };
+ const messages = v1Messages(tree.messages, {
+ sessionID: session.id,
+ directory: session.location?.directory,
+ root: "/",
+ model: parentModel,
+ child: Boolean(session.parentID),
+ });
+ return { messages, children: tree.children.map((child) => mapTree(child, parentModel)) };
+}
+
+type Mapped = ReturnType<typeof mapTree>;
+/** Sub-agents start concurrently: children are paired by the task they were given. */
+const taskOf = (messages: unknown[]): string => {
+ const first = messages[0] as { parts?: Array<{ text?: string }> } | undefined;
+ return String(first?.parts?.[0]?.text ?? "");
+};
+
+function compareTrees(v1: Tree, mapped: Mapped, path: string, out: string[]): void {
+ shapeDiff(v1.messages, mapped.messages, `${path}.messages`, out);
+ if (v1.children.length !== mapped.children.length) out.push(`${path}: children ${v1.children.length} != ${mapped.children.length}`);
+ const left = [...v1.children].sort((a, b) => taskOf(a.messages).localeCompare(taskOf(b.messages)));
+ const right = [...mapped.children].sort((a, b) => taskOf(a.messages).localeCompare(taskOf(b.messages)));
+ left.forEach((child, index) => {
+ if (right[index]) compareTrees(child, right[index]!, `${path}.child[${index}]`, out);
+ });
+}
+
+describe("2.x messages in the 1.x shape (uploaded trace parity)", () => {
+ for (const scenario of ["p1", "sub", "nest"]) {
+ test(`${scenario}: every message, part and field the 1.x engine wrote, and no other`, () => {
+ const out: string[] = [];
+ compareTrees(fixture(`v1-${scenario}`), mapTree(fixture(`v2-${scenario}`)), "root", out);
+ expect(out).toEqual([]);
+ });
+ }
+
+ test("p1: the uploaded messages, field for field", () => {
+ const [user, first, second, third, answer] = mapTree(fixture("v2-p1")).messages;
+ expect(user!.info).toEqual({
+ id: "msg_0e0eb02300010Ie6K3lQAqUici",
+ sessionID: "ses_f1f14fdf6ffe32y5eLxrDN6MFs",
+ role: "user",
+ time: { created: 1790479893113 },
+ summary: { diffs: [] },
+ agent: "build",
+ model: { providerID: "mock", modelID: "mock-model" },
+ });
+ expect(user!.parts).toEqual([{
+ id: "prt_0e0eb02300010Ie6K3lQAqUici_u0",
+ sessionID: "ses_f1f14fdf6ffe32y5eLxrDN6MFs",
+ messageID: "msg_0e0eb02300010Ie6K3lQAqUici",
+ type: "text",
+ text: "PARITY-1 create the notes file",
+ }]);
+ expect(first!.info).toEqual({
+ id: "msg_0e0eb029c001Gb432955hHZq2J",
+ sessionID: "ses_f1f14fdf6ffe32y5eLxrDN6MFs",
+ role: "assistant",
+ time: { created: 1790479893170, completed: 1790479893443 },
+ parentID: "msg_0e0eb02300010Ie6K3lQAqUici",
+ modelID: "mock-model",
+ providerID: "mock",
+ mode: "build",
+ agent: "build",
+ path: { cwd: "/work/proj", root: "/" },
+ cost: 0,
+ tokens: { total: 1242, input: 202, output: 28, reasoning: 12, cache: { read: 1000, write: 0 } },
+ finish: "tool-calls",
+ });
+ expect(first!.parts.map((part) => part.type)).toEqual(["step-start", "reasoning", "tool", "step-finish"]);
+ expect(first!.parts[2]).toEqual({
+ id: "prt_0e0eb029c001Gb432955hHZq2J_c_call_2_0",
+ sessionID: "ses_f1f14fdf6ffe32y5eLxrDN6MFs",
+ messageID: "msg_0e0eb029c001Gb432955hHZq2J",
+ type: "tool",
+ callID: "call_2_0",
+ tool: "bash",
+ state: {
+ status: "completed",
+ input: { command: "ls -a", description: "List files" },
+ output: ".\n..\n",
+ title: "List files",
+ metadata: { output: ".\n..\n", truncated: false, exit: 0 },
+ time: { start: 1790479893299, end: 1790479893435 },
+ },
+ });
+ expect(first!.parts[3]).toEqual({
+ id: "prt_0e0eb029c001Gb432955hHZq2J_f0",
+ sessionID: "ses_f1f14fdf6ffe32y5eLxrDN6MFs",
+ messageID: "msg_0e0eb029c001Gb432955hHZq2J",
+ type: "step-finish",
+ reason: "tool-calls",
+ cost: 0,
+ tokens: { total: 1242, input: 202, output: 28, reasoning: 12, cache: { read: 1000, write: 0 } },
+ });
+ const write = second!.parts.find((part) => part.type === "tool") as { tool: string; state: { input: unknown; metadata: unknown; title: string } };
+ expect(write.tool).toBe("write");
+ expect(write.state.input).toEqual({ filePath: "/work/proj/notes.md", content: "# Notes\nline one\n" });
+ expect(write.state.metadata).toEqual({ diagnostics: {}, filepath: "/work/proj/notes.md", exists: false, truncated: false });
+ expect(write.state.title).toBe("work/proj/notes.md");
+ 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"]);
+ expect(edit.state.metadata.filediff).toMatchObject({ file: "/work/proj/notes.md", additions: 1, deletions: 0 });
+ expect(answer!.parts.map((part) => part.type)).toEqual(["step-start", "reasoning", "text", "step-finish"]);
+ expect(answer!.info.finish).toBe("stop");
+ });
+
+ test("sub: task calls name their child sessions the way the 1.x engine did", () => {
+ const tree = fixture("v2-sub");
+ const mapped = mapTree(tree, { providerID: "mock", modelID: "mock-model" });
+ const tasks = mapped.messages.flatMap((message) => message.parts).filter((part) => part.type === "tool") as Array<{ tool: string; state: { input: Record<string, unknown>; output: string; metadata: Record<string, unknown> } }>;
+ expect(tasks.map((task) => task.tool)).toEqual(["task", "task"]);
+ expect(tasks[0]!.state.input).toEqual({ subagent_type: "general", description: "Read notes", prompt: "CHILD-A: read notes.md and summarise it" });
+ const children = tree.children.map((child) => (child.session as { id: string }).id);
+ expect(tasks.map((task) => task.state.metadata.sessionId).sort()).toEqual([...children].sort());
+ expect(tasks[0]!.state.metadata).toMatchObject({ parentSessionId: (tree.session as { id: string }).id, model: { modelID: "mock-model", providerID: "mock" }, truncated: false });
+ expect(tasks[0]!.state.output).toMatch(/^<task id="ses_[^"]+" state="completed">\n<task_result>\n[\s\S]+\n<\/task_result>\n<\/task>$/);
+ // A child's first message is the task the parent wrote, without the 2.x preamble.
+ const firstChildUser = mapped.children[0]!.messages[0]!;
+ expect(firstChildUser.info.role).toBe("user");
+ expect((firstChildUser.parts[0] as { text: string }).text).toMatch(/^CHILD-/);
+ });
+
+ test("sessions carry the 1.x fields (child titles name their sub-agent)", () => {
+ const tree = fixture("v2-sub");
+ const child = v1Session(tree.children[0]!.session, { version: "2.0.18" })!;
+ expect(child.title).toMatch(/ \(@general subagent\)$/);
+ expect(child.parentID).toBe((tree.session as { id: string }).id);
+ expect(child.permission).toEqual([]);
+ expect(Object.keys(child).sort()).toEqual(
+ ["agent", "cost", "directory", "id", "parentID", "path", "permission", "projectID", "slug", "summary", "time", "title", "tokens", "version"].sort(),
+ );
+ });
+});
+
+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) => 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("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", () => {
+ 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("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", () => {
+ expect(partId("msg_abc", "t0")).toBe("prt_abc_t0");
+ expect(partId("msg_abc", "c", "call_9")).toBe("prt_abc_c_call_9");
+ });
+});
diff --git a/apps/server/src/engine2/shapes.ts b/apps/server/src/engine2/shapes.ts
new file mode 100644
index 00000000..74e86b8b
--- /dev/null
+++ b/apps/server/src/engine2/shapes.ts
@@ -0,0 +1,984 @@
+/**
+ * The 2.x engine's records in the 1.x shapes the app, the collector and the
+ * uploaded traces are written against.
+ *
+ * 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:
+ *
+ * - 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,
+ * modelID, providerID, mode, agent, path, cost, tokens{total,…}, finish}, parts:[step-start,
+ * reasoning/text/tool…, step-finish]}`;
+ * - 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`, …);
+ * - 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.
+ */
+import { arr, isRecord, num, omitUndefined, record, str, unwrap, type JsonRecord } from "./util.js";
+
+export type V1Message = { info: JsonRecord; parts: JsonRecord[] };
+
+/** The prefix the 2.x subagent tool puts before a child session's task (core/src/tool/plugin/subagent.ts). */
+export const SUBAGENT_PROMPT_PREFIX = "You are a subagent spawned by another session.\n";
+
+const TOOL_NAMES_V1: Record<string, string> = {
+ shell: "bash",
+ subagent: "task",
+ patch: "apply_patch",
+};
+
+/** A 2.x tool name in its 1.x spelling. */
+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 {};
+ try {
+ const parsed: unknown = JSON.parse(value);
+ return isRecord(parsed) ? parsed : {};
+ } catch {
+ return {};
+ }
+}
+
+/** A 2.x tool input with the 1.x key names of the same tool. */
+export function v1ToolInput(name: string, raw: unknown): JsonRecord {
+ const input = parseInput(raw);
+ switch (name) {
+ case "read":
+ case "write":
+ case "edit": {
+ if (typeof input.path !== "string" || "filePath" in input) return input;
+ const { path, ...rest } = input;
+ return { filePath: path, ...rest };
+ }
+ case "subagent": {
+ if (typeof input.agent !== "string" || "subagent_type" in input) return input;
+ const { agent, ...rest } = input;
+ return { subagent_type: agent, ...rest };
+ }
+ default:
+ return input;
+ }
+}
+
+/** 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 "";
+ return content
+ .flatMap((item) => (isRecord(item) && item.type === "text" && typeof item.text === "string" ? [item.text] : []))
+ .join("\n");
+}
+
+function relativeTo(root: string | undefined, file: string): string {
+ if (!root || !file.startsWith("/") && !/^[A-Za-z]:[\\/]/.test(file)) return file;
+ const normalizedRoot = root.replace(/[\\/]+$/, "");
+ if (file === normalizedRoot) return ".";
+ if (file.startsWith(`${normalizedRoot}/`) || file.startsWith(`${normalizedRoot}\\`)) return file.slice(normalizedRoot.length + 1);
+ return file.replace(/^\/+/, "");
+}
+
+function absoluteFrom(directory: string | undefined, file: string): string {
+ if (!directory || file.startsWith("/") || /^[A-Za-z]:[\\/]/.test(file)) return file;
+ const sep = directory.includes("\\") && !directory.includes("/") ? "\\" : "/";
+ return `${directory.replace(/[\\/]+$/, "")}${sep}${file}`;
+}
+
+/** The 2.x subagent result `<subagent sessionID="…" state="…">…</subagent>` in the 1.x task tool's form. */
+function v1TaskOutput(text: string): string {
+ const match = text.match(/^<subagent sessionID="([^"]+)" state="([^"]+)">\n?([\s\S]*?)\n?<\/subagent>\s*$/);
+ if (!match) return text;
+ return `<task id="${match[1]}" state="${match[2]}">\n<task_result>\n${match[3]}\n</task_result>\n</task>`;
+}
+
+type ToolContext = { sessionID: string; directory?: string; root?: string; parentModel?: { providerID: string; modelID: string } };
+
+function v1ToolTitle(name: string, input: JsonRecord, ctx: ToolContext): string {
+ switch (name) {
+ case "shell":
+ return typeof input.description === "string" && input.description ? input.description : String(input.command ?? "");
+ case "subagent":
+ return String(input.description ?? "");
+ case "read":
+ case "write":
+ case "edit": {
+ const file = typeof input.path === "string" ? input.path : typeof input.filePath === "string" ? input.filePath : "";
+ return relativeTo(ctx.root ?? ctx.directory, absoluteFrom(ctx.directory, file));
+ }
+ case "glob":
+ case "grep":
+ return String(input.pattern ?? "");
+ case "webfetch":
+ return String(input.url ?? "");
+ case "websearch":
+ return String(input.query ?? "");
+ case "skill":
+ return String(input.id ?? input.name ?? "");
+ default:
+ return v1ToolName(name);
+ }
+}
+
+/** A completed 2.x tool call's metadata with the 1.x keys the app, swarm board and converter read. */
+function v1ToolMetadata(name: string, input: JsonRecord, metadata: JsonRecord, output: string, ctx: ToolContext): JsonRecord {
+ switch (name) {
+ case "shell": {
+ const { status: _status, ...rest } = metadata;
+ return { output, ...rest };
+ }
+ case "subagent": {
+ const { sessionID, status: _status, ...rest } = metadata;
+ // The model the sub-agent ran on: the call's `model` ("provider/model[#variant]"), else the caller's.
+ const requested = typeof input.model === "string" ? input.model.match(/^([^/#]+)\/([^#]+)/) : null;
+ const model = requested ? { modelID: requested[2]!, providerID: requested[1]! } : ctx.parentModel;
+ return omitUndefined({
+ parentSessionId: ctx.sessionID,
+ sessionId: typeof sessionID === "string" ? sessionID : undefined,
+ model: model ? { modelID: model.modelID, providerID: model.providerID } : undefined,
+ ...rest,
+ });
+ }
+ case "read": {
+ const file = absoluteFrom(ctx.directory, String(input.path ?? input.filePath ?? ""));
+ // 2.x prints numbered lines ("12: text"); 1.x kept the plain text as preview and display.
+ const numbered = output.split("\n").map((line) => line.match(/^(\d+): ?(.*)$/)).filter((match): match is RegExpMatchArray => Boolean(match));
+ if (numbered.length === 0) return { truncated: false, loaded: [], ...metadata };
+ const lines = numbered.map((match) => match[2] ?? "");
+ const lineStart = Number(numbered[0]![1]);
+ const lineEnd = Number(numbered[numbered.length - 1]![1]);
+ const truncated = metadata.truncated === true;
+ const text = lines.join("\n");
+ return {
+ preview: lines.slice(0, 20).join("\n"),
+ truncated,
+ loaded: [],
+ display: { type: "file", path: file, text, lineStart, lineEnd, totalLines: truncated ? lineEnd : lineEnd, truncated },
+ ...metadata,
+ };
+ }
+ case "write": {
+ const file = absoluteFrom(ctx.directory, String(input.path ?? input.filePath ?? ""));
+ // 2.x reports whether the file existed in its text result ("Created file…" / "Updated file…").
+ const exists = typeof metadata.existed === "boolean" ? metadata.existed : !/^Created\b/i.test(output);
+ const { existed: _existed, ...rest } = metadata;
+ return { diagnostics: {}, filepath: file, exists, ...rest };
+ }
+ case "edit":
+ case "patch": {
+ const files = Array.isArray(metadata.files) ? metadata.files.filter(isRecord) : [];
+ const first = files[0];
+ const { files: _files, ...rest } = metadata;
+ if (!first) return { diagnostics: {}, ...rest };
+ const file = absoluteFrom(ctx.directory, String(first.file ?? ""));
+ const patch = typeof first.patch === "string" ? first.patch : "";
+ return omitUndefined({
+ diagnostics: {},
+ diff: patch,
+ filediff: omitUndefined({
+ file,
+ patch,
+ additions: typeof first.additions === "number" ? first.additions : 0,
+ deletions: typeof first.deletions === "number" ? first.deletions : 0,
+ }),
+ ...(name === "patch" ? { files: files.map((entry) => ({ ...entry, file: absoluteFrom(ctx.directory, String(entry.file ?? "")) })) } : {}),
+ ...rest,
+ });
+ }
+ default:
+ return metadata;
+ }
+}
+
+function fileAttachments(content: unknown, ids: { messageID: string; sessionID: string; callID: string }): JsonRecord[] {
+ if (!Array.isArray(content)) return [];
+ const files: JsonRecord[] = [];
+ for (const item of content) {
+ if (!isRecord(item) || item.type !== "file") continue;
+ const url = str(item, "uri");
+ const mime = str(item, "mime");
+ if (!url || !mime) continue;
+ files.push(omitUndefined({
+ id: partId(ids.messageID, `a${files.length}`, ids.callID),
+ sessionID: ids.sessionID,
+ messageID: ids.messageID,
+ type: "file",
+ mime,
+ filename: str(item, "name"),
+ url,
+ }));
+ }
+ return files;
+}
+
+function errorMessage(value: unknown): string {
+ if (typeof value === "string") return value;
+ if (isRecord(value)) return str(value, "message") ?? str(value, "type") ?? JSON.stringify(value);
+ return value === undefined ? "" : String(value);
+}
+
+/** Part ids: `prt_<message id sans prefix>_<slot>[_<call id>]`, the same from a read and from events. */
+export function partId(messageID: string, slot: string, callID?: string): string {
+ const core = messageID.startsWith("msg_") ? messageID.slice(4) : messageID;
+ return callID ? `prt_${core}_${slot}_${callID}` : `prt_${core}_${slot}`;
+}
+
+/** A 2.x tool content entry as a 1.x tool part (null for a shape it does not know). */
+export function v1ToolPart(
+ entry: JsonRecord,
+ ids: { messageID: string; sessionID: string },
+ ctx: ToolContext,
+ messageCreated: number,
+): JsonRecord | null {
+ const callID = str(entry, "id") ?? str(entry, "callID");
+ const name = str(entry, "name") ?? str(entry, "tool");
+ const state = record(entry, "state");
+ if (!callID || !name || !state) return null;
+ const status = str(state, "status");
+ const time = record(entry, "time");
+ const created = num(time, "created") ?? messageCreated;
+ const start = num(time, "ran") ?? created;
+ const end = num(time, "completed") ?? start;
+ const input = v1ToolInput(name, state.input);
+ const rawInput = parseInput(state.input);
+ const base = {
+ id: partId(ids.messageID, "c", callID),
+ sessionID: ids.sessionID,
+ messageID: ids.messageID,
+ type: "tool",
+ callID,
+ tool: v1ToolName(name),
+ };
+ if (status === "streaming" || status === "pending") {
+ return { ...base, state: { status: "pending", input, raw: typeof state.input === "string" ? state.input : JSON.stringify(state.input ?? {}) } };
+ }
+ const { __title: pluginTitle, ...metadata } = record(state, "metadata") ?? {};
+ const title = (fallback: string) => (typeof pluginTitle === "string" && pluginTitle ? pluginTitle : fallback);
+ if (status === "running") {
+ const runningTitle = title(v1ToolTitle(name, rawInput, ctx));
+ const running = name === "subagent" ? v1ToolMetadata(name, rawInput, metadata, "", ctx) : metadata;
+ return { ...base, state: omitUndefined({ status: "running", input, title: runningTitle || undefined, metadata: running, time: { start } }) };
+ }
+ if (status === "completed") {
+ const text = contentText(state.content);
+ const output = name === "subagent" ? v1TaskOutput(text) : text;
+ const attachments = fileAttachments(state.content, { ...ids, callID });
+ return {
+ ...base,
+ state: omitUndefined({
+ status: "completed",
+ input,
+ output,
+ title: title(v1ToolTitle(name, rawInput, ctx)),
+ metadata: v1ToolMetadata(name, rawInput, metadata, output, ctx),
+ time: { start, end },
+ attachments: attachments.length > 0 ? attachments : undefined,
+ }),
+ };
+ }
+ if (status === "error") {
+ return {
+ ...base,
+ state: omitUndefined({
+ status: "error",
+ input,
+ error: errorMessage(state.error),
+ metadata: Object.keys(metadata).length > 0 ? v1ToolMetadata(name, rawInput, metadata, contentText(state.content), ctx) : undefined,
+ time: { start, end },
+ }),
+ };
+ }
+ return null;
+}
+
+function v1Tokens(value: unknown): JsonRecord {
+ const tokens = isRecord(value) ? value : {};
+ const cache = record(tokens, "cache") ?? {};
+ const input = num(tokens, "input") ?? 0;
+ const output = num(tokens, "output") ?? 0;
+ const reasoning = num(tokens, "reasoning") ?? 0;
+ const read = num(cache, "read") ?? 0;
+ const write = num(cache, "write") ?? 0;
+ return { total: input + output + reasoning + read + write, input, output, reasoning, cache: { read, write } };
+}
+
+/** A 2.x session error `{type, message, status?}` as the 1.x named error. */
+export function v1Error(value: unknown, providerID?: string): JsonRecord | undefined {
+ if (!isRecord(value)) return undefined;
+ const type = str(value, "type") ?? "unknown";
+ const message = str(value, "message") ?? type;
+ const status = num(value, "status");
+ if (type === "aborted") return { name: "MessageAbortedError", data: { message } };
+ if (type === "provider.auth") return { name: "ProviderAuthError", data: { providerID: providerID ?? "", message } };
+ if (type === "provider.content-filter") return { name: "ContentFilterError", data: { message } };
+ if (/context|overflow/i.test(type)) return { name: "ContextOverflowError", data: { message } };
+ if (type.startsWith("provider.")) {
+ return {
+ name: "APIError",
+ data: omitUndefined({
+ message,
+ statusCode: status,
+ isRetryable: ["provider.rate-limit", "provider.transport", "provider.internal", "provider.timeout"].includes(type),
+ }),
+ };
+ }
+ return { name: "UnknownError", data: { message } };
+}
+
+function userFileParts(files: unknown[], ids: { messageID: string; sessionID: string }): JsonRecord[] {
+ const parts: JsonRecord[] = [];
+ files.forEach((file, index) => {
+ if (!isRecord(file)) return;
+ const url = str(file, "uri");
+ if (!url) return;
+ parts.push(omitUndefined({
+ id: partId(ids.messageID, `f${index}`),
+ sessionID: ids.sessionID,
+ messageID: ids.messageID,
+ type: "file",
+ mime: str(file, "mime") ?? mimeFromUri(url, str(file, "name")),
+ filename: str(file, "name"),
+ url,
+ }));
+ });
+ return parts;
+}
+
+const EXTENSION_MIME: Record<string, string> = {
+ png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", svg: "image/svg+xml",
+ pdf: "application/pdf", txt: "text/plain", md: "text/markdown", json: "application/json", csv: "text/csv",
+ docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
+};
+
+export function mimeFromUri(uri: string, name?: string): string {
+ const data = uri.match(/^data:([^;,]+)[;,]/);
+ if (data?.[1]) return data[1];
+ const source = name ?? uri.split(/[?#]/)[0] ?? "";
+ const ext = source.split(".").pop()?.toLowerCase() ?? "";
+ if (uri.startsWith("file:") && !source.includes(".")) return "application/x-directory";
+ return EXTENSION_MIME[ext] ?? "text/plain";
+}
+
+export type MessageContext = {
+ sessionID: string;
+ directory?: string;
+ /** The project's worktree root (a git root) for `path.root`; "/" when there is none, as 1.x reported. */
+ root?: string;
+ /** The session's selected agent/model, for user messages that precede any assistant reply. */
+ agent?: string;
+ 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;
+};
+
+type ModelRef = { providerID: string; modelID: string; variant?: string };
+
+function modelRef(value: unknown): ModelRef | undefined {
+ if (!isRecord(value)) return undefined;
+ const providerID = str(value, "providerID");
+ const modelID = str(value, "id") ?? str(value, "modelID");
+ if (!providerID || !modelID) return undefined;
+ const variant = str(value, "variant");
+ return variant ? { providerID, modelID, variant } : { providerID, modelID };
+}
+
+/** One 2.x assistant message (one step) as a 1.x assistant message. */
+export function v1AssistantMessage(message: JsonRecord, ctx: MessageContext, parentID: string, completedOverride?: boolean): V1Message {
+ const id = str(message, "id") ?? "";
+ const time = record(message, "time") ?? {};
+ const created = num(time, "created") ?? 0;
+ const completed = num(time, "completed");
+ 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 };
+ const tokens = v1Tokens(message.tokens);
+ const cost = num(message, "cost") ?? 0;
+ const finish = str(message, "finish");
+ const snapshot = str(message, "snapshot");
+ const parts: JsonRecord[] = [omitUndefined({ id: partId(id, "s0"), sessionID: ctx.sessionID, messageID: id, type: "step-start", snapshot })];
+ const ordinals = { text: 0, reasoning: 0 };
+ for (const entry of arr(message, "content")) {
+ if (!isRecord(entry)) continue;
+ const type = str(entry, "type");
+ if (type === "text" || type === "reasoning") {
+ const ordinal = ordinals[type]++;
+ const text = str(entry, "text") ?? "";
+ const entryTime = record(entry, "time");
+ const start = num(entryTime, "created");
+ const end = num(entryTime, "completed");
+ if (type === "reasoning") {
+ parts.push(omitUndefined({
+ id: partId(id, `r${ordinal}`),
+ sessionID: ctx.sessionID,
+ messageID: id,
+ type: "reasoning",
+ text,
+ time: omitUndefined({ start: start ?? created, end: end ?? (completed !== undefined ? completed : undefined) }),
+ }));
+ } else {
+ parts.push(omitUndefined({
+ id: partId(id, `t${ordinal}`),
+ sessionID: ctx.sessionID,
+ messageID: id,
+ type: "text",
+ text,
+ time: start !== undefined || completed !== undefined ? omitUndefined({ start: start ?? created, end: end ?? completed }) : undefined,
+ }));
+ }
+ continue;
+ }
+ if (type === "tool") {
+ const part = v1ToolPart(entry, ids, toolCtx, created);
+ if (part) parts.push(part);
+ }
+ }
+ const done = completedOverride ?? completed !== undefined;
+ if (done && finish !== undefined) {
+ parts.push(omitUndefined({
+ id: partId(id, "f0"),
+ sessionID: ctx.sessionID,
+ messageID: id,
+ type: "step-finish",
+ reason: finish,
+ snapshot,
+ cost,
+ tokens,
+ }));
+ }
+ const error = v1Error(message.error, model?.providerID);
+ const info = omitUndefined({
+ id,
+ sessionID: ctx.sessionID,
+ role: "assistant",
+ time: omitUndefined({ created, completed }),
+ error,
+ parentID,
+ modelID: model?.modelID ?? "",
+ providerID: model?.providerID ?? "",
+ mode: agent,
+ agent,
+ path: { cwd: ctx.directory ?? "", root: ctx.root ?? "/" },
+ cost,
+ tokens,
+ variant: model?.variant,
+ finish,
+ });
+ return { info, parts };
+}
+
+function v1UserMessage(
+ message: JsonRecord,
+ ctx: MessageContext,
+ text: string,
+ files: unknown[],
+ synthetic: boolean,
+ agent: string,
+ model: ModelRef | undefined,
+): V1Message {
+ const id = str(message, "id") ?? "";
+ const created = num(record(message, "time"), "created") ?? 0;
+ const ids = { messageID: id, sessionID: ctx.sessionID };
+ const parts: JsonRecord[] = [];
+ if (text || files.length === 0) {
+ parts.push(omitUndefined({ id: partId(id, "u0"), sessionID: ctx.sessionID, messageID: id, type: "text", text, synthetic: synthetic || undefined }));
+ }
+ parts.push(...userFileParts(files, ids));
+ const info = omitUndefined({
+ id,
+ sessionID: ctx.sessionID,
+ role: "user",
+ time: { created },
+ summary: { diffs: [] },
+ agent,
+ model: model ? omitUndefined({ providerID: model.providerID, modelID: model.modelID, variant: model.variant }) : { providerID: "", modelID: "" },
+ });
+ return { info, parts };
+}
+
+/** A 2.x user-run shell command (`shell` message) as the 1.x shell pair: a synthetic user message and an assistant bash call. */
+function v1ShellMessages(message: JsonRecord, ctx: MessageContext, agent: string, model: ModelRef | undefined): V1Message[] {
+ const id = str(message, "id") ?? "";
+ const created = num(record(message, "time"), "created") ?? 0;
+ const completed = num(record(message, "time"), "completed");
+ const command = str(message, "command") ?? "";
+ const status = str(message, "status");
+ const output = str(message, "output") ?? "";
+ const userId = `${id}u`;
+ const user = v1UserMessage({ id: userId, time: { created } }, ctx, "The following tool was executed by the user", [], true, agent, model);
+ const callID = str(message, "shellID") ?? `${id}_shell`;
+ const tool = {
+ id: partId(id, "c", callID),
+ sessionID: ctx.sessionID,
+ messageID: id,
+ type: "tool",
+ callID,
+ tool: "bash",
+ state: status === "running"
+ ? { status: "running", input: { command }, title: command, metadata: {}, time: { start: created } }
+ : { status: "completed", input: { command }, output, title: command, metadata: omitUndefined({ output, exit: num(message, "exit") }), time: { start: created, end: completed ?? created } },
+ };
+ const assistant: V1Message = {
+ info: omitUndefined({
+ id,
+ sessionID: ctx.sessionID,
+ role: "assistant",
+ time: omitUndefined({ created, completed }),
+ parentID: userId,
+ modelID: model?.modelID ?? "",
+ providerID: model?.providerID ?? "",
+ mode: agent,
+ agent,
+ path: { cwd: ctx.directory ?? "", root: ctx.root ?? "/" },
+ cost: 0,
+ tokens: v1Tokens(undefined),
+ }),
+ parts: [tool],
+ };
+ return [user, assistant];
+}
+
+/** A 2.x compaction record as the 1.x pair: a user message with a compaction part and the summary reply. */
+function v1CompactionMessages(message: JsonRecord, ctx: MessageContext, model: ModelRef | undefined): V1Message[] {
+ const id = str(message, "id") ?? "";
+ const created = num(record(message, "time"), "created") ?? 0;
+ const completed = num(record(message, "time"), "completed");
+ const userId = `${id}u`;
+ const user: V1Message = {
+ info: omitUndefined({
+ id: userId,
+ sessionID: ctx.sessionID,
+ role: "user",
+ time: { created },
+ agent: "compaction",
+ model: model ? { providerID: model.providerID, modelID: model.modelID } : { providerID: "", modelID: "" },
+ }),
+ parts: [{ id: partId(userId, "k0"), sessionID: ctx.sessionID, messageID: userId, type: "compaction", auto: str(message, "reason") !== "manual" }],
+ };
+ const summary = str(message, "summary");
+ if (summary === undefined && str(message, "status") === "running") return [user];
+ const assistant: V1Message = {
+ info: omitUndefined({
+ id,
+ sessionID: ctx.sessionID,
+ role: "assistant",
+ time: omitUndefined({ created, completed }),
+ parentID: userId,
+ modelID: model?.modelID ?? "",
+ providerID: model?.providerID ?? "",
+ mode: "compaction",
+ agent: "compaction",
+ path: { cwd: ctx.directory ?? "", root: ctx.root ?? "/" },
+ summary: true,
+ cost: num(message, "cost") ?? 0,
+ tokens: v1Tokens(message.tokens),
+ finish: str(message, "status") === "failed" ? undefined : "stop",
+ error: str(message, "status") === "failed" ? { name: "UnknownError", data: { message: "Compaction failed" } } : undefined,
+ }),
+ parts: summary ? [{ id: partId(id, "t0"), sessionID: ctx.sessionID, messageID: id, type: "text", text: summary }] : [],
+ };
+ return [user, assistant];
+}
+
+/**
+ * A session's 2.x messages (oldest first) as its 1.x messages. The model and
+ * agent of a user message come from the reply that follows it (2.x records
+ * them on the step), else from the latest switch record or the session.
+ */
+export function v1Messages(messages: unknown[], ctx: MessageContext): V1Message[] {
+ const list = messages.filter(isRecord);
+ const out: V1Message[] = [];
+ let agent = ctx.agent ?? "build";
+ let model = ctx.model;
+ let lastUserId = "";
+ let firstUser = true;
+ // The reply's agent/model decide the user message's: look ahead once.
+ const nextAssistant = (index: number): JsonRecord | undefined => {
+ for (let i = index + 1; i < list.length; i++) {
+ const candidate = list[i]!;
+ const type = str(candidate, "type");
+ if (type === "assistant") return candidate;
+ if (type === "user" || type === "synthetic") return undefined;
+ }
+ return undefined;
+ };
+ list.forEach((message, index) => {
+ const type = str(message, "type") ?? str(message, "role");
+ switch (type) {
+ case "agent-switched":
+ agent = str(message, "agent") ?? agent;
+ return;
+ case "model-switched":
+ model = modelRef(message.model) ?? model;
+ return;
+ case "user":
+ case "synthetic": {
+ const reply = nextAssistant(index);
+ const replyAgent = reply ? str(reply, "agent") : undefined;
+ const replyModel = reply ? modelRef(reply.model) : undefined;
+ let text = str(message, "text") ?? "";
+ if (ctx.child && firstUser && type === "user" && text.startsWith(SUBAGENT_PROMPT_PREFIX)) text = text.slice(SUBAGENT_PROMPT_PREFIX.length);
+ if (type === "user") firstUser = false;
+ const mapped = v1UserMessage(message, ctx, text, arr(message, "files"), type === "synthetic", replyAgent ?? agent, replyModel ?? model);
+ lastUserId = String(mapped.info.id);
+ out.push(mapped);
+ return;
+ }
+ case "skill": {
+ const mapped = v1UserMessage(message, ctx, str(message, "text") ?? "", [], true, agent, model);
+ out.push(mapped);
+ return;
+ }
+ case "assistant": {
+ const mapped = v1AssistantMessage(message, ctx, lastUserId);
+ agent = String(mapped.info.agent ?? agent);
+ const stepModel = modelRef(message.model);
+ if (stepModel) model = { ...stepModel, ...(model?.variant && !stepModel.variant ? { variant: model.variant } : {}) };
+ out.push(mapped);
+ return;
+ }
+ case "shell":
+ out.push(...v1ShellMessages(message, ctx, agent, model));
+ return;
+ case "compaction":
+ out.push(...v1CompactionMessages(message, ctx, model));
+ return;
+ default:
+ // system, location-switched, idle: context records the 1.x engine never listed.
+ return;
+ }
+ });
+ return out;
+}
+
+export type SessionShapeOptions = {
+ version: string;
+ /** The directory a session with no location record is reported under. */
+ directory?: string;
+};
+
+function permissionRules(value: unknown): JsonRecord[] {
+ return (Array.isArray(value) ? value : []).filter(isRecord).map((rule) => ({
+ permission: v1ToolName(str(rule, "action") ?? "*"),
+ pattern: str(rule, "resource") ?? "*",
+ action: str(rule, "effect") ?? "ask",
+ }));
+}
+
+/** A 2.x session as a 1.x session record. */
+export function v1Session(value: unknown, options: SessionShapeOptions): JsonRecord | null {
+ const data = unwrap(value);
+ if (!isRecord(data)) return null;
+ const source = record(data, "info") ?? data;
+ const id = str(source, "id") ?? str(source, "sessionID");
+ if (!id) return null;
+ const time = record(source, "time") ?? {};
+ const created = num(time, "created") ?? num(source, "created") ?? 0;
+ const updated = num(time, "updated") ?? created;
+ const archived = num(time, "archived");
+ const location = record(source, "location");
+ const directory = str(location, "directory") ?? str(source, "directory") ?? options.directory ?? "";
+ const parentID = str(source, "parentID");
+ const agent = str(source, "agent");
+ const rawTitle = str(source, "title");
+ let title = rawTitle && rawTitle.trim() ? rawTitle : `${parentID ? "Child session" : "New session"} - ${new Date(created).toISOString()}`;
+ if (parentID && agent && rawTitle && !/\(@[^)]+ subagent\)$/.test(rawTitle)) title = `${rawTitle} (@${agent} subagent)`;
+ const model = record(source, "model");
+ const tokens = record(source, "tokens");
+ const revert = record(source, "revert");
+ return omitUndefined({
+ id,
+ slug: str(source, "slug") ?? id.replace(/^ses_/, "").slice(-12).toLowerCase(),
+ projectID: str(source, "projectID") ?? "global",
+ directory,
+ path: str(source, "subpath") || directory.replace(/^[\\/]+/, ""),
+ parentID,
+ summary: { additions: 0, deletions: 0, files: 0 },
+ cost: num(source, "cost"),
+ tokens: tokens ? { input: num(tokens, "input") ?? 0, output: num(tokens, "output") ?? 0, reasoning: num(tokens, "reasoning") ?? 0, cache: { read: num(record(tokens, "cache"), "read") ?? 0, write: num(record(tokens, "cache"), "write") ?? 0 } } : undefined,
+ title,
+ agent,
+ model: model && str(model, "id") && str(model, "providerID") ? omitUndefined({ id: str(model, "id"), providerID: str(model, "providerID"), variant: str(model, "variant") }) : undefined,
+ version: options.version,
+ metadata: record(source, "metadata"),
+ time: omitUndefined({ created, updated, archived }),
+ permission: parentID ? permissionRules(source.permissions) : undefined,
+ 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/util.ts b/apps/server/src/engine2/util.ts
new file mode 100644
index 00000000..956be35e
--- /dev/null
+++ b/apps/server/src/engine2/util.ts
@@ -0,0 +1,47 @@
+/** Small readers shared by the engine 2.x dialect adapter (engine2/*). */
+
+export type JsonRecord = Record<string, unknown>;
+
+export function isRecord(value: unknown): value is JsonRecord {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+export function record(value: unknown, key: string): JsonRecord | undefined {
+ if (!isRecord(value)) return undefined;
+ const nested = value[key];
+ return isRecord(nested) ? nested : undefined;
+}
+
+export function str(value: unknown, key: string): string | undefined {
+ if (!isRecord(value)) return undefined;
+ const field = value[key];
+ return typeof field === "string" ? field : undefined;
+}
+
+export function num(value: unknown, key: string): number | undefined {
+ if (!isRecord(value)) return undefined;
+ const field = value[key];
+ return typeof field === "number" && Number.isFinite(field) ? field : undefined;
+}
+
+export function bool(value: unknown, key: string): boolean | undefined {
+ if (!isRecord(value)) return undefined;
+ const field = value[key];
+ return typeof field === "boolean" ? field : undefined;
+}
+
+export function arr(value: unknown, key: string): unknown[] {
+ if (!isRecord(value)) return [];
+ const field = value[key];
+ return Array.isArray(field) ? field : [];
+}
+
+/** A 2.x response body: `{data}` / `{location, data}` wrappers are unwrapped. */
+export function unwrap(value: unknown): unknown {
+ return isRecord(value) && "data" in value ? value.data : value;
+}
+
+export function omitUndefined<T extends JsonRecord>(value: T): T {
+ for (const key of Object.keys(value)) if (value[key] === undefined) delete value[key];
+ return value;
+}
diff --git a/apps/server/src/managed-opencode.ts b/apps/server/src/managed-opencode.ts
index ef365b9a..1818a59a 100644
--- a/apps/server/src/managed-opencode.ts
+++ b/apps/server/src/managed-opencode.ts
@@ -1,6 +1,8 @@
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";
export type ManagedChildProcess = {
exitCode: number | null;
@@ -121,6 +123,12 @@ 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;
@@ -144,11 +152,134 @@ 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 OpenCode 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,
+ });
+ } 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();
+ },
+ };
+}
+
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", "*"];
diff --git a/apps/server/src/mcp.authorization-link.e2e.test.ts b/apps/server/src/mcp.authorization-link.e2e.test.ts
index 3b837393..3fe006fa 100644
--- a/apps/server/src/mcp.authorization-link.e2e.test.ts
+++ b/apps/server/src/mcp.authorization-link.e2e.test.ts
@@ -4,6 +4,7 @@ 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 { buildOmniRushRuntimeConfigObjectFromSnapshot } from "./omnirush-runtime-config.js";
const repoRoot = resolve(import.meta.dir, "../../..");
@@ -91,26 +92,26 @@ const enginePath = findEngine();
const describeMaybe = enginePath ? describe : describe.skip;
describeMaybe("authorization-required MCP tool error pass-through", () => {
- let engine: ChildProcess;
+ let engine: ManagedOpencodeServer;
let mcp: ChildProcess;
let llm: ReturnType<typeof Bun.serve>;
let workspace = "";
let dataDir = "";
- let enginePort = 0;
let mcpPort = 0;
let modelSawAuthorizationError = false;
let modelRequests: Array<{ hasToolError: boolean; toolNames: Array<string | undefined> }> = [];
let engineLogs = "";
- const engineUrl = () => `http://127.0.0.1:${enginePort}`;
+ // The engine as the app runs it: the bundled 2.x engine behind the 1.x engine adapter.
const engineFetch = (path: string, init?: RequestInit) => {
- const url = new URL(`${engineUrl()}${path}`);
+ const url = new URL(`${engine.url}${path}`);
url.searchParams.set("directory", workspace);
- return fetch(url, init);
+ const headers = new Headers(init?.headers);
+ headers.set("authorization", `Basic ${Buffer.from(`${engine.username}:${engine.password}`).toString("base64")}`);
+ return fetch(url, { ...init, headers });
};
beforeAll(async () => {
- enginePort = await freePort();
mcpPort = await freePort();
workspace = mkdtempSync(join(tmpdir(), "mcp-authorization-link-ws-"));
dataDir = mkdtempSync(join(tmpdir(), "mcp-authorization-link-data-"));
@@ -164,7 +165,7 @@ describeMaybe("authorization-required MCP tool error pass-through", () => {
});
const runtime = buildOmniRushRuntimeConfigObjectFromSnapshot({});
- const configPath = join(workspace, "opencode.json");
+ const configPath = join(dataDir, "runtime-opencode-config.json");
writeFileSync(configPath, JSON.stringify({
$schema: "https://opencode.ai/config.json",
formatter: false,
@@ -218,23 +219,20 @@ describeMaybe("authorization-required MCP tool error pass-through", () => {
});
await waitFor(async () => (await fetch(`http://127.0.0.1:${mcpPort}/health`)).ok ? true : null, "MCP mock");
- engine = spawn(enginePath!, ["serve", "--pure", "--hostname", "127.0.0.1", "--port", String(enginePort)], {
+ engine = await createManagedOpencodeServer({
+ bin: enginePath!,
+ cwd: workspace,
env: {
- ...process.env,
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"),
XDG_CACHE_HOME: join(dataDir, "cache"),
},
- stdio: ["ignore", "pipe", "pipe"],
- });
- engine.stdout?.on("data", (chunk) => {
- engineLogs = `${engineLogs}${String(chunk)}`.slice(-8_000);
- });
- engine.stderr?.on("data", (chunk) => {
- engineLogs = `${engineLogs}${String(chunk)}`.slice(-8_000);
});
await waitFor(async () => (await engineFetch("/mcp")).ok ? true : null, "OpenCode engine");
await waitFor(async () => {
@@ -243,8 +241,8 @@ describeMaybe("authorization-required MCP tool error pass-through", () => {
}, "MCP connection");
}, 60_000);
- afterAll(() => {
- engine?.kill();
+ afterAll(async () => {
+ await engine?.close();
mcp?.kill();
llm?.stop(true);
if (workspace) rmSync(workspace, { recursive: true, force: true });
diff --git a/apps/server/src/mcp.oauth-flow.e2e.test.ts b/apps/server/src/mcp.oauth-flow.e2e.test.ts
index f5a2b1b7..8b048f40 100644
--- a/apps/server/src/mcp.oauth-flow.e2e.test.ts
+++ b/apps/server/src/mcp.oauth-flow.e2e.test.ts
@@ -1,13 +1,14 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { spawn, type ChildProcess } from "node:child_process";
-import { mkdtempSync, rmSync, writeFileSync, existsSync, readFileSync } from "node:fs";
+import { mkdtempSync, rmSync, writeFileSync, existsSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
/**
* Full MCP OAuth flow e2e:
*
- * real opencode engine (sidecar binary)
+ * real opencode engine (sidecar binary, started as the app starts it: the
+ * 2.x engine behind the 1.x engine adapter, managed-opencode.ts)
* -> mock OAuth MCP server (scripts/mock-oauth-mcp-server.mjs)
* -> discovery + dynamic client registration + PKCE (S256)
* -> authorization redirect ("the browser")
@@ -41,6 +42,8 @@ function findSidecar(): string | null {
return null;
}
+import { createManagedOpencodeServer, type ManagedOpencodeServer } from "./managed-opencode.js";
+
const enginePath = findSidecar();
const describeMaybe = enginePath ? describe : describe.skip;
@@ -71,24 +74,32 @@ async function getFreePort(): Promise<number> {
describeMaybe("mcp oauth flow against mock provider", () => {
let mockProc: ChildProcess;
- let engineProc: ChildProcess;
+ let engine: ManagedOpencodeServer;
let mockPort = 0;
- let enginePort = 0;
let workDir = "";
let dataDir = "";
const mockUrl = () => `http://127.0.0.1:${mockPort}`;
- const engineUrl = () => `http://127.0.0.1:${enginePort}`;
async function engineFetch(path: string, init?: RequestInit) {
- const url = new URL(`${engineUrl()}${path}`);
+ const url = new URL(`${engine.url}${path}`);
url.searchParams.set("directory", workDir);
- return fetch(url, init);
+ const headers = new Headers(init?.headers);
+ headers.set("authorization", `Basic ${Buffer.from(`${engine.username}:${engine.password}`).toString("base64")}`);
+ 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");
}
beforeAll(async () => {
mockPort = await getFreePort();
- enginePort = await getFreePort();
workDir = mkdtempSync(join(tmpdir(), "mcp-oauth-ws-"));
dataDir = mkdtempSync(join(tmpdir(), "mcp-oauth-data-"));
@@ -115,16 +126,19 @@ describeMaybe("mcp oauth flow against mock provider", () => {
"mock oauth server",
);
- engineProc = spawn(enginePath!, ["serve", "--hostname", "127.0.0.1", "--port", String(enginePort)], {
+ engine = await createManagedOpencodeServer({
+ bin: enginePath!,
+ cwd: workDir,
env: {
- ...process.env,
XDG_DATA_HOME: join(dataDir, "xdg-data"),
XDG_CONFIG_HOME: join(dataDir, "xdg-config"),
XDG_STATE_HOME: join(dataDir, "xdg-state"),
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"),
},
- stdio: "ignore",
});
await waitFor(
async () => {
@@ -136,8 +150,8 @@ describeMaybe("mcp oauth flow against mock provider", () => {
);
}, 60_000);
- afterAll(() => {
- engineProc?.kill();
+ afterAll(async () => {
+ await engine?.close();
mockProc?.kill();
rmSync(workDir, { recursive: true, force: true });
rmSync(dataDir, { recursive: true, force: true });
@@ -206,11 +220,8 @@ describeMaybe("mcp oauth flow against mock provider", () => {
);
expect(connected[MCP_NAME].status).toBe("connected");
- // Tokens are persisted for reuse across restarts.
- const authFile = join(dataDir, "xdg-data", "opencode", "mcp-auth.json");
- expect(existsSync(authFile)).toBe(true);
- const saved = JSON.parse(readFileSync(authFile, "utf8")) as Record<string, { tokens?: { accessToken?: string } }>;
- expect(saved[MCP_NAME]?.tokens?.accessToken).toStartWith("mock-access-");
+ // Tokens are persisted for reuse across restarts (a credential of the server's integration).
+ expect((await storedCredentials()).length).toBeGreaterThan(0);
// The mock saw the full, authenticated MCP handshake.
const log = (await (await fetch(`${mockUrl()}/requests`)).json()) as {
@@ -228,14 +239,8 @@ describeMaybe("mcp oauth flow against mock provider", () => {
test(
"engine silently refreshes an expired access token without re-authorization",
async () => {
- const authFile = join(dataDir, "xdg-data", "opencode", "mcp-auth.json");
- const before = JSON.parse(readFileSync(authFile, "utf8")) as Record<
- string,
- { tokens?: { accessToken?: string; refreshToken?: string } }
- >;
- const beforeAccess = before[MCP_NAME]?.tokens?.accessToken;
- expect(beforeAccess).toStartWith("mock-access-");
- expect(before[MCP_NAME]?.tokens?.refreshToken).toStartWith("mock-refresh-");
+ const before = await storedCredentials();
+ expect(before.length).toBeGreaterThan(0);
// Only assert on traffic that happens after this point.
const markLog = (await (await fetch(`${mockUrl()}/requests`)).json()) as { requests: Array<unknown> };
@@ -284,13 +289,7 @@ 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.
- const after = JSON.parse(readFileSync(authFile, "utf8")) as Record<
- string,
- { tokens?: { accessToken?: string; refreshToken?: string } }
- >;
- 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);
+ expect((await storedCredentials()).length).toBeGreaterThan(0);
},
60_000,
);
@@ -298,9 +297,6 @@ 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);
-
- const authFile = join(dataDir, "xdg-data", "opencode", "mcp-auth.json");
- const saved = JSON.parse(readFileSync(authFile, "utf8")) as Record<string, unknown>;
- expect(saved[MCP_NAME]).toBeUndefined();
+ expect(await storedCredentials()).toEqual([]);
}, 30_000);
});
diff --git a/apps/server/src/opencode-plugins/omnirush-engine2.ts b/apps/server/src/opencode-plugins/omnirush-engine2.ts
new file mode 100644
index 00000000..a6871122
--- /dev/null
+++ b/apps/server/src/opencode-plugins/omnirush-engine2.ts
@@ -0,0 +1,466 @@
+/**
+ * OmniRush.ai's engine plugins on the opencode 2.x plugin API.
+ *
+ * The OmniRush.ai plugins (managed policy, browser tools, capabilities
+ * knowledge, extensions, office/PDF attachments, spreadsheets, reasoning
+ * effort, swarm, …) are written against the 1.x hook contract
+ * (`tool.execute.before`, `experimental.chat.system.transform`,
+ * `chat.params`, `chat.headers`, `chat.message`, `shell.env`, `event`, custom
+ * `tool` definitions). The 2.x engine loads plugins of a different shape
+ * (`export default {id, setup(ctx)}` with `ctx.tool.hook`, `ctx.session.hook`,
+ * …) and no longer runs 1.x plugins at all. This module is the one 2.x plugin
+ * the engine loads (from `<config dir>/plugins/`): it builds every OmniRush.ai
+ * 1.x plugin with the 1.x factory input and bridges each 1.x hook onto its 2.x
+ * counterpart, translating tool names and inputs (`shell`↔`bash`,
+ * `subagent`↔`task`, `path`↔`filePath`) and message shapes both ways:
+ *
+ * 1.x hook 2.x hook
+ * experimental.chat.system.transform session "context" (system parts)
+ * experimental.chat.messages.transform session "context" (messages; media parts as file parts)
+ * chat.params session "context" (options)
+ * chat.headers session "model.request" (headers)
+ * chat.message session "prompt" (a changed model → session.switchModel)
+ * tool.execute.before / .after tool "execute.before" / "execute.after"
+ * shell.env shell "create.before"
+ * event 1.x events from the engine adapter's `/event` stream
+ * tool: {name: {args, execute}} tool.transform add (zod args as JSON Schema)
+ *
+ * The 1.x `client` the plugins receive is the 1.x SDK client on OmniRush.ai's
+ * engine adapter (engine2/facade.ts), whose URL and credentials the server
+ * hands the engine as OMNIRUSH_ENGINE_ADAPTER_URL / _AUTHORIZATION.
+ */
+import { createOpencodeClient } from "@opencode-ai/sdk";
+import { z } from "zod";
+import { v1ToolInput, v1ToolName, v2ToolInput } from "../engine2/shapes.js";
+import * as ManagedPolicy from "./managed-policy.js";
+import * as ChromeDevtools from "./omnirush-chrome-devtools.js";
+import * as CapabilitiesKnowledge from "./omnirush-capabilities-knowledge.js";
+import * as ExtensionsPreview from "./omnirush-extensions-preview.js";
+import * as OfficeAttachments from "./omnirush-office-attachments.js";
+import * as Spreadsheets from "./omnirush-spreadsheets.js";
+import * as PdfAttachments from "./omnirush-pdf-attachments.js";
+import * as AnthropicAdaptiveThinking from "./omnirush-anthropic-adaptive-thinking.js";
+import * as AnthropicToolSchema from "./omnirush-anthropic-tool-schema.js";
+import * as ReasoningEffort from "./omnirush-reasoning-effort.js";
+import * as TitleRecovery from "./omnirush-title-recovery.js";
+import * as Swarm from "./omnirush-swarm.js";
+
+type Rec = Record<string, unknown>;
+type Hook = (input: any, output: any) => Promise<void> | void;
+type V1Tool = { description?: string; args?: Record<string, unknown>; execute: (args: any, context: any) => Promise<unknown> | unknown };
+type V1Hooks = Record<string, unknown> & { tool?: Record<string, V1Tool>; event?: (input: { event: unknown }) => Promise<void> | void };
+
+/** Registration order is prompt order (as in the 1.x engine config's plugin list). */
+export const OMNIRUSH_V1_PLUGIN_MODULES: ReadonlyArray<Record<string, unknown>> = [
+ ManagedPolicy,
+ ChromeDevtools,
+ CapabilitiesKnowledge,
+ ExtensionsPreview,
+ OfficeAttachments,
+ Spreadsheets,
+ PdfAttachments,
+ AnthropicAdaptiveThinking,
+ AnthropicToolSchema,
+ ReasoningEffort,
+ TitleRecovery,
+ Swarm,
+];
+
+function isRec(value: unknown): value is Rec {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function adapterClient() {
+ const baseUrl = process.env.OMNIRUSH_ENGINE_ADAPTER_URL?.trim();
+ const authorization = process.env.OMNIRUSH_ENGINE_ADAPTER_AUTHORIZATION?.trim();
+ if (!baseUrl) return undefined;
+ return createOpencodeClient({ baseUrl, headers: authorization ? { authorization } : undefined });
+}
+
+async function adapterJson(path: string, directory: string): Promise<unknown> {
+ const baseUrl = process.env.OMNIRUSH_ENGINE_ADAPTER_URL?.trim();
+ if (!baseUrl) return undefined;
+ const authorization = process.env.OMNIRUSH_ENGINE_ADAPTER_AUTHORIZATION?.trim();
+ try {
+ const response = await fetch(`${baseUrl}${path}`, {
+ headers: { ...(authorization ? { authorization } : {}), "x-opencode-directory": encodeURIComponent(directory) },
+ signal: AbortSignal.timeout(5_000),
+ });
+ if (!response.ok) return undefined;
+ return await response.json();
+ } catch {
+ return undefined;
+ }
+}
+
+/** The text of a 2.x tool result (string or content list). */
+function resultText(content: unknown): string {
+ if (typeof content === "string") return content;
+ if (!Array.isArray(content)) return "";
+ return content.flatMap((item) => (isRec(item) && item.type === "text" && typeof item.text === "string" ? [item.text] : [])).join("\n");
+}
+
+/** A 1.x tool return (`string` or `{title, output, metadata, attachments}`) as a 2.x tool result. */
+export function v2ToolResult(value: unknown): { content: Array<Rec>; metadata?: Rec } {
+ if (typeof value === "string") return { content: [{ type: "text", text: value }] };
+ if (!isRec(value)) return { content: [{ type: "text", text: value === undefined ? "" : JSON.stringify(value) }] };
+ const output = typeof value.output === "string" ? value.output : JSON.stringify(value.output ?? "");
+ const content: Rec[] = [{ type: "text", text: output }];
+ for (const attachment of Array.isArray(value.attachments) ? value.attachments : []) {
+ if (!isRec(attachment) || typeof attachment.url !== "string" || typeof attachment.mime !== "string") continue;
+ content.push({ type: "file", uri: attachment.url, mime: attachment.mime, ...(typeof attachment.filename === "string" ? { name: attachment.filename } : {}) });
+ }
+ const metadata = isRec(value.metadata) ? { ...value.metadata } : {};
+ if (typeof value.title === "string" && value.title) metadata.__title = value.title;
+ return { content, ...(Object.keys(metadata).length ? { metadata } : {}) };
+}
+
+/** Zod raw shape (1.x tool `args`) as a JSON Schema object for the 2.x tool registry. */
+export function argsJsonSchema(args: Record<string, unknown> | undefined): Rec {
+ try {
+ const schema = z.toJSONSchema(z.object((args ?? {}) as z.ZodRawShape), { io: "input", unrepresentable: "any" }) as Rec;
+ delete schema.$schema;
+ return schema;
+ } catch {
+ return { type: "object", properties: {}, additionalProperties: true };
+ }
+}
+
+type AssetLike = { inline?: () => { mime: string; dataUrl: string } | undefined; mediaType?: string; constructor: new (input: unknown) => unknown };
+
+/** 2.x model-request messages as 1.x-style messages whose media parts read as 1.x file parts. */
+function messagesForV1(messages: unknown[]): { v1: Rec[]; restore: (edited: Rec[]) => unknown[] } {
+ let AssetCtor: AssetLike["constructor"] | undefined;
+ const originals = new Map<Rec, Rec>();
+ const v1 = messages.map((message, index) => {
+ if (!isRec(message) || !Array.isArray(message.content)) return { info: { id: `m${index}`, role: "system" }, content: [] } as Rec;
+ const content = message.content.map((part) => {
+ if (!isRec(part) || part.type !== "media" || !isRec(part.media)) return part;
+ const asset = part.media as unknown as AssetLike;
+ AssetCtor ??= asset.constructor;
+ const inline = typeof asset.inline === "function" ? asset.inline() : undefined;
+ if (!inline) return part;
+ const file: Rec = { type: "file", mime: inline.mime, url: inline.dataUrl, ...(typeof part.filename === "string" ? { filename: part.filename } : {}) };
+ originals.set(file, part);
+ return file;
+ });
+ return { ...message, info: { id: `m${index}`, role: message.role }, content };
+ });
+ const toV2Part = (part: unknown): unknown => {
+ if (!isRec(part)) return part;
+ const original = originals.get(part);
+ if (original) return original;
+ if (part.type === "file" && typeof part.url === "string" && typeof part.mime === "string" && AssetCtor) {
+ const match = part.url.match(/^data:([^;,]+);base64,(.*)$/s);
+ if (!match) return { type: "text", text: `[file ${String(part.filename ?? part.url)}]` };
+ const media = new AssetCtor({ source: { type: "base64", data: match[2], mediaType: match[1] } });
+ return { type: "media", media, ...(typeof part.filename === "string" ? { filename: part.filename } : {}) };
+ }
+ if (part.type === "text" && typeof part.text === "string") {
+ const { synthetic: _synthetic, id: _id, sessionID: _s, messageID: _m, ...rest } = part;
+ return rest;
+ }
+ return part;
+ };
+ const restore = (edited: Rec[]) =>
+ edited.map((message) => {
+ if (!isRec(message)) return message;
+ const { info: _info, parts, ...rest } = message;
+ const content = Array.isArray(message.content) ? message.content : Array.isArray(parts) ? parts : [];
+ return { ...rest, content: content.map(toV2Part) };
+ });
+ return { v1, restore };
+}
+
+type ModelInfo = Rec & { id: string; providerID: string };
+
+export default {
+ id: "omnirush",
+ async setup(ctx: any) {
+ const directory: string = ctx?.location?.directory ?? process.cwd();
+ const client = adapterClient();
+ const factoryInput = { client, directory, worktree: directory, project: { id: "omnirush", worktree: directory } };
+ const plugins: V1Hooks[] = [];
+ for (const module of OMNIRUSH_V1_PLUGIN_MODULES) {
+ for (const factory of Object.values(module)) {
+ if (typeof factory !== "function") continue;
+ try {
+ const hooks = await (factory as (input: unknown) => Promise<unknown>)(factoryInput);
+ if (isRec(hooks)) plugins.push(hooks as V1Hooks);
+ } catch (error) {
+ console.error("[omnirush] plugin factory failed", error instanceof Error ? error.message : error);
+ }
+ }
+ }
+ const hooks = (name: string): Hook[] => plugins.flatMap((plugin) => (typeof plugin[name] === "function" ? [plugin[name] as Hook] : []));
+
+ // 1.x model records for chat.params / chat.headers inputs (catalog read through the adapter, cached briefly).
+ let catalog: { at: number; models: Map<string, ModelInfo> } | null = null;
+ const modelInfo = async (ref: { providerID?: string; id?: string; variant?: string } | undefined): Promise<ModelInfo> => {
+ const providerID = ref?.providerID ?? "";
+ const id = ref?.id ?? "";
+ if (!catalog || Date.now() - catalog.at > 30_000) {
+ const payload = await adapterJson("/provider", directory);
+ const models = new Map<string, ModelInfo>();
+ for (const provider of isRec(payload) && Array.isArray(payload.all) ? payload.all : []) {
+ if (!isRec(provider) || !isRec(provider.models)) continue;
+ for (const model of Object.values(provider.models)) if (isRec(model) && typeof model.id === "string") models.set(`${provider.id}/${model.id}`, model as ModelInfo);
+ }
+ catalog = { at: Date.now(), models };
+ }
+ return catalog.models.get(`${providerID}/${id}`) ?? { id, providerID, api: { id, npm: "" }, capabilities: {} };
+ };
+ const hookInput = async (event: Rec) => {
+ const ref = isRec(event.model) ? (event.model as { providerID?: string; id?: string; variant?: string }) : undefined;
+ const model = await modelInfo(ref);
+ const agent = event.kind === "title" ? "title" : event.kind === "compaction" ? "compaction" : String(event.agent ?? "");
+ return {
+ sessionID: String(event.sessionID ?? ""),
+ agent,
+ model,
+ provider: { info: { id: model.providerID }, options: {} },
+ message: { id: `${String(event.sessionID ?? "")}:turn`, sessionID: event.sessionID, model: { providerID: model.providerID, modelID: model.id, variant: ref?.variant } },
+ };
+ };
+
+ // ---- custom tools ------------------------------------------------------
+ const tools: Array<[string, V1Tool]> = plugins.flatMap((plugin) => (isRec(plugin.tool) ? Object.entries(plugin.tool as Record<string, V1Tool>) : []));
+ if (tools.length > 0) {
+ await ctx.tool.transform((editor: any) => {
+ for (const [name, definition] of tools) {
+ editor.add({
+ name,
+ description: definition.description ?? name,
+ input: argsJsonSchema(definition.args),
+ options: { codemode: false },
+ execute: async (input: unknown, context: any) => {
+ const result = await definition.execute(input ?? {}, {
+ sessionID: context?.sessionID,
+ messageID: context?.messageID,
+ agent: context?.agent,
+ callID: context?.id,
+ abort: context?.signal ?? new AbortController().signal,
+ directory,
+ worktree: directory,
+ metadata: (update: unknown) => {
+ if (isRec(update) && typeof context?.progress === "function") void context.progress(isRec(update.metadata) ? update.metadata : update);
+ },
+ });
+ return v2ToolResult(result);
+ },
+ });
+ }
+ });
+ }
+ // The code-mode tool is never offered: tools are called directly, as with the 1.x engine.
+ // MCP servers (also ones from a project's own opencode.json) default to direct tools.
+ await ctx.tool.transform((editor: any) => {
+ if (editor.get?.("execute")) editor.remove("execute");
+ });
+ if (typeof ctx.mcp?.transform === "function") {
+ await ctx.mcp.transform((editor: any) => {
+ for (const [, server] of editor.list() as Array<[string, Rec]>) {
+ if (server.codemode === undefined) server.codemode = false;
+ }
+ });
+ }
+
+ // ---- tool calls --------------------------------------------------------
+ const before = hooks("tool.execute.before");
+ if (before.length) {
+ await ctx.tool.hook("execute.before", async (event: any) => {
+ const tool = v1ToolName(String(event.tool));
+ const output = { args: v1ToolInput(String(event.tool), event.input) };
+ for (const hook of before) await hook({ tool, sessionID: event.sessionID, callID: event.id, agent: event.agent }, output);
+ event.input = v2ToolInput(tool, isRec(output.args) ? output.args : {});
+ });
+ }
+ const after = hooks("tool.execute.after");
+ if (after.length) {
+ await ctx.tool.hook("execute.after", async (event: any) => {
+ if (event.status !== "completed" || !isRec(event.result)) return;
+ const tool = v1ToolName(String(event.tool));
+ const original = resultText(event.result.content ?? event.result.output);
+ const output: { title: string; output: string; metadata: Rec } = {
+ title: "",
+ output: original,
+ metadata: isRec(event.result.metadata) ? { ...event.result.metadata } : {},
+ };
+ for (const hook of after) await hook({ tool, sessionID: event.sessionID, callID: event.id, args: v1ToolInput(String(event.tool), event.input) }, output);
+ const files = Array.isArray(event.result.content) ? event.result.content.filter((item: unknown) => isRec(item) && item.type === "file") : [];
+ event.result = {
+ ...event.result,
+ content: output.output === original && typeof event.result.content !== "undefined" ? event.result.content : [{ type: "text", text: output.output }, ...files],
+ metadata: output.metadata,
+ };
+ });
+ }
+
+ // ---- shell env ---------------------------------------------------------
+ const shellEnv = hooks("shell.env");
+ if (shellEnv.length) {
+ await ctx.shell.hook("create.before", async (event: any) => {
+ const output = { env: { ...(isRec(event.env) ? event.env : {}) } };
+ for (const hook of shellEnv) await hook({ cwd: event.cwd }, output);
+ event.env = output.env;
+ });
+ }
+
+ // ---- model request context: system prompt, messages, params -----------
+ const systemHooks = hooks("experimental.chat.system.transform");
+ const messageHooks = hooks("experimental.chat.messages.transform");
+ const paramHooks = hooks("chat.params");
+ if (systemHooks.length || messageHooks.length || paramHooks.length) {
+ await ctx.session.hook("context", async (event: any) => {
+ const input = await hookInput(event);
+ if (systemHooks.length && Array.isArray(event.system)) {
+ const parts = event.system as Rec[];
+ const output = { system: parts.map((part) => (typeof part?.text === "string" ? part.text : "")) };
+ for (const hook of systemHooks) await hook({ sessionID: input.sessionID, model: input.model }, output);
+ event.system = output.system.map((text, index) => (parts[index] && parts[index]!.text === text ? parts[index] : { ...(parts[index] ?? {}), type: "text", text }));
+ }
+ if (messageHooks.length && Array.isArray(event.messages)) {
+ const { v1, restore } = messagesForV1(event.messages);
+ const output = { messages: v1 };
+ for (const hook of messageHooks) await hook({ sessionID: input.sessionID, model: input.model }, output);
+ event.messages = restore(output.messages as Rec[]);
+ }
+ if (paramHooks.length && isRec(event.options)) {
+ const options = event.options as Rec;
+ const { temperature, topP, topK, ...rest } = options;
+ const output: Rec & { options: Rec } = { temperature, topP, topK, options: { ...rest } };
+ for (const hook of paramHooks) await hook(input, output);
+ const next: Rec = { ...output.options };
+ if (output.temperature !== undefined) next.temperature = output.temperature;
+ if (output.topP !== undefined) next.topP = output.topP;
+ if (output.topK !== undefined) next.topK = output.topK;
+ event.options = next;
+ }
+ });
+ }
+
+ const headerHooks = hooks("chat.headers");
+ if (headerHooks.length) {
+ await ctx.session.hook("model.request", async (event: any) => {
+ const input = await hookInput(event);
+ const output = { headers: { ...(isRec(event.headers) ? event.headers : {}) } as Record<string, string> };
+ for (const hook of headerHooks) await hook(input, output);
+ event.headers = output.headers;
+ });
+ }
+
+ const messageCreated = hooks("chat.message");
+ if (messageCreated.length) {
+ await ctx.session.hook("prompt", async (event: any) => {
+ const sessionID = String(event.sessionID ?? "");
+ const info = await adapterJson(`/session/${encodeURIComponent(sessionID)}`, directory);
+ const current = isRec(info) && isRec(info.model) ? { providerID: String(info.model.providerID), modelID: String(info.model.id), variant: typeof info.model.variant === "string" && info.model.variant !== "default" ? info.model.variant : undefined } : undefined;
+ const message: Rec = { id: event.messageID, sessionID, role: "user", model: current ? { ...current } : undefined };
+ const agent = isRec(info) && typeof info.agent === "string" ? info.agent : undefined;
+ for (const hook of messageCreated) {
+ await hook({ sessionID, agent, model: current ? { providerID: current.providerID, modelID: current.modelID } : undefined, messageID: event.messageID, variant: current?.variant }, { message, parts: [] });
+ }
+ const chosen = isRec(message.model) ? message.model : undefined;
+ if (chosen && typeof chosen.providerID === "string" && typeof chosen.modelID === "string"
+ && (!current || chosen.providerID !== current.providerID || chosen.modelID !== current.modelID || (chosen.variant ?? undefined) !== current.variant)) {
+ await ctx.session.switchModel({
+ sessionID,
+ model: { providerID: chosen.providerID, id: chosen.modelID, ...(typeof chosen.variant === "string" && chosen.variant ? { variant: chosen.variant } : {}) },
+ }).catch((error: unknown) => console.error("[omnirush] model switch failed", error instanceof Error ? error.message : error));
+ }
+ });
+ }
+
+ // ---- tool listing: the adapter answers 1.x `/experimental/tool[/ids]` from this report ----
+ let reportedTools = "";
+ const reportTools = async () => {
+ const baseUrl = process.env.OMNIRUSH_ENGINE_ADAPTER_URL?.trim();
+ if (!baseUrl || typeof ctx.tool?.list !== "function") return;
+ try {
+ const list = (await ctx.tool.list()) as Array<Rec & { id: string }>;
+ const tools = list
+ .map((tool) => ({
+ id: v1ToolName(String(tool.id ?? tool.name ?? "")),
+ description: typeof tool.description === "string" ? tool.description : "",
+ parameters: isRec(tool.input) && typeof (tool.input as Rec).type === "string" ? tool.input : {},
+ }))
+ .filter((tool) => tool.id && tool.id !== "execute")
+ .sort((left, right) => left.id.localeCompare(right.id));
+ const key = JSON.stringify(tools.map((tool) => tool.id));
+ if (key === reportedTools) return;
+ const authorization = process.env.OMNIRUSH_ENGINE_ADAPTER_AUTHORIZATION?.trim();
+ const response = await fetch(`${baseUrl}/omnirush/engine-tools`, {
+ method: "POST",
+ headers: { "content-type": "application/json", ...(authorization ? { authorization } : {}) },
+ body: JSON.stringify({ directory, tools }),
+ signal: AbortSignal.timeout(5_000),
+ });
+ if (response.ok) reportedTools = key;
+ } catch {
+ // Reported again on the next tick.
+ }
+ };
+ await reportTools();
+ const toolTimer = setInterval(() => void reportTools(), 3_000);
+ toolTimer.unref?.();
+
+ // ---- events: the 1.x stream of the engine adapter ---------------------
+ const eventHooks = plugins.flatMap((plugin) => (typeof plugin.event === "function" ? [plugin.event] : []));
+ const controller = new AbortController();
+ if (eventHooks.length && process.env.OMNIRUSH_ENGINE_ADAPTER_URL) {
+ void (async () => {
+ const baseUrl = process.env.OMNIRUSH_ENGINE_ADAPTER_URL!.trim();
+ const authorization = process.env.OMNIRUSH_ENGINE_ADAPTER_AUTHORIZATION?.trim();
+ while (!controller.signal.aborted) {
+ try {
+ const response = await fetch(`${baseUrl}/event`, {
+ headers: { ...(authorization ? { authorization } : {}), accept: "text/event-stream", "x-opencode-directory": encodeURIComponent(directory) },
+ signal: controller.signal,
+ });
+ if (!response.ok || !response.body) throw new Error(`event stream ${response.status}`);
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = "";
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+ let index: number;
+ while ((index = buffer.indexOf("\n\n")) >= 0) {
+ const frame = buffer.slice(0, index);
+ buffer = buffer.slice(index + 2);
+ const data = frame.split("\n").filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
+ if (!data) continue;
+ let event: unknown;
+ try {
+ event = JSON.parse(data);
+ } catch {
+ continue;
+ }
+ for (const hook of eventHooks) {
+ try {
+ await hook!({ event });
+ } catch (error) {
+ console.error("[omnirush] plugin event hook failed", error instanceof Error ? error.message : error);
+ }
+ }
+ }
+ }
+ } catch {
+ if (controller.signal.aborted) return;
+ }
+ await new Promise((resolve) => setTimeout(resolve, 1_000));
+ }
+ })();
+ }
+
+ return async () => {
+ clearInterval(toolTimer);
+ controller.abort();
+ for (const plugin of plugins) {
+ const dispose = plugin.dispose;
+ if (typeof dispose === "function") await Promise.resolve((dispose as () => unknown)()).catch(() => undefined);
+ }
+ };
+ },
+};
diff --git a/constants.json b/constants.json
index da2c0879..3ac9c7e0 100644
--- a/constants.json
+++ b/constants.json
@@ -1,4 +1,4 @@
{
- "opencodeVersion": "v1.18.32",
+ "opencodeVersion": "v2.0.18",
"opencodeV2Version": "0.0.0-beta-19086"
}