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

Merge pull request #33
This commit is contained in:
Jason Xu authored and GitHub committed 2026-09-19 13:05:54 +08:00
commit e5f4e3a583
4 files changed
+82 -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.
+49 -1
View File
@@ -344,6 +344,9 @@ func prepareAnonymousBody(body []byte, protocol wire.Protocol) []byte {
payload["stream"] = true
changed = true
}
if ensureAnonymousChatUsage(payload, protocol) {
changed = true
}
if ensureAnonymousTools(payload, protocol) {
changed = true
}
@@ -357,6 +360,26 @@ func prepareAnonymousBody(body []byte, protocol wire.Protocol) []byte {
return encoded
}
// 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.
func ensureAnonymousChatUsage(payload map[string]any, protocol wire.Protocol) bool {
if protocol != wire.Chat {
return false
}
options, ok := payload["stream_options"].(map[string]any)
if !ok {
payload["stream_options"] = map[string]any{"include_usage": true}
return true
}
includeUsage, ok := options["include_usage"].(bool)
if ok && includeUsage {
return false
}
options["include_usage"] = true
return true
}
// ensureAnonymousTools appends minimal definitions for any missing core
// tool so the request reads as an agent session upstream. It reports
// whether the payload changed. Tools the client already declared are left
@@ -500,7 +523,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 +557,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 +605,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,