From 596e1f098b6739607667bec7e54ac9ae65a489ab Mon Sep 17 00:00:00 2001 From: Philipp Kapfer Date: Wed, 11 Nov 2026 10:35:26 +0100 Subject: [PATCH 1/3] feat: route unavailable models to their mapped fallback OpenCode resolves an explicitly selected unavailable model to a hard 'Model unavailable' error and silently substitutes its default model for an unavailable agent pin - both at resolution time, before any provider request exists, so the retry hooks cannot see them. route_unavailable (on by default) extends the prompt hook to consult OpenCode's enabled model inventory before the request is built: a mapped original that is not in the inventory is routed to its fallback without waiting for a failure, and sessions return to the original once it is available again. Sessions without an explicit selection (e.g. subagents running on their agent's pinned model) are covered too: an unavailable mapped original pin is routed away, while a deliberately pinned fallback is respected. The inventory snapshot is cached for 30 seconds and invalidated by provider.updated/model.updated events; an inventory that cannot be read never routes. --- README.md | 5 ++ lib/options.js | 1 + lib/router.js | 86 +++++++++++++++++-- test/e2e.fallback.test.js | 26 +++++- test/router.test.js | 168 +++++++++++++++++++++++++++++++++++++- 5 files changed, 276 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index de2955e..6fb7420 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,7 @@ If you want to set plugin options, add them to the entry: - `retryable_error_patterns`: retryable error message patterns. Defaults to `["rate.?limit"]`. - `cooldown_seconds`: how long a failed original model remains on fallback. Defaults to `3600`. - `notify_on_fallback`: log fallback/recovery notices. Defaults to `true`. +- `route_unavailable`: also route when the selected or agent-pinned original model is unavailable (not in OpenCode's enabled model inventory, e.g. its provider has no credentials on this machine). Defaults to `true`. ## How it works @@ -133,6 +134,10 @@ cooling down. When the cooldown expires, mapped requests switch back to the original model. +### Unavailable model + +With `route_unavailable` (the default), the `prompt` hook also consults OpenCode's enabled model inventory before the request is built. OpenCode resolves an explicitly selected unavailable model to a hard `Model unavailable` error and silently substitutes its default model for an unavailable agent pin - both happen at resolution time, before any provider request exists, so the retry hooks cannot see them. When the requested model is a mapped original that is not in the inventory, the session is switched to its fallback; once the original is available again, the next prompt switches the session back. Sessions without an explicit selection (e.g. subagents running on their agent's pinned model) are covered too: an unavailable mapped original pin is routed away, while a deliberately pinned fallback is respected. An inventory that cannot be read never routes. + ### Exhausted fallback Mappings are one-to-one. If the fallback model also hits a retryable failure, diff --git a/lib/options.js b/lib/options.js index 4b44c73..bbfce9b 100644 --- a/lib/options.js +++ b/lib/options.js @@ -4,6 +4,7 @@ const DEFAULT_OPTIONS = { retryable_error_patterns: ["rate.?limit"], cooldown_seconds: 3600, notify_on_fallback: true, + route_unavailable: true, }; export function normalizeOptions(rawOptions) { diff --git a/lib/router.js b/lib/router.js index 631b434..f4d602c 100644 --- a/lib/router.js +++ b/lib/router.js @@ -13,6 +13,14 @@ export function createMappedFallbackRouter(ctx, rawOptions) { const activeOriginals = new Map(); const activeRequested = new Map(); const activeTargets = new Map(); + // Availability routing: a mapped original that is not in OpenCode's enabled model + // inventory (e.g. its provider has no credentials on this machine) is routed to its + // fallback even without a failure-driven cooldown, and sessions return to the + // original once it is available again. + const AVAILABLE_MODELS_TTL_MS = 30_000; + let availableModels; + let availableModelsFetchedAt = 0; + let availableModelsRequest; function hasMapping(model) { return !!model && !!options.mappings[model]; @@ -33,7 +41,60 @@ export function createMappedFallbackRouter(ctx, rawOptions) { const fallback = options.mappings[original]; if (!fallback) return requested; const cooldown = await store.getModelCooldown(original); - return cooldown ? fallback : original; + if (cooldown) return fallback; + if (!(await isModelAvailable(original))) return fallback; + return original; + } + + function invalidateAvailableModels() { + availableModelsFetchedAt = 0; + } + + async function fetchAvailableModels() { + if (Date.now() - availableModelsFetchedAt < AVAILABLE_MODELS_TTL_MS) return availableModels; + if (availableModelsRequest) return availableModelsRequest; + availableModelsRequest = (async () => { + try { + const result = await ctx.model.list(); + // The client returns { location, data }; older hosts may return a bare array. + const models = Array.isArray(result) ? result : (result?.data ?? []); + availableModels = new Set( + models + .filter((model) => model.enabled !== false) + .map((model) => `${model.providerID}/${model.modelID}`), + ); + } catch { + // An untrusted inventory must never route: treat every model as available + // until a fresh snapshot arrives. + availableModels = undefined; + } finally { + availableModelsFetchedAt = Date.now(); + } + return availableModels; + })(); + try { + return await availableModelsRequest; + } finally { + availableModelsRequest = undefined; + } + } + + async function isModelAvailable(model) { + if (!options.route_unavailable) return true; + const available = await fetchAvailableModels(); + if (!available) return true; + return available.has(model); + } + + async function agentPinnedModel(agentID) { + if (!agentID || typeof agentID !== "string" || !ctx.agent?.get) return undefined; + try { + const agent = await ctx.agent.get({ agentID }); + // The client returns { location, data }; older hosts may return the info directly. + return modelRefString(agent?.data?.model ?? agent?.model); + } catch { + return undefined; + } } function notify(title, message) { @@ -68,8 +129,17 @@ export function createMappedFallbackRouter(ctx, rawOptions) { if (!sessionID) return; // SessionPrompt carries no model; the session's current selection does. const session = await ctx.session.get({ sessionID }).catch(() => undefined); - const requested = modelRefString(session?.model); - if (!requested || !shouldRoute(requested)) return; + let requested = modelRefString(session?.model); + if (!requested) { + // Sessions without an explicit selection (e.g. subagents) run on their + // agent's pinned model; availability routing applies to that pin too. + // Only a mapped original pin may be routed away - a deliberately pinned + // fallback is respected. + requested = await agentPinnedModel(session?.agent); + if (!requested || !hasMapping(requested)) return; + } else if (!shouldRoute(requested)) { + return; + } const original = mappedOriginal(requested); const target = await selectedModel(requested); if (!target) return; @@ -133,6 +203,10 @@ export function createMappedFallbackRouter(ctx, rawOptions) { * V1 `event` handler -> V2 `ctx.event.subscribe` background loop. */ async function event(event) { + if (event?.type === "provider.updated" || event?.type === "model.updated") { + invalidateAvailableModels(); + return; + } if (event?.type === "session.deleted") { const id = event?.data?.sessionID; if (id) { @@ -150,11 +224,11 @@ export function createMappedFallbackRouter(ctx, rawOptions) { const controller = new AbortController(); const loop = (async () => { try { - // Only session deletions matter here; an unfiltered subscription would - // receive every streaming delta just to be discarded. + // Only deletions and inventory changes matter here; an unfiltered + // subscription would receive every streaming delta just to be discarded. for await (const e of ctx.event.subscribe({ signal: controller.signal, - types: ["session.deleted"], + types: ["session.deleted", "provider.updated", "model.updated"], })) { await event(e); } diff --git a/test/e2e.fallback.test.js b/test/e2e.fallback.test.js index 56fe847..1841896 100644 --- a/test/e2e.fallback.test.js +++ b/test/e2e.fallback.test.js @@ -120,7 +120,7 @@ function startOpencode(envRoot, mockPort, apiPort) { { package: repoRoot, options: { - mappings: { "mock/original": "mock/fallback" }, + mappings: { "mock/original": "mock/fallback", "mock/missing": "mock/fallback" }, notify_on_fallback: true, cooldown_seconds: 3600, }, @@ -298,6 +298,30 @@ describe.skipIf(!run)("e2e: fallback against a real opencode server", { timeout: ).length; expect(originalCallsAfter).toBe(originalCallsBefore); }); + + test("an unavailable model routes to the fallback before the request is built", async () => { + // mock/missing is mapped but not declared in the mock provider's model + // list, so it never enters OpenCode's enabled inventory. Without routing, + // the turn dies with a hard "Model unavailable" resolution error. + const session = await state.client.session.create({ + title: "e2e unavailable", + model: { providerID: "mock", id: "missing" }, + }); + await state.client.session.prompt({ sessionID: session.id, text: "hello missing" }); + await turnDone(state.client, session.id); + + expect(await assistantText(state.client, session.id)).toContain("fallback reply"); + const after = await state.client.session.get({ sessionID: session.id }); + expect(after.model).toMatchObject({ providerID: "mock", id: "fallback" }); + + // The unavailable model never reached the provider. + expect(state.mock.requests.some((request) => request.model?.includes("missing"))).toBe(false); + expect( + state.mock.requests.some( + (request) => request.model?.includes("fallback") && request.status === 200, + ), + ).toBe(true); + }); }); if (!run) { diff --git a/test/router.test.js b/test/router.test.js index 67021fb..c2fc8a6 100644 --- a/test/router.test.js +++ b/test/router.test.js @@ -254,7 +254,7 @@ test("setup registers hooks, subscribes to deletions only and cleans up", async expect(ctx.hooks.prompt).toHaveLength(1); expect(ctx.hooks.retry).toHaveLength(1); expect(ctx.subscribeCalls).toBe(1); - expect(ctx.subscribeTypes).toEqual(["session.deleted"]); + expect(ctx.subscribeTypes).toEqual(["session.deleted", "provider.updated", "model.updated"]); await ctx.pushEvent({ type: "session.deleted", data: { sessionID: "session-1" } }); await cleanup(); @@ -262,6 +262,146 @@ test("setup registers hooks, subscribes to deletions only and cleans up", async expect(ctx.disposed).toEqual(["prompt", "retry"]); }); +test("unavailable original routes to the fallback without a cooldown", async () => { + const ctx = createContext({}, modelRef(ORIGINAL), { availableModels: [FALLBACK] }); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK }, + }); + + await router.prompt(promptEvent("session-1")); + + expect(ctx.session.switchModel).toHaveBeenCalledWith({ + sessionID: "session-1", + model: modelRef(FALLBACK), + }); + expect(ctx.warnings()).toEqual([ + { title: "Model Fallback", message: `Using ${FALLBACK} instead of ${ORIGINAL}` }, + ]); +}); + +test("session stays on the fallback while the original is unavailable", async () => { + const ctx = createContext({}, modelRef(FALLBACK), { availableModels: [FALLBACK] }); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK }, + }); + + await router.prompt(promptEvent("session-1")); + + expect(ctx.session.switchModel).not.toHaveBeenCalled(); + expect(ctx.warnings()).toEqual([]); +}); + +test("session returns to the original once it is available again", async () => { + const ctx = createContext({}, modelRef(ORIGINAL), { availableModels: [FALLBACK] }); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK }, + }); + + await router.prompt(promptEvent("session-1")); + ctx.availableModels = [ORIGINAL, FALLBACK]; + ctx.sessionModel = modelRef(FALLBACK); + vi.setSystemTime(new Date("2026-01-01T00:00:31.000Z")); + await router.prompt(promptEvent("session-1")); + + expect(ctx.session.switchModel).toHaveBeenLastCalledWith({ + sessionID: "session-1", + model: modelRef(ORIGINAL), + }); + expect(ctx.warnings()).toEqual([ + { title: "Model Fallback", message: `Using ${FALLBACK} instead of ${ORIGINAL}` }, + { title: "Model Recovered", message: `${FALLBACK} -> ${ORIGINAL}` }, + ]); +}); + +test("provider updates invalidate the availability snapshot", async () => { + const ctx = createContext({}, modelRef(ORIGINAL), { availableModels: [FALLBACK] }); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK }, + }); + const cleanup = await router.setup(); + + await router.prompt(promptEvent("session-1")); + ctx.availableModels = [ORIGINAL, FALLBACK]; + ctx.sessionModel = modelRef(FALLBACK); + await ctx.pushEvent({ type: "provider.updated", data: {} }); + await router.prompt(promptEvent("session-1")); + + expect(ctx.session.switchModel).toHaveBeenLastCalledWith({ + sessionID: "session-1", + model: modelRef(ORIGINAL), + }); + await cleanup(); +}); + +test("unavailable agent pin routes to the mapped fallback", async () => { + const ctx = createContext({}, null, { + availableModels: [FALLBACK], + agent: { id: "build", model: modelRef(ORIGINAL) }, + }); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK }, + }); + + await router.prompt(promptEvent("session-1")); + + expect(ctx.agent.get).toHaveBeenCalledWith({ agentID: "build" }); + expect(ctx.session.switchModel).toHaveBeenCalledWith({ + sessionID: "session-1", + model: modelRef(FALLBACK), + }); +}); + +test("available agent pin is left untouched", async () => { + const ctx = createContext({}, null, { + agent: { id: "build", model: modelRef(ORIGINAL) }, + }); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK }, + }); + + await router.prompt(promptEvent("session-1")); + + expect(ctx.session.switchModel).not.toHaveBeenCalled(); +}); + +test("pinned fallback models are not rerouted to their original", async () => { + const ctx = createContext({}, null, { + agent: { id: "build", model: modelRef(FALLBACK) }, + }); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK }, + }); + + await router.prompt(promptEvent("session-1")); + + expect(ctx.session.switchModel).not.toHaveBeenCalled(); +}); + +test("route_unavailable: false keeps cooldown-only routing", async () => { + const ctx = createContext({}, modelRef(ORIGINAL), { availableModels: [FALLBACK] }); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK }, + route_unavailable: false, + }); + + await router.prompt(promptEvent("session-1")); + + expect(ctx.model.list).not.toHaveBeenCalled(); + expect(ctx.session.switchModel).not.toHaveBeenCalled(); +}); + +test("an untrustworthy model inventory never routes", async () => { + const ctx = createContext({}, modelRef(ORIGINAL)); + ctx.model.list.mockRejectedValue(new Error("inventory unavailable")); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK }, + }); + + await router.prompt(promptEvent("session-1")); + + expect(ctx.session.switchModel).not.toHaveBeenCalled(); +}); + function promptEvent(sessionID) { return { sessionID, messageID: "msg-1", prompt: {}, delivery: "user" }; } @@ -290,7 +430,7 @@ function modelRef(model) { return { providerID, id }; } -function createContext(initial = {}, sessionModel = modelRef(ORIGINAL)) { +function createContext(initial = {}, sessionModel = modelRef(ORIGINAL), overrides = {}) { const data = new Map(Object.entries(initial)); const warningLines = []; const hooks = { prompt: [], retry: [] }; @@ -303,6 +443,24 @@ function createContext(initial = {}, sessionModel = modelRef(ORIGINAL)) { subscribeCalls: 0, subscribeTypes: undefined, sessionModel, + agentID: overrides.agentID ?? "build", + availableModels: overrides.availableModels ?? [ + ORIGINAL, + FALLBACK, + "openai/gpt-2", + "azure/gpt-2", + ], + model: { + list: vi.fn(async () => ({ + data: ctx.availableModels.map((name) => { + const [providerID, modelID] = name.split("/"); + return { providerID, modelID, enabled: true }; + }), + })), + }, + agent: { + get: vi.fn(async ({ agentID }) => overrides.agent ?? { id: agentID }), + }, storage: { async get(key) { return data.get(key); @@ -315,7 +473,11 @@ function createContext(initial = {}, sessionModel = modelRef(ORIGINAL)) { }, }, session: { - get: vi.fn(async ({ sessionID }) => ({ id: sessionID, model: ctx.sessionModel })), + get: vi.fn(async ({ sessionID }) => ({ + id: sessionID, + model: ctx.sessionModel, + agent: ctx.agentID, + })), switchModel: vi.fn(async () => {}), hook: vi.fn(async (name, callback) => { hooks[name].push(callback); From 5cf9c72eaf030e8d0e215a4bd8829bdcfaf1cf80 Mon Sep 17 00:00:00 2001 From: Philipp Kapfer Date: Wed, 11 Nov 2026 12:51:59 +0100 Subject: [PATCH 2/3] feat: preserve reasoning effort across fallback switches Switches dropped the session's reasoning effort entirely: the fallback model ran at its default even when it supported the same effort level. switchSessionModel now keeps the session's current variant when the target lists it in its catalog, and falls back to the target's default otherwise (e.g. a non-reasoning fallback or one without the specific level). A mapping value may pin the effort explicitly ('azure/gpt-5.5#high'), which always wins over matching; mapping keys are normalized to be variant-less. When the fallback drops the effort, recovery restores it without plugin-side state: from the session agent's pinned model when it points at the original, else from the original's most recent recorded response (assistant messages persist the model ref with variant). Both sources survive plugin restarts. An untrustworthy inventory never reports support, keeping the previous default-effort behavior. --- README.md | 6 +- lib/models.js | 4 +- lib/options.js | 4 +- lib/router.js | 70 +++++++++++-- test/e2e.fallback.test.js | 17 +++- test/router.test.js | 208 +++++++++++++++++++++++++++++++++++++- 6 files changed, 295 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 6fb7420..ee26960 100644 --- a/README.md +++ b/README.md @@ -136,7 +136,11 @@ When the cooldown expires, mapped requests switch back to the original model. ### Unavailable model -With `route_unavailable` (the default), the `prompt` hook also consults OpenCode's enabled model inventory before the request is built. OpenCode resolves an explicitly selected unavailable model to a hard `Model unavailable` error and silently substitutes its default model for an unavailable agent pin - both happen at resolution time, before any provider request exists, so the retry hooks cannot see them. When the requested model is a mapped original that is not in the inventory, the session is switched to its fallback; once the original is available again, the next prompt switches the session back. Sessions without an explicit selection (e.g. subagents running on their agent's pinned model) are covered too: an unavailable mapped original pin is routed away, while a deliberately pinned fallback is respected. An inventory that cannot be read never routes. +With `route_unavailable` (the default), the `prompt` hook also consults OpenCode's enabled model inventory before the request is built. OpenCode resolves an explicitly selected unavailable model to a hard `Model unavailable` error and silently substitutes its default model for an unavailable agent pin - both happen at resolution time, before any provider request exists, so the retry hooks cannot see them. When the requested model is a mapped original that is not in the inventory, the session is switched to its fallback; once the original is available again, the next prompt switches the session back. Sessions without an explicit selection (e.g. subagents running on their agent's pinned model) are covered too: an unavailable mapped original pin is routed away, while a deliberately pinned fallback is respected. An inventory that cannot be read never routes. A provider that vanishes mid-turn cannot be saved: the agentic loop builds a new request after each tool result without a prompt, and core resolves the unavailable model to a terminal error before any plugin hook can reroute it - the turn fails visibly and the next prompt recovers automatically. + +### Reasoning effort + +Switches keep the session's reasoning effort. When the target model lists the session's current variant (e.g. `high`) in its catalog, the session is switched with that variant; an unsupported effort falls back to the target's default, as before. A mapping value may pin the effort explicitly (`"openai/gpt-5.5": "azure/gpt-5.5#high"`), which always wins over matching; mapping keys are variant-less. Recovery applies the same rule, so `original#high -> fallback#high -> original#high` round-trips while both models support the effort. When the fallback drops the effort (e.g. a non-reasoning fallback), recovery restores it without plugin-side state - from the session agent's pinned model when it points at the original, else from the original's last recorded response - so it survives plugin restarts. ### Exhausted fallback diff --git a/lib/models.js b/lib/models.js index e71f370..5293711 100644 --- a/lib/models.js +++ b/lib/models.js @@ -1,7 +1,9 @@ export function modelRef(model) { const [providerID, ...modelParts] = model.split("/"); if (!providerID || modelParts.length === 0) return undefined; - return { providerID, id: modelParts.join("/") }; + const [id, variant] = modelParts.join("/").split("#"); + if (!id) return undefined; + return { providerID, id, ...(variant ? { variant } : {}) }; } export function modelRefString(ref) { diff --git a/lib/options.js b/lib/options.js index bbfce9b..cbac1fc 100644 --- a/lib/options.js +++ b/lib/options.js @@ -19,7 +19,9 @@ function normalizeMappings(mappings) { const normalized = {}; for (const [from, to] of Object.entries(mappings)) { if (!from || typeof to !== "string" || !to.includes("/")) continue; - normalized[from] = to; + // Mapping keys are variant-less: the session's reasoning effort is matched + // onto the target automatically, or set explicitly in the value's #variant. + normalized[from.split("#")[0]] = to; } return normalized; } diff --git a/lib/router.js b/lib/router.js index f4d602c..b74061c 100644 --- a/lib/router.js +++ b/lib/router.js @@ -58,10 +58,13 @@ export function createMappedFallbackRouter(ctx, rawOptions) { const result = await ctx.model.list(); // The client returns { location, data }; older hosts may return a bare array. const models = Array.isArray(result) ? result : (result?.data ?? []); - availableModels = new Set( + availableModels = new Map( models .filter((model) => model.enabled !== false) - .map((model) => `${model.providerID}/${model.modelID}`), + .map((model) => [ + `${model.providerID}/${model.modelID}`, + new Set((model.variants ?? []).map((variant) => variant.id)), + ]), ); } catch { // An untrusted inventory must never route: treat every model as available @@ -86,17 +89,52 @@ export function createMappedFallbackRouter(ctx, rawOptions) { return available.has(model); } + // Whether a model lists the given reasoning effort as a variant. An + // untrustworthy inventory never reports support, so the effort is dropped. + async function supportsVariant(model, variant) { + if (!variant || variant === "default") return false; + const available = await fetchAvailableModels(); + if (!available) return false; + return available.get(model)?.has(variant) === true; + } + async function agentPinnedModel(agentID) { if (!agentID || typeof agentID !== "string" || !ctx.agent?.get) return undefined; try { const agent = await ctx.agent.get({ agentID }); // The client returns { location, data }; older hosts may return the info directly. - return modelRefString(agent?.data?.model ?? agent?.model); + return agent?.data?.model ?? agent?.model; } catch { return undefined; } } + // The effort the original last ran with, without plugin-side state: the + // session agent's pinned model when it points at the original, else the + // most recent assistant message the original produced. Both sources are + // persisted, so recovery survives plugin restarts. + async function recoveredEffort(sessionID, agentID, original) { + const pin = await agentPinnedModel(agentID); + if (pin && modelRefString(pin) === original && pin.variant && pin.variant !== "default") { + return pin.variant; + } + if (!ctx.session?.context) return undefined; + try { + const result = await ctx.session.context({ sessionID }); + const messages = Array.isArray(result) ? result : (result?.data ?? []); + for (let index = messages.length - 1; index >= 0; index--) { + const message = messages[index]; + const model = message?.type === "assistant" ? message.model : undefined; + if (!model?.providerID || !model?.id) continue; + if (`${model.providerID}/${model.id}` !== original) continue; + return model.variant && model.variant !== "default" ? model.variant : undefined; + } + } catch { + // History is best-effort: without it the original recovers at its default. + } + return undefined; + } + function notify(title, message) { if (!options.notify_on_fallback) return; console.warn(`[model-fallback] ${title}: ${message}`); @@ -130,12 +168,15 @@ export function createMappedFallbackRouter(ctx, rawOptions) { // SessionPrompt carries no model; the session's current selection does. const session = await ctx.session.get({ sessionID }).catch(() => undefined); let requested = modelRefString(session?.model); + let effort = session?.model?.variant; if (!requested) { // Sessions without an explicit selection (e.g. subagents) run on their // agent's pinned model; availability routing applies to that pin too. // Only a mapped original pin may be routed away - a deliberately pinned // fallback is respected. - requested = await agentPinnedModel(session?.agent); + const pin = await agentPinnedModel(session?.agent); + requested = modelRefString(pin); + effort = pin?.variant; if (!requested || !hasMapping(requested)) return; } else if (!shouldRoute(requested)) { return; @@ -144,14 +185,29 @@ export function createMappedFallbackRouter(ctx, rawOptions) { const target = await selectedModel(requested); if (!target) return; if (original) activeOriginals.set(sessionID, original); - if (target !== requested) await switchSessionModel(sessionID, target).catch(() => {}); + if (target !== requested) { + // On recovery the session may carry no effort (a fallback without support + // drops it); the agent pin or the original's last recorded response + // restores it without plugin-side state. + const recovered = + hasMapping(requested) || effort + ? undefined + : await recoveredEffort(sessionID, session?.agent, original); + await switchSessionModel(sessionID, target, recovered ?? effort).catch(() => {}); + } logRouteChange(sessionID, requested, target, original); } - async function switchSessionModel(sessionID, model) { + async function switchSessionModel(sessionID, model, effort) { if (!sessionID) return; const ref = modelRef(model); if (!ref) return; + // Keep the session's reasoning effort when the target supports it; an + // explicit #variant in the mapping value always wins. An unsupported or + // unknown effort falls back to the target's default, as before. + if (!ref.variant && (await supportsVariant(`${ref.providerID}/${ref.id}`, effort))) { + ref.variant = effort; + } await ctx.session.switchModel({ sessionID, model: ref }); } @@ -191,7 +247,7 @@ export function createMappedFallbackRouter(ctx, rawOptions) { try { const fallback = options.mappings[original]; activeOriginals.set(sessionID, original); - await switchSessionModel(sessionID, fallback); + await switchSessionModel(sessionID, fallback, event.model?.variant); event.decision = { retry: true, delay: options.retry_delay_ms ?? 0 }; notify("Model Fallback", `${original} -> ${fallback} (${event.error?.type ?? "retry"})`); } finally { diff --git a/test/e2e.fallback.test.js b/test/e2e.fallback.test.js index 1841896..a56d801 100644 --- a/test/e2e.fallback.test.js +++ b/test/e2e.fallback.test.js @@ -111,8 +111,8 @@ function startOpencode(envRoot, mockPort, apiPort) { package: "aisdk:@ai-sdk/openai-compatible", settings: { baseURL: `http://127.0.0.1:${mockPort}/v1`, apiKey: "dummy" }, models: { - original: { name: "Original" }, - fallback: { name: "Fallback" }, + original: { name: "Original", variants: [{ id: "high" }] }, + fallback: { name: "Fallback", variants: [{ id: "high" }] }, }, }, }, @@ -322,6 +322,19 @@ describe.skipIf(!run)("e2e: fallback against a real opencode server", { timeout: ), ).toBe(true); }); + + test("a routed fallback keeps the session's reasoning effort when the target supports it", async () => { + const session = await state.client.session.create({ + title: "e2e effort", + model: { providerID: "mock", id: "original", variant: "high" }, + }); + await state.client.session.prompt({ sessionID: session.id, text: "hello effort" }); + await turnDone(state.client, session.id); + + expect(await assistantText(state.client, session.id)).toContain("fallback reply"); + const after = await state.client.session.get({ sessionID: session.id }); + expect(after.model).toMatchObject({ providerID: "mock", id: "fallback", variant: "high" }); + }); }); if (!run) { diff --git a/test/router.test.js b/test/router.test.js index c2fc8a6..2167db3 100644 --- a/test/router.test.js +++ b/test/router.test.js @@ -402,6 +402,199 @@ test("an untrustworthy model inventory never routes", async () => { expect(ctx.session.switchModel).not.toHaveBeenCalled(); }); +test("fallback keeps the reasoning effort when the target supports it", async () => { + const now = Date.now(); + const ctx = createContext( + { [cooldownKey(ORIGINAL)]: cooldown(now - 1_000, now + 60_000) }, + { ...modelRef(ORIGINAL), variant: "high" }, + { availableModels: [`${ORIGINAL}|high`, `${FALLBACK}|high`] }, + ); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK }, + }); + + await router.prompt(promptEvent("session-1")); + + expect(ctx.session.switchModel).toHaveBeenCalledWith({ + sessionID: "session-1", + model: { ...modelRef(FALLBACK), variant: "high" }, + }); +}); + +test("fallback drops the reasoning effort when the target does not support it", async () => { + const now = Date.now(); + const ctx = createContext( + { [cooldownKey(ORIGINAL)]: cooldown(now - 1_000, now + 60_000) }, + { ...modelRef(ORIGINAL), variant: "high" }, + { availableModels: [`${ORIGINAL}|high`, FALLBACK] }, + ); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK }, + }); + + await router.prompt(promptEvent("session-1")); + + expect(ctx.session.switchModel).toHaveBeenCalledWith({ + sessionID: "session-1", + model: modelRef(FALLBACK), + }); +}); + +test("an explicit variant in the mapping value wins over matching", async () => { + const now = Date.now(); + const ctx = createContext( + { [cooldownKey(ORIGINAL)]: cooldown(now - 1_000, now + 60_000) }, + modelRef(ORIGINAL), + { availableModels: [ORIGINAL, FALLBACK] }, + ); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: `${FALLBACK}#high` }, + }); + + await router.prompt(promptEvent("session-1")); + + expect(ctx.session.switchModel).toHaveBeenCalledWith({ + sessionID: "session-1", + model: { ...modelRef(FALLBACK), variant: "high" }, + }); +}); + +test("recovery restores the reasoning effort", async () => { + const ctx = createContext( + {}, + { ...modelRef(FALLBACK), variant: "high" }, + { availableModels: [`${ORIGINAL}|high`, `${FALLBACK}|high`] }, + ); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK }, + }); + + await router.prompt(promptEvent("session-1")); + + expect(ctx.session.switchModel).toHaveBeenCalledWith({ + sessionID: "session-1", + model: { ...modelRef(ORIGINAL), variant: "high" }, + }); +}); + +test("retry preserves the reasoning effort on the fallback", async () => { + const ctx = createContext({}, modelRef(ORIGINAL), { + availableModels: [`${ORIGINAL}|high`, `${FALLBACK}|high`], + }); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK }, + notify_on_fallback: false, + }); + + const event = retryEvent(ORIGINAL, { status: 429, type: "rate-limit", message: "rate limit" }); + event.model = { ...event.model, variant: "high" }; + await router.retry(event); + + expect(ctx.session.switchModel).toHaveBeenCalledWith({ + sessionID: "session-1", + model: { ...modelRef(FALLBACK), variant: "high" }, + }); +}); + +test("the default variant is not carried over to the target", async () => { + const now = Date.now(); + const ctx = createContext( + { [cooldownKey(ORIGINAL)]: cooldown(now - 1_000, now + 60_000) }, + { ...modelRef(ORIGINAL), variant: "default" }, + { availableModels: [`${ORIGINAL}|high`, `${FALLBACK}|high`] }, + ); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK }, + }); + + await router.prompt(promptEvent("session-1")); + + expect(ctx.session.switchModel).toHaveBeenCalledWith({ + sessionID: "session-1", + model: modelRef(FALLBACK), + }); +}); + +test("recovery restores the effort from the agent pin", async () => { + const now = Date.now(); + const ctx = createContext( + { [cooldownKey(ORIGINAL)]: cooldown(now - 1_000, now + 60_000) }, + { ...modelRef(ORIGINAL), variant: "high" }, + { + availableModels: [`${ORIGINAL}|high`, FALLBACK], + agent: { id: "build", model: { ...modelRef(ORIGINAL), variant: "high" } }, + }, + ); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK }, + }); + + await router.prompt(promptEvent("session-1")); + expect(ctx.session.switchModel).toHaveBeenLastCalledWith({ + sessionID: "session-1", + model: modelRef(FALLBACK), + }); + + await ctx.storage.remove(cooldownKey(ORIGINAL)); + ctx.sessionModel = modelRef(FALLBACK); + await router.prompt(promptEvent("session-1")); + expect(ctx.session.switchModel).toHaveBeenLastCalledWith({ + sessionID: "session-1", + model: { ...modelRef(ORIGINAL), variant: "high" }, + }); +}); + +test("recovery restores the effort from the original's last recorded response", async () => { + const now = Date.now(); + const ctx = createContext( + { [cooldownKey(ORIGINAL)]: cooldown(now - 1_000, now + 60_000) }, + { ...modelRef(ORIGINAL), variant: "high" }, + { + availableModels: [`${ORIGINAL}|high`, FALLBACK], + messages: [{ type: "assistant", model: { ...modelRef(ORIGINAL), variant: "high" } }], + }, + ); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK }, + }); + + await router.prompt(promptEvent("session-1")); + await ctx.storage.remove(cooldownKey(ORIGINAL)); + ctx.sessionModel = modelRef(FALLBACK); + await router.prompt(promptEvent("session-1")); + expect(ctx.session.switchModel).toHaveBeenLastCalledWith({ + sessionID: "session-1", + model: { ...modelRef(ORIGINAL), variant: "high" }, + }); + expect(ctx.session.context).toHaveBeenCalledWith({ sessionID: "session-1" }); +}); + +test("a retry away-switch recovers the effort statelessly", async () => { + const ctx = createContext({}, modelRef(ORIGINAL), { + availableModels: [`${ORIGINAL}|high`, FALLBACK], + messages: [{ type: "assistant", model: { ...modelRef(ORIGINAL), variant: "high" } }], + }); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK }, + notify_on_fallback: false, + }); + + const event = retryEvent(ORIGINAL, { status: 429, type: "rate-limit", message: "rate limit" }); + event.model = { ...event.model, variant: "high" }; + await router.retry(event); + expect(ctx.session.switchModel).toHaveBeenLastCalledWith({ + sessionID: "session-1", + model: modelRef(FALLBACK), + }); + + await ctx.storage.remove(cooldownKey(ORIGINAL)); + ctx.sessionModel = modelRef(FALLBACK); + await router.prompt(promptEvent("session-1")); + expect(ctx.session.switchModel).toHaveBeenLastCalledWith({ + sessionID: "session-1", + model: { ...modelRef(ORIGINAL), variant: "high" }, + }); +}); function promptEvent(sessionID) { return { sessionID, messageID: "msg-1", prompt: {}, delivery: "user" }; } @@ -444,6 +637,7 @@ function createContext(initial = {}, sessionModel = modelRef(ORIGINAL), override subscribeTypes: undefined, sessionModel, agentID: overrides.agentID ?? "build", + messages: overrides.messages ?? [], availableModels: overrides.availableModels ?? [ ORIGINAL, FALLBACK, @@ -452,9 +646,18 @@ function createContext(initial = {}, sessionModel = modelRef(ORIGINAL), override ], model: { list: vi.fn(async () => ({ - data: ctx.availableModels.map((name) => { + data: ctx.availableModels.map((entry) => { + const [name, variants] = entry.split("|"); const [providerID, modelID] = name.split("/"); - return { providerID, modelID, enabled: true }; + return { + providerID, + modelID, + enabled: true, + variants: (variants ?? "") + .split(",") + .filter(Boolean) + .map((id) => ({ id })), + }; }), })), }, @@ -479,6 +682,7 @@ function createContext(initial = {}, sessionModel = modelRef(ORIGINAL), override agent: ctx.agentID, })), switchModel: vi.fn(async () => {}), + context: vi.fn(async () => ctx.messages), hook: vi.fn(async (name, callback) => { hooks[name].push(callback); return { From e113abe18dcc5608ec91d62da21e5eb138f76656 Mon Sep 17 00:00:00 2001 From: Philipp Kapfer Date: Wed, 11 Nov 2026 16:31:19 +0100 Subject: [PATCH 3/3] fix: key the model inventory by catalog id, not the provider modelID Model.Info carries both the catalog id (the selectable reference used by sessions, agent pins and mappings) and modelID (the ID sent to the provider). A model renamed through a modelID config attribute - e.g. a provider config key 'mistral-medium-latest' with modelID 'magistral-medium-latest' - made the inventory lookup miss it, so availability routing treated the model as unavailable and silently rerouted sessions to the fallback without any failed request. The inventory now keys by the catalog id, falling back to modelID for entries without one. --- lib/router.js | 5 ++++- test/router.test.js | 27 +++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/lib/router.js b/lib/router.js index b74061c..4a5bd9e 100644 --- a/lib/router.js +++ b/lib/router.js @@ -62,7 +62,10 @@ export function createMappedFallbackRouter(ctx, rawOptions) { models .filter((model) => model.enabled !== false) .map((model) => [ - `${model.providerID}/${model.modelID}`, + // The catalog id is the selectable reference used by sessions, + // agent pins and mappings; `modelID` is what the provider sends + // and may differ (a `modelID` config attribute renaming a model). + `${model.providerID}/${model.id ?? model.modelID}`, new Set((model.variants ?? []).map((variant) => variant.id)), ]), ); diff --git a/test/router.test.js b/test/router.test.js index 2167db3..9881094 100644 --- a/test/router.test.js +++ b/test/router.test.js @@ -595,6 +595,33 @@ test("a retry away-switch recovers the effort statelessly", async () => { model: { ...modelRef(ORIGINAL), variant: "high" }, }); }); +test("a model renamed by a modelID attribute is routable under its catalog key", async () => { + // The config key (mistral-medium-latest) is the selectable reference; the + // provider-facing modelID (magistral-medium-latest) differs. The inventory + // must be keyed by the catalog id, or availability routing treats the + // model as unavailable and silently reroutes it. + const ctx = createContext({}, modelRef("leo/mistral-medium-latest"), { + availableModels: [], + }); + ctx.model.list.mockResolvedValue({ + data: [ + { + id: "mistral-medium-latest", + modelID: "magistral-medium-latest", + providerID: "leo", + enabled: true, + variants: [{ id: "high" }], + }, + ], + }); + const router = createMappedFallbackRouter(ctx, { + mappings: { "leo/mistral-medium-latest": FALLBACK }, + }); + + await router.prompt(promptEvent("session-1")); + expect(ctx.session.switchModel).not.toHaveBeenCalled(); +}); + function promptEvent(sessionID) { return { sessionID, messageID: "msg-1", prompt: {}, delivery: "user" }; }