gateway: Claude Code's advisor runs in magpie for a model whose upstream can't (Awad_Yoo on X)

Claude Code 2.1.316 sends its advisor (/advisor, settings.json's
advisorModel) for any model when CLAUDE_CODE_ENABLE_EXPERIMENTAL_ADVISOR_TOOL
is set: an advisor_20260301 server tool, which only Anthropic's server
runs. Until now magpie left it out for every other upstream (b6fae8efd).

Now, when the advisor model is one magpie serves and the upstream can't
run it (not a Claude model on Anthropic's API with a same-provider Claude
advisor, which keeps the native passthrough), magpie runs it:
- the model is offered an "advisor" function tool with no parameters;
- a call is answered by asking the advisor model, through magpie's own
  routing, with the conversation so far and a short ask after it (up to 3
  calls a reply, then max_uses_exceeded, as Anthropic answers);
- the client gets the server_tool_use and advisor_tool_result blocks
  Anthropic writes (advisor_tool_result_error with its error_code on a
  failure), and the history Claude Code echoes back is read as a call and
  its result.
Claude Code's system prompt, identity text and its own advisor
instructions go upstream as it wrote them; nothing about the advisor is
added to the prompt beside the tool's neutral description.

Claude Code's agent row gets an Advisor line under Tiers, after Auto
mode, default Off: picking a model writes advisorModel and the env switch
(only when the user hasn't set it themselves); Off removes both, and so
does disconnecting. CLI: magpie claude advisor <model|default>.

Run (on the Linux box, xiaomi-gpu magpie-desktop, at this head; mote was
over its load the whole time and mica's disk is full):
- go vet ./internal/gateway ./internal/agent, and with GOOS
  linux/windows/darwin (CGO_ENABLED=0); gofmt -l clean
- go test ./internal/gateway -run 'Advisor|Advised|Search|Anthropic': ok
- go test ./internal/agent -run Claude: ok
- node --test claude-advisor, claude-auto-mode, i18n-keys,
  i18n-en-no-cjk (Chromium + WebKit, en and zh, 1100 and 560px): 24/24
- TestCoreScriptBudget measured by its own rule: app.js 1,084,341 of
  1,086,267, core 1,267,726 of 1,267,762 (no raise)
- Real Claude Code 2.1.316 in a sandbox HOME/CLAUDE_CONFIG_DIR against a
  sandbox `magpie serve` (darwin nogui build of this tree) with only the
  DeepSeek provider: `magpie claude advisor deepseek/deepseek-v4-pro`
  wrote advisorModel + the env; `claude -p --model deepseek/deepseek-flash`
  asked to consult the advisor got text, server_tool_use (srvtoolu_…),
  advisor_tool_result with deepseek-v4-pro's advice (usage row: v4-pro
  11,205 in / 221 out), then its answer quoting it. A --resume turn sent
  that history back and completed.

Broken by hand:
- advisedHere returning false: TestAdvisorServedForAVendorModel,
  TestAdvisorHistoryGoesBackAsACall, TestAdvisorFailureIsAnErrorCode,
  TestAdvisedHere and TestAdvisorModelAsTheUpstreamNamesIt red.
- the env write left out of the advisor field's Set:
  TestClaudeAdvisorModel red.

Not tried: the interactive TUI's /advisor picker (only -p and the
settings.json route); an advisor on a Chat-only or Responses upstream
with a real account (the fake upstream in the tests is Chat); an advisor
call in the same round as a client tool call, which is dropped as a
search call is. Seen on the way, not changed: in the fresh sandbox,
Claude Code's own "sonnet[1m]" default resolved to sonnet-4-5-20250929
rather than ANTHROPIC_DEFAULT_SONNET_MODEL without --model.
This commit is contained in:
yetone
2026-11-13 15:31:06 +08:00
parent e5c793ebb1
commit db9a5ec7c4
15 changed files with 1058 additions and 38 deletions
+1
View File
@@ -141,6 +141,7 @@ something else shows up as drift.
- While this machine's Claude Desktop is on magpie, Claude Code's shared settings get `CLAUDE_CODE_DISABLE_EXPLORE_INHERIT_CAP="1"` (`writeExplore` in `claudeIn`, [`claude.go`](../../internal/agent/claude.go)). Claude Code 2.1.295's Explore inherit cap can otherwise replace Desktop's `mythos-magpie` compatibility alias with Opus. This disables that cap, not the model choices of all subagents. It applies with Desktop alone or beside a connected Claude Code, including model picks and Sync; WSL twins do not get it. A user's existing value, including an empty string, stays. The stash (`claude.explore_inherit_cap`) marks only magpie's value: taking Claude Code off magpie leaves it while Desktop is on, and taking Desktop off removes it only if the user has not changed it. Since the settings file is shared, other Claude Code sessions reading it see the flag while Desktop is connected too.
- Claude Code's tier and subagent models the user had set for their own endpoint (`claudeOwnEnv`) are stashed with that endpoint and token when magpie is wired in, and come back with them when magpie steps out, by Disconnect or by Claude Code's own model (#1050). So does their main model in the env (`ANTHROPIC_MODEL`, a Bedrock model id beside `CLAUDE_CODE_USE_BEDROCK` for one), which magpie takes out while wired in because it outranks a pick in `/model`. A model name of magpie's is never one of them (`claudeMagpieModel`): it is neither stashed as the user's nor given back from a stash an older magpie wrote, and a Claude Code on Anthropic's own endpoint (no `ANTHROPIC_BASE_URL`) has any left in its model or its env's models taken out by `Sync` at each start and when magpie steps out (`dropStray`), since Anthropic answers one with a 404 (roswellcsy on X: "There's an issue with the selected model (claude/claude-opus-5-5)" from `ANTHROPIC_MODEL`, given back on every Disconnect). Magpie's wiring at a gateway address since changed (its key, `keyOurs`) goes whole when magpie steps out, by Disconnect too. An endpoint of the user's own may name its models so, and they stay (`TestClaudeOffLeavesNoMagpieModel`).
- Claude Code's auto mode field (`auto_mode`, `claudeAutoModeEnv` in [`claude.go`](../../internal/agent/claude.go)) is `CLAUDE_CODE_AUTO_MODE_MODEL`, the model Claude Code 2.1.302's client-side auto mode classifier judges each action with (Linka on Discord). It changes nothing about server-side auto mode, and a classifier model Anthropic configures for the account comes before it. Unset, Claude Code picks its own (the sonnet tier's model, else Sonnet), so it follows no field and isn't `Follows`. It is set only while Claude Code is routed through magpie, only to one of magpie's models, dashed as the other model keys are, and never to Sonnet 5.5, Opus 5.5 or Opus 5 (`claudeNoClassifier`), which Claude Code 2.1.303 refuses there and replaces with its own pick. A value the user had before magpie routed Claude Code is stashed and taken out with their tiers (`claudeOwnEnv`), and comes back when magpie steps out, unless they set one again since; magpie's own value (`claude.auto_mode_model` in the stash, or any of magpie's models) goes then, and one the user set while wired in is left alone. Claude Code reads it as it goes, so it is Quiet and needs no restart.
- Claude Code's advisor field (`advisor`, Label `advisor model`, `claudeAdvisorEnv` in [`claude.go`](../../internal/agent/claude.go)) writes settings.json's `advisorModel`, as `/advisor` does, and `CLAUDE_CODE_ENABLE_EXPERIMENTAL_ADVISOR_TOOL=1`, without which Claude Code 2.1.316 sends the advisor only for Anthropic's own models by their names (Awad_Yoo on X). Unset by default, off. It is set only while Claude Code is routed through magpie and only to one of magpie's models, dashed as the other model keys are; the gateway runs the advisor where the upstream can't (gateway-routing.md). The switch is magpie's only when magpie wrote it (`claude.advisor_env` in the stash): clearing the field or magpie stepping out takes `advisorModel` (when it is one of magpie's models) and magpie's switch away, and leaves a switch the user wrote. It shows as the Advisor row under Claude Code's Tiers, beside Auto mode. Quiet: Claude Code reads both as it starts. `TestClaudeAdvisorModel`, `TestClaudeAdvisorUserSwitch`.
- 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.<var>`, 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.
+2 -1
View File
@@ -403,7 +403,8 @@ recorded as a prediction failure (`noPrediction`).
- Claude Desktop's `/v1/models` tags a model with `anthropic_family_tier` only when the user picked it for that tier (`DesktopTiers`, the Agents page's opus, sonnet, haiku and fable). Before, a Claude model magpie served was tagged with its own tier unpicked, so Desktop's Code tab told Claude Code to run its haiku calls (its small, fast model) on whichever provider served a `claude-haiku-…`: a chat on AgentRouter's gpt-6.1-sol sent them to Leee's `claude-haiku-5-5` (cybercaius on Discord). Untagged, Claude Code asks for its own id of the tier. A background call (no tools) or a subagent's turn asking for a Claude model by Claude's own id that is no catalog id (`claudeOwnID`) stays on the chat's provider (`desktopPicked`), even when another provider serves a model of that name: `servedBeside` gives that provider's model of that name, else its newest model of the tier, beside the chat's model first, else the call goes to the chat's model. The provider's Claude models stand in only when the chat itself is on one of them: a chat on Leee's DeepSeek had Claude Code's sonnet calls sent to Leee's `claude-sonnet-5-5`, which its key may not use (403, CyberCaius on Discord), so Claude Code's own calls in a chat on another vendor's model go to the chat's model, and a tier the user picked takes Claude Code's own id of it even where a provider lists a model by that name (`TestClaudeDesktopNonClaudeChatKeepsTierCalls`). A lead's turn and an id the user picked for a tier (a catalog id) go as asked. `TestClaudeDesktopBackgroundStaysOnChatProvider`.
- While a model is picked for one of Claude Desktop's tiers, magpie's Desktop profile also lists Desktop's models in `inferenceModels` (`DesktopInferenceModels` in [`desktop_list.go`](../../internal/gateway/desktop_list.go)), so a pick that isn't a Claude model runs in the Code tab with the prompt of its tier's newest Claude model (`behavesAs`: `claude-opus-5-5`, `claude-sonnet-5-5`, `claude-haiku-5-5`, Desktop's catalog v3739; `claude-fable-5-2`, Claude Code 2.1.321's newest Fable, which Desktop's catalog v4371 doesn't list yet), not Claude Code's generic one (moer2831 on Discord). Desktop 4.29 and later hand Claude Code `behavesAs` only from that list (z3t in its app.asar, 4.4212: `modelPicker.options` with each entry's `behavesAs`); the gateway's `behaves_as` row field feeds Desktop's own effort profile only. A non-empty list replaces `/v1/models` in Desktop's menus (pzn: a discovered row gives only its name and description, by id), so the list is every row `/v1/models` gives Desktop, by its id and in its order, each with what Desktop would have read off the row: `supports1m` for a window of 1M and up, `prefer1m` (and the row's `display_name` as `labelOverride`, where Desktop names the row by display_name) for a model listed by its `[1m]` id, and a pick's `anthropicFamilyTier` with `isFamilyDefault`. Desktop keys the list by name and reads one tier off an entry (FPn in its app.asar, 4.23118: the entry tagged with a tier names its `ANTHROPIC_DEFAULT_<TIER>_MODEL`), so a model picked for two tiers is tagged with the first (`desktopTierOf`). Each later tier (`desktopSharedTiers`) gets the model's id form under a number of its own (`desktopTierAlias`: magpie-<number>.anthropic.<model>, mythos-magpie-<number> or anthropic/magpie-<number>), which `aliased` reads back to the model, so the gateway serves it as the pick (`desktopTierAsked`). That id is a row of Desktop's `/v1/models` only (`DesktopTierRows`, a copy of the model's row tagged `anthropic_family_tier` and `is_family_default`), never a list entry: the list is Desktop's model menu, and an entry there showed as a model of its own, "Gemini 4 Hydrogen · haiku" beside "Gemini 4 Hydrogen" (yanghonghang on X, v0.1.3997). Desktop's discovery pins a tier the list leaves out from a tagged row (`shortnameIdentityOverrides` in its app.asar, 4.23118, under the list's own pins), and with a list it reads `/v1/models` only when the profile says `modelDiscoveryEnabled`, which magpie's profile carries while a tier is shared (`DesktopDiscovers`). The later tier has no `behavesAs`, which Desktop takes only from the list, so a model that isn't Claude runs there on Claude Code's generic prompt. Before, the later tier had no model: copilot/claude-sonnet-5.5 picked for sonnet and haiku gave Claude Code an empty `ANTHROPIC_DEFAULT_HAIKU_MODEL`, and its small tasks, WebFetch's page summaries among them, ran on the session's model. A Claude model picked runs as itself where Claude Code knows it by the id it is listed by; a routing group led by one is listed by its mythos-magpie-<number> and runs as the group's model, as one listed by anthropic/magpie-<number> does (`desktopRunsAs`; `TestDesktopTierSharedPick`, `TestDesktopGroupPickRunsAsItsModel`). Nothing picked (or a pick of a model no longer listed): no list, and Desktop finds the models as before. Picks that can't be read are unknown, and what is written stays. Older builds take the entries' names and drop the rest (2.7032's entry is a zod object, which strips unknown keys). Desktop reads its profile only as it starts, so the tiers' menu says to restart it, and the Agents row's Restart shows (`AppBehind` reads the profile). `TestDesktopInferenceModels`.
- Antigravity answers a system instruction holding one of a few lines with a 429 "Resource has been exhausted" whatever quota is left, on every model (`agTurnedAway` in [`codeassist.go`](../../internal/gateway/codeassist.go)): Claude Code's billing line, the Claude Agent SDK's identity line, Codex's identity lines for its GPT-5 models (which a Codex thread begun on a GPT model keeps after a switch), and Hermes Agent's earlier default persona. An Antigravity account's system instruction goes with zero-width spaces after the first and second character of every word of each such line (`antigravityCloak`, in `codeAssistBody`; one after the first letter only was turned away again on 11-11 for Claude Code's two lines, with Claude Code 2.1.316's prompt on a real account), which Google lets through and the model reads the same; every other provider, Gemini CLI's sign-in on the same envelope included, is sent the prompt as written. `magpie provider set antigravity prompt=as-written` (`Provider.PromptAsWritten`) turns it off. The refusal is still told against the system prompt as the agent wrote it (`antigravityTurnedAway`): a 400 with the hint for that prompt, the account not rested, and a group skipping Antigravity for that prompt for 6 hours after a refusal (`antigravityForeseen`).
- Claude Code's advisor (`/advisor`, `--advisor`) is Anthropic's server tool `advisor_20260301`, its `model` named as Claude Code names its own: on magpie, by magpie's id (the tier an alias like `opus` is on), which no vendor knows, so the request was turned away whole (JackChou on Discord). Relayed on Messages (`passthrough`), the advisor's model goes as the upstream's own name for it when it is the same provider's Claude model, or a Claude id naming no provider (`advisorTools` in [`advisor.go`](../../internal/gateway/advisor.go)); one it can't run there (another provider's, a group, not Claude's) is left out, as is every advisor when the request's own model isn't a Claude model (a vendor's Messages API knows no such tool), and the turn is answered without one. A translation drops it with every other server tool. Claude Code (2.1.300) also puts the advisor in the conversation: a `{role: "system"}` message whose text ends in its instructions ("# Advisor Tool … call advisor BEFORE substantive work") and a `tool_addition` naming it. Where the advisor is left out, that `tool_addition` goes too (and a message it leaves empty), and the instructions become Claude Code's own "The advisor tool is no longer available; disregard the earlier advisor instructions." (`withoutAdvisor` on Messages, `advisorGoneIn` in `parseAnthropic` for a translation): left there, the model called `advisor()` as one of the agent's tools and Claude Code answered "No such tool available: advisor" (JackChou on Discord). The Claude subscription's run declares only magpie's tools, so it never has one. `TestAdvisorModelAsTheUpstreamNamesIt`, `TestAdvisorLeftOutOnTranslation`.
- Claude Code's advisor (`/advisor`, `--advisor`) is Anthropic's server tool `advisor_20260301`, its `model` named as Claude Code names its own: on magpie, by magpie's id (the tier an alias like `opus` is on), which no vendor knows, so the request was turned away whole (JackChou on Discord). Relayed on Messages (`passthrough`), the advisor's model goes as the upstream's own name for it when it is the same provider's Claude model, or a Claude id naming no provider (`advisorTools` in [`advisor.go`](../../internal/gateway/advisor.go)); one it can't run there (another provider's, a group, not Claude's) is run by magpie when magpie serves it (below) and otherwise left out, as is every advisor when the request's own model isn't a Claude model (a vendor's Messages API knows no such tool), and the turn is answered without one. A translation drops it with every other server tool. Claude Code (2.1.300) also puts the advisor in the conversation: a `{role: "system"}` message whose text ends in its instructions ("# Advisor Tool … call advisor BEFORE substantive work") and a `tool_addition` naming it. Where the advisor is left out, that `tool_addition` goes too (and a message it leaves empty), and the instructions become Claude Code's own "The advisor tool is no longer available; disregard the earlier advisor instructions." (`withoutAdvisor` on Messages, `advisorGoneIn` in `parseAnthropic` for a translation): left there, the model called `advisor()` as one of the agent's tools and Claude Code answered "No such tool available: advisor" (JackChou on Discord). The Claude subscription's run declares only magpie's tools, so it never has one. `TestAdvisorModelAsTheUpstreamNamesIt`, `TestAdvisorLeftOutOnTranslation`.
- magpie runs Claude Code's advisor itself where the upstream can't and the advisor's model is one magpie serves (`provider.Resolve` takes it; `advisedHere` in [`advisor_serve.go`](../../internal/gateway/advisor_serve.go), Awad_Yoo on X). Claude Code sends the advisor for any model only with `CLAUDE_CODE_ENABLE_EXPERIMENTAL_ADVISOR_TOOL` set (2.1.316), which the Claude Code advisor field writes (agent-wiring.md). Such a request is translated, a relay on Messages too (`ownAPI`): the server tool becomes `Request.Advisor`, and the model is offered a function tool `advisor` with no parameters (`advisorToolDef`, a neutral description naming neither magpie nor a vendor), Claude Code's instructions and `tool_addition` kept as written. A call of it is answered inside the reply's rounds, beside web search's (`searchRounds`, `adviceRound`): the advisor model is asked through the gateway (`advise`, User-Agent `magpie-advisor/1`, the executor's system prompt and conversation, what the model said before the call, its tools offered with `tool_choice` none, no reasoning, and a short ask appended to the last user message, `adviceFor`), and the reply goes on with the advice as the call's result. Claude Code is told as Anthropic's server tells it: a `server_tool_use` (`srvtoolu_…`, empty input) and an `advisor_tool_result` with `{type: advisor_result, text}`, or `{type: advisor_tool_result_error, error_code}` (`unavailable`, `too_many_requests`, `overloaded`, `prompt_too_long`, `execution_time_exceeded`, or `max_uses_exceeded` past three calls a reply). Claude Code echoes both blocks in the next turn's assistant message; `readAdvised` reads them back as the model's call and its result, splitting the message around them (`adviceApart`). Not handled: a round that calls the advisor beside an agent tool keeps the agent's tool call only, as with web search. `TestAdvisorServedForAVendorModel`, `TestAdvisorHistoryGoesBackAsACall`, `TestAdvisorFailureIsAnErrorCode`, `TestAdvisedHere`.
- Kiro is told where to cache the prompt (plugins#110: a Kiro subscription read 0 from its cache). Its API takes Bedrock's `cachePoint: {"type":"default"}` on a `userInputMessage`, an `assistantResponseMessage` or as a tool entry. The built-in (`buildKiro` in [`kiro.go`](../../internal/gateway/kiro.go)) marks the first message when there is a system prompt, which it folds into that message, and the current message, as `buildAnthropic` marks Anthropic's. A moved Kiro's plugin (opencode-kiro-auth 0.1.10, the mover's `min`) turns each `cache_control` in the Anthropic body it is handed into one, at most 4, the last kept.
- The cache marks `buildAnthropic` adds for a Responses client (Codex) to a Claude model last an hour (`addedMark`, `Request.hourMarks`; 7eleven on Discord): Codex's turns are often more than five minutes apart, and Codex's own vendor keeps a thread cached an hour (`chatGPTCold`). A 1h write costs 2x the input price where Anthropic's default 5m costs 1.25x and a read 0.1x or less, so one turn read after a 5 to 60 minute pause, which a 5m mark would have written again, pays for the dearer writes of dozens of turns in quick succession. Every mark it adds has the same ttl, since Anthropic refuses a 1h mark after a 5m one. The client's `prompt_cache_retention: "in_memory"` keeps them at 5m. A Chat client's marks, a model that isn't Claude's, and marks a client placed itself (an Anthropic client's, relayed as sent) are unchanged. An upstream that answers 400 naming `cache_control` and `ttl` (a relay that knows no ttl) is asked again at 5m and remembered in `unfit` (`hourMarksRefused`) until magpie restarts. A Claude subscription is served by Claude Code, which asks 1h unless the user picked 5m ([Claude subscription bridge](claude-subscription-bridge.md)). `TestResponsesToClaudeMarksLastAnHour`, `TestHourMarksRefused`.
- A model that refuses a conversation ending with the assistant's message (`refusesPrefill`: OpenCode Go's Claude models over Messages, "This model does not support assistant message prefill"; Volcengine's Agent Plan, "…for a model that does not support prefill"; Gemini's, "Requests ending with a model turn are not supported") is marked for that provider, model and API (`prefillRefused`, #1447); the provider's other models keep their prefill ([`prefill.go`](../../internal/gateway/prefill.go)). A Chat or Responses client's conversation ending with the assistant's message, which those APIs read as a turn already said (`Request.LastIsTurn`), is asked again with a user turn after it (`continueText`), translated (`forwardTranslated`) or relayed (`passthrough`, `userLastBody`), and so from then on. An Anthropic client's prefill is its own ask and gets the refusal as sent. magpie's own continuation of a cut reply (`continuation.go`) isn't asked of that model again; the try the model refused ends the reply with what cut it, not with the refusal. A request magpie builds in Gemini's own shape (`buildCodeAssistSent`: Vertex AI, Gemini CLI's and Antigravity's Code Assist, Factory) never ends with the model's turn, which all of them turn away: a user turn goes after it, `continueText`, or `compactLastText` when an agent is compacting with its ask in the system prompt (`modelLastAsk`), as one goes before a history that opens with the model's. Nor does it send a user turn that mixes a tool's `functionResponse` with text, which Vertex AI answers with the same "ending with a model turn" (#1533: Codex's compaction prompt after a tool's output): what the user said goes in a user turn of its own after the tools' responses (`hasResponse`), except for a Claude model on Antigravity, whose tool_result turn holds both.
+74
View File
@@ -81,6 +81,14 @@ var claudeOwnEnv = append([]string{
// comes before it.
const claudeAutoModeEnv = "CLAUDE_CODE_AUTO_MODE_MODEL"
// claudeAdvisorEnv turns Claude Code's advisor (/advisor, settings.json's
// advisorModel) on for any model (2.1.316): without it, Claude Code sends
// the advisor only for Anthropic's own models by their public names, and
// a model on magpie gets none. The advisor field writes it, and magpie's
// gateway runs the advisor for a model whose upstream can't
// (internal/gateway/advisor_serve.go).
const claudeAdvisorEnv = "CLAUDE_CODE_ENABLE_EXPERIMENTAL_ADVISOR_TOOL"
// claudeNoClassifier are the Claude models Claude Code 2.1.303 won't run
// its classifier on from claudeAutoModeEnv ("the API's safeguards refuse
// the classifier's escalated check on it"): it warns and takes its own
@@ -739,6 +747,14 @@ func claudeIn(at place) *Agent {
v := rawEnv(claudeAutoModeEnv)
return v != "" && (v == stashShared()[autoKey] || isMagpie(env(claudeAutoModeEnv)))
}
// the advisor's switch as magpie wrote it (the advisor field), which
// goes when the advisor does or magpie steps out; one the user wrote
// is theirs
advisorKey := at.key("claude.advisor_env")
advisorOurs := func() bool {
v := rawEnv(claudeAdvisorEnv)
return v != "" && v == stashShared()[advisorKey]
}
// set once magpie has taken what the env said about each tier's model
// from before it routed Claude Code (claudeAbout): what is there after
// that the user wrote about magpie's model, and stays while the tier
@@ -1657,6 +1673,19 @@ func claudeIn(at place) *Agent {
}
}
forget(autoKey)
// the advisor goes where it is on magpie's model, and its switch
// where magpie wrote it
if isMagpie(strings.TrimSuffix(claudeReadOwn(jsonGet(path, "advisorModel")()), "[1m]")) {
if err := edit.DelJSON(path, "advisorModel"); err != nil {
return "", err
}
}
if advisorOurs() {
if err := edit.DelJSON(path, "env."+claudeAdvisorEnv); err != nil {
return "", err
}
}
forget(advisorKey)
was := unstash(at.key("claude.model"))
var back []edit.KV
for _, k := range claudeOwnEnv {
@@ -2292,6 +2321,51 @@ func claudeIn(at place) *Agent {
})
},
})
// advisor: the model Claude Code's advisor runs on (settings.json's
// advisorModel, as /advisor writes it), turned on for magpie's models
// (claudeAdvisorEnv). Unset, no advisor. The gateway runs it for a
// model whose upstream can't. Claude Code reads both as it starts.
fields = append(fields, Field{
Key: "advisor", Label: "advisor model", Quiet: true,
Get: func() string {
if !routed() {
return ""
}
return claudeReadOwn(jsonGet(path, "advisorModel")())
},
Set: func(v string) error {
v = strings.TrimSpace(v)
if !routed() {
if v == "" {
return nil
}
return fmt.Errorf("pick a model through magpie for Claude Code first; its advisor can then have a model")
}
if v != "" && !isMagpie(strings.TrimSuffix(v, "[1m]")) {
return fmt.Errorf("advisor: %q is not a model magpie serves", v)
}
if v == "" {
keys := []string{"advisorModel"}
if advisorOurs() {
keys = append(keys, "env."+claudeAdvisorEnv)
}
forget(advisorKey)
return edit.DelJSON(path, keys...)
}
kv := []edit.KV{{Path: "advisorModel", Value: spell(v)}}
if rawEnv(claudeAdvisorEnv) == "" || advisorOurs() {
stash(map[string]string{advisorKey: "1"})
kv = append(kv, edit.KV{Path: "env." + claudeAdvisorEnv, Value: "1"})
}
return edit.SetJSON(path, kv...)
},
Options: func(map[string]string) []Option {
if !routed() {
return nil
}
return claudeViaMagpie(false)
},
})
// its sign-in while it runs through magpie: magpie's key, or its own
// claude.ai sign-in kept (loginKey), where the gateway takes any key
fields = append(fields, Field{
+98
View File
@@ -0,0 +1,98 @@
package agent
import (
"os"
"path/filepath"
"testing"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/provider"
)
// Claude Code's advisor for magpie's models (Awad_Yoo on X): Claude Code
// sends it only for Anthropic's own models unless
// CLAUDE_CODE_ENABLE_EXPERIMENTAL_ADVISOR_TOOL is set (2.1.316). The
// advisor field writes advisorModel, as /advisor does, with that switch,
// only while magpie routes Claude Code and only for a model magpie serves;
// clearing it, or magpie stepping out, takes both away, but never a switch
// the user wrote.
func TestClaudeAdvisorModel(t *testing.T) {
a, path, env := claudeAutoModeHome(t, `{}`)
f := a.Field("advisor")
if f == nil {
t.Fatal("no advisor field")
}
get := func() string { v, _ := edit.GetJSON(path, "advisorModel"); return v }
if err := f.Set("relay/claude-opus-5-5"); err == nil {
t.Fatal("an advisor before Claude Code is routed should fail")
}
if err := a.Field("model").Set("relay/deepseek-pro"); err != nil {
t.Fatal(err)
}
// unset by default: no advisor, no switch
if f.Get() != "" || get() != "" || env(claudeAdvisorEnv) != "" {
t.Fatalf("advisor on by default: %q %q", get(), env(claudeAdvisorEnv))
}
if !containsOption(f.Options(nil), "relay/claude-opus-5-5") {
t.Fatalf("options miss magpie's models: %v", f.Options(nil))
}
if err := f.Set("claude-opus-5-5"); err == nil || get() != "" {
t.Fatalf("a model magpie doesn't serve taken: %v %q", err, get())
}
if err := f.Set("relay/claude-opus-5-5"); err != nil {
t.Fatal(err)
}
if got := get(); got != provider.ClaudeSpelled("relay/claude-opus-5-5") || env(claudeAdvisorEnv) != "1" {
t.Fatalf("advisorModel %q, switch %q", got, env(claudeAdvisorEnv))
}
if f.Get() != "relay/claude-opus-5-5" {
t.Fatalf("get %q", f.Get())
}
if err := f.Set(""); err != nil {
t.Fatal(err)
}
if get() != "" || env(claudeAdvisorEnv) != "" {
t.Fatalf("clearing left %q %q", get(), env(claudeAdvisorEnv))
}
// magpie stepping out takes its advisor away
if err := f.Set("relay/deepseek-pro"); err != nil {
t.Fatal(err)
}
if err := a.Disconnect(); err != nil {
t.Fatal(err)
}
if get() != "" || env(claudeAdvisorEnv) != "" {
b, _ := os.ReadFile(path)
t.Fatalf("disconnect left the advisor: %s", b)
}
}
// A switch the user turned on themselves stays theirs: clearing magpie's
// advisor, or magpie stepping out, leaves it.
func TestClaudeAdvisorUserSwitch(t *testing.T) {
a, path, env := claudeAutoModeHome(t, `{"env":{"CLAUDE_CODE_ENABLE_EXPERIMENTAL_ADVISOR_TOOL":"1"},"advisorModel":"opus"}`)
if err := a.Field("model").Set("relay/deepseek-pro"); err != nil {
t.Fatal(err)
}
f := a.Field("advisor")
if err := f.Set("relay/claude-opus-5-5"); err != nil {
t.Fatal(err)
}
if err := f.Set(""); err != nil {
t.Fatal(err)
}
if env(claudeAdvisorEnv) != "1" {
b, _ := os.ReadFile(filepath.Clean(path))
t.Fatalf("the user's own switch taken: %s", b)
}
if err := f.Set("relay/claude-opus-5-5"); err != nil {
t.Fatal(err)
}
if err := a.Disconnect(); err != nil {
t.Fatal(err)
}
if env(claudeAdvisorEnv) != "1" {
b, _ := os.ReadFile(path)
t.Fatalf("disconnect took the user's own switch: %s", b)
}
}
+305
View File
@@ -0,0 +1,305 @@
package gateway
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"slices"
"strings"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
// Claude Code's advisor (/advisor, --advisor, settings.json's
// advisorModel) is Anthropic's server tool: the model calls advisor() with
// no arguments, Anthropic's server asks the advisor model about the whole
// conversation, and the reply carries both, a server_tool_use block and an
// advisor_tool_result with the advice, before the model goes on. Claude
// Code sends it for any model with CLAUDE_CODE_ENABLE_EXPERIMENTAL_ADVISOR_TOOL
// set (2.1.316), which magpie's advisor field writes (internal/agent).
//
// An upstream that runs it itself (a Claude model on Anthropic's API, its
// advisor a Claude model of the same provider) is given it as it is
// (advisorTools). For any other, where the advisor model is one magpie
// serves, magpie runs it: the model is offered an advisor tool of its own,
// a call of it is answered by asking the advisor model (advise), and the
// client is told of it in the blocks Anthropic's server writes. Where
// magpie can't (no such model), it is left out as before (advisorTools,
// readAnthropic). Claude Code's own instructions for the advisor stay as
// it wrote them either way: nothing about it is added to the prompt the
// model is sent beside the tool's description.
// advisorTool is the name Claude Code gives its advisor tool, and the one
// the model calls it by.
const advisorTool = "advisor"
// AdvisorAgent is the User-Agent of the advisor's requests magpie makes.
const AdvisorAgent = "magpie-advisor/1"
// advisorUses is how many times one reply may call the advisor; one more
// is answered max_uses_exceeded, as Anthropic's server answers it.
const advisorUses = 3
// advisedHere tells whether magpie runs the advisor of a Messages request
// it serves on p's model on API to: Claude Code asked for one, the
// upstream doesn't run it itself, and magpie serves its model.
func advisedHere(p provider.Provider, from, to provider.Protocol, model string, body []byte, wires map[string]string) bool {
if from != provider.Anthropic || !bytes.Contains(body, []byte(`"advisor_`)) {
return false
}
adv := ""
for _, t := range gjson.GetBytes(body, "tools").Array() {
typ := t.Get("type").String()
if strings.HasPrefix(typ, "advisor_") {
if adv == "" {
adv = t.Get("model").String()
}
continue
}
if t.Get("name").String() == advisorTool {
return false // a tool of the client's own goes by the name
}
}
if adv == "" {
return false
}
if to == provider.Anthropic && anthropicModel.MatchString(provider.UpstreamNameIn(wires, p.ID, model)) {
if _, ok := advisorModel(p, adv, wires); ok {
return false // Anthropic's server runs it (advisorTools)
}
}
_, _, ok := provider.Resolve(adv)
return ok
}
// advisorToolDef is the tool the model is offered for the advisor. It
// names no vendor and no gateway: it goes upstream as the client's tools
// do.
func advisorToolDef() Tool {
return Tool{Name: advisorTool,
Description: "Ask a stronger reviewer model for advice. Takes no parameters: the whole conversation so far is passed to it, and its advice comes back as the result.",
Schema: json.RawMessage(`{"type":"object","properties":{}}`)}
}
// adviceOf is the advice in an advisor_tool_result's content, and whether
// it is an error's.
func adviceOf(raw json.RawMessage) (string, bool) {
c := gjson.ParseBytes(raw)
switch c.Get("type").String() {
case "advisor_result":
return c.Get("text").String(), false
case "advisor_redacted_result":
return "The advice is not readable here.", false
}
code := c.Get("error_code").String()
if code == "" {
code = "unavailable"
}
return "The advisor failed: " + code, true
}
// adviceBlock is an advisor_tool_result as Anthropic writes it: the
// advice, or the error_code of a call that failed.
func adviceBlock(id, text, code string) map[string]any {
content := map[string]any{"type": "advisor_result", "text": text}
if code != "" {
content = map[string]any{"type": "advisor_tool_result_error", "error_code": code}
}
return map[string]any{"type": "advisor_tool_result", "tool_use_id": id, "content": content}
}
// adviceOutID is the id an advisor call is given to the client by, which
// adviceInID turns back: Anthropic's own are srvtoolu_…
func adviceOutID(id string) string { return "srvtoolu_" + anthropicOutID(id) }
func adviceInID(id string) string { return anthropicInID(strings.TrimPrefix(id, "srvtoolu_")) }
// adviceApart is an assistant message of Claude Code's history as the
// model's turns: Anthropic's server writes the advisor's result in the
// assistant's message, after its call, where every other API has a tool's
// result in a message of its own. A call with no result, or a result with
// no call, is left out.
func adviceApart(m Message) []Message {
called, answered := map[string]bool{}, map[string]bool{}
for _, p := range m.Parts {
switch {
case p.Kind == ToolCall && p.Name == advisorTool:
called[p.ID] = true
case p.Kind == ToolResult:
answered[p.CallID] = true
}
}
if len(called) == 0 && len(answered) == 0 {
return []Message{m}
}
var out []Message
var said, results []Part
flush := func() {
if len(said) > 0 {
out = append(out, Message{Role: "assistant", Parts: said})
said = nil
}
if len(results) > 0 {
out = append(out, Message{Role: "user", Parts: results})
results = nil
}
}
for _, p := range m.Parts {
switch {
case p.Kind == ToolCall && p.Name == advisorTool:
if !answered[p.ID] {
continue
}
case p.Kind == ToolResult:
if called[p.CallID] {
results = append(results, p)
}
continue
}
if len(results) > 0 {
flush()
}
said = append(said, p)
}
flush()
if len(out) == 0 {
return []Message{{Role: "assistant"}}
}
return out
}
// advisorAsk is what the advisor model is asked after the conversation.
const advisorAsk = "You are an advisor reviewing the conversation above, in which an assistant works on the user's task. Give the assistant brief, concrete advice for what to do next: the approach to take, what to check first, and any mistake or risk you see. Write plain text addressed to the assistant; do not call tools."
// adviceFor is the request the advisor model is asked: the model's own,
// its system prompt and conversation, with what the model said before the
// call (said), and the ask after. Its tools are offered with no call
// allowed, as the conversation calls them. Reasoning is left out: another
// model's signatures are nothing to it.
func adviceFor(q *Request, said []Part) *Request {
c := *q
c.Advisor, c.WebSearch, c.Stream, c.Format = "", false, false, nil
c.Thinking, c.ThinkOff, c.Effort = false, false, ""
c.Metadata = nil
c.MaxTokens = 4096
c.ToolChoice = "none"
c.Tools = slices.DeleteFunc(slices.Clone(q.Tools), func(t Tool) bool { return t.Name == advisorTool })
var msgs []Message
keep := func(m Message) Message {
m.Parts = slices.DeleteFunc(slices.Clone(m.Parts), func(p Part) bool { return p.Kind == Thinking })
return m
}
for _, m := range q.Messages {
if m = keep(m); len(m.Parts) > 0 {
msgs = append(msgs, m)
}
}
// what it said, its words only: a call in the same round has no
// result yet
said = slices.DeleteFunc(slices.Clone(said), func(p Part) bool { return p.Kind != Text })
if m := keep(Message{Role: "assistant", Parts: said}); len(m.Parts) > 0 {
msgs = append(msgs, m)
}
ask := Part{Kind: Text, Text: advisorAsk}
if n := len(msgs); n > 0 && msgs[n-1].Role == "user" {
msgs[n-1].Parts = append(slices.Clone(msgs[n-1].Parts), ask)
} else {
msgs = append(msgs, Message{Role: "user", Parts: []Part{ask}})
}
c.Messages = msgs
return &c
}
// errAdvice is an advisor call that failed, with the error_code the client
// is told.
type errAdvice struct {
code string
err error
}
func (e errAdvice) Error() string { return e.err.Error() }
// advise asks the advisor model, model, about q, the model's request, and
// what it said before calling the advisor.
func (s *Server) advise(ctx context.Context, q *Request, said []Part, model string) (string, error) {
body := buildAnthropic(adviceFor(q, said), model)
r, err := http.NewRequestWithContext(ownAsk(magpieChose(ctx)), http.MethodPost, "http://magpie/v1/messages", nil)
if err != nil {
return "", errAdvice{"unavailable", err}
}
r.Header.Set("Content-Type", "application/json")
r.Header.Set("User-Agent", AdvisorAgent)
w := httptest.NewRecorder()
s.serve(w, r, provider.Anthropic, body)
var out struct {
Content []struct {
Type string `json:"type"`
Text string `json:"text"`
} `json:"content"`
Error *struct {
Message string `json:"message"`
} `json:"error"`
}
if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil || w.Code >= 300 || out.Error != nil {
msg := http.StatusText(w.Code)
if out.Error != nil && out.Error.Message != "" {
msg = out.Error.Message
}
code := "unavailable"
switch {
case ctx.Err() != nil || errors.Is(err, context.DeadlineExceeded):
code = "execution_time_exceeded"
case w.Code == http.StatusRequestEntityTooLarge:
code = "prompt_too_long"
case w.Code == 529 || w.Code == http.StatusServiceUnavailable:
code = "overloaded"
default:
if failure(w.Code, w.Body.Bytes()) == failRate {
code = "too_many_requests"
}
}
return "", errAdvice{code, fmt.Errorf("%s: %s", model, msg)}
}
var text strings.Builder
for _, b := range out.Content {
if b.Type == "text" {
text.WriteString(b.Text)
}
}
advice := strings.TrimSpace(text.String())
if advice == "" {
return "", errAdvice{"unavailable", fmt.Errorf("%s said nothing", model)}
}
return advice, nil
}
// adviceRound answers the model's nth advisor call, c, made after said:
// the result the model is given, and the event the client is told of it
// by.
func (s *Server) adviceRound(ctx context.Context, q *Request, said []Part, c Part, n int) (Part, Event) {
res := Part{Kind: ToolResult, CallID: c.ID}
ev := Event{Kind: KAdvice, ID: adviceOutID(c.ID)}
if n > advisorUses {
ev.Code = "max_uses_exceeded"
res.Text, res.IsError = "The advisor failed: max_uses_exceeded. Go on without it.", true
return res, ev
}
advice, err := s.advise(ctx, q, said, q.Advisor)
if err != nil {
var e errAdvice
ev.Code = "unavailable"
if errors.As(err, &e) {
ev.Code = e.code
}
res.Text, res.IsError = "The advisor failed: "+ev.Code, true
return res, ev
}
ev.Text, res.Text = advice, advice
return res, ev
}
+289
View File
@@ -0,0 +1,289 @@
package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
// advisedUpstream is a Chat Completions upstream serving two models: the
// executor, which calls advisor() once it is offered and answers once the
// advice is back, and the advisor model (adv-pro), which answers with
// advice, or fails with fail when that is set.
type advisedUpstream struct {
mu sync.Mutex
exec []string // the executor's requests
advisor []string // the advisor model's
fail int // the advisor model's status, 0 = answers
}
func (u *advisedUpstream) ServeHTTP(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
q := gjson.ParseBytes(b)
u.mu.Lock()
defer u.mu.Unlock()
w.Header().Set("Content-Type", "text/event-stream")
if q.Get("model").String() == "adv-pro" {
u.advisor = append(u.advisor, string(b))
if u.fail != 0 {
w.WriteHeader(u.fail)
io.WriteString(w, `{"error":{"message":"slow down","type":"rate_limit_error"}}`)
return
}
io.WriteString(w, chatSSE("Check the tests first.", "", ""))
return
}
u.exec = append(u.exec, string(b))
msgs := q.Get("messages").Array()
offered := false
for _, t := range q.Get("tools").Array() {
offered = offered || t.Get("function.name").String() == advisorTool
}
switch {
case len(msgs) > 0 && msgs[len(msgs)-1].Get("role").String() == "tool":
io.WriteString(w, chatSSE("Done.", "", ""))
case offered:
io.WriteString(w, chatSSE("Let me ask.", advisorTool, "{}"))
default:
io.WriteString(w, chatSSE("ok", "", ""))
}
}
// advisedSetup saves an executor provider (v, glm-5.1) and an advisor's
// (adv, adv-pro) at one advisedUpstream.
func advisedSetup(t *testing.T) *advisedUpstream {
t.Helper()
fresh(t)
u := &advisedUpstream{}
srv := httptest.NewServer(u)
t.Cleanup(srv.Close)
for _, p := range []provider.Provider{
{ID: "v", Name: "V", Key: "k", Chat: srv.URL + "/v1", Models: []string{"glm-5.1"}},
{ID: "adv", Name: "Adv", Key: "k", Chat: srv.URL + "/v1", Models: []string{"adv-pro"}},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
return u
}
// sendAdvised is Claude Code's advised turn, body, streamed or not, and
// the reply's content blocks.
func sendAdvised(t *testing.T, s *Server, body string, stream bool) []map[string]any {
t.Helper()
if !stream {
body = strings.Replace(body, `"stream":true`, `"stream":false`, 1)
}
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/messages?beta=true", strings.NewReader(body))
req.Header.Set("User-Agent", "claude-cli/2.1.316 (external, cli)")
req.Header.Set("Authorization", "Bearer "+Token)
s.Handler().ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
if !stream {
var out struct {
Content []map[string]any `json:"content"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatalf("%v: %s", err, rec.Body)
}
return out.Content
}
// the blocks as a client puts them together from the stream
var blocks []map[string]any
for _, line := range strings.Split(rec.Body.String(), "\n") {
data, ok := strings.CutPrefix(line, "data: ")
if !ok {
continue
}
ev := gjson.Parse(data)
switch ev.Get("type").String() {
case "content_block_start":
var b map[string]any
json.Unmarshal([]byte(ev.Get("content_block").Raw), &b)
blocks = append(blocks, b)
case "content_block_delta":
if d := ev.Get("delta"); d.Get("type").String() == "text_delta" && len(blocks) > 0 {
blocks[len(blocks)-1]["text"] = blocks[len(blocks)-1]["text"].(string) + d.Get("text").String()
}
}
}
return blocks
}
func blockTypes(blocks []map[string]any) string {
var out []string
for _, b := range blocks {
out = append(out, b["type"].(string))
}
return strings.Join(out, ",")
}
// Claude Code's advisor on a model whose upstream has none (Awad_Yoo on
// X): magpie offers the model an advisor tool, asks the advisor model when
// it is called, and tells Claude Code of it as Anthropic's server does, a
// server_tool_use and an advisor_tool_result with the advice, before the
// model's answer. Before, the advisor was left out and Claude Code's
// instructions for it said to be void.
func TestAdvisorServedForAVendorModel(t *testing.T) {
for _, stream := range []bool{true, false} {
u := advisedSetup(t)
s := New()
blocks := sendAdvised(t, s, advisorTurn("v/glm-5.1", "adv/adv-pro"), stream)
if got := blockTypes(blocks); got != "text,server_tool_use,advisor_tool_result,text" {
t.Fatalf("stream=%t: blocks %s: %v", stream, got, blocks)
}
call, result := blocks[1], blocks[2]
id, _ := call["id"].(string)
if call["name"] != advisorTool || !strings.HasPrefix(id, "srvtoolu_") || result["tool_use_id"] != id {
t.Fatalf("stream=%t: call %v, result %v", stream, call, result)
}
content, _ := result["content"].(map[string]any)
if content["type"] != "advisor_result" || content["text"] != "Check the tests first." {
t.Fatalf("stream=%t: advice %v", stream, content)
}
// what it says after goes on from what it said before, as after a
// search
if after, _ := blocks[3]["text"].(string); strings.TrimSpace(after) != "Done." {
t.Fatalf("stream=%t: answer %v", stream, blocks[3])
}
u.mu.Lock()
exec, adv := u.exec, u.advisor
u.mu.Unlock()
if len(exec) != 2 || len(adv) != 1 {
t.Fatalf("stream=%t: %d executor requests, %d advisor's", stream, len(exec), len(adv))
}
// the executor is offered the tool, Claude Code's instructions for
// it as written, none said to be void
if !strings.Contains(exec[0], `"name":"advisor"`) || !strings.Contains(exec[0], "You have access to an `advisor` tool") || strings.Contains(exec[0], advisorGone) {
t.Fatalf("stream=%t: executor sent %s", stream, exec[0])
}
if strings.Contains(exec[0], "advisor_2026") {
t.Fatalf("stream=%t: the server tool went upstream: %s", stream, exec[0])
}
// the advisor is asked the conversation, with no tool to call
a := gjson.Parse(adv[0])
if !strings.Contains(adv[0], `"hi"`) || !strings.Contains(adv[0], "Let me ask.") || a.Get("tool_choice").String() != "none" {
t.Fatalf("stream=%t: advisor asked %s", stream, adv[0])
}
for _, tl := range a.Get("tools").Array() {
if tl.Get("function.name").String() == advisorTool {
t.Fatalf("stream=%t: the advisor was offered itself: %s", stream, adv[0])
}
}
// the advice reaches the executor as the call's result
if !strings.Contains(exec[1], "Check the tests first.") {
t.Fatalf("stream=%t: the advice never reached the model: %s", stream, exec[1])
}
}
}
// The next turn has the advisor's blocks in the assistant's message, as
// Claude Code echoes them back: they go to the model as its call and the
// call's result, the assistant's message split around them.
func TestAdvisorHistoryGoesBackAsACall(t *testing.T) {
u := advisedSetup(t)
body := advisorTurn("v/glm-5.1", "adv/adv-pro")
turn := `{"role":"assistant","content":[{"type":"text","text":"Let me ask."},` +
`{"type":"server_tool_use","id":"srvtoolu_abc","name":"advisor","input":{}},` +
`{"type":"advisor_tool_result","tool_use_id":"srvtoolu_abc","content":{"type":"advisor_result","text":"Check the tests first."}},` +
`{"type":"text","text":"Done."}]},{"role":"user","content":[{"type":"text","text":"thanks"}]}`
body = strings.Replace(body, `"output_config":{"effort":"medium"}}]`, `"output_config":{"effort":"medium"}},`+turn+`]`, 1)
if !strings.Contains(body, "srvtoolu_abc") {
t.Fatal("fixture not changed")
}
sendAdvised(t, New(), body, true)
u.mu.Lock()
sent := u.exec[0]
u.mu.Unlock()
var shape []string
for _, m := range gjson.Get(sent, "messages").Array() {
s := m.Get("role").String()
if m.Get("tool_calls.0.function.name").String() == advisorTool {
s += "+advisor()"
}
if m.Get("role").String() == "tool" && !strings.Contains(m.Get("content").Raw, "Check the tests first.") {
t.Fatalf("result lost: %s", sent)
}
shape = append(shape, s)
}
got := strings.Join(shape, ",")
if !strings.Contains(got, "assistant+advisor(),tool,assistant,user") {
t.Fatalf("messages %s: %s", got, sent)
}
call := gjson.Get(sent, `messages.#(role=="assistant").tool_calls.0.id`).String()
res := gjson.Get(sent, `messages.#(role=="tool").tool_call_id`).String()
if call == "" || call != res {
t.Fatalf("call %q, result %q: %s", call, res, sent)
}
}
// An advisor that fails is told as Anthropic's server tells it, an
// advisor_tool_result_error with its code, and the model goes on.
func TestAdvisorFailureIsAnErrorCode(t *testing.T) {
u := advisedSetup(t)
u.fail = 429
blocks := sendAdvised(t, New(), advisorTurn("v/glm-5.1", "adv/adv-pro"), false)
if got := blockTypes(blocks); got != "text,server_tool_use,advisor_tool_result,text" {
t.Fatalf("blocks %s: %v", got, blocks)
}
content, _ := blocks[2]["content"].(map[string]any)
if content["type"] != "advisor_tool_result_error" || content["error_code"] == "" {
t.Fatalf("result %v", blocks[2])
}
}
// Who runs the advisor: Anthropic's server for a Claude model with a Claude
// advisor of the same provider, magpie for a model magpie can ask the
// advisor beside, nobody for an advisor model magpie doesn't serve or a
// tool of the client's own by the name.
func TestAdvisedHere(t *testing.T) {
fresh(t)
for _, p := range []provider.Provider{
{ID: "relay", Name: "Relay", Key: "k", Anthropic: "http://127.0.0.1:1", Models: []string{"claude-opus-5-5", "claude-sonnet-5-5"}},
{ID: "v", Name: "V", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"glm-5.1"}},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
rp, err := provider.Find("relay")
if err != nil {
t.Fatal(err)
}
vp, err := provider.Find("v")
if err != nil {
t.Fatal(err)
}
relay, v := *rp, *vp
for _, c := range []struct {
name string
p provider.Provider
to provider.Protocol
model string
body string
want bool
}{
{"native", relay, provider.Anthropic, "claude-sonnet-5-5", advisorTurn("relay/claude-sonnet-5-5", "relay/claude-opus-5-5"), false},
{"vendor model", v, provider.Chat, "glm-5.1", advisorTurn("v/glm-5.1", "relay/claude-opus-5-5"), true},
{"another provider's advisor", relay, provider.Anthropic, "claude-sonnet-5-5", advisorTurn("relay/claude-sonnet-5-5", "v/glm-5.1"), true},
{"unknown advisor", v, provider.Chat, "glm-5.1", advisorTurn("v/glm-5.1", "nobody/x"), false},
{"no advisor", v, provider.Chat, "glm-5.1", claudeCodeTurn("v/glm-5.1", "x"), false},
{"client's own advisor", v, provider.Chat, "glm-5.1", strings.Replace(advisorTurn("v/glm-5.1", "relay/claude-opus-5-5"), `{"name":"Read"`, `{"name":"advisor","input_schema":{"type":"object"}},{"name":"Read"`, 1), false},
} {
if got := advisedHere(c.p, provider.Anthropic, c.to, c.model, []byte(c.body), nil); got != c.want {
t.Errorf("%s: advisedHere %t, want %t", c.name, got, c.want)
}
}
}
+18 -7
View File
@@ -28,7 +28,8 @@ func advisorTurn(model, advisor string) string {
// turned away whole and the advisor never ran (JackChou on Discord). The
// advisor's model now goes as the upstream's own name for it when it is
// the same provider's Claude model; one the upstream can't run (another
// provider's, a vendor's model asked) is left out and the turn still
// provider's, a vendor's model asked) is run by magpie (advisor_serve.go),
// and one magpie doesn't serve either is left out and the turn still
// answered.
func TestAdvisorModelAsTheUpstreamNamesIt(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
@@ -53,13 +54,15 @@ func TestAdvisorModelAsTheUpstreamNamesIt(t *testing.T) {
return out
}
for _, c := range []struct {
name, model, advisor, want string // want "" = left out
name, model, advisor, want string // want "" = not sent upstream
served bool // run by magpie
}{
{"same provider", "relay/claude-sonnet-5-5", "relay/claude-opus-5-5", "claude-opus-5-5"},
{"1M mark", "relay/claude-sonnet-5-5", "relay/claude-opus-5-5[1m]", "claude-opus-5-5"},
{"Claude's own id", "relay/claude-sonnet-5-5", "claude-opus-5-5", "claude-opus-5-5"},
{"another provider", "relay/claude-sonnet-5-5", "other/claude-opus-5-5", ""},
{"a vendor's model", "ds/deepseek-v4.1-flash", "relay/claude-opus-5-5", ""},
{"same provider", "relay/claude-sonnet-5-5", "relay/claude-opus-5-5", "claude-opus-5-5", false},
{"1M mark", "relay/claude-sonnet-5-5", "relay/claude-opus-5-5[1m]", "claude-opus-5-5", false},
{"Claude's own id", "relay/claude-sonnet-5-5", "claude-opus-5-5", "claude-opus-5-5", false},
{"another provider", "relay/claude-sonnet-5-5", "other/claude-opus-5-5", "", true},
{"a vendor's model", "ds/deepseek-v4.1-flash", "relay/claude-opus-5-5", "", true},
{"a model magpie doesn't serve", "ds/deepseek-v4.1-flash", "nobody/claude-opus-5-5", "", false},
} {
claudeCodeSends(t, advisorTurn(c.model, c.advisor))
b := u.last(t)
@@ -71,6 +74,14 @@ func TestAdvisorModelAsTheUpstreamNamesIt(t *testing.T) {
if !strings.Contains(b, `"name":"Read"`) {
t.Errorf("%s: the agent's own tool lost: %s", c.name, b)
}
if c.served {
// offered as the model's own tool, Claude Code's instructions
// for it as written
if !strings.Contains(b, `"name":"advisor"`) || !strings.Contains(b, "You have access to an `advisor` tool") || strings.Contains(b, advisorGone) {
t.Errorf("%s: advisor not offered as magpie's: %s", c.name, b)
}
continue
}
advisorSaid(t, c.name, b, c.want != "")
}
}
+46
View File
@@ -107,6 +107,8 @@ type aRequest struct {
InputSchema json.RawMessage `json:"input_schema,omitempty"`
CacheControl json.RawMessage `json:"cache_control,omitempty"`
DeferLoading bool `json:"defer_loading,omitempty"`
// an advisor's (advisor_20260301): the model it runs on
Model string `json:"model,omitempty"`
} `json:"tools,omitempty"`
ToolChoice *struct {
Type string `json:"type"`
@@ -146,6 +148,14 @@ func parseAnthropicRequest(body []byte, clientMarks bool) (*Request, error) {
// out what they never read, as readChat does: the assistant's blocks, the
// tools' outputs, and the copies of raw values a parse kept would need.
func readAnthropic(body []byte, clientMarks, facts bool) (*Request, error) {
return readAdvised(body, clientMarks, facts, false)
}
// readAdvised is readAnthropic; advised, Claude Code's advisor is one
// magpie runs (advisor_serve.go): its calls and results in the
// conversation are read as the model's tool calls and their results, and
// its instructions stay as Claude Code wrote them.
func readAdvised(body []byte, clientMarks, facts, advised bool) (*Request, error) {
decode := decodeJSON
if facts {
decode = decodeJSONView
@@ -226,6 +236,16 @@ func readAnthropic(body []byte, clientMarks, facts bool) (*Request, error) {
msg.Parts = append(msg.Parts, Part{Kind: ToolResult, CallID: anthropicInID(b.ToolUseID), Text: out, Images: images, IsError: b.IsError, Loads: toolRefs(b.Content), block: true})
case "thinking":
msg.Parts = append(msg.Parts, Part{Kind: Thinking, Text: b.Thinking, Signature: b.Signature, block: true})
case "server_tool_use":
// the advisor's call, as magpie gave it (advisor_serve.go)
if advised && b.Name == advisorTool {
msg.Parts = append(msg.Parts, Part{Kind: ToolCall, ID: adviceInID(b.ID), Name: advisorTool, Args: json.RawMessage(`{}`), block: true})
}
case "advisor_tool_result", "advisor_tool_result_error":
if advised {
text, failed := adviceOf(b.Content)
msg.Parts = append(msg.Parts, Part{Kind: ToolResult, CallID: adviceInID(b.ToolUseID), Text: text, IsError: failed, block: true})
}
case "redacted_thinking":
// Claude's reasoning its safety systems sealed: it
// goes back to Messages whole, and is nothing to
@@ -248,6 +268,10 @@ func readAnthropic(body []byte, clientMarks, facts bool) (*Request, error) {
}
}
}
if advised && msg.Role == "assistant" {
r.Messages = append(r.Messages, adviceApart(msg)...)
continue
}
r.Messages = append(r.Messages, msg)
}
for _, t := range a.Tools {
@@ -258,6 +282,12 @@ func readAnthropic(body []byte, clientMarks, facts bool) (*Request, error) {
r.WebSearch = true
}
if strings.HasPrefix(t.Type, "advisor_") {
if advised {
// run by magpie: offered as a tool of the model's
// own when the reply is asked (advisor_serve.go)
r.Advisor = cmp.Or(r.Advisor, t.Model)
continue
}
// Claude Code's advisor: its instructions, which would
// have the model call a tool it hasn't got (advisor.go)
for i := range r.Messages {
@@ -1792,6 +1822,18 @@ func (e *anthropicEncoder) event(ev Event) {
e.cite.hits = append(e.cite.hits, ev.Hits...)
e.w.event("content_block_stop", map[string]any{"type": "content_block_stop", "index": e.index})
e.index++
case KAdvice:
// as Anthropic's own advisor tells it: its call, then its result
e.close()
e.w.event("content_block_start", map[string]any{"type": "content_block_start", "index": e.index,
"content_block": map[string]any{"type": "server_tool_use", "id": ev.ID, "name": advisorTool, "input": map[string]any{}}})
e.delta(map[string]any{"type": "input_json_delta", "partial_json": ""})
e.w.event("content_block_stop", map[string]any{"type": "content_block_stop", "index": e.index})
e.index++
e.w.event("content_block_start", map[string]any{"type": "content_block_start", "index": e.index,
"content_block": adviceBlock(ev.ID, ev.Text, ev.Code)})
e.w.event("content_block_stop", map[string]any{"type": "content_block_stop", "index": e.index})
e.index++
case KError:
e.close()
typ := "api_error"
@@ -1880,6 +1922,10 @@ func renderAnthropic(res Result, model string) []byte {
map[string]any{"type": "server_tool_use", "id": id, "name": "web_search", "input": map[string]any{"query": p.Text}},
searchResultBlock(id, p.Hits))
cite.hits = append(cite.hits, p.Hits...)
case Advice:
content = append(content,
map[string]any{"type": "server_tool_use", "id": p.ID, "name": advisorTool, "input": map[string]any{}},
adviceBlock(p.ID, p.Text, p.Name))
}
}
id := anthropicID(res.ID)
+27 -11
View File
@@ -5700,6 +5700,11 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P
if relay && searchedForIt(r.Context(), p, from, model, body) && !(from == provider.Responses && (hasSealedAgentMessage(body) || codexAsSent(p, r.Header))) {
relay, ownAPI = false, true
}
// Claude Code's advisor, which magpie runs for a model whose upstream
// can't (advisor_serve.go): a relay would leave it out (advisorTools)
if relay && advisedHere(p, from, from, model, body, wiresOf(r.Context())) {
relay, ownAPI = false, true
}
// Copilot seals an argument the tools mark "encrypted" (spawn_agent's
// message, MultiAgentV2) and then can't open what it sealed: the
// subagent's turn came back "Encrypted function output content could
@@ -9073,12 +9078,19 @@ var cacheControlField = []byte("cache_control")
// not refused with a 400 the old translation never gave (#3835). Every
// other request is one bytes.Contains away from this, a scan next to the
// parse of the same body.
func parseTranslated(from, to provider.Protocol, body []byte) (*Request, error) {
func parseTranslated(from, to provider.Protocol, body []byte, advised bool) (*Request, error) {
if from == provider.Anthropic && to == provider.Anthropic && bytes.Contains(body, cacheControlField) {
if req, err := parseAnthropicRequest(body, true); err == nil {
if req, err := readAdvised(body, true, false, advised); err == nil {
return afterParse(from, body, req)
}
}
if advised && from == provider.Anthropic {
req, err := readAdvised(body, false, false, true)
if err != nil {
return nil, err
}
return afterParse(from, body, req)
}
return parseRequest(from, body, false, to == provider.Responses)
}
@@ -9090,7 +9102,10 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr
msg := "input_image without image_url cannot be translated; send an image_url or use a native Responses route"
return writeError(w, from, 400, msg), msg
}
request, err := parseTranslated(from, to, body)
// Claude Code's advisor, run by magpie for a model whose upstream
// can't (advisor_serve.go)
advised := advisedHere(p, from, to, model, body, wiresOf(r.Context()))
request, err := parseTranslated(from, to, body, advised)
if err != nil {
return writeError(w, from, 400, err.Error()), err.Error()
}
@@ -9133,16 +9148,17 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr
if p.OpenCodeFree(model) {
zen = &zenReply{z: zenFreeTools(request)}
}
if request.WebSearch {
if !searching(r.Context()) && canSearchFor(p) && (!searchesFor(p, to, model, request) || magpieSearches(r.Context(), p)) {
ask := antigravityRound(w, p, s.askTranslated(p, to, model, r.Header, w.Header()))
if zen != nil {
ask = zenRound(zen.z, ask)
}
search := request.WebSearch && !searching(r.Context()) && canSearchFor(p) && (!searchesFor(p, to, model, request) || magpieSearches(r.Context(), p))
if search || request.Advisor != "" {
ask := antigravityRound(w, p, s.askTranslated(p, to, model, r.Header, w.Header()))
if zen != nil {
ask = zenRound(zen.z, ask)
}
if search {
// a Kimi Code plan's own searches stay on it
r = r.WithContext(searchingOn(r.Context(), p))
return s.searchReply(w, r, from, p.Name, request, u, ask)
}
return s.searchReply(w, r, from, p.Name, request, u, ask, search)
}
if msg := unportableVideo(to, request); msg != "" {
// told, not left out for the model to answer the words alone (#6135)
@@ -9396,7 +9412,7 @@ func saysSomething(ev Event) bool {
switch ev.Kind {
case KText:
return ev.Text != ""
case KToolStart, KSearch, KImage:
case KToolStart, KSearch, KImage, KAdvice:
return true
}
return false
+14
View File
@@ -28,6 +28,10 @@ const (
ToolResult Kind = "tool_result"
Thinking Kind = "thinking"
Search Kind = "web_search" // a web search run for the model: its query and hits
// Advice is Claude Code's advisor run by magpie for the model
// (advisor_serve.go): ID the call's, Text the advice, or Name an
// error_code and nothing in Text
Advice Kind = "advisor"
)
// Part is one block of a message.
@@ -292,6 +296,10 @@ type Request struct {
ThinkOff bool
Parallel *bool // parallel tool calls allowed
WebSearch bool // the client offered its provider's own web search
// Advisor is the model of Claude Code's advisor that magpie runs
// itself (advisor_serve.go), "" when it doesn't: its calls and results
// in the conversation are ToolCall and ToolResult parts then
Advisor string
// WebAccess is the external_web_access of the client's web_search
// tool, as it sent it: Codex's web_search mode (false for "cached",
// true for "live"), which magpie's own search for a model that can't
@@ -451,6 +459,9 @@ const (
// keepaliveGap of nothing else: a reply read in rounds (searchReply)
// keeps its client alive with it as a translated stream does (#2316)
KAlive
// KAdvice: Claude Code's advisor run by magpie (advisor_serve.go), ID
// the call's, Text the advice, or Code its error_code
KAdvice
)
// Event is one thing a streaming reply said.
@@ -788,6 +799,9 @@ func (c *collector) add(ev Event) {
case KImage:
c.closeTool()
c.res.Parts = append(c.res.Parts, Part{Kind: Image, MediaType: ev.Name, Data: ev.Text})
case KAdvice:
c.closeTool()
c.res.Parts = append(c.res.Parts, Part{Kind: Advice, ID: ev.ID, Text: ev.Text, Name: ev.Code})
}
switch ev.Kind {
case KStart, KUsage, KError, KAlive:
@@ -218,7 +218,7 @@ func TestTranslatedWithMarksTakesSignaturesOffCallIDs(t *testing.T) {
{"role":"user","content":[{"type":"text","text":"go"}]},
{"role":"assistant","content":[{"type":"tool_use","id":` + string(q) + `,"name":"Bash","input":{}}]},
{"role":"user","content":[{"type":"tool_result","tool_use_id":` + string(q) + `,"content":"ok","cache_control":{"type":"ephemeral","ttl":"1h"}}]}]}`)
req, err := parseTranslated(provider.Anthropic, provider.Anthropic, body)
req, err := parseTranslated(provider.Anthropic, provider.Anthropic, body, false)
if err != nil {
t.Fatal(err)
}
+36 -11
View File
@@ -1282,16 +1282,24 @@ func textCallRound(tools []Tool, ask round) round {
}
// searchReply answers req through ask, running the searches its model
// asks for and asking it again with what they found; the client sees one
// reply. The first round's failure is a status, as another provider may
// take over.
func (s *Server) searchReply(w http.ResponseWriter, r *http.Request, from provider.Protocol, name string, req *Request, usage *Usage, ask round) (int, string) {
// asks for (when search) and the advisor calls (req.Advisor,
// advisor_serve.go), and asking it again with what they gave; the client
// sees one reply. The first round's failure is a status, as another
// provider may take over.
func (s *Server) searchReply(w http.ResponseWriter, r *http.Request, from provider.Protocol, name string, req *Request, usage *Usage, ask round, search bool) (int, string) {
ctx, cancel := context.WithCancel(withWebAccess(context.WithValue(r.Context(), searchForKey{}, &CallFor{Agent: callerOf(r).agent, Model: unprefixed(req.Model)}), req.WebAccess))
defer cancel()
q := *req
q.WebSearch = false
tool := searchTool(q.Tools)
q.Tools = append(slices.Clone(q.Tools), tool)
q.Tools = slices.Clone(q.Tools)
var tool Tool
if search {
q.WebSearch = false
tool = searchTool(q.Tools)
q.Tools = append(q.Tools, tool)
}
if q.Advisor != "" {
q.Tools = append(q.Tools, advisorToolDef())
}
q.Messages = slices.Clone(q.Messages)
ask = textCallRound(q.Tools, ask)
first, status, msg := ask(ctx, &q)
@@ -1317,6 +1325,10 @@ func (s *Server) searchRounds(ctx context.Context, q *Request, tool string, in <
}
var before, this Usage
started, said := false, false
ours := func(name string) bool {
return name != "" && name == tool || q.Advisor != "" && name == advisorTool
}
advised := 0 // the advisor's calls so far
for n := 1; ; n++ {
var col collector
mine, theirs, gap := false, false, said
@@ -1353,7 +1365,7 @@ func (s *Server) searchRounds(ctx context.Context, q *Request, tool string, in <
}
said = said || ev.Text != ""
case KToolStart:
mine = ev.Name == tool
mine = ours(ev.Name)
theirs = theirs || !mine
if mine {
continue
@@ -1375,12 +1387,18 @@ func (s *Server) searchRounds(ctx context.Context, q *Request, tool string, in <
}
res := col.finish()
var calls []Part
var at []int // where in the reply each call is
for i, p := range res.Parts {
if p.Kind == ToolCall && p.Name == tool {
if p.Kind == ToolCall && ours(p.Name) {
if p.ID == "" {
res.Parts[i].ID = fmt.Sprintf("call_search_%d_%d", n, i)
kind := "search"
if p.Name == advisorTool && p.Name != tool {
kind = advisorTool
}
res.Parts[i].ID = fmt.Sprintf("call_%s_%d_%d", kind, n, i)
}
calls = append(calls, res.Parts[i])
at = append(at, i)
}
}
// a reply that calls the client's tools goes to the client: it
@@ -1396,6 +1414,13 @@ func (s *Server) searchRounds(ctx context.Context, q *Request, tool string, in <
searches := make([]Event, len(calls))
var wg sync.WaitGroup
for i, c := range calls {
if c.Name == advisorTool && c.Name != tool {
// the advisor, in order, each seeing what the model
// said before it
advised++
results[i], searches[i] = s.adviceRound(ctx, q, res.Parts[:at[i]], c, advised)
continue
}
wg.Add(1)
go func() {
defer wg.Done()
@@ -1427,7 +1452,7 @@ func (s *Server) searchRounds(ctx context.Context, q *Request, tool string, in <
}
// the client hears of the searches as its provider's own
for _, ev := range searches {
if ev.Kind == KSearch && !send(ev) {
if (ev.Kind == KSearch || ev.Kind == KAdvice) && !send(ev) {
return
}
}
+13 -7
View File
@@ -514,7 +514,7 @@ function renderAgents() {
const fields = el("div", "fields");
const wide = (f) => f.label === "model" || f.label === "large" || f.label === "executor" || f.label === "planner";
// a field with nothing to pick and nothing set isn't drawn (#1499)
const none = (f) => (f.key === "effort" || toggled(f) || f.label === "subagents" || f.label === "gateway" || f.label === SUB_EFFORT || f.label === SUB_MODEL || f.label === AUTO_MODE || f.label === MEMORIES || f.label === COMPACT_MODEL || f.label === "sign-in" || f.key === "small" || asideAccount(a, f)) && !f.options.length && !f.value;
const none = (f) => (f.key === "effort" || toggled(f) || f.label === "subagents" || f.label === "gateway" || f.label === SUB_EFFORT || f.label === SUB_MODEL || f.label === AUTO_MODE || f.label === ADVISOR || f.label === MEMORIES || f.label === COMPACT_MODEL || f.label === "sign-in" || f.key === "small" || asideAccount(a, f)) && !f.options.length && !f.value;
const shownFields = a.fields.filter((f) => !grouped(a, f) && !none(f) && !codexOwnSub(a, f) && !codexRowed(a, f) && !hermesBot(f) && !ompAdvisorKey(f));
const tiers = tierMenu(a);
if (tiers) shownFields.push(tiers);
@@ -535,7 +535,7 @@ function renderAgents() {
else if (!f.value && !f.menu && a.icon) b.append(icon(a.icon));
else if (!wide(f) || !f.value) b.append(el("span", "k", t(f.label)));
if ((f.label === "executor" || f.label === "planner") && !b.querySelector(".k")) b.append(el("span", "k", t(f.label)));
const shown = f.menu ? f.summary : effort ? effortName(opt || { value: f.value }) : (opt?.label || f.value || t(claudePicks(a, f) ? AUTO_MODE_UNSET : FOLLOWS_MODEL.includes(f.label) ? "same as model" : "default"));
const shown = f.menu ? f.summary : effort ? effortName(opt || { value: f.value }) : (opt?.label || f.value || t(claudePicks(a, f) ? AUTO_MODE_UNSET : f.label === ADVISOR ? "Off" : FOLLOWS_MODEL.includes(f.label) ? "same as model" : "default"));
if (f.menu) b.title = f.options.map((o) => `${o.label}: ${o.note}`).join("\n");
b.append(el("span", "v" + (f.value || f.custom ? "" : " empty"), shown));
if (f.value && opt?.fast) b.append(fastTag(opt.ultra));
@@ -710,7 +710,7 @@ function renderAgents() {
// Claude Code's tiers, subagents and auto mode have rows of their own
// when opened
if (kindOf(a) === "claude") {
for (const f of a.fields.filter((f) => TIERS.includes(f.label) || f.label === "subagents" || f.label === SUB_EFFORT || f.label === AUTO_MODE)) extras.querySelector(`[data-key="${CSS.escape(f.key)}"]`)?.remove();
for (const f of a.fields.filter((f) => TIERS.includes(f.label) || f.label === "subagents" || f.label === SUB_EFFORT || f.label === AUTO_MODE || f.label === ADVISOR)) extras.querySelector(`[data-key="${CSS.escape(f.key)}"]`)?.remove();
extras.querySelector('[data-key="tiers"]')?.remove();
}
row.append(agentHandle(a, row, inFold), who);
@@ -2217,6 +2217,9 @@ function connectPanel(a, { fields, fieldBtn }) {
// the model its auto mode classifier runs on; unset, Claude Code's own
const auto = a.fields.find((f) => f.label === AUTO_MODE && (f.options.length || f.value));
if (auto) rows.push(line(el("span", "ag-tier", t("Auto mode")), fieldBtn(auto, "ag-pick"), el("span", "ag-hint", t("the model that checks each action in auto mode"))));
// the model its advisor (/advisor) asks; unset, off
const adv = a.fields.find((f) => f.label === ADVISOR && (f.options.length || f.value));
if (adv) rows.push(line(el("span", "ag-tier", t("Advisor")), fieldBtn(adv, "ag-pick"), el("span", "ag-hint", "/advisor")));
if (rows.length) kv(t("Tiers"), ...rows);
const main = a.fields.find((f) => f.key === "model");
const hasSub = main?.options.some((o) => (o.ref || "").startsWith("claude/"));
@@ -3922,6 +3925,8 @@ const SUB_MODEL = "subagent model";
// pick, not the model's
const AUTO_MODE = "auto mode";
const AUTO_MODE_UNSET = "Claude Code's own pick";
// Claude Code's advisor: the model /advisor asks, for any model on magpie
const ADVISOR = "advisor model";
// DeepSeek Harness's compaction square: the model the gateway puts its
// compactions on, not the session's, whose provider may be out of its
// limit (Musikrv77852 on X, #5395)
@@ -3966,7 +3971,7 @@ function codexSubSaid(a, f) {
: f.value ? t(SUB_MODEL_SET) : (lead ? t(SUB_MODEL_UNSET, { model: lead }) : t(SUB_MODEL_UNSET_PLAIN)) + (old ? "\n" + t(SUB_MODEL_OLD, { model: optionFor(a.fields.find((x) => x.label === "subagents"), old)?.label || old }) : "");
return { name, line, old, lead };
}
const extra = (f) => f.key === "tiers" || FOLLOWS_MODEL.includes(f.label) || f.label === "sign-in" || toggled(f) || f.label === SUB_EFFORT || f.label === SUB_MODEL || f.label === AUTO_MODE || f.label === MEMORIES || f.label === COMPACT_MODEL;
const extra = (f) => f.key === "tiers" || FOLLOWS_MODEL.includes(f.label) || f.label === "sign-in" || toggled(f) || f.label === SUB_EFFORT || f.label === SUB_MODEL || f.label === AUTO_MODE || f.label === ADVISOR || f.label === MEMORIES || f.label === COMPACT_MODEL;
const EXTRA_GLYPH = {
subagents: "M4.5 2.75v10.5M4.5 9.25c0-2.2 1.6-3.75 3.9-3.75h3.35M9.9 3.6l1.9 1.9-1.9 1.9",
// a feather for omp's smol role, an hourglass for its slow one
@@ -4001,7 +4006,7 @@ function extraField(a, f) {
const opt = optionFor(f, f.value);
b.title = said ? t("{label}: {value}", { label: t(f.label), value: said.name }) + "\n" + said.line
: f.label === SUB_EFFORT ? subEffortTitle(a, f, opt) : f.menu ? menuTitle(f)
: t("{label}: {value}", { label: f.label === MEMORIES ? t("Codex memories model") : t(f.label), value: t(opt?.label || f.value || (f.label === MEMORIES ? MEMORIES_DEFAULT : f.label === SUB_MODEL ? "the model the lead asks for" : f.label === AUTO_MODE ? AUTO_MODE_UNSET : f.label === COMPACT_MODEL ? COMPACT_UNSET : leadPicks(a, f) ? "the lead's pick, else same as model" : "same as model")) }) + (opt?.note && !FOLLOWS_MODEL.includes(f.label) ? "\n" + t(opt.note) : "") + (leadPicks(a, f) ? "\n" + t(claudePicks(a, f) ? CLAUDE_PICKS : LEAD_PICKS) : "");
: t("{label}: {value}", { label: f.label === MEMORIES ? t("Codex memories model") : t(f.label), value: t(opt?.label || f.value || (f.label === MEMORIES ? MEMORIES_DEFAULT : f.label === SUB_MODEL ? "the model the lead asks for" : f.label === AUTO_MODE ? AUTO_MODE_UNSET : f.label === ADVISOR ? "Off" : f.label === COMPACT_MODEL ? COMPACT_UNSET : leadPicks(a, f) ? "the lead's pick, else same as model" : "same as model")) }) + (opt?.note && !FOLLOWS_MODEL.includes(f.label) ? "\n" + t(opt.note) : "") + (leadPicks(a, f) ? "\n" + t(claudePicks(a, f) ? CLAUDE_PICKS : LEAD_PICKS) : "");
b.setAttribute("aria-label", b.title);
b.dataset.key = f.key;
// the menu as the state is now
@@ -4765,12 +4770,13 @@ function openPicker(agent, field, anchor, ev, only) {
: field.label === MEMORIES ? MEMORIES_DEFAULT
: field.label === SUB_MODEL ? "each subagent on the model {agent}'s lead asks for"
: field.label === AUTO_MODE ? "the model {agent} picks for its auto mode classifier"
: field.label === ADVISOR ? "no advisor"
: field.label === COMPACT_MODEL ? "each compaction on the session's model"
: ompAgent(agent) && OMP_OWN_PICK.includes(field.label) ? OMP_UNSET[field.label]
: asideAccount(agent, field) ? "the account active in {agent}"
: agent.id.startsWith("hermes#") ? "put back what {agent} had before magpie"
: "what {agent} ships with";
options.unshift({ value: "", label: t("Default"), note: t(note, { agent: agent.name, field: t(field.label) }), icon: agent.icon, reset: true });
options.unshift({ value: "", label: t(field.label === ADVISOR ? "Off" : "Default"), note: t(note, { agent: agent.name, field: t(field.label) }), icon: agent.icon, reset: true });
}
// Default is the agent as installed; this is the agent as it was before
// magpie, beside it so the two aren't taken for each other
@@ -4778,7 +4784,7 @@ function openPicker(agent, field, anchor, ev, only) {
const at = options.findIndex((o) => !o.reset);
options.splice(at < 0 ? options.length : at, 0, { value: "\0disconnect", label: t("Disconnect from magpie"), note: t("put back what {agent} had before magpie", { agent: agent.name }), svg: UNPLUG, reset: true, run: () => askDisconnect(agent) });
}
const modelPicker = (["model", "small", "large", MEMORIES, SUB_MODEL, AUTO_MODE, COMPACT_MODEL, "executor", "planner", ...ROLE_MODELS].includes(field.label)) && !only;
const modelPicker = (["model", "small", "large", MEMORIES, SUB_MODEL, AUTO_MODE, ADVISOR, COMPACT_MODEL, "executor", "planner", ...ROLE_MODELS].includes(field.label)) && !only;
pick = { agent, field, options, groups, anchor, cursor: 0, free: !only && !field.menu, modelPicker, effortPicker, groupFilter: "all" };
if (modelPicker) { readSpeeds(); readLoads(); }
anchor.classList.add("open");
+8
View File
@@ -4895,6 +4895,8 @@ const I18N = {
"Quit Claude Magpie if it is open: it no longer runs on magpie.": "如果 Claude Magpie 正在运行,请退出它:它已不再使用 magpie。",
"Telemetry": "遥测",
"Advisor": "顾问",
"advisor model": "顾问模型",
"no advisor": "不用顾问",
"Every turn": "每轮",
"At the end": "结束时",
"Don't wait": "不等",
@@ -10070,6 +10072,8 @@ const I18N = {
"Quit Claude Magpie if it is open: it no longer runs on magpie.": "如果 Claude Magpie 正在執行,請結束它:它已不再使用 magpie。",
"Telemetry": "遙測",
"Advisor": "顧問",
"advisor model": "顧問模型",
"no advisor": "不用顧問",
"Every turn": "每輪",
"At the end": "結束時",
"Don't wait": "不等",
@@ -15247,6 +15251,8 @@ const I18N = {
"Quit Claude Magpie if it is open: it no longer runs on magpie.": "Claude Magpie を開いている場合は終了してください。もう magpie では動きません。",
"Telemetry": "テレメトリ",
"Advisor": "アドバイザー",
"advisor model": "アドバイザーモデル",
"no advisor": "アドバイザーなし",
"Every turn": "毎ターン",
"At the end": "終了時",
"Don't wait": "待たない",
@@ -20424,6 +20430,8 @@ const I18N = {
"Quit Claude Magpie if it is open: it no longer runs on magpie.": "Beende Claude Magpie, falls es offen ist: Es läuft nicht mehr über magpie.",
"Telemetry": "Telemetrie",
"Advisor": "Berater",
"advisor model": "Berater-Modell",
"no advisor": "kein Berater",
"Every turn": "Jede Runde",
"At the end": "Am Ende",
"Don't wait": "Nicht warten",
+126
View File
@@ -0,0 +1,126 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Claude Code's advisor (/advisor) for magpie's models (Awad_Yoo on X):
// connected, the opened row's Tiers has an Advisor line after Auto mode.
// Unset it says Off; a click opens the app's model picker with Off first,
// noted "no advisor", and a model picked is posted; Off posts it empty. It
// is no square of the row's own. Before Claude Code goes through magpie it
// has no options, so neither line nor square shows. No click scrolls the
// page. In English and Chinese, at a normal and a narrow width. No
// backend: the API is faked here.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const models = [{ value: "magpie/v/glm", label: "GLM", ref: "v/glm" }, { value: "magpie/v/flash", label: "Flash", ref: "v/flash" }];
const tiers = ["opus", "sonnet", "haiku", "fable"];
const claude = (id, routed) => ({
id, name: "Claude Code", path: "/test/settings.json", icon: "claudecode-color", wired: routed,
fields: [
{ key: "model", label: "model", value: routed ? "magpie/v/glm" : "opus", options: routed ? models : [{ value: "opus" }] },
...tiers.map((tier) => ({ key: tier, label: tier, value: "", options: models })),
{ key: "subagent", label: "subagents", value: "", options: routed ? models : [] },
{ key: "auto_mode", label: "auto mode", value: "", options: routed ? models : [] },
{ key: "advisor", label: "advisor model", value: "", options: routed ? models : [] },
],
});
const fresh = () => ({ agents: [claude("claude", true), claude("cc-own", false)], profiles: [] });
function server(lang, sets) {
let cur = fresh();
return async (route) => {
const req = route.request(), url = new URL(req.url());
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return route.fulfill({ json: { ...cur, settings: { lang, theme: "light" } } });
if (url.pathname === "/api/set") {
const body = req.postDataJSON();
sets.push(body);
cur = JSON.parse(JSON.stringify(cur));
cur.agents.find((a) => a.id === body.agent).fields.find((f) => f.key === body.field).value = body.value;
return route.fulfill({ json: { ...cur, settings: { lang, theme: "light" } } });
}
if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] });
if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } });
if (url.pathname === "/api/agents/cli") return route.fulfill({ json: { agents: {}, pending: false } });
if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } });
if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } });
if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} });
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await route.fulfill({ body: await fs.readFile(file), contentType });
};
}
// the words as i18n.js has them
const W = {
en: { line: "Advisor", off: "Off", note: "no advisor" },
zh: { line: "顾问", off: "关闭", note: "不用顾问" },
};
const cc = '.row.agent[data-id="claude"]';
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
for (const width of [1100, 560]) {
test(`${engine} ${lang} ${width}px: Claude Code's advisor model is picked in its Tiers`, async (t) => {
const w = W[lang];
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await browser.newPage({ viewport: { width, height: 800 } });
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [], sets = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, sets));
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-claude-advisor.png`) });
}
await browser.close();
});
await page.goto("http://magpie.test/");
await page.locator(cc).waitFor();
// not through magpie: nothing to pick, so nothing shows
assert.equal(await page.locator('.row.agent[data-id="cc-own"] [data-key="advisor"]').count(), 0);
await page.locator(`${cc} .ag-link`).click();
await page.locator(`${cc} .ag-exp`).waitFor();
// a line of the opened row's Tiers, after Auto mode; no square
assert.equal(await page.locator(`${cc} .field.extra[data-key="advisor"]`).count(), 0);
const pick = page.locator(`${cc} .ag-exp .field.ag-pick[data-key="advisor"]`);
assert.equal(await pick.count(), 1);
const keys = await page.locator(`${cc} .ag-exp .field.ag-pick`).evaluateAll((es) => es.map((e) => e.dataset.key));
assert.deepEqual(keys.slice(-2), ["auto_mode", "advisor"]);
const line = pick.locator("xpath=..");
assert.equal(await line.locator(".ag-tier").textContent(), w.line);
assert.equal(await line.locator(".ag-hint").textContent(), "/advisor");
assert.equal(await pick.locator(".v").textContent(), w.off);
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), "the Agents view overflows");
// the app's model picker, Off first
const y = await page.evaluate(() => scrollY);
await pick.click();
await page.locator("#pop:not([hidden]) #list li").first().waitFor();
assert.equal(await page.evaluate(() => scrollY), y, "the click scrolled the page");
assert.equal(await page.locator("#pop").evaluate((e) => e.classList.contains("model-picker")), true);
const first = await page.locator("#pop #list li").first().innerText();
assert.ok(first.includes(w.off) && first.includes(w.note), first);
await page.locator("#pop #list li", { hasText: "Flash" }).first().click();
await page.waitForFunction(() => document.querySelector('.row.agent[data-id="claude"] .ag-exp .field[data-key="advisor"] .v:not(.empty)'));
assert.deepEqual(sets, [{ agent: "claude", field: "advisor", value: "magpie/v/flash" }]);
// Off takes it out again
await page.locator(`${cc} .ag-exp .field.ag-pick[data-key="advisor"]`).click();
await page.locator("#pop:not([hidden]) #list li").first().waitFor();
await page.locator("#pop #list li").first().click();
await page.waitForFunction(() => document.querySelector('.row.agent[data-id="claude"] .ag-exp .field[data-key="advisor"] .v.empty'));
assert.deepEqual(sets.at(-1), { agent: "claude", field: "advisor", value: "" });
assert.equal(await page.evaluate(() => scrollY), y, "a pick scrolled the page");
assert.deepEqual(errors, []);
});
}
}
}