Files
magpie/internal/gateway/advisor.go
T
yetone 81a24cf8fe groups: a found group is listed as auto/<model id as the vendor spells it>
ZeroClover asked on X: Auto Group ids group/auto-<slug> can't be looked
up on models.dev. A found group is now listed and written as
auto/<model>, e.g. auto/claude-opus-5.5: /v1/models, the catalog, agent
configs, the GUI's Routing page and the CLI. Context and output limits
come from the model's metadata as before.

What stays the same:
- The internal id is still group/auto-<slug> (Group.Ref() gives the
  public one). Every old form is still accepted as input forever:
  provider.CanonicalRef turns auto/<model>[:level][[1m]] into it at the
  gateway (validateModel), keys, stats, affinity and usage, so both ids
  route to the same group and count as one.
- A key's model list allows a model by either id, group/* included
  (allows() in key_models.go).
- Hand-made groups stay group/<id>.
- A provider whose stored id is "auto" keeps its models: while one
  exists, found groups are listed by their old id (AutoRefsOn) and
  auto/<x> means that provider's model. Documented in
  docs/subsystems/gateway-routing.md.

Agent configs: SyncCatalog rewrites a field that holds a found group's
old id (renameFoundGroups), but only while the value is still what
applied.json says magpie wrote; a value the user set stays. A pick by
the old id written now is written as auto/<model> (Apply). Hidden,
picked and ordered model lists saved by the old id hold for the new one
(visible.go), and a bare model id still reaches its found group (bare.go).

Claude Code is given a dotted Claude version dashed (ClaudeSpelled), so
auto/claude-sonnet-4.5 sits in its settings as auto/claude-sonnet-4-5.
That routes to the same group, but with found groups off nothing reads
it back dotted, and Reseat took the field for changed and left the agent
on a group that was gone. Reseat now compares a group pick by its
canonical id (samePick). The old ids had no dots, so this is new with
auto/<model>.

Run at this tree (sandbox HOME, caches pinned):
- gofmt -l: clean. go vet ./...: clean on darwin, GOOS=linux -tags
  nogui, GOOS=windows.
- go test -p 4 -timeout 45m ./...: every package ok except agent and
  gateway, whose failures were the tests' expected ids (updated here)
  and two regressions now fixed (bare ids; desktop models hiding groups
  by prefix). Every failing test passes on rerun. Load average was
  ~210-290 from other sessions throughout.
- Reruns: provider, cli, codexcat ok. internal/gui: only
  TestSetAnswersWhileDevinAndProvidersHang fails (set slow/slow-1 took
  10.19s), and it fails the same in a git-archive export of 33dbdcc52.
- agent and gateway in full, -p 2 -timeout 120m: gateway ok (2996s).
  agent failed four tests that still expected the old ids
  (TestOmp/PiModelsAskedOnTheirNativeAPI, TestReseatFoundGroupsOff,
  TestReseatKeepsAFoundGroupWithAProviderOff); updating them showed the
  Reseat bug above. After the fix, go test -count=1 -timeout 120m
  ./internal/agent/: ok (1000s, load ~160-220).
- GUI files the change reaches, chromium and webkit: group-found-off and
  the routing files pass, except routing-bodies, routing-model-rest,
  routing-keys-fold and routing-request-metrics, which fail the same with
  33dbdcc52's JS.

Broken by hand and watched red, then restored: CanonicalRef in
validateModel (both-ids routing test), allows() (key tests both ways),
the Save refusal and AutoRefsOn checks in Ref/CanonicalRef (provider
named auto), catalog.Lists' preference (models.dev lookup of the part
after auto/), renameFoundGroups' applied.json check and its SyncCatalog
call (user values kept), PublicRef in visible.go, the codexcat prefix,
samePick in Reseat (TestReseatFoundGroupsOff: opus left on the gone
group).
TestBareModelIDsShared was red before the bare.go fix.

Not verified: no real agent, vendor or models.dev client run; no run on
the Windows box. Settings pickers (vision, title model) holding a saved
group/auto-... value may show it as saved. codexcat can't tell a stored
"auto" provider apart, so its models lose the "text only" hint. The
pre-existing reds above are not filed.
2026-10-20 00:18:51 +08:00

224 lines
6.6 KiB
Go

package gateway
import (
"bytes"
"encoding/json"
"strings"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
// advisorTools fits Claude Code's advisor (/advisor, --advisor) to the
// upstream a Messages request goes to as it is (passthrough). Claude Code
// declares it as Anthropic's server tool, {"type": "advisor_20260301",
// "name": "advisor", "model": …}, and names the advisor's model as it
// names its own: on magpie, by magpie's id ("anthropic/claude-opus-5-5",
// or the tier an alias like opus is on), which no vendor knows, so the
// whole request was turned away (JackChou on Discord).
//
// The advisor runs at the vendor, on the same account: its model goes as
// that upstream's own name for it when it is p's, as the request's own
// model does (wires). An advisor magpie can't give that upstream (another
// provider's model, or not a Claude model) is left out, and so is every
// advisor when the request's model is not Claude's (a vendor's Messages
// API knows no such tool): the turn is answered without one, as a model
// that isn't on magpie would be. What Claude Code put in the conversation
// for an advisor left out goes with it (withoutAdvisor).
func advisorTools(body []byte, p provider.Provider, upstream string, wires map[string]string) []byte {
if !bytes.Contains(body, []byte(`"advisor_`)) {
return body
}
tools := gjson.GetBytes(body, "tools")
if !tools.IsArray() {
return body
}
var top map[string]json.RawMessage
var list []map[string]json.RawMessage
if json.Unmarshal(body, &top) != nil || json.Unmarshal([]byte(tools.Raw), &list) != nil {
return body
}
claude := anthropicModel.MatchString(upstream)
changed := false
gone := map[string]bool{}
kept := list[:0]
for _, t := range list {
var typ, model string
json.Unmarshal(t["type"], &typ)
if !strings.HasPrefix(typ, "advisor_") {
kept = append(kept, t)
continue
}
json.Unmarshal(t["model"], &model)
name, ok := advisorModel(p, model, wires)
if !claude || !ok {
var n string
json.Unmarshal(t["name"], &n)
gone[n] = true
changed = true
continue
}
if name != model {
t["model"], _ = json.Marshal(name)
changed = true
}
kept = append(kept, t)
}
if !changed {
return body
}
if len(kept) == 0 {
delete(top, "tools")
delete(top, "tool_choice")
} else {
top["tools"], _ = json.Marshal(kept)
}
if m, ok := withoutAdvisor(top["messages"], gone); ok {
top["messages"] = m
}
out, err := json.Marshal(top)
if err != nil {
return body
}
return out
}
// advisorModel is the name p's upstream knows the advisor model by, and
// whether p can run it: one of p's models, by magpie's id, or a Claude
// model's own id that names no provider.
func advisorModel(p provider.Provider, model string, wires map[string]string) (string, bool) {
model = strings.TrimSuffix(strings.TrimSpace(model), "[1m]")
if model == "" {
return "", false
}
if q, m, ok := provider.Resolve(model); ok && !provider.IsGroupRef(model) {
if q.ID != p.ID {
return "", false
}
name := provider.UpstreamNameIn(wires, p.ID, m)
return name, anthropicModel.MatchString(name)
}
if strings.Contains(model, "/") {
return "", false
}
return model, anthropicModel.MatchString(model)
}
// advisorNote opens the instructions Claude Code puts in the conversation
// when its advisor is on ("# Advisor Tool\n\nYou have access to an
// `advisor` tool … Call advisor BEFORE substantive work"), at the end of a
// {role: "system"} message's text (2.1.300), and advisorGone is what Claude
// Code itself says there once the advisor is turned off.
const (
advisorNote = "# Advisor Tool\n"
advisorGone = "The advisor tool is no longer available; disregard the earlier advisor instructions."
)
// advisorGoneIn is text with the advisor's instructions, up to the end of
// the reminder they are in or of the text, said to be void as Claude Code
// says it, and whether it held them.
func advisorGoneIn(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
}
note := text[i:end]
trail := note[len(strings.TrimRight(note, " \t\r\n")):]
return text[:i] + advisorGone + trail + 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
// that leaves empty; and its instructions, said to be void (advisorGoneIn).
// Left there, the reference named a tool the request no longer has, and
// the instructions had the model call advisor() as one of the agent's own
// tools, which Claude Code answers "No such tool available: advisor"
// (JackChou on Discord).
func withoutAdvisor(raw json.RawMessage, gone map[string]bool) (json.RawMessage, bool) {
if len(gone) == 0 || !bytes.Contains(raw, []byte("dvisor")) {
return raw, false
}
var msgs []map[string]json.RawMessage
if json.Unmarshal(raw, &msgs) != nil {
return raw, false
}
changed := false
out := msgs[:0]
for _, m := range msgs {
var s string
if json.Unmarshal(m["content"], &s) == nil {
if t, ok := advisorGoneIn(s); ok {
m["content"], _ = marshalPlain(t)
changed = true
}
out = append(out, m)
continue
}
var blocks []map[string]json.RawMessage
if json.Unmarshal(m["content"], &blocks) != nil {
out = append(out, m)
continue
}
moved := false
kept := blocks[:0]
for _, b := range blocks {
var typ string
json.Unmarshal(b["type"], &typ)
if deferredBlock(typ) && gone[advisorRefName(b)] {
moved = true
continue
}
var text string
if typ == "text" && json.Unmarshal(b["text"], &text) == nil {
if t, ok := advisorGoneIn(text); ok {
b["text"], _ = marshalPlain(t)
moved = true
}
}
kept = append(kept, b)
}
if !moved {
out = append(out, m)
continue
}
changed = true
if len(kept) == 0 {
continue // it said only that the advisor came or went
}
m["content"], _ = marshalPlain(kept)
out = append(out, m)
}
if !changed {
return raw, false
}
b, err := marshalPlain(out)
if err != nil {
return raw, false
}
return b, true
}
// advisorRefName is the tool a deferred-tool block names: a tool_addition's
// or tool_removal's tool, or a tool_reference's own name.
func advisorRefName(b map[string]json.RawMessage) string {
var n string
if t, ok := b["tool"]; ok {
var tool map[string]json.RawMessage
if json.Unmarshal(t, &tool) == nil {
json.Unmarshal(tool["name"], &n)
}
return n
}
if json.Unmarshal(b["name"], &n) == nil && n != "" {
return n
}
json.Unmarshal(b["tool_name"], &n)
return n
}