CLJY (Discord) had %APPDATA%\npm with only the 308-byte sh shim of claude: no claude.cmd, no claude.ps1 and no codex at all, and `npm i -g @anthropic-ai/claude-code` ended in "npm warn cleanup ... EPERM ... unlink ...\.claude-code-<rand>\...\claude-code-win32-x64\claude.exe". On Windows a running program's file can't be removed. npm moves the old package aside, takes the old shims away, and stops partway when a claude.exe of that package is still running; the sh shim is what is left. magpie keeps such processes running itself: - the Claude subscription bridge keeps up to 6 Claude Code runs waiting for their conversations' next turns, for up to an hour; - Codex's app-server daemon has no idle exit, and magpie restarts it. Its Update button ran npm with both still up. - agent.UpdateCLI, on Windows through npm, bun or pnpm, first lets go of them: gateway.LetGoIdleClaudeCode ends every waiting run (its session shelved for the next turn, as a run let go past idleMost is) and returns once each has exited; provider.StopIdleCodexDaemon stops the daemon when no codex session is on it. Runs in a turn and sessions are left. - An update on Windows that leaves the CLI's file gone fails, saying to quit it and reinstall, instead of "updated". - proc's toolIn (FindTool) and codexExecutable no longer take the bare extensionless file on Windows, which CreateProcess can't run. Beside name.exe and name.cmd, the sh shim alone stands for the .exe it runs (Claude Code's bin\claude.exe), read from cmd-shim's exec line and kept inside its folder; a node shim (codex) or any other script is skipped. The testdata shims are cmd-shim 7's bytes, made with cmd-shim@7 on the Windows box. Run at this head (rebased on origin/main; after the rebase, vet on all three systems and the changed tests again: ok on Windows and macOS): - gofmt -l internal/: clean. go vet of proc, agent, provider and gateway on macOS (mote), Windows (win-run) and Linux (wsl-run): ok. - Windows (win-run): internal/proc ok; TestToolInNPMShShimAlone, TestLetGoIdleClaudeCodeFreesTheExe and the TestClaudeIdle* tests pass. internal/agent, internal/provider and internal/gateway (-run "Claude|LetGo|Codex") have Windows reds, and the same run at origin/mainc9d253e4ahas the same ones (26 in agent, 15 in provider, 2 in gateway), except TestUsageReadAndReadAgain, a clock-tick flake filed as #4796. - macOS (mote): internal/proc, internal/agent, internal/provider and internal/gateway (-run "Claude|LetGo|Codex") ok. - Linux (wsl-run): internal/proc and internal/provider ok; internal/agent red only in TestGrokInstalled, red the same on origin/mainc9d253e4a(3 of 3), filed as #3548. Broken by hand: - toolIn taking the bare name again: TestToolInNPMShShimAlone red on Windows (6 cases). - letGoIdle not waiting for the trees: TestLetGoIdleClaudeCodeFreesTheExe red on Windows, and with that check off the removal fails with "Access is denied" - the user's EPERM. - no let-go call and no gone check: TestUpdateCLIOnWindowsLetsGoFirst red; StopIdleCodexDaemon ignoring sessions: TestStopIdleCodexDaemon red. Not tried: a real npm update of Claude Code or Codex on the Windows box with magpie running; the Windows-only path is tested with updateGOOS = "windows" on macOS, and the process lock with a copy of the test binary. Reported-by: CLJY (Discord)
7455 lines
272 KiB
Go
7455 lines
272 KiB
Go
package gateway
|
||
|
||
// Claude Subscription is driven through the genuine Claude Code binary rather
|
||
// than by replaying its OAuth token over HTTP. Anthropic applies subscription
|
||
// eligibility checks to request content (not just credentials/CCH); prompts
|
||
// generated by Pi, OpenCode and other harnesses can otherwise be routed to
|
||
// Extra Usage. The subprocess keeps Claude Code's real Agent/CLI identity.
|
||
//
|
||
// Caller tools are exposed as an MCP server. A tools/call blocks in the hidden
|
||
// stdio helper while magpie returns the tool_use to the caller. The caller's next
|
||
// HTTP request supplies tool_result blocks, which unblock the same Claude Code
|
||
// turn. This is the protocol-neutral equivalent of pi-claude-bridge's parked
|
||
// Agent SDK query (https://github.com/elidickinson/pi-claude-bridge, MIT).
|
||
//
|
||
// A turn that ends leaves its Claude Code running, its input still open, for
|
||
// the conversation's next turn: that one is told only what the user said
|
||
// since, so the conversation Claude Code keeps goes on as it began and the
|
||
// prompt it has cached is read again. A new run would start from the whole
|
||
// history in one message, which shares nothing with what was cached but
|
||
// Claude Code's own prompt.
|
||
//
|
||
// 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"
|
||
"path/filepath"
|
||
"reflect"
|
||
"regexp"
|
||
"runtime"
|
||
"slices"
|
||
"strconv"
|
||
"strings"
|
||
"sync"
|
||
"sync/atomic"
|
||
"time"
|
||
"unicode/utf8"
|
||
|
||
"github.com/santhosh-tekuri/jsonschema/v6"
|
||
"github.com/yetone/magpie/internal/appdir"
|
||
"github.com/yetone/magpie/internal/claudecode"
|
||
"github.com/yetone/magpie/internal/claudetui"
|
||
"github.com/yetone/magpie/internal/edit"
|
||
"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
|
||
// untrusted are callers' folders, by account folder, whose
|
||
// interactive Claude Code asked whether to trust them, and when: a
|
||
// run for one goes in magpie's own folder until untrustedFor has
|
||
// passed (start)
|
||
untrusted sync.Map
|
||
// thirdParty are agents' system prompts (thirdPartyKey) Anthropic
|
||
// refused in the interactive mode as a third-party app's, and when:
|
||
// their turns run as claude -p until thirdPartyFor has passed (#4503)
|
||
thirdParty sync.Map
|
||
}
|
||
|
||
// untrustedFor is how long a caller's folder Claude Code asked to trust
|
||
// is passed over before it is tried again, the user having maybe trusted
|
||
// it in their own Claude Code since.
|
||
const untrustedFor = 10 * time.Minute
|
||
|
||
// tuiUntrusted is a run whose interactive Claude Code, in the caller's
|
||
// folder under the user's own account, asked whether to trust it, which
|
||
// the helper leaves to the user (claudetui.TrustEnv).
|
||
type tuiUntrusted struct {
|
||
key, dir string
|
||
err error
|
||
}
|
||
|
||
func (e *tuiUntrusted) Error() string { return e.err.Error() }
|
||
func (e *tuiUntrusted) Unwrap() error { return e.err }
|
||
|
||
// passedOver is whether a run in dir under configDir's account goes in
|
||
// magpie's own folder instead: its Claude Code asked lately whether to
|
||
// trust it.
|
||
func (b *subscriptionBridge) passedOver(configDir, dir string) bool {
|
||
at, ok := b.untrusted.Load(configDir + "\x00" + dir)
|
||
return ok && time.Since(at.(time.Time)) < untrustedFor
|
||
}
|
||
|
||
// 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; claudeRunTTL unless the user picked 5m, when a run kept
|
||
// the hour only holds its process longer), 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
|
||
// allowed is the client's tools its turn under way may call, nil for
|
||
// every one: none when the client chose none (tool_choice), its tools
|
||
// still offered, so Claude Code asks Anthropic the prefix the
|
||
// conversation's other turns cached (allowedTools). Under r.mu.
|
||
allowed map[string]bool
|
||
// names is the caller's name of each tool by the name the run's agent
|
||
// has it under (bridgeToolName), for those it differs: under r.mu
|
||
names map[string]string
|
||
|
||
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
|
||
// guard is the file the interactive mode's tap reads its safeguards
|
||
// from on each request (claudetui.GuardEnv); "" with none
|
||
guard string
|
||
clientMarks bool
|
||
lean bool // started with leanSystem as its system prompt
|
||
// appended: started with the caller's instructions after Claude
|
||
// Code's own system prompt (req.appendPrompt), not in its first
|
||
// message; its session, resumed, is given them so again
|
||
appended bool
|
||
tui bool // Claude Code's interactive mode (claudeTUI)
|
||
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
|
||
// convPrev is the boundary before convKey's (conversationKeys): the
|
||
// conversation as the client has it, when the run went on with a side
|
||
// question after its last turn — a prompt suggestion — whose exchange
|
||
// the client's own next turn leaves out
|
||
convPrev string
|
||
// handed is set (b.mu held) when its account was handed over to
|
||
// Claude Code itself during a turn (handedOver): it isn't kept for
|
||
// the next one
|
||
handed bool
|
||
// 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
|
||
// behindLine is the session line the conversation at behindKey ends
|
||
// at: the interactive mode, which can't be taken back, is branched
|
||
// off its session there (resume). behindMsg is the id of the reply
|
||
// that line is of: the cut goes after that reply's last line, which
|
||
// the interactive mode may tell after the turn ended (cutReply)
|
||
behindLine string
|
||
behindMsg 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
|
||
// replied says it answered a whole turn since its conversation was
|
||
// taken back (rewound): the file's lines since are that turn and what
|
||
// came after, and Claude Code's resume goes on from them, whatever the
|
||
// taken-back turn's own still sit above (shelve)
|
||
replied 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
|
||
|
||
// A run whose output may not carry a call before it is made (Claude
|
||
// Code's interactive mode, readOutput) learns of it here, as the MCP
|
||
// helper hands each one over. Set and read under mu.
|
||
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
|
||
// answerName is the interactive mode's answer tool for a request with
|
||
// a JSON schema (claude_tui_schema.go), its calls checked against
|
||
// answerSchema, and answerArgs the input of the one that fit, until the
|
||
// turn's result takes it. Under mu.
|
||
answerName string
|
||
answerSchema *jsonschema.Schema
|
||
answerArgs json.RawMessage
|
||
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
|
||
// unended is whether the segment's reply has begun (KStart) and not
|
||
// ended, by its stop or an error, under r.mu: a Claude Code whose
|
||
// output ends then exited mid-reply (readOutput)
|
||
unended bool
|
||
|
||
// lines is where in its session each call of the client's tools its
|
||
// replies made was written, by Claude Code's id for the call: a
|
||
// request that answers them after another did branches off the
|
||
// session there (branch). lineSeq counts the lines, and parkedSeq is
|
||
// lineSeq when it last parked. Under mu.
|
||
lines map[string]callLine
|
||
lineSeq int
|
||
parkedSeq int
|
||
// lastLine is the session line of the reply it wrote last, and
|
||
// backLine lastLine as the turn it was resumed for began: the
|
||
// conversation at backKey ends there. lastMsg is the id of the reply
|
||
// heard last, and backMsg lastMsg as the turn began: the interactive
|
||
// mode streams a reply first and tells its session lines after, read
|
||
// from the file it writes, so a client that asks its next turn (a
|
||
// prompt suggestion) at once finds lastLine still a line before that
|
||
// reply (sleepy_shibe: the call before its result). Under mu.
|
||
lastLine string
|
||
backLine string
|
||
lastMsg string
|
||
backMsg string
|
||
}
|
||
|
||
// callLine is the session line of an assistant message block calling a
|
||
// client's tool: its uuid, its place among the run's lines, and the
|
||
// conversation the reply answered (historyKey), set as the run parks on
|
||
// the calls.
|
||
type callLine struct {
|
||
uuid string
|
||
seq int
|
||
told string
|
||
}
|
||
|
||
// linesMost is how many call lines a run keeps (lines).
|
||
const linesMost = 256
|
||
|
||
// 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 names, the first one
|
||
// it names (clientNamedWorkPlace), as Claude Code ("Primary working directory:", or just "CWD:"
|
||
// on a --bare run), 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() {
|
||
// a folder the redact rules masked a word of names no folder on
|
||
// disk, and is never unmasked to run in: Claude Code tells its
|
||
// vendor the folder it runs in, so the masked word would go out
|
||
// as it is. The run works in magpie's folder, told the caller's
|
||
// (envElsewhere), and the model's paths are put back on the way
|
||
// to the caller's tools (#4449)
|
||
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 {
|
||
dir, _ := clientNamedWorkPlace(req)
|
||
return dir
|
||
}
|
||
|
||
// clientNamedWorkPlace is clientNamedWorkDir, and whether the caller
|
||
// named it in a message rather than in its instructions: Claude Code
|
||
// 2.1.296 and later give their environment as a {role: "system"} message
|
||
// after the user's first, so the run is told it in the conversation,
|
||
// after the caller's instructions (envTurnsNote).
|
||
//
|
||
// What the caller itself says wins over what a turn of the conversation
|
||
// says: a user turn that quotes a working-directory line ("Primary
|
||
// working directory: /x", alone on its line or inside a longer one) is no
|
||
// caller's word. Only the forms a caller states in a turn are read there
|
||
// (Codex's <environment_context> is one of the user's, OpenCode's <env> a
|
||
// later message), and a line quoted from Claude Code's own words — its
|
||
// instructions or a --bare run's "CWD:" — is never one of them.
|
||
//
|
||
// Of the texts that name a folder, the first goes: the one the
|
||
// conversation started in (in that text, its last line). A caller that
|
||
// moves says so in a message after (Claude
|
||
// Code's "# Environment update", "Primary working directory: /y (was
|
||
// /x)"), and taking that one gave a run started again for the
|
||
// conversation (its saved session resumed, a branch, a replay) another
|
||
// system prompt than the conversation's first run: envTurnsNote names the
|
||
// folder, and a run in the caller's own folder has it in Claude Code's own
|
||
// environment and saves its session in that folder's project, so the
|
||
// session wasn't found. The prompt differed right after Claude Code's own
|
||
// part, and the whole conversation was written to the cache again
|
||
// (EricWvi on X: …/frontend, then …/frontend/src). The run has no tools
|
||
// of its own; the move reaches the model in the conversation as the
|
||
// caller said it.
|
||
func clientNamedWorkPlace(req *Request) (dir string, inTurns bool) {
|
||
look := func(t string, turn bool, re *regexp.Regexp) {
|
||
if dir != "" {
|
||
return
|
||
}
|
||
for _, m := range re.FindAllStringSubmatch(t, -1) {
|
||
for _, g := range m[1:] {
|
||
g = strings.Trim(strings.TrimSpace(g), "`'\"")
|
||
if g = wasDir.ReplaceAllString(g, ""); g != "" {
|
||
dir, inTurns = g, turn
|
||
}
|
||
}
|
||
}
|
||
}
|
||
// the caller's own: its instructions, then a system message of its
|
||
// own, which says so after
|
||
look(req.System, false, clientSaidWorkDir)
|
||
for _, m := range req.Messages {
|
||
if m.Role != "system" {
|
||
continue
|
||
}
|
||
for _, p := range m.Parts {
|
||
if p.Kind == Text {
|
||
look(p.Text, true, clientSaidWorkDir)
|
||
}
|
||
}
|
||
}
|
||
if dir != "" {
|
||
return dir, inTurns
|
||
}
|
||
// what a caller states in a turn, which its own instructions and
|
||
// Claude Code's lines are never part of
|
||
for _, m := range req.Messages {
|
||
if m.Role == "assistant" || m.Role == "system" {
|
||
continue
|
||
}
|
||
for _, p := range m.Parts {
|
||
if p.Kind == Text {
|
||
look(p.Text, true, clientTurnWorkDir)
|
||
}
|
||
}
|
||
}
|
||
return dir, inTurns
|
||
}
|
||
|
||
// clientSaidWorkDir is where the caller itself says its working directory
|
||
// is, on a line of its own: Claude Code's, in its instructions (" - Primary
|
||
// working directory: /x", a moved folder as "Primary working directory: /y
|
||
// (was /x)"), on a --bare run just "CWD: /x"; OpenCode's, in its <env>;
|
||
// pi's ("Current working directory:"); Codex's and pi's <cwd>.
|
||
var clientSaidWorkDir = regexp.MustCompile(`(?m)^\s*(?:-\s*)?(?:Primary working directory|Working directory|Current working directory|CWD): *([^\r\n]+)$|<cwd>([^<\r\n]+)</cwd>`)
|
||
|
||
// clientTurnWorkDir is where a caller says its working directory is in a
|
||
// turn of the conversation, on a line of its own: Codex's
|
||
// <environment_context> is one of the user's, OpenCode's <env> a later
|
||
// message. Claude Code states its folder in its instructions or a system
|
||
// message of its own, and --bare's "CWD:" is its whole system prompt, so
|
||
// their forms are not read in a turn: a line a user message quotes —
|
||
// Claude Code's or anyone's — is no caller's word.
|
||
var clientTurnWorkDir = regexp.MustCompile(`(?m)^\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. A run in a
|
||
// turn ends as the turn does, not kept for the next (keepIdle): it went
|
||
// on waiting there, with the same token, for up to idleLongest (#4532).
|
||
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)
|
||
}
|
||
}
|
||
for _, run := range b.runs {
|
||
if u, own := ownerAccount(run.owned()); !own && strings.EqualFold(u, user) {
|
||
run.handed = true
|
||
}
|
||
}
|
||
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",
|
||
"CLAUDE_CODE_EXTRA_BODY", "DISABLE_PROMPT_CACHING"}
|
||
|
||
// 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 slices.ContainsFunc(env, func(e string) bool { return strings.HasPrefix(e, "CLAUDE_CODE_OAUTH_TOKEN=") }) {
|
||
names = append(slices.Clone(names), "CLAUDE_CODE_OAUTH_TOKEN")
|
||
}
|
||
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
|
||
}
|
||
|
||
// tuiWSL is how the interactive mode's helper runs this Claude Code, one
|
||
// in WSL, in config directory configDir (claudetui.WSL), as JSON: its
|
||
// transcripts read from Windows, through \\wsl$ for the distro's own
|
||
// folder.
|
||
func (c claudeCLI) tuiWSL(configDir string) string {
|
||
w := claudetui.WSL{Args: c.wsl.Args(), Mount: c.wsl.Mount, Projects: filepath.Join(configDir, "projects")}
|
||
if configDir == "" {
|
||
w.Projects = c.wsl.Windows(path.Join(c.wsl.Home, ".claude", "projects"))
|
||
if c.tuiWSLUnread() {
|
||
// the helper reads the transcript inside the distro
|
||
w.Projects, w.Distro = "", c.wsl.Distro
|
||
}
|
||
}
|
||
b, _ := json.Marshal(w)
|
||
return string(b)
|
||
}
|
||
|
||
// wslStat is os.Stat; a var for tests.
|
||
var wslStat = os.Stat
|
||
|
||
// tuiWSLUnread is whether Windows can't read the transcripts of this
|
||
// Claude Code in WSL in its own folder: the probe didn't find the distro
|
||
// user's home, or Windows can't read it through \\wsl$, which a session
|
||
// with no 9P redirector (one over ssh) has none of. An account's folder
|
||
// is a Windows one.
|
||
func (c claudeCLI) tuiWSLUnread() bool {
|
||
if c.wsl.Home == "" {
|
||
return true
|
||
}
|
||
_, err := wslStat(c.wsl.Windows(c.wsl.Home))
|
||
return err != nil
|
||
}
|
||
|
||
// 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.startTrusted(ctx, req, model, configDir, owner, from)
|
||
var noStart *tuiNoStart
|
||
if errors.As(err, &noStart) {
|
||
// never tried again as -p (claudeTUIErr)
|
||
return nil, nil, claudeTUIErr("Claude Code's interactive mode didn't start: " + err.Error())
|
||
}
|
||
var full *claudeFull
|
||
var refused *cliSchemaRefused
|
||
var tui *tuiRefusal
|
||
if err != nil && (from != nil || req.replayed) && !errors.As(err, &full) && !errors.As(err, &refused) && !errors.As(err, &tui) && 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)
|
||
req.branch, req.told = nil, true
|
||
return b.startTrusted(ctx, req, model, configDir, owner, nil)
|
||
}
|
||
return run, events, err
|
||
}
|
||
|
||
// startTrusted is startRun, run again in magpie's own folder when the
|
||
// caller's is one the user hasn't trusted in their own Claude Code, which
|
||
// only they answer: told the caller's folder (envElsewhere), the turn is
|
||
// answered. It was a 502, which a Claude Code client asks again and
|
||
// again, so the turn hung (lwjef on X).
|
||
func (b *subscriptionBridge) startTrusted(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 untrusted *tuiUntrusted
|
||
if !errors.As(err, &untrusted) || ctx.Err() != nil {
|
||
return run, events, err
|
||
}
|
||
// passed over from now on (passedOver): this run, and the next,
|
||
// aren't in the caller's folder. The conversation's session, kept
|
||
// (startRun), is gone on with there when it is magpie's folder's: a
|
||
// run started anew replayed the whole conversation once in each
|
||
// folder (sleepy_shibe on Discord)
|
||
b.untrusted.Store(untrusted.key, time.Now())
|
||
log.Printf("claude: Claude Code asks whether to trust %s, which its user hasn't; the run goes in magpie's own folder, told the caller's", untrusted.dir)
|
||
return b.startRun(ctx, req, model, configDir, owner, from)
|
||
}
|
||
|
||
// untrustedHere is whether a run in the caller's folder work goes in
|
||
// magpie's own instead: in the interactive mode under the account Claude
|
||
// Code is signed in to, Claude Code would ask whether to trust it, which
|
||
// only the user answers. It is decided for each run as Claude Code
|
||
// decides it (claudeTrusts), before the run, so a conversation whose
|
||
// session is in magpie's folder goes on with it there instead of being
|
||
// replayed in the caller's, asked about and replayed again in magpie's
|
||
// every time passedOver's 10 minutes were up (sleepy_shibe on Discord),
|
||
// and a folder the user trusts since is run in from the next turn on.
|
||
// A folder Claude Code asked about lately all the same stays passed
|
||
// over, as one is while the user's answers can't be read.
|
||
func (b *subscriptionBridge) untrustedHere(req *Request, binary claudeCLI, configDir, work string) bool {
|
||
if b.passedOver(configDir, work) {
|
||
return true
|
||
}
|
||
if configDir != "" || claudePrintWhy(req, binary) != "" {
|
||
// a saved account's folder is magpie's, which answers yes, and
|
||
// claude -p asks nothing
|
||
return false
|
||
}
|
||
trusted, err := claudeTrusts(work)
|
||
if err != nil {
|
||
log.Printf("claude: whether Claude Code trusts the caller's folder is unknown (%v); the run goes there", logSafe(err.Error()))
|
||
return false
|
||
}
|
||
if !trusted {
|
||
log.Printf("claude: Claude Code hasn't been told to trust %s; the run goes in magpie's own folder, told the caller's", logSafe(work))
|
||
}
|
||
return !trusted
|
||
}
|
||
|
||
// 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
|
||
}
|
||
// the interactive mode's first message waits for the file the tool
|
||
// server writes once Claude Code has listed its tools (MinhuWang on X)
|
||
mcpConfig, _ := json.Marshal(map[string]any{"mcpServers": map[string]any{
|
||
"magpie": map[string]any{"command": exe, "args": []string{claudetui.MCPCommand, callbackPath, toolsPath, filepath.Join(tmp, "listed")}},
|
||
}})
|
||
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)
|
||
if work != "" && b.untrustedHere(req, binary, configDir, work) {
|
||
work = ""
|
||
}
|
||
}
|
||
client := work != ""
|
||
if !client {
|
||
work, err = claudeWorkDir()
|
||
named, inTurns := clientNamedWorkPlace(req)
|
||
req.envElsewhere = named != ""
|
||
req.envInTurns = inTurns
|
||
req.envDir = named
|
||
// 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))
|
||
}
|
||
// set below for a run that appends them: a request asked again
|
||
// starts anew
|
||
req.appendPrompt = false
|
||
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)
|
||
}
|
||
}
|
||
// kept is the session from was, for startTrusted to go on with in
|
||
// magpie's folder when Claude Code asks about the caller's
|
||
kept := false
|
||
if from != nil {
|
||
defer func(from *savedSession) {
|
||
if !kept {
|
||
from.discard() // unless the run took it
|
||
}
|
||
}(from)
|
||
if sessions == nil || !slices.Equal(from.sessions, sessions) || !from.saved() {
|
||
from = nil
|
||
}
|
||
}
|
||
if from != nil && from == req.branch && !from.tui && wantTUI(req) {
|
||
// a branch of a -p run's session, made before the interactive
|
||
// mode was turned on: -p's prompt isn't the interactive mode's,
|
||
// so the cache has nothing of it; a new interactive Claude Code
|
||
// is told the whole conversation, never a -p run
|
||
log.Printf("claude: a branch of a claude -p run's session goes to a new interactive Claude Code, told the whole conversation")
|
||
from, req.branch = nil, nil
|
||
}
|
||
if from != nil && from.cut != "" {
|
||
// a branch is a copy of the run's session as far as the reply
|
||
// that made the calls, a session of its own: Claude Code's
|
||
// interactive mode doesn't take --resume-session-at, and resumes
|
||
// the whole session (Claude Code 2.1.316), so the branch was -p,
|
||
// and its prompt not the one the run's interactive mode had
|
||
// cached (bbfatx on X)
|
||
sid, err := cutSession(from.sessions, from.session, from.cut)
|
||
if err != nil {
|
||
log.Printf("claude: a branch of a run's session couldn't be cut (%v); a new Claude Code is told the whole conversation", err)
|
||
from, req.branch = nil, nil
|
||
} else {
|
||
log.Printf("claude: tool results another request answered first go on in a branch of their run's session, told from the results (%d messages)", len(from.since))
|
||
from.mu.Lock()
|
||
from.session, from.cut, from.gone = sid, "", false
|
||
from.mu.Unlock()
|
||
}
|
||
}
|
||
// The interactive mode's caller instructions go after Claude Code's own
|
||
// system prompt (appendsPrompt), in the block Claude Code marks for the
|
||
// cache itself, for every run of a conversation: a session resumed
|
||
// (saved, branched or a replayed transcript) has them as its run did,
|
||
// the file given again, since a session keeps no system prompt.
|
||
if from != nil {
|
||
req.appendPrompt = from.appended && !req.leanPrompt && req.clientCache == nil
|
||
} else {
|
||
req.appendPrompt = appendsPrompt(req, binary)
|
||
}
|
||
req.replayed = false
|
||
if from == nil && !req.told && sessions != nil && claudePrintWhy(req, binary) == "" {
|
||
// the interactive mode is given the conversation as Claude Code's
|
||
// own transcript, and typed its last turn (replaySession)
|
||
if from = replaySession(sessions, work, model, req); from != nil {
|
||
req.replayed = true
|
||
defer from.discard() // unless the run took it
|
||
}
|
||
}
|
||
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))
|
||
}
|
||
if req.appendPrompt {
|
||
// pasted, the caller's instructions lose their cache mark (the
|
||
// paste is one text), and every new run wrote them to the cache
|
||
// anew: Claude Code's auto mode classifier, 80k tokens an ask with
|
||
// 1,197 read (#2432), and a conversation's turn after a one-off
|
||
// first one, or after a client changed a reply, 7,290 written and
|
||
// 1,273 read of 8,565 (m4rs0n on Discord). After Claude Code's
|
||
// own system prompt they are in the block it marks itself, which
|
||
// every run under the same instructions sends the same; a file of
|
||
// the run's own, as a lean run's
|
||
appendPath := filepath.Join(tmp, "append.md")
|
||
req.appendPrompt = true
|
||
if err := os.WriteFile(appendPath, []byte(leanSystem(req)), 0o600); err != nil {
|
||
cleanup()
|
||
return nil, nil, err
|
||
}
|
||
args = append(args, "--append-system-prompt-file", binary.file(appendPath))
|
||
}
|
||
req.clientCache.selected(from == nil)
|
||
var prompt []map[string]any
|
||
var prefix cachePrefix
|
||
if from != nil {
|
||
// the session's first message has the marks it was started with:
|
||
// its cache is kept as long as before, whatever the pick is now
|
||
prefix = from.cachePrefix
|
||
prompt = renderClaudeTurn(req.Messages[len(req.Messages)-len(from.since):], req.Tools)
|
||
} else {
|
||
req.cacheTTL = runTTLFor(req, os.Environ())
|
||
prompt, err = renderClaudePrompt(req)
|
||
if err != nil {
|
||
cleanup()
|
||
return nil, nil, err
|
||
}
|
||
if req.clientCache != nil {
|
||
prefix = promptCachePrefix(prompt)
|
||
}
|
||
prefix.ttl = req.cacheTTL
|
||
}
|
||
// Claude Code's interactive mode unless the user turned it off
|
||
// (claudeTUI): the shim (claudetui) is handed the -p arguments, and
|
||
// runs them interactively. A run it can't take is refused, never made
|
||
// -p: a refused request never ran, and isn't the last run
|
||
tui, code := claudeTUI(req, binary)
|
||
if !tui && code != "off" && code != "no-shim" && code != thirdPartyCode && code != cacheMarksCode {
|
||
cleanup()
|
||
return nil, nil, &tuiRefusal{claudeTUIErr(claudeNotTUIWhy(req, binary))}
|
||
}
|
||
// the interactive mode's start takes its turn (tuiStarts); held till
|
||
// this run has been started and answered, and given back however this
|
||
// goes
|
||
turn := func() {}
|
||
if tui {
|
||
release, err := tuiStartTurn(ctx, "a Claude Code run on "+model)
|
||
if err != nil {
|
||
cleanup()
|
||
return nil, nil, err
|
||
}
|
||
turn = release
|
||
}
|
||
defer turn()
|
||
noteClaudeRun(code)
|
||
var cmd *exec.Cmd
|
||
if tui {
|
||
if cmd, err = binary.tuiCommand(context.Background(), args...); err != nil {
|
||
cleanup()
|
||
return nil, nil, err
|
||
}
|
||
} else {
|
||
cmd = binary.command(context.Background(), args...)
|
||
}
|
||
cmd.Dir = work
|
||
env, err := binary.proxied(ctx, cleanClaudeEnvTTL(os.Environ(), prefix.runTTL()))
|
||
if err != nil {
|
||
cleanup()
|
||
return nil, nil, err
|
||
}
|
||
if req.clientCache != nil && !tui {
|
||
// the client's marks take the place of Claude Code's own; the
|
||
// interactive mode is pasted the words without them, and keeps
|
||
// its own (clientCache.pasted)
|
||
env = append(env, "DISABLE_PROMPT_CACHING=1")
|
||
}
|
||
if len(req.Safeguards) > 0 {
|
||
env = append(env, "ANTHROPIC_BETAS="+req.SafeguardBeta)
|
||
}
|
||
// The interactive mode's Claude Code reads CLAUDE_CODE_EXTRA_BODY from
|
||
// its own environment, which apply_flag_settings or a --settings file
|
||
// rewritten don't reach once it runs: the run is given the safeguards
|
||
// here, and a file (guard) its tap puts each later turn's in every
|
||
// request from (claudetui.GuardEnv, setSafeguards). A client's cache
|
||
// tail isn't added to Claude Code's own marks, which it keeps
|
||
// (clientCache.pasted).
|
||
tuiBody, guard := "", ""
|
||
if tui && len(req.Safeguards) > 0 {
|
||
tuiBody = claudeExtraBody(req.Safeguards, "")
|
||
env = append(env, "CLAUDE_CODE_EXTRA_BODY="+tuiBody)
|
||
guard = filepath.Join(tmp, "guard.json")
|
||
if writeGuard(guard, tuiBody) == nil {
|
||
env = append(env, claudetui.GuardEnv+"="+guard)
|
||
} else {
|
||
guard = ""
|
||
}
|
||
}
|
||
if tui && (!client || configDir != "") {
|
||
// a folder of magpie's, or an account folder of magpie's whose
|
||
// Claude Code no one else runs: asked whether to trust it, the
|
||
// shim says yes; in the user's own account a caller's folder is
|
||
// theirs to answer for, and the run goes in magpie's
|
||
// (startTrusted)
|
||
env = append(env, claudetui.TrustEnv+"=1")
|
||
}
|
||
env = append(env, claudeBypassEnv(tui, configDir)...)
|
||
if tui && !client {
|
||
// a saved account's run in magpie's folder is never asked (#4830)
|
||
trustWork(binary, configDir, work)
|
||
}
|
||
cmd.Env = binary.env(binary.asRoot(env), configDir)
|
||
if tui {
|
||
cmd.Env = binary.tuiEnv(cmd.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.appended = req.appendPrompt
|
||
run.tui = tui
|
||
run.cachePrefix = prefix
|
||
if tuiBody != "" {
|
||
run.safeguards = bytes.Clone(req.Safeguards)
|
||
run.guard = guard
|
||
}
|
||
run.allowed = allowedTools(req)
|
||
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 || tui {
|
||
// 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.
|
||
// The interactive mode's helper answers it once Claude Code shows
|
||
// its prompt, and ends saying why when it doesn't in
|
||
// claudetui.ReadyWait: the wait is longer. 10s ended the helper
|
||
// as it waited, and every try of the turn was answered 502 with
|
||
// no reason (#4504).
|
||
wait := controlWait
|
||
if tui {
|
||
wait = tuiInitWait
|
||
}
|
||
if err := run.cliControlWithin(ctx, map[string]any{"subtype": "initialize"}, wait); err != nil {
|
||
run.abort()
|
||
if tui && client && configDir == "" && run.saidOnEnd(claudetui.Untrusted) {
|
||
kept = true
|
||
return nil, nil, &tuiUntrusted{key: configDir + "\x00" + work, dir: work, err: err}
|
||
}
|
||
var unanswered *controlUnanswered
|
||
if tui && errors.As(err, &unanswered) {
|
||
// the helper hung: the turn fails (start)
|
||
return nil, nil, &tuiNoStart{err}
|
||
}
|
||
if tui && run.saidOnEnd("claude-tui: ") && !run.saidOnEnd(claudetui.EndedEarly) {
|
||
// the helper ended saying why Claude Code didn't come up,
|
||
// and Claude Code hadn't ended itself, as one that can't
|
||
// load the session does: a new one told the whole
|
||
// conversation waited out the same 45s, and the turn was
|
||
// answered 502 after twice that (sowhynot)
|
||
return nil, nil, &tuiNoStart{err}
|
||
}
|
||
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; a branch's is the copy cut
|
||
// for it
|
||
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
|
||
}
|
||
|
||
// claudeTUIHelper, when set, is run as the interactive mode's helper in
|
||
// place of magpie's executable: a test's stand-in.
|
||
var claudeTUIHelper string
|
||
|
||
// tuiStarts is the interactive mode's starts, one at a time: a Claude Code
|
||
// takes longer to come up the more start with it, and on a machine of cold
|
||
// ones none showed its prompt in the 45s a start alone fits in, so each
|
||
// was ended at the deadline and answered 502, and every caller's next try
|
||
// started the pile again — 531 interactive starts in an hour, 420 of them
|
||
// ending "showed no prompt" (#5579). The turn taken (tuiStartTurn) is held
|
||
// till the run has been started and its helper has answered initialize —
|
||
// its prompt shown — and given back however the start goes; a start that
|
||
// missed the wait holds it until magpie has given up on it (its stop is
|
||
// under way, not waited out), so the retries behind it land on a machine
|
||
// with one start to do, not a pile.
|
||
// Runs already up are none of it: a -p run starts without a prompt to
|
||
// wait for, and a start that fits in the wait alone holds the turn only
|
||
// as long as coming up takes.
|
||
var tuiStarts = make(chan struct{}, 1)
|
||
|
||
// tuiStartTurn takes the one start's turn, waiting as long as ctx lasts.
|
||
func tuiStartTurn(ctx context.Context, what string) (func(), error) {
|
||
select {
|
||
case tuiStarts <- struct{}{}:
|
||
return func() { <-tuiStarts }, nil
|
||
default:
|
||
}
|
||
began := time.Now()
|
||
log.Printf("claude: %s waits for another interactive start to show its prompt", what)
|
||
select {
|
||
case tuiStarts <- struct{}{}:
|
||
log.Printf("claude: %s had its start's turn after %s", what, time.Since(began).Round(time.Millisecond))
|
||
return func() { <-tuiStarts }, nil
|
||
case <-ctx.Done():
|
||
return nil, ctx.Err()
|
||
}
|
||
}
|
||
|
||
// controlWait is how long Claude Code may take to answer a control
|
||
// request; tuiInitWait the interactive mode's helper its initialize: as
|
||
// long as Claude Code may take to show its prompt, with controlWait's
|
||
// room twice over.
|
||
var (
|
||
controlWait = 10 * time.Second
|
||
tuiInitWait = claudetui.ReadyWait + 2*controlWait
|
||
)
|
||
|
||
// controlUnanswered is a control request Claude Code took and didn't
|
||
// answer in time.
|
||
type controlUnanswered struct{ what string }
|
||
|
||
func (e *controlUnanswered) Error() string { return "Claude Code has not " + e.what }
|
||
|
||
// tuiNoStart is a run whose interactive mode's helper never answered its
|
||
// initialize request: start fails the turn, saying so.
|
||
type tuiNoStart struct{ err error }
|
||
|
||
func (e *tuiNoStart) Error() string { return e.err.Error() }
|
||
func (e *tuiNoStart) Unwrap() error { return e.err }
|
||
|
||
// claudeTUIRuns is false where magpie's executable has no shim to run:
|
||
// the gateway's tests, whose fake Claude Codes are -p ones. It is the one
|
||
// case besides the setting turned off (ClaudePrintMode) where a model
|
||
// request runs as -p.
|
||
var claudeTUIRuns = true
|
||
|
||
// claudeTUI says whether a run is Claude Code's interactive mode, as a
|
||
// person runs it (claudetui), rather than -p: the plan counts a -p
|
||
// request, its entrypoint sdk-cli, at about twice the interactive mode's
|
||
// (anthropics/claude-code#97074), and a -p run starts without the
|
||
// interactive mode's cache. On unless the user turned it off
|
||
// (ClaudePrintMode), on macOS, Linux and Windows, Claude Code in WSL too
|
||
// (its home known, so its transcripts are found); not for what only -p
|
||
// takes: safeguards and a client's cache marks (control requests and an
|
||
// extra body), a JSON schema, and images by URL. With it on, such a run is
|
||
// refused (startRun), never made -p. A first message of any length is
|
||
// pasted (a 3MB paste was taken in 35s, a 500KB one answered whole).
|
||
// The code is claudePrint's, for the provider editor's last run
|
||
// (ClaudeMode.Last).
|
||
func claudeTUI(req *Request, binary claudeCLI) (bool, string) {
|
||
code, why := claudePrint(req, binary)
|
||
if why != "" && code != "no-shim" {
|
||
log.Printf("claude: not the interactive mode: %s", why)
|
||
}
|
||
return why == "", code
|
||
}
|
||
|
||
// claudePrintWhy is why a run is -p, "" when it is the interactive mode.
|
||
func claudePrintWhy(req *Request, binary claudeCLI) string {
|
||
_, why := claudePrint(req, binary)
|
||
return why
|
||
}
|
||
|
||
// claudePrint is claudePrintWhy with a code the GUI names it by.
|
||
func claudePrint(req *Request, binary claudeCLI) (code, why string) {
|
||
if code, why := claudeMachineWhy(binary); why != "" {
|
||
return code, why
|
||
}
|
||
for _, c := range []struct {
|
||
is bool
|
||
code, why string
|
||
}{
|
||
{urlImages(req.Messages) > 0, "image", "an image known by its URL"},
|
||
{req.tuiRefused, thirdPartyCode, "Anthropic refused this agent's system prompt in the interactive mode as a third-party app's"},
|
||
{req.clientCache.keptAsPrint(), cacheMarksCode, fmt.Sprintf("the client's cache marks keep %dKB of history, which a fresh interactive run writes again each call", markedHistory(req)>>10)},
|
||
} {
|
||
if c.is {
|
||
return c.code, c.why
|
||
}
|
||
}
|
||
return "", ""
|
||
}
|
||
|
||
// claudeMachineWhy is why every run on this machine is -p, whatever it
|
||
// asks: a code for the provider page (ClaudeModeNow) and the log's words,
|
||
// "" "" when runs can be the interactive mode.
|
||
func claudeMachineWhy(binary claudeCLI) (code, why string) {
|
||
for _, c := range []struct {
|
||
is bool
|
||
code, why string
|
||
}{
|
||
{!claudeTUIRuns, "no-shim", "no shim"},
|
||
{runtime.GOOS != "darwin" && runtime.GOOS != "linux" && runtime.GOOS != "windows", "os", runtime.GOOS},
|
||
{binary.wsl == nil && binary.path == "", "missing", "no Claude Code path"},
|
||
{settings.Load().ClaudePrintMode, "off", "the interactive mode is turned off"},
|
||
} {
|
||
if c.is {
|
||
return c.code, c.why
|
||
}
|
||
}
|
||
return "", ""
|
||
}
|
||
|
||
// ClaudeMode is how a Claude subscription's runs are made on this
|
||
// machine, for the Claude Code provider page: TUI when Claude Code's
|
||
// interactive mode, else -p (turned off) or none (it can't run here), Why
|
||
// the code of claudeMachineWhy. With it on, a request only -p takes
|
||
// (claudePrint) is refused.
|
||
type ClaudeMode struct {
|
||
TUI bool `json:"tui"`
|
||
Why string `json:"why,omitempty"`
|
||
WSL bool `json:"wsl,omitempty"` // Claude Code in WSL
|
||
// how the last run since magpie started went (noteClaudeRun)
|
||
Last *ClaudeLastRun `json:"last,omitempty"`
|
||
}
|
||
|
||
// ClaudeLastRun is how one run went: Why is claudePrint's code ("off")
|
||
// when it was -p.
|
||
type ClaudeLastRun struct {
|
||
TUI bool `json:"tui"`
|
||
Why string `json:"why,omitempty"`
|
||
At time.Time `json:"at"`
|
||
}
|
||
|
||
// claudeLast is the last run's, since magpie started
|
||
var claudeLast struct {
|
||
sync.Mutex
|
||
run ClaudeLastRun
|
||
}
|
||
|
||
// noteClaudeRun records a run's mode: "" is the interactive mode, else
|
||
// why it is -p.
|
||
func noteClaudeRun(why string) {
|
||
claudeLast.Lock()
|
||
claudeLast.run = ClaudeLastRun{TUI: why == "", Why: why, At: time.Now()}
|
||
claudeLast.Unlock()
|
||
}
|
||
|
||
// ClaudeModeNow is ClaudeMode as of now.
|
||
func ClaudeModeNow() ClaudeMode {
|
||
m := ClaudeMode{Why: "missing"}
|
||
if binary, err := claudeBinary(); err == nil {
|
||
code, _ := claudeMachineWhy(binary)
|
||
m = ClaudeMode{TUI: code == "", Why: code, WSL: binary.wsl != nil}
|
||
}
|
||
claudeLast.Lock()
|
||
if !claudeLast.run.At.IsZero() {
|
||
r := claudeLast.run
|
||
m.Last = &r
|
||
}
|
||
claudeLast.Unlock()
|
||
return m
|
||
}
|
||
|
||
// 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)
|
||
}
|
||
|
||
// safeguardVaries is what Claude Code's classifier context carries that
|
||
// changes from one request to the next, the parts 2.1.316 itself names as
|
||
// variable and leaves out over its 256KB budget (its "shed" list): the
|
||
// turns before (prior_turn_context), system-reminder ids, artifacts,
|
||
// Chrome's tabs, where its text came from, and git's status and remotes.
|
||
var safeguardVaries = []string{"prior_turn_context", "system_reminders", "artifacts", "text_provenance", "shed"}
|
||
|
||
// safeguardsKept is a safety field without the parts that vary
|
||
// (safeguardVaries), for telling whether what it says the user allows
|
||
// changed: the rules, the permission and auto mode, the folders, the
|
||
// repository and branch. A field it can't read is kept whole, so any
|
||
// change to it counts.
|
||
func safeguardsKept(raw json.RawMessage) []byte {
|
||
var guards []map[string]any
|
||
if len(raw) == 0 || json.Unmarshal(raw, &guards) != nil {
|
||
return raw
|
||
}
|
||
for _, g := range guards {
|
||
ctx, ok := g["classifier_context"].(map[string]any)
|
||
if !ok {
|
||
continue
|
||
}
|
||
for _, k := range safeguardVaries {
|
||
delete(ctx, k)
|
||
}
|
||
if nav, ok := ctx["chrome_navigation"].(map[string]any); ok {
|
||
delete(nav, "tabs")
|
||
}
|
||
if git, ok := ctx["git_state"].(map[string]any); ok {
|
||
kept := map[string]any{}
|
||
for _, k := range []string{"cwd", "root", "branch", "default_branch"} {
|
||
if v, ok := git[k]; ok {
|
||
kept[k] = v
|
||
}
|
||
}
|
||
ctx["git_state"] = kept
|
||
}
|
||
}
|
||
b, err := json.Marshal(guards)
|
||
if err != nil {
|
||
return raw
|
||
}
|
||
return 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.tui {
|
||
tail = "" // its own marks, not the client's (startRun)
|
||
}
|
||
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")
|
||
}
|
||
if r.tui {
|
||
// Its tap puts the guard file's safeguards in each request it
|
||
// makes from now on, as Claude Code would with them in its
|
||
// environment, once it has seen a request to put them in
|
||
// (guardLive): the run goes on, its cache too, and upstream is
|
||
// sent this turn's classifier context whole (#4804).
|
||
if len(req.Safeguards) > 0 && r.guardLive() {
|
||
if err := writeGuard(r.guard, claudeExtraBody(req.Safeguards, "")); err != nil {
|
||
return fmt.Errorf("the turn's safeguards could not be handed to Claude Code (%v); restart it", err)
|
||
}
|
||
r.safeguards = bytes.Clone(req.Safeguards)
|
||
return nil
|
||
}
|
||
// A Claude Code without the tap read them as it started
|
||
// (startRun), and reads them no more. Its classifier context
|
||
// changes on nearly every request in parts of its own (the tool
|
||
// ids of the turns before, git status, system-reminder ids):
|
||
// restarting for those started a new run for every tool round
|
||
// and every turn, each one writing the whole conversation to the
|
||
// cache again, and one message of xybio's spent a Pro account's
|
||
// 5-hour window. Such a run goes on with what it started with
|
||
// unless a part that says what the user allows changed.
|
||
if bytes.Equal(safeguardsKept(r.safeguards), safeguardsKept(req.Safeguards)) {
|
||
return nil
|
||
}
|
||
return errors.New("safeguards changed; restart Claude Code's interactive mode")
|
||
}
|
||
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
|
||
}
|
||
|
||
// guardLive is whether the run's tap puts the guard file's safeguards in
|
||
// Claude Code's requests: it said so (<guard>.live) at the first one.
|
||
func (r *subscriptionRun) guardLive() bool {
|
||
if r.guard == "" {
|
||
return false
|
||
}
|
||
_, err := os.Stat(r.guard + ".live")
|
||
return err == nil
|
||
}
|
||
|
||
// writeGuard replaces the guard file with body whole: the tap reads it as
|
||
// Claude Code makes a request, never half-written.
|
||
func writeGuard(path, body string) error {
|
||
f, err := os.CreateTemp(filepath.Dir(path), "guard-*.tmp")
|
||
if err != nil {
|
||
return err
|
||
}
|
||
_, err = f.WriteString(body)
|
||
if err == nil {
|
||
err = f.Sync()
|
||
}
|
||
if cerr := f.Close(); err == nil {
|
||
err = cerr
|
||
}
|
||
if err != nil {
|
||
_ = os.Remove(f.Name())
|
||
return err
|
||
}
|
||
// on Windows a rename over a file being read fails a moment
|
||
for i := 0; ; i++ {
|
||
if err = os.Rename(f.Name(), path); err == nil || i == 20 {
|
||
break
|
||
}
|
||
time.Sleep(10 * time.Millisecond)
|
||
}
|
||
if err != nil {
|
||
_ = os.Remove(f.Name())
|
||
}
|
||
return err
|
||
}
|
||
|
||
// tuiCommand is the interactive mode's helper (claudetui) running this
|
||
// Claude Code with the -p arguments args; tuiEnv adds to its environment.
|
||
func (c claudeCLI) tuiCommand(ctx context.Context, args ...string) (*exec.Cmd, error) {
|
||
// the helper runs here, on Windows for Claude Code in WSL too: magpie
|
||
// itself, not exe, which is magpie as the distro starts it (/mnt/c/…)
|
||
helper, err := os.Executable()
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
if claudeTUIHelper != "" {
|
||
helper = claudeTUIHelper
|
||
}
|
||
// Claude Code in WSL is run through wsl.exe, its arguments in
|
||
// claudetui.WSLEnv
|
||
claude := c.path
|
||
if c.wsl != nil {
|
||
claude = "wsl.exe"
|
||
}
|
||
return proc.CommandContext(ctx, helper, append([]string{claudetui.Command, claude}, args...)...), nil
|
||
}
|
||
|
||
// tuiEnv is env with what the helper is told: how to run Claude Code in
|
||
// WSL.
|
||
func (c claudeCLI) tuiEnv(env []string, configDir string) []string {
|
||
if c.wsl != nil {
|
||
env = append(env, claudetui.WSLEnv+"="+c.tuiWSL(configDir))
|
||
}
|
||
return env
|
||
}
|
||
|
||
// claudeTUIOn is whether a Claude subscription's model requests run in
|
||
// Claude Code's interactive mode, and never as -p: the user hasn't turned
|
||
// it off (ClaudePrintMode), and magpie has its shim (claudeTUIRuns).
|
||
func claudeTUIOn() bool {
|
||
return claudeTUIRuns && !settings.Load().ClaudePrintMode
|
||
}
|
||
|
||
// wantTUI is whether req's run is to be the interactive mode: it is on,
|
||
// and Anthropic hasn't refused req's agent's prompt there (tuiRefused).
|
||
// A -p run made for such a prompt goes on with its turns, as a -p run
|
||
// from before the interactive mode was turned on doesn't.
|
||
func wantTUI(req *Request) bool {
|
||
return claudeTUIOn() && !req.tuiRefused && !req.clientCache.keptAsPrint()
|
||
}
|
||
|
||
// claudeNotTUIWhy is why a run isn't the interactive mode.
|
||
func claudeNotTUIWhy(req *Request, binary claudeCLI) string {
|
||
if why := claudePrintWhy(req, binary); why != "" {
|
||
return why
|
||
}
|
||
return "the interactive mode can't run here"
|
||
}
|
||
|
||
// claudeTUIErr is the error a request gets that Claude Code's interactive
|
||
// mode can't take, or didn't start for: it never falls back to -p, which
|
||
// the plan counts as another client's request and which starts without
|
||
// the interactive mode's cache.
|
||
func claudeTUIErr(why string) error {
|
||
// the settings come first: "Models" close before the error's
|
||
// "invalid_request_error" read as a model the account doesn't serve
|
||
// (provider.ModelUnserved), and the next account was asked
|
||
return fmt.Errorf("Claude Code's interactive mode, on in Settings › Models › Replies, can't answer this request (%s), and magpie never runs it as claude -p instead; turned off there, every request runs as -p", why)
|
||
}
|
||
|
||
// tuiRefusal is a request the interactive mode refuses for what it asks,
|
||
// or for this computer: the same on every account, and no account's
|
||
// fault. It is answered 400, which no account rests for and which isn't
|
||
// asked of the next: a 502 was asked of every account in turn, 15 tries
|
||
// across 3, and rested some of them (#4778).
|
||
type tuiRefusal struct{ error }
|
||
|
||
func (e *tuiRefusal) Unwrap() error { return e.error }
|
||
|
||
// 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 {
|
||
return r.cliControlWithin(context.Background(), request, controlWait)
|
||
}
|
||
|
||
// cliControlWithin is cliControl, answered within wait, while ctx lasts.
|
||
func (r *subscriptionRun) cliControlWithin(ctx context.Context, request map[string]any, wait time.Duration) 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(wait)
|
||
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 <-ctx.Done():
|
||
return ctx.Err()
|
||
case <-t.C:
|
||
return &controlUnanswered{fmt.Sprintf("%s in %s", what, wait)}
|
||
}
|
||
}
|
||
|
||
// 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
|
||
}
|
||
|
||
// released gives up a claimed handoff whose request turned out to carry
|
||
// another conversation's rewrite of the run's: the run goes on waiting for
|
||
// the results of the client that has not rewritten anything, parkLongest
|
||
// more, as a run whose caller stopped does (#2933).
|
||
func (r *subscriptionRun) released() {
|
||
r.mu.Lock()
|
||
r.resuming = false
|
||
r.mu.Unlock()
|
||
if r.timer != nil {
|
||
r.endIn(parkLongest)
|
||
}
|
||
}
|
||
|
||
// 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, at, atMsg := "", "", "" // the turn the run is taken back from first, the line before it and its reply
|
||
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, at, atMsg = r, r.behindTurn, r.behindLine, r.behindMsg
|
||
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) && !r.asideOf(req) {
|
||
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, run.behindLine, run.behindMsg = "", "", "", ""
|
||
}
|
||
b.mu.Unlock()
|
||
if run == nil {
|
||
return nil, nil
|
||
}
|
||
if !run.tui && wantTUI(req) {
|
||
// a -p run from before the interactive mode was turned on goes
|
||
// on with no turn more
|
||
run.abortFor("Claude Code's interactive mode is on, and this run is -p")
|
||
return nil, nil
|
||
}
|
||
req.clientCache.selected(false)
|
||
if run.tui && back != "" && urlImages(since) == 0 {
|
||
// the interactive mode can't be taken back: a run of its own goes
|
||
// on from a copy of the session cut before the side question, as
|
||
// a branch does, told only the turn. Let go, a new Claude Code was
|
||
// told the whole conversation each turn Claude Code asked its
|
||
// prompt suggestion after (bbfatx on X).
|
||
req.branch = run.branchAt(at, atMsg, owner, since)
|
||
}
|
||
if run.tui && (back != "" || urlImages(since) > 0) {
|
||
// the interactive mode can't be taken back, nor pasted an image
|
||
// it has no bytes of
|
||
run.abortFor("the interactive Claude Code can't go on with this turn")
|
||
return nil, nil
|
||
}
|
||
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 until the run
|
||
// answers a whole turn (shelve)
|
||
run.mu.Lock()
|
||
run.rewound, run.replied = true, false
|
||
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, run.backLine, run.backMsg = turn, key, run.lastLine, run.lastMsg
|
||
run.allowed = allowedTools(req)
|
||
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 run.tui {
|
||
// the interactive mode takes its effort at its start only:
|
||
// the run is let go, and one at the new effort started
|
||
run.abortFor("its effort is set at its start, and the next turn asks another")
|
||
return nil, nil
|
||
}
|
||
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.
|
||
// An aside carries a conversation of tools nothing on, and retires none
|
||
// of its runs (aside).
|
||
func (b *subscriptionBridge) retire(owner string, req *Request) {
|
||
keys := conversationKeys(owner, req.Messages)
|
||
var drop []*subscriptionRun
|
||
b.mu.Lock()
|
||
for key, run := range b.idle {
|
||
if run.owned() == owner && run.convKey != "" && slices.Contains(keys, run.convKey) && !run.asideOf(req) {
|
||
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) && !(aside(req) && len(s.tools) > 0) {
|
||
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")
|
||
}
|
||
}
|
||
|
||
// aside says req may call none of the client's tools: a tool_choice of
|
||
// none, or no tools.
|
||
func aside(req *Request) bool {
|
||
return req.ToolChoice == "none" || len(req.Tools) == 0
|
||
}
|
||
|
||
// asideOf says req asks something of r's conversation that doesn't go on
|
||
// with it: r was told tools, and req may call none, as a client asks a
|
||
// title or a summary between a conversation's turns. It is not the
|
||
// conversation's next turn. Retired, or taken as the conversation
|
||
// rewritten (looseTurn has no tools), the run the conversation waited in
|
||
// was gone or waited at the aside, so the next turn found no run, and a
|
||
// new Claude Code was told the whole conversation, writing it to the
|
||
// cache again (bbfatx on X).
|
||
func (r *subscriptionRun) asideOf(req *Request) bool {
|
||
if !aside(req) {
|
||
return false
|
||
}
|
||
r.mu.Lock()
|
||
defer r.mu.Unlock()
|
||
return len(r.tools) > 0
|
||
}
|
||
|
||
// 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, backLine, backMsg := r.turnUUID, r.backKey, r.backLine, r.backMsg
|
||
if !ok || stop != "tool" {
|
||
r.turnUUID, r.backKey, r.backLine, r.backMsg = "", "", "", ""
|
||
}
|
||
if ok && stop == "stop" {
|
||
r.replied = true
|
||
}
|
||
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 := ""
|
||
keys := conversationKeys(r.owned(), msgs)
|
||
if 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, r.behindLine, r.behindMsg = back, turn, backLine, backMsg
|
||
// the boundary before conv's: the conversation as the client has it,
|
||
// when this turn was a side question of it, whose exchange the
|
||
// client's own next turn leaves out
|
||
if n := len(keys); n > 1 {
|
||
r.convPrev = keys[n-2]
|
||
}
|
||
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
|
||
}
|
||
if r.handed {
|
||
b.mu.Unlock()
|
||
r.abortFor("its account was handed over to Claude Code itself")
|
||
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)
|
||
// behind is where the conversation's next turn comes by when the run
|
||
// went on with a side question after its last turn (behindKey): the
|
||
// session carries that exchange, and the next turn leaves it out, so
|
||
// the turn that takes it resumes a copy cut before it (unshelve):
|
||
// before the side question's own message, behindTurn, that a -p run
|
||
// was told under magpie's uuid, or, for the interactive mode, which
|
||
// names its messages itself, after behindLine, the reply before it
|
||
// (as far as that reply's last line, behindMsg)
|
||
behind string
|
||
behindTurn string
|
||
behindLine string
|
||
behindMsg string
|
||
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
|
||
// cut, for a branch of a live run's session (branch), is the line it
|
||
// is cut after: the run that takes it resumes a copy of the session
|
||
// as far as that line (cutSession), and the file stays the run's
|
||
cut string
|
||
// tui: the session was made by Claude Code's interactive mode; a
|
||
// branch of it is too, where it can be (claudePrint)
|
||
tui bool
|
||
// appended: its run had the caller's instructions after Claude Code's
|
||
// system prompt (appendsPrompt), which the session doesn't keep: the
|
||
// run that resumes it is given them so again
|
||
appended bool
|
||
|
||
// cachePrefix is the marks, and the cache lifetime, of the run whose
|
||
// session this is: the run that goes on from it keeps both. Every
|
||
// savedSession is given its run's, a branch's too: one without it ran
|
||
// an hour's cache under a 5m pick (linkaww)
|
||
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, replied, tools := run.sessionID, run.sessions, run.rewound, run.replied, maps.Clone(run.tools)
|
||
run.mu.Unlock()
|
||
if sid == "" || len(sessions) == 0 || rewound && !replied || run.idleKey == "" {
|
||
return
|
||
}
|
||
key := run.idleKey
|
||
s := &savedSession{session: sid, sessions: sessions, owner: run.owned(), conv: run.convKey, key: key, behind: run.behindKey, loose: run.loose, tools: tools, at: run.idleAt, cachePrefix: run.cachePrefix, appended: run.appended}
|
||
if run.tui {
|
||
s.behindLine, s.behindMsg = run.behindLine, run.behindMsg
|
||
} else {
|
||
s.behindTurn = run.behindTurn
|
||
}
|
||
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, behind := b.shelf[key], false
|
||
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")
|
||
}
|
||
}
|
||
if s == nil {
|
||
// the run went on with a side question after the conversation's
|
||
// last turn — a prompt suggestion — and its session is shelved
|
||
// where that turn put it, not where the conversation's own next
|
||
// turn comes by (#4914)
|
||
for _, e := range b.shelf {
|
||
if e.behind == key && (e.behindTurn != "" || e.behindLine != "" || e.behindMsg != "") && (s == nil || e.at.After(s.at)) {
|
||
s = e
|
||
}
|
||
}
|
||
if s != nil {
|
||
key, behind = s.key, true
|
||
log.Printf("claude: a conversation whose run answered a side question since goes on from its saved session, cut before the side question")
|
||
}
|
||
}
|
||
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
|
||
}
|
||
if behind && !s.cutBehind() {
|
||
s.discard()
|
||
return nil
|
||
}
|
||
s.since = since
|
||
return s
|
||
}
|
||
|
||
// cutBehind makes the shelved session s a copy of itself cut before the
|
||
// side question its run answered after the conversation's last turn
|
||
// (behind), and removes the file it was: resumed whole, Claude Code would
|
||
// go on with the side question's exchange as the conversation's, which
|
||
// the client never had (#4914). false when the session can't be cut.
|
||
func (s *savedSession) cutBehind() bool {
|
||
var cut string
|
||
var err error
|
||
if s.behindLine != "" || s.behindMsg != "" {
|
||
cut, err = cutReply(s.sessions, s.session, s.behindLine, s.behindMsg)
|
||
} else {
|
||
cut, err = cutSessionBefore(s.sessions, s.session, s.behindTurn)
|
||
}
|
||
if err != nil {
|
||
log.Printf("claude: a saved session couldn't be cut before the side question its run answered (%v); a new Claude Code is told the whole conversation", err)
|
||
return false
|
||
}
|
||
removeSession(s.sessions, s.session)
|
||
s.mu.Lock()
|
||
s.session = cut
|
||
s.mu.Unlock()
|
||
return true
|
||
}
|
||
|
||
// noteLines keeps where in the run's session a line calling the client's
|
||
// tools ids was written: uuid, as Claude Code's output tells it. Claude
|
||
// Code's own lines (<synthetic>) are no reply's.
|
||
// msg is the line's message id, when it wasn't streamed (replyBegun says so).
|
||
func (r *subscriptionRun) noteLines(uuid, model, msg string, ids []string) {
|
||
if uuid == "" || model == "<synthetic>" {
|
||
return
|
||
}
|
||
r.mu.Lock()
|
||
defer r.mu.Unlock()
|
||
r.lastLine = uuid
|
||
if msg != "" {
|
||
r.lastMsg = msg
|
||
}
|
||
if len(ids) == 0 {
|
||
return
|
||
}
|
||
if r.lines == nil {
|
||
r.lines = map[string]callLine{}
|
||
}
|
||
r.lineSeq++
|
||
for _, id := range ids {
|
||
// the conversation its reply answered, kept as the run parked on
|
||
// the call before its line was read (park)
|
||
r.lines[id] = callLine{uuid: uuid, seq: r.lineSeq, told: r.lines[id].told}
|
||
}
|
||
if len(r.lines) > linesMost {
|
||
for id, l := range r.lines {
|
||
if l.seq <= r.lineSeq-linesMost/2 {
|
||
delete(r.lines, id)
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// branch is where a request's conversation goes on from a run's session
|
||
// when no run takes its tool results: another request answered the calls
|
||
// first, and the run went on with that one. Claude Code's fork sub-agents
|
||
// 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 (2b5f19fc7); a client may
|
||
// also send a turn again while the first is answered. Each but one used to
|
||
// be told the whole conversation by a new Claude Code, in one message, a
|
||
// prefix the cache has never seen: Aisiverto on X saw two requests 100ms
|
||
// apart, one reading 900K from the cache and the other writing 877K to it,
|
||
// a fifth of a Pro plan's five hours each. The run's session, cut after
|
||
// the reply that made the calls (a copy of it, cutSession, as the run
|
||
// still has it), is the conversation as Claude Code asked
|
||
// it of Anthropic, whose cache has it: the request's own run reads it and
|
||
// is told only the results and what came after, as a turn after an
|
||
// unshelve is. nil when the run is gone, the conversation before the reply
|
||
// isn't the one it answered, or the run can't be resumed so: a client's
|
||
// own cache marks, Claude Code in WSL (no session on disk), a session
|
||
// taken back since (rewound), or, with the interactive mode on, a -p
|
||
// run's session, as its branch is -p too.
|
||
func (b *subscriptionBridge) branch(req *Request, owner string) *savedSession {
|
||
if req.clientCache != nil {
|
||
return nil
|
||
}
|
||
msgs := req.Messages
|
||
i := len(msgs)
|
||
for i > 0 && msgs[i-1].Role != "assistant" {
|
||
i--
|
||
}
|
||
if i == 0 || i == len(msgs) {
|
||
return nil
|
||
}
|
||
k := i
|
||
for k > 0 && msgs[k-1].Role == "assistant" {
|
||
k--
|
||
}
|
||
var calls []string
|
||
for _, m := range msgs[k:i] {
|
||
for _, p := range m.Parts {
|
||
if p.Kind == ToolCall {
|
||
calls = append(calls, p.ID)
|
||
}
|
||
}
|
||
}
|
||
if len(calls) == 0 {
|
||
return nil
|
||
}
|
||
b.mu.Lock()
|
||
runs := make([]*subscriptionRun, 0, len(b.runs))
|
||
for _, run := range b.runs {
|
||
runs = append(runs, run)
|
||
}
|
||
b.mu.Unlock()
|
||
told := ""
|
||
for _, run := range runs {
|
||
if run.owned() != owner {
|
||
continue
|
||
}
|
||
run.mu.Lock()
|
||
at, seq, said := "", 0, ""
|
||
for _, id := range calls {
|
||
if l, ok := run.lines[id]; ok && l.uuid != "" && l.seq > seq {
|
||
at, seq, said = l.uuid, l.seq, l.told
|
||
}
|
||
}
|
||
sid, sessions, prefix := run.sessionID, slices.Clone(run.sessions), run.cachePrefix
|
||
usable := !run.closed && !run.rewound && run.lean == req.leanPrompt && !run.clientMarks && (run.tui || !wantTUI(req))
|
||
run.mu.Unlock()
|
||
if at == "" {
|
||
continue
|
||
}
|
||
if told == "" {
|
||
told = historyKey(msgs[:k])
|
||
}
|
||
if !usable || sid == "" || len(sessions) == 0 || said != told {
|
||
return nil
|
||
}
|
||
return &savedSession{session: sid, sessions: sessions, owner: owner, at: time.Now(), since: msgs[i:], cut: at, tui: run.tui, appended: run.appended, cachePrefix: prefix, gone: true}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// retryBranch is where a turn sent again while its run is busy answering
|
||
// it goes on from a copy of the run's session, cut before the turn
|
||
// (#5405): the client's connection dropped mid-reply, its request was
|
||
// retried, and no cancel reached magpie — the run the first attempt
|
||
// started is still busy with the very turn, and its answer would reach no
|
||
// one. A new Claude Code told the whole conversation writes it all to the
|
||
// cache again, only its own system prompt and tools read from it; the
|
||
// copy is the conversation as Claude Code asked it of Anthropic, whose
|
||
// cache has it, so the retry's own run reads the history from the cache
|
||
// and is told only the turn, as a turn after an unshelve is. nil when no
|
||
// busy run of the owner is answering this very turn (the request it heard
|
||
// is this one, message for message), or the copy can't be
|
||
// made: a client's own cache marks, a session taken back or being taken
|
||
// back (rewound, rewinding), a run started for the turn (its session has
|
||
// no line or reply from before it to cut at), or no session on disk.
|
||
func (b *subscriptionBridge) retryBranch(req *Request, owner string) *savedSession {
|
||
if req.clientCache != nil {
|
||
return nil
|
||
}
|
||
key, since := nextTurn(req, owner)
|
||
if key == "" {
|
||
return nil
|
||
}
|
||
keys, want := conversationKeys(owner, req.Messages), historyKey(req.Messages)
|
||
b.mu.Lock()
|
||
runs := make([]*subscriptionRun, 0, len(b.runs))
|
||
for _, run := range b.runs {
|
||
if run.owned() != owner || run.idleKey != "" || run.convKey == "" || !slices.Contains(keys, run.convKey) {
|
||
continue
|
||
}
|
||
runs = append(runs, run)
|
||
}
|
||
b.mu.Unlock()
|
||
var found *savedSession
|
||
var at time.Time
|
||
for _, run := range runs {
|
||
run.mu.Lock()
|
||
// the very turn, not one that goes on from it (follows): a turn
|
||
// whose reply the client has is no retry of it
|
||
busy := !run.closed && run.rewinding == nil && !run.rewound && run.lean == req.leanPrompt &&
|
||
!run.clientMarks && (run.tui || !wantTUI(req)) && run.told == want
|
||
sid, sessions, backLine, backMsg, appended, tui, prefix := run.sessionID, slices.Clone(run.sessions), run.backLine, run.backMsg, run.appended, run.tui, run.cachePrefix
|
||
started := run.started
|
||
run.mu.Unlock()
|
||
if !busy || sid == "" || backLine == "" && backMsg == "" || len(sessions) == 0 {
|
||
continue
|
||
}
|
||
if found != nil && !started.After(at) {
|
||
continue
|
||
}
|
||
cut, err := cutReply(sessions, sid, backLine, backMsg)
|
||
if err != nil {
|
||
log.Printf("claude: the busy run's session couldn't be cut before the turn sent again (%v)", err)
|
||
continue
|
||
}
|
||
if found != nil {
|
||
found.discard() // a newer run's copy is taken: the older one's goes
|
||
}
|
||
found, at = &savedSession{session: cut, sessions: sessions, owner: owner, at: time.Now(), since: since, tui: tui, appended: appended, cachePrefix: prefix}, started
|
||
}
|
||
if found == nil {
|
||
return nil
|
||
}
|
||
log.Printf("claude: a turn sent again while its run is busy answering it goes on in a branch of its session, cut before the turn")
|
||
return found
|
||
}
|
||
|
||
// replyBegun notes a reply message as it begins: its lines in the session
|
||
// come later (lastMsg).
|
||
func (r *subscriptionRun) replyBegun(msg string) {
|
||
if msg == "" {
|
||
return
|
||
}
|
||
r.mu.Lock()
|
||
r.lastMsg = msg
|
||
r.mu.Unlock()
|
||
}
|
||
|
||
// branchAt is a branch of the run's session cut after its line at, as far
|
||
// as the last line of its reply msg (cutReply), for a turn of its
|
||
// conversation told since: the copy is made now, before the run is let go
|
||
// with its file, and is the branch's own. A run whose reply was its first
|
||
// may have heard no line of its own as the side question began, only the
|
||
// reply's id, and is cut by that alone (sleepy_shibe). nil when there is
|
||
// neither a line nor a reply, no session, or the copy can't be made.
|
||
func (r *subscriptionRun) branchAt(at, msg, owner string, since []Message) *savedSession {
|
||
r.mu.Lock()
|
||
sid, sessions, marks := r.sessionID, slices.Clone(r.sessions), r.clientMarks
|
||
r.mu.Unlock()
|
||
if at == "" && msg == "" || sid == "" || len(sessions) == 0 || marks {
|
||
return nil
|
||
}
|
||
cut, err := cutReply(sessions, sid, at, msg)
|
||
if err != nil {
|
||
log.Printf("claude: the interactive run's session couldn't be cut before its side question (%v)", err)
|
||
return nil
|
||
}
|
||
log.Printf("claude: the conversation's next turn goes on in a branch of its interactive run's session, cut before the side question it answered since")
|
||
return &savedSession{session: cut, sessions: sessions, owner: owner, at: time.Now(), since: since, tui: true, appended: r.appended, cachePrefix: r.cachePrefix}
|
||
}
|
||
|
||
// cutWait is how long cutSession waits for the line it cuts after to be
|
||
// in the session's file: Claude Code tells a reply on its output as it
|
||
// writes it to the file.
|
||
var cutWait = 2 * time.Second
|
||
|
||
// cutSession copies session sid, from whichever of dirs has it, as far as
|
||
// its line uuid, to a session of a new id beside it, and says the id:
|
||
// Claude Code resumes the copy as the conversation stood after that line,
|
||
// in either mode, and reads it from Anthropic's cache as the run asked it
|
||
// (Claude Code 2.1.316: 14 tokens written). Each line is the session's
|
||
// as written, its sessionId the copy's. An error when the line isn't
|
||
// there within cutWait.
|
||
func cutSession(dirs []string, sid, uuid string) (string, error) {
|
||
return cutSessionAt(dirs, sid, uuid, cutAfter)
|
||
}
|
||
|
||
// cutSessionAt is cutSession as far as where at says in the session's
|
||
// lines, uuid's line found by mark.
|
||
func cutSessionAt(dirs []string, sid, uuid string, at func(b, mark []byte, uuid string) int) (string, error) {
|
||
if uuid == "" {
|
||
return "", errors.New("no session to cut")
|
||
}
|
||
mark := []byte(`"uuid":"` + uuid + `"`)
|
||
return cutSessionWhere(dirs, sid, "line "+uuid, func(b []byte, _ bool) int { return at(b, mark, uuid) })
|
||
}
|
||
|
||
// cutReply is cutSession as far as the last line of the reply msg, the
|
||
// message whose line uuid is or one after it: the conversation as it
|
||
// stood before the side question asked after that reply. The interactive
|
||
// mode tells a reply's lines only after its stream ended, so the line the
|
||
// run had heard last as the side question began may be one before the
|
||
// reply (its tool call, before the result and the reply's words): cut
|
||
// there, the conversation went on with a call Claude Code took as
|
||
// interrupted (sleepy_shibe). A run's first reply may have no line heard
|
||
// at all, uuid empty, and is cut by msg alone. Lines of msg come before
|
||
// the side question's, which the run was told after the reply; they are
|
||
// waited for as long as a line is (cutWait), as an earlier line found
|
||
// first would cut the reply off. With no msg, or none of its lines in the
|
||
// session by then, the cut is after uuid's line.
|
||
func cutReply(dirs []string, sid, uuid, msg string) (string, error) {
|
||
if msg == "" {
|
||
return cutSession(dirs, sid, uuid)
|
||
}
|
||
mark := []byte(`"uuid":"` + uuid + `"`)
|
||
return cutSessionWhere(dirs, sid, "reply "+msg, func(b []byte, last bool) int {
|
||
if end := cutAfterReply(b, msg); end > 0 {
|
||
return end
|
||
}
|
||
if !last || uuid == "" {
|
||
return -1
|
||
}
|
||
return cutAfter(b, mark, uuid)
|
||
})
|
||
}
|
||
|
||
// cutAfterReply is where in a session's lines b the last whole assistant
|
||
// line of message msg ends, -1 when none is there.
|
||
func cutAfterReply(b []byte, msg string) int {
|
||
mark := []byte(`"id":"` + msg + `"`)
|
||
end := -1
|
||
for at := 0; at < len(b); {
|
||
nl := bytes.IndexByte(b[at:], '\n')
|
||
if nl < 0 {
|
||
break
|
||
}
|
||
line := b[at : at+nl]
|
||
at += nl + 1
|
||
if !bytes.Contains(line, mark) {
|
||
continue
|
||
}
|
||
var l struct {
|
||
Type string `json:"type"`
|
||
IsSidechain bool `json:"isSidechain"`
|
||
Message struct {
|
||
ID string `json:"id"`
|
||
} `json:"message"`
|
||
}
|
||
if json.Unmarshal(line, &l) == nil && l.Type == "assistant" && !l.IsSidechain && l.Message.ID == msg {
|
||
end = at
|
||
}
|
||
}
|
||
return end
|
||
}
|
||
|
||
// cutSessionBefore is cutSession as far as the line before uuid's: the
|
||
// session as it stood before that message was told.
|
||
func cutSessionBefore(dirs []string, sid, uuid string) (string, error) {
|
||
return cutSessionAt(dirs, sid, uuid, cutBefore)
|
||
}
|
||
|
||
// cutSessionWhere copies session sid as far as the place at finds in its
|
||
// lines (> 0), asked again until cutWait is over; last is the final ask.
|
||
// what is what it looks for, as an error says.
|
||
func cutSessionWhere(dirs []string, sid, what string, at func(b []byte, last bool) int) (string, error) {
|
||
if sid == "" || strings.ContainsAny(sid, `/\`) || strings.Contains(sid, "..") {
|
||
return "", errors.New("no session to cut")
|
||
}
|
||
for deadline := time.Now().Add(cutWait); ; time.Sleep(20 * time.Millisecond) {
|
||
last := time.Now().After(deadline)
|
||
for _, dir := range dirs {
|
||
b, err := os.ReadFile(filepath.Join(dir, sid+".jsonl"))
|
||
if err != nil {
|
||
continue
|
||
}
|
||
end := at(b, last)
|
||
if end <= 0 {
|
||
continue
|
||
}
|
||
id := newUUID()
|
||
lines := bytes.ReplaceAll(b[:end], []byte(`"sessionId":"`+sid+`"`), []byte(`"sessionId":"`+id+`"`))
|
||
// a name no one has: nothing reads it before the run starts
|
||
path := filepath.Join(dir, id+".jsonl")
|
||
if err := os.WriteFile(path, lines, 0o600); err != nil {
|
||
_ = os.Remove(path)
|
||
return "", err
|
||
}
|
||
return id, nil
|
||
}
|
||
if last {
|
||
return "", fmt.Errorf("%s isn't in session %s", what, sid)
|
||
}
|
||
}
|
||
}
|
||
|
||
// cutAfter is where in a session's lines b the whole line whose uuid is
|
||
// uuid ends, -1 when none does yet; mark is its uuid as a line writes it.
|
||
// A line half written is no line.
|
||
func cutAfter(b, mark []byte, uuid string) int {
|
||
for at := 0; at < len(b); {
|
||
nl := bytes.IndexByte(b[at:], '\n')
|
||
if nl < 0 {
|
||
return -1
|
||
}
|
||
line := b[at : at+nl]
|
||
at += nl + 1
|
||
if !bytes.Contains(line, mark) {
|
||
continue
|
||
}
|
||
var l struct {
|
||
UUID string `json:"uuid"`
|
||
}
|
||
if json.Unmarshal(line, &l) == nil && l.UUID == uuid {
|
||
return at
|
||
}
|
||
}
|
||
return -1
|
||
}
|
||
|
||
// cutBefore is where in a session's lines b the whole line whose uuid is
|
||
// uuid begins, -1 when none is there yet.
|
||
func cutBefore(b, mark []byte, uuid string) int {
|
||
end := cutAfter(b, mark, uuid)
|
||
if end < 0 {
|
||
return -1
|
||
}
|
||
return bytes.LastIndexByte(b[:end-1], '\n') + 1
|
||
}
|
||
|
||
// 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
|
||
// the interactive mode (claudeTUI) can't be taken back
|
||
can := !r.closed && !r.tui && 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, r.replied = true, false
|
||
}
|
||
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
|
||
// the calls just made answer the conversation the run last heard
|
||
for id, l := range r.lines {
|
||
if l.seq > r.parkedSeq && l.told == "" {
|
||
l.told = r.told
|
||
r.lines[id] = l
|
||
}
|
||
}
|
||
// The interactive mode streams a reply first and its session lines
|
||
// come after, read from the file Claude Code writes (118 to 162ms
|
||
// after the call), so the run parks before it has the line of a call
|
||
// it made. The calls the client was shown are this reply's: they
|
||
// answer the conversation heard now, whenever their line comes
|
||
// (noteLines keeps it). Before, the line came with no conversation
|
||
// and the next park gave it the next request's, so no request that
|
||
// answered those calls after another did matched it (branch): Claude
|
||
// Code's AgentSummary, asking its sub-agent's progress with the
|
||
// results the sub-agent's own next turn had taken, and a fork's
|
||
// directive were told the whole conversation by a new Claude Code,
|
||
// pasted as one text, and read only the tools and system prompt from
|
||
// the cache, 6% of 169k twice in 35s (kay20475 on X).
|
||
if r.lines == nil {
|
||
r.lines = map[string]callLine{}
|
||
}
|
||
for _, c := range r.shown {
|
||
if l := r.lines[c.id]; l.told == "" {
|
||
if l.uuid == "" {
|
||
l.seq = r.lineSeq // aged as a line noted now (linesMost)
|
||
}
|
||
l.told = r.told
|
||
r.lines[c.id] = l
|
||
}
|
||
}
|
||
r.parkedSeq = r.lineSeq
|
||
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 or text blocks 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.
|
||
//
|
||
// Its words have no whitespace in them at all (messageWords), so where a
|
||
// reply's text is split into blocks is left out too: the run keeps its
|
||
// reply as the one text it said, and the client as Anthropic's stream told
|
||
// it, a block for each run of words between a thinking block, a web search
|
||
// or an attempt Claude Code asked again. Read with a space where its blocks
|
||
// met ("Looking at it: Here" for "Looking at it:Here"), the client's
|
||
// conversation was none the run had, and the next turn was told to a new
|
||
// Claude Code, all of it written to the cache again (#5705).
|
||
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: with no whitespace, so neither how the client
|
||
// spaced them nor where it split them into blocks or messages counts.
|
||
func messageWords(msgs []Message) []string {
|
||
out := make([]string, len(msgs))
|
||
for i, parts := range messageParts(msgs) {
|
||
var b strings.Builder
|
||
for _, p := range parts {
|
||
for _, f := range strings.Fields(p.words) {
|
||
b.WriteString(f)
|
||
}
|
||
}
|
||
out[i] = b.String()
|
||
}
|
||
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", "", "--settings", disableDeepLinkSettings, "--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)+2)
|
||
for _, e := range env {
|
||
switch k, _, _ := strings.Cut(e, "="); k {
|
||
case "CLAUDE_CONFIG_DIR", "CLAUDE_SECURESTORAGE_CONFIG_DIR", "CLAUDE_CODE_OAUTH_TOKEN":
|
||
continue
|
||
}
|
||
out = append(out, e)
|
||
}
|
||
out = append(out, "CLAUDE_CONFIG_DIR="+configDir)
|
||
// an account added by a setup-token: Claude Code takes the token as
|
||
// `claude setup-token` says to, in its environment, for this account's
|
||
// directory alone; never on the command line, nor logged
|
||
if tok := provider.ClaudeDirToken(configDir); tok != "" {
|
||
out = append(out, "CLAUDE_CODE_OAUTH_TOKEN="+tok)
|
||
}
|
||
return out
|
||
}
|
||
|
||
func forced(v string) bool { return v != "" && v != "0" && v != "false" }
|
||
|
||
// claudeForced5m: FORCE_PROMPT_CACHING_5M is set, in env or in Claude
|
||
// Code's settings.json's env, as claudeRunTTL reads it.
|
||
func claudeForced5m(env []string) bool {
|
||
if v, _ := edit.GetJSON(filepath.Join(claudeConfigDir(), "settings.json"), "env.FORCE_PROMPT_CACHING_5M"); v != "" {
|
||
return forced(v)
|
||
}
|
||
for _, e := range env {
|
||
if v, ok := strings.CutPrefix(e, "FORCE_PROMPT_CACHING_5M="); ok {
|
||
return forced(v)
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
// claudeRunTTL is how long the prompt cache of a bridge's Claude Code run
|
||
// is kept, "5m" or "1h": the user's own pick for Claude Code's main
|
||
// conversation, as Claude Code resolves it (FORCE_PROMPT_CACHING_5M, then
|
||
// CLAUDE_CODE_PROMPT_CACHE_TTL, in env or in settings.json's env, then
|
||
// settings.json's promptCacheTtl, which the Agents page writes), and an
|
||
// hour with none set, as Claude Code writes it on a subscription within
|
||
// its limits. The run is given it in its environment, since a saved
|
||
// account's Claude Code reads the settings of the account's folder, not
|
||
// the user's (linkaww: 5m picked, every relayed write an hour's).
|
||
func claudeRunTTL(env []string) string {
|
||
if ttl := claudePickedTTL(env); ttl != "" {
|
||
return ttl
|
||
}
|
||
return "1h"
|
||
}
|
||
|
||
// claudePickedTTL is the user's pick claudeRunTTL reads, "" for none.
|
||
func claudePickedTTL(env []string) string {
|
||
settingsPath := filepath.Join(claudeConfigDir(), "settings.json")
|
||
envOf := func(k string) string {
|
||
if v, _ := edit.GetJSON(settingsPath, "env."+k); v != "" {
|
||
return v
|
||
}
|
||
for _, e := range env {
|
||
if v, found := strings.CutPrefix(e, k+"="); found {
|
||
return v
|
||
}
|
||
}
|
||
return ""
|
||
}
|
||
if forced(envOf("FORCE_PROMPT_CACHING_5M")) {
|
||
return "5m"
|
||
}
|
||
if v := envOf("CLAUDE_CODE_PROMPT_CACHE_TTL"); v == "5m" || v == "1h" {
|
||
return v
|
||
}
|
||
if v, _ := edit.GetJSON(settingsPath, "promptCacheTtl"); v == "5m" || v == "1h" {
|
||
return v
|
||
}
|
||
return ""
|
||
}
|
||
|
||
// claudeSettingsKnown: Claude Code's settings.json here is missing or
|
||
// reads and parses, so claudePickedTTL is the pick; a file that can't be
|
||
// read says nothing of one.
|
||
func claudeSettingsKnown() bool {
|
||
b, err := edit.Read(filepath.Join(claudeConfigDir(), "settings.json"))
|
||
return err == nil && (len(bytes.TrimSpace(b)) == 0 || edit.ValidJSONC(b))
|
||
}
|
||
|
||
// runTTLFor is how long a bridge run started for req keeps its prompt
|
||
// cache:
|
||
// - five minutes when FORCE_PROMPT_CACHING_5M says so, as Claude Code
|
||
// itself would;
|
||
// - an hour when the request's marks name it: its client picked it;
|
||
// - the pick of the user of the computer the request's Claude Code runs
|
||
// on (pickedTTL: this one's, or what the magpie it came through
|
||
// named), and with none picked this computer's or an hour, as Claude
|
||
// Code keeps it on a subscription. Claude Code marks five minutes with
|
||
// no ttl, picked or as its default off a subscription, so its marks
|
||
// can't say which (linkaww: a 5m pick, relayed side calls an hour's;
|
||
// nothing picked, every relayed write five minutes');
|
||
// - else what the marks ask for, five minutes for a mark with no ttl (a
|
||
// remote magpie's relay was given the hour of its own setting, never
|
||
// the Mac's, Linka);
|
||
// - else, for a request with no marks, this computer's pick or an hour
|
||
// (claudeRunTTL).
|
||
func runTTLFor(req *Request, env []string) string {
|
||
if claudeForced5m(env) {
|
||
return "5m"
|
||
}
|
||
if req != nil {
|
||
if req.askedTTL == "1h" {
|
||
return "1h"
|
||
}
|
||
switch req.pickedTTL {
|
||
case "5m", "1h":
|
||
return req.pickedTTL
|
||
case "default":
|
||
return claudeRunTTL(env)
|
||
}
|
||
if req.askedTTL != "" {
|
||
return req.askedTTL
|
||
}
|
||
}
|
||
return claudeRunTTL(env)
|
||
}
|
||
|
||
func cleanClaudeEnv(env []string) []string {
|
||
return cleanClaudeEnvTTL(env, claudeRunTTL(env))
|
||
}
|
||
|
||
// cleanClaudeEnvTTL is cleanClaudeEnv with the run's cache kept ttl
|
||
// (claudeRunTTL).
|
||
func cleanClaudeEnvTTL(env []string, ttl 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, "FORCE_PROMPT_CACHING_5M": 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",
|
||
// the cache kept as the user picked (claudeRunTTL), stated so that
|
||
// the marks magpie puts in the first message (renderClaudePrompt,
|
||
// Request.cacheTTL) are the same: Anthropic refuses a 1h mark after
|
||
// a 5m one
|
||
"CLAUDE_CODE_PROMPT_CACHE_TTL="+ttl)
|
||
}
|
||
|
||
type lockedWriter struct{ run *subscriptionRun }
|
||
|
||
func (w *lockedWriter) Write(p []byte) (int, error) {
|
||
// the interactive mode's helper says on its own line why it ended
|
||
// (claudetui.Run)
|
||
if bytes.Contains(p, []byte("claude-tui: ")) {
|
||
for _, l := range strings.Split(string(p), "\n") {
|
||
if why, ok := strings.CutPrefix(l, "claude-tui: "); ok {
|
||
log.Printf("claude: %s", why)
|
||
}
|
||
}
|
||
}
|
||
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()
|
||
r.unended = false
|
||
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, r.unended = nil, true
|
||
case KStop, KError:
|
||
r.unended = false
|
||
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
|
||
// A message Anthropic's safeguards stopped (stop_reason refusal) Claude
|
||
// Code asks again once, then on its fallback model (its
|
||
// model_refusal_fallback), and the reply goes on in the message that
|
||
// answers, as after its own call. Ended there, the client was told a
|
||
// refusal, and the gateway took it to another account or handed it
|
||
// back, while Claude Code went on to answer (Chixi_Fang on X). Only a
|
||
// refusal still standing at the turn's result ends the reply as one.
|
||
refused := false // a refusal Claude Code may go on from
|
||
var refusedDetails []byte // its stop_details, told only if it stands
|
||
replyModel := "" // the model the reply began with
|
||
// what the messages before cost, as each message's usage counts only
|
||
// itself and the client keeps the last it is told: their output is
|
||
// told with this one's, their prompt billed only (after)
|
||
var before, this Usage
|
||
var lateUsage cliUsage // a message left out as told by its call (onCall)
|
||
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
|
||
// the messages streamed: their whole messages come too, after their
|
||
// stream has begun, in Claude Code's interactive mode (claudetui's
|
||
// tap) as late as during the next message's stream
|
||
streamed := map[string]bool{}
|
||
// 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
|
||
// A turn whose result came with no message begun since the last one:
|
||
// Claude Code took the user's message and answered nothing, or only
|
||
// in words of its own (<synthetic>). Its segment, left open, was
|
||
// closed empty when the run ended, and a reply asked for whole went
|
||
// as a 200 with no content and no usage, which the client took for
|
||
// the answer (steven_4422, 18 images to claude-sonnet-5-5).
|
||
begun := false // a message began since the turn's last result
|
||
aside := "" // what Claude Code said in its own words this turn
|
||
retell := false // the run is told to make its calls once this turn's result is in
|
||
answerAsked := false // the interactive mode's turn was asked for its answer tool's call
|
||
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 == "refusal" && !theirs {
|
||
// the attempt Claude Code retracts: its held words go with it
|
||
inside, refused, calls = true, true, textCalls{}
|
||
} 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
|
||
}
|
||
rest, ok := strings.CutPrefix(name, "mcp__magpie__")
|
||
r.mu.Lock()
|
||
called := name
|
||
name = declaredName(r.names, rest)
|
||
search := r.search != nil && name == r.searchName || r.answerName != "" && name == r.answerName
|
||
refused := r.allowed != nil && !r.allowed[name]
|
||
// a tool the client announced but hasn't loaded yet (Claude
|
||
// Code's deferred tools, told by name in the conversation and
|
||
// not in tools until a ToolSearch) is called by the client's
|
||
// own name. A tool of magpie's MCP server is
|
||
// mcp__magpie__<server>__<tool> there, the name the run's agent
|
||
// called: cut to <server>__<tool> it is no tool the client has,
|
||
// and it answered "No such tool available" before a retry
|
||
// (packinggoods). A deferred built-in (WebFetch, CronCreate) has
|
||
// no __ in its name and the client no prefix on it: handed over
|
||
// as mcp__magpie__WebFetch it was no tool either (steven_4422).
|
||
// Another server's (mcp__linear__…) is the client's name as cut.
|
||
if ok && !search && name == rest && r.tools != nil && !r.tools[rest] && magpieServerTool(rest) {
|
||
name = called
|
||
}
|
||
r.mu.Unlock()
|
||
// magpie answers its own web search, as Claude Code does
|
||
// its WebSearch, and a call of a tool the turn may not call
|
||
// (mcpCall): the client is never shown it
|
||
if !ok || search || refused {
|
||
own[index] = true
|
||
return "", false
|
||
}
|
||
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, refused, refusedDetails = false, false, false, nil
|
||
before, this = before.plus(this, false), Usage{}
|
||
// Claude Code's fallback model answering: a reply told
|
||
// whole names it; a stream named its model as it began
|
||
// its prompt is the reply's, the messages before billed as
|
||
// its Deferred (after)
|
||
v := usage(u)
|
||
v.restart = true
|
||
if model == replyModel {
|
||
model = ""
|
||
}
|
||
v.Served = model
|
||
r.emit(Event{Kind: KUsage, Usage: v, Model: model})
|
||
return
|
||
}
|
||
replyModel = model
|
||
begun = true
|
||
before, this = lateUsage.gateway(), Usage{}
|
||
lateUsage = cliUsage{}
|
||
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)})
|
||
}
|
||
// A run in Claude Code's interactive mode tells its messages from the
|
||
// session's transcript (claudetui), where a message is written whole
|
||
// once it ends, and not always before its call of a client's tool is
|
||
// answered: Claude Code may hold the message back until the result is
|
||
// in, which only the client gives. The call, as the MCP helper hands it
|
||
// over, then tells the client: not in the transcript within callFirst,
|
||
// it is the reply, a message calling that one tool (Claude Code makes
|
||
// its MCP calls one at a time), and the message written later is left
|
||
// out, its usage told with the next reply's. That message is the first
|
||
// written after such a call: Claude Code writes no other before it.
|
||
// Calls of one message may now come in side by side (#4611), and a
|
||
// second one before its input is written: such a call is held back and
|
||
// told by the message itself, which carries its input whole.
|
||
told := map[string]bool{} // the client's calls it was shown
|
||
awaited := map[string]bool{} // calls told by themselves, their message not written yet
|
||
written := map[string]bool{} // calls in a message left out, not made yet
|
||
unheard := map[string]bool{} // calls held back: no reply to tell them in, or their input not written yet
|
||
lateID := "" // the message left out
|
||
over := false // the output has ended
|
||
if r.tui {
|
||
r.mu.Lock()
|
||
r.onCall = func(id, name string, args json.RawMessage) {
|
||
time.AfterFunc(callFirst, func() {
|
||
pmu.Lock()
|
||
defer pmu.Unlock()
|
||
if over || told[id] {
|
||
return
|
||
}
|
||
settle()
|
||
r.mu.Lock()
|
||
waits := r.segment != nil && r.pending[id] != nil
|
||
r.mu.Unlock()
|
||
if !waits || len(args) == 0 || string(args) == "null" {
|
||
// A call the client is not hearing now, or one with no
|
||
// arguments to run (#4611: Claude Code calls a second
|
||
// tool while its input is still being streamed), would
|
||
// reach the client broken. The message written after it
|
||
// carries its input whole: it tells the call from there.
|
||
unheard[id] = true
|
||
return
|
||
}
|
||
begin("msg_"+strings.ReplaceAll(newUUID(), "-", ""), r.model, cliUsage{})
|
||
name, _ = toolStart(0, "mcp__magpie__"+name)
|
||
told[id] = true
|
||
if written[id] {
|
||
delete(written, id)
|
||
} else {
|
||
awaited[id] = true
|
||
}
|
||
log.Printf("claude: Claude Code called %s before writing its message; the call is the reply", name)
|
||
r.emit(Event{Kind: KToolStart, ID: id, Name: name})
|
||
if len(args) > 0 {
|
||
r.emit(Event{Kind: KToolArgs, Text: string(args)})
|
||
}
|
||
end("tool_use")
|
||
if !inside {
|
||
r.endSegment()
|
||
}
|
||
})
|
||
}
|
||
r.mu.Unlock()
|
||
}
|
||
// refusal ends the reply as refused, once Claude Code went on from
|
||
// its refusal no more
|
||
refusal := func() {
|
||
refused, cut = false, false
|
||
r.emit(Event{Kind: KUsage, StopDetails: refusedDetails})
|
||
refusedDetails = nil
|
||
r.emit(Event{Kind: KStop, Stop: stopFromAnthropic("refusal")})
|
||
r.endSegment()
|
||
}
|
||
// heldIfRefused is a message's stop_details as told the client: a
|
||
// refusal's are held until it stands, the reply not ending on it
|
||
heldIfRefused := func(why string, raw json.RawMessage) json.RawMessage {
|
||
d := stopDetails(raw)
|
||
if why != "refusal" || theirs || r.schema {
|
||
return d
|
||
}
|
||
if d != nil {
|
||
refusedDetails = d
|
||
}
|
||
return nil
|
||
}
|
||
// 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. UUID is its line's
|
||
// in the session (lines).
|
||
Message json.RawMessage `json:"message"`
|
||
UUID string `json:"uuid"`
|
||
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"`
|
||
EstimatedTokens *int `json:"estimated_tokens"`
|
||
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)
|
||
var ids []string
|
||
for _, c := range whole.Content {
|
||
if c.Type == "tool_use" && strings.HasPrefix(c.Name, "mcp__magpie__") && c.ID != "" {
|
||
ids = append(ids, c.ID)
|
||
}
|
||
}
|
||
msg := ""
|
||
if !streamed[whole.ID] {
|
||
msg = whole.ID
|
||
}
|
||
r.noteLines(envelope.UUID, whole.Model, msg, ids)
|
||
}
|
||
// 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 != "" && !streamed[whole.ID] && 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" && r.schema && r.tui && inside && !envelope.IsError && !refused && !cut {
|
||
// the interactive mode's answer is its answer tool's call
|
||
// (claude_tui_schema.go); a turn that ended without one is
|
||
// asked for it once, and the reply goes on in its answer
|
||
if a := r.takeAnswer(); a != nil {
|
||
envelope.StructuredOutput = a
|
||
} else if r.answerName != "" && !answerAsked {
|
||
answerAsked = true
|
||
ask, _ := json.Marshal(map[string]any{"type": "user", "uuid": newUUID(), "message": map[string]any{"role": "user",
|
||
"content": []map[string]any{{"type": "text", "text": answerAsk(r.answerName)}}}})
|
||
if err := r.tell(ask); err == nil {
|
||
return
|
||
}
|
||
}
|
||
}
|
||
if envelope.Type == "result" {
|
||
retell, answerAsked = false, false
|
||
silent, said := !begun, aside
|
||
begun, aside = 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
|
||
standing := refused
|
||
inside, refused = false, false
|
||
switch {
|
||
case standing && envelope.APIErrorStatus == 0:
|
||
// nothing came after the refusal: with no model left to
|
||
// fall back on, Claude Code ends the turn on it, failed
|
||
// (its model_refusal_no_fallback, told in an error of its
|
||
// own); a retry that failed has its status
|
||
refusal()
|
||
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()
|
||
case silent && r.waitingOnReply():
|
||
r.emit(Event{Kind: KError, Text: noAnswer(said, envelope.Result), Status: http.StatusBadGateway, RequestID: reqID})
|
||
r.endSegment()
|
||
}
|
||
return
|
||
}
|
||
if envelope.Type == "assistant" && whole.Model == "<synthetic>" {
|
||
for _, c := range whole.Content {
|
||
if c.Type == "text" && strings.TrimSpace(c.Text) != "" {
|
||
aside = strings.TrimSpace(c.Text)
|
||
}
|
||
}
|
||
}
|
||
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
|
||
}
|
||
anyUnheard := false
|
||
for _, c := range whole.Content {
|
||
if c.Type == "tool_use" && unheard[c.ID] {
|
||
anyUnheard = true
|
||
break
|
||
}
|
||
}
|
||
if whole.ID != lateID && whole.ID != unstreamed {
|
||
if lateID != "" && len(awaited) > 0 {
|
||
log.Printf("claude: %d calls told by themselves were not in the message written after them", len(awaited))
|
||
clear(awaited)
|
||
}
|
||
lateID = ""
|
||
if len(awaited) > 0 && !anyUnheard {
|
||
lateID = whole.ID
|
||
}
|
||
}
|
||
if whole.ID == lateID && !anyUnheard {
|
||
lateUsage = whole.Usage
|
||
for _, c := range whole.Content {
|
||
if c.Type != "tool_use" {
|
||
continue
|
||
}
|
||
if awaited[c.ID] {
|
||
delete(awaited, c.ID)
|
||
} else if !told[c.ID] {
|
||
written[c.ID] = true // told when it is made
|
||
}
|
||
}
|
||
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":
|
||
delete(awaited, c.ID)
|
||
if told[c.ID] {
|
||
continue // its call told the client itself already
|
||
}
|
||
// a call held back (#4611) is told here, whole
|
||
delete(unheard, c.ID)
|
||
name, theirs := toolStart(index, c.Name)
|
||
if !theirs {
|
||
continue
|
||
}
|
||
told[c.ID] = true
|
||
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: heldIfRefused(whole.StopReason, 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] = true
|
||
r.replyBegun(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 {
|
||
// shown, its call doesn't tell it again (onCall)
|
||
told[e.ContentBlock.ID] = true
|
||
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, Estimated: e.Delta.EstimatedTokens})
|
||
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: heldIfRefused(e.Delta.StopReason, 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()
|
||
over = true
|
||
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")
|
||
} else if refused {
|
||
refusal()
|
||
} else if r.replyUnended() {
|
||
// Claude Code exited after its reply began, with no message_stop
|
||
// nor a result: only its message_start, or part of its text, was
|
||
// heard. Closed as it was, the segment went to the client as a
|
||
// reply that ended, a 200 with nothing or part of the answer, and
|
||
// the agent took it as done (#4822). It is a failure: a status
|
||
// before anything was sent, else the stream's error event
|
||
r.emit(Event{Kind: KError, Text: "Claude Code " + r.endedBefore("ended its reply").Error(), Status: http.StatusBadGateway, RequestID: reqID})
|
||
r.endSegment()
|
||
}
|
||
}
|
||
|
||
// waitingOnReply is whether a request waits on the run's segment.
|
||
func (r *subscriptionRun) waitingOnReply() bool {
|
||
r.mu.Lock()
|
||
defer r.mu.Unlock()
|
||
return r.segment != nil
|
||
}
|
||
|
||
// noAnswer is the error of a turn Claude Code ended with no message:
|
||
// what it said in its own words, else its result's, else that it said
|
||
// nothing.
|
||
func noAnswer(said, result string) string {
|
||
why := "Claude Code ended the turn without an answer"
|
||
for _, w := range []string{said, strings.TrimSpace(result)} {
|
||
if len(w) > 300 {
|
||
w = strings.ToValidUTF8(w[:300], "") + "…"
|
||
}
|
||
if w != "" {
|
||
return why + ": " + w
|
||
}
|
||
}
|
||
return why + ", and said nothing of why"
|
||
}
|
||
|
||
// replyUnended is whether a reply was begun on the run's segment, which
|
||
// is still open, and hasn't ended.
|
||
func (r *subscriptionRun) replyUnended() bool {
|
||
r.mu.Lock()
|
||
defer r.mu.Unlock()
|
||
return r.segment != nil && r.unended
|
||
}
|
||
|
||
// 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
|
||
|
||
// callFirst is how long a call of a client's tool in Claude Code's
|
||
// interactive mode waits for its message in the transcript before the call
|
||
// tells the client itself (readOutput). A message written before its call
|
||
// was read 118 to 162ms after the call came in (8 calls on a real account),
|
||
// so half a second leaves it room and makes a late message cost half as
|
||
// long as it did at 1s.
|
||
var callFirst = 500 * 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"`
|
||
}
|
||
|
||
// 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
|
||
// (after).
|
||
func (u Usage) carryUpdate(this, before Usage) Usage {
|
||
if u.CacheWrite1h == 0 && u.cacheCreationHasCounts {
|
||
u.CacheWrite1h = this.CacheWrite1h
|
||
}
|
||
return u.after(before, true)
|
||
}
|
||
|
||
// after is u, the usage of the request answering now, as told the
|
||
// client of a reply that earlier requests began (before): another try,
|
||
// the message after Claude Code's own tool call, a search round. What
|
||
// they wrote out was streamed to the client as it came, so their output
|
||
// and reasoning are added to this one's. Their prompt (input, cache
|
||
// reads and writes) is billed as the reply's Deferred and never told as
|
||
// its own: a client reads the last reply's prompt back as how full its
|
||
// conversation is, and each later request re-sent what the earlier one
|
||
// had, so a reply told the sum read twice its size and Claude Code
|
||
// compacted early (sleepy_shibe on Discord; WorkBuddy, #5115). update
|
||
// is whether u only updates what the client was told (a message_delta),
|
||
// so only the counts it has are added to.
|
||
func (u Usage) after(before Usage, update bool) Usage {
|
||
b := before.billed()
|
||
u = u.plus(Usage{Output: b.Output, Reasoning: b.Reasoning}, update)
|
||
if b.Input+b.CacheRead+b.CacheWrite+b.CacheWrite1h == 0 {
|
||
return u
|
||
}
|
||
d := Usage{Input: b.Input, CacheRead: b.CacheRead, CacheWrite: b.CacheWrite, CacheWrite1h: b.CacheWrite1h}
|
||
if own := u.Deferred; own != nil {
|
||
d.Input += own.Input
|
||
d.Output += own.Output
|
||
d.CacheRead += own.CacheRead
|
||
d.CacheWrite += own.CacheWrite
|
||
d.CacheWrite1h += own.CacheWrite1h
|
||
d.Reasoning += own.Reasoning
|
||
}
|
||
u.Deferred = &d
|
||
return u
|
||
}
|
||
|
||
// plus adds v's counts to u's; only to those u has, when it only updates
|
||
// what the client was told.
|
||
func (u Usage) plus(v Usage, only bool) Usage {
|
||
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) {
|
||
return renderClaudePromptAt(req, historyEnd(req.Messages))
|
||
}
|
||
|
||
// renderClaudePromptAt is renderClaudePrompt with the turn to answer
|
||
// beginning at split. split == len(req.Messages) tells every message as
|
||
// history, with no turn to answer: a transcript's user line before its
|
||
// reply (replaySession), which answers the last of them, while the turn to
|
||
// answer is typed after it.
|
||
func renderClaudePromptAt(req *Request, split int) ([]map[string]any, error) {
|
||
var blocks []map[string]any
|
||
var text strings.Builder
|
||
// a lean run has them as its system prompt (leanSystem), an appending
|
||
// one after Claude Code's (appendsPrompt)
|
||
if !req.leanPrompt && !req.appendPrompt && (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 (runMark): 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"] = req.runMark()
|
||
}
|
||
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).
|
||
whole := split > 0 && split == len(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 countImages(req.Messages[split:]) > 0 && (split == 0 || countImages(req.Messages[:split]) == 0) {
|
||
text.WriteString(imageNotesNote + "\n\n")
|
||
}
|
||
if slices.ContainsFunc(req.Messages, callsTool) {
|
||
text.WriteString(pastCallsNote + "\n\n")
|
||
}
|
||
switch {
|
||
case whole:
|
||
text.WriteString("</conversation_history>")
|
||
case 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"] = req.runMark()
|
||
}
|
||
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."
|
||
|
||
// envTurnsNote is envElsewhereNote, in either mode, for a caller whose
|
||
// environment is in its messages, not its instructions (Claude Code
|
||
// 2.1.296 and later, req.envInTurns), dir the working directory it names.
|
||
// envElsewhereNote pointed the model at instructions that describe no
|
||
// environment. d77da5bff then said the last environment given is the
|
||
// caller's, taking the run's own to come first; but the run's Claude Code
|
||
// gives its own as a {role: "system"} message after the run's first
|
||
// message (2.1.316, claude-opus-5-5), so after the caller's, and the model
|
||
// was pointed at the gateway's (packinggoods on Discord: a Mac client of a
|
||
// Windows gateway told to use PowerShell). Which comes last depends on
|
||
// Claude Code's version and the model, so the caller's environment is
|
||
// named by its working directory, never by its place. It names no app and
|
||
// no vendor.
|
||
func envTurnsNote(dir string) string {
|
||
return "\n\nOf the environments given in this conversation (working directory, platform, OS, shell, git status), the one whose working directory is " + dir +
|
||
" is the one every tool runs in. Any other one describes a computer no tool runs on: don't take a platform, shell or path for a tool call from it. Nothing has changed and there is no need to check."
|
||
}
|
||
|
||
// 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.envInTurns:
|
||
return envTurnsNote(req.envDir)
|
||
case req.envElsewhere && (req.leanPrompt || req.appendPrompt):
|
||
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 ""
|
||
}
|
||
|
||
// appendsPrompt: a new run for req gives the caller's instructions after
|
||
// Claude Code's own system prompt (--append-system-prompt-file), not in
|
||
// its first message. Every run in the interactive mode, which pastes its
|
||
// first message as one text, without the mark renderClaudePrompt puts on
|
||
// the instructions' block: there, a run started anew for the same
|
||
// instructions (the next one-off ask, a conversation's turn after a
|
||
// one-off first one, a turn whose run was lost) read nothing past Claude
|
||
// Code's own prompt. A run resuming a session is given them as the
|
||
// session's run was (savedSession.appended). A lean run has them as its
|
||
// system prompt already, a client's own marks keep theirs, and -p keeps
|
||
// the mark.
|
||
func appendsPrompt(req *Request, binary claudeCLI) bool {
|
||
return !req.leanPrompt && req.clientCache == nil &&
|
||
withoutBillingHeader(req.System)+envNote(req)+toolChoiceAsk(req) != "" && claudePrintWhy(req, binary) == ""
|
||
}
|
||
|
||
// 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 an hour's prompt-cache mark.
|
||
func cacheMark1h() map[string]string {
|
||
return map[string]string{"type": "ephemeral", "ttl": "1h"}
|
||
}
|
||
|
||
// runMark is the prompt-cache mark on what magpie gives a run: kept as
|
||
// long as Claude Code's own (Request.cacheTTL, given to the run by
|
||
// cleanClaudeEnvTTL), since Anthropic refuses a 1h mark after a 5m one.
|
||
func (r *Request) runMark() map[string]string {
|
||
if r.cacheTTL == "5m" {
|
||
return cacheMark("5m")
|
||
}
|
||
return cacheMark1h()
|
||
}
|
||
|
||
// 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"
|
||
}
|
||
|
||
// imageNotesNote ends a turn whose images (a tool result's among them) all
|
||
// belong to it, where currentTurnOpen has no history to say whose the notes
|
||
// are. Claude Code notes each image it is given ("[Image: source:
|
||
// …/images/3.jpg]") in a note after the message, with a path in the
|
||
// gateway's temp folder. Told nothing of them, the model took the notes for
|
||
// the images, said it could not see them and quoted the paths as on
|
||
// another computer (a Discord report, v0.1.2862).
|
||
const imageNotesNote = "(The images above, those in tool results too, are attached to this message as image content you can see. " +
|
||
"Any \"[Image: …]\" notes after it are Claude Code's record of where it keeps them, on its own computer: " +
|
||
"a path in one is not something to open, and the image itself is in the message.)"
|
||
|
||
// 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
|
||
}
|
||
|
||
// urlImages counts msgs' images known by their URL alone, which Claude
|
||
// Code's interactive mode can't be pasted: it takes an image as a file.
|
||
func urlImages(msgs []Message) int {
|
||
n := 0
|
||
for _, m := range msgs {
|
||
for _, p := range m.Parts {
|
||
if p.Kind == Image && p.Data == "" {
|
||
n++
|
||
}
|
||
for _, im := range p.Images {
|
||
if im.Data == "" {
|
||
n++
|
||
}
|
||
}
|
||
}
|
||
}
|
||
return n
|
||
}
|
||
|
||
// urlImageBytes keeps the images fetchURLImages downloaded, by URL, for
|
||
// the turns after: a conversation hands the same URLs over each turn.
|
||
var urlImageBytes = struct {
|
||
sync.Mutex
|
||
got map[string]Part
|
||
keys []string
|
||
}{got: map[string]Part{}}
|
||
|
||
// urlImagesKept is how many downloaded images urlImageBytes keeps.
|
||
const urlImagesKept = 32
|
||
|
||
// fetchURLImages fills in the bytes of msgs' images known by their URL
|
||
// alone, in place: from public addresses only (publicClient), and each
|
||
// must be an image. One that can't be had fails the request, saying which
|
||
// and why.
|
||
func fetchURLImages(ctx context.Context, msgs []Message) error {
|
||
fill := func(p *Part) error {
|
||
if p.Data != "" || p.URL == "" {
|
||
return nil
|
||
}
|
||
urlImageBytes.Lock()
|
||
got, ok := urlImageBytes.got[p.URL]
|
||
urlImageBytes.Unlock()
|
||
if !ok {
|
||
b, _, err := FetchImage(ctx, publicClient, p.URL)
|
||
if err != nil {
|
||
return fmt.Errorf("couldn't fetch the image at %s for the interactive mode: %v", p.URL, err)
|
||
}
|
||
mt := http.DetectContentType(b)
|
||
if !strings.HasPrefix(mt, "image/") {
|
||
return fmt.Errorf("couldn't use the image at %s: it isn't an image (it reads as %s)", p.URL, mt)
|
||
}
|
||
got = Part{MediaType: mt, Data: base64.StdEncoding.EncodeToString(b)}
|
||
urlImageBytes.Lock()
|
||
if _, ok := urlImageBytes.got[p.URL]; !ok {
|
||
urlImageBytes.keys = append(urlImageBytes.keys, p.URL)
|
||
if len(urlImageBytes.keys) > urlImagesKept {
|
||
delete(urlImageBytes.got, urlImageBytes.keys[0])
|
||
urlImageBytes.keys = urlImageBytes.keys[1:]
|
||
}
|
||
}
|
||
urlImageBytes.got[p.URL] = got
|
||
urlImageBytes.Unlock()
|
||
}
|
||
p.MediaType, p.Data = got.MediaType, got.Data
|
||
return nil
|
||
}
|
||
for i := range msgs {
|
||
for j := range msgs[i].Parts {
|
||
part := &msgs[i].Parts[j]
|
||
if part.Kind == Image {
|
||
if err := fill(part); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
for k := range part.Images {
|
||
if err := fill(&part.Images[k]); err != nil {
|
||
return err
|
||
}
|
||
}
|
||
}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// 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.
|
||
//
|
||
// A tool of magpie's own MCP server, which the client (Claude Code with
|
||
// magpie's Library) already names mcp__magpie__<server>__<tool>, is
|
||
// offered under the rest of its name: with the helper's mcp__magpie__
|
||
// before it again, the run's model was shown
|
||
// mcp__magpie__mcp__magpie__magpie-browser__browser_click, while a
|
||
// deferred tool the client named in its text kept the single prefix
|
||
// (packinggoods on Discord, 11-01). The model now sees the client's own
|
||
// name. A client offering both "mcp__magpie__x" and a bare "x" would
|
||
// have the two offered alike, which this doesn't tell apart.
|
||
func bridgeToolName(name string) string {
|
||
if rest, ok := strings.CutPrefix(name, "mcp__magpie__"); ok && bridgeToolNameOK.MatchString(rest) && !bridgeToolNameHashed.MatchString(rest) {
|
||
return rest
|
||
}
|
||
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
|
||
}
|
||
|
||
// magpieServerTool says whether rest, a name the run's agent called with
|
||
// mcp__magpie__ cut off, is a tool of magpie's MCP server as the client
|
||
// names it after that prefix: <server>__<tool> (the router's names,
|
||
// hub_mcp.go). Claude Code's built-ins (WebFetch, WebSearch, CronCreate,
|
||
// NotebookEdit…) have no __ in their names, and another MCP server's tool
|
||
// is mcp__<server>__<tool> whole.
|
||
func magpieServerTool(rest string) bool {
|
||
return strings.Contains(rest, "__") && !strings.HasPrefix(rest, "mcp__")
|
||
}
|
||
|
||
// 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 countImages(msgs) > 0 {
|
||
text.WriteString("\n\n" + imageNotesNote)
|
||
}
|
||
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)
|
||
}
|
||
// A client block ends its rendered block even without a mark of its
|
||
// own: the mark a client put on this position last round has moved
|
||
// on with the conversation's growth, and with the boundary merged
|
||
// into the next marked block Anthropic's prefix check — which looks
|
||
// back over block boundaries, not into them — finds the old write
|
||
// no more and the whole history is written again (#3835)
|
||
if cached && (p.cache != "" || p.block) {
|
||
blocks = closeBlocks(blocks, text)
|
||
text.Reset()
|
||
if p.cache != "" {
|
||
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 != "":
|
||
mediaType, data := claudeImage(p.MediaType, p.Data)
|
||
blocks = append(blocks, map[string]any{"type": "image", "source": map[string]any{"type": "base64", "media_type": mediaType, "data": 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
|
||
}
|
||
|
||
// skillBody is the text Claude Code sends after a Skill call's result:
|
||
// the skill's SKILL.md, headed with where its files are.
|
||
var skillBody = regexp.MustCompile(`^Base directory for this skill: `)
|
||
|
||
// withSkillBodies hands the run each skill's body that came after the
|
||
// results, at the end of its Skill call's result. Claude Code answers a
|
||
// Skill call with "Launching skill: pdf" and sends the skill's SKILL.md
|
||
// as a text block after the results; since #5403 that text counts as the
|
||
// agent's (desktopNote), not the user's, and was handed to no one, so the
|
||
// run's model loaded a skill and never saw what it says.
|
||
func withSkillBodies(results []Part, msgs []Message) []Part {
|
||
if len(results) == 0 {
|
||
return results
|
||
}
|
||
i := len(msgs)
|
||
for i > 0 && msgs[i-1].Role != "assistant" {
|
||
i--
|
||
}
|
||
skills := map[string]bool{}
|
||
if i > 0 {
|
||
for _, p := range msgs[i-1].Parts {
|
||
if p.Kind == ToolCall && p.Name == "Skill" {
|
||
skills[p.CallID] = true
|
||
skills[p.ID] = true
|
||
}
|
||
}
|
||
}
|
||
var out []Part
|
||
seen := false
|
||
for _, m := range msgs[i:] {
|
||
if withImages(m) {
|
||
continue
|
||
}
|
||
var last string
|
||
for _, p := range m.Parts {
|
||
switch {
|
||
case p.Kind == ToolResult:
|
||
seen = true
|
||
last = p.CallID
|
||
case p.Kind != Text || !seen:
|
||
default:
|
||
body := strings.TrimSpace(reminderTag.ReplaceAllString(p.Text, ""))
|
||
if !skillBody.MatchString(body) {
|
||
continue
|
||
}
|
||
if out == nil {
|
||
out = slices.Clone(results)
|
||
}
|
||
// the Skill call's result, else the one it follows, else the last
|
||
k := slices.IndexFunc(out, func(r Part) bool {
|
||
return r.CallID != "" && skills[r.CallID] && !strings.Contains(r.Text, "Base directory for this skill: ")
|
||
})
|
||
if k < 0 {
|
||
k = slices.IndexFunc(out, func(r Part) bool { return r.CallID == last })
|
||
}
|
||
if k < 0 {
|
||
k = len(out) - 1
|
||
}
|
||
if out[k].Text != "" {
|
||
out[k].Text += "\n\n"
|
||
}
|
||
out[k].Text += body
|
||
}
|
||
}
|
||
}
|
||
if out == nil {
|
||
return results
|
||
}
|
||
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[^>]*)?>`)
|
||
// desktopNote is an annotation Claude Desktop (its Claude Code) puts
|
||
// beside what the run reads, telling it about the picture it scaled
|
||
// down, where a skill's files live, or that a tool of ToolSearch's
|
||
// was loaded: the agent's own words about its own work (#5403), never
|
||
// the user's — the picture itself rides in the tool result. Wide
|
||
// images read in parallel bring one note each, which may come as one
|
||
// text joined by blank lines: every note in it is the agent's.
|
||
desktopNote = regexp.MustCompile(`(?s)^(?:(?:\[Image: original \d+x\d+, displayed at \d+x\d+\. Multiply coordinates by [\d.]+ to map to original image\.\]|Tool loaded\.)\s*)+$|^Base directory for this skill: `)
|
||
)
|
||
|
||
// 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) || desktopNote.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 {
|
||
err := fmt.Errorf("the agent is not waiting for tool results %s", callIDs(results))
|
||
r.abortFor(err.Error())
|
||
return nil, err
|
||
}
|
||
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 != "":
|
||
mimeType, data := claudeImage(imageMediaType(im), im.Data)
|
||
content = append(content, map[string]any{"type": "image", "data": data, "mimeType": mimeType})
|
||
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, answerName := run.search, run.searchName, run.answerName
|
||
run.mu.Unlock()
|
||
if answerName != "" && call.Name == answerName {
|
||
run.answer(w, call.Arguments)
|
||
return
|
||
}
|
||
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
|
||
}
|
||
run.mu.Lock()
|
||
refused := run.allowed != nil && !run.allowed[call.Name]
|
||
run.mu.Unlock()
|
||
if refused {
|
||
// the client chose no tool for this turn: the call is answered
|
||
// here, and Claude Code goes on to answer in words
|
||
writeJSON(w, 200, mcpToolResult{Content: []map[string]any{{"type": "text", "text": "No tool can be used for this reply. Answer without tools."}}, IsError: true})
|
||
return
|
||
}
|
||
waiter := make(chan mcpToolResult, 1)
|
||
run.mu.Lock()
|
||
if result, ok := run.early[call.ToolCallID]; ok {
|
||
delete(run.early, call.ToolCallID)
|
||
run.mu.Unlock()
|
||
writeJSON(w, 200, result)
|
||
return
|
||
}
|
||
run.pending[call.ToolCallID] = waiter
|
||
onCall := run.onCall
|
||
run.mu.Unlock()
|
||
b.mu.Lock()
|
||
b.calls[call.ToolCallID] = run
|
||
b.mu.Unlock()
|
||
if onCall != nil {
|
||
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()
|
||
mode := "claude -p"
|
||
if r.tui {
|
||
mode = "interactive mode"
|
||
}
|
||
log.Printf("claude: Claude Code pid %d started, a run on %s (%s)", r.pid(), r.model, mode)
|
||
go func() {
|
||
err := t.Wait()
|
||
how := "exited"
|
||
if err != nil {
|
||
how = err.Error()
|
||
}
|
||
log.Printf("claude: Claude Code pid %d (%s, %s) ended after %s (%s), %d MiB resident at most", r.pid(), r.model, mode, time.Since(started).Round(time.Second), how, proc.PeakRSS(r.cmd)>>20)
|
||
r.drain()
|
||
// exited closes under mu, which abort reads it under: a run it
|
||
// counts as leaving the room is one whose room is freed here
|
||
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})
|
||
} else if r.waitingOnReply() {
|
||
// it ended with a request waiting on it and nothing of the
|
||
// reply begun (a reply begun is readOutput's): closed as it
|
||
// was, the segment went as an answer of nothing. Its exit
|
||
// and stderr say why, the interactive helper's its deadline
|
||
r.emit(Event{Kind: KError, Text: "Claude Code " + r.endedBefore("answered").Error(), Status: http.StatusBadGateway})
|
||
}
|
||
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")
|
||
}
|
||
|
||
// saidOnEnd is whether the run, ended, wrote words on its stderr, read to
|
||
// its end: its output may end before its stderr is read.
|
||
func (r *subscriptionRun) saidOnEnd(words string) bool {
|
||
read := make(chan struct{})
|
||
go func() {
|
||
r.reading.Wait()
|
||
close(read)
|
||
}()
|
||
select {
|
||
case <-read:
|
||
case <-time.After(2 * time.Second):
|
||
}
|
||
r.mu.Lock()
|
||
defer r.mu.Unlock()
|
||
return strings.Contains(r.stderr.String(), words)
|
||
}
|
||
|
||
// 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)
|
||
}
|
||
if run.convPrev != "" && run.convPrev != run.convKey {
|
||
keepLost(b.lost, run.convPrev, 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, or
|
||
// the run whose calls another request answered first has it
|
||
from := s.subscription.unshelve(req, owner)
|
||
if from == nil {
|
||
from = req.branch
|
||
}
|
||
if from == nil {
|
||
// a turn sent again while its run is still busy answering it
|
||
// (#5405): the run goes on from a copy of its session, cut
|
||
// before the turn, and the retry's run reads the history from
|
||
// the cache, told only the turn
|
||
from = s.subscription.retryBranch(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)
|
||
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
|
||
}
|
||
// Claude Code is asked for the model by Anthropic's id, not one
|
||
// the user lists it by (SetModelID): no wire name reaches its run
|
||
return s.subscription.start(ctx, req, p.OwnModelID(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) {
|
||
return s.serveSubscriptionAs(w, r, from, name, model, owner, body, usage, start, false)
|
||
}
|
||
|
||
// serveSubscriptionAs is serveSubscription, asPrint for the turn asked
|
||
// again as claude -p after the interactive mode's run was refused as a
|
||
// third-party app's with nothing of the reply said (redoAsPrint).
|
||
func (s *Server) serveSubscriptionAs(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), asPrint bool) (int, string) {
|
||
var req *Request
|
||
var err error
|
||
if name == "Claude Code" && wantsClientCache(r, from) {
|
||
req, err = parseAnthropicRequest(body, true)
|
||
} else if name == "Claude Code" && classifierClientCache(from, body) {
|
||
// the classifier never asked for its marks through magpie's
|
||
// header: a set the bridge can't keep (a TTL order Anthropic
|
||
// would refuse) goes the default way, as before, not refused; in
|
||
// the interactive mode, which can't place them, it goes the
|
||
// default way, Claude Code placing its own, unless they keep
|
||
// enough history that it runs as -p for them (keptByPrint)
|
||
if req, err = parseAnthropicRequest(body, true); err != nil || claudeTUIOn() && !keptByPrint(req) {
|
||
req, err = parse(from, body)
|
||
}
|
||
} else {
|
||
req, err = parse(from, body)
|
||
}
|
||
if err != nil {
|
||
return writeError(w, from, 400, err.Error()), err.Error()
|
||
}
|
||
// output_config's effort is the level the CLI thinks at (--effort), which
|
||
// works whatever the turn thinks: taken also when the request asks no
|
||
// thinking, which upstream a reasoning ask would turn on though the
|
||
// request never asked for it (Claude Code's title requests carry an
|
||
// effort and no thinking) (#2899). Claude Code's auto mode classifier
|
||
// is still asked at low (#250), whatever effort it carries.
|
||
if from == provider.Anthropic && req.Effort == "" && !req.ThinkOff && !autoModeClassifier(req) {
|
||
if e := outputConfigEffort(body); e != "" {
|
||
req.Effort = e
|
||
}
|
||
}
|
||
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)
|
||
// how long the user of the computer the request's Claude Code runs on
|
||
// keeps its cache, which its marks don't say (runTTLFor)
|
||
req.pickedTTL = claudeTTLOf(callerOf(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
|
||
}
|
||
}
|
||
}
|
||
// a turn whose agent's system prompt Anthropic refused in the
|
||
// interactive mode as a third-party app's runs as claude -p, which is
|
||
// served it: asked again after the refusal, or of a prompt refused
|
||
// within thirdPartyFor (#4503)
|
||
if name == "Claude Code" && claudeTUIOn() && (asPrint || s.subscription.tuiRefused(req)) {
|
||
req.tuiRefused = true
|
||
if req.clientCache != nil {
|
||
req.clientCache.print = true
|
||
}
|
||
}
|
||
if name == "Claude Code" && claudeTUIOn() && !req.tuiRefused && keptByPrint(req) {
|
||
// the classifier's marks keep more than its fresh interactive
|
||
// run would write again each call: claude -p keeps them
|
||
req.clientCache.print, req.clientCache.kept = true, true
|
||
}
|
||
if name == "Claude Code" && wantTUI(req) && urlImages(req.Messages) > 0 {
|
||
// the interactive mode is pasted files: an image known by its URL
|
||
// is downloaded first, as -p's Claude Code had Anthropic fetch it
|
||
if err := fetchURLImages(r.Context(), req.Messages); err != nil {
|
||
return writeError(w, from, 400, "Claude Code: "+err.Error()), err.Error()
|
||
}
|
||
}
|
||
// the interactive mode answers a schema through magpie's answer tool
|
||
var answer Tool
|
||
var answerSchema *jsonschema.Schema
|
||
if name == "Claude Code" && wantTUI(req) && len(req.Format.schema()) > 0 {
|
||
if answerSchema, err = compileAnswerSchema(cliSchema(req.Format.schema())); err != nil {
|
||
return writeError(w, from, 400, "Claude Code: "+err.Error()), err.Error()
|
||
}
|
||
answer = answerTool(req.Tools, req.Format.schema())
|
||
req.Tools = append(slices.Clone(req.Tools), answer)
|
||
}
|
||
// 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 request's conversation was rewritten since the run's last reply —
|
||
// the client's own, as Pi does compacting it mid-turn, or another
|
||
// session's: Claude Code's fork sub-agents and resumed sessions answer
|
||
// the very calls the run waits on, by their ids, and theirs is the
|
||
// history this request carries. The run's agent holds the conversation
|
||
// from before, would answer from it, and tell the client a context as
|
||
// large as ever, so the client compacted again at each tool call: these
|
||
// results go on in a run of their own, told the conversation as the
|
||
// request has it. The run that made the calls is not ended for them
|
||
// (#2933): the results of the client that has not rewritten anything are
|
||
// still to come, and it goes on waiting for them, parkLongest more, as a
|
||
// run whose caller stopped does.
|
||
if run != nil && !run.follows(req.Messages) {
|
||
log.Printf("%s on %s: tool results go on in a run of their own: earlier messages changed while the run that made the calls waits for them", name, model)
|
||
run.released()
|
||
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 {
|
||
// the turn may call what this request lets it: a client may
|
||
// choose none once it has its tools' results
|
||
run.mu.Lock()
|
||
run.allowed = allowedTools(req)
|
||
run.mu.Unlock()
|
||
events, err = run.continueWith(withTaskNotices(withSkillBodies(results, req.Messages), req.Messages), saidWithResults(req.Messages), more)
|
||
}
|
||
if err != nil {
|
||
// it ended while it waited, or can't take the results: a new
|
||
// one is told the whole conversation, and the log, and what a
|
||
// later request is told of it (whyLost), say why
|
||
run.abortFor(err.Error())
|
||
run, how = nil, runExpired+": "+err.Error()
|
||
}
|
||
}
|
||
// 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 && name == "Claude Code" {
|
||
req.branch = s.subscription.branch(req, owner)
|
||
}
|
||
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
|
||
}
|
||
if answer.Name != "" && run.tui {
|
||
run.answerName, run.answerSchema = answer.Name, answerSchema
|
||
}
|
||
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
|
||
var tui *tuiRefusal
|
||
if errors.As(err, &full) {
|
||
code = 503
|
||
} else if errors.As(err, &refused) || errors.As(err, &tui) {
|
||
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) }
|
||
}
|
||
run.mu.Lock()
|
||
req.interactive = run.tui
|
||
run.mu.Unlock()
|
||
if req.Stream {
|
||
quit := make(chan struct{})
|
||
defer close(quit)
|
||
events = keepBridgeHeard(events, quit)
|
||
}
|
||
code, msg := 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)
|
||
})
|
||
if req.interactive && strings.Contains(msg, thirdPartyWords) {
|
||
s.subscription.refusedTUI(req)
|
||
}
|
||
if code == redoAsPrint {
|
||
gone()
|
||
log.Printf("claude: Anthropic refused an interactive-mode turn on %s as a third-party app's, with nothing of the reply said: asked again as claude -p (#4503)", req.Model)
|
||
return s.serveSubscriptionAs(w, r, from, name, model, owner, body, usage, start, true)
|
||
}
|
||
return code, msg
|
||
}
|
||
|
||
// unansweredWhy is the error of a bridged reply that ended with neither
|
||
// its stop nor an error: nothing said, or its words cut short.
|
||
func unansweredWhy(said string) string {
|
||
if said == "" {
|
||
return "it ended without an answer"
|
||
}
|
||
return errEndedShort.Error()
|
||
}
|
||
|
||
// 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
|
||
}
|
||
|
||
// thirdPartyWords is how Anthropic refuses a Claude subscription's turn
|
||
// it counts as a third-party app's: "API Error: 400 Third-party apps now
|
||
// draw from your extra usage, not your plan limits. Add more at
|
||
// claude.ai/settings/usage and keep going." (#4503, isjiajia01 and
|
||
// sounfury). isjiajia01's controlled tests had it of Claude Code's
|
||
// interactive mode (the cli entrypoint) told a client agent's own system
|
||
// prompt (Pi's, judged as a whole, no phrase of it alone), where claude -p
|
||
// (sdk-cli) was served the same prompt.
|
||
const thirdPartyWords = "Third-party apps now draw from your extra usage"
|
||
|
||
// thirdPartyRefused is msg, the words a Claude Code run's failure is
|
||
// answered with, with what happened and what to do said after it when
|
||
// Anthropic refused the turn as a third-party app's (#4503). The bare
|
||
// 400 said "keep going" and nothing of why a client's turn was refused
|
||
// while plain ones were served. An interactive-mode turn refused with
|
||
// nothing of its reply said is asked again as claude -p before it gets
|
||
// here (redoAsPrint); one that gets here had begun its reply, and the
|
||
// next turns of its agent's prompt run as -p (tuiRefused). The refusal
|
||
// is about the request, the same on every account, so it stays a 400
|
||
// that no account rests for and the next isn't asked
|
||
// (TestClaudeTUIRefusalIsNoAccountsFault). The words avoid quotaWords',
|
||
// which would read it as an account out of quota.
|
||
func thirdPartyRefused(name string, req *Request, code int, msg string) string {
|
||
if !thirdPartySaid(name, code, msg) {
|
||
return msg
|
||
}
|
||
if !req.interactive {
|
||
log.Printf("claude: Anthropic refused a claude -p turn on %s as a third-party app's (#4503)", req.Model)
|
||
return msg + " (magpie: Anthropic counted this turn, run as claude -p, as a third-party app's and answered nothing. " +
|
||
"Asking again may draw from the Claude account's extra usage, so magpie doesn't ask again on its own.)"
|
||
}
|
||
log.Printf("claude: Anthropic refused an interactive-mode turn on %s as a third-party app's, its reply begun (#4503)", req.Model)
|
||
return msg + " (magpie: Anthropic counted this turn as a third-party app's once its reply had begun. " +
|
||
"It ran in Claude Code's interactive mode with your agent's own system prompt, which Anthropic can refuse there. " +
|
||
"magpie runs this agent's next turns as claude -p, which is served such prompts: ask again.)"
|
||
}
|
||
|
||
// thirdPartySaid is whether a Claude Code run's failure is Anthropic's
|
||
// refusal of its turn as a third-party app's.
|
||
func thirdPartySaid(name string, code int, msg string) bool {
|
||
return name == "Claude Code" && code == http.StatusBadRequest && strings.Contains(msg, thirdPartyWords)
|
||
}
|
||
|
||
// thirdPartyCode is claudePrint's code for a run that is claude -p
|
||
// because Anthropic refused its agent's prompt in the interactive mode.
|
||
const thirdPartyCode = "third-party"
|
||
|
||
// cacheMarksCode is claudePrint's code for a run that is claude -p
|
||
// because its client's cache marks keep more history than a fresh
|
||
// interactive run should write again (keptByPrint).
|
||
const cacheMarksCode = "cache-marks"
|
||
|
||
// redoAsPrint is relay's status for an interactive-mode turn Anthropic
|
||
// refused as a third-party app's (#4503, Raven on Discord: Pi in Cindy
|
||
// through group/auto) before any of its reply was said, or reached the
|
||
// client: nothing was written, and serveSubscriptionAs asks it again, once,
|
||
// as claude -p, which isjiajia01's controlled tests had served the same
|
||
// prompt. Anthropic answered the refused turn nothing, so the -p run is
|
||
// its only answer, and one that would draw from extra usage would have
|
||
// been served, not refused. A -p turn is never asked again (req.interactive
|
||
// is false), and neither is one whose reply had begun: that client has its
|
||
// start already, and the turn may have said or done something.
|
||
const redoAsPrint = -4503
|
||
|
||
// redoable is whether relay hands an interactive-mode turn's refusal,
|
||
// code and msg, back as redoAsPrint: Anthropic's third-party refusal, the
|
||
// user's interactive mode still on (Off, every run is -p already), and the
|
||
// client still waiting.
|
||
func redoable(r *http.Request, name string, req *Request, code int, msg string) bool {
|
||
return req.interactive && !req.tuiRefused && thirdPartySaid(name, code, msg) && claudeTUIOn() && r.Context().Err() == nil
|
||
}
|
||
|
||
// thirdPartyFor is how long an agent's system prompt Anthropic refused in
|
||
// the interactive mode runs as claude -p before the interactive mode is
|
||
// tried for it again. A try refused costs a Claude Code's start and no
|
||
// usage; a -p turn the plan counts at about twice.
|
||
const thirdPartyFor = 12 * time.Hour
|
||
|
||
// thirdPartyKeyLen is how much of a system prompt its fingerprint reads:
|
||
// an agent's own part, which comes first, and not what it adds after of
|
||
// the day, its folder or its files (Pi's date and working directory), so
|
||
// that each conversation of the agent isn't refused once first.
|
||
const thirdPartyKeyLen = 2048
|
||
|
||
// thirdPartyKey is req's agent's system prompt's fingerprint, "" when it
|
||
// has none: what the interactive mode was refused for is the prompt,
|
||
// judged as a whole (#4503), not the account or the conversation.
|
||
func thirdPartyKey(req *Request) string {
|
||
sys := strings.TrimSpace(withoutBillingHeader(req.System))
|
||
if sys == "" {
|
||
return ""
|
||
}
|
||
if len(sys) > thirdPartyKeyLen {
|
||
sys = sys[:thirdPartyKeyLen]
|
||
}
|
||
sum := sha256.Sum256([]byte(sys))
|
||
return hex.EncodeToString(sum[:])
|
||
}
|
||
|
||
// refusedTUI keeps that Anthropic refused req's agent's prompt in the
|
||
// interactive mode, for its next turns to run as claude -p (tuiRefused).
|
||
func (b *subscriptionBridge) refusedTUI(req *Request) {
|
||
key := thirdPartyKey(req)
|
||
if key == "" {
|
||
return
|
||
}
|
||
now := time.Now()
|
||
b.thirdParty.Range(func(k, v any) bool {
|
||
if now.Sub(v.(time.Time)) >= thirdPartyFor {
|
||
b.thirdParty.Delete(k)
|
||
}
|
||
return true
|
||
})
|
||
b.thirdParty.Store(key, now)
|
||
}
|
||
|
||
// tuiRefused is whether Anthropic refused req's agent's prompt in the
|
||
// interactive mode within thirdPartyFor.
|
||
func (b *subscriptionBridge) tuiRefused(req *Request) bool {
|
||
key := thirdPartyKey(req)
|
||
if key == "" {
|
||
return false
|
||
}
|
||
at, ok := b.thirdParty.Load(key)
|
||
return ok && time.Since(at.(time.Time)) < thirdPartyFor
|
||
}
|
||
|
||
// bridgeHeardAfter is how long a Claude Code run may work on its turn
|
||
// with nothing of the reply before its client is told the reply goes on
|
||
// (keepBridgeHeard). Before it, a failure is still a status for the next
|
||
// account; after it, the client's stream begins, held for another account
|
||
// all the same (holdLead), so that its first event reaches the client
|
||
// well within the 600s Claude Code waits for one.
|
||
var bridgeHeardAfter = time.Minute
|
||
|
||
// keepBridgeHeard hands on a run's events, and a KAlive whenever the run
|
||
// has said nothing for keepaliveEvery, from bridgeHeardAfter on, for up
|
||
// to translatedQuietLongest of silence: a run whose Claude Code is still
|
||
// working is heard from, as a translated provider's keepalives are. The
|
||
// interactive mode tells a message only once it is written whole, and a
|
||
// long conversation's first reply, at effort high on claude-opus-5-5,
|
||
// took 385 to 527s (#5043). Its client heard the held stream's comments
|
||
// for keepaliveLongest (keepQuiet), then nothing, and Claude Code 2.1.316
|
||
// ended the request at 599s ("Streaming idle timeout (byte-level): no
|
||
// bytes for 300000ms"); comments for as long as it waited would not do
|
||
// either, since it ends a stream with no event for 600s from its headers
|
||
// ("no chunks received for 300s"). Every new try then started a Claude
|
||
// Code that wrote the whole conversation to the cache again (#3808).
|
||
// What this buys is bounded: Claude Code 2.1.316 makes a ping of its own
|
||
// of every 10s with bytes and counts 30 pings in a row, so a stream that
|
||
// sends only pings and comments is ended 600s after its last other
|
||
// event. The reply's start goes out when the hold lets it (holdLead,
|
||
// ~4 minutes in), and the run then has until ~14 minutes, where it had
|
||
// 599s.
|
||
// The run's end closes events, and with them what this hands on; quit
|
||
// ends it when relay is done with them.
|
||
func keepBridgeHeard(events <-chan Event, quit <-chan struct{}) <-chan Event {
|
||
out := make(chan Event)
|
||
go func() {
|
||
defer close(out)
|
||
tick := time.NewTicker(keepaliveEvery)
|
||
defer tick.Stop()
|
||
began := time.Now()
|
||
last := began
|
||
started := false // the reply has its start, the run's or this one's
|
||
send := func(ev Event) bool {
|
||
select {
|
||
case <-quit:
|
||
return false
|
||
case out <- ev:
|
||
return true
|
||
}
|
||
}
|
||
for {
|
||
select {
|
||
case <-quit:
|
||
return
|
||
case ev, ok := <-events:
|
||
if !ok {
|
||
return
|
||
}
|
||
last = time.Now()
|
||
started = started || ev.Kind == KStart
|
||
if !send(ev) {
|
||
return
|
||
}
|
||
case <-tick.C:
|
||
quiet := time.Since(last)
|
||
if time.Since(began) < bridgeHeardAfter || quiet < keepaliveEvery || quiet >= translatedQuietLongest {
|
||
continue
|
||
}
|
||
// the reply begins, with none of it, for the client's
|
||
// keepalive to be its protocol's own event: an Anthropic
|
||
// ping before message_start breaks the SDKs (keepalive);
|
||
// the run's own start that comes later adds its usage
|
||
if !started {
|
||
started = true
|
||
if !send(Event{Kind: KStart}) {
|
||
return
|
||
}
|
||
}
|
||
if !send(Event{Kind: KAlive}) {
|
||
return
|
||
}
|
||
}
|
||
}
|
||
}()
|
||
return out
|
||
}
|
||
|
||
// 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()
|
||
// what Anthropic said the reply's start used, the conversation
|
||
// written to the account's cache, is the failed try's, kept
|
||
// with its row when the request goes on to another (serve)
|
||
for _, ev := range head {
|
||
if ev.Kind == KStart || ev.Kind == KUsage {
|
||
usage.add(ev.Usage)
|
||
}
|
||
}
|
||
code := 502
|
||
if n > 0 {
|
||
code, msg = bridgeFailed(name, msg, head[n-1].Status)
|
||
// nothing of the reply was said, nor has reached the client
|
||
if redoable(r, name, req, code, msg) {
|
||
return redoAsPrint, msg
|
||
}
|
||
usage.add(Usage{ErrType: head[n-1].Code, RequestID: head[n-1].RequestID})
|
||
msg = thirdPartyRefused(name, req, code, msg)
|
||
}
|
||
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
|
||
})
|
||
// a reply that ended with neither its stop nor an error was cut
|
||
// short, or never said: finished, it went as the turn's end, the
|
||
// client taking nothing, or part of the answer, for the answer
|
||
if failed == "" && stop == "" && r.Context().Err() == nil {
|
||
see(Event{Kind: KError, Text: name + ": " + unansweredWhy(said), Status: http.StatusBadGateway})
|
||
}
|
||
// 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 == "" && stop == "" && r.Context().Err() == nil {
|
||
// as in a stream: an answer of nothing, the reply's segment
|
||
// closed with nothing said, went as a 200 with content null and
|
||
// no usage (steven_4422)
|
||
col.err, col.errStatus = unansweredWhy(said), http.StatusBadGateway
|
||
}
|
||
if col.err != "" {
|
||
abort()
|
||
// a status, as in a stream, so another account can take over;
|
||
// what the reply's start used is the failed try's. Words said
|
||
// before the failure are no answer either: handed whole, they
|
||
// went as a 200, the turn's end, and the agent took a reply cut
|
||
// short for a finished one (#4822); nothing has reached the
|
||
// client yet, so it is told the failure, as a translated reply
|
||
// cut short is (errEndedShort)
|
||
usage.add(col.res.Usage)
|
||
code, msg := bridgeFailed(name, col.err, col.errStatus)
|
||
if len(col.res.Parts) == 0 && redoable(r, name, req, code, msg) {
|
||
return redoAsPrint, msg
|
||
}
|
||
usage.add(Usage{ErrType: col.errCode})
|
||
msg = thirdPartyRefused(name, req, code, msg)
|
||
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 a named tool_choice rules out. A choice of none keeps them all:
|
||
// Anthropic caches a prompt as its tools, then its system prompt, then
|
||
// its messages, so a turn told none of them is a prefix the cache has
|
||
// never seen, and was written to it whole, its tools and system prompt
|
||
// too (bbfatx on X: a title or a summary asked with tool_choice none, of
|
||
// a long conversation). The turn may call none of them (allowedTools).
|
||
func bridgeTools(req *Request) []bridgeTool {
|
||
tools := make([]bridgeTool, 0, len(req.Tools))
|
||
for _, t := range req.Tools {
|
||
if 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
|
||
}
|
||
|
||
// allowedTools is the client's tools a turn of req may call, nil for all
|
||
// it offers (subscriptionRun.allowed): none when it chose none.
|
||
func allowedTools(req *Request) map[string]bool {
|
||
if req.ToolChoice == "none" {
|
||
return map[string]bool{}
|
||
}
|
||
return nil
|
||
}
|
||
|
||
// LetGoIdleClaudeCode ends the Claude Code runs every subscription bridge
|
||
// keeps waiting for their conversations' next turns, each one's session
|
||
// shelved for that turn as a run let go past idleMost is, and waits for
|
||
// them to have exited. It says how many it ended. An update of Claude
|
||
// Code by npm on Windows asks it first (agent.UpdateCLI): a run holds the
|
||
// package's claude.exe for up to idleLongest, which npm can't remove
|
||
// while it runs (EPERM), so the update stopped partway and left
|
||
// %APPDATA%\npm without claude.cmd (CLJY on Discord). A run in a turn is
|
||
// left to finish it.
|
||
func LetGoIdleClaudeCode() int {
|
||
var runs []*subscriptionRun
|
||
bridges.Range(func(b, _ any) bool {
|
||
runs = append(runs, b.(*subscriptionBridge).letGoIdle("Claude Code is being updated")...)
|
||
return true
|
||
})
|
||
// Windows' Stop kills the tree and returns; the process has exited,
|
||
// and let go of its files, once exited closes
|
||
gone := time.After(stopGrace + time.Second)
|
||
for _, r := range runs {
|
||
r.mu.Lock()
|
||
exited := r.exited
|
||
r.mu.Unlock()
|
||
if exited == nil {
|
||
continue
|
||
}
|
||
select {
|
||
case <-exited:
|
||
case <-gone:
|
||
return len(runs)
|
||
}
|
||
}
|
||
return len(runs)
|
||
}
|
||
|
||
// letGoIdle ends b's runs waiting for their next turn, for why, waits
|
||
// until each tree is ended, and says which they were.
|
||
func (b *subscriptionBridge) letGoIdle(why string) []*subscriptionRun {
|
||
var drop []*subscriptionRun
|
||
b.mu.Lock()
|
||
for key, run := range b.idle {
|
||
if run.idleKey == key {
|
||
b.shelve(run)
|
||
}
|
||
delete(b.idle, key)
|
||
run.idleKey = ""
|
||
if !slices.Contains(drop, run) {
|
||
drop = append(drop, run)
|
||
}
|
||
}
|
||
b.mu.Unlock()
|
||
stops := make([]<-chan struct{}, 0, len(drop))
|
||
for _, run := range drop {
|
||
run.abortFor(why)
|
||
}
|
||
for _, run := range drop {
|
||
stops = append(stops, run.abort())
|
||
}
|
||
for _, s := range stops {
|
||
<-s
|
||
}
|
||
claudeRoom.nudge()
|
||
return drop
|
||
}
|