From 6043d0d9d6b32339c50e48a8f5a48f38df7d6aa5 Mon Sep 17 00:00:00 2001 From: Egor Shatalov Date: Wed, 30 Sep 2026 02:25:51 +0300 Subject: [PATCH 1/6] feat(opencode): support OpenCode 2.x only, login snapshotted from opencode.db OpenCode 2.x keeps credentials in the credential table of opencode.db, next to the sessions; auth.json is gone and a fresh data dir never imports it, so the 1.x plugin reported "not authorized" against a live login and its shadow could not share the user's providers. The plugin now targets 2.x only. auth() reads the provider ids from the credential table through node:sqlite without launching the harness. home() builds the shadow as a snapshot of the user's DB (VACUUM INTO from a read-only connection, every project/session row deleted, no table dropped, ~240 KB) written through a .tmp file, so a resumed turn finds a finished shadow. models() runs the same throwaway ACP handshake grok uses inside a temporary shadow, because `opencode models` starts a persistent background service when none runs and `--standalone` prints nothing in 2.0.20. OPENCODE_PRINT_LOGS=1 keeps the private server's stderr as evidence. extractUsage also reads thoughtTokens and cachedWriteTokens. Node 22.13+ for unflagged node:sqlite. Offline tests cover the snapshot, idempotent resume, and the auth refusals. Verified against opencode 2.0.20: smoke + resume and the cancel probe on zai-coding-plan/glm-5.3-flash, the user's session list and background service untouched. Designed and finished by Claude Fable 5.1, implemented by Claude Opus, reviewed by Claude Sonnet, in Claude Code. Co-Authored-By: Claude Fable 5.1 --- README.md | 6 +- package-lock.json | 2 +- package.json | 2 +- src/core/acp-turn.ts | 4 +- src/plugins/acp-models-probe.ts | 28 +++-- src/plugins/opencode.ts | 153 +++++++++++++++++-------- test/opencode.test.ts | 192 ++++++++++++++++++++++++++++++++ 7 files changed, 326 insertions(+), 61 deletions(-) create mode 100644 test/opencode.test.ts diff --git a/README.md b/README.md index 2709ffe..6f7b78d 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ npm install -g subturn claude mcp add subturn -- subturn serve ``` -Requires Node 22 or newer. Until the package is published, `npx github:eshatalov/subturn` works the same way. From a checkout, `npm install` builds `dist/` and the server is `node dist/faces/mcp.js`. +Requires Node 22.13 or newer, and OpenCode 2 or newer for that harness. Until the package is published, `npx github:eshatalov/subturn` works the same way. From a checkout, `npm install` builds `dist/` and the server is `node dist/faces/mcp.js`. ## The caller's whole manual @@ -54,7 +54,7 @@ CLI `spawn` and `resume` detach a per-turn supervisor, so the one-shot invocatio ## How it works -**Core** (`src/core`) has five functions, one per verb. Admission runs before any quota is spent: a persisted per-harness pin (the newest copy of the binary on PATH or in the usual install dirs, re-probed when that set of files changes) and a cheap auth check that never launches the harness (Codex's `auth.json` tokens, the macOS keychain item for Claude Code, Grok's and OpenCode's auth files). A spawn that dies before the harness produces a session id throws a plain error carrying the auth result, argv, stderr, and exit inline. Model ids are never gated: a wrong one fails inside the harness and comes back as evidence. +**Core** (`src/core`) has five functions, one per verb. Admission runs before any quota is spent: a persisted per-harness pin (the newest copy of the binary on PATH or in the usual install dirs, re-probed when that set of files changes) and a cheap auth check that never launches the harness (Codex's `auth.json` tokens, the macOS keychain item for Claude Code, Grok's auth file, the `credential` table in OpenCode's database). A spawn that dies before the harness produces a session id throws a plain error carrying the auth result, argv, stderr, and exit inline. Model ids are never gated: a wrong one fails inside the harness and comes back as evidence. **Sessions** live under `~/.local/state/subturn/sessions//` (`SUBTURN_STATE_DIR` overrides). The directory holds the record, the prompt, the spawn command, the event stream as it happens, stderr, the acknowledged bundle where the harness echoes one, and the final text, so `inspect` works on a running session. Retention is 7 days after the last turn (`SUBTURN_RETENTION_DAYS`), swept on each spawn or on demand by `prune`; the resume window is the retention window, because the harness state needed for resume lives in the same directory. The deadline default is 3600 s (`SUBTURN_DEADLINE_S`), the maximum six hours. @@ -66,7 +66,7 @@ CLI `spawn` and `resume` detach a per-turn supervisor, so the one-shot invocatio | harness | transport | bundle | resume | session hygiene | |----------|-----------|--------|--------|-----------------| -| opencode | native ACP (`opencode acp`) | `session/set_config_option` model then effort, every turn | ACP `session/load`, replay isolated from the new turn's final text | shadow data dir via `XDG_DATA_HOME`; `auth.json` symlinked back | +| opencode | native ACP (`opencode acp`) | `session/set_config_option` model then effort, every turn | ACP `session/load`, replay isolated from the new turn's final text | shadow data dir via `XDG_DATA_HOME`; the user's credentials snapshotted into a private `opencode.db` with the session tables emptied | | grok | native ACP (`grok agent … stdio`) | `-m` / `--reasoning-effort` every turn; ack read from `session/new` | ACP `session/load` | shadow home via `GROK_HOME`; `auth.json` symlinked back | | codex | headless `codex exec --json` | `-m` / `-c model_reasoning_effort=` every turn | `codex exec resume ` in the session's `CODEX_HOME` shadow | shadow home via `CODEX_HOME`; `auth.json` symlinked back; the user's `config.toml` deliberately not shared | | claude | headless `claude -p --output-format stream-json` | `--model` / `--effort` every turn | `claude -p --resume ` after restoring parked files | default config dir, because keychain auth is bound to it; session files parked out of `~/.claude/projects` the moment a turn ends | diff --git a/package-lock.json b/package-lock.json index cea344d..247c500 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,7 +19,7 @@ "typescript": "^7.0.2" }, "engines": { - "node": ">=22" + "node": ">=22.13" } }, "node_modules/@hono/node-server": { diff --git a/package.json b/package.json index 4a45f13..c6e5de9 100644 --- a/package.json +++ b/package.json @@ -24,7 +24,7 @@ ], "type": "module", "engines": { - "node": ">=22" + "node": ">=22.13" }, "bin": { "subturn": "dist/faces/cli.js" diff --git a/src/core/acp-turn.ts b/src/core/acp-turn.ts index 9066f93..b350b1b 100644 --- a/src/core/acp-turn.ts +++ b/src/core/acp-turn.ts @@ -74,8 +74,8 @@ function extractUsage(candidates: unknown[]): Usage | undefined { const out = c["output_tokens"] ?? c["outputTokens"]; const total = c["total_tokens"] ?? c["totalTokens"]; const cacheRead = c["cache_read_input_tokens"] ?? c["cachedReadTokens"] ?? c["cache_read_tokens"]; - const cacheCreate = c["cache_creation_input_tokens"] ?? c["cacheCreationTokens"]; - const reasoning = c["reasoning_tokens"] ?? c["reasoningTokens"]; + const cacheCreate = c["cache_creation_input_tokens"] ?? c["cacheCreationTokens"] ?? c["cachedWriteTokens"]; + const reasoning = c["reasoning_tokens"] ?? c["reasoningTokens"] ?? c["thoughtTokens"]; const cost = c["cost_usd"] ?? c["costUsd"] ?? c["total_cost_usd"]; if (typeof inp === "number") usage.input_tokens = inp; if (typeof out === "number") usage.output_tokens = out; diff --git a/src/plugins/acp-models-probe.ts b/src/plugins/acp-models-probe.ts index dd49724..6d8d566 100644 --- a/src/plugins/acp-models-probe.ts +++ b/src/plugins/acp-models-probe.ts @@ -1,6 +1,9 @@ // plugins/acp-models-probe.ts — throwaway ACP handshake for CLI `status`: // spawn the agent, initialize + session/new in a temp cwd, read the -// advertised models, kill. Never sends a prompt; costs no quota. +// advertised models, kill. Never sends a prompt; costs no quota. Models are +// read from either shape a harness advertises them in: grok's +// `models.availableModels[].modelId`, or opencode's `configOptions[]` entry +// with id "model" (`options[].value`). import { mkdtempSync, rmSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -34,14 +37,25 @@ export async function probeAcpModels( }, 20_000); const res = await client.request("session/new", { cwd, mcpServers: [] }, 30_000); if (!isRecord(res)) return null; + const ids: string[] = []; const models = isRecord(res["models"]) ? res["models"] : null; const available = models?.["availableModels"]; - if (!Array.isArray(available)) return null; - const ids = available - .filter(isRecord) - .map((m) => (typeof m["modelId"] === "string" ? m["modelId"] : null)) - .filter((m): m is string => m !== null); - return ids.length > 0 ? ids : null; + if (Array.isArray(available)) { + for (const m of available) { + if (isRecord(m) && typeof m["modelId"] === "string") ids.push(m["modelId"]); + } + } + const configOptions = res["configOptions"]; + if (Array.isArray(configOptions)) { + for (const o of configOptions) { + if (!isRecord(o) || o["id"] !== "model" || !Array.isArray(o["options"])) continue; + for (const v of o["options"]) { + if (isRecord(v) && typeof v["value"] === "string") ids.push(v["value"]); + } + } + } + // grok advertises the same ids in both shapes. + return ids.length > 0 ? [...new Set(ids)] : null; } catch { return null; } finally { diff --git a/src/plugins/opencode.ts b/src/plugins/opencode.ts index b744551..c4e20d6 100644 --- a/src/plugins/opencode.ts +++ b/src/plugins/opencode.ts @@ -12,35 +12,87 @@ // with the most permissive option (core/acp.ts). No prompt can fire // unanswered. // -// Shadow home: VERIFIED EMPIRICALLY 2026-09-01 against opencode 1.18.25 — -// `XDG_DATA_HOME= opencode session list` creates and uses -// `/opencode/` (opencode.db, log/) and sees none of the user's -// sessions. OpenCode keeps sessions AND auth in that one data dir, so the -// shadow sets XDG_DATA_HOME and symlinks the user's real auth.json back in. -// The user's config dir (~/.config/opencode) is deliberately left alone: -// provider definitions may live there and auth alone is not enough for -// custom providers (zai-coding-plan et al.). +// Shadow home: `opencode acp` runs its own `opencode serve --stdio` child, +// never the user's background service, and that server keeps sessions and +// credentials (table `credential`) in one SQLite file, +// $XDG_DATA_HOME/opencode/opencode.db. The shadow is a snapshot of the +// user's file: `VACUUM INTO` from a read-only connection (consistent while +// the user's service writes), then every table outside KEEP_TABLES emptied +// and the models.dev catalog cache dropped from kv (the binary bundles +// one). No table is dropped: the server refuses to start with one missing. +// Foreign keys are off on that connection so emptying a table cannot +// cascade into a kept one. The snapshot is renamed into place from a .tmp +// file, so an existing opencode.db is always a finished shadow. +// OPENCODE_PRINT_LOGS=1 sends the private server's stderr to stderr.log, +// so a startup death leaves evidence. +// +// OAuth rows are copied with an empty refresh token: the shadow uses the +// access token but can never refresh it, so it can never revoke the user's. +// Once the token expires, turns in that shadow fail with an auth error and +// a fresh spawn snapshots the user's current login. +// +// The user's config dir (~/.config/opencode) is left alone: provider +// definitions may live there (zai-coding-plan et al.). -import { existsSync, readFileSync } from "node:fs"; -import { homedir } from "node:os"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, renameSync, rmSync } from "node:fs"; +import { homedir, tmpdir } from "node:os"; import path from "node:path"; +import { DatabaseSync } from "node:sqlite"; import type { AuthResult, LaunchContext, LaunchOutcome, Plugin, ShadowHome } from "./types.ts"; -import { ensureDir, shareAuth } from "./shadow.ts"; import { configuredValue, runAcpTurn } from "../core/acp-turn.ts"; import type { AcpClient } from "../core/acp.ts"; -import { spawn } from "node:child_process"; +import { probeAcpModels } from "./acp-models-probe.ts"; const SET_CONFIG_TIMEOUT_MS = 30_000; +// The login and the schema bookkeeping; every other table is emptied. +const KEEP_TABLES = new Set(["credential", "migration", "account", "account_state", "control_account", "kv"]); + function realDataDir(): string { const xdg = process.env["XDG_DATA_HOME"]; const base = xdg !== undefined && xdg !== "" ? xdg : path.join(homedir(), ".local", "share"); return path.join(base, "opencode"); } -function realAuthPath(): string { - return path.join(realDataDir(), "auth.json"); +function realDbPath(): string { + return path.join(realDataDir(), "opencode.db"); +} + +/** Copy the user's opencode.db to `shadowDb` keeping only the login (see + * header). The user's DB is opened read-only. */ +export function snapshotCredentials(userDb: string, shadowDb: string): void { + mkdirSync(path.dirname(shadowDb), { recursive: true }); + const tmp = `${shadowDb}.tmp`; + rmSync(tmp, { force: true }); + try { + const src = new DatabaseSync(userDb, { readOnly: true }); + try { + src.prepare("VACUUM INTO ?").run(tmp); + } finally { + src.close(); + } + chmodSync(tmp, 0o600); // like the user's DB: the copy holds their credentials + const db = new DatabaseSync(tmp, { enableForeignKeyConstraints: false }); + try { + const tables = db + .prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'") + .all() + .map((r) => String(r["name"])); + for (const t of tables) { + if (!KEEP_TABLES.has(t)) db.exec(`DELETE FROM "${t.replaceAll('"', '""')}"`); + } + db.exec("DELETE FROM kv WHERE key LIKE 'models-dev:catalog%'"); + db.exec("UPDATE credential SET value = json_set(value, '$.refresh', '') WHERE json_extract(value, '$.type') = 'oauth'"); + db.exec("VACUUM"); + } finally { + db.close(); + } + renameSync(tmp, shadowDb); + } catch (err) { + rmSync(tmp, { force: true }); + throw err; + } } async function setConfig( @@ -64,50 +116,57 @@ export const opencodePlugin: Plugin = { }, auth(): Promise { - const p = realAuthPath(); + const p = realDbPath(); if (!existsSync(p)) { - return Promise.resolve({ ok: false, detail: `no auth file at ${p} — run \`opencode auth login\`` }); + return Promise.resolve({ ok: false, detail: `no opencode.db at ${p} — run \`opencode auth login\`` }); } + let ids: string[]; try { - const parsed = JSON.parse(readFileSync(p, "utf8")) as Record; - const providers = Object.keys(parsed); - if (providers.length === 0) { - return Promise.resolve({ ok: false, detail: `${p} has no provider credentials` }); + const db = new DatabaseSync(p, { readOnly: true }); + try { + // A row's presence is the login; which one is active is the harness's call. + ids = db + .prepare("SELECT DISTINCT integration_id FROM credential WHERE integration_id IS NOT NULL ORDER BY integration_id") + .all() + .map((r) => String(r["integration_id"])); + } finally { + db.close(); } - return Promise.resolve({ ok: true, detail: `auth.json providers: ${providers.join(", ")}` }); - } catch { - return Promise.resolve({ ok: false, detail: `${p} is not valid JSON` }); + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + return Promise.resolve({ ok: false, detail: `cannot read credentials from ${p}: ${msg}` }); + } + if (ids.length === 0) { + return Promise.resolve({ ok: false, detail: `${p} has no credentials — run \`opencode auth login\`` }); } + return Promise.resolve({ ok: true, detail: `credentials in opencode.db: ${ids.join(", ")}` }); }, - models(binPath: string): Promise { - // `opencode models` lists provider/model ids without launching a turn. - return new Promise((resolve) => { - let out = ""; - const child = spawn(binPath, ["models"], { stdio: ["ignore", "pipe", "ignore"] }); - const timer = setTimeout(() => { - try { child.kill("SIGKILL"); } catch { /* gone */ } - resolve(null); - }, 30_000); - child.stdout?.setEncoding("utf8"); - child.stdout?.on("data", (d: string) => { out += d; }); - child.on("error", () => { clearTimeout(timer); resolve(null); }); - child.on("close", () => { - clearTimeout(timer); - const models = out.split("\n").map((l) => l.trim()).filter((l) => l.includes("/")); - resolve(models.length > 0 ? models : null); - }); - }); + async models(binPath: string): Promise { + // Throwaway ACP handshake in a temp shadow; `opencode models` would start + // a background service that outlives us. + const tmp = mkdtempSync(path.join(tmpdir(), "subturn-opencode-models-")); + try { + snapshotCredentials(realDbPath(), path.join(tmp, "opencode", "opencode.db")); + return await probeAcpModels([binPath, "acp"], { XDG_DATA_HOME: tmp }); + } catch { + return null; + } finally { + rmSync(tmp, { recursive: true, force: true }); + } }, home(sessionDir: string): Promise { - const shadowData = ensureDir(path.join(sessionDir, "home", "opencode-data")); - const linked = shareAuth(realAuthPath(), path.join(shadowData, "opencode", "auth.json")); + const shadowData = path.join(sessionDir, "home", "opencode-data"); + const shadowDb = path.join(shadowData, "opencode", "opencode.db"); + // A resumed turn reuses the shadow: session/load finds the session there. + const fresh = !existsSync(shadowDb); + if (fresh) snapshotCredentials(realDbPath(), shadowDb); return Promise.resolve({ - env: { XDG_DATA_HOME: shadowData }, - note: - `XDG_DATA_HOME=${shadowData} (verified: opencode puts its data dir, sessions included, under $XDG_DATA_HOME/opencode); ` + - `auth.json ${linked ? "symlinked from" : "NOT FOUND at"} ${realAuthPath()}`, + env: { XDG_DATA_HOME: shadowData, OPENCODE_PRINT_LOGS: "1" }, + note: fresh + ? `XDG_DATA_HOME=${shadowData}; credentials snapshotted from ${realDbPath()}, session tables emptied` + : `XDG_DATA_HOME=${shadowData}; existing shadow reused (resumed turn)`, }); }, diff --git a/test/opencode.test.ts b/test/opencode.test.ts new file mode 100644 index 0000000..ae12dd6 --- /dev/null +++ b/test/opencode.test.ts @@ -0,0 +1,192 @@ +// test/opencode.test.ts — opencode auth and shadow, offline, against a fake +// user opencode.db. No harness is launched. + +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, mkdirSync, rmSync, existsSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { DatabaseSync } from "node:sqlite"; + +import { opencodePlugin, snapshotCredentials } from "../src/plugins/opencode.ts"; + +const userData = mkdtempSync(path.join(tmpdir(), "subturn-opencode-user-")); +const sessionDir = mkdtempSync(path.join(tmpdir(), "subturn-opencode-session-")); +const scratch = mkdtempSync(path.join(tmpdir(), "subturn-opencode-scratch-")); +const userDb = path.join(userData, "opencode", "opencode.db"); +const savedXdg = process.env["XDG_DATA_HOME"]; + +mkdirSync(path.dirname(userDb), { recursive: true }); +{ + const db = new DatabaseSync(userDb); + // Like the real one: WAL, and foreign keys that cascade between emptied tables. + db.exec(` + PRAGMA journal_mode = WAL; + CREATE TABLE credential (id TEXT PRIMARY KEY, integration_id TEXT, label TEXT, value TEXT, + connector_id TEXT, method_id TEXT, active INTEGER, time_created INTEGER, time_updated INTEGER); + CREATE TABLE migration (id TEXT PRIMARY KEY, time_completed INTEGER); + CREATE TABLE kv (key TEXT PRIMARY KEY, value TEXT); + CREATE TABLE project (id TEXT PRIMARY KEY, worktree TEXT); + CREATE TABLE session_v2 (id TEXT PRIMARY KEY, + project_id TEXT REFERENCES project(id) ON DELETE CASCADE, directory TEXT); + CREATE TABLE session_message (id TEXT PRIMARY KEY, + session_id TEXT REFERENCES session_v2(id) ON DELETE CASCADE, data TEXT); + INSERT INTO credential VALUES + ('cred_1', 'opencode', 'default', '{"type":"oauth","methodID":"device","refresh":"r1","access":"a1","expires":1}', NULL, NULL, 1, 1, 1), + ('cred_2', 'zai-coding-plan', 'default', '{"type":"key","key":"k2"}', NULL, NULL, 1, 2, 2); + INSERT INTO migration VALUES ('m1', 1), ('m2', 2), ('m3', 3); + INSERT INTO kv VALUES ('models-dev:catalog', '${"x".repeat(100_000)}'), ('wellknown:sources', '[]'); + INSERT INTO project VALUES ('proj_1', '/Users/someone/proj'); + INSERT INTO session_v2 VALUES ('ses_1', 'proj_1', '/Users/someone/proj'); + INSERT INTO session_message VALUES ('msg_1', 'ses_1', 'hi'), ('msg_2', 'ses_1', 'hello'); + `); + db.close(); +} +process.env["XDG_DATA_HOME"] = userData; + +test.after(() => { + if (savedXdg === undefined) delete process.env["XDG_DATA_HOME"]; + else process.env["XDG_DATA_HOME"] = savedXdg; + for (const d of [userData, sessionDir, scratch]) rmSync(d, { recursive: true, force: true }); +}); + +function query(file: string, sql: string): Record[] { + const db = new DatabaseSync(file, { readOnly: true }); + try { + return db.prepare(sql).all(); + } finally { + db.close(); + } +} + +const count = (file: string, table: string): number => + Number(query(file, `SELECT count(*) AS n FROM ${table}`)[0]?.["n"]); + +const tableNames = (file: string): string[] => + query(file, "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name") + .map((r) => String(r["name"])); + +const shadowData = path.join(sessionDir, "home", "opencode-data"); +const shadowDb = path.join(shadowData, "opencode", "opencode.db"); +const userCounts = (): Record => + Object.fromEntries(tableNames(userDb).map((t) => [t, count(userDb, t)])); +const userBefore = userCounts(); + +test("auth reads the provider ids from the credential table", async () => { + const res = await opencodePlugin.auth(); + assert.equal(res.ok, true, res.detail); + assert.match(res.detail, /opencode/); + assert.match(res.detail, /zai-coding-plan/); +}); + +test("home snapshots credentials into a private DB with session tables emptied", async () => { + // A live writer holds an open transaction, as the user's service might. + const writer = new DatabaseSync(userDb); + writer.exec("BEGIN; INSERT INTO credential (id, integration_id) VALUES ('cred_uncommitted', 'x')"); + let home: Awaited>; + try { + home = await opencodePlugin.home(sessionDir); + } finally { + writer.exec("ROLLBACK"); + writer.close(); + } + assert.ok(existsSync(shadowDb)); + assert.equal(home.env["XDG_DATA_HOME"], shadowData); + assert.equal(home.env["OPENCODE_PRINT_LOGS"], "1"); + + const creds = "SELECT id, integration_id FROM credential ORDER BY id"; + assert.deepEqual(query(shadowDb, creds), query(userDb, creds)); + const values = query(shadowDb, "SELECT value FROM credential ORDER BY id").map((r) => JSON.parse(String(r["value"]))); + assert.deepEqual(values, [ + { type: "oauth", methodID: "device", refresh: "", access: "a1", expires: 1 }, + { type: "key", key: "k2" }, + ]); + assert.equal(count(shadowDb, "migration"), count(userDb, "migration")); + const keys = query(shadowDb, "SELECT key FROM kv ORDER BY key").map((r) => r["key"]); + assert.deepEqual(keys, ["wellknown:sources"]); + for (const t of ["session_v2", "session_message", "project"]) { + assert.equal(count(shadowDb, t), 0, `${t} must be emptied`); + } + assert.deepEqual(tableNames(shadowDb), tableNames(userDb), "no table may be dropped"); +}); + +test("home on a resumed turn leaves the existing shadow alone", async () => { + const db = new DatabaseSync(shadowDb); + db.exec("INSERT INTO project VALUES ('p', '/tmp'); INSERT INTO session_v2 VALUES ('ses_marker', 'p', '/tmp')"); + db.close(); + const home = await opencodePlugin.home(sessionDir); + assert.equal(count(shadowDb, "session_v2"), 1); + assert.equal(query(shadowDb, "SELECT id FROM session_v2")[0]?.["id"], "ses_marker"); + assert.match(home.note, /existing shadow reused/); +}); + +test("the user's DB is untouched", () => { + assert.deepEqual(userCounts(), userBefore); +}); + +async function authWith(dataHome: string): Promise<{ ok: boolean; detail: string }> { + process.env["XDG_DATA_HOME"] = dataHome; + try { + return await opencodePlugin.auth(); + } finally { + process.env["XDG_DATA_HOME"] = userData; + } +} + +test("auth without opencode.db points at opencode auth login", async () => { + const empty = mkdtempSync(path.join(scratch, "empty-")); + const res = await authWith(empty); + assert.equal(res.ok, false); + assert.match(res.detail, /opencode auth login/); +}); + +test("auth with an empty credential table points at opencode auth login", async () => { + const dir = mkdtempSync(path.join(scratch, "nocreds-")); + mkdirSync(path.join(dir, "opencode")); + const db = new DatabaseSync(path.join(dir, "opencode", "opencode.db")); + db.exec("CREATE TABLE credential (id TEXT PRIMARY KEY, integration_id TEXT, value TEXT)"); + db.close(); + const res = await authWith(dir); + assert.equal(res.ok, false); + assert.match(res.detail, /opencode auth login/); +}); + +test("auth on a DB without a credential table says it cannot read credentials", async () => { + const dir = mkdtempSync(path.join(scratch, "nocredtable-")); + mkdirSync(path.join(dir, "opencode")); + const db = new DatabaseSync(path.join(dir, "opencode", "opencode.db")); + db.exec("CREATE TABLE session (id TEXT PRIMARY KEY)"); + db.close(); + const res = await authWith(dir); + assert.equal(res.ok, false); + assert.match(res.detail, /^cannot read credentials/); +}); + +test("emptying a table never cascades into kept credentials", () => { + const dir = mkdtempSync(path.join(scratch, "cascade-")); + const src = path.join(dir, "user.db"); + const db = new DatabaseSync(src); + db.exec(` + CREATE TABLE kv (key TEXT PRIMARY KEY, value TEXT); + CREATE TABLE project (id TEXT PRIMARY KEY); + CREATE TABLE credential (id TEXT PRIMARY KEY, integration_id TEXT, value TEXT, + project_id TEXT REFERENCES project(id) ON DELETE CASCADE); + INSERT INTO project VALUES ('p1'); + INSERT INTO credential VALUES ('c1', 'opencode', '{"type":"key","key":"k"}', 'p1'), ('c2', 'zai-coding-plan', '{"type":"key","key":"k"}', 'p1'); + `); + db.close(); + const out = path.join(dir, "shadow", "opencode.db"); + snapshotCredentials(src, out); + assert.equal(count(out, "credential"), 2); + assert.equal(count(out, "project"), 0); +}); + +test("a failed snapshot leaves no shadow behind", () => { + const dir = mkdtempSync(path.join(scratch, "failed-")); + const src = path.join(dir, "user.db"); + writeFileSync(src, "not a database"); + const out = path.join(dir, "shadow", "opencode.db"); + assert.throws(() => snapshotCredentials(src, out)); + assert.equal(existsSync(out), false); + assert.equal(existsSync(`${out}.tmp`), false); +}); From 4fc6da69f4996ddd1d7c546f6dacb13586f9399f Mon Sep 17 00:00:00 2001 From: Egor Shatalov Date: Thu, 1 Oct 2026 01:08:22 +0300 Subject: [PATCH 2/6] chore: current codex model ids in docs and the live test Codex no longer serves gpt-5.3-codex-spark or the gpt-5.6 pair to ChatGPT accounts; the routing template, the tool description example and the live test's cheap bundle now name gpt-6.1-sol and gpt-6-luna. Claude Fable 5.1 in Claude Code. Co-Authored-By: Claude Fable 5.1 --- CLAUDE.local.template.md | 2 +- src/faces/interface.ts | 2 +- test/live.test.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CLAUDE.local.template.md b/CLAUDE.local.template.md index e2dc09b..c9b7c14 100644 --- a/CLAUDE.local.template.md +++ b/CLAUDE.local.template.md @@ -9,7 +9,7 @@ Spawn with a harness (`codex`, `claude`, `grok`, `opencode`), a full model id an ## Routing -`sol` = codex `gpt-5.6-sol`, `luna` = codex `gpt-5.6-luna`, `glm` = opencode `zai-coding-plan/glm-5.3`. `/` = any of these, `+` = both, findings merged. For `fable`, `opus`, `sonnet` and `haiku` don't use MCP, use native subagents instead +`sol` = codex `gpt-6.1-sol`, `luna` = codex `gpt-6-luna`, `glm` = opencode `zai-coding-plan/glm-5.3`. `/` = any of these, `+` = both, findings merged. For `fable`, `opus`, `sonnet` and `haiku` don't use MCP, use native subagents instead | Task | Default | When the default falls short | |---|---|---| diff --git a/src/faces/interface.ts b/src/faces/interface.ts index 26970eb..1e97d61 100644 --- a/src/faces/interface.ts +++ b/src/faces/interface.ts @@ -77,7 +77,7 @@ const specs: VerbSpec[] = [ type: "object", properties: { harness: str(`One of ${harnessList()}.`), - model: str("Model id as the harness names it, e.g. gpt-5.6-sol, zai-coding-plan/glm-5.3, grok-4.6."), + model: str("Model id as the harness names it, e.g. gpt-6.1-sol, zai-coding-plan/glm-5.3, grok-4.6."), effort: str("Reasoning effort as the harness names it, e.g. low, medium, high."), prompt: str("What you want done."), cwd: str("Absolute directory the subagent works in. It can write anything there."), diff --git a/test/live.test.ts b/test/live.test.ts index b44f660..c636eb1 100644 --- a/test/live.test.ts +++ b/test/live.test.ts @@ -23,7 +23,7 @@ const harness = process.env["SUBTURN_LIVE_HARNESS"] ?? "opencode"; const cheapBundles: Record = { claude: { model: "claude-haiku-4-5-20251001", effort: "low" }, - codex: { model: "gpt-5.3-codex-spark", effort: "low" }, + codex: { model: "gpt-6-luna", effort: "low" }, grok: { model: "grok-4.6", effort: "low" }, opencode: { model: "zai-coding-plan/glm-5.3-flash", effort: "low" }, }; From 2a3fe4426927053b9973053d0e0e01358848eec1 Mon Sep 17 00:00:00 2001 From: Egor Shatalov Date: Thu, 1 Oct 2026 01:08:22 +0300 Subject: [PATCH 3/6] chore(plugins): comments state the quirk, not when it was seen Dates and anecdotes in the grok, codex and claude plugin comments are replaced by the fact they were recording. Claude Fable 5.1 in Claude Code. Co-Authored-By: Claude Fable 5.1 --- src/plugins/claude.ts | 2 +- src/plugins/codex.ts | 7 +++---- src/plugins/grok.ts | 7 +++---- 3 files changed, 7 insertions(+), 9 deletions(-) diff --git a/src/plugins/claude.ts b/src/plugins/claude.ts index 5306af5..e2c89a6 100644 --- a/src/plugins/claude.ts +++ b/src/plugins/claude.ts @@ -8,7 +8,7 @@ // Posture: `--dangerously-skip-permissions` — claude's validated bypass // mode; no permission prompt can fire in print mode with it. // -// Hygiene by parking, NOT a shadow home (proven by live smoke 2026-09-01): +// Hygiene by parking, NOT a shadow home: // claude's keychain credentials are per-config-dir — the service name is // "Claude Code-credentials-<8-hex hash of the dir>" — so any fresh // CLAUDE_CONFIG_DIR shadow starts logged out, and the owner refuses extra diff --git a/src/plugins/codex.ts b/src/plugins/codex.ts index ee33c13..5af37c5 100644 --- a/src/plugins/codex.ts +++ b/src/plugins/codex.ts @@ -9,7 +9,7 @@ // validated non-interactive full-access mode; no approval prompt exists in // exec mode with it. `--skip-git-repo-check` keeps non-repo cwds working. // stdin carries the prompt and is closed immediately (codex hangs on an -// open stdin — recorded harness homework). +// open stdin). // // Shadow home: CODEX_HOME relocates the whole home; the user's real // ~/.codex/auth.json is symlinked back in (auth.json is the one @@ -128,9 +128,8 @@ export const codexPlugin: Plugin = { // Resume: `codex exec resume ` continues the stored rollout in this // session's CODEX_HOME shadow — non-forking, same conversation. Model // and effort are re-applied explicitly (never server defaults). The - // resume subcommand takes the same flags EXCEPT --color (validated live - // 2026-09-01: `--color` is rejected there), so --color rides only on - // the fresh-exec argv. + // resume subcommand takes the same flags EXCEPT --color (it rejects it), + // so --color rides only on the fresh-exec argv. const argv = ctx.nativeSessionId !== undefined ? [ctx.binPath, "exec", "resume", ...bundleFlags, ctx.nativeSessionId, "-"] : [ctx.binPath, "exec", "--color", "never", ...bundleFlags, "-"]; // prompt from stdin diff --git a/src/plugins/grok.ts b/src/plugins/grok.ts index 659c963..b00328e 100644 --- a/src/plugins/grok.ts +++ b/src/plugins/grok.ts @@ -11,7 +11,7 @@ // all tool executions), plus Subturn's ACP client's allow-everything // permission handler as a backstop. // -// Past-ACP quirk (observed live): grok can complete a +// Quirk: grok can complete a // prompt via the private `_x.ai/session/prompt_complete` notification // without ever answering the standard session/prompt request. The turn // races both; the promptId rides in _meta.promptId/_meta.requestId. @@ -92,10 +92,9 @@ export const grokPlugin: Plugin = { ], grokCompletionRace: true, extNotifications: { - // Grok's private session channel (validated live 2026-09-02): + // Grok's private session channel: // - `model_changed` fires when the server re-selects the model - // AFTER session/new (a launch campaign flipped grok-4.5 to - // grok-4.6 despite `-m`); the ack must follow. + // AFTER session/new, even against `-m`; the ack must follow. // - `turn_completed` carries the turn's usage (camelCase) and // `modelUsage` keyed by the model that actually served it. "_x.ai/session_notification": (params, sink) => { From 9b1d1a8159a7c48a35520ab623b29d7023482ccd Mon Sep 17 00:00:00 2001 From: Egor Shatalov Date: Sat, 3 Oct 2026 14:44:11 +0300 Subject: [PATCH 4/6] fix(opencode): models the server announces after the session opens can be selected OpenCode lists its models before its plugins have added theirs, so a spawn on an OpenCode Go model (or a provider from the user's config) was refused with "model not found" every time. The server announces the full list with config_option_update about a second later. When the model is refused with -32602, the ACP turn now sets it again after each config_option_update, for up to 5 s, and records each retry in the evidence. A model that never appears fails with the harness's own refusal, as before. Co-Authored-By: Claude Fable 5.1 --- src/core/acp-turn.ts | 42 +++++++++++++++++++++++++++++++++++++++-- src/plugins/fake.ts | 12 +++++++----- src/plugins/opencode.ts | 10 ++++++++-- test/core.test.ts | 31 ++++++++++++++++++++++++++++++ test/fake-agent.mjs | 18 ++++++++++++++++++ 5 files changed, 104 insertions(+), 9 deletions(-) diff --git a/src/core/acp-turn.ts b/src/core/acp-turn.ts index b350b1b..12321f8 100644 --- a/src/core/acp-turn.ts +++ b/src/core/acp-turn.ts @@ -20,6 +20,13 @@ import path from "node:path"; const INITIALIZE_TIMEOUT_MS = 30_000; const SESSION_NEW_TIMEOUT_MS = 60_000; const SESSION_LOAD_TIMEOUT_MS = 120_000; // replay of a long history takes time +const CONFIG_SETTLE_MS = 5_000; + +/** Runs `attempt`; when the harness refuses it with -32602, runs it again + * after each config_option_update, until none arrives within + * CONFIG_SETTLE_MS of the first try. For a harness whose option list is + * still loading when the session opens and that announces the rest. */ +export type RetryOnConfigUpdate = (attempt: () => Promise) => Promise; export interface AcpTurnPlan { argv: string[]; @@ -27,7 +34,11 @@ export interface AcpTurnPlan { * acknowledged-bundle record for ack.json, or null when the harness * echoes nothing. Throw to fail. Runs on resumed turns too — this is * where model+effort are re-applied explicitly. */ - configure?: (client: AcpClient, sessionId: string) => Promise | null>; + configure?: ( + client: AcpClient, + sessionId: string, + retryOnConfigUpdate: RetryOnConfigUpdate, + ) => Promise | null>; /** Extract the acknowledged bundle from the session/new response (grok: * models.currentModelId + reasoningEffort meta). */ ackFromSessionNew?: (result: Record) => Record | null; @@ -102,6 +113,8 @@ export async function runAcpTurn(ctx: LaunchContext, plan: AcpTurnPlan): Promise const usageCandidates: unknown[] = []; let activeSessionId = ""; let collecting = false; // off until the prompt goes out (replay isn't ours) + let configUpdates = 0; + let onConfigUpdate: (() => void) | null = null; const client = new AcpClient(spawned.child, { emit: (e) => ctx.emit(e), @@ -111,6 +124,10 @@ export async function runAcpTurn(ctx: LaunchContext, plan: AcpTurnPlan): Promise return; } ctx.emit({ type: collecting ? "session_update" : "session_update_replay", update }); + if (update["sessionUpdate"] === "config_option_update") { + configUpdates++; + onConfigUpdate?.(); + } if (!collecting) return; if (update["sessionUpdate"] === "agent_message_chunk") { const content = update["content"]; @@ -147,6 +164,27 @@ export async function runAcpTurn(ctx: LaunchContext, plan: AcpTurnPlan): Promise client.onExtNotification(method, (params) => handler(params, sink)); } + const nextConfigUpdate = (timeoutMs: number): Promise => + new Promise((resolve) => { + const timer = setTimeout(() => { onConfigUpdate = null; resolve(false); }, timeoutMs); + onConfigUpdate = () => { clearTimeout(timer); onConfigUpdate = null; resolve(true); }; + }); + const retryOnConfigUpdate: RetryOnConfigUpdate = async (attempt) => { + const deadline = Date.now() + CONFIG_SETTLE_MS; + for (;;) { + const seen = configUpdates; // an update landing mid-attempt counts + try { + return await attempt(); + } catch (e) { + if (!(e instanceof RpcError) || e.code !== -32602) throw e; + const left = deadline - Date.now(); + if (left <= 0) throw e; + if (configUpdates === seen && !(await nextConfigUpdate(left))) throw e; + ctx.emit({ type: "configure_retry", refused: e.message }); + } + } + }; + try { const initResult = await client.request("initialize", { protocolVersion: 1, @@ -190,7 +228,7 @@ export async function runAcpTurn(ctx: LaunchContext, plan: AcpTurnPlan): Promise ackBase = plan.ackFromSessionNew(sessionNewResult); } if (plan.configure !== undefined) { - const configureAck = await plan.configure(client, activeSessionId); + const configureAck = await plan.configure(client, activeSessionId, retryOnConfigUpdate); if (configureAck !== null) ackBase = { ...(ackBase ?? {}), ...configureAck }; } if (currentAck() !== null) { diff --git a/src/plugins/fake.ts b/src/plugins/fake.ts index 9eb6cc6..4b306c4 100644 --- a/src/plugins/fake.ts +++ b/src/plugins/fake.ts @@ -41,11 +41,13 @@ export const fakePlugin: Plugin = { } return runAcpTurn(ctx, { argv: [process.execPath, script], - configure: async (client, sessionId) => { - const modelRes = await client.request( - "session/set_config_option", - { sessionId, configId: "model", value: ctx.model }, - 15_000, + configure: async (client, sessionId, retryOnConfigUpdate) => { + const modelRes = await retryOnConfigUpdate(() => + client.request( + "session/set_config_option", + { sessionId, configId: "model", value: ctx.model }, + 15_000, + ), ); const effortRes = await client.request( "session/set_config_option", diff --git a/src/plugins/opencode.ts b/src/plugins/opencode.ts index c4e20d6..e66c397 100644 --- a/src/plugins/opencode.ts +++ b/src/plugins/opencode.ts @@ -7,6 +7,12 @@ // session/load, handled in acp-turn) runs the same configure step, so the // bundle is re-applied explicitly on every turn — never server defaults. // +// The server lists models before its plugins have added theirs (the +// OpenCode Console providers, providers from the user's config) and +// announces the rest with config_option_update about a second later. A +// model refused right after the session opens is therefore set again after +// each such update (retryOnConfigUpdate in acp-turn). +// // Posture: `opencode acp` has no --auto flag; the permissive posture is the // Subturn's ACP client itself, which answers every session/request_permission // with the most permissive option (core/acp.ts). No prompt can fire @@ -173,9 +179,9 @@ export const opencodePlugin: Plugin = { launch(ctx: LaunchContext): Promise { return runAcpTurn(ctx, { argv: [ctx.binPath, "acp"], - configure: async (client, sessionId) => { + configure: async (client, sessionId, retryOnConfigUpdate) => { // Model FIRST — the effort option appears only after the model set. - const modelRes = await setConfig(client, sessionId, "model", ctx.model); + const modelRes = await retryOnConfigUpdate(() => setConfig(client, sessionId, "model", ctx.model)); const effortRes = await setConfig(client, sessionId, "effort", ctx.effort); // The effort response is the later echo of the whole option list, so // it is the authoritative currentValue for both. diff --git a/test/core.test.ts b/test/core.test.ts index 9538119..f2f4806 100644 --- a/test/core.test.ts +++ b/test/core.test.ts @@ -194,6 +194,37 @@ test("posture: a permission request is auto-answered with the most permissive op } }); +test("a model the harness announces after the session opens is set once announced", async () => { + process.env["FAKE_MODE"] = "latemodel"; + try { + const res = await spawn(baseInput()); + const done = await awaitTurn(res.session_id, 30); + assert.equal(done.status, "completed"); + assert.deepEqual(done.bundle, { model: "fake-model-1", effort: "high" }); + const events = inspect(res.session_id).events.parsed as Array>; + assert.deepEqual( + events.filter((e) => e["type"] === "configure_retry").map((e) => e["refused"]), + ["model not found: fake-model-1"], + ); + } finally { + delete process.env["FAKE_MODE"]; + } +}); + +test("a model the harness never announces fails with the harness's refusal", async () => { + process.env["FAKE_MODE"] = "nomodel"; + try { + const res = await spawn(baseInput()); + const done = await awaitTurn(res.session_id, 30); + assert.equal(done.status, "failed"); + const evidence = inspect(res.session_id); + assert.ok(evidence.error.text?.includes("-32602")); + assert.ok(evidence.error.text?.includes("model not found: fake-model-1")); + } finally { + delete process.env["FAKE_MODE"]; + } +}); + test("configure failure after the id exists: failed turn with raw rpc evidence", async () => { process.env["FAKE_MODE"] = "badeffort"; try { diff --git a/test/fake-agent.mjs b/test/fake-agent.mjs index 66789ab..8430f19 100644 --- a/test/fake-agent.mjs +++ b/test/fake-agent.mjs @@ -4,6 +4,9 @@ // permission — asks for permission mid-prompt; completes only when allowed // hang — accepts the prompt request and never answers (deadline test) // badeffort — refuses the "effort" set_config with -32602 +// latemodel — refuses the "model" set_config with -32602 until it has +// announced its models with a config_option_update +// nomodel — refuses the "model" set_config with -32602, announces nothing // grok — never answers the prompt request; completes via the private // _x.ai/session/prompt_complete notification (race test) // die — exits immediately (launch-failure-before-session-id test) @@ -24,6 +27,7 @@ if (mode === "die") { let buf = ""; const config = { model: null, effort: null }; let loadedSessionId = null; +let modelsAnnounced = false; let pendingPermissionId = null; let pendingPromptId = null; let promptSessionId = null; @@ -90,6 +94,20 @@ function handle(msg) { send({ jsonrpc: "2.0", id, error: { code: -32602, message: `invalid effort: ${params.value}` } }); return; } + if ((mode === "latemodel" || mode === "nomodel") && params.configId === "model" && !modelsAnnounced) { + send({ jsonrpc: "2.0", id, error: { code: -32602, message: `model not found: ${params.value}` } }); + if (mode === "latemodel") { + setTimeout(() => { + modelsAnnounced = true; + send({ + jsonrpc: "2.0", + method: "session/update", + params: { sessionId: params.sessionId, update: { sessionUpdate: "config_option_update", configOptions: [] } }, + }); + }, 50); + } + return; + } config[params.configId] = params.value; result(id, { configId: params.configId, currentValue: params.value }); return; From 5c1cc72ab733aae30fa569ac1fa47a2222eea85a Mon Sep 17 00:00:00 2001 From: Egor Shatalov Date: Sat, 3 Oct 2026 16:46:14 +0300 Subject: [PATCH 5/6] chore: reflow two comments Co-Authored-By: Claude Fable 5.1 --- src/core/acp-turn.ts | 6 +++--- src/plugins/grok.ts | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/core/acp-turn.ts b/src/core/acp-turn.ts index 12321f8..58479af 100644 --- a/src/core/acp-turn.ts +++ b/src/core/acp-turn.ts @@ -23,9 +23,9 @@ const SESSION_LOAD_TIMEOUT_MS = 120_000; // replay of a long history takes time const CONFIG_SETTLE_MS = 5_000; /** Runs `attempt`; when the harness refuses it with -32602, runs it again - * after each config_option_update, until none arrives within - * CONFIG_SETTLE_MS of the first try. For a harness whose option list is - * still loading when the session opens and that announces the rest. */ + * after each config_option_update, giving up CONFIG_SETTLE_MS after the + * first try. For a harness that opens a session before its option list has + * loaded and announces the rest. */ export type RetryOnConfigUpdate = (attempt: () => Promise) => Promise; export interface AcpTurnPlan { diff --git a/src/plugins/grok.ts b/src/plugins/grok.ts index b00328e..a74a8d0 100644 --- a/src/plugins/grok.ts +++ b/src/plugins/grok.ts @@ -11,10 +11,10 @@ // all tool executions), plus Subturn's ACP client's allow-everything // permission handler as a backstop. // -// Quirk: grok can complete a -// prompt via the private `_x.ai/session/prompt_complete` notification -// without ever answering the standard session/prompt request. The turn -// races both; the promptId rides in _meta.promptId/_meta.requestId. +// Quirk: grok can complete a prompt via the private +// `_x.ai/session/prompt_complete` notification without ever answering the +// standard session/prompt request. The turn races both; the promptId rides +// in _meta.promptId/_meta.requestId. // // Shadow home: GROK_HOME relocates the whole home (sessions land under // $GROK_HOME/sessions); the user's real ~/.grok/auth.json is symlinked in. From 48d63911d71cd913677b958f02ea5d243840eaa7 Mon Sep 17 00:00:00 2001 From: Egor Shatalov Date: Sat, 3 Oct 2026 16:54:56 +0300 Subject: [PATCH 6/6] fix(opencode): a user's OPENCODE_DB cannot lead the subagent to their database OpenCode takes its database path from OPENCODE_DB when it is set. The shadow only changed XDG_DATA_HOME, so with that variable in the user's environment the subagent's session landed in the user's own database, and the login check and the snapshot looked at the default file instead. The login check and the snapshot now read the file OPENCODE_DB names, and the child gets OPENCODE_DB set to the shadow database. Co-Authored-By: Claude Fable 5.1 --- src/plugins/opencode.ts | 15 ++++++++++----- test/opencode.test.ts | 24 ++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 5 deletions(-) diff --git a/src/plugins/opencode.ts b/src/plugins/opencode.ts index e66c397..44395c4 100644 --- a/src/plugins/opencode.ts +++ b/src/plugins/opencode.ts @@ -21,7 +21,9 @@ // Shadow home: `opencode acp` runs its own `opencode serve --stdio` child, // never the user's background service, and that server keeps sessions and // credentials (table `credential`) in one SQLite file, -// $XDG_DATA_HOME/opencode/opencode.db. The shadow is a snapshot of the +// $XDG_DATA_HOME/opencode/opencode.db, or wherever OPENCODE_DB points. The +// child gets both variables, so a user's OPENCODE_DB cannot lead it back to +// the user's file. The shadow is a snapshot of the // user's file: `VACUUM INTO` from a read-only connection (consistent while // the user's service writes), then every table outside KEEP_TABLES emptied // and the models.dev catalog cache dropped from kv (the binary bundles @@ -62,7 +64,9 @@ function realDataDir(): string { } function realDbPath(): string { - return path.join(realDataDir(), "opencode.db"); + // OpenCode resolves OPENCODE_DB against its data dir. + const override = process.env["OPENCODE_DB"]; + return path.resolve(realDataDir(), override !== undefined && override !== "" ? override : "opencode.db"); } /** Copy the user's opencode.db to `shadowDb` keeping only the login (see @@ -153,8 +157,9 @@ export const opencodePlugin: Plugin = { // a background service that outlives us. const tmp = mkdtempSync(path.join(tmpdir(), "subturn-opencode-models-")); try { - snapshotCredentials(realDbPath(), path.join(tmp, "opencode", "opencode.db")); - return await probeAcpModels([binPath, "acp"], { XDG_DATA_HOME: tmp }); + const shadowDb = path.join(tmp, "opencode", "opencode.db"); + snapshotCredentials(realDbPath(), shadowDb); + return await probeAcpModels([binPath, "acp"], { XDG_DATA_HOME: tmp, OPENCODE_DB: shadowDb }); } catch { return null; } finally { @@ -169,7 +174,7 @@ export const opencodePlugin: Plugin = { const fresh = !existsSync(shadowDb); if (fresh) snapshotCredentials(realDbPath(), shadowDb); return Promise.resolve({ - env: { XDG_DATA_HOME: shadowData, OPENCODE_PRINT_LOGS: "1" }, + env: { XDG_DATA_HOME: shadowData, OPENCODE_DB: shadowDb, OPENCODE_PRINT_LOGS: "1" }, note: fresh ? `XDG_DATA_HOME=${shadowData}; credentials snapshotted from ${realDbPath()}, session tables emptied` : `XDG_DATA_HOME=${shadowData}; existing shadow reused (resumed turn)`, diff --git a/test/opencode.test.ts b/test/opencode.test.ts index ae12dd6..903c285 100644 --- a/test/opencode.test.ts +++ b/test/opencode.test.ts @@ -92,6 +92,7 @@ test("home snapshots credentials into a private DB with session tables emptied", } assert.ok(existsSync(shadowDb)); assert.equal(home.env["XDG_DATA_HOME"], shadowData); + assert.equal(home.env["OPENCODE_DB"], shadowDb); assert.equal(home.env["OPENCODE_PRINT_LOGS"], "1"); const creds = "SELECT id, integration_id FROM credential ORDER BY id"; @@ -133,6 +134,29 @@ async function authWith(dataHome: string): Promise<{ ok: boolean; detail: string } } +test("OPENCODE_DB names the user's DB and never reaches the child", async () => { + const elsewhere = mkdtempSync(path.join(scratch, "override-")); + const moved = path.join(elsewhere, "mine.db"); + const src = new DatabaseSync(userDb, { readOnly: true }); + src.prepare("VACUUM INTO ?").run(moved); + src.close(); + const session = mkdtempSync(path.join(scratch, "override-session-")); + process.env["XDG_DATA_HOME"] = mkdtempSync(path.join(scratch, "override-empty-")); + process.env["OPENCODE_DB"] = moved; + try { + const res = await opencodePlugin.auth(); + assert.equal(res.ok, true, res.detail); + const home = await opencodePlugin.home(session); + const shadow = path.join(session, "home", "opencode-data", "opencode", "opencode.db"); + assert.equal(home.env["OPENCODE_DB"], shadow); + assert.equal(count(shadow, "credential"), 2); + assert.equal(count(shadow, "session_v2"), 0); + } finally { + delete process.env["OPENCODE_DB"]; + process.env["XDG_DATA_HOME"] = userData; + } +}); + test("auth without opencode.db points at opencode auth login", async () => { const empty = mkdtempSync(path.join(scratch, "empty-")); const res = await authWith(empty);