diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 4d5d72386..5954fa586 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -152,7 +152,7 @@ something else shows up as drift. - Claude Code's provider switches (`agentenv.ClaudeProviders`: `CLAUDE_CODE_USE_BEDROCK`, `_VERTEX`, `_FOUNDRY`, `_ANTHROPIC_AWS`, `_ANTHROPIC_GOOGLE_CLOUD`, `_MANTLE`, Claude Code 2.1.300) send it to that cloud's own endpoint and pass `ANTHROPIC_BASE_URL` over, so with one on it never reaches magpie (jw1dev on X: Bedrock refused magpie's model, and magpie showed nothing). Claude Code reads 1, true, yes and on as on (`claudeSwitchOn`). One that is on in the settings magpie writes is taken out on every route that writes the wiring (`dropClouds` in `writeTiers` and `Sync`), its raw value stashed (`claude.cloud.`, under the distro's id for a WSL twin), and put back as written when magpie steps out (`putClouds` in `unroute`), unless the user set it again since. The cloud's own variables (`AWS_*`, `ANTHROPIC_VERTEX_PROJECT_ID`, …) and a switch that is off stay. Where magpie doesn't write it, Check says so, naming the variable, the cloud and where (`claudeCloud`): the managed settings, which win over the user's; `~/.claude.json`'s env, under the user's settings; and, for this machine's Claude Code, the login shell's environment (`proc.LoginEnv`, read but never set in magpie's), under every settings file. A project's `.claude/settings.json` isn't read: magpie doesn't know which folders Claude Code runs in. T3 Code's Check says the same of the user's `~/.claude` settings, which are put over its magpie instance's environment, and a switch put on that instance goes at its next write; that Check first says when the instance's `ANTHROPIC_BASE_URL` no longer reaches the gateway (`t3EnvOf`), as every agent's Check does, so a port move rewrites it too. The drift's detail is shown in the row's line and its pill through `tNotice` (`claude-cloud-drift.test.cjs`). Claude Desktop's Code tab runs with `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST`, under which Claude Code ignores a switch in settings files, so Desktop needs neither. - Claude Code's sign-in (`login`) is magpie's key (`""`, the default) or claude.ai (`claudeai`). claude.ai writes `ANTHROPIC_AUTH_TOKEN` empty, which Claude Code reads as no key: it keeps its claude.ai login and sends that to magpie, which never passes it on (`claudeSignIn` in the gateway). Every later write keeps the token empty (`wiredKey`), and a caller key of the gateway's own put there by hand is taken for magpie's, by Check and a model pick alike, kept as the user left it (`keyHolds`, #2545); a key the gateway would refuse is reported by Check and wired over, and so is the sharing key magpie itself made (`access.Default`), once sharing is off — magpie's own, however well the gateway still takes it. It's offered only where the gateway takes any key (`gwKey() == gateway.Token`: loopback, a WSL distro mirrored), not from a distro under NAT while magpie is shared on the network, where only the sharing key gets in. The choice is stashed, so it survives Disconnect and a port move. An empty token counts as magpie's only beside the address magpie last wrote (`claude.wired_at` in the stash, which Rewire carries to the new port, `keyOurs`): an endpoint of the user's own with an empty token stays theirs when the model goes back to Claude Code's own. - Claude Code's auto mode review (`CLAUDE_CODE_AUTO_MODE_SERVER`, `claudeReviewEnv` in [`claude.go`](../../internal/agent/claude.go)) is written `"0"` while Claude Code is routed through magpie, unless every model it can reach there surely gets Anthropic's results back (`claudeReviewed`, by `gateway.AutoModeAnswered`: a model `AutoModeReviewable` on the Claude subscription or on `api.anthropic.com` itself; a relay's Claude model, even on its Anthropic endpoint, may drop `safeguard_results`, and a Claude model asked on Chat or Responses never carries the review, nexnull on Discord, `TestClaudeReviewedOnlyWhereResultsComeBack`): those it is shown (and Claude Desktop's while Desktop is on magpie), a shown group's members, those providers' fallbacks, and the models it is set to, each judged on the provider (or group, or fallback) it resolves to, as the gateway judges its requests, so a Claude model on Copilot or Kiro writes `"0"` and a name magpie doesn't know is judged by the name (`TestClaudeReviewedJudgesTheSetModelWhereItGoes`). One model that doesn't answer is enough, since `/model` can take the session there; a model hidden from Claude Code doesn't count. Off, Claude Code runs its own classifier through the gateway (fitted to any model, `classifierStandIn`; the model is the Claude Code card's auto mode square, `CLAUDE_CODE_AUTO_MODE_MODEL`), which works on every model. Left on behind a route that doesn't answer, 2.1.322 doesn't fall back: with telemetry or feature flags off (`DISABLE_TELEMETRY`, `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, …) it denies each action it would check, "Auto mode can't check actions in this session … your requests go through 127.0.0.1:3425, which doesn't pass it through" (`auto_mode_no_check_in_session`), on a Claude model too when the session could also reach another model (JoyYoung2Lucky on X). Before this, any reviewed model left it unset, which is how a relay's Claude beside DeepSeek met that denial. It is rewritten on every model set and `Sync`, so adding a Claude provider turns the review back on. magpie's value is kept apart in the stash (`claude.auto_mode_server`), a user's own is left alone, and it goes when Claude Code is taken off magpie (`desktopOnly`, `unroute`). T3 Code's magpie instance, which runs Claude Code on the gateway through its own environment, carries the same `"0"` there by the models it lists (`t3InstanceJSON` in [`t3code.go`](../../internal/agent/t3code.go)); a value in the user's `~/.claude` settings comes after it. -- Claude Code's tool search (`ENABLE_TOOL_SEARCH`, `claudeSearchEnv` in [`claude.go`](../../internal/agent/claude.go)) is written `"true"` while Claude Code is routed through magpie. On, MCP tools are named in a reminder and loaded by `ToolSearch` when the model needs them, not sent whole on every request. Claude Code before 2.1.304 keeps it off behind an `ANTHROPIC_BASE_URL` other than Anthropic's, so the MCP router's tools all went on each request (cybercaius on Discord: 245 tools, 124K tokens of a 341K context; 2.1.290 through a sandbox gateway sent 242,346 bytes of tools, 27,443 with it on); 2.1.304 and later turn it on there themselves, and `"true"` also keeps it on in a conversation begun without it. The gateway carries deferred tools to every upstream (`Tool.Deferred`, `withoutDeferredTools`). magpie's value is kept apart in the stash (`claude.tool_search`); a value the user set, an empty one too, is theirs; it goes when Claude Code is taken off magpie (`desktopOnly`, `unroute`; `TestClaudeToolSearchOn`). T3 Code's magpie instance carries `"true"` in its environment unless the user gave it a value there (`TestT3CodeToolSearchOn`). +- Claude Code's tool search (`ENABLE_TOOL_SEARCH`, `claudeSearchEnv` in [`claude.go`](../../internal/agent/claude.go)) is written `"true"` while Claude Code is routed through magpie. On, MCP tools are named in a reminder and loaded by `ToolSearch` when the model needs them, not sent whole on every request. Claude Code before 2.1.304 keeps it off behind an `ANTHROPIC_BASE_URL` other than Anthropic's, so the MCP router's tools all went on each request (cybercaius on Discord: 245 tools, 124K tokens of a 341K context; 2.1.290 through a sandbox gateway sent 242,346 bytes of tools, 27,443 with it on); 2.1.304 and later turn it on there themselves, and `"true"` also keeps it on in a conversation begun without it. The gateway carries deferred tools to Anthropic upstreams and to a Responses upstream that loads them in place (`Tool.Deferred`, `withoutDeferredTools`); elsewhere it turns them away so Claude Code declares every tool and the prompt cache holds (`refusesDeferred`, gateway-routing.md). magpie's value is kept apart in the stash (`claude.tool_search`); a value the user set, an empty one too, is theirs; it goes when Claude Code is taken off magpie (`desktopOnly`, `unroute`; `TestClaudeToolSearchOn`). T3 Code's magpie instance carries `"true"` in its environment unless the user gave it a value there (`TestT3CodeToolSearchOn`). - Claude Desktop's Code tab gets tool search only with Desktop's own `toolSearchEnabled` policy on (3p only, off by default). Off, Desktop 2.7032 (`Ztr` "off") starts Claude Code with `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`, and Claude Code (2.1.312, 2.1.316: `oae` returns "standard") then keeps tool search off whatever `ENABLE_TOOL_SEARCH` says, so every MCP tool went whole on each request (bigcat1800 on Discord: 13 MCP servers, ~162K tokens; a sandbox CLI with 60 MCP tools sent 83 tools, 205KB). On, with the gateway provider and a bundled Claude Code of 2.1.247 or later, Desktop hands the CLI `ENABLE_TOOL_SEARCH=force` as a managed setting and the same CLI sent 13 tools, MCP ones behind `ToolSearch`, 56KB, asking only `tool-search-tool-2025-10-19` of the betas. magpie's profile gets `toolSearchEnabled: true` once, on a switch on and from Sync, as `claudeAiImport` is (`desktopSeedToolSearch`, `desktopSeedOnce`, mark `claude-desktop.tool-search`): a value the user set, false too, or took away since, stays theirs (`TestClaudeDesktopTurnsOnToolSearch`). A profile the user applied for magpie's gateway (`desktopAppliedGateway`) is not written. - Claude Desktop 5.11492 starts its Code tab's Claude Code with `CLAUDE_CODE_MAX_CONTEXT_TOKENS=200000` in its `--settings` file whenever the provider routes models itself, the gateway included (`Fcn`, `Lcn` in its app.asar; 4.16336 had none). Flag settings come before `~/.claude/settings.json`, so the window magpie writes there (`claudeContextEnv`) no longer reaches the Code tab: a 1M model picked by its plain entry ran at 200K (fwxkogaia on X, v0.1.4321). Claude Code takes a `[1m]` id for 1M whatever that variable says (2.1.322's `pT`), so magpie's profile gets Desktop's own "Use 1M wherever it's available" (`modelPrefer1mContext: true`, 3p only, Desktop 1.28929 and later) once, on a switch on and from Sync, as `toolSearchEnabled` is (`desktopSeedPrefer1M`, mark `claude-desktop.prefer-1m`; `TestClaudeDesktopPrefers1M`). Desktop then shows a model it offers a 1M entry for by that entry alone; it offers one only for a row whose `max_input_tokens` is 1M or more, so it does nothing for a smaller model. A model past 200K and under 1M that isn't Claude's (a 272K or 872K GPT) is listed by its `[1m]` id whatever `DesktopLongest` says (`desktopMidWindow` in [`desktop.go`](../../internal/gateway/desktop.go)), described by its own size ("872K context window"), because by its plain id it ran at 200K whatever its window was (RQuantum198888 on X: a GPT set to 872K showed 200K). Claude Code 2.1.326 then runs it in 1M (`peo` in `aV`, past the forced 200000), and it compacts within its own window through `modelSettings..autoCompactWindow` (`claudePlan`): the window the user typed whole, else the working window (`TestClaudeDesktopMidWindowRunsPast200K`). Its `/context` then reads "/ 872k" where the plain id read "/ 200k" (tried on 2.1.326 with Desktop's flag settings); a managed policy setting is the only thing that comes before flag settings, and magpie writes none. The user's own value, false too, or their taking it away, stays theirs. - OpenMausBot (`openmausbot.go`) runs each bot on an engine from `instances` in `~/.openmausbot/config.json` (`$OMB_DATA_DIR`, `server/config.ts` in its source). magpie writes the `magpie` engine as OpenMausBot's own Claude endpoint (`newClaudeEndpoint`, `claude-endpoints.ts`): driver `claudeAgent`, access `custom`, `config.configDir` under `providers/magpie` so OpenMausBot starts Claude Code with its own `CLAUDE_CONFIG_DIR` and strips account keys the engine doesn't set (`claudeEnvironment`, `claude.ts`), `ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN` and `ANTHROPIC_API_KEY` at the gateway, and magpie's models as `config.endpointModels`, kept to the ids OpenMausBot's `CLAUDE_MODEL_ID` accepts (one bad id makes it refuse the whole engine). A non-empty `instances` is the whole fleet, so with none saved magpie writes OpenMausBot's `DEFAULT_FLEET` beside it (`ombFleet`, stashed as `openmausbot.fleet`) and takes it out again on off if the user hasn't changed it (`TestOpenMausBotFleetChanged`). The name, a model picked from the list, other env and a `cli` are the user's. OpenMausBot reads the file once at start and writes back the fleet it holds whenever an engine is edited in it, so the switch is refused while it runs (`errOMBRunning`; not checked on Windows) and the notice asks to quit it first. That write-back, and an edit of magpie's engine there (`updateClaudeEndpoint` keeps only the model picked and its tiers), leave `endpointModels` without models picked in magpie, and no catalog change follows to sync it again: while magpie serves, `KeepOpenMausBotListed` runs the sync every 30 seconds when the saved list differs from magpie's (`ombListStale`; maxleebeta on Discord, 11-08: Antigravity's models missing from its search). A copy started before magpie's last change to the engine (`ombPart`: the gateway, the first model and the list) offers the row's Restart (`restartApps`, `OpenMausBot.app` and `OpenMausBot.exe`). Codex bots use `~/.codex`, which magpie's Codex wiring already covers. diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index ff743e7cf..afaf1ab8c 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -417,6 +417,7 @@ the key's leaves the call as asked, with a log line (`compactRefused`). - ToolSearch's answer is a `tool_result` whose content is `tool_reference` blocks alone. OpenDesign's Anthropic endpoint can't read one: 422 "Failed to deserialize the JSON body into the target type: messages[4]: missing field `content`" (#2124, the reporter's direct request without magpie fails the same way; the same result with a text block beside the references is taken). A provider that refuses in those words while the request holds such a result is asked again at once with a text block first in each, "Tool is loaded and can be called now." (`toolLoadedText`, the words a translated route already gives a model in `stringOrText`), the references and the `tool_use`/`tool_result` pairing kept, and is sent it that way while magpie runs (`refuseShapes`, `shapeRefsOnly`, `withRefsSaid`). This is in `forward`, so `/v1/messages`, `count_tokens` and a group's member all get it; a request translated to another API already carries the references as that text. Any other provider is sent the bare references (`TestRefsOnlyToolResultRefusedGetsText`, `TestRefsSaidLeavesOtherResults`). - An endpoint that reads only text and images in a `tool_result` refuses the references themselves: "DeepSeek V4.1 supports text and image content only; got 'tool_reference'" (emilochen on X, an Anthropic-compatible URL). A 400 or 422 that refuses `tool_reference` in words (`refsRefused`: a refusal word within the same clause, no brace between, so a request echoed back doesn't count, and "expected `tool_reference`" doesn't either) while the request as sent holds one in a `tool_result` is asked again at once with each reference as the text `toolLoadedText` gives, the tools they name sent without `defer_loading` (the rest stay deferred), and is sent it that way while magpie runs (`shapeRefs`, `withRefsAsText`; `deferredOutUpFront` is the same up-front strip `forwardOnce` makes for Kimi, DeepSeek's own API and OpenCode's DeepSeek). A refusal a deferred block's refusal explains, while such blocks are still sent, is that one's. Chat, Responses and Gemini upstreams already get the references as that text (`stringOrText`). (`TestToolReferenceRefusedGoesAsText`, `TestToolReferenceNamedOtherwiseLearnsNothing`, `TestRefsAsTextLeavesOthers`) - A tool Claude Code's ToolSearch loads, translated to a Responses API, used to join the top-level `tools` on the next request, which changed the prompt from its first bytes and missed the cache on every load (#2660). A deferred tool (`defer_loading`, `Tool.Deferred`) that a `tool_result`'s `tool_reference` names (`toolRefs`, `Part.Loads`) now goes, where `Request.LoadedInPlace` is set, in an `{"type":"additional_tools","role":"developer","tools":[…]}` item right after the run of tool outputs that loaded it, once, and not in `tools` (`buildResponses`): tools loaded by parallel results or one result naming several share one item, a tool named again isn't repeated, and the tool output's text is as before. OpenAI's tool search guide documents the item and that its tools load at the end of the context so the cache is kept. A compacted or edited history whose loading result is gone puts the tool back in `tools`, a new prefix, as is expected. `LoadedInPlace` is set (`loadsInPlace`, in `forwardTranslated`) for OpenAI's own API with a key (`api.openai.com`, `*.api.openai.com`), for a ChatGPT (Codex) account, and for a provider set `additionalTools` (`magpie provider set additional-tools=on`); `additional-tools=off` (`additionalToolsOff`) turns it off even where it is the default, and `default` goes back to magpie's. The ChatGPT backend was tried with a real account (#4738, gpt-5.6-terra, gpt-6-luna, gpt-6-sol): it takes the item where it was loaded, the model calls the tool in it, and the next request read 7680–7936 tokens from cache where, with the tool moved into `tools`, it read none. Nothing else is sent it by default, since xAI answers the item 422 (#350), and no relay, other vendor's sign-in (Copilot) or plugin's vendor has been tried. An upstream that refuses a request holding the item with a 400 or 422 naming `additional_tools` is asked again with every tool in `tools`, logged ("turned away additional_tools … loaded tools go in tools from now on") and not sent the item again while magpie runs. Not handled: a tool a `tool_addition` block loads (an MCP server's late tool, the advisor) stays in `tools`. `TestLoadedToolsKeepThePrefix`, `TestLoadedToolsInOneItem`, `TestLoadedToolsWhereNotTaken`, `TestLoadsInPlaceScope`, `TestLoadedToolsThroughTheGateway`, `TestCodexAccountLoadsInPlace`. +- Where a loaded tool can't go in place, Claude Code's deferred tools are turned away (`refusesDeferred` in [`deferred_route.go`](../../internal/gateway/deferred_route.go)), since every load changed the prompt from its first bytes and the conversation was read again uncached (Seapawn1 on X: GPT in Claude Code loses its cache with tool search on; 2.1.327 defers WebFetch, WebSearch, Monitor and the other built-ins too, so loads are frequent). A request from Anthropic's Messages with Claude Code's `DeferredToolPlaceholder` (`Request.DeferredNamed`), asked on Chat, Gemini or a Responses upstream without `LoadedInPlace`, is answered 400 `invalid_request_error` naming `tools.defer_loading` (`deferredRefusal`), without reaching the upstream. Claude Code (2.1.327, tried with the real binary) takes a 400 that names `defer_loading` as the endpoint not taking deferred tools: after its own beta-strip retries it asks again with every tool declared in full, and keeps that for the rest of the conversation, `--continue` included, so the tools are those of its first request and the prefix holds. A new conversation tries tool search again, so one on a Claude model on Anthropic's API, or on a Responses upstream that loads in place, keeps it. The message doesn't name the tool search beta, which Claude Code would remember for every conversation. Only while the tools its reminder names ("The following deferred tools are now available via ToolSearch", one a line, `deferredCount`) are 50 or fewer (`maxDeferredDeclared`, about the tenth of a 200K context Claude Code's own auto mode allows tool definitions): a longer list, an MCP router's hundreds, keeps tool search and loses the cache at a load as before, and so does a request whose reminder can't be found. The refusal is about the request, so a group doesn't fall to its next member for it, and nothing rests. A user's own `ENABLE_TOOL_SEARCH` can't be told apart on the wire; `additional-tools=on` keeps tool search on a Responses relay that takes the item. `TestDeferredToolsTurnedAwayWhereTheyLoseTheCache`, `TestDeferredToolsKeptWhereLoadedInPlace`, `TestDeferredToolsKeptOnAnthropic`, `TestDeferredCount`. - A Responses upstream that wants a turn's reasoning back (`replaysReasoning` in [`responses.go`](../../internal/gateway/responses.go): a model with `deepseek` in its name, on any host but OpenAI's, xAI's, Copilot's and Azure's) gets every reasoning item with a `reasoning_text` and every tool call after one, relayed (`withReasoningText` in `passthrough`) or translated (`buildResponses`). DeepSeek's `/v1/responses` turns the whole request away ("The `reasoning_text` in the thinking mode must be passed back to the API") over a reasoning item without text, one with an empty text, and a `function_call` whose step (since the last user message or tool output) has no reasoning item. Codex sends all three in a routing group that falls to DeepSeek after ChatGPT: the backend's sealed items (`encrypted_content` only), magpie's summary-only items, and another member's calls with none (#1104, #1592). DeepSeek reads a step (a run of reasoning, assistant messages and calls) as one assistant message whose thinking is the item it starts with: in the current turn, a step with a call or after a tool output must lead with a reasoning item, so [message, reasoning, call] and [output, message] are refused while [reasoning, message, call] and [output, reasoning, message] are taken (checked against api.deepseek.com on 2026-10-12). Codex sends a step that said something before its call with no reasoning for another model's turn, which magpie used to send [message, reasoning " ", call] and DeepSeek refused intermittently, only while the turn lasted (#1822, through OpenCode Go). An item's own text is kept; one without gets its summary, else a space (`noReasoning`); each such step leads with its reasoning (`reasonFirst`): its own first reasoning item moved ahead, else one holding a space. A sealed item keeps its id and `encrypted_content`; a body already in that shape goes byte for byte. A channel that turns a reasoning item without an id away (a DeepSeek channel's 422 "Input tag 'reasoning' found using 'type' does not match any of the expected tags: 'message', 'tool_result'", `idlessReasoningRefusal`) is asked once more without such items, relayed or translated, and not sent one again (`idlessReasoningRefused`, `withoutIDlessReasoning`); items with an id still go. The refusal is a shape (`shapeWords`), so a group's next member, DeepSeek's own API among them, is asked and the member doesn't rest (`TestIdlessReasoningRefusedByChannel`, `TestGroupFailsOverIdlessReasoningRefusal`). - A Messages upstream that wants a turn's thinking back (`anthropicReplaysThinking` in [`anthropic.go`](../../internal/gateway/anthropic.go): a host or a model with `deepseek` in it, never `api.anthropic.com` or a Claude model) gets a thinking block on every assistant message with a `tool_use` or right after tool results alone (refused the same way, checked 2026-10-12, #1822), relayed (`withThinkingOnToolTurns` in `passthrough`) or translated (`build`, which also keeps unsigned thinking as its text there). DeepSeek's `/anthropic/v1/messages`, thinking (its default, or asked for), turns the whole request away with 400 "The `content[].thinking` in the thinking mode must be passed back to the API" when such a message has none, and answers any `redacted_thinking` with 422, a block it can't read. Claude Code sends both in a routing group that falls to DeepSeek after Claude (#1611). A message with no thinking gets one holding a space (`noReasoning`) first; Claude's `redacted_thinking` becomes that block, or is left out beside thinking of the message's own. Signed thinking, DeepSeek's own and every other message go as they came. Checked against the real endpoint on 2026-10-11: it takes Claude's signed thinking, unsigned thinking and a space, anywhere in the message. A thinking block magpie sends unsigned (the space, or a turn's reasoning kept as its text) says `"signature": ""`, as `aBlock` writes `thinking` even when empty: OpenRouter's `/api/v1/messages` holds a block's signature to a string and turns a DeepSeek request with none away, 400 "Invalid Anthropic Messages API request" (#2883, #3696), and DeepSeek's own endpoint takes the empty one (checked 2026-10-19). `TestOpenRouterDeepSeekThinkingHasASignature`. - A Messages or Chat upstream whose host and model don't say DeepSeek but whose model answers 400 "The `content[].thinking` (or `reasoning_content`) in the thinking mode must be passed back to the API" (`thinkingBackRefusal` in [`thinking_back.go`](../../internal/gateway/thinking_back.go)) is asked once more with its tool turns filled as above (`withThinkingOnToolTurns`, `withReasoningOnToolTurns`), and that provider's model is sent them at once from then on (`thinkingBackNeeded` in `unfit`, filled in `forwardOnce`), on every route to it. A relay serving DeepSeek under another name, or a provider the user named "My Claude", got a routing group's fall from a rate-limited Codex subscription mid tool loop refused, Codex's sealed reasoning having no text to give (qisishiqi on Discord, 2026-11-02). Checked against api.deepseek.com on 2026-11-02: only the tool loop being continued needs it; finished turns and plain replies are taken without. A provider that never asked is sent the turns as before. `TestThinkingBackLearnedBehindAnotherName`, `TestReasoningBackLearnedBehindAnotherName`. diff --git a/internal/agent/claude.go b/internal/agent/claude.go index 7da20428a..8ff9b401e 100644 --- a/internal/agent/claude.go +++ b/internal/agent/claude.go @@ -373,7 +373,10 @@ const claudeReviewEnv = "CLAUDE_CODE_AUTO_MODE_SERVER" // (cybercaius on Discord). 2.1.304 and later turn it on there themselves; // "true" also keeps it on in a conversation begun without it, which // Claude Code otherwise holds off until it is compacted. The gateway -// carries deferred tools to every upstream (#2660, anthropic_shapes.go). +// carries deferred tools to Anthropic upstreams and loads them in place on +// a Responses upstream that takes it (#2660); elsewhere it turns them away, +// and Claude Code declares every tool for that conversation, so a load +// doesn't cost the prompt cache (gateway/deferred_route.go). // One the user set is theirs. const claudeSearchEnv = "ENABLE_TOOL_SEARCH" diff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.go index e9d434cf1..432f10ce3 100644 --- a/internal/gateway/anthropic.go +++ b/internal/gateway/anthropic.go @@ -316,6 +316,7 @@ func readAdvised(body []byte, clientMarks, facts, advised bool) (*Request, error } if t.Name == "DeferredToolPlaceholder" { // only keeps Anthropic's deferred loading on; never to be called + r.DeferredNamed = true continue } r.Tools = append(r.Tools, Tool{Name: t.Name, Description: t.Description, Schema: t.InputSchema, Deferred: t.DeferLoading}) diff --git a/internal/gateway/deferred_route.go b/internal/gateway/deferred_route.go new file mode 100644 index 000000000..bbdea0542 --- /dev/null +++ b/internal/gateway/deferred_route.go @@ -0,0 +1,107 @@ +package gateway + +import ( + "strings" + + "github.com/yetone/magpie/internal/provider" +) + +// Claude Code with tool search on (ENABLE_TOOL_SEARCH, which magpie writes +// "true", and which 2.1.304 and later turn on behind a gateway by +// themselves) names its deferred tools in a reminder and declares one only +// once ToolSearch loaded it: from that request on the tool is in the +// request's tools. Anthropic's Messages API keeps a deferred tool out of +// the cached prefix, and an OpenAI Responses upstream that takes an +// additional_tools item is given it there, after the result that loaded +// it (Request.LoadedInPlace, #2660). Every other route has only the +// top-level tools for it: Chat Completions, a Responses relay, Gemini. An +// OpenAI-style prompt cache is a prefix, with the tools before the +// messages, so each tool loaded there changed the start of the prompt and +// the whole conversation was read again uncached (Seapawn1 on X: GPT in +// Claude Code loses its cache with tool search on). WebFetch, WebSearch +// and the other deferred built-ins are loaded that way too, so it happens +// often. +// +// On such a route magpie turns the deferred tools away with a 400 that +// names defer_loading, which Claude Code answers by asking again with +// every tool declared in full, for the rest of that conversation: the +// tools stay as they were from the first request, and the cache holds. A +// conversation on a Claude model, on Anthropic's API, keeps tool search, +// and so does one on a Responses upstream that loads in place. Only a +// request with Claude Code's DeferredToolPlaceholder is turned away (a +// client that declares its deferred tools whole has a stable prefix +// already), and only while the tools it named are few enough to declare: +// a long list, such as an MCP router's hundreds, would fill the context on +// every request (cybercaius on Discord: 245 tools, 124K tokens), so it +// keeps tool search, and loses the cache on a load as before. + +// deferredRefusal is the message of a 400 Claude Code takes as the +// endpoint not taking deferred tools (it looks for defer_loading). +const deferredRefusal = "tools.defer_loading: deferred tools are not loaded in place on this route, so a tool loaded later would change the start of the prompt and lose its cache; ask again with every tool declared in full" + +// maxDeferredDeclared is how many deferred tools Claude Code may be asked +// to declare in full: at about 400 tokens a tool, 50 are the tenth of a +// 200K context that Claude Code's own auto mode lets tool definitions take +// before it searches for them. +const maxDeferredDeclared = 50 + +// deferredAnnouncement opens Claude Code's reminder listing its deferred +// tools, one name a line (2.1.327). +const deferredAnnouncement = "The following deferred tools are now available via ToolSearch" + +// deferredCount is how many tools Claude Code's reminders name as +// deferred, each once, and whether a reminder was found at all. +func deferredCount(r *Request) (int, bool) { + names := map[string]bool{} + found := false + see := func(s string) { + for { + i := strings.Index(s, deferredAnnouncement) + if i < 0 { + return + } + found = true + s = s[i+len(deferredAnnouncement):] + // the names start on the line after the announcement + nl := strings.IndexByte(s, '\n') + if nl < 0 { + return + } + s = s[nl+1:] + for s != "" { + line, rest, _ := strings.Cut(s, "\n") + line = strings.TrimSpace(line) + if line == "" || strings.HasPrefix(line, "<") { + break + } + names[line] = true + s = rest + } + } + } + see(r.System) + for _, m := range r.Messages { + for _, p := range m.Parts { + if p.Kind == Text { + see(p.Text) + } + } + } + return len(names), found +} + +// refusesDeferred is whether a Claude Code request with deferred tools is +// turned away on its way to p over to (deferredRefusal): from Anthropic's +// Messages to another API, where the tools it loads couldn't be given in +// place, and naming few enough tools to declare. One whose reminder can't +// be found or read keeps tool search, as it did. +func (s *Server) refusesDeferred(p provider.Provider, from, to provider.Protocol, model string, r *Request) bool { + if from != provider.Anthropic || to == provider.Anthropic || !r.DeferredNamed { + return false + } + if to == provider.Responses && loadsInPlace(p) && s.fits(p.ID, additionalToolsItem, to) { + return false + } + n, ok := deferredCount(r) + return ok && n <= maxDeferredDeclared +} diff --git a/internal/gateway/deferred_route_test.go b/internal/gateway/deferred_route_test.go new file mode 100644 index 000000000..f0f2e953c --- /dev/null +++ b/internal/gateway/deferred_route_test.go @@ -0,0 +1,137 @@ +package gateway + +import ( + "fmt" + "net/http/httptest" + "strings" + "testing" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/provider" +) + +// ccDeferred is Claude Code 2.1.327's reminder naming its deferred tools, +// as a sandboxed run with three MCP tools sent it. +func ccDeferred(names ...string) string { + return "The following deferred tools are now available via ToolSearch. Their schemas are NOT loaded — calling them directly will fail with InputValidationError. Use ToolSearch with query \"select:[,...]\" to load tool schemas before calling them:\n" + + strings.Join(names, "\n") + "\n\nAvailable agent types for the Agent tool:\n- claude: Catch-all" +} + +var ccDeferredNames = []string{"CronCreate", "CronDelete", "CronList", "EnterWorktree", "ExitWorktree", "Monitor", "NotebookEdit", "SendMessage", "TaskStop", "WebFetch", "WebSearch", "mcp__fk__alpha", "mcp__fk__beta", "mcp__fk__gamma"} + +func ccSearchRequest(names []string, tools ...string) string { + reminder := fmt.Sprintf(`{"role":"user","content":[{"type":"text","text":%q},{"type":"text","text":"hi"}]}`, ccDeferred(names...)) + return tsRequest(append([]string{tsTools0}, tools...), reminder) +} + +// Seapawn1 on X: GPT in Claude Code loses its prompt cache with tool +// search on. A tool ToolSearch loads joins the request's tools on a Chat +// route, before every message, so the start of the prompt changed at each +// load. Such a route turns the deferred tools away with a 400 naming +// defer_loading, which Claude Code answers with every tool declared in +// full; a route that loads in place, an Anthropic one, a list too long to +// declare and a request without Claude Code's placeholder go as before. +func TestDeferredToolsTurnedAwayWhereTheyLoseTheCache(t *testing.T) { + ok := sse( + `data: {"id":"c1","model":"m1","choices":[{"index":0,"delta":{"role":"assistant","content":"ok"}}]}`, + `data: {"id":"c1","model":"m1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":1}}`, + `data: [DONE]`) + f := &fake{t: t, reply: ok} + setup(t, provider.Chat, f) + + body := ccSearchRequest(ccDeferredNames, tsPlaceholder) + code, out := post(t, "/v1/messages", body) + if code != 400 || !strings.Contains(out, "defer_loading") || f.calls != 0 { + t.Fatalf("Chat route: status %d, %d upstream calls: %s", code, f.calls, out) + } + if gjson.Get(out, "type").String() != "error" || gjson.Get(out, "error.type").String() != "invalid_request_error" { + t.Fatalf("not an Anthropic invalid_request_error: %s", out) + } + // the beta header named would make Claude Code drop tool search for + // every conversation, a Claude model's too + if strings.Contains(out, "anthropic-beta") || strings.Contains(out, "tool-search") || strings.Contains(out, "advanced-tool-use") { + t.Fatalf("the refusal names the beta: %s", out) + } + + // Claude Code's retry: every tool declared, no placeholder + full := ccSearchRequest(ccDeferredNames, tsReadA, tsReadB) + if code, out := post(t, "/v1/messages", full); code != 200 { + t.Fatalf("the retry with every tool declared: status %d: %s", code, out) + } + if n := len(gjson.GetBytes(f.got, "tools").Array()); n != 4 { + t.Fatalf("the retry reached the upstream with %d tools: %s", n, f.got) + } + + // hundreds of deferred tools, an MCP router's, keep tool search + many := make([]string, 300) + for i := range many { + many[i] = fmt.Sprintf("mcp__router__t%d", i) + } + f.calls = 0 + if code, out := post(t, "/v1/messages", ccSearchRequest(many, tsPlaceholder)); code != 200 || f.calls != 1 { + t.Fatalf("300 deferred tools: status %d, %d calls: %s", code, f.calls, out) + } + // no reminder to count from: unknown, so tool search stays + f.calls = 0 + if code, out := post(t, "/v1/messages", tsRequests[1]); code != 200 || f.calls != 1 { + t.Fatalf("no reminder: status %d, %d calls: %s", code, f.calls, out) + } +} + +// A Responses upstream that takes additional_tools keeps tool search: the +// tools it loads go in place, and the prefix holds (#2660). +func TestDeferredToolsKeptWhereLoadedInPlace(t *testing.T) { + f := &fake{t: t, reply: sse( + `data: {"type":"response.created","response":{"id":"r1","model":"m1"}}`, + `data: {"type":"response.completed","response":{"id":"r1","output":[],"usage":{"input_tokens":5,"output_tokens":2}}}`)} + setup(t, provider.Responses, f) + body := ccSearchRequest(ccDeferredNames, tsPlaceholder) + if code, out := post(t, "/v1/messages", body); code != 400 || !strings.Contains(out, "defer_loading") { + t.Fatalf("a Responses relay without additional_tools: status %d: %s", code, out) + } + p, err := provider.Find("fake") + if err != nil { + t.Fatal(err) + } + p.AdditionalTools = true + if err := provider.Save(*p); err != nil { + t.Fatal(err) + } + if code, out := post(t, "/v1/messages", body); code != 200 { + t.Fatalf("a relay that takes additional_tools: status %d: %s", code, out) + } +} + +// A Claude model on Anthropic's API keeps tool search. +func TestDeferredToolsKeptOnAnthropic(t *testing.T) { + f := &fake{t: t, ctype: "application/json", reply: `{"id":"msg_1","type":"message","role":"assistant","model":"m1","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`} + setup(t, provider.Anthropic, f) + if code, out := post(t, "/v1/messages", ccSearchRequest(ccDeferredNames, tsPlaceholder)); code != 200 || !strings.Contains(string(f.got), "DeferredToolPlaceholder") { + t.Fatalf("status %d: %s\nsent %s", code, out, f.got) + } +} + +func TestDeferredCount(t *testing.T) { + r, err := parseAnthropic([]byte(ccSearchRequest(ccDeferredNames, tsPlaceholder))) + if err != nil { + t.Fatal(err) + } + if n, ok := deferredCount(r); !ok || n != len(ccDeferredNames) { + t.Fatalf("count = %d %v, want %d", n, ok, len(ccDeferredNames)) + } + if !r.DeferredNamed { + t.Fatal("the placeholder was not seen") + } + // the refusal is about the request: a group doesn't fall to its next + // member for it, nor rest the account + if body := []byte(writeErrorBody(deferredRefusal)); retryable(400, body) || shapeRefused(400, body) { + t.Fatal("the refusal reads as a member's fault") + } +} + +func writeErrorBody(msg string) string { + rec := httptest.NewRecorder() + writeError(rec, provider.Anthropic, 400, msg) + return rec.Body.String() +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index a774d1cfc..99780cfe9 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -9608,6 +9608,11 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr // told, not left out for the model to answer the words alone (#6135) return writeError(w, from, 400, msg), msg } + if s.refusesDeferred(p, from, to, model, request) { + // Claude Code asks again with every tool declared, so a tool it + // loads doesn't change the prompt's start (deferred_route.go) + return writeError(w, from, 400, deferredRefusal), deferredRefusal + } stream := request.Stream request.Stream = true if stream { diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go index e472a6b95..9d26f98e3 100644 --- a/internal/gateway/ir.go +++ b/internal/gateway/ir.go @@ -439,6 +439,11 @@ type Request struct { // and the conversation sent before stay as they were, so its prompt // cache does (#2660). Every other upstream gets them in tools. LoadedInPlace bool + // DeferredNamed is set on a Claude Code request carrying its + // DeferredToolPlaceholder: its deferred tools are named in a + // reminder and declared only once ToolSearch loads them + // (deferred_route.go). + DeferredNamed bool // CR is set when the model asked is one of the glm-5.3-flash* routes // whose replicas stitch CR into a call's arguments (#4256): the // arguments reach the client with the stitched CR dropped