diff --git a/README.md b/README.md index e8a7458..ddfabbe 100644 --- a/README.md +++ b/README.md @@ -256,7 +256,7 @@ See [config.example.json](config.example.json) for a complete starting configura | `zen_keys`, `go_keys` | At least one upstream key is required unless anonymous access is enabled. | | `anonymous` | `false`. | | `prefer` | `go`; accepts `go` or `zen`. | -| `upstream.zen` | `https://opencode.ai/zen`. | +| `upstream.zen` | `https://opencode.ai/inference/openai`. | | `upstream.go` | `https://opencode.ai/zen/go`. | | `proxies` | Falls back to `["direct"]` when both proxy sources are empty. | | `proxyfile` | Optional; relative paths resolve beside the configuration file. | diff --git a/README.zh-CN.md b/README.zh-CN.md index 344b8ea..c99a954 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -256,7 +256,7 @@ Key 初始化时均衡分配到代理。真实流量可以触发代理检查、K | `zen_keys`、`go_keys` | 未启用匿名模式时,至少需要一个上游 Key。 | | `anonymous` | `false`。 | | `prefer` | `go`;可选 `go`、`zen`。 | -| `upstream.zen` | `https://opencode.ai/zen`。 | +| `upstream.zen` | `https://opencode.ai/inference/openai`。 | | `upstream.go` | `https://opencode.ai/zen/go`。 | | `proxies` | 两个代理来源都为空时,使用 `["direct"]`。 | | `proxyfile` | 可选;相对路径基于配置文件所在目录解析。 | diff --git a/internal/gateway/probe.go b/internal/gateway/probe.go index 9dccfdb..ed5bbc0 100644 --- a/internal/gateway/probe.go +++ b/internal/gateway/probe.go @@ -73,7 +73,7 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult if !d.AvailableZen || !g.catalog.Supported(model) { return probeResult{reason: "unsupported_probe"} } - ids := identity.RequestIDs{Session: identity.CanonicalSessionID("availability:" + model), Project: identity.StableID("prj", "opencode2api:default-project")} + ids := identity.RequestIDs{Session: identity.CanonicalSessionID("availability:" + model), Project: "opencode2api:default-project"} type lane struct { key, name, baseURL string client *http.Client diff --git a/internal/gateway/refresh.go b/internal/gateway/refresh.go index 0a404a7..acd5b46 100644 --- a/internal/gateway/refresh.go +++ b/internal/gateway/refresh.go @@ -220,6 +220,11 @@ func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []strin } refreshCtx, cancel := context.WithTimeout(ctx, 30*time.Second) models, status, err := modelcatalog.FetchModels(refreshCtx, node.proxy.client, base, anonymousZenKey) + if err != nil && status == 404 { + // The new inference backend does not expose a models listing; + // probe the legacy Zen console origin once before giving up. + models, status, err = modelcatalog.FetchModels(refreshCtx, node.proxy.client, modelcatalog.LegacyZenBase, anonymousZenKey) + } g.syncProxyResult(refreshCtx, node.proxy, status, err) cancel() if err == nil { diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 8c68b8b..19f71ed 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -270,10 +270,10 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b return nil, errors.New("no prepared Zen request body"), 0 } // The anonymous free tier only serves agent-shaped streaming requests - // (anything else is rejected with 403 FreeTierError). Normalize the - // wire body here; the gateway collapses the stream back when the - // downstream client asked for a plain JSON reply. Key tiers keep their - // original bodies. + // carrying the official core tool definitions (anything else is rejected + // with 403 FreeTierError). Normalize the wire body here; the gateway + // collapses the stream back when the downstream client asked for a plain + // JSON reply. Key tiers keep their original bodies. body = prepareAnonymousBody(body, route.ProtocolFor(config.TierZen)) for attempts < limit { if ctx.Err() != nil { @@ -346,7 +346,11 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b // "shell" is the name OpenCode 2.x ships; the pre-2.x "bash" spelling is // deliberately not injected because the free tier validates the definition of // every tool it recognises, and a "bash" definition the gateway synthesises -// does not match the one upstream expects. +// does not match the one upstream expects. Since 2026-10-14 name presence is +// not enough either: the upstream compares each recognised tool's description +// and parameter schema against the official CLI's definitions byte-for-byte +// (minimal stand-ins 403), which is why the genuine definitions below are +// embedded. Tool order is irrelevant and extra client tools are allowed. var anonymousCoreTools = []string{"shell", "edit", "glob", "grep", "read"} // opencodeToolsJSON holds the genuine OpenCode tool definitions (description @@ -496,19 +500,25 @@ func anonymousToolName(protocol wire.Protocol, item any) string { return jsonutil.StringAt(entry, "name") } +// anonymousToolset returns the official wire-shaped definitions for the +// given tool names (all core tools when names is nil). func anonymousToolset(protocol wire.Protocol, names []string) []any { if names == nil { names = anonymousCoreTools } tools := make([]any, 0, len(names)) for _, name := range names { - tools = append(tools, anonymousTool(protocol, name)) + if tool := anonymousTool(protocol, name); tool != nil { + tools = append(tools, tool) + } } return tools } // anonymousTool renders one core tool in the shape the given protocol expects, -// using the genuine OpenCode definition whenever one is known. +// using the genuine OpenCode definition whenever one is known. SystemOne +// payloads never reach this path (prepareAnonymousBody forwards them +// verbatim), so it falls back to the Chat shape. func anonymousTool(protocol wire.Protocol, name string) map[string]any { description := "Agent tool " + name parameters := map[string]any{"type": "object", "properties": map[string]any{}} @@ -873,10 +883,18 @@ func newUpstreamRequest(ctx context.Context, baseURL string, protocol wire.Proto // FreeTierError, so the client's header set is mirrored exactly. req.Header.Set("User-Agent", httpx.UserAgent()) req.Header.Set("x-opencode-client", "cli") + // The free tier requires both session headers to carry the same + // descending-encoded id. The x-opencode-request correlation header and + // canonical prj_* project ids are rejected with 403 since 2026-10-14, so + // neither is forwarded; tracing stays local to this gateway. req.Header.Set("x-opencode-session", ids.Session) req.Header.Set("x-opencode-session-id", ids.Session) req.Header.Set("x-session-affinity", ids.Session) req.Header.Set("X-Session-Id", ids.Session) + // A canonical prj_* project id is rejected with 403 since 2026-10-14; the + // client's own bare 40-hex shape (or any non-canonical value, e.g. + // "global") passes. Hash the local project signal into the accepted shape + // so one conversation stays pinned to one upstream project. req.Header.Set("x-opencode-project", clientProjectID(ids.Project)) if ids.ParentSession != "" { req.Header.Set("x-parent-session-id", ids.ParentSession) @@ -886,6 +904,9 @@ func newUpstreamRequest(ctx context.Context, baseURL string, protocol wire.Proto req.Header.Set("anthropic-version", "2023-06-01") req.Header.Set("anthropic-beta", "interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14") } else { + // The anonymous credential is the literal token "public". The 2026-10-14 + // gate rejects keyless requests (an absent header used to pass) and is + // case-sensitive: "Bearer PUBLIC" 401s. req.Header.Set("Authorization", "Bearer "+key) } return req, nil diff --git a/internal/httpx/client.go b/internal/httpx/client.go index 804f2ee..b0e619d 100644 --- a/internal/httpx/client.go +++ b/internal/httpx/client.go @@ -1,8 +1,8 @@ package httpx // clientVersion is the OpenCode release the gateway claims to be. Upstream -// accepts a range of releases, so this only needs bumping when it starts -// rejecting older ones. +// accepts a range of releases (the version number itself is not validated), +// so this only needs bumping when it starts rejecting older ones. const clientVersion = "2.0.29" // UserAgent reports the gateway as an OpenCode client using the shape upstream diff --git a/internal/identity/request.go b/internal/identity/request.go index 497f68e..5c5f0ea 100644 --- a/internal/identity/request.go +++ b/internal/identity/request.go @@ -1,4 +1,11 @@ -// Package identity derives stable session identities and unique request IDs. +// Package identity derives stable session identities. +// +// The 2026-10-14 Zen free-tier gate validates a descending-timestamp session +// id plus a client User-Agent, and it 403s requests that still carry the +// legacy x-opencode-request header. The identity that matters upstream is +// therefore the pair (x-opencode-session, x-opencode-session-id): Session is +// the conversation-affinity key and must keep the descending layout minted by +// CanonicalSessionID. package identity import ( @@ -14,6 +21,10 @@ import ( "opencode2api/internal/jsonutil" ) +// RequestIDs carries the identity headers the upstream free tier inspects. +// Session is sent as both x-opencode-session and x-opencode-session-id; both +// headers are required since the 2026-10-14 gate. Request is retained for +// request-level tracing of this gateway only — it must NOT reach upstream. type RequestIDs struct { Session string Request string @@ -24,6 +35,7 @@ type RequestIDs struct { func DeriveRequestIDs(r *http.Request, body map[string]any) RequestIDs { signal := jsonutil.FirstString( r.Header.Get("x-opencode-session"), + r.Header.Get("x-opencode-session-id"), r.Header.Get("x-session-affinity"), r.Header.Get("X-Session-Id"), r.Header.Get("x-session-id"), @@ -43,6 +55,10 @@ func DeriveRequestIDs(r *http.Request, body map[string]any) RequestIDs { signal = RandomID("fallback", 16) } session := CanonicalSessionID(signal) + // The upstream free tier 403s canonical prj_* project ids (2026-10-14 + // probing) while accepting the literal "global" every official client + // sends. Anything non-canonical also passes, so the project header is only + // used as a local correlation hint and is no longer forwarded upstream. projectSignal := jsonutil.FirstString(r.Header.Get("x-opencode-project"), jsonutil.StringAt(body, "metadata", "project_id")) if projectSignal == "" { projectSignal = "opencode2api:default-project" @@ -54,7 +70,7 @@ func DeriveRequestIDs(r *http.Request, body map[string]any) RequestIDs { return RequestIDs{ Session: session, Request: RandomID("req", 16), - Project: StableID("prj", projectSignal), + Project: projectSignal, ParentSession: parentSession, } } diff --git a/internal/models/discovery.go b/internal/models/discovery.go index 05ac4ff..566fefd 100644 --- a/internal/models/discovery.go +++ b/internal/models/discovery.go @@ -19,6 +19,9 @@ const ( CapabilitiesURL = "https://models.opencode.ai/api.json" ZenDocsURL = "https://raw.githubusercontent.com/anomalyco/opencode/dev/packages/web/src/content/docs/zen.mdx" GoDocsURL = "https://raw.githubusercontent.com/anomalyco/opencode/dev/packages/web/src/content/docs/go.mdx" + // LegacyZenBase is the console origin that still serves the anonymous + // models listing after chat traffic moved to the inference backend. + LegacyZenBase = "https://opencode.ai/zen" ) var protocolDocEndpointPattern = regexp.MustCompile("\\|[^|]+\\|\\s*`?([^|`\\s]+)`?\\s*\\|\\s*`[^`]+/v1/(chat/completions|responses|messages|systemone)`")