From 64262a19f00e83d08b3b30e826fa29d8d23263b6 Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 11 Oct 2026 01:39:16 +0800 Subject: [PATCH] agent: Prime Agent is an Agents-page row, wired like Pi into ~/.prime/agent, and Disconnect puts its files back (#1528, takltc) What changed - internal/agent/primeagent.go: Prime Agent (PrimeIntellect-ai/prime-agent, CLI prime-agent) through the piLike path, as OmO was added. Its folder is ~/.prime/agent or PRIME_AGENT_CODING_AGENT_DIR (~ expands, as upstream's agent_dir does; appdir now lets that variable carry ~). models.json and settings.json were checked against upstream v0.10.0 (pa-core settings and models registry): Pi's camelCase fields, the same thinking levels and enabledModels rules. Connect writes providers.magpie, defaultProvider and defaultModel and keeps the user's providers and settings. Only the global settings.json is written; allowedModels and subagentDefaultModel are left alone. - Prime Agent sends no User-Agent, so its provider block carries the key magpie-prime-agent and the usage log names it (piLikeKeyed). The block is Pi's otherwise, compat.sendSessionAffinityHeaders included (Prime Agent's openai_completions honours it), kept as the user set it (piBlockKept). - Disconnect restores both files byte-for-byte: before magpie's first write a copy is kept (*.before-magpie, or a note that the file was absent), and Disconnect puts it back when nothing else changed since (Agent.Restore). A file changed while connected is left with only magpie's part taken out. - WSL kind, agentenv, the icon, PICKS_ITSELF in the GUI, docs and READMEs. Run - go test -tags nogui ./internal/agent ./internal/appdir ./internal/agentenv ./internal/library ./internal/usage; the new tests went red with the key, the restore, the ~ expansion, PICKS_ITSELF and the icon each taken out. - pi-default-note.test.cjs in chromium and webkit. - Real use: prime-agent 0.10.0 installed into a sandbox HOME, a sandbox gateway on 127.0.0.1:3651 and a fake upstream on 3652. The interactive TUI with no flags started on magpie/fake/echo-1, the fake got the request and usage.jsonl recorded agent "prime-agent". `magpie prime-agent default` put models.json back byte-for-byte; settings.json got its values back, but Prime Agent rewrites the whole file when it runs (every key, nulls), so that file is equal in content, not bytes. Reconnecting over that null-filled file and disconnecting again left it byte-identical. After the rebase onto 7a5536793 (compat in Pi's block) the turn was run again: same result, and both files byte-identical after Disconnect. `prime-agent -p` ignores the saved default upstream (print mode picks a featured model); with --provider magpie --model it goes through magpie. - gofmt -l, GOOS=linux and GOOS=windows go vet, full go test ./... --- README.md | 2 +- README.zh-CN.md | 2 +- docs/reference.md | 1 + docs/subsystems/agent-wiring.md | 2 +- internal/agent/agent.go | 4 + internal/agent/agents.go | 106 +++++++++- internal/agent/applied.go | 5 + internal/agent/primeagent.go | 46 +++++ internal/agent/primeagent_test.go | 205 ++++++++++++++++++++ internal/agent/spelled_test.go | 2 +- internal/agent/sync_test.go | 1 + internal/agent/wsl.go | 11 ++ internal/agentenv/agentenv.go | 1 + internal/appdir/env.go | 2 +- internal/appdir/env_test.go | 4 + internal/gui/assets/app.js | 2 +- internal/gui/assets/icons/prime-agent.svg | 1 + internal/gui/tests/pi-default-note.test.cjs | 14 +- 18 files changed, 402 insertions(+), 9 deletions(-) create mode 100644 internal/agent/primeagent.go create mode 100644 internal/agent/primeagent_test.go create mode 100644 internal/gui/assets/icons/prime-agent.svg diff --git a/README.md b/README.md index ccf2521a5..5fb955679 100644 --- a/README.md +++ b/README.md @@ -70,7 +70,7 @@ magpie tui # the whole thing, in a terminal
-Claude Code · Claude Desktop · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · Pi · oh-my-pi · Aside · OmO · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · JetBrains Air · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · Qwen Code · Muse Code · Empryo · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy Code · Pencil · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy +Claude Code · Claude Desktop · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · Pi · oh-my-pi · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · JetBrains Air · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · Qwen Code · Muse Code · Empryo · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy Code · Pencil · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy
diff --git a/README.zh-CN.md b/README.zh-CN.md index 5905eb6c4..1aa9b032e 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -70,7 +70,7 @@ magpie tui # 全部功能,在终端里
-Claude Code · Claude Desktop · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · Pi · oh-my-pi · Aside · OmO · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · JetBrains Air · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · Qwen Code · Muse Code · Empryo · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy Code · Pencil · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy +Claude Code · Claude Desktop · Codex · Gemini CLI · Antigravity CLI · OpenCode · OpenChamber · MiMo Code · Pi · oh-my-pi · Aside · OmO · Prime Agent · Goose · Cursor CLI · Cursor Private Inference · Zed · VS Code Chat · VS Code Insiders · VSCodium Chat · JetBrains Air · Copilot (JetBrains) · Copilot CLI · Crush · DeepSeek Harness · Reasonix Studio · Command Code · fx · Devin · Hermes Agent · Mister Morph · Kimi Code · Qwen Code · Muse Code · Empryo · MiniMax Code · Droid · Cline · Qoder · Qoder CN · Grok Build · ZCode · WorkBuddy · WorkBuddy AI · CodeBuddy Code · Pencil · T3 Code · OpenHanako · AtomCode · Snow CLI · Alma · Cindy
diff --git a/docs/reference.md b/docs/reference.md index 084be062a..54cd86003 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -94,6 +94,7 @@ line; agents connected to magpie lose it when it quits. | Pi | `~/.pi/agent/settings.json` | model | | Aside | `~/.aside/u/0/settings.json` (+ `models.json`; the first account, the only one magpie wires) | model, effort, fast, standard, deep, visual, image | | OmO (omo-ai) | `~/.omo/agent/settings.json` (+ `models.json`; `$OMO_CODING_AGENT_DIR`, `$SENPI_CODING_AGENT_DIR`) | model | +| Prime Agent | `~/.prime/agent/settings.json` (+ `models.json`; `$PRIME_AGENT_CODING_AGENT_DIR`) | model, thinking (Pi's fields; its key `magpie-prime-agent` names it, since its requests carry no User-Agent; the global settings alone, `allowedModels` and `subagentDefaultModel` left as they are) | | Goose | `~/.config/goose/config.yaml` | model | | Cursor CLI | `~/.cursor/cli-config.json` | model | | Zed | `~/.config/zed/settings.json` (`$XDG_CONFIG_HOME` on Linux, `%APPDATA%\Zed` on Windows) | model (a `magpie` OpenAI-compatible provider; its catalog in Zed's picker) | diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 029e50fc2..ecd5e2e6f 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -18,7 +18,7 @@ something else shows up as drift. | Connect | `ConnectHow` picks the model an agent starts on and reports how. `How` is one of: `kept`, `again`, `joined`, `magpie`, `same`, `alike`, `default` or `first` (#726). With no models to give, it returns `NoModelsError` (code `no_models`). | [`applied.go`](../../internal/agent/applied.go) | | What magpie set | `Apply` sets a field and records it in `applied.json`. `Wired` says whether magpie is in the config. `Drift` reports `unwired`, `replaced`, `unreachable` or `bypassed`. `Reapply` sets the record again. `Keep` accepts the config as it is now. | [`applied.go`](../../internal/agent/applied.go) | | What came before | The stash (`stash.json`) remembers what the config said before magpie pointed it at the gateway, so Disconnect restores it rather than guessing. | [`stash.go`](../../internal/agent/stash.go) | -| Disconnect and preview | `Disconnect` runs `Unwire`, then returns each field still on magpie to its default. `DisconnectPreview` runs the real Disconnect on a copy under a temporary home, in a subprocess (`DryRunArg`), and diffs the files. The preview is never a second account of what Disconnect does. | [`applied.go`](../../internal/agent/applied.go), [`preview.go`](../../internal/agent/preview.go) | +| Disconnect and preview | `Disconnect` runs `Unwire`, then returns each field still on magpie to its default. Last it runs `Restore`: Pi and its kin (`piLike`: Pi, OmO, Prime Agent) copy `settings.json` and `models.json` aside (`*.before-magpie`, `beforeMagpie`) before magpie's first write, and put that copy back byte for byte where what Disconnect left is the same JSON; a file that wasn't there goes again when only empty objects are left in it. `DisconnectPreview` runs the real Disconnect on a copy under a temporary home, in a subprocess (`DryRunArg`), and diffs the files. The preview is never a second account of what Disconnect does. | [`applied.go`](../../internal/agent/applied.go), [`preview.go`](../../internal/agent/preview.go) | | Keeping configs current | `Reseat` moves agents off a model magpie no longer serves (#200). `OnGateway` and `Rewire` write the new gateway address into every connected agent when the port changes. `Source` and `Stale` say what an unconnected agent runs on, and whether running copies still use the old list. | [`reseat.go`](../../internal/agent/reseat.go), [`rewire.go`](../../internal/agent/rewire.go), [`connectinfo.go`](../../internal/agent/connectinfo.go) | | Named omp profiles | omp keeps a profile's settings under `~/.omp/profiles/` (or under `PI_CONFIG_DIR`), each with its own `config.yml` and `models.yml`. Every such profile is an agent of its own — `omp#` on Windows, `omp#@wsl:` in a distro — so each can be connected, drifted and disconnected on its own. They share omp's model lists (`ListsFor`), and the default `omp` row is the folder `ompDir`/`ompIn` already pick, so an `OMP_PROFILE` that row is already pointed at is not listed twice. A name omp refuses is not a row: `default`, a trailing dot, or a Windows reserved device name (`aux`, `nul`, `com1`, `lpt9.x`, `con.work`), on every platform (`ompProfileOK`). A distro's profile names come from its probe and are kept in `wsl.json`; a stopped distro is never started to list them, its profile rows showing what was last seen (`asleep`). | [`omp.go`](../../internal/agent/omp.go), [`wsl.go`](../../internal/agent/wsl.go) | | WSL twins | On Windows each running distro is probed once, without starting a stopped one. The `wslKinds` agents found there become agents of their own, `@wsl:`, edited through `\\wsl.localhost\`. A kind is found by its folder under the distro's home or by its command there (not one on a Windows drive). Where another tool shares one of them, the kind leaves it out: Gemini CLI is found by its command alone, because Antigravity keeps `~/.gemini` too. Goose is found by its folder alone, because a `goose` command can be pressly's migration tool. Reasonix also needs the version its command gives (`accept`), because the old npm client is named `reasonix` too. The gateway address and key follow the distro's networking: mirrored or NAT (`place`, `keyAt`). `ListsFor` keeps a twin's model picks under the Windows twin's id (#927). | [`wsl.go`](../../internal/agent/wsl.go), [`gatewaykey.go`](../../internal/agent/gatewaykey.go) | diff --git a/internal/agent/agent.go b/internal/agent/agent.go index b5a0e74a1..6a05eb6c3 100644 --- a/internal/agent/agent.go +++ b/internal/agent/agent.go @@ -129,6 +129,10 @@ type Agent struct { // kept: the endpoint, provider and model the user had. Disconnect runs // it before the fields' defaults. Unwire func() error + // Restore, for an agent whose files magpie copied aside before its + // first write (beforeMagpie), puts them back as they were where what + // Disconnect left says the same. Disconnect runs it last. + Restore func() error // Join, for an agent that can have magpie's models in its own list // while it stays on the model it was on (Codex signed in with ChatGPT), // connects it so, its model left as its own last pick; false where it diff --git a/internal/agent/agents.go b/internal/agent/agents.go index 711cda431..c00390a82 100644 --- a/internal/agent/agents.go +++ b/internal/agent/agents.go @@ -1,6 +1,7 @@ package agent import ( + "bytes" "encoding/json" "errors" "fmt" @@ -8,6 +9,7 @@ import ( "os" "os/exec" "path/filepath" + "reflect" "runtime" "slices" "sort" @@ -89,6 +91,7 @@ func builtins(home, cfg string) []*Agent { pi(home), aside(home), omo(home), + primeAgent(home), goose(home, cfg), cursor(home), cursorLocal(), @@ -834,10 +837,96 @@ func homeDir(home, d string) string { return filepath.Clean(d) } +// beforeMagpie is a copy of an agent's own files taken before magpie first +// writes them (file.before-magpie beside each), which Disconnect puts back +// byte for byte when what it left says the same as the copy: the same +// JSON, in the user's own order, spacing and comments-free layout. Where +// they differ (the user changed something while connected), what +// Disconnect left stands. A file that wasn't there (named in the stash +// under absent) goes again when nothing but empty objects is left in it. +type beforeMagpie struct { + absent string + files []string +} + +// take copies each file aside, or notes it absent; a file that can't be +// read is neither, and isn't put back. +func (b beforeMagpie) take() { + var gone []string + for _, f := range b.files { + raw, err := os.ReadFile(f) + switch { + case err == nil: + if edit.WriteAtomic(f+".before-magpie", raw) != nil { + os.Remove(f + ".before-magpie") + } + case errors.Is(err, fs.ErrNotExist): + os.Remove(f + ".before-magpie") + gone = append(gone, filepath.Base(f)) + default: + os.Remove(f + ".before-magpie") + } + } + stash(map[string]string{b.absent: strings.Join(gone, "\n")}) +} + +// restore puts back what take kept, where Disconnect left the same. +func (b beforeMagpie) restore() error { + gone := strings.Split(unstash(b.absent), "\n") + for _, f := range b.files { + cur, err := os.ReadFile(f) + if err != nil { + os.Remove(f + ".before-magpie") + continue + } + var now any + if json.Unmarshal(cur, &now) != nil { + continue + } + if was, err := os.ReadFile(f + ".before-magpie"); err == nil { + var then any + if json.Unmarshal(was, &then) == nil && reflect.DeepEqual(now, then) && !bytes.Equal(cur, was) { + if err := edit.WriteAtomic(f, was); err != nil { + return err + } + } + os.Remove(f + ".before-magpie") + continue + } + if slices.Contains(gone, filepath.Base(f)) && emptyJSON(now) { + if err := os.Remove(f); err != nil { + return err + } + } + } + return nil +} + +// emptyJSON says v is an object holding nothing but empty objects. +func emptyJSON(v any) bool { + m, ok := v.(map[string]any) + if !ok { + return false + } + for _, x := range m { + if !emptyJSON(x) { + return false + } + } + return true +} + // piLike is Pi, or a fork of it that keeps Pi's settings.json and // models.json in an agent folder of its own (OmO, omo.go): id is its id, // icon and command, dir its agent folder. func piLike(at place, id, name, dir string) *Agent { + return piLikeKeyed(at, id, name, dir, at.gwKey) +} + +// piLikeKeyed is piLike whose provider "magpie" carries key's key: one +// that names the agent (agentKeyAt) for an agent whose requests carry +// nothing else of it (Prime Agent, primeagent.go). +func piLikeKeyed(at place, id, name, dir string, key func() string) *Agent { path := filepath.Join(dir, "settings.json") modelsPath := filepath.Join(dir, "models.json") auth := filepath.Join(dir, "auth.json") @@ -846,18 +935,26 @@ func piLike(at place, id, name, dir string) *Agent { pair := pairSet(set, "defaultProvider", "defaultModel") // the model a new session starts on, as the model field shows it startup := func() string { return piStartup(path, pairGet(get, "defaultProvider", "defaultModel")()) } - block := piBlockKept(modelsPath, func() any { return magpieProviderJSONAt("pi", id, at.gw()) }) + block := piBlockKept(modelsPath, func() any { + b := magpieProviderJSONAt("pi", id, at.gw()).(map[string]any) + b["apiKey"] = key() + return b + }) writeMagpie := func() error { return edit.SetJSON(modelsPath, edit.KV{Path: "providers." + magpieID, Value: block()}) } + // the user's two files as they were before magpie's first write, put + // back byte for byte by Disconnect where it leaves them saying the same + before := beforeMagpie{at.key(id + ".before.absent"), []string{path, modelsPath}} return &Agent{ ID: id, Name: name, Icon: id, Bin: id, Dir: dir, Path: path, Spelled: prefixed, + Restore: before.restore, Check: func() string { if p, _ := get("defaultProvider"); p != magpieID { return "" } return wiringOff(name, modelsPath, func(k string) (string, bool) { return edit.GetJSON(modelsPath, "providers."+magpieID+"."+k) }, - "baseUrl", at.v1(), "apiKey", at.gwKey()) + "baseUrl", at.v1(), "apiKey", key()) }, Sync: func() error { return syncJSON(modelsPath, "providers."+magpieID, block) @@ -878,6 +975,11 @@ func piLike(at place, id, name, dir string) *Agent { return piScopeWithout(path) } if ref, ok := strings.CutPrefix(v, magpieID+"/"); ok && isMagpie(ref) { + if _, has := edit.GetJSON(modelsPath, "providers."+magpieID); !has { + if p, _ := get("defaultProvider"); p != magpieID { + before.take() + } + } if err := writeMagpie(); err != nil { return err } diff --git a/internal/agent/applied.go b/internal/agent/applied.go index defcc373b..9506328b3 100644 --- a/internal/agent/applied.go +++ b/internal/agent/applied.go @@ -695,6 +695,11 @@ func (a *Agent) Disconnect() error { } } } + if a.Restore != nil { + if err := a.Restore(); err != nil { + return err + } + } // what it was on through magpie, for switching it on again back := reconnection{Magpie: map[string]string{}, Left: a.Values()} for _, f := range a.Fields { diff --git a/internal/agent/primeagent.go b/internal/agent/primeagent.go new file mode 100644 index 000000000..c0a2ceb74 --- /dev/null +++ b/internal/agent/primeagent.go @@ -0,0 +1,46 @@ +package agent + +// Prime Agent (PrimeIntellect-ai/prime-agent, the prime-agent command) is +// a Rust agent that keeps Pi's settings.json and models.json in an agent +// folder of its own: $PRIME_AGENT_CODING_AGENT_DIR, "~" in it standing for +// home, else ~/.prime/agent (pa-types platform/dirs.rs, agent_dir). It +// reads both files with Pi's fields and types (pa-core models/custom.rs, +// settings/types.rs), so magpie wires it as it does Pi: +// defaultProvider/defaultModel/defaultThinkingLevel in settings.json and +// magpie as the provider "magpie" in models.json. +// +// Its requests carry no User-Agent (its HTTP client sets none), so the key +// magpie gives it names it (magpie-prime-agent): that is how the gateway +// counts its requests as Prime Agent's. +// +// Its global settings.json alone is written, as Pi's is: a project's +// .prime/agent/settings.json is the user's, and so are allowedModels (its +// daemon's allow-list, which a model outside fails loudly) and +// subagentDefaultModel. + +import ( + "path/filepath" + + "github.com/yetone/magpie/internal/appdir" +) + +func primeAgent(home string) *Agent { return primeAgentIn(here(home)) } + +// primeAgentIn is Prime Agent at a place: this machine's home, where its +// variable moves it, or a WSL distro's, whose variables magpie can't read. +func primeAgentIn(at place) *Agent { + return piLikeKeyed(at, "prime-agent", "Prime Agent", primeAgentDir(at), + func() string { return agentKeyAt("prime-agent", at.gw()) }) +} + +// primeAgentDir is Prime Agent's agent folder at a place. A relative +// PRIME_AGENT_CODING_AGENT_DIR is its working directory's, which magpie +// can't know, so it is not taken. +func primeAgentDir(at place) string { + if at.spell == nil { + if d := homeDir(at.home, appdir.Getenv("PRIME_AGENT_CODING_AGENT_DIR")); d != "" { + return d + } + } + return filepath.Join(at.home, ".prime", "agent") +} diff --git a/internal/agent/primeagent_test.go b/internal/agent/primeagent_test.go new file mode 100644 index 000000000..b599e6fff --- /dev/null +++ b/internal/agent/primeagent_test.go @@ -0,0 +1,205 @@ +package agent + +import ( + "bytes" + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/gateway" + "github.com/yetone/magpie/internal/usage" +) + +// Prime Agent (#1528) is an agent of its own, wired as Pi is but in +// ~/.prime/agent: a model through magpie sets settings.json's +// defaultProvider/defaultModel and magpie's provider in models.json there, +// beside the user's own providers and settings. The provider's key names +// Prime Agent, whose requests carry no User-Agent; Disconnect puts both +// files back as they were, byte for byte. +func TestPrimeAgent(t *testing.T) { + home := syncHome(t) + var a *Agent + for _, x := range All() { + if x.ID == "prime-agent" { + a = x + } + } + if a == nil { + t.Fatal("no prime-agent in All()") + } + dir := filepath.Join(home, ".prime", "agent") + settings, models := filepath.Join(dir, "settings.json"), filepath.Join(dir, "models.json") + if a.Name != "Prime Agent" || a.Icon != "prime-agent" || a.Bin != "prime-agent" || a.Dir != dir || a.Path != settings || a.Detected() { + t.Fatalf("%+v", a) + } + os.MkdirAll(dir, 0o755) + // the user's own, as they wrote them: comments aside, Prime Agent + // takes Pi's JSON + userSettings := "{\n \"theme\": \"dark\",\n \"defaultProvider\": \"xai\",\n \"defaultModel\": \"grok-4.6\",\n \"allowedModels\": [\"xai/grok-4.6\", \"magpie/relay/glm-4.6\"],\n \"subagentDefaultModel\": \"xai/grok-4.6\"\n}\n" + userModels := "{\n \"providers\": {\n \"mine\": {\n \"baseUrl\": \"http://127.0.0.1:9/v1\",\n \"api\": \"openai-completions\",\n \"apiKey\": \"MINE_KEY\",\n \"models\": [{\"id\": \"m1\", \"contextWindow\": 64000}]\n }\n }\n}\n" + writeFile(t, settings, userSettings) + writeFile(t, models, userModels) + if !a.Detected() || a.Field("model").Get() != "xai/grok-4.6" { + t.Fatalf("detected %v, model %q", a.Detected(), a.Field("model").Get()) + } + + if err := a.Connect(); err != nil { + t.Fatal(err) + } + for k, want := range map[string]string{"defaultProvider": "magpie", "defaultModel": "relay/glm-4.6", + "theme": "dark", "subagentDefaultModel": "xai/grok-4.6", "allowedModels.0": "xai/grok-4.6"} { + if v, _ := edit.GetJSON(settings, k); v != want { + t.Fatalf("%s = %q:\n%s", k, v, readFile(settings)) + } + } + var file struct { + Providers map[string]map[string]any `json:"providers"` + } + if err := json.Unmarshal([]byte(readFile(models)), &file); err != nil { + t.Fatal(err) + } + if mine := file.Providers["mine"]; mine == nil || mine["apiKey"] != "MINE_KEY" { + t.Fatalf("their provider:\n%s", readFile(models)) + } + got := file.Providers["magpie"] + if got["baseUrl"] != gateway.URL()+"/v1" || got["api"] != "openai-completions" || got["apiKey"] != "magpie-prime-agent" { + t.Fatalf("models:\n%s", readFile(models)) + } + // Pi's block, but for the key: the fields Prime Agent's models.json + // takes, of the types it takes (pa-core models/custom.rs) + want := magpieProviderJSON("pi").(map[string]any) + want["apiKey"] = gateway.TokenFor("prime-agent") + wb, _ := json.Marshal(want) + if b, _ := json.Marshal(got); string(b) != string(wb) { + t.Fatalf("not Pi's block:\n got %s\nwant %s", b, wb) + } + if c := a.Check(); c != "" { + t.Fatal(c) + } + // a key magpie no longer gives it is off + edit.SetJSON(models, edit.KV{Path: "providers.magpie.apiKey", Value: gateway.Token}) + if a.Check() == "" { + t.Fatal("the shared key reads as Prime Agent's") + } + if err := a.Sync(); err != nil { + t.Fatal(err) + } + if k, _ := edit.GetJSON(models, "providers.magpie.apiKey"); k != "magpie-prime-agent" || a.Check() != "" { + t.Fatalf("sync left %q: %s", k, a.Check()) + } + for _, other := range []string{".pi", ".omo"} { + if _, err := os.Stat(filepath.Join(home, other)); !os.IsNotExist(err) { + t.Fatalf("~/%s was touched: %v", other, err) + } + } + + // its requests, which say nothing of it but the key, are its: the + // gateway reads the agent off magpie- (gateway.agentOf) + if got := usage.AgentOf("prime-agent"); got != "prime-agent" { + t.Fatalf("usage: %q", got) + } + + if err := a.Disconnect(); err != nil { + t.Fatal(err) + } + if a.Wired() { + t.Fatal("still connected") + } + if b := readFile(settings); b != userSettings { + t.Fatalf("settings.json not as it was:\n%s", b) + } + if b := readFile(models); b != userModels { + t.Fatalf("models.json not as it was:\n%s", b) + } +} + +// Connect and Disconnect from the Agents page, with nothing of the user's +// in models.json, leave it as it was too. +func TestPrimeAgentRoundTrip(t *testing.T) { + home := syncHome(t) + a := primeAgent(home) + dir := filepath.Join(home, ".prime", "agent") + userSettings := []byte("{\n \"defaultProvider\": \"prime-inference\",\n \"defaultModel\": \"glm-5.3\",\n \"enabledModels\": [\"prime-inference/*\"]\n}\n") + writeFile(t, filepath.Join(dir, "settings.json"), string(userSettings)) + for i := 0; i < 2; i++ { + if err := a.Connect(); err != nil { + t.Fatal(err) + } + if !a.Wired() || a.Check() != "" { + t.Fatalf("not connected:\n%s", readFile(a.Path)) + } + // a model outside enabledModels would never start + if v, _ := edit.GetJSON(a.Path, "enabledModels"); !bytes.Contains([]byte(v), []byte("magpie/")) { + t.Fatalf("enabledModels: %s", v) + } + if err := a.Disconnect(); err != nil { + t.Fatal(err) + } + if b, _ := os.ReadFile(a.Path); !bytes.Equal(b, userSettings) { + t.Fatalf("round %d:\n%s", i, b) + } + // models.json wasn't there, and isn't again; nor is a copy left + for _, f := range []string{"models.json", "models.json.before-magpie", "settings.json.before-magpie"} { + if _, err := os.Stat(filepath.Join(dir, f)); !os.IsNotExist(err) { + t.Fatalf("round %d: %s left: %v", i, f, err) + } + } + } +} + +// What the user changes while it is connected stands: Disconnect takes +// magpie out of it and leaves their change, rather than putting back the +// copy from before. +func TestPrimeAgentKeepsWhatChangedWhileConnected(t *testing.T) { + home := syncHome(t) + a := primeAgent(home) + settings := filepath.Join(home, ".prime", "agent", "settings.json") + writeFile(t, settings, `{"defaultProvider": "prime-inference", "defaultModel": "glm-5.3"}`) + if err := a.Connect(); err != nil { + t.Fatal(err) + } + if err := edit.SetJSON(settings, edit.KV{Path: "theme", Value: "light"}); err != nil { + t.Fatal(err) + } + if err := a.Disconnect(); err != nil { + t.Fatal(err) + } + for k, want := range map[string]string{"theme": "light", "defaultProvider": "prime-inference", "defaultModel": "glm-5.3"} { + if v, _ := edit.GetJSON(settings, k); v != want { + t.Fatalf("%s = %q:\n%s", k, v, readFile(settings)) + } + } + if _, err := os.Stat(settings + ".before-magpie"); !os.IsNotExist(err) { + t.Fatalf("copy left: %v", err) + } +} + +// PRIME_AGENT_CODING_AGENT_DIR moves its folder, "~" in it standing for +// home, as its own agent_dir does; a relative one is not taken, and a +// distro's Prime Agent is at its home whatever this machine's says. +func TestPrimeAgentDir(t *testing.T) { + home := syncHome(t) + own := filepath.Join(home, "own") + def := filepath.Join(home, ".prime", "agent") + for _, c := range []struct{ env, want string }{ + {"", def}, + {own, own}, + {"~", home}, + {"~/pa", filepath.Join(home, "pa")}, + {"rel/dir", def}, + } { + t.Setenv("PRIME_AGENT_CODING_AGENT_DIR", c.env) + if a := primeAgent(home); a.Dir != c.want || a.Path != filepath.Join(c.want, "settings.json") { + t.Errorf("%+v: %s", c, a.Dir) + } + } + t.Setenv("PRIME_AGENT_CODING_AGENT_DIR", own) + root := t.TempDir() + d := distro{Name: "Ubuntu", Root: root, Home: "/home/me", Has: map[string]bool{"dir:.prime/agent": true}, Mirrored: true, Running: true} + a := wslAgent(wslKindOf("prime-agent"), d) + if a.ID != "prime-agent@wsl:Ubuntu" || a.Name != "Prime Agent · WSL Ubuntu" || a.Dir != filepath.Join(root, "home", "me", ".prime", "agent") { + t.Fatalf("%+v", a) + } +} diff --git a/internal/agent/spelled_test.go b/internal/agent/spelled_test.go index 4cda79749..42f3fcb64 100644 --- a/internal/agent/spelled_test.go +++ b/internal/agent/spelled_test.go @@ -12,7 +12,7 @@ import ( // leaving the row connected on the model it went back to (#835, OpenHanako's // own deepseek/deepseek-v4-pro). func TestOwnProviderNamedAsMagpies(t *testing.T) { - ids := []string{"agy", "opencode", "openchamber", "mimocode", "pi", "aside", "omo", "goose", "zed", "vscode", + ids := []string{"agy", "opencode", "openchamber", "mimocode", "pi", "aside", "omo", "prime-agent", "goose", "zed", "vscode", "crush", "dsh", "commandcode", "fx", "omp", "hermes", "morph", "kimi", "empryo", "minimax-code", "droid", "qoder", "qoder-cn", "grok", "atomcode", "cline", "snow"} for _, id := range ids { diff --git a/internal/agent/sync_test.go b/internal/agent/sync_test.go index 8f789c72b..c51b27fb7 100644 --- a/internal/agent/sync_test.go +++ b/internal/agent/sync_test.go @@ -36,6 +36,7 @@ func syncHome(t *testing.T) string { t.Setenv("DSH_HOME", "") t.Setenv("OMO_CODING_AGENT_DIR", "") t.Setenv("SENPI_CODING_AGENT_DIR", "") + t.Setenv("PRIME_AGENT_CODING_AGENT_DIR", "") t.Setenv("PI_CODING_AGENT_DIR", "") t.Setenv("PI_CONFIG_DIR", "") t.Setenv("OMP_PROFILE", "") diff --git a/internal/agent/wsl.go b/internal/agent/wsl.go index 7e6f1b67b..dce518b00 100644 --- a/internal/agent/wsl.go +++ b/internal/agent/wsl.go @@ -290,6 +290,17 @@ var wslKinds = []wslKind{ } return nil }}, + // Prime Agent, Pi's files in a folder of its own, at its default + // folder: the distro's variable that moves it isn't read + {id: "prime-agent", name: "Prime Agent", dir: ".prime/agent", bin: "prime-agent", in: primeAgentIn, + asleep: func(key string) func(map[string]string) []Option { + if key == "model" { + return func(cur map[string]string) []Option { + return append(ownOptions("", cur["model"]), viaMagpie("prime-agent", magpieID+"/")...) + } + } + return nil + }}, // only its settings.json: its sign-in, sessions and prompt history, // read on this machine for Claude Code here, aren't read in a distro {id: "claude", name: "Claude Code", dir: ".claude", bin: "claude", in: claudeIn, diff --git a/internal/agentenv/agentenv.go b/internal/agentenv/agentenv.go index 9d9969274..615fed85f 100644 --- a/internal/agentenv/agentenv.go +++ b/internal/agentenv/agentenv.go @@ -43,6 +43,7 @@ var Vars = []string{ // Pi and its forks (OmO, Senpi), whose profile and config are apart "PI_CODING_AGENT_DIR", "PI_CODING_AGENT_SESSION_DIR", "PI_CONFIG_DIR", "PI_PROFILE", "OMO_CODING_AGENT_DIR", "SENPI_CODING_AGENT_DIR", + "PRIME_AGENT_CODING_AGENT_DIR", // omp "OMP_PROFILE", // Qoder's two builds, the global site's and China's diff --git a/internal/appdir/env.go b/internal/appdir/env.go index bbb393402..94438ab85 100644 --- a/internal/appdir/env.go +++ b/internal/appdir/env.go @@ -86,7 +86,7 @@ func usable(name, v string) bool { return true } switch name { - case "PI_CODING_AGENT_DIR", "PI_CODING_AGENT_SESSION_DIR", "HANA_HOME", "T3CODE_HOME": + case "PI_CODING_AGENT_DIR", "PI_CODING_AGENT_SESSION_DIR", "PRIME_AGENT_CODING_AGENT_DIR", "HANA_HOME", "T3CODE_HOME": return v == "~" || strings.HasPrefix(v, "~/") || (runtime.GOOS == "windows" && strings.HasPrefix(v, `~\`)) } return false diff --git a/internal/appdir/env_test.go b/internal/appdir/env_test.go index aa9475e03..6c7d3e0ca 100644 --- a/internal/appdir/env_test.go +++ b/internal/appdir/env_test.go @@ -117,6 +117,10 @@ func TestTildeFolderVariables(t *testing.T) { {"HANA_HOME", "~other/hanako", false}, {"PI_CODING_AGENT_DIR", "~other/pi", false}, {"PI_CODING_AGENT_DIR", `~\pi`, runtime.GOOS == "windows"}, + {"PRIME_AGENT_CODING_AGENT_DIR", "~", true}, + {"PRIME_AGENT_CODING_AGENT_DIR", "~/pa", true}, + {"PRIME_AGENT_CODING_AGENT_DIR", "~other/pa", false}, + {"PRIME_AGENT_CODING_AGENT_DIR", `~\pa`, runtime.GOOS == "windows"}, } { t.Run(tc.name+"="+tc.value, func(t *testing.T) { t.Setenv(tc.name, tc.value) diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 4f9e77a2a..6f3848473 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -2961,7 +2961,7 @@ const grouped = (a, f) => menuRoles(a).includes(f.label) || roleLevel(f.label); const ROLE_MODELS = [...FOLLOWS_MODEL, ...OMP_OWN_PICK]; // agents with no default model of their own, whose Default leaves the pick // to them (#709) -const PICKS_ITSELF = ["pi", "omo"]; +const PICKS_ITSELF = ["pi", "omo", "prime-agent"]; // A field that follows the model unless set — Codex's subagents, Claude // Code's tiers, omp's roles — is a small square after the pickers rather diff --git a/internal/gui/assets/icons/prime-agent.svg b/internal/gui/assets/icons/prime-agent.svg new file mode 100644 index 000000000..85ba8df8c --- /dev/null +++ b/internal/gui/assets/icons/prime-agent.svg @@ -0,0 +1 @@ +Prime Agent diff --git a/internal/gui/tests/pi-default-note.test.cjs b/internal/gui/tests/pi-default-note.test.cjs index 4369d888d..a74586027 100644 --- a/internal/gui/tests/pi-default-note.test.cjs +++ b/internal/gui/tests/pi-default-note.test.cjs @@ -2,7 +2,7 @@ // #709: Pi has no default model of its own — Default in its model picker // clears the default it has, and Pi then takes the first provider signed in // (openai's gpt-5.5 before openai-codex's), so "what Pi ships with" read as -// a model Pi would keep. Pi's and OmO's Default says it clears the default +// a model Pi would keep. Pi's, OmO's and Prime Agent's (#1528) Default says it clears the default // and Pi picks one itself; other agents' says what it said. Pi's // openai-codex models are rows of their own beside openai's of the same // name. Both connected to magpie, so the pickers in their rows list every @@ -23,6 +23,9 @@ const piOptions = [ const state = { agents: [ { id: "pi", name: "Pi", icon: "generic", path: "/fixture/pi", wired: true, fields: [{ key: "model", label: "model", value: "openai/gpt-6-astra", options: piOptions }] }, + // #1528: Prime Agent, Pi's files in ~/.prime/agent, with no default of + // its own either (it starts on its featured model) + { id: "prime-agent", name: "Prime Agent", icon: "prime-agent", path: "/fixture/prime", wired: true, fields: [{ key: "model", label: "model", value: "magpie/relay/m1", options: piOptions.filter((o) => o.ref) }] }, { id: "claude", name: "Claude Code", icon: "generic", path: "/fixture/claude", wired: true, fields: [{ key: "model", label: "model", value: "opus", options: [{ value: "opus" }, { value: "sonnet" }, { value: "relay/m1", label: "m1", ref: "relay/m1", note: "Relay · via magpie" }] }] }, ], profiles: [], @@ -84,6 +87,15 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.ok(values.includes("openai/gpt-6-astra") && values.includes("openai-codex/gpt-6-astra"), "same-named models stay a row each: " + values); await close(); + await open("prime-agent"); + assert.equal(await page.locator("#list li", { hasText: w.pi.replace("Pi", "Prime Agent") }).count(), 1, "Prime Agent's Default says it clears the default"); + await close(); + // its icon is its own, loaded, not the generic one a missing file falls to + const ic = page.locator(`${row("prime-agent")} .ic[data-icon="prime-agent"]`).first(); + await ic.locator(".mask").waitFor(); + assert.equal(await ic.evaluate((e) => e.classList.contains("generic")), false); + assert.ok(await page.evaluate(() => new Promise((ok) => { const i = new Image(); i.onload = () => ok(i.naturalWidth > 0); i.onerror = () => ok(false); i.src = "icons/prime-agent.svg"; })), "icons/prime-agent.svg loads"); + await open("claude"); assert.equal(await page.locator("#list li", { hasText: w.claude }).count(), 1, "other agents' Default is as it was"); assert.equal(await page.locator("#list li", { hasText: w.pi.replace("Pi", "Claude Code") }).count(), 0);