diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 12889f7c2..24b8a8856 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -21,6 +21,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Rate windows | A provider bills the hours it says at its own rate (#2463): `RateWindows`, each a span `HH:MM`–`HH:MM` on this computer's clock whose end may pass its start over midnight, the days it is on (`Days`, `time.Weekday`'s numbers, none for every day), and a rate from just over 0 to 1000 at three decimals. The first window that holds a call's time multiplies the price again, on top of `PriceRate` — a price the user set for a model included, which the price rate alone leaves as set — and outside every window the price rate alone counts. A call is priced at its own time wherever a cost is counted call by call — the Usage page and its CSV, a gateway key's cost limit, the gateway's sessions in Usage — by `EffectivePriceAt`, which `EffectivePriceIn` is at `time.Now()`, and its record's time is read on this computer's clock whatever zone it was written in (a call reported as `…Z`); the Sessions page sums a session's calls by model, not by time, so it prices them without any window (`BasePriceIn` in `sessions.priceOf`), the same at every hour it is read; the ledger's `Pricer` holds each provider's base price and windows once and reads each record's rate at the record's own time, so a window that opens mid-page prices only the calls inside it; a gateway block's rows (`blockPricer`, the Requests tab) take their price from a memo asked with no time, which `RateAt` reads as no window, and each row is put at its own window's rate there (`atWindow` before `Price.In`). A list price billed double at peak (`Peak`, DeepSeek's, Ollama Cloud's two DeepSeek models' and the relays `PeakOf` names) is part of the base: the final price is that base, peak included, times the window's rate, so a provider with a `Peak` needs no window for the same hours: the order is the spec (the author, YangHonghang), so a 0.8 window on a shared DeepSeek key takes 0.8 off the peak price at peak, and a window set over the official peak hours would double them twice, which the editor's hint says under the windows. `/v1/models` prices its list at now (`EntryPricer`); the model list magpie writes into an agent's own config (`AgentPricer`, Pi's and omp's cost) leaves every window out, since nothing rewrites that file as a window opens or closes. `CheckRateWindows` says what is wrong with a set; the editor keeps the windows under Advanced, drawn by `ratewindows.js`, which app.js imports when an editor draws the field (`rateWindowsField`) so it adds nothing to the core's scripts — until it has loaded, a save leaves `rateWindows` out, which keeps them. A provider with windows shows what it bills at now on its row (`rateNow` in `/api/providers`, `rateNowOf` in the GUI's `providers.go`: `RateAt` on the server's clock, which calls are counted on, never the browser's); one with a price rate alone shows nothing new. Windows are kept with the provider: a save that leaves them out keeps them, null or an empty list clears them, and a signed-in account's survive its `Save` — the account branch and `withPicks` both go through one list, `accountSettings`, beside its `PriceRate`, or the editor's Save would quietly drop what it shows (#4738: two lists drifted, and `additionalTools`, extraBody, reply headers, its rests, `limitRestOff` and patience were each lost one way; `TestAccountSettingsKept`). | [`ratewindow.go`](../../internal/provider/ratewindow.go), [`models.go`](../../internal/provider/models.go), [`ledger.go`](../../internal/usage/ledger.go) (`Pricer`), [`app.js`](../../internal/gui/assets/app.js) (`rateWindowsField`), [`ratewindows.js`](../../internal/gui/assets/ratewindows.js), [`gui/providers.go`](../../internal/gui/providers.go) (`rateNowOf`) | | Anthropic key header | A provider of the user's own on a third-party Anthropic API is sent its key as both `x-api-key` and `Authorization: Bearer` (`AuthHeaders`); Anthropic's own API, Bedrock, Azure, Vertex and every subscription account have their own and never this choice (`BothAuth` is false). Some services refuse the two together with a 401 (Aloha on Discord: "鉴权 header, x-api-key 和 Authorization 不可以同时存在"), so `Provider.AuthHeader` (`authHeader`: empty for both, `x-api-key` or `bearer`; anything else is read as empty) sends one alone, picked in the editor's Key header row (shown while `bothAuth` is true, or a custom provider's Anthropic URL is a third party's). Left at both, a 401 whose body `catalog.BothAuthRefused` tells as that refusal (it names both headers and says they can't be together, in Chinese or English) is asked once more with x-api-key alone, then Bearer alone (`RetryOneAuth`, in the gateway's `forwardOnce` and the provider test's `probe`; `catalog.fetchOne` for the model list through `listAuth`); the first not answered 401 or 403 is kept with `LearnAuthHeader`, which never changes a pick the user made. A request carrying the user's own `Authorization` or `x-api-key` header is never retried. | [`authheader.go`](../../internal/provider/authheader.go), [`test.go`](../../internal/provider/test.go), [`catalog/authheader.go`](../../internal/catalog/authheader.go), [`catalog/live.go`](../../internal/catalog/live.go) | | GLM Coding Plan key at pay as you go | Zhipu's and Z.ai's presets offer Pay as you go first (`/api/paas/v4`) and the Coding Plan (`/api/coding/paas/v4`, Responses at `/api/v1`); both share `/api/anthropic`, which bills the plan, so a plan's key left at Pay as you go worked in Claude Code and was refused 429 code 1113 "余额不足或无可用资源包" in Codex (@cleverpigo on X). Nothing in the key tells the two apart, so a Chat request to `open.bigmodel.cn` or `api.z.ai` at `/api/paas/v4` refused 1113 is asked once more at `/api/coding/paas/v4` (`RetryZhipuCoding`, in the gateway's `forwardOnce` and the provider test's `probe`). Served there, `LearnZhipuCoding` moves a saved provider with that one key, still at that URL, to the plan's OpenAI URL (and the preset's plan Responses URL when it has none); one with other keys stays and is asked again each time. Refused there too, the 1113 body keeps its code and gets both URLs and what to change in its message (`ZhipuNoBalanceHint`). A pay-as-you-go key with a balance is never answered 1113 and never sent to the plan's endpoint. | [`zhipu_coding.go`](../../internal/provider/zhipu_coding.go), [`test.go`](../../internal/provider/test.go) | +| A Zen free model on OpenCode Go | OpenCode's two gateways serve different free models: Zen's free tier (`/zen`, asked with the public key `OpenCodeAnonymousKey`) serves its `-free` models and big-pickle, Go (`/zen/go`, a Go key) only a few of its own (beam-free, iceman-contributor-free on 2026-11-02). Go answers a model it doesn't serve 400 "Upstream request failed: Model is unavailable." before it reads the key, so Claude Code asking one of Zen's free models on an OpenCode Go provider failed on every request (51bit.eth on Discord). Such a request, a free model by `OpenCodeFree`, is asked once more at Zen's free tier on the same API (`openCodeGoToZenFree`, `OpenCodeFreeURL`), with the public key and never the user's Go key (`RetryOpenCodeFreeOnZen`, in the gateway's `forwardOnce`); a model that isn't free isn't. Refused there too, or not free, the 400 keeps Go's words and says where the model is served. Not changed: when Go's `/models` refuses the key, the provider lists models.dev's `opencode-go`, which names free models Go doesn't serve (#4900). | [`opencode_go_free.go`](../../internal/provider/opencode_go_free.go) | | Zhipu's 200 refusals | Zhipu's and Z.ai's `/api/v1` (the GLM Coding Plan's Responses API, from their Codex pages) and `/api/monitor` answer a refusal 200 in the platform's envelope, `{"code":1000,"msg":"身份验证失败。","success":false}`, where their OpenAI and Anthropic endpoints answer the same key 401 (@xanahopper on X: a refused key tested green on the Responses row only). `ZhipuEnveloped` turns a 2xx JSON body from `open.bigmodel.cn` or `api.z.ai` with `success: false` into `{"error":{"code","message"}}` at the status Zhipu's error-code table gives (1000–1005 → 401, 1113 and 1302–1399 → 429, 1220 → 403, 1210–1229, 1261 and 1301 → 400, anything else → 502), in the provider test's `probe` (endpoint tests, model tests, Detect APIs) and the gateway's `forwardOnce`. A stream, a compressed body, a body over 64 KB and every other host pass as they came. The plan's quota card for a key refused there (1000–1005, or a 401) says ` didn't take this key (): …` with the vendor's API-keys page (`zhipuRefused`), not asked again as a team's key, and the GUI shows it as that (`quotaError`) rather than "Allowance unavailable". | [`zhipu_envelope.go`](../../internal/provider/zhipu_envelope.go), [`planquota.go`](../../internal/provider/planquota.go), [`test.go`](../../internal/provider/test.go) | | Extra body | `ExtraBody` (`extraBody` in providers.json, the editor's *Extra body*, #1604) is a JSON object whose fields `WithExtraBody` adds at the top level of every JSON body sent to the provider: Messages, Chat, Responses and Gemini, relayed as they came or translated, in the gateway's `forwardOnce` and in Test and Detect (`tested`). A field the body has already is kept; a name written `"!name"` replaces it. Values are put in as written, objects whole, not merged. `${sessionId}` in any string, at any depth, becomes the request's session: the agent's session header (`sessionOf`), else the id `conversationID` derives from the first user message (`magpie-` and its hash), so it stays the same through one conversation; Test and Detect send `magpie-test-` and 12 random letters, a new one each time. `${threadId}` is the thread the agent names within that session: Codex's `thread_id` (its turn metadata or `thread-id` header, `threadOf`), which a subagent has of its own while it shares its lead's session; read only when the provider's headers or extraBody name it (`AsksThread`). No other agent names a thread, and there `${threadId}` is the session's id. `${subagentId}` becomes the Claude Code subagent the request is of (`x-claude-code-agent-id`, `subOf`), "" on the conversation's own turns, which never send the header, so `${sessionId}:${subagentId}` keeps one prompt_cache_key per subagent where `${sessionId}` alone carries every subagent's turns on one key (#2937). `model`, `stream` and the conversation (`messages`, `input`, `contents`, `system`, `systemInstruction`, `system_instruction`, `instructions`, `tools`, `ExtraBodyReserved`) are magpie's: Save refuses them with or without `!` (`ExtraBodyOK`), the editor says so as they are typed, and one written into providers.json by hand is dropped on read (`cleanExtraBody`). Not sent with it: `count_tokens`, embeddings, images, video and System One's decision model (other APIs), and a signed-in account's requests, except a ChatGPT (Codex) account's (magpie-releases#18): its requests are built as Codex CLI's (`codexBody`) and take the fields Codex CLI adds by choice, such as `access_programs` (OpenAI's Daybreak), while `store`, `tool_choice` and `include`, which the backend needs as `codexBody` sets them, can't be set (`codexOwned`). Its extraBody is written into providers.json by hand under the account's entry and kept onto the account by `withPicks`, and kept by a later `Save` (#4738: `Save` dropped it before); the editor has no box for it. A client's own top-level `access_programs` on Responses or Chat is carried to a Responses build as it came (`Request.AccessPrograms`), so a request translated (a Codex account is streamed, so a whole Responses request is made again) keeps it as a relayed one does. It reaches only the upstreams Codex itself sends it to (`keepsAccessPrograms`, #3172, see [gateway routing](gateway-routing.md)); it is taken out before the extraBody merge, so an `access_programs` the user puts in a provider's extraBody still goes. One object goes to every API; fields for one API alone are not a thing yet. A `thinking` budget it puts in on an Anthropic endpoint is fitted to a Claude that thinks only adaptively after the merge, as an agent's is (`adaptiveThinking`, `TestExtraBodyBudgetFittedToAdaptiveModel`). | [`extrabody.go`](../../internal/provider/extrabody.go), [`gateway.go`](../../internal/gateway/gateway.go) | | Headers' conversation ids | `${sessionId}`, `${threadId}` and `${subagentId}` in a value of the provider's `Headers` (Axel Burks on Discord: a gateway in front of several Azure accounts routes one conversation to one account by a session header) are the ids extraBody gets, on every request `Sign` signs: the gateway carries the conversation to it in the request's context (`WithConversation`), on every API and `count_tokens` too. A request that is no turn of a conversation (a model list, a balance, an embedding, image or video, System One's decision model, a search) gets an id of its own, `magpie-` and 12 random letters, new each time (`OwnConversation`); Test and Detect's is their `magpie-test-` id, the same in headers and body. A literal placeholder is never sent. In a header the ids go without control characters (`headerSafe`): an agent's session id with CR or LF in it would split the header, or Go would fail the request. A value with neither placeholder goes as written (`SentHeaders`). | [`conversation.go`](../../internal/provider/conversation.go), [`account.go`](../../internal/provider/account.go), [`gateway.go`](../../internal/gateway/gateway.go), [`codex_resume.go`](../../internal/gateway/codex_resume.go) | diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 65ea4e8f5..beb3b360d 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -5194,6 +5194,13 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid // it; else the refusal says what to change (@cleverpigo on X) res, err = provider.RetryZhipuCoding(p, req, res, func(r *http.Request) (*http.Response, error) { return p.Do(s.client, r) }) } + if err == nil && provider.OpenCodeURL(req.URL.String()) { + // a model OpenCode Go answers "Model is unavailable": one of Zen's + // free models asked at Zen's free tier, signed out as OpenCode + // asks it; else the refusal says where it is served (51bit.eth on + // Discord) + res, err = provider.RetryOpenCodeFreeOnZen(p, to, req, res, func(r *http.Request) (*http.Response, error) { return p.Do(s.client, r) }) + } if err != nil { return res, err } diff --git a/internal/gateway/opencode_go_free_test.go b/internal/gateway/opencode_go_free_test.go new file mode 100644 index 000000000..3327b319a --- /dev/null +++ b/internal/gateway/opencode_go_free_test.go @@ -0,0 +1,144 @@ +package gateway + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// goUnavailable is what OpenCode Go answered on 2026-11-02 to a model it +// doesn't serve (deepseek-v4.1-flash-free, Zen's), the same on its chat +// and Messages APIs, before it looked at the key. +const goUnavailable = `{"type":"error","error":{"type":"api_error","message":"Upstream request failed: Model is unavailable."}}` + +type goAsk struct{ url, auth, apiKey string } + +// streamFor is a stream saying text in the shape of the API path is on. +func streamFor(path, text string) string { + if strings.HasSuffix(path, "/chat/completions") { + return chatSSE(text, "", "") + } + return anthropicSSE(text) +} + +// goFreeServer is a gateway whose provider go is OpenCode Go as the preset +// adds it, with a Go key, listing the models given; Go answers +// goUnavailable to every model but those in serves, and Zen's free tier +// answers zen (status, then body) to everything, a stream saying "from +// zen" when the status is 200. +func goFreeServer(t *testing.T, models, serves []string, zenStatus int, zenRefusal string) (*Server, func() []goAsk) { + t.Helper() + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + if err := provider.Save(provider.Provider{ID: "go", Name: "OpenCode Go", Preset: "opencode-go", Key: "sk-go-users-own", + Chat: "https://opencode.ai/zen/go/v1", Responses: "https://opencode.ai/zen/go/v1", Anthropic: "https://opencode.ai/zen/go", + Models: models}); err != nil { + t.Fatal(err) + } + var mu sync.Mutex + var asked []goAsk + s := New() + s.client = &http.Client{Transport: countTransport(func(r *http.Request) (*http.Response, error) { + b, _ := io.ReadAll(r.Body) + r.Body.Close() + mu.Lock() + asked = append(asked, goAsk{r.URL.Host + r.URL.Path, r.Header.Get("Authorization"), r.Header.Get("x-api-key")}) + mu.Unlock() + model := "" + for _, m := range models { + if strings.Contains(string(b), `"model":"`+m+`"`) { + model = m + } + } + if strings.HasPrefix(r.URL.Path, "/zen/go/") { + for _, m := range serves { + if m == model { + return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(streamFor(r.URL.Path, "from go")))}, nil + } + } + return &http.Response{StatusCode: 400, Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(goUnavailable))}, nil + } + if zenStatus < 300 { + return &http.Response{StatusCode: zenStatus, Header: http.Header{"Content-Type": {"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(streamFor(r.URL.Path, "from zen")))}, nil + } + return &http.Response{StatusCode: zenStatus, Header: http.Header{"Content-Type": {"application/json"}}, + Body: io.NopCloser(strings.NewReader(zenRefusal))}, nil + })} + return s, func() []goAsk { mu.Lock(); defer mu.Unlock(); return append([]goAsk(nil), asked...) } +} + +func goClaudeAsk(s *Server, model string) *httptest.ResponseRecorder { + req := httptest.NewRequest("POST", "/v1/messages", strings.NewReader( + `{"model":"`+model+`","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"hi"}],`+claudeTools+`}`)) + req.Header.Set("anthropic-version", "2023-06-01") + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, req) + return rec +} + +// 51bit.eth's case: Claude Code asking one of Zen's free models on an +// OpenCode Go provider. Go answers "Model is unavailable"; the request is +// asked again at Zen's free tier, where OpenCode asks it, with the public +// key and never the user's Go key, and Claude Code gets Zen's reply. +func TestOpenCodeGoFreeModelAskedAtZen(t *testing.T) { + s, asked := goFreeServer(t, []string{"deepseek-v4.1-flash-free"}, nil, 200, "") + rec := goClaudeAsk(s, "go/deepseek-v4.1-flash-free") + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "from zen") { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + a := asked() + // on the API Go was asked on, at Zen's free tier + want := map[string]string{"opencode.ai/zen/go/v1/messages": "opencode.ai/inference/anthropic/v1/messages", + "opencode.ai/zen/go/v1/chat/completions": "opencode.ai/inference/openai/v1/chat/completions"} + if len(a) != 2 || want[a[0].url] == "" || a[1].url != want[a[0].url] { + t.Fatalf("asked %+v", a) + } + z := a[1] + if z.auth != "Bearer public" || z.apiKey != "" && z.apiKey != "public" || strings.Contains(z.auth+z.apiKey, "sk-go") { + t.Fatalf("Zen asked with %+v", z) + } +} + +// A free model Go serves itself stays on Go, asked once, with the Go key. +func TestOpenCodeGoOwnFreeModelStaysOnGo(t *testing.T) { + s, asked := goFreeServer(t, []string{"beam-free"}, []string{"beam-free"}, 500, `{"error":{"message":"zen asked"}}`) + rec := goClaudeAsk(s, "go/beam-free") + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "from go") { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + if a := asked(); len(a) != 1 || !strings.HasPrefix(a[0].url, "opencode.ai/zen/go/") { + t.Fatalf("asked %+v", a) + } +} + +// Refused at Zen too, the refusal says what both said and where the model +// is served; a paid model Go doesn't serve isn't asked at Zen at all, and +// its refusal says to pick one of Go's. +func TestOpenCodeGoUnavailableSaysWhere(t *testing.T) { + s, asked := goFreeServer(t, []string{"cat-jam-free", "claude-opus-5"}, nil, 400, + `{"error":{"type":"server_error","message":"Upstream request failed: Model is unavailable."}}`) + rec := goClaudeAsk(s, "go/cat-jam-free") + body := rec.Body.String() + if rec.Code < 400 || !strings.Contains(body, "OpenCode Go doesn't serve cat-jam-free") || !strings.Contains(body, "OpenCode Zen provider, which needs no key") { + t.Fatalf("%d %s", rec.Code, body) + } + n := len(asked()) + rec = goClaudeAsk(s, "go/claude-opus-5") + body = rec.Body.String() + if rec.Code < 400 || !strings.Contains(body, "OpenCode Go doesn't serve claude-opus-5: pick a model the OpenCode Go provider lists") { + t.Fatalf("%d %s", rec.Code, body) + } + for _, a := range asked()[n:] { + if !strings.HasPrefix(a.url, "opencode.ai/zen/go/") { + t.Fatalf("a paid model asked at %s", a.url) + } + } +} diff --git a/internal/provider/opencode_go_free.go b/internal/provider/opencode_go_free.go new file mode 100644 index 000000000..523839fd3 --- /dev/null +++ b/internal/provider/opencode_go_free.go @@ -0,0 +1,125 @@ +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 +} diff --git a/internal/provider/opencode_go_free_test.go b/internal/provider/opencode_go_free_test.go new file mode 100644 index 000000000..58e046e47 --- /dev/null +++ b/internal/provider/opencode_go_free_test.go @@ -0,0 +1,27 @@ +package provider + +import "testing" + +// Each of Go's URLs a request can go to has Zen's free tier's beside it, +// where OpenCode 2 asks it; any other URL has none. +func TestOpenCodeGoToZenFree(t *testing.T) { + for _, c := range []struct { + u string + proto Protocol + want string + }{ + {"https://opencode.ai/zen/go/v1/chat/completions", Chat, "https://opencode.ai/inference/openai/v1/chat/completions"}, + {"https://opencode.ai/zen/go/v1/responses", Responses, "https://opencode.ai/inference/openai/v1/responses"}, + {"https://opencode.ai/zen/go/v1/messages", Anthropic, "https://opencode.ai/inference/anthropic/v1/messages"}, + {"https://opencode.ai/inference/go/v1/chat/completions", Chat, "https://opencode.ai/inference/openai/v1/chat/completions"}, + {"https://opencode.ai/inference/go/openai/v1/chat/completions", Chat, "https://opencode.ai/inference/openai/v1/chat/completions"}, + {"https://opencode.ai/inference/go/anthropic/v1/messages", Anthropic, "https://opencode.ai/inference/anthropic/v1/messages"}, + {"https://opencode.ai/zen/v1/chat/completions", Chat, ""}, + {"https://opencode.ai/inference/custom/v1/chat/completions", Chat, ""}, + {"https://example.com/zen/go/v1/chat/completions", Chat, ""}, + } { + if got := openCodeGoToZenFree(c.u, c.proto); got != c.want { + t.Errorf("%s: %q, want %q", c.u, got, c.want) + } + } +}