Following up on the bot's note that "the session.retry hook can only decide whether to retry and how long to wait, not which model to use. So this can't be built cleanly as a plugin yet."
I built it as a plugin anyway and have been running it on 2.4.2. It works, and the exercise narrowed the required core change to something quite small. Writing up what I hit, including three bugs that are all symptoms of the same missing primitive.
Related: #64222 adds fallback chains driven by time-based availability windows. That is complementary to this request — this is the error-driven case (429, quota, dead key), and the two should share the same chain representation rather than growing two config shapes.
It is buildable today, with two paths
Fast path — session.retry hook:
await ctx.session.hook("retry", (event) => {
if (!fallbackWorthy(event.error)) return
void ctx.session.switchModel({ sessionID, model: next }) // fire and forget
event.decision = { retry: true, delay: 3000 }
})
Safety net — when retries exhaust and the session halts, session.execution.failed plus a queued prompt resumes it:
for await (const event of ctx.event.subscribe({ types: ["session.execution.failed"] })) {
await ctx.session.switchModel({ sessionID, model: next })
await ctx.session.prompt({ sessionID, text: "Continue where you left off.", delivery: "queue" })
}
Verified end-to-end on a session pinned to a model with an exhausted free-tier limit: it switched through two models and completed the task with no user action.
Gap 1: the race the bot described
Because RetryDecision has no model field, the switch and the retry are two separate operations with no ordering guarantee. switchModel is async and the retry fires after delay. I use 3000 ms as a fudge factor. If the switch is slower than that, the retry goes out on the dead model and burns another attempt.
This is the whole reason it belongs in core: the plugin has to guess how long a state change takes.
Proposed minimal change
type RetryDecision =
| { retry: false }
| { retry: true; delay: number; model?: { providerID: string; id: string } }
The hook names the replacement atomically and the race disappears. Backwards-compatible union widening. This is the "small addition" the bot referred to.
Gap 2: attempt is not a useful bound across a chain
Related and worth calling out. The retry hook gets attempt, but that counter is shared across every model in a fallback chain, so a plugin cannot tell "this is the third model" from "this is the third retry of the same model".
I originally wrote if (event.attempt > 4) return and it silently truncated an eight-model chain at the fifth entry. The fix was to bound by chain length instead, but that is a workaround. If the decision carried the model, an attemptsPerModel notion would fall out naturally.
Gap 3: two events racing cause a switch loop
This one is a genuine bug that produced a visible ping-pong:
model-switched: refuseless/x → tokenharbor/y
model-switched: tokenharbor/y → refuseless/x
model-switched: refuseless/x → tokenharbor/y
all within ~2 seconds. Cause: I updated the plugin's notion of "current model" before switchModel resolved, so a session.execution.failed arriving mid-switch read the stale value and started a second switch. Fixed with a per-session lock that clears on the next experimental.model.resolve.
A { retry: true, model } decision removes the class of bug entirely, because there is no window between "decide to switch" and "retry on the new model" for a second event to land in.
Gap 4: the halt loses step context
After retries exhaust, the session halts. The only recovery a plugin has is session.execution.failed plus a queued prompt. It works, but:
- it appears in the transcript as a new user turn rather than a continuation
- the in-flight step context is gone, so the model re-orients instead of resuming
- any pending tool call in that step is dropped
Keeping the agent loop alive across a model switch — rather than halting and re-prompting — would be worth more than the queue hack. A model on the retry decision gets this for free.
Provider cooldown (echoing @moritzWa)
Confirmed necessary, and it needs to outlive the process. Without it, every new chat walks the chain from the top and burns a failed request on each provider already known to be dead. I persist cooldowns through ctx.storage with a TTL: 30 min for quota/credit/dead-key, 2 min for a rate limit. A successful run clears the entry.
Detecting a provider that has no credentials
Worth documenting because it was not obvious and I got it wrong first.
ctx.integration.list() returns a { location, data } envelope, not a bare array, so the obvious list.filter(...) sees nothing. The reliable call is per provider:
const active = await ctx.integration.connection.active(providerID) // null when unconfigured
Skipping those before any request is valuable: a provider can sit at the top of a chain before its key is added, costing nothing. My first two attempts silently failed and wasted a request per turn against a 401.
Free-first ordering
The concrete reason I built this: I want free tiers tried before spending anything, then the cheapest paid model, with a specific provider order inside each tier.
{
"model": "tokenharbor/deepseek-v4.1-flash:free",
"fallback": {
"models": [
"tokenharbor/mimo-v2.6-flash:free",
"openrouter/google/gemma-4-31b-it:free",
"opencode/deepseek-v4.1-flash-free",
"refuseless/deepseek-v4.1-flash-fast",
"opencode/deepseek-v4.1-flash",
"openrouter/~z-ai/glm-flash-latest"
],
"cooldown": "30m"
}
}
Two notes on the shape:
- A per-model chain reads better than a top-level array, because "what to fall back to" depends on what you fell back from.
- Walk forward from the failed model rather than restarting at index 0, so a provider that is down is not retried just because it is listed first.
- The chain has to stay shorter than the retry allowance (ten attempts per step today). Nine entries is about the practical ceiling, which is a third argument for the counter being per model.
This is the explicit answer to #63958
#63958 reports that OpenCode's current implicit fallback switched a user from a free model to a paid glm-5.2 they had deliberately excluded, costing $12.94 in a day.
A configured chain fixes that by construction: the chain is authored by the user, so a paid model is only ever reached because the user listed it. Everything not in the chain is out of bounds. My plugin additionally refuses to leave the chain at all — if every entry is exhausted it stops and surfaces the error rather than improvising.
That distinction seems worth encoding in core: implicit fallback (pick something that works) versus explicit fallback (walk the list I gave you). The bug in #63958 is the former; this request and #64222 are the latter.
Triggers I ended up using
Status codes are inconsistent across providers, so message matching is unavoidable:
- status 401, 402, 403, 404, 429
quota, credit, balance, billing, insufficient, usage limit, limit reached, daily limit
rate limit, too many requests, overloaded, capacity
no such model, model not found, invalid api key, unavailable
Explicitly excluded and checked first: context overflow, content filter, user abort. Those must still surface normally.
Happy to open a PR for the RetryDecision.model widening if that shape is acceptable. It is a small change and I can include the reference plugin as a test fixture — it is a single file with no dependencies, and it now covers free-tier-first ordering, persistent cooldowns, credential-aware skipping, and the resume path.