When magpie answers Codex's compaction itself (a magpie model, Codex's
own models through magpie's accounts, a CC Switch table), the item it
returns carries encrypted_content "magpie1:"+base64(summary). Codex keeps
it in the rollout (a response_item, and the compacted checkpoint's
replacement_history) and replays it with every later turn. Sent to the
ChatGPT backend directly, it is refused: "The encrypted content for item
cmp_magpie_1 could not be verified ... invalid_encrypted_content"
(probed with a real request on gpt-5.6-luna; the same summary as a user
message was answered).
Codex's remote compaction v2 keeps exactly one Compaction item, so magpie
can't answer with a plain message instead. sessions.PortCodexRollouts
writes each of magpie's items in a rollout as the message it stands for
(codexsummary.Message: Codex's summary prefix, a newline and the summary,
as a user message), which is what Codex's own local compaction stores and
what the gateway already sends in its place, so it reads the same through
magpie and goes on without it.
- Only magpie's compaction items change; other lines keep their bytes,
the file its line count, mode and time. An unreadable one is left out
of a list with its replacement_history_metadata entry, as Codex's own
ghost-snapshot strip does.
- Published as Codex publishes a compressed rollout: temp file and
rename, under thread-writer-locks/.coordination.lock and only with the
thread's lock free. A thread a Codex has open is left for a later pass.
A Codex home without thread-writer-locks is left alone.
- .jsonl.zst rollouts are read and written packed.
- Passes: 2 minutes after the GUI or magpie serve starts and every 10
minutes; on Codex Disconnect (3s); as the GUI quits (3s). The first
pass reads rollouts written since 2026-09-24; later ones only what
changed since the last whole pass, plus what was left held
(codex-portable.json in magpie's folder).
Run at this series' head (on origin/main 0fe039f14):
- Real codex 0.162.1, sandbox HOME/CODEX_HOME, exec </dev/null, against a
fake upstream. In magpie mode it auto-compacted and the rollout's
compacted line held magpie1:. In OpenAI mode, `exec resume --last`
failed with "Error running remote compact task: ...
invalid_encrypted_content". After PortCodexRollouts on that home, only
that line changed (42 lines before and after). The same resume exited
0, and the upstream saw the summary message.
- Broken by hand. With the thread-lock TryLock check off,
TestPortCodexRolloutsLeavesAnOpenThread went red. With the replacement
off, TestPortCodexRollouts went red. Both green with the fix restored.
- gofmt -l clean. go vet ./... (darwin) clean, GOOS=windows go vet
./internal/... clean, and GOOS=linux go vet -tags nogui ./... clean.
- go test ./... -count=1 -timeout 45m: 64 packages ok, two reds.
- internal/agent ran out of time at 2706s (load average 25 to 57), the
known #2723/#2544. Alone, go test ./internal/agent -count=1 is ok in
901s.
- internal/provider TestHoldReadsMigrationsOnce: "migrations.json read
again while held" at 2.70s. It passes alone 5 of 5. I didn't touch
that package. Filed #3095: heldFor (1s) can run out between the
test's two reads.
Not tried:
- api.openai.com itself after a port. The refusal was probed on the
ChatGPT backend, and the resume ran against a fake.
- A Codex in a WSL distro. Disconnect skips it, because its locks can't
be taken from Windows.
- The Codex app still holding a thread when magpie quits. Its lock is
held, so the file is left for the next pass, and the thread in that
app's memory keeps the magpie1 item until it is loaded again.
157 lines
5.1 KiB
Go
157 lines
5.1 KiB
Go
package gui
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/yetone/magpie/internal/agent"
|
|
"github.com/yetone/magpie/internal/catalog"
|
|
"github.com/yetone/magpie/internal/gateway"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
"github.com/yetone/magpie/internal/update"
|
|
)
|
|
|
|
// served is the gateway this process serves, nil while another magpie
|
|
// has it.
|
|
var served atomic.Pointer[gateway.Server]
|
|
|
|
// backendCtx ends the gateway this process serves (stopServing).
|
|
var backendCtx, endBackend = context.WithCancel(context.Background())
|
|
|
|
// serving is the gateway this process serves, until it has finished.
|
|
var serving sync.WaitGroup
|
|
|
|
// stopServing stops this process's gateway taking requests and returns
|
|
// once those in flight have finished.
|
|
func stopServing() {
|
|
endBackend()
|
|
serving.Wait()
|
|
}
|
|
|
|
// startBackend starts what serves the page and the agents: the gateway,
|
|
// unless another magpie has it (then that one serves and this one only
|
|
// shows its status, and gw is nil — until that one is gone: a magpie left
|
|
// running from before an update, a magpie serve in a terminal), and the
|
|
// model lists kept warm.
|
|
func startBackend() (gw *gateway.Server) {
|
|
gateway.Window = true // the routing this process serves is shown on its page
|
|
gw = serveGateway()
|
|
go watchGateway(backendCtx, gatewayWatch)
|
|
// Codex's background app-server, restarted when it has the list from
|
|
// before a change and no codex session is on it (luci)
|
|
go agent.KeepCodexDaemonCurrent(backendCtx)
|
|
// the compactions magpie made in Codex's threads written as Codex's
|
|
// own, so a thread goes on when Codex talks to OpenAI itself
|
|
go agent.KeepCodexRolloutsPortable(backendCtx)
|
|
// Model lists are fetched, never compiled in: whatever the agents can see
|
|
// comes from the models.dev catalog plus each vendor's own /models answer.
|
|
// Keep both halves warm without making the user click anything.
|
|
go func() {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
if catalog.Stale() {
|
|
if err := catalog.Sync(ctx); err != nil {
|
|
log.Println("catalog:", err)
|
|
}
|
|
}
|
|
cancel()
|
|
// A signed-in agent's list exists only at the vendor; fill it in the
|
|
// first time so the picker never shows a stale snapshot.
|
|
provider.FetchNew(20 * time.Second)
|
|
// lists an older magpie wrote into agents' files, without what
|
|
// it has learnt since (context windows, providers added)
|
|
agent.SyncCatalog()
|
|
// and fetched again each day it stays open, for new models' prices
|
|
catalog.KeepFresh()
|
|
}()
|
|
return gw
|
|
}
|
|
|
|
// gatewayWatch is how often a magpie without the gateway looks for it gone.
|
|
const gatewayWatch = 15 * time.Second
|
|
|
|
// watchGateway takes the gateway up once the magpie that had it is gone,
|
|
// looking every so often until ctx ends: a watch that outlived it would
|
|
// start a gateway after this one has stopped serving.
|
|
func watchGateway(ctx context.Context, every time.Duration) {
|
|
t := time.NewTicker(every)
|
|
defer t.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-t.C:
|
|
}
|
|
gatewayMu.Lock()
|
|
if ctx.Err() == nil && served.Load() == nil && !gateway.Running() {
|
|
serveGatewayLocked()
|
|
}
|
|
gatewayMu.Unlock()
|
|
}
|
|
}
|
|
|
|
// takenSaid: the log has said the gateway's port is taken by one that
|
|
// doesn't answer, said once until it is free again.
|
|
var takenSaid atomic.Bool
|
|
|
|
// gatewayMu keeps one start of the gateway here at a time: the watch's,
|
|
// a restart's, a take-over's (takeover.go).
|
|
var gatewayMu sync.Mutex
|
|
|
|
// servedRun ends the gateway this process serves, and is closed once it
|
|
// has, for a restart; under gatewayMu.
|
|
var servedRun struct {
|
|
stop context.CancelFunc
|
|
done chan struct{}
|
|
}
|
|
|
|
// serveGateway starts the gateway here when no magpie has it: the one
|
|
// started, or nil.
|
|
func serveGateway() *gateway.Server {
|
|
gatewayMu.Lock()
|
|
defer gatewayMu.Unlock()
|
|
return serveGatewayLocked()
|
|
}
|
|
|
|
func serveGatewayLocked() *gateway.Server {
|
|
// handing over, the one there is this one's predecessor, which lets go
|
|
// once this one listens beside it
|
|
if !gateway.Handover {
|
|
if o := gateway.ServedBy(); o.Running {
|
|
if update.Newer(gateway.Version, o.Version) {
|
|
log.Printf("gateway: magpie %s serves %s, older than this one (%s); agents' requests go through it until it quits", o.Version, gateway.URL(), gateway.Version)
|
|
}
|
|
return nil
|
|
}
|
|
// a magpie too busy to answer the question in time (a small
|
|
// server, one starting), or another program, has the port: a
|
|
// second listen only fails (K.Liu on Discord: magpie web beside
|
|
// the service logged "bind: address already in use")
|
|
if gateway.Taken() {
|
|
if !takenSaid.Swap(true) {
|
|
log.Printf("gateway: %s is taken but doesn't answer as magpie yet; this magpie serves the gateway once it is free", gateway.URL())
|
|
}
|
|
return nil
|
|
}
|
|
}
|
|
takenSaid.Store(false)
|
|
gw := gateway.New()
|
|
served.Store(gw)
|
|
serving.Add(1)
|
|
ctx, stop := context.WithCancel(backendCtx)
|
|
done := make(chan struct{})
|
|
servedRun.stop, servedRun.done = stop, done
|
|
go func() {
|
|
defer serving.Done()
|
|
defer close(done)
|
|
defer stop()
|
|
if err := gw.ListenAndServe(ctx); err != nil {
|
|
log.Println("gateway:", err)
|
|
served.CompareAndSwap(gw, nil) // another took the port first
|
|
}
|
|
}()
|
|
return gw
|
|
}
|