agent: a proxy on this machine with a route of its own reaches magpie too, and a pick in Claude Code keeps it (#1985)

ffd077869 took the issue's nginx example (https://ai.corp.example/magpie)
and left loopback out as "magpie on an older port". The reporter's follow-up
on #1985 is the real case: a company-mandated compliance proxy at
http://127.0.0.1:8788/claude-code-anthropic/<route> in front of
127.0.0.1:3425, which every Claude Code request must go through. On
ffd077869 that was still "unwired", Reconnect and a pick wrote 3425 back
(bypassing the proxy), and the sync did too.

- reach.go: proxyBase also takes a loopback address with a path of its own
  (loopbackWithPath). The gateway's own address, and so an older port's,
  has none, so port moves still move those. surelyMagpie: magpie has
  answered there (not merely untried), for writes.
- keptaway.go: the sync keeps such a route where magpie answered or hasn't
  been asked; one where something else answered follows the gateway.
- claude.go: routed() and the written ANTHROPIC_BASE_URL (gwAt) keep a
  proxy where magpie answered, so a model picked in magpie keeps the
  proxy and a tier's own model; before the answer, or at a relay, a pick
  points Claude Code at this magpie as before. claudeStandInAt too.
- codex.go: codexKeptGateway keeps a loopback route as well.

Run (sandbox HOME, worktree at origin/main + this):
- go test -tags nogui ./internal/agent: ok (471s).
- TestReverseProxyIsStillMagpie now runs every agent at the nginx address
  and at the reporter's local route; TestClaudeBehindLocalProxyKeepsIt is
  the reporter's case: no drift, a pick keeps the URL and a tier's own
  model, the sync keeps it, a relay there is told and a pick re-points.
- Broke by hand, each red: proxyBase without loopback (claude,
  claude-desktop... unwired), keptAway's loopback branch (every file back
  on 127.0.0.1:3591), gwAt (pick wrote 127.0.0.1:3425), routed (haiku's
  own model went), codexKeptGateway without loopback.
- gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows.

Not tried: the reporter's real proxy daemon; other agents' picks still
point at this magpie (the sync and Reconnect keep the proxy for them).
This commit is contained in:
yetone
2026-10-13 18:26:03 +08:00
parent 60f896031e
commit a0dc89e5cf
6 changed files with 177 additions and 41 deletions
+3 -3
View File
@@ -31,13 +31,13 @@ something else shows up as drift.
1. **Connect.** The Agents page's switch calls `ConnectHow` (`POST /api/agents/{action}/{id}` in [`internal/gui/api.go`](../../internal/gui/api.go)). It stashes the current values (`<id>.connect.was`). It brings back the models used before a switch-off (`reconnect`), or calls `Join` where the agent keeps its own model (Codex signed in with ChatGPT). Otherwise it picks a model by the order `ConnectHow` documents and sets it through `Apply`.
2. **Pick.** `Pick` sets a field from the model picker. Picking one of magpie's models on an agent that isn't connected connects it first.
3. **Notice.** After a change the page shows `Notice` when the agent reads its config only at start-up and needs a restart.
4. **Drift.** As the Agents page is drawn, `Drift` compares the config with `applied.json`. It runs `Check` first, then each field. An agent pointed at magpie through a reverse proxy is still on magpie (#1985, davisjiahao: a company's nginx at `https://ai.corp.example/magpie`). `wiringOff`, where most agents' `Check` compares a URL, and the checks of their own (Claude Code's managed settings, Reasonix's provider) take a URL that isn't magpie's when it ends with magpie's path, the rest is an http or https address on another machine (`onAnotherMachine`), and `GET <rest>/` there answers as the gateway's own `GET /` does (`{"name":"magpie"}`, `magpieAt` in [`reach.go`](../../internal/agent/reach.go), tried in the background like `reachProbe`). Something else there (a relay CC Switch put in) is `unwired`, as is an address on this machine's loopback, which is magpie's on an older port and is never tried. Until the answer is known it isn't drift, so Reconnect isn't offered and doesn't write the proxy away; port moves (`OnGateway`, `Rewire`) re-set only `unwired` agents, so they leave it too. Codex keeps such an address by magpie's key, as for #816 (`codexKeptGateway`: http or https, any port, a path before magpie's). Tests stub `magpieAt` in `TestMain` as known and not magpie. When the config is right and points at an address off loopback (a WSL twin under NAT, or this machine's Codex at an address the user kept, #816), it tries that address ([`reach.go`](../../internal/agent/reach.go)): in the background, at most every 20 s, never waited for. When nothing answers there while the gateway answers on loopback, the drift is `unreachable` (#1013), with what has to listen there: Share on local network, the user's portproxy, Windows' firewall. Then it checks whether the agent's latest use (`LastUsed`, `Reached`) reached the gateway: a request Codex's log says went to the host its config keeps magpie at, or one the gateway saw from it after (`lastSeen`), reached it.
4. **Drift.** As the Agents page is drawn, `Drift` compares the config with `applied.json`. It runs `Check` first, then each field. An agent pointed at magpie through a reverse proxy is still on magpie (#1985, davisjiahao: a company's nginx at `https://ai.corp.example/magpie`). `wiringOff`, where most agents' `Check` compares a URL, and the checks of their own (Claude Code's managed settings, Reasonix's provider) take a URL that isn't magpie's when it ends with magpie's path, the rest is an http or https address on another machine (`onAnotherMachine`) or one on this machine's loopback with a path of its own (`loopbackWithPath`: the reporter's compliance proxy at `http://127.0.0.1:8788/claude-code-anthropic/<route>`; `proxyBase`), and `GET <rest>/` there answers as the gateway's own `GET /` does (`{"name":"magpie"}`, `magpieAt` in [`reach.go`](../../internal/agent/reach.go), tried in the background like `reachProbe`). Something else there (a relay CC Switch put in) is `unwired`, as is an address on this machine's loopback without a path, which is magpie's on an older port and is never tried. Until the answer is known it isn't drift, so Reconnect isn't offered and doesn't write the proxy away; port moves (`OnGateway`, `Rewire`) re-set only `unwired` agents, so they leave it too. Codex keeps such an address by magpie's key, as for #816 (`codexKeptGateway`: http or https, any port, a path before magpie's, loopback with a path). A model picked in Claude Code keeps it too once magpie has answered there (`surelyMagpie`; `routed` and `gwAt` in `claude.go`), so a proxy every request must go through isn't bypassed; before that, or at a relay, a pick points Claude Code at this magpie. Tests stub `magpieAt` in `TestMain` as known and not magpie. When the config is right and points at an address off loopback (a WSL twin under NAT, or this machine's Codex at an address the user kept, #816), it tries that address ([`reach.go`](../../internal/agent/reach.go)): in the background, at most every 20 s, never waited for. When nothing answers there while the gateway answers on loopback, the drift is `unreachable` (#1013), with what has to listen there: Share on local network, the user's portproxy, Windows' firewall. Then it checks whether the agent's latest use (`LastUsed`, `Reached`) reached the gateway: a request Codex's log says went to the host its config keeps magpie at, or one the gateway saw from it after (`lastSeen`), reached it.
5. **Disconnect.** `Disconnect` puts back what the stash kept and forgets the record. It also marks the agent disconnected (`<id>.disconnected` in the stash, `Disconnected`) until the user connects it again (`connect`, or an `Apply` that leaves it wired): nothing magpie does by itself puts magpie back in meanwhile, neither a start's `Sync` nor Codex's account failover nor #701's magpie API wiring (paynezhuang on Discord: Codex had `openai_base_url` back after every update).
## Constraints and failure behavior
- magpie only removes what it wrote. Anything else in an agent's config stays as it was.
- A sync brings magpie's models up to date, not where the agent reaches magpie. Every `Sync` that `SyncCatalog` runs (each start and update of magpie, a provider added) goes through `synced`, which passes each file written through `keptAway` (`edit.Filtered`, [`keptaway.go`](../../internal/agent/keptaway.go)). In a file without the gateway's own address, whose magpie the user pointed at an address on another machine (a NAS's, or this machine's LAN address), and with no address a WSL distro was seen at, that address stays in place of `gateway.URL()`, with the path before magpie's every URL at it had (`awayPath`: a reverse proxy's `/magpie`), and so does the key that went with it in place of magpie's own (coeo91 on Discord: the base URL went back to 127.0.0.1 after an update or restart). An address on this machine's loopback follows the gateway; with more than one address or key gone, the write is left as it is. Picking a model in magpie still points the agent at this magpie. ZCode and WorkBuddy keep such an address in their own writers too (`zcodeAddress`, `buddyWriteAt`).
- A sync brings magpie's models up to date, not where the agent reaches magpie. Every `Sync` that `SyncCatalog` runs (each start and update of magpie, a provider added) goes through `synced`, which passes each file written through `keptAway` (`edit.Filtered`, [`keptaway.go`](../../internal/agent/keptaway.go)). In a file without the gateway's own address, whose magpie the user pointed at an address on another machine (a NAS's, or this machine's LAN address), and with no address a WSL distro was seen at, that address stays in place of `gateway.URL()`, with the path before magpie's every URL at it had (`awayPath`: a reverse proxy's `/magpie`; on loopback, a local proxy's route where magpie answered or hasn't been asked), and so does the key that went with it in place of magpie's own (coeo91 on Discord: the base URL went back to 127.0.0.1 after an update or restart). An address on this machine's loopback follows the gateway; with more than one address or key gone, the write is left as it is. Picking a model in magpie still points the agent at this magpie, but for Claude Code at a proxy to it (above). ZCode and WorkBuddy keep such an address in their own writers too (`zcodeAddress`, `buddyWriteAt`).
- JetBrains Air's `magpie-opencode.json` keeps user-added fields in `provider.magpie`, including nested options, on sync and model picks (`air` in [`air.go`](../../internal/agent/air.go), using `theirsKept` in [`sync.go`](../../internal/agent/sync.go)). The gateway fields and complete model list are still replaced, so removed models leave the list.
- Copilot in JetBrains IDEs keeps its Bring Your Own Key providers in the Copilot language server's `byok.json`, shared with Xcode's and Eclipse's Copilot (`copilotJetBrains` in [`copilotjetbrains.go`](../../internal/agent/copilotjetbrains.go)). magpie writes its own three keys there, `magpie-provider-config`, `magpie-api-key` and `magpie-models-config`, in the bytes the server itself writes, and only when they differ; the user's providers and keys stay. A magpie model the user hid in Manage Models (`isRegistered: false`) stays hidden through a sync. A new file is made 0600 in a 0700 folder, as the server makes it.
- dsh (DeepSeek Harness) sets one API per llm-pi-ai route, so magpie writes a route per protocol (`dshKinds` in [`dsh.go`](../../internal/agent/dsh.go); 01huadalang on Discord): `magpie` (Chat Completions) for most models, `magpie-responses` (`openai-responses`) for a model served on Responses, `magpie-anthropic` (`anthropic-messages`, the gateway root, `forceAdaptiveThinking` where `AdaptiveThinking`) for one served on Messages, by the model's `APIs` (`dshRouteOf`). A model's `APIs` is the one its provider serves it on best (`Provider.Native`, in `magpieModels`, [`route.go`](../../internal/agent/route.go)), and Pi, omp and droid read it the same way. A routing group has `responses` when every member is best on Responses (`allResponses`, #1594), so its tool-call arguments are relayed as they stream; any other group has none and stays on Chat, a Messages-only group too, as a Claude member's thinking is known by its own model. A route with no models is taken out. An api the user picked for a route in dsh's Models page is kept, and so are keys they added there. The start (`agent-default-model`) names its model's route, and Sync moves a start on one of magpie's routes to the route its model is now on (`dshStartOnItsRoute`), its effort and marks kept. Check asks the route the start names to list its model. A dsh session resumed on a model that has since moved routes asks for the model to be picked again, since dsh finds a model by route and id.
@@ -85,7 +85,7 @@ go test -tags nogui ./internal/agent -run '^TestStepCode'
go test -tags nogui ./internal/agent -run 'TestClaudeAutoModeReview|TestT3CodeAutoModeReview|TestConnect|TestDisconnect|Drift|TestKeptAddress|TestWSLAgentAddress|TestReachProbe|TestDryRunKnowsTheAskersProviders|TestReseat|TestPort|TestWSL|TestClaudeKeepsItsClaudeAISignIn|TestClaudeSignIn|TestClaudeOwnEndpointWithAnEmptyKey|TestClaudeAtAnOlderGatewayAddress'
go test -tags nogui ./internal/agent
go test -tags nogui ./internal/agent -run '^TestAir'
go test -tags nogui ./internal/agent -run 'TestReverseProxy|TestClaudeManagedProxyIsStillMagpie|TestMagpieProbe|TestCodexBehindReverseProxy|TestCodexSignedInBehindReverseProxy|TestAwayPath'
go test -tags nogui ./internal/agent -run 'TestReverseProxy|TestClaudeManagedProxyIsStillMagpie|TestMagpieProbe|TestCodexBehindReverseProxy|TestCodexSignedInBehindReverseProxy|TestAwayPath|TestClaudeBehindLocalProxyKeepsIt'
go test -tags nogui ./internal/agent ./internal/edit -run 'TestSyncKeepsAnAddressOnAnotherMachine|TestKeptAwayOnlyWhatIsSure|TestKeyValuesFormats|TestFilteredWrites'
go test -tags nogui ./internal/edit -run 'BOM|CRLF'
go test -tags nogui ./internal/agent -run '^TestAnte'
+13 -4
View File
@@ -492,7 +492,15 @@ func claudeIn(at place) *Agent {
// Claude version dashed, which it would read as Claude Opus 4
spell := provider.ClaudeSpelled
model := jsonGet(path, "model")
routed := func() bool { return env("ANTHROPIC_BASE_URL") == at.gw() }
// routed: on magpie's gateway, or on a proxy to it where magpie has
// answered (#1985), which a pick keeps (gwAt)
routed := func() bool { u := env("ANTHROPIC_BASE_URL"); return u == at.gw() || surelyMagpie(u, at.gw()) }
gwAt := func() string {
if u := env("ANTHROPIC_BASE_URL"); u != at.gw() && surelyMagpie(u, at.gw()) {
return u
}
return at.gw()
}
// the main model while routed: settings.json's model, which Claude
// Code's /model saves, so a model picked there holds for its next
// sessions too (the owner: 去掉 ANTHROPIC_MODEL,让 /model 的选择对新会话也生效)
@@ -1083,8 +1091,9 @@ func claudeIn(at place) *Agent {
return err
}
}
gw := gwAt()
kvs := []edit.KV{
{Path: "env.ANTHROPIC_BASE_URL", Value: at.gw()},
{Path: "env.ANTHROPIC_BASE_URL", Value: gw},
{Path: "env.ANTHROPIC_AUTH_TOKEN", Value: wiredKey()},
{Path: "env.ANTHROPIC_SMALL_FAST_MODEL", Value: spell(tiers["haiku"])},
{Path: "model", Value: spell(main)},
@@ -1109,7 +1118,7 @@ func claudeIn(at place) *Agent {
} else if err := edit.DelJSON(path, "env.CLAUDE_CODE_SUBAGENT_MODEL"); err != nil {
return err
}
stash(map[string]string{mainKey: main, wroteAt: at.gw()})
stash(map[string]string{mainKey: main, wroteAt: gw})
// the new model's window replaces the old one's, when magpie knows
// it; one the user set is theirs
if err := writeWindow(main, tiers); err != nil {
@@ -2016,7 +2025,7 @@ func claudeStandIn(path, model string) string { return claudeStandInAt(path, mod
// gateway at gw.
func claudeStandInAt(path, model, gw string) string {
env := func(k string) string { v, _ := edit.GetJSON(path, "env."+k); return provider.ClaudeRead(v) }
if env("ANTHROPIC_BASE_URL") != gw {
if u := env("ANTHROPIC_BASE_URL"); u != gw && !surelyMagpie(u, gw) {
return ""
}
// the model Claude Code is set to itself, by that id, is its own pick
+3 -3
View File
@@ -1593,12 +1593,12 @@ func codexGatewayURL() string { return gateway.URL() + gateway.CodexPath }
// [model_providers.magpie]'s base_url with magpie's key, that one first
// while magpie is Codex's provider), else gateway.URL(). It is http or
// https, on any port or the scheme's own, and may have a path before
// magpie's: a company's reverse proxy at https://ai.corp.example/magpie
// (#1985).
// magpie's: a company's reverse proxy at https://ai.corp.example/magpie,
// or one on this machine at http://127.0.0.1:8788/<route> (#1985).
func codexKeptGateway(path string) string {
kept := func(u, suffix string) string {
base, ok := strings.CutSuffix(strings.TrimSuffix(strings.TrimSpace(u), "/"), suffix)
if !ok || !onAnotherMachine(base) {
if !ok || !onAnotherMachine(base) && !loopbackWithPath(base) {
return ""
}
if p, err := url.Parse(base); err != nil || p.User != nil || p.RawQuery != "" || p.Fragment != "" {
+23 -6
View File
@@ -78,8 +78,11 @@ func keyValues(b []byte) []keyValue {
// to move, wslMovedFrom). Where the write brings the gateway's address in
// place of one on another machine, that one stays; where it brings magpie's
// own key in place of another, in a file that had none of magpie's keys,
// the other stays. An address on this machine's loopback (another port,
// localhost) is magpie's own and follows the gateway; with more than one
// the other stays, with the path every URL there had before magpie's (a
// reverse proxy's /magpie). An address on this machine's loopback
// (another port, localhost) is magpie's own and follows the gateway, but
// for a local proxy's route, one with a path of its own where nothing but
// magpie has answered (#1985); with more than one
// address or key gone, which went where can't be told, and the write is
// left as it is. magpie's own files are never the user's pointing.
func keptAway(path string, data []byte) []byte {
@@ -91,14 +94,17 @@ func keptAway(path string, data []byte) []byte {
if err != nil || len(was) == 0 || bytes.Contains(was, []byte(g)) {
return data
}
elsewhere := false
elsewhere, local := false, false
for _, o := range originRE.FindAll(was, -1) {
if wslHost(string(o)) {
return data
}
elsewhere = elsewhere || onAnotherMachine(string(o))
}
if !elsewhere {
for _, u := range urlRE.FindAll(was, -1) {
local = local || loopbackWithPath(string(u))
}
if !elsewhere && !local {
return data
}
out := data
@@ -112,10 +118,21 @@ func keptAway(path string, data []byte) []byte {
away = s
}
}
p := awayPath(was, data, g, away)
// on this machine, a local proxy's route (#1985): one with a path
// of its own before magpie's, where magpie answers or hasn't been
// asked yet; without one it is magpie's own on an older port
if !onAnotherMachine(away) {
return data
if !loopbackWithPath(away + p) {
return data
}
if ok, known := magpieAt(away + p); known && !ok {
return data
}
}
out = replaceOrigin(data, g, away+awayPath(was, data, g, away))
out = replaceOrigin(data, g, away+p)
} else if !elsewhere {
return data
}
// the key: the one that went with the address, in place of magpie's
+88 -12
View File
@@ -20,6 +20,10 @@ import (
// path of its own before magpie's (#1985).
const corpProxy = "https://ai.corp.example/magpie"
// localProxy is the reporter's: a company-mandated compliance proxy on this
// machine, its route before magpie's paths.
const localProxy = "http://127.0.0.1:8788/claude-code-anthropic/cc-7f3a9e"
// fakeMagpieAt answers magpieAt from answers (a base missing is no magpie),
// as the probe would have, and says which bases were asked.
func fakeMagpieAt(t *testing.T, answers map[string]bool) func() []string {
@@ -38,15 +42,25 @@ func fakeMagpieAt(t *testing.T, answers map[string]bool) func() []string {
}
// davisjiahao (#1985): every agent connected to magpie, then pointed by the
// user at a company's nginx (https://ai.corp.example/magpie) that forwards
// to the gateway, magpie's key and model kept. That is still magpie: no
// agent's Check calls it changed, and the sync every start runs keeps the
// proxy's address, its path included. The same address where something
// else answers (a relay CC Switch put there) is still told, for every
// agent but Codex, which keeps an address with magpie's key in its
// provider table as it did for #816 and tries it (unreachable).
// user at a proxy that forwards to the gateway, magpie's key and model
// kept: a company's nginx (https://ai.corp.example/magpie), or the
// reporter's own, a compliance proxy on this machine every request must go
// through (http://127.0.0.1:8788/claude-code-anthropic/<route>). That is
// still magpie: no agent's Check calls it changed, and the sync every
// start runs keeps the proxy's address, its path included. The same
// address where something else answers (a relay CC Switch put there) is
// still told, for every agent but Codex, which keeps an address with
// magpie's key in its provider table as it did for #816 and tries it
// (unreachable).
func TestReverseProxyIsStillMagpie(t *testing.T) {
// named so the test's folders, which carry the name, hold no address
t.Run("nginx", func(t *testing.T) { reverseProxyIsStillMagpie(t, corpProxy) })
t.Run("local", func(t *testing.T) { reverseProxyIsStillMagpie(t, localProxy) })
}
func reverseProxyIsStillMagpie(t *testing.T, proxy string) {
t.Setenv("MAGPIE_ADDR", "")
host := strings.SplitN(strings.SplitN(proxy, "://", 2)[1], "/", 2)[0]
home, _ := codexHome(t, "", "")
managed := claudeManaged
claudeManaged = func() string { return filepath.Join(home, "managed-settings.json") }
@@ -88,10 +102,10 @@ func TestReverseProxyIsStillMagpie(t *testing.T) {
}
for _, p := range moved {
b, _ := os.ReadFile(p)
os.WriteFile(p, []byte(strings.ReplaceAll(string(b), "http://127.0.0.1:3591", corpProxy)), 0o644)
os.WriteFile(p, []byte(strings.ReplaceAll(string(b), "http://127.0.0.1:3591", proxy)), 0o644)
}
asked := fakeMagpieAt(t, map[string]bool{corpProxy: true})
asked := fakeMagpieAt(t, map[string]bool{proxy: true})
for _, a := range agents {
if c := a.Check(); c != "" {
t.Errorf("%s behind the proxy: %s", a.ID, c)
@@ -101,7 +115,7 @@ func TestReverseProxyIsStillMagpie(t *testing.T) {
}
}
for _, b := range asked() {
if b != corpProxy {
if b != proxy {
t.Errorf("asked %s, not the proxy's own address", b)
}
}
@@ -115,7 +129,7 @@ func TestReverseProxyIsStillMagpie(t *testing.T) {
}
// the sync keeps the proxy, its /magpie too
fakeMagpieAt(t, map[string]bool{corpProxy: true})
fakeMagpieAt(t, map[string]bool{proxy: true})
if err := provider.Save(provider.Provider{ID: "fake2", Name: "Fake2", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m2"}}); err != nil {
t.Fatal(err)
}
@@ -126,7 +140,7 @@ func TestReverseProxyIsStillMagpie(t *testing.T) {
if strings.Contains(s, "127.0.0.1:3591") {
t.Errorf("%s is back on this machine's gateway", name)
}
if !strings.Contains(s, corpProxy) || strings.Count(s, "ai.corp.example") != strings.Count(s, corpProxy) {
if !strings.Contains(s, proxy) || strings.Count(s, host) != strings.Count(s, proxy) {
t.Errorf("%s lost the proxy's path:\n%s", name, s)
}
}
@@ -329,3 +343,65 @@ func TestCodexSignedInBehindReverseProxy(t *testing.T) {
t.Fatalf("behind the proxy: %s", c)
}
}
// The reporter's case (#1985, davisjiahao): Claude Code must go through a
// compliance proxy on this machine (http://127.0.0.1:8788/<route>, which
// forwards to the gateway). Once magpie has answered there, picking a
// model in magpie keeps the proxy (it wrote 127.0.0.1:3425 back, bypassing
// the proxy the company requires), as does Reconnect, which isn't offered,
// and the sync. A relay there is magpie's to point away from on a pick.
func TestClaudeBehindLocalProxyKeepsIt(t *testing.T) {
home, path := claudeSettings(t, `{}`)
saveDeepseek(t)
cl := claude(home)
if err := cl.Apply("model", "deepseek/pro"); err != nil {
t.Fatal(err)
}
edit.SetJSON(path, edit.KV{Path: "env.ANTHROPIC_BASE_URL", Value: localProxy})
fakeMagpieAt(t, map[string]bool{localProxy: true})
url := func() string { u, _ := edit.GetJSON(path, "env.ANTHROPIC_BASE_URL"); return u }
if d := cl.Drift(); d != nil {
t.Fatalf("behind the proxy: %+v", d)
}
if err := cl.Apply("model", "deepseek/flash"); err != nil {
t.Fatal(err)
}
if u := url(); u != localProxy {
t.Fatalf("a pick wrote %s", u)
}
if m := cl.Field("model").Get(); m != "deepseek/flash" {
t.Fatalf("model %q", m)
}
if d := cl.Drift(); d != nil {
t.Fatalf("after a pick: %+v", d)
}
// a tier given a model of its own keeps it on the next pick, as on
// the gateway's own address
edit.SetJSON(path, edit.KV{Path: "env." + tierEnv("haiku"), Value: "deepseek/pro"})
if err := cl.Apply("model", "deepseek/flash"); err != nil {
t.Fatal(err)
}
if v, _ := edit.GetJSON(path, "env."+tierEnv("haiku")); v != "deepseek/pro" {
t.Fatalf("haiku's own model went: %q", v)
}
if err := provider.Save(provider.Provider{ID: "fake2", Name: "Fake2", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m2"}}); err != nil {
t.Fatal(err)
}
SyncCatalog()
if u := url(); u != localProxy {
t.Fatalf("the sync wrote %s", u)
}
// a relay there, not magpie: told, and a pick puts magpie back
fakeMagpieAt(t, map[string]bool{})
if d := cl.Drift(); d == nil || d.Kind != "unwired" {
t.Fatalf("a relay: %+v", d)
}
if err := cl.Apply("model", "deepseek/pro"); err != nil {
t.Fatal(err)
}
if u := url(); u != gateway.URL() {
t.Fatalf("a pick at a relay left %s", u)
}
}
+47 -13
View File
@@ -75,32 +75,66 @@ var magpieAt = func(base string) (ok, known bool) {
return probed("magpie "+base, func() bool { return magpieProbe(base) })
}
// reachesMagpie says v, the address an agent's config names where magpie
// wrote want, still reaches magpie another way: a URL on another machine or
// a name, such as a company's reverse proxy in front of the gateway
// (davisjiahao, #1985: https://ai.corp.example/magpie forwarding to
// 127.0.0.1:3425), with want's path after it (/v1 where want has it),
// whose root answers as magpie. Until it has been tried it is taken as
// reaching magpie, as an address not yet tried isn't unreachable either:
// telling drift first would offer Reconnect, which writes the proxy away.
// One on this machine's loopback is magpie's own on an older port, never
// proxyBase is v, the address an agent's config names where magpie wrote
// want, with want's path (/v1 where want has it) cut off its end, when
// that can be another way to magpie: a URL on another machine or a name,
// such as a company's reverse proxy in front of the gateway (davisjiahao,
// #1985: https://ai.corp.example/magpie forwarding to 127.0.0.1:3425), or
// one on this machine's loopback with a path of its own before magpie's (a
// compliance proxy's http://127.0.0.1:8788/claude-code-anthropic/<route>).
// One on loopback with none is magpie's own on an older port, never
// another way to it.
func reachesMagpie(v, want string) bool {
func proxyBase(v, want string) (string, bool) {
w, err := url.Parse(want)
if err != nil || (w.Scheme != "http" && w.Scheme != "https") || w.Host == "" {
return false
return "", false
}
base, ok := strings.CutSuffix(strings.TrimSuffix(strings.TrimSpace(v), "/"), strings.TrimSuffix(w.Path, "/"))
if !ok || !onAnotherMachine(base) {
return false
if !ok || !onAnotherMachine(base) && !loopbackWithPath(base) {
return "", false
}
if u, err := url.Parse(base); err != nil || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
return "", false
}
return base, true
}
// loopbackWithPath says base is an http(s) address on this machine's
// loopback with a path: a local proxy's route, never the gateway's own
// address, which has none.
func loopbackWithPath(base string) bool {
u, err := url.Parse(base)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || onAnotherMachine(base) {
return false
}
return strings.Trim(u.Path, "/") != ""
}
// reachesMagpie says v reaches magpie another way (proxyBase) whose root
// answers as magpie. Until it has been tried it is taken as reaching
// magpie, as an address not yet tried isn't unreachable either: telling
// drift first would offer Reconnect, which writes the proxy away.
func reachesMagpie(v, want string) bool {
base, ok := proxyBase(v, want)
if !ok {
return false
}
ok, known := magpieAt(base)
return ok || !known
}
// surelyMagpie is reachesMagpie once magpie has answered there: what a
// write that keeps the address waits for, so a relay not yet tried never
// gets magpie's model or key.
func surelyMagpie(v, want string) bool {
base, ok := proxyBase(v, want)
if !ok {
return false
}
ok, known := magpieAt(base)
return ok && known
}
var reach struct {
sync.Mutex
m map[string]reachAnswer