fix: shape key-tier free-model bodies to agent shape

Upstream now rejects non-agent-shaped free-tier requests on every lane
with 403 FreeTierError (#29); #31 covered the anonymous lane only, so
keyed-only configs still 403 on bare probes. Mirror the normalization
(stream + core agent tools) for catalog-free models on key tiers; paid
bodies untouched. Non-streaming clients get the same stream collapse
as the anonymous lane. Free check uses catalog pricing metadata, not
the -free name, so nameless free models are covered.
This commit is contained in:
sk-dev-ai committed 2026-09-18 19:38:29 +05:30
1 parent 5cf3b590ee
commit 79378c8744
4 files changed
+59 -13

No files matched your search

+3 -1
View File
@@ -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.
+26 -1
View File
@@ -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
+9
View File
@@ -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]
+21 -11
View File
@@ -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,