agent: an agent behind billion-context's /bili/ lane still goes through magpie (33sczf on X)

The Library's billion-context tab puts Claude Code behind bili's lane:
ANTHROPIC_BASE_URL http://127.0.0.1:18787/bili/http://127.0.0.1:3425,
which forwards to the gateway. A local proxy with a path is checked by
asking GET / there for magpie's info (#1985), and a bili lane runs only
beside its agent, so the probe said no: the Agents page showed "配置已变更"
with Reconnect, which would have written the gateway over the user's
billion-context.

chainsToGateway (reach.go): an address on this machine's loopback whose
path ends in the gateway's own URL (/bili/<gw>, /bili/anthropic/<gw>, any
port) reaches magpie without a probe. reachesMagpie and surelyMagpie take
it, so every agent's drift check (wiringOff, Claude's managed settings,
Reasonix, T3 Code, Zed) holds, and Claude Code's writes (a pick,
Reconnect) keep ANTHROPIC_BASE_URL on the lane (gwAt/claudeProxied).
The sync's kept-away filter (keptaway.go) kept nothing for a file that
already named the gateway: chainPrefix now keeps one such proxy in front
of the gateway wherever the file had it, for every agent's sync.

Codex is left as it was: its openai_base_url check is exact, and bili's
Codex lane is an MCP server that never takes this address.

Run (mote):
- go test -run 'TestBiliChain|TestChainsToGateway|TestClaudeBehindBili' ./internal/agent: ok
- go test -run 'TestBiliChain|TestChainsToGateway|TestReverseProxy|TestClaudeManagedProxy|Kept|Away|Elsewhere|Proxy' ./internal/agent: ok
- gofmt -l clean; go vet ./internal/agent for darwin, linux (nogui) and windows
Broken by hand: chainsToGateway taken out of reachesMagpie/surelyMagpie
and chainPrefix off: TestBiliChainIsStillMagpie red with the reporter's
exact message for claude, claude-desktop, gemini, opencode and others,
53 files back on the gateway after a sync; TestClaudeBehindBiliLaneKept
red.
Not tried: a real bili lane with a real Claude Code; the full suite
(started after the tag).
This commit is contained in:
yetone
2026-11-10 22:46:21 +08:00
parent ee818e8bce
commit 40cd70d54e
4 changed files with 235 additions and 2 deletions
+1 -1
View File
@@ -43,7 +43,7 @@ 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). `reconnect` calls `Join` first too, so a Codex switched off on a routing group comes back joined, as the switch first connected it: put back on the group alone it was beside its sign-in only, and an own model picked on the Agents page took it off magpie (NancyTom18 on X, `TestCodexReconnectStaysJoined`). One that can't join then (a provider of the user's own, magpie API) is connected as at first unless its own model was one of magpie's: its memories' or subagents' model put back alone read as connected while its own model stayed off magpie (#3868, `TestCodexOffAndOnJoinsAgainWithItsHelpersOnMagpie`). 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. Each row of a model picker that a provider served with a timed reply this week says how fast: tokens a second, or the first token's wait when only that was timed (`speedTag` in app.js, from `GET /api/model-speeds`, `modelSpeeds` in [`internal/gui/speeds.go`](../../internal/gui/speeds.go): the usage ledger's mean TTFT and decode speed by `provider/model`, the catalog ref an option carries). Under a search, rows that match equally go fastest first by about how long a 200-token reply takes (`speedRank`), the untimed last, so a model several providers serve lists the fastest one first (axuhere on X). Without a search the rows keep catalog order, grouped by provider. A routing group that always asks the fastest provider is the Speed first strategy ([gateway routing](gateway-routing.md)).
3. **Notice.** After a change the page shows `Notice` when the agent reads its config only at start-up and needs a restart. A field that is `Live` (`Field.Live`: magpie's own setting, which the gateway reads on each request, Claude Desktop's `subagent_model` and `subagent_effort`) needs no restart, so `POST /api/set` and `magpie <agent> <field> <value>` leave the Notice out after it, unless the pick connected the agent too (`Pick` on an agent not connected). A stopped WSL distro's copy of a field keeps the flag (`asleep`).
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; at a relay, a pick points Claude Code at this magpie. Every write to Claude Code (a field's `Set`, `Sync`, `Unwire`) asks such an address first where magpie hasn't answered yet, and waits (`claudeAsk`, `magpieAsked`, as `codexProxyOK` does): unasked, it read as a relay, and the first write in a magpie just started (the CLI's: a pick, the `Sync` a provider added runs, Disconnect) wrote the proxy away, turned the auto mode review back on, or left magpie in and forgot the endpoint the user had. `Follow` writes nothing until the answer is in, and reads never wait. Claude Code's address is asked only while what it sends is for magpie (`claudeProxied`, `claudeKeyed`: a key the gateway takes, or none where it keeps its claude.ai sign-in through magpie): with a key of the user's own it is their endpoint, never asked, and the drift a model of magpie's name there shows says that address, or an administrator's in managed settings, as it is (`whatsOff`; zhangt2333, #3480: magpie sent `GET /` about every 30 s to the `ANTHROPIC_BASE_URL` of a Claude Code it never connected). 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. Claude Code's `LastUsed` passes over the prompts in its `history.jsonl` whose `project` is magpie's own work folder (`magpie-claude-work`, `-<uid>` off Windows; `inMagpieWork`): the bridge's runs write there too and went through magpie (ifccod7391564 on X: they warned Claude Code bypassed magpie; `TestClaudeBridgePromptsArentBypass`).
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; at a relay, a pick points Claude Code at this magpie. Every write to Claude Code (a field's `Set`, `Sync`, `Unwire`) asks such an address first where magpie hasn't answered yet, and waits (`claudeAsk`, `magpieAsked`, as `codexProxyOK` does): unasked, it read as a relay, and the first write in a magpie just started (the CLI's: a pick, the `Sync` a provider added runs, Disconnect) wrote the proxy away, turned the auto mode review back on, or left magpie in and forgot the endpoint the user had. `Follow` writes nothing until the answer is in, and reads never wait. Claude Code's address is asked only while what it sends is for magpie (`claudeProxied`, `claudeKeyed`: a key the gateway takes, or none where it keeps its claude.ai sign-in through magpie): with a key of the user's own it is their endpoint, never asked, and the drift a model of magpie's name there shows says that address, or an administrator's in managed settings, as it is (`whatsOff`; zhangt2333, #3480: magpie sent `GET /` about every 30 s to the `ANTHROPIC_BASE_URL` of a Claude Code it never connected). An address on loopback whose path ends in the gateway's own URL (billion-context's lane, `http://127.0.0.1:18787/bili/<gateway>`, which the Library's billion-context tab gives Claude Code) is magpie without asking (`chainsToGateway`): the lane runs only beside its agent, so `GET /` there found nothing, and the Agents page offered Reconnect over the user's billion-context (33sczf on X). A sync keeps such a prefix in front of the gateway (`chainPrefix` in `keptaway.go`). `TestBiliChainIsStillMagpie`, `TestClaudeBehindBiliLaneKept`. 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. Claude Code's `LastUsed` passes over the prompts in its `history.jsonl` whose `project` is magpie's own work folder (`magpie-claude-work`, `-<uid>` off Windows; `inMagpieWork`): the bridge's runs write there too and went through magpie (ifccod7391564 on X: they warned Claude Code bypassed magpie; `TestClaudeBridgePromptsArentBypass`).
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). A Codex thread keeps the provider it was started on, so one started while magpie was Codex's provider (its API, or the takeover of a used-up account) still sends to `/v1` after Disconnect or a switch back to ChatGPT. One of Codex's own models asked there that no account in magpie serves (an OpenAI model of Codex's models cache or the catalog), from Codex on this computer with no held gateway key, goes on Codex's own ChatGPT sign-in through `codexBackend`, magpie's key and `x-openai-actor-authorization` left behind (`codexOwnOffMagpie` in [`codex_own_v1.go`](../../internal/gateway/codex_own_v1.go)); it was answered 404 "magpie knows no model" (iuengei on Discord). With the sign-in out of reach (subscription accounts off, signed out, expired) the 404 says why and to start a new thread. `TestCodexOwnModelOnMagpieThreadGoesOnSignIn`, `TestCodexOwnModelOnMagpieThreadStaysHere`, `TestCodexOwnModelOnMagpieThreadSaysWhy`.
## Constraints and failure behavior
+152
View File
@@ -0,0 +1,152 @@
package agent
import (
"os"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/provider"
)
// 33sczf on X: the Library's billion-context tab put Claude Code behind
// bili's lane, ANTHROPIC_BASE_URL
// http://127.0.0.1:18787/bili/http://127.0.0.1:3425, which forwards to the
// gateway. The Agents page called it "配置已变更", and Reconnect would
// have written the gateway over the user's billion-context. The lane runs
// only beside its agent, so nothing answers GET / there as magpie: every
// agent whose address names the gateway at the end of a local proxy's
// path still reaches magpie, with no probe, and a sync keeps the chain.
func TestBiliChainIsStillMagpie(t *testing.T) {
t.Setenv("MAGPIE_ADDR", "")
home, _ := codexHome(t, "", "")
managed := claudeManaged
claudeManaged = func() string { return filepath.Join(home, "managed-settings.json") }
t.Cleanup(func() { claudeManaged = managed })
os.MkdirAll(filepath.Join(home, ".hanako", "agents", "hana"), 0o755)
os.WriteFile(filepath.Join(home, ".hanako", "agents", "hana", "config.yaml"), []byte("agent:\n name: Hana\n"), 0o644)
craftFixture(t, home)
t.Setenv("ASTRBOT_ROOT", "")
writeFile(t, filepath.Join(home, ".astrbot", "data", "cmd_config.json"), astrbotConfig)
qwenpawFixture(t, home)
setPort(t, 3592)
const gw = "http://127.0.0.1:3592"
const lane = "http://127.0.0.1:18787/bili/"
var agents []*Agent
for _, a := range All() {
if a.Check == nil || a.Launch != nil || a.WSL != "" || a.Native != nil || a.ID == "alma" || a.ID == "shelley" || a.ID == "cursorlocal" {
continue
}
var key, want string
for _, g := range a.Fields {
for _, o := range g.Options(a.Values()) {
if want == "" && (o.Ref == "fake/m1" || o.Value == magpieID) {
key, want = g.Key, o.Value
}
}
}
if want == "" {
t.Fatalf("%s: no field takes magpie's models", a.ID)
}
if err := a.Apply(key, want); err != nil {
t.Fatalf("%s: %v", a.ID, err)
}
agents = append(agents, a)
}
moved := filesWith(home, "127.0.0.1:3592")
if len(moved) < 20 {
t.Fatalf("only %d files have the gateway's address: %v", len(moved), moved)
}
for _, p := range moved {
b, _ := os.ReadFile(p)
os.WriteFile(p, []byte(strings.ReplaceAll(string(b), gw, lane+gw)), 0o644)
}
// the lane is down, or answers GET / as itself: never asked
asked := fakeMagpieAt(t, map[string]bool{})
for _, a := range agents {
if a.ID == "codex" {
// its openai_base_url is held to the gateway itself; bili's
// Codex lane is an MCP server, never this address
continue
}
if c := a.Check(); c != "" {
t.Errorf("%s behind billion-context: %s", a.ID, c)
}
if d := a.Drift(); d != nil && d.Kind == "unwired" {
t.Errorf("%s behind billion-context drifted: %+v", a.ID, d)
}
}
for _, b := range asked() {
if strings.Contains(b, "/bili/") {
t.Errorf("asked %s whether it is magpie", b)
}
}
// a sync, which a pick and Reconnect write through, keeps the chain
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()
for _, p := range moved {
b, _ := os.ReadFile(p)
s, name := string(b), strings.TrimPrefix(p, home)
if strings.Count(s, gw) != strings.Count(s, lane+gw) {
t.Errorf("%s is back on the gateway past billion-context:\n%s", name, s)
}
}
}
func TestChainsToGateway(t *testing.T) {
for v, want := range map[string]bool{
"http://127.0.0.1:18787/bili/http://127.0.0.1:3425": true,
"http://127.0.0.1:18787/bili/http://127.0.0.1:3425/": true,
"http://localhost:8787/bili/anthropic/http://127.0.0.1:3425": true,
"http://127.0.0.1:8787/bili/http://localhost:3425": true,
"http://127.0.0.1:18787/bili/http://127.0.0.1:3426": false,
"http://127.0.0.1:18787/bili/https://api.anthropic.com": false,
"http://127.0.0.1:18787/bili/http://127.0.0.1:3425/v1": false,
"https://relay.example/bili/http://127.0.0.1:3425": false,
"http://127.0.0.1:3425": false,
"http://127.0.0.1:18787/bili/http://user@127.0.0.1:3425": false,
"http://127.0.0.1:18787/bili/http://evil.example:3425": false,
} {
if got := chainsToGateway(v, "http://127.0.0.1:3425"); got != want {
t.Errorf("chainsToGateway(%s) = %v, want %v", v, got, want)
}
}
if !chainsToGateway("http://127.0.0.1:8787/bili/http://127.0.0.1:3425/v1", "http://127.0.0.1:3425/v1") {
t.Error("an OpenAI agent's /v1 through bili isn't magpie")
}
}
// The reporter's own: Claude Code behind bili's lane, which isn't running.
// No drift, and a pick (what Reconnect and the model picker write) keeps
// ANTHROPIC_BASE_URL on the lane.
func TestClaudeBehindBiliLaneKept(t *testing.T) {
home, path := claudeSettings(t, `{}`)
saveDeepseek(t)
cl := claude(home)
if err := cl.Apply("model", "deepseek/pro"); err != nil {
t.Fatal(err)
}
gw, _ := edit.GetJSON(path, "env.ANTHROPIC_BASE_URL")
lane := "http://127.0.0.1:18787/bili/" + gw
if err := edit.SetJSON(path, edit.KV{Path: "env.ANTHROPIC_BASE_URL", Value: lane}); err != nil {
t.Fatal(err)
}
fakeMagpieAt(t, map[string]bool{})
if c := cl.Check(); c != "" {
t.Fatalf("Check: %s", c)
}
if d := cl.Drift(); d != nil {
t.Fatalf("drift: %+v", d)
}
if err := cl.Apply("model", "deepseek/flash"); err != nil {
t.Fatal(err)
}
if u, _ := edit.GetJSON(path, "env.ANTHROPIC_BASE_URL"); u != lane {
t.Fatalf("a pick wrote ANTHROPIC_BASE_URL = %s over the lane %s", u, lane)
}
}
+36 -1
View File
@@ -132,7 +132,16 @@ func (k kept) away(path string, data []byte) []byte {
}
g := k.gateway
was, err := edit.Read(path)
if err != nil || len(was) == 0 || bytes.Contains(was, []byte(g)) {
if err != nil || len(was) == 0 {
return data
}
if p := chainPrefix(was, g); p != "" {
// behind a local proxy that names the gateway in its path
// (billion-context's /bili/, chainsToGateway): kept in front of it
pg := []byte(p + g)
return bytes.ReplaceAll(bytes.ReplaceAll(data, pg, []byte(g)), []byte(g), pg)
}
if bytes.Contains(was, []byte(g)) {
return data
}
elsewhere, local := false, false
@@ -207,6 +216,32 @@ func (k kept) away(path string, data []byte) []byte {
return out
}
// chainPrefix is what goes before the gateway's address g at every place
// was has it, when that is one local proxy naming g as its upstream
// (chainsToGateway: http://127.0.0.1:18787/bili/), "" otherwise: g
// somewhere on its own, or behind two different proxies.
func chainPrefix(was []byte, g string) string {
prefix := ""
n := 0
for _, u := range urlRE.FindAll(was, -1) {
s := string(u)
i := strings.Index(s, "/"+g)
if i < 0 {
continue
}
p := s[:i+1]
if !chainsToGateway(p+g, g) || prefix != "" && p != prefix {
return ""
}
prefix = p
n++
}
if prefix == "" || bytes.Count(was, []byte(g)) != bytes.Count(was, []byte(prefix+g)) || n == 0 {
return ""
}
return prefix
}
// urlRE is an http(s) URL with its path, as it is written in a file.
var urlRE = lazyre.New(`https?://[^\s"'<>,{}\[\]\\]+`)
+46
View File
@@ -116,6 +116,9 @@ func loopbackWithPath(base string) bool {
// 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 {
if chainsToGateway(v, want) {
return true
}
base, ok := proxyBase(v, want)
if !ok {
return false
@@ -128,6 +131,9 @@ func reachesMagpie(v, want string) bool {
// write that keeps the address waits for (magpieAsked), so a relay not yet
// tried never gets magpie's model or key.
func surelyMagpie(v, want string) bool {
if chainsToGateway(v, want) {
return true
}
base, ok := proxyBase(v, want)
if !ok {
return false
@@ -136,6 +142,46 @@ func surelyMagpie(v, want string) bool {
return ok && known
}
// chainsToGateway says v is a proxy on this machine's loopback that names
// want, magpie's gateway, as its upstream at the end of its path:
// billion-context's http://127.0.0.1:18787/bili/http://127.0.0.1:3425
// (its Claude Code lane, which the Library's billion-context tab installs;
// also /bili/anthropic/<upstream>, and bili start's 8787). Its requests
// reach magpie whether or not the proxy answers GET / as magpie: a bili
// lane runs only beside its agent, and magpieProbe asked it while it was
// down, so the Agents page told drift and Reconnect wrote the gateway over
// the user's billion-context (33sczf on X). No probe is needed, as the
// upstream is the gateway itself.
func chainsToGateway(v, want string) bool {
v = strings.TrimSuffix(strings.TrimSpace(v), "/")
if !loopbackWithPath(v) {
return false
}
u, err := url.Parse(v)
if err != nil || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
return false
}
rest := u.Path
i := strings.Index(rest, "/http://")
if j := strings.Index(rest, "/https://"); j >= 0 && (i < 0 || j < i) {
i = j
}
if i < 0 {
return false
}
up, err := url.Parse(rest[i+1:])
if err != nil {
return false
}
w, err := url.Parse(strings.TrimSuffix(want, "/"))
if err != nil || onAnotherMachine(want) || onAnotherMachine(rest[i+1:]) {
return false
}
return up.Scheme == w.Scheme && up.Port() == w.Port() && up.Port() != "" &&
strings.TrimSuffix(up.Path, "/") == strings.TrimSuffix(w.Path, "/") &&
up.User == nil && up.RawQuery == ""
}
// magpieAsked is magpieAt waited for, for a write: base, not asked yet, is
// asked now (probedNow, as codexProxyOK asks a proxy), so what the write
// reads after is magpie's answer there. Unasked, surelyMagpie is no, and