diff --git a/internal/gateway/chat.go b/internal/gateway/chat.go index 9613924e2..b269ff43d 100644 --- a/internal/gateway/chat.go +++ b/internal/gateway/chat.go @@ -581,6 +581,9 @@ func buildChat(r *Request, model, host string, rejectTemp bool) []byte { if len(t.Schema) > 0 { fn["parameters"] = t.Schema } + if r.strictSaid { + fn["strict"] = t.Strict + } tools = append(tools, map[string]any{"type": "function", "function": fn}) } out["tools"] = tools diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 1b8aaf114..c6afc1f31 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -4811,9 +4811,10 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid path, body = at, b } base := p.Base(to) - if p.IsOpenCode() && p.OpenCodeFree(gjson.GetBytes(body, "model").String()) { - // Zen's free tier answers at the inference API's URL alone (zenfree.go) - base = provider.OpenCodeFreeURL(base) + zenFree := p.IsOpenCode() && p.OpenCodeFree(gjson.GetBytes(body, "model").String()) + if zenFree { + // Zen's free tier answers at OpenCode 2's paths alone (zenfree.go) + base = provider.OpenCodeFreeURL(base, to) } if mantleRoutes(p, to) { // Bedrock Mantle serves each model under /v1 or /openai/v1 @@ -4894,10 +4895,27 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid } } if provider.OpenCodeURL(req.URL.String()) { + if zenFree { + // only what OpenCode 2.2.5 sends its gateway: an agent's own + // headers (Claude Code's x-stainless-*, Codex's originator) + // would mark the request as not OpenCode's (#3491) + kept := http.Header{} + for _, k := range []string{"Content-Type", "Anthropic-Version", "Anthropic-Beta"} { + if v := req.Header.Values(k); len(v) > 0 { + kept[k] = v + } + } + req.Header = kept + } // as OpenCode itself sends it, which Zen's free tier asks for, // with the conversation's own session, which Zen and Go route and - // cache by and answer 400 without - provider.OpenCodeClient(req.Header, openCodeSeed(in, body)) + // cache by and answer 400 without, from the folder the agent says + // it works in + provider.OpenCodeClient(req.Header, openCodeSeed(in, body), openCodeDir(factsOf(to, body).dir)) + if v := in.Get("x-opencode-project"); v != "" { + // OpenCode's own, asking through magpie + req.Header.Set("x-opencode-project", v) + } } if p.IsCline() { // as Cline's desktop app sends it: its free models are 403'd diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go index d4e5cf088..6e7330ba4 100644 --- a/internal/gateway/ir.go +++ b/internal/gateway/ir.go @@ -211,6 +211,11 @@ type Request struct { // Gemini's API of a model not named for images (drawCodeAssist). draws bool + // strictSaid has a Chat request's tools say strict as each is set, + // false included, as OpenCode's own do: Zen's free tier + // (zenFreeTools). + strictSaid bool + Model string System string Messages []Message diff --git a/internal/gateway/opencode_client_test.go b/internal/gateway/opencode_client_test.go index 023de79e6..1db23b9ef 100644 --- a/internal/gateway/opencode_client_test.go +++ b/internal/gateway/opencode_client_test.go @@ -12,8 +12,9 @@ import ( ) // OpenCode Zen's free models answer 403 "OpenCode's free tier can only be -// used from within OpenCode" unless the request says it is OpenCode's: its -// User-Agent (1.18.0 or newer) and a session id of its form, as OpenCode +// used from within OpenCode", and since late October 2026 429 "Free models +// work in OpenCode" to 1.x's shape (#3491), unless the request says it is +// OpenCode 2's: its User-Agent and a session id of its form, as OpenCode // sends them to a provider whose id starts with "opencode". Requests to // OpenCode's gateway carry them, those to anyone else don't, and the body // goes as the caller sent it either way. @@ -64,26 +65,21 @@ func TestOpenCodeClientHeaders(t *testing.T) { if len(zen) != 3 || len(other) != 1 { t.Fatalf("requests: %v", got) } - id := regexp.MustCompile(`^(ses|msg)_[0-9a-f]{12}[0-9A-Za-z]{14}$`) + id := regexp.MustCompile(`^ses_[0-9a-f]{12}[0-9A-Za-z]{14}$`) for i, r := range zen { - if ua := r.h.Get("User-Agent"); ua != provider.OpenCodeUserAgent { + if ua := r.h.Get("User-Agent"); ua != provider.OpenCodeUserAgent() { t.Errorf("zen %d: User-Agent %q", i, ua) } - if !id.MatchString(r.h.Get("x-opencode-session")) || !id.MatchString(r.h.Get("x-opencode-request")) || - !strings.HasPrefix(r.h.Get("x-opencode-session"), "ses_") || !strings.HasPrefix(r.h.Get("x-opencode-request"), "msg_") { + if !id.MatchString(r.h.Get("x-opencode-session")) || r.h.Get("x-opencode-request") != "" { t.Errorf("zen %d: session %q request %q", i, r.h.Get("x-opencode-session"), r.h.Get("x-opencode-request")) } - if v := r.h.Get("x-opencode-session-id"); v != r.h.Get("x-opencode-session") { - t.Errorf("zen %d: x-opencode-session-id %q, x-opencode-session %q", i, v, r.h.Get("x-opencode-session")) - } - // OpenCode 1.19.0 sends Zen neither, and Zen's free tier answers 403 - // FreeTierError to a request carrying x-session-affinity - for _, h := range []string{"x-session-affinity", "X-Session-Id"} { - if v := r.h.Get(h); v != "" { - t.Errorf("zen %d: %s %q went to Zen", i, h, v) + // OpenCode 2.2.5 sends the session in all four + for _, h := range []string{"x-opencode-session-id", "x-session-affinity", "X-Session-Id"} { + if v := r.h.Get(h); v != r.h.Get("x-opencode-session") { + t.Errorf("zen %d: %s %q, x-opencode-session %q", i, h, v, r.h.Get("x-opencode-session")) } } - if r.h.Get("x-opencode-client") != "cli" || r.h.Get("x-opencode-project") != "global" { + if r.h.Get("x-opencode-client") != "cli" || len(r.h.Get("x-opencode-project")) != 40 || r.h.Get("b3") == "" || r.h.Get("traceparent") == "" { t.Errorf("zen %d: client %q project %q", i, r.h.Get("x-opencode-client"), r.h.Get("x-opencode-project")) } if r.h.Get("Authorization") != "Bearer public" { @@ -93,10 +89,11 @@ func TestOpenCodeClientHeaders(t *testing.T) { t.Errorf("zen %d: body changed:\n%s\nvs\n%s", i, r.body, other[0].body) } } - // one conversation, one session; each request its own id - if zen[0].h.Get("x-opencode-session") != zen[1].h.Get("x-opencode-session") || zen[0].h.Get("x-opencode-request") == zen[1].h.Get("x-opencode-request") { - t.Errorf("session %q %q, request %q %q", zen[0].h.Get("x-opencode-session"), zen[1].h.Get("x-opencode-session"), - zen[0].h.Get("x-opencode-request"), zen[1].h.Get("x-opencode-request")) + // one conversation, one session and trace; each request its own span + if zen[0].h.Get("x-opencode-session") != zen[1].h.Get("x-opencode-session") || zen[0].h.Get("traceparent")[:35] != zen[1].h.Get("traceparent")[:35] || + zen[0].h.Get("traceparent") == zen[1].h.Get("traceparent") { + t.Errorf("session %q %q, traceparent %q %q", zen[0].h.Get("x-opencode-session"), zen[1].h.Get("x-opencode-session"), + zen[0].h.Get("traceparent"), zen[1].h.Get("traceparent")) } if s := zen[2].h.Get("x-opencode-session"); s != "ses_ecc5d8f28ffe9Cy14V8Em7lI2u" { t.Errorf("OpenCode's own session became %q", s) diff --git a/internal/gateway/zenfree.go b/internal/gateway/zenfree.go index c9fbc5a9b..efc55793a 100644 --- a/internal/gateway/zenfree.go +++ b/internal/gateway/zenfree.go @@ -11,26 +11,32 @@ import ( // OpenCode Zen's free models (-free) are served to OpenCode alone: a // request must carry OpenCode's headers (provider.OpenCodeClient), be -// streamed, and offer tools named bash and read, or Zen answers 403 -// "OpenCode's free tier can only be used from within OpenCode", and since -// mid-October 2026 be asked at the inference API's URL, not Zen's -// (provider.OpenCodeFreeURL), with bash and read each taking a parameter -// (provider.OpenCodeToolSchemas). The user -// allowed magpie to ask them as OpenCode does, on this route only. So a -// request to one is never relayed as it came: it is translated (which -// always streams upstream, and gathers the stream into one reply for a -// client that didn't ask for a stream), and on the way +// streamed, and offer OpenCode's core tools, or Zen answers 403 +// "OpenCode's free tier can only be used from within OpenCode"; be asked +// at OpenCode 2's paths (provider.OpenCodeFreeURL), with each core tool +// taking OpenCode's parameters (provider.OpenCodeToolSchemas); and since +// late October 2026 carry OpenCode 2's User-Agent and its environment +// block in the system prompt (provider.OpenCodeEnvironment), or Zen +// answers 429 "Free usage limit reached. Free models work in OpenCode" +// (#3491). The user allowed magpie to ask them as OpenCode does, on this +// route only. So a request to one is never relayed as it came: it is +// translated (which always streams upstream, and gathers the stream into +// one reply for a client that didn't ask for a stream), and on the way // -// - a tool of the client's named bash or read in another case (Claude -// Code's Bash and Read) is offered under the lowercase name, and the -// model's calls of it go back to the client under the client's own; -// - a missing bash or read (Codex's shell and exec_command are not bash) -// is offered as a stub that says never to call it, with OpenCode's own -// parameters. tool_choice is left -// as the client sent it. A call of a stub is never handed on: it is -// left out of the reply, and a turn that called nothing else ends there, -// with what the model said so far (a short note when it said nothing), -// as a plain stop rather than a tool call. +// - a tool of the client's named as a core tool in another case (Claude +// Code's Read, Edit, Glob and Grep) is offered under the lowercase name, +// and the model's calls of it go back to the client under the client's +// own; +// - a missing core tool (Claude Code's Bash is not shell) is offered as +// a stub that says never to call it, with OpenCode's own parameters. +// On Chat each tool says strict false, as OpenCode's do. tool_choice +// is left as the client sent it. A call of a stub is never handed on: +// it is left out of the reply, and a turn that called nothing else ends +// there, with what the model said so far (a short note when it said +// nothing), as a plain stop rather than a tool call; +// - OpenCode's environment block is added to the system prompt, for the +// folder the agent says it works in (the home folder when it says +// none), unless the prompt has one already (OpenCode's own). // zenTools is how one request's tools were offered to Zen's free tier. type zenTools struct { @@ -62,6 +68,8 @@ func zenFreeTools(r *Request) *zenTools { z.stubs[need] = true } r.Tools = tools + r.strictSaid = true + zenEnvironment(r) if len(z.back) == 0 { return z } @@ -93,6 +101,43 @@ func zenFreeTools(r *Request) *zenTools { return z } +// zenEnvironment adds OpenCode's environment block to r's system prompt, +// unless the prompt carries one already. +func zenEnvironment(r *Request) { + if provider.OpenCodeHasEnvironment(r.System) { + return + } + for _, m := range r.Messages { + if m.Role != "system" && m.Role != "developer" { + continue + } + for _, p := range m.Parts { + if p.Kind == Text && provider.OpenCodeHasEnvironment(p.Text) { + return + } + } + } + env := provider.OpenCodeEnvironment(openCodeDir(workDir(r))) + if r.System == "" { + r.System = env + } else { + r.System += "\n\n" + env + } +} + +// openCodeDir is dir when it is a folder OpenCode could name, an absolute +// path (or one under ~), else "" for the home folder. +func openCodeDir(dir string) string { + if dir == "/" || dir == "~/" { + return "" + } + if strings.HasPrefix(dir, "/") || strings.HasPrefix(dir, "~/") || strings.HasPrefix(dir, `\\`) || + len(dir) >= 3 && dir[1] == ':' && (dir[2] == '\\' || dir[2] == '/') { + return dir + } + return "" +} + // zenReply turns the model's events back into the client's: its tools' // names, and no call of a stub. One is made for each reply. type zenReply struct { diff --git a/internal/gateway/zenfree_test.go b/internal/gateway/zenfree_test.go index e8e5e904d..b79de9ee1 100644 --- a/internal/gateway/zenfree_test.go +++ b/internal/gateway/zenfree_test.go @@ -102,24 +102,26 @@ const claudeTools = `"tools":[{"name":"Bash","description":"run","input_schema": `{"name":"Read","description":"read","input_schema":{"type":"object","properties":{"file_path":{"type":"string"}}}},` + `{"name":"Grep","description":"grep","input_schema":{"type":"object"}}]` -// Claude Code's Bash and Read go to Zen's free models as bash and read, in a -// streamed request, and the model's call of bash comes back to Claude Code -// as Bash, in the stream it asked for and in a reply it didn't stream. +// Claude Code's Read and Grep go to Zen's free models as OpenCode's read +// and grep, beside stubs of the core tools it lacks (its Bash is not +// shell), in a streamed request, and the model's call of read comes back +// to Claude Code as Read, in the stream it asked for and in a reply it +// didn't stream. func TestZenFreeClaudeCodeTools(t *testing.T) { - s, got := zenServer(t, chatSSE("Running it.", "bash", `{"command":"ls"}`)) + s, got := zenServer(t, chatSSE("Reading it.", "read", `{"path":"a"}`)) history := `"messages":[{"role":"user","content":"list"},` + `{"role":"assistant","content":[{"type":"tool_use","id":"t0","name":"Read","input":{"file_path":"a"}}]},` + `{"role":"user","content":[{"type":"tool_result","tool_use_id":"t0","content":"ok"}]}]` - rec := zenSend(t, s, "/v1/messages", `{"model":"zen/mimo-v2.6-flash-free","max_tokens":100,"stream":true,`+claudeTools+`,"tool_choice":{"type":"tool","name":"Bash"},`+history+`}`) + rec := zenSend(t, s, "/v1/messages", `{"model":"zen/mimo-v2.6-flash-free","max_tokens":100,"stream":true,`+claudeTools+`,"tool_choice":{"type":"tool","name":"Read"},`+history+`}`) sent := got["opencode.ai"][0] if sent["stream"] != true { t.Fatalf("not streamed: %v", sent) } - if n := toolNames(sent); strings.Join(n, ",") != "bash,read,Grep" { + if n := toolNames(sent); strings.Join(n, ",") != "Bash,read,grep,edit,glob,shell" { t.Fatalf("tools %v", n) } tc, _ := json.Marshal(sent["tool_choice"]) - if !strings.Contains(string(tc), `"bash"`) { + if !strings.Contains(string(tc), `"read"`) { t.Fatalf("tool_choice %s", tc) } hist, _ := json.Marshal(sent["messages"]) @@ -127,7 +129,7 @@ func TestZenFreeClaudeCodeTools(t *testing.T) { t.Fatalf("history %s", hist) } out := rec.Body.String() - if !strings.Contains(out, `"name":"Bash"`) || strings.Contains(out, `"name":"bash"`) || !strings.Contains(out, "tool_use") { + if !strings.Contains(out, `"name":"Read"`) || strings.Contains(out, `"name":"read"`) || !strings.Contains(out, "tool_use") { t.Fatalf("stream %s", out) } @@ -149,20 +151,20 @@ func TestZenFreeClaudeCodeTools(t *testing.T) { names = append(names, c.Name) } } - if strings.Join(names, ",") != "Bash" || msg.StopReason != "tool_use" { + if strings.Join(names, ",") != "Read" || msg.StopReason != "tool_use" { t.Fatalf("reply %s", rec.Body) } } -// Codex's shell is not bash: Zen is offered stubs of bash and read beside -// it, and a call of a stub never reaches Codex; the turn ends with what the +// Codex's shell is OpenCode's shell by name: Zen is offered stubs of the +// other core tools beside it, and a call of a stub never reaches Codex; the turn ends with what the // model said. func TestZenFreeCodexStubs(t *testing.T) { s, got := zenServer(t, chatSSE("Let me look.", "read", `{"path":"x"}`)) rec := zenSend(t, s, "/v1/responses", `{"model":"zen/mimo-v2.6-flash-free","stream":true,"input":"look",`+ `"tools":[{"type":"function","name":"shell","parameters":{"type":"object","properties":{"command":{"type":"array"}}}}],"tool_choice":"auto"}`) sent := got["opencode.ai"][0] - if n := toolNames(sent); strings.Join(n, ",") != "shell,bash,read" { + if n := toolNames(sent); strings.Join(n, ",") != "shell,edit,glob,grep,read" { t.Fatalf("tools %v", n) } if sent["tool_choice"] != "auto" { @@ -174,7 +176,7 @@ func TestZenFreeCodexStubs(t *testing.T) { } // a stub called with nothing said: a short note, a plain stop - s, _ = zenServer(t, chatSSE("", "bash", `{}`)) + s, _ = zenServer(t, chatSSE("", "shell", `{}`)) rec = zenSend(t, s, "/v1/chat/completions", `{"model":"zen/mimo-v2.6-flash-free","messages":[{"role":"user","content":"hi"}]}`) var res struct { Choices []struct { @@ -230,7 +232,7 @@ func TestZenFreeZeroCostModels(t *testing.T) { zenSend(t, s, "/v1/chat/completions", strings.Replace(body, "%s", m, 1)) sent := got["opencode.ai"][i] free := i < 2 - if n := strings.Join(toolNames(sent), ","); (n == "bash,read") != free { + if n := strings.Join(toolNames(sent), ","); (n == "Bash,edit,glob,grep,read,shell") != free { t.Errorf("%s: tools %s", m, n) } if (sent["stream"] == true) != free { @@ -242,11 +244,11 @@ func TestZenFreeZeroCostModels(t *testing.T) { // A request that searches is asked in rounds (searchReply): each round's // reply comes back with the client's names and without a stub's call. func TestZenFreeSearchRounds(t *testing.T) { - z := zenFreeTools(&Request{Tools: []Tool{{Name: "Bash"}}}) + z := zenFreeTools(&Request{Tools: []Tool{{Name: "Read"}}}) ask := zenRound(z, func(ctx context.Context, req *Request) (<-chan Event, int, string) { ch := make(chan Event, 8) - for _, ev := range []Event{{Kind: KText, Text: "hi"}, {Kind: KToolStart, ID: "a", Name: "bash"}, {Kind: KToolArgs, Text: "{}"}, - {Kind: KToolStart, ID: "b", Name: "read"}, {Kind: KToolArgs, Text: "{}"}, {Kind: KStop, Stop: "tool"}} { + for _, ev := range []Event{{Kind: KText, Text: "hi"}, {Kind: KToolStart, ID: "a", Name: "read"}, {Kind: KToolArgs, Text: "{}"}, + {Kind: KToolStart, ID: "b", Name: "shell"}, {Kind: KToolArgs, Text: "{}"}, {Kind: KStop, Stop: "tool"}} { ch <- ev } close(ch) @@ -257,16 +259,17 @@ func TestZenFreeSearchRounds(t *testing.T) { for ev := range in { got = append(got, ev.Name+ev.Text+ev.Stop) } - if strings.Join(got, ",") != "hi,Bash,{},tool" { + if strings.Join(got, ",") != "hi,Read,{},tool" { t.Fatalf("got %q", got) } } -// Since mid-October 2026 Zen's free tier answers at the inference API's -// URL alone, and refuses bash or read offered with no parameters (c9cu on -// Discord: Muse Spark 1.3 free 403 FreeTierError again): a free model is -// asked at /inference/v1 with stubs that take OpenCode's own parameters, -// and a paid one stays at the provider's /zen/v1. +// Zen's free tier refuses a core tool offered with no parameters (c9cu on +// Discord: Muse Spark 1.3 free 403 FreeTierError), and since late October +// 2026 answers 429 to 1.x's /inference/v1 shape (#3491): a free model is +// asked at OpenCode 2's /inference/openai/v1 with stubs that take OpenCode +// 2.2.5's own parameters, strict false, and a paid one stays at the +// provider's /zen/v1. func TestZenFreeAtInferenceURL(t *testing.T) { s, _ := zenServer(t, chatSSE("hi", "", "")) var paths []string @@ -282,11 +285,11 @@ func TestZenFreeAtInferenceURL(t *testing.T) { })} zenSend(t, s, "/v1/chat/completions", `{"model":"zen/mimo-v2.6-flash-free","messages":[{"role":"user","content":"hi"}]}`) zenSend(t, s, "/v1/chat/completions", `{"model":"zen/kimi-k2.6","messages":[{"role":"user","content":"hi"}]}`) - if len(paths) != 2 || paths[0] != "opencode.ai/inference/v1/chat/completions" || paths[1] != "opencode.ai/zen/v1/chat/completions" { + if len(paths) != 2 || paths[0] != "opencode.ai/inference/openai/v1/chat/completions" || paths[1] != "opencode.ai/zen/v1/chat/completions" { t.Fatalf("paths %v", paths) } tools, _ := sent[0]["tools"].([]any) - if len(tools) != 2 { + if len(tools) != 5 { t.Fatalf("tools %v", sent[0]["tools"]) } for _, tl := range tools { @@ -295,5 +298,12 @@ func TestZenFreeAtInferenceURL(t *testing.T) { if props, _ := ps["properties"].(map[string]any); len(props) == 0 { t.Fatalf("stub %v takes no parameter", f["name"]) } + if f["strict"] != false { + t.Fatalf("stub %v strict %v", f["name"], f["strict"]) + } + } + // a paid model is offered nothing it didn't ask for + if tools, _ := sent[1]["tools"].([]any); len(tools) != 0 { + t.Fatalf("paid model offered %v", tools) } } diff --git a/internal/gateway/zenfree_v2_test.go b/internal/gateway/zenfree_v2_test.go new file mode 100644 index 000000000..815659980 --- /dev/null +++ b/internal/gateway/zenfree_v2_test.go @@ -0,0 +1,181 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// #3491 (laomao04_65777 on Discord): Zen's free models answered 429 "Free +// usage limit reached. Free models work in OpenCode" to magpie while real +// OpenCode on the same machine was served. A free model is now asked as +// OpenCode 2.2.5 asked it (../provider/testdata/opencode-2.2.5-chat.json), +// on every protocol: at its v2 path, with only the headers it sends (none +// of the agent's own), its environment block for the folder the agent says +// it works in, and that folder's project id. +func TestZenFreeAsOpenCode225(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + var capture struct { + Headers [][2]string `json:"headers"` + } + b, err := os.ReadFile("../provider/testdata/opencode-2.2.5-chat.json") + if err != nil { + t.Fatal(err) + } + if err := json.Unmarshal(b, &capture); err != nil { + t.Fatal(err) + } + transport := map[string]bool{"host": true, "content-length": true, "accept-encoding": true, "connection": true} + var want []string + for _, kv := range capture.Headers { + if !transport[strings.ToLower(kv[0])] { + want = append(want, strings.ToLower(kv[0])) + } + } + slices.Sort(want) + + if err := provider.Save(provider.Provider{ID: "zen", Name: "Zen", Key: "public", + Chat: "https://opencode.ai/zen/v1", Responses: "https://opencode.ai/zen/v1", Anthropic: "https://opencode.ai/zen", + Models: []string{"mimo-v2.6-flash-free"}}); err != nil { + t.Fatal(err) + } + type seen struct { + path string + h http.Header + body map[string]any + } + var got []seen + s := New() + s.client = &http.Client{Transport: countTransport(func(r *http.Request) (*http.Response, error) { + b, _ := io.ReadAll(r.Body) + r.Body.Close() + var m map[string]any + _ = json.Unmarshal(b, &m) + got = append(got, seen{r.URL.Host + r.URL.Path, r.Header.Clone(), m}) + return &http.Response{StatusCode: 200, Header: http.Header{"Content-Type": {"text/event-stream"}}, + Body: io.NopCloser(strings.NewReader(chatSSE("hi", "", "")))}, nil + })} + dir := filepath.Join(t.TempDir(), "proj") + os.MkdirAll(dir, 0o755) + dir, _ = filepath.EvalSymlinks(dir) + // as Claude Code says it, on its own line + dirJSON, _ := json.Marshal("\n - Primary working directory: " + dir + "\n") + dirOnly, _ := json.Marshal(dir) + claudeCode := func(r *http.Request) { + r.Header.Set("User-Agent", "claude-cli/2.1.0 (external, cli)") + r.Header.Set("anthropic-version", "2023-06-01") + r.Header.Set("x-app", "cli") + r.Header.Set("X-Stainless-Lang", "js") + } + codex := func(r *http.Request) { + r.Header.Set("User-Agent", "codex_cli_rs/0.200.0") + r.Header.Set("originator", "codex_cli_rs") + r.Header.Set("x-codex-turn-metadata", "{}") + } + for _, c := range []struct { + name, path, body string + as func(*http.Request) + }{ + {"chat", "/v1/chat/completions", `{"model":"zen/mimo-v2.6-flash-free","messages":[{"role":"system","content":"You help. ` + strings.Trim(string(dirJSON), `"`) + `"},{"role":"user","content":"hi"}]}`, nil}, + {"messages", "/v1/messages", `{"model":"zen/mimo-v2.6-flash-free","max_tokens":10,"system":"You are Claude Code. ` + strings.Trim(string(dirJSON), `"`) + `","messages":[{"role":"user","content":"hi"}]}`, claudeCode}, + {"responses", "/v1/responses", `{"model":"zen/mimo-v2.6-flash-free","instructions":"You are Codex.","input":[{"role":"user","content":"` + strings.Trim(string(dirOnly), `"`) + `"}]}`, codex}, + } { + got = nil + req := httptest.NewRequest("POST", c.path, strings.NewReader(c.body)) + req.Header.Set("Content-Type", "application/json") + if c.as != nil { + c.as(req) + } + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 || len(got) != 1 { + t.Fatalf("%s: %d %s (%d sent)", c.name, rec.Code, rec.Body, len(got)) + } + r := got[0] + // the zen provider here is Chat-first; whatever protocol the + // agent spoke, the free request goes at OpenCode 2's path + if !strings.HasPrefix(r.path, "opencode.ai/inference/openai/v1/") && !strings.HasPrefix(r.path, "opencode.ai/inference/anthropic/v1/") { + t.Errorf("%s: asked at %s", c.name, r.path) + } + var names []string + for k := range r.h { + names = append(names, strings.ToLower(k)) + } + slices.Sort(names) + // Messages carries anthropic-version and x-api-key besides, as + // OpenCode's Anthropic requests do + names = slices.DeleteFunc(names, func(k string) bool { return k == "anthropic-version" || k == "x-api-key" }) + if !slices.Equal(names, want) { + t.Errorf("%s: headers\n got %v\nwant %v", c.name, names, want) + } + if r.h.Get("User-Agent") != provider.OpenCodeUserAgent() || r.h.Get("Accept") != "*/*" { + t.Errorf("%s: User-Agent %q Accept %q", c.name, r.h.Get("User-Agent"), r.h.Get("Accept")) + } + if p := r.h.Get("x-opencode-project"); p != provider.OpenCodeProject(dir) { + t.Errorf("%s: project %q, want %q (%s's)", c.name, p, provider.OpenCodeProject(dir), dir) + } + sys := systemText(r.body) + if !strings.Contains(sys, provider.OpenCodeEnvironment(dir)) || strings.Count(sys, "") != 1 { + t.Errorf("%s: system prompt %q", c.name, sys) + } + } + + // OpenCode's own request through magpie: its block and project as it + // sent them, nothing added + got = nil + own := provider.OpenCodeEnvironment("/somewhere/else") + ownJSON, _ := json.Marshal("You are opencode.\n" + own) + req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"zen/mimo-v2.6-flash-free","messages":[{"role":"system","content":`+string(ownJSON)+`},{"role":"user","content":"hi"}]}`)) + req.Header.Set("x-opencode-project", "0123456789abcdef0123456789abcdef01234567") + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 || len(got) != 1 { + t.Fatalf("OpenCode's own: %d %s", rec.Code, rec.Body) + } + if sys := systemText(got[0].body); strings.Count(sys, "") != 1 || !strings.Contains(sys, own) { + t.Errorf("OpenCode's own block: %q", sys) + } + if p := got[0].h.Get("x-opencode-project"); p != "0123456789abcdef0123456789abcdef01234567" { + t.Errorf("OpenCode's own project became %q", p) + } +} + +// systemText is a request body's system prompt, on any protocol. +func systemText(m map[string]any) string { + var out []string + add := func(v any) { + switch v := v.(type) { + case string: + out = append(out, v) + case []any: + for _, p := range v { + if pm, ok := p.(map[string]any); ok { + if s, ok := pm["text"].(string); ok { + out = append(out, s) + } + } + } + } + } + add(m["system"]) + add(m["instructions"]) + for _, key := range []string{"messages", "input"} { + msgs, _ := m[key].([]any) + for _, x := range msgs { + mm, _ := x.(map[string]any) + if r := mm["role"]; r == "system" || r == "developer" { + add(mm["content"]) + } + } + } + return strings.Join(out, "\n") +} diff --git a/internal/provider/opencode_client.go b/internal/provider/opencode_client.go index 968fda952..3498913cd 100644 --- a/internal/provider/opencode_client.go +++ b/internal/provider/opencode_client.go @@ -1,57 +1,165 @@ package provider import ( + "cmp" "container/list" "crypto/rand" + "crypto/sha1" + "encoding/hex" "encoding/json" + "errors" "fmt" + "io" "net/http" "net/url" + "os" + "path/filepath" "regexp" + "runtime" "strconv" "strings" "sync" + "testing" "time" "github.com/yetone/magpie/internal/catalog" ) -// OpenCodeVersion is the OpenCode release magpie says it is to OpenCode's -// gateway. Zen's free tier turns away anything older than 1.18.0 (426 -// "OpenCode 1.18.0 or newer is required to use the free tier"). -const OpenCodeVersion = "1.19.0" +// OpenCodeVersion is the oldest OpenCode release magpie says it is to +// OpenCode's gateway: 2.2.5, npm's latest @opencode/cli on 2026-11-01. +// Since 2026-10-26 Zen's free tier answers 429 FreeUsageLimitError ("Free +// models work in OpenCode") to OpenCode 1.19.0's User-Agent whatever the +// request says (#3491). A fixed version goes stale as OpenCode updates +// itself, so the one sent is what OpenCode's own updater says is latest +// (openCodeLatest), never older than this. +const OpenCodeVersion = "2.2.5" -// OpenCodeUserAgent is the User-Agent OpenCode 1.19.0 sends, its ai-sdk -// and Bun included, as captured from the real client. -const OpenCodeUserAgent = "opencode/" + OpenCodeVersion + " ai-sdk/provider-utils/4.0.23 runtime/bun/1.3.14" +// OpenCodeUserAgent is the User-Agent OpenCode sends on every protocol, +// opencode/${channel}/${version}/${name} (packages/core/src/app.ts), as +// @opencode/cli 2.2.5 sent it to Zen on 2026-11-01: +// opencode/latest/2.2.5/cli. +func OpenCodeUserAgent() string { + return "opencode/latest/" + openCodeLatest() + "/cli" +} + +// openCodeVersionURL is OpenCode's updater, which answers +// {"version":"x.y.z"} for its npm channel. +var openCodeVersionURL = openCodeUpdater + +const openCodeUpdater = "https://opencode.ai/update/api/latest/cli/npm" + +// openCodeVersionEvery is how often the updater is asked again. +const openCodeVersionEvery = 6 * time.Hour + +var openCodeVersion struct { + sync.Mutex + v string // the latest read, "" before one is + at time.Time // when it was last asked + asking bool +} + +// openCodeLatest is the OpenCode version to send: the updater's latest +// as last read, or OpenCodeVersion. The updater is asked in the +// background at most every openCodeVersionEvery, never from a test +// binary unless a test points openCodeVersionURL at a fake. +func openCodeLatest() string { + openCodeVersion.Lock() + defer openCodeVersion.Unlock() + v := cmp.Or(openCodeVersion.v, OpenCodeVersion) + u := openCodeVersionURL + if openCodeVersion.asking || time.Since(openCodeVersion.at) < openCodeVersionEvery || testing.Testing() && u == openCodeUpdater { + return v + } + openCodeVersion.asking = true + go func() { + found := openCodeAskVersion(u, v) + openCodeVersion.Lock() + if found != "" { + openCodeVersion.v = found + } + openCodeVersion.at, openCodeVersion.asking = time.Now(), false + openCodeVersion.Unlock() + }() + return v +} + +var openCodeVersionRe = regexp.MustCompile(`^\d{1,4}\.\d{1,4}\.\d{1,6}$`) + +// openCodeAskVersion is the latest version u says, or "" when it can't be +// read, isn't a release version or is older than OpenCodeVersion (a stale +// mirror). Asked as the zen-free plugin asks it: 3s, no redirect. +func openCodeAskVersion(u, current string) string { + c := &http.Client{ + Timeout: 3 * time.Second, + Transport: http.DefaultClient.Transport, + CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirected") }, + } + res, err := c.Get(u + "?current=" + url.QueryEscape(current)) + if err != nil { + return "" + } + defer res.Body.Close() + if res.StatusCode != http.StatusOK { + return "" + } + var got struct { + Version any `json:"version"` + } + if json.NewDecoder(io.LimitReader(res.Body, 64<<10)).Decode(&got) != nil { + return "" + } + v, _ := got.Version.(string) + if !openCodeVersionRe.MatchString(v) || !openCodeAtLeast(v, OpenCodeVersion) { + return "" + } + return v +} + +// openCodeAtLeast says whether version a is b or later. +func openCodeAtLeast(a, b string) bool { + x, y := strings.Split(a, "."), strings.Split(b, ".") + for i := range 3 { + m, _ := strconv.Atoi(x[i]) + n, _ := strconv.Atoi(y[i]) + if m != n { + return m > n + } + } + return true +} // OpenCodeAnonymousKey is the key OpenCode asks Zen with when no one is // signed in to it, which Zen's free models answer. const OpenCodeAnonymousKey = "public" // OpenCodeClient makes a request to OpenCode's gateway (Zen or Go) carry -// what OpenCode itself sends there (packages/core/src/session/ -// model-request.ts): its User-Agent, the session in x-opencode-session and -// x-opencode-session-id, the turn in x-opencode-request, and -// x-opencode-client and x-opencode-project. OpenCode 1.19.0 sends Zen no -// x-session-affinity or X-Session-Id (captured from the real client), and -// since mid-October 2026 Zen's free tier answers 403 FreeTierError to a -// request carrying x-session-affinity, so neither goes. Zen's -// free models are served to no one else ("OpenCode's free tier can only be -// used from within OpenCode"), and Zen reads the session id as OpenCode -// lays one out (openCodeSession). session names the conversation, whose -// turns keep one session id, which Zen routes and caches by. -func OpenCodeClient(h http.Header, session string) { +// what OpenCode 2.2.5 itself sends there, as captured on 2026-11-01 +// (testdata/opencode-2.2.5-chat.json): its User-Agent (OpenCodeUserAgent), +// trace headers b3 and traceparent (one trace a session, a new span each +// request), x-opencode-client cli, the project dir is in +// (OpenCodeProject), and the session in x-opencode-session, +// x-opencode-session-id, x-session-affinity and x-session-id, with Accept +// */*. 1.x's x-opencode-request and its project "global" (which 2.x sends +// only from a git repository with no remote and no commit) don't go: Zen's +// free tier answers 429 FreeUsageLimitError to 1.x's shape (#3491). Zen +// reads the session id as OpenCode lays one out (openCodeSession); session +// names the conversation, whose turns keep one session id, which Zen routes +// and caches by. dir is the folder the agent works in, the home folder +// when "". The order 2.2.5 sends them in isn't kept: Go's HTTP/1 writes +// headers sorted and HTTP/2 in no fixed order. +func OpenCodeClient(h http.Header, session, dir string) { id := openCodeSession(session) - h.Set("User-Agent", OpenCodeUserAgent) - h.Set("x-opencode-session", id) - h.Set("x-opencode-session-id", id) - h.Del("x-session-affinity") - h.Del("X-Session-Id") - h.Set("x-opencode-request", openCodeNewID("msg", false, time.Now())) + b3, traceparent := openCodeTrace(id) + h.Set("User-Agent", OpenCodeUserAgent()) + h.Set("b3", b3) + h.Set("traceparent", traceparent) h.Set("x-opencode-client", "cli") - // OpenCode's project outside a git repository - h.Set("x-opencode-project", "global") + h.Set("x-opencode-project", OpenCodeProject(dir)) + for _, k := range []string{"x-opencode-session", "x-opencode-session-id", "x-session-affinity", "x-session-id"} { + h.Set(k, id) + } + h.Del("x-opencode-request") + h.Set("Accept", "*/*") } // OpenCodeURL says whether u is at OpenCode's gateway (Zen, Go or the @@ -92,9 +200,10 @@ func OpenCodeSession(h http.Header, u string) { // OpenCodeFree says whether model is one of OpenCode Zen's free ones on p, // which Zen serves only to what looks like OpenCode: besides the headers -// OpenCodeClient sets, a streamed request offering tools named bash and -// read (lowercase, each taking a parameter: OpenCodeToolSchemas) at the -// inference API (OpenCodeFreeURL), as checked against Zen in October 2026. The +// OpenCodeClient sets, a streamed request offering OpenCode's core tools +// (OpenCodeTools, OpenCodeToolSchemas) with OpenCode's environment block +// in its system prompt (OpenCodeEnvironment), at the paths OpenCode 2 +// asks (OpenCodeFreeURL), as checked against Zen in October 2026. The // gateway asks them so whoever the client is (gateway/zenfree.go), and the // Test button's probe so (zenFreeProbe). A free model is one whose id ends // in -free, or one models.dev's opencode prices at nothing, as big-pickle, @@ -115,40 +224,51 @@ func (p Provider) OpenCodeFree(model string) bool { // openCodeFreeIDs are Zen's free models whose ids don't end in -free. var openCodeFreeIDs = map[string]bool{"big-pickle": true, "grok-code": true} -// OpenCodeTools are the tools Zen's free tier wants offered, by name. -var OpenCodeTools = []string{"bash", "read"} +// OpenCodeTools are OpenCode 2's core tools, which Zen's free tier wants +// offered, by name: shell, not 1.x's bash (what 2.2.5 sent on 2026-11-01). +var OpenCodeTools = []string{"edit", "glob", "grep", "read", "shell"} -// OpenCodeToolSchemas are the parameters OpenCode itself gives bash and -// read (1.19.0, as it sent them to Zen). Since mid-October 2026 Zen's free -// tier answers 403 FreeTierError when either is offered with no -// parameters, as magpie's stubs were ({"type":"object","properties":{}}); -// one property is enough, and these are OpenCode's own. +// OpenCodeToolSchemas are the parameters OpenCode 2.2.5 gives its core +// tools, as it sent them to Zen (testdata/opencode-2.2.5-chat.json). Zen's +// free tier answers 403 FreeTierError to one offered with no parameters. var OpenCodeToolSchemas = map[string]string{ - "bash": `{"type":"object","properties":{"command":{"type":"string","description":"The command to execute"},"timeout":{"type":"integer","description":"Optional timeout in milliseconds"},"workdir":{"type":"string","description":"The working directory to run the command in"}},"required":["command"]}`, - "read": `{"type":"object","properties":{"filePath":{"type":"string","description":"The absolute path to the file or directory to read"},"offset":{"type":"integer","description":"The line number to start reading from (1-indexed)"},"limit":{"type":"integer","description":"The maximum number of lines to read"}},"required":["filePath"]}`, + "edit": `{"type":"object","properties":{"path":{"type":"string","description":"File to edit"},"oldString":{"type":"string","description":"Exact text to find and replace"},"newString":{"type":"string","description":"Text to replace oldString with (must differ from oldString)"},"replaceAll":{"type":"boolean","description":"Whether to replace every occurrence of oldString. When false, oldString must match exactly once. Defaults to false."}},"required":["path","oldString","newString"],"additionalProperties":false}`, + "glob": `{"type":"object","properties":{"pattern":{"type":"string","description":"Glob pattern to match files against"},"path":{"type":"string","description":"Directory to search. Defaults to the current working directory."},"hidden":{"type":"boolean","description":"Include hidden files and directories (default: false)."},"limit":{"type":"integer","exclusiveMinimum":0,"description":"Maximum number of matching files to return (default: 100)"}},"required":["pattern"],"additionalProperties":false}`, + "grep": `{"type":"object","properties":{"pattern":{"type":"string","minLength":1,"description":"Regular expression or literal text to match in file contents."},"path":{"type":"string","description":"File or directory to search. Defaults to the current working directory."},"include":{"type":"string","description":"Glob pattern to filter files (for example, \"*.js\" or \"*.{ts,tsx}\")"},"literal":{"type":"boolean","description":"Treat ` + "`pattern`" + ` as exact text instead of a regular expression (default: false)."},"caseSensitive":{"type":"boolean","description":"Use case-sensitive matching (default: true)."},"limit":{"type":"integer","exclusiveMinimum":0,"description":"Maximum number of matching lines to return (default: 100)"}},"required":["pattern"],"additionalProperties":false}`, + "read": `{"type":"object","properties":{"path":{"type":"string","description":"File or directory to read"},"offset":{"type":"integer","minimum":0,"description":"The line or directory entry to start reading from (1-based)"},"limit":{"type":"integer","minimum":0,"description":"The maximum number of lines or directory entries to read (defaults to and capped at 2000)"}},"required":["path"],"additionalProperties":false}`, + "shell": `{"type":"object","properties":{"command":{"type":"string","description":"Shell command string to execute"},"workdir":{"type":"string","description":"Working directory to execute the command in. Defaults to the current working directory. When possible, avoid changing directories in the command and set the working directory here instead."},"timeout":{"type":"integer","minimum":0,"description":"Timeout in milliseconds. Set to 0 to disable the timeout. Defaults to 120000 for foreground commands. Background commands have no timeout by default."},"background":{"type":"boolean","description":"Run the command in the background and return immediately (useful for dev servers and long-running builds). You do not need to use '&' at the end of the command when using this parameter. You will be notified when it completes. DO NOT poll for completion."}},"required":["command"],"additionalProperties":false}`, } -// OpenCodeFreeURL is where a request to Zen's free tier goes, given the -// URL it would go to at Zen (https://opencode.ai/zen/v1/…, or under the -// root for Messages): the same path under the inference API's root, which -// models.dev gives OpenCode as Zen's URL since October 2026 and OpenCode -// 1.19.0 asks. Since mid-October 2026 Zen answers a free model at /zen/v1 -// with 403 FreeTierError even when the request is OpenCode's own, word for -// word, and the same request at /inference/v1 with 200. Any other URL, Go's -// (/zen/go) among them, is u. -func OpenCodeFreeURL(u string) string { +// OpenCodeFreeURL is where a request on proto to Zen's free tier goes, +// given the URL it would go to at Zen (https://opencode.ai/zen/v1/…, or +// under /zen for Messages): where OpenCode 2 sends it, the base_url +// models.dev's v2 catalog (models.opencode.ai/experimental/v2.0/api.json, +// which 2.2.5 reads) gives every opencode model on 2026-11-01: +// /inference/openai/v1 for Chat and Responses, /inference/anthropic/v1 for +// Messages. 1.x's /inference/v1, which no OpenCode 2 request goes to, is +// moved there too. Gemini, on which Zen gives nothing free, goes under +// /inference as before. Any other URL, Go's (/zen/go) among them, is u. +func OpenCodeFreeURL(u string, proto Protocol) string { pu, err := url.Parse(strings.TrimSpace(u)) - if err != nil || pu.Scheme == "" { - return u - } - if !openCodeHost(pu.Hostname()) { + if err != nil || pu.Scheme == "" || !openCodeHost(pu.Hostname()) { return u } rest, ok := strings.CutPrefix(pu.Path, "/zen") - if !ok || rest != "" && rest[0] != '/' || rest == "/go" || strings.HasPrefix(rest, "/go/") { + if !ok { + rest, ok = strings.CutPrefix(pu.Path, "/inference") + } + under := func(dir string) bool { return rest == dir || strings.HasPrefix(rest, dir+"/") } + if !ok || rest != "" && rest[0] != '/' || under("/go") || under("/openai") || under("/anthropic") || under("/google") || under("/systemone") { return u } - pu.Path = "/inference" + rest + switch proto { + case Chat, Responses: + pu.Path = "/inference/openai" + rest + case Anthropic: + pu.Path = "/inference/anthropic" + rest + default: + pu.Path = "/inference" + rest + } return pu.String() } @@ -157,8 +277,9 @@ func OpenCodeFreeURL(u string) string { const OpenCodeStub = "Not available in this session. Never call this tool." // zenFreeProbe is the Test button's smallest request, body, asked as Zen's -// free tier wants it: streamed, offering bash and read, which say they -// aren't to be called. +// free tier wants it: streamed, offering OpenCode's core tools, which say +// they aren't to be called (strict false on Chat, as OpenCode's are), with +// OpenCode's environment block for the home folder. func zenFreeProbe(proto Protocol, body string) string { var m map[string]any if json.Unmarshal([]byte(body), &m) != nil { @@ -170,7 +291,7 @@ func zenFreeProbe(proto Protocol, body string) string { _ = json.Unmarshal([]byte(OpenCodeToolSchemas[n]), &schema) switch proto { case Chat: - tools = append(tools, map[string]any{"type": "function", "function": map[string]any{"name": n, "description": OpenCodeStub, "parameters": schema}}) + tools = append(tools, map[string]any{"type": "function", "function": map[string]any{"name": n, "description": OpenCodeStub, "parameters": schema, "strict": false}}) case Responses: tools = append(tools, map[string]any{"type": "function", "name": n, "description": OpenCodeStub, "parameters": schema}) default: @@ -178,6 +299,17 @@ func zenFreeProbe(proto Protocol, body string) string { } } m["stream"], m["tools"] = true, tools + env := OpenCodeEnvironment("") + switch proto { + case Chat: + msgs, _ := m["messages"].([]any) + m["messages"] = append([]any{map[string]any{"role": "system", "content": env}}, msgs...) + m["stream_options"] = map[string]any{"include_usage": true} + case Responses: + m["instructions"] = env + default: + m["system"] = env + } b, err := json.Marshal(m) if err != nil { return body @@ -185,6 +317,233 @@ func zenFreeProbe(proto Protocol, body string) string { return string(b) } +// openCodeHasEnvironment matches OpenCode's environment block: , a +// Working directory: line and . +var openCodeHasEnvironment = regexp.MustCompile(`[\s\S]*Working directory:[\s\S]*`) + +// OpenCodeHasEnvironment says whether a system prompt already carries +// OpenCode's environment block, as OpenCode's own does. +func OpenCodeHasEnvironment(system string) bool { + return openCodeHasEnvironment.MatchString(system) +} + +// OpenCodeEnvironment is OpenCode 2.2.5's environment block, word for word +// (packages/core/src/instructions/builtins.ts, as 2.2.5 sent it to Zen on +// 2026-11-01), said for dir, the home folder when "". Zen's free tier +// serves a request as OpenCode's own only when a system message carries +// one; without it a request gets a small allowance a day, then 429 +// FreeUsageLimitError ("Free models work in OpenCode"), and fixed text in +// it that only magpie would send (a directory "unknown") is a fingerprint. +func OpenCodeEnvironment(dir string) string { + if dir == "" { + dir, _ = os.UserHomeDir() + } + local := openCodeLocalDir(dir) + root, _, isRepo := openCodeRepository(local) + workspace := dir + if isRepo && root != local { + workspace = root + } + git := "no" + if isRepo { + git = "yes" + } + platform := runtime.GOOS + if platform == "windows" { + platform = "win32" + } + tmp := os.TempDir() + if real, err := filepath.EvalSymlinks(tmp); err == nil { + tmp = real + } + return strings.Join([]string{ + "Here is some useful information about the environment you are running in:", + "", + " Working directory: " + dir, + " Workspace root folder: " + workspace, + " Is directory a git repo: " + git, + " Platform: " + platform, + " Prefer " + filepath.Join(tmp, "opencode") + " over generic system temporary directories such as /tmp; it is pre-created and approved for external access.", + "", + }, "\n") +} + +// OpenCodeProject is OpenCode's project id for dir (packages/core/src/ +// project.ts), the home folder when "": in a git repository with a remote, +// sha1 of git-remote:host/path; anywhere else sha1 of directory: and the +// repository's root, or dir. A repository with no remote, which OpenCode +// names by its root commit, is named by its folder, as the zen-free plugin +// names it: the same shape, and no git to run. +func OpenCodeProject(dir string) string { + if dir == "" { + dir, _ = os.UserHomeDir() + } + local := openCodeLocalDir(dir) + root, remote, isRepo := openCodeRepository(local) + var key string + switch { + case remote != "": + key = "git-remote:" + remote + case isRepo: + key = "directory:" + root + default: + key = "directory:" + local + } + sum := sha1.Sum([]byte(key)) + return hex.EncodeToString(sum[:]) +} + +// openCodeLocalDir is dir with ~ for the home folder and its links +// resolved, as far as they resolve. +func openCodeLocalDir(dir string) string { + if dir == "~" || strings.HasPrefix(dir, "~/") { + home, _ := os.UserHomeDir() + dir = home + dir[1:] + } + if real, err := filepath.EvalSymlinks(dir); err == nil { + return real + } + return dir +} + +var ( + openCodeRemoteRe = regexp.MustCompile(`(?m)^\s*\[remote\s+"([^"]+)"\]([^\[]*)`) + openCodeURLRe = regexp.MustCompile(`(?m)^\s*url\s*=\s*(.+)$`) + openCodeGitdirRe = regexp.MustCompile(`(?m)^gitdir:\s*(.+)$`) + openCodeSchemeRe = regexp.MustCompile(`(?i)^[a-z][a-z0-9+.-]*://`) + openCodeSCPRe = regexp.MustCompile(`^([^@/:]+@)?([^/:]+):(.+)$`) + openCodeDotGitRe = regexp.MustCompile(`\.git/?$`) +) + +// openCodeRepository is the git repository dir is in, as OpenCode finds +// it: the nearest .git up from dir (a worktree's file naming its gitdir +// and that one's commondir), its root, and the remote OpenCode names it by +// (origin, else the first one listed) as host/path, "" when none. +func openCodeRepository(dir string) (root, remote string, ok bool) { + for d := dir; ; { + dotGit := filepath.Join(d, ".git") + if fi, err := os.Stat(dotGit); err == nil { + common := dotGit + if !fi.IsDir() { + b, err := os.ReadFile(dotGit) + if err != nil { + return d, "", true + } + m := openCodeGitdirRe.FindStringSubmatch(string(b)) + if m == nil || strings.TrimSpace(m[1]) == "" { + return "", "", false + } + own := strings.TrimSpace(m[1]) + if !filepath.IsAbs(own) { + own = filepath.Join(d, own) + } + common = own + if c, err := os.ReadFile(filepath.Join(own, "commondir")); err == nil { + shared := strings.TrimSpace(string(c)) + if !filepath.IsAbs(shared) { + shared = filepath.Join(own, shared) + } + common = shared + } + } + config, err := os.ReadFile(filepath.Join(common, "config")) + if err != nil { + return d, "", true + } + var first, origin string + for i, m := range openCodeRemoteRe.FindAllStringSubmatch(string(config), -1) { + var u string + if um := openCodeURLRe.FindStringSubmatch(m[2]); um != nil { + u = um[1] + } + if i == 0 { + first = u + } + if m[1] == "origin" { + origin = u + break + } + } + u := first + if origin != "" || openCodeRemoteRe.MatchString(string(config)) && strings.Contains(string(config), `"origin"`) { + u = origin + } + return d, openCodeRemotePath(u), true + } + up := filepath.Dir(d) + if up == d { + return "", "", false + } + d = up + } +} + +// openCodeRemotePath is a remote's URL as OpenCode names a project by it: +// host/path, the host lowercased, without .git; "" for a file: URL or one +// it can't read. +func openCodeRemotePath(value string) string { + in := strings.TrimSpace(value) + if in == "" { + return "" + } + parts := func(host, name string) string { + p := strings.TrimLeft(name, "/") + p = openCodeDotGitRe.ReplaceAllString(p, "") + p = strings.TrimRight(p, "/") + if host == "" || p == "" { + return "" + } + return strings.ToLower(host) + "/" + p + } + if openCodeSchemeRe.MatchString(in) { + u, err := url.Parse(in) + if err != nil || strings.EqualFold(u.Scheme, "file") { + return "" + } + return parts(u.Hostname(), u.EscapedPath()) + } + if m := openCodeSCPRe.FindStringSubmatch(in); m != nil { + return parts(m[2], m[3]) + } + return "" +} + +// openCodeTraces is the trace each session's requests are in, the last +// openCodeKeep sessions'. +var openCodeTraces = struct { + sync.Mutex + of map[string]*list.Element // session → its element in order + order *list.List // of openCodeKept (seed: session, id: trace) +}{of: map[string]*list.Element{}, order: list.New()} + +// openCodeTrace is the b3 and traceparent headers OpenCode's tracer sends +// with a request in session: one trace a session, a new span each request. +func openCodeTrace(session string) (b3, traceparent string) { + hexOf := func(n int) string { + b := make([]byte, n) + if _, err := rand.Read(b); err != nil { + copy(b, randomUUID()) + } + return hex.EncodeToString(b) + } + trace := hexOf(16) + openCodeTraces.Lock() + if e, ok := openCodeTraces.of[session]; ok { + openCodeTraces.order.MoveToBack(e) + trace = e.Value.(openCodeKept).id + } else { + if openCodeTraces.order.Len() >= openCodeKeep { + oldest := openCodeTraces.order.Front() + openCodeTraces.order.Remove(oldest) + delete(openCodeTraces.of, oldest.Value.(openCodeKept).seed) + } + openCodeTraces.of[session] = openCodeTraces.order.PushBack(openCodeKept{session, trace}) + } + openCodeTraces.Unlock() + span := hexOf(8) + return trace + "-" + span + "-1-" + hexOf(8), "00-" + trace + "-" + span + "-01" +} + var openCodeIDRe = regexp.MustCompile(`^[a-z]{3}_[0-9a-f]{12}[0-9A-Za-z]{14}$`) const base62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" diff --git a/internal/provider/opencode_client_test.go b/internal/provider/opencode_client_test.go index 98fb6ed75..4166d9608 100644 --- a/internal/provider/opencode_client_test.go +++ b/internal/provider/opencode_client_test.go @@ -58,17 +58,14 @@ func TestOpenCodeSessionIsOpenCodes(t *testing.T) { t.Fatalf("a hashed session went on as %q", got) } h := http.Header{"X-Session-Affinity": {"from-the-agent"}} - OpenCodeClient(h, "conversation-a") - if h.Get("x-opencode-session") != id || h.Get("x-opencode-session-id") != id || h.Get("User-Agent") != OpenCodeUserAgent { + OpenCodeClient(h, "conversation-a", "") + if h.Get("x-opencode-session") != id || h.Get("x-opencode-session-id") != id || h.Get("User-Agent") != OpenCodeUserAgent() { t.Fatalf("headers %v", h) } - // Zen's free tier refuses a request carrying x-session-affinity, which - // OpenCode itself doesn't send it - if h.Get("x-session-affinity") != "" || h.Get("X-Session-Id") != "" { - t.Fatalf("headers OpenCode doesn't send: %v", h) - } - if req := h.Get("x-opencode-request"); req[:4] != "msg_" || !openCodeIDRe.MatchString(req) { - t.Fatalf("request %q", req) + // OpenCode 2.2.5 sends the session in x-session-affinity and + // x-session-id too, and no x-opencode-request (#3491) + if h.Get("x-session-affinity") != id || h.Get("X-Session-Id") != id || h.Get("x-opencode-request") != "" { + t.Fatalf("headers %v", h) } } diff --git a/internal/provider/opencode_session_test.go b/internal/provider/opencode_session_test.go index 35dd79610..cba402bbe 100644 --- a/internal/provider/opencode_session_test.go +++ b/internal/provider/opencode_session_test.go @@ -96,7 +96,7 @@ func TestOpenCodeSessionOnEveryCall(t *testing.T) { } // a turn's session, named before signing, stays req, _ := http.NewRequest("POST", "https://opencode.ai/zen/v1/chat/completions", nil) - OpenCodeClient(req.Header, "conversation-x") + OpenCodeClient(req.Header, "conversation-x", "") turn := req.Header.Get("x-opencode-session") if err := zen.Sign(context.Background(), req, Chat, nil); err != nil || req.Header.Get("x-opencode-session") != turn { t.Errorf("a turn's session became %q (%v)", req.Header.Get("x-opencode-session"), err) diff --git a/internal/provider/opencode_v2_test.go b/internal/provider/opencode_v2_test.go new file mode 100644 index 000000000..e03988ef1 --- /dev/null +++ b/internal/provider/opencode_v2_test.go @@ -0,0 +1,379 @@ +package provider + +import ( + "crypto/sha1" + "encoding/hex" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "regexp" + "runtime" + "slices" + "strings" + "sync/atomic" + "testing" + "time" +) + +// opencode225 is OpenCode 2.2.5's own chat request to Zen, as a recording +// proxy saw it on 2026-11-01 (#3491): its headers in order, its core tools +// and its environment block. +type opencode225 struct { + Headers [][2]string `json:"headers"` + Environment string `json:"environment"` + Tools []struct { + Function struct { + Name string `json:"name"` + Parameters json.RawMessage `json:"parameters"` + Strict *bool `json:"strict"` + } `json:"function"` + } `json:"tools"` +} + +func loadOpenCode225(t *testing.T) opencode225 { + t.Helper() + b, err := os.ReadFile("testdata/opencode-2.2.5-chat.json") + if err != nil { + t.Fatal(err) + } + var c opencode225 + if err := json.Unmarshal(b, &c); err != nil { + t.Fatal(err) + } + return c +} + +func (c opencode225) header(name string) string { + for _, h := range c.Headers { + if strings.EqualFold(h[0], name) { + return h[1] + } + } + return "" +} + +func sha1Hex(s string) string { + sum := sha1.Sum([]byte(s)) + return hex.EncodeToString(sum[:]) +} + +// #3491: Zen's free tier answers 429 "Free models work in OpenCode" to +// OpenCode 1.x's request shape. A request to OpenCode's gateway carries +// the headers OpenCode 2.2.5 sent, by name, with values of the same +// shape: its User-Agent, one trace a session and a new span a request, +// one session id in all four session headers, its project, and no 1.x +// x-opencode-request. +func TestOpenCodeClientIs225(t *testing.T) { + c := loadOpenCode225(t) + h := http.Header{"X-Opencode-Request": {"msg_old"}} + // what the gateway and Sign put on beside OpenCodeClient + h.Set("Authorization", "Bearer public") + h.Set("Content-Type", "application/json") + OpenCodeClient(h, "conversation-225", t.TempDir()) + + transport := map[string]bool{"host": true, "content-length": true, "accept-encoding": true, "connection": true} + var want, got []string + for _, kv := range c.Headers { + if !transport[strings.ToLower(kv[0])] { + want = append(want, strings.ToLower(kv[0])) + } + } + for k := range h { + got = append(got, strings.ToLower(k)) + } + slices.Sort(want) + slices.Sort(got) + if !slices.Equal(got, want) { + t.Fatalf("headers\n got %v\nwant %v", got, want) + } + if ua := h.Get("User-Agent"); ua != c.header("User-Agent") || ua != OpenCodeUserAgent() { + t.Errorf("User-Agent %q, OpenCode 2.2.5 sent %q", ua, c.header("User-Agent")) + } + for _, k := range []string{"Accept", "x-opencode-client"} { + if h.Get(k) != c.header(k) { + t.Errorf("%s %q, OpenCode sent %q", k, h.Get(k), c.header(k)) + } + } + id := h.Get("x-opencode-session") + if !openCodeRealSession(id) { + t.Errorf("session %q", id) + } + for _, k := range []string{"x-opencode-session-id", "x-session-affinity", "x-session-id"} { + if h.Get(k) != id { + t.Errorf("%s %q, session %q", k, h.Get(k), id) + } + } + b3 := regexp.MustCompile(`^([0-9a-f]{32})-([0-9a-f]{16})-1-[0-9a-f]{16}$`) + tp := regexp.MustCompile(`^00-([0-9a-f]{32})-([0-9a-f]{16})-01$`) + if !b3.MatchString(c.header("b3")) || !tp.MatchString(c.header("traceparent")) { + t.Fatalf("the capture's trace headers aren't of the shape checked: %q %q", c.header("b3"), c.header("traceparent")) + } + b, p := b3.FindStringSubmatch(h.Get("b3")), tp.FindStringSubmatch(h.Get("traceparent")) + if b == nil || p == nil || b[1] != p[1] || b[2] != p[2] { + t.Fatalf("b3 %q traceparent %q", h.Get("b3"), h.Get("traceparent")) + } + if !regexp.MustCompile(`^[0-9a-f]{40}$`).MatchString(h.Get("x-opencode-project")) || h.Get("x-opencode-project") == "global" { + t.Errorf("project %q", h.Get("x-opencode-project")) + } + // the conversation's next request: the same session and trace, a new span + h2 := http.Header{} + OpenCodeClient(h2, "conversation-225", "") + b2 := b3.FindStringSubmatch(h2.Get("b3")) + if h2.Get("x-opencode-session") != id || b2 == nil || b2[1] != b[1] || b2[2] == b[2] { + t.Errorf("next request: session %q b3 %q (first %q)", h2.Get("x-opencode-session"), h2.Get("b3"), h.Get("b3")) + } + // another conversation: another trace + h3 := http.Header{} + OpenCodeClient(h3, "conversation-other", "") + if b3 := b3.FindStringSubmatch(h3.Get("b3")); b3 == nil || b3[1] == b[1] { + t.Errorf("another conversation's b3 %q", h3.Get("b3")) + } +} + +// OpenCode's project id (packages/core/src/project.ts): sha1 of +// git-remote:host/path in a repository with a remote (origin, else the +// first), else of directory: and the repository's root or the folder. +func TestOpenCodeProjectIs225s(t *testing.T) { + c := loadOpenCode225(t) + if runtime.GOOS != "windows" { + // the folder 2.2.5 ran in, not a repository: the id it sent + if got := OpenCodeProject("/Users/yetone/runs/zencap/home/work"); got != c.header("x-opencode-project") { + t.Errorf("project %q, OpenCode sent %q", got, c.header("x-opencode-project")) + } + } + root := t.TempDir() + root, _ = filepath.EvalSymlinks(root) + repo := func(name, config string) string { + d := filepath.Join(root, name) + os.MkdirAll(filepath.Join(d, ".git"), 0o755) + os.MkdirAll(filepath.Join(d, "src", "deep"), 0o755) + os.WriteFile(filepath.Join(d, ".git", "config"), []byte(config), 0o644) + return d + } + plain := filepath.Join(root, "plain") + os.MkdirAll(plain, 0o755) + scp := repo("scp", "[core]\n\tbare = false\n[remote \"upstream\"]\n\turl = https://other.test/x/y.git\n[remote \"origin\"]\n\turl = git@GitHub.com:Foo/Bar.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n") + first := repo("first", "[remote \"upstream\"]\n\turl = https://GitLab.com/a/b/\n") + local := repo("local", "[core]\n\tbare = false\n") + file := repo("file", "[remote \"origin\"]\n\turl = file:///srv/x.git\n") + // a worktree: .git is a file naming its gitdir, whose commondir is the + // main repository's + wt := filepath.Join(root, "wt") + os.MkdirAll(wt, 0o755) + own := filepath.Join(scp, ".git", "worktrees", "wt") + os.MkdirAll(own, 0o755) + os.WriteFile(filepath.Join(own, "commondir"), []byte("../..\n"), 0o644) + os.WriteFile(filepath.Join(wt, ".git"), []byte("gitdir: "+own+"\n"), 0o644) + for dir, want := range map[string]string{ + plain: "directory:" + plain, + filepath.Join(scp, "src", "deep"): "git-remote:github.com/Foo/Bar", + filepath.Join(first, "src"): "git-remote:gitlab.com/a/b", + filepath.Join(local, "src", "deep"): "directory:" + local, + file: "directory:" + file, + wt: "git-remote:github.com/Foo/Bar", + } { + if got := OpenCodeProject(dir); got != sha1Hex(want) { + t.Errorf("%s: %s, want sha1(%q)", dir, got, want) + } + } + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("USERPROFILE", home) + home, _ = filepath.EvalSymlinks(home) + if got := OpenCodeProject(""); got != sha1Hex("directory:"+home) { + t.Errorf("no folder: %s, want the home folder's", got) + } +} + +// The environment block is OpenCode 2.2.5's word for word, said for the +// folder given (#3491: Zen's free tier serves a request as OpenCode's only +// with one). +func TestOpenCodeEnvironmentIs225s(t *testing.T) { + c := loadOpenCode225(t) + tmp := t.TempDir() + t.Setenv("TMPDIR", tmp) + t.Setenv("TEMP", tmp) + t.Setenv("TMP", tmp) + realTmp, _ := filepath.EvalSymlinks(os.TempDir()) + platform := map[string]string{"windows": "win32"}[runtime.GOOS] + if platform == "" { + platform = runtime.GOOS + } + dir := filepath.Join(t.TempDir(), "work") + os.MkdirAll(dir, 0o755) + want := c.Environment + want = strings.ReplaceAll(want, "/Users/yetone/runs/zencap/home/work", dir) + want = strings.Replace(want, "Platform: darwin", "Platform: "+platform, 1) + want = strings.Replace(want, "/private/tmp/opencode", filepath.Join(realTmp, "opencode"), 1) + if got := OpenCodeEnvironment(dir); got != want { + t.Fatalf("block\n%s\nwant\n%s", got, want) + } + if !OpenCodeHasEnvironment("You are OpenCode.\n\n"+c.Environment) || OpenCodeHasEnvironment("\n working directory: /x\n") { + t.Fatal("OpenCode's block is told by , Working directory: and ") + } + // in a repository's subfolder: the root is the workspace + repo := filepath.Join(t.TempDir(), "repo") + sub := filepath.Join(repo, "pkg") + os.MkdirAll(filepath.Join(repo, ".git"), 0o755) + os.MkdirAll(sub, 0o755) + repo, _ = filepath.EvalSymlinks(repo) + sub, _ = filepath.EvalSymlinks(sub) + got := OpenCodeEnvironment(sub) + if !strings.Contains(got, " Working directory: "+sub+"\n Workspace root folder: "+repo+"\n Is directory a git repo: yes\n") { + t.Fatalf("in a repository:\n%s", got) + } +} + +// The core tools a free request offers are OpenCode 2.2.5's, by name and +// parameters, strict false on Chat as its are. +func TestOpenCodeToolsAre225s(t *testing.T) { + c := loadOpenCode225(t) + var names []string + for _, tl := range c.Tools { + names = append(names, tl.Function.Name) + var want, got any + _ = json.Unmarshal(tl.Function.Parameters, &want) + if err := json.Unmarshal([]byte(OpenCodeToolSchemas[tl.Function.Name]), &got); err != nil { + t.Fatalf("%s: %v", tl.Function.Name, err) + } + w, _ := json.Marshal(want) + g, _ := json.Marshal(got) + if string(w) != string(g) { + t.Errorf("%s:\n got %s\nwant %s", tl.Function.Name, g, w) + } + if tl.Function.Strict == nil || *tl.Function.Strict { + t.Fatalf("the capture's %s isn't strict false", tl.Function.Name) + } + } + if !slices.Equal(names, OpenCodeTools) { + t.Fatalf("tools %v, OpenCode 2.2.5 sent %v", OpenCodeTools, names) + } + // the Test button's probe offers them so, with the block + probe := zenFreeProbe(Chat, `{"model":"m","messages":[{"role":"user","content":"hi"}],"max_tokens":16}`) + var m struct { + Messages []struct{ Role, Content string } + Tools []struct { + Function struct { + Name string + Strict *bool + } + } + Stream bool + StreamOptions map[string]bool `json:"stream_options"` + } + if err := json.Unmarshal([]byte(probe), &m); err != nil { + t.Fatal(err) + } + if len(m.Tools) != 5 || m.Tools[0].Function.Strict == nil || *m.Tools[0].Function.Strict || !m.Stream || !m.StreamOptions["include_usage"] { + t.Fatalf("probe %s", probe) + } + if len(m.Messages) != 2 || m.Messages[0].Role != "system" || !OpenCodeHasEnvironment(m.Messages[0].Content) { + t.Fatalf("probe's prompt %s", probe) + } + for proto, key := range map[Protocol]string{Responses: "instructions", Anthropic: "system"} { + var o map[string]any + _ = json.Unmarshal([]byte(zenFreeProbe(proto, `{"model":"m"}`)), &o) + if s, _ := o[key].(string); !OpenCodeHasEnvironment(s) { + t.Errorf("%s probe: %s %v", proto, key, o[key]) + } + } +} + +// The version OpenCode's updater says is latest is sent, read at most +// every six hours, never one older than 2.2.5 or not a release's. +func TestOpenCodeVersionFromUpdater(t *testing.T) { + var asked atomic.Int32 + answer := atomic.Value{} + answer.Store(`{"version":"2.3.1"}`) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + asked.Add(1) + if r.URL.Query().Get("current") == "" { + w.WriteHeader(400) + return + } + switch a := answer.Load().(string); a { + case "500": + w.WriteHeader(500) + case "redirect": + http.Redirect(w, r, "/elsewhere", http.StatusFound) + default: + w.Write([]byte(a)) + } + })) + defer srv.Close() + for a, want := range map[string]string{ + `{"version":"2.3.1"}`: "2.3.1", + `{"version":"2.2.5"}`: "2.2.5", + `{"version":"2.10.0"}`: "2.10.0", + `{"version":"2.2.4"}`: "", + `{"version":"1.19.0"}`: "", + `{"version":"2.3.0-beta"}`: "", + `{"version":"latest"}`: "", + `{"version":3}`: "", + `not json`: "", + "500": "", + "redirect": "", + } { + answer.Store(a) + if got := openCodeAskVersion(srv.URL, OpenCodeVersion); got != want { + t.Errorf("%s: %q, want %q", a, got, want) + } + } + + answer.Store(`{"version":"2.3.1"}`) + asked.Store(0) + openCodeVersion.Lock() + savedV, savedAt := openCodeVersion.v, openCodeVersion.at + openCodeVersion.v, openCodeVersion.at = "", time.Time{} + openCodeVersion.Unlock() + oldURL := openCodeVersionURL + openCodeVersionURL = srv.URL + t.Cleanup(func() { + openCodeVersion.Lock() + openCodeVersion.v, openCodeVersion.at, openCodeVersion.asking = savedV, savedAt, false + openCodeVersion.Unlock() + openCodeVersionURL = oldURL + }) + if ua := OpenCodeUserAgent(); ua != "opencode/latest/2.2.5/cli" { + t.Fatalf("before the updater answers: %q", ua) + } + deadline := time.Now().Add(10 * time.Second) + for OpenCodeUserAgent() != "opencode/latest/2.3.1/cli" { + if time.Now().After(deadline) { + t.Fatalf("the updater's version never taken: %q", OpenCodeUserAgent()) + } + time.Sleep(10 * time.Millisecond) + } + for range 5 { + OpenCodeUserAgent() + } + if n := asked.Load(); n != 1 { + t.Fatalf("updater asked %d times within six hours", n) + } + // six hours on, asked again; a read that fails keeps the last + answer.Store("500") + openCodeVersion.Lock() + openCodeVersion.at = time.Now().Add(-openCodeVersionEvery - time.Minute) + openCodeVersion.Unlock() + OpenCodeUserAgent() + for asked.Load() != 2 { + if time.Now().After(deadline) { + t.Fatal("not asked again after six hours") + } + time.Sleep(10 * time.Millisecond) + } + for { + openCodeVersion.Lock() + done := !openCodeVersion.asking + openCodeVersion.Unlock() + if done { + break + } + time.Sleep(10 * time.Millisecond) + } + if ua := OpenCodeUserAgent(); ua != "opencode/latest/2.3.1/cli" { + t.Fatalf("after a failed read: %q", ua) + } +} diff --git a/internal/provider/opencode_zen_test.go b/internal/provider/opencode_zen_test.go index a0148e0aa..7b9a68e4f 100644 --- a/internal/provider/opencode_zen_test.go +++ b/internal/provider/opencode_zen_test.go @@ -40,8 +40,8 @@ func TestOpenCodeZenListsFreeModels(t *testing.T) { } } -// The Test button's probe of a free model is streamed and offers bash and -// read, each in the protocol's own tool shape. +// The Test button's probe of a free model is streamed and offers +// OpenCode's five core tools, each in the protocol's own tool shape. func TestZenFreeProbe(t *testing.T) { for proto, key := range map[Protocol]string{Chat: "function", Responses: "name", Anthropic: "input_schema"} { var m map[string]any @@ -49,7 +49,7 @@ func TestZenFreeProbe(t *testing.T) { t.Fatal(err) } tools, _ := m["tools"].([]any) - if m["stream"] != true || len(tools) != 2 || m["model"] != "x-free" { + if m["stream"] != true || len(tools) != len(OpenCodeTools) || m["model"] != "x-free" { t.Fatalf("%v: %v", proto, m) } if _, ok := tools[0].(map[string]any)[key]; !ok { @@ -141,28 +141,45 @@ func TestZenAddKeyEmptyIsPublic(t *testing.T) { } } -// Zen's free tier is asked at the inference API's root, on every API's -// URL Zen's own is saved with; Go's and other URLs are as they were. +// Zen's free tier is asked where OpenCode 2 asks it, the base_url +// models.dev's v2 catalog gives each protocol (#3491): /inference/openai/v1 +// for Chat and Responses, /inference/anthropic for Messages, from Zen's own +// URL or 1.x's /inference/v1. Go's and other URLs are as they were. func TestOpenCodeFreeURL(t *testing.T) { - for in, want := range map[string]string{ - "https://opencode.ai/zen/v1": "https://opencode.ai/inference/v1", - "https://opencode.ai/zen/v1/": "https://opencode.ai/inference/v1/", - "https://opencode.ai/zen/v1/responses": "https://opencode.ai/inference/v1/responses", - "https://opencode.ai/zenith/v1": "https://opencode.ai/zenith/v1", - "https://opencode.ai/zen": "https://opencode.ai/inference", - "https://opencode.ai/inference/v1": "https://opencode.ai/inference/v1", - "https://opencode.ai/zen/go/v1": "https://opencode.ai/zen/go/v1", - "https://relay.test/zen/v1": "https://relay.test/zen/v1", - "https://api.opencode.ai/zen/v1": "https://api.opencode.ai/inference/v1", + for _, c := range []struct { + in string + proto Protocol + want string + }{ + {"https://opencode.ai/zen/v1", Chat, "https://opencode.ai/inference/openai/v1"}, + {"https://opencode.ai/zen/v1/", Chat, "https://opencode.ai/inference/openai/v1/"}, + {"https://opencode.ai/zen/v1/chat/completions", Chat, "https://opencode.ai/inference/openai/v1/chat/completions"}, + {"https://opencode.ai/zen/v1/responses", Responses, "https://opencode.ai/inference/openai/v1/responses"}, + {"https://opencode.ai/inference/v1", Chat, "https://opencode.ai/inference/openai/v1"}, + {"https://opencode.ai/inference/v1", Responses, "https://opencode.ai/inference/openai/v1"}, + {"https://opencode.ai/inference/openai/v1", Chat, "https://opencode.ai/inference/openai/v1"}, + {"https://opencode.ai/zen", Anthropic, "https://opencode.ai/inference/anthropic"}, + {"https://opencode.ai/zen/v1/messages", Anthropic, "https://opencode.ai/inference/anthropic/v1/messages"}, + {"https://opencode.ai/inference", Anthropic, "https://opencode.ai/inference/anthropic"}, + {"https://opencode.ai/inference/anthropic/v1", Anthropic, "https://opencode.ai/inference/anthropic/v1"}, + {"https://opencode.ai/zen/v1", Gemini, "https://opencode.ai/inference/v1"}, + {"https://opencode.ai/zenith/v1", Chat, "https://opencode.ai/zenith/v1"}, + {"https://opencode.ai/zen/go/v1", Chat, "https://opencode.ai/zen/go/v1"}, + {"https://opencode.ai/zen/go", Anthropic, "https://opencode.ai/zen/go"}, + {"https://relay.test/zen/v1", Chat, "https://relay.test/zen/v1"}, + {"https://api.opencode.ai/zen/v1", Chat, "https://api.opencode.ai/inference/openai/v1"}, } { - if got := OpenCodeFreeURL(in); got != want { - t.Errorf("%s: %s, want %s", in, got, want) + if got := OpenCodeFreeURL(c.in, c.proto); got != c.want { + t.Errorf("%s on %s: %s, want %s", c.in, c.proto, got, c.want) } } p, _ := FromPreset("opencode-zen") - if url, _ := tiny(p, Responses, "muse-spark-1.3-contributor-free"); url != "https://opencode.ai/inference/v1/responses" { + if url, _ := tiny(p, Responses, "muse-spark-1.3-contributor-free"); url != "https://opencode.ai/inference/openai/v1/responses" { t.Fatalf("probe %s", url) } + if url, _ := tiny(p, Anthropic, "claude-free"); url != "https://opencode.ai/inference/anthropic/v1/messages" { + t.Fatalf("Messages probe %s", url) + } if url, _ := tiny(p, Responses, "gpt-5.5"); url != "https://opencode.ai/zen/v1/responses" { t.Fatalf("paid probe %s", url) } @@ -208,7 +225,7 @@ func zenFake(t *testing.T) func() []string { if api == "" { api = "chat" } - path := map[string]string{"chat": "/inference/v1/chat/completions", "responses": "/inference/v1/responses", "anthropic": "/inference/messages"}[api] + path := map[string]string{"chat": "/inference/openai/v1/chat/completions", "responses": "/inference/openai/v1/responses", "anthropic": "/inference/anthropic/v1/messages"}[api] if !strings.HasSuffix(model, "-free") && model != "big-pickle" || r.URL.Path != path { w.WriteHeader(http.StatusUnauthorized) return diff --git a/internal/provider/remote_magpie.go b/internal/provider/remote_magpie.go index 9ff7f03cc..255d4255e 100644 --- a/internal/provider/remote_magpie.go +++ b/internal/provider/remote_magpie.go @@ -3,6 +3,7 @@ package provider import ( "context" "maps" + "slices" "strings" "github.com/yetone/magpie/internal/catalog" @@ -152,6 +153,13 @@ func (p Provider) listHeadersAt(u string) map[string]string { } id := openCodeSession("") h["X-Opencode-Session"], h["X-Opencode-Session-Id"] = id, id + // as OpenCode 2 asks its gateway (#3491), unless the user set their own + if !slices.ContainsFunc(slices.Collect(maps.Keys(h)), func(k string) bool { return strings.EqualFold(k, "User-Agent") }) { + h["User-Agent"] = OpenCodeUserAgent() + } + if !slices.ContainsFunc(slices.Collect(maps.Keys(h)), func(k string) bool { return strings.EqualFold(k, "x-opencode-client") }) { + h["X-Opencode-Client"] = "cli" + } return h } diff --git a/internal/provider/test.go b/internal/provider/test.go index 19b3589d5..a29178747 100644 --- a/internal/provider/test.go +++ b/internal/provider/test.go @@ -117,7 +117,7 @@ func tiny(q Provider, proto Protocol, model string) (url, body string) { body = strings.TrimSuffix(body, "}") + `,"stream":true}` } if q.OpenCodeFree(model) && body != "" { - url, body = OpenCodeFreeURL(url), zenFreeProbe(proto, body) + url, body = OpenCodeFreeURL(url, proto), zenFreeProbe(proto, body) } if q.IsCline() && body != "" { body = clineProbe(body) @@ -690,7 +690,7 @@ func probeOnce(ctx context.Context, p Provider, proto Protocol, url string, body req.Header.Set("anthropic-version", "2023-06-01") } if OpenCodeURL(url) { - OpenCodeClient(req.Header, "") // a session of the probe's own + OpenCodeClient(req.Header, "", "") // a session of the probe's own, from the home folder } if p.IsCline() { ClineClient(req.Header) diff --git a/internal/provider/testdata/opencode-2.2.5-chat.json b/internal/provider/testdata/opencode-2.2.5-chat.json new file mode 100644 index 000000000..17346af8f --- /dev/null +++ b/internal/provider/testdata/opencode-2.2.5-chat.json @@ -0,0 +1,263 @@ +{ + "captured": "OpenCode 2.2.5 release binary (@opencode/cli), sandbox HOME on mote, at a recording proxy, 2026-11-01T05:33Z: its primary chat request for deepseek-v4.1-flash-free", + "method": "POST", + "url": "/inference/v1/chat/completions", + "status": 429, + "headers": [ + [ + "Authorization", + "Bearer public" + ], + [ + "Content-Type", + "application/json" + ], + [ + "User-Agent", + "opencode/latest/2.2.5/cli" + ], + [ + "b3", + "6a693d4fc42bc0b0c04fd83712a03bae-f076ef33aef71e8e-1-4727dea9e05b5761" + ], + [ + "traceparent", + "00-6a693d4fc42bc0b0c04fd83712a03bae-f076ef33aef71e8e-01" + ], + [ + "x-opencode-client", + "cli" + ], + [ + "x-opencode-project", + "1132ded9876e9dc00df57eea7de251c155550345" + ], + [ + "x-opencode-session", + "ses_e6a66888dffe4VGjh70Dg9k6f3" + ], + [ + "x-opencode-session-id", + "ses_e6a66888dffe4VGjh70Dg9k6f3" + ], + [ + "x-session-affinity", + "ses_e6a66888dffe4VGjh70Dg9k6f3" + ], + [ + "x-session-id", + "ses_e6a66888dffe4VGjh70Dg9k6f3" + ], + [ + "Connection", + "keep-alive" + ], + [ + "Accept", + "*/*" + ], + [ + "Host", + "127.0.0.1:47811" + ], + [ + "Accept-Encoding", + "gzip, deflate, br, zstd" + ], + [ + "Content-Length", + "22720" + ] + ], + "bodyKeys": [ + "model", + "messages", + "tools", + "stream", + "stream_options", + "max_completion_tokens" + ], + "stream_options": { + "include_usage": true + }, + "environment": "Here is some useful information about the environment you are running in:\n\n Working directory: /Users/yetone/runs/zencap/home/work\n Workspace root folder: /Users/yetone/runs/zencap/home/work\n Is directory a git repo: no\n Platform: darwin\n Prefer /private/tmp/opencode over generic system temporary directories such as /tmp; it is pre-created and approved for external access.\n", + "tools": [ + { + "type": "function", + "function": { + "name": "edit", + "description": "(OpenCode description left out)", + "parameters": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "File to edit" + }, + "oldString": { + "type": "string", + "description": "Exact text to find and replace" + }, + "newString": { + "type": "string", + "description": "Text to replace oldString with (must differ from oldString)" + }, + "replaceAll": { + "type": "boolean", + "description": "Whether to replace every occurrence of oldString. When false, oldString must match exactly once. Defaults to false." + } + }, + "required": [ + "path", + "oldString", + "newString" + ], + "additionalProperties": false + }, + "strict": false + } + }, + { + "type": "function", + "function": { + "name": "glob", + "description": "(OpenCode description left out)", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "description": "Glob pattern to match files against" + }, + "path": { + "type": "string", + "description": "Directory to search. Defaults to the current working directory." + }, + "hidden": { + "type": "boolean", + "description": "Include hidden files and directories (default: false)." + }, + "limit": { + "type": "integer", + "exclusiveMinimum": 0, + "description": "Maximum number of matching files to return (default: 100)" + } + }, + "required": [ + "pattern" + ], + "additionalProperties": false + }, + "strict": false + } + }, + { + "type": "function", + "function": { + "name": "grep", + "description": "(OpenCode description left out)", + "parameters": { + "type": "object", + "properties": { + "pattern": { + "type": "string", + "minLength": 1, + "description": "Regular expression or literal text to match in file contents." + }, + "path": { + "type": "string", + "description": "File or directory to search. Defaults to the current working directory." + }, + "include": { + "type": "string", + "description": "Glob pattern to filter files (for example, \"*.js\" or \"*.{ts,tsx}\")" + }, + "literal": { + "type": "boolean", + "description": "Treat `pattern` as exact text instead of a regular expression (default: false)." + }, + "caseSensitive": { + "type": "boolean", + "description": "Use case-sensitive matching (default: true)." + }, + "limit": { + "type": "integer", + "exclusiveMinimum": 0, + "description": "Maximum number of matching lines to return (default: 100)" + } + }, + "required": [ + "pattern" + ], + "additionalProperties": false + }, + "strict": false + } + }, + { + "type": "function", + "function": { + "name": "read", + "description": "(OpenCode description left out)", + "parameters": { + "type": "object", + "properties": { + "path": { + "type": "string", + "description": "File or directory to read" + }, + "offset": { + "type": "integer", + "minimum": 0, + "description": "The line or directory entry to start reading from (1-based)" + }, + "limit": { + "type": "integer", + "minimum": 0, + "description": "The maximum number of lines or directory entries to read (defaults to and capped at 2000)" + } + }, + "required": [ + "path" + ], + "additionalProperties": false + }, + "strict": false + } + }, + { + "type": "function", + "function": { + "name": "shell", + "description": "(OpenCode description left out)", + "parameters": { + "type": "object", + "properties": { + "command": { + "type": "string", + "description": "Shell command string to execute" + }, + "workdir": { + "type": "string", + "description": "Working directory to execute the command in. Defaults to the current working directory. When possible, avoid changing directories in the command and set the working directory here instead." + }, + "timeout": { + "type": "integer", + "minimum": 0, + "description": "Timeout in milliseconds. Set to 0 to disable the timeout. Defaults to 120000 for foreground commands. Background commands have no timeout by default." + }, + "background": { + "type": "boolean", + "description": "Run the command in the background and return immediately (useful for dev servers and long-running builds). You do not need to use '&' at the end of the command when using this parameter. You will be notified when it completes. DO NOT poll for completion." + } + }, + "required": [ + "command" + ], + "additionalProperties": false + }, + "strict": false + } + } + ] +}