Skip to content
Open
10 changes: 7 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ only document constraints and rules an agent would get wrong without being told.
## Architecture

Server plugin exported from `index.js` via `Plugin.define` (`@opencode/plugin`)
with logic split into `lib/`.
with logic split into `lib/`. The TUI is exported from `tui.js` via
`@opencode/plugin/tui`; it calls the shared `rpc.js` contract for recent usage
and error state. The TUI uses `@opentui/solid/jsx-dev-runtime` directly to keep
the package as plain ESM without a build step.

## Key invariants

Expand All @@ -22,8 +25,9 @@ with logic split into `lib/`.
the switch must happen before the request is built.
- Global model cooldowns are persisted with the V2 `ctx.storage` domain (already
namespaced per plugin id); do not add per-session fallback state.
- Configuration is read from plugin `ctx.options`; do not add dotfile-based
config reads.
- Configuration is read from plugin `ctx.options`. `/fallback-config` opens the
global `opencode.json(c)` in an external editor and validates the saved source
through `lib/config-file.js`; do not add a separate configuration source.
- No build step. Plain ESM JavaScript, shipped as-is.

## Scripts
Expand Down
57 changes: 46 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ Mapped model fallback router for [OpenCode](https://opencode.ai/).
There are situations where you may want to use the quota that comes with a
subscription first, then fall back to an API pay-as-you-go model only when that
subscription-backed model is rate-limited or usage-limited. You can solve that
with a local proxy, but maintaining a proxy server is often not worth it if all
you need is a simple one-to-one fallback inside OpenCode. This plugin handles
that routing directly in OpenCode.
with a local proxy, but maintaining a proxy server is often not worth it for
simple fallback routing inside OpenCode. This plugin handles that routing
directly in OpenCode, including chained and circular fallback routes.

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
Expand All @@ -21,14 +21,15 @@ routes back to the original model after the cooldown expires.

## Install

Add to your OpenCode V2 config at `~/.config/opencode/opencode.json`:
Install with OpenCode V2's plugin manager:

```json
{
"plugins": [{ "package": "@renjfk/opencode-model-fallback" }]
}
```bash
opencode plugin add @renjfk/opencode-model-fallback
```

This adds the package to `~/.config/opencode/opencode.json` or `opencode.jsonc`.
Both its server and TUI parts load automatically.

`package` may be an npm package name or an absolute path to a local plugin
directory (the directory resolves its server entry through `package.json`
`exports["."]`).
Expand All @@ -39,7 +40,7 @@ If OpenCode keeps using an older published version of the plugin after an
update, clear the cached package and restart OpenCode:

```bash
rm -rf ~/.cache/opencode/packages/@renjfk/
rm -rf ~/.cache/opencode/npm/@renjfk/
```

## Configuration
Expand All @@ -62,13 +63,44 @@ If you want to set plugin options, add them to the entry:
}
```

## TUI sidebar and configuration

The sidebar shows only the activated route containing the current session's
selected model, using rounded cards ordered by fallback priority. Unrelated
routes are hidden, and the cards update automatically when fallback switches
models. Each route shows:

- mapping routes in configured priority order, including chained fallbacks;
- `[Recent]` and relative-time tags on the latest model's priority card, plus its reasoning variant; and
- a compact error row only for models with a recorded provider error.

Mappings are always shown, including before any prompt has run. Used rows are
hidden for unused and currently recent models. Activity is kept in server memory and resets
when the OpenCode service restarts; configured model cooldowns remain persisted
through plugin storage.

Run `/fallback-config` to open the global `opencode.json(c)` in `$VISUAL`,
`$EDITOR`, or `vi` when neither is set. Set the plugin's `editor` option to use a
specific command, such as `code --wait`. OpenCode suspends its renderer while the
editor runs and resumes afterward.

After the editor exits successfully, the plugin validates the model mappings,
retry budget, cooldown, HTTP statuses, error regexes, and notification setting.
It reports every detected issue in a TUI toast. The JSONC file remains under your
control; the plugin does not rewrite it.

Fallback switches preserve the current reasoning variant when the target model
supports it. Unsupported variants are omitted instead of causing a model error.

## Options

- `mappings`: map original model IDs to fallback model IDs.
- `retry_on_errors`: retryable HTTP status codes. Defaults to `429`.
- `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`.
- `max_fallback_attempts`: maximum fallback switches in one turn. Defaults to `5`, allowing two full attempts through a three-model circular route before stopping.
- `notify_on_fallback`: log fallback/recovery notices. Defaults to `true`.
- `editor`: external editor command for `/fallback-config`. Defaults to `$VISUAL`, `$EDITOR`, then `vi`; use a wait-compatible command such as `code --wait`.

## How it works

Expand All @@ -84,8 +116,11 @@ Global model cooldowns are persisted with OpenCode's plugin storage
sessions avoid immediately retrying a model that has just failed. When the
cooldown expires, mapped requests are routed back to the original model.

The plugin does not load balance, race models, or retry through a chain. Each
mapping is one original model to one fallback model.
The plugin does not load balance or race models. Each mapping is one original
model to one fallback model; chained mappings such as `A -> B` and `B -> C`
continue through the next mapping when a fallback also fails. Add `C -> A` to
make the route circular. Circular routes stop after `max_fallback_attempts`
(default `5`), producing `A -> B -> C -> A -> B -> C -> stop`.

## Scenarios

Expand Down
13 changes: 12 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
import { Plugin } from "@opencode/plugin";

import { createMappedFallbackRouter } from "./lib/router.js";
import { ModelFallback } from "./rpc.js";

export default Plugin.define({
id: "model-fallback",
async setup(ctx) {
const router = createMappedFallbackRouter(ctx, ctx.options);
return router.setup(ctx);
const status = () => ({ ...router.status(), mappings: ctx.options.mappings ?? {} });
const registration = await ctx.rpc.register(ModelFallback, {
status: async () => status(),
});
const unsubscribe = router.subscribe(() => registration.events.emit("updated", status()));
const cleanup = await router.setup(ctx);
return async () => {
unsubscribe();
await cleanup();
await registration.dispose();
};
},
});
65 changes: 65 additions & 0 deletions lib/activity.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
function errorRecord(error, attempt) {
const message =
typeof error?.message === "string" ? error.message.slice(0, 500) : "Provider request failed";
return {
at: Date.now(),
type: typeof error?.type === "string" ? error.type : "provider.error",
message,
status: typeof error?.status === "number" ? error.status : undefined,
attempt,
};
}

export function createActivity() {
const models = new Map();
let latest;
let onUpdate;

function changed() {
if (onUpdate) void onUpdate(snapshot());
}

function used(model, sessionID, variant) {
if (!model) return;
const at = Date.now();
const current = models.get(model) ?? {};
models.set(model, { ...current, lastUsedAt: at, sessionID, variant });
latest = { model, sessionID, variant, at };
changed();
}

function failed(model, error, attempt, sessionID, variant) {
if (!model) return;
const current = models.get(model) ?? {};
models.set(model, {
...current,
lastUsedAt: Date.now(),
sessionID,
variant,
lastError: errorRecord(error, attempt),
});
latest = { model, sessionID, variant, at: Date.now() };
changed();
}

function snapshot() {
return JSON.parse(
JSON.stringify({
latest,
models: Object.fromEntries(models),
}),
);
}

return {
used,
failed,
snapshot,
subscribe(callback) {
onUpdate = callback;
return () => {
if (onUpdate === callback) onUpdate = undefined;
};
},
};
}
101 changes: 101 additions & 0 deletions lib/config-file.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { readFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { parse } from "jsonc-parser";

async function configPath(env, home) {
const directory = path.join(env.XDG_CONFIG_HOME ?? path.join(home, ".config"), "opencode");
for (const name of ["opencode.jsonc", "opencode.json"]) {
const candidate = path.join(directory, name);
try {
return { path: candidate, source: await readFile(candidate, "utf8") };
} catch {}
}
throw new Error("Global opencode.jsonc or opencode.json was not found");
}

function pluginIndex(config) {
const plugins = Array.isArray(config?.plugins) ? config.plugins : [];
return plugins.findIndex((plugin) => {
const name = typeof plugin === "string" ? plugin : plugin?.package;
return typeof name === "string" && name.includes("opencode-model-fallback");
});
}

export async function readFallbackConfig(options = {}) {
return configPath(options.env ?? process.env, options.home ?? os.homedir());
}

export function validateFallbackSource(source) {
const errors = [];
const parseErrors = [];
const config = parse(source, parseErrors, { allowTrailingComma: true });
if (parseErrors.length) errors.push("Configuration is not valid JSONC");
const index = pluginIndex(config);
if (index < 0) errors.push("The model-fallback plugin is not in the global configuration");
const options = index >= 0 ? config.plugins[index]?.options : undefined;
if (!options || typeof options !== "object" || Array.isArray(options)) {
errors.push("Fallback plugin options must be an object");
}

const mappings = options?.mappings;
if (!mappings || typeof mappings !== "object" || Array.isArray(mappings)) {
errors.push("options.mappings must be an object");
} else {
const entries = Object.entries(mappings);
if (!entries.length) errors.push("Add at least one fallback mapping");
for (const [from, to] of entries) {
if (!from.includes("/") || from.startsWith("/") || from.endsWith("/")) {
errors.push(`Invalid source model: ${from}`);
}
if (typeof to !== "string" || !to.includes("/") || to.startsWith("/") || to.endsWith("/")) {
errors.push(`Invalid fallback for ${from}`);
}
if (from === to) errors.push(`A model cannot fall back to itself: ${from}`);
}
}

if (options?.max_fallback_attempts !== undefined) {
const value = options.max_fallback_attempts;
if (!Number.isInteger(value) || value < 0 || value > 100) {
errors.push("max_fallback_attempts must be an integer from 0 to 100");
}
}
if (options?.cooldown_seconds !== undefined) {
const value = options.cooldown_seconds;
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
errors.push("cooldown_seconds must be a non-negative number");
}
}
if (options?.retry_on_errors !== undefined) {
const value = options.retry_on_errors;
if (
!Array.isArray(value) ||
value.some((status) => !Number.isInteger(status) || status < 100 || status > 599)
) {
errors.push("retry_on_errors must contain HTTP status codes from 100 to 599");
}
}
if (options?.retryable_error_patterns !== undefined) {
const patterns = options.retryable_error_patterns;
if (!Array.isArray(patterns) || patterns.some((pattern) => typeof pattern !== "string")) {
errors.push("retryable_error_patterns must contain strings");
} else {
for (const pattern of patterns) {
try {
new RegExp(pattern, "i");
} catch {
errors.push(`Invalid retryable error regex: ${pattern}`);
}
}
}
}
if (
options?.notify_on_fallback !== undefined &&
typeof options.notify_on_fallback !== "boolean"
) {
errors.push("notify_on_fallback must be true or false");
}

return { valid: errors.length === 0, errors, options };
}
9 changes: 6 additions & 3 deletions lib/models.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
export function modelRef(model) {
export function modelRef(model, variant) {
const [providerID, ...modelParts] = model.split("/");
if (!providerID || modelParts.length === 0) return undefined;
return { providerID, id: modelParts.join("/") };
const idAndVariant = modelParts.join("/");
const [id, inlineVariant] = idAndVariant.split("#");
const selectedVariant = inlineVariant || variant;
if (!providerID || !id) return undefined;
return { providerID, id, ...(selectedVariant ? { variant: selectedVariant } : {}) };
}

export function modelRefString(ref) {
Expand Down
1 change: 1 addition & 0 deletions lib/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const DEFAULT_OPTIONS = {
retry_on_errors: [429],
retryable_error_patterns: ["rate.?limit"],
cooldown_seconds: 3600,
max_fallback_attempts: 5,
notify_on_fallback: true,
};

Expand Down
Loading