fix(gateway): preserve OpenCode v2 title requests and avoid WARP pool churn (#169)

Co-authored-by: NekomyaDev <neko@nekomya.dev>
This commit is contained in:
NEKOMYAandNekomyaDev authored and GitHub committed 2026-11-05 11:41:29 +08:00
1 parent 87e798318d
commit 86be64bfbe
4 files changed
+681 -6

No files matched your search

+260
View File
@@ -0,0 +1,260 @@
package gateway
import (
"bytes"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"unicode/utf8"
"opencode2api/internal/jsonutil"
)
// Legacy OpenCode v1 title prompt prefix in a user message.
const titlePromptLegacy = "generate a title for this conversation"
// OpenCode v2 title generation signatures in system / developer messages.
const (
titlePromptV2Name = "you name conversations so the user can find them later in a list of past sessions"
titlePromptV2Desc = "you generate a descriptive title for this conversation"
titlePromptV2Auto = "you decide whether the session title still matches the conversation"
titlePromptV2Rule = "reply with a title and nothing else"
titlePromptV2RuleAlt = "reply with a title for it and nothing else"
)
// isTitleGenerationBody checks if raw JSON body is an OpenCode title-generation request.
func isTitleGenerationBody(body []byte) bool {
if len(body) == 0 {
return false
}
var payload map[string]any
if err := json.Unmarshal(body, &payload); err != nil {
return false
}
return isTitleGenerationRequest(payload)
}
// isTitleGenerationRequest reports whether payload is OpenCode's session-title
// generation call rather than agent traffic (PR #102, Issue #164).
//
// OpenCode issues title calls with an EMPTY tool list. The upstream free-tier gate
// accepts that tool-free form but rejects the same call with 403 FreeTierError or
// 429 FreeUsageLimitError once an agent tool list is attached. Therefore, the gateway
// must not inject tools into title requests.
//
// To prevent false positives on user agent requests:
// 1. Tool lists must be absent or empty.
// 2. Message count must be at most 3 without assistant or tool turns.
// 3. Known OpenCode title prompt signatures must match in their expected roles.
func isTitleGenerationRequest(payload map[string]any) bool {
if payload == nil {
return false
}
// 1. Tool list must be absent or empty
if tools, ok := payload["tools"].([]any); ok && len(tools) > 0 {
return false
}
if functions, ok := payload["functions"].([]any); ok && len(functions) > 0 {
return false
}
// 2. Must have 1 to 3 messages
messages, ok := payload["messages"].([]any)
if !ok || len(messages) == 0 || len(messages) > 3 {
return false
}
hasSystemSignature := false
hasLegacyUserSignature := false
for _, raw := range messages {
msg, ok := raw.(map[string]any)
if !ok {
continue
}
role := strings.ToLower(strings.TrimSpace(jsonutil.StringAt(msg, "role")))
// Any in-progress conversation turn means this is NOT a fresh title request
if role == "assistant" || role == "tool" || role == "function" {
return false
}
text := strings.ToLower(strings.TrimSpace(strings.Join(textFragments(msg["content"]), " ")))
if text == "" {
continue
}
if role == "system" || role == "developer" {
if strings.Contains(text, titlePromptV2Name) ||
strings.Contains(text, titlePromptV2Desc) ||
strings.Contains(text, titlePromptV2Auto) ||
(strings.Contains(text, titlePromptV2Rule) || strings.Contains(text, titlePromptV2RuleAlt)) {
hasSystemSignature = true
}
} else if role == "user" {
// Legacy v1 title generation: user message starts with the command prompt
if strings.HasPrefix(text, titlePromptLegacy) {
hasLegacyUserSignature = true
}
}
}
return hasSystemSignature || hasLegacyUserSignature
}
// synthesizeTitle extracts the conversation topic from the payload's user message
// and formats a clean, compact title suitable for OpenCode sessions.
func synthesizeTitle(payload map[string]any) string {
if payload == nil {
return "New Session"
}
messages, ok := payload["messages"].([]any)
if !ok {
return "New Session"
}
userText := ""
for _, raw := range messages {
msg, ok := raw.(map[string]any)
if !ok {
continue
}
if strings.ToLower(strings.TrimSpace(jsonutil.StringAt(msg, "role"))) == "user" {
userText = strings.TrimSpace(strings.Join(textFragments(msg["content"]), " "))
if userText != "" {
break
}
}
}
if userText == "" {
return "New Session"
}
// Strip legacy prompt wrapper if present
lower := strings.ToLower(userText)
if strings.HasPrefix(lower, titlePromptLegacy) {
idx := strings.Index(userText, "\n")
if idx >= 0 && idx < len(userText)-1 {
userText = strings.TrimSpace(userText[idx+1:])
}
}
// Clean whitespace and linebreaks
lines := strings.Split(userText, "\n")
firstLine := strings.TrimSpace(lines[0])
words := strings.Fields(firstLine)
if len(words) == 0 {
return "New Session"
}
// Take up to 6 words
if len(words) > 6 {
words = words[:6]
}
title := strings.Join(words, " ")
// Unicode rune-safe truncation up to 40 runes
if utf8.RuneCountInString(title) > 40 {
runes := []rune(title)
title = string(runes[:40])
}
// Strip surrounding quotes or trailing periods
title = strings.Trim(title, `"'`+" \t\r\n.")
if title == "" {
return "New Session"
}
return title
}
// synthesizeTitleResponse builds an OpenAI-compliant 200 OK HTTP response
// carrying the synthesized title, supporting both non-streaming and SSE streaming.
func synthesizeTitleResponse(model, title string, stream bool) *http.Response {
var idBytes [8]byte
_, _ = rand.Read(idBytes[:])
reqID := "chatcmpl-title-" + hex.EncodeToString(idBytes[:])
now := time.Now().Unix()
resp := &http.Response{
StatusCode: http.StatusOK,
Header: make(http.Header),
}
if !stream {
respBody := map[string]any{
"id": reqID,
"object": "chat.completion",
"created": now,
"model": model,
"choices": []any{
map[string]any{
"index": 0,
"message": map[string]any{
"role": "assistant",
"content": title,
},
"finish_reason": "stop",
},
},
"usage": map[string]any{
"prompt_tokens": 10,
"completion_tokens": utf8.RuneCountInString(title),
"total_tokens": 10 + utf8.RuneCountInString(title),
},
}
data, _ := json.Marshal(respBody)
resp.Header.Set("Content-Type", "application/json")
resp.Header.Set("Content-Length", fmt.Sprintf("%d", len(data)))
resp.Body = io.NopCloser(bytes.NewReader(data))
return resp
}
// SSE streaming format
var buf bytes.Buffer
chunk1 := map[string]any{
"id": reqID,
"object": "chat.completion.chunk",
"created": now,
"model": model,
"choices": []any{
map[string]any{
"index": 0,
"delta": map[string]any{
"role": "assistant",
"content": title,
},
"finish_reason": nil,
},
},
}
chunk2 := map[string]any{
"id": reqID,
"object": "chat.completion.chunk",
"created": now,
"model": model,
"choices": []any{
map[string]any{
"index": 0,
"delta": map[string]any{},
"finish_reason": "stop",
},
},
}
d1, _ := json.Marshal(chunk1)
d2, _ := json.Marshal(chunk2)
buf.WriteString("data: ")
buf.Write(d1)
buf.WriteString("\n\ndata: ")
buf.Write(d2)
buf.WriteString("\n\ndata: [DONE]\n\n")
resp.Header.Set("Content-Type", "text/event-stream")
resp.Body = io.NopCloser(&buf)
return resp
}
+359
View File
@@ -0,0 +1,359 @@
package gateway
import (
"context"
"encoding/json"
"io"
"log/slog"
"net/http"
"testing"
"time"
"opencode2api/internal/config"
"opencode2api/internal/identity"
"opencode2api/internal/models"
wire "opencode2api/internal/protocol"
"opencode2api/internal/telemetry"
"opencode2api/internal/warp"
)
func TestIsTitleGenerationRequest_Comprehensive(t *testing.T) {
tests := []struct {
name string
body string
expected bool
}{
{
name: "Legacy v1 OpenCode title prompt in user turn",
body: `{
"model": "flint-40b-free",
"messages": [
{"role": "user", "content": "Generate a title for this conversation:\nUser: Fix login bug"}
]
}`,
expected: true,
},
{
name: "New v2 OpenCode title prompt in system turn",
body: `{
"model": "flint-40b-free",
"messages": [
{"role": "system", "content": "You name conversations so the user can find them later in a list of past sessions. Reply with a title and nothing else: one line, no quotes, no trailing period."},
{"role": "user", "content": "Implement auth middleware"}
]
}`,
expected: true,
},
{
name: "New v2 OpenCode title prompt variant with 'for it'",
body: `{
"model": "flint-40b-free",
"messages": [
{"role": "system", "content": "You name conversations so the user can find them later in a list of past sessions. Reply with a title for it and nothing else: one line, no quotes, no trailing period."},
{"role": "user", "content": "Fix typo"}
]
}`,
expected: true,
},
{
name: "New v2 auto-rename prompt",
body: `{
"model": "flint-40b-free",
"messages": [
{"role": "system", "content": "You decide whether the session title still matches the conversation. Reply with KEEP or new title."},
{"role": "user", "content": "Database migration script"}
]
}`,
expected: true,
},
{
name: "Normal user agent request with declared tools",
body: `{
"model": "flint-40b-free",
"messages": [
{"role": "system", "content": "You are a coding assistant."},
{"role": "user", "content": "List files in current directory"}
],
"tools": [
{"type": "function", "function": {"name": "shell", "description": "run command"}}
]
}`,
expected: false,
},
{
name: "Tool-free regular Q&A request (must NOT be treated as title)",
body: `{
"model": "flint-40b-free",
"messages": [
{"role": "user", "content": "What is the capital of France?"}
]
}`,
expected: false,
},
{
name: "User message quotes title prompt in normal conversation (false positive prevention)",
body: `{
"model": "flint-40b-free",
"messages": [
{"role": "system", "content": "You are a helpful coding assistant."},
{"role": "user", "content": "Can you review this prompt for me: 'You name conversations so the user can find them later in a list of past sessions.'"}
]
}`,
expected: false,
},
{
name: "User message mentions legacy prompt in the middle of text",
body: `{
"model": "flint-40b-free",
"messages": [
{"role": "user", "content": "How does OpenCode generate a title for this conversation?"}
]
}`,
expected: false,
},
{
name: "Multi-turn conversation with assistant turn (must NOT be treated as title)",
body: `{
"model": "flint-40b-free",
"messages": [
{"role": "system", "content": "You name conversations so the user can find them later in a list of past sessions."},
{"role": "user", "content": "Hi"},
{"role": "assistant", "content": "Hello!"},
{"role": "user", "content": "Now generate code"}
]
}`,
expected: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := isTitleGenerationBody([]byte(tt.body))
if got != tt.expected {
t.Errorf("isTitleGenerationBody() = %v, expected %v", got, tt.expected)
}
})
}
}
func TestPrepareAnonymousBody_TitleVsAgentToolsInjection(t *testing.T) {
v2TitleBody := []byte(`{
"model": "flint-40b-free",
"messages": [
{"role": "system", "content": "You name conversations so the user can find them later in a list of past sessions. Reply with a title and nothing else: one line, no quotes, no trailing period."},
{"role": "user", "content": "Add Redis caching"}
]
}`)
v1TitleBody := []byte(`{
"model": "flint-40b-free",
"messages": [
{"role": "user", "content": "Generate a title for this conversation:\nUser: Add Redis caching"}
]
}`)
regularAgentBody := []byte(`{
"model": "flint-40b-free",
"messages": [
{"role": "user", "content": "Explain how Go channels work."}
]
}`)
// 1. v2 Title body: must NOT have tools injected
shapedV2, _ := prepareAnonymousBody(v2TitleBody, wire.Chat, false)
var parsedV2 map[string]any
if err := json.Unmarshal(shapedV2, &parsedV2); err != nil {
t.Fatalf("Unmarshal shapedV2 error: %v", err)
}
if tools, ok := parsedV2["tools"].([]any); ok && len(tools) > 0 {
t.Errorf("expected title request to stay tool-free, but got %d tools injected", len(tools))
}
// 2. v1 Title body: must NOT have tools injected
shapedV1, _ := prepareAnonymousBody(v1TitleBody, wire.Chat, false)
var parsedV1 map[string]any
if err := json.Unmarshal(shapedV1, &parsedV1); err != nil {
t.Fatalf("Unmarshal shapedV1 error: %v", err)
}
if tools, ok := parsedV1["tools"].([]any); ok && len(tools) > 0 {
t.Errorf("expected v1 title request to stay tool-free, but got %d tools injected", len(tools))
}
// 3. Regular agent request without tools: MUST have tools injected
shapedAgent, _ := prepareAnonymousBody(regularAgentBody, wire.Chat, false)
var parsedAgent map[string]any
if err := json.Unmarshal(shapedAgent, &parsedAgent); err != nil {
t.Fatalf("Unmarshal shapedAgent error: %v", err)
}
tools, ok := parsedAgent["tools"].([]any)
if !ok || len(tools) == 0 {
t.Errorf("expected regular agent request to have official tools injected, got %v", parsedAgent["tools"])
}
}
func TestSynthesizeTitle_UnicodeAndFallbacks(t *testing.T) {
tests := []struct {
name string
payload map[string]any
expected string
}{
{
name: "Standard english prompt",
payload: map[string]any{
"messages": []any{
map[string]any{"role": "user", "content": "Fix authentication bug in middleware"},
},
},
expected: "Fix authentication bug in middleware",
},
{
name: "Unicode characters and truncation",
payload: map[string]any{
"messages": []any{
map[string]any{"role": "user", "content": "Türkçe başlık oluşturma ve kota sınırlaması çözümü"},
},
},
expected: "Türkçe başlık oluşturma ve kota sınırlam",
},
{
name: "Legacy prefix stripped cleanly",
payload: map[string]any{
"messages": []any{
map[string]any{"role": "user", "content": "Generate a title for this conversation:\nUser: Upgrade database schema to v3"},
},
},
expected: "User: Upgrade database schema to v3",
},
{
name: "Empty content safe fallback",
payload: map[string]any{
"messages": []any{
map[string]any{"role": "user", "content": " "},
},
},
expected: "New Session",
},
{
name: "No user message safe fallback",
payload: map[string]any{
"messages": []any{
map[string]any{"role": "system", "content": "System prompt only"},
},
},
expected: "New Session",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := synthesizeTitle(tt.payload)
if got != tt.expected {
t.Errorf("synthesizeTitle() = %q, expected %q", got, tt.expected)
}
})
}
}
func TestWarpAnonymous_TitleRequestSingleAttemptFallbackOn429(t *testing.T) {
// Mock 2 WARP exits that both return 429
exit1, l1 := createMockWarpExit(t, "exit-1", "2a09:bac1:7280:18::1", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Retry-After", "120")
w.WriteHeader(http.StatusTooManyRequests)
_, _ = w.Write([]byte(`{"error":"quota_exceeded"}`))
})
defer l1.Close()
exit2, l2 := createMockWarpExit(t, "exit-2", "2a09:bac5:58c0:d2d::1", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Retry-After", "120")
w.WriteHeader(http.StatusTooManyRequests)
_, _ = w.Write([]byte(`{"error":"quota_exceeded"}`))
})
defer l2.Close()
pool := warp.NewTestPoolWithExits([]*warp.TestExit{exit1, exit2})
cfg := config.Config{
Anonymous: true,
Retry: config.RetryConfig{
MaxAttempts: 12, // Normally 12, but must be capped to 1 for title requests
TimeoutSeconds: 5,
},
Warp: config.WarpConfig{
Enabled: true,
PoolSize: 2,
Stack: "ipv6",
},
Upstream: config.UpstreamConfig{
Anonymous: "http://[fd00::1]:80",
},
Performance: config.PerformanceConfig{
FailureCooldownSeconds: 15,
},
}
logger := slog.New(slog.NewTextHandler(io.Discard, nil))
monitor := telemetry.Monitor()
gw, err := New(cfg, logger, monitor, pool)
if err != nil {
t.Fatalf("New gateway error: %v", err)
}
ctx := context.Background()
route := models.Route{ID: "test-model", Protocol: wire.Chat}
titleBody := []byte(`{
"model": "test-model",
"messages": [
{"role": "system", "content": "You name conversations so the user can find them later in a list of past sessions. Reply with a title and nothing else: one line, no quotes, no trailing period."},
{"role": "user", "content": "Refactor auth middleware"}
],
"stream": false
}`)
bodies := map[config.Tier][]byte{
config.TierZen: titleBody,
}
ids := identity.RequestIDs{Request: "req-title-1", Session: "ses-title-1"}
start := time.Now()
resp, err, attempts := gw.doWarpAnonymousUpstream(ctx, route, bodies, ids, 0)
duration := time.Since(start)
if err != nil {
t.Fatalf("expected fallback response without error, got %v", err)
}
if resp == nil {
t.Fatalf("expected response, got nil")
}
defer resp.Body.Close()
// Must stop after exactly 1 attempt so it does NOT burn the entire pool
if attempts != 1 {
t.Errorf("expected title request to try exactly 1 exit, got %d attempts", attempts)
}
if resp.StatusCode != http.StatusOK {
t.Errorf("expected fallback status 200 OK, got %d", resp.StatusCode)
}
if duration > 1*time.Second {
t.Errorf("expected quick response, took %v", duration)
}
// Read and verify synthesized JSON response
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("ReadAll error: %v", err)
}
var res map[string]any
if err := json.Unmarshal(bodyBytes, &res); err != nil {
t.Fatalf("Unmarshal error: %v", err)
}
choices, ok := res["choices"].([]any)
if !ok || len(choices) == 0 {
t.Fatalf("expected choices array in fallback response, got %v", res)
}
firstChoice := choices[0].(map[string]any)
message := firstChoice["message"].(map[string]any)
content := message["content"].(string)
expectedContent := "Refactor auth middleware"
if content != expectedContent {
t.Errorf("expected synthesized title %q, got %q", expectedContent, content)
}
}
+25 -4
View File
@@ -375,7 +375,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
// then reports errDeterministicClientRejection so the caller keeps this
// 4xx instead of replacing it with a later tier's answer.
halted := false
cursor := g.anonymous.CursorFor(ids.Session)
cursor := g.anonymous.CursorForOffset(ids.Session, attemptOffset)
limit := min(g.anonymous.Len(), g.maxAnonymousExits())
if g.anonymous.HasPool() && g.cfg.Retry.MaxAttempts > limit {
limit = g.cfg.Retry.MaxAttempts
@@ -386,6 +386,10 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
if len(rawBody) == 0 {
return nil, errors.New("no prepared Zen request body"), 0
}
isTitle := isTitleGenerationBody(rawBody)
if isTitle {
limit = 1
}
// The anonymous free tier only serves agent-shaped streaming requests
// carrying the required tool definitions (anything else is rejected with 403
// FreeTierError). Normalize the wire body per upstream gate (v1 /zen vs v2
@@ -525,6 +529,19 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
g.logger.Warn("anonymous lane circuit breaker opened", "component", "upstream", "event", "anonymous_breaker_open", "reason", "all_exits_blocked", "request_id", ids.Request, "paused_for", pause.String())
}
}
if isTitle {
if upstreamStatus(lastResponse) == http.StatusTooManyRequests || (lastResponse == nil && lastErr != nil) {
var payload map[string]any
_ = json.Unmarshal(rawBody, &payload)
title := synthesizeTitle(payload)
stream, _ := payload["stream"].(bool)
if lastResponse != nil {
httpx.DrainAndClose(lastResponse.Body)
}
g.logger.Info("title generation request rejected by upstream; returning synthesized title fallback", "component", "upstream", "event", "title_fallback_synthesized", "model", route.ID, "title", title)
return synthesizeTitleResponse(route.ID, title, stream), nil, attempts
}
}
if lastResponse != nil {
// The caller keeps and forwards this response; a block or a
// deterministic rejection only changes the error so the keyed tiers
@@ -613,9 +630,13 @@ func prepareAnonymousBody(body []byte, protocol wire.Protocol, v1 bool) ([]byte,
if injectOfficialPrompt(payload, protocol, v1) {
changed = true
}
renames, toolsChanged := renameAndCompleteTools(payload, protocol, v1)
if toolsChanged {
changed = true
var renames *wire.ToolRenames
if !isTitleGenerationRequest(payload) {
var toolsChanged bool
renames, toolsChanged = renameAndCompleteTools(payload, protocol, v1)
if toolsChanged {
changed = true
}
}
if !v1 && protocol == wire.Chat && ensureV2CompletionLimit(payload) {
changed = true
+37 -2
View File
@@ -3,6 +3,7 @@ package gateway
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
@@ -193,7 +194,11 @@ func (g *Gateway) doWARPAttempt(ctx context.Context, req *http.Request, baseURL,
if resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusTooManyRequests {
body = peekResponseBody(resp)
}
g.warp.Report(lease, resp.StatusCode, body)
var retryAfter time.Duration
if resp.StatusCode == http.StatusTooManyRequests {
retryAfter = parseRetryAfter(resp.Header.Get("Retry-After"))
}
g.warp.ReportWithRetryAfter(lease, resp.StatusCode, body, retryAfter)
}
resp.Body = &warpBody{ReadCloser: resp.Body, lease: owned, diagnostic: diagnostic}
return resp, label, nil
@@ -241,8 +246,11 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout
// A 429 is scoped to the exit that carried it, so the request keeps
// rotating exits until the configured attempt budget is spent; only then
// does the last 429 reach the client.
isTitle := isTitleGenerationBody(rawBody)
limit := g.cfg.Retry.MaxAttempts
if limit < 1 {
if isTitle {
limit = 1
} else if limit < 1 {
limit = 1
}
firstEventTimeout := time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds) * time.Second
@@ -250,6 +258,7 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout
var lastErr error
blocked, halted := false, false
attempts := 0
triedEgresses := make(map[string]bool)
for attempts < limit {
if ctx.Err() != nil {
if lastErr == nil {
@@ -313,6 +322,14 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout
g.logger.Warn("upstream rejected the request; not trying other upstreams", "component", "upstream", "event", "deterministic_rejection", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "status", status, "duration_ms", duration.Milliseconds())
break
}
if status == http.StatusTooManyRequests {
triedEgresses[egress] = true
if !g.warp.HasUntriedActive(triedEgresses) {
g.logger.Warn("all active WARP exits exhausted or cooling down; stopping retries", "component", "upstream", "event", "warp_429_exhausted", "request_id", ids.Request, "attempt", attempts)
halted = false
break
}
}
g.logger.Debug("anonymous WARP upstream returned an error response; trying the next upstream or exit", "component", "upstream", "event", "anonymous_attempt_response_failed", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", egress, "status", status, "duration_ms", duration.Milliseconds())
if index+1 < len(upstreams) {
break
@@ -321,6 +338,11 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout
if halted || ctx.Err() != nil {
break
}
if status := upstreamStatus(lastResponse); status == http.StatusTooManyRequests {
if !g.warp.HasUntriedActive(triedEgresses) {
break
}
}
if !leaseBlocked && upstreamStatus(lastResponse) != http.StatusTooManyRequests {
if pause, tripped := g.anonymous.NoteFailure(); tripped {
g.logger.Warn("anonymous lane circuit breaker opened", "component", "upstream", "event", "anonymous_breaker_open", "status", upstreamStatus(lastResponse), "paused_for", pause.String())
@@ -331,6 +353,19 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout
if halted {
return lastResponse, errDeterministicClientRejection, attempts
}
if isTitle {
if upstreamStatus(lastResponse) == http.StatusTooManyRequests || (lastResponse == nil && lastErr != nil) {
var payload map[string]any
_ = json.Unmarshal(rawBody, &payload)
title := synthesizeTitle(payload)
stream, _ := payload["stream"].(bool)
if lastResponse != nil {
httpx.DrainAndClose(lastResponse.Body)
}
g.logger.Info("title generation request rejected by upstream; returning synthesized title fallback", "component", "upstream", "event", "title_fallback_synthesized", "model", route.ID, "title", title)
return synthesizeTitleResponse(route.ID, title, stream), nil, attempts
}
}
if lastResponse != nil {
if blocked {
return lastResponse, errFreeTierIPBlocked, attempts