From f1aa32014f85aeca94a7d8a2e0164c3f659c9855 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Wed, 2 Dec 2026 22:55:48 +0700 Subject: [PATCH 1/2] fix(models): retry a cold catalogue and never cache it empty A freshly spawned `opencode serve` answers `/api/model` with an empty list for a moment after it reports readiness. The gateway cached that answer for OPENCODE_MODEL_CACHE_TTL_MS, so for the next five minutes every request failed with `404 model_not_found` for models that do exist; only `GET /v1/models?refresh=true` recovered (observed against opencode 2.4.3). Retry an empty model list the way an empty agent list was already retried, and leave the catalogue uncached while it holds no models, so the next request picks them up as soon as the provider registers them. --- src/upstream/models.ts | 78 ++++++++++++++++++++++++++++---------- test/openai-models.test.ts | 68 ++++++++++++++++++++++++++++++++- 2 files changed, 126 insertions(+), 20 deletions(-) diff --git a/src/upstream/models.ts b/src/upstream/models.ts index 6aea50d..5395659 100644 --- a/src/upstream/models.ts +++ b/src/upstream/models.ts @@ -57,17 +57,33 @@ export class ModelRegistry { this.#client.listProviders().catch(() => [] as OpencodeProviderInfo[]), this.#client.listAgents().catch(() => [] as OpencodeAgentInfo[]), ]); - // A freshly started OpenCode server can answer `/api/agent` with an empty - // list before its built-in agents are registered; retry once instead of - // caching that empty result for the whole TTL. - const resolvedAgents = - agents.length === 0 ? await this.#retryAgents() : agents; - const catalog: ModelCatalog = { models, providers, agents: resolvedAgents, fetchedAt: Date.now() }; - this.#catalog = catalog; - this.#log.debug( - { models: models.length, agents: resolvedAgents.length }, - "refreshed model catalog", - ); + // A freshly started OpenCode server reports readiness before its providers + // and built-in agents are registered, so the first `/api/model` or + // `/api/agent` call can answer an empty list. Retry briefly instead of + // caching that answer for the whole TTL. + const settled = await this.#retryEmpty(models, agents); + const catalog: ModelCatalog = { + models: settled.models, + providers, + agents: settled.agents, + fetchedAt: Date.now(), + }; + // An empty model list is never a usable catalogue: do not cache it, so the + // next request picks the models up as soon as the provider registers them + // (previously every request failed with `model_not_found` for the full + // cache TTL). + this.#catalog = catalog.models.length > 0 ? catalog : undefined; + if (catalog.models.length === 0) { + this.#log.warn( + { agents: catalog.agents.length }, + "OpenCode reported no models; the catalogue will be retried on the next request", + ); + } else { + this.#log.debug( + { models: catalog.models.length, agents: catalog.agents.length }, + "refreshed model catalog", + ); + } return catalog; })().finally(() => { this.#inFlight = undefined; @@ -76,17 +92,41 @@ export class ModelRegistry { return this.#inFlight; } - async #retryAgents(): Promise { - for (const delayMs of [500, 1_500]) { + /** + * Re-read the parts of the catalogue that can arrive empty right after the + * server starts. + * + * Both lists are retried independently, with short delays, so a cold start + * costs at most about a second before the caller sees the real answer. + */ + async #retryEmpty( + models: OpencodeModelInfo[], + agents: OpencodeAgentInfo[], + ): Promise<{ models: OpencodeModelInfo[]; agents: OpencodeAgentInfo[] }> { + let currentModels = models; + let currentAgents = agents; + + for (const delayMs of [250, 750]) { + if (currentModels.length > 0 && currentAgents.length > 0) break; await new Promise((resolve) => setTimeout(resolve, delayMs)); - try { - const agents = await this.#client.listAgents(); - if (agents.length > 0) return agents; - } catch { - /* keep retrying */ + + if (currentModels.length === 0) { + try { + currentModels = await this.#client.listModels(); + } catch { + /* keep retrying */ + } + } + if (currentAgents.length === 0) { + try { + currentAgents = await this.#client.listAgents(); + } catch { + /* keep retrying */ + } } } - return []; + + return { models: currentModels, agents: currentAgents }; } async list(): Promise { diff --git a/test/openai-models.test.ts b/test/openai-models.test.ts index db3f94b..fff4932 100644 --- a/test/openai-models.test.ts +++ b/test/openai-models.test.ts @@ -2,8 +2,12 @@ * Unit tests for the OpenAI-compatible model listing surface. */ import { describe, expect, it } from "vitest"; +import { createLogger } from "../src/logger.js"; import { buildServer } from "../src/server.js"; -import { createTestContext } from "./helpers/context.js"; +import type { OpencodeClient } from "../src/upstream/client.js"; +import { ModelRegistry } from "../src/upstream/models.js"; +import type { OpencodeAgentInfo } from "../src/types/opencode.js"; +import { createTestContext, defaultModels, testConfig } from "./helpers/context.js"; const AUTH = { authorization: "Bearer test-key" }; @@ -106,6 +110,68 @@ describe("GET /v1/models", () => { }); }); +describe("ModelRegistry catalogue loading", () => { + function registry(client: Partial): ModelRegistry { + const config = testConfig({ modelCacheTtlMs: 60_000 }); + return new ModelRegistry(client as unknown as OpencodeClient, config, createLogger(config)); + } + + const agent: OpencodeAgentInfo = { id: "build", name: "Build", mode: "primary", hidden: false, request: {} }; + + it("retries the model list when a cold server reports none", async () => { + const models = defaultModels(); + let calls = 0; + const reg = registry({ + listModels: async () => { + calls += 1; + return calls === 1 ? [] : models; + }, + listProviders: async () => [], + listAgents: async () => [agent], + }); + + // `opencode serve` answers the first /api/model before its providers are + // registered; the old code cached that empty list for the whole TTL and + // every request failed with model_not_found. + const catalog = await reg.catalog(); + expect(calls).toBeGreaterThan(1); + expect(catalog.models).toHaveLength(models.length); + }); + + it("does not cache an empty catalogue", async () => { + let calls = 0; + const reg = registry({ + listModels: async () => { + calls += 1; + return []; + }, + listProviders: async () => [], + listAgents: async () => [], + }); + + expect((await reg.catalog()).models).toHaveLength(0); + expect(reg.cached).toBeUndefined(); + + const callsAfterFirst = calls; + await reg.catalog(); + expect(calls).toBeGreaterThan(callsAfterFirst); + }); + + it("still retries an empty agent list", async () => { + let agentCalls = 0; + const reg = registry({ + listModels: async () => defaultModels(), + listProviders: async () => [], + listAgents: async () => { + agentCalls += 1; + return agentCalls === 1 ? [] : [agent]; + }, + }); + + expect((await reg.catalog()).agents).toHaveLength(1); + }); +}); + describe("GET /v1/models/:id", () => { it("returns a single entry with the full capability block for a bare id", async () => { const app = await buildServer(createTestContext()); From fe63dd9f6151361ab97f7d44499c84de9a718ed4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ph=E1=BA=A1m=20V=C4=83n=20=C4=90=E1=BB=8Bnh?= Date: Wed, 2 Dec 2026 22:56:01 +0700 Subject: [PATCH 2/2] docs(models): describe the cold-start catalogue behaviour Record that the catalogue is retried and never cached empty, that opencode 2.4.3 was re-verified (spawn output, /api/model, /api/provider, /api/agent and the model ids are unchanged), and add the matching troubleshooting row for a 404 model_not_found right after startup. --- README.md | 3 ++- docs/API.md | 4 ++++ docs/ARCHITECTURE.md | 7 +++++++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index c28fc17..5141690 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ existing OpenAI or Anthropic SDK at it by changing only the base URL. * **Node.js >= 20.11** (verified on Node 26) * **pnpm** (the repository ships a `pnpm-lock.yaml`) * An installed **`opencode` CLI 2.x** on `PATH`, or an explicit path through - `OPENCODE_BIN` (verified against **2.3.2**) + `OPENCODE_BIN` (verified against **2.3.2** and **2.4.3**) * Network access for the OpenCode runtime to reach its model providers ## Quick start @@ -643,6 +643,7 @@ opencode-api/ # package name; the project is "OpenCode API" | No first token, then `504 timeout_error` | The model never produced a delta within `OPENCODE_FIRST_TOKEN_TIMEOUT_MS` | Raise `OPENCODE_FIRST_TOKEN_TIMEOUT_MS`, retry, or switch model; check `/logs/opencode-*.log`. | | Stream ends with an `error` frame and no output | Upstream step failed mid-stream | The HTTP status was already `200`; inspect the frame's `error.message`. Model-unavailable errors are transient. | | `EADDRINUSE` on startup | Port 20123 is taken | Set `PORT` (or stop the other process). The *internal* upstream port is separate and auto-retries. | +| `404 model_not_found` for a model that `GET /v1/models` lists | A cold upstream had not registered its models yet and an old build cached the empty list | The gateway retries and never caches an empty catalogue; `GET /v1/models?refresh=true` forces an immediate reload | | `400 unsupported_modality` | The model cannot accept that media type | Pick a model whose `capabilities.input` includes it (`GET /v1/models`). | | `400` about attachment URI or file roots | Local files disabled, or the path escapes the allowed roots | Enable `OPENCODE_ALLOW_LOCAL_FILES` and/or add the directory to `OPENCODE_ALLOWED_FILE_ROOTS`. | | `501` from `/v1/embeddings` | Expected: OpenCode has no embedding model | Route embeddings to a dedicated provider. | diff --git a/docs/API.md b/docs/API.md index 89420e4..e561092 100644 --- a/docs/API.md +++ b/docs/API.md @@ -670,6 +670,10 @@ non-OpenAI fields are gateway extensions placed next to the standard keys. back to the current Unix time in seconds when the field is missing or zero. * The list is cached for `OPENCODE_MODEL_CACHE_TTL_MS` (default 5 min). Add `?refresh=true` to force a catalog reload (`GET /v1/models?refresh=true`). +* A cold `opencode serve` reports readiness before its providers are + registered, so the first `/api/model` answer can be an empty list. The gateway + retries briefly and **never caches an empty catalogue**, so the models appear as + soon as the provider registers them instead of failing for the whole TTL. ### curl diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 369c0fa..bdac69c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -66,6 +66,13 @@ opencode serve --hostname 127.0.0.1 --port `video`. The gateway must **reject** unsupported modalities with HTTP 400. * There is exactly one provider in a default install: `opencode` (`@opencode/ai/providers/openai-compatible`), holding the free-tier models. +* A freshly spawned `opencode serve` answers `/api/model` (and `/api/agent`) with + an empty list for a moment after reporting readiness. `ModelRegistry` retries + both lists briefly and never caches a catalogue without models, so a cold + gateway cannot serve `model_not_found` for a model that exists. +* Re-verified against **opencode 2.4.3** (2026-12-02): spawn/readiness output, + `/api/model`, `/api/provider`, `/api/agent` and the model ids are unchanged + from 2.3.2; only the cold-start timing above differs in practice. ### 2.3 Sessions and prompts