Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
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.
//
// A turn the client gives up on mid-reply (a 499: the user stopped it) is
// taken back in the same Claude Code, not ended with it (#780): Claude
// Code is told to rewind its conversation to before that turn's message,
// stopping the reply, and the run waits again as it did before the turn.
// The client's resend — the same conversation, its last message reworded
// — goes on from there, and the prefix it sends Anthropic is the one
// already cached. Ended, the run's conversation was told to a new one in
// one message, written to the cache again whole.
import (
"bufio"
"bytes"
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"hash"
"io"
"io/fs"
"log"
"maps"
"net/http"
"os"
"os/exec"
"path/filepath"
"reflect"
"regexp"
"runtime"
"slices"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unicode/utf8"
"github.com/yetone/magpie/internal/appdir"
"github.com/yetone/magpie/internal/claudecode"
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/proc"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/wslrun"
)
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
shelf map[string]*savedSession // conversation so far (turnKey) → its saved session
baseURL string
sweep sync.Once
swept sync.Map // Claude Code's project folders sweepSessions went through
// lost is why each run that had a conversation ended, by that
// conversation (convKey), and lostCalls by the tool calls it waited
// on or was last handed results for, for the log of a request that
// finds no run
lost map[string]lostRun
lostCalls map[string]lostRun
}
// 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.
//
// It waits as long as the prompt cache it wrote lasts: on a subscription
// within its limits Claude Code writes Anthropic's cache for an hour
// (claudeCacheTTL; cleanClaudeEnv pins its CLAUDE_CODE_PROMPT_CACHE_TTL to
// 1h), and a run let go sooner has its conversation told to a new one in one message, a
// prefix the cache has never seen, so the whole of it is written again
// while what the old run wrote is still there to read (#463: a turn
// after 39 minutes idle wrote the conversation again). Past the hour the cache is gone
// either way, and the run would only hold a process.
const (
claudeCacheTTL = time.Hour
idleLongest = claudeCacheTTL
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
// A run whose reply called nothing but a tool that ends its caller's turn
// (finalTools: an Agent SDK or workflow subagent's StructuredOutput, answered
// by the client itself) hears no result for it when the call was good, the
// subagent done: it waits finalGrace, for the error result a call that
// broke its schema gets at once, and is let go (#345).
var (
finalGrace = 30 * time.Second
finalTools = map[string]bool{"StructuredOutput": true}
)
// Of the runs waiting on their caller's tool calls, parkedMost are kept
// once they have waited parkLongest, the longest waiting let go first: a
// caller stopped with its calls unanswered (a subagent its workflow ended)
// sends none, and each is a Claude Code process. One let go that does get
// its results is started anew with the whole conversation.
const parkedMost = 16
type subscriptionRun struct {
bridge *subscriptionBridge
token string
model string
cmd *exec.Cmd
tree *proc.Tree // cmd once started, with all it starts
// the read ends of Claude Code's output, and their readers
outputs []*os.File
reading sync.WaitGroup
// exited is closed once Claude Code has exited and its output is read,
// exit then how it ended (Wait's error); killed says magpie ended it
// (abort) while it ran
exited chan struct{}
exit error
killed bool
tmp string
// room frees the process's place in claudeRoom once it has exited,
// roomLeft telling it magpie ended it (abort)
room func(left bool)
roomLeft bool
// schema says the client asked for an answer fitting a JSON schema,
// which Claude Code gives as its StructuredOutput call
schema bool
// the tools its agent was told of, as it started and since
tools 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
mu sync.Mutex
// sending is held across a send to the segment and taken before it is
// closed, so a send blocked on a full segment no one reads yet holds
// this, not mu: the request's heard, stderr and abort go on meanwhile
sending sync.Mutex
segment chan Event
pending map[string]chan mcpToolResult
closed bool
resuming bool // a tool-result request owns this run until its segment ends
stderr strings.Builder
// Only one settings update is in flight; it must be acknowledged before
// a tool result or a new user turn can trigger the next model request.
settingsMu sync.Mutex
safeguards json.RawMessage
safeguardBeta string
clientMarks bool
lean bool // started with leanSystem as its system prompt
cacheTail string
cachePrefix cachePrefix
timer *time.Timer
// Claude Code's input, kept open for the next turn; owner is the account
// it runs as (owned, named once in its life when it started unnamed:
// takeNamedOwner), and idleKey and idleAt say it is waiting for one.
// convKey is the conversation it has had, whatever the model
// (conversationKeys).
stdin io.WriteCloser
owner atomic.Pointer[string]
idleKey string
idleAt time.Time
convKey string
// loose is the conversation it waits at as a client may send it back
// rewritten (looseTurn)
loose *looseTurn
// turnUUID is the id the turn it was resumed for gave its user message,
// and backKey the conversation it was waiting at before (turnKey):
// a turn the client gives up on is rewound to that message, and the
// run waits at backKey again (letGo). rewinding is open while it is
// told to; controls are its control requests waiting on an answer.
turnUUID string
backKey string
rewinding chan struct{}
controls map[string]chan controlReply
// behindKey and behindTurn are backKey and turnUUID of the turn it
// last answered whole, while it waits for the next (b.mu): a request
// that goes on from before that turn takes it back to there (resume).
// Claude Code asks a turn's side questions — its prompt suggestion,
// what to remember — as the conversation so far and a message more,
// so the run went on with them, and the conversation's own next turn
// found none (#1638).
behindKey string
behindTurn string
// endWhy is why magpie ended it, as the log of a turn that finds it
// gone says (abortFor); results are the calls whose results it was
// last handed (continueWith)
endWhy string
results []string
// sessionID is its Claude Code's session, saved in sessions (Claude
// Code's project folder for claudeWorkDir) when it is kept on disk
// (claudeSessions), "" otherwise; shelved says it is on the bridge's
// shelf, to be resumed, so its file outlives it, and rewound that its
// conversation was taken back (letGo), which the file may not say
sessionID string
sessions []string
shelved bool
rewound bool
// effort is the level its Claude Code thinks at, as it started (its
// --effort) or was told since (setEffort); "" is Claude Code's own
effort string
// loginVersion is the credential the run's account had when it
// started (provider.ClaudeLoginVersion), which a refusal it reports is
// kept for
loginVersion string
// told is the conversation as the client had it in its last request
// here (historyKey): tool results are the run's while the client's
// conversation goes on from that one. toldRuns is it as lostMedia
// compares it, for a client that took its images out since (#1382).
told string
toldRuns []heardRun
// 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
// queued is the user's words sent with tool results, written to Claude
// Code's input as a message of their own while it waits on the calls,
// by the message's uuid: closed once Claude Code says it queued it
// (its command_lifecycle), so it is in hand before the results are
// (continueWith, #1878)
queued map[string]chan struct{}
// asked is the client's tools its reply called, and parkedAt when it
// began waiting on them
asked []string
parkedAt time.Time
// started is when it was started, and active when its turn under way
// began (r.mu), for `magpie claude-code runs` (claudeRunList)
started time.Time
active time.Time
// ends is when its timer lets it go (endIn), under r.mu
ends time.Time
// shown is the client's tool calls its last reply made, in the order
// the client was told them: a client that names them by ids of its own
// (AmpCode) has its results paired with them by position (remap)
shown []shownCall
}
// shownCall is one of a reply's calls of the client's tools, as the client
// was told it: Claude Code's id for it, the tool and its arguments.
type shownCall struct {
id, name, args string
}
// 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"`
// Tools, when set, is the run's tools from now on: the MCP helper tells
// Claude Code its list changed, and answers the call once Claude Code
// has listed them again
Tools []bridgeTool `json:"tools,omitempty"`
}
type bridgeTool struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
InputSchema json.RawMessage `json:"inputSchema"`
}
func claudeConfigDir() string { return appdir.ClaudeDir() }
// claudeProjectName is the folder Claude Code keeps a working directory's
// sessions under: the path with everything but letters and digits made "-".
func claudeProjectName(path string) string {
return strings.Map(func(r rune) rune {
if r < 128 && (r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9') {
return r
}
return '-'
}, path)
}
// sweepBridgeProjects removes the projects that runs from before
// --no-session-persistence left in Claude Code's folder: only those named
// after a magpie-claude- folder in the temp directory, which no one but the
// bridge works in.
func sweepBridgeProjects(claudeDir, tempDir string) {
var prefixes []string
for _, d := range []string{tempDir, evalSymlinks(tempDir)} {
prefix := claudeProjectName(filepath.Join(d, "magpie-claude-"))
if !slices.Contains(prefixes, prefix) {
prefixes = append(prefixes, prefix)
}
}
root := filepath.Join(claudeDir, "projects")
entries, _ := os.ReadDir(root)
for _, e := range entries {
for _, prefix := range prefixes {
rest, ok := strings.CutPrefix(e.Name(), prefix)
if ok && e.IsDir() && rest != "" && strings.Trim(rest, "0123456789") == "" {
_ = os.RemoveAll(filepath.Join(root, e.Name()))
break
}
}
}
}
// sweepBridgeTemps removes the folders runs a gateway no longer running
// left in the temp directory: a run's own magpie-claude-<n> (its tools.json,
// its work folder when it has no shared one) is removed when it ends, but a
// gateway quit for an update, or killed, ends none of its runs (#958).
// Another gateway on the same account (a dev build) makes them in the same
// folder, so only those untouched for as long as a session's passing files
// are left (tempLongest) go: a run's helper reads its tools.json as it
// starts, and a run working in its folder touches it.
func sweepBridgeTemps(tempDir string) {
entries, _ := os.ReadDir(tempDir)
for _, e := range entries {
rest, ok := strings.CutPrefix(e.Name(), "magpie-claude-")
if !ok || !e.IsDir() || rest == "" || strings.Trim(rest, "0123456789") != "" {
continue
}
if path := filepath.Join(tempDir, e.Name()); untouchedFor(path, tempLongest) {
_ = os.RemoveAll(path)
}
}
}
// claudeWorkDir is the folder every run works in. Claude Code tells its
// model the working directory in its system prompt, after its own fixed
// part and before the conversation: a folder of its own for each run made
// every prompt new to Anthropic's cache from there on, a caller's system
// prompt and its history written again each time, with only Claude Code's
// own part (some 2.8k tokens) read.
//
// It is in the temp folder, which is in no git repository: Claude Code puts
// the status and recent commits of the repository its folder is in into
// the prompt, so a folder under a home kept in git (dotfiles) would send
// them with every request, and break the cache whenever they change. The
// folder is the user's own (claudeWorkName: their uid in its name where
// the temp folder is shared, as /tmp is on Linux), and used only when it
// is a folder they own that no one else can write to: one someone else
// made, or could put a CLAUDE.md in, would be read by every run.
func claudeWorkDir() (string, error) {
dir := filepath.Join(os.TempDir(), claudeWorkName())
if err := os.MkdirAll(dir, 0o700); err != nil {
return "", err
}
fi, err := os.Lstat(dir)
switch {
case err != nil:
return "", err
case !fi.IsDir():
return "", fmt.Errorf("%s is not a folder", dir)
case othersCanWrite(fi):
return "", fmt.Errorf("%s can be written by others (%v)", dir, fi.Mode().Perm())
case !ownedByMe(fi):
return "", fmt.Errorf("%s belongs to another user", dir)
}
return dir, nil
}
// clientWorkDir is the working directory the caller's instructions name,
// the last one they name, as Claude Code ("Primary working directory:"),
// Codex (<cwd>), OpenCode ("Working directory:") and pi ("Current working
// directory:") write it; "" when they name none, or one that isn't an
// absolute path to a folder on this computer (a caller elsewhere). The
// model's own words are not read: what it says is no caller's.
func clientWorkDir(req *Request) string {
dir := clientNamedWorkDir(req)
if dir == "" || !filepath.IsAbs(dir) {
return ""
}
dir = filepath.Clean(dir)
if fi, err := os.Stat(dir); err != nil || !fi.IsDir() {
return ""
}
return dir
}
// clientNamedWorkDir is the working directory the caller's instructions
// name, as they write it, wherever it is; "" when they name none.
func clientNamedWorkDir(req *Request) string {
texts := []string{req.System}
for _, m := range req.Messages {
if m.Role == "assistant" {
continue
}
for _, p := range m.Parts {
if p.Kind == Text {
texts = append(texts, p.Text)
}
}
}
dir := ""
for _, t := range texts {
for _, m := range clientCwdPattern.FindAllStringSubmatch(t, -1) {
for _, g := range m[1:] {
if g = strings.Trim(strings.TrimSpace(g), "`'\""); g != "" {
dir = g
}
}
}
}
return dir
}
var clientCwdPattern = regexp.MustCompile(`(?m)(?:Primary working directory|^\s*(?:-\s*)?Working directory|Current working directory): *([^\r\n]+)$|<cwd>([^<\r\n]+)</cwd>`)
func evalSymlinks(path string) string {
if p, err := filepath.EvalSymlinks(path); err == nil {
return p
}
return path
}
func newSubscriptionBridge() *subscriptionBridge {
b := &subscriptionBridge{runs: map[string]*subscriptionRun{}, calls: map[string]*subscriptionRun{}, idle: map[string]*subscriptionRun{}, shelf: map[string]*savedSession{}}
bridges.Store(b, true)
return b
}
// bridges are the subscription bridges made, told when a saved Claude
// account is handed over to Claude Code itself (handedOver).
var bridges sync.Map
func init() {
provider.ClaudeHandedOver = func(user string) {
bridges.Range(func(b, _ any) bool {
b.(*subscriptionBridge).handedOver(user)
return true
})
}
}
// handedOver lets go of the runs waiting for their next turn in the
// directory of the saved Claude account user, now Claude Code's own sign-in
// (provider.ClaudeHandedOver): each holds its refresh token, which a
// refresh there would rotate under Claude Code's copy. Their conversations
// go on in a new run, on the account the gateway picks then.
func (b *subscriptionBridge) handedOver(user string) {
var drop []*subscriptionRun
b.mu.Lock()
for key, run := range b.idle {
if u, own := ownerAccount(run.owned()); !own && strings.EqualFold(u, user) {
delete(b.idle, key)
run.idleKey = ""
drop = append(drop, run)
}
}
b.mu.Unlock()
for _, run := range drop {
run.abort()
}
}
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[:])
}
// claudeCLI is the Claude Code magpie runs: this machine's, or, on Windows
// without one, the one installed in a running WSL distro, run there with
// its own login and quota (wslrun).
type claudeCLI struct {
path string
wsl *wslrun.Tool
}
// claudeBinary is this machine's Claude Code, or the one magpie downloaded
// for it (claudecode.Find), else one in WSL.
func claudeBinary() (claudeCLI, error) {
if p := claudecode.Find(); p != "" {
return claudeCLI{path: p}, nil
}
if t, ok := wslrun.Find("claude"); ok {
return claudeCLI{wsl: &t}, nil
}
return claudeCLI{}, errors.New("Claude Code is not installed; install it and run `claude auth login`, " + claudecode.InstallHint)
}
func (c claudeCLI) command(ctx context.Context, args ...string) *exec.Cmd {
if c.wsl != nil {
return c.wsl.Command(ctx, args...)
}
return proc.CommandContext(ctx, c.path, args...)
}
// claudeEuid is the user magpie runs as; a var for tests.
var claudeEuid = os.Geteuid
// root is whether this Claude Code runs as root: magpie itself as root
// (a server's or a container's), or a WSL distro's default user root.
func (c claudeCLI) root() bool {
if c.wsl != nil {
return c.wsl.Root
}
return runtime.GOOS != "windows" && claudeEuid() == 0
}
// asRoot is env for a bridge run (claudeCLIArgs) by a Claude Code run as
// root, which refuses --dangerously-skip-permissions there ("cannot be
// used with root/sudo privileges") unless IS_SANDBOX is "1" or
// CLAUDE_CODE_BUBBLEWRAP is set: its setup checks exactly that (2.1.296).
// The run has no tool of Claude Code's own that touches the machine, only
// magpie's MCP ones, answered by the client, and Anthropic's web search,
// so skipping the permission prompts as root does nothing more than as
// anyone else. Run as anyone else, env is kept as it is.
func (c claudeCLI) asRoot(env []string) []string {
if !c.root() {
return env
}
out := make([]string, 0, len(env)+1)
for _, e := range env {
switch k, v, _ := strings.Cut(e, "="); {
case k == "CLAUDE_CODE_BUBBLEWRAP" && v != "":
return env
case k == "IS_SANDBOX":
if v == "1" {
return env
}
continue
}
out = append(out, e)
}
return append(out, "IS_SANDBOX=1")
}
// claudeEnvVars are the variables magpie sets for a Claude Code run, which
// one in WSL is handed (wslrun's Env).
var claudeEnvVars = []string{"ENABLE_CLAUDEAI_MCP_SERVERS", "DISABLE_AUTO_COMPACT", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC",
"DISABLE_TELEMETRY", "DISABLE_ERROR_REPORTING", "DISABLE_AUTOUPDATER", "ANTHROPIC_BETAS"}
// env is env for a run in config directory configDir ("" for the account
// Claude Code is signed in to): for one in WSL, what of it goes in.
func (c claudeCLI) env(env []string, configDir string) []string {
env = inClaudeDir(env, configDir)
if c.wsl == nil {
return env
}
names := claudeEnvVars
if configDir != "" {
names = append(slices.Clone(names), "CLAUDE_CONFIG_DIR/p")
}
if c.wsl.Root {
// asRoot's, for a distro whose user is root
names = append(slices.Clone(names), "IS_SANDBOX")
}
return c.wsl.Env(env, names...)
}
// proxied is env told the proxy a run for ctx goes through (claudeProxy),
// a SOCKS one bridged: Claude Code is built with Bun, which takes only
// http:// and https:// proxies (#2651). One in a WSL distro reaches the
// bridge only when the distro shares Windows' loopback.
func (c claudeCLI) proxied(ctx context.Context, env []string) ([]string, error) {
return netproxy.EnvForBunWith(claudeProxy(ctx), env, c.wsl == nil || c.wsl.Host == "")
}
// file is where this Claude Code reads a file of magpie's at path: one in
// WSL under the distro's mount of the drive.
func (c claudeCLI) file(path string) string {
if c.wsl != nil {
return c.wsl.Linux(path)
}
return path
}
// exe is magpie's own executable, as this Claude Code starts it.
func (c claudeCLI) exe() (string, error) {
if c.wsl != nil {
return c.wsl.Exe()
}
return os.Executable()
}
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
}
// claudeMCPPath is where the Claude subscription bridge's MCP helper hands
// a tool call back: the path, then the run's callback token.
const claudeMCPPath = "/_magpie/claude-mcp/"
// from, when set, is the conversation's session a run let go past idleMost
// saved (unshelve): Claude Code goes on with it, told only the messages
// since. One that can't go on from it is let go with the session, and a
// new Claude Code is told the whole conversation: Claude Code that can't
// load a session ("No conversation found with session ID") exits before it
// reads its input, and the turn was answered 502 "Claude Code ended"
// (FrierenF on Discord).
func (b *subscriptionBridge) start(ctx context.Context, req *Request, model, configDir, owner string, from *savedSession) (*subscriptionRun, <-chan Event, error) {
run, events, err := b.startRun(ctx, req, model, configDir, owner, from)
var full *claudeFull
var refused *cliSchemaRefused
if err != nil && from != nil && !errors.As(err, &full) && !errors.As(err, &refused) && ctx.Err() == nil {
log.Printf("claude: Claude Code could not go on from the conversation's saved session (%v); a new one is told the whole conversation", err)
return b.startRun(ctx, req, model, configDir, owner, nil)
}
return run, events, err
}
// startRun is start's Claude Code, from the saved session from when set.
func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, configDir, owner string, from *savedSession) (*subscriptionRun, <-chan Event, error) {
binary, err := claudeBinary()
if err != nil {
return nil, nil, err
}
exe, err := binary.exe()
if err != nil {
return nil, nil, err
}
// a place among the Claude Code processes this machine holds (#2956),
// freed as the process exits, or here if it never starts
room, err := claudeRoom.take(ctx, "a Claude Code run on "+model)
if err != nil {
return nil, nil, err
}
launched := false
defer func() {
if !launched {
room(false)
}
}()
b.sweep.Do(func() {
go func() {
sweepBridgeProjects(claudeConfigDir(), os.TempDir())
sweepBridgeTemps(os.TempDir())
}()
})
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
}
// the token lets the helper's calls in without a gateway key
// (ownCallback), so it is handed over in a file of the run's own, which
// only this user reads, never on Claude Code's command line, which every
// user of the computer can list
token := randomToken()
callbackPath := filepath.Join(tmp, "callback")
if err := os.WriteFile(callbackPath, []byte(callbackBaseURL()+claudeMCPPath+token), 0o600); err != nil {
cleanup()
return nil, nil, err
}
mcpConfig, _ := json.Marshal(map[string]any{"mcpServers": map[string]any{
"magpie": map[string]any{"command": exe, "args": []string{"claude-mcp-helper", callbackPath, toolsPath}},
}})
args := claudeCLIArgs(model, string(mcpConfig), req.Effort, req.WebSearch)
if req.ThinkOff {
// the client turned thinking off, as Claude Code's auto mode
// classifier and its small asks do: a run at Claude Code's own
// default thought before its 64-token verdict, thousands of output
// tokens a check on the subscription (0xAncientTwo)
args = append(args, "--thinking", "disabled")
}
if len(req.Format.schema()) > 0 {
args = append(args, "--json-schema", string(cliSchema(req.Format.schema())))
}
// in the caller's own folder when it says which it is and it is one
// here (clientWorkDir): Claude Code tells the model the folder it runs
// in as its working directory, and a model told magpie's folder wrote
// the caller's files there, through tools that run in the caller's
work := ""
if binary.wsl == nil {
work = clientWorkDir(req)
}
client := work != ""
if !client {
work, err = claudeWorkDir()
req.envElsewhere = clientNamedWorkDir(req) != ""
// a caller on another computer that names no folder: Claude Code's
// environment is this computer's, and the tools run on the
// caller's (packinggoods on Discord: a Mac client of a Windows
// gateway had its commands wrapped in PowerShell)
req.envUnknown = !req.envElsewhere && req.remoteCaller
}
if req.leanPrompt {
// in a file of the run's own: instructions can be longer than
// Windows lets a command line be
systemPath := filepath.Join(tmp, "system.md")
if err := os.WriteFile(systemPath, []byte(leanSystem(req)), 0o600); err != nil {
cleanup()
return nil, nil, err
}
args = append(args, "--system-prompt-file", binary.file(systemPath))
}
var sessions []string
switch {
case err != nil:
// a run of its own folder answers all the same, its prompt only
// read from the cache as far as Claude Code's own part
log.Printf("claude: working in a folder of the run's own: %v", err)
work = tmp
case binary.wsl == nil:
// its session is kept on disk, for a turn after it is let go to
// go on with it (claudeSessions)
sessions = claudeSessions(configDir, work)
args = slices.DeleteFunc(args, func(a string) bool { return a == "--no-session-persistence" })
// a caller's folder keeps its own sessions beside the runs': only
// magpie's own folder is swept, a run's session removed by its id
if !client {
b.sweepSessions(sessions)
}
}
if from != nil {
defer from.discard() // unless the run took it
if sessions == nil || !slices.Equal(from.sessions, sessions) || !from.saved() {
from = nil
}
}
if from != nil {
args = append(args, "--resume", from.session)
} else if hasReply(req.Messages) {
// no run had the conversation: this one is told it whole, in one
// message, its earlier turns marked as such (renderClaudePrompt)
log.Printf("claude: a new Claude Code is told the whole conversation: %d messages, %d images, the last turn marked as the one to answer", len(req.Messages), countImages(req.Messages))
}
req.clientCache.selected(from == nil)
var prompt []map[string]any
var prefix cachePrefix
if from != nil {
prefix = from.cachePrefix
prompt = renderClaudeTurn(req.Messages[len(req.Messages)-len(from.since):], req.Tools)
} else {
prompt, err = renderClaudePrompt(req)
if err != nil {
cleanup()
return nil, nil, err
}
if req.clientCache != nil {
prefix = promptCachePrefix(prompt)
}
}
cmd := binary.command(context.Background(), args...)
cmd.Dir = work
env, err := binary.proxied(ctx, cleanClaudeEnv(os.Environ()))
if err != nil {
cleanup()
return nil, nil, err
}
if req.clientCache != nil {
env = append(env, "DISABLE_PROMPT_CACHING=1")
}
if len(req.Safeguards) > 0 {
env = append(env, "ANTHROPIC_BETAS="+req.SafeguardBeta)
}
cmd.Env = binary.env(binary.asRoot(env), configDir)
stdin, err := cmd.StdinPipe()
if err != nil {
cleanup()
return nil, nil, err
}
// Claude Code's output comes through pipes of the run's own, not
// cmd.StdoutPipe's, which Wait closes as Claude Code exits: what it
// wrote last, or the reading under way as it was stopped, failed
// "file already closed", and the client heard that for an error.
stdout, stdoutW, err := os.Pipe()
if err != nil {
cleanup()
return nil, nil, err
}
stderr, stderrW, err := os.Pipe()
if err != nil {
_, _ = stdout.Close(), stdoutW.Close()
cleanup()
return nil, nil, err
}
cmd.Stdout, cmd.Stderr = stdoutW, stderrW
run := &subscriptionRun{bridge: b, token: token, model: model, cmd: cmd, tmp: tmp, schema: len(req.Format.schema()) > 0, pending: map[string]chan mcpToolResult{}, stdin: stdin, effort: req.Effort, sessions: sessions, started: time.Now()}
run.owner.Store(&owner)
run.names = bridgeNames(req.Tools)
run.safeguardBeta = req.SafeguardBeta
run.clientMarks = req.clientCache != nil
run.lean = req.leanPrompt
run.cachePrefix = prefix
if user, _ := ownerAccount(owner); user != "" {
run.loginVersion = provider.ClaudeLoginVersion(user)
}
// 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(runTimeout, func() { run.abortFor("it waited as long as it may") })
run.ends = time.Now().Add(runTimeout)
segment := run.attach()
b.mu.Lock()
b.runs[token] = run
b.mu.Unlock()
addCallback(token)
run.outputs = []*os.File{stdout, stderr}
run.reading.Add(2)
run.room = room
err = run.launch()
launched = err == nil
_, _ = stdoutW.Close(), stderrW.Close() // Claude Code has its own
if err != nil {
_, _ = stdout.Close(), stderr.Close()
b.removeRun(run)
return nil, nil, err
}
go func() {
defer run.reading.Done()
_, _ = io.Copy(&lockedWriter{run: run}, io.LimitReader(stderr, 1<<20))
_, _ = io.Copy(io.Discard, stderr)
}()
go func() {
defer run.reading.Done()
run.readOutput(stdout)
}()
if len(req.Safeguards) > 0 || from != nil || run.clientMarks {
// Initialize the SDK before applying settings. Send the potentially
// large context over stdin rather than an environment entry. A
// Claude Code resumed from a saved session answers it only once
// it has loaded the session, and one that can't exits instead
// (start tells a new one the whole conversation): told the turn
// first, it ended with no reply.
if err := run.cliControl(map[string]any{"subtype": "initialize"}); err != nil {
run.abort()
return nil, nil, err
}
}
if err := run.setSafeguards(req); err != nil {
run.abort()
return nil, nil, err
}
if from != nil {
// the session is the run's now: its file goes when the run does,
// unless the run is shelved in turn
from.taken()
run.mu.Lock()
run.sessionID = from.session
run.mu.Unlock()
}
line, _ := json.Marshal(map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": prompt}})
if err := run.tell(line); err != nil {
run.abort()
return nil, nil, err
}
return run, segment, nil
}
// safeguardBody is the safety-only form of the run's extra body.
func safeguardBody(raw json.RawMessage) string {
return claudeExtraBody(raw, "")
}
// claudeExtraBody passes the safety field and opted-in cache tail through
// EXTRA_BODY. It leaves the CLI's own beta headers intact.
func claudeExtraBody(raw json.RawMessage, tail string) string {
body := map[string]any{}
if tail != "" {
body["cache_control"] = cacheMark(tail)
}
if len(raw) > 0 {
body["safeguards"] = raw
}
b, _ := json.Marshal(body)
return string(b)
}
// setSafeguards updates the caller's safety context and opted-in cache tail.
// It does not change the VPS's permission state.
// A CLI unable to acknowledge the update is discarded by the caller; its old
// context must never be used for another turn. The client's approval still
// decides whether the tool runs, including a server verdict that is unavailable.
func (r *subscriptionRun) setSafeguards(req *Request) error {
r.settingsMu.Lock()
defer r.settingsMu.Unlock()
tail := req.cacheTail()
if r.clientMarks != (req.clientCache != nil) || !r.cachePrefix.accepts(tail) {
return errors.New("client cache marks changed; restart Claude Code")
}
if r.cacheTail == tail && bytes.Equal(r.safeguards, req.Safeguards) && (len(req.Safeguards) == 0 || r.safeguardBeta == req.SafeguardBeta) {
return nil
}
if len(req.Safeguards) > 0 && r.safeguardBeta != req.SafeguardBeta {
return errors.New("safety beta changed; restart Claude Code")
}
err := r.cliControl(map[string]any{"subtype": "apply_flag_settings", "settings": map[string]any{
"env": map[string]string{"CLAUDE_CODE_EXTRA_BODY": claudeExtraBody(req.Safeguards, tail)}}})
if err == nil {
r.cacheTail = tail
r.safeguards = bytes.Clone(req.Safeguards)
}
return err
}
// cliControl shares the SDK reply dispatcher with rewind, so unrelated or
// late control responses cannot acknowledge a safety-context update.
func (r *subscriptionRun) cliControl(request map[string]any) error {
id := randomToken()
ch := make(chan controlReply, 1)
// one that ended says how, and the last it wrote to stderr: "Claude
// Code ended" alone left the user nothing to act on
what := fmt.Sprintf("answered magpie's %v request", request["subtype"])
r.mu.Lock()
if r.closed {
r.mu.Unlock()
return r.endedBefore(what)
}
if r.controls == nil {
r.controls = map[string]chan controlReply{}
}
r.controls[id] = ch
r.mu.Unlock()
defer func() {
r.mu.Lock()
delete(r.controls, id)
r.mu.Unlock()
}()
line, _ := json.Marshal(map[string]any{"type": "control_request", "request_id": id, "request": request})
if err := r.tell(line); err != nil {
return err
}
t := time.NewTimer(10 * time.Second)
defer t.Stop()
select {
case reply, ok := <-ch:
if !ok {
return r.endedBefore(what)
}
if reply.Subtype != "success" {
return fmt.Errorf("Claude settings: %s", reply.Error)
}
return nil
case <-t.C:
return fmt.Errorf("Claude Code has not %s in 10s", what)
}
}
// claimResume holds a tool-result handoff across its context update and reply.
func (r *subscriptionRun) claimResume() bool {
r.mu.Lock()
defer r.mu.Unlock()
if r.closed || r.resuming || r.segment != nil {
return false
}
r.resuming = true
return true
}
// 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) {
key, since := nextTurn(req, owner)
if key == "" {
return nil, nil
}
b.mu.Lock()
run := b.idle[key]
back := "" // the turn the run is taken back from first
if run == nil {
// the run went on with a turn this one doesn't follow: Claude
// Code's side question, asked as the conversation so far and a
// message more (#1638). It goes back to before that turn.
for _, r := range b.idle {
if r.behindKey == key && r.behindTurn != "" {
run, back = r, r.behindTurn
break
}
}
}
if run == nil {
// the client sent the conversation back rewritten (#912): the
// run is its own when nothing else could be, and its agent was
// told every tool the client offers now
if r, _ := b.rewritten(req, owner); r != nil && r.offers(req.Tools) {
run = r
log.Printf("claude: a conversation whose last turn the client rewrote goes on in its run")
}
}
if run != nil {
delete(b.idle, run.idleKey)
run.idleKey = ""
run.behindKey, run.behindTurn = "", ""
}
b.mu.Unlock()
if run == nil {
return nil, nil
}
req.clientCache.selected(false)
if back != "" {
if err := run.rewind(back); err != nil {
log.Printf("claude: a run that went on with a side question could not be taken back to the conversation's turn, let go: %v", err)
run.abortFor("it could not be taken back from a side question: " + err.Error())
return nil, nil
}
// its session file may not say so: it isn't shelved (shelve)
run.mu.Lock()
run.rewound = true
run.mu.Unlock()
log.Printf("claude: the conversation's next turn goes on in its run, taken back from the side question it answered since")
}
if slices.ContainsFunc(since[len(since)-1].Parts, func(p Part) bool { return p.Kind == ToolResult }) {
// said after the "no run waiting" line it follows: the run took
// the turn back when the client went away (letGo), and is told it
// again from its user message, not the whole conversation
log.Printf("claude: a turn taken back goes on in its run, told again from its user message (%d messages)", len(since))
}
// a run still taking back the turn the client gave up on (letGo) is
// waited for: it goes on from before that turn, or ended
run.mu.Lock()
rewinding := run.rewinding
run.mu.Unlock()
if rewinding != nil {
<-rewinding
}
if err := run.setSafeguards(req); err != nil {
run.abortFor("its safeguards could not be set for the next turn: " + err.Error())
return nil, nil
}
// the message's id is the turn's, to rewind to if the client gives up
// on it
turn := newUUID()
line, _ := json.Marshal(map[string]any{"type": "user", "uuid": turn, "message": map[string]any{"role": "user", "content": renderClaudeTurn(since, req.Tools)}})
run.mu.Lock()
if run.closed {
run.mu.Unlock()
return nil, nil
}
ch := make(chan Event, 64)
run.segment = ch
run.active = time.Now()
run.turnUUID, run.backKey = turn, key
run.mu.Unlock()
run.endIn(runTimeout)
// a turn the router picked another effort for (#502) goes on in the
// same Claude Code, told the level first: it asks the next turn at it
// in output_config alone, the conversation it wrote to the cache
// untouched, where a run started anew is told it in one message, a
// prefix the cache has never seen
if req.Effort != run.effort {
if err := run.setEffort(req.Effort); err != nil {
run.abortFor("it could not be told the next turn's effort: " + err.Error())
return nil, nil
}
}
if err := run.tell(line); err != nil {
run.abortFor("it could not be told the next turn: " + err.Error())
return nil, nil
}
return run, ch
}
// nextTurn is the conversation a request goes on from, after its last
// reply (turnKey), and the messages since; "" when it isn't a new turn
// after a reply: a first one, or tool results for a call made before it.
// A reply that ends a turn calls no tool, so the calls after it, and their
// results, are the client's own: an agent's framework that ran a tool
// itself after the reply and put it in the conversation as a call and its
// result (Pi Team Bright's team_sync). They go to the run as the rest of
// what was said since, where a run started anew would be told the whole
// conversation in one message, a prefix the cache has never seen.
func nextTurn(req *Request, owner string) (string, []Message) {
msgs := req.Messages
if len(msgs) == 0 || msgs[len(msgs)-1].Role == "assistant" {
return "", nil
}
j := len(msgs) - 1
for j >= 0 && (msgs[j].Role != "assistant" || callsTool(msgs[j])) {
j--
}
if j < 0 {
return "", nil
}
since := msgs[j+1:]
calls := map[string]bool{}
for _, m := range since {
for _, p := range m.Parts {
switch {
case p.Kind == ToolCall:
calls[p.ID] = true
case p.Kind == ToolResult && !calls[p.CallID]:
return "", nil
}
}
}
return turnKey(owner, req, msgs[:j+1]), since
}
// looseTurn is a conversation a run waits at, as a client may send it
// back rewritten (#912): Alma takes the [Context: …] it gave a turn's user
// message out of it once the turn is over, and the notification block at
// the end of a reply, its own, out of the reply, so the next turn's
// conversation is never the one the run had (turnKey), and each turn was
// told to a new Claude Code in one message, all of it written to the
// prompt cache again. key is the settings, tools aside, and the
// conversation up to its last turn, which must be as they were; turn is
// that turn's messages, its reply last, of which the client may have cut
// the user's messages and the reply's end (rewrote).
type looseTurn struct {
key string
turn []turnWords
// runs is the turn as lostMedia compares it (#1382): sealed as a run
// keeps it, with its words as a request has it
runs []heardRun
}
// turnWords is a message of a turn as hashMessages reads it: its role,
// its words, and whether it calls a tool or carries a result.
type turnWords struct {
role, words string
tools bool
}
// newLooseTurn is msgs, which end with a reply, as looseTurn keeps them
// (sealed) or a request has them. The message count isn't in the key:
// rewrote compares the turn's, which a client that took the images out of
// it changed (lostMedia), and the earlier turns' are in their hash.
func newLooseTurn(owner string, req *Request, msgs []Message, sealed bool) *looseTurn {
if len(msgs) == 0 {
return nil
}
start := 0 // the last turn's first message
for i := len(msgs) - 2; i >= 0; i-- {
if msgs[i].Role == "assistant" && !callsTool(msgs[i]) {
start = i + 1
break
}
}
h := sha256.New()
fmt.Fprintf(h, "%s\x00%s\x00%t\x00%t\x00%s\x00%s\x00%t\x00%s\x00%d", owner, req.Model, req.Effort != "", req.ThinkOff, req.ToolChoice, withoutBillingHeader(req.System), req.WebSearch, req.Format.schema(), start)
cacheIdentity(h, req)
hashMessages(h, msgs[:start], nil)
l := &looseTurn{key: hex.EncodeToString(h.Sum(nil)), runs: heardRuns(msgs[start:], sealed)}
words := messageWords(msgs)
for i := start; i < len(msgs); i++ {
tools := false
for _, p := range msgs[i].Parts {
tools = tools || p.Kind == ToolCall || p.Kind == ToolResult
}
l.turn = append(l.turn, turnWords{msgs[i].Role, words[i], tools})
}
return l
}
// rewrote says now's turn is the one l kept as a client sends it back:
// the same messages, calls and results, a user's message no more than cut
// (a part of it taken out, but not all), and the reply's start (its end
// taken out, but not all of it); or the same turn with images taken out
// of it, and only those (lostMedia, #1382).
func (l *looseTurn) rewrote(now *looseTurn) bool {
if l.cut(now.turn) {
return true
}
return len(now.runs) == len(l.runs) && lostMedia(l.runs, now.runs)
}
// cut is rewrote for a client that cut a user's message or the reply.
func (l *looseTurn) cut(turn []turnWords) bool {
if len(turn) != len(l.turn) {
return false
}
for i, m := range turn {
was := l.turn[i]
switch {
case m.role != was.role || m.tools != was.tools:
return false
case m.words == was.words:
case m.tools || m.words == "":
return false
case i == len(turn)-1:
if !strings.HasPrefix(was.words, m.words) {
return false
}
case m.role != "user" || !cutFrom(was.words, m.words):
return false
}
}
return true
}
// cutFrom says s is was with one part of it taken out: was's start and
// end, which meet.
func cutFrom(was, s string) bool {
if len(s) >= len(was) {
return false
}
n := 0
for n < len(s) && s[n] == was[n] {
n++
}
return strings.HasSuffix(was, s[n:])
}
// rewritten finds the run, or the saved session, waiting at the
// conversation a request goes on from as its client rewrote it
// (looseTurn), when there is just one (b.mu held). Two that could be it
// are two conversations alike as far as their words go, and neither is
// taken: a run handed another's would answer from what the other was told.
func (b *subscriptionBridge) rewritten(req *Request, owner string) (*subscriptionRun, *savedSession) {
key, since := nextTurn(req, owner)
if key == "" {
return nil, nil
}
l := newLooseTurn(owner, req, req.Messages[:len(req.Messages)-len(since)], false)
if l == nil {
return nil, nil
}
var run *subscriptionRun
var saved *savedSession
found := 0
for _, r := range b.idle {
if r.owned() == owner && r.loose != nil && r.loose.key == l.key && r.loose.rewrote(l) {
run, found = r, found+1
}
}
for _, s := range b.shelf {
if s.owner == owner && s.loose != nil && s.loose.key == l.key && s.loose.rewrote(l) {
saved, found = s, found+1
}
}
if found != 1 {
if found > 1 {
log.Printf("claude: %d conversations could be the one a rewritten turn goes on from; none is taken", found)
}
return nil, nil
}
return run, saved
}
// toolsCover says tools has every one of names: a session resumed with
// them has no call of a tool it isn't told of.
func toolsCover(tools []Tool, names map[string]bool) bool {
for name := range names {
if !slices.ContainsFunc(tools, func(t Tool) bool { return t.Name == name }) {
return false
}
}
return true
}
// callsTool says m calls a tool.
func callsTool(m Message) bool {
for _, p := range m.Parts {
if p.Kind == ToolCall {
return true
}
}
return false
}
// setEffort tells the run's Claude Code to think at effort from its next
// turn, as its SDK's applyFlagSettings does: a control request, answered
// with a control_response its output is read past.
func (r *subscriptionRun) setEffort(effort string) error {
line, _ := json.Marshal(map[string]any{"type": "control_request", "request_id": "effort-" + randomToken()[:12],
"request": map[string]any{"subtype": "apply_flag_settings", "settings": map[string]any{"effortLevel": effort}}})
if err := r.tell(line); err != nil {
return err
}
r.effort = effort
return nil
}
// retire lets go of the runs left waiting at an earlier point of this
// conversation, which a new run now carries on: its turns since went to
// another model (switched to and back), so none of them comes back to
// those runs, each a Claude Code process kept idleLongest for nothing.
func (b *subscriptionBridge) retire(owner string, msgs []Message) {
keys := conversationKeys(owner, msgs)
var drop []*subscriptionRun
b.mu.Lock()
for key, run := range b.idle {
if run.owned() == owner && run.convKey != "" && slices.Contains(keys, run.convKey) {
delete(b.idle, key)
run.idleKey = ""
drop = append(drop, run)
}
}
var gone []*savedSession
for key, s := range b.shelf {
if s.owner == owner && s.conv != "" && slices.Contains(keys, s.conv) {
delete(b.shelf, key)
gone = append(gone, s)
}
}
b.mu.Unlock()
for _, s := range gone {
s.discard()
}
for _, run := range drop {
run.abortFor("its conversation was told to a new one")
}
}
// 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, as is a one-off ask.
func (r *subscriptionRun) ended(req *Request, said, stop string, ok bool) {
// the turn's reply is over: nothing after it is taken back to before
// it (letGo). A reply that calls tools hasn't ended the turn: the
// client's results go on with it, and a client that goes away during
// what the run says to them takes back the whole turn, its user
// message on, as it would before its first call (#1365). Ended there,
// the client's next request, its results sent again or the next turn,
// found no run and a new one was told the whole conversation.
r.mu.Lock()
turn, back := r.turnUUID, r.backKey
if !ok || stop != "tool" {
r.turnUUID, r.backKey = "", ""
}
r.mu.Unlock()
switch {
case !ok:
// the caller has no whole reply, so no tool calls to answer
r.abortFor("its reply failed or was cut short")
return
case stop == "tool":
r.park()
return // it waits on its tool calls
case r.stdin == nil:
return // it ends by itself
case stop != "stop":
r.abortFor("its reply ended as " + stop)
return
case len(req.Tools) == 0 && !hasReply(req.Messages):
// a one-off ask — an agent's title or topic, the router's
// classifier, Claude Code's auto mode classifier with its
// transcript in several user messages (#250) — has no next turn:
// kept, it would be a Claude Code process idle for idleLongest,
// several at once, pushing out the conversations' own
r.abort()
return
}
// kept under the name the next turn comes by: a run that began on
// Claude Code's own sign-in before it had one has named it since
r.nameOwner()
reply := Message{Role: "assistant", Parts: []Part{{Kind: Text, Text: said}}}
msgs := append(req.Messages[:len(req.Messages):len(req.Messages)], reply)
key := turnKey(r.owned(), req, msgs)
conv := ""
if keys := conversationKeys(r.owned(), msgs); len(keys) > 0 {
conv = keys[len(keys)-1]
}
loose := newLooseTurn(r.owned(), req, msgs, true)
r.bridge.mu.Lock()
r.loose = loose
// the conversation before this turn, when the run was resumed for
// it: a side question Claude Code asked of it is taken back from
// there when the conversation's own next turn comes (resume)
r.behindKey, r.behindTurn = back, turn
r.bridge.mu.Unlock()
if why, over := r.oversized(2); over {
r.bridge.letGoOversized(r, key, conv, why)
return
}
if !r.bridge.keepIdle(r, key, conv) {
return // it ended during its reply (#1667)
}
r.endIn(idleLongest)
}
// keepIdle leaves run waiting for the turn after the conversation key
// names, the longest waiting let go past idleMost; conv, when set, is that
// conversation whatever the model (convKey). A run that has ended isn't
// kept, and keepIdle says so: its 30-minute timer can end it during a
// reply that still reaches the client whole (#1667), and kept, it held one
// of idleMost places until pushed out, as removeRun, which takes it out,
// had already been. finish says it ended before removeRun takes b.mu, so a
// run kept here before then is taken out by it.
func (b *subscriptionBridge) keepIdle(r *subscriptionRun, key, conv string) bool {
var drop []*subscriptionRun
b.mu.Lock()
r.mu.Lock()
closed := r.closed
r.mu.Unlock()
if closed {
b.mu.Unlock()
return false
}
// a run waits at one point of its conversation: kept again, it leaves
// the key it waited at, unless another run waits there now (#1596:
// which caller kept one run twice isn't known; ended and letGo of one
// request exclude each other through gone()). Left there, the same
// run under two keys was the oldest again after each pass below, which
// let go of one key only, so the loop never ended and drop grew with
// b.mu held (X, Sma1lboy: magpie at 158 GB after two days).
if r.idleKey != "" && r.idleKey != key && b.idle[r.idleKey] == r {
delete(b.idle, r.idleKey)
}
if old := b.idle[key]; old != nil && old != r {
drop = append(drop, old)
}
b.idle[key] = r
r.idleKey, r.idleAt = key, time.Now()
if conv != "" {
r.convKey = conv
}
for len(b.idle) > idleMost {
var oldKey string
var oldest *subscriptionRun
for k, run := range b.idle {
if oldest == nil || run.idleAt.Before(oldest.idleAt) {
oldKey, oldest = k, run
}
}
b.shelve(oldest)
// the key found, not the run's own: each pass takes one entry out
delete(b.idle, oldKey)
if oldest.idleKey == oldKey {
oldest.idleKey = ""
}
if !slices.Contains(drop, oldest) {
drop = append(drop, oldest)
}
}
b.mu.Unlock()
for _, run := range drop {
run.abortFor("another run was kept in its place (" + strconv.Itoa(idleMost) + " wait at most)")
}
claudeRoom.nudge() // an ask waiting for room may let it go
return true
}
// shelfMost is how many saved sessions the shelf keeps, the longest
// waiting let go first: each is a file of its conversation.
const shelfMost = 64
// savedSession is the saved Claude Code session of a run let go past idleMost,
// kept for its conversation's next turn as long as the run would have
// waited. That turn starts Claude Code with --resume on it, told only the
// messages since, so Anthropic is asked the conversation as the run would
// have asked it, a prefix it has cached; a run started anew is told the
// whole conversation in one message, and writes all of it to the cache
// again (X, AncientTwo: a Claude subscription's limits went much faster
// through magpie than in Claude Code — with more than idleMost
// conversations going, each turn of each wrote its whole conversation).
type savedSession struct {
session string
sessions []string // Claude Code's project folders it is saved in
owner string
conv string // its conversation whatever the model (convKey)
key string // where it is on the shelf (turnKey)
loose *looseTurn
tools map[string]bool // the tools its agent was told of
at time.Time // since when it waits
timer *time.Timer
since []Message // the turn's messages, once unshelved
cachePrefix cachePrefix
mu sync.Mutex
gone bool // taken by a run, or discarded
}
// shelve keeps run's session, when it has one, for its conversation's
// next turn (b.mu held). The file is the shelf's from here: the run, let
// go, leaves it.
func (b *subscriptionBridge) shelve(run *subscriptionRun) {
run.mu.Lock()
sid, sessions, rewound, tools := run.sessionID, run.sessions, run.rewound, maps.Clone(run.tools)
run.mu.Unlock()
if sid == "" || len(sessions) == 0 || rewound || run.idleKey == "" {
return
}
key := run.idleKey
s := &savedSession{session: sid, sessions: sessions, owner: run.owned(), conv: run.convKey, key: key, loose: run.loose, tools: tools, at: run.idleAt, cachePrefix: run.cachePrefix}
if old := b.shelf[key]; old != nil {
go old.discard()
}
b.shelf[key] = s
run.mu.Lock()
run.shelved = true
run.mu.Unlock()
s.timer = time.AfterFunc(idleLongest-time.Since(s.at), func() {
b.mu.Lock()
if b.shelf[key] == s {
delete(b.shelf, key)
}
b.mu.Unlock()
s.discard()
})
for len(b.shelf) > shelfMost {
var oldKey string
var oldest *savedSession
for k, e := range b.shelf {
if oldest == nil || e.at.Before(oldest.at) {
oldKey, oldest = k, e
}
}
delete(b.shelf, oldKey)
go oldest.discard()
}
}
// unshelve takes the saved session a request's conversation goes on
// from, if there is one: its next turn, asked of the account, model and
// settings it had.
func (b *subscriptionBridge) unshelve(req *Request, owner string) *savedSession {
key, since := nextTurn(req, owner)
if key == "" {
return nil
}
b.mu.Lock()
s := b.shelf[key]
if s == nil {
// rewritten (resume); its Claude Code is told the tools the
// client offers now, and the session keeps the calls made of
// those it had
if _, saved := b.rewritten(req, owner); saved != nil && toolsCover(req.Tools, saved.tools) {
s, key = saved, saved.key
log.Printf("claude: a conversation whose last turn the client rewrote goes on from its saved session")
}
}
delete(b.shelf, key)
b.mu.Unlock()
if s == nil {
return nil
}
s.timer.Stop()
if !s.cachePrefix.accepts(req.cacheTail()) {
s.discard()
return nil
}
s.since = since
return s
}
// saved says its session's file is still there.
func (s *savedSession) saved() bool {
for _, dir := range s.sessions {
if _, err := os.Stat(filepath.Join(dir, s.session+".jsonl")); err == nil {
return true
}
}
return false
}
// taken hands the session to the run that goes on with it.
func (s *savedSession) taken() {
s.mu.Lock()
s.gone = true
s.mu.Unlock()
}
// discard removes the session's files, unless a run took it.
func (s *savedSession) discard() {
s.mu.Lock()
gone := s.gone
s.gone = true
s.mu.Unlock()
if s.timer != nil {
s.timer.Stop()
}
if !gone {
removeSession(s.sessions, s.session)
}
}
// claudeSessions is the project folders Claude Code saves a session of a
// run in work under: work's own name and, where it is a link (macOS's
// /var), the real path's, in configDir ("" for Claude Code's own).
func claudeSessions(configDir, work string) []string {
if configDir == "" {
configDir = claudeConfigDir()
}
var dirs []string
for _, w := range []string{work, evalSymlinks(work)} {
d := filepath.Join(configDir, "projects", claudeProjectName(w))
if !slices.Contains(dirs, d) {
dirs = append(dirs, d)
}
}
return dirs
}
// removeSession removes a session's file, and the folder of its own
// Claude Code may keep beside it.
func removeSession(dirs []string, sid string) {
if sid == "" || strings.ContainsAny(sid, `/\`) || strings.Contains(sid, "..") {
return
}
for _, dir := range dirs {
_ = os.Remove(filepath.Join(dir, sid+".jsonl"))
_ = os.RemoveAll(filepath.Join(dir, sid))
if tmp := claudeTempDir(dir); tmp != "" {
_ = os.RemoveAll(filepath.Join(tmp, sid))
}
}
}
// claudeTempDir is the folder Claude Code keeps its sessions' passing
// files in for the project whose sessions are in dir: the images each was
// given, one file for each, where nothing removed them (#912: 16, then 33
// in one conversation's). It is CLAUDE_CODE_TMPDIR's, else /tmp's,
// claude-<uid>, by the project's name; "" where Claude Code has no uid to
// name it by (Windows).
func claudeTempDir(dir string) string {
if runtime.GOOS == "windows" {
return ""
}
root := os.Getenv("CLAUDE_CODE_TMPDIR")
if root == "" {
root = "/tmp"
}
return filepath.Join(root, fmt.Sprintf("claude-%d", os.Getuid()), filepath.Base(dir))
}
// tempLongest is how long a session's passing files are left, untouched
// and with no session file beside them, before a sweep removes them: the
// folder is the work folder's, whichever account's Claude Code it was, and
// another account's sessions are saved in another config folder, so a
// session still going has its files left as long as a session could.
const tempLongest = 24 * time.Hour
// untouchedFor says nothing in the folder at path changed for age.
func untouchedFor(path string, age time.Duration) bool {
old := true
_ = filepath.WalkDir(path, func(_ string, d fs.DirEntry, err error) error {
if err != nil {
old = false
return filepath.SkipAll
}
if fi, err := d.Info(); err != nil || time.Since(fi.ModTime()) <= age {
old = false
return filepath.SkipAll
}
return nil
})
return old
}
// sweepSessions removes, once a gateway for each of Claude Code's
// folders, the sessions a gateway that stopped or crashed left there:
// those untouched for longer than one would be kept. Another gateway on
// the same account (a dev build) works in the same folder; its sessions
// are newer.
func (b *subscriptionBridge) sweepSessions(dirs []string) {
for _, dir := range dirs {
if _, done := b.swept.LoadOrStore(dir, true); done {
continue
}
go func() {
entries, _ := os.ReadDir(dir)
for _, e := range entries {
sid, ok := strings.CutSuffix(e.Name(), ".jsonl")
if !ok || e.IsDir() {
continue
}
if fi, err := e.Info(); err == nil && time.Since(fi.ModTime()) > idleLongest+time.Minute {
removeSession([]string{dir}, sid)
}
}
tmp := claudeTempDir(dir)
if tmp == "" {
return
}
entries, _ = os.ReadDir(tmp)
for _, e := range entries {
sid := e.Name()
if !e.IsDir() || strings.HasPrefix(sid, ".") {
continue
}
if _, err := os.Stat(filepath.Join(dir, sid+".jsonl")); err == nil {
continue
}
if untouchedFor(filepath.Join(tmp, sid), tempLongest) {
_ = os.RemoveAll(filepath.Join(tmp, sid))
}
}
}()
}
}
// rewindLongest is how long Claude Code may take to answer a rewind
// before its run is let go.
var rewindLongest = 10 * time.Second
// controlReply is Claude Code's control_response to a control request.
type controlReply struct {
Subtype string `json:"subtype"`
RequestID string `json:"request_id"`
Error string `json:"error"`
Response struct {
Rewound bool `json:"rewound"`
} `json:"response"`
}
// letGo is told the client went away mid-reply (#780). A turn resumed in
// a run kept for it is taken back: Claude Code is told to rewind to the
// turn's message, which stops the reply and leaves its conversation as it
// was before the turn, and the run waits there again, for the client's
// resend to go on from the prefix it cached. That holds in the reply to
// the turn's tool results too (#1365): the turn is taken back whole, its
// tool rounds with it, and the client's next request is told the turn
// since its user message, not the whole conversation. Any other run — one
// started for the turn, one with a tool call in the client's hands, one
// whose Claude Code refuses or doesn't answer — is ended, as before.
func (r *subscriptionRun) letGo() {
r.mu.Lock()
turn, back := r.turnUUID, r.backKey
can := !r.closed && r.stdin != nil && r.bridge != nil && r.timer != nil &&
turn != "" && back != "" && len(r.pending) == 0 && r.rewinding == nil
done := make(chan struct{})
if can {
r.rewinding = done
r.turnUUID, r.backKey = "", "" // once a turn
r.rewound = true
}
r.mu.Unlock()
if !can {
r.abortFor("the client went away during a turn it can't take back")
return
}
defer func() {
r.mu.Lock()
r.rewinding = nil
r.mu.Unlock()
close(done)
}()
// the reply goes to no one from here: what Claude Code says as it
// stops (an interrupted result) is read past
r.endSegment()
// found at once by a resend, which waits for the rewind (resume)
if !r.bridge.keepIdle(r, back, "") {
return // it ended since (#1667): there is nothing to take back
}
if err := r.rewind(turn); err != nil {
log.Printf("claude: a turn the client gave up on could not be taken back, its run let go: %v", err)
r.abortFor("a turn the client gave up on could not be taken back: " + err.Error())
return
}
r.mu.Lock()
r.asked, r.shown, r.parkedAt = nil, nil, time.Time{}
clear(r.early)
r.mu.Unlock()
r.endIn(idleLongest)
log.Printf("claude: the turn the client gave up on was taken back; its run waits for the conversation's next turn")
}
// rewind tells the run's Claude Code to take its conversation back to
// before the user message turn, stopping a reply under way, as its SDK's
// rewindConversation does.
func (r *subscriptionRun) rewind(turn string) error {
id := "rewind-" + randomToken()[:12]
ch := make(chan controlReply, 1)
r.mu.Lock()
if r.closed {
r.mu.Unlock()
return errors.New("the run ended")
}
if r.controls == nil {
r.controls = map[string]chan controlReply{}
}
r.controls[id] = ch
r.mu.Unlock()
defer func() {
r.mu.Lock()
delete(r.controls, id)
r.mu.Unlock()
}()
line, _ := json.Marshal(map[string]any{"type": "control_request", "request_id": id,
"request": map[string]any{"subtype": "rewind_conversation", "target_message_uuid": turn, "interrupt_if_running": true}})
if err := r.tell(line); err != nil {
return err
}
t := time.NewTimer(rewindLongest)
defer t.Stop()
select {
case reply, ok := <-ch:
switch {
case !ok:
return errors.New("the run ended")
case reply.Subtype != "success":
return fmt.Errorf("Claude Code refused it: %s", reply.Error)
case !reply.Response.Rewound:
return errors.New("Claude Code did not rewind")
}
return nil
case <-t.C:
return errors.New("Claude Code did not answer in " + rewindLongest.String())
}
}
// answered hands a control_response to the request waiting on it.
func (r *subscriptionRun) answered(raw json.RawMessage) {
var reply controlReply
if json.Unmarshal(raw, &reply) != nil {
return
}
r.mu.Lock()
ch := r.controls[reply.RequestID]
delete(r.controls, reply.RequestID)
r.mu.Unlock()
if ch != nil {
ch <- reply
}
}
// park leaves the run waiting on its reply's tool calls: parkLongest for
// a run started anew for each turn, finalGrace when they end the caller's
// turn, and among the parkedMost longest waiting otherwise.
func (r *subscriptionRun) park() {
r.mu.Lock()
final := len(r.asked) > 0
for _, name := range r.asked {
final = final && finalTools[name]
}
now := time.Now()
r.parkedAt = now
r.mu.Unlock()
switch {
case r.timer == nil:
return
case final:
r.endIn(finalGrace)
return
case r.stdin == nil:
r.endIn(parkLongest)
return
}
if why, over := r.oversized(3); over {
log.Printf("claude: Claude Code pid %d (%s) is let go while it waits on tool calls: %s; their results go to a new one told the whole conversation", r.pid(), r.model, why)
r.abortFor(why)
return
}
b := r.bridge
if b == nil {
return
}
type waiting struct {
run *subscriptionRun
at time.Time
}
var parked []waiting
b.mu.Lock()
for _, run := range b.runs {
run.mu.Lock()
at, closed := run.parkedAt, run.closed
run.mu.Unlock()
if !closed && !at.IsZero() && now.Sub(at) >= parkLongest {
parked = append(parked, waiting{run, at})
}
}
b.mu.Unlock()
if len(parked) <= parkedMost {
return
}
slices.SortFunc(parked, func(a, b waiting) int { return a.at.Compare(b.at) })
for _, w := range parked[:len(parked)-parkedMost] {
w.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. Its effort is not in it, only whether it asked for one (or
// turned thinking off, which its Claude Code was started with): a
// run is told another level as its turn starts (setEffort), where one
// started anew would write the whole conversation to the cache again (#502).
// Nor is the client's billing line, which renderClaudePrompt leaves out of
// what a run is told: its Claude Code changes fields in it every turn (cch,
// cc_prompt_id, cc_prev_req…), and with them in the key no turn found the
// run it went on from, so each started one anew (#1638).
func turnKey(owner string, req *Request, msgs []Message) string {
h := sha256.New()
tools, _ := json.Marshal(req.Tools)
fmt.Fprintf(h, "%s\x00%s\x00%t\x00%t\x00%s\x00%s\x00%s\x00%t\x00%s", owner, req.Model, req.Effort != "", req.ThinkOff, req.ToolChoice, withoutBillingHeader(req.System), tools, req.WebSearch, req.Format.schema())
cacheIdentity(h, req)
hashMessages(h, msgs, nil)
return hex.EncodeToString(h.Sum(nil))
}
// conversationKeys is the conversation so far as it stood after each of
// its replies, for the account alone — not the model, its effort or the
// tools — so a run left waiting at one of them is known whatever the model
// that turn was asked of.
func conversationKeys(owner string, msgs []Message) []string {
h := sha256.New()
fmt.Fprintf(h, "%s\x00", owner)
var keys []string
hashMessages(h, msgs, func(i int) {
if msgs[i].Role == "assistant" {
keys = append(keys, hex.EncodeToString(h.Sum(nil)))
}
})
return keys
}
// historyKey is a conversation's messages, as hashMessages reads them.
func historyKey(msgs []Message) string {
h := sha256.New()
hashMessages(h, msgs, nil)
return hex.EncodeToString(h.Sum(nil))
}
// heard keeps the conversation of the request the run now answers.
func (r *subscriptionRun) heard(msgs []Message) {
key, runs := historyKey(msgs), heardRuns(msgs, true)
r.mu.Lock()
r.told, r.toldRuns = key, runs
r.mu.Unlock()
}
// follows says msgs go on from the conversation the run last heard: that
// one whole, then the reply and what came since. A client that rewrote it
// meanwhile — Pi compacting between a tool call and its result, a rewind —
// sends another, while the run's agent still holds the one it was told.
// One whose client only took the images out of it (lostMedia, #1382) goes
// on: the run's agent holds them, and nothing else changed.
func (r *subscriptionRun) follows(msgs []Message) bool {
r.mu.Lock()
told, runs := r.told, r.toldRuns
r.mu.Unlock()
if told == "" {
return true // a run made in a test may have heard none
}
h := sha256.New()
found := false
hashMessages(h, msgs, func(int) {
found = found || hex.EncodeToString(h.Sum(nil)) == told
})
if !found && runs != nil && lostMedia(runs, heardRuns(msgs, false)) {
log.Printf("claude: tool results go on in their run, the images before them taken out by the client")
return true
}
return found
}
// hashMessages writes the messages' words, tool calls and results to h,
// calling after, when set, once each message is in. A call is told by its
// place among the conversation's calls, and a result by the call it
// answers, not by their ids: a client may name the calls it was told with
// ids of its own, the same in every request after (AmpCode's TU-…), and its
// conversation is the same one all the same.
func hashMessages(h hash.Hash, msgs []Message, after func(i int)) {
role := ""
for i, words := range messageWords(msgs) {
if words != "" {
if m := msgs[i]; m.Role != role {
role = m.Role
fmt.Fprintf(h, "\x00%s:", role)
}
h.Write([]byte(words + " "))
}
if after != nil {
after(i)
}
}
}
// messageWords is each message's words, tool calls and results, as
// hashMessages reads them.
func messageWords(msgs []Message) []string {
out := make([]string, len(msgs))
for i, parts := range messageParts(msgs) {
words := make([]string, len(parts))
for k, p := range parts {
words[k] = p.words
}
out[i] = strings.Join(words, " ")
}
return out
}
// 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",
// the run's history lives in the process; start keeps it on disk
// where a turn after the run is let go can go on with it
// (savedSession), in the folder all runs share
"--no-session-persistence",
}
if effort != "" {
// Claude Code takes xhigh as its own level, below max (#385)
args = append(args, "--effort", effort, "--thinking-display", "summarized")
}
return args
}
// inClaudeDir is env for a Claude Code run on a saved account in use beside
// the one it is signed in to: in the account's config directory
// (provider's claude_dirs.go), where Claude Code keeps the sign-in fresh
// itself. configDir "" is the account Claude Code is signed in to, and env
// is kept as it is.
func inClaudeDir(env []string, configDir string) []string {
if configDir == "" {
return env
}
out := make([]string, 0, len(env)+1)
for _, e := range env {
switch k, _, _ := strings.Cut(e, "="); k {
case "CLAUDE_CONFIG_DIR", "CLAUDE_SECURESTORAGE_CONFIG_DIR":
continue
}
out = append(out, e)
}
return append(out, "CLAUDE_CONFIG_DIR="+configDir)
}
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, "CLAUDE_CODE_PROMPT_CACHE_TTL": true,
"CLAUDE_CODE_EXTRA_BODY": true, "ANTHROPIC_BETAS": true,
}
out := make([]string, 0, len(env)+3)
for _, e := range env {
k, _, _ := strings.Cut(e, "=")
if !blocked[k] {
out = append(out, e)
}
}
// no auto memory: every run works in one folder (claudeWorkDir), so a
// memory one conversation's caller wrote there would be in the system
// prompt of all the account's others, and a change to it would undo
// the cache from there on
return append(out, "ENABLE_CLAUDEAI_MCP_SERVERS=0", "DISABLE_AUTO_COMPACT=1", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1", "CLAUDE_CODE_DISABLE_AUTO_MEMORY=1",
// run in a caller's folder (clientWorkDir), Claude Code would put
// its repository's status in the prompt too: the caller tells its
// model that itself, and a status changing with each commit undoes
// the cache from there on
"CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS=1",
// an hour's cache, as Claude Code writes it on a subscription within
// its limits, always: the mark on the caller's instructions
// (renderClaudePrompt) is an hour's, which may not follow a 5m one
"CLAUDE_CODE_PROMPT_CACHE_TTL=1h")
}
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
}
// endIn has the run let go in d unless something comes for it first.
func (r *subscriptionRun) endIn(d time.Duration) {
r.mu.Lock()
r.ends = time.Now().Add(d)
r.mu.Unlock()
r.timer.Reset(d)
}
func (r *subscriptionRun) attach() chan Event {
r.mu.Lock()
defer r.mu.Unlock()
ch := make(chan Event, 64)
r.segment = ch
r.active = time.Now()
return ch
}
func (r *subscriptionRun) emit(ev Event) {
r.sending.Lock()
defer r.sending.Unlock()
r.mu.Lock()
ch := r.segment
if ch != nil {
switch ev.Kind {
case KStart: // a reply begins
r.shown = nil
case KToolStart:
r.shown = append(r.shown, shownCall{id: ev.ID, name: ev.Name})
case KToolArgs:
if n := len(r.shown); n > 0 {
r.shown[n-1].args += ev.Text
}
}
}
r.mu.Unlock()
if ch != nil {
ch <- ev
}
}
// closeSegment closes a segment taken off the run, once no send to it is
// under way.
func (r *subscriptionRun) closeSegment(ch chan Event) {
r.sending.Lock()
close(ch)
r.sending.Unlock()
}
func (r *subscriptionRun) endSegment() {
r.mu.Lock()
ch := r.segment
r.segment = nil
if ch != nil {
r.resuming = false
}
r.mu.Unlock()
if ch != nil {
r.closeSegment(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
// With a schema the answer is what Claude Code's StructuredOutput call
// gave once Claude Code took it as fitting: its result's
// structured_output. A call that doesn't fit is told so and made again,
// and a reply in words is asked for the call, so every message but one
// calling a client's tool goes on into the next, as after Claude Code's
// own call, and the text the model writes is left out.
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
var reqID, errKind string // the last request's id, and how it failed
usage := func(u cliUsage) Usage {
v := u.gateway()
this.add(v)
return v.carryUpdate(this, before)
}
// A stream Anthropic cut short (a dropped connection, a stall) Claude
// Code ends with a message_stop of its own and no message_delta, and
// asks again: streamed, then once more without a stream, whose answer
// it tells only in whole messages, a block each (#726). That
// message_stop ends nothing: the reply goes on in the attempt that
// answers. Taken for the reply's end, it told the client end_turn with
// the first attempt's usage (5 tokens out, the thinking so far, no
// answer) and ended the run, its next turn writing the whole
// conversation to the cache again.
stopped := false // this message's message_delta said why it stopped
cut := false // an attempt was cut short, and Claude Code asks again
shown := false // this message has shown the client words or a call
streamed := "" // the message whose stream the events are
// a message told in whole messages: its id, its stop, and its blocks
// so far; it is whole when anything else comes, or nothing does for
// unstreamedQuiet, as when Claude Code goes on to call the client's
// tools and waits on them
unstreamed, unstreamedStop, blocks := "", "", 0
// The reply's tool calls written as text (textCalls), held back from
// the client. A reply that ends with them and calls none of the
// client's tools goes on: once its turn's result is in, the run is
// told to make them (textCallsAsk), and the reply goes on in its next
// message, as after Claude Code's own call. Only once a reply: told
// again, the words go to the client as written.
var calls textCalls
retell := false // the run is told to make its calls once this turn's result is in
retold := false // this reply was told so
var pmu sync.Mutex // held for each line, and by quiet's settle
var quiet *time.Timer
text := func(s string) {
if s != "" && !r.schema {
shown = true
r.emit(Event{Kind: KText, Text: s})
}
}
said := func(s string) { text(calls.push(s)) }
// what each message's end does, once its stop is known
end := func(why string) {
if goesOn := why != "" && r.schema && !theirs || why == "tool_use" && len(own) > 0 && !theirs; goesOn {
inside = true // the answer is the next message's, or the result's
} else if why != "" {
held, seen := calls.end()
switch {
case seen && !theirs && why == "end_turn" && !retold && r.stdin != nil:
retell, retold, inside = true, true, true
log.Printf("claude: a reply wrote its tool calls as text (%d bytes held back); its run is told to make them", len(held))
return
case seen && theirs:
// it called the client's tools too: those are the reply's
log.Printf("claude: a reply wrote tool calls as text beside real ones; the text (%d bytes) is left out", len(held))
case seen:
log.Printf("claude: a reply wrote its tool calls as text again; the client is told the words as written")
text(held)
default:
text(held)
}
r.emit(Event{Kind: KStop, Stop: stopFromAnthropic(why)})
}
}
settle := func() { // pmu held
if quiet != nil {
quiet.Stop()
}
if unstreamed == "" {
return
}
unstreamed = ""
end(unstreamedStop)
if !inside {
r.endSegment()
}
}
// toolStart says whether a tool_use block, index of this message, is a
// call of the client's, to be handed over as name: Claude Code's own
// calls (WebSearch, magpie's web search, a schema's StructuredOutput)
// are its own to answer
toolStart := func(index int, name string) (string, bool) {
if r.schema && name == "StructuredOutput" {
own[index] = true
return "", false
}
name, ok := strings.CutPrefix(name, "mcp__magpie__")
r.mu.Lock()
name = declaredName(r.names, name)
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[index] = true
return "", false
}
theirs, shown = true, true
r.mu.Lock()
r.asked = append(r.asked, name)
r.mu.Unlock()
return name, true
}
// begin starts a message: the reply's first, or one it goes on in,
// after Claude Code's own call or an attempt cut short
begin := func(id, model string, u cliUsage) {
own, theirs, stopped, shown = map[int]bool{}, false, false, false
if inside || cut {
inside, cut = false, false
before, this = before.plus(this, false), Usage{}
r.emit(Event{Kind: KUsage, Usage: usage(u)})
return
}
before, this = Usage{}, Usage{}
calls, retold = textCalls{}, false
r.mu.Lock()
r.asked = nil
r.mu.Unlock()
r.emit(Event{Kind: KStart, MsgID: id, Model: model, Usage: usage(u)})
}
// failed ends the reply with an error where it was cut short with
// nothing to go on in
failed := func(why string) {
cut = false
r.emit(Event{Kind: KError, Text: "Claude Code's stream from Anthropic was cut short " + why, Status: http.StatusBadGateway, RequestID: reqID})
r.endSegment()
}
line := func(b []byte) {
var envelope struct {
Type string `json:"type"`
Subtype string `json:"subtype"`
IsError bool `json:"is_error"`
// Claude Code's session, on its init message
SessionID string `json:"session_id"`
Result string `json:"result"`
// the answer fitting the schema, with --json-schema, and what
// went wrong in a turn that ended without one
StructuredOutput json.RawMessage `json:"structured_output"`
Errors []string `json:"errors"`
// Anthropic's id for the request, on the messages it answered,
// and on a failure the HTTP status Claude Code got and its
// name for the kind of error (rate_limit, server_error…)
RequestID string `json:"request_id"`
APIErrorStatus int `json:"api_error_status"`
ErrorKind json.RawMessage `json:"error"`
// what Claude Code's WebSearch found, on the message that
// answers its call
ToolUseResult json.RawMessage `json:"tool_use_result"`
// what the account has left, as Anthropic told Claude Code
RateLimitInfo json.RawMessage `json:"rate_limit_info"`
// Claude Code's answer to a control request (rewind)
Response json.RawMessage `json:"response"`
// a user message it took from its input, by the uuid it was
// given, and where it is: queued, started, completed
CommandUUID string `json:"command_uuid"`
State string `json:"state"`
// an assistant message, one of its blocks at a time; raw, as
// a user message's content may be a string
Message json.RawMessage `json:"message"`
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"`
SafeguardResults json.RawMessage `json:"safeguard_results"`
StopDetails json.RawMessage `json:"stop_details"`
} `json:"delta"`
Usage cliUsage `json:"usage"`
} `json:"event"`
}
if json.Unmarshal(b, &envelope) != nil {
return
}
var whole struct {
ID string `json:"id"`
Model string `json:"model"`
StopReason string `json:"stop_reason"`
Usage cliUsage `json:"usage"`
SafeguardResults json.RawMessage `json:"safeguard_results"`
StopDetails json.RawMessage `json:"stop_details"`
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
Thinking string `json:"thinking"`
Signature string `json:"signature"`
ID string `json:"id"`
Name string `json:"name"`
Input json.RawMessage `json:"input"`
} `json:"content"`
}
if envelope.Type == "assistant" {
_ = json.Unmarshal(envelope.Message, &whole)
}
// a message not streamed is told by its id: a streamed one's
// whole messages come after its stream's events, under its id;
// Claude Code's own (an error it tells as a message) is
// <synthetic>
next := envelope.Type == "assistant" && whole.ID != "" && whole.ID != streamed && whole.Model != "<synthetic>"
if unstreamed != "" && !(next && whole.ID == unstreamed) {
settle()
}
if envelope.Type == "control_response" {
r.answered(envelope.Response)
return
}
if envelope.Type == "command_lifecycle" {
r.mu.Lock()
if ch := r.queued[envelope.CommandUUID]; ch != nil {
close(ch)
delete(r.queued, envelope.CommandUUID)
}
r.mu.Unlock()
return
}
if envelope.Type == "system" && envelope.Subtype == "init" && envelope.SessionID != "" {
r.mu.Lock()
r.sessionID = envelope.SessionID
r.mu.Unlock()
return
}
if envelope.Type == "rate_limit_event" {
// a run in Claude Code's own home is on whatever account
// Claude Code is signed in to by now: switched off the
// owner's, what it says is another's (nil_1024)
if user, own := ownerAccount(r.owned()); user != "" && !(own && provider.ClaudeCodeMovedOff(user)) {
provider.NoteClaudeLimits(user, claudeLimits(envelope.RateLimitInfo))
}
return
}
if envelope.Type == "result" && retell && !envelope.IsError {
// the turn whose reply wrote its calls as text is over: the run
// is told to make them, and the reply goes on in its answer
retell = false
calls = textCalls{}
ask, _ := json.Marshal(map[string]any{"type": "user", "uuid": newUUID(), "message": map[string]any{"role": "user",
"content": []map[string]any{{"type": "text", "text": textCallsAsk}}}})
if err := r.tell(ask); err != nil {
inside = false
r.emit(Event{Kind: KError, Text: "Claude Code could not be told to make the tool calls its reply wrote as text: " + err.Error(), Status: http.StatusBadGateway, RequestID: reqID})
r.endSegment()
}
return
}
if envelope.Type == "result" {
retell = false
// a turn that failed — out of quota, rate limited — ends with
// this and no message_stop, the CLI waiting on its next input:
// the reply ends here, or it would wait with it (#177)
waiting := r.schema && inside
inside = false
switch {
case envelope.IsError:
cut = false
text := envelope.Result
if text == "" && waiting {
text = "Claude Code gave no answer fitting the schema (" + envelope.Subtype + ")"
if len(envelope.Errors) > 0 {
text += ": " + strings.Join(envelope.Errors, "; ")
}
}
// Anthropic refused the account's sign-in: kept on it, so
// it isn't run again on that one (provider/claude_auth.go) —
// not when Claude Code's own run went on as another account,
// which is read only for such an error
if user, own := ownerAccount(r.owned()); user != "" && provider.ClaudeSignInRequired(text) &&
!(own && provider.ClaudeCodeMovedOff(user)) {
provider.NoteClaudeSignInFailure(user, r.loginVersion, text)
}
r.emit(Event{Kind: KError, Text: text, Status: envelope.APIErrorStatus, Code: errKind, RequestID: reqID})
r.endSegment()
case cut:
failed("and Claude Code ended the turn without asking again")
case waiting && len(envelope.StructuredOutput) > 0 && string(envelope.StructuredOutput) != "null":
r.emit(Event{Kind: KText, Text: string(envelope.StructuredOutput)})
r.emit(Event{Kind: KStop, Stop: "stop"})
r.endSegment()
case waiting:
r.emit(Event{Kind: KError, Text: "Claude Code ended the turn with no answer fitting the schema", RequestID: reqID})
r.endSegment()
}
return
}
if envelope.Type == "assistant" {
// a failure says how it failed here, before its result
if envelope.RequestID != "" {
reqID = envelope.RequestID
}
var kind string
_ = json.Unmarshal(envelope.ErrorKind, &kind)
errKind = kind
if !next {
return
}
// asked again without a stream, after attempts cut short:
// the answer is told here only
if whole.ID != unstreamed {
begin(whole.ID, whole.Model, whole.Usage)
unstreamed, blocks = whole.ID, 0
}
unstreamedStop = whole.StopReason
var raws struct {
Content []json.RawMessage `json:"content"`
}
for i, c := range whole.Content {
index := blocks
blocks++
switch c.Type {
case "redacted_thinking":
// sealed whole, as Anthropic wrote it (#1445)
if raws.Content == nil {
_ = json.Unmarshal(envelope.Message, &raws)
}
if i < len(raws.Content) {
r.emit(Event{Kind: KSealed, Name: sealAnthropic, Text: string(raws.Content[i])})
}
case "thinking":
r.emit(Event{Kind: KThinkStart})
if c.Thinking != "" {
r.emit(Event{Kind: KThink, Text: c.Thinking})
}
if c.Signature != "" {
r.emit(Event{Kind: KSig, Name: sealAnthropic, Text: c.Signature})
}
case "text":
said(c.Text)
case "tool_use":
name, theirs := toolStart(index, c.Name)
if !theirs {
continue
}
r.emit(Event{Kind: KToolStart, ID: c.ID, Name: name})
if len(c.Input) > 0 {
r.emit(Event{Kind: KToolArgs, Text: string(c.Input)})
}
}
}
r.emit(Event{Kind: KUsage, Usage: usage(whole.Usage), RequestID: reqID, SafeguardResults: whole.SafeguardResults, StopDetails: stopDetails(whole.StopDetails)})
if quiet != nil {
quiet.Stop()
}
quiet = time.AfterFunc(unstreamedQuiet, func() {
pmu.Lock()
defer pmu.Unlock()
settle()
})
return
}
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})
return
}
if envelope.Type != "stream_event" {
return
}
e := envelope.Event
switch e.Type {
case "message_start":
streamed = e.Message.ID
begin(e.Message.ID, e.Message.Model, e.Message.Usage)
case "content_block_start":
switch e.ContentBlock.Type {
case "tool_use":
if name, theirs := toolStart(e.Index, e.ContentBlock.Name); theirs {
r.emit(Event{Kind: KToolStart, ID: e.ContentBlock.ID, Name: name})
}
case "text":
said(e.ContentBlock.Text)
case "thinking":
// a block of its own, signed with no text or not (#1445)
r.emit(Event{Kind: KThinkStart})
case "redacted_thinking":
var raw struct {
Event struct {
Block json.RawMessage `json:"content_block"`
} `json:"event"`
}
if json.Unmarshal(b, &raw) == nil && len(raw.Event.Block) > 0 {
r.emit(Event{Kind: KSealed, Name: sealAnthropic, Text: string(raw.Event.Block)})
}
}
case "content_block_delta":
switch e.Delta.Type {
case "text_delta":
said(e.Delta.Text)
case "thinking_delta":
r.emit(Event{Kind: KThink, Text: e.Delta.Thinking})
case "signature_delta":
r.emit(Event{Kind: KSig, Name: sealAnthropic, 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), RequestID: reqID, SafeguardResults: e.Delta.SafeguardResults, StopDetails: stopDetails(e.Delta.StopDetails)})
if e.Delta.StopReason != "" {
stopped = true
}
end(e.Delta.StopReason)
case "message_stop":
switch {
case inside:
case !stopped && shown:
// what the client was shown can't be taken back, nor
// the attempt's answer added to it: Claude Code's own
// request is the client's to make again
failed("after the reply had begun")
case !stopped:
cut = true
default:
r.endSegment()
}
}
}
for s.Scan() {
pmu.Lock()
line(s.Bytes())
pmu.Unlock()
}
pmu.Lock()
defer pmu.Unlock()
settle()
if err := s.Err(); err != nil && !errors.Is(err, os.ErrClosed) {
r.emit(Event{Kind: KError, Text: err.Error()})
} else if cut {
failed("and Claude Code stopped")
}
}
// unstreamedQuiet is how long a message told in whole messages is taken
// as whole once none of its blocks come: Claude Code writes them all at
// once.
var unstreamedQuiet = 300 * time.Millisecond
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"`
CacheCreation *aCacheCreation `json:"cache_creation"`
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.
// claudeLimits are the allowance windows a rate_limit_event's info tells:
// each of its unifiedWindows, and the one it is about, when that says how
// much is used or that it turned the request away.
func claudeLimits(raw json.RawMessage) []provider.ClaudeLimit {
type window struct {
Utilization float64 `json:"utilization"`
ResetsAt int64 `json:"resetsAt"`
}
var info struct {
Status string `json:"status"`
RateLimitType string `json:"rateLimitType"`
Utilization *float64 `json:"utilization"`
ResetsAt int64 `json:"resetsAt"`
UnifiedWindows map[string]window `json:"unifiedWindows"`
}
if json.Unmarshal(raw, &info) != nil {
return nil
}
var out []provider.ClaudeLimit
for kind, w := range info.UnifiedWindows {
out = append(out, provider.ClaudeLimit{Kind: kind, Used: w.Utilization, ResetsAt: w.ResetsAt})
}
if _, told := info.UnifiedWindows[info.RateLimitType]; !told && info.RateLimitType != "" {
switch {
case info.Utilization != nil:
out = append(out, provider.ClaudeLimit{Kind: info.RateLimitType, Used: *info.Utilization, ResetsAt: info.ResetsAt})
case info.Status == "rejected":
out = append(out, provider.ClaudeLimit{Kind: info.RateLimitType, Used: 1, ResetsAt: info.ResetsAt})
}
}
return out
}
// carryUpdate keeps this message's known 1h writes when a partial split
// reports only 5m counts, then adds usage from earlier messages.
func (u Usage) carryUpdate(this, before Usage) Usage {
if u.CacheWrite1h == 0 && u.cacheCreationHasCounts {
u.CacheWrite1h = this.CacheWrite1h
}
return u.plus(before, true)
}
func (u Usage) plus(v Usage, only bool) Usage {
if only && u.CacheWrite > 0 && !u.cacheCreationHasCounts && u.CacheWrite1h == 0 {
u.cacheCreationReported = false
}
for _, f := range []struct{ a, b *int }{{&u.Input, &v.Input}, {&u.Output, &v.Output}, {&u.CacheRead, &v.CacheRead}, {&u.Reasoning, &v.Reasoning}} {
if *f.a > 0 || !only {
*f.a += *f.b
}
}
writes := u.CacheWrite > 0
if writes || !only {
u.CacheWrite += v.CacheWrite
}
if u.CacheWrite1h > 0 || u.cacheCreationHasCounts || !only {
u.CacheWrite1h += v.CacheWrite1h
}
if !only {
u.cacheCreationReported = u.cacheCreationReported || v.cacheCreationReported
}
return u
}
func (u cliUsage) gateway() Usage {
out := Usage{Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite, Reasoning: u.OutputDetails.Thinking}
if c := u.CacheCreation; c != nil {
out.cacheCreationReported = true
out.cacheCreationHasCounts = c.Ephemeral5m+c.Ephemeral1h > 0
out.CacheWrite = max(out.CacheWrite, c.Ephemeral5m+c.Ephemeral1h)
out.CacheWrite1h = c.Ephemeral1h
}
return out
}
func renderClaudePrompt(req *Request) ([]map[string]any, error) {
var blocks []map[string]any
var text strings.Builder
// a lean run has them as its system prompt (leanSystem)
if !req.leanPrompt && (req.System != "" || req.ToolChoice == "required" || strings.HasPrefix(req.ToolChoice, "name:") || envNote(req) != "") {
text.WriteString("<external_system_instructions>\n")
system := withoutBillingHeader(req.System)
pos := 0
if c := req.clientCache; c != nil {
cut := len(req.System) - len(system)
for _, mark := range c.system {
end := mark.End - cut
if end <= pos || end > len(system) {
c.droppedSystem++
continue
}
text.WriteString(system[pos:end])
blocks = append(blocks, map[string]any{"type": "text", "text": text.String(), "cache_control": cacheMark(mark.TTL)})
text.Reset()
pos = end
}
}
text.WriteString(system[pos:])
text.WriteString(envNote(req))
text.WriteString(toolChoiceAsk(req))
text.WriteString("\n</external_system_instructions>\n\n")
// The caller's instructions are a block of their own, marked for the
// cache: Claude Code marks only the end of the message, so with them
// in one block with the conversation a request whose messages differ
// (the next item of a batch, a new conversation under the same
// instructions) found nothing cached past Claude Code's own prompt.
// The mark's TTL is the one Claude Code uses (claudeCacheTTL, pinned
// in cleanClaudeEnv): Anthropic refuses a 1h mark after a 5m one.
block := map[string]any{"type": "text", "text": text.String()}
if req.clientCache == nil {
block["cache_control"] = cacheMark1h()
}
blocks = append(blocks, block)
text.Reset()
}
instructions := len(blocks) - 1
chunk := -1
offered := offeredTools(req.Tools)
// A conversation with replies in it is told in two parts: the turns
// already answered, and the one to answer now (from the user message
// after the last reply that calls no tool, as nextTurn splits it). Told
// as one stretch of Human:/Assistant: text, the images of earlier turns
// read as just sent, and the model answered them again (#1365).
split := historyEnd(req.Messages)
// The history is told in chunks, each a block of its own (historyChunk).
// A conversation with no reply that calls no tool, as a sub-agent's
// loop of tool calls (Claude Code's AgentSummary asks a summary of one
// with its last results), has no history: its every message but the
// last is chunked instead, which a later request of the same loop
// repeats. One with a history later is told it wrapped, from its first
// message on, so nothing is lost there either.
chunked := split
if split == 0 {
chunked = len(req.Messages) - 1
}
for i, m := range req.Messages {
if split > 0 && i == 0 {
text.WriteString(historyOpen)
}
if split > 0 && i == split {
text.WriteString(currentTurnOpen(req.Messages, split))
}
label := "Human"
if m.Role == "assistant" {
label = "Assistant"
}
text.WriteString(label + ": ")
blocks = renderCachedParts(blocks, &text, m.Parts, offered, req.clientCache != nil)
text.WriteString("\n\n")
if i+1 <= chunked && (i+1)%historyChunk == 0 {
blocks = append(blocks, map[string]any{"type": "text", "text": text.String()})
text.Reset()
chunk = len(blocks) - 1
}
}
if slices.ContainsFunc(req.Messages, callsTool) {
text.WriteString(pastCallsNote + "\n\n")
}
if split > 0 {
text.WriteString("</current_turn>")
}
// The one mark a run's first message may have (Claude Code keeps three
// of Anthropic's four) moves from the instructions to the history's
// last whole chunk, which holds them too: a later run started anew for
// the same conversation, as after a change of tools or a turn that
// missed its run, reads the history this one wrote, found within
// Anthropic's 20-block lookback, instead of writing all of it again.
// The turn to answer is never chunked when there is a history: a later
// run whose history ends further on tells those messages in it.
if c := req.clientCache; c != nil {
c.fresh = true
if chunk >= 0 && c.count < 4 && blocks[chunk]["cache_control"] == nil {
ttl := "1h"
for _, b := range blocks[:chunk] {
if cc, ok := b["cache_control"].(map[string]string); ok {
ttl = shorterTTL(ttl, cacheTTL(cc))
}
}
blocks[chunk]["cache_control"] = cacheMark(ttl)
}
} else if chunk >= 0 {
if instructions >= 0 {
delete(blocks[instructions], "cache_control")
}
blocks[chunk]["cache_control"] = cacheMark1h()
}
return closeBlocks(blocks, &text), nil
}
// toolChoiceAsk is the client's tool choice in words, which Claude Code
// takes no flag for.
// envElsewhereNote follows the caller's instructions when they name a
// working directory the run is not in: Claude Code's own prompt then gives
// the gateway's computer (its platform, OS and a temp folder), the caller's
// gives the computer its tools run on, and a model told both spent tool
// calls finding out which is real (vv_nil on X, a Mac client of a Linux
// gateway). Every tool is the caller's, so the caller's is. It names no
// app and no vendor: it goes to the vendor with the prompt.
const envElsewhereNote = "\n\nThe environment these instructions describe (working directory, platform, OS, shell, git status) is the one every tool runs in. Where an environment given before them differs, go by these instructions; nothing has changed and there is no need to check."
// envElsewhereLeanNote is envElsewhereNote for a lean run, whose
// instructions are its system prompt: Claude Code gives its environment
// after them, in the run's first message, not before.
const envElsewhereLeanNote = "\n\nThe environment these instructions describe (working directory, platform, OS, shell, git status) is the one every tool runs in. Where an environment given elsewhere in this conversation differs, go by these instructions; nothing has changed and there is no need to check."
// envUnknownNote follows the caller's instructions when the caller is on
// another computer and names no folder: Claude Code's environment (its
// platform, OS, shell and folder) is the gateway's, which no tool runs
// on, and a model told only that one wrapped the caller's commands in the
// gateway's shell. It names no app and no vendor.
const envUnknownNote = "\n\nThe environment given elsewhere in this conversation (its working directory, platform, OS and shell) is not the one the tools run on: don't take a platform, shell or path for a tool call from it."
// envNote is what a run is told after the caller's instructions of where
// its tools run: "" for a run in the caller's own folder, or for a caller
// on this computer that names none.
func envNote(req *Request) string {
switch {
case req.envElsewhere && req.leanPrompt:
return envElsewhereLeanNote
case req.envElsewhere:
return envElsewhereNote
case req.envUnknown:
return envUnknownNote
}
return ""
}
func toolChoiceAsk(req *Request) string {
switch {
case req.ToolChoice == "required":
return "\nYou must call at least one available tool before answering."
case strings.HasPrefix(req.ToolChoice, "name:"):
return fmt.Sprintf("\nYou must call the %s tool.", bridgeName(strings.TrimPrefix(req.ToolChoice, "name:")))
}
return ""
}
// leanSystem is a lean run's system prompt (ClaudeLeanPrompt): the
// caller's instructions without the client Claude Code's billing line, as
// renderClaudePrompt tells them to a run that keeps Claude Code's own,
// with where its tools run (envNote) and its tool choice. Claude Code
// still puts its billing line and its
// identity line before it, and marks it for the cache itself.
func leanSystem(req *Request) string {
return strings.TrimSpace(withoutBillingHeader(req.System) + envNote(req) + toolChoiceAsk(req))
}
// historyChunk is how many messages of the history renderClaudePrompt puts
// in a block. Blocks end at the same messages in every run told the same
// conversation, so their text is the same; 20 blocks back from a run's
// mark reach a mark 320 messages earlier.
const historyChunk = 16
// cacheMark1h is the prompt-cache mark on what magpie gives a run: an
// hour's, as Claude Code's own (claudeCacheTTL, pinned in cleanClaudeEnv),
// since Anthropic refuses a 1h mark after a 5m one.
func cacheMark1h() map[string]string {
return map[string]string{"type": "ephemeral", "ttl": "1h"}
}
// historyOpen and historyClose wrap the turns a run started anew is told
// were answered already, before the turn it is to answer (renderClaudePrompt).
const (
historyOpen = "<conversation_history>\nThe conversation so far, each turn of it answered already. " +
"Images and files in it were sent with those earlier messages: none of them is new, and none needs answering again.\n\n"
historyClose = "</conversation_history>\n\n<current_turn>\nThe turn to answer now:\n\n"
)
// currentTurnOpen is historyClose for the turn of msgs from split on. Claude
// Code notes each image of the message it is given ("[Image: source:
// …/images/1.png]", where it keeps them, or the size it showed one at) in a
// note of its own after the message, so after the turn to answer: told
// nothing of them, the model took the history's images for ones sent with
// that turn, said they were attached and opened them again (#1751). Where
// the history has images, the turn says whose the notes are.
func currentTurnOpen(msgs []Message, split int) string {
earlier, now := countImages(msgs[:split]), countImages(msgs[split:])
switch {
case earlier == 0:
return historyClose
case now == 0:
return "</conversation_history>\n\n<current_turn>\nThe turn to answer now. Any \"[Image: …]\" notes after it are about " +
"the images in the conversation history above, not images sent with this turn.\n\n"
}
return "</conversation_history>\n\n<current_turn>\nThe turn to answer now. Any \"[Image: …]\" notes after it are about " +
"the images above in their order: the conversation history's first, then this turn's.\n\n"
}
// countImages is how many images msgs carry, their tool results' among them.
func countImages(msgs []Message) int {
n := 0
for _, m := range msgs {
for _, p := range m.Parts {
if p.Kind == Image {
n++
}
n += len(p.Images)
}
}
return n
}
// historyEnd is where the turn to answer begins in msgs: the message after
// the last reply that calls no tool. 0 when there is no such reply, or
// nothing after it, and the messages are told as one turn.
func historyEnd(msgs []Message) int {
for j := len(msgs) - 1; j >= 0; j-- {
if msgs[j].Role == "assistant" && !callsTool(msgs[j]) {
if j == len(msgs)-1 {
return 0
}
return j + 1
}
}
return 0
}
// bridgeName is the name the run's Claude Code has a tool of the caller's
// under: the MCP helper's (bridgeTools). Its built-ins are off (--tools
// ""), so a call of the bare name is answered by Claude Code itself with
// "Bash is disabled for this session, in subagents as well as here.",
// which the model takes for a fact and gives up (#958).
func bridgeName(name string) string {
return "mcp__magpie__" + bridgeToolName(name)
}
// bridgeToolName is the name the MCP helper offers a tool of the caller's
// under. Claude Code takes an MCP tool's name as [A-Za-z0-9_-] only, with
// mcp__magpie__ before it in at most 64: it made "spawn.agent" its
// spawn_agent, which the client never offered (#2649). A name it would
// change, or one ending as a changed name ends, is told apart by a hash of
// it, the same in every run, so a resumed session and a conversation's
// history name the tool as before; declaredName maps it back.
func bridgeToolName(name string) string {
if bridgeToolNameOK.MatchString(name) && !bridgeToolNameHashed.MatchString(name) {
return name
}
sum := sha256.Sum256([]byte(name))
short := bridgeToolNameBad.ReplaceAllString(name, "_")
if len(short) > 38 {
short = short[:38]
}
return short + "_" + hex.EncodeToString(sum[:6])
}
var (
bridgeToolNameOK = regexp.MustCompile(`^[A-Za-z0-9_-]{1,51}$`)
bridgeToolNameBad = regexp.MustCompile(`[^A-Za-z0-9_-]`)
bridgeToolNameHashed = regexp.MustCompile(`_[0-9a-f]{12}$`)
)
// bridgeNames is the caller's name of each of tools by the name the MCP
// helper offers it under, for those that differ (bridgeToolName).
func bridgeNames(tools []Tool) map[string]string {
names := map[string]string{}
for _, t := range tools {
if b := bridgeToolName(t.Name); b != t.Name {
names[b] = t.Name
}
}
return names
}
// declaredName is the caller's name of the tool the run's agent called
// name, by the names it was offered under (bridgeNames).
func declaredName(names map[string]string, name string) string {
if n, ok := names[name]; ok {
return n
}
return name
}
// offeredTools is the names of the caller's tools, whose past calls a run
// is told under bridgeName: a conversation told in text with hundreds of
// calls of the bare names had the model call those, not the run's.
func offeredTools(tools []Tool) map[string]bool {
offered := make(map[string]bool, len(tools))
for _, t := range tools {
offered[t.Name] = true
}
return offered
}
// withoutBillingHeader is a system prompt without the billing line Claude
// Code puts first in its own (x-anthropic-billing-header: cc_version=…),
// whose last part is a hash of the request's first user message. Its auto
// mode classifier sends its policy, about 35k tokens, with the transcript
// so far as that message: kept, every check's instructions began with
// another line, so none was read from the cache and each check wrote all of
// it again at twice the input price, on the session's model (X, AncientTwo).
// The run's Claude Code sends its own.
func withoutBillingHeader(system string) string {
return billingHeader.ReplaceAllString(system, "")
}
// billingHeader is the line with its fields (cc_version=…; cc_entrypoint=…;
// cch=…;), which the block after follows with no newline between.
var billingHeader = regexp.MustCompile(`^x-anthropic-billing-header:(\s*[A-Za-z_]+=[^;\s]*;)*\s*`)
// renderClaudeTurn is the messages since a reply in a conversation Claude
// Code already has, as it would be told them itself. The user's alone go
// as they are; with the client's own calls among them (nextTurn), each is
// labeled with who said it, as a run started anew is told the conversation
// (renderClaudePrompt).
func renderClaudeTurn(msgs []Message, tools []Tool) []map[string]any {
var blocks []map[string]any
var text strings.Builder
labeled := hasReply(msgs)
offered := offeredTools(tools)
for i, m := range msgs {
if i > 0 {
text.WriteString("\n\n")
}
if labeled {
label := "Human"
if m.Role == "assistant" {
label = "Assistant"
}
text.WriteString(label + ": ")
}
blocks = renderParts(blocks, &text, m.Parts, offered)
}
if slices.ContainsFunc(msgs, callsTool) {
text.WriteString("\n\n" + pastCallsNote)
}
return closeBlocks(blocks, &text)
}
// renderParts writes the parts as text, a call of one of the offered tools
// under the name the run can call it by (bridgeName). A call of a tool the
// caller doesn't offer (its framework's own) keeps its name.
//
// The user's words after a tool result in the same message (Claude Code's
// AgentSummary asks for its label that way) are the user's, not the tool's:
// the result is closed and the words marked as the user's. Run on after the
// tool's last line, the model read them as tool output and went on with the
// task (#1878). Only the message's parts say where the result ends; what the
// tool wrote stays inside it, whatever it says.
func renderParts(blocks []map[string]any, text *strings.Builder, parts []Part, offered map[string]bool) []map[string]any {
return renderCachedParts(blocks, text, parts, offered, false)
}
func renderCachedParts(blocks []map[string]any, text *strings.Builder, parts []Part, offered map[string]bool, cached bool) []map[string]any {
open := "" // the tool result told last, not closed yet
for _, p := range parts {
if open != "" && p.Kind == Text && agentNotice(p.Text) {
// the agent's notice (a hook's output, a token count) closes
// the result but is not the user's (#2060)
fmt.Fprintf(text, "\n[end of tool result id=%s]\n\n", open)
open = ""
}
if open != "" && (p.Kind == Text || p.Kind == File) {
fmt.Fprintf(text, "\n[end of tool result id=%s]\n\n[user message]\n", open)
open = ""
}
switch p.Kind {
case Text:
text.WriteString(p.Text)
case File:
text.WriteString(attachmentText(p))
case Thinking:
text.WriteString(p.Text)
case ToolCall:
name := p.Name
if offered[name] {
name = bridgeName(name)
}
fmt.Fprintf(text, "\n[tool call %s id=%s args=%s]", 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)
open = p.CallID
// the images the tool returned follow its text
for _, im := range p.Images {
blocks = imageBlocks(blocks, text, im)
}
case Image:
blocks = imageBlocks(blocks, text, p)
}
if cached && p.cache != "" {
blocks = closeBlocks(blocks, text)
text.Reset()
blocks[len(blocks)-1]["cache_control"] = cacheMark(p.cache)
}
}
return blocks
}
func imageBlocks(blocks []map[string]any, text *strings.Builder, p Part) []map[string]any {
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.
// An image sent beside the results, as a client whose tool messages hold
// text only sends a tool's (Chat), goes with the result before it.
func (b *subscriptionBridge) findRun(req *Request) (*subscriptionRun, []Part) {
run, fresh, _ := b.match(req)
return run, fresh
}
// The ways a request's tool results find the run they are for, or don't,
// as the gateway's log tells them.
const (
byExactID = "exact id"
byRemap = "remapped"
historyChanged = "history changed"
ambiguousCalls = "ambiguous"
runExpired = "process expired"
noRunWaiting = "no run waiting"
accountChanged = "account changed"
// another request has the run's calls answered, or is answering them
answeredElsewhere = "answered by another request"
)
// match is findRun, and how the results found their run (byExactID,
// byRemap) or why none was found. The results are named by Claude Code's
// ids for the calls, as the run waits on them, when the client named them
// by its own (remap).
func (b *subscriptionBridge) match(req *Request) (*subscriptionRun, []Part, string) {
i := len(req.Messages)
for i > 0 && req.Messages[i-1].Role != "assistant" {
i--
}
var fresh, loose []Part
for _, m := range req.Messages[i:] {
captions := withImages(m)
for _, p := range m.Parts {
switch {
case p.Kind == ToolResult:
p.Images = slices.Clone(p.Images)
fresh = append(fresh, p)
case p.Kind == Text && len(fresh) > 0 && captions:
// the words of a message of the results' images, which go
// with the result before them: pi-ai's "Attached image(s)
// from tool result:" over Chat. The user's own words, in a
// message with no images, are not the tool's: continueWith
// tells them as a message of the user's (saidWithResults,
// #872, #1878).
last := &fresh[len(fresh)-1]
if last.Text != "" && p.Text != "" {
last.Text += "\n\n"
}
last.Text += p.Text
case p.Kind == Image && len(fresh) > 0:
last := &fresh[len(fresh)-1]
last.Images = append(last.Images, p)
case p.Kind == Image:
loose = append(loose, p)
}
}
}
if len(fresh) == 0 {
return nil, nil, ""
}
fresh[0].Images = append(loose, fresh[0].Images...)
// the calls the results answer: those of the assistant's last turn
var calls []Part
k := i
for k > 0 && req.Messages[k-1].Role == "assistant" {
k--
}
for _, m := range req.Messages[k:i] {
for _, p := range m.Parts {
if p.Kind == ToolCall {
calls = append(calls, p)
}
}
}
var before map[string]bool // the conversation as it stood after each message
why := noRunWaiting
// 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, byExactID
}
if before == nil {
before = map[string]bool{}
h := sha256.New()
hashMessages(h, req.Messages, func(int) { before[hex.EncodeToString(h.Sum(nil))] = true })
}
run, named, w := b.remap(req.Model, calls, fresh, before)
if run != nil {
return run, named, byRemap
}
why = w
time.Sleep(25 * time.Millisecond)
}
return nil, nil, why
}
// remap finds the run a client's results are for when the client named the
// calls by ids of its own, the same in every request after (AmpCode
// rewrites each tool_use id, and the tool_use_id of its result, to a TU-…
// of its own), so none is an id the run's agent waits on. The run is the
// one waiting on its reply's calls whose conversation the request goes on
// from (before, the request's conversation after each of its messages:
// the run's last is one of them), and whose calls were the client's last
// turn's, one for one in the same order, each the same tool with the same
// arguments. Only one may be: two conversations that are the same so far,
// down to their calls, would have their results told to either, and a new
// run is started instead. The results are returned named by the run's ids.
func (b *subscriptionBridge) remap(model string, calls, fresh []Part, before map[string]bool) (*subscriptionRun, []Part, string) {
if len(calls) == 0 {
return nil, nil, noRunWaiting
}
theirs := map[string]int{} // the client's id for a call → its place
for n, c := range calls {
if _, twice := theirs[c.ID]; twice || c.ID == "" {
return nil, nil, noRunWaiting
}
theirs[c.ID] = n
}
for _, p := range fresh {
if _, ok := theirs[p.CallID]; !ok {
return nil, nil, noRunWaiting
}
}
b.mu.Lock()
runs := make([]*subscriptionRun, 0, len(b.runs))
for _, run := range b.runs {
runs = append(runs, run)
}
b.mu.Unlock()
why := noRunWaiting
var found *subscriptionRun
var ids []string // the run's id for each of calls
for _, run := range runs {
run.mu.Lock()
shown, told := slices.Clone(run.shown), run.told
waiting := !run.closed && !run.parkedAt.IsZero() && (run.model == "" || model == "" || run.model == model)
run.mu.Unlock()
if !waiting || len(shown) != len(calls) {
continue
}
same := true
for n, c := range calls {
same = same && shown[n].name == c.Name && sameArgs(shown[n].args, argsOf(c))
}
if !same {
continue
}
if told == "" || !before[told] {
// the same calls, from a conversation this one doesn't go on
// from: compacted or edited since, or another one
why = historyChanged
continue
}
if found != nil {
return nil, nil, ambiguousCalls
}
found, ids = run, make([]string, len(shown))
for n, c := range shown {
ids[n] = c.id
}
}
if found == nil {
return nil, nil, why
}
named := slices.Clone(fresh)
waits := false // the run's agent is waiting on one of them
b.mu.Lock()
for n := range named {
named[n].CallID = ids[theirs[named[n].CallID]]
waits = waits || b.calls[named[n].CallID] == found
}
b.mu.Unlock()
if !waits {
// its agent hasn't made its first call yet, or was answered
// already (a request sent again)
return nil, nil, noRunWaiting
}
return found, named, ""
}
// sameArgs says a call's arguments as the client was told them, a and as
// it sends them back, b, are the same object, whatever their spacing and
// the order of their keys.
func sameArgs(a string, b json.RawMessage) bool {
if strings.TrimSpace(a) == "" {
a = "{}"
}
var x, y any
if json.Unmarshal([]byte(a), &x) != nil || json.Unmarshal(b, &y) != nil {
return strings.TrimSpace(a) == strings.TrimSpace(string(b))
}
return reflect.DeepEqual(x, y)
}
// offers says the run's agent was told every one of tools.
func (r *subscriptionRun) offers(tools []Tool) bool {
r.mu.Lock()
defer r.mu.Unlock()
if r.tools == nil {
return true
}
for _, t := range tools {
if !r.tools[t.Name] {
return false
}
}
return true
}
// untold is how many of tools the run's agent was never told of, and
// their names, the first five and a count of the rest, for the log
// (whyNoRun).
func (r *subscriptionRun) untold(tools []Tool) (int, string) {
r.mu.Lock()
defer r.mu.Unlock()
if r.tools == nil {
return 0, ""
}
var names []string
for _, t := range tools {
if !r.tools[t.Name] {
names = append(names, t.Name)
}
}
n := len(names)
if n > 5 {
names = append(names[:5], fmt.Sprintf("%d more", n-5))
}
return n, strings.Join(names, ", ")
}
// saidWithResults is the user's words after tool results in the messages
// since the last reply: a message the user sent while a tool ran (#872),
// or what a request forked from the conversation asks (Claude Code's
// AgentSummary, #1878). The words of a message with images go with the
// results (match), as before. "" when there are no results, or no words.
//
// What the client's agent put in beside the results is not the user's
// (#2060): Claude Code's hooks' notices ("PreToolUse:Read hook additional
// context: …"), its <total_tokens> count, its other notices (agentNotice).
// Told to the run as the user's, the model was told after nearly every
// call that the user had sent a message, of a hook's output or of nothing
// (the run's Claude Code doesn't show a bare <total_tokens>). Claude Code
// 2.1.296 sends them as one {role: "system"} message after the results,
// with a message the user sent mid-turn among them (midTurnSaid): only
// those words are the user's. A system message is never the user's
// otherwise.
func saidWithResults(msgs []Message) string {
i := len(msgs)
for i > 0 && msgs[i-1].Role != "assistant" {
i--
}
var said []string
results := false
for _, m := range msgs[i:] {
captions := withImages(m)
for _, p := range m.Parts {
// a background task's notification goes with the results
// (withTaskNotices), not as the user's
text := p.Text
if p.Kind == Text && results && !captions {
text = taskNotice.ReplaceAllString(text, "")
}
switch {
case p.Kind == ToolResult:
results = true
case p.Kind != Text || !results || captions:
case midTurnHead.MatchString(text):
said = append(said, midTurnSaid(text)...)
case m.Role == "system" || m.Role == "developer":
case text != p.Text && agentNotice(text):
case !agentNotice(text):
said = append(said, text)
}
}
}
if !results {
return ""
}
return strings.Join(said, "\n\n")
}
// taskNotice is Claude Code's notification that a background task (a
// sub-agent, a background command) ended, with the header it puts before
// it: "[SYSTEM NOTIFICATION - NOT USER INPUT]" … <task-notification>…
// </task-notification>.
var taskNotice = regexp.MustCompile(`(?s)(?:\[SYSTEM NOTIFICATION - NOT USER INPUT\][^<]*)?<task-notification>.*?</task-notification>`)
// withTaskNotices hands the run the notifications of background tasks
// that came after the results (taskNotice), in a reminder at the end of the
// last result, where Claude Code itself puts one for some models (inside
// the tool_result's text). Claude Code 2.1.310 on Opus sends one that
// arrives mid-turn as a {role: "system"} message after the results, and
// before as a text block of the results' message; both were left out of
// what the run was handed (#2060's rule for hooks' notices), so the run's
// model never heard that a sub-agent it started in the background had
// finished, nor its result, and waited for it (stones_2026 on Discord).
func withTaskNotices(results []Part, msgs []Message) []Part {
if len(results) == 0 {
return results
}
i := len(msgs)
for i > 0 && msgs[i-1].Role != "assistant" {
i--
}
var notices []string
seen := false
for _, m := range msgs[i:] {
if withImages(m) {
continue
}
for _, p := range m.Parts {
switch {
case p.Kind == ToolResult:
seen = true
case p.Kind == Text && seen:
notices = append(notices, taskNotice.FindAllString(p.Text, -1)...)
}
}
}
if len(notices) == 0 {
return results
}
out := slices.Clone(results)
last := &out[len(out)-1]
if last.Text != "" {
last.Text += "\n\n"
}
last.Text += "<system-reminder>\n" + strings.Join(notices, "\n\n") + "\n</system-reminder>"
return out
}
var (
// midTurnHead heads a message the user sent while a tool ran, as
// Claude Code tells its model one: "The user sent a new message while
// you were working:" (2.1.296), "The user sent the following message:"
// (older).
midTurnHead = regexp.MustCompile(`The user sent (?:a new message while you were working|the following message):[ \t]*\n`)
// midTurnEnd is where the user's words after midTurnHead end: Claude
// Code's ask to address them, the reminder's end, or a notice of its
// own after them.
midTurnEnd = regexp.MustCompile(`\n\n(?:This is how Claude Code surfaces messages the user sends mid-turn|IMPORTANT: After completing your current task, you MUST address the user's message above|Please address this message and continue with your tasks)|</system-reminder>|\n\n<total_tokens>|\n\n` + hookNoticeLead)
// hookNotice is a Claude Code hook's output told to the model:
// "PreToolUse:Read hook additional context: …", "SessionStart hook
// success: …", "Stop hook blocking error from command: …". Only
// these kinds: "Stop hook is broken: …" may be the user's.
hookNoticeLead = `[A-Z][A-Za-z]+(?::\S+)? hook (?:additional context|success|blocking error(?: from command)?|stopped continuation|feedback):`
hookNotice = regexp.MustCompile(`^` + hookNoticeLead)
// tokenCount is Claude Code's count of the tokens left, or used.
tokenCount = regexp.MustCompile(`^(?:<total_tokens>[^<]*</total_tokens>|Token usage: \S+; \S+ remaining)$`)
// reminderTag is a <system-reminder> tag, open or close.
reminderTag = regexp.MustCompile(`</?system-reminder(?:\s[^>]*)?>`)
)
// midTurnSaid is the user's words in each message they sent mid-turn
// that text tells, without what Claude Code tells its model around them.
func midTurnSaid(text string) []string {
var said []string
at := midTurnHead.FindAllStringIndex(text, -1)
for k, h := range at {
rest := text[h[1]:]
if k+1 < len(at) {
rest = text[h[1]:at[k+1][0]]
}
if e := midTurnEnd.FindStringIndex(rest); e != nil {
rest = rest[:e[0]]
}
if w := strings.TrimSpace(rest); w != "" {
said = append(said, w)
}
}
return said
}
// agentNotice says a text after tool results is the agent's, not words
// of the user's: empty within its reminder tags, or a hook's notice, a
// token count, or a notice userWords knows (injected).
func agentNotice(text string) bool {
t := strings.TrimSpace(reminderTag.ReplaceAllString(text, ""))
if t == "" || hookNotice.MatchString(t) || tokenCount.MatchString(t) {
return true
}
for _, lead := range injected {
if strings.HasPrefix(t, lead) {
return true
}
}
return false
}
// withImages says m has an image of its own, not in a tool result.
func withImages(m Message) bool {
return slices.ContainsFunc(m.Parts, func(p Part) bool { return p.Kind == Image })
}
// queuedWait is how long continueWith waits for Claude Code to say it
// queued the user's words before it hands over the results. One that never
// says (a version without command_lifecycle) still has them on its input,
// read before the results it is about to get.
var queuedWait = 2 * time.Second
// continueWith hands the agent its tool results: at once for the calls it
// is waiting on, the others kept until it makes them. tools, when set, are
// the agent's tools from now on, handed over with the results.
//
// said, the user's words sent with the results (saidWithResults), is
// written to Claude Code's input first, as a user message, and the results
// handed over once Claude Code has queued it. Claude Code tells a message
// that comes while a tool runs with that tool's result, marked as one the
// user sent ("The user sent a new message while you were working"), in the
// turn it is in. Handed over as part of the MCP result, the words were the
// tool's output to the model, which went on with the task instead of
// doing what they asked (#1878).
func (r *subscriptionRun) continueWith(results []Part, said string, tools []bridgeTool) (<-chan Event, error) {
if r.timer != nil {
r.endIn(runTimeout)
}
if said != "" {
if err := r.queue(said); err != nil {
return nil, err
}
}
r.mu.Lock()
r.parkedAt = time.Time{}
r.mu.Unlock()
ch := r.attach()
if r.begin != nil {
r.emit(r.begin())
}
delivered := 0
for _, p := range results {
result := mcpResult(p)
result.Tools = tools
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))
}
r.mu.Lock()
r.results = r.results[:0]
for _, p := range results {
r.results = append(r.results, p.CallID)
}
r.mu.Unlock()
if r.resume != nil {
r.resume()
}
return ch, nil
}
// queue writes said to Claude Code's input as a user message and waits,
// at most queuedWait, for Claude Code to say it queued it.
func (r *subscriptionRun) queue(said string) error {
id := newUUID()
got := make(chan struct{})
r.mu.Lock()
if r.queued == nil {
r.queued = map[string]chan struct{}{}
}
r.queued[id] = got
exited := r.exited
r.mu.Unlock()
defer func() {
r.mu.Lock()
delete(r.queued, id)
r.mu.Unlock()
}()
line, _ := json.Marshal(map[string]any{"type": "user", "uuid": id, "message": map[string]any{"role": "user", "content": []map[string]any{{"type": "text", "text": said}}}})
if err := r.tell(line); err != nil {
return err
}
select {
case <-got:
case <-exited: // nil before launch: never
case <-time.After(queuedWait):
log.Printf("claude: Claude Code didn't say it queued the user's words sent with tool results in %s; the results go on", queuedWait)
}
return nil
}
// mcpResult is a tool result as an MCP tools/call answers: its text, then
// the images the tool returned as MCP image content, which Claude Code hands
// its model as image blocks. MCP carries an image's bytes only, so one known
// by its URL alone is named in text.
func mcpResult(p Part) mcpToolResult {
content := []map[string]any{{"type": "text", "text": p.Text}}
for _, im := range p.Images {
switch {
case im.Data != "":
content = append(content, map[string]any{"type": "image", "data": im.Data, "mimeType": imageMediaType(im)})
case im.URL != "":
content = append(content, map[string]any{"type": "text", "text": "[image: " + im.URL + "]"})
}
}
return mcpToolResult{Content: content, IsError: p.IsError}
}
// imageMediaType is an inline image's type, read from its bytes when the
// client did not say.
func imageMediaType(p Part) string {
if p.MediaType != "" {
return p.MediaType
}
head := p.Data[:min(len(p.Data), 64)]
b, _ := base64.StdEncoding.DecodeString(head[:len(head)/4*4])
return http.DetectContentType(b)
}
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 {
// a run of the magpie this one took the gateway over from, its
// turn under way when the gateway changed hands (handover.go)
if forwardCallback(w, r) {
return
}
http.Error(w, "unknown or expired Claude run", http.StatusNotFound)
return
}
body, status, err := readBoundedRequestBody(w, r, requestLimits{body: 16 << 20})
if err != nil {
http.Error(w, err.Error(), status)
return
}
var call struct {
ToolCallID string `json:"tool_call_id"`
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
}
if json.Unmarshal(body, &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()
call.Name = declaredName(run.names, call.Name)
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
r.resuming = false
if r.timer != nil {
r.timer.Stop()
}
pending := r.pending
r.pending = map[string]chan mcpToolResult{}
controls := r.controls
r.controls = nil
ch := r.segment
r.segment = nil
r.mu.Unlock()
for _, waiter := range pending {
close(waiter)
}
for _, waiter := range controls {
close(waiter)
}
if ch != nil {
r.closeSegment(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
}
exited := make(chan struct{})
r.mu.Lock()
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)
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)
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
r.mu.Lock()
r.exit = err
close(exited)
room, left := r.room, r.roomLeft
r.room = nil
r.mu.Unlock()
if room != nil {
room(left)
}
if err := r.schemaEnded(); err != nil {
r.emit(Event{Kind: KError, Text: err.Error(), Status: http.StatusBadRequest})
}
r.finish()
}()
return nil
}
// tell writes line to Claude Code's input. Wait closes that input as
// Claude Code exits, and a write after it failed "write |1: file already
// closed", which said nothing of why: one Claude Code no longer reads says
// how it ended, or that magpie ended it, and the last it wrote to stderr —
// the cause comes last, after any warnings before it.
func (r *subscriptionRun) tell(line []byte) error {
// one magpie ended is not written to: until Wait has reaped it, its
// input still takes a write, which no one will read
r.mu.Lock()
killed := r.killed
r.mu.Unlock()
if killed {
return r.whyEnded()
}
_, err := r.stdin.Write(append(line, '\n'))
if err == nil {
return nil
}
r.mu.Lock()
exited := r.exited
r.mu.Unlock()
if exited == nil {
return err
}
select {
case <-exited:
case <-time.After(outputDrain + time.Second):
return err
}
return r.whyEnded()
}
// whyEnded says how the run's Claude Code ended, or that magpie ended it,
// and the last it wrote to stderr.
func (r *subscriptionRun) whyEnded() error {
return r.endedBefore("read its input")
}
// endedBefore is whyEnded for a run that ended before it did what: its
// exit status (once Wait has it) and its stderr's tail.
func (r *subscriptionRun) endedBefore(what string) error {
r.mu.Lock()
defer r.mu.Unlock()
why := "exited before it " + what
if r.killed {
why = "was ended by magpie before it " + what
} else if r.exit != nil {
why += " (" + r.exit.Error() + ")"
}
said := strings.TrimSpace(r.stderr.String())
if at := cliSchemaWords.FindStringIndex(said); at != nil {
// its words from the flag on, which a long list of Ajv's
// errors after them would push out of the tail
said = said[at[0]:]
if len(said) > 300 {
said = strings.ToValidUTF8(said[:300], "") + "…"
}
return &cliSchemaRefused{why + ": " + said}
}
if said != "" {
why += ": " + clipTail(said, 300)
}
return errors.New(why)
}
// schemaEnded is the error of a run whose Claude Code took its input and
// then ended over its --json-schema, nil for any other end: it checks the
// schema while it starts, and its input may be taken before it gets to
// it, so the turn told it heard no answer, and was "ended without an
// answer", a 502 asked again.
func (r *subscriptionRun) schemaEnded() error {
r.mu.Lock()
killed, said := r.killed, r.stderr.String()
r.mu.Unlock()
if killed || !cliSchemaWords.MatchString(said) {
return nil
}
return r.endedBefore("answered")
}
// cliSchema is a schema as Claude Code's --json-schema takes it: without
// its root $schema. Claude Code checks the schema with Ajv's default
// class, which knows draft-07's meta-schema alone, and exits "no schema
// with key or ref" over any other a schema names, as Codex's titles name
// draft 2020-12 (zod's toJSONSchema), before it reads its input (#3036).
// Without it the schema is read as draft-07. The rest is kept as written:
// $id, $defs and a $schema below the root pass Ajv as they are.
func cliSchema(raw json.RawMessage) json.RawMessage {
var root map[string]json.RawMessage
if json.Unmarshal(raw, &root) != nil {
return raw
}
if _, ok := root["$schema"]; !ok {
return raw
}
delete(root, "$schema")
out, err := json.Marshal(root)
if err != nil {
return raw
}
return out
}
// cliSchemaWords are how Claude Code exits over the --json-schema it was
// given, before it reads its input: not JSON, not an object, or a schema
// its Ajv won't compile ("strict mode: unknown keyword" for one only a
// later draft has).
var cliSchemaWords = regexp.MustCompile(`--json-schema (is not a valid JSON Schema|is not valid JSON|must be a JSON object)`)
// cliSchemaRefused is a run's Claude Code ending over the request's schema:
// it ends the same for the same schema on every account and every try,
// so it is the request's 400, neither asked again nor of the next
// account, and no account rests for it (#3036: asked three times).
type cliSchemaRefused struct{ msg string }
func (e *cliSchemaRefused) Error() string { return e.msg }
// clipTail is s's last n bytes at most, cut at a rune, "…" before them
// where some went.
func clipTail(s string, n int) string {
if len(s) <= n {
return s
}
i := len(s) - n
for i < len(s) && !utf8.RuneStart(s[i]) {
i++
}
return "…" + s[i:]
}
// outputDrain is how long the run's output is read once Claude Code has
// exited and its group been ended: a process that left the group may
// still hold the pipes, and is not waited for longer.
var outputDrain = 2 * time.Second
// drain waits for what Claude Code wrote to be read, so its last lines
// reach the client before the run ends, then closes its pipes.
func (r *subscriptionRun) drain() {
read := make(chan struct{})
go func() {
r.reading.Wait()
close(read)
}()
select {
case <-read:
case <-time.After(outputDrain):
}
for _, f := range r.outputs {
_ = f.Close()
}
}
// stopGrace is how long Claude Code is given to clean up after it is asked
// to end, before its tree is killed: it removes an OAuth refresh lock it
// holds as it exits, which a SIGKILL left for the next requests to wait on
// (#2195). Claude Code 2.1.299 exits within half a second of SIGTERM.
const stopGrace = 5 * time.Second
// abort ends the run: Claude Code is asked to end (proc.Tree.Stop) and its
// tree killed if it hasn't within stopGrace. The run counts as ended at
// once. The channel closes once the tree is.
func (r *subscriptionRun) abort() <-chan struct{} {
r.mu.Lock()
t := r.tree
if t != nil && r.exited != nil {
select {
case <-r.exited:
default:
if !r.killed && r.room != nil {
// asks waiting for room count it as ending
r.roomLeft = true
claudeRoom.leave()
}
r.killed = true
}
}
r.mu.Unlock()
var stopped <-chan struct{} = closedChan
if t != nil {
stopped = t.Stop(stopGrace)
}
r.finish()
return stopped
}
var closedChan = func() chan struct{} { c := make(chan struct{}); close(c); return c }()
// abortFor is abort, why kept for the log of a turn that finds the run
// gone (whyNoRun); the first reason given is the one kept.
func (r *subscriptionRun) abortFor(why string) {
r.mu.Lock()
if r.endWhy == "" && !r.closed {
r.endWhy = why
}
r.mu.Unlock()
r.abort()
}
// 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()
// each asked at once, then waited for: a Claude Code magpie exits
// under is not left to be killed by no one
stops := make([]<-chan struct{}, 0, len(runs))
for _, run := range runs {
stops = append(stops, run.abort())
}
for _, s := range stops {
<-s
}
}
// lostRun is a run that had a conversation and ended: when, and why.
type lostRun struct {
at time.Time
why string
}
// lostMost is how many ended runs' reasons are kept for the log, by
// conversation and by tool call.
const lostMost = 64
// keepLost keeps l in m under key, the oldest let go past most (b.mu held).
func keepLost(m map[string]lostRun, key string, l lostRun, most int) {
for len(m) >= most {
oldest := ""
for k, o := range m {
if oldest == "" || o.at.Before(m[oldest].at) {
oldest = k
}
}
delete(m, oldest)
}
m[key] = l
}
// whyLost is why the run ended, for the log of its conversation's next
// turn: the reason magpie gave (abortFor), or how its Claude Code exited.
func (r *subscriptionRun) whyLost() string {
r.mu.Lock()
why, killed, exit := r.endWhy, r.killed, r.exit
r.mu.Unlock()
switch {
case why != "":
return why
case killed:
return "magpie ended it"
case exit != nil:
return "its Claude Code exited (" + exit.Error() + ")"
}
return "its Claude Code exited"
}
func (b *subscriptionBridge) removeRun(run *subscriptionRun) {
dropCallback(run.token)
why := run.whyLost()
run.mu.Lock()
results := slices.Clone(run.results)
run.mu.Unlock()
lost := lostRun{at: time.Now(), why: why}
b.mu.Lock()
if b.lost == nil {
b.lost, b.lostCalls = map[string]lostRun{}, map[string]lostRun{}
}
if run.convKey != "" {
keepLost(b.lost, run.convKey, lost, lostMost)
}
for _, id := range results {
keepLost(b.lostCalls, id, lost, 4*lostMost)
}
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)
keepLost(b.lostCalls, id, lost, 4*lostMost)
}
}
b.mu.Unlock()
_ = os.RemoveAll(run.tmp)
run.mu.Lock()
sid, sessions, shelved := run.sessionID, run.sessions, run.shelved
run.mu.Unlock()
if !shelved {
removeSession(sessions, sid)
}
}
// owned is the account the run runs as (serveClaudeSubscription's owner).
func (r *subscriptionRun) owned() string {
if o := r.owner.Load(); o != nil {
return *o
}
return ""
}
// takeNamedOwner has a run started on Claude Code's own sign-in while it
// was known by no name (unnamedOwner) go on as owner, that sign-in named
// since: a run in Claude Code's own home runs as whatever it is signed in
// to, as a new run there would. It says whether the run took it.
func (r *subscriptionRun) takeNamedOwner(owner string) bool {
o := r.owner.Load()
if o == nil {
return false
}
w, n := strings.Split(*o, "\x00"), strings.Split(owner, "\x00")
if len(w) != 4 || w[2] != ownHome || w[3] != unnamedOwner || len(n) < 3 || n[0] != w[0] || n[2] != ownHome {
return false
}
if !r.owner.CompareAndSwap(o, &owner) {
return false
}
log.Printf("claude: the run on Claude Code's own sign-in, %q until it was named, goes on as %q", w[1], n[1])
return true
}
// nameOwner has a run begun on Claude Code's own sign-in while it had no
// name take the name that sign-in has now, when it has one: the turn the
// run waits for comes by it (takeNamedOwner).
func (r *subscriptionRun) nameOwner() {
o := r.owner.Load()
if o == nil {
return
}
f := strings.Split(*o, "\x00")
if len(f) != 4 || f[2] != ownHome || f[3] != unnamedOwner {
return
}
if user, ok := claudeOwnName(); ok {
r.takeNamedOwner(f[0] + "\x00" + user + "\x00" + ownHome)
}
}
// claudeOwnName is provider.ClaudeOwnName; tests name the sign-in.
var claudeOwnName = provider.ClaudeOwnName
// unnamedOwner marks a run's owner as Claude Code's own sign-in while it
// is known by no name (provider's Account.Unnamed): the name in the owner
// is made from its plan, and the next turn may come named by its email.
const unnamedOwner = "unnamed"
// ownHome marks a run's owner as Claude Code's own sign-in, run in its
// own home.
const ownHome = "own"
// ownerAccount is the account a run's owner names, "" when it names none,
// and whether it is Claude Code's own sign-in (ownHome).
func ownerAccount(owner string) (user string, own bool) {
f := strings.Split(owner, "\x00")
if len(f) < 2 {
return "", false
}
return f[1], len(f) > 2 && f[2] == ownHome
}
// whyNoRun says why a turn that goes on from a reply found no run waiting
// for it, "" when it isn't such a turn, for the log line before a new run
// is told the whole conversation (#1638): a run of the conversation waits
// under another key or at an earlier turn, or is busy, or it ended and
// why, or none had it.
//
// A run whose conversation the client sent back rewritten (Alma, #912)
// and whose Claude Code wasn't told a tool the client offers now is named
// by those tools (#2375): its conversation is no longer the one the run
// had, so none of the conversation's keys is the run's, and the line said
// no run had ever had it.
func (b *subscriptionBridge) whyNoRun(req *Request, owner string) string {
key, _ := nextTurn(req, owner)
if key == "" {
return ""
}
keys := conversationKeys(owner, req.Messages)
b.mu.Lock()
defer b.mu.Unlock()
if r, _ := b.rewritten(req, owner); r != nil {
if n, names := r.untold(req.Tools); n > 0 {
return fmt.Sprintf("its run waits under another key: the client offers %d tool(s) its Claude Code wasn't told of (%s), and a run is told its tools when it starts", n, names)
}
}
for _, r := range b.idle {
if r.behindKey == key {
return "its run went on with a turn this one doesn't follow, and wasn't taken back"
}
if r.owned() != owner || r.convKey == "" || !slices.Contains(keys, r.convKey) {
continue
}
if r.convKey == keys[len(keys)-1] {
return "its run waits under another key: the model, settings, system prompt or tools differ from the turn before"
}
return "its run waits at an earlier turn of the conversation"
}
for _, r := range b.runs {
if r.owned() == owner && r.idleKey == "" && r.convKey != "" && slices.Contains(keys, r.convKey) {
return "its run is busy with another request"
}
}
for i := len(keys) - 1; i >= 0; i-- {
if l, ok := b.lost[keys[i]]; ok {
return "its run ended " + time.Since(l.at).Round(time.Second).String() + " ago: " + l.why
}
}
return "no run here has had this conversation"
}
// whyCallsLost says what became of the run that made the calls whose
// results a request sends, when it ended: "" when none is known to have.
func (b *subscriptionBridge) whyCallsLost(req *Request) string {
i := len(req.Messages)
for i > 0 && req.Messages[i-1].Role != "assistant" {
i--
}
b.mu.Lock()
defer b.mu.Unlock()
for _, m := range req.Messages[i:] {
for _, p := range m.Parts {
if l, ok := b.lostCalls[p.CallID]; ok && p.Kind == ToolResult {
return "the run that made the calls ended " + time.Since(l.at).Round(time.Second).String() + " ago: " + l.why
}
}
}
return ""
}
func (s *Server) serveClaudeSubscription(w http.ResponseWriter, r *http.Request, from provider.Protocol, p provider.Provider, model string, body []byte, usage *Usage) (int, string) {
defer s.bridgeTurn()()
owner := p.ID
if p.Account != nil {
owner += "\x00" + p.Account.User
if p.Account.AgentsOwn() {
// A process in the agent's home reads that home's current sign-in.
// A saved account must not resume it after the sign-in moves.
owner += "\x00" + ownHome
if p.Account.Unnamed() {
owner += "\x00" + unnamedOwner
}
}
}
start := func(ctx context.Context, req *Request) (*subscriptionRun, <-chan Event, error) {
ctx = p.Via(ctx) // the account's own proxy, its CLI run's too
if run, events := s.subscription.resume(req, owner); run != nil {
return run, events, nil
}
// a run let go past idleMost left its session for this turn
from := s.subscription.unshelve(req, owner)
if from == nil {
if why := s.subscription.whyNoRun(req, owner); why != "" {
log.Printf("claude: no run waits for this turn: %s", why)
}
}
s.subscription.retire(owner, req.Messages)
if req.Effort == "" && autoModeClassifier(req) {
// Claude Code's auto mode classifier asks a verdict of a few
// words within a minute; a Claude Code run at its default
// effort can think past that (#250)
req.Effort = "low"
}
req.clientCache.selected(from == nil)
dir, _, err := p.Account.Token(ctx)
if err != nil {
if from != nil {
from.discard()
}
return nil, nil, err
}
return s.subscription.start(ctx, req, model, dir, owner, from)
}
return s.serveSubscription(w, r, from, "Claude Code", model, owner, body, usage, start)
}
// limitHeaders says on a reply what is kept of the allowance of the account
// a run's owner names, as Anthropic says it to Claude Code: its
// anthropic-ratelimit-unified-* headers, which a Claude Code signed in to
// claude.ai reads into its status line's rate_limits (claude-hud's 5-hour
// and weekly figures, #1257). Its run tells them in its rate_limit_event,
// not as headers, so they are said again from what magpie keeps.
func limitHeaders(w http.ResponseWriter, owner string) {
user, own := ownerAccount(owner)
if user == "" || own && provider.ClaudeCodeMovedOff(user) {
return
}
set := func(k, v string) {
if hw, ok := w.(*holdWriter); ok {
hw.note(k, v) // keepAlive may send the headers before the reply has them
} else {
w.Header().Set(k, v)
}
}
for _, l := range provider.KeptClaudeLimits(user) {
if win, ok := ratelimitWindows[l.Kind]; ok {
set("anthropic-ratelimit-unified-"+win+"-utilization", strconv.FormatFloat(l.Used, 'f', -1, 64))
set("anthropic-ratelimit-unified-"+win+"-reset", strconv.FormatInt(l.ResetsAt, 10))
}
}
}
// ratelimitWindows are the windows Claude Code reads from
// anthropic-ratelimit-unified-<window>-*, by the kind it names them in its
// rate_limit_event.
var ratelimitWindows = map[string]string{
"five_hour": "5h",
"seven_day": "7d",
"seven_day_overage_included": "7d_oi",
}
// 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, owner string, body []byte, usage *Usage,
start func(ctx context.Context, req *Request) (*subscriptionRun, <-chan Event, error)) (int, string) {
var req *Request
var err error
if name == "Claude Code" && wantsClientCache(r, from) {
req, err = parseAnthropicRequest(body, true)
} else {
req, err = parse(from, body)
}
if err != nil {
return writeError(w, from, 400, err.Error()), err.Error()
}
req.Model = model
if req.clientCache != nil {
req.clientCache.report = func() { cacheReportReady(w, req) }
}
// a client that places its own cache marks keeps Claude Code's prompt:
// its system marks are placed in the run's first message (#1717)
req.leanPrompt = name == "Claude Code" && req.clientCache == nil && settings.Load().ClaudeLeanPrompt
// the tools of a caller on another computer run there, not where
// Claude Code runs (envUnknownNote)
req.remoteCaller = !local(r)
if req.Format != nil && req.Format.schema() == nil {
// --json-schema takes a schema only: any JSON object is asked for
// in words
req = req.inSystem()
}
if len(req.Safeguards) > 0 {
req.SafeguardBeta = "dangerous-tool-use-2026-09-03"
for _, beta := range strings.Split(r.Header.Get("anthropic-beta"), ",") {
if beta = strings.TrimSpace(beta); strings.HasPrefix(beta, "dangerous-tool-use-") {
req.SafeguardBeta = beta
break
}
}
}
// its model searches the web with magpie's tool, which magpie answers
var search Tool
if req.WebSearch && !searching(r.Context()) {
if canSearch() {
search = searchTool(req.Tools)
req.Tools = append(slices.Clone(req.Tools), search)
}
}
run, results, how := s.subscription.match(req)
// Another request has the run's calls answered, or is answering them,
// or the run ended. Claude Code's fork sub-agents each start from their
// lead's conversation as it stands, a result for each of its calls and
// their directive after, so the lead's next turn and every fork it
// started answer the same calls at once; a client may also send a turn
// again while the first is still answered. The run takes one set of
// results only, and is not waiting for this request's once it is past
// the turn they were for: this request is its own conversation from
// here and gets a run of its own, told it whole. A 409 isn't retried,
// and the fork died with it (ylorn on Discord).
if run != nil && run.clientMarks != (req.clientCache != nil) {
run, how = nil, "cache mode changed"
}
if run != nil && run.lean != req.leanPrompt {
run, how = nil, "system prompt mode changed"
}
if run != nil && !run.claimResume() {
run, how = nil, answeredElsewhere
}
// Tool-call IDs find the process that made them, independently of the
// account routing selected. Continuing a different owner's process would
// spend its quota and report its reply or limit against the chosen account.
// The first turn on Claude Code's own sign-in, known by no name yet, is
// the exception: its run's Claude Code puts the account's profile in
// Claude Code's config, so its tool results come back on the same
// sign-in named by its email, and the run goes on under that name.
if run != nil && run.owned() != owner && !run.takeNamedOwner(owner) {
run.abort()
run, how = nil, accountChanged
}
// the client rewrote the conversation since the run's last reply, as Pi
// does compacting it mid-turn: the run's agent holds the one from before,
// would answer from it, and tell the client a context as large as ever,
// so the client compacts again at each tool call. It is let go, and a
// run started anew is told the conversation as the client now has it.
if run != nil && !run.follows(req.Messages) {
log.Printf("%s run on %s let go: earlier messages changed while it waited for tool results", name, model)
run.abort()
run, how = nil, ""
}
// the client offers a tool the run's agent was never told of, as Claude
// Code's ToolSearch loads a deferred one mid-turn: the run is handed it
// with the results, as its MCP server's tools changed. A run started
// anew would be told the conversation in one message, its tool calls as
// text, and its model went on to write its own calls as text.
var more []bridgeTool
if run != nil && !run.offers(req.Tools) {
more = bridgeTools(req)
}
var events <-chan Event
if run != nil {
req.clientCache.selected(false)
if name == "Claude Code" {
err = run.setSafeguards(req)
}
// the tools are the run's before its agent is handed them: from
// then on it may answer, finish the turn and be shelved, or be
// asked whether it offers them, before this goroutine goes on
if err == nil && more != nil {
run.mu.Lock()
for _, t := range req.Tools {
run.tools[t.Name] = true
}
if run.names == nil {
run.names = map[string]string{}
}
maps.Copy(run.names, bridgeNames(req.Tools))
run.mu.Unlock()
}
if err == nil {
events, err = run.continueWith(withTaskNotices(results, req.Messages), saidWithResults(req.Messages), more)
}
if err != nil {
run.abort()
// it ended while it waited: a new one is told the whole
// conversation
run, how = nil, runExpired
}
}
// how tool results found the run waiting on them, or why a new one is
// told the conversation; never what was said
if how != "" && how != byExactID {
if why := s.subscription.whyCallsLost(req); why != "" && how == noRunWaiting {
how += ": " + why
}
log.Printf("%s on %s: tool results %s", name, model, how)
}
if run == nil {
run, events, err = start(r.Context(), req)
if err == nil {
// its agent is running already: what it was told is set
// under the run's lock, as offers and shelve read it
tools := map[string]bool{}
for _, t := range req.Tools {
tools[t.Name] = true
}
run.mu.Lock()
run.tools = tools
if search.Name != "" {
run.search, run.searchName = s.webSearch, search.Name
}
run.mu.Unlock()
}
}
if err != nil {
// no room for another Claude Code on this machine is no fault of
// the account: a 503 passes it to the next (#2956)
code := 502
var full *claudeFull
var refused *cliSchemaRefused
if errors.As(err, &full) {
code = 503
} else if errors.As(err, &refused) {
code = 400
}
return writeError(w, from, code, name+": "+err.Error()), err.Error()
}
cacheDropped(w, req)
run.heard(req.Messages)
// 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
began := time.Now()
// A turn resumed in a run kept for it is taken back instead, the run
// left waiting where it was before it (letGo, #780); the reply's end,
// which comes of that, leaves the run to it.
var letting atomic.Bool
gone := context.AfterFunc(r.Context(), func() {
letting.Store(true)
// said in the log, as the routing trace says it with a 499 (#751)
log.Printf("%s run on %s stopped: the client went away %s into the reply", name, model, time.Since(began).Round(time.Millisecond))
run.letGo()
})
defer gone()
abort := func() {
if !letting.Load() {
run.abort()
}
}
// the allowance as kept now, and again as the reply begins, its turn
// having told it by then
var begin func()
if name == "Claude Code" {
limitHeaders(w, owner)
begin = func() { limitHeaders(w, owner) }
}
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
}
run.ended(req, said, stop, ok)
})
}
// bridgeFailed is the status and words a client is answered with when an
// agent's run ended in an error before any answer: the status the agent
// got, else a guess from the words, else 502.
//
// Claude Code says "Prompt is too long" with no status when its own check
// turned the conversation away before asking Anthropic (#2162). That is a
// conversation that no longer fits, not an upstream fault: as a 502 a
// client such as pi neither compacts nor shows why. It is a 400, as
// Anthropic's own too-long answer is, and says whose check it was and
// what lowers it. Claude Code holds a subscription to 200K once Anthropic
// has said the account needs extra usage for long context, whatever the
// model's window.
func bridgeFailed(name, msg string, status int) (int, string) {
switch {
case status >= 400:
return status, msg
case quotaSaid(msg):
return 429, msg
case name == "Claude Code" && tooLong(400, msg):
return 400, msg + " (Claude Code's own check, before Anthropic was asked: it holds a conversation to its own limit for the account, " +
"200K once Anthropic has said the account needs extra usage for long context. " +
"Compact the conversation, or turn on extra usage for the Claude account.)"
}
return 502, msg
}
// 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, begin 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
// — unless the provider is heard from first with nothing of the
// answer yet, queued or thinking (KAlive): the client is then
// sent the reply's start and kept alive while it waits, as a
// translated stream's is, or Codex hangs up at its idle timeout
// with only comments heard (#2316)
var head []Event
alive := false
for ev := range events {
if ev.Kind == KAlive {
alive = true
break
}
head = append(head, ev)
if ev.Kind != KStart && ev.Kind != KUsage {
break
}
}
if n := len(head); !alive && (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 n > 0 {
usage.add(Usage{ErrType: head[n-1].Code, RequestID: head[n-1].RequestID})
code, msg = bridgeFailed(name, msg, head[n-1].Status)
}
return writeError(w, from, code, name+": "+msg), msg
}
if begin != nil {
begin()
}
sw := newSSEWriter(w)
enc := encoder(from, sw, req, usage)
var failed, said, stop string
see := func(ev Event) {
switch ev.Kind {
case KAlive:
if sw.quiet() >= keepaliveGap {
enc.keepalive()
}
return
case KError:
failed = ev.Text
case KStart, KUsage:
usage.add(ev.Usage)
usage.add(Usage{Served: ev.Model, RequestID: ev.RequestID})
case KText:
said += ev.Text
case KStop:
stop = ev.Stop
}
enc.event(ev)
}
for _, ev := range head {
see(ev)
}
if alive {
see(Event{Kind: KAlive})
}
// a client waiting on a reply that goes on is kept from its idle
// timeout while none of it comes (#436)
relayEvents(events, sw, enc, func(ev Event) bool {
see(ev)
return true
})
// 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 != "" && !saidAnything(col.res.Parts) {
abort()
// a status, as in a stream, so another account can take over
usage.add(Usage{ErrType: col.errCode})
code, msg := bridgeFailed(name, col.err, col.errStatus)
return writeError(w, from, code, name+": "+msg), msg
}
ended(said, stop, col.err == "" && r.Context().Err() == nil)
if begin != nil {
begin()
}
res := col.finish()
usage.add(res.Usage)
usage.add(Usage{Served: res.Model})
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, _ = w.Write(renderUsage(from, res, req, usage))
return 200, col.err
}
// bridgeTools are the caller's tools as the MCP helper offers them, less
// those tool_choice rules out.
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:")) {
continue
}
schema := t.Schema
if len(schema) == 0 {
schema = json.RawMessage(`{"type":"object","properties":{}}`)
}
tools = append(tools, bridgeTool{Name: bridgeToolName(t.Name), Description: t.Description, InputSchema: schema})
}
return tools
}