Files
opencode2api/internal/admin/debug.go
T
Jason Xu 81ad2842c7 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.
2026-10-19 03:46:09 +08:00

304 lines
11 KiB
Go

package admin
import (
"bytes"
"encoding/json"
"net/http"
"strings"
"time"
"opencode2api/internal/config"
"opencode2api/internal/gateway"
"opencode2api/internal/httpx"
"opencode2api/internal/jsonutil"
modelcatalog "opencode2api/internal/models"
"opencode2api/internal/protocol"
"opencode2api/internal/telemetry"
)
// DebugKeySelection tells the Playground whether to use normal routing or to
// 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"`
DurationMS int64 `json:"duration_ms"`
RequestID string `json:"request_id,omitempty"`
Route modelcatalog.RouteDiagnostic `json:"route"`
SelectedKey *gateway.DebugKeyView `json:"selected_key,omitempty"`
KeyTest string `json:"key_test,omitempty"`
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
keys := a.manager.DebugKeys()
a.mu.Lock()
last := a.lastInference
a.mu.Unlock()
w.Header().Set("Cache-Control", "no-store")
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")
return
}
var input DebugInferenceRequest
if err := decodeAdminJSON(w, r, &input); err != nil {
writeAdminError(w, http.StatusBadRequest, "invalid_request", err.Error())
return
}
if !protocol.Valid(input.Protocol) {
writeAdminError(w, http.StatusBadRequest, "invalid_protocol", "protocol must be chat, responses, or anthropic")
return
}
if input.Request == nil {
writeAdminError(w, http.StatusBadRequest, "invalid_request", "request must be a JSON object")
return
}
payload := jsonutil.CloneMap(input.Request)
payload["stream"] = false
model := jsonutil.StringAt(payload, "model")
if model == "" {
writeAdminError(w, http.StatusBadRequest, "invalid_request", "request.model is required")
return
}
if input.Key.Mode == "" {
input.Key.Mode = "auto"
}
if input.Key.Mode != "auto" && input.Key.Mode != "selected" {
writeAdminError(w, http.StatusBadRequest, "invalid_key_mode", "key.mode must be auto or selected")
return
}
var selectedKey *gateway.DebugKeyView
if input.Key.Mode == "selected" {
selectedKey = a.manager.DebugKey(input.Key.Tier, input.Key.ID)
if selectedKey == nil {
writeAdminError(w, http.StatusBadRequest, "unknown_key_id", "selected key is not configured")
return
}
}
route := a.manager.DebugRoute(model, input.Protocol)
if selectedKey != nil {
selected, routeErr := a.manager.DebugRouteForTier(model, selectedKey.Tier)
if routeErr != nil {
writeAdminError(w, http.StatusBadRequest, "model_unavailable_for_key_tier", routeErr.Error())
return
}
route = selected
}
encoded, err := json.Marshal(payload)
if err != nil {
writeAdminError(w, http.StatusBadRequest, "invalid_request", "request contains unsupported JSON values")
return
}
path := protocol.Path(input.Protocol)
trace := &telemetry.RequestMeta{}
ctx := telemetry.WithRequestMeta(gateway.WithDiagnosticRequest(r.Context()), trace)
request, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://gateway.local"+path, bytes.NewReader(encoded))
if err != nil {
writeAdminError(w, http.StatusInternalServerError, "debug_request_failed", "could not construct Gateway request")
return
}
cfg := a.manager.Config()
if cfg.FirstEnabledServerKey() == "" {
writeAdminError(w, http.StatusServiceUnavailable, "debug_unavailable", "no local server key is configured")
return
}
request.Header.Set("Authorization", "Bearer "+cfg.FirstEnabledServerKey())
if selectedKey != nil {
request = request.WithContext(gateway.WithDebugKeyOverride(request.Context(), gateway.DebugKeyOverride{Tier: selectedKey.Tier, KeyID: selectedKey.ID}))
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json")
recorder := debugResponseRecorder()
started := time.Now()
a.manager.Handler().ServeHTTP(recorder, request)
duration := time.Since(started)
requestID := recorder.Header().Get("x-request-id")
if trace.Channel != "" {
route.Anonymous = trace.Anonymous
route.Tier = config.Tier(trace.Tier)
route.KeyID = trace.KeyID
route.Channel = trace.Channel
route.Attempts = trace.Attempts
route.NativeProtocol = trace.Protocol
}
var raw any
if json.Unmarshal(recorder.body.Bytes(), &raw) != nil {
raw = recorder.body.String()
}
raw = sanitizeDebugValue(raw, a.manager.Redact)
keyTest := ""
if selectedKey != nil {
if current := a.manager.DebugKey(selectedKey.Tier, selectedKey.ID); current != nil {
selectedKey = current
}
keyTest = classifyKeyTest(recorder.status, trace.AttemptOutcome)
}
result := DebugInferenceResult{
OK: recorder.status >= 200 && recorder.status < 300, HTTPStatus: recorder.status,
DurationMS: max(duration.Milliseconds(), 0), RequestID: requestID, Route: route,
SelectedKey: selectedKey, KeyTest: keyTest, Response: raw,
}
a.mu.Lock()
a.lastInference = &result
a.mu.Unlock()
w.Header().Set("Cache-Control", "no-store")
httpx.WriteJSON(w, http.StatusOK, result)
}
// 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
}
// 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 *debugResponseCapture) Header() http.Header { return recorder.header }
func (recorder *debugResponseCapture) WriteHeader(status int) {
if recorder.status != http.StatusOK || status == http.StatusOK {
return
}
recorder.status = status
}
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:
result := make(map[string]any, len(current))
for key, item := range current {
lower := strings.ToLower(key)
if sensitiveDebugKey(lower) {
result[key] = "***"
continue
}
result[key] = sanitizeDebugValue(item, redact)
}
return result
case []any:
result := make([]any, len(current))
for index, item := range current {
result[index] = sanitizeDebugValue(item, redact)
}
return result
case string:
return redact(current)
default:
return value
}
}
// 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()
now := time.Now()
window := a.debugAttempts[client]
if window.Started.IsZero() || now.Sub(window.Started) >= time.Minute {
window = loginWindow{Started: now}
}
if window.Count >= 12 {
return false
}
window.Count++
a.debugAttempts[client] = window
if len(a.debugAttempts) > 4096 {
for key, candidate := range a.debugAttempts {
if now.Sub(candidate.Started) >= time.Minute {
delete(a.debugAttempts, key)
}
}
}
return true
}
// classifyKeyTest turns a per-key diagnostic into a verdict about that key.
// Only statuses that are unambiguous about the credential are reported as key
// problems: a 4xx request-shape error says nothing about the key, and a 5xx may
// be entirely unrelated to it.
func classifyKeyTest(status int, attemptOutcome string) string {
switch {
case attemptOutcome == "transport_error":
return "transport_error"
case status >= 200 && status < 300:
return "usable"
case status == http.StatusUnauthorized || status == http.StatusForbidden:
return "rejected"
case status == http.StatusTooManyRequests:
return "rate_limited"
case status == 0:
return "unavailable"
case status >= 500:
return "upstream_error"
default:
return "request_error"
}
}
// 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",
"access_token", "refresh_token", "set-cookie", "credential",
} {
if strings.Contains(key, hint) {
return true
}
}
return false
}