v2: new session sometimes gets the built-in default model (opencode/big-pickle) instead of the configured model
Description
On opencode v2 (2.4.1), a new session sometimes gets the built-in default model opencode/big-pickle instead of the model set in the config. The configured small_model is still used for the title, so the title request reaches the configured provider and the turn goes to opencode/big-pickle.
We see this in automated end-to-end tests that drive the TUI in a sandboxed VM without internet access. There, opencode/big-pickle is unreachable, so the turn never completes. It happens in about 1 of 10 runs, more often under host load. In the other runs the configured model is used.
Setup
opencode serve --hostname 127.0.0.1 --port 4096runs as a background service.- The TUI attaches with
opencode --server http://127.0.0.1:4096 /workspace. - A prompt is typed shortly after the TUI is drawn.
~/.config/opencode/opencode.json:
{
"provider": {
"stub": {
"npm": "@ai-sdk/openai-compatible",
"options": { "baseURL": "http://<local-endpoint>/v1", "apiKey": "<dummy>" },
"models": { "stub": {}, "stub-title": {} }
}
},
"model": "stub/stub",
"small_model": "stub/stub-title"
}
What the server reports for a failing run
GET /api/session:
{"agent":"build","model":{"id":"big-pickle","providerID":"opencode","variant":"default"},"title":"stub-title", ...}
GET /api/session/<id>/message, as the user message followed by the assistant message:
{"type":"user","text":"journeys core first turn", ...}
{"type":"assistant","model":{"id":"big-pickle","providerID":"opencode"},"content":[],
"retry":{"attempt":9,"error":{"type":"provider.transport","message":"ECONNREFUSED: Unable to connect. Is the computer able to access the url?"}}}
What we tried
"enabled_providers": ["stub"]: the session still getsopencode/big-pickle. The turn now fails immediately withprovider.no-route: Model unavailable: opencode/big-pickleinstead of retrying.OPENCODE_DISABLE_MODELS_FETCH=1on the server, which removes the failing models.dev fetch from the log: it still happens.- Pinning the model: we found neither a
--modelflag on the v2 TUI nor a model-selection state file to pin it.
Expected
A new session uses the configured model (here stub/stub), or at least never a provider that enabled_providers excludes. It looks like a race: a session created before the configured model is known takes the built-in default.
Version
opencode 2.4.1 (opencode.ai/v2/install), Linux x86_64.
Thanks for the detailed report. I reproduced this on 2.4.1 through the server API, and it still happens on the latest dev (4bb997e).
With your config started fresh, the server briefly lists only the built-in opencode provider while it loads the project, for about 0.1 s after the first client request. During that window GET /api/model/default returns opencode/big-pickle. This happens even with "enabled_providers": ["stub"]. A moment later both endpoints correctly show stub/stub.
The script below starts opencode serve, waits for that window, and creates a session with the model the server reports, as the TUI does when you submit a prompt. The session is stored as {"id":"big-pickle","providerID":"opencode","variant":"default"}. With enabled_providers the turn ends with provider.no-route: Model unavailable: opencode/big-pickle, the same result as yours. A prompt sent to a session created without a model ran on stub/stub, so the problem is the catalog the server publishes during startup.
I didn't manage to make the TUI itself submit inside that window. In my attached-TUI runs, its model list was always corrected before I typed. With a loaded host and the TUI as the first client to hit the server, I expect it to land in the window now and then, as you saw.
Reproduction script (api_race.py)
#!/usr/bin/env python3
"""Reproduce #66110 against the server API of the released CLI, no TUI and no model needed.
Starts `opencode serve` with a config whose `model` is a custom provider (`stub/stub`), then, as a client
would right after connecting, watches GET /api/model and /api/model/default and sends a prompt to a new
session. While the project is loading, the server briefly lists only the built-in `opencode` provider and
reports `opencode/big-pickle` as the default model, even with `enabled_providers: ["stub"]`; a turn started
then runs on opencode/big-pickle.
Usage: OPENCODE=opencode ENABLED_ONLY=1 RUNS=3 python3 api_race.py"""
import os, subprocess, time, json, base64, urllib.request, tempfile, shlex
OPENCODE = shlex.split(os.environ.get("OPENCODE", "opencode")); PORT = int(os.environ.get("PORT", "4099")); PW = "repro-pass"
root = tempfile.mkdtemp(prefix="oc66110a.", dir="/tmp/opencode" if os.path.isdir("/tmp/opencode") else None)
env = dict(os.environ, OPENCODE_PASSWORD=PW, OPENCODE_DISABLE_MODELS_FETCH="1",
XDG_CONFIG_HOME=f"{root}/config", XDG_DATA_HOME=f"{root}/data", XDG_STATE_HOME=f"{root}/state",
XDG_CACHE_HOME=f"{root}/cache", HOME=f"{root}/home")
for d in ("config/opencode", "home", "proj"): os.makedirs(f"{root}/{d}", exist_ok=True)
cfg = {"provider": {"stub": {"npm": "@ai-sdk/openai-compatible",
"options": {"baseURL": "http://127.0.0.1:9/v1", "apiKey": "dummy"}, "models": {"stub": {}, "stub-title": {}}}},
"model": "stub/stub", "small_model": "stub/stub-title"}
if os.environ.get("ENABLED_ONLY"): cfg["enabled_providers"] = ["stub"]
json.dump(cfg, open(f"{root}/config/opencode/opencode.json", "w"))
print("config:", json.dumps(cfg))
auth = "Basic " + base64.b64encode(f"opencode:{PW}".encode()).decode()
def api(path, body=None):
req = urllib.request.Request(f"http://127.0.0.1:{PORT}{path}", headers={"authorization": auth, "content-type": "application/json"},
data=None if body is None else json.dumps(body).encode(), method="GET" if body is None else "POST")
return json.load(urllib.request.urlopen(req, timeout=10))
for run in range(int(os.environ.get("RUNS", "3"))):
srv = subprocess.Popen(OPENCODE + ["serve", "--hostname", "127.0.0.1", "--port", str(PORT)], cwd=f"{root}/proj",
env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
t0 = time.time(); sid = None; sent = False
while time.time() - t0 < 15 and not sent:
try:
if sid is None: sid = api("/api/session", {})["data"]["id"]
models = api("/api/model")["data"]; default = api("/api/model/default")["data"]
if models:
print(f"run {run} t={time.time()-t0:.2f}s /api/model providers={sorted({m['providerID'] for m in models})} "
f"/api/model/default={default and default['providerID'] + '/' + default['id']}", flush=True)
# Like the TUI, create the new session with the model the server reports for it
# (the TUI passes its selection to session.create).
if os.environ.get("CLIENT_PICKS", "1") == "1" and default:
sid = api("/api/session", {"model": {"providerID": default["providerID"], "id": default["id"]}})["data"]["id"]
api(f"/api/session/{sid}/prompt", {"text": "journeys core first turn"}); sent = True
except Exception: time.sleep(0.01)
time.sleep(3)
print(f"run {run} session model={json.dumps(api(f'/api/session/{sid}')['data'].get('model'))}", flush=True)
msgs = api(f"/api/session/{sid}/message")["data"]
for m in msgs:
if m.get("type") != "user":
err = (m.get("retry") or {}).get("error") or m.get("error")
print(f"run {run} assistant model={(m.get('model') or {}).get('providerID')}/{(m.get('model') or {}).get('id')} type={m.get('type')} error={json.dumps(err)}", flush=True)
srv.terminate(); srv.wait()
subprocess.run(["rm", "-rf", f"{root}/data", f"{root}/state", f"{root}/cache"])
Run it: python3 api_race.py
One more way to hit this, from #66128 (closed as a duplicate): starting the TUI with --prompt reproduces it on 2.4.0. Both of my runs of opencode --standalone --prompt "@file.md review this" /path/to/project created the session on opencode/big-pickle and failed with Model unavailable: opencode/big-pickle. My config uses enabled_providers with one custom OpenAI-compatible provider, and the model and per-agent models also come through OPENCODE_CONFIG_CONTENT. Without --prompt, the same command gets the configured model. --prompt submits at startup, so it lands in the window you describe.
The same --prompt invocation worked on 2.3.2, which may help narrow down where it broke. In my log, the error comes about 70 ms after the first provider.updated/model.updated pair, and a second pair arrives about 1 s later.
[!NOTE] AI disclosure: this was prepared with Claude Code (Opus 5.5) at my behest; I tested its application in practice.
I traced this far enough to say where the window comes from. There are two different fixes depending on which contract you want, so writing it down before anyone codes.
The mechanism
Model.default()returns the configured default only whendata.defaultModelresolves to an enabled model; otherwise it falls back tovalue.available.find(supportsText)—packages/core/src/model.ts:310-315.data.defaultModelis set by the config plugin, not at boot:sources.defaultModel = Config.latest(…, "model"), thenmodels.default.set(…)—packages/core/src/config/plugin/provider.ts:93,:99-101.- Before that plugin settles, the catalog is the built-in one and
default()answers with its first text model, which isopencode/big-picklebecausePREFERRED_FREEputs it first —model.ts:337-350. enabled_providerscannot help: it is config too, applied by the same plugin.
This is not undocumented. The model list says "The snapshot may precede initial plugin settlement" (packages/protocol/src/groups/model.ts:28), and the HTTP layer is already gated on status.ready (packages/server/src/process.ts:137), which is reached before plugins settle. The default route's success type is already Schema.UndefinedOr(Model.Info) (:35), so "not known yet" is a legal answer today.
Two options
B — don't substitute. default() stops falling back to the first available model once configuration has named one: the Model layer records that the provider/model config plugin has applied, and default() returns undefined until the named model resolves. The endpoint already allows undefined; session creation without a model is fine, and ModelResolver.fallback() (packages/core/src/model-resolver.ts:554-557) resolves it at the first turn, when config is present. This also fixes the second half of the bug: a configured default that is temporarily unresolvable currently becomes big-pickle instead of an error.
A — gate. Hold /api/model/default (and maybe model.list) until the first config-driven snapshot arrives, bounded, then answer. No wrong answer, but a client asking at boot waits or gets 503, and the route's own description argues against that.
C — independent of both, and worth doing either way. A session that already stored {providerID: "opencode", id: "big-pickle"} stays broken after the window closes. At prompt time, if the stored model's provider is not enabled, re-resolve and update the session, or fail with a message naming the configured model. That is what makes --prompt recoverable without a reconnect.
I would take B + C: B removes the wrong answer at the source, C repairs sessions created inside the window. B needs one decision from a maintainer — an explicit "config has been applied" signal on the Model layer (or permission to infer it from the transforms already applied). Gating on a timer would be a guess and I would not ship one.
Happy to write whichever you pick, with a test that drives --prompt (deterministic, per @reagle's comment) or a unit test on default() with and without the config transform applied.
Follow-up on my own suggestion: I built option B to measure it instead of arguing for it, and it is larger than I claimed. Correcting my recommendation.
What B actually costs
Gating Model.default() on "configuration has been applied" needs a signal, and the config plugin applies config through the public plugin ModelEditor — so the signal is a new method on that interface, in both surfaces (packages/plugin/src/effect/model.ts, packages/plugin/src/promise/model.ts), plus the adapters that implement it (packages/core/src/plugin/host.ts, and the test host at packages/core/test/plugin/host.ts). That is a public plugin API addition for an internal readiness concern.
Then the behaviour change is wider than "decline to guess": with B applied, bun run test catalog model-resolver config/provider config/config gives 168 pass, 5 fail, and the five are the product decisions themselves:
falls back to newest available model when no default is configureddefaults to big-pickle when only free OpenCode models are availablekeeps the newest default when a paid model is availableuses a transform-provided default model until that transform is replacedignores a configured default on a disabled provider
So "never answer before config" cannot be added without also deciding what a first run with no configured model should do, and what a transform-provided default means. That is not a bug fix, it is a product call — exactly the thing I should not settle in a PR.
Revised recommendation: A, then C
A — hold /api/model/default (bounded) until the first config-driven snapshot lands — leaves Model.default() and every one of those tests untouched, needs no plugin API change, and the route already permits undefined for a late answer. It fixes the reported failure without re-litigating first-run behaviour.
C — a session that already stored the built-in model inside the window still needs repairing at prompt time — stays as it was, and is where the user-visible recovery lives.
If a maintainer does want B, the measurement above is the shape of the change: one public editor method, four implementations, five tests re-specified. I am happy to write it that way, but I would rather not pick for you.
Another reproduction from a launcher that runs opencode --standalone --prompt "..." with OPENCODE_CONFIG_CONTENT='{"model":"fixture/sonnet#xhigh", ...}' and a config-defined openai-compatible provider. On v2.4.1 and on dev 5ad8bac2, every prefilled launch created the session on opencode/big-pickle and never reached the provider. Typed prompts used fixture/sonnet with xhigh. With #66182 (8a2e47aa) compiled, prefilled launches used the requested model and variant (xhigh, low, and no variant all matched), and no false warning appeared. One gap remains: when the configured model is missing from the catalog after plugins have activated, the prompt is sent to the first catalog model instead.