diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 7b1512f22..7345442f6 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -5163,14 +5163,18 @@ func (r *subscriptionRun) launch() error { r.tree, r.exited = t, exited r.mu.Unlock() started := time.Now() - log.Printf("claude: Claude Code pid %d started, a run on %s", r.pid(), r.model) + mode := "claude -p" + if r.tui { + mode = "interactive mode" + } + log.Printf("claude: Claude Code pid %d started, a run on %s (%s)", r.pid(), r.model, mode) go func() { err := t.Wait() how := "exited" if err != nil { how = err.Error() } - log.Printf("claude: Claude Code pid %d (%s) ended after %s (%s), %d MiB resident at most", r.pid(), r.model, time.Since(started).Round(time.Second), how, proc.PeakRSS(r.cmd)>>20) + log.Printf("claude: Claude Code pid %d (%s, %s) ended after %s (%s), %d MiB resident at most", r.pid(), r.model, mode, time.Since(started).Round(time.Second), how, proc.PeakRSS(r.cmd)>>20) r.drain() // exited closes under mu, which abort reads it under: a run it // counts as leaving the room is one whose room is freed here @@ -5977,6 +5981,9 @@ func (s *Server) serveSubscription(w http.ResponseWriter, r *http.Request, from limitHeaders(w, owner) begin = func() { limitHeaders(w, owner) } } + run.mu.Lock() + req.interactive = run.tui + run.mu.Unlock() return relay(w, r, from, name, req, events, usage, abort, begin, func(said, stop string, ok bool) { if !gone() { return // the client went first: letGo has the run @@ -6011,6 +6018,44 @@ func bridgeFailed(name, msg string, status int) (int, string) { return 502, msg } +// thirdPartyWords is how Anthropic refuses a Claude subscription's turn +// it counts as a third-party app's: "API Error: 400 Third-party apps now +// draw from your extra usage, not your plan limits. Add more at +// claude.ai/settings/usage and keep going." (#4503, isjiajia01 and +// sounfury). isjiajia01's controlled tests had it of Claude Code's +// interactive mode (the cli entrypoint) told a client agent's own system +// prompt (Pi's, judged as a whole, no phrase of it alone), where claude -p +// (sdk-cli) was served the same prompt. +const thirdPartyWords = "Third-party apps now draw from your extra usage" + +// thirdPartyRefused is msg, the words a Claude Code run's failure is +// answered with, with what happened and what to do said after it when +// Anthropic refused the turn as a third-party app's (#4503). The bare +// 400 said "keep going" and nothing of why a client's turn was refused +// while plain ones were served. magpie never asks again on its own, as +// claude -p or otherwise: a second try may draw from the account's extra +// usage, which is the user's to spend (the owner's call on #4503). The +// refusal is about the request, the same on every account, so it stays a +// 400 that no account rests for and the next isn't asked +// (TestClaudeTUIRefusalIsNoAccountsFault). The words avoid quotaWords', +// which would read it as an account out of quota. +func thirdPartyRefused(name string, req *Request, code int, msg string) string { + if name != "Claude Code" || code != http.StatusBadRequest || !strings.Contains(msg, thirdPartyWords) { + return msg + } + if !req.interactive { + log.Printf("claude: Anthropic refused a claude -p turn on %s as a third-party app's (#4503)", req.Model) + return msg + " (magpie: Anthropic counted this turn, run as claude -p, as a third-party app's and answered nothing. " + + "Asking again may draw from the Claude account's extra usage, so magpie doesn't ask again on its own.)" + } + log.Printf("claude: Anthropic refused an interactive-mode turn on %s as a third-party app's (#4503)", req.Model) + return msg + " (magpie: Anthropic counted this turn as a third-party app's and answered nothing. " + + "It ran in Claude Code's interactive mode with your agent's own system prompt, which Anthropic can refuse there. " + + "Asking again the same way may draw from the Claude account's extra usage, so magpie doesn't ask again on its own. " + + "Claude Code as claude -p is served such prompts: turn off Claude Code's interactive mode in Settings › Models › Replies " + + "or in this provider's editor; the plan counts a -p request at about twice the interactive mode's.)" +} + // relay answers the client with a reply's events: abort is called when // there is no answer to give, ended when one was given, before its last // event goes out. @@ -6055,6 +6100,7 @@ func relay(w http.ResponseWriter, r *http.Request, from provider.Protocol, name if n > 0 { usage.add(Usage{ErrType: head[n-1].Code, RequestID: head[n-1].RequestID}) code, msg = bridgeFailed(name, msg, head[n-1].Status) + msg = thirdPartyRefused(name, req, code, msg) } return writeError(w, from, code, name+": "+msg), msg } @@ -6126,6 +6172,7 @@ func relay(w http.ResponseWriter, r *http.Request, from provider.Protocol, name usage.add(col.res.Usage) usage.add(Usage{ErrType: col.errCode}) code, msg := bridgeFailed(name, col.err, col.errStatus) + msg = thirdPartyRefused(name, req, code, msg) return writeError(w, from, code, name+": "+msg), msg } ended(said, stop, col.err == "" && r.Context().Err() == nil) diff --git a/internal/gateway/claude_tui_refusal_test.go b/internal/gateway/claude_tui_refusal_test.go index 1a271f129..80801a736 100644 --- a/internal/gateway/claude_tui_refusal_test.go +++ b/internal/gateway/claude_tui_refusal_test.go @@ -2,10 +2,13 @@ package gateway import ( "net/http/httptest" + "path/filepath" "strings" "testing" + "github.com/yetone/magpie/internal/claudetui" "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/testenv" ) // A request the interactive mode refuses is refused the same on every @@ -24,3 +27,100 @@ func TestClaudeTUIRefusalIsNoAccountsFault(t *testing.T) { t.Fatalf("the refusal is asked of the next account: %s", rec.Body.String()) } } + +// tuiThirdPartyRefusal is the 400 an interactive Claude Code answers a +// turn Anthropic counts as a third-party app's, in the words isjiajia01 +// and sounfury reported (#4503). +const tuiThirdPartyRefusal = `{"type":"result","subtype":"error_during_execution","is_error":true,"result":"API Error: 400 Third-party apps now draw from your extra usage, not your plan limits. Add more at claude.ai/settings/usage and keep going.","api_error_status":400}` + +// tuiThirdPartyHarness is tuiHelperHarness whose interactive Claude Code +// answers every turn with that refusal; as claude -p it answers "ok". +// (ggbdpq's harness, #4503.) +func tuiThirdPartyHarness(t *testing.T) (*resumeHarness, string) { + t.Helper() + start := `if [ -n "$MG_TEST_TUI" ]; then + echo '{"type":"system","subtype":"init","session_id":"'$sid'"}' + 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 + echo '` + tuiThirdPartyRefusal + `' + exit 1 + done + exit 0 +fi +` + h := newScriptHarness(t, "ok", start) + claudeTUIRuns = true + t.Cleanup(func() { claudeTUIRuns = false }) + started := filepath.Join(t.TempDir(), "started") + helper := filepath.Join(t.TempDir(), "magpie") + testenv.Program(t, helper, `#!/bin/sh +[ "$1" = "`+claudetui.Command+`" ] || exit 9 +echo start >> '`+started+`' +MG_TEST_TUI=1 +export MG_TEST_TUI +shift; claude=$1; shift +exec "$claude" "$@" +`) + claudeTUIHelper = helper + t.Cleanup(func() { claudeTUIHelper = "" }) + return h, started +} + +// A turn Anthropic refuses in the interactive mode as a third-party app's +// (#4503) reaches the client as a 400 that says what happened, that asking +// again may draw from extra usage, and where to turn the interactive mode +// off. magpie asks nothing again on its own: no claude -p run starts, which +// the plan counts at about twice and which may draw from extra usage (the +// owner's call), and no account rests for it or is asked next. +func TestClaudeTUIThirdPartyRefusalSaysWhy(t *testing.T) { + for _, stream := range []bool{false, true} { + t.Run(map[bool]string{false: "whole", true: "stream"}[stream], func(t *testing.T) { + h, started := tuiThirdPartyHarness(t) + s := "" + if stream { + s = `"stream":true,` + } + body := `{"model":"claude-sonnet-5","max_tokens":100,` + s + `"system":"You are pi, a coding agent harness.","tools":[{"name":"read","input_schema":{"type":"object"}}],"messages":[{"role":"user","content":"hi"}]}` + rec := httptest.NewRecorder() + var u Usage + code, msg := h.s.serveClaudeSubscription(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, h.p, "claude-sonnet-5", []byte(body), &u) + if code != 400 { + t.Fatalf("%d %.400s", code, msg) + } + for _, w := range []string{thirdPartyWords, "interactive mode with your agent's own system prompt", "may draw from the Claude account's extra usage", "doesn't ask again on its own", "Settings › Models › Replies"} { + if !strings.Contains(msg, w) || !strings.Contains(rec.Body.String(), w) { + t.Fatalf("the client isn't told %q: %s", w, rec.Body.String()) + } + } + if n := helperStarts(started); n != 1 { + t.Fatalf("the interactive mode started %d times, want once", n) + } + if runs := h.runs(); len(runs) != 1 { + t.Fatalf("%d runs, want the interactive one alone: nothing is asked again as claude -p", len(runs)) + } + if retryable(code, rec.Body.Bytes()) { + t.Fatalf("the refusal is asked of the next account: %s", rec.Body.String()) + } + switch f := failure(code, rec.Body.Bytes()); f { + case failCredit, failQuota, failRate, failAuth: + t.Fatalf("the refusal reads as the account's (%s): %s", f, rec.Body.String()) + } + }) + } +} + +// The same refusal of a claude -p run says so without telling the user to +// turn the interactive mode off, which it already is. +func TestClaudeThirdPartyRefusalOfPrint(t *testing.T) { + msg := thirdPartyRefused("Claude Code", &Request{Model: "m"}, 400, "API Error: 400 Third-party apps now draw from your extra usage, not your plan limits.") + if !strings.Contains(msg, "run as claude -p") || strings.Contains(msg, "turn off") { + t.Fatal(msg) + } + if got := thirdPartyRefused("Claude Code", &Request{interactive: true}, 502, "other"); got != "other" { + t.Fatal(got) + } +} diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go index d7a8f2716..35bf9565c 100644 --- a/internal/gateway/ir.go +++ b/internal/gateway/ir.go @@ -219,6 +219,10 @@ type Request struct { // replayed: the run started was given the conversation as a // transcript (replaySession) replayed bool + // interactive, for the Claude bridge, is that the run answering this + // request is Claude Code's interactive mode, not claude -p: what a + // refusal it ends in is told with (thirdPartyRefused, #4503) + interactive bool // hourMarks has the cache marks magpie adds on Anthropic's Messages // (anthropicBody) last an hour: a Responses client's (Codex's), whose // turns are often more than five minutes apart and whose own vendor