Files
magpie/internal/gateway/claude_subscription.go
T

1182 lines
34 KiB
Go

package gateway
// Claude Subscription is driven through the genuine Claude Code binary rather
// than by replaying its OAuth token over HTTP. Anthropic applies subscription
// eligibility checks to request content (not just credentials/CCH); prompts
// generated by Pi, OpenCode and other harnesses can otherwise be routed to
// Extra Usage. The subprocess keeps Claude Code's real Agent/CLI identity.
//
// Caller tools are exposed as an MCP server. A tools/call blocks in the hidden
// stdio helper while magpie returns the tool_use to the caller. The caller's next
// HTTP request supplies tool_result blocks, which unblock the same Claude Code
// turn. This is the protocol-neutral equivalent of pi-claude-bridge's parked
// Agent SDK query (https://github.com/elidickinson/pi-claude-bridge, MIT).
//
// A turn that ends leaves its Claude Code running, its input still open, for
// the conversation's next turn: that one is told only what the user said
// since, so the conversation Claude Code keeps goes on as it began and the
// prompt it has cached is read again. A new run would start from the whole
// history in one message, which shares nothing with what was cached but
// Claude Code's own prompt.
import (
"bufio"
"context"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/proc"
"github.com/yetone/magpie/internal/provider"
)
type subscriptionBridge struct {
mu sync.Mutex
runs map[string]*subscriptionRun // callback token → run
calls map[string]*subscriptionRun // tool_use id → run
idle map[string]*subscriptionRun // conversation so far (turnKey) → run
baseURL string
}
// A run left for its conversation's next turn waits idleLongest at most,
// and idleMost of them are kept, the longest waiting let go first: each is
// a Claude Code process.
const (
idleLongest = 20 * time.Minute
idleMost = 6
)
// parkLongest is how long a run started anew for each turn (Cursor)
// waits on its caller's tool results. A caller that quit, or was stopped,
// sends none; one whose tool ran longer gets its answer all the same, from a
// run started with the whole conversation, as its next turn would be.
var parkLongest = 5 * time.Minute
type subscriptionRun struct {
bridge *subscriptionBridge
token string
model string
cmd *exec.Cmd
tree *proc.Tree // cmd once started, with all it starts
tmp string
// the tools it was started with: its agent is told them once
tools map[string]bool
mu sync.Mutex
segment chan Event
pending map[string]chan mcpToolResult
closed bool
stderr strings.Builder
timer *time.Timer
// Claude Code's input, kept open for the next turn; owner is the account
// it runs as, and idleKey and idleAt say it is waiting for one.
stdin io.WriteCloser
owner string
idleKey string
idleAt time.Time
// An agent whose stream does not carry its tool calls in full (Cursor)
// learns of them here, as the MCP helper hands each one over, and opens
// each answer with a message start of its own.
onCall func(id, name string, args json.RawMessage)
// search answers magpie's web search tool, searchName, which the
// client never sees
search func(ctx context.Context, query string) (string, []Hit, error)
searchName string
begin func() Event
resume func() // after a resumed turn has its segment
// patience, when set, is how long a tool call may park before the agent
// is told it is still running (its MCP client gives up on a call at a
// minute); the result is then collected with waitTool, from late.
patience time.Duration
late map[string]chan mcpToolResult
// early holds the results the client sent for calls the agent hasn't
// made yet: Claude Code makes its MCP calls one after another, so of a
// reply's two tool calls the second is made only once the first has its
// result, while the client ran both and sent both results back at once.
early map[string]mcpToolResult
}
// waitTool collects a tool result that took longer than an agent's patience.
const waitTool = "magpie_wait"
type mcpToolResult struct {
Content []map[string]any `json:"content"`
IsError bool `json:"is_error,omitempty"`
}
type bridgeTool struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
InputSchema json.RawMessage `json:"inputSchema"`
}
func newSubscriptionBridge() *subscriptionBridge {
return &subscriptionBridge{runs: map[string]*subscriptionRun{}, calls: map[string]*subscriptionRun{}, idle: map[string]*subscriptionRun{}}
}
func randomToken() string {
var b [24]byte
if _, err := rand.Read(b[:]); err != nil {
return fmt.Sprintf("%d", time.Now().UnixNano())
}
return hex.EncodeToString(b[:])
}
func claudeBinary() (string, error) {
if p, err := exec.LookPath("claude"); err == nil {
return p, nil
}
home, _ := os.UserHomeDir()
for _, p := range []string{filepath.Join(home, ".local", "bin", "claude"), "/usr/local/bin/claude", "/opt/homebrew/bin/claude"} {
if st, err := os.Stat(p); err == nil && !st.IsDir() {
return p, nil
}
}
return "", errors.New("Claude Code is not installed; install it and run `claude auth login`")
}
func callbackBaseURL() string {
a := Addr()
host, port, ok := strings.Cut(a, ":")
if !ok {
return "http://" + a
}
if host == "" || host == "0.0.0.0" || host == "::" || host == "[::]" {
host = "127.0.0.1"
}
return "http://" + host + ":" + port
}
func (b *subscriptionBridge) start(ctx context.Context, req *Request, model, oauth, owner string) (*subscriptionRun, <-chan Event, error) {
binary, err := claudeBinary()
if err != nil {
return nil, nil, err
}
exe, err := os.Executable()
if err != nil {
return nil, nil, err
}
tmp, err := os.MkdirTemp("", "magpie-claude-")
if err != nil {
return nil, nil, err
}
cleanup := func() { _ = os.RemoveAll(tmp) }
tools := bridgeTools(req)
toolsPath := filepath.Join(tmp, "tools.json")
toolBytes, _ := json.Marshal(tools)
if err := os.WriteFile(toolsPath, toolBytes, 0o600); err != nil {
cleanup()
return nil, nil, err
}
token := randomToken()
callback := callbackBaseURL() + "/_magpie/claude-mcp/" + token
mcpConfig, _ := json.Marshal(map[string]any{"mcpServers": map[string]any{
"magpie": map[string]any{"command": exe, "args": []string{"claude-mcp-helper", callback, toolsPath}},
}})
args := claudeCLIArgs(model, string(mcpConfig), req.Effort, req.WebSearch)
cmd := proc.CommandContext(context.Background(), binary, args...)
cmd.Dir = tmp
cmd.Env = netproxy.Env(cleanClaudeEnv(os.Environ()))
if oauth != "" {
// a saved account in use beside the one Claude Code is signed in to
cmd.Env = append(cmd.Env, "CLAUDE_CODE_OAUTH_TOKEN="+oauth)
}
stdin, err := cmd.StdinPipe()
if err != nil {
cleanup()
return nil, nil, err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
cleanup()
return nil, nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
cleanup()
return nil, nil, err
}
run := &subscriptionRun{bridge: b, token: token, model: model, cmd: cmd, tmp: tmp, pending: map[string]chan mcpToolResult{}, stdin: stdin, owner: owner}
// A caller may abandon a turn after receiving tool_use. Do not leave the
// parked Claude process and MCP request alive forever.
run.timer = time.AfterFunc(30*time.Minute, run.abort)
segment := run.attach()
b.mu.Lock()
b.runs[token] = run
b.mu.Unlock()
if err := run.launch(); err != nil {
b.removeRun(run)
return nil, nil, err
}
go func() {
_, _ = io.Copy(&lockedWriter{run: run}, io.LimitReader(stderr, 1<<20))
}()
go run.readOutput(stdout)
prompt, err := renderClaudePrompt(req)
if err != nil {
run.abort()
return nil, nil, err
}
line, _ := json.Marshal(map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": prompt}})
if _, err := stdin.Write(append(line, '\n')); err != nil {
run.abort()
return nil, nil, err
}
return run, segment, nil
}
// resume hands a conversation's next turn to the run that had its last
// one, when one is waiting: the user's messages since, and nothing else.
func (b *subscriptionBridge) resume(req *Request, owner string) (*subscriptionRun, <-chan Event) {
j := len(req.Messages) - 1
for j >= 0 && req.Messages[j].Role != "assistant" {
j--
}
if j < 0 || j == len(req.Messages)-1 {
return nil, nil
}
since := req.Messages[j+1:]
for _, m := range since {
for _, p := range m.Parts {
if p.Kind == ToolResult {
return nil, nil
}
}
}
key := turnKey(owner, req, req.Messages[:j+1])
b.mu.Lock()
run := b.idle[key]
if run != nil {
delete(b.idle, key)
run.idleKey = ""
}
b.mu.Unlock()
if run == nil {
return nil, nil
}
line, _ := json.Marshal(map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": renderClaudeTurn(since)}})
run.mu.Lock()
if run.closed {
run.mu.Unlock()
return nil, nil
}
ch := make(chan Event, 64)
run.segment = ch
run.mu.Unlock()
run.timer.Reset(30 * time.Minute)
if _, err := run.stdin.Write(append(line, '\n')); err != nil {
run.abort()
return nil, nil
}
return run, ch
}
// ended is told how a turn's reply went. A run whose reply was whole and
// asked for nothing more waits for the conversation's next turn; one that
// failed, was cut short or went unheard is let go.
func (r *subscriptionRun) ended(req *Request, said, stop string, ok bool) {
switch {
case !ok:
// the caller has no whole reply, so no tool calls to answer
r.abort()
return
case stop == "tool":
if r.stdin == nil && r.timer != nil {
r.timer.Reset(parkLongest)
}
return // it waits on its tool calls
case r.stdin == nil:
return // it ends by itself
case stop != "stop":
r.abort()
return
}
reply := Message{Role: "assistant", Parts: []Part{{Kind: Text, Text: said}}}
key := turnKey(r.owner, req, append(req.Messages[:len(req.Messages):len(req.Messages)], reply))
b := r.bridge
var drop []*subscriptionRun
b.mu.Lock()
if old := b.idle[key]; old != nil {
drop = append(drop, old)
}
b.idle[key] = r
r.idleKey, r.idleAt = key, time.Now()
for len(b.idle) > idleMost {
var oldest *subscriptionRun
for _, run := range b.idle {
if oldest == nil || run.idleAt.Before(oldest.idleAt) {
oldest = run
}
}
delete(b.idle, oldest.idleKey)
oldest.idleKey = ""
drop = append(drop, oldest)
}
b.mu.Unlock()
r.timer.Reset(idleLongest)
for _, run := range drop {
run.abort()
}
}
// turnKey is what a conversation has been so far, for the run that had it
// to be found again: whom it runs as, the model, its settings and tools,
// and the messages' words, tool calls and results. Whitespace, thinking and
// how a reply is split into messages are left out, as clients keep those
// differently.
func turnKey(owner string, req *Request, msgs []Message) string {
h := sha256.New()
tools, _ := json.Marshal(req.Tools)
fmt.Fprintf(h, "%s\x00%s\x00%s\x00%s\x00%s\x00%s\x00%t", owner, req.Model, req.Effort, req.ToolChoice, req.System, tools, req.WebSearch)
role := ""
for _, m := range msgs {
var b strings.Builder
for _, p := range m.Parts {
switch p.Kind {
case Text:
b.WriteString(p.Text + " ")
case ToolCall:
fmt.Fprintf(&b, "\x01call %s %s ", p.Name, p.ID)
case ToolResult:
fmt.Fprintf(&b, "\x01result %s %s ", p.CallID, p.Text)
case File:
fmt.Fprintf(&b, "\x01file %s %d %s ", p.MediaType, len(p.Data), p.URL)
case Image:
fmt.Fprintf(&b, "\x01image %d %s ", len(p.Data), p.URL)
}
}
words := strings.Join(strings.Fields(b.String()), " ")
if words == "" {
continue
}
if m.Role != role {
role = m.Role
fmt.Fprintf(h, "\x00%s:", role)
}
h.Write([]byte(words + " "))
}
return hex.EncodeToString(h.Sum(nil))
}
// claudeCLIArgs runs Claude Code with none of its own tools but, when the
// client offered a web search (Claude Code's own WebSearch tool asks for
// Anthropic's), its WebSearch, which searches as the subscription does.
func claudeCLIArgs(model, mcpConfig, effort string, web bool) []string {
own := ""
if web {
own = "WebSearch"
}
args := []string{
"-p", "--output-format", "stream-json", "--input-format", "stream-json",
"--include-partial-messages", "--verbose", "--model", model,
"--tools", own, "--strict-mcp-config", "--mcp-config", mcpConfig,
"--setting-sources", "", "--dangerously-skip-permissions",
}
if effort != "" {
if effort == "xhigh" {
effort = "max"
}
args = append(args, "--effort", effort, "--thinking-display", "summarized")
}
return args
}
func cleanClaudeEnv(env []string) []string {
blocked := map[string]bool{
"ANTHROPIC_BASE_URL": true, "ANTHROPIC_API_KEY": true, "ANTHROPIC_AUTH_TOKEN": true,
"CLAUDECODE": true, "CLAUDE_CODE_ENTRYPOINT": true, "CLAUDE_CODE_SSE_PORT": true,
"CLAUDE_CODE_OAUTH_TOKEN": true,
}
out := make([]string, 0, len(env)+3)
for _, e := range env {
k, _, _ := strings.Cut(e, "=")
if !blocked[k] {
out = append(out, e)
}
}
return append(out, "ENABLE_CLAUDEAI_MCP_SERVERS=0", "DISABLE_AUTO_COMPACT=1", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1")
}
type lockedWriter struct{ run *subscriptionRun }
func (w *lockedWriter) Write(p []byte) (int, error) {
w.run.mu.Lock()
defer w.run.mu.Unlock()
if w.run.stderr.Len() < 1<<20 {
_, _ = w.run.stderr.Write(p)
}
return len(p), nil
}
func (r *subscriptionRun) attach() chan Event {
r.mu.Lock()
defer r.mu.Unlock()
ch := make(chan Event, 64)
r.segment = ch
return ch
}
func (r *subscriptionRun) attached() bool {
r.mu.Lock()
defer r.mu.Unlock()
return r.segment != nil
}
func (r *subscriptionRun) emit(ev Event) {
r.mu.Lock()
defer r.mu.Unlock()
if r.segment != nil {
r.segment <- ev
}
}
func (r *subscriptionRun) endSegment() {
r.mu.Lock()
ch := r.segment
r.segment = nil
r.mu.Unlock()
if ch != nil {
close(ch)
}
}
func (r *subscriptionRun) readOutput(rd io.Reader) {
s := bufio.NewScanner(rd)
s.Buffer(make([]byte, 64<<10), 64<<20)
// A call to one of Claude Code's own tools (WebSearch) is run by Claude
// Code, not the client: its block is left out, and the message it ends
// goes on in the next one, so the client hears one reply.
own := map[int]bool{} // this message's blocks that are such calls
theirs := false // this message calls a client's tool
inside := false // a message goes on after Claude Code's own call
// what the messages before cost, as each message's usage counts only
// itself and the client keeps the last it is told
var before, this Usage
usage := func(u cliUsage) Usage {
v := u.gateway()
this.add(v)
return v.plus(before, true)
}
for s.Scan() {
var envelope struct {
Type string `json:"type"`
Subtype string `json:"subtype"`
IsError bool `json:"is_error"`
Result string `json:"result"`
// what Claude Code's WebSearch found, on the message that
// answers its call
ToolUseResult json.RawMessage `json:"tool_use_result"`
Event struct {
Type string `json:"type"`
Index int `json:"index"`
Message struct {
ID string `json:"id"`
Model string `json:"model"`
Usage cliUsage `json:"usage"`
} `json:"message"`
ContentBlock struct {
Type string `json:"type"`
ID string `json:"id"`
Name string `json:"name"`
Text string `json:"text"`
} `json:"content_block"`
Delta struct {
Type string `json:"type"`
Text string `json:"text"`
Thinking string `json:"thinking"`
Signature string `json:"signature"`
PartialJSON string `json:"partial_json"`
StopReason string `json:"stop_reason"`
} `json:"delta"`
Usage cliUsage `json:"usage"`
} `json:"event"`
}
if json.Unmarshal(s.Bytes(), &envelope) != nil {
continue
}
if envelope.Type == "result" {
if envelope.IsError {
r.emit(Event{Kind: KError, Text: envelope.Result})
}
continue
}
var searched struct {
Query string `json:"query"`
Results []json.RawMessage `json:"results"`
}
if envelope.Type == "user" && json.Unmarshal(envelope.ToolUseResult, &searched) == nil && searched.Query != "" && searched.Results != nil {
var hits []Hit
for _, raw := range searched.Results {
var found struct {
Content []Hit `json:"content"`
}
if json.Unmarshal(raw, &found) == nil {
hits = append(hits, found.Content...)
}
}
r.emit(Event{Kind: KSearch, Text: searched.Query, Hits: hits})
continue
}
if envelope.Type != "stream_event" {
continue
}
e := envelope.Event
switch e.Type {
case "message_start":
own, theirs = map[int]bool{}, false
if inside {
inside = false
before, this = before.plus(this, false), Usage{}
r.emit(Event{Kind: KUsage, Usage: usage(e.Message.Usage)})
continue
}
before, this = Usage{}, Usage{}
r.emit(Event{Kind: KStart, MsgID: e.Message.ID, Model: e.Message.Model, Usage: usage(e.Message.Usage)})
case "content_block_start":
switch e.ContentBlock.Type {
case "tool_use":
name, ok := strings.CutPrefix(e.ContentBlock.Name, "mcp__magpie__")
r.mu.Lock()
search := r.search != nil && name == r.searchName
r.mu.Unlock()
// magpie answers its own web search, as Claude Code does
// its WebSearch
if !ok || search {
own[e.Index] = true
continue
}
theirs = true
r.emit(Event{Kind: KToolStart, ID: e.ContentBlock.ID, Name: name})
case "text":
if e.ContentBlock.Text != "" {
r.emit(Event{Kind: KText, Text: e.ContentBlock.Text})
}
}
case "content_block_delta":
switch e.Delta.Type {
case "text_delta":
r.emit(Event{Kind: KText, Text: e.Delta.Text})
case "thinking_delta":
r.emit(Event{Kind: KThink, Text: e.Delta.Thinking})
case "signature_delta":
r.emit(Event{Kind: KSig, Text: e.Delta.Signature})
case "input_json_delta":
if !own[e.Index] {
r.emit(Event{Kind: KToolArgs, Text: e.Delta.PartialJSON})
}
}
case "message_delta":
r.emit(Event{Kind: KUsage, Usage: usage(e.Usage)})
if e.Delta.StopReason == "tool_use" && len(own) > 0 && !theirs {
inside = true
} else if e.Delta.StopReason != "" {
r.emit(Event{Kind: KStop, Stop: stopFromAnthropic(e.Delta.StopReason)})
}
case "message_stop":
if !inside {
r.endSegment()
}
}
}
if err := s.Err(); err != nil {
r.emit(Event{Kind: KError, Text: err.Error()})
}
}
type cliUsage struct {
Input int `json:"input_tokens"`
Output int `json:"output_tokens"`
CacheRead int `json:"cache_read_input_tokens"`
CacheWrite int `json:"cache_creation_input_tokens"`
OutputDetails struct {
Thinking int `json:"thinking_tokens"`
} `json:"output_tokens_details"`
}
// plus adds v's counts to u's; only to those u has, when it only updates
// what the client was told.
func (u Usage) plus(v Usage, only bool) Usage {
for _, f := range []struct{ a, b *int }{{&u.Input, &v.Input}, {&u.Output, &v.Output}, {&u.CacheRead, &v.CacheRead}, {&u.CacheWrite, &v.CacheWrite}, {&u.Reasoning, &v.Reasoning}} {
if *f.a > 0 || !only {
*f.a += *f.b
}
}
return u
}
func (u cliUsage) gateway() Usage {
return Usage{Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite, Reasoning: u.OutputDetails.Thinking}
}
func renderClaudePrompt(req *Request) ([]map[string]any, error) {
var blocks []map[string]any
var text strings.Builder
if req.System != "" || req.ToolChoice == "required" || strings.HasPrefix(req.ToolChoice, "name:") {
text.WriteString("<external_system_instructions>\n")
text.WriteString(req.System)
switch {
case req.ToolChoice == "required":
text.WriteString("\nYou must call at least one available tool before answering.")
case strings.HasPrefix(req.ToolChoice, "name:"):
fmt.Fprintf(&text, "\nYou must call the %s tool.", strings.TrimPrefix(req.ToolChoice, "name:"))
}
text.WriteString("\n</external_system_instructions>\n\n")
}
for _, m := range req.Messages {
label := "Human"
if m.Role == "assistant" {
label = "Assistant"
}
text.WriteString(label + ": ")
blocks = renderParts(blocks, &text, m.Parts)
text.WriteString("\n\n")
}
return closeBlocks(blocks, &text), nil
}
// renderClaudeTurn is the user's messages in a conversation Claude Code
// already has, as it would be told them itself.
func renderClaudeTurn(msgs []Message) []map[string]any {
var blocks []map[string]any
var text strings.Builder
for i, m := range msgs {
if i > 0 {
text.WriteString("\n\n")
}
blocks = renderParts(blocks, &text, m.Parts)
}
return closeBlocks(blocks, &text)
}
func renderParts(blocks []map[string]any, text *strings.Builder, parts []Part) []map[string]any {
for _, p := range parts {
switch p.Kind {
case Text:
text.WriteString(p.Text)
case File:
text.WriteString(attachmentText(p))
case Thinking:
text.WriteString(p.Text)
case ToolCall:
fmt.Fprintf(text, "\n[tool call %s id=%s args=%s]", p.Name, p.ID, argsString(p))
case ToolResult:
fmt.Fprintf(text, "\n[tool result id=%s%s]\n%s", p.CallID, map[bool]string{true: " error"}[p.IsError], p.Text)
case Image:
if text.Len() > 0 {
blocks = append(blocks, map[string]any{"type": "text", "text": text.String()})
text.Reset()
}
switch {
case p.Data != "":
blocks = append(blocks, map[string]any{"type": "image", "source": map[string]any{"type": "base64", "media_type": p.MediaType, "data": p.Data}})
case p.URL != "":
blocks = append(blocks, map[string]any{"type": "image", "source": map[string]any{"type": "url", "url": p.URL}})
}
}
}
return blocks
}
func closeBlocks(blocks []map[string]any, text *strings.Builder) []map[string]any {
if text.Len() > 0 {
blocks = append(blocks, map[string]any{"type": "text", "text": text.String()})
}
if len(blocks) == 0 {
blocks = append(blocks, map[string]any{"type": "text", "text": "[continue]"})
}
return blocks
}
// findRun is the run the request's new tool results are for, and those
// results: the ones sent since the last assistant message. They are the
// run's when one of them is a call it made; the rest it hasn't made yet.
func (b *subscriptionBridge) findRun(req *Request) (*subscriptionRun, []Part) {
var fresh []Part
for i := len(req.Messages) - 1; i >= 0 && req.Messages[i].Role != "assistant"; i-- {
var parts []Part
for _, p := range req.Messages[i].Parts {
if p.Kind == ToolResult {
parts = append(parts, p)
}
}
fresh = append(parts, fresh...)
}
if len(fresh) == 0 {
return nil, nil
}
// Claude emits message_stop just before its MCP calls are all scheduled.
// A very fast client can return a result while the callback is still being
// registered; give that tiny race a bounded grace period.
for attempt := 0; attempt < 20; attempt++ {
var found *subscriptionRun
b.mu.Lock()
for _, p := range fresh {
run := b.calls[p.CallID]
if run == nil {
continue
}
if found != nil && found != run {
found = nil
break
}
found = run
}
b.mu.Unlock()
if found != nil {
return found, fresh
}
time.Sleep(25 * time.Millisecond)
}
return nil, nil
}
// offers says the run's agent was told every one of tools.
func (r *subscriptionRun) offers(tools []Tool) bool {
if r.tools == nil {
return true
}
for _, t := range tools {
if !r.tools[t.Name] {
return false
}
}
return true
}
// continueWith hands the agent its tool results: at once for the calls it
// is waiting on, the others kept until it makes them.
func (r *subscriptionRun) continueWith(results []Part) (<-chan Event, error) {
if r.timer != nil {
r.timer.Reset(30 * time.Minute)
}
ch := r.attach()
if r.begin != nil {
r.emit(r.begin())
}
delivered := 0
for _, p := range results {
result := mcpToolResult{Content: []map[string]any{{"type": "text", "text": p.Text}}, IsError: p.IsError}
r.mu.Lock()
waiter := r.pending[p.CallID]
delete(r.pending, p.CallID)
if waiter == nil && !r.closed {
if r.early == nil {
r.early = map[string]mcpToolResult{}
}
r.early[p.CallID] = result
}
r.mu.Unlock()
if waiter == nil {
continue
}
delivered++
r.bridge.mu.Lock()
delete(r.bridge.calls, p.CallID)
r.bridge.mu.Unlock()
waiter <- result
close(waiter)
}
if delivered == 0 {
r.abort()
return nil, fmt.Errorf("the agent is not waiting for tool results %s", callIDs(results))
}
if r.resume != nil {
r.resume()
}
return ch, nil
}
func callIDs(parts []Part) string {
ids := make([]string, len(parts))
for i, p := range parts {
ids[i] = p.CallID
}
return strings.Join(ids, ", ")
}
func (b *subscriptionBridge) mcpCall(w http.ResponseWriter, r *http.Request) {
token := r.PathValue("token")
b.mu.Lock()
run := b.runs[token]
b.mu.Unlock()
if run == nil {
http.Error(w, "unknown or expired Claude run", http.StatusNotFound)
return
}
var call struct {
ToolCallID string `json:"tool_call_id"`
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
}
if json.NewDecoder(io.LimitReader(r.Body, 16<<20)).Decode(&call) != nil || call.ToolCallID == "" {
http.Error(w, "invalid tool call", http.StatusBadRequest)
return
}
if call.Name == waitTool && run.patience > 0 {
run.await(w, r, call.Arguments)
return
}
run.mu.Lock()
search, searchName := run.search, run.searchName
run.mu.Unlock()
if search != nil && call.Name == searchName {
var a struct {
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)
defer cancel()
found, hits, err := search(ctx, a.Query)
if err != nil {
writeJSON(w, 200, mcpToolResult{Content: []map[string]any{{"type": "text", "text": "search failed: " + err.Error()}}, IsError: true})
return
}
run.emit(Event{Kind: KSearch, Text: a.Query, Hits: hits})
writeJSON(w, 200, mcpToolResult{Content: []map[string]any{{"type": "text", "text": found}}})
return
}
waiter := make(chan mcpToolResult, 1)
run.mu.Lock()
if result, ok := run.early[call.ToolCallID]; ok {
delete(run.early, call.ToolCallID)
run.mu.Unlock()
writeJSON(w, 200, result)
return
}
run.pending[call.ToolCallID] = waiter
run.mu.Unlock()
b.mu.Lock()
b.calls[call.ToolCallID] = run
b.mu.Unlock()
if run.onCall != nil {
run.onCall(call.ToolCallID, call.Name, call.Arguments)
}
var expire <-chan time.Time
if run.patience > 0 {
t := time.NewTimer(run.patience)
defer t.Stop()
expire = t.C
}
select {
case result, ok := <-waiter:
if !ok {
http.Error(w, "the agent's run ended", http.StatusGone)
return
}
writeJSON(w, 200, result)
case <-expire:
run.mu.Lock()
run.late[call.ToolCallID] = waiter
run.mu.Unlock()
writeJSON(w, 200, stillRunning(call.ToolCallID, call.Name))
case <-r.Context().Done():
return
}
}
// await answers waitTool: the late result once it is in, or that the call
// is still running.
func (r *subscriptionRun) await(w http.ResponseWriter, req *http.Request, args json.RawMessage) {
var a struct {
Call string `json:"call"`
}
_ = json.Unmarshal(args, &a)
r.mu.Lock()
ch := r.late[a.Call]
r.mu.Unlock()
if ch == nil {
writeJSON(w, 200, mcpToolResult{IsError: true, Content: []map[string]any{{"type": "text", "text": fmt.Sprintf("No tool call %q is running.", a.Call)}}})
return
}
t := time.NewTimer(r.patience)
defer t.Stop()
select {
case result, ok := <-ch:
r.mu.Lock()
delete(r.late, a.Call)
r.mu.Unlock()
if !ok {
http.Error(w, "the agent's run ended", http.StatusGone)
return
}
writeJSON(w, 200, result)
case <-t.C:
writeJSON(w, 200, stillRunning(a.Call, ""))
case <-req.Context().Done():
}
}
func stillRunning(id, name string) mcpToolResult {
what := "The tool call"
if name != "" {
what = "The " + name + " call"
}
return mcpToolResult{Content: []map[string]any{{"type": "text", "text": fmt.Sprintf(
"%s is still running in the user's environment. Call %s with {\"call\": %q} to wait for its result. Do not make the call again.", what, waitTool, id)}}}
}
func (r *subscriptionRun) finish() {
r.mu.Lock()
if r.closed {
r.mu.Unlock()
return
}
r.closed = true
if r.timer != nil {
r.timer.Stop()
}
pending := r.pending
r.pending = map[string]chan mcpToolResult{}
ch := r.segment
r.segment = nil
r.mu.Unlock()
for _, waiter := range pending {
close(waiter)
}
if ch != nil {
close(ch)
}
if r.bridge != nil { // a run made in a test may have none
r.bridge.removeRun(r)
}
}
// launch starts the run's agent, to end with all it starts.
func (r *subscriptionRun) launch() error {
t, err := proc.StartTree(r.cmd)
if err != nil {
return err
}
r.mu.Lock()
r.tree = t
r.mu.Unlock()
go func() {
_ = t.Wait()
r.finish()
}()
return nil
}
func (r *subscriptionRun) abort() {
r.mu.Lock()
t := r.tree
r.mu.Unlock()
if t != nil {
t.Kill()
}
r.finish()
}
// abortAll ends every run, as the gateway stops: they are no terminal's
// to be interrupted with it.
func (b *subscriptionBridge) abortAll() {
b.mu.Lock()
runs := make([]*subscriptionRun, 0, len(b.runs))
for _, run := range b.runs {
runs = append(runs, run)
}
b.mu.Unlock()
for _, run := range runs {
run.abort()
}
}
func (b *subscriptionBridge) removeRun(run *subscriptionRun) {
b.mu.Lock()
delete(b.runs, run.token)
if run.idleKey != "" && b.idle[run.idleKey] == run {
delete(b.idle, run.idleKey)
}
for id, owner := range b.calls {
if owner == run {
delete(b.calls, id)
}
}
b.mu.Unlock()
_ = os.RemoveAll(run.tmp)
}
func (s *Server) serveClaudeSubscription(w http.ResponseWriter, r *http.Request, from provider.Protocol, p provider.Provider, model string, body []byte, usage *Usage) (int, string) {
start := func(ctx context.Context, req *Request) (*subscriptionRun, <-chan Event, error) {
owner := p.ID + "\x00" + p.Account.User
if run, events := s.subscription.resume(req, owner); run != nil {
return run, events, nil
}
token, _, err := p.Account.Token(ctx)
if err != nil {
return nil, nil, err
}
return s.subscription.start(ctx, req, model, token, owner)
}
return s.serveSubscription(w, r, from, "Claude Code", model, body, usage, start)
}
// serveSubscription answers a request through an agent's own binary: a new
// turn starts it, a request carrying tool results resumes the turn waiting
// on them.
func (s *Server) serveSubscription(w http.ResponseWriter, r *http.Request, from provider.Protocol, name, model string, body []byte, usage *Usage,
start func(ctx context.Context, req *Request) (*subscriptionRun, <-chan Event, error)) (int, string) {
req, err := parse(from, body)
if err != nil {
return writeError(w, from, 400, err.Error()), err.Error()
}
req.Model = model
// its model searches the web with magpie's tool, which magpie answers
var search Tool
if req.WebSearch && !searching(r.Context()) {
if _, _, ok := searcher(); ok {
search = searchTool(req.Tools)
req.Tools = append(slices.Clone(req.Tools), search)
}
}
run, results := s.subscription.findRun(req)
if run != nil && !run.offers(req.Tools) {
// the client offers a tool the run's agent was never told of, as
// Claude Code's ToolSearch loads a deferred one (WebSearch) mid-turn:
// a run started now has it, the conversation told over
run.abort()
run = nil
}
var events <-chan Event
if run != nil {
if events, err = run.continueWith(results); err != nil {
// it ended while it waited: a new one is told the whole
// conversation
run = nil
}
}
if run == nil {
run, events, err = start(r.Context(), req)
if err == nil {
run.tools = map[string]bool{}
for _, t := range req.Tools {
run.tools[t.Name] = true
}
if search.Name != "" {
run.mu.Lock()
run.search, run.searchName = s.webSearch, search.Name
run.mu.Unlock()
}
}
}
if err != nil {
return writeError(w, from, 502, name+": "+err.Error()), err.Error()
}
// a caller gone before the reply is whole won't carry it on: its agent
// is stopped at once, not left to answer no one and wait on tool calls
// it never handed over
gone := context.AfterFunc(r.Context(), run.abort)
defer gone()
return relay(w, r, from, name, req, events, usage, run.abort, func(said, stop string, ok bool) {
gone()
run.ended(req, said, stop, ok)
})
}
// 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.
func relay(w http.ResponseWriter, r *http.Request, from provider.Protocol, name string, req *Request, events <-chan Event, usage *Usage,
abort func(), ended func(said, stop string, ok bool)) (int, string) {
stream := req.Stream
if stream {
// an error before any of the answer — out of quota, rate limited —
// is a status, not a stream, so another account can take over
var head []Event
for ev := range events {
head = append(head, ev)
if ev.Kind != KStart && ev.Kind != KUsage {
break
}
}
if n := len(head); n == 0 || head[n-1].Kind == KError {
msg := name + " ended without an answer"
if n > 0 {
msg = head[n-1].Text
}
abort()
code := 502
if quotaWords.MatchString(msg) {
code = 429
}
return writeError(w, from, code, name+": "+msg), msg
}
enc := encoder(from, newSSEWriter(w), req.Model)
var failed, said, stop string
see := func(ev Event) {
switch ev.Kind {
case KError:
failed = ev.Text
case KStart, KUsage:
usage.add(ev.Usage)
case KText:
said += ev.Text
case KStop:
stop = ev.Stop
}
enc.event(ev)
}
for _, ev := range head {
see(ev)
}
for ev := range events {
see(ev)
}
// before the reply's last event, which the agent may answer at once
ended(said, stop, failed == "" && r.Context().Err() == nil)
// an error event already ended the reply in the client's protocol
if failed == "" {
enc.finish()
}
return 200, failed
}
var col collector
var said, stop string
for ev := range events {
switch ev.Kind {
case KText:
said += ev.Text
case KStop:
stop = ev.Stop
}
col.add(ev)
}
if col.err != "" && len(col.res.Parts) == 0 {
abort()
return writeError(w, from, 502, name+": "+col.err), col.err
}
ended(said, stop, col.err == "" && r.Context().Err() == nil)
res := col.finish()
usage.add(res.Usage)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, _ = w.Write(render(from, res, req.Model))
return 200, col.err
}