diff --git a/README.md b/README.md index de2955e..ee26960 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,14 @@ 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. 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 Mappings are one-to-one. If the fallback model also hits a retryable failure, 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 4b44c73..cbac1fc 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) { @@ -18,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 631b434..4a5bd9e 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,101 @@ 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 Map( + models + .filter((model) => model.enabled !== false) + .map((model) => [ + // 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)), + ]), + ); + } 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); + } + + // 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 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) { @@ -68,20 +170,47 @@ 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); + 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. + const pin = await agentPinnedModel(session?.agent); + requested = modelRefString(pin); + effort = pin?.variant; + if (!requested || !hasMapping(requested)) return; + } else if (!shouldRoute(requested)) { + return; + } const original = mappedOriginal(requested); 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 }); } @@ -121,7 +250,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 { @@ -133,6 +262,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 +283,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..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" }] }, }, }, }, @@ -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,43 @@ 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); + }); + + 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 67021fb..9881094 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,366 @@ 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(); +}); + +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" }, + }); +}); +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" }; } @@ -290,7 +650,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 +663,34 @@ function createContext(initial = {}, sessionModel = modelRef(ORIGINAL)) { subscribeCalls: 0, subscribeTypes: undefined, sessionModel, + agentID: overrides.agentID ?? "build", + messages: overrides.messages ?? [], + availableModels: overrides.availableModels ?? [ + ORIGINAL, + FALLBACK, + "openai/gpt-2", + "azure/gpt-2", + ], + model: { + list: vi.fn(async () => ({ + data: ctx.availableModels.map((entry) => { + const [name, variants] = entry.split("|"); + const [providerID, modelID] = name.split("/"); + return { + providerID, + modelID, + enabled: true, + variants: (variants ?? "") + .split(",") + .filter(Boolean) + .map((id) => ({ id })), + }; + }), + })), + }, + agent: { + get: vi.fn(async ({ agentID }) => overrides.agent ?? { id: agentID }), + }, storage: { async get(key) { return data.get(key); @@ -315,8 +703,13 @@ 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 () => {}), + context: vi.fn(async () => ctx.messages), hook: vi.fn(async (name, callback) => { hooks[name].push(callback); return {