fix(gateway): harden free-tier retries and client compatibility

Preserve upstream HTTP failures across transport retries, classify title requests before shaping, and rename legacy functions exactly once.

Keep adjacent Responses assistant items together, including interleaved text and calls. Add opt-in prompt environment overrides with matching shell descriptions, strict validation, and WebUI round-trip preservation.

Document compatibility boundaries and retain existing defaults. Include the requested test/ ignore rule. Offline zz_ regressions passed and were removed after validation as requested; vet and Windows/Linux builds passed.

Refs #173, #175, #176, #178, #179, #181
This commit is contained in:
Jason Xu committed 2026-11-17 01:00:29 +08:00
1 parent b296a61d0e
commit 14faec7654
13 files changed
+304 -94

No files matched your search

+58 -1
View File
@@ -11,6 +11,7 @@ import (
"os"
"strings"
"time"
"unicode"
"opencode2api/internal/jsonutil"
wire "opencode2api/internal/protocol"
@@ -133,7 +134,44 @@ type UpstreamConfig struct {
// anonymous lane uses only this origin: the v1 /zen fallback is retired for
// free models and its call site is commented out. Empty means
// https://opencode.ai/inference.
Anonymous string `json:"anonymous"`
Anonymous string `json:"anonymous"`
PromptEnvironment *PromptEnvironmentConfig `json:"prompt_environment,omitempty"`
}
type PromptEnvironmentConfig struct {
WorkingDirectory string `json:"working_directory,omitempty"`
WorkspaceRoot string `json:"workspace_root,omitempty"`
Platform string `json:"platform,omitempty"`
IsGitRepo *bool `json:"is_git_repo,omitempty"`
}
func (environment *PromptEnvironmentConfig) Normalize() error {
if environment == nil {
return nil
}
for name, value := range map[string]string{
"working_directory": environment.WorkingDirectory,
"workspace_root": environment.WorkspaceRoot,
} {
for _, character := range value {
if unicode.IsControl(character) || character == '\u2028' || character == '\u2029' || character == '<' || character == '>' {
return fmt.Errorf("upstream.prompt_environment.%s must not contain control characters, line separators, or angle brackets", name)
}
}
}
platform := strings.ToLower(strings.TrimSpace(environment.Platform))
if platform == "windows" {
platform = "win32"
}
switch platform {
case "", "linux", "darwin", "win32":
default:
return errors.New("upstream.prompt_environment.platform must be linux, darwin, win32, windows, or empty")
}
environment.WorkingDirectory = strings.TrimSpace(environment.WorkingDirectory)
environment.WorkspaceRoot = strings.TrimSpace(environment.WorkspaceRoot)
environment.Platform = platform
return nil
}
// RetryConfig bounds the upstream retries. MaxAttempts caps the attempts of a
@@ -345,6 +383,17 @@ func Normalize(path string, cfg Config) (Config, error) {
if cfg.Listen == "" {
return Config{}, errors.New("listen must not be empty")
}
if cfg.Upstream.PromptEnvironment != nil {
environment := *cfg.Upstream.PromptEnvironment
if err := environment.Normalize(); err != nil {
return Config{}, err
}
if environment.IsGitRepo != nil {
isGitRepo := *environment.IsGitRepo
environment.IsGitRepo = &isGitRepo
}
cfg.Upstream.PromptEnvironment = &environment
}
cfg.Upstream.Zen = strings.TrimSpace(cfg.Upstream.Zen)
cfg.Upstream.Go = strings.TrimSpace(cfg.Upstream.Go)
cfg.Upstream.Anonymous = strings.TrimSpace(cfg.Upstream.Anonymous)
@@ -560,6 +609,14 @@ func Clone(cfg Config) Config {
cfg.GoKeys = append([]string(nil), cfg.GoKeys...)
cfg.Proxies = append([]string(nil), cfg.Proxies...)
cfg.effectiveProxies = append([]string(nil), cfg.effectiveProxies...)
if cfg.Upstream.PromptEnvironment != nil {
environment := *cfg.Upstream.PromptEnvironment
if environment.IsGitRepo != nil {
isGitRepo := *environment.IsGitRepo
environment.IsGitRepo = &isGitRepo
}
cfg.Upstream.PromptEnvironment = &environment
}
if cfg.Models.Protocols != nil {
protocols := make(map[string]string, len(cfg.Models.Protocols))
for key, value := range cfg.Models.Protocols {
+25
View File
@@ -7,6 +7,8 @@ import (
"net/http"
"strings"
"time"
"opencode2api/internal/httpx"
)
// errFreeTierIPBlocked reports that OpenCode's free gateway refused the request
@@ -92,6 +94,29 @@ func peekResponseBody(resp *http.Response) []byte {
return prefix
}
// bufferRetryResponse releases a response's transport before the next attempt,
// retaining at most 64 KiB of its body, including any prefix read before an error.
func bufferRetryResponse(resp *http.Response) {
if resp == nil || resp.Body == nil {
return
}
body, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
_ = resp.Body.Close()
resp.Body = io.NopCloser(bytes.NewReader(body))
}
// replaceRetryResponse keeps the latest HTTP response across transport failures
// and closes a superseded response before giving ownership to its replacement.
func replaceRetryResponse(previous, current *http.Response) *http.Response {
if current == nil {
return previous
}
if previous != nil && previous != current {
httpx.DrainAndClose(previous.Body)
}
return current
}
// peekNetworkAbuseBlock classifies a response without consuming its body.
func peekNetworkAbuseBlock(resp *http.Response) bool {
if resp == nil || resp.StatusCode != http.StatusForbidden {
+29 -10
View File
@@ -9,6 +9,7 @@ import (
"sync"
"time"
"opencode2api/internal/config"
wire "opencode2api/internal/protocol"
)
@@ -46,9 +47,9 @@ var (
)
// opencodeEnvironment renders the <env> block the CLI puts after its base
// prompt. The working directory is resolved once per process; a platform
// without one falls back to the official container path.
func opencodeEnvironment(model string) string {
// prompt. Configured values replace the host defaults without changing the
// field names or order; the host directory is resolved once per process.
func opencodeEnvironment(model string, environment *config.PromptEnvironmentConfig) string {
opencodeEnvOnce.Do(func() {
directory := ""
if current, err := os.Getwd(); err == nil {
@@ -67,13 +68,31 @@ func opencodeEnvironment(model string) string {
if platform == "windows" {
platform = "win32"
}
directory := opencodeWorkDir
workspace := directory
gitRepo := "yes"
if environment != nil {
if environment.WorkingDirectory != "" {
directory = environment.WorkingDirectory
workspace = directory
}
if environment.WorkspaceRoot != "" {
workspace = environment.WorkspaceRoot
}
if environment.Platform != "" {
platform = environment.Platform
}
if environment.IsGitRepo != nil && !*environment.IsGitRepo {
gitRepo = "no"
}
}
return strings.Join([]string{
"You are powered by the model named " + apiModel + ". The exact model ID is opencode/" + apiModel,
"Here is some useful information about the environment you are running in:",
"<env>",
" Working directory: " + opencodeWorkDir,
" Workspace root folder: " + opencodeWorkDir,
" Is directory a git repo: yes",
" Working directory: " + directory,
" Workspace root folder: " + workspace,
" Is directory a git repo: " + gitRepo,
" Platform: " + platform,
" Today's date: " + time.Now().UTC().Format("Mon Jan 02 2006"),
"</env>",
@@ -82,12 +101,12 @@ func opencodeEnvironment(model string) string {
// opencodeSystemPrompt assembles the full CLI system prompt for model and the
// upstream generation's tool naming.
func opencodeSystemPrompt(model string, v1 bool) string {
func opencodeSystemPrompt(model string, v1 bool, environment *config.PromptEnvironmentConfig) string {
base := opencodePromptV2
if v1 {
base = opencodePromptV1
}
return base + opencodeEnvironment(model) + "\n" + opencodeSkills
return base + opencodeEnvironment(model, environment) + "\n" + opencodeSkills
}
// injectOfficialPrompt prepends the official CLI system prompt to a shaped
@@ -95,12 +114,12 @@ func opencodeSystemPrompt(model string, v1 bool) string {
// already carries the marker is left untouched, so repeated shaping cannot
// duplicate the prompt. System One payloads are not chat bodies and are never
// touched.
func injectOfficialPrompt(payload map[string]any, protocol wire.Protocol, v1 bool) bool {
func injectOfficialPrompt(payload map[string]any, protocol wire.Protocol, v1 bool, environment *config.PromptEnvironmentConfig) bool {
if payload == nil || protocol == wire.SystemOne {
return false
}
model, _ := payload["model"].(string)
prompt := opencodeSystemPrompt(model, v1)
prompt := opencodeSystemPrompt(model, v1, environment)
switch protocol {
case wire.Chat:
return injectChatPrompt(payload, prompt)
+3 -3
View File
@@ -57,7 +57,7 @@ func (g *Gateway) resolvedEffort(model string, tier config.Tier, protocol wire.P
// free tier by prepareAnonymousBody. v1 reports whether the probe targets the
// v1 lane (models.IsV1Upstream), which selects the 1.x toolset instead of the
// 2.x one.
func probePayload(model string, protocol wire.Protocol, effort string, v1 bool) ([]byte, error) {
func probePayload(model string, protocol wire.Protocol, effort string, v1 bool, environment *config.PromptEnvironmentConfig) ([]byte, error) {
if protocol == wire.SystemOne {
// TypeSafe's native boolean type is "noul", not JSON Schema boolean.
return json.Marshal(map[string]any{"model": model, "state": "1 + 1 = 2", "questions": map[string]any{
@@ -76,7 +76,7 @@ func probePayload(model string, protocol wire.Protocol, effort string, v1 bool)
if err != nil {
return nil, err
}
shaped, _ := prepareAnonymousBody(b, protocol, v1)
shaped, _ := prepareAnonymousBody(b, protocol, v1, environment)
return shaped, nil
}
@@ -224,7 +224,7 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult
// (http_<status>, model_unavailable, probe_timeout, warp_unavailable, ...) and
// whether the upstream rejected the reasoning effort.
func (g *Gateway) probeAttempt(parent context.Context, client *http.Client, baseURL, key, model string, protocol wire.Protocol, ids identity.RequestIDs, effort string, overWARP bool) probeResult {
b, err := probePayload(model, protocol, effort, models.IsV1Upstream(baseURL))
b, err := probePayload(model, protocol, effort, models.IsV1Upstream(baseURL), g.cfg.Upstream.PromptEnvironment)
if err != nil {
return probeResult{reason: "request_conversion_error"}
}
+40 -22
View File
@@ -135,7 +135,7 @@ func officialToolDefinition(name string, v1 bool) (opencodeToolDefinition, bool)
// officialTool renders one official definition in the wire shape the protocol
// expects. The 2.x Chat shape marks every tool strict:false, as the client does;
// the captured 1.x entries carry no strict field and are rendered verbatim.
func officialTool(protocol wire.Protocol, name string, v1 bool) map[string]any {
func officialTool(protocol wire.Protocol, name string, v1 bool, platform string) map[string]any {
description := "Agent tool " + name
parameters := map[string]any{"type": "object", "properties": map[string]any{}}
if definition, ok := officialToolDefinition(name, v1); ok {
@@ -146,10 +146,10 @@ func officialTool(protocol wire.Protocol, name string, v1 bool) map[string]any {
}
if v1 {
if name == "bash" {
description = v1BashDescription(description)
description = v1BashDescription(description, platform)
}
} else if name == "shell" {
description = v2ShellDescription(description)
description = v2ShellDescription(description, platform)
}
switch protocol {
case wire.Chat:
@@ -179,39 +179,58 @@ func officialTool(protocol wire.Protocol, name string, v1 bool) map[string]any {
}
// officialToolset renders the full official set for a lane.
func officialToolset(protocol wire.Protocol, v1 bool) []any {
func officialToolset(protocol wire.Protocol, v1 bool, platform string) []any {
names := officialToolNames(v1)
tools := make([]any, 0, len(names))
for _, name := range names {
tools = append(tools, officialTool(protocol, name, v1))
tools = append(tools, officialTool(protocol, name, v1, platform))
}
return tools
}
// v2ShellDescription renders the shell tool description for the host platform.
// The 2.x client describes the shell it actually has, so a Windows host says
// powershell where a Unix host says bash.
func v2ShellDescription(base string) string {
if runtime.GOOS != "windows" {
// v2ShellDescription renders the configured platform's shell description,
// retaining the host-based behavior when no platform override is supplied.
func v2ShellDescription(base, platform string) string {
if platform == "" {
platform = runtime.GOOS
if platform != "windows" {
return base
}
}
switch platform {
case "win32", "windows":
return strings.Replace(base, "on Linux using bash", "on Windows using powershell", 1)
case "darwin":
return strings.Replace(base, "on Linux using bash", "on macOS using bash", 1)
default:
return base
}
return strings.Replace(base, "on Linux using bash", "on Windows using powershell", 1)
}
// v1BashDescription applies the same platform rewrite to the 1.x bash
// definition, which states its OS and shell inline.
func v1BashDescription(base string) string {
if runtime.GOOS != "windows" {
func v1BashDescription(base, platform string) string {
if platform == "" {
platform = runtime.GOOS
if platform != "windows" {
return base
}
}
switch platform {
case "win32", "windows":
return strings.Replace(base, "OS: linux, Shell: bash", "OS: windows, Shell: powershell", 1)
case "darwin":
return strings.Replace(base, "OS: linux, Shell: bash", "OS: darwin, Shell: bash", 1)
default:
return base
}
return strings.Replace(base, "OS: linux, Shell: bash", "OS: windows, Shell: powershell", 1)
}
// renameAndCompleteTools makes the tool list read as an official CLI session:
// every named client tool is renamed to an opaque wire name, legacy functions
// arrays are converted, and the full official set for the lane is appended.
// The returned map restores the client names in the upstream response.
func renameAndCompleteTools(payload map[string]any, protocol wire.Protocol, v1 bool) (*wire.ToolRenames, bool) {
func renameAndCompleteTools(payload map[string]any, protocol wire.Protocol, v1 bool, platform string) (*wire.ToolRenames, bool) {
switch protocol {
case wire.Chat, wire.Responses, wire.Anthropic:
default:
@@ -245,7 +264,7 @@ func renameAndCompleteTools(payload map[string]any, protocol wire.Protocol, v1 b
}
}
}
items = append(items, convertLegacyFunctions(legacy, protocol, renames, used)...)
items = append(items, convertLegacyFunctions(legacy, protocol)...)
delete(payload, "functions")
}
}
@@ -266,7 +285,7 @@ func renameAndCompleteTools(payload map[string]any, protocol wire.Protocol, v1 b
}
shaped = append(shaped, entry)
}
shaped = append(shaped, officialToolset(protocol, v1)...)
shaped = append(shaped, officialToolset(protocol, v1, platform)...)
payload["tools"] = shaped
officialNames := officialToolNames(v1)
bindOfficialToolAliases(renames, declaredNames, officialNames)
@@ -558,8 +577,8 @@ func setToolName(protocol wire.Protocol, entry map[string]any, name string) {
}
// convertLegacyFunctions turns the pre-tools "functions" array into entries of
// the protocol's tool shape and renames their names.
func convertLegacyFunctions(entries []any, protocol wire.Protocol, renames *wire.ToolRenames, used map[string]bool) []any {
// the protocol's tool shape for the shared renaming pass.
func convertLegacyFunctions(entries []any, protocol wire.Protocol) []any {
converted := make([]any, 0, len(entries))
for _, raw := range entries {
entry, ok := raw.(map[string]any)
@@ -570,12 +589,11 @@ func convertLegacyFunctions(entries []any, protocol wire.Protocol, renames *wire
if name == "" {
continue
}
wireName := clientWireName(renames, used, name)
description := jsonutil.StringAt(entry, "description")
switch protocol {
case wire.Chat:
function := map[string]any{
"name": wireName,
"name": name,
"description": description,
"parameters": legacyParameters(entry),
}
@@ -586,7 +604,7 @@ func convertLegacyFunctions(entries []any, protocol wire.Protocol, renames *wire
case wire.Responses:
tool := map[string]any{
"type": "function",
"name": wireName,
"name": name,
"description": description,
"parameters": legacyParameters(entry),
}
+60 -36
View File
@@ -299,8 +299,13 @@ func stripStaleReasoningInputs(route models.Route, bodies map[config.Tier][]byte
// 2xx. Without a success it returns the last HTTP response, whose body is still
// open, in preference to the last error. Once ctx is done it no longer enters
// the key tiers.
func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, models.Route, int, error) {
func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (response *http.Response, resultRoute models.Route, resultAttempts int, resultErr error) {
var lastResponse *http.Response
defer func() {
if lastResponse != nil && lastResponse != response {
httpx.DrainAndClose(lastResponse.Body)
}
}()
var lastErr error
effectiveRoute := route
attempts := attemptOffset
@@ -313,10 +318,13 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie
if route.Anonymous {
resp, err, used := g.doAnonymousUpstream(ctx, route, bodies, ids, attempts)
attempts += used
lastResponse, lastErr = resp, err
if errors.Is(ctx.Err(), context.Canceled) {
return nil, effectiveRoute, attempts, ctx.Err()
}
if err == nil && resp != nil && resp.StatusCode/100 == 2 {
return resp, route, attempts, nil
}
lastResponse, lastErr = resp, err
if errors.Is(err, errDeterministicClientRejection) {
// The request itself was rejected. Another lane or key gets the same
// answer, and retrying only buries this error under the next one, so
@@ -341,6 +349,9 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie
// The anonymous phase already consumed the request budget. Entering the
// authenticated tiers here would only fire instant attempts against a
// dead context, cooling keys that were never really tried.
if errors.Is(ctx.Err(), context.Canceled) {
return nil, effectiveRoute, attempts, ctx.Err()
}
if lastResponse != nil {
return lastResponse, effectiveRoute, attempts, nil
}
@@ -363,13 +374,17 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie
keyRoute.Tier = tier
keyRoute.Anonymous = false
keyRoute.Protocol = route.ProtocolFor(tier)
effectiveRoute = keyRoute
bufferRetryResponse(lastResponse)
resp, err, used := g.doKeyUpstream(ctx, keyRoute, bodies, ids, attempts)
attempts += used
lastResponse = replaceRetryResponse(lastResponse, resp)
if resp != nil {
effectiveRoute = keyRoute
}
if errors.Is(ctx.Err(), context.Canceled) {
return nil, effectiveRoute, attempts, ctx.Err()
}
if err == nil && resp != nil && resp.StatusCode/100 == 2 {
if lastResponse != nil {
httpx.DrainAndClose(lastResponse.Body)
}
return resp, keyRoute, attempts, nil
}
if resp != nil {
@@ -377,27 +392,20 @@ func (g *Gateway) doUpstreamTiers(ctx context.Context, route models.Route, bodie
// Same request-level rejection as on the anonymous lane: no
// other tier can fix it, so return it as is.
g.logger.Warn("upstream rejected the request; not trying other tiers", "component", "upstream", "event", "deterministic_rejection", "request_id", ids.Request, "attempts", attempts, "tier", keyRoute.Tier, "status", resp.StatusCode)
if lastResponse != nil {
httpx.DrainAndClose(lastResponse.Body)
}
return resp, keyRoute, attempts, nil
}
if lastResponse != nil {
httpx.DrainAndClose(lastResponse.Body)
}
lastResponse = resp
}
if err != nil {
lastErr = err
}
}
if errors.Is(ctx.Err(), context.Canceled) {
return nil, effectiveRoute, attempts, ctx.Err()
}
if blocked {
// The request never left the free tier's IP block: keep the block as
// the client-facing cause even if a Go fallback also failed, and close
// the last free-tier response whose body the handler will not forward.
if lastResponse != nil {
httpx.DrainAndClose(lastResponse.Body)
}
return nil, effectiveRoute, attempts, errFreeTierIPBlocked
}
if lastResponse != nil {
@@ -436,7 +444,7 @@ func (g *Gateway) maxAnonymousExits() int {
// exhausting the proxy cursor returns control to the preferred authenticated
// tiers. It returns the last response (body still open), else the last error,
// plus the number of attempts made.
func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, error, int) {
func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (response *http.Response, resultErr error, resultAttempts int) {
if g.usesWARP(route.ID, config.TierZen, true) {
return g.doWarpAnonymousUpstream(ctx, route, bodies, ids, attemptOffset)
}
@@ -447,6 +455,11 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
}
defer g.anonymous.ReleaseProbe()
var lastResponse *http.Response
defer func() {
if lastResponse != nil && lastResponse != response {
httpx.DrainAndClose(lastResponse.Body)
}
}()
var lastErr error
// blocked records that some exit is under the free tier's IP block. The
// result then reports errFreeTierIPBlocked even when no exit was left to
@@ -494,7 +507,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
preparedBodies := make([][]byte, len(upstreams))
toolRenames := make([]*wire.ToolRenames, len(upstreams))
for i, baseURL := range upstreams {
preparedBodies[i], toolRenames[i] = prepareAnonymousBody(rawBody, protocol, models.IsV1Upstream(baseURL))
preparedBodies[i], toolRenames[i] = prepareAnonymousBody(rawBody, protocol, models.IsV1Upstream(baseURL), g.cfg.Upstream.PromptEnvironment)
}
for proxies < limit {
if ctx.Err() != nil {
@@ -531,10 +544,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
meta.Attempts = attemptOffset + attempts
meta.Tier = string(config.TierZen)
}
if lastResponse != nil {
httpx.DrainAndClose(lastResponse.Body)
lastResponse = nil
}
bufferRetryResponse(lastResponse)
req, err := upstreamRequest(ctx, baseURL, protocol, preparedBodies[index], ids, anonymousZenKey)
if err != nil {
return nil, err, attempts
@@ -546,11 +556,12 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
started := time.Now()
resp, err := doInferenceAttempt(g.inferenceClient(node.proxy, baseURL, route.ID), req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout)
duration := time.Since(started)
lastResponse = replaceRetryResponse(lastResponse, resp)
if ctx.Err() != nil {
// The parent budget expired while this attempt was in flight. Its
// outcome says nothing about this proxy, so record nothing and stop
// scanning.
lastResponse, lastErr = resp, err
lastErr = err
if lastErr == nil && lastResponse == nil {
lastErr = ctx.Err()
}
@@ -563,7 +574,6 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
g.logger.Debug("anonymous upstream accepted request", "component", "upstream", "event", "anonymous_attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "status", resp.StatusCode, "duration_ms", duration.Milliseconds())
return resp, nil, attempts
}
lastResponse = resp
lastErr = asProxyUnavailable(node.proxy, err)
if err != nil {
g.logger.Debug("anonymous transport attempt failed", "component", "upstream", "event", "anonymous_attempt_transport_failed", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", config.RedactURL(node.proxy.name), "duration_ms", duration.Milliseconds(), "error", err)
@@ -614,6 +624,9 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
break
}
}
if errors.Is(ctx.Err(), context.Canceled) {
return nil, ctx.Err(), attempts
}
// Every configured exit is under the same IP block: another request
// cannot reach a working exit, so pause the lane instead of repeating the
// 403 walk until the exit cool-downs expire.
@@ -624,6 +637,7 @@ func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, b
}
if isTitle {
if fallback := titleFallback(g.logger, route.ID, rawBody, lastResponse, lastErr); fallback != nil {
lastResponse = nil
return fallback, nil, attempts
}
}
@@ -696,7 +710,7 @@ func (g *Gateway) inferenceClient(proxy *proxyTransport, baseURL, model string)
// (/zen) and v2 lanes. System One payloads are decision requests, not agent
// traffic, so they are forwarded verbatim, as is a body that is not a JSON
// object.
func prepareAnonymousBody(body []byte, protocol wire.Protocol, v1 bool) ([]byte, *wire.ToolRenames) {
func prepareAnonymousBody(body []byte, protocol wire.Protocol, v1 bool, environment *config.PromptEnvironmentConfig) ([]byte, *wire.ToolRenames) {
if protocol == wire.SystemOne {
return body, nil
}
@@ -704,6 +718,7 @@ func prepareAnonymousBody(body []byte, protocol wire.Protocol, v1 bool) ([]byte,
if err := json.Unmarshal(body, &payload); err != nil {
return body, nil
}
isTitle := isTitleGenerationRequest(payload)
changed := false
if streaming, ok := payload["stream"].(bool); !ok || !streaming {
payload["stream"] = true
@@ -712,13 +727,17 @@ func prepareAnonymousBody(body []byte, protocol wire.Protocol, v1 bool) ([]byte,
if ensureAnonymousChatUsage(payload, protocol) {
changed = true
}
if injectOfficialPrompt(payload, protocol, v1) {
if injectOfficialPrompt(payload, protocol, v1, environment) {
changed = true
}
var renames *wire.ToolRenames
if !isTitleGenerationRequest(payload) {
if !isTitle {
platform := ""
if environment != nil {
platform = environment.Platform
}
var toolsChanged bool
renames, toolsChanged = renameAndCompleteTools(payload, protocol, v1)
renames, toolsChanged = renameAndCompleteTools(payload, protocol, v1, platform)
if toolsChanged {
changed = true
}
@@ -904,7 +923,7 @@ func (g *Gateway) shapeKeyBody(body []byte, route models.Route, tier config.Tier
if tier == config.TierGo {
baseURL = g.cfg.Upstream.Go
}
shaped, renames := prepareAnonymousBody(body, route.ProtocolFor(tier), models.IsV1Upstream(baseURL))
shaped, renames := prepareAnonymousBody(body, route.ProtocolFor(tier), models.IsV1Upstream(baseURL), g.cfg.Upstream.PromptEnvironment)
return shaped, renames, !bytes.Equal(shaped, body)
}
@@ -996,8 +1015,13 @@ func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route,
// without being held against the key or the proxy. It returns the last
// response (body still open), else the last error, plus the number of
// attempts made.
func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, error, int) {
func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (response *http.Response, resultErr error, resultAttempts int) {
var lastResponse *http.Response
defer func() {
if lastResponse != nil && lastResponse != response {
httpx.DrainAndClose(lastResponse.Body)
}
}()
var lastErr error
nodes := g.zenNodes
baseURL := g.cfg.Upstream.Zen
@@ -1047,10 +1071,7 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies
meta.Attempts = attemptOffset + attempts
meta.Tier = string(route.Tier)
}
if lastResponse != nil {
httpx.DrainAndClose(lastResponse.Body)
lastResponse = nil
}
bufferRetryResponse(lastResponse)
req, err := upstreamRequest(ctx, baseURL, route.Protocol, body, ids, node.key)
if err != nil {
return nil, err, attempts
@@ -1085,12 +1106,13 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies
resp, err = doInferenceAttempt(g.inferenceClient(proxy, baseURL, route.ID), req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout)
}
attemptDuration := time.Since(attemptStarted)
lastResponse = replaceRetryResponse(lastResponse, resp)
if ctx.Err() != nil {
// The request budget expired while this attempt was in flight. A
// canceled context says nothing about the key or the proxy: without
// this guard the instant DeadlineExceeded would cool a healthy key
// and evict a healthy proxy from the pool.
lastResponse, lastErr = resp, err
lastErr = err
if lastErr == nil && lastResponse == nil {
lastErr = ctx.Err()
}
@@ -1119,7 +1141,6 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies
g.logger.Debug("upstream rejected a non-retryable request", "component", "upstream", "event", "attempt_rejected", "request_id", ids.Request, "attempt", attempts, "tier", route.Tier, "key_id", keyID, "status", resp.StatusCode, "proxy", proxyLabel, "duration_ms", attemptDuration.Milliseconds())
return resp, nil, attempts
}
lastResponse = resp
if useWARP && errors.Is(err, errWARPUnavailable) {
// No exit at all: another key would only wait on the same pool.
lastErr = err
@@ -1136,6 +1157,9 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies
g.logger.Debug("upstream returned a retryable response", "component", "upstream", "event", "attempt_retryable_response", "request_id", ids.Request, "attempt", attempts, "tier", route.Tier, "key_id", keyID, "status", resp.StatusCode, "proxy", proxyLabel, "duration_ms", attemptDuration.Milliseconds())
}
}
if errors.Is(ctx.Err(), context.Canceled) {
return nil, ctx.Err(), attempts
}
if lastResponse != nil {
return lastResponse, nil, attempts
}
+20 -11
View File
@@ -226,7 +226,7 @@ func warpProxy(label string) *proxyTransport {
// proxy. The lane breaker still applies; per-proxy cooldowns and the block
// cursor do not, because a block is a property of the WARP exit and rotation
// replaces it.
func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, error, int) {
func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (response *http.Response, resultErr error, resultAttempts int) {
if !g.anonymous.AllowAttempt() {
return nil, errAnonymousLanePaused, 0
}
@@ -240,7 +240,7 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout
prepared := make([][]byte, len(upstreams))
renames := make([]*wire.ToolRenames, len(upstreams))
for index, baseURL := range upstreams {
prepared[index], renames[index] = prepareAnonymousBody(rawBody, protocol, models.IsV1Upstream(baseURL))
prepared[index], renames[index] = prepareAnonymousBody(rawBody, protocol, models.IsV1Upstream(baseURL), g.cfg.Upstream.PromptEnvironment)
}
// 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
@@ -253,6 +253,11 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout
}
firstEventTimeout := time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds) * time.Second
var lastResponse *http.Response
defer func() {
if lastResponse != nil && lastResponse != response {
httpx.DrainAndClose(lastResponse.Body)
}
}()
var lastErr error
blocked, halted := false, false
attempts := 0
@@ -265,6 +270,7 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout
break
}
leaseBlocked := false
lastStatus := 0
for index, baseURL := range upstreams {
if ctx.Err() != nil {
break
@@ -275,10 +281,7 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout
meta.Attempts = attemptOffset + attempts
meta.Tier = string(config.TierZen)
}
if lastResponse != nil {
httpx.DrainAndClose(lastResponse.Body)
lastResponse = nil
}
bufferRetryResponse(lastResponse)
req, err := upstreamRequest(ctx, baseURL, protocol, prepared[index], ids, anonymousZenKey)
if err != nil {
return nil, err, attempts
@@ -287,21 +290,23 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout
started := time.Now()
resp, egress, err := g.doWARPAttempt(ctx, req, baseURL, route.ID, firstEventTimeout)
duration := time.Since(started)
lastResponse = replaceRetryResponse(lastResponse, resp)
if ctx.Err() != nil {
lastResponse, lastErr = resp, err
lastErr = err
if lastErr == nil && lastResponse == nil {
lastErr = ctx.Err()
}
break
}
status := upstreamStatus(resp)
lastStatus = status
g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+attempts, "anonymous", "anonymous", true, warpProxy(egress), resp, err, duration)
if err == nil && status/100 == 2 {
g.anonymous.NoteSuccess()
g.logger.Debug("anonymous WARP upstream accepted request", "component", "upstream", "event", "anonymous_attempt_succeeded", "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())
return resp, nil, attempts
}
lastResponse, lastErr = resp, err
lastErr = err
if err != nil {
g.logger.Debug("anonymous WARP transport attempt failed", "component", "upstream", "event", "anonymous_attempt_transport_failed", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", egress, "duration_ms", duration.Milliseconds(), "error", err)
// A broken tunnel affects both upstream gates; rotate the exit
@@ -335,23 +340,27 @@ func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Rout
if halted || ctx.Err() != nil {
break
}
if status := upstreamStatus(lastResponse); status == http.StatusTooManyRequests {
if lastStatus == http.StatusTooManyRequests {
if !g.warp.HasUntriedActive(triedEgresses) {
break
}
}
if !leaseBlocked && upstreamStatus(lastResponse) != http.StatusTooManyRequests {
if !leaseBlocked && lastStatus != 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())
g.logger.Warn("anonymous lane circuit breaker opened", "component", "upstream", "event", "anonymous_breaker_open", "status", lastStatus, "paused_for", pause.String())
break
}
}
}
if errors.Is(ctx.Err(), context.Canceled) {
return nil, ctx.Err(), attempts
}
if halted {
return lastResponse, errDeterministicClientRejection, attempts
}
if isTitle {
if fallback := titleFallback(g.logger, route.ID, rawBody, lastResponse, lastErr); fallback != nil {
lastResponse = nil
return fallback, nil, attempts
}
}
+11 -9
View File
@@ -540,7 +540,9 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest
request.System = append(request.System, blocks...)
} else if role == "developer" {
request.Developer = append(request.Developer, blocks...)
} else if role == "user" || role == "assistant" {
} else if role == "assistant" {
appendBridgeBlock(&request.Messages, role, blocks...)
} else if role == "user" {
request.Messages = append(request.Messages, bridgeMessage{Role: role, Blocks: blocks})
}
default:
@@ -659,19 +661,19 @@ func decodeBridgeRequest(protocol Protocol, input map[string]any) (bridgeRequest
return request, nil
}
// appendBridgeBlock adds a block decoded from a standalone Responses item. It
// joins the previous message when that has the same role and holds only tool
// calls or results, so consecutive function_call (or function_call_output)
// items form one turn; otherwise the block starts a new message.
func appendBridgeBlock(messages *[]bridgeMessage, role string, block bridgeBlock) {
// appendBridgeBlock adds blocks decoded from a standalone Responses item. It
// joins adjacent assistant items into one turn, including interleaved text,
// reasoning and tool calls. Tool results join only a preceding tool-only user
// message, so results and user input keep assistant turns separate.
func appendBridgeBlock(messages *[]bridgeMessage, role string, blocks ...bridgeBlock) {
if len(*messages) > 0 {
last := &(*messages)[len(*messages)-1]
if last.Role == role && bridgeBlocksOnlyTools(last.Blocks) {
last.Blocks = append(last.Blocks, block)
if last.Role == role && (role == "assistant" || bridgeBlocksOnlyTools(last.Blocks)) {
last.Blocks = append(last.Blocks, blocks...)
return
}
}
*messages = append(*messages, bridgeMessage{Role: role, Blocks: []bridgeBlock{block}})
*messages = append(*messages, bridgeMessage{Role: role, Blocks: blocks})
}
// bridgeBlocksOnlyTools reports whether blocks is non-empty and holds only