From 81ad2842c7869594bf338a64a0fe0c6f86811b30 Mon Sep 17 00:00:00 2001 From: Jason Xu Date: Mon, 19 Oct 2026 03:46:09 +0800 Subject: [PATCH] refactor: drop new prefixes, unify v1/v2 lane naming, audit comments - Remove the new/New prefix from constructors; rename the colliding types semantically (ModelCatalog, RuntimeController, Metrics, LogBroker, Redactor, proxyTransports, upstreamNodes, ...). - Unify upstream lane naming on v1 (/zen, OpenCode 1.x shape) and v2 (/inference and /zen/go, 2.x CLI shape); add models.IsV1Upstream and drop the duplicated lane detection. - Fix inaccurate, truncated and stale comments across all packages and document exported symbols plus non-obvious internals. - Fix anthropicThinking passing "enabled"/"adaptive" through as an effort; derive the level from the budget instead. - Delete dead code (identity.StableID, unused protocol decoders and stream parser wrappers). - Export EffectiveListeners, rename modelsDev* metadata constants, and describe the metadata source as the OpenCode endpoint. - Rename the forced-collapse log event to stream_collapse_failed and add an anonymous field. - Correct the README upstream.zen default and add upstream.anonymous. --- README.md | 3 +- README.vi.md | 3 +- README.zh-CN.md | 3 +- cmd/opencode2api/main.go | 14 +- internal/admin/api_keys.go | 18 +- internal/admin/auth.go | 46 ++ internal/admin/availability.go | 8 + internal/admin/debug.go | 49 ++- internal/admin/model_quotas.go | 44 +- internal/admin/rotation.go | 10 + internal/admin/server.go | 66 ++- internal/buildinfo/version.go | 4 +- internal/config/config.go | 111 +++-- internal/config/json.go | 8 +- internal/config/password.go | 9 + internal/config/persistence.go | 17 +- internal/config/proxy.go | 21 +- internal/config/proxy_test.go | 95 ----- internal/config/rotation.go | 22 + internal/config/secrets.go | 40 +- internal/config/server_keys.go | 10 +- internal/config/tier.go | 9 +- internal/gateway/availability.go | 22 +- internal/gateway/first_event.go | 58 ++- internal/gateway/gateway.go | 109 +++-- internal/gateway/health.go | 7 + internal/gateway/pool.go | 183 +++++--- internal/gateway/probe.go | 48 ++- internal/gateway/refresh.go | 58 ++- internal/gateway/rotation.go | 45 +- internal/gateway/runtime.go | 137 ++++-- internal/gateway/upstream.go | 600 +++++++++++++++++++-------- internal/httpx/body.go | 4 + internal/httpx/client.go | 63 ++- internal/httpx/response.go | 10 + internal/identity/message.go | 190 +++++++++ internal/identity/request.go | 31 +- internal/jsonutil/decode.go | 4 + internal/jsonutil/value.go | 30 ++ internal/models/availability.go | 57 ++- internal/models/cache.go | 25 +- internal/models/catalog.go | 192 ++++++--- internal/models/discovery.go | 72 +++- internal/models/pricing.go | 122 ++++-- internal/protocol/bridge.go | 186 ++++++--- internal/protocol/collapse.go | 22 +- internal/protocol/content.go | 67 ++- internal/protocol/errors.go | 5 + internal/protocol/protocol.go | 26 +- internal/protocol/request.go | 167 ++++++-- internal/protocol/response.go | 70 +++- internal/protocol/rotation_stream.go | 48 ++- internal/protocol/stream.go | 127 +++++- internal/protocol/stream_emitter.go | 116 +++++- internal/protocol/stream_parser.go | 51 ++- internal/protocol/tool_images.go | 22 +- internal/rotation/state.go | 76 +++- internal/telemetry/http.go | 19 +- internal/telemetry/logging.go | 59 ++- internal/telemetry/metrics.go | 142 +++++-- internal/telemetry/recovery.go | 2 + webui/index.html | 2 +- webui/js/i18n.js | 4 +- 63 files changed, 2988 insertions(+), 900 deletions(-) delete mode 100644 internal/config/proxy_test.go create mode 100644 internal/identity/message.go diff --git a/README.md b/README.md index 21387d0..f37174b 100644 --- a/README.md +++ b/README.md @@ -260,8 +260,9 @@ 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/inference/openai`. | +| `upstream.zen` | `https://opencode.ai/zen`. | | `upstream.go` | `https://opencode.ai/zen/go`. | +| `upstream.anonymous` | `https://opencode.ai/inference`; the anonymous lane's fallback after `/zen`. | | `proxies` | Falls back to `["direct"]` when both proxy sources are empty. | | `proxyfile` | Optional; relative paths resolve beside the configuration file. | | `models.refresh_seconds` | `300`; minimum 1. | diff --git a/README.vi.md b/README.vi.md index 5d26d72..468d7df 100644 --- a/README.vi.md +++ b/README.vi.md @@ -264,8 +264,9 @@ Xem [config.example.json](config.example.json) để có một cấu hình khở | `zen_keys`, `go_keys` | Cần ít nhất một key upstream trừ khi bật truy cập ẩn danh. | | `anonymous` | `false`. | | `prefer` | `go`; nhận `go` hoặc `zen`. | -| `upstream.zen` | `https://opencode.ai/inference/openai`. | +| `upstream.zen` | `https://opencode.ai/zen`. | | `upstream.go` | `https://opencode.ai/zen/go`. | +| `upstream.anonymous` | `https://opencode.ai/inference`; upstream dự phòng của kênh ẩn danh sau `/zen`. | | `proxies` | Rơi về `["direct"]` khi cả hai nguồn proxy đều rỗng. | | `proxyfile` | Không bắt buộc; đường dẫn tương đối được phân giải cạnh file cấu hình. | | `models.refresh_seconds` | `300`; tối thiểu 1. | diff --git a/README.zh-CN.md b/README.zh-CN.md index fc6f9b9..ca3c3eb 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -260,8 +260,9 @@ Key 初始化时均衡分配到代理。真实流量可以触发代理检查、K | `zen_keys`、`go_keys` | 未启用匿名模式时,至少需要一个上游 Key。 | | `anonymous` | `false`。 | | `prefer` | `go`;可选 `go`、`zen`。 | -| `upstream.zen` | `https://opencode.ai/inference/openai`。 | +| `upstream.zen` | `https://opencode.ai/zen`。 | | `upstream.go` | `https://opencode.ai/zen/go`。 | +| `upstream.anonymous` | `https://opencode.ai/inference`;匿名通道在 `/zen` 之后的回退上游。 | | `proxies` | 两个代理来源都为空时,使用 `["direct"]`。 | | `proxyfile` | 可选;相对路径基于配置文件所在目录解析。 | | `models.refresh_seconds` | `300`;最小为 1。 | diff --git a/cmd/opencode2api/main.go b/cmd/opencode2api/main.go index 0938863..9a5e0aa 100644 --- a/cmd/opencode2api/main.go +++ b/cmd/opencode2api/main.go @@ -21,6 +21,8 @@ import ( // version remains the linker injection point used by release builds. var version = "dev" +// main loads the configuration, starts the gateway runtime and the API and +// WebUI servers, and shuts them down on SIGINT or SIGTERM. func main() { buildinfo.Version = version configPath := flag.String("config", "config.json", "path to config.json") @@ -44,12 +46,12 @@ func main() { defer cancel() level := new(slog.LevelVar) telemetry.SetLogLevel(level, cfg.Logging.Level) - hub := telemetry.NewLogHub(cfg.Logging.RingSize) - redactor := config.NewSecretRedactor() + hub := telemetry.LogHub(cfg.Logging.RingSize) + redactor := config.SecretRedactor() redactor.Replace(cfg) - logger := telemetry.NewStructuredLogger(level, hub, redactor) - monitor := telemetry.NewMonitor() - manager, err := gateway.NewRuntimeManager(ctx, *configPath, cfg, logger, monitor, hub, redactor, level) + logger := telemetry.StructuredLogger(level, hub, redactor) + monitor := telemetry.Monitor() + manager, err := gateway.RuntimeManager(ctx, *configPath, cfg, logger, monitor, hub, redactor, level) if err != nil { logger.Error("failed to initialize runtime", "component", "runtime", "event", "runtime_initialization_failed", "error", err) os.Exit(1) @@ -81,6 +83,8 @@ func main() { } } +// serveHTTP serves server until it is shut down. An unexpected stop is logged +// and cancels the root context, which begins the shutdown of every server. func serveHTTP(cancel context.CancelFunc, logger *slog.Logger, server *http.Server, component string) { logger.Info("server listening", "component", component, "event", "server_started", "address", server.Addr, "version", buildinfo.Version) if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { diff --git a/internal/admin/api_keys.go b/internal/admin/api_keys.go index 30cb49f..670a67d 100644 --- a/internal/admin/api_keys.go +++ b/internal/admin/api_keys.go @@ -14,6 +14,9 @@ import ( "opencode2api/internal/telemetry" ) +// APIKeyView is a server key as the API keys page lists it: its Fingerprint +// ID, its name (a numbered placeholder when none is stored), the masked value, +// whether it is enabled, and its usage. type APIKeyView struct { ID string `json:"id"` Name string `json:"name"` @@ -23,8 +26,9 @@ type APIKeyView struct { Usage APIKeyUsage `json:"usage"` } -// APIKeyUsage is in-memory like the rest of the monitor: it restarts from zero -// with the process and survives hot reloads. +// APIKeyUsage is in-memory like the rest of telemetry.Metrics: it restarts +// from zero with the process and survives hot reloads. Window covers the last +// hour. type APIKeyUsage struct { Lifetime telemetry.ServerKeyUsage `json:"lifetime"` Window telemetry.ServerKeyUsage `json:"last_hour"` @@ -58,6 +62,7 @@ func (a *Server) handleListAPIKeys(w http.ResponseWriter, _ *http.Request) { httpx.WriteJSON(w, http.StatusOK, map[string]any{"keys": a.apiKeyViews(a.manager.Config())}) } +// validateKeyName requires a name of 1-80 characters. func validateKeyName(name string) error { if name == "" || len([]rune(name)) > 80 { return errors.New("名称需为 1–80 个字符") @@ -65,6 +70,9 @@ func validateKeyName(name string) error { return nil } +// addAPIKey appends key as a new server key named name. The name must have +// 1-80 characters and the key 16-256 characters from [A-Za-z0-9._-]; at most +// 200 keys are allowed, and a key whose fingerprint already exists is refused. func addAPIKey(cfg *config.Config, name, key string) error { if err := validateKeyName(name); err != nil { return err @@ -94,6 +102,9 @@ func addAPIKey(cfg *config.Config, name, key string) error { return nil } +// handleCreateAPIKey adds a server key, generating "sk-local-" plus 48 hex +// digits when the request carries no value, and answers with the plaintext +// key next to the updated, masked list. func (a *Server) handleCreateAPIKey(w http.ResponseWriter, r *http.Request) { var input struct { Name string `json:"name"` @@ -121,6 +132,9 @@ func (a *Server) handleCreateAPIKey(w http.ResponseWriter, r *http.Request) { httpx.WriteJSON(w, 201, map[string]any{"key": key, "keys": a.apiKeyViews(a.manager.Config())}) } +// changeAPIKey renames, enables or disables, or (with remove) deletes the +// server key whose fingerprint is id. A change that would leave no enabled +// key is refused. func changeAPIKey(cfg *config.Config, id string, name *string, enabled *bool, remove bool) error { index := -1 for i, key := range cfg.ServerKeys { diff --git a/internal/admin/auth.go b/internal/admin/auth.go index cf21b2b..c60163a 100644 --- a/internal/admin/auth.go +++ b/internal/admin/auth.go @@ -19,6 +19,10 @@ import ( const adminCookieName = "opencode2api_session" +// adminSession is a logged-in WebUI session. The map key is the SHA-256 digest +// of the cookie token, so the raw token is never stored. AuthVersion is the +// fingerprint of the password hash the session was created with: changing the +// username or password invalidates every session. type adminSession struct { Username string AuthVersion string @@ -26,11 +30,17 @@ type adminSession struct { Expires time.Time } +// loginWindow is a fixed-window counter for one client: Started is when the +// window opened and Count the events in it. Login failures use a five-minute +// window, Playground requests a one-minute one. type loginWindow struct { Started time.Time Count int } +// handleLogin checks the credentials against the configured username and +// password hash, creates a session and its CSRF token, and sets the session +// cookie. A successful login clears that client's failure window. func (a *Server) handleLogin(w http.ResponseWriter, r *http.Request) { client := clientIP(r) if !a.allowLogin(client) { @@ -79,12 +89,16 @@ func (a *Server) handleLogin(w http.ResponseWriter, r *http.Request) { httpx.WriteJSON(w, http.StatusOK, map[string]any{"username": cfg.WebUI.Username, "csrf_token": csrf, "expires_at": expires.UTC()}) } +// handleSession reports the current session's username, CSRF token and +// expiry; it runs behind authenticate, so the session already exists. func (a *Server) handleSession(w http.ResponseWriter, r *http.Request) { session, _ := sessionFromContext(r) w.Header().Set("Cache-Control", "no-store") httpx.WriteJSON(w, http.StatusOK, map[string]any{"authenticated": true, "username": session.Username, "csrf_token": session.CSRF, "expires_at": session.Expires.UTC()}) } +// handleLogout deletes the session and expires the cookie; it answers 204 even +// when the request carried no cookie. func (a *Server) handleLogout(w http.ResponseWriter, r *http.Request) { cookie, _ := r.Cookie(adminCookieName) if cookie != nil { @@ -98,6 +112,9 @@ func (a *Server) handleLogout(w http.ResponseWriter, r *http.Request) { type sessionContextKey struct{} +// authenticate rejects a request without a live session cookie and otherwise +// stores the session in the request context. A session dies with its expiry, +// and also as soon as the configured username or password hash changes. func (a *Server) authenticate(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { cookie, err := r.Cookie(adminCookieName) @@ -127,11 +144,16 @@ func (a *Server) authenticate(next http.Handler) http.Handler { }) } +// sessionFromContext returns the session authenticate stored, if any. func sessionFromContext(r *http.Request) (adminSession, bool) { session, ok := r.Context().Value(sessionContextKey{}).(adminSession) return session, ok } +// csrf rejects a state-changing request whose X-CSRF-Token header does not +// match the session's token. A request that carries an Origin header must also +// have been sent by this server: same host and the scheme the request arrived +// on. func (a *Server) csrf(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { session, ok := sessionFromContext(r) @@ -154,6 +176,9 @@ func (a *Server) csrf(next http.Handler) http.Handler { }) } +// handleAccount changes the WebUI username and/or password after verifying the +// current password, then drops every session (including this one) and clears +// the cookie, so the operator has to log in again. func (a *Server) handleAccount(w http.ResponseWriter, r *http.Request) { var input struct { CurrentPassword string `json:"current_password"` @@ -187,6 +212,10 @@ func (a *Server) handleAccount(w http.ResponseWriter, r *http.Request) { httpx.WriteJSON(w, http.StatusOK, map[string]any{"updated": true, "reauthenticate": true}) } +// allowLogin reports whether client may try to log in: at most five failures +// per five-minute window. Once more than 1024 clients are tracked it also +// drops windows older than five minutes, and it refuses a new client outright +// when 4096 are tracked, so the map cannot grow without bound. func (a *Server) allowLogin(client string) bool { a.mu.Lock() defer a.mu.Unlock() @@ -208,6 +237,8 @@ func (a *Server) allowLogin(client string) bool { return window.Count < 5 } +// recordLoginFailure adds one failure for client, starting a new window when +// the previous one is older than five minutes. func (a *Server) recordLoginFailure(client string) { a.mu.Lock() defer a.mu.Unlock() @@ -220,6 +251,7 @@ func (a *Server) recordLoginFailure(client string) { a.attempts[client] = window } +// cleanupSessionsLocked deletes the expired sessions; a.mu must be held. func (a *Server) cleanupSessionsLocked(now time.Time) { for token, session := range a.sessions { if now.After(session.Expires) { @@ -228,6 +260,8 @@ func (a *Server) cleanupSessionsLocked(now time.Time) { } } +// removeEarliestSessionLocked deletes the session that expires first, making +// room when the session map is full; a.mu must be held. func (a *Server) removeEarliestSessionLocked() { var earliestToken string var earliest time.Time @@ -241,6 +275,8 @@ func (a *Server) removeEarliestSessionLocked() { } } +// randomToken returns length random bytes as unpadded base64url, safe for a +// cookie value and a header. func randomToken(length int) (string, error) { data := make([]byte, length) if _, err := rand.Read(data); err != nil { @@ -249,11 +285,18 @@ func randomToken(length int) (string, error) { return base64.RawURLEncoding.EncodeToString(data), nil } +// tokenDigest returns the hex SHA-256 of a session token, which is what the +// session map is keyed by. func tokenDigest(token string) string { sum := sha256.Sum256([]byte(token)) return hex.EncodeToString(sum[:]) } +// clientIP returns the IP address of the direct peer, without the port. It +// deliberately ignores X-Forwarded-For: the header is client-controlled, so +// trusting it would let anyone escape the login and Playground rate limits by +// rotating a value. Behind a reverse proxy every client therefore shares the +// proxy's address. func clientIP(r *http.Request) string { host, _, err := net.SplitHostPort(r.RemoteAddr) if err == nil { @@ -262,6 +305,9 @@ func clientIP(r *http.Request) string { return r.RemoteAddr } +// requestIsSecure reports whether the browser reached the server over TLS, +// directly or, for the cookie's Secure flag and the CSRF origin check, through +// a proxy that sets X-Forwarded-Proto to https. func requestIsSecure(r *http.Request) bool { if r == nil { return false diff --git a/internal/admin/availability.go b/internal/admin/availability.go index 6b9a3fd..ac420cc 100644 --- a/internal/admin/availability.go +++ b/internal/admin/availability.go @@ -5,11 +5,16 @@ import ( "opencode2api/internal/httpx" ) +// handleAvailability lists the free models with their probe state, so the +// availability page can show which ones are disabled and why. func (a *Server) handleAvailability(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-store") httpx.WriteJSON(w, http.StatusOK, map[string]any{"models": a.manager.AvailabilitySnapshot()}) } +// handleRestoreModel returns a disabled free model to manual control, which +// re-enables it and keeps automatic probes from disabling it again. It answers +// with the refreshed availability list. func (a *Server) handleRestoreModel(w http.ResponseWriter, r *http.Request) { var input struct { Model string `json:"model"` @@ -25,6 +30,9 @@ func (a *Server) handleRestoreModel(w http.ResponseWriter, r *http.Request) { a.handleAvailability(w, r) } +// handleManualModel switches a free model between manual and automatic +// control: a manual model stays enabled and is not probed, while switching +// back to automatic schedules a probe. It answers with the refreshed list. func (a *Server) handleManualModel(w http.ResponseWriter, r *http.Request) { var input struct { Model string `json:"model"` diff --git a/internal/admin/debug.go b/internal/admin/debug.go index 62a1cc5..aca5523 100644 --- a/internal/admin/debug.go +++ b/internal/admin/debug.go @@ -17,19 +17,29 @@ import ( ) // DebugKeySelection tells the Playground whether to use normal routing or to -// exercise one explicitly chosen upstream key. +// exercise one explicitly chosen upstream key. Mode is "auto" (empty means +// auto) or "selected"; in selected mode, Tier and ID pick one of the keys that +// DebugKeys lists. type DebugKeySelection struct { Mode string `json:"mode,omitempty"` Tier config.Tier `json:"tier,omitempty"` ID string `json:"id,omitempty"` } +// DebugInferenceRequest is one Playground request: the protocol it is +// expressed in, which upstream key to test (Mode "auto" or "selected", the +// latter naming Tier and ID), and the request body itself. type DebugInferenceRequest struct { Protocol protocol.Protocol `json:"protocol"` Key DebugKeySelection `json:"key,omitempty"` Request map[string]any `json:"request"` } +// DebugInferenceResult is the outcome of a Playground request: the status and +// duration of the gateway's answer, the route it took (filled from the request +// trace when one was recorded), the key that was tested and a verdict about +// it, and the response body (or the raw text when it was not JSON), redacted +// and with credential-bearing fields masked. type DebugInferenceResult struct { OK bool `json:"ok"` HTTPStatus int `json:"http_status"` @@ -41,6 +51,9 @@ type DebugInferenceResult struct { Response any `json:"response"` } +// handleDebugModels lists the routes, the per-key targets, the catalog and the +// result of the last Playground request, so the page can render before the +// first test runs. func (a *Server) handleDebugModels(w http.ResponseWriter, _ *http.Request) { models, metadata := a.manager.DebugModels() catalog := a.manager.Resources().Models @@ -52,6 +65,12 @@ func (a *Server) handleDebugModels(w http.ResponseWriter, _ *http.Request) { httpx.WriteJSON(w, http.StatusOK, map[string]any{"models": models, "keys": keys, "metadata": metadata, "catalog": catalog, "last_inference": last}) } +// handleDebugInference runs a request through the gateway itself, in process +// and always non-streaming, and reports what happened. Auto mode follows +// normal routing; selected mode pins one upstream key and disables failover, +// so the verdict describes that key alone. The request is authenticated with +// the first enabled server key, which the gateway accounts to the Playground +// bucket, and the result is kept for handleDebugModels. func (a *Server) handleDebugInference(w http.ResponseWriter, r *http.Request) { if !a.allowDebug(clientIP(r)) { writeAdminError(w, http.StatusTooManyRequests, "debug_rate_limited", "too many Playground requests; retry in one minute") @@ -125,7 +144,7 @@ func (a *Server) handleDebugInference(w http.ResponseWriter, r *http.Request) { } request.Header.Set("Content-Type", "application/json") request.Header.Set("Accept", "application/json") - recorder := newDebugResponseRecorder() + recorder := debugResponseRecorder() started := time.Now() a.manager.Handler().ServeHTTP(recorder, request) duration := time.Since(started) @@ -162,29 +181,38 @@ func (a *Server) handleDebugInference(w http.ResponseWriter, r *http.Request) { httpx.WriteJSON(w, http.StatusOK, result) } -type debugResponseRecorder struct { +// debugResponseCapture is a minimal http.ResponseWriter that keeps the status +// and body of the gateway's answer instead of sending them. +type debugResponseCapture struct { header http.Header body bytes.Buffer status int } -func newDebugResponseRecorder() *debugResponseRecorder { - return &debugResponseRecorder{header: make(http.Header), status: http.StatusOK} +// debugResponseRecorder returns a response writer that captures the gateway's +// answer for inspection. It starts at 200 and keeps the first status other +// than 200 that is written, so an explicit WriteHeader(200) after an error +// does not hide the error. +func debugResponseRecorder() *debugResponseCapture { + return &debugResponseCapture{header: make(http.Header), status: http.StatusOK} } -func (recorder *debugResponseRecorder) Header() http.Header { return recorder.header } +func (recorder *debugResponseCapture) Header() http.Header { return recorder.header } -func (recorder *debugResponseRecorder) WriteHeader(status int) { +func (recorder *debugResponseCapture) WriteHeader(status int) { if recorder.status != http.StatusOK || status == http.StatusOK { return } recorder.status = status } -func (recorder *debugResponseRecorder) Write(data []byte) (int, error) { +func (recorder *debugResponseCapture) Write(data []byte) (int, error) { return recorder.body.Write(data) } +// sanitizeDebugValue walks a decoded JSON value, replacing the values of keys +// that name a credential (see sensitiveDebugKey) and running every string +// through redact. Maps and slices are copied; other values are returned as is. func sanitizeDebugValue(value any, redact func(string) string) any { switch current := value.(type) { case map[string]any: @@ -211,6 +239,9 @@ func sanitizeDebugValue(value any, redact func(string) string) any { } } +// allowDebug rate-limits Playground requests to 12 per client per minute and +// counts the request as it is allowed. When more than 4096 clients are +// tracked, windows older than a minute are dropped. func (a *Server) allowDebug(client string) bool { a.mu.Lock() defer a.mu.Unlock() @@ -257,6 +288,8 @@ func classifyKeyTest(status int, attemptOutcome string) string { } } +// sensitiveDebugKey reports whether a lowercased JSON key names a credential +// that must not be shown in the Playground. func sensitiveDebugKey(key string) bool { for _, hint := range []string{ "authorization", "cookie", "password", "secret", "api_key", "api-key", "x-api-key", diff --git a/internal/admin/model_quotas.go b/internal/admin/model_quotas.go index d1842ed..dda122e 100644 --- a/internal/admin/model_quotas.go +++ b/internal/admin/model_quotas.go @@ -13,8 +13,12 @@ import ( "opencode2api/internal/config" "opencode2api/internal/httpx" + "opencode2api/internal/identity" ) +// quotaWindow is one subscription-wide quota window as the Go plan reports it: +// its status ("ok" or "rate-limited"), the used percentage the upstream gave +// (it rounds), the complement the WebUI shows, and when the window resets. type quotaWindow struct { Status string `json:"status"` UsedPercent float64 `json:"used_percent"` @@ -22,6 +26,9 @@ type quotaWindow struct { ResetsAt time.Time `json:"resets_at"` } +// quotaAccount is one Go key's quota state. ID is the key fingerprint and +// Display its masked value; FetchedAt is when the windows were last read +// successfully, so a later failure reports "stale" rather than "unavailable". type quotaAccount struct { ID string `json:"id"` Display string `json:"display"` @@ -32,11 +39,19 @@ type quotaAccount struct { Windows map[string]quotaWindow `json:"windows,omitempty"` } +// quotaCacheEntry is a cached quotaAccount and the time it expires; a success +// is kept for a minute, a failure for 15 seconds. type quotaCacheEntry struct { Account quotaAccount Expires time.Time } +// decodeQuota reads the Go plan's /v1/usage answer. All three windows +// (rolling, weekly and monthly) must be present and valid: a percentage from +// 0 to 100, a non-zero resetsAt, and a status of "ok" or "rate-limited". +// Anything else is reported as an incomplete answer rather than a partial +// quota. +// // The first-party endpoint returns subscription-wide percentages, not balances // for individual models. Never infer model dollars or sum keys' shared quotas. // Reference: anomalyco/opencode packages/console/app/src/routes/zen/go/v1/usage.ts @@ -62,15 +77,23 @@ func decodeQuota(reader io.Reader) (map[string]quotaWindow, error) { return result, nil } +// fetchQuota reads endpoint once with the Go key and parses it with +// decodeQuota. The statuses the operator can act on (invalid key, key not +// allowed, rate limited) get their own messages. Redirects are not followed. func fetchQuota(ctx context.Context, endpoint, key string) (map[string]quotaWindow, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) if err != nil { return nil, errors.New("额度查询地址无效") } + // The Go lane is a v2 lane: report the v2 CLI identity and a canonical + // session pinned to the key instead of anything naming the gateway. + session := identity.CanonicalSessionID("quota\x00" + config.Fingerprint(key)) req.Header.Set("Authorization", "Bearer "+key) - req.Header.Set("User-Agent", "opencode2api-admin/1.0") + req.Header.Set("User-Agent", httpx.V2UserAgent()) req.Header.Set("Accept", "application/json") - req.Header.Set("x-opencode-session", "opencode2api-quota-"+config.Fingerprint(key)) + req.Header.Set("x-opencode-client", "cli") + req.Header.Set("x-opencode-session", session) + req.Header.Set("x-opencode-session-id", session) client := &http.Client{Timeout: 12 * time.Second, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }} resp, err := client.Do(req) if err != nil { @@ -92,6 +115,9 @@ func fetchQuota(ctx context.Context, endpoint, key string) (map[string]quotaWind return decodeQuota(resp.Body) } +// refreshQuota builds the account entry for key, keeping the windows of the +// previous entry when the query fails so the WebUI can still show them as +// stale. func refreshQuota(ctx context.Context, endpoint, key string, previous quotaCacheEntry) quotaCacheEntry { now := time.Now().UTC() account := previous.Account @@ -110,13 +136,19 @@ func refreshQuota(ctx context.Context, endpoint, key string, previous quotaCache return quotaCacheEntry{Account: account, Expires: now.Add(60 * time.Second)} } +// handleModelQuotas reports the shared Go plan quota per Go key and the models +// the plan can serve. The upstream is queried per key, at most four at a time, +// and a key's answer is cached for a minute (15 seconds after a failure), so +// several open tabs share one round of queries. The cache is rebuilt from the +// keys configured for this request, so entries of removed or changed keys do +// not survive. func (a *Server) handleModelQuotas(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-store") cfg := a.manager.Config() endpoint := strings.TrimRight(cfg.Upstream.Go, "/") + "/v1/usage" accounts := make([]quotaAccount, len(cfg.GoKeys)) // Coalesce refreshes from multiple browser tabs; at most four upstream - // queries run at a time. The cache is pruned when upstream credentials change. + // queries run at a time. a.quotaMu.Lock() if a.quotaCache == nil { a.quotaCache = map[string]quotaCacheEntry{} @@ -144,12 +176,12 @@ func (a *Server) handleModelQuotas(w http.ResponseWriter, r *http.Request) { }(i, key, previous) } wg.Wait() - newCache := map[string]quotaCacheEntry{} + cache := map[string]quotaCacheEntry{} for i, key := range cfg.GoKeys { - newCache[endpoint+"|"+config.Fingerprint(key)] = entries[i] + cache[endpoint+"|"+config.Fingerprint(key)] = entries[i] accounts[i] = entries[i].Account } - a.quotaCache = newCache + a.quotaCache = cache a.quotaMu.Unlock() all, _ := a.manager.DebugModels() type modelView struct { diff --git a/internal/admin/rotation.go b/internal/admin/rotation.go index 5cba909..cd313fd 100644 --- a/internal/admin/rotation.go +++ b/internal/admin/rotation.go @@ -8,10 +8,17 @@ import ( "slices" ) +// handleRotation reports the rotation state: both groups with their alias, +// order, current model, pause map and recent switches, plus the recent +// attempts and the first-output timeout. func (a *Server) handleRotation(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-store") httpx.WriteJSON(w, 200, a.manager.RotationSnapshot()) } + +// handleSaveRotation stores new aliases and orders. Each order must be a +// permutation of the group's current order, so a list the WebUI rendered +// before a catalog refresh is rejected instead of dropping models. func (a *Server) handleSaveRotation(w http.ResponseWriter, r *http.Request) { var input config.RotationConfig if err := decodeAdminJSON(w, r, &input); err != nil { @@ -46,6 +53,9 @@ func (a *Server) handleSaveRotation(w http.ResponseWriter, r *http.Request) { } a.handleRotation(w, r) } + +// handleSelectRotation switches a group to another of its models manually, +// clearing that model's pause. func (a *Server) handleSelectRotation(w http.ResponseWriter, r *http.Request) { var input struct { Group string `json:"group"` diff --git a/internal/admin/server.go b/internal/admin/server.go index 88bcb3e..c963d6a 100644 --- a/internal/admin/server.go +++ b/internal/admin/server.go @@ -22,10 +22,13 @@ import ( "opencode2api/webui" ) +// Server serves the management API and the embedded WebUI. All mutable state +// here is guarded by mu; quotaCache has its own quotaMu because a quota +// refresh holds it across network calls. type Server struct { - manager *gateway.RuntimeManager - monitor *telemetry.Monitor - logs *telemetry.LogHub + manager *gateway.RuntimeController + monitor *telemetry.Metrics + logs *telemetry.LogBroker logger *slog.Logger mu sync.Mutex sessions map[string]adminSession @@ -36,13 +39,19 @@ type Server struct { quotaCache map[string]quotaCacheEntry } -func New(manager *gateway.RuntimeManager, monitor *telemetry.Monitor, logs *telemetry.LogHub, logger *slog.Logger) *Server { +// New returns a Server for manager, reporting to monitor and logs. +func New(manager *gateway.RuntimeController, monitor *telemetry.Metrics, logs *telemetry.LogBroker, logger *slog.Logger) *Server { return &Server{ manager: manager, monitor: monitor, logs: logs, logger: logger, sessions: make(map[string]adminSession), attempts: make(map[string]loginWindow), debugAttempts: make(map[string]loginWindow), } } +// Handler returns the management routes: the API under /api/ and the embedded +// WebUI for anything else. Every API route except login requires a session, +// and every mutating one also requires a CSRF token. Unknown /api/ paths +// answer 404 as JSON, and a path that is not an embedded asset falls back to +// index.html so the single-page app can route it. func (a *Server) Handler() http.Handler { mux := http.NewServeMux() mux.HandleFunc("POST /api/auth/login", a.handleLogin) @@ -73,6 +82,8 @@ func (a *Server) Handler() http.Handler { return a.securityHeaders(telemetry.Recover(a.logger, mux)) } +// staticHandler serves the embedded WebUI assets, with the index fallback +// described on Handler. func (a *Server) staticHandler() http.Handler { assets := webui.Assets files := http.FileServer(http.FS(assets)) @@ -90,6 +101,9 @@ func (a *Server) staticHandler() http.Handler { }) } +// securityHeaders sets the CSP and the other hardening headers the WebUI +// relies on: no inline or third-party scripts or styles, no referrer, no +// framing and no embedding. func (a *Server) securityHeaders(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self'; script-src 'self'; connect-src 'self'; img-src 'self' data:") @@ -102,11 +116,17 @@ func (a *Server) securityHeaders(next http.Handler) http.Handler { }) } +// SecretView is a configured secret as the config page shows it: the +// fingerprint to send back when the value is unchanged, and the masked display +// text. type SecretView struct { ID string `json:"id"` Display string `json:"display"` } +// ConfigView is the configuration as GET /api/config returns it: every secret +// masked, plus the listeners that are actually in effect and the fields whose +// change needs a restart. type ConfigView struct { Listen string `json:"listen"` ServerKeys []SecretView `json:"server_keys"` @@ -127,12 +147,16 @@ type ConfigView struct { Restart []string `json:"restart_required_fields,omitempty"` } +// EffectiveView is the set of listeners the running process actually bound, +// which may differ from the configured ones until a restart. type EffectiveView struct { Listen string `json:"listen"` WebUIListen string `json:"webui_listen"` WebUIEnabled bool `json:"webui_enabled"` } +// WebUIView is the writable part of the WebUI configuration; the password and +// its hash are never exposed. type WebUIView struct { Enabled bool `json:"enabled"` Listen string `json:"listen"` @@ -140,11 +164,16 @@ type WebUIView struct { SessionTTLMinutes int `json:"session_ttl_minutes"` } +// SecretInput is one secret in a configuration update: a new Value, or the ID +// of an existing secret to keep unchanged. type SecretInput struct { ID string `json:"id,omitempty"` Value string `json:"value,omitempty"` } +// ConfigUpdate is the body of PUT /api/config. Secrets carry either a new +// value or the ID of the existing one. The WebUI username and password are +// not changed here; they go through /api/account. type ConfigUpdate struct { Listen string `json:"listen"` ServerKeys []SecretInput `json:"server_keys"` @@ -165,11 +194,16 @@ type ConfigUpdate struct { WebUI WebUIView `json:"webui"` } +// handleGetConfig answers with the current configuration, secrets masked. func (a *Server) handleGetConfig(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Cache-Control", "no-store") httpx.WriteJSON(w, http.StatusOK, a.configView()) } +// handlePutConfig resolves the submitted secrets against the current ones, +// keeps what the update omits (rotation, server key metadata, the WebUI +// username and password hash, and reasoning when the field is absent), and +// hands the result to the runtime, which validates, applies and persists it. func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) { var update ConfigUpdate if err := decodeAdminJSON(w, r, &update); err != nil { @@ -218,6 +252,8 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) { httpx.WriteJSON(w, http.StatusOK, map[string]any{"result": result, "config": a.configView()}) } +// handleReload re-reads config.json and applies it, so an edit made on disk +// takes effect without a restart. func (a *Server) handleReload(w http.ResponseWriter, _ *http.Request) { result, err := a.manager.Reload() if err != nil { @@ -227,6 +263,8 @@ func (a *Server) handleReload(w http.ResponseWriter, _ *http.Request) { httpx.WriteJSON(w, http.StatusOK, result) } +// handleReveal returns the plaintext server, Zen, Go and proxy secrets after +// verifying the current WebUI password, and logs that it happened. func (a *Server) handleReveal(w http.ResponseWriter, r *http.Request) { var input struct { Password string `json:"password"` @@ -245,6 +283,8 @@ func (a *Server) handleReveal(w http.ResponseWriter, r *http.Request) { httpx.WriteJSON(w, http.StatusOK, map[string]any{"server_keys": cfg.ServerKeys, "zen_keys": cfg.ZenKeys, "go_keys": cfg.GoKeys, "proxies": cfg.Proxies}) } +// handleMonitor answers with the build version, the metrics snapshot and the +// current resource counts. func (a *Server) handleMonitor(w http.ResponseWriter, _ *http.Request) { metrics := a.monitor.Snapshot() httpx.WriteJSON(w, http.StatusOK, map[string]any{ @@ -252,6 +292,8 @@ func (a *Server) handleMonitor(w http.ResponseWriter, _ *http.Request) { }) } +// handleLogs returns the buffered log events after the "after" sequence, +// newest "limit" of them, and whether older events have already expired. func (a *Server) handleLogs(w http.ResponseWriter, r *http.Request) { after, _ := strconv.ParseUint(r.URL.Query().Get("after"), 10, 64) limit, _ := strconv.Atoi(r.URL.Query().Get("limit")) @@ -259,6 +301,11 @@ func (a *Server) handleLogs(w http.ResponseWriter, r *http.Request) { httpx.WriteJSON(w, http.StatusOK, map[string]any{"events": events, "gap": gap}) } +// handleLogStream streams log events as server-sent events, starting after the +// Last-Event-ID header or the "after" query parameter. A gap event marks a +// cursor that has already expired, and a keepalive is sent every 20 seconds; +// a keepalive that finds the session no longer valid ends the stream, since +// nothing re-authenticates it mid-stream. func (a *Server) handleLogStream(w http.ResponseWriter, r *http.Request) { flusher, ok := w.(http.Flusher) if !ok { @@ -311,6 +358,8 @@ func (a *Server) handleLogStream(w http.ResponseWriter, r *http.Request) { } } +// sessionTokenValid reports whether token still names a live session that +// belongs to the current username and password hash. func (a *Server) sessionTokenValid(token string) bool { a.mu.Lock() session, ok := a.sessions[tokenDigest(token)] @@ -326,6 +375,7 @@ func (a *Server) sessionTokenValid(token string) bool { return session.Username == cfg.WebUI.Username && session.AuthVersion == config.Fingerprint(cfg.WebUI.PasswordHash) } +// configView builds the masked view of the current configuration. func (a *Server) configView() ConfigView { cfg := a.manager.Config() effective, restart := a.manager.RestartStatus() @@ -339,6 +389,8 @@ func (a *Server) configView() ConfigView { } } +// maskSecrets turns secrets into views carrying their fingerprint and either +// the masked value or, for proxies, the URL with its credentials redacted. func maskSecrets(values []string, proxy bool) []SecretView { result := make([]SecretView, 0, len(values)) for _, value := range values { @@ -351,6 +403,9 @@ func maskSecrets(values []string, proxy bool) []SecretView { return result } +// resolveSecrets rebuilds a secret list from the update: an item with a value +// supplies it, an item with only an ID keeps the existing secret it names. An +// unknown ID is an error, which is how a stale page is detected. func resolveSecrets(inputs []SecretInput, existing []string) ([]string, error) { known := make(map[string]string, len(existing)) for _, value := range existing { @@ -374,6 +429,8 @@ func resolveSecrets(inputs []SecretInput, existing []string) ([]string, error) { return result, nil } +// decodeAdminJSON decodes one JSON value of at most 2 MiB into target, +// rejecting unknown fields and any trailing value. func decodeAdminJSON(w http.ResponseWriter, r *http.Request, target any) error { decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 2<<20)) decoder.DisallowUnknownFields() @@ -390,6 +447,7 @@ func decodeAdminJSON(w http.ResponseWriter, r *http.Request, target any) error { return nil } +// writeAdminError answers with {"error":{"code":...,"message":...}}. func writeAdminError(w http.ResponseWriter, status int, code, message string) { httpx.WriteJSON(w, status, map[string]any{"error": map[string]string{"code": code, "message": message}}) } diff --git a/internal/buildinfo/version.go b/internal/buildinfo/version.go index 81b4bea..ffafa67 100644 --- a/internal/buildinfo/version.go +++ b/internal/buildinfo/version.go @@ -1,5 +1,7 @@ // Package buildinfo shares the executable version with HTTP handlers. package buildinfo -// Version is set once by the command before any background work starts. +// Version is set once by the command before any background work starts, from +// the value the release build injected into its own version variable. It is +// reported by /api/monitor and by the gateway health endpoints. var Version = "dev" diff --git a/internal/config/config.go b/internal/config/config.go index 8ace67e..0ee2bb6 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -15,6 +15,14 @@ import ( wire "opencode2api/internal/protocol" ) +// Config is the service configuration stored in config.json. +// +// ServerKeys are the local keys clients present to the gateway; ZenKeys and +// GoKeys are the upstream keys of the two keyed tiers, and Anonymous enables +// the keyless free tier. Proxies lists the configured proxy entries; the +// entries read from ProxyFile join them only in the resolved list that +// RuntimeProxies returns, which is never saved. Prefer picks the keyed tier +// that is tried first when both serve a model. type Config struct { Rotation RotationConfig `json:"rotation"` Listen string `json:"listen"` @@ -41,9 +49,12 @@ type Config struct { // // Effort is the default for every model; EffortByModel overrides it for the // model IDs it names. A level a client sends explicitly (Anthropic's -// output_config.effort / top-level effort, or Chat's reasoning_effort) always -// wins, so a forced level only replaces a value that would otherwise have been -// derived from thinking.budget_tokens or left unset. +// output_config.effort / top-level effort, Chat's reasoning_effort, or +// Responses' reasoning.effort) always wins, so a forced level only replaces a +// value that would otherwise have been derived from thinking.budget_tokens or +// left unset. Besides the levels themselves, "none" strips reasoning from the +// request, and "auto" applies, for free models on the Zen tier only, the +// highest level the availability probe found the model to accept. type ReasoningConfig struct { // omitempty keeps a saved configuration free of the fields the operator // never set, matching how the rest of the optional surface is persisted. @@ -51,20 +62,38 @@ type ReasoningConfig struct { EffortByModel map[string]string `json:"effort_by_model,omitempty"` } +// UpstreamConfig holds the base URLs of the OpenCode origins. The gateway +// picks the request shape from the base URL (models.IsV1Upstream): one ending +// in /zen is the v1 lane, any other a v2 lane. type UpstreamConfig struct { + // Zen is the base URL of the keyed Zen tier. Its default, + // https://opencode.ai/zen, is the v1 lane, which expects the OpenCode 1.x + // client request shape. Zen string `json:"zen"` - Go string `json:"go"` - // Anonymous is the base URL used by the keyless free-tier lane. Upstream - // moved keyless inference off /zen onto its own host, so the anonymous lane - // no longer shares the Zen base with the keyed lanes. + // Go is the base URL of the keyed Go plan tier. Its default, + // https://opencode.ai/zen/go, is a v2 lane, which expects the OpenCode 2.x + // CLI shape. The WebUI also reads the plan's quota from its /v1/usage. + Go string `json:"go"` + // Anonymous is the v2 /inference origin of the keyless free tier. The + // anonymous lane tries the v1 /zen origin (models.V1Base, not Zen) first + // and falls back to this one, which is skipped when it equals the v1 + // origin. Empty means https://opencode.ai/inference. Anonymous string `json:"anonymous"` } +// RetryConfig bounds the upstream retries. MaxAttempts caps the attempts of a +// retry loop: the keyed attempts of a client request outside the rotation +// path, and the catalog refresh. For the anonymous lane it is instead a floor +// for how many rotating proxies may be drawn. TimeoutSeconds is the deadline +// of the whole client request, retries included. type RetryConfig struct { MaxAttempts int `json:"max_attempts"` TimeoutSeconds int `json:"timeout_seconds"` } +// ModelsConfig controls model discovery and routing. RefreshSeconds is the +// catalog refresh interval, and Protocols maps a model ID to the wire protocol +// used upstream, overriding the one the catalog reports. type ModelsConfig struct { RefreshSeconds int `json:"refresh_seconds"` Protocols map[string]string `json:"protocols"` @@ -73,6 +102,8 @@ type ModelsConfig struct { FreeOnly bool `json:"free_only"` } +// LoggingConfig sets the minimum log level (debug, info, warn or error) and +// RingSize, the number of recent log events kept in memory for the WebUI. type LoggingConfig struct { Level string `json:"level"` RingSize int `json:"ring_size"` @@ -82,6 +113,11 @@ type LoggingConfig struct { DumpRequestBodies bool `json:"dump_request_bodies"` } +// WebUIConfig configures the management WebUI. Password is a plaintext +// password supplied only to set one: it is hashed into PasswordHash and +// cleared before the configuration is saved. SessionTTLMinutes is the +// lifetime of a login session. Changes to Enabled and Listen take effect only +// after a restart. type WebUIConfig struct { Enabled bool `json:"enabled"` Listen string `json:"listen"` @@ -91,6 +127,12 @@ type WebUIConfig struct { SessionTTLMinutes int `json:"session_ttl_minutes"` } +// PerformanceConfig tunes the shared upstream transports and failure +// handling: the connection pool limits (MaxConnsPerHost 0 means unlimited), +// the dial timeout, the base cooldown after an upstream key or anonymous +// proxy fails, and the per-attempt and first-event timeouts. +// AttemptTimeoutSeconds 0 leaves only the request-level timeout in place, and +// FirstEventTimeoutSeconds 0 disables the first-event wait. type PerformanceConfig struct { MaxIdleConns int `json:"max_idle_conns"` MaxIdleConnsPerHost int `json:"max_idle_conns_per_host"` @@ -102,19 +144,21 @@ type PerformanceConfig struct { FirstEventTimeoutSeconds int `json:"first_event_timeout_seconds"` } -// AttemptTimeout bounds how long a single upstream attempt may wait for -// response headers before it is abandoned and the next node is tried. Values -// <= 0 keep the historical behavior of using the request-level retry timeout, -// so existing configs are unaffected. The result never exceeds requestTimeout. -// It bounds the whole attempt up to the response being released (dial, request -// write, headers and, when enabled, the first SSE event); an established -// stream keeps flowing under the request-level timeout. +// AttemptTimeout returns the bound for a single upstream attempt. When +// attempt_timeout_seconds is positive the result is that setting, capped at +// requestTimeout only when requestTimeout is positive. Otherwise the result is +// requestTimeout unchanged, so a config without the setting keeps using the +// request-level retry timeout. // -// The bound is installed on the shared transports as the header wait and on -// each attempt's context, so it covers every attempt in both the anonymous and -// the authenticated loops. Without it, one hung exit can consume the entire -// request budget by itself, and the attempts that follow are fired against an -// already-expired context. +// The gateway installs the result on the shared transports as the +// response-header wait. When the setting is positive, the inference attempts +// except /systemone also arm it as a context deadline (the rotation path keeps +// only the header wait, since it has its own first-output timer), covering the +// whole attempt up to the response being released (dial, request write, +// headers and, when enabled, the first SSE event); an established stream +// keeps flowing under the request-level timeout. Without that deadline, one +// hung exit can consume the entire request budget by itself, and the attempts +// that follow are fired against an already-expired context. func (cfg PerformanceConfig) AttemptTimeout(requestTimeout time.Duration) time.Duration { if cfg.AttemptTimeoutSeconds > 0 { attempt := time.Duration(cfg.AttemptTimeoutSeconds) * time.Second @@ -126,6 +170,10 @@ func (cfg PerformanceConfig) AttemptTimeout(requestTimeout time.Duration) time.D return requestTimeout } +// Load reads the config file at path, strips its // and /* */ comments, and +// decodes it over the built-in defaults. Decoding is strict: unknown fields +// and anything after the first JSON value are errors. The result is then +// checked by Normalize. func Load(path string) (Config, error) { data, err := os.ReadFile(path) if err != nil { @@ -157,7 +205,8 @@ func Load(path string) (Config, error) { } // Normalize resolves external inputs and validates a Config supplied by -// either the JSON file or the authenticated management API. +// either the JSON file or the authenticated management API. A relative +// proxyfile is resolved against the directory of path. func Normalize(path string, cfg Config) (Config, error) { cfg.Rotation.Defaults() if err := cfg.Rotation.Validate(nil); err != nil { @@ -302,7 +351,8 @@ func normalizeReasoning(cfg *Config) error { } // validateEffort accepts the levels the OpenAI and Anthropic surfaces define -// plus an empty string, which means "not forced". +// (minimal through max), the gateway controls "auto" and "none", and an empty +// string, which means "not forced". func validateEffort(name, value string) error { switch value { case "", "auto", "minimal", "low", "medium", "high", "xhigh", "max", "none": @@ -313,7 +363,8 @@ func validateEffort(name, value string) error { } // ForcedEffort returns the level the operator forced for a model, or an empty -// string when none applies. A stored level is already lowercase. +// string when none applies. A per-model entry, even an empty one, takes +// precedence over the default. A stored level is already lowercase. func (cfg Config) ForcedEffort(model string) string { if effort, ok := cfg.Reasoning.EffortByModel[model]; ok { return effort @@ -321,9 +372,10 @@ func (cfg Config) ForcedEffort(model string) string { return cfg.Reasoning.Effort } -// RuntimeProxies returns the resolved proxy list, including proxyfile entries. -// Config.Proxies intentionally remains the list stored in config.json so a -// save never duplicates values loaded from proxyfile. +// RuntimeProxies returns the resolved proxy list, including proxyfile entries, +// or ["direct"] when there are none. Config.Proxies intentionally remains the +// list stored in config.json so a save never duplicates values loaded from +// proxyfile. func (cfg Config) RuntimeProxies() []string { if len(cfg.effectiveProxies) > 0 { return cfg.effectiveProxies @@ -334,12 +386,17 @@ func (cfg Config) RuntimeProxies() []string { return []string{"direct"} } -// PasswordForSave ensures resolved-only data is excluded. The method is kept -// separate to make accidental persistence of effective proxy values obvious. +// PasswordForSave clears the resolved proxy list (the proxies plus proxyfile +// entries that RuntimeProxies returns), leaving only Config.Proxies; despite +// its name it does not touch the WebUI password. SaveAtomic calls it on its +// own copy before encoding. The field is unexported and so never encoded +// anyway, which makes the call a guard rather than a requirement. func (cfg *Config) PasswordForSave() { cfg.effectiveProxies = nil } +// Clone returns a copy of cfg whose slices and maps, including the rotation +// orders and the resolved proxy list, no longer share storage with cfg. func Clone(cfg Config) Config { cfg.Rotation.SOTA.Order = append([]string(nil), cfg.Rotation.SOTA.Order...) cfg.Rotation.Sweet.Order = append([]string(nil), cfg.Rotation.Sweet.Order...) diff --git a/internal/config/json.go b/internal/config/json.go index 1c66c28..11526d3 100644 --- a/internal/config/json.go +++ b/internal/config/json.go @@ -5,9 +5,11 @@ import ( "errors" ) -// stripJSONComments removes // and /* */ comments without changing newlines, -// so syntax errors still point at the correct line in config.json. Comment -// markers inside JSON strings (for example, https:// URLs) are preserved. +// stripJSONComments removes // and /* */ comments by overwriting each comment +// byte with a space but keeping newlines, so a position in the result is on +// the same line as in config.json. Comment markers inside JSON strings (for +// example, https:// URLs) are preserved. A leading UTF-8 BOM is stripped, and +// an unterminated /* comment is an error. func stripJSONComments(data []byte) ([]byte, error) { data = bytes.TrimPrefix(data, []byte{0xef, 0xbb, 0xbf}) out := make([]byte, 0, len(data)) diff --git a/internal/config/password.go b/internal/config/password.go index 19494c7..ed39a0c 100644 --- a/internal/config/password.go +++ b/internal/config/password.go @@ -20,6 +20,9 @@ const ( argonKeyLength = 32 ) +// HashPassword returns an argon2id hash of password with a random 16-byte +// salt, in the "$argon2id$v=19$m=...,t=...,p=...$salt$hash" form that +// VerifyPassword reads. Passwords shorter than 10 bytes are rejected. func HashPassword(password string) (string, error) { if len(password) < 10 { return "", errors.New("webui password must contain at least 10 characters") @@ -33,6 +36,10 @@ func HashPassword(password string) (string, error) { base64.RawStdEncoding.EncodeToString(salt), base64.RawStdEncoding.EncodeToString(hash)), nil } +// VerifyPassword reports whether password matches an encoded argon2id hash. +// A malformed hash never matches, and neither does one whose parameters, +// salt or key length fall outside fixed bounds, so a crafted hash cannot +// demand excessive memory or time. The final comparison is constant-time. func VerifyPassword(encoded, password string) bool { parts := strings.Split(encoded, "$") if len(parts) != 6 || parts[1] != "argon2id" || parts[2] != "v=19" { @@ -60,6 +67,8 @@ func VerifyPassword(encoded, password string) bool { return subtle.ConstantTimeCompare(actual, expected) == 1 } +// parseArgonParameter parses one "name=value" element of the argon2 parameter +// list. func parseArgonParameter(value, name string) (uint64, error) { prefix := name + "=" if !strings.HasPrefix(value, prefix) { diff --git a/internal/config/persistence.go b/internal/config/persistence.go index 0cc1ea5..37ce676 100644 --- a/internal/config/persistence.go +++ b/internal/config/persistence.go @@ -9,9 +9,18 @@ import ( "runtime" ) -// SaveAtomic writes normalized JSON and keeps the preceding file as -// config.json.bak. The temporary file is created beside the target so the -// final rename stays on the same filesystem. +// SaveAtomic writes cfg to path as indented JSON, after clearing the resolved +// proxy list (see PasswordForSave). It does not normalize cfg; callers pass a +// config that Normalize already accepted. An existing file is kept as +// path+".bak". +// +// The data is written and synced to a temporary file created beside the +// target, so the final rename stays on the same filesystem; the temporary +// file takes over the existing file's permission bits. Outside Windows the +// backup is a copy and the rename replaces path atomically. On Windows it +// takes two renames instead, path to the backup and then the temporary file +// to path, so path is briefly absent; if the second rename fails, the backup +// is moved back. func SaveAtomic(path string, cfg Config) error { cfg.PasswordForSave() data, err := json.MarshalIndent(cfg, "", " ") @@ -65,6 +74,8 @@ func SaveAtomic(path string, cfg Config) error { return nil } +// copyFile copies source to target, truncating target, and preserves source's +// permission bits. The copy is synced before target is closed. func copyFile(source, target string) error { in, err := os.Open(source) if err != nil { diff --git a/internal/config/proxy.go b/internal/config/proxy.go index 7cd09b3..3f55850 100644 --- a/internal/config/proxy.go +++ b/internal/config/proxy.go @@ -35,6 +35,10 @@ func ParseProxyEntry(raw string) (clean string, pool bool) { return trimmed, pool } +// resolveProxyFiles trims cfg.Proxies in place and stores the runtime proxy +// list: those proxies followed by the entries of cfg.ProxyFile (resolved +// against the directory of configPath when relative), deduplicated, or +// ["direct"] when nothing is left. func resolveProxyFiles(configPath string, cfg *Config) error { trimList(&cfg.Proxies) effective := append([]string(nil), cfg.Proxies...) @@ -58,6 +62,9 @@ func resolveProxyFiles(configPath string, cfg *Config) error { return nil } +// readProxyFile returns one proxy entry per non-empty line of path, ignoring a +// byte-order mark and comments (see stripProxyLineComment). A line may be up +// to 1 MiB long. func readProxyFile(path string) ([]string, error) { file, err := os.Open(path) if err != nil { @@ -81,6 +88,9 @@ func readProxyFile(path string) ([]string, error) { return proxies, nil } +// stripProxyLineComment cuts line at the first "#", ";" or "//" that starts +// the line or follows a space or tab, so a #pool fragment or the "//" of a +// URL survives. func stripProxyLineComment(line string) string { for i := 0; i < len(line); i++ { if i > 0 && line[i-1] != ' ' && line[i-1] != '\t' { @@ -93,9 +103,13 @@ func stripProxyLineComment(line string) string { return line } -// uniqueProxyEntries drops exact repeats while keeping a #pool entry next to a -// static proxy that dials the same endpoint: they are different routes (fresh -// connection, no cooldown, no health eviction), not two spellings of one. +// uniqueProxyEntries drops empty entries and repeats, keeping the first +// spelling of each, and filters items in place. Entries are compared by their +// clean dial URL (see ParseProxyEntry) together with the pool marker, so +// "pool+URL" and "URL#pool" are one entry, while a #pool entry next to a +// static proxy that dials the same endpoint is kept: they are different +// routes (fresh connection, no cooldown, no health eviction), not two +// spellings of one. func uniqueProxyEntries(items []string) []string { out := items[:0] seen := make(map[string]struct{}, len(items)) @@ -122,6 +136,7 @@ func uniqueProxyEntries(items []string) []string { return out } +// trimList trims every item in place and drops the empty ones. func trimList(items *[]string) { out := (*items)[:0] for _, item := range *items { diff --git a/internal/config/proxy_test.go b/internal/config/proxy_test.go deleted file mode 100644 index df97e85..0000000 --- a/internal/config/proxy_test.go +++ /dev/null @@ -1,95 +0,0 @@ -package config - -import "testing" - -func TestParseProxyEntry(t *testing.T) { - cases := []struct { - raw string - want string - pool bool - }{ - {"direct", "direct", false}, - {"", "", false}, - {" http://127.0.0.1:7890 ", "http://127.0.0.1:7890", false}, - {"http://127.0.0.1:7890", "http://127.0.0.1:7890", false}, - {"http://127.0.0.1:7890#pool", "http://127.0.0.1:7890", true}, - {"http://127.0.0.1:7890#POOL", "http://127.0.0.1:7890", true}, - {"http://user:pass@127.0.0.1:7890#pool", "http://user:pass@127.0.0.1:7890", true}, - {"socks5://127.0.0.1:1080#pool", "socks5://127.0.0.1:1080", true}, - {"socks5h://127.0.0.1:1080#pool", "socks5h://127.0.0.1:1080", true}, - {"pool+http://127.0.0.1:7890", "http://127.0.0.1:7890", true}, - {"pool+socks5://127.0.0.1:1080", "socks5://127.0.0.1:1080", true}, - // A fragment that is not the pool marker belongs to the proxy URL. - {"http://127.0.0.1:7890#other", "http://127.0.0.1:7890#other", false}, - } - for _, tc := range cases { - clean, pool := ParseProxyEntry(tc.raw) - if clean != tc.want || pool != tc.pool { - t.Errorf("ParseProxyEntry(%q) = (%q, %v), want (%q, %v)", tc.raw, clean, pool, tc.want, tc.pool) - } - } -} - -func TestRedactURLKeepsPoolMarker(t *testing.T) { - // url.User("***") percent-escapes the asterisks; that is the existing - // RedactURL shape for every proxy, so the expectation mirrors it. - const masked = "http://%2A%2A%2A@127.0.0.1:7890#pool" - if got := RedactURL("http://user:pass@127.0.0.1:7890#pool"); got != masked { - t.Errorf("pool URL redacted as %q, want %q", got, masked) - } - if got := RedactURL("pool+http://user:pass@127.0.0.1:7890"); got != masked { - t.Errorf("pool+ URL redacted as %q, want %q", got, masked) - } - if got := RedactURL("http://127.0.0.1:7890"); got != "http://127.0.0.1:7890" { - t.Errorf("static URL redacted as %q", got) - } -} - -// The same endpoint listed statically and as a pool is two distinct routes and -// must survive deduplication; an exact repeat must not. -func TestResolveProxyFilesKeepsPoolVariantOfSameEndpoint(t *testing.T) { - cfg := Config{Proxies: []string{ - "http://127.0.0.1:7890", - "http://127.0.0.1:7890#pool", - "http://127.0.0.1:7890", - }} - if err := resolveProxyFiles("config.json", &cfg); err != nil { - t.Fatalf("resolveProxyFiles failed: %v", err) - } - got := cfg.RuntimeProxies() - want := []string{"http://127.0.0.1:7890", "http://127.0.0.1:7890#pool"} - if len(got) != len(want) { - t.Fatalf("resolved proxies = %q, want %q", got, want) - } - for i := range want { - if got[i] != want[i] { - t.Fatalf("resolved proxies = %q, want %q", got, want) - } - } -} - -// A pool entry must validate against the clean URL, and its credentials must -// stay redactable after the marker is stripped. -func TestNormalizeAcceptsPoolProxy(t *testing.T) { - cfg := Config{ - Listen: "127.0.0.1:8080", - ServerKeys: []string{"local-key"}, - Anonymous: true, - Proxies: []string{"http://user:secret@127.0.0.1:7890#pool", "direct"}, - Upstream: UpstreamConfig{Zen: "https://opencode.ai/zen", Go: "https://opencode.ai/zen/go", Anonymous: "https://opencode.ai/inference"}, - Retry: RetryConfig{MaxAttempts: 3, TimeoutSeconds: 300}, - Models: ModelsConfig{RefreshSeconds: 300, Protocols: map[string]string{}}, - Performance: PerformanceConfig{MaxIdleConns: 10, MaxIdleConnsPerHost: 10, IdleConnTimeoutSeconds: 30, ConnectTimeoutSeconds: 5, FailureCooldownSeconds: 15}, - Logging: LoggingConfig{Level: "info", RingSize: 100}, - Prefer: TierGo, - } - normalized, err := Normalize("config.json", cfg) - if err != nil { - t.Fatalf("Normalize rejected a pool proxy: %v", err) - } - redactor := NewSecretRedactor() - redactor.Replace(normalized) - if got := redactor.String("dial http://user:secret@127.0.0.1:7890 failed"); got != "dial *** failed" { - t.Errorf("pool proxy credentials survived redaction: %q", got) - } -} diff --git a/internal/config/rotation.go b/internal/config/rotation.go index 2eef2b1..774bb70 100644 --- a/internal/config/rotation.go +++ b/internal/config/rotation.go @@ -6,19 +6,34 @@ import ( "slices" ) +// SOTAModels lists the models of the "sota" rotation group in their default +// order. That group must hold exactly these models; every other model belongs +// to the "sweet" group. var SOTAModels = []string{"deepseek-v4.1-flash", "glm-5.3", "grok-4.6", "kimi-k3", "qwen3.8-max"} +// RotationGroup is one model-rotation group: Alias is the model name clients +// request to use the group, and Order is the failover order of its models. type RotationGroup struct { Alias string `json:"alias"` Order []string `json:"order"` } + +// RotationConfig configures the two model-rotation groups, which are served by +// the Go tier. FirstOutputSeconds bounds how long an attempt may take to +// produce its first output before the next attempt runs. type RotationConfig struct { SOTA RotationGroup `json:"sota"` Sweet RotationGroup `json:"sweet"` FirstOutputSeconds int `json:"first_output_seconds"` } +// IsSOTA reports whether model is one of SOTAModels. func IsSOTA(model string) bool { return slices.Contains(SOTAModels, model) } + +// Defaults fills in what is unset: the aliases "sota" and "sweet", the SOTA +// order (SOTAModels) and a 30-second first-output timeout. The sweet order has +// no default: the rotation state adds the Go tier's other models to the group +// as they appear. func (c *RotationConfig) Defaults() { if c.SOTA.Alias == "" { c.SOTA.Alias = "sota" @@ -33,6 +48,13 @@ func (c *RotationConfig) Defaults() { c.FirstOutputSeconds = 30 } } + +// Validate requires a first-output timeout of 1-300 seconds; two distinct +// aliases of up to 64 letters, digits, dots, dashes or underscores, starting +// with a letter or digit, that do not shadow a model ID (one of realModels, +// SOTAModels or the sweet order); and orders without empty or repeated +// entries, where the SOTA group holds exactly SOTAModels and the sweet group +// only other models. A nil realModels skips the catalog check. func (c RotationConfig) Validate(realModels []string) error { if c.FirstOutputSeconds < 1 || c.FirstOutputSeconds > 300 { return fmt.Errorf("首个有效输出超时需为 1–300 秒") diff --git a/internal/config/secrets.go b/internal/config/secrets.go index 544992d..a49f45c 100644 --- a/internal/config/secrets.go +++ b/internal/config/secrets.go @@ -9,6 +9,8 @@ import ( "sync/atomic" ) +// MaskValue hides a secret for display: "••••" followed by its last five +// characters, or "••••" alone when the value has five characters or fewer. func MaskValue(value string) string { runes := []rune(value) if len(runes) <= 5 { @@ -17,6 +19,9 @@ func MaskValue(value string) string { return "••••" + string(runes[len(runes)-5:]) } +// RedactURL renders a proxy entry or URL for display with any userinfo +// replaced by "***". A pool entry gets a #pool fragment when it has none, and +// an unparsable value becomes "". func RedactURL(raw string) string { clean, pool := ParseProxyEntry(raw) if clean != "" { @@ -35,17 +40,28 @@ func RedactURL(raw string) string { return u.String() } -type SecretRedactor struct { +// Redactor scrubs configured secrets from text such as log lines and error +// messages. It is safe for concurrent use: Replace swaps the whole secret set +// atomically. +type Redactor struct { values atomic.Value } -func NewSecretRedactor() *SecretRedactor { - r := &SecretRedactor{} +// SecretRedactor returns a Redactor with no secrets loaded; Replace loads +// them. +func SecretRedactor() *Redactor { + r := &Redactor{} r.values.Store([]string(nil)) return r } -func (r *SecretRedactor) Replace(cfg Config) { +// Replace loads the secrets of cfg: the server, Zen and Go keys, the WebUI +// plaintext password, each upstream URL that carries userinfo (whole, plus its +// username and password), and each entry of RuntimeProxies other than +// "direct" (as written and as its clean URL, plus any username and password). +// Longer secrets are replaced first, so a secret that contains a shorter one +// is scrubbed whole. +func (r *Redactor) Replace(cfg Config) { values := make([]string, 0, len(cfg.ServerKeys)+len(cfg.ZenKeys)+len(cfg.GoKeys)+2) values = append(values, cfg.ServerKeys...) values = append(values, cfg.ZenKeys...) @@ -77,7 +93,9 @@ func (r *SecretRedactor) Replace(cfg Config) { r.values.Store(values) } -func (r *SecretRedactor) String(value string) string { +// String returns value with every loaded secret of at least four bytes +// replaced by "***". +func (r *Redactor) String(value string) string { for _, secret := range r.values.Load().([]string) { if len(secret) >= 4 { value = strings.ReplaceAll(value, secret, "***") @@ -86,14 +104,20 @@ func (r *SecretRedactor) String(value string) string { return value } +// Fingerprint returns the first 10 hex digits of the SHA-256 of value. It is +// the stable ID of a secret in config, session and usage bookkeeping +// (ServerKeyMetadata is keyed by it), and it doubles as the id of the masked +// secrets, API keys and Playground key choices that the WebUI shows and sends +// back. func Fingerprint(value string) string { sum := sha256.Sum256([]byte(value)) return hex.EncodeToString(sum[:])[:10] } -// keyDisplayID is intentionally separate from secretFingerprint. The latter -// is an internal stable identifier used by session/config bookkeeping; this -// value is safe for logs and the operator UI and shows only the key suffix. +// KeyDisplayID returns the last five characters of value, or the whole value +// when it has five characters or fewer. It is intentionally separate from +// Fingerprint: it is meant to be read by a person, and it is the key_id of an +// upstream key in logs, request telemetry and the key status list. func KeyDisplayID(value string) string { runes := []rune(value) if len(runes) <= 5 { diff --git a/internal/config/server_keys.go b/internal/config/server_keys.go index 1dcb3cf..2b17168 100644 --- a/internal/config/server_keys.go +++ b/internal/config/server_keys.go @@ -2,18 +2,24 @@ package config import "time" -// Metadata is keyed by the existing key fingerprint; secret values remain in -// server_keys for compatibility with existing configuration and clients. +// ServerKeyMetadata holds the WebUI-managed details of one server key: its +// display name, whether it is disabled, and when it was created. It is keyed +// by the existing key fingerprint; secret values remain in server_keys for +// compatibility with existing configuration and clients. type ServerKeyMetadata struct { Name string `json:"name"` Disabled bool `json:"disabled,omitempty"` CreatedAt time.Time `json:"created_at,omitempty"` } +// ServerKeyEnabled reports whether key may authenticate clients. A key +// without metadata is enabled. func (c Config) ServerKeyEnabled(key string) bool { return !c.ServerKeyMetadata[Fingerprint(key)].Disabled } +// FirstEnabledServerKey returns the first enabled server key, or "" when every +// key is disabled. The Playground sends its requests with this key. func (c Config) FirstEnabledServerKey() string { for _, key := range c.ServerKeys { if c.ServerKeyEnabled(key) { diff --git a/internal/config/tier.go b/internal/config/tier.go index b0220f4..0f0014e 100644 --- a/internal/config/tier.go +++ b/internal/config/tier.go @@ -1,8 +1,15 @@ package config +// Tier names a keyed upstream tier. It is also the type of the "prefer" +// setting, which picks the tier that is tried first when both serve a model. type Tier string const ( + // TierZen is the keyed Zen tier, served by upstream.zen, whose default is + // the v1 /zen origin. Anonymous routes resolve to TierZen too, although + // the keyless lane sends to its own origins (see UpstreamConfig.Anonymous). TierZen Tier = "zen" - TierGo Tier = "go" + // TierGo is the keyed Go plan tier, served by upstream.go, whose default + // is the v2 /zen/go origin. + TierGo Tier = "go" ) diff --git a/internal/gateway/availability.go b/internal/gateway/availability.go index bcb2d46..cabe575 100644 --- a/internal/gateway/availability.go +++ b/internal/gateway/availability.go @@ -10,7 +10,9 @@ import ( "opencode2api/internal/models" ) -func (m *RuntimeManager) AvailabilitySnapshot() []models.Availability { +// AvailabilitySnapshot returns the availability state of every free model in +// the current runtime's catalog. +func (m *RuntimeController) AvailabilitySnapshot() []models.Availability { items := []models.Availability{} r := m.current.Load() if r == nil { @@ -24,7 +26,11 @@ func (m *RuntimeManager) AvailabilitySnapshot() []models.Availability { return items } -func (m *RuntimeManager) RestoreModel(model string) error { +// RestoreModel re-enables a free model by putting it under manual control +// (see AvailabilityRegistry.Restore), which also discards the results of +// probes already in flight. It fails for a model that is not a free model of +// the current catalog. +func (m *RuntimeController) RestoreModel(model string) error { m.updateMu.Lock() defer m.updateMu.Unlock() r := m.current.Load() @@ -41,7 +47,7 @@ func (m *RuntimeManager) RestoreModel(model string) error { // SetManualModel switches a free model between manual and automatic control. // Manual models stay enabled and are excluded from automatic probing. -func (m *RuntimeManager) SetManualModel(model string, manual bool) error { +func (m *RuntimeController) SetManualModel(model string, manual bool) error { m.updateMu.Lock() defer m.updateMu.Unlock() r := m.current.Load() @@ -56,7 +62,10 @@ func (m *RuntimeManager) SetManualModel(model string, manual bool) error { return errors.New("unknown free model") } -func (m *RuntimeManager) startAvailabilityChecks() { +// startAvailabilityChecks probes due free models at once and then every +// minute until Shutdown or the root context stops it. It runs on the +// controller's root context, so it survives runtime swaps. +func (m *RuntimeController) startAvailabilityChecks() { ctx, cancel := context.WithCancel(m.root) m.availabilityCancel = cancel go func() { @@ -73,7 +82,10 @@ func (m *RuntimeManager) startAvailabilityChecks() { }() } -func (m *RuntimeManager) checkFreeModels(ctx context.Context) { +// checkFreeModels probes, one at a time, every free model under automatic +// control whose next check is due. A result is recorded only while the +// runtime that ran the probe is still current. +func (m *RuntimeController) checkFreeModels(ctx context.Context) { for _, item := range m.AvailabilitySnapshot() { if ctx.Err() != nil { return diff --git a/internal/gateway/first_event.go b/internal/gateway/first_event.go index e003a58..0f73295 100644 --- a/internal/gateway/first_event.go +++ b/internal/gateway/first_event.go @@ -18,13 +18,16 @@ import ( "opencode2api/internal/config" ) +// errFirstEventTimeout and errAttemptTimeout are the cancel causes of the two +// deadlines doInferenceAttempt arms. Both wrap context.DeadlineExceeded, so +// generic timeout checks still match them. var ( errFirstEventTimeout = fmt.Errorf("upstream first SSE event timed out: %w", context.DeadlineExceeded) errAttemptTimeout = fmt.Errorf("upstream attempt timed out: %w", context.DeadlineExceeded) ) // attemptTrace records how far a single attempt got before it failed. The -// shared ResponseHeaderTimeout only covers the header wait; this probe tells +// shared ResponseHeaderTimeout only covers the header wait; this trace tells // apart the phases it cannot see (dial, request write) from the ones it can. // The callbacks run on transport goroutines, so the flags are atomic. type attemptTrace struct { @@ -33,6 +36,9 @@ type attemptTrace struct { gotFirstByte atomic.Bool } +// phase names the phase the attempt is in: "dial" until a connection is +// obtained, "write" until the request is written, "headers" until the first +// response byte arrives, and "first_event" afterwards. func (t *attemptTrace) phase() string { switch { case !t.gotConn.Load(): @@ -77,6 +83,9 @@ func (e *phasedError) Unwrap() error { return e.err } // client gets a proxy error instead of a generic bad gateway. var errProxyUnavailable = errors.New("proxy unavailable") +// proxyUnavailableError is an attempt error that asProxyUnavailable attributed +// to the proxy route. It matches both errProxyUnavailable and the original +// error under errors.Is and errors.As. type proxyUnavailableError struct { proxy string err error @@ -87,11 +96,14 @@ func (e *proxyUnavailableError) Error() string { } func (e *proxyUnavailableError) Unwrap() []error { return []error{errProxyUnavailable, e.err} } -// asProxyUnavailable tags an attempt error that died before a connection to the -// upstream existed. Through a real proxy that phase covers the proxy dial, the -// CONNECT/SOCKS handshake and the TLS handshake tunnelled through it, so the -// failure belongs to the proxy rather than the upstream. Direct transports are -// left untouched: there a dial failure is an upstream reachability problem. +// asProxyUnavailable tags an attempt error that belongs to the proxy route +// rather than the upstream: one that died before a connection to the upstream +// existed (the "dial" phase), or a *net.OpError raised by the proxy dialer +// itself (Op "proxyconnect", or one starting with "socks"). Through a real +// proxy the dial phase covers the proxy dial, the CONNECT/SOCKS handshake and +// the TLS handshake tunnelled through it, so the failure belongs to the proxy +// rather than the upstream. Direct transports are left untouched: there a dial +// failure is an upstream reachability problem. func asProxyUnavailable(proxy *proxyTransport, err error) error { if err == nil || proxy == nil || proxy.name == "direct" { return err @@ -105,8 +117,9 @@ func asProxyUnavailable(proxy *proxyTransport, err error) error { } // classifyAttemptError renders a leg token for the request log. The phase is -// appended for the attempt-deadline and transport cases so a hung exit can be -// attributed without grepping logs. +// appended for the attempt-deadline, generic timeout and transport cases so a +// hung exit can be attributed without grepping logs; a first-event timeout is +// its own phase and is reported as plain "first_event". func classifyAttemptError(err error) string { var pe *phasedError phase := "" @@ -125,6 +138,9 @@ func classifyAttemptError(err error) string { } } +// attemptBody is the response body doInferenceAttempt hands back. Reading +// replays any buffered SSE prelude before the rest of the stream, and Close +// also releases the attempt's context. type attemptBody struct { io.Reader body io.ReadCloser @@ -136,14 +152,27 @@ func (b *attemptBody) Close() error { return b.body.Close() } -// Wait before returning a successful SSE response to the retry loop, while -// nothing has been committed downstream. Keep every byte for native forwarding. -// Comments and incomplete frames do not count as the first event. +// doInferenceAttempt sends one upstream attempt through client under two +// optional deadlines. It passes straight through to client.Do when both +// timeouts are zero or negative, and for the /systemone path. +// +// firstEventTimeout applies only to a 2xx text/event-stream response: before +// returning it to the retry loop, while nothing has been committed downstream, +// it waits for the first complete SSE event (see readFirstEvent). Every byte +// read meanwhile is kept and replayed for native forwarding. Comments and +// incomplete frames do not count as the first event. Any other response is +// returned as soon as its headers arrive. // // attemptTimeout bounds the whole attempt (dial + request write + response // headers + first event). ResponseHeaderTimeout only covers the header wait, // so a wedged exit can otherwise hang in the write or dial phase until the -// request-level budget is gone. +// request-level budget is gone. Once the response is committed the timer can +// no longer cut the established stream. +// +// Outside the pass-through cases, failures are returned as a *phasedError +// naming the phase the attempt reached, with errAttemptTimeout or +// errFirstEventTimeout as the error when that deadline caused the failure, and +// closing the returned body also releases the attempt's context. func doInferenceAttempt(client *http.Client, req *http.Request, firstEventTimeout, attemptTimeout time.Duration) (*http.Response, error) { if (firstEventTimeout <= 0 && attemptTimeout <= 0) || strings.HasSuffix(req.URL.Path, "/systemone") { return client.Do(req) @@ -234,6 +263,11 @@ func doInferenceAttempt(client *http.Client, req *http.Request, firstEventTimeou return resp, nil } +// readFirstEvent reads up to and including the blank line that ends the first +// SSE event carrying a data field, and returns every byte read for replay. +// Comment lines and data-less events before it stay in the returned prefix but +// do not end the wait. It fails if the stream ends first (io.ErrUnexpectedEOF), +// on a read error, or once the prelude would exceed 1 MiB. func readFirstEvent(reader *bufio.Reader) ([]byte, error) { const maxPrelude = 1 << 20 var prefix, line []byte diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 58cdfd6..02b6847 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1,4 +1,15 @@ // Package gateway routes inference requests through managed upstream pools. +// +// Upstreams fall into two lanes, named after the OpenCode client generation +// whose request shape they expect, not after their URL path: both lanes +// append the /v1/... route segment. The v1 lane is the https://opencode.ai/zen +// origin (models.V1Base, also the default upstream.zen), which +// models.IsV1Upstream detects. It expects the OpenCode 1.x client shape: the +// 1.x User-Agent, the x-opencode-request header, a git-commit-shaped project +// and, on the free tier, the single "read" tool. The v2 lane is the /inference +// origin (upstream.anonymous) and the Go plan's /zen/go origin, which expect +// the OpenCode 2.x CLI shape. The anonymous free tier tries the v1 origin +// first and falls back to the configured v2 /inference origin. package gateway import ( @@ -25,11 +36,14 @@ import ( const maxRequestBody = 32 << 20 +// anonymousZenKey is the shared credential the anonymous free tier sends as +// its API key. const anonymousZenKey = "public" -// attemptDeadline is the per-attempt context deadline. It is armed only when -// attempt_timeout_seconds is set: otherwise the request-level budget already -// bounds the single attempt it would cover. +// attemptDeadline returns the per-attempt deadline, capped at the request +// timeout. It is zero unless attempt_timeout_seconds is set: AttemptTimeout +// would otherwise fall back to the request timeout, which the request context +// already enforces. func attemptDeadline(cfg config.Config) time.Duration { if cfg.Performance.AttemptTimeoutSeconds <= 0 { return 0 @@ -41,46 +55,61 @@ func attemptDeadline(cfg config.Config) time.Duration { // gateway could answer, so the failure is neither upstream nor ours. const statusClientClosedRequest = 499 -// proxyUnavailableMessage is returned when every attempt died on the proxy -// route itself, so operators look at their proxies instead of the upstream. +// proxyUnavailableMessage is the 503 message sent when the error a request +// finally failed with is tagged errProxyUnavailable: its last attempt never +// reached the upstream because the proxy route failed, or the anonymous lane +// had no proxy to try while none was healthy. Only that final error is +// inspected; earlier attempts may have failed for other reasons. The message +// points operators at their proxies instead of the upstream. const proxyUnavailableMessage = "all proxies are unavailable; the upstream could not be reached" +// Gateway serves the local inference API for one configuration. It owns the +// proxy transports and the key and anonymous node pools built from that +// config; applying a new config builds a new Gateway (see RuntimeController) +// instead of mutating this one. type Gateway struct { rotation *rotation.Manager cfg config.Config logger *slog.Logger - transports *transportPool - zenNodes *nodePool - goNodes *nodePool - anonymous *anonymousPool - catalog *models.Catalog - monitor *telemetry.Monitor - availability *models.AvailabilityStore - // attemptTimeout bounds a whole upstream attempt (dial + write + headers + - // first event), not just the header wait. Zero keeps the legacy behavior. + transports *proxyTransports + zenNodes *upstreamNodes + goNodes *upstreamNodes + anonymous *anonymousNodes + catalog *models.ModelCatalog + monitor *telemetry.Metrics + availability *models.AvailabilityRegistry + // attemptTimeout bounds a whole upstream attempt (dial + write + headers + // and, when the first-event wait is enabled, the first event), not just + // the header wait. Zero arms no per-attempt deadline: each attempt is then + // bounded only by the request-level budget. attemptTimeout time.Duration } -func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Monitor) (*Gateway, error) { +// New builds a Gateway for cfg: one proxy transport per runtime proxy (a +// single direct transport when none is configured), Zen and Go key pools +// bound to those transports, the anonymous node pool and a model catalog. Its +// rotation manager is not persisted; RuntimeController replaces it with the +// shared one. +func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Metrics) (*Gateway, error) { cfg.Rotation.Defaults() rotationManager, err := rotation.New("", cfg.Rotation) if err != nil { return nil, err } - transports, err := newTransportPool(cfg.RuntimeProxies(), cfg.Performance, cfg.Performance.AttemptTimeout(time.Duration(cfg.Retry.TimeoutSeconds)*time.Second)) + transports, err := transportPool(cfg.RuntimeProxies(), cfg.Performance, cfg.Performance.AttemptTimeout(time.Duration(cfg.Retry.TimeoutSeconds)*time.Second)) if err != nil { return nil, err } cooldown := time.Duration(cfg.Performance.FailureCooldownSeconds) * time.Second - zenNodes, err := newNodePool(cfg.ZenKeys, transports, cooldown) + zenNodes, err := nodePool(cfg.ZenKeys, transports, cooldown) if err != nil { return nil, fmt.Errorf("zen node pool: %w", err) } - goNodes, err := newNodePool(cfg.GoKeys, transports, cooldown) + goNodes, err := nodePool(cfg.GoKeys, transports, cooldown) if err != nil { return nil, fmt.Errorf("go node pool: %w", err) } - catalog := models.NewCatalog(cfg.Prefer, cfg.Models.Protocols) + catalog := models.Catalog(cfg.Prefer, cfg.Models.Protocols) catalog.SetRefreshInterval(time.Duration(cfg.Models.RefreshSeconds) * time.Second) catalog.SetFreeOnly(cfg.Models.FreeOnly) return &Gateway{ @@ -90,13 +119,16 @@ func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Monitor) (*G transports: transports, zenNodes: zenNodes, goNodes: goNodes, - anonymous: newAnonymousPool(cfg.Anonymous, transports, cooldown), + anonymous: anonymousPool(cfg.Anonymous, transports, cooldown), catalog: catalog, monitor: monitor, attemptTimeout: attemptDeadline(cfg), }, nil } +// Handler returns the gateway's HTTP API: the server-key authenticated /v1 +// model, inference and System One routes plus the open /healthz, wrapped in +// panic recovery. func (g *Gateway) Handler() http.Handler { mux := http.NewServeMux() mux.HandleFunc("GET /v1/models", g.authenticate(g.handleModels)) @@ -108,6 +140,10 @@ func (g *Gateway) Handler() http.Handler { return telemetry.Recover(g.logger, mux) } +// authenticate admits a request whose x-api-key header or Bearer token +// matches an enabled server key, and stores the caller's fingerprint in the +// request context and telemetry metadata. Anything else gets a 401 shaped for +// the endpoint: Anthropic for /v1/messages, Chat otherwise. func (g *Gateway) authenticate(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { candidates := []string{strings.TrimSpace(r.Header.Get("x-api-key"))} @@ -155,6 +191,10 @@ func callerScope(ctx context.Context) string { return caller } +// handleInference serves a message endpoint whose wire protocol is external. +// A rotation group alias is handed to handleRotation. Any other model is +// routed through the catalog, encoded per upstream tier, sent through +// doUpstream and translated back into external, streaming or not. func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxRequestBody)) @@ -242,8 +282,9 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { return } g.logger.Warn("all upstream attempts failed", "component", "upstream", "event", "request_failed", "request_id", ids.Request, "tier", finalTier, "key_id", keyID, "channel", channel, "anonymous", anonymous, "error", err) - // The request never reached the upstream because the proxy route - // failed; report that instead of blaming the upstream with a 502. + // The final attempt never reached the upstream because its proxy + // route failed; report that instead of blaming the upstream with + // a 502. if errors.Is(err, errProxyUnavailable) { wire.WriteError(w, external, http.StatusServiceUnavailable, proxyUnavailableMessage, "proxy_error", ids.Request) return @@ -283,7 +324,7 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { w.Header().Set("Cache-Control", "no-cache") w.Header().Set("X-Accel-Buffering", "no") w.WriteHeader(resp.StatusCode) - streamBody := wire.RenameStreamReader(resp.Body, upstreamRoute.Protocol, legacyAnonymousReadTool, toolAlias) + streamBody := wire.RenameStreamReader(resp.Body, upstreamRoute.Protocol, v1ReadTool, toolAlias) var usage wire.Usage var usageReported bool if external == upstreamRoute.Protocol { @@ -311,20 +352,19 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { return } if upstreamRoute.Anonymous || (meta != nil && meta.Shaped) { - // Key-tier shaped requests were force-streamed like the - // anonymous lane; collapse the same way. - // The anonymous lane is served streaming (see prepareAnonymousBody); - // collapse the events back into the single document this - // non-streaming client asked for. + // The anonymous lane, and a key-tier request shaped like it, is + // force-streamed upstream (see prepareAnonymousBody); collapse + // the events back into the single document this non-streaming + // client asked for. collapsed, err := wire.CollapseStream(bytes.NewReader(responseBody), upstreamRoute.Protocol, model) if err != nil { - g.logger.Warn("anonymous stream collapse failed", "component", "conversion", "event", "anonymous_collapse_failed", "request_id", ids.Request, "model", model, "source_protocol", upstreamRoute.Protocol, "error", err) + g.logger.Warn("forced stream collapse failed", "component", "conversion", "event", "stream_collapse_failed", "request_id", ids.Request, "model", model, "anonymous", upstreamRoute.Anonymous, "source_protocol", upstreamRoute.Protocol, "error", err) wire.WriteError(w, external, http.StatusBadGateway, "unsupported upstream response", "upstream_error", ids.Request) return } responseBody = collapsed } - responseBody = wire.RenameResponseTool(responseBody, upstreamRoute.Protocol, legacyAnonymousReadTool, toolAlias) + responseBody = wire.RenameResponseTool(responseBody, upstreamRoute.Protocol, v1ReadTool, toolAlias) if usage, reported := wire.ResponseUsage(upstreamRoute.Protocol, responseBody); meta != nil { meta.Usage, meta.UsageReported = usage, reported } @@ -467,6 +507,11 @@ func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body _, _ = w.Write(responseBody) } +// prepareRouteBodies encodes input once for each key tier the route may use, +// the preferred tier first and then its KeyTiers, in that tier's upstream +// protocol and with any forced reasoning effort applied. A fallback tier the +// request cannot be converted for is skipped; only a conversion failure on +// the preferred tier is an error. func (g *Gateway) prepareRouteBodies(from wire.Protocol, route models.Route, input map[string]any) (map[config.Tier][]byte, error) { tiers := make([]config.Tier, 0, len(route.KeyTiers)+1) seen := make(map[config.Tier]bool, len(route.KeyTiers)+1) @@ -515,6 +560,10 @@ func (g *Gateway) prepareRouteBodies(from wire.Protocol, route models.Route, inp return bodies, nil } +// copyErrorResponse relays a non-2xx upstream reply as an error in the +// client's protocol. It keeps the status and any Retry-After, and takes the +// message from a JSON body's error.message or message, falling back to the +// status text. func copyErrorResponse(w http.ResponseWriter, protocol wire.Protocol, resp *http.Response, requestID string) { body, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) if retryAfter := resp.Header.Get("Retry-After"); retryAfter != "" { diff --git a/internal/gateway/health.go b/internal/gateway/health.go index 8586c77..697b345 100644 --- a/internal/gateway/health.go +++ b/internal/gateway/health.go @@ -47,6 +47,10 @@ type healthProxies struct { Unhealthy int `json:"unhealthy"` } +// handleHealth reports readiness. It answers 503 while the model catalog is +// pending or empty or no proxy is healthy, and 200 otherwise. Any issue, +// including a stale catalog or no upstream credentials, marks the status +// degraded, except that a pending catalog reports starting. func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { _, models := g.availableModels() proxyTotal, proxyHealthy := g.transports.healthCounts() @@ -135,6 +139,9 @@ func (g *Gateway) reasoningEfforts(model string, route modelcatalog.Route) []str return slices.Clone(reasoningLevels) } +// handleModels lists every servable model with its tier-scoped metadata in +// the OpenAI list shape, plus, when Go keys are configured, one entry per +// rotation group alias that has a Go-routable model. func (g *Gateway) handleModels(w http.ResponseWriter, _ *http.Request) { now := time.Now().Unix() routes, _ := g.availableModels() diff --git a/internal/gateway/pool.go b/internal/gateway/pool.go index b794368..3b8e26b 100644 --- a/internal/gateway/pool.go +++ b/internal/gateway/pool.go @@ -22,6 +22,11 @@ import ( "opencode2api/internal/httpx" ) +// proxyTransport is one configured proxy route, or "direct", with its own HTTP +// client. pool marks a rotating proxy pool entry (#pool or pool+), whose +// health is never tracked. healthy is cleared by proxy-route failures and set +// again by upstream HTTP responses (see syncProxyResult) or a passing health +// check; checking claims the single health check allowed in flight. type proxyTransport struct { index int name string @@ -31,14 +36,16 @@ type proxyTransport struct { checking atomic.Bool } -type transportPool struct { +// proxyTransports holds every configured proxy route, indexed by +// proxyTransport.index, shared by the key and anonymous node pools. +type proxyTransports struct { items []*proxyTransport } -// anonymousPool gives the shared OpenCode "public" credential an independent +// anonymousNodes gives the shared OpenCode "public" credential an independent // cooldown per proxy. Unlike key nodes, anonymous nodes are never rebound: // changing proxy is the failover mechanism because Zen rate-limits them by IP. -type anonymousPool struct { +type anonymousNodes struct { nodes []*anonymousNode next atomic.Uint64 cooldown time.Duration @@ -51,15 +58,20 @@ type anonymousNode struct { cooldownUntil atomic.Int64 } +// anonymousCursor walks the anonymous nodes for one request from start; +// offset counts the positions visited so far and used marks the nodes the +// first pass or the fallback of Next has already returned. type anonymousCursor struct { - pool *anonymousPool + pool *anonymousNodes start int offset int used []bool } -func newAnonymousPool(enabled bool, transports *transportPool, cooldown time.Duration) *anonymousPool { - pool := &anonymousPool{cooldown: cooldown} +// anonymousPool builds one anonymous node per proxy transport, or an empty +// pool when the anonymous tier is disabled. +func anonymousPool(enabled bool, transports *proxyTransports, cooldown time.Duration) *anonymousNodes { + pool := &anonymousNodes{cooldown: cooldown} if !enabled || transports == nil { return pool } @@ -73,18 +85,23 @@ func newAnonymousPool(enabled bool, transports *transportPool, cooldown time.Dur return pool } -func (p *anonymousPool) Len() int { +func (p *anonymousNodes) Len() int { if p == nil { return 0 } return len(p.nodes) } -func (p *anonymousPool) HasPool() bool { +// HasPool reports whether any node uses a rotating proxy pool (#pool), which +// lets callers make more attempts than there are nodes. +func (p *anonymousNodes) HasPool() bool { return p != nil && p.hasPool } -func (p *anonymousPool) CursorFor(affinity string) anonymousCursor { +// CursorFor returns a cursor whose first node is stable for a non-empty +// affinity key, keeping a conversation on one exit; an empty affinity rotates +// the starting node round-robin. +func (p *anonymousNodes) CursorFor(affinity string) anonymousCursor { if p == nil || len(p.nodes) == 0 { return anonymousCursor{pool: p} } @@ -99,13 +116,15 @@ func (p *anonymousPool) CursorFor(affinity string) anonymousCursor { return anonymousCursor{pool: p, start: start} } -// Next visits each healthy, non-cooling static proxy at most once per cursor. -// When the pool contains rotating proxy-pool transports (#pool), it continues -// cycling through them after the first pass so retry.max_attempts can draw a -// fresh upstream connection (and new exit IP) on every attempt. If all static -// proxies are currently cooling or marked unhealthy, Next falls back to the -// earliest-expiring node not yet tried by this cursor instead of returning nil -// immediately. +// Next returns the next node to try. Its first pass visits every node once +// from the cursor's start and returns each healthy, non-cooling static proxy +// and each rotating proxy-pool transport (#pool) it reaches, so healthy nodes +// are tried first. When the pool contains #pool transports, Next then keeps +// cycling through only those, so retry.max_attempts can draw a fresh upstream +// connection (and new exit IP) on every attempt. Otherwise it falls back to +// the nodes this cursor has not returned yet, healthy ones first and, among +// those, the one whose cooldown expires earliest, and returns nil only once +// every node has been returned. func (c *anonymousCursor) Next() *anonymousNode { if c.pool == nil || len(c.pool.nodes) == 0 { return nil @@ -156,7 +175,7 @@ func (c *anonymousCursor) Next() *anonymousNode { return nil } -func (p *anonymousPool) MarkSuccess(node *anonymousNode) { +func (p *anonymousNodes) MarkSuccess(node *anonymousNode) { if node == nil { return } @@ -165,10 +184,11 @@ func (p *anonymousPool) MarkSuccess(node *anonymousNode) { } // RestoreProxy clears cooldowns for anonymous nodes bound to a recovered -// proxy, mirroring nodePool.RestoreProxy for key nodes. Without this, an +// proxy, mirroring upstreamNodes.RestoreProxy for key nodes. Without this, an // outage-era cooldown survives the proxy's recovery and the anonymous lane -// stays skipped even though the route is healthy again. -func (p *anonymousPool) RestoreProxy(proxy *proxyTransport) int { +// stays skipped even though the route is healthy again. It returns how many +// nodes it cleared. +func (p *anonymousNodes) RestoreProxy(proxy *proxyTransport) int { if p == nil || proxy == nil { return 0 } @@ -189,14 +209,20 @@ func (p *anonymousPool) RestoreProxy(proxy *proxyTransport) int { // maxAnonymousRetryAfterMultiplier bounds an upstream Retry-After on the // anonymous lane to the same 8x ceiling as its exponential backoff. The lane -// is rate limited per exit IP and, unlike key lanes, has no earliest-expiry -// fallback: a quota response asking for hours would keep the exit skipped long -// after a network change gave it a fresh allowance. Key lanes keep honoring -// Retry-After in full, since their cursor already falls back to the node that -// recovers first. +// is rate limited per exit IP, and a cooling node is reached only through the +// cursor's fallback: after every eligible node, and not at all while #pool +// transports are present, since the cursor then keeps cycling those. A quota +// response asking for hours would keep the exit demoted long after a network +// change gave it a fresh allowance. Key lanes keep honoring Retry-After in +// full. const maxAnonymousRetryAfterMultiplier = 8 -func (p *anonymousPool) MarkFailure(node *anonymousNode, resp *http.Response, err error) { +// MarkFailure cools node down after an error or a 401, 403, 429 or 5xx +// response; any other response leaves it untouched, and #pool nodes are never +// cooled. The cooldown doubles with each consecutive failure, from the +// base cooldown up to 8x, and a longer Retry-After extends it up to that same +// 8x ceiling. +func (p *anonymousNodes) MarkFailure(node *anonymousNode, resp *http.Response, err error) { if node == nil || (node.proxy != nil && node.proxy.pool) { return } @@ -213,7 +239,7 @@ func (p *anonymousPool) MarkFailure(node *anonymousNode, resp *http.Response, er node.cooldownUntil.Store(time.Now().Add(delay).UnixNano()) } -func (p *transportPool) hasHealthy() bool { +func (p *proxyTransports) hasHealthy() bool { for _, proxy := range p.items { if proxy.healthy.Load() { return true @@ -222,7 +248,7 @@ func (p *transportPool) hasHealthy() bool { return false } -func (p *transportPool) healthCounts() (total, healthy int) { +func (p *proxyTransports) healthCounts() (total, healthy int) { if p == nil { return 0, 0 } @@ -234,8 +260,13 @@ func (p *transportPool) healthCounts() (total, healthy int) { return len(p.items), healthy } -func newTransportPool(proxies []string, cfg config.PerformanceConfig, responseHeaderTimeout time.Duration) (*transportPool, error) { - p := &transportPool{items: make([]*proxyTransport, 0, len(proxies))} +// transportPool builds one HTTP client per configured proxy entry, each +// starting healthy, with responseHeaderTimeout as its header wait. A #pool +// entry gets an HTTP/1.1 transport without keep-alives, so every attempt opens +// a new connection through the pool; "direct" dials the upstream without any +// proxy, ignoring the proxy environment variables. +func transportPool(proxies []string, cfg config.PerformanceConfig, responseHeaderTimeout time.Duration) (*proxyTransports, error) { + p := &proxyTransports{items: make([]*proxyTransport, 0, len(proxies))} for _, raw := range proxies { clean, isPool := config.ParseProxyEntry(raw) transport := http.DefaultTransport.(*http.Transport).Clone() @@ -281,6 +312,9 @@ func newTransportPool(proxies []string, cfg config.PerformanceConfig, responseHe return p, nil } +// proxyHealthResult is the outcome of one health check. failed is set only +// for a proxy-route failure (see isProxyFailure), and wasHealthy is the +// healthy flag as it stood before the check updated it. type proxyHealthResult struct { proxy *proxyTransport err error @@ -288,11 +322,12 @@ type proxyHealthResult struct { wasHealthy bool } -// CheckHealth concurrently rechecks only proxies already marked unhealthy. -// Healthy proxies are skipped before a check is claimed. Any HTTP response -// from the test URL proves that the route is reachable; only a timeout or -// connection refusal keeps the proxy unhealthy. -func (p *transportPool) CheckHealth(ctx context.Context, target string, timeout time.Duration) []proxyHealthResult { +// CheckHealth concurrently rechecks only proxies already marked unhealthy and +// waits for every check to finish. Healthy proxies, #pool transports and +// proxies whose check is already in flight are skipped. Any HTTP response +// from the test URL proves that the route is reachable and restores the +// proxy; any error keeps it unhealthy. +func (p *proxyTransports) CheckHealth(ctx context.Context, target string, timeout time.Duration) []proxyHealthResult { results := make(chan proxyHealthResult, len(p.items)) checks := 0 for _, proxy := range p.items { @@ -317,14 +352,17 @@ func (p *transportPool) CheckHealth(ctx context.Context, target string, timeout return out } -// checkClaimedProxy performs a check after the caller has acquired checking. -func (p *transportPool) checkClaimedProxy(ctx context.Context, proxy *proxyTransport, target string, timeout time.Duration) proxyHealthResult { +// checkClaimedProxy sends one GET to target through proxy after the caller +// has acquired checking, and releases that claim when done. Any HTTP response +// marks the proxy healthy, a proxy-route failure marks it unhealthy, and any +// other error leaves the flag as it is. +func (p *proxyTransports) checkClaimedProxy(ctx context.Context, proxy *proxyTransport, target string, timeout time.Duration) proxyHealthResult { defer proxy.checking.Store(false) checkCtx, cancel := context.WithTimeout(ctx, timeout) defer cancel() req, err := http.NewRequestWithContext(checkCtx, http.MethodGet, target, nil) if err == nil { - req.Header.Set("User-Agent", httpx.UserAgent()) + req.Header.Set("User-Agent", httpx.V2UserAgent()) resp, requestErr := proxy.client.Do(req) err = requestErr if resp != nil { @@ -343,8 +381,9 @@ func (p *transportPool) checkClaimedProxy(ctx context.Context, proxy *proxyTrans } // isProxyFailure deliberately recognizes only failures that say the proxy -// route is unavailable. HTTP responses and unrelated transport/protocol errors -// must not evict a proxy. +// route is unavailable: a timeout or a connection refusal. HTTP responses, +// timeouts in the first-event wait (the upstream already answered with +// headers) and unrelated transport/protocol errors must not evict a proxy. func isProxyFailure(err error) bool { if errors.Is(err, errFirstEventTimeout) || upstreamAccepted(err) { return false // The upstream accepted HTTP; slow generation is not a broken proxy. @@ -370,23 +409,27 @@ type upstreamNode struct { cooldownUntil atomic.Int64 } -type nodePool struct { +// upstreamNodes is one tier's key pool. bindingsMu serializes rebinding and +// guards bindingCount, the number of keys bound to each proxy index; a node's +// proxyIndex is atomic, so reading a binding needs no lock. +type upstreamNodes struct { nodes []*upstreamNode - transports *transportPool + transports *proxyTransports next atomic.Uint64 cooldown time.Duration bindingsMu sync.Mutex bindingCount []int } -// newNodePool distributes keys over proxies in round-robin order. When there +// nodePool distributes keys over proxies in round-robin order. When there // are fewer keys than proxies, the remaining proxies are intentionally idle and -// can take over a key immediately if an active proxy fails. -func newNodePool(keys []string, transports *transportPool, cooldown time.Duration) (*nodePool, error) { +// can take over a key immediately if an active proxy fails. It needs at least +// one proxy transport. +func nodePool(keys []string, transports *proxyTransports, cooldown time.Duration) (*upstreamNodes, error) { if transports == nil || len(transports.items) == 0 { return nil, fmt.Errorf("at least one proxy transport is required") } - pool := &nodePool{ + pool := &upstreamNodes{ nodes: make([]*upstreamNode, 0, len(keys)), transports: transports, cooldown: cooldown, @@ -406,9 +449,10 @@ func newNodePool(keys []string, transports *transportPool, cooldown time.Duratio } // RestoreProxy moves keys that were originally assigned to a recovered proxy -// back to it. Proxies without an original key simply become healthy failover -// candidates again. -func (p *nodePool) RestoreProxy(recoveredProxy int) int { +// back to it, clearing their failure counts and cooldowns, and returns how +// many keys moved. Proxies without an original key simply become healthy +// failover candidates again. +func (p *upstreamNodes) RestoreProxy(recoveredProxy int) int { if p == nil || p.transports == nil || recoveredProxy < 0 || recoveredProxy >= len(p.transports.items) { return 0 } @@ -433,11 +477,11 @@ func (p *nodePool) RestoreProxy(recoveredProxy int) int { return moved } -func (p *nodePool) Len() int { return len(p.nodes) } +func (p *upstreamNodes) Len() int { return len(p.nodes) } // NodeByID resolves a node by its stable fingerprint. Callers only ever hold // the fingerprint, never the key value, so the lookup cannot leak a secret. -func (p *nodePool) NodeByID(id string) *upstreamNode { +func (p *upstreamNodes) NodeByID(id string) *upstreamNode { if p == nil || id == "" { return nil } @@ -449,7 +493,7 @@ func (p *nodePool) NodeByID(id string) *upstreamNode { return nil } -func (p *nodePool) Proxy(node *upstreamNode) *proxyTransport { +func (p *upstreamNodes) Proxy(node *upstreamNode) *proxyTransport { if p == nil || node == nil || p.transports == nil { return nil } @@ -463,8 +507,10 @@ func (p *nodePool) Proxy(node *upstreamNode) *proxyTransport { // RebindProxy moves every key currently using failedProxy to the least-loaded // healthy proxy. Empty proxies are selected in configuration order; otherwise // one of the least-loaded proxies is chosen at random. If every alternative is -// currently unhealthy, it still attempts the least-loaded alternative. -func (p *nodePool) RebindProxy(failedProxy int) int { +// currently unhealthy, it still moves the key to the least-loaded alternative. +// Moved keys start with a clean failure count and cooldown. It returns how +// many keys moved; with a single proxy there is nowhere to move them. +func (p *upstreamNodes) RebindProxy(failedProxy int) int { if p == nil || p.transports == nil || len(p.transports.items) < 2 || failedProxy < 0 || failedProxy >= len(p.transports.items) { return 0 } @@ -493,7 +539,12 @@ func (p *nodePool) RebindProxy(failedProxy int) int { return moved } -func (p *nodePool) replacementLocked(failedProxy int, healthyOnly bool) int { +// replacementLocked picks the proxy a key leaving failedProxy moves to: the +// first proxy in configuration order with no keys bound, otherwise a random +// one of the least-loaded, considering only healthy proxies when healthyOnly +// is set. It returns -1 when no proxy qualifies. The caller must hold +// bindingsMu. +func (p *upstreamNodes) replacementLocked(failedProxy int, healthyOnly bool) int { minimum := int(^uint(0) >> 1) candidates := make([]int, 0, len(p.transports.items)-1) for i := range p.transports.items { @@ -519,14 +570,14 @@ func (p *nodePool) replacementLocked(failedProxy int, healthyOnly bool) int { } type nodeCursor struct { - pool *nodePool + pool *upstreamNodes next int } // Cursor reserves a different starting node for each concurrent request. // Selection is delayed until Next, so a node marked failed by the preceding // attempt is immediately skipped. Both Cursor and Next allocate no memory. -func (p *nodePool) Cursor() nodeCursor { +func (p *upstreamNodes) Cursor() nodeCursor { if len(p.nodes) == 0 { return nodeCursor{pool: p} } @@ -537,7 +588,7 @@ func (p *nodePool) Cursor() nodeCursor { // affinity key. This keeps every turn in a conversation on the same upstream // key while retaining Next's cooldown-aware failover behavior. Empty affinity // keys keep the round-robin behavior used by background tasks. -func (p *nodePool) CursorFor(affinity string) nodeCursor { +func (p *upstreamNodes) CursorFor(affinity string) nodeCursor { if affinity == "" || len(p.nodes) == 0 { return p.Cursor() } @@ -546,6 +597,11 @@ func (p *nodePool) CursorFor(affinity string) nodeCursor { return nodeCursor{pool: p, next: int(hash.Sum64() % uint64(len(p.nodes)))} } +// Next returns the first node from the cursor position that is not cooling +// down or, when every key is cooling, the one whose cooldown expires +// earliest, and moves the cursor past it. Unlike anonymousCursor.Next it never +// returns nil for a non-empty pool and may revisit a node, so callers bound +// their attempts themselves. func (c *nodeCursor) Next() *upstreamNode { if c.pool == nil || len(c.pool.nodes) == 0 { return nil @@ -571,12 +627,16 @@ func (c *nodeCursor) Next() *upstreamNode { return c.pool.nodes[choice] } -func (p *nodePool) MarkSuccess(node *upstreamNode) { +func (p *upstreamNodes) MarkSuccess(node *upstreamNode) { node.failures.Store(0) node.cooldownUntil.Store(0) } -func (p *nodePool) MarkFailure(node *upstreamNode, resp *http.Response, err error) { +// MarkFailure cools node down after an error or a 401, 403, 429 or 5xx +// response; any other response leaves it untouched. The cooldown doubles with +// each consecutive failure, from the base cooldown up to 8x, and an upstream +// Retry-After longer than that is honored in full. +func (p *upstreamNodes) MarkFailure(node *upstreamNode, resp *http.Response, err error) { if err == nil && resp != nil && resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusTooManyRequests && resp.StatusCode < 500 { return } @@ -591,6 +651,9 @@ func (p *nodePool) MarkFailure(node *upstreamNode, resp *http.Response, err erro node.cooldownUntil.Store(time.Now().Add(delay).UnixNano()) } +// parseRetryAfter reads a Retry-After header in delta-seconds or HTTP-date +// form. It returns 0 for an empty, non-positive or unparsable value and for a +// date already in the past. func parseRetryAfter(value string) time.Duration { if seconds, err := strconv.Atoi(strings.TrimSpace(value)); err == nil && seconds > 0 { return time.Duration(seconds) * time.Second diff --git a/internal/gateway/probe.go b/internal/gateway/probe.go index cdd9243..17b3e68 100644 --- a/internal/gateway/probe.go +++ b/internal/gateway/probe.go @@ -16,18 +16,26 @@ import ( wire "opencode2api/internal/protocol" ) +// probeResult is the outcome of a free-model probe: whether it succeeded and +// whether any request was sent at all, whether the upstream rejected the +// requested reasoning effort, a reason code, the channel ("anonymous" or +// "zen") that produced it, and the effort observation to store. type probeResult struct { success, attempted, effortRejected bool reason, channel string effort models.EffortProbe } +// resolvedEffort returns the reasoning effort to force on a request for model: +// the configured effort unless it is "auto", otherwise the level a recent +// availability probe confirmed for this protocol on the free Zen tier, or "" +// to inject none. 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 + // Only the free Zen tier 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 "" @@ -42,7 +50,13 @@ func (g *Gateway) resolvedEffort(model string, tier config.Tier, protocol wire.P return item.AutoEffort.Effort } -func probePayload(model string, protocol wire.Protocol, effort string, legacy bool) ([]byte, error) { +// probePayload builds the probe body for model: a System One arithmetic +// question, or a minimal streaming "Reply with OK." Chat prompt converted to +// protocol, with effort forced when non-empty and the result shaped for the +// free tier by prepareAnonymousBody. v1 reports whether the probe targets the +// v1 lane (models.IsV1Upstream), which selects the single "read" tool shaping +// instead of the v2 toolset. +func probePayload(model string, protocol wire.Protocol, effort string, v1 bool) ([]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{ @@ -61,10 +75,18 @@ func probePayload(model string, protocol wire.Protocol, effort string, legacy bo if err != nil { return nil, err } - shaped, _ := prepareAnonymousBody(b, protocol, legacy) + shaped, _ := prepareAnonymousBody(b, protocol, v1) return shaped, nil } +// probeFreeModel checks whether a free model currently answers on the Zen +// tier. It tries one anonymous proxy against each anonymous upstream (in +// anonymousUpstreams order) and then one Zen key, and stops at the first lane +// that succeeds. For a reasoning model whose effort is "auto", a successful +// baseline is followed by trials from "max" downward to find the highest +// effort it accepts on this protocol. The reason is model_unavailable only +// when every lane reported it; any other failure keeps the result +// inconclusive. func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult { if !g.catalog.IsFreeModel(model) { return probeResult{reason: "not_free"} @@ -83,7 +105,8 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult if g.cfg.Anonymous { cursor := g.anonymous.CursorFor(ids.Session) if node := cursor.Next(); node != nil { - // Prefer the legacy /zen/v1 lane before falling back to /inference. + // Prefer the v1 lane (/zen) before falling back to the v2 + // /inference origin. for _, baseURL := range g.anonymousUpstreams() { lanes = append(lanes, lane{anonymousZenKey, "anonymous", baseURL, node.proxy.client}) } @@ -146,15 +169,22 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult return result } +// probeAttempt sends one probe request through client with a 60-second budget +// and classifies the result. Unlike live traffic it bypasses +// doInferenceAttempt and records nothing against keys or proxies. Success +// requires a 2xx whose SSE stream collapses cleanly or whose JSON document has +// the protocol's result field; a failure carries a reason code (http_, +// model_unavailable, probe_timeout, ...) and whether the upstream rejected the +// reasoning effort. 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, isLegacyZenUpstream(baseURL)) + b, err := probePayload(model, protocol, effort, models.IsV1Upstream(baseURL)) 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) + req, err := upstreamRequest(ctx, baseURL, protocol, b, ids, key) if err != nil { return probeResult{reason: "request_creation_error"} } @@ -226,6 +256,9 @@ func (g *Gateway) probeAttempt(parent context.Context, client *http.Client, base return result } +// isModelUnavailable reports whether a 400, 404, 410 or 422 error body says +// the model itself is unknown, retired or no longer available, as opposed to +// a transient or credential failure. func isModelUnavailable(status int, body string) bool { if status != 400 && status != 404 && status != 410 && status != 422 { return false @@ -239,6 +272,9 @@ func isModelUnavailable(status int, body string) bool { return false } +// isEffortRejection reports whether a 400 or 422 error body rejects the +// requested reasoning level: it must mention effort, thinking or reasoning +// together with a validation marker such as "invalid" or "unsupported". func isEffortRejection(status int, body string) bool { if status != 400 && status != 422 { return false diff --git a/internal/gateway/refresh.go b/internal/gateway/refresh.go index 54d5021..8946ab1 100644 --- a/internal/gateway/refresh.go +++ b/internal/gateway/refresh.go @@ -17,11 +17,15 @@ const ( proxyHealthCheckTimeout = 10 * time.Second ) -// syncProxyResult updates proxy health from real traffic. Only timeouts and -// connection refusals mark a proxy unavailable. Any HTTP response — including -// 4xx/5xx — proves the route is reachable and restores a proxy evicted by an -// earlier transient failure, so a rate-limited exit is never blamed on the -// proxy route itself. +// syncProxyResult updates proxy health from real traffic and reports whether +// it treated the outcome as a proxy-route failure; nil and #pool proxies are +// skipped and report false. Only timeouts and connection refusals mark a +// proxy unavailable: its keys are rebound elsewhere at once and a confirming +// health check starts in the background. An HTTP status (a 2xx/3xx, or a +// 4xx/5xx reported without an error) proves the route is reachable and +// restores a proxy evicted by an earlier transient failure, so a rate-limited +// exit is never blamed on the proxy route itself. Any other error only starts +// the background check, which never affects the return value. func (g *Gateway) syncProxyResult(ctx context.Context, proxy *proxyTransport, status int, err error) bool { if proxy == nil || proxy.pool { return false @@ -55,11 +59,14 @@ func (g *Gateway) syncProxyResult(ctx context.Context, proxy *proxyTransport, st return false } +// verifyProxyAfterError starts a background health check of proxy, unless one +// is already in flight, and applies its result. status is the upstream status +// that prompted it and only labels the log. func (g *Gateway) verifyProxyAfterError(ctx context.Context, proxy *proxyTransport, status int) { if !proxy.checking.CompareAndSwap(false, true) { return } - // The client request may finish or be cancelled while the verification is + // The client request may finish or be canceled while the verification is // running. Keep its values but give the proxy check an independent timeout. checkCtx := context.WithoutCancel(ctx) go func() { @@ -68,6 +75,8 @@ func (g *Gateway) verifyProxyAfterError(ctx context.Context, proxy *proxyTranspo }() } +// rebindFailedProxy marks proxy unhealthy and moves the Zen and Go keys bound +// to it to other proxies (see rebindUnavailableProxy). func (g *Gateway) rebindFailedProxy(proxy *proxyTransport) (zenMoved, goMoved int) { if proxy == nil { return 0, 0 @@ -76,6 +85,10 @@ func (g *Gateway) rebindFailedProxy(proxy *proxyTransport) (zenMoved, goMoved in return g.rebindUnavailableProxy(proxy, wasHealthy) } +// rebindUnavailableProxy moves the Zen and Go keys bound to proxy to other +// proxies and logs the eviction when the proxy was healthy before or any key +// moved. It does not touch the healthy flag, and anonymous nodes are never +// rebound. func (g *Gateway) rebindUnavailableProxy(proxy *proxyTransport, wasHealthy bool) (zenMoved, goMoved int) { zenMoved = g.zenNodes.RebindProxy(proxy.index) goMoved = g.goNodes.RebindProxy(proxy.index) @@ -85,6 +98,9 @@ func (g *Gateway) rebindUnavailableProxy(proxy *proxyTransport, wasHealthy bool) return zenMoved, goMoved } +// restoreProxy moves keys back to a recovered proxy they were originally +// assigned to and clears the anonymous cooldowns bound to it. It does not set +// the healthy flag; callers do that first. func (g *Gateway) restoreProxy(proxy *proxyTransport) (zenMoved, goMoved int) { if proxy == nil { return 0, 0 @@ -100,6 +116,9 @@ func (g *Gateway) restoreProxy(proxy *proxyTransport) (zenMoved, goMoved int) { return zenMoved, goMoved } +// StartProxyHealthChecks rechecks unhealthy proxies every +// proxyHealthCheckInterval until ctx is canceled. There is no check at +// startup, since every proxy starts healthy. func (g *Gateway) StartProxyHealthChecks(ctx context.Context) { check := func() { results := g.transports.CheckHealth(ctx, proxyHealthCheckURL, proxyHealthCheckTimeout) @@ -121,6 +140,10 @@ func (g *Gateway) StartProxyHealthChecks(ctx context.Context) { }() } +// applyProxyHealthResult acts on one health check: a pass restores a proxy +// that was unhealthy, a proxy-route failure rebinds its keys only while some +// proxy is still healthy, and an inconclusive error changes nothing. source +// and upstreamStatus only label the log. func (g *Gateway) applyProxyHealthResult(result proxyHealthResult, source string, upstreamStatus int) { if result.err == nil { if !result.wasHealthy { @@ -143,6 +166,12 @@ func (g *Gateway) applyProxyHealthResult(result proxyHealthResult, source string g.logger.Debug("proxy health check is still failing", "component", "proxy", "event", "health_check_still_failing", "source", source, "upstream_status", upstreamStatus, "proxy", config.RedactURL(result.proxy.name), "error", result.err) } +// StartModelRefresh refreshes the model catalog at once and then every +// models.refresh_seconds until ctx is canceled. Each round concurrently lists +// the Zen models (through the anonymous lane when no Zen key can) and the Go +// models, and fetches OpenCode's protocol capabilities. The catalog is +// replaced only when at least one listing succeeded; the rotation groups are +// then resynced and the catalog cache saved. func (g *Gateway) StartModelRefresh(ctx context.Context) { refresh := func() { var zen, goModels []string @@ -191,6 +220,9 @@ func (g *Gateway) StartModelRefresh(ctx context.Context) { }() } +// refreshProtocolCapabilities fetches OpenCode's capability catalog through +// each healthy proxy in turn until one succeeds. Only a gateway without any +// transport falls back to a direct client. func (g *Gateway) refreshProtocolCapabilities(ctx context.Context) (modelcatalog.Capabilities, error) { if g.transports == nil || len(g.transports.items) == 0 { return modelcatalog.FetchCapabilities(ctx, &http.Client{Timeout: 30 * time.Second}, modelcatalog.CapabilitiesURL) @@ -212,6 +244,8 @@ func (g *Gateway) refreshProtocolCapabilities(ctx context.Context) (modelcatalog return modelcatalog.Capabilities{}, lastErr } +// refreshZen lists the Zen models with the Zen keys and, when that fails and +// the anonymous tier is enabled, with the public credential instead. func (g *Gateway) refreshZen(ctx context.Context) []string { if models := g.refreshTier(ctx, g.cfg.Upstream.Zen, g.zenNodes); models != nil { return models @@ -222,6 +256,9 @@ func (g *Gateway) refreshZen(ctx context.Context) []string { return g.refreshAnonymousTier(ctx, g.cfg.Upstream.Anonymous) } +// refreshAnonymousTier lists models with the public credential, one anonymous +// node per attempt: one pass over the nodes, or up to retry.max_attempts +// attempts when #pool transports exist. base only labels the logs. func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []string { cursor := g.anonymous.CursorFor("") limit := g.anonymous.Len() @@ -237,8 +274,8 @@ func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []strin var models []string var status int var err error - // Prefer the legacy /zen/v1 models listing before falling back to the - // configured anonymous upstream. + // List models on the v1 origin first, then fall back to the + // configured v2 /inference origin (see anonymousUpstreams). for _, upstream := range g.anonymousUpstreams() { models, status, err = modelcatalog.FetchModels(refreshCtx, node.proxy.client, upstream, anonymousZenKey) if err == nil { @@ -258,7 +295,10 @@ func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []strin return nil } -func (g *Gateway) refreshTier(ctx context.Context, base string, nodes *nodePool) []string { +// refreshTier lists the models at base with up to retry.max_attempts keys +// from nodes, updating proxy health and key cooldowns after every attempt. It +// returns nil when the pool has no keys or every attempt fails. +func (g *Gateway) refreshTier(ctx context.Context, base string, nodes *upstreamNodes) []string { cursor := nodes.Cursor() for attempt := 0; attempt < g.cfg.Retry.MaxAttempts; attempt++ { node := cursor.Next() diff --git a/internal/gateway/rotation.go b/internal/gateway/rotation.go index c53ec10..9976b35 100644 --- a/internal/gateway/rotation.go +++ b/internal/gateway/rotation.go @@ -20,6 +20,9 @@ import ( "opencode2api/internal/telemetry" ) +// syncRotation tells the rotation manager which catalog models the Go tier can +// serve right now: every model with a Go route except System One models, and +// none while no Go key is configured. func (g *Gateway) syncRotation() { available := map[string]bool{} for _, model := range g.catalog.List() { @@ -29,19 +32,30 @@ func (g *Gateway) syncRotation() { } g.rotation.Sync(available) } -func (m *RuntimeManager) RotationSnapshot() rotation.Snapshot { + +// RotationSnapshot resyncs the rotation groups with the current catalog and +// returns their state. +func (m *RuntimeController) RotationSnapshot() rotation.Snapshot { r := m.current.Load() r.gateway.syncRotation() return m.rotation.Snapshot() } -func (m *RuntimeManager) SelectRotation(id, model string) error { + +// SelectRotation manually switches rotation group id to model, clearing any +// pause on it, after resyncing the groups with the current catalog. model +// must be one of the group's currently available models. +func (m *RuntimeController) SelectRotation(id, model string) error { m.updateMu.Lock() defer m.updateMu.Unlock() m.current.Load().gateway.syncRotation() return m.rotation.Manual(id, model) } -// Explicit quota markers only: ordinary provider errors must keep their budget. +// quotaError reports whether a failed rotation attempt hit a quota or rate +// limit, which pauses the model for its Retry-After instead of spending the +// request's ordinary-failure budget. Any 429 counts; otherwise only explicit +// quota markers in the body do, since ordinary provider errors must keep +// their budget. func quotaError(status int, body string) bool { if status == 429 { return true @@ -55,6 +69,10 @@ func quotaError(status int, body string) bool { return false } +// groupAttempt is the outcome of one rotation attempt. quota marks a quota or +// rate-limit failure, committed means the reply already reached the client, +// pause is how long a quota failure pauses the model, and reason labels the +// attempt record. type groupAttempt struct { err error quota, committed bool @@ -62,6 +80,16 @@ type groupAttempt struct { reason string } +// handleRotation serves a request addressed to a rotation group alias on the +// Go tier. It walks the group's usable models from the current one, giving +// each up to three single-call attempts. A quota or rate-limit failure pauses +// the model for its Retry-After (60 seconds without one) and moves on to the +// next model; a model that fails a third time for another reason is paused +// for 15 seconds. The walk ends on success, once a reply has been committed +// downstream, once three models have failed for ordinary reasons, when no +// usable model is left, or when the request budget runs out. Unless the client +// went away, a request left without a reply then gets a 503, or a 504 when +// the budget ran out. func (g *Gateway) handleRotation(w http.ResponseWriter, r *http.Request, external wire.Protocol, payload map[string]any, id, alias string) { g.syncRotation() ctx, cancel := context.WithTimeout(r.Context(), time.Duration(g.cfg.Retry.TimeoutSeconds)*time.Second) @@ -163,6 +191,11 @@ func (g *Gateway) handleRotation(w http.ResponseWriter, r *http.Request, externa wire.WriteError(w, external, status, message, "rotation_unavailable", ids.Request) } +// rotationAttempt makes one upstream call for a rotation group model with the +// attempt-th key the session's Go cursor yields. Nothing reaches the client +// unless the first useful output (for a non-streaming reply, the whole body) +// arrives within the rotation's first_output_seconds, and the reply names the +// group alias as its model. func (g *Gateway) rotationAttempt(parent context.Context, w http.ResponseWriter, original *http.Request, external wire.Protocol, payload map[string]any, alias string, route models.Route, ids identity.RequestIDs, attempt int) groupAttempt { result := groupAttempt{reason: "upstream_error", pause: 60 * time.Second} ctx, cancel := context.WithCancel(parent) @@ -201,7 +234,7 @@ func (g *Gateway) rotationAttempt(parent context.Context, w http.ResponseWriter, result.err = errors.New("no proxy") return result } - req, err := newUpstreamRequest(ctx, g.cfg.Upstream.Go, route.Protocol, body, ids, node.key) + req, err := upstreamRequest(ctx, g.cfg.Upstream.Go, route.Protocol, body, ids, node.key) if err != nil { result.err = err return result @@ -264,7 +297,7 @@ func (g *Gateway) rotationAttempt(parent context.Context, w http.ResponseWriter, g.monitor.BeginStream() defer g.monitor.EndStream() } - streamBody := wire.RenameStreamReader(resp.Body, route.Protocol, legacyAnonymousReadTool, toolAlias) + streamBody := wire.RenameStreamReader(resp.Body, route.Protocol, v1ReadTool, toolAlias) usage, reported, committed, err := wire.RotationStream(original.Context(), w, streamBody, route.Protocol, external, alias, ready) if meta != nil { meta.Usage = usage @@ -302,7 +335,7 @@ func (g *Gateway) rotationAttempt(parent context.Context, w http.ResponseWriter, b, err = wire.CollapseStream(bytes.NewReader(b), route.Protocol, route.ID) } if err == nil { - b = wire.RenameResponseTool(b, route.Protocol, legacyAnonymousReadTool, toolAlias) + b = wire.RenameResponseTool(b, route.Protocol, v1ReadTool, toolAlias) } var document map[string]any if err == nil { diff --git a/internal/gateway/runtime.go b/internal/gateway/runtime.go index eae5404..4b76356 100644 --- a/internal/gateway/runtime.go +++ b/internal/gateway/runtime.go @@ -17,50 +17,69 @@ import ( "opencode2api/internal/telemetry" ) +// gatewayRuntime is one applied configuration: the Gateway built from it, that +// gateway's HTTP handler, the availability registry it uses, and cancel, +// which stops the gateway's background proxy checks and model refresh. type gatewayRuntime struct { - availability *modelcatalog.AvailabilityStore + availability *modelcatalog.AvailabilityRegistry config config.Config gateway *Gateway handler http.Handler cancel context.CancelFunc } +// ApplyResult reports whether a configuration was applied and which listener +// fields only take effect after a restart. type ApplyResult struct { Applied bool `json:"applied"` RestartRequired bool `json:"restart_required"` RestartFields []string `json:"restart_fields,omitempty"` } -type RuntimeManager struct { +// RuntimeController owns the running gateway and swaps in a freshly built one +// whenever a configuration is applied; each request is served by the runtime +// that was current when it arrived. It also owns the state that outlives a +// runtime: the persisted rotation manager, the pricing metadata, the +// free-model availability checks and the listeners bound at startup. +type RuntimeController struct { rotation *rotation.Manager configPath string root context.Context logger *slog.Logger - monitor *telemetry.Monitor - hub *telemetry.LogHub - redactor *config.SecretRedactor + monitor *telemetry.Metrics + hub *telemetry.LogBroker + redactor *config.Redactor level *slog.LevelVar current atomic.Pointer[gatewayRuntime] updateMu sync.Mutex - effective effectiveListeners - metadata *modelcatalog.PricingStore + effective EffectiveListeners + metadata *modelcatalog.PricingRegistry availabilityCancel context.CancelFunc } -type effectiveListeners struct { +// EffectiveListeners are the listener settings the running process actually +// bound at startup. They only change after a restart. +type EffectiveListeners struct { API string WebUI string WebUIEnabled bool } -func NewRuntimeManager(root context.Context, configPath string, cfg config.Config, logger *slog.Logger, monitor *telemetry.Monitor, hub *telemetry.LogHub, redactor *config.SecretRedactor, level *slog.LevelVar) (*RuntimeManager, error) { - manager := &RuntimeManager{ +// RuntimeManager builds the RuntimeController for cfg and starts its first +// runtime. Along the way it migrates a plaintext webui.password to a hash, +// rewriting the config file and deleting the backup that held the plaintext; +// loads the persisted rotation state and the model catalog cache; and starts +// the pricing metadata refresh and the free-model availability checks. It +// fails when the rotation config does not validate against the catalog. +func RuntimeManager(root context.Context, configPath string, cfg config.Config, logger *slog.Logger, monitor *telemetry.Metrics, hub *telemetry.LogBroker, redactor *config.Redactor, level *slog.LevelVar) (*RuntimeController, error) { + manager := &RuntimeController{ configPath: configPath, root: root, logger: logger, monitor: monitor, hub: hub, redactor: redactor, level: level, - effective: effectiveListeners{API: cfg.Listen, WebUI: cfg.WebUI.Listen, WebUIEnabled: cfg.WebUI.Enabled}, + effective: EffectiveListeners{API: cfg.Listen, WebUI: cfg.WebUI.Listen, WebUIEnabled: cfg.WebUI.Enabled}, } - manager.metadata = modelcatalog.NewPricingStore(configPath, logger) - // models.dev refreshes ride the active runtime's healthy proxy transports - // and fall back to the store's direct client when none are available. + manager.metadata = modelcatalog.PricingStore(configPath, logger) + // OpenCode metadata refreshes ride the active runtime's healthy proxy + // transports and fall back to the registry's direct client when none are + // available. manager.metadata.SetClientProvider(func() []*http.Client { runtime := manager.current.Load() if runtime == nil || runtime.gateway == nil || runtime.gateway.transports == nil { @@ -116,7 +135,11 @@ func NewRuntimeManager(root context.Context, configPath string, cfg config.Confi return manager, nil } -func (m *RuntimeManager) build(cfg config.Config) (*gatewayRuntime, error) { +// build constructs a runtime for cfg without starting it. The runtime shares +// the controller's rotation manager and pricing metadata, and keeps the +// current runtime's availability registry while the Zen upstream is +// unchanged; otherwise it uses the registry persisted for the new upstream. +func (m *RuntimeController) build(cfg config.Config) (*gatewayRuntime, error) { gateway, err := New(cfg, m.logger, m.monitor) if err != nil { return nil, err @@ -126,7 +149,7 @@ func (m *RuntimeManager) build(cfg config.Config) (*gatewayRuntime, error) { if m.configPath != "" { availabilityPath = m.configPath + "." + config.Fingerprint(cfg.Upstream.Zen) + ".availability.json" } - availability, err := modelcatalog.NewAvailabilityStore(availabilityPath) + availability, err := modelcatalog.AvailabilityStore(availabilityPath) if err != nil { return nil, fmt.Errorf("load model availability: %w", err) } @@ -140,16 +163,23 @@ func (m *RuntimeManager) build(cfg config.Config) (*gatewayRuntime, error) { return &gatewayRuntime{config: cfg, gateway: gateway, availability: availability, handler: gateway.Handler(), cancel: func() {}}, nil } -func (m *RuntimeManager) start(runtime *gatewayRuntime) { - // Store the context through a lightweight wrapper so cancel stops catalog - // and proxy checks while in-flight HTTP requests continue on the old pools. +// start launches runtime's proxy health checks and model refresh, and stores +// the func that stops them in runtime.cancel. +func (m *RuntimeController) start(runtime *gatewayRuntime) { + // The loops run under their own context derived from the controller's + // root, not under any request's: cancel stops catalog refresh and proxy + // checks while in-flight HTTP requests continue on the old pools. runtimeCtx, cancel := context.WithCancel(m.root) runtime.cancel = cancel runtime.gateway.StartProxyHealthChecks(runtimeCtx) runtime.gateway.StartModelRefresh(runtimeCtx) } -func (m *RuntimeManager) Handler() http.Handler { +// Handler returns the API handler, wrapped in the telemetry middleware. Each +// request is served by the runtime current when it arrives, so an applied +// configuration reaches new requests without a restart; before the first +// runtime exists the handler answers 503. +func (m *RuntimeController) Handler() http.Handler { dynamic := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { runtime := m.current.Load() if runtime == nil { @@ -162,11 +192,13 @@ func (m *RuntimeManager) Handler() http.Handler { } // Redact removes configured credentials from diagnostic output. -func (m *RuntimeManager) Redact(value string) string { +func (m *RuntimeController) Redact(value string) string { return m.redactor.String(value) } -func (m *RuntimeManager) Config() config.Config { +// Config returns a copy of the configuration the current runtime was built +// from, or the zero Config when no runtime exists. +func (m *RuntimeController) Config() config.Config { runtime := m.current.Load() if runtime == nil { return config.Config{} @@ -174,7 +206,10 @@ func (m *RuntimeManager) Config() config.Config { return config.Clone(runtime.config) } -func (m *RuntimeManager) RestartStatus() (effectiveListeners, []string) { +// RestartStatus returns the listeners the process bound at startup and the +// config fields (listen, webui.listen, webui.enabled) whose current value +// differs from them, i.e. the changes waiting for a restart. +func (m *RuntimeController) RestartStatus() (EffectiveListeners, []string) { cfg := m.Config() fields := make([]string, 0, 3) if cfg.Listen != m.effective.API { @@ -189,14 +224,19 @@ func (m *RuntimeManager) RestartStatus() (effectiveListeners, []string) { return m.effective, fields } -func (m *RuntimeManager) Apply(candidate config.Config, persist bool) (ApplyResult, error) { +// Apply normalizes and validates candidate, builds a runtime from it and +// swaps it in, stopping the previous runtime's background loops. It saves the +// config file when persist is set or candidate carried a plaintext WebUI +// password, which is hashed first. +func (m *RuntimeController) Apply(candidate config.Config, persist bool) (ApplyResult, error) { m.updateMu.Lock() defer m.updateMu.Unlock() return m.applyLocked(candidate, persist) } // Update serializes read-modify-write operations against the latest config. -func (m *RuntimeManager) Update(change func(*config.Config) error) (ApplyResult, error) { +// The changed config is applied and always saved. +func (m *RuntimeController) Update(change func(*config.Config) error) (ApplyResult, error) { m.updateMu.Lock() defer m.updateMu.Unlock() candidate := m.Config() @@ -206,7 +246,11 @@ func (m *RuntimeManager) Update(change func(*config.Config) error) (ApplyResult, return m.applyLocked(candidate, true) } -func (m *RuntimeManager) applyLocked(candidate config.Config, persist bool) (ApplyResult, error) { +// applyLocked does the work of Apply and Update; the caller must hold +// updateMu. Nothing changes until candidate has been normalized, built, +// validated and, when required, saved. The new runtime inherits the current +// catalog state and is started before it is swapped in. +func (m *RuntimeController) applyLocked(candidate config.Config, persist bool) (ApplyResult, error) { current := m.current.Load() hadPlaintextPassword := candidate.WebUI.Password != "" @@ -266,7 +310,10 @@ func (m *RuntimeManager) applyLocked(candidate config.Config, persist bool) (App return result, nil } -func (m *RuntimeManager) Reload() (ApplyResult, error) { +// Reload re-reads the config file and applies it without rewriting it, unless +// it holds a plaintext WebUI password: that is hashed and saved, and the +// backup holding the plaintext is removed. +func (m *RuntimeController) Reload() (ApplyResult, error) { cfg, err := config.Load(m.configPath) if err != nil { return ApplyResult{}, err @@ -279,7 +326,9 @@ func (m *RuntimeManager) Reload() (ApplyResult, error) { return result, err } -func (m *RuntimeManager) Shutdown() { +// Shutdown stops the free-model availability checks and the current runtime's +// background loops. +func (m *RuntimeController) Shutdown() { if m.availabilityCancel != nil { m.availabilityCancel() } @@ -288,6 +337,8 @@ func (m *RuntimeManager) Shutdown() { } } +// ResourceSnapshot is the operator view of the current runtime's models, keys, +// proxies and model metadata (see Resources). type ResourceSnapshot struct { Models modelcatalog.CatalogSnapshot `json:"models"` Keys []KeyStatus `json:"keys"` @@ -296,6 +347,9 @@ type ResourceSnapshot struct { Metadata modelcatalog.MetadataSnapshot `json:"metadata"` } +// KeyStatus describes one upstream key by its display ID (its last five +// characters): its tier, its current proxy binding, its consecutive failures +// and any active cooldown. type KeyStatus struct { ID string `json:"id"` Tier string `json:"tier"` @@ -305,6 +359,10 @@ type KeyStatus struct { CooldownUntil *time.Time `json:"cooldown_until,omitempty"` } +// ProxyStatus describes one proxy route: its redacted address, its health, +// whether a health check is in flight, and how many Zen and Go keys are bound +// to it. Anonymous reports whether the anonymous lane, which uses every +// proxy, is enabled. type ProxyStatus struct { Index int `json:"index"` Address string `json:"address"` @@ -315,7 +373,10 @@ type ProxyStatus struct { Anonymous bool `json:"anonymous"` } -func (m *RuntimeManager) Resources() ResourceSnapshot { +// Resources reports the current runtime's servable models, per-key state and +// per-proxy health and key bindings, or an empty snapshot when no runtime +// exists. +func (m *RuntimeController) Resources() ResourceSnapshot { runtime := m.current.Load() if runtime == nil { return ResourceSnapshot{} @@ -345,7 +406,9 @@ func (m *RuntimeManager) Resources() ResourceSnapshot { return result } -func (m *RuntimeManager) DebugModels() ([]modelcatalog.RouteDiagnostic, modelcatalog.MetadataSnapshot) { +// DebugModels returns a routing diagnostic for every catalog model, with no +// requested protocol, plus the catalog's metadata snapshot. +func (m *RuntimeController) DebugModels() ([]modelcatalog.RouteDiagnostic, modelcatalog.MetadataSnapshot) { runtime := m.current.Load() if runtime == nil { return nil, modelcatalog.MetadataSnapshot{} @@ -360,7 +423,9 @@ func (m *RuntimeManager) DebugModels() ([]modelcatalog.RouteDiagnostic, modelcat return result, metadata } -func (m *RuntimeManager) DebugRoute(model string, requested protocol.Protocol) modelcatalog.RouteDiagnostic { +// DebugRoute reports how the current runtime would route a request for model +// sent on the requested protocol. +func (m *RuntimeController) DebugRoute(model string, requested protocol.Protocol) modelcatalog.RouteDiagnostic { runtime := m.current.Load() if runtime == nil { return modelcatalog.RouteDiagnostic{Model: model, RequestedProtocol: requested, RouteError: "gateway runtime is unavailable"} @@ -382,7 +447,7 @@ type DebugKeyView struct { // DebugKeys lists every configured upstream key per tier so the Playground can // offer an explicit per-key test target. -func (m *RuntimeManager) DebugKeys() map[string][]DebugKeyView { +func (m *RuntimeController) DebugKeys() map[string][]DebugKeyView { result := map[string][]DebugKeyView{"zen": {}, "go": {}} runtime := m.current.Load() if runtime == nil { @@ -406,7 +471,9 @@ func (m *RuntimeManager) DebugKeys() map[string][]DebugKeyView { return result } -func (m *RuntimeManager) DebugKey(tier config.Tier, id string) *DebugKeyView { +// DebugKey returns the view of the tier's key whose fingerprint is id, or nil +// when no such key is configured. +func (m *RuntimeController) DebugKey(tier config.Tier, id string) *DebugKeyView { for _, view := range m.DebugKeys()[string(tier)] { if view.ID == id { selected := view @@ -417,7 +484,7 @@ func (m *RuntimeManager) DebugKey(tier config.Tier, id string) *DebugKeyView { } // DebugRouteForTier reports the route a diagnostic against one tier would take. -func (m *RuntimeManager) DebugRouteForTier(model string, tier config.Tier) (modelcatalog.RouteDiagnostic, error) { +func (m *RuntimeController) DebugRouteForTier(model string, tier config.Tier) (modelcatalog.RouteDiagnostic, error) { runtime := m.current.Load() if runtime == nil { return modelcatalog.RouteDiagnostic{Model: model, RouteError: "gateway runtime is unavailable"}, fmt.Errorf("gateway runtime is unavailable") @@ -437,7 +504,7 @@ func (m *RuntimeManager) DebugRouteForTier(model string, tier config.Tier) (mode return diagnostic, nil } -func keyStatuses(tier string, pool *nodePool) []KeyStatus { +func keyStatuses(tier string, pool *upstreamNodes) []KeyStatus { result := make([]KeyStatus, 0, len(pool.nodes)) for _, node := range pool.nodes { status := KeyStatus{ID: config.KeyDisplayID(node.key), Tier: tier, Index: node.index, ProxyIndex: int(node.proxyIndex.Load()), Failures: node.failures.Load()} diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 3a14ee1..50220b5 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -11,6 +11,8 @@ import ( "fmt" "io" "net/http" + "regexp" + "slices" "sort" "strconv" "strings" @@ -37,6 +39,10 @@ type debugKeyOverrideContextKey struct{} type diagnosticContextKey struct{} +// WithDiagnosticRequest marks ctx as a Playground diagnostic request. It uses +// the production routing and transports, but its outcomes never update key +// cooldowns, proxy health or bindings, and its traffic is accounted to the +// Playground server key rather than the key that authenticated it. func WithDiagnosticRequest(ctx context.Context) context.Context { return context.WithValue(ctx, diagnosticContextKey{}, true) } @@ -46,6 +52,10 @@ func isDiagnosticRequest(ctx context.Context) bool { return diagnostic } +// WithDebugKeyOverride marks ctx as a diagnostic request (see +// WithDiagnosticRequest) pinned to override: the request is routed to +// override.Tier only and sent once through that key, with no failover (see +// doSelectedKeyUpstream). An override without a KeyID is ignored. func WithDebugKeyOverride(ctx context.Context, override DebugKeyOverride) context.Context { return context.WithValue(WithDiagnosticRequest(ctx), debugKeyOverrideContextKey{}, override) } @@ -55,6 +65,14 @@ func debugKeyOverrideFrom(ctx context.Context) (DebugKeyOverride, bool) { return override, ok && override.KeyID != "" } +// doUpstream sends one inference request through the anonymous and key tiers +// (see doUpstreamTiers) and returns the response, whose body the caller must +// close, together with the route that produced it. It repairs one known +// failure: when the returned response is a 400 reporting a stale reasoning +// reference, it replays the request once with those references stripped, and +// returns the original 400 if the replay does not succeed. A 400 body is +// buffered (up to 1 MiB) so it can be read again. Debug key overrides skip the +// replay so the Playground sees the selected key's own answer. func (g *Gateway) doUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs) (*http.Response, models.Route, error) { resp, effectiveRoute, attempts, err := g.doUpstreamTiers(ctx, route, bodies, ids, 0) if _, selected := debugKeyOverrideFrom(ctx); selected { @@ -65,9 +83,9 @@ func (g *Gateway) doUpstream(ctx context.Context, route models.Route, bodies map } origBody := resp.Body errBody, readErr := io.ReadAll(io.LimitReader(origBody, 1<<20)) - // The original network body is always closed here: the retry path below - // reuses the connection, otherwise downstream receives a fresh in-memory - // reader over the cached bytes. + // The network body is always drained and closed here so its connection + // can be reused, for instance by the retry below; downstream receives a + // fresh in-memory reader over the cached bytes instead. httpx.DrainAndClose(origBody) if readErr != nil { resp.Body = io.NopCloser(bytes.NewReader(errBody)) @@ -78,9 +96,10 @@ func (g *Gateway) doUpstream(ctx context.Context, route models.Route, bodies map resp.Body = io.NopCloser(bytes.NewReader(errBody)) // Log a capped snippet of the upstream error body so the 400 class is // visible without dumping full payloads. Bodies stay out of attempt - // records; the hub redactor scrubs configured secrets from log output. + // records, and the snippet is scrubbed of configured secrets before it is + // logged. if len(errBody) > 0 { - redactor := config.NewSecretRedactor() + redactor := config.SecretRedactor() redactor.Replace(g.cfg) snippet := redactor.String(string(errBody)) if len(snippet) > 240 { @@ -191,6 +210,15 @@ func stripStaleReasoningInputs(route models.Route, bodies map[config.Tier][]byte return out, changed } +// doUpstreamTiers runs one routing pass and reports the response, the route +// that produced it, and the attempt count so far (attemptOffset plus the +// attempts made here). A debug key override short-circuits to that single key +// and reports only its own attempt, without attemptOffset. Otherwise an +// anonymous route first tries the free tier, then every tier in +// route.KeyTiers order (a keyed Zen or Go route without KeyTiers uses its own +// tier) until one returns 2xx. Without a success it returns the last HTTP +// response, whose body is still open, in preference to the last error. Once +// ctx is done it no longer enters the key tiers. func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, models.Route, int, error) { var lastResponse *http.Response var lastErr error @@ -262,12 +290,17 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie return nil, effectiveRoute, attempts, lastErr } -// doAnonymousUpstream tries every currently available proxy at most once. For -// each proxy it prefers the legacy /zen/v1 lane (LegacyZenBase) before falling -// back to the newer /inference upstream (Upstream.Anonymous). Any failure, -// 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. +// doAnonymousUpstream walks the session's anonymous proxy cursor. Each static +// proxy is tried at most once; rotating #pool proxies may be drawn again until +// Retry.MaxAttempts proxies were used. For each proxy it tries the upstreams in +// anonymousUpstreams order: the v1 lane (models.V1Base) before the v2 +// /inference upstream (Upstream.Anonymous). Any failure, including an HTTP +// error response, advances to the next upstream or proxy; a proxy-route +// failure, or a proxy marked unhealthy, skips that proxy's remaining +// upstreams. Only a successful response ends the anonymous phase; exhausting +// the proxy cursor returns control to the preferred authenticated tiers. It +// returns the last response (body still open), else the last error, plus the +// number of attempts made. 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 lastErr error @@ -284,15 +317,16 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b } // The anonymous free tier only serves agent-shaped streaming requests // carrying the required tool definitions (anything else is rejected with 403 - // FreeTierError). Normalize the wire body per upstream gate (legacy /zen/v1 - // vs /inference); the gateway collapses the stream back when the downstream - // client asked for a plain JSON reply. Key tiers keep their original bodies. + // FreeTierError). Normalize the wire body per upstream gate (v1 /zen vs v2 + // /inference); the gateway collapses the stream back when the downstream + // client asked for a plain JSON reply. Key tiers shape their own bodies + // (see shapeKeyBody). protocol := route.ProtocolFor(config.TierZen) upstreams := g.anonymousUpstreams() preparedBodies := make([][]byte, len(upstreams)) toolAliases := make([]string, len(upstreams)) for i, baseURL := range upstreams { - preparedBodies[i], toolAliases[i] = prepareAnonymousBody(rawBody, protocol, isLegacyZenUpstream(baseURL)) + preparedBodies[i], toolAliases[i] = prepareAnonymousBody(rawBody, protocol, models.IsV1Upstream(baseURL)) } for proxies < limit { if ctx.Err() != nil { @@ -328,7 +362,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b httpx.DrainAndClose(lastResponse.Body) lastResponse = nil } - req, err := newUpstreamRequest(ctx, baseURL, protocol, preparedBodies[index], ids, anonymousZenKey) + req, err := upstreamRequest(ctx, baseURL, protocol, preparedBodies[index], ids, anonymousZenKey) if err != nil { return nil, err, attempts } @@ -387,45 +421,37 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b return nil, lastErr, attempts } -// anonymousUpstreams returns the ordered base URLs for the keyless free-tier -// lane: the legacy /zen/v1 origin (models.LegacyZenBase) is tried first, and -// the configured /inference origin (Upstream.Anonymous) is kept as a fallback. +// anonymousUpstreams returns the ordered base URLs for the keyless free tier: +// the v1 origin (models.V1Base) is tried first, and the configured v2 +// /inference origin (Upstream.Anonymous) is kept as a fallback. Only the v1 +// origin is returned when Upstream.Anonymous is empty or names that same +// origin. func (g *Gateway) anonymousUpstreams() []string { - legacy := strings.TrimRight(models.LegacyZenBase, "/") + v1 := strings.TrimRight(models.V1Base, "/") primary := strings.TrimRight(g.cfg.Upstream.Anonymous, "/") - if primary == "" || strings.EqualFold(legacy, primary) { - return []string{models.LegacyZenBase} + if primary == "" || strings.EqualFold(v1, primary) { + return []string{models.V1Base} } - return []string{models.LegacyZenBase, g.cfg.Upstream.Anonymous} + return []string{models.V1Base, 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") -} - -// legacyAnonymousReadTool is the single tool name required by the legacy -// /zen/v1 free-tier gate. Unlike /inference, the /zen/v1 gate does not require -// a shell/edit/glob/grep toolset and does not validate tool descriptions or +// v1ReadTool is the single tool name required by the v1 free-tier gate +// (/zen). Unlike the v2 /inference gate, it does not require a +// shell/edit/glob/grep toolset and does not validate tool descriptions or // parameter schemas: a single tool named "read" is sufficient. -const legacyAnonymousReadTool = "read" +const v1ReadTool = "read" -// legacyDeprecatedReadDescription is attached when the gateway must inject a -// placeholder "read" tool on the legacy /zen/v1 lane because the client -// request declared no read-related tool of its own. It explicitly tells the -// model that the tool is deprecated and must never be invoked. -const legacyDeprecatedReadDescription = "DEPRECATED: This tool is deprecated and disabled. Do NOT call or reference this tool under any circumstances; ignore it completely." +// v1DeprecatedReadDescription is attached when the gateway must inject a +// placeholder "read" tool on the v1 lane (/zen) because the client request +// declared no read-related tool of its own. It explicitly tells the model that +// the tool is deprecated and must never be invoked. +const v1DeprecatedReadDescription = "DEPRECATED: This tool is deprecated and disabled. Do NOT call or reference this tool under any circumstances; ignore it completely." -// 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 +// v2CoreTools are the tool names the v2 /inference free-tier gate expects on +// an agent-shaped request. Requests without a shell tool and a read tool are // 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 v1 client's "bash" spelling is // deliberately not injected on /inference because that gate validates the // definition of every tool it recognises, and a "bash" definition the gateway // synthesises does not match the one upstream expects. Since 2026-10-14 name @@ -434,19 +460,20 @@ const legacyDeprecatedReadDescription = "DEPRECATED: This tool is deprecated and // 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"} +var v2CoreTools = []string{"shell", "edit", "glob", "grep", "read"} // opencodeToolsJSON holds the genuine OpenCode tool definitions (description // and JSON schema) captured from the official client. The /inference free-tier // gate checks the definition of every tool whose name it recognises, so a // synthesised stub — even one carrying the right name — is rejected with 403 -// FreeTierError. The gateway therefore ships the real definitions for the -// /inference lane and uses them both for the tools it injects and for any -// same-named tool the downstream client declared. +// FreeTierError. The gateway therefore ships the real definitions for the v2 +// lane and uses them both for the tools it injects and for any same-named tool +// the downstream client declared. // //go:embed opencode_tools.json var opencodeToolsJSON []byte +// opencodeToolDefinition is one entry of opencode_tools.json. type opencodeToolDefinition struct { Description string `json:"description"` Parameters map[string]any `json:"parameters"` @@ -458,6 +485,7 @@ var ( ) // knownOpencodeTool returns the genuine definition for an OpenCode tool name. +// The embedded JSON is decoded once; if it fails to decode, no tool is known. func knownOpencodeTool(name string) (opencodeToolDefinition, bool) { opencodeToolsOnce.Do(func() { definitions := map[string]opencodeToolDefinition{} @@ -470,21 +498,22 @@ func knownOpencodeTool(name string) (opencodeToolDefinition, bool) { return definition, ok } -// prepareAnonymousBody returns a copy of body normalized for the anonymous -// free tier alongside any original client tool name that was aliased to "read" -// for the legacy /zen/v1 gate. +// prepareAnonymousBody returns body normalized for the free tier alongside any +// original client tool name that was aliased to "read" for the v1 gate. The +// body is forced to stream (keeping Chat usage reporting on) and its tools are +// shaped for the lane v1 selects; an unchanged body is returned as is. // -// On the legacy /zen/v1 gate (legacy == true), pre-injection of other tools is -// dropped: if the client declared a read-related tool (case-insensitive, e.g. -// "reAd", "Read_file", "readFile"), it is renamed in-place to "read" while -// keeping its original description and parameters, and its original name is -// returned so the gateway can restore it in the downstream response; if no -// read-related tool is present, a single deprecated "read" stub is injected. +// On the v1 gate (v1 == true), none of the v2 core tools are injected: if the +// client declared a read-related tool (case-insensitive, e.g. "reAd", +// "Read_file", "readFile"), it is renamed in-place to "read" while keeping its +// original description and parameters, and its original name is returned so +// the gateway can restore it in the downstream response; if no read-related +// tool is present, a single deprecated "read" stub is injected. // -// On the /inference gate (legacy == false), anonymousCoreTools with genuine -// CLI 2.x definitions are ensured. System One payloads are decision requests, -// not agent traffic, so they are forwarded verbatim. -func prepareAnonymousBody(body []byte, protocol wire.Protocol, legacy bool) ([]byte, string) { +// On a v2 gate (v1 == false), v2CoreTools with genuine CLI 2.x definitions are +// ensured. System One payloads are decision requests, not agent traffic, so +// they are forwarded verbatim, as is a body that is not a JSON object. +func prepareAnonymousBody(body []byte, protocol wire.Protocol, v1 bool) ([]byte, string) { if protocol == wire.SystemOne { return body, "" } @@ -501,13 +530,13 @@ func prepareAnonymousBody(body []byte, protocol wire.Protocol, legacy bool) ([]b changed = true } var alias string - if legacy { + if v1 { var toolChanged bool - alias, toolChanged = ensureLegacyAnonymousReadTool(payload, protocol) + alias, toolChanged = ensureV1ReadTool(payload, protocol) if toolChanged { changed = true } - } else if ensureAnonymousTools(payload, protocol) { + } else if ensureV2Tools(payload, protocol) { changed = true } if !changed { @@ -524,7 +553,8 @@ func prepareAnonymousBody(body []byte, protocol wire.Protocol, legacy bool) ([]b // ensureAnonymousChatUsage keeps token usage available when a non-streaming // request is forced onto the Chat SSE path. OpenAI-compatible Chat streams -// require stream_options.include_usage for the final usage event. +// require stream_options.include_usage for the final usage event. It reports +// whether the payload changed. func ensureAnonymousChatUsage(payload map[string]any, protocol wire.Protocol) bool { if protocol != wire.Chat { return false @@ -542,8 +572,8 @@ func ensureAnonymousChatUsage(payload map[string]any, protocol wire.Protocol) bo return true } -// ensureLegacyAnonymousReadTool satisfies the legacy /zen/v1 free-tier gate -// using only the single "read" tool requirement: +// ensureV1ReadTool satisfies the v1 free-tier gate (/zen) using only the +// single "read" tool requirement: // 1. If the client already has an exact "read" tool, nothing is injected or // renamed. // 2. If the client has a read-related tool (case-insensitive match such as @@ -551,13 +581,17 @@ func ensureAnonymousChatUsage(payload map[string]any, protocol wire.Protocol) bo // (preserving its client description and schema), any matching tool_choice // or historical tool call in the request is rewritten to "read", and the // client's original tool name is returned so responses can be restored. +// A case-insensitive "read" is preferred over other read-related names. // 3. If the client has no read-related tool at all, a single "read" stub tool // is appended with a deprecated/ignore description so the model never // invokes it. -func ensureLegacyAnonymousReadTool(payload map[string]any, protocol wire.Protocol) (string, bool) { +// +// It also reports whether the payload changed. A "tools" value that is not an +// array is left untouched. +func ensureV1ReadTool(payload map[string]any, protocol wire.Protocol) (string, bool) { raw, exists := payload["tools"] if !exists { - payload["tools"] = []any{legacyDeprecatedReadTool(protocol)} + payload["tools"] = []any{v1DeprecatedReadTool(protocol)} return "", true } items, ok := raw.([]any) @@ -571,34 +605,34 @@ func ensureLegacyAnonymousReadTool(payload map[string]any, protocol wire.Protoco if name == "" { continue } - if name == legacyAnonymousReadTool { + if name == v1ReadTool { return "", false } - if strings.EqualFold(name, legacyAnonymousReadTool) { + if strings.EqualFold(name, v1ReadTool) { candidateIndex = index candidateName = name break } - if candidateIndex < 0 && isLegacyReadToolCandidate(name) { + if candidateIndex < 0 && isV1ReadToolCandidate(name) { candidateIndex = index candidateName = name } } if candidateIndex >= 0 { - setAnonymousToolName(protocol, items[candidateIndex], legacyAnonymousReadTool) - rewriteLegacyRequestToolReferences(payload, protocol, candidateName, legacyAnonymousReadTool) + setAnonymousToolName(protocol, items[candidateIndex], v1ReadTool) + rewriteV1ToolReferences(payload, protocol, candidateName, v1ReadTool) payload["tools"] = items return candidateName, true } - items = append(items, legacyDeprecatedReadTool(protocol)) + items = append(items, v1DeprecatedReadTool(protocol)) payload["tools"] = items return "", true } -// isLegacyReadToolCandidate reports whether a client tool name represents a +// isV1ReadToolCandidate reports whether a client tool name represents a // read-related tool (case-insensitive), such as "reAd", "read_file", // "ReadFile", "file_read", or "view_file". -func isLegacyReadToolCandidate(name string) bool { +func isV1ReadToolCandidate(name string) bool { lower := strings.ToLower(strings.TrimSpace(name)) if lower == "" { return false @@ -631,10 +665,10 @@ func setAnonymousToolName(protocol wire.Protocol, item any, name string) { entry["name"] = name } -// rewriteLegacyRequestToolReferences renames any named tool_choice and +// rewriteV1ToolReferences renames any named tool_choice and // assistant tool-call history entries from fromName to toName so the outbound // request stays self-consistent after a client read tool is aliased to "read". -func rewriteLegacyRequestToolReferences(payload map[string]any, protocol wire.Protocol, fromName, toName string) { +func rewriteV1ToolReferences(payload map[string]any, protocol wire.Protocol, fromName, toName string) { if fromName == "" || fromName == toName { return } @@ -680,46 +714,47 @@ func rewriteLegacyRequestToolReferences(payload map[string]any, protocol wire.Pr } } -// legacyDeprecatedReadTool builds the single placeholder "read" tool injected -// on the legacy /zen/v1 lane when the client request has no read-related tool -// of its own. Its description marks the tool as deprecated and instructs the -// model to ignore it completely. -func legacyDeprecatedReadTool(protocol wire.Protocol) map[string]any { +// v1DeprecatedReadTool builds the single placeholder "read" tool injected on +// the v1 lane (/zen) when the client request has no read-related tool of its +// own, in the wire shape of protocol. Its description marks the tool as +// deprecated and instructs the model to ignore it completely. +func v1DeprecatedReadTool(protocol wire.Protocol) map[string]any { parameters := map[string]any{"type": "object", "properties": map[string]any{}} switch protocol { case wire.Chat: return map[string]any{ "type": "function", "function": map[string]any{ - "name": legacyAnonymousReadTool, - "description": legacyDeprecatedReadDescription, + "name": v1ReadTool, + "description": v1DeprecatedReadDescription, "parameters": parameters, }, } case wire.Anthropic: return map[string]any{ - "name": legacyAnonymousReadTool, - "description": legacyDeprecatedReadDescription, + "name": v1ReadTool, + "description": v1DeprecatedReadDescription, "input_schema": parameters, } default: return map[string]any{ "type": "function", - "name": legacyAnonymousReadTool, - "description": legacyDeprecatedReadDescription, + "name": v1ReadTool, + "description": v1DeprecatedReadDescription, "parameters": parameters, } } } -// ensureAnonymousTools makes the tool list read as an OpenCode 2.x agent -// session on the /inference gate: every recognised OpenCode tool carries its -// genuine CLI 2.x definition and missing core tools are appended with genuine -// schemas; unrecognised client tools are left untouched. -func ensureAnonymousTools(payload map[string]any, protocol wire.Protocol) bool { +// ensureV2Tools makes the tool list read as an OpenCode 2.x agent session on +// a v2 gate: every recognised OpenCode tool carries its genuine CLI 2.x +// definition and missing core tools are appended with genuine schemas; +// unrecognised client tools are left untouched. It reports whether the payload +// changed; a "tools" value that is not an array is left untouched. +func ensureV2Tools(payload map[string]any, protocol wire.Protocol) bool { raw, exists := payload["tools"] if !exists { - payload["tools"] = anonymousToolset(protocol, anonymousCoreTools) + payload["tools"] = v2Toolset(protocol, v2CoreTools) return true } items, ok := raw.([]any) @@ -735,18 +770,18 @@ func ensureAnonymousTools(payload map[string]any, protocol wire.Protocol) bool { } present[name] = true if _, known := knownOpencodeTool(name); known { - items[index] = anonymousTool(protocol, name) + items[index] = v2Tool(protocol, name) changed = true } } - missing := make([]string, 0, len(anonymousCoreTools)) - for _, name := range anonymousCoreTools { + missing := make([]string, 0, len(v2CoreTools)) + for _, name := range v2CoreTools { if !present[name] { missing = append(missing, name) } } if len(missing) > 0 { - items = append(items, anonymousToolset(protocol, missing)...) + items = append(items, v2Toolset(protocol, missing)...) changed = true } if !changed { @@ -756,6 +791,8 @@ func ensureAnonymousTools(payload map[string]any, protocol wire.Protocol) bool { return true } +// anonymousToolName returns the name of a tool definition in the wire shape +// of protocol (function.name on Chat, name elsewhere), or "" when it has none. func anonymousToolName(protocol wire.Protocol, item any) string { entry, ok := item.(map[string]any) if !ok { @@ -767,26 +804,27 @@ func anonymousToolName(protocol wire.Protocol, item any) string { return jsonutil.StringAt(entry, "name") } -// anonymousToolset returns the wire-shaped genuine CLI 2.x definitions for the -// given tool names on the /inference gate. -func anonymousToolset(protocol wire.Protocol, names []string) []any { +// v2Toolset returns the wire-shaped genuine CLI 2.x definitions for the given +// tool names on a v2 gate. A nil names selects every v2CoreTools entry. +func v2Toolset(protocol wire.Protocol, names []string) []any { if names == nil { - names = anonymousCoreTools + names = v2CoreTools } tools := make([]any, 0, len(names)) for _, name := range names { - if tool := anonymousTool(protocol, name); tool != nil { + if tool := v2Tool(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 CLI 2.x definition whenever one is known. -// SystemOne payloads never reach this path (prepareAnonymousBody forwards them +// v2Tool renders one tool in the shape the given protocol expects, using the +// genuine OpenCode CLI 2.x definition whenever one is known and an "Agent tool +// " placeholder with an empty object schema otherwise. SystemOne +// payloads never reach this path (prepareAnonymousBody forwards them // verbatim), so it falls back to the Responses/default shape. -func anonymousTool(protocol wire.Protocol, name string) map[string]any { +func v2Tool(protocol wire.Protocol, name string) map[string]any { description := "Agent tool " + name parameters := map[string]any{"type": "object", "properties": map[string]any{}} if definition, ok := knownOpencodeTool(name); ok { @@ -863,12 +901,12 @@ func (g *Gateway) dumpOutboundBodies(route models.Route, bodies map[config.Tier] } // shapeKeyBody normalizes key-tier free-model wire bodies to agent shape -// (stream + required tools), mirroring the anonymous lane. Upstream now -// rejects non-agent-shaped free-tier requests on every lane with 403 -// FreeTierError; paid models keep their original bodies. It reports the -// shaped body, any legacy "read" tool alias that must be restored in the -// response, and whether the body changed so the gateway can collapse the SSE -// stream a non-streaming client receives back. +// (stream + required tools), mirroring the anonymous lane; the tier's base URL +// decides between v1 and v2 shaping. Upstream now rejects non-agent-shaped +// free-tier requests on every lane with 403 FreeTierError; paid models keep +// their original bodies. It reports the shaped body, any v1 "read" tool alias +// that must be restored in the response, and whether the body changed so the +// gateway can collapse the SSE stream a non-streaming client receives back. func (g *Gateway) shapeKeyBody(body []byte, route models.Route, tier config.Tier) ([]byte, string, bool) { if !g.catalog.IsFreeModel(route.ID) { return body, "", false @@ -877,15 +915,17 @@ func (g *Gateway) shapeKeyBody(body []byte, route models.Route, tier config.Tier if tier == config.TierGo { baseURL = g.cfg.Upstream.Go } - shaped, alias := prepareAnonymousBody(body, route.ProtocolFor(tier), isLegacyZenUpstream(baseURL)) + shaped, alias := prepareAnonymousBody(body, route.ProtocolFor(tier), models.IsV1Upstream(baseURL)) return shaped, alias, !bytes.Equal(shaped, body) } +// doSelectedKeyUpstream sends exactly one attempt through the operator-selected // key. It performs no failover at all — no anonymous lane, no other key and no // other tier — so the outcome describes that one key. It also leaves pool state // untouched on purpose: a diagnostic request must never cool a production key or // evict a proxy, which is exactly what made a bad Playground request degrade -// live traffic before. +// live traffic before. The attempt is still recorded in telemetry, and any HTTP +// response, whatever its status, is returned as is. func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, override DebugKeyOverride, attemptOffset int) (*http.Response, error, int) { nodes := g.zenNodes baseURL := g.cfg.Upstream.Zen @@ -919,7 +959,7 @@ func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route, } keyID := config.KeyDisplayID(node.key) setRequestCredential(ctx, override.Tier, keyID, "key", false, proxy) - req, err := newUpstreamRequest(ctx, baseURL, route.ProtocolFor(override.Tier), body, ids, node.key) + req, err := upstreamRequest(ctx, baseURL, route.ProtocolFor(override.Tier), body, ids, node.key) if err != nil { return nil, err, 0 } @@ -936,6 +976,17 @@ func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route, return resp, nil, 1 } +// doKeyUpstream rotates through the keys of route.Tier, starting from the +// session's affinity key, for at most Retry.MaxAttempts attempts; free-model +// bodies are shaped first (see shapeKeyBody). Every attempt is fed to +// observeKeyResult, which may cool the key or evict its proxy on failure. A +// 2xx ends the loop, and so does a non-retryable 4xx (see +// isNonRetryableClientResponse), which is returned as is so the caller can +// move on to the next tier; after any other response or transport error the +// next key is tried. An attempt that finishes after ctx is done ends the loop +// without being held against the key or the proxy. It returns the last +// response (body still open), else the last error, plus the number of +// attempts made. func (g *Gateway) doKeyUpstream(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 lastErr error @@ -986,7 +1037,7 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies httpx.DrainAndClose(lastResponse.Body) lastResponse = nil } - req, err := newUpstreamRequest(ctx, baseURL, route.Protocol, body, ids, node.key) + req, err := upstreamRequest(ctx, baseURL, route.Protocol, body, ids, node.key) if err != nil { return nil, err, attempts } @@ -1005,7 +1056,7 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies attemptDuration := time.Since(attemptStarted) if ctx.Err() != nil { // The request budget expired while this attempt was in flight. A - // cancelled context says nothing about the key or the proxy: without + // canceled context says nothing about the key or the proxy: without // this guard the instant DeadlineExceeded would cool a healthy key // and evict a healthy proxy from the pool. lastResponse, lastErr = resp, err @@ -1042,9 +1093,14 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies return nil, lastErr, attempts } -// Diagnostics use the same routing and transports as production, but must not -// update cooldowns, health, or bindings, including after successful attempts. -func (g *Gateway) observeKeyResult(ctx context.Context, nodes *nodePool, node *upstreamNode, proxy *proxyTransport, resp *http.Response, err error) { +// observeKeyResult feeds the outcome of one key attempt back into proxy health +// (syncProxyResult) and the key's cooldown. Diagnostics use the same routing +// and transports as production, but must not update cooldowns, health, or +// bindings, including after successful attempts. A 2xx or non-retryable 4xx +// clears the key's cooldown. Other outcomes go to MarkFailure, which cools the +// key, unless the proxy route itself failed and the key has already been +// rebound to another proxy. +func (g *Gateway) observeKeyResult(ctx context.Context, nodes *upstreamNodes, node *upstreamNode, proxy *proxyTransport, resp *http.Response, err error) { if isDiagnosticRequest(ctx) { return } @@ -1059,6 +1115,9 @@ func (g *Gateway) observeKeyResult(ctx context.Context, nodes *nodePool, node *u } } +// observeAnonymousResult is the anonymous counterpart of observeKeyResult: it +// syncs the proxy's health and clears or extends the anonymous node's +// per-proxy cooldown, except for diagnostic requests. func (g *Gateway) observeAnonymousResult(ctx context.Context, node *anonymousNode, resp *http.Response, err error) { if isDiagnosticRequest(ctx) { return @@ -1079,6 +1138,9 @@ func upstreamStatus(resp *http.Response) int { return resp.StatusCode } +// setRequestCredential records the credential and proxy of the attempt about +// to be sent on the request's telemetry meta, with the proxy URL redacted. It +// is a no-op when ctx carries no meta. func setRequestCredential(ctx context.Context, tier config.Tier, keyID, channel string, anonymous bool, proxy *proxyTransport) { meta := telemetry.MetaFromContext(ctx) if meta == nil { @@ -1102,6 +1164,9 @@ func requestCredential(ctx context.Context) (string, string, bool) { return meta.KeyID, meta.Channel, meta.Anonymous } +// recordUpstreamAttempt classifies one finished attempt (success, rejected, +// retryable_failure or transport_error), appends its leg to the request's +// telemetry meta and reports it to the metrics monitor when one is configured. func (g *Gateway) recordUpstreamAttempt(ctx context.Context, route models.Route, ids identity.RequestIDs, attempt int, keyID, channel string, anonymous bool, proxy *proxyTransport, resp *http.Response, err error, duration time.Duration) { status := upstreamStatus(resp) success := err == nil && status >= 200 && status < 300 @@ -1116,9 +1181,9 @@ func (g *Gateway) recordUpstreamAttempt(ctx context.Context, route models.Route, if meta := telemetry.MetaFromContext(ctx); meta != nil { meta.AttemptOutcome = outcome meta.Protocol = route.Protocol - // Append a per-attempt leg (key:status:ms, anonymized for the - // public lane) so the request log shows the whole attempt chain - // at a glance. Only the redacted key suffix is retained. + // Append a per-attempt leg (key:status:ms, with "anon" as the key + // on the anonymous lane) so the request log shows the whole attempt + // chain at a glance. Only the redacted key suffix is retained. label := keyID if anonymous { label = "anon" @@ -1146,42 +1211,26 @@ func (g *Gateway) recordUpstreamAttempt(ctx context.Context, route models.Route, }) } -func newUpstreamRequest(ctx context.Context, baseURL string, protocol wire.Protocol, body []byte, ids identity.RequestIDs, key string) (*http.Request, error) { +// upstreamRequest builds the POST for one attempt: baseURL plus the protocol's +// /v1/... route, carrying body. The header set follows the lane: setV1Headers +// when models.IsV1Upstream(baseURL), setV2Headers otherwise. key is sent as +// x-api-key (with anthropic-version) on the Anthropic protocol and as a Bearer +// token on every other one; the anonymous lane passes anonymousZenKey. +func upstreamRequest(ctx context.Context, baseURL string, protocol wire.Protocol, body []byte, ids identity.RequestIDs, key string) (*http.Request, error) { endpoint := strings.TrimRight(baseURL, "/") + wire.Path(protocol) req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body)) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/json") - req.Header.Set("Accept", "application/json, text/event-stream") - req.Header.Set("x-opencode-client", "cli") - req.Header.Set("x-opencode-session", ids.Session) - req.Header.Set("x-session-affinity", ids.Session) - req.Header.Set("X-Session-Id", ids.Session) - if isLegacyZenUpstream(baseURL) { - // The legacy /zen/v1 origin uses the pre-2.x OpenCode 1.18.x request - // shape from v1.3.7: the legacy User-Agent, x-opencode-request, and a - // canonical prj_* project id. - req.Header.Set("User-Agent", httpx.LegacyUserAgent()) - req.Header.Set("x-opencode-request", ids.Request) - req.Header.Set("x-opencode-project", legacyProjectID(ids.Project)) + if models.IsV1Upstream(baseURL) { + setV1Headers(req.Header, protocol, body, ids) } else { - // The newer /inference gate fingerprints the 2.x CLI header set: it - // wants the "opencode///cli" User-Agent, both - // session headers set to the same descending-encoded id, and a bare - // 40-character hex x-opencode-project, and it rejects x-opencode-request - // and canonical prj_* project ids with 403 FreeTierError. - req.Header.Set("User-Agent", httpx.UserAgent()) - req.Header.Set("x-opencode-session-id", ids.Session) - req.Header.Set("x-opencode-project", clientProjectID(ids.Project)) - } - if ids.ParentSession != "" { - req.Header.Set("x-parent-session-id", ids.ParentSession) + setV2Headers(req.Header, protocol, ids) } if protocol == wire.Anthropic { req.Header.Set("x-api-key", key) 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 @@ -1191,26 +1240,247 @@ func newUpstreamRequest(ctx context.Context, baseURL string, protocol wire.Proto return req, nil } -// legacyProjectID renders the project header in the v1.3.7 canonical -// "prj_<24hex>" shape expected by the pre-2.x /zen/v1 origin, preserving an -// already-prefixed prj_* value verbatim. -func legacyProjectID(project string) string { - if strings.HasPrefix(project, "prj_") { - return project +// setV1Headers renders the v1 lane's header set, that of an OpenCode 1.19.3 +// model request on its opencode provider, as captured from the official +// release: the AI SDK User-Agent of the package serving the protocol, both +// session headers, the user message id as x-opencode-request (a fresh +// ascending msg_ id when none was derived), the git root commit as the +// project, the canonical parent session under both parent headers, and only +// the anthropic-beta flags the AI SDK derives from the body. The v1 client +// sends no x-session-affinity or X-Session-Id to this provider. +func setV1Headers(header http.Header, protocol wire.Protocol, body []byte, ids identity.RequestIDs) { + header.Set("Accept", "*/*") + header.Set("User-Agent", httpx.V1ModelUserAgent(v1ProviderUtils(protocol))) + header.Set("x-opencode-client", "cli") + header.Set("x-opencode-session", ids.Session) + header.Set("x-opencode-session-id", ids.Session) + message := ids.Message + if message == "" { + message = identity.AscendingID("msg", time.Now()) + } + header.Set("x-opencode-request", message) + header.Set("x-opencode-project", v1ProjectID(ids.Project)) + if ids.ParentSession != "" { + parent := identity.CanonicalSessionID(ids.ParentSession) + header.Set("x-opencode-parent-session-id", parent) + header.Set("x-parent-session-id", parent) + } + if protocol == wire.Anthropic { + if betas := v1AnthropicBetas(body); betas != "" { + header.Set("anthropic-beta", betas) + } } - return identity.StableID("prj", project) } -// clientProjectID renders the project header the way the 2.x CLI does for the -// /inference gate: a bare 40-character lowercase hex id rather than the -// gateway's "prj_" prefixed stable id. The value itself is not checked -// upstream, only its shape, but hashing keeps one conversation pinned to one -// project. -func clientProjectID(project string) string { +// setV2Headers renders the OpenCode 2.x CLI header set the v2 gates +// fingerprint: the "opencode///cli" User-Agent, every +// session header (x-opencode-session, x-opencode-session-id, +// x-session-affinity, X-Session-Id) set to the same descending-encoded id, +// and a bare 40-character hex x-opencode-project. The v2 gate rejects +// x-opencode-request and canonical prj_* project ids with 403 FreeTierError, +// so neither is sent. Anthropic requests carry a fixed anthropic-beta set. +func setV2Headers(header http.Header, protocol wire.Protocol, ids identity.RequestIDs) { + header.Set("Accept", "application/json, text/event-stream") + header.Set("x-opencode-client", "cli") + header.Set("x-opencode-session", ids.Session) + header.Set("x-session-affinity", ids.Session) + header.Set("X-Session-Id", ids.Session) + header.Set("User-Agent", httpx.V2UserAgent()) + header.Set("x-opencode-session-id", ids.Session) + header.Set("x-opencode-project", v2ProjectID(ids.Project)) + if ids.ParentSession != "" { + header.Set("x-parent-session-id", ids.ParentSession) + } + if protocol == wire.Anthropic { + header.Set("anthropic-beta", "interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14") + } +} + +// v1ProviderUtils names the provider-utils version of the AI SDK package the +// OpenCode 1.x client routes a protocol through, for the v1 User-Agent. System +// One has no v1 counterpart and reports the chat package. +func v1ProviderUtils(protocol wire.Protocol) string { + switch protocol { + case wire.Responses: + return httpx.V1ResponsesSDK + case wire.Anthropic: + return httpx.V1AnthropicSDK + default: + return httpx.V1ChatSDK + } +} + +// gitCommitPattern matches the git root commit hash OpenCode 1.x uses as its +// project id. +var gitCommitPattern = regexp.MustCompile(`^[0-9a-f]{40}$`) + +// v1ProjectID renders the project header the way the OpenCode 1.x client +// does: the git root commit hash of the project, or "global" outside a git +// repository. A genuine value from a v1 client is kept verbatim; any other +// project is hashed into the commit shape (see v2ProjectID). +func v1ProjectID(project string) string { + if project == "global" || gitCommitPattern.MatchString(project) { + return project + } + return v2ProjectID(project) +} + +// v1AnthropicBetaRequest holds the Messages body fields the AI SDK +// anthropic provider derives beta flags from. Fields whose JSON type varies +// stay raw so one unexpected value cannot hide the others. +type v1AnthropicBetaRequest struct { + Model string `json:"model"` + MCPServers []json.RawMessage `json:"mcp_servers"` + ContextManagement *struct { + Edits []struct { + Type string `json:"type"` + } `json:"edits"` + } `json:"context_management"` + Container json.RawMessage `json:"container"` + OutputConfig struct { + TaskBudget json.RawMessage `json:"task_budget"` + } `json:"output_config"` + Speed json.RawMessage `json:"speed"` + Fallbacks json.RawMessage `json:"fallbacks"` + Thinking struct { + BlockBinding json.RawMessage `json:"block_binding"` + } `json:"thinking"` + Tools []struct { + Type string `json:"type"` + InputExamples json.RawMessage `json:"input_examples"` + AllowedCallers json.RawMessage `json:"allowed_callers"` + } `json:"tools"` +} + +// v1AnthropicToolBetas maps the server tool types of a Messages body to the +// beta flag the AI SDK anthropic provider sends with each. +var v1AnthropicToolBetas = map[string]string{ + "code_execution_20250522": "code-execution-2025-05-22", + "code_execution_20250825": "code-execution-2025-08-25", + "computer_20241022": "computer-use-2024-10-22", + "computer_20250124": "computer-use-2025-01-24", + "computer_20251124": "computer-use-2025-11-24", + "text_editor_20241022": "computer-use-2024-10-22", + "text_editor_20250124": "computer-use-2025-01-24", + "text_editor_20250429": "computer-use-2025-01-24", + "bash_20241022": "computer-use-2024-10-22", + "bash_20250124": "computer-use-2025-01-24", + "memory_20250818": "context-management-2025-06-27", + "web_fetch_20250910": "web-fetch-2025-09-10", + "web_fetch_20260209": "code-execution-web-tools-2026-02-09", + "web_search_20260209": "code-execution-web-tools-2026-02-09", + "advisor_20260301": "advisor-tool-2026-03-01", +} + +// v1AnthropicBetas returns the anthropic-beta value OpenCode 1.19.3 sends +// with a Messages body on the v1 lane, or "" when no flag applies. Its +// opencode provider sets no fixed betas: the AI SDK derives them from the +// request features (body features first, then tools, in the SDK's order), and +// per-tool eager_input_streaming has replaced the old +// fine-grained-tool-streaming flag. +func v1AnthropicBetas(body []byte) string { + var request v1AnthropicBetaRequest + // A field of an unexpected type fails alone; the rest still decode. + _ = json.Unmarshal(body, &request) + var betas []string + add := func(beta string) { + if !slices.Contains(betas, beta) { + betas = append(betas, beta) + } + } + if len(request.MCPServers) > 0 { + add("mcp-client-2025-04-04") + } + if request.ContextManagement != nil { + add("context-management-2025-06-27") + for _, edit := range request.ContextManagement.Edits { + if edit.Type == "compact_20260112" { + add("compact-2026-01-12") + } + } + } + var container struct { + Skills []json.RawMessage `json:"skills"` + } + if json.Unmarshal(request.Container, &container) == nil && len(container.Skills) > 0 { + add("code-execution-2025-08-25") + add("skills-2025-10-02") + add("files-api-2025-04-14") + } + if isPresentJSON(request.OutputConfig.TaskBudget) { + add("task-budgets-2026-03-13") + } + if string(request.Speed) == `"fast"` { + add("fast-mode-2026-02-01") + } + var fallbacks []json.RawMessage + if string(request.Fallbacks) == `"default"` { + add("server-side-fallback-2026-07-01") + } else if json.Unmarshal(request.Fallbacks, &fallbacks) == nil && len(fallbacks) > 0 { + add("server-side-fallback-2026-06-01") + } + if isPresentJSON(request.Thinking.BlockBinding) { + add("thinking-binding-controls-2026-08-01") + } + for _, tool := range request.Tools { + if tool.Type == "" || tool.Type == "custom" { + if anthropicSupportsStructuredOutput(request.Model) { + add("structured-outputs-2025-11-13") + } + if isPresentJSON(tool.InputExamples) || isPresentJSON(tool.AllowedCallers) { + add("advanced-tool-use-2025-11-20") + } + } else if beta := v1AnthropicToolBetas[tool.Type]; beta != "" { + add(beta) + } + } + return strings.Join(betas, ",") +} + +func isPresentJSON(raw json.RawMessage) bool { + return len(raw) > 0 && string(raw) != "null" +} + +// claude3OrOlderPattern matches the Claude model families older than Claude 4 +// (Claude Instant, Claude 2 and every Claude 3.x model) that the AI SDK treats +// as lacking structured output. +var claude3OrOlderPattern = regexp.MustCompile(`claude-(?:instant(?:-|$)|v?2(?:$|[-.:])|3(?:$|[-.]))`) + +// anthropicSupportsStructuredOutput mirrors the AI SDK anthropic provider's +// model capability table, checked in the same order: the dated Claude 4.0 +// releases and Claude 3 and older lack structured output, every other Claude +// model has it, and non-Claude models do not. +func anthropicSupportsStructuredOutput(model string) bool { + for _, supported := range []string{ + "claude-opus-5", "claude-opus-4-8", "claude-opus-4-7", "claude-fable-5", "claude-sonnet-5", + "claude-sonnet-4-6", "claude-opus-4-6", "claude-sonnet-4-5", "claude-opus-4-5", "claude-haiku-4-5", + "claude-opus-4-1", + } { + if strings.Contains(model, supported) { + return true + } + } + if strings.Contains(model, "claude-sonnet-4-") || strings.Contains(model, "claude-opus-4-") || + strings.Contains(model, "claude-3-haiku") || claude3OrOlderPattern.MatchString(model) { + return false + } + return strings.Contains(model, "claude-") +} + +// v2ProjectID renders the project header in the shape the OpenCode 2.x CLI +// sends to the v2 gates: a bare 40-character lowercase hex id, here the first +// 20 bytes of a domain-separated SHA-256 of the project. The value itself is +// not checked upstream, only its shape, but hashing keeps one project mapped +// to one stable upstream project id. v1ProjectID reuses it to fit a +// non-genuine project into the git commit shape. +func v2ProjectID(project string) string { sum := sha256.Sum256([]byte("opencode-project\x00" + project)) return hex.EncodeToString(sum[:20]) } +// isNonRetryableClientResponse reports whether resp is a 4xx that retrying on +// another key of the same tier cannot fix: every 4xx except 401, 403 and 429, +// which can be specific to the key. A transport error is never non-retryable. func isNonRetryableClientResponse(resp *http.Response, err error) bool { return err == nil && resp != nil && resp.StatusCode >= 400 && resp.StatusCode < 500 && resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusTooManyRequests } diff --git a/internal/httpx/body.go b/internal/httpx/body.go index b6f38d3..beebaa3 100644 --- a/internal/httpx/body.go +++ b/internal/httpx/body.go @@ -4,6 +4,10 @@ import ( "io" ) +// DrainAndClose discards up to 64 KiB of body and closes it, so the +// connection can be reused. A nil body is ignored. The bound keeps a small +// response fully drained while a large or endless one cannot hold the caller +// for more than that amount of data. func DrainAndClose(body io.ReadCloser) { if body == nil { return diff --git a/internal/httpx/client.go b/internal/httpx/client.go index 2b397d2..c8aa2b8 100644 --- a/internal/httpx/client.go +++ b/internal/httpx/client.go @@ -1,29 +1,50 @@ package httpx -import ( - "fmt" - "runtime" +// v2ClientVersion is the OpenCode 2.x CLI release the gateway claims to be on +// the v2 lanes (/inference and /zen/go). Upstream accepts a range of releases +// (the version number itself is not validated), so this only needs bumping +// when it starts rejecting older ones. +const v2ClientVersion = "2.0.32" + +// v1ClientVersion is the OpenCode 1.x release the gateway claims to be on the +// v1 lane (/zen), and v1BunVersion is the Bun runtime that release ships with. +// Bump them together with the provider-utils versions below, all taken from a +// captured request of the same release. +const ( + v1ClientVersion = "1.19.3" + v1BunVersion = "1.3.14" ) -// clientVersion is the OpenCode release the gateway claims to be on the -// /inference lane. Upstream 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.32" +// The AI SDK provider packages of OpenCode 1.19.3 each bundle their own +// provider-utils, whose version ends up in the User-Agent of every v1 model +// request, so the version depends on the wire protocol. +const ( + // V1ChatSDK is bundled by @ai-sdk/openai-compatible (chat completions). + V1ChatSDK = "4.0.23" + // V1ResponsesSDK is bundled by @ai-sdk/openai (responses). + V1ResponsesSDK = "4.0.40" + // V1AnthropicSDK is bundled by @ai-sdk/anthropic (messages). + V1AnthropicSDK = "4.0.46" +) -// legacyClientVersion is the pre-2.x OpenCode release reported on the legacy -// /zen/v1 lane, matching the v1.3.7 User-Agent shape. -const legacyClientVersion = "1.18.31" - -// UserAgent reports the gateway as an OpenCode 2.x client using the shape the -// /inference gate expects: "opencode///". -func UserAgent() string { - return "opencode/latest/" + clientVersion + "/cli" +// V2UserAgent reports the gateway as an OpenCode 2.x CLI using the shape the +// v2 gate expects: "opencode///". +func V2UserAgent() string { + return "opencode/latest/" + v2ClientVersion + "/cli" } -// LegacyUserAgent reports the gateway using the v1.3.7 OpenCode 1.18.x -// User-Agent shape ("opencode/ ( ; )") for the -// legacy /zen/v1 lane. -func LegacyUserAgent() string { - return fmt.Sprintf("opencode/%s (%s %s; %s)", legacyClientVersion, runtime.GOOS, runtime.GOARCH, runtime.Version()) +// V1UserAgent is the OpenCode 1.x client's own User-Agent, a bare +// "opencode/", which it sends as-is on requests that bypass the AI +// SDK. The earlier "( ; )" suffix carried the gateway's Go +// runtime, which no real OpenCode client sends. +func V1UserAgent() string { + return "opencode/" + v1ClientVersion +} + +// V1ModelUserAgent is the User-Agent of a v1 model request: the AI SDK appends +// the provider-utils version of the package serving the request and the +// runtime to the client's own User-Agent, e.g. +// "opencode/1.19.3 ai-sdk/provider-utils/4.0.23 runtime/bun/1.3.14". +func V1ModelUserAgent(providerUtils string) string { + return V1UserAgent() + " ai-sdk/provider-utils/" + providerUtils + " runtime/bun/" + v1BunVersion } diff --git a/internal/httpx/response.go b/internal/httpx/response.go index c52e01a..c97583a 100644 --- a/internal/httpx/response.go +++ b/internal/httpx/response.go @@ -7,16 +7,26 @@ import ( "net/http" ) +// WriteJSON writes value as a JSON response with the given status, setting the +// Content-Type header first. func WriteJSON(w http.ResponseWriter, status int, value any) { w.Header().Set("Content-Type", "application/json") WriteJSONStatus(w, status, value) } +// WriteJSONStatus writes value as a JSON body with the given status without +// touching the headers, so a caller can set a Content-Type or Cache-Control of +// its own first. An encoding error cannot be reported: the status is already +// committed, and the body is simply cut short. func WriteJSONStatus(w http.ResponseWriter, status int, value any) { w.WriteHeader(status) _ = json.NewEncoder(w).Encode(value) } +// WriteSSE writes one server-sent event: an optional "id:" line when id is +// positive, an optional "event:" line when event is not empty, and the JSON +// encoding of value as the data. It returns an error only for the data: a +// value that cannot be encoded, or a data line that cannot be written. func WriteSSE(w http.ResponseWriter, event string, id uint64, value any) error { data, err := json.Marshal(value) if err != nil { diff --git a/internal/identity/message.go b/internal/identity/message.go new file mode 100644 index 0000000..82f4b02 --- /dev/null +++ b/internal/identity/message.go @@ -0,0 +1,190 @@ +package identity + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "net/http" + "regexp" + "strconv" + "sync" + "time" + + "opencode2api/internal/jsonutil" +) + +// messageIDPattern matches a user message id minted by the official client's +// Identifier.ascending(): "msg_" + 12 hex time characters + 14 Base62. +var messageIDPattern = regexp.MustCompile(`^msg_[0-9a-f]{12}[0-9A-Za-z]{14}$`) + +// userMessages pins one user message id to each user turn of a session. +var userMessages = &messageStore{turns: map[string]messageEntry{}, latest: map[string]messageEntry{}} + +// UserMessageID returns the user message id the v1 lane receives as +// x-opencode-request, which is the id the OpenCode 1.x client reports there. +// The client mints it when the user sends a message and repeats it on every +// request of that turn (the agent loop's tool steps and the title request), so +// the gateway keeps one id per user turn of a session rather than one per +// request. A genuine id from an official client is kept verbatim. +func UserMessageID(r *http.Request, body map[string]any, session string) string { + if id := r.Header.Get("x-opencode-request"); messageIDPattern.MatchString(id) { + return id + } + return userMessages.idFor(session, userTurn(body), time.Now()) +} + +// userTurn fingerprints the latest turn the user typed: how many user turns the +// conversation holds and what the last one said. Tool results travel as user +// messages on the Anthropic wire, so a user message carrying one belongs to the +// agent loop, not to a new turn. An empty fingerprint means the request +// continues a turn it does not repeat (a stateful Responses continuation). +func userTurn(body map[string]any) string { + if input, ok := body["input"].(string); ok && input != "" { + return turnFingerprint(1, input) + } + count := 0 + var last any + for _, field := range []string{"messages", "input"} { + for _, raw := range jsonutil.SliceAt(body, field) { + item, ok := raw.(map[string]any) + if !ok || jsonutil.StringAt(item, "role") != "user" || carriesToolResult(item["content"]) { + continue + } + count++ + last = item["content"] + } + } + if count == 0 { + return "" + } + return turnFingerprint(count, last) +} + +// turnFingerprint identifies a user turn by its position among the user turns +// of the conversation and the hash of its content. +func turnFingerprint(count int, content any) string { + encoded, _ := json.Marshal(content) + sum := sha256.Sum256(encoded) + return strconv.Itoa(count) + ":" + hex.EncodeToString(sum[:8]) +} + +// carriesToolResult reports whether content is a block list holding a +// tool_result block. +func carriesToolResult(content any) bool { + blocks, ok := content.([]any) + if !ok { + return false + } + for _, raw := range blocks { + if block, ok := raw.(map[string]any); ok && jsonutil.StringAt(block, "type") == "tool_result" { + return true + } + } + return false +} + +// messageTTL bounds how long an idle turn keeps its id, and messageStoreLimit +// how many turns are remembered before idle ones are dropped. +const ( + messageTTL = 6 * time.Hour + messageStoreLimit = 8192 +) + +type messageEntry struct { + id string + seen time.Time +} + +// messageStore remembers the id of every recent user turn, keyed by session +// and turn so interleaved conversations of one session (a client's title +// request beside its agent loop) each keep their own id, plus the latest id of +// each session for requests that carry no user turn of their own. +type messageStore struct { + mu sync.Mutex + turns map[string]messageEntry + latest map[string]messageEntry +} + +// idFor returns the id pinned to the turn of session, minting one when the +// turn is unknown or idle for longer than messageTTL. An empty turn reuses the +// session's latest id and never pins a new turn. +func (s *messageStore) idFor(session, turn string, now time.Time) string { + s.mu.Lock() + defer s.mu.Unlock() + key := session + "\x00" + turn + entry, ok := s.turns[key] + if turn == "" { + entry, ok = s.latest[session] + } + if !ok || now.Sub(entry.seen) > messageTTL { + entry = messageEntry{id: AscendingID("msg", now)} + } + entry.seen = now + if turn != "" { + s.turns[key] = entry + } + s.latest[session] = entry + if len(s.turns) > messageStoreLimit || len(s.latest) > messageStoreLimit { + s.prune(now) + } + return entry.id +} + +// prune drops idle turns, then arbitrary ones if every turn is still live, +// until each map is down to three quarters of messageStoreLimit. +func (s *messageStore) prune(now time.Time) { + for _, entries := range []map[string]messageEntry{s.turns, s.latest} { + for key, entry := range entries { + if now.Sub(entry.seen) > messageTTL { + delete(entries, key) + } + } + for key := range entries { + if len(entries) <= messageStoreLimit*3/4 { + break + } + delete(entries, key) + } + } +} + +// ascendingClock mirrors the official client's Identifier, whose counter +// restarts every millisecond and is shared by every id it mints. +var ascendingClock struct { + sync.Mutex + last int64 + counter int64 +} + +// AscendingID mints an id in the official client's Identifier.ascending() +// layout: prefix + "_" + the low 48 bits of (ms<<12 | counter) as 12 hex +// characters + 14 random Base62 characters. +func AscendingID(prefix string, now time.Time) string { + ms := now.UnixMilli() + ascendingClock.Lock() + if ms != ascendingClock.last { + ascendingClock.last, ascendingClock.counter = ms, 0 + } + ascendingClock.counter++ + value := uint64(ms)<<12 | uint64(ascendingClock.counter) + ascendingClock.Unlock() + timePart := hex.EncodeToString([]byte{ + byte(value >> 40), byte(value >> 32), byte(value >> 24), + byte(value >> 16), byte(value >> 8), byte(value), + }) + return prefix + "_" + timePart + randomBase62(14) +} + +// randomBase62 returns length random Base62 characters. It panics when the +// system random source fails. +func randomBase62(length int) string { + buf := make([]byte, length) + if _, err := rand.Read(buf); err != nil { + panic("crypto/rand failed: " + err.Error()) + } + for i, b := range buf { + buf[i] = base62Alphabet[int(b)%62] + } + return string(buf) +} diff --git a/internal/identity/request.go b/internal/identity/request.go index 30489fa..24a8886 100644 --- a/internal/identity/request.go +++ b/internal/identity/request.go @@ -1,11 +1,11 @@ // 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. +// id plus a client User-Agent, and the /inference gate 403s requests that +// carry the v1 lane's 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 ( @@ -22,14 +22,15 @@ import ( ) // RequestIDs carries the identity headers the upstream free tier inspects. -// Session is sent as x-opencode-session on every lane and additionally as -// x-opencode-session-id on /inference, which requires both. Request travels as -// x-opencode-request on the legacy /zen/v1 lane only; /inference rejects it. -// Project is rendered per lane by the gateway (prj_* on /zen/v1, bare 40-hex -// on /inference). +// Session is sent as both x-opencode-session and x-opencode-session-id. +// Message is the user message id the v1 lane receives as x-opencode-request; +// the v2 lane rejects that header. Request only identifies the request inside +// the gateway. Project is rendered per lane by the gateway (prj_* on the v1 +// lane, bare 40-hex on the v2 lane). type RequestIDs struct { Session string Request string + Message string Project string ParentSession string } @@ -83,6 +84,7 @@ func DeriveRequestIDs(r *http.Request, body map[string]any, scope string) Reques return RequestIDs{ Session: session, Request: RandomID("req", 16), + Message: UserMessageID(r, body, session), Project: projectSignal, ParentSession: parentSession, } @@ -170,11 +172,6 @@ func firstUserTurn(body map[string]any, prelude *[]any) (any, bool) { return nil, false } -func StableID(prefix, value string) string { - sum := sha256.Sum256([]byte(prefix + "\x00" + value)) - return prefix + "_" + hex.EncodeToString(sum[:12]) -} - // canonicalSessionPattern matches OpenCode's canonical session format: // "ses_" + 12 lowercase hex timestamp characters + 14 Base62 characters. // Since 2026-09-16 the Zen free tier rejects any other session shape with @@ -233,6 +230,8 @@ func descendingTimePart(hash []byte) string { }) } +// base62Fixed renders n in the Base62 alphabet, zero-padded to width +// characters. It consumes n. func base62Fixed(n *big.Int, width int) string { base := big.NewInt(62) out := make([]byte, width) @@ -244,6 +243,8 @@ func base62Fixed(n *big.Int, width int) string { return string(out) } +// RandomID returns prefix + "_" + size random bytes in hex. It panics when the +// system random source fails. func RandomID(prefix string, size int) string { buf := make([]byte, size) if _, err := rand.Read(buf); err != nil { diff --git a/internal/jsonutil/decode.go b/internal/jsonutil/decode.go index c8e2d36..3f6b61b 100644 --- a/internal/jsonutil/decode.go +++ b/internal/jsonutil/decode.go @@ -6,6 +6,10 @@ import ( "io" ) +// EnsureEOF reports an error when dec holds anything besides the value that +// was already decoded: a trailing JSON value is "multiple JSON values", and +// trailing garbage is returned as the decoder's own error. Anything up to EOF +// is fine, so whitespace after the value is accepted. func EnsureEOF(dec *json.Decoder) error { var extra any if err := dec.Decode(&extra); err != io.EOF { diff --git a/internal/jsonutil/value.go b/internal/jsonutil/value.go index 5fbb845..3d57204 100644 --- a/internal/jsonutil/value.go +++ b/internal/jsonutil/value.go @@ -6,6 +6,7 @@ import ( "strings" ) +// FirstNonZero returns the first value that is not zero, or 0 when all are. func FirstNonZero(values ...int) int { for _, value := range values { if value != 0 { @@ -15,6 +16,9 @@ func FirstNonZero(values ...int) int { return 0 } +// ParseJSONOrString decodes value as JSON, returning the decoded value when it +// parses and the string itself otherwise. An empty string yields an empty +// object rather than an empty string, so callers always get a JSON value. func ParseJSONOrString(value string) any { if value == "" { return map[string]any{} @@ -26,12 +30,15 @@ func ParseJSONOrString(value string) any { return value } +// Put sets object[key] to value unless value is nil, in which case the key is +// left untouched. The object must not be nil. func Put(object map[string]any, key string, value any) { if value != nil { object[key] = value } } +// FirstAny returns the first value that is not nil, or nil when all are. func FirstAny(values ...any) any { for _, value := range values { if value != nil { @@ -41,6 +48,7 @@ func FirstAny(values ...any) any { return nil } +// CloneMap deep-copies a decoded JSON object, keeping a nil map nil. func CloneMap(input map[string]any) map[string]any { if input == nil { return nil @@ -60,6 +68,8 @@ func cloneMap(input map[string]any) map[string]any { return output } +// cloneValue deep-copies the JSON containers in value; any other value is +// returned as is. func cloneValue(value any) any { switch typed := value.(type) { case map[string]any: @@ -75,6 +85,9 @@ func cloneValue(value any) any { } } +// AsSlice returns value as a slice: a []any unchanged, nil as nil, and any +// other value as a one-element slice. It is what lets a request field accept +// either one item or a list. func AsSlice(value any) []any { if values, ok := value.([]any); ok { return values @@ -85,26 +98,37 @@ func AsSlice(value any) []any { return []any{value} } +// SliceAt returns the []any at the given path, or nil when the path is missing +// or the value there is not a slice. func SliceAt(object map[string]any, path ...string) []any { values, _ := AnyAt(object, path...).([]any) return values } +// MapAt returns the object at the given path, or nil when the path is missing +// or the value there is not an object. func MapAt(object map[string]any, path ...string) map[string]any { value, _ := AnyAt(object, path...).(map[string]any) return value } +// StringAt returns the string at the given path, or "" when the path is +// missing or the value there is not a string. func StringAt(object map[string]any, path ...string) string { value, _ := AnyAt(object, path...).(string) return value } +// BoolAt returns the bool at the given path, or false when the path is missing +// or the value there is not a bool. func BoolAt(object map[string]any, path ...string) bool { value, _ := AnyAt(object, path...).(bool) return value } +// IntAt returns the number at the given path as an int, accepting float64 +// (fractions are truncated), int and json.Number. Any other value, a missing +// path or an unparsable json.Number yields 0. func IntAt(object map[string]any, path ...string) int { value := AnyAt(object, path...) switch number := value.(type) { @@ -120,10 +144,14 @@ func IntAt(object map[string]any, path ...string) int { } } +// Int64At is IntAt widened to int64. func Int64At(object map[string]any, path ...string) int64 { return int64(IntAt(object, path...)) } +// AnyAt walks path through nested objects and returns the value found, or nil +// when a step is missing or the value at a step is not an object. An empty +// path returns object itself. func AnyAt(object map[string]any, path ...string) any { var current any = object for _, key := range path { @@ -136,6 +164,8 @@ func AnyAt(object map[string]any, path ...string) any { return current } +// FirstString returns the first value that is not empty after trimming space, +// trimmed, or "" when all are. func FirstString(values ...string) string { for _, value := range values { if value = strings.TrimSpace(value); value != "" { diff --git a/internal/models/availability.go b/internal/models/availability.go index 001835e..530b025 100644 --- a/internal/models/availability.go +++ b/internal/models/availability.go @@ -8,15 +8,28 @@ import ( "time" ) +// FreeModelCheckInterval is the delay before a free model is probed again +// after a success or an inconclusive failure. const FreeModelCheckInterval = time.Hour + +// FailedModelCheckInterval is the longer delay once a probe has found the model +// unavailable, and after an inconclusive recheck of a disabled model. const FailedModelCheckInterval = 24 * time.Hour +// EffortProbe is the result of the automatic reasoning-effort probe: the +// highest Effort the model accepted ("none" when only the baseline request +// succeeded) and the Protocol it was probed on. Reset is never persisted; it +// asks Record to clear a previously stored result. type EffortProbe struct { Effort string `json:"effort,omitempty"` Protocol string `json:"protocol,omitempty"` Reset bool `json:"-"` } +// Availability is the probe state of one free model. Generation lives only in +// memory: every manual/automatic switch bumps it, so Record can drop the result +// of a probe that started before the switch. ProbeVersion 0 marks a record +// written by the old probe, which AvailabilityStore migrates on load. type Availability struct { Model string `json:"model"` Disabled bool `json:"disabled"` @@ -31,14 +44,19 @@ type Availability struct { EffortCheckedAt time.Time `json:"effort_checked_at,omitempty"` } -type AvailabilityStore struct { +// AvailabilityRegistry tracks which free models the background probes found +// available and which ones an operator put under manual control. It is +// persisted as JSON at path, or kept in memory only when path is empty. +type AvailabilityRegistry struct { mu sync.RWMutex path string items map[string]Availability } -func NewAvailabilityStore(path string) (*AvailabilityStore, error) { - s := &AvailabilityStore{path: path, items: map[string]Availability{}} +// AvailabilityStore loads the registry from path. A missing file starts an +// empty registry; an unreadable or malformed one is an error. +func AvailabilityStore(path string) (*AvailabilityRegistry, error) { + s := &AvailabilityRegistry{path: path, items: map[string]Availability{}} if path != "" { b, err := os.ReadFile(path) if err == nil { @@ -74,7 +92,9 @@ func NewAvailabilityStore(path string) (*AvailabilityStore, error) { return s, nil } -func (s *AvailabilityStore) Get(model string) Availability { +// Get returns the record of model, or an enabled, never-checked record when the +// registry has none. +func (s *AvailabilityRegistry) Get(model string) Availability { s.mu.RLock() defer s.mu.RUnlock() item := s.items[model] @@ -82,12 +102,14 @@ func (s *AvailabilityStore) Get(model string) Availability { return item } -func (s *AvailabilityStore) Disabled(model string) bool { return s.Get(model).Disabled } +func (s *AvailabilityRegistry) Disabled(model string) bool { return s.Get(model).Disabled } // SetManual switches a model between manual and automatic control. Manual // mode keeps the model enabled and excludes it from automatic probing; -// switching back to automatic schedules a probe on the next check. -func (s *AvailabilityStore) SetManual(model string, manual bool, now time.Time) error { +// switching back to automatic schedules a probe on the next check. A call that +// does not change the mode is a no-op. A switch bumps Generation, and the +// previous record is restored when it cannot be persisted. +func (s *AvailabilityRegistry) SetManual(model string, manual bool, now time.Time) error { s.mu.Lock() defer s.mu.Unlock() item, existed := s.items[model] @@ -120,13 +142,22 @@ func (s *AvailabilityStore) SetManual(model string, manual bool, now time.Time) return nil } -// A manual restore takes the model under manual control and invalidates -// results from probes that were already running. -func (s *AvailabilityStore) Restore(model string, now time.Time) error { +// Restore takes the model under manual control, which re-enables it and, by +// bumping Generation, invalidates results from probes that were already +// running. A model already under manual control is left untouched and its +// Generation is not bumped; Record ignores manual records anyway. +func (s *AvailabilityRegistry) Restore(model string, now time.Time) error { return s.SetManual(model, true, now) } -func (s *AvailabilityStore) Record(model string, generation uint64, success bool, reason, channel string, now time.Time, effort EffortProbe) error { +// Record stores the result of an automatic probe that started when the record +// was at generation. The result is dropped when Generation has moved on since +// then or the model is under manual control. Only the reason +// "model_unavailable" disables a model and moves it to the daily schedule; any +// other failure of an enabled model is recorded with an hourly retry. A +// successful probe stores effort when it names a level and clears the stored +// level when effort.Reset is set. +func (s *AvailabilityRegistry) Record(model string, generation uint64, success bool, reason, channel string, now time.Time, effort EffortProbe) error { s.mu.Lock() defer s.mu.Unlock() item := s.items[model] @@ -173,7 +204,9 @@ func (s *AvailabilityStore) Record(model string, generation uint64, success bool return s.saveLocked() } -func (s *AvailabilityStore) saveLocked() error { +// saveLocked rewrites the registry file through a temporary file and a rename. +// It is a no-op without a path. The caller holds s.mu for writing. +func (s *AvailabilityRegistry) saveLocked() error { if s.path == "" { return nil } diff --git a/internal/models/cache.go b/internal/models/cache.go index 5d836d4..d49d17a 100644 --- a/internal/models/cache.go +++ b/internal/models/cache.go @@ -17,10 +17,15 @@ import ( wire "opencode2api/internal/protocol" ) +// modelCatalogCacheSchemaVersion is the layout version of the catalog cache. A +// file with any other version is rejected, so bump it with every layout change. const modelCatalogCacheSchemaVersion = 3 +// modelCatalogCacheWriteMu serializes cache writes across catalogs: every +// runtime built from one config writes the same cache file. var modelCatalogCacheWriteMu sync.Mutex +// modelCatalogCache is the on-disk snapshot written by SaveCache. type modelCatalogCache struct { SchemaVersion int `json:"schema_version"` UpdatedAt time.Time `json:"updated_at"` @@ -33,8 +38,10 @@ type modelCatalogCache struct { // LoadCache installs a validated disk snapshot into a catalog. It deliberately // changes only discovered state; configured protocol overrides and routing -// preferences stay owned by the current Config. -func (c *Catalog) LoadCache(path string) error { +// preferences stay owned by the current Config. The snapshot is reported as +// stale until the next live refresh, and path becomes the cache path unless +// one is already set. +func (c *ModelCatalog) LoadCache(path string) error { cache, err := loadModelCatalogCache(path) if err != nil { return err @@ -56,9 +63,9 @@ func (c *Catalog) LoadCache(path string) error { } // SaveCache snapshots only public model capability data. Credentials and -// proxy configuration are not part of modelCatalog and can never enter this -// file. -func (c *Catalog) SaveCache() error { +// proxy configuration are not part of ModelCatalog and can never enter this +// file. It is a no-op while the catalog has no cache path. +func (c *ModelCatalog) SaveCache() error { c.mu.RLock() path := c.cachePath cache := modelCatalogCache{ @@ -77,6 +84,8 @@ func (c *Catalog) SaveCache() error { return saveModelCatalogCache(path, cache) } +// CatalogCachePath returns the catalog cache file kept beside the config file, +// or "" when there is no config path. func CatalogCachePath(configPath string) string { if configPath == "" { return "" @@ -84,6 +93,9 @@ func CatalogCachePath(configPath string) string { return configPath + ".models.catalog.json" } +// loadModelCatalogCache reads and validates a cache file: exactly one JSON +// value of the current schema, with a timestamp, at least one model and only +// known tiers and protocols. Model IDs are trimmed, deduplicated and sorted. func loadModelCatalogCache(path string) (modelCatalogCache, error) { if path == "" { return modelCatalogCache{}, os.ErrNotExist @@ -167,6 +179,9 @@ func validateCatalogCapabilities(native map[config.Tier]map[string]wire.Protocol return nil } +// saveModelCatalogCache writes cache through a 0600 temporary file and a +// rename. On Windows the existing file is first moved to path+".replace" and +// put back if the final rename fails. func saveModelCatalogCache(path string, cache modelCatalogCache) error { if path == "" { return nil diff --git a/internal/models/catalog.go b/internal/models/catalog.go index 1d5a972..a1b65f5 100644 --- a/internal/models/catalog.go +++ b/internal/models/catalog.go @@ -1,4 +1,5 @@ -// Package models discovers model capabilities, pricing, and available routes. +// Package models discovers model capabilities, pricing, availability, and +// available routes. package models import ( @@ -13,6 +14,9 @@ import ( wire "opencode2api/internal/protocol" ) +// Route is the plan for serving one model: the tier and native protocol of the +// first attempt, the protocol of every tier a retry may reach, and the +// authenticated fallback order. type Route struct { ID string Tier config.Tier @@ -23,6 +27,8 @@ type Route struct { // Messages on Go. The request must therefore be re-encoded when a retry // crosses tiers. Protocols map[config.Tier]wire.Protocol + // Anonymous marks a route that starts on the anonymous lane with the + // public credential; Tier is then always Zen. Anonymous bool // KeyTiers is the ordered authenticated fallback plan. Anonymous requests // always start on Zen, then enter this list when the public credential does @@ -30,6 +36,9 @@ type Route struct { KeyTiers []config.Tier } +// RouteDiagnostic explains how a model is routed: where its protocol comes +// from, which tiers advertise it, its anonymous eligibility, and the route that +// was built or the error that prevented one. type RouteDiagnostic struct { Model string `json:"model"` RequestedProtocol wire.Protocol `json:"requested_protocol,omitempty"` @@ -48,7 +57,11 @@ type RouteDiagnostic struct { RouteError string `json:"route_error,omitempty"` } -type Catalog struct { +// ModelCatalog knows which models the Zen and Go tiers advertise, their native +// protocols and metadata, and routes requests for them. mu guards every field; +// methods ending in Locked expect the caller to hold it, and a read lock is +// enough for all of them. +type ModelCatalog struct { mu sync.RWMutex zen map[string]bool goModels map[string]bool @@ -60,8 +73,8 @@ type Catalog struct { modelMeta map[config.Tier]map[string]Metadata updatedAt time.Time prefer config.Tier - pricing *PricingStore - availability *AvailabilityStore + pricing *PricingRegistry + availability *AvailabilityRegistry cachePath string cacheSource string stale bool @@ -69,6 +82,11 @@ type Catalog struct { freeOnly bool } +// CatalogSnapshot summarizes the catalog for health reporting. Exposed counts +// the models with a usable protocol on a tier that advertises them; +// AvailableModels narrows it to the models that can be routed. Stale is set +// while the catalog still holds a disk cache, or when the last refresh is older +// than twice the refresh interval (at least a minute). type CatalogSnapshot struct { Zen int `json:"zen"` Go int `json:"go"` @@ -79,12 +97,15 @@ type CatalogSnapshot struct { Stale bool `json:"stale"` } -func NewCatalog(prefer config.Tier, overrides map[string]string) *Catalog { +// Catalog creates an empty ModelCatalog. prefer is the tier authenticated +// routes try first, and overrides are the configured per-model protocols that +// take precedence over the upstream capability data. +func Catalog(prefer config.Tier, overrides map[string]string) *ModelCatalog { protocols := make(map[string]wire.Protocol, len(overrides)) for model, protocol := range overrides { protocols[model] = wire.Protocol(protocol) } - return &Catalog{ + return &ModelCatalog{ zen: map[string]bool{}, goModels: map[string]bool{}, protocols: protocols, nativeProtocols: map[config.Tier]map[string]wire.Protocol{config.TierZen: {}, config.TierGo: {}}, unsupported: map[config.Tier]map[string]bool{config.TierZen: {}, config.TierGo: {}}, prefer: prefer, @@ -93,20 +114,23 @@ func NewCatalog(prefer config.Tier, overrides map[string]string) *Catalog { } // SetPricingStore connects routing decisions to the shared pricing metadata. -func (c *Catalog) SetPricingStore(store *PricingStore) { +func (c *ModelCatalog) SetPricingStore(store *PricingRegistry) { c.mu.Lock() c.pricing = store c.mu.Unlock() } -func (c *Catalog) SetAvailabilityStore(store *AvailabilityStore) { +// SetAvailabilityStore lets routing reject models that the availability probes +// disabled. +func (c *ModelCatalog) SetAvailabilityStore(store *AvailabilityRegistry) { c.mu.Lock() c.availability = store c.mu.Unlock() } -// MetadataSnapshot reports pricing freshness without exposing the store. -func (c *Catalog) MetadataSnapshot() MetadataSnapshot { +// MetadataSnapshot reports pricing freshness without exposing the registry. It +// returns the zero snapshot while no PricingRegistry is attached. +func (c *ModelCatalog) MetadataSnapshot() MetadataSnapshot { c.mu.RLock() store := c.pricing c.mu.RUnlock() @@ -116,40 +140,52 @@ func (c *Catalog) MetadataSnapshot() MetadataSnapshot { return store.Snapshot() } -func (c *Catalog) SetCachePath(path string) { +// SetCachePath sets the file SaveCache writes; an empty path disables it. +func (c *ModelCatalog) SetCachePath(path string) { c.mu.Lock() c.cachePath = path c.mu.Unlock() } -func (c *Catalog) SetRefreshInterval(interval time.Duration) { +// SetRefreshInterval sets the expected catalog refresh interval, which decides +// when a snapshot counts as stale. Zero disables the age check. +func (c *ModelCatalog) SetRefreshInterval(interval time.Duration) { c.mu.Lock() c.refreshAfter = interval c.mu.Unlock() } -// SetFreeOnly hides every model that is not free from discovery and routing. -func (c *Catalog) SetFreeOnly(enabled bool) { +// SetFreeOnly makes routing reject every model that is not free. The models +// listing (AvailableModels) and the rotation aliases are built from routes, so +// they hide those models too. The upstream catalog refresh, List and Supported +// are unaffected. +func (c *ModelCatalog) SetFreeOnly(enabled bool) { c.mu.Lock() c.freeOnly = enabled c.mu.Unlock() } -// freeOnlyErrorLocked rejects paid models while models.free_only is set. Both -// routing entry points check it, so /v1/models, inference, rotation aliases and -// diagnostics agree on what is exposed. -func (c *Catalog) freeOnlyErrorLocked(model string) error { +// freeOnlyErrorLocked rejects models that are not free while models.free_only +// is set. Both routing entry points (routeLocked and RouteForTier) check it, so +// /v1/models, inference, rotation aliases and diagnostics agree on what is +// exposed. +func (c *ModelCatalog) freeOnlyErrorLocked(model string) error { if c.freeOnly && !c.anonymousDecision(model).Allowed { return fmt.Errorf("model %q is not free and models.free_only is enabled", model) } return nil } -func (c *Catalog) Replace(zen, goModels []string) { +// Replace installs freshly listed model IDs and keeps the capability data. +func (c *ModelCatalog) Replace(zen, goModels []string) { c.ReplaceWithCapabilities(zen, goModels, nil, nil, nil) } -func (c *Catalog) ReplaceWithCapabilities(zen, goModels []string, native map[config.Tier]map[string]wire.Protocol, unsupported map[config.Tier]map[string]bool, metadata map[config.Tier]map[string]Metadata) { +// ReplaceWithCapabilities installs the result of a live refresh and marks the +// catalog fresh. A nil argument leaves that part of the state unchanged, so a +// tier whose listing failed keeps its previous models; native and unsupported +// are replaced per tier, metadata as a whole. +func (c *ModelCatalog) ReplaceWithCapabilities(zen, goModels []string, native map[config.Tier]map[string]wire.Protocol, unsupported map[config.Tier]map[string]bool, metadata map[config.Tier]map[string]Metadata) { c.mu.Lock() defer c.mu.Unlock() if zen != nil { @@ -180,7 +216,12 @@ func (c *Catalog) ReplaceWithCapabilities(zen, goModels []string, native map[con c.stale = false } -func (c *Catalog) CopyState(source *Catalog) { +// CopyState copies the discovered state of source (models, capabilities, +// metadata and cache freshness) into c, so a runtime rebuilt for a config +// change starts with the current catalog. Configuration (protocol overrides, +// tier preference, free_only, cache path, refresh interval) and the attached +// registries are not copied. +func (c *ModelCatalog) CopyState(source *ModelCatalog) { if source == nil { return } @@ -215,13 +256,18 @@ func (c *Catalog) CopyState(source *Catalog) { c.mu.Unlock() } -func (c *Catalog) Route(model string, hasZenKeys, hasGoKeys, hasAnonymous bool) (Route, error) { +// Route plans how model is served given which credentials exist. A free model +// can start on the anonymous lane when hasAnonymous is set; otherwise, and as +// the fallback, the key tiers are tried in prefer order. It fails when the probes +// disabled the model, when models.free_only hides it, or when no lane or tier +// can serve it. +func (c *ModelCatalog) Route(model string, hasZenKeys, hasGoKeys, hasAnonymous bool) (Route, error) { c.mu.RLock() defer c.mu.RUnlock() return c.routeLocked(model, hasZenKeys, hasGoKeys, hasAnonymous) } -func (c *Catalog) routeLocked(model string, hasZenKeys, hasGoKeys, hasAnonymous bool) (Route, error) { +func (c *ModelCatalog) routeLocked(model string, hasZenKeys, hasGoKeys, hasAnonymous bool) (Route, error) { if c.availability != nil && c.availability.Disabled(model) { return Route{}, fmt.Errorf("model %q is disabled after a failed availability check; restore it in the WebUI or wait for the next probe", model) } @@ -229,9 +275,10 @@ func (c *Catalog) routeLocked(model string, hasZenKeys, hasGoKeys, hasAnonymous return Route{}, err } keyTiers := c.keyTierOrderLocked(model, hasZenKeys, hasGoKeys) - // OpenCode's public credential is a Zen-only lane. Every free model starts - // there, even if the current catalog only advertises it on Go: an upstream - // rejection will move the request into the authenticated fallback plan. + // OpenCode's public credential belongs to the Zen tier. Every free model + // starts there unless the Zen capability data marks it unsupported, even if + // the current catalog only advertises it on Go: an upstream rejection will + // move the request into the authenticated fallback plan. decision := c.anonymousDecision(model) if hasAnonymous && decision.Allowed && (c.protocols[model] != "" || !c.unsupported[config.TierZen][model]) && (len(c.zen) == 0 && len(c.goModels) == 0 || c.zen[model] || c.goModels[model]) { @@ -245,6 +292,8 @@ func (c *Catalog) routeLocked(model string, hasZenKeys, hasGoKeys, hasAnonymous return Route{}, fmt.Errorf("model %q is not available in the configured Zen or Go pools", model) } +// ProtocolFor returns the native protocol of the route on tier, or Protocol +// when the route has no entry for that tier. func (r Route) ProtocolFor(tier config.Tier) wire.Protocol { if protocol := r.Protocols[tier]; protocol != "" { return protocol @@ -252,7 +301,9 @@ func (r Route) ProtocolFor(tier config.Tier) wire.Protocol { return r.Protocol } -func (c *Catalog) protocolsForLocked(model string, keyTiers []config.Tier, includeZen bool) map[config.Tier]wire.Protocol { +// protocolsForLocked resolves the protocol of every tier in keyTiers, plus Zen +// when includeZen is set for an anonymous route. +func (c *ModelCatalog) protocolsForLocked(model string, keyTiers []config.Tier, includeZen bool) map[config.Tier]wire.Protocol { protocols := make(map[config.Tier]wire.Protocol, len(keyTiers)+1) if includeZen { protocols[config.TierZen] = c.protocolForLocked(model, config.TierZen) @@ -263,7 +314,9 @@ func (c *Catalog) protocolsForLocked(model string, keyTiers []config.Tier, inclu return protocols } -func (c *Catalog) protocolForLocked(model string, tier config.Tier) wire.Protocol { +// protocolForLocked resolves the protocol of model on tier: the configured +// override first, then the tier's capability data, then Chat. +func (c *ModelCatalog) protocolForLocked(model string, tier config.Tier) wire.Protocol { if protocol := c.protocols[model]; protocol != "" { return protocol } @@ -277,10 +330,11 @@ func (c *Catalog) protocolForLocked(model string, tier config.Tier) wire.Protoco } // keyTierOrderLocked builds an authenticated route in prefer order. A tier is -// included only when it has a key and advertises the model. Before the first -// successful catalog refresh, configured key pools remain usable so temporary -// discovery failures do not take the gateway offline. -func (c *Catalog) keyTierOrderLocked(model string, hasZenKeys, hasGoKeys bool) []config.Tier { +// included only when it has a key, advertises the model, and can carry its +// protocol (tierSupportedLocked). Before the first successful catalog refresh, +// configured key pools remain usable so temporary discovery failures do not +// take the gateway offline. +func (c *ModelCatalog) keyTierOrderLocked(model string, hasZenKeys, hasGoKeys bool) []config.Tier { catalogPending := len(c.zen) == 0 && len(c.goModels) == 0 available := func(tier config.Tier) bool { switch tier { @@ -309,7 +363,7 @@ func (c *Catalog) keyTierOrderLocked(model string, hasZenKeys, hasGoKeys bool) [ // per-key diagnostics. It never selects the anonymous lane and never adds a // fallback tier: the operator asked to exercise one configured key, so the // result describes that key and nothing else. -func (c *Catalog) RouteForTier(model string, tier config.Tier, hasZenKeys, hasGoKeys bool) (Route, error) { +func (c *ModelCatalog) RouteForTier(model string, tier config.Tier, hasZenKeys, hasGoKeys bool) (Route, error) { if tier != config.TierZen && tier != config.TierGo { return Route{}, errors.New("selected key tier must be zen or go") } @@ -347,23 +401,31 @@ func (c *Catalog) RouteForTier(model string, tier config.Tier, hasZenKeys, hasGo }, nil } -func (c *Catalog) anonymousDecision(model string) AnonymousDecision { +// anonymousDecision asks the pricing registry whether model is free and falls +// back to the name rule while none is attached. It reads c.pricing, which +// SetPricingStore only writes while a runtime is being built. +func (c *ModelCatalog) anonymousDecision(model string) AnonymousDecision { if c.pricing != nil { return c.pricing.Decide(model) } return AnonymousDecision{Allowed: isFreeModel(model), Source: "name_fallback_metadata_pending"} } -// IsFreeModel reports whether the catalog considers the model free-tier -// (pricing metadata, falling back to the -free name convention). Key-tier -// shaping uses it so free models without "free" in the name are covered. -func (c *Catalog) IsFreeModel(model string) bool { +// IsFreeModel reports whether the catalog considers the model free-tier: its +// name contains "free" in any case, or the pricing metadata lists it, not +// deprecated, at zero input and output cost. Until the metadata is ready only +// the name rule applies. Key-tier shaping uses it so free models without +// "free" in the name are covered. +func (c *ModelCatalog) IsFreeModel(model string) bool { c.mu.RLock() defer c.mu.RUnlock() return c.anonymousDecision(model).Allowed } -func (c *Catalog) Diagnostic(model string, requested wire.Protocol, hasZenKeys, hasGoKeys, hasAnonymous bool) RouteDiagnostic { +// Diagnostic explains the protocol choice and the route of model for the given +// credentials; requested is only echoed. It never fails: a routing error is +// reported in RouteError. +func (c *ModelCatalog) Diagnostic(model string, requested wire.Protocol, hasZenKeys, hasGoKeys, hasAnonymous bool) RouteDiagnostic { c.mu.RLock() configured, explicit := c.protocols[model] zen, goModel := c.zen[model], c.goModels[model] @@ -406,11 +468,15 @@ func (c *Catalog) Diagnostic(model string, requested wire.Protocol, hasZenKeys, return diagnostic } +// isFreeModel is the name rule: a model whose ID contains "free" in any case. func isFreeModel(model string) bool { return strings.Contains(strings.ToLower(model), "free") } -func (c *Catalog) List() []string { +// List returns the sorted IDs of the advertised models that have a usable +// protocol on a tier advertising them. It ignores credentials, availability and +// models.free_only; AvailableModels applies those. +func (c *ModelCatalog) List() []string { c.mu.RLock() defer c.mu.RUnlock() ids := c.modelIDsLocked() @@ -423,7 +489,7 @@ func (c *Catalog) List() []string { return models } -func (c *Catalog) modelIDsLocked() []string { +func (c *ModelCatalog) modelIDsLocked() []string { seen := make(map[string]bool, len(c.zen)+len(c.goModels)) for model := range c.zen { seen[model] = true @@ -434,15 +500,18 @@ func (c *Catalog) modelIDsLocked() []string { return sortedSetKeys(seen) } -func (c *Catalog) Snapshot() CatalogSnapshot { +// Snapshot summarizes the catalog without route filtering. +func (c *ModelCatalog) Snapshot() CatalogSnapshot { c.mu.RLock() defer c.mu.RUnlock() return c.snapshotLocked(c.modelIDsLocked()) } // AvailableModels provides discovery and readiness with the same route -// filtering, including configured key tiers and anonymous eligibility. -func (c *Catalog) AvailableModels(hasZenKeys, hasGoKeys, hasAnonymous bool) ([]Route, CatalogSnapshot) { +// filtering, including configured key tiers and anonymous eligibility. It +// returns the route of every routable model and a snapshot whose Exposed +// counts those routes. +func (c *ModelCatalog) AvailableModels(hasZenKeys, hasGoKeys, hasAnonymous bool) ([]Route, CatalogSnapshot) { c.mu.RLock() defer c.mu.RUnlock() ids := c.modelIDsLocked() @@ -460,7 +529,7 @@ func (c *Catalog) AvailableModels(hasZenKeys, hasGoKeys, hasAnonymous bool) ([]R return routes, snapshot } -func (c *Catalog) snapshotLocked(ids []string) CatalogSnapshot { +func (c *ModelCatalog) snapshotLocked(ids []string) CatalogSnapshot { exposed := 0 for _, model := range ids { if c.supportedLocked(model) { @@ -477,21 +546,24 @@ func (c *Catalog) snapshotLocked(ids []string) CatalogSnapshot { } } -func (c *Catalog) Supported(model string) bool { +// Supported reports whether some tier advertises model with a usable protocol. +// Every model is supported while the catalog is still pending. +func (c *ModelCatalog) Supported(model string) bool { c.mu.RLock() defer c.mu.RUnlock() return c.supportedLocked(model) } // MetadataForTier returns the rich per-model metadata (context window, -// reasoning, tool call, modalities) captured from the opencode catalog for -// the tier that will actually serve the request. Same-named models can carry -// different limits per tier, so callers must pass route.Tier — never a -// tier-blind lookup. Anonymous routes always resolve to TierZen, which keeps +// reasoning, tool call, modalities) captured from the OpenCode capability +// catalog for the tier that will actually serve the request. Same-named models +// can carry different limits per tier, so callers must pass route.Tier — never +// a tier-blind lookup. Anonymous routes always resolve to TierZen, which keeps // the keyless path on Zen metadata. Limits the catalog omitted are filled from -// models.dev; capability flags always come from the catalog. The zero value is -// returned for models neither source describes (or before the first refresh). -func (c *Catalog) MetadataForTier(model string, tier config.Tier) Metadata { +// the OpenCode pricing metadata, which also supplies Cost; capability flags +// always come from the catalog. The zero value is returned for models neither +// source describes (or before the first refresh). +func (c *ModelCatalog) MetadataForTier(model string, tier config.Tier) Metadata { c.mu.RLock() md := c.modelMeta[tier][model] pricing := c.pricing @@ -503,9 +575,9 @@ func (c *Catalog) MetadataForTier(model string, tier config.Tier) Metadata { if !ok { return md } - // OpenCode's capability catalog is authoritative. Use models.dev limits - // only to fill fields it omitted so discovery clients still get per-model - // context and output limits. + // OpenCode's capability catalog is authoritative. Use the pricing + // metadata's limits only to fill fields it omitted so discovery clients + // still get per-model context and output limits. if md.ContextWindow == 0 { md.ContextWindow = price.ContextWindow } @@ -521,7 +593,7 @@ func (c *Catalog) MetadataForTier(model string, tier config.Tier) Metadata { return md } -func (c *Catalog) supportedLocked(model string) bool { +func (c *ModelCatalog) supportedLocked(model string) bool { if len(c.zen) == 0 && len(c.goModels) == 0 { return true } @@ -534,7 +606,11 @@ func (c *Catalog) supportedLocked(model string) bool { return false } -func (c *Catalog) tierSupportedLocked(model string, tier config.Tier) bool { +// tierSupportedLocked reports whether tier can carry model's protocol. A +// configured override always can; otherwise the tier's capability data +// decides, and a model it does not know is accepted only while the catalog is +// pending. +func (c *ModelCatalog) tierSupportedLocked(model string, tier config.Tier) bool { if c.protocols[model] != "" { return true } diff --git a/internal/models/discovery.go b/internal/models/discovery.go index 251b71b..1287862 100644 --- a/internal/models/discovery.go +++ b/internal/models/discovery.go @@ -15,18 +15,41 @@ import ( wire "opencode2api/internal/protocol" ) +// CapabilitiesURL is OpenCode's machine-readable model catalog. It feeds +// FetchCapabilities and is also the OpenCode metadata endpoint the +// PricingRegistry reads. ZenDocsURL and GoDocsURL are the Zen and Go +// documentation pages whose endpoint tables FetchCapabilities reads with +// FetchProtocolDocs. 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 legacy /zen console origin (serving /zen/v1/*) that - // still serves anonymous inference and the models listing alongside the newer - // /inference backend. - LegacyZenBase = "https://opencode.ai/zen" + // V1Base is the v1 lane's origin: the /zen console (serving /zen/v1/*) that + // expects the OpenCode 1.x request shape. It is the default keyed Zen + // upstream, and the anonymous lane tries it before the v2 /inference + // origin. It also serves the models listing. + V1Base = "https://opencode.ai/zen" ) +// IsV1Upstream reports whether baseURL targets the v1 /zen gate, which expects +// the OpenCode 1.x request shape, rather than a v2 gate (/inference or +// /zen/go), which expects the OpenCode 2.x CLI shape. +func IsV1Upstream(baseURL string) bool { + trimmed := strings.ToLower(strings.TrimRight(strings.TrimSpace(baseURL), "/")) + if strings.EqualFold(trimmed, strings.TrimRight(V1Base, "/")) { + return true + } + return strings.HasSuffix(trimmed, "/zen") +} + +// protocolDocEndpointPattern matches a row of a documentation endpoint table, +// "| name | `model-id` | `.../v1/` |", capturing the model ID and the +// endpoint. var protocolDocEndpointPattern = regexp.MustCompile("\\|[^|]+\\|\\s*`?([^|`\\s]+)`?\\s*\\|\\s*`[^`]+/v1/(chat/completions|responses|messages|systemone)`") +// Capabilities is the per-tier result of FetchCapabilities: the native +// protocol of every model, the models whose SDK maps to no supported protocol, +// and the metadata of every listed model. type Capabilities struct { Protocols map[config.Tier]map[string]wire.Protocol Unsupported map[config.Tier]map[string]bool @@ -74,7 +97,8 @@ type Metadata struct { StructuredOutput bool `json:"structured_output,omitempty"` InputModalities []string `json:"input_modalities,omitempty"` OutputModalities []string `json:"output_modalities,omitempty"` - // Cost is filled from models.dev at read time, in USD per million tokens. + // Cost is filled from the OpenCode pricing metadata at read time, in USD per + // million tokens. Cost *Cost `json:"cost,omitempty"` } @@ -109,10 +133,13 @@ type capabilityModelProvider struct { NPM string `json:"npm"` } -// fetchProtocolCapabilities reads OpenCode's machine-readable provider -// catalog. Unlike /v1/models, this source includes the SDK selected for each -// model, which is the upstream's protocol declaration. No model IDs are kept -// in this project. +// FetchCapabilities reads OpenCode's machine-readable provider catalog from +// endpoint (normally CapabilitiesURL). Unlike /v1/models, this source includes +// the SDK selected for each model, which is the upstream's protocol +// declaration. The Zen and Go endpoint tables then refine it. Protocol +// discovery is data-driven: no model IDs are embedded here (the fixed SOTA +// rotation list in config.SOTAModels is unrelated). It fails when the catalog +// cannot be read or yields no Zen or Go model. func FetchCapabilities(ctx context.Context, client *http.Client, endpoint string) (Capabilities, error) { if client == nil { client = http.DefaultClient @@ -122,7 +149,7 @@ func FetchCapabilities(ctx context.Context, client *http.Client, endpoint string return Capabilities{}, err } req.Header.Set("Accept", "application/json") - req.Header.Set("User-Agent", httpx.UserAgent()) + req.Header.Set("User-Agent", httpx.V2UserAgent()) resp, err := client.Do(req) if err != nil { return Capabilities{}, err @@ -165,7 +192,9 @@ func FetchCapabilities(ctx context.Context, client *http.Client, endpoint string // The machine catalog is the primary source. The upstream endpoint tables // are a supplemental source for models whose provider inherits a default SDK // but whose published endpoint is more specific (for example a Messages - // route). This remains data-driven: no model IDs are embedded here. + // route), so a listed endpoint wins over the SDK and clears an unsupported + // mark. A table that cannot be fetched is skipped. This remains + // data-driven: no model IDs are embedded here. for _, doc := range []struct { tier config.Tier url string @@ -188,13 +217,17 @@ func FetchCapabilities(ctx context.Context, client *http.Client, endpoint string return result, nil } +// FetchProtocolDocs parses the endpoint table of an OpenCode documentation +// page into a model-to-protocol map, deriving the protocol from the endpoint +// path of each row. It fails when no row matches. Unlike FetchCapabilities it +// requires a non-nil client. func FetchProtocolDocs(ctx context.Context, client *http.Client, endpoint string) (map[string]wire.Protocol, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) if err != nil { return nil, err } req.Header.Set("Accept", "text/plain, text/markdown, */*") - req.Header.Set("User-Agent", httpx.UserAgent()) + req.Header.Set("User-Agent", httpx.V2UserAgent()) resp, err := client.Do(req) if err != nil { return nil, err @@ -238,6 +271,9 @@ func FetchProtocolDocs(ctx context.Context, client *http.Client, endpoint string return result, nil } +// capabilityTier maps a catalog provider to a tier by its ID and API URL: an +// opencode-go provider or a /go/ URL is Go, any other OpenCode provider or a +// /zen/ URL is Zen, and every other provider is skipped. func capabilityTier(providerID, api string) (config.Tier, bool) { value := strings.ToLower(strings.TrimSpace(providerID + " " + api)) if strings.Contains(value, "opencode-go") || strings.Contains(value, "/go/") { @@ -249,6 +285,8 @@ func capabilityTier(providerID, api string) (config.Tier, bool) { return "", false } +// protocolForSDK maps the AI SDK package a model is served through to its wire +// protocol. It reports false for a package the gateway cannot speak. func protocolForSDK(npm string) (wire.Protocol, bool) { value := strings.ToLower(strings.TrimSpace(npm)) switch { @@ -269,6 +307,10 @@ type modelsResponse struct { } `json:"data"` } +// FetchModels lists the model IDs at baseURL's /v1/models with key, sending +// the v1 or v2 User-Agent that matches the lane. It also returns the HTTP +// status, 0 when no response arrived, so callers can judge the proxy. An empty +// list is an error. func FetchModels(ctx context.Context, client *http.Client, baseURL, key string) ([]string, int, error) { trimmed := strings.TrimRight(strings.TrimSpace(baseURL), "/") req, err := http.NewRequestWithContext(ctx, http.MethodGet, trimmed+"/v1/models", nil) @@ -276,10 +318,10 @@ func FetchModels(ctx context.Context, client *http.Client, baseURL, key string) return nil, 0, err } req.Header.Set("Authorization", "Bearer "+key) - if strings.EqualFold(trimmed, strings.TrimRight(LegacyZenBase, "/")) || strings.HasSuffix(strings.ToLower(trimmed), "/zen") { - req.Header.Set("User-Agent", httpx.LegacyUserAgent()) + if IsV1Upstream(trimmed) { + req.Header.Set("User-Agent", httpx.V1UserAgent()) } else { - req.Header.Set("User-Agent", httpx.UserAgent()) + req.Header.Set("User-Agent", httpx.V2UserAgent()) } req.Header.Set("x-opencode-client", "cli") resp, err := client.Do(req) diff --git a/internal/models/pricing.go b/internal/models/pricing.go index 9051374..05bc846 100644 --- a/internal/models/pricing.go +++ b/internal/models/pricing.go @@ -20,12 +20,16 @@ import ( "opencode2api/internal/jsonutil" ) +// metadataDefaultURL is the OpenCode metadata endpoint, metadataRefresh the +// interval between refreshes, and metadataTimeout the limit of one fetch. const ( - modelsDevDefaultURL = CapabilitiesURL - modelsDevRefresh = 24 * time.Hour - modelsDevTimeout = 30 * time.Second + metadataDefaultURL = CapabilitiesURL + metadataRefresh = 24 * time.Hour + metadataTimeout = 30 * time.Second ) +// Price is the pricing and limit metadata of one model. A nil cost means the +// metadata did not state it. type Price struct { ID string `json:"id"` Input *float64 `json:"input_cost,omitempty"` @@ -38,6 +42,11 @@ type Price struct { Deprecated bool `json:"deprecated"` } +// AnonymousDecision reports whether a model counts as free, which admits it to +// the anonymous lane and keeps it visible under models.free_only. Source names +// the rule that decided, such as "name_free", "metadata_free" or +// "metadata_paid". Known reports whether the metadata lists the model; it is +// also false for "metadata_cost_unknown". type AnonymousDecision struct { Allowed bool `json:"allowed"` Source string `json:"source"` @@ -47,6 +56,10 @@ type AnonymousDecision struct { OutputCost *float64 `json:"output_cost,omitempty"` } +// MetadataSnapshot reports the freshness of the pricing metadata. Ready means +// models were loaded from the cache or the endpoint. Stale means the last +// successful refresh is older than the refresh interval, and NextRefresh is +// UpdatedAt plus that interval, not the refresh loop's actual schedule. type MetadataSnapshot struct { Ready bool `json:"ready"` Models int `json:"models"` @@ -57,12 +70,17 @@ type MetadataSnapshot struct { NextRefresh *time.Time `json:"next_refresh,omitempty"` } +// modelMetadataCache is the on-disk copy of the last successful refresh. type modelMetadataCache struct { UpdatedAt time.Time `json:"updated_at"` Models map[string]Price `json:"models"` } -type PricingStore struct { +// PricingRegistry holds the per-model pricing and limit metadata from the +// OpenCode metadata endpoint, keyed by model ID. It decides which models are +// free and keeps the last good response in a cache file so a restart has data +// before the first refresh. +type PricingRegistry struct { mu sync.RWMutex models map[string]Price updatedAt time.Time @@ -74,14 +92,20 @@ type PricingStore struct { logger *slog.Logger } -func NewPricingStore(configPath string, logger *slog.Logger) *PricingStore { +// PricingStore creates a PricingRegistry whose cache file lives beside +// configPath (none when configPath is empty) and loads that cache. A missing +// cache is not an error; any other load failure is kept as the snapshot's +// LastError. +func PricingStore(configPath string, logger *slog.Logger) *PricingRegistry { cachePath := "" if configPath != "" { + // The suffix predates the switch to the OpenCode metadata endpoint and + // is kept so existing caches keep loading after an upgrade. cachePath = configPath + ".models.dev.json" } - store := &PricingStore{ - models: make(map[string]Price), cachePath: cachePath, endpoint: modelsDevDefaultURL, - client: &http.Client{Timeout: modelsDevTimeout}, logger: logger, + store := &PricingRegistry{ + models: make(map[string]Price), cachePath: cachePath, endpoint: metadataDefaultURL, + client: &http.Client{Timeout: metadataTimeout}, logger: logger, } if err := store.loadCache(); err != nil && !errors.Is(err, os.ErrNotExist) { store.lastError = "load metadata cache: " + err.Error() @@ -90,15 +114,17 @@ func NewPricingStore(configPath string, logger *slog.Logger) *PricingStore { } // SetClientProvider supplies candidate HTTP clients for refresh attempts, most -// preferred first. It lets the periodic models.dev refresh ride the proxy +// preferred first. It lets the periodic OpenCode metadata refresh ride the proxy // transports exposed by whichever gateway runtime is currently active. -func (store *PricingStore) SetClientProvider(provider func() []*http.Client) { +func (store *PricingRegistry) SetClientProvider(provider func() []*http.Client) { store.mu.Lock() defer store.mu.Unlock() store.clientProvider = provider } -func (store *PricingStore) refreshClients() []*http.Client { +// refreshClients returns the provider's clients, or the registry's own direct +// client when no provider is set or it offers none. +func (store *PricingRegistry) refreshClients() []*http.Client { store.mu.RLock() provider := store.clientProvider store.mu.RUnlock() @@ -112,10 +138,13 @@ func (store *PricingStore) refreshClients() []*http.Client { return clients } -func (store *PricingStore) Start(ctx context.Context) { +// Start refreshes the metadata at once and then every metadataRefresh in the +// background until ctx ends. A failed refresh is logged and keeps the previous +// data. +func (store *PricingRegistry) Start(ctx context.Context) { go func() { store.refreshAndLog(ctx) - ticker := time.NewTicker(modelsDevRefresh) + ticker := time.NewTicker(metadataRefresh) defer ticker.Stop() for { select { @@ -128,19 +157,24 @@ func (store *PricingStore) Start(ctx context.Context) { }() } -func (store *PricingStore) refreshAndLog(ctx context.Context) { +func (store *PricingRegistry) refreshAndLog(ctx context.Context) { if err := store.Refresh(ctx); err != nil { if store.logger != nil { - store.logger.Warn("models.dev metadata refresh failed", "component", "models", "event", "metadata_refresh_failed", "error", err) + store.logger.Warn("OpenCode metadata refresh failed", "component", "models", "event", "metadata_refresh_failed", "error", err) } return } if store.logger != nil { - store.logger.Info("models.dev metadata refreshed", "component", "models", "event", "metadata_refreshed", "models", store.Snapshot().Models) + store.logger.Info("OpenCode metadata refreshed", "component", "models", "event", "metadata_refreshed", "models", store.Snapshot().Models) } } -func (store *PricingStore) Refresh(ctx context.Context) error { +// Refresh fetches the metadata, trying each refresh client in turn until one +// gets a 2xx response. That response is final: a decode or cache write error +// is returned without trying the remaining clients. The cache file is written +// before the in-memory data is replaced, so a failed write keeps the previous +// data. The final failure is also kept as LastError. +func (store *PricingRegistry) Refresh(ctx context.Context) error { var lastErr error for _, client := range store.refreshClients() { data, err := store.fetch(ctx, client) @@ -148,7 +182,7 @@ func (store *PricingStore) Refresh(ctx context.Context) error { lastErr = err continue } - models, err := decodeModelsDev(data) + models, err := decodeMetadata(data) if err != nil { return store.recordError(err) } @@ -165,39 +199,43 @@ func (store *PricingStore) Refresh(ctx context.Context) error { return nil } if lastErr == nil { - lastErr = errors.New("no HTTP client available for models.dev refresh") + lastErr = errors.New("no HTTP client available for OpenCode metadata refresh") } return store.recordError(lastErr) } -func (store *PricingStore) fetch(ctx context.Context, client *http.Client) ([]byte, error) { - refreshCtx, cancel := context.WithTimeout(ctx, modelsDevTimeout) +func (store *PricingRegistry) fetch(ctx context.Context, client *http.Client) ([]byte, error) { + refreshCtx, cancel := context.WithTimeout(ctx, metadataTimeout) defer cancel() req, err := http.NewRequestWithContext(refreshCtx, http.MethodGet, store.endpoint, nil) if err != nil { return nil, err } req.Header.Set("Accept", "application/json") - req.Header.Set("User-Agent", httpx.UserAgent()) + req.Header.Set("User-Agent", httpx.V2UserAgent()) resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() if resp.StatusCode/100 != 2 { - return nil, fmt.Errorf("models.dev returned HTTP %d", resp.StatusCode) + return nil, fmt.Errorf("OpenCode metadata endpoint returned HTTP %d", resp.StatusCode) } return io.ReadAll(io.LimitReader(resp.Body, 32<<20)) } -func (store *PricingStore) recordError(err error) error { +func (store *PricingRegistry) recordError(err error) error { store.mu.Lock() store.lastError = err.Error() store.mu.Unlock() return err } -func (store *PricingStore) Decide(model string) AnonymousDecision { +// Decide reports whether model counts as free. A name containing "free" in any +// case always qualifies. Otherwise the metadata must list the model, not +// deprecated, at zero input and output cost; until the metadata is ready only +// the name rule applies. +func (store *PricingRegistry) Decide(model string) AnonymousDecision { store.mu.RLock() price, exists := store.models[model] ready := !store.updatedAt.IsZero() && len(store.models) > 0 @@ -244,27 +282,31 @@ func (store *PricingStore) Decide(model string) AnonymousDecision { return decision } -func (store *PricingStore) Price(model string) (Price, bool) { +// Price returns the metadata of model and whether the metadata lists it. +func (store *PricingRegistry) Price(model string) (Price, bool) { store.mu.RLock() defer store.mu.RUnlock() price, ok := store.models[model] return price, ok } -func (store *PricingStore) Snapshot() MetadataSnapshot { +// Snapshot reports the freshness of the metadata; see MetadataSnapshot. +func (store *PricingRegistry) Snapshot() MetadataSnapshot { store.mu.RLock() defer store.mu.RUnlock() snapshot := MetadataSnapshot{Ready: !store.updatedAt.IsZero() && len(store.models) > 0, Models: len(store.models), LastError: store.lastError, CachePath: store.cachePath} if !store.updatedAt.IsZero() { updated := store.updatedAt.UTC() - next := updated.Add(modelsDevRefresh) + next := updated.Add(metadataRefresh) snapshot.UpdatedAt, snapshot.NextRefresh = &updated, &next - snapshot.Stale = time.Since(updated) > modelsDevRefresh + snapshot.Stale = time.Since(updated) > metadataRefresh } return snapshot } -func (store *PricingStore) loadCache() error { +// loadCache installs the cache file. It takes no lock, so it must only run +// while PricingStore constructs the registry. +func (store *PricingRegistry) loadCache() error { if store.cachePath == "" { return nil } @@ -285,10 +327,15 @@ func (store *PricingStore) loadCache() error { return nil } -func decodeModelsDev(data []byte) (map[string]Price, error) { +// decodeMetadata extracts a Price for every model of the OpenCode providers in +// the metadata endpoint's provider map. The opencode, opencode-zen and +// opencode_zen entries rank first; any other provider whose key contains +// "opencode" is read only when its id or name does too, and every other +// provider is ignored. It fails when no OpenCode model is found. +func decodeMetadata(data []byte) (map[string]Price, error) { var providers map[string]json.RawMessage if err := json.Unmarshal(data, &providers); err != nil { - return nil, fmt.Errorf("decode models.dev: %w", err) + return nil, fmt.Errorf("decode OpenCode metadata: %w", err) } keys := make([]string, 0, len(providers)) for key := range providers { @@ -337,9 +384,12 @@ func decodeModelsDev(data []byte) (map[string]Price, error) { if len(result) > 0 { return result, nil } - return nil, errors.New("models.dev contains no OpenCode model metadata") + return nil, errors.New("OpenCode metadata contains no OpenCode models") } +// metadataProviderRank orders metadata provider keys: 0 for opencode, +// opencode-zen and opencode_zen, 1 for any other key containing "opencode", +// and 2 for the providers decodeMetadata ignores. func metadataProviderRank(key string) int { lower := strings.ToLower(key) if lower == "opencode" || lower == "opencode-zen" || lower == "opencode_zen" { @@ -363,6 +413,9 @@ func numberPointer(object map[string]any, key string) *float64 { return &number } +// metadataDeprecated reports whether a metadata model is flagged deprecated, +// carries a deprecated, retired or disabled status or lifecycle, or names a +// deprecation or retirement date. func metadataDeprecated(model map[string]any) bool { if jsonutil.BoolAt(model, "deprecated") { return true @@ -374,6 +427,9 @@ func metadataDeprecated(model map[string]any) bool { return model["deprecated_at"] != nil || model["retirement_date"] != nil } +// saveMetadataCache writes cache through a 0600 temporary file and a rename. +// On Windows the existing file is first moved to path+".replace" and put back +// if the final rename fails. func saveMetadataCache(path string, cache modelMetadataCache) error { data, err := json.MarshalIndent(cache, "", " ") if err != nil { diff --git a/internal/protocol/bridge.go b/internal/protocol/bridge.go index bf1dbac..ef8814d 100644 --- a/internal/protocol/bridge.go +++ b/internal/protocol/bridge.go @@ -6,13 +6,25 @@ import ( "opencode2api/internal/jsonutil" ) +// Placeholder reasoning texts. toolReasoningPlaceholder fills the reasoning a +// tool-call turn is missing, and anthropicRedactedThinkingPlaceholder stands +// in for encrypted reasoning wherever a readable text is required. const ( toolReasoningPlaceholder = "tool call" anthropicRedactedThinkingPlaceholder = "[redacted thinking]" ) +// reasoningVendorHints are substrings of a model ID or upstream URL that +// identify the reasoning vendors whose endpoints reject tool-call turns +// without reasoning history (see normalizeToolReasoningHistory). var reasoningVendorHints = [...]string{"moonshot", "kimi", "deepseek", "mimo", "xiaomimimo"} +// bridgeBlock is one content block of the protocol-neutral bridge model. Kind +// is "text", "image", "file", "reasoning", "tool_call" or "tool_result", and +// only the fields that kind uses are set. A tool call carries its input as +// decoded Arguments (from Anthropic) or as raw ArgumentsJSON (from Chat and +// Responses). A tool result's Result is the client's raw content, or a +// []bridgeBlock once decodeToolImages has parsed images out of it. type bridgeBlock struct { Kind string Text string @@ -44,11 +56,20 @@ type bridgeTool struct { Strict bool } +// bridgeToolChoice is a decoded tool_choice. Mode is "auto", "none", +// "required" or "named" (with Name set), or empty when the client chose +// nothing; a mode the target protocol cannot express is not encoded. type bridgeToolChoice struct { Mode string Name string } +// bridgeRequest is a client request decoded into the protocol-neutral form +// every request encoder reads. System and Developer instructions stay apart so +// the Chat and Responses encoders can keep them distinct; the Anthropic +// encoder merges them. Reasoning holds the client's reasoning controls as an +// opaque value that reasoningEffort, responsesReasoning and anthropicThinking +// project onto each target. type bridgeRequest struct { Model string System []bridgeBlock @@ -64,25 +85,35 @@ type bridgeRequest struct { Reasoning any Metadata any // Sampling and response-shape knobs are carried across the bridge as - // opaque values. Each protocol accepts a different shape, so a value that - // cannot be expressed natively is omitted rather than rejected: dropping a - // knob silently was the old behavior and it made clients believe (for - // example) that JSON mode had been honored. + // opaque values. The bridge used to drop them all, which made clients + // believe (for example) that JSON mode had been honored. Each encoder now + // re-emits the knobs its protocol can express: ResponseFormat and + // ParallelToolCalls for Chat and Responses, the two penalties and Seed for + // Chat only. A knob or format the target cannot express is omitted rather + // than rejected, and the Anthropic encoder emits none of them. ResponseFormat any ParallelToolCalls any FrequencyPenalty any PresencePenalty any Seed any - // Native-fidelity knobs decoded from the client body and re-emitted - // upstream. prompt_cache_key is the big one: native opencode sends the - // session-sliced ID here and rides prompt-cache affinity; without it - // every proxied turn pays full attention over the whole history. + // Native-fidelity knobs, decoded from Chat and Responses bodies and + // re-emitted only by the Chat and Responses encoders; the Anthropic + // decoder and encoder ignore them. prompt_cache_key is the big one: native + // OpenCode sends the session-sliced ID here and rides prompt-cache + // affinity; without it every proxied turn pays full attention over the + // whole history. PromptCacheKey any SafetyIdentifier any ServiceTier any Store any } +// Usage is the token accounting of one response in bridge form. Decoders +// normalize each protocol's usage object into it and encoders split it back +// out. Output is the completion output, Total the reported total (Input+Output +// when the upstream reports none), Cached and CacheCreation the cache-read and +// cache-write parts of Input, and Reasoning the reasoning tokens an +// OpenAI-style upstream reports as part of Output. type Usage struct { // Input is the total prompt input, including cache reads and writes. This // matches OpenAI's prompt_tokens semantics and lets each output encoder @@ -95,6 +126,8 @@ type Usage struct { Reasoning int } +// bridgeResponse is a complete (non-streaming) response in protocol-neutral +// form, as decoded by decodeBridgeResponse or accumulated by CollapseStream. type bridgeResponse struct { ID string Model string @@ -107,6 +140,11 @@ type bridgeResponse struct { Created int64 } +// ConvertRequest converts a decoded client request body from one protocol to +// another. A same-protocol body is deep-cloned unchanged, so provider-specific +// fields survive; any other body is decoded into the bridge model and +// re-encoded for the target. The error reports content that is malformed or +// that the target protocol cannot represent. func ConvertRequest(from, to Protocol, input map[string]any) (map[string]any, error) { if from == to { return jsonutil.CloneMap(input), nil @@ -118,6 +156,9 @@ func ConvertRequest(from, to Protocol, input map[string]any) (map[string]any, er return encodeBridgeRequest(to, request) } +// normalizeResponsesRole maps a bridge message role onto a Responses message +// role: assistant stays, everything else becomes user. Bridge messages only +// ever carry user and assistant, so this is a guard rather than a conversion. func normalizeResponsesRole(role string) string { if role == "assistant" { return "assistant" @@ -125,6 +166,8 @@ func normalizeResponsesRole(role string) string { return "user" } +// schemaOrDefault substitutes an empty object schema for a tool that declared +// no parameters. func schemaOrDefault(value any) any { if value == nil { return map[string]any{"type": "object", "properties": map[string]any{}} @@ -191,14 +234,20 @@ func responsesTextFormat(format any) any { } // reasoningEffort projects a bridge-level reasoning value onto the OpenAI Chat -// "reasoning_effort" field. +// "reasoning_effort" field. A nil result omits the field. // -// Precedence matters: a level the client stated explicitly (the "effort" field, -// whether or not it arrived next to a thinking block) wins over anything -// inferred from a thinking budget. Before this, an Anthropic request carrying -// both thinking.budget_tokens and output_config.effort threw the explicit -// effort away and reported the budget bucket instead, so a client asking for -// "max" was served as "high". +// Precedence matters: a level the client stated explicitly (an "effort" or +// "reasoning_effort" key, whether or not it arrived next to a thinking block) +// wins over anything inferred from a thinking budget. Before this, an +// Anthropic request carrying both thinking.budget_tokens and +// output_config.effort threw the explicit effort away and reported the budget +// bucket instead, so a client asking for "max" was served as "high". +// +// Without a stated level, an object of type "disabled" yields nil, one of type +// "enabled"/"adaptive" the effortForThinkingBudget rung of its budget_tokens, +// and any other object its "type" value as the level (nil when it has none). A +// non-object value passes through unchanged, except that the strings "none" +// and "disabled" yield nil. func reasoningEffort(value any) any { if object, ok := value.(map[string]any); ok { if effort, ok := explicitEffort(object); ok { @@ -220,9 +269,11 @@ func reasoningEffort(value any) any { } // explicitEffort reports the effort a client stated verbatim in a reasoning -// object and whether the object carried one at all. A stated effort outranks a -// budget, including inside a thinking block that also has budget_tokens: -// budget 2048 plus effort "max" is a request for "max", not for "low". +// object and whether the object carried one at all. It looks at "effort" first +// and at "reasoning_effort" when "effort" states nothing; a key holding a blank +// or non-string value counts as stating nothing. A stated effort outranks a +// budget, including inside a thinking block that also has budget_tokens: budget +// 2048 plus effort "max" is a request for "max", not for "low". // // The second return is ok, not "effort != nil": the stated value nil means the // client named "none"/"disabled" explicitly, which must clear an inferred level @@ -239,10 +290,11 @@ func explicitEffort(object map[string]any) (any, bool) { } // normalizeEffortValue validates an effort a client stated explicitly. A -// non-empty string is passed through verbatim (case preserved) so unsupported +// non-blank string is passed through verbatim (case preserved) so unsupported // levels are not silently rewritten or dropped; only "none"/"disabled" mean -// "no reasoning" and clear the value. Everything else, nil included, reports -// ok=false so the caller can fall back to a budget-derived level. +// "no reasoning" and clear the value. Everything else, a blank string or any +// non-string value (nil included), reports ok=false so the caller can fall +// back to a budget-derived level. func normalizeEffortValue(value any) (any, bool) { text, ok := value.(string) if !ok { @@ -261,12 +313,15 @@ func normalizeEffortValue(value any) (any, bool) { // anthropicThinking maps a bridge-level reasoning value back onto the Anthropic // "thinking" block plus the "output_config" that carries the effort natively. +// Both are nil when the value disables reasoning or says nothing about it. // // The budget reproduced here keeps the Anthropic payload self-consistent and -// mirrors what the inverse direction (effortForThinkingBudget) reads back, so -// the two are inverse on every rung. A budget the client originally named is -// restored verbatim rather than re-derived from the level, so an Anthropic -> -// Chat -> Anthropic round trip does not rewrite 32000 into an 8192 rung. +// mirrors what the inverse direction (effortForThinkingBudget) reads back, so a +// synthesized budget maps back to the same level, except that "minimal" comes +// back as "low". A budget the client originally named is restored verbatim +// rather than re-derived from the level, so an Anthropic -> Chat -> Anthropic +// round trip does not rewrite 32000 into 16384, the budget budgetForEffort +// synthesizes for the "xhigh" rung 32000 falls on. // // The emitted number is a float64 because that is the shape a decoded JSON // number has, which keeps converted payloads indistinguishable from the ones @@ -281,7 +336,7 @@ func anthropicThinking(value any) (any, map[string]any) { // A budget is what makes the round trip lossless, so it is read before // the effort: a value that reached the bridge as a thinking block still // names the budget the client sent, and re-deriving one from the level - // would fold 32000 back down to the 16384 rung. + // would fold 32000 back down to 16384, the budget of its "xhigh" rung. budget = jsonutil.IntAt(object, "budget_tokens") if effort, stated := explicitEffort(object); stated { // "none"/"disabled" clears the reasoning configuration entirely. @@ -293,8 +348,15 @@ func anthropicThinking(value any) (any, map[string]any) { if kind == "disabled" { return nil, nil } - // A level carried in "type" (Chat's {"reasoning":{"type":"high"}}), or a - // one-sided {"type":"enabled"} whose only control is its budget. + // "enabled"/"adaptive" are thinking modes, not levels: the level comes + // from the budget, as in reasoningEffort, and a missing budget means + // "high". Passing the mode through would send output_config.effort + // "enabled", which no upstream accepts. + if kind == "enabled" || kind == "adaptive" { + effort := effortForThinkingBudget(budget) + return thinkingFor(effort, budget), map[string]any{"effort": effort} + } + // A level carried in "type", as in Chat's {"reasoning":{"type":"high"}}. if effort, stated := normalizeEffortValue(object["type"]); stated { if effort == nil { return nil, nil @@ -310,8 +372,8 @@ func anthropicThinking(value any) (any, map[string]any) { effort, ok := normalizeEffortValue(value) if !ok { if number, isNumber := numericValue(value); isNumber { - // A reasoning value that only carries a budget: keep the budget and - // publish the level it maps to, so no rung is invented. + // A bare number is a budget: keep it and publish the level it maps + // to, so no rung is invented. if number <= 0 { return nil, nil } @@ -330,8 +392,8 @@ func anthropicThinking(value any) (any, map[string]any) { } // thinkingFor builds the Anthropic "thinking" block for an effort, reusing the -// budget the client named when there is one and synthesizing the rung's -// lower bound otherwise. +// budget the client named when there is one and synthesizing the level's +// budgetForEffort budget otherwise. func thinkingFor(effort any, budget int) map[string]any { if budget <= 0 { budget = budgetForEffort(effort) @@ -340,7 +402,15 @@ func thinkingFor(effort any, budget int) map[string]any { } // reasoningBudget reports the thinking budget a bridge-level reasoning value -// names, or 0 when the value carries none. +// names, or 0 when the value carries none. Only an object can name one: a bare +// effort string states a level, not a budget, and a bare number is not read as +// a budget here (only anthropicThinking treats it as one). +// +// The budget is normally the object's budget_tokens, which holds both an +// Anthropic thinking budget and one the Chat decoder read back from an +// assistant message's reasoning_budget_tokens. An object without it may still +// name a budget under its own "reasoning_budget_tokens" key, but that key is +// read only when the object also states an effort. func reasoningBudget(value any) int { object, ok := value.(map[string]any) if !ok { @@ -352,13 +422,14 @@ func reasoningBudget(value any) int { if _, ok := explicitEffort(object); !ok { return 0 } - // An effort states a level, not a budget. A Chat client that sends only - // {"reasoning_effort":"high"} has no budget to carry. + // A stated effort may carry its budget under the Chat field name. return numericValueOrZero(object["reasoning_budget_tokens"]) } // withReasoningBudget attaches a budget to a bridge-level reasoning value, -// keeping any effort already present alongside it. +// keeping any effort already present alongside it: an object is copied with +// budget_tokens set, and any other value becomes the "effort" of a new object. +// A non-positive budget leaves the value unchanged. func withReasoningBudget(value any, budget int) any { if budget <= 0 { return value @@ -376,8 +447,9 @@ func withReasoningBudget(value any, budget int) any { } } -// numericValue reads a JSON number out of a decoded body, which reports every -// number as float64. +// numericValue reads a number as an int, truncating any fraction. A decoded +// JSON body reports every number as float64; int and int64 are accepted too, +// so a value built in Go rather than decoded is read as well. func numericValue(value any) (int, bool) { switch number := value.(type) { case float64: @@ -391,15 +463,19 @@ func numericValue(value any) (int, bool) { } } +// numericValueOrZero is numericValue with a zero for anything that is not a +// number. func numericValueOrZero(value any) int { number, _ := numericValue(value) return number } -// budgetForEffort is the inverse of effortForThinkingBudget: the smallest -// lower-bound budget that maps back to the same rung. Only "high" and above -// need a real number, since Anthropic requires budget_tokens to be at least -// 1024 and a top-of-range budget already means "max". +// budgetForEffort synthesizes a thinking budget for a level when an Anthropic +// body needs one the client never named: "minimal" and "low" get 1024 (the +// smallest budget_tokens Anthropic accepts), "medium" 4096, "high" 8192, +// "xhigh" 16384 and "max" 32768. It is the inverse of effortForThinkingBudget: +// each budget maps back to its own level, except that "minimal" comes back as +// "low". Any other value gets the "medium" budget. func budgetForEffort(value any) int { text, _ := value.(string) switch strings.ToLower(strings.TrimSpace(text)) { @@ -419,16 +495,18 @@ func budgetForEffort(value any) int { } // effortForThinkingBudget buckets an Anthropic thinking budget onto an OpenAI -// reasoning level. The rungs are ordered and pairwise distinct so that a -// budget a client chose deliberately stays distinguishable: before this, -// everything at or above 8192 collapsed to "high" and the ladder had no rung -// above it, so 32000 and 8192 were indistinguishable and an Anthropic -> Chat -// -> Anthropic round trip rewrote 32000 into 8192. +// reasoning level: a positive budget up to 2048 is "low", 2049..8191 +// "medium", 8192..16383 "high", 16384..32767 "xhigh" and 32768 or more +// "max". The rungs are ordered and pairwise distinct so that a budget a client +// chose deliberately stays distinguishable: before this, everything at or +// above 8192 collapsed to "high" and the ladder had no rung above it, so 32000 +// and 8192 were indistinguishable and an Anthropic -> Chat -> Anthropic round +// trip rewrote 32000 into 8192. // // A missing budget keeps the historical "high": thinking:{type:"adaptive"} // with no budget_tokens is the common shape, and it must not silently change -// level. An explicit "max"/"xhigh" effort is how a client asks for a rung -// above "high", and that path does not consult the budget. +// level. A client that wants a higher rung states "xhigh" or "max" explicitly, +// and that level is taken as stated instead of being derived from a budget. func effortForThinkingBudget(budget int) string { switch { case budget <= 0: @@ -438,8 +516,8 @@ func effortForThinkingBudget(budget int) string { case budget >= 16384: return "xhigh" case budget > 8192: - // 8193..16383 sits above the old "high" boundary; folding it into - // "high" would report a larger budget as the same level. + // 8193..16383 is still "high": the "xhigh" rung starts at 16384, the + // budget budgetForEffort synthesizes for it. return "high" case budget >= 8192: // The threshold itself keeps its historical bucket. @@ -451,6 +529,8 @@ func effortForThinkingBudget(budget int) string { } } +// bridgeBlocksText concatenates the text of the "text" blocks and ignores +// every other kind. func bridgeBlocksText(blocks []bridgeBlock) string { var text strings.Builder for _, block := range blocks { @@ -461,6 +541,10 @@ func bridgeBlocksText(blocks []bridgeBlock) string { return text.String() } +// asPrefix returns id in the target protocol's ID style, prefix plus "_". An +// id that already has that prefix is returned unchanged; otherwise any +// "chatcmpl_", "resp_" or "msg_" prefix is stripped first, so one upstream ID +// maps consistently onto every protocol. func asPrefix(id, prefix string) string { if strings.HasPrefix(id, prefix+"_") { return id diff --git a/internal/protocol/collapse.go b/internal/protocol/collapse.go index b89ad2c..529296d 100644 --- a/internal/protocol/collapse.go +++ b/internal/protocol/collapse.go @@ -13,7 +13,10 @@ import ( // // It exists for upstream lanes that only serve streaming responses: the // gateway forces stream:true on the wire and collapses the events back so -// downstream clients that asked for a plain JSON reply keep working. +// downstream clients that asked for a plain JSON reply keep working. model is +// the response's model name unless the stream's start event names one. A +// stream that reports an error, cannot be parsed or ends without a terminal +// event is an error. func CollapseStream(reader io.Reader, protocol Protocol, model string) ([]byte, error) { parser := &bridgeStreamParser{ protocol: protocol, @@ -63,12 +66,18 @@ func CollapseStream(reader io.Reader, protocol Protocol, model string) ([]byte, return json.Marshal(encodeBridgeResponse(protocol, acc.response)) } +// collapseAccumulator folds bridge stream events into one bridgeResponse. +// tools maps a stream tool key to its index in response.Tools, and reason +// points at the reasoning block currently accepting deltas, if any. type collapseAccumulator struct { response bridgeResponse tools map[string]int reason *bridgeBlock } +// apply folds one stream event into the response. Reasoning text and +// signatures accumulate into the open reasoning block, while encrypted +// reasoning is stored in a block of its own that is closed at once. func (acc *collapseAccumulator) apply(event bridgeStreamEvent) { switch event.Kind { case "start": @@ -106,9 +115,9 @@ func (acc *collapseAccumulator) apply(event bridgeStreamEvent) { } } -// reasoningBlock returns the reasoning block deltas accumulate into, -// starting a fresh one when the previous block already carries encrypted -// content (a different item on the wire). +// reasoningBlock returns the open reasoning block that deltas accumulate into, +// appending a new one when none is open: before the first reasoning event, and +// after an encrypted event or splitReasoning has closed the previous block. func (acc *collapseAccumulator) reasoningBlock() *bridgeBlock { if acc.reason == nil { acc.response.Reasoning = append(acc.response.Reasoning, bridgeBlock{Kind: "reasoning"}) @@ -117,10 +126,14 @@ func (acc *collapseAccumulator) reasoningBlock() *bridgeBlock { return acc.reason } +// splitReasoning closes the open reasoning block, so the next reasoning delta +// starts a new one. func (acc *collapseAccumulator) splitReasoning() { acc.reason = nil } +// toolBlock returns the tool call for a stream tool key, appending it on first +// sight and filling in an ID or name that earlier events lacked. func (acc *collapseAccumulator) toolBlock(key, id, name string) *bridgeBlock { if index, ok := acc.tools[key]; ok { block := &acc.response.Tools[index] @@ -137,6 +150,7 @@ func (acc *collapseAccumulator) toolBlock(key, id, name string) *bridgeBlock { return &acc.response.Tools[len(acc.response.Tools)-1] } +// firstNonEmpty returns the first non-empty string, or "". func firstNonEmpty(values ...string) string { for _, value := range values { if value != "" { diff --git a/internal/protocol/content.go b/internal/protocol/content.go index c176240..49644d2 100644 --- a/internal/protocol/content.go +++ b/internal/protocol/content.go @@ -10,11 +10,11 @@ import ( "opencode2api/internal/jsonutil" ) -func decodeOpenAIBlocks(value any) []bridgeBlock { - blocks, _ := decodeOpenAIBlocksChecked(value) - return blocks -} - +// decodeOpenAIBlocksChecked decodes Chat or Responses content into bridge +// blocks. It accepts a plain string, a single part object or an array of +// parts; nil and "" decode to no blocks. Text, image and file parts of either +// protocol are recognized, and any other part type is an error rather than +// being dropped. func decodeOpenAIBlocksChecked(value any) ([]bridgeBlock, error) { switch value := value.(type) { case string: @@ -60,11 +60,10 @@ func decodeOpenAIBlocksChecked(value any) ([]bridgeBlock, error) { } } -func decodeAnthropicBlocks(value any) []bridgeBlock { - blocks, _ := decodeAnthropicBlocksChecked(value) - return blocks -} - +// decodeAnthropicBlocksChecked decodes Anthropic content (a string, a single +// block or an array of blocks) into bridge blocks. thinking and +// redacted_thinking become reasoning blocks, a text document becomes plain +// text and any other document a file, and an unknown block type is an error. func decodeAnthropicBlocksChecked(value any) ([]bridgeBlock, error) { if text, ok := value.(string); ok { if text == "" { @@ -130,6 +129,10 @@ func decodeAnthropicBlocksChecked(value any) ([]bridgeBlock, error) { return blocks, nil } +// decodeChatReasoning reads a Chat message's reasoning into one block: the +// reasoning_content string, or the "reasoning" string when reasoning_content +// is absent, together with any reasoning_signature. A present but empty string +// still yields a block; a missing or non-string value yields none. func decodeChatReasoning(message map[string]any) []bridgeBlock { value, exists := message["reasoning_content"] if !exists { @@ -146,6 +149,10 @@ func decodeChatReasoning(message map[string]any) []bridgeBlock { }} } +// decodeResponsesReasoning folds a Responses reasoning item into one block: +// its summary and content texts are concatenated, and its ID and +// encrypted_content are kept. An item with neither text nor encrypted content +// yields no block. func decodeResponsesReasoning(item map[string]any) []bridgeBlock { var text strings.Builder for _, raw := range jsonutil.AsSlice(item["summary"]) { @@ -182,6 +189,9 @@ func encodeResponsesReasoningInput(block bridgeBlock) (map[string]any, bool) { return encodeResponsesReasoning(block, false), true } +// encodeResponsesReasoning renders a reasoning block as a Responses reasoning +// item with its text as the summary, synthesizing an ID when the block has +// none. completed adds the "completed" status a response output item carries. func encodeResponsesReasoning(block bridgeBlock, completed bool) map[string]any { id := block.ID if id == "" { @@ -201,6 +211,10 @@ func encodeResponsesReasoning(block bridgeBlock, completed bool) map[string]any return item } +// bridgeReasoningText joins reasoning blocks into the single text Chat's +// reasoning_content holds, using a placeholder for a block that carries only +// encrypted content. ok is false only when there are no blocks, so reasoning +// that is present but empty still produces the field. func bridgeReasoningText(blocks []bridgeBlock) (string, bool) { if len(blocks) == 0 { return "", false @@ -216,6 +230,8 @@ func bridgeReasoningText(blocks []bridgeBlock) (string, bool) { return text.String(), true } +// bridgeReasoningSignature returns the signature of the last signed reasoning +// block, or "" when no block is signed. func bridgeReasoningSignature(blocks []bridgeBlock) string { for i := len(blocks) - 1; i >= 0; i-- { if blocks[i].Signature != "" { @@ -225,6 +241,10 @@ func bridgeReasoningSignature(blocks []bridgeBlock) string { return "" } +// encodeChatBlocks renders blocks as Chat message content: a lone text block +// becomes a plain string and anything else an array of text, image_url and +// file parts. Inline image data becomes a data URI, and kinds Chat content +// cannot hold (reasoning, tool calls and results) are skipped. func encodeChatBlocks(blocks []bridgeBlock) any { if len(blocks) == 1 && blocks[0].Kind == "text" { return blocks[0].Text @@ -251,6 +271,11 @@ func encodeChatBlocks(blocks []bridgeBlock) any { return parts } +// encodeAnthropicBlocks renders blocks as Anthropic content blocks. A file +// with neither a URL nor inline data has no Anthropic source and is skipped +// (validateBridgeRequest rejects one known only by file_id up front), +// encrypted reasoning becomes redacted_thinking, and a tool result that +// decodeToolImages parsed is re-encoded block by block. func encodeAnthropicBlocks(blocks []bridgeBlock) []any { parts := make([]any, 0, len(blocks)) for _, block := range blocks { @@ -299,6 +324,9 @@ func encodeAnthropicBlocks(blocks []bridgeBlock) []any { return parts } +// bridgeArgumentsJSON returns a tool call's arguments as JSON text: the raw +// ArgumentsJSON when set, else Arguments marshaled, and "{}" when there are +// none or they cannot be marshaled. func bridgeArgumentsJSON(block bridgeBlock) string { if block.ArgumentsJSON != "" { return block.ArgumentsJSON @@ -313,6 +341,9 @@ func bridgeArgumentsJSON(block bridgeBlock) string { return string(data) } +// bridgeToolResultContent flattens a tool result into a string: a string as +// is, an array made only of text parts as their joined text, and anything else +// as its JSON encoding ("" when it cannot be marshaled). func bridgeToolResultContent(value any) string { if text, ok := value.(string); ok { return text @@ -339,6 +370,8 @@ func bridgeToolResultContent(value any) string { return string(data) } +// decodeChatToolChoice maps a Chat tool_choice onto the bridge. A string is +// the mode as is; a function object is a named choice. func decodeChatToolChoice(value any) bridgeToolChoice { if mode, ok := value.(string); ok { return bridgeToolChoice{Mode: mode} @@ -350,6 +383,9 @@ func decodeChatToolChoice(value any) bridgeToolChoice { return bridgeToolChoice{} } +// decodeResponsesToolChoice maps a Responses tool_choice onto the bridge. A +// string is the mode as is; a function object is a named choice, whose name +// sits at the top level rather than nested as in Chat. func decodeResponsesToolChoice(value any) bridgeToolChoice { if mode, ok := value.(string); ok { return bridgeToolChoice{Mode: mode} @@ -361,6 +397,9 @@ func decodeResponsesToolChoice(value any) bridgeToolChoice { return bridgeToolChoice{} } +// decodeAnthropicToolChoice maps an Anthropic tool_choice onto the bridge, +// where Anthropic's "any" is "required" and "tool" is a named choice. A bare +// string is read as the type, with OpenAI's "required" accepted for "any". func decodeAnthropicToolChoice(value any) bridgeToolChoice { if mode, ok := value.(string); ok { if mode == "required" { @@ -383,6 +422,8 @@ func decodeAnthropicToolChoice(value any) bridgeToolChoice { } } +// encodeChatToolChoice renders a bridge tool choice for Chat, nesting the name +// under a function object. It returns nil for an empty or unknown mode. func encodeChatToolChoice(choice bridgeToolChoice) any { switch choice.Mode { case "named": @@ -394,6 +435,8 @@ func encodeChatToolChoice(choice bridgeToolChoice) any { } } +// encodeResponsesToolChoice renders a bridge tool choice for Responses, with +// the name at the top level. It returns nil for an empty or unknown mode. func encodeResponsesToolChoice(choice bridgeToolChoice) any { switch choice.Mode { case "named": @@ -405,6 +448,10 @@ func encodeResponsesToolChoice(choice bridgeToolChoice) any { } } +// encodeAnthropicToolChoice renders a bridge tool choice for Anthropic. It +// returns nil for "none", which Anthropic cannot express; +// encodeAnthropicRequest omits the tools instead. It also returns nil for an +// empty or unknown mode. func encodeAnthropicToolChoice(choice bridgeToolChoice) any { switch choice.Mode { case "named": diff --git a/internal/protocol/errors.go b/internal/protocol/errors.go index 369243c..5a0780e 100644 --- a/internal/protocol/errors.go +++ b/internal/protocol/errors.go @@ -6,6 +6,11 @@ import ( "opencode2api/internal/httpx" ) +// WriteError writes a JSON error response with the given status in the +// envelope the protocol's clients expect: {"type":"error","error":{...}} for +// Anthropic, and the OpenAI {"error":{message,type,param,code}} shape for +// every other protocol, System One included. kind becomes the error type, and +// a non-empty requestID is echoed in the x-request-id header. func WriteError(w http.ResponseWriter, protocol Protocol, status int, message, kind, requestID string) { w.Header().Set("Content-Type", "application/json") if requestID != "" { diff --git a/internal/protocol/protocol.go b/internal/protocol/protocol.go index 5adad72..076a71c 100644 --- a/internal/protocol/protocol.go +++ b/internal/protocol/protocol.go @@ -1,24 +1,42 @@ -// Package protocol translates Chat, Responses, and Anthropic payloads and -// streams, and carries the opaque System One decision payloads. +// Package protocol converts request bodies, response bodies and SSE streams +// between the OpenAI Chat Completions, OpenAI Responses and Anthropic Messages +// protocols through a shared bridge model. +// +// System One is recognized but never translated: Valid accepts it, Path maps +// it to its endpoint and WriteError gives it the OpenAI error envelope. It has +// no bridge encoding, so a cross-protocol conversion fails, and the gateway +// forwards its decision payloads verbatim. package protocol +// Protocol names the wire protocol of a client-facing endpoint or of an +// upstream model. type Protocol string +// The protocol constants name the wire protocol of a client endpoint or an +// upstream model, and each is both: the gateway serves a request in the +// client's protocol and speaks the route's protocol upstream, converting +// between the two when they differ. Chat is OpenAI Chat Completions, Responses +// is OpenAI Responses, Anthropic is Anthropic Messages, and SystemOne is +// described below. const ( Chat Protocol = "chat" Responses Protocol = "responses" Anthropic Protocol = "anthropic" // SystemOne is OpenCode Zen's structured decision endpoint. A request pairs // a free-form state with typed questions and the reply carries typed - // answers, so the payload shares no shape with the chat/responses bridge and - // is forwarded as-is. + // answers, so the payload shares no shape with the message protocols the + // bridge converts and is forwarded as-is. SystemOne Protocol = "systemone" ) +// Valid reports whether p is one of the protocols defined above. func Valid(p Protocol) bool { return p == Chat || p == Responses || p == Anthropic || p == SystemOne } +// Path returns the endpoint path that serves a protocol, relative to an API +// base. The gateway's own routes and the upstream endpoints share these +// paths. An unknown protocol gets the Chat path. func Path(protocol Protocol) string { switch protocol { case Responses: diff --git a/internal/protocol/request.go b/internal/protocol/request.go index a51dcba..5b4c27e 100644 --- a/internal/protocol/request.go +++ b/internal/protocol/request.go @@ -13,7 +13,8 @@ import ( // pass-through and transcoded requests. Same-protocol requests are cloned so // provider-specific fields survive, while cross-protocol requests go through // the bridge. Target-protocol normalization then repairs reasoning history in -// either case. +// either case, using the model and upstreamURL to recognize reasoning +// vendors, and a Responses body has its max_output_tokens floored. func PrepareRequest(from, to Protocol, input map[string]any, upstreamURL string) (map[string]any, error) { output, err := ConvertRequest(from, to, input) if err != nil { @@ -30,14 +31,19 @@ func PrepareRequest(from, to Protocol, input map[string]any, upstreamURL string) // ForcedEffort applies an operator-configured thinking level to a prepared // upstream body, so a client can be served at a fixed level without the client -// cooperating. +// cooperating. A level validForcedEffort rejects is ignored, and "none" +// removes the reasoning configuration instead of setting a level. // -// A level the client stated explicitly always wins. That is what the "forced" -// level is for: replacing a level nobody actually asked for, either because the -// request said nothing about reasoning or because the conversion had to derive -// one from thinking.budget_tokens. It is applied to the finished upstream body -// rather than to the bridge value because the same-protocol path never goes -// through the bridge, and only there can the client's own body be seen. +// A level already present in the body always wins (see clientEffortExplicit). +// The forced level fills in only where the body carries no level in the slot +// that protocol's encoder writes, such as a request that said nothing about +// reasoning, or a same-protocol Anthropic request whose thinking block names +// only a budget; that budget is then rewritten to the forced level's. A body +// the bridge converted has that slot filled whenever it derived a level from +// thinking.budget_tokens, so the derived level counts as present and is kept. +// The level is applied to the finished upstream body rather than to the bridge +// value because a same-protocol request is cloned and never passes through the +// bridge; the body is the one place both paths share. func ForcedEffort(protocol Protocol, body map[string]any, effort string) { if body == nil { return @@ -79,14 +85,17 @@ func ForcedEffort(protocol Protocol, body map[string]any, effort string) { } } -// clientEffortExplicit reports whether an upstream body already carries a level -// the client stated, as opposed to one the gateway derived from a budget. +// clientEffortExplicit reports whether an upstream body already carries a +// level in its protocol's native slot, which a forced level must not replace. // // The shapes differ per protocol, and each one mirrors how that protocol -// expressed the level natively: Anthropic states it in output_config.effort (or -// a top-level effort), Chat in a bare reasoning_effort string, and Responses in -// reasoning.effort. Anything else in those slots is a structural value the -// conversion produced, which a forced level is allowed to replace. +// expresses the level natively: Anthropic in a non-blank output_config.effort +// (or top-level effort) string, Chat in a reasoning_effort string, and +// Responses in a reasoning.effort string. The check is structural: a string +// value counts (and for Anthropic must not be blank), so it cannot tell a level +// the client stated from one the converter derived from a budget, because the +// converter writes both as strings. A missing or non-string value counts as no +// level. func clientEffortExplicit(protocol Protocol, body map[string]any) bool { switch protocol { case Chat: @@ -112,7 +121,8 @@ func clientEffortExplicit(protocol Protocol, body map[string]any) bool { // Anthropic represents a level as output_config.effort, but also requires a // thinking block to carry a budget and requires max_tokens to exceed that // budget. Forcing a level therefore has to move all three together, or the -// upstream rejects the request it was just told to run at a higher level. +// upstream rejects the request it was just told to run at a higher level. With +// disable set, the thinking block and output_config are removed instead. func applyAnthropicForcedEffort(body map[string]any, effort string, disable bool) { if disable { delete(body, "thinking") @@ -149,10 +159,13 @@ func validForcedEffort(effort string) bool { } } -// normalizeToolReasoningHistory applies only to endpoints that are known to -// require reasoning replay, or to requests that explicitly enable reasoning. -// Normalizing the target shape makes the behavior independent of the client -// protocol used to reach the gateway. +// normalizeToolReasoningHistory repairs the reasoning history of assistant +// tool-call turns in a prepared upstream body and reports whether it changed +// anything. It applies only to endpoints that are known to require reasoning +// replay, identified by the model or upstream URL naming a reasoning vendor; +// a Chat body is also repaired when the request explicitly enables reasoning. +// Responses bodies are never touched. Normalizing the target shape makes the +// behavior independent of the client protocol used to reach the gateway. func normalizeToolReasoningHistory(protocol Protocol, model, upstreamURL string, input map[string]any) bool { vendor := isReasoningVendorIdentifier(model) || isReasoningVendorIdentifier(upstreamURL) widened := vendor || requestEnablesReasoning(input) @@ -181,6 +194,8 @@ func normalizeToolReasoningHistory(protocol Protocol, model, upstreamURL string, } } +// isReasoningVendorIdentifier reports whether a model ID or upstream URL +// contains one of the reasoningVendorHints, ignoring case. func isReasoningVendorIdentifier(value string) bool { value = strings.ToLower(value) for _, hint := range reasoningVendorHints { @@ -191,6 +206,11 @@ func isReasoningVendorIdentifier(value string) bool { return false } +// requestEnablesReasoning reports whether a body's reasoning_effort, +// reasoning, thinking or effort field asks for reasoning. A string counts +// unless it is blank, "none" or "disabled"; a bool counts when true; an object +// counts unless its type (or, without one, its effort) is "none" or +// "disabled"; any other non-null value counts. func requestEnablesReasoning(input map[string]any) bool { for _, key := range []string{"reasoning_effort", "reasoning", "thinking", "effort"} { value, exists := input[key] @@ -223,7 +243,8 @@ func requestEnablesReasoning(input map[string]any) bool { // normalizeChatToolReasoningHistory ensures every assistant tool-call turn // carries reasoning_content. Some clients discard this non-standard field // while retaining tool_calls, which otherwise makes the next thinking-mode -// request invalid. A legacy reasoning string is promoted when available. +// request invalid. A legacy reasoning string is promoted when available, and a +// placeholder is used otherwise. It reports whether any message changed. func normalizeChatToolReasoningHistory(input map[string]any) bool { messages, ok := input["messages"].([]any) if !ok { @@ -252,7 +273,10 @@ func normalizeChatToolReasoningHistory(input map[string]any) bool { // normalizeAnthropicToolThinkingHistory repairs only assistant turns that // contain tool_use. DeepSeek, Kimi/Moonshot and MiMo reject signed, redacted, // empty or missing thinking history on those turns even though Anthropic -// clients can legitimately send each of those shapes. +// clients can legitimately send each of those shapes. It strips thinking +// signatures, replaces redacted_thinking blocks and empty thinking text with +// placeholders, and prepends a placeholder thinking block to a turn that has +// none. It reports whether any message changed. func normalizeAnthropicToolThinkingHistory(input map[string]any) bool { messages, ok := input["messages"].([]any) if !ok { @@ -309,6 +333,8 @@ func normalizeAnthropicToolThinkingHistory(input map[string]any) bool { return changed } +// anthropicContentHasType reports whether any block of an Anthropic content +// array has the given type. func anthropicContentHasType(content []any, kind string) bool { for _, rawBlock := range content { block, _ := rawBlock.(map[string]any) @@ -326,7 +352,9 @@ func anthropicContentHasType(content []any, kind string) bool { // Choosing input["thinking"] first (as this used to) shadowed // output_config.effort and a top-level effort entirely, so `thinking: // {adaptive}` plus `output_config: {effort: "max"}` decoded as the thinking -// block and was reported downstream as the budget bucket "high". +// block and was reported downstream as the budget bucket "high". A stated +// "none"/"disabled" decodes as no reasoning at all, even next to a thinking +// block. func anthropicReasoning(input map[string]any) any { stated := jsonutil.FirstAny(jsonutil.AnyAt(input, "output_config", "effort"), input["effort"]) if effort, ok := normalizeEffortValue(stated); ok { @@ -348,6 +376,14 @@ func anthropicReasoning(input map[string]any) any { return input["thinking"] } +// decodeBridgeRequest decodes a client request body of the given protocol into +// the bridge model. It rejects what the bridge cannot carry faithfully: a +// malformed message or tool, an unsupported role, content block or Responses +// item type, and a Chat tool that is not a function. Built-in Responses tools +// are skipped, as is a Responses message item with a role other than system, +// developer, user or assistant. Tool results of Responses and Anthropic +// requests then go through decodeToolImages, and a result carrying images +// must name its tool call. func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest, error) { request := bridgeRequest{ Model: jsonutil.StringAt(input, "model"), @@ -375,7 +411,7 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest blocks = append(decodeChatReasoning(message), blocks...) // A budget the gateway carried out on the assistant message is // read back next to the effort, so both directions agree on the - // level the client originally named. + // budget the client originally named. if budget := jsonutil.IntAt(message, "reasoning_budget_tokens"); budget > 0 { request.Reasoning = withReasoningBudget(request.Reasoning, budget) } @@ -534,7 +570,8 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest role := jsonutil.StringAt(message, "role") // Some clients (e.g. Claude Code) inline system/developer messages // into the messages array instead of using the top-level system - // field. Fold them into the system prompt rather than rejecting. + // field. Fold system messages into request.System and developer + // messages into request.Developer rather than rejecting them. if role == "system" { blocks, err := decodeAnthropicBlocksChecked(message["content"]) if err != nil { @@ -595,6 +632,10 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest return request, nil } +// appendBridgeBlock adds a block decoded from a standalone Responses item. It +// joins the previous message when that has the same role and holds only tool +// calls or results, so consecutive function_call (or function_call_output) +// items form one turn; otherwise the block starts a new message. func appendBridgeBlock(messages *[]bridgeMessage, role string, block bridgeBlock) { if len(*messages) > 0 { last := &(*messages)[len(*messages)-1] @@ -606,6 +647,8 @@ func appendBridgeBlock(messages *[]bridgeMessage, role string, block bridgeBlock *messages = append(*messages, bridgeMessage{Role: role, Blocks: []bridgeBlock{block}}) } +// bridgeBlocksOnlyTools reports whether blocks is non-empty and holds only +// tool calls and tool results. func bridgeBlocksOnlyTools(blocks []bridgeBlock) bool { if len(blocks) == 0 { return false @@ -618,6 +661,10 @@ func bridgeBlocksOnlyTools(blocks []bridgeBlock) bool { return true } +// encodeBridgeRequest validates a bridge request against the target protocol +// and encodes it as that protocol's request body. The target must be one of +// the three message protocols, and the Chat encoder can also fail on a history +// whose tool calls and results do not pair up. func encodeBridgeRequest(protocol Protocol, request bridgeRequest) (map[string]any, error) { if err := validateBridgeRequest(protocol, request); err != nil { return nil, err @@ -634,6 +681,9 @@ func encodeBridgeRequest(protocol Protocol, request bridgeRequest) (map[string]a } } +// validateBridgeRequest rejects content the target protocol cannot represent +// at all: a file in Responses instructions, and for Anthropic a file known +// only by its file_id. func validateBridgeRequest(protocol Protocol, request bridgeRequest) error { if protocol == Responses { for _, block := range request.System { @@ -656,6 +706,16 @@ func validateBridgeRequest(protocol Protocol, request bridgeRequest) error { return nil } +// encodeChatRequest encodes a bridge request as a Chat Completions body. +// +// System and developer blocks become leading system and developer messages. +// Chat answers each tool call with a separate "tool" message that must follow +// the assistant message carrying the calls, so the encoder tracks pending +// calls: once every pending call has a result, the tool messages are emitted +// in call order, followed by user messages for any images the results carried +// (a tool message holds only text), and then by user content that arrived +// while the calls were pending. A history that breaks the call/result pairing +// is an error. func encodeChatRequest(request bridgeRequest) (map[string]any, error) { output := map[string]any{"model": request.Model, "stream": request.Stream} jsonutil.Put(output, "temperature", request.Temperature) @@ -689,11 +749,11 @@ func encodeChatRequest(request bridgeRequest) (map[string]any, error) { pendingResults := make(map[string]bridgeBlock) var pendingOrder []string var deferred [][]bridgeBlock - // Anthropic's reasoning controls belong to a whole conversation, but Chat - // carries a single reasoning_effort for the request. The budget the client - // named is emitted once, on the first assistant message, so that decoding - // this Chat body back into Anthropic can restore the level exactly instead - // of re-deriving it from a bucket (32000 used to come back as 8192). + // Chat has a reasoning_effort level but no field for an Anthropic thinking + // budget. The budget the client named is emitted once, as + // reasoning_budget_tokens on the first assistant message, so that decoding + // this Chat body back into Anthropic can restore the budget exactly instead + // of re-deriving it from the level (32000 used to come back as 8192). budgetCarried := false carryBudget := func(encoded map[string]any) { if budgetCarried { @@ -714,8 +774,8 @@ func encodeChatRequest(request bridgeRequest) (map[string]any, error) { } // A conversation can end before any assistant turn exists to carry the // budget. Attaching it to an empty assistant message keeps it on the wire - // without inventing visible output; Chat clients treat the empty turn as an - // assistant prefill. + // without inventing visible output; the upstream Chat endpoint treats the + // empty turn as an assistant prefill. carryBudgetOnly := func() { if budgetCarried { return @@ -859,6 +919,9 @@ func encodeChatRequest(request bridgeRequest) (map[string]any, error) { return output, nil } +// missingToolIDs lists the tool calls still waiting for a result, for an error +// message: in call order when that accounts for every pending call, and sorted +// otherwise. func missingToolIDs(order []string, pending map[string]bool) []string { missing := make([]string, 0, len(pending)) for _, id := range order { @@ -885,21 +948,28 @@ func missingToolIDs(order []string, pending map[string]bool) []string { return missing } -// responsesReasoning builds the Responses "reasoning" object. +// responsesReasoning builds the Responses "reasoning" object. A nil result +// omits the field. // -// A bare effort string, or a thinking-style block that carries budget_tokens -// but no effort, is projected onto "reasoning.effort". Copying such a block -// through verbatim (the old behavior) forwarded {"type":"adaptive"} and dropped -// the effort completely, so a client asking for "max" reached the upstream with -// no reasoning configuration at all. +// A bare effort string, or a reasoning object from which reasoningEffort reads +// a level (a thinking block of type "enabled"/"adaptive" included), is +// projected onto "reasoning.effort". Copying such a block through verbatim +// (the old behavior) forwarded {"type":"adaptive"} and dropped the effort +// completely, so a client asking for "max" reached the upstream with no +// reasoning configuration at all. +// +// An object of type "disabled", or one that yields no level, is still +// forwarded unchanged, and a bare "none"/"disabled" string yields nil. func responsesReasoning(value any) any { if object, ok := value.(map[string]any); ok { if jsonutil.StringAt(object, "type") == "disabled" { return object } - // "effort" is authoritative here for the same reason as in - // encodeChatRequest: it either came from the client verbatim or was - // derived from the budget by reasoningEffort. + // The object is reduced to the level reasoningEffort reads from it: + // an "effort" or "reasoning_effort" the client stated, else the rung + // of a thinking block's budget, else a level carried in "type". + // Responses takes only the level here, so the object's other keys + // (budget_tokens among them) are not forwarded. if effort := reasoningEffort(object); effort != nil { switch typed := effort.(type) { case string: @@ -943,6 +1013,13 @@ func floorResponsesMaxTokens(value any) any { return value } +// encodeResponsesRequest encodes a bridge request as a Responses body. +// Instructions come from the system blocks and a leading developer message +// from the developer blocks. Each message becomes one or more input items: +// reasoning blocks become reasoning items (only when they carry a +// server-issued ID or encrypted content), text and images become content +// parts, files input_file parts, and tool calls and results standalone +// function_call and function_call_output items. func encodeResponsesRequest(request bridgeRequest) map[string]any { output := map[string]any{"model": request.Model, "stream": request.Stream} jsonutil.Put(output, "temperature", request.Temperature) @@ -962,8 +1039,9 @@ func encodeResponsesRequest(request bridgeRequest) map[string]any { output["text"] = map[string]any{"format": format} } jsonutil.Put(output, "parallel_tool_calls", request.ParallelToolCalls) - // ponytail: native-fidelity knobs. Omit-when-absent: clients that never - // send them see zero behavior change; opencode turns ride cache affinity. + // Native-fidelity knobs. Each is emitted only when the client sent it, so + // a client that never sends them sees no behavior change, while OpenCode + // turns ride prompt-cache affinity. jsonutil.Put(output, "prompt_cache_key", request.PromptCacheKey) jsonutil.Put(output, "safety_identifier", request.SafetyIdentifier) jsonutil.Put(output, "service_tier", request.ServiceTier) @@ -1058,6 +1136,11 @@ func encodeResponsesRequest(request bridgeRequest) map[string]any { return output } +// encodeAnthropicRequest encodes a bridge request as an Anthropic Messages +// body. System and developer blocks are merged into one system prompt, a +// missing max_tokens defaults to 4096, and adjacent same-role messages are +// joined into one, because Anthropic expects the turns to alternate. A "none" +// tool choice omits the tools entirely. func encodeAnthropicRequest(request bridgeRequest) map[string]any { output := map[string]any{"model": request.Model, "stream": request.Stream} jsonutil.Put(output, "temperature", request.Temperature) diff --git a/internal/protocol/response.go b/internal/protocol/response.go index bd8ca78..4b04484 100644 --- a/internal/protocol/response.go +++ b/internal/protocol/response.go @@ -11,6 +11,11 @@ import ( "opencode2api/internal/jsonutil" ) +// ConvertResponse converts a serialized response body from one protocol to +// another. A same-protocol body is returned as a copy, unchanged; otherwise +// the body is decoded into the bridge model and re-encoded for the target. An +// upstream error envelope becomes an error, and so does a body the target +// protocol cannot represent. func ConvertResponse(from, to Protocol, body []byte) ([]byte, error) { if from == to { return append([]byte(nil), body...), nil @@ -29,6 +34,11 @@ func ConvertResponse(from, to Protocol, body []byte) ([]byte, error) { return json.Marshal(encodeBridgeResponse(to, response)) } +// decodeBridgeResponse decodes a complete response body of the given protocol +// into the bridge model. An error envelope or error status is reported in +// response.Error (and the caller turns it into an error), an unknown output +// item, content block or protocol is an error, and a missing creation time +// defaults to now. func decodeBridgeResponse(protocol Protocol, input map[string]any) (bridgeResponse, error) { response := bridgeResponse{ ID: jsonutil.StringAt(input, "id"), @@ -141,6 +151,10 @@ func decodeBridgeResponse(protocol Protocol, input map[string]any) (bridgeRespon return response, nil } +// encodeBridgeResponse encodes a bridge response as the target protocol's +// body. A tool stop with no usable tool block is demoted to a plain stop first +// (the reason is spelled out at the guard below), and an ID is synthesized when +// the response has none. func encodeBridgeResponse(protocol Protocol, response bridgeResponse) map[string]any { if response.ID == "" { response.ID = identity.RandomID("resp", 12) @@ -277,6 +291,10 @@ func encodeBridgeResponse(protocol Protocol, response bridgeResponse) map[string } } +// decodeOpenAIUsage reads a Chat or Responses usage object. Either spelling of +// each field is accepted, prompt/input and completion/output alike, and the +// cache-read, cache-write and reasoning details are read from both the Chat +// and the Responses nesting. func decodeOpenAIUsage(usage map[string]any) Usage { input := jsonutil.FirstNonZero(jsonutil.IntAt(usage, "prompt_tokens"), jsonutil.IntAt(usage, "input_tokens")) output := jsonutil.FirstNonZero(jsonutil.IntAt(usage, "completion_tokens"), jsonutil.IntAt(usage, "output_tokens")) @@ -295,6 +313,9 @@ func decodeOpenAIUsage(usage map[string]any) Usage { return Usage{Input: input, Output: output, Total: total, Cached: cached, CacheCreation: cacheCreation, Reasoning: reasoning} } +// decodeAnthropicUsage reads an Anthropic usage object. Anthropic reports the +// cache parts separately from input_tokens, so Input is the sum of the three, +// matching the prompt-token semantics the bridge uses. func decodeAnthropicUsage(usage map[string]any) Usage { input := jsonutil.IntAt(usage, "input_tokens") cached := jsonutil.IntAt(usage, "cache_read_input_tokens") @@ -310,6 +331,7 @@ func decodeAnthropicUsage(usage map[string]any) Usage { } } +// openAIUsage renders bridge usage in the Chat usage shape. func openAIUsage(usage Usage) map[string]any { return map[string]any{ "prompt_tokens": usage.Input, @@ -324,6 +346,9 @@ func openAIUsage(usage Usage) map[string]any { } } +// anthropicUsage renders bridge usage in the Anthropic shape, where +// input_tokens excludes the cache parts, so it is Input minus Cached and +// CacheCreation, floored at zero. func anthropicUsage(usage Usage) map[string]any { return map[string]any{ "input_tokens": max(usage.Input-usage.Cached-usage.CacheCreation, 0), @@ -333,6 +358,7 @@ func anthropicUsage(usage Usage) map[string]any { } } +// chatStop maps a canonical bridge stop reason onto Chat's finish_reason. func chatStop(stop string) string { switch stop { case "tool_use", "tool_calls": @@ -346,6 +372,8 @@ func chatStop(stop string) string { } } +// anthropicStop maps a canonical bridge stop reason onto Anthropic's +// stop_reason. func anthropicStop(stop string) string { switch stop { case "tool_use", "tool_calls": @@ -359,6 +387,8 @@ func anthropicStop(stop string) string { } } +// canonicalChatStop maps Chat's finish_reason onto a canonical bridge stop +// reason. func canonicalChatStop(stop string) string { switch stop { case "tool_calls", "function_call": @@ -374,6 +404,8 @@ func canonicalChatStop(stop string) string { } } +// canonicalAnthropicStop maps Anthropic's stop_reason onto a canonical bridge +// stop reason. func canonicalAnthropicStop(stop string) string { switch stop { case "tool_use": @@ -389,8 +421,9 @@ func canonicalAnthropicStop(stop string) string { } } -// isToolStop reports whether a canonical bridge stop reason promises tool -// calls downstream. +// isToolStop reports whether a stop reason promises tool calls downstream. It +// accepts the canonical "tool_calls" as well as the raw "tool_use" and +// "function_call" spellings an upstream may report. func isToolStop(stop string) bool { switch stop { case "tool_calls", "tool_use", "function_call": @@ -402,7 +435,9 @@ func isToolStop(stop string) bool { // usableToolBlocks drops phantom tool blocks that cannot be executed by a // downstream client. Empty arguments are valid, so the tool name is the -// minimum required signal here; the streaming emitter uses the same rule. +// minimum required signal here: a name that is empty or only whitespace is +// dropped. The streaming emitter applies a looser version of the rule, opening +// a tool as soon as its name is non-empty. func usableToolBlocks(tools []bridgeBlock) []bridgeBlock { if len(tools) == 0 { return nil @@ -417,6 +452,9 @@ func usableToolBlocks(tools []bridgeBlock) []bridgeBlock { return usable } +// canonicalResponsesIncomplete maps a Responses incomplete_details.reason onto +// a canonical bridge stop reason: "content_filter" stays itself and any other +// reason, max_output_tokens included, becomes "length". func canonicalResponsesIncomplete(reason string) string { switch reason { case "content_filter": @@ -426,6 +464,8 @@ func canonicalResponsesIncomplete(reason string) string { } } +// responsesIncompleteReason is the inverse of canonicalResponsesIncomplete: +// the incomplete_details.reason to report for a canonical stop. func responsesIncompleteReason(stop string) string { if stop == "content_filter" { return "content_filter" @@ -433,6 +473,9 @@ func responsesIncompleteReason(stop string) string { return "max_output_tokens" } +// responseTextBlocks joins the text of blocks, erroring on any other kind: +// neither a Chat message nor a Responses output message may carry more than +// text. func responseTextBlocks(blocks []bridgeBlock, protocol string) (string, error) { for _, block := range blocks { if block.Kind != "text" { @@ -442,6 +485,9 @@ func responseTextBlocks(blocks []bridgeBlock, protocol string) (string, error) { return bridgeBlocksText(blocks), nil } +// ResponseUsage extracts the usage of a serialized response body and reports +// whether it carried any. The body is decoded per protocol, so an Anthropic +// usage is read with its separate cache fields. func ResponseUsage(protocol Protocol, body []byte) (Usage, bool) { var payload map[string]any if json.Unmarshal(body, &payload) != nil { @@ -460,13 +506,14 @@ func ResponseUsage(protocol Protocol, body []byte) (Usage, bool) { // RenameResponseTool rewrites tool call names matching fromName to toName inside // a serialized JSON response or SSE event data object for the given protocol. // It is used to restore a client's original read-related tool name (e.g. -// "reAd" or "read_file") after the legacy /zen/v1 shaper aliased it to "read" -// on the outbound wire. +// "reAd" or "read_file") after the v1 lane's shaper aliased it to "read" on the +// outbound wire. // -// fromName is guaranteed not to occur as a substring of any other text in a -// response (tool names are never echoed back inside content), so a byte-level -// occurrence check is enough to skip the re-marshal for the vast majority of -// frames. +// The bytes.Contains check is only a fast path that skips the unmarshal for +// frames that cannot contain the name; correctness does not depend on it, +// because every name that is rewritten is compared exactly after decoding. +// Names that do not match fromName, including ones already equal to toName, +// are left alone. func RenameResponseTool(body []byte, protocol Protocol, fromName, toName string) []byte { if fromName == "" || toName == "" || fromName == toName || len(body) == 0 { return body @@ -488,6 +535,11 @@ func RenameResponseTool(body []byte, protocol Protocol, fromName, toName string) return encoded } +// renameToolInMap rewrites matching tool names in a decoded response or stream +// event and reports whether anything changed. Every place a protocol reports a +// tool call is visited: Chat message and delta tool_calls, Responses +// function_call items under "item", "output" and a "response" envelope, and +// Anthropic tool_use blocks under "content_block" or "content". func renameToolInMap(payload map[string]any, protocol Protocol, fromName, toName string) bool { changed := false switch protocol { diff --git a/internal/protocol/rotation_stream.go b/internal/protocol/rotation_stream.go index 6dbb50e..bdea42d 100644 --- a/internal/protocol/rotation_stream.go +++ b/internal/protocol/rotation_stream.go @@ -8,27 +8,61 @@ import ( "net/http" ) -// StreamFailure carries upstream classification without exposing its raw text -// to the caller or diagnostics. It can be examined before committing a stream. +// StreamFailure classifies a failed upstream stream without putting its raw +// text into the returned error. Message holds the upstream error text so a +// caller can classify the failure (quota wording, for one) without returning +// that text to the client; Type holds the upstream error type. Error reports a +// fixed generic message instead. It is returned for failures both before and +// after a stream is committed, and the gateway inspects it to classify the +// attempt before deciding whether to rotate to another model. type StreamFailure struct{ Message, Type string } +// Error returns a generic message, keeping the upstream text out of logs and +// error chains that print the error itself. func (e *StreamFailure) Error() string { return "upstream stream failed" } +// ClientWriteError wraps a failure to write to the downstream client, so the +// gateway can tell a vanished client from an upstream failure. Unwrap exposes +// the underlying write error. type ClientWriteError struct{ Err error } +// Error returns a generic message; Err carries the detail. func (e *ClientWriteError) Error() string { return "downstream write failed" } + +// Unwrap returns the underlying write error. func (e *ClientWriteError) Unwrap() error { return e.Err } -// RotationStream holds role/start/usage events until useful content or a normal -// terminal event. Ready commits the chosen model and stops the first-output -// timer. Once committed, failures are emitted in-band and never replayed. +// RotationStream streams one upstream response to the client while holding +// back events until the attempt is worth committing to. Upstream events are +// parsed with the parser for from, and the emitter encodes them for to under +// the requested alias. +// +// Events that carry no output (start, usage, finish) are held in pending until +// an effective event arrives: text, reasoning, a reasoning signature, a tool +// start or delta, or done. At that point ready is called (the gateway uses it +// to stop the first-output timer and set the response headers), the attempt is +// marked committed, and the held events are emitted first. If 256 events are +// already held and another non-effective one arrives, the attempt fails with +// invalid_prelude. An upstream error event before that point is returned as a +// StreamFailure so the gateway can rotate to another model; once committed, a +// failure is emitted in-band as an error event and never replayed. The event +// model is always cleared, because the emitter's model is the requested alias +// for the whole response. +// +// It returns the usage the emitter collected and whether the upstream reported +// usage at all, whether the stream was committed, and the stream error: nil +// after a normal termination; a *StreamFailure for an upstream error event, a +// parse error, more than 256 held events, or a stream that ended without a +// terminal event; a *ClientWriteError when writing to the client failed; the +// error returned by ready; or whatever ended the read, errSSEUnexpectedEOF +// included. A client cancellation does not get a synthetic error event. func RotationStream(ctx context.Context, w http.ResponseWriter, reader io.Reader, from, to Protocol, alias string, ready func() error) (usage Usage, reported, committed bool, result error) { flusher, ok := w.(http.Flusher) if !ok { return usage, false, false, fmt.Errorf("streaming is unsupported") } - parser := newStreamUsageObserver(from).parser - emitter := newBridgeStreamEmitter(w, flusher, to, alias) + parser := streamUsageObserver(from).parser + emitter := bridgeStreamEmitter(w, flusher, to, alias) pending := []bridgeStreamEvent{} var upstreamFailure error emit := func(event bridgeStreamEvent) error { diff --git a/internal/protocol/stream.go b/internal/protocol/stream.go index 221c404..18182cf 100644 --- a/internal/protocol/stream.go +++ b/internal/protocol/stream.go @@ -14,12 +14,20 @@ import ( "opencode2api/internal/jsonutil" ) +// errStreamUpstreamFailure marks a stream that failed in a way already +// reported, or, in CollapseStream, already recorded, so the caller must not +// report it a second time. var errStreamUpstreamFailure = errors.New("upstream stream failure delivered") +// errStreamNormalTermination reports that the stream reached its own terminal +// event, so the caller treats it as a success. var errStreamNormalTermination = errors.New("upstream stream terminated normally") +// errSSEUnexpectedEOF reports a stream that ended without a terminal event. var errSSEUnexpectedEOF = errors.New("unexpected end of SSE stream") +// streamTermination records how a transcoded stream ended, so the code after +// readSSE can tell a normal terminal event from an upstream error. type streamTermination uint8 const ( @@ -28,6 +36,12 @@ const ( streamErrorTermination ) +// bridgeStreamEvent is one protocol-neutral streaming event, parsed from an +// upstream stream and encoded for the downstream protocol. Kind selects which +// fields matter: "start" (ResponseID, Model), "text", "reasoning" (Text and/or +// Encrypted), "reasoning_signature" (Signature), "tool_start" and "tool_delta" +// (ToolKey, ToolID, ToolName, Text), "usage", "finish" (Stop), "error" +// (Error, ErrorType) and "done". type bridgeStreamEvent struct { Kind string ResponseID string @@ -44,9 +58,20 @@ type bridgeStreamEvent struct { Usage *Usage } -// TranscodeStream is the request-aware form used by the -// gateway. A cancelled client must not receive a synthetic upstream error -// after its connection has gone away. +// TranscodeStream parses an upstream stream of one protocol and re-encodes it +// for another, writing each downstream event as it arrives. It returns the +// usage the emitter collected and whether the upstream reported any. +// +// A nil error means the stream reached its terminal event. Otherwise the error +// is errStreamUpstreamFailure when the failure was already reported in-band, +// the error that ended the read, or ctx.Err() when the client was canceled +// after the stream itself ended cleanly. A stream that ends without a terminal +// event is reported in-band with an error event first, using +// errSSEUnexpectedEOF when nothing more specific is known. +// +// A canceled client gets no synthetic upstream error event: the gateway +// cancels the request context when the client goes away, and writing after +// that only wastes the remaining attempt. func TranscodeStream(ctx context.Context, w http.ResponseWriter, reader io.Reader, from, to Protocol, model string) (Usage, bool, error) { flusher, ok := w.(http.Flusher) if !ok { @@ -60,7 +85,7 @@ func TranscodeStream(ctx context.Context, w http.ResponseWriter, reader io.Reade responseArgs: map[string]bool{}, responseReasoning: map[string]bool{}, } - emitter := newBridgeStreamEmitter(w, flusher, to, model) + emitter := bridgeStreamEmitter(w, flusher, to, model) termination := streamOpen readErr := readSSE(reader, func(eventName, data string) error { events, err := parser.Parse(eventName, data) @@ -116,7 +141,10 @@ func TranscodeStream(ctx context.Context, w http.ResponseWriter, reader io.Reade return emitter.usage, emitter.usageReported, errSSEUnexpectedEOF } -func emitUnexpectedStreamError(emitter *bridgeStreamEmitter, cause error) error { +// emitUnexpectedStreamError reports a stream that ended without a terminal +// event, as an in-band error event in the downstream protocol. It returns nil +// once that event is written, and the write error otherwise. +func emitUnexpectedStreamError(emitter *bridgeStreamEncoder, cause error) error { message := "upstream SSE stream ended before a terminal event" if cause != nil && !errors.Is(cause, errSSEUnexpectedEOF) { message = fmt.Sprintf("upstream SSE stream failed: %v", cause) @@ -128,6 +156,8 @@ func emitUnexpectedStreamError(emitter *bridgeStreamEmitter, cause error) error return err } +// ClientCanceled reports whether a stream error is the client going away, +// either through the stream error itself or through the request context. func ClientCanceled(ctx context.Context, streamErr error) bool { if errors.Is(streamErr, context.Canceled) { return true @@ -152,12 +182,20 @@ func (writer *sseFlushWriter) Write(data []byte) (int, error) { return n, err } +// ForwardStream relays a same-protocol upstream stream to the client byte for +// byte, flushing each write, while a usage tracker reads the same bytes +// through a TeeReader. It returns the tracked usage and whether the upstream +// reported any, plus an error: the copy error, if any, for a normal +// termination that parsed cleanly; otherwise errStreamUpstreamFailure when an +// upstream error event was relayed, the copy error, or the parse error (or +// errSSEUnexpectedEOF) after an error event was emitted for a stream that +// ended early. A canceled client gets no synthetic error event. func ForwardStream(ctx context.Context, w http.ResponseWriter, reader io.Reader, protocol Protocol, model string) (Usage, bool, error) { flusher, ok := w.(http.Flusher) if !ok { return Usage{}, false, fmt.Errorf("response writer does not support streaming") } - observer := newStreamUsageObserver(protocol) + observer := streamUsageObserver(protocol) _, copyErr := io.Copy(&sseFlushWriter{writer: w, flusher: flusher}, io.TeeReader(reader, observer)) usage := observer.Finish() if observer.ErrorTermination() { @@ -182,7 +220,7 @@ func ForwardStream(ctx context.Context, w http.ResponseWriter, reader io.Reader, if cause == nil { cause = errSSEUnexpectedEOF } - emitter := newBridgeStreamEmitter(w, flusher, protocol, model) + emitter := bridgeStreamEmitter(w, flusher, protocol, model) if err := emitUnexpectedStreamError(emitter, cause); err != nil { return usage, observer.Reported(), err } @@ -195,7 +233,9 @@ func ForwardStream(ctx context.Context, w http.ResponseWriter, reader io.Reader, // returned unchanged. // // It is a pull-based transform instead of a goroutine plus io.Pipe so a client -// that disconnects mid-stream cannot strand a blocked writer. +// that disconnects mid-stream cannot strand a blocked writer. Chat frames go +// through the fragment-aware rewriter, while the other protocols use the +// stateless RenameResponseTool rewrite on each frame. func RenameStreamReader(reader io.Reader, protocol Protocol, fromName, toName string) io.Reader { if fromName == "" || toName == "" || fromName == toName { return reader @@ -206,6 +246,9 @@ func RenameStreamReader(reader io.Reader, protocol Protocol, fromName, toName st } } +// renameStreamReader is the io.Reader RenameStreamReader returns: it reads the +// upstream stream line by line, rewrites the data lines that need it, and +// serves the rewritten bytes, carrying an error over to the next Read. type renameStreamReader struct { buffer *bufio.Reader renamer *streamToolRenamer @@ -213,14 +256,16 @@ type renameStreamReader struct { err error } +// Read returns the rewritten stream bytes, buffering one line at a time. func (reader *renameStreamReader) Read(data []byte) (int, error) { for len(reader.pending) == 0 { if reader.err != nil { return 0, reader.err } // ReadString either returns a non-empty chunk with a nil error or - // returns the trailing chunk together with EOF, so this loop can only - // repeat while a rewritten chunk is still being drained. + // returns the trailing chunk together with EOF, so one iteration + // always either fills pending or reports the error below; the loop + // condition only guards the entry. line, err := reader.buffer.ReadString('\n') if len(line) > 0 { reader.pending = reader.rewriteLine(line) @@ -275,6 +320,9 @@ type streamToolRenameState struct { pending string } +// streamToolRenamer rewrites the tool names of one protocol's SSE frames, +// keeping per-tool state across frames so a name split over several Chat +// chunks is reassembled before it is matched. type streamToolRenamer struct { protocol Protocol fromName string @@ -282,7 +330,10 @@ type streamToolRenamer struct { tools map[string]*streamToolRenameState } -// rewriteFrame rewrites one decoded SSE data object. +// rewriteFrame rewrites one SSE data payload, which is raw JSON text. Frames +// that cannot carry a tool name are returned untouched, so only a payload that +// mentions the source name (Anthropic and Responses) or "tool_calls" (Chat) is +// decoded. func (renamer *streamToolRenamer) rewriteFrame(raw string) []byte { if renamer.protocol != Chat { // Anthropic and Responses streams always carry a complete tool name in @@ -298,6 +349,10 @@ func (renamer *streamToolRenamer) rewriteFrame(raw string) []byte { return renamer.rewriteChatFrame(raw) } +// rewriteChatFrame rewrites the tool names of one Chat chunk. Tool calls are +// keyed by index, then id, then array position, and each name fragment is fed +// through applyNameFragment so a name split across chunks is restored as a +// whole. It returns the frame unchanged when nothing was rewritten. func (renamer *streamToolRenamer) rewriteChatFrame(raw string) []byte { var payload map[string]any if err := json.Unmarshal([]byte(raw), &payload); err != nil { @@ -346,7 +401,11 @@ func (renamer *streamToolRenamer) rewriteChatFrame(raw string) []byte { } // applyNameFragment folds one name fragment into a tool's rename state and -// reports whether the frame changed. +// reports whether the frame changed. Once the accumulated name completes +// fromName, it is replaced by toName; while it is still a prefix of fromName +// the name is held back; on divergence the accumulated name is written out as +// is. After a resolved rename, any further fragment is dropped, because it +// belongs to a longer name the client never declared. func (renamer *streamToolRenamer) applyNameFragment(state *streamToolRenameState, function map[string]any, fragment string) bool { if state.decided { if !state.renamed { @@ -378,6 +437,8 @@ func (renamer *streamToolRenamer) applyNameFragment(state *streamToolRenameState } } +// toolState returns the rename state for a tool key, creating it on first +// sight. func (renamer *streamToolRenamer) toolState(key string) *streamToolRenameState { if state := renamer.tools[key]; state != nil { return state @@ -387,7 +448,11 @@ func (renamer *streamToolRenamer) toolState(key string) *streamToolRenameState { return state } -type streamUsageObserver struct { +// streamUsageTracker is an io.Writer that splits a relayed stream into SSE +// frames and parses them for usage, while recording whether the stream reached +// a terminal or error event and whether any frame failed to parse. It never +// modifies the bytes it is given. +type streamUsageTracker struct { parser *bridgeStreamParser buffer []byte usage Usage @@ -397,14 +462,18 @@ type streamUsageObserver struct { parseErr error } -func newStreamUsageObserver(protocol Protocol) *streamUsageObserver { - return &streamUsageObserver{parser: &bridgeStreamParser{ +// streamUsageObserver builds a usage tracker whose parser reads the given +// protocol. +func streamUsageObserver(protocol Protocol) *streamUsageTracker { + return &streamUsageTracker{parser: &bridgeStreamParser{ protocol: protocol, tools: map[string]bool{}, toolIDs: map[string]string{}, toolNames: map[string]string{}, responseArgs: map[string]bool{}, responseReasoning: map[string]bool{}, }} } -func (observer *streamUsageObserver) Write(data []byte) (int, error) { +// Write buffers the relayed bytes and consumes every complete SSE frame they +// contain, keeping the incomplete tail for the next call. It never fails. +func (observer *streamUsageTracker) Write(data []byte) (int, error) { observer.buffer = append(observer.buffer, data...) for { index, width := nextSSEBoundary(observer.buffer) @@ -418,22 +487,26 @@ func (observer *streamUsageObserver) Write(data []byte) (int, error) { return len(data), nil } -func (observer *streamUsageObserver) Finish() Usage { +// Finish returns the merged usage and discards the buffered tail. +func (observer *streamUsageTracker) Finish() Usage { // An unterminated final line is not an SSE frame. In particular, do not // count a usage object from a response that was cut off at EOF. observer.buffer = nil return observer.usage } -func (observer *streamUsageObserver) Reported() bool { return observer.reported } +func (observer *streamUsageTracker) Reported() bool { return observer.reported } -func (observer *streamUsageObserver) NormalTermination() bool { return observer.normal } +func (observer *streamUsageTracker) NormalTermination() bool { return observer.normal } -func (observer *streamUsageObserver) ErrorTermination() bool { return observer.error } +func (observer *streamUsageTracker) ErrorTermination() bool { return observer.error } -func (observer *streamUsageObserver) ParseError() error { return observer.parseErr } +func (observer *streamUsageTracker) ParseError() error { return observer.parseErr } -func (observer *streamUsageObserver) consume(frame []byte) { +// consume parses one complete SSE frame and records its terminal events and +// usage. A parse error is remembered but not propagated, because the relay +// must keep copying bytes. +func (observer *streamUsageTracker) consume(frame []byte) { _ = readSSE(strings.NewReader(string(frame)), func(eventName, data string) error { events, err := observer.parser.Parse(eventName, data) if err != nil { @@ -458,6 +531,10 @@ func (observer *streamUsageObserver) consume(frame []byte) { }) } +// nextSSEBoundary finds the end of the first complete SSE frame in data: it +// returns the index where the frame's terminator starts and the terminator's +// width, preferring whichever of a blank line ("\n\n") or a CRLF blank line +// ("\r\n\r\n") comes first. No complete frame yields -1. func nextSSEBoundary(data []byte) (int, int) { lf := bytes.Index(data, []byte("\n\n")) crlf := bytes.Index(data, []byte("\r\n\r\n")) @@ -473,6 +550,12 @@ func nextSSEBoundary(data []byte) (int, int) { return lf, 2 } +// readSSE reads a stream and calls handler once per complete SSE record, with +// the record's event name and its data lines joined by newlines. A record ends +// at a blank line; comment lines are skipped, and a record without any data +// line is not delivered. A final record whose data is not terminated by a +// blank line is an unexpected EOF rather than a complete event. Scanner +// errors, and errors returned by handler, end the read. func readSSE(reader io.Reader, handler func(eventName, data string) error) error { scanner := bufio.NewScanner(reader) scanner.Buffer(make([]byte, 64<<10), 16<<20) diff --git a/internal/protocol/stream_emitter.go b/internal/protocol/stream_emitter.go index 85b2ab4..b1a3d33 100644 --- a/internal/protocol/stream_emitter.go +++ b/internal/protocol/stream_emitter.go @@ -12,6 +12,12 @@ import ( "opencode2api/internal/jsonutil" ) +// bridgeStreamTool accumulates one tool call while a stream is encoded. Key is +// the parser's stream key, ID and ItemID the call and output-item identifiers, +// Arguments the full argument text so far and EmittedArguments how much of it +// has reached the client. Index is the Chat index or Responses output index, +// and AnthropicIndex the content block index; Started records whether the tool +// was opened downstream. type bridgeStreamTool struct { Key string ID string @@ -24,7 +30,12 @@ type bridgeStreamTool struct { EmittedArguments int } -type bridgeStreamEmitter struct { +// bridgeStreamEncoder turns bridge stream events into one downstream protocol's +// SSE stream. It opens the response on the first start or content event (or on +// Finish when the stream carried none), tracks which text, reasoning and tool +// blocks are open so each protocol's block ordering is respected, and records +// usage as it goes. +type bridgeStreamEncoder struct { w io.Writer flush http.Flusher target Protocol @@ -59,8 +70,11 @@ type bridgeStreamEmitter struct { responseOutput []any } -func newBridgeStreamEmitter(writer io.Writer, flusher http.Flusher, target Protocol, model string) *bridgeStreamEmitter { - return &bridgeStreamEmitter{ +// bridgeStreamEmitter builds an encoder for the target protocol. The response +// ID is taken from the first event that carries one and the model from the +// last event that carries one, so the constructor's model is only a fallback. +func bridgeStreamEmitter(writer io.Writer, flusher http.Flusher, target Protocol, model string) *bridgeStreamEncoder { + return &bridgeStreamEncoder{ w: writer, flush: flusher, target: target, @@ -70,7 +84,11 @@ func newBridgeStreamEmitter(writer io.Writer, flusher http.Flusher, target Proto } } -func (emitter *bridgeStreamEmitter) Emit(event bridgeStreamEvent) error { +// Emit encodes one bridge stream event for the target protocol. The response +// is opened before the first start or content event. "error" writes an in-band +// error event and then returns errStreamUpstreamFailure; "done" finishes the +// stream through Finish. +func (emitter *bridgeStreamEncoder) Emit(event bridgeStreamEvent) error { if event.ResponseID != "" && emitter.id == "" { emitter.id = event.ResponseID } @@ -154,7 +172,10 @@ func (emitter *bridgeStreamEmitter) Emit(event bridgeStreamEvent) error { return nil } -func (emitter *bridgeStreamEmitter) emitError(message, errorType string) error { +// emitError writes an error in the target protocol's stream form: an "error" +// event for Anthropic, a response.failed event for Responses, and an error +// object followed by [DONE] for Chat. +func (emitter *bridgeStreamEncoder) emitError(message, errorType string) error { switch emitter.target { case Anthropic: return emitter.sse("error", map[string]any{ @@ -182,7 +203,10 @@ func (emitter *bridgeStreamEmitter) emitError(message, errorType string) error { } } -func (emitter *bridgeStreamEmitter) tool(key string) *bridgeStreamTool { +// tool returns the state for a stream tool key, creating it with fresh IDs and +// the next index on first sight. An empty key gets a position-based one, so +// each unnamed event starts its own tool. +func (emitter *bridgeStreamEncoder) tool(key string) *bridgeStreamTool { if key == "" { key = fmt.Sprintf("tool-%d", len(emitter.order)) } @@ -203,7 +227,7 @@ func (emitter *bridgeStreamEmitter) tool(key string) *bridgeStreamTool { // anyToolStarted reports whether at least one tool block was actually opened // downstream. Tools stuck without a name never start; their stop promise must // not be advertised as a tool stop. -func (emitter *bridgeStreamEmitter) anyToolStarted() bool { +func (emitter *bridgeStreamEncoder) anyToolStarted() bool { for _, key := range emitter.order { if tool := emitter.tools[key]; tool != nil && tool.Started { return true @@ -212,7 +236,10 @@ func (emitter *bridgeStreamEmitter) anyToolStarted() bool { return false } -func (emitter *bridgeStreamEmitter) start() error { +// start opens the response in the target protocol's shape: a role chunk for +// Chat, message_start for Anthropic, and response.created plus +// response.in_progress for Responses. It is a no-op once started. +func (emitter *bridgeStreamEncoder) start() error { if emitter.started { return nil } @@ -258,7 +285,11 @@ func (emitter *bridgeStreamEmitter) start() error { } } -func (emitter *bridgeStreamEmitter) emitText(delta string) error { +// emitText writes a text delta, closing the reasoning block first for +// Anthropic and Responses, whose content blocks are sequential. Anthropic +// opens a text content block and Responses a message output item with a text +// part, each on the first delta; Chat just takes the delta. +func (emitter *bridgeStreamEncoder) emitText(delta string) error { if emitter.target == Anthropic || emitter.target == Responses { if err := emitter.finishReasoning(); err != nil { return err @@ -305,7 +336,9 @@ func (emitter *bridgeStreamEmitter) emitText(delta string) error { return nil } -func (emitter *bridgeStreamEmitter) emitReasoning(delta string) error { +// emitReasoning writes a reasoning delta into the open reasoning block, +// opening it first if needed. Responses reports the text as a summary delta. +func (emitter *bridgeStreamEncoder) emitReasoning(delta string) error { if err := emitter.startReasoning(); err != nil { return err } @@ -324,7 +357,9 @@ func (emitter *bridgeStreamEmitter) emitReasoning(delta string) error { return nil } -func (emitter *bridgeStreamEmitter) emitReasoningSignature(signature string) error { +// emitReasoningSignature writes a reasoning signature delta. Chat and Anthropic +// have a field for it; Responses has none, so the signature is dropped there. +func (emitter *bridgeStreamEncoder) emitReasoningSignature(signature string) error { if err := emitter.startReasoning(); err != nil { return err } @@ -341,7 +376,11 @@ func (emitter *bridgeStreamEmitter) emitReasoningSignature(signature string) err return nil } -func (emitter *bridgeStreamEmitter) startReasoning() error { +// startReasoning opens the reasoning block, once: a thinking content block for +// Anthropic, a reasoning output item with a summary part for Responses, and +// nothing at all for Chat, which has no block to open. It also does nothing +// after the block has been closed. +func (emitter *bridgeStreamEncoder) startReasoning() error { if emitter.reasoningOpen || emitter.reasoningClosed { return nil } @@ -369,7 +408,10 @@ func (emitter *bridgeStreamEmitter) startReasoning() error { return nil } -func (emitter *bridgeStreamEmitter) finishReasoning() error { +// finishReasoning closes the open reasoning block. Anthropic gets a +// content_block_stop, and Responses the summary done events plus the completed +// output item, which carries the encrypted content when the upstream sent any. +func (emitter *bridgeStreamEncoder) finishReasoning() error { if !emitter.reasoningOpen || emitter.reasoningClosed { return nil } @@ -395,7 +437,11 @@ func (emitter *bridgeStreamEmitter) finishReasoning() error { return nil } -func (emitter *bridgeStreamEmitter) startTool(tool *bridgeStreamTool) error { +// startTool opens a tool call downstream once its name is non-empty, closing +// the reasoning block and, for Anthropic, the open text block first. A tool +// with no name stays unstarted, so a phantom call is never announced. Unlike +// usableToolBlocks, this check does not trim the name. +func (emitter *bridgeStreamEncoder) startTool(tool *bridgeStreamTool) error { if tool.Started || tool.Name == "" { return nil } @@ -438,7 +484,9 @@ func (emitter *bridgeStreamEmitter) startTool(tool *bridgeStreamTool) error { return nil } -func (emitter *bridgeStreamEmitter) emitToolDelta(tool *bridgeStreamTool, delta string) error { +// emitToolDelta writes a tool argument delta in the target protocol's form. +// The caller is responsible for having started the tool first. +func (emitter *bridgeStreamEncoder) emitToolDelta(tool *bridgeStreamTool, delta string) error { if delta == "" { return nil } @@ -456,7 +504,10 @@ func (emitter *bridgeStreamEmitter) emitToolDelta(tool *bridgeStreamTool, delta return nil } -func (emitter *bridgeStreamEmitter) emitPendingToolArguments(tool *bridgeStreamTool) error { +// emitPendingToolArguments writes the argument text a tool has accumulated but +// not yet sent. A tool that has not started holds its arguments until it does, +// so nothing is lost when the name arrives late. +func (emitter *bridgeStreamEncoder) emitPendingToolArguments(tool *bridgeStreamTool) error { if !tool.Started { return nil } @@ -469,7 +520,12 @@ func (emitter *bridgeStreamEmitter) emitPendingToolArguments(tool *bridgeStreamT return emitter.emitToolDelta(tool, delta) } -func (emitter *bridgeStreamEmitter) Finish() error { +// Finish closes the response in the target protocol's shape: the remaining +// text, reasoning and tool blocks, the stop reason, and the usage report. The +// stop reason defaults to "tool_calls" when any tool call was seen and "stop" +// otherwise, and a tool stop with no started tool is demoted to "stop" so the +// client does not wait for a call it never received. Finish is idempotent. +func (emitter *bridgeStreamEncoder) Finish() error { if emitter.done { return nil } @@ -567,7 +623,10 @@ func (emitter *bridgeStreamEmitter) Finish() error { return nil } -func (emitter *bridgeStreamEmitter) finishResponsesItems() error { +// finishResponsesItems closes the open text item and every tool item with the +// done events a Responses client expects. A tool without arguments is closed +// with "{}", so the item is still executable. +func (emitter *bridgeStreamEncoder) finishResponsesItems() error { if emitter.textOpen { text := emitter.text.String() if err := emitter.sse("response.output_text.done", map[string]any{"type": "response.output_text.done", "text": text, "item_id": emitter.textItemID, "output_index": emitter.textOutput, "content_index": 0, "sequence_number": emitter.nextSequence()}); err != nil { @@ -605,7 +664,8 @@ func (emitter *bridgeStreamEmitter) finishResponsesItems() error { return nil } -func (emitter *bridgeStreamEmitter) chatChunk(delta map[string]any, finish any) error { +// chatChunk writes one Chat chunk with the given delta and finish_reason. +func (emitter *bridgeStreamEncoder) chatChunk(delta map[string]any, finish any) error { return emitter.sse("", map[string]any{ "id": asPrefix(emitter.id, "chatcmpl"), "object": "chat.completion.chunk", @@ -619,7 +679,9 @@ func (emitter *bridgeStreamEmitter) chatChunk(delta map[string]any, finish any) }) } -func (emitter *bridgeStreamEmitter) responsesBase(status string, output []any) map[string]any { +// responsesBase builds the response object that Responses lifecycle events +// carry. +func (emitter *bridgeStreamEncoder) responsesBase(status string, output []any) map[string]any { return map[string]any{ "id": asPrefix(emitter.id, "resp"), "object": "response", @@ -631,13 +693,15 @@ func (emitter *bridgeStreamEmitter) responsesBase(status string, output []any) m } } -func (emitter *bridgeStreamEmitter) nextSequence() int { +// nextSequence returns the next Responses sequence_number. +func (emitter *bridgeStreamEncoder) nextSequence() int { sequence := emitter.sequence emitter.sequence++ return sequence } -func (emitter *bridgeStreamEmitter) sse(eventName string, value any) error { +// sse writes value as the data of one SSE event. +func (emitter *bridgeStreamEncoder) sse(eventName string, value any) error { data, err := json.Marshal(value) if err != nil { return err @@ -645,7 +709,9 @@ func (emitter *bridgeStreamEmitter) sse(eventName string, value any) error { return emitter.rawSSE(eventName, string(data)) } -func (emitter *bridgeStreamEmitter) rawSSE(eventName, data string) error { +// rawSSE writes one SSE event and flushes it, so the client sees each event as +// it is produced. An empty eventName omits the event line, as Chat streams do. +func (emitter *bridgeStreamEncoder) rawSSE(eventName, data string) error { if eventName != "" { if _, err := fmt.Fprintf(emitter.w, "event: %s\n", eventName); err != nil { return err @@ -658,6 +724,10 @@ func (emitter *bridgeStreamEmitter) rawSSE(eventName, data string) error { return nil } +// mergeBridgeUsage folds a usage report into the accumulated usage. A non-zero +// field replaces the stored one, Total keeps the larger of the two, and Total +// is finally raised to at least Input+Output so a report that leaves it out +// still adds up. func mergeBridgeUsage(destination *Usage, source Usage) { if source.Input != 0 { destination.Input = source.Input diff --git a/internal/protocol/stream_parser.go b/internal/protocol/stream_parser.go index 64115d6..8c2e086 100644 --- a/internal/protocol/stream_parser.go +++ b/internal/protocol/stream_parser.go @@ -8,6 +8,11 @@ import ( "opencode2api/internal/jsonutil" ) +// bridgeStreamParser turns one upstream protocol's SSE events into bridge +// stream events, remembering across events which tool calls were announced and +// which arguments or reasoning already arrived. A Chat stream is the only one +// whose tool names can be split across events, so it accumulates them; the +// other protocols report a complete name in one event. type bridgeStreamParser struct { protocol Protocol started bool @@ -19,6 +24,10 @@ type bridgeStreamParser struct { responseReasoning map[string]bool } +// Parse turns one SSE event of the parser's protocol into zero or more bridge +// events. An event the protocol has no meaning for yields none. Invalid JSON +// is an error, and so is a "[DONE]" terminator on a protocol other than Chat, +// which uses it to end the stream. func (parser *bridgeStreamParser) Parse(eventName, data string) ([]bridgeStreamEvent, error) { if data == "[DONE]" { if parser.protocol != Chat { @@ -42,10 +51,12 @@ func (parser *bridgeStreamParser) Parse(eventName, data string) ([]bridgeStreamE } } -func (parser *bridgeStreamParser) parseChat(value map[string]any) []bridgeStreamEvent { - return parser.parseChatEvent("", value) -} - +// parseChatEvent turns one Chat chunk into bridge events: an error envelope or +// error finish_reason becomes an error event, the first chunk supplies the +// response ID and model, usage is reported as it appears, and each choice +// contributes reasoning, text, tool and finish events. A tool call whose +// arguments arrive is started once its name is known, and a call whose name is +// known but whose arguments never arrived is started at finish_reason. func (parser *bridgeStreamParser) parseChatEvent(eventName string, value map[string]any) []bridgeStreamEvent { events := make([]bridgeStreamEvent, 0, 4) if eventName == "error" { @@ -113,10 +124,12 @@ func (parser *bridgeStreamParser) parseChatEvent(eventName string, value map[str return events } -func (parser *bridgeStreamParser) parseAnthropic(value map[string]any) ([]bridgeStreamEvent, error) { - return parser.parseAnthropicEvent("", value) -} - +// parseAnthropicEvent turns one Anthropic stream event into bridge events, +// keyed by its type (or the event name when the payload carries none): +// message_start supplies the ID, model and usage, content blocks yield +// reasoning, text and tool events, message_delta the usage and stop, and +// message_stop the done event. A stop reason that reports an error becomes an +// error event instead. func (parser *bridgeStreamParser) parseAnthropicEvent(eventName string, value map[string]any) ([]bridgeStreamEvent, error) { typeName := jsonutil.StringAt(value, "type") if typeName == "" { @@ -190,6 +203,13 @@ func (parser *bridgeStreamParser) parseAnthropicEvent(eventName string, value ma return nil, nil } +// parseResponses turns one Responses stream event into bridge events, keyed by +// its type (or the event name when the payload carries none): deltas become +// text, reasoning and tool deltas, item events open and close tool calls, and +// a terminal event reports the usage, the stop reason and done. A failed +// response becomes an error event after any usage it reports. A tool's +// arguments are taken from its deltas, and from the done event only when no +// delta arrived. func (parser *bridgeStreamParser) parseResponses(eventName string, value map[string]any) []bridgeStreamEvent { typeName := jsonutil.StringAt(value, "type") if typeName == "" { @@ -302,6 +322,8 @@ func (parser *bridgeStreamParser) responsesCompletedStop(response map[string]any return "stop" } +// streamErrorMessage extracts the upstream error text, accepting the OpenAI +// nested error object, a top-level message and a bare error string. func streamErrorMessage(value map[string]any, fallback string) string { if message := jsonutil.StringAt(value, "error", "message"); message != "" { return message @@ -315,10 +337,14 @@ func streamErrorMessage(value map[string]any, fallback string) string { return fallback } +// streamErrorType extracts the upstream error type, falling back to its code +// and then to "upstream_error". func streamErrorType(value map[string]any) string { return jsonutil.FirstString(jsonutil.StringAt(value, "error", "type"), jsonutil.StringAt(value, "error", "code"), "upstream_error") } +// isStreamErrorFinish reports whether a finish or stop reason reports an +// upstream error rather than a normal end. func isStreamErrorFinish(stop string) bool { switch strings.ToLower(strings.TrimSpace(stop)) { case "error", "network_error", "server_error": @@ -328,6 +354,8 @@ func isStreamErrorFinish(stop string) bool { } } +// rememberTool records a tool call seen in a Responses stream: its key is +// remembered as not yet started, and its ID and name are stored when given. func (parser *bridgeStreamParser) rememberTool(key, id, name string) { if _, seen := parser.tools[key]; !seen { parser.tools[key] = false @@ -341,6 +369,10 @@ func (parser *bridgeStreamParser) rememberTool(key, id, name string) { } } +// mergeToolName folds a Chat name fragment into the name accumulated so far. +// A fragment that repeats the current name replaces it, one that extends it +// (the upstream re-sends a growing prefix) becomes the new name, and anything +// else is appended. func mergeToolName(current, fragment string) string { if current == "" || fragment == current { return fragment @@ -351,6 +383,9 @@ func mergeToolName(current, fragment string) string { return current + fragment } +// responseToolKey identifies the tool call a Responses event belongs to: the +// item's id when the event carries an item, else the event's item_id, else its +// output_index. func responseToolKey(event map[string]any, item map[string]any) string { if item != nil { if id := jsonutil.StringAt(item, "id"); id != "" { diff --git a/internal/protocol/tool_images.go b/internal/protocol/tool_images.go index 0dd369d..5f718c9 100644 --- a/internal/protocol/tool_images.go +++ b/internal/protocol/tool_images.go @@ -7,8 +7,15 @@ import ( "opencode2api/internal/jsonutil" ) -// Only image-bearing tool results enter this path. Keep all legacy text and -// opaque results unchanged, and reuse bridgeBlock rather than a second model. +// decodeToolImages parses a Responses or Anthropic tool result that carries +// images into bridge blocks, so the images can be re-encoded for a target +// protocol whose tool result holds them differently. A result without images +// is returned unchanged. When images are present, every part must be a valid text or image +// part of the source protocol (an Anthropic image needs a URL or base64 source +// of its own; a Responses image needs an image_url and no file reference) and +// anything else is an error. For a Responses result, a data URI whose header is +// not a well-formed image is an error too. The text and opaque results of a +// tool without images are never reinterpreted here. func decodeToolImages(from Protocol, value any) (any, error) { parts, ok := value.([]any) if !ok { @@ -78,6 +85,13 @@ func decodeToolImages(from Protocol, value any) (any, error) { return blocks, nil } +// chatToolImages splits a tool result that decodeToolImages parsed into the +// text a Chat tool message can hold and the image parts that must be sent in a +// separate user message. Each image is announced in the text by a +// "[tool_image call_id=... index=N]" marker, with the call ID JSON-quoted, and +// the image list starts with that marker as a text block so the two stay +// associated. A result that was not parsed is flattened by +// bridgeToolResultContent and yields no images. func chatToolImages(result bridgeBlock) (string, []bridgeBlock) { parts, ok := result.Result.([]bridgeBlock) if !ok { @@ -99,6 +113,10 @@ func chatToolImages(result bridgeBlock) (string, []bridgeBlock) { return text.String(), images } +// responsesToolContent renders a parsed tool result as Responses +// function_call_output content: text parts as input_text and image parts as +// input_image, with inline data turned back into a data URI. An unparsed +// result is flattened by bridgeToolResultContent. func responsesToolContent(value any) any { parts, ok := value.([]bridgeBlock) if !ok { diff --git a/internal/rotation/state.go b/internal/rotation/state.go index 9f42417..b0d738c 100644 --- a/internal/rotation/state.go +++ b/internal/rotation/state.go @@ -1,5 +1,6 @@ // Package rotation owns sticky, service-wide model selection. No network call -// runs under its lock. A generation prevents late requests undoing a switch. +// runs under its lock. A generation prevents late requests from undoing a +// switch. package rotation import ( @@ -14,6 +15,8 @@ import ( "time" ) +// Attempt is one upstream attempt of a rotation request, kept for the WebUI. +// Number counts the attempts of that request across models; Record sets Time. type Attempt struct { Time time.Time `json:"time"` Request string `json:"request"` @@ -22,12 +25,20 @@ type Attempt struct { Number int `json:"number"` Outcome string `json:"outcome"` } + +// Switch records one change of a group's current model. type Switch struct { Time time.Time `json:"time"` From string `json:"from"` To string `json:"to"` Reason string `json:"reason"` } + +// Group is one rotation group ("sota" or "sweet"), served under Alias. Order +// is the rotation order and Current the model requests start on. Generation +// grows whenever Current is set and whenever Configure changes Order or Alias. +// Paused maps a model to the end of its pause, Available holds the models of +// the last Sync, and Switches keeps the latest 30 switches. type Group struct { ID string `json:"id"` Alias string `json:"alias"` @@ -38,16 +49,28 @@ type Group struct { Available map[string]bool `json:"available"` Switches []Switch `json:"switches"` } + +// Snapshot is the rotation state: both groups, the latest 100 attempts, the +// configured first-output timeout, and the error of the last write when it +// failed. type Snapshot struct { Groups []*Group `json:"groups"` Attempts []Attempt `json:"attempts"` PersistenceError string `json:"persistence_error,omitempty"` FirstOutputSeconds int `json:"first_output_seconds"` } + +// Token is the model Select handed to a request, with the group generation it +// was selected at. Fail only switches away from the model while that +// generation is still current. type Token struct { Group, Model string Generation uint64 } + +// Manager owns the rotation state and persists it as JSON at path, or keeps it +// in memory only when path is empty. mu guards all state; methods ending in +// Locked expect the caller to hold it. type Manager struct { mu sync.Mutex path string @@ -55,6 +78,10 @@ type Manager struct { cfg config.RotationConfig } +// New loads the state from path (a missing file starts empty), applies cfg and +// persists the result. It fails when the file cannot be read or parsed, when +// its groups are not exactly sota and sweet, or when the state cannot be +// written. func New(path string, cfg config.RotationConfig) (*Manager, error) { m := &Manager{path: path} if path != "" { @@ -76,6 +103,12 @@ func New(path string, cfg config.RotationConfig) (*Manager, error) { } return m, nil } + +// Configure applies the configured aliases and orders and persists the state. +// When a group has no order yet, or its configured order differs from the one +// applied last, the configured order replaces it and the models of the old +// order that it omits are appended. A Current that left the order moves to its +// first model. func (m *Manager) Configure(cfg config.RotationConfig) { m.mu.Lock() defer m.mu.Unlock() @@ -116,6 +149,12 @@ func (m *Manager) Configure(cfg config.RotationConfig) { m.state.FirstOutputSeconds = cfg.FirstOutputSeconds m.saveLocked() } + +// Sync replaces each group's Available set with the models of available that +// belong to it (the SOTA models to sota, every other model to sweet). Models +// new to a group are appended to its order in sorted order, glm-5.3-flash +// first when the order was empty, and a group without a Current starts on its +// first model. The state is persisted only when an order or Current changed. func (m *Manager) Sync(available map[string]bool) { m.mu.Lock() defer m.mu.Unlock() @@ -151,6 +190,9 @@ func (m *Manager) Sync(available map[string]bool) { m.saveLocked() } } + +// GroupID returns the ID of the group served under alias, or "" when alias +// names no group. func (m *Manager) GroupID(alias string) string { m.mu.Lock() defer m.mu.Unlock() @@ -161,6 +203,8 @@ func (m *Manager) GroupID(alias string) string { } return "" } + +// Snapshot returns a deep copy of the state. func (m *Manager) Snapshot() Snapshot { m.mu.Lock() defer m.mu.Unlock() @@ -169,6 +213,8 @@ func (m *Manager) Snapshot() Snapshot { _ = json.Unmarshal(b, &s) return s } + +// group returns the group with id, or nil. The caller holds m.mu. func (m *Manager) group(id string) *Group { for _, g := range m.state.Groups { if g.ID == id { @@ -177,9 +223,17 @@ func (m *Manager) group(id string) *Group { } return nil } + +// usable reports whether model is available in g and not paused. func usable(g *Group, model string) bool { return g.Available[model] && !time.Now().Before(g.Paused[model]) } + +// Select returns the first usable model of group id that the request has not +// visited, starting at Current and following the order. When Current itself +// is unusable, the selection becomes the new global Current; skipping a model +// the request already visited does not. It reports false when no model is +// left. func (m *Manager) Select(id string, visited map[string]bool) (Token, bool) { m.mu.Lock() defer m.mu.Unlock() @@ -202,6 +256,9 @@ func (m *Manager) Select(id string, visited map[string]bool) (Token, bool) { } return Token{}, false } + +// switchLocked sets the Current of g to to, bumps its Generation and records +// the switch, keeping the latest 30. The caller persists the state. func (m *Manager) switchLocked(g *Group, to, reason string) { from := g.Current g.Current = to @@ -211,6 +268,11 @@ func (m *Manager) switchLocked(g *Group, to, reason string) { g.Switches = g.Switches[len(g.Switches)-30:] } } + +// Fail pauses the model of t for pause, never shortening a longer pause. If +// t is still the group's Current at the same generation, Current moves to the +// next usable model in the order; when there is none, the recorded switch +// keeps the same model but still bumps the generation. func (m *Manager) Fail(t Token, pause time.Duration, reason string) { m.mu.Lock() defer m.mu.Unlock() @@ -236,6 +298,10 @@ func (m *Manager) Fail(t Token, pause time.Duration, reason string) { } m.saveLocked() } + +// Manual makes model the Current of group id at an operator's request and +// lifts its pause. The model must be in the group's order and available. It +// fails when the new state cannot be persisted. func (m *Manager) Manual(id, model string) error { m.mu.Lock() defer m.mu.Unlock() @@ -251,6 +317,9 @@ func (m *Manager) Manual(id, model string) error { } return nil } + +// Record stamps a with the current time and keeps it among the latest 100 +// attempts. func (m *Manager) Record(a Attempt) { m.mu.Lock() defer m.mu.Unlock() @@ -261,6 +330,9 @@ func (m *Manager) Record(a Attempt) { } m.saveLocked() } + +// saveLocked persists the state when there is a path. A failed write is not +// returned: it is kept in PersistenceError until the next successful write. func (m *Manager) saveLocked() { if m.path == "" { return @@ -270,6 +342,8 @@ func (m *Manager) saveLocked() { m.state.PersistenceError = "轮转状态写入失败,请检查磁盘空间和文件权限" } } + +// writeLocked writes the state through a temporary file and a rename. func (m *Manager) writeLocked() error { b, e := json.MarshalIndent(m.state, "", " ") if e != nil { diff --git a/internal/telemetry/http.go b/internal/telemetry/http.go index 418eba9..aa51f17 100644 --- a/internal/telemetry/http.go +++ b/internal/telemetry/http.go @@ -11,6 +11,9 @@ import ( "opencode2api/internal/protocol" ) +// RequestMeta is the request-local trace that Middleware attaches to a request +// and the gateway fills in while it routes, retries and streams it. Metrics and +// the request log read it once the handler returns. type RequestMeta struct { ModelAlias string Model string @@ -41,8 +44,8 @@ type RequestMeta struct { // and must be collapsed like anonymous ones. Shaped bool // ToolAlias holds the client's original read-related tool name (e.g. - // "reAd" or "read_file") when the legacy /zen/v1 shaper renamed it to - // "read" on the outbound wire. When non-empty, "read" tool calls in the + // "reAd" or "read_file") when the v1 lane's shaper renamed it to "read" + // on the outbound wire. When non-empty, "read" tool calls in the // upstream response are rewritten back to ToolAlias before returning. ToolAlias string Usage protocol.Usage @@ -68,10 +71,15 @@ func MetaFromContext(ctx context.Context) *RequestMeta { return meta } +// MetaFromRequest returns the request-local trace of r, or nil when it is +// absent. func MetaFromRequest(r *http.Request) *RequestMeta { return MetaFromContext(r.Context()) } +// statusWriter records the status and body size of a response. Only the first +// WriteHeader reaches the underlying writer, and a Write without one implies +// 200. type statusWriter struct { http.ResponseWriter status int @@ -101,7 +109,12 @@ func (w *statusWriter) Flush() { func (w *statusWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } -func Middleware(monitor *Monitor, logger *slog.Logger, next http.Handler) http.Handler { +// Middleware counts active requests and attaches a RequestMeta to every +// request, reusing one that is already present. When the handler returns it +// records the request in monitor and logs it: at info level when it was routed +// to an upstream channel, and always at debug level. /healthz bypasses all of +// it. +func Middleware(monitor *Metrics, logger *slog.Logger, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/healthz" { next.ServeHTTP(w, r) diff --git a/internal/telemetry/logging.go b/internal/telemetry/logging.go index 92d8ba3..1029be6 100644 --- a/internal/telemetry/logging.go +++ b/internal/telemetry/logging.go @@ -13,6 +13,8 @@ import ( "opencode2api/internal/config" ) +// LogEvent is one structured log record as the LogBroker keeps and streams it. +// Sequence grows by one per published event, so a subscriber can detect gaps. type LogEvent struct { Sequence uint64 `json:"sequence"` Time time.Time `json:"time"` @@ -26,7 +28,9 @@ type logSubscriber struct { ch chan LogEvent } -type LogHub struct { +// LogBroker keeps the most recent log events in a ring buffer for the WebUI and +// fans every new event out to live subscribers. +type LogBroker struct { mu sync.RWMutex buffer []LogEvent start int @@ -36,14 +40,17 @@ type LogHub struct { nextSub uint64 } -func NewLogHub(capacity int) *LogHub { +// LogHub creates a LogBroker that keeps the last capacity events, at least 100. +func LogHub(capacity int) *LogBroker { if capacity < 100 { capacity = 100 } - return &LogHub{buffer: make([]LogEvent, capacity), subscribers: make(map[uint64]*logSubscriber)} + return &LogBroker{buffer: make([]LogEvent, capacity), subscribers: make(map[uint64]*logSubscriber)} } -func (h *LogHub) Resize(capacity int) { +// Resize changes the buffer capacity (at least 100), keeping the newest events +// that still fit. +func (h *LogBroker) Resize(capacity int) { if capacity < 100 { capacity = 100 } @@ -62,7 +69,9 @@ func (h *LogHub) Resize(capacity int) { h.mu.Unlock() } -func (h *LogHub) Publish(event LogEvent) { +// Publish assigns event the next sequence number, stores it, overwriting the +// oldest event when the buffer is full, and offers it to every subscriber. +func (h *LogBroker) Publish(event LogEvent) { h.mu.Lock() h.next++ event.Sequence = h.next @@ -78,14 +87,19 @@ func (h *LogHub) Publish(event LogEvent) { select { case sub.ch <- event: default: - // A slow browser must never block request processing. Its reconnect - // cursor will make the gap visible on the next subscription. + // A slow browser must never block request processing. The dropped + // event leaves a hole in the sequence numbers, which the subscriber + // can report as a gap. } } h.mu.Unlock() } -func (h *LogHub) Recent(after uint64, limit int) ([]LogEvent, bool) { +// Recent returns the buffered events with a sequence number above after, at +// most limit of the newest (the whole buffer when limit is out of range). The +// second result reports a gap: events following after have already been +// overwritten. +func (h *LogBroker) Recent(after uint64, limit int) ([]LogEvent, bool) { h.mu.RLock() defer h.mu.RUnlock() if limit < 1 || limit > len(h.buffer) { @@ -109,7 +123,10 @@ func (h *LogHub) Recent(after uint64, limit int) ([]LogEvent, bool) { return out, gap } -func (h *LogHub) Subscribe() (<-chan LogEvent, func()) { +// Subscribe returns a channel of newly published events and a function that +// ends the subscription. The channel buffers 128 events; Publish drops events +// that do not fit instead of blocking. The channel is never closed. +func (h *LogBroker) Subscribe() (<-chan LogEvent, func()) { h.mu.Lock() h.nextSub++ id := h.nextSub @@ -123,26 +140,34 @@ func (h *LogHub) Subscribe() (<-chan LogEvent, func()) { } } +// hubHandler is the slog.Handler behind StructuredLogger. It passes each +// record to base and publishes a redacted copy to hub. type hubHandler struct { base slog.Handler - hub *LogHub - redactor *config.SecretRedactor + hub *LogBroker + redactor *config.Redactor attrs []slog.Attr groups []string } -func NewStructuredLogger(level *slog.LevelVar, hub *LogHub, redactor *config.SecretRedactor) *slog.Logger { - return newStructuredLogger(os.Stdout, level, hub, redactor) +// StructuredLogger returns a logger that writes JSON to stdout and mirrors +// every record into hub. Both outputs pass through redactor, and attributes +// whose keys mention a password, authorization, cookie or secret are masked. +func StructuredLogger(level *slog.LevelVar, hub *LogBroker, redactor *config.Redactor) *slog.Logger { + return structuredLogger(os.Stdout, level, hub, redactor) } -func newStructuredLogger(output io.Writer, level *slog.LevelVar, hub *LogHub, redactor *config.SecretRedactor) *slog.Logger { +// structuredLogger is StructuredLogger with an explicit JSON output. +func structuredLogger(output io.Writer, level *slog.LevelVar, hub *LogBroker, redactor *config.Redactor) *slog.Logger { base := slog.NewJSONHandler(output, &slog.HandlerOptions{Level: level, ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr { return sanitizeLogAttr(redactor, attr) }}) return slog.New(&hubHandler{base: base, hub: hub, redactor: redactor}) } -func sanitizeLogAttr(redactor *config.SecretRedactor, attr slog.Attr) slog.Attr { +// sanitizeLogAttr prepares an attribute for the JSON output: a sensitive key +// masks the value, and string and error values pass through redactor. +func sanitizeLogAttr(redactor *config.Redactor, attr slog.Attr) slog.Attr { attr.Value = attr.Value.Resolve() lower := strings.ToLower(attr.Key) if strings.Contains(lower, "password") || strings.Contains(lower, "authorization") || strings.Contains(lower, "cookie") || strings.Contains(lower, "secret") { @@ -201,6 +226,8 @@ func (h *hubHandler) WithGroup(name string) slog.Handler { return &clone } +// addAttr stores attr in fields under its dotted group path. A sensitive key +// masks the value; strings and values of non-scalar kinds are redacted as text. func (h *hubHandler) addAttr(fields map[string]any, attr slog.Attr) { attr.Value = attr.Value.Resolve() key := attr.Key @@ -234,6 +261,8 @@ func (h *hubHandler) addAttr(fields map[string]any, attr slog.Attr) { fields[key] = value } +// SetLogLevel applies a configured level name to level. Anything other than +// "debug", "warn" or "error" selects info. func SetLogLevel(level *slog.LevelVar, value string) { switch value { case "debug": diff --git a/internal/telemetry/metrics.go b/internal/telemetry/metrics.go index 30b4573..ca5852d 100644 --- a/internal/telemetry/metrics.go +++ b/internal/telemetry/metrics.go @@ -9,6 +9,8 @@ import ( "opencode2api/internal/protocol" ) +// metricBucket holds the request metrics of one minute. Metrics keeps 60 of +// them, indexed by minute modulo 60, to cover the last hour. type metricBucket struct { minute int64 total uint64 @@ -29,6 +31,7 @@ type metricBucket struct { usageKeys map[string]ServerKeyUsage } +// reset clears the bucket for reuse by minute. func (b *metricBucket) reset(minute int64) { *b = metricBucket{ minute: minute, endpoints: make(map[string]uint64), models: make(map[string]uint64), @@ -38,6 +41,7 @@ func (b *metricBucket) reset(minute int64) { } } +// TokenCounts sums the token usage the upstream reported. type TokenCounts struct { Input uint64 `json:"input_tokens"` Output uint64 `json:"output_tokens"` @@ -46,6 +50,9 @@ type TokenCounts struct { Total uint64 `json:"total_tokens"` } +// UsagePeriod is the token usage of the requests routed to a tier over one +// period. Coverage is the share of those Requests whose usage the upstream +// Reported. type UsagePeriod struct { Requests uint64 `json:"requests"` Reported uint64 `json:"reported"` @@ -62,22 +69,27 @@ type UsagePeriod struct { ServerKeys map[string]ServerKeyUsage `json:"server_keys"` } +// ServerKeyUsage is the request count and token usage of one server key. type ServerKeyUsage struct { Requests uint64 `json:"requests"` TokenCounts } +// UsageSnapshot is the token usage since start and over the last hour. type UsageSnapshot struct { Lifetime UsagePeriod `json:"lifetime"` Window UsagePeriod `json:"last_hour"` } +// AttemptCounts counts upstream attempts by result. type AttemptCounts struct { Total uint64 `json:"total"` Success uint64 `json:"success"` Failed uint64 `json:"failed"` } +// AttemptAggregate counts upstream attempts in total and per tier, channel and +// upstream key. type AttemptAggregate struct { AttemptCounts SuccessRate float64 `json:"success_rate"` @@ -86,6 +98,8 @@ type AttemptAggregate struct { Keys map[string]AttemptCounts `json:"keys"` } +// UpstreamAttempt is one upstream call made for a client request: one key or +// anonymous credential through one proxy. type UpstreamAttempt struct { Time time.Time `json:"time"` RequestID string `json:"request_id"` @@ -104,7 +118,8 @@ type UpstreamAttempt struct { // UpstreamRequest is the credential route that was actually used for one // client inference request. It is kept separately from UpstreamAttempt, -// because a single request can try several keys before it succeeds. +// because a single request can try several keys before it succeeds. A request +// that never reached an upstream is recorded too, with Channel "not_routed". type UpstreamRequest struct { Time time.Time `json:"time"` RequestID string `json:"request_id"` @@ -123,11 +138,15 @@ type UpstreamRequest struct { Outcome string `json:"outcome"` } +// attemptBucket holds the upstream attempts of one minute, like metricBucket. type attemptBucket struct { minute int64 aggregate AttemptAggregate } +// UpstreamSnapshot is the upstream attempt view of the monitor: aggregates +// since start and over the last hour, plus the newest requests and attempts of +// the last hour, oldest first. type UpstreamSnapshot struct { Lifetime AttemptAggregate `json:"lifetime"` Window AttemptAggregate `json:"last_hour"` @@ -135,23 +154,30 @@ type UpstreamSnapshot struct { Recent []UpstreamAttempt `json:"recent"` } +// The recent request and attempt buffers hold at most an hour of entries up to +// these capacities; a snapshot returns the newest monitorRecentOutputLimit. const ( monitorRecentRequestCapacity = 10000 monitorRecentAttemptCapacity = 20000 monitorRecentOutputLimit = 500 ) -type upstreamRequestRing struct { +// upstreamRequestBuffer is a fixed-capacity ring of recent requests in the +// order they were added. Add overwrites the oldest entry when it is full, and +// PruneBefore drops entries from the oldest end until one is not older than +// cutoff. +type upstreamRequestBuffer struct { items []UpstreamRequest start int count int } -func newUpstreamRequestRing() upstreamRequestRing { - return upstreamRequestRing{items: make([]UpstreamRequest, monitorRecentRequestCapacity)} +func upstreamRequestRing() upstreamRequestBuffer { + return upstreamRequestBuffer{items: make([]UpstreamRequest, monitorRecentRequestCapacity)} } -func (ring *upstreamRequestRing) Add(value UpstreamRequest) { +// Add appends value, overwriting the oldest entry once the ring is full. +func (ring *upstreamRequestBuffer) Add(value UpstreamRequest) { if len(ring.items) == 0 { ring.items = make([]UpstreamRequest, monitorRecentRequestCapacity) } @@ -165,7 +191,8 @@ func (ring *upstreamRequestRing) Add(value UpstreamRequest) { ring.count++ } -func (ring *upstreamRequestRing) PruneBefore(cutoff time.Time) { +// PruneBefore drops the oldest entries that are older than cutoff. +func (ring *upstreamRequestBuffer) PruneBefore(cutoff time.Time) { for ring.count > 0 && ring.items[ring.start].Time.Before(cutoff) { ring.items[ring.start] = UpstreamRequest{} ring.start = (ring.start + 1) % len(ring.items) @@ -173,7 +200,9 @@ func (ring *upstreamRequestRing) PruneBefore(cutoff time.Time) { } } -func (ring *upstreamRequestRing) Snapshot(cutoff time.Time, limit int) []UpstreamRequest { +// Snapshot copies the newest limit entries that are not older than cutoff, +// oldest first. +func (ring *upstreamRequestBuffer) Snapshot(cutoff time.Time, limit int) []UpstreamRequest { if limit < 1 || ring.count == 0 { return nil } @@ -190,17 +219,19 @@ func (ring *upstreamRequestRing) Snapshot(cutoff time.Time, limit int) []Upstrea return result } -type upstreamAttemptRing struct { +// upstreamAttemptBuffer is the upstreamRequestBuffer counterpart for attempts. +type upstreamAttemptBuffer struct { items []UpstreamAttempt start int count int } -func newUpstreamAttemptRing() upstreamAttemptRing { - return upstreamAttemptRing{items: make([]UpstreamAttempt, monitorRecentAttemptCapacity)} +func upstreamAttemptRing() upstreamAttemptBuffer { + return upstreamAttemptBuffer{items: make([]UpstreamAttempt, monitorRecentAttemptCapacity)} } -func (ring *upstreamAttemptRing) Add(value UpstreamAttempt) { +// Add appends value, overwriting the oldest entry once the ring is full. +func (ring *upstreamAttemptBuffer) Add(value UpstreamAttempt) { if len(ring.items) == 0 { ring.items = make([]UpstreamAttempt, monitorRecentAttemptCapacity) } @@ -214,7 +245,8 @@ func (ring *upstreamAttemptRing) Add(value UpstreamAttempt) { ring.count++ } -func (ring *upstreamAttemptRing) PruneBefore(cutoff time.Time) { +// PruneBefore drops the oldest entries that are older than cutoff. +func (ring *upstreamAttemptBuffer) PruneBefore(cutoff time.Time) { for ring.count > 0 && ring.items[ring.start].Time.Before(cutoff) { ring.items[ring.start] = UpstreamAttempt{} ring.start = (ring.start + 1) % len(ring.items) @@ -222,7 +254,9 @@ func (ring *upstreamAttemptRing) PruneBefore(cutoff time.Time) { } } -func (ring *upstreamAttemptRing) Snapshot(cutoff time.Time, limit int) []UpstreamAttempt { +// Snapshot copies the newest limit entries that are not older than cutoff, +// oldest first. +func (ring *upstreamAttemptBuffer) Snapshot(cutoff time.Time, limit int) []UpstreamAttempt { if limit < 1 || ring.count == 0 { return nil } @@ -239,7 +273,10 @@ func (ring *upstreamAttemptRing) Snapshot(cutoff time.Time, limit int) []Upstrea return result } -type Monitor struct { +// Metrics aggregates request, token usage and upstream attempt statistics for +// the WebUI monitor: totals since start plus a per-minute view of the last +// hour. The request counters are atomic; mu guards everything else. +type Metrics struct { started time.Time active atomic.Int64 activeStreams atomic.Int64 @@ -252,30 +289,37 @@ type Monitor struct { sessionSeen map[string]int64 attemptLifetime AttemptAggregate attemptBuckets [60]attemptBucket - recentRequests upstreamRequestRing - recentAttempts upstreamAttemptRing + recentRequests upstreamRequestBuffer + recentAttempts upstreamAttemptBuffer } -func NewMonitor() *Monitor { - return &Monitor{ +// Monitor creates an empty Metrics whose uptime starts now. +func Monitor() *Metrics { + return &Metrics{ started: time.Now().UTC(), - lifetimeUsage: newUsagePeriod(), + lifetimeUsage: usagePeriod(), sessionSeen: make(map[string]int64), - attemptLifetime: newAttemptAggregate(), - recentRequests: newUpstreamRequestRing(), - recentAttempts: newUpstreamAttemptRing(), + attemptLifetime: attemptAggregate(), + recentRequests: upstreamRequestRing(), + recentAttempts: upstreamAttemptRing(), } } // BeginStream records a stream entering its response body phase. -func (m *Monitor) BeginStream() { m.activeStreams.Add(1) } +func (m *Metrics) BeginStream() { m.activeStreams.Add(1) } // EndStream releases a stream recorded by BeginStream. -func (m *Monitor) EndStream() { m.activeStreams.Add(-1) } +func (m *Metrics) EndStream() { m.activeStreams.Add(-1) } +// latencyBounds are the upper bounds, in milliseconds, of the latency +// histogram buckets. The histogram's last bucket counts slower requests. var latencyBounds = [...]uint64{50, 100, 250, 500, 1000, 2500, 5000, 10000, 30000, 60000} -func (m *Monitor) Record(endpoint string, status int, duration time.Duration, meta *RequestMeta) { +// Record accounts one finished HTTP request. Every request counts toward the +// totals, latency, endpoints and statuses. Token usage is counted once the +// request was routed to a tier, and a request that carries a request ID and a +// model joins the recent requests. +func (m *Metrics) Record(endpoint string, status int, duration time.Duration, meta *RequestMeta) { success := requestSucceeded(status, meta) m.total.Add(1) if success { @@ -355,12 +399,17 @@ func (m *Monitor) Record(endpoint string, status int, duration time.Duration, me m.mu.Unlock() } -// A stream can fail after HTTP headers have been sent. Preserve its HTTP -// status while using the terminal result for request success and error counts. +// requestSucceeded reports whether a request counts as a success: a 2xx or 3xx +// status and no terminal failure in meta.Outcome. A stream can fail after HTTP +// headers have been sent. Preserve its HTTP status while using the terminal +// result for request success and error counts. func requestSucceeded(status int, meta *RequestMeta) bool { return status >= 200 && status < 400 && (meta == nil || meta.Outcome == "") } +// requestOutcome classifies a request that carries no explicit outcome. A +// request without a channel, or with the "not_routed" default, never reached an +// upstream. func requestOutcome(status int, channel string) string { if channel == "" || channel == "not_routed" { return "not_routed" @@ -377,7 +426,8 @@ func requestOutcome(status int, channel string) string { return "unknown" } -func (m *Monitor) RecordAttempt(attempt UpstreamAttempt) { +// RecordAttempt accounts one upstream attempt; a zero Time means now. +func (m *Metrics) RecordAttempt(attempt UpstreamAttempt) { if attempt.Time.IsZero() { attempt.Time = time.Now().UTC() } else { @@ -388,7 +438,7 @@ func (m *Monitor) RecordAttempt(attempt UpstreamAttempt) { recordAttemptAggregate(&m.attemptLifetime, attempt) bucket := &m.attemptBuckets[minute%60] if bucket.minute != minute { - *bucket = attemptBucket{minute: minute, aggregate: newAttemptAggregate()} + *bucket = attemptBucket{minute: minute, aggregate: attemptAggregate()} } recordAttemptAggregate(&bucket.aggregate, attempt) m.recentAttempts.PruneBefore(attempt.Time.Add(-time.Hour)) @@ -396,6 +446,9 @@ func (m *Monitor) RecordAttempt(attempt UpstreamAttempt) { m.mu.Unlock() } +// MonitorSnapshot is the WebUI monitor view of Metrics. Lifetime covers the +// time since start and Window the last hour, which Series breaks down per +// minute; the per-endpoint, model, tier and status counts cover the last hour. type MonitorSnapshot struct { StartedAt time.Time `json:"started_at"` UptimeSeconds int64 `json:"uptime_seconds"` @@ -412,6 +465,9 @@ type MonitorSnapshot struct { Upstream UpstreamSnapshot `json:"upstream"` } +// MetricSummary counts requests by result. The latency fields are filled only +// for the last hour, and each percentile is the upper bound of the histogram +// bucket that holds it. type MetricSummary struct { Total uint64 `json:"total"` Success uint64 `json:"success"` @@ -423,6 +479,7 @@ type MetricSummary struct { P99MS uint64 `json:"p99_ms,omitempty"` } +// MetricSeries is one minute of the last-hour series. type MetricSeries struct { Minute time.Time `json:"minute"` Total uint64 `json:"total"` @@ -438,7 +495,7 @@ type MetricSeries struct { // ServerKeyUsage returns per-server-key usage for the lifetime and the last // hour. The API key list polls it, so it skips building a full Snapshot. -func (m *Monitor) ServerKeyUsage() (lifetime, window map[string]ServerKeyUsage) { +func (m *Metrics) ServerKeyUsage() (lifetime, window map[string]ServerKeyUsage) { nowMinute := time.Now().Unix() / 60 lifetime, window = make(map[string]ServerKeyUsage), make(map[string]ServerKeyUsage) m.mu.Lock() @@ -457,14 +514,16 @@ func (m *Monitor) ServerKeyUsage() (lifetime, window map[string]ServerKeyUsage) return lifetime, window } -func (m *Monitor) Snapshot() MonitorSnapshot { +// Snapshot builds the monitor view. It also prunes recent requests and +// attempts older than an hour. +func (m *Metrics) Snapshot() MonitorSnapshot { nowMinute := time.Now().Unix() / 60 window := MetricSummary{} var histogram [11]uint64 endpoints, models, tiers, statuses := map[string]uint64{}, map[string]uint64{}, map[string]uint64{}, map[string]uint64{} series := make([]MetricSeries, 0, 60) - usageWindow := newUsagePeriod() - upstreamWindow := newAttemptAggregate() + usageWindow := usagePeriod() + upstreamWindow := attemptAggregate() var recentRequests []UpstreamRequest var recentAttempts []UpstreamAttempt m.mu.Lock() @@ -542,7 +601,8 @@ func mergeCounts(target, source map[string]uint64) { } } -func newUsagePeriod() UsagePeriod { +// usagePeriod returns an empty UsagePeriod with its maps allocated. +func usagePeriod() UsagePeriod { return UsagePeriod{Models: make(map[string]TokenCounts), Tiers: make(map[string]TokenCounts), Sessions: make(map[string]TokenCounts), ServerKeys: make(map[string]ServerKeyUsage)} } @@ -594,7 +654,10 @@ func mergeTokenMaps(target, source map[string]TokenCounts) { // short-lived and stay uncapped. const maxLifetimeSessions = 500 -func (m *Monitor) addLifetimeSessionLocked(session string, tokens TokenCounts) { +// addLifetimeSessionLocked adds tokens to the lifetime total of session and +// marks it as just seen, evicting the least recently seen session first when +// the map is full. The caller holds m.mu. +func (m *Metrics) addLifetimeSessionLocked(session string, tokens TokenCounts) { if session == "" { return } @@ -613,7 +676,7 @@ func (m *Monitor) addLifetimeSessionLocked(session string, tokens TokenCounts) { } func cloneUsagePeriod(source UsagePeriod) UsagePeriod { - result := newUsagePeriod() + result := usagePeriod() result.Requests, result.Reported, result.Tokens = source.Requests, source.Reported, source.Tokens mergeTokenMaps(result.Models, source.Models) mergeTokenMaps(result.Tiers, source.Tiers) @@ -630,7 +693,8 @@ func finalizeUsagePeriod(period *UsagePeriod) { } } -func newAttemptAggregate() AttemptAggregate { +// attemptAggregate returns an empty AttemptAggregate with its maps allocated. +func attemptAggregate() AttemptAggregate { return AttemptAggregate{ Tiers: make(map[string]AttemptCounts), Channels: make(map[string]AttemptCounts), Keys: make(map[string]AttemptCounts), } @@ -681,7 +745,7 @@ func mergeAttemptMaps(target, source map[string]AttemptCounts) { } func cloneAttemptAggregate(source AttemptAggregate) AttemptAggregate { - result := newAttemptAggregate() + result := attemptAggregate() mergeAttemptAggregate(&result, source) return result } @@ -692,6 +756,8 @@ func finalizeAttemptAggregate(aggregate *AttemptAggregate) { } } +// histogramPercentile returns the upper bound of the bucket holding the given +// percentile of total, or one past the last bound for the overflow bucket. func histogramPercentile(histogram [11]uint64, total uint64, percentile float64) uint64 { target := uint64(float64(total)*percentile + 0.999) var count uint64 diff --git a/internal/telemetry/recovery.go b/internal/telemetry/recovery.go index f6d134a..4738b27 100644 --- a/internal/telemetry/recovery.go +++ b/internal/telemetry/recovery.go @@ -7,6 +7,8 @@ import ( "opencode2api/internal/protocol" ) +// Recover turns a panic in next into a logged error and a 500 response in the +// Chat error format. func Recover(logger *slog.Logger, next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer func() { diff --git a/webui/index.html b/webui/index.html index b5a8bbd..5070ce3 100644 --- a/webui/index.html +++ b/webui/index.html @@ -405,7 +405,7 @@

模型 Metadata

- models.dev OpenCode 价格缓存状态。 + OpenCode 元数据价格缓存状态。

diff --git a/webui/js/i18n.js b/webui/js/i18n.js index e222735..e14058e 100644 --- a/webui/js/i18n.js +++ b/webui/js/i18n.js @@ -212,7 +212,7 @@ const DICTIONARY = { "diagnostics.metadata.title": "Model metadata", "diagnostics.metadata.caption": - "Status of the OpenCode price cache from models.dev; a price of 0 or a name containing free is enough to qualify for the anonymous channel.", + "Status of the price cache from the OpenCode metadata endpoint; a price of 0 or a name containing free is enough to qualify for the anonymous channel.", "diagnostics.last.title": "Latest playground run", "diagnostics.last.caption": "Only the last run is retained in the current admin process.", @@ -758,7 +758,7 @@ const DICTIONARY = { "diagnostics.metadata.title": "Metadata mô hình", "diagnostics.metadata.caption": - "Trạng thái cache giá OpenCode từ models.dev; giá bằng 0 hoặc tên chứa free là đủ điều kiện vào kênh ẩn danh.", + "Trạng thái cache giá từ điểm cuối metadata OpenCode; giá bằng 0 hoặc tên chứa free là đủ điều kiện vào kênh ẩn danh.", "diagnostics.last.title": "Playground gần nhất", "diagnostics.last.caption": "Chỉ giữ lần theo dõi cuối cùng trong tiến trình quản trị hiện tại.",