Skip to content

Commit 630c1aa

Browse files
committed
connect-opencode: write the catalog, because opencode never reads /v1/models
opencode builds its picker from models.dev plus the static `models` map in opencode.json. It does not call a custom provider's /v1/models — discovery is hardcoded to Ollama, LM Studio and vLLM at their default ports. A provider written with only npm + baseURL shows up as "Provider not found" with an empty list. Verified on 1.18.3, where `opencode models archrouter` listed nothing at all; general discovery is still an open PR (anomalyco/opencode#42660), so there is nothing to wait for. So the static list is now the default and --variants becomes --no-models, which only exists to clean up an older install. The key is resolved from ARCHROUTER_KEY, then first-key.txt, then whatever /connect saved, and written into options.apiKey: auth is required by default, so /v1/models answers 401 without it — including the probe this command runs to fetch that list, which is why --variants died on every auth-on install with "router not answering". Models opencode cannot reach are still listed, with the measurements kept in modelCaps.js and opencodeConfig.js rather than hidden: muse-spark-*-contributor- free and jev-1.13-free answer only on /v1/responses and /v1/messages and 500 on the chat path, and ling-3.0-flash-fin-free (400) plus ling-3.1-flash-free (429) are reproducibly dead upstream, 3/3 attempts each on 2026-10-04. The other 7 answer 200 through /v1/chat/completions. 206 tests pass: test-p0 52, test-auth-store 6, test-setup-sh 40, test-uninstall 48, test-setup-flow 60. The suite carried a test whose name asserted the false premise above; it is inverted now, and two more cover the apiKey and the default shape. Not tested: WARP registration end to end (it burns real Cloudflare slots), and opencode's own picker — the catalog was confirmed through `opencode --pure models`, because a local plugin's dependency install deadlocks the plain CLI (anomalyco/opencode#47212, unrelated to this repo).
1 parent c68464f commit 630c1aa

5 files changed

Lines changed: 211 additions & 37 deletions

File tree

‎README.md‎

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ archrouter rollback # restore pre-update v
109109
archrouter warp-setup [--force] # 2 WARP accounts + sing-box configs (idempotent; --force burns 2 new slots)
110110
archrouter warp-reset [a|b] # bounce one backend (pool coordinator hook)
111111
archrouter key [name] # mint another API key
112-
archrouter connect-opencode [--variants] # point opencode at this router
112+
archrouter connect-opencode [--no-models|--no-key] # point opencode at this router
113113
archrouter uninstall [--yes|--purge] # remove what install put on the machine
114114
archrouter doctor # env / ports / bins / upstream check
115115
```
@@ -160,6 +160,45 @@ answers only on `/v1/responses`, `jev-1.13-free` only on `/v1/messages`, the
160160
rest on `/v1/chat/completions`. `GET /v1/models` reports the correct one per
161161
model in `capabilities.kind`.
162162

163+
### Pointing opencode at it
164+
165+
```bash
166+
archrouter connect-opencode
167+
```
168+
169+
This writes the `archrouter` provider into `~/.config/opencode/opencode.json`
170+
**with a static `models` block** (ids + effort levels from `modelCaps`), plus
171+
`options.apiKey` when a key can be resolved — `ARCHROUTER_KEY`, else the key
172+
printed at install, else the one `/connect` already saved.
173+
174+
The static block is not a shortcut, it is the only shape opencode honours.
175+
opencode builds its picker from models.dev plus the `models` map in
176+
`opencode.json`, and it never calls a custom provider's `/v1/models`;
177+
auto-discovery is hardcoded to Ollama, LM Studio and vLLM at their default
178+
ports. A provider written with only `npm` + `baseURL` shows up as
179+
`Provider not found` with an empty list — verified on opencode 1.18.3. General
180+
discovery is still an open PR (`anomalyco/opencode#42660`), so nothing to wait
181+
for. `--no-models` exists only to clean up an older install; it writes a
182+
provider opencode cannot use.
183+
184+
The cost is that a new upstream free model needs another `connect-opencode`
185+
run. Check it with:
186+
187+
```bash
188+
opencode models archrouter
189+
```
190+
191+
The catalog is the full live list, so a few entries will fail when picked —
192+
recorded rather than hidden:
193+
194+
| model | what happens in opencode |
195+
| --- | --- |
196+
| `muse-spark-*-contributor-free`, `jev-1.13-free` | 500 — they only answer on `/v1/responses` and `/v1/messages`, while `@ai-sdk/openai-compatible` posts to `/v1/chat/completions` |
197+
| `ling-3.0-flash-fin-free` | 400 `Endpoint is unavailable` (upstream, reproducible 3/3) |
198+
| `ling-3.1-flash-free` | 429 `Endpoint is unavailable` (upstream, reproducible 3/3) |
199+
200+
The other 7 are confirmed working through opencode.
201+
163202
### API keys
164203

165204
Keys live in the dashboard (`http://127.0.0.1:20399/` → **API keys**), not in

‎archrouter.js‎

Lines changed: 77 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
* value, contradicting its own comment.
2323
*
2424
* Usage: archrouter start|stop|restart|status|logs [name]|update
25-
* [--check|--no-restart|--force|--full]|rollback|uninstall [--yes|--purge]|key [name]|connect-opencode [--variants]|warp-setup [--force]
25+
* [--check|--no-restart|--force|--full]|rollback|uninstall [--yes|--purge]|key [name]|connect-opencode [--no-models|--no-key]|warp-setup [--force]
2626
* |warp-reset [a|b]|doctor|version
2727
*/
2828

@@ -453,39 +453,94 @@ function cmdKey(nameArg) {
453453
log(`${store.countActiveApiKeys()} active key(s). The router requires a key on its next start.`);
454454
}
455455

456-
// Points opencode at this router. Default writes npm + baseURL only, which is
457-
// enough for opencode to read the catalog from /v1/models itself; --variants
458-
// additionally writes the static list with per-model effort levels. Needs no
459-
// running router in the default mode.
456+
// Points opencode at this router.
457+
//
458+
// The catalog opencode shows is built from models.dev plus the STATIC `models`
459+
// map in opencode.json. opencode never calls a custom provider's /v1/models —
460+
// auto-discovery is hardcoded to Ollama/LM Studio/vLLM at their default ports —
461+
// so a provider written without a `models` block shows up as
462+
// "Provider not found" with an empty list. Writing the static list is therefore
463+
// the default, not an opt-in extra.
464+
//
465+
// The key goes into options.apiKey when one can be resolved, because auth is
466+
// required by default and that includes the probe below: without it /v1/models
467+
// answers 401 and this command has nothing to write.
460468
function cmdConnectOpencode(flags) {
461-
let variants = false;
469+
let includeModels = true;
470+
let writeKey = true;
462471
for (const f of flags) {
463-
if (f === "--variants") variants = true;
464-
else die(`usage: ${PROG} connect-opencode [--variants]`);
472+
if (f === "--no-models") includeModels = false;
473+
else if (f === "--no-key") writeKey = false;
474+
else die(`usage: ${PROG} connect-opencode [--no-models] [--no-key]`);
465475
}
466476
const oc = require(path.join(REPO, "server", "lib", "opencodeConfig.js"));
467-
const modelIds = [];
468-
if (variants) {
469-
const list = httpGetSync(`http://${API_HOST}:${API_PORT}/v1/models`);
470-
const data = list?.data || [];
471-
for (const m of data) modelIds.push(m.id);
472-
if (!modelIds.length) die(`router not answering on :${API_PORT} — start it first, or drop --variants`);
473-
}
474-
const fragment = oc.buildFragment({ host: API_HOST, port: API_PORT, modelIds, includeModels: variants });
477+
const { key: apiKey, from: keyFrom } = resolveClientKey(oc);
478+
// The probe needs the same credential opencode will use, otherwise the
479+
// catalog comes back empty on any install with auth on.
480+
const list = apiKey ? httpGetSync(`http://${API_HOST}:${API_PORT}/v1/models`, apiKey) : null;
481+
const data = list?.data || [];
482+
if (includeModels) {
483+
if (!data.length) {
484+
const authed = apiKey ? " with the resolved key" : " (no key resolved — see below)";
485+
die(`router not answering on :${API_PORT}${authed}. Start it, fix the key, or pass --no-key.`);
486+
}
487+
}
488+
const modelIds = data.map((m) => m.id);
489+
const fragment = oc.buildFragment({
490+
host: API_HOST,
491+
port: API_PORT,
492+
modelIds,
493+
includeModels,
494+
apiKey: writeKey ? apiKey : "",
495+
});
475496
const result = oc.writeConfig(fragment);
476497
if (!result.ok) die(result.error);
477498
log(`opencode provider written to ${result.file} (${result.mode})`);
478499
if (result.backup) log(`backup: ${result.backup}`);
479-
if (variants) log(`${result.models} models with effort levels.`);
480-
else log("opencode now reads the model list from /v1/models, so new free models appear on their own.");
481-
log("in opencode: /connect -> Other -> archrouter -> paste your key (see `archrouter key`).");
500+
if (includeModels) {
501+
log(`${result.models} models in the catalog, with effort levels where the model accepts them.`);
502+
log("static list: a new upstream free model needs another `connect-opencode` run.");
503+
} else {
504+
log("no models block written — opencode will NOT discover them from /v1/models.");
505+
log("the picker will stay empty for this provider. Re-run without --no-models.");
506+
}
507+
if (writeKey && apiKey) log(`apiKey written into options, taken from ${keyFrom}.`);
508+
else if (writeKey) log("no apiKey found — set one with `/connect -> Other -> archrouter` or re-run after `archrouter key`.");
509+
}
510+
511+
// The credential opencode should use against this router, most explicit source
512+
// first: ARCHROUTER_KEY, then the key printed at install, then whatever
513+
// /connect already saved for this provider id. Returns { key: "", from: "" } when
514+
// nothing is available — the caller reports that instead of guessing.
515+
function resolveClientKey(oc) {
516+
const env = (process.env.ARCHROUTER_KEY || "").trim();
517+
if (env) return { key: env, from: "ARCHROUTER_KEY" };
518+
const firstKeyFile = path.join(DATA, "first-key.txt");
519+
try {
520+
if (fs.existsSync(firstKeyFile)) {
521+
const k = fs.readFileSync(firstKeyFile, "utf8").trim();
522+
if (k) return { key: k, from: firstKeyFile };
523+
}
524+
} catch { /* unreadable — try the next source */ }
525+
const authFile = typeof oc?.authPath === "function" ? oc.authPath() : null;
526+
if (authFile) {
527+
try {
528+
if (fs.existsSync(authFile)) {
529+
const stored = JSON.parse(fs.readFileSync(authFile, "utf8"));
530+
const k = stored?.[oc.PROVIDER_ID]?.key;
531+
if (typeof k === "string" && k.trim()) return { key: k.trim(), from: authFile };
532+
}
533+
} catch { /* malformed store — not fatal, just no key */ }
534+
}
535+
return { key: "", from: "" };
482536
}
483537

484-
function httpGetSync(url) {
538+
function httpGetSync(url, apiKey = "") {
539+
const init = apiKey ? `{ headers: { Authorization: "Bearer " + ${JSON.stringify(apiKey)} } }` : "";
485540
try {
486541
const r = spawnSync(process.execPath, ["-e", `
487542
const u = ${JSON.stringify(url)};
488-
fetch(u).then(r => r.json()).then(j => { process.stdout.write(JSON.stringify(j)); })
543+
fetch(u, ${init}).then(r => r.json()).then(j => { process.stdout.write(JSON.stringify(j)); })
489544
.catch(() => process.exit(1));
490545
`], { encoding: "utf8", timeout: 20000 });
491546
if (r.status !== 0) return null;
@@ -875,7 +930,7 @@ async function cmdWarpReset(idArg) {
875930

876931
/* ---------------- dispatch ---------------- */
877932

878-
const HELP = `Usage: ${PROG} start|stop|restart|status|logs [name]|update [--check|--no-restart|--force|--full]|rollback|uninstall [--yes|--purge]|key [name]|connect-opencode [--variants]|warp-setup [--force]|warp-reset [a|b]|doctor|version`;
933+
const HELP = `Usage: ${PROG} start|stop|restart|status|logs [name]|update [--check|--no-restart|--force|--full]|rollback|uninstall [--yes|--purge]|key [name]|connect-opencode [--no-models|--no-key]|warp-setup [--force]|warp-reset [a|b]|doctor|version`;
879934

880935
async function main() {
881936
const argv = process.argv.slice(2);

‎server/lib/modelCaps.js‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@ const CAPS = {
2222
"mimo-v2.5-free": { kind: "chat", reasoning: true, efforts: ["low", "medium", "high"] },
2323
"mimo-v2.6-flash-free": { kind: "chat", reasoning: true, efforts: ["low", "medium", "high"] },
2424
"space-bunny-free": { kind: "chat", reasoning: true, efforts: ["low", "medium", "high"] },
25+
// Upstream keeps listing it but the chat path is dead: 3/3 attempts on
26+
// 2026-10-04 gave 400 "Endpoint is unavailable". Stays "chat" on purpose so it
27+
// is not silently hidden — see the ling note below.
2528
"ling-3.0-flash-fin-free": { kind: "chat", reasoning: true, efforts: ["low", "medium", "high"] },
2629
"nemotron-3.5-lightning-free": { kind: "chat", reasoning: true, efforts: ["low", "medium", "high"] },
2730
"nemotron-3-ultra-free": { kind: "chat", reasoning: true, efforts: ["low", "medium", "high"] },
@@ -38,6 +41,15 @@ const CAPS = {
3841

3942
// Upstream answered 400 "Model is unavailable" on 2026-09-30.
4043
"deepseek-v4-flash-free": { kind: "unavailable", reasoning: false, efforts: [] },
44+
45+
// Left as chat on purpose — NOT to be unlisted. Measured 2026-10-04, three
46+
// identical attempts each through /v1/chat/completions:
47+
// ling-3.0-flash-fin-free -> 400 "Upstream request failed: Endpoint is unavailable"
48+
// ling-3.1-flash-free -> 429, same message
49+
// Reproducible, so it is upstream, not archrouter. They stay in the catalog so
50+
// the failure is visible where it happens; flip them to "unavailable" only if
51+
// upstream stops listing them or you would rather the picker not offer them.
52+
"ling-3.1-flash-free": { kind: "chat", reasoning: true, efforts: ["low", "medium", "high"] },
4153
};
4254

4355
// Unknown model: assume the chat path with reasoning and the two levels that

‎server/lib/opencodeConfig.js‎

Lines changed: 55 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,32 @@
22
/*
33
* opencodeConfig.js — build the opencode.json provider entry for archrouter.
44
*
5-
* Two shapes, both one command to apply:
5+
* includeModels: true — the model list plus per-model `variants`, generated from
6+
* the live list and modelCaps so only effort levels a model really accepts
7+
* are advertised. This is the DEFAULT and the only shape opencode actually
8+
* uses.
69
*
7-
* includeModels: false (default here) — npm + baseURL only. opencode then
8-
* calls archrouter's /v1/models and builds the catalog itself, so a new
9-
* free model shows up without touching this file. The trade-off: effort
10-
* levels are config-driven, so the picker has no low/medium/high.
10+
* includeModels: false — npm + baseURL only, no `models` block. Kept only so an
11+
* existing install can be cleaned up. **This does not work.** opencode builds
12+
* its catalog from models.dev plus the static `models` map in opencode.json
13+
* and never calls a custom provider's /v1/models; auto-discovery is
14+
* hardcoded to Ollama, LM Studio and vLLM at their default ports. A provider
15+
* written this way shows up as "Provider not found" with an empty list.
16+
* General discovery is still an open PR (anomalyco/opencode#42660), so do
17+
* not build on it. Verified on opencode 1.18.3.
1118
*
12-
* includeModels: true — the model list plus per-model `variants`, generated
13-
* from the live list and modelCaps so only effort levels a model really
14-
* accepts are advertised. Static, but gives the effort picker.
19+
* The list is static, so a new upstream free model needs a re-run of
20+
* `archrouter connect-opencode`. That is the cost of opencode's config-driven
21+
* catalog, not something this file can work around.
22+
*
23+
* The catalog is the full live list, minus models upstream marks unavailable.
24+
* A few of them cannot be reached through opencode (see the note in
25+
* buildProvider) and are listed anyway — recorded, not hidden.
26+
*
27+
* `apiKey` is written into options when we can resolve one, because with auth
28+
* required every route including /v1/models rejects an unauthenticated request.
29+
* opencode also reads a credential saved via /connect; either source works, but
30+
* an explicit key here survives a wiped auth store.
1531
*
1632
* Only our own key is touched; every other provider, agent and MCP entry in
1733
* the user's file is preserved as-is.
@@ -34,11 +50,26 @@ function configPath() {
3450
return path.join(base, "opencode.json");
3551
}
3652

37-
function buildProvider({ host = "127.0.0.1", port = 20399, modelIds = [], includeModels = true } = {}) {
53+
// Where /connect stores credentials. opencode uses ~/.local/share on Windows
54+
// too (the archrouter shim already lives in ~/.local/bin), so the shape is the
55+
// same everywhere; XDG_DATA_HOME is honoured on unix. Best-effort: a null or
56+
// missing path just means "no key available", never an error.
57+
function authPath() {
58+
const home = process.env.HOME || (() => { try { return os.homedir(); } catch { return null; } })();
59+
if (!home) return null;
60+
const base = process.platform === "win32"
61+
? path.join(home, ".local", "share")
62+
: (process.env.XDG_DATA_HOME || path.join(home, ".local", "share"));
63+
return path.join(base, "opencode", "auth.json");
64+
}
65+
66+
function buildProvider({ host = "127.0.0.1", port = 20399, modelIds = [], includeModels = true, apiKey = "" } = {}) {
3867
const provider = {
3968
npm: PROVIDER_NPM,
69+
name: "archrouter",
4070
options: { baseURL: `http://${host}:${port}/v1` },
4171
};
72+
if (apiKey) provider.options.apiKey = apiKey;
4273
if (!includeModels) {
4374
// Explicitly undefined, so mergeFragment drops a models block written by
4475
// an earlier run instead of leaving a stale list behind.
@@ -49,6 +80,20 @@ function buildProvider({ host = "127.0.0.1", port = 20399, modelIds = [], includ
4980
for (const raw of modelIds) {
5081
const id = String(raw).replace(/^(oc|combo)\//, "");
5182
const caps = capsFor(id);
83+
// Only upstream-unavailable models are dropped. Everything else is listed,
84+
// including the models opencode cannot actually reach through this provider:
85+
//
86+
// @ai-sdk/openai-compatible always posts to /v1/chat/completions, so a
87+
// caps.kind of "responses" (muse-spark-*-contributor-free) or "systemone"
88+
// (jev-1.13-free) gets a 500 from upstream on the chat path. They are kept
89+
// in the catalog on purpose — the user asked for the full list, and hiding
90+
// them makes a router limitation look like a missing model. Reach them on
91+
// their own endpoints (/v1/responses, /v1/messages) instead.
92+
//
93+
// Also observed 2026-10-02/04, upstream-side and not archrouter's doing:
94+
// ling-3.0-flash-fin-free answers 400 "Endpoint is unavailable" and
95+
// ling-3.1-flash-free answers 429 with the same text, reproducibly. Both stay
96+
// listed; they may come back when upstream rotates them.
5297
if (caps.kind === "unavailable") continue;
5398
const entry = { name: id };
5499
const variants = variantsFor(id);
@@ -102,4 +147,4 @@ function writeConfig(fragment, { file = configPath() } = {}) {
102147
};
103148
}
104149

105-
module.exports = { PROVIDER_ID, PROVIDER_NPM, configPath, buildProvider, buildFragment, mergeFragment, writeConfig };
150+
module.exports = { PROVIDER_ID, PROVIDER_NPM, configPath, authPath, buildProvider, buildFragment, mergeFragment, writeConfig };

0 commit comments

Comments
 (0)