Files
magpie/internal/agent/reach.go
T
JoeyWu-tech 51f37638e5 agent: a write to Claude Code waits to hear whether its proxy is magpie (#1985, #3512)
davisjiahao (#1985): Claude Code pointed by hand at a proxy in front of
magpie, magpie's key kept (a company's nginx, or a compliance proxy on
this machine every request must go through), is kept there once magpie
has answered at the proxy (surelyMagpie). That answer comes from a probe
a read starts in the background and never waits for, and every write to
Claude Code reads routed() first: in a magpie just started, the CLI's,
the first write found no answer yet and took the proxy for a relay of
the user's own. surelyMagpie's comment says a write waits for the
answer; none did. Codex's account failover does (codexProxyOK).

From the CLI, with the proxy (relay.py, answering GET / as magpie's
gateway does) taking 0.3s or 1.5s to answer, as one across a VPN can;
the same on 40b5c2da and on d970371e (#3480):
  magpie claude fakeco/fake-3: ANTHROPIC_BASE_URL went from the proxy
    (http://127.0.0.1:<port>/corp-relay) to magpie's own
    127.0.0.1:<port>, and the haiku tier the user gave fakeco/fake-2
    went to fake-3
  magpie provider add …, whose sync rewrites Claude Code's lists: the
    CLAUDE_CODE_AUTO_MODE_SERVER=0 magpie wrote went
  magpie claude haiku fakeco/fake-3: "pick a model through magpie for
    Claude Code first; haiku can then have its own"
  magpie claude default (Disconnect): said "disconnected from magpie,
    back to what it had before" and left the proxy, magpie's key and
    magpie's tiers (fake-1 on all four) in, so its "opus" still named
    fakeco/fake-1 through magpie; the endpoint and key the user had
    before magpie (https://own.example/api, sk-own-user) were gone from
    the stash
With the proxy answering at once, the probe a read started came back
first, and all of these held. magpie web's start held in my runs too
(0s and 1.5s first starts, a 1.5s restart): its sync runs after the
catalog's fetch and the vendors' lists (FetchNew).

Now every write to Claude Code (each field's Set, Sync, Unwire) asks
first (claudeAsk): where claudeProxied would ask the address (proxyBase,
not the gateway's own address, claudeKeyed) and magpie hasn't answered
there yet, magpieAsked asks it now and waits (probedNow, the probe's 3s
timeout). An answer had before, at any age, is what the write goes by,
as the reads do. Follow is left as it is: it writes nothing until
routed, and runs again as the Agents page is drawn. Reads still never
wait (TestReverseProxyTriedFirst).

Before and after, for a write while ANTHROPIC_BASE_URL is such an
address and magpie hasn't answered there in this process:
  before: taken as a relay, as above
  after: the address is asked (GET /) and the write waits for the
    answer, then goes as it does with the answer in: a proxy to magpie
    kept, a relay pointed away from
Not changed: an address sent a key of the user's own is never asked
(#3480); the reads; a write once the answer is in.

Cost: the first write of a process waits for one GET / at such an
address. The read before it has usually asked already, in the
background; this doesn't wait for that probe but asks again, as
codexProxyOK does (the proxy got 2 GET / where it got 1). A proxy that
doesn't answer holds that write up to the probe's 3s.

Left as it is: what Apply and Disconnect read before the write (was,
before) still sees the address unasked. After the CLI's Disconnect
behind the proxy at 1.5s, the record for reconnecting
(claude.reconnect) kept the model alone, without the haiku tier the
user gave fakeco/fake-2 in magpie, which the same Disconnect on
magpie's own address keeps.

TestClaudeFirstWriteAsksTheProxy: an nginx and a local proxy, magpie
just started, nothing asked yet (coldMagpie): a pick, a Sync, a tier,
Disconnect. With claudeAsk asking nothing, all 8 are red, each on what
it is there for (the pick wrote http://127.0.0.1:3425 over the proxy
and haiku went to fake/m3; the sync took out the review; "pick a model
through magpie for Claude Code first"; Disconnect left the proxy with
"magpie" and magpie's haiku tier). With Unwire's ask alone taken out,
the two Disconnects are red.

Verified at 57ae956b: the runs above, after, at 0.3s and 1.5s: every
case held, and Disconnect put back https://own.example/api and
sk-own-user with nothing of magpie's left. Both hand breaks as above.
go test -race -count=3 of the proxy, Codex proxy, review and sign-in
tests: ok. The agent package with magpieProbe made to panic: no test
reached it. gofmt clean; go vet ./internal/agent/ for linux, darwin and
windows: exit 0. go test ./...: 63 packages ok, 7 red with this box's
own reds alone: the proc.Look tick tests (#3141:
TestInstalledVersion, TestCursorFolderFromTheEditorIsNotTheCLI,
TestOmpDetectedWithPiDir, TestZedAppPath), the Reasonix fixture builds
(a /tmp/.git that isn't magpie's), graftcp's
(TestCallbackGoesPastTheAgentsProxy,
TestClaudeToolCallbackOnANonLoopbackAddress,
TestGatewayHeldByAContainer, TestGatewayFixQuitsOnlyAMagpie), umask
077's (TestWriteAtomicReadOnlyHardLink, TestProgram/first) and Bun
1.3.11's (TestBunProxyLoginWithReservedCharacters, #3397).

Landed by yetone in a batch of Coffemon's patches from the issues.
What was run, go1.26.8, on origin/main cc81ad4ea, then again at
70a0c387c (gofmt, the three vets, the changed tests, umask 077):
- mote (macOS 27): gofmt -l clean; go vet, GOOS=linux go vet -tags
  nogui and GOOS=windows go vet ./...: ok. edit and testenv at umask
  077; agent, provider, library and gateway with an empty .git above
  TMPDIR; davsync, imagemcp, plugin, library, edit, testenv whole; the
  changed tests in agent, provider, gateway and gui; the timing tests
  -count=10 (gateway, davsync, imagemcp) and -count=5 (agent): all ok.
  TestCoreScriptBudget ok: core 1,536,751 of 1,537,034, app.js
  1,312,975 of 1,315,316, no budget raised.
- Red on the old code: on origin/main, TestWriteAtomicReadOnlyHardLink
  at umask 077 and two Reasonix tests under an empty .git; on Linux
  (wsl-run) TestProgram at umask 077 with the old program.go. With
  each fix's code taken back to main's, the Gemini imageConfig tests,
  TestPluginToldWhereTheAgentWorks, TestSkillRepoTraced,
  TestTaggedHooksAlone, TestMainURL/TestMainView and update-auto,
  plugin-github-hooks, plugins-more-discover, plugin-namesake were
  red. Broken by hand: claudeKeyed always true (both
  OwnEndpointNeverAsked tests red), claudeAsk a no-op
  (TestClaudeFirstWriteAsksTheProxy red), GitAt taking any .git folder
  (the three TestGitOnDisk tests red).
- GUI: 123 files (plugins*, update-*, panel/tray/start/context, i18n,
  gui-zh-tw/ja/de and every file that evals app.js parts) in WebKit on
  Linux (wsl-run). 11 files had reds (click-scroll, panel-fold,
  plugin-card-update, plugin-github, plugin-move*, segs-glide,
  tray-totals, update-*), and run again side by side they fail the
  same on origin/main d80d75f30 (79 pass, 26 fail here; 78 and 27
  there). They are click-scroll guards ("the click must not scroll
  the page"), varying by language from run to run (#4385).
  copilot-ghe's route-after-close red is #1949, seen on main 244d80e23
  too. In Chromium on mote, Chromium segfaulted partway through files
  (#4125): context-map, context-scroll-end and context-tune fail the
  same on origin/main 0911a65e7, so the batch's own files
  (plugin-namesake, update-auto, plugins-more-discover,
  plugin-github-hooks) ran in Chromium on Linux: 62 of 62.
- Full suite (go test -tags nogui -count=1 -timeout 45m ./..., mote)
  at 472a0608f (on 70a0c387c): every package ok but internal/gateway,
  whose five reds were #4362's (Antigravity turned-away and
  TestCodexSpentGrokFailingIsTold), fixed on main in d80d75f30. After
  the rebase on 244d80e23 the five pass, and gofmt, the three vets
  and the targeted runs above were run again: ok. In Linux the
  sign-in, copilot, plugin-github*, plugins-more-discover,
  plugin-namesake, plugin-gateway, update-auto, quota-refresh-order
  and i18n files ran in both engines: 475 pass, 4 fail (copilot-ghe
  #1949, plugin-github's click scroll, both red on main too).
- Rebased again on c7171a256, over its budget fix e94bf7a08: gofmt, vet of
  gui, gateway, provider and plugin, TestCoreScriptBudget (core
  1,536,265 of 1,536,586 with the batch's last commit, statusTErr and settingsErr), the Gemini,
  GitOnDisk and plugin tests, and in Linux both engines i18n-keys,
  update-mirror, plugin-namesake, plugins-more-discover,
  plugin-github-hooks and update-auto (138 of 138): ok.
Not tried: the whole GUI suite (mote's WebKit wouldn't launch and its
Chromium segfaulted, #4125); macOS WebKit; the real app's window.
2026-10-30 15:53:22 +08:00

355 lines
12 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package agent
import (
"cmp"
"encoding/json"
"net"
"net/http"
"net/url"
"os"
"runtime"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/netproxy"
"github.com/yetone/magpie/internal/wslrun"
)
// An agent pointed at magpie by an address other than this machine's
// loopback — this machine's Codex at Windows as WSL sees it or a forward of
// the user's (#816), an agent in a WSL distro under NAT — is connected by
// its config alone; whether anything answers there is another matter
// (#1013: a portproxy gone after a reboot, the Agents page still said
// connected). Drift asks: each such address is tried from here, in the
// background, and one that doesn't answer while the gateway does on
// loopback is told (Drift kind "unreachable"), with what listens there.
// reachAge is how long an answer is taken as it is: Drift is asked every
// few seconds while the window is up, a probe at most this often.
var reachAge = 20 * time.Second
// reachProbe says whether anything HTTP answers at base: any status will
// do (a gateway shared on the network answers 401 to no key), a refused or
// timed-out connection doesn't. A var for tests.
var reachProbe = realReachProbe
func realReachProbe(base string) bool {
c := &http.Client{Timeout: 2 * time.Second}
res, err := c.Get(strings.TrimSuffix(base, "/") + "/v1/models")
if err != nil {
return false
}
res.Body.Close()
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) })
}
// 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 proxyBase(v, want string) (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) && !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 (magpieAsked), 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
}
// 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
// the first write in a magpie just started, the CLI's, took a proxy to
// magpie for the user's own endpoint (#1985). One answered before, at any
// age, is what the write goes by, as the reads do.
func magpieAsked(base string) {
if _, known := magpieAt(base); !known {
probedNow("magpie "+base, func() bool { return magpieProbe(base) })
}
}
var reach struct {
sync.Mutex
m map[string]reachAnswer
}
type reachAnswer struct {
at time.Time // when the last probe finished; zero: none yet
ok, busy bool
}
// reachable is what the last probe of base said, and whether there is one
// (known); a probe older than reachAge, or none, is started in the
// background and never waited for, so Drift stays quick.
func reachable(base string) (ok, known bool) {
probe := reachProbe
return probed(base, func() bool { return probe(base) })
}
// probed is reachable for any probe, kept under key: its last answer, and
// whether there is one, with a new one started in the background when
// that is older than reachAge.
func probed(key string, probe func() bool) (ok, known bool) {
reach.Lock()
defer reach.Unlock()
if reach.m == nil {
reach.m = map[string]reachAnswer{}
}
a := reach.m[key]
if !a.busy && time.Since(a.at) > reachAge {
a.busy = true
reach.m[key] = a
go func() {
ok := probe()
reach.Lock()
reach.m[key] = reachAnswer{at: time.Now(), ok: ok}
reach.Unlock()
}()
}
return a.ok, !a.at.IsZero()
}
// probedNow is probed waited for: the last answer while it is fresh, else
// one asked now, which the next probed of key gets too.
func probedNow(key string, probe func() bool) bool {
reach.Lock()
a := reach.m[key]
reach.Unlock()
if !a.at.IsZero() && time.Since(a.at) <= reachAge {
return a.ok
}
ok := probe()
reach.Lock()
if reach.m == nil {
reach.m = map[string]reachAnswer{}
}
reach.m[key] = reachAnswer{at: time.Now(), ok: ok}
reach.Unlock()
return ok
}
// 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.Scheme != "https") || u.Hostname() == "" {
return false
}
h := u.Hostname()
if h == "localhost" || sameHost(base, gateway.URL()) {
return false
}
ip := net.ParseIP(h)
return ip == nil || !ip.IsLoopback()
}
// pointedAt is the gateway's address in the agent's config: where it is
// kept apart from gateway.URL (this machine's Codex), a WSL distro's way to
// it, else "".
func (a *Agent) pointedAt() string {
switch {
case a.reach != nil:
return a.reach()
case a.Gateway != nil:
return a.Gateway()
}
return ""
}
// unreachable is the drift of an agent pointed at an address off loopback
// that doesn't answer from here while the gateway answers on loopback; nil
// when it answers, isn't asked yet, or the gateway itself is down (then
// nothing would, and that is no fault of the address).
func (a *Agent) unreachable(on Field, now string) *Drift {
addr := a.pointedAt()
if !offLoopback(addr) {
return nil
}
// both asked at once, so one round of probes settles it
inside := a.reachFrom != nil && gateway.OnWSLNet(addr)
var ok, known bool
if inside {
ok, known = a.reachFrom(addr)
} else {
ok, known = reachable(addr)
}
up, upKnown := reachable(gateway.URL())
if ok || !known || !up || !upKnown {
return nil
}
d := &Drift{Kind: "unreachable", Field: on.Key, Now: now, Want: now, Addr: addr}
host := strings.TrimPrefix(strings.TrimPrefix(addr, "http://"), "https://")
if inside {
// magpie listens there itself (gateway/wsl.go): what keeps WSL out
// is Windows' firewall
d.Detail = a.Name + " is pointed at magpie at " + addr + ", where magpie listens for WSL, but nothing answers there from WSL " + a.WSL + ": Windows' firewall keeps WSL out. " +
"Allow magpie in when Windows asks, or, in PowerShell as administrator: " + wslFirewallCommand() + ". " +
"On Windows 11, networkingMode=mirrored under [wsl2] in %UserProfile%\\.wslconfig lets WSL reach magpie at 127.0.0.1 instead."
return d
}
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 +
": magpie itself with Settings › Network and sharing › Share on local network on (it then listens on every address, and asks other computers for a gateway key), or a forward of your own (netsh interface portproxy, which may need setting up again after Windows restarts). " +
"Once it answers here and WSL still can't connect, Windows' firewall may be keeping WSL out: allow the port " + gateway.Port() + " for the WSL network. " +
"On Windows 11, networkingMode=mirrored under [wsl2] in %UserProfile%\\.wslconfig lets WSL reach magpie at 127.0.0.1 instead."
} else {
d.Detail += "Whatever forwarded " + host + " to magpie isn't listening now; start it again, or point " + a.Name + " at " + gateway.URL() + "."
}
if to, distro := wslMovedFrom(addr); to != "" {
d.Move = to
d.Detail += " WSL " + distro + " reaches Windows at " + to + " now, not " + addr + " as before: Use " + to + " points " + a.Name + " there."
}
return d
}
// wslFirewallCommand lets magpie in from WSL's networks through Windows'
// firewall, for an administrator's PowerShell. WSL's network is a Public
// one, so a rule for Private networks only (what Windows' own prompt
// offers ticked) doesn't do.
func wslFirewallCommand() string {
exe, err := os.Executable()
if err != nil || exe == "" {
exe = "magpie.exe"
}
return "New-NetFirewallRule -DisplayName 'magpie (WSL)' -Direction Inbound -Action Allow -Profile Any -InterfaceAlias 'vEthernet (WSL*)' -Program '" + strings.ReplaceAll(exe, "'", "''") + "'"
}
// wslMovedFrom is the address a WSL distro reaches Windows at now, when
// base is on one it reached Windows at before (its networking's address
// changed since, or it is in mirrored or consomme networking now, where
// that is 127.0.0.1), and that distro's name; "" otherwise. A host no
// distro was seen at is the user's own, and is never offered to be moved.
func wslMovedFrom(base string) (to, name string) {
u, err := url.Parse(base)
if err != nil {
return "", ""
}
h, port := u.Hostname(), u.Port()
wsl.Lock()
defer wsl.Unlock()
for n, d := range wsl.seen {
if d == nil {
continue
}
loopback := wslrun.HostLoopback(d.Net)
if !loopback && (d.Gateway == "" || d.Gateway == h) {
continue
}
for _, w := range d.Was {
if w != h {
continue
}
if loopback {
return gateway.URL(), n
}
if port == "" {
port = gateway.Port()
}
return "http://" + net.JoinHostPort(d.Gateway, port), n
}
}
return "", ""
}
// proxied is the drift of an agent whose requests for the gateway go
// through a proxy that doesn't pass them on to it, while the gateway
// answers here; nil when they get there, or it isn't known yet.
func (a *Agent) proxied(on Field, now string) *Drift {
if a.viaProxy == nil {
return nil
}
// with no proxy in the way, nothing is tried; with one, both are asked
// at once, so one round of probes settles it
ok, known, proxy, from := a.viaProxy()
if proxy == "" {
return nil
}
up, upKnown := reachable(gateway.URL())
if ok || !known || !up || !upKnown {
return nil
}
base := cmp.Or(a.pointedAt(), gateway.URL())
return &Drift{Kind: "proxied", Field: on.Key, Now: now, Want: now, Addr: netproxy.Redact(proxy), Detail: codexProxiedDetail(base, proxy, from)}
}