diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index c0eb60d..54df821 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -217,7 +217,9 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { wire.WriteError(w, external, http.StatusBadGateway, "failed to read upstream response", "upstream_error", ids.Request) return } - if upstreamRoute.Anonymous { + 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 forceStreamBody); // collapse the events back into the single document this // non-streaming client asked for. diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index a590b23..3d2f584 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -500,7 +500,20 @@ func (g *Gateway) dumpOutboundBodies(route models.Route, bodies map[config.Tier] } } -// doSelectedKeyUpstream sends exactly one attempt through the operator-selected +// shapeKeyBody normalizes key-tier free-model wire bodies to agent shape +// (stream + core 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 +// 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, bool) { + if !g.catalog.IsFreeModel(route.ID) { + return body, false + } + shaped := prepareAnonymousBody(body, route.ProtocolFor(tier)) + return shaped, !bytes.Equal(shaped, body) +} + // 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 @@ -521,6 +534,12 @@ func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route, if len(body) == 0 { return nil, fmt.Errorf("no prepared %s request body", override.Tier), 0 } + if shaped, changed := g.shapeKeyBody(body, route, override.Tier); changed { + body = shaped + if meta := telemetry.MetaFromContext(ctx); meta != nil { + meta.Shaped = true + } + } proxy := nodes.Proxy(node) if proxy == nil { return nil, errors.New("selected upstream key has no proxy binding"), 0 @@ -563,6 +582,12 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies if len(body) == 0 { return nil, fmt.Errorf("no prepared %s request body", route.Tier), 0 } + if shaped, changed := g.shapeKeyBody(body, route, route.Tier); changed { + body = shaped + if meta := telemetry.MetaFromContext(ctx); meta != nil { + meta.Shaped = true + } + } for attempts < g.cfg.Retry.MaxAttempts { if ctx.Err() != nil { // Same guard as the anonymous loop: an exhausted request budget diff --git a/internal/models/catalog.go b/internal/models/catalog.go index 18b7b6f..bac8874 100644 --- a/internal/models/catalog.go +++ b/internal/models/catalog.go @@ -317,6 +317,15 @@ func (c *Catalog) anonymousDecision(model string) AnonymousDecision { 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 { + 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 { c.mu.RLock() configured, explicit := c.protocols[model] diff --git a/internal/telemetry/http.go b/internal/telemetry/http.go index ea3c3c6..75758a9 100644 --- a/internal/telemetry/http.go +++ b/internal/telemetry/http.go @@ -5,22 +5,31 @@ import ( "context" "log/slog" "net/http" + "strings" "time" "opencode2api/internal/protocol" ) type RequestMeta struct { - Model string - Tier string - Protocol protocol.Protocol - Request string - KeyID string - Channel string - Anonymous bool - Proxy string - Attempts int - Stream bool + Model string + Tier string + Protocol protocol.Protocol + Request string + KeyID string + Channel string + Anonymous bool + Proxy string + Attempts int + Legs []string + Stop string + Tail string + Stream bool + // Shaped marks a key-tier free-model request whose wire body was + // normalized to agent shape (stream + core tools) like the anonymous + // lane. Non-streaming responses for shaped requests arrive as SSE + // and must be collapsed like anonymous ones. + Shaped bool Usage protocol.Usage UsageReported bool AttemptOutcome string @@ -103,7 +112,8 @@ func Middleware(monitor *Monitor, logger *slog.Logger, next http.Handler) http.H logger.Info("request routed", "component", "http", "event", "request_routed", "method", r.Method, "path", r.URL.Path, "status", status, "duration_ms", duration.Milliseconds(), "request_id", meta.Request, "model", meta.Model, "tier", meta.Tier, "key_id", meta.KeyID, "channel", meta.Channel, - "anonymous", meta.Anonymous, "attempts", meta.Attempts, "stream", meta.Stream, "outcome", outcome) + "anonymous", meta.Anonymous, "attempts", meta.Attempts, "legs", strings.Join(meta.Legs, " "), "stream", meta.Stream, "outcome", outcome, + "stop", meta.Stop, "in", meta.Usage.Input, "out", meta.Usage.Output, "reasoning_tokens", meta.Usage.Reasoning, "cached", meta.Usage.Cached, "tail", meta.Tail) } logger.Debug("request completed", "component", "http", "event", "request_complete", "method", r.Method, "path", r.URL.Path, "status", status, "duration_ms", duration.Milliseconds(), "bytes", writer.bytes,