From 596e1f098b6739607667bec7e54ac9ae65a489ab Mon Sep 17 00:00:00 2001 From: Philipp Kapfer Date: Wed, 11 Nov 2026 10:35:26 +0100 Subject: [PATCH 1/4] 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/4] 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/4] 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" }; } From 34fe16a62be2413f87dcf4577c4b282999a538bd Mon Sep 17 00:00:00 2001 From: Philipp Kapfer Date: Wed, 11 Nov 2026 14:14:30 +0100 Subject: [PATCH 4/4] feat: follow fallback chains transitively Mappings were followed exactly one step: a retryable failure on the fallback itself reported 'Model Fallback Exhausted' and left the decision to the host. Chains now emerge from the transitive composition of the one-to-one mappings ({ A: B, B: C } routes A through B to C): a retryable failure switches the session to the first chain member that can serve the request, skipping members in a global cooldown or missing from the enabled model inventory - which also breaks configured cycles (a cycle truncates at the first repeat). Prompt-time routing walks the same chain. Recovery steps back one level per prompt; a chain member that is itself a mapping key continues to its upstream root when the session's recorded responses show it arrived from there, so deliberately pinned chain members are never yanked. Chain members may carry an explicit #variant (the mapping value), which wins over effort matching as before. --- AGENTS.md | 8 ++- README.md | 56 +++++++++------ lib/router.js | 142 ++++++++++++++++++++++++++++++-------- test/e2e.fallback.test.js | 41 ++++++++++- test/router.test.js | 141 ++++++++++++++++++++++++++++++++++++- 5 files changed, 329 insertions(+), 59 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 82c4929..2351b49 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,10 +13,12 @@ with logic split into `lib/`. - Single default export: `Plugin.define({ id, setup })`. `createMappedFallbackRouter(ctx, options)` receives the V2 plugin context; `ctx.options` holds the plugin options. - Fallback mappings are one-to-one: one original model maps to one fallback - model. + model. Chains are the transitive composition of mappings and are followed + transitively; a configured cycle truncates at the first repeat. - A retryable failure is handled by the V2 session `retry` hook: set the global - cooldown (unless one is already active), switch the session to the fallback - model (`ctx.session.switchModel`), and force `event.decision = { retry: true }`. + cooldown (unless one is already active), switch the session to the next + healthy chain member (`ctx.session.switchModel`), and force + `event.decision = { retry: true }`. Routing at prompt time happens through the session `prompt` hook: the `context` hook's `model` field is readonly and core ignores writes to it, so the switch must happen before the request is built. diff --git a/README.md b/README.md index ee26960..f20e773 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,9 @@ you need is a simple one-to-one fallback inside OpenCode. This plugin handles that routing directly in OpenCode. When a configured model hits a retryable provider failure, this plugin switches -the session to the mapped fallback model, forces an immediate retry of the failed -request on that fallback, persists a global cooldown for the failed model, and -routes back to the original model after the cooldown expires. +the session to the next healthy model in its fallback chain, forces an immediate +retry of the failed request there, persists a global cooldown for the failed +model, and steps back up the chain as cooldowns expire. ## Install @@ -77,16 +77,18 @@ The plugin hooks into OpenCode's session prompt and retry flows. When a prompt is submitted with a model listed in `mappings`, that model is preferred unless it has an active global cooldown; the switch happens before the request is built, so the current turn is routed. If OpenCode reports a retryable provider -failure, the plugin switches to the mapped fallback model, forces an immediate -retry of the request on it, and stores a global cooldown for the failed model. +failure, the plugin switches to the next healthy chain member, forces an +immediate retry of the request on it, and stores a global cooldown for the +failed model. Global model cooldowns are persisted with OpenCode's plugin storage (`ctx.storage`), which is namespaced per plugin. Persisted cooldowns let all -sessions avoid immediately retrying a model that has just failed. When the -cooldown expires, mapped requests are routed back to the original model. +sessions avoid immediately retrying a model that has just failed. When +cooldowns expire, sessions step back up the chain one level per prompt. -The plugin does not load balance, race models, or retry through a chain. Each -mapping is one original model to one fallback model. +Each mapping is one original model to one fallback model; chains emerge from +composition (a/gpt -> b/gpt -> c/gpt) and are followed transitively. The plugin +does not load balance or race models. ## Scenarios @@ -95,14 +97,16 @@ mapping is one original model to one fallback model. If you send a message with `openai/gpt-5.5` and the model has a mapping, the request goes to `openai/gpt-5.5` normally unless it has an active cooldown. If you select the mapped fallback model directly, the plugin still routes back -to the original model unless the original has an active cooldown. +to the original model unless the original has an active cooldown (a chain +member that is itself a mapping key is respected as its own root - see +Chained fallbacks). ### Retryable failure If OpenCode reports a retryable provider failure such as a rate limit or a -configured retryable status code, the plugin switches the session to the mapped -fallback model and forces an immediate retry, so the failed attempt is replayed -on the fallback instead of waiting out the provider's retry-after. This applies +configured retryable status code, the plugin switches the session to the next +healthy chain member and forces an immediate retry, so the failed attempt is +replayed there instead of waiting out the provider's retry-after. This applies even when the cooldown is already active from another session's failure: the cooldown window is kept, but a session still on the original model is switched and retried right away. @@ -123,30 +127,36 @@ If `openai/gpt-5.5` fails with a retryable error, the session continues on ### Active cooldown After fallback is triggered, the original model is considered cooling down for -`cooldown_seconds`. During that cooldown, mapped requests use the fallback model -instead of switching back and immediately hitting the same provider -failure again. +`cooldown_seconds`. During that cooldown, mapped requests use the next healthy +chain member instead of switching back and immediately hitting the same +provider failure again. -All sessions are routed straight to the fallback while the original model is -cooling down. +All sessions are routed past it to the next healthy chain member while the +original model is cooling down. ### Recovery -When the cooldown expires, mapped requests switch back to the original model. +When cooldowns expire, sessions step back up the chain one level per prompt +(see Chained fallbacks). ### 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. 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. +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 the first available chain member; 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. +### Chained fallbacks + +Chains are the transitive composition of the one-to-one mappings: `{ "a/gpt": "b/gpt", "b/gpt": "c/gpt" }` routes `a/gpt` through `b/gpt` to `c/gpt`. A retryable failure switches the session to the first chain member that can serve the request - members in a global cooldown or missing from the enabled model inventory are skipped, which also breaks configured cycles (a cycle truncates at the first repeat). Prompt-time routing walks the same chain. Recovery steps back one level per prompt: a session that walked `a/gpt -> b/gpt -> c/gpt` returns to `b/gpt` once it is healthy again, and a chain member that is itself a mapping key continues to its upstream root when the session's recorded responses show it actually arrived from there - a deliberately pinned chain member is never yanked. + ### Exhausted fallback -Mappings are one-to-one. If the fallback model also hits a retryable failure, -there is no next fallback to try. The plugin logs a fallback exhausted notice -when notifications are enabled. Route-change notices (`notify_on_fallback`) +Exhausted means no healthy member is left in the failed model's chain: every +following member is either in a global cooldown or missing from OpenCode's enabled +model inventory. The plugin logs a fallback exhausted notice when notifications +are enabled. Route-change notices (`notify_on_fallback`) are written to OpenCode's log (the plugin runs in the background service, so there is no TUI toast; check `~/.local/share/opencode/log/opencode.log` for `[model-fallback]` lines). diff --git a/lib/router.js b/lib/router.js index 4a5bd9e..d81aae7 100644 --- a/lib/router.js +++ b/lib/router.js @@ -35,15 +35,72 @@ export function createMappedFallbackRouter(ctx, rawOptions) { return hasMapping(requested) || !!fallbackToOriginal[requested]; } - async function selectedModel(requested) { - const original = mappedOriginal(requested); - if (!original) return requested; - const fallback = options.mappings[original]; - if (!fallback) return requested; - const cooldown = await store.getModelCooldown(original); - if (cooldown) return fallback; - if (!(await isModelAvailable(original))) return fallback; - return original; + // Chains are the transitive composition of the one-to-one mappings: + // { A: B, B: C } routes A through B to C. A cycle truncates at the first + // repeat, and the global cooldown store keeps a failure from looping. + function chainFrom(model) { + const chain = []; + const visited = new Set(); + let current = model; + while (current && !visited.has(current)) { + visited.add(current); + chain.push(current); + const next = options.mappings[current]; + if (!next) break; + current = next; + } + return chain; + } + + // The upstream root of a chain member: walking reverse mappings until a + // model that is not itself a fallback. Cycles stop at the first repeat. + function chainRootOf(model) { + const visited = new Set(); + let root; + let current = model; + while (current && !visited.has(current)) { + visited.add(current); + root = current; + current = fallbackToOriginal[current]; + } + return root && root !== model ? root : undefined; + } + + async function isRoutable(model) { + // Chain members may carry an explicit #variant; cooldowns and the + // inventory are keyed by the base name. + const name = modelRefString(modelRef(model)) ?? model; + if (await store.getModelCooldown(name)) return false; + return await isModelAvailable(name); + } + + // The first chain member after `model` that can serve the request. + async function nextInChain(model) { + for (const candidate of chainFrom(model).slice(1)) { + if (await isRoutable(candidate)) return candidate; + } + return undefined; + } + + async function selectedModel(sessionID, requested) { + if (hasMapping(requested)) { + // A mapping key is the root of its own chain: it advances only when it + // cannot serve the request itself. + if (await isRoutable(requested)) { + // A chain member that is itself a mapping key still recovers toward + // its upstream root when the session actually arrived from there. + const root = chainRootOf(requested); + if (root && (await isRoutable(root)) && (await sessionUsedModel(sessionID, root))) { + return root; + } + return requested; + } + return (await nextInChain(requested)) ?? requested; + } + // A mapped fallback recovers to its predecessor once that is healthy again. + const predecessor = fallbackToOriginal[requested]; + if (predecessor && (await isRoutable(predecessor))) return predecessor; + return requested; } function invalidateAvailableModels() { @@ -138,6 +195,25 @@ export function createMappedFallbackRouter(ctx, rawOptions) { return undefined; } + // Whether the session ever ran on the given model - evidence that it + // arrived at the current chain member from there. Best-effort: compaction + // may have dropped the evidence. + async function sessionUsedModel(sessionID, model) { + if (!ctx.session?.context) return false; + try { + const result = await ctx.session.context({ sessionID }); + const messages = Array.isArray(result) ? result : (result?.data ?? []); + return messages.some( + (message) => + message?.type === "assistant" && + message.model?.providerID && + `${message.model.providerID}/${message.model.id}` === model, + ); + } catch { + return false; + } + } + function notify(title, message) { if (!options.notify_on_fallback) return; console.warn(`[model-fallback] ${title}: ${message}`); @@ -184,21 +260,27 @@ export function createMappedFallbackRouter(ctx, rawOptions) { } else if (!shouldRoute(requested)) { return; } - const original = mappedOriginal(requested); - const target = await selectedModel(requested); + const target = await selectedModel(sessionID, requested); if (!target) return; - if (original) activeOriginals.set(sessionID, original); + // A recovery returns to a healthier model (predecessor or chain root); an + // advance moves down the chain. The anchor names what the session is + // recovering to, so notifications report the right direction. + const isRecovery = + target === fallbackToOriginal[requested] || + (hasMapping(requested) && target === chainRootOf(requested)); + const anchor = isRecovery ? target : mappedOriginal(requested); + if (anchor) activeOriginals.set(sessionID, anchor); 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. + // drops it); the target's pin or last recorded response restores it + // without plugin-side state. const recovered = - hasMapping(requested) || effort - ? undefined - : await recoveredEffort(sessionID, session?.agent, original); + isRecovery && !effort + ? await recoveredEffort(sessionID, session?.agent, target) + : undefined; await switchSessionModel(sessionID, target, recovered ?? effort).catch(() => {}); } - logRouteChange(sessionID, requested, target, original); + logRouteChange(sessionID, requested, target, anchor); } async function switchSessionModel(sessionID, model, effort) { @@ -230,17 +312,20 @@ export function createMappedFallbackRouter(ctx, rawOptions) { const sessionID = event.sessionID; if (!sessionID || retrying.has(sessionID)) return; if (!isRetryable(event.error, options)) return; - const requested = modelRefString(event.model); - const original = mappedOriginal(requested); - if (!original) return; - if (requested !== original) { - notify("Model Fallback Exhausted", `No mapped fallback left for ${original}`); + const failed = modelRefString(event.model); + if (!failed || !shouldRoute(failed)) return; + // The failed model is the root of its own chain: the next member that can + // serve the request takes over. Cooldowns skip recently failed members, + // which also breaks configured cycles. + const next = hasMapping(failed) ? await nextInChain(failed) : undefined; + if (!next) { + notify("Model Fallback Exhausted", `No mapped fallback left for ${failed}`); return; } - if (!(await store.getModelCooldown(original))) { + if (!(await store.getModelCooldown(failed))) { const failedAt = Date.now(); await store.setModelCooldown( - original, + failed, event.error?.type ?? "retry", failedAt, failedAt + options.cooldown_seconds * 1000, @@ -248,11 +333,10 @@ export function createMappedFallbackRouter(ctx, rawOptions) { } retrying.add(sessionID); try { - const fallback = options.mappings[original]; - activeOriginals.set(sessionID, original); - await switchSessionModel(sessionID, fallback, event.model?.variant); + activeOriginals.set(sessionID, failed); + await switchSessionModel(sessionID, next, event.model?.variant); event.decision = { retry: true, delay: options.retry_delay_ms ?? 0 }; - notify("Model Fallback", `${original} -> ${fallback} (${event.error?.type ?? "retry"})`); + notify("Model Fallback", `${failed} -> ${next} (${event.error?.type ?? "retry"})`); } finally { retrying.delete(sessionID); } diff --git a/test/e2e.fallback.test.js b/test/e2e.fallback.test.js index a56d801..4d2ddf5 100644 --- a/test/e2e.fallback.test.js +++ b/test/e2e.fallback.test.js @@ -50,13 +50,18 @@ function freePort() { // chat completion for everything else. Every request is recorded in order. function startMock() { const requests = []; + // The chain test fails "fallback" on demand, after the 429-on-original tests. + const mock = { failFallback: false }; const server = createServer((req, res) => { let body = ""; req.on("data", (chunk) => (body += chunk)); req.on("end", () => { const parsed = body ? JSON.parse(body) : {}; const model = parsed.model ?? ""; - if (req.url.includes("/chat/completions") && model.includes("original")) { + if ( + req.url.includes("/chat/completions") && + (model.includes("original") || (model === "fallback" && mock.failFallback)) + ) { requests.push({ model, status: 429, stream: Boolean(parsed.stream) }); res.writeHead(429, { "content-type": "application/json" }); res.end( @@ -92,7 +97,9 @@ function startMock() { }); return new Promise((resolve, reject) => { server.on("error", reject); - server.listen(0, "127.0.0.1", () => resolve({ server, requests, port: server.address().port })); + server.listen(0, "127.0.0.1", () => + resolve({ server, requests, port: server.address().port, mock }), + ); }); } @@ -113,6 +120,7 @@ function startOpencode(envRoot, mockPort, apiPort) { models: { original: { name: "Original", variants: [{ id: "high" }] }, fallback: { name: "Fallback", variants: [{ id: "high" }] }, + fallback2: { name: "Fallback 2" }, }, }, }, @@ -120,7 +128,11 @@ function startOpencode(envRoot, mockPort, apiPort) { { package: repoRoot, options: { - mappings: { "mock/original": "mock/fallback", "mock/missing": "mock/fallback" }, + mappings: { + "mock/original": "mock/fallback", + "mock/missing": "mock/fallback", + "mock/fallback": "mock/fallback2", + }, notify_on_fallback: true, cooldown_seconds: 3600, }, @@ -335,6 +347,29 @@ describe.skipIf(!run)("e2e: fallback against a real opencode server", { timeout: const after = await state.client.session.get({ sessionID: session.id }); expect(after.model).toMatchObject({ providerID: "mock", id: "fallback", variant: "high" }); }); + + test("a failing fallback advances to the fallback's fallback", async () => { + state.mock.mock.failFallback = true; + const session = await state.client.session.create({ + title: "e2e chain", + model: { providerID: "mock", id: "original" }, + }); + await state.client.session.prompt({ sessionID: session.id, text: "hello chain" }); + await turnDone(state.client, session.id); + state.mock.mock.failFallback = false; + + 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: "fallback2" }); + expect( + state.mock.requests.some((request) => request.model === "fallback" && request.status === 429), + ).toBe(true); + expect( + state.mock.requests.some( + (request) => request.model === "fallback2" && request.status === 200, + ), + ).toBe(true); + }); }); if (!run) { diff --git a/test/router.test.js b/test/router.test.js index 9881094..0193379 100644 --- a/test/router.test.js +++ b/test/router.test.js @@ -4,6 +4,7 @@ import { createMappedFallbackRouter } from "../lib/router.js"; const ORIGINAL = "openai/gpt"; const FALLBACK = "azure/gpt"; +const THIRD = "azure/gpt-2"; beforeEach(() => { vi.useFakeTimers(); @@ -221,7 +222,7 @@ test("fallback failure reports an exhausted fallback without changing the decisi expect(event.decision).toEqual({ retry: false }); expect(ctx.session.switchModel).not.toHaveBeenCalled(); expect(ctx.warnings()).toEqual([ - { title: "Model Fallback Exhausted", message: `No mapped fallback left for ${ORIGINAL}` }, + { title: "Model Fallback Exhausted", message: `No mapped fallback left for ${FALLBACK}` }, ]); }); @@ -622,6 +623,144 @@ test("a model renamed by a modelID attribute is routable under its catalog key", expect(ctx.session.switchModel).not.toHaveBeenCalled(); }); +test("a failing fallback advances to the fallback's fallback", async () => { + const ctx = createContext({}, modelRef(FALLBACK)); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK, [FALLBACK]: THIRD }, + notify_on_fallback: false, + }); + + const event = retryEvent(FALLBACK, { status: 429, type: "rate-limit", message: "rate limit" }); + await router.retry(event); + + expect(event.decision).toEqual({ retry: true, delay: 0 }); + expect(ctx.session.switchModel).toHaveBeenCalledWith({ + sessionID: "session-1", + model: modelRef(THIRD), + }); + expect(await ctx.storage.get(cooldownKey(FALLBACK))).toMatchObject({ reason: "rate-limit" }); +}); + +test("the failure walk skips cooldown members", async () => { + const now = Date.now(); + const ctx = createContext( + { + [cooldownKey(ORIGINAL)]: cooldown(now - 1_000, now + 60_000), + [cooldownKey(FALLBACK)]: cooldown(now - 1_000, now + 60_000), + }, + modelRef(ORIGINAL), + ); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK, [FALLBACK]: THIRD }, + notify_on_fallback: false, + }); + + const event = retryEvent(ORIGINAL, { status: 429, type: "rate-limit", message: "rate limit" }); + await router.retry(event); + + expect(event.decision).toEqual({ retry: true, delay: 0 }); + expect(ctx.session.switchModel).toHaveBeenCalledWith({ + sessionID: "session-1", + model: modelRef(THIRD), + }); +}); + +test("the failure walk skips unavailable members", async () => { + const ctx = createContext({}, modelRef(ORIGINAL), { + availableModels: [ORIGINAL, THIRD], + }); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK, [FALLBACK]: THIRD }, + notify_on_fallback: false, + }); + + const event = retryEvent(ORIGINAL, { status: 429, type: "rate-limit", message: "rate limit" }); + await router.retry(event); + + expect(event.decision).toEqual({ retry: true, delay: 0 }); + expect(ctx.session.switchModel).toHaveBeenCalledWith({ + sessionID: "session-1", + model: modelRef(THIRD), + }); +}); + +test("a configured cycle truncates instead of ping-ponging", async () => { + const now = Date.now(); + const ctx = createContext( + { + [cooldownKey(ORIGINAL)]: cooldown(now - 1_000, now + 60_000), + [cooldownKey(FALLBACK)]: cooldown(now - 1_000, now + 60_000), + }, + modelRef(FALLBACK), + ); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK, [FALLBACK]: ORIGINAL }, + notify_on_fallback: false, + }); + + const event = retryEvent(FALLBACK, { status: 429, type: "rate-limit", message: "rate limit" }); + await router.retry(event); + + expect(event.decision).toEqual({ retry: false }); + expect(ctx.session.switchModel).not.toHaveBeenCalled(); +}); + +test("prompt routing walks the chain past cooldown members", async () => { + const now = Date.now(); + const ctx = createContext( + { + [cooldownKey(ORIGINAL)]: cooldown(now - 1_000, now + 60_000), + [cooldownKey(FALLBACK)]: cooldown(now - 1_000, now + 60_000), + }, + modelRef(ORIGINAL), + ); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK, [FALLBACK]: THIRD }, + }); + + await router.prompt(promptEvent("session-1")); + + expect(ctx.session.switchModel).toHaveBeenCalledWith({ + sessionID: "session-1", + model: modelRef(THIRD), + }); +}); + +test("recovery steps back one level at a time through the chain", async () => { + const ctx = createContext({}, modelRef(THIRD), { + messages: [{ type: "assistant", model: modelRef(ORIGINAL) }], + }); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK, [FALLBACK]: THIRD }, + }); + + await router.prompt(promptEvent("session-1")); + expect(ctx.session.switchModel).toHaveBeenLastCalledWith({ + sessionID: "session-1", + model: modelRef(FALLBACK), + }); + + ctx.sessionModel = modelRef(FALLBACK); + await router.prompt(promptEvent("session-1")); + expect(ctx.session.switchModel).toHaveBeenLastCalledWith({ + sessionID: "session-1", + model: modelRef(ORIGINAL), + }); +}); + +test("a pinned chain member is not yanked to its root without history", async () => { + const ctx = createContext({}, modelRef(FALLBACK), { + messages: [{ type: "assistant", model: modelRef(FALLBACK) }], + }); + const router = createMappedFallbackRouter(ctx, { + mappings: { [ORIGINAL]: FALLBACK, [FALLBACK]: THIRD }, + }); + + await router.prompt(promptEvent("session-1")); + + expect(ctx.session.switchModel).not.toHaveBeenCalled(); +}); + function promptEvent(sessionID) { return { sessionID, messageID: "msg-1", prompt: {}, delivery: "user" }; }