Files
opencode2api/internal/gateway/probe.go
T
Empty 0204ca1fdf fix: harden the free-tier gate shape and probe lanes (#81 fallout) (#84)
OpenCode's 2026-10-14 gate rejects the gateway on every lane again
(403 FreeTierError) while the official CLI keeps working. Probing
byte-identical CLI v2.0.29 replays against the live endpoint isolated
the deltas this changeset fixes on top of #83:

- identity: derive the session from the new x-opencode-session-id
  signal too, and stop forwarding the legacy x-opencode-request header
  and canonical prj_* project ids upstream — both are instant 403s.
- upstream: the x-opencode-project header keeps one conversation pinned
  to one upstream project but is now hashed into the bare 40-hex shape
  the client sends (a prj_* value 403s).
- refresh: when the configured anonymous upstream has no models route
  (404), fall back to the legacy Zen console listing so the anonymous
  catalog still populates.

The endpoint move, genuine tool definitions, and UA shape came in with
#83; the definitions embedded there were re-verified byte-for-byte
against a fresh CLI v2.0.29 capture, including the smallest passing
toolset (shell + read) and per-tool definition checks.

Validation: live end-to-end against opencode.ai — anonymous lane serves
streaming and plain JSON chat completions on big-pickle and
step-5-preview-free, tool calls pass through, all nine exposed free
models probe available, go vet/build/gofmt clean.
2026-10-15 01:43:14 +08:00

253 lines
8.4 KiB
Go

package gateway
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"opencode2api/internal/config"
"opencode2api/internal/identity"
"opencode2api/internal/jsonutil"
"opencode2api/internal/models"
wire "opencode2api/internal/protocol"
)
type probeResult struct {
success, attempted, effortRejected bool
reason, channel string
effort models.EffortProbe
}
func (g *Gateway) resolvedEffort(model string, tier config.Tier, protocol wire.Protocol) string {
effort := g.cfg.ForcedEffort(model)
if effort != "auto" {
return effort
}
// Only the free Zen lane is actively probed. Never transfer observations
// to a different protocol/tier, or guess a level for an unprobed model.
if tier != config.TierZen || protocol == wire.SystemOne || g.availability == nil || !g.catalog.IsFreeModel(model) {
return ""
}
item := g.availability.Get(model)
if !g.catalog.MetadataForTier(model, tier).Reasoning || item.AutoEffort.Effort == "none" {
return "" // Do not inject reasoning into a model that only accepted the baseline.
}
if item.Disabled || item.AutoEffort.Protocol != string(protocol) || time.Since(item.EffortCheckedAt) > 2*models.FreeModelCheckInterval {
return ""
}
return item.AutoEffort.Effort
}
func probePayload(model string, protocol wire.Protocol, effort string) ([]byte, error) {
if protocol == wire.SystemOne {
// 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{
"arithmetic": map[string]any{"type": "noul", "instructions": "Is 1 + 1 equal to 2?"},
}})
}
payload := map[string]any{"model": model, "stream": true, "max_tokens": 64, "messages": []any{map[string]any{"role": "user", "content": "Reply with OK."}}}
converted, err := wire.ConvertRequest(wire.Chat, protocol, payload)
if err != nil {
return nil, err
}
if effort != "" {
wire.ForcedEffort(protocol, converted, effort)
}
b, err := json.Marshal(converted)
if err != nil {
return nil, err
}
return prepareAnonymousBody(b, protocol), nil
}
func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult {
if !g.catalog.IsFreeModel(model) {
return probeResult{reason: "not_free"}
}
d := g.catalog.Diagnostic(model, wire.Chat, g.zenNodes.Len() > 0, false, g.cfg.Anonymous)
protocol := d.NativeProtocols[config.TierZen]
if !d.AvailableZen || !g.catalog.Supported(model) {
return probeResult{reason: "unsupported_probe"}
}
ids := identity.RequestIDs{Session: identity.CanonicalSessionID("availability:" + model), Project: "opencode2api:default-project"}
type lane struct {
key, name, baseURL string
client *http.Client
}
var lanes []lane
if g.cfg.Anonymous {
cursor := g.anonymous.CursorFor(ids.Session)
if node := cursor.Next(); node != nil {
lanes = append(lanes, lane{anonymousZenKey, "anonymous", g.cfg.Upstream.Anonymous, node.proxy.client})
}
}
cursor := g.zenNodes.CursorFor(ids.Session)
if node := cursor.Next(); node != nil {
if proxy := g.zenNodes.Proxy(node); proxy != nil {
lanes = append(lanes, lane{node.key, "zen", g.cfg.Upstream.Zen, proxy.client})
}
}
result := probeResult{reason: "no_probe_channel"}
inconclusive := ""
for _, lane := range lanes {
if ctx.Err() != nil {
return probeResult{reason: "canceled"}
}
run := func(effort string) probeResult {
return g.probeAttempt(ctx, lane.client, lane.baseURL, lane.key, model, protocol, ids, effort)
}
result = run("")
result.channel = lane.name
if result.success {
if g.cfg.ForcedEffort(model) == "auto" && protocol != wire.SystemOne {
if !g.catalog.MetadataForTier(model, config.TierZen).Reasoning {
result.effort = models.EffortProbe{Effort: "none", Protocol: string(protocol)}
} else {
for _, effort := range []string{"max", "xhigh", "high", "medium", "low", "minimal", "none"} {
if effort == "none" {
// Baseline already succeeded without an effort field.
result.effort = models.EffortProbe{Effort: "none", Protocol: string(protocol)}
break
}
trial := run(effort)
if trial.success {
result.effort = models.EffortProbe{Effort: effort, Protocol: string(protocol)}
break
}
// A rate limit or timeout gives no evidence that a lower
// reasoning level is required. Keep previous observations.
if !trial.effortRejected {
break
}
// Once higher levels were explicitly rejected, do not
// retain an older ceiling if the next trial is inconclusive.
result.effort = models.EffortProbe{Reset: true}
}
}
}
return result
}
if result.reason != "model_unavailable" {
inconclusive = result.reason
}
}
// One lane's auth/transient failure cannot establish global unavailability.
if inconclusive != "" {
result.reason = inconclusive
}
return result
}
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)
if err != nil {
return probeResult{reason: "request_conversion_error"}
}
ctx, cancel := context.WithTimeout(parent, 60*time.Second)
defer cancel()
ids.Request = identity.RandomID("req", 16)
req, err := newUpstreamRequest(ctx, baseURL, protocol, b, ids, key)
if err != nil {
return probeResult{reason: "request_creation_error"}
}
result := probeResult{attempted: true}
resp, err := client.Do(req)
if err != nil {
result.reason = "transport_error"
if ctx.Err() != nil {
result.reason = "probe_timeout"
}
return result
}
defer resp.Body.Close()
if resp.StatusCode/100 != 2 {
body, readErr := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
result.reason = fmt.Sprintf("http_%d", resp.StatusCode)
if readErr == nil {
result.effortRejected = isEffortRejection(resp.StatusCode, string(body))
if isModelUnavailable(resp.StatusCode, string(body)) {
result.reason = "model_unavailable"
}
}
return result
}
reader := io.LimitReader(resp.Body, 1<<20)
if strings.Contains(strings.ToLower(resp.Header.Get("Content-Type")), "text/event-stream") && protocol != wire.SystemOne {
_, err = wire.CollapseStream(reader, protocol, model)
} else {
var document map[string]any
err = json.NewDecoder(reader).Decode(&document)
if err == nil && (document == nil || document["error"] != nil) {
err = fmt.Errorf("upstream error envelope: %v", document["error"])
}
if err == nil {
switch protocol {
case wire.SystemOne:
answer := jsonutil.MapAt(document, "answers", "arithmetic")
probability, ok := answer["noul"].(float64)
if !ok || probability < 0 || probability > 1 || answer["type"] != "noul" {
err = fmt.Errorf("invalid System One answer")
}
default:
field := "choices"
if protocol == wire.Anthropic {
field = "content"
} else if protocol == wire.Responses {
field = "output"
}
if _, ok := document[field].([]any); !ok {
err = fmt.Errorf("invalid response schema")
}
}
}
}
result.success = err == nil && ctx.Err() == nil
result.reason = "probe_succeeded"
if !result.success {
result.reason = "invalid_or_incomplete_response"
if err != nil {
result.effortRejected = isEffortRejection(400, err.Error())
if isModelUnavailable(400, err.Error()) {
result.reason = "model_unavailable"
}
}
if ctx.Err() != nil {
result.reason = "probe_timeout"
}
}
return result
}
func isModelUnavailable(status int, body string) bool {
if status != 400 && status != 404 && status != 410 && status != 422 {
return false
}
text := strings.ToLower(body)
for _, marker := range []string{"model_not_found", "model_not_available", "model_retired", "model_deprecated", "unknown model", "model does not exist", "model has been retired", "model is no longer available"} {
if strings.Contains(text, marker) {
return true
}
}
return false
}
func isEffortRejection(status int, body string) bool {
if status != 400 && status != 422 {
return false
}
text := strings.ToLower(body)
if !strings.Contains(text, "effort") && !strings.Contains(text, "thinking") && !strings.Contains(text, "reasoning") {
return false
}
for _, marker := range []string{"invalid", "unsupported", "not support", "not allowed", "must be", "allowed values"} {
if strings.Contains(text, marker) {
return true
}
}
return false
}