diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index a985591af..11f995ab8 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -154,6 +154,11 @@ type subscriptionRun struct { // the tools its agent was told of, as it started and since tools map[string]bool + // allowed is the client's tools its turn under way may call, nil for + // every one: none when the client chose none (tool_choice), its tools + // still offered, so Claude Code asks Anthropic the prefix the + // conversation's other turns cached (allowedTools). Under r.mu. + allowed map[string]bool // names is the caller's name of each tool by the name the run's agent // has it under (bridgeToolName), for those it differs: under r.mu names map[string]string @@ -977,6 +982,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, run.lean = req.leanPrompt run.tui = tui run.cachePrefix = prefix + run.allowed = allowedTools(req) if user, _ := ownerAccount(owner); user != "" { run.loginVersion = provider.ClaudeLoginVersion(user) } @@ -1494,6 +1500,7 @@ func (b *subscriptionBridge) resume(req *Request, owner string) (*subscriptionRu run.segment = ch run.active = time.Now() run.turnUUID, run.backKey = turn, key + run.allowed = allowedTools(req) run.mu.Unlock() run.endIn(runTimeout) // a turn the router picked another effort for (#502) goes on in the @@ -2851,10 +2858,12 @@ func (r *subscriptionRun) readOutput(rd io.Reader) { r.mu.Lock() name = declaredName(r.names, name) search := r.search != nil && name == r.searchName + refused := r.allowed != nil && !r.allowed[name] r.mu.Unlock() // magpie answers its own web search, as Claude Code does - // its WebSearch - if !ok || search { + // its WebSearch, and a call of a tool the turn may not call + // (mcpCall): the client is never shown it + if !ok || search || refused { own[index] = true return "", false } @@ -4539,6 +4548,15 @@ func (b *subscriptionBridge) mcpCall(w http.ResponseWriter, r *http.Request) { writeJSON(w, 200, mcpToolResult{Content: []map[string]any{{"type": "text", "text": found}}}) return } + run.mu.Lock() + refused := run.allowed != nil && !run.allowed[call.Name] + run.mu.Unlock() + if refused { + // the client chose no tool for this turn: the call is answered + // here, and Claude Code goes on to answer in words + writeJSON(w, 200, mcpToolResult{Content: []map[string]any{{"type": "text", "text": "No tool can be used for this reply. Answer without tools."}}, IsError: true}) + return + } waiter := make(chan mcpToolResult, 1) run.mu.Lock() if result, ok := run.early[call.ToolCallID]; ok { @@ -5335,6 +5353,11 @@ func (s *Server) serveSubscription(w http.ResponseWriter, r *http.Request, from run.mu.Unlock() } if err == nil { + // the turn may call what this request lets it: a client may + // choose none once it has its tools' results + run.mu.Lock() + run.allowed = allowedTools(req) + run.mu.Unlock() events, err = run.continueWith(withTaskNotices(results, req.Messages), saidWithResults(req.Messages), more) } if err != nil { @@ -5564,11 +5587,16 @@ func relay(w http.ResponseWriter, r *http.Request, from provider.Protocol, name } // bridgeTools are the caller's tools as the MCP helper offers them, less -// those tool_choice rules out. +// those a named tool_choice rules out. A choice of none keeps them all: +// Anthropic caches a prompt as its tools, then its system prompt, then +// its messages, so a turn told none of them is a prefix the cache has +// never seen, and was written to it whole, its tools and system prompt +// too (bbfatx on X: a title or a summary asked with tool_choice none, of +// a long conversation). The turn may call none of them (allowedTools). func bridgeTools(req *Request) []bridgeTool { tools := make([]bridgeTool, 0, len(req.Tools)) for _, t := range req.Tools { - if req.ToolChoice == "none" || (strings.HasPrefix(req.ToolChoice, "name:") && t.Name != strings.TrimPrefix(req.ToolChoice, "name:")) { + if strings.HasPrefix(req.ToolChoice, "name:") && t.Name != strings.TrimPrefix(req.ToolChoice, "name:") { continue } schema := t.Schema @@ -5579,3 +5607,12 @@ func bridgeTools(req *Request) []bridgeTool { } return tools } + +// allowedTools is the client's tools a turn of req may call, nil for all +// it offers (subscriptionRun.allowed): none when it chose none. +func allowedTools(req *Request) map[string]bool { + if req.ToolChoice == "none" { + return map[string]bool{} + } + return nil +} diff --git a/internal/gateway/claude_subscription_prefix_test.go b/internal/gateway/claude_subscription_prefix_test.go new file mode 100644 index 000000000..38aa4f4e6 --- /dev/null +++ b/internal/gateway/claude_subscription_prefix_test.go @@ -0,0 +1,228 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "regexp" + "runtime" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/testenv" +) + +// prefixHarness is a gateway whose Claude subscription runs a stand-in +// for Claude Code that keeps its session as Claude Code does: a line for +// each user message it is told and each reply, with its uuid and the +// session's id. It logs its arguments, the tools its MCP helper offers +// (.tools) and each line it is told, and answers "pid P had H turn +// T": H the lines its session had as it started (a branch's copy, or a +// resumed session), T the turns it was told. A turn that says CALLTOOL +// calls the client's read tool first and says what the call was answered. +type prefixHarness struct { + t *testing.T + s *Server + srv *httptest.Server + logs string + config string +} + +func newPrefixHarness(t *testing.T) *prefixHarness { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("a shell script stands in for Claude Code") + } + if _, err := exec.LookPath("curl"); err != nil { + t.Skip("the script makes its MCP calls with curl") + } + home := t.TempDir() + testenv.SetHome(t, home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + config := filepath.Join(home, ".claude") + t.Setenv("CLAUDE_CONFIG_DIR", config) + os.MkdirAll(config, 0o755) + os.WriteFile(filepath.Join(config, ".credentials.json"), mustJSON(map[string]any{"claudeAiOauth": map[string]any{ + "accessToken": "tok-lead", "refreshToken": "r-lead", "expiresAt": time.Now().Add(24 * time.Hour).UnixMilli(), "subscriptionType": "max"}}), 0o600) + os.WriteFile(filepath.Join(home, ".claude.json"), mustJSON(map[string]any{ + "oauthAccount": map[string]any{"emailAddress": "lead@example.com", "accountUuid": "u-lead"}}), 0o600) + dir, logs := t.TempDir(), t.TempDir() + testenv.Program(t, filepath.Join(dir, "claude"), `#!/bin/sh +if [ "$1" = auth ]; then echo '{"loggedIn":true,"authMethod":"claude.ai","apiProvider":"firstParty","email":"lead@example.com","subscriptionType":"max"}'; exit 0; fi +log=`+logs+`/$$ +echo "args $*" > $log +helper=$(printf '%s\n' "$@" | grep -o '"claude-mcp-helper","[^"]*","[^"]*"' | head -1) +cb=$(cat "$(printf '%s' "$helper" | sed 's/^"claude-mcp-helper","//; s/",".*//')") +cp "$(printf '%s' "$helper" | sed 's/.*","//; s/"$//')" `+logs+`/$$.tools +sid=s$$; prev= +for a in "$@"; do + if [ "$prev" = --resume ]; then sid=$a; fi + prev=$a +done +proj="$CLAUDE_CONFIG_DIR/projects/$(pwd -P | sed 's/[^A-Za-z0-9]/-/g')" +mkdir -p "$proj" +f="$proj/$sid.jsonl" +had=$(cat "$f" 2>/dev/null | wc -l | tr -d ' ') +echo '{"type":"system","subtype":"init","session_id":"'$sid'"}' +n=0; m=0 +say() { + m=$((m+1)) + echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m'$$'-'$m'","model":"claude-opus-5-5","usage":{"input_tokens":1}}}}' + echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"'"$1"'"}}}' + echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}}' + echo '{"type":"stream_event","event":{"type":"message_stop"}}' + echo '{"type":"assistant","uuid":"a'$$'-'$m'","sessionId":"'$sid'","message":{"role":"assistant","content":[{"type":"text","text":"'"$1"'"}]}}' >> "$f" + echo '{"type":"assistant","uuid":"a'$$'-'$m'","message":{"id":"m'$$'-'$m'","model":"claude-opus-5-5","content":[{"type":"text","text":"'"$1"'"}]}}' + echo '{"type":"result","subtype":"success","is_error":false,"result":""}' +} +while read -r line; do + case "$line" in *'"type":"control_request"'*) + id=$(printf '%s' "$line" | sed 's/.*"request_id":"\([^"]*\)".*/\1/') + echo '{"type":"control_response","response":{"subtype":"success","request_id":"'$id'"}}' + continue ;; + esac + n=$((n+1)) + echo "told $line" >> $log + echo '{"type":"user","uuid":"u'$$'-'$n'","sessionId":"'$sid'","message":{"role":"user","content":"x"}}' >> "$f" + case "$line" in *CALLTOOL*) + m=$((m+1)) + echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m'$$'-'$m'","model":"claude-opus-5-5","usage":{"input_tokens":1}}}}' + echo '{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_R'$$'_'$n'","name":"mcp__magpie__read"}}}' + echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{}"}}}' + echo '{"type":"stream_event","event":{"type":"content_block_stop","index":0}}' + echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":3}}}' + echo '{"type":"stream_event","event":{"type":"message_stop"}}' + echo '{"type":"assistant","uuid":"a'$$'-'$m'","sessionId":"'$sid'","message":{"role":"assistant","content":[{"type":"tool_use","id":"toolu_R'$$'_'$n'","name":"mcp__magpie__read","input":{}}]}}' >> "$f" + echo '{"type":"assistant","uuid":"a'$$'-'$m'","message":{"id":"m'$$'-'$m'","model":"claude-opus-5-5","content":[{"type":"tool_use","id":"toolu_R'$$'_'$n'","name":"mcp__magpie__read","input":{}}]}}' + got=$(curl --noproxy '*' -s -m 20 -X POST -H 'Content-Type: application/json' --data '{"tool_call_id":"toolu_R'$$'_'$n'","name":"read","arguments":{}}' "$cb") + case "$got" in *"No tool can be used"*) got=refused ;; *) got=answered ;; esac + say "pid $$ had $had turn $n call $got" + continue ;; + esac + say "pid $$ had $had turn $n" +done +`) + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + provider.ForgetAccounts() + t.Cleanup(provider.ForgetAccounts) + if err := provider.SaveGroup(provider.Group{ID: "orchestrator", Name: "Orchestrator", Members: []string{"claude/claude-opus-5-5"}}); err != nil { + t.Fatal(err) + } + s := New() + srv := httptest.NewServer(s.Handler()) + t.Cleanup(srv.Close) + t.Cleanup(s.subscription.abortAll) // before srv.Close: a run's MCP call holds a request open + t.Setenv("MAGPIE_ADDR", srv.Listener.Addr().String()) + return &prefixHarness{t: t, s: s, srv: srv, logs: logs, config: config} +} + +// prefixTools is the client's tools, as the harness's requests offer them. +const prefixTools = `[{"name":"read","description":"Read a file","input_schema":{"type":"object","properties":{"path":{"type":"string"}}}},{"name":"bash","description":"Run a command","input_schema":{"type":"object","properties":{"command":{"type":"string"}}}}]` + +var prefixAnswer = regexp.MustCompile(`pid (\d+) had (\d+) turn (\d+)( call [a-z]+)?`) + +// ask posts messages with extra fields (`"tools":…,` and the like) and +// gives the answer, "pid P had H turn T", and the whole body. +func (h *prefixHarness) ask(extra, messages string) (string, string) { + h.t.Helper() + res, err := http.Post(h.srv.URL+"/v1/messages", "application/json", strings.NewReader( + `{"model":"group/orchestrator","max_tokens":1000,"stream":true,"system":"be brief",`+extra+`"messages":`+messages+`}`)) + if err != nil { + h.t.Fatal(err) + } + defer res.Body.Close() + b, _ := io.ReadAll(res.Body) + if res.StatusCode != 200 { + h.t.Fatalf("%d %.600s", res.StatusCode, b) + } + return prefixAnswer.FindString(string(b)), string(b) +} + +// log is what the run of pid was started with and told. +func (h *prefixHarness) log(pid string) string { + b, _ := os.ReadFile(filepath.Join(h.logs, pid)) + return string(b) +} + +// pids are the runs started so far. +func (h *prefixHarness) pids() []string { + entries, _ := os.ReadDir(h.logs) + var pids []string + for _, e := range entries { + if !strings.Contains(e.Name(), ".") { + pids = append(pids, e.Name()) + } + } + return pids +} + +// tools is the tools the run of pid's MCP helper offered its agent. +func (h *prefixHarness) tools(pid string) []bridgeTool { + h.t.Helper() + b, err := os.ReadFile(filepath.Join(h.logs, pid+".tools")) + if err != nil { + h.t.Fatal(err) + } + var tools []bridgeTool + if err := json.Unmarshal(b, &tools); err != nil { + h.t.Fatalf("%v: %s", err, b) + } + return tools +} + +func answerPID(t *testing.T, answer string) string { + t.Helper() + m := prefixAnswer.FindStringSubmatch(answer) + if m == nil { + t.Fatalf("answer %q", answer) + } + return m[1] +} + +// bbfatx on X: a client asks a conversation's title or summary with +// tool_choice none and its tools as ever, so the request shares the +// conversation's cached prefix. The bridge offered such a turn's Claude +// Code no tools at all, and Anthropic caches a prompt as its tools, then +// its system prompt, then its messages: the turn was a prefix the cache +// had never seen, all of it written again, Claude Code's own tools and +// system prompt too (measured with Claude Code 2.1.316 against a stand-in +// that counts as Anthropic's cache does: 0 read and 7595 written, where +// the same turn offered its tools read 15780 of them). It is offered +// every tool the client sent, and may call none: a call it makes is +// answered at once, never shown to the client, and the reply goes on in +// words. +func TestClaudeToolChoiceNoneKeepsTheTools(t *testing.T) { + h := newPrefixHarness(t) + conv := `[` + rmsg("user", "fix the bug") + `,` + rmsg("assistant", "done") + `,` + rmsg("user", "Write a title for this conversation. CALLTOOL") + `]` + answer, body := h.ask(`"tools":`+prefixTools+`,"tool_choice":{"type":"none"},`, conv) + pids := h.pids() + if len(pids) != 1 { + t.Fatalf("runs %v", pids) + } + pid := pids[0] + var names []string + for _, tool := range h.tools(pid) { + names = append(names, tool.Name) + } + if strings.Join(names, ",") != "read,bash" { + t.Errorf("a tool_choice none turn's Claude Code was offered %v, want every tool the client sent", names) + } + if !strings.HasSuffix(answer, " call refused") { + t.Errorf("the turn's call was %q, want it refused", answer) + } + if strings.Contains(body, `"tool_use"`) || strings.Contains(body, "toolu_R") { + t.Errorf("the client was shown a call it chose none of: %.800s", body) + } + // a turn that may call them hands its call to the client, as ever + _, body = h.ask(`"tools":`+prefixTools+`,`, `[`+rmsg("user", "read it. CALLTOOL")+`]`) + if !strings.Contains(body, `"tool_use"`) || !strings.Contains(body, `"name":"read"`) { + t.Errorf("a turn of tool_choice auto was not shown its call: %.800s", body) + } +}