Skip to content

Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.

app: route Codex auto review through selected model (#18246)

Parth Sareen43e667004aa8
diff --git a/cmd/launch/codex_app.go b/cmd/launch/codex_app.go
index 57b49d872..3822fce25 100644
--- a/cmd/launch/codex_app.go
+++ b/cmd/launch/codex_app.go
@@ -101,7 +101,7 @@ func (c *CodexApp) ConfigureWithModels(primary string, models []LaunchModel) err
return fmt.Errorf("chatgpt requires a model")
}
models = codexAppCatalogModels(primary, models)
- autoReviewModel, err := codexAppConfiguredAutoReviewModel(primary, models)
+ autoReview, err := codexAppConfiguredAutoReviewModel(primary, models)
if err != nil {
return err
}
@@ -122,7 +122,7 @@ func (c *CodexApp) ConfigureWithModels(primary string, models []LaunchModel) err
return err
}
routingCatalogPath := codexAppRoutingCatalogPathForConfig(configPath)
- if err := writeCodexAppRoutingCatalog(routingCatalogPath, models, autoReviewModel); err != nil {
+ if err := writeCodexAppRoutingCatalog(routingCatalogPath, models, autoReview); err != nil {
return err
}
if err := writeCodexAppCombinedModelCatalog(catalogPath, models, nativeCatalog); err != nil {
@@ -1090,7 +1090,12 @@ func codexAppOllamaPriorityStart(nativeCatalog codexAppRawModelCatalog, ollamaMo
return lowestNativePriority - ollamaModelCount
}
-func writeCodexAppRoutingCatalog(path string, models []LaunchModel, autoReviewModel string) error {
+type codexAppAutoReviewRoute struct {
+ Model string
+ FallbackModel string
+}
+
+func writeCodexAppRoutingCatalog(path string, models []LaunchModel, autoReview codexAppAutoReviewRoute) error {
if len(models) == 0 {
return fmt.Errorf("chatgpt routing catalog cannot be empty")
}
@@ -1116,11 +1121,13 @@ func writeCodexAppRoutingCatalog(path string, models []LaunchModel, autoReviewMo
})
}
catalog := struct {
- Models []routingEntry `json:"models"`
- AutoReviewModel string `json:"auto_review_model,omitempty"`
+ Models []routingEntry `json:"models"`
+ AutoReviewModel string `json:"auto_review_model,omitempty"`
+ AutoReviewFallbackModel string `json:"auto_review_fallback_model,omitempty"`
}{
- Models: entries,
- AutoReviewModel: autoReviewModel,
+ Models: entries,
+ AutoReviewModel: autoReview.Model,
+ AutoReviewFallbackModel: autoReview.FallbackModel,
}
data, err := json.MarshalIndent(catalog, "", " ")
if err != nil {
@@ -1132,22 +1139,24 @@ func writeCodexAppRoutingCatalog(path string, models []LaunchModel, autoReviewMo
return fileutil.WriteWithBackup(path, append(data, '\n'), codexAppIntegrationName)
}
-func codexAppConfiguredAutoReviewModel(primary string, models []LaunchModel) (string, error) {
+func codexAppConfiguredAutoReviewModel(primary string, models []LaunchModel) (codexAppAutoReviewRoute, error) {
configured := strings.TrimSpace(os.Getenv(codexAppAutoReviewModelEnv))
switch strings.ToLower(configured) {
- case "", "selected", "ollama":
- return primary, nil
+ case "", "selected":
+ return codexAppAutoReviewRoute{Model: "selected", FallbackModel: primary}, nil
+ case "ollama":
+ return codexAppAutoReviewRoute{Model: primary}, nil
case "native", "chatgpt":
- return "", nil
+ return codexAppAutoReviewRoute{}, nil
}
target := codexAppCatalogModelKey(configured)
for _, model := range models {
if codexAppCatalogModelKey(model.Name) == target {
- return model.Name, nil
+ return codexAppAutoReviewRoute{Model: model.Name}, nil
}
}
- return "", fmt.Errorf("%s=%q is not one of the configured Ollama models", codexAppAutoReviewModelEnv, configured)
+ return codexAppAutoReviewRoute{}, fmt.Errorf("%s=%q is not one of the configured Ollama models", codexAppAutoReviewModelEnv, configured)
}
func parseCodexAppModelCatalog(data []byte) (codexAppRawModelCatalog, error) {
diff --git a/cmd/launch/codex_app_test.go b/cmd/launch/codex_app_test.go
index 2132aa066..4786a6a92 100644
--- a/cmd/launch/codex_app_test.go
+++ b/cmd/launch/codex_app_test.go
@@ -1363,14 +1363,15 @@ func TestCodexAppConfigureIsIdempotentAndPreservesUnrelatedProvider(t *testing.T
func TestCodexAppConfigurePersistsAutoReviewModel(t *testing.T) {
for _, test := range []struct {
- name string
- configured string
- want string
+ name string
+ configured string
+ want string
+ wantFallback string
}{
- {name: "selected model default", want: "glm-5.3:cloud"},
+ {name: "selected model default", want: "selected", wantFallback: "glm-5.3:cloud"},
{name: "native explicit", configured: "native"},
{name: "chatgpt explicit", configured: "chatgpt"},
- {name: "selected cloud model", configured: "selected", want: "glm-5.3:cloud"},
+ {name: "selected cloud model", configured: "selected", want: "selected", wantFallback: "glm-5.3:cloud"},
{name: "ollama alias", configured: "ollama", want: "glm-5.3:cloud"},
{name: "explicit configured model", configured: "qwen3:8b", want: "qwen3:8b"},
{name: "explicit configured cloud model", configured: "deepseek-v4-flash:cloud", want: "deepseek-v4-flash:cloud"},
@@ -1389,7 +1390,8 @@ func TestCodexAppConfigurePersistsAutoReviewModel(t *testing.T) {
t.Fatal(err)
}
var catalog struct {
- AutoReviewModel string `json:"auto_review_model"`
+ AutoReviewModel string `json:"auto_review_model"`
+ AutoReviewFallbackModel string `json:"auto_review_fallback_model"`
}
if err := json.Unmarshal(data, &catalog); err != nil {
t.Fatal(err)
@@ -1397,6 +1399,9 @@ func TestCodexAppConfigurePersistsAutoReviewModel(t *testing.T) {
if catalog.AutoReviewModel != test.want {
t.Fatalf("auto_review_model = %q, want %q", catalog.AutoReviewModel, test.want)
}
+ if catalog.AutoReviewFallbackModel != test.wantFallback {
+ t.Fatalf("auto_review_fallback_model = %q, want %q", catalog.AutoReviewFallbackModel, test.wantFallback)
+ }
})
}
}
diff --git a/internal/proxy/codex_desktop.go b/internal/proxy/codex_desktop.go
index f5c975195..eb6a86bd2 100644
--- a/internal/proxy/codex_desktop.go
+++ b/internal/proxy/codex_desktop.go
@@ -72,6 +72,7 @@ type CodexDesktop struct {
upstreamErrors atomic.Uint64
lastRoute atomic.Value
activityLogMu sync.Mutex
+ turnModels turnModelCache
}
type routeSnapshot struct {
@@ -199,7 +200,7 @@ func (h *CodexDesktop) ServeHTTP(w http.ResponseWriter, r *http.Request) {
writeJSONError(w, http.StatusServiceUnavailable, "read Codex Ollama model catalog: "+err.Error())
return
}
- model, decodedBody, err = autoReview.resolveModel(model, catalog, decodedBody)
+ model, decodedBody, err = autoReview.resolveModel(model, catalog, decodedBody, &h.turnModels)
if err != nil {
h.logActivity(started, r.Method, suffix, model, "ollama", http.StatusBadRequest, "request_error")
writeJSONError(w, http.StatusBadRequest, "prepare Codex Auto-review request for Ollama: "+err.Error())
@@ -242,6 +243,12 @@ func (h *CodexDesktop) ServeHTTP(w http.ResponseWriter, r *http.Request) {
writeJSONError(w, http.StatusBadRequest, "prepare Codex request for Ollama: "+err.Error())
return
}
+ requestBody, err = normalizeFullAccessExecTool(requestBody)
+ if err != nil {
+ h.logActivity(started, r.Method, suffix, model, "ollama", http.StatusBadRequest, "request_error")
+ writeJSONError(w, http.StatusBadRequest, "prepare Codex Full Access tools for Ollama: "+err.Error())
+ return
+ }
} else {
requestBody, requestBodyNormalized, err = normalizeNativeRequestBody(decodedBody)
if err != nil {
@@ -249,6 +256,7 @@ func (h *CodexDesktop) ServeHTTP(w http.ResponseWriter, r *http.Request) {
writeJSONError(w, http.StatusBadRequest, "prepare Codex request for OpenAI: "+err.Error())
return
}
+ requestBodyNormalized = requestBodyNormalized || autoReview.rewritten
if !requestBodyNormalized {
requestBody = rawBody
}
@@ -271,19 +279,25 @@ func (h *CodexDesktop) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
h.logger.Debug("routing Codex request", "path", suffix, "model", model, "ollama", routed)
recorder := &responseRecorder{ResponseWriter: w}
- h.proxy.ServeHTTP(recorder, r.WithContext(context.WithValue(r.Context(), proxyRequestKey{}, state)))
+ aborted := h.serveReverseProxy(recorder, r.WithContext(context.WithValue(r.Context(), proxyRequestKey{}, state)))
result := state.result
if result == "" {
- result = "ok"
- if recorder.writeErr != nil {
- if r.Context().Err() != nil && errors.Is(recorder.writeErr, r.Context().Err()) {
- result = "canceled"
- } else {
- result = "stream_error"
- h.upstreamErrors.Add(1)
+ switch {
+ case aborted && r.Context().Err() != nil:
+ result = "canceled"
+ case recorder.writeErr != nil && r.Context().Err() != nil && errors.Is(recorder.writeErr, r.Context().Err()):
+ result = "canceled"
+ case aborted || recorder.writeErr != nil:
+ result = "stream_error"
+ h.upstreamErrors.Add(1)
+ if recorder.writeErr != nil {
h.logger.Warn("Codex proxy response write failed", "path", suffix, "model", model, "ollama", routed, "error", recorder.writeErr)
+ } else {
+ h.logger.Warn("Codex proxy response stream aborted", "path", suffix, "model", model, "ollama", routed)
}
+ default:
+ result = "ok"
}
}
status := state.status
@@ -293,6 +307,26 @@ func (h *CodexDesktop) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.logActivity(started, r.Method, suffix, model, route, status, result)
}
+// serveReverseProxy handles the sentinel panic ReverseProxy uses when a
+// streamed response fails after its headers have already been sent. A normal
+// net/http server suppresses this panic, but doing so outside this handler
+// would skip the terminal activity log and let middleware report a false 500.
+// All other panics remain programming errors and propagate unchanged.
+func (h *CodexDesktop) serveReverseProxy(w http.ResponseWriter, r *http.Request) (aborted bool) {
+ defer func() {
+ if recovered := recover(); recovered != nil {
+ if recovered != http.ErrAbortHandler {
+ panic(recovered)
+ }
+ aborted = true
+ }
+ }()
+ h.proxy.ServeHTTP(w, r)
+ return
+}
+
+// proxyRequestKey carries the per-request routing state through the reverse
+// proxy hooks.
type proxyRequestKey struct{}
// proxyRequest shares routing and response state between reverse-proxy hooks.
@@ -548,8 +582,9 @@ type routingModel struct {
}
type routingCatalog struct {
- models map[string]routingModel
- autoReviewModel string
+ models map[string]routingModel
+ autoReviewModel string
+ autoReviewFallbackModel string
}
func loadRoutingCatalog(path string) (routingCatalog, error) {
@@ -561,8 +596,9 @@ func loadRoutingCatalog(path string) (routingCatalog, error) {
return routingCatalog{}, err
}
var catalog struct {
- Models []routingModel `json:"models"`
- AutoReviewModel string `json:"auto_review_model"`
+ Models []routingModel `json:"models"`
+ AutoReviewModel string `json:"auto_review_model"`
+ AutoReviewFallbackModel string `json:"auto_review_fallback_model"`
}
if err := json.Unmarshal(data, &catalog); err != nil {
return routingCatalog{}, err
@@ -574,12 +610,21 @@ func loadRoutingCatalog(path string) (routingCatalog, error) {
}
}
autoReviewModel := strings.TrimSpace(catalog.AutoReviewModel)
- if autoReviewModel != "" {
+ autoReviewFallbackModel := strings.TrimSpace(catalog.AutoReviewFallbackModel)
+ if modelKey(autoReviewModel) == modelKey(autoReviewSelectedModel) {
+ if _, ok := models[modelKey(autoReviewFallbackModel)]; !ok {
+ return routingCatalog{}, fmt.Errorf("Auto-review fallback model %q is not in the Ollama routing catalog", autoReviewFallbackModel)
+ }
+ } else if autoReviewModel != "" {
if _, ok := models[modelKey(autoReviewModel)]; !ok {
return routingCatalog{}, fmt.Errorf("Auto-review model %q is not in the Ollama routing catalog", autoReviewModel)
}
}
- return routingCatalog{models: models, autoReviewModel: autoReviewModel}, nil
+ return routingCatalog{
+ models: models,
+ autoReviewModel: autoReviewModel,
+ autoReviewFallbackModel: autoReviewFallbackModel,
+ }, nil
}
func modelKey(model string) string {
diff --git a/internal/proxy/codex_desktop_autoreview.go b/internal/proxy/codex_desktop_autoreview.go
index 0b5f548a8..ce7c8b18f 100644
--- a/internal/proxy/codex_desktop_autoreview.go
+++ b/internal/proxy/codex_desktop_autoreview.go
@@ -8,13 +8,16 @@ import (
"io"
"net/http"
"strings"
+ "sync"
)
const (
// autoReviewModel is the native Codex reviewer alias. The routing catalog
// may map requests for this alias to a selected Ollama model.
autoReviewModel = "codex-auto-review"
+ autoReviewSelectedModel = "selected"
guardianDecisionToolName = "submit_guardian_decision"
+ maxTrackedTurnModels = 2048
guardianDecisionInstruction = `
@@ -52,23 +55,97 @@ var guardianDecisionTool = map[string]any{
}
type autoReviewState struct {
- alias bool // requested model is the native auto-review alias
- eligible bool // routed auto-review call that needs translation
+ alias bool // requested model is the native auto-review alias
+ eligible bool // routed auto-review call that needs translation
+ rewritten bool // model alias was replaced in the decoded request body
}
-func (s *autoReviewState) resolveModel(model string, catalog routingCatalog, body []byte) (string, []byte, error) {
+type turnModelCache struct {
+ mu sync.Mutex
+ models map[string]string
+ order []string
+}
+
+// resolveModel tracks each parent turn's selected model, then maps the native
+// auto-review alias according to the catalog policy and rewrites the request
+// body. Other requests pass through unchanged.
+func (s *autoReviewState) resolveModel(model string, catalog routingCatalog, body []byte, turnModels *turnModelCache) (string, []byte, error) {
if modelKey(model) != modelKey(autoReviewModel) {
+ turnID, _ := extractTurnMetadata(body)
+ turnModels.remember(turnID, model)
return model, body, nil
}
s.alias = true
- if catalog.autoReviewModel == "" {
+ selectedModel := catalog.autoReviewModel
+ if modelKey(selectedModel) == modelKey(autoReviewSelectedModel) {
+ _, parentTurnID := extractTurnMetadata(body)
+ var ok bool
+ selectedModel, ok = turnModels.lookup(parentTurnID)
+ if !ok {
+ selectedModel = catalog.autoReviewFallbackModel
+ }
+ }
+ if selectedModel == "" {
return model, body, nil
}
- replaced, err := replaceRequestModel(body, catalog.autoReviewModel)
+ replaced, err := replaceRequestModel(body, selectedModel)
if err != nil {
- return catalog.autoReviewModel, body, err
+ return selectedModel, body, err
+ }
+ s.rewritten = true
+ return selectedModel, replaced, nil
+}
+
+func extractTurnMetadata(body []byte) (turnID, parentTurnID string) {
+ if len(body) == 0 {
+ return "", ""
+ }
+ var payload struct {
+ ClientMetadata struct {
+ TurnID string `json:"turn_id"`
+ ParentTurnID string `json:"parent_turn_id"`
+ } `json:"client_metadata"`
+ }
+ if err := json.Unmarshal(body, &payload); err != nil {
+ return "", ""
+ }
+ return strings.TrimSpace(payload.ClientMetadata.TurnID), strings.TrimSpace(payload.ClientMetadata.ParentTurnID)
+}
+
+func (c *turnModelCache) remember(turnID, model string) {
+ turnID = strings.TrimSpace(turnID)
+ model = strings.TrimSpace(model)
+ if turnID == "" || model == "" {
+ return
+ }
+
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if c.models == nil {
+ c.models = make(map[string]string)
+ }
+ if _, exists := c.models[turnID]; exists {
+ c.models[turnID] = model
+ return
+ }
+ if len(c.order) == maxTrackedTurnModels {
+ delete(c.models, c.order[0])
+ copy(c.order, c.order[1:])
+ c.order = c.order[:len(c.order)-1]
+ }
+ c.models[turnID] = model
+ c.order = append(c.order, turnID)
+}
+
+func (c *turnModelCache) lookup(turnID string) (string, bool) {
+ turnID = strings.TrimSpace(turnID)
+ if turnID == "" {
+ return "", false
}
- return catalog.autoReviewModel, replaced, nil
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ model, ok := c.models[turnID]
+ return model, ok
}
func (s *autoReviewState) prepareRequest(routed bool, suffix string, body []byte) ([]byte, error) {
@@ -89,6 +166,11 @@ func prepareAutoReviewRequest(body []byte) ([]byte, error) {
if err := json.Unmarshal(body, &payload); err != nil {
return nil, err
}
+ // Codex asks its native Guardian for structured assistant text. Ollama uses
+ // the proxy-owned decision tool instead, so do not send two competing final
+ // output contracts to the selected model.
+ delete(payload, "text")
+ delete(payload, "response_format")
var tools []json.RawMessage
if raw := bytes.TrimSpace(payload["tools"]); len(raw) > 0 && !bytes.Equal(raw, []byte("null")) {
@@ -290,6 +372,8 @@ func inspectAutoReviewOutput(output []json.RawMessage) (autoReviewInspection, er
result := autoReviewInspection{discardedMessageIDs: make(map[string]struct{})}
decisionCalls := 0
otherTerminalOutput := false
+ var decisionText string
+ messageCount := 0
for _, raw := range output {
var item autoReviewOutputItem
if err := json.Unmarshal(raw, &item); err != nil {
@@ -304,6 +388,10 @@ func inspectAutoReviewOutput(output []json.RawMessage) (autoReviewInspection, er
return result, errors.New("Guardian assistant message has no item ID")
}
result.discardedMessageIDs[item.ID] = struct{}{}
+ messageCount++
+ if messageCount == 1 {
+ decisionText, _ = autoReviewMessageText(raw)
+ }
case "function_call":
if item.Name != guardianDecisionToolName {
if decisionCalls > 0 {
@@ -331,7 +419,17 @@ func inspectAutoReviewOutput(output []json.RawMessage) (autoReviewInspection, er
return result, nil
}
if decisionCalls == 0 {
- return result, errors.New("Guardian did not call submit_guardian_decision")
+ if otherTerminalOutput || messageCount != 1 || decisionText == "" {
+ return result, errors.New("Guardian did not call submit_guardian_decision")
+ }
+ if err := validateGuardianTextDecision(decisionText); err != nil {
+ return result, fmt.Errorf("Guardian did not call submit_guardian_decision and its text fallback is invalid: %w", err)
+ }
+ // A few providers occasionally ignore the requested decision tool and
+ // return the same JSON as their only assistant text. It already has the
+ // shape Codex expects, so preserve the response after strict validation.
+ result.passthrough = true
+ return result, nil
}
if result.passthrough || otherTerminalOutput {
return result, errors.New("Guardian mixed its decision with other terminal output")
@@ -339,6 +437,22 @@ func inspectAutoReviewOutput(output []json.RawMessage) (autoReviewInspection, er
return result, nil
}
+func autoReviewMessageText(raw json.RawMessage) (string, error) {
+ var message struct {
+ Content []struct {
+ Type string `json:"type"`
+ Text string `json:"text"`
+ } `json:"content"`
+ }
+ if err := json.Unmarshal(raw, &message); err != nil {
+ return "", err
+ }
+ if len(message.Content) != 1 || message.Content[0].Type != "output_text" {
+ return "", errors.New("Guardian assistant message is not a single output_text item")
+ }
+ return strings.TrimSpace(message.Content[0].Text), nil
+}
+
func validateGuardianDecision(arguments string) (string, error) {
decoder := json.NewDecoder(strings.NewReader(arguments))
decoder.DisallowUnknownFields()
@@ -368,6 +482,31 @@ func validateGuardianDecision(arguments string) (string, error) {
return string(encoded), nil
}
+func validateGuardianTextDecision(text string) error {
+ if _, err := validateGuardianDecision(text); err == nil {
+ return nil
+ }
+
+ // Codex's Guardian contract permits this compact form for low-risk allows.
+ // Keep it text-only: decision tool calls must always provide the complete
+ // schema above, while any extra or unknown text field still fails closed.
+ decoder := json.NewDecoder(strings.NewReader(text))
+ decoder.DisallowUnknownFields()
+ var decision struct {
+ Outcome string `json:"outcome"`
+ }
+ if err := decoder.Decode(&decision); err != nil {
+ return fmt.Errorf("decode compact Guardian decision: %w", err)
+ }
+ if decoder.Decode(&struct{}{}) != io.EOF {
+ return errors.New("compact Guardian decision contains trailing data")
+ }
+ if decision.Outcome != "allow" {
+ return fmt.Errorf("invalid compact Guardian outcome %q", decision.Outcome)
+ }
+ return nil
+}
+
func oneOf(value string, allowed ...string) bool {
for _, candidate := range allowed {
if value == candidate {
diff --git a/internal/proxy/codex_desktop_normalize.go b/internal/proxy/codex_desktop_normalize.go
index 3b9f2f55b..0bac877e9 100644
--- a/internal/proxy/codex_desktop_normalize.go
+++ b/internal/proxy/codex_desktop_normalize.go
@@ -44,6 +44,128 @@ func normalizeOllamaRequestBody(body []byte, model routingModel) ([]byte, error)
return normalizeOllamaThinking(normalized, *model.Thinking)
}
+// normalizeFullAccessExecTool removes escalation-only arguments from the tool
+// contract when Codex is already running without a sandbox. If an Ollama model
+// redundantly emits require_escalated in this mode, Codex rejects the entire
+// command because its approval policy is Never. Keeping those arguments out of
+// the advertised schema makes the only representable call the direct one that
+// Full Access already authorizes.
+func normalizeFullAccessExecTool(body []byte) ([]byte, error) {
+ if codexSandboxMode(body) != "danger-full-access" {
+ return body, nil
+ }
+
+ var payload map[string]json.RawMessage
+ if err := json.Unmarshal(body, &payload); err != nil {
+ return nil, err
+ }
+ rawTools, ok := payload["tools"]
+ if !ok {
+ return body, nil
+ }
+ var tools []json.RawMessage
+ if err := json.Unmarshal(rawTools, &tools); err != nil {
+ return nil, fmt.Errorf("decode tools: %w", err)
+ }
+
+ changed := false
+ for i, rawTool := range tools {
+ var tool map[string]json.RawMessage
+ if err := json.Unmarshal(rawTool, &tool); err != nil {
+ return nil, fmt.Errorf("decode tool: %w", err)
+ }
+ var name string
+ if err := json.Unmarshal(tool["name"], &name); err != nil || name != "exec_command" {
+ continue
+ }
+
+ var parameters map[string]json.RawMessage
+ if err := json.Unmarshal(tool["parameters"], &parameters); err != nil {
+ return nil, fmt.Errorf("decode exec_command parameters: %w", err)
+ }
+ var properties map[string]json.RawMessage
+ if err := json.Unmarshal(parameters["properties"], &properties); err != nil {
+ return nil, fmt.Errorf("decode exec_command properties: %w", err)
+ }
+ toolChanged := false
+ for _, property := range []string{"sandbox_permissions", "justification", "prefix_rule"} {
+ if _, ok := properties[property]; ok {
+ delete(properties, property)
+ toolChanged = true
+ }
+ }
+ if !toolChanged {
+ continue
+ }
+ changed = true
+
+ encodedProperties, err := json.Marshal(properties)
+ if err != nil {
+ return nil, fmt.Errorf("encode exec_command properties: %w", err)
+ }
+ parameters["properties"] = encodedProperties
+ if rawRequired, ok := parameters["required"]; ok {
+ var required []string
+ if err := json.Unmarshal(rawRequired, &required); err != nil {
+ return nil, fmt.Errorf("decode exec_command required properties: %w", err)
+ }
+ required = slices.DeleteFunc(required, func(property string) bool {
+ return property == "sandbox_permissions" || property == "justification" || property == "prefix_rule"
+ })
+ parameters["required"], err = json.Marshal(required)
+ if err != nil {
+ return nil, fmt.Errorf("encode exec_command required properties: %w", err)
+ }
+ }
+ tool["parameters"], err = json.Marshal(parameters)
+ if err != nil {
+ return nil, fmt.Errorf("encode exec_command parameters: %w", err)
+ }
+ tools[i], err = json.Marshal(tool)
+ if err != nil {
+ return nil, fmt.Errorf("encode exec_command tool: %w", err)
+ }
+ }
+ if !changed {
+ return body, nil
+ }
+
+ encodedTools, err := json.Marshal(tools)
+ if err != nil {
+ return nil, fmt.Errorf("encode tools: %w", err)
+ }
+ payload["tools"] = encodedTools
+ encoded, err := json.Marshal(payload)
+ if err != nil {
+ return nil, fmt.Errorf("encode request: %w", err)
+ }
+ return encoded, nil
+}
+
+func codexSandboxMode(body []byte) string {
+ var payload struct {
+ ClientMetadata map[string]json.RawMessage `json:"client_metadata"`
+ }
+ if json.Unmarshal(body, &payload) != nil {
+ return ""
+ }
+ raw := payload.ClientMetadata["x-codex-turn-metadata"]
+ if len(raw) == 0 {
+ return ""
+ }
+ var encoded string
+ if json.Unmarshal(raw, &encoded) == nil {
+ raw = []byte(encoded)
+ }
+ var metadata struct {
+ SandboxMode string `json:"sandbox_mode"`
+ }
+ if json.Unmarshal(raw, &metadata) != nil {
+ return ""
+ }
+ return strings.TrimSpace(metadata.SandboxMode)
+}
+
func normalizeOllamaThinking(body []byte, metadata routingThinkingMetadata) ([]byte, error) {
var payload map[string]json.RawMessage
if err := json.Unmarshal(body, &payload); err != nil {
diff --git a/internal/proxy/codex_desktop_test.go b/internal/proxy/codex_desktop_test.go
index 1f9652396..395df8d9f 100644
--- a/internal/proxy/codex_desktop_test.go
+++ b/internal/proxy/codex_desktop_test.go
@@ -2,13 +2,16 @@ package proxy
import (
"bytes"
+ "context"
"encoding/json"
+ "errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
+ "slices"
"strings"
"testing"
"time"
@@ -315,6 +318,67 @@ func TestNormalizeOllamaThinkingRejectsMalformedReasoning(t *testing.T) {
}
}
+func TestNormalizeFullAccessExecToolRemovesEscalationArguments(t *testing.T) {
+ turnMetadata := `{"sandbox_mode":"danger-full-access"}`
+ body := []byte(fmt.Sprintf(`{
+ "model":"glm-5.3-flash:cloud",
+ "client_metadata":{"x-codex-turn-metadata":%q},
+ "tools":[
+ {"type":"function","name":"exec_command","parameters":{"type":"object","properties":{"cmd":{"type":"string"},"sandbox_permissions":{"type":"string"},"justification":{"type":"string"},"prefix_rule":{"type":"array"}},"required":["cmd","sandbox_permissions","justification","prefix_rule"],"additionalProperties":false}},
+ {"type":"function","name":"other_tool","parameters":{"type":"object","properties":{"sandbox_permissions":{"type":"string"}}}}
+ ]
+ }`, turnMetadata))
+
+ normalized, err := normalizeFullAccessExecTool(body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var payload struct {
+ Tools []struct {
+ Name string `json:"name"`
+ Parameters struct {
+ Properties map[string]json.RawMessage `json:"properties"`
+ Required []string `json:"required"`
+ } `json:"parameters"`
+ } `json:"tools"`
+ }
+ if err := json.Unmarshal(normalized, &payload); err != nil {
+ t.Fatal(err)
+ }
+ if len(payload.Tools) != 2 {
+ t.Fatalf("tools = %d, want 2", len(payload.Tools))
+ }
+ execTool := payload.Tools[0]
+ if _, ok := execTool.Parameters.Properties["cmd"]; !ok {
+ t.Fatal("exec_command cmd property was removed")
+ }
+ for _, property := range []string{"sandbox_permissions", "justification", "prefix_rule"} {
+ if _, ok := execTool.Parameters.Properties[property]; ok {
+ t.Fatalf("exec_command retained %q property", property)
+ }
+ if slices.Contains(execTool.Parameters.Required, property) {
+ t.Fatalf("exec_command retained required %q", property)
+ }
+ }
+ if !slices.Equal(execTool.Parameters.Required, []string{"cmd"}) {
+ t.Fatalf("exec_command required = %v, want [cmd]", execTool.Parameters.Required)
+ }
+ if _, ok := payload.Tools[1].Parameters.Properties["sandbox_permissions"]; !ok {
+ t.Fatal("non-exec tool was changed")
+ }
+}
+
+func TestNormalizeFullAccessExecToolLeavesSandboxedTurnUnchanged(t *testing.T) {
+ body := []byte(`{"client_metadata":{"x-codex-turn-metadata":"{\"sandbox_mode\":\"workspace-write\"}"},"tools":[{"name":"exec_command","parameters":{"properties":{"sandbox_permissions":{"type":"string"}}}}]}`)
+ normalized, err := normalizeFullAccessExecTool(body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !bytes.Equal(normalized, body) {
+ t.Fatalf("sandboxed request changed:\n%s", normalized)
+ }
+}
+
func TestLoadCatalogModelsReadsOptionalThinkingMetadata(t *testing.T) {
path := filepath.Join(t.TempDir(), CodexDesktopModelCatalogFilename)
data := []byte(`{"models":[{"slug":"legacy"},{"slug":"binary","thinking":{"supported":true,"levels":["none","medium"],"values":{"none":false,"medium":true}}}]}`)
@@ -338,6 +402,141 @@ func TestLoadCatalogModelsReadsOptionalThinkingMetadata(t *testing.T) {
}
}
+func TestCodexDesktopRoutesAutoReviewToSelectedNativeModel(t *testing.T) {
+ ollama := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
+ t.Fatal("native selected model should not reach Ollama")
+ }))
+ defer ollama.Close()
+
+ var models []string
+ var encodings []string
+ var guardianBody map[string]json.RawMessage
+ chatGPT := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var payload map[string]json.RawMessage
+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
+ t.Fatal(err)
+ }
+ var model string
+ if err := json.Unmarshal(payload["model"], &model); err != nil {
+ t.Fatal(err)
+ }
+ models = append(models, model)
+ encodings = append(encodings, r.Header.Get("Content-Encoding"))
+ if len(models) == 2 {
+ guardianBody = payload
+ }
+ w.WriteHeader(http.StatusNoContent)
+ }))
+ defer chatGPT.Close()
+
+ handler := newTestCodexDesktop(t, ollama.URL, chatGPT.URL, writeCatalogWithSelectedAutoReview(t, "glm-5.3-flash:cloud", "glm-5.3-flash:cloud"))
+ proxy := httptest.NewServer(handler)
+ defer proxy.Close()
+
+ postCodexRequest(t, proxy.URL, `{"model":"gpt-5.6-sol","client_metadata":{"turn_id":"turn-native"}}`, true)
+ postCompressedCodexRequest(t, proxy.URL, `{"model":"codex-auto-review","client_metadata":{"parent_turn_id":"turn-native"},"text":{"format":{"type":"json_schema"}}}`)
+
+ if strings.Join(models, ",") != "gpt-5.6-sol,gpt-5.6-sol" {
+ t.Fatalf("forwarded models = %q, want selected native model for Guardian", models)
+ }
+ if _, ok := guardianBody["text"]; !ok {
+ t.Fatalf("native Guardian structured output was removed: %#v", guardianBody)
+ }
+ if _, ok := guardianBody["tools"]; ok {
+ t.Fatalf("proxy decision tool was added to native Guardian: %#v", guardianBody)
+ }
+ if encodings[1] != "" {
+ t.Fatalf("rewritten native Guardian retained content encoding %q", encodings[1])
+ }
+}
+
+func TestCodexDesktopRoutesAutoReviewToSelectedOllamaModel(t *testing.T) {
+ var models []string
+ var guardianBody map[string]json.RawMessage
+ ollama := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var payload map[string]json.RawMessage
+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
+ t.Fatal(err)
+ }
+ var model string
+ if err := json.Unmarshal(payload["model"], &model); err != nil {
+ t.Fatal(err)
+ }
+ models = append(models, model)
+ if len(models) == 2 {
+ guardianBody = payload
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.WriteString(w, autoReviewJSONResponse(`{"risk_level":"low","user_authorization":"high","outcome":"allow","rationale":"Allowed."}`))
+ return
+ }
+ w.WriteHeader(http.StatusNoContent)
+ }))
+ defer ollama.Close()
+ chatGPT := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
+ t.Fatal("Ollama selected model should not reach ChatGPT")
+ }))
+ defer chatGPT.Close()
+
+ handler := newTestCodexDesktop(t, ollama.URL, chatGPT.URL, writeCatalogWithSelectedAutoReview(t, "glm-5.3-flash:cloud", "glm-5.3-flash:cloud", "deepseek-v3.1:671b-cloud"))
+ proxy := httptest.NewServer(handler)
+ defer proxy.Close()
+
+ postCodexRequest(t, proxy.URL, `{"model":"deepseek-v3.1:671b-cloud","client_metadata":{"turn_id":"turn-ollama"}}`, false)
+ postCodexRequest(t, proxy.URL, `{"model":"codex-auto-review","client_metadata":{"parent_turn_id":"turn-ollama"},"input":[{"role":"user","content":"review"}],"text":{"format":{"type":"json_schema"}}}`, false)
+
+ if strings.Join(models, ",") != "deepseek-v3.1:671b-cloud,deepseek-v3.1:671b-cloud" {
+ t.Fatalf("forwarded models = %q, want selected Ollama model for Guardian", models)
+ }
+ if _, ok := guardianBody["text"]; ok {
+ t.Fatalf("Ollama Guardian retained competing structured output: %#v", guardianBody)
+ }
+ if _, ok := guardianBody["tools"]; !ok {
+ t.Fatalf("Ollama Guardian decision tool is missing: %#v", guardianBody)
+ }
+}
+
+func TestCodexDesktopSelectedAutoReviewFallsBackWithoutParentTurn(t *testing.T) {
+ var gotModel string
+ ollama := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var payload struct {
+ Model string `json:"model"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
+ t.Fatal(err)
+ }
+ gotModel = payload.Model
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.WriteString(w, autoReviewJSONResponse(`{"risk_level":"low","user_authorization":"high","outcome":"allow","rationale":"Allowed."}`))
+ }))
+ defer ollama.Close()
+ chatGPT := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
+ t.Fatal("selected Auto-review fallback should not reach ChatGPT")
+ }))
+ defer chatGPT.Close()
+
+ handler := newTestCodexDesktop(t, ollama.URL, chatGPT.URL, writeCatalogWithSelectedAutoReview(t, "glm-5.3-flash:cloud", "glm-5.3-flash:cloud"))
+ proxy := httptest.NewServer(handler)
+ defer proxy.Close()
+
+ postCodexRequest(t, proxy.URL, `{"model":"codex-auto-review","input":[{"role":"user","content":"review"}]}`, false)
+ if gotModel != "glm-5.3-flash:cloud" {
+ t.Fatalf("fallback model = %q, want launch primary", gotModel)
+ }
+}
+
+func TestTurnModelCacheIsBounded(t *testing.T) {
+ var cache turnModelCache
+ for i := 0; i <= maxTrackedTurnModels; i++ {
+ cache.remember(fmt.Sprintf("turn-%d", i), fmt.Sprintf("model-%d", i))
+ }
+ if _, ok := cache.lookup("turn-0"); ok {
+ t.Fatal("oldest turn was not evicted")
+ }
+ if model, ok := cache.lookup(fmt.Sprintf("turn-%d", maxTrackedTurnModels)); !ok || model != fmt.Sprintf("model-%d", maxTrackedTurnModels) {
+ t.Fatalf("newest turn = %q, %v", model, ok)
+ }
+}
+
func TestCodexDesktopRoutesAutoReviewToConfiguredOllamaModel(t *testing.T) {
var gotBody []byte
ollama := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -359,7 +558,7 @@ func TestCodexDesktopRoutesAutoReviewToConfiguredOllamaModel(t *testing.T) {
resp, err := http.Post(
proxy.URL+CodexDesktopPathPrefix+"/v1/responses",
"application/json",
- strings.NewReader(`{"model":"codex-auto-review","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"review"}]}]}`),
+ strings.NewReader(`{"model":"codex-auto-review","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"review"}]}],"text":{"format":{"type":"json_schema"}},"response_format":{"type":"json_object"}}`),
)
if err != nil {
t.Fatal(err)
@@ -552,12 +751,58 @@ func TestTransformAutoReviewResponseRejectsInvalidDecision(t *testing.T) {
}
func TestTransformAutoReviewResponseRejectsTextDecision(t *testing.T) {
- body := []byte(`{"id":"resp_1","status":"completed","output":[{"id":"msg_1","type":"message","status":"completed","role":"assistant","content":[{"type":"output_text","text":"{\\\"outcome\\\":\\\"allow\\\"}"}]}]}`)
+ body := []byte(`{"id":"resp_1","status":"completed","output":[{"id":"msg_1","type":"message","status":"completed","role":"assistant","content":[{"type":"output_text","text":"{\\\"outcome\\\":\\\"deny\\\"}"}]}]}`)
if _, _, err := transformAutoReviewResponse(body, "application/json"); err == nil || !strings.Contains(err.Error(), "did not call") {
t.Fatalf("error = %v, want missing decision tool call", err)
}
}
+func TestTransformAutoReviewResponseAcceptsValidatedTextFallback(t *testing.T) {
+ decision := `{"risk_level":"low","user_authorization":"high","outcome":"allow","rationale":"The user requested this benign local action."}`
+ jsonBody := []byte(fmt.Sprintf(`{"id":"resp_1","status":"completed","output":[{"id":"msg_1","type":"message","status":"completed","role":"assistant","content":[{"type":"output_text","text":%q}]}]}`, decision))
+ for _, test := range []struct {
+ name string
+ contentType string
+ body []byte
+ }{
+ {name: "json", contentType: "application/json", body: jsonBody},
+ {name: "event stream", contentType: "text/event-stream", body: autoReviewTextEventStream(t, decision)},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ transformed, changed, err := transformAutoReviewResponse(test.body, test.contentType)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if changed || !bytes.Equal(transformed, test.body) {
+ t.Fatalf("validated text fallback changed:\n%s", transformed)
+ }
+ })
+ }
+}
+
+func TestTransformAutoReviewResponseAcceptsCompactAllowTextFallback(t *testing.T) {
+ decision := `{"outcome":"allow"}`
+ jsonBody := []byte(fmt.Sprintf(`{"id":"resp_1","status":"completed","output":[{"id":"msg_1","type":"message","status":"completed","role":"assistant","content":[{"type":"output_text","text":%q}]}]}`, decision))
+ for _, test := range []struct {
+ name string
+ contentType string
+ body []byte
+ }{
+ {name: "json", contentType: "application/json", body: jsonBody},
+ {name: "event stream", contentType: "text/event-stream", body: autoReviewTextEventStream(t, decision)},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ transformed, changed, err := transformAutoReviewResponse(test.body, test.contentType)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if changed || !bytes.Equal(transformed, test.body) {
+ t.Fatalf("compact allow fallback changed:\n%s", transformed)
+ }
+ })
+ }
+}
+
func TestTransformAutoReviewJSONDiscardsProseWithValidDecision(t *testing.T) {
arguments := `{"risk_level":"low","user_authorization":"high","outcome":"allow","rationale":"The command is read-only and explicitly requested."}`
body := []byte(fmt.Sprintf(`{"id":"resp_1","status":"completed","output":[{"id":"fc_1","type":"function_call","status":"completed","call_id":"call_1","name":%q,"arguments":%q},{"id":"msg_1","type":"message","status":"completed","role":"assistant","content":[{"type":"output_text","text":"Submitting approval."}]}]}`, guardianDecisionToolName, arguments))
@@ -1395,6 +1640,117 @@ func TestCodexDesktopWritesSafeActivityLog(t *testing.T) {
}
}
+func TestCodexDesktopRecordsMidstreamAbortWithoutPanicking(t *testing.T) {
+ activityLogPath := filepath.Join(t.TempDir(), "codex-proxy.log")
+ streamErr := errors.New("upstream stream failed")
+ handler, err := NewCodexDesktop(CodexDesktopConfig{
+ OllamaURL: "http://127.0.0.1:11434",
+ ChatGPTURL: "https://chatgpt.com/backend-api/codex",
+ RoutingCatalogPath: writeCatalog(t, "glm-5.3-flash:cloud"),
+ ActivityLogPath: activityLogPath,
+ Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ return &http.Response{
+ Status: "200 OK",
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"text/event-stream"}},
+ Body: io.NopCloser(io.MultiReader(
+ strings.NewReader("data: partial\n\n"),
+ errorReader{err: streamErr},
+ )),
+ Request: req,
+ }, nil
+ }),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ req := httptest.NewRequest(
+ http.MethodPost,
+ "http://localhost"+CodexDesktopPathPrefix+"/v1/responses",
+ strings.NewReader(`{"model":"glm-5.3-flash:cloud"}`),
+ )
+ req.RemoteAddr = "127.0.0.1:1234"
+ req = req.WithContext(context.WithValue(req.Context(), http.ServerContextKey, &http.Server{}))
+ recorder := httptest.NewRecorder()
+
+ handler.ServeHTTP(recorder, req)
+
+ if recorder.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200", recorder.Code)
+ }
+ if got := recorder.Body.String(); got != "data: partial\n\n" {
+ t.Fatalf("body = %q, want partial event", got)
+ }
+ if got := handler.upstreamErrors.Load(); got != 1 {
+ t.Fatalf("upstream errors = %d, want 1", got)
+ }
+ data, err := os.ReadFile(activityLogPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ logText := string(data)
+ for _, want := range []string{
+ `route=ollama model="glm-5.3-flash:cloud"`,
+ "status=200",
+ "result=stream_error",
+ } {
+ if !strings.Contains(logText, want) {
+ t.Fatalf("activity log missing %q:\n%s", want, logText)
+ }
+ }
+}
+
+func TestCodexDesktopRecordsClientCanceledStream(t *testing.T) {
+ activityLogPath := filepath.Join(t.TempDir(), "codex-proxy.log")
+ handler, err := NewCodexDesktop(CodexDesktopConfig{
+ OllamaURL: "http://127.0.0.1:11434",
+ ChatGPTURL: "https://chatgpt.com/backend-api/codex",
+ RoutingCatalogPath: writeCatalog(t, "glm-5.3-flash:cloud"),
+ ActivityLogPath: activityLogPath,
+ Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
+ return &http.Response{
+ Status: "200 OK",
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"text/event-stream"}},
+ Body: io.NopCloser(strings.NewReader("data: ignored\n\n")),
+ Request: req,
+ }, nil
+ }),
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ req := httptest.NewRequest(
+ http.MethodPost,
+ "http://localhost"+CodexDesktopPathPrefix+"/v1/responses",
+ strings.NewReader(`{"model":"glm-5.3-flash:cloud"}`),
+ )
+ req.RemoteAddr = "127.0.0.1:1234"
+ ctx, cancel := context.WithCancel(req.Context())
+ cancel()
+ req = req.WithContext(ctx)
+ recorder := &writeErrorResponseWriter{err: context.Canceled}
+
+ handler.ServeHTTP(recorder, req)
+
+ if recorder.status != http.StatusOK {
+ t.Fatalf("status = %d, want 200", recorder.status)
+ }
+ if got := handler.upstreamErrors.Load(); got != 0 {
+ t.Fatalf("upstream errors = %d, want 0", got)
+ }
+ data, err := os.ReadFile(activityLogPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ logText := string(data)
+ if !strings.Contains(logText, "status=200") || !strings.Contains(logText, "result=canceled") {
+ t.Fatalf("activity log did not record cancellation:\n%s", logText)
+ }
+}
+
func TestCodexDesktopRejectsNonLoopbackClients(t *testing.T) {
handler := newTestCodexDesktop(t, "http://127.0.0.1:11434", "https://chatgpt.com/backend-api/codex", writeCatalog(t, "glm"))
req := httptest.NewRequest(http.MethodGet, "http://example.test"+CodexDesktopPathPrefix+"/_health", nil)
@@ -1419,6 +1775,55 @@ func TestCodexDesktopFailsClosedWhenCatalogIsMissing(t *testing.T) {
}
}
+func postCodexRequest(t *testing.T, proxyURL, body string, chatGPT bool) {
+ t.Helper()
+ req, err := http.NewRequest(http.MethodPost, proxyURL+CodexDesktopPathPrefix+"/v1/responses", strings.NewReader(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Content-Type", "application/json")
+ if chatGPT {
+ req.Header.Set("Authorization", "Bearer chatgpt-secret")
+ req.Header.Set("ChatGPT-Account-ID", "account-123")
+ }
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
+ responseBody, _ := io.ReadAll(resp.Body)
+ t.Fatalf("status = %d: %s", resp.StatusCode, responseBody)
+ }
+}
+
+func postCompressedCodexRequest(t *testing.T, proxyURL, body string) {
+ t.Helper()
+ encoder, err := zstd.NewWriter(nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ compressed := encoder.EncodeAll([]byte(body), nil)
+ encoder.Close()
+ req, err := http.NewRequest(http.MethodPost, proxyURL+CodexDesktopPathPrefix+"/v1/responses", bytes.NewReader(compressed))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Content-Encoding", "zstd")
+ req.Header.Set("Authorization", "Bearer chatgpt-secret")
+ req.Header.Set("ChatGPT-Account-ID", "account-123")
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
+ responseBody, _ := io.ReadAll(resp.Body)
+ t.Fatalf("status = %d: %s", resp.StatusCode, responseBody)
+ }
+}
+
func newTestCodexDesktop(t *testing.T, ollamaURL, chatGPTURL, catalogPath string) *CodexDesktop {
t.Helper()
handler, err := NewCodexDesktop(CodexDesktopConfig{
@@ -1437,12 +1842,24 @@ func writeCatalog(t *testing.T, models ...string) string {
}
func writeCatalogWithAutoReview(t *testing.T, autoReviewModel string, models ...string) string {
+ return writeRoutingCatalog(t, autoReviewModel, "", models...)
+}
+
+func writeCatalogWithSelectedAutoReview(t *testing.T, fallbackModel string, models ...string) string {
+ return writeRoutingCatalog(t, autoReviewSelectedModel, fallbackModel, models...)
+}
+
+func writeRoutingCatalog(t *testing.T, autoReviewModel, fallbackModel string, models ...string) string {
t.Helper()
entries := make([]map[string]string, 0, len(models))
for _, model := range models {
entries = append(entries, map[string]string{"slug": model})
}
- data, err := json.Marshal(map[string]any{"models": entries, "auto_review_model": autoReviewModel})
+ data, err := json.Marshal(map[string]any{
+ "models": entries,
+ "auto_review_model": autoReviewModel,
+ "auto_review_fallback_model": fallbackModel,
+ })
if err != nil {
t.Fatal(err)
}
@@ -1457,6 +1874,35 @@ func autoReviewJSONResponse(arguments string) string {
return autoReviewJSONResponseForTool(guardianDecisionToolName, arguments)
}
+type errorReader struct {
+ err error
+}
+
+func (r errorReader) Read([]byte) (int, error) {
+ return 0, r.err
+}
+
+type writeErrorResponseWriter struct {
+ header http.Header
+ status int
+ err error
+}
+
+func (w *writeErrorResponseWriter) Header() http.Header {
+ if w.header == nil {
+ w.header = make(http.Header)
+ }
+ return w.header
+}
+
+func (w *writeErrorResponseWriter) WriteHeader(status int) {
+ w.status = status
+}
+
+func (w *writeErrorResponseWriter) Write([]byte) (int, error) {
+ return 0, w.err
+}
+
func autoReviewJSONResponseForTool(name, arguments string) string {
return fmt.Sprintf(`{"id":"resp_1","status":"completed","output":[{"id":"fc_1","type":"function_call","status":"completed","call_id":"call_1","name":%q,"arguments":%q}]}`, name, arguments)
}
@@ -1500,6 +1946,32 @@ func autoReviewEventStream(t *testing.T, name, arguments string, extraOutput ...
return encoded
}
+func autoReviewTextEventStream(t *testing.T, text string) []byte {
+ t.Helper()
+ inProgressItem := map[string]any{
+ "id": "msg_1", "type": "message", "status": "in_progress", "role": "assistant", "content": []any{},
+ }
+ content := map[string]any{"type": "output_text", "text": text, "annotations": []any{}, "logprobs": []any{}}
+ completedItem := map[string]any{
+ "id": "msg_1", "type": "message", "status": "completed", "role": "assistant", "content": []any{content},
+ }
+ events := []serverSentEvent{
+ newServerSentEvent("response.created", map[string]any{"response": map[string]any{"id": "resp_1", "status": "in_progress", "output": []any{}}}),
+ newServerSentEvent("response.output_item.added", map[string]any{"output_index": 0, "item": inProgressItem}),
+ newServerSentEvent("response.content_part.added", map[string]any{"item_id": "msg_1", "output_index": 0, "content_index": 0, "part": map[string]any{"type": "output_text", "text": "", "annotations": []any{}, "logprobs": []any{}}}),
+ newServerSentEvent("response.output_text.delta", map[string]any{"item_id": "msg_1", "output_index": 0, "content_index": 0, "delta": text, "logprobs": []any{}}),
+ newServerSentEvent("response.output_text.done", map[string]any{"item_id": "msg_1", "output_index": 0, "content_index": 0, "text": text, "logprobs": []any{}}),
+ newServerSentEvent("response.content_part.done", map[string]any{"item_id": "msg_1", "output_index": 0, "content_index": 0, "part": content}),
+ newServerSentEvent("response.output_item.done", map[string]any{"output_index": 0, "item": completedItem}),
+ newServerSentEvent("response.completed", map[string]any{"response": map[string]any{"id": "resp_1", "status": "completed", "output": []any{completedItem}}}),
+ }
+ encoded, err := encodeServerSentEvents(events)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return encoded
+}
+
func TestCodexDesktopDoesNotAddForwardedHeaders(t *testing.T) {
forwardedHeaders := func(r *http.Request) []string {
var forwarded []string