From f996040784ae8fae05896f533f64107453893c51 Mon Sep 17 00:00:00 2001 From: Chenyme <118253778+chenyme@users.noreply.github.com> Date: Tue, 4 Aug 2026 18:42:09 +0800 Subject: [PATCH] feat: support Grok Build Composer discovery and protocol compatibility --- .../application/gateway/prompt_cache.go | 31 +++++++++ .../application/gateway/prompt_cache_test.go | 30 +++++++++ .../internal/application/gateway/service.go | 11 +++- .../application/model/service_test.go | 28 ++++++-- backend/internal/domain/model/reasoning.go | 13 +++- .../internal/domain/model/reasoning_test.go | 14 ++++ .../internal/infra/provider/cli/adapter.go | 65 +++++++++++++++---- .../infra/provider/cli/adapter_test.go | 62 ++++++++++++++++++ .../internal/infra/provider/cli/normalize.go | 15 +++++ .../infra/provider/cli/normalize_test.go | 59 +++++++++++++++++ 10 files changed, 308 insertions(+), 20 deletions(-) diff --git a/backend/internal/application/gateway/prompt_cache.go b/backend/internal/application/gateway/prompt_cache.go index debce770..ed88d00d 100644 --- a/backend/internal/application/gateway/prompt_cache.go +++ b/backend/internal/application/gateway/prompt_cache.go @@ -9,6 +9,7 @@ import ( "unicode/utf8" accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" + modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" ) const buildSessionIdentityVersion = "v3" @@ -22,6 +23,9 @@ type buildSessionIdentity struct { replayKey string // soft indicates a fallback identity derived from message content when no explicit session is available. soft bool + // isolated indicates a Composer-only request identity used when the client + // supplied no stable session. + isolated bool } // resolveBuildSessionIdentity derives a stable Grok Build session identity: @@ -65,6 +69,33 @@ func resolveBuildSessionIdentity(clientKeyID uint64, provider accountdomain.Prov } } +// ensureBuildComposerSessionIdentity mirrors Composer's isolated-conversation +// requirement without copying CPA's per-attempt random UUID behavior. The +// request scope is stable across retries and route failover, while replay stays +// disabled because this is not an explicit client conversation. +func ensureBuildComposerSessionIdentity(identity buildSessionIdentity, clientKeyID uint64, provider accountdomain.Provider, upstreamModel, requestScope string) buildSessionIdentity { + // Explicit client sessions and previous-response ownership are authoritative. + // A soft message-prefix identity is intentionally replaced: two independent + // Composer requests may begin with the same text and must not share a + // conversation merely because their first message matches. + if (identity.upstreamID != "" && !identity.soft) || clientKeyID == 0 || provider != accountdomain.ProviderBuild || !modeldomain.IsGrokComposerModel(upstreamModel) { + return identity + } + requestScope = strings.TrimSpace(requestScope) + if requestScope == "" { + return identity + } + model := strings.ToLower(strings.TrimSpace(upstreamModel)) + upstreamSource := fmt.Sprintf("grok2api:build-composer-isolated:v1:%d:%s:%s:%s", clientKeyID, provider, model, requestScope) + affinitySource := fmt.Sprintf("grok2api:build-composer-affinity:v1:%d:%s:%s:%s", clientKeyID, provider, model, requestScope) + identity.upstreamID = digestUUID(upstreamSource) + identity.affinityKey = hexDigest(affinitySource) + identity.replayKey = "" + identity.soft = false + identity.isolated = true + return identity +} + func digestUUID(source string) string { digest := sha256.Sum256([]byte(source)) hexID := hex.EncodeToString(digest[:16]) diff --git a/backend/internal/application/gateway/prompt_cache_test.go b/backend/internal/application/gateway/prompt_cache_test.go index f64fb82c..630fef7a 100644 --- a/backend/internal/application/gateway/prompt_cache_test.go +++ b/backend/internal/application/gateway/prompt_cache_test.go @@ -4,6 +4,7 @@ import ( "testing" accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" + modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" ) func TestResolveBuildSessionIdentityIsStableAndTenantIsolated(t *testing.T) { @@ -22,6 +23,35 @@ func TestResolveBuildSessionIdentityIsStableAndTenantIsolated(t *testing.T) { } } +func TestEnsureBuildComposerSessionIdentityIsRequestStable(t *testing.T) { + empty := buildSessionIdentity{} + first := ensureBuildComposerSessionIdentity(empty, 7, accountdomain.ProviderBuild, modeldomain.GrokComposer25Fast, "request-1") + repeated := ensureBuildComposerSessionIdentity(empty, 7, accountdomain.ProviderBuild, modeldomain.GrokComposer25Fast, "request-1") + other := ensureBuildComposerSessionIdentity(empty, 7, accountdomain.ProviderBuild, modeldomain.GrokComposer25Fast, "request-2") + if first.upstreamID == "" || first.affinityKey == "" || !first.isolated || first.replayKey != "" || first != repeated { + t.Fatalf("Composer isolated identity unstable: first=%#v repeated=%#v", first, repeated) + } + if first.upstreamID == other.upstreamID || first.affinityKey == other.affinityKey { + t.Fatalf("different Composer requests shared identity: first=%#v other=%#v", first, other) + } + if got := ensureBuildComposerSessionIdentity(empty, 7, accountdomain.ProviderBuild, "grok-4.5", "request-1"); got != empty { + t.Fatalf("non-Composer request gained an identity: %#v", got) + } + explicit := resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, modeldomain.GrokComposer25Fast, "client-session", "", nil) + if got := ensureBuildComposerSessionIdentity(explicit, 7, accountdomain.ProviderBuild, modeldomain.GrokComposer25Fast, "request-1"); got != explicit { + t.Fatalf("explicit Composer identity was overwritten: got=%#v want=%#v", got, explicit) + } + soft := resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, modeldomain.GrokComposer25Fast, "", "", []byte(`{"input":"same opening message"}`)) + isolated := ensureBuildComposerSessionIdentity(soft, 7, accountdomain.ProviderBuild, modeldomain.GrokComposer25Fast, "request-1") + if !soft.soft || isolated.upstreamID == soft.upstreamID || isolated.soft || !isolated.isolated { + t.Fatalf("soft Composer identity was not isolated: soft=%#v isolated=%#v", soft, isolated) + } + softNonComposer := resolveBuildSessionIdentity(7, accountdomain.ProviderBuild, "grok-4.5", "", "", []byte(`{"input":"same opening message"}`)) + if got := ensureBuildComposerSessionIdentity(softNonComposer, 7, accountdomain.ProviderBuild, "grok-4.5", "request-1"); got != softNonComposer { + t.Fatalf("non-Composer soft identity was overwritten: got=%#v want=%#v", got, softNonComposer) + } +} + 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) diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index 9945cd67..500a5e31 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -722,6 +722,9 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string firstToken = newFirstTokenTimer(startedAt) } eventID := newAuditEventID() + // Use a server-generated scope so repeated or absent client request IDs + // cannot accidentally join independent Composer conversations. + requestSessionScope := eventID operation := input.Operation if operation == "" { operation = audit.OperationResponses @@ -774,6 +777,7 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string input.PromptCacheSeed, input.Body, ) + identity = ensureBuildComposerSessionIdentity(identity, input.ClientKey.ID, candidate.Provider, candidate.UpstreamModel, requestSessionScope) affinityKey = identity.affinityKey } candidateSession, selectionErr := s.selector.beginSelectionSessionForKey( @@ -841,7 +845,9 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string ownershipPromptCacheKey := "" reasoningReplayKey := "" if route.Provider == accountdomain.ProviderBuild { - // Derive a stable identity from explicit session signals, message anchors, and model; never generate a random conv-id. + // Derive a stable identity from explicit session signals, message anchors, + // and model. Composer replaces message-only fallback identities with an + // isolated request identity that remains stable across retries. identity := buildSessionIdentity{} if ownership != nil && ownership.PromptCacheKey != "" { // previous_response_id belongs to an existing Response chain and must inherit the root session identity; @@ -858,6 +864,7 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string input.Body, ) } + identity = ensureBuildComposerSessionIdentity(identity, input.ClientKey.ID, route.Provider, route.UpstreamModel, requestSessionScope) input.PromptCacheKey = identity.upstreamID affinityKey = identity.affinityKey ownershipPromptCacheKey = identity.upstreamID @@ -866,6 +873,8 @@ func (s *Service) createResponseAt(ctx context.Context, input Input, path string s.logger.Debug("prompt_cache_session_empty", "request_id", input.RequestID, "model", route.UpstreamModel, "provider", route.Provider) } else if identity.soft { s.logger.Debug("prompt_cache_session_soft", "request_id", input.RequestID, "model", route.UpstreamModel) + } else if identity.isolated { + s.logger.Debug("prompt_cache_session_isolated", "request_id", input.RequestID, "model", route.UpstreamModel) } } adapter, ok := s.providers.Responses(route.Provider) diff --git a/backend/internal/application/model/service_test.go b/backend/internal/application/model/service_test.go index d83b7de9..48267162 100644 --- a/backend/internal/application/model/service_test.go +++ b/backend/internal/application/model/service_test.go @@ -135,7 +135,7 @@ func TestSyncAccountNormalizesBuildVideo15ByBillingSuper(t *testing.T) { // 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", + Provider: account.ProviderBuild, AuthType: account.AuthTypeOAuth, Name: "super-primary", SourceKey: "super-primary", EncryptedAccessToken: encrypted, ExpiresAt: time.Now().Add(time.Hour), AuthStatus: account.AuthStatusActive, }) if err != nil { @@ -143,7 +143,7 @@ func TestSyncAccountNormalizesBuildVideo15ByBillingSuper(t *testing.T) { } // 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", + Provider: account.ProviderBuild, AuthType: account.AuthTypeOAuth, Name: "super-fallback", SourceKey: "super-fallback", EncryptedAccessToken: encrypted, ExpiresAt: time.Now().Add(time.Hour), AuthStatus: account.AuthStatusActive, BuildAPIFallback: true, }) @@ -152,7 +152,7 @@ func TestSyncAccountNormalizesBuildVideo15ByBillingSuper(t *testing.T) { } // 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", + Provider: account.ProviderBuild, AuthType: account.AuthTypeOAuth, Name: "free-fallback", SourceKey: "free-fallback", EncryptedAccessToken: encrypted, ExpiresAt: time.Now().Add(time.Hour), AuthStatus: account.AuthStatusActive, BuildAPIFallback: true, }) @@ -161,7 +161,7 @@ func TestSyncAccountNormalizesBuildVideo15ByBillingSuper(t *testing.T) { } // 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", + Provider: account.ProviderBuild, AuthType: account.AuthTypeOAuth, Name: "unknown", SourceKey: "unknown", EncryptedAccessToken: encrypted, ExpiresAt: time.Now().Add(time.Hour), AuthStatus: account.AuthStatusActive, }) if err != nil { @@ -235,12 +235,19 @@ func TestSyncAccountNormalizesBuildVideo15ByBillingSuper(t *testing.T) { assertSupports(superPrimary.ID, "grok-4.5", true) assertSupports(superFallback.ID, "grok-code-fast-1", true) assertSupports(freeAccount.ID, "grok-4.5", true) + for _, accountID := range []uint64{superPrimary.ID, superFallback.ID, freeAccount.ID, unknownAccount.ID} { + assertSupports(accountID, modeldomain.GrokComposer25Fast, true) + } // 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) } + composerRoute, err := modelRepo.GetByPublicID(ctx, modeldomain.GrokComposer25Fast) + if err != nil || composerRoute.Provider != account.ProviderBuild || composerRoute.Capability != modeldomain.CapabilityResponses { + t.Fatalf("Build Composer route = %#v, err = %v", composerRoute, err) + } // Web does not use Build normalization and still supports its catalog models. webCandidates, err := accountRepo.ListRoutingCandidates(ctx, account.ProviderWeb, 0, "grok-imagine-video", "") if err != nil || len(webCandidates) != 1 || !webCandidates[0].SupportsModel { @@ -337,11 +344,13 @@ type buildCapabilityNormalizerAdapter struct { } func (a *buildCapabilityNormalizerAdapter) NormalizeAccountModelCapabilities(models []string, billing *account.Billing, credential account.Credential) []string { - // Match cli.Adapter rules: Super (paid or entitlement) ensures 1.5; otherwise remove it exactly. Ignore BuildAPIFallback. + // Match cli.Adapter rules: Build OAuth adds Composer; Super (paid or + // entitlement) ensures 1.5; otherwise remove video 1.5 exactly. const video15 = "grok-imagine-video-1.5" super := account.IsBuildSuper(credential, billing) - result := make([]string, 0, len(models)+1) - seen := make(map[string]struct{}, len(models)+1) + composer := credential.Provider == account.ProviderBuild && credential.AuthType == account.AuthTypeOAuth + result := make([]string, 0, len(models)+2) + seen := make(map[string]struct{}, len(models)+2) hasVideo15 := false for _, modelName := range models { if modelName == "" { @@ -362,6 +371,11 @@ func (a *buildCapabilityNormalizerAdapter) NormalizeAccountModelCapabilities(mod if super && !hasVideo15 { result = append(result, video15) } + if composer { + if _, exists := seen[modeldomain.GrokComposer25Fast]; !exists { + result = append(result, modeldomain.GrokComposer25Fast) + } + } return result } diff --git a/backend/internal/domain/model/reasoning.go b/backend/internal/domain/model/reasoning.go index 5ffb8d98..35fcac5b 100644 --- a/backend/internal/domain/model/reasoning.go +++ b/backend/internal/domain/model/reasoning.go @@ -19,6 +19,10 @@ const ( ReasoningEffortMax ReasoningEffort = "max" ) +const GrokComposer25Fast = "grok-composer-2.5-fast" + +const grokComposerModelPrefix = "grok-composer-" + // reasoningEffortSuffixes is ordered longest-first so "xhigh" wins over "high". var reasoningEffortSuffixes = []string{ ReasoningEffortXHigh, @@ -46,7 +50,14 @@ var grokReasoningCapabilities = map[string][]string{ "grok-4.20-multi-agent-0309": {ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh, ReasoningEffortXHigh}, "grok-3-mini": {ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh}, "grok-3-mini-fast": {ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh}, - "grok-composer-2.5-fast": {ReasoningEffortNone}, + GrokComposer25Fast: {ReasoningEffortNone}, +} + +// IsGrokComposerModel reports whether value belongs to the Composer family. +// Composer uses an isolated upstream conversation and does not accept a +// configurable reasoning effort, including when addressed through Build/. +func IsGrokComposerModel(value string) bool { + return strings.HasPrefix(strings.ToLower(externalModelSlug(value)), grokComposerModelPrefix) } // The Console reasoning variant has a fixed reasoning mode: it produces reasoning diff --git a/backend/internal/domain/model/reasoning_test.go b/backend/internal/domain/model/reasoning_test.go index 157bdffc..3e42599f 100644 --- a/backend/internal/domain/model/reasoning_test.go +++ b/backend/internal/domain/model/reasoning_test.go @@ -18,6 +18,7 @@ func TestSupportedReasoningEffortsPerModel(t *testing.T) { {model: "Console/grok-4.20-0309-reasoning", want: []string{}}, {model: "grok-4.20-multi-agent-0309", want: []string{"low", "medium", "high", "xhigh"}}, {model: "grok-build-0.1", want: []string{"none"}}, + {model: GrokComposer25Fast, want: []string{"none"}}, {model: "unknown-model", want: []string{"none"}}, } for _, test := range tests { @@ -46,6 +47,19 @@ func TestSupportedReasoningEffortsPerModel(t *testing.T) { } } +func TestIsGrokComposerModel(t *testing.T) { + for _, value := range []string{GrokComposer25Fast, "Build/" + GrokComposer25Fast, "GROK-COMPOSER-FUTURE"} { + if !IsGrokComposerModel(value) { + t.Fatalf("Composer model not recognized: %q", value) + } + } + for _, value := range []string{"grok-4.5", "Console/grok-composerish", ""} { + if IsGrokComposerModel(value) { + t.Fatalf("non-Composer model recognized: %q", value) + } + } +} + func TestParseReasoningModelAlias(t *testing.T) { tests := []struct { name string diff --git a/backend/internal/infra/provider/cli/adapter.go b/backend/internal/infra/provider/cli/adapter.go index 15e9129a..35def5a6 100644 --- a/backend/internal/infra/provider/cli/adapter.go +++ b/backend/internal/infra/provider/cli/adapter.go @@ -22,6 +22,7 @@ import ( "github.com/google/uuid" "github.com/chenyme/grok2api/backend/internal/domain/account" + modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" settingsdomain "github.com/chenyme/grok2api/backend/internal/domain/settings" infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" "github.com/chenyme/grok2api/backend/internal/infra/provider" @@ -563,7 +564,8 @@ func (a *Adapter) ListModels(ctx context.Context, credential account.Credential) return nil, err } // 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. + // NormalizeAccountModelCapabilities fills session-contract capabilities such + // as Composer and paid video entitlement locally. models, status, err := a.listModelsAt(ctx, credential, accessToken, a.primaryBaseURL()) if err != nil { return nil, err @@ -574,12 +576,16 @@ func (a *Adapter) ListModels(ctx context.Context, credential account.Credential) return nil, fmt.Errorf("上游模型接口返回 %d", status) } -// 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. +// NormalizeAccountModelCapabilities normalizes capabilities that the OAuth +// session contract exposes independently of the account's sparse /models list. +// Composer is available to Build OAuth sessions even though the live catalog can +// return only grok-4.5. Super always includes video 1.5; Free and Unknown remove +// video 1.5 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) - seen := make(map[string]struct{}, len(models)+1) + composer := credential.Provider == account.ProviderBuild && credential.AuthType == account.AuthTypeOAuth + result := make([]string, 0, len(models)+2) + seen := make(map[string]struct{}, len(models)+2) hasVideo15 := false for _, model := range models { model = strings.TrimSpace(model) @@ -601,9 +607,37 @@ func (a *Adapter) NormalizeAccountModelCapabilities(models []string, billing *ac if super && !hasVideo15 { result = append(result, buildVideoModel) } + if composer { + if _, exists := seen[modeldomain.GrokComposer25Fast]; !exists { + result = append(result, modeldomain.GrokComposer25Fast) + } + } return result } +type buildModelCatalogEntry struct { + ID string `json:"id"` + Model string `json:"model"` + ModelID string `json:"modelId"` + Hidden bool `json:"hidden"` + Meta struct { + Model string `json:"model"` + ModelID string `json:"modelId"` + Hidden bool `json:"hidden"` + } `json:"_meta"` +} + +// modelIdentifier keeps the legacy top-level id authoritative and uses the +// additional official Grok Build shapes only as fallbacks. This makes catalog +// parsing additive: existing route IDs never change merely because model or +// modelId metadata appears alongside id. +func (e buildModelCatalogEntry) modelIdentifier() string { + if e.Hidden || e.Meta.Hidden { + return "" + } + return firstNonEmpty(e.ID, e.Model, e.ModelID, e.Meta.Model, e.Meta.ModelID) +} + func (a *Adapter) listModelsAt(ctx context.Context, credential account.Credential, accessToken, base string) ([]string, int, error) { requestCtx := infraegress.WithCredential(ctx, credential) req, err := http.NewRequestWithContext(requestCtx, http.MethodGet, a.urlWithBase(base, "/models"), nil) @@ -629,18 +663,27 @@ func (a *Adapter) listModelsAt(ctx context.Context, credential account.Credentia return nil, resp.StatusCode, nil } var payload struct { - Data []struct { - ID string `json:"id"` - } `json:"data"` + Data []json.RawMessage `json:"data"` } if err := json.Unmarshal(body, &payload); err != nil { return nil, resp.StatusCode, err } models := make([]string, 0, len(payload.Data)) - for _, item := range payload.Data { - if item.ID != "" { - models = append(models, item.ID) + seen := make(map[string]struct{}, len(payload.Data)) + for _, raw := range payload.Data { + var item buildModelCatalogEntry + if json.Unmarshal(raw, &item) != nil { + continue } + identifier := item.modelIdentifier() + if identifier == "" { + continue + } + if _, exists := seen[identifier]; exists { + continue + } + seen[identifier] = struct{}{} + models = append(models, identifier) } a.recordModelsETag(credential.ID, resp.Header.Get("ETag")) return models, resp.StatusCode, nil diff --git a/backend/internal/infra/provider/cli/adapter_test.go b/backend/internal/infra/provider/cli/adapter_test.go index edc3612e..d189d086 100644 --- a/backend/internal/infra/provider/cli/adapter_test.go +++ b/backend/internal/infra/provider/cli/adapter_test.go @@ -16,6 +16,7 @@ import ( "github.com/google/uuid" "github.com/chenyme/grok2api/backend/internal/domain/account" + modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" "github.com/chenyme/grok2api/backend/internal/infra/provider" "github.com/chenyme/grok2api/backend/internal/infra/provider/conversation" @@ -395,6 +396,45 @@ func TestListModelsUsesOfficialMetadataHeaders(t *testing.T) { } } +func TestListModelsParsesOfficialIdentifierFallbacksAdditively(t *testing.T) { + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) + if err != nil { + t.Fatal(err) + } + encrypted, err := cipher.Encrypt("access-token") + if err != nil { + t.Fatal(err) + } + adapter := NewAdapter(Config{BaseURL: "https://cli-chat-proxy.grok.com/v1"}, cipher) + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + body := `{"data":[ + {"id":"grok-4.5","model":"must-not-replace-id"}, + {"model":"grok-composer-2.5-fast"}, + {"modelId":"future-model"}, + {"_meta":{"model":"meta-model"}}, + {"_meta":{"modelId":"meta-id-model"}}, + {"id":"hidden-model","hidden":true}, + {"id":"meta-hidden-model","_meta":{"hidden":true}}, + {"id":"grok-4.5"}, + "malformed" + ]}` + return &http.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: request}, nil + }) + models, err := adapter.ListModels(context.Background(), account.Credential{EncryptedAccessToken: encrypted}) + if err != nil { + t.Fatal(err) + } + want := []string{"grok-4.5", modeldomain.GrokComposer25Fast, "future-model", "meta-model", "meta-id-model"} + if len(models) != len(want) { + t.Fatalf("models = %#v, want %#v", models, want) + } + for index := range want { + if models[index] != want[index] { + t.Fatalf("models = %#v, want %#v", models, want) + } + } +} + func TestModelCatalogETagSignalsMissingOrChangedCatalogBaseline(t *testing.T) { cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) if err != nil { @@ -530,6 +570,28 @@ func TestNormalizeAccountModelCapabilitiesSuperAddsVideo15(t *testing.T) { } } +func TestNormalizeAccountModelCapabilitiesAddsComposerOnlyForBuildOAuth(t *testing.T) { + adapter := &Adapter{} + oauth := account.Credential{Provider: account.ProviderBuild, AuthType: account.AuthTypeOAuth} + got := adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5"}, &account.Billing{PlanName: "free"}, oauth) + if len(got) != 2 || got[0] != "grok-4.5" || got[1] != modeldomain.GrokComposer25Fast { + t.Fatalf("OAuth Free capabilities = %#v", got) + } + got = adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5", modeldomain.GrokComposer25Fast, modeldomain.GrokComposer25Fast}, nil, oauth) + if len(got) != 2 || got[0] != "grok-4.5" || got[1] != modeldomain.GrokComposer25Fast { + t.Fatalf("Composer capability was not deduplicated: %#v", got) + } + for _, credential := range []account.Credential{ + {Provider: account.ProviderBuild, AuthType: account.AuthTypeSSO}, + {Provider: account.ProviderWeb, AuthType: account.AuthTypeOAuth}, + } { + got = adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5"}, nil, credential) + if len(got) != 1 || got[0] != "grok-4.5" { + t.Fatalf("Composer leaked outside Build OAuth for %#v: %#v", credential, got) + } + } +} + func TestGrokSessionIDFollowsConversationIdentity(t *testing.T) { explicit := "019f6b02-5bae-7cf3-b26e-73e85c861749" if value, err := grokSessionID(explicit); err != nil || value != explicit { diff --git a/backend/internal/infra/provider/cli/normalize.go b/backend/internal/infra/provider/cli/normalize.go index e19141ee..624b7c1b 100644 --- a/backend/internal/infra/provider/cli/normalize.go +++ b/backend/internal/infra/provider/cli/normalize.go @@ -128,6 +128,21 @@ func normalizeBuildReasoningEffortPayload(payload map[string]json.RawMessage, mo if err := json.Unmarshal(raw, &reasoning); err != nil || reasoning == nil { return false } + // CPA and the current xAI model registry both treat Composer as a model + // without configurable thinking levels. Preserve other reasoning controls + // such as summary, but never forward reasoning.effort to Composer. + if modeldomain.IsGrokComposerModel(model) { + if _, exists := reasoning["effort"]; !exists { + return false + } + delete(reasoning, "effort") + if len(reasoning) == 0 { + delete(payload, "reasoning") + } else { + payload["reasoning"] = mustJSON(reasoning) + } + return true + } var effort string if err := json.Unmarshal(reasoning["effort"], &effort); err != nil { return false diff --git a/backend/internal/infra/provider/cli/normalize_test.go b/backend/internal/infra/provider/cli/normalize_test.go index 5606f528..5d8bf0b9 100644 --- a/backend/internal/infra/provider/cli/normalize_test.go +++ b/backend/internal/infra/provider/cli/normalize_test.go @@ -8,7 +8,9 @@ import ( "testing" "time" + modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" "github.com/chenyme/grok2api/backend/internal/infra/provider" + "github.com/chenyme/grok2api/backend/internal/infra/provider/conversation" ) func TestNormalizeResponsesRequest(t *testing.T) { @@ -74,6 +76,63 @@ func TestNormalizeBuildReasoningEffort(t *testing.T) { } } +func TestNormalizeBuildComposerStripsReasoningEffort(t *testing.T) { + tests := []struct { + name string + body []byte + }{ + {name: "responses", body: []byte(`{"reasoning":{"effort":"high","summary":"auto"},"input":"hello"}`)}, + {name: "chat conversion", body: func() []byte { + converted, _, err := conversation.ConvertRequestWithOptions( + []byte(`{"model":"public","messages":[{"role":"user","content":"hello"}],"reasoning_effort":"high"}`), + modeldomain.GrokComposer25Fast, + conversation.OperationChat, + ) + if err != nil { + t.Fatal(err) + } + return converted + }()}, + {name: "messages conversion", body: func() []byte { + converted, _, err := conversation.ConvertRequestWithOptions( + []byte(`{"model":"public","max_tokens":64,"messages":[{"role":"user","content":"hello"}],"thinking":{"type":"adaptive"},"output_config":{"effort":"xhigh"}}`), + modeldomain.GrokComposer25Fast, + conversation.OperationMessages, + ) + if err != nil { + t.Fatal(err) + } + return converted + }()}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + normalized, err := normalizeBuildRequest(test.body, modeldomain.GrokComposer25Fast) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if json.Unmarshal(normalized, &payload) != nil { + t.Fatalf("invalid normalized payload: %s", normalized) + } + if reasoning, ok := payload["reasoning"].(map[string]any); ok { + if _, exists := reasoning["effort"]; exists { + t.Fatalf("Composer reasoning effort leaked upstream: %#v", payload) + } + } + }) + } + + stripped, err := normalizeBuildRequest([]byte(`{"reasoning":{"effort":"medium"},"input":"hello"}`), modeldomain.GrokComposer25Fast) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if json.Unmarshal(stripped, &payload) != nil || payload["reasoning"] != nil { + t.Fatalf("empty Composer reasoning object was not removed: %s", stripped) + } +} + func TestNormalizeBuildRequestAppliesSafeDefaultsAndStripsCodexEnvelope(t *testing.T) { body := []byte(`{ "model":"public",