From 8d61e8c212e7a46a5bc35303a15f881df08c52ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=9D=9A?= <578376659@qq.com> Date: Sun, 22 Nov 2026 19:03:41 +0800 Subject: [PATCH] feat(codex): give Codex a model catalog for gateways it does not know Codex falls back to its built-in metadata for a model it has never heard of. That metadata understates the context window of a model served by another gateway and makes the CLI warn on every turn, so a run against such a gateway truncates turns early and complains about a model the user deliberately configured. The platform now writes a model catalog next to the CLI's own configuration and passes it as model_catalog_json. The catalog describes the models of the user's personal catalog and of the gateway it points at, plus the model of the current turn. A model the gateway does not publish a window for gets a conservative one, because Codex's fallback is smaller still. A turn without a personal catalog and without a custom Base URL keeps the CLI's own catalog, which is right for OpenAI's own endpoint. A catalog that cannot be written does not fail the turn: the CLI still runs and only loses the real window. --- internal/engine/codex_catalog.go | 30 +++ internal/engine/codex_catalog_test.go | 29 +++ internal/engine/run_environment.go | 1 + internal/httpapi/assistant.go | 1 + internal/httpapi/assistant_codex_catalog.go | 47 ++++ .../httpapi/assistant_codex_catalog_test.go | 77 ++++++ internal/httpapi/assistant_engine_cli.go | 4 + internal/httpapi/assistant_engine_codex.go | 2 +- internal/runtime/codex_model_catalog.go | 223 ++++++++++++++++++ internal/runtime/codex_model_catalog_test.go | 175 ++++++++++++++ internal/runtime/command_binding.go | 16 +- internal/runtime/runtime.go | 16 +- 12 files changed, 614 insertions(+), 7 deletions(-) create mode 100644 internal/engine/codex_catalog.go create mode 100644 internal/engine/codex_catalog_test.go create mode 100644 internal/httpapi/assistant_codex_catalog.go create mode 100644 internal/httpapi/assistant_codex_catalog_test.go create mode 100644 internal/runtime/codex_model_catalog.go create mode 100644 internal/runtime/codex_model_catalog_test.go diff --git a/internal/engine/codex_catalog.go b/internal/engine/codex_catalog.go new file mode 100644 index 000000000..7af7371e0 --- /dev/null +++ b/internal/engine/codex_catalog.go @@ -0,0 +1,30 @@ +package engine + +import ( + "strings" + + "agentflow/internal/domain" + "agentflow/internal/runtime" +) + +// codexCatalogModels lists the models a Codex run may use, so that Codex +// does not fall back to its built-in metadata for a model it has never heard +// of. The fallback understates the context window of a model served by +// another gateway. +// +// The personal catalog is the source of truth: it is what the user chose in +// 个人配置. A run without one keeps Codex's own catalog. +func (e *Engine) codexCatalogModels(user domain.User) []runtime.CodexModel { + if len(user.CodexModels) == 0 { + return nil + } + out := make([]runtime.CodexModel, 0, len(user.CodexModels)) + for _, model := range user.CodexModels { + id := strings.TrimSpace(model.ID) + if id == "" { + continue + } + out = append(out, runtime.CodexModel{ID: id, Name: strings.TrimSpace(model.Name)}) + } + return out +} diff --git a/internal/engine/codex_catalog_test.go b/internal/engine/codex_catalog_test.go new file mode 100644 index 000000000..6be34e4ae --- /dev/null +++ b/internal/engine/codex_catalog_test.go @@ -0,0 +1,29 @@ +package engine + +import ( + "testing" + + "agentflow/internal/domain" +) + +func TestCodexCatalogModelsUsesThePersonalCatalog(t *testing.T) { + e := &Engine{} + user := domain.User{CodexModels: []domain.CLIModel{ + {ID: " domestic-model ", Name: " Domestic Model "}, + {ID: "", Name: "no id"}, + }} + got := e.codexCatalogModels(user) + if len(got) != 1 { + t.Fatalf("models = %+v", got) + } + if got[0].ID != "domestic-model" || got[0].Name != "Domestic Model" { + t.Fatalf("model = %+v", got[0]) + } +} + +func TestCodexCatalogModelsWithoutAPersonalCatalog(t *testing.T) { + e := &Engine{} + if got := e.codexCatalogModels(domain.User{}); got != nil { + t.Fatalf("a user without a catalog keeps the CLI one: %+v", got) + } +} diff --git a/internal/engine/run_environment.go b/internal/engine/run_environment.go index 51e08da65..8a24994d8 100644 --- a/internal/engine/run_environment.go +++ b/internal/engine/run_environment.go @@ -236,6 +236,7 @@ func (e *Engine) resolveRunCredentials(run domain.Run) runtime.RunCredentials { credentials.GitUserEmail = identity.email if user, ok := e.repo.User(userID); ok { credentials.Codex = runtime.ProviderCredential{APIKey: user.CodexAPIKey, BaseURL: user.CodexBaseURL} + credentials.CodexModels = e.codexCatalogModels(user) credentials.ClaudeCode = runtime.ProviderCredential{APIKey: user.ClaudeCodeAPIKey, BaseURL: user.ClaudeCodeBaseURL} credentials.AgentCLI = runtime.AgentCLIUserCredentials(user) } diff --git a/internal/httpapi/assistant.go b/internal/httpapi/assistant.go index 97b361e60..3499dfbdf 100644 --- a/internal/httpapi/assistant.go +++ b/internal/httpapi/assistant.go @@ -1594,6 +1594,7 @@ func runAssistantCLI(ctx context.Context, req assistantCLIRequest, user domain.U case assistantEngineCodex: if !req.RunnerLogin { engineOpts.User = runtime.ProviderCredential{APIKey: user.CodexAPIKey, BaseURL: user.CodexBaseURL} + engineOpts.Models = codexCatalogModels(ctx, user, engineModel) } inv, err = prepareAssistantCodexInvocation(engineOpts) default: diff --git a/internal/httpapi/assistant_codex_catalog.go b/internal/httpapi/assistant_codex_catalog.go new file mode 100644 index 000000000..648aef935 --- /dev/null +++ b/internal/httpapi/assistant_codex_catalog.go @@ -0,0 +1,47 @@ +package httpapi + +import ( + "context" + "strings" + + "agentflow/internal/domain" + "agentflow/internal/runtime" +) + +// codexCatalogModels lists the models the Codex catalog describes: the +// personal catalog first, then the gateway's published models. The model of +// the current turn is always included, even when the gateway does not publish +// it, because Codex would fall back for it otherwise. +// +// Codex falls back to built-in metadata for a model it does not know, and +// that metadata understates the context window of a model served by another +// gateway. The catalog gives the CLI the real numbers. +func codexCatalogModels(ctx context.Context, user domain.User, model string) []runtime.CodexModel { + seen := map[string]bool{} + var out []runtime.CodexModel + add := func(id, name string) { + id = strings.TrimSpace(id) + if id == "" || seen[id] { + return + } + seen[id] = true + out = append(out, runtime.CodexModel{ + ID: id, + Name: strings.TrimSpace(name), + Efforts: assistantModelEffortsForBaseURL(id, user.CodexModels, ""), + }) + } + for _, personal := range user.CodexModels { + add(personal.ID, personal.Name) + } + // The gateway's own list is the source of truth for what it serves. + if baseURL := strings.TrimSpace(user.CodexBaseURL); baseURL != "" && strings.TrimSpace(user.CodexAPIKey) != "" { + for _, discovered := range cachedAssistantEngineDiscovery(ctx, assistantEngineProtocol(user, assistantEngineCodex), user.CodexAPIKey, baseURL) { + add(discovered.ID, discovered.Name) + } + } + if engine, id := assistantModelEngine(model); engine == assistantEngineCodex { + add(id, id) + } + return out +} diff --git a/internal/httpapi/assistant_codex_catalog_test.go b/internal/httpapi/assistant_codex_catalog_test.go new file mode 100644 index 000000000..bf8c39aad --- /dev/null +++ b/internal/httpapi/assistant_codex_catalog_test.go @@ -0,0 +1,77 @@ +package httpapi + +import ( + "context" + "testing" + + "agentflow/internal/domain" + "agentflow/internal/runtime" +) + +func TestCodexCatalogModelsCombinesThePersonalAndThePublishedCatalog(t *testing.T) { + restore := assistantEngineDiscover + assistantEngineDiscover = func(ctx context.Context, anthropic bool, apiKey, baseURL string) ([]assistantDiscoveredModel, error) { + return []assistantDiscoveredModel{ + {ID: "published-model", Name: "Published Model"}, + {ID: "domestic-model", Name: "Published Domestic"}, + }, nil + } + t.Cleanup(func() { assistantEngineDiscover = restore }) + + user := domain.User{ + CodexAPIKey: "turn-key", + CodexBaseURL: "https://gateway.example/v1", + CodexModels: []domain.CLIModel{{ID: "domestic-model", Name: "Domestic Model"}}, + } + got := codexCatalogModels(context.Background(), user, "") + if len(got) != 2 { + t.Fatalf("models = %+v", got) + } + // The personal catalog comes first: it is what the user chose. + if got[0].ID != "domestic-model" || got[0].Name != "Domestic Model" { + t.Fatalf("the personal catalog must come first: %+v", got[0]) + } + if got[1].ID != "published-model" { + t.Fatalf("models = %+v", got) + } +} + +func TestCodexCatalogModelsIncludesTheModelOfTheTurn(t *testing.T) { + restore := assistantEngineDiscover + assistantEngineDiscover = func(ctx context.Context, anthropic bool, apiKey, baseURL string) ([]assistantDiscoveredModel, error) { + return nil, nil + } + t.Cleanup(func() { assistantEngineDiscover = restore }) + // The discovery cache is shared by the process, so the entry of an earlier + // test would answer this one. + assistantDiscoveryCache.Delete(assistantDiscoveryKey("", "turn-key", "https://gateway.example/v1")) + + user := domain.User{CodexAPIKey: "turn-key", CodexBaseURL: "https://gateway.example/v1"} + // The gateway does not publish this model, but the turn runs on it, so the + // catalog has to describe it or Codex falls back for it. + got := codexCatalogModels(context.Background(), user, "codex:turn-model") + if len(got) != 1 { + t.Fatalf("models = %+v", got) + } + if got[0].ID != "turn-model" { + t.Fatalf("model = %+v", got[0]) + } +} + +func TestCodexCatalogModelsWithoutAGateway(t *testing.T) { + // A user on the official endpoint keeps the CLI's own catalog. + user := domain.User{CodexModels: []domain.CLIModel{{ID: "personal-model"}}} + got := codexCatalogModels(context.Background(), user, "") + if len(got) != 1 || got[0].ID != "personal-model" { + t.Fatalf("models = %+v", got) + } +} + +func TestCodexCatalogModelsSkipsAnEmptyID(t *testing.T) { + user := domain.User{CodexModels: []domain.CLIModel{{ID: " ", Name: "blank"}}} + if got := codexCatalogModels(context.Background(), user, ""); len(got) != 0 { + t.Fatalf("a model without an ID must be skipped: %+v", got) + } +} + +var _ = runtime.CodexModel{} diff --git a/internal/httpapi/assistant_engine_cli.go b/internal/httpapi/assistant_engine_cli.go index c5a4dc8da..a3c7170a3 100644 --- a/internal/httpapi/assistant_engine_cli.go +++ b/internal/httpapi/assistant_engine_cli.go @@ -46,6 +46,10 @@ type assistantEngineInvocationOpts struct { ReviewOnly bool ReportOnly bool User runtime.ProviderCredential + // Models is the model catalog written for a CLI that falls back to its + // own metadata for an unknown model. Codex uses it so a model served by + // another gateway keeps its real context window. + Models []runtime.CodexModel } func assistantEngineConfigDir(engine string) string { diff --git a/internal/httpapi/assistant_engine_codex.go b/internal/httpapi/assistant_engine_codex.go index 2f87f0ffc..60214cc13 100644 --- a/internal/httpapi/assistant_engine_codex.go +++ b/internal/httpapi/assistant_engine_codex.go @@ -54,7 +54,7 @@ func prepareAssistantCodexInvocation(o assistantEngineInvocationOpts) (assistant server.request("initialize", map[string]any{"clientInfo": map[string]string{"name": "agentflow", "title": "AgentFlow", "version": "1"}}) return assistantCLIInvocation{ command: runtime.CommandSpec{Argv: argv, Provider: "codex", CredentialBindings: []runtime.CredentialBinding{runtime.BindCodex}, Stdin: stdin}, - credentials: runtime.RunCredentials{Codex: o.User}, + credentials: runtime.RunCredentials{Codex: o.User, CodexModels: o.Models}, sessionRef: thread, translate: server.translate, finish: func(ok bool) { diff --git a/internal/runtime/codex_model_catalog.go b/internal/runtime/codex_model_catalog.go new file mode 100644 index 000000000..12f005906 --- /dev/null +++ b/internal/runtime/codex_model_catalog.go @@ -0,0 +1,223 @@ +package runtime + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" +) + +// Codex falls back to built-in metadata for a model it does not know, which +// understates the context window of a model served by another gateway and +// makes the CLI warn on every turn. A gateway that serves a model outside +// OpenAI's catalog therefore needs a model catalog: Codex reads it from +// model_catalog_json. +// +// The schema is Codex's own; every field below is required by its parser +// except the ones marked optional. +type codexModelCatalog struct { + Models []codexModelInfo `json:"models"` +} + +type codexModelInfo struct { + Slug string `json:"slug"` + DisplayName string `json:"display_name"` + ContextWindow int `json:"context_window"` + MaxOutputTokens int `json:"max_output_tokens"` + ShellType string `json:"shell_type"` + Visibility string `json:"visibility"` + SupportedInAPI bool `json:"supported_in_api"` + SupportsReasoningSummary bool `json:"supports_reasoning_summaries"` + Priority int `json:"priority"` + SupportVerbosity bool `json:"support_verbosity"` + TruncationPolicy codexTruncationPolicy `json:"truncation_policy"` + ExperimentalTools []string `json:"experimental_supported_tools"` + BaseInstructions string `json:"base_instructions"` + SupportedReasoningLevels []codexReasoningEffortSpec `json:"supported_reasoning_levels"` + InputModalities []string `json:"input_modalities,omitempty"` +} + +type codexTruncationPolicy struct { + Mode string `json:"mode"` + Limit int `json:"limit"` +} + +type codexReasoningEffortSpec struct { + Effort string `json:"effort"` + Description string `json:"description"` +} + +// codexModelCatalogWindow is the window a model gets when the gateway does +// not publish one. It is deliberately generous: the catalog only has to be +// wide enough that Codex does not truncate a turn early. +const codexModelCatalogWindow = 128000 + +// codexModelCatalogOutput is the output budget used when the gateway does +// not publish one. +const codexModelCatalogOutput = 32000 + +// codexModelCatalogLimit is the truncation budget, half the window, so a +// turn leaves room for the reply. +func codexModelCatalogLimit(window int) int { + limit := window / 2 + if limit < 1024 { + limit = 1024 + } + return limit +} + +// CodexModel describes one model for the Codex catalog. +type CodexModel struct { + // ID is the model ID the CLI sends to the gateway. + ID string + // Name is the label Codex shows. + Name string + // ContextWindow is the model's real context window; 0 means unknown. + ContextWindow int + // MaxOutputTokens is the model's output budget; 0 means unknown. + MaxOutputTokens int + // Efforts are the reasoning-effort levels the model accepts. + Efforts []string +} + +// codexCatalogArg writes the model catalog for this turn and returns the path +// the CLI should read. +// +// A catalog that cannot be written is not fatal: the CLI still runs, it only +// falls back to its own metadata for a model it does not know. The turn then +// behaves like the one before the catalog existed. +func codexCatalogArg(bound CommandSpec, models []CodexModel) string { + if len(models) == 0 { + return "" + } + path, err := codexCatalogPath(bound, models) + if err != nil { + return "" + } + return path +} + +// codexCatalogPath writes the model catalog next to the CLI's own +// configuration and returns its path. The catalog lives in the private home +// of the turn, so it is written where CODEX_HOME points. +// +// An empty model list returns an empty path: Codex then keeps its own +// catalog, which is right for OpenAI's own endpoint. +func codexCatalogPath(bound CommandSpec, models []CodexModel) (string, error) { + if len(models) == 0 { + return "", nil + } + home := strings.TrimSpace(bound.environment["HOME"]) + if home == "" { + return "", fmt.Errorf("codex private home is not set") + } + codexHome := strings.TrimSpace(bound.environment["CODEX_HOME"]) + if codexHome == "" { + codexHome = filepath.Join(home, ".codex") + } + path := filepath.Join(codexHome, "models.json") + if _, err := WriteCodexModelCatalog(home, path, models); err != nil { + return "", err + } + return path, nil +} + +// codexCatalogEffortOrder is the order Codex lists its effort levels in. +// The catalog lists a subset of them, in this order. +var codexCatalogEffortOrder = []string{"minimal", "low", "medium", "high", "xhigh"} + +// WriteCodexModelCatalog writes the model catalog Codex reads through +// model_catalog_json, and returns its path. A model without a known window +// gets a conservative one, because Codex's fallback is smaller still. +// +// The file is written next to the CLI's own configuration so that it lives +// and dies with the private home of the turn. +func WriteCodexModelCatalog(home, path string, models []CodexModel) (string, error) { + if len(models) == 0 { + return "", nil + } + catalog := codexModelCatalog{Models: make([]codexModelInfo, 0, len(models))} + for _, model := range models { + if strings.TrimSpace(model.ID) == "" { + continue + } + window := model.ContextWindow + if window <= 0 { + window = codexModelCatalogWindow + } + output := model.MaxOutputTokens + if output <= 0 { + output = codexModelCatalogOutput + } + name := strings.TrimSpace(model.Name) + if name == "" { + name = model.ID + } + catalog.Models = append(catalog.Models, codexModelInfo{ + Slug: model.ID, + DisplayName: name, + ContextWindow: window, + MaxOutputTokens: output, + ShellType: "disabled", + Visibility: "list", + SupportedInAPI: true, + SupportsReasoningSummary: true, + Priority: 1, + SupportVerbosity: false, + TruncationPolicy: codexTruncationPolicy{Mode: "tokens", Limit: codexModelCatalogLimit(window)}, + ExperimentalTools: []string{}, + BaseInstructions: "You are a helpful assistant.", + SupportedReasoningLevels: codexCatalogEfforts(model.Efforts), + InputModalities: []string{"text"}, + }) + } + if len(catalog.Models) == 0 { + return "", nil + } + data, err := json.MarshalIndent(catalog, "", " ") + if err != nil { + return "", err + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return "", err + } + if err := os.WriteFile(path, data, 0o600); err != nil { + return "", err + } + return path, nil +} + +// codexCatalogEfforts keeps the levels the model accepts, in Codex's order. +// A model without levels keeps the CLI's default handling. +func codexCatalogEfforts(efforts []string) []codexReasoningEffortSpec { + allowed := map[string]bool{} + for _, effort := range efforts { + allowed[effort] = true + } + var out []codexReasoningEffortSpec + for _, effort := range codexCatalogEffortOrder { + if !allowed[effort] { + continue + } + out = append(out, codexReasoningEffortSpec{Effort: effort, Description: codexEffortDescription(effort)}) + } + return out +} + +func codexEffortDescription(effort string) string { + switch effort { + case "minimal": + return "Minimal reasoning" + case "low": + return "Low reasoning" + case "medium": + return "Medium reasoning" + case "high": + return "High reasoning" + case "xhigh": + return "Extra high reasoning" + default: + return fmt.Sprintf("%s reasoning", effort) + } +} diff --git a/internal/runtime/codex_model_catalog_test.go b/internal/runtime/codex_model_catalog_test.go new file mode 100644 index 000000000..6572726c9 --- /dev/null +++ b/internal/runtime/codex_model_catalog_test.go @@ -0,0 +1,175 @@ +package runtime + +import ( + "encoding/json" + "os" + "path/filepath" + "slices" + "strings" + "testing" +) + +func TestCodexUserProviderArgvWithCatalogAddsTheCatalog(t *testing.T) { + in := []string{"codex", "exec", "--json", "prompt"} + got, err := CodexUserProviderArgvWithCatalog(in, "https://gateway.example/v1", "/tmp/models.json") + if err != nil { + t.Fatal(err) + } + joined := strings.Join(got, " ") + if !strings.Contains(joined, `model_catalog_json="/tmp/models.json"`) { + t.Fatalf("the catalog must be passed to the CLI: %q", joined) + } + // The catalog is a config override, so it belongs with the other overrides + // and not after the prompt. + prompt := indexOf(got, "prompt") + catalog := indexOf(got, `model_catalog_json="/tmp/models.json"`) + if catalog < 0 || catalog > prompt { + t.Fatalf("the catalog must precede the prompt: %q", got) + } +} + +func TestCodexUserProviderArgvWithoutCatalogKeepsTheCLIOne(t *testing.T) { + for _, path := range []string{"", " "} { + got, err := CodexUserProviderArgvWithCatalog([]string{"codex", "exec", "prompt"}, "", path) + if err != nil { + t.Fatal(err) + } + if strings.Contains(strings.Join(got, " "), "model_catalog_json") { + t.Fatalf("no catalog must be passed for %q: %q", path, got) + } + } +} + +func indexOf(argv []string, want string) int { + for i, v := range argv { + if v == want { + return i + } + } + return -1 +} + +func TestWriteCodexModelCatalogDescribesTheModels(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "models.json") + models := []CodexModel{ + {ID: "domestic-model", Name: "Domestic Model", ContextWindow: 200000, MaxOutputTokens: 64000, Efforts: []string{"low", "high"}}, + {ID: " ", Name: "skipped"}, + } + if _, err := WriteCodexModelCatalog(dir, path, models); err != nil { + t.Fatal(err) + } + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var catalog codexModelCatalog + if err := json.Unmarshal(raw, &catalog); err != nil { + t.Fatal(err) + } + if len(catalog.Models) != 1 { + t.Fatalf("a model without an ID must be skipped: %+v", catalog.Models) + } + model := catalog.Models[0] + if model.Slug != "domestic-model" || model.DisplayName != "Domestic Model" { + t.Fatalf("model = %+v", model) + } + if model.ContextWindow != 200000 || model.MaxOutputTokens != 64000 { + t.Fatalf("the real window must survive: %+v", model) + } + // The truncation budget leaves room for the reply. + if model.TruncationPolicy.Mode != "tokens" || model.TruncationPolicy.Limit != 100000 { + t.Fatalf("truncation = %+v", model.TruncationPolicy) + } + // Only the levels the model accepts, in Codex's own order. + var efforts []string + for _, level := range model.SupportedReasoningLevels { + efforts = append(efforts, level.Effort) + } + if !slices.Equal(efforts, []string{"low", "high"}) { + t.Fatalf("efforts = %v", efforts) + } +} + +func TestWriteCodexModelCatalogUsesAConservativeWindow(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "models.json") + if _, err := WriteCodexModelCatalog(dir, path, []CodexModel{{ID: "unknown-model"}}); err != nil { + t.Fatal(err) + } + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var catalog codexModelCatalog + if err := json.Unmarshal(raw, &catalog); err != nil { + t.Fatal(err) + } + if len(catalog.Models) != 1 { + t.Fatalf("models = %+v", catalog.Models) + } + model := catalog.Models[0] + // Codex's own fallback is smaller than this, so the catalog still wins. + if model.ContextWindow != codexModelCatalogWindow { + t.Fatalf("window = %d want %d", model.ContextWindow, codexModelCatalogWindow) + } + if model.MaxOutputTokens != codexModelCatalogOutput { + t.Fatalf("output = %d want %d", model.MaxOutputTokens, codexModelCatalogOutput) + } + if model.DisplayName != "unknown-model" { + t.Fatalf("a model without a name is labelled by its ID: %q", model.DisplayName) + } +} + +func TestWriteCodexModelCatalogWithoutModelsWritesNothing(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "models.json") + got, err := WriteCodexModelCatalog(dir, path, nil) + if err != nil { + t.Fatal(err) + } + if got != "" { + t.Fatalf("no model list must produce no path: %q", got) + } + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("no file must be written: %v", err) + } +} + +func TestCodexCatalogPathUsesTheCodexHome(t *testing.T) { + home := t.TempDir() + bound := CommandSpec{environment: map[string]string{ + "HOME": home, + "CODEX_HOME": filepath.Join(home, ".codex"), + }} + path, err := codexCatalogPath(bound, []CodexModel{{ID: "m"}}) + if err != nil { + t.Fatal(err) + } + if path != filepath.Join(home, ".codex", "models.json") { + t.Fatalf("path = %q", path) + } + if _, err := os.Stat(path); err != nil { + t.Fatalf("the catalog must be written: %v", err) + } +} + +func TestCodexCatalogPathWithoutModelsWritesNothing(t *testing.T) { + bound := CommandSpec{environment: map[string]string{"HOME": t.TempDir()}} + path, err := codexCatalogPath(bound, nil) + if err != nil { + t.Fatal(err) + } + if path != "" { + t.Fatalf("path = %q", path) + } +} + +func TestCodexCatalogArgSurvivesAFailedWrite(t *testing.T) { + // A turn without a private home cannot write a catalog. The CLI still has + // to run, it only falls back to its own metadata. + bound := CommandSpec{environment: map[string]string{}} + if got := codexCatalogArg(bound, []CodexModel{{ID: "m"}}); got != "" { + t.Fatalf("a catalog that cannot be written must be skipped: %q", got) + } +} diff --git a/internal/runtime/command_binding.go b/internal/runtime/command_binding.go index f23df5d29..633517b18 100644 --- a/internal/runtime/command_binding.go +++ b/internal/runtime/command_binding.go @@ -141,7 +141,7 @@ func bindCommand(ctx context.Context, sandbox Sandbox, workspace string, command if bound.environment["CODEX_API_KEY"] == "" { return CommandSpec{}, fmt.Errorf("需求责任人未配置 Codex API Key,请在个人配置中配置") } - argv, err := CodexUserProviderArgv(bound.Argv, credentials.Codex.BaseURL) + argv, err := CodexUserProviderArgvWithCatalog(bound.Argv, credentials.Codex.BaseURL, codexCatalogArg(bound, credentials.CodexModels)) if err != nil { return CommandSpec{}, err } @@ -225,6 +225,17 @@ func bindTelemetryEnvironment(env map[string]string, telemetry *InvocationOption // only its variable name is written to argv, and the dedicated provider // prevents a fallback to the host login. The input slice is not modified. func CodexUserProviderArgv(argv []string, baseURL string) ([]string, error) { + return CodexUserProviderArgvWithCatalog(argv, baseURL, "") +} + +// CodexUserProviderArgvWithCatalog is CodexUserProviderArgv with an optional +// model catalog. The catalog path is passed to the CLI as +// model_catalog_json, so a model outside OpenAI's own catalog keeps the real +// context window instead of the CLI's fallback. +// +// An empty catalog path leaves the CLI with its own catalog, which is right +// for OpenAI's own endpoint. +func CodexUserProviderArgvWithCatalog(argv []string, baseURL, catalogPath string) ([]string, error) { if len(argv) < 2 { return nil, fmt.Errorf("invalid Codex invocation") } @@ -240,6 +251,9 @@ func CodexUserProviderArgv(argv []string, baseURL string) ([]string, error) { "-c", `model_providers.agentflow_user.wire_api="responses"`, "-c", "model_providers.agentflow_user.requires_openai_auth=false", } + if catalogPath = strings.TrimSpace(catalogPath); catalogPath != "" { + config = append(config, "-c", "model_catalog_json="+strconv.Quote(catalogPath)) + } out := make([]string, 0, len(argv)+len(config)) out = append(out, argv[:len(argv)-1]...) out = append(out, config...) diff --git a/internal/runtime/runtime.go b/internal/runtime/runtime.go index dec6cdb39..19f8c734c 100644 --- a/internal/runtime/runtime.go +++ b/internal/runtime/runtime.go @@ -59,11 +59,17 @@ func CodeBuddyUserCredential(user domain.User) CodeBuddyCredential { // RunCredentials lives only on the in-memory run sandbox handle. It is never // serialized into domain objects, run-context.json, or workspace files. type RunCredentials struct { - CodeBuddy CodeBuddyCredential - Codex ProviderCredential - ClaudeCode ProviderCredential - AgentCLI map[string]ProviderCredential - GitSSHKeys map[string]string `json:"-"` + CodeBuddy CodeBuddyCredential + Codex ProviderCredential + // CodexModels is the model catalog written for the Codex CLI. Codex falls + // back to its own metadata for a model it does not know, which understates + // the context window of a model served by another gateway. The catalog + // travels beside the credential rather than inside it, because a + // credential is compared for equality in several places. + CodexModels []CodexModel + ClaudeCode ProviderCredential + AgentCLI map[string]ProviderCredential + GitSSHKeys map[string]string `json:"-"` // GitSSHHostKeys maps "host:port" to the requester's private key for a // conversation workspace. It travels to the execution machine on the // authenticated control connection only, in the start request of the CLI.