feat: prefer legacy /zen/v1 anonymous lane with fallback to /inference

This commit is contained in:
Jason Xu committed 2026-10-17 01:02:59 +08:00
1 parent a6601da673
commit 076451fa31
4 files changed
+131 -53

No files matched your search

+7 -4
View File
@@ -42,7 +42,7 @@ func (g *Gateway) resolvedEffort(model string, tier config.Tier, protocol wire.P
return item.AutoEffort.Effort return item.AutoEffort.Effort
} }
func probePayload(model string, protocol wire.Protocol, effort string) ([]byte, error) { func probePayload(model string, protocol wire.Protocol, effort string, legacy bool) ([]byte, error) {
if protocol == wire.SystemOne { if protocol == wire.SystemOne {
// TypeSafe's native boolean type is "noul", not JSON Schema boolean. // TypeSafe's native boolean type is "noul", not JSON Schema boolean.
return json.Marshal(map[string]any{"model": model, "state": "1 + 1 = 2", "questions": map[string]any{ return json.Marshal(map[string]any{"model": model, "state": "1 + 1 = 2", "questions": map[string]any{
@@ -61,7 +61,7 @@ func probePayload(model string, protocol wire.Protocol, effort string) ([]byte,
if err != nil { if err != nil {
return nil, err return nil, err
} }
return prepareAnonymousBody(b, protocol), nil return prepareAnonymousBody(b, protocol, legacy), nil
} }
func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult { func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult {
@@ -82,7 +82,10 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult
if g.cfg.Anonymous { if g.cfg.Anonymous {
cursor := g.anonymous.CursorFor(ids.Session) cursor := g.anonymous.CursorFor(ids.Session)
if node := cursor.Next(); node != nil { if node := cursor.Next(); node != nil {
lanes = append(lanes, lane{anonymousZenKey, "anonymous", g.cfg.Upstream.Anonymous, node.proxy.client}) // Prefer the legacy /zen/v1 lane before falling back to /inference.
for _, baseURL := range g.anonymousUpstreams() {
lanes = append(lanes, lane{anonymousZenKey, "anonymous", baseURL, node.proxy.client})
}
} }
} }
cursor := g.zenNodes.CursorFor(ids.Session) cursor := g.zenNodes.CursorFor(ids.Session)
@@ -143,7 +146,7 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult
} }
func (g *Gateway) probeAttempt(parent context.Context, client *http.Client, baseURL, key, model string, protocol wire.Protocol, ids identity.RequestIDs, effort string) probeResult { func (g *Gateway) probeAttempt(parent context.Context, client *http.Client, baseURL, key, model string, protocol wire.Protocol, ids identity.RequestIDs, effort string) probeResult {
b, err := probePayload(model, protocol, effort) b, err := probePayload(model, protocol, effort, isLegacyZenUpstream(baseURL))
if err != nil { if err != nil {
return probeResult{reason: "request_conversion_error"} return probeResult{reason: "request_conversion_error"}
} }
+10 -5
View File
@@ -222,11 +222,16 @@ func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []strin
break break
} }
refreshCtx, cancel := context.WithTimeout(ctx, 30*time.Second) refreshCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
models, status, err := modelcatalog.FetchModels(refreshCtx, node.proxy.client, base, anonymousZenKey) var models []string
if err != nil && status == 404 { var status int
// The new inference backend does not expose a models listing; var err error
// probe the legacy Zen console origin once before giving up. // Prefer the legacy /zen/v1 models listing before falling back to the
models, status, err = modelcatalog.FetchModels(refreshCtx, node.proxy.client, modelcatalog.LegacyZenBase, anonymousZenKey) // configured anonymous upstream.
for _, upstream := range g.anonymousUpstreams() {
models, status, err = modelcatalog.FetchModels(refreshCtx, node.proxy.client, upstream, anonymousZenKey)
if err == nil {
break
}
} }
g.syncProxyResult(refreshCtx, node.proxy, status, err) g.syncProxyResult(refreshCtx, node.proxy, status, err)
cancel() cancel()
+111 -42
View File
@@ -255,27 +255,35 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie
return nil, effectiveRoute, attempts, lastErr return nil, effectiveRoute, attempts, lastErr
} }
// doAnonymousUpstream tries every currently available proxy at most once. Any // doAnonymousUpstream tries every currently available proxy at most once. For
// failure, including an HTTP error response, advances to the next proxy. Only a // each proxy it prefers the legacy /zen/v1 lane (LegacyZenBase) before falling
// successful response ends the anonymous phase; exhausting the proxy cursor // back to the newer /inference upstream (Upstream.Anonymous). Any failure,
// returns control to the preferred authenticated tiers. // including an HTTP error response, advances to the next upstream or proxy.
// Only a successful response ends the anonymous phase; exhausting the proxy
// cursor returns control to the preferred authenticated tiers.
func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, error, int) { func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, error, int) {
var lastResponse *http.Response var lastResponse *http.Response
var lastErr error var lastErr error
cursor := g.anonymous.CursorFor(ids.Session) cursor := g.anonymous.CursorFor(ids.Session)
limit := g.anonymous.Len() limit := g.anonymous.Len()
proxies := 0
attempts := 0 attempts := 0
body := bodies[config.TierZen] rawBody := bodies[config.TierZen]
if len(body) == 0 { if len(rawBody) == 0 {
return nil, errors.New("no prepared Zen request body"), 0 return nil, errors.New("no prepared Zen request body"), 0
} }
// The anonymous free tier only serves agent-shaped streaming requests // The anonymous free tier only serves agent-shaped streaming requests
// carrying the official core tool definitions (anything else is rejected // carrying the core tool definitions (anything else is rejected with 403
// with 403 FreeTierError). Normalize the wire body here; the gateway // FreeTierError). Normalize the wire body per upstream gate (legacy /zen/v1
// collapses the stream back when the downstream client asked for a plain // vs /inference); the gateway collapses the stream back when the downstream
// JSON reply. Key tiers keep their original bodies. // client asked for a plain JSON reply. Key tiers keep their original bodies.
body = prepareAnonymousBody(body, route.ProtocolFor(config.TierZen)) protocol := route.ProtocolFor(config.TierZen)
for attempts < limit { upstreams := g.anonymousUpstreams()
preparedBodies := make([][]byte, len(upstreams))
for i, baseURL := range upstreams {
preparedBodies[i] = prepareAnonymousBody(rawBody, protocol, isLegacyZenUpstream(baseURL))
}
for proxies < limit {
if ctx.Err() != nil { if ctx.Err() != nil {
// The request-level budget is already gone. Stop scanning instead // The request-level budget is already gone. Stop scanning instead
// of firing attempts that cannot succeed and then recording them // of firing attempts that cannot succeed and then recording them
@@ -289,6 +297,16 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
if node == nil { if node == nil {
break break
} }
proxies++
var nodeResp *http.Response
var nodeErr error
for index, baseURL := range upstreams {
if ctx.Err() != nil {
if lastErr == nil && lastResponse == nil {
lastErr = ctx.Err()
}
break
}
attempts++ attempts++
if meta := telemetry.MetaFromContext(ctx); meta != nil { if meta := telemetry.MetaFromContext(ctx); meta != nil {
meta.Attempts = attemptOffset + attempts meta.Attempts = attemptOffset + attempts
@@ -298,7 +316,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
httpx.DrainAndClose(lastResponse.Body) httpx.DrainAndClose(lastResponse.Body)
lastResponse = nil lastResponse = nil
} }
req, err := newUpstreamRequest(ctx, g.cfg.Upstream.Anonymous, route.Protocol, body, ids, anonymousZenKey) req, err := newUpstreamRequest(ctx, baseURL, route.Protocol, preparedBodies[index], ids, anonymousZenKey)
if err != nil { if err != nil {
return nil, err, attempts return nil, err, attempts
} }
@@ -316,19 +334,31 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
} }
break break
} }
g.observeAnonymousResult(ctx, node, resp, err) nodeResp, nodeErr = resp, err
g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+attempts, "anonymous", "anonymous", true, node.proxy, resp, err, duration) g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+attempts, "anonymous", "anonymous", true, node.proxy, resp, err, duration)
if err == nil && resp.StatusCode/100 == 2 { if err == nil && resp.StatusCode/100 == 2 {
g.logger.Debug("anonymous upstream accepted request", "component", "upstream", "event", "anonymous_attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds()) g.observeAnonymousResult(ctx, node, resp, nil)
g.logger.Debug("anonymous upstream accepted request", "component", "upstream", "event", "anonymous_attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds())
return resp, nil, attempts return resp, nil, attempts
} }
lastResponse = resp lastResponse = resp
lastErr = asProxyUnavailable(node.proxy, err) lastErr = asProxyUnavailable(node.proxy, err)
if err != nil { if err != nil {
g.logger.Debug("anonymous transport attempt failed", "component", "upstream", "event", "anonymous_attempt_transport_failed", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "duration_ms", duration.Milliseconds(), "error", err) g.logger.Debug("anonymous transport attempt failed", "component", "upstream", "event", "anonymous_attempt_transport_failed", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "duration_ms", duration.Milliseconds(), "error", err)
} else { if isProxyFailure(err) {
g.logger.Debug("anonymous upstream returned an error response; trying the next proxy", "component", "upstream", "event", "anonymous_attempt_response_failed", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds()) break
} }
} else {
g.logger.Debug("anonymous upstream returned an error response; trying the next upstream or proxy", "component", "upstream", "event", "anonymous_attempt_response_failed", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds())
}
if index+1 < len(upstreams) && !node.proxy.healthy.Load() {
break
}
}
if ctx.Err() != nil {
break
}
g.observeAnonymousResult(ctx, node, nodeResp, nodeErr)
} }
if lastResponse != nil { if lastResponse != nil {
return lastResponse, nil, attempts return lastResponse, nil, attempts
@@ -342,18 +372,46 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
return nil, lastErr, attempts return nil, lastErr, attempts
} }
// anonymousCoreTools are the tool names the anonymous free tier expects on // anonymousUpstreams returns the ordered base URLs for the keyless free-tier
// an agent-shaped request. Requests without a shell tool and a read tool are // lane: the legacy /zen/v1 origin (models.LegacyZenBase) is tried first, and
// the configured /inference origin (Upstream.Anonymous) is kept as a fallback.
func (g *Gateway) anonymousUpstreams() []string {
legacy := strings.TrimRight(models.LegacyZenBase, "/")
primary := strings.TrimRight(g.cfg.Upstream.Anonymous, "/")
if primary == "" || strings.EqualFold(legacy, primary) {
return []string{models.LegacyZenBase}
}
return []string{models.LegacyZenBase, g.cfg.Upstream.Anonymous}
}
// isLegacyZenUpstream reports whether baseURL targets the legacy /zen/v1
// gate rather than the newer /inference gate.
func isLegacyZenUpstream(baseURL string) bool {
trimmed := strings.ToLower(strings.TrimRight(strings.TrimSpace(baseURL), "/"))
if strings.EqualFold(trimmed, strings.TrimRight(models.LegacyZenBase, "/")) {
return true
}
return strings.HasSuffix(trimmed, "/zen")
}
// legacyAnonymousCoreTools are the pre-2.x OpenCode 1.18.x tool names expected
// by the legacy /zen/v1 free-tier gate ("bash" + "read" required; stub
// definitions pass without schema validation).
var legacyAnonymousCoreTools = []string{"bash", "edit", "glob", "grep", "read"}
// anonymousCoreTools are the tool names the /inference free-tier gate expects
// on an agent-shaped request. Requests without a shell tool and a read tool are
// rejected with 403 FreeTierError. // rejected with 403 FreeTierError.
// //
// "shell" is the name OpenCode 2.x ships; the pre-2.x "bash" spelling is // "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 // deliberately not injected on /inference because that gate validates the
// every tool it recognises, and a "bash" definition the gateway synthesises // definition of every tool it recognises, and a "bash" definition the gateway
// does not match the one upstream expects. Since 2026-10-14 name presence is // synthesises does not match the one upstream expects. Since 2026-10-14 name
// not enough either: the upstream compares each recognised tool's description // presence is not enough on /inference either: the upstream compares each
// and parameter schema against the official CLI's definitions byte-for-byte // recognised tool's description and parameter schema against the official CLI's
// (minimal stand-ins 403), which is why the genuine definitions below are // definitions byte-for-byte (minimal stand-ins 403), which is why the genuine
// embedded. Tool order is irrelevant and extra client tools are allowed. // definitions below are embedded. Tool order is irrelevant and extra client
// tools are allowed.
var anonymousCoreTools = []string{"shell", "edit", "glob", "grep", "read"} var anonymousCoreTools = []string{"shell", "edit", "glob", "grep", "read"}
// opencodeToolsJSON holds the genuine OpenCode tool definitions (description // opencodeToolsJSON holds the genuine OpenCode tool definitions (description
@@ -390,12 +448,14 @@ func knownOpencodeTool(name string) (opencodeToolDefinition, bool) {
} }
// prepareAnonymousBody returns a copy of body normalized for the anonymous // prepareAnonymousBody returns a copy of body normalized for the anonymous
// free tier: streaming enabled plus the core agent tools present with genuine // free tier: streaming enabled plus the core agent tools present (using
// definitions. Bodies that already satisfy all of that (or are not JSON // legacyAnonymousCoreTools for the legacy /zen/v1 gate and anonymousCoreTools
// objects) are returned unchanged. System One payloads are decision requests, // with genuine definitions for the /inference gate). Bodies that already
// not agent traffic, so they are forwarded verbatim; injecting streaming or // satisfy all of that (or are not JSON objects) are returned unchanged. System
// tool definitions would make the upstream reject them. // One payloads are decision requests, not agent traffic, so they are forwarded
func prepareAnonymousBody(body []byte, protocol wire.Protocol) []byte { // verbatim; injecting streaming or tool definitions would make the upstream
// reject them.
func prepareAnonymousBody(body []byte, protocol wire.Protocol, legacy bool) []byte {
if protocol == wire.SystemOne { if protocol == wire.SystemOne {
return body return body
} }
@@ -411,7 +471,7 @@ func prepareAnonymousBody(body []byte, protocol wire.Protocol) []byte {
if ensureAnonymousChatUsage(payload, protocol) { if ensureAnonymousChatUsage(payload, protocol) {
changed = true changed = true
} }
if ensureAnonymousTools(payload, protocol) { if ensureAnonymousTools(payload, protocol, legacy) {
changed = true changed = true
} }
if !changed { if !changed {
@@ -446,13 +506,18 @@ func ensureAnonymousChatUsage(payload map[string]any, protocol wire.Protocol) bo
// ensureAnonymousTools makes the tool list read as an agent session: every // ensureAnonymousTools makes the tool list read as an agent session: every
// recognised OpenCode tool carries its genuine definition, and the missing // recognised OpenCode tool carries its genuine definition, and the missing
// core tools are appended. It reports whether the payload changed. Tools whose // core tools (legacy /zen/v1 or /inference) are appended. It reports whether
// names upstream does not recognise are left exactly as the client declared // the payload changed. Tools whose names upstream does not recognise are left
// them, so downstream function calling keeps working. // exactly as the client declared them, so downstream function calling keeps
func ensureAnonymousTools(payload map[string]any, protocol wire.Protocol) bool { // working.
func ensureAnonymousTools(payload map[string]any, protocol wire.Protocol, legacy bool) bool {
coreTools := anonymousCoreTools
if legacy {
coreTools = legacyAnonymousCoreTools
}
raw, exists := payload["tools"] raw, exists := payload["tools"]
if !exists { if !exists {
payload["tools"] = anonymousToolset(protocol, nil) payload["tools"] = anonymousToolset(protocol, coreTools)
return true return true
} }
items, ok := raw.([]any) items, ok := raw.([]any)
@@ -475,8 +540,8 @@ func ensureAnonymousTools(payload map[string]any, protocol wire.Protocol) bool {
changed = true changed = true
} }
} }
missing := make([]string, 0, len(anonymousCoreTools)) missing := make([]string, 0, len(coreTools))
for _, name := range anonymousCoreTools { for _, name := range coreTools {
if !present[name] { if !present[name] {
missing = append(missing, name) missing = append(missing, name)
} }
@@ -608,7 +673,11 @@ func (g *Gateway) shapeKeyBody(body []byte, route models.Route, tier config.Tier
if !g.catalog.IsFreeModel(route.ID) { if !g.catalog.IsFreeModel(route.ID) {
return body, false return body, false
} }
shaped := prepareAnonymousBody(body, route.ProtocolFor(tier)) baseURL := g.cfg.Upstream.Zen
if tier == config.TierGo {
baseURL = g.cfg.Upstream.Go
}
shaped := prepareAnonymousBody(body, route.ProtocolFor(tier), isLegacyZenUpstream(baseURL))
return shaped, !bytes.Equal(shaped, body) return shaped, !bytes.Equal(shaped, body)
} }
+3 -2
View File
@@ -19,8 +19,9 @@ const (
CapabilitiesURL = "https://models.opencode.ai/api.json" CapabilitiesURL = "https://models.opencode.ai/api.json"
ZenDocsURL = "https://raw.githubusercontent.com/anomalyco/opencode/dev/packages/web/src/content/docs/zen.mdx" 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" 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 // LegacyZenBase is the legacy /zen console origin (serving /zen/v1/*) that
// models listing after chat traffic moved to the inference backend. // still serves anonymous inference and the models listing alongside the newer
// /inference backend.
LegacyZenBase = "https://opencode.ai/zen" LegacyZenBase = "https://opencode.ai/zen"
) )