Files
magpie/internal/provider/opencode_session_test.go
yetone 9feb1024c7 zen: free models are asked as OpenCode 2.2.5 asks them (#3491)
laomao04_65777 on Discord: Zen's free models answered 429 "Free usage limit
reached. Free models work in OpenCode" to the built-in OpenCode Zen provider,
while real OpenCode 2 on the same machine was served. magpie sent OpenCode
1.x's shape. It now sends what OpenCode 2.2.5 sent in a captured request
(internal/provider/testdata/opencode-2.2.5-chat.json, from a recording proxy),
as the zen-free plugin does since plugins d62193c and 8501988:

- User-Agent opencode/latest/<v>/cli. <v> is the version OpenCode's updater
  (opencode.ai/update/api/latest/cli/npm) names, never below 2.2.5 and never
  anything but a plain x.y.z. It is read in the background at most every 6h,
  with a 3s timeout and no redirects.
- x-opencode-project is OpenCode's project id for the folder the agent says it
  works in: sha1 of git-remote:host/path (origin, else the first remote;
  worktree .git files followed), else of directory:<root or folder>. It is no
  longer "global".
- b3 and traceparent: one trace a conversation, a new span a request.
- The session id goes in x-opencode-session, x-opencode-session-id,
  x-session-affinity and x-session-id. Accept is */*, and x-opencode-request
  is gone.
- On a free request the agent's own headers (Claude Code's x-stainless-*,
  Codex's originator) are dropped. Only Content-Type and Anthropic-Version
  and Anthropic-Beta are kept.
- The core tools are edit, glob, grep, read and shell with 2.2.5's schemas,
  strict false on Chat. Claude Code's Read, Edit, Glob and Grep are offered
  under those names. Its Bash is no longer bash: shell is a stub.
- OpenCode's <env> block, word for word, for the agent's folder, is added to
  the system prompt unless it has one already (OpenCode's own).
- Paths are the v2 catalog's: /inference/openai/v1 for Chat and Responses,
  and /inference/anthropic/v1 for Messages. The models list is unchanged.

Every route takes this: chat, responses and messages through forwardOnce, the
Test button's probe (tiny/zenFreeProbe), and the models list
(listHeadersAt: UA and x-opencode-client).

Sibling: paid Zen and OpenCode Go share OpenCodeClient, so they get 2.2.5's
headers. Their /zen/v1 and /zen/go/v1 paths are left as they are: #4740.

Run on mote (mote-run) at this tree:
- gofmt -l . is clean.
- GOOS=darwin and windows go vet ./... pass. GOOS=linux go vet passes for
  internal/provider and internal/gateway. The whole-tree Linux vet stops in
  Wails' cgo when run from macOS, and in WSL for want of gtk4, before it
  reaches this change.
- go test ./internal/provider ./internal/gateway -count=1 -timeout 45m:
  ok provider (154s) and ok gateway (715s) on base 788057340. After the
  rebase onto a5a9cdf7b, which touched gateway.go and ir.go, the same
  tree passed again: ok provider (138s) and ok gateway (816s), with GOOS
  darwin, linux and windows go vet of both packages.
- Rebased again onto 4c815ac2a, which touched search.go and provider.go.
  At that head gofmt and the three-OS vet of both packages are clean, and
  -run 'OpenCode|Zen|Search|Searcher' passes in both packages. The full
  suites were not rerun after this last rebase.

Broken by hand, each turning a test red (provider and gateway, -run
'OpenCode|Zen', on mote):
- version 1.19.0: TestOpenCodeClientIs225 and TestOpenCodeVersionFromUpdater.
- the old /inference/v1 path: TestOpenCodeFreeURL, TestZenFreeAsOpenCode225,
  TestZenFreeAtInferenceURL and TestZenPublicTestAsksFreeModels.
- caller headers kept: TestZenFreeAsOpenCode225.
- no env block: TestZenFreeAsOpenCode225.
- no strict: TestZenFreeAtInferenceURL.
- project "global": TestOpenCodeClientIs225, TestOpenCodeClientHeaders and
  TestZenFreeAsOpenCode225.
- the same span on every request: TestOpenCodeClientIs225 and
  TestOpenCodeClientHeaders.
- no 2.2.5 floor: TestOpenCodeVersionFromUpdater.
- a changed read schema: TestOpenCodeToolsAre225s.

Not tried:
- A real 200 from a free model: this egress IP's free allowance is spent.
  The captured 2.2.5 request itself got 429.
- Header order and case: Go's HTTP/1 writes headers sorted, and HTTP/2
  lowercases them, so OpenCode's order cannot be copied.
- Windows' project id against real OpenCode on Windows.
2026-11-01 14:48:19 +08:00

120 lines
5.0 KiB
Go

package provider
import (
"context"
"io"
"net/http"
"strings"
"sync"
"testing"
)
// openCodeAsked stands in for OpenCode's gateway on http.DefaultClient,
// where model lists and the Test button's probe go: it answers 400
// "Request is missing x-opencode-session" to a request naming no session,
// as the gateway does since September 2026 (luci on Discord), and keeps
// the session each request named, with its path.
func openCodeAsked(t *testing.T) func() [][2]string {
t.Helper()
var mu sync.Mutex
var asked [][2]string
rt := openCodeTransport(func(r *http.Request) (*http.Response, error) {
if r.Body != nil {
io.Copy(io.Discard, r.Body)
r.Body.Close()
}
s := r.Header.Get("x-opencode-session")
mu.Lock()
asked = append(asked, [2]string{r.URL.Path, s})
mu.Unlock()
h := http.Header{"Content-Type": {"application/json"}}
reply, status := `{"type":"error","error":{"type":"invalid_request_error","message":"Request is missing x-opencode-session and cannot be routed efficiently"}}`, 400
switch {
case s == "":
case strings.HasSuffix(r.URL.Path, "/models"):
reply, status = `{"object":"list","data":[{"id":"glm-5.3","object":"model"}]}`, 200
default:
reply, status = `{"id":"c","object":"chat.completion","model":"glm-5.3","choices":[{"index":0,"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]}`, 200
}
return &http.Response{StatusCode: status, Header: h, Body: io.NopCloser(strings.NewReader(reply)), Request: r}, nil
})
oldT, oldC := http.DefaultTransport, http.DefaultClient.Transport
http.DefaultTransport, http.DefaultClient.Transport = rt, rt
t.Cleanup(func() { http.DefaultTransport, http.DefaultClient.Transport = oldT, oldC })
return func() [][2]string {
mu.Lock()
defer mu.Unlock()
return append([][2]string(nil), asked...)
}
}
type openCodeTransport func(*http.Request) (*http.Response, error)
func (f openCodeTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
// What isn't a conversation's turn names a session too, each its own, as
// OpenCode's own stateless calls do: the model list and the Test button's
// probe of a custom provider at OpenCode Go (its URL naming a port, which
// IsOpenCode didn't see past), and whatever else Sign signs for OpenCode's
// gateway (a System One decision). A session the user set on the
// provider stays theirs; no other vendor is sent one.
func TestOpenCodeSessionOnEveryCall(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
asked := openCodeAsked(t)
p := Provider{ID: "ocgo", Name: "OpenCode Go", Key: "k", Chat: "https://opencode.ai:443/zen/go/v1", Models: []string{"glm-5.3"}}
if err := Save(p); err != nil {
t.Fatal(err)
}
if !p.IsOpenCode() {
t.Error("a URL naming OpenCode's port isn't OpenCode's")
}
rs := p.Test(context.Background())
if len(rs) != 1 || !rs[0].OK {
t.Fatalf("test: %+v", rs)
}
got := asked()
if len(got) != 2 || got[0][0] != "/zen/go/v1/models" || got[1][0] != "/zen/go/v1/chat/completions" {
t.Fatalf("asked: %q", got)
}
if !strings.HasPrefix(got[0][1], "ses_") || !strings.HasPrefix(got[1][1], "ses_") || got[0][1] == got[1][1] {
t.Errorf("list's session %q, probe's %q", got[0][1], got[1][1])
}
sign := func(p Provider, u string) http.Header {
t.Helper()
req, _ := http.NewRequest("POST", u, nil)
if err := p.Sign(context.Background(), req, Chat, nil); err != nil {
t.Fatal(err)
}
return req.Header
}
zen := Provider{ID: "zen", Key: "k", Chat: "https://opencode.ai/zen/v1", Decide: "https://opencode.ai/zen/v1"}
h1, h2 := sign(zen, "https://opencode.ai/zen/v1/systemone"), sign(zen, "https://opencode.ai/zen/v1/systemone")
if s := h1.Get("x-opencode-session"); !openCodeRealSession(s) || h1.Get("x-opencode-session-id") != s || h2.Get("x-opencode-session") == s {
t.Errorf("decisions: %q %q", s, h2.Get("x-opencode-session"))
}
// 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", "")
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)
}
mine := zen
mine.Headers = map[string]string{"X-Opencode-Session": "ses_mine"}
if s := sign(mine, "https://opencode.ai/zen/v1/systemone").Values("x-opencode-session"); len(s) != 1 || s[0] != "ses_mine" {
t.Errorf("the user's own session: %q", s)
}
if h := mine.listHeadersAt("https://opencode.ai/zen/v1"); h["X-Opencode-Session"] != "ses_mine" || len(h) != 1 {
t.Errorf("the user's own session in a list: %q", h)
}
other := Provider{ID: "other", Key: "k", Chat: "https://other.test/v1"}
if h := sign(other, "https://other.test/v1/chat/completions"); h.Get("x-opencode-session") != "" || h.Get("x-opencode-session-id") != "" {
t.Errorf("another vendor: %v", h)
}
if h := other.listHeadersAt("https://other.test/v1"); len(h) != 0 {
t.Errorf("another vendor's list: %v", h)
}
}