gateway: a Claude Code run on an account asks Anthropic's own models, never magpie's routing names

@ahz2ygnhjmIJ0E0 on X (v0.1.4573): the Claude warm-up sent
claude/claude-haiku-5-5 and group/opus-5-5[1m] to Anthropic, which
answered "There's an issue with the selected model", so the 5-hour
window never opened.

Cause: the warm-up runs `claude -p --model haiku --setting-sources ""`.
--setting-sources keeps settings.json's env out, but Claude Code 2.1.327
still takes the tier variables (ANTHROPIC_DEFAULT_HAIKU_MODEL, ...) from
its own environment, which cleanClaudeEnv passed on from magpie's, and
from ~/.claude.json's legacy env, read whatever --setting-sources says.
Where they hold magpie's routing names, haiku resolved to
claude/claude-haiku-5-5 and opus to group/opus-5-5 (the [1m] cut off).

Fix, for every Claude Code run on an account (warm-up, Warm up now, the
model test, /usage, the bridge's turns, -p and interactive): each run's
--settings sets every model variable (ANTHROPIC_MODEL, each tier's model
and its _NAME/_DESCRIPTION/_SUPPORTED_CAPABILITIES, the small fast,
subagent and auto mode models) to "", which outranks both the
environment and ~/.claude.json, and an empty one is Claude Code's own
default; cleanClaudeEnv no longer passes them on either. An id given
with --model (claude-opus-5-5[1m]) is sent as given. There is no
warm-up model setting: the warm-up asks the haiku alias, so no picker
to limit. Codex's warm-up already asks the account's own catalog id.

Run:
- TestClaudeRunsAskAnthropicsOwnModels (new; the reporter's literal
  names in magpie's env) red on 9494a38b4 for the warm-up, model test,
  /usage, the bridge's args and its env; green after (mica-run, mote-run).
- go test ./internal/gateway -run 'TestClaudeRunsAskAnthropicsOwnModels|
  TestWarmClaude|TestClaudeUsage|TestClaudeCLI|TestAskClaude|
  TestCleanClaudeEnv|TestClaudeTest|Claude.*Settings|TestClaudeBridge'
  ok on mote; gofmt clean. The same run again after rebasing onto
  eae77a48a (this commit's parent): ok on mica.
- Real Claude Code 2.1.327, sandbox HOME, against a local fake
  Messages server logging the model, with ANTHROPIC_DEFAULT_HAIKU_MODEL
  and ANTHROPIC_MODEL set to the reporter's names in the env and
  ~/.claude.json: old --settings sent claude/claude-haiku-5-5 (haiku) and
  group/opus-5-5 (opus); new sends claude-haiku-5-5 and claude-opus-5-5;
  claude-opus-5-5[1m] went as claude-opus-5-5 both ways. Process env
  alone and ~/.claude.json alone each leaked on the old settings.

Not tried: a warm-up against Anthropic on a real account; the
interactive mode's run with a real account; Windows/WSL Claude Code.
The full suite (go test -timeout 45m ./..., Linux/Windows vet of
internal/gateway) was started on mote at the tree before the rebase and is not in this
record.
This commit is contained in:
yetone
2026-11-20 14:29:12 +08:00
parent eae77a48a0
commit 848e3b1b26
6 changed files with 166 additions and 6 deletions
+113
View File
@@ -0,0 +1,113 @@
package gateway
import (
"context"
"encoding/json"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/yetone/magpie/internal/testenv"
)
// A Claude Code run on an account (the warm-up, a model test, /usage, a
// bridge's turns) goes to Anthropic, which knows none of magpie's routing
// names. Where magpie wires Claude Code to itself, the variables its
// aliases resolve through hold them (claude/claude-haiku-5-5,
// group/opus-5-5[1m]); one in magpie's environment, or in ~/.claude.json's
// env, which Claude Code reads whatever --setting-sources says, made the
// warm-up's haiku ask Anthropic for claude/claude-haiku-5-5, refused "There's
// an issue with the selected model", and the 5-hour window never opened
// (@ahz2ygnhjmIJ0E0 on X). Each run's --settings sets them empty, which
// outranks both, and none of them is passed on from magpie's environment.
func TestClaudeRunsAskAnthropicsOwnModels(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("a shell script stands in for Claude Code")
}
dir := t.TempDir()
log := filepath.Join(dir, "log")
// each argument on its own line, then the model variables it was given
script := "#!/bin/sh\n{ for a in \"$@\"; do printf 'arg:%s\\n' \"$a\"; done; env | grep -E '^(ANTHROPIC_|CLAUDE_CODE_SUBAGENT|CLAUDE_CODE_AUTO_MODE)' ; } > " + log + "\n" +
"cat >/dev/null\necho '{\"type\":\"result\",\"is_error\":false,\"result\":\"Hi!\"}'\n"
testenv.Program(t, filepath.Join(dir, "claude"), script)
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
// the reporter's names, as a Claude Code wired to magpie holds them
reporter := map[string]string{
"ANTHROPIC_MODEL": "group/opus-5-5[1m]",
"ANTHROPIC_DEFAULT_OPUS_MODEL": "group/opus-5-5[1m]",
"ANTHROPIC_DEFAULT_SONNET_MODEL": "claude/claude-sonnet-5-5",
"ANTHROPIC_DEFAULT_HAIKU_MODEL": "claude/claude-haiku-5-5",
"ANTHROPIC_SMALL_FAST_MODEL": "claude/claude-haiku-5-5",
"CLAUDE_CODE_SUBAGENT_MODEL": "claude/claude-haiku-5-5",
}
for k, v := range reporter {
t.Setenv(k, v)
}
runs := map[string]func() error{
"warm-up": func() error { return warmClaude(context.Background(), "") },
"model test": func() error { return askClaude(context.Background(), "", "claude-haiku-5-5") },
"/usage": func() error { _, err := claudeUsage(context.Background(), ""); return err },
}
for name, run := range runs {
_ = os.Remove(log)
if err := run(); err != nil {
t.Fatalf("%s: %v", name, err)
}
b, _ := os.ReadFile(log)
got := string(b)
for _, v := range []string{"claude/", "group/"} {
if strings.Contains(got, "="+v) {
t.Errorf("%s: Claude Code was given magpie's names in its environment:\n%s", name, got)
break
}
}
checkOwnModelSettings(t, name, strings.Split(got, "\n"), reporter)
}
// a bridge's turns
args := claudeCLIArgs("claude-opus-5-5[1m]", `{}`, "", false)
var lines []string
for _, a := range args {
lines = append(lines, "arg:"+a)
}
checkOwnModelSettings(t, "a bridge run", lines, reporter)
// and its environment
for _, e := range claudeRunEnv(os.Environ(), "1h") {
if k, _, _ := strings.Cut(e, "="); reporter[k] != "" {
t.Errorf("a bridge run keeps %s", e)
}
}
}
// checkOwnModelSettings has the run's --settings set each of reporter's
// variables, and each tier's, to "", so an alias resolves to Anthropic's own
// model whatever magpie's environment or ~/.claude.json say.
func checkOwnModelSettings(t *testing.T, name string, lines []string, reporter map[string]string) {
t.Helper()
var set string
for i, l := range lines {
if l == "arg:--settings" && i+1 < len(lines) {
set = strings.TrimPrefix(lines[i+1], "arg:")
}
}
var s struct {
DeepLink string `json:"disableDeepLinkRegistration"`
Env map[string]*string `json:"env"`
}
if err := json.Unmarshal([]byte(set), &s); err != nil {
t.Fatalf("%s: --settings %q: %v", name, set, err)
}
if s.DeepLink != "disable" {
t.Errorf("%s: --settings %s lost disableDeepLinkRegistration", name, set)
}
want := []string{"ANTHROPIC_DEFAULT_FABLE_MODEL"}
for k := range reporter {
want = append(want, k)
}
for _, k := range want {
if v, ok := s.Env[k]; !ok || v == nil || *v != "" {
t.Errorf("%s: --settings %s doesn't set %s empty", name, set, k)
}
}
}
+4
View File
@@ -4133,6 +4133,10 @@ func cleanClaudeEnvTTL(env []string, ttl string) []string {
"CLAUDE_CODE_OAUTH_TOKEN": true, "CLAUDE_CODE_PROMPT_CACHE_TTL": true, "FORCE_PROMPT_CACHING_5M": true,
"CLAUDE_CODE_EXTRA_BODY": true, "ANTHROPIC_BETAS": true,
}
// magpie's routing names, never Anthropic's (claudeModelEnv)
for _, k := range claudeModelEnv {
blocked[k] = true
}
out := make([]string, 0, len(env)+3)
for _, e := range env {
k, _, _ := strings.Cut(e, "=")
+1 -1
View File
@@ -43,7 +43,7 @@ func TestClaudeSubscriptionPromptKeepsForeignHarnessOutOfSystem(t *testing.T) {
// the setting is passed as flag settings, which --setting-sources does
// not control.
for _, want := range []string{"--input-format stream-json", "--include-partial-messages", "--strict-mcp-config", "--effort medium",
`--settings {"disableDeepLinkRegistration":"disable","showThinkingSummaries":true}`} {
`--settings {"disableDeepLinkRegistration":"disable",`, `"showThinkingSummaries":true}`} {
if !strings.Contains(args, want) {
t.Fatalf("missing CLI contract %q in %q", want, args)
}
+1 -1
View File
@@ -111,7 +111,7 @@ exec "$claude" "$@"
if want := "-p --output-format stream-json --input-format stream-json --verbose --model haiku --tools --strict-mcp-config --setting-sources "; !strings.Contains(args, want) {
t.Fatalf("Claude Code ran with %q", args)
}
if want := `--settings {"disableDeepLinkRegistration":"disable"}`; !strings.Contains(args, want) {
if want := `--settings {"disableDeepLinkRegistration":"disable",`; !strings.Contains(args, want) {
t.Fatalf("Claude Code registers no URL handler, ran with %q", args)
}
if !strings.Contains(told, `told {"message":{"content":[{"text":"hi","type":"text"}],"role":"user"},"type":"user"}`) {
+45 -2
View File
@@ -584,14 +584,57 @@ func claudeResult(b []byte) (claudeRun, bool) {
// has no use for the handler. --settings is not one of the sources
// --setting-sources controls, so this applies however the user's settings
// read.
const disableDeepLinkSettings = `{"disableDeepLinkRegistration":"disable"}`
var disableDeepLinkSettings = withAnthropicModels(`{"disableDeepLinkRegistration":"disable"}`)
// claudeModelEnv are the variables Claude Code picks a model by: the main
// one, each tier's (what its alias, haiku in the warm-up, resolves to) and
// what /model says of it, the small fast model, the subagents' and the auto
// mode classifier's. Where magpie wires Claude Code to itself they hold
// magpie's routing names (claude/claude-haiku-5-5, group/opus-5-5[1m]),
// while a run on an account goes to Anthropic, which knows none of them.
// One in magpie's environment, or in ~/.claude.json's env, which Claude
// Code reads whatever --setting-sources says (2.1.327), sent the warm-up's
// haiku as claude/claude-haiku-5-5: Anthropic answered "There's an issue
// with the selected model" and the 5-hour window never opened
// (@ahz2ygnhjmIJ0E0 on X).
var claudeModelEnv = func() []string {
out := []string{"ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_MODEL", "ANTHROPIC_SMALL_FAST_MODEL",
"CLAUDE_CODE_SUBAGENT_MODEL", "CLAUDE_CODE_AUTO_MODE_MODEL"}
for _, tier := range []string{"OPUS", "SONNET", "HAIKU", "FABLE"} {
for _, s := range []string{"", "_NAME", "_DESCRIPTION", "_SUPPORTED_CAPABILITIES"} {
out = append(out, "ANTHROPIC_DEFAULT_"+tier+"_MODEL"+s)
}
}
return out
}()
// withAnthropicModels is the --settings JSON object settings with each of
// claudeModelEnv set empty in its env: --settings outranks both the
// environment and ~/.claude.json, and an empty one is Claude Code's own
// default, so an alias is Anthropic's model and an id stays as given.
func withAnthropicModels(settings string) string {
var m map[string]any
if err := json.Unmarshal([]byte(settings), &m); err != nil {
panic(err)
}
env := map[string]string{}
for _, k := range claudeModelEnv {
env[k] = ""
}
m["env"] = env
b, err := json.Marshal(m)
if err != nil {
panic(err)
}
return string(b)
}
// claudeRunSettings is a run's settings: no deep link, and the thinking
// shown as a summary. -p has --thinking-display, but the interactive mode
// (interactiveArgs drops that flag) shows none unless showThinkingSummaries
// is on, so a client saw no thinking at all (DIYgod on X, #5379). It costs
// no quota.
const claudeRunSettings = `{"disableDeepLinkRegistration":"disable","showThinkingSummaries":true}`
var claudeRunSettings = withAnthropicModels(`{"disableDeepLinkRegistration":"disable","showThinkingSummaries":true}`)
func claudeUsageArgs() []string {
return []string{"-p", "/usage", "--output-format", "json",
+2 -2
View File
@@ -46,7 +46,7 @@ func TestWarmClaudeAsksClaudeCodeOnce(t *testing.T) {
b, _ := os.ReadFile(log)
got := string(b)
for _, want := range []string{"[-p]", "[--model][haiku]", "[--tools][]", "[--setting-sources][]", "[--no-session-persistence]",
`[--settings][{"disableDeepLinkRegistration":"disable"}]`,
`[--settings][{"disableDeepLinkRegistration":"disable",`,
"dir:/saved/account\n", "base:\n", "stdin:hi", "magpie-claude-"} {
if !strings.Contains(got, want) {
t.Errorf("run lacks %q:\n%s", want, got)
@@ -120,7 +120,7 @@ func TestClaudeUsageRunsClaudeCode(t *testing.T) {
}
b, _ = os.ReadFile(log)
for _, want := range []string{"[-p][/usage]", "[--setting-sources][]", "[--strict-mcp-config]", "[--no-session-persistence]", "token:\n",
`[--settings][{"disableDeepLinkRegistration":"disable"}]`} {
`[--settings][{"disableDeepLinkRegistration":"disable",`} {
if !strings.Contains(string(b), want) {
t.Errorf("run lacks %q:\n%s", want, b)
}