From 5a5dbd65fe767717121b80227c08763f991e37f2 Mon Sep 17 00:00:00 2001 From: Kristof Lemmens Date: Wed, 4 Nov 2026 11:40:34 +0100 Subject: [PATCH] fix: keep the Auto route across plugin reloads opencode reloads plugins on every config change and recycles idle instances. That dropped every pinned route, so the next turn routed again on whatever was typed last and could switch the model mid-conversation, losing its prompt cache. Routes are now kept per session and auto, with their session token, in routes.json next to the plugin log (mode 0600, written atomically) until the token expires. A restored route the auto can no longer send is routed again, and a compaction marks restored routes for re-routing too. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 ++ src/core.ts | 151 +++++++++++++++++++++++++++++++++++++++++++++--- src/v1.ts | 42 ++++---------- src/v2.ts | 41 ++++--------- test/setup.ts | 13 ++++- test/v1.test.ts | 48 ++++++++++++++- test/v2.test.ts | 87 +++++++++++++++++++++++++++- 7 files changed, 310 insertions(+), 76 deletions(-) diff --git a/README.md b/README.md index a206bfc..b823dc9 100644 --- a/README.md +++ b/README.md @@ -99,6 +99,10 @@ POST https://api.githubcopilot.com/auto model and mints a 24-hour session token. The conversation stays on that model, so its prompt cache stays warm; every request carries `Copilot-Session-Token`, which bills it as Auto (10% discount on paid plans). +- **Across reloads.** opencode reloads plugins when the config changes and recycles idle + instances. The route survives that: it is kept, with its session token, in + `routes.json` next to the plugin log (owner-only), until the token expires. A restored + route the auto can no longer send (another anchor or catalog) is routed again. - **Routing again** happens, as in VS Code, on the next turn after compaction, when the token is within 5 minutes of expiring, when a turn attaches an image the model cannot read, and when you switch tier. diff --git a/src/core.ts b/src/core.ts index 300134e..f7219bc 100644 --- a/src/core.ts +++ b/src/core.ts @@ -2,7 +2,7 @@ // call, which autos to inject and which server pick an auto can actually send. // Mirrors VS Code's Copilot Auto (extensions/copilot/src/platform/endpoint in // microsoft/vscode: automodeService.ts, autoV2Fetcher.ts, autoModeTiers.ts). -import { appendFile, mkdir } from "node:fs/promises" +import { appendFile, mkdir, readFile, rename, rm, writeFile } from "node:fs/promises" import { homedir } from "node:os" import path from "node:path" @@ -93,18 +93,20 @@ export type Route = { expiresAtMs: number } +// --- state directory -------------------------------------------------------------------- +// ~/.local/state/opencode-copilot-auto (or $XDG_STATE_HOME, %LOCALAPPDATA% on Windows): +// the log and the persisted routes. Resolved per call, so tests can move it. +function stateDir() { + if (process.platform === "win32") + return path.join(process.env.LOCALAPPDATA ?? path.join(homedir(), "AppData", "Local"), PLUGIN_ID) + return path.join(process.env.XDG_STATE_HOME ?? path.join(homedir(), ".local", "state"), PLUGIN_ID) +} + // --- logging ---------------------------------------------------------------------------- // File logger — keeps the TUI clean. // Tail ~/.local/state/opencode-copilot-auto/plugin.log to observe. function logFile() { - if (process.platform === "win32") - return path.join( - process.env.LOCALAPPDATA ?? path.join(homedir(), "AppData", "Local"), - PLUGIN_ID, - "plugin.log", - ) - const xdg = process.env.XDG_STATE_HOME - return path.join(xdg ?? path.join(homedir(), ".local", "state"), PLUGIN_ID, "plugin.log") + return path.join(stateDir(), "plugin.log") } let logReady: Promise | undefined @@ -278,3 +280,134 @@ export async function fetchAutoDecision( clearTimeout(timer) } } + +// --- conversations ---------------------------------------------------------------------- +// Everything tracked per opencode session and auto: the pinned route plus the inputs +// for the next routing round. +export type ConvState = { + route?: Route + routing?: Promise + needsReEval?: boolean + // The prompt a routing round last failed for (no Auto session); the next attempt + // waits for the next user prompt instead of stalling every tool step. + failedFor?: object +} + +// What survives a reload: the route (with its session token, so the conversation +// stays billed against its Auto session) and a pending re-evaluation. +type StoredConv = Route & { needsReEval?: boolean } +type StoredSessions = Record> + +// opencode reloads plugins whenever the config changes and recycles idle instances, +// which used to drop every pinned route: the next turn routed again on whatever the +// user typed last and could switch the model mid-conversation, losing its prompt +// cache. VS Code keeps the route per conversation; so do we, across reloads, in +// routes.json next to the log. Entries live as long as their session token (24h). +function routesFile() { + return path.join(stateDir(), "routes.json") +} + +function durable(route: Route | undefined, now = Date.now()): route is Route { + return !!route && route.expiresAtMs > now +} + +async function readRoutes(file: string): Promise { + try { + const data = JSON.parse(await readFile(file, "utf8")) as { sessions?: unknown } + return data.sessions && typeof data.sessions === "object" ? (data.sessions as StoredSessions) : {} + } catch { + return {} + } +} + +// Writes from this process run one at a time; each re-reads the file, so instances +// for other directories (or other opencode processes) keep their entries. +let routeWrites: Promise = Promise.resolve() + +function writeRoute(sessionID: string, autoID: string, entry: StoredConv | undefined): Promise { + const file = routesFile() + const write = async () => { + const sessions = await readRoutes(file) + const now = Date.now() + if (entry) (sessions[sessionID] ??= {})[autoID] = entry + else if (sessions[sessionID]) delete sessions[sessionID][autoID] + for (const [id, autos] of Object.entries(sessions)) { + for (const [auto, stored] of Object.entries(autos)) if (!durable(stored, now)) delete autos[auto] + if (!Object.keys(autos).length) delete sessions[id] + } + await mkdir(path.dirname(file), { recursive: true }) + // Holds session tokens: owner-only, replaced atomically. + const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp` + try { + await writeFile(tmp, JSON.stringify({ version: 1, sessions }), { mode: 0o600 }) + await rename(tmp, file) + } catch (error) { + await rm(tmp, { force: true }).catch(() => undefined) + throw error + } + } + routeWrites = routeWrites.then(write).catch((error) => log(`route store write failed: ${String(error)}`)) + return routeWrites +} + +export class Conversations { + private live = new Map>() + private stored: StoredSessions = {} + + // Reads the routes persisted by earlier instances. Never throws. + async load() { + this.stored = await readRoutes(routesFile()) + } + + // The conversation of `auto` in a session. A route persisted before a reload comes + // back while its token is valid and the auto can still send its model (the anchor + // or catalog may have changed since). + get(sessionID: string, auto: AutoSpec, catalog: CatalogModel[]): ConvState { + let sessionAutos = this.live.get(sessionID) + if (!sessionAutos) { + sessionAutos = new Map() + this.live.set(sessionID, sessionAutos) + } + let conv = sessionAutos.get(auto.id) + if (conv) return conv + conv = {} + const stored = this.stored[sessionID]?.[auto.id] + if (stored) { + delete this.stored[sessionID][auto.id] + const { needsReEval, ...route } = stored + if (durable(route) && servable(auto, route.modelID, catalog)) { + conv.route = route + conv.needsReEval = needsReEval + log(`${auto.id}: restored ${route.modelID} for ${sessionID}`) + } + } + sessionAutos.set(auto.id, conv) + return conv + } + + // Persists a conversation after a routing round or an invalidation. + save(sessionID: string, autoID: string, conv: ConvState): Promise { + const route = conv.route + return writeRoute( + sessionID, + autoID, + durable(route) ? { ...route, ...(conv.needsReEval ? { needsReEval: true } : {}) } : undefined, + ) + } + + // Marks every auto of a session for re-routing on its next agent turn, including + // routes restored from disk but not used yet. Returns whether there was any. + async invalidate(sessionID: string): Promise { + const writes: Promise[] = [] + for (const [autoID, conv] of this.live.get(sessionID) ?? []) { + conv.needsReEval = true + writes.push(this.save(sessionID, autoID, conv)) + } + for (const [autoID, stored] of Object.entries(this.stored[sessionID] ?? {})) { + stored.needsReEval = true + writes.push(writeRoute(sessionID, autoID, stored)) + } + await Promise.all(writes) + return writes.length > 0 + } +} diff --git a/src/v1.ts b/src/v1.ts index ae68441..b7a45de 100644 --- a/src/v1.ts +++ b/src/v1.ts @@ -6,6 +6,7 @@ import type { Model } from "@opencode-ai/sdk/v2" import { type AutoSpec, type CatalogModel, + Conversations, type Options, PLUGIN_ID, PROVIDER_ID, @@ -18,17 +19,6 @@ import { routeUsable, } from "./core" -// Everything tracked per opencode session and auto: the pinned route plus whether the -// next agent turn has to route again. -type ConvState = { - route?: Route - routing?: Promise - needsReEval?: boolean - // The prompt a routing round last failed for (no Auto session); the next attempt - // waits for the next user prompt instead of stalling every tool step. - failedFor?: object -} - // opencode's github-copilot provider sends GPT-5+ (except gpt-5-mini) over the // Responses API and everything else over Chat Completions; Claude goes through the // Anthropic SDK. @@ -107,23 +97,12 @@ export const server: Plugin = async ({ client }, options) => { let catalog: CatalogModel[] = [] let autos = new Map() const prompts = new Map() - const conversations = new Map>() + const conversations = new Conversations() + await conversations.load() const modelByAPIID = (apiID: string) => models.find((m) => m.api.id === apiID) - function getConv(sessionID: string, autoID: string): ConvState { - let sessionAutos = conversations.get(sessionID) - if (!sessionAutos) { - sessionAutos = new Map() - conversations.set(sessionID, sessionAutos) - } - let conv = sessionAutos.get(autoID) - if (!conv) { - conv = {} - sessionAutos.set(autoID, conv) - } - return conv - } + const getConv = (sessionID: string, auto: AutoSpec) => conversations.get(sessionID, auto, catalog) // One routing round through POST /auto. async function resolveRoute(sessionID: string, auto: AutoSpec, hasImage: boolean): Promise { @@ -135,7 +114,7 @@ export const server: Plugin = async ({ client }, options) => { : undefined // As VS Code: when routing fails, keep the last route while it can still serve // the turn, and route again on the next one. - const previous = getConv(sessionID, auto.id).route + const previous = getConv(sessionID, auto).route if (!session && previous?.sessionToken && routeUsable(previous, catalog, hasImage)) { log(`${auto.id}: routing failed, keeping ${previous.modelID} for ${sessionID}`) return previous @@ -160,10 +139,8 @@ export const server: Plugin = async ({ client }, options) => { // turn (mirrors VS Code's invalidateRouterCache). event: async ({ event }) => { if (event.type !== "session.compacted") return - const sessionAutos = conversations.get(event.properties.sessionID) - if (!sessionAutos?.size) return - for (const conv of sessionAutos.values()) conv.needsReEval = true - log(`route invalidated by compaction for ${event.properties.sessionID}`) + const sessionID = event.properties.sessionID + if (await conversations.invalidate(sessionID)) log(`route invalidated by compaction for ${sessionID}`) }, // Capture what the user typed; only POST /auto sees it. Synthetic parts (file // contents, reminders) are opencode's additions, not the user's prompt. @@ -181,7 +158,7 @@ export const server: Plugin = async ({ client }, options) => { if (incoming.model.providerID !== PROVIDER_ID) return const auto = autos.get(incoming.model.id) if (!auto) return - const conv = getConv(incoming.sessionID, auto.id) + const conv = getConv(incoming.sessionID, auto) // Route once per conversation and stick with it so the model — and its prompt // KV cache — stays stable, as VS Code does. Route again after compaction, when // the token is about to expire, when the turn attaches an image the model @@ -204,6 +181,7 @@ export const server: Plugin = async ({ client }, options) => { if (next !== route) conv.needsReEval = false conv.failedFor = next.sessionToken && next !== route ? undefined : prompt conv.route = next + await conversations.save(incoming.sessionID, auto.id, conv) } // The model itself is swapped in by the fetch wrapper (see chat.headers). @@ -221,7 +199,7 @@ export const server: Plugin = async ({ client }, options) => { if (incoming.model.providerID !== PROVIDER_ID) return const auto = autos.get(incoming.model.id) if (!auto) return - const route = getConv(incoming.sessionID, auto.id).route + const route = getConv(incoming.sessionID, auto).route if (!route) return output.headers[ROUTE_HEADER] = route.modelID if (route.sessionToken) output.headers["Copilot-Session-Token"] = route.sessionToken diff --git a/src/v2.ts b/src/v2.ts index 3157adb..28b8570 100644 --- a/src/v2.ts +++ b/src/v2.ts @@ -5,6 +5,7 @@ import { type AutoSpec, type CatalogModel, type ConvKind, + Conversations, DEFAULT_BASE_URL, type Options, PROVIDER_ID, @@ -32,17 +33,6 @@ type CopilotModel = { capabilities?: { input?: readonly string[] } } -// Everything tracked per opencode session and auto: the pinned route plus the -// inputs for the next routing round. -type ConvState = { - route?: Route - routing?: Promise - needsReEval?: boolean - // The prompt a routing round last failed for (no Auto session); the next attempt - // waits for the next user prompt instead of stalling every tool step. - failedFor?: object -} - // opencode's Copilot provider sends GPT-5+ (except gpt-5-mini), Grok and MAI Code // over the Responses API and the rest over Chat Completions, unless the live model // list advertised an endpoint (settings.endpoint). @@ -104,21 +94,10 @@ export const setup: Plugin.Plugin["setup"] = async (ctx) => { let autos = new Map() let injectedSignature = "" const prompts = new Map() - const conversations = new Map>() + const conversations = new Conversations() + await conversations.load() - function getConv(sessionID: string, autoID: string): ConvState { - let sessionAutos = conversations.get(sessionID) - if (!sessionAutos) { - sessionAutos = new Map() - conversations.set(sessionID, sessionAutos) - } - let conv = sessionAutos.get(autoID) - if (!conv) { - conv = {} - sessionAutos.set(autoID, conv) - } - return conv - } + const getConv = (sessionID: string, auto: AutoSpec) => conversations.get(sessionID, auto, catalog) // One routing round through POST /auto. async function resolveRoute(sessionID: string, auto: AutoSpec, hasImage: boolean): Promise { @@ -130,7 +109,7 @@ export const setup: Plugin.Plugin["setup"] = async (ctx) => { : undefined // As VS Code: when routing fails, keep the last route while it can still serve // the turn, and route again on the next one. - const previous = getConv(sessionID, auto.id).route + const previous = getConv(sessionID, auto).route if (!session && previous?.sessionToken && routeUsable(previous, catalog, hasImage)) { log(`${auto.id}: routing failed, keeping ${previous.modelID} for ${sessionID}`) return previous @@ -146,7 +125,7 @@ export const setup: Plugin.Plugin["setup"] = async (ctx) => { // compaction, when the token is about to expire, when the turn attaches an image // the model cannot read, or after a failed round. async function ensureRoute(sessionID: string, auto: AutoSpec, kind: ConvKind): Promise { - const conv = getConv(sessionID, auto.id) + const conv = getConv(sessionID, auto) const prompt = prompts.get(sessionID) const hasImage = kind === "primary" && !!prompt?.hasImage const route = conv.route @@ -163,6 +142,7 @@ export const setup: Plugin.Plugin["setup"] = async (ctx) => { if (next !== route && kind === "primary") conv.needsReEval = false conv.failedFor = next.sessionToken && next !== route ? undefined : prompt conv.route = next + await conversations.save(sessionID, auto.id, conv) return next } @@ -209,10 +189,9 @@ export const setup: Plugin.Plugin["setup"] = async (ctx) => { // keeps the current route. await ctx.session.hook( "compaction", - (event) => { + async (event) => { if (!autos.has(event.model.id)) return - for (const conv of conversations.get(event.sessionID)?.values() ?? []) conv.needsReEval = true - log(`route invalidated by compaction for ${event.sessionID}`) + if (await conversations.invalidate(event.sessionID)) log(`route invalidated by compaction for ${event.sessionID}`) }, { providerID: PROVIDER_ID }, ) @@ -236,7 +215,7 @@ export const setup: Plugin.Plugin["setup"] = async (ctx) => { async (event) => { const auto = autos.get(event.model.id) if (!auto) return - const modelID = conversations.get(event.sessionID)?.get(auto.id)?.route?.modelID + const modelID = getConv(event.sessionID, auto).route?.modelID if (!modelID) return const text = await event.request.clone().text().catch(() => "") let body: Record diff --git a/test/setup.ts b/test/setup.ts index 3064221..c1a6246 100644 --- a/test/setup.ts +++ b/test/setup.ts @@ -1,6 +1,15 @@ -// Keep test runs out of the real plugin log (~/.local/state/opencode-copilot-auto). +// Keep test runs out of the real plugin state (~/.local/state/opencode-copilot-auto): +// the log and the persisted routes. import { mkdtempSync } from "node:fs" import { tmpdir } from "node:os" import path from "node:path" -process.env.XDG_STATE_HOME = mkdtempSync(path.join(tmpdir(), "opencode-copilot-auto-test-")) +// Points the plugin at an empty state directory, so no test sees routes another one +// persisted. Returns it, for tests that reload the plugin on the same state. +export function freshStateDir(): string { + const dir = mkdtempSync(path.join(tmpdir(), "opencode-copilot-auto-test-")) + process.env.XDG_STATE_HOME = dir + return dir +} + +freshStateDir() diff --git a/test/v1.test.ts b/test/v1.test.ts index 445d35d..546f57a 100644 --- a/test/v1.test.ts +++ b/test/v1.test.ts @@ -1,6 +1,7 @@ // opencode 1 adapter (`server`), against opencode 1's provider and chat hooks. import { describe, expect, test } from "bun:test" import plugin from "../src/index" +import { freshStateDir } from "./setup" const makeModel = (id: string, apiId: string, npm: string, url: string, name: string, reasoning = false, temperature = true) => ({ id, @@ -71,7 +72,10 @@ const autoPicks = (id: string, ttlSeconds = 86_400) => () => ({ selected_model: { id }, }) -async function setup(models: Record, options: Record = {}, ctx: object = oauth) { +// `stateDir` reuses the state of an earlier setup, as a plugin reload would. +async function setup(models: Record, options: Record = {}, ctx: object = oauth, stateDir?: string) { + if (stateDir) process.env.XDG_STATE_HOME = stateDir + else freshStateDir() const hooks = await plugin.server({ client: { tui: { showToast: async () => {} } } } as never, options) const resolved = (await hooks.provider!.models!({ id: "github-copilot", models } as never, ctx as never)) as Record // One model call; `prompt: null` is a follow-up step of the same turn (no new user message). @@ -442,3 +446,45 @@ describe("when routing fails or cannot serve the turn", () => { }) }) }) + +describe("across plugin reloads", () => { + test("keeps the route and its token, without routing again on the next prompt", async () => { + let pick = "gpt-5.4-mini" + await withFetch({ auto: () => autoPicks(pick)() }, async (calls) => { + const dir = freshStateDir() + await (await setup(catalog, {}, oauth, dir)).turn("auto") + pick = "gpt-5.4" + const next = await (await setup(catalog, {}, oauth, dir)).turn("auto", { prompt: "continue" }) + expect(calls).toHaveLength(1) + expect(next.model).toBe("gpt-5.4-mini") + expect(next.token).toBe("tok-gpt-5.4-mini") + }) + }) + + test("a compaction before the reload still re-routes the next turn", async () => { + let pick = "gpt-5.4-mini" + await withFetch({ auto: () => autoPicks(pick)() }, async (calls) => { + const dir = freshStateDir() + const first = await setup(catalog, {}, oauth, dir) + await first.turn("auto") + await first.hooks.event!({ event: { type: "session.compacted", properties: { sessionID: "ses_test" } } } as never) + pick = "gpt-5.4" + const after = await (await setup(catalog, {}, oauth, dir)).turn("auto") + expect(calls).toHaveLength(2) + expect(after.model).toBe("gpt-5.4") + }) + }) + + test("a compaction right after a reload re-routes a route not used yet", async () => { + let pick = "gpt-5.4-mini" + await withFetch({ auto: () => autoPicks(pick)() }, async (calls) => { + const dir = freshStateDir() + await (await setup(catalog, {}, oauth, dir)).turn("auto") + const reloaded = await setup(catalog, {}, oauth, dir) + await reloaded.hooks.event!({ event: { type: "session.compacted", properties: { sessionID: "ses_test" } } } as never) + pick = "gpt-5.4" + expect((await reloaded.turn("auto")).model).toBe("gpt-5.4") + expect(calls).toHaveLength(2) + }) + }) +}) diff --git a/test/v2.test.ts b/test/v2.test.ts index 9400fbf..95a8481 100644 --- a/test/v2.test.ts +++ b/test/v2.test.ts @@ -1,6 +1,9 @@ // opencode 2 adapter (`setup`), against a minimal stand-in for its plugin context. import { describe, expect, test } from "bun:test" +import { existsSync, readFileSync, statSync } from "node:fs" +import path from "node:path" import plugin from "../src/index" +import { freshStateDir } from "./setup" const COPILOT = "https://api.githubcopilot.com" const COPILOT_SDK = "aisdk:@ai-sdk/github-copilot" @@ -80,7 +83,10 @@ type Hook = (event: any) => Promise | void // Loads the plugin against a minimal stand-in for opencode 2's plugin context: a // model editor over `models` and a recorder for session hooks. -async function setup(models: FakeModel[], options: Record = {}, credential: unknown = oauth) { +// `stateDir` reuses the state of an earlier setup, as a plugin reload would. +async function setup(models: FakeModel[], options: Record = {}, credential: unknown = oauth, stateDir?: string) { + if (stateDir) process.env.XDG_STATE_HOME = stateDir + else freshStateDir() const store = new Map(models.map((m) => [m.id, structuredClone(m)])) const hooks = new Map() const transforms: Array<(editor: unknown) => void> = [] @@ -469,3 +475,82 @@ describe("when routing fails or cannot serve the turn", () => { }) }) }) + +describe("across plugin reloads", () => { + // opencode reloads the plugin on every config change and recycles idle instances. + test("keeps the route and its token, without routing again on the next prompt", async () => { + let pick = "gpt-6-luna" + await withFetch({ auto: () => autoPicks(pick)() }, async (calls) => { + const dir = freshStateDir() + await (await setup(catalog, {}, oauth, dir)).turn("auto") + pick = "gpt-6.1-sol" + const reloaded = await setup(catalog, {}, oauth, dir) + const next = await reloaded.turn("auto", { prompt: "continue" }) + expect(calls).toHaveLength(1) + expect(next.model).toBe("gpt-6-luna") + expect(next.token).toBe("tok-gpt-6-luna") + }) + }) + + test("keeps every session and auto apart", async () => { + await withFetch({ auto: (body) => autoPicks(body.tier === "intelligence" ? "gpt-6.1-sol" : "gpt-6-luna")() }, async (calls) => { + const dir = freshStateDir() + const first = await setup(catalog, {}, oauth, dir) + await first.turn("auto", { sessionID: "ses_a" }) + await first.turn("auto-intelligence", { sessionID: "ses_b" }) + const reloaded = await setup(catalog, {}, oauth, dir) + expect((await reloaded.turn("auto", { sessionID: "ses_a" })).model).toBe("gpt-6-luna") + expect((await reloaded.turn("auto-intelligence", { sessionID: "ses_b" })).model).toBe("gpt-6.1-sol") + expect(calls).toHaveLength(2) + }) + }) + + test("routes again when the restored token is about to expire", async () => { + await withFetch({ auto: autoPicks("gpt-6-luna", 60) }, async (calls) => { + const dir = freshStateDir() + await (await setup(catalog, {}, oauth, dir)).turn("auto") + await (await setup(catalog, {}, oauth, dir)).turn("auto") + expect(calls).toHaveLength(2) + }) + }) + + test("routes again when the restored model can no longer be sent", async () => { + await withFetch({ auto: autoPicks("gpt-6-luna") }, async (calls) => { + const dir = freshStateDir() + await (await setup(catalog, {}, oauth, dir)).turn("auto") + const result = await (await setup([sonnet, haiku, gpt54, sol], {}, oauth, dir)).turn("auto") + expect(calls).toHaveLength(2) + expect(result.model).toBe("gpt-5.4") + }) + }) + + test("a compaction before the reload still re-routes the next agent turn", async () => { + let pick = "gpt-6-luna" + await withFetch({ auto: () => autoPicks(pick)() }, async (calls) => { + const dir = freshStateDir() + const first = await setup(catalog, {}, oauth, dir) + await first.turn("auto") + await first.turn("auto", { prompt: null, kind: "compaction" }) + pick = "gpt-6.1-sol" + const after = await (await setup(catalog, {}, oauth, dir)).turn("auto") + expect(calls).toHaveLength(2) + expect(after.model).toBe("gpt-6.1-sol") + }) + }) + + test("stores the session tokens owner-only, and no fallback without a token", async () => { + await withFetch({ auto: () => 503 }, async () => { + const dir = freshStateDir() + await (await setup(catalog, {}, oauth, dir)).turn("auto") + expect(existsSync(path.join(dir, "opencode-copilot-auto", "routes.json"))).toBe(true) + expect(JSON.parse(readFileSync(path.join(dir, "opencode-copilot-auto", "routes.json"), "utf8")).sessions).toEqual({}) + }) + await withFetch({ auto: autoPicks("gpt-6-luna") }, async () => { + const dir = freshStateDir() + await (await setup(catalog, {}, oauth, dir)).turn("auto") + const file = path.join(dir, "opencode-copilot-auto", "routes.json") + expect(statSync(file).mode & 0o777).toBe(0o600) + expect(JSON.parse(readFileSync(file, "utf8")).sessions.ses_test.auto.sessionToken).toBe("tok-gpt-6-luna") + }) + }) +})