idkatbro on X: a Codex session started while magpie was open keeps failing after magpie quits with "unexpected status 503 Service Unavailable: Unknown error, url: http://127.0.0.1:3425/backend-api/codex/responses", until magpie is opened again. Cause: Codex signed in to ChatGPT, with more of its accounts on in magpie, gets openai_base_url = the gateway's /backend-api/codex (failover). At quit EndCodexFailover takes it out of config.toml, but a thread already open, in the Codex app and its app-server above all, keeps the base URL it started with. Every turn after went to a closed port. With a system or env proxy in between, the proxy answers 503 with an empty body, which Codex shows as "Unknown error"; without one Codex says "Connection refused" and reconnects. Reproduced on mote with codex 0.162.1 and a proxy answering 503 for the closed port. Masking plays no part: it runs only in the gateway, is opt-in, and its own 503 carries a readable message. Fix: when quit really ends failover (EndCodexFailover now says so), the gateway is on loopback, and Codex processes run (provider.CodexPIDs), magpie starts a detached `magpie codex-relay` (internal/codexrelay). It waits up to 60s for the gateway's port, then passes /backend-api/codex/* on to the ChatGPT backend with the same transforms the gateway applies to Codex's own turns, signed by the caller's own Authorization; it adds no credential (gateway.CodexRelay). - Refused with a readable 400 (Codex retries a 5xx five times over): a magpie model, a turn naming one of magpie's Codex accounts, and a turn masking would have masked, which is never sent unmasked. - 403 for any Origin (null too) or a non-loopback Host, as corsGuard. - Any other path gets 503 "magpie isn't running", never readable as magpie by ServedBy. - It ends once every Codex process it was left for is gone and nothing is in flight. - The next magpie (GUI or `magpie serve`) calls codexrelay.Leave first: a POST with the token from a 0600 state file. The relay closes its listener at once, so the port is free when Leave returns, and finishes its streams (up to 30 minutes). No running turn is cut. Run (at 6df7dc287 on origin/main4d9058a98, on mote): - go vet of the six touched packages; gofmt -l clean. - go test ./internal/codexrelay and the CodexRelay, CodexFailover, CodexProxy, RelayOpenCodex and CodexPIDs tests: ok. - codexrelay tests on Windows (win-run) and Linux (wsl-run, magpie-desktop): ok. - Windows smoke of the real binary (nogui build): `codex-relay` answers / with the readable 503, stays while its watched process lives, ends after it. - Real codex 0.162.1 e2e on mote, sandbox CODEX_HOME, API-key sign-in, fake upstream: the relay waited out a port held 2s, then turn 1 completed (RELAYED-OK); a turn on openrouter/kimi-k2 showed the refusal's message; turn 2 was mid-stream when Leave ran, the port was free at once, the turn completed, and the relay ended. - GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... and a Windows build: ok. - Full suite, go test -count=1 -timeout 45m ./... on mote: every package ok but internal/gui, where 10 real-window AppKit tests (dock, panel, tray, titlebar, covered window, plugin page) are killed at their 20-80s bars. The same 10 fail the same way at origin/main4d9058a98on mote, run alone: mote's AppKit hang, #4125 (and #2645, #1936). None of them touches the quit path changed here. - Rebased on origin/main1198cff60to push. Still running there when pushed: go vet ./..., Windows and Linux vet of the touched packages, and go test of codexrelay, gateway, agent, provider and cli. A red it shows gets its own issue. Broken by hand, each red, then restored: - Leave without ln.Close(), with a 1s delay before Shutdown injected: "the port isn't free after Leave" (with ln.Close: green). - No pid watch: "relay outlived the Codex it was left for". - Leave without the token check: an empty token got 204. - No Origin/Host guard: Origin null got 200. - No masking refusal, no magpie-model refusal: 200, sent upstream. - An empty 503 at "/": TestCodexRelayIsNotMagpie red. - RelayOpenCodex starting nothing: "no relay for the open Codex". - EndCodexFailover never saying ended: TestCodexFailoverEndsWithMagpie. - CodexPIDs missing "codex": the Codex app and CLI not found. Not tried: - the real Codex desktop app, and a real ChatGPT account. With a fake ChatGPT token codex 0.162.1 stops at its own "workspace routing discovery" against chatgpt.com before sending a turn, so the ChatGPT path is covered by unit tests only; - a Codex in a WSL distro, and a connected (not failover) Codex: both left as they were; - a magpie that ends without quitting (killed, crashed): still leaves failover in place and no relay; - the relay's memory use as the full binary.
304 lines
8.0 KiB
Go
304 lines
8.0 KiB
Go
// Package codexrelay keeps the Codex threads open when magpie quits
|
|
// working until magpie is opened again or they end.
|
|
//
|
|
// Codex signed in to ChatGPT sends its turns to magpie's gateway while
|
|
// magpie fails it over (agent.EndCodexFailover). At quit magpie takes that
|
|
// base URL out of Codex's config, but a thread already open, in the Codex
|
|
// app above all, keeps the URL it started with, and every turn after went
|
|
// to a closed port: "503 Service Unavailable: Unknown error" through a
|
|
// system proxy, "Connection refused" without one, until magpie was opened
|
|
// again (idkatbro on X). So at quit, with Codex running, magpie starts a
|
|
// small process of its own (`magpie codex-relay`) that takes the port up
|
|
// once the gateway lets go of it and passes those turns on to the ChatGPT
|
|
// backend on Codex's own sign-in (gateway.CodexRelay). It ends once every
|
|
// Codex process it was started for has, and leaves when the next magpie
|
|
// starts (Leave), finishing the turns it is streaming first: no running
|
|
// turn is cut.
|
|
package codexrelay
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/subtle"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"sync/atomic"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/proc"
|
|
"github.com/yetone/magpie/internal/settings"
|
|
)
|
|
|
|
// Command is the magpie command a relay runs as.
|
|
const Command = "codex-relay"
|
|
|
|
// LeavePath is where the next magpie tells the relay to leave; with
|
|
// TokenHeader holding the token the relay wrote in its state file.
|
|
const (
|
|
LeavePath = "/.magpie-codex-relay/leave"
|
|
TokenHeader = "X-Magpie-Relay-Token"
|
|
)
|
|
|
|
// Timings, vars for tests.
|
|
var (
|
|
// bindFor is how long the relay waits for the gateway's port: the
|
|
// quitting magpie holds it until its own requests have finished.
|
|
bindFor = 60 * time.Second
|
|
// watchEvery is how often the relay looks for its Codex processes.
|
|
watchEvery = 15 * time.Second
|
|
// drainFor caps how long a leaving relay finishes its streams.
|
|
drainFor = 30 * time.Minute
|
|
// leaveWait is how long Leave waits for the relay to answer.
|
|
leaveWait = 2 * time.Second
|
|
)
|
|
|
|
// state is what a running relay says of itself, for Leave.
|
|
type state struct {
|
|
Pid int `json:"pid"`
|
|
Addr string `json:"addr"`
|
|
Token string `json:"token"`
|
|
}
|
|
|
|
func statePath() string { return filepath.Join(settings.Dir(), "codex-relay.json") }
|
|
|
|
// Start runs a relay at addr for the Codex processes pids, apart from
|
|
// this process so it outlives it.
|
|
func Start(addr string, pids []int) error {
|
|
exe, err := os.Executable()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
ids := make([]string, len(pids))
|
|
for i, p := range pids {
|
|
ids[i] = strconv.Itoa(p)
|
|
}
|
|
cmd := proc.Command(exe, Command, "--addr", addr, "--pids", strings.Join(ids, ","))
|
|
detach(cmd)
|
|
if err := cmd.Start(); err != nil {
|
|
return err
|
|
}
|
|
return cmd.Process.Release()
|
|
}
|
|
|
|
// Main is `magpie codex-relay --addr host:port --pids 1,2`, serving h.
|
|
func Main(args []string, h http.Handler) error {
|
|
var addr string
|
|
var pids []int
|
|
for i := 0; i < len(args); i++ {
|
|
switch args[i] {
|
|
case "--addr":
|
|
if i+1 < len(args) {
|
|
addr = args[i+1]
|
|
i++
|
|
}
|
|
case "--pids":
|
|
if i+1 < len(args) {
|
|
for _, s := range strings.Split(args[i+1], ",") {
|
|
if s == "" {
|
|
continue
|
|
}
|
|
n, err := strconv.Atoi(s)
|
|
if err != nil || n <= 0 {
|
|
return fmt.Errorf("codex-relay: bad pid %q", s)
|
|
}
|
|
pids = append(pids, n)
|
|
}
|
|
i++
|
|
}
|
|
default:
|
|
return fmt.Errorf("codex-relay: unknown argument %q (magpie starts this itself when it quits)", args[i])
|
|
}
|
|
}
|
|
if addr == "" || len(pids) == 0 {
|
|
return errors.New("usage: magpie codex-relay --addr host:port --pids pid,… (magpie starts this itself when it quits)")
|
|
}
|
|
sig := make(chan os.Signal, 1)
|
|
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
|
|
ctx, stop := context.WithCancel(context.Background())
|
|
go func() { <-sig; stop() }()
|
|
return Run(ctx, addr, pids, h)
|
|
}
|
|
|
|
// Run serves h at addr until ctx ends, the next magpie tells it to leave,
|
|
// or none of pids runs and nothing is in flight; then it finishes the
|
|
// requests it has, for up to drainFor.
|
|
func Run(ctx context.Context, addr string, pids []int, h http.Handler) error {
|
|
ln, err := bind(ctx, addr)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
b := make([]byte, 16)
|
|
if _, err := rand.Read(b); err != nil {
|
|
ln.Close()
|
|
return err
|
|
}
|
|
me := state{Pid: os.Getpid(), Addr: ln.Addr().String(), Token: hex.EncodeToString(b)}
|
|
if err := writeState(me); err != nil {
|
|
ln.Close()
|
|
return err
|
|
}
|
|
defer dropState(me.Token)
|
|
|
|
var inFlight atomic.Int64
|
|
left := make(chan struct{})
|
|
var leaving atomic.Bool
|
|
srv := &http.Server{ReadHeaderTimeout: 30 * time.Second}
|
|
srv.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path == LeavePath {
|
|
tok := r.Header.Get(TokenHeader)
|
|
if r.Method != http.MethodPost || r.Header.Get("Origin") != "" || subtle.ConstantTimeCompare([]byte(tok), []byte(me.Token)) != 1 {
|
|
http.Error(w, "forbidden", http.StatusForbidden)
|
|
return
|
|
}
|
|
// the port is free once this is answered: the next magpie
|
|
// binds it at once, while the streams here finish
|
|
srv.SetKeepAlivesEnabled(false)
|
|
ln.Close()
|
|
if leaving.CompareAndSwap(false, true) {
|
|
close(left)
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
return
|
|
}
|
|
inFlight.Add(1)
|
|
defer inFlight.Add(-1)
|
|
h.ServeHTTP(w, r)
|
|
})
|
|
go srv.Serve(ln)
|
|
|
|
t := time.NewTicker(watchEvery)
|
|
defer t.Stop()
|
|
wait:
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
break wait
|
|
case <-left:
|
|
break wait
|
|
case <-t.C:
|
|
if inFlight.Load() == 0 && !anyAlive(pids) {
|
|
break wait
|
|
}
|
|
}
|
|
}
|
|
drain, cancel := context.WithTimeout(context.Background(), drainFor)
|
|
defer cancel()
|
|
srv.Shutdown(drain)
|
|
return nil
|
|
}
|
|
|
|
// bind listens at addr, waiting up to bindFor for it to be let go of.
|
|
func bind(ctx context.Context, addr string) (net.Listener, error) {
|
|
end := time.Now().Add(bindFor)
|
|
for {
|
|
ln, err := net.Listen("tcp", addr)
|
|
if err == nil {
|
|
return ln, nil
|
|
}
|
|
if time.Now().After(end) {
|
|
return nil, err
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
return nil, ctx.Err()
|
|
case <-time.After(200 * time.Millisecond):
|
|
}
|
|
}
|
|
}
|
|
|
|
func anyAlive(pids []int) bool {
|
|
for _, p := range pids {
|
|
if alive(p) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// writeState writes the relay's state where only this user reads it,
|
|
// whole or not at all.
|
|
func writeState(st state) error {
|
|
b, err := json.Marshal(st)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
p := statePath()
|
|
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
|
|
return err
|
|
}
|
|
tmp, err := os.CreateTemp(filepath.Dir(p), ".codex-relay-*")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer os.Remove(tmp.Name())
|
|
if err := tmp.Chmod(0o600); err != nil && !errors.Is(err, errors.ErrUnsupported) {
|
|
tmp.Close()
|
|
return err
|
|
}
|
|
if _, err := tmp.Write(b); err != nil {
|
|
tmp.Close()
|
|
return err
|
|
}
|
|
if err := tmp.Sync(); err != nil {
|
|
tmp.Close()
|
|
return err
|
|
}
|
|
if err := tmp.Close(); err != nil {
|
|
return err
|
|
}
|
|
return os.Rename(tmp.Name(), p)
|
|
}
|
|
|
|
func readState() (state, bool) {
|
|
b, err := os.ReadFile(statePath())
|
|
if err != nil {
|
|
return state{}, false
|
|
}
|
|
var st state
|
|
if json.Unmarshal(b, &st) != nil || st.Pid <= 0 || st.Addr == "" || st.Token == "" {
|
|
return state{}, false
|
|
}
|
|
return st, true
|
|
}
|
|
|
|
// dropState removes the state file when it is still this relay's.
|
|
func dropState(token string) {
|
|
if st, ok := readState(); ok && st.Token == token {
|
|
os.Remove(statePath())
|
|
}
|
|
}
|
|
|
|
// Leave tells a relay serving at the gateway's port to let go of it,
|
|
// for the magpie starting to serve there. It returns once the relay has
|
|
// closed its listener (its streams go on finishing), or at once when
|
|
// there is none.
|
|
func Leave() {
|
|
st, ok := readState()
|
|
if !ok {
|
|
return
|
|
}
|
|
if !alive(st.Pid) {
|
|
os.Remove(statePath())
|
|
return
|
|
}
|
|
req, err := http.NewRequest(http.MethodPost, "http://"+st.Addr+LeavePath, nil)
|
|
if err != nil {
|
|
return
|
|
}
|
|
req.Header.Set(TokenHeader, st.Token)
|
|
c := &http.Client{Timeout: leaveWait, Transport: &http.Transport{Proxy: nil, DisableKeepAlives: true}}
|
|
if res, err := c.Do(req); err == nil {
|
|
res.Body.Close()
|
|
}
|
|
}
|