feat: align Grok Build 1.0.40 headers and catalog-driven reasoning menus

This commit is contained in:
Chenyme committed 2026-09-22 01:17:29 +08:00
1 parent 906b9493b0
commit 9dda42ae41
22 files changed
+629 -68

No files matched your search

+5
View File
@@ -116,6 +116,7 @@ type tokenPriceRule struct {
var officialTokenPriceRules = []tokenPriceRule{
{Pattern: regexp.MustCompile(`^grok-(?:build-0\.1|code-fast(?:-1)?|composer-2\.5-fast)(?:-[a-z0-9.]+)*$`), CanonicalModel: "grok-build-0.1"},
{Pattern: regexp.MustCompile(`^grok-4\.7(?:-[a-z0-9.]+)*$`), CanonicalModel: "grok-4.7"},
{Pattern: regexp.MustCompile(`^grok-4\.6(?:-[a-z0-9.]+)*$`), CanonicalModel: "grok-4.6"},
{Pattern: regexp.MustCompile(`^grok-4\.5(?:-[a-z0-9.]+)*$`), CanonicalModel: "grok-4.5"},
{Pattern: regexp.MustCompile(`^grok-4\.3(?:-[a-z0-9.]+)*$`), CanonicalModel: "grok-4.3"},
@@ -136,6 +137,10 @@ func buildOfficialTokenPrices() map[string]tokenPrice {
}
register("grok-build-0.1", tokenPrice{InputTicks: 10000, CachedInputTicks: 2000, OutputTicks: 20000, LongContextTokens: 200000, LongInputTicks: 20000, LongCachedTicks: 4000, LongOutputTicks: 40000},
"grok-code-fast-1", "grok-code-fast", "grok-code-fast-1-0825", "grok-composer-2.5-fast")
// grok-4.7 has not been published on the xAI pricing page yet; it is billed
// at the grok-4.6 frontier rate until an official rate is available.
register("grok-4.7", tokenPrice{InputTicks: 20000, CachedInputTicks: 5000, OutputTicks: 60000, LongContextTokens: 200000, LongInputTicks: 40000, LongCachedTicks: 10000, LongOutputTicks: 120000},
"grok-4.7-latest")
register("grok-4.6", tokenPrice{InputTicks: 20000, CachedInputTicks: 5000, OutputTicks: 60000, LongContextTokens: 200000, LongInputTicks: 40000, LongCachedTicks: 10000, LongOutputTicks: 120000},
"grok-4.6-latest")
register("grok-4.5", tokenPrice{InputTicks: 20000, CachedInputTicks: 3000, OutputTicks: 60000, LongContextTokens: 200000, LongInputTicks: 40000, LongCachedTicks: 6000, LongOutputTicks: 120000},
@@ -28,6 +28,7 @@ func TestEstimateOfficialCostMatchesControlledModelFamilies(t *testing.T) {
}{
{model: "Build/grok-build-0.1", canonical: "grok-build-0.1"},
{model: "Console/grok-4.6-latest", canonical: "grok-4.6"},
{model: "Build/grok-4.7-xhigh", canonical: "grok-4.7"},
{model: "grok_build/grok-code-fast-1-0825", canonical: "grok-build-0.1"},
{model: "Console/grok-4.3-high", canonical: "grok-4.3"},
{model: "Web/grok-4.5-2026-07-14", canonical: "grok-4.5"},
@@ -6,7 +6,7 @@ import "strings"
// Provider adapters must resolve client aliases before calling this function.
func NormalizeReasoningEffort(value string) string {
switch normalized := strings.ToLower(strings.TrimSpace(value)); normalized {
case "auto", "none", "low", "medium", "high", "xhigh", "fixed":
case "auto", "none", "minimal", "low", "medium", "high", "xhigh", "max", "fixed":
return normalized
default:
return ""
@@ -9,7 +9,10 @@ func TestNormalizeReasoningEffort(t *testing.T) {
}{
{value: " XHIGH ", want: "xhigh"},
{value: "fixed", want: "fixed"},
{value: "max", want: ""},
// max/minimal are real grok-build wire tiers; adapters only forward them when the model menu lists them.
{value: "max", want: "max"},
{value: "MINIMAL", want: "minimal"},
{value: "ultra", want: ""},
{value: "thinking:32000", want: ""},
{value: "customer@example.com", want: ""},
}
+46 -25
View File
@@ -11,12 +11,13 @@ import (
type ReasoningEffort = string
const (
ReasoningEffortNone ReasoningEffort = "none"
ReasoningEffortLow ReasoningEffort = "low"
ReasoningEffortMedium ReasoningEffort = "medium"
ReasoningEffortHigh ReasoningEffort = "high"
ReasoningEffortXHigh ReasoningEffort = "xhigh"
ReasoningEffortMax ReasoningEffort = "max"
ReasoningEffortNone ReasoningEffort = "none"
ReasoningEffortMinimal ReasoningEffort = "minimal"
ReasoningEffortLow ReasoningEffort = "low"
ReasoningEffortMedium ReasoningEffort = "medium"
ReasoningEffortHigh ReasoningEffort = "high"
ReasoningEffortXHigh ReasoningEffort = "xhigh"
ReasoningEffortMax ReasoningEffort = "max"
)
const GrokComposer25Fast = "grok-composer-2.5-fast"
@@ -25,6 +26,7 @@ const grokComposerModelPrefix = "grok-composer-"
// reasoningEffortSuffixes is ordered longest-first so "xhigh" wins over "high".
var reasoningEffortSuffixes = []string{
ReasoningEffortMinimal,
ReasoningEffortXHigh,
ReasoningEffortMedium,
ReasoningEffortHigh,
@@ -33,18 +35,35 @@ var reasoningEffortSuffixes = []string{
ReasoningEffortMax,
}
// knownReasoningEfforts is the full grok-build wire vocabulary
// (xai-grok-sampling-types ReasoningEffort). Upstream catalog menus are
// filtered against it so a tier this gateway cannot name is never advertised.
var knownReasoningEfforts = map[string]struct{}{
ReasoningEffortNone: {}, ReasoningEffortMinimal: {}, ReasoningEffortLow: {}, ReasoningEffortMedium: {},
ReasoningEffortHigh: {}, ReasoningEffortXHigh: {}, ReasoningEffortMax: {},
}
// IsKnownReasoningEffort reports whether value is a grok-build wire effort tier.
func IsKnownReasoningEffort(value string) bool {
_, ok := knownReasoningEfforts[strings.ToLower(strings.TrimSpace(value))]
return ok
}
// grokReasoningCapabilities maps external public model IDs to the reasoning levels
// generally accepted by the model family. Provider-specific wire restrictions are
// applied by providerReasoningEffortOverrides:
// - grok-4.5: low/medium/high (reasoning cannot be disabled; no xhigh/max)
// - grok-4.6: low/medium/high/xhigh (xhigh is a real upstream effort; max stays guarded)
// - grok-4.6 / grok-4.7: low/medium/high/xhigh (xhigh is a real upstream effort; max stays guarded)
// - grok-4.3: none/low/medium/high
// - grok-4.20-multi-agent: low/medium/high/xhigh (effort controls agent count)
//
// Unknown models default to none-only and never expand into effort aliases.
// When the Build catalog advertises a reasoning menu for a model (see
// RegisterUpstreamModelProfile), that live menu takes precedence over this table.
var grokReasoningCapabilities = map[string][]string{
"grok-4.5": {ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh},
"grok-4.6": {ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh, ReasoningEffortXHigh},
"grok-4.7": {ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh, ReasoningEffortXHigh},
"grok-4.3": {ReasoningEffortNone, ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh},
"grok-build-0.1": {ReasoningEffortNone},
"grok-4.20-0309-reasoning": {ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh},
@@ -166,16 +185,7 @@ func DefaultReasoningEffort(publicModel string) string {
if _, effort, ok := ParseReasoningModelAlias(publicModel); ok {
return effort
}
levels := SupportedReasoningEfforts(publicModel)
for _, level := range levels {
if level == ReasoningEffortMedium {
return level
}
}
if len(levels) > 0 {
return levels[0]
}
return ReasoningEffortNone
return preferredReasoningEffort(externalModelSlug(publicModel), SupportedReasoningEfforts(publicModel))
}
// DefaultReasoningEffortForProvider returns a configurable Provider default.
@@ -184,7 +194,25 @@ func DefaultReasoningEffortForProvider(providerValue account.Provider, publicMod
if _, effort, ok := ParseReasoningModelAlias(publicModel); ok && SupportsReasoningEffortForProvider(providerValue, publicModel, effort) {
return effort
}
levels := SupportedReasoningEffortsForProvider(providerValue, publicModel)
return preferredReasoningEffort(externalModelSlug(publicModel), SupportedReasoningEffortsForProvider(providerValue, publicModel))
}
func reasoningEffortsForSlug(slug string) []string {
if profile, ok := UpstreamProfile(slug); ok && len(profile.ReasoningEfforts) > 0 {
return append([]string(nil), profile.ReasoningEfforts...)
}
if levels, ok := grokReasoningCapabilities[slug]; ok {
return append([]string(nil), levels...)
}
return []string{ReasoningEffortNone}
}
// preferredReasoningEffort picks the default among levels: the catalog-declared
// default when the live menu provides one, otherwise medium, otherwise the first level.
func preferredReasoningEffort(slug string, levels []string) string {
if profile, ok := UpstreamProfile(slug); ok && profile.DefaultReasoningEffort != "" && levelsContain(levels, profile.DefaultReasoningEffort) {
return profile.DefaultReasoningEffort
}
for _, level := range levels {
if level == ReasoningEffortMedium {
return level
@@ -196,13 +224,6 @@ func DefaultReasoningEffortForProvider(providerValue account.Provider, publicMod
return ReasoningEffortNone
}
func reasoningEffortsForSlug(slug string) []string {
if levels, ok := grokReasoningCapabilities[slug]; ok {
return append([]string(nil), levels...)
}
return []string{ReasoningEffortNone}
}
// ReasoningAliasPublicIDs returns effort-suffixed aliases for a base public model ID.
// Models with fewer than two controllable levels produce no aliases (base name is enough).
// Only levels the model truly supports are included — never a blanket none/low/medium/high/xhigh/max template.
@@ -0,0 +1,119 @@
package model
import (
"sort"
"strings"
"sync"
)
// UpstreamModelProfile carries the per-model metadata the Grok Build
// /v1/models catalog advertises. grok-build (xai-grok-shell remote/client.rs)
// drives its reasoning-effort menu, default effort, and context budget from
// exactly these fields instead of a compiled-in table, so the gateway mirrors
// the same source of truth once an account has synchronized its catalog.
type UpstreamModelProfile struct {
// ReasoningEfforts is the ordered menu from `reasoning_efforts[].value`,
// filtered to the grok-build wire vocabulary. Empty means the catalog did
// not publish a menu and static capabilities apply.
ReasoningEfforts []string
// DefaultReasoningEffort is the menu entry flagged `default: true`, or the
// top-level `reasoning_effort` when the menu carries no flag.
DefaultReasoningEffort string
// SupportsReasoningEffort mirrors `supports_reasoning_effort`.
SupportsReasoningEffort bool
// ContextWindow mirrors `context_window` (tokens); zero when absent.
ContextWindow int
// MaxCompletionTokens mirrors `max_completion_tokens`; zero when absent.
MaxCompletionTokens int
// SupportsBackendSearch mirrors `supports_backend_search`.
SupportsBackendSearch bool
}
var (
upstreamProfilesMu sync.RWMutex
upstreamProfiles = map[string]UpstreamModelProfile{}
)
// NormalizeUpstreamProfile validates and canonicalizes a catalog profile:
// effort values are lower-cased, de-duplicated, restricted to known tiers,
// and the default is dropped when the menu does not contain it.
func NormalizeUpstreamProfile(profile UpstreamModelProfile) UpstreamModelProfile {
efforts := make([]string, 0, len(profile.ReasoningEfforts))
seen := make(map[string]struct{}, len(profile.ReasoningEfforts))
for _, raw := range profile.ReasoningEfforts {
value := strings.ToLower(strings.TrimSpace(raw))
if !IsKnownReasoningEffort(value) {
continue
}
if _, exists := seen[value]; exists {
continue
}
seen[value] = struct{}{}
efforts = append(efforts, value)
}
profile.ReasoningEfforts = efforts
profile.DefaultReasoningEffort = strings.ToLower(strings.TrimSpace(profile.DefaultReasoningEffort))
if _, exists := seen[profile.DefaultReasoningEffort]; !exists {
profile.DefaultReasoningEffort = ""
}
if len(efforts) > 0 {
profile.SupportsReasoningEffort = true
}
if profile.ContextWindow < 0 {
profile.ContextWindow = 0
}
if profile.MaxCompletionTokens < 0 {
profile.MaxCompletionTokens = 0
}
return profile
}
// RegisterUpstreamModelProfile stores the catalog profile for an upstream model
// slug (without provider prefix). Later registrations replace earlier ones so a
// catalog refresh always wins.
func RegisterUpstreamModelProfile(upstreamModel string, profile UpstreamModelProfile) {
slug := strings.ToLower(externalModelSlug(upstreamModel))
if slug == "" {
return
}
normalized := NormalizeUpstreamProfile(profile)
upstreamProfilesMu.Lock()
upstreamProfiles[slug] = normalized
upstreamProfilesMu.Unlock()
}
// UpstreamProfile returns the registered catalog profile for a model slug.
func UpstreamProfile(upstreamModel string) (UpstreamModelProfile, bool) {
slug := strings.ToLower(externalModelSlug(upstreamModel))
if slug == "" {
return UpstreamModelProfile{}, false
}
upstreamProfilesMu.RLock()
profile, ok := upstreamProfiles[slug]
upstreamProfilesMu.RUnlock()
if !ok {
return UpstreamModelProfile{}, false
}
profile.ReasoningEfforts = append([]string(nil), profile.ReasoningEfforts...)
return profile, true
}
// UpstreamProfileSlugs lists registered slugs in stable order (for admin/debug views).
func UpstreamProfileSlugs() []string {
upstreamProfilesMu.RLock()
slugs := make([]string, 0, len(upstreamProfiles))
for slug := range upstreamProfiles {
slugs = append(slugs, slug)
}
upstreamProfilesMu.RUnlock()
sort.Strings(slugs)
return slugs
}
// ResetUpstreamProfiles clears every registered profile. Tests use it to
// isolate catalog state between cases.
func ResetUpstreamProfiles() {
upstreamProfilesMu.Lock()
upstreamProfiles = map[string]UpstreamModelProfile{}
upstreamProfilesMu.Unlock()
}
@@ -0,0 +1,94 @@
package model
import (
"reflect"
"testing"
"github.com/chenyme/grok2api/backend/internal/domain/account"
)
func TestUpstreamProfileOverridesStaticReasoningTable(t *testing.T) {
ResetUpstreamProfiles()
t.Cleanup(ResetUpstreamProfiles)
// Unknown model: none-only until the catalog says otherwise.
if got := SupportedReasoningEfforts("grok-9.9"); !reflect.DeepEqual(got, []string{ReasoningEffortNone}) {
t.Fatalf("unknown model efforts = %v", got)
}
RegisterUpstreamModelProfile("grok-9.9", UpstreamModelProfile{
ReasoningEfforts: []string{"XHigh", "high", "medium", "low", "high", "bogus"},
DefaultReasoningEffort: "high",
ContextWindow: 500000,
})
want := []string{ReasoningEffortXHigh, ReasoningEffortHigh, ReasoningEffortMedium, ReasoningEffortLow}
if got := SupportedReasoningEfforts("grok-9.9"); !reflect.DeepEqual(got, want) {
t.Fatalf("catalog efforts = %v, want %v", got, want)
}
if got := SupportedReasoningEfforts("Build/grok-9.9"); !reflect.DeepEqual(got, want) {
t.Fatalf("prefixed catalog efforts = %v", got)
}
if !SupportsReasoningEffort("grok-9.9", "xhigh") || SupportsReasoningEffort("grok-9.9", "max") {
t.Fatal("menu membership must drive SupportsReasoningEffort")
}
// Catalog default wins over the static medium preference.
if got := DefaultReasoningEffort("grok-9.9"); got != ReasoningEffortHigh {
t.Fatalf("default = %q", got)
}
if got := DefaultReasoningEffortForProvider(account.ProviderBuild, "grok-9.9"); got != ReasoningEffortHigh {
t.Fatalf("provider default = %q", got)
}
// Aliases follow the live menu.
if base, effort, ok := ParseReasoningModelAlias("grok-9.9-xhigh"); !ok || base != "grok-9.9" || effort != ReasoningEffortXHigh {
t.Fatalf("alias parse = %q %q %v", base, effort, ok)
}
if got := ReasoningAliasPublicIDs("grok-9.9"); !reflect.DeepEqual(got, []string{"grok-9.9-xhigh", "grok-9.9-high", "grok-9.9-medium", "grok-9.9-low"}) {
t.Fatalf("aliases = %v", got)
}
profile, ok := UpstreamProfile("Build/grok-9.9")
if !ok || profile.ContextWindow != 500000 || !profile.SupportsReasoningEffort || profile.DefaultReasoningEffort != "high" {
t.Fatalf("profile = %#v ok=%v", profile, ok)
}
}
func TestUpstreamProfileWithoutMenuKeepsStaticTable(t *testing.T) {
ResetUpstreamProfiles()
t.Cleanup(ResetUpstreamProfiles)
RegisterUpstreamModelProfile("grok-4.5", UpstreamModelProfile{ContextWindow: 256000})
want := []string{ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh}
if got := SupportedReasoningEfforts("grok-4.5"); !reflect.DeepEqual(got, want) {
t.Fatalf("efforts = %v", got)
}
if got := DefaultReasoningEffort("grok-4.5"); got != ReasoningEffortMedium {
t.Fatalf("default = %q", got)
}
}
func TestUpstreamProfileDefaultDroppedWhenNotInMenu(t *testing.T) {
profile := NormalizeUpstreamProfile(UpstreamModelProfile{ReasoningEfforts: []string{"low", "high"}, DefaultReasoningEffort: "xhigh"})
if profile.DefaultReasoningEffort != "" {
t.Fatalf("default = %q", profile.DefaultReasoningEffort)
}
}
func TestMinimalIsAKnownTierAndAliasSuffix(t *testing.T) {
ResetUpstreamProfiles()
t.Cleanup(ResetUpstreamProfiles)
if !IsKnownReasoningEffort("minimal") || !IsKnownReasoningEffort("MAX") || IsKnownReasoningEffort("ultra") {
t.Fatal("known tier vocabulary drifted from grok-build")
}
RegisterUpstreamModelProfile("grok-9.8", UpstreamModelProfile{ReasoningEfforts: []string{"minimal", "low", "max"}})
if base, effort, ok := ParseReasoningModelAlias("grok-9.8-minimal"); !ok || base != "grok-9.8" || effort != ReasoningEffortMinimal {
t.Fatalf("alias = %q %q %v", base, effort, ok)
}
if base, effort, ok := ParseReasoningModelAlias("grok-9.8-max"); !ok || base != "grok-9.8" || effort != ReasoningEffortMax {
t.Fatalf("alias = %q %q %v", base, effort, ok)
}
}
func TestGrok47StaticCapabilities(t *testing.T) {
ResetUpstreamProfiles()
want := []string{ReasoningEffortLow, ReasoningEffortMedium, ReasoningEffortHigh, ReasoningEffortXHigh}
if got := SupportedReasoningEfforts("grok-4.7"); !reflect.DeepEqual(got, want) {
t.Fatalf("grok-4.7 efforts = %v", got)
}
}
+1 -1
View File
@@ -29,7 +29,7 @@ const (
ClearanceModeOnDemand = "on_demand"
DefaultStatsigSignerURL = "https://grok.wodf.de/sign"
DefaultFlareSolverrURL = "http://flaresolverr:8191"
RecommendedBuildClientVersion = "1.0.4"
RecommendedBuildClientVersion = "1.0.40"
RecommendedBuildUserAgent = "grok-shell/" + RecommendedBuildClientVersion + " (linux; x86_64)"
maxServerBodyBytes = 256 << 20
+2 -2
View File
@@ -281,13 +281,13 @@ func TestBuildResponseHeaderTimeoutIsRuntimeOnly(t *testing.T) {
func TestDefaultGrokBuildClientVersionMatchesLocalBaseline(t *testing.T) {
build := defaultConfig().Provider.Build
if RecommendedBuildClientVersion != "1.0.4" {
if RecommendedBuildClientVersion != "1.0.40" {
t.Fatalf("recommended clientVersion = %q", RecommendedBuildClientVersion)
}
if build.ClientVersion != RecommendedBuildClientVersion {
t.Fatalf("clientVersion = %q", build.ClientVersion)
}
if RecommendedBuildUserAgent != "grok-shell/1.0.4 (linux; x86_64)" {
if RecommendedBuildUserAgent != "grok-shell/1.0.40 (linux; x86_64)" {
t.Fatalf("recommended userAgent = %q", RecommendedBuildUserAgent)
}
if build.UserAgent != RecommendedBuildUserAgent {
@@ -12,6 +12,7 @@ import (
"fmt"
"io"
"log/slog"
"math"
"net/http"
"strconv"
"strings"
@@ -810,6 +811,22 @@ type buildModelCatalogEntry struct {
ModelID string `json:"modelId"`
Hidden bool `json:"hidden"`
} `json:"_meta"`
// Reasoning and budget metadata, mirroring the keys grok-build reads in
// xai-grok-shell remote/client.rs parse_remote_model_value. Snake and camel
// case spellings are both accepted there, so both are accepted here.
ContextWindow int64 `json:"context_window"`
ContextWindowCamel int64 `json:"contextWindow"`
MaxCompletionTokens int64 `json:"max_completion_tokens"`
MaxCompletionTokensCamel int64 `json:"maxCompletionTokens"`
ReasoningEffort string `json:"reasoning_effort"`
ReasoningEffortCamel string `json:"reasoningEffort"`
SupportsReasoningEffort *bool `json:"supports_reasoning_effort"`
SupportsReasoningCamel *bool `json:"supportsReasoningEffort"`
SupportsBackendSearch bool `json:"supports_backend_search"`
// reasoning_efforts entries are either bare strings ("high") or objects
// {value,id,label,description,default}; decode lazily per entry.
ReasoningEfforts []json.RawMessage `json:"reasoning_efforts"`
ReasoningEffortsCamel []json.RawMessage `json:"reasoningEfforts"`
}
// modelIdentifier keeps the legacy top-level id authoritative and uses the
@@ -823,6 +840,81 @@ func (e buildModelCatalogEntry) modelIdentifier() string {
return firstNonEmpty(e.ID, e.Model, e.ModelID, e.Meta.Model, e.Meta.ModelID)
}
// reasoningMenu decodes reasoning_efforts the way grok-build's
// parse_reasoning_effort_options does: each entry is a bare effort string or an
// object with a required `value`; unreadable entries are skipped instead of
// discarding the whole menu. It returns the ordered values and the entry
// flagged default (empty when none is flagged).
func (e buildModelCatalogEntry) reasoningMenu() (values []string, defaultValue string) {
raw := e.ReasoningEfforts
if len(raw) == 0 {
raw = e.ReasoningEffortsCamel
}
for _, entry := range raw {
var bare string
if err := json.Unmarshal(entry, &bare); err == nil {
if bare = strings.TrimSpace(bare); bare != "" {
values = append(values, bare)
}
continue
}
var option struct {
Value string `json:"value"`
Default bool `json:"default"`
}
if err := json.Unmarshal(entry, &option); err != nil {
continue
}
value := strings.TrimSpace(option.Value)
if value == "" {
continue
}
values = append(values, value)
if option.Default && defaultValue == "" {
defaultValue = value
}
}
return values, defaultValue
}
// upstreamProfile projects the catalog entry onto the domain profile.
func (e buildModelCatalogEntry) upstreamProfile() modeldomain.UpstreamModelProfile {
menu, menuDefault := e.reasoningMenu()
supports := false
switch {
case e.SupportsReasoningEffort != nil:
supports = *e.SupportsReasoningEffort
case e.SupportsReasoningCamel != nil:
supports = *e.SupportsReasoningCamel
}
contextWindow := e.ContextWindow
if contextWindow <= 0 {
contextWindow = e.ContextWindowCamel
}
maxCompletion := e.MaxCompletionTokens
if maxCompletion <= 0 {
maxCompletion = e.MaxCompletionTokensCamel
}
return modeldomain.UpstreamModelProfile{
ReasoningEfforts: menu,
DefaultReasoningEffort: firstNonEmpty(menuDefault, e.ReasoningEffort, e.ReasoningEffortCamel),
SupportsReasoningEffort: supports,
ContextWindow: clampInt(contextWindow),
MaxCompletionTokens: clampInt(maxCompletion),
SupportsBackendSearch: e.SupportsBackendSearch,
}
}
func clampInt(value int64) int {
if value <= 0 {
return 0
}
if value > math.MaxInt32 {
return math.MaxInt32
}
return int(value)
}
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)
@@ -869,6 +961,9 @@ func (a *Adapter) listModelsAt(ctx context.Context, credential account.Credentia
}
seen[identifier] = struct{}{}
models = append(models, identifier)
// Publish the live reasoning menu / context budget so effort validation,
// aliases, and catalog output follow the upstream catalog like grok-build does.
modeldomain.RegisterUpstreamModelProfile(identifier, item.upstreamProfile())
}
a.recordModelsETag(credential.ID, resp.Header.Get("ETag"))
return models, resp.StatusCode, nil
@@ -1034,6 +1129,9 @@ func (a *Adapter) applyHeaders(req *http.Request, credential account.Credential,
if sessionID != "" {
req.Header.Set("x-grok-session-id", sessionID)
req.Header.Set("x-grok-conv-id", sessionID)
// grok-build derives x-grok-conv-group-id from the root session so the
// proxy can group a root conversation with its subagent descendants.
req.Header.Set("x-grok-conv-group-id", grokConversationGroupID(sessionID))
}
req.Header.Set("x-grok-req-id", requestID)
// The gateway cannot reliably recover the CLI prompt index from a stateless API request.
@@ -1080,6 +1178,17 @@ func grokSessionID(promptCacheKey string) (string, error) {
return uuid.NewHash(sha256.New(), uuid.NameSpaceURL, []byte("grok2api:session:"+key), 8).String(), nil
}
// grokConversationGroupIDNamespace mirrors xai-grok-shell `CONVERSATION_GROUP_NAMESPACE`.
const grokConversationGroupIDNamespace = "xai:grok-build:conversation-group:"
// grokConversationGroupID reproduces grok-build `derive_conversation_group_id`:
// UUIDv5(NAMESPACE_OID, namespace + root_session_id). The gateway treats each
// stable session as its own root conversation, so the group id derives from the
// same session id sent as x-grok-conv-id.
func grokConversationGroupID(rootSessionID string) string {
return uuid.NewSHA1(uuid.NameSpaceOID, []byte(grokConversationGroupIDNamespace+rootSessionID)).String()
}
func injectPromptCacheKey(body []byte, clientKey string) ([]byte, error) {
key := strings.TrimSpace(clientKey)
if key == "" {
@@ -10,6 +10,7 @@ import (
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
@@ -278,7 +279,7 @@ func TestForwardResponseMatchesGrokBuildHeadersAndPreservesReasoning(t *testing.
}
requestUUID, requestErr := uuid.Parse(requestID)
agentUUID, agentErr := uuid.Parse(r.Header.Get("x-grok-agent-id"))
if requestErr != nil || requestUUID.Version() != uuid.Version(4) || agentErr != nil || agentUUID.Version() != uuid.Version(4) || sessionID != expectedSessionID || r.Header.Get("x-grok-conv-id") != sessionID {
if requestErr != nil || requestUUID.Version() != uuid.Version(4) || agentErr != nil || agentUUID.Version() != uuid.Version(4) || sessionID != expectedSessionID || r.Header.Get("x-grok-conv-id") != sessionID || r.Header.Get("x-grok-conv-group-id") != grokConversationGroupID(sessionID) {
t.Fatalf("client identity headers = %#v", r.Header)
}
for _, legacy := range []string{"x-grok-client-surface", "x-grok-client-name", "x-grok-conversation-id", "x-grok-session-id-legacy", "x-grok-request-id"} {
@@ -1449,3 +1450,67 @@ func TestForwardResponsePreservesTruncatedRateLimitDiagnostic(t *testing.T) {
t.Fatalf("diagnostic = %#v", response.Diagnostic)
}
}
// TestListModelsRegistersUpstreamReasoningMenu replays a real cli-chat-proxy
// /v1/models payload (grok-build 1.0.40 era) and checks the live reasoning
// menu drives domain capabilities the same way it drives grok-build's picker.
func TestListModelsRegistersUpstreamReasoningMenu(t *testing.T) {
modeldomain.ResetUpstreamProfiles()
t.Cleanup(modeldomain.ResetUpstreamProfiles)
catalog, err := os.ReadFile("testdata/build_models_catalog.json")
if err != nil {
t.Fatal(err)
}
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) {
return &http.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: make(http.Header), Body: io.NopCloser(bytes.NewReader(catalog)), Request: request}, nil
})
models, err := adapter.ListModels(context.Background(), account.Credential{EncryptedAccessToken: encrypted})
if err != nil {
t.Fatal(err)
}
if len(models) != 2 || models[0] != "grok-4.7" || models[1] != "grok-4.6" {
t.Fatalf("models = %#v", models)
}
for _, model := range models {
profile, ok := modeldomain.UpstreamProfile(model)
if !ok {
t.Fatalf("%s profile not registered", model)
}
wantMenu := []string{"xhigh", "high", "medium", "low"}
if strings.Join(profile.ReasoningEfforts, ",") != strings.Join(wantMenu, ",") || profile.DefaultReasoningEffort != "high" || !profile.SupportsReasoningEffort || profile.ContextWindow != 500000 {
t.Fatalf("%s profile = %#v", model, profile)
}
if got := modeldomain.DefaultReasoningEffort(model); got != "high" {
t.Fatalf("%s default = %q", model, got)
}
if !modeldomain.SupportsReasoningEffort(model, "xhigh") || modeldomain.SupportsReasoningEffort(model, "max") || modeldomain.SupportsReasoningEffort(model, "none") {
t.Fatalf("%s effort gate drifted from catalog", model)
}
}
if profile, _ := modeldomain.UpstreamProfile("grok-4.7"); profile.MaxCompletionTokens != 1000000 || !profile.SupportsBackendSearch {
t.Fatalf("grok-4.7 profile = %#v", profile)
}
if profile, _ := modeldomain.UpstreamProfile("grok-4.6"); profile.MaxCompletionTokens != 0 || profile.SupportsBackendSearch {
t.Fatalf("grok-4.6 profile = %#v", profile)
}
}
func TestCatalogEntryReasoningMenuAcceptsBareAndObjectEntries(t *testing.T) {
var entry buildModelCatalogEntry
if err := json.Unmarshal([]byte(`{"id":"m","reasoningEfforts":["low",{"value":"max","default":true},{"label":"no value"},"","medium"],"contextWindow":1234,"supportsReasoningEffort":true}`), &entry); err != nil {
t.Fatal(err)
}
profile := modeldomain.NormalizeUpstreamProfile(entry.upstreamProfile())
if strings.Join(profile.ReasoningEfforts, ",") != "low,max,medium" || profile.DefaultReasoningEffort != "max" || profile.ContextWindow != 1234 || !profile.SupportsReasoningEffort {
t.Fatalf("profile = %#v", profile)
}
}
@@ -203,10 +203,11 @@ func applyBuildResponseDefaults(payload map[string]json.RawMessage) (bool, error
}
// normalizeBuildReasoningEffortPayload maps client aliases to levels accepted by
// the selected Grok model. Grok 4.5 and unknown models retain the proven defensive
// xhigh/max -> high behavior for models without an xhigh wire contract. Models
// that explicitly support xhigh keep xhigh and map the client-only max alias to
// that highest verified upstream level.
// the selected Grok model. grok-build treats minimal/xhigh/max as distinct wire
// tiers, so a tier the model's catalog menu lists is forwarded verbatim. Only
// tiers the model does not offer are folded onto the nearest offered level:
// minimal -> low, max -> xhigh -> high. Grok 4.5 and unknown models therefore
// retain the proven defensive xhigh/max -> high behavior.
func normalizeBuildReasoningEffortPayload(payload map[string]json.RawMessage, model string) bool {
raw, exists := payload["reasoning"]
if !exists || isEmptyJSON(raw) {
@@ -235,22 +236,15 @@ func normalizeBuildReasoningEffortPayload(payload map[string]json.RawMessage, mo
if err := json.Unmarshal(reasoning["effort"], &effort); err != nil {
return false
}
requested := strings.ToLower(strings.TrimSpace(effort))
var normalized string
switch strings.ToLower(strings.TrimSpace(effort)) {
case "minimal":
normalized = modeldomain.ReasoningEffortLow
case "xhigh":
if modeldomain.SupportsReasoningEffort(model, modeldomain.ReasoningEffortXHigh) {
normalized = modeldomain.ReasoningEffortXHigh
} else {
normalized = modeldomain.ReasoningEffortHigh
}
case "max":
if modeldomain.SupportsReasoningEffort(model, modeldomain.ReasoningEffortXHigh) {
normalized = modeldomain.ReasoningEffortXHigh
} else {
normalized = modeldomain.ReasoningEffortHigh
}
switch requested {
case modeldomain.ReasoningEffortMinimal:
normalized = foldBuildReasoningEffort(model, modeldomain.ReasoningEffortMinimal, modeldomain.ReasoningEffortLow)
case modeldomain.ReasoningEffortXHigh:
normalized = foldBuildReasoningEffort(model, modeldomain.ReasoningEffortXHigh, modeldomain.ReasoningEffortHigh)
case modeldomain.ReasoningEffortMax:
normalized = foldBuildReasoningEffort(model, modeldomain.ReasoningEffortMax, modeldomain.ReasoningEffortXHigh, modeldomain.ReasoningEffortHigh)
default:
return false
}
@@ -262,6 +256,18 @@ func normalizeBuildReasoningEffortPayload(payload map[string]json.RawMessage, mo
return true
}
// foldBuildReasoningEffort returns the first candidate tier the model offers,
// falling back to the last candidate when none is offered. Candidates are
// ordered from the requested tier down to the proven safe level.
func foldBuildReasoningEffort(model string, candidates ...string) string {
for _, candidate := range candidates {
if modeldomain.SupportsReasoningEffort(model, candidate) {
return candidate
}
}
return candidates[len(candidates)-1]
}
// patchReasoningTextTypes 对齐官方 CLI 的序列化后修补:Responses 上游要求
// reasoning.content[*] 必须携带 type=reasoning_text,即使部分客户端只发送 text。
func patchReasoningTextTypes(payload map[string]json.RawMessage) {
@@ -62,7 +62,17 @@ func TestNormalizeBuildReasoningEffort(t *testing.T) {
{name: "minimal maps to low", model: "grok-4.6", effort: "minimal", want: "low"},
{name: "high", model: "grok-4.5", effort: "high", want: "high"},
{name: "medium", model: "grok-4.5", effort: "medium", want: "medium"},
// Catalog-driven menus (grok-build reasoning_efforts) override the static table.
{name: "catalog max forwarded verbatim", model: "grok-menu-max", effort: "max", want: "max"},
{name: "catalog minimal forwarded verbatim", model: "grok-menu-max", effort: "minimal", want: "minimal"},
{name: "catalog without xhigh folds max to high", model: "grok-menu-plain", effort: "max", want: "high"},
{name: "catalog without xhigh folds xhigh to high", model: "grok-menu-plain", effort: "XHIGH", want: "high"},
{name: "catalog without low folds minimal to low fallback", model: "grok-menu-plain", effort: "minimal", want: "low"},
}
modeldomain.ResetUpstreamProfiles()
t.Cleanup(modeldomain.ResetUpstreamProfiles)
modeldomain.RegisterUpstreamModelProfile("grok-menu-max", modeldomain.UpstreamModelProfile{ReasoningEfforts: []string{"minimal", "low", "medium", "high", "xhigh", "max"}})
modeldomain.RegisterUpstreamModelProfile("grok-menu-plain", modeldomain.UpstreamModelProfile{ReasoningEfforts: []string{"medium", "high"}})
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
body := []byte(`{"reasoning":{"effort":"` + test.effort + `"},"input":"hello"}`)
@@ -273,7 +273,7 @@ func TestRecoverReasoningDecodeFailureResetsSessionWithoutOpaqueInput(t *testing
}
return jsonHTTPResponse(request, http.StatusBadRequest, `{"error":"Could not decode the compaction blob. Ensure it is unmodified from the compact response."}`), nil
case 2:
if request.Header.Get("x-grok-session-id") != "" || request.Header.Get("x-grok-conv-id") != "" || strings.Contains(string(data), `"prompt_cache_key"`) {
if request.Header.Get("x-grok-session-id") != "" || request.Header.Get("x-grok-conv-id") != "" || request.Header.Get("x-grok-conv-group-id") != "" || strings.Contains(string(data), `"prompt_cache_key"`) {
t.Fatalf("stateless recovery headers=%#v body=%s", request.Header, data)
}
return jsonHTTPResponse(request, http.StatusOK, `{"id":"resp_ok","status":"completed","output":[]}`), nil
@@ -27,3 +27,19 @@ func TestGrokSessionIDStableForSameKey(t *testing.T) {
t.Fatalf("unstable: first=%q second=%q err=%v", first, second, err)
}
}
func TestGrokConversationGroupIDMatchesGrokBuildDerivation(t *testing.T) {
// Reference vector: uuid5(NAMESPACE_OID, "xai:grok-build:conversation-group:" + root_session_id),
// identical to xai-grok-shell `derive_conversation_group_id`.
const root = "0f4c7a1e-6c1b-5a0e-8e6c-3b0f6a6a2a1d"
got := grokConversationGroupID(root)
if got != "d5de345a-3509-59bc-b73c-7d33029d840b" {
t.Fatalf("conversation group id = %q", got)
}
if again := grokConversationGroupID(root); again != got {
t.Fatalf("unstable: first=%q second=%q", got, again)
}
if other := grokConversationGroupID("another-root"); other == got {
t.Fatalf("different roots must not share a group id: %q", other)
}
}
@@ -0,0 +1,100 @@
{
"object": "list",
"data": [
{
"id": "grok-4.7",
"object": "model",
"owned_by": "xAI",
"model": "grok-4.7",
"model_family": "xai",
"name": "Grok 4.7",
"description": "SpaceXAI's latest frontier model",
"context_window": 500000,
"auto_compact_threshold_percent": 80,
"system_prompt_label": "Grok 4.7",
"max_completion_tokens": 1000000,
"api_backend": "responses",
"reasoning_effort": "high",
"supports_reasoning_effort": true,
"reasoning_efforts": [
{
"id": "xhigh",
"value": "xhigh",
"label": "Extra High",
"description": "Maximum reasoning for the hardest tasks.",
"default": false
},
{
"id": "high",
"value": "high",
"label": "High",
"description": "Thorough reasoning and quality. Recommended.",
"default": true
},
{
"id": "medium",
"value": "medium",
"label": "Medium",
"description": "Strong quality with a faster turnaround.",
"default": false
},
{
"id": "low",
"value": "low",
"label": "Low",
"description": "Fastest responses. Best for simple tasks.",
"default": false
}
],
"supports_backend_search": true,
"compactions_remaining": 1,
"compaction_at_tokens": true
},
{
"id": "grok-4.6",
"object": "model",
"owned_by": "xAI",
"model": "grok-4.6",
"model_family": "xai",
"name": "Grok 4.6",
"context_window": 500000,
"auto_compact_threshold_percent": 80,
"system_prompt_label": "Grok 4.6",
"api_backend": "responses",
"reasoning_effort": "high",
"supports_reasoning_effort": true,
"reasoning_efforts": [
{
"id": "xhigh",
"value": "xhigh",
"label": "Extra High",
"description": "Highest effort and reasoning level",
"default": false
},
{
"id": "high",
"value": "high",
"label": "High",
"description": "Higher implementation quality with extensive reasoning",
"default": true
},
{
"id": "medium",
"value": "medium",
"label": "Medium",
"description": "Balanced effort with standard implementation and testing",
"default": false
},
{
"id": "low",
"value": "low",
"label": "Low",
"description": "Quick, fast implementations",
"default": false
}
],
"compactions_remaining": 1,
"compaction_at_tokens": true
}
]
}
@@ -548,7 +548,7 @@ func TestGenerateVideoFailedStatusAndDownloadTrustedURL(t *testing.T) {
for _, key := range []string{
"Authorization", "X-XAI-Token-Auth", "x-userid",
"x-grok-model-override", "x-grok-session-id", "x-grok-agent-id",
"x-grok-conv-id", "x-grok-req-id", "x-grok-conversation-id",
"x-grok-conv-id", "x-grok-conv-group-id", "x-grok-req-id", "x-grok-conversation-id",
"x-grok-session-id-legacy", "x-grok-request-id",
"x-grok-client-version", "x-grok-client-identifier",
} {
@@ -107,10 +107,10 @@ func convertMessagesRequestWithReasoningReplay(body []byte, model string, cache
if request.OutputConfig != nil && request.OutputConfig.Effort != "" {
effort = request.OutputConfig.Effort
}
// Every grok-build wire tier passes through; the Build normalizer folds
// tiers the selected model's catalog menu does not offer.
switch effort {
case "minimal":
effort = "low"
case "low", "medium", "high", "xhigh", "max":
case "minimal", "low", "medium", "high", "xhigh", "max":
default:
return nil, ResponseOptions{}, fmt.Errorf("不支持 output_config.effort=%q", effort)
}
@@ -69,12 +69,13 @@ type codexModelCatalog struct {
}
var codexReasoningDescriptions = map[string]string{
"none": "No reasoning",
"low": "Fast responses with lighter reasoning",
"medium": "Balances speed and reasoning depth for everyday tasks",
"high": "Greater reasoning depth for complex problems",
"xhigh": "Extra high reasoning depth for complex problems",
"max": "Maximum reasoning depth for the hardest problems",
"none": "No reasoning",
"minimal": "Minimal reasoning for the fastest responses",
"low": "Fast responses with lighter reasoning",
"medium": "Balances speed and reasoning depth for everyday tasks",
"high": "Greater reasoning depth for complex problems",
"xhigh": "Extra high reasoning depth for complex problems",
"max": "Maximum reasoning depth for the hardest problems",
}
type grokModelCapability struct {
@@ -88,6 +89,7 @@ type grokModelCapability struct {
var grokCapabilities = map[string]grokModelCapability{
"grok-4.5": {500000, "xAI Grok 4.5 frontier model with reasoning and vision.", true},
"grok-4.6": {500000, "xAI Grok 4.6 frontier model with reasoning and vision.", true},
"grok-4.7": {500000, "xAI Grok 4.7 frontier model with reasoning and vision.", true},
"grok-4.3": {1000000, "xAI Grok 4.3 high-capacity reasoning model.", true},
"grok-build-0.1": {256000, "xAI Grok Build 0.1 coding model.", false},
"grok-4.20-0309-reasoning": {2000000, "xAI Grok 4.20 reasoning model.", true},
@@ -109,10 +111,18 @@ func lookupGrokCapability(providerValue account.Provider, slug string) (grokMode
slug = base
}
levels := modeldomain.SupportedReasoningEffortsForProvider(providerValue, slug)
if capability, ok := grokCapabilities[slug]; ok {
return capability, levels
capability, ok := grokCapabilities[slug]
if !ok {
capability = grokDefaultCapability
}
return grokDefaultCapability, levels
// The live Build catalog (context_window) is authoritative over the static
// table once an account has synchronized it, exactly like grok-build.
if providerValue == account.ProviderBuild {
if profile, exists := modeldomain.UpstreamProfile(slug); exists && profile.ContextWindow > 0 {
capability.contextWindow = profile.ContextWindow
}
}
return capability, levels
}
func codexVisibilityForCapability(capability modeldomain.Capability) string {
@@ -47,9 +47,9 @@ func TestSettingsResponseIncludesBuildTokenAuth(t *testing.T) {
func TestSettingsResponseIncludesRecommendedBuildBaseline(t *testing.T) {
response := newSettingsResponse(settingsapp.Snapshot{RecommendedProviderBuild: settingsapp.ProviderBuildRecommendation{
ClientVersion: "1.0.4", UserAgent: "grok-shell/1.0.4 (linux; x86_64)",
ClientVersion: "1.0.40", UserAgent: "grok-shell/1.0.40 (linux; x86_64)",
}})
if response.RecommendedProviderBuild.ClientVersion != "1.0.4" || response.RecommendedProviderBuild.UserAgent == "" {
if response.RecommendedProviderBuild.ClientVersion != "1.0.40" || response.RecommendedProviderBuild.UserAgent == "" {
t.Fatalf("recommended build = %#v", response.RecommendedProviderBuild)
}
}
@@ -35,7 +35,7 @@ export type AuditDTO = {
provider: "grok_build" | "grok_web" | "grok_console";
operation: "responses" | "compaction" | "chat" | "messages" | "image" | "image_edit" | "video" | "tts" | "stt" | "realtime" | "voice";
usageSource: "upstream" | "estimated" | "none";
reasoningEffort?: "auto" | "none" | "low" | "medium" | "high" | "xhigh" | "fixed";
reasoningEffort?: "auto" | "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max" | "fixed";
accountId?: string;
accountName?: string;
egressNodeId?: string;
@@ -147,7 +147,7 @@ const auditValidator = hasShape({
id: isString, requestId: isString, clientKeyId: isString, clientKeyName: isOptional(isString), clientIp: isOptional(isString), modelRouteId: isString,
modelPublicId: isOptional(isString), modelUpstreamModel: isOptional(isString), provider: isOneOf("grok_build", "grok_web", "grok_console"),
operation: isOneOf("responses", "compaction", "chat", "messages", "image", "image_edit", "video", "tts", "stt", "realtime", "voice"), usageSource: isOneOf("upstream", "estimated", "none"),
reasoningEffort: isOptional(isOneOf("auto", "none", "low", "medium", "high", "xhigh", "fixed")),
reasoningEffort: isOptional(isOneOf("auto", "none", "minimal", "low", "medium", "high", "xhigh", "max", "fixed")),
accountId: isOptional(isString), accountName: isOptional(isString),
egressNodeId: isOptional(isString), egressNodeName: isOptional(isString),
egressScope: isOptional(isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset", "grok_console_asset")), egressMode: isOptional(isOneOf("direct", "proxy")),
@@ -667,10 +667,12 @@ function UsageMetric({ label, value, reasoningEffort }: {
function reasoningEffortTone(effort: NonNullable<AuditDTO["reasoningEffort"]>): string {
switch (effort) {
case "none": return "text-muted-foreground";
case "minimal": return "text-teal-600 dark:text-teal-400";
case "low": return "text-sky-600 dark:text-sky-400";
case "medium": return "text-amber-600 dark:text-amber-400";
case "high": return "text-orange-600 dark:text-orange-400";
case "xhigh": return "text-rose-600 dark:text-rose-400";
case "max": return "text-fuchsia-600 dark:text-fuchsia-400";
case "auto": return "text-violet-600 dark:text-violet-400";
case "fixed": return "text-indigo-600 dark:text-indigo-400";
}