diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 87f22c6bb..1db6a573e 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -61,6 +61,7 @@ import ( "unicode/utf8" "github.com/santhosh-tekuri/jsonschema/v6" + "github.com/yetone/magpie/internal/access" "github.com/yetone/magpie/internal/appdir" "github.com/yetone/magpie/internal/bridgesid" "github.com/yetone/magpie/internal/catalog" @@ -348,9 +349,14 @@ type subscriptionRun struct { // the run now answers, adviceReq, its nth call made after said. The // run's agent is offered magpie's tools only, never the server tool. // adviceSaid is the reply's words so far, and advised the calls of - // it, both counted from the request. Under mu. + // it, both counted from the request. asker is the caller of the + // request the run answers now: its advisor and web search are asked + // as it, held to its key's models, accounts and limits, never as the + // run's own MCP call from this computer, which carries no key. + // Under mu. advice func(ctx context.Context, q *Request, said []Part, c Part, n int) (Part, Event) adviceReq *Request + asker access.Identity adviceSaid []string advised int // answerName is the interactive mode's answer tool for a request with @@ -4120,11 +4126,13 @@ func (r *subscriptionRun) emit(ev Event) { // adviseOn has the run answer the advisor calls of the reply to req, the // advisor seeing req's conversation, with advice when req asks for the -// advisor; a request that doesn't takes it away. -func (r *subscriptionRun) adviseOn(req *Request, advice func(ctx context.Context, q *Request, said []Part, c Part, n int) (Part, Event)) { +// advisor; a request that doesn't takes it away. ctx is req's own: the +// advisor and web search are asked as its caller. +func (r *subscriptionRun) adviseOn(ctx context.Context, req *Request, advice func(ctx context.Context, q *Request, said []Part, c Part, n int) (Part, Event)) { r.mu.Lock() defer r.mu.Unlock() r.advice, r.adviceReq, r.advised, r.adviceSaid = nil, nil, 0, nil + r.asker = access.Caller(ctx) if req.Advisor != "" { r.advice, r.adviceReq = advice, req } @@ -6354,7 +6362,7 @@ func (b *subscriptionBridge) mcpCall(w http.ResponseWriter, r *http.Request) { run.mu.Lock() call.Name = declaredName(run.names, call.Name) search, searchName, answerName := run.search, run.searchName, run.answerName - advice := run.advice + advice, asker := run.advice, run.asker run.mu.Unlock() if answerName != "" && call.Name == answerName { run.answer(w, call.Arguments) @@ -6363,11 +6371,13 @@ func (b *subscriptionBridge) mcpCall(w http.ResponseWriter, r *http.Request) { if advice != nil && call.Name == advisorTool { run.mu.Lock() run.advised++ - q, n := run.adviceReq, run.advised + q, n, who := run.adviceReq, run.advised, run.asker said := []Part{{Kind: Text, Text: strings.Join(run.adviceSaid, "")}} run.mu.Unlock() - // within the minute its MCP client waits for a call - ctx, cancel := context.WithTimeout(r.Context(), 55*time.Second) + // within the minute its MCP client waits for a call; asked as the + // client's request, held to its key, not as this call from the + // run's own Claude Code, which carries none + ctx, cancel := context.WithTimeout(access.WithIdentity(r.Context(), who), 55*time.Second) defer cancel() res, ev := advice(ctx, q, said, Part{Kind: ToolCall, ID: call.ToolCallID, Name: advisorTool}, n) run.emit(ev) @@ -6379,8 +6389,9 @@ func (b *subscriptionBridge) mcpCall(w http.ResponseWriter, r *http.Request) { Query string `json:"query"` } _ = json.Unmarshal(call.Arguments, &a) - // within the minute its MCP client waits for a call - ctx, cancel := context.WithTimeout(r.Context(), 55*time.Second) + // within the minute its MCP client waits for a call; asked as the + // client's request, its key's limits holding the searcher's spend + ctx, cancel := context.WithTimeout(access.WithIdentity(r.Context(), asker), 55*time.Second) defer cancel() found, hits, err := search(ctx, a.Query) if err != nil { @@ -7375,7 +7386,7 @@ func (s *Server) serveSubscriptionAs(w http.ResponseWriter, r *http.Request, fro run.mu.Lock() run.allowed = allowedTools(req) run.mu.Unlock() - run.adviseOn(req, s.adviceRound) + run.adviseOn(r.Context(), req, s.adviceRound) events, err = run.continueWith(withTaskNotices(withSkillBodies(results, req.Messages), req.Messages), saidWithResults(req.Messages), more) } if err != nil { @@ -7419,7 +7430,7 @@ func (s *Server) serveSubscriptionAs(w http.ResponseWriter, r *http.Request, fro run.answerName, run.answerSchema = answer.Name, answerSchema } run.mu.Unlock() - run.adviseOn(req, s.adviceRound) + run.adviseOn(r.Context(), req, s.adviceRound) } } if err != nil { diff --git a/internal/gateway/claude_subscription_advisor_test.go b/internal/gateway/claude_subscription_advisor_test.go index bf052ec23..36ac71c1c 100644 --- a/internal/gateway/claude_subscription_advisor_test.go +++ b/internal/gateway/claude_subscription_advisor_test.go @@ -1,6 +1,7 @@ package gateway import ( + "context" "encoding/json" "net/http/httptest" "strings" @@ -8,6 +9,7 @@ import ( "github.com/tidwall/gjson" + "github.com/yetone/magpie/internal/access" "github.com/yetone/magpie/internal/provider" ) @@ -72,7 +74,7 @@ func TestClaudeTUIAdvisorAnsweredHere(t *testing.T) { if err != nil { t.Fatal(err) } - c.run.adviseOn(q, New().adviceRound) + c.run.adviseOn(context.Background(), q, New().adviceRound) first := c.run.segment // a message's blocks are each a row of their own, by its id c.write(tuiRow("msg_a0", `{"type":"text","text":"Let me ask."}`, "tool_use", 4)) @@ -142,3 +144,62 @@ func (c *tuiCalls) adviceCall(id string) mcpToolResult { } return res } + +// The advisor a Claude subscription's run calls is asked as the client's +// request, held to its gateway key, never as the run's own MCP call from +// this computer, which carries no key. A key held to the subscription's +// model alone that names another model as its advisor is not given that +// model through the advisor: the call fails, and the advisor's provider +// is never asked. +func TestClaudeTUIAdvisorHeldToTheCallersKey(t *testing.T) { + u := advisedSetup(t) + c := newTUICalls(t) + q, err := bridgeRequest(httptest.NewRequest("POST", "/v1/messages", nil), provider.Anthropic, "Claude Code", []byte(advisorTurn("claude/claude-sonnet-5-5", "adv/adv-pro"))) + if err != nil { + t.Fatal(err) + } + if q.Advisor != "adv/adv-pro" { + t.Fatalf("the advisor is %q", q.Advisor) + } + held := access.WithIdentity(context.Background(), access.Identity{KeyID: "friend", KeyName: "Friend", Models: []string{"claude/claude-sonnet-5-5"}}) + c.run.adviseOn(held, q, New().adviceRound) + c.write(tuiRow("msg_a0", `{"type":"text","text":"Let me ask."}`, "tool_use", 4)) + c.write(tuiRow("msg_a1", `{"type":"tool_use","id":"toolu_adv0","name":"mcp__magpie__advisor","input":{}}`, "tool_use", 2)) + res := c.adviceCall("toolu_adv0") + c.write(tuiRow("msg_end", `{"type":"text","text":"Done."}`, "end_turn", 2), tuiDone) + if !res.IsError || res.Content[0]["text"] == "Check the tests first." { + t.Fatalf("a key held to the subscription's model was advised by adv/adv-pro: %+v", res) + } + u.mu.Lock() + asked := len(u.advisor) + u.mu.Unlock() + if asked != 0 { + t.Fatalf("the advisor's provider was asked %d times for a key that doesn't list it", asked) + } +} + +// The run's web search is asked as the client's request too: the +// searcher's spend counts against the client's gateway key and its limits +// hold it, never as the run's own MCP call, which carries no key. +func TestClaudeRunSearchAskedAsTheCaller(t *testing.T) { + var asked []access.Identity + run := &subscriptionRun{pending: map[string]chan mcpToolResult{}, searchName: "web_search"} + run.search = func(ctx context.Context, query string) (string, []Hit, error) { + asked = append(asked, access.Caller(ctx)) + return "found", nil, nil + } + b := &subscriptionBridge{runs: map[string]*subscriptionRun{"run": run}, calls: map[string]*subscriptionRun{}} + friend := access.Identity{KeyID: "friend", KeyName: "Friend", Limit: &access.Limit{Period: "day", Tokens: 700}} + q := &Request{Model: "claude/claude-sonnet-5-5"} + run.adviseOn(access.WithIdentity(context.Background(), friend), q, New().adviceRound) + r := httptest.NewRequest("POST", "/", strings.NewReader(`{"tool_call_id":"toolu_s","name":"web_search","arguments":{"query":"magpie"}}`)) + r.SetPathValue("token", "run") + rec := httptest.NewRecorder() + b.mcpCall(rec, r) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "found") { + t.Fatalf("the search call was answered %d %s", rec.Code, rec.Body) + } + if len(asked) != 1 || asked[0].KeyID != "friend" || asked[0].Limit == nil { + t.Fatalf("the search was asked as %+v, not the client's key", asked) + } +}