Files

329 lines
11 KiB
Go

package gateway
import (
"net/http"
"slices"
"time"
"opencode2api/internal/buildinfo"
"opencode2api/internal/config"
"opencode2api/internal/httpx"
modelcatalog "opencode2api/internal/models"
"opencode2api/internal/oauth"
wire "opencode2api/internal/protocol"
)
type healthResponse struct {
Status string `json:"status"`
Ready bool `json:"ready"`
Version string `json:"version"`
Models healthModels `json:"models"`
Keys healthKeys `json:"keys"`
Proxies healthProxies `json:"proxies"`
Warp *healthWarp `json:"warp,omitempty"`
Issues []string `json:"issues,omitempty"`
}
type healthModels struct {
Status string `json:"status"`
Total int `json:"total"`
Exposed int `json:"exposed"`
Zen int `json:"zen"`
Go int `json:"go"`
LastRefresh *time.Time `json:"last_refresh,omitempty"`
StaleAfterSeconds int `json:"stale_after_seconds"`
CacheSource string `json:"cache_source,omitempty"`
Stale bool `json:"stale"`
}
type healthKeys struct {
Zen int `json:"zen"`
Go int `json:"go"`
Total int `json:"total"`
Anonymous bool `json:"anonymous"`
}
type healthProxies struct {
Total int `json:"total"`
Healthy int `json:"healthy"`
Unhealthy int `json:"unhealthy"`
}
// healthWarp reports the state of the userspace WARP pool. It is omitted when
// the switch is off so existing readiness consumers see the same document.
type healthWarp struct {
Status string `json:"status"`
Stack string `json:"stack"`
Size int `json:"size"`
Preload int `json:"preload"`
Active int `json:"active"`
Standby int `json:"standby"`
Cooling int `json:"cooling"`
}
// handleHealth reports readiness. It answers 503 while the model catalog is
// pending or empty, while WARP is enabled but no exit is active, or while no
// proxy is healthy when free traffic cannot leave through WARP (WARP off, or Go
// keys configured). 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()
sharedHealthy := proxyHealthy
for _, proxy := range g.transports.items {
if proxy.keysOnly && proxy.healthy.Load() {
sharedHealthy--
}
}
zenKeys, goKeys := g.zenNodes.Len(), g.goNodes.Len()
if g.cfg.ZenOAuth != nil {
zenKeys = 1
}
if g.cfg.GoOAuth != nil {
goKeys = 1
}
staleAfter := max(2*time.Duration(g.cfg.Models.RefreshSeconds)*time.Second, time.Minute)
var warpStatus *healthWarp
warpActive := 0
if g.warp != nil {
snapshot := g.warp.Snapshot()
warpActive = snapshot.Active
warpStatus = &healthWarp{
Status: "unavailable",
Stack: snapshot.Stack,
Size: snapshot.Size,
Preload: snapshot.Preload,
Active: snapshot.Active,
Standby: snapshot.Standby,
Cooling: snapshot.Cooling,
}
if snapshot.Active > 0 {
warpStatus.Status = "ready"
}
}
modelStatus := "ready"
var lastRefresh *time.Time
issues := make([]string, 0, 3)
if g.cfg.GoOAuth != nil && g.cfg.GoOAuth.NeedsLogin {
issues = append(issues, "go_oauth_authorization_required")
}
if g.cfg.ZenOAuth != nil && g.cfg.ZenOAuth.NeedsLogin {
issues = append(issues, "zen_oauth_authorization_required")
}
if models.UpdatedAt.IsZero() {
modelStatus = "pending"
issues = append(issues, "model_catalog_pending")
} else {
updatedAt := models.UpdatedAt.UTC()
lastRefresh = &updatedAt
if models.Exposed == 0 {
modelStatus = "empty"
issues = append(issues, "model_catalog_empty")
} else if models.Stale || time.Since(models.UpdatedAt) > staleAfter {
modelStatus = "stale"
issues = append(issues, "model_catalog_stale")
}
}
if zenKeys+goKeys == 0 && !g.cfg.Anonymous {
issues = append(issues, "no_upstream_keys")
}
warpBlocking := g.warp != nil && warpActive == 0
if warpBlocking {
issues = append(issues, "warp_unavailable")
}
// Proxies carry Go-tier traffic whenever Go keys exist, and every lane
// while WARP is off; free-model traffic alone does not need them.
proxyBlocking := proxyHealthy == 0 && (g.warp == nil || goKeys > 0 || g.cfg.ZenOAuth != nil)
sharedRequired := g.cfg.GoOAuth != nil || g.cfg.ZenOAuth != nil || g.cfg.Anonymous && g.warp == nil
if sharedRequired && sharedHealthy == 0 {
proxyBlocking = true
issues = append(issues, "no_healthy_shared_proxies")
}
if proxyHealthy == 0 {
issues = append(issues, "no_healthy_proxies")
}
status := "ok"
if len(issues) > 0 {
status = "degraded"
}
blocking := modelStatus == "pending" || modelStatus == "empty" || warpBlocking || proxyBlocking
httpStatus := http.StatusOK
ready := !blocking
if blocking {
httpStatus = http.StatusServiceUnavailable
if modelStatus == "pending" {
status = "starting"
}
}
httpx.WriteJSON(w, httpStatus, healthResponse{
Status: status,
Ready: ready,
Version: buildinfo.Version,
Models: healthModels{
Status: modelStatus,
Total: models.Total,
Exposed: models.Exposed,
Zen: models.Zen,
Go: models.Go,
LastRefresh: lastRefresh,
StaleAfterSeconds: int(staleAfter / time.Second),
CacheSource: models.CacheSource,
Stale: models.Stale,
},
Keys: healthKeys{Zen: zenKeys, Go: goKeys, Total: zenKeys + goKeys, Anonymous: g.cfg.Anonymous},
Proxies: healthProxies{
Total: proxyTotal,
Healthy: proxyHealthy,
Unhealthy: proxyTotal - proxyHealthy,
},
Warp: warpStatus,
Issues: issues,
})
}
func (g *Gateway) availableModels() ([]modelcatalog.Route, modelcatalog.CatalogSnapshot) {
if g.cfg.GoOAuth == nil && g.cfg.ZenOAuth == nil && !g.catalog.TierPending(config.TierGo) && !g.catalog.TierPending(config.TierZen) {
return g.catalog.AvailableModels(g.zenNodes.Len() > 0, g.goNodes.Len() > 0, g.cfg.Anonymous)
}
modelIDs := g.catalog.List()
seen := make(map[string]bool, len(modelIDs))
for _, model := range modelIDs {
seen[model] = true
}
for _, connection := range []*oauth.Connection{g.cfg.GoOAuth, g.cfg.ZenOAuth} {
if connection == nil {
continue
}
for model := range connection.Routes {
if !seen[model] {
modelIDs = append(modelIDs, model)
seen[model] = true
}
}
}
slices.Sort(modelIDs)
routes := make([]modelcatalog.Route, 0, len(modelIDs))
for _, model := range modelIDs {
if route, err := g.routeForModel(model, ""); err == nil {
routes = append(routes, route)
}
}
snapshot := g.catalog.Snapshot()
snapshot.Exposed = len(routes)
return routes, snapshot
}
// reasoningLevels are the effort values the gateway accepts and forwards, from
// lowest to highest. "auto" and "none" are gateway controls, not levels.
var reasoningLevels = []string{"minimal", "low", "medium", "high", "xhigh", "max"}
// reasoningEfforts lists the levels a reasoning model can be asked for. When an
// "auto" probe has found the highest level the upstream accepts, the list stops
// there so clients do not offer levels that would be rejected.
func (g *Gateway) reasoningEfforts(model string, route modelcatalog.Route) []string {
if g.cfg.ForcedEffort(model) == "auto" {
if ceiling := slices.Index(reasoningLevels, g.resolvedEffort(model, route.Tier, route.Protocol)); ceiling >= 0 {
return slices.Clone(reasoningLevels[:ceiling+1])
}
}
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()
names := g.modelNames(routes)
data := make([]map[string]any, 0, len(routes))
for _, route := range routes {
model := names.public[route.ID]
// Tier-scoped metadata: the advertised context window must match
// the tier that will serve the request (anonymous ⇒ Zen).
md := g.catalog.MetadataForTier(route.ID, route.Tier)
entry := map[string]any{
"id": model, "object": "model", "created": now, "owned_by": "opencode",
"metadata": md,
"native_protocol": route.Protocol,
}
if route.Protocol == wire.SystemOne {
entry["supported_endpoints"] = []string{"/v1/systemone"}
} else {
entry["supported_endpoints"] = []string{"/v1/chat/completions", "/v1/responses", "/v1/messages"}
}
// Top-level OpenAI-standard fields: discovery clients (jcode, Pi, …)
// read context/reasoning at the top level of each model entry.
if md.ContextWindow > 0 {
entry["context_window"] = md.ContextWindow
entry["context_length"] = md.ContextWindow
}
if md.MaxInput > 0 {
entry["max_input"] = md.MaxInput
}
if md.MaxOutput > 0 {
entry["max_output"] = md.MaxOutput
}
if md.Reasoning {
entry["reasoning"] = true
entry["supports_reasoning"] = true
efforts := g.reasoningEfforts(route.ID, route)
entry["reasoning_efforts"] = efforts
// OpenClaw and similar harnesses read effort levels from compat
// rather than inferring them, and otherwise offer only off/max.
entry["compat"] = map[string]any{"supportsReasoningEffort": true, "supportedReasoningEfforts": efforts}
if effort := g.resolvedEffort(route.ID, route.Tier, route.Protocol); effort != "" && effort != "none" {
entry["default_reasoning_effort"] = effort
}
}
if md.Cost != nil {
cost := map[string]any{}
// Camel-case aliases match OpenClaw's model cost shape.
for _, field := range []struct {
names []string
value *float64
}{
{[]string{"input"}, md.Cost.Input},
{[]string{"output"}, md.Cost.Output},
{[]string{"cache_read", "cacheRead"}, md.Cost.CacheRead},
{[]string{"cache_write", "cacheWrite"}, md.Cost.CacheWrite},
} {
if field.value == nil {
continue
}
for _, name := range field.names {
cost[name] = *field.value
}
}
entry["cost"] = cost
}
if md.ToolCall {
entry["tool_call"] = true
}
if md.StructuredOutput {
entry["structured_output"] = true
}
data = append(data, entry)
}
for _, group := range g.rotation.Snapshot().Groups {
if !g.goAvailable() {
continue
}
available := false
for _, model := range group.Order {
if route, err := g.routeForModel(model, config.TierGo); err == nil && route.Protocol != wire.SystemOne {
available = true
break
}
}
if !available {
continue
}
data = append(data, map[string]any{"id": group.Alias, "object": "model", "created": now, "owned_by": "opencode-go-rotation"})
}
httpx.WriteJSON(w, http.StatusOK, map[string]any{"object": "list", "data": data})
}