Files
magpie/internal/provider/opencode_go_free.go
T
yetone 02727188a4 gateway: a Zen free model asked on OpenCode Go is asked at Zen's free tier, else the refusal says where it is served (51bit.eth)
51bit.eth (Discord #general) ran Claude Code through magpie with
OpenCode's free models on a provider named OpenCode Go
(opencode.ai/zen/go). Every request failed "400 OpenCode Go: Upstream
request failed: Model is unavailable.", and a header of their own
(x-opencode-session) didn't help. The same models worked in OpenCode.

Cause: OpenCode's two gateways serve different free models. Zen's free
tier (/zen, the public key) serves the -free models and big-pickle; Go
(/zen/go, a Go key) serves only beam-free and iceman-contributor-free
(its /models on 2026-11-02). Go answers any model it doesn't serve 400
"Model is unavailable." before it reads the key. A user ends up with a
Zen free model under Go by typing it, or because a Go key /models
refuses makes the provider list models.dev's opencode-go catalog,
which names free models Go doesn't serve (#4900, not changed here).

What changed:
- provider.RetryOpenCodeFreeOnZen, called in forwardOnce for OpenCode
  URLs beside RetryZhipuCoding: a 400 "Model is unavailable" from Go
  for a model OpenCodeFree calls free is asked once more at Zen's free
  tier on the same API (openCodeGoToZenFree: /zen/go/v1/... and
  /inference/go/... to OpenCodeFreeURL's /inference/openai|anthropic),
  with the public key in Authorization (and x-api-key on Anthropic),
  never the user's Go key. Zen's 2xx is returned as is.
- Refused at Zen too, Go's 400 keeps its words and adds what Zen said
  and where the model is served: under the OpenCode Zen provider,
  which needs no key. A model that isn't free isn't asked at Zen; its
  400 says to pick one the OpenCode Go provider lists.
- docs/subsystems/providers-accounts.md: a row beside the GLM Coding
  Plan one.

Run (mote, through mote-run):
- go test ./internal/provider -run 'OpenCode|Zen' and
  ./internal/gateway -run 'OpenCodeGo|ZenFree': ok, at the pushed head
  after the rebase too.
- gofmt -l: clean. GOOS=linux and GOOS=windows go vet ./internal/provider
  ./internal/gateway: ok.
- go test ./internal/provider -count=1 -timeout 45m: ok (113.9s).
  go test ./internal/gateway -count=1 -timeout 45m: one red,
  TestCodexPoolSaysTheClientsVersion, which is #4807 (open, red in full
  runs on mote; this change touches no Codex path). Output added there.
- Real: a built magpie serve on mote, sandbox HOME, port 3591, an
  opencode-go provider with a made-up key, Claude Code-shaped
  /v1/messages:
  - deepseek-v4.1-flash-free (Zen's): Go 400, then asked at
    /inference/openai/v1/chat/completions with the public key; Zen
    answered 429 FreeUsageLimitError (#3491), and the message names
    both and the OpenCode Zen provider.
  - cat-jam-free (in the catalog, served by neither): Go 400, Zen 400,
    message says where.
  - glm-5.3 (Go's, paid): "Invalid credential" as before, Zen not asked.

Broken by hand:
- Retry call removed from forwardOnce: TestOpenCodeGoFreeModelAskedAtZen
  and TestOpenCodeGoUnavailableSaysWhere red (old message, one request).
- Key swap removed: TestOpenCodeGoFreeModelAskedAtZen red, Zen asked
  with "Bearer sk-go-users-own".

Not tried:
- A working Go key (the owner's is expired), so beam-free on Go
  end to end is only the fake.
- A Zen free reply end to end: from mote Zen's free tier answers 429
  FreeUsageLimitError to magpie with the built-in OpenCode Zen
  provider too (#3491).
- Gemini protocol: not asked at Zen (OpenCode has no Gemini free URL).
2026-11-02 17:08:45 +08:00

126 lines
4.9 KiB
Go

package provider
import (
"bytes"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/tidwall/gjson"
)
// OpenCode's two gateways serve different free models. Zen's free tier
// (…/zen) serves its -free models, big-pickle and the rest models.dev's
// opencode prices at nothing, to anyone OpenCode is signed out as (the
// public key, OpenCodeAnonymousKey); Go (…/zen/go) serves a few of its
// own (beam-free and iceman-contributor-free on 2026-11-02) to a Go key
// alone. Asked a model it doesn't serve, Go answers 400 "Upstream request
// failed: Model is unavailable." before it looks at the key. So a free
// model of Zen's asked on an OpenCode Go provider — what a user who wants
// "OpenCode's free models", as OpenCode serves them signed out, ends up
// with when they add the provider named OpenCode Go (51bit.eth on Discord,
// in Claude Code: every request failed so, and a header of their own
// didn't help) — is asked again at Zen's free tier with the public key,
// which is where OpenCode itself asks it. Refused there too, the refusal
// says what each gateway said and where the model is served.
// openCodeUnavailable is whether b is the refusal OpenCode's gateway
// gives a model it doesn't serve.
func openCodeUnavailable(status int, b []byte) bool {
return status == http.StatusBadRequest && strings.Contains(apiError(b, ""), "Model is unavailable")
}
// openCodeGoToZenFree is the URL at Zen's free tier of a request on proto
// that went to Go's gateway at u, "" when u isn't Go's: …/zen/go/v1/… and
// …/inference/go/v1/… are Zen's …/zen/v1/… asked where OpenCode 2 asks the
// free tier (OpenCodeFreeURL), and Go's inference URLs by API
// (…/inference/go/openai/v1/…) are Zen's beside them.
func openCodeGoToZenFree(u string, proto Protocol) string {
pu, err := url.Parse(u)
if err != nil || openCodeGateway(u) != "go" {
return ""
}
seg := strings.SplitN(strings.TrimPrefix(pu.Path, "/"), "/", 3) // zen|inference, go, rest
rest := ""
if len(seg) == 3 {
rest = "/" + seg[2]
}
if strings.HasPrefix(rest, "/openai/") || strings.HasPrefix(rest, "/anthropic/") {
pu.Path = "/inference" + rest
pu.RawPath = ""
return pu.String()
}
pu.Path = "/zen" + rest
pu.RawPath = ""
return OpenCodeFreeURL(pu.String(), proto)
}
// RetryOpenCodeFreeOnZen asks Zen's free tier for a free model p's OpenCode
// Go gateway answered "Model is unavailable" to (req, res), with the public
// key in place of the user's, and returns what Zen answered when it served
// it. Otherwise res is returned, its message saying where the model is
// served. Any other request or answer is res as it was.
func RetryOpenCodeFreeOnZen(p Provider, proto Protocol, req *http.Request, res *http.Response, do func(*http.Request) (*http.Response, error)) (*http.Response, error) {
if res == nil || res.StatusCode != http.StatusBadRequest || req.GetBody == nil || openCodeGateway(req.URL.String()) != "go" {
return res, nil
}
b, _ := io.ReadAll(io.LimitReader(res.Body, 64<<10))
res.Body.Close()
res.Body = io.NopCloser(bytes.NewReader(b))
if !openCodeUnavailable(res.StatusCode, b) {
return res, nil
}
body, err := req.GetBody()
if err != nil {
return res, nil
}
sent, _ := io.ReadAll(body)
body.Close()
model := gjson.GetBytes(sent, "model").String()
hint := fmt.Sprintf("OpenCode Go doesn't serve %s: pick a model the OpenCode Go provider lists", model)
zen := openCodeGoToZenFree(req.URL.String(), proto)
if p.OpenCodeFree(model) && zen != "" && proto != Gemini {
again := req.Clone(req.Context())
again.Body = io.NopCloser(bytes.NewReader(sent))
again.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(sent)), nil }
again.ContentLength = int64(len(sent))
if u, err := again.URL.Parse(zen); err == nil {
again.URL = u
again.Host = u.Host
// the public key, never the user's Go key, as OpenCode asks
// Zen's free tier signed out
again.Header.Del("x-api-key")
again.Header.Set("Authorization", "Bearer "+OpenCodeAnonymousKey)
if proto == Anthropic {
again.Header.Set("x-api-key", OpenCodeAnonymousKey)
}
got, err := do(again)
said := ""
switch {
case err != nil:
said = err.Error()
case got.StatusCode < 300:
res.Body.Close()
return got, nil
default:
gb, _ := io.ReadAll(io.LimitReader(got.Body, 64<<10))
got.Body.Close()
said = fmt.Sprintf("%d %s", got.StatusCode, APIError(gb, got.Status))
}
hint = fmt.Sprintf("OpenCode Go doesn't serve %s, and OpenCode Zen's free tier didn't serve it either (%s). "+
"Pick a model the OpenCode Go provider lists, or one of Zen's free models under the OpenCode Zen provider, which needs no key", model, said)
}
}
b = withMessage(b, apiError(b, res.Status)+" — "+hint)
res.Body = io.NopCloser(bytes.NewReader(b))
res.ContentLength = int64(len(b))
if res.Header == nil {
res.Header = http.Header{}
}
res.Header.Set("Content-Length", strconv.Itoa(len(b)))
return res, nil
}