opencode icon indicating copy to clipboard operation
opencode copied to clipboard

github-copilot: Gemini model fails on directory wake/boot with "does not support Responses API" before async /models sync finishes

Open mehulparmariitr opened this issue 2 weeks ago • 5 comments

Description

When an OpenCode directory wakes up after location services evicted (or immediately on boot) and sends a prompt using github-copilot/gemini-4-hydrogen, the step fails with HTTP 400 (unsupported_api_for_model):

Session.StepFailedError: model gemini-4-hydrogen does not support Responses API.

From opencode.log and packages/core/src/plugin/provider/github-copilot.ts:

  • At location services booted (e.g. 16:12:44.176Z), ProviderRefresh.start loads Copilot's /models list asynchronously in the background (taking ~2.4s until the second provider.updated / model.updated at 16:12:46.563Z).
  • Before that sync completes, /api/provider/github-copilot exposes default package @opencode/ai/providers/openai/responses, and gemini-4-hydrogen is not in models.dev.
  • Any turn dispatched in that startup window sends gemini-4-hydrogen to /responses instead of /chat/completions, so Copilot rejects it with HTTP 400 (and retries inside SessionRunner.drain reuse the pre-sync route).
  • Once the background /models sync completes, /api/model shows gemini-4-hydrogen updated to @opencode/ai/providers/openai-compatible, and the next prompt succeeds normally.

Related: #53712, #53961 (#62034 fixed fallbackEndpoint for gemini-* in packages/core/src/github-copilot/models.ts and #63146 cached the login baseURL, but the pre-sync window before loaded.models arrives still hits this on config-overridden / non-models.dev Gemini models).

Plugins

None affecting providers (claude-mem local session plugin only)

OpenCode version

2.3.0

Steps to reproduce

  1. Set model: "github-copilot/gemini-4-hydrogen" with a providers.github-copilot.models["gemini-4-hydrogen"] entry (for example settings.reasoningEffort) using an authenticated GitHub Copilot account whose /models serves gemini-4-hydrogen on /chat/completions.
  2. Leave a directory idle until location services evicted (or restart opencode service).
  3. Send a prompt immediately on wake/boot before GithubCopilotPlugin's background /models sync finishes (~2–3s).
  4. Observe model gemini-4-hydrogen does not support Responses API. (400 unsupported_api_for_model). Sending another prompt a few seconds later succeeds once model.updated switches gemini-4-hydrogen to @opencode/ai/providers/openai-compatible.

Operating System

macOS 26.x (Darwin 25.6.0, arm64)

Terminal

Ghostty (xterm-ghostty, truecolor)

mehulparmariitr avatar Nov 14 '26 16:11 mehulparmariitr

Seen with a simulated model or a mock server, not a real provider; a maintainer should confirm.

Thanks for the detailed report. I reproduced this on 2.3.0, and it still happens on the latest dev (d759c54). A mock Copilot API stood in for the real one, since I don't have a Copilot account here.

Setup: gemini-4-hydrogen defined only under providers.github-copilot.models in the project config, and a Copilot credential pointing at the mock, whose /models answers after 3 seconds and lists the model on /chat/completions only.

  • Right after the directory boots, /api/model shows gemini-4-hydrogen with package @opencode/ai/providers/openai/responses and base URL https://api.githubcopilot.com. That URL is not the endpoint stored with the credential.
  • Once the /models sync completes, the same model switches to @opencode/ai/providers/openai-compatible on the credential's endpoint.

A prompt sent in that window went to the public host instead of the mock and failed there (401, because my token was fake). I couldn't see Copilot's own does not support Responses API 400 without a real account, but the route the model gets before the sync matches what you describe.

The script below reproduces it (it starts the mock itself). Related earlier reports of the same error: #53712 and #53961; #54208 changed the fallback route for gemini-* to chat completions.

Reproduction script (repro.sh)
#!/usr/bin/env bash
# Repro for #63956: config-only Copilot Gemini model is routed to Responses (and the
# public host) until the background Copilot /models sync finishes.
# Writes mock.ts: a mock Copilot API on :4999 whose /models answers after 3s.
# Uses `opencode` from PATH, or OC_DEV=<checkout> to run from source.
set -u
cd "$(dirname "$0")"
R=$PWD
export HOME=$R/home XDG_DATA_HOME=$R/home/.local/share XDG_CONFIG_HOME=$R/home/.config XDG_STATE_HOME=$R/home/.local/state XDG_CACHE_HOME=$R/home/.cache
rm -rf "$HOME"; mkdir -p "$HOME" proj
oc() {
  if [ -n "${OC_DEV:-}" ]; then
    bun --conditions=browser --preload="$OC_DEV/packages/tui/node_modules/@opentui/solid/scripts/preload.js" "$OC_DEV/packages/cli/src/index.ts" "$@"
  else opencode "$@"; fi
}
cat > proj/opencode.json <<'JSON'
{ "model": "github-copilot/gemini-4-hydrogen",
  "providers": { "github-copilot": { "models": { "gemini-4-hydrogen": { "settings": { "reasoningEffort": "low" } } } } } }
JSON
cat > mock.ts <<'TS'
// Mock Copilot API: /models is slow (MODELS_DELAY_MS), /responses rejects gemini, /chat/completions streams.
const delay = Number(process.env.MODELS_DELAY_MS ?? 3000)
const log = (...a: any[]) => console.log(new Date().toISOString(), ...a)
Bun.serve({
  port: 4999,
  async fetch(req) {
    const url = new URL(req.url)
    log(req.method, url.pathname)
    if (url.pathname.endsWith("/models")) {
      await Bun.sleep(delay)
      return Response.json({ data: [{ id: "gemini-4-hydrogen", name: "Gemini 4 Hydrogen", version: "gemini-4-hydrogen", model_picker_enabled: true, supported_endpoints: ["/chat/completions"], policy: { state: "enabled" }, capabilities: { family: "gemini-4", type: "chat", limits: { max_context_window_tokens: 128000, max_output_tokens: 8192, max_prompt_tokens: 120000 }, supports: { streaming: true, tool_calls: true } } }] })
    }
    if (url.pathname.endsWith("/responses")) {
      const body = await req.json().catch(() => ({}))
      log("responses model:", body.model)
      return Response.json({ error: { message: `model ${body.model} does not support Responses API.`, code: "unsupported_api_for_model" } }, { status: 400 })
    }
    if (url.pathname.endsWith("/chat/completions")) {
      const body = await req.json().catch(() => ({}))
      log("chat model:", body.model)
      const chunk = (d: any) => `data: ${JSON.stringify(d)}\n\n`
      const base = { id: "c1", object: "chat.completion.chunk", created: 1, model: body.model }
      const s = chunk({ ...base, choices: [{ index: 0, delta: { role: "assistant", content: "hello from chat completions" } }] }) +
        chunk({ ...base, choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage: { prompt_tokens: 1, completion_tokens: 1, total_tokens: 2 } }) + "data: [DONE]\n\n"
      return new Response(s, { headers: { "content-type": "text/event-stream" } })
    }
    return new Response("not found", { status: 404 })
  },
})
log("mock on 4999, models delay", delay)
TS
MODELS_DELAY_MS=3000 bun mock.ts > mock.log 2>&1 & MOCK=$!
sleep 1
(cd proj && oc serve --port 4096 --hostname 127.0.0.1 > ../serve.log 2>&1) & SRV=$!
for i in $(seq 1 120); do grep -q "server password" serve.log && break; sleep 0.5; done
P=$(sed -n 's/^server password //p' serve.log)
# Store a Copilot OAuth credential whose API endpoint is the mock, before the project directory boots.
curl -s -u opencode:$P -H 'content-type: application/json' -X POST http://127.0.0.1:4096/api/credential \
  -d '{"integrationID":"github-copilot","label":"mock","activate":true,"value":{"type":"oauth","methodID":"device","refresh":"gho_fake","access":"gho_fake","expires":0,"metadata":{"apiEndpoint":"http://127.0.0.1:4999"}}}' >/dev/null
show() {
  echo "== $(date -u +%T.%3N) $1"
  curl -s -u opencode:$P "http://127.0.0.1:4096/api/model?directory=$R/proj" | python3 -c "
import json,sys
for m in json.load(sys.stdin)['data']:
  if m['id']=='gemini-4-hydrogen': print('gemini-4-hydrogen:', m['package'], m.get('settings'))"
}
show "immediately after the directory boots (before /models answers)"
sleep 7
show "after the /models sync"
echo "== mock log"; cat mock.log
kill $SRV $MOCK 2>/dev/null; pkill -f "serve --port 4096" 2>/dev/null; true

Run it: bash repro.sh

opencodejr[bot] avatar Nov 14 '26 16:11 opencodejr[bot]

I reproduced the pre-discovery state with the real Config/Provider/Model services while /models is held pending: the config-only Gemini model inherits Responses and the public host.

Candidate fix (diff): apply the ID-based route after config seeds models, preserve API-model aliases, and keep explicit package/URL overrides last. No plugin-load wait is added.

Validation: 79 related tests pass; the three new cases fail on dev and pass 30 randomized repetitions here. bun run check passes. The broader config/model suite has the same snapshot-reload failure on both dev and this patch (349/350 pass). Injected Copilot API only; no real Copilot account tested. AI-assisted.

GitHub currently blocks another PR at the repository's 3-open-PR limit, so I'm sharing the branch here for review.

r266-tech avatar Nov 15 '26 00:11 r266-tech

Taking this one.

I traced the window on dev (38bd7378): the provider-level fold gives every copilot model the provider-level package, which the bundled models.dev snapshot makes @opencode/ai/providers/openai/responses (the most common package among copilot's models), with the public api.githubcopilot.com baseURL. A config-declared model such as gemini-4-hydrogen is added during config collapse, which happens after the provider fold and has no later re-route: the pre-sync routing loop in the copilot provider plugin only maps the models that existed at provider fold time. So the new model keeps the inherited openai/responses package against the public host until the first models sync completes, and Gemini 400s on /responses — matching the reported error. After the sync lands, CopilotModels.derive rebuilds the routes and the session self-heals.

Planned fix: move the pre-sync route mapping from the provider transform into the model transform (same guard as the current loop), so any model added by config collapse gets its route applied when model state refolds. I'll follow up with a PR.

ccclucky avatar Nov 15 '26 01:11 ccclucky

@ccclucky Please feel free to reuse the integration regressions from the candidate above. They hold /models pending and cover the credential endpoint, API aliases (fast → gpt-5-future), and provider/per-model package/URL overrides.

One ordering detail: config modelID currently lands in the late model transform, so moving the routing loop alone can still route an alias by its local ID. The candidate seeds it during the provider fold. I'll defer a competing PR while yours proceeds. AI-assisted.

r266-tech avatar Nov 15 '26 01:11 r266-tech

Thanks @r266-tech — the real-service repro and the offer of integration regressions are very helpful. My fix routes config-declared models through the pre-sync model transform (which always folds after the config plugin adds them), and I plan to reuse your integration tests as extra coverage when I open the PR.

ccclucky avatar Nov 15 '26 02:11 ccclucky