Merge branch 'main' into codex/improve-upload-error-details

This commit is contained in:
Chenyme authored and GitHub committed 2026-07-21 16:06:11 +08:00
commit a04d7f0b22
23 files changed
+1464 -300

No files matched your search

@@ -1,61 +0,0 @@
package gateway
import (
"testing"
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
)
// 模拟 Sub2API → Grok2API 官方缓存亲和链路(不连真上游)。
func TestOfficialCache_Sub2APIPromptCacheKeyStickyAcrossTurns(t *testing.T) {
// Sub2API 透传 body.prompt_cache_key
explicit := "sub2api-stable-session-uuid-001"
turn1Body := []byte(`{"model":"grok-4.5","prompt_cache_key":"sub2api-stable-session-uuid-001","messages":[{"role":"user","content":"hello"}]}`)
turn2Body := []byte(`{"model":"grok-4.5","prompt_cache_key":"sub2api-stable-session-uuid-001","messages":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":"again"}]}`)
id1 := resolveBuildSessionIdentity(42, accountdomain.ProviderBuild, "grok-4.5", explicit, "", turn1Body)
id2 := resolveBuildSessionIdentity(42, accountdomain.ProviderBuild, "grok-4.5", explicit, "", turn2Body)
if id1.upstreamID == "" || id1.upstreamID != id2.upstreamID {
t.Fatalf("sub2api prompt_cache_key must yield stable upstream id: %#v %#v", id1, id2)
}
if id1.affinityKey == "" || id1.affinityKey != id2.affinityKey {
t.Fatalf("affinity must stick across turns: %#v %#v", id1, id2)
}
// 不同租户(clientKey)必须隔离
other := resolveBuildSessionIdentity(99, accountdomain.ProviderBuild, "grok-4.5", explicit, "", turn1Body)
if other.upstreamID == id1.upstreamID {
t.Fatal("tenant isolation broken for explicit prompt_cache_key")
}
}
func TestOfficialCache_Sub2APIMissingSessionFallsBackToMessageHash(t *testing.T) {
// Sub2API 没透传任何 session:靠首条 user 内容 soft 粘滞
turn1 := []byte(`{"messages":[{"role":"system","content":"sys"},{"role":"user","content":"what is mutex"}]}`)
turn2 := []byte(`{"messages":[{"role":"system","content":"sys"},{"role":"user","content":"what is mutex"},{"role":"assistant","content":"A lock."},{"role":"user","content":"and deadlock?"}]}`)
id1 := resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.5", "", "", turn1)
id2 := resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.5", "", "", turn2)
if !id1.soft || id1.upstreamID == "" {
t.Fatalf("expected soft session, got %#v", id1)
}
if id1.upstreamID != id2.upstreamID {
t.Fatalf("soft session drifted: %s vs %s", id1.upstreamID, id2.upstreamID)
}
}
func TestOfficialCache_NoSignalMeansNoRandomConvID(t *testing.T) {
// 完全无信号:不得生成上游 ID(由 adapter 侧保证不写随机 conv-id)
id := resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.5", "", "", []byte(`{}`))
if id.upstreamID != "" || id.affinityKey != "" {
t.Fatalf("empty signal must not invent session: %#v", id)
}
}
func TestOfficialCache_ClaudeCodeSessionHeaderPath(t *testing.T) {
// 模拟 handler 已把 X-Claude-Code-Session-Id 抽成 seed
seed := "123e4567-e89b-12d3-a456-426614174000"
a := resolveBuildSessionIdentity(1, accountdomain.ProviderBuild, "grok-4.5", "", seed, nil)
b := resolveBuildSessionIdentity(1, accountdomain.ProviderBuild, "grok-4.5", "", seed, []byte(`{"messages":[{"role":"user","content":"x"}]}`))
if a.upstreamID == "" || a.upstreamID != b.upstreamID {
t.Fatalf("claude session seed unstable: %#v %#v", a, b)
}
}
@@ -11,50 +11,52 @@ import (
accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account"
)
const buildSessionIdentityVersion = "v2"
const buildSessionIdentityVersion = "v3"
type buildSessionIdentity struct {
// upstreamID 写入上游 prompt_cache_key 与 x-grok-conv-id,须跨轮稳定。
// upstreamID is sent as prompt_cache_key and x-grok-conv-id and must remain stable across turns.
upstreamID string
// affinityKey 用于账号粘滞;按模型隔离,避免不同模型能力账号互相覆盖。
// affinityKey controls account stickiness and is isolated by model to avoid cross-model collisions.
affinityKey string
// replayKey 仅由客户端显式会话信号生成;soft 消息锚点不得驱动 encrypted reasoning 回放。
// replayKey is derived only from explicit client session signals; soft anchors must not drive encrypted reasoning replay.
replayKey string
// soft 表示由消息内容兜底生成(无显式 session 时),仍须稳定。
// soft indicates a fallback identity derived from message content when no explicit session is available.
soft bool
}
// resolveBuildSessionIdentity 对齐 CPA 官方缓存会话策略:
// 1) 显式 prompt_cache_key / session seed → 稳定哈希身份(多租户隔离)
// 2) 否则用消息锚点(system + 首条 user)生成 soft 身份,保证多轮粘滞与 conv-id 不漂移
// 3) 完全无信号 → 空身份(禁止每请求随机 ID,避免打散 xAI 服务器亲和)
// resolveBuildSessionIdentity derives a stable Grok Build session identity:
// 1. Prefer explicit client session signals, isolated by client key, provider, and model.
// 2. Fall back to system/instructions and the first user message when no explicit signal exists.
// 3. Return an empty identity when no signal exists; never generate a random session ID per request.
func resolveBuildSessionIdentity(clientKeyID uint64, provider accountdomain.Provider, upstreamModel, explicitKey, sessionSeed string, body []byte) buildSessionIdentity {
seed := strings.TrimSpace(explicitKey)
// Prefer Claude Code and Codex session signals extracted by the transport layer.
// body.prompt_cache_key is only a fallback when no stronger header or session signal exists.
seed := strings.TrimSpace(sessionSeed)
if seed == "" {
seed = strings.TrimSpace(sessionSeed)
seed = strings.TrimSpace(explicitKey)
}
model := strings.ToLower(strings.TrimSpace(upstreamModel))
if clientKeyID == 0 || provider == "" || model == "" {
return buildSessionIdentity{}
}
if seed != "" {
upstreamSource := fmt.Sprintf("grok2api:build-session:%s:%d:%s:%s", buildSessionIdentityVersion, clientKeyID, provider, seed)
upstreamSource := fmt.Sprintf("grok2api:build-session:%s:%d:%s:%s:%s", buildSessionIdentityVersion, clientKeyID, provider, model, seed)
affinitySource := fmt.Sprintf("grok2api:build-affinity:%s:%d:%s:%s:%s", buildSessionIdentityVersion, clientKeyID, provider, model, seed)
replaySource := fmt.Sprintf("grok2api:build-replay:%s:%d:%s:%s", buildSessionIdentityVersion, clientKeyID, provider, seed)
replaySource := fmt.Sprintf("grok2api:build-replay:%s:%d:%s:%s:%s", buildSessionIdentityVersion, clientKeyID, provider, model, seed)
return buildSessionIdentity{
upstreamID: digestUUID(upstreamSource),
affinityKey: hexDigest(affinitySource),
replayKey: hexDigest(replaySource),
}
}
// CPA 风格消息 hash 兜底:无 session 时仍尽量粘账号 + 稳定 conv-id,服务 Sub2API 未透传 session 的场景。
// Fall back to a message-prefix hash to keep account affinity and session IDs stable without client session signals.
system, firstUser, _ := extractMessageAnchors(body)
firstUser = truncateAnchor(firstUser, 200)
system = truncateAnchor(system, 100)
if firstUser == "" {
return buildSessionIdentity{}
}
upstreamSource := fmt.Sprintf("grok2api:build-soft-session:%s:%d:%s:%s:%s", buildSessionIdentityVersion, clientKeyID, provider, system, firstUser)
upstreamSource := fmt.Sprintf("grok2api:build-soft-session:%s:%d:%s:%s:%s:%s", buildSessionIdentityVersion, clientKeyID, provider, model, system, firstUser)
affinitySource := fmt.Sprintf("grok2api:build-soft-affinity:%s:%d:%s:%s:%s:%s", buildSessionIdentityVersion, clientKeyID, provider, model, system, firstUser)
return buildSessionIdentity{
upstreamID: digestUUID(upstreamSource),
@@ -86,8 +88,8 @@ func truncateAnchor(value string, maxRunes int) string {
return string(runes[:maxRunes])
}
// extractMessageAnchors 从 Chat / Messages / Responses 请求体提取稳定前缀锚点。
// 仅使用 system + 首条 user(及可选首条 assistant),避免后续轮次追加导致 hash 漂移。
// extractMessageAnchors extracts stable prefix anchors from Chat, Messages, and Responses request bodies.
// It uses only system, the first user message, and an optional first assistant message to avoid hash drift across turns.
func extractMessageAnchors(body []byte) (system, firstUser, firstAssistant string) {
if len(body) == 0 {
return "", "", ""
@@ -96,7 +98,7 @@ func extractMessageAnchors(body []byte) (system, firstUser, firstAssistant strin
if json.Unmarshal(body, &root) != nil {
return "", "", ""
}
// 顶层 system / instructions(OpenAI Responses / Chat 常见)作为稳定前缀 system 锚点。
// Top-level system or instructions fields provide a stable system anchor for OpenAI Responses and Chat.
if raw, ok := root["instructions"]; ok {
system = flattenMessageContent(raw)
}
@@ -164,7 +166,7 @@ func anchorsFromRoleMessages(raw json.RawMessage) (system, firstUser, firstAssis
}
func anchorsFromResponsesInput(raw json.RawMessage) (system, firstUser, firstAssistant string) {
// 简写:input 直接是字符串
// Shorthand form: input is a direct string.
var asString string
if json.Unmarshal(raw, &asString) == nil {
return "", strings.TrimSpace(asString), ""
@@ -179,13 +181,13 @@ func anchorsFromResponsesInput(raw json.RawMessage) (system, firstUser, firstAss
_ = json.Unmarshal(item["role"], &role)
typeName = strings.TrimSpace(typeName)
role = strings.ToLower(strings.TrimSpace(role))
// instructions 级 system 由顶层处理;此处抓 message
// Top-level instructions handle the system anchor; this branch extracts messages.
if typeName != "" && typeName != "message" {
continue
}
content := flattenMessageContent(item["content"])
if content == "" {
// 兼容 content 为字符串字段 text
// Support content objects whose text field is a string.
var text string
if json.Unmarshal(item["text"], &text) == nil {
content = strings.TrimSpace(text)
@@ -208,7 +210,7 @@ func anchorsFromResponsesInput(raw json.RawMessage) (system, firstUser, firstAss
firstAssistant = content
}
default:
// 无 role 的纯文本 input 项视为 user
// Treat role-less plain-text input items as user input.
if role == "" && firstUser == "" && (typeName == "" || typeName == "message") {
firstUser = content
}
@@ -217,7 +219,7 @@ func anchorsFromResponsesInput(raw json.RawMessage) (system, firstUser, firstAss
break
}
}
// 顶层 instructions 作为 system 补充
// Use top-level instructions as a system fallback.
return system, firstUser, firstAssistant
}
@@ -25,19 +25,35 @@ func TestResolveBuildSessionIdentityIsStableAndTenantIsolated(t *testing.T) {
func TestResolveBuildSessionIdentitySeparatesAffinityFromUpstreamSession(t *testing.T) {
first := resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.5", "", "session-1", nil)
otherModel := resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.3", "", "session-1", nil)
if first.upstreamID == "" || first.upstreamID != otherModel.upstreamID {
t.Fatalf("upstream session changed with model: first=%#v other=%#v", first, otherModel)
if first.upstreamID == "" || first.upstreamID == otherModel.upstreamID || first.replayKey == otherModel.replayKey {
t.Fatalf("model-specific upstream session was not isolated: first=%#v other=%#v", first, otherModel)
}
if first.affinityKey == otherModel.affinityKey {
t.Fatalf("model-specific account affinity was not isolated: %#v", first)
}
}
func TestResolveBuildSessionIdentityPrefersExplicitKey(t *testing.T) {
func TestResolveBuildSoftSessionIdentityIsModelScoped(t *testing.T) {
body := []byte(`{"instructions":"stable system","input":[{"role":"user","content":"hello"}]}`)
first := resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.5", "", "", body)
otherModel := resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.3", "", "", body)
if first.upstreamID == "" || first.affinityKey == "" || !first.soft || !otherModel.soft {
t.Fatalf("soft identity missing: first=%#v other=%#v", first, otherModel)
}
if first.upstreamID == otherModel.upstreamID || first.affinityKey == otherModel.affinityKey {
t.Fatalf("soft identity must be model scoped: first=%#v other=%#v", first, otherModel)
}
}
func TestResolveBuildSessionIdentityPrefersSessionSignal(t *testing.T) {
first := resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.5", "client-key", "session-1", nil)
second := resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.5", "client-key", "session-2", nil)
if first.upstreamID == "" || first != second {
t.Fatalf("explicit key did not take precedence: first=%#v second=%#v", first, second)
if first.upstreamID == "" || first == second {
t.Fatalf("session signal did not take precedence: first=%#v second=%#v", first, second)
}
clientKeyOnly := resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.5", "client-key", "", nil)
if clientKeyOnly.upstreamID == "" || clientKeyOnly == first {
t.Fatalf("explicit key fallback was not isolated: session=%#v explicit=%#v", first, clientKeyOnly)
}
if value := resolveBuildSessionIdentity(0, accountdomain.ProviderBuild, "grok-4.5", "client-key", "", nil); value != (buildSessionIdentity{}) {
t.Fatal("identity without client ownership should be empty")
@@ -61,7 +77,7 @@ func TestResolveBuildSessionIdentitySoftFromMessagesIsStableAcrossTurns(t *testi
if first.upstreamID != second.upstreamID || first.affinityKey != second.affinityKey {
t.Fatalf("soft identity drifted across turns: first=%#v second=%#v", first, second)
}
// 不同首条用户内容必须隔离
// Different first user messages must remain isolated.
other := resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.5", "", "", []byte(`{"messages":[{"role":"user","content":"different"}]}`))
if other.upstreamID == first.upstreamID {
t.Fatal("different first user shared soft upstream id")
@@ -81,7 +97,7 @@ func TestResolveBuildSessionIdentitySoftFromResponsesInput(t *testing.T) {
}
func TestResolveBuildSessionIdentityUsesInstructionsAsSystemAnchor(t *testing.T) {
// Responses 协议常用顶层 instructions 而不是 messages[system]
// Responses commonly uses top-level instructions instead of messages[system].
a := resolveBuildSessionIdentity(3, accountdomain.ProviderBuild, "grok-4.5", "", "", []byte(`{"instructions":"stable system","input":[{"role":"user","content":"hello"}]}`))
b := resolveBuildSessionIdentity(3, accountdomain.ProviderBuild, "grok-4.5", "", "", []byte(`{"instructions":"stable system","input":[{"role":"user","content":"hello"},{"role":"assistant","content":"hi"},{"role":"user","content":"next"}]}`))
c := resolveBuildSessionIdentity(3, accountdomain.ProviderBuild, "grok-4.5", "", "", []byte(`{"instructions":"other system","input":[{"role":"user","content":"hello"}]}`))
+37 -35
View File
@@ -49,15 +49,18 @@ const modelCatalogRefreshTimeout = 30 * time.Second
var freeQuotaUsagePattern = regexp.MustCompile(`(?i)tokens\s*\(actual/limit\)\s*:\s*([0-9]+)\s*/\s*([0-9]+)`)
type Input struct {
RequestID string
ClientKey clientkey.Key
PublicModel string
Body []byte
Streaming bool
PromptCacheKey string
PromptCacheSeed string
PreviousResponseID string
// GrokTurnIndex 仅透传真实 Grok Shell 客户端提供的轮次;服务端不推算或递增。
RequestID string
ClientKey clientkey.Key
PublicModel string
Body []byte
Streaming bool
PromptCacheKey string
PromptCacheSeed string
// AllowClientToolCacheRoute indicates that the client request is compatible with the Build mixed-tool cache route.
// It only controls whether native x_search is added to existing client tools; it is not an authentication result.
AllowClientToolCacheRoute bool
PreviousResponseID string
// GrokTurnIndex forwards only the turn supplied by a real Grok Shell client; the server never infers or increments it.
GrokTurnIndex string
Operation audit.Operation
}
@@ -85,8 +88,8 @@ type Result struct {
Finalize func(usage Usage, responseID, errorCode string)
}
// StreamFailureDiagnostic 是下游已收到 2xx headers 后,上游在流内返回失败终止事件的安全投影。
// Body 只包含 Transport 提取的错误字段,仍会在 attempt recorder 中执行统一脱敏和容量限制。
// StreamFailureDiagnostic safely projects a failure termination event returned in-stream after downstream 2xx headers.
// Body contains only transport-extracted error fields and still receives the standard redaction and size limits.
type StreamFailureDiagnostic struct {
Body []byte
BodyTruncated bool
@@ -103,7 +106,7 @@ type routeResolver interface {
GetByProviderUpstream(ctx context.Context, providerValue accountdomain.Provider, upstreamModel string) (modeldomain.Route, error)
}
// videoAssetStore 负责归档并读取 Provider 已生成的视频结果。
// videoAssetStore archives and reads video results generated by a Provider.
type videoAssetStore interface {
SaveVideo(ctx context.Context, jobID, contentType string, body io.Reader) (mediadomain.Asset, error)
OpenVideo(ctx context.Context, id string) (mediadomain.Asset, io.ReadCloser, error)
@@ -113,7 +116,7 @@ type accountModelSyncer interface {
SyncAccount(ctx context.Context, accountID uint64) (int, error)
}
// Service 负责模型路由、账号选择、故障切换与审计收口。
// Service handles model routing, account selection, failover, and audit finalization.
type Service struct {
models routeResolver
audits auditRecorder
@@ -153,7 +156,7 @@ func (s *Service) ConfigureMedia(repository repository.MediaJobRepository, concu
s.mediaQueued = make(map[string]struct{})
}
// ConfigureMediaAssets 注入本地视频资产归档与读取能力(可选)。
// ConfigureMediaAssets injects optional local video asset archival and reading.
func (s *Service) ConfigureMediaAssets(store videoAssetStore) {
s.mediaAssets = store
}
@@ -262,7 +265,7 @@ func (s *Service) CreateChatCompletion(ctx context.Context, input Input) (*Resul
return s.createResponseAt(ctx, input, "/responses")
}
// CreateMessage 通过统一 Responses 上游执行 Anthropic Messages 请求。
// CreateMessage executes an Anthropic Messages request through the unified Responses upstream.
func (s *Service) CreateMessage(ctx context.Context, input Input) (*Result, error) {
input.Operation = audit.OperationMessages
return s.createResponseAt(ctx, input, "/responses")
@@ -274,7 +277,7 @@ func (s *Service) CompactResponse(ctx context.Context, input Input) (*Result, er
return s.createResponseAt(ctx, input, "/responses/compact")
}
// resolvePublicModelRoutes 同时支持下游无前缀模型名和显式指定来源的兼容名称。
// resolvePublicModelRoutes supports both unprefixed downstream model names and explicitly sourced compatibility names.
func (s *Service) resolvePublicModelRoutes(ctx context.Context, publicModel string) ([]modeldomain.Route, string, error) {
routes, err := s.models.GetByPublicIDCandidates(ctx, publicModel)
if err == nil {
@@ -298,7 +301,7 @@ func (s *Service) resolvePublicModelRoutes(ctx context.Context, publicModel stri
return routes, alias.ReasoningEffort, err
}
// selectConversationRoute 从同名模型的可用来源中选择满足权限、协议和会话归属的路由。
// selectConversationRoute selects a route for the named model that satisfies permissions, protocol, and session affinity.
func (s *Service) selectConversationRoute(routes []modeldomain.Route, key clientkey.Key, operation audit.Operation, path string, requireStoredResponse bool, ownership *inferencedomain.ResponseOwnership) (modeldomain.Route, error) {
if len(routes) == 0 || s.providers == nil {
return modeldomain.Route{}, ErrModelNotFound
@@ -346,7 +349,7 @@ func (s *Service) selectConversationRoute(routes []modeldomain.Route, key client
return fallback, ErrConversationUnsupported
}
// selectMediaRoute 从同名路由中选择同时满足媒体能力、密钥权限和 Provider 实现的来源。
// selectMediaRoute selects a same-name route that satisfies media capability, key permissions, and Provider support.
func (s *Service) selectMediaRoute(routes []modeldomain.Route, key clientkey.Key, capability modeldomain.Capability, providerSupported func(accountdomain.Provider) bool) (modeldomain.Route, error) {
if len(routes) == 0 {
return modeldomain.Route{}, ErrModelNotFound
@@ -389,10 +392,8 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string
if err != nil {
return nil, ErrModelNotFound
}
// Select the route first without requiring stored-response support. Console
// is intentionally stateless but can still accept a complete input replay;
// rejecting it here would prevent the Provider compatibility boundary from
// normalizing the request.
// Select the route first instead of requiring stored Responses support up front. Console is stateless
// but still accepts complete history; Provider-level normalization handles the compatibility details.
route, routeErr := s.selectConversationRoute(routes, input.ClientKey, operation, path, false, nil)
var ownership *inferencedomain.ResponseOwnership
if input.PreviousResponseID != "" && routeErr == nil {
@@ -404,8 +405,8 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string
ownership = &value
route, routeErr = s.selectConversationRoute(routes, input.ClientKey, operation, path, true, ownership)
} else if route.Provider == accountdomain.ProviderConsole {
// Console has no response store. It receives the current request as a
// stateless replay; the Provider normalizer removes the stale ID.
// Console does not retain Response state, so replay the history statelessly here;
// Provider normalization removes stale Response IDs.
input.PreviousResponseID = ""
} else {
return nil, ErrResponseStateUnsupported
@@ -457,11 +458,11 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string
ownershipPromptCacheKey := ""
reasoningReplayKey := ""
if route.Provider == accountdomain.ProviderBuild {
// 显式 key / session seed / 消息锚点 soft session(CPA 风格),禁止空 session 随机 conv-id。
// Derive a stable identity from explicit session signals, message anchors, and model; never generate a random conv-id.
identity := buildSessionIdentity{}
if ownership != nil && ownership.PromptCacheKey != "" {
// previous_response_id 属于既有 Response 链,必须继承根会话身份,
// 不能用本轮增量 input 重新计算 soft key。
// previous_response_id belongs to an existing Response chain and must inherit the root session identity;
// do not recompute the soft key from this turn's incremental input.
identity.upstreamID = ownership.PromptCacheKey
identity.replayKey = ownership.ReasoningReplayKey
} else {
@@ -518,7 +519,7 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string
forwardResponse := func(credential accountdomain.Credential, billing *accountdomain.Billing) (*provider.Response, error) {
started := time.Now()
responseStartedAt = started
response, err := adapter.ForwardResponse(ctx, provider.ResponseResourceRequest{Credential: credential, Billing: billing, Method: http.MethodPost, Path: path, Model: route.UpstreamModel, PromptCacheKey: input.PromptCacheKey, ReasoningReplayKey: reasoningReplayKey, GrokTurnIndex: input.GrokTurnIndex, IdempotencyID: idempotencyID, Body: input.Body, Streaming: input.Streaming, NormalizeBody: true, Operation: string(operation)})
response, err := adapter.ForwardResponse(ctx, provider.ResponseResourceRequest{Credential: credential, Billing: billing, Method: http.MethodPost, Path: path, Model: route.UpstreamModel, PromptCacheKey: input.PromptCacheKey, ReasoningReplayKey: reasoningReplayKey, AllowClientToolCacheRoute: input.AllowClientToolCacheRoute, GrokTurnIndex: input.GrokTurnIndex, IdempotencyID: idempotencyID, Body: input.Body, Streaming: input.Streaming, NormalizeBody: true, Operation: string(operation)})
err = failureAttempts.captureResponse(credential, started, response, err)
timing.markUpstream(time.Since(started))
return response, err
@@ -658,7 +659,7 @@ attemptLoop:
retryAfter := parseRetryAfter(response.Header.Get("Retry-After"), time.Now().UTC())
body, _ := readRetryableBody(response.Body)
if egressForbidden {
// Web 403/code 7 表示出口浏览器会话被拒绝;Provider 已重建会话并降低节点健康,不应误伤账号。
// Web 403/code 7 means the browser session at the egress was rejected; the Provider rebuilt it and reduced node health, so do not penalize the account.
delete(excluded, credential.ID)
lease.Release()
lastErr = fmt.Errorf("Grok Web 出口会话被反机器人规则拒绝")
@@ -666,7 +667,8 @@ attemptLoop:
continue
}
lastFailure = newHTTPUpstreamFailure(response.StatusCode, body, credential.ID, credential.Name)
// Adapter 仅允许 auto Super 在同请求内回退 XAI;非 Super 的 403 按账号级故障冷却换号。
// The adapter only allows auto Super accounts to fall back to XAI within the same request;
// 403 from non-Super accounts triggers account-level cooldown and rotation.
freeBuildForbidden := response.StatusCode == http.StatusForbidden && credential.Provider == accountdomain.ProviderBuild && !accountdomain.IsBuildSuper(credential, lease.Billing)
if freeBuildForbidden {
lastFailure.AccountScoped = true
@@ -726,9 +728,8 @@ attemptLoop:
}
if s.providers.SupportsCredentialRefresh(credential.Provider) && lastFailure.PermanentAccountDenial {
if credential.Provider == accountdomain.ProviderBuild {
// A Build account can lack access to one chat model while its OAuth
// credential and video entitlement remain valid. Keep the denial
// model-scoped; only an actual credential rejection requires reauth.
// A Build account may lack permission for one chat model while its OAuth credential and video
// access remain valid. Isolate this denial to the model; reauthorization is needed only when the credential is rejected.
s.selector.MarkModelAccessDenied(ctx, credential, route.UpstreamModel, retryAfter)
} else {
_ = s.accounts.MarkReauthRequired(ctx, credential.ID, fmt.Sprintf("%s chat endpoint access denied", credential.Provider))
@@ -909,7 +910,8 @@ func (s *Service) markSSOCredentialRejected(ctx context.Context, credential acco
if err := s.accounts.MarkReauthRequired(writeCtx, credential.ID, reason); err != nil {
s.logger.Error("account_reauth_required_write_failed", "account_id", credential.ID, "provider", credential.Provider, "error", err)
}
// 即使持久化失败也立即丢弃本进程的一秒候选快照,避免当前失效账号被下一请求再次选中。
// Discard the process-local one-second candidate snapshot even if persistence fails,
// preventing the invalid account from being selected by the next request.
s.selector.MarkQuotaStateChanged(credential.Provider)
}
@@ -1083,7 +1085,7 @@ func (s *Service) forwardOwnedResponse(ctx context.Context, input ResourceInput,
return &Result{StatusCode: response.StatusCode, Status: response.Status, Header: response.Header, Body: &finalizingBody{ReadCloser: response.Body, finalize: release}, Finalize: finalize}, nil
}
// markPermanentlyUnrefreshableCredentialRejected 在真实上游请求确认 access token 失效后立即移出账号池。
// markPermanentlyUnrefreshableCredentialRejected removes an account from the pool after a real upstream request confirms its access token is invalid.
func (s *Service) markPermanentlyUnrefreshableCredentialRejected(ctx context.Context, credential accountdomain.Credential) bool {
if !credential.RefreshPermanent {
return false
@@ -133,7 +133,7 @@ func TestSyncAccountNormalizesBuildVideo15ByBillingSuper(t *testing.T) {
modelRepo := relational.NewModelRepository(database)
auditRepo := relational.NewAuditRepository(database)
// Super 主 Build:上游仅 grok-4.5,未开 fallback。
// Super on primary Build: upstream exposes only grok-4.5 and fallback is disabled.
superPrimary, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{
Provider: account.ProviderBuild, Name: "super-primary", SourceKey: "super-primary",
EncryptedAccessToken: encrypted, ExpiresAt: time.Now().Add(time.Hour), AuthStatus: account.AuthStatusActive,
@@ -141,7 +141,7 @@ func TestSyncAccountNormalizesBuildVideo15ByBillingSuper(t *testing.T) {
if err != nil {
t.Fatal(err)
}
// Super fallback:上游目录含 1.5 与其它模型。
// Super with fallback: the upstream catalog includes 1.5 and other models.
superFallback, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{
Provider: account.ProviderBuild, Name: "super-fallback", SourceKey: "super-fallback",
EncryptedAccessToken: encrypted, ExpiresAt: time.Now().Add(time.Hour), AuthStatus: account.AuthStatusActive,
@@ -150,7 +150,7 @@ func TestSyncAccountNormalizesBuildVideo15ByBillingSuper(t *testing.T) {
if err != nil {
t.Fatal(err)
}
// Free:Billing 无 paid 信号,但上游目录暴露 1.5。
// Free: Billing has no paid signal, but the upstream catalog exposes 1.5.
freeAccount, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{
Provider: account.ProviderBuild, Name: "free-fallback", SourceKey: "free-fallback",
EncryptedAccessToken: encrypted, ExpiresAt: time.Now().Add(time.Hour), AuthStatus: account.AuthStatusActive,
@@ -159,7 +159,7 @@ func TestSyncAccountNormalizesBuildVideo15ByBillingSuper(t *testing.T) {
if err != nil {
t.Fatal(err)
}
// Unknown:无 Billing 快照,上游目录暴露 1.5。
// Unknown: no Billing snapshot and the upstream catalog exposes 1.5.
unknownAccount, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{
Provider: account.ProviderBuild, Name: "unknown", SourceKey: "unknown",
EncryptedAccessToken: encrypted, ExpiresAt: time.Now().Add(time.Hour), AuthStatus: account.AuthStatusActive,
@@ -167,7 +167,7 @@ func TestSyncAccountNormalizesBuildVideo15ByBillingSuper(t *testing.T) {
if err != nil {
t.Fatal(err)
}
// Web 不应实现能力归一化;目录原样写入。
// Web must not implement capability normalization; persist its catalog unchanged.
webAccount, _, err := accountRepo.UpsertByIdentity(ctx, account.Credential{
Provider: account.ProviderWeb, AuthType: account.AuthTypeSSO, WebTier: account.WebTierSuper, Name: "web", SourceKey: "web",
EncryptedAccessToken: encrypted, ExpiresAt: time.Now().Add(time.Hour), AuthStatus: account.AuthStatusActive,
@@ -189,9 +189,9 @@ func TestSyncAccountNormalizesBuildVideo15ByBillingSuper(t *testing.T) {
const video15 = "grok-imagine-video-1.5"
buildAdapter := &buildCapabilityNormalizerAdapter{modelCapabilityAdapter: &modelCapabilityAdapter{models: map[uint64][]string{
superPrimary.ID: {"grok-4.5"},
superFallback.ID: {"grok-4.5", video15, "grok-code-fast-1", video15},
freeAccount.ID: {"grok-4.5", video15},
superPrimary.ID: {"grok-4.5"},
superFallback.ID: {"grok-4.5", video15, "grok-code-fast-1", video15},
freeAccount.ID: {"grok-4.5", video15},
unknownAccount.ID: {video15, "grok-4.5"},
}}}
webAdapter := &modelCapabilityAdapter{provider: account.ProviderWeb, models: map[uint64][]string{
@@ -236,12 +236,12 @@ func TestSyncAccountNormalizesBuildVideo15ByBillingSuper(t *testing.T) {
assertSupports(superFallback.ID, "grok-code-fast-1", true)
assertSupports(freeAccount.ID, "grok-4.5", true)
// Build 1.5 路由默认 capability 为 video。
// Build 1.5 routes default to the video capability.
route, err := modelRepo.GetByPublicID(ctx, "Build/"+video15)
if err != nil || route.Capability != modeldomain.CapabilityVideo {
t.Fatalf("build video route = %#v, err = %v", route, err)
}
// Web 未走 Build 归一化,仍支持其目录模型。
// Web does not use Build normalization and still supports its catalog models.
webCandidates, err := accountRepo.ListRoutingCandidates(ctx, account.ProviderWeb, "grok-imagine-video", "")
if err != nil || len(webCandidates) != 1 || !webCandidates[0].SupportsModel {
t.Fatalf("web candidates = %#v, err = %v", webCandidates, err)
@@ -331,13 +331,13 @@ type modelCapabilityAdapter struct {
peak atomic.Int64
}
// buildCapabilityNormalizerAdapter 模拟 Build Adapter:实现可选能力归一化契约。
// buildCapabilityNormalizerAdapter simulates a Build Adapter implementing optional capability normalization.
type buildCapabilityNormalizerAdapter struct {
*modelCapabilityAdapter
}
func (a *buildCapabilityNormalizerAdapter) NormalizeAccountModelCapabilities(models []string, billing *account.Billing, credential account.Credential) []string {
// 与 cli.Adapter 规则一致:Super(paid 或 entitlement)确保 1.5;否则精确移除。不读 BuildAPIFallback。
// Match cli.Adapter rules: Super (paid or entitlement) ensures 1.5; otherwise remove it exactly. Ignore BuildAPIFallback.
const video15 = "grok-imagine-video-1.5"
super := account.IsBuildSuper(credential, billing)
result := make([]string, 0, len(models)+1)
+11 -11
View File
@@ -169,9 +169,9 @@ func (m *Manager) AcquireCredential(ctx context.Context, scope domain.Scope, cre
identity = string(credential.Provider) + "_" + strconv.FormatUint(credential.ID, 10)
}
// Web and Console accounts can be two database projections of the same SSO
// login. Resin must see one stable account identity across both channels;
// login. Resin must see one stable account identity across both channels;
// otherwise the proxy rotates the IP while the clearance remains bound to
// the other lease. The digest is non-reversible and is only used as a proxy
// the other lease. The digest is non-reversible and is only used as a proxy
// template account label.
if strings.TrimSpace(credential.EgressIdentity) == "" && credential.AuthType == accountdomain.AuthTypeSSO && strings.TrimSpace(credential.EncryptedAccessToken) != "" {
token, decryptErr := m.cipher.Decrypt(credential.EncryptedAccessToken)
@@ -393,7 +393,7 @@ func fallbackScopes(scope domain.Scope) []domain.Scope {
return []domain.Scope{domain.ScopeWebAsset, domain.ScopeWeb}
}
if scope == domain.ScopeConsole {
// Console uses the same browser/clearance surface as Grok Web. A
// Console uses the same browser/clearance surface as Grok Web. A
// dedicated Console node is preferred, but a Web node is a safe and
// expected fallback for deployments that configure one shared pool.
return []domain.Scope{domain.ScopeConsole, domain.ScopeWeb}
@@ -462,9 +462,9 @@ func (m *Manager) clientFor(id uint64, scope domain.Scope, proxyURL, userAgent,
value.browser = client
}
value.lastUsed = now
// 固定代理同节点出现新指纹说明配置已更新,旧连接池应淘汰。
// 账号模板代理的指纹会随 Resin Account 变化,必须并存才能维持各账号的粘性连接池。
// 直连节点统一使用 ID 0,不同 Provider 的传输必须并存,避免 Build 与 Web 互相重建客户端。
// A new fingerprint on the same fixed-proxy node means its configuration changed, so evict the old connection pool.
// Account-template proxy fingerprints vary by Resin Account and must coexist to preserve per-account sticky pools.
// Direct nodes all use ID 0, so transports for different Providers must coexist to prevent Build and Web rebuilding each other.
if id != 0 && !sticky {
for previousKey, previous := range m.clients {
if previousKey.nodeID != id {
@@ -550,17 +550,17 @@ func (m *Manager) FeedbackForScope(ctx context.Context, scope domain.Scope, node
case status == http.StatusUnauthorized || status == http.StatusTooManyRequests:
return
case scope == domain.ScopeBuild && status == http.StatusForbidden:
// Build 403 可能是账号权限、额度、Token 或出口策略,响应体由网关层
// 分类;仅凭状态码不能把标准 CLI 出口误判为 Web anti-bot。
// Build 403 may indicate account permissions, quota, token, or egress policy. The gateway classifies the body;
// status alone must not misclassify standard CLI egress as Web anti-bot behavior.
return
case scope == domain.ScopeBuild && status == http.StatusBadRequest:
// Device OAuth 在用户确认前会以 400 + authorization_pending 轮询,
// 这是协议正常状态,不能当作出口节点故障进入冷却。
// Device OAuth polls with 400 + authorization_pending before user confirmation.
// This is a normal protocol state and must not cool the egress node.
return
case status == http.StatusForbidden:
if m.isStickyProxyNode(value) {
// A 403 on an account-bound Resin lease usually means that account's
// clearance is stale. Do not cool or invalidate the shared node for
// The account clearance is stale. Do not cool or invalidate the shared node for
// unrelated accounts.
return
}
+12 -11
View File
@@ -10,8 +10,8 @@ import (
domain "github.com/chenyme/grok2api/backend/internal/domain/egress"
)
// Selection 是一次上游请求实际选择的出口快照。它只包含可安全写入审计的元数据,
// 不包含代理 URL、认证信息、User-Agent 或 Cookie。
// Selection is the egress snapshot actually selected for an upstream request. It contains only metadata safe for audit
// and excludes proxy URLs, credentials, User-Agent, and Cookies.
type Selection struct {
NodeID uint64
NodeName string
@@ -19,8 +19,8 @@ type Selection struct {
Proxied bool
}
// Trace 按作用域保留最后一次实际出口选择。相同请求发生出口重试时,审计记录最终尝试;
// Web 资源归档使用独立作用域,不会覆盖主要的 Grok Web 推理出口。
// Trace retains the most recent actual egress selection per scope. When a request retries egress, audit records the final attempt.
// Web asset archival uses an independent scope and does not overwrite the primary Grok Web inference egress.
type Trace struct {
mu sync.RWMutex
selections map[domain.Scope]Selection
@@ -29,8 +29,8 @@ type Trace struct {
type traceContextKey struct{}
type accountContextKey struct{}
// WithAccount 将稳定的 Provider 账号身份传递到出口层。该值只用于渲染
// Resin 等粘性代理的认证用户名,不会写入上游 Header 或审计。
// WithAccount passes a stable Provider account identity to the egress layer. It is used only to render
// authentication usernames for sticky proxies such as Resin and is never written to upstream headers or audit.
func WithAccount(ctx context.Context, provider string, accountID uint64) context.Context {
if ctx == nil || strings.TrimSpace(provider) == "" || accountID == 0 {
return ctx
@@ -38,7 +38,8 @@ func WithAccount(ctx context.Context, provider string, accountID uint64) context
return WithAccountIdentity(ctx, strings.TrimSpace(provider)+"_"+fmt.Sprintf("%d", accountID))
}
// WithCredential 将弱关联账号的稳定出口身份传给 Build 传输;未关联账号保持原有 Provider+ID 身份。
// WithCredential passes the stable egress identity of a weakly linked account to Build transport;
// unlinked accounts retain the existing Provider+ID identity.
func WithCredential(ctx context.Context, credential accountdomain.Credential) context.Context {
identity := strings.TrimSpace(credential.EgressIdentity)
if identity == "" {
@@ -52,7 +53,7 @@ func WithCredential(ctx context.Context, credential accountdomain.Credential) co
}
// WithAccountIdentity attaches the stable, non-sensitive identity used by
// account-bound proxy templates such as Resin. Providers that represent the
// account-bound proxy templates such as Resin. Providers that represent the
// same upstream login (for example Web and Console sharing one SSO token) can
// deliberately pass the same identity so their proxy and clearance lease is
// not split by the internal provider name.
@@ -75,7 +76,7 @@ func accountFromContext(ctx context.Context) string {
// provider transports while keeping the context key private.
func AccountFromContext(ctx context.Context) string { return accountFromContext(ctx) }
// WithTrace 为一次网关请求创建或复用并发安全的出口选择轨迹。
// WithTrace creates or reuses a concurrency-safe egress selection trace for one gateway request.
func WithTrace(ctx context.Context) (context.Context, *Trace) {
if existing := TraceFromContext(ctx); existing != nil {
return ctx, existing
@@ -84,7 +85,7 @@ func WithTrace(ctx context.Context) (context.Context, *Trace) {
return context.WithValue(ctx, traceContextKey{}, trace), trace
}
// TraceFromContext 返回上下文中的出口轨迹;未配置时返回 nil。
// TraceFromContext returns the egress trace from context, or nil when none is configured.
func TraceFromContext(ctx context.Context) *Trace {
if ctx == nil {
return nil
@@ -93,7 +94,7 @@ func TraceFromContext(ctx context.Context) *Trace {
return trace
}
// Selection 返回指定作用域最后一次实际出口选择的安全快照。
// Selection returns a safe snapshot of the most recent actual egress selection for a scope.
func (t *Trace) Selection(scope domain.Scope) (Selection, bool) {
if t == nil {
return Selection{}, false
+53 -35
View File
@@ -39,7 +39,7 @@ type Config struct {
const subscriptionTierTimeout = 10 * time.Second
// Adapter 实现 Grok Build CLI Responses、模型、Billing 与 OAuth 协议。
// Adapter implements the Grok Build CLI Responses, model, Billing, and OAuth protocols.
type Adapter struct {
cfgMu sync.RWMutex
cfg Config
@@ -60,8 +60,8 @@ type Adapter struct {
func NewAdapter(cfg Config, cipher *security.Cipher) *Adapter {
transport := &http.Transport{Proxy: http.ProxyFromEnvironment, ForceAttemptHTTP2: true, MaxIdleConns: 256, MaxIdleConnsPerHost: 128, MaxConnsPerHost: 256, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ResponseHeaderTimeout: 30 * time.Second}
httpClient := &http.Client{Transport: transport}
// 官方 CLI 使用持久化机器身份。网关不采集机器指纹,改为每个后端
// 进程生成一个随机 UUID,在进程生命周期内作为统一 Agent 身份。
// The official CLI uses a persistent machine identity. The gateway does not collect machine fingerprints;
// instead each backend process generates one random UUID for its lifetime as the Agent identity.
agentID := uuid.NewString()
return &Adapter{
cfg: cfg, http: httpClient, oauth: newOAuthClient(httpClient), cipher: cipher, base: transport,
@@ -81,15 +81,15 @@ func (a *Adapter) SetEgress(manager *infraegress.Manager) {
}
}
// SetReasoningReplay 注入服务端推理回放缓存(可选)。
// SetReasoningReplay injects the optional server-side reasoning replay cache.
func (a *Adapter) SetReasoningReplay(replay *reasoningreplay.ReasoningReplay) {
a.replay = replay
}
func (a *Adapter) Provider() account.Provider { return account.ProviderBuild }
// CredentialMetadata 只从 Build access token 提取非敏感风险标记。
// bot_flag_source 必须是 JSON 数字 1;其他值、畸形 token 或解密失败均不标记。
// CredentialMetadata extracts only non-sensitive risk flags from a Build access token.
// bot_flag_source must be JSON number 1; other values, malformed tokens, and decryption failures are not marked.
func (a *Adapter) CredentialMetadata(credential account.Credential) provider.CredentialMetadata {
if credential.Provider != account.ProviderBuild || a.cipher == nil || credential.EncryptedAccessToken == "" {
return provider.CredentialMetadata{}
@@ -122,6 +122,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
body := request.Body
var toolCompatibility *responsesToolCompatibility
var conversationOptions conversation.ResponseOptions
cacheRoute := buildPromptCacheRoute{}
compactionRequested := false
if request.NormalizeBody {
if request.Operation == conversation.OperationChat || request.Operation == conversation.OperationMessages {
@@ -158,6 +159,15 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
}
if len(body) > 0 && request.Method == http.MethodPost {
if !compactionRequested {
allowClientTools := request.AllowClientToolCacheRoute || (account.RoutingCandidate{Credential: request.Credential, Billing: request.Billing}).IsKnownFreeBuild()
body, cacheRoute, err = prepareBuildPromptCacheRoute(body, request.Operation, request.Model, request.PromptCacheKey, allowClientTools)
if err != nil {
err = fmt.Errorf("准备 Build prompt cache 路由: %w", err)
if request.Operation == conversation.OperationChat || request.Operation == conversation.OperationMessages {
return invalidConversationResponse(request.Operation, err), nil
}
return invalidResponsesResponse(err), nil
}
body, err = injectPromptCacheKey(body, request.PromptCacheKey)
if err != nil {
err = fmt.Errorf("写入 prompt_cache_key: %w", err)
@@ -175,11 +185,11 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
}
return a.forwardGatewayCompaction(ctx, request, accessToken, body, warnings)
}
// 显式模式优先;auto 下仅已确认 Super 且 bot_flag_source=1 的账号默认走 XAI。
// Explicit mode wins; in auto mode only confirmed Super accounts with bot_flag_source=1 default to XAI.
primaryBase := a.primaryBaseURL()
base := a.inferenceBaseForOperation(request.Credential, request.Billing, request.Method, request.Path)
// 缓存亲和与推理回放使用不同身份。回放还必须绑定实际账号和上游平面,
// 避免把一个账号或 Build 平面签发的 opaque reasoning 发给另一作用域。
// Cache affinity and reasoning replay use separate identities. Replay is also bound to the actual account and upstream plane,
// preventing opaque reasoning issued for one account or Build plane from reaching another scope.
replayBaseBody := body
body, replayKey := a.applyReasoningReplay(ctx, request, replayBaseBody, base)
resp, reqURL, err := a.doResponseRequest(ctx, request, accessToken, body, base)
@@ -190,9 +200,9 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
return nil, err
}
resp, reqURL, reasoningRecovery := a.recoverReasoningDecodeFailure(ctx, request, accessToken, body, base, replayKey, resp, reqURL)
// 仅可回退操作在当次 Build 主地址明确 403 时用等价请求探测 XAI。
// Only eligible operations probe XAI with an equivalent request after the Build primary explicitly returns 403.
if strings.EqualFold(base, primaryBase) && shouldProbeXAIInferenceFallback(request.Credential, request.Billing, request.Method, request.Path, resp.StatusCode) {
// 缓冲主 403 正文,备用失败时原样回放,避免二次 primary POST。
// Buffer the primary 403 body and replay it unchanged if fallback fails; never issue a second primary POST.
primaryBody, primaryTruncated, readErr := provider.ReadDiagnosticBody(resp.Body)
_ = resp.Body.Close()
if readErr != nil {
@@ -218,7 +228,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
if fallbackErr == nil {
_ = fallbackResp.Body.Close()
}
// 保留原 primary 403 的 URL 与缓冲正文,不再次请求主地址。
// Preserve the original primary 403 URL and buffered body without requesting the primary again.
resp = primaryResp
}
} else {
@@ -226,10 +236,17 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response
}
}
modelCatalogChanged := a.modelCatalogChanged(request.Credential.ID, resp.Header.Get("x-models-etag"))
// 在协议转换前捕获上游 Responses 形态,写入/清理推理回放缓存。
// Capture or clear reasoning replay in the upstream Responses shape before protocol conversion.
if a.shouldCaptureReplay(request, resp, replayKey) {
resp.Body = a.replay.CaptureBody(resp.Body, request.Model, replayKey, request.Streaming, isCompactPath(request.Path))
}
// Replay must read the raw upstream output. Hide xAI native search subcalls from downstream clients
// only after capture wrapping has completed.
if isHTTPSuccess(resp.StatusCode) {
if err := filterBuildPromptCacheResponse(resp, request.Streaming, cacheRoute); err != nil {
return nil, err
}
}
responsesOperation := request.Operation == "" || request.Operation == conversation.OperationResponses || request.Operation == conversation.OperationCompaction
if responsesOperation && toolCompatibility != nil {
if warnings := toolCompatibility.warningHeader(); warnings != "" {
@@ -323,7 +340,7 @@ func (a *Adapter) applyReasoningReplay(ctx context.Context, request provider.Res
return body, ""
}
if isCompactPath(request.Path) {
// compact 不注入历史,但成功后仍需用同一作用域清理旧 replay。
// compact does not inject history, but a successful request still clears old replay in the same scope.
return body, key
}
return a.replay.Apply(ctx, request.Model, key, body), key
@@ -379,7 +396,7 @@ func (a *Adapter) doResponseRequest(ctx context.Context, request provider.Respon
return resp, req.URL.String(), nil
}
// applyGrokTurnIndexHeader 只在请求已有稳定 Grok session 时透传真实客户端轮次。
// applyGrokTurnIndexHeader forwards a real client turn only when the request has a stable Grok session.
func applyGrokTurnIndexHeader(request *http.Request, value string) {
if request.Header.Get("x-grok-session-id") == "" {
return
@@ -389,8 +406,8 @@ func applyGrokTurnIndexHeader(request *http.Request, value string) {
}
}
// normalizeGrokTurnIndex 只接受官方客户端生成的非负十进制 u64。
// 空值或非法值直接省略,避免网关根据历史、工具循环或 compact 结果伪造轮次。
// normalizeGrokTurnIndex accepts only non-negative decimal u64 values generated by an official client.
// Empty or invalid values are omitted; the gateway never fabricates turns from history, tool loops, or compaction.
func normalizeGrokTurnIndex(value string) string {
value = strings.TrimSpace(value)
if value == "" || len(value) > 20 {
@@ -407,7 +424,8 @@ func normalizeGrokTurnIndex(value string) string {
return value
}
// invalidResponsesResponse 将本地协议校验错误转换为标准 OpenAI 错误响应,避免触发上游账号重试。
// invalidResponsesResponse converts local protocol validation errors to a standard OpenAI error response,
// avoiding an upstream account retry.
func invalidResponsesResponse(err error) *provider.Response {
code := "invalid_request"
param := ""
@@ -448,8 +466,8 @@ func (a *Adapter) ListModels(ctx context.Context, credential account.Credential)
if err != nil {
return nil, err
}
// 模型目录始终请求 Build 主地址;不得因目录缺 1.5 或 Super entitlement 预切 XAI。
// 1.5 能力由 NormalizeAccountModelCapabilities 按 Billing paid / BuildSuperEntitled 本地补齐。
// Always request the model catalog from the Build primary; do not preemptively switch to XAI because 1.5 or Super entitlement is absent.
// NormalizeAccountModelCapabilities fills 1.5 locally from Billing paid or BuildSuperEntitled.
models, status, err := a.listModelsAt(ctx, credential, accessToken, a.primaryBaseURL())
if err != nil {
return nil, err
@@ -460,8 +478,8 @@ func (a *Adapter) ListModels(ctx context.Context, credential account.Credential)
return nil, fmt.Errorf("上游模型接口返回 %d", status)
}
// NormalizeAccountModelCapabilities 按 Super(Billing paid 或 BuildSuperEntitled)归一化 1.5 视频资格。
// Super 确保包含 grok-imagine-video-1.5;Free/Unknown 精确移除。不读取 BuildAPIFallback。
// NormalizeAccountModelCapabilities normalizes 1.5 video entitlement from Super (Billing paid or BuildSuperEntitled).
// Super always includes grok-imagine-video-1.5; Free and Unknown remove it exactly. BuildAPIFallback is ignored.
func (a *Adapter) NormalizeAccountModelCapabilities(models []string, billing *account.Billing, credential account.Credential) []string {
super := account.IsBuildSuper(credential, billing)
result := make([]string, 0, len(models)+1)
@@ -557,8 +575,8 @@ func (a *Adapter) modelCatalogChanged(accountID uint64, etag string) bool {
}
current := a.modelsETags[accountID]
if current == "" {
// 进程重启后内存中没有目录基线。让 Gateway 补一次账号级
// /models 同步;同步成功后 recordModelsETag 会建立基线。
// After a process restart there is no in-memory catalog baseline. Let the Gateway perform one account-level
// /models sync; recordModelsETag establishes the baseline after success.
return true
}
return current != etag
@@ -573,8 +591,8 @@ func (a *Adapter) GetBilling(ctx context.Context, credential account.Credential)
if err != nil {
return account.Billing{}, err
}
// 周额度在 0% 使用时无法区分 Free 与刚开通的付费套餐。官方 CLI
// 使用 /user?include=subscription 获取实时订阅等级;失败时再退回 JWT tier。
// A weekly quota at 0% usage cannot distinguish Free from a newly activated paid plan.
// The official CLI uses /user?include=subscription for the live subscription tier, then falls back to the JWT tier.
if tier, tierErr := a.getSubscriptionTier(ctx, credential, accessToken); tierErr == nil && tier != "" {
billing.PlanName = tier
} else if billing.PlanCode == "" && billing.PlanName == "" {
@@ -588,9 +606,9 @@ func (a *Adapter) GetBilling(ctx context.Context, credential account.Credential)
func (a *Adapter) RefreshCredential(ctx context.Context, credential account.Credential) (provider.RefreshedCredential, error) {
refreshToken, err := a.cipher.Decrypt(credential.EncryptedRefreshToken)
if err != nil {
// 解密失败通常是本地 encryption key 临时/不匹配,属于可恢复故障;
// 不得标记为 permanent(否则密钥恢复后手动/批量刷新永远不会重试)。
// 真正的 OAuth 永久失败(如 invalid_grant)由 oauth.refresh 返回 Permanent=true。
// Decryption failures are usually temporary or mismatched local encryption keys and are recoverable;
// do not mark them permanent, or manual/batch refresh will never retry after the key is fixed.
// True permanent OAuth failures such as invalid_grant are returned by oauth.refresh with Permanent=true.
return provider.RefreshedCredential{}, &provider.CredentialRefreshError{Code: "credential_decrypt_failed", Permanent: false, Cause: err}
}
if strings.TrimSpace(refreshToken) == "" {
@@ -645,8 +663,8 @@ func (a *Adapter) applyHeaders(req *http.Request, credential account.Credential,
if trace {
requestID := uuid.NewString()
// 对齐 CPA:仅在存在稳定 session 时设置 x-grok-conv-id / session-id。
// 禁止每请求随机 UUID,否则会打散 xAI 服务器亲和,导致 cached_tokens 长期为 0。
// Set x-grok-conv-id and session-id only when a stable session exists.
// Never generate a random UUID per request; it breaks xAI session affinity and keeps cached_tokens at zero.
sessionID, err := grokSessionID(promptCacheKey)
if err != nil {
return err
@@ -658,8 +676,8 @@ func (a *Adapter) applyHeaders(req *http.Request, credential account.Credential,
req.Header.Set("x-grok-conv-id", sessionID)
}
req.Header.Set("x-grok-req-id", requestID)
// 网关无法从无状态 API 请求可靠恢复 CLI prompt index;该字段在
// 官方协议中可选,因此不伪造 x-grok-turn-idx。
// The gateway cannot reliably recover the CLI prompt index from a stateless API request.
// The field is optional in the official protocol, so do not fabricate x-grok-turn-idx.
if credential.UserID != "" {
req.Header.Set("x-grok-user-id", credential.UserID)
}
@@ -689,8 +707,8 @@ func (a *Adapter) applyHeaders(req *http.Request, credential account.Credential,
return nil
}
// grokSessionID 将稳定会话键转为上游 x-grok-conv-id。
// 空键返回空串(对齐 CPA grok_build_stays_stateless_without_session),绝不每请求随机生成。
// grokSessionID converts a stable session key to the upstream x-grok-conv-id.
// An empty key returns an empty string; stateless requests never receive a random ID.
func grokSessionID(promptCacheKey string) (string, error) {
key := strings.TrimSpace(promptCacheKey)
if key == "" {
@@ -451,12 +451,12 @@ func TestGetBillingUsesCreditsAndLiveSubscriptionTier(t *testing.T) {
func TestNormalizeAccountModelCapabilitiesSuperAddsVideo15(t *testing.T) {
adapter := &Adapter{}
build := account.Credential{Provider: account.ProviderBuild}
// Super / paid:主 Build 仅返回 grok-4.5 时也必须补齐 1.5。
// Super / paid: add 1.5 even when primary Build returns only grok-4.5.
got := adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5", " ", "grok-4.5"}, &account.Billing{MonthlyLimit: 100}, build)
if len(got) != 2 || got[0] != "grok-4.5" || got[1] != buildVideoModel {
t.Fatalf("super primary catalog = %#v", got)
}
// Super + 目录已含 1.5:幂等去重,其它模型不变。
// Super with 1.5 already present: deduplicate idempotently and preserve other models.
got = adapter.NormalizeAccountModelCapabilities(
[]string{"grok-4.5", buildVideoModel, "grok-code-fast-1", buildVideoModel},
&account.Billing{OnDemandCap: 10},
@@ -465,22 +465,22 @@ func TestNormalizeAccountModelCapabilitiesSuperAddsVideo15(t *testing.T) {
if len(got) != 3 || got[0] != "grok-4.5" || got[1] != buildVideoModel || got[2] != "grok-code-fast-1" {
t.Fatalf("super catalog = %#v", got)
}
// Free:即使目录暴露 1.5 也必须移除。
// Free: remove 1.5 even when the catalog exposes it.
got = adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5", buildVideoModel}, &account.Billing{Used: 1, PlanName: "free"}, build)
if len(got) != 1 || got[0] != "grok-4.5" {
t.Fatalf("free catalog = %#v", got)
}
// Unknown(无 Billing):与 Free 相同,移除 1.5。
// Unknown (no Billing): treat as Free and remove 1.5.
got = adapter.NormalizeAccountModelCapabilities([]string{buildVideoModel, "grok-4.5"}, nil, build)
if len(got) != 1 || got[0] != "grok-4.5" {
t.Fatalf("unknown catalog = %#v", got)
}
// 不得依赖 BuildAPIFallback;空目录 + Billing Super 仅补 1.5。
// Do not depend on BuildAPIFallback; an empty catalog with Billing Super adds only 1.5.
got = adapter.NormalizeAccountModelCapabilities(nil, &account.Billing{PlanName: "SuperGrok", CreditUsagePercent: 1}, build)
if len(got) != 1 || got[0] != buildVideoModel {
t.Fatalf("super empty catalog = %#v", got)
}
// 零 Billing + BuildSuperEntitled:补齐 1.5。
// Zero-value Billing with BuildSuperEntitled: add 1.5.
entitled := account.Credential{Provider: account.ProviderBuild, BuildSuperEntitled: true}
got = adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5"}, &account.Billing{IsUnifiedBillingUser: true}, entitled)
if len(got) != 2 || got[0] != "grok-4.5" || got[1] != buildVideoModel {
@@ -505,7 +505,7 @@ func TestGrokSessionIDFollowsConversationIdentity(t *testing.T) {
if err != nil || parsed.Version() != uuid.Version(8) || first != second {
t.Fatalf("derived sessions = %q %q, %v", first, second, err)
}
// 对齐 CPA:无会话键时不得伪造随机 conv-id,否则会打散 xAI 服务器亲和导致 cached_tokens=0。
// Never fabricate a random conv-id without a session key; it breaks xAI server affinity and keeps cached_tokens at zero.
generated, err := grokSessionID("")
if err != nil {
t.Fatal(err)
@@ -0,0 +1,155 @@
package cli
import (
"encoding/json"
"fmt"
"strings"
)
// buildPromptCacheRoute records internal tools added to route this request through the cache-capable path.
// injectedToolTypes restores the client's original visible tool list during response processing.
type buildPromptCacheRoute struct {
filterXSearch bool
injectedToolTypes map[string]struct{}
clientDeclaredTools map[string]struct{}
}
func prepareBuildPromptCacheRoute(body []byte, operation, model, promptCacheKey string, allowClientTools bool) ([]byte, buildPromptCacheRoute, error) {
route := buildPromptCacheRoute{
injectedToolTypes: make(map[string]struct{}),
clientDeclaredTools: make(map[string]struct{}),
}
var payload map[string]json.RawMessage
if err := json.Unmarshal(body, &payload); err != nil {
return nil, route, fmt.Errorf("解析 Build prompt cache 请求: %w", err)
}
if payload == nil {
payload = make(map[string]json.RawMessage)
}
tools, err := buildCacheRouteTools(payload)
if err != nil {
return nil, route, err
}
for _, rawTool := range tools {
kind, name := buildCacheToolIdentity(rawTool)
if kind == "function" || kind == "custom" {
if name != "" {
route.clientDeclaredTools[name] = struct{}{}
}
}
if kind == "x_search" {
route.filterXSearch = true
}
}
// Hide upstream internal subcalls even when the client explicitly declares x_search.
// Cache routing itself applies only to plain-text conversations with a stable cache session identity.
if strings.TrimSpace(promptCacheKey) == "" || !isBuildCacheConversationOperation(operation) || isBuildCacheMediaModel(model) || hasBuildCacheToolType(tools, "image_generation") {
return body, route, nil
}
if len(tools) == 0 {
// A tool-free request uses none to select the cache-capable route without granting search capability.
tools = append(tools, json.RawMessage(`{"type":"web_search"}`), json.RawMessage(`{"type":"x_search"}`))
payload["tool_choice"] = mustJSON("none")
route.injectedToolTypes["web_search"] = struct{}{}
route.injectedToolTypes["x_search"] = struct{}{}
route.filterXSearch = true
} else if !hasBuildCacheToolType(tools, "x_search") && (allowClientTools || hasBuildCacheToolType(tools, "web_search")) {
// With client tools, add only the x_search route required by the official Build behavior and preserve
// the original tool_choice. Do not also expose web_search.
tools = append(tools, json.RawMessage(`{"type":"x_search"}`))
route.injectedToolTypes["x_search"] = struct{}{}
route.filterXSearch = true
}
payload["tools"] = mustJSON(tools)
if _, injected := route.injectedToolTypes["x_search"]; injected {
updatedChoice, choiceErr := appendBuildCacheXSearchToAllowedTools(payload["tool_choice"])
if choiceErr != nil {
return nil, route, choiceErr
}
if len(updatedChoice) > 0 {
payload["tool_choice"] = updatedChoice
}
}
encoded, err := json.Marshal(payload)
if err != nil {
return nil, route, fmt.Errorf("编码 Build prompt cache 请求: %w", err)
}
return encoded, route, nil
}
func appendBuildCacheXSearchToAllowedTools(raw json.RawMessage) (json.RawMessage, error) {
if isEmptyJSON(raw) {
return nil, nil
}
var choice map[string]json.RawMessage
if json.Unmarshal(raw, &choice) != nil || choice == nil {
return nil, nil
}
var choiceType string
_ = json.Unmarshal(choice["type"], &choiceType)
if strings.TrimSpace(choiceType) != "allowed_tools" {
return nil, nil
}
var allowed []json.RawMessage
if json.Unmarshal(choice["tools"], &allowed) != nil {
return nil, nil
}
for _, item := range allowed {
kind, _ := buildCacheToolIdentity(item)
if kind == "x_search" {
return nil, nil
}
}
allowed = append(allowed, json.RawMessage(`{"type":"x_search"}`))
choice["tools"] = mustJSON(allowed)
return json.Marshal(choice)
}
func buildCacheRouteTools(payload map[string]json.RawMessage) ([]json.RawMessage, error) {
raw, exists := payload["tools"]
if !exists || isEmptyJSON(raw) {
return nil, nil
}
var tools []json.RawMessage
if json.Unmarshal(raw, &tools) != nil {
return nil, &responsesRequestError{Message: "tools 必须是数组", Param: "tools", Code: "invalid_parameter"}
}
return tools, nil
}
func buildCacheToolIdentity(raw json.RawMessage) (kind, name string) {
var tool struct {
Type string `json:"type"`
Name string `json:"name"`
}
if json.Unmarshal(raw, &tool) != nil {
return "", ""
}
return strings.TrimSpace(tool.Type), strings.TrimSpace(tool.Name)
}
func hasBuildCacheToolType(tools []json.RawMessage, kind string) bool {
for _, rawTool := range tools {
toolType, _ := buildCacheToolIdentity(rawTool)
if toolType == kind {
return true
}
}
return false
}
func isBuildCacheConversationOperation(operation string) bool {
switch strings.TrimSpace(operation) {
case "", "responses", "chat", "messages":
return true
default:
return false
}
}
func isBuildCacheMediaModel(model string) bool {
model = strings.ToLower(strings.TrimSpace(model))
return strings.Contains(model, "image") || strings.Contains(model, "imagine") || strings.Contains(model, "video")
}
@@ -0,0 +1,237 @@
package cli
import (
"encoding/json"
"io"
"net/http"
"strconv"
"strings"
"testing"
)
func TestPrepareBuildPromptCacheRouteToolFree(t *testing.T) {
body, route, err := prepareBuildPromptCacheRoute([]byte(`{"model":"grok-4.5","input":"hello"}`), "responses", "grok-4.5", "cache-key", false)
if err != nil {
t.Fatal(err)
}
var payload map[string]any
if err := json.Unmarshal(body, &payload); err != nil {
t.Fatal(err)
}
tools := payload["tools"].([]any)
if len(tools) != 2 || stringField(tools[0].(map[string]any), "type") != "web_search" || stringField(tools[1].(map[string]any), "type") != "x_search" {
t.Fatalf("tools = %#v", tools)
}
if payload["tool_choice"] != "none" || !route.filterXSearch || len(route.injectedToolTypes) != 2 {
t.Fatalf("route = %#v payload = %#v", route, payload)
}
}
func TestPrepareBuildPromptCacheRouteComplementsToolBearingRequest(t *testing.T) {
body, route, err := prepareBuildPromptCacheRoute([]byte(`{
"model":"grok-4.5","input":"hello","tool_choice":"auto",
"tools":[{"type":"function","name":"Read","parameters":{"type":"object"}}]
}`), "messages", "grok-4.5", "cache-key", true)
if err != nil {
t.Fatal(err)
}
var payload map[string]any
if err := json.Unmarshal(body, &payload); err != nil {
t.Fatal(err)
}
tools := payload["tools"].([]any)
if len(tools) != 2 || stringField(tools[1].(map[string]any), "type") != "x_search" || payload["tool_choice"] != "auto" {
t.Fatalf("payload = %#v", payload)
}
if _, ok := route.clientDeclaredTools["Read"]; !ok || len(route.injectedToolTypes) != 1 || !route.filterXSearch {
t.Fatalf("route = %#v", route)
}
}
func TestPrepareBuildPromptCacheRoutePreservesLargeIntegers(t *testing.T) {
body, _, err := prepareBuildPromptCacheRoute([]byte(`{"input":"hello","metadata":{"sequence":9007199254740993}}`), "responses", "grok-4.5", "cache-key", false)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(body), `"sequence":9007199254740993`) {
t.Fatalf("large integer changed during cache route rewrite: %s", body)
}
}
func TestPrepareBuildPromptCacheRouteDoesNotBroadenUntrustedFunctions(t *testing.T) {
body, route, err := prepareBuildPromptCacheRoute([]byte(`{
"input":"hello","tools":[{"type":"function","name":"lookup","parameters":{"type":"object"}}]
}`), "responses", "grok-4.5", "cache-key", false)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(body), `"x_search"`) || route.filterXSearch || len(route.injectedToolTypes) != 0 {
t.Fatalf("untrusted function request was broadened: body=%s route=%#v", body, route)
}
}
func TestPrepareBuildPromptCacheRouteComplementsExistingSearch(t *testing.T) {
body, route, err := prepareBuildPromptCacheRoute([]byte(`{"input":"hello","tools":[{"type":"web_search"}]}`), "responses", "grok-4.5", "cache-key", false)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(string(body), `"x_search"`) || !route.filterXSearch {
t.Fatalf("existing search route was not completed: body=%s route=%#v", body, route)
}
}
func TestPrepareBuildPromptCacheRouteExtendsAllowedTools(t *testing.T) {
body, _, err := prepareBuildPromptCacheRoute([]byte(`{
"input":"hello",
"tools":[{"type":"function","name":"Read"}],
"tool_choice":{"type":"allowed_tools","tools":[{"type":"function","name":"Read"}]}
}`), "responses", "grok-4.5", "cache-key", true)
if err != nil {
t.Fatal(err)
}
var payload map[string]any
if err := json.Unmarshal(body, &payload); err != nil {
t.Fatal(err)
}
choice := payload["tool_choice"].(map[string]any)
allowed := choice["tools"].([]any)
if len(allowed) != 2 || stringField(allowed[1].(map[string]any), "type") != "x_search" {
t.Fatalf("allowed tools = %#v", allowed)
}
}
func TestPrepareBuildPromptCacheRoutePreservesExplicitXSearch(t *testing.T) {
body, route, err := prepareBuildPromptCacheRoute([]byte(`{
"input":"hello","tools":[{"type":"x_search"}],"tool_choice":"auto"
}`), "responses", "grok-4.5", "cache-key", false)
if err != nil {
t.Fatal(err)
}
var payload map[string]any
if err := json.Unmarshal(body, &payload); err != nil {
t.Fatal(err)
}
tools := payload["tools"].([]any)
if len(tools) != 1 || stringField(tools[0].(map[string]any), "type") != "x_search" || payload["tool_choice"] != "auto" {
t.Fatalf("explicit x_search changed: %#v", payload)
}
if !route.filterXSearch || len(route.injectedToolTypes) != 0 {
t.Fatalf("explicit x_search route = %#v", route)
}
}
func TestPrepareBuildPromptCacheRouteRespectsBoundaries(t *testing.T) {
tests := []struct {
name string
body string
operation string
model string
key string
}{
{name: "no cache identity", body: `{"input":"hello"}`, operation: "responses", model: "grok-4.5"},
{name: "compaction", body: `{"input":"hello"}`, operation: "compaction", model: "grok-4.5", key: "key"},
{name: "image operation", body: `{"input":"hello"}`, operation: "image", model: "grok-4.5", key: "key"},
{name: "image model", body: `{"input":"hello"}`, operation: "responses", model: "grok-imagine-1.0", key: "key"},
{name: "image tool", body: `{"input":"hello","tools":[{"type":"image_generation"}]}`, operation: "responses", model: "grok-4.5", key: "key"},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
body, route, err := prepareBuildPromptCacheRoute([]byte(test.body), test.operation, test.model, test.key, false)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(body), `"x_search"`) || route.filterXSearch || len(route.injectedToolTypes) != 0 {
t.Fatalf("unexpected cache route: body=%s route=%#v", body, route)
}
})
}
}
func TestFilterBuildPromptCacheResponseJSON(t *testing.T) {
route := buildPromptCacheRoute{
filterXSearch: true,
injectedToolTypes: map[string]struct{}{"x_search": {}},
clientDeclaredTools: map[string]struct{}{"x_keyword_search": {}},
}
response := &http.Response{Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{
"id":"resp_1",
"usage":{"cost_in_usd_ticks":9007199254740993},
"tools":[{"type":"function","name":"x_keyword_search"},{"type":"x_search"}],
"output":[
{"type":"custom_tool_call","id":"internal","call_id":"xs_call-1","name":"x_keyword_search"},
{"type":"custom_tool_call","id":"client_custom","call_id":"call_custom_1","name":"x_keyword_search","input":"{}"},
{"type":"function_call","id":"client","call_id":"call_1","name":"x_keyword_search","arguments":"{}"},
{"type":"message","id":"msg_1","content":[{"type":"output_text","text":"done"}]}
]
}`))}
if err := filterBuildPromptCacheResponse(response, false, route); err != nil {
t.Fatal(err)
}
data, err := io.ReadAll(response.Body)
if err != nil {
t.Fatal(err)
}
text := string(data)
if strings.Contains(text, `"id":"internal"`) || strings.Contains(text, `"type":"x_search"`) || !strings.Contains(text, `"id":"client_custom"`) || !strings.Contains(text, `"id":"client"`) || !strings.Contains(text, `"id":"msg_1"`) || !strings.Contains(text, `"cost_in_usd_ticks":9007199254740993`) {
t.Fatalf("filtered response = %s", text)
}
if response.ContentLength != int64(len(data)) || response.Header.Get("Content-Length") != strconv.Itoa(len(data)) {
t.Fatalf("content length = %d header=%q want=%d", response.ContentLength, response.Header.Get("Content-Length"), len(data))
}
}
func TestFilterBuildPromptCacheResponseDropsInjectedWebSearch(t *testing.T) {
route := buildPromptCacheRoute{
injectedToolTypes: map[string]struct{}{"web_search": {}},
clientDeclaredTools: map[string]struct{}{},
}
response := &http.Response{Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{
"output":[{"type":"web_search_call","id":"ws_1"},{"type":"message","id":"msg_1"}]
}`))}
if err := filterBuildPromptCacheResponse(response, false, route); err != nil {
t.Fatal(err)
}
data, err := io.ReadAll(response.Body)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(data), "web_search_call") || !strings.Contains(string(data), `"id":"msg_1"`) {
t.Fatalf("injected web search trace leaked: %s", data)
}
}
func TestFilterBuildPromptCacheResponseStream(t *testing.T) {
route := buildPromptCacheRoute{
filterXSearch: true,
injectedToolTypes: map[string]struct{}{"x_search": {}},
clientDeclaredTools: map[string]struct{}{},
}
source := strings.Join([]string{
`event: response.output_item.added`,
`data: {"type":"response.output_item.added","output_index":1,"item":{"type":"custom_tool_call","id":"ctc_1","call_id":"xs_call-1","name":"x_semantic_search"}}`, "",
`event: response.custom_tool_call_input.delta`,
`data: {"type":"response.custom_tool_call_input.delta","output_index":1,"item_id":"ctc_1","delta":"{}"}`, "",
`event: response.output_item.added`,
`data: {"type":"response.output_item.added","output_index":2,"item":{"type":"message","id":"msg_1"}}`, "",
`event: response.completed`,
`data: {"type":"response.completed","response":{"tools":[{"type":"x_search"}],"output":[{"type":"custom_tool_call","id":"ctc_1","call_id":"xs_call-1","name":"x_semantic_search"},{"type":"message","id":"msg_1"}]}}`, "", "",
}, "\n")
response := &http.Response{Header: http.Header{"Content-Type": {"text/event-stream"}}, Body: io.NopCloser(strings.NewReader(source))}
if err := filterBuildPromptCacheResponse(response, true, route); err != nil {
t.Fatal(err)
}
if response.ContentLength != -1 || response.Header.Get("Content-Length") != "" {
t.Fatalf("stream content length = %d header=%q", response.ContentLength, response.Header.Get("Content-Length"))
}
data, err := io.ReadAll(response.Body)
if err != nil {
t.Fatal(err)
}
text := string(data)
if strings.Contains(text, "x_semantic_search") || strings.Contains(text, "ctc_1") || strings.Contains(text, `"type":"x_search"`) {
t.Fatalf("internal x_search trace leaked:\n%s", text)
}
if !strings.Contains(text, `"output_index":1`) || !strings.Contains(text, `"id":"msg_1"`) {
t.Fatalf("remaining output was not compacted:\n%s", text)
}
}
@@ -12,6 +12,7 @@ import (
"github.com/chenyme/grok2api/backend/internal/domain/account"
"github.com/chenyme/grok2api/backend/internal/infra/provider"
"github.com/chenyme/grok2api/backend/internal/infra/provider/conversation"
"github.com/chenyme/grok2api/backend/internal/infra/security"
)
@@ -211,6 +212,109 @@ func TestForwardResponseEmulatesRemoteCompactionV2(t *testing.T) {
}
}
// TestGatewayCompactionLifecycleWithMillionTokenScaleHistory 验证超长历史压缩后,
// 下一轮只会向上游发送解密出的摘要和新消息,不会重新发送原始历史或 opaque blob。
func TestGatewayCompactionLifecycleWithMillionTokenScaleHistory(t *testing.T) {
adapter, encrypted := newCompactionTestAdapter(t)
// “x ”在常见 BPE 编码中接近一个 token;此处保守构造超过 1M token 量级的历史文本。
history := strings.Repeat("x ", 2<<20)
summary := healthyCompactionSummary()
continuation := gatewayCompactionContinuation(summary)
encodedSummary, err := json.Marshal(continuation)
if err != nil {
t.Fatal(err)
}
var calls atomic.Int32
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
call := calls.Add(1)
data, readErr := io.ReadAll(request.Body)
if readErr != nil {
t.Fatal(readErr)
}
switch call {
case 1:
if len(data) < 4<<20 || strings.Contains(string(data), "compaction_trigger") {
t.Fatalf("压缩采样未携带完整超长历史:size=%d", len(data))
}
return sseResponse(http.StatusOK, compactionSampleSSE("resp_million", summary), request), nil
case 2:
if len(data) >= 4096 || strings.Contains(string(data), `"type":"compaction"`) || strings.Contains(string(data), `"encrypted_content"`) || !strings.Contains(string(data), string(encodedSummary)) || !strings.Contains(string(data), "压缩后继续执行") {
t.Fatalf("压缩回放泄漏原始状态:size=%d", len(data))
}
return jsonHTTPResponse(request, http.StatusOK, `{"id":"resp_continue","status":"completed","output":[]}`), nil
default:
t.Fatalf("unexpected call %d", call)
return nil, nil
}
})
initialBody, err := json.Marshal(map[string]any{
"model": "grok-4.5",
"input": []any{
map[string]any{"type": "message", "role": "user", "content": history},
map[string]any{"type": "compaction_trigger"},
},
})
if err != nil {
t.Fatal(err)
}
compacted, err := adapter.ForwardResponse(t.Context(), provider.ResponseResourceRequest{
Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted},
Method: http.MethodPost,
Path: "/responses",
Model: "grok-4.5",
PromptCacheKey: "million-token-session",
Body: initialBody,
NormalizeBody: true,
Operation: conversation.OperationResponses,
})
if err != nil {
t.Fatal(err)
}
compactedBody, readErr := io.ReadAll(compacted.Body)
_ = compacted.Body.Close()
if readErr != nil {
t.Fatal(readErr)
}
var compactedPayload struct {
Output []struct {
Type string `json:"type"`
EncryptedContent string `json:"encrypted_content"`
} `json:"output"`
}
if json.Unmarshal(compactedBody, &compactedPayload) != nil || len(compactedPayload.Output) != 1 || compactedPayload.Output[0].Type != "compaction" || compactedPayload.Output[0].EncryptedContent == "" {
t.Fatalf("压缩响应无有效 blob:%s", compactedBody)
}
continuedBody, err := json.Marshal(map[string]any{
"model": "grok-4.5",
"input": []any{
map[string]any{"type": "compaction", "encrypted_content": compactedPayload.Output[0].EncryptedContent},
map[string]any{"type": "message", "role": "user", "content": "压缩后继续执行"},
},
})
if err != nil {
t.Fatal(err)
}
continued, err := adapter.ForwardResponse(t.Context(), provider.ResponseResourceRequest{
Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted},
Method: http.MethodPost,
Path: "/responses",
Model: "grok-4.5",
PromptCacheKey: "million-token-session",
Body: continuedBody,
NormalizeBody: true,
Operation: conversation.OperationResponses,
})
if err != nil {
t.Fatal(err)
}
defer continued.Body.Close()
if calls.Load() != 2 || continued.StatusCode != http.StatusOK {
t.Fatalf("calls=%d status=%d", calls.Load(), continued.StatusCode)
}
}
func TestCompactionRetriesDegenerateSamplesOnSameAccount(t *testing.T) {
adapter, encrypted := newCompactionTestAdapter(t)
var attempts atomic.Int32
@@ -96,6 +96,13 @@ func (a *Adapter) recoverReasoningDecodeFailure(
a.logReasoningRecovery(request, base, "encrypted_content", "recovered", retry.StatusCode, nil)
return retry, retryURL, reasoningRecoveryOutcome{encryptedContentDowngraded: true}
}
if retry.StatusCode == http.StatusTooManyRequests {
// 去除失效密文后得到的 429 是当前账号的真实上游状态。保留它,
// 让网关进行账号冷却和切换,不能回退成已无效的初始解码 400。
_ = original.Body.Close()
a.logReasoningRecovery(request, base, "encrypted_content", "rate_limited", retry.StatusCode, nil)
return retry, retryURL, reasoningRecoveryOutcome{encryptedContentDowngraded: true}
}
sameDecodeFailure, inspectErr := responseHasReasoningDecodeFailure(retry)
if inspectErr != nil || !sameDecodeFailure {
a.logReasoningRecovery(request, base, "encrypted_content", "retry_rejected", retry.StatusCode, inspectErr)
@@ -119,6 +126,16 @@ func (a *Adapter) recoverReasoningDecodeFailure(
a.logReasoningRecovery(request, base, "session_reset", "response_decode_failed", retry.StatusCode, err)
return original, requestURL, reasoningRecoveryOutcome{failed: true}
}
if retry.StatusCode == http.StatusTooManyRequests {
// 无状态恢复也可能命中当前账号的真实限流。与去密文恢复保持一致,
// 必须把 429 交回网关,才能执行账号冷却和候选账号切换。
_ = original.Body.Close()
a.logReasoningRecovery(request, base, "session_reset", "rate_limited", retry.StatusCode, nil)
return retry, retryURL, reasoningRecoveryOutcome{
encryptedContentDowngraded: encryptedChanged,
sessionReset: true,
}
}
if !isHTTPSuccess(retry.StatusCode) {
status := retry.StatusCode
_ = retry.Body.Close()
@@ -245,6 +245,152 @@ func TestRecoverReasoningDecodeFailureEscalatesFromOpaqueStripToSessionReset(t *
}
}
func TestRecoverReasoningDecodeFailurePreservesRateLimitAfterOpaqueStrip(t *testing.T) {
adapter, encrypted := newReasoningRecoveryTestAdapter(t)
var calls atomic.Int32
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
switch calls.Add(1) {
case 1:
return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`), nil
case 2:
data, _ := io.ReadAll(request.Body)
if strings.Contains(string(data), `"encrypted_content"`) {
t.Fatalf("rate-limit recovery body still contains encrypted content: %s", data)
}
return jsonHTTPResponse(request, http.StatusTooManyRequests, `{"error":{"message":"rate limited"}}`), nil
default:
t.Fatalf("unexpected call %d", calls.Load())
return nil, nil
}
})
response, err := adapter.ForwardResponse(t.Context(), provider.ResponseResourceRequest{
Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted},
Method: http.MethodPost, Path: "/responses", Model: "grok-4.5", PromptCacheKey: "session-1",
Body: []byte(`{"model":"grok-4.5","input":[{"type":"reasoning","summary":[],"encrypted_content":"opaque"},{"role":"user","content":"continue"}]}`),
})
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
body, _ := io.ReadAll(response.Body)
warnings := response.Header.Get("X-Grok2API-Compatibility-Warnings")
if calls.Load() != 2 || response.StatusCode != http.StatusTooManyRequests || !strings.Contains(string(body), "rate limited") || !strings.Contains(warnings, "reasoning_encrypted_content_downgraded") || strings.Contains(warnings, "reasoning_recovery_failed") {
t.Fatalf("calls=%d status=%d warnings=%q body=%s", calls.Load(), response.StatusCode, warnings, body)
}
}
func TestRecoverReasoningDecodeFailurePreservesRateLimitAfterSessionReset(t *testing.T) {
adapter, encrypted := newReasoningRecoveryTestAdapter(t)
var calls atomic.Int32
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
call := calls.Add(1)
data, _ := io.ReadAll(request.Body)
switch call {
case 1:
if !strings.Contains(string(data), `"encrypted_content":"opaque"`) || request.Header.Get("x-grok-session-id") == "" {
t.Fatalf("initial body=%s headers=%#v", data, request.Header)
}
case 2:
if strings.Contains(string(data), `"encrypted_content"`) || request.Header.Get("x-grok-session-id") == "" || !strings.Contains(string(data), `"prompt_cache_key":"session-1"`) {
t.Fatalf("opaque downgrade body=%s headers=%#v", data, request.Header)
}
case 3:
if strings.Contains(string(data), `"encrypted_content"`) || strings.Contains(string(data), `"prompt_cache_key"`) || request.Header.Get("x-grok-session-id") != "" || request.Header.Get("x-grok-conv-id") != "" {
t.Fatalf("session reset body=%s headers=%#v", data, request.Header)
}
response := jsonHTTPResponse(request, http.StatusTooManyRequests, `{"error":{"message":"rate limited after session reset"}}`)
response.Header.Set("Retry-After", "17")
return response, nil
default:
t.Fatalf("unexpected call %d", call)
return nil, nil
}
return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`), nil
})
response, err := adapter.ForwardResponse(t.Context(), provider.ResponseResourceRequest{
Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted},
Method: http.MethodPost, Path: "/responses", Model: "grok-4.5", PromptCacheKey: "session-1",
Body: []byte(`{"model":"grok-4.5","input":[{"type":"reasoning","summary":[],"encrypted_content":"opaque"},{"role":"user","content":"continue"}]}`),
})
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
body, _ := io.ReadAll(response.Body)
warnings := response.Header.Get("X-Grok2API-Compatibility-Warnings")
if calls.Load() != 3 || response.StatusCode != http.StatusTooManyRequests || response.Header.Get("Retry-After") != "17" || !strings.Contains(string(body), "rate limited after session reset") {
t.Fatalf("calls=%d status=%d retry_after=%q body=%s", calls.Load(), response.StatusCode, response.Header.Get("Retry-After"), body)
}
if !strings.Contains(warnings, "reasoning_encrypted_content_downgraded") || !strings.Contains(warnings, "reasoning_session_reset") || strings.Contains(warnings, "reasoning_recovery_failed") {
t.Fatalf("warnings=%q", warnings)
}
}
// TestRecoverReasoningDecodeFailureWithMillionTokenScaleCompactionBlob 覆盖 Claude Code
// 在超长上下文压缩后回放大体积 opaque 状态、且上游拒绝该状态的恢复路径。
func TestRecoverReasoningDecodeFailureWithMillionTokenScaleCompactionBlob(t *testing.T) {
adapter, encrypted := newReasoningRecoveryTestAdapter(t)
// 按常用的约 4 字节/token 估算,4 MiB 的 opaque 状态覆盖约 100 万 token 的量级。
compactionBlob := strings.Repeat("x", 4<<20)
body, err := json.Marshal(map[string]any{
"model": "grok-4.5",
"input": []any{
map[string]any{
"type": "reasoning",
"summary": []any{},
"encrypted_content": compactionBlob,
},
map[string]any{"role": "user", "content": "压缩后继续执行"},
},
})
if err != nil {
t.Fatal(err)
}
var calls atomic.Int32
adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) {
call := calls.Add(1)
data, readErr := io.ReadAll(request.Body)
if readErr != nil {
t.Fatal(readErr)
}
switch call {
case 1:
if len(data) < 4<<20 || !strings.Contains(string(data), `"encrypted_content"`) {
t.Fatalf("初始 1M 级 compaction 请求不完整:size=%d", len(data))
}
return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`), nil
case 2:
if len(data) >= 4096 || strings.Contains(string(data), `"encrypted_content"`) || !strings.Contains(string(data), "压缩后继续执行") {
t.Fatalf("恢复请求仍携带 opaque 状态:size=%d", len(data))
}
return jsonHTTPResponse(request, http.StatusTooManyRequests, `{"error":{"message":"rate limited after compaction recovery"}}`), nil
default:
t.Fatalf("unexpected call %d", call)
return nil, nil
}
})
response, err := adapter.ForwardResponse(t.Context(), provider.ResponseResourceRequest{
Credential: account.Credential{ID: 1, Provider: account.ProviderBuild, EncryptedAccessToken: encrypted},
Method: http.MethodPost,
Path: "/responses",
Model: "grok-4.5",
PromptCacheKey: "million-token-session",
Body: body,
})
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
responseBody, _ := io.ReadAll(response.Body)
warnings := response.Header.Get("X-Grok2API-Compatibility-Warnings")
if calls.Load() != 2 || response.StatusCode != http.StatusTooManyRequests || !strings.Contains(string(responseBody), "rate limited after compaction recovery") || !strings.Contains(warnings, "reasoning_encrypted_content_downgraded") {
t.Fatalf("calls=%d status=%d warnings=%q body=%s", calls.Load(), response.StatusCode, warnings, responseBody)
}
}
func TestRecoverReasoningDecodeFailureDoesNotResetStoredResponseChain(t *testing.T) {
adapter, encrypted := newReasoningRecoveryTestAdapter(t)
var calls atomic.Int32
@@ -0,0 +1,299 @@
package cli
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"strings"
)
// buildXSearchResponseFilter hides internal custom_tool_call items emitted while xAI executes native x_search.
// The upstream has already completed them, so Codex and Claude Code must not execute them again.
type buildXSearchResponseFilter struct {
clientTools map[string]struct{}
injectedToolTypes map[string]struct{}
droppedOutputIndexes map[int]struct{}
droppedItemIDs map[string]struct{}
}
func newBuildXSearchResponseFilter(route buildPromptCacheRoute) *buildXSearchResponseFilter {
return &buildXSearchResponseFilter{
clientTools: route.clientDeclaredTools,
injectedToolTypes: route.injectedToolTypes,
droppedOutputIndexes: make(map[int]struct{}),
droppedItemIDs: make(map[string]struct{}),
}
}
func filterBuildPromptCacheResponse(response *http.Response, streaming bool, route buildPromptCacheRoute) error {
if response == nil || response.Body == nil || (!route.filterXSearch && len(route.injectedToolTypes) == 0) {
return nil
}
filter := newBuildXSearchResponseFilter(route)
if streaming {
response.Body = filter.stream(response.Body)
response.Header.Del("Content-Length")
response.ContentLength = -1
return nil
}
source := response.Body
data, err := io.ReadAll(io.LimitReader(source, maxCompatibleResponseBytes+1))
_ = source.Close()
if err != nil {
return err
}
if len(data) > maxCompatibleResponseBytes {
return fmt.Errorf("Grok Build Responses 响应超过 %d MiB", maxCompatibleResponseBytes>>20)
}
filtered, err := filter.filterJSON(data)
if err != nil {
return err
}
response.Body = io.NopCloser(bytes.NewReader(filtered))
response.Header.Set("Content-Length", strconv.Itoa(len(filtered)))
response.ContentLength = int64(len(filtered))
return nil
}
func (f *buildXSearchResponseFilter) stream(source io.ReadCloser) io.ReadCloser {
reader, writer := io.Pipe()
go func() {
defer source.Close()
err := consumeCompatibleSSE(source, func(event compatibleSSEEvent) error {
if !event.HasData() {
return event.writeTo(writer)
}
data := event.Data()
if bytes.Equal(bytes.TrimSpace(data), []byte("[DONE]")) {
return event.writeTo(writer)
}
filtered, keep, filterErr := f.filterEvent(data)
if filterErr != nil {
return filterErr
}
if !keep {
return nil
}
event.SetData(filtered)
return event.writeTo(writer)
})
_ = writer.CloseWithError(err)
}()
return reader
}
func (f *buildXSearchResponseFilter) filterJSON(body []byte) ([]byte, error) {
var payload map[string]json.RawMessage
if err := json.Unmarshal(body, &payload); err != nil {
return nil, fmt.Errorf("解析 Grok Build Responses 响应: %w", err)
}
if err := f.filterEnvelope(payload); err != nil {
return nil, err
}
filtered, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("编码 Grok Build Responses 响应: %w", err)
}
return filtered, nil
}
func (f *buildXSearchResponseFilter) filterEvent(data []byte) ([]byte, bool, error) {
var payload map[string]json.RawMessage
if err := json.Unmarshal(data, &payload); err != nil {
return data, true, nil
}
if item := payload["item"]; !isEmptyJSON(item) && f.isInternalCall(item) {
f.recordDroppedItem(payload, item)
return nil, false, nil
}
if err := f.filterEnvelope(payload); err != nil {
return nil, false, err
}
if f.referencesDroppedItem(payload) {
return nil, false, nil
}
f.compactOutputIndex(payload)
filtered, err := json.Marshal(payload)
if err != nil {
return nil, false, err
}
return filtered, true, nil
}
func (f *buildXSearchResponseFilter) filterEnvelope(payload map[string]json.RawMessage) error {
if err := f.filterOutput(payload); err != nil {
return err
}
if err := f.filterTools(payload); err != nil {
return err
}
if raw := payload["response"]; !isEmptyJSON(raw) {
var response map[string]json.RawMessage
if json.Unmarshal(raw, &response) == nil && response != nil {
if err := f.filterOutput(response); err != nil {
return err
}
if err := f.filterTools(response); err != nil {
return err
}
payload["response"] = mustJSON(response)
}
}
return nil
}
func (f *buildXSearchResponseFilter) filterOutput(envelope map[string]json.RawMessage) error {
raw := envelope["output"]
if isEmptyJSON(raw) {
return nil
}
var output []json.RawMessage
if json.Unmarshal(raw, &output) != nil {
return fmt.Errorf("解析 Grok Build Responses output 失败")
}
filtered := make([]json.RawMessage, 0, len(output))
for _, rawItem := range output {
if f.isInternalCall(rawItem) {
continue
}
filtered = append(filtered, rawItem)
}
envelope["output"] = mustJSON(filtered)
return nil
}
func (f *buildXSearchResponseFilter) filterTools(envelope map[string]json.RawMessage) error {
if len(f.injectedToolTypes) == 0 {
return nil
}
raw := envelope["tools"]
if isEmptyJSON(raw) {
return nil
}
var tools []json.RawMessage
if json.Unmarshal(raw, &tools) != nil {
return fmt.Errorf("解析 Grok Build Responses tools 失败")
}
filtered := make([]json.RawMessage, 0, len(tools))
for _, rawTool := range tools {
kind, _ := buildCacheToolIdentity(rawTool)
if _, injected := f.injectedToolTypes[kind]; injected {
continue
}
filtered = append(filtered, rawTool)
}
if len(filtered) == 0 {
delete(envelope, "tools")
return nil
}
envelope["tools"] = mustJSON(filtered)
return nil
}
type buildXSearchResponseItem struct {
Type string `json:"type"`
ID string `json:"id"`
CallID string `json:"call_id"`
Name string `json:"name"`
Namespace string `json:"namespace"`
}
func (f *buildXSearchResponseFilter) isInternalCall(raw json.RawMessage) bool {
var item buildXSearchResponseItem
if json.Unmarshal(raw, &item) != nil {
return false
}
kind := strings.TrimSpace(item.Type)
if kind == "web_search_call" {
_, injected := f.injectedToolTypes["web_search"]
return injected
}
if kind != "custom_tool_call" && kind != "function_call" {
return false
}
callID := strings.TrimSpace(item.CallID)
if strings.HasPrefix(callID, "xs_call") {
return true
}
name := strings.TrimSpace(item.Name)
if !isBuildInternalXSearchToolName(name) || strings.TrimSpace(item.Namespace) != "" {
return false
}
if _, declared := f.clientTools[name]; declared {
return false
}
return true
}
func isBuildInternalXSearchToolName(name string) bool {
switch strings.TrimSpace(name) {
case "x_user_search", "x_semantic_search", "x_keyword_search", "x_thread_fetch":
return true
default:
return false
}
}
func (f *buildXSearchResponseFilter) recordDroppedItem(payload map[string]json.RawMessage, rawItem json.RawMessage) {
if index, ok := rawJSONInt(payload["output_index"]); ok {
f.droppedOutputIndexes[index] = struct{}{}
}
var item buildXSearchResponseItem
if json.Unmarshal(rawItem, &item) != nil {
return
}
for _, value := range []string{item.ID, item.CallID} {
if value = strings.TrimSpace(value); value != "" {
f.droppedItemIDs[value] = struct{}{}
}
}
}
func (f *buildXSearchResponseFilter) referencesDroppedItem(payload map[string]json.RawMessage) bool {
if index, ok := rawJSONInt(payload["output_index"]); ok {
if _, dropped := f.droppedOutputIndexes[index]; dropped {
return true
}
}
for _, name := range []string{"item_id", "call_id"} {
if value := strings.TrimSpace(rawJSONString(payload[name])); value != "" {
if _, dropped := f.droppedItemIDs[value]; dropped {
return true
}
}
}
return false
}
func (f *buildXSearchResponseFilter) compactOutputIndex(payload map[string]json.RawMessage) {
index, ok := rawJSONInt(payload["output_index"])
if !ok {
return
}
removedBefore := 0
for dropped := range f.droppedOutputIndexes {
if dropped < index {
removedBefore++
}
}
if removedBefore > 0 {
payload["output_index"] = mustJSON(index - removedBefore)
}
}
func rawJSONInt(raw json.RawMessage) (int, bool) {
if isEmptyJSON(raw) {
return 0, false
}
parsed, err := strconv.Atoi(string(bytes.TrimSpace(raw)))
return parsed, err == nil
}
func rawJSONString(raw json.RawMessage) string {
var value string
_ = json.Unmarshal(raw, &value)
return value
}
@@ -6,7 +6,7 @@ import (
"github.com/chenyme/grok2api/backend/internal/infra/provider"
)
// Definition 集中声明 Grok Console 的稳定能力边界;Console 保持无状态 Responses 语义。
// Definition declares the stable Grok Console capability boundary; Console retains stateless Responses semantics.
func (a *Adapter) Definition() provider.Definition {
return provider.Definition{
Provider: account.ProviderConsole,
@@ -20,7 +20,7 @@ func (a *Adapter) Definition() provider.Definition {
Conversation: provider.ConversationSurface{
Responses: true, ChatCompletions: true, Messages: true,
},
// Console shares the browser/clearance surface with Web. A 403 is
// Console shares the browser/clearance surface with Web. A 403 is
// therefore normally an egress challenge, not proof that the SSO
// credential is invalid; the gateway must retry after rebuilding the
// browser session instead of cooling the account.
@@ -26,9 +26,8 @@ func normalizeRequest(body []byte, spec ModelSpec) ([]byte, error) {
return nil, fmt.Errorf("解析 Console Responses 请求: %w", err)
}
payload["model"] = spec.UpstreamModel
// Console is stateless. Match the reference adapter's compatibility
// boundary: replay the supplied input and silently discard stateful client
// hints instead of rejecting an otherwise valid request.
// Console is stateless. Replay the supplied input and silently discard
// stateful client hints instead of rejecting an otherwise valid request.
payload["store"] = false
for _, field := range []string{
"metadata", "previous_response_id", "service_tier", "prompt_cache_key",
@@ -232,6 +232,31 @@ func TestConvertAnthropicMessagesRequestToResponses(t *testing.T) {
}
}
func TestConvertAnthropicMessagesDropsClaudeCodeBillingAttribution(t *testing.T) {
body := []byte(`{
"model":"claude","max_tokens":128,
"system":[
{"type":"text","text":"x-anthropic-billing-header: cc_version=2.1.170.abc; cc_entrypoint=sdk-cli; cch=12345;"},
{"type":"text","text":"stable system instruction","cache_control":{"type":"ephemeral"}}
],
"messages":[{"role":"user","content":"hello"}]
}`)
converted, err := ConvertRequest(body, "grok-4.5", OperationMessages)
if err != nil {
t.Fatal(err)
}
var payload map[string]any
if err := json.Unmarshal(converted, &payload); err != nil {
t.Fatal(err)
}
if payload["instructions"] != "stable system instruction" {
t.Fatalf("instructions = %#v", payload["instructions"])
}
if strings.Contains(string(converted), anthropicBillingHeaderPrefix) {
t.Fatalf("billing attribution leaked into Build request: %s", converted)
}
}
func TestConvertAnthropicMessagesInlineSystemRole(t *testing.T) {
body := []byte(`{
"model":"public-chat","max_tokens":1024,
@@ -7,6 +7,8 @@ import (
"strings"
)
const anthropicBillingHeaderPrefix = "x-anthropic-billing-header: "
func convertMessagesRequest(body []byte, model string) ([]byte, ResponseOptions, error) {
var request anthropicRequest
if err := json.Unmarshal(body, &request); err != nil {
@@ -308,9 +310,8 @@ func convertAnthropicMessages(messages []anthropicMessage, declaredTools map[str
if json.Unmarshal(block["data"], &data) != nil || data == "" {
return nil, nil, fmt.Errorf("%s.data 无效", path)
}
// Grok Build / XAI requires the reasoning summary field to exist
// whenever encrypted_content is replayed. An empty summary is the
// canonical carrier for Anthropic redacted_thinking.
// Grok Build requires summary to exist whenever encrypted_content is replayed.
// An empty array is the canonical Anthropic redacted_thinking representation.
input = append(input, map[string]any{"type": "reasoning", "summary": []any{}, "encrypted_content": data})
case "server_tool_use":
if role != "assistant" {
@@ -389,6 +390,9 @@ func anthropicSystemText(raw json.RawMessage) (string, error) {
}
var text string
if json.Unmarshal(raw, &text) == nil {
if isAnthropicBillingHeaderText(text) {
return "", nil
}
return text, nil
}
var blocks []struct {
@@ -403,11 +407,20 @@ func anthropicSystemText(raw json.RawMessage) (string, error) {
if block.Type != "text" {
return "", fmt.Errorf("system 不支持 type=%q", block.Type)
}
// Claude Code identity blocks may carry a per-request cch fingerprint and are not model instructions.
// Keeping them during Build conversion changes the cache prefix each turn and reduces cache hits.
if isAnthropicBillingHeaderText(block.Text) {
continue
}
parts = append(parts, block.Text)
}
return strings.Join(parts, "\n\n"), nil
}
func isAnthropicBillingHeaderText(text string) bool {
return strings.HasPrefix(strings.TrimLeft(text, " \t\r\n"), anthropicBillingHeaderPrefix)
}
func anthropicImageURL(raw json.RawMessage) (string, error) {
var source struct {
Type string `json:"type"`
@@ -519,8 +532,8 @@ func anthropicToolResult(raw json.RawMessage, declaredTools map[string]struct{})
if _, exists := declaredTools[toolName]; !exists {
return nil, fmt.Errorf("tool_reference 引用了未声明的工具 %q", toolName)
}
// Responses 没有 Anthropic tool_reference 内容块。Messages 请求中的全部
// 工具定义已发送给上游,因此用确定性的结果文本保留“搜索命中”语义。
// Responses has no Anthropic tool_reference content block. All tool definitions from Messages
// have already been sent upstream, so deterministic result text preserves the search-hit meaning.
parts = append(parts, map[string]any{
"type": "input_text",
"text": fmt.Sprintf("Tool search matched declared tool %q; its definition is available in this request.", toolName),
@@ -694,11 +707,11 @@ func convertAnthropicWebSearchTool(tool map[string]json.RawMessage, index int) (
}
converted["filters"] = map[string]any{"allowed_domains": value}
case "max_uses", "blocked_domains", "user_location", "search_context_size":
// Build 0.2.106 只支持 allowed_domains;其余 Anthropic
// 可选控制字段不转发,避免上游因未知参数拒绝整个请求。
// Build 0.2.106 supports only allowed_domains. Do not forward other optional Anthropic controls,
// preventing unknown parameters from causing the upstream to reject the request.
continue
default:
// 对未来新增的 hosted-tool 可选字段保持向前兼容。
// Preserve forward compatibility with future hosted-tool optional fields.
continue
}
}
@@ -750,8 +763,8 @@ func convertAnthropicToolChoice(choice anthropicToolChoice, hasHostedWebSearch b
if strings.TrimSpace(choice.Name) == "" {
return nil, false, errors.New("tool_choice.tool 缺少 name")
}
// Claude Code secondary search forces name=web_search (hosted). Build accepts
// hosted tool_choice only as "required" when a single hosted tool remains.
// Claude Code secondary search uses a hosted tool with name=web_search.
// When only one hosted tool remains, Grok Build accepts only required tool_choice.
if hasHostedWebSearch && strings.EqualFold(strings.TrimSpace(choice.Name), "web_search") {
return "required", parallel, nil
}
+54 -51
View File
@@ -22,13 +22,13 @@ var (
ErrBirthDateAlreadySet = errors.New("upstream birth date is already set")
)
// HTTPStatusError 允许流式或异步 Provider 在无法返回 Response 时保留上游状态码。
// HTTPStatusError preserves the upstream status when a streaming or asynchronous Provider cannot return a Response.
type HTTPStatusError interface {
error
HTTPStatusCode() int
}
// ErrorHTTPStatus 从 Provider 错误链中提取上游 HTTP 状态。
// ErrorHTTPStatus extracts the upstream HTTP status from a Provider error chain.
func ErrorHTTPStatus(err error) (int, bool) {
var statusError HTTPStatusError
if !errors.As(err, &statusError) {
@@ -38,7 +38,7 @@ func ErrorHTTPStatus(err error) (int, bool) {
return status, status > 0
}
// MediaPostProcessingStage 标识媒体已经生成后失败的本地处理阶段。
// MediaPostProcessingStage identifies a local processing stage that failed after media generation.
type MediaPostProcessingStage string
const (
@@ -46,8 +46,8 @@ const (
MediaPostProcessingStorage MediaPostProcessingStage = "storage"
)
// MediaPostProcessingError 表示上游媒体已经产生,后续下载或保存失败。
// 此类错误不得触发换号重新生成,也不应降低生成账号的健康度。
// MediaPostProcessingError indicates that upstream media was created but download or storage failed.
// These errors must not trigger generation on another account or reduce the generating account's health.
type MediaPostProcessingError struct {
Stage MediaPostProcessingStage
Cause error
@@ -67,7 +67,7 @@ func (e *MediaPostProcessingError) Unwrap() error {
return e.Cause
}
// NewMediaPostProcessingError 将下载或保存错误标记为不可跨账号重试。
// NewMediaPostProcessingError marks a download or storage error as non-retryable across accounts.
func NewMediaPostProcessingError(stage MediaPostProcessingStage, cause error) error {
if cause == nil {
return nil
@@ -75,13 +75,13 @@ func NewMediaPostProcessingError(stage MediaPostProcessingStage, cause error) er
return &MediaPostProcessingError{Stage: stage, Cause: cause}
}
// IsMediaPostProcessingError 判断错误是否发生在媒体生成后的本地处理阶段。
// IsMediaPostProcessingError reports whether an error occurred during local processing after media generation.
func IsMediaPostProcessingError(err error) bool {
var target *MediaPostProcessingError
return errors.As(err, &target)
}
// CredentialRefreshError 区分需要重新认证的永久 OAuth 错误与可后台退避重试的临时错误。
// CredentialRefreshError distinguishes permanent OAuth errors requiring reauthorization from temporary errors that can retry with backoff.
type CredentialRefreshError struct {
Status int
Code string
@@ -110,19 +110,22 @@ func (e *CredentialRefreshError) Unwrap() error {
return e.Cause
}
// ResponseResourceRequest 表示对 Responses 资源端点的通用上游请求。
// ResponseResourceRequest describes a common upstream request to a Responses resource endpoint.
type ResponseResourceRequest struct {
Credential account.Credential
// Billing 仅用于 Build auto 模式的 XAI 资格判断;nil 表示账号等级尚未确认。
// Billing is used only to determine XAI eligibility in Build auto mode; nil means the account tier is unknown.
Billing *account.Billing
Method string
Path string
Body []byte
Model string
PromptCacheKey string
// ReasoningReplayKey 只来自客户端显式会话身份;soft cache identity 不得用于密文回放。
// ReasoningReplayKey comes only from explicit client session identity; soft cache identity must not replay ciphertext.
ReasoningReplayKey string
// GrokTurnIndex 是客户端显式提供的 Grok Shell 用户轮次;Build 出站前会校验,禁止服务端伪造。
// AllowClientToolCacheRoute allows the Build native cache route to supplement existing client tools.
// This is a protocol compatibility signal, not a client authentication result.
AllowClientToolCacheRoute bool
// GrokTurnIndex is the explicit Grok Shell client turn; it is validated before Build egress and never fabricated by the server.
GrokTurnIndex string
IdempotencyID string
Streaming bool
@@ -130,7 +133,7 @@ type ResponseResourceRequest struct {
Operation string
}
// Response 表示尚未写入下游的上游响应。
// Response represents an upstream response that has not yet been written downstream.
type Response struct {
StatusCode int
Status string
@@ -140,8 +143,8 @@ type Response struct {
UpstreamURL string
Diagnostic *DiagnosticResponse
RateLimit *RateLimitMetadata
// ModelCatalogChanged 表示上游推理响应中的模型目录 ETag 与该账号
// 最近一次成功 /models 同步的 ETag 不一致。
// ModelCatalogChanged indicates that the model catalog ETag in an inference response differs from
// the ETag from the account's most recent successful /models sync.
ModelCatalogChanged bool
}
@@ -150,7 +153,7 @@ const (
RateLimitScopeRPM = "rpm"
)
// RateLimitMetadata 表示上游返回的可安全传播的瞬时限流元数据。
// RateLimitMetadata contains transient rate-limit metadata that is safe to propagate from upstream.
type RateLimitMetadata struct {
Scope string
TeamID string
@@ -162,7 +165,7 @@ type RateLimitMetadata struct {
const MaxDiagnosticBodyBytes = 64 << 10
// DiagnosticResponse 保留 Provider 转换前经过容量限制的失败响应。
// DiagnosticResponse retains a size-limited failure response before Provider conversion.
type DiagnosticResponse struct {
StatusCode int
Status string
@@ -171,7 +174,7 @@ type DiagnosticResponse struct {
BodyTruncated bool
}
// ReadDiagnosticBody 最多读取诊断正文上限,并报告上游是否还有未保留内容。
// ReadDiagnosticBody reads up to the diagnostic body limit and reports whether upstream content was truncated.
func ReadDiagnosticBody(body io.Reader) ([]byte, bool, error) {
if body == nil {
return nil, false, nil
@@ -183,7 +186,7 @@ func ReadDiagnosticBody(body io.Reader) ([]byte, bool, error) {
return data[:MaxDiagnosticBodyBytes], true, err
}
// DeviceAuthorization 表示 Device OAuth 启动结果。
// DeviceAuthorization represents the result of starting Device OAuth.
type DeviceAuthorization struct {
DeviceCode string
UserCode string
@@ -193,7 +196,7 @@ type DeviceAuthorization struct {
ExpiresIn time.Duration
}
// CredentialSeed 表示登录或导入后尚未持久化的 OAuth 凭据。
// CredentialSeed represents an OAuth credential not yet persisted after login or import.
type CredentialSeed struct {
Provider account.Provider
AuthType account.AuthType
@@ -255,9 +258,9 @@ type ImageEditRequest struct {
type VideoRequest struct {
Credential account.Credential
// Billing 仅用于 Build auto 模式的 XAI 资格判断;nil 表示账号等级尚未确认。
// Billing is used only to determine XAI eligibility in Build auto mode; nil means the account tier is unknown.
Billing *account.Billing
// JobID 绑定本地视频任务,供 XAI ZDR 上传票据与结果资产关联。
// JobID binds the local video job to XAI ZDR upload tickets and result assets.
JobID string
Prompt string
Duration int
@@ -270,18 +273,18 @@ type VideoRequest struct {
type VideoResult struct {
URL string
ContentType string
// AssetID 非空时表示结果已写入本地媒体资产,内容读取应走 MediaObjectStorage。
// A non-empty AssetID means the result is stored as a local media asset; content reads must use MediaObjectStorage.
AssetID string
}
// RefreshedCredential 表示 OAuth 刷新后的旋转凭据。
// RefreshedCredential represents rotated credentials returned by an OAuth refresh.
type RefreshedCredential struct {
EncryptedAccessToken string
EncryptedRefreshToken string
ExpiresAt time.Time
}
// Adapter 只定义 Provider 身份;具体能力通过小接口按需注册。
// Adapter defines only Provider identity; concrete capabilities are registered through small interfaces as needed.
type Adapter interface {
Provider() account.Provider
}
@@ -296,9 +299,9 @@ type ModelCatalogAdapter interface {
ListModels(ctx context.Context, credential account.Credential) ([]string, error)
}
// AccountModelCapabilityNormalizer 可选:按 Billing 与 credential entitlement 归一化账号模型能力。
// 未实现时模型同步原样写入上游目录;billing 为 nil 表示 Unknown(无快照)。
// credential 用于 Build Super entitlement;默认 Provider 可忽略。
// AccountModelCapabilityNormalizer is optional and normalizes account model capabilities from Billing and credential entitlement.
// Without it, model sync writes the upstream catalog unchanged; nil billing means Unknown with no snapshot.
// credential is used for Build Super entitlement; default Providers may ignore it.
type AccountModelCapabilityNormalizer interface {
Adapter
NormalizeAccountModelCapabilities(models []string, billing *account.Billing, credential account.Credential) []string
@@ -326,8 +329,8 @@ type CredentialCodecAdapter interface {
MarshalCredentials(values []CredentialSeed) ([]byte, error)
}
// CredentialMetadata 是从已保存凭据安全派生的非敏感展示信息。
// 原始 token 和完整 JWT claims 不得通过该结构暴露。
// CredentialMetadata contains non-sensitive display data safely derived from a stored credential.
// Raw tokens and complete JWT claims must never be exposed through this structure.
type CredentialMetadata struct {
BuildBotFlagged bool
}
@@ -337,8 +340,8 @@ type CredentialMetadataAdapter interface {
CredentialMetadata(credential account.Credential) CredentialMetadata
}
// AccountIdentity 是上游确认的非敏感账号身份元数据。
// Email 只用于展示;跨 Provider 自动关联仅使用稳定 UserID。
// AccountIdentity contains non-sensitive account identity metadata confirmed by upstream.
// Email is for display only; cross-Provider automatic linking uses stable UserID only.
type AccountIdentity struct {
Email string
UserID string
@@ -361,8 +364,8 @@ type QuotaAdapter interface {
SyncQuotaMode(ctx context.Context, credential account.Credential, mode string) (account.QuotaWindow, error)
}
// WebAccountSettingsAdapter 定义 Grok Web SSO 账号的上游资料设置能力。
// 该能力只属于 Web Provider;Build 与 Console 不应通过通用账号逻辑模拟实现。
// WebAccountSettingsAdapter defines upstream profile-setting capabilities for Grok Web SSO accounts.
// This capability belongs only to the Web Provider; Build and Console must not emulate it through generic account logic.
type WebAccountSettingsAdapter interface {
Adapter
AcceptTerms(ctx context.Context, credential account.Credential) error
@@ -370,19 +373,19 @@ type WebAccountSettingsAdapter interface {
EnableNSFW(ctx context.Context, credential account.Credential) error
}
// ImageGenerationAdapter 定义 Provider 可选的图片生成能力。
// ImageGenerationAdapter defines an optional Provider image-generation capability.
type ImageGenerationAdapter interface {
Adapter
GenerateImage(ctx context.Context, request ImageGenerationRequest) (*Response, error)
}
// ImageEditAdapter 定义 Provider 可选的图片编辑能力。
// ImageEditAdapter defines an optional Provider image-editing capability.
type ImageEditAdapter interface {
Adapter
EditImage(ctx context.Context, request ImageEditRequest) (*Response, error)
}
// ImageAssetStore 将生成图片归档为可由后端稳定读取的本地资源。
// ImageAssetStore archives generated images as local resources that the backend can read reliably.
type ImageAssetStore interface {
SaveImage(ctx context.Context, data []byte) (media.Asset, error)
PublicImageURL(id string) string
@@ -393,8 +396,8 @@ type VideoAdapter interface {
GenerateVideo(ctx context.Context, request VideoRequest) (VideoResult, error)
}
// VideoContentDownloader streams a completed provider video using the
// credential that created the job. Callers must enforce job ownership first.
// VideoContentDownloader reads completed video content using the credential that created the task.
// Callers must verify task ownership first.
type VideoContentDownloader interface {
VideoAdapter
DownloadVideo(ctx context.Context, credential account.Credential, rawURL string) (io.ReadCloser, string, int64, error)
@@ -406,7 +409,7 @@ type RoutingMetadataAdapter interface {
TierOrder(upstreamModel string) []account.WebTier
}
// ModelAlias 将隐藏兼容模型名解析到唯一公开路由,并可固定推理强度。
// ModelAlias resolves a hidden compatibility model name to one public route and can fix reasoning effort.
type ModelAlias struct {
Alias string
PublicModel string
@@ -420,13 +423,13 @@ type ModelAliasAdapter interface {
ModelAliases() []ModelAlias
}
// PricingMetadataAdapter 将 Provider 私有模型标识映射到公开计费模型。
// PricingMetadataAdapter maps Provider-private model identifiers to public billing models.
type PricingMetadataAdapter interface {
Adapter
PricingModel(upstreamModel string) string
}
// Registry 保存已启用 Provider Adapter,不创建未实现来源的占位对象。
// Registry stores enabled Provider Adapters and does not create placeholders for unsupported sources.
type Registry struct {
adapters map[account.Provider]Adapter
definitions map[account.Provider]Definition
@@ -484,25 +487,25 @@ func NewRegistry(adapters ...Adapter) *Registry {
return registry
}
// Get 返回已注册的 Provider Adapter。
// Get returns a registered Provider Adapter.
func (r *Registry) Get(value account.Provider) (Adapter, bool) {
adapter, ok := r.adapters[value]
return adapter, ok
}
// ResolveModelAlias 返回隐藏兼容模型名对应的规范内部路由。
// ResolveModelAlias returns the canonical internal route for a hidden compatibility model name.
func (r *Registry) ResolveModelAlias(value string) (ModelAlias, bool) {
result, ok := r.aliases[value]
return result, ok
}
// Definition 返回生产 Adapter 声明的稳定能力描述。
// Definition returns the stable capability declaration from a production Adapter.
func (r *Registry) Definition(value account.Provider) (Definition, bool) {
definition, ok := r.definitions[value]
return definition.Clone(), ok
}
// Providers 返回按固定渠道顺序注册且具备能力描述的 Provider。
// Providers returns registered Providers in fixed channel order with capability definitions.
func (r *Registry) Providers() []account.Provider {
values := make([]account.Provider, 0, len(r.definitions))
for _, value := range account.Providers() {
@@ -513,7 +516,7 @@ func (r *Registry) Providers() []account.Provider {
return values
}
// Validate 检查生产注册表的定义与实际小接口实现是否一致。
// Validate checks that production registry definitions match their implemented capability interfaces.
func (r *Registry) Validate() error {
if r == nil {
return errors.New("Provider Registry 不能为空")
@@ -680,7 +683,7 @@ func (r *Registry) CredentialCodec(value account.Provider) (CredentialCodecAdapt
return result, ok
}
// CredentialMetadata 返回账号凭据中可安全用于管理端展示的派生信息。
// CredentialMetadata returns derived credential metadata safe for admin display.
func (r *Registry) CredentialMetadata(credential account.Credential) CredentialMetadata {
if r == nil {
return CredentialMetadata{}
@@ -723,7 +726,7 @@ func (r *Registry) Quota(value account.Provider) (QuotaAdapter, bool) {
return result, ok
}
// WebAccountSettings 返回 Grok Web 专属的账号资料设置能力。
// WebAccountSettings returns the Grok Web-specific account profile settings capability.
func (r *Registry) WebAccountSettings() (WebAccountSettingsAdapter, bool) {
adapter, ok := r.Get(account.ProviderWeb)
if !ok {
@@ -772,7 +775,7 @@ func (r *Registry) PricingModel(value account.Provider, upstreamModel string) st
return upstreamModel
}
// ImageGeneration 返回 Provider 注册的图片生成能力。
// ImageGeneration returns the image-generation capability registered by the Provider.
func (r *Registry) ImageGeneration(value account.Provider) (ImageGenerationAdapter, bool) {
adapter, ok := r.Get(value)
if !ok {
@@ -782,7 +785,7 @@ func (r *Registry) ImageGeneration(value account.Provider) (ImageGenerationAdapt
return result, ok
}
// ImageEdit 返回 Provider 注册的图片编辑能力。
// ImageEdit returns the image-editing capability registered by the Provider.
func (r *Registry) ImageEdit(value account.Provider) (ImageEditAdapter, bool) {
adapter, ok := r.Get(value)
if !ok {
@@ -70,8 +70,8 @@ func NewHandler(gatewayService *gateway.Service, models *modelapp.Service, maxBo
return &Handler{gateway: gatewayService, models: models, maxBodyBytes: maxBodyBytes, publicAPIBaseURL: baseURL}
}
// SetPublicAPIBaseURLResolver 让视频内容 URL 跟随运行设置热更新。
// 应在 Register 前设置;请求处理期间只读取该函数。
// SetPublicAPIBaseURLResolver makes video content URLs follow hot-updated runtime settings.
// Set it before Register; request handling only reads the resolver.
func (h *Handler) SetPublicAPIBaseURLResolver(resolve func() string) *Handler {
h.publicBaseURL = resolve
return h
@@ -180,7 +180,7 @@ func (h *Handler) listModels(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"object": "list", "data": newModelListItems(values)})
}
// newModelListItems 按下游公开名称去重,隐藏仅用于内部选路的 Provider 前缀。
// newModelListItems deduplicates by downstream public name and hides Provider prefixes used only for internal routing.
func newModelListItems(values []modeldomain.Route) []modelListItem {
data := make([]modelListItem, 0, len(values))
seen := make(map[string]bool, len(values))
@@ -230,8 +230,9 @@ func (h *Handler) createChatCompletion(c *gin.Context) {
result, err := h.gateway.CreateChatCompletion(c.Request.Context(), gateway.Input{
RequestID: requestIDValue, ClientKey: clientKey, PublicModel: request.Model,
Body: body, Streaming: request.Stream, PromptCacheKey: request.PromptCacheKey,
PromptCacheSeed: extractPromptCacheSeed(c.Request.Header, body),
GrokTurnIndex: c.GetHeader("x-grok-turn-idx"),
PromptCacheSeed: extractPromptCacheSeed(c.Request.Header, body),
AllowClientToolCacheRoute: allowBuildClientToolCacheRoute(c.Request.Header),
GrokTurnIndex: c.GetHeader("x-grok-turn-idx"),
})
if err != nil {
writeGatewayError(c, err)
@@ -271,8 +272,9 @@ func (h *Handler) createMessage(c *gin.Context) {
result, err := h.gateway.CreateMessage(c.Request.Context(), gateway.Input{
RequestID: requestIDValue, ClientKey: clientKey, PublicModel: request.Model,
Body: body, Streaming: request.Stream, PromptCacheKey: request.PromptCacheKey,
PromptCacheSeed: extractPromptCacheSeed(c.Request.Header, body),
GrokTurnIndex: c.GetHeader("x-grok-turn-idx"),
PromptCacheSeed: extractPromptCacheSeed(c.Request.Header, body),
AllowClientToolCacheRoute: allowBuildClientToolCacheRoute(c.Request.Header),
GrokTurnIndex: c.GetHeader("x-grok-turn-idx"),
})
if err != nil {
writeGatewayAnthropicError(c, err)
@@ -818,7 +820,8 @@ func (h *Handler) handleCreate(c *gin.Context, compact bool) {
RequestID: requestIDValue, ClientKey: clientKey, PublicModel: request.Model,
Body: body, Streaming: request.Stream, PromptCacheKey: request.PromptCacheKey,
PromptCacheSeed: extractPromptCacheSeed(c.Request.Header, body), PreviousResponseID: request.PreviousResponseID,
GrokTurnIndex: c.GetHeader("x-grok-turn-idx"),
AllowClientToolCacheRoute: allowBuildClientToolCacheRoute(c.Request.Header),
GrokTurnIndex: c.GetHeader("x-grok-turn-idx"),
}
var result *gateway.Result
if compact {
@@ -1286,15 +1289,15 @@ type responseUsageDTO struct {
CostInUSDTicks int64 `json:"cost_in_usd_ticks"`
NumSourcesUsed int64 `json:"num_sources_used"`
NumServerSideToolsUsed int64 `json:"num_server_side_tools_used"`
// Responses 协议:input_tokens_details.cached_tokens
// Responses protocol: input_tokens_details.cached_tokens
InputTokensDetails responseInputDetailsDTO `json:"input_tokens_details"`
// OpenAI Chat Completions 协议:prompt_tokens_details.cached_tokens
// OpenAI Chat Completions protocol: prompt_tokens_details.cached_tokens
PromptTokensDetails responseInputDetailsDTO `json:"prompt_tokens_details"`
// Anthropic Messages 协议:顶层 cache_read_input_tokens
// Anthropic Messages protocol: top-level cache_read_input_tokens
CacheReadInputTokens int64 `json:"cache_read_input_tokens"`
CacheCreationInputTokens int64 `json:"cache_creation_input_tokens"`
OutputTokensDetails responseOutputDetailsDTO `json:"output_tokens_details"`
// OpenAI Chat Completions 协议:completion_tokens_details.reasoning_tokens
// OpenAI Chat Completions protocol: completion_tokens_details.reasoning_tokens
CompletionTokensDetails responseOutputDetailsDTO `json:"completion_tokens_details"`
ContextDetails responseContextDetailsDTO `json:"context_details"`
PromptTokens int64 `json:"prompt_tokens"`
@@ -1336,7 +1339,7 @@ func (value responseUsageDTO) toGatewayUsage(responseModel string) gateway.Usage
if total == 0 {
total = input + output
}
// 统一缓存命中:Responses / Chat Completions / Anthropic Messages
// Unified cache hits: Responses / Chat Completions / Anthropic Messages
cached := value.InputTokensDetails.CachedTokens
if cached == 0 {
cached = value.PromptTokensDetails.CachedTokens
@@ -1365,7 +1368,8 @@ func hasUsageSignal(usage gateway.Usage) bool {
usage.ContextInputTokens > 0 || usage.ContextOutputTokens > 0
}
// mergeGatewayUsage 合并流式多帧 usage:非零字段覆盖,避免后到半截帧抹掉已解析缓存命中。
// mergeGatewayUsage merges usage from multiple streaming frames; non-zero fields overwrite,
// preventing a later partial frame from erasing an already parsed cache hit.
func mergeGatewayUsage(base, next gateway.Usage) gateway.Usage {
if next.InputTokens > 0 {
base.InputTokens = next.InputTokens
@@ -6,19 +6,33 @@ import (
"strings"
)
const maxPromptCacheSeedBytes = 1024
const (
maxPromptCacheSeedBytes = 1024
maxCodexTurnMetadataSize = 16 << 10
)
// extractPromptCacheSeed 提取客户端会话标识;真正发往上游的 key 会在 Gateway 中隔离并哈希。
// 兼容 Claude Code / Codex / Sub2API(session_id、conversation_id、prompt_cache_key)。
// extractPromptCacheSeed extracts the client session identifier; the gateway isolates and hashes the key sent upstream.
// It supports Claude Code, Codex, and OpenAI-compatible session_id, conversation_id, and prompt_cache_key signals.
func extractPromptCacheSeed(headers http.Header, body []byte) string {
// Claude Code sends auxiliary requests such as title generation concurrently and reuses the main session ID.
// If an auxiliary request uses the explicit session seed, it shares reasoning replay with the main conversation.
// Falling back to soft identity preserves account affinity without allowing encrypted reasoning to leak across requests.
if isClaudeCodeTitleRequest(headers, body) {
return ""
}
if headers != nil {
// 优先级对齐 CPA + Sub2API 常用信号
// Prefer standard session signals from Claude Code, Codex, and OpenAI-compatible clients.
if seed := normalizePromptCacheSeed(headers.Get("X-Claude-Code-Session-Id")); seed != "" {
return claudeCodePromptCacheSeed(seed, headers)
}
if seed := codexPromptCacheSeedFromHeaders(headers); seed != "" {
return seed
}
for _, name := range []string{
"X-Claude-Code-Session-Id",
"X-Session-ID", "X-Session-Id", "Session-Id", "Session_id", "session_id",
"X-Conversation-Id", "Conversation-Id", "Conversation_id", "conversation_id",
// Sub2API / 反代偶发透传
"X-Client-Session-Id", "X-Grok-Conv-Id", "x-grok-conv-id",
"X-Session-Id", "Session-Id", "Session_id",
"X-Conversation-Id", "Conversation-Id", "Conversation_id",
// Support session signals forwarded by reverse proxies.
"X-Client-Session-Id", "X-Grok-Conv-Id",
} {
if seed := normalizePromptCacheSeed(headers.Get(name)); seed != "" {
return seed
@@ -36,12 +50,13 @@ func extractPromptCacheSeed(headers http.Header, body []byte) string {
SessionIDCamel string `json:"sessionId"`
UserID string `json:"user_id"`
} `json:"metadata"`
ClientMetadata map[string]json.RawMessage `json:"client_metadata"`
}
if json.Unmarshal(body, &payload) != nil {
return ""
}
// body.prompt_cache_key 在 handler 里也会进 PromptCacheKey;这里再提取一次,
// 保证仅依赖 seed 路径的中间件/日志也能看到。
// The handler also writes body.prompt_cache_key to PromptCacheKey. Extract it here as well so middleware
// and logs that depend only on the seed path can observe it.
if seed := normalizePromptCacheSeed(payload.PromptCacheKey); seed != "" {
return seed
}
@@ -52,8 +67,14 @@ func extractPromptCacheSeed(headers http.Header, body []byte) string {
return seed
}
if seed := promptCacheSeedFromUserID(payload.Metadata.UserID); seed != "" {
return claudeCodePromptCacheSeed(seed, headers)
}
if seed := codexPromptCacheSeedFromRawTurnMetadata(payload.ClientMetadata["x-codex-turn-metadata"]); seed != "" {
return seed
}
if seed := normalizeRawPromptCacheSeed(payload.ClientMetadata["x-codex-window-id"]); seed != "" {
return "codex:window:" + seed
}
if seed := normalizePromptCacheSeed(payload.SessionID); seed != "" {
return seed
}
@@ -66,6 +87,128 @@ func extractPromptCacheSeed(headers http.Header, body []byte) string {
return normalizePromptCacheSeed(payload.ConversationIDCamel)
}
func claudeCodePromptCacheSeed(sessionID string, headers http.Header) string {
sessionID = normalizePromptCacheSeed(sessionID)
if sessionID == "" {
return ""
}
agentID := "main"
if headers != nil {
if value := normalizePromptCacheSeed(headers.Get("X-Claude-Code-Agent-Id")); value != "" {
agentID = value
}
}
return "claude:" + sessionID + ":agent:" + agentID
}
func codexPromptCacheSeedFromHeaders(headers http.Header) string {
if headers == nil {
return ""
}
if seed := codexPromptCacheSeedFromTurnMetadata(headers.Get("X-Codex-Turn-Metadata")); seed != "" {
return seed
}
if seed := normalizePromptCacheSeed(headers.Get("X-Codex-Window-Id")); seed != "" {
return "codex:window:" + seed
}
return ""
}
func codexPromptCacheSeedFromTurnMetadata(value string) string {
value = strings.TrimSpace(value)
if value == "" || len(value) > maxCodexTurnMetadataSize {
return ""
}
var metadata struct {
PromptCacheKey string `json:"prompt_cache_key"`
WindowID string `json:"window_id"`
}
if json.Unmarshal([]byte(value), &metadata) != nil {
return ""
}
if seed := normalizePromptCacheSeed(metadata.PromptCacheKey); seed != "" {
// Keep the same seed as body.prompt_cache_key so a Codex session does not rotate its upstream cache identity
// when the signal source changes.
return seed
}
if seed := normalizePromptCacheSeed(metadata.WindowID); seed != "" {
return "codex:window:" + seed
}
return ""
}
func codexPromptCacheSeedFromRawTurnMetadata(raw json.RawMessage) string {
if len(raw) == 0 {
return ""
}
var value string
if json.Unmarshal(raw, &value) == nil {
return codexPromptCacheSeedFromTurnMetadata(value)
}
return codexPromptCacheSeedFromTurnMetadata(string(raw))
}
func normalizeRawPromptCacheSeed(raw json.RawMessage) string {
if len(raw) == 0 {
return ""
}
var value string
if json.Unmarshal(raw, &value) != nil {
return ""
}
return normalizePromptCacheSeed(value)
}
func allowBuildClientToolCacheRoute(headers http.Header) bool {
if headers == nil {
return false
}
if normalizePromptCacheSeed(headers.Get("X-Claude-Code-Session-Id")) != "" {
return true
}
if codexPromptCacheSeedFromHeaders(headers) != "" {
return true
}
return strings.Contains(strings.ToLower(headers.Get("User-Agent")), "codex")
}
func isClaudeCodeTitleRequest(headers http.Header, body []byte) bool {
if headers == nil || normalizePromptCacheSeed(headers.Get("X-Claude-Code-Session-Id")) == "" || len(body) == 0 {
return false
}
var payload struct {
System json.RawMessage `json:"system"`
}
if json.Unmarshal(body, &payload) != nil || len(payload.System) == 0 {
return false
}
var texts []string
var text string
if json.Unmarshal(payload.System, &text) == nil {
texts = append(texts, text)
} else {
var blocks []struct {
Type string `json:"type"`
Text string `json:"text"`
}
if json.Unmarshal(payload.System, &blocks) != nil {
return false
}
for _, block := range blocks {
if block.Type == "text" {
texts = append(texts, block.Text)
}
}
}
for _, value := range texts {
value = strings.ToLower(strings.TrimSpace(value))
if strings.Contains(value, "generate a concise") && strings.Contains(value, "title") && strings.Contains(value, "coding session") {
return true
}
}
return false
}
func promptCacheSeedFromUserID(userID string) string {
userID = strings.TrimSpace(userID)
if userID == "" {
@@ -13,19 +13,26 @@ func TestExtractPromptCacheSeedSupportsClaudeCodeForms(t *testing.T) {
body string
want string
}{
{name: "claude header", headers: http.Header{"X-Claude-Code-Session-Id": {"claude-session"}, "X-Session-Id": {"generic-session"}}, body: `{"metadata":{"session_id":"body-session"}}`, want: "claude-session"},
{name: "claude header", headers: http.Header{"X-Claude-Code-Session-Id": {"claude-session"}, "X-Session-Id": {"generic-session"}}, body: `{"metadata":{"session_id":"body-session"}}`, want: "claude:claude-session:agent:main"},
{name: "claude agent header", headers: http.Header{"X-Claude-Code-Session-Id": {"claude-session"}, "X-Claude-Code-Agent-Id": {"agent-7"}}, want: "claude:claude-session:agent:agent-7"},
{name: "codex turn prompt cache", headers: http.Header{"X-Codex-Turn-Metadata": {`{"prompt_cache_key":"codex-cache","window_id":"window-1"}`}}, want: "codex-cache"},
{name: "codex turn window", headers: http.Header{"X-Codex-Turn-Metadata": {`{"window_id":"window-1"}`}}, want: "codex:window:window-1"},
{name: "codex window header", headers: http.Header{"X-Codex-Window-Id": {"window-2"}}, want: "codex:window:window-2"},
{name: "generic header", headers: http.Header{"X-Session-Id": {"generic-session"}}, want: "generic-session"},
{name: "codex hyphen header", headers: http.Header{"Session-Id": {"codex-session"}}, want: "codex-session"},
{name: "codex underscore header", headers: http.Header{"Session_id": {"legacy-codex-session"}}, want: "legacy-codex-session"},
{name: "underscore session header", headers: http.Header{"Session_id": {"underscore-session"}}, want: "underscore-session"},
{name: "metadata snake case", body: `{"metadata":{"session_id":"snake-session"}}`, want: "snake-session"},
{name: "metadata camel case", body: `{"metadata":{"sessionId":"camel-session"}}`, want: "camel-session"},
{name: "embedded json user id", body: `{"metadata":{"user_id":"{\"device_id\":\"d1\",\"session_id\":\"embedded-session\"}"}}`, want: "embedded-session"},
{name: "suffix user id", body: `{"metadata":{"user_id":"user_account_session_123e4567-e89b-12d3-a456-426614174000"}}`, want: "123e4567-e89b-12d3-a456-426614174000"},
{name: "embedded json user id", body: `{"metadata":{"user_id":"{\"device_id\":\"d1\",\"session_id\":\"embedded-session\"}"}}`, want: "claude:embedded-session:agent:main"},
{name: "suffix user id", body: `{"metadata":{"user_id":"user_account_session_123e4567-e89b-12d3-a456-426614174000"}}`, want: "claude:123e4567-e89b-12d3-a456-426614174000:agent:main"},
{name: "conversation snake case", body: `{"conversation_id":"conversation-session"}`, want: "conversation-session"},
{name: "conversation camel case", body: `{"conversationId":"camel-conversation"}`, want: "camel-conversation"},
{name: "body prompt_cache_key", body: `{"prompt_cache_key":"sub2api-session"}`, want: "sub2api-session"},
// http.Header canonical key is Session-Id for "session_id"
{name: "sub2api session_id via Set", headers: func() http.Header { h := make(http.Header); h.Set("session_id", "sub2-header-session"); return h }(), want: "sub2-header-session"},
{name: "body prompt_cache_key", body: `{"prompt_cache_key":"client-session"}`, want: "client-session"},
{name: "body codex turn metadata", body: `{"client_metadata":{"x-codex-turn-metadata":"{\"prompt_cache_key\":\"body-codex-cache\"}"}}`, want: "body-codex-cache"},
{name: "body codex turn metadata object", body: `{"client_metadata":{"x-codex-turn-metadata":{"prompt_cache_key":"body-codex-object"}}}`, want: "body-codex-object"},
{name: "body codex window", body: `{"client_metadata":{"x-codex-window-id":"body-window"}}`, want: "codex:window:body-window"},
// http.Header canonicalizes "session_id" to Session-Id.
{name: "compatible client session_id via Set", headers: func() http.Header { h := make(http.Header); h.Set("session_id", "client-header-session"); return h }(), want: "client-header-session"},
{name: "grok conv header", headers: http.Header{"X-Grok-Conv-Id": {"grok-conv-session"}}, want: "grok-conv-session"},
{name: "per request id ignored", headers: http.Header{"X-Client-Request-Id": {"request-123"}}, want: ""},
{name: "ordinary user id", body: `{"metadata":{"user_id":"user-123"}}`, want: ""},
@@ -39,6 +46,20 @@ func TestExtractPromptCacheSeedSupportsClaudeCodeForms(t *testing.T) {
}
}
func TestExtractPromptCacheSeedIsolatesClaudeCodeTitleRequest(t *testing.T) {
headers := http.Header{"X-Claude-Code-Session-Id": {"claude-session"}}
body := []byte(`{
"system":[
{"type":"text","text":"x-anthropic-billing-header: cc_version=2.1.170; cch=abcde;"},
{"type":"text","text":"Generate a concise, sentence-case title (3-7 words) that captures the main topic or goal of this coding session."}
],
"messages":[{"role":"user","content":"<session>hello</session>"}]
}`)
if seed := extractPromptCacheSeed(headers, body); seed != "" {
t.Fatalf("title request seed = %q, want empty explicit seed", seed)
}
}
func TestExtractPromptCacheSeedRejectsOversizedValues(t *testing.T) {
headers := make(http.Header)
headers.Set("X-Claude-Code-Session-Id", strings.Repeat("x", maxPromptCacheSeedBytes+1))
@@ -46,3 +67,23 @@ func TestExtractPromptCacheSeedRejectsOversizedValues(t *testing.T) {
t.Fatalf("oversized seed = %q", seed)
}
}
func TestAllowBuildClientToolCacheRouteUsesKnownCLISignals(t *testing.T) {
tests := []struct {
name string
headers http.Header
want bool
}{
{name: "claude", headers: http.Header{"X-Claude-Code-Session-Id": {"session"}}, want: true},
{name: "codex metadata", headers: http.Header{"X-Codex-Turn-Metadata": {`{"window_id":"window-1"}`}}, want: true},
{name: "codex user agent", headers: http.Header{"User-Agent": {"Codex Desktop/1.0"}}, want: true},
{name: "generic", headers: http.Header{"User-Agent": {"custom-client/1.0"}}},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := allowBuildClientToolCacheRoute(test.headers); got != test.want {
t.Fatalf("allowed = %t, want %t", got, test.want)
}
})
}
}