A desktop coding agent with free access to frontier models.
TypeScript
build: bundle the engine from the CLI release
ogsamrat0eeb32a5807c
diff --git a/.github/actions/setup-tests/action.yml b/.github/actions/setup-tests/action.ymlindex 30cca990..12f76433 100644--- a/.github/actions/setup-tests/action.yml+++ b/.github/actions/setup-tests/action.yml@@ -13,70 +13,19 @@ runs:with:version: 11.4.0+ # The engine is OmniRush.ai's build of opencode 1.18.32, on a private+ # release of omnirush-ai/omnirush-cli (sha256-pinned in+ # apps/desktop/scripts/engine-release.json). The calling job passes a token+ # that can read it as OMNIRUSH_ENGINE_TOKEN.- name: Install OpenCode CLIshell: bashrun: |set -euo pipefail-- 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//')"-- if [ -z "$version" ]; then- echo "Unable to resolve OpenCode version from constants.json." >&2- 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_pkg="cli-linux-arm64"- else- opencode_pkg="cli-linux-x64-baseline"- fi- ;;- macOS)- if [ "$arch" = "arm64" ]; then- opencode_pkg="cli-darwin-arm64"- else- opencode_pkg="cli-darwin-x64-baseline"- fi- ;;- *)- echo "Unsupported OS: ${RUNNER_OS}" >&2- exit 1- ;;- esac-- 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"-- 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/package/bin/opencode" ]; then- bin_path="$extract_dir/package/bin/opencode"- else- echo "OpenCode binary not found in package" >&2- ls -laR "$extract_dir"- exit 1- fi-+ sidecar_dir="$RUNNER_TEMP/opencode-sidecar"+ node apps/desktop/scripts/prepare-sidecar.mjs --outdir "$sidecar_dir"install_dir="$HOME/.opencode/bin"mkdir -p "$install_dir"- cp "$bin_path" "$install_dir/opencode"+ cp "$sidecar_dir/opencode" "$install_dir/opencode"chmod 755 "$install_dir/opencode"echo "$install_dir" >> "$GITHUB_PATH"diff --git a/.github/workflows/build-electron-desktop.yml b/.github/workflows/build-electron-desktop.ymlindex 103f16bc..298196f0 100644--- a/.github/workflows/build-electron-desktop.yml+++ b/.github/workflows/build-electron-desktop.yml@@ -14,6 +14,11 @@ on:- package.json- .github/workflows/build-electron-desktop.yml+# The bundled engine is fetched from a private release of omnirush-ai/omnirush-cli+# (apps/desktop/scripts/prepare-sidecar.mjs): this repo's own token cannot read it.+env:+ OMNIRUSH_ENGINE_TOKEN: ${{ secrets.OMNIRUSH_ENGINE_TOKEN }}+permissions:contents: read@@ -97,29 +102,51 @@ jobs:- name: Install dependenciesrun: pnpm install --frozen-lockfile+ # Same signing inputs as the release workflow's mac leg.- name: Write notary API keyenv:- APPLE_NOTARY_API_KEY_P8_BASE64: ${{ secrets.APPLE_NOTARY_API_KEY_P8_BASE64 }}+ APPLE_API_KEY_P8_BASE64: ${{ secrets.APPLE_API_KEY }}+ APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}+ APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}run: |set -euo pipefail-- NOTARY_KEY_PATH="$RUNNER_TEMP/AuthKey.p8"- printf '%s' "$APPLE_NOTARY_API_KEY_P8_BASE64" | base64 --decode > "$NOTARY_KEY_PATH"- chmod 600 "$NOTARY_KEY_PATH"-- echo "NOTARY_KEY_PATH=$NOTARY_KEY_PATH" >> "$GITHUB_ENV"+ key="$RUNNER_TEMP/AuthKey_${APPLE_API_KEY_ID}.p8"+ printf '%s' "$APPLE_API_KEY_P8_BASE64" | base64 --decode > "$key"+ chmod 600 "$key"+ {+ echo "APPLE_API_KEY=$key"+ echo "APPLE_API_KEY_ID=$APPLE_API_KEY_ID"+ echo "APPLE_API_ISSUER=$APPLE_API_ISSUER"+ } >> "$GITHUB_ENV"- name: Package Electron desktop (signed + notarized, no publish)env:- CSC_LINK: ${{ secrets.APPLE_CODESIGN_CERT_P12_BASE64 }}- CSC_KEY_PASSWORD: ${{ secrets.APPLE_CODESIGN_CERT_PASSWORD }}- MACOS_NOTARIZE: true- APPLE_API_KEY: ${{ secrets.APPLE_NOTARY_API_KEY_ID }}- APPLE_API_ISSUER: ${{ secrets.APPLE_NOTARY_API_ISSUER_ID }}- APPLE_API_KEY_PATH: ${{ env.NOTARY_KEY_PATH }}+ CSC_LINK: ${{ secrets.MAC_CSC_LINK }}+ CSC_KEY_PASSWORD: ${{ secrets.MAC_CSC_KEY_PASSWORD }}OMNIRUSH_DESKTOP_SENTRY_DSN: ${{ secrets.OMNIRUSH_DESKTOP_SENTRY_DSN || vars.OMNIRUSH_DESKTOP_SENTRY_DSN }}OMNIRUSH_DESKTOP_SENTRY_TRACES_SAMPLE_RATE: ${{ vars.OMNIRUSH_DESKTOP_SENTRY_TRACES_SAMPLE_RATE || '0.01' }}run: |set -euo pipefailpnpm --filter @omnirush/desktop run build:electron- pnpm --dir apps/desktop exec electron-builder --config electron-builder.yml --mac dmg zip --publish never+ pnpm --dir apps/desktop exec electron-builder --config electron-builder.yml --mac --arm64 -c.mac.notarize=true --publish never++ - name: Verify macOS signature and notarization+ run: |+ set -euo pipefail+ app=$(find apps/desktop/dist-electron -maxdepth 2 -name '*.app' -type d | head -n 1)+ codesign --verify --deep --strict --verbose=2 "$app"+ codesign -dv --verbose=4 "$app" 2>&1 | grep -E '^(Authority|TeamIdentifier|Runtime)'+ spctl --assess --type execute --verbose=4 "$app"+ xcrun stapler validate "$app"++ - name: Verify the bundled engine is signed and runs+ run: |+ set -euo pipefail+ app=$(find apps/desktop/dist-electron -maxdepth 2 -name '*.app' -type d | head -n 1)+ engine="$app/Contents/Resources/sidecars/opencode-aarch64-apple-darwin"+ codesign --verify --strict --verbose=2 "$engine"+ codesign -dv --verbose=4 "$engine" 2>&1 | grep -E '^(Authority|TeamIdentifier|Runtime|Identifier)'+ codesign -dv --verbose=4 "$engine" 2>&1 | grep -q '^Authority=Developer ID Application' || { echo "the bundled engine is not Developer ID signed" >&2; exit 1; }+ version=$("$engine" --version)+ echo "bundled engine: $version"+ test "$version" = "$(node -p "require('./apps/desktop/scripts/engine-release.json').version")"diff --git a/.github/workflows/ci-tests.yml b/.github/workflows/ci-tests.ymlindex d0f3ce33..b86d3477 100644--- a/.github/workflows/ci-tests.yml+++ b/.github/workflows/ci-tests.yml@@ -17,8 +17,10 @@ concurrency:group: omnirush-tests-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }}cancel-in-progress: ${{ github.event_name == 'pull_request' }}+# The bundled engine is fetched from a private release of omnirush-ai/omnirush-cli+# (apps/desktop/scripts/prepare-sidecar.mjs): this repo's own token cannot read it.env:- OPENCODE_GITHUB_REPO: ${{ vars.OPENCODE_GITHUB_REPO || 'anomalyco/opencode' }}+ OMNIRUSH_ENGINE_TOKEN: ${{ secrets.OMNIRUSH_ENGINE_TOKEN }}permissions:contents: read@@ -88,7 +90,7 @@ jobs:~/.cache/electron~/.cache/electron-builderapps/desktop/resources/sidecars- key: ${{ runner.os }}-${{ runner.arch }}-desktop-smoke-${{ hashFiles('constants.json', 'pnpm-lock.yaml', 'apps/desktop/scripts/prepare-sidecar.mjs') }}+ key: ${{ runner.os }}-${{ runner.arch }}-desktop-smoke-${{ hashFiles('constants.json', 'pnpm-lock.yaml', 'apps/desktop/scripts/prepare-sidecar.mjs', 'apps/desktop/scripts/engine-release.json') }}- name: Setup testsid: setupuses: ./.github/actions/setup-testsdiff --git a/.github/workflows/daytona-e2e.yml b/.github/workflows/daytona-e2e.ymlindex d85a3aec..5b9434eb 100644--- a/.github/workflows/daytona-e2e.yml+++ b/.github/workflows/daytona-e2e.yml@@ -20,6 +20,11 @@ on:workflows: [Warden]types: [completed]+# The bundled engine is fetched from a private release of omnirush-ai/omnirush-cli+# (apps/desktop/scripts/prepare-sidecar.mjs): this repo's own token cannot read it.+env:+ OMNIRUSH_ENGINE_TOKEN: ${{ secrets.OMNIRUSH_ENGINE_TOKEN }}+permissions:actions: readcontents: readdiff --git a/.github/workflows/linux-packages.yml b/.github/workflows/linux-packages.ymlindex fdd329d6..071a5080 100644--- a/.github/workflows/linux-packages.yml+++ b/.github/workflows/linux-packages.yml@@ -11,11 +11,17 @@ on:paths:- apps/desktop/electron-builder*.yml- apps/desktop/scripts/prepare-sidecar.mjs+ - apps/desktop/scripts/engine-release.json- packaging/aur/**- scripts/aur/**- .github/workflows/release-desktop.yml- .github/workflows/linux-packages.yml+# The bundled engine is fetched from a private release of omnirush-ai/omnirush-cli+# (apps/desktop/scripts/prepare-sidecar.mjs): this repo's own token cannot read it.+env:+ OMNIRUSH_ENGINE_TOKEN: ${{ secrets.OMNIRUSH_ENGINE_TOKEN }}+permissions:contents: readdiff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.ymlindex abfa6e72..a9b9e4e5 100644--- a/.github/workflows/release-desktop.yml+++ b/.github/workflows/release-desktop.yml@@ -11,6 +11,11 @@ on:required: truetype: string+# The bundled engine is fetched from a private release of omnirush-ai/omnirush-cli+# (apps/desktop/scripts/prepare-sidecar.mjs): this repo's own token cannot read it.+env:+ OMNIRUSH_ENGINE_TOKEN: ${{ secrets.OMNIRUSH_ENGINE_TOKEN }}+permissions:contents: writediff --git a/apps/desktop/electron/runtime.mjs b/apps/desktop/electron/runtime.mjsindex be784125..5733e715 100644--- a/apps/desktop/electron/runtime.mjs+++ b/apps/desktop/electron/runtime.mjs@@ -1824,17 +1824,6 @@ export function createRuntimeManager({};}- async function pinnedOpencodeInstallCommand() {- const constantsPath = path.resolve(desktopRoot, "../../constants.json");- const payload = JSON.parse(await readFile(constantsPath, "utf8"));- const version = String(payload?.opencodeVersion ?? "").trim().replace(/^v/, "");- if (!version) {- throw new Error("constants.json is missing opencodeVersion");- }- // The 2.x engine ships on npm as @opencode/cli (binaries `opencode` / `opencode2`).- return `npm install -g @opencode/cli@${version}`;- }-function processMatchesSidecar(command) {return commandMatchesPackagedSidecar(command, sidecarDirs);}@@ -2591,27 +2580,15 @@ export function createRuntimeManager({}async function engineInstall() {- if (process.platform === "win32") {- return {- ok: false,- status: -1,- stdout: "",- stderr:- "Guided install is not supported on Windows yet. Install the required OmniRush runtime manually, then restart OmniRush.ai.",- };- }-- const installDir = path.join(app.getPath("home"), ".opencode", "bin");- const command = await pinnedOpencodeInstallCommand();- const result = await runShellCommand("bash", ["-lc", command], {- env: { ...(await buildChildEnv()), OPENCODE_INSTALL_DIR: installDir },- timeoutMs: 180_000,- });+ // The engine is OmniRush.ai's own build of opencode 1.18.32 and ships+ // inside the app (resources/sidecars); there is no separate installer.+ // An upstream opencode install would keep its sessions apart from the+ // app's, so none is offered.return {- ok: result.status === 0,- status: result.status,- stdout: result.stdout,- stderr: result.stderr,+ ok: false,+ status: -1,+ stdout: "",+ stderr: "The OmniRush engine ships inside OmniRush.ai. Reinstall OmniRush.ai to restore it, then restart the app.",};}diff --git a/apps/desktop/electron/runtime.test.mjs b/apps/desktop/electron/runtime.test.mjsindex 12572d96..d1b99a6c 100644--- a/apps/desktop/electron/runtime.test.mjs+++ b/apps/desktop/electron/runtime.test.mjs@@ -90,14 +90,22 @@ describe("workspace root preparation", () => {});describe("bundled OpenCode runtime", () => {- 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"));-- // 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");+ it("pins the 1.x engine build the CLI bundles", async () => {+ const here = path.dirname(fileURLToPath(import.meta.url));+ const constants = JSON.parse(await readFile(path.resolve(here, "../../../constants.json"), "utf8"));+ const release = JSON.parse(await readFile(path.resolve(here, "../scripts/engine-release.json"), "utf8"));++ // OmniRush.ai's build of opencode 1.18.32 (engine-1.18.32-r2 of+ // omnirush-ai/omnirush-cli), the engine the CLI ships; the 2.x engine+ // bundled from 2.2.0 is gone (its sessions are imported, engine2/import.ts).+ assert.equal(constants.opencodeVersion, "v1.18.32");+ assert.equal(release.version, "1.18.32");+ assert.equal(release.repo, "omnirush-ai/omnirush-cli");+ assert.equal(release.tag, "engine-1.18.32-r2");+ for (const target of ["aarch64-apple-darwin", "x86_64-apple-darwin", "x86_64-unknown-linux-gnu", "aarch64-unknown-linux-gnu"]) {+ assert.match(release.assets[target].name, /^omnirush-engine-[a-z0-9-]+-1\.18\.32\.tar\.gz$/);+ assert.match(release.assets[target].sha256, /^[0-9a-f]{64}$/);+ }});});diff --git a/apps/desktop/scripts/engine-release.json b/apps/desktop/scripts/engine-release.jsonnew file mode 100644index 00000000..b5adba6a--- /dev/null+++ b/apps/desktop/scripts/engine-release.json@@ -0,0 +1,35 @@+{+ "repo": "omnirush-ai/omnirush-cli",+ "tag": "engine-1.18.32-r2",+ "version": "1.18.32",+ "license": {+ "name": "LICENSE-opencode-MIT",+ "sha256": "625f0f619133f89bbbb2abe37369613dfa1885eba1e50d02170deb62bb42cb6b"+ },+ "assets": {+ "aarch64-apple-darwin": {+ "name": "omnirush-engine-darwin-arm64-1.18.32.tar.gz",+ "sha256": "5682ff0a931169798bb47edec41421ab1bfe14a7894f7f7370be44d8368a165f"+ },+ "x86_64-apple-darwin": {+ "name": "omnirush-engine-darwin-x64-1.18.32.tar.gz",+ "sha256": "4312c372d2b0feb62da245872de448bd69709bdb24b2a2d5d9a07f2a819493c0"+ },+ "x86_64-unknown-linux-gnu": {+ "name": "omnirush-engine-linux-x64-1.18.32.tar.gz",+ "sha256": "e6eb85520b08cdf00e28080d500ea4ee36759d14e5c13e646d45eb381da78d15"+ },+ "aarch64-unknown-linux-gnu": {+ "name": "omnirush-engine-linux-arm64-1.18.32.tar.gz",+ "sha256": "9d9c9b164cf104cf2575a16806323012a8965567a82c497d885ca6c0b1c87232"+ },+ "x86_64-pc-windows-msvc": {+ "name": "omnirush-engine-win32-x64-1.18.32.tar.gz",+ "sha256": "b409697469ae0a3b525b5a24019109195202e2cc96deb651489567b8c785d47e"+ },+ "aarch64-pc-windows-msvc": {+ "name": "omnirush-engine-win32-arm64-1.18.32.tar.gz",+ "sha256": "ceef50fa7e4a2176b725b2076a142c0178b411f02618e109741d87293fc98d6f"+ }+ }+}diff --git a/apps/desktop/scripts/prepare-sidecar.mjs b/apps/desktop/scripts/prepare-sidecar.mjsindex 70eb0d09..4829c533 100644--- a/apps/desktop/scripts/prepare-sidecar.mjs+++ b/apps/desktop/scripts/prepare-sidecar.mjs@@ -15,7 +15,7 @@ import {writeFileSync,} from "fs";import { basename, dirname, join, resolve } from "path";-import { tmpdir } from "os";+import { homedir, tmpdir } from "os";import { fileURLToPath } from "url";const __dirname = dirname(fileURLToPath(import.meta.url));@@ -32,20 +32,6 @@ const sidecarOverride = process.env.OMNIRUSH_SIDECAR_DIR?.trim() || readArg("--oconst sidecarDir = sidecarOverride ? resolve(sidecarOverride) : join(__dirname, "..", "resources", "sidecars");const constantsPath = resolve(__dirname, "..", "..", "..", "constants.json");-const opencodeGithubRepo = (() => {- const raw =- process.env.OPENCODE_GITHUB_REPO?.trim() ||- process.env.OMNIRUSH_OPENCODE_GITHUB_REPO?.trim() ||- "anomalyco/opencode";- const normalized = raw- .replace(/^https:\/\/github\.com\//i, "")- .replace(/\.git$/i, "")- .trim();- if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(normalized)) {- return "anomalyco/opencode";- }- return normalized;-})();const opencodeVersion = (() => {try {const raw = readFileSync(constantsPath, "utf8");@@ -63,7 +49,12 @@ const normalizeVersion = (value) => {return raw.startsWith("v") ? raw.slice(1) : raw;};-const opencodeAssetOverride = process.env.OPENCODE_ASSET?.trim() || null;+// The engine is OmniRush.ai's build of opencode 1.18.32 (the one the CLI+// bundles), published as per-platform tarballs on a private GitHub release of+// the CLI repo and sha256-pinned in engine-release.json. Each tarball holds one+// executable, `opencode[.exe]`, at its root.+const engineReleasePath = resolve(__dirname, "engine-release.json");+const engineRelease = JSON.parse(readFileSync(engineReleasePath, "utf8"));// Target triple for native platform binariesconst resolvedTargetTriple = (() => {@@ -157,7 +148,7 @@ const readBinaryVersion = (filePath) => {try {const result = spawnSync(filePath, ["--version"], { encoding: "utf8" });if (result.status === 0 && result.stdout) {- // 2.x prints "opencode v2.0.18"; 1.x printed the bare version.+ // The engine prints the bare version ("1.18.32").const match = result.stdout.trim().match(/(\d+\.\d+\.\d+(?:[-+][\w.-]+)?)\s*$/);return match ? match[1] : result.stdout.trim();}@@ -224,70 +215,129 @@ if (!normalizedOpencodeVersion) {process.exit(1);}-// 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",-};+if (normalizedOpencodeVersion !== engineRelease.version) {+ console.error(+ `constants.json pins OpenCode ${normalizedOpencodeVersion}, but ${engineReleasePath} pins the engine release ${engineRelease.tag} (${engineRelease.version}).`+ );+ process.exit(1);+}-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 engineAsset = resolvedTargetTriple ? engineRelease.assets?.[resolvedTargetTriple] ?? null : null;++/** What the sidecar directory holds: the engine release and archive it was taken from. */+const readRecordedEngine = () => {+ const names = [resolvedTargetTriple ? `versions.json-${resolvedTargetTriple}${isWindowsTarget ? ".exe" : ""}` : null, "versions.json"];+ for (const name of names.filter(Boolean)) {+ try {+ const parsed = JSON.parse(readFileSync(join(sidecarDir, name), "utf8"));+ if (parsed?.opencode) return parsed.opencode;+ } catch {+ // not recorded+ }+ }+ return null;+};+const recordedEngine = readRecordedEngine();const shouldDownloadOpencode =!opencodeCandidatePath ||!existsSync(opencodeCandidatePath) ||isStubBinary(opencodeCandidatePath) ||!existingOpencodeVersion ||- existingOpencodeVersion !== normalizedOpencodeVersion;+ existingOpencodeVersion !== normalizedOpencodeVersion ||+ !engineAsset ||+ recordedEngine?.archiveSha256 !== engineAsset.sha256 ||+ (opencodeCandidatePath && recordedEngine?.sha256 !== sha256File(opencodeCandidatePath));if (!shouldDownloadOpencode) {- console.log(`OpenCode sidecar already present (${existingOpencodeVersion}).`);+ console.log(`OpenCode sidecar already present (${existingOpencodeVersion}, ${engineRelease.tag}).`);}-/** 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;+/** A token that can read the private engine release (never printed). */+const githubToken = () => {+ for (const name of ["OMNIRUSH_ENGINE_TOKEN", "GH_TOKEN", "GITHUB_TOKEN"]) {+ const value = process.env[name]?.trim();+ if (value) return value;+ }+ const gh = spawnSync("gh", ["auth", "token"], { encoding: "utf8" });+ return gh.status === 0 ? gh.stdout.trim() || null : null;};-if (shouldDownloadOpencode) {- if (!opencodePackage || !opencodeUrl) {- console.error(- `No OpenCode package configured for target ${resolvedTargetTriple ?? "unknown"}. Set OPENCODE_ASSET to override.`+const githubApi = async (url, accept, token) => {+ const response = await fetch(url, {+ headers: {+ accept,+ authorization: `Bearer ${token}`,+ "user-agent": "omnirush-desktop-prepare-sidecar",+ "x-github-api-version": "2022-11-28",+ },+ redirect: "follow",+ });+ if (!response.ok) throw new Error(`GitHub answered ${response.status} for ${url}`);+ return response;+};++/** The pinned archive's bytes: a local copy (OMNIRUSH_ENGINE_ARCHIVE), the cache, or the release. */+const readEngineArchive = async () => {+ const verify = (bytes, source) => {+ const actual = createHash("sha256").update(bytes).digest("hex");+ if (actual !== engineAsset.sha256) {+ throw new Error(`Checksum mismatch for ${engineAsset.name} from ${source}: expected ${engineAsset.sha256}, got ${actual}`);+ }+ return bytes;+ };+ const local = process.env.OMNIRUSH_ENGINE_ARCHIVE?.trim();+ if (local) return verify(readFileSync(resolve(local)), local);+ const cacheDir = process.env.OMNIRUSH_ENGINE_CACHE?.trim()+ ? resolve(process.env.OMNIRUSH_ENGINE_CACHE.trim())+ : join(homedir(), ".cache", "omnirush-desktop", "engine");+ const cached = join(cacheDir, engineRelease.tag, engineAsset.name);+ if (existsSync(cached)) {+ try {+ return verify(readFileSync(cached), cached);+ } catch (error) {+ console.warn(`${error instanceof Error ? error.message : String(error)}; downloading it again.`);+ }+ }+ const token = githubToken();+ if (!token) {+ throw new Error(+ `A GitHub token that can read ${engineRelease.repo} is required to fetch the engine from its private release ${engineRelease.tag}: ` ++ "set OMNIRUSH_ENGINE_TOKEN (or GH_TOKEN / GITHUB_TOKEN), sign in with `gh auth login`, or point OMNIRUSH_ENGINE_ARCHIVE at the archive.",);+ }+ const release = await (await githubApi(+ `https://api.github.com/repos/${engineRelease.repo}/releases/tags/${engineRelease.tag}`,+ "application/vnd.github+json",+ token,+ )).json();+ const asset = (release.assets ?? []).find((entry) => entry.name === engineAsset.name);+ if (!asset) throw new Error(`${engineAsset.name} is not an asset of ${engineRelease.repo} release ${engineRelease.tag}`);+ const bytes = verify(Buffer.from(await (await githubApi(asset.url, "application/octet-stream", token)).arrayBuffer()), asset.url);+ try {+ mkdirSync(dirname(cached), { recursive: true });+ writeFileSync(cached, bytes);+ } catch {+ // the cache is optional+ }+ return bytes;+};++if (shouldDownloadOpencode) {+ if (!engineAsset) {+ console.error(`No engine archive is pinned for target ${resolvedTargetTriple ?? "unknown"} in ${engineReleasePath}.`);process.exit(1);}mkdirSync(sidecarDir, { recursive: true });const stamp = Date.now();- const archivePath = join(tmpdir(), `opencode-${stamp}-${opencodeAsset}`);+ const archivePath = join(tmpdir(), `opencode-${stamp}-${engineAsset.name}`);const extractDir = join(tmpdir(), `opencode-${stamp}`);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);+ writeFileSync(archivePath, await readEngineArchive());} catch (error) {console.error(error instanceof Error ? error.message : String(error));process.exit(1);@@ -327,8 +377,13 @@ if (shouldDownloadOpencode) {// ignore}}+ try {+ unlinkSync(archivePath);+ } catch {+ // ignore+ }- console.log(`OpenCode sidecar updated to ${normalizedOpencodeVersion}.`);+ console.log(`OpenCode sidecar updated to ${normalizedOpencodeVersion} (${engineRelease.tag}).`);}adHocSignDarwinSidecars([@@ -350,6 +405,8 @@ const versions = {opencode: {version: normalizedOpencodeVersion,sha256: opencodeCandidatePath && existsSync(opencodeCandidatePath) ? sha256File(opencodeCandidatePath) : null,+ release: engineRelease.tag,+ archiveSha256: engineAsset?.sha256 ?? null,},"omnirush-server": {version: omnirushServerVersion,diff --git a/apps/server/src/engine2/plugin-bridge.e2e.test.ts b/apps/server/src/engine-plugin-bridge.e2e.test.tssimilarity index 100%rename from apps/server/src/engine2/plugin-bridge.e2e.test.tsrename to apps/server/src/engine-plugin-bridge.e2e.test.tsdiff --git a/apps/server/src/engine2/restraint-notes.e2e.test.ts b/apps/server/src/engine-restraint-notes.e2e.test.tssimilarity index 100%rename from apps/server/src/engine2/restraint-notes.e2e.test.tsrename to apps/server/src/engine-restraint-notes.e2e.test.tsdiff --git a/apps/server/src/engine2/revert.e2e.test.ts b/apps/server/src/engine-revert.e2e.test.tssimilarity index 100%rename from apps/server/src/engine2/revert.e2e.test.tsrename to apps/server/src/engine-revert.e2e.test.tsdiff --git a/apps/server/src/engine2/config.test.ts b/apps/server/src/engine2/config.test.tsdeleted file mode 100644index 2be2dcca..00000000--- a/apps/server/src/engine2/config.test.ts+++ /dev/null@@ -1,138 +0,0 @@-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.tsdeleted file mode 100644index 5e06229c..00000000--- a/apps/server/src/engine2/config.ts+++ /dev/null@@ -1,321 +0,0 @@-/**- * 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.tsdeleted file mode 100644index d7ccd384..00000000--- a/apps/server/src/engine2/events.ts+++ /dev/null@@ -1,649 +0,0 @@-/**- * 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,- v1UserTextParts,- v1PermissionRequest,- v1QuestionRequest,- v1Session,- type QuestionMapping,-} from "./shapes.js";-import { arr, isRecord, num, omitUndefined, promptFileUrl, 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;- /** The 1.x ids of the messages a staged revert hides (removed when it is committed). */- reverted?: string[];-};--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>;- /** The 1.x ids of a session's messages, oldest first (what a staged revert hides). */- messageIDs?: (sessionID: string) => Promise<string[]>;- 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;- // 2.x records "default" when no variant was picked; 1.x left the field out.- const variant = str(value, "variant");- return variant && variant !== "default" ? { providerID, modelID, variant } : { providerID, modelID };-}--/** The child session a sub-agent call's progress or end metadata names. */-function childSessionIn(metadata: unknown): string | undefined {- return isRecord(metadata) && typeof metadata.sessionID === "string" && metadata.sessionID ? metadata.sessionID : undefined;-}--/**- * A backstop on the remembered child sessions: an entry normally goes when its- * call ends, so this only bounds calls that never report an end (engine crash).- */-const MAX_CHILD_SESSIONS = 2000;--export class EventTranslator {- private readonly sessions = new Map<string, SessionState>();- private readonly live = new Map<string, LiveAssistant>();- private readonly questions = new Map<string, QuestionMapping>();- /**- * `<session>\0<call>` → the child session a sub-agent call runs in. The 2.x- * engine names the child only in the call's progress events; its message- * list leaves a running call's metadata without it until the call ends.- */- private readonly childSessions = new Map<string, string>();- private readonly options: EventTranslatorOptions;-- constructor(options: EventTranslatorOptions) {- this.options = options;- }-- /** The child session of a sub-agent call, when its progress named one. */- childSessionOf(sessionID: string, callID: string): string | undefined {- return this.childSessions.get(`${sessionID}\u0000${callID}`);- }-- private noteChildSession(sessionID: string, callID: string, metadata: unknown): void {- const child = childSessionIn(metadata);- if (!child) return;- const key = `${sessionID}\u0000${callID}`;- this.childSessions.delete(key);- this.childSessions.set(key, child);- if (this.childSessions.size > MAX_CHILD_SESSIONS) this.childSessions.delete(this.childSessions.keys().next().value as string);- }-- /**- * Forgets a call's child once its end event names it: the engine's own record- * of the call carries it from then on. An end that does not name it (a failure- * the engine may store without it) keeps the entry, so the card stays linked.- */- private settleChildSession(sessionID: string, callID: string, metadata: unknown): void {- if (childSessionIn(metadata)) this.childSessions.delete(`${sessionID}\u0000${callID}`);- }-- private forgetChildSessionsOf(sessionID: string): void {- const prefix = `${sessionID}\u0000`;- for (const key of this.childSessions.keys()) if (key.startsWith(prefix)) this.childSessions.delete(key);- }-- /** 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);- }-- /** The session's 1.x info, read fresh when possible (else the last one seen). */- private async currentInfo(sessionID: string): Promise<JsonRecord | null> {- if (this.options.lookupSession) {- try {- const info = v1Session(await this.options.lookupSession(sessionID), { version: this.options.version });- if (info) return info;- } catch {- // fall back to the last info seen- }- }- return this.session(sessionID).info ?? null;- }-- 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),- childSessionOf: (callID: string) => this.childSessionOf(sessionID, callID),- };- }-- 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.revert.staged":- case "session.revert.cleared":- case "session.revert.committed": {- // 2.x stages a revert (files restored, later messages kept), clears it- // (files back) or commits it (the later messages are deleted, which a- // prompt does first). 1.x showed the same through session.revert.- if (!sessionID) return [];- const state = this.session(sessionID);- const out: ScopedV1Event[] = [];- let revert: JsonRecord | undefined;- if (type === "session.revert.staged") {- const staged = record(data, "revert");- const boundary = str(staged, "messageID");- if (boundary) {- revert = omitUndefined({ messageID: boundary, partID: str(staged, "partID"), snapshot: str(staged, "snapshot") });- const ids = this.options.messageIDs ? await this.options.messageIDs(sessionID).catch(() => []) : [];- const index = ids.indexOf(boundary);- state.reverted = index >= 0 ? ids.slice(index) : [boundary];- }- } else if (type === "session.revert.committed") {- const boundary = str(data, "to");- const removed = state.reverted ?? (boundary ? [boundary] : []);- for (const messageID of removed) out.push(this.scoped(sessionID, "message.removed", { sessionID, messageID }));- state.reverted = undefined;- } else {- state.reverted = undefined;- }- const info = await this.currentInfo(sessionID);- if (info) {- const next = { ...info, time: { ...(record(info, "time") ?? {}), updated: num(raw, "created") ?? this.now() } } as JsonRecord;- if (revert) next.revert = revert;- else delete next.revert;- this.noteSession(sessionID, { info: next });- out.push(this.scoped(sessionID, "session.updated", { sessionID, info: next }));- }- return out;- }- 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);- this.forgetChildSessionsOf(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) {- const layout = record(record(payload, "metadata"), "omnirush")?.textParts;- for (const part of v1UserTextParts({ messageID: id, sessionID }, text, layout, false)) {- out.push(this.scoped(sessionID, "message.part.updated", { sessionID, part, time: created }));- }- }- files.forEach((file, index) => {- const url = promptFileUrl(file);- if (!isRecord(file) || !url) 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 }),- 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",- snapshot: str(data, "snapshot") ? { start: str(data, "snapshot") } : undefined,- 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");- const files = arr(data, "files").filter((file) => typeof file === "string");- const previous = record(live.message, "snapshot") ?? {};- if (snapshot || files.length) live.message.snapshot = omitUndefined({ ...previous, end: snapshot ?? str(previous, "end"), files: files.length ? files : undefined });- 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, partId(String(live.message.id), "p0"), 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() };- if (isRecord(data.state)) entry.state = data.state;- 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;- if (isRecord(data.state)) entry.state = data.state;- 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: {} };- if (isRecord(data.providerState)) entry.providerState = data.providerState;- 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 callID = str(data, "id");- // Remembered even without a live message: a later read of the session fills it in.- if (sessionID && callID) this.noteChildSession(sessionID, callID, data.metadata);- const live = this.liveFor(data);- 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 callID = str(data, "id");- if (sessionID && callID) this.settleChildSession(sessionID, callID, data.metadata);- const live = this.liveFor(data);- 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-model-wait.test.ts b/apps/server/src/engine2/facade-model-wait.test.tsdeleted file mode 100644index b0ac7832..00000000--- a/apps/server/src/engine2/facade-model-wait.test.ts+++ /dev/null@@ -1,115 +0,0 @@-import { afterAll, beforeAll, describe, expect, test } from "bun:test";-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";--import { startEngineFacade, type EngineFacade } from "./facade.js";--// A prompt for a model the engine does not serve yet: the omnirush.ai catalog-// arrived after launch and the engine is still applying it live.-const DIRECTORY = "/work/proj";-const SESSION = "ses_wait";--type Recorded = { method: string; path: string; body: unknown };-const recorded: Recorded[] = [];-/** The `provider/model` pairs the mock engine lists at GET /api/model. */-const served = new Set<string>(["omnirush/gpt-6-astra", "mock/mock-model"]);-let modelLookups = 0;-let upstream: ReturnType<typeof Bun.serve>;-let facade: EngineFacade;-let configDir = "";--const auth = { authorization: `Basic ${Buffer.from("user:secret").toString("base64")}`, "x-opencode-directory": encodeURIComponent(DIRECTORY) };-const post = (path: string, body: unknown) => fetch(`${facade.url}${path}`, { method: "POST", headers: { ...auth, "content-type": "application/json" }, body: JSON.stringify(body) });-const prompt = (modelID: string, providerID = "omnirush") => post(`/session/${SESSION}/prompt_async`, {- model: { providerID, modelID },- agent: "omnirush",- parts: [{ type: "text", text: "hello" }],-});-const sent = () => recorded.filter((call) => call.path === `/api/session/${SESSION}/prompt`).length;--beforeAll(async () => {- configDir = mkdtempSync(join(tmpdir(), "facade-model-wait-"));- const v1Config = join(configDir, "runtime.json");- writeFileSync(v1Config, JSON.stringify({- model: "omnirush/gpt-6-astra",- provider: { omnirush: { npm: "@ai-sdk/openai", options: { baseURL: "http://127.0.0.1:1/v1" }, models: { "gpt-6-astra": {} } } },- }));- upstream = Bun.serve({- port: 0,- async fetch(request) {- const url = new URL(request.url);- const body = request.method === "GET" ? undefined : await request.json().catch(() => undefined);- recorded.push({ method: request.method, path: url.pathname, body });- if (url.pathname === "/api/event") return new Response(new ReadableStream({ start() {} }), { headers: { "content-type": "text/event-stream" } });- if (url.pathname === "/api/model") {- modelLookups += 1;- return Response.json({- location: { directory: DIRECTORY },- data: [...served].map((key) => {- const [providerID, id] = key.split("/");- return { id, providerID, name: id, capabilities: { tools: true, input: ["text"], output: ["text"] } };- }),- });- }- if (request.method === "POST" || request.method === "PUT" || request.method === "DELETE") return new Response(null, { status: 204 });- return Response.json({ data: null }, { status: 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 () => undefined,- modelWaitMs: 1_500,- });-});--afterAll(async () => {- await facade?.close();- upstream?.stop(true);- rmSync(configDir, { recursive: true, force: true });-});--describe("a prompt for a model the engine does not serve yet", () => {- test("a served model is sent at once", async () => {- recorded.length = 0;- expect((await prompt("gpt-6-astra")).status).toBe(204);- expect(sent()).toBe(1);- });-- test("waits while the engine applies the new catalog, then starts the turn", async () => {- recorded.length = 0;- const started = Date.now();- setTimeout(() => served.add("omnirush/muse-spark-1.1"), 400);- const response = await prompt("muse-spark-1.1");- expect(response.status).toBe(204);- expect(Date.now() - started).toBeGreaterThanOrEqual(350);- // The session model is only switched once the engine serves it, then the prompt goes out.- const calls = recorded.filter((call) => call.method !== "GET").map((call) => call.path);- expect(calls).toEqual([`/api/session/${SESSION}/model`, `/api/session/${SESSION}/prompt`]);- });-- test("a model still missing after the wait is refused with a clear error, never sent", async () => {- recorded.length = 0;- const response = await prompt("muse-spark-9");- expect(response.status).toBe(400);- const body = (await response.json()) as { name: string; data: { message: string } };- expect(body.name).toBe("ProviderModelNotFoundError");- expect(body.data.message).toContain("omnirush/muse-spark-9 is not available yet");- expect(sent()).toBe(0);- expect(recorded.some((call) => call.path === `/api/session/${SESSION}/model` && call.method === "POST")).toBe(false);- });-- test("a provider the runtime config does not define is not held", async () => {- recorded.length = 0;- const lookups = modelLookups;- expect((await prompt("some-model", "elsewhere")).status).toBe(204);- expect(modelLookups).toBe(lookups);- expect(sent()).toBe(1);- });-});diff --git a/apps/server/src/engine2/facade.test.ts b/apps/server/src/engine2/facade.test.tsdeleted file mode 100644index 3132c045..00000000--- a/apps/server/src/engine2/facade.test.ts+++ /dev/null@@ -1,368 +0,0 @@-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 { EventTranslator } from "./events.js";-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);-// How many copies of the fixture's messages the mock engine serves (a long history spans several 200-message pages).-let LONG_REPEAT = 1;-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[] = [];-/** Sessions the mock engine reports running (`/api/session/active`). */-let activeSessions: Record<string, 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`) {- // Like 2.0.18: a cursor carries its own direction, and naming `order` next to it is refused.- if (query.cursor && query.order) return json({ name: "InvalidCursorError", data: { message: "Cursor cannot be combined with order" } }, 400);- const long = Array.from({ length: LONG_REPEAT }, (_, round) =>- tree.messages.map((message) => {- const m = message as { id: string };- return round === 0 ? message : { ...m, id: `${m.id}_r${String(round).padStart(3, "0")}` };- }),- ).flat();- const [order, start] = query.cursor ? (JSON.parse(atob(query.cursor)) as [string, number]) : [query.order ?? "asc", 0];- const messages = order === "desc" ? [...long].reverse() : long;- const limit = Number(query.limit ?? 50);- const end = start + limit;- return json({ data: messages.slice(start, end), cursor: { next: end < messages.length ? btoa(JSON.stringify([order, end])) : null } });- }- if (url.pathname === "/api/session/active") return json({ data: activeSessions });- 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);- },- reloadPollMs: 50,- });-});--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 history longer than one engine page loads without naming order next to the cursor", async () => {- LONG_REPEAT = 90;- try {- const response = await get(`/session/${SESSION}/message`);- expect(response.status).toBe(200);- const all = (await response.json()) as Array<{ info: { id: string } }>;- expect(all.length).toBe(5 * 90); // the fixture's 6 engine messages read as 5 in 1.x form- const paged = recorded.filter((r) => r.path === `/api/session/${SESSION}/message` && r.query.cursor);- expect(paged.length).toBeGreaterThan(0);- expect(paged.every((r) => r.query.order === undefined)).toBe(true);- } finally {- LONG_REPEAT = 1;- }- });-- 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 1.x user message fields 2.x does not keep travel as message metadata.- metadata: { omnirush: { agent: "omnirush", model: { providerID: "omnirush", modelID: "gpt-6-astra", variant: "high" }, system: "Extra system" } },- });- // 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("a synthetic attachment note reaches the model and its text-part layout is kept", async () => {- recorded.length = 0;- const note = "Attached files were copied into this worker workspace for tool access:\n- image.png: .opencode/omnirush/inbox/chat-attachments/s/1-image.png (file:///home/u/p/.opencode/omnirush/inbox/chat-attachments/s/1-image.png)";- const metadata = { omnirushAttachments: [] };- await post(`/session/${SESSION}/prompt_async`, {- model: { providerID: "omnirush", modelID: "gpt-6-astra" },- variant: "high",- agent: "omnirush",- system: "Extra system",- parts: [- { type: "text", text: note, synthetic: true, metadata },- { type: "text", text: "hi" },- { type: "file", mime: "image/png", filename: "image.png", url: "data:image/png;base64,AAAA" },- ],- });- const prompt = recorded.find((call) => call.path === `/api/session/${SESSION}/prompt`)!;- expect(prompt.body).toMatchObject({- text: `${note}\n\nhi`,- metadata: { omnirush: { textParts: [{ length: note.length, synthetic: true, metadata }, { length: 2 }] } },- });- });-- 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("revert stages a reversible revert and unrevert clears it; neither commits", async () => {- recorded.length = 0;- const reverted = await post(`/session/${SESSION}/revert`, { messageID: "msg_b" });- expect(reverted.status).toBe(200);- const unreverted = await post(`/session/${SESSION}/unrevert`, {});- expect(unreverted.status).toBe(200);- const calls = recorded.filter((entry) => entry.path.includes("/revert")).map((entry) => `${entry.method} ${entry.path}`);- expect(calls).toEqual([`POST /api/session/${SESSION}/revert/stage`, `DELETE /api/session/${SESSION}/revert`]);- expect(recorded.find((entry) => entry.path.endsWith("/revert/stage"))!.body).toEqual({ messageID: "msg_b" });- });-- test("a shell command or slash command makes a staged revert final first", async () => {- recorded.length = 0;- expect((await post(`/session/${SESSION}/shell`, { command: "ls", agent: "build" })).status).toBe(200);- expect((await post(`/session/${SESSION}/command`, { command: "/review", arguments: "" })).status).toBe(204);- const calls = recorded.filter((entry) => entry.method === "POST" && /\/(revert\/commit|shell|command)$/.test(entry.path)).map((entry) => entry.path.split("/").slice(4).join("/"));- expect(calls).toEqual(["revert/commit", "shell", "revert/commit", "command"]);- });-- 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}`,- ]);- });-});--describe("revert events", () => {- const info = (revert?: Record<string, unknown>) => ({ data: { id: "ses_r", title: "T", location: { directory: DIRECTORY }, time: { created: 1, updated: 1 }, ...(revert ? { revert } : {}) } });- const make = (current: { revert?: Record<string, unknown> }) => new EventTranslator({- version: "2.0.18",- lookupSession: async () => info(current.revert),- messageIDs: async () => ["msg_a", "msg_a2", "msg_b", "msg_b2", "msg_c", "msg_c2"],- });-- test("staged, cleared and committed reach the app as session.updated and message.removed", async () => {- const current: { revert?: Record<string, unknown> } = {};- const translator = make(current);- const summary = (out: Awaited<ReturnType<EventTranslator["translate"]>>) => out.map((item) => {- const properties = item.event.properties as Record<string, any>;- return item.event.type === "message.removed" ? `removed:${properties.messageID}` : `${item.event.type}:${properties.info?.revert?.messageID ?? "-"}`;- });-- current.revert = { messageID: "msg_b", snapshot: "abc" };- const staged = await translator.translate({ type: "session.revert.staged", data: { sessionID: "ses_r", revert: { messageID: "msg_b", snapshot: "abc", files: [] } } });- expect(summary(staged)).toEqual(["session.updated:msg_b"]);- expect((staged[0]!.event.properties as any).info.revert).toEqual({ messageID: "msg_b", snapshot: "abc" });-- current.revert = undefined;- expect(summary(await translator.translate({ type: "session.revert.cleared", data: { sessionID: "ses_r" } }))).toEqual(["session.updated:-"]);-- current.revert = { messageID: "msg_b" };- await translator.translate({ type: "session.revert.staged", data: { sessionID: "ses_r", revert: { messageID: "msg_b" } } });- current.revert = undefined;- const committed = await translator.translate({ type: "session.revert.committed", data: { sessionID: "ses_r", to: "msg_b" } });- expect(summary(committed)).toEqual(["removed:msg_b", "removed:msg_b2", "removed:msg_c", "removed:msg_c2", "session.updated:-"]);- });-- test("a revert committed without a staged one seen removes the boundary message", async () => {- const translator = make({});- const out = await translator.translate({ type: "session.revert.committed", data: { sessionID: "ses_r", to: "msg_c" } });- expect(out.map((item) => item.event.type)).toEqual(["message.removed", "session.updated"]);- });-});--describe("location reloads (/instance/dispose)", () => {- const reloads = () => recorded.filter((entry) => entry.method === "POST" && entry.path === "/api/location/reload").length;- const waitFor = async (check: () => boolean, ms = 3_000) => {- const deadline = Date.now() + ms;- while (!check() && Date.now() < deadline) await Bun.sleep(20);- return check();- };-- test("an idle engine reloads at once", async () => {- activeSessions = {};- const before = reloads();- expect((await post("/instance/dispose", {})).status).toBe(200);- expect(reloads()).toBe(before + 1);- });-- test("a reload asked while a session runs waits until no session runs", async () => {- // A 2.x location reload closes every location: the running step's tool- // calls (a subagent start among them) would be declined with- // "Interaction cancelled because the location shut down".- activeSessions = { [SESSION]: { type: "running" } };- const before = reloads();- const configsBefore = written.length;- expect((await post("/instance/dispose", {})).status).toBe(200);- expect(written.length).toBe(configsBefore + 1); // the config is re-rendered at once- expect((await post("/instance/dispose", {})).status).toBe(200);- await Bun.sleep(200);- expect(reloads()).toBe(before);- activeSessions = {};- expect(await waitFor(() => reloads() === before + 1)).toBe(true);- await Bun.sleep(200);- expect(reloads()).toBe(before + 1); // both requests are served by one reload- });-- test("the next prompt runs a deferred reload first once the engine is idle", async () => {- activeSessions = { other: { type: "running" } };- const before = reloads();- expect((await post("/instance/dispose", {})).status).toBe(200);- activeSessions = {};- const sent = recorded.length;- expect((await post(`/session/${SESSION}/prompt_async`, { parts: [{ type: "text", text: "next" }] })).status).toBe(204);- const after = recorded.slice(sent).map((entry) => `${entry.method} ${entry.path}`);- const reloadAt = after.indexOf("POST /api/location/reload");- const promptAt = after.indexOf(`POST /api/session/${SESSION}/prompt`);- expect(reloadAt).toBeGreaterThanOrEqual(0);- expect(promptAt).toBeGreaterThan(reloadAt);- await Bun.sleep(200);- expect(reloads()).toBe(before + 1);- });-});diff --git a/apps/server/src/engine2/facade.ts b/apps/server/src/engine2/facade.tsdeleted file mode 100644index 956fcec0..00000000--- a/apps/server/src/engine2/facade.ts+++ /dev/null@@ -1,1461 +0,0 @@-/**- * 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 { existsSync } from "node:fs";-import { readFile } from "node:fs/promises";-import { dirname as parentDir, join as joinPath } from "node:path";-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;- /** How long a prompt waits for the engine to serve its model (see ensureModelServed). */- modelWaitMs?: number;- /** How often a location reload deferred behind a running session checks for an idle engine. */- reloadPollMs?: number;-};--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.- }-}--const roots = new Map<string, string>();-/** The worktree root 1.x reported in `path.root` / relative paths: the enclosing git root, else "/". */-export function worktreeRoot(directory: string | undefined): string {- if (!directory) return "/";- const known = roots.get(directory);- if (known) return known;- let current = directory;- let root = "/";- for (let depth = 0; depth < 64; depth++) {- if (existsSync(joinPath(current, ".git"))) {- root = current;- break;- }- const parent = parentDir(current);- if (parent === current) break;- current = parent;- }- if (roots.size > 256) roots.clear();- roots.set(directory, root);- return root;-}--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 modelWaitMs = options.modelWaitMs ?? 20_000;- 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 todos = new Map<string, JsonRecord[]>();-- 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 send = () => 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,- });- // Reads are retried through a transient engine failure (a 5xx or a dropped connection).- let response: Response | undefined;- for (let attempt = 0; ; attempt++) {- try {- response = await send();- if (method !== "GET" || response.status < 500 || attempt >= 2) break;- log("engine read failed, retrying", { path, status: response.status });- await response.body?.cancel().catch(() => undefined);- } catch (error) {- if (method !== "GET" || attempt >= 2 || init.signal?.aborted) throw error;- }- await new Promise((resolve) => setTimeout(resolve, 150 * (attempt + 1)));- }- 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,- rootFor: worktreeRoot,- lookupSession: (sessionID) => call("GET", `/api/session/${encodeURIComponent(sessionID)}`),- messageIDs: async (sessionID) => (await sessionMessages(sessionID)).map((message) => String(message.info.id)),- });- /**- * Makes a staged revert final (as a 2.x prompt does before it runs); a- * no-op without one. A busy session (409) cannot hold a staged revert: the- * app stops a run before it reverts, and a prompt commits it.- */- const commitRevert = async (encodedSessionID: string) => {- await call("POST", `/api/session/${encodedSessionID}/revert/commit`, { body: {} }).catch((error) => {- if (error instanceof UpstreamError && (error.status === 404 || error.status === 409)) return undefined;- throw error;- });- };-- // ---- 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 }));- };-- // ---- location reloads ---------------------------------------------------- /*- * `/instance/dispose` is a 2.x `location/reload`, which closes every cached- * location, not just the requested one. A step running when its location- * closes keeps the old services, whose permission service now declines- * every request: each tool call of that step fails with "Interaction- * cancelled because the location shut down" (a subagent call fails before- * it creates its child session). So a reload asked while any session runs- * waits until no session runs: it is retried on a timer, and the next- * prompt runs it first when the engine is idle by then. The config itself- * is re-rendered at once; the engine applies config changes live.- */- const reloadPollMs = options.reloadPollMs ?? 500;- let reloadPending = false;- let reloadTimer: ReturnType<typeof setTimeout> | null = null;- let reloadChain: Promise<void> = Promise.resolve();- let facadeClosed = false;- /** Whether any session runs; an unreadable answer counts as running. */- const engineBusy = async (): Promise<boolean> => {- try {- const active = unwrap(await call("GET", "/api/session/active"));- return isRecord(active) && Object.keys(active).length > 0;- } catch {- return true;- }- };- /** Reloads now; reloads are serialized so a later request never joins one that read older config. */- const reloadLocations = (directory?: string): Promise<void> => {- reloadPending = false;- const run = reloadChain.then(() => call("POST", "/api/location/reload", { directory, body: {} }).then(() => undefined, () => undefined));- reloadChain = run;- return run;- };- const scheduleDeferredReload = () => {- if (reloadTimer || facadeClosed) return;- reloadTimer = setTimeout(() => {- reloadTimer = null;- void (async () => {- if (!reloadPending || facadeClosed) return;- if (await engineBusy()) {- scheduleDeferredReload();- return;- }- if (reloadPending) await reloadLocations();- })();- }, reloadPollMs);- reloadTimer.unref?.();- };- /** `/instance/dispose`: reloads now when no session runs, else once none does. */- const requestLocationReload = async (directory: string): Promise<"reloaded" | "deferred"> => {- if (await engineBusy()) {- if (!reloadPending) log("location reload deferred while a session runs", { directory });- reloadPending = true;- scheduleDeferredReload();- return "deferred";- }- await reloadLocations(directory);- return "reloaded";- };- /** Before a prompt: a deferred reload runs now if the engine went idle. */- const settleDeferredReload = async (): Promise<void> => {- if (!reloadPending) return;- if (await engineBusy()) return;- if (reloadPending) await reloadLocations();- };-- // ---- 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 };- const picked = selected.get(sessionID);- if (picked?.model) {- // The model and agent this adapter last selected for the session (its next step runs on them).- const [ref, variant] = picked.model.split("#");- const slash = ref!.indexOf("/");- info.model = { id: ref!.slice(slash + 1), providerID: ref!.slice(0, slash), variant: variant || "default" };- }- if (picked?.agent) info.agent = picked.agent;- 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`, {- // 2.x rejects `order` next to a cursor (InvalidCursorError: the cursor- // already carries the direction), so only the first page names it.- query: cursor ? { limit: "200", cursor } : { order: "asc", limit: "200" },- });- 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;- };-- // The turn observer and the renderer page a long history newest-first, one request per page.- // A history read is reused while the session's newest message is the same completed record- // (and the session's busy state is unchanged): one small read instead of the whole history.- const messageCache = new Map<string, { key: string; value: V1Message[] }>();- const inflight = new Map<string, Promise<V1Message[]>>();- const sessionMessages = async (sessionID: string): Promise<V1Message[]> => {- const pending = inflight.get(sessionID);- if (pending) return pending;- const run = (async () => {- const newest = await call("GET", `/api/session/${encodeURIComponent(sessionID)}/message`, { query: { order: "desc", limit: "1" } }).catch(() => undefined);- const head = arr(newest, "data")[0];- const completed = isRecord(head) && (str(head, "type") !== "assistant" || num(record(head, "time"), "completed") !== undefined);- const key = isRecord(head) && completed ? `${str(head, "id")}|${translator.statusOf(sessionID)?.type ?? "idle"}` : "";- const cached = messageCache.get(sessionID);- if (key && cached?.key === key) return cached.value;- const value = await readSessionMessages(sessionID);- if (key) messageCache.set(sessionID, { key, value });- else messageCache.delete(sessionID);- if (messageCache.size > 64) messageCache.delete(messageCache.keys().next().value as string);- return value;- })();- inflight.set(sessionID, run);- try {- return await run;- } finally {- inflight.delete(sessionID);- }- };- const readSessionMessages = async (sessionID: string): Promise<V1Message[]> => {- const info = await sessionInfo(sessionID).catch(() => null);- const directory = info ? String(info.directory || "") || undefined : undefined;- const variant = str(info?.model, "variant");- const model = isRecord(info?.model) && str(info!.model, "id")- ? omitUndefined({ providerID: String(str(info!.model, "providerID")), modelID: String(str(info!.model, "id")), variant: variant && variant !== "default" ? variant : undefined })- : undefined;- const mapped = v1Messages(await rawMessages(sessionID), {- sessionID,- directory,- root: worktreeRoot(directory),- agent: info ? str(info, "agent") : undefined,- model,- child: Boolean(info && str(info, "parentID")),- // A running sub-agent call keeps the child session its progress named (the read leaves it out).- childSessionOf: (callID) => translator.childSessionOf(sessionID, callID),- });- await attachTurnDiffs(sessionID, mapped);- return mapped;- };-- // 1.x put each prompt's turn diff (whole-file patches) on the user message as `summary.diffs`.- const turnDiffs = new Map<string, JsonRecord[]>();- const attachTurnDiffs = async (sessionID: string, messages: V1Message[]): Promise<void> => {- const busy = translator.statusOf(sessionID)?.type === "busy";- // A prompt may carry synthetic notes beside what was typed; a message of synthetic text alone is not a prompt.- const prompts = messages.filter((message) => message.info.role === "user"- && !(message.parts.length > 0 && message.parts.every((part) => part.type === "text" && part.synthetic === true)));- for (const [index, message] of prompts.entries()) {- const id = String(message.info.id);- const key = `${sessionID}\u0000${id}`;- let diffs = turnDiffs.get(key);- const current = index === prompts.length - 1;- if (!diffs && !(current && busy)) {- const payload = await call("GET", `/api/session/${encodeURIComponent(sessionID)}/diff`, { query: { from: id } }).catch(() => undefined);- const list = unwrap(payload);- if (Array.isArray(list)) {- diffs = list.filter(isRecord).map((diff) => omitUndefined({- file: str(diff, "file"),- patch: str(diff, "patch"),- additions: num(diff, "additions") ?? 0,- deletions: num(diff, "deletions") ?? 0,- status: str(diff, "status"),- }));- if (!current) turnDiffs.set(key, diffs);- if (turnDiffs.size > 4096) turnDiffs.delete(turnDiffs.keys().next().value as string);- }- }- if (diffs) message.info.summary = { diffs };- }- };-- 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 };- };-- /** The `provider/model` ids the engine serves for a folder; null when it cannot tell. */- const engineModelIds = async (directory: string): Promise<Set<string> | null> => {- try {- const models = unwrap(await call("GET", "/api/model", { directory }));- if (!Array.isArray(models)) return null;- const ids = new Set<string>();- for (const provider of v1ProviderList([], models, {}).all as JsonRecord[]) {- for (const id of Object.keys(record(provider, "models") ?? {})) ids.add(`${String(provider.id)}/${id}`);- }- return ids;- } catch {- return null;- }- };-- /**- * A prompt for a model of a provider the runtime config defines (the- * omnirush.ai catalog) waits while the engine does not list it yet: a- * config change it is applying live (a catalog that just arrived). The 2.x- * engine accepts a session model it does not know and then never starts the- * run, so a model still missing after the wait is refused with a clear- * error instead of a turn that silently never answers. A failed lookup never- * blocks the prompt.- */- const ensureModelServed = async (directory: string, model: ModelRef): Promise<void> => {- if (!isRecord(record(v1ConfigCache, "provider")?.[model.providerID])) return;- const key = `${model.providerID}/${model.modelID}`;- const deadline = Date.now() + modelWaitMs;- for (;;) {- const served = await engineModelIds(directory);- if (!served || served.has(key)) return;- if (Date.now() >= deadline) {- log("prompt refused: model not served", { model: key });- throw new UpstreamError(400, {- name: "ProviderModelNotFoundError",- data: {- providerID: model.providerID,- modelID: model.modelID,- message: `The model ${key} is not available yet. Pick another model or try again in a moment.`,- },- });- }- await new Promise((resolve) => setTimeout(resolve, 250));- }- };-- /** 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, directory: string): Promise<void> => {- await settleDeferredReload();- const current = selected.get(sessionID) ?? {};- const model = modelRefFromBody(body);- if (model) {- const key = `${model.providerID}/${model.modelID}#${model.variant ?? ""}`;- if (current.model !== key) {- await ensureModelServed(directory, model);- 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[] = [];- // 2.x keeps one text per prompt: the layout of the 1.x text parts lets reads split it back,- // so synthetic notes (attachment paths, mention instructions) reach the model but stay out- // of the user's bubble and the trace's typed prompt.- const textParts: JsonRecord[] = [];- let splitText = false;- 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);- const synthetic = part.synthetic === true || undefined;- const metadata = isRecord(part.metadata) && Object.keys(part.metadata).length ? part.metadata : undefined;- if (synthetic || metadata) splitText = true;- textParts.push(omitUndefined({ length: part.text.length, synthetic, metadata }));- }- 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);- textParts.push({ length: part.prompt.length });- }- }- // The 1.x user message fields 2.x does not keep (system prompt, agent and model as picked,- // tool switches) travel in the message metadata, so reads return them field for field.- const model = modelRefFromBody(body);- const v1 = omitUndefined({- agent: str(body, "agent"),- model: model ? omitUndefined({ providerID: model.providerID, modelID: model.modelID, variant: model.variant && model.variant !== "default" ? model.variant : undefined }) : undefined,- system: str(body, "system"),- tools: isRecord(body.tools) ? body.tools : undefined,- textParts: splitText ? textParts : undefined,- });- return omitUndefined({- id: str(body, "messageID"),- text: texts.join("\n\n"),- files: files.length ? files : undefined,- agents: agents.length ? agents : undefined,- metadata: Object.keys(v1).length ? { omnirush: v1 } : 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; end: () => void };- const subscribers = new Set<Subscriber>();- const streamController = new AbortController();- let streamStarted = false;- const dispatch = (items: ScopedV1Event[]) => {- for (const item of items) {- const touched = str(item.event.properties, "sessionID") ?? str(record(item.event.properties, "info"), "sessionID") ?? str(record(item.event.properties, "part"), "sessionID");- if (touched) messageCache.delete(touched);- 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, end: () => res.end() };- 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, dir);- 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, dir);- 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, dir);- 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, dir);- await commitRevert(encoded);- 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 settleDeferredReload();- await commitRevert(encoded);- 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, dir);- await call("POST", `/api/session/${encoded}/compact`, { body: {} });- json(res, 200, true);- return;- }- case "revert": {- // 2.x stages a reversible revert: the files go back to before the- // message, the session carries the revert point and the later- // messages stay until a prompt commits it (1.x's cleanup) or- // unrevert clears it. 1.x's partID (a revert inside a message)- // has no 2.x equivalent: the whole message is the boundary.- const body = ((await readBody(req)) ?? {}) as JsonRecord;- const messageID = str(body, "messageID");- if (messageID) await call("POST", `/api/session/${encoded}/revert/stage`, { body: { messageID } });- json(res, 200, await sessionInfo(sessionID, directory));- return;- }- case "unrevert": {- // Restores the files and the hidden messages; a no-op once a prompt committed the revert.- await call("DELETE", `/api/session/${encoded}/revert`);- 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": {- if (!todos.has(sessionID)) {- // Rebuilt from the session's last todo list call when the adapter has not seen one yet.- const messages = await sessionMessages(sessionID).catch(() => []);- const last = messages.flatMap((message) => message.parts).filter((part) => part.type === "tool" && part.tool === "todowrite").at(-1);- const input = record(record(last, "state"), "input");- todos.set(sessionID, arr(input, "todos").filter(isRecord));- }- json(res, 200, todos.get(sessionID) ?? []);- 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/todos") {- // The plugin bridge's todo list tool: remembered per session and announced as the 1.x event.- const body = ((await readBody(req)) ?? {}) as JsonRecord;- const sessionID = str(body, "sessionID");- if (sessionID) {- const list = arr(body, "todos").filter(isRecord);- todos.set(sessionID, list);- dispatch([{ directory: translator.directoryOf(sessionID), event: { type: "todo.updated", properties: { sessionID, todos: list } } }]);- }- json(res, 200, true);- 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 requestLocationReload(dir);- 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) {- if (error.status >= 500) log("engine request failed", { url: req.url, status: error.status });- 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 () => {- facadeClosed = true;- if (reloadTimer) clearTimeout(reloadTimer);- reloadTimer = null;- streamController.abort();- // Event streams stay open until ended; end them so the server can close.- for (const subscriber of subscribers) {- subscribers.delete(subscriber);- try {- subscriber.end();- } catch {- // already closed- }- }- const closed = new Promise<void>((resolve) => server.close(() => resolve()));- server.closeAllConnections?.();- await Promise.race([closed, new Promise<void>((resolve) => setTimeout(resolve, 3_000).unref?.())]);- },- };-}diff --git a/apps/server/src/engine2/fixtures/v1-sub-events.json b/apps/server/src/engine2/fixtures/v1-sub-events.jsondeleted file mode 100644index fde7acae..00000000--- a/apps/server/src/engine2/fixtures/v1-sub-events.json+++ /dev/null@@ -1,3132 +0,0 @@-[-{-"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 filediff --git a/apps/server/src/engine2/fixtures/v2-sub-events.json b/apps/server/src/engine2/fixtures/v2-sub-events.jsondeleted file mode 100644index 56817944..00000000--- a/apps/server/src/engine2/fixtures/v2-sub-events.json+++ /dev/null@@ -1,1653 +0,0 @@-[-{-"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 filediff --git a/apps/server/src/engine2/launch.ts b/apps/server/src/engine2/launch.tsdeleted file mode 100644index e4b8b27f..00000000--- a/apps/server/src/engine2/launch.ts+++ /dev/null@@ -1,179 +0,0 @@-/**- * 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/native.ts b/apps/server/src/engine2/native.tsdeleted file mode 100644index 320cb764..00000000--- a/apps/server/src/engine2/native.ts+++ /dev/null@@ -1,210 +0,0 @@-/**- * The 2.x engine's own fields, kept next to the 1.x shape.- *- * engine2/shapes.ts writes every message and part in the 1.x shape the app,- * the viewer, the admin converter and the CLI's trace format read. The 2.x- * engine records more than 1.x did (provider response ids and service tier,- * raw finish reasons, the step's snapshots and changed files, stream timing,- * whether a tool ran provider-side, structured tool content, native tool- * names and inputs, agent/model switches, turn outcomes, …). This module adds- * all of it to the same records, additively:- *- * - a 2.x field whose name the 1.x record does not use is added under that- * name, as-is (`info.rawFinish`, `info.providerState`, `part.executed`,- * `part.time.ran`, `state.content`, …);- * - a 2.x field whose 1.x counterpart has the same value is not repeated;- * - objects both engines write (`time`, `tokens`, `error`, tool `state` and- * `metadata`) are merged key by key, so the 2.x keys sit next to the 1.x ones;- * - a 2.x value under a name the 1.x record already uses with another value- * or shape (a patch's native file list, a streaming tool's status) goes- * under `v2.<name>` on the same record, so the 1.x value keeps its place;- * a tool's native input keeps there only the entries the 1.x input lacks- * (`state.v2.input.path` next to `state.input.filePath`);- * - 2.x records 1.x never listed (agent/model/location switches, system- * context, idle markers with the turn outcome) become parts of the nearest- * conversation message, typed by their 2.x type (`"model-switched"`, …);- * - a `data:` URI the 1.x record already carries byte for byte (an image- * prompt's file part, a tool attachment) is written once: the 2.x copy- * says `sameAs:<where>` instead of repeating the bytes.- */-import type { V1Message } from "./shapes.js";-import { isRecord, promptFileUrl, type JsonRecord } from "./util.js";--/** Where a 2.x value goes when its name is taken on the 1.x record by another value. */-export const NATIVE_COLLISIONS = "v2";--function deepEqual(a: unknown, b: unknown): boolean {- if (a === b) return true;- if (typeof a !== typeof b || a === null || b === null || typeof a !== "object") return false;- if (Array.isArray(a) !== Array.isArray(b)) return false;- if (Array.isArray(a)) {- const other = b as unknown[];- return a.length === other.length && a.every((item, index) => deepEqual(item, other[index]));- }- const ka = Object.keys(a as object);- const kb = Object.keys(b as object);- return ka.length === kb.length && ka.every((key) => deepEqual((a as JsonRecord)[key], (b as JsonRecord)[key]));-}--/**- * Adds `native`'s fields to `target` (see the module comment). `nested` names- * the keys whose objects are merged key by key; its value gives the keys to- * merge one level further down. Objects in `target` are copied before they- * change, so a 1.x value shared between records is never altered.- */-export function mergeNative(target: JsonRecord, native: JsonRecord, nested: Record<string, Record<string, unknown>> = {}): JsonRecord {- for (const [key, value] of Object.entries(native)) {- if (value === undefined || key === NATIVE_COLLISIONS) continue;- if (!(key in target)) {- target[key] = value;- continue;- }- const current = target[key];- if (deepEqual(current, value)) continue;- if (key in nested && isRecord(current) && isRecord(value)) {- target[key] = mergeNative({ ...current }, value, nested[key] as Record<string, Record<string, unknown>>);- continue;- }- const bucket: JsonRecord = isRecord(target[NATIVE_COLLISIONS]) ? { ...(target[NATIVE_COLLISIONS] as JsonRecord) } : {};- bucket[key] = value;- target[NATIVE_COLLISIONS] = bucket;- }- return target;-}--/** `value`, with `data:` URIs the 1.x record already holds (`known`: uri → where) written as `sameAs:<where>`. */-function elideKnownDataUris(value: unknown, known: Map<string, string>): unknown {- if (known.size === 0) return value;- if (typeof value === "string") return value.startsWith("data:") && known.has(value) ? `sameAs:${known.get(value)}` : value;- if (Array.isArray(value)) return value.map((item) => elideKnownDataUris(item, known));- if (!isRecord(value)) return value;- return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, elideKnownDataUris(item, known)]));-}--function without(record: JsonRecord, ...keys: string[]): JsonRecord {- const copy = { ...record };- for (const key of keys) delete copy[key];- return copy;-}--const STATE_NESTED = { metadata: {}, time: {} };-const INFO_NESTED = { time: {}, tokens: { cache: {} }, error: { data: {} } };--/** Adds a 2.x content entry's own fields to the 1.x part built from it. */-function enrichPart(part: JsonRecord, entry: JsonRecord): void {- if (part.type === "tool") {- const state = isRecord(part.state) ? part.state : undefined;- const known = new Map<string, string>();- const attachments = state && Array.isArray(state.attachments) ? state.attachments : [];- attachments.forEach((attachment, index) => {- if (isRecord(attachment) && typeof attachment.url === "string") known.set(attachment.url, `state.attachments[${index}].url`);- });- const native = elideKnownDataUris(entry, known) as JsonRecord;- // The call id is the 1.x `callID`; the part keeps its own id.- const { id: callID, state: nativeState, ...rest } = native;- mergeNative(part, rest);- if (callID !== part.callID) mergeNative(part, { id: callID });- if (state && isRecord(nativeState)) {- const merged = mergeNative({ ...state }, nativeState, STATE_NESTED);- // A native input differs from the 1.x one by its key names (`path` for `filePath`, `agent` for- // `subagent_type`): only the native entries the 1.x input lacks are kept, so no value is written twice.- const bucket = isRecord(merged[NATIVE_COLLISIONS]) ? (merged[NATIVE_COLLISIONS] as JsonRecord) : undefined;- if (bucket && isRecord(bucket.input) && isRecord(state.input)) {- const v1Input = state.input as JsonRecord;- bucket.input = Object.fromEntries(Object.entries(bucket.input).filter(([key, value]) => !deepEqual(v1Input[key], value)));- }- part.state = merged;- }- return;- }- mergeNative(part, entry, { time: {} });-}--/** A 2.x assistant message's fields (and those of its content entries) on its 1.x message. */-export function enrichAssistant(message: V1Message, native: JsonRecord): void {- message.info = mergeNative({ ...message.info }, without(native, "content"), INFO_NESTED);- const content = Array.isArray(native.content) ? native.content.filter(isRecord) : [];- const ordinals = { text: 0, reasoning: 0 };- const byId = new Map(message.parts.map((part) => [String(part.id), part]));- const core = String(message.info.id).replace(/^msg_/, "");- for (const entry of content) {- let id: string | undefined;- if (entry.type === "text") id = `prt_${core}_t${ordinals.text++}`;- else if (entry.type === "reasoning") id = `prt_${core}_r${ordinals.reasoning++}`;- else if (entry.type === "tool" && typeof entry.id === "string") id = `prt_${core}_c_${entry.id}`;- const part = id ? byId.get(id) : undefined;- if (part) enrichPart(part, entry);- }-}--/** A 2.x user (or synthetic) message's fields on its 1.x message; native file entries on the file parts. */-export function enrichPrompt(message: V1Message, native: JsonRecord): void {- const known = new Map<string, string>();- message.parts.forEach((part, index) => {- if (part.type === "file" && typeof part.url === "string") known.set(part.url, `parts[${index}].url`);- });- // Inline file bytes the file part already holds as its `data:` URL are not repeated.- const files = (Array.isArray(native.files) ? native.files : []).map((file) => {- if (!isRecord(file) || typeof file.data !== "string" || typeof file.uri === "string") return file;- const url = promptFileUrl(file);- const where = url ? known.get(url) : undefined;- return where ? { ...file, data: `sameAs:${where}` } : file;- });- if (Array.isArray(native.files)) native = { ...native, files };- message.info = mergeNative({ ...message.info }, elideKnownDataUris(native, known) as JsonRecord, INFO_NESTED);- const fileParts = message.parts.filter((part) => part.type === "file");- files.forEach((file, index) => {- const part = fileParts[index];- if (!part || !isRecord(file)) return;- // Inline bytes stay on the message's `files` (the part's `data:` URL holds them), and the- // engine's `source: {type: "inline"}` is not a 1.x file source (a path the UI shows as a- // document), so neither goes on the part.- const { uri, data: _data, source, ...rest } = file;- const v1Source = isRecord(source) && ["file", "symbol", "resource"].includes(String(source.type));- mergeNative(part, v1Source ? { ...rest, source } : rest);- if (uri !== part.url) mergeNative(part, { uri });- });-}--/** 2.x records the 1.x engine never listed, as parts of the nearest conversation message. */-const CONTEXT_TYPES = new Set(["agent-switched", "model-switched", "location-switched", "system", "idle"]);--export function isContextRecord(native: JsonRecord): boolean {- return CONTEXT_TYPES.has(String(native.type));-}--/**- * Adds the 2.x fields to the 1.x messages mapped from `natives` (`mapped`- * names the 1.x messages each native message became) and places the context- * records: an idle marker closes the message before it, every other record- * joins the message after it (the last message when none follows).- */-export function withNativeFields(messages: V1Message[], natives: JsonRecord[], mapped: Map<JsonRecord, V1Message[]>, sessionID: string): V1Message[] {- const pending: JsonRecord[] = [];- let previous: V1Message | undefined;- const attach = (host: V1Message, record: JsonRecord, atEnd: boolean) => {- const part = { ...record, sessionID, messageID: host.info.id };- host.parts = atEnd ? [...host.parts, part] : [part, ...host.parts];- };- for (const native of natives) {- if (isContextRecord(native)) {- if (native.type === "idle" && previous) attach(previous, native, true);- else pending.push(native);- continue;- }- const targets = mapped.get(native) ?? [];- if (targets.length === 0) continue;- const type = String(native.type);- if (type === "assistant") enrichAssistant(targets[0]!, native);- else if (type === "user" || type === "synthetic" || type === "skill") enrichPrompt(targets[0]!, native);- else {- // shell and compaction became a prompt and a reply: the reply carries the record's fields.- const reply = targets[targets.length - 1]!;- reply.info = mergeNative({ ...reply.info }, native, INFO_NESTED);- }- for (const record of pending.splice(0).reverse()) attach(targets[0]!, record, false);- previous = targets[targets.length - 1];- }- if (pending.length && messages.length) for (const record of pending) attach(messages[messages.length - 1]!, record, true);- return messages;-}diff --git a/apps/server/src/engine2/subagent-location-reload.e2e.test.ts b/apps/server/src/engine2/subagent-location-reload.e2e.test.tsdeleted file mode 100644index 2813fb09..00000000--- a/apps/server/src/engine2/subagent-location-reload.e2e.test.ts+++ /dev/null@@ -1,167 +0,0 @@-import { afterAll, beforeAll, describe, expect, test } from "bun:test";-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";--/**- * A reload (`/instance/dispose`) that lands while the model is still writing- * the reply that starts a sub-agent, on the real 2.x engine (the bundled- * sidecar behind the 1.x adapter) with the desktop's runtime config and a- * mock provider.- *- * A 2.x location reload closes the location under the running step, and- * every tool call of that step is then declined with "Interaction cancelled- * because the location shut down": the subagent call failed before it made- * its child session. The adapter now defers the reload until no session- * runs, so the sub-agent starts as a child of the main session.- *- * Skipped when the sidecar binary is not present (prepare:sidecar not run).- */--const repoRoot = resolve(import.meta.dir, "../../../..");-const sidecarDir = join(repoRoot, "apps/desktop/resources/sidecars");-function findSidecar(): string | null {- const arch = process.arch === "arm64" ? "aarch64" : "x86_64";- const name = process.platform === "darwin" ? `opencode-${arch}-apple-darwin` : process.platform === "linux" ? `opencode-${arch}-unknown-linux-gnu` : "";- const candidate = join(sidecarDir, name);- return name && existsSync(candidate) ? candidate : null;-}-const enginePath = findSidecar();-const describeMaybe = enginePath ? describe : describe.skip;--type Body = { messages?: Array<{ role: string; content: unknown }>; tools?: Array<{ type: string; function: { name: string } }> };-type V1Part = { type: string; tool?: string; text?: string; state?: { status?: string; error?: string; output?: string } };-type V1Message = { info: { id: string; role: string; time?: { completed?: number } }; parts: V1Part[] };--const CHILD_MARK = "CHILD-RELOAD-51c2";--function text(content: unknown): string {- if (typeof content === "string") return content;- if (!Array.isArray(content)) return "";- return content.map((part) => (part && typeof part === "object" && typeof (part as { text?: unknown }).text === "string" ? (part as { text: string }).text : "")).join("\n");-}-function sse(chunks: object[]): Response {- const frame = (payload: object) => `data: ${JSON.stringify({ id: "c", object: "chat.completion.chunk", created: 1, model: "m", ...payload })}\n\n`;- const body = chunks.map((choice) => frame({ choices: [choice] })).join("")- + frame({ choices: [], usage: { prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 } })- + "data: [DONE]\n\n";- return new Response(body, { headers: { "content-type": "text/event-stream" } });-}-const say = (content: string) => sse([{ index: 0, delta: { role: "assistant", content } }, { index: 0, delta: {}, finish_reason: "stop" }]);-const callSubagent = () => sse([- { index: 0, delta: { role: "assistant", content: "" } },- { index: 0, delta: { tool_calls: [{ index: 0, id: "call_sub_1", type: "function", function: { name: "subagent", arguments: JSON.stringify({ agent: "general", description: "Inspect", prompt: `${CHILD_MARK}: reply with one word.` }) } }] } },- { index: 0, delta: {}, finish_reason: "tool_calls" },-]);--describeMaybe("a reload while a sub-agent starts (2.x engine, mock provider)", () => {- let engine: ManagedOpencodeServer;- let provider: ReturnType<typeof Bun.serve>;- let work = "";- let data = "";- /** Set while the mock provider holds the main reply that starts the sub-agent. */- let mainReplyHeld = false;-- const engineFetch = async (path: string, init?: RequestInit) => {- const headers = new Headers(init?.headers);- headers.set("authorization", `Basic ${Buffer.from(`${engine.username}:${engine.password}`).toString("base64")}`);- headers.set("x-opencode-directory", encodeURIComponent(work));- if (init?.body) headers.set("content-type", "application/json");- return fetch(`${engine.url}${path}`, { ...init, headers });- };- const getJson = async <T>(path: string): Promise<T> => (await (await engineFetch(path)).json()) as T;- const waitFor = async <T>(read: () => Promise<T | null | undefined | false> | T | null | undefined | false, label: string, ms = 60_000): Promise<T> => {- const deadline = Date.now() + ms;- while (Date.now() < deadline) {- const value = await Promise.resolve(read()).catch(() => null);- if (value) return value as T;- await Bun.sleep(100);- }- throw new Error(`timed out waiting for ${label}`);- };-- beforeAll(async () => {- work = mkdtempSync(join(tmpdir(), "subagent-reload-ws-"));- data = mkdtempSync(join(tmpdir(), "subagent-reload-data-"));- provider = Bun.serve({- port: 0,- async fetch(request) {- const url = new URL(request.url);- const body = request.method === "POST" ? ((await request.json().catch(() => ({}))) as Body) : {};- if (url.pathname.startsWith("/managed-policy")) return Response.json({ allowed: true, approvalMode: "guarded" });- if (!url.pathname.startsWith("/v1/")) return Response.json({});- if (!Array.isArray(body.tools) || body.tools.length === 0) return say("Reload title");- const messages = body.messages ?? [];- if (messages.some((message) => message.role === "user" && text(message.content).includes(CHILD_MARK))) return say("child done");- if (messages.at(-1)?.role === "tool") return say("All done.");- mainReplyHeld = true;- await Bun.sleep(2_500);- mainReplyHeld = false;- return callSubagent();- },- });- const base = `http://127.0.0.1:${provider.port}`;- // The desktop's own runtime config (guarded approvals, the omnirush agent and plugins) with a mock provider.- const config = buildOmniRushRuntimeConfigObjectFromSnapshot({- provider: {- mock: { name: "Mock", npm: "@ai-sdk/openai-compatible", options: { baseURL: `${base}/v1`, apiKey: "mock-key" }, models: { "mock-model": { name: "Mock", tool_call: true, limit: { context: 100_000, output: 4_000 } } } },- },- }, undefined, {});- const configPath = join(data, "runtime-opencode-config.json");- writeFileSync(configPath, JSON.stringify({ ...config, model: "mock/mock-model" }));- engine = await createManagedOpencodeServer({- bin: enginePath!,- cwd: work,- env: {- OPENCODE_CONFIG: configPath,- OPENCODE_DISABLE_MODELS_FETCH: "1",- OMNIRUSH_ENGINE2_CONFIG_DIR: join(data, "engine2"),- OMNIRUSH_SERVER_URL: base,- OMNIRUSH_POLICY_TOKEN: "policy",- OMNIRUSH_SERVER_TOKEN: "server",- HOME: join(data, "home"),- OPENCODE_TEST_HOME: join(data, "home"),- XDG_DATA_HOME: join(data, "xdg-data"),- XDG_CONFIG_HOME: join(data, "xdg-config"),- XDG_STATE_HOME: join(data, "xdg-state"),- XDG_CACHE_HOME: join(data, "xdg-cache"),- },- });- await waitFor(async () => (await engineFetch("/session")).ok, "engine");- }, 120_000);-- afterAll(async () => {- await engine?.close();- provider?.stop(true);- rmSync(work, { recursive: true, force: true });- rmSync(data, { recursive: true, force: true });- }, 30_000);-- test("the sub-agent starts as a child session and its task completes", async () => {- const session = (await (await engineFetch("/session", { method: "POST", body: "{}" })).json()) as { id: string };- const sent = await engineFetch(`/session/${session.id}/prompt_async`, { method: "POST", body: JSON.stringify({ parts: [{ type: "text", text: "inspect it" }] }) });- expect(sent.status).toBe(204);-- await waitFor(() => mainReplyHeld, "the main reply");- await Bun.sleep(300);- // What a provider sync, a skill change or an idle sweep sends mid-turn.- expect((await engineFetch("/instance/dispose", { method: "POST" })).status).toBe(200);-- const done = await waitFor(async () => {- const list = await getJson<V1Message[]>(`/session/${session.id}/message`);- const last = list.at(-1);- return last?.info.role === "assistant" && last.info.time?.completed && last.parts.some((part) => part.type === "text" && part.text === "All done.") ? list : null;- }, "the main turn");- const task = done.flatMap((message) => message.parts).find((part) => part.type === "tool" && part.tool === "task");- expect(task?.state?.error ?? "").not.toContain("location shut down");- expect(task?.state?.status).toBe("completed");- expect(task?.state?.output ?? "").toContain("child done");-- const sessions = await getJson<Array<{ id: string; parentID?: string }>>("/session");- const children = sessions.filter((entry) => entry.parentID === session.id);- expect(children).toHaveLength(1);- }, 120_000);-});diff --git a/apps/server/src/engine2/trace-parity.test.ts b/apps/server/src/engine2/trace-parity.test.tsdeleted file mode 100644index 5490ff59..00000000--- a/apps/server/src/engine2/trace-parity.test.ts+++ /dev/null@@ -1,215 +0,0 @@-import { afterAll, describe, expect, test } from "bun:test";-import { readFileSync } from "node:fs";-import { join } from "node:path";--import { createSessionObservers, observeUploadedSession, type EngineTarget, type ObservedUploader, type ObserverTiming } from "../session-upload-observer.js";-import type { UploadChildSession } from "../session-uploader.js";-import { startEngineFacade, type EngineFacade } from "./facade.js";--/**- * The uploaded trace does not depend on the engine: the turn observer- * (session-upload-observer.ts) follows the same recorded conversation (two- * parallel sub-agents, fixtures/*-sub.json) once on the 1.x engine and once- * on the 2.x engine behind the engine adapter, and hands the session uploader the- * same trace events, carrying messages and sub-agent sessions with the same- * fields.- */--type Tree = { session: Record<string, unknown>; messages: Array<Record<string, 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;-}--const NATIVE_PART_TYPES = new Set(["agent-switched", "model-switched", "location-switched", "system", "idle"]);--/**- * What the 2.x trace lacks or changes against the 1.x trace (the 2.x- * engine's own fields and parts are additions, engine2/native.ts, and are- * not reported).- */-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)) {- const right = path.endsWith(".parts") ? b.filter((part) => !NATIVE_PART_TYPES.has(String((part as { type?: string }).type))) : b;- if (a.length !== right.length) out.push(`${path}: length ${a.length} != ${right.length}`);- for (let index = 0; index < Math.min(a.length, right.length); index++) shapeDiff(a[index], right[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 on 1.x`);- 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;-}--const stops: Array<() => unknown> = [];-afterAll(async () => {- while (stops.length) await stops.pop()?.();-});--function page(url: URL, list: unknown[]): Response {- const limit = Number(url.searchParams.get("limit") ?? 0);- if (!limit) return Response.json(list);- const end = url.searchParams.has("before") ? Number(url.searchParams.get("before")) : list.length;- const start = Math.max(0, end - limit);- return Response.json(list.slice(start, end), start > 0 ? { headers: { "X-Next-Cursor": String(start) } } : {});-}--function flatten(tree: Tree, out: Tree[] = []): Tree[] {- out.push(tree);- for (const child of tree.children) flatten(child, out);- return out;-}--/** The 1.x engine's routes the observer reads, serving a recorded 1.x conversation. */-function startV1Engine(tree: Tree): EngineTarget {- const sessions = new Map(flatten(tree).map((node) => [String(node.session.id), node]));- const server = Bun.serve({- hostname: "127.0.0.1",- port: 0,- fetch(request) {- const url = new URL(request.url);- if (url.pathname === "/session/status") return Response.json({});- const match = url.pathname.match(/^\/session\/([^/]+)(?:\/(message|children))?$/);- const node = match ? sessions.get(decodeURIComponent(match[1]!)) : undefined;- if (!node) return Response.json({ name: "NotFoundError" }, { status: 404 });- if (match![2] === "message") return page(url, node.messages);- if (match![2] === "children") return Response.json(node.children.map((child) => child.session));- return Response.json(node.session);- },- });- stops.push(() => server.stop(true));- return { baseUrl: `http://127.0.0.1:${server.port}`, headers: [], search: "", engine: "v1" };-}--/** The 2.x engine's routes the adapter reads, serving the same conversation recorded on 2.x. */-async function startV2Engine(tree: Tree): Promise<EngineTarget> {- const sessions = new Map(flatten(tree).map((node) => [String(node.session.id), node]));- const upstream = Bun.serve({- hostname: "127.0.0.1",- port: 0,- fetch(request) {- const url = new URL(request.url);- if (url.pathname === "/api/event") return new Response(new ReadableStream({ start() {} }), { headers: { "content-type": "text/event-stream" } });- if (url.pathname === "/api/session/active") return Response.json({ data: {} });- if (url.pathname === "/api/session") {- const parent = url.searchParams.get("parentID");- const node = parent ? sessions.get(parent) : undefined;- return Response.json({ data: node ? node.children.map((child) => child.session) : [], cursor: {} });- }- const match = url.pathname.match(/^\/api\/session\/([^/]+)(?:\/(message|diff))?$/);- const node = match ? sessions.get(decodeURIComponent(match[1]!)) : undefined;- if (!node) return Response.json({ name: "NotFoundError" }, { status: 404 });- if (match![2] === "message") {- const list = url.searchParams.get("order") === "desc" ? [...node.messages].reverse() : node.messages;- return Response.json({ data: list.slice(0, Number(url.searchParams.get("limit") ?? 50)), cursor: {} });- }- if (match![2] === "diff") return Response.json({ data: [] });- return Response.json({ data: node.session });- },- });- stops.push(() => upstream.stop(true));- const facade: EngineFacade = await startEngineFacade({- upstreamUrl: `http://127.0.0.1:${upstream.port}`,- upstreamPassword: "pw",- username: "u",- password: "p",- version: "2.0.18",- defaultDirectory: "/work/proj",- });- stops.push(() => facade.close());- return { baseUrl: facade.url, headers: [["authorization", `Basic ${Buffer.from("u:p").toString("base64")}`]], search: "", engine: "v1" };-}--type Entry =- | { kind: "trace"; type: string; data?: unknown }- | { kind: "model"; model: unknown }- | { kind: "child"; child: UploadChildSession }- | { kind: "flush"; final?: unknown };--class RecordingUploader implements ObservedUploader {- readonly enabled = true;- readonly entries: Entry[] = [];- async sessionCheckpoint() {- return { resumed: false };- }- async setSessionCheckpoint() {}- recordTrace(_sessionId: string, type: string, data?: unknown) {- this.entries.push({ kind: "trace", type, ...(data === undefined ? {} : { data }) });- }- recordSessionModel(_sessionId: string, model: unknown) {- this.entries.push({ kind: "model", model });- }- async childCheckpoints() {- return {};- }- async childSessionIds() {- return [];- }- recordChildSession(_sessionId: string, child: UploadChildSession) {- this.entries.push({ kind: "child", child });- }- captureSnapshot() {}- flushTrace(_sessionId: string, final?: unknown) {- this.entries.push({ kind: "flush", ...(final === undefined ? {} : { final }) });- }-}--const timing: Partial<ObserverTiming> = { sleep: async () => undefined };--async function observe(target: EngineTarget, sessionId: string): Promise<RecordingUploader> {- const sessionUploader = new RecordingUploader();- const archive = { turnFollowed: () => undefined, turnCompleted: () => undefined, turnIncomplete: () => undefined };- await observeUploadedSession({ sessionUploader, archive, observers: createSessionObservers(), sessionId, target, timing });- return sessionUploader;-}--/** Sub-agents start concurrently: children are compared by the task they were given. */-function childKey(child: UploadChildSession): string {- const first = (child.messages as Array<{ parts?: Array<{ text?: string }> }>)[0];- return String(first?.parts?.[0]?.text ?? "");-}--describe("the uploaded trace over the 2.x engine matches the 1.x engine's", () => {- test("two parallel sub-agents: same events, messages and sub-agent sessions", async () => {- const v1 = fixture("v1-sub");- const v2 = fixture("v2-sub");- // As the engine records it in the app: no variant picked reads as "default" on each step.- for (const node of flatten(v2)) for (const message of node.messages) if (message.type === "assistant" && message.model && typeof message.model === "object") (message.model as Record<string, unknown>).variant = "default";- const before = await observe(startV1Engine(v1), String(v1.session.id));- const after = await observe(await startV2Engine(v2), String(v2.session.id));- const labels = (sessionUploader: RecordingUploader) => sessionUploader.entries.map((entry) => (entry.kind === "trace" ? entry.type : entry.kind));- expect(labels(after)).toEqual(labels(before));- expect(labels(after)).toContain("child");-- const final = (sessionUploader: RecordingUploader) => (sessionUploader.entries.find((entry) => entry.kind === "flush" && entry.final !== undefined) as { final: { messages: unknown[] } }).final;- expect(shapeDiff(final(before).messages, final(after).messages)).toEqual([]);-- const children = (sessionUploader: RecordingUploader) => sessionUploader.entries- .flatMap((entry) => (entry.kind === "child" ? [entry.child] : []))- .sort((a, b) => childKey(a).localeCompare(childKey(b)));- const [left, right] = [children(before), children(after)];- expect(right.length).toBe(2);- left.forEach((child, index) => {- const other = right[index]!;- expect(Object.keys(other).sort()).toEqual(Object.keys(child).sort());- expect(other.agent).toBe(child.agent);- expect(String(other.title)).toMatch(/\(@general subagent\)$/);- expect(shapeDiff(child.messages, other.messages)).toEqual([]);- });-- // The session.model event: the same provider, model, variant and agent.- const model = (sessionUploader: RecordingUploader) => sessionUploader.entries.find((entry) => entry.kind === "model");- expect(model(after)).toBeDefined();- expect(model(after)).toEqual(model(before));- });-});diff --git a/apps/server/src/opencode-plugins/omnirush-anthropic-tool-schema.test.ts b/apps/server/src/opencode-plugins/omnirush-anthropic-tool-schema.test.tsindex 30b1fab6..d29f753d 100644--- a/apps/server/src/opencode-plugins/omnirush-anthropic-tool-schema.test.ts+++ b/apps/server/src/opencode-plugins/omnirush-anthropic-tool-schema.test.ts@@ -123,43 +123,3 @@ describe("OmniRushAnthropicToolSchema fetch patch", () => {expect(Object.keys(mod)).toEqual(["OmniRushAnthropicToolSchema"]);});});--describe("tool schema transform on the 2.x engine's context hook", () => {- const anthropicModel = { id: "claude-sonnet-5", api: { npm: "@opencode/ai/providers/anthropic" } };- const openaiModel = { id: "gpt-6-astra", api: { npm: "@opencode/ai/providers/openai" } };-- async function transform(model: unknown, tools: Record<string, { description: string; input: Record<string, unknown> }>) {- const hooks = (await OmniRushAnthropicToolSchema()) as unknown as Record<string, (input: unknown, output: unknown) => Promise<void>>;- await hooks["omnirush.tools.transform"]!({ model }, { tools });- return tools;- }-- test("flattens a top-level anyOf for an Anthropic model, in place", async () => {- const tools = await transform(anthropicModel, {- export_batch: { description: "Export", input: structuredClone(topLevelAnyOf) },- plain: { description: "Plain", input: { type: "object", properties: { a: { type: "string" } } } },- });- expect(tools.export_batch!.input.anyOf).toBeUndefined();- expect(tools.export_batch!.input.type).toBe("object");- expect(Object.keys(tools.export_batch!.input.properties as object).sort()).toEqual(["file", "name", "url"]);- expect(tools.plain!.input).toEqual({ type: "object", properties: { a: { type: "string" } } });- });-- test("flattens oneOf and allOf, and Messages-protocol and Claude models too", async () => {- for (const model of [{ id: "x", api: { npm: "@opencode/ai/providers/google-vertex/messages" } }, { id: "claude-4", api: { npm: "@opencode/ai/providers/amazon-bedrock" } }]) {- const tools = await transform(model, {- one: { description: "", input: { oneOf: [{ type: "object", properties: { a: { type: "string" } }, required: ["a"] }, { type: "object", properties: { b: { type: "number" } }, required: ["b"] }] } },- all: { description: "", input: { allOf: [{ type: "object", properties: { a: { type: "string" } }, required: ["a"] }, { type: "object", properties: { b: { type: "number" } }, required: ["b"] }] } },- });- expect(tools.one!.input.oneOf).toBeUndefined();- expect(tools.all!.input.allOf).toBeUndefined();- expect(tools.all!.input.required).toEqual(["a", "b"]);- }- });-- test("leaves other providers' schemas unchanged", async () => {- const input = structuredClone(topLevelAnyOf);- const tools = await transform(openaiModel, { export_batch: { description: "Export", input } });- expect(tools.export_batch!.input).toEqual(topLevelAnyOf);- });-});diff --git a/apps/server/src/opencode-plugins/omnirush-anthropic-tool-schema.ts b/apps/server/src/opencode-plugins/omnirush-anthropic-tool-schema.tsindex be407aa9..98286cdf 100644--- a/apps/server/src/opencode-plugins/omnirush-anthropic-tool-schema.ts+++ b/apps/server/src/opencode-plugins/omnirush-anthropic-tool-schema.ts@@ -119,38 +119,9 @@ function installAnthropicFetchPatch(): void {globalThis.fetch = Object.assign(patched, base);}-/**- * Whether a model is served over the Anthropic Messages API: its AI SDK- * package (the catalog's `api.npm`) is an Anthropic or Messages-protocol one,- * or it is a Claude model.- */-function speaksAnthropicMessages(model: unknown): boolean {- if (!isRecord(model)) return false;- const api = isRecord(model.api) ? model.api : {};- const npm = typeof api.npm === "string" ? api.npm : "";- const id = typeof model.id === "string" ? model.id : "";- return /anthropic|\/messages$/i.test(npm) || /claude/i.test(id);-}-// Single export: the OpenCode plugin loader treats every export of a plugin// module as a plugin factory, so helpers must stay module-private.export const OmniRushAnthropicToolSchema = async () => {- // The 1.x engine sends model requests through the global fetch.installAnthropicFetchPatch();- return {- // The 2.x engine does not use the global fetch: the plugin bridge- // (omnirush-engine2.ts) calls this with the tool definitions of every- // model request before it is sent (the engine's session "context" hook).- "omnirush.tools.transform": async (- input: { model?: unknown },- output: { tools: Record<string, { input?: unknown }> },- ) => {- if (!speaksAnthropicMessages(input?.model) || !isRecord(output?.tools)) return;- for (const tool of Object.values(output.tools)) {- if (!isRecord(tool) || !isRecord(tool.input)) continue;- const flattened = flattenTopLevelCombinators(tool.input);- if (flattened !== tool.input) tool.input = flattened;- }- },- };+ return {};};diff --git a/apps/server/src/opencode-plugins/omnirush-engine2.ts b/apps/server/src/opencode-plugins/omnirush-engine2.tsdeleted file mode 100644index a813b858..00000000--- a/apps/server/src/opencode-plugins/omnirush-engine2.ts+++ /dev/null@@ -1,573 +0,0 @@-/**- * 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"- * tool.definition session "context" (tools: description)- * 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 BudgetWrap from "./omnirush-budget-wrap.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,- BudgetWrap,- 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 };--/** The subagent tool's `model` parameter as offered: the swarm plugin keeps it only when the user named it. */-const SUBAGENT_MODEL_DESCRIPTION = [- "Leave this out unless the user's own message asks for a particular model for the sub-agent.",- 'Then pass the model the user named, as "omnirush/<model id>", or "omnirush/<model id>#<effort>" when they also named an effort.',- "A model id is its display name in lowercase with dashes for spaces (a model shown as \"Some Model 2\" has the id some-model-2).",- "It is used only when the user's latest message names that model, by id or display name; otherwise the sub-agent runs on the user's sub-agent model setting.",-].join(" ");--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>) : []));- // The 2.x engine has no todo list tool; the app's todo panel reads the 1.x one (`todowrite`).- const todoItem = z.object({- content: z.string().describe("Brief description of the task"),- status: z.string().describe("Current status of the task: pending, in_progress, completed, cancelled"),- priority: z.string().describe("Priority level of the task: high, medium, low"),- id: z.string().optional().describe("Unique identifier for the todo item"),- });- const todoArgs = { todos: z.array(todoItem).describe("The updated todo list") };- tools.push(["todowrite", {- description: "Use this tool to create and manage a structured task list for your current session. It helps you track progress on complex, multi-step work and shows the user what you are doing. Send the whole updated list every time; mark exactly one task in_progress while you work on it and mark tasks completed as soon as they are done.",- args: todoArgs,- async execute(raw: unknown, context: { sessionID?: string }) {- const todos = z.object(todoArgs).parse(raw).todos;- const baseUrl = process.env.OMNIRUSH_ENGINE_ADAPTER_URL?.trim();- if (baseUrl && context?.sessionID) {- const authorization = process.env.OMNIRUSH_ENGINE_ADAPTER_AUTHORIZATION?.trim();- await fetch(`${baseUrl}/omnirush/todos`, {- method: "POST",- headers: { "content-type": "application/json", ...(authorization ? { authorization } : {}) },- body: JSON.stringify({ sessionID: context.sessionID, todos }),- signal: AbortSignal.timeout(5_000),- }).catch(() => undefined);- }- return { title: `${todos.filter((todo) => todo.status !== "completed").length} todos`, output: JSON.stringify(todos, null, 2), metadata: { todos } };- },- }]);-- 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 --------------------------------------------------------- // Sub-agents run in the foreground, as the 1.x task tool did (the swarm counts running- // sub-agents and the task result carries the sub-agent's answer).- // A call's own `model` is kept here: the swarm plugin's tool.execute.before (below) keeps it only- // when the user's own message names that model, and drops it otherwise, so the sub-agent runs on- // the app's sub-agent setting (or the caller's model), as with the 1.x task tool.- await ctx.tool.hook("execute.before", async (event: any) => {- if (event.tool !== "subagent" || !isRec(event.input)) return;- const { background: _background, ...input } = event.input;- event.input = input;- });- // …so the subagent tool is offered without `background`, and with `model` for a model the user asks for.- await ctx.session.hook("context", async (event: any) => {- const input = event?.tools?.subagent?.input;- if (!isRec(input) || !isRec(input.properties)) return;- const { background: _background, ...properties } = input.properties as Rec;- if (isRec(properties.model)) properties.model = { ...properties.model, description: SUBAGENT_MODEL_DESCRIPTION };- event.tools.subagent.input = {- ...input,- properties,- ...(Array.isArray(input.required) ? { required: input.required.filter((key: unknown) => key !== "background") } : {}),- };- });- 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 metadata: Rec = isRec(event.result.metadata) ? { ...event.result.metadata } : {};- // The 1.x task tool named its child session `sessionId`.- if (event.tool === "subagent" && typeof metadata.sessionID === "string" && metadata.sessionId === undefined) metadata.sessionId = metadata.sessionID;- const output: { title: string; output: string; metadata: Rec } = { title: "", output: original, 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 };- // `agent` names title and compaction requests, which may run on another model.- for (const hook of messageHooks) await hook({ sessionID: input.sessionID, model: input.model, agent: input.agent }, 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;- }- });- }-- // Hooks OmniRush plugins offer for the 2.x engine only (the 1.x engine has no counterpart):- // the real outgoing model request and its response, and each request's tool definitions.- const httpRequestHooks = hooks("omnirush.http.request");- const httpResponseHooks = hooks("omnirush.http.response");- if (httpRequestHooks.length) {- await ctx.session.hook("http.request", async (event: any) => {- for (const hook of httpRequestHooks) await hook(event, event);- });- }- if (httpResponseHooks.length) {- await ctx.session.hook("http.response", async (event: any) => {- for (const hook of httpResponseHooks) await hook(event, event);- });- }- // 1.x `tool.definition` (a tool's description and parameters, per model request): the 2.x- // engine offers each request's tools in the session "context" hook, under 2.x names.- const definitionHooks = hooks("tool.definition");- if (definitionHooks.length) {- await ctx.session.hook("context", async (event: any) => {- if (!isRec(event.tools)) return;- for (const [name, tool] of Object.entries(event.tools as Record<string, unknown>)) {- if (!isRec(tool) || typeof tool.description !== "string") continue;- const output = { description: tool.description, parameters: tool.input };- for (const hook of definitionHooks) await hook({ toolID: v1ToolName(name) }, output);- if (output.description !== tool.description) tool.description = output.description;- }- });- }- const toolSchemaHooks = hooks("omnirush.tools.transform");- if (toolSchemaHooks.length) {- await ctx.session.hook("context", async (event: any) => {- if (!isRec(event.tools)) return;- const input = await hookInput(event);- for (const hook of toolSchemaHooks) await hook({ sessionID: input.sessionID, model: input.model }, { tools: event.tools });- });- }-- 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);- // A new sub-agent session has no step yet: it runs on the model of the session above it.- let current: { providerID: string; modelID: string; variant?: string } | undefined;- let cursor: unknown = info;- for (let hop = 0; hop < 5 && isRec(cursor); hop++) {- if (isRec(cursor.model) && typeof cursor.model.id === "string") {- current = { providerID: String(cursor.model.providerID), modelID: String(cursor.model.id), variant: typeof cursor.model.variant === "string" && cursor.model.variant !== "default" ? cursor.model.variant : undefined };- break;- }- if (typeof cursor.parentID !== "string") break;- cursor = await adapterJson(`/session/${encodeURIComponent(cursor.parentID)}`, directory);- }- 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/apps/server/src/opencode-plugins/omnirush-title-recovery.test.ts b/apps/server/src/opencode-plugins/omnirush-title-recovery.test.tsdeleted file mode 100644index 1cb656d7..00000000--- a/apps/server/src/opencode-plugins/omnirush-title-recovery.test.ts+++ /dev/null@@ -1,82 +0,0 @@-import { afterAll, describe, expect, test } from "bun:test";--import { OmniRushTitleRecovery } from "./omnirush-title-recovery.js";--/**- * The 2.x engine's side of title recovery: the plugin bridge hands the- * plugin the real outgoing request ("omnirush.http.request") and its response- * ("omnirush.http.response"). The private marker header never leaves, and an- * optional parameter the provider rejects is retried without it.- */--const HEADER = "x-omnirush-title-attempt";-const seen: Array<{ headers: Headers; body: Record<string, unknown> }> = [];-const provider = Bun.serve({- port: 0,- async fetch(request) {- const body = (await request.json()) as Record<string, unknown>;- seen.push({ headers: request.headers, body });- if ("temperature" in body) {- return Response.json({ error: { code: "unsupported_parameter", param: "temperature", message: "temperature is not supported" } }, { status: 400 });- }- return Response.json({ ok: true });- },-});-afterAll(() => provider.stop(true));--type Hooks = Record<string, (...args: any[]) => Promise<void>>;-async function plugin(): Promise<{ hooks: Hooks; logs: Array<{ outcome: string; parameter?: string }> }> {- const logs: Array<{ outcome: string; parameter?: string }> = [];- const hooks = (await OmniRushTitleRecovery({- client: { app: { log: async (input) => { logs.push(input.body.extra); } } },- })) as unknown as Hooks;- return { hooks, logs };-}--/** What the engine does around one model request: headers from chat.headers, then the http hooks. */-async function send(hooks: Hooks, agent: string, body: Record<string, unknown>): Promise<Response> {- const headers: Record<string, string> = { "content-type": "application/json", authorization: "Bearer k" };- await hooks["chat.headers"]!({ sessionID: "ses_1", agent, model: { id: "m", providerID: "p" } }, { headers });- const event = { request: new Request(`http://127.0.0.1:${provider.port}/v1/chat/completions`, { method: "POST", headers, body: JSON.stringify(body) }) } as { request: Request; response?: Response };- await hooks["omnirush.http.request"]!(event);- const response = await fetch(event.request);- const after = { request: event.request, response };- await hooks["omnirush.http.response"]!(after);- return after.response;-}--describe("title recovery on the 2.x engine's http hooks", () => {- test("the marker never reaches the provider; a rejected temperature is retried without it", async () => {- seen.length = 0;- const { hooks, logs } = await plugin();- const response = await send(hooks, "title", { model: "m", temperature: 0.5, messages: [] });- expect(response.status).toBe(200);- expect(seen.length).toBe(2);- for (const request of seen) expect(request.headers.get(HEADER)).toBeNull();- expect(seen[0]!.headers.get("authorization")).toBe("Bearer k");- expect("temperature" in seen[0]!.body).toBe(true);- expect("temperature" in seen[1]!.body).toBe(false);- expect(seen[1]!.headers.get("authorization")).toBe("Bearer k");- expect(logs.map((log) => log.outcome)).toEqual(["started", "request_rejected", "retrying_parameter", "accepted_after_recovery"]);- expect(logs[2]!.parameter).toBe("temperature");- });-- test("an accepted title request goes out once, without the marker", async () => {- seen.length = 0;- const { hooks, logs } = await plugin();- const response = await send(hooks, "title", { model: "m", messages: [] });- expect(response.status).toBe(200);- expect(seen.length).toBe(1);- expect(seen[0]!.headers.get(HEADER)).toBeNull();- expect(logs.map((log) => log.outcome)).toEqual(["started", "accepted"]);- });-- test("other agents' requests are left alone (no retry, no rewrite)", async () => {- seen.length = 0;- const { hooks } = await plugin();- const response = await send(hooks, "build", { model: "m", temperature: 0.5, messages: [] });- expect(response.status).toBe(400);- expect(seen.length).toBe(1);- expect(seen[0]!.headers.get(HEADER)).toBeNull();- });-});diff --git a/apps/server/src/opencode-plugins/omnirush-title-recovery.ts b/apps/server/src/opencode-plugins/omnirush-title-recovery.tsindex b32e3d9d..6d9bd2b7 100644--- a/apps/server/src/opencode-plugins/omnirush-title-recovery.ts+++ b/apps/server/src/opencode-plugins/omnirush-title-recovery.ts@@ -159,58 +159,7 @@ export const OmniRushTitleRecovery = async (input: {service: "omnirush.title", level, message: "Automatic title generation", extra: diagnostic,} }).catch(() => undefined);};- /** Requests the 2.x hooks stripped the marker from: the marker and the body as sent. */- const sent = new WeakMap<Request, { id: string; body: string | undefined }>();return {- // The 2.x engine does not use the global fetch: the plugin bridge- // (omnirush-engine2.ts) hands these the real outgoing request and its- // response (the engine's session "http.request" / "http.response" hooks).- // The marker never reaches a provider, and a rejected optional title- // parameter is retried without it, as the fetch patch does for 1.x.- "omnirush.http.request": async (event: { request: Request }) => {- const request = event?.request;- const id = request?.headers.get(HEADER);- if (!request || !id) return;- const headers = new Headers(request.headers);- headers.delete(HEADER);- const body = request.body ? await request.clone().text() : undefined;- const next = new Request(request.url, { method: request.method, headers, body, signal: request.signal });- sent.set(next, { id, body });- event.request = next;- },- "omnirush.http.response": async (event: { request: Request; response: Response }) => {- const entry = event?.request ? sent.get(event.request) : undefined;- if (!entry) return;- sent.delete(event.request);- const attempt = attempts.get(entry.id);- if (!attempt) return;- const response = event.response;- if (response.ok) {- report(attempt, "accepted", response.status);- return;- }- report(attempt, failure(response.status), response.status);- if (attempt.retried || response.status !== 400 || entry.body === undefined) return;- const recovered = correction(entry.body, await errorBody(response));- if (!recovered || attempts.get(entry.id) !== attempt || event.request.signal.aborted) return;- attempt.retried = true;- report(attempt, "retrying_parameter", response.status, recovered.parameter);- const headers = new Headers(event.request.headers);- headers.delete("content-length");- try {- const retry = await globalThis.fetch(event.request.url, {- method: event.request.method,- headers,- body: recovered.body,- signal: AbortSignal.any([event.request.signal, AbortSignal.timeout(DEADLINE_MS)]),- });- report(attempt, retry.ok ? "accepted_after_recovery" : failure(retry.status), retry.status);- void response.body?.cancel().catch(() => undefined);- event.response = retry;- } catch {- report(attempt, event.request.signal.aborted ? "cancelled" : "transport_failed");- }- },"chat.headers": async (request: {sessionID: string; agent: string; model: { id: string; providerID: string };}, output: { headers: Record<string, string> }) => {diff --git a/constants.json b/constants.jsonindex 3ac9c7e0..da2c0879 100644--- a/constants.json+++ b/constants.json@@ -1,4 +1,4 @@{- "opencodeVersion": "v2.0.18",+ "opencodeVersion": "v1.18.32","opencodeV2Version": "0.0.0-beta-19086"}