The Claude subscription bridge runs the real Claude Code with magpie's
tools only, so Claude Code's advisor (Anthropic's server tool
advisor_20260301) was read like a translation without one: dropped from
the request and its instructions rewritten to "The advisor tool is no
longer available". /advisor did nothing (recih on X, #6813; swordencao's
group advisor, #6804).
bridgeRequest now reads a Claude Code request whose advisor model magpie
serves (advisedInBridge: provider.Resolve takes it, groups and [1m]
included) as readAdvised does: Request.Advisor is set, the instructions
stay as Claude Code wrote them. The run is offered advisorToolDef beside
magpie's tools; mcpCall answers a call by asking the advisor model
(adviceRound, 55s), and the client is told a server_tool_use and an
advisor_tool_result as Anthropic's server tells it, max_uses_exceeded
past three a reply. Claude Desktop and an advisor magpie doesn't serve
go as before. Nothing about the request's identity changes: the run is
still the real Claude Code, and the advisor tool goes to no upstream.
adviceFor, shared with the vendor route, now cuts Claude Code's advisor
instructions from what the advisor model is asked (advisorCut). With
them, or advisorGone in their place, the advisor answered as the executor
that it had no advisor; seen in the reporter's exact #6804 run.
Not changed: Claude Code's Code Mode (read in 2.1.325) needs ANTHROPIC_BASE_URL
on api.anthropic.com, first-party auth with no auth token or helper, and
a GrowthBook flag; no gateway can serve it without faking Anthropic.
Run:
- go test ./internal/gateway -run 'Advis|ClaudeTUIAdvisor|BridgeRequest'
ok (mote). Red on the old code: TestBridgeRequestKeepsTheAdvisor
("the advisor is \"\""); with advisorCut a no-op,
TestAdvisorServedForAVendorModel and TestClaudeTUIAdvisorAnsweredHere
("the advisor was told of itself").
- go vet ./internal/gateway on darwin, linux, windows; go test
./internal/gateway -timeout 45m at 7abbfac34 (rebased on origin/main
2026-11-16): ok, 946s (mote). At d54abb292, rebased on 58cf76453:
vet on the three OSes and -run 'Advis|ClaudeTUI|BridgeRequest|
Subscription|Doc|Subsystem' ok.
- Real Claude Code 2.1.316, sandbox CLAUDE_CONFIG_DIR and HOME, the
owner's real Claude subscription, magpie serve on a sandbox port,
#6804's settings (model group/claude-opus-max, advisorModel
group/claude-fable-high[1m], effort max), claude -p: server_tool_use plus an
advisor_tool_result with real advice (17x19 checked two ways), the
answer built on it. Earlier, a natural coding task got advice mid-run
and kept going. Tokens unchanged; the sandbox keychain item deleted.
Not tried: the interactive /advisor in the TUI client (only -p), Windows
and Linux runs of the bridge, Code Mode in a sandbox.
This commit is contained in:
@@ -135,6 +135,30 @@ handed over as `mcp__linear__…`. A deferred tool the run's model calls
|
||||
by the bare client name (`WebFetch`, `mcp__linear__…`) is the run's
|
||||
Claude Code's to answer and is not handed over.
|
||||
|
||||
Claude Code's `/advisor` (`advisor_20260301`, sent with
|
||||
`CLAUDE_CODE_ENABLE_EXPERIMENTAL_ADVISOR_TOOL`, which the Claude Code
|
||||
advisor field writes) is a server tool: the run's Claude Code, offered
|
||||
magpie's tools only, can't pass it on, and Anthropic's server would not
|
||||
take magpie's id for its model anyway. Before #6804 the bridge read the
|
||||
request as a translation without one: the advisor was left out and its
|
||||
instructions turned into "The advisor tool is no longer available"
|
||||
(`advisorGoneIn`), so `/advisor` did nothing (recih on X, #6813).
|
||||
`bridgeRequest` now reads a Claude Code request whose advisor model
|
||||
magpie serves (`advisedInBridge`: `provider.Resolve` takes it, the client
|
||||
has no `advisor` tool of its own) as `readAdvised` does on a translation:
|
||||
`Request.Advisor` is set, the instructions and `tool_addition` stay as
|
||||
written, and the echoed `server_tool_use` and `advisor_tool_result` go
|
||||
back as the model's call and its result (`adviceApart`). The run is
|
||||
offered `advisorToolDef` beside magpie's tools, and `adviseOn` gives the
|
||||
run, for this request, `adviceRound`. A call of it is answered in
|
||||
`mcpCall`, as web search is: the advisor model is asked with what the
|
||||
reply said before the call (`adviceSaid`), within 55 seconds, and three
|
||||
calls a reply (`max_uses_exceeded` after). `toolStart` keeps the call
|
||||
from the client, which is told `KAdvice`'s `server_tool_use` and
|
||||
`advisor_tool_result` as on a translation. Claude Desktop, and an
|
||||
advisor model magpie doesn't serve, go as before.
|
||||
`TestBridgeRequestKeepsTheAdvisor`, `TestClaudeTUIAdvisorAnsweredHere`.
|
||||
|
||||
A turn with `tool_choice` none is offered every tool the client sent, as
|
||||
any other turn is (bbfatx on X). Anthropic caches a prompt as tools, then
|
||||
system, then messages, so a turn offered fewer tools (a title or summary
|
||||
|
||||
@@ -406,8 +406,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, unless two rows are named after one Claude model of Desktop's catalog, when the list is written for its `labelOverride`s alone (`desktopNamesClash`, onkashiko on X). 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), Hermes Agent's earlier default persona, and oh-my-pi's RFC 2119 line; since the evening of 11-14 also "You are Hermes Agent" (Hermes' current persona), "You are OpenCode", Codex CLI's "You are a coding agent running in the Codex CLI" (its prompt for models it has none of its own for) and pi's "a coding assistant running inside pi". Codex's GPT-6 prompt, Claude Code's own line, Gemini CLI, Qwen Code, Cline, Kilo, goose, Amp, Droid, Kimi, Aider and Cursor pass as written (real account, 11-14). An Antigravity account's system instruction goes with each such line reworded with the same meaning (`antigravityCloak`, `agSaidAs`, in `codeAssistBody`): the billing line left out, "built on the Claude Agent SDK by Anthropic", Codex's "built on GPT-5", Hermes' "built by Nous Research", oh-my-pi's "RFC 2119 key words", "You're" for Hermes', OpenCode's and Codex CLI's "You are", and pi's "running within pi". The refusal's hint names the agent (`antigravityHint`: Codex, Codex CLI, Hermes, OpenCode, pi, RFC), word for word as the antigravity and agy-cli plugins and the Routing page's `HINTS` have it. Until 11-14 they went broken up by zero-width spaces; since then Google's check reads past invisible characters and turned every broken-up line away 5 of 5 on a real account, so a line is also matched with invisible characters inside it and a copy an older magpie or middleware broke up is reworded too. 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 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`.
|
||||
- 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 bridge runs it as magpie does on a translation (below, and [claude-subscription-bridge.md](claude-subscription-bridge.md)). `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`; Claude Code's advisor instructions are cut from its system prompt and messages, `advisorCut`, since with them, or `advisorGone` in their place, the advisor answered as the executor that it had no advisor, #6804), 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.
|
||||
|
||||
@@ -148,6 +148,23 @@ func advisorGoneIn(text string) (string, bool) {
|
||||
return text[:i] + advisorGone + trail + text[end:], true
|
||||
}
|
||||
|
||||
// advisorCut is text without the advisor's instructions, up to the end of
|
||||
// the reminder they are in or of the text, and whether it held them: the
|
||||
// advisor model is asked with the executor's conversation (adviceFor), and
|
||||
// the executor's instructions to call it, or advisorGone in their place,
|
||||
// had it answer as the executor that it has no advisor (#6804).
|
||||
func advisorCut(text string) (string, bool) {
|
||||
i := strings.Index(text, advisorNote)
|
||||
if i < 0 {
|
||||
return text, false
|
||||
}
|
||||
end := len(text)
|
||||
if j := strings.Index(text[i:], "</system-reminder>"); j >= 0 {
|
||||
end = i + j
|
||||
}
|
||||
return strings.TrimRight(text[:i], " \t\r\n") + text[end:], true
|
||||
}
|
||||
|
||||
// withoutAdvisor is a Messages request's messages without what Claude Code
|
||||
// put there for an advisor tool that is left out, named in gone: the
|
||||
// tool_addition (or tool_removal, tool_reference) naming it, and a message
|
||||
|
||||
@@ -49,9 +49,25 @@ const advisorUses = 3
|
||||
// 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 || !bodyHas(body, `"advisor_`) {
|
||||
adv := advisorAsked(from, body)
|
||||
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
|
||||
}
|
||||
|
||||
// advisorAsked is the advisor model a Messages request asks for, or ""
|
||||
// when it asks for none or has a tool of its own by the advisor's name.
|
||||
func advisorAsked(from provider.Protocol, body []byte) string {
|
||||
if from != provider.Anthropic || !bodyHas(body, `"advisor_`) {
|
||||
return ""
|
||||
}
|
||||
adv := ""
|
||||
for _, t := range gjson.GetBytes(body, "tools").Array() {
|
||||
typ := t.Get("type").String()
|
||||
@@ -62,17 +78,21 @@ func advisedHere(p provider.Provider, from, to provider.Protocol, model string,
|
||||
continue
|
||||
}
|
||||
if t.Get("name").String() == advisorTool {
|
||||
return false // a tool of the client's own goes by the name
|
||||
return "" // a tool of the client's own goes by the name
|
||||
}
|
||||
}
|
||||
return adv
|
||||
}
|
||||
|
||||
// advisedInBridge tells whether magpie runs the advisor of a Messages
|
||||
// request a Claude subscription serves through Claude Code: the run's
|
||||
// agent is offered magpie's tools only, never Anthropic's server tool, so
|
||||
// magpie answers it whenever it serves the advisor's model.
|
||||
func advisedInBridge(from provider.Protocol, body []byte) bool {
|
||||
adv := advisorAsked(from, body)
|
||||
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
|
||||
}
|
||||
@@ -174,7 +194,7 @@ func adviceApart(m Message) []Message {
|
||||
}
|
||||
|
||||
// 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."
|
||||
const advisorAsk = "You are the advisor the assistant has just consulted. Review the conversation above, in which the assistant works on the user's task, and answer its consultation yourself. 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
|
||||
@@ -189,9 +209,16 @@ func adviceFor(q *Request, said []Part) *Request {
|
||||
c.MaxTokens = 4096
|
||||
c.ToolChoice = "none"
|
||||
c.Tools = slices.DeleteFunc(slices.Clone(q.Tools), func(t Tool) bool { return t.Name == advisorTool })
|
||||
c.System, _ = advisorCut(q.System)
|
||||
var msgs []Message
|
||||
keep := func(m Message) Message {
|
||||
m.Parts = slices.DeleteFunc(slices.Clone(m.Parts), func(p Part) bool { return p.Kind == Thinking })
|
||||
for i, p := range m.Parts {
|
||||
if p.Kind == Text {
|
||||
m.Parts[i].Text, _ = advisorCut(p.Text)
|
||||
}
|
||||
}
|
||||
m.Parts = slices.DeleteFunc(m.Parts, func(p Part) bool { return p.Kind == Text && strings.TrimSpace(p.Text) == "" })
|
||||
return m
|
||||
}
|
||||
for _, m := range q.Messages {
|
||||
|
||||
@@ -177,6 +177,11 @@ func TestAdvisorServedForAVendorModel(t *testing.T) {
|
||||
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])
|
||||
}
|
||||
// and not the executor's instructions to call it, nor that it is
|
||||
// gone: it answered as the executor that it has no advisor (#6804)
|
||||
if strings.Contains(adv[0], "You have access to an `advisor` tool") || strings.Contains(adv[0], advisorGone) {
|
||||
t.Fatalf("stream=%t: the advisor was told of itself: %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])
|
||||
|
||||
@@ -343,6 +343,16 @@ type subscriptionRun struct {
|
||||
// client never sees
|
||||
search func(ctx context.Context, query string) (string, []Hit, error)
|
||||
searchName string
|
||||
// advice answers Claude Code's advisor (advisor_serve.go), which the
|
||||
// client is told of as Anthropic's server tells it: for the request
|
||||
// the run now answers, adviceReq, its nth call made after said. The
|
||||
// run's agent is offered magpie's tools only, never the server tool.
|
||||
// adviceSaid is the reply's words so far, and advised the calls of
|
||||
// it, both counted from the request. Under mu.
|
||||
advice func(ctx context.Context, q *Request, said []Part, c Part, n int) (Part, Event)
|
||||
adviceReq *Request
|
||||
adviceSaid []string
|
||||
advised int
|
||||
// answerName is the interactive mode's answer tool for a request with
|
||||
// a JSON schema (claude_tui_schema.go), its calls checked against
|
||||
// answerSchema, and answerArgs the input of the one that fit, until the
|
||||
@@ -4074,6 +4084,10 @@ func (r *subscriptionRun) emit(ev Event) {
|
||||
switch ev.Kind {
|
||||
case KStart: // a reply begins
|
||||
r.shown, r.unended = nil, true
|
||||
case KText:
|
||||
if r.adviceReq != nil {
|
||||
r.adviceSaid = append(r.adviceSaid, ev.Text)
|
||||
}
|
||||
case KStop, KError:
|
||||
r.unended = false
|
||||
case KToolStart:
|
||||
@@ -4104,6 +4118,18 @@ func (r *subscriptionRun) emit(ev Event) {
|
||||
}
|
||||
}
|
||||
|
||||
// adviseOn has the run answer the advisor calls of the reply to req, the
|
||||
// advisor seeing req's conversation, with advice when req asks for the
|
||||
// advisor; a request that doesn't takes it away.
|
||||
func (r *subscriptionRun) adviseOn(req *Request, advice func(ctx context.Context, q *Request, said []Part, c Part, n int) (Part, Event)) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.advice, r.adviceReq, r.advised, r.adviceSaid = nil, nil, 0, nil
|
||||
if req.Advisor != "" {
|
||||
r.advice, r.adviceReq = advice, req
|
||||
}
|
||||
}
|
||||
|
||||
// closeSegment closes a segment taken off the run, once no send to it is
|
||||
// under way.
|
||||
func (r *subscriptionRun) closeSegment(ch chan Event) {
|
||||
@@ -4261,7 +4287,8 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
|
||||
r.mu.Lock()
|
||||
called := name
|
||||
name = declaredName(r.names, rest)
|
||||
search := r.search != nil && name == r.searchName || r.answerName != "" && name == r.answerName
|
||||
search := r.search != nil && name == r.searchName || r.answerName != "" && name == r.answerName ||
|
||||
r.advice != nil && name == advisorTool
|
||||
refused := r.allowed != nil && !r.allowed[name]
|
||||
// a tool the client announced but hasn't loaded yet (Claude
|
||||
// Code's deferred tools, told by name in the conversation and
|
||||
@@ -6327,11 +6354,26 @@ func (b *subscriptionBridge) mcpCall(w http.ResponseWriter, r *http.Request) {
|
||||
run.mu.Lock()
|
||||
call.Name = declaredName(run.names, call.Name)
|
||||
search, searchName, answerName := run.search, run.searchName, run.answerName
|
||||
advice := run.advice
|
||||
run.mu.Unlock()
|
||||
if answerName != "" && call.Name == answerName {
|
||||
run.answer(w, call.Arguments)
|
||||
return
|
||||
}
|
||||
if advice != nil && call.Name == advisorTool {
|
||||
run.mu.Lock()
|
||||
run.advised++
|
||||
q, n := run.adviceReq, run.advised
|
||||
said := []Part{{Kind: Text, Text: strings.Join(run.adviceSaid, "")}}
|
||||
run.mu.Unlock()
|
||||
// within the minute its MCP client waits for a call
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 55*time.Second)
|
||||
defer cancel()
|
||||
res, ev := advice(ctx, q, said, Part{Kind: ToolCall, ID: call.ToolCallID, Name: advisorTool}, n)
|
||||
run.emit(ev)
|
||||
writeJSON(w, 200, mcpToolResult{Content: []map[string]any{{"type": "text", "text": res.Text}}, IsError: res.IsError})
|
||||
return
|
||||
}
|
||||
if search != nil && call.Name == searchName {
|
||||
var a struct {
|
||||
Query string `json:"query"`
|
||||
@@ -7105,14 +7147,27 @@ func (s *Server) serveSubscription(w http.ResponseWriter, r *http.Request, from
|
||||
return s.serveSubscriptionAs(w, r, from, name, model, owner, body, usage, start, "")
|
||||
}
|
||||
|
||||
// serveSubscriptionAs is serveSubscription, redo the code of a turn asked
|
||||
// again as claude -p after the interactive mode's run failed with nothing
|
||||
// of the reply said (redoAsPrint): thirdPartyCode, refused as a
|
||||
// third-party app's, or unpastedCode, its message not taken there.
|
||||
func (s *Server) serveSubscriptionAs(w http.ResponseWriter, r *http.Request, from provider.Protocol, name, model, owner string, body []byte, usage *Usage,
|
||||
start func(ctx context.Context, req *Request) (*subscriptionRun, <-chan Event, error), redo string) (int, string) {
|
||||
var req *Request
|
||||
var err error
|
||||
// bridgeRequest is the request a Claude subscription's run is told, as
|
||||
// serveSubscriptionAs reads it: with the client's cache marks when Claude
|
||||
// Code places its own, and with Claude Code's advisor, which magpie runs
|
||||
// (advisor_serve.go), when magpie serves the advisor's model.
|
||||
func bridgeRequest(r *http.Request, from provider.Protocol, name string, body []byte) (req *Request, err error) {
|
||||
// Claude Code's advisor, run by magpie: the run's agent has no server
|
||||
// tools (advisor_serve.go)
|
||||
advised := name == "Claude Code" && advisedInBridge(from, body)
|
||||
parse := parse
|
||||
if advised {
|
||||
parse = func(from provider.Protocol, body []byte) (*Request, error) {
|
||||
req, err := readAdvised(body, false, false, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return afterParse(from, body, req)
|
||||
}
|
||||
}
|
||||
parseAnthropicRequest := func(body []byte, clientMarks bool) (*Request, error) {
|
||||
return readAdvised(body, clientMarks, false, advised)
|
||||
}
|
||||
if name == "Claude Code" && wantsClientCache(r, from) {
|
||||
req, err = parseAnthropicRequest(body, true)
|
||||
} else if name == "Claude Code" && classifierClientCache(from, body) {
|
||||
@@ -7128,6 +7183,16 @@ func (s *Server) serveSubscriptionAs(w http.ResponseWriter, r *http.Request, fro
|
||||
} else {
|
||||
req, err = parse(from, body)
|
||||
}
|
||||
return req, err
|
||||
}
|
||||
|
||||
// serveSubscriptionAs is serveSubscription, redo the code of a turn asked
|
||||
// again as claude -p after the interactive mode's run failed with nothing
|
||||
// of the reply said (redoAsPrint): thirdPartyCode, refused as a
|
||||
// third-party app's, or unpastedCode, its message not taken there.
|
||||
func (s *Server) serveSubscriptionAs(w http.ResponseWriter, r *http.Request, from provider.Protocol, name, model, owner string, body []byte, usage *Usage,
|
||||
start func(ctx context.Context, req *Request) (*subscriptionRun, <-chan Event, error), redo string) (int, string) {
|
||||
req, err := bridgeRequest(r, from, name, body)
|
||||
if err != nil {
|
||||
return writeError(w, from, 400, err.Error()), err.Error()
|
||||
}
|
||||
@@ -7221,6 +7286,10 @@ func (s *Server) serveSubscriptionAs(w http.ResponseWriter, r *http.Request, fro
|
||||
req.Tools = append(slices.Clone(req.Tools), search)
|
||||
}
|
||||
}
|
||||
// and asks the advisor with magpie's tool, which magpie answers
|
||||
if req.Advisor != "" {
|
||||
req.Tools = append(slices.Clone(req.Tools), advisorToolDef())
|
||||
}
|
||||
|
||||
run, results, how := s.subscription.match(req)
|
||||
// Another request has the run's calls answered, or is answering them,
|
||||
@@ -7306,6 +7375,7 @@ func (s *Server) serveSubscriptionAs(w http.ResponseWriter, r *http.Request, fro
|
||||
run.mu.Lock()
|
||||
run.allowed = allowedTools(req)
|
||||
run.mu.Unlock()
|
||||
run.adviseOn(req, s.adviceRound)
|
||||
events, err = run.continueWith(withTaskNotices(withSkillBodies(results, req.Messages), req.Messages), saidWithResults(req.Messages), more)
|
||||
}
|
||||
if err != nil {
|
||||
@@ -7349,6 +7419,7 @@ func (s *Server) serveSubscriptionAs(w http.ResponseWriter, r *http.Request, fro
|
||||
run.answerName, run.answerSchema = answer.Name, answerSchema
|
||||
}
|
||||
run.mu.Unlock()
|
||||
run.adviseOn(req, s.adviceRound)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// Claude Code's /advisor through a Claude subscription (recih on X,
|
||||
// #6804, #6813): the run's Claude Code is offered magpie's tools only, so
|
||||
// the advisor, Anthropic's server tool, was left out of the request and
|
||||
// its instructions said to be void. magpie now runs it as it does for a
|
||||
// vendor's model: it is read as the model's own advisor, its instructions
|
||||
// kept as Claude Code wrote them, and an advisor magpie doesn't serve is
|
||||
// still left out.
|
||||
func TestBridgeRequestKeepsTheAdvisor(t *testing.T) {
|
||||
advisedSetup(t)
|
||||
r := httptest.NewRequest("POST", "/v1/messages", nil)
|
||||
req, err := bridgeRequest(r, provider.Anthropic, "Claude Code", []byte(advisorTurn("claude/claude-sonnet-5-5", "adv/adv-pro")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if req.Advisor != "adv/adv-pro" {
|
||||
t.Fatalf("the advisor is %q", req.Advisor)
|
||||
}
|
||||
if words := allText(req); !strings.Contains(words, advisorNote) || strings.Contains(words, advisorGone) {
|
||||
t.Fatalf("the advisor's instructions were changed:\n%s", words)
|
||||
}
|
||||
for _, c := range []struct{ name, advisor string }{
|
||||
{"Claude Desktop", "adv/adv-pro"},
|
||||
{"Claude Code", "nobody/x"},
|
||||
} {
|
||||
req, err := bridgeRequest(r, provider.Anthropic, c.name, []byte(advisorTurn("claude/claude-sonnet-5-5", c.advisor)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if req.Advisor != "" {
|
||||
t.Fatalf("%s, advisor %s: advised by %q", c.name, c.advisor, req.Advisor)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// allText is every text part of req's messages.
|
||||
func allText(req *Request) string {
|
||||
var b strings.Builder
|
||||
for _, m := range req.Messages {
|
||||
for _, p := range m.Parts {
|
||||
if p.Kind == Text {
|
||||
b.WriteString(p.Text)
|
||||
b.WriteString("\n")
|
||||
}
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// The run's Claude Code calls magpie's advisor tool: magpie asks the
|
||||
// advisor model, hands the advice back to the run, and tells the client
|
||||
// as Anthropic's server does, a server_tool_use and an
|
||||
// advisor_tool_result with the advice, never a call of a tool of its own.
|
||||
// The advisor sees what the reply said before the call; a reply's fourth
|
||||
// call is answered max_uses_exceeded without asking.
|
||||
func TestClaudeTUIAdvisorAnsweredHere(t *testing.T) {
|
||||
u := advisedSetup(t)
|
||||
c := newTUICalls(t)
|
||||
q, err := bridgeRequest(httptest.NewRequest("POST", "/v1/messages", nil), provider.Anthropic, "Claude Code", []byte(advisorTurn("claude/claude-sonnet-5-5", "adv/adv-pro")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c.run.adviseOn(q, New().adviceRound)
|
||||
first := c.run.segment
|
||||
// a message's blocks are each a row of their own, by its id
|
||||
c.write(tuiRow("msg_a0", `{"type":"text","text":"Let me ask."}`, "tool_use", 4))
|
||||
var res []mcpToolResult
|
||||
for i := range advisorUses + 1 {
|
||||
id := "toolu_adv" + itoa(i)
|
||||
c.write(tuiRow("msg_a"+itoa(i), `{"type":"tool_use","id":"`+id+`","name":"mcp__magpie__advisor","input":{}}`, "tool_use", 2))
|
||||
res = append(res, c.adviceCall(id))
|
||||
}
|
||||
c.write(tuiRow("msg_end", `{"type":"text","text":"Done."}`, "end_turn", 2), tuiDone)
|
||||
text, calls, stop, _, raw := c.reply(first)
|
||||
if len(calls) != 0 || stop != "end_turn" || !strings.Contains(text, "Done.") {
|
||||
t.Fatalf("the reply %q %v %q:\n%s", text, calls, stop, raw)
|
||||
}
|
||||
for i, r := range res[:advisorUses] {
|
||||
if r.IsError || r.Content[0]["text"] != "Check the tests first." {
|
||||
t.Fatalf("call %d was answered %+v", i, r)
|
||||
}
|
||||
}
|
||||
if last := res[advisorUses]; !last.IsError || !strings.Contains(last.Content[0]["text"].(string), "max_uses_exceeded") {
|
||||
t.Fatalf("a call past the limit was answered %+v", last)
|
||||
}
|
||||
u.mu.Lock()
|
||||
asked := append([]string(nil), u.advisor...)
|
||||
u.mu.Unlock()
|
||||
if len(asked) != advisorUses || !strings.Contains(asked[0], "Let me ask.") {
|
||||
t.Fatalf("the advisor model was asked %d times: %v", len(asked), asked)
|
||||
}
|
||||
if strings.Contains(asked[0], "You have access to an `advisor` tool") || strings.Contains(asked[0], advisorGone) {
|
||||
t.Fatalf("the advisor was told of itself: %s", asked[0])
|
||||
}
|
||||
var uses, results, advice int
|
||||
for _, l := range strings.Split(raw, "\n") {
|
||||
data, ok := strings.CutPrefix(l, "data: ")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
b := gjson.Get(data, "content_block")
|
||||
switch {
|
||||
case b.Get("type").String() == "server_tool_use" && b.Get("name").String() == advisorTool:
|
||||
uses++
|
||||
case b.Get("type").String() == "advisor_tool_result":
|
||||
results++
|
||||
if b.Get("content.text").String() == "Check the tests first." {
|
||||
advice++
|
||||
}
|
||||
case b.Get("type").String() == "tool_use":
|
||||
t.Fatalf("the client was told a call of its own:\n%s", raw)
|
||||
}
|
||||
}
|
||||
if uses != advisorUses+1 || results != advisorUses+1 || advice != advisorUses {
|
||||
t.Fatalf("told %d uses, %d results, %d with the advice:\n%s", uses, results, advice, raw)
|
||||
}
|
||||
}
|
||||
|
||||
// adviceCall makes Claude Code's call of the advisor tool and returns
|
||||
// what the MCP helper is told.
|
||||
func (c *tuiCalls) adviceCall(id string) mcpToolResult {
|
||||
c.t.Helper()
|
||||
r := httptest.NewRequest("POST", "/", strings.NewReader(`{"tool_call_id":"`+id+`","name":"advisor","arguments":{}}`))
|
||||
r.SetPathValue("token", "run")
|
||||
rec := httptest.NewRecorder()
|
||||
c.bridge.mcpCall(rec, r)
|
||||
var res mcpToolResult
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
|
||||
c.t.Fatalf("the advisor tool said %q: %v", rec.Body.String(), err)
|
||||
}
|
||||
return res
|
||||
}
|
||||
Reference in New Issue
Block a user