fix: serve anonymous free tier as agent-shaped streams

Upstream now rejects anonymous free-tier requests unless they look
like real agent traffic: stream:true plus the core agent tools
(bash/edit/glob/grep/read), returning 403 FreeTierError otherwise.

Normalize the anonymous-lane wire body (force stream:true, inject
minimal definitions for any missing core tools) and collapse the
SSE stream back into the single JSON document non-streaming
clients asked for. Authenticated tiers are untouched.
This commit is contained in:
58 committed 2026-09-18 09:09:20 +08:00
1 parent fcd61ff58b
commit 2ce1f9e44b
3 files changed
+301

No files matched your search

+13
View File
@@ -2,6 +2,7 @@
package gateway
import (
"bytes"
"context"
"crypto/subtle"
"encoding/json"
@@ -216,6 +217,18 @@ 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 {
// The anonymous lane is served streaming (see forceStreamBody);
// collapse the events back into the single document this
// non-streaming client asked for.
collapsed, err := wire.CollapseStream(bytes.NewReader(responseBody), upstreamRoute.Protocol, model)
if err != nil {
g.logger.Warn("anonymous stream collapse failed", "component", "conversion", "event", "anonymous_collapse_failed", "request_id", ids.Request, "model", model, "source_protocol", upstreamRoute.Protocol, "error", err)
wire.WriteError(w, external, http.StatusBadGateway, "unsupported upstream response", "upstream_error", ids.Request)
return
}
responseBody = collapsed
}
if usage, reported := wire.ResponseUsage(upstreamRoute.Protocol, responseBody); meta != nil {
meta.Usage, meta.UsageReported = usage, reported
}
+141
View File
@@ -254,6 +254,12 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
if len(body) == 0 {
return nil, errors.New("no prepared Zen request body"), 0
}
// The anonymous free tier only serves agent-shaped streaming requests
// (anything else is rejected with 403 FreeTierError). Normalize the
// wire body here; the gateway collapses the stream back when the
// downstream client asked for a plain JSON reply. Key tiers keep their
// original bodies.
body = prepareAnonymousBody(body, route.ProtocolFor(config.TierZen))
for attempts < limit {
if ctx.Err() != nil {
// The request-level budget is already gone. Stop scanning instead
@@ -318,6 +324,141 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
return nil, lastErr, attempts
}
// anonymousCoreTools are the tool names the anonymous free tier expects on
// an agent-shaped request. Requests without them are rejected with 403
// FreeTierError. Only the names matter; the gateway synthesizes minimal
// definitions for whichever ones the downstream client did not declare.
var anonymousCoreTools = []string{"bash", "edit", "glob", "grep", "read"}
// prepareAnonymousBody returns a copy of body normalized for the anonymous
// free tier: streaming enabled plus the core agent tools present. Bodies
// that already satisfy both (or are not JSON objects) are returned
// unchanged.
func prepareAnonymousBody(body []byte, protocol wire.Protocol) []byte {
var payload map[string]any
if err := json.Unmarshal(body, &payload); err != nil {
return body
}
changed := false
if streaming, ok := payload["stream"].(bool); !ok || !streaming {
payload["stream"] = true
changed = true
}
if ensureAnonymousTools(payload, protocol) {
changed = true
}
if !changed {
return body
}
encoded, err := json.Marshal(payload)
if err != nil {
return body
}
return encoded
}
// 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
// untouched.
func ensureAnonymousTools(payload map[string]any, protocol wire.Protocol) bool {
raw, exists := payload["tools"]
if !exists {
payload["tools"] = anonymousToolset(protocol, nil)
return true
}
items, ok := raw.([]any)
if !ok {
return false
}
present := make(map[string]bool, len(items))
for _, item := range items {
if name := anonymousToolName(protocol, item); name != "" {
present[name] = true
}
}
missing := make([]string, 0, len(anonymousCoreTools))
for _, name := range anonymousCoreTools {
if !present[name] {
missing = append(missing, name)
}
}
if len(missing) == 0 {
return false
}
payload["tools"] = append(items, anonymousToolset(protocol, missing)...)
return true
}
func anonymousToolName(protocol wire.Protocol, item any) string {
entry, ok := item.(map[string]any)
if !ok {
return ""
}
if protocol == wire.Chat {
return jsonutil.StringAt(entry, "function", "name")
}
return jsonutil.StringAt(entry, "name")
}
func anonymousToolset(protocol wire.Protocol, names []string) []any {
if names == nil {
names = anonymousCoreTools
}
tools := make([]any, 0, len(names))
for _, name := range names {
tools = append(tools, anonymousTool(protocol, name))
}
return tools
}
func anonymousTool(protocol wire.Protocol, name string) map[string]any {
description := "Agent tool " + name
parameters := map[string]any{"type": "object", "properties": map[string]any{}}
switch protocol {
case wire.Chat:
return map[string]any{
"type": "function",
"function": map[string]any{
"name": name,
"description": description,
"parameters": parameters,
},
}
case wire.Anthropic:
return map[string]any{
"name": name,
"description": description,
"input_schema": parameters,
}
default:
return map[string]any{
"type": "function",
"name": name,
"description": description,
"parameters": parameters,
}
}
}
// forceStreamBody returns a copy of body with streaming enabled. Bodies
// that already stream (or are not JSON objects) are returned unchanged.
func forceStreamBody(body []byte) []byte {
var payload map[string]any
if err := json.Unmarshal(body, &payload); err != nil {
return body
}
if streaming, ok := payload["stream"].(bool); ok && streaming {
return body
}
payload["stream"] = true
encoded, err := json.Marshal(payload)
if err != nil {
return body
}
return encoded
}
// requestBodyDumpLimit caps how much of an outbound body is written to the log.
const requestBodyDumpLimit = 64 << 10
+147
View File
@@ -0,0 +1,147 @@
package protocol
import (
"encoding/json"
"fmt"
"io"
"time"
)
// CollapseStream consumes one complete upstream SSE stream and synthesizes
// the equivalent single (non-streaming) response document in the same
// protocol.
//
// It exists for upstream lanes that only serve streaming responses: the
// gateway forces stream:true on the wire and collapses the events back so
// downstream clients that asked for a plain JSON reply keep working.
func CollapseStream(reader io.Reader, protocol Protocol, model string) ([]byte, error) {
parser := &bridgeStreamParser{
protocol: protocol,
tools: map[string]bool{},
toolIDs: map[string]string{},
toolNames: map[string]string{},
responseArgs: map[string]bool{},
responseReasoning: map[string]bool{},
}
acc := &collapseAccumulator{tools: map[string]int{}}
acc.response.Created = time.Now().Unix()
acc.response.Model = model
terminated := false
streamErr := error(nil)
readErr := readSSE(reader, func(eventName, data string) error {
events, err := parser.Parse(eventName, data)
if err != nil {
streamErr = err
return errStreamUpstreamFailure
}
for _, event := range events {
switch event.Kind {
case "done":
terminated = true
return errStreamNormalTermination
case "error":
streamErr = fmt.Errorf("%s", firstNonEmpty(event.Error, "upstream stream failed"))
return errStreamUpstreamFailure
default:
acc.apply(event)
}
}
return nil
})
if readErr != nil && readErr != errStreamNormalTermination {
if streamErr != nil {
return nil, streamErr
}
return nil, readErr
}
if !terminated {
if streamErr != nil {
return nil, streamErr
}
return nil, errSSEUnexpectedEOF
}
return json.Marshal(encodeBridgeResponse(protocol, acc.response))
}
type collapseAccumulator struct {
response bridgeResponse
tools map[string]int
reason *bridgeBlock
}
func (acc *collapseAccumulator) apply(event bridgeStreamEvent) {
switch event.Kind {
case "start":
if event.ResponseID != "" {
acc.response.ID = event.ResponseID
}
if event.Model != "" {
acc.response.Model = event.Model
}
case "text":
acc.response.Text += event.Text
case "reasoning":
if event.Text == "" && event.Encrypted == "" && event.Signature == "" {
break
}
acc.reasoningBlock().Text += event.Text
if event.Encrypted != "" {
acc.splitReasoning()
acc.reasoningBlock().Encrypted += event.Encrypted
acc.reason = nil
}
case "reasoning_signature":
acc.reasoningBlock().Signature += event.Signature
case "tool_start":
acc.toolBlock(event.ToolKey, event.ToolID, event.ToolName)
case "tool_delta":
block := acc.toolBlock(event.ToolKey, event.ToolID, event.ToolName)
block.ArgumentsJSON += event.Text
case "usage":
if event.Usage != nil {
mergeBridgeUsage(&acc.response.Usage, *event.Usage)
}
case "finish":
acc.response.Stop = event.Stop
}
}
// reasoningBlock returns the reasoning block deltas accumulate into,
// starting a fresh one when the previous block already carries encrypted
// content (a different item on the wire).
func (acc *collapseAccumulator) reasoningBlock() *bridgeBlock {
if acc.reason == nil {
acc.response.Reasoning = append(acc.response.Reasoning, bridgeBlock{Kind: "reasoning"})
acc.reason = &acc.response.Reasoning[len(acc.response.Reasoning)-1]
}
return acc.reason
}
func (acc *collapseAccumulator) splitReasoning() {
acc.reason = nil
}
func (acc *collapseAccumulator) toolBlock(key, id, name string) *bridgeBlock {
if index, ok := acc.tools[key]; ok {
block := &acc.response.Tools[index]
if block.ID == "" {
block.ID = id
}
if block.Name == "" {
block.Name = name
}
return block
}
acc.response.Tools = append(acc.response.Tools, bridgeBlock{Kind: "tool_call", ID: id, Name: name})
acc.tools[key] = len(acc.response.Tools) - 1
return &acc.response.Tools[len(acc.response.Tools)-1]
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
if value != "" {
return value
}
}
return ""
}