Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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,
Expand Down
4 changes: 3 additions & 1 deletion lib/models.js
Original file line number Diff line number Diff line change
@@ -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) {
Expand Down
5 changes: 4 additions & 1 deletion lib/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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;
}
151 changes: 142 additions & 9 deletions lib/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand All @@ -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) {
Expand Down Expand Up @@ -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 });
}

Expand Down Expand Up @@ -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 {
Expand All @@ -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) {
Expand All @@ -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);
}
Expand Down
43 changes: 40 additions & 3 deletions test/e2e.fallback.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -111,16 +111,16 @@ 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" }] },
},
},
},
plugins: [
{
package: repoRoot,
options: {
mappings: { "mock/original": "mock/fallback" },
mappings: { "mock/original": "mock/fallback", "mock/missing": "mock/fallback" },
notify_on_fallback: true,
cooldown_seconds: 3600,
},
Expand Down Expand Up @@ -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) {
Expand Down
Loading