agent: an agent reaching magpie through a reverse proxy isn't drift, and a sync keeps the proxy's path (#1985)
davisjiahao put magpie behind a company nginx (https://ai.corp.example/magpie) and pointed their agents there with magpie's key. Every agent whose Check compares its URL exactly called that "unwired", offered Reconnect (which writes 127.0.0.1 back), and each start's sync replaced the origin but dropped the /magpie path. Decision: a URL that isn't magpie's is still magpie when it ends with magpie's path, the rest is an http/https address on another machine, and GET <rest>/ answers as the gateway's GET / ({"name":"magpie"}). Something else there (a relay CC Switch wrote) stays drift. Loopback on another port is magpie on an older port: drift, never probed. An unknown answer is not drift (as unreachable/proxied), so Reconnect isn't offered before the probe has answered. - reach.go: magpieAt / realMagpieProbe / reachesMagpie, probed in the background through the existing cache; answersAsMagpie shared with codex_proxy.go's realProxyProbe. offLoopback takes https too. - applied.go: wiringOff (the choke point for ~40 agents) accepts it; Codex's "bypassed" isn't told for a request to the host the config keeps magpie at, or one the gateway saw from it after. - claude.go (managed settings) and reasonix.go: their own exact checks. - codex.go: codexKeptGateway keeps https, default ports and a path prefix (#816's kept address, trusted by magpie's key); viaBase matches the kept codexURL, since at.host() falls back to loopback for https. - keptaway.go: awayPath keeps the path every URL at the away address had. - Port moves need nothing: Rewire/OnGateway re-set only unwired agents. - Picking a model in magpie still points the agent at this magpie (documented, unchanged). Run (sandbox HOME, worktree): - go test -tags nogui ./internal/agent: ok (297s) rebased on12ecb6d8e. Before the rebase only TestFolderVarsAreListed failed, fixed on main byc6de0d2a5. - New proxy_kept_test.go: every agent behind the proxy has no Check/ unwired drift, at a relay all but Codex are told, SyncCatalog keeps https://ai.corp.example/magpie with its path in every file; Claude managed settings; unknown-then-not-magpie; loopback not probed; the real probe against httptest serving the gateway's handler under /magpie/; Codex https kept address, Reached and lastSeen; signed-in Codex via openai_base_url; awayPath table. - Broke each fix by hand, each went red: wiringOff (claude, claude-desktop, gemini, opencode... told), claude managed, reasonix, awayPath (every synced file lost /magpie), bypassed host and lastSeen, unknown-as-drift, codexKeptGateway http-only/no-path, viaBase. - gofmt -l; go vet darwin, GOOS=linux -tags nogui, GOOS=windows. Not tried: a real nginx (Host rewriting, auth in front of GET /), the Windows box, a real CC Switch. No GUI change.
This commit is contained in:
@@ -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. 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.
|
||||
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.
|
||||
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()`, 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`), 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`).
|
||||
- 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,6 +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 ./internal/edit -run 'TestSyncKeepsAnAddressOnAnotherMachine|TestKeptAwayOnlyWhatIsSure|TestKeyValuesFormats|TestFilteredWrites'
|
||||
go test -tags nogui ./internal/edit -run 'BOM|CRLF'
|
||||
go test -tags nogui ./internal/agent -run '^TestAnte'
|
||||
|
||||
@@ -202,7 +202,10 @@ func (a *Agent) Drift() *Drift {
|
||||
if a.Reached != nil && onMagpie {
|
||||
if at, to, refused := a.Reached(rec.At); !at.IsZero() {
|
||||
switch {
|
||||
case !sameHost(to, gateway.URL()):
|
||||
// a request the gateway saw since, or one to where the config
|
||||
// keeps magpie (Codex's kept address, a reverse proxy, #1985),
|
||||
// came through
|
||||
case !sameHost(to, gateway.URL()) && !sameHost(to, a.pointedAt()) && lastSeen(a.ID).Before(at.Add(-2*time.Second)):
|
||||
return &Drift{Kind: "bypassed", Field: on.Key, Now: vals[on.Key], Want: vals[on.Key],
|
||||
Detail: a.Name + "'s last request (" + at.Format("15:04") + ") went to " + hostOf(to) + ", not magpie — it was started before magpie set it up and still runs on its old config: quit and reopen it"}
|
||||
case refused:
|
||||
@@ -839,12 +842,14 @@ func sameHost(a, b string) bool { return hostOf(a) == hostOf(b) }
|
||||
|
||||
// wiringOff checks what magpie wrote into an agent's config to reach the
|
||||
// gateway — pairs of key and value, read with get — and says which no longer
|
||||
// holds, "" when all do. A URL is quoted; a key's value never is.
|
||||
// holds, "" when all do. A URL is quoted; a key's value never is. A URL
|
||||
// that reaches magpie another way (reachesMagpie: a reverse proxy, #1985)
|
||||
// holds.
|
||||
func wiringOff(name, file string, get func(string) (string, bool), kvs ...string) string {
|
||||
for i := 0; i+1 < len(kvs); i += 2 {
|
||||
k, want := kvs[i], kvs[i+1]
|
||||
v, _ := get(k)
|
||||
if v == want {
|
||||
if v == want || v != "" && reachesMagpie(v, want) {
|
||||
continue
|
||||
}
|
||||
where := name + "'s " + k + " (" + filepath.Base(file) + ")"
|
||||
|
||||
@@ -1585,7 +1585,7 @@ func claudeIn(at place) *Agent {
|
||||
if at.sys != nil {
|
||||
managed = at.sys("/etc/claude-code/managed-settings.json")
|
||||
}
|
||||
if u, _ := edit.GetJSON(managed, "env.ANTHROPIC_BASE_URL"); u != "" && u != at.gw() {
|
||||
if u, _ := edit.GetJSON(managed, "env.ANTHROPIC_BASE_URL"); u != "" && u != at.gw() && !reachesMagpie(u, at.gw()) {
|
||||
return "Claude Code's managed settings (" + at.native(managed) + ") set ANTHROPIC_BASE_URL to " + u + ", which wins over magpie's"
|
||||
}
|
||||
getEnv := func(k string) (string, bool) { return edit.GetJSON(path, "env."+k) }
|
||||
|
||||
+13
-10
@@ -5,7 +5,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
@@ -261,7 +261,10 @@ func codexIn(at place) *Agent {
|
||||
}
|
||||
}
|
||||
asProvider := func() bool { return get("model_provider") == magpieID }
|
||||
viaBase := func() bool { return isCodexGatewayOn(get("openai_base_url"), at.host()) }
|
||||
viaBase := func() bool {
|
||||
u := get("openai_base_url")
|
||||
return isCodexGatewayOn(u, at.host()) || strings.TrimSuffix(u, "/") == at.codexURL()
|
||||
}
|
||||
routed := func() bool { return asProvider() || viaBase() }
|
||||
// joined: connected by Join, on a model of Codex's own (its last pick)
|
||||
// with magpie's beside it, by the base URL
|
||||
@@ -1588,20 +1591,20 @@ func codexGatewayURL() string { return gateway.URL() + gateway.CodexPath }
|
||||
// address its config names when that is magpie's gateway on a host other
|
||||
// than this one's loopback (openai_base_url at the Codex path, or
|
||||
// [model_providers.magpie]'s base_url with magpie's key, that one first
|
||||
// while magpie is Codex's provider), else gateway.URL().
|
||||
// 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).
|
||||
func codexKeptGateway(path string) string {
|
||||
kept := func(u, suffix string) string {
|
||||
u = strings.TrimSuffix(strings.TrimSpace(u), "/")
|
||||
rest, ok := strings.CutPrefix(u, "http://")
|
||||
if !ok || !strings.HasSuffix(rest, suffix) {
|
||||
base, ok := strings.CutSuffix(strings.TrimSuffix(strings.TrimSpace(u), "/"), suffix)
|
||||
if !ok || !onAnotherMachine(base) {
|
||||
return ""
|
||||
}
|
||||
hp := strings.TrimSuffix(rest, suffix)
|
||||
h, _, err := net.SplitHostPort(hp)
|
||||
if err != nil || h == "" || h == "127.0.0.1" || h == "localhost" || h == "::1" {
|
||||
if p, err := url.Parse(base); err != nil || p.User != nil || p.RawQuery != "" || p.Fragment != "" {
|
||||
return ""
|
||||
}
|
||||
return "http://" + hp
|
||||
return base
|
||||
}
|
||||
base, _ := edit.GetTOMLTop(path, "openai_base_url")
|
||||
var table string
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -228,11 +227,7 @@ func realProxyProbe(base, proxy string) bool {
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
defer res.Body.Close()
|
||||
var info struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
return res.StatusCode == http.StatusOK && json.NewDecoder(res.Body).Decode(&info) == nil && info.Name == "magpie"
|
||||
return answersAsMagpie(res)
|
||||
}
|
||||
|
||||
// codexThroughProxy says whether Codex, configured by cfg, gets to the
|
||||
|
||||
@@ -115,7 +115,7 @@ func keptAway(path string, data []byte) []byte {
|
||||
if !onAnotherMachine(away) {
|
||||
return data
|
||||
}
|
||||
out = replaceOrigin(data, g, away)
|
||||
out = replaceOrigin(data, g, away+awayPath(was, data, g, away))
|
||||
}
|
||||
|
||||
// the key: the one that went with the address, in place of magpie's
|
||||
@@ -149,6 +149,46 @@ func keptAway(path string, data []byte) []byte {
|
||||
return out
|
||||
}
|
||||
|
||||
// urlRE is an http(s) URL with its path, as it is written in a file.
|
||||
var urlRE = regexp.MustCompile(`https?://[^\s"'<>,{}\[\]\\]+`)
|
||||
|
||||
// awayPath is the path before magpie's own that the address away keeps in
|
||||
// was, the file before a sync wrote data with the gateway's address g: the
|
||||
// /magpie of https://ai.corp.example/magpie/v1, a reverse proxy's (#1985),
|
||||
// where data has g/v1. It is the shortest that every one of was's URLs at
|
||||
// away starts with; "" when one is at away itself, or none fits.
|
||||
func awayPath(was, data []byte, g, away string) string {
|
||||
var tails []string
|
||||
for _, d := range urlRE.FindAll(data, -1) {
|
||||
if t, ok := strings.CutPrefix(strings.TrimSuffix(string(d), "/"), g); ok {
|
||||
tails = append(tails, t)
|
||||
}
|
||||
}
|
||||
var ws []string
|
||||
for _, w := range urlRE.FindAll(was, -1) {
|
||||
if s := strings.TrimSuffix(string(w), "/"); s == away || strings.HasPrefix(s, away+"/") {
|
||||
ws = append(ws, s)
|
||||
}
|
||||
}
|
||||
best, found := "", false
|
||||
for _, w := range ws {
|
||||
for _, t := range tails {
|
||||
p, ok := strings.CutSuffix(strings.TrimPrefix(w, away), t)
|
||||
if !ok || found && len(p) >= len(best) {
|
||||
continue
|
||||
}
|
||||
all := true
|
||||
for _, o := range ws {
|
||||
all = all && (o == away+p || strings.HasPrefix(o, away+p+"/"))
|
||||
}
|
||||
if all {
|
||||
best, found = p, true
|
||||
}
|
||||
}
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
// keyCounts are the values of the keys keyName takes in b, "Bearer " left
|
||||
// out, and how many times each is there.
|
||||
func keyCounts(b []byte) map[string]int {
|
||||
|
||||
@@ -50,5 +50,9 @@ func TestMain(m *testing.M) {
|
||||
codexProxyEnv = func(string) string { return "" }
|
||||
codexSystemProxy = func() netproxy.Proxy { return netproxy.Proxy{} }
|
||||
proxyProbe = func(string, string) bool { return true }
|
||||
// nor an address of the agent's own asked whether magpie answers
|
||||
// there (a reverse proxy, #1985): known, and not magpie, as for a
|
||||
// relay; the proxy-kept tests answer it
|
||||
magpieAt = func(string) (bool, bool) { return false, true }
|
||||
os.Exit(testenv.Run(m))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/edit"
|
||||
"github.com/yetone/magpie/internal/gateway"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// corpProxy is a company's reverse proxy in front of the gateway, with a
|
||||
// path of its own before magpie's (#1985).
|
||||
const corpProxy = "https://ai.corp.example/magpie"
|
||||
|
||||
// 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 {
|
||||
t.Helper()
|
||||
var mu sync.Mutex
|
||||
var asked []string
|
||||
was := magpieAt
|
||||
magpieAt = func(base string) (bool, bool) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
asked = append(asked, base)
|
||||
return answers[base], true
|
||||
}
|
||||
t.Cleanup(func() { magpieAt = was })
|
||||
return func() []string { mu.Lock(); defer mu.Unlock(); return append([]string(nil), asked...) }
|
||||
}
|
||||
|
||||
// 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).
|
||||
func TestReverseProxyIsStillMagpie(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)
|
||||
t.Setenv("ASTRBOT_ROOT", "")
|
||||
writeFile(t, filepath.Join(home, ".astrbot", "data", "cmd_config.json"), astrbotConfig)
|
||||
setPort(t, 3591)
|
||||
var agents []*Agent
|
||||
for _, a := range All() {
|
||||
// Alma is told through its running app, and Cursor's local
|
||||
// gateway is started by launchctl: neither is in the sandbox
|
||||
if a.Check == nil || a.Launch != nil || a.WSL != "" || a.Native != nil || a.ID == "alma" || 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)
|
||||
}
|
||||
if c := a.Check(); c != "" {
|
||||
t.Fatalf("%s connected, yet: %s", a.ID, c)
|
||||
}
|
||||
agents = append(agents, a)
|
||||
}
|
||||
moved := filesWith(home, "127.0.0.1:3591")
|
||||
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), "http://127.0.0.1:3591", corpProxy)), 0o644)
|
||||
}
|
||||
|
||||
asked := fakeMagpieAt(t, map[string]bool{corpProxy: true})
|
||||
for _, a := range agents {
|
||||
if c := a.Check(); c != "" {
|
||||
t.Errorf("%s behind the proxy: %s", a.ID, c)
|
||||
}
|
||||
if d := a.Drift(); d != nil && d.Kind == "unwired" {
|
||||
t.Errorf("%s behind the proxy drifted: %+v", a.ID, d)
|
||||
}
|
||||
}
|
||||
for _, b := range asked() {
|
||||
if b != corpProxy {
|
||||
t.Errorf("asked %s, not the proxy's own address", b)
|
||||
}
|
||||
}
|
||||
|
||||
// a relay at that address, not magpie: told
|
||||
fakeMagpieAt(t, map[string]bool{})
|
||||
for _, a := range agents {
|
||||
if c := a.Check(); (c == "") != (a.ID == "codex") {
|
||||
t.Errorf("%s at a relay: %q", a.ID, c)
|
||||
}
|
||||
}
|
||||
|
||||
// the sync keeps the proxy, its /magpie too
|
||||
fakeMagpieAt(t, map[string]bool{corpProxy: 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)
|
||||
}
|
||||
SyncCatalog()
|
||||
for _, p := range moved {
|
||||
b, _ := os.ReadFile(p)
|
||||
s, name := string(b), strings.TrimPrefix(p, home)
|
||||
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) {
|
||||
t.Errorf("%s lost the proxy's path:\n%s", name, s)
|
||||
}
|
||||
}
|
||||
for _, a := range agents {
|
||||
if c := a.Check(); c != "" {
|
||||
t.Errorf("%s after a sync: %s", a.ID, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Claude Code's managed settings pointing it at the company's proxy to
|
||||
// magpie win over the user's, and still reach magpie: not drift.
|
||||
func TestClaudeManagedProxyIsStillMagpie(t *testing.T) {
|
||||
home, _ := codexHome(t, "", "")
|
||||
managed := claudeManaged
|
||||
claudeManaged = func() string { return filepath.Join(home, "managed-settings.json") }
|
||||
t.Cleanup(func() { claudeManaged = managed })
|
||||
cl := claude(home)
|
||||
if err := cl.Apply("model", "fake/m1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
os.WriteFile(claudeManaged(), []byte(`{"env":{"ANTHROPIC_BASE_URL":"`+corpProxy+`"}}`), 0o644)
|
||||
fakeMagpieAt(t, map[string]bool{corpProxy: true})
|
||||
if d := cl.Drift(); d != nil {
|
||||
t.Fatalf("managed proxy to magpie: %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
// Where it reaches magpie isn't known until the address has been tried,
|
||||
// in the background: until then it isn't told as changed (Reconnect would
|
||||
// write the proxy away), once tried and not magpie it is; an address on
|
||||
// this machine's loopback is magpie's own on an older port, told at once,
|
||||
// never tried.
|
||||
func TestReverseProxyTriedFirst(t *testing.T) {
|
||||
home, path := claudeSettings(t, `{}`)
|
||||
saveDeepseek(t)
|
||||
cl := claude(home)
|
||||
if err := cl.Apply("model", "deepseek/pro"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
was, wasAt, age := magpieProbe, magpieAt, reachAge
|
||||
release := make(chan struct{})
|
||||
var mu sync.Mutex
|
||||
var tried []string
|
||||
magpieProbe = func(base string) bool {
|
||||
<-release
|
||||
mu.Lock()
|
||||
tried = append(tried, base)
|
||||
mu.Unlock()
|
||||
return false
|
||||
}
|
||||
magpieAt = func(base string) (bool, bool) {
|
||||
return probed("magpie "+base, func() bool { return magpieProbe(base) })
|
||||
}
|
||||
reachAge = time.Hour
|
||||
reachForget()
|
||||
t.Cleanup(func() { magpieProbe, magpieAt, reachAge = was, wasAt, age; reachForget() })
|
||||
|
||||
edit.SetJSON(path, edit.KV{Path: "env.ANTHROPIC_BASE_URL", Value: corpProxy + "/"})
|
||||
if d := cl.Drift(); d != nil {
|
||||
t.Fatalf("told before the proxy was tried: %+v", d)
|
||||
}
|
||||
close(release)
|
||||
if d := driftSettled(t, cl); d == nil || d.Kind != "unwired" || !strings.Contains(d.Detail, corpProxy) {
|
||||
t.Fatalf("not magpie there, yet %+v", d)
|
||||
}
|
||||
if len(tried) != 1 || tried[0] != corpProxy {
|
||||
t.Fatalf("tried %v", tried)
|
||||
}
|
||||
|
||||
edit.SetJSON(path, edit.KV{Path: "env.ANTHROPIC_BASE_URL", Value: "http://127.0.0.1:1"})
|
||||
if d := cl.Drift(); d == nil || d.Kind != "unwired" {
|
||||
t.Fatalf("an older port on loopback: %+v", d)
|
||||
}
|
||||
if len(tried) != 1 {
|
||||
t.Fatalf("loopback tried: %v", tried)
|
||||
}
|
||||
}
|
||||
|
||||
// The probe takes magpie's own answer at the proxy's path (the gateway's
|
||||
// GET /, forwarded), and nothing else: a relay's, an error page, magpie's
|
||||
// name in a page that isn't 200.
|
||||
func TestMagpieProbe(t *testing.T) {
|
||||
gw := gateway.New().Handler()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case strings.HasPrefix(r.URL.Path, "/magpie/"):
|
||||
r.URL.Path = strings.TrimPrefix(r.URL.Path, "/magpie")
|
||||
gw.ServeHTTP(w, r)
|
||||
case r.URL.Path == "/broken/":
|
||||
w.WriteHeader(502)
|
||||
w.Write([]byte(`{"name":"magpie"}`))
|
||||
default:
|
||||
w.WriteHeader(404)
|
||||
w.Write([]byte(`{"error":{"message":"not found"}}`))
|
||||
}
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
for base, want := range map[string]bool{
|
||||
srv.URL + "/magpie": true,
|
||||
srv.URL + "/magpie/": true,
|
||||
srv.URL + "/relay": false,
|
||||
srv.URL + "/broken": false,
|
||||
"http://127.0.0.1:1": false,
|
||||
} {
|
||||
if got := realMagpieProbe(base); got != want {
|
||||
t.Errorf("%s: %v, want %v", base, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Codex at the proxy (https, no port, a path of its own): kept as its
|
||||
// gateway as #816's address on another host is, written again there, and
|
||||
// a request its log says went there reached magpie (bypassed was told
|
||||
// from the host alone); one to chatgpt.com still didn't.
|
||||
func TestCodexBehindReverseProxy(t *testing.T) {
|
||||
home, _ := codexAt(t, corpProxy)
|
||||
cx := codex(home)
|
||||
cfg := filepath.Join(home, ".codex", "config.toml")
|
||||
if g := codexKeptGateway(cfg); g != corpProxy {
|
||||
t.Fatalf("kept %q", g)
|
||||
}
|
||||
if err := cx.Apply("model", "fake/m1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if u, _ := edit.GetTOMLTop(cfg, "openai_base_url"); u != corpProxy+gateway.CodexPath {
|
||||
t.Fatalf("written back to %s", u)
|
||||
}
|
||||
db, err := sql.Open("sqlite", filepath.Join(home, ".codex", "logs_2.sqlite"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if _, err := db.Exec(`CREATE TABLE logs (id INTEGER PRIMARY KEY AUTOINCREMENT, ts INTEGER NOT NULL, ts_nanos INTEGER NOT NULL,
|
||||
level TEXT NOT NULL, target TEXT NOT NULL, feedback_log_body TEXT)`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
at := time.Now().Add(2 * time.Second).Unix()
|
||||
log := func(body string) {
|
||||
at++
|
||||
db.Exec(`INSERT INTO logs (ts, ts_nanos, level, target, feedback_log_body) VALUES (?, 0, 'INFO', 'codex_api::endpoint::responses_websocket', ?)`,
|
||||
at, "responses_websocket.connect{}: "+body)
|
||||
}
|
||||
log("connecting to websocket: wss://ai.corp.example/magpie/backend-api/codex/responses")
|
||||
if d := codex(home).Drift(); d != nil {
|
||||
t.Fatalf("reached magpie through the proxy: %+v", d)
|
||||
}
|
||||
log("connecting to websocket: wss://chatgpt.com/backend-api/codex/responses")
|
||||
if d := codex(home).Drift(); d == nil || d.Kind != "bypassed" {
|
||||
t.Fatalf("to chatgpt.com: %+v", d)
|
||||
}
|
||||
// one the gateway saw after it: not bypassed, wherever the log says
|
||||
seen := lastSeen
|
||||
lastSeen = func(string) time.Time { return time.Unix(at, 0) }
|
||||
t.Cleanup(func() { lastSeen = seen })
|
||||
if d := codex(home).Drift(); d != nil {
|
||||
t.Fatalf("the gateway saw it: %+v", d)
|
||||
}
|
||||
}
|
||||
|
||||
// The sync keeps a path before magpie's only where every URL at the
|
||||
// address has it.
|
||||
func TestAwayPath(t *testing.T) {
|
||||
g := "http://127.0.0.1:3591"
|
||||
for _, c := range []struct{ was, data, want string }{
|
||||
{`{"u":"https://x.example/magpie"}`, `{"u":"` + g + `"}`, "/magpie"},
|
||||
{`{"u":"https://x.example/magpie/v1"}`, `{"u":"` + g + `/v1"}`, "/magpie"},
|
||||
{`{"u":"https://x.example/magpie","v":"https://x.example/magpie/v1"}`, `{"u":"` + g + `","v":"` + g + `/v1"}`, "/magpie"},
|
||||
{`{"u":"https://x.example","v":"https://x.example/v1"}`, `{"u":"` + g + `","v":"` + g + `/v1"}`, ""},
|
||||
{`{"u":"https://x.example/v1"}`, `{"u":"` + g + `/v1"}`, ""},
|
||||
{`{"u":"https://x.example/a/v1","v":"https://x.example/b/v1"}`, `{"u":"` + g + `/v1","v":"` + g + `/v1"}`, ""},
|
||||
} {
|
||||
if got := awayPath([]byte(c.was), []byte(c.data), g, "https://x.example"); got != c.want {
|
||||
t.Errorf("%s: %q, want %q", c.was, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Codex signed in to ChatGPT reaches magpie by openai_base_url alone,
|
||||
// magpie not its provider: at the proxy that is still magpie, though the
|
||||
// address's host isn't the one isCodexGatewayOn is asked about.
|
||||
func TestCodexSignedInBehindReverseProxy(t *testing.T) {
|
||||
home, _ := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, "")
|
||||
cx := codex(home)
|
||||
if err := cx.Apply("model", "fake/m1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p, _ := edit.GetTOMLTop(cx.Path, "model_provider"); p == magpieID {
|
||||
t.Fatal("signed in, yet magpie is Codex's provider")
|
||||
}
|
||||
b, _ := os.ReadFile(cx.Path)
|
||||
if !strings.Contains(string(b), gateway.URL()) {
|
||||
t.Fatalf("no gateway address:\n%s", b)
|
||||
}
|
||||
os.WriteFile(cx.Path, []byte(strings.ReplaceAll(string(b), gateway.URL(), corpProxy)), 0o644)
|
||||
if u, _ := edit.GetTOMLTop(cx.Path, "openai_base_url"); u != corpProxy+gateway.CodexPath {
|
||||
t.Fatalf("openai_base_url %q", u)
|
||||
}
|
||||
if c := codex(home).Check(); c != "" {
|
||||
t.Fatalf("behind the proxy: %s", c)
|
||||
}
|
||||
}
|
||||
+61
-3
@@ -2,6 +2,7 @@ package agent
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -43,6 +44,63 @@ func realReachProbe(base string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// magpieProbe says whether base answers as a magpie gateway: GET base/ is
|
||||
// 200 with {"name":"magpie"} (the gateway's info), as it is through a
|
||||
// reverse proxy that forwards base to it. A var for tests.
|
||||
var magpieProbe = realMagpieProbe
|
||||
|
||||
func realMagpieProbe(base string) bool {
|
||||
c := &http.Client{Timeout: 3 * time.Second}
|
||||
res, err := c.Get(strings.TrimSuffix(base, "/") + "/")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return answersAsMagpie(res)
|
||||
}
|
||||
|
||||
// answersAsMagpie: res, closed here, is the gateway's info (GET /).
|
||||
func answersAsMagpie(res *http.Response) bool {
|
||||
defer res.Body.Close()
|
||||
var info struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
return res.StatusCode == http.StatusOK && json.NewDecoder(res.Body).Decode(&info) == nil && info.Name == "magpie"
|
||||
}
|
||||
|
||||
// magpieAt is whether base answers as magpie (magpieProbe), and whether
|
||||
// that is known yet: the last probe's answer, a new one started in the
|
||||
// background as reachable does, never waited for. A var for tests, which
|
||||
// are told no without a probe.
|
||||
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
|
||||
// another way to it.
|
||||
func reachesMagpie(v, want string) bool {
|
||||
w, err := url.Parse(want)
|
||||
if err != nil || (w.Scheme != "http" && w.Scheme != "https") || w.Host == "" {
|
||||
return false
|
||||
}
|
||||
base, ok := strings.CutSuffix(strings.TrimSuffix(strings.TrimSpace(v), "/"), strings.TrimSuffix(w.Path, "/"))
|
||||
if !ok || !onAnotherMachine(base) {
|
||||
return false
|
||||
}
|
||||
if u, err := url.Parse(base); err != nil || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
|
||||
return false
|
||||
}
|
||||
ok, known := magpieAt(base)
|
||||
return ok || !known
|
||||
}
|
||||
|
||||
var reach struct {
|
||||
sync.Mutex
|
||||
m map[string]reachAnswer
|
||||
@@ -103,11 +161,11 @@ func probedNow(key string, probe func() bool) bool {
|
||||
return ok
|
||||
}
|
||||
|
||||
// offLoopback: base is an http address on a host other than this
|
||||
// offLoopback: base is an http(s) address on a host other than this
|
||||
// machine's loopback and the gateway's own.
|
||||
func offLoopback(base string) bool {
|
||||
u, err := url.Parse(base)
|
||||
if err != nil || u.Scheme != "http" || u.Hostname() == "" {
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" {
|
||||
return false
|
||||
}
|
||||
h := u.Hostname()
|
||||
@@ -147,7 +205,7 @@ func (a *Agent) unreachable(on Field, now string) *Drift {
|
||||
return nil
|
||||
}
|
||||
d := &Drift{Kind: "unreachable", Field: on.Key, Now: now, Want: now, Addr: addr}
|
||||
host := strings.TrimPrefix(addr, "http://")
|
||||
host := strings.TrimPrefix(strings.TrimPrefix(addr, "http://"), "https://")
|
||||
d.Detail = a.Name + " is pointed at magpie at " + addr + ", where nothing answers from this computer, though magpie answers at " + gateway.URL() + ". "
|
||||
if a.WSL != "" || runtime.GOOS == "windows" {
|
||||
d.Detail += "Under WSL's NAT networking, Windows as WSL sees it reaches magpie only while something listens on " + host +
|
||||
|
||||
@@ -328,7 +328,7 @@ func reasonixIn(at place) *Agent {
|
||||
if err := checkOwner(cfg, state); err != nil {
|
||||
return err.Error()
|
||||
}
|
||||
if p.Kind != "openai" || p.BaseURL != at.v1() {
|
||||
if p.Kind != "openai" || p.BaseURL != at.v1() && !reachesMagpie(p.BaseURL, at.v1()) {
|
||||
return "Reasonix's magpie base_url or kind changed"
|
||||
}
|
||||
if token, _ := edit.GetEnvFile(env, reasonixKey); token != gwKey() {
|
||||
|
||||
Reference in New Issue
Block a user